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)
11 #include <sys/types.h>
12 #include "common_field_optimization.h"
13 #include "global_variables.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
28 #define UH_FL_RESSTART 0x400 /* for check_client_connection */
29 #define UH_FL_HIJACK 0x800
31 /* all of these flags need to be set for keepalive to be supported */
32 #define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER)
34 static unsigned int MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
36 /* this is only intended for use with Rainbows! */
37 static VALUE set_maxhdrlen(VALUE self, VALUE len)
39 return UINT2NUM(MAX_HEADER_LEN = NUM2UINT(len));
42 /* keep this small for other servers (e.g. yahns) since every client has one */
44 int cs; /* Ragel internal state */
48 union { /* these 2 fields don't nest */
53 unsigned int field_len; /* only used during header processing */
54 unsigned int dest_offset; /* only used during body processing */
58 VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
65 static ID id_set_backtrace, id_is_chunked_p;
66 static VALUE cHttpParser;
68 static void finalize_header(struct http_parser *hp);
70 static void parser_raise(VALUE klass, const char *msg)
72 VALUE exc = rb_exc_new2(klass, msg);
73 VALUE bt = rb_ary_new();
75 rb_funcall(exc, id_set_backtrace, 1, bt);
79 static inline unsigned int ulong2uint(unsigned long n)
81 unsigned int i = (unsigned int)n;
83 if (sizeof(unsigned int) != sizeof(unsigned long)) {
84 if ((unsigned long)i != n) {
85 rb_raise(rb_eRangeError, "too large to be 32-bit uint: %lu", n);
91 #define REMAINING (unsigned long)(pe - p)
92 #define LEN(AT, FPC) (ulong2uint(FPC - buffer) - hp->AT)
93 #define MARK(M,FPC) (hp->M = ulong2uint((FPC) - buffer))
94 #define PTR_TO(F) (buffer + hp->F)
95 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
96 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
98 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
99 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
100 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
101 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
103 static int is_lws(char c)
105 return (c == ' ' || c == '\t');
108 static VALUE stripped_str_new(const char *str, long len)
112 for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
114 return rb_str_new(str, end + 1);
118 * handles values of the "Connection:" header, keepalive is implied
119 * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
120 * Additionally, we require GET/HEAD requests to support keepalive.
122 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
124 if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
125 /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
126 HP_FL_SET(hp, KAVERSION);
127 } else if (STR_CSTR_CASE_EQ(val, "close")) {
129 * it doesn't matter what HTTP version or request method we have,
130 * if a client says "Connection: close", we disable keepalive
132 HP_FL_UNSET(hp, KAVERSION);
135 * client could've sent anything, ignore it for now. Maybe
136 * "HP_FL_UNSET(hp, KAVERSION);" just in case?
137 * Raising an exception might be too mean...
143 request_method(struct http_parser *hp, const char *ptr, size_t len)
145 VALUE v = rb_str_new(ptr, len);
147 rb_hash_aset(hp->env, g_request_method, v);
151 http_version(struct http_parser *hp, const char *ptr, size_t len)
155 HP_FL_SET(hp, HASHEADER);
157 if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
158 /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
159 HP_FL_SET(hp, KAVERSION);
161 } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
164 v = rb_str_new(ptr, len);
166 rb_hash_aset(hp->env, g_server_protocol, v);
167 rb_hash_aset(hp->env, g_http_version, v);
170 static inline void hp_invalid_if_trailer(struct http_parser *hp)
172 if (HP_FL_TEST(hp, INTRAILER))
173 parser_raise(eHttpParserError, "invalid Trailer");
176 static void write_cont_value(struct http_parser *hp,
177 char *buffer, const char *p)
181 long len = LEN(mark, p);
184 if (hp->cont == Qfalse)
185 parser_raise(eHttpParserError, "invalid continuation line");
187 return; /* we're ignoring this header (probably Host:) */
189 assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
190 assert(hp->mark > 0 && "impossible continuation line offset");
195 cont_len = RSTRING_LEN(hp->cont);
202 /* normalize tab to space */
204 assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
208 for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
209 rb_str_buf_cat(hp->cont, vptr, end + 1);
212 static int is_chunked(VALUE v)
214 /* common case first */
215 if (STR_CSTR_CASE_EQ(v, "chunked"))
219 * call Ruby function in unicorn/http_request.rb to deal with unlikely
220 * comma-delimited case
222 return rb_funcall(cHttpParser, id_is_chunked_p, 1, v) != Qfalse;
225 static void write_value(struct http_parser *hp,
226 const char *buffer, const char *p)
228 VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
232 VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
233 v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
235 const char *field = PTR_TO(start.field);
236 size_t flen = hp->s.field_len;
238 VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
241 * ignore "Version" headers since they conflict with the HTTP_VERSION
244 if (CONST_MEM_EQ("VERSION", field, flen)) {
248 f = uncommon_field(field, flen);
249 } else if (f == g_http_connection) {
250 hp_keepalive_connection(hp, v);
251 } else if (f == g_content_length && !HP_FL_TEST(hp, CHUNKED)) {
253 parser_raise(eHttpParserError, "Content-Length already set");
254 hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
255 if (hp->len.content < 0)
256 parser_raise(eHttpParserError, "invalid Content-Length");
257 if (hp->len.content != 0)
258 HP_FL_SET(hp, HASBODY);
259 hp_invalid_if_trailer(hp);
260 } else if (f == g_http_transfer_encoding) {
262 if (HP_FL_TEST(hp, CHUNKED))
265 * A sender MUST NOT apply chunked more than once to a message body
266 * (i.e., chunking an already chunked message is not allowed).
268 parser_raise(eHttpParserError, "Transfer-Encoding double chunked");
270 HP_FL_SET(hp, CHUNKED);
271 HP_FL_SET(hp, HASBODY);
273 /* RFC 7230 3.3.3, 3: favor chunked if Content-Length exists */
275 } else if (HP_FL_TEST(hp, CHUNKED)) {
277 * RFC 7230 3.3.3, point 3 states:
278 * If a Transfer-Encoding header field is present in a request and
279 * the chunked transfer coding is not the final encoding, the
280 * message body length cannot be determined reliably; the server
281 * MUST respond with the 400 (Bad Request) status code and then
282 * close the connection.
284 parser_raise(eHttpParserError, "invalid Transfer-Encoding");
286 hp_invalid_if_trailer(hp);
287 } else if (f == g_http_trailer) {
288 HP_FL_SET(hp, HASTRAILER);
289 hp_invalid_if_trailer(hp);
291 assert(TYPE(f) == T_STRING && "memoized object is not a string");
295 e = rb_hash_aref(hp->env, f);
297 hp->cont = rb_hash_aset(hp->env, f, v);
298 } else if (f == g_http_host) {
300 * ignored, absolute URLs in REQUEST_URI take precedence over
301 * the Host: header (ref: rfc 2616, section 5.2.1)
305 rb_str_buf_cat(e, ",", 1);
306 hp->cont = rb_str_buf_append(e, v);
315 action mark {MARK(mark, fpc); }
317 action start_field { MARK(start.field, fpc); }
318 action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
319 action downcase_char { downcase_char(deconst(fpc)); }
320 action write_field { hp->s.field_len = LEN(start.field, fpc); }
321 action start_value { MARK(mark, fpc); }
322 action write_value { write_value(hp, buffer, fpc); }
323 action write_cont_value { write_cont_value(hp, buffer, fpc); }
324 action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
326 rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
328 action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
332 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
333 str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
335 * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
336 * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
338 if (STR_CSTR_EQ(str, "*")) {
339 str = rb_str_new(NULL, 0);
340 rb_hash_aset(hp->env, g_path_info, str);
341 rb_hash_aset(hp->env, g_request_path, str);
345 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
346 rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
348 action start_query {MARK(start.query, fpc); }
349 action query_string {
350 VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
351 rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
353 action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
354 action request_path {
357 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
358 val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
360 /* rack says PATH_INFO must start with "/" or be empty */
361 if (!STR_CSTR_EQ(val, "*"))
362 rb_hash_aset(hp->env, g_path_info, val);
364 action add_to_chunk_size {
365 hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
366 if (hp->len.chunk < 0)
367 parser_raise(eHttpParserError, "invalid chunk size");
372 cs = http_parser_first_final;
373 if (HP_FL_TEST(hp, HASBODY)) {
374 HP_FL_SET(hp, INBODY);
375 if (HP_FL_TEST(hp, CHUNKED))
376 cs = http_parser_en_ChunkedBody;
378 HP_FL_SET(hp, REQEOF);
379 assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
382 * go back to Ruby so we can call the Rack application, we'll reenter
383 * the parser iff the body needs to be processed.
388 action end_trailers {
389 cs = http_parser_first_final;
393 action end_chunked_body {
394 HP_FL_SET(hp, INTRAILER);
395 cs = http_parser_en_Trailers;
397 assert(p <= pe && "buffer overflow after chunked body");
401 action skip_chunk_data {
402 skip_chunk_data_hack: {
403 size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
404 memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
405 hp->s.dest_offset += nr;
408 assert(hp->len.chunk >= 0 && "negative chunk length");
409 if ((size_t)hp->len.chunk > REMAINING) {
410 HP_FL_SET(hp, INCHUNK);
418 include unicorn_http_common "unicorn_http_common.rl";
424 static void http_parser_init(struct http_parser *hp)
433 hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
440 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
444 size_t off = hp->offset;
446 if (cs == http_parser_first_final)
449 assert(off <= len && "offset past end of buffer");
454 assert((void *)(pe - p) == (void *)(len - off) &&
455 "pointers aren't same distance");
457 if (HP_FL_TEST(hp, INCHUNK)) {
458 HP_FL_UNSET(hp, INCHUNK);
459 goto skip_chunk_data_hack;
462 post_exec: /* "_out:" also goes here */
463 if (hp->cs != http_parser_error)
465 hp->offset = ulong2uint(p - buffer);
467 assert(p <= pe && "buffer overflow after parsing execute");
468 assert(hp->offset <= len && "offset longer than length");
471 static void hp_mark(void *ptr)
473 struct http_parser *hp = ptr;
477 rb_gc_mark(hp->cont);
480 static size_t hp_memsize(const void *ptr)
482 return sizeof(struct http_parser);
485 static const rb_data_type_t hp_type = {
487 { hp_mark, RUBY_TYPED_DEFAULT_FREE, hp_memsize, /* reserved */ },
488 /* parent, data, [ flags ] */
491 static struct http_parser *data_get(VALUE self)
493 struct http_parser *hp;
495 TypedData_Get_Struct(self, struct http_parser, &hp_type, hp);
496 assert(hp && "failed to extract http_parser struct");
501 * set rack.url_scheme to "https" or "http", no others are allowed by Rack
502 * this resembles the Rack::Request#scheme method as of rack commit
503 * 35bb5ba6746b5d346de9202c004cc926039650c7
505 static void set_url_scheme(VALUE env, VALUE *server_port)
507 VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
511 * would anybody be horribly opposed to removing the X-Forwarded-SSL
512 * and X-Forwarded-Proto handling from this parser? We've had it
513 * forever and nobody has said anything against it, either.
514 * Anyways, please send comments to our public mailing list:
515 * unicorn-public@yhbt.net (no HTML mail, no subscription necessary)
517 scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
518 if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
519 *server_port = g_port_443;
522 scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
526 long len = RSTRING_LEN(scheme);
527 if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
530 *server_port = g_port_443;
536 rb_hash_aset(env, g_rack_url_scheme, scheme);
537 } else if (STR_CSTR_EQ(scheme, "https")) {
538 *server_port = g_port_443;
540 assert(*server_port == g_port_80 && "server_port not set");
545 * Parse and set the SERVER_NAME and SERVER_PORT variables
546 * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
547 * anybody who needs them is using an unsupported configuration and/or
548 * incompetent. Rack::Request will handle X-Forwarded-{Port,Host} just
551 static void set_server_vars(VALUE env, VALUE *server_port)
553 VALUE server_name = g_localhost;
554 VALUE host = rb_hash_aref(env, g_http_host);
557 char *host_ptr = RSTRING_PTR(host);
558 long host_len = RSTRING_LEN(host);
561 if (*host_ptr == '[') { /* ipv6 address format */
562 char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
565 colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
567 colon = memchr(host_ptr + 1, ':', host_len - 1);
569 colon = memchr(host_ptr, ':', host_len);
573 long port_start = colon - host_ptr + 1;
575 server_name = rb_str_substr(host, 0, colon - host_ptr);
576 if ((host_len - port_start) > 0)
577 *server_port = rb_str_substr(host, port_start, host_len);
582 rb_hash_aset(env, g_server_name, server_name);
583 rb_hash_aset(env, g_server_port, *server_port);
586 static void finalize_header(struct http_parser *hp)
588 VALUE server_port = g_port_80;
590 set_url_scheme(hp->env, &server_port);
591 set_server_vars(hp->env, &server_port);
593 if (!HP_FL_TEST(hp, HASHEADER))
594 rb_hash_aset(hp->env, g_server_protocol, g_http_09);
596 /* rack requires QUERY_STRING */
597 if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
598 rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
601 static VALUE HttpParser_alloc(VALUE klass)
603 struct http_parser *hp;
605 return TypedData_Make_Struct(klass, struct http_parser, &hp_type, hp);
610 * parser.new => parser
612 * Creates a new parser.
614 static VALUE HttpParser_init(VALUE self)
616 struct http_parser *hp = data_get(self);
618 http_parser_init(hp);
619 hp->buf = rb_str_new(NULL, 0);
620 hp->env = rb_hash_new();
627 * parser.clear => parser
629 * Resets the parser to it's initial state so that you can reuse it
630 * rather than making new ones.
632 static VALUE HttpParser_clear(VALUE self)
634 struct http_parser *hp = data_get(self);
636 /* we can't safely reuse .buf and .env if hijacked */
637 if (HP_FL_TEST(hp, HIJACK))
638 return HttpParser_init(self);
640 http_parser_init(hp);
641 rb_hash_clear(hp->env);
646 static void advance_str(VALUE str, off_t nr)
648 long len = RSTRING_LEN(str);
655 assert(nr <= len && "trying to advance past end of buffer");
657 if (len > 0) /* unlikely, len is usually 0 */
658 memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
659 rb_str_set_len(str, len);
664 * parser.content_length => nil or Integer
666 * Returns the number of bytes left to run through HttpParser#filter_body.
667 * This will initially be the value of the "Content-Length" HTTP header
668 * after header parsing is complete and will decrease in value as
669 * HttpParser#filter_body is called for each chunk. This should return
670 * zero for requests with no body.
672 * This will return nil on "Transfer-Encoding: chunked" requests.
674 static VALUE HttpParser_content_length(VALUE self)
676 struct http_parser *hp = data_get(self);
678 return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
682 * Document-method: parse
684 * parser.parse => env or nil
686 * Takes a Hash and a String of data, parses the String of data filling
687 * in the Hash returning the Hash if parsing is finished, nil otherwise
688 * When returning the env Hash, it may modify data to point to where
689 * body processing should begin.
691 * Raises HttpParserError if there are parsing errors.
693 static VALUE HttpParser_parse(VALUE self)
695 struct http_parser *hp = data_get(self);
696 VALUE data = hp->buf;
698 if (HP_FL_TEST(hp, TO_CLEAR))
699 HttpParser_clear(self);
701 http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
702 if (hp->offset > MAX_HEADER_LEN)
703 parser_raise(e413, "HTTP header is too large");
705 if (hp->cs == http_parser_first_final ||
706 hp->cs == http_parser_en_ChunkedBody) {
707 advance_str(data, hp->offset + 1);
709 if (HP_FL_TEST(hp, INTRAILER))
710 HP_FL_SET(hp, REQEOF);
715 if (hp->cs == http_parser_error)
716 parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
722 * Document-method: parse
724 * parser.add_parse(buffer) => env or nil
726 * adds the contents of +buffer+ to the internal buffer and attempts to
727 * continue parsing. Returns the +env+ Hash on success or nil if more
730 * Raises HttpParserError if there are parsing errors.
732 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
734 struct http_parser *hp = data_get(self);
736 Check_Type(buffer, T_STRING);
737 rb_str_buf_append(hp->buf, buffer);
739 return HttpParser_parse(self);
743 * Document-method: trailers
745 * parser.trailers(req, data) => req or nil
747 * This is an alias for HttpParser#headers
751 * Document-method: headers
753 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
755 struct http_parser *hp = data_get(self);
760 return HttpParser_parse(self);
763 static int chunked_eof(struct http_parser *hp)
765 return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
770 * parser.body_eof? => true or false
772 * Detects if we're done filtering the body or not. This can be used
773 * to detect when to stop calling HttpParser#filter_body.
775 static VALUE HttpParser_body_eof(VALUE self)
777 struct http_parser *hp = data_get(self);
779 if (HP_FL_TEST(hp, CHUNKED))
780 return chunked_eof(hp) ? Qtrue : Qfalse;
782 return hp->len.content == 0 ? Qtrue : Qfalse;
787 * parser.keepalive? => true or false
789 * This should be used to detect if a request can really handle
790 * keepalives and pipelining. Currently, the rules are:
792 * 1. MUST be a GET or HEAD request
793 * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
794 * 3. MUST NOT have "Connection: close" set
796 static VALUE HttpParser_keepalive(VALUE self)
798 struct http_parser *hp = data_get(self);
800 return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
805 * parser.next? => true or false
807 * Exactly like HttpParser#keepalive?, except it will reset the internal
808 * parser state on next parse if it returns true.
810 static VALUE HttpParser_next(VALUE self)
812 struct http_parser *hp = data_get(self);
814 if (HP_FL_ALL(hp, KEEPALIVE)) {
815 HP_FL_SET(hp, TO_CLEAR);
823 * parser.headers? => true or false
825 * This should be used to detect if a request has headers (and if
826 * the response will have headers as well). HTTP/0.9 requests
827 * should return false, all subsequent HTTP versions will return true
829 static VALUE HttpParser_has_headers(VALUE self)
831 struct http_parser *hp = data_get(self);
833 return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
836 static VALUE HttpParser_buf(VALUE self)
838 return data_get(self)->buf;
841 static VALUE HttpParser_env(VALUE self)
843 return data_get(self)->env;
846 static VALUE HttpParser_hijacked_bang(VALUE self)
848 struct http_parser *hp = data_get(self);
850 HP_FL_SET(hp, HIJACK);
857 * parser.filter_body(dst, src) => nil/src
859 * Takes a String of +src+, will modify data if dechunking is done.
860 * Returns +nil+ if there is more data left to process. Returns
861 * +src+ if body processing is complete. When returning +src+,
862 * it may modify +src+ so the start of the string points to where
863 * the body ended so that trailer processing can begin.
865 * Raises HttpParserError if there are dechunking errors.
866 * Basically this is a glorified memcpy(3) that copies +src+
867 * into +buf+ while filtering it through the dechunker.
869 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
871 struct http_parser *hp = data_get(self);
875 srcptr = RSTRING_PTR(src);
876 srclen = RSTRING_LEN(src);
880 if (HP_FL_TEST(hp, CHUNKED)) {
881 if (!chunked_eof(hp)) {
883 rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
885 hp->s.dest_offset = 0;
888 http_parser_execute(hp, srcptr, srclen);
889 if (hp->cs == http_parser_error)
890 parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
892 assert(hp->s.dest_offset <= hp->offset &&
893 "destination buffer overflow");
894 advance_str(src, hp->offset);
895 rb_str_set_len(dst, hp->s.dest_offset);
897 if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
898 assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
904 /* no need to enter the Ragel machine for unchunked transfers */
905 assert(hp->len.content >= 0 && "negative Content-Length");
906 if (hp->len.content > 0) {
907 long nr = MIN(srclen, hp->len.content);
910 rb_str_resize(dst, nr);
912 * using rb_str_replace() to avoid memcpy() doesn't help in
913 * most cases because a GC-aware programmer will pass an explicit
914 * buffer to env["rack.input"].read and reuse the buffer in a loop.
915 * This causes copy-on-write behavior to be triggered anyways
916 * when the +src+ buffer is modified (when reading off the socket).
919 memcpy(RSTRING_PTR(dst), srcptr, nr);
920 hp->len.content -= nr;
921 if (hp->len.content == 0) {
922 HP_FL_SET(hp, REQEOF);
923 hp->cs = http_parser_first_final;
925 advance_str(src, nr);
929 hp->offset = 0; /* for trailer parsing */
933 static VALUE HttpParser_rssset(VALUE self, VALUE boolean)
935 struct http_parser *hp = data_get(self);
938 HP_FL_SET(hp, RESSTART);
940 HP_FL_UNSET(hp, RESSTART);
942 return boolean; /* ignored by Ruby anyways */
945 static VALUE HttpParser_rssget(VALUE self)
947 struct http_parser *hp = data_get(self);
949 return HP_FL_TEST(hp, RESSTART) ? Qtrue : Qfalse;
952 #define SET_GLOBAL(var,str) do { \
953 var = find_common_field(str, sizeof(str) - 1); \
954 assert(!NIL_P(var) && "missed global field"); \
957 void Init_unicorn_http(void)
961 mUnicorn = rb_define_module("Unicorn");
962 cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
964 rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
965 e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
967 e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
971 rb_define_alloc_func(cHttpParser, HttpParser_alloc);
972 rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
973 rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
974 rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
975 rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
976 rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
977 rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
978 rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
979 rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
980 rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
981 rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
982 rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
983 rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
984 rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
985 rb_define_method(cHttpParser, "env", HttpParser_env, 0);
986 rb_define_method(cHttpParser, "hijacked!", HttpParser_hijacked_bang, 0);
987 rb_define_method(cHttpParser, "response_start_sent=", HttpParser_rssset, 1);
988 rb_define_method(cHttpParser, "response_start_sent", HttpParser_rssget, 0);
991 * The maximum size a single chunk when using chunked transfer encoding.
992 * This is only a theoretical maximum used to detect errors in clients,
993 * it is highly unlikely to encounter clients that send more than
994 * several kilobytes at once.
996 rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
999 * The maximum size of the body as specified by Content-Length.
1000 * This is only a theoretical maximum, the actual limit is subject
1001 * to the limits of the file system used for +Dir.tmpdir+.
1003 rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
1005 rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
1007 init_common_fields();
1008 SET_GLOBAL(g_http_host, "HOST");
1009 SET_GLOBAL(g_http_trailer, "TRAILER");
1010 SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
1011 SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1012 SET_GLOBAL(g_http_connection, "CONNECTION");
1013 id_set_backtrace = rb_intern("set_backtrace");
1014 init_unicorn_httpdate();
1016 #ifndef HAVE_RB_HASH_CLEAR
1017 id_clear = rb_intern("clear");
1019 id_is_chunked_p = rb_intern("is_chunked?");