http: -Wshorten-64-to-32 warnings on clang
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blobde836528c1bafb375d556be3da93e7eeeccc3cff
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
29 /* all of these flags need to be set for keepalive to be supported */
30 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
32 static unsigned int MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
34 /* this is only intended for use with Rainbows! */
35 static VALUE set_maxhdrlen(VALUE self, VALUE len)
37   return UINT2NUM(MAX_HEADER_LEN = NUM2UINT(len));
40 /* keep this small for Rainbows! since every client has one */
41 struct http_parser {
42   int cs; /* Ragel internal state */
43   unsigned int flags;
44   unsigned int mark;
45   unsigned int offset;
46   union { /* these 2 fields don't nest */
47     unsigned int field;
48     unsigned int query;
49   } start;
50   union {
51     unsigned int field_len; /* only used during header processing */
52     unsigned int dest_offset; /* only used during body processing */
53   } s;
54   VALUE buf;
55   VALUE env;
56   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
57   union {
58     off_t content;
59     off_t chunk;
60   } len;
63 static ID id_clear, id_set_backtrace, id_response_start_sent;
65 static void finalize_header(struct http_parser *hp);
67 static void parser_raise(VALUE klass, const char *msg)
69   VALUE exc = rb_exc_new2(klass, msg);
70   VALUE bt = rb_ary_new();
72   rb_funcall(exc, id_set_backtrace, 1, bt);
73   rb_exc_raise(exc);
76 static inline unsigned int ulong2uint(unsigned long n)
78   unsigned int i = (unsigned int)n;
80   if (sizeof(unsigned int) != sizeof(unsigned long)) {
81     if ((unsigned long)i != n) {
82       rb_raise(rb_eRangeError, "too large to be 32-bit uint: %lu", n);
83     }
84   }
85   return i;
88 #define REMAINING (unsigned long)(pe - p)
89 #define LEN(AT, FPC) (ulong2uint(FPC - buffer) - hp->AT)
90 #define MARK(M,FPC) (hp->M = ulong2uint((FPC) - buffer))
91 #define PTR_TO(F) (buffer + hp->F)
92 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
93 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
95 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
96 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
97 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
98 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
100 static int is_lws(char c)
102   return (c == ' ' || c == '\t');
105 static VALUE stripped_str_new(const char *str, long len)
107   long end;
109   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
111   return rb_str_new(str, end + 1);
115  * handles values of the "Connection:" header, keepalive is implied
116  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
117  * Additionally, we require GET/HEAD requests to support keepalive.
118  */
119 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
121   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
122     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
123     HP_FL_SET(hp, KAVERSION);
124   } else if (STR_CSTR_CASE_EQ(val, "close")) {
125     /*
126      * it doesn't matter what HTTP version or request method we have,
127      * if a client says "Connection: close", we disable keepalive
128      */
129     HP_FL_UNSET(hp, KAVERSION);
130   } else {
131     /*
132      * client could've sent anything, ignore it for now.  Maybe
133      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
134      * Raising an exception might be too mean...
135      */
136   }
139 static void
140 request_method(struct http_parser *hp, const char *ptr, size_t len)
142   VALUE v = rb_str_new(ptr, len);
144   rb_hash_aset(hp->env, g_request_method, v);
147 static void
148 http_version(struct http_parser *hp, const char *ptr, size_t len)
150   VALUE v;
152   HP_FL_SET(hp, HASHEADER);
154   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
155     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
156     HP_FL_SET(hp, KAVERSION);
157     v = g_http_11;
158   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
159     v = g_http_10;
160   } else {
161     v = rb_str_new(ptr, len);
162   }
163   rb_hash_aset(hp->env, g_server_protocol, v);
164   rb_hash_aset(hp->env, g_http_version, v);
167 static inline void hp_invalid_if_trailer(struct http_parser *hp)
169   if (HP_FL_TEST(hp, INTRAILER))
170     parser_raise(eHttpParserError, "invalid Trailer");
173 static void write_cont_value(struct http_parser *hp,
174                              char *buffer, const char *p)
176   char *vptr;
177   long end;
178   long len = LEN(mark, p);
179   long cont_len;
181   if (hp->cont == Qfalse)
182      parser_raise(eHttpParserError, "invalid continuation line");
183   if (NIL_P(hp->cont))
184      return; /* we're ignoring this header (probably Host:) */
186   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
187   assert(hp->mark > 0 && "impossible continuation line offset");
189   if (len == 0)
190     return;
192   cont_len = RSTRING_LEN(hp->cont);
193   if (cont_len > 0) {
194     --hp->mark;
195     len = LEN(mark, p);
196   }
197   vptr = PTR_TO(mark);
199   /* normalize tab to space */
200   if (cont_len > 0) {
201     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
202     *vptr = ' ';
203   }
205   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
206   rb_str_buf_cat(hp->cont, vptr, end + 1);
209 static void write_value(struct http_parser *hp,
210                         const char *buffer, const char *p)
212   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
213   VALUE v;
214   VALUE e;
216   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
217   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
218   if (NIL_P(f)) {
219     const char *field = PTR_TO(start.field);
220     size_t flen = hp->s.field_len;
222     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
224     /*
225      * ignore "Version" headers since they conflict with the HTTP_VERSION
226      * rack env variable.
227      */
228     if (CONST_MEM_EQ("VERSION", field, flen)) {
229       hp->cont = Qnil;
230       return;
231     }
232     f = uncommon_field(field, flen);
233   } else if (f == g_http_connection) {
234     hp_keepalive_connection(hp, v);
235   } else if (f == g_content_length) {
236     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
237     if (hp->len.content < 0)
238       parser_raise(eHttpParserError, "invalid Content-Length");
239     if (hp->len.content != 0)
240       HP_FL_SET(hp, HASBODY);
241     hp_invalid_if_trailer(hp);
242   } else if (f == g_http_transfer_encoding) {
243     if (STR_CSTR_CASE_EQ(v, "chunked")) {
244       HP_FL_SET(hp, CHUNKED);
245       HP_FL_SET(hp, HASBODY);
246     }
247     hp_invalid_if_trailer(hp);
248   } else if (f == g_http_trailer) {
249     HP_FL_SET(hp, HASTRAILER);
250     hp_invalid_if_trailer(hp);
251   } else {
252     assert(TYPE(f) == T_STRING && "memoized object is not a string");
253     assert_frozen(f);
254   }
256   e = rb_hash_aref(hp->env, f);
257   if (NIL_P(e)) {
258     hp->cont = rb_hash_aset(hp->env, f, v);
259   } else if (f == g_http_host) {
260     /*
261      * ignored, absolute URLs in REQUEST_URI take precedence over
262      * the Host: header (ref: rfc 2616, section 5.2.1)
263      */
264      hp->cont = Qnil;
265   } else {
266     rb_str_buf_cat(e, ",", 1);
267     hp->cont = rb_str_buf_append(e, v);
268   }
271 /** Machine **/
274   machine http_parser;
276   action mark {MARK(mark, fpc); }
278   action start_field { MARK(start.field, fpc); }
279   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
280   action downcase_char { downcase_char(deconst(fpc)); }
281   action write_field { hp->s.field_len = LEN(start.field, fpc); }
282   action start_value { MARK(mark, fpc); }
283   action write_value { write_value(hp, buffer, fpc); }
284   action write_cont_value { write_cont_value(hp, buffer, fpc); }
285   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
286   action scheme {
287     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
288   }
289   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
290   action request_uri {
291     VALUE str;
293     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
294     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
295     /*
296      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
297      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
298      */
299     if (STR_CSTR_EQ(str, "*")) {
300       str = rb_str_new(NULL, 0);
301       rb_hash_aset(hp->env, g_path_info, str);
302       rb_hash_aset(hp->env, g_request_path, str);
303     }
304   }
305   action fragment {
306     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
307     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
308   }
309   action start_query {MARK(start.query, fpc); }
310   action query_string {
311     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
312     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
313   }
314   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
315   action request_path {
316     VALUE val;
318     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
319     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
321     /* rack says PATH_INFO must start with "/" or be empty */
322     if (!STR_CSTR_EQ(val, "*"))
323       rb_hash_aset(hp->env, g_path_info, val);
324   }
325   action add_to_chunk_size {
326     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
327     if (hp->len.chunk < 0)
328       parser_raise(eHttpParserError, "invalid chunk size");
329   }
330   action header_done {
331     finalize_header(hp);
333     cs = http_parser_first_final;
334     if (HP_FL_TEST(hp, HASBODY)) {
335       HP_FL_SET(hp, INBODY);
336       if (HP_FL_TEST(hp, CHUNKED))
337         cs = http_parser_en_ChunkedBody;
338     } else {
339       HP_FL_SET(hp, REQEOF);
340       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
341     }
342     /*
343      * go back to Ruby so we can call the Rack application, we'll reenter
344      * the parser iff the body needs to be processed.
345      */
346     goto post_exec;
347   }
349   action end_trailers {
350     cs = http_parser_first_final;
351     goto post_exec;
352   }
354   action end_chunked_body {
355     HP_FL_SET(hp, INTRAILER);
356     cs = http_parser_en_Trailers;
357     ++p;
358     assert(p <= pe && "buffer overflow after chunked body");
359     goto post_exec;
360   }
362   action skip_chunk_data {
363   skip_chunk_data_hack: {
364     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
365     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
366     hp->s.dest_offset += nr;
367     hp->len.chunk -= nr;
368     p += nr;
369     assert(hp->len.chunk >= 0 && "negative chunk length");
370     if ((size_t)hp->len.chunk > REMAINING) {
371       HP_FL_SET(hp, INCHUNK);
372       goto post_exec;
373     } else {
374       fhold;
375       fgoto chunk_end;
376     }
377   }}
379   include unicorn_http_common "unicorn_http_common.rl";
382 /** Data **/
383 %% write data;
385 static void http_parser_init(struct http_parser *hp)
387   int cs = 0;
388   hp->flags = 0;
389   hp->mark = 0;
390   hp->offset = 0;
391   hp->start.field = 0;
392   hp->s.field_len = 0;
393   hp->len.content = 0;
394   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
395   %% write init;
396   hp->cs = cs;
399 /** exec **/
400 static void
401 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
403   const char *p, *pe;
404   int cs = hp->cs;
405   size_t off = hp->offset;
407   if (cs == http_parser_first_final)
408     return;
410   assert(off <= len && "offset past end of buffer");
412   p = buffer+off;
413   pe = buffer+len;
415   assert((void *)(pe - p) == (void *)(len - off) &&
416          "pointers aren't same distance");
418   if (HP_FL_TEST(hp, INCHUNK)) {
419     HP_FL_UNSET(hp, INCHUNK);
420     goto skip_chunk_data_hack;
421   }
422   %% write exec;
423 post_exec: /* "_out:" also goes here */
424   if (hp->cs != http_parser_error)
425     hp->cs = cs;
426   hp->offset = ulong2uint(p - buffer);
428   assert(p <= pe && "buffer overflow after parsing execute");
429   assert(hp->offset <= len && "offset longer than length");
432 static struct http_parser *data_get(VALUE self)
434   struct http_parser *hp;
436   Data_Get_Struct(self, struct http_parser, hp);
437   assert(hp && "failed to extract http_parser struct");
438   return hp;
442  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
443  * this resembles the Rack::Request#scheme method as of rack commit
444  * 35bb5ba6746b5d346de9202c004cc926039650c7
445  */
446 static void set_url_scheme(VALUE env, VALUE *server_port)
448   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
450   if (NIL_P(scheme)) {
451     /*
452      * would anybody be horribly opposed to removing the X-Forwarded-SSL
453      * and X-Forwarded-Proto handling from this parser?  We've had it
454      * forever and nobody has said anything against it, either.
455      * Anyways, please send comments to our public mailing list:
456      * unicorn-public@bogomips.org (no HTML mail, no subscription necessary)
457      */
458     scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
459     if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
460       *server_port = g_port_443;
461       scheme = g_https;
462     } else {
463       scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
464       if (NIL_P(scheme)) {
465         scheme = g_http;
466       } else {
467         long len = RSTRING_LEN(scheme);
468         if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
469           if (len != 5)
470             scheme = g_https;
471           *server_port = g_port_443;
472         } else {
473           scheme = g_http;
474         }
475       }
476     }
477     rb_hash_aset(env, g_rack_url_scheme, scheme);
478   } else if (STR_CSTR_EQ(scheme, "https")) {
479     *server_port = g_port_443;
480   } else {
481     assert(*server_port == g_port_80 && "server_port not set");
482   }
486  * Parse and set the SERVER_NAME and SERVER_PORT variables
487  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
488  * anybody who needs them is using an unsupported configuration and/or
489  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
490  * fine.
491  */
492 static void set_server_vars(VALUE env, VALUE *server_port)
494   VALUE server_name = g_localhost;
495   VALUE host = rb_hash_aref(env, g_http_host);
497   if (!NIL_P(host)) {
498     char *host_ptr = RSTRING_PTR(host);
499     long host_len = RSTRING_LEN(host);
500     char *colon;
502     if (*host_ptr == '[') { /* ipv6 address format */
503       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
505       if (rbracket)
506         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
507       else
508         colon = memchr(host_ptr + 1, ':', host_len - 1);
509     } else {
510       colon = memchr(host_ptr, ':', host_len);
511     }
513     if (colon) {
514       long port_start = colon - host_ptr + 1;
516       server_name = rb_str_substr(host, 0, colon - host_ptr);
517       if ((host_len - port_start) > 0)
518         *server_port = rb_str_substr(host, port_start, host_len);
519     } else {
520       server_name = host;
521     }
522   }
523   rb_hash_aset(env, g_server_name, server_name);
524   rb_hash_aset(env, g_server_port, *server_port);
527 static void finalize_header(struct http_parser *hp)
529   VALUE server_port = g_port_80;
531   set_url_scheme(hp->env, &server_port);
532   set_server_vars(hp->env, &server_port);
534   if (!HP_FL_TEST(hp, HASHEADER))
535     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
537   /* rack requires QUERY_STRING */
538   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
539     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
542 static void hp_mark(void *ptr)
544   struct http_parser *hp = ptr;
546   rb_gc_mark(hp->buf);
547   rb_gc_mark(hp->env);
548   rb_gc_mark(hp->cont);
551 static VALUE HttpParser_alloc(VALUE klass)
553   struct http_parser *hp;
554   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
559  * call-seq:
560  *    parser.new => parser
562  * Creates a new parser.
563  */
564 static VALUE HttpParser_init(VALUE self)
566   struct http_parser *hp = data_get(self);
568   http_parser_init(hp);
569   hp->buf = rb_str_new(NULL, 0);
570   hp->env = rb_hash_new();
572   return self;
576  * call-seq:
577  *    parser.clear => parser
579  * Resets the parser to it's initial state so that you can reuse it
580  * rather than making new ones.
581  */
582 static VALUE HttpParser_clear(VALUE self)
584   struct http_parser *hp = data_get(self);
586   http_parser_init(hp);
587   rb_funcall(hp->env, id_clear, 0);
588   rb_ivar_set(self, id_response_start_sent, Qfalse);
590   return self;
594  * call-seq:
595  *    parser.dechunk! => parser
597  * Resets the parser to a state suitable for dechunking response bodies
599  */
600 static VALUE HttpParser_dechunk_bang(VALUE self)
602   struct http_parser *hp = data_get(self);
604   http_parser_init(hp);
606   /*
607    * we don't care about trailers in dechunk-only mode,
608    * but if we did we'd set UH_FL_HASTRAILER and clear hp->env
609    */
610   if (0) {
611     rb_funcall(hp->env, id_clear, 0);
612     hp->flags = UH_FL_HASTRAILER;
613   }
615   hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED;
616   hp->cs = http_parser_en_ChunkedBody;
618   return self;
622  * call-seq:
623  *    parser.reset => nil
625  * Resets the parser to it's initial state so that you can reuse it
626  * rather than making new ones.
628  * This method is deprecated and to be removed in Unicorn 4.x
629  */
630 static VALUE HttpParser_reset(VALUE self)
632   static int warned;
634   if (!warned) {
635     rb_warn("Unicorn::HttpParser#reset is deprecated; "
636             "use Unicorn::HttpParser#clear instead");
637   }
638   HttpParser_clear(self);
639   return Qnil;
642 static void advance_str(VALUE str, off_t nr)
644   long len = RSTRING_LEN(str);
646   if (len == 0)
647     return;
649   rb_str_modify(str);
651   assert(nr <= len && "trying to advance past end of buffer");
652   len -= nr;
653   if (len > 0) /* unlikely, len is usually 0 */
654     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
655   rb_str_set_len(str, len);
659  * call-seq:
660  *   parser.content_length => nil or Integer
662  * Returns the number of bytes left to run through HttpParser#filter_body.
663  * This will initially be the value of the "Content-Length" HTTP header
664  * after header parsing is complete and will decrease in value as
665  * HttpParser#filter_body is called for each chunk.  This should return
666  * zero for requests with no body.
668  * This will return nil on "Transfer-Encoding: chunked" requests.
669  */
670 static VALUE HttpParser_content_length(VALUE self)
672   struct http_parser *hp = data_get(self);
674   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
678  * Document-method: parse
679  * call-seq:
680  *    parser.parse => env or nil
682  * Takes a Hash and a String of data, parses the String of data filling
683  * in the Hash returning the Hash if parsing is finished, nil otherwise
684  * When returning the env Hash, it may modify data to point to where
685  * body processing should begin.
687  * Raises HttpParserError if there are parsing errors.
688  */
689 static VALUE HttpParser_parse(VALUE self)
691   struct http_parser *hp = data_get(self);
692   VALUE data = hp->buf;
694   if (HP_FL_TEST(hp, TO_CLEAR))
695     HttpParser_clear(self);
697   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
698   if (hp->offset > MAX_HEADER_LEN)
699     parser_raise(e413, "HTTP header is too large");
701   if (hp->cs == http_parser_first_final ||
702       hp->cs == http_parser_en_ChunkedBody) {
703     advance_str(data, hp->offset + 1);
704     hp->offset = 0;
705     if (HP_FL_TEST(hp, INTRAILER))
706       HP_FL_SET(hp, REQEOF);
708     return hp->env;
709   }
711   if (hp->cs == http_parser_error)
712     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
714   return Qnil;
718  * Document-method: parse
719  * call-seq:
720  *    parser.add_parse(buffer) => env or nil
722  * adds the contents of +buffer+ to the internal buffer and attempts to
723  * continue parsing.  Returns the +env+ Hash on success or nil if more
724  * data is needed.
726  * Raises HttpParserError if there are parsing errors.
727  */
728 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
730   struct http_parser *hp = data_get(self);
732   Check_Type(buffer, T_STRING);
733   rb_str_buf_append(hp->buf, buffer);
735   return HttpParser_parse(self);
739  * Document-method: trailers
740  * call-seq:
741  *    parser.trailers(req, data) => req or nil
743  * This is an alias for HttpParser#headers
744  */
747  * Document-method: headers
748  */
749 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
751   struct http_parser *hp = data_get(self);
753   hp->env = env;
754   hp->buf = buf;
756   return HttpParser_parse(self);
759 static int chunked_eof(struct http_parser *hp)
761   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
765  * call-seq:
766  *    parser.body_eof? => true or false
768  * Detects if we're done filtering the body or not.  This can be used
769  * to detect when to stop calling HttpParser#filter_body.
770  */
771 static VALUE HttpParser_body_eof(VALUE self)
773   struct http_parser *hp = data_get(self);
775   if (HP_FL_TEST(hp, CHUNKED))
776     return chunked_eof(hp) ? Qtrue : Qfalse;
778   return hp->len.content == 0 ? Qtrue : Qfalse;
782  * call-seq:
783  *    parser.keepalive? => true or false
785  * This should be used to detect if a request can really handle
786  * keepalives and pipelining.  Currently, the rules are:
788  * 1. MUST be a GET or HEAD request
789  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
790  * 3. MUST NOT have "Connection: close" set
791  */
792 static VALUE HttpParser_keepalive(VALUE self)
794   struct http_parser *hp = data_get(self);
796   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
800  * call-seq:
801  *    parser.next? => true or false
803  * Exactly like HttpParser#keepalive?, except it will reset the internal
804  * parser state on next parse if it returns true.
805  */
806 static VALUE HttpParser_next(VALUE self)
808   struct http_parser *hp = data_get(self);
810   if (HP_FL_ALL(hp, KEEPALIVE)) {
811     HP_FL_SET(hp, TO_CLEAR);
812     return Qtrue;
813   }
814   return Qfalse;
818  * call-seq:
819  *    parser.headers? => true or false
821  * This should be used to detect if a request has headers (and if
822  * the response will have headers as well).  HTTP/0.9 requests
823  * should return false, all subsequent HTTP versions will return true
824  */
825 static VALUE HttpParser_has_headers(VALUE self)
827   struct http_parser *hp = data_get(self);
829   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
832 static VALUE HttpParser_buf(VALUE self)
834   return data_get(self)->buf;
837 static VALUE HttpParser_env(VALUE self)
839   return data_get(self)->env;
843  * call-seq:
844  *    parser.filter_body(dst, src) => nil/src
846  * Takes a String of +src+, will modify data if dechunking is done.
847  * Returns +nil+ if there is more data left to process.  Returns
848  * +src+ if body processing is complete. When returning +src+,
849  * it may modify +src+ so the start of the string points to where
850  * the body ended so that trailer processing can begin.
852  * Raises HttpParserError if there are dechunking errors.
853  * Basically this is a glorified memcpy(3) that copies +src+
854  * into +buf+ while filtering it through the dechunker.
855  */
856 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
858   struct http_parser *hp = data_get(self);
859   char *srcptr;
860   long srclen;
862   srcptr = RSTRING_PTR(src);
863   srclen = RSTRING_LEN(src);
865   StringValue(dst);
867   if (HP_FL_TEST(hp, CHUNKED)) {
868     if (!chunked_eof(hp)) {
869       rb_str_modify(dst);
870       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
872       hp->s.dest_offset = 0;
873       hp->cont = dst;
874       hp->buf = src;
875       http_parser_execute(hp, srcptr, srclen);
876       if (hp->cs == http_parser_error)
877         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
879       assert(hp->s.dest_offset <= hp->offset &&
880              "destination buffer overflow");
881       advance_str(src, hp->offset);
882       rb_str_set_len(dst, hp->s.dest_offset);
884       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
885         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
886       } else {
887         src = Qnil;
888       }
889     }
890   } else {
891     /* no need to enter the Ragel machine for unchunked transfers */
892     assert(hp->len.content >= 0 && "negative Content-Length");
893     if (hp->len.content > 0) {
894       long nr = MIN(srclen, hp->len.content);
896       rb_str_modify(dst);
897       rb_str_resize(dst, nr);
898       /*
899        * using rb_str_replace() to avoid memcpy() doesn't help in
900        * most cases because a GC-aware programmer will pass an explicit
901        * buffer to env["rack.input"].read and reuse the buffer in a loop.
902        * This causes copy-on-write behavior to be triggered anyways
903        * when the +src+ buffer is modified (when reading off the socket).
904        */
905       hp->buf = src;
906       memcpy(RSTRING_PTR(dst), srcptr, nr);
907       hp->len.content -= nr;
908       if (hp->len.content == 0) {
909         HP_FL_SET(hp, REQEOF);
910         hp->cs = http_parser_first_final;
911       }
912       advance_str(src, nr);
913       src = Qnil;
914     }
915   }
916   hp->offset = 0; /* for trailer parsing */
917   return src;
920 #define SET_GLOBAL(var,str) do { \
921   var = find_common_field(str, sizeof(str) - 1); \
922   assert(!NIL_P(var) && "missed global field"); \
923 } while (0)
925 void Init_unicorn_http(void)
927   VALUE mUnicorn, cHttpParser;
929   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
930   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
931   eHttpParserError =
932          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
933   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
934                                eHttpParserError);
935   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
936                                eHttpParserError);
938   init_globals();
939   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
940   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
941   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
942   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
943   rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0);
944   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
945   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
946   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
947   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
948   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
949   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
950   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
951   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
952   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
953   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
954   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
955   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
957   /*
958    * The maximum size a single chunk when using chunked transfer encoding.
959    * This is only a theoretical maximum used to detect errors in clients,
960    * it is highly unlikely to encounter clients that send more than
961    * several kilobytes at once.
962    */
963   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
965   /*
966    * The maximum size of the body as specified by Content-Length.
967    * This is only a theoretical maximum, the actual limit is subject
968    * to the limits of the file system used for +Dir.tmpdir+.
969    */
970   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
972   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
974   init_common_fields();
975   SET_GLOBAL(g_http_host, "HOST");
976   SET_GLOBAL(g_http_trailer, "TRAILER");
977   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
978   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
979   SET_GLOBAL(g_http_connection, "CONNECTION");
980   id_clear = rb_intern("clear");
981   id_set_backtrace = rb_intern("set_backtrace");
982   id_response_start_sent = rb_intern("@response_start_sent");
983   init_unicorn_httpdate();
985 #undef SET_GLOBAL