http: parser handles IPv6 bracketed IP hostnames
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob971cdc13b92d64229e43e4667f400a11af7ea42b
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 void init_unicorn_httpdate(void);
17 #define UH_FL_CHUNKED  0x1
18 #define UH_FL_HASBODY  0x2
19 #define UH_FL_INBODY   0x4
20 #define UH_FL_HASTRAILER 0x8
21 #define UH_FL_INTRAILER 0x10
22 #define UH_FL_INCHUNK  0x20
23 #define UH_FL_REQEOF 0x40
24 #define UH_FL_KAVERSION 0x80
25 #define UH_FL_HASHEADER 0x100
26 #define UH_FL_TO_CLEAR 0x200
28 /* all of these flags need to be set for keepalive to be supported */
29 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
32  * whether or not to trust X-Forwarded-Proto and X-Forwarded-SSL when
33  * setting rack.url_scheme
34  */
35 static VALUE trust_x_forward = Qtrue;
37 static unsigned long keepalive_requests = 100; /* same as nginx */
40  * Returns the maximum number of keepalive requests a client may make
41  * before the parser refuses to continue.
42  */
43 static VALUE ka_req(VALUE self)
45   return ULONG2NUM(keepalive_requests);
49  * Sets the maximum number of keepalive requests a client may make.
50  * A special value of +nil+ causes this to be the maximum value
51  * possible (this is architecture-dependent).
52  */
53 static VALUE set_ka_req(VALUE self, VALUE val)
55   keepalive_requests = NIL_P(val) ? ULONG_MAX : NUM2ULONG(val);
57   return ka_req(self);
61  * Sets whether or not the parser will trust X-Forwarded-Proto and
62  * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
63  * Rainbows!/Zbatery installations facing untrusted clients directly
64  * should set this to +false+
65  */
66 static VALUE set_xftrust(VALUE self, VALUE val)
68   if (Qtrue == val || Qfalse == val)
69     trust_x_forward = val;
70   else
71     rb_raise(rb_eTypeError, "must be true or false");
73   return val;
77  * returns whether or not the parser will trust X-Forwarded-Proto and
78  * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly
79  */
80 static VALUE xftrust(VALUE self)
82   return trust_x_forward;
85 /* keep this small for Rainbows! since every client has one */
86 struct http_parser {
87   int cs; /* Ragel internal state */
88   unsigned int flags;
89   unsigned long nr_requests;
90   size_t mark;
91   size_t offset;
92   union { /* these 2 fields don't nest */
93     size_t field;
94     size_t query;
95   } start;
96   union {
97     size_t field_len; /* only used during header processing */
98     size_t dest_offset; /* only used during body processing */
99   } s;
100   VALUE buf;
101   VALUE env;
102   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
103   union {
104     off_t content;
105     off_t chunk;
106   } len;
109 static ID id_clear;
111 static void finalize_header(struct http_parser *hp);
113 static void parser_error(const char *msg)
115   VALUE exc = rb_exc_new2(eHttpParserError, msg);
116   VALUE bt = rb_ary_new();
118   rb_funcall(exc, rb_intern("set_backtrace"), 1, bt);
119   rb_exc_raise(exc);
122 #define REMAINING (unsigned long)(pe - p)
123 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
124 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
125 #define PTR_TO(F) (buffer + hp->F)
126 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
128 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
129 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
130 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
131 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
134  * handles values of the "Connection:" header, keepalive is implied
135  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
136  * Additionally, we require GET/HEAD requests to support keepalive.
137  */
138 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
140   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
141     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
142     HP_FL_SET(hp, KAVERSION);
143   } else if (STR_CSTR_CASE_EQ(val, "close")) {
144     /*
145      * it doesn't matter what HTTP version or request method we have,
146      * if a client says "Connection: close", we disable keepalive
147      */
148     HP_FL_UNSET(hp, KAVERSION);
149   } else {
150     /*
151      * client could've sent anything, ignore it for now.  Maybe
152      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
153      * Raising an exception might be too mean...
154      */
155   }
158 static void
159 request_method(struct http_parser *hp, const char *ptr, size_t len)
161   VALUE v = rb_str_new(ptr, len);
163   rb_hash_aset(hp->env, g_request_method, v);
166 static void
167 http_version(struct http_parser *hp, const char *ptr, size_t len)
169   VALUE v;
171   HP_FL_SET(hp, HASHEADER);
173   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
174     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
175     HP_FL_SET(hp, KAVERSION);
176     v = g_http_11;
177   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
178     v = g_http_10;
179   } else {
180     v = rb_str_new(ptr, len);
181   }
182   rb_hash_aset(hp->env, g_server_protocol, v);
183   rb_hash_aset(hp->env, g_http_version, v);
186 static inline void hp_invalid_if_trailer(struct http_parser *hp)
188   if (HP_FL_TEST(hp, INTRAILER))
189     parser_error("invalid Trailer");
192 static void write_cont_value(struct http_parser *hp,
193                              char *buffer, const char *p)
195   char *vptr;
197   if (hp->cont == Qfalse)
198      parser_error("invalid continuation line");
199   if (NIL_P(hp->cont))
200      return; /* we're ignoring this header (probably Host:) */
202   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
203   assert(hp->mark > 0 && "impossible continuation line offset");
205   if (LEN(mark, p) == 0)
206     return;
208   if (RSTRING_LEN(hp->cont) > 0)
209     --hp->mark;
211   vptr = PTR_TO(mark);
213   if (RSTRING_LEN(hp->cont) > 0) {
214     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
215     *vptr = ' ';
216   }
217   rb_str_buf_cat(hp->cont, vptr, LEN(mark, p));
220 static void write_value(struct http_parser *hp,
221                         const char *buffer, const char *p)
223   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
224   VALUE v;
225   VALUE e;
227   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
228   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STR_NEW(mark, p);
229   if (NIL_P(f)) {
230     const char *field = PTR_TO(start.field);
231     size_t flen = hp->s.field_len;
233     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
235     /*
236      * ignore "Version" headers since they conflict with the HTTP_VERSION
237      * rack env variable.
238      */
239     if (CONST_MEM_EQ("VERSION", field, flen)) {
240       hp->cont = Qnil;
241       return;
242     }
243     f = uncommon_field(field, flen);
244   } else if (f == g_http_connection) {
245     hp_keepalive_connection(hp, v);
246   } else if (f == g_content_length) {
247     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
248     if (hp->len.content < 0)
249       parser_error("invalid Content-Length");
250     if (hp->len.content != 0)
251       HP_FL_SET(hp, HASBODY);
252     hp_invalid_if_trailer(hp);
253   } else if (f == g_http_transfer_encoding) {
254     if (STR_CSTR_CASE_EQ(v, "chunked")) {
255       HP_FL_SET(hp, CHUNKED);
256       HP_FL_SET(hp, HASBODY);
257     }
258     hp_invalid_if_trailer(hp);
259   } else if (f == g_http_trailer) {
260     HP_FL_SET(hp, HASTRAILER);
261     hp_invalid_if_trailer(hp);
262   } else {
263     assert(TYPE(f) == T_STRING && "memoized object is not a string");
264     assert_frozen(f);
265   }
267   e = rb_hash_aref(hp->env, f);
268   if (NIL_P(e)) {
269     hp->cont = rb_hash_aset(hp->env, f, v);
270   } else if (f == g_http_host) {
271     /*
272      * ignored, absolute URLs in REQUEST_URI take precedence over
273      * the Host: header (ref: rfc 2616, section 5.2.1)
274      */
275      hp->cont = Qnil;
276   } else {
277     rb_str_buf_cat(e, ",", 1);
278     hp->cont = rb_str_buf_append(e, v);
279   }
282 /** Machine **/
285   machine http_parser;
287   action mark {MARK(mark, fpc); }
289   action start_field { MARK(start.field, fpc); }
290   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
291   action downcase_char { downcase_char(deconst(fpc)); }
292   action write_field { hp->s.field_len = LEN(start.field, fpc); }
293   action start_value { MARK(mark, fpc); }
294   action write_value { write_value(hp, buffer, fpc); }
295   action write_cont_value { write_cont_value(hp, buffer, fpc); }
296   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
297   action scheme {
298     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
299   }
300   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
301   action request_uri {
302     VALUE str;
304     VALIDATE_MAX_LENGTH(LEN(mark, fpc), REQUEST_URI);
305     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
306     /*
307      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
308      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
309      */
310     if (STR_CSTR_EQ(str, "*")) {
311       str = rb_str_new(NULL, 0);
312       rb_hash_aset(hp->env, g_path_info, str);
313       rb_hash_aset(hp->env, g_request_path, str);
314     }
315   }
316   action fragment {
317     VALIDATE_MAX_LENGTH(LEN(mark, fpc), FRAGMENT);
318     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
319   }
320   action start_query {MARK(start.query, fpc); }
321   action query_string {
322     VALIDATE_MAX_LENGTH(LEN(start.query, fpc), QUERY_STRING);
323     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
324   }
325   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
326   action request_path {
327     VALUE val;
329     VALIDATE_MAX_LENGTH(LEN(mark, fpc), REQUEST_PATH);
330     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
332     /* rack says PATH_INFO must start with "/" or be empty */
333     if (!STR_CSTR_EQ(val, "*"))
334       rb_hash_aset(hp->env, g_path_info, val);
335   }
336   action add_to_chunk_size {
337     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
338     if (hp->len.chunk < 0)
339       parser_error("invalid chunk size");
340   }
341   action header_done {
342     finalize_header(hp);
344     cs = http_parser_first_final;
345     if (HP_FL_TEST(hp, HASBODY)) {
346       HP_FL_SET(hp, INBODY);
347       if (HP_FL_TEST(hp, CHUNKED))
348         cs = http_parser_en_ChunkedBody;
349     } else {
350       HP_FL_SET(hp, REQEOF);
351       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
352     }
353     /*
354      * go back to Ruby so we can call the Rack application, we'll reenter
355      * the parser iff the body needs to be processed.
356      */
357     goto post_exec;
358   }
360   action end_trailers {
361     cs = http_parser_first_final;
362     goto post_exec;
363   }
365   action end_chunked_body {
366     HP_FL_SET(hp, INTRAILER);
367     cs = http_parser_en_Trailers;
368     ++p;
369     assert(p <= pe && "buffer overflow after chunked body");
370     goto post_exec;
371   }
373   action skip_chunk_data {
374   skip_chunk_data_hack: {
375     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
376     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
377     hp->s.dest_offset += nr;
378     hp->len.chunk -= nr;
379     p += nr;
380     assert(hp->len.chunk >= 0 && "negative chunk length");
381     if ((size_t)hp->len.chunk > REMAINING) {
382       HP_FL_SET(hp, INCHUNK);
383       goto post_exec;
384     } else {
385       fhold;
386       fgoto chunk_end;
387     }
388   }}
390   include unicorn_http_common "unicorn_http_common.rl";
393 /** Data **/
394 %% write data;
396 static void http_parser_init(struct http_parser *hp)
398   int cs = 0;
399   hp->flags = 0;
400   hp->mark = 0;
401   hp->offset = 0;
402   hp->start.field = 0;
403   hp->s.field_len = 0;
404   hp->len.content = 0;
405   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
406   %% write init;
407   hp->cs = cs;
410 /** exec **/
411 static void
412 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
414   const char *p, *pe;
415   int cs = hp->cs;
416   size_t off = hp->offset;
418   if (cs == http_parser_first_final)
419     return;
421   assert(off <= len && "offset past end of buffer");
423   p = buffer+off;
424   pe = buffer+len;
426   assert((void *)(pe - p) == (void *)(len - off) &&
427          "pointers aren't same distance");
429   if (HP_FL_TEST(hp, INCHUNK)) {
430     HP_FL_UNSET(hp, INCHUNK);
431     goto skip_chunk_data_hack;
432   }
433   %% write exec;
434 post_exec: /* "_out:" also goes here */
435   if (hp->cs != http_parser_error)
436     hp->cs = cs;
437   hp->offset = p - buffer;
439   assert(p <= pe && "buffer overflow after parsing execute");
440   assert(hp->offset <= len && "offset longer than length");
443 static struct http_parser *data_get(VALUE self)
445   struct http_parser *hp;
447   Data_Get_Struct(self, struct http_parser, hp);
448   assert(hp && "failed to extract http_parser struct");
449   return hp;
453  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
454  * this resembles the Rack::Request#scheme method as of rack commit
455  * 35bb5ba6746b5d346de9202c004cc926039650c7
456  */
457 static void set_url_scheme(VALUE env, VALUE *server_port)
459   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
461   if (NIL_P(scheme)) {
462     if (trust_x_forward == Qfalse) {
463       scheme = g_http;
464     } else {
465       scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
466       if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
467         *server_port = g_port_443;
468         scheme = g_https;
469       } else {
470         scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
471         if (NIL_P(scheme)) {
472           scheme = g_http;
473         } else {
474           long len = RSTRING_LEN(scheme);
475           if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
476             if (len != 5)
477               scheme = g_https;
478             *server_port = g_port_443;
479           } else {
480             scheme = g_http;
481           }
482         }
483       }
484     }
485     rb_hash_aset(env, g_rack_url_scheme, scheme);
486   } else if (STR_CSTR_EQ(scheme, "https")) {
487     *server_port = g_port_443;
488   } else {
489     assert(*server_port == g_port_80 && "server_port not set");
490   }
494  * Parse and set the SERVER_NAME and SERVER_PORT variables
495  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
496  * anybody who needs them is using an unsupported configuration and/or
497  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
498  * fine.
499  */
500 static void set_server_vars(VALUE env, VALUE *server_port)
502   VALUE server_name = g_localhost;
503   VALUE host = rb_hash_aref(env, g_http_host);
505   if (!NIL_P(host)) {
506     char *host_ptr = RSTRING_PTR(host);
507     long host_len = RSTRING_LEN(host);
508     char *colon;
510     if (*host_ptr == '[') { /* ipv6 address format */
511       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
513       if (rbracket)
514         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
515       else
516         colon = memchr(host_ptr + 1, ':', host_len - 1);
517     } else {
518       colon = memchr(host_ptr, ':', host_len);
519     }
521     if (colon) {
522       long port_start = colon - host_ptr + 1;
524       server_name = rb_str_substr(host, 0, colon - host_ptr);
525       if ((host_len - port_start) > 0)
526         *server_port = rb_str_substr(host, port_start, host_len);
527     } else {
528       server_name = host;
529     }
530   }
531   rb_hash_aset(env, g_server_name, server_name);
532   rb_hash_aset(env, g_server_port, *server_port);
535 static void finalize_header(struct http_parser *hp)
537   VALUE server_port = g_port_80;
539   set_url_scheme(hp->env, &server_port);
540   set_server_vars(hp->env, &server_port);
542   if (!HP_FL_TEST(hp, HASHEADER))
543     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
545   /* rack requires QUERY_STRING */
546   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
547     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
550 static void hp_mark(void *ptr)
552   struct http_parser *hp = ptr;
554   rb_gc_mark(hp->buf);
555   rb_gc_mark(hp->env);
556   rb_gc_mark(hp->cont);
559 static VALUE HttpParser_alloc(VALUE klass)
561   struct http_parser *hp;
562   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
567  * call-seq:
568  *    parser.new => parser
570  * Creates a new parser.
571  */
572 static VALUE HttpParser_init(VALUE self)
574   struct http_parser *hp = data_get(self);
576   http_parser_init(hp);
577   hp->buf = rb_str_new(NULL, 0);
578   hp->env = rb_hash_new();
579   hp->nr_requests = keepalive_requests;
581   return self;
585  * call-seq:
586  *    parser.clear => parser
588  * Resets the parser to it's initial state so that you can reuse it
589  * rather than making new ones.
590  */
591 static VALUE HttpParser_clear(VALUE self)
593   struct http_parser *hp = data_get(self);
595   http_parser_init(hp);
596   rb_funcall(hp->env, id_clear, 0);
598   return self;
602  * call-seq:
603  *    parser.reset => nil
605  * Resets the parser to it's initial state so that you can reuse it
606  * rather than making new ones.
608  * This method is deprecated and to be removed in Unicorn 4.x
609  */
610 static VALUE HttpParser_reset(VALUE self)
612   static int warned;
614   if (!warned) {
615     rb_warn("Unicorn::HttpParser#reset is deprecated; "
616             "use Unicorn::HttpParser#clear instead");
617   }
618   HttpParser_clear(self);
619   return Qnil;
622 static void advance_str(VALUE str, off_t nr)
624   long len = RSTRING_LEN(str);
626   if (len == 0)
627     return;
629   rb_str_modify(str);
631   assert(nr <= len && "trying to advance past end of buffer");
632   len -= nr;
633   if (len > 0) /* unlikely, len is usually 0 */
634     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
635   rb_str_set_len(str, len);
639  * call-seq:
640  *   parser.content_length => nil or Integer
642  * Returns the number of bytes left to run through HttpParser#filter_body.
643  * This will initially be the value of the "Content-Length" HTTP header
644  * after header parsing is complete and will decrease in value as
645  * HttpParser#filter_body is called for each chunk.  This should return
646  * zero for requests with no body.
648  * This will return nil on "Transfer-Encoding: chunked" requests.
649  */
650 static VALUE HttpParser_content_length(VALUE self)
652   struct http_parser *hp = data_get(self);
654   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
658  * Document-method: parse
659  * call-seq:
660  *    parser.parse => env or nil
662  * Takes a Hash and a String of data, parses the String of data filling
663  * in the Hash returning the Hash if parsing is finished, nil otherwise
664  * When returning the env Hash, it may modify data to point to where
665  * body processing should begin.
667  * Raises HttpParserError if there are parsing errors.
668  */
669 static VALUE HttpParser_parse(VALUE self)
671   struct http_parser *hp = data_get(self);
672   VALUE data = hp->buf;
674   if (HP_FL_TEST(hp, TO_CLEAR)) {
675     http_parser_init(hp);
676     rb_funcall(hp->env, id_clear, 0);
677   }
679   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
680   VALIDATE_MAX_LENGTH(hp->offset, HEADER);
682   if (hp->cs == http_parser_first_final ||
683       hp->cs == http_parser_en_ChunkedBody) {
684     advance_str(data, hp->offset + 1);
685     hp->offset = 0;
686     if (HP_FL_TEST(hp, INTRAILER))
687       HP_FL_SET(hp, REQEOF);
689     return hp->env;
690   }
692   if (hp->cs == http_parser_error)
693     parser_error("Invalid HTTP format, parsing fails.");
695   return Qnil;
699  * Document-method: trailers
700  * call-seq:
701  *    parser.trailers(req, data) => req or nil
703  * This is an alias for HttpParser#headers
704  */
707  * Document-method: headers
708  */
709 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
711   struct http_parser *hp = data_get(self);
713   hp->env = env;
714   hp->buf = buf;
716   return HttpParser_parse(self);
719 static int chunked_eof(struct http_parser *hp)
721   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
725  * call-seq:
726  *    parser.body_eof? => true or false
728  * Detects if we're done filtering the body or not.  This can be used
729  * to detect when to stop calling HttpParser#filter_body.
730  */
731 static VALUE HttpParser_body_eof(VALUE self)
733   struct http_parser *hp = data_get(self);
735   if (HP_FL_TEST(hp, CHUNKED))
736     return chunked_eof(hp) ? Qtrue : Qfalse;
738   return hp->len.content == 0 ? Qtrue : Qfalse;
742  * call-seq:
743  *    parser.keepalive? => true or false
745  * This should be used to detect if a request can really handle
746  * keepalives and pipelining.  Currently, the rules are:
748  * 1. MUST be a GET or HEAD request
749  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
750  * 3. MUST NOT have "Connection: close" set
751  */
752 static VALUE HttpParser_keepalive(VALUE self)
754   struct http_parser *hp = data_get(self);
756   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
760  * call-seq:
761  *    parser.next? => true or false
763  * Exactly like HttpParser#keepalive?, except it will reset the internal
764  * parser state on next parse if it returns true.  It will also respect
765  * the maximum *keepalive_requests* value and return false if that is
766  * reached.
767  */
768 static VALUE HttpParser_next(VALUE self)
770   struct http_parser *hp = data_get(self);
772   if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
773     HP_FL_SET(hp, TO_CLEAR);
774     return Qtrue;
775   }
776   return Qfalse;
780  * call-seq:
781  *    parser.headers? => true or false
783  * This should be used to detect if a request has headers (and if
784  * the response will have headers as well).  HTTP/0.9 requests
785  * should return false, all subsequent HTTP versions will return true
786  */
787 static VALUE HttpParser_has_headers(VALUE self)
789   struct http_parser *hp = data_get(self);
791   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
794 static VALUE HttpParser_buf(VALUE self)
796   return data_get(self)->buf;
799 static VALUE HttpParser_env(VALUE self)
801   return data_get(self)->env;
805  * call-seq:
806  *    parser.filter_body(buf, data) => nil/data
808  * Takes a String of +data+, will modify data if dechunking is done.
809  * Returns +nil+ if there is more data left to process.  Returns
810  * +data+ if body processing is complete. When returning +data+,
811  * it may modify +data+ so the start of the string points to where
812  * the body ended so that trailer processing can begin.
814  * Raises HttpParserError if there are dechunking errors.
815  * Basically this is a glorified memcpy(3) that copies +data+
816  * into +buf+ while filtering it through the dechunker.
817  */
818 static VALUE HttpParser_filter_body(VALUE self, VALUE buf, VALUE data)
820   struct http_parser *hp = data_get(self);
821   char *dptr;
822   long dlen;
824   dptr = RSTRING_PTR(data);
825   dlen = RSTRING_LEN(data);
827   StringValue(buf);
828   rb_str_resize(buf, dlen); /* we can never copy more than dlen bytes */
829   OBJ_TAINT(buf); /* keep weirdo $SAFE users happy */
831   if (HP_FL_TEST(hp, CHUNKED)) {
832     if (!chunked_eof(hp)) {
833       hp->s.dest_offset = 0;
834       hp->cont = buf;
835       hp->buf = data;
836       http_parser_execute(hp, dptr, dlen);
837       if (hp->cs == http_parser_error)
838         parser_error("Invalid HTTP format, parsing fails.");
840       assert(hp->s.dest_offset <= hp->offset &&
841              "destination buffer overflow");
842       advance_str(data, hp->offset);
843       rb_str_set_len(buf, hp->s.dest_offset);
845       if (RSTRING_LEN(buf) == 0 && chunked_eof(hp)) {
846         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
847       } else {
848         data = Qnil;
849       }
850     }
851   } else {
852     /* no need to enter the Ragel machine for unchunked transfers */
853     assert(hp->len.content >= 0 && "negative Content-Length");
854     if (hp->len.content > 0) {
855       long nr = MIN(dlen, hp->len.content);
857       hp->buf = data;
858       memcpy(RSTRING_PTR(buf), dptr, nr);
859       hp->len.content -= nr;
860       if (hp->len.content == 0) {
861         HP_FL_SET(hp, REQEOF);
862         hp->cs = http_parser_first_final;
863       }
864       advance_str(data, nr);
865       rb_str_set_len(buf, nr);
866       data = Qnil;
867     }
868   }
869   hp->offset = 0; /* for trailer parsing */
870   return data;
873 #define SET_GLOBAL(var,str) do { \
874   var = find_common_field(str, sizeof(str) - 1); \
875   assert(!NIL_P(var) && "missed global field"); \
876 } while (0)
878 void Init_unicorn_http(void)
880   VALUE mUnicorn, cHttpParser;
882   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
883   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
884   eHttpParserError =
885          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
887   init_globals();
888   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
889   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
890   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
891   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
892   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
893   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
894   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
895   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
896   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
897   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
898   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
899   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
900   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
901   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
902   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
904   /*
905    * The maximum size a single chunk when using chunked transfer encoding.
906    * This is only a theoretical maximum used to detect errors in clients,
907    * it is highly unlikely to encounter clients that send more than
908    * several kilobytes at once.
909    */
910   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
912   /*
913    * The maximum size of the body as specified by Content-Length.
914    * This is only a theoretical maximum, the actual limit is subject
915    * to the limits of the file system used for +Dir.tmpdir+.
916    */
917   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
919   /* default value for keepalive_requests */
920   rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
921                   ULONG2NUM(keepalive_requests));
923   rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
924   rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
925   rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
926   rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
928   init_common_fields();
929   SET_GLOBAL(g_http_host, "HOST");
930   SET_GLOBAL(g_http_trailer, "TRAILER");
931   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
932   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
933   SET_GLOBAL(g_http_connection, "CONNECTION");
934   id_clear = rb_intern("clear");
935   init_unicorn_httpdate();
937 #undef SET_GLOBAL