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 void init_unicorn_httpdate(void);
17 #define UH_FL_CHUNKED 0x1
18 #define UH_FL_HASBODY 0x2
19 #define UH_FL_INBODY 0x4
20 #define UH_FL_HASTRAILER 0x8
21 #define UH_FL_INTRAILER 0x10
22 #define UH_FL_INCHUNK 0x20
23 #define UH_FL_REQEOF 0x40
24 #define UH_FL_KAVERSION 0x80
25 #define UH_FL_HASHEADER 0x100
26 #define UH_FL_TO_CLEAR 0x200
28 /* all of these flags need to be set for keepalive to be supported */
29 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
32 * whether or not to trust X-Forwarded-Proto and X-Forwarded-SSL when
33 * setting rack.url_scheme
35 static VALUE trust_x_forward = Qtrue;
37 static unsigned long keepalive_requests = 100; /* same as nginx */
40 * Returns the maximum number of keepalive requests a client may make
41 * before the parser refuses to continue.
43 static VALUE ka_req(VALUE self)
45 return ULONG2NUM(keepalive_requests);
49 * Sets the maximum number of keepalive requests a client may make.
50 * A special value of +nil+ causes this to be the maximum value
51 * possible (this is architecture-dependent).
53 static VALUE set_ka_req(VALUE self, VALUE val)
55 keepalive_requests = NIL_P(val) ? ULONG_MAX : NUM2ULONG(val);
61 * Sets whether or not the parser will trust X-Forwarded-Proto and
62 * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
63 * Rainbows!/Zbatery installations facing untrusted clients directly
64 * should set this to +false+
66 static VALUE set_xftrust(VALUE self, VALUE val)
68 if (Qtrue == val || Qfalse == val)
69 trust_x_forward = val;
71 rb_raise(rb_eTypeError, "must be true or false");
77 * returns whether or not the parser will trust X-Forwarded-Proto and
78 * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly
80 static VALUE xftrust(VALUE self)
82 return trust_x_forward;
85 /* keep this small for Rainbows! since every client has one */
87 int cs; /* Ragel internal state */
89 unsigned long nr_requests;
92 union { /* these 2 fields don't nest */
97 size_t field_len; /* only used during header processing */
98 size_t dest_offset; /* only used during body processing */
102 VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
109 static ID id_clear, id_set_backtrace;
111 static void finalize_header(struct http_parser *hp);
113 NORETURN(static void raise_with_empty_bt(VALUE));
115 static void raise_with_empty_bt(VALUE exc)
117 VALUE bt = rb_ary_new();
119 rb_funcall(exc, id_set_backtrace, 1, bt);
123 static void parser_error(const char *msg)
125 VALUE exc = rb_exc_new2(eHttpParserError, msg);
127 raise_with_empty_bt(exc);
130 static void raise_414(const char *msg)
132 VALUE exc = rb_exc_new2(eRequestURITooLongError, msg);
134 raise_with_empty_bt(exc);
137 #define REMAINING (unsigned long)(pe - p)
138 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
139 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
140 #define PTR_TO(F) (buffer + hp->F)
141 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
143 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
144 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
145 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
146 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
149 * handles values of the "Connection:" header, keepalive is implied
150 * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
151 * Additionally, we require GET/HEAD requests to support keepalive.
153 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
155 if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
156 /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
157 HP_FL_SET(hp, KAVERSION);
158 } else if (STR_CSTR_CASE_EQ(val, "close")) {
160 * it doesn't matter what HTTP version or request method we have,
161 * if a client says "Connection: close", we disable keepalive
163 HP_FL_UNSET(hp, KAVERSION);
166 * client could've sent anything, ignore it for now. Maybe
167 * "HP_FL_UNSET(hp, KAVERSION);" just in case?
168 * Raising an exception might be too mean...
174 request_method(struct http_parser *hp, const char *ptr, size_t len)
176 VALUE v = rb_str_new(ptr, len);
178 rb_hash_aset(hp->env, g_request_method, v);
182 http_version(struct http_parser *hp, const char *ptr, size_t len)
186 HP_FL_SET(hp, HASHEADER);
188 if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
189 /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
190 HP_FL_SET(hp, KAVERSION);
192 } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
195 v = rb_str_new(ptr, len);
197 rb_hash_aset(hp->env, g_server_protocol, v);
198 rb_hash_aset(hp->env, g_http_version, v);
201 static inline void hp_invalid_if_trailer(struct http_parser *hp)
203 if (HP_FL_TEST(hp, INTRAILER))
204 parser_error("invalid Trailer");
207 static void write_cont_value(struct http_parser *hp,
208 char *buffer, const char *p)
212 if (hp->cont == Qfalse)
213 parser_error("invalid continuation line");
215 return; /* we're ignoring this header (probably Host:) */
217 assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
218 assert(hp->mark > 0 && "impossible continuation line offset");
220 if (LEN(mark, p) == 0)
223 if (RSTRING_LEN(hp->cont) > 0)
228 if (RSTRING_LEN(hp->cont) > 0) {
229 assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
232 rb_str_buf_cat(hp->cont, vptr, LEN(mark, p));
235 static void write_value(struct http_parser *hp,
236 const char *buffer, const char *p)
238 VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
242 VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
243 v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STR_NEW(mark, p);
245 const char *field = PTR_TO(start.field);
246 size_t flen = hp->s.field_len;
248 VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
251 * ignore "Version" headers since they conflict with the HTTP_VERSION
254 if (CONST_MEM_EQ("VERSION", field, flen)) {
258 f = uncommon_field(field, flen);
259 } else if (f == g_http_connection) {
260 hp_keepalive_connection(hp, v);
261 } else if (f == g_content_length) {
262 hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
263 if (hp->len.content < 0)
264 parser_error("invalid Content-Length");
265 if (hp->len.content != 0)
266 HP_FL_SET(hp, HASBODY);
267 hp_invalid_if_trailer(hp);
268 } else if (f == g_http_transfer_encoding) {
269 if (STR_CSTR_CASE_EQ(v, "chunked")) {
270 HP_FL_SET(hp, CHUNKED);
271 HP_FL_SET(hp, HASBODY);
273 hp_invalid_if_trailer(hp);
274 } else if (f == g_http_trailer) {
275 HP_FL_SET(hp, HASTRAILER);
276 hp_invalid_if_trailer(hp);
278 assert(TYPE(f) == T_STRING && "memoized object is not a string");
282 e = rb_hash_aref(hp->env, f);
284 hp->cont = rb_hash_aset(hp->env, f, v);
285 } else if (f == g_http_host) {
287 * ignored, absolute URLs in REQUEST_URI take precedence over
288 * the Host: header (ref: rfc 2616, section 5.2.1)
292 rb_str_buf_cat(e, ",", 1);
293 hp->cont = rb_str_buf_append(e, v);
302 action mark {MARK(mark, fpc); }
304 action start_field { MARK(start.field, fpc); }
305 action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
306 action downcase_char { downcase_char(deconst(fpc)); }
307 action write_field { hp->s.field_len = LEN(start.field, fpc); }
308 action start_value { MARK(mark, fpc); }
309 action write_value { write_value(hp, buffer, fpc); }
310 action write_cont_value { write_cont_value(hp, buffer, fpc); }
311 action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
313 rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
315 action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
319 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
320 str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
322 * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
323 * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
325 if (STR_CSTR_EQ(str, "*")) {
326 str = rb_str_new(NULL, 0);
327 rb_hash_aset(hp->env, g_path_info, str);
328 rb_hash_aset(hp->env, g_request_path, str);
332 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
333 rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
335 action start_query {MARK(start.query, fpc); }
336 action query_string {
337 VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
338 rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
340 action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
341 action request_path {
344 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
345 val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
347 /* rack says PATH_INFO must start with "/" or be empty */
348 if (!STR_CSTR_EQ(val, "*"))
349 rb_hash_aset(hp->env, g_path_info, val);
351 action add_to_chunk_size {
352 hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
353 if (hp->len.chunk < 0)
354 parser_error("invalid chunk size");
359 cs = http_parser_first_final;
360 if (HP_FL_TEST(hp, HASBODY)) {
361 HP_FL_SET(hp, INBODY);
362 if (HP_FL_TEST(hp, CHUNKED))
363 cs = http_parser_en_ChunkedBody;
365 HP_FL_SET(hp, REQEOF);
366 assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
369 * go back to Ruby so we can call the Rack application, we'll reenter
370 * the parser iff the body needs to be processed.
375 action end_trailers {
376 cs = http_parser_first_final;
380 action end_chunked_body {
381 HP_FL_SET(hp, INTRAILER);
382 cs = http_parser_en_Trailers;
384 assert(p <= pe && "buffer overflow after chunked body");
388 action skip_chunk_data {
389 skip_chunk_data_hack: {
390 size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
391 memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
392 hp->s.dest_offset += nr;
395 assert(hp->len.chunk >= 0 && "negative chunk length");
396 if ((size_t)hp->len.chunk > REMAINING) {
397 HP_FL_SET(hp, INCHUNK);
405 include unicorn_http_common "unicorn_http_common.rl";
411 static void http_parser_init(struct http_parser *hp)
420 hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
427 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
431 size_t off = hp->offset;
433 if (cs == http_parser_first_final)
436 assert(off <= len && "offset past end of buffer");
441 assert((void *)(pe - p) == (void *)(len - off) &&
442 "pointers aren't same distance");
444 if (HP_FL_TEST(hp, INCHUNK)) {
445 HP_FL_UNSET(hp, INCHUNK);
446 goto skip_chunk_data_hack;
449 post_exec: /* "_out:" also goes here */
450 if (hp->cs != http_parser_error)
452 hp->offset = p - buffer;
454 assert(p <= pe && "buffer overflow after parsing execute");
455 assert(hp->offset <= len && "offset longer than length");
458 static struct http_parser *data_get(VALUE self)
460 struct http_parser *hp;
462 Data_Get_Struct(self, struct http_parser, hp);
463 assert(hp && "failed to extract http_parser struct");
468 * set rack.url_scheme to "https" or "http", no others are allowed by Rack
469 * this resembles the Rack::Request#scheme method as of rack commit
470 * 35bb5ba6746b5d346de9202c004cc926039650c7
472 static void set_url_scheme(VALUE env, VALUE *server_port)
474 VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
477 if (trust_x_forward == Qfalse) {
480 scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
481 if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
482 *server_port = g_port_443;
485 scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
489 long len = RSTRING_LEN(scheme);
490 if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
493 *server_port = g_port_443;
500 rb_hash_aset(env, g_rack_url_scheme, scheme);
501 } else if (STR_CSTR_EQ(scheme, "https")) {
502 *server_port = g_port_443;
504 assert(*server_port == g_port_80 && "server_port not set");
509 * Parse and set the SERVER_NAME and SERVER_PORT variables
510 * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
511 * anybody who needs them is using an unsupported configuration and/or
512 * incompetent. Rack::Request will handle X-Forwarded-{Port,Host} just
515 static void set_server_vars(VALUE env, VALUE *server_port)
517 VALUE server_name = g_localhost;
518 VALUE host = rb_hash_aref(env, g_http_host);
521 char *host_ptr = RSTRING_PTR(host);
522 long host_len = RSTRING_LEN(host);
525 if (*host_ptr == '[') { /* ipv6 address format */
526 char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
529 colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
531 colon = memchr(host_ptr + 1, ':', host_len - 1);
533 colon = memchr(host_ptr, ':', host_len);
537 long port_start = colon - host_ptr + 1;
539 server_name = rb_str_substr(host, 0, colon - host_ptr);
540 if ((host_len - port_start) > 0)
541 *server_port = rb_str_substr(host, port_start, host_len);
546 rb_hash_aset(env, g_server_name, server_name);
547 rb_hash_aset(env, g_server_port, *server_port);
550 static void finalize_header(struct http_parser *hp)
552 VALUE server_port = g_port_80;
554 set_url_scheme(hp->env, &server_port);
555 set_server_vars(hp->env, &server_port);
557 if (!HP_FL_TEST(hp, HASHEADER))
558 rb_hash_aset(hp->env, g_server_protocol, g_http_09);
560 /* rack requires QUERY_STRING */
561 if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
562 rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
565 static void hp_mark(void *ptr)
567 struct http_parser *hp = ptr;
571 rb_gc_mark(hp->cont);
574 static VALUE HttpParser_alloc(VALUE klass)
576 struct http_parser *hp;
577 return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
583 * parser.new => parser
585 * Creates a new parser.
587 static VALUE HttpParser_init(VALUE self)
589 struct http_parser *hp = data_get(self);
591 http_parser_init(hp);
592 hp->buf = rb_str_new(NULL, 0);
593 hp->env = rb_hash_new();
594 hp->nr_requests = keepalive_requests;
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.
606 static VALUE HttpParser_clear(VALUE self)
608 struct http_parser *hp = data_get(self);
610 http_parser_init(hp);
611 rb_funcall(hp->env, id_clear, 0);
618 * parser.reset => nil
620 * Resets the parser to it's initial state so that you can reuse it
621 * rather than making new ones.
623 * This method is deprecated and to be removed in Unicorn 4.x
625 static VALUE HttpParser_reset(VALUE self)
630 rb_warn("Unicorn::HttpParser#reset is deprecated; "
631 "use Unicorn::HttpParser#clear instead");
633 HttpParser_clear(self);
637 static void advance_str(VALUE str, off_t nr)
639 long len = RSTRING_LEN(str);
646 assert(nr <= len && "trying to advance past end of buffer");
648 if (len > 0) /* unlikely, len is usually 0 */
649 memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
650 rb_str_set_len(str, len);
655 * parser.content_length => nil or Integer
657 * Returns the number of bytes left to run through HttpParser#filter_body.
658 * This will initially be the value of the "Content-Length" HTTP header
659 * after header parsing is complete and will decrease in value as
660 * HttpParser#filter_body is called for each chunk. This should return
661 * zero for requests with no body.
663 * This will return nil on "Transfer-Encoding: chunked" requests.
665 static VALUE HttpParser_content_length(VALUE self)
667 struct http_parser *hp = data_get(self);
669 return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
673 * Document-method: parse
675 * parser.parse => env or nil
677 * Takes a Hash and a String of data, parses the String of data filling
678 * in the Hash returning the Hash if parsing is finished, nil otherwise
679 * When returning the env Hash, it may modify data to point to where
680 * body processing should begin.
682 * Raises HttpParserError if there are parsing errors.
684 static VALUE HttpParser_parse(VALUE self)
686 struct http_parser *hp = data_get(self);
687 VALUE data = hp->buf;
689 if (HP_FL_TEST(hp, TO_CLEAR)) {
690 http_parser_init(hp);
691 rb_funcall(hp->env, id_clear, 0);
694 http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
695 VALIDATE_MAX_LENGTH(hp->offset, HEADER);
697 if (hp->cs == http_parser_first_final ||
698 hp->cs == http_parser_en_ChunkedBody) {
699 advance_str(data, hp->offset + 1);
701 if (HP_FL_TEST(hp, INTRAILER))
702 HP_FL_SET(hp, REQEOF);
707 if (hp->cs == http_parser_error)
708 parser_error("Invalid HTTP format, parsing fails.");
714 * Document-method: trailers
716 * parser.trailers(req, data) => req or nil
718 * This is an alias for HttpParser#headers
722 * Document-method: headers
724 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
726 struct http_parser *hp = data_get(self);
731 return HttpParser_parse(self);
734 static int chunked_eof(struct http_parser *hp)
736 return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
741 * parser.body_eof? => true or false
743 * Detects if we're done filtering the body or not. This can be used
744 * to detect when to stop calling HttpParser#filter_body.
746 static VALUE HttpParser_body_eof(VALUE self)
748 struct http_parser *hp = data_get(self);
750 if (HP_FL_TEST(hp, CHUNKED))
751 return chunked_eof(hp) ? Qtrue : Qfalse;
753 return hp->len.content == 0 ? Qtrue : Qfalse;
758 * parser.keepalive? => true or false
760 * This should be used to detect if a request can really handle
761 * keepalives and pipelining. Currently, the rules are:
763 * 1. MUST be a GET or HEAD request
764 * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
765 * 3. MUST NOT have "Connection: close" set
767 static VALUE HttpParser_keepalive(VALUE self)
769 struct http_parser *hp = data_get(self);
771 return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
776 * parser.next? => true or false
778 * Exactly like HttpParser#keepalive?, except it will reset the internal
779 * parser state on next parse if it returns true. It will also respect
780 * the maximum *keepalive_requests* value and return false if that is
783 static VALUE HttpParser_next(VALUE self)
785 struct http_parser *hp = data_get(self);
787 if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
788 HP_FL_SET(hp, TO_CLEAR);
796 * parser.headers? => true or false
798 * This should be used to detect if a request has headers (and if
799 * the response will have headers as well). HTTP/0.9 requests
800 * should return false, all subsequent HTTP versions will return true
802 static VALUE HttpParser_has_headers(VALUE self)
804 struct http_parser *hp = data_get(self);
806 return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
809 static VALUE HttpParser_buf(VALUE self)
811 return data_get(self)->buf;
814 static VALUE HttpParser_env(VALUE self)
816 return data_get(self)->env;
821 * parser.filter_body(buf, data) => nil/data
823 * Takes a String of +data+, will modify data if dechunking is done.
824 * Returns +nil+ if there is more data left to process. Returns
825 * +data+ if body processing is complete. When returning +data+,
826 * it may modify +data+ so the start of the string points to where
827 * the body ended so that trailer processing can begin.
829 * Raises HttpParserError if there are dechunking errors.
830 * Basically this is a glorified memcpy(3) that copies +data+
831 * into +buf+ while filtering it through the dechunker.
833 static VALUE HttpParser_filter_body(VALUE self, VALUE buf, VALUE data)
835 struct http_parser *hp = data_get(self);
839 dptr = RSTRING_PTR(data);
840 dlen = RSTRING_LEN(data);
843 rb_str_resize(buf, dlen); /* we can never copy more than dlen bytes */
844 OBJ_TAINT(buf); /* keep weirdo $SAFE users happy */
846 if (HP_FL_TEST(hp, CHUNKED)) {
847 if (!chunked_eof(hp)) {
848 hp->s.dest_offset = 0;
851 http_parser_execute(hp, dptr, dlen);
852 if (hp->cs == http_parser_error)
853 parser_error("Invalid HTTP format, parsing fails.");
855 assert(hp->s.dest_offset <= hp->offset &&
856 "destination buffer overflow");
857 advance_str(data, hp->offset);
858 rb_str_set_len(buf, hp->s.dest_offset);
860 if (RSTRING_LEN(buf) == 0 && chunked_eof(hp)) {
861 assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
867 /* no need to enter the Ragel machine for unchunked transfers */
868 assert(hp->len.content >= 0 && "negative Content-Length");
869 if (hp->len.content > 0) {
870 long nr = MIN(dlen, hp->len.content);
873 memcpy(RSTRING_PTR(buf), dptr, nr);
874 hp->len.content -= nr;
875 if (hp->len.content == 0) {
876 HP_FL_SET(hp, REQEOF);
877 hp->cs = http_parser_first_final;
879 advance_str(data, nr);
880 rb_str_set_len(buf, nr);
884 hp->offset = 0; /* for trailer parsing */
888 #define SET_GLOBAL(var,str) do { \
889 var = find_common_field(str, sizeof(str) - 1); \
890 assert(!NIL_P(var) && "missed global field"); \
893 void Init_unicorn_http(void)
895 VALUE mUnicorn, cHttpParser;
897 mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
898 cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
900 rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
901 eRequestURITooLongError =
902 rb_define_class_under(mUnicorn, "RequestURITooLongError",
906 rb_define_alloc_func(cHttpParser, HttpParser_alloc);
907 rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
908 rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
909 rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
910 rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
911 rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
912 rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
913 rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
914 rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
915 rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
916 rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
917 rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
918 rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
919 rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
920 rb_define_method(cHttpParser, "env", HttpParser_env, 0);
923 * The maximum size a single chunk when using chunked transfer encoding.
924 * This is only a theoretical maximum used to detect errors in clients,
925 * it is highly unlikely to encounter clients that send more than
926 * several kilobytes at once.
928 rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
931 * The maximum size of the body as specified by Content-Length.
932 * This is only a theoretical maximum, the actual limit is subject
933 * to the limits of the file system used for +Dir.tmpdir+.
935 rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
937 /* default value for keepalive_requests */
938 rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
939 ULONG2NUM(keepalive_requests));
941 rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
942 rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
943 rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
944 rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
946 init_common_fields();
947 SET_GLOBAL(g_http_host, "HOST");
948 SET_GLOBAL(g_http_trailer, "TRAILER");
949 SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
950 SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
951 SET_GLOBAL(g_http_connection, "CONNECTION");
952 id_clear = rb_intern("clear");
953 id_set_backtrace = rb_intern("set_backtrace");
954 init_unicorn_httpdate();