http: move response_start_sent into the C ext
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
bloba5f069d9ed593efdbedc3a2dc45b344e29001fea
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 */
30 /* all of these flags need to be set for keepalive to be supported */
31 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
33 static unsigned int MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
35 /* this is only intended for use with Rainbows! */
36 static VALUE set_maxhdrlen(VALUE self, VALUE len)
38   return UINT2NUM(MAX_HEADER_LEN = NUM2UINT(len));
41 /* keep this small for Rainbows! since every client has one */
42 struct http_parser {
43   int cs; /* Ragel internal state */
44   unsigned int flags;
45   unsigned int mark;
46   unsigned int offset;
47   union { /* these 2 fields don't nest */
48     unsigned int field;
49     unsigned int query;
50   } start;
51   union {
52     unsigned int field_len; /* only used during header processing */
53     unsigned int dest_offset; /* only used during body processing */
54   } s;
55   VALUE buf;
56   VALUE env;
57   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
58   union {
59     off_t content;
60     off_t chunk;
61   } len;
64 static ID id_set_backtrace;
66 #ifdef HAVE_RB_HASH_CLEAR /* Ruby >= 2.0 */
67 #  define my_hash_clear(h) (void)rb_hash_clear(h)
68 #else /* !HAVE_RB_HASH_CLEAR - Ruby <= 1.9.3 */
70 static ID id_clear;
72 static void my_hash_clear(VALUE h)
74   rb_funcall(h, id_clear, 0);
76 #endif /* HAVE_RB_HASH_CLEAR */
78 static void finalize_header(struct http_parser *hp);
80 static void parser_raise(VALUE klass, const char *msg)
82   VALUE exc = rb_exc_new2(klass, msg);
83   VALUE bt = rb_ary_new();
85   rb_funcall(exc, id_set_backtrace, 1, bt);
86   rb_exc_raise(exc);
89 static inline unsigned int ulong2uint(unsigned long n)
91   unsigned int i = (unsigned int)n;
93   if (sizeof(unsigned int) != sizeof(unsigned long)) {
94     if ((unsigned long)i != n) {
95       rb_raise(rb_eRangeError, "too large to be 32-bit uint: %lu", n);
96     }
97   }
98   return i;
101 #define REMAINING (unsigned long)(pe - p)
102 #define LEN(AT, FPC) (ulong2uint(FPC - buffer) - hp->AT)
103 #define MARK(M,FPC) (hp->M = ulong2uint((FPC) - buffer))
104 #define PTR_TO(F) (buffer + hp->F)
105 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
106 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
108 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
109 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
110 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
111 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
113 static int is_lws(char c)
115   return (c == ' ' || c == '\t');
118 static VALUE stripped_str_new(const char *str, long len)
120   long end;
122   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
124   return rb_str_new(str, end + 1);
128  * handles values of the "Connection:" header, keepalive is implied
129  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
130  * Additionally, we require GET/HEAD requests to support keepalive.
131  */
132 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
134   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
135     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
136     HP_FL_SET(hp, KAVERSION);
137   } else if (STR_CSTR_CASE_EQ(val, "close")) {
138     /*
139      * it doesn't matter what HTTP version or request method we have,
140      * if a client says "Connection: close", we disable keepalive
141      */
142     HP_FL_UNSET(hp, KAVERSION);
143   } else {
144     /*
145      * client could've sent anything, ignore it for now.  Maybe
146      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
147      * Raising an exception might be too mean...
148      */
149   }
152 static void
153 request_method(struct http_parser *hp, const char *ptr, size_t len)
155   VALUE v = rb_str_new(ptr, len);
157   rb_hash_aset(hp->env, g_request_method, v);
160 static void
161 http_version(struct http_parser *hp, const char *ptr, size_t len)
163   VALUE v;
165   HP_FL_SET(hp, HASHEADER);
167   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
168     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
169     HP_FL_SET(hp, KAVERSION);
170     v = g_http_11;
171   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
172     v = g_http_10;
173   } else {
174     v = rb_str_new(ptr, len);
175   }
176   rb_hash_aset(hp->env, g_server_protocol, v);
177   rb_hash_aset(hp->env, g_http_version, v);
180 static inline void hp_invalid_if_trailer(struct http_parser *hp)
182   if (HP_FL_TEST(hp, INTRAILER))
183     parser_raise(eHttpParserError, "invalid Trailer");
186 static void write_cont_value(struct http_parser *hp,
187                              char *buffer, const char *p)
189   char *vptr;
190   long end;
191   long len = LEN(mark, p);
192   long cont_len;
194   if (hp->cont == Qfalse)
195      parser_raise(eHttpParserError, "invalid continuation line");
196   if (NIL_P(hp->cont))
197      return; /* we're ignoring this header (probably Host:) */
199   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
200   assert(hp->mark > 0 && "impossible continuation line offset");
202   if (len == 0)
203     return;
205   cont_len = RSTRING_LEN(hp->cont);
206   if (cont_len > 0) {
207     --hp->mark;
208     len = LEN(mark, p);
209   }
210   vptr = PTR_TO(mark);
212   /* normalize tab to space */
213   if (cont_len > 0) {
214     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
215     *vptr = ' ';
216   }
218   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
219   rb_str_buf_cat(hp->cont, vptr, end + 1);
222 static void write_value(struct http_parser *hp,
223                         const char *buffer, const char *p)
225   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
226   VALUE v;
227   VALUE e;
229   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
230   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
231   if (NIL_P(f)) {
232     const char *field = PTR_TO(start.field);
233     size_t flen = hp->s.field_len;
235     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
237     /*
238      * ignore "Version" headers since they conflict with the HTTP_VERSION
239      * rack env variable.
240      */
241     if (CONST_MEM_EQ("VERSION", field, flen)) {
242       hp->cont = Qnil;
243       return;
244     }
245     f = uncommon_field(field, flen);
246   } else if (f == g_http_connection) {
247     hp_keepalive_connection(hp, v);
248   } else if (f == g_content_length) {
249     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
250     if (hp->len.content < 0)
251       parser_raise(eHttpParserError, "invalid Content-Length");
252     if (hp->len.content != 0)
253       HP_FL_SET(hp, HASBODY);
254     hp_invalid_if_trailer(hp);
255   } else if (f == g_http_transfer_encoding) {
256     if (STR_CSTR_CASE_EQ(v, "chunked")) {
257       HP_FL_SET(hp, CHUNKED);
258       HP_FL_SET(hp, HASBODY);
259     }
260     hp_invalid_if_trailer(hp);
261   } else if (f == g_http_trailer) {
262     HP_FL_SET(hp, HASTRAILER);
263     hp_invalid_if_trailer(hp);
264   } else {
265     assert(TYPE(f) == T_STRING && "memoized object is not a string");
266     assert_frozen(f);
267   }
269   e = rb_hash_aref(hp->env, f);
270   if (NIL_P(e)) {
271     hp->cont = rb_hash_aset(hp->env, f, v);
272   } else if (f == g_http_host) {
273     /*
274      * ignored, absolute URLs in REQUEST_URI take precedence over
275      * the Host: header (ref: rfc 2616, section 5.2.1)
276      */
277      hp->cont = Qnil;
278   } else {
279     rb_str_buf_cat(e, ",", 1);
280     hp->cont = rb_str_buf_append(e, v);
281   }
284 /** Machine **/
287   machine http_parser;
289   action mark {MARK(mark, fpc); }
291   action start_field { MARK(start.field, fpc); }
292   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
293   action downcase_char { downcase_char(deconst(fpc)); }
294   action write_field { hp->s.field_len = LEN(start.field, fpc); }
295   action start_value { MARK(mark, fpc); }
296   action write_value { write_value(hp, buffer, fpc); }
297   action write_cont_value { write_cont_value(hp, buffer, fpc); }
298   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
299   action scheme {
300     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
301   }
302   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
303   action request_uri {
304     VALUE str;
306     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
307     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
308     /*
309      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
310      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
311      */
312     if (STR_CSTR_EQ(str, "*")) {
313       str = rb_str_new(NULL, 0);
314       rb_hash_aset(hp->env, g_path_info, str);
315       rb_hash_aset(hp->env, g_request_path, str);
316     }
317   }
318   action fragment {
319     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
320     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
321   }
322   action start_query {MARK(start.query, fpc); }
323   action query_string {
324     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
325     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
326   }
327   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
328   action request_path {
329     VALUE val;
331     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
332     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
334     /* rack says PATH_INFO must start with "/" or be empty */
335     if (!STR_CSTR_EQ(val, "*"))
336       rb_hash_aset(hp->env, g_path_info, val);
337   }
338   action add_to_chunk_size {
339     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
340     if (hp->len.chunk < 0)
341       parser_raise(eHttpParserError, "invalid chunk size");
342   }
343   action header_done {
344     finalize_header(hp);
346     cs = http_parser_first_final;
347     if (HP_FL_TEST(hp, HASBODY)) {
348       HP_FL_SET(hp, INBODY);
349       if (HP_FL_TEST(hp, CHUNKED))
350         cs = http_parser_en_ChunkedBody;
351     } else {
352       HP_FL_SET(hp, REQEOF);
353       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
354     }
355     /*
356      * go back to Ruby so we can call the Rack application, we'll reenter
357      * the parser iff the body needs to be processed.
358      */
359     goto post_exec;
360   }
362   action end_trailers {
363     cs = http_parser_first_final;
364     goto post_exec;
365   }
367   action end_chunked_body {
368     HP_FL_SET(hp, INTRAILER);
369     cs = http_parser_en_Trailers;
370     ++p;
371     assert(p <= pe && "buffer overflow after chunked body");
372     goto post_exec;
373   }
375   action skip_chunk_data {
376   skip_chunk_data_hack: {
377     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
378     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
379     hp->s.dest_offset += nr;
380     hp->len.chunk -= nr;
381     p += nr;
382     assert(hp->len.chunk >= 0 && "negative chunk length");
383     if ((size_t)hp->len.chunk > REMAINING) {
384       HP_FL_SET(hp, INCHUNK);
385       goto post_exec;
386     } else {
387       fhold;
388       fgoto chunk_end;
389     }
390   }}
392   include unicorn_http_common "unicorn_http_common.rl";
395 /** Data **/
396 %% write data;
398 static void http_parser_init(struct http_parser *hp)
400   int cs = 0;
401   hp->flags = 0;
402   hp->mark = 0;
403   hp->offset = 0;
404   hp->start.field = 0;
405   hp->s.field_len = 0;
406   hp->len.content = 0;
407   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
408   %% write init;
409   hp->cs = cs;
412 /** exec **/
413 static void
414 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
416   const char *p, *pe;
417   int cs = hp->cs;
418   size_t off = hp->offset;
420   if (cs == http_parser_first_final)
421     return;
423   assert(off <= len && "offset past end of buffer");
425   p = buffer+off;
426   pe = buffer+len;
428   assert((void *)(pe - p) == (void *)(len - off) &&
429          "pointers aren't same distance");
431   if (HP_FL_TEST(hp, INCHUNK)) {
432     HP_FL_UNSET(hp, INCHUNK);
433     goto skip_chunk_data_hack;
434   }
435   %% write exec;
436 post_exec: /* "_out:" also goes here */
437   if (hp->cs != http_parser_error)
438     hp->cs = cs;
439   hp->offset = ulong2uint(p - buffer);
441   assert(p <= pe && "buffer overflow after parsing execute");
442   assert(hp->offset <= len && "offset longer than length");
445 static struct http_parser *data_get(VALUE self)
447   struct http_parser *hp;
449   Data_Get_Struct(self, struct http_parser, hp);
450   assert(hp && "failed to extract http_parser struct");
451   return hp;
455  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
456  * this resembles the Rack::Request#scheme method as of rack commit
457  * 35bb5ba6746b5d346de9202c004cc926039650c7
458  */
459 static void set_url_scheme(VALUE env, VALUE *server_port)
461   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
463   if (NIL_P(scheme)) {
464     /*
465      * would anybody be horribly opposed to removing the X-Forwarded-SSL
466      * and X-Forwarded-Proto handling from this parser?  We've had it
467      * forever and nobody has said anything against it, either.
468      * Anyways, please send comments to our public mailing list:
469      * unicorn-public@bogomips.org (no HTML mail, no subscription necessary)
470      */
471     scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
472     if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
473       *server_port = g_port_443;
474       scheme = g_https;
475     } else {
476       scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
477       if (NIL_P(scheme)) {
478         scheme = g_http;
479       } else {
480         long len = RSTRING_LEN(scheme);
481         if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
482           if (len != 5)
483             scheme = g_https;
484           *server_port = g_port_443;
485         } else {
486           scheme = g_http;
487         }
488       }
489     }
490     rb_hash_aset(env, g_rack_url_scheme, scheme);
491   } else if (STR_CSTR_EQ(scheme, "https")) {
492     *server_port = g_port_443;
493   } else {
494     assert(*server_port == g_port_80 && "server_port not set");
495   }
499  * Parse and set the SERVER_NAME and SERVER_PORT variables
500  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
501  * anybody who needs them is using an unsupported configuration and/or
502  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
503  * fine.
504  */
505 static void set_server_vars(VALUE env, VALUE *server_port)
507   VALUE server_name = g_localhost;
508   VALUE host = rb_hash_aref(env, g_http_host);
510   if (!NIL_P(host)) {
511     char *host_ptr = RSTRING_PTR(host);
512     long host_len = RSTRING_LEN(host);
513     char *colon;
515     if (*host_ptr == '[') { /* ipv6 address format */
516       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
518       if (rbracket)
519         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
520       else
521         colon = memchr(host_ptr + 1, ':', host_len - 1);
522     } else {
523       colon = memchr(host_ptr, ':', host_len);
524     }
526     if (colon) {
527       long port_start = colon - host_ptr + 1;
529       server_name = rb_str_substr(host, 0, colon - host_ptr);
530       if ((host_len - port_start) > 0)
531         *server_port = rb_str_substr(host, port_start, host_len);
532     } else {
533       server_name = host;
534     }
535   }
536   rb_hash_aset(env, g_server_name, server_name);
537   rb_hash_aset(env, g_server_port, *server_port);
540 static void finalize_header(struct http_parser *hp)
542   VALUE server_port = g_port_80;
544   set_url_scheme(hp->env, &server_port);
545   set_server_vars(hp->env, &server_port);
547   if (!HP_FL_TEST(hp, HASHEADER))
548     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
550   /* rack requires QUERY_STRING */
551   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
552     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
555 static void hp_mark(void *ptr)
557   struct http_parser *hp = ptr;
559   rb_gc_mark(hp->buf);
560   rb_gc_mark(hp->env);
561   rb_gc_mark(hp->cont);
564 static VALUE HttpParser_alloc(VALUE klass)
566   struct http_parser *hp;
567   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
572  * call-seq:
573  *    parser.new => parser
575  * Creates a new parser.
576  */
577 static VALUE HttpParser_init(VALUE self)
579   struct http_parser *hp = data_get(self);
581   http_parser_init(hp);
582   hp->buf = rb_str_new(NULL, 0);
583   hp->env = rb_hash_new();
585   return self;
589  * call-seq:
590  *    parser.clear => parser
592  * Resets the parser to it's initial state so that you can reuse it
593  * rather than making new ones.
594  */
595 static VALUE HttpParser_clear(VALUE self)
597   struct http_parser *hp = data_get(self);
599   http_parser_init(hp);
600   my_hash_clear(hp->env);
602   return self;
605 static void advance_str(VALUE str, off_t nr)
607   long len = RSTRING_LEN(str);
609   if (len == 0)
610     return;
612   rb_str_modify(str);
614   assert(nr <= len && "trying to advance past end of buffer");
615   len -= nr;
616   if (len > 0) /* unlikely, len is usually 0 */
617     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
618   rb_str_set_len(str, len);
622  * call-seq:
623  *   parser.content_length => nil or Integer
625  * Returns the number of bytes left to run through HttpParser#filter_body.
626  * This will initially be the value of the "Content-Length" HTTP header
627  * after header parsing is complete and will decrease in value as
628  * HttpParser#filter_body is called for each chunk.  This should return
629  * zero for requests with no body.
631  * This will return nil on "Transfer-Encoding: chunked" requests.
632  */
633 static VALUE HttpParser_content_length(VALUE self)
635   struct http_parser *hp = data_get(self);
637   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
641  * Document-method: parse
642  * call-seq:
643  *    parser.parse => env or nil
645  * Takes a Hash and a String of data, parses the String of data filling
646  * in the Hash returning the Hash if parsing is finished, nil otherwise
647  * When returning the env Hash, it may modify data to point to where
648  * body processing should begin.
650  * Raises HttpParserError if there are parsing errors.
651  */
652 static VALUE HttpParser_parse(VALUE self)
654   struct http_parser *hp = data_get(self);
655   VALUE data = hp->buf;
657   if (HP_FL_TEST(hp, TO_CLEAR))
658     HttpParser_clear(self);
660   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
661   if (hp->offset > MAX_HEADER_LEN)
662     parser_raise(e413, "HTTP header is too large");
664   if (hp->cs == http_parser_first_final ||
665       hp->cs == http_parser_en_ChunkedBody) {
666     advance_str(data, hp->offset + 1);
667     hp->offset = 0;
668     if (HP_FL_TEST(hp, INTRAILER))
669       HP_FL_SET(hp, REQEOF);
671     return hp->env;
672   }
674   if (hp->cs == http_parser_error)
675     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
677   return Qnil;
681  * Document-method: parse
682  * call-seq:
683  *    parser.add_parse(buffer) => env or nil
685  * adds the contents of +buffer+ to the internal buffer and attempts to
686  * continue parsing.  Returns the +env+ Hash on success or nil if more
687  * data is needed.
689  * Raises HttpParserError if there are parsing errors.
690  */
691 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
693   struct http_parser *hp = data_get(self);
695   Check_Type(buffer, T_STRING);
696   rb_str_buf_append(hp->buf, buffer);
698   return HttpParser_parse(self);
702  * Document-method: trailers
703  * call-seq:
704  *    parser.trailers(req, data) => req or nil
706  * This is an alias for HttpParser#headers
707  */
710  * Document-method: headers
711  */
712 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
714   struct http_parser *hp = data_get(self);
716   hp->env = env;
717   hp->buf = buf;
719   return HttpParser_parse(self);
722 static int chunked_eof(struct http_parser *hp)
724   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
728  * call-seq:
729  *    parser.body_eof? => true or false
731  * Detects if we're done filtering the body or not.  This can be used
732  * to detect when to stop calling HttpParser#filter_body.
733  */
734 static VALUE HttpParser_body_eof(VALUE self)
736   struct http_parser *hp = data_get(self);
738   if (HP_FL_TEST(hp, CHUNKED))
739     return chunked_eof(hp) ? Qtrue : Qfalse;
741   return hp->len.content == 0 ? Qtrue : Qfalse;
745  * call-seq:
746  *    parser.keepalive? => true or false
748  * This should be used to detect if a request can really handle
749  * keepalives and pipelining.  Currently, the rules are:
751  * 1. MUST be a GET or HEAD request
752  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
753  * 3. MUST NOT have "Connection: close" set
754  */
755 static VALUE HttpParser_keepalive(VALUE self)
757   struct http_parser *hp = data_get(self);
759   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
763  * call-seq:
764  *    parser.next? => true or false
766  * Exactly like HttpParser#keepalive?, except it will reset the internal
767  * parser state on next parse if it returns true.
768  */
769 static VALUE HttpParser_next(VALUE self)
771   struct http_parser *hp = data_get(self);
773   if (HP_FL_ALL(hp, KEEPALIVE)) {
774     HP_FL_SET(hp, TO_CLEAR);
775     return Qtrue;
776   }
777   return Qfalse;
781  * call-seq:
782  *    parser.headers? => true or false
784  * This should be used to detect if a request has headers (and if
785  * the response will have headers as well).  HTTP/0.9 requests
786  * should return false, all subsequent HTTP versions will return true
787  */
788 static VALUE HttpParser_has_headers(VALUE self)
790   struct http_parser *hp = data_get(self);
792   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
795 static VALUE HttpParser_buf(VALUE self)
797   return data_get(self)->buf;
800 static VALUE HttpParser_env(VALUE self)
802   return data_get(self)->env;
806  * call-seq:
807  *    parser.filter_body(dst, src) => nil/src
809  * Takes a String of +src+, will modify data if dechunking is done.
810  * Returns +nil+ if there is more data left to process.  Returns
811  * +src+ if body processing is complete. When returning +src+,
812  * it may modify +src+ so the start of the string points to where
813  * the body ended so that trailer processing can begin.
815  * Raises HttpParserError if there are dechunking errors.
816  * Basically this is a glorified memcpy(3) that copies +src+
817  * into +buf+ while filtering it through the dechunker.
818  */
819 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
821   struct http_parser *hp = data_get(self);
822   char *srcptr;
823   long srclen;
825   srcptr = RSTRING_PTR(src);
826   srclen = RSTRING_LEN(src);
828   StringValue(dst);
830   if (HP_FL_TEST(hp, CHUNKED)) {
831     if (!chunked_eof(hp)) {
832       rb_str_modify(dst);
833       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
835       hp->s.dest_offset = 0;
836       hp->cont = dst;
837       hp->buf = src;
838       http_parser_execute(hp, srcptr, srclen);
839       if (hp->cs == http_parser_error)
840         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
842       assert(hp->s.dest_offset <= hp->offset &&
843              "destination buffer overflow");
844       advance_str(src, hp->offset);
845       rb_str_set_len(dst, hp->s.dest_offset);
847       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
848         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
849       } else {
850         src = Qnil;
851       }
852     }
853   } else {
854     /* no need to enter the Ragel machine for unchunked transfers */
855     assert(hp->len.content >= 0 && "negative Content-Length");
856     if (hp->len.content > 0) {
857       long nr = MIN(srclen, hp->len.content);
859       rb_str_modify(dst);
860       rb_str_resize(dst, nr);
861       /*
862        * using rb_str_replace() to avoid memcpy() doesn't help in
863        * most cases because a GC-aware programmer will pass an explicit
864        * buffer to env["rack.input"].read and reuse the buffer in a loop.
865        * This causes copy-on-write behavior to be triggered anyways
866        * when the +src+ buffer is modified (when reading off the socket).
867        */
868       hp->buf = src;
869       memcpy(RSTRING_PTR(dst), srcptr, nr);
870       hp->len.content -= nr;
871       if (hp->len.content == 0) {
872         HP_FL_SET(hp, REQEOF);
873         hp->cs = http_parser_first_final;
874       }
875       advance_str(src, nr);
876       src = Qnil;
877     }
878   }
879   hp->offset = 0; /* for trailer parsing */
880   return src;
883 static VALUE HttpParser_rssset(VALUE self, VALUE boolean)
885   struct http_parser *hp = data_get(self);
887   if (RTEST(boolean))
888     HP_FL_SET(hp, RESSTART);
889   else
890     HP_FL_UNSET(hp, RESSTART);
892   return boolean; /* ignored by Ruby anyways */
895 static VALUE HttpParser_rssget(VALUE self)
897   struct http_parser *hp = data_get(self);
899   return HP_FL_TEST(hp, RESSTART) ? Qtrue : Qfalse;
902 #define SET_GLOBAL(var,str) do { \
903   var = find_common_field(str, sizeof(str) - 1); \
904   assert(!NIL_P(var) && "missed global field"); \
905 } while (0)
907 void Init_unicorn_http(void)
909   VALUE mUnicorn, cHttpParser;
911   mUnicorn = rb_define_module("Unicorn");
912   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
913   eHttpParserError =
914          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
915   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
916                                eHttpParserError);
917   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
918                                eHttpParserError);
920   init_globals();
921   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
922   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
923   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
924   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
925   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
926   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
927   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
928   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
929   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
930   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
931   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
932   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
933   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
934   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
935   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
936   rb_define_method(cHttpParser, "response_start_sent=", HttpParser_rssset, 1);
937   rb_define_method(cHttpParser, "response_start_sent", HttpParser_rssget, 0);
939   /*
940    * The maximum size a single chunk when using chunked transfer encoding.
941    * This is only a theoretical maximum used to detect errors in clients,
942    * it is highly unlikely to encounter clients that send more than
943    * several kilobytes at once.
944    */
945   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
947   /*
948    * The maximum size of the body as specified by Content-Length.
949    * This is only a theoretical maximum, the actual limit is subject
950    * to the limits of the file system used for +Dir.tmpdir+.
951    */
952   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
954   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
956   init_common_fields();
957   SET_GLOBAL(g_http_host, "HOST");
958   SET_GLOBAL(g_http_trailer, "TRAILER");
959   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
960   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
961   SET_GLOBAL(g_http_connection, "CONNECTION");
962   id_set_backtrace = rb_intern("set_backtrace");
963   init_unicorn_httpdate();
965 #ifndef HAVE_RB_HASH_CLEAR
966   id_clear = rb_intern("clear");
967 #endif
969 #undef SET_GLOBAL