diff options
-rw-r--r-- | src/cowboy_dispatcher.erl | 64 | ||||
-rw-r--r-- | src/cowboy_http.erl | 17 | ||||
-rw-r--r-- | src/cowboy_protocol.erl | 79 | ||||
-rw-r--r-- | src/cowboy_req.erl | 132 | ||||
-rw-r--r-- | src/cowboy_rest.erl | 10 | ||||
-rw-r--r-- | test/http_SUITE.erl | 4 |
6 files changed, 176 insertions, 130 deletions
diff --git a/src/cowboy_dispatcher.erl b/src/cowboy_dispatcher.erl index f5dfcd9..cfb8fb6 100644 --- a/src/cowboy_dispatcher.erl +++ b/src/cowboy_dispatcher.erl @@ -17,7 +17,7 @@ -module(cowboy_dispatcher). %% API. --export([match/4]). +-export([match/3]). -type bindings() :: [{atom(), binary()}]. -type tokens() :: [binary()]. @@ -63,53 +63,51 @@ %% options found in the dispatch list, a key-value list of bindings and %% the tokens that were matched by the <em>'...'</em> atom for both the %% hostname and path. --spec match(dispatch_rules(), fun((binary()) -> binary()), - Host::binary() | tokens(), Path::binary()) +-spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary()) -> {ok, module(), any(), bindings(), HostInfo::undefined | tokens(), PathInfo::undefined | tokens()} | {error, notfound, host} | {error, notfound, path}. -match([], _, _, _) -> +match([], _, _) -> {error, notfound, host}; -match([{'_', PathMatchs}|_Tail], URLDecode, _, Path) -> - match_path(PathMatchs, URLDecode, undefined, Path, []); -match([{HostMatch, PathMatchs}|Tail], URLDecode, Tokens, Path) +match([{'_', PathMatchs}|_Tail], _, Path) -> + match_path(PathMatchs, undefined, Path, []); +match([{HostMatch, PathMatchs}|Tail], Tokens, Path) when is_list(Tokens) -> case list_match(Tokens, lists:reverse(HostMatch), []) of false -> - match(Tail, URLDecode, Tokens, Path); + match(Tail, Tokens, Path); {true, Bindings, undefined} -> - match_path(PathMatchs, URLDecode, undefined, Path, Bindings); + match_path(PathMatchs, undefined, Path, Bindings); {true, Bindings, HostInfo} -> - match_path(PathMatchs, URLDecode, lists:reverse(HostInfo), + match_path(PathMatchs, lists:reverse(HostInfo), Path, Bindings) end; -match(Dispatch, URLDecode, Host, Path) -> - match(Dispatch, URLDecode, split_host(Host), Path). +match(Dispatch, Host, Path) -> + match(Dispatch, split_host(Host), Path). --spec match_path(dispatch_path(), fun((binary()) -> binary()), +-spec match_path(dispatch_path(), HostInfo::undefined | tokens(), binary() | tokens(), bindings()) -> {ok, module(), any(), bindings(), HostInfo::undefined | tokens(), PathInfo::undefined | tokens()} | {error, notfound, path}. -match_path([], _, _, _, _) -> +match_path([], _, _, _) -> {error, notfound, path}; -match_path([{'_', Handler, Opts}|_Tail], _, HostInfo, _, Bindings) -> +match_path([{'_', Handler, Opts}|_Tail], HostInfo, _, Bindings) -> {ok, Handler, Opts, Bindings, HostInfo, undefined}; -match_path([{'*', Handler, Opts}|_Tail], _, HostInfo, '*', Bindings) -> +match_path([{'*', Handler, Opts}|_Tail], HostInfo, '*', Bindings) -> {ok, Handler, Opts, Bindings, HostInfo, undefined}; -match_path([{PathMatch, Handler, Opts}|Tail], URLDecode, HostInfo, Tokens, +match_path([{PathMatch, Handler, Opts}|Tail], HostInfo, Tokens, Bindings) when is_list(Tokens) -> case list_match(Tokens, PathMatch, []) of false -> - match_path(Tail, URLDecode, HostInfo, Tokens, Bindings); + match_path(Tail, HostInfo, Tokens, Bindings); {true, PathBinds, PathInfo} -> {ok, Handler, Opts, Bindings ++ PathBinds, HostInfo, PathInfo} end; -match_path(Dispatch, URLDecode, HostInfo, Path, Bindings) -> - match_path(Dispatch, URLDecode, HostInfo, - split_path(Path, URLDecode), Bindings). +match_path(Dispatch, HostInfo, Path, Bindings) -> + match_path(Dispatch, HostInfo, split_path(Path), Bindings). %% Internal. @@ -135,19 +133,19 @@ split_host(Host, Acc) -> %% Following RFC2396, this function may return path segments containing any %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped %% and part of a path segment. --spec split_path(binary(), fun((binary()) -> binary())) -> tokens(). -split_path(<< $/, Path/bits >>, URLDec) -> - split_path(Path, URLDec, []). +-spec split_path(binary()) -> tokens(). +split_path(<< $/, Path/bits >>) -> + split_path(Path, []). -split_path(Path, URLDec, Acc) -> +split_path(Path, Acc) -> case binary:match(Path, <<"/">>) of nomatch when Path =:= <<>> -> - lists:reverse([URLDec(S) || S <- Acc]); + lists:reverse([cowboy_http:urldecode(S) || S <- Acc]); nomatch -> - lists:reverse([URLDec(S) || S <- [Path|Acc]]); + lists:reverse([cowboy_http:urldecode(S) || S <- [Path|Acc]]); {Pos, _} -> << Segment:Pos/binary, _:8, Rest/bits >> = Path, - split_path(Rest, URLDec, [Segment|Acc]) + split_path(Rest, [Segment|Acc]) end. -spec list_match(tokens(), match_rule(), bindings()) @@ -201,9 +199,7 @@ split_path_test_() -> {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]}, {<<"/users/a+b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]} ], - URLDecode = fun(Bin) -> cowboy_http:urldecode(Bin, crash) end, - [{P, fun() -> R = split_path(P, URLDecode) end} - || {P, R} <- Tests]. + [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests]. match_test_() -> Dispatch = [ @@ -249,10 +245,9 @@ match_test_() -> {ok, match_duplicate_vars, [we, {expect, two}, var, here], [{var, <<"fr">>}, {var, <<"987">>}]}} ], - URLDecode = fun(Bin) -> cowboy_http:urldecode(Bin, crash) end, [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> {ok, Handler, Opts, Binds, undefined, undefined} - = match(Dispatch, URLDecode, H, P) + = match(Dispatch, H, P) end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests]. match_info_test_() -> @@ -278,9 +273,8 @@ match_info_test_() -> {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>, {ok, match_path, [], [], undefined, [<<"foo">>, <<"bar">>]}} ], - URLDecode = fun(Bin) -> cowboy_http:urldecode(Bin, crash) end, [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> - R = match(Dispatch, URLDecode, H, P) + R = match(Dispatch, H, P) end} || {H, P, R} <- Tests]. -endif. diff --git a/src/cowboy_http.erl b/src/cowboy_http.erl index 6ba4834..e0b1632 100644 --- a/src/cowboy_http.erl +++ b/src/cowboy_http.erl @@ -47,7 +47,7 @@ -export([urldecode/2]). -export([urlencode/1]). -export([urlencode/2]). --export([x_www_form_urlencoded/2]). +-export([x_www_form_urlencoded/1]). -type version() :: {Major::non_neg_integer(), Minor::non_neg_integer()}. -type headers() :: [{binary(), iodata()}]. @@ -861,15 +861,14 @@ tohexu(C) when C < 17 -> $A + C - 10. tohexl(C) when C < 10 -> $0 + C; tohexl(C) when C < 17 -> $a + C - 10. --spec x_www_form_urlencoded(binary(), fun((binary()) -> binary())) -> - list({binary(), binary() | true}). -x_www_form_urlencoded(<<>>, _URLDecode) -> +-spec x_www_form_urlencoded(binary()) -> list({binary(), binary() | true}). +x_www_form_urlencoded(<<>>) -> []; -x_www_form_urlencoded(Qs, URLDecode) -> +x_www_form_urlencoded(Qs) -> Tokens = binary:split(Qs, <<"&">>, [global, trim]), [case binary:split(Token, <<"=">>) of - [Token] -> {URLDecode(Token), true}; - [Name, Value] -> {URLDecode(Name), URLDecode(Value)} + [Token] -> {urldecode(Token), true}; + [Name, Value] -> {urldecode(Name), urldecode(Value)} end || Token <- Tokens]. %% Tests. @@ -1053,9 +1052,7 @@ x_www_form_urlencoded_test_() -> {<<"a=b=c=d=e&f=g">>, [{<<"a">>, <<"b=c=d=e">>}, {<<"f">>, <<"g">>}]}, {<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]} ], - URLDecode = fun urldecode/1, - [{Qs, fun() -> R = x_www_form_urlencoded( - Qs, URLDecode) end} || {Qs, R} <- Tests]. + [{Qs, fun() -> R = x_www_form_urlencoded(Qs) end} || {Qs, R} <- Tests]. urldecode_test_() -> U = fun urldecode/2, diff --git a/src/cowboy_protocol.erl b/src/cowboy_protocol.erl index b0b5aa6..bf81e52 100644 --- a/src/cowboy_protocol.erl +++ b/src/cowboy_protocol.erl @@ -20,11 +20,23 @@ %% <dt>dispatch</dt><dd>The dispatch list for this protocol.</dd> %% <dt>max_empty_lines</dt><dd>Max number of empty lines before a request. %% Defaults to 5.</dd> +%% <dt>max_header_name_length</dt><dd>Max length allowed for header names. +%% Defaults to 64.</dd> +%% <dt>max_header_value_length</dt><dd>Max length allowed for header values. +%% Defaults to 4096.</dd> +%% <dt>max_headers</dt><dd>Max number of headers allowed. +%% Defaults to 100.</dd> +%% <dt>max_keepalive</dt><dd>Max number of requests allowed in a single +%% keep-alive session. Defaults to infinity.</dd> +%% <dt>max_request_line_length</dt><dd>Max length allowed for the request +%% line. Defaults to 4096.</dd> +%% <dt>onrequest</dt><dd>Optional fun that allows Req interaction before +%% any dispatching is done. Host info, path info and bindings are thus +%% not available at this point.</dd> +%% <dt>onresponse</dt><dd>Optional fun that allows replacing a response +%% sent by the application based on its status code or headers.</dd> %% <dt>timeout</dt><dd>Time in milliseconds before an idle %% connection is closed. Defaults to 5000 milliseconds.</dd> -%% <dt>urldecode</dt><dd>Function and options argument to use when decoding -%% URL encoded strings. Defaults to `{fun cowboy_http:urldecode/2, crash}'. -%% </dd> %% </dl> %% %% Note that there is no need to monitor these processes when using Cowboy as @@ -56,13 +68,13 @@ dispatch :: cowboy_dispatcher:dispatch_rules(), onrequest :: undefined | onrequest_fun(), onresponse = undefined :: undefined | onresponse_fun(), - urldecode :: {fun((binary(), T) -> binary()), T}, - max_empty_lines :: integer(), - req_keepalive = 1 :: integer(), - max_keepalive :: integer(), - max_request_line_length :: integer(), - max_header_name_length :: integer(), - max_header_value_length :: integer(), + max_empty_lines :: non_neg_integer(), + req_keepalive = 1 :: non_neg_integer(), + max_keepalive :: non_neg_integer(), + max_request_line_length :: non_neg_integer(), + max_header_name_length :: non_neg_integer(), + max_header_value_length :: non_neg_integer(), + max_headers :: non_neg_integer(), timeout :: timeout(), hibernate = false :: boolean(), loop_timeout = infinity :: timeout(), @@ -92,24 +104,22 @@ get_value(Key, Opts, Default) -> init(ListenerPid, Socket, Transport, Opts) -> Dispatch = get_value(dispatch, Opts, []), MaxEmptyLines = get_value(max_empty_lines, Opts, 5), - MaxKeepalive = get_value(max_keepalive, Opts, infinity), - MaxRequestLineLength = get_value(max_request_line_length, Opts, 4096), MaxHeaderNameLength = get_value(max_header_name_length, Opts, 64), MaxHeaderValueLength = get_value(max_header_value_length, Opts, 4096), + MaxHeaders = get_value(max_headers, Opts, 100), + MaxKeepalive = get_value(max_keepalive, Opts, infinity), + MaxRequestLineLength = get_value(max_request_line_length, Opts, 4096), OnRequest = get_value(onrequest, Opts, undefined), OnResponse = get_value(onresponse, Opts, undefined), Timeout = get_value(timeout, Opts, 5000), - URLDecDefault = {fun cowboy_http:urldecode/2, crash}, - URLDec = get_value(urldecode, Opts, URLDecDefault), ok = ranch:accept_ack(ListenerPid), wait_request(<<>>, #state{listener=ListenerPid, socket=Socket, transport=Transport, dispatch=Dispatch, max_empty_lines=MaxEmptyLines, max_keepalive=MaxKeepalive, max_request_line_length=MaxRequestLineLength, max_header_name_length=MaxHeaderNameLength, - max_header_value_length=MaxHeaderValueLength, - timeout=Timeout, onrequest=OnRequest, onresponse=OnResponse, - urldecode=URLDec}, 0). + max_header_value_length=MaxHeaderValueLength, max_headers=MaxHeaders, + timeout=Timeout, onrequest=OnRequest, onresponse=OnResponse}, 0). %% Request parsing. %% @@ -139,7 +149,7 @@ parse_request(Buffer, State=#state{max_request_line_length=MaxLength, max_empty_lines=MaxEmpty}, ReqEmpty) -> case binary:match(Buffer, <<"\n">>) of nomatch when byte_size(Buffer) > MaxLength -> - error_terminate(413, State); + error_terminate(414, State); nomatch -> wait_request(Buffer, State, ReqEmpty); {1, _} when ReqEmpty =:= MaxEmpty -> @@ -207,6 +217,10 @@ parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, S, M, P, Q, F) -> parse_version(_, State, _, _, _, _) -> error_terminate(505, State). +%% Stop receiving data if we have more than allowed number of headers. +wait_header(_, State=#state{max_headers=MaxHeaders}, _, _, _, _, _, Headers) + when length(Headers) >= MaxHeaders -> + error_terminate(400, State); wait_header(Buffer, State=#state{socket=Socket, transport=Transport, timeout=Timeout}, M, P, Q, F, V, H) -> case Transport:recv(Socket, 0, Timeout) of @@ -225,7 +239,7 @@ parse_header(Buffer, State=#state{max_header_name_length=MaxLength}, M, P, Q, F, V, H) -> case binary:match(Buffer, <<":">>) of nomatch when byte_size(Buffer) > MaxLength -> - error_terminate(413, State); + error_terminate(400, State); nomatch -> wait_header(Buffer, State, M, P, Q, F, V, H); {_, _} -> @@ -300,7 +314,7 @@ parse_hd_before_value(Buffer, State=#state{ max_header_value_length=MaxLength}, M, P, Q, F, V, H, N) -> case binary:match(Buffer, <<"\n">>) of nomatch when byte_size(Buffer) > MaxLength -> - error_terminate(413, State); + error_terminate(400, State); nomatch -> wait_hd_before_value(Buffer, State, M, P, Q, F, V, H, N); {_, _} -> @@ -353,7 +367,7 @@ parse_hd_value(<< C, Rest/bits >>, S, M, P, Q, F, V, H, N, SoFar) -> parse_hd_value(Rest, S, M, P, Q, F, V, H, N, << SoFar/binary, C >>); parse_hd_value(<<>>, State=#state{max_header_value_length=MaxLength}, _, _, _, _, _, _, _, SoFar) when byte_size(SoFar) > MaxLength -> - error_terminate(413, State); + error_terminate(400, State); parse_hd_value(<<>>, S, M, P, Q, F, V, H, N, SoFar) -> wait_hd_value(<<>>, S, M, P, Q, F, V, H, N, SoFar). @@ -421,11 +435,11 @@ parse_host(<< C, Rest/bits >>, Acc) -> request(Buffer, State=#state{socket=Socket, transport=Transport, req_keepalive=ReqKeepalive, max_keepalive=MaxKeepalive, - onresponse=OnResponse, urldecode=URLDecode}, + onresponse=OnResponse}, Method, Path, Query, Fragment, Version, Headers, Host, Port) -> Req = cowboy_req:new(Socket, Transport, Method, Path, Query, Fragment, Version, Headers, Host, Port, Buffer, ReqKeepalive < MaxKeepalive, - OnResponse, URLDecode), + OnResponse), onrequest(Req, State, Host, Path). %% Call the global onrequest callback. The callback can send a reply, @@ -437,16 +451,14 @@ onrequest(Req, State=#state{onrequest=undefined}, Host, Path) -> dispatch(Req, State, Host, Path); onrequest(Req, State=#state{onrequest=OnRequest}, Host, Path) -> Req2 = OnRequest(Req), - case cowboy_req:get_resp_state(Req2) of + case cowboy_req:get(resp_state, Req2) of waiting -> dispatch(Req2, State, Host, Path); _ -> next_request(Req2, State, ok) end. -spec dispatch(cowboy_req:req(), #state{}, binary(), binary()) -> ok. -dispatch(Req, State=#state{dispatch=Dispatch, urldecode={URLDecFun, URLDecArg}}, - Host, Path) -> - case cowboy_dispatcher:match(Dispatch, - fun(Bin) -> URLDecFun(Bin, URLDecArg) end, Host, Path) of +dispatch(Req, State=#state{dispatch=Dispatch}, Host, Path) -> + case cowboy_dispatcher:match(Dispatch, Host, Path) of {ok, Handler, Opts, Bindings, HostInfo, PathInfo} -> Req2 = cowboy_req:set_bindings(HostInfo, PathInfo, Bindings, Req), handler_init(Req2, State, Handler, Opts); @@ -540,6 +552,7 @@ handler_loop_timeout(State=#state{loop_timeout=Timeout, TRef = erlang:start_timer(Timeout, self(), ?MODULE), State#state{loop_timeout_ref=TRef}. +%% @private -spec handler_loop(cowboy_req:req(), #state{}, module(), any()) -> ok. handler_loop(Req, State=#state{loop_timeout_ref=TRef}, Handler, HandlerState) -> receive @@ -597,13 +610,13 @@ terminate_request(Req, State, Handler, HandlerState) -> -spec next_request(cowboy_req:req(), #state{}, any()) -> ok. next_request(Req, State=#state{req_keepalive=Keepalive}, HandlerRes) -> cowboy_req:ensure_response(Req, 204), - {BodyRes, Buffer} = case cowboy_req:skip_body(Req) of - {ok, Req2} -> {ok, cowboy_req:get_buffer(Req2)}; - {error, _} -> {close, <<>>} + {BodyRes, [Buffer, Connection]} = case cowboy_req:skip_body(Req) of + {ok, Req2} -> {ok, cowboy_req:get([buffer, connection], Req2)}; + {error, _} -> {close, [<<>>, close]} end, %% Flush the resp_sent message before moving on. receive {cowboy_req, resp_sent} -> ok after 0 -> ok end, - case {HandlerRes, BodyRes, cowboy_req:get_connection(Req)} of + case {HandlerRes, BodyRes, Connection} of {ok, ok, keepalive} -> ?MODULE:parse_request(Buffer, State#state{ req_keepalive=Keepalive + 1}, 0); @@ -620,7 +633,7 @@ error_terminate(Code, State=#state{socket=Socket, transport=Transport, after 0 -> _ = cowboy_req:reply(Code, cowboy_req:new(Socket, Transport, <<"GET">>, <<>>, <<>>, <<>>, {1, 1}, [], <<>>, undefined, - <<>>, false, OnResponse, undefined)), + <<>>, false, OnResponse)), ok end, terminate(State). diff --git a/src/cowboy_req.erl b/src/cowboy_req.erl index 17ae0de..dddf92e 100644 --- a/src/cowboy_req.erl +++ b/src/cowboy_req.erl @@ -42,7 +42,7 @@ -module(cowboy_req). %% Request API. --export([new/14]). +-export([new/13]). -export([method/1]). -export([version/1]). -export([peer/1]). @@ -104,10 +104,9 @@ -export([ensure_response/2]). %% Private setter/getter API. +-export([get/2]). +-export([set/2]). -export([set_bindings/4]). --export([get_resp_state/1]). --export([get_buffer/1]). --export([get_connection/1]). %% Misc API. -export([compact/1]). @@ -157,8 +156,7 @@ resp_body = <<>> :: iodata() | {non_neg_integer(), resp_body_fun()}, %% Functions. - onresponse = undefined :: undefined | cowboy_protocol:onresponse_fun(), - urldecode :: {fun((binary(), T) -> binary()), T} + onresponse = undefined :: undefined | cowboy_protocol:onresponse_fun() }). -opaque req() :: #http_req{}. @@ -176,16 +174,15 @@ -spec new(inet:socket(), module(), binary(), binary(), binary(), binary(), cowboy_http:version(), cowboy_http:headers(), binary(), inet:port_number() | undefined, binary(), boolean(), - undefined | cowboy_protocol:onresponse_fun(), - undefined | {fun(), atom()}) + undefined | cowboy_protocol:onresponse_fun()) -> req(). new(Socket, Transport, Method, Path, Query, Fragment, Version, Headers, Host, Port, Buffer, CanKeepalive, - OnResponse, URLDecode) -> + OnResponse) -> Req = #http_req{socket=Socket, transport=Transport, pid=self(), method=Method, path=Path, qs=Query, fragment=Fragment, version=Version, headers=Headers, host=Host, port=Port, buffer=Buffer, - onresponse=OnResponse, urldecode=URLDecode}, + onresponse=OnResponse}, case CanKeepalive of false -> Req#http_req{connection=close}; @@ -289,10 +286,9 @@ qs_val(Name, Req) when is_binary(Name) -> %% missing. -spec qs_val(binary(), Req, Default) -> {binary() | true | Default, Req} when Req::req(), Default::any(). -qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined, - urldecode={URLDecFun, URLDecArg}}, Default) when is_binary(Name) -> - QsVals = cowboy_http:x_www_form_urlencoded( - RawQs, fun(Bin) -> URLDecFun(Bin, URLDecArg) end), +qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default) + when is_binary(Name) -> + QsVals = cowboy_http:x_www_form_urlencoded(RawQs), qs_val(Name, Req#http_req{qs_vals=QsVals}, Default); qs_val(Name, Req, Default) -> case lists:keyfind(Name, 1, Req#http_req.qs_vals) of @@ -302,10 +298,8 @@ qs_val(Name, Req, Default) -> %% @doc Return the full list of query string values. -spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req(). -qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined, - urldecode={URLDecFun, URLDecArg}}) -> - QsVals = cowboy_http:x_www_form_urlencoded( - RawQs, fun(Bin) -> URLDecFun(Bin, URLDecArg) end), +qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) -> + QsVals = cowboy_http:x_www_form_urlencoded(RawQs), qs_vals(Req#http_req{qs_vals=QsVals}); qs_vals(Req=#http_req{qs_vals=QsVals}) -> {QsVals, Req}. @@ -739,17 +733,16 @@ skip_body(Req) -> {error, Reason} -> {error, Reason} end. -%% @doc Return the full body sent with the reqest, parsed as an +%% @doc Return the full body sent with the request, parsed as an %% application/x-www-form-urlencoded string. Essentially a POST query string. %% @todo We need an option to limit the size of the body for QS too. -spec body_qs(Req) -> {ok, [{binary(), binary() | true}], Req} | {error, atom()} when Req::req(). -body_qs(Req=#http_req{urldecode={URLDecFun, URLDecArg}}) -> +body_qs(Req) -> case body(Req) of {ok, Body, Req2} -> - {ok, cowboy_http:x_www_form_urlencoded( - Body, fun(Bin) -> URLDecFun(Bin, URLDecArg) end), Req2}; + {ok, cowboy_http:x_www_form_urlencoded(Body), Req2}; {error, Reason} -> {error, Reason} end. @@ -993,27 +986,78 @@ ensure_response(#http_req{socket=Socket, transport=Transport, %% Private setter/getter API. %% @private +-spec get(atom(), req()) -> any(); ([atom()], req()) -> any(). +get(List, Req) when is_list(List) -> + [g(Atom, Req) || Atom <- List]; +get(Atom, Req) when is_atom(Atom) -> + g(Atom, Req). + +g(bindings, #http_req{bindings=Ret}) -> Ret; +g(body_state, #http_req{body_state=Ret}) -> Ret; +g(buffer, #http_req{buffer=Ret}) -> Ret; +g(connection, #http_req{connection=Ret}) -> Ret; +g(cookies, #http_req{cookies=Ret}) -> Ret; +g(fragment, #http_req{fragment=Ret}) -> Ret; +g(headers, #http_req{headers=Ret}) -> Ret; +g(host, #http_req{host=Ret}) -> Ret; +g(host_info, #http_req{host_info=Ret}) -> Ret; +g(meta, #http_req{meta=Ret}) -> Ret; +g(method, #http_req{method=Ret}) -> Ret; +g(multipart, #http_req{multipart=Ret}) -> Ret; +g(onresponse, #http_req{onresponse=Ret}) -> Ret; +g(p_headers, #http_req{p_headers=Ret}) -> Ret; +g(path, #http_req{path=Ret}) -> Ret; +g(path_info, #http_req{path_info=Ret}) -> Ret; +g(peer, #http_req{peer=Ret}) -> Ret; +g(pid, #http_req{pid=Ret}) -> Ret; +g(port, #http_req{port=Ret}) -> Ret; +g(qs, #http_req{qs=Ret}) -> Ret; +g(qs_vals, #http_req{qs_vals=Ret}) -> Ret; +g(resp_body, #http_req{resp_body=Ret}) -> Ret; +g(resp_headers, #http_req{resp_headers=Ret}) -> Ret; +g(resp_state, #http_req{resp_state=Ret}) -> Ret; +g(socket, #http_req{socket=Ret}) -> Ret; +g(transport, #http_req{transport=Ret}) -> Ret; +g(version, #http_req{version=Ret}) -> Ret. + +%% @private +-spec set([{atom(), any()}], Req) -> Req when Req::req(). +set([], Req) -> Req; +set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val}); +set([{body_state, Val}|Tail], Req) -> set(Tail, Req#http_req{body_state=Val}); +set([{buffer, Val}|Tail], Req) -> set(Tail, Req#http_req{buffer=Val}); +set([{connection, Val}|Tail], Req) -> set(Tail, Req#http_req{connection=Val}); +set([{cookies, Val}|Tail], Req) -> set(Tail, Req#http_req{cookies=Val}); +set([{fragment, Val}|Tail], Req) -> set(Tail, Req#http_req{fragment=Val}); +set([{headers, Val}|Tail], Req) -> set(Tail, Req#http_req{headers=Val}); +set([{host, Val}|Tail], Req) -> set(Tail, Req#http_req{host=Val}); +set([{host_info, Val}|Tail], Req) -> set(Tail, Req#http_req{host_info=Val}); +set([{meta, Val}|Tail], Req) -> set(Tail, Req#http_req{meta=Val}); +set([{method, Val}|Tail], Req) -> set(Tail, Req#http_req{method=Val}); +set([{multipart, Val}|Tail], Req) -> set(Tail, Req#http_req{multipart=Val}); +set([{onresponse, Val}|Tail], Req) -> set(Tail, Req#http_req{onresponse=Val}); +set([{p_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{p_headers=Val}); +set([{path, Val}|Tail], Req) -> set(Tail, Req#http_req{path=Val}); +set([{path_info, Val}|Tail], Req) -> set(Tail, Req#http_req{path_info=Val}); +set([{peer, Val}|Tail], Req) -> set(Tail, Req#http_req{peer=Val}); +set([{pid, Val}|Tail], Req) -> set(Tail, Req#http_req{pid=Val}); +set([{port, Val}|Tail], Req) -> set(Tail, Req#http_req{port=Val}); +set([{qs, Val}|Tail], Req) -> set(Tail, Req#http_req{qs=Val}); +set([{qs_vals, Val}|Tail], Req) -> set(Tail, Req#http_req{qs_vals=Val}); +set([{resp_body, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_body=Val}); +set([{resp_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_headers=Val}); +set([{resp_state, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_state=Val}); +set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val}); +set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val}); +set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}). + +%% @private -spec set_bindings(cowboy_dispatcher:tokens(), cowboy_dispatcher:tokens(), cowboy_dispatcher:bindings(), Req) -> Req when Req::req(). set_bindings(HostInfo, PathInfo, Bindings, Req) -> Req#http_req{host_info=HostInfo, path_info=PathInfo, bindings=Bindings}. -%% @private --spec get_resp_state(req()) -> locked | waiting | chunks | done. -get_resp_state(#http_req{resp_state=RespState}) -> - RespState. - -%% @private --spec get_buffer(req()) -> binary(). -get_buffer(#http_req{buffer=Buffer}) -> - Buffer. - -%% @private --spec get_connection(req()) -> keepalive | close. -get_connection(#http_req{connection=Connection}) -> - Connection. - %% Misc API. %% @doc Compact the request data by removing all non-system information. @@ -1090,15 +1134,13 @@ response_connection([], Connection) -> Connection; response_connection([{Name, Value}|Tail], Connection) -> case Name of - <<"connection">> -> response_connection_parse(Value); - _ -> response_connection(Tail, Connection) + <<"connection">> -> + Tokens = parse_connection_before(Value, []), + connection_to_atom(Tokens); + _ -> + response_connection(Tail, Connection) end. --spec response_connection_parse(binary()) -> keepalive | close. -response_connection_parse(ReplyConn) -> - Tokens = cowboy_http:nonempty_list(ReplyConn, fun cowboy_http:token/2), - connection_to_atom(Tokens). - -spec response_merge_headers(cowboy_http:headers(), cowboy_http:headers(), cowboy_http:headers()) -> cowboy_http:headers(). response_merge_headers(Headers, RespHeaders, DefaultHeaders) -> @@ -1184,7 +1226,7 @@ parse_connection_after(<< C, Rest/bits >>, Acc) %% @doc Walk through a tokens list and return whether %% the connection is keepalive or closed. %% -%% We don't match on <<"keep-alive">> since it is the default value. +%% We don't match on "keep-alive" since it is the default value. -spec connection_to_atom([binary()]) -> keepalive | close. connection_to_atom([]) -> keepalive; diff --git a/src/cowboy_rest.erl b/src/cowboy_rest.erl index ad8d62f..2f9faa8 100644 --- a/src/cowboy_rest.erl +++ b/src/cowboy_rest.erl @@ -58,16 +58,16 @@ -> {ok, Req} | close when Req::cowboy_req:req(). upgrade(_ListenerPid, Handler, Opts, Req) -> try - {Method, Req1} = cowboy_req:method(Req), + Method = cowboy_req:get(method, Req), case erlang:function_exported(Handler, rest_init, 2) of true -> - case Handler:rest_init(Req1, Opts) of + case Handler:rest_init(Req, Opts) of {ok, Req2, HandlerState} -> service_available(Req2, #state{method=Method, handler=Handler, handler_state=HandlerState}) end; false -> - service_available(Req1, #state{method=Method, + service_available(Req, #state{method=Method, handler=Handler}) end catch Class:Reason -> @@ -693,8 +693,8 @@ is_conflict(Req, State) -> expect(Req, State, is_conflict, false, fun put_resource/2, 409). put_resource(Req, State) -> - {Path, Req2} = cowboy_req:path(Req), - put_resource(cowboy_req:set_meta(put_path, Path, Req2), + Path = cowboy_req:get(path, Req), + put_resource(cowboy_req:set_meta(put_path, Path, Req), State, fun is_new_resource/2). %% content_types_accepted should return a list of media types and their diff --git a/test/http_SUITE.erl b/test/http_SUITE.erl index bb0e345..cb59c07 100644 --- a/test/http_SUITE.erl +++ b/test/http_SUITE.erl @@ -359,8 +359,8 @@ The document has moved {408, "GET / HTTP/1.1\r\nHost: localhost"}, {408, "GET / HTTP/1.1\r\nHost: localhost\r\n"}, {408, "GET / HTTP/1.1\r\nHost: localhost\r\n\r"}, - {413, Huge}, - {413, "GET / HTTP/1.1\r\n" ++ Huge}, + {414, Huge}, + {400, "GET / HTTP/1.1\r\n" ++ Huge}, {505, "GET / HTTP/1.2\r\nHost: localhost\r\n\r\n"}, {closed, ""}, {closed, "\r\n"}, |