KNOWN_ISSUES: add link to FreeBSD jail workaround notes
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob6049d9cff91dd773e1885cc97a65de5ad74bc8fc
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 static size_t MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
87 /* this is only intended for use with Rainbows! */
88 static VALUE set_maxhdrlen(VALUE self, VALUE len)
90   return SIZET2NUM(MAX_HEADER_LEN = NUM2SIZET(len));
93 /* keep this small for Rainbows! since every client has one */
94 struct http_parser {
95   int cs; /* Ragel internal state */
96   unsigned int flags;
97   unsigned long nr_requests;
98   size_t mark;
99   size_t offset;
100   union { /* these 2 fields don't nest */
101     size_t field;
102     size_t query;
103   } start;
104   union {
105     size_t field_len; /* only used during header processing */
106     size_t dest_offset; /* only used during body processing */
107   } s;
108   VALUE buf;
109   VALUE env;
110   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
111   union {
112     off_t content;
113     off_t chunk;
114   } len;
117 static ID id_clear, id_set_backtrace;
119 static void finalize_header(struct http_parser *hp);
121 static void parser_raise(VALUE klass, const char *msg)
123   VALUE exc = rb_exc_new2(klass, msg);
124   VALUE bt = rb_ary_new();
126         rb_funcall(exc, id_set_backtrace, 1, bt);
127         rb_exc_raise(exc);
130 #define REMAINING (unsigned long)(pe - p)
131 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
132 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
133 #define PTR_TO(F) (buffer + hp->F)
134 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
135 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
137 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
138 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
139 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
140 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
142 static int is_lws(char c)
144   return (c == ' ' || c == '\t');
147 static VALUE stripped_str_new(const char *str, long len)
149   long end;
151   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
153   return rb_str_new(str, end + 1);
157  * handles values of the "Connection:" header, keepalive is implied
158  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
159  * Additionally, we require GET/HEAD requests to support keepalive.
160  */
161 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
163   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
164     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
165     HP_FL_SET(hp, KAVERSION);
166   } else if (STR_CSTR_CASE_EQ(val, "close")) {
167     /*
168      * it doesn't matter what HTTP version or request method we have,
169      * if a client says "Connection: close", we disable keepalive
170      */
171     HP_FL_UNSET(hp, KAVERSION);
172   } else {
173     /*
174      * client could've sent anything, ignore it for now.  Maybe
175      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
176      * Raising an exception might be too mean...
177      */
178   }
181 static void
182 request_method(struct http_parser *hp, const char *ptr, size_t len)
184   VALUE v = rb_str_new(ptr, len);
186   rb_hash_aset(hp->env, g_request_method, v);
189 static void
190 http_version(struct http_parser *hp, const char *ptr, size_t len)
192   VALUE v;
194   HP_FL_SET(hp, HASHEADER);
196   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
197     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
198     HP_FL_SET(hp, KAVERSION);
199     v = g_http_11;
200   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
201     v = g_http_10;
202   } else {
203     v = rb_str_new(ptr, len);
204   }
205   rb_hash_aset(hp->env, g_server_protocol, v);
206   rb_hash_aset(hp->env, g_http_version, v);
209 static inline void hp_invalid_if_trailer(struct http_parser *hp)
211   if (HP_FL_TEST(hp, INTRAILER))
212     parser_raise(eHttpParserError, "invalid Trailer");
215 static void write_cont_value(struct http_parser *hp,
216                              char *buffer, const char *p)
218   char *vptr;
219   long end;
220   long len = LEN(mark, p);
221   long cont_len;
223   if (hp->cont == Qfalse)
224      parser_raise(eHttpParserError, "invalid continuation line");
225   if (NIL_P(hp->cont))
226      return; /* we're ignoring this header (probably Host:) */
228   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
229   assert(hp->mark > 0 && "impossible continuation line offset");
231   if (len == 0)
232     return;
234   cont_len = RSTRING_LEN(hp->cont);
235   if (cont_len > 0) {
236     --hp->mark;
237     len = LEN(mark, p);
238   }
239   vptr = PTR_TO(mark);
241   /* normalize tab to space */
242   if (cont_len > 0) {
243     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
244     *vptr = ' ';
245   }
247   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
248   rb_str_buf_cat(hp->cont, vptr, end + 1);
251 static void write_value(struct http_parser *hp,
252                         const char *buffer, const char *p)
254   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
255   VALUE v;
256   VALUE e;
258   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
259   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
260   if (NIL_P(f)) {
261     const char *field = PTR_TO(start.field);
262     size_t flen = hp->s.field_len;
264     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
266     /*
267      * ignore "Version" headers since they conflict with the HTTP_VERSION
268      * rack env variable.
269      */
270     if (CONST_MEM_EQ("VERSION", field, flen)) {
271       hp->cont = Qnil;
272       return;
273     }
274     f = uncommon_field(field, flen);
275   } else if (f == g_http_connection) {
276     hp_keepalive_connection(hp, v);
277   } else if (f == g_content_length) {
278     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
279     if (hp->len.content < 0)
280       parser_raise(eHttpParserError, "invalid Content-Length");
281     if (hp->len.content != 0)
282       HP_FL_SET(hp, HASBODY);
283     hp_invalid_if_trailer(hp);
284   } else if (f == g_http_transfer_encoding) {
285     if (STR_CSTR_CASE_EQ(v, "chunked")) {
286       HP_FL_SET(hp, CHUNKED);
287       HP_FL_SET(hp, HASBODY);
288     }
289     hp_invalid_if_trailer(hp);
290   } else if (f == g_http_trailer) {
291     HP_FL_SET(hp, HASTRAILER);
292     hp_invalid_if_trailer(hp);
293   } else {
294     assert(TYPE(f) == T_STRING && "memoized object is not a string");
295     assert_frozen(f);
296   }
298   e = rb_hash_aref(hp->env, f);
299   if (NIL_P(e)) {
300     hp->cont = rb_hash_aset(hp->env, f, v);
301   } else if (f == g_http_host) {
302     /*
303      * ignored, absolute URLs in REQUEST_URI take precedence over
304      * the Host: header (ref: rfc 2616, section 5.2.1)
305      */
306      hp->cont = Qnil;
307   } else {
308     rb_str_buf_cat(e, ",", 1);
309     hp->cont = rb_str_buf_append(e, v);
310   }
313 /** Machine **/
316   machine http_parser;
318   action mark {MARK(mark, fpc); }
320   action start_field { MARK(start.field, fpc); }
321   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
322   action downcase_char { downcase_char(deconst(fpc)); }
323   action write_field { hp->s.field_len = LEN(start.field, fpc); }
324   action start_value { MARK(mark, fpc); }
325   action write_value { write_value(hp, buffer, fpc); }
326   action write_cont_value { write_cont_value(hp, buffer, fpc); }
327   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
328   action scheme {
329     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
330   }
331   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
332   action request_uri {
333     VALUE str;
335     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
336     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
337     /*
338      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
339      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
340      */
341     if (STR_CSTR_EQ(str, "*")) {
342       str = rb_str_new(NULL, 0);
343       rb_hash_aset(hp->env, g_path_info, str);
344       rb_hash_aset(hp->env, g_request_path, str);
345     }
346   }
347   action fragment {
348     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
349     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
350   }
351   action start_query {MARK(start.query, fpc); }
352   action query_string {
353     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
354     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
355   }
356   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
357   action request_path {
358     VALUE val;
360     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
361     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
363     /* rack says PATH_INFO must start with "/" or be empty */
364     if (!STR_CSTR_EQ(val, "*"))
365       rb_hash_aset(hp->env, g_path_info, val);
366   }
367   action add_to_chunk_size {
368     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
369     if (hp->len.chunk < 0)
370       parser_raise(eHttpParserError, "invalid chunk size");
371   }
372   action header_done {
373     finalize_header(hp);
375     cs = http_parser_first_final;
376     if (HP_FL_TEST(hp, HASBODY)) {
377       HP_FL_SET(hp, INBODY);
378       if (HP_FL_TEST(hp, CHUNKED))
379         cs = http_parser_en_ChunkedBody;
380     } else {
381       HP_FL_SET(hp, REQEOF);
382       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
383     }
384     /*
385      * go back to Ruby so we can call the Rack application, we'll reenter
386      * the parser iff the body needs to be processed.
387      */
388     goto post_exec;
389   }
391   action end_trailers {
392     cs = http_parser_first_final;
393     goto post_exec;
394   }
396   action end_chunked_body {
397     HP_FL_SET(hp, INTRAILER);
398     cs = http_parser_en_Trailers;
399     ++p;
400     assert(p <= pe && "buffer overflow after chunked body");
401     goto post_exec;
402   }
404   action skip_chunk_data {
405   skip_chunk_data_hack: {
406     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
407     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
408     hp->s.dest_offset += nr;
409     hp->len.chunk -= nr;
410     p += nr;
411     assert(hp->len.chunk >= 0 && "negative chunk length");
412     if ((size_t)hp->len.chunk > REMAINING) {
413       HP_FL_SET(hp, INCHUNK);
414       goto post_exec;
415     } else {
416       fhold;
417       fgoto chunk_end;
418     }
419   }}
421   include unicorn_http_common "unicorn_http_common.rl";
424 /** Data **/
425 %% write data;
427 static void http_parser_init(struct http_parser *hp)
429   int cs = 0;
430   hp->flags = 0;
431   hp->mark = 0;
432   hp->offset = 0;
433   hp->start.field = 0;
434   hp->s.field_len = 0;
435   hp->len.content = 0;
436   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
437   %% write init;
438   hp->cs = cs;
441 /** exec **/
442 static void
443 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
445   const char *p, *pe;
446   int cs = hp->cs;
447   size_t off = hp->offset;
449   if (cs == http_parser_first_final)
450     return;
452   assert(off <= len && "offset past end of buffer");
454   p = buffer+off;
455   pe = buffer+len;
457   assert((void *)(pe - p) == (void *)(len - off) &&
458          "pointers aren't same distance");
460   if (HP_FL_TEST(hp, INCHUNK)) {
461     HP_FL_UNSET(hp, INCHUNK);
462     goto skip_chunk_data_hack;
463   }
464   %% write exec;
465 post_exec: /* "_out:" also goes here */
466   if (hp->cs != http_parser_error)
467     hp->cs = cs;
468   hp->offset = p - buffer;
470   assert(p <= pe && "buffer overflow after parsing execute");
471   assert(hp->offset <= len && "offset longer than length");
474 static struct http_parser *data_get(VALUE self)
476   struct http_parser *hp;
478   Data_Get_Struct(self, struct http_parser, hp);
479   assert(hp && "failed to extract http_parser struct");
480   return hp;
484  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
485  * this resembles the Rack::Request#scheme method as of rack commit
486  * 35bb5ba6746b5d346de9202c004cc926039650c7
487  */
488 static void set_url_scheme(VALUE env, VALUE *server_port)
490   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
492   if (NIL_P(scheme)) {
493     if (trust_x_forward == Qfalse) {
494       scheme = g_http;
495     } else {
496       scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
497       if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
498         *server_port = g_port_443;
499         scheme = g_https;
500       } else {
501         scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
502         if (NIL_P(scheme)) {
503           scheme = g_http;
504         } else {
505           long len = RSTRING_LEN(scheme);
506           if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
507             if (len != 5)
508               scheme = g_https;
509             *server_port = g_port_443;
510           } else {
511             scheme = g_http;
512           }
513         }
514       }
515     }
516     rb_hash_aset(env, g_rack_url_scheme, scheme);
517   } else if (STR_CSTR_EQ(scheme, "https")) {
518     *server_port = g_port_443;
519   } else {
520     assert(*server_port == g_port_80 && "server_port not set");
521   }
525  * Parse and set the SERVER_NAME and SERVER_PORT variables
526  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
527  * anybody who needs them is using an unsupported configuration and/or
528  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
529  * fine.
530  */
531 static void set_server_vars(VALUE env, VALUE *server_port)
533   VALUE server_name = g_localhost;
534   VALUE host = rb_hash_aref(env, g_http_host);
536   if (!NIL_P(host)) {
537     char *host_ptr = RSTRING_PTR(host);
538     long host_len = RSTRING_LEN(host);
539     char *colon;
541     if (*host_ptr == '[') { /* ipv6 address format */
542       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
544       if (rbracket)
545         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
546       else
547         colon = memchr(host_ptr + 1, ':', host_len - 1);
548     } else {
549       colon = memchr(host_ptr, ':', host_len);
550     }
552     if (colon) {
553       long port_start = colon - host_ptr + 1;
555       server_name = rb_str_substr(host, 0, colon - host_ptr);
556       if ((host_len - port_start) > 0)
557         *server_port = rb_str_substr(host, port_start, host_len);
558     } else {
559       server_name = host;
560     }
561   }
562   rb_hash_aset(env, g_server_name, server_name);
563   rb_hash_aset(env, g_server_port, *server_port);
566 static void finalize_header(struct http_parser *hp)
568   VALUE server_port = g_port_80;
570   set_url_scheme(hp->env, &server_port);
571   set_server_vars(hp->env, &server_port);
573   if (!HP_FL_TEST(hp, HASHEADER))
574     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
576   /* rack requires QUERY_STRING */
577   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
578     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
581 static void hp_mark(void *ptr)
583   struct http_parser *hp = ptr;
585   rb_gc_mark(hp->buf);
586   rb_gc_mark(hp->env);
587   rb_gc_mark(hp->cont);
590 static VALUE HttpParser_alloc(VALUE klass)
592   struct http_parser *hp;
593   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
598  * call-seq:
599  *    parser.new => parser
601  * Creates a new parser.
602  */
603 static VALUE HttpParser_init(VALUE self)
605   struct http_parser *hp = data_get(self);
607   http_parser_init(hp);
608   hp->buf = rb_str_new(NULL, 0);
609   hp->env = rb_hash_new();
610   hp->nr_requests = keepalive_requests;
612   return self;
616  * call-seq:
617  *    parser.clear => parser
619  * Resets the parser to it's initial state so that you can reuse it
620  * rather than making new ones.
621  */
622 static VALUE HttpParser_clear(VALUE self)
624   struct http_parser *hp = data_get(self);
626   http_parser_init(hp);
627   rb_funcall(hp->env, id_clear, 0);
629   return self;
633  * call-seq:
634  *    parser.dechunk! => parser
636  * Resets the parser to a state suitable for dechunking response bodies
638  */
639 static VALUE HttpParser_dechunk_bang(VALUE self)
641   struct http_parser *hp = data_get(self);
643   http_parser_init(hp);
645   /*
646    * we don't care about trailers in dechunk-only mode,
647    * but if we did we'd set UH_FL_HASTRAILER and clear hp->env
648    */
649   if (0) {
650     rb_funcall(hp->env, id_clear, 0);
651     hp->flags = UH_FL_HASTRAILER;
652   }
654   hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED;
655   hp->cs = http_parser_en_ChunkedBody;
657   return self;
661  * call-seq:
662  *    parser.reset => nil
664  * Resets the parser to it's initial state so that you can reuse it
665  * rather than making new ones.
667  * This method is deprecated and to be removed in Unicorn 4.x
668  */
669 static VALUE HttpParser_reset(VALUE self)
671   static int warned;
673   if (!warned) {
674     rb_warn("Unicorn::HttpParser#reset is deprecated; "
675             "use Unicorn::HttpParser#clear instead");
676   }
677   HttpParser_clear(self);
678   return Qnil;
681 static void advance_str(VALUE str, off_t nr)
683   long len = RSTRING_LEN(str);
685   if (len == 0)
686     return;
688   rb_str_modify(str);
690   assert(nr <= len && "trying to advance past end of buffer");
691   len -= nr;
692   if (len > 0) /* unlikely, len is usually 0 */
693     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
694   rb_str_set_len(str, len);
698  * call-seq:
699  *   parser.content_length => nil or Integer
701  * Returns the number of bytes left to run through HttpParser#filter_body.
702  * This will initially be the value of the "Content-Length" HTTP header
703  * after header parsing is complete and will decrease in value as
704  * HttpParser#filter_body is called for each chunk.  This should return
705  * zero for requests with no body.
707  * This will return nil on "Transfer-Encoding: chunked" requests.
708  */
709 static VALUE HttpParser_content_length(VALUE self)
711   struct http_parser *hp = data_get(self);
713   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
717  * Document-method: parse
718  * call-seq:
719  *    parser.parse => env or nil
721  * Takes a Hash and a String of data, parses the String of data filling
722  * in the Hash returning the Hash if parsing is finished, nil otherwise
723  * When returning the env Hash, it may modify data to point to where
724  * body processing should begin.
726  * Raises HttpParserError if there are parsing errors.
727  */
728 static VALUE HttpParser_parse(VALUE self)
730   struct http_parser *hp = data_get(self);
731   VALUE data = hp->buf;
733   if (HP_FL_TEST(hp, TO_CLEAR)) {
734     http_parser_init(hp);
735     rb_funcall(hp->env, id_clear, 0);
736   }
738   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
739   if (hp->offset > MAX_HEADER_LEN)
740     parser_raise(e413, "HTTP header is too large");
742   if (hp->cs == http_parser_first_final ||
743       hp->cs == http_parser_en_ChunkedBody) {
744     advance_str(data, hp->offset + 1);
745     hp->offset = 0;
746     if (HP_FL_TEST(hp, INTRAILER))
747       HP_FL_SET(hp, REQEOF);
749     return hp->env;
750   }
752   if (hp->cs == http_parser_error)
753     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
755   return Qnil;
759  * Document-method: parse
760  * call-seq:
761  *    parser.add_parse(buffer) => env or nil
763  * adds the contents of +buffer+ to the internal buffer and attempts to
764  * continue parsing.  Returns the +env+ Hash on success or nil if more
765  * data is needed.
767  * Raises HttpParserError if there are parsing errors.
768  */
769 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
771   struct http_parser *hp = data_get(self);
773   Check_Type(buffer, T_STRING);
774   rb_str_buf_append(hp->buf, buffer);
776   return HttpParser_parse(self);
780  * Document-method: trailers
781  * call-seq:
782  *    parser.trailers(req, data) => req or nil
784  * This is an alias for HttpParser#headers
785  */
788  * Document-method: headers
789  */
790 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
792   struct http_parser *hp = data_get(self);
794   hp->env = env;
795   hp->buf = buf;
797   return HttpParser_parse(self);
800 static int chunked_eof(struct http_parser *hp)
802   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
806  * call-seq:
807  *    parser.body_eof? => true or false
809  * Detects if we're done filtering the body or not.  This can be used
810  * to detect when to stop calling HttpParser#filter_body.
811  */
812 static VALUE HttpParser_body_eof(VALUE self)
814   struct http_parser *hp = data_get(self);
816   if (HP_FL_TEST(hp, CHUNKED))
817     return chunked_eof(hp) ? Qtrue : Qfalse;
819   return hp->len.content == 0 ? Qtrue : Qfalse;
823  * call-seq:
824  *    parser.keepalive? => true or false
826  * This should be used to detect if a request can really handle
827  * keepalives and pipelining.  Currently, the rules are:
829  * 1. MUST be a GET or HEAD request
830  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
831  * 3. MUST NOT have "Connection: close" set
832  */
833 static VALUE HttpParser_keepalive(VALUE self)
835   struct http_parser *hp = data_get(self);
837   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
841  * call-seq:
842  *    parser.next? => true or false
844  * Exactly like HttpParser#keepalive?, except it will reset the internal
845  * parser state on next parse if it returns true.  It will also respect
846  * the maximum *keepalive_requests* value and return false if that is
847  * reached.
848  */
849 static VALUE HttpParser_next(VALUE self)
851   struct http_parser *hp = data_get(self);
853   if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
854     HP_FL_SET(hp, TO_CLEAR);
855     return Qtrue;
856   }
857   return Qfalse;
861  * call-seq:
862  *    parser.headers? => true or false
864  * This should be used to detect if a request has headers (and if
865  * the response will have headers as well).  HTTP/0.9 requests
866  * should return false, all subsequent HTTP versions will return true
867  */
868 static VALUE HttpParser_has_headers(VALUE self)
870   struct http_parser *hp = data_get(self);
872   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
875 static VALUE HttpParser_buf(VALUE self)
877   return data_get(self)->buf;
880 static VALUE HttpParser_env(VALUE self)
882   return data_get(self)->env;
886  * call-seq:
887  *    parser.filter_body(dst, src) => nil/src
889  * Takes a String of +src+, will modify data if dechunking is done.
890  * Returns +nil+ if there is more data left to process.  Returns
891  * +src+ if body processing is complete. When returning +src+,
892  * it may modify +src+ so the start of the string points to where
893  * the body ended so that trailer processing can begin.
895  * Raises HttpParserError if there are dechunking errors.
896  * Basically this is a glorified memcpy(3) that copies +src+
897  * into +buf+ while filtering it through the dechunker.
898  */
899 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
901   struct http_parser *hp = data_get(self);
902   char *srcptr;
903   long srclen;
905   srcptr = RSTRING_PTR(src);
906   srclen = RSTRING_LEN(src);
908   StringValue(dst);
910   if (HP_FL_TEST(hp, CHUNKED)) {
911     if (!chunked_eof(hp)) {
912       rb_str_modify(dst);
913       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
915       hp->s.dest_offset = 0;
916       hp->cont = dst;
917       hp->buf = src;
918       http_parser_execute(hp, srcptr, srclen);
919       if (hp->cs == http_parser_error)
920         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
922       assert(hp->s.dest_offset <= hp->offset &&
923              "destination buffer overflow");
924       advance_str(src, hp->offset);
925       rb_str_set_len(dst, hp->s.dest_offset);
927       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
928         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
929       } else {
930         src = Qnil;
931       }
932     }
933   } else {
934     /* no need to enter the Ragel machine for unchunked transfers */
935     assert(hp->len.content >= 0 && "negative Content-Length");
936     if (hp->len.content > 0) {
937       long nr = MIN(srclen, hp->len.content);
939       rb_str_modify(dst);
940       rb_str_resize(dst, nr);
941       /*
942        * using rb_str_replace() to avoid memcpy() doesn't help in
943        * most cases because a GC-aware programmer will pass an explicit
944        * buffer to env["rack.input"].read and reuse the buffer in a loop.
945        * This causes copy-on-write behavior to be triggered anyways
946        * when the +src+ buffer is modified (when reading off the socket).
947        */
948       hp->buf = src;
949       memcpy(RSTRING_PTR(dst), srcptr, nr);
950       hp->len.content -= nr;
951       if (hp->len.content == 0) {
952         HP_FL_SET(hp, REQEOF);
953         hp->cs = http_parser_first_final;
954       }
955       advance_str(src, nr);
956       src = Qnil;
957     }
958   }
959   hp->offset = 0; /* for trailer parsing */
960   return src;
963 #define SET_GLOBAL(var,str) do { \
964   var = find_common_field(str, sizeof(str) - 1); \
965   assert(!NIL_P(var) && "missed global field"); \
966 } while (0)
968 void Init_unicorn_http(void)
970   VALUE mUnicorn, cHttpParser;
972   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
973   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
974   eHttpParserError =
975          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
976   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
977                                eHttpParserError);
978   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
979                                eHttpParserError);
981   init_globals();
982   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
983   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
984   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
985   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
986   rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0);
987   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
988   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
989   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
990   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
991   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
992   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
993   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
994   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
995   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
996   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
997   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
998   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
1000   /*
1001    * The maximum size a single chunk when using chunked transfer encoding.
1002    * This is only a theoretical maximum used to detect errors in clients,
1003    * it is highly unlikely to encounter clients that send more than
1004    * several kilobytes at once.
1005    */
1006   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
1008   /*
1009    * The maximum size of the body as specified by Content-Length.
1010    * This is only a theoretical maximum, the actual limit is subject
1011    * to the limits of the file system used for +Dir.tmpdir+.
1012    */
1013   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
1015   /* default value for keepalive_requests */
1016   rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
1017                   ULONG2NUM(keepalive_requests));
1019   rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
1020   rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
1021   rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
1022   rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
1023   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
1025   init_common_fields();
1026   SET_GLOBAL(g_http_host, "HOST");
1027   SET_GLOBAL(g_http_trailer, "TRAILER");
1028   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
1029   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1030   SET_GLOBAL(g_http_connection, "CONNECTION");
1031   id_clear = rb_intern("clear");
1032   id_set_backtrace = rb_intern("set_backtrace");
1033   init_unicorn_httpdate();
1035 #undef SET_GLOBAL