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.
10 #include <sys/types.h>
11 #include "common_field_optimization.h"
12 #include "global_variables.h"
15 #define UH_FL_CHUNKED 0x1
16 #define UH_FL_HASBODY 0x2
17 #define UH_FL_INBODY 0x4
18 #define UH_FL_HASTRAILER 0x8
19 #define UH_FL_INTRAILER 0x10
20 #define UH_FL_INCHUNK 0x20
21 #define UH_FL_REQEOF 0x40
22 #define UH_FL_KAVERSION 0x80
23 #define UH_FL_HASHEADER 0x100
25 /* all of these flags need to be set for keepalive to be supported */
26 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
28 /* keep this small for Rainbows! since every client has one */
30 int cs; /* Ragel internal state */
34 union { /* these 2 fields don't nest */
39 size_t field_len; /* only used during header processing */
40 size_t dest_offset; /* only used during body processing */
44 VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
53 static void finalize_header(struct http_parser *hp);
55 static void parser_error(const char *msg)
57 VALUE exc = rb_exc_new2(eHttpParserError, msg);
58 VALUE bt = rb_ary_new();
60 rb_funcall(exc, rb_intern("set_backtrace"), 1, bt);
64 #define REMAINING (unsigned long)(pe - p)
65 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
66 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
67 #define PTR_TO(F) (buffer + hp->F)
68 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
70 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
71 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
72 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
73 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
76 * handles values of the "Connection:" header, keepalive is implied
77 * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
78 * Additionally, we require GET/HEAD requests to support keepalive.
80 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
82 if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
83 /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
84 HP_FL_SET(hp, KAVERSION);
85 } else if (STR_CSTR_CASE_EQ(val, "close")) {
87 * it doesn't matter what HTTP version or request method we have,
88 * if a client says "Connection: close", we disable keepalive
90 HP_FL_UNSET(hp, KAVERSION);
93 * client could've sent anything, ignore it for now. Maybe
94 * "HP_FL_UNSET(hp, KAVERSION);" just in case?
95 * Raising an exception might be too mean...
101 request_method(struct http_parser *hp, const char *ptr, size_t len)
103 VALUE v = rb_str_new(ptr, len);
105 rb_hash_aset(hp->env, g_request_method, v);
109 http_version(struct http_parser *hp, const char *ptr, size_t len)
113 HP_FL_SET(hp, HASHEADER);
115 if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
116 /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
117 HP_FL_SET(hp, KAVERSION);
119 } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
122 v = rb_str_new(ptr, len);
124 rb_hash_aset(hp->env, g_server_protocol, v);
125 rb_hash_aset(hp->env, g_http_version, v);
128 static inline void hp_invalid_if_trailer(struct http_parser *hp)
130 if (HP_FL_TEST(hp, INTRAILER))
131 parser_error("invalid Trailer");
134 static void write_cont_value(struct http_parser *hp,
135 char *buffer, const char *p)
139 if (hp->cont == Qfalse)
140 parser_error("invalid continuation line");
142 return; /* we're ignoring this header (probably Host:) */
144 assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
145 assert(hp->mark > 0 && "impossible continuation line offset");
147 if (LEN(mark, p) == 0)
150 if (RSTRING_LEN(hp->cont) > 0)
155 if (RSTRING_LEN(hp->cont) > 0) {
156 assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
159 rb_str_buf_cat(hp->cont, vptr, LEN(mark, p));
162 static void write_value(struct http_parser *hp,
163 const char *buffer, const char *p)
165 VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
169 VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
170 v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STR_NEW(mark, p);
172 const char *field = PTR_TO(start.field);
173 size_t flen = hp->s.field_len;
175 VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
178 * ignore "Version" headers since they conflict with the HTTP_VERSION
181 if (CONST_MEM_EQ("VERSION", field, flen)) {
185 f = uncommon_field(field, flen);
186 } else if (f == g_http_connection) {
187 hp_keepalive_connection(hp, v);
188 } else if (f == g_content_length) {
189 hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
190 if (hp->len.content < 0)
191 parser_error("invalid Content-Length");
192 if (hp->len.content != 0)
193 HP_FL_SET(hp, HASBODY);
194 hp_invalid_if_trailer(hp);
195 } else if (f == g_http_transfer_encoding) {
196 if (STR_CSTR_CASE_EQ(v, "chunked")) {
197 HP_FL_SET(hp, CHUNKED);
198 HP_FL_SET(hp, HASBODY);
200 hp_invalid_if_trailer(hp);
201 } else if (f == g_http_trailer) {
202 HP_FL_SET(hp, HASTRAILER);
203 hp_invalid_if_trailer(hp);
205 assert(TYPE(f) == T_STRING && "memoized object is not a string");
209 e = rb_hash_aref(hp->env, f);
211 hp->cont = rb_hash_aset(hp->env, f, v);
212 } else if (f == g_http_host) {
214 * ignored, absolute URLs in REQUEST_URI take precedence over
215 * the Host: header (ref: rfc 2616, section 5.2.1)
219 rb_str_buf_cat(e, ",", 1);
220 hp->cont = rb_str_buf_append(e, v);
229 action mark {MARK(mark, fpc); }
231 action start_field { MARK(start.field, fpc); }
232 action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
233 action downcase_char { downcase_char(deconst(fpc)); }
234 action write_field { hp->s.field_len = LEN(start.field, fpc); }
235 action start_value { MARK(mark, fpc); }
236 action write_value { write_value(hp, buffer, fpc); }
237 action write_cont_value { write_cont_value(hp, buffer, fpc); }
238 action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
240 rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
242 action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
246 VALIDATE_MAX_LENGTH(LEN(mark, fpc), REQUEST_URI);
247 str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
249 * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
250 * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
252 if (STR_CSTR_EQ(str, "*")) {
253 str = rb_str_new(NULL, 0);
254 rb_hash_aset(hp->env, g_path_info, str);
255 rb_hash_aset(hp->env, g_request_path, str);
259 VALIDATE_MAX_LENGTH(LEN(mark, fpc), FRAGMENT);
260 rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
262 action start_query {MARK(start.query, fpc); }
263 action query_string {
264 VALIDATE_MAX_LENGTH(LEN(start.query, fpc), QUERY_STRING);
265 rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
267 action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
268 action request_path {
271 VALIDATE_MAX_LENGTH(LEN(mark, fpc), REQUEST_PATH);
272 val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
274 /* rack says PATH_INFO must start with "/" or be empty */
275 if (!STR_CSTR_EQ(val, "*"))
276 rb_hash_aset(hp->env, g_path_info, val);
278 action add_to_chunk_size {
279 hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
280 if (hp->len.chunk < 0)
281 parser_error("invalid chunk size");
286 cs = http_parser_first_final;
287 if (HP_FL_TEST(hp, HASBODY)) {
288 HP_FL_SET(hp, INBODY);
289 if (HP_FL_TEST(hp, CHUNKED))
290 cs = http_parser_en_ChunkedBody;
292 HP_FL_SET(hp, REQEOF);
293 assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
296 * go back to Ruby so we can call the Rack application, we'll reenter
297 * the parser iff the body needs to be processed.
302 action end_trailers {
303 cs = http_parser_first_final;
307 action end_chunked_body {
308 HP_FL_SET(hp, INTRAILER);
309 cs = http_parser_en_Trailers;
311 assert(p <= pe && "buffer overflow after chunked body");
315 action skip_chunk_data {
316 skip_chunk_data_hack: {
317 size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
318 memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
319 hp->s.dest_offset += nr;
322 assert(hp->len.chunk >= 0 && "negative chunk length");
323 if ((size_t)hp->len.chunk > REMAINING) {
324 HP_FL_SET(hp, INCHUNK);
332 include unicorn_http_common "unicorn_http_common.rl";
338 static void http_parser_init(struct http_parser *hp)
347 hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
354 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
358 size_t off = hp->offset;
360 if (cs == http_parser_first_final)
363 assert(off <= len && "offset past end of buffer");
368 assert((void *)(pe - p) == (void *)(len - off) &&
369 "pointers aren't same distance");
371 if (HP_FL_TEST(hp, INCHUNK)) {
372 HP_FL_UNSET(hp, INCHUNK);
373 goto skip_chunk_data_hack;
376 post_exec: /* "_out:" also goes here */
377 if (hp->cs != http_parser_error)
379 hp->offset = p - buffer;
381 assert(p <= pe && "buffer overflow after parsing execute");
382 assert(hp->offset <= len && "offset longer than length");
385 static struct http_parser *data_get(VALUE self)
387 struct http_parser *hp;
389 Data_Get_Struct(self, struct http_parser, hp);
390 assert(hp && "failed to extract http_parser struct");
394 static void finalize_header(struct http_parser *hp)
396 VALUE temp = rb_hash_aref(hp->env, g_rack_url_scheme);
397 VALUE server_name = g_localhost;
398 VALUE server_port = g_port_80;
400 /* set rack.url_scheme to "https" or "http", no others are allowed by Rack */
402 temp = rb_hash_aref(hp->env, g_http_x_forwarded_proto);
403 if (!NIL_P(temp) && STR_CSTR_EQ(temp, "https"))
404 server_port = g_port_443;
407 rb_hash_aset(hp->env, g_rack_url_scheme, temp);
408 } else if (STR_CSTR_EQ(temp, "https")) {
409 server_port = g_port_443;
411 assert(server_port == g_port_80 && "server_port not set");
414 /* parse and set the SERVER_NAME and SERVER_PORT variables */
415 temp = rb_hash_aref(hp->env, g_http_host);
417 char *colon = memchr(RSTRING_PTR(temp), ':', RSTRING_LEN(temp));
419 long port_start = colon - RSTRING_PTR(temp) + 1;
421 server_name = rb_str_substr(temp, 0, colon - RSTRING_PTR(temp));
422 if ((RSTRING_LEN(temp) - port_start) > 0)
423 server_port = rb_str_substr(temp, port_start, RSTRING_LEN(temp));
428 rb_hash_aset(hp->env, g_server_name, server_name);
429 rb_hash_aset(hp->env, g_server_port, server_port);
430 if (!HP_FL_TEST(hp, HASHEADER))
431 rb_hash_aset(hp->env, g_server_protocol, g_http_09);
433 /* rack requires QUERY_STRING */
434 if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
435 rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
438 static void hp_mark(void *ptr)
440 struct http_parser *hp = ptr;
444 rb_gc_mark(hp->cont);
447 static VALUE HttpParser_alloc(VALUE klass)
449 struct http_parser *hp;
450 return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
456 * parser.new => parser
458 * Creates a new parser.
460 static VALUE HttpParser_init(VALUE self)
462 struct http_parser *hp = data_get(self);
464 http_parser_init(hp);
465 hp->buf = rb_str_new(NULL, 0);
466 hp->env = rb_hash_new();
473 * parser.reset => nil
475 * Resets the parser to it's initial state so that you can reuse it
476 * rather than making new ones.
478 static VALUE HttpParser_reset(VALUE self)
480 struct http_parser *hp = data_get(self);
482 http_parser_init(hp);
483 rb_funcall(hp->env, id_clear, 0);
488 static void advance_str(VALUE str, off_t nr)
490 long len = RSTRING_LEN(str);
497 assert(nr <= len && "trying to advance past end of buffer");
499 if (len > 0) /* unlikely, len is usually 0 */
500 memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
501 rb_str_set_len(str, len);
506 * parser.content_length => nil or Integer
508 * Returns the number of bytes left to run through HttpParser#filter_body.
509 * This will initially be the value of the "Content-Length" HTTP header
510 * after header parsing is complete and will decrease in value as
511 * HttpParser#filter_body is called for each chunk. This should return
512 * zero for requests with no body.
514 * This will return nil on "Transfer-Encoding: chunked" requests.
516 static VALUE HttpParser_content_length(VALUE self)
518 struct http_parser *hp = data_get(self);
520 return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
524 * Document-method: parse
526 * parser.parse => env or nil
528 * Takes a Hash and a String of data, parses the String of data filling
529 * in the Hash returning the Hash if parsing is finished, nil otherwise
530 * When returning the env Hash, it may modify data to point to where
531 * body processing should begin.
533 * Raises HttpParserError if there are parsing errors.
535 static VALUE HttpParser_parse(VALUE self)
537 struct http_parser *hp = data_get(self);
538 VALUE data = hp->buf;
540 http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
541 VALIDATE_MAX_LENGTH(hp->offset, HEADER);
543 if (hp->cs == http_parser_first_final ||
544 hp->cs == http_parser_en_ChunkedBody) {
545 advance_str(data, hp->offset + 1);
547 if (HP_FL_TEST(hp, INTRAILER))
548 HP_FL_SET(hp, REQEOF);
553 if (hp->cs == http_parser_error)
554 parser_error("Invalid HTTP format, parsing fails.");
560 * Document-method: trailers
562 * parser.trailers(req, data) => req or nil
564 * This is an alias for HttpParser#headers
568 * Document-method: headers
570 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
572 struct http_parser *hp = data_get(self);
577 return HttpParser_parse(self);
580 static int chunked_eof(struct http_parser *hp)
582 return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
587 * parser.body_eof? => true or false
589 * Detects if we're done filtering the body or not. This can be used
590 * to detect when to stop calling HttpParser#filter_body.
592 static VALUE HttpParser_body_eof(VALUE self)
594 struct http_parser *hp = data_get(self);
596 if (HP_FL_TEST(hp, CHUNKED))
597 return chunked_eof(hp) ? Qtrue : Qfalse;
599 return hp->len.content == 0 ? Qtrue : Qfalse;
604 * parser.keepalive? => true or false
606 * This should be used to detect if a request can really handle
607 * keepalives and pipelining. Currently, the rules are:
609 * 1. MUST be a GET or HEAD request
610 * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
611 * 3. MUST NOT have "Connection: close" set
613 static VALUE HttpParser_keepalive(VALUE self)
615 struct http_parser *hp = data_get(self);
617 return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
622 * parser.next? => true or false
624 * Exactly like HttpParser#keepalive?, except it will reset the internal
625 * parser state if it returns true.
627 static VALUE HttpParser_next(VALUE self)
629 struct http_parser *hp = data_get(self);
631 if (HP_FL_ALL(hp, KEEPALIVE)) {
632 http_parser_init(hp);
633 rb_funcall(hp->env, id_clear, 0);
641 * parser.headers? => true or false
643 * This should be used to detect if a request has headers (and if
644 * the response will have headers as well). HTTP/0.9 requests
645 * should return false, all subsequent HTTP versions will return true
647 static VALUE HttpParser_has_headers(VALUE self)
649 struct http_parser *hp = data_get(self);
651 return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
654 static VALUE HttpParser_buf(VALUE self)
656 return data_get(self)->buf;
659 static VALUE HttpParser_env(VALUE self)
661 return data_get(self)->env;
666 * parser.filter_body(buf, data) => nil/data
668 * Takes a String of +data+, will modify data if dechunking is done.
669 * Returns +nil+ if there is more data left to process. Returns
670 * +data+ if body processing is complete. When returning +data+,
671 * it may modify +data+ so the start of the string points to where
672 * the body ended so that trailer processing can begin.
674 * Raises HttpParserError if there are dechunking errors.
675 * Basically this is a glorified memcpy(3) that copies +data+
676 * into +buf+ while filtering it through the dechunker.
678 static VALUE HttpParser_filter_body(VALUE self, VALUE buf, VALUE data)
680 struct http_parser *hp = data_get(self);
684 dptr = RSTRING_PTR(data);
685 dlen = RSTRING_LEN(data);
688 rb_str_resize(buf, dlen); /* we can never copy more than dlen bytes */
689 OBJ_TAINT(buf); /* keep weirdo $SAFE users happy */
691 if (HP_FL_TEST(hp, CHUNKED)) {
692 if (!chunked_eof(hp)) {
693 hp->s.dest_offset = 0;
696 http_parser_execute(hp, dptr, dlen);
697 if (hp->cs == http_parser_error)
698 parser_error("Invalid HTTP format, parsing fails.");
700 assert(hp->s.dest_offset <= hp->offset &&
701 "destination buffer overflow");
702 advance_str(data, hp->offset);
703 rb_str_set_len(buf, hp->s.dest_offset);
705 if (RSTRING_LEN(buf) == 0 && chunked_eof(hp)) {
706 assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
712 /* no need to enter the Ragel machine for unchunked transfers */
713 assert(hp->len.content >= 0 && "negative Content-Length");
714 if (hp->len.content > 0) {
715 long nr = MIN(dlen, hp->len.content);
718 memcpy(RSTRING_PTR(buf), dptr, nr);
719 hp->len.content -= nr;
720 if (hp->len.content == 0) {
721 HP_FL_SET(hp, REQEOF);
722 hp->cs = http_parser_first_final;
724 advance_str(data, nr);
725 rb_str_set_len(buf, nr);
729 hp->offset = 0; /* for trailer parsing */
733 #define SET_GLOBAL(var,str) do { \
734 var = find_common_field(str, sizeof(str) - 1); \
735 assert(!NIL_P(var) && "missed global field"); \
738 void Init_unicorn_http(void)
740 VALUE mUnicorn, cHttpParser;
742 mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
743 cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
745 rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
748 rb_define_alloc_func(cHttpParser, HttpParser_alloc);
749 rb_define_method(cHttpParser, "initialize", HttpParser_init,0);
750 rb_define_method(cHttpParser, "reset", HttpParser_reset,0);
751 rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
752 rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
753 rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
754 rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
755 rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
756 rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
757 rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
758 rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
759 rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
760 rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
761 rb_define_method(cHttpParser, "env", HttpParser_env, 0);
764 * The maximum size a single chunk when using chunked transfer encoding.
765 * This is only a theoretical maximum used to detect errors in clients,
766 * it is highly unlikely to encounter clients that send more than
767 * several kilobytes at once.
769 rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
772 * The maximum size of the body as specified by Content-Length.
773 * This is only a theoretical maximum, the actual limit is subject
774 * to the limits of the file system used for +Dir.tmpdir+.
776 rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
778 init_common_fields();
779 SET_GLOBAL(g_http_host, "HOST");
780 SET_GLOBAL(g_http_trailer, "TRAILER");
781 SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
782 SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
783 SET_GLOBAL(g_http_connection, "CONNECTION");
784 id_clear = rb_intern("clear");