http: remove xftrust options
[unicorn.git] / ext / unicorn_http / unicorn_http.rl
blobecdadb0c35ac210a4abbbe62127f3e13cab85253
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 long keepalive_requests = 100; /* same as nginx */
35  * Returns the maximum number of keepalive requests a client may make
36  * before the parser refuses to continue.
37  */
38 static VALUE ka_req(VALUE self)
40   return ULONG2NUM(keepalive_requests);
44  * Sets the maximum number of keepalive requests a client may make.
45  * A special value of +nil+ causes this to be the maximum value
46  * possible (this is architecture-dependent).
47  */
48 static VALUE set_ka_req(VALUE self, VALUE val)
50   keepalive_requests = NIL_P(val) ? ULONG_MAX : NUM2ULONG(val);
52   return ka_req(self);
55 static size_t MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
57 /* this is only intended for use with Rainbows! */
58 static VALUE set_maxhdrlen(VALUE self, VALUE len)
60   return SIZET2NUM(MAX_HEADER_LEN = NUM2SIZET(len));
63 /* keep this small for Rainbows! since every client has one */
64 struct http_parser {
65   int cs; /* Ragel internal state */
66   unsigned int flags;
67   unsigned long nr_requests;
68   size_t mark;
69   size_t offset;
70   union { /* these 2 fields don't nest */
71     size_t field;
72     size_t query;
73   } start;
74   union {
75     size_t field_len; /* only used during header processing */
76     size_t dest_offset; /* only used during body processing */
77   } s;
78   VALUE buf;
79   VALUE env;
80   VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
81   union {
82     off_t content;
83     off_t chunk;
84   } len;
87 static ID id_clear, id_set_backtrace, id_response_start_sent;
89 static void finalize_header(struct http_parser *hp);
91 static void parser_raise(VALUE klass, const char *msg)
93   VALUE exc = rb_exc_new2(klass, msg);
94   VALUE bt = rb_ary_new();
96         rb_funcall(exc, id_set_backtrace, 1, bt);
97         rb_exc_raise(exc);
100 #define REMAINING (unsigned long)(pe - p)
101 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
102 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
103 #define PTR_TO(F) (buffer + hp->F)
104 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
105 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
107 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
108 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
109 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
110 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
112 static int is_lws(char c)
114   return (c == ' ' || c == '\t');
117 static VALUE stripped_str_new(const char *str, long len)
119   long end;
121   for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
123   return rb_str_new(str, end + 1);
127  * handles values of the "Connection:" header, keepalive is implied
128  * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
129  * Additionally, we require GET/HEAD requests to support keepalive.
130  */
131 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
133   if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
134     /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
135     HP_FL_SET(hp, KAVERSION);
136   } else if (STR_CSTR_CASE_EQ(val, "close")) {
137     /*
138      * it doesn't matter what HTTP version or request method we have,
139      * if a client says "Connection: close", we disable keepalive
140      */
141     HP_FL_UNSET(hp, KAVERSION);
142   } else {
143     /*
144      * client could've sent anything, ignore it for now.  Maybe
145      * "HP_FL_UNSET(hp, KAVERSION);" just in case?
146      * Raising an exception might be too mean...
147      */
148   }
151 static void
152 request_method(struct http_parser *hp, const char *ptr, size_t len)
154   VALUE v = rb_str_new(ptr, len);
156   rb_hash_aset(hp->env, g_request_method, v);
159 static void
160 http_version(struct http_parser *hp, const char *ptr, size_t len)
162   VALUE v;
164   HP_FL_SET(hp, HASHEADER);
166   if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
167     /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
168     HP_FL_SET(hp, KAVERSION);
169     v = g_http_11;
170   } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
171     v = g_http_10;
172   } else {
173     v = rb_str_new(ptr, len);
174   }
175   rb_hash_aset(hp->env, g_server_protocol, v);
176   rb_hash_aset(hp->env, g_http_version, v);
179 static inline void hp_invalid_if_trailer(struct http_parser *hp)
181   if (HP_FL_TEST(hp, INTRAILER))
182     parser_raise(eHttpParserError, "invalid Trailer");
185 static void write_cont_value(struct http_parser *hp,
186                              char *buffer, const char *p)
188   char *vptr;
189   long end;
190   long len = LEN(mark, p);
191   long cont_len;
193   if (hp->cont == Qfalse)
194      parser_raise(eHttpParserError, "invalid continuation line");
195   if (NIL_P(hp->cont))
196      return; /* we're ignoring this header (probably Host:) */
198   assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
199   assert(hp->mark > 0 && "impossible continuation line offset");
201   if (len == 0)
202     return;
204   cont_len = RSTRING_LEN(hp->cont);
205   if (cont_len > 0) {
206     --hp->mark;
207     len = LEN(mark, p);
208   }
209   vptr = PTR_TO(mark);
211   /* normalize tab to space */
212   if (cont_len > 0) {
213     assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
214     *vptr = ' ';
215   }
217   for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
218   rb_str_buf_cat(hp->cont, vptr, end + 1);
221 static void write_value(struct http_parser *hp,
222                         const char *buffer, const char *p)
224   VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
225   VALUE v;
226   VALUE e;
228   VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
229   v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
230   if (NIL_P(f)) {
231     const char *field = PTR_TO(start.field);
232     size_t flen = hp->s.field_len;
234     VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
236     /*
237      * ignore "Version" headers since they conflict with the HTTP_VERSION
238      * rack env variable.
239      */
240     if (CONST_MEM_EQ("VERSION", field, flen)) {
241       hp->cont = Qnil;
242       return;
243     }
244     f = uncommon_field(field, flen);
245   } else if (f == g_http_connection) {
246     hp_keepalive_connection(hp, v);
247   } else if (f == g_content_length) {
248     hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
249     if (hp->len.content < 0)
250       parser_raise(eHttpParserError, "invalid Content-Length");
251     if (hp->len.content != 0)
252       HP_FL_SET(hp, HASBODY);
253     hp_invalid_if_trailer(hp);
254   } else if (f == g_http_transfer_encoding) {
255     if (STR_CSTR_CASE_EQ(v, "chunked")) {
256       HP_FL_SET(hp, CHUNKED);
257       HP_FL_SET(hp, HASBODY);
258     }
259     hp_invalid_if_trailer(hp);
260   } else if (f == g_http_trailer) {
261     HP_FL_SET(hp, HASTRAILER);
262     hp_invalid_if_trailer(hp);
263   } else {
264     assert(TYPE(f) == T_STRING && "memoized object is not a string");
265     assert_frozen(f);
266   }
268   e = rb_hash_aref(hp->env, f);
269   if (NIL_P(e)) {
270     hp->cont = rb_hash_aset(hp->env, f, v);
271   } else if (f == g_http_host) {
272     /*
273      * ignored, absolute URLs in REQUEST_URI take precedence over
274      * the Host: header (ref: rfc 2616, section 5.2.1)
275      */
276      hp->cont = Qnil;
277   } else {
278     rb_str_buf_cat(e, ",", 1);
279     hp->cont = rb_str_buf_append(e, v);
280   }
283 /** Machine **/
286   machine http_parser;
288   action mark {MARK(mark, fpc); }
290   action start_field { MARK(start.field, fpc); }
291   action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
292   action downcase_char { downcase_char(deconst(fpc)); }
293   action write_field { hp->s.field_len = LEN(start.field, fpc); }
294   action start_value { MARK(mark, fpc); }
295   action write_value { write_value(hp, buffer, fpc); }
296   action write_cont_value { write_cont_value(hp, buffer, fpc); }
297   action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
298   action scheme {
299     rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
300   }
301   action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
302   action request_uri {
303     VALUE str;
305     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
306     str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
307     /*
308      * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
309      * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
310      */
311     if (STR_CSTR_EQ(str, "*")) {
312       str = rb_str_new(NULL, 0);
313       rb_hash_aset(hp->env, g_path_info, str);
314       rb_hash_aset(hp->env, g_request_path, str);
315     }
316   }
317   action fragment {
318     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
319     rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
320   }
321   action start_query {MARK(start.query, fpc); }
322   action query_string {
323     VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
324     rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
325   }
326   action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
327   action request_path {
328     VALUE val;
330     VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
331     val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
333     /* rack says PATH_INFO must start with "/" or be empty */
334     if (!STR_CSTR_EQ(val, "*"))
335       rb_hash_aset(hp->env, g_path_info, val);
336   }
337   action add_to_chunk_size {
338     hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
339     if (hp->len.chunk < 0)
340       parser_raise(eHttpParserError, "invalid chunk size");
341   }
342   action header_done {
343     finalize_header(hp);
345     cs = http_parser_first_final;
346     if (HP_FL_TEST(hp, HASBODY)) {
347       HP_FL_SET(hp, INBODY);
348       if (HP_FL_TEST(hp, CHUNKED))
349         cs = http_parser_en_ChunkedBody;
350     } else {
351       HP_FL_SET(hp, REQEOF);
352       assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
353     }
354     /*
355      * go back to Ruby so we can call the Rack application, we'll reenter
356      * the parser iff the body needs to be processed.
357      */
358     goto post_exec;
359   }
361   action end_trailers {
362     cs = http_parser_first_final;
363     goto post_exec;
364   }
366   action end_chunked_body {
367     HP_FL_SET(hp, INTRAILER);
368     cs = http_parser_en_Trailers;
369     ++p;
370     assert(p <= pe && "buffer overflow after chunked body");
371     goto post_exec;
372   }
374   action skip_chunk_data {
375   skip_chunk_data_hack: {
376     size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
377     memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
378     hp->s.dest_offset += nr;
379     hp->len.chunk -= nr;
380     p += nr;
381     assert(hp->len.chunk >= 0 && "negative chunk length");
382     if ((size_t)hp->len.chunk > REMAINING) {
383       HP_FL_SET(hp, INCHUNK);
384       goto post_exec;
385     } else {
386       fhold;
387       fgoto chunk_end;
388     }
389   }}
391   include unicorn_http_common "unicorn_http_common.rl";
394 /** Data **/
395 %% write data;
397 static void http_parser_init(struct http_parser *hp)
399   int cs = 0;
400   hp->flags = 0;
401   hp->mark = 0;
402   hp->offset = 0;
403   hp->start.field = 0;
404   hp->s.field_len = 0;
405   hp->len.content = 0;
406   hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
407   %% write init;
408   hp->cs = cs;
411 /** exec **/
412 static void
413 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
415   const char *p, *pe;
416   int cs = hp->cs;
417   size_t off = hp->offset;
419   if (cs == http_parser_first_final)
420     return;
422   assert(off <= len && "offset past end of buffer");
424   p = buffer+off;
425   pe = buffer+len;
427   assert((void *)(pe - p) == (void *)(len - off) &&
428          "pointers aren't same distance");
430   if (HP_FL_TEST(hp, INCHUNK)) {
431     HP_FL_UNSET(hp, INCHUNK);
432     goto skip_chunk_data_hack;
433   }
434   %% write exec;
435 post_exec: /* "_out:" also goes here */
436   if (hp->cs != http_parser_error)
437     hp->cs = cs;
438   hp->offset = p - buffer;
440   assert(p <= pe && "buffer overflow after parsing execute");
441   assert(hp->offset <= len && "offset longer than length");
444 static struct http_parser *data_get(VALUE self)
446   struct http_parser *hp;
448   Data_Get_Struct(self, struct http_parser, hp);
449   assert(hp && "failed to extract http_parser struct");
450   return hp;
454  * set rack.url_scheme to "https" or "http", no others are allowed by Rack
455  * this resembles the Rack::Request#scheme method as of rack commit
456  * 35bb5ba6746b5d346de9202c004cc926039650c7
457  */
458 static void set_url_scheme(VALUE env, VALUE *server_port)
460   VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
462   if (NIL_P(scheme)) {
463     /*
464      * would anybody be horribly opposed to removing the X-Forwarded-SSL
465      * and X-Forwarded-Proto handling from this parser?  We've had it
466      * forever and nobody has said anything against it, either.
467      * Anyways, please send comments to our public mailing list:
468      * unicorn-public@bogomips.org (no HTML mail, no subscription necessary)
469      */
470     scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
471     if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
472       *server_port = g_port_443;
473       scheme = g_https;
474     } else {
475       scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
476       if (NIL_P(scheme)) {
477         scheme = g_http;
478       } else {
479         long len = RSTRING_LEN(scheme);
480         if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
481           if (len != 5)
482             scheme = g_https;
483           *server_port = g_port_443;
484         } else {
485           scheme = g_http;
486         }
487       }
488     }
489     rb_hash_aset(env, g_rack_url_scheme, scheme);
490   } else if (STR_CSTR_EQ(scheme, "https")) {
491     *server_port = g_port_443;
492   } else {
493     assert(*server_port == g_port_80 && "server_port not set");
494   }
498  * Parse and set the SERVER_NAME and SERVER_PORT variables
499  * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
500  * anybody who needs them is using an unsupported configuration and/or
501  * incompetent.  Rack::Request will handle X-Forwarded-{Port,Host} just
502  * fine.
503  */
504 static void set_server_vars(VALUE env, VALUE *server_port)
506   VALUE server_name = g_localhost;
507   VALUE host = rb_hash_aref(env, g_http_host);
509   if (!NIL_P(host)) {
510     char *host_ptr = RSTRING_PTR(host);
511     long host_len = RSTRING_LEN(host);
512     char *colon;
514     if (*host_ptr == '[') { /* ipv6 address format */
515       char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
517       if (rbracket)
518         colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
519       else
520         colon = memchr(host_ptr + 1, ':', host_len - 1);
521     } else {
522       colon = memchr(host_ptr, ':', host_len);
523     }
525     if (colon) {
526       long port_start = colon - host_ptr + 1;
528       server_name = rb_str_substr(host, 0, colon - host_ptr);
529       if ((host_len - port_start) > 0)
530         *server_port = rb_str_substr(host, port_start, host_len);
531     } else {
532       server_name = host;
533     }
534   }
535   rb_hash_aset(env, g_server_name, server_name);
536   rb_hash_aset(env, g_server_port, *server_port);
539 static void finalize_header(struct http_parser *hp)
541   VALUE server_port = g_port_80;
543   set_url_scheme(hp->env, &server_port);
544   set_server_vars(hp->env, &server_port);
546   if (!HP_FL_TEST(hp, HASHEADER))
547     rb_hash_aset(hp->env, g_server_protocol, g_http_09);
549   /* rack requires QUERY_STRING */
550   if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
551     rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
554 static void hp_mark(void *ptr)
556   struct http_parser *hp = ptr;
558   rb_gc_mark(hp->buf);
559   rb_gc_mark(hp->env);
560   rb_gc_mark(hp->cont);
563 static VALUE HttpParser_alloc(VALUE klass)
565   struct http_parser *hp;
566   return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
571  * call-seq:
572  *    parser.new => parser
574  * Creates a new parser.
575  */
576 static VALUE HttpParser_init(VALUE self)
578   struct http_parser *hp = data_get(self);
580   http_parser_init(hp);
581   hp->buf = rb_str_new(NULL, 0);
582   hp->env = rb_hash_new();
583   hp->nr_requests = keepalive_requests;
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   rb_funcall(hp->env, id_clear, 0);
601   rb_ivar_set(self, id_response_start_sent, Qfalse);
603   return self;
607  * call-seq:
608  *    parser.dechunk! => parser
610  * Resets the parser to a state suitable for dechunking response bodies
612  */
613 static VALUE HttpParser_dechunk_bang(VALUE self)
615   struct http_parser *hp = data_get(self);
617   http_parser_init(hp);
619   /*
620    * we don't care about trailers in dechunk-only mode,
621    * but if we did we'd set UH_FL_HASTRAILER and clear hp->env
622    */
623   if (0) {
624     rb_funcall(hp->env, id_clear, 0);
625     hp->flags = UH_FL_HASTRAILER;
626   }
628   hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED;
629   hp->cs = http_parser_en_ChunkedBody;
631   return self;
635  * call-seq:
636  *    parser.reset => nil
638  * Resets the parser to it's initial state so that you can reuse it
639  * rather than making new ones.
641  * This method is deprecated and to be removed in Unicorn 4.x
642  */
643 static VALUE HttpParser_reset(VALUE self)
645   static int warned;
647   if (!warned) {
648     rb_warn("Unicorn::HttpParser#reset is deprecated; "
649             "use Unicorn::HttpParser#clear instead");
650   }
651   HttpParser_clear(self);
652   return Qnil;
655 static void advance_str(VALUE str, off_t nr)
657   long len = RSTRING_LEN(str);
659   if (len == 0)
660     return;
662   rb_str_modify(str);
664   assert(nr <= len && "trying to advance past end of buffer");
665   len -= nr;
666   if (len > 0) /* unlikely, len is usually 0 */
667     memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
668   rb_str_set_len(str, len);
672  * call-seq:
673  *   parser.content_length => nil or Integer
675  * Returns the number of bytes left to run through HttpParser#filter_body.
676  * This will initially be the value of the "Content-Length" HTTP header
677  * after header parsing is complete and will decrease in value as
678  * HttpParser#filter_body is called for each chunk.  This should return
679  * zero for requests with no body.
681  * This will return nil on "Transfer-Encoding: chunked" requests.
682  */
683 static VALUE HttpParser_content_length(VALUE self)
685   struct http_parser *hp = data_get(self);
687   return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
691  * Document-method: parse
692  * call-seq:
693  *    parser.parse => env or nil
695  * Takes a Hash and a String of data, parses the String of data filling
696  * in the Hash returning the Hash if parsing is finished, nil otherwise
697  * When returning the env Hash, it may modify data to point to where
698  * body processing should begin.
700  * Raises HttpParserError if there are parsing errors.
701  */
702 static VALUE HttpParser_parse(VALUE self)
704   struct http_parser *hp = data_get(self);
705   VALUE data = hp->buf;
707   if (HP_FL_TEST(hp, TO_CLEAR))
708     HttpParser_clear(self);
710   http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
711   if (hp->offset > MAX_HEADER_LEN)
712     parser_raise(e413, "HTTP header is too large");
714   if (hp->cs == http_parser_first_final ||
715       hp->cs == http_parser_en_ChunkedBody) {
716     advance_str(data, hp->offset + 1);
717     hp->offset = 0;
718     if (HP_FL_TEST(hp, INTRAILER))
719       HP_FL_SET(hp, REQEOF);
721     return hp->env;
722   }
724   if (hp->cs == http_parser_error)
725     parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
727   return Qnil;
731  * Document-method: parse
732  * call-seq:
733  *    parser.add_parse(buffer) => env or nil
735  * adds the contents of +buffer+ to the internal buffer and attempts to
736  * continue parsing.  Returns the +env+ Hash on success or nil if more
737  * data is needed.
739  * Raises HttpParserError if there are parsing errors.
740  */
741 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
743   struct http_parser *hp = data_get(self);
745   Check_Type(buffer, T_STRING);
746   rb_str_buf_append(hp->buf, buffer);
748   return HttpParser_parse(self);
752  * Document-method: trailers
753  * call-seq:
754  *    parser.trailers(req, data) => req or nil
756  * This is an alias for HttpParser#headers
757  */
760  * Document-method: headers
761  */
762 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
764   struct http_parser *hp = data_get(self);
766   hp->env = env;
767   hp->buf = buf;
769   return HttpParser_parse(self);
772 static int chunked_eof(struct http_parser *hp)
774   return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
778  * call-seq:
779  *    parser.body_eof? => true or false
781  * Detects if we're done filtering the body or not.  This can be used
782  * to detect when to stop calling HttpParser#filter_body.
783  */
784 static VALUE HttpParser_body_eof(VALUE self)
786   struct http_parser *hp = data_get(self);
788   if (HP_FL_TEST(hp, CHUNKED))
789     return chunked_eof(hp) ? Qtrue : Qfalse;
791   return hp->len.content == 0 ? Qtrue : Qfalse;
795  * call-seq:
796  *    parser.keepalive? => true or false
798  * This should be used to detect if a request can really handle
799  * keepalives and pipelining.  Currently, the rules are:
801  * 1. MUST be a GET or HEAD request
802  * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
803  * 3. MUST NOT have "Connection: close" set
804  */
805 static VALUE HttpParser_keepalive(VALUE self)
807   struct http_parser *hp = data_get(self);
809   return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
813  * call-seq:
814  *    parser.next? => true or false
816  * Exactly like HttpParser#keepalive?, except it will reset the internal
817  * parser state on next parse if it returns true.  It will also respect
818  * the maximum *keepalive_requests* value and return false if that is
819  * reached.
820  */
821 static VALUE HttpParser_next(VALUE self)
823   struct http_parser *hp = data_get(self);
825   if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
826     HP_FL_SET(hp, TO_CLEAR);
827     return Qtrue;
828   }
829   return Qfalse;
833  * call-seq:
834  *    parser.headers? => true or false
836  * This should be used to detect if a request has headers (and if
837  * the response will have headers as well).  HTTP/0.9 requests
838  * should return false, all subsequent HTTP versions will return true
839  */
840 static VALUE HttpParser_has_headers(VALUE self)
842   struct http_parser *hp = data_get(self);
844   return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
847 static VALUE HttpParser_buf(VALUE self)
849   return data_get(self)->buf;
852 static VALUE HttpParser_env(VALUE self)
854   return data_get(self)->env;
858  * call-seq:
859  *    parser.filter_body(dst, src) => nil/src
861  * Takes a String of +src+, will modify data if dechunking is done.
862  * Returns +nil+ if there is more data left to process.  Returns
863  * +src+ if body processing is complete. When returning +src+,
864  * it may modify +src+ so the start of the string points to where
865  * the body ended so that trailer processing can begin.
867  * Raises HttpParserError if there are dechunking errors.
868  * Basically this is a glorified memcpy(3) that copies +src+
869  * into +buf+ while filtering it through the dechunker.
870  */
871 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
873   struct http_parser *hp = data_get(self);
874   char *srcptr;
875   long srclen;
877   srcptr = RSTRING_PTR(src);
878   srclen = RSTRING_LEN(src);
880   StringValue(dst);
882   if (HP_FL_TEST(hp, CHUNKED)) {
883     if (!chunked_eof(hp)) {
884       rb_str_modify(dst);
885       rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
887       hp->s.dest_offset = 0;
888       hp->cont = dst;
889       hp->buf = src;
890       http_parser_execute(hp, srcptr, srclen);
891       if (hp->cs == http_parser_error)
892         parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
894       assert(hp->s.dest_offset <= hp->offset &&
895              "destination buffer overflow");
896       advance_str(src, hp->offset);
897       rb_str_set_len(dst, hp->s.dest_offset);
899       if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
900         assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
901       } else {
902         src = Qnil;
903       }
904     }
905   } else {
906     /* no need to enter the Ragel machine for unchunked transfers */
907     assert(hp->len.content >= 0 && "negative Content-Length");
908     if (hp->len.content > 0) {
909       long nr = MIN(srclen, hp->len.content);
911       rb_str_modify(dst);
912       rb_str_resize(dst, nr);
913       /*
914        * using rb_str_replace() to avoid memcpy() doesn't help in
915        * most cases because a GC-aware programmer will pass an explicit
916        * buffer to env["rack.input"].read and reuse the buffer in a loop.
917        * This causes copy-on-write behavior to be triggered anyways
918        * when the +src+ buffer is modified (when reading off the socket).
919        */
920       hp->buf = src;
921       memcpy(RSTRING_PTR(dst), srcptr, nr);
922       hp->len.content -= nr;
923       if (hp->len.content == 0) {
924         HP_FL_SET(hp, REQEOF);
925         hp->cs = http_parser_first_final;
926       }
927       advance_str(src, nr);
928       src = Qnil;
929     }
930   }
931   hp->offset = 0; /* for trailer parsing */
932   return src;
935 #define SET_GLOBAL(var,str) do { \
936   var = find_common_field(str, sizeof(str) - 1); \
937   assert(!NIL_P(var) && "missed global field"); \
938 } while (0)
940 void Init_unicorn_http(void)
942   VALUE mUnicorn, cHttpParser;
944   mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
945   cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
946   eHttpParserError =
947          rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
948   e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
949                                eHttpParserError);
950   e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
951                                eHttpParserError);
953   init_globals();
954   rb_define_alloc_func(cHttpParser, HttpParser_alloc);
955   rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
956   rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
957   rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
958   rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0);
959   rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
960   rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
961   rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
962   rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
963   rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
964   rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
965   rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
966   rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
967   rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
968   rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
969   rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
970   rb_define_method(cHttpParser, "env", HttpParser_env, 0);
972   /*
973    * The maximum size a single chunk when using chunked transfer encoding.
974    * This is only a theoretical maximum used to detect errors in clients,
975    * it is highly unlikely to encounter clients that send more than
976    * several kilobytes at once.
977    */
978   rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
980   /*
981    * The maximum size of the body as specified by Content-Length.
982    * This is only a theoretical maximum, the actual limit is subject
983    * to the limits of the file system used for +Dir.tmpdir+.
984    */
985   rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
987   /* default value for keepalive_requests */
988   rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
989                   ULONG2NUM(keepalive_requests));
991   rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
992   rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
993   rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
995   init_common_fields();
996   SET_GLOBAL(g_http_host, "HOST");
997   SET_GLOBAL(g_http_trailer, "TRAILER");
998   SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
999   SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1000   SET_GLOBAL(g_http_connection, "CONNECTION");
1001   id_clear = rb_intern("clear");
1002   id_set_backtrace = rb_intern("set_backtrace");
1003   id_response_start_sent = rb_intern("@response_start_sent");
1004   init_unicorn_httpdate();
1006 #undef SET_GLOBAL