doc: s/bogomips.org/yhbt.net/g
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blobdfe3a6337fad1f64233a10e73651acddd3e4b5c3
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;
67 #ifdef HAVE_RB_HASH_CLEAR /* Ruby >= 2.0 */
68 #  define my_hash_clear(h) (void)rb_hash_clear(h)
69 #else /* !HAVE_RB_HASH_CLEAR - Ruby <= 1.9.3 */
71 static ID id_clear;
73 static void my_hash_clear(VALUE h)
75   rb_funcall(h, id_clear, 0);
77 #endif /* HAVE_RB_HASH_CLEAR */
79 static void finalize_header(struct http_parser *hp);
81 static void parser_raise(VALUE klass, const char *msg)
83   VALUE exc = rb_exc_new2(klass, msg);
84   VALUE bt = rb_ary_new();
86   rb_funcall(exc, id_set_backtrace, 1, bt);
87   rb_exc_raise(exc);
90 static inline unsigned int ulong2uint(unsigned long n)
92   unsigned int i = (unsigned int)n;
94   if (sizeof(unsigned int) != sizeof(unsigned long)) {
95     if ((unsigned long)i != n) {
96       rb_raise(rb_eRangeError, "too large to be 32-bit uint: %lu", n);
97     }
98   }
99   return i;
102 #define REMAINING (unsigned long)(pe - p)
103 #define LEN(AT, FPC) (ulong2uint(FPC - buffer) - hp->AT)
104 #define MARK(M,FPC) (hp->M = ulong2uint((FPC) - buffer))
105 #define PTR_TO(F) (buffer + hp->F)
106 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
107 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
109 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
110 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
111 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
112 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
114 static int is_lws(char c)
116   return (c == ' ' || c == '\t');
119 static VALUE stripped_str_new(const char *str, long len)
121   long end;
123   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
125   return rb_str_new(str, end + 1);
129  * handles values of the "Connection:" header, keepalive is implied
130  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
131  * Additionally, we require GET/HEAD requests to support keepalive.
132  */
133 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
135   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
136     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
137     HP_FL_SET(hp, KAVERSION);
138   } else if (STR_CSTR_CASE_EQ(val, "close")) {
139     /*
140      * it doesn't matter what HTTP version or request method we have,
141      * if a client says "Connection: close", we disable keepalive
142      */
143     HP_FL_UNSET(hp, KAVERSION);
144   } else {
145     /*
146      * client could've sent anything, ignore it for now.  Maybe
147      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
148      * Raising an exception might be too mean...
149      */
150   }
153 static void
154 request_method(struct http_parser *hp, const char *ptr, size_t len)
156   VALUE v = rb_str_new(ptr, len);
158   rb_hash_aset(hp->env, g_request_method, v);
161 static void
162 http_version(struct http_parser *hp, const char *ptr, size_t len)
164   VALUE v;
166   HP_FL_SET(hp, HASHEADER);
168   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
169     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
170     HP_FL_SET(hp, KAVERSION);
171     v = g_http_11;
172   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
173     v = g_http_10;
174   } else {
175     v = rb_str_new(ptr, len);
176   }
177   rb_hash_aset(hp->env, g_server_protocol, v);
178   rb_hash_aset(hp->env, g_http_version, v);
181 static inline void hp_invalid_if_trailer(struct http_parser *hp)
183   if (HP_FL_TEST(hp, INTRAILER))
184     parser_raise(eHttpParserError, "invalid Trailer");
187 static void write_cont_value(struct http_parser *hp,
188                              char *buffer, const char *p)
190   char *vptr;
191   long end;
192   long len = LEN(mark, p);
193   long cont_len;
195   if (hp->cont == Qfalse)
196      parser_raise(eHttpParserError, "invalid continuation line");
197   if (NIL_P(hp->cont))
198      return; /* we're ignoring this header (probably Host:) */
200   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
201   assert(hp->mark > 0 && "impossible continuation line offset");
203   if (len == 0)
204     return;
206   cont_len = RSTRING_LEN(hp->cont);
207   if (cont_len > 0) {
208     --hp->mark;
209     len = LEN(mark, p);
210   }
211   vptr = PTR_TO(mark);
213   /* normalize tab to space */
214   if (cont_len > 0) {
215     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
216     *vptr = ' ';
217   }
219   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
220   rb_str_buf_cat(hp->cont, vptr, end + 1);
223 static void write_value(struct http_parser *hp,
224                         const char *buffer, const char *p)
226   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
227   VALUE v;
228   VALUE e;
230   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
231   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
232   if (NIL_P(f)) {
233     const char *field = PTR_TO(start.field);
234     size_t flen = hp->s.field_len;
236     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
238     /*
239      * ignore "Version" headers since they conflict with the HTTP_VERSION
240      * rack env variable.
241      */
242     if (CONST_MEM_EQ("VERSION", field, flen)) {
243       hp->cont = Qnil;
244       return;
245     }
246     f = uncommon_field(field, flen);
247   } else if (f == g_http_connection) {
248     hp_keepalive_connection(hp, v);
249   } else if (f == g_content_length) {
250     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
251     if (hp->len.content < 0)
252       parser_raise(eHttpParserError, "invalid Content-Length");
253     if (hp->len.content != 0)
254       HP_FL_SET(hp, HASBODY);
255     hp_invalid_if_trailer(hp);
256   } else if (f == g_http_transfer_encoding) {
257     if (STR_CSTR_CASE_EQ(v, "chunked")) {
258       HP_FL_SET(hp, CHUNKED);
259       HP_FL_SET(hp, HASBODY);
260     }
261     hp_invalid_if_trailer(hp);
262   } else if (f == g_http_trailer) {
263     HP_FL_SET(hp, HASTRAILER);
264     hp_invalid_if_trailer(hp);
265   } else {
266     assert(TYPE(f) == T_STRING && "memoized object is not a string");
267     assert_frozen(f);
268   }
270   e = rb_hash_aref(hp->env, f);
271   if (NIL_P(e)) {
272     hp->cont = rb_hash_aset(hp->env, f, v);
273   } else if (f == g_http_host) {
274     /*
275      * ignored, absolute URLs in REQUEST_URI take precedence over
276      * the Host: header (ref: rfc 2616, section 5.2.1)
277      */
278      hp->cont = Qnil;
279   } else {
280     rb_str_buf_cat(e, ",", 1);
281     hp->cont = rb_str_buf_append(e, v);
282   }
285 /** Machine **/
288   machine http_parser;
290   action mark {MARK(mark, fpc); }
292   action start_field { MARK(start.field, fpc); }
293   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
294   action downcase_char { downcase_char(deconst(fpc)); }
295   action write_field { hp->s.field_len = LEN(start.field, fpc); }
296   action start_value { MARK(mark, fpc); }
297   action write_value { write_value(hp, buffer, fpc); }
298   action write_cont_value { write_cont_value(hp, buffer, fpc); }
299   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
300   action scheme {
301     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
302   }
303   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
304   action request_uri {
305     VALUE str;
307     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
308     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
309     /*
310      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
311      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
312      */
313     if (STR_CSTR_EQ(str, "*")) {
314       str = rb_str_new(NULL, 0);
315       rb_hash_aset(hp->env, g_path_info, str);
316       rb_hash_aset(hp->env, g_request_path, str);
317     }
318   }
319   action fragment {
320     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
321     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
322   }
323   action start_query {MARK(start.query, fpc); }
324   action query_string {
325     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
326     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
327   }
328   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
329   action request_path {
330     VALUE val;
332     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
333     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
335     /* rack says PATH_INFO must start with "/" or be empty */
336     if (!STR_CSTR_EQ(val, "*"))
337       rb_hash_aset(hp->env, g_path_info, val);
338   }
339   action add_to_chunk_size {
340     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
341     if (hp->len.chunk < 0)
342       parser_raise(eHttpParserError, "invalid chunk size");
343   }
344   action header_done {
345     finalize_header(hp);
347     cs = http_parser_first_final;
348     if (HP_FL_TEST(hp, HASBODY)) {
349       HP_FL_SET(hp, INBODY);
350       if (HP_FL_TEST(hp, CHUNKED))
351         cs = http_parser_en_ChunkedBody;
352     } else {
353       HP_FL_SET(hp, REQEOF);
354       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
355     }
356     /*
357      * go back to Ruby so we can call the Rack application, we'll reenter
358      * the parser iff the body needs to be processed.
359      */
360     goto post_exec;
361   }
363   action end_trailers {
364     cs = http_parser_first_final;
365     goto post_exec;
366   }
368   action end_chunked_body {
369     HP_FL_SET(hp, INTRAILER);
370     cs = http_parser_en_Trailers;
371     ++p;
372     assert(p <= pe && "buffer overflow after chunked body");
373     goto post_exec;
374   }
376   action skip_chunk_data {
377   skip_chunk_data_hack: {
378     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
379     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
380     hp->s.dest_offset += nr;
381     hp->len.chunk -= nr;
382     p += nr;
383     assert(hp->len.chunk >= 0 && "negative chunk length");
384     if ((size_t)hp->len.chunk > REMAINING) {
385       HP_FL_SET(hp, INCHUNK);
386       goto post_exec;
387     } else {
388       fhold;
389       fgoto chunk_end;
390     }
391   }}
393   include unicorn_http_common "unicorn_http_common.rl";
396 /** Data **/
397 %% write data;
399 static void http_parser_init(struct http_parser *hp)
401   int cs = 0;
402   hp->flags = 0;
403   hp->mark = 0;
404   hp->offset = 0;
405   hp->start.field = 0;
406   hp->s.field_len = 0;
407   hp->len.content = 0;
408   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
409   %% write init;
410   hp->cs = cs;
413 /** exec **/
414 static void
415 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
417   const char *p, *pe;
418   int cs = hp->cs;
419   size_t off = hp->offset;
421   if (cs == http_parser_first_final)
422     return;
424   assert(off <= len && "offset past end of buffer");
426   p = buffer+off;
427   pe = buffer+len;
429   assert((void *)(pe - p) == (void *)(len - off) &&
430          "pointers aren't same distance");
432   if (HP_FL_TEST(hp, INCHUNK)) {
433     HP_FL_UNSET(hp, INCHUNK);
434     goto skip_chunk_data_hack;
435   }
436   %% write exec;
437 post_exec: /* "_out:" also goes here */
438   if (hp->cs != http_parser_error)
439     hp->cs = cs;
440   hp->offset = ulong2uint(p - buffer);
442   assert(p <= pe && "buffer overflow after parsing execute");
443   assert(hp->offset <= len && "offset longer than length");
446 static void hp_mark(void *ptr)
448   struct http_parser *hp = ptr;
450   rb_gc_mark(hp->buf);
451   rb_gc_mark(hp->env);
452   rb_gc_mark(hp->cont);
455 static size_t hp_memsize(const void *ptr)
457   return sizeof(struct http_parser);
460 static const rb_data_type_t hp_type = {
461   "unicorn_http",
462   { hp_mark, RUBY_TYPED_DEFAULT_FREE, hp_memsize, /* reserved */ },
463   /* parent, data, [ flags ] */
466 static struct http_parser *data_get(VALUE self)
468   struct http_parser *hp;
470   TypedData_Get_Struct(self, struct http_parser, &hp_type, hp);
471   assert(hp && "failed to extract http_parser struct");
472   return hp;
476  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
477  * this resembles the Rack::Request#scheme method as of rack commit
478  * 35bb5ba6746b5d346de9202c004cc926039650c7
479  */
480 static void set_url_scheme(VALUE env, VALUE *server_port)
482   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
484   if (NIL_P(scheme)) {
485     /*
486      * would anybody be horribly opposed to removing the X-Forwarded-SSL
487      * and X-Forwarded-Proto handling from this parser?  We've had it
488      * forever and nobody has said anything against it, either.
489      * Anyways, please send comments to our public mailing list:
490      * unicorn-public@yhbt.net (no HTML mail, no subscription necessary)
491      */
492     scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
493     if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
494       *server_port = g_port_443;
495       scheme = g_https;
496     } else {
497       scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
498       if (NIL_P(scheme)) {
499         scheme = g_http;
500       } else {
501         long len = RSTRING_LEN(scheme);
502         if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
503           if (len != 5)
504             scheme = g_https;
505           *server_port = g_port_443;
506         } else {
507           scheme = g_http;
508         }
509       }
510     }
511     rb_hash_aset(env, g_rack_url_scheme, scheme);
512   } else if (STR_CSTR_EQ(scheme, "https")) {
513     *server_port = g_port_443;
514   } else {
515     assert(*server_port == g_port_80 && "server_port not set");
516   }
520  * Parse and set the SERVER_NAME and SERVER_PORT variables
521  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
522  * anybody who needs them is using an unsupported configuration and/or
523  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
524  * fine.
525  */
526 static void set_server_vars(VALUE env, VALUE *server_port)
528   VALUE server_name = g_localhost;
529   VALUE host = rb_hash_aref(env, g_http_host);
531   if (!NIL_P(host)) {
532     char *host_ptr = RSTRING_PTR(host);
533     long host_len = RSTRING_LEN(host);
534     char *colon;
536     if (*host_ptr == '[') { /* ipv6 address format */
537       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
539       if (rbracket)
540         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
541       else
542         colon = memchr(host_ptr + 1, ':', host_len - 1);
543     } else {
544       colon = memchr(host_ptr, ':', host_len);
545     }
547     if (colon) {
548       long port_start = colon - host_ptr + 1;
550       server_name = rb_str_substr(host, 0, colon - host_ptr);
551       if ((host_len - port_start) > 0)
552         *server_port = rb_str_substr(host, port_start, host_len);
553     } else {
554       server_name = host;
555     }
556   }
557   rb_hash_aset(env, g_server_name, server_name);
558   rb_hash_aset(env, g_server_port, *server_port);
561 static void finalize_header(struct http_parser *hp)
563   VALUE server_port = g_port_80;
565   set_url_scheme(hp->env, &server_port);
566   set_server_vars(hp->env, &server_port);
568   if (!HP_FL_TEST(hp, HASHEADER))
569     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
571   /* rack requires QUERY_STRING */
572   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
573     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
576 static VALUE HttpParser_alloc(VALUE klass)
578   struct http_parser *hp;
580   return TypedData_Make_Struct(klass, struct http_parser, &hp_type, hp);
584  * call-seq:
585  *    parser.new => parser
587  * Creates a new parser.
588  */
589 static VALUE HttpParser_init(VALUE self)
591   struct http_parser *hp = data_get(self);
593   http_parser_init(hp);
594   hp->buf = rb_str_new(NULL, 0);
595   hp->env = rb_hash_new();
597   return self;
601  * call-seq:
602  *    parser.clear => parser
604  * Resets the parser to it's initial state so that you can reuse it
605  * rather than making new ones.
606  */
607 static VALUE HttpParser_clear(VALUE self)
609   struct http_parser *hp = data_get(self);
611   /* we can't safely reuse .buf and .env if hijacked */
612   if (HP_FL_TEST(hp, HIJACK))
613     return HttpParser_init(self);
615   http_parser_init(hp);
616   my_hash_clear(hp->env);
618   return self;
621 static void advance_str(VALUE str, off_t nr)
623   long len = RSTRING_LEN(str);
625   if (len == 0)
626     return;
628   rb_str_modify(str);
630   assert(nr <= len && "trying to advance past end of buffer");
631   len -= nr;
632   if (len > 0) /* unlikely, len is usually 0 */
633     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
634   rb_str_set_len(str, len);
638  * call-seq:
639  *   parser.content_length => nil or Integer
641  * Returns the number of bytes left to run through HttpParser#filter_body.
642  * This will initially be the value of the "Content-Length" HTTP header
643  * after header parsing is complete and will decrease in value as
644  * HttpParser#filter_body is called for each chunk.  This should return
645  * zero for requests with no body.
647  * This will return nil on "Transfer-Encoding: chunked" requests.
648  */
649 static VALUE HttpParser_content_length(VALUE self)
651   struct http_parser *hp = data_get(self);
653   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
657  * Document-method: parse
658  * call-seq:
659  *    parser.parse => env or nil
661  * Takes a Hash and a String of data, parses the String of data filling
662  * in the Hash returning the Hash if parsing is finished, nil otherwise
663  * When returning the env Hash, it may modify data to point to where
664  * body processing should begin.
666  * Raises HttpParserError if there are parsing errors.
667  */
668 static VALUE HttpParser_parse(VALUE self)
670   struct http_parser *hp = data_get(self);
671   VALUE data = hp->buf;
673   if (HP_FL_TEST(hp, TO_CLEAR))
674     HttpParser_clear(self);
676   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
677   if (hp->offset > MAX_HEADER_LEN)
678     parser_raise(e413, "HTTP header is too large");
680   if (hp->cs == http_parser_first_final ||
681       hp->cs == http_parser_en_ChunkedBody) {
682     advance_str(data, hp->offset + 1);
683     hp->offset = 0;
684     if (HP_FL_TEST(hp, INTRAILER))
685       HP_FL_SET(hp, REQEOF);
687     return hp->env;
688   }
690   if (hp->cs == http_parser_error)
691     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
693   return Qnil;
697  * Document-method: parse
698  * call-seq:
699  *    parser.add_parse(buffer) => env or nil
701  * adds the contents of +buffer+ to the internal buffer and attempts to
702  * continue parsing.  Returns the +env+ Hash on success or nil if more
703  * data is needed.
705  * Raises HttpParserError if there are parsing errors.
706  */
707 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
709   struct http_parser *hp = data_get(self);
711   Check_Type(buffer, T_STRING);
712   rb_str_buf_append(hp->buf, buffer);
714   return HttpParser_parse(self);
718  * Document-method: trailers
719  * call-seq:
720  *    parser.trailers(req, data) => req or nil
722  * This is an alias for HttpParser#headers
723  */
726  * Document-method: headers
727  */
728 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
730   struct http_parser *hp = data_get(self);
732   hp->env = env;
733   hp->buf = buf;
735   return HttpParser_parse(self);
738 static int chunked_eof(struct http_parser *hp)
740   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
744  * call-seq:
745  *    parser.body_eof? => true or false
747  * Detects if we're done filtering the body or not.  This can be used
748  * to detect when to stop calling HttpParser#filter_body.
749  */
750 static VALUE HttpParser_body_eof(VALUE self)
752   struct http_parser *hp = data_get(self);
754   if (HP_FL_TEST(hp, CHUNKED))
755     return chunked_eof(hp) ? Qtrue : Qfalse;
757   return hp->len.content == 0 ? Qtrue : Qfalse;
761  * call-seq:
762  *    parser.keepalive? => true or false
764  * This should be used to detect if a request can really handle
765  * keepalives and pipelining.  Currently, the rules are:
767  * 1. MUST be a GET or HEAD request
768  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
769  * 3. MUST NOT have "Connection: close" set
770  */
771 static VALUE HttpParser_keepalive(VALUE self)
773   struct http_parser *hp = data_get(self);
775   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
779  * call-seq:
780  *    parser.next? => true or false
782  * Exactly like HttpParser#keepalive?, except it will reset the internal
783  * parser state on next parse if it returns true.
784  */
785 static VALUE HttpParser_next(VALUE self)
787   struct http_parser *hp = data_get(self);
789   if (HP_FL_ALL(hp, KEEPALIVE)) {
790     HP_FL_SET(hp, TO_CLEAR);
791     return Qtrue;
792   }
793   return Qfalse;
797  * call-seq:
798  *    parser.headers? => true or false
800  * This should be used to detect if a request has headers (and if
801  * the response will have headers as well).  HTTP/0.9 requests
802  * should return false, all subsequent HTTP versions will return true
803  */
804 static VALUE HttpParser_has_headers(VALUE self)
806   struct http_parser *hp = data_get(self);
808   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
811 static VALUE HttpParser_buf(VALUE self)
813   return data_get(self)->buf;
816 static VALUE HttpParser_env(VALUE self)
818   return data_get(self)->env;
821 static VALUE HttpParser_hijacked_bang(VALUE self)
823   struct http_parser *hp = data_get(self);
825   HP_FL_SET(hp, HIJACK);
827   return self;
831  * call-seq:
832  *    parser.filter_body(dst, src) => nil/src
834  * Takes a String of +src+, will modify data if dechunking is done.
835  * Returns +nil+ if there is more data left to process.  Returns
836  * +src+ if body processing is complete. When returning +src+,
837  * it may modify +src+ so the start of the string points to where
838  * the body ended so that trailer processing can begin.
840  * Raises HttpParserError if there are dechunking errors.
841  * Basically this is a glorified memcpy(3) that copies +src+
842  * into +buf+ while filtering it through the dechunker.
843  */
844 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
846   struct http_parser *hp = data_get(self);
847   char *srcptr;
848   long srclen;
850   srcptr = RSTRING_PTR(src);
851   srclen = RSTRING_LEN(src);
853   StringValue(dst);
855   if (HP_FL_TEST(hp, CHUNKED)) {
856     if (!chunked_eof(hp)) {
857       rb_str_modify(dst);
858       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
860       hp->s.dest_offset = 0;
861       hp->cont = dst;
862       hp->buf = src;
863       http_parser_execute(hp, srcptr, srclen);
864       if (hp->cs == http_parser_error)
865         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
867       assert(hp->s.dest_offset <= hp->offset &&
868              "destination buffer overflow");
869       advance_str(src, hp->offset);
870       rb_str_set_len(dst, hp->s.dest_offset);
872       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
873         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
874       } else {
875         src = Qnil;
876       }
877     }
878   } else {
879     /* no need to enter the Ragel machine for unchunked transfers */
880     assert(hp->len.content >= 0 && "negative Content-Length");
881     if (hp->len.content > 0) {
882       long nr = MIN(srclen, hp->len.content);
884       rb_str_modify(dst);
885       rb_str_resize(dst, nr);
886       /*
887        * using rb_str_replace() to avoid memcpy() doesn't help in
888        * most cases because a GC-aware programmer will pass an explicit
889        * buffer to env["rack.input"].read and reuse the buffer in a loop.
890        * This causes copy-on-write behavior to be triggered anyways
891        * when the +src+ buffer is modified (when reading off the socket).
892        */
893       hp->buf = src;
894       memcpy(RSTRING_PTR(dst), srcptr, nr);
895       hp->len.content -= nr;
896       if (hp->len.content == 0) {
897         HP_FL_SET(hp, REQEOF);
898         hp->cs = http_parser_first_final;
899       }
900       advance_str(src, nr);
901       src = Qnil;
902     }
903   }
904   hp->offset = 0; /* for trailer parsing */
905   return src;
908 static VALUE HttpParser_rssset(VALUE self, VALUE boolean)
910   struct http_parser *hp = data_get(self);
912   if (RTEST(boolean))
913     HP_FL_SET(hp, RESSTART);
914   else
915     HP_FL_UNSET(hp, RESSTART);
917   return boolean; /* ignored by Ruby anyways */
920 static VALUE HttpParser_rssget(VALUE self)
922   struct http_parser *hp = data_get(self);
924   return HP_FL_TEST(hp, RESSTART) ? Qtrue : Qfalse;
927 #define SET_GLOBAL(var,str) do { \
928   var = find_common_field(str, sizeof(str) - 1); \
929   assert(!NIL_P(var) && "missed global field"); \
930 } while (0)
932 void Init_unicorn_http(void)
934   VALUE mUnicorn, cHttpParser;
936   mUnicorn = rb_define_module("Unicorn");
937   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
938   eHttpParserError =
939          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
940   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
941                                eHttpParserError);
942   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
943                                eHttpParserError);
945   init_globals();
946   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
947   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
948   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
949   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
950   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
951   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
952   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
953   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
954   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
955   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
956   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
957   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
958   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
959   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
960   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
961   rb_define_method(cHttpParser, "hijacked!", HttpParser_hijacked_bang, 0);
962   rb_define_method(cHttpParser, "response_start_sent=", HttpParser_rssset, 1);
963   rb_define_method(cHttpParser, "response_start_sent", HttpParser_rssget, 0);
965   /*
966    * The maximum size a single chunk when using chunked transfer encoding.
967    * This is only a theoretical maximum used to detect errors in clients,
968    * it is highly unlikely to encounter clients that send more than
969    * several kilobytes at once.
970    */
971   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
973   /*
974    * The maximum size of the body as specified by Content-Length.
975    * This is only a theoretical maximum, the actual limit is subject
976    * to the limits of the file system used for +Dir.tmpdir+.
977    */
978   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
980   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
982   init_common_fields();
983   SET_GLOBAL(g_http_host, "HOST");
984   SET_GLOBAL(g_http_trailer, "TRAILER");
985   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
986   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
987   SET_GLOBAL(g_http_connection, "CONNECTION");
988   id_set_backtrace = rb_intern("set_backtrace");
989   init_unicorn_httpdate();
991 #ifndef HAVE_RB_HASH_CLEAR
992   id_clear = rb_intern("clear");
993 #endif
995 #undef SET_GLOBAL