return 414 for URI length violations
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob741f8eea48b25946b24fa93d95e767d5f4df6642
1 /**
2  * Copyright (c) 2009 Eric Wong (all bugs are Eric's fault)
3  * Copyright (c) 2005 Zed A. Shaw
4  * You can redistribute it and/or modify it under the same terms as Ruby.
5  */
6 #include "ruby.h"
7 #include "ext_help.h"
8 #include <assert.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include "common_field_optimization.h"
12 #include "global_variables.h"
13 #include "c_util.h"
15 void init_unicorn_httpdate(void);
17 #define UH_FL_CHUNKED  0x1
18 #define UH_FL_HASBODY  0x2
19 #define UH_FL_INBODY   0x4
20 #define UH_FL_HASTRAILER 0x8
21 #define UH_FL_INTRAILER 0x10
22 #define UH_FL_INCHUNK  0x20
23 #define UH_FL_REQEOF 0x40
24 #define UH_FL_KAVERSION 0x80
25 #define UH_FL_HASHEADER 0x100
26 #define UH_FL_TO_CLEAR 0x200
28 /* all of these flags need to be set for keepalive to be supported */
29 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
32  * whether or not to trust X-Forwarded-Proto and X-Forwarded-SSL when
33  * setting rack.url_scheme
34  */
35 static VALUE trust_x_forward = Qtrue;
37 static unsigned long keepalive_requests = 100; /* same as nginx */
40  * Returns the maximum number of keepalive requests a client may make
41  * before the parser refuses to continue.
42  */
43 static VALUE ka_req(VALUE self)
45   return ULONG2NUM(keepalive_requests);
49  * Sets the maximum number of keepalive requests a client may make.
50  * A special value of +nil+ causes this to be the maximum value
51  * possible (this is architecture-dependent).
52  */
53 static VALUE set_ka_req(VALUE self, VALUE val)
55   keepalive_requests = NIL_P(val) ? ULONG_MAX : NUM2ULONG(val);
57   return ka_req(self);
61  * Sets whether or not the parser will trust X-Forwarded-Proto and
62  * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
63  * Rainbows!/Zbatery installations facing untrusted clients directly
64  * should set this to +false+
65  */
66 static VALUE set_xftrust(VALUE self, VALUE val)
68   if (Qtrue == val || Qfalse == val)
69     trust_x_forward = val;
70   else
71     rb_raise(rb_eTypeError, "must be true or false");
73   return val;
77  * returns whether or not the parser will trust X-Forwarded-Proto and
78  * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly
79  */
80 static VALUE xftrust(VALUE self)
82   return trust_x_forward;
85 /* keep this small for Rainbows! since every client has one */
86 struct http_parser {
87   int cs; /* Ragel internal state */
88   unsigned int flags;
89   unsigned long nr_requests;
90   size_t mark;
91   size_t offset;
92   union { /* these 2 fields don't nest */
93     size_t field;
94     size_t query;
95   } start;
96   union {
97     size_t field_len; /* only used during header processing */
98     size_t dest_offset; /* only used during body processing */
99   } s;
100   VALUE buf;
101   VALUE env;
102   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
103   union {
104     off_t content;
105     off_t chunk;
106   } len;
109 static ID id_clear, id_set_backtrace;
111 static void finalize_header(struct http_parser *hp);
113 NORETURN(static void raise_with_empty_bt(VALUE));
115 static void raise_with_empty_bt(VALUE exc)
117   VALUE bt = rb_ary_new();
119         rb_funcall(exc, id_set_backtrace, 1, bt);
120         rb_exc_raise(exc);
123 static void parser_error(const char *msg)
125   VALUE exc = rb_exc_new2(eHttpParserError, msg);
127   raise_with_empty_bt(exc);
130 static void raise_414(const char *msg)
132   VALUE exc = rb_exc_new2(eRequestURITooLongError, msg);
134   raise_with_empty_bt(exc);
137 #define REMAINING (unsigned long)(pe - p)
138 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
139 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
140 #define PTR_TO(F) (buffer + hp->F)
141 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
143 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
144 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
145 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
146 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
149  * handles values of the "Connection:" header, keepalive is implied
150  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
151  * Additionally, we require GET/HEAD requests to support keepalive.
152  */
153 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
155   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
156     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
157     HP_FL_SET(hp, KAVERSION);
158   } else if (STR_CSTR_CASE_EQ(val, "close")) {
159     /*
160      * it doesn't matter what HTTP version or request method we have,
161      * if a client says "Connection: close", we disable keepalive
162      */
163     HP_FL_UNSET(hp, KAVERSION);
164   } else {
165     /*
166      * client could've sent anything, ignore it for now.  Maybe
167      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
168      * Raising an exception might be too mean...
169      */
170   }
173 static void
174 request_method(struct http_parser *hp, const char *ptr, size_t len)
176   VALUE v = rb_str_new(ptr, len);
178   rb_hash_aset(hp->env, g_request_method, v);
181 static void
182 http_version(struct http_parser *hp, const char *ptr, size_t len)
184   VALUE v;
186   HP_FL_SET(hp, HASHEADER);
188   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
189     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
190     HP_FL_SET(hp, KAVERSION);
191     v = g_http_11;
192   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
193     v = g_http_10;
194   } else {
195     v = rb_str_new(ptr, len);
196   }
197   rb_hash_aset(hp->env, g_server_protocol, v);
198   rb_hash_aset(hp->env, g_http_version, v);
201 static inline void hp_invalid_if_trailer(struct http_parser *hp)
203   if (HP_FL_TEST(hp, INTRAILER))
204     parser_error("invalid Trailer");
207 static void write_cont_value(struct http_parser *hp,
208                              char *buffer, const char *p)
210   char *vptr;
212   if (hp->cont == Qfalse)
213      parser_error("invalid continuation line");
214   if (NIL_P(hp->cont))
215      return; /* we're ignoring this header (probably Host:) */
217   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
218   assert(hp->mark > 0 && "impossible continuation line offset");
220   if (LEN(mark, p) == 0)
221     return;
223   if (RSTRING_LEN(hp->cont) > 0)
224     --hp->mark;
226   vptr = PTR_TO(mark);
228   if (RSTRING_LEN(hp->cont) > 0) {
229     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
230     *vptr = ' ';
231   }
232   rb_str_buf_cat(hp->cont, vptr, LEN(mark, p));
235 static void write_value(struct http_parser *hp,
236                         const char *buffer, const char *p)
238   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
239   VALUE v;
240   VALUE e;
242   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
243   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STR_NEW(mark, p);
244   if (NIL_P(f)) {
245     const char *field = PTR_TO(start.field);
246     size_t flen = hp->s.field_len;
248     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
250     /*
251      * ignore "Version" headers since they conflict with the HTTP_VERSION
252      * rack env variable.
253      */
254     if (CONST_MEM_EQ("VERSION", field, flen)) {
255       hp->cont = Qnil;
256       return;
257     }
258     f = uncommon_field(field, flen);
259   } else if (f == g_http_connection) {
260     hp_keepalive_connection(hp, v);
261   } else if (f == g_content_length) {
262     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
263     if (hp->len.content < 0)
264       parser_error("invalid Content-Length");
265     if (hp->len.content != 0)
266       HP_FL_SET(hp, HASBODY);
267     hp_invalid_if_trailer(hp);
268   } else if (f == g_http_transfer_encoding) {
269     if (STR_CSTR_CASE_EQ(v, "chunked")) {
270       HP_FL_SET(hp, CHUNKED);
271       HP_FL_SET(hp, HASBODY);
272     }
273     hp_invalid_if_trailer(hp);
274   } else if (f == g_http_trailer) {
275     HP_FL_SET(hp, HASTRAILER);
276     hp_invalid_if_trailer(hp);
277   } else {
278     assert(TYPE(f) == T_STRING && "memoized object is not a string");
279     assert_frozen(f);
280   }
282   e = rb_hash_aref(hp->env, f);
283   if (NIL_P(e)) {
284     hp->cont = rb_hash_aset(hp->env, f, v);
285   } else if (f == g_http_host) {
286     /*
287      * ignored, absolute URLs in REQUEST_URI take precedence over
288      * the Host: header (ref: rfc 2616, section 5.2.1)
289      */
290      hp->cont = Qnil;
291   } else {
292     rb_str_buf_cat(e, ",", 1);
293     hp->cont = rb_str_buf_append(e, v);
294   }
297 /** Machine **/
300   machine http_parser;
302   action mark {MARK(mark, fpc); }
304   action start_field { MARK(start.field, fpc); }
305   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
306   action downcase_char { downcase_char(deconst(fpc)); }
307   action write_field { hp->s.field_len = LEN(start.field, fpc); }
308   action start_value { MARK(mark, fpc); }
309   action write_value { write_value(hp, buffer, fpc); }
310   action write_cont_value { write_cont_value(hp, buffer, fpc); }
311   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
312   action scheme {
313     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
314   }
315   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
316   action request_uri {
317     VALUE str;
319     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
320     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
321     /*
322      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
323      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
324      */
325     if (STR_CSTR_EQ(str, "*")) {
326       str = rb_str_new(NULL, 0);
327       rb_hash_aset(hp->env, g_path_info, str);
328       rb_hash_aset(hp->env, g_request_path, str);
329     }
330   }
331   action fragment {
332     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
333     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
334   }
335   action start_query {MARK(start.query, fpc); }
336   action query_string {
337     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
338     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
339   }
340   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
341   action request_path {
342     VALUE val;
344     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
345     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
347     /* rack says PATH_INFO must start with "/" or be empty */
348     if (!STR_CSTR_EQ(val, "*"))
349       rb_hash_aset(hp->env, g_path_info, val);
350   }
351   action add_to_chunk_size {
352     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
353     if (hp->len.chunk < 0)
354       parser_error("invalid chunk size");
355   }
356   action header_done {
357     finalize_header(hp);
359     cs = http_parser_first_final;
360     if (HP_FL_TEST(hp, HASBODY)) {
361       HP_FL_SET(hp, INBODY);
362       if (HP_FL_TEST(hp, CHUNKED))
363         cs = http_parser_en_ChunkedBody;
364     } else {
365       HP_FL_SET(hp, REQEOF);
366       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
367     }
368     /*
369      * go back to Ruby so we can call the Rack application, we'll reenter
370      * the parser iff the body needs to be processed.
371      */
372     goto post_exec;
373   }
375   action end_trailers {
376     cs = http_parser_first_final;
377     goto post_exec;
378   }
380   action end_chunked_body {
381     HP_FL_SET(hp, INTRAILER);
382     cs = http_parser_en_Trailers;
383     ++p;
384     assert(p <= pe && "buffer overflow after chunked body");
385     goto post_exec;
386   }
388   action skip_chunk_data {
389   skip_chunk_data_hack: {
390     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
391     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
392     hp->s.dest_offset += nr;
393     hp->len.chunk -= nr;
394     p += nr;
395     assert(hp->len.chunk >= 0 && "negative chunk length");
396     if ((size_t)hp->len.chunk > REMAINING) {
397       HP_FL_SET(hp, INCHUNK);
398       goto post_exec;
399     } else {
400       fhold;
401       fgoto chunk_end;
402     }
403   }}
405   include unicorn_http_common "unicorn_http_common.rl";
408 /** Data **/
409 %% write data;
411 static void http_parser_init(struct http_parser *hp)
413   int cs = 0;
414   hp->flags = 0;
415   hp->mark = 0;
416   hp->offset = 0;
417   hp->start.field = 0;
418   hp->s.field_len = 0;
419   hp->len.content = 0;
420   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
421   %% write init;
422   hp->cs = cs;
425 /** exec **/
426 static void
427 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
429   const char *p, *pe;
430   int cs = hp->cs;
431   size_t off = hp->offset;
433   if (cs == http_parser_first_final)
434     return;
436   assert(off <= len && "offset past end of buffer");
438   p = buffer+off;
439   pe = buffer+len;
441   assert((void *)(pe - p) == (void *)(len - off) &&
442          "pointers aren't same distance");
444   if (HP_FL_TEST(hp, INCHUNK)) {
445     HP_FL_UNSET(hp, INCHUNK);
446     goto skip_chunk_data_hack;
447   }
448   %% write exec;
449 post_exec: /* "_out:" also goes here */
450   if (hp->cs != http_parser_error)
451     hp->cs = cs;
452   hp->offset = p - buffer;
454   assert(p <= pe && "buffer overflow after parsing execute");
455   assert(hp->offset <= len && "offset longer than length");
458 static struct http_parser *data_get(VALUE self)
460   struct http_parser *hp;
462   Data_Get_Struct(self, struct http_parser, hp);
463   assert(hp && "failed to extract http_parser struct");
464   return hp;
468  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
469  * this resembles the Rack::Request#scheme method as of rack commit
470  * 35bb5ba6746b5d346de9202c004cc926039650c7
471  */
472 static void set_url_scheme(VALUE env, VALUE *server_port)
474   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
476   if (NIL_P(scheme)) {
477     if (trust_x_forward == Qfalse) {
478       scheme = g_http;
479     } else {
480       scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
481       if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
482         *server_port = g_port_443;
483         scheme = g_https;
484       } else {
485         scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
486         if (NIL_P(scheme)) {
487           scheme = g_http;
488         } else {
489           long len = RSTRING_LEN(scheme);
490           if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
491             if (len != 5)
492               scheme = g_https;
493             *server_port = g_port_443;
494           } else {
495             scheme = g_http;
496           }
497         }
498       }
499     }
500     rb_hash_aset(env, g_rack_url_scheme, scheme);
501   } else if (STR_CSTR_EQ(scheme, "https")) {
502     *server_port = g_port_443;
503   } else {
504     assert(*server_port == g_port_80 && "server_port not set");
505   }
509  * Parse and set the SERVER_NAME and SERVER_PORT variables
510  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
511  * anybody who needs them is using an unsupported configuration and/or
512  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
513  * fine.
514  */
515 static void set_server_vars(VALUE env, VALUE *server_port)
517   VALUE server_name = g_localhost;
518   VALUE host = rb_hash_aref(env, g_http_host);
520   if (!NIL_P(host)) {
521     char *host_ptr = RSTRING_PTR(host);
522     long host_len = RSTRING_LEN(host);
523     char *colon;
525     if (*host_ptr == '[') { /* ipv6 address format */
526       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
528       if (rbracket)
529         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
530       else
531         colon = memchr(host_ptr + 1, ':', host_len - 1);
532     } else {
533       colon = memchr(host_ptr, ':', host_len);
534     }
536     if (colon) {
537       long port_start = colon - host_ptr + 1;
539       server_name = rb_str_substr(host, 0, colon - host_ptr);
540       if ((host_len - port_start) > 0)
541         *server_port = rb_str_substr(host, port_start, host_len);
542     } else {
543       server_name = host;
544     }
545   }
546   rb_hash_aset(env, g_server_name, server_name);
547   rb_hash_aset(env, g_server_port, *server_port);
550 static void finalize_header(struct http_parser *hp)
552   VALUE server_port = g_port_80;
554   set_url_scheme(hp->env, &server_port);
555   set_server_vars(hp->env, &server_port);
557   if (!HP_FL_TEST(hp, HASHEADER))
558     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
560   /* rack requires QUERY_STRING */
561   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
562     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
565 static void hp_mark(void *ptr)
567   struct http_parser *hp = ptr;
569   rb_gc_mark(hp->buf);
570   rb_gc_mark(hp->env);
571   rb_gc_mark(hp->cont);
574 static VALUE HttpParser_alloc(VALUE klass)
576   struct http_parser *hp;
577   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
582  * call-seq:
583  *    parser.new => parser
585  * Creates a new parser.
586  */
587 static VALUE HttpParser_init(VALUE self)
589   struct http_parser *hp = data_get(self);
591   http_parser_init(hp);
592   hp->buf = rb_str_new(NULL, 0);
593   hp->env = rb_hash_new();
594   hp->nr_requests = keepalive_requests;
596   return self;
600  * call-seq:
601  *    parser.clear => parser
603  * Resets the parser to it's initial state so that you can reuse it
604  * rather than making new ones.
605  */
606 static VALUE HttpParser_clear(VALUE self)
608   struct http_parser *hp = data_get(self);
610   http_parser_init(hp);
611   rb_funcall(hp->env, id_clear, 0);
613   return self;
617  * call-seq:
618  *    parser.reset => nil
620  * Resets the parser to it's initial state so that you can reuse it
621  * rather than making new ones.
623  * This method is deprecated and to be removed in Unicorn 4.x
624  */
625 static VALUE HttpParser_reset(VALUE self)
627   static int warned;
629   if (!warned) {
630     rb_warn("Unicorn::HttpParser#reset is deprecated; "
631             "use Unicorn::HttpParser#clear instead");
632   }
633   HttpParser_clear(self);
634   return Qnil;
637 static void advance_str(VALUE str, off_t nr)
639   long len = RSTRING_LEN(str);
641   if (len == 0)
642     return;
644   rb_str_modify(str);
646   assert(nr <= len && "trying to advance past end of buffer");
647   len -= nr;
648   if (len > 0) /* unlikely, len is usually 0 */
649     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
650   rb_str_set_len(str, len);
654  * call-seq:
655  *   parser.content_length => nil or Integer
657  * Returns the number of bytes left to run through HttpParser#filter_body.
658  * This will initially be the value of the "Content-Length" HTTP header
659  * after header parsing is complete and will decrease in value as
660  * HttpParser#filter_body is called for each chunk.  This should return
661  * zero for requests with no body.
663  * This will return nil on "Transfer-Encoding: chunked" requests.
664  */
665 static VALUE HttpParser_content_length(VALUE self)
667   struct http_parser *hp = data_get(self);
669   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
673  * Document-method: parse
674  * call-seq:
675  *    parser.parse => env or nil
677  * Takes a Hash and a String of data, parses the String of data filling
678  * in the Hash returning the Hash if parsing is finished, nil otherwise
679  * When returning the env Hash, it may modify data to point to where
680  * body processing should begin.
682  * Raises HttpParserError if there are parsing errors.
683  */
684 static VALUE HttpParser_parse(VALUE self)
686   struct http_parser *hp = data_get(self);
687   VALUE data = hp->buf;
689   if (HP_FL_TEST(hp, TO_CLEAR)) {
690     http_parser_init(hp);
691     rb_funcall(hp->env, id_clear, 0);
692   }
694   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
695   VALIDATE_MAX_LENGTH(hp->offset, HEADER);
697   if (hp->cs == http_parser_first_final ||
698       hp->cs == http_parser_en_ChunkedBody) {
699     advance_str(data, hp->offset + 1);
700     hp->offset = 0;
701     if (HP_FL_TEST(hp, INTRAILER))
702       HP_FL_SET(hp, REQEOF);
704     return hp->env;
705   }
707   if (hp->cs == http_parser_error)
708     parser_error("Invalid HTTP format, parsing fails.");
710   return Qnil;
714  * Document-method: trailers
715  * call-seq:
716  *    parser.trailers(req, data) => req or nil
718  * This is an alias for HttpParser#headers
719  */
722  * Document-method: headers
723  */
724 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
726   struct http_parser *hp = data_get(self);
728   hp->env = env;
729   hp->buf = buf;
731   return HttpParser_parse(self);
734 static int chunked_eof(struct http_parser *hp)
736   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
740  * call-seq:
741  *    parser.body_eof? => true or false
743  * Detects if we're done filtering the body or not.  This can be used
744  * to detect when to stop calling HttpParser#filter_body.
745  */
746 static VALUE HttpParser_body_eof(VALUE self)
748   struct http_parser *hp = data_get(self);
750   if (HP_FL_TEST(hp, CHUNKED))
751     return chunked_eof(hp) ? Qtrue : Qfalse;
753   return hp->len.content == 0 ? Qtrue : Qfalse;
757  * call-seq:
758  *    parser.keepalive? => true or false
760  * This should be used to detect if a request can really handle
761  * keepalives and pipelining.  Currently, the rules are:
763  * 1. MUST be a GET or HEAD request
764  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
765  * 3. MUST NOT have "Connection: close" set
766  */
767 static VALUE HttpParser_keepalive(VALUE self)
769   struct http_parser *hp = data_get(self);
771   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
775  * call-seq:
776  *    parser.next? => true or false
778  * Exactly like HttpParser#keepalive?, except it will reset the internal
779  * parser state on next parse if it returns true.  It will also respect
780  * the maximum *keepalive_requests* value and return false if that is
781  * reached.
782  */
783 static VALUE HttpParser_next(VALUE self)
785   struct http_parser *hp = data_get(self);
787   if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
788     HP_FL_SET(hp, TO_CLEAR);
789     return Qtrue;
790   }
791   return Qfalse;
795  * call-seq:
796  *    parser.headers? => true or false
798  * This should be used to detect if a request has headers (and if
799  * the response will have headers as well).  HTTP/0.9 requests
800  * should return false, all subsequent HTTP versions will return true
801  */
802 static VALUE HttpParser_has_headers(VALUE self)
804   struct http_parser *hp = data_get(self);
806   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
809 static VALUE HttpParser_buf(VALUE self)
811   return data_get(self)->buf;
814 static VALUE HttpParser_env(VALUE self)
816   return data_get(self)->env;
820  * call-seq:
821  *    parser.filter_body(buf, data) => nil/data
823  * Takes a String of +data+, will modify data if dechunking is done.
824  * Returns +nil+ if there is more data left to process.  Returns
825  * +data+ if body processing is complete. When returning +data+,
826  * it may modify +data+ so the start of the string points to where
827  * the body ended so that trailer processing can begin.
829  * Raises HttpParserError if there are dechunking errors.
830  * Basically this is a glorified memcpy(3) that copies +data+
831  * into +buf+ while filtering it through the dechunker.
832  */
833 static VALUE HttpParser_filter_body(VALUE self, VALUE buf, VALUE data)
835   struct http_parser *hp = data_get(self);
836   char *dptr;
837   long dlen;
839   dptr = RSTRING_PTR(data);
840   dlen = RSTRING_LEN(data);
842   StringValue(buf);
843   rb_str_resize(buf, dlen); /* we can never copy more than dlen bytes */
844   OBJ_TAINT(buf); /* keep weirdo $SAFE users happy */
846   if (HP_FL_TEST(hp, CHUNKED)) {
847     if (!chunked_eof(hp)) {
848       hp->s.dest_offset = 0;
849       hp->cont = buf;
850       hp->buf = data;
851       http_parser_execute(hp, dptr, dlen);
852       if (hp->cs == http_parser_error)
853         parser_error("Invalid HTTP format, parsing fails.");
855       assert(hp->s.dest_offset <= hp->offset &&
856              "destination buffer overflow");
857       advance_str(data, hp->offset);
858       rb_str_set_len(buf, hp->s.dest_offset);
860       if (RSTRING_LEN(buf) == 0 && chunked_eof(hp)) {
861         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
862       } else {
863         data = Qnil;
864       }
865     }
866   } else {
867     /* no need to enter the Ragel machine for unchunked transfers */
868     assert(hp->len.content >= 0 && "negative Content-Length");
869     if (hp->len.content > 0) {
870       long nr = MIN(dlen, hp->len.content);
872       hp->buf = data;
873       memcpy(RSTRING_PTR(buf), dptr, nr);
874       hp->len.content -= nr;
875       if (hp->len.content == 0) {
876         HP_FL_SET(hp, REQEOF);
877         hp->cs = http_parser_first_final;
878       }
879       advance_str(data, nr);
880       rb_str_set_len(buf, nr);
881       data = Qnil;
882     }
883   }
884   hp->offset = 0; /* for trailer parsing */
885   return data;
888 #define SET_GLOBAL(var,str) do { \
889   var = find_common_field(str, sizeof(str) - 1); \
890   assert(!NIL_P(var) && "missed global field"); \
891 } while (0)
893 void Init_unicorn_http(void)
895   VALUE mUnicorn, cHttpParser;
897   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
898   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
899   eHttpParserError =
900          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
901   eRequestURITooLongError =
902          rb_define_class_under(mUnicorn, "RequestURITooLongError",
903                                eHttpParserError);
905   init_globals();
906   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
907   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
908   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
909   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
910   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
911   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
912   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
913   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
914   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
915   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
916   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
917   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
918   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
919   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
920   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
922   /*
923    * The maximum size a single chunk when using chunked transfer encoding.
924    * This is only a theoretical maximum used to detect errors in clients,
925    * it is highly unlikely to encounter clients that send more than
926    * several kilobytes at once.
927    */
928   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
930   /*
931    * The maximum size of the body as specified by Content-Length.
932    * This is only a theoretical maximum, the actual limit is subject
933    * to the limits of the file system used for +Dir.tmpdir+.
934    */
935   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
937   /* default value for keepalive_requests */
938   rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
939                   ULONG2NUM(keepalive_requests));
941   rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
942   rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
943   rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
944   rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
946   init_common_fields();
947   SET_GLOBAL(g_http_host, "HOST");
948   SET_GLOBAL(g_http_trailer, "TRAILER");
949   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
950   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
951   SET_GLOBAL(g_http_connection, "CONNECTION");
952   id_clear = rb_intern("clear");
953   id_set_backtrace = rb_intern("set_backtrace");
954   init_unicorn_httpdate();
956 #undef SET_GLOBAL