require 'pp' if $DEBUG is set by Rack app
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blob357440b51f3e350875f10b47e1dec0623c8bd14e
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(VALUE mark_ary);
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 other servers (e.g. yahns) 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 void hp_mark(void *ptr)
447   struct http_parser *hp = ptr;
449   rb_gc_mark(hp->buf);
450   rb_gc_mark(hp->env);
451   rb_gc_mark(hp->cont);
454 static size_t hp_memsize(const void *ptr)
456   return sizeof(struct http_parser);
459 static const rb_data_type_t hp_type = {
460   "unicorn_http",
461   { hp_mark, RUBY_TYPED_DEFAULT_FREE, hp_memsize, /* reserved */ },
462   /* parent, data, [ flags ] */
465 static struct http_parser *data_get(VALUE self)
467   struct http_parser *hp;
469   TypedData_Get_Struct(self, struct http_parser, &hp_type, hp);
470   assert(hp && "failed to extract http_parser struct");
471   return hp;
475  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
476  * this resembles the Rack::Request#scheme method as of rack commit
477  * 35bb5ba6746b5d346de9202c004cc926039650c7
478  */
479 static void set_url_scheme(VALUE env, VALUE *server_port)
481   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
483   if (NIL_P(scheme)) {
484     /*
485      * would anybody be horribly opposed to removing the X-Forwarded-SSL
486      * and X-Forwarded-Proto handling from this parser?  We've had it
487      * forever and nobody has said anything against it, either.
488      * Anyways, please send comments to our public mailing list:
489      * unicorn-public@bogomips.org (no HTML mail, no subscription necessary)
490      */
491     scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
492     if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
493       *server_port = g_port_443;
494       scheme = g_https;
495     } else {
496       scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
497       if (NIL_P(scheme)) {
498         scheme = g_http;
499       } else {
500         long len = RSTRING_LEN(scheme);
501         if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
502           if (len != 5)
503             scheme = g_https;
504           *server_port = g_port_443;
505         } else {
506           scheme = g_http;
507         }
508       }
509     }
510     rb_hash_aset(env, g_rack_url_scheme, scheme);
511   } else if (STR_CSTR_EQ(scheme, "https")) {
512     *server_port = g_port_443;
513   } else {
514     assert(*server_port == g_port_80 && "server_port not set");
515   }
519  * Parse and set the SERVER_NAME and SERVER_PORT variables
520  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
521  * anybody who needs them is using an unsupported configuration and/or
522  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
523  * fine.
524  */
525 static void set_server_vars(VALUE env, VALUE *server_port)
527   VALUE server_name = g_localhost;
528   VALUE host = rb_hash_aref(env, g_http_host);
530   if (!NIL_P(host)) {
531     char *host_ptr = RSTRING_PTR(host);
532     long host_len = RSTRING_LEN(host);
533     char *colon;
535     if (*host_ptr == '[') { /* ipv6 address format */
536       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
538       if (rbracket)
539         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
540       else
541         colon = memchr(host_ptr + 1, ':', host_len - 1);
542     } else {
543       colon = memchr(host_ptr, ':', host_len);
544     }
546     if (colon) {
547       long port_start = colon - host_ptr + 1;
549       server_name = rb_str_substr(host, 0, colon - host_ptr);
550       if ((host_len - port_start) > 0)
551         *server_port = rb_str_substr(host, port_start, host_len);
552     } else {
553       server_name = host;
554     }
555   }
556   rb_hash_aset(env, g_server_name, server_name);
557   rb_hash_aset(env, g_server_port, *server_port);
560 static void finalize_header(struct http_parser *hp)
562   VALUE server_port = g_port_80;
564   set_url_scheme(hp->env, &server_port);
565   set_server_vars(hp->env, &server_port);
567   if (!HP_FL_TEST(hp, HASHEADER))
568     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
570   /* rack requires QUERY_STRING */
571   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
572     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
575 static VALUE HttpParser_alloc(VALUE klass)
577   struct http_parser *hp;
579   return TypedData_Make_Struct(klass, struct http_parser, &hp_type, hp);
583  * call-seq:
584  *    parser.new => parser
586  * Creates a new parser.
587  */
588 static VALUE HttpParser_init(VALUE self)
590   struct http_parser *hp = data_get(self);
592   http_parser_init(hp);
593   hp->buf = rb_str_new(NULL, 0);
594   hp->env = rb_hash_new();
596   return self;
600  * call-seq:
601  *    parser.clear => parser
603  * Resets the parser to it's initial state so that you can reuse it
604  * rather than making new ones.
605  */
606 static VALUE HttpParser_clear(VALUE self)
608   struct http_parser *hp = data_get(self);
610   http_parser_init(hp);
611   my_hash_clear(hp->env);
613   return self;
616 static void advance_str(VALUE str, off_t nr)
618   long len = RSTRING_LEN(str);
620   if (len == 0)
621     return;
623   rb_str_modify(str);
625   assert(nr <= len && "trying to advance past end of buffer");
626   len -= nr;
627   if (len > 0) /* unlikely, len is usually 0 */
628     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
629   rb_str_set_len(str, len);
633  * call-seq:
634  *   parser.content_length => nil or Integer
636  * Returns the number of bytes left to run through HttpParser#filter_body.
637  * This will initially be the value of the "Content-Length" HTTP header
638  * after header parsing is complete and will decrease in value as
639  * HttpParser#filter_body is called for each chunk.  This should return
640  * zero for requests with no body.
642  * This will return nil on "Transfer-Encoding: chunked" requests.
643  */
644 static VALUE HttpParser_content_length(VALUE self)
646   struct http_parser *hp = data_get(self);
648   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
652  * Document-method: parse
653  * call-seq:
654  *    parser.parse => env or nil
656  * Takes a Hash and a String of data, parses the String of data filling
657  * in the Hash returning the Hash if parsing is finished, nil otherwise
658  * When returning the env Hash, it may modify data to point to where
659  * body processing should begin.
661  * Raises HttpParserError if there are parsing errors.
662  */
663 static VALUE HttpParser_parse(VALUE self)
665   struct http_parser *hp = data_get(self);
666   VALUE data = hp->buf;
668   if (HP_FL_TEST(hp, TO_CLEAR))
669     HttpParser_clear(self);
671   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
672   if (hp->offset > MAX_HEADER_LEN)
673     parser_raise(e413, "HTTP header is too large");
675   if (hp->cs == http_parser_first_final ||
676       hp->cs == http_parser_en_ChunkedBody) {
677     advance_str(data, hp->offset + 1);
678     hp->offset = 0;
679     if (HP_FL_TEST(hp, INTRAILER))
680       HP_FL_SET(hp, REQEOF);
682     return hp->env;
683   }
685   if (hp->cs == http_parser_error)
686     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
688   return Qnil;
692  * Document-method: parse
693  * call-seq:
694  *    parser.add_parse(buffer) => env or nil
696  * adds the contents of +buffer+ to the internal buffer and attempts to
697  * continue parsing.  Returns the +env+ Hash on success or nil if more
698  * data is needed.
700  * Raises HttpParserError if there are parsing errors.
701  */
702 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
704   struct http_parser *hp = data_get(self);
706   Check_Type(buffer, T_STRING);
707   rb_str_buf_append(hp->buf, buffer);
709   return HttpParser_parse(self);
713  * Document-method: trailers
714  * call-seq:
715  *    parser.trailers(req, data) => req or nil
717  * This is an alias for HttpParser#headers
718  */
721  * Document-method: headers
722  */
723 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
725   struct http_parser *hp = data_get(self);
727   hp->env = env;
728   hp->buf = buf;
730   return HttpParser_parse(self);
733 static int chunked_eof(struct http_parser *hp)
735   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
739  * call-seq:
740  *    parser.body_eof? => true or false
742  * Detects if we're done filtering the body or not.  This can be used
743  * to detect when to stop calling HttpParser#filter_body.
744  */
745 static VALUE HttpParser_body_eof(VALUE self)
747   struct http_parser *hp = data_get(self);
749   if (HP_FL_TEST(hp, CHUNKED))
750     return chunked_eof(hp) ? Qtrue : Qfalse;
752   return hp->len.content == 0 ? Qtrue : Qfalse;
756  * call-seq:
757  *    parser.keepalive? => true or false
759  * This should be used to detect if a request can really handle
760  * keepalives and pipelining.  Currently, the rules are:
762  * 1. MUST be a GET or HEAD request
763  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
764  * 3. MUST NOT have "Connection: close" set
765  */
766 static VALUE HttpParser_keepalive(VALUE self)
768   struct http_parser *hp = data_get(self);
770   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
774  * call-seq:
775  *    parser.next? => true or false
777  * Exactly like HttpParser#keepalive?, except it will reset the internal
778  * parser state on next parse if it returns true.
779  */
780 static VALUE HttpParser_next(VALUE self)
782   struct http_parser *hp = data_get(self);
784   if (HP_FL_ALL(hp, KEEPALIVE)) {
785     HP_FL_SET(hp, TO_CLEAR);
786     return Qtrue;
787   }
788   return Qfalse;
792  * call-seq:
793  *    parser.headers? => true or false
795  * This should be used to detect if a request has headers (and if
796  * the response will have headers as well).  HTTP/0.9 requests
797  * should return false, all subsequent HTTP versions will return true
798  */
799 static VALUE HttpParser_has_headers(VALUE self)
801   struct http_parser *hp = data_get(self);
803   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
806 static VALUE HttpParser_buf(VALUE self)
808   return data_get(self)->buf;
811 static VALUE HttpParser_env(VALUE self)
813   return data_get(self)->env;
817  * call-seq:
818  *    parser.filter_body(dst, src) => nil/src
820  * Takes a String of +src+, will modify data if dechunking is done.
821  * Returns +nil+ if there is more data left to process.  Returns
822  * +src+ if body processing is complete. When returning +src+,
823  * it may modify +src+ so the start of the string points to where
824  * the body ended so that trailer processing can begin.
826  * Raises HttpParserError if there are dechunking errors.
827  * Basically this is a glorified memcpy(3) that copies +src+
828  * into +buf+ while filtering it through the dechunker.
829  */
830 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
832   struct http_parser *hp = data_get(self);
833   char *srcptr;
834   long srclen;
836   srcptr = RSTRING_PTR(src);
837   srclen = RSTRING_LEN(src);
839   StringValue(dst);
841   if (HP_FL_TEST(hp, CHUNKED)) {
842     if (!chunked_eof(hp)) {
843       rb_str_modify(dst);
844       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
846       hp->s.dest_offset = 0;
847       hp->cont = dst;
848       hp->buf = src;
849       http_parser_execute(hp, srcptr, srclen);
850       if (hp->cs == http_parser_error)
851         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
853       assert(hp->s.dest_offset <= hp->offset &&
854              "destination buffer overflow");
855       advance_str(src, hp->offset);
856       rb_str_set_len(dst, hp->s.dest_offset);
858       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
859         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
860       } else {
861         src = Qnil;
862       }
863     }
864   } else {
865     /* no need to enter the Ragel machine for unchunked transfers */
866     assert(hp->len.content >= 0 && "negative Content-Length");
867     if (hp->len.content > 0) {
868       long nr = MIN(srclen, hp->len.content);
870       rb_str_modify(dst);
871       rb_str_resize(dst, nr);
872       /*
873        * using rb_str_replace() to avoid memcpy() doesn't help in
874        * most cases because a GC-aware programmer will pass an explicit
875        * buffer to env["rack.input"].read and reuse the buffer in a loop.
876        * This causes copy-on-write behavior to be triggered anyways
877        * when the +src+ buffer is modified (when reading off the socket).
878        */
879       hp->buf = src;
880       memcpy(RSTRING_PTR(dst), srcptr, nr);
881       hp->len.content -= nr;
882       if (hp->len.content == 0) {
883         HP_FL_SET(hp, REQEOF);
884         hp->cs = http_parser_first_final;
885       }
886       advance_str(src, nr);
887       src = Qnil;
888     }
889   }
890   hp->offset = 0; /* for trailer parsing */
891   return src;
894 static VALUE HttpParser_rssset(VALUE self, VALUE boolean)
896   struct http_parser *hp = data_get(self);
898   if (RTEST(boolean))
899     HP_FL_SET(hp, RESSTART);
900   else
901     HP_FL_UNSET(hp, RESSTART);
903   return boolean; /* ignored by Ruby anyways */
906 static VALUE HttpParser_rssget(VALUE self)
908   struct http_parser *hp = data_get(self);
910   return HP_FL_TEST(hp, RESSTART) ? Qtrue : Qfalse;
913 #define SET_GLOBAL(var,str) do { \
914   var = find_common_field(str, sizeof(str) - 1); \
915   assert(!NIL_P(var) && "missed global field"); \
916 } while (0)
918 void Init_unicorn_http(void)
920   static VALUE mark_ary;
921   VALUE mUnicorn, cHttpParser;
923   mark_ary = rb_ary_new();
924   rb_global_variable(&mark_ary);
925   mUnicorn = rb_define_module("Unicorn");
926   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
927   eHttpParserError =
928          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
929   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
930                                eHttpParserError);
931   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
932                                eHttpParserError);
934   init_globals(mark_ary);
935   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
936   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
937   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
938   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
939   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
940   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
941   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
942   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
943   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
944   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
945   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
946   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
947   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
948   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
949   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
950   rb_define_method(cHttpParser, "response_start_sent=", HttpParser_rssset, 1);
951   rb_define_method(cHttpParser, "response_start_sent", HttpParser_rssget, 0);
953   /*
954    * The maximum size a single chunk when using chunked transfer encoding.
955    * This is only a theoretical maximum used to detect errors in clients,
956    * it is highly unlikely to encounter clients that send more than
957    * several kilobytes at once.
958    */
959   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
961   /*
962    * The maximum size of the body as specified by Content-Length.
963    * This is only a theoretical maximum, the actual limit is subject
964    * to the limits of the file system used for +Dir.tmpdir+.
965    */
966   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
968   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
970   init_common_fields(mark_ary);
971   SET_GLOBAL(g_http_host, "HOST");
972   SET_GLOBAL(g_http_trailer, "TRAILER");
973   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
974   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
975   SET_GLOBAL(g_http_connection, "CONNECTION");
976   id_set_backtrace = rb_intern("set_backtrace");
977   init_unicorn_httpdate(mark_ary);
979   OBJ_FREEZE(mark_ary);
981 #ifndef HAVE_RB_HASH_CLEAR
982   id_clear = rb_intern("clear");
983 #endif
985 #undef SET_GLOBAL