add GPLv3 option to the license
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob96dcf835b2e23a33282a2e1057d0154eaaab3794
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;
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);
630   return self;
634  * call-seq:
635  *    parser.dechunk! => parser
637  * Resets the parser to a state suitable for dechunking response bodies
639  */
640 static VALUE HttpParser_dechunk_bang(VALUE self)
642   struct http_parser *hp = data_get(self);
644   http_parser_init(hp);
646   /*
647    * we don't care about trailers in dechunk-only mode,
648    * but if we did we'd set UH_FL_HASTRAILER and clear hp->env
649    */
650   if (0) {
651     rb_funcall(hp->env, id_clear, 0);
652     hp->flags = UH_FL_HASTRAILER;
653   }
655   hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED;
656   hp->cs = http_parser_en_ChunkedBody;
658   return self;
662  * call-seq:
663  *    parser.reset => nil
665  * Resets the parser to it's initial state so that you can reuse it
666  * rather than making new ones.
668  * This method is deprecated and to be removed in Unicorn 4.x
669  */
670 static VALUE HttpParser_reset(VALUE self)
672   static int warned;
674   if (!warned) {
675     rb_warn("Unicorn::HttpParser#reset is deprecated; "
676             "use Unicorn::HttpParser#clear instead");
677   }
678   HttpParser_clear(self);
679   return Qnil;
682 static void advance_str(VALUE str, off_t nr)
684   long len = RSTRING_LEN(str);
686   if (len == 0)
687     return;
689   rb_str_modify(str);
691   assert(nr <= len && "trying to advance past end of buffer");
692   len -= nr;
693   if (len > 0) /* unlikely, len is usually 0 */
694     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
695   rb_str_set_len(str, len);
699  * call-seq:
700  *   parser.content_length => nil or Integer
702  * Returns the number of bytes left to run through HttpParser#filter_body.
703  * This will initially be the value of the "Content-Length" HTTP header
704  * after header parsing is complete and will decrease in value as
705  * HttpParser#filter_body is called for each chunk.  This should return
706  * zero for requests with no body.
708  * This will return nil on "Transfer-Encoding: chunked" requests.
709  */
710 static VALUE HttpParser_content_length(VALUE self)
712   struct http_parser *hp = data_get(self);
714   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
718  * Document-method: parse
719  * call-seq:
720  *    parser.parse => env or nil
722  * Takes a Hash and a String of data, parses the String of data filling
723  * in the Hash returning the Hash if parsing is finished, nil otherwise
724  * When returning the env Hash, it may modify data to point to where
725  * body processing should begin.
727  * Raises HttpParserError if there are parsing errors.
728  */
729 static VALUE HttpParser_parse(VALUE self)
731   struct http_parser *hp = data_get(self);
732   VALUE data = hp->buf;
734   if (HP_FL_TEST(hp, TO_CLEAR)) {
735     http_parser_init(hp);
736     rb_funcall(hp->env, id_clear, 0);
737   }
739   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
740   if (hp->offset > MAX_HEADER_LEN)
741     parser_raise(e413, "HTTP header is too large");
743   if (hp->cs == http_parser_first_final ||
744       hp->cs == http_parser_en_ChunkedBody) {
745     advance_str(data, hp->offset + 1);
746     hp->offset = 0;
747     if (HP_FL_TEST(hp, INTRAILER))
748       HP_FL_SET(hp, REQEOF);
750     return hp->env;
751   }
753   if (hp->cs == http_parser_error)
754     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
756   return Qnil;
760  * Document-method: parse
761  * call-seq:
762  *    parser.add_parse(buffer) => env or nil
764  * adds the contents of +buffer+ to the internal buffer and attempts to
765  * continue parsing.  Returns the +env+ Hash on success or nil if more
766  * data is needed.
768  * Raises HttpParserError if there are parsing errors.
769  */
770 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
772   struct http_parser *hp = data_get(self);
774   Check_Type(buffer, T_STRING);
775   rb_str_buf_append(hp->buf, buffer);
777   return HttpParser_parse(self);
781  * Document-method: trailers
782  * call-seq:
783  *    parser.trailers(req, data) => req or nil
785  * This is an alias for HttpParser#headers
786  */
789  * Document-method: headers
790  */
791 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
793   struct http_parser *hp = data_get(self);
795   hp->env = env;
796   hp->buf = buf;
798   return HttpParser_parse(self);
801 static int chunked_eof(struct http_parser *hp)
803   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
807  * call-seq:
808  *    parser.body_eof? => true or false
810  * Detects if we're done filtering the body or not.  This can be used
811  * to detect when to stop calling HttpParser#filter_body.
812  */
813 static VALUE HttpParser_body_eof(VALUE self)
815   struct http_parser *hp = data_get(self);
817   if (HP_FL_TEST(hp, CHUNKED))
818     return chunked_eof(hp) ? Qtrue : Qfalse;
820   return hp->len.content == 0 ? Qtrue : Qfalse;
824  * call-seq:
825  *    parser.keepalive? => true or false
827  * This should be used to detect if a request can really handle
828  * keepalives and pipelining.  Currently, the rules are:
830  * 1. MUST be a GET or HEAD request
831  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
832  * 3. MUST NOT have "Connection: close" set
833  */
834 static VALUE HttpParser_keepalive(VALUE self)
836   struct http_parser *hp = data_get(self);
838   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
842  * call-seq:
843  *    parser.next? => true or false
845  * Exactly like HttpParser#keepalive?, except it will reset the internal
846  * parser state on next parse if it returns true.  It will also respect
847  * the maximum *keepalive_requests* value and return false if that is
848  * reached.
849  */
850 static VALUE HttpParser_next(VALUE self)
852   struct http_parser *hp = data_get(self);
854   if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
855     HP_FL_SET(hp, TO_CLEAR);
856     return Qtrue;
857   }
858   return Qfalse;
862  * call-seq:
863  *    parser.headers? => true or false
865  * This should be used to detect if a request has headers (and if
866  * the response will have headers as well).  HTTP/0.9 requests
867  * should return false, all subsequent HTTP versions will return true
868  */
869 static VALUE HttpParser_has_headers(VALUE self)
871   struct http_parser *hp = data_get(self);
873   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
876 static VALUE HttpParser_buf(VALUE self)
878   return data_get(self)->buf;
881 static VALUE HttpParser_env(VALUE self)
883   return data_get(self)->env;
887  * call-seq:
888  *    parser.filter_body(dst, src) => nil/src
890  * Takes a String of +src+, will modify data if dechunking is done.
891  * Returns +nil+ if there is more data left to process.  Returns
892  * +src+ if body processing is complete. When returning +src+,
893  * it may modify +src+ so the start of the string points to where
894  * the body ended so that trailer processing can begin.
896  * Raises HttpParserError if there are dechunking errors.
897  * Basically this is a glorified memcpy(3) that copies +src+
898  * into +buf+ while filtering it through the dechunker.
899  */
900 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
902   struct http_parser *hp = data_get(self);
903   char *srcptr;
904   long srclen;
906   srcptr = RSTRING_PTR(src);
907   srclen = RSTRING_LEN(src);
909   StringValue(dst);
911   if (HP_FL_TEST(hp, CHUNKED)) {
912     if (!chunked_eof(hp)) {
913       rb_str_modify(dst);
914       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
916       hp->s.dest_offset = 0;
917       hp->cont = dst;
918       hp->buf = src;
919       http_parser_execute(hp, srcptr, srclen);
920       if (hp->cs == http_parser_error)
921         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
923       assert(hp->s.dest_offset <= hp->offset &&
924              "destination buffer overflow");
925       advance_str(src, hp->offset);
926       rb_str_set_len(dst, hp->s.dest_offset);
928       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
929         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
930       } else {
931         src = Qnil;
932       }
933     }
934   } else {
935     /* no need to enter the Ragel machine for unchunked transfers */
936     assert(hp->len.content >= 0 && "negative Content-Length");
937     if (hp->len.content > 0) {
938       long nr = MIN(srclen, hp->len.content);
940       rb_str_modify(dst);
941       rb_str_resize(dst, nr);
942       /*
943        * using rb_str_replace() to avoid memcpy() doesn't help in
944        * most cases because a GC-aware programmer will pass an explicit
945        * buffer to env["rack.input"].read and reuse the buffer in a loop.
946        * This causes copy-on-write behavior to be triggered anyways
947        * when the +src+ buffer is modified (when reading off the socket).
948        */
949       hp->buf = src;
950       memcpy(RSTRING_PTR(dst), srcptr, nr);
951       hp->len.content -= nr;
952       if (hp->len.content == 0) {
953         HP_FL_SET(hp, REQEOF);
954         hp->cs = http_parser_first_final;
955       }
956       advance_str(src, nr);
957       src = Qnil;
958     }
959   }
960   hp->offset = 0; /* for trailer parsing */
961   return src;
964 #define SET_GLOBAL(var,str) do { \
965   var = find_common_field(str, sizeof(str) - 1); \
966   assert(!NIL_P(var) && "missed global field"); \
967 } while (0)
969 void Init_unicorn_http(void)
971   VALUE mUnicorn, cHttpParser;
973   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
974   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
975   eHttpParserError =
976          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
977   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
978                                eHttpParserError);
979   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
980                                eHttpParserError);
982   init_globals();
983   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
984   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
985   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
986   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
987   rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0);
988   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
989   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
990   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
991   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
992   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
993   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
994   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
995   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
996   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
997   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
998   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
999   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
1001   /*
1002    * The maximum size a single chunk when using chunked transfer encoding.
1003    * This is only a theoretical maximum used to detect errors in clients,
1004    * it is highly unlikely to encounter clients that send more than
1005    * several kilobytes at once.
1006    */
1007   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
1009   /*
1010    * The maximum size of the body as specified by Content-Length.
1011    * This is only a theoretical maximum, the actual limit is subject
1012    * to the limits of the file system used for +Dir.tmpdir+.
1013    */
1014   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
1016   /* default value for keepalive_requests */
1017   rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
1018                   ULONG2NUM(keepalive_requests));
1020   rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
1021   rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
1022   rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
1023   rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
1024   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
1026   init_common_fields();
1027   SET_GLOBAL(g_http_host, "HOST");
1028   SET_GLOBAL(g_http_trailer, "TRAILER");
1029   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
1030   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1031   SET_GLOBAL(g_http_connection, "CONNECTION");
1032   id_clear = rb_intern("clear");
1033   id_set_backtrace = rb_intern("set_backtrace");
1034   init_unicorn_httpdate();
1036 #undef SET_GLOBAL