tee_input: switch to simpler API for parsing trailers
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob6cc2958cd7050ca568fcc366bc037e21efe7a692
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 #define UH_FL_CHUNKED  0x1
16 #define UH_FL_HASBODY  0x2
17 #define UH_FL_INBODY   0x4
18 #define UH_FL_HASTRAILER 0x8
19 #define UH_FL_INTRAILER 0x10
20 #define UH_FL_INCHUNK  0x20
21 #define UH_FL_REQEOF 0x40
22 #define UH_FL_KAVERSION 0x80
23 #define UH_FL_HASHEADER 0x100
25 /* all of these flags need to be set for keepalive to be supported */
26 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
28 /* keep this small for Rainbows! since every client has one */
29 struct http_parser {
30   int cs; /* Ragel internal state */
31   unsigned int flags;
32   size_t mark;
33   size_t offset;
34   union { /* these 2 fields don't nest */
35     size_t field;
36     size_t query;
37   } start;
38   union {
39     size_t field_len; /* only used during header processing */
40     size_t dest_offset; /* only used during body processing */
41   } s;
42   VALUE buf;
43   VALUE env;
44   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
45   union {
46     off_t content;
47     off_t chunk;
48   } len;
51 static ID id_clear;
53 static void finalize_header(struct http_parser *hp);
55 static void parser_error(const char *msg)
57   VALUE exc = rb_exc_new2(eHttpParserError, msg);
58   VALUE bt = rb_ary_new();
60   rb_funcall(exc, rb_intern("set_backtrace"), 1, bt);
61   rb_exc_raise(exc);
64 #define REMAINING (unsigned long)(pe - p)
65 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
66 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
67 #define PTR_TO(F) (buffer + hp->F)
68 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
70 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
71 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
72 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
73 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
76  * handles values of the "Connection:" header, keepalive is implied
77  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
78  * Additionally, we require GET/HEAD requests to support keepalive.
79  */
80 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
82   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
83     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
84     HP_FL_SET(hp, KAVERSION);
85   } else if (STR_CSTR_CASE_EQ(val, "close")) {
86     /*
87      * it doesn't matter what HTTP version or request method we have,
88      * if a client says "Connection: close", we disable keepalive
89      */
90     HP_FL_UNSET(hp, KAVERSION);
91   } else {
92     /*
93      * client could've sent anything, ignore it for now.  Maybe
94      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
95      * Raising an exception might be too mean...
96      */
97   }
100 static void
101 request_method(struct http_parser *hp, const char *ptr, size_t len)
103   VALUE v = rb_str_new(ptr, len);
105   rb_hash_aset(hp->env, g_request_method, v);
108 static void
109 http_version(struct http_parser *hp, const char *ptr, size_t len)
111   VALUE v;
113   HP_FL_SET(hp, HASHEADER);
115   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
116     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
117     HP_FL_SET(hp, KAVERSION);
118     v = g_http_11;
119   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
120     v = g_http_10;
121   } else {
122     v = rb_str_new(ptr, len);
123   }
124   rb_hash_aset(hp->env, g_server_protocol, v);
125   rb_hash_aset(hp->env, g_http_version, v);
128 static inline void hp_invalid_if_trailer(struct http_parser *hp)
130   if (HP_FL_TEST(hp, INTRAILER))
131     parser_error("invalid Trailer");
134 static void write_cont_value(struct http_parser *hp,
135                              char *buffer, const char *p)
137   char *vptr;
139   if (hp->cont == Qfalse)
140      parser_error("invalid continuation line");
141   if (NIL_P(hp->cont))
142      return; /* we're ignoring this header (probably Host:) */
144   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
145   assert(hp->mark > 0 && "impossible continuation line offset");
147   if (LEN(mark, p) == 0)
148     return;
150   if (RSTRING_LEN(hp->cont) > 0)
151     --hp->mark;
153   vptr = PTR_TO(mark);
155   if (RSTRING_LEN(hp->cont) > 0) {
156     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
157     *vptr = ' ';
158   }
159   rb_str_buf_cat(hp->cont, vptr, LEN(mark, p));
162 static void write_value(struct http_parser *hp,
163                         const char *buffer, const char *p)
165   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
166   VALUE v;
167   VALUE e;
169   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
170   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STR_NEW(mark, p);
171   if (NIL_P(f)) {
172     const char *field = PTR_TO(start.field);
173     size_t flen = hp->s.field_len;
175     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
177     /*
178      * ignore "Version" headers since they conflict with the HTTP_VERSION
179      * rack env variable.
180      */
181     if (CONST_MEM_EQ("VERSION", field, flen)) {
182       hp->cont = Qnil;
183       return;
184     }
185     f = uncommon_field(field, flen);
186   } else if (f == g_http_connection) {
187     hp_keepalive_connection(hp, v);
188   } else if (f == g_content_length) {
189     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
190     if (hp->len.content < 0)
191       parser_error("invalid Content-Length");
192     if (hp->len.content != 0)
193       HP_FL_SET(hp, HASBODY);
194     hp_invalid_if_trailer(hp);
195   } else if (f == g_http_transfer_encoding) {
196     if (STR_CSTR_CASE_EQ(v, "chunked")) {
197       HP_FL_SET(hp, CHUNKED);
198       HP_FL_SET(hp, HASBODY);
199     }
200     hp_invalid_if_trailer(hp);
201   } else if (f == g_http_trailer) {
202     HP_FL_SET(hp, HASTRAILER);
203     hp_invalid_if_trailer(hp);
204   } else {
205     assert(TYPE(f) == T_STRING && "memoized object is not a string");
206     assert_frozen(f);
207   }
209   e = rb_hash_aref(hp->env, f);
210   if (NIL_P(e)) {
211     hp->cont = rb_hash_aset(hp->env, f, v);
212   } else if (f == g_http_host) {
213     /*
214      * ignored, absolute URLs in REQUEST_URI take precedence over
215      * the Host: header (ref: rfc 2616, section 5.2.1)
216      */
217      hp->cont = Qnil;
218   } else {
219     rb_str_buf_cat(e, ",", 1);
220     hp->cont = rb_str_buf_append(e, v);
221   }
224 /** Machine **/
227   machine http_parser;
229   action mark {MARK(mark, fpc); }
231   action start_field { MARK(start.field, fpc); }
232   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
233   action downcase_char { downcase_char(deconst(fpc)); }
234   action write_field { hp->s.field_len = LEN(start.field, fpc); }
235   action start_value { MARK(mark, fpc); }
236   action write_value { write_value(hp, buffer, fpc); }
237   action write_cont_value { write_cont_value(hp, buffer, fpc); }
238   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
239   action scheme {
240     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
241   }
242   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
243   action request_uri {
244     VALUE str;
246     VALIDATE_MAX_LENGTH(LEN(mark, fpc), REQUEST_URI);
247     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
248     /*
249      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
250      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
251      */
252     if (STR_CSTR_EQ(str, "*")) {
253       str = rb_str_new(NULL, 0);
254       rb_hash_aset(hp->env, g_path_info, str);
255       rb_hash_aset(hp->env, g_request_path, str);
256     }
257   }
258   action fragment {
259     VALIDATE_MAX_LENGTH(LEN(mark, fpc), FRAGMENT);
260     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
261   }
262   action start_query {MARK(start.query, fpc); }
263   action query_string {
264     VALIDATE_MAX_LENGTH(LEN(start.query, fpc), QUERY_STRING);
265     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
266   }
267   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
268   action request_path {
269     VALUE val;
271     VALIDATE_MAX_LENGTH(LEN(mark, fpc), REQUEST_PATH);
272     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
274     /* rack says PATH_INFO must start with "/" or be empty */
275     if (!STR_CSTR_EQ(val, "*"))
276       rb_hash_aset(hp->env, g_path_info, val);
277   }
278   action add_to_chunk_size {
279     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
280     if (hp->len.chunk < 0)
281       parser_error("invalid chunk size");
282   }
283   action header_done {
284     finalize_header(hp);
286     cs = http_parser_first_final;
287     if (HP_FL_TEST(hp, HASBODY)) {
288       HP_FL_SET(hp, INBODY);
289       if (HP_FL_TEST(hp, CHUNKED))
290         cs = http_parser_en_ChunkedBody;
291     } else {
292       HP_FL_SET(hp, REQEOF);
293       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
294     }
295     /*
296      * go back to Ruby so we can call the Rack application, we'll reenter
297      * the parser iff the body needs to be processed.
298      */
299     goto post_exec;
300   }
302   action end_trailers {
303     cs = http_parser_first_final;
304     goto post_exec;
305   }
307   action end_chunked_body {
308     HP_FL_SET(hp, INTRAILER);
309     cs = http_parser_en_Trailers;
310     ++p;
311     assert(p <= pe && "buffer overflow after chunked body");
312     goto post_exec;
313   }
315   action skip_chunk_data {
316   skip_chunk_data_hack: {
317     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
318     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
319     hp->s.dest_offset += nr;
320     hp->len.chunk -= nr;
321     p += nr;
322     assert(hp->len.chunk >= 0 && "negative chunk length");
323     if ((size_t)hp->len.chunk > REMAINING) {
324       HP_FL_SET(hp, INCHUNK);
325       goto post_exec;
326     } else {
327       fhold;
328       fgoto chunk_end;
329     }
330   }}
332   include unicorn_http_common "unicorn_http_common.rl";
335 /** Data **/
336 %% write data;
338 static void http_parser_init(struct http_parser *hp)
340   int cs = 0;
341   hp->flags = 0;
342   hp->mark = 0;
343   hp->offset = 0;
344   hp->start.field = 0;
345   hp->s.field_len = 0;
346   hp->len.content = 0;
347   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
348   %% write init;
349   hp->cs = cs;
352 /** exec **/
353 static void
354 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
356   const char *p, *pe;
357   int cs = hp->cs;
358   size_t off = hp->offset;
360   if (cs == http_parser_first_final)
361     return;
363   assert(off <= len && "offset past end of buffer");
365   p = buffer+off;
366   pe = buffer+len;
368   assert((void *)(pe - p) == (void *)(len - off) &&
369          "pointers aren't same distance");
371   if (HP_FL_TEST(hp, INCHUNK)) {
372     HP_FL_UNSET(hp, INCHUNK);
373     goto skip_chunk_data_hack;
374   }
375   %% write exec;
376 post_exec: /* "_out:" also goes here */
377   if (hp->cs != http_parser_error)
378     hp->cs = cs;
379   hp->offset = p - buffer;
381   assert(p <= pe && "buffer overflow after parsing execute");
382   assert(hp->offset <= len && "offset longer than length");
385 static struct http_parser *data_get(VALUE self)
387   struct http_parser *hp;
389   Data_Get_Struct(self, struct http_parser, hp);
390   assert(hp && "failed to extract http_parser struct");
391   return hp;
394 static void finalize_header(struct http_parser *hp)
396   VALUE temp = rb_hash_aref(hp->env, g_rack_url_scheme);
397   VALUE server_name = g_localhost;
398   VALUE server_port = g_port_80;
400   /* set rack.url_scheme to "https" or "http", no others are allowed by Rack */
401   if (NIL_P(temp)) {
402     temp = rb_hash_aref(hp->env, g_http_x_forwarded_proto);
403     if (!NIL_P(temp) && STR_CSTR_EQ(temp, "https"))
404       server_port = g_port_443;
405     else
406       temp = g_http;
407     rb_hash_aset(hp->env, g_rack_url_scheme, temp);
408   } else if (STR_CSTR_EQ(temp, "https")) {
409     server_port = g_port_443;
410   } else {
411     assert(server_port == g_port_80 && "server_port not set");
412   }
414   /* parse and set the SERVER_NAME and SERVER_PORT variables */
415   temp = rb_hash_aref(hp->env, g_http_host);
416   if (!NIL_P(temp)) {
417     char *colon = memchr(RSTRING_PTR(temp), ':', RSTRING_LEN(temp));
418     if (colon) {
419       long port_start = colon - RSTRING_PTR(temp) + 1;
421       server_name = rb_str_substr(temp, 0, colon - RSTRING_PTR(temp));
422       if ((RSTRING_LEN(temp) - port_start) > 0)
423         server_port = rb_str_substr(temp, port_start, RSTRING_LEN(temp));
424     } else {
425       server_name = temp;
426     }
427   }
428   rb_hash_aset(hp->env, g_server_name, server_name);
429   rb_hash_aset(hp->env, g_server_port, server_port);
430   if (!HP_FL_TEST(hp, HASHEADER))
431     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
433   /* rack requires QUERY_STRING */
434   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
435     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
438 static void hp_mark(void *ptr)
440   struct http_parser *hp = ptr;
442   rb_gc_mark(hp->buf);
443   rb_gc_mark(hp->env);
444   rb_gc_mark(hp->cont);
447 static VALUE HttpParser_alloc(VALUE klass)
449   struct http_parser *hp;
450   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
455  * call-seq:
456  *    parser.new => parser
458  * Creates a new parser.
459  */
460 static VALUE HttpParser_init(VALUE self)
462   struct http_parser *hp = data_get(self);
464   http_parser_init(hp);
465   hp->buf = rb_str_new(NULL, 0);
466   hp->env = rb_hash_new();
468   return self;
472  * call-seq:
473  *    parser.reset => nil
475  * Resets the parser to it's initial state so that you can reuse it
476  * rather than making new ones.
477  */
478 static VALUE HttpParser_reset(VALUE self)
480   struct http_parser *hp = data_get(self);
482   http_parser_init(hp);
483   rb_funcall(hp->env, id_clear, 0);
485   return Qnil;
488 static void advance_str(VALUE str, off_t nr)
490   long len = RSTRING_LEN(str);
492   if (len == 0)
493     return;
495   rb_str_modify(str);
497   assert(nr <= len && "trying to advance past end of buffer");
498   len -= nr;
499   if (len > 0) /* unlikely, len is usually 0 */
500     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
501   rb_str_set_len(str, len);
505  * call-seq:
506  *   parser.content_length => nil or Integer
508  * Returns the number of bytes left to run through HttpParser#filter_body.
509  * This will initially be the value of the "Content-Length" HTTP header
510  * after header parsing is complete and will decrease in value as
511  * HttpParser#filter_body is called for each chunk.  This should return
512  * zero for requests with no body.
514  * This will return nil on "Transfer-Encoding: chunked" requests.
515  */
516 static VALUE HttpParser_content_length(VALUE self)
518   struct http_parser *hp = data_get(self);
520   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
524  * Document-method: parse
525  * call-seq:
526  *    parser.parse => env or nil
528  * Takes a Hash and a String of data, parses the String of data filling
529  * in the Hash returning the Hash if parsing is finished, nil otherwise
530  * When returning the env Hash, it may modify data to point to where
531  * body processing should begin.
533  * Raises HttpParserError if there are parsing errors.
534  */
535 static VALUE HttpParser_parse(VALUE self)
537   struct http_parser *hp = data_get(self);
538   VALUE data = hp->buf;
540   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
541   VALIDATE_MAX_LENGTH(hp->offset, HEADER);
543   if (hp->cs == http_parser_first_final ||
544       hp->cs == http_parser_en_ChunkedBody) {
545     advance_str(data, hp->offset + 1);
546     hp->offset = 0;
547     if (HP_FL_TEST(hp, INTRAILER))
548       HP_FL_SET(hp, REQEOF);
550     return hp->env;
551   }
553   if (hp->cs == http_parser_error)
554     parser_error("Invalid HTTP format, parsing fails.");
556   return Qnil;
560  * Document-method: trailers
561  * call-seq:
562  *    parser.trailers(req, data) => req or nil
564  * This is an alias for HttpParser#headers
565  */
568  * Document-method: headers
569  */
570 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
572   struct http_parser *hp = data_get(self);
574   hp->env = env;
575   hp->buf = buf;
577   return HttpParser_parse(self);
580 static int chunked_eof(struct http_parser *hp)
582   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
586  * call-seq:
587  *    parser.body_eof? => true or false
589  * Detects if we're done filtering the body or not.  This can be used
590  * to detect when to stop calling HttpParser#filter_body.
591  */
592 static VALUE HttpParser_body_eof(VALUE self)
594   struct http_parser *hp = data_get(self);
596   if (HP_FL_TEST(hp, CHUNKED))
597     return chunked_eof(hp) ? Qtrue : Qfalse;
599   return hp->len.content == 0 ? Qtrue : Qfalse;
603  * call-seq:
604  *    parser.keepalive? => true or false
606  * This should be used to detect if a request can really handle
607  * keepalives and pipelining.  Currently, the rules are:
609  * 1. MUST be a GET or HEAD request
610  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
611  * 3. MUST NOT have "Connection: close" set
612  */
613 static VALUE HttpParser_keepalive(VALUE self)
615   struct http_parser *hp = data_get(self);
617   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
621  * call-seq:
622  *    parser.next? => true or false
624  * Exactly like HttpParser#keepalive?, except it will reset the internal
625  * parser state if it returns true.
626  */
627 static VALUE HttpParser_next(VALUE self)
629   struct http_parser *hp = data_get(self);
631   if (HP_FL_ALL(hp, KEEPALIVE)) {
632     http_parser_init(hp);
633     rb_funcall(hp->env, id_clear, 0);
634     return Qtrue;
635   }
636   return Qfalse;
640  * call-seq:
641  *    parser.headers? => true or false
643  * This should be used to detect if a request has headers (and if
644  * the response will have headers as well).  HTTP/0.9 requests
645  * should return false, all subsequent HTTP versions will return true
646  */
647 static VALUE HttpParser_has_headers(VALUE self)
649   struct http_parser *hp = data_get(self);
651   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
654 static VALUE HttpParser_buf(VALUE self)
656   return data_get(self)->buf;
659 static VALUE HttpParser_env(VALUE self)
661   return data_get(self)->env;
665  * call-seq:
666  *    parser.filter_body(buf, data) => nil/data
668  * Takes a String of +data+, will modify data if dechunking is done.
669  * Returns +nil+ if there is more data left to process.  Returns
670  * +data+ if body processing is complete. When returning +data+,
671  * it may modify +data+ so the start of the string points to where
672  * the body ended so that trailer processing can begin.
674  * Raises HttpParserError if there are dechunking errors.
675  * Basically this is a glorified memcpy(3) that copies +data+
676  * into +buf+ while filtering it through the dechunker.
677  */
678 static VALUE HttpParser_filter_body(VALUE self, VALUE buf, VALUE data)
680   struct http_parser *hp = data_get(self);
681   char *dptr;
682   long dlen;
684   dptr = RSTRING_PTR(data);
685   dlen = RSTRING_LEN(data);
687   StringValue(buf);
688   rb_str_resize(buf, dlen); /* we can never copy more than dlen bytes */
689   OBJ_TAINT(buf); /* keep weirdo $SAFE users happy */
691   if (HP_FL_TEST(hp, CHUNKED)) {
692     if (!chunked_eof(hp)) {
693       hp->s.dest_offset = 0;
694       hp->cont = buf;
695       hp->buf = data;
696       http_parser_execute(hp, dptr, dlen);
697       if (hp->cs == http_parser_error)
698         parser_error("Invalid HTTP format, parsing fails.");
700       assert(hp->s.dest_offset <= hp->offset &&
701              "destination buffer overflow");
702       advance_str(data, hp->offset);
703       rb_str_set_len(buf, hp->s.dest_offset);
705       if (RSTRING_LEN(buf) == 0 && chunked_eof(hp)) {
706         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
707       } else {
708         data = Qnil;
709       }
710     }
711   } else {
712     /* no need to enter the Ragel machine for unchunked transfers */
713     assert(hp->len.content >= 0 && "negative Content-Length");
714     if (hp->len.content > 0) {
715       long nr = MIN(dlen, hp->len.content);
717       hp->buf = data;
718       memcpy(RSTRING_PTR(buf), dptr, nr);
719       hp->len.content -= nr;
720       if (hp->len.content == 0) {
721         HP_FL_SET(hp, REQEOF);
722         hp->cs = http_parser_first_final;
723       }
724       advance_str(data, nr);
725       rb_str_set_len(buf, nr);
726       data = Qnil;
727     }
728   }
729   hp->offset = 0; /* for trailer parsing */
730   return data;
733 #define SET_GLOBAL(var,str) do { \
734   var = find_common_field(str, sizeof(str) - 1); \
735   assert(!NIL_P(var) && "missed global field"); \
736 } while (0)
738 void Init_unicorn_http(void)
740   VALUE mUnicorn, cHttpParser;
742   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
743   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
744   eHttpParserError =
745          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
747   init_globals();
748   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
749   rb_define_method(cHttpParser, "initialize", HttpParser_init,0);
750   rb_define_method(cHttpParser, "reset", HttpParser_reset,0);
751   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
752   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
753   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
754   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
755   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
756   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
757   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
758   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
759   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
760   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
761   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
763   /*
764    * The maximum size a single chunk when using chunked transfer encoding.
765    * This is only a theoretical maximum used to detect errors in clients,
766    * it is highly unlikely to encounter clients that send more than
767    * several kilobytes at once.
768    */
769   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
771   /*
772    * The maximum size of the body as specified by Content-Length.
773    * This is only a theoretical maximum, the actual limit is subject
774    * to the limits of the file system used for +Dir.tmpdir+.
775    */
776   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
778   init_common_fields();
779   SET_GLOBAL(g_http_host, "HOST");
780   SET_GLOBAL(g_http_trailer, "TRAILER");
781   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
782   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
783   SET_GLOBAL(g_http_connection, "CONNECTION");
784   id_clear = rb_intern("clear");
786 #undef SET_GLOBAL