Begin writing HTTP request headers early to detect disconnected clients
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob1a8003f97401c69c716da447c073e918bfb94cd6
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 1.8 or
5  * the GPLv3
6  */
7 #include "ruby.h"
8 #include "ext_help.h"
9 #include <assert.h>
10 #include <string.h>
11 #include <sys/types.h>
12 #include "common_field_optimization.h"
13 #include "global_variables.h"
14 #include "c_util.h"
16 void init_unicorn_httpdate(void);
18 #define UH_FL_CHUNKED  0x1
19 #define UH_FL_HASBODY  0x2
20 #define UH_FL_INBODY   0x4
21 #define UH_FL_HASTRAILER 0x8
22 #define UH_FL_INTRAILER 0x10
23 #define UH_FL_INCHUNK  0x20
24 #define UH_FL_REQEOF 0x40
25 #define UH_FL_KAVERSION 0x80
26 #define UH_FL_HASHEADER 0x100
27 #define UH_FL_TO_CLEAR 0x200
29 /* all of these flags need to be set for keepalive to be supported */
30 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
33  * whether or not to trust X-Forwarded-Proto and X-Forwarded-SSL when
34  * setting rack.url_scheme
35  */
36 static VALUE trust_x_forward = Qtrue;
38 static unsigned long keepalive_requests = 100; /* same as nginx */
41  * Returns the maximum number of keepalive requests a client may make
42  * before the parser refuses to continue.
43  */
44 static VALUE ka_req(VALUE self)
46   return ULONG2NUM(keepalive_requests);
50  * Sets the maximum number of keepalive requests a client may make.
51  * A special value of +nil+ causes this to be the maximum value
52  * possible (this is architecture-dependent).
53  */
54 static VALUE set_ka_req(VALUE self, VALUE val)
56   keepalive_requests = NIL_P(val) ? ULONG_MAX : NUM2ULONG(val);
58   return ka_req(self);
62  * Sets whether or not the parser will trust X-Forwarded-Proto and
63  * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
64  * Rainbows!/Zbatery installations facing untrusted clients directly
65  * should set this to +false+
66  */
67 static VALUE set_xftrust(VALUE self, VALUE val)
69   if (Qtrue == val || Qfalse == val)
70     trust_x_forward = val;
71   else
72     rb_raise(rb_eTypeError, "must be true or false");
74   return val;
78  * returns whether or not the parser will trust X-Forwarded-Proto and
79  * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly
80  */
81 static VALUE xftrust(VALUE self)
83   return trust_x_forward;
86 static size_t MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
88 /* this is only intended for use with Rainbows! */
89 static VALUE set_maxhdrlen(VALUE self, VALUE len)
91   return SIZET2NUM(MAX_HEADER_LEN = NUM2SIZET(len));
94 /* keep this small for Rainbows! since every client has one */
95 struct http_parser {
96   int cs; /* Ragel internal state */
97   unsigned int flags;
98   unsigned long nr_requests;
99   size_t mark;
100   size_t offset;
101   union { /* these 2 fields don't nest */
102     size_t field;
103     size_t query;
104   } start;
105   union {
106     size_t field_len; /* only used during header processing */
107     size_t dest_offset; /* only used during body processing */
108   } s;
109   VALUE buf;
110   VALUE env;
111   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
112   union {
113     off_t content;
114     off_t chunk;
115   } len;
118 static ID id_clear, id_set_backtrace, id_response_start_sent;
120 static void finalize_header(struct http_parser *hp);
122 static void parser_raise(VALUE klass, const char *msg)
124   VALUE exc = rb_exc_new2(klass, msg);
125   VALUE bt = rb_ary_new();
127         rb_funcall(exc, id_set_backtrace, 1, bt);
128         rb_exc_raise(exc);
131 #define REMAINING (unsigned long)(pe - p)
132 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
133 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
134 #define PTR_TO(F) (buffer + hp->F)
135 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
136 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
138 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
139 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
140 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
141 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
143 static int is_lws(char c)
145   return (c == ' ' || c == '\t');
148 static VALUE stripped_str_new(const char *str, long len)
150   long end;
152   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
154   return rb_str_new(str, end + 1);
158  * handles values of the "Connection:" header, keepalive is implied
159  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
160  * Additionally, we require GET/HEAD requests to support keepalive.
161  */
162 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
164   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
165     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
166     HP_FL_SET(hp, KAVERSION);
167   } else if (STR_CSTR_CASE_EQ(val, "close")) {
168     /*
169      * it doesn't matter what HTTP version or request method we have,
170      * if a client says "Connection: close", we disable keepalive
171      */
172     HP_FL_UNSET(hp, KAVERSION);
173   } else {
174     /*
175      * client could've sent anything, ignore it for now.  Maybe
176      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
177      * Raising an exception might be too mean...
178      */
179   }
182 static void
183 request_method(struct http_parser *hp, const char *ptr, size_t len)
185   VALUE v = rb_str_new(ptr, len);
187   rb_hash_aset(hp->env, g_request_method, v);
190 static void
191 http_version(struct http_parser *hp, const char *ptr, size_t len)
193   VALUE v;
195   HP_FL_SET(hp, HASHEADER);
197   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
198     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
199     HP_FL_SET(hp, KAVERSION);
200     v = g_http_11;
201   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
202     v = g_http_10;
203   } else {
204     v = rb_str_new(ptr, len);
205   }
206   rb_hash_aset(hp->env, g_server_protocol, v);
207   rb_hash_aset(hp->env, g_http_version, v);
210 static inline void hp_invalid_if_trailer(struct http_parser *hp)
212   if (HP_FL_TEST(hp, INTRAILER))
213     parser_raise(eHttpParserError, "invalid Trailer");
216 static void write_cont_value(struct http_parser *hp,
217                              char *buffer, const char *p)
219   char *vptr;
220   long end;
221   long len = LEN(mark, p);
222   long cont_len;
224   if (hp->cont == Qfalse)
225      parser_raise(eHttpParserError, "invalid continuation line");
226   if (NIL_P(hp->cont))
227      return; /* we're ignoring this header (probably Host:) */
229   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
230   assert(hp->mark > 0 && "impossible continuation line offset");
232   if (len == 0)
233     return;
235   cont_len = RSTRING_LEN(hp->cont);
236   if (cont_len > 0) {
237     --hp->mark;
238     len = LEN(mark, p);
239   }
240   vptr = PTR_TO(mark);
242   /* normalize tab to space */
243   if (cont_len > 0) {
244     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
245     *vptr = ' ';
246   }
248   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
249   rb_str_buf_cat(hp->cont, vptr, end + 1);
252 static void write_value(struct http_parser *hp,
253                         const char *buffer, const char *p)
255   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
256   VALUE v;
257   VALUE e;
259   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
260   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
261   if (NIL_P(f)) {
262     const char *field = PTR_TO(start.field);
263     size_t flen = hp->s.field_len;
265     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
267     /*
268      * ignore "Version" headers since they conflict with the HTTP_VERSION
269      * rack env variable.
270      */
271     if (CONST_MEM_EQ("VERSION", field, flen)) {
272       hp->cont = Qnil;
273       return;
274     }
275     f = uncommon_field(field, flen);
276   } else if (f == g_http_connection) {
277     hp_keepalive_connection(hp, v);
278   } else if (f == g_content_length) {
279     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
280     if (hp->len.content < 0)
281       parser_raise(eHttpParserError, "invalid Content-Length");
282     if (hp->len.content != 0)
283       HP_FL_SET(hp, HASBODY);
284     hp_invalid_if_trailer(hp);
285   } else if (f == g_http_transfer_encoding) {
286     if (STR_CSTR_CASE_EQ(v, "chunked")) {
287       HP_FL_SET(hp, CHUNKED);
288       HP_FL_SET(hp, HASBODY);
289     }
290     hp_invalid_if_trailer(hp);
291   } else if (f == g_http_trailer) {
292     HP_FL_SET(hp, HASTRAILER);
293     hp_invalid_if_trailer(hp);
294   } else {
295     assert(TYPE(f) == T_STRING && "memoized object is not a string");
296     assert_frozen(f);
297   }
299   e = rb_hash_aref(hp->env, f);
300   if (NIL_P(e)) {
301     hp->cont = rb_hash_aset(hp->env, f, v);
302   } else if (f == g_http_host) {
303     /*
304      * ignored, absolute URLs in REQUEST_URI take precedence over
305      * the Host: header (ref: rfc 2616, section 5.2.1)
306      */
307      hp->cont = Qnil;
308   } else {
309     rb_str_buf_cat(e, ",", 1);
310     hp->cont = rb_str_buf_append(e, v);
311   }
314 /** Machine **/
317   machine http_parser;
319   action mark {MARK(mark, fpc); }
321   action start_field { MARK(start.field, fpc); }
322   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
323   action downcase_char { downcase_char(deconst(fpc)); }
324   action write_field { hp->s.field_len = LEN(start.field, fpc); }
325   action start_value { MARK(mark, fpc); }
326   action write_value { write_value(hp, buffer, fpc); }
327   action write_cont_value { write_cont_value(hp, buffer, fpc); }
328   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
329   action scheme {
330     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
331   }
332   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
333   action request_uri {
334     VALUE str;
336     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
337     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
338     /*
339      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
340      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
341      */
342     if (STR_CSTR_EQ(str, "*")) {
343       str = rb_str_new(NULL, 0);
344       rb_hash_aset(hp->env, g_path_info, str);
345       rb_hash_aset(hp->env, g_request_path, str);
346     }
347   }
348   action fragment {
349     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
350     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
351   }
352   action start_query {MARK(start.query, fpc); }
353   action query_string {
354     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
355     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
356   }
357   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
358   action request_path {
359     VALUE val;
361     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
362     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
364     /* rack says PATH_INFO must start with "/" or be empty */
365     if (!STR_CSTR_EQ(val, "*"))
366       rb_hash_aset(hp->env, g_path_info, val);
367   }
368   action add_to_chunk_size {
369     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
370     if (hp->len.chunk < 0)
371       parser_raise(eHttpParserError, "invalid chunk size");
372   }
373   action header_done {
374     finalize_header(hp);
376     cs = http_parser_first_final;
377     if (HP_FL_TEST(hp, HASBODY)) {
378       HP_FL_SET(hp, INBODY);
379       if (HP_FL_TEST(hp, CHUNKED))
380         cs = http_parser_en_ChunkedBody;
381     } else {
382       HP_FL_SET(hp, REQEOF);
383       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
384     }
385     /*
386      * go back to Ruby so we can call the Rack application, we'll reenter
387      * the parser iff the body needs to be processed.
388      */
389     goto post_exec;
390   }
392   action end_trailers {
393     cs = http_parser_first_final;
394     goto post_exec;
395   }
397   action end_chunked_body {
398     HP_FL_SET(hp, INTRAILER);
399     cs = http_parser_en_Trailers;
400     ++p;
401     assert(p <= pe && "buffer overflow after chunked body");
402     goto post_exec;
403   }
405   action skip_chunk_data {
406   skip_chunk_data_hack: {
407     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
408     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
409     hp->s.dest_offset += nr;
410     hp->len.chunk -= nr;
411     p += nr;
412     assert(hp->len.chunk >= 0 && "negative chunk length");
413     if ((size_t)hp->len.chunk > REMAINING) {
414       HP_FL_SET(hp, INCHUNK);
415       goto post_exec;
416     } else {
417       fhold;
418       fgoto chunk_end;
419     }
420   }}
422   include unicorn_http_common "unicorn_http_common.rl";
425 /** Data **/
426 %% write data;
428 static void http_parser_init(struct http_parser *hp)
430   int cs = 0;
431   hp->flags = 0;
432   hp->mark = 0;
433   hp->offset = 0;
434   hp->start.field = 0;
435   hp->s.field_len = 0;
436   hp->len.content = 0;
437   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
438   %% write init;
439   hp->cs = cs;
442 /** exec **/
443 static void
444 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
446   const char *p, *pe;
447   int cs = hp->cs;
448   size_t off = hp->offset;
450   if (cs == http_parser_first_final)
451     return;
453   assert(off <= len && "offset past end of buffer");
455   p = buffer+off;
456   pe = buffer+len;
458   assert((void *)(pe - p) == (void *)(len - off) &&
459          "pointers aren't same distance");
461   if (HP_FL_TEST(hp, INCHUNK)) {
462     HP_FL_UNSET(hp, INCHUNK);
463     goto skip_chunk_data_hack;
464   }
465   %% write exec;
466 post_exec: /* "_out:" also goes here */
467   if (hp->cs != http_parser_error)
468     hp->cs = cs;
469   hp->offset = p - buffer;
471   assert(p <= pe && "buffer overflow after parsing execute");
472   assert(hp->offset <= len && "offset longer than length");
475 static struct http_parser *data_get(VALUE self)
477   struct http_parser *hp;
479   Data_Get_Struct(self, struct http_parser, hp);
480   assert(hp && "failed to extract http_parser struct");
481   return hp;
485  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
486  * this resembles the Rack::Request#scheme method as of rack commit
487  * 35bb5ba6746b5d346de9202c004cc926039650c7
488  */
489 static void set_url_scheme(VALUE env, VALUE *server_port)
491   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
493   if (NIL_P(scheme)) {
494     if (trust_x_forward == Qfalse) {
495       scheme = g_http;
496     } else {
497       scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
498       if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
499         *server_port = g_port_443;
500         scheme = g_https;
501       } else {
502         scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
503         if (NIL_P(scheme)) {
504           scheme = g_http;
505         } else {
506           long len = RSTRING_LEN(scheme);
507           if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
508             if (len != 5)
509               scheme = g_https;
510             *server_port = g_port_443;
511           } else {
512             scheme = g_http;
513           }
514         }
515       }
516     }
517     rb_hash_aset(env, g_rack_url_scheme, scheme);
518   } else if (STR_CSTR_EQ(scheme, "https")) {
519     *server_port = g_port_443;
520   } else {
521     assert(*server_port == g_port_80 && "server_port not set");
522   }
526  * Parse and set the SERVER_NAME and SERVER_PORT variables
527  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
528  * anybody who needs them is using an unsupported configuration and/or
529  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
530  * fine.
531  */
532 static void set_server_vars(VALUE env, VALUE *server_port)
534   VALUE server_name = g_localhost;
535   VALUE host = rb_hash_aref(env, g_http_host);
537   if (!NIL_P(host)) {
538     char *host_ptr = RSTRING_PTR(host);
539     long host_len = RSTRING_LEN(host);
540     char *colon;
542     if (*host_ptr == '[') { /* ipv6 address format */
543       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
545       if (rbracket)
546         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
547       else
548         colon = memchr(host_ptr + 1, ':', host_len - 1);
549     } else {
550       colon = memchr(host_ptr, ':', host_len);
551     }
553     if (colon) {
554       long port_start = colon - host_ptr + 1;
556       server_name = rb_str_substr(host, 0, colon - host_ptr);
557       if ((host_len - port_start) > 0)
558         *server_port = rb_str_substr(host, port_start, host_len);
559     } else {
560       server_name = host;
561     }
562   }
563   rb_hash_aset(env, g_server_name, server_name);
564   rb_hash_aset(env, g_server_port, *server_port);
567 static void finalize_header(struct http_parser *hp)
569   VALUE server_port = g_port_80;
571   set_url_scheme(hp->env, &server_port);
572   set_server_vars(hp->env, &server_port);
574   if (!HP_FL_TEST(hp, HASHEADER))
575     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
577   /* rack requires QUERY_STRING */
578   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
579     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
582 static void hp_mark(void *ptr)
584   struct http_parser *hp = ptr;
586   rb_gc_mark(hp->buf);
587   rb_gc_mark(hp->env);
588   rb_gc_mark(hp->cont);
591 static VALUE HttpParser_alloc(VALUE klass)
593   struct http_parser *hp;
594   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
599  * call-seq:
600  *    parser.new => parser
602  * Creates a new parser.
603  */
604 static VALUE HttpParser_init(VALUE self)
606   struct http_parser *hp = data_get(self);
608   http_parser_init(hp);
609   hp->buf = rb_str_new(NULL, 0);
610   hp->env = rb_hash_new();
611   hp->nr_requests = keepalive_requests;
613   return self;
617  * call-seq:
618  *    parser.clear => parser
620  * Resets the parser to it's initial state so that you can reuse it
621  * rather than making new ones.
622  */
623 static VALUE HttpParser_clear(VALUE self)
625   struct http_parser *hp = data_get(self);
627   http_parser_init(hp);
628   rb_funcall(hp->env, id_clear, 0);
629   rb_ivar_set(self, id_response_start_sent, Qfalse);
631   return self;
635  * call-seq:
636  *    parser.dechunk! => parser
638  * Resets the parser to a state suitable for dechunking response bodies
640  */
641 static VALUE HttpParser_dechunk_bang(VALUE self)
643   struct http_parser *hp = data_get(self);
645   http_parser_init(hp);
647   /*
648    * we don't care about trailers in dechunk-only mode,
649    * but if we did we'd set UH_FL_HASTRAILER and clear hp->env
650    */
651   if (0) {
652     rb_funcall(hp->env, id_clear, 0);
653     hp->flags = UH_FL_HASTRAILER;
654   }
656   hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED;
657   hp->cs = http_parser_en_ChunkedBody;
659   return self;
663  * call-seq:
664  *    parser.reset => nil
666  * Resets the parser to it's initial state so that you can reuse it
667  * rather than making new ones.
669  * This method is deprecated and to be removed in Unicorn 4.x
670  */
671 static VALUE HttpParser_reset(VALUE self)
673   static int warned;
675   if (!warned) {
676     rb_warn("Unicorn::HttpParser#reset is deprecated; "
677             "use Unicorn::HttpParser#clear instead");
678   }
679   HttpParser_clear(self);
680   return Qnil;
683 static void advance_str(VALUE str, off_t nr)
685   long len = RSTRING_LEN(str);
687   if (len == 0)
688     return;
690   rb_str_modify(str);
692   assert(nr <= len && "trying to advance past end of buffer");
693   len -= nr;
694   if (len > 0) /* unlikely, len is usually 0 */
695     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
696   rb_str_set_len(str, len);
700  * call-seq:
701  *   parser.content_length => nil or Integer
703  * Returns the number of bytes left to run through HttpParser#filter_body.
704  * This will initially be the value of the "Content-Length" HTTP header
705  * after header parsing is complete and will decrease in value as
706  * HttpParser#filter_body is called for each chunk.  This should return
707  * zero for requests with no body.
709  * This will return nil on "Transfer-Encoding: chunked" requests.
710  */
711 static VALUE HttpParser_content_length(VALUE self)
713   struct http_parser *hp = data_get(self);
715   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
719  * Document-method: parse
720  * call-seq:
721  *    parser.parse => env or nil
723  * Takes a Hash and a String of data, parses the String of data filling
724  * in the Hash returning the Hash if parsing is finished, nil otherwise
725  * When returning the env Hash, it may modify data to point to where
726  * body processing should begin.
728  * Raises HttpParserError if there are parsing errors.
729  */
730 static VALUE HttpParser_parse(VALUE self)
732   struct http_parser *hp = data_get(self);
733   VALUE data = hp->buf;
735   if (HP_FL_TEST(hp, TO_CLEAR)) {
736     http_parser_init(hp);
737     rb_funcall(hp->env, id_clear, 0);
738   }
740   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
741   if (hp->offset > MAX_HEADER_LEN)
742     parser_raise(e413, "HTTP header is too large");
744   if (hp->cs == http_parser_first_final ||
745       hp->cs == http_parser_en_ChunkedBody) {
746     advance_str(data, hp->offset + 1);
747     hp->offset = 0;
748     if (HP_FL_TEST(hp, INTRAILER))
749       HP_FL_SET(hp, REQEOF);
751     return hp->env;
752   }
754   if (hp->cs == http_parser_error)
755     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
757   return Qnil;
761  * Document-method: parse
762  * call-seq:
763  *    parser.add_parse(buffer) => env or nil
765  * adds the contents of +buffer+ to the internal buffer and attempts to
766  * continue parsing.  Returns the +env+ Hash on success or nil if more
767  * data is needed.
769  * Raises HttpParserError if there are parsing errors.
770  */
771 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
773   struct http_parser *hp = data_get(self);
775   Check_Type(buffer, T_STRING);
776   rb_str_buf_append(hp->buf, buffer);
778   return HttpParser_parse(self);
782  * Document-method: trailers
783  * call-seq:
784  *    parser.trailers(req, data) => req or nil
786  * This is an alias for HttpParser#headers
787  */
790  * Document-method: headers
791  */
792 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
794   struct http_parser *hp = data_get(self);
796   hp->env = env;
797   hp->buf = buf;
799   return HttpParser_parse(self);
802 static int chunked_eof(struct http_parser *hp)
804   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
808  * call-seq:
809  *    parser.body_eof? => true or false
811  * Detects if we're done filtering the body or not.  This can be used
812  * to detect when to stop calling HttpParser#filter_body.
813  */
814 static VALUE HttpParser_body_eof(VALUE self)
816   struct http_parser *hp = data_get(self);
818   if (HP_FL_TEST(hp, CHUNKED))
819     return chunked_eof(hp) ? Qtrue : Qfalse;
821   return hp->len.content == 0 ? Qtrue : Qfalse;
825  * call-seq:
826  *    parser.keepalive? => true or false
828  * This should be used to detect if a request can really handle
829  * keepalives and pipelining.  Currently, the rules are:
831  * 1. MUST be a GET or HEAD request
832  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
833  * 3. MUST NOT have "Connection: close" set
834  */
835 static VALUE HttpParser_keepalive(VALUE self)
837   struct http_parser *hp = data_get(self);
839   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
843  * call-seq:
844  *    parser.next? => true or false
846  * Exactly like HttpParser#keepalive?, except it will reset the internal
847  * parser state on next parse if it returns true.  It will also respect
848  * the maximum *keepalive_requests* value and return false if that is
849  * reached.
850  */
851 static VALUE HttpParser_next(VALUE self)
853   struct http_parser *hp = data_get(self);
855   if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
856     HP_FL_SET(hp, TO_CLEAR);
857     return Qtrue;
858   }
859   return Qfalse;
863  * call-seq:
864  *    parser.headers? => true or false
866  * This should be used to detect if a request has headers (and if
867  * the response will have headers as well).  HTTP/0.9 requests
868  * should return false, all subsequent HTTP versions will return true
869  */
870 static VALUE HttpParser_has_headers(VALUE self)
872   struct http_parser *hp = data_get(self);
874   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
877 static VALUE HttpParser_buf(VALUE self)
879   return data_get(self)->buf;
882 static VALUE HttpParser_env(VALUE self)
884   return data_get(self)->env;
888  * call-seq:
889  *    parser.filter_body(dst, src) => nil/src
891  * Takes a String of +src+, will modify data if dechunking is done.
892  * Returns +nil+ if there is more data left to process.  Returns
893  * +src+ if body processing is complete. When returning +src+,
894  * it may modify +src+ so the start of the string points to where
895  * the body ended so that trailer processing can begin.
897  * Raises HttpParserError if there are dechunking errors.
898  * Basically this is a glorified memcpy(3) that copies +src+
899  * into +buf+ while filtering it through the dechunker.
900  */
901 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
903   struct http_parser *hp = data_get(self);
904   char *srcptr;
905   long srclen;
907   srcptr = RSTRING_PTR(src);
908   srclen = RSTRING_LEN(src);
910   StringValue(dst);
912   if (HP_FL_TEST(hp, CHUNKED)) {
913     if (!chunked_eof(hp)) {
914       rb_str_modify(dst);
915       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
917       hp->s.dest_offset = 0;
918       hp->cont = dst;
919       hp->buf = src;
920       http_parser_execute(hp, srcptr, srclen);
921       if (hp->cs == http_parser_error)
922         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
924       assert(hp->s.dest_offset <= hp->offset &&
925              "destination buffer overflow");
926       advance_str(src, hp->offset);
927       rb_str_set_len(dst, hp->s.dest_offset);
929       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
930         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
931       } else {
932         src = Qnil;
933       }
934     }
935   } else {
936     /* no need to enter the Ragel machine for unchunked transfers */
937     assert(hp->len.content >= 0 && "negative Content-Length");
938     if (hp->len.content > 0) {
939       long nr = MIN(srclen, hp->len.content);
941       rb_str_modify(dst);
942       rb_str_resize(dst, nr);
943       /*
944        * using rb_str_replace() to avoid memcpy() doesn't help in
945        * most cases because a GC-aware programmer will pass an explicit
946        * buffer to env["rack.input"].read and reuse the buffer in a loop.
947        * This causes copy-on-write behavior to be triggered anyways
948        * when the +src+ buffer is modified (when reading off the socket).
949        */
950       hp->buf = src;
951       memcpy(RSTRING_PTR(dst), srcptr, nr);
952       hp->len.content -= nr;
953       if (hp->len.content == 0) {
954         HP_FL_SET(hp, REQEOF);
955         hp->cs = http_parser_first_final;
956       }
957       advance_str(src, nr);
958       src = Qnil;
959     }
960   }
961   hp->offset = 0; /* for trailer parsing */
962   return src;
965 #define SET_GLOBAL(var,str) do { \
966   var = find_common_field(str, sizeof(str) - 1); \
967   assert(!NIL_P(var) && "missed global field"); \
968 } while (0)
970 void Init_unicorn_http(void)
972   VALUE mUnicorn, cHttpParser;
974   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
975   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
976   eHttpParserError =
977          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
978   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
979                                eHttpParserError);
980   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
981                                eHttpParserError);
983   init_globals();
984   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
985   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
986   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
987   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
988   rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0);
989   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
990   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
991   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
992   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
993   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
994   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
995   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
996   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
997   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
998   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
999   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
1000   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
1002   /*
1003    * The maximum size a single chunk when using chunked transfer encoding.
1004    * This is only a theoretical maximum used to detect errors in clients,
1005    * it is highly unlikely to encounter clients that send more than
1006    * several kilobytes at once.
1007    */
1008   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
1010   /*
1011    * The maximum size of the body as specified by Content-Length.
1012    * This is only a theoretical maximum, the actual limit is subject
1013    * to the limits of the file system used for +Dir.tmpdir+.
1014    */
1015   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
1017   /* default value for keepalive_requests */
1018   rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
1019                   ULONG2NUM(keepalive_requests));
1021   rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
1022   rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
1023   rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
1024   rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
1025   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
1027   init_common_fields();
1028   SET_GLOBAL(g_http_host, "HOST");
1029   SET_GLOBAL(g_http_trailer, "TRAILER");
1030   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
1031   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1032   SET_GLOBAL(g_http_connection, "CONNECTION");
1033   id_clear = rb_intern("clear");
1034   id_set_backtrace = rb_intern("set_backtrace");
1035   id_response_start_sent = rb_intern("@response_start_sent");
1036   init_unicorn_httpdate();
1038 #undef SET_GLOBAL