1%% Copyright (c) 2011-2014, Loïc Hoguin <essen@ninenines.eu> 2%% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu> 3%% 4%% Permission to use, copy, modify, and/or distribute this software for any 5%% purpose with or without fee is hereby granted, provided that the above 6%% copyright notice and this permission notice appear in all copies. 7%% 8%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 16-module(cowboy_req). 17 18%% Request API. 19-export([new/14]). 20-export([method/1]). 21-export([version/1]). 22-export([peer/1]). 23-export([host/1]). 24-export([host_info/1]). 25-export([port/1]). 26-export([path/1]). 27-export([path_info/1]). 28-export([qs/1]). 29-export([qs_val/2]). 30-export([qs_val/3]). 31-export([qs_vals/1]). 32-export([host_url/1]). 33-export([url/1]). 34-export([binding/2]). 35-export([binding/3]). 36-export([bindings/1]). 37-export([header/2]). 38-export([header/3]). 39-export([headers/1]). 40-export([parse_header/2]). 41-export([parse_header/3]). 42-export([cookie/2]). 43-export([cookie/3]). 44-export([cookies/1]). 45-export([meta/2]). 46-export([meta/3]). 47-export([set_meta/3]). 48 49%% Request body API. 50-export([has_body/1]). 51-export([body_length/1]). 52-export([body/1]). 53-export([body/2]). 54-export([body_qs/1]). 55-export([body_qs/2]). 56 57%% Multipart API. 58-export([part/1]). 59-export([part/2]). 60-export([part_body/1]). 61-export([part_body/2]). 62 63%% Response API. 64-export([set_resp_cookie/4]). 65-export([set_resp_header/3]). 66-export([set_resp_body/2]). 67-export([set_resp_body_fun/2]). 68-export([set_resp_body_fun/3]). 69-export([has_resp_header/2]). 70-export([has_resp_body/1]). 71-export([delete_resp_header/2]). 72-export([reply/2]). 73-export([reply/3]). 74-export([reply/4]). 75-export([chunked_reply/2]). 76-export([chunked_reply/3]). 77-export([chunk/2]). 78-export([upgrade_reply/3]). 79-export([continue/1]). 80-export([maybe_reply/2]). 81-export([ensure_response/2]). 82 83%% Private setter/getter API. 84-export([append_buffer/2]). 85-export([get/2]). 86-export([set/2]). 87-export([set_bindings/4]). 88 89%% Misc API. 90-export([compact/1]). 91-export([lock/1]). 92-export([to_list/1]). 93 94-type cookie_opts() :: cow_cookie:cookie_opts(). 95-export_type([cookie_opts/0]). 96 97-type content_decode_fun() :: fun((binary()) 98 -> {ok, binary()} 99 | {error, atom()}). 100-type transfer_decode_fun() :: fun((binary(), any()) 101 -> cow_http_te:decode_ret()). 102 103-type body_opts() :: [{continue, boolean()} 104 | {length, non_neg_integer()} 105 | {read_length, non_neg_integer()} 106 | {read_timeout, timeout()} 107 | {transfer_decode, transfer_decode_fun(), any()} 108 | {content_decode, content_decode_fun()}]. 109-export_type([body_opts/0]). 110 111-type resp_body_fun() :: fun((any(), module()) -> ok). 112-type send_chunk_fun() :: fun((iodata()) -> ok | {error, atom()}). 113-type resp_chunked_fun() :: fun((send_chunk_fun()) -> ok). 114 115-record(http_req, { 116 %% Transport. 117 socket = undefined :: any(), 118 transport = undefined :: undefined | module(), 119 connection = keepalive :: keepalive | close, 120 121 %% Request. 122 pid = undefined :: pid(), 123 method = <<"GET">> :: binary(), 124 version = 'HTTP/1.1' :: cowboy:http_version(), 125 peer = undefined :: undefined | {inet:ip_address(), inet:port_number()}, 126 host = undefined :: undefined | binary(), 127 host_info = undefined :: undefined | cowboy_router:tokens(), 128 port = undefined :: undefined | inet:port_number(), 129 path = undefined :: binary(), 130 path_info = undefined :: undefined | cowboy_router:tokens(), 131 qs = undefined :: binary(), 132 qs_vals = undefined :: undefined | list({binary(), binary() | true}), 133 bindings = undefined :: undefined | cowboy_router:bindings(), 134 headers = [] :: cowboy:http_headers(), 135 p_headers = [] :: [any()], 136 cookies = undefined :: undefined | [{binary(), binary()}], 137 meta = [] :: [{atom(), any()}], 138 139 %% Request body. 140 body_state = waiting :: waiting | done | {stream, non_neg_integer(), 141 transfer_decode_fun(), any(), content_decode_fun()}, 142 buffer = <<>> :: binary(), 143 multipart = undefined :: undefined | {binary(), binary()}, 144 145 %% Response. 146 resp_compress = false :: boolean(), 147 resp_state = waiting :: locked | waiting | waiting_stream 148 | chunks | stream | done, 149 resp_headers = [] :: cowboy:http_headers(), 150 resp_body = <<>> :: iodata() | resp_body_fun() 151 | {non_neg_integer(), resp_body_fun()} 152 | {chunked, resp_chunked_fun()}, 153 154 %% Functions. 155 onresponse = undefined :: undefined | already_called 156 | cowboy:onresponse_fun() 157}). 158 159-opaque req() :: #http_req{}. 160-export_type([req/0]). 161 162%% Request API. 163 164-spec new(any(), module(), 165 undefined | {inet:ip_address(), inet:port_number()}, 166 binary(), binary(), binary(), 167 cowboy:http_version(), cowboy:http_headers(), binary(), 168 inet:port_number() | undefined, binary(), boolean(), boolean(), 169 undefined | cowboy:onresponse_fun()) 170 -> req(). 171new(Socket, Transport, Peer, Method, Path, Query, 172 Version, Headers, Host, Port, Buffer, CanKeepalive, 173 Compress, OnResponse) -> 174 Req = #http_req{socket=Socket, transport=Transport, pid=self(), peer=Peer, 175 method=Method, path=Path, qs=Query, version=Version, 176 headers=Headers, host=Host, port=Port, buffer=Buffer, 177 resp_compress=Compress, onresponse=OnResponse}, 178 case CanKeepalive of 179 false -> 180 Req#http_req{connection=close}; 181 true -> 182 case lists:keyfind(<<"connection">>, 1, Headers) of 183 false -> 184 case Version of 185 'HTTP/1.1' -> Req; %% keepalive 186 'HTTP/1.0' -> Req#http_req{connection=close} 187 end; 188 {_, ConnectionHeader} -> 189 Tokens = cow_http_hd:parse_connection(ConnectionHeader), 190 Connection = connection_to_atom(Tokens), 191 Req#http_req{connection=Connection, 192 p_headers=[{<<"connection">>, Tokens}]} 193 end 194 end. 195 196-spec method(Req) -> {binary(), Req} when Req::req(). 197method(Req) -> 198 {Req#http_req.method, Req}. 199 200-spec version(Req) -> {cowboy:http_version(), Req} when Req::req(). 201version(Req) -> 202 {Req#http_req.version, Req}. 203 204-spec peer(Req) 205 -> {{inet:ip_address(), inet:port_number()}, Req} 206 when Req::req(). 207peer(Req) -> 208 {Req#http_req.peer, Req}. 209 210-spec host(Req) -> {binary(), Req} when Req::req(). 211host(Req) -> 212 {Req#http_req.host, Req}. 213 214-spec host_info(Req) 215 -> {cowboy_router:tokens() | undefined, Req} when Req::req(). 216host_info(Req) -> 217 {Req#http_req.host_info, Req}. 218 219-spec port(Req) -> {inet:port_number(), Req} when Req::req(). 220port(Req) -> 221 {Req#http_req.port, Req}. 222 223-spec path(Req) -> {binary(), Req} when Req::req(). 224path(Req) -> 225 {Req#http_req.path, Req}. 226 227-spec path_info(Req) 228 -> {cowboy_router:tokens() | undefined, Req} when Req::req(). 229path_info(Req) -> 230 {Req#http_req.path_info, Req}. 231 232-spec qs(Req) -> {binary(), Req} when Req::req(). 233qs(Req) -> 234 {Req#http_req.qs, Req}. 235 236-spec qs_val(binary(), Req) 237 -> {binary() | true | undefined, Req} when Req::req(). 238qs_val(Name, Req) when is_binary(Name) -> 239 qs_val(Name, Req, undefined). 240 241-spec qs_val(binary(), Req, Default) 242 -> {binary() | true | Default, Req} when Req::req(), Default::any(). 243qs_val(Name, Req=#http_req{qs=RawQs, qs_vals=undefined}, Default) 244 when is_binary(Name) -> 245 QsVals = cow_qs:parse_qs(RawQs), 246 qs_val(Name, Req#http_req{qs_vals=QsVals}, Default); 247qs_val(Name, Req, Default) -> 248 case lists:keyfind(Name, 1, Req#http_req.qs_vals) of 249 {Name, Value} -> {Value, Req}; 250 false -> {Default, Req} 251 end. 252 253-spec qs_vals(Req) -> {list({binary(), binary() | true}), Req} when Req::req(). 254qs_vals(Req=#http_req{qs=RawQs, qs_vals=undefined}) -> 255 QsVals = cow_qs:parse_qs(RawQs), 256 qs_vals(Req#http_req{qs_vals=QsVals}); 257qs_vals(Req=#http_req{qs_vals=QsVals}) -> 258 {QsVals, Req}. 259 260%% The URL includes the scheme, host and port only. 261-spec host_url(Req) -> {undefined | binary(), Req} when Req::req(). 262host_url(Req=#http_req{port=undefined}) -> 263 {undefined, Req}; 264host_url(Req=#http_req{transport=Transport, host=Host, port=Port}) -> 265 TransportName = Transport:name(), 266 Secure = case TransportName of 267 ssl -> <<"s">>; 268 _ -> <<>> 269 end, 270 PortBin = case {TransportName, Port} of 271 {ssl, 443} -> <<>>; 272 {tcp, 80} -> <<>>; 273 _ -> << ":", (integer_to_binary(Port))/binary >> 274 end, 275 {<< "http", Secure/binary, "://", Host/binary, PortBin/binary >>, Req}. 276 277%% The URL includes the scheme, host, port, path and query string. 278-spec url(Req) -> {undefined | binary(), Req} when Req::req(). 279url(Req=#http_req{}) -> 280 {HostURL, Req2} = host_url(Req), 281 url(HostURL, Req2). 282 283url(undefined, Req=#http_req{}) -> 284 {undefined, Req}; 285url(HostURL, Req=#http_req{path=Path, qs=QS}) -> 286 QS2 = case QS of 287 <<>> -> <<>>; 288 _ -> << "?", QS/binary >> 289 end, 290 {<< HostURL/binary, Path/binary, QS2/binary >>, Req}. 291 292-spec binding(atom(), Req) -> {any() | undefined, Req} when Req::req(). 293binding(Name, Req) when is_atom(Name) -> 294 binding(Name, Req, undefined). 295 296-spec binding(atom(), Req, Default) 297 -> {any() | Default, Req} when Req::req(), Default::any(). 298binding(Name, Req, Default) when is_atom(Name) -> 299 case lists:keyfind(Name, 1, Req#http_req.bindings) of 300 {Name, Value} -> {Value, Req}; 301 false -> {Default, Req} 302 end. 303 304-spec bindings(Req) -> {[{atom(), any()}], Req} when Req::req(). 305bindings(Req) -> 306 {Req#http_req.bindings, Req}. 307 308-spec header(binary(), Req) 309 -> {binary() | undefined, Req} when Req::req(). 310header(Name, Req) -> 311 header(Name, Req, undefined). 312 313-spec header(binary(), Req, Default) 314 -> {binary() | Default, Req} when Req::req(), Default::any(). 315header(Name, Req, Default) -> 316 case lists:keyfind(Name, 1, Req#http_req.headers) of 317 {Name, Value} -> {Value, Req}; 318 false -> {Default, Req} 319 end. 320 321-spec headers(Req) -> {cowboy:http_headers(), Req} when Req::req(). 322headers(Req) -> 323 {Req#http_req.headers, Req}. 324 325-spec parse_header(binary(), Req) 326 -> {ok, any(), Req} | {undefined, binary(), Req} 327 | {error, badarg} when Req::req(). 328parse_header(Name, Req=#http_req{p_headers=PHeaders}) -> 329 case lists:keyfind(Name, 1, PHeaders) of 330 false -> parse_header(Name, Req, parse_header_default(Name)); 331 {Name, Value} -> {ok, Value, Req} 332 end. 333 334-spec parse_header_default(binary()) -> any(). 335parse_header_default(<<"transfer-encoding">>) -> [<<"identity">>]; 336parse_header_default(_Name) -> undefined. 337 338-spec parse_header(binary(), Req, any()) 339 -> {ok, any(), Req} | {undefined, binary(), Req} 340 | {error, badarg} when Req::req(). 341parse_header(Name = <<"accept">>, Req, Default) -> 342 parse_header(Name, Req, Default, 343 fun (Value) -> 344 cowboy_http:list(Value, fun cowboy_http:media_range/2) 345 end); 346parse_header(Name = <<"accept-charset">>, Req, Default) -> 347 parse_header(Name, Req, Default, 348 fun (Value) -> 349 cowboy_http:nonempty_list(Value, fun cowboy_http:conneg/2) 350 end); 351parse_header(Name = <<"accept-encoding">>, Req, Default) -> 352 parse_header(Name, Req, Default, 353 fun (Value) -> 354 cowboy_http:list(Value, fun cowboy_http:conneg/2) 355 end); 356parse_header(Name = <<"accept-language">>, Req, Default) -> 357 parse_header(Name, Req, Default, 358 fun (Value) -> 359 cowboy_http:nonempty_list(Value, fun cowboy_http:language_range/2) 360 end); 361parse_header(Name = <<"authorization">>, Req, Default) -> 362 parse_header(Name, Req, Default, 363 fun (Value) -> 364 cowboy_http:token_ci(Value, fun cowboy_http:authorization/2) 365 end); 366parse_header(Name = <<"content-length">>, Req, Default) -> 367 parse_header(Name, Req, Default, fun cow_http_hd:parse_content_length/1); 368parse_header(Name = <<"content-type">>, Req, Default) -> 369 parse_header(Name, Req, Default, fun cowboy_http:content_type/1); 370parse_header(Name = <<"cookie">>, Req, Default) -> 371 parse_header(Name, Req, Default, fun cow_cookie:parse_cookie/1); 372parse_header(Name = <<"expect">>, Req, Default) -> 373 parse_header(Name, Req, Default, 374 fun (Value) -> 375 cowboy_http:nonempty_list(Value, fun cowboy_http:expectation/2) 376 end); 377parse_header(Name, Req, Default) 378 when Name =:= <<"if-match">>; 379 Name =:= <<"if-none-match">> -> 380 parse_header(Name, Req, Default, fun cowboy_http:entity_tag_match/1); 381parse_header(Name, Req, Default) 382 when Name =:= <<"if-modified-since">>; 383 Name =:= <<"if-unmodified-since">> -> 384 parse_header(Name, Req, Default, fun cowboy_http:http_date/1); 385parse_header(Name = <<"range">>, Req, Default) -> 386 parse_header(Name, Req, Default, fun cowboy_http:range/1); 387parse_header(Name, Req, Default) 388 when Name =:= <<"sec-websocket-protocol">>; 389 Name =:= <<"x-forwarded-for">> -> 390 parse_header(Name, Req, Default, 391 fun (Value) -> 392 cowboy_http:nonempty_list(Value, fun cowboy_http:token/2) 393 end); 394parse_header(Name = <<"transfer-encoding">>, Req, Default) -> 395 parse_header(Name, Req, Default, fun cow_http_hd:parse_transfer_encoding/1); 396%% @todo Product version. 397parse_header(Name = <<"upgrade">>, Req, Default) -> 398 parse_header(Name, Req, Default, 399 fun (Value) -> 400 cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2) 401 end); 402parse_header(Name = <<"sec-websocket-extensions">>, Req, Default) -> 403 parse_header(Name, Req, Default, fun cowboy_http:parameterized_tokens/1); 404parse_header(Name, Req, Default) -> 405 {Value, Req2} = header(Name, Req, Default), 406 {undefined, Value, Req2}. 407 408parse_header(Name, Req=#http_req{p_headers=PHeaders}, Default, Fun) -> 409 case header(Name, Req) of 410 {undefined, Req2} -> 411 {ok, Default, Req2#http_req{p_headers=[{Name, Default}|PHeaders]}}; 412 {Value, Req2} -> 413 case Fun(Value) of 414 {error, badarg} -> 415 {error, badarg}; 416 P -> 417 {ok, P, Req2#http_req{p_headers=[{Name, P}|PHeaders]}} 418 end 419 end. 420 421-spec cookie(binary(), Req) 422 -> {binary() | undefined, Req} when Req::req(). 423cookie(Name, Req) when is_binary(Name) -> 424 cookie(Name, Req, undefined). 425 426-spec cookie(binary(), Req, Default) 427 -> {binary() | Default, Req} when Req::req(), Default::any(). 428cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) -> 429 case parse_header(<<"cookie">>, Req) of 430 {ok, undefined, Req2} -> 431 {Default, Req2#http_req{cookies=[]}}; 432 {ok, Cookies, Req2} -> 433 cookie(Name, Req2#http_req{cookies=Cookies}, Default) 434 end; 435cookie(Name, Req, Default) -> 436 case lists:keyfind(Name, 1, Req#http_req.cookies) of 437 {Name, Value} -> {Value, Req}; 438 false -> {Default, Req} 439 end. 440 441-spec cookies(Req) -> {list({binary(), binary()}), Req} when Req::req(). 442cookies(Req=#http_req{cookies=undefined}) -> 443 case parse_header(<<"cookie">>, Req) of 444 {ok, undefined, Req2} -> 445 {[], Req2#http_req{cookies=[]}}; 446 {ok, Cookies, Req2} -> 447 cookies(Req2#http_req{cookies=Cookies}); 448 %% Flash player incorrectly sends an empty Cookie header. 449 {error, badarg} -> 450 {[], Req#http_req{cookies=[]}} 451 end; 452cookies(Req=#http_req{cookies=Cookies}) -> 453 {Cookies, Req}. 454 455-spec meta(atom(), Req) -> {any() | undefined, Req} when Req::req(). 456meta(Name, Req) -> 457 meta(Name, Req, undefined). 458 459-spec meta(atom(), Req, any()) -> {any(), Req} when Req::req(). 460meta(Name, Req, Default) -> 461 case lists:keyfind(Name, 1, Req#http_req.meta) of 462 {Name, Value} -> {Value, Req}; 463 false -> {Default, Req} 464 end. 465 466-spec set_meta(atom(), any(), Req) -> Req when Req::req(). 467set_meta(Name, Value, Req=#http_req{meta=Meta}) -> 468 Req#http_req{meta=lists:keystore(Name, 1, Meta, {Name, Value})}. 469 470%% Request Body API. 471 472-spec has_body(req()) -> boolean(). 473has_body(Req) -> 474 case lists:keyfind(<<"content-length">>, 1, Req#http_req.headers) of 475 {_, <<"0">>} -> 476 false; 477 {_, _} -> 478 true; 479 _ -> 480 lists:keymember(<<"transfer-encoding">>, 1, Req#http_req.headers) 481 end. 482 483%% The length may not be known if Transfer-Encoding is not identity, 484%% and the body hasn't been read at the time of the call. 485-spec body_length(Req) -> {undefined | non_neg_integer(), Req} when Req::req(). 486body_length(Req) -> 487 case parse_header(<<"transfer-encoding">>, Req) of 488 {ok, [<<"identity">>], Req2} -> 489 {ok, Length, Req3} = parse_header(<<"content-length">>, Req2, 0), 490 {Length, Req3}; 491 {ok, _, Req2} -> 492 {undefined, Req2} 493 end. 494 495-spec body(Req) 496 -> {ok, binary(), Req} | {more, binary(), Req} 497 | {error, atom()} when Req::req(). 498body(Req) -> 499 body(Req, []). 500 501-spec body(Req, body_opts()) 502 -> {ok, binary(), Req} | {more, binary(), Req} 503 | {error, atom()} when Req::req(). 504body(Req=#http_req{body_state=waiting}, Opts) -> 505 %% Send a 100 continue if needed (enabled by default). 506 Req1 = case lists:keyfind(continue, 1, Opts) of 507 {_, false} -> 508 Req; 509 _ -> 510 {ok, ExpectHeader, Req0} = parse_header(<<"expect">>, Req), 511 ok = case ExpectHeader of 512 [<<"100-continue">>] -> continue(Req0); 513 _ -> ok 514 end, 515 Req0 516 end, 517 %% Initialize body streaming state. 518 CFun = case lists:keyfind(content_decode, 1, Opts) of 519 false -> 520 fun cowboy_http:ce_identity/1; 521 {_, CFun0} -> 522 CFun0 523 end, 524 case lists:keyfind(transfer_decode, 1, Opts) of 525 false -> 526 case parse_header(<<"transfer-encoding">>, Req1) of 527 {ok, [<<"chunked">>], Req2} -> 528 body(Req2#http_req{body_state={stream, 0, 529 fun cow_http_te:stream_chunked/2, {0, 0}, CFun}}, Opts); 530 {ok, [<<"identity">>], Req2} -> 531 {Len, Req3} = body_length(Req2), 532 case Len of 533 0 -> 534 {ok, <<>>, Req3#http_req{body_state=done}}; 535 _ -> 536 body(Req3#http_req{body_state={stream, Len, 537 fun cow_http_te:stream_identity/2, {0, Len}, 538 CFun}}, Opts) 539 end 540 end; 541 {_, TFun, TState} -> 542 body(Req1#http_req{body_state={stream, 0, 543 TFun, TState, CFun}}, Opts) 544 end; 545body(Req=#http_req{body_state=done}, _) -> 546 {ok, <<>>, Req}; 547body(Req, Opts) -> 548 ChunkLen = case lists:keyfind(length, 1, Opts) of 549 false -> 8000000; 550 {_, ChunkLen0} -> ChunkLen0 551 end, 552 ReadLen = case lists:keyfind(read_length, 1, Opts) of 553 false -> 1000000; 554 {_, ReadLen0} -> ReadLen0 555 end, 556 ReadTimeout = case lists:keyfind(read_timeout, 1, Opts) of 557 false -> 15000; 558 {_, ReadTimeout0} -> ReadTimeout0 559 end, 560 body_loop(Req, ReadTimeout, ReadLen, ChunkLen, <<>>). 561 562body_loop(Req=#http_req{buffer=Buffer, body_state={stream, Length, _, _, _}}, 563 ReadTimeout, ReadLength, ChunkLength, Acc) -> 564 {Tag, Res, Req2} = case Buffer of 565 <<>> -> 566 body_recv(Req, ReadTimeout, min(Length, ReadLength)); 567 _ -> 568 body_decode(Req, ReadTimeout) 569 end, 570 case {Tag, Res} of 571 {ok, {ok, Data}} -> 572 {ok, << Acc/binary, Data/binary >>, Req2}; 573 {more, {ok, Data}} -> 574 Acc2 = << Acc/binary, Data/binary >>, 575 case byte_size(Acc2) >= ChunkLength of 576 true -> {more, Acc2, Req2}; 577 false -> body_loop(Req2, ReadTimeout, ReadLength, ChunkLength, Acc2) 578 end; 579 _ -> %% Error. 580 Res 581 end. 582 583body_recv(Req=#http_req{transport=Transport, socket=Socket, buffer=Buffer}, 584 ReadTimeout, ReadLength) -> 585 case Transport:recv(Socket, ReadLength, ReadTimeout) of 586 {ok, Data} -> 587 body_decode(Req#http_req{buffer= << Buffer/binary, Data/binary >>}, 588 ReadTimeout); 589 Error = {error, _} -> 590 {error, Error, Req} 591 end. 592 593%% Two decodings happen. First a decoding function is applied to the 594%% transferred data, and then another is applied to the actual content. 595%% 596%% Transfer encoding is generally used for chunked bodies. The decoding 597%% function uses a state to keep track of how much it has read, which is 598%% also initialized through this function. 599%% 600%% Content encoding is generally used for compression. 601%% 602%% @todo Handle chunked after-the-facts headers. 603%% @todo Depending on the length returned we might want to 0 or +5 it. 604body_decode(Req=#http_req{buffer=Data, body_state={stream, _, 605 TDecode, TState, CDecode}}, ReadTimeout) -> 606 case TDecode(Data, TState) of 607 more -> 608 body_recv(Req#http_req{body_state={stream, 0, 609 TDecode, TState, CDecode}}, ReadTimeout, 0); 610 {more, Data2, TState2} -> 611 {more, CDecode(Data2), Req#http_req{body_state={stream, 0, 612 TDecode, TState2, CDecode}, buffer= <<>>}}; 613 {more, Data2, Length, TState2} when is_integer(Length) -> 614 {more, CDecode(Data2), Req#http_req{body_state={stream, Length, 615 TDecode, TState2, CDecode}, buffer= <<>>}}; 616 {more, Data2, Rest, TState2} -> 617 {more, CDecode(Data2), Req#http_req{body_state={stream, 0, 618 TDecode, TState2, CDecode}, buffer=Rest}}; 619 {done, TotalLength, Rest} -> 620 {ok, {ok, <<>>}, body_decode_end(Req, TotalLength, Rest)}; 621 {done, Data2, TotalLength, Rest} -> 622 {ok, CDecode(Data2), body_decode_end(Req, TotalLength, Rest)} 623 end. 624 625body_decode_end(Req=#http_req{headers=Headers, p_headers=PHeaders}, 626 TotalLength, Rest) -> 627 Headers2 = lists:keystore(<<"content-length">>, 1, Headers, 628 {<<"content-length">>, integer_to_binary(TotalLength)}), 629 %% At this point we just assume TEs were all decoded. 630 Headers3 = lists:keydelete(<<"transfer-encoding">>, 1, Headers2), 631 PHeaders2 = lists:keystore(<<"content-length">>, 1, PHeaders, 632 {<<"content-length">>, TotalLength}), 633 PHeaders3 = lists:keydelete(<<"transfer-encoding">>, 1, PHeaders2), 634 Req#http_req{buffer=Rest, body_state=done, 635 headers=Headers3, p_headers=PHeaders3}. 636 637-spec body_qs(Req) 638 -> {ok, [{binary(), binary() | true}], Req} | {error, atom()} 639 when Req::req(). 640body_qs(Req) -> 641 body_qs(Req, [ 642 {length, 64000}, 643 {read_length, 64000}, 644 {read_timeout, 5000}]). 645 646-spec body_qs(Req, body_opts()) -> {ok, [{binary(), binary() | true}], Req} 647 | {badlength, Req} | {error, atom()} when Req::req(). 648body_qs(Req, Opts) -> 649 case body(Req, Opts) of 650 {ok, Body, Req2} -> 651 {ok, cow_qs:parse_qs(Body), Req2}; 652 {more, _, Req2} -> 653 {badlength, Req2}; 654 {error, Reason} -> 655 {error, Reason} 656 end. 657 658%% Multipart API. 659 660-spec part(Req) 661 -> {ok, cow_multipart:headers(), Req} | {done, Req} 662 when Req::req(). 663part(Req) -> 664 part(Req, [ 665 {length, 64000}, 666 {read_length, 64000}, 667 {read_timeout, 5000}]). 668 669-spec part(Req, body_opts()) 670 -> {ok, cow_multipart:headers(), Req} | {done, Req} 671 when Req::req(). 672part(Req=#http_req{multipart=undefined}, Opts) -> 673 part(init_multipart(Req), Opts); 674part(Req, Opts) -> 675 {Data, Req2} = stream_multipart(Req, Opts), 676 part(Data, Opts, Req2). 677 678part(Buffer, Opts, Req=#http_req{multipart={Boundary, _}}) -> 679 case cow_multipart:parse_headers(Buffer, Boundary) of 680 more -> 681 {Data, Req2} = stream_multipart(Req, Opts), 682 part(<< Buffer/binary, Data/binary >>, Opts, Req2); 683 {more, Buffer2} -> 684 {Data, Req2} = stream_multipart(Req, Opts), 685 part(<< Buffer2/binary, Data/binary >>, Opts, Req2); 686 {ok, Headers, Rest} -> 687 {ok, Headers, Req#http_req{multipart={Boundary, Rest}}}; 688 %% Ignore epilogue. 689 {done, _} -> 690 {done, Req#http_req{multipart=undefined}} 691 end. 692 693-spec part_body(Req) 694 -> {ok, binary(), Req} | {more, binary(), Req} 695 when Req::req(). 696part_body(Req) -> 697 part_body(Req, []). 698 699-spec part_body(Req, body_opts()) 700 -> {ok, binary(), Req} | {more, binary(), Req} 701 when Req::req(). 702part_body(Req=#http_req{multipart=undefined}, Opts) -> 703 part_body(init_multipart(Req), Opts); 704part_body(Req, Opts) -> 705 part_body(<<>>, Opts, Req, <<>>). 706 707part_body(Buffer, Opts, Req=#http_req{multipart={Boundary, _}}, Acc) -> 708 ChunkLen = case lists:keyfind(length, 1, Opts) of 709 false -> 8000000; 710 {_, ChunkLen0} -> ChunkLen0 711 end, 712 case byte_size(Acc) > ChunkLen of 713 true -> 714 {more, Acc, Req#http_req{multipart={Boundary, Buffer}}}; 715 false -> 716 {Data, Req2} = stream_multipart(Req, Opts), 717 case cow_multipart:parse_body(<< Buffer/binary, Data/binary >>, Boundary) of 718 {ok, Body} -> 719 part_body(<<>>, Opts, Req2, << Acc/binary, Body/binary >>); 720 {ok, Body, Rest} -> 721 part_body(Rest, Opts, Req2, << Acc/binary, Body/binary >>); 722 done -> 723 {ok, Acc, Req2}; 724 {done, Body} -> 725 {ok, << Acc/binary, Body/binary >>, Req2}; 726 {done, Body, Rest} -> 727 {ok, << Acc/binary, Body/binary >>, 728 Req2#http_req{multipart={Boundary, Rest}}} 729 end 730 end. 731 732init_multipart(Req) -> 733 {ok, {<<"multipart">>, _, Params}, Req2} 734 = parse_header(<<"content-type">>, Req), 735 {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params), 736 Req2#http_req{multipart={Boundary, <<>>}}. 737 738stream_multipart(Req=#http_req{body_state=BodyState, multipart={_, <<>>}}, Opts) -> 739 true = BodyState =/= done, 740 {_, Data, Req2} = body(Req, Opts), 741 {Data, Req2}; 742stream_multipart(Req=#http_req{multipart={Boundary, Buffer}}, _) -> 743 {Buffer, Req#http_req{multipart={Boundary, <<>>}}}. 744 745%% Response API. 746 747%% The cookie name cannot contain any of the following characters: 748%% =,;\s\t\r\n\013\014 749%% 750%% The cookie value cannot contain any of the following characters: 751%% ,; \t\r\n\013\014 752-spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req) 753 -> Req when Req::req(). 754set_resp_cookie(Name, Value, Opts, Req) -> 755 Cookie = cow_cookie:setcookie(Name, Value, Opts), 756 set_resp_header(<<"set-cookie">>, Cookie, Req). 757 758-spec set_resp_header(binary(), iodata(), Req) 759 -> Req when Req::req(). 760set_resp_header(Name, Value, Req=#http_req{resp_headers=RespHeaders}) -> 761 Req#http_req{resp_headers=[{Name, Value}|RespHeaders]}. 762 763-spec set_resp_body(iodata(), Req) -> Req when Req::req(). 764set_resp_body(Body, Req) -> 765 Req#http_req{resp_body=Body}. 766 767-spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req(). 768set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) -> 769 Req#http_req{resp_body=StreamFun}. 770 771%% If the body function crashes while writing the response body or writes 772%% fewer bytes than declared the behaviour is undefined. 773-spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req) 774 -> Req when Req::req(); 775 (chunked, resp_chunked_fun(), Req) 776 -> Req when Req::req(). 777set_resp_body_fun(StreamLen, StreamFun, Req) 778 when is_integer(StreamLen), is_function(StreamFun) -> 779 Req#http_req{resp_body={StreamLen, StreamFun}}; 780set_resp_body_fun(chunked, StreamFun, Req) 781 when is_function(StreamFun) -> 782 Req#http_req{resp_body={chunked, StreamFun}}. 783 784-spec has_resp_header(binary(), req()) -> boolean(). 785has_resp_header(Name, #http_req{resp_headers=RespHeaders}) -> 786 lists:keymember(Name, 1, RespHeaders). 787 788-spec has_resp_body(req()) -> boolean(). 789has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) -> 790 true; 791has_resp_body(#http_req{resp_body={chunked, _}}) -> 792 true; 793has_resp_body(#http_req{resp_body={Length, _}}) -> 794 Length > 0; 795has_resp_body(#http_req{resp_body=RespBody}) -> 796 iolist_size(RespBody) > 0. 797 798-spec delete_resp_header(binary(), Req) 799 -> Req when Req::req(). 800delete_resp_header(Name, Req=#http_req{resp_headers=RespHeaders}) -> 801 RespHeaders2 = lists:keydelete(Name, 1, RespHeaders), 802 Req#http_req{resp_headers=RespHeaders2}. 803 804-spec reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req(). 805reply(Status, Req=#http_req{resp_body=Body}) -> 806 reply(Status, [], Body, Req). 807 808-spec reply(cowboy:http_status(), cowboy:http_headers(), Req) 809 -> {ok, Req} when Req::req(). 810reply(Status, Headers, Req=#http_req{resp_body=Body}) -> 811 reply(Status, Headers, Body, Req). 812 813-spec reply(cowboy:http_status(), cowboy:http_headers(), 814 iodata() | {non_neg_integer() | resp_body_fun()}, Req) 815 -> {ok, Req} when Req::req(). 816reply(Status, Headers, Body, Req=#http_req{ 817 socket=Socket, transport=Transport, 818 version=Version, connection=Connection, 819 method=Method, resp_compress=Compress, 820 resp_state=RespState, resp_headers=RespHeaders}) 821 when RespState =:= waiting; RespState =:= waiting_stream -> 822 HTTP11Headers = if 823 Transport =/= cowboy_spdy, Version =:= 'HTTP/1.0', Connection =:= keepalive -> 824 [{<<"connection">>, atom_to_connection(Connection)}]; 825 Transport =/= cowboy_spdy, Version =:= 'HTTP/1.1', Connection =:= close -> 826 [{<<"connection">>, atom_to_connection(Connection)}]; 827 true -> 828 [] 829 end, 830 Req3 = case Body of 831 BodyFun when is_function(BodyFun) -> 832 %% We stream the response body until we close the connection. 833 RespConn = close, 834 {RespType, Req2} = if 835 Transport =:= cowboy_spdy -> 836 response(Status, Headers, RespHeaders, [ 837 {<<"date">>, cowboy_clock:rfc1123()}, 838 {<<"server">>, <<"Cowboy">>} 839 ], stream, Req); 840 true -> 841 response(Status, Headers, RespHeaders, [ 842 {<<"connection">>, <<"close">>}, 843 {<<"date">>, cowboy_clock:rfc1123()}, 844 {<<"server">>, <<"Cowboy">>}, 845 {<<"transfer-encoding">>, <<"identity">>} 846 ], <<>>, Req) 847 end, 848 if RespType =/= hook, Method =/= <<"HEAD">> -> 849 BodyFun(Socket, Transport); 850 true -> ok 851 end, 852 Req2#http_req{connection=RespConn}; 853 {chunked, BodyFun} -> 854 %% We stream the response body in chunks. 855 {RespType, Req2} = chunked_response(Status, Headers, Req), 856 if RespType =/= hook, Method =/= <<"HEAD">> -> 857 ChunkFun = fun(IoData) -> chunk(IoData, Req2) end, 858 BodyFun(ChunkFun), 859 %% Send the last chunk if chunked encoding was used. 860 if 861 Version =:= 'HTTP/1.0'; RespState =:= waiting_stream -> 862 Req2; 863 true -> 864 last_chunk(Req2) 865 end; 866 true -> Req2 867 end; 868 {ContentLength, BodyFun} -> 869 %% We stream the response body for ContentLength bytes. 870 RespConn = response_connection(Headers, Connection), 871 {RespType, Req2} = response(Status, Headers, RespHeaders, [ 872 {<<"content-length">>, integer_to_list(ContentLength)}, 873 {<<"date">>, cowboy_clock:rfc1123()}, 874 {<<"server">>, <<"Cowboy">>} 875 |HTTP11Headers], stream, Req), 876 if RespType =/= hook, Method =/= <<"HEAD">> -> 877 BodyFun(Socket, Transport); 878 true -> ok 879 end, 880 Req2#http_req{connection=RespConn}; 881 _ when Compress -> 882 RespConn = response_connection(Headers, Connection), 883 Req2 = reply_may_compress(Status, Headers, Body, Req, 884 RespHeaders, HTTP11Headers, Method), 885 Req2#http_req{connection=RespConn}; 886 _ -> 887 RespConn = response_connection(Headers, Connection), 888 Req2 = reply_no_compress(Status, Headers, Body, Req, 889 RespHeaders, HTTP11Headers, Method, iolist_size(Body)), 890 Req2#http_req{connection=RespConn} 891 end, 892 {ok, Req3#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}. 893 894reply_may_compress(Status, Headers, Body, Req, 895 RespHeaders, HTTP11Headers, Method) -> 896 BodySize = iolist_size(Body), 897 case parse_header(<<"accept-encoding">>, Req) of 898 {ok, Encodings, Req2} -> 899 CanGzip = (BodySize > 300) 900 andalso (false =:= lists:keyfind(<<"content-encoding">>, 901 1, Headers)) 902 andalso (false =:= lists:keyfind(<<"content-encoding">>, 903 1, RespHeaders)) 904 andalso (false =:= lists:keyfind(<<"transfer-encoding">>, 905 1, Headers)) 906 andalso (false =:= lists:keyfind(<<"transfer-encoding">>, 907 1, RespHeaders)) 908 andalso (Encodings =/= undefined) 909 andalso (false =/= lists:keyfind(<<"gzip">>, 1, Encodings)), 910 case CanGzip of 911 true -> 912 GzBody = zlib:gzip(Body), 913 {_, Req3} = response(Status, Headers, RespHeaders, [ 914 {<<"content-length">>, integer_to_list(byte_size(GzBody))}, 915 {<<"content-encoding">>, <<"gzip">>}, 916 {<<"date">>, cowboy_clock:rfc1123()}, 917 {<<"server">>, <<"Cowboy">>} 918 |HTTP11Headers], 919 case Method of <<"HEAD">> -> <<>>; _ -> GzBody end, 920 Req2), 921 Req3; 922 false -> 923 reply_no_compress(Status, Headers, Body, Req, 924 RespHeaders, HTTP11Headers, Method, BodySize) 925 end; 926 {error, badarg} -> 927 reply_no_compress(Status, Headers, Body, Req, 928 RespHeaders, HTTP11Headers, Method, BodySize) 929 end. 930 931reply_no_compress(Status, Headers, Body, Req, 932 RespHeaders, HTTP11Headers, Method, BodySize) -> 933 {_, Req2} = response(Status, Headers, RespHeaders, [ 934 {<<"content-length">>, integer_to_list(BodySize)}, 935 {<<"date">>, cowboy_clock:rfc1123()}, 936 {<<"server">>, <<"Cowboy">>} 937 |HTTP11Headers], 938 case Method of <<"HEAD">> -> <<>>; _ -> Body end, 939 Req), 940 Req2. 941 942-spec chunked_reply(cowboy:http_status(), Req) -> {ok, Req} when Req::req(). 943chunked_reply(Status, Req) -> 944 chunked_reply(Status, [], Req). 945 946-spec chunked_reply(cowboy:http_status(), cowboy:http_headers(), Req) 947 -> {ok, Req} when Req::req(). 948chunked_reply(Status, Headers, Req) -> 949 {_, Req2} = chunked_response(Status, Headers, Req), 950 {ok, Req2}. 951 952-spec chunk(iodata(), req()) -> ok | {error, atom()}. 953chunk(_Data, #http_req{method= <<"HEAD">>}) -> 954 ok; 955chunk(Data, #http_req{socket=Socket, transport=cowboy_spdy, 956 resp_state=chunks}) -> 957 cowboy_spdy:stream_data(Socket, Data); 958chunk(Data, #http_req{socket=Socket, transport=Transport, 959 resp_state=stream}) -> 960 Transport:send(Socket, Data); 961chunk(Data, #http_req{socket=Socket, transport=Transport, 962 resp_state=chunks}) -> 963 Transport:send(Socket, [integer_to_list(iolist_size(Data), 16), 964 <<"\r\n">>, Data, <<"\r\n">>]). 965 966%% If ever made public, need to send nothing if HEAD. 967-spec last_chunk(Req) -> Req when Req::req(). 968last_chunk(Req=#http_req{socket=Socket, transport=cowboy_spdy}) -> 969 _ = cowboy_spdy:stream_close(Socket), 970 Req#http_req{resp_state=done}; 971last_chunk(Req=#http_req{socket=Socket, transport=Transport}) -> 972 _ = Transport:send(Socket, <<"0\r\n\r\n">>), 973 Req#http_req{resp_state=done}. 974 975-spec upgrade_reply(cowboy:http_status(), cowboy:http_headers(), Req) 976 -> {ok, Req} when Req::req(). 977upgrade_reply(Status, Headers, Req=#http_req{transport=Transport, 978 resp_state=waiting, resp_headers=RespHeaders}) 979 when Transport =/= cowboy_spdy -> 980 {_, Req2} = response(Status, Headers, RespHeaders, [ 981 {<<"connection">>, <<"Upgrade">>} 982 ], <<>>, Req), 983 {ok, Req2#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}}. 984 985-spec continue(req()) -> ok | {error, atom()}. 986continue(#http_req{socket=Socket, transport=Transport, 987 version=Version}) -> 988 HTTPVer = atom_to_binary(Version, latin1), 989 Transport:send(Socket, 990 << HTTPVer/binary, " ", (status(100))/binary, "\r\n\r\n" >>). 991 992%% Meant to be used internally for sending errors after crashes. 993-spec maybe_reply([{module(), atom(), arity() | [term()], _}], req()) -> ok. 994maybe_reply(Stacktrace, Req) -> 995 receive 996 {cowboy_req, resp_sent} -> ok 997 after 0 -> 998 _ = do_maybe_reply(Stacktrace, Req), 999 ok 1000 end. 1001 1002do_maybe_reply([ 1003 {cow_http_hd, _, _, _}, 1004 {cowboy_req, parse_header, _, _}|_], Req) -> 1005 cowboy_req:reply(400, Req); 1006do_maybe_reply(_, Req) -> 1007 cowboy_req:reply(500, Req). 1008 1009-spec ensure_response(req(), cowboy:http_status()) -> ok. 1010%% The response has already been fully sent to the client. 1011ensure_response(#http_req{resp_state=done}, _) -> 1012 ok; 1013%% No response has been sent but everything apparently went fine. 1014%% Reply with the status code found in the second argument. 1015ensure_response(Req=#http_req{resp_state=RespState}, Status) 1016 when RespState =:= waiting; RespState =:= waiting_stream -> 1017 _ = reply(Status, [], [], Req), 1018 ok; 1019%% Terminate the chunked body for HTTP/1.1 only. 1020ensure_response(#http_req{method= <<"HEAD">>}, _) -> 1021 ok; 1022ensure_response(Req=#http_req{resp_state=chunks}, _) -> 1023 _ = last_chunk(Req), 1024 ok; 1025ensure_response(#http_req{}, _) -> 1026 ok. 1027 1028%% Private setter/getter API. 1029 1030-spec append_buffer(binary(), Req) -> Req when Req::req(). 1031append_buffer(Suffix, Req=#http_req{buffer=Buffer}) -> 1032 Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}. 1033 1034-spec get(atom(), req()) -> any(); ([atom()], req()) -> any(). 1035get(List, Req) when is_list(List) -> 1036 [g(Atom, Req) || Atom <- List]; 1037get(Atom, Req) when is_atom(Atom) -> 1038 g(Atom, Req). 1039 1040g(bindings, #http_req{bindings=Ret}) -> Ret; 1041g(body_state, #http_req{body_state=Ret}) -> Ret; 1042g(buffer, #http_req{buffer=Ret}) -> Ret; 1043g(connection, #http_req{connection=Ret}) -> Ret; 1044g(cookies, #http_req{cookies=Ret}) -> Ret; 1045g(headers, #http_req{headers=Ret}) -> Ret; 1046g(host, #http_req{host=Ret}) -> Ret; 1047g(host_info, #http_req{host_info=Ret}) -> Ret; 1048g(meta, #http_req{meta=Ret}) -> Ret; 1049g(method, #http_req{method=Ret}) -> Ret; 1050g(multipart, #http_req{multipart=Ret}) -> Ret; 1051g(onresponse, #http_req{onresponse=Ret}) -> Ret; 1052g(p_headers, #http_req{p_headers=Ret}) -> Ret; 1053g(path, #http_req{path=Ret}) -> Ret; 1054g(path_info, #http_req{path_info=Ret}) -> Ret; 1055g(peer, #http_req{peer=Ret}) -> Ret; 1056g(pid, #http_req{pid=Ret}) -> Ret; 1057g(port, #http_req{port=Ret}) -> Ret; 1058g(qs, #http_req{qs=Ret}) -> Ret; 1059g(qs_vals, #http_req{qs_vals=Ret}) -> Ret; 1060g(resp_body, #http_req{resp_body=Ret}) -> Ret; 1061g(resp_compress, #http_req{resp_compress=Ret}) -> Ret; 1062g(resp_headers, #http_req{resp_headers=Ret}) -> Ret; 1063g(resp_state, #http_req{resp_state=Ret}) -> Ret; 1064g(socket, #http_req{socket=Ret}) -> Ret; 1065g(transport, #http_req{transport=Ret}) -> Ret; 1066g(version, #http_req{version=Ret}) -> Ret. 1067 1068-spec set([{atom(), any()}], Req) -> Req when Req::req(). 1069set([], Req) -> Req; 1070set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val}); 1071set([{body_state, Val}|Tail], Req) -> set(Tail, Req#http_req{body_state=Val}); 1072set([{buffer, Val}|Tail], Req) -> set(Tail, Req#http_req{buffer=Val}); 1073set([{connection, Val}|Tail], Req) -> set(Tail, Req#http_req{connection=Val}); 1074set([{cookies, Val}|Tail], Req) -> set(Tail, Req#http_req{cookies=Val}); 1075set([{headers, Val}|Tail], Req) -> set(Tail, Req#http_req{headers=Val}); 1076set([{host, Val}|Tail], Req) -> set(Tail, Req#http_req{host=Val}); 1077set([{host_info, Val}|Tail], Req) -> set(Tail, Req#http_req{host_info=Val}); 1078set([{meta, Val}|Tail], Req) -> set(Tail, Req#http_req{meta=Val}); 1079set([{method, Val}|Tail], Req) -> set(Tail, Req#http_req{method=Val}); 1080set([{multipart, Val}|Tail], Req) -> set(Tail, Req#http_req{multipart=Val}); 1081set([{onresponse, Val}|Tail], Req) -> set(Tail, Req#http_req{onresponse=Val}); 1082set([{p_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{p_headers=Val}); 1083set([{path, Val}|Tail], Req) -> set(Tail, Req#http_req{path=Val}); 1084set([{path_info, Val}|Tail], Req) -> set(Tail, Req#http_req{path_info=Val}); 1085set([{peer, Val}|Tail], Req) -> set(Tail, Req#http_req{peer=Val}); 1086set([{pid, Val}|Tail], Req) -> set(Tail, Req#http_req{pid=Val}); 1087set([{port, Val}|Tail], Req) -> set(Tail, Req#http_req{port=Val}); 1088set([{qs, Val}|Tail], Req) -> set(Tail, Req#http_req{qs=Val}); 1089set([{qs_vals, Val}|Tail], Req) -> set(Tail, Req#http_req{qs_vals=Val}); 1090set([{resp_body, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_body=Val}); 1091set([{resp_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_headers=Val}); 1092set([{resp_state, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_state=Val}); 1093set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val}); 1094set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val}); 1095set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}). 1096 1097-spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(), 1098 cowboy_router:bindings(), Req) -> Req when Req::req(). 1099set_bindings(HostInfo, PathInfo, Bindings, Req) -> 1100 Req#http_req{host_info=HostInfo, path_info=PathInfo, 1101 bindings=Bindings}. 1102 1103%% Misc API. 1104 1105-spec compact(Req) -> Req when Req::req(). 1106compact(Req) -> 1107 Req#http_req{host_info=undefined, 1108 path_info=undefined, qs_vals=undefined, 1109 bindings=undefined, headers=[], 1110 p_headers=[], cookies=[]}. 1111 1112-spec lock(Req) -> Req when Req::req(). 1113lock(Req) -> 1114 Req#http_req{resp_state=locked}. 1115 1116-spec to_list(req()) -> [{atom(), any()}]. 1117to_list(Req) -> 1118 lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))). 1119 1120%% Internal. 1121 1122-spec chunked_response(cowboy:http_status(), cowboy:http_headers(), Req) -> 1123 {normal | hook, Req} when Req::req(). 1124chunked_response(Status, Headers, Req=#http_req{ 1125 transport=cowboy_spdy, resp_state=waiting, 1126 resp_headers=RespHeaders}) -> 1127 {RespType, Req2} = response(Status, Headers, RespHeaders, [ 1128 {<<"date">>, cowboy_clock:rfc1123()}, 1129 {<<"server">>, <<"Cowboy">>} 1130 ], stream, Req), 1131 {RespType, Req2#http_req{resp_state=chunks, 1132 resp_headers=[], resp_body= <<>>}}; 1133chunked_response(Status, Headers, Req=#http_req{ 1134 version=Version, connection=Connection, 1135 resp_state=RespState, resp_headers=RespHeaders}) 1136 when RespState =:= waiting; RespState =:= waiting_stream -> 1137 RespConn = response_connection(Headers, Connection), 1138 HTTP11Headers = if 1139 Version =:= 'HTTP/1.0', Connection =:= keepalive -> 1140 [{<<"connection">>, atom_to_connection(Connection)}]; 1141 Version =:= 'HTTP/1.0' -> []; 1142 true -> 1143 MaybeTE = if 1144 RespState =:= waiting_stream -> []; 1145 true -> [{<<"transfer-encoding">>, <<"chunked">>}] 1146 end, 1147 if 1148 Connection =:= close -> 1149 [{<<"connection">>, atom_to_connection(Connection)}|MaybeTE]; 1150 true -> 1151 MaybeTE 1152 end 1153 end, 1154 RespState2 = if 1155 Version =:= 'HTTP/1.1', RespState =:= 'waiting' -> chunks; 1156 true -> stream 1157 end, 1158 {RespType, Req2} = response(Status, Headers, RespHeaders, [ 1159 {<<"date">>, cowboy_clock:rfc1123()}, 1160 {<<"server">>, <<"Cowboy">>} 1161 |HTTP11Headers], <<>>, Req), 1162 {RespType, Req2#http_req{connection=RespConn, resp_state=RespState2, 1163 resp_headers=[], resp_body= <<>>}}. 1164 1165-spec response(cowboy:http_status(), cowboy:http_headers(), 1166 cowboy:http_headers(), cowboy:http_headers(), stream | iodata(), Req) 1167 -> {normal | hook, Req} when Req::req(). 1168response(Status, Headers, RespHeaders, DefaultHeaders, Body, Req=#http_req{ 1169 socket=Socket, transport=Transport, version=Version, 1170 pid=ReqPid, onresponse=OnResponse}) -> 1171 FullHeaders = case OnResponse of 1172 already_called -> Headers; 1173 _ -> response_merge_headers(Headers, RespHeaders, DefaultHeaders) 1174 end, 1175 Body2 = case Body of stream -> <<>>; _ -> Body end, 1176 {Status2, FullHeaders2, Req2} = case OnResponse of 1177 already_called -> {Status, FullHeaders, Req}; 1178 undefined -> {Status, FullHeaders, Req}; 1179 OnResponse -> 1180 case OnResponse(Status, FullHeaders, Body2, 1181 %% Don't call 'onresponse' from the hook itself. 1182 Req#http_req{resp_headers=[], resp_body= <<>>, 1183 onresponse=already_called}) of 1184 StHdReq = {_, _, _} -> 1185 StHdReq; 1186 Req1 -> 1187 {Status, FullHeaders, Req1} 1188 end 1189 end, 1190 ReplyType = case Req2#http_req.resp_state of 1191 waiting when Transport =:= cowboy_spdy, Body =:= stream -> 1192 cowboy_spdy:stream_reply(Socket, status(Status2), FullHeaders2), 1193 ReqPid ! {?MODULE, resp_sent}, 1194 normal; 1195 waiting when Transport =:= cowboy_spdy -> 1196 cowboy_spdy:reply(Socket, status(Status2), FullHeaders2, Body), 1197 ReqPid ! {?MODULE, resp_sent}, 1198 normal; 1199 RespState when RespState =:= waiting; RespState =:= waiting_stream -> 1200 HTTPVer = atom_to_binary(Version, latin1), 1201 StatusLine = << HTTPVer/binary, " ", 1202 (status(Status2))/binary, "\r\n" >>, 1203 HeaderLines = [[Key, <<": ">>, Value, <<"\r\n">>] 1204 || {Key, Value} <- FullHeaders2], 1205 Transport:send(Socket, [StatusLine, HeaderLines, <<"\r\n">>, Body2]), 1206 ReqPid ! {?MODULE, resp_sent}, 1207 normal; 1208 _ -> 1209 hook 1210 end, 1211 {ReplyType, Req2}. 1212 1213-spec response_connection(cowboy:http_headers(), keepalive | close) 1214 -> keepalive | close. 1215response_connection([], Connection) -> 1216 Connection; 1217response_connection([{Name, Value}|Tail], Connection) -> 1218 case Name of 1219 <<"connection">> -> 1220 Tokens = cow_http_hd:parse_connection(Value), 1221 connection_to_atom(Tokens); 1222 _ -> 1223 response_connection(Tail, Connection) 1224 end. 1225 1226-spec response_merge_headers(cowboy:http_headers(), cowboy:http_headers(), 1227 cowboy:http_headers()) -> cowboy:http_headers(). 1228response_merge_headers(Headers, RespHeaders, DefaultHeaders) -> 1229 Headers2 = [{Key, Value} || {Key, Value} <- Headers], 1230 merge_headers( 1231 merge_headers(Headers2, RespHeaders), 1232 DefaultHeaders). 1233 1234-spec merge_headers(cowboy:http_headers(), cowboy:http_headers()) 1235 -> cowboy:http_headers(). 1236 1237%% Merge headers by prepending the tuples in the second list to the 1238%% first list. It also handles Set-Cookie properly, which supports 1239%% duplicated entries. Notice that, while the RFC2109 does allow more 1240%% than one cookie to be set per Set-Cookie header, we are following 1241%% the implementation of common web servers and applications which 1242%% return many distinct headers per each Set-Cookie entry to avoid 1243%% issues with clients/browser which may not support it. 1244merge_headers(Headers, []) -> 1245 Headers; 1246merge_headers(Headers, [{<<"set-cookie">>, Value}|Tail]) -> 1247 merge_headers([{<<"set-cookie">>, Value}|Headers], Tail); 1248merge_headers(Headers, [{Name, Value}|Tail]) -> 1249 Headers2 = case lists:keymember(Name, 1, Headers) of 1250 true -> Headers; 1251 false -> [{Name, Value}|Headers] 1252 end, 1253 merge_headers(Headers2, Tail). 1254 1255-spec atom_to_connection(keepalive) -> <<_:80>>; 1256 (close) -> <<_:40>>. 1257atom_to_connection(keepalive) -> 1258 <<"keep-alive">>; 1259atom_to_connection(close) -> 1260 <<"close">>. 1261 1262%% We don't match on "keep-alive" since it is the default value. 1263-spec connection_to_atom([binary()]) -> keepalive | close. 1264connection_to_atom([]) -> 1265 keepalive; 1266connection_to_atom([<<"close">>|_]) -> 1267 close; 1268connection_to_atom([_|Tail]) -> 1269 connection_to_atom(Tail). 1270 1271-spec status(cowboy:http_status()) -> binary(). 1272status(100) -> <<"100 Continue">>; 1273status(101) -> <<"101 Switching Protocols">>; 1274status(102) -> <<"102 Processing">>; 1275status(200) -> <<"200 OK">>; 1276status(201) -> <<"201 Created">>; 1277status(202) -> <<"202 Accepted">>; 1278status(203) -> <<"203 Non-Authoritative Information">>; 1279status(204) -> <<"204 No Content">>; 1280status(205) -> <<"205 Reset Content">>; 1281status(206) -> <<"206 Partial Content">>; 1282status(207) -> <<"207 Multi-Status">>; 1283status(226) -> <<"226 IM Used">>; 1284status(300) -> <<"300 Multiple Choices">>; 1285status(301) -> <<"301 Moved Permanently">>; 1286status(302) -> <<"302 Found">>; 1287status(303) -> <<"303 See Other">>; 1288status(304) -> <<"304 Not Modified">>; 1289status(305) -> <<"305 Use Proxy">>; 1290status(306) -> <<"306 Switch Proxy">>; 1291status(307) -> <<"307 Temporary Redirect">>; 1292status(400) -> <<"400 Bad Request">>; 1293status(401) -> <<"401 Unauthorized">>; 1294status(402) -> <<"402 Payment Required">>; 1295status(403) -> <<"403 Forbidden">>; 1296status(404) -> <<"404 Not Found">>; 1297status(405) -> <<"405 Method Not Allowed">>; 1298status(406) -> <<"406 Not Acceptable">>; 1299status(407) -> <<"407 Proxy Authentication Required">>; 1300status(408) -> <<"408 Request Timeout">>; 1301status(409) -> <<"409 Conflict">>; 1302status(410) -> <<"410 Gone">>; 1303status(411) -> <<"411 Length Required">>; 1304status(412) -> <<"412 Precondition Failed">>; 1305status(413) -> <<"413 Request Entity Too Large">>; 1306status(414) -> <<"414 Request-URI Too Long">>; 1307status(415) -> <<"415 Unsupported Media Type">>; 1308status(416) -> <<"416 Requested Range Not Satisfiable">>; 1309status(417) -> <<"417 Expectation Failed">>; 1310status(418) -> <<"418 I'm a teapot">>; 1311status(422) -> <<"422 Unprocessable Entity">>; 1312status(423) -> <<"423 Locked">>; 1313status(424) -> <<"424 Failed Dependency">>; 1314status(425) -> <<"425 Unordered Collection">>; 1315status(426) -> <<"426 Upgrade Required">>; 1316status(428) -> <<"428 Precondition Required">>; 1317status(429) -> <<"429 Too Many Requests">>; 1318status(431) -> <<"431 Request Header Fields Too Large">>; 1319status(500) -> <<"500 Internal Server Error">>; 1320status(501) -> <<"501 Not Implemented">>; 1321status(502) -> <<"502 Bad Gateway">>; 1322status(503) -> <<"503 Service Unavailable">>; 1323status(504) -> <<"504 Gateway Timeout">>; 1324status(505) -> <<"505 HTTP Version Not Supported">>; 1325status(506) -> <<"506 Variant Also Negotiates">>; 1326status(507) -> <<"507 Insufficient Storage">>; 1327status(510) -> <<"510 Not Extended">>; 1328status(511) -> <<"511 Network Authentication Required">>; 1329status(B) when is_binary(B) -> B. 1330 1331%% Tests. 1332 1333-ifdef(TEST). 1334url_test() -> 1335 {undefined, _} = 1336 url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined, 1337 path= <<>>, qs= <<>>, pid=self()}), 1338 {<<"http://localhost/path">>, _ } = 1339 url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=80, 1340 path= <<"/path">>, qs= <<>>, pid=self()}), 1341 {<<"http://localhost:443/path">>, _} = 1342 url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=443, 1343 path= <<"/path">>, qs= <<>>, pid=self()}), 1344 {<<"http://localhost:8080/path">>, _} = 1345 url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080, 1346 path= <<"/path">>, qs= <<>>, pid=self()}), 1347 {<<"http://localhost:8080/path?dummy=2785">>, _} = 1348 url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080, 1349 path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}), 1350 {<<"https://localhost/path">>, _} = 1351 url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=443, 1352 path= <<"/path">>, qs= <<>>, pid=self()}), 1353 {<<"https://localhost:8443/path">>, _} = 1354 url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443, 1355 path= <<"/path">>, qs= <<>>, pid=self()}), 1356 {<<"https://localhost:8443/path?dummy=2785">>, _} = 1357 url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443, 1358 path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}), 1359 ok. 1360 1361connection_to_atom_test_() -> 1362 Tests = [ 1363 {[<<"close">>], close}, 1364 {[<<"keep-alive">>], keepalive}, 1365 {[<<"keep-alive">>, <<"upgrade">>], keepalive} 1366 ], 1367 [{lists:flatten(io_lib:format("~p", [T])), 1368 fun() -> R = connection_to_atom(T) end} || {T, R} <- Tests]. 1369 1370merge_headers_test_() -> 1371 Tests = [ 1372 {[{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}], 1373 [{<<"set-cookie">>,<<"foo=bar">>},{<<"content-length">>,<<"11">>}], 1374 [{<<"set-cookie">>,<<"foo=bar">>}, 1375 {<<"content-length">>,<<"13">>}, 1376 {<<"server">>,<<"Cowboy">>}]}, 1377 {[{<<"content-length">>,<<"13">>},{<<"server">>,<<"Cowboy">>}], 1378 [{<<"set-cookie">>,<<"foo=bar">>},{<<"set-cookie">>,<<"bar=baz">>}], 1379 [{<<"set-cookie">>,<<"bar=baz">>}, 1380 {<<"set-cookie">>,<<"foo=bar">>}, 1381 {<<"content-length">>,<<"13">>}, 1382 {<<"server">>,<<"Cowboy">>}]} 1383 ], 1384 [fun() -> Res = merge_headers(L,R) end || {L, R, Res} <- Tests]. 1385-endif. 1386