drop Ruby 1.9.3 support, require 2.0+ for now
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blobe934a3242bdc137e1b3c2feaad16869ff57d0f83
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 GPLv2+ (GPLv3+ preferred)
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
28 #define UH_FL_RESSTART 0x400 /* for check_client_connection */
29 #define UH_FL_HIJACK 0x800
31 /* all of these flags need to be set for keepalive to be supported */
32 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
34 static unsigned int MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
36 /* this is only intended for use with Rainbows! */
37 static VALUE set_maxhdrlen(VALUE self, VALUE len)
39   return UINT2NUM(MAX_HEADER_LEN = NUM2UINT(len));
42 /* keep this small for other servers (e.g. yahns) since every client has one */
43 struct http_parser {
44   int cs; /* Ragel internal state */
45   unsigned int flags;
46   unsigned int mark;
47   unsigned int offset;
48   union { /* these 2 fields don't nest */
49     unsigned int field;
50     unsigned int query;
51   } start;
52   union {
53     unsigned int field_len; /* only used during header processing */
54     unsigned int dest_offset; /* only used during body processing */
55   } s;
56   VALUE buf;
57   VALUE env;
58   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
59   union {
60     off_t content;
61     off_t chunk;
62   } len;
65 static ID id_set_backtrace, id_is_chunked_p;
66 static VALUE cHttpParser;
68 static void finalize_header(struct http_parser *hp);
70 static void parser_raise(VALUE klass, const char *msg)
72   VALUE exc = rb_exc_new2(klass, msg);
73   VALUE bt = rb_ary_new();
75   rb_funcall(exc, id_set_backtrace, 1, bt);
76   rb_exc_raise(exc);
79 static inline unsigned int ulong2uint(unsigned long n)
81   unsigned int i = (unsigned int)n;
83   if (sizeof(unsigned int) != sizeof(unsigned long)) {
84     if ((unsigned long)i != n) {
85       rb_raise(rb_eRangeError, "too large to be 32-bit uint: %lu", n);
86     }
87   }
88   return i;
91 #define REMAINING (unsigned long)(pe - p)
92 #define LEN(AT, FPC) (ulong2uint(FPC - buffer) - hp->AT)
93 #define MARK(M,FPC) (hp->M = ulong2uint((FPC) - buffer))
94 #define PTR_TO(F) (buffer + hp->F)
95 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
96 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
98 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
99 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
100 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
101 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
103 static int is_lws(char c)
105   return (c == ' ' || c == '\t');
108 static VALUE stripped_str_new(const char *str, long len)
110   long end;
112   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
114   return rb_str_new(str, end + 1);
118  * handles values of the "Connection:" header, keepalive is implied
119  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
120  * Additionally, we require GET/HEAD requests to support keepalive.
121  */
122 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
124   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
125     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
126     HP_FL_SET(hp, KAVERSION);
127   } else if (STR_CSTR_CASE_EQ(val, "close")) {
128     /*
129      * it doesn't matter what HTTP version or request method we have,
130      * if a client says "Connection: close", we disable keepalive
131      */
132     HP_FL_UNSET(hp, KAVERSION);
133   } else {
134     /*
135      * client could've sent anything, ignore it for now.  Maybe
136      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
137      * Raising an exception might be too mean...
138      */
139   }
142 static void
143 request_method(struct http_parser *hp, const char *ptr, size_t len)
145   VALUE v = rb_str_new(ptr, len);
147   rb_hash_aset(hp->env, g_request_method, v);
150 static void
151 http_version(struct http_parser *hp, const char *ptr, size_t len)
153   VALUE v;
155   HP_FL_SET(hp, HASHEADER);
157   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
158     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
159     HP_FL_SET(hp, KAVERSION);
160     v = g_http_11;
161   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
162     v = g_http_10;
163   } else {
164     v = rb_str_new(ptr, len);
165   }
166   rb_hash_aset(hp->env, g_server_protocol, v);
167   rb_hash_aset(hp->env, g_http_version, v);
170 static inline void hp_invalid_if_trailer(struct http_parser *hp)
172   if (HP_FL_TEST(hp, INTRAILER))
173     parser_raise(eHttpParserError, "invalid Trailer");
176 static void write_cont_value(struct http_parser *hp,
177                              char *buffer, const char *p)
179   char *vptr;
180   long end;
181   long len = LEN(mark, p);
182   long cont_len;
184   if (hp->cont == Qfalse)
185      parser_raise(eHttpParserError, "invalid continuation line");
186   if (NIL_P(hp->cont))
187      return; /* we're ignoring this header (probably Host:) */
189   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
190   assert(hp->mark > 0 && "impossible continuation line offset");
192   if (len == 0)
193     return;
195   cont_len = RSTRING_LEN(hp->cont);
196   if (cont_len > 0) {
197     --hp->mark;
198     len = LEN(mark, p);
199   }
200   vptr = PTR_TO(mark);
202   /* normalize tab to space */
203   if (cont_len > 0) {
204     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
205     *vptr = ' ';
206   }
208   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
209   rb_str_buf_cat(hp->cont, vptr, end + 1);
212 static int is_chunked(VALUE v)
214   /* common case first */
215   if (STR_CSTR_CASE_EQ(v, "chunked"))
216     return 1;
218   /*
219    * call Ruby function in unicorn/http_request.rb to deal with unlikely
220    * comma-delimited case
221    */
222   return rb_funcall(cHttpParser, id_is_chunked_p, 1, v) != Qfalse;
225 static void write_value(struct http_parser *hp,
226                         const char *buffer, const char *p)
228   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
229   VALUE v;
230   VALUE e;
232   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
233   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
234   if (NIL_P(f)) {
235     const char *field = PTR_TO(start.field);
236     size_t flen = hp->s.field_len;
238     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
240     /*
241      * ignore "Version" headers since they conflict with the HTTP_VERSION
242      * rack env variable.
243      */
244     if (CONST_MEM_EQ("VERSION", field, flen)) {
245       hp->cont = Qnil;
246       return;
247     }
248     f = uncommon_field(field, flen);
249   } else if (f == g_http_connection) {
250     hp_keepalive_connection(hp, v);
251   } else if (f == g_content_length && !HP_FL_TEST(hp, CHUNKED)) {
252     if (hp->len.content)
253       parser_raise(eHttpParserError, "Content-Length already set");
254     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
255     if (hp->len.content < 0)
256       parser_raise(eHttpParserError, "invalid Content-Length");
257     if (hp->len.content != 0)
258       HP_FL_SET(hp, HASBODY);
259     hp_invalid_if_trailer(hp);
260   } else if (f == g_http_transfer_encoding) {
261     if (is_chunked(v)) {
262       if (HP_FL_TEST(hp, CHUNKED))
263         /*
264          * RFC 7230 3.3.1:
265          * A sender MUST NOT apply chunked more than once to a message body
266          * (i.e., chunking an already chunked message is not allowed).
267          */
268         parser_raise(eHttpParserError, "Transfer-Encoding double chunked");
270       HP_FL_SET(hp, CHUNKED);
271       HP_FL_SET(hp, HASBODY);
273       /* RFC 7230 3.3.3, 3: favor chunked if Content-Length exists */
274       hp->len.content = 0;
275     } else if (HP_FL_TEST(hp, CHUNKED)) {
276       /*
277        * RFC 7230 3.3.3, point 3 states:
278        * If a Transfer-Encoding header field is present in a request and
279        * the chunked transfer coding is not the final encoding, the
280        * message body length cannot be determined reliably; the server
281        * MUST respond with the 400 (Bad Request) status code and then
282        * close the connection.
283        */
284       parser_raise(eHttpParserError, "invalid Transfer-Encoding");
285     }
286     hp_invalid_if_trailer(hp);
287   } else if (f == g_http_trailer) {
288     HP_FL_SET(hp, HASTRAILER);
289     hp_invalid_if_trailer(hp);
290   } else {
291     assert(TYPE(f) == T_STRING && "memoized object is not a string");
292     assert_frozen(f);
293   }
295   e = rb_hash_aref(hp->env, f);
296   if (NIL_P(e)) {
297     hp->cont = rb_hash_aset(hp->env, f, v);
298   } else if (f == g_http_host) {
299     /*
300      * ignored, absolute URLs in REQUEST_URI take precedence over
301      * the Host: header (ref: rfc 2616, section 5.2.1)
302      */
303      hp->cont = Qnil;
304   } else {
305     rb_str_buf_cat(e, ",", 1);
306     hp->cont = rb_str_buf_append(e, v);
307   }
310 /** Machine **/
313   machine http_parser;
315   action mark {MARK(mark, fpc); }
317   action start_field { MARK(start.field, fpc); }
318   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
319   action downcase_char { downcase_char(deconst(fpc)); }
320   action write_field { hp->s.field_len = LEN(start.field, fpc); }
321   action start_value { MARK(mark, fpc); }
322   action write_value { write_value(hp, buffer, fpc); }
323   action write_cont_value { write_cont_value(hp, buffer, fpc); }
324   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
325   action scheme {
326     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
327   }
328   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
329   action request_uri {
330     VALUE str;
332     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
333     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
334     /*
335      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
336      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
337      */
338     if (STR_CSTR_EQ(str, "*")) {
339       str = rb_str_new(NULL, 0);
340       rb_hash_aset(hp->env, g_path_info, str);
341       rb_hash_aset(hp->env, g_request_path, str);
342     }
343   }
344   action fragment {
345     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
346     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
347   }
348   action start_query {MARK(start.query, fpc); }
349   action query_string {
350     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
351     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
352   }
353   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
354   action request_path {
355     VALUE val;
357     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
358     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
360     /* rack says PATH_INFO must start with "/" or be empty */
361     if (!STR_CSTR_EQ(val, "*"))
362       rb_hash_aset(hp->env, g_path_info, val);
363   }
364   action add_to_chunk_size {
365     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
366     if (hp->len.chunk < 0)
367       parser_raise(eHttpParserError, "invalid chunk size");
368   }
369   action header_done {
370     finalize_header(hp);
372     cs = http_parser_first_final;
373     if (HP_FL_TEST(hp, HASBODY)) {
374       HP_FL_SET(hp, INBODY);
375       if (HP_FL_TEST(hp, CHUNKED))
376         cs = http_parser_en_ChunkedBody;
377     } else {
378       HP_FL_SET(hp, REQEOF);
379       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
380     }
381     /*
382      * go back to Ruby so we can call the Rack application, we'll reenter
383      * the parser iff the body needs to be processed.
384      */
385     goto post_exec;
386   }
388   action end_trailers {
389     cs = http_parser_first_final;
390     goto post_exec;
391   }
393   action end_chunked_body {
394     HP_FL_SET(hp, INTRAILER);
395     cs = http_parser_en_Trailers;
396     ++p;
397     assert(p <= pe && "buffer overflow after chunked body");
398     goto post_exec;
399   }
401   action skip_chunk_data {
402   skip_chunk_data_hack: {
403     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
404     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
405     hp->s.dest_offset += nr;
406     hp->len.chunk -= nr;
407     p += nr;
408     assert(hp->len.chunk >= 0 && "negative chunk length");
409     if ((size_t)hp->len.chunk > REMAINING) {
410       HP_FL_SET(hp, INCHUNK);
411       goto post_exec;
412     } else {
413       fhold;
414       fgoto chunk_end;
415     }
416   }}
418   include unicorn_http_common "unicorn_http_common.rl";
421 /** Data **/
422 %% write data;
424 static void http_parser_init(struct http_parser *hp)
426   int cs = 0;
427   hp->flags = 0;
428   hp->mark = 0;
429   hp->offset = 0;
430   hp->start.field = 0;
431   hp->s.field_len = 0;
432   hp->len.content = 0;
433   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
434   %% write init;
435   hp->cs = cs;
438 /** exec **/
439 static void
440 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
442   const char *p, *pe;
443   int cs = hp->cs;
444   size_t off = hp->offset;
446   if (cs == http_parser_first_final)
447     return;
449   assert(off <= len && "offset past end of buffer");
451   p = buffer+off;
452   pe = buffer+len;
454   assert((void *)(pe - p) == (void *)(len - off) &&
455          "pointers aren't same distance");
457   if (HP_FL_TEST(hp, INCHUNK)) {
458     HP_FL_UNSET(hp, INCHUNK);
459     goto skip_chunk_data_hack;
460   }
461   %% write exec;
462 post_exec: /* "_out:" also goes here */
463   if (hp->cs != http_parser_error)
464     hp->cs = cs;
465   hp->offset = ulong2uint(p - buffer);
467   assert(p <= pe && "buffer overflow after parsing execute");
468   assert(hp->offset <= len && "offset longer than length");
471 static void hp_mark(void *ptr)
473   struct http_parser *hp = ptr;
475   rb_gc_mark(hp->buf);
476   rb_gc_mark(hp->env);
477   rb_gc_mark(hp->cont);
480 static size_t hp_memsize(const void *ptr)
482   return sizeof(struct http_parser);
485 static const rb_data_type_t hp_type = {
486   "unicorn_http",
487   { hp_mark, RUBY_TYPED_DEFAULT_FREE, hp_memsize, /* reserved */ },
488   /* parent, data, [ flags ] */
491 static struct http_parser *data_get(VALUE self)
493   struct http_parser *hp;
495   TypedData_Get_Struct(self, struct http_parser, &hp_type, hp);
496   assert(hp && "failed to extract http_parser struct");
497   return hp;
501  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
502  * this resembles the Rack::Request#scheme method as of rack commit
503  * 35bb5ba6746b5d346de9202c004cc926039650c7
504  */
505 static void set_url_scheme(VALUE env, VALUE *server_port)
507   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
509   if (NIL_P(scheme)) {
510     /*
511      * would anybody be horribly opposed to removing the X-Forwarded-SSL
512      * and X-Forwarded-Proto handling from this parser?  We've had it
513      * forever and nobody has said anything against it, either.
514      * Anyways, please send comments to our public mailing list:
515      * unicorn-public@yhbt.net (no HTML mail, no subscription necessary)
516      */
517     scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
518     if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
519       *server_port = g_port_443;
520       scheme = g_https;
521     } else {
522       scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
523       if (NIL_P(scheme)) {
524         scheme = g_http;
525       } else {
526         long len = RSTRING_LEN(scheme);
527         if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
528           if (len != 5)
529             scheme = g_https;
530           *server_port = g_port_443;
531         } else {
532           scheme = g_http;
533         }
534       }
535     }
536     rb_hash_aset(env, g_rack_url_scheme, scheme);
537   } else if (STR_CSTR_EQ(scheme, "https")) {
538     *server_port = g_port_443;
539   } else {
540     assert(*server_port == g_port_80 && "server_port not set");
541   }
545  * Parse and set the SERVER_NAME and SERVER_PORT variables
546  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
547  * anybody who needs them is using an unsupported configuration and/or
548  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
549  * fine.
550  */
551 static void set_server_vars(VALUE env, VALUE *server_port)
553   VALUE server_name = g_localhost;
554   VALUE host = rb_hash_aref(env, g_http_host);
556   if (!NIL_P(host)) {
557     char *host_ptr = RSTRING_PTR(host);
558     long host_len = RSTRING_LEN(host);
559     char *colon;
561     if (*host_ptr == '[') { /* ipv6 address format */
562       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
564       if (rbracket)
565         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
566       else
567         colon = memchr(host_ptr + 1, ':', host_len - 1);
568     } else {
569       colon = memchr(host_ptr, ':', host_len);
570     }
572     if (colon) {
573       long port_start = colon - host_ptr + 1;
575       server_name = rb_str_substr(host, 0, colon - host_ptr);
576       if ((host_len - port_start) > 0)
577         *server_port = rb_str_substr(host, port_start, host_len);
578     } else {
579       server_name = host;
580     }
581   }
582   rb_hash_aset(env, g_server_name, server_name);
583   rb_hash_aset(env, g_server_port, *server_port);
586 static void finalize_header(struct http_parser *hp)
588   VALUE server_port = g_port_80;
590   set_url_scheme(hp->env, &server_port);
591   set_server_vars(hp->env, &server_port);
593   if (!HP_FL_TEST(hp, HASHEADER))
594     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
596   /* rack requires QUERY_STRING */
597   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
598     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
601 static VALUE HttpParser_alloc(VALUE klass)
603   struct http_parser *hp;
605   return TypedData_Make_Struct(klass, struct http_parser, &hp_type, hp);
609  * call-seq:
610  *    parser.new => parser
612  * Creates a new parser.
613  */
614 static VALUE HttpParser_init(VALUE self)
616   struct http_parser *hp = data_get(self);
618   http_parser_init(hp);
619   hp->buf = rb_str_new(NULL, 0);
620   hp->env = rb_hash_new();
622   return self;
626  * call-seq:
627  *    parser.clear => parser
629  * Resets the parser to it's initial state so that you can reuse it
630  * rather than making new ones.
631  */
632 static VALUE HttpParser_clear(VALUE self)
634   struct http_parser *hp = data_get(self);
636   /* we can't safely reuse .buf and .env if hijacked */
637   if (HP_FL_TEST(hp, HIJACK))
638     return HttpParser_init(self);
640   http_parser_init(hp);
641   rb_hash_clear(hp->env);
643   return self;
646 static void advance_str(VALUE str, off_t nr)
648   long len = RSTRING_LEN(str);
650   if (len == 0)
651     return;
653   rb_str_modify(str);
655   assert(nr <= len && "trying to advance past end of buffer");
656   len -= nr;
657   if (len > 0) /* unlikely, len is usually 0 */
658     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
659   rb_str_set_len(str, len);
663  * call-seq:
664  *   parser.content_length => nil or Integer
666  * Returns the number of bytes left to run through HttpParser#filter_body.
667  * This will initially be the value of the "Content-Length" HTTP header
668  * after header parsing is complete and will decrease in value as
669  * HttpParser#filter_body is called for each chunk.  This should return
670  * zero for requests with no body.
672  * This will return nil on "Transfer-Encoding: chunked" requests.
673  */
674 static VALUE HttpParser_content_length(VALUE self)
676   struct http_parser *hp = data_get(self);
678   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
682  * Document-method: parse
683  * call-seq:
684  *    parser.parse => env or nil
686  * Takes a Hash and a String of data, parses the String of data filling
687  * in the Hash returning the Hash if parsing is finished, nil otherwise
688  * When returning the env Hash, it may modify data to point to where
689  * body processing should begin.
691  * Raises HttpParserError if there are parsing errors.
692  */
693 static VALUE HttpParser_parse(VALUE self)
695   struct http_parser *hp = data_get(self);
696   VALUE data = hp->buf;
698   if (HP_FL_TEST(hp, TO_CLEAR))
699     HttpParser_clear(self);
701   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
702   if (hp->offset > MAX_HEADER_LEN)
703     parser_raise(e413, "HTTP header is too large");
705   if (hp->cs == http_parser_first_final ||
706       hp->cs == http_parser_en_ChunkedBody) {
707     advance_str(data, hp->offset + 1);
708     hp->offset = 0;
709     if (HP_FL_TEST(hp, INTRAILER))
710       HP_FL_SET(hp, REQEOF);
712     return hp->env;
713   }
715   if (hp->cs == http_parser_error)
716     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
718   return Qnil;
722  * Document-method: parse
723  * call-seq:
724  *    parser.add_parse(buffer) => env or nil
726  * adds the contents of +buffer+ to the internal buffer and attempts to
727  * continue parsing.  Returns the +env+ Hash on success or nil if more
728  * data is needed.
730  * Raises HttpParserError if there are parsing errors.
731  */
732 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
734   struct http_parser *hp = data_get(self);
736   Check_Type(buffer, T_STRING);
737   rb_str_buf_append(hp->buf, buffer);
739   return HttpParser_parse(self);
743  * Document-method: trailers
744  * call-seq:
745  *    parser.trailers(req, data) => req or nil
747  * This is an alias for HttpParser#headers
748  */
751  * Document-method: headers
752  */
753 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
755   struct http_parser *hp = data_get(self);
757   hp->env = env;
758   hp->buf = buf;
760   return HttpParser_parse(self);
763 static int chunked_eof(struct http_parser *hp)
765   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
769  * call-seq:
770  *    parser.body_eof? => true or false
772  * Detects if we're done filtering the body or not.  This can be used
773  * to detect when to stop calling HttpParser#filter_body.
774  */
775 static VALUE HttpParser_body_eof(VALUE self)
777   struct http_parser *hp = data_get(self);
779   if (HP_FL_TEST(hp, CHUNKED))
780     return chunked_eof(hp) ? Qtrue : Qfalse;
782   return hp->len.content == 0 ? Qtrue : Qfalse;
786  * call-seq:
787  *    parser.keepalive? => true or false
789  * This should be used to detect if a request can really handle
790  * keepalives and pipelining.  Currently, the rules are:
792  * 1. MUST be a GET or HEAD request
793  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
794  * 3. MUST NOT have "Connection: close" set
795  */
796 static VALUE HttpParser_keepalive(VALUE self)
798   struct http_parser *hp = data_get(self);
800   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
804  * call-seq:
805  *    parser.next? => true or false
807  * Exactly like HttpParser#keepalive?, except it will reset the internal
808  * parser state on next parse if it returns true.
809  */
810 static VALUE HttpParser_next(VALUE self)
812   struct http_parser *hp = data_get(self);
814   if (HP_FL_ALL(hp, KEEPALIVE)) {
815     HP_FL_SET(hp, TO_CLEAR);
816     return Qtrue;
817   }
818   return Qfalse;
822  * call-seq:
823  *    parser.headers? => true or false
825  * This should be used to detect if a request has headers (and if
826  * the response will have headers as well).  HTTP/0.9 requests
827  * should return false, all subsequent HTTP versions will return true
828  */
829 static VALUE HttpParser_has_headers(VALUE self)
831   struct http_parser *hp = data_get(self);
833   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
836 static VALUE HttpParser_buf(VALUE self)
838   return data_get(self)->buf;
841 static VALUE HttpParser_env(VALUE self)
843   return data_get(self)->env;
846 static VALUE HttpParser_hijacked_bang(VALUE self)
848   struct http_parser *hp = data_get(self);
850   HP_FL_SET(hp, HIJACK);
852   return self;
856  * call-seq:
857  *    parser.filter_body(dst, src) => nil/src
859  * Takes a String of +src+, will modify data if dechunking is done.
860  * Returns +nil+ if there is more data left to process.  Returns
861  * +src+ if body processing is complete. When returning +src+,
862  * it may modify +src+ so the start of the string points to where
863  * the body ended so that trailer processing can begin.
865  * Raises HttpParserError if there are dechunking errors.
866  * Basically this is a glorified memcpy(3) that copies +src+
867  * into +buf+ while filtering it through the dechunker.
868  */
869 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
871   struct http_parser *hp = data_get(self);
872   char *srcptr;
873   long srclen;
875   srcptr = RSTRING_PTR(src);
876   srclen = RSTRING_LEN(src);
878   StringValue(dst);
880   if (HP_FL_TEST(hp, CHUNKED)) {
881     if (!chunked_eof(hp)) {
882       rb_str_modify(dst);
883       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
885       hp->s.dest_offset = 0;
886       hp->cont = dst;
887       hp->buf = src;
888       http_parser_execute(hp, srcptr, srclen);
889       if (hp->cs == http_parser_error)
890         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
892       assert(hp->s.dest_offset <= hp->offset &&
893              "destination buffer overflow");
894       advance_str(src, hp->offset);
895       rb_str_set_len(dst, hp->s.dest_offset);
897       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
898         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
899       } else {
900         src = Qnil;
901       }
902     }
903   } else {
904     /* no need to enter the Ragel machine for unchunked transfers */
905     assert(hp->len.content >= 0 && "negative Content-Length");
906     if (hp->len.content > 0) {
907       long nr = MIN(srclen, hp->len.content);
909       rb_str_modify(dst);
910       rb_str_resize(dst, nr);
911       /*
912        * using rb_str_replace() to avoid memcpy() doesn't help in
913        * most cases because a GC-aware programmer will pass an explicit
914        * buffer to env["rack.input"].read and reuse the buffer in a loop.
915        * This causes copy-on-write behavior to be triggered anyways
916        * when the +src+ buffer is modified (when reading off the socket).
917        */
918       hp->buf = src;
919       memcpy(RSTRING_PTR(dst), srcptr, nr);
920       hp->len.content -= nr;
921       if (hp->len.content == 0) {
922         HP_FL_SET(hp, REQEOF);
923         hp->cs = http_parser_first_final;
924       }
925       advance_str(src, nr);
926       src = Qnil;
927     }
928   }
929   hp->offset = 0; /* for trailer parsing */
930   return src;
933 static VALUE HttpParser_rssset(VALUE self, VALUE boolean)
935   struct http_parser *hp = data_get(self);
937   if (RTEST(boolean))
938     HP_FL_SET(hp, RESSTART);
939   else
940     HP_FL_UNSET(hp, RESSTART);
942   return boolean; /* ignored by Ruby anyways */
945 static VALUE HttpParser_rssget(VALUE self)
947   struct http_parser *hp = data_get(self);
949   return HP_FL_TEST(hp, RESSTART) ? Qtrue : Qfalse;
952 #define SET_GLOBAL(var,str) do { \
953   var = find_common_field(str, sizeof(str) - 1); \
954   assert(!NIL_P(var) && "missed global field"); \
955 } while (0)
957 void Init_unicorn_http(void)
959   VALUE mUnicorn;
961   mUnicorn = rb_define_module("Unicorn");
962   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
963   eHttpParserError =
964          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
965   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
966                                eHttpParserError);
967   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
968                                eHttpParserError);
970   init_globals();
971   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
972   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
973   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
974   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
975   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
976   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
977   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
978   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
979   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
980   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
981   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
982   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
983   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
984   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
985   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
986   rb_define_method(cHttpParser, "hijacked!", HttpParser_hijacked_bang, 0);
987   rb_define_method(cHttpParser, "response_start_sent=", HttpParser_rssset, 1);
988   rb_define_method(cHttpParser, "response_start_sent", HttpParser_rssget, 0);
990   /*
991    * The maximum size a single chunk when using chunked transfer encoding.
992    * This is only a theoretical maximum used to detect errors in clients,
993    * it is highly unlikely to encounter clients that send more than
994    * several kilobytes at once.
995    */
996   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
998   /*
999    * The maximum size of the body as specified by Content-Length.
1000    * This is only a theoretical maximum, the actual limit is subject
1001    * to the limits of the file system used for +Dir.tmpdir+.
1002    */
1003   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
1005   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
1007   init_common_fields();
1008   SET_GLOBAL(g_http_host, "HOST");
1009   SET_GLOBAL(g_http_trailer, "TRAILER");
1010   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
1011   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1012   SET_GLOBAL(g_http_connection, "CONNECTION");
1013   id_set_backtrace = rb_intern("set_backtrace");
1014   init_unicorn_httpdate();
1016 #ifndef HAVE_RB_HASH_CLEAR
1017   id_clear = rb_intern("clear");
1018 #endif
1019   id_is_chunked_p = rb_intern("is_chunked?");
1021 #undef SET_GLOBAL