http: minor cleanup of http_field handling
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob462281c23bf9dde51017e045d6bbbeaeaa0aeb3b
1 /**
2  * Copyright (c) 2009 Eric Wong (all bugs are Eric's fault)
3  * Copyright (c) 2005 Zed A. Shaw
4  * You can redistribute it and/or modify it under the same terms as Ruby.
5  */
6 #include "ruby.h"
7 #include "ext_help.h"
8 #include <assert.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include "common_field_optimization.h"
12 #include "global_variables.h"
13 #include "c_util.h"
15 struct http_parser {
16   int cs;
17   union {
18     size_t body;
19     size_t field;
20     size_t query;
21     size_t offset;
22   } start;
23   size_t mark;
24   size_t field_len;
27 static void http_field(VALUE req, const char *field, size_t flen, VALUE val);
28 static void header_done(VALUE req, const char *at, size_t length);
30 static int http_parser_has_error(struct http_parser *hp);
31 static int http_parser_is_finished(struct http_parser *hp);
34 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
35 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
36 #define PTR_TO(F) (buffer + hp->F)
37 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
39 /** Machine **/
41 %%{
42   machine http_parser;
44   action mark {MARK(mark, fpc); }
46   action start_field { MARK(start.field, fpc); }
47   action snake_upcase_field { snake_upcase_char((char *)fpc); }
48   action downcase_char { downcase_char((char *)fpc); }
49   action write_field { hp->field_len = LEN(start.field, fpc); }
50   action start_value { MARK(mark, fpc); }
51   action write_value {
52     VALIDATE_MAX_LENGTH(LEN(mark, fpc), FIELD_VALUE);
53     http_field(req, PTR_TO(start.field), hp->field_len, STR_NEW(mark, fpc));
54   }
55   action request_method {
56     rb_hash_aset(req, g_request_method, STR_NEW(mark, fpc));
57   }
58   action scheme {
59     rb_hash_aset(req, g_rack_url_scheme, STR_NEW(mark, fpc));
60   }
61   action host {
62     rb_hash_aset(req, g_http_host, STR_NEW(mark, fpc));
63   }
64   action request_uri {
65     size_t len = LEN(mark, fpc);
66     VALIDATE_MAX_LENGTH(len, REQUEST_URI);
67     rb_hash_aset(req, g_request_uri, STR_NEW(mark, fpc));
68     /*
69      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
70      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
71      */
72     if (len == 1 && *PTR_TO(mark) == '*') {
73       VALUE val = rb_str_new(NULL, 0);
74       rb_hash_aset(req, g_request_path, val);
75       rb_hash_aset(req, g_path_info, val);
76     }
77   }
78   action fragment {
79     VALIDATE_MAX_LENGTH(LEN(mark, fpc), FRAGMENT);
80     rb_hash_aset(req, g_fragment, STR_NEW(mark, fpc));
81   }
82   action start_query {MARK(start.query, fpc); }
83   action query_string {
84     VALIDATE_MAX_LENGTH(LEN(start.query, fpc), QUERY_STRING);
85     rb_hash_aset(req, g_query_string, STR_NEW(start.query, fpc));
86   }
87   action http_version {
88     rb_hash_aset(req, g_http_version, STR_NEW(mark, fpc));
89   }
90   action request_path {
91     VALUE val;
92     size_t len = LEN(mark, fpc);
94     VALIDATE_MAX_LENGTH(len, REQUEST_PATH);
95     val = STR_NEW(mark, fpc);
97     rb_hash_aset(req, g_request_path, val);
98     /* rack says PATH_INFO must start with "/" or be empty */
99     if (!(len == 1 && *PTR_TO(mark) == '*'))
100       rb_hash_aset(req, g_path_info, val);
101   }
102   action done {
103     hp->start.body = fpc - buffer + 1;
104     header_done(req, fpc + 1, pe - fpc - 1);
105     fbreak;
106   }
108   include unicorn_http_common "unicorn_http_common.rl";
111 /** Data **/
112 %% write data;
114 static void http_parser_init(struct http_parser *hp)
116   int cs = 0;
117   memset(hp, 0, sizeof(struct http_parser));
118   %% write init;
119   hp->cs = cs;
122 /** exec **/
123 static void http_parser_execute(struct http_parser *hp,
124   VALUE req, const char *buffer, size_t len)
126   const char *p, *pe;
127   int cs = hp->cs;
128   size_t off = hp->start.offset;
130   assert(off <= len && "offset past end of buffer");
132   p = buffer+off;
133   pe = buffer+len;
135   assert(pe - p == len - off && "pointers aren't same distance");
137   %% write exec;
139   if (!http_parser_has_error(hp))
140     hp->cs = cs;
141   hp->start.offset = p - buffer;
143   assert(p <= pe && "buffer overflow after parsing execute");
144   assert(hp->start.offset <= len && "start.offset longer than length");
145   assert(hp->mark < len && "mark is after buffer end");
146   assert(hp->field_len <= len && "field has length longer than whole buffer");
149 static int http_parser_has_error(struct http_parser *hp)
151   return hp->cs == http_parser_error;
154 static int http_parser_is_finished(struct http_parser *hp)
156   return hp->cs == http_parser_first_final;
159 static struct http_parser *data_get(VALUE self)
161   struct http_parser *hp;
163   Data_Get_Struct(self, struct http_parser, hp);
164   assert(hp);
165   return hp;
167 static void http_field(VALUE req, const char *field, size_t flen, VALUE val)
169   VALUE f = find_common_field(field, flen);
171   if (f == Qnil) {
172     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
173     f = uncommon_field(field, flen);
174   } else if (f == g_http_host && rb_hash_aref(req, f) != Qnil) {
175     return;
176   }
178   rb_hash_aset(req, f, val);
181 static int is_https(VALUE str)
183   return RSTRING_LEN(str) == 5 && !memcmp("https", RSTRING_PTR(str), 5);
186 /** Finalizes the request header to have a bunch of stuff that's needed. */
187 static void header_done(VALUE req, const char *at, size_t length)
189   VALUE server_name = g_localhost;
190   VALUE server_port = g_port_80;
191   VALUE temp;
193   /* rack requires QUERY_STRING */
194   if (rb_hash_aref(req, g_query_string) == Qnil)
195     rb_hash_aset(req, g_query_string, rb_str_new(NULL, 0));
197   /* set rack.url_scheme to "https" or "http", no others are allowed by Rack */
198   if ((temp = rb_hash_aref(req, g_rack_url_scheme)) == Qnil) {
199     if ((temp = rb_hash_aref(req, g_http_x_forwarded_proto)) != Qnil &&
200         is_https(temp))
201       server_port = g_port_443;
202     else
203       temp = g_http;
204     rb_hash_aset(req, g_rack_url_scheme, temp);
205   } else if (is_https(temp)) {
206     server_port = g_port_443;
207   }
209   /* parse and set the SERVER_NAME and SERVER_PORT variables */
210   if ((temp = rb_hash_aref(req, g_http_host)) != Qnil) {
211     char *colon = memchr(RSTRING_PTR(temp), ':', RSTRING_LEN(temp));
212     if (colon) {
213       long port_start = colon - RSTRING_PTR(temp) + 1;
215       server_name = rb_str_substr(temp, 0, colon - RSTRING_PTR(temp));
216       if ((RSTRING_LEN(temp) - port_start) > 0)
217         server_port = rb_str_substr(temp, port_start, RSTRING_LEN(temp));
218     } else {
219       server_name = temp;
220     }
221   }
222   rb_hash_aset(req, g_server_name, server_name);
223   rb_hash_aset(req, g_server_port, server_port);
224   rb_hash_aset(req, g_server_protocol, g_server_protocol_value);
226   /* grab the initial body and stuff it into the hash */
227   temp = rb_hash_aref(req, g_request_method);
228   if (temp != Qnil) {
229     long len = RSTRING_LEN(temp);
230     char *ptr = RSTRING_PTR(temp);
232     if (memcmp(ptr, "HEAD", len) && memcmp(ptr, "GET", len))
233       rb_hash_aset(req, sym_http_body, rb_str_new(at, length));
234   }
237 static VALUE HttpParser_alloc(VALUE klass)
239   struct http_parser *hp;
240   return Data_Make_Struct(klass, struct http_parser, NULL, NULL, hp);
245  * call-seq:
246  *    parser.new -> parser
248  * Creates a new parser.
249  */
250 static VALUE HttpParser_init(VALUE self)
252   http_parser_init(data_get(self));
254   return self;
259  * call-seq:
260  *    parser.reset -> nil
262  * Resets the parser to it's initial state so that you can reuse it
263  * rather than making new ones.
264  */
265 static VALUE HttpParser_reset(VALUE self)
267   http_parser_init(data_get(self));
269   return Qnil;
274  * call-seq:
275  *    parser.execute(req, data) -> true/false
277  * Takes a Hash and a String of data, parses the String of data filling
278  * in the Hash returning a boolean to indicate whether or not parsing
279  * is finished.
281  * This function now throws an exception when there is a parsing error.
282  * This makes the logic for working with the parser much easier.  You
283  * will need to wrap the parser with an exception handling block.
284  */
286 static VALUE HttpParser_execute(VALUE self, VALUE req, VALUE data)
288   struct http_parser *hp = data_get(self);
289   char *dptr = RSTRING_PTR(data);
290   long dlen = RSTRING_LEN(data);
292   if (hp->start.offset < dlen) {
293     http_parser_execute(hp, req, dptr, dlen);
295     VALIDATE_MAX_LENGTH(hp->start.offset, HEADER);
297     if (!http_parser_has_error(hp))
298       return http_parser_is_finished(hp) ? Qtrue : Qfalse;
300     rb_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
301   }
302   rb_raise(eHttpParserError, "Requested start is after data buffer end.");
305 void Init_unicorn_http(void)
307   mUnicorn = rb_define_module("Unicorn");
309   DEF_GLOBAL(rack_url_scheme, "rack.url_scheme");
310   DEF_GLOBAL(request_method, "REQUEST_METHOD");
311   DEF_GLOBAL(request_uri, "REQUEST_URI");
312   DEF_GLOBAL(fragment, "FRAGMENT");
313   DEF_GLOBAL(query_string, "QUERY_STRING");
314   DEF_GLOBAL(http_version, "HTTP_VERSION");
315   DEF_GLOBAL(request_path, "REQUEST_PATH");
316   DEF_GLOBAL(path_info, "PATH_INFO");
317   DEF_GLOBAL(server_name, "SERVER_NAME");
318   DEF_GLOBAL(server_port, "SERVER_PORT");
319   DEF_GLOBAL(server_protocol, "SERVER_PROTOCOL");
320   DEF_GLOBAL(server_protocol_value, "HTTP/1.1");
321   DEF_GLOBAL(http_x_forwarded_proto, "HTTP_X_FORWARDED_PROTO");
322   DEF_GLOBAL(port_80, "80");
323   DEF_GLOBAL(port_443, "443");
324   DEF_GLOBAL(localhost, "localhost");
325   DEF_GLOBAL(http, "http");
327   eHttpParserError = rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
329   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
330   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
331   rb_define_method(cHttpParser, "initialize", HttpParser_init,0);
332   rb_define_method(cHttpParser, "reset", HttpParser_reset,0);
333   rb_define_method(cHttpParser, "execute", HttpParser_execute,2);
334   sym_http_body = ID2SYM(rb_intern("http_body"));
335   init_common_fields();
336   g_http_host = find_common_field("HOST", 4);
337   assert(g_http_host != Qnil);