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 static size_t MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */
87 /* this is only intended for use with Rainbows! */
88 static VALUE set_maxhdrlen(VALUE self, VALUE len)
90 return SIZET2NUM(MAX_HEADER_LEN = NUM2SIZET(len));
93 /* keep this small for Rainbows! since every client has one */
95 int cs; /* Ragel internal state */
97 unsigned long nr_requests;
100 union { /* these 2 fields don't nest */
105 size_t field_len; /* only used during header processing */
106 size_t dest_offset; /* only used during body processing */
110 VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */
117 static ID id_clear, id_set_backtrace;
119 static void finalize_header(struct http_parser *hp);
121 static void parser_raise(VALUE klass, const char *msg)
123 VALUE exc = rb_exc_new2(klass, msg);
124 VALUE bt = rb_ary_new();
126 rb_funcall(exc, id_set_backtrace, 1, bt);
130 #define REMAINING (unsigned long)(pe - p)
131 #define LEN(AT, FPC) (FPC - buffer - hp->AT)
132 #define MARK(M,FPC) (hp->M = (FPC) - buffer)
133 #define PTR_TO(F) (buffer + hp->F)
134 #define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC))
135 #define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC))
137 #define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl))
138 #define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl))
139 #define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl))
140 #define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl))
142 static int is_lws(char c)
144 return (c == ' ' || c == '\t');
147 static VALUE stripped_str_new(const char *str, long len)
151 for (end = len - 1; end >= 0 && is_lws(str[end]); end--);
153 return rb_str_new(str, end + 1);
157 * handles values of the "Connection:" header, keepalive is implied
158 * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0
159 * Additionally, we require GET/HEAD requests to support keepalive.
161 static void hp_keepalive_connection(struct http_parser *hp, VALUE val)
163 if (STR_CSTR_CASE_EQ(val, "keep-alive")) {
164 /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */
165 HP_FL_SET(hp, KAVERSION);
166 } else if (STR_CSTR_CASE_EQ(val, "close")) {
168 * it doesn't matter what HTTP version or request method we have,
169 * if a client says "Connection: close", we disable keepalive
171 HP_FL_UNSET(hp, KAVERSION);
174 * client could've sent anything, ignore it for now. Maybe
175 * "HP_FL_UNSET(hp, KAVERSION);" just in case?
176 * Raising an exception might be too mean...
182 request_method(struct http_parser *hp, const char *ptr, size_t len)
184 VALUE v = rb_str_new(ptr, len);
186 rb_hash_aset(hp->env, g_request_method, v);
190 http_version(struct http_parser *hp, const char *ptr, size_t len)
194 HP_FL_SET(hp, HASHEADER);
196 if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) {
197 /* HTTP/1.1 implies keepalive unless "Connection: close" is set */
198 HP_FL_SET(hp, KAVERSION);
200 } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) {
203 v = rb_str_new(ptr, len);
205 rb_hash_aset(hp->env, g_server_protocol, v);
206 rb_hash_aset(hp->env, g_http_version, v);
209 static inline void hp_invalid_if_trailer(struct http_parser *hp)
211 if (HP_FL_TEST(hp, INTRAILER))
212 parser_raise(eHttpParserError, "invalid Trailer");
215 static void write_cont_value(struct http_parser *hp,
216 char *buffer, const char *p)
220 long len = LEN(mark, p);
223 if (hp->cont == Qfalse)
224 parser_raise(eHttpParserError, "invalid continuation line");
226 return; /* we're ignoring this header (probably Host:) */
228 assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string");
229 assert(hp->mark > 0 && "impossible continuation line offset");
234 cont_len = RSTRING_LEN(hp->cont);
241 /* normalize tab to space */
243 assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space");
247 for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--);
248 rb_str_buf_cat(hp->cont, vptr, end + 1);
251 static void write_value(struct http_parser *hp,
252 const char *buffer, const char *p)
254 VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len);
258 VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE);
259 v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p);
261 const char *field = PTR_TO(start.field);
262 size_t flen = hp->s.field_len;
264 VALIDATE_MAX_LENGTH(flen, FIELD_NAME);
267 * ignore "Version" headers since they conflict with the HTTP_VERSION
270 if (CONST_MEM_EQ("VERSION", field, flen)) {
274 f = uncommon_field(field, flen);
275 } else if (f == g_http_connection) {
276 hp_keepalive_connection(hp, v);
277 } else if (f == g_content_length) {
278 hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v));
279 if (hp->len.content < 0)
280 parser_raise(eHttpParserError, "invalid Content-Length");
281 if (hp->len.content != 0)
282 HP_FL_SET(hp, HASBODY);
283 hp_invalid_if_trailer(hp);
284 } else if (f == g_http_transfer_encoding) {
285 if (STR_CSTR_CASE_EQ(v, "chunked")) {
286 HP_FL_SET(hp, CHUNKED);
287 HP_FL_SET(hp, HASBODY);
289 hp_invalid_if_trailer(hp);
290 } else if (f == g_http_trailer) {
291 HP_FL_SET(hp, HASTRAILER);
292 hp_invalid_if_trailer(hp);
294 assert(TYPE(f) == T_STRING && "memoized object is not a string");
298 e = rb_hash_aref(hp->env, f);
300 hp->cont = rb_hash_aset(hp->env, f, v);
301 } else if (f == g_http_host) {
303 * ignored, absolute URLs in REQUEST_URI take precedence over
304 * the Host: header (ref: rfc 2616, section 5.2.1)
308 rb_str_buf_cat(e, ",", 1);
309 hp->cont = rb_str_buf_append(e, v);
318 action mark {MARK(mark, fpc); }
320 action start_field { MARK(start.field, fpc); }
321 action snake_upcase_field { snake_upcase_char(deconst(fpc)); }
322 action downcase_char { downcase_char(deconst(fpc)); }
323 action write_field { hp->s.field_len = LEN(start.field, fpc); }
324 action start_value { MARK(mark, fpc); }
325 action write_value { write_value(hp, buffer, fpc); }
326 action write_cont_value { write_cont_value(hp, buffer, fpc); }
327 action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); }
329 rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc));
331 action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); }
335 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI);
336 str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc));
338 * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*'
339 * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain
341 if (STR_CSTR_EQ(str, "*")) {
342 str = rb_str_new(NULL, 0);
343 rb_hash_aset(hp->env, g_path_info, str);
344 rb_hash_aset(hp->env, g_request_path, str);
348 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT);
349 rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc));
351 action start_query {MARK(start.query, fpc); }
352 action query_string {
353 VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING);
354 rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc));
356 action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); }
357 action request_path {
360 VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH);
361 val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc));
363 /* rack says PATH_INFO must start with "/" or be empty */
364 if (!STR_CSTR_EQ(val, "*"))
365 rb_hash_aset(hp->env, g_path_info, val);
367 action add_to_chunk_size {
368 hp->len.chunk = step_incr(hp->len.chunk, fc, 16);
369 if (hp->len.chunk < 0)
370 parser_raise(eHttpParserError, "invalid chunk size");
375 cs = http_parser_first_final;
376 if (HP_FL_TEST(hp, HASBODY)) {
377 HP_FL_SET(hp, INBODY);
378 if (HP_FL_TEST(hp, CHUNKED))
379 cs = http_parser_en_ChunkedBody;
381 HP_FL_SET(hp, REQEOF);
382 assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!");
385 * go back to Ruby so we can call the Rack application, we'll reenter
386 * the parser iff the body needs to be processed.
391 action end_trailers {
392 cs = http_parser_first_final;
396 action end_chunked_body {
397 HP_FL_SET(hp, INTRAILER);
398 cs = http_parser_en_Trailers;
400 assert(p <= pe && "buffer overflow after chunked body");
404 action skip_chunk_data {
405 skip_chunk_data_hack: {
406 size_t nr = MIN((size_t)hp->len.chunk, REMAINING);
407 memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr);
408 hp->s.dest_offset += nr;
411 assert(hp->len.chunk >= 0 && "negative chunk length");
412 if ((size_t)hp->len.chunk > REMAINING) {
413 HP_FL_SET(hp, INCHUNK);
421 include unicorn_http_common "unicorn_http_common.rl";
427 static void http_parser_init(struct http_parser *hp)
436 hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */
443 http_parser_execute(struct http_parser *hp, char *buffer, size_t len)
447 size_t off = hp->offset;
449 if (cs == http_parser_first_final)
452 assert(off <= len && "offset past end of buffer");
457 assert((void *)(pe - p) == (void *)(len - off) &&
458 "pointers aren't same distance");
460 if (HP_FL_TEST(hp, INCHUNK)) {
461 HP_FL_UNSET(hp, INCHUNK);
462 goto skip_chunk_data_hack;
465 post_exec: /* "_out:" also goes here */
466 if (hp->cs != http_parser_error)
468 hp->offset = p - buffer;
470 assert(p <= pe && "buffer overflow after parsing execute");
471 assert(hp->offset <= len && "offset longer than length");
474 static struct http_parser *data_get(VALUE self)
476 struct http_parser *hp;
478 Data_Get_Struct(self, struct http_parser, hp);
479 assert(hp && "failed to extract http_parser struct");
484 * set rack.url_scheme to "https" or "http", no others are allowed by Rack
485 * this resembles the Rack::Request#scheme method as of rack commit
486 * 35bb5ba6746b5d346de9202c004cc926039650c7
488 static void set_url_scheme(VALUE env, VALUE *server_port)
490 VALUE scheme = rb_hash_aref(env, g_rack_url_scheme);
493 if (trust_x_forward == Qfalse) {
496 scheme = rb_hash_aref(env, g_http_x_forwarded_ssl);
497 if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) {
498 *server_port = g_port_443;
501 scheme = rb_hash_aref(env, g_http_x_forwarded_proto);
505 long len = RSTRING_LEN(scheme);
506 if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) {
509 *server_port = g_port_443;
516 rb_hash_aset(env, g_rack_url_scheme, scheme);
517 } else if (STR_CSTR_EQ(scheme, "https")) {
518 *server_port = g_port_443;
520 assert(*server_port == g_port_80 && "server_port not set");
525 * Parse and set the SERVER_NAME and SERVER_PORT variables
526 * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since
527 * anybody who needs them is using an unsupported configuration and/or
528 * incompetent. Rack::Request will handle X-Forwarded-{Port,Host} just
531 static void set_server_vars(VALUE env, VALUE *server_port)
533 VALUE server_name = g_localhost;
534 VALUE host = rb_hash_aref(env, g_http_host);
537 char *host_ptr = RSTRING_PTR(host);
538 long host_len = RSTRING_LEN(host);
541 if (*host_ptr == '[') { /* ipv6 address format */
542 char *rbracket = memchr(host_ptr + 1, ']', host_len - 1);
545 colon = (rbracket[1] == ':') ? rbracket + 1 : NULL;
547 colon = memchr(host_ptr + 1, ':', host_len - 1);
549 colon = memchr(host_ptr, ':', host_len);
553 long port_start = colon - host_ptr + 1;
555 server_name = rb_str_substr(host, 0, colon - host_ptr);
556 if ((host_len - port_start) > 0)
557 *server_port = rb_str_substr(host, port_start, host_len);
562 rb_hash_aset(env, g_server_name, server_name);
563 rb_hash_aset(env, g_server_port, *server_port);
566 static void finalize_header(struct http_parser *hp)
568 VALUE server_port = g_port_80;
570 set_url_scheme(hp->env, &server_port);
571 set_server_vars(hp->env, &server_port);
573 if (!HP_FL_TEST(hp, HASHEADER))
574 rb_hash_aset(hp->env, g_server_protocol, g_http_09);
576 /* rack requires QUERY_STRING */
577 if (NIL_P(rb_hash_aref(hp->env, g_query_string)))
578 rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0));
581 static void hp_mark(void *ptr)
583 struct http_parser *hp = ptr;
587 rb_gc_mark(hp->cont);
590 static VALUE HttpParser_alloc(VALUE klass)
592 struct http_parser *hp;
593 return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp);
599 * parser.new => parser
601 * Creates a new parser.
603 static VALUE HttpParser_init(VALUE self)
605 struct http_parser *hp = data_get(self);
607 http_parser_init(hp);
608 hp->buf = rb_str_new(NULL, 0);
609 hp->env = rb_hash_new();
610 hp->nr_requests = keepalive_requests;
617 * parser.clear => parser
619 * Resets the parser to it's initial state so that you can reuse it
620 * rather than making new ones.
622 static VALUE HttpParser_clear(VALUE self)
624 struct http_parser *hp = data_get(self);
626 http_parser_init(hp);
627 rb_funcall(hp->env, id_clear, 0);
634 * parser.dechunk! => parser
636 * Resets the parser to a state suitable for dechunking response bodies
639 static VALUE HttpParser_dechunk_bang(VALUE self)
641 struct http_parser *hp = data_get(self);
643 http_parser_init(hp);
646 * we don't care about trailers in dechunk-only mode,
647 * but if we did we'd set UH_FL_HASTRAILER and clear hp->env
650 rb_funcall(hp->env, id_clear, 0);
651 hp->flags = UH_FL_HASTRAILER;
654 hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED;
655 hp->cs = http_parser_en_ChunkedBody;
662 * parser.reset => nil
664 * Resets the parser to it's initial state so that you can reuse it
665 * rather than making new ones.
667 * This method is deprecated and to be removed in Unicorn 4.x
669 static VALUE HttpParser_reset(VALUE self)
674 rb_warn("Unicorn::HttpParser#reset is deprecated; "
675 "use Unicorn::HttpParser#clear instead");
677 HttpParser_clear(self);
681 static void advance_str(VALUE str, off_t nr)
683 long len = RSTRING_LEN(str);
690 assert(nr <= len && "trying to advance past end of buffer");
692 if (len > 0) /* unlikely, len is usually 0 */
693 memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len);
694 rb_str_set_len(str, len);
699 * parser.content_length => nil or Integer
701 * Returns the number of bytes left to run through HttpParser#filter_body.
702 * This will initially be the value of the "Content-Length" HTTP header
703 * after header parsing is complete and will decrease in value as
704 * HttpParser#filter_body is called for each chunk. This should return
705 * zero for requests with no body.
707 * This will return nil on "Transfer-Encoding: chunked" requests.
709 static VALUE HttpParser_content_length(VALUE self)
711 struct http_parser *hp = data_get(self);
713 return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content);
717 * Document-method: parse
719 * parser.parse => env or nil
721 * Takes a Hash and a String of data, parses the String of data filling
722 * in the Hash returning the Hash if parsing is finished, nil otherwise
723 * When returning the env Hash, it may modify data to point to where
724 * body processing should begin.
726 * Raises HttpParserError if there are parsing errors.
728 static VALUE HttpParser_parse(VALUE self)
730 struct http_parser *hp = data_get(self);
731 VALUE data = hp->buf;
733 if (HP_FL_TEST(hp, TO_CLEAR)) {
734 http_parser_init(hp);
735 rb_funcall(hp->env, id_clear, 0);
738 http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data));
739 if (hp->offset > MAX_HEADER_LEN)
740 parser_raise(e413, "HTTP header is too large");
742 if (hp->cs == http_parser_first_final ||
743 hp->cs == http_parser_en_ChunkedBody) {
744 advance_str(data, hp->offset + 1);
746 if (HP_FL_TEST(hp, INTRAILER))
747 HP_FL_SET(hp, REQEOF);
752 if (hp->cs == http_parser_error)
753 parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
759 * Document-method: parse
761 * parser.add_parse(buffer) => env or nil
763 * adds the contents of +buffer+ to the internal buffer and attempts to
764 * continue parsing. Returns the +env+ Hash on success or nil if more
767 * Raises HttpParserError if there are parsing errors.
769 static VALUE HttpParser_add_parse(VALUE self, VALUE buffer)
771 struct http_parser *hp = data_get(self);
773 Check_Type(buffer, T_STRING);
774 rb_str_buf_append(hp->buf, buffer);
776 return HttpParser_parse(self);
780 * Document-method: trailers
782 * parser.trailers(req, data) => req or nil
784 * This is an alias for HttpParser#headers
788 * Document-method: headers
790 static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf)
792 struct http_parser *hp = data_get(self);
797 return HttpParser_parse(self);
800 static int chunked_eof(struct http_parser *hp)
802 return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER));
807 * parser.body_eof? => true or false
809 * Detects if we're done filtering the body or not. This can be used
810 * to detect when to stop calling HttpParser#filter_body.
812 static VALUE HttpParser_body_eof(VALUE self)
814 struct http_parser *hp = data_get(self);
816 if (HP_FL_TEST(hp, CHUNKED))
817 return chunked_eof(hp) ? Qtrue : Qfalse;
819 return hp->len.content == 0 ? Qtrue : Qfalse;
824 * parser.keepalive? => true or false
826 * This should be used to detect if a request can really handle
827 * keepalives and pipelining. Currently, the rules are:
829 * 1. MUST be a GET or HEAD request
830 * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive"
831 * 3. MUST NOT have "Connection: close" set
833 static VALUE HttpParser_keepalive(VALUE self)
835 struct http_parser *hp = data_get(self);
837 return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse;
842 * parser.next? => true or false
844 * Exactly like HttpParser#keepalive?, except it will reset the internal
845 * parser state on next parse if it returns true. It will also respect
846 * the maximum *keepalive_requests* value and return false if that is
849 static VALUE HttpParser_next(VALUE self)
851 struct http_parser *hp = data_get(self);
853 if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) {
854 HP_FL_SET(hp, TO_CLEAR);
862 * parser.headers? => true or false
864 * This should be used to detect if a request has headers (and if
865 * the response will have headers as well). HTTP/0.9 requests
866 * should return false, all subsequent HTTP versions will return true
868 static VALUE HttpParser_has_headers(VALUE self)
870 struct http_parser *hp = data_get(self);
872 return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse;
875 static VALUE HttpParser_buf(VALUE self)
877 return data_get(self)->buf;
880 static VALUE HttpParser_env(VALUE self)
882 return data_get(self)->env;
887 * parser.filter_body(dst, src) => nil/src
889 * Takes a String of +src+, will modify data if dechunking is done.
890 * Returns +nil+ if there is more data left to process. Returns
891 * +src+ if body processing is complete. When returning +src+,
892 * it may modify +src+ so the start of the string points to where
893 * the body ended so that trailer processing can begin.
895 * Raises HttpParserError if there are dechunking errors.
896 * Basically this is a glorified memcpy(3) that copies +src+
897 * into +buf+ while filtering it through the dechunker.
899 static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src)
901 struct http_parser *hp = data_get(self);
905 srcptr = RSTRING_PTR(src);
906 srclen = RSTRING_LEN(src);
910 if (HP_FL_TEST(hp, CHUNKED)) {
911 if (!chunked_eof(hp)) {
913 rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */
915 hp->s.dest_offset = 0;
918 http_parser_execute(hp, srcptr, srclen);
919 if (hp->cs == http_parser_error)
920 parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails.");
922 assert(hp->s.dest_offset <= hp->offset &&
923 "destination buffer overflow");
924 advance_str(src, hp->offset);
925 rb_str_set_len(dst, hp->s.dest_offset);
927 if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) {
928 assert(hp->len.chunk == 0 && "chunk at EOF but more to parse");
934 /* no need to enter the Ragel machine for unchunked transfers */
935 assert(hp->len.content >= 0 && "negative Content-Length");
936 if (hp->len.content > 0) {
937 long nr = MIN(srclen, hp->len.content);
940 rb_str_resize(dst, nr);
942 * using rb_str_replace() to avoid memcpy() doesn't help in
943 * most cases because a GC-aware programmer will pass an explicit
944 * buffer to env["rack.input"].read and reuse the buffer in a loop.
945 * This causes copy-on-write behavior to be triggered anyways
946 * when the +src+ buffer is modified (when reading off the socket).
949 memcpy(RSTRING_PTR(dst), srcptr, nr);
950 hp->len.content -= nr;
951 if (hp->len.content == 0) {
952 HP_FL_SET(hp, REQEOF);
953 hp->cs = http_parser_first_final;
955 advance_str(src, nr);
959 hp->offset = 0; /* for trailer parsing */
963 #define SET_GLOBAL(var,str) do { \
964 var = find_common_field(str, sizeof(str) - 1); \
965 assert(!NIL_P(var) && "missed global field"); \
968 void Init_unicorn_http(void)
970 VALUE mUnicorn, cHttpParser;
972 mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn"));
973 cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject);
975 rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError);
976 e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError",
978 e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError",
982 rb_define_alloc_func(cHttpParser, HttpParser_alloc);
983 rb_define_method(cHttpParser, "initialize", HttpParser_init, 0);
984 rb_define_method(cHttpParser, "clear", HttpParser_clear, 0);
985 rb_define_method(cHttpParser, "reset", HttpParser_reset, 0);
986 rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0);
987 rb_define_method(cHttpParser, "parse", HttpParser_parse, 0);
988 rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1);
989 rb_define_method(cHttpParser, "headers", HttpParser_headers, 2);
990 rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2);
991 rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2);
992 rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0);
993 rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0);
994 rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0);
995 rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0);
996 rb_define_method(cHttpParser, "next?", HttpParser_next, 0);
997 rb_define_method(cHttpParser, "buf", HttpParser_buf, 0);
998 rb_define_method(cHttpParser, "env", HttpParser_env, 0);
1001 * The maximum size a single chunk when using chunked transfer encoding.
1002 * This is only a theoretical maximum used to detect errors in clients,
1003 * it is highly unlikely to encounter clients that send more than
1004 * several kilobytes at once.
1006 rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX));
1009 * The maximum size of the body as specified by Content-Length.
1010 * This is only a theoretical maximum, the actual limit is subject
1011 * to the limits of the file system used for +Dir.tmpdir+.
1013 rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX));
1015 /* default value for keepalive_requests */
1016 rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT",
1017 ULONG2NUM(keepalive_requests));
1019 rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0);
1020 rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1);
1021 rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1);
1022 rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0);
1023 rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1);
1025 init_common_fields();
1026 SET_GLOBAL(g_http_host, "HOST");
1027 SET_GLOBAL(g_http_trailer, "TRAILER");
1028 SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING");
1029 SET_GLOBAL(g_content_length, "CONTENT_LENGTH");
1030 SET_GLOBAL(g_http_connection, "CONNECTION");
1031 id_clear = rb_intern("clear");
1032 id_set_backtrace = rb_intern("set_backtrace");
1033 init_unicorn_httpdate();