Debian Codegraph @

src/cowboy_http.erl

raw
1 %% Copyright (c) Loïc Hoguin <[email protected]>
2 %%
3 %% Permission to use, copy, modify, and/or distribute this software for any
4 %% purpose with or without fee is hereby granted, provided that the above
5 %% copyright notice and this permission notice appear in all copies.
6 %%
7 %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10 %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15 %% @todo Worth renaming to cowboy_http1.
16 %% @todo Change use of cow_http to cow_http1 where appropriate.
17 -module(cowboy_http).
18
19 -export([init/6]).
20 -export([loop/1]).
21
22 %% Shared with other HTTP versions.
23 -export([validate_response_headers/2]).
24
25 -export([system_continue/3]).
26 -export([system_terminate/4]).
27 -export([system_code_change/4]).
28
29 -type opts() :: #{
30 active_n => pos_integer(),
31 alpn_default_protocol => http | http2,
32 chunked => boolean(),
33 compress_buffering => boolean(),
34 compress_threshold => non_neg_integer(),
35 connection_type => worker | supervisor,
36 dynamic_buffer => false | {pos_integer(), pos_integer()},
37 dynamic_buffer_initial_average => non_neg_integer(),
38 dynamic_buffer_initial_size => pos_integer(),
39 env => cowboy_middleware:env(),
40 hibernate => boolean(),
41 http10_keepalive => boolean(),
42 idle_timeout => timeout(),
43 inactivity_timeout => timeout(),
44 initial_stream_flow_size => non_neg_integer(),
45 invalid_response_headers => error_terminate | ignore,
46 linger_timeout => timeout(),
47 logger => module(),
48 max_authority_length => non_neg_integer(),
49 max_authorization_header_value_length => non_neg_integer(),
50 max_cookie_header_value_length => non_neg_integer(),
51 max_empty_lines => non_neg_integer(),
52 max_header_name_length => non_neg_integer(),
53 max_header_value_length => non_neg_integer(),
54 max_headers => non_neg_integer(),
55 max_keepalive => non_neg_integer(),
56 max_method_length => non_neg_integer(),
57 max_request_line_length => non_neg_integer(),
58 max_skip_body_length => non_neg_integer(),
59 metrics_callback => cowboy_metrics_h:metrics_callback(),
60 metrics_req_filter => fun((cowboy_req:req()) -> map()),
61 metrics_resp_headers_filter => fun((cowboy:http_headers()) -> cowboy:http_headers()),
62 middlewares => [module()],
63 protocols => [http | http2],
64 proxy_header => boolean(),
65 request_timeout => timeout(),
66 reset_idle_timeout_on_send => boolean(),
67 sendfile => boolean(),
68 shutdown_timeout => timeout(),
69 stream_handlers => [module()],
70 tracer_callback => cowboy_tracer_h:tracer_callback(),
71 tracer_flags => [atom()],
72 tracer_match_specs => cowboy_tracer_h:tracer_match_specs(),
73 %% Open ended because configured stream handlers might add options.
74 _ => _
75 }.
76 -export_type([opts/0]).
77
78 -record(ps_request_line, {
79 empty_lines = 0 :: non_neg_integer()
80 }).
81
82 -record(ps_header, {
83 method = undefined :: binary(),
84 authority = undefined :: binary() | undefined,
85 path = undefined :: binary(),
86 qs = undefined :: binary(),
87 version = undefined :: cowboy:http_version(),
88 headers = undefined :: cowboy:http_headers() | undefined,
89 num_headers = 0 :: non_neg_integer(),
90 name = undefined :: binary() | undefined
91 }).
92
93 -record(ps_body, {
94 length :: non_neg_integer() | undefined,
95 received = 0 :: non_neg_integer(),
96 transfer_decode_fun :: fun((binary(), cow_http_te:state()) -> cow_http_te:decode_ret()),
97 transfer_decode_state :: cow_http_te:state()
98 }).
99
100 -record(ps_trailer, {
101 }).
102
103 -record(stream, {
104 id = undefined :: cowboy_stream:streamid(),
105 %% Stream handlers and their state.
106 state = undefined :: {module(), any()},
107 %% Request method.
108 method = undefined :: binary(),
109 %% Client HTTP version for this stream.
110 version = undefined :: cowboy:http_version(),
111 %% Unparsed te header. Used to know if we can send trailers.
112 te :: undefined | binary(),
113 %% Expected body size.
114 local_expected_size = undefined :: undefined | non_neg_integer(),
115 %% Sent body size.
116 local_sent_size = 0 :: non_neg_integer()
117 }).
118
119 -type stream() :: #stream{}.
120
121 -record(state, {
122 parent :: pid(),
123 ref :: ranch:ref(),
124 socket :: inet:socket(),
125 transport :: module(),
126 proxy_header :: undefined | ranch_proxy_header:proxy_info(),
127 opts = #{} :: cowboy:opts(),
128 buffer = <<>> :: binary(),
129
130 %% Some options may be overriden for the current stream.
131 overriden_opts = #{} :: cowboy:opts(),
132
133 %% Remote address and port for the connection.
134 peer = undefined :: {inet:ip_address(), inet:port_number()},
135
136 %% Local address and port for the connection.
137 sock = undefined :: {inet:ip_address(), inet:port_number()},
138
139 %% Client certificate (TLS only).
140 cert :: undefined | binary(),
141
142 timer = undefined :: undefined | reference(),
143
144 %% Whether we are currently receiving data from the socket.
145 active = true :: boolean(),
146
147 %% Identifier for the stream currently being read (or waiting to be received).
148 in_streamid = 1 :: pos_integer(),
149
150 %% Parsing state for the current stream or stream-to-be.
151 in_state = #ps_request_line{} :: #ps_request_line{} | #ps_header{} | #ps_body{} | #ps_trailer{} | ps_next_request,
152
153 %% Flow requested for the current stream.
154 flow = infinity :: non_neg_integer() | infinity,
155
156 %% Dynamic buffer moving average and current buffer size.
157 dynamic_buffer_size :: pos_integer() | false,
158 dynamic_buffer_moving_average :: float(),
159
160 %% Whether we finished writing data for the current stream.
161 out_state = wait :: wait | chunked | streaming | done,
162
163 %% The connection will be closed after this stream.
164 last_streamid = undefined :: pos_integer(),
165
166 %% Current HTTP/1.1 stream.
167 stream = undefined :: undefined | stream(),
168
169 %% Children processes created by streams.
170 children = cowboy_children:init() :: cowboy_children:children()
171 }).
172
173 -include_lib("cowlib/include/cow_inline.hrl").
174 -include_lib("cowlib/include/cow_parse.hrl").
175
176 -spec init(pid(), ranch:ref(), inet:socket(), module(),
177 ranch_proxy_header:proxy_info(), cowboy:opts()) -> no_return().
178
179 init(Parent, Ref, Socket, Transport, ProxyHeader, Opts) ->
180 {ok, Peer} = maybe_socket_error(undefined, Transport:peername(Socket),
181 'A socket error occurred when retrieving the peer name.'),
182 {ok, Sock} = maybe_socket_error(undefined, Transport:sockname(Socket),
183 'A socket error occurred when retrieving the sock name.'),
184 CertResult = case Transport:name() of
185 ssl ->
186 case ssl:peercert(Socket) of
187 {error, no_peercert} ->
188 {ok, undefined};
189 Cert0 ->
190 Cert0
191 end;
192 _ ->
193 {ok, undefined}
194 end,
195 {ok, Cert} = maybe_socket_error(undefined, CertResult,
196 'A socket error occurred when retrieving the client TLS certificate.'),
197 State = #state{
198 parent=Parent, ref=Ref, socket=Socket,
199 transport=Transport, proxy_header=ProxyHeader, opts=Opts,
200 peer=Peer, sock=Sock, cert=Cert,
201 dynamic_buffer_size=init_dynamic_buffer_size(Opts),
202 dynamic_buffer_moving_average=maps:get(dynamic_buffer_initial_average, Opts, 0.0),
203 last_streamid=maps:get(max_keepalive, Opts, 1000)},
204 safe_setopts_active(State),
205 before_loop(set_timeout(State, request_timeout)).
206
207 -include("cowboy_dynamic_buffer.hrl").
208
209 setopts_active(#state{socket=Socket, transport=Transport, opts=Opts}) ->
210 N = maps:get(active_n, Opts, 1),
211 Transport:setopts(Socket, [{active, N}]).
212
213 safe_setopts_active(State) ->
214 ok = maybe_socket_error(State, setopts_active(State)).
215
216 active(State) ->
217 safe_setopts_active(State),
218 State#state{active=true}.
219
220 passive(State=#state{socket=Socket, transport=Transport}) ->
221 ok = maybe_socket_error(State, Transport:setopts(Socket, [{active, false}])),
222 Messages = Transport:messages(),
223 flush_passive(Socket, Messages),
224 State#state{active=false}.
225
226 flush_passive(Socket, Messages) ->
227 receive
228 {Passive, Socket} when Passive =:= element(4, Messages);
229 %% Hardcoded for compatibility with Ranch 1.x.
230 Passive =:= tcp_passive; Passive =:= ssl_passive ->
231 flush_passive(Socket, Messages)
232 after 0 ->
233 ok
234 end.
235
236 before_loop(State0=#state{in_state=ps_next_request, stream=undefined}) ->
237 next_request(State0);
238 before_loop(State=#state{opts=#{hibernate := true}}) ->
239 proc_lib:hibernate(?MODULE, loop, [State]);
240 before_loop(State) ->
241 loop(State).
242
243 next_request(State0=#state{buffer=Buffer}) ->
244 %% Switch back to the request_timeout.
245 State1 = set_timeout(State0, request_timeout),
246 State = State1#state{in_state=#ps_request_line{}},
247 case Buffer of
248 <<>> -> before_loop(State);
249 _ -> parse(Buffer, State)
250 end.
251
252 -spec loop(#state{}) -> no_return().
253
254 loop(State=#state{parent=Parent, socket=Socket, transport=Transport, opts=Opts,
255 buffer=Buffer, timer=TimerRef, children=Children, in_streamid=InStreamID,
256 last_streamid=LastStreamID}) ->
257 Messages = Transport:messages(),
258 InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
259 receive
260 %% Discard data coming in after the last request
261 %% we want to process was received fully.
262 {OK, Socket, Data} when OK =:= element(1, Messages), InStreamID > LastStreamID ->
263 State1 = maybe_resize_buffer(State, Data),
264 before_loop(State1);
265 %% Socket messages.
266 {OK, Socket, Data} when OK =:= element(1, Messages) ->
267 State1 = maybe_resize_buffer(State, Data),
268 parse(<< Buffer/binary, Data/binary >>, State1);
269 {Closed, Socket} when Closed =:= element(2, Messages) ->
270 terminate(State, {socket_error, closed, 'The socket has been closed.'});
271 {Error, Socket, Reason} when Error =:= element(3, Messages) ->
272 terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
273 {Passive, Socket} when Passive =:= element(4, Messages);
274 %% Hardcoded for compatibility with Ranch 1.x.
275 Passive =:= tcp_passive; Passive =:= ssl_passive ->
276 safe_setopts_active(State),
277 before_loop(State);
278 %% Timeouts.
279 {timeout, Ref, {shutdown, Pid}} ->
280 cowboy_children:shutdown_timeout(Children, Ref, Pid),
281 before_loop(State);
282 {timeout, TimerRef, Reason} ->
283 timeout(State, Reason);
284 {timeout, _, _} ->
285 before_loop(State);
286 %% System messages.
287 {'EXIT', Parent, shutdown} ->
288 Reason = {stop, {exit, shutdown}, 'Parent process requested shutdown.'},
289 before_loop(initiate_closing(State, Reason));
290 {'EXIT', Parent, Reason} ->
291 terminate(State, {stop, {exit, Reason}, 'Parent process terminated.'});
292 {system, From, Request} ->
293 sys:handle_system_msg(Request, From, Parent, ?MODULE, [], State);
294 %% Messages pertaining to a stream.
295 {{Pid, StreamID}, Msg} when Pid =:= self() ->
296 before_loop(info(State, StreamID, Msg));
297 %% Exit signal from children.
298 Msg = {'EXIT', Pid, _} ->
299 before_loop(down(State, Pid, Msg));
300 %% Calls from supervisor module.
301 {'$gen_call', From, Call} ->
302 cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE),
303 before_loop(State);
304 %% Unknown messages.
305 Msg ->
306 cowboy:log(warning, "Received stray message ~p.~n", [Msg], Opts),
307 before_loop(State)
308 after InactivityTimeout ->
309 terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
310 end.
311
312 %% For HTTP/1.1 we have two types of timeouts: the request_timeout
313 %% is used when there is no currently ongoing request. This means
314 %% that we are not currently sending or receiving data and that
315 %% the next data to be received will be a new request. The
316 %% request_timeout is set once when we no longer have ongoing
317 %% requests, and runs until the full set of request headers
318 %% is received. It is not reset.
319 %%
320 %% After that point we use the idle_timeout. We continue using
321 %% the idle_timeout if pipelined requests come in: we are doing
322 %% work and just want to ensure the socket is not half-closed.
323 %% We continue using the idle_timeout up until there is no
324 %% ongoing request. This includes requests that were processed
325 %% and for which we only want to skip the body. Once the body
326 %% has been read fully we can go back to request_timeout. The
327 %% idle_timeout is reset every time we receive data and,
328 %% optionally, every time we send data.
329
330 %% We do not set idle_timeout if there are no active streams,
331 %% unless when we are skipping a body.
332 set_timeout(State=#state{stream=undefined, in_state=InState}, idle_timeout)
333 when InState =:= ps_next_request;
334 element(1, InState) =:= ps_request_line;
335 element(1, InState) =:= ps_header ->
336 State;
337 %% Otherwise we can set the timeout.
338 %% @todo Don't do this so often, use a strategy similar to Websocket/H2 if possible.
339 set_timeout(State0=#state{opts=Opts, overriden_opts=Override}, Name) ->
340 State = cancel_timeout(State0),
341 Default = case Name of
342 request_timeout -> 5000;
343 idle_timeout -> 60000
344 end,
345 Timeout = case Override of
346 %% The timeout may have been overriden for the current stream.
347 #{Name := Timeout0} -> Timeout0;
348 _ -> maps:get(Name, Opts, Default)
349 end,
350 TimerRef = case Timeout of
351 infinity -> undefined;
352 Timeout -> erlang:start_timer(Timeout, self(), Name)
353 end,
354 State#state{timer=TimerRef}.
355
356 maybe_reset_idle_timeout(State=#state{opts=Opts}) ->
357 case maps:get(reset_idle_timeout_on_send, Opts, false) of
358 true ->
359 set_timeout(State, idle_timeout);
360 false ->
361 State
362 end.
363
364 cancel_timeout(State=#state{timer=TimerRef}) ->
365 ok = case TimerRef of
366 undefined ->
367 ok;
368 _ ->
369 %% Do a synchronous cancel and remove the message if any
370 %% to avoid receiving stray messages.
371 _ = erlang:cancel_timer(TimerRef, [{async, false}, {info, false}]),
372 receive
373 {timeout, TimerRef, _} -> ok
374 after 0 ->
375 ok
376 end
377 end,
378 State#state{timer=undefined}.
379
380 -spec timeout(_, _) -> no_return().
381
382 timeout(State=#state{in_state=#ps_request_line{}}, request_timeout) ->
383 terminate(State, {connection_error, timeout,
384 'No request-line received before timeout.'});
385 timeout(State=#state{in_state=#ps_header{}}, request_timeout) ->
386 error_terminate(408, State, {connection_error, timeout,
387 'Request headers not received before timeout.'});
388 timeout(State, idle_timeout) ->
389 terminate(State, {connection_error, timeout,
390 'Connection idle longer than configuration allows.'}).
391
392 parse(<<>>, State) ->
393 before_loop(State#state{buffer= <<>>});
394 %% Do not process requests that come in after the last request
395 %% and discard the buffer if any to save memory.
396 parse(_, State=#state{in_streamid=InStreamID, in_state=InState,
397 last_streamid=LastStreamID}) when InStreamID > LastStreamID,
398 (InState =:= ps_next_request) orelse (element(1, InState) =:= ps_request_line) ->
399 before_loop(State#state{buffer= <<>>});
400 %% Delay parsing pipelined requests until current stream stops.
401 parse(Buffer, State=#state{in_state=ps_next_request, stream=#stream{}}) ->
402 before_loop(State#state{buffer=Buffer});
403 parse(Buffer, State=#state{in_state=ps_next_request, stream=undefined}) ->
404 next_request(State#state{buffer=Buffer});
405 parse(Buffer, State=#state{in_state=#ps_request_line{empty_lines=EmptyLines}}) ->
406 after_parse(parse_request(Buffer, State, EmptyLines));
407 parse(Buffer, State=#state{in_state=PS=#ps_header{
408 headers=Headers, num_headers=Num, name=undefined}}) ->
409 after_parse(parse_header(Buffer,
410 State#state{in_state=PS#ps_header{headers=undefined}},
411 Headers, Num));
412 parse(Buffer, State=#state{in_state=PS=#ps_header{
413 headers=Headers, num_headers=Num, name=Name}}) ->
414 after_parse(parse_hd_before_value(Buffer,
415 State#state{in_state=PS#ps_header{headers=undefined, name=undefined}},
416 Headers, Num, Name));
417 parse(Buffer, State=#state{in_state=#ps_body{}}) ->
418 after_parse(parse_body(Buffer, State));
419 parse(Buffer, State=#state{in_state=#ps_trailer{}}) ->
420 after_parse(parse_trailer(Buffer, State)).
421
422 after_parse({request, Req=#{streamid := StreamID, method := Method,
423 headers := Headers, version := Version},
424 State0=#state{opts=Opts, buffer=Buffer, stream=undefined}}) ->
425 try cowboy_stream:init(StreamID, Req, Opts) of
426 {Commands, StreamState} ->
427 Flow = maps:get(initial_stream_flow_size, Opts, 65535),
428 TE = maps:get(<<"te">>, Headers, undefined),
429 Stream = #stream{id=StreamID, state=StreamState,
430 method=Method, version=Version, te=TE},
431 State1 = State0#state{stream=Stream, flow=Flow},
432 State = set_timeout(State1, idle_timeout),
433 parse(Buffer, commands(State, Commands))
434 catch Class:Exception:Stacktrace ->
435 cowboy:log(cowboy_stream:make_error_log(init,
436 [StreamID, Req, Opts],
437 Class, Exception, Stacktrace), Opts),
438 %% We do not reset the idle timeout on send here
439 %% because an error occurred in the application. While we
440 %% are keeping the connection open for further requests we
441 %% do not want to keep the connection up too long if no
442 %% additional requests come in.
443 early_error(500, State0, {internal_error, {Class, Exception},
444 'Unhandled exception in cowboy_stream:init/3.'}, Req),
445 parse(Buffer, State0)
446 end;
447 after_parse({data, IsFin, Data, State0=#state{opts=Opts, buffer=Buffer,
448 stream=Stream0=#stream{id=StreamID, state=StreamState0}}}) ->
449 try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
450 {Commands, StreamState} ->
451 Stream = Stream0#stream{state=StreamState},
452 State1 = set_timeout(State0#state{stream=Stream}, idle_timeout),
453 State = update_flow(IsFin, Data, State1),
454 parse(Buffer, commands(State, Commands))
455 catch Class:Exception:Stacktrace ->
456 cowboy:log(cowboy_stream:make_error_log(data,
457 [StreamID, IsFin, Data, StreamState0],
458 Class, Exception, Stacktrace), Opts),
459 Reason = {internal_error, {Class, Exception},
460 'Unhandled exception in cowboy_stream:data/4.'},
461 terminate(stream_terminate(State0, Reason), Reason)
462 end;
463 %% No corresponding stream. We must skip the body of the previous request
464 %% in order to process the next one.
465 after_parse({data, _, _, State=#state{buffer=Buffer}}) ->
466 parse(Buffer, set_timeout(State, idle_timeout));
467 after_parse({more, State}) ->
468 before_loop(set_timeout(State, idle_timeout)).
469
470 update_flow(fin, _, State) ->
471 %% This function is only called after parsing, therefore we
472 %% are expecting to be in active mode already.
473 State#state{flow=infinity};
474 update_flow(nofin, Data, State0=#state{flow=Flow0}) ->
475 Flow = Flow0 - byte_size(Data),
476 State = State0#state{flow=Flow},
477 if
478 Flow0 > 0, Flow =< 0 ->
479 passive(State);
480 true ->
481 State
482 end.
483
484 %% Request-line.
485
486 -spec parse_request(Buffer, State, non_neg_integer())
487 -> {request, cowboy_req:req(), State}
488 | {more, State}
489 when Buffer::binary(), State::#state{}.
490
491 %% Empty lines must be using \r\n.
492 parse_request(<< $\n, _/bits >>, State, _) ->
493 error_terminate(400, State, {connection_error, protocol_error,
494 'Empty lines between requests must use the CRLF line terminator. (RFC7230 3.5)'});
495 parse_request(<< $\s, _/bits >>, State, _) ->
496 error_terminate(400, State, {connection_error, protocol_error,
497 'The request-line must not begin with a space. (RFC7230 3.1.1, RFC7230 3.5)'});
498 %% We limit the length of the Request-line to MaxLength to avoid endlessly
499 %% reading from the socket and eventually crashing.
500 parse_request(Buffer, State=#state{opts=Opts, in_streamid=InStreamID}, EmptyLines) ->
501 MaxLength = maps:get(max_request_line_length, Opts, 8000),
502 MaxEmptyLines = maps:get(max_empty_lines, Opts, 5),
503 case match_eol(Buffer, 0) of
504 nomatch when byte_size(Buffer) > MaxLength ->
505 error_terminate(414, State, {connection_error, limit_reached,
506 'The request-line length is larger than configuration allows. (RFC7230 3.1.1)'});
507 nomatch ->
508 {more, State#state{buffer=Buffer, in_state=#ps_request_line{empty_lines=EmptyLines}}};
509 error ->
510 error_terminate(400, State, {connection_error, protocol_error,
511 'The request-line must use the CRLF line terminator. (RFC7230 3.1.1, RFC7230 3.5)'});
512 0 when EmptyLines =:= MaxEmptyLines ->
513 error_terminate(400, State, {connection_error, limit_reached,
514 'More empty lines were received than configuration allows. (RFC7230 3.5)'});
515 0 ->
516 << _:16, Rest/bits >> = Buffer,
517 parse_request(Rest, State, EmptyLines + 1);
518 _ ->
519 case Buffer of
520 %% @todo * is only for server-wide OPTIONS request (RFC7230 5.3.4); tests
521 << "OPTIONS * ", Rest/bits >> ->
522 parse_version(Rest, State, <<"OPTIONS">>, undefined, <<"*">>, <<>>);
523 <<"CONNECT ", _/bits>> ->
524 error_terminate(501, State, {connection_error, no_error,
525 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)'});
526 <<"TRACE ", _/bits>> ->
527 error_terminate(501, State, {connection_error, no_error,
528 'The TRACE method is currently not implemented. (RFC7231 4.3.8)'});
529 %% Accept direct HTTP/2 only at the beginning of the connection.
530 << "PRI * HTTP/2.0\r\n", _/bits >> when InStreamID =:= 1 ->
531 case lists:member(http2, maps:get(protocols, Opts, [http2, http])) of
532 true ->
533 http2_upgrade(State, Buffer);
534 false ->
535 error_terminate(501, State, {connection_error, no_error,
536 'Prior knowledge upgrade to HTTP/2 is disabled by configuration.'})
537 end;
538 _ ->
539 parse_method(Buffer, State, <<>>,
540 maps:get(max_method_length, Opts, 32))
541 end
542 end.
543
544 match_eol(<< $\r, $\n, _/bits >>, N) ->
545 N;
546 match_eol(<< $\r, _, _/bits >>, _) ->
547 error;
548 match_eol(<< $\n, _/bits >>, _) ->
549 error;
550 match_eol(<< _, Rest/bits >>, N) ->
551 match_eol(Rest, N + 1);
552 match_eol(_, _) ->
553 nomatch.
554
555 parse_method(_, State, _, 0) ->
556 error_terminate(501, State, {connection_error, limit_reached,
557 'The method name is longer than configuration allows. (RFC7230 3.1.1)'});
558 parse_method(<< C, Rest/bits >>, State, SoFar, Remaining) ->
559 case C of
560 $\r -> error_terminate(400, State, {connection_error, protocol_error,
561 'The method name must not be followed with a line break. (RFC7230 3.1.1)'});
562 $\s -> parse_uri(Rest, State, SoFar);
563 _ when ?IS_TOKEN(C) -> parse_method(Rest, State, << SoFar/binary, C >>, Remaining - 1);
564 _ -> error_terminate(400, State, {connection_error, protocol_error,
565 'The method name must contain only valid token characters. (RFC7230 3.1.1)'})
566 end.
567
568 parse_uri(<< H, T, T, P, "://", Rest/bits >>, State, Method)
569 when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
570 P =:= $p orelse P =:= $P ->
571 parse_uri_authority(Rest, State, Method);
572 parse_uri(<< H, T, T, P, S, "://", Rest/bits >>, State, Method)
573 when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
574 P =:= $p orelse P =:= $P; S =:= $s orelse S =:= $S ->
575 parse_uri_authority(Rest, State, Method);
576 parse_uri(<< $/, Rest/bits >>, State, Method) ->
577 parse_uri_path(Rest, State, Method, undefined, <<$/>>);
578 parse_uri(_, State, _) ->
579 error_terminate(400, State, {connection_error, protocol_error,
580 'Invalid request-line or request-target. (RFC7230 3.1.1, RFC7230 5.3)'}).
581
582 parse_uri_authority(Rest, State=#state{opts=Opts}, Method) ->
583 parse_uri_authority(Rest, State, Method, <<>>,
584 maps:get(max_authority_length, Opts, 255)).
585
586 parse_uri_authority(<<C, Rest/bits>>, State, Method, SoFar, Remaining) ->
587 case C of
588 $\r ->
589 error_terminate(400, State, {connection_error, protocol_error,
590 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
591 $@ ->
592 error_terminate(400, State, {connection_error, protocol_error,
593 'Absolute URIs must not include a userinfo component. (RFC7230 2.7.1)'});
594 $# ->
595 error_terminate(400, State, {connection_error, protocol_error,
596 'The request-target must not include a fragment component. (RFC9110 4.1, RFC9112 3.2)'});
597 C when SoFar =:= <<>> andalso
598 ((C =:= $/) orelse (C =:= $\s) orelse (C =:= $?) orelse (C =:= $:)) ->
599 error_terminate(400, State, {connection_error, protocol_error,
600 'Absolute URIs must include a non-empty host component. (RFC7230 2.7.1)'});
601 $/ -> parse_uri_path(Rest, State, Method, SoFar, <<"/">>);
602 $\s -> parse_version(Rest, State, Method, SoFar, <<"/">>, <<>>);
603 $? -> parse_uri_query(Rest, State, Method, SoFar, <<"/">>, <<>>);
604 C when Remaining > 0 ->
605 parse_uri_authority(Rest, State, Method, <<SoFar/binary, C>>, Remaining - 1);
606 _ ->
607 error_terminate(414, State, {connection_error, limit_reached,
608 'The authority component of the absolute URI is longer than configuration allows. (RFC7230 2.7.1)'})
609 end.
610
611 parse_uri_path(<<C, Rest/bits>>, State, Method, Authority, SoFar) ->
612 case C of
613 $\0 -> error_terminate(400, State, {connection_error, protocol_error,
614 'NUL byte is not allowed in the request-target. (RFC7230 3.1.1)'});
615 $\r -> error_terminate(400, State, {connection_error, protocol_error,
616 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
617 $# -> error_terminate(400, State, {connection_error, protocol_error,
618 'The request-target must not include a fragment component. (RFC9110 4.1, RFC9112 3.2)'});
619 $\s -> parse_version(Rest, State, Method, Authority, SoFar, <<>>);
620 $? -> parse_uri_query(Rest, State, Method, Authority, SoFar, <<>>);
621 _ -> parse_uri_path(Rest, State, Method, Authority, <<SoFar/binary, C>>)
622 end.
623
624 parse_uri_query(<<C, Rest/bits>>, State, M, A, P, SoFar) ->
625 case C of
626 $\0 -> error_terminate(400, State, {connection_error, protocol_error,
627 'NUL byte is not allowed in the request-target. (RFC7230 3.1.1)'});
628 $\r -> error_terminate(400, State, {connection_error, protocol_error,
629 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
630 $# -> error_terminate(400, State, {connection_error, protocol_error,
631 'The request-target must not include a fragment component. (RFC9110 4.1, RFC9112 3.2)'});
632 $\s -> parse_version(Rest, State, M, A, P, SoFar);
633 _ -> parse_uri_query(Rest, State, M, A, P, <<SoFar/binary, C>>)
634 end.
635
636 parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, State, M, A, P, Q) ->
637 before_parse_headers(Rest, State, M, A, P, Q, 'HTTP/1.1');
638 parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, State, M, A, P, Q) ->
639 before_parse_headers(Rest, State, M, A, P, Q, 'HTTP/1.0');
640 parse_version(<< "HTTP/1.", _, C, _/bits >>, State, _, _, _, _) when C =:= $\s; C =:= $\t ->
641 error_terminate(400, State, {connection_error, protocol_error,
642 'Whitespace is not allowed after the HTTP version. (RFC7230 3.1.1)'});
643 parse_version(<< C, _/bits >>, State, _, _, _, _) when C =:= $\s; C =:= $\t ->
644 error_terminate(400, State, {connection_error, protocol_error,
645 'The separator between request target and version must be a single SP. (RFC7230 3.1.1)'});
646 parse_version(_, State, _, _, _, _) ->
647 error_terminate(505, State, {connection_error, protocol_error,
648 'Unsupported HTTP version. (RFC7230 2.6)'}).
649
650 before_parse_headers(Rest, State, M, A, P, Q, V) ->
651 parse_header(Rest, State#state{in_state=#ps_header{
652 method=M, authority=A, path=P, qs=Q, version=V}}, #{}, 0).
653
654 %% Headers.
655
656 parse_header(<< $\n, _/bits >>, State=#state{in_state=PS}, Headers, Num) ->
657 error_terminate(400, State#state{in_state=PS#ps_header{
658 headers=Headers, num_headers=Num}},
659 {connection_error, protocol_error,
660 'Header lines must use the CRLF line terminator. (RFC7230 3.2, RFC7230 3.5)'});
661 %% We need two or more bytes in the buffer to continue.
662 parse_header(Rest, State=#state{in_state=PS}, Headers, Num) when byte_size(Rest) < 2 ->
663 {more, State#state{buffer=Rest, in_state=PS#ps_header{
664 headers=Headers, num_headers=Num}}};
665 parse_header(<< $\r, $\n, Rest/bits >>, S, Headers, _) ->
666 request(Rest, S, Headers);
667 parse_header(Buffer, State=#state{opts=Opts, in_state=PS}, Headers, Num) ->
668 MaxHeaders = maps:get(max_headers, Opts, 100),
669 if
670 Num >= MaxHeaders ->
671 error_terminate(431, State#state{in_state=PS#ps_header{
672 headers=Headers, num_headers=Num}},
673 {connection_error, limit_reached,
674 'The number of headers is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'});
675 true ->
676 parse_header_colon(Buffer, State, Headers, Num)
677 end.
678
679 parse_header_colon(Buffer, State=#state{opts=Opts, in_state=PS}, Headers, Num) ->
680 MaxLength = maps:get(max_header_name_length, Opts, 64),
681 case match_colon(Buffer, 0) of
682 nomatch when byte_size(Buffer) > MaxLength ->
683 error_terminate(431, State#state{in_state=PS#ps_header{
684 headers=Headers, num_headers=Num}},
685 {connection_error, limit_reached,
686 'A header name is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'});
687 nomatch ->
688 case match_eol(Buffer, 0) of
689 nomatch ->
690 {more, State#state{buffer=Buffer, in_state=PS#ps_header{
691 headers=Headers, num_headers=Num}}};
692 error ->
693 error_terminate(400, State#state{in_state=PS#ps_header{
694 headers=Headers, num_headers=Num}},
695 {connection_error, protocol_error,
696 'Header lines must use the CRLF line terminator. (RFC7230 3.2, RFC7230 3.5)'});
697 _ ->
698 error_terminate(400, State#state{in_state=PS#ps_header{
699 headers=Headers, num_headers=Num}},
700 {connection_error, protocol_error,
701 'A header line is missing a colon separator. (RFC7230 3.2.4)'})
702 end;
703 _ ->
704 parse_hd_name(Buffer, State, Headers, Num, <<>>)
705 end.
706
707 match_colon(<< $:, _/bits >>, N) ->
708 N;
709 match_colon(<< _, Rest/bits >>, N) ->
710 match_colon(Rest, N + 1);
711 match_colon(_, _) ->
712 nomatch.
713
714 parse_hd_name(<< $:, Rest/bits >>, State, H, Num, SoFar) ->
715 parse_hd_before_value(Rest, State, H, Num, SoFar);
716 parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, Num, <<>>) when ?IS_WS(C) ->
717 error_terminate(400, State#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
718 {connection_error, protocol_error,
719 'Whitespace is not allowed before the header name. (RFC7230 3.2)'});
720 parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, Num, _) when ?IS_WS(C) ->
721 error_terminate(400, State#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
722 {connection_error, protocol_error,
723 'Whitespace is not allowed between the header name and the colon. (RFC7230 3.2.4)'});
724 parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, Num, _)
725 when C =:= $\r; C =:= $\n ->
726 error_terminate(400, State#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
727 {connection_error, protocol_error,
728 'A header line is missing a colon separator. (RFC7230 3.2.4)'});
729 parse_hd_name(<< $\0, _/bits >>, State=#state{in_state=PS}, H, Num, _) ->
730 error_terminate(400, State#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
731 {connection_error, protocol_error,
732 'NUL byte is not allowed in header name. (RFC9110 5.5)'});
733 parse_hd_name(<< C, Rest/bits >>, State, H, Num, SoFar) ->
734 ?LOWER(parse_hd_name, Rest, State, H, Num, SoFar).
735
736 parse_hd_before_value(<< $\s, Rest/bits >>, S, H, Num, N) ->
737 parse_hd_before_value(Rest, S, H, Num, N);
738 parse_hd_before_value(<< $\t, Rest/bits >>, S, H, Num, N) ->
739 parse_hd_before_value(Rest, S, H, Num, N);
740 parse_hd_before_value(Buffer, State=#state{opts=Opts, in_state=PS}, H, Num, N) ->
741 MaxLength = max_header_value_length(N, Opts),
742 case match_eol(Buffer, 0) of
743 nomatch when byte_size(Buffer) > MaxLength ->
744 error_terminate(431, State#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
745 {connection_error, limit_reached,
746 'A header value is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'});
747 nomatch ->
748 {more, State#state{buffer=Buffer, in_state=PS#ps_header{
749 headers=H, num_headers=Num, name=N}}};
750 error ->
751 error_terminate(400, State#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
752 {connection_error, protocol_error,
753 'Header lines must use the CRLF line terminator. (RFC7230 3.2, RFC7230 3.5)'});
754 _ ->
755 parse_hd_value(Buffer, State, H, Num, N, <<>>)
756 end.
757
758 max_header_value_length(<<"authorization">>, #{max_authorization_header_value_length := Max}) ->
759 Max;
760 max_header_value_length(<<"cookie">>, #{max_cookie_header_value_length := Max}) ->
761 Max;
762 %% Stop early when possible. But because the max header value length
763 %% is a soft limit we may not catch a long host value here. We will
764 %% check the host length again later.
765 max_header_value_length(<<"host">>, Opts) ->
766 maps:get(max_authority_length, Opts, 255);
767 max_header_value_length(_, #{max_header_value_length := Max}) ->
768 Max;
769 max_header_value_length(_, _) ->
770 4096.
771
772 parse_hd_value(<< $\r, $\n, Rest/bits >>, S, Headers0, Num, Name, SoFar) ->
773 Value = clean_value_ws_end(SoFar, byte_size(SoFar) - 1),
774 Headers = case maps:get(Name, Headers0, undefined) of
775 undefined -> Headers0#{Name => Value};
776 %% The cookie header does not use proper HTTP header lists.
777 Value0 when Name =:= <<"cookie">> -> Headers0#{Name => << Value0/binary, "; ", Value/binary >>};
778 Value0 -> Headers0#{Name => << Value0/binary, ", ", Value/binary >>}
779 end,
780 parse_header(Rest, S, Headers, Num + 1);
781 parse_hd_value(<< $\0, _/bits >>, S=#state{in_state=PS}, H, Num, _, _) ->
782 error_terminate(400, S#state{in_state=PS#ps_header{headers=H, num_headers=Num}},
783 {connection_error, protocol_error,
784 'NUL byte is not allowed in header value. (RFC9110 5.5)'});
785 parse_hd_value(<< C, Rest/bits >>, S, H, Num, N, SoFar) ->
786 parse_hd_value(Rest, S, H, Num, N, << SoFar/binary, C >>).
787
788 clean_value_ws_end(_, -1) ->
789 <<>>;
790 clean_value_ws_end(Value, N) ->
791 case binary:at(Value, N) of
792 $\s -> clean_value_ws_end(Value, N - 1);
793 $\t -> clean_value_ws_end(Value, N - 1);
794 _ ->
795 S = N + 1,
796 << Value2:S/binary, _/bits >> = Value,
797 Value2
798 end.
799
800 -ifdef(TEST).
801 clean_value_ws_end_test_() ->
802 Tests = [
803 {<<>>, <<>>},
804 {<<" ">>, <<>>},
805 {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
806 "text/html;level=2;q=0.4, */*;q=0.5 \t \t ">>,
807 <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
808 "text/html;level=2;q=0.4, */*;q=0.5">>}
809 ],
810 [{V, fun() -> R = clean_value_ws_end(V, byte_size(V) - 1) end} || {V, R} <- Tests].
811
812 horse_clean_value_ws_end() ->
813 horse:repeat(200000,
814 clean_value_ws_end(
815 <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
816 "text/html;level=2;q=0.4, */*;q=0.5 ">>,
817 byte_size(<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
818 "text/html;level=2;q=0.4, */*;q=0.5 ">>) - 1)
819 ).
820 -endif.
821
822 request(Buffer, State=#state{transport=Transport,
823 in_state=PS=#ps_header{authority=Authority, version=Version}}, Headers) ->
824 case maps:get(<<"host">>, Headers, undefined) of
825 undefined when Version =:= 'HTTP/1.1' ->
826 %% @todo Might want to not close the connection on this and next one.
827 error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}},
828 {stream_error, protocol_error,
829 'HTTP/1.1 requests must include a host header. (RFC7230 5.4)'});
830 undefined ->
831 request_parse_connection(Buffer, State, Headers, <<>>,
832 default_port(Transport:secure()));
833 %% @todo When CONNECT requests come in we need to ignore the RawHost
834 %% and instead use the Authority as the source of host.
835 RawHost when Authority =:= undefined; Authority =:= RawHost ->
836 request_parse_host(Buffer, State, Headers, RawHost);
837 %% RFC7230 does not explicitly ask us to reject requests
838 %% that have a different authority component and host header.
839 %% However it DOES ask clients to set them to the same value,
840 %% so we enforce that.
841 _ ->
842 error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}},
843 {stream_error, protocol_error,
844 'The host header is different than the absolute-form authority component. (RFC7230 5.4)'})
845 end.
846
847 request_parse_host(Buffer, State=#state{opts=Opts}, Headers, RawHost) ->
848 case byte_size(RawHost) > maps:get(max_authority_length, Opts, 255) of
849 true ->
850 error_terminate(414, State, {connection_error, limit_reached,
851 'The host header is longer than configuration allows. (RFC7230 2.7.1, RFC7230 5.4)'});
852 false ->
853 request_parse_host1(Buffer, State, Headers, RawHost)
854 end.
855
856 request_parse_host1(Buffer, State=#state{transport=Transport, in_state=PS}, Headers, RawHost) ->
857 try cow_http_hd:parse_host(RawHost) of
858 {Host, undefined} ->
859 request_parse_connection(Buffer, State, Headers, Host,
860 default_port(Transport:secure()));
861 {Host, Port} when Port > 0, Port =< 65535 ->
862 request_parse_connection(Buffer, State, Headers, Host, Port);
863 _ ->
864 error_terminate(400, State, {stream_error, protocol_error,
865 'The port component of the absolute-form is not in the range 0..65535. (RFC7230 2.7.1)'})
866 catch _:_ ->
867 error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}},
868 {stream_error, protocol_error,
869 'The host header is invalid. (RFC7230 5.4)'})
870 end.
871
872 -spec default_port(boolean()) -> 80 | 443.
873
874 default_port(true) -> 443;
875 default_port(_) -> 80.
876
877 request_parse_connection(Buffer, State0=#state{in_streamid=StreamID,
878 in_state=PS=#ps_header{version=Version}}, Headers, Host, Port) ->
879 State = case maybe_req_close(State0, Headers, Version) of
880 close ->
881 State0#state{last_streamid=StreamID};
882 keepalive ->
883 State0;
884 bad_connection_header ->
885 error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers}},
886 {connection_error, protocol_error,
887 'The Connection header is invalid. (RFC7230 6.1)'})
888 end,
889 request(Buffer, State, Headers, Host, Port).
890
891 %% End of request parsing.
892
893 request(Buffer, State0=#state{ref=Ref, transport=Transport, peer=Peer, sock=Sock, cert=Cert,
894 opts=Opts, proxy_header=ProxyHeader, in_streamid=StreamID, in_state=
895 PS=#ps_header{method=Method, path=Path, qs=Qs, version=Version}},
896 Headers, Host, Port) ->
897 Scheme = case Transport:secure() of
898 true -> <<"https">>;
899 false -> <<"http">>
900 end,
901 {HasBody, BodyLength, TDecodeFun, TDecodeState} = case Headers of
902 #{<<"transfer-encoding">> := _, <<"content-length">> := _} ->
903 error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers}},
904 {stream_error, protocol_error,
905 'The request had both transfer-encoding and content-length headers. (RFC7230 3.3.3)'});
906 #{<<"transfer-encoding">> := TransferEncoding0} ->
907 try cow_http_hd:parse_transfer_encoding(TransferEncoding0) of
908 [<<"chunked">>] ->
909 {true, undefined, fun cow_http_te:stream_chunked/2, {0, 0}};
910 _ ->
911 error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers}},
912 {stream_error, protocol_error,
913 'Cowboy only supports transfer-encoding: chunked. (RFC7230 3.3.1)'})
914 catch _:_ ->
915 error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers}},
916 {stream_error, protocol_error,
917 'The transfer-encoding header is invalid. (RFC7230 3.3.1)'})
918 end;
919 #{<<"content-length">> := <<"0">>} ->
920 {false, 0, undefined, undefined};
921 #{<<"content-length">> := BinLength} ->
922 Length = try
923 cow_http_hd:parse_content_length(BinLength)
924 catch _:_ ->
925 error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers}},
926 {stream_error, protocol_error,
927 'The content-length header is invalid. (RFC7230 3.3.2)'})
928 end,
929 {true, Length, fun cow_http_te:stream_identity/2, {0, Length}};
930 _ ->
931 {false, 0, undefined, undefined}
932 end,
933 Req0 = #{
934 ref => Ref,
935 pid => self(),
936 streamid => StreamID,
937 peer => Peer,
938 sock => Sock,
939 cert => Cert,
940 method => Method,
941 scheme => Scheme,
942 host => Host,
943 port => Port,
944 path => Path,
945 qs => Qs,
946 version => Version,
947 %% We are transparently taking care of transfer-encodings so
948 %% the user code has no need to know about it.
949 headers => maps:remove(<<"transfer-encoding">>, Headers),
950 has_body => HasBody,
951 body_length => BodyLength
952 },
953 %% We add the PROXY header information if any.
954 Req = case ProxyHeader of
955 undefined -> Req0;
956 _ -> Req0#{proxy_header => ProxyHeader}
957 end,
958 case is_http2_upgrade(Headers, Version, Opts) of
959 false ->
960 State = case HasBody of
961 true ->
962 State0#state{in_state=#ps_body{
963 length = BodyLength,
964 transfer_decode_fun = TDecodeFun,
965 transfer_decode_state = TDecodeState
966 }};
967 false ->
968 State0#state{in_streamid=StreamID + 1, in_state=ps_next_request}
969 end,
970 {request, Req, State#state{buffer=Buffer}};
971 {true, HTTP2Settings} ->
972 %% We save the headers in case the upgrade will fail
973 %% and we need to pass them to cowboy_stream:early_error.
974 http2_upgrade(State0#state{in_state=PS#ps_header{headers=Headers}},
975 Buffer, HTTP2Settings, Req)
976 end.
977
978 %% HTTP/2 upgrade.
979
980 is_http2_upgrade(#{<<"connection">> := Conn, <<"upgrade">> := Upgrade,
981 <<"http2-settings">> := HTTP2Settings}, 'HTTP/1.1', Opts) ->
982 Conns = cow_http_hd:parse_connection(Conn),
983 case lists:member(<<"upgrade">>, Conns)
984 andalso lists:member(<<"http2-settings">>, Conns)
985 andalso lists:member(http2, maps:get(protocols, Opts, [http2, http])) of
986 true ->
987 try cow_http_hd:parse_upgrade(Upgrade) of
988 Protocols ->
989 case lists:member(<<"h2c">>, Protocols) of
990 true ->
991 {true, HTTP2Settings};
992 false ->
993 false
994 end
995 catch _:_ ->
996 false
997 end;
998 _ ->
999 false
1000 end;
1001 is_http2_upgrade(_, _, _) ->
1002 false.
1003
1004 %% Prior knowledge upgrade, without an HTTP/1.1 request.
1005 http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
1006 proxy_header=ProxyHeader, peer=Peer, sock=Sock, cert=Cert}, Buffer) ->
1007 case Transport:secure() of
1008 false ->
1009 _ = cancel_timeout(State),
1010 cowboy_http2:init(Parent, Ref, Socket, Transport, ProxyHeader,
1011 opts_for_upgrade(State), Peer, Sock, Cert, Buffer);
1012 true ->
1013 error_terminate(400, State, {connection_error, protocol_error,
1014 'Clients that support HTTP/2 over TLS MUST use ALPN. (RFC7540 3.4)'})
1015 end.
1016
1017 %% Upgrade via an HTTP/1.1 request.
1018 http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
1019 proxy_header=ProxyHeader, peer=Peer, sock=Sock, cert=Cert},
1020 Buffer, HTTP2Settings, Req) ->
1021 case Transport:secure() of
1022 false ->
1023 %% @todo
1024 %% However if the client sent a body, we need to read the body in full
1025 %% and if we can't do that, return a 413 response. Some options are in order.
1026 %% Always half-closed stream coming from this side.
1027 try cow_http_hd:parse_http2_settings(HTTP2Settings) of
1028 Settings ->
1029 _ = cancel_timeout(State),
1030 cowboy_http2:init(Parent, Ref, Socket, Transport, ProxyHeader,
1031 opts_for_upgrade(State), Peer, Sock, Cert, Buffer, Settings, Req)
1032 catch _:_ ->
1033 error_terminate(400, State, {connection_error, protocol_error,
1034 'The HTTP2-Settings header must contain a base64 SETTINGS payload. (RFC7540 3.2, RFC7540 3.2.1)'})
1035 end;
1036 true ->
1037 error_terminate(400, State, {connection_error, protocol_error,
1038 'Clients that support HTTP/2 over TLS MUST use ALPN. (RFC7540 3.4)'})
1039 end.
1040
1041 opts_for_upgrade(#state{opts=Opts, dynamic_buffer_size=false}) ->
1042 Opts;
1043 opts_for_upgrade(#state{opts=Opts, dynamic_buffer_size=Size,
1044 dynamic_buffer_moving_average=MovingAvg}) ->
1045 Opts#{
1046 dynamic_buffer_initial_average => MovingAvg,
1047 dynamic_buffer_initial_size => Size
1048 }.
1049
1050 %% Request body parsing.
1051
1052 parse_body(Buffer, State=#state{in_streamid=StreamID, in_state=
1053 PS=#ps_body{received=Received, transfer_decode_fun=TDecode,
1054 transfer_decode_state=TState0}}) ->
1055 try TDecode(Buffer, TState0) of
1056 more ->
1057 {more, State#state{buffer=Buffer}};
1058 {more, Data, TState} ->
1059 {data, nofin, Data, State#state{buffer= <<>>,
1060 in_state=PS#ps_body{received=Received + byte_size(Data),
1061 transfer_decode_state=TState}}};
1062 {more, Data, _Length, TState} when is_integer(_Length) ->
1063 {data, nofin, Data, State#state{buffer= <<>>,
1064 in_state=PS#ps_body{received=Received + byte_size(Data),
1065 transfer_decode_state=TState}}};
1066 {more, Data, Rest, TState} ->
1067 {data, nofin, Data, State#state{buffer=Rest,
1068 in_state=PS#ps_body{received=Received + byte_size(Data),
1069 transfer_decode_state=TState}}};
1070 {done, no_trailers, Rest} ->
1071 {data, fin, <<>>, State#state{
1072 buffer=Rest,
1073 in_streamid=StreamID + 1,
1074 in_state=ps_next_request
1075 }};
1076 {done, trailers, Rest} ->
1077 {data, fin, <<>>, State#state{
1078 buffer=Rest,
1079 in_state=#ps_trailer{}
1080 }};
1081 {done, Data, no_trailers, Rest} ->
1082 {data, fin, Data, State#state{
1083 buffer=Rest,
1084 in_streamid=StreamID + 1,
1085 in_state=ps_next_request
1086 }};
1087 {done, Data, trailers, Rest} ->
1088 {data, fin, Data, State#state{
1089 buffer=Rest,
1090 in_state=#ps_trailer{}
1091 }}
1092 catch _:_ ->
1093 Reason = {connection_error, protocol_error,
1094 'Failure to decode the content. (RFC7230 4)'},
1095 terminate(stream_terminate(State, Reason), Reason)
1096 end.
1097
1098 %% Trailer field values.
1099
1100 %% @todo Proper trailers.
1101 parse_trailer(Buffer, State=#state{in_streamid=StreamID, stream=Stream}) ->
1102 case binary:split(Buffer, <<"\r\n\r\n">>) of
1103 [_] when byte_size(Buffer) >= 4096 ->
1104 Reason = {connection_error, limit_reached,
1105 'Trailer field values larger than hard limit allows.'},
1106 case Stream of
1107 #stream{} ->
1108 terminate(stream_terminate(State, Reason), Reason);
1109 %% Stream already terminated.
1110 undefined ->
1111 terminate(State, Reason)
1112 end;
1113 [_] ->
1114 {more, State#state{buffer=Buffer}};
1115 [_, Rest] ->
1116 parse(Rest, State#state{
1117 in_streamid=StreamID + 1,
1118 in_state=ps_next_request
1119 })
1120 end.
1121
1122 %% Message handling.
1123
1124 down(State=#state{opts=Opts, children=Children0}, Pid, Msg) ->
1125 case cowboy_children:down(Children0, Pid) of
1126 %% The stream was terminated already.
1127 {ok, undefined, Children} ->
1128 State#state{children=Children};
1129 %% The stream is still running.
1130 {ok, StreamID, Children} ->
1131 info(State#state{children=Children}, StreamID, Msg);
1132 %% The process was unknown.
1133 error ->
1134 cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n",
1135 [Msg, Pid], Opts),
1136 State
1137 end.
1138
1139 info(State=#state{opts=Opts, stream=Stream0=#stream{id=StreamID, state=StreamState0}},
1140 StreamID, Msg) ->
1141 try cowboy_stream:info(StreamID, Msg, StreamState0) of
1142 {Commands, StreamState} ->
1143 Stream = Stream0#stream{state=StreamState},
1144 commands(State#state{stream=Stream}, Commands)
1145 catch Class:Exception:Stacktrace ->
1146 cowboy:log(cowboy_stream:make_error_log(info,
1147 [StreamID, Msg, StreamState0],
1148 Class, Exception, Stacktrace), Opts),
1149 stream_terminate(State, {internal_error, {Class, Exception},
1150 'Unhandled exception in cowboy_stream:info/3.'})
1151 end;
1152 info(State=#state{opts=Opts}, StreamID, Msg) ->
1153 cowboy:log(warning, "Received message ~p for unknown stream ~p.~n",
1154 [Msg, StreamID], Opts),
1155 State.
1156
1157 %% Commands.
1158 %%
1159 %% The order in which the commands are given matters. Cowboy may
1160 %% stop processing commands after the 'stop' command or when an
1161 %% error occurred, such as a socket error. Critical commands such
1162 %% as 'spawn' should always be given first.
1163
1164 commands(State, []) ->
1165 State;
1166 %% Supervise a child process.
1167 commands(State=#state{stream=#stream{id=StreamID}, children=Children0},
1168 [{spawn, Pid, Shutdown}|Tail]) ->
1169 Children = cowboy_children:up(Children0, Pid, StreamID, Shutdown),
1170 commands(State#state{children=Children}, Tail);
1171 %% Error handling.
1172 commands(State, [Error = {internal_error, _, _}|Tail]) ->
1173 commands(stream_terminate(State, Error), Tail);
1174 %% When we have finished reading the request body, do nothing.
1175 commands(State=#state{flow=infinity}, [{flow, _}|Tail]) ->
1176 commands(State, Tail);
1177 %% Read the request body.
1178 commands(State0=#state{flow=Flow0}, [{flow, Size}|Tail]) ->
1179 %% We must read *at least* Size of data otherwise functions
1180 %% like cowboy_req:read_body/1,2 will wait indefinitely.
1181 Flow = if
1182 Flow0 < 0 -> Size;
1183 true -> Flow0 + Size
1184 end,
1185 %% Reenable active mode if necessary.
1186 State = if
1187 Flow0 =< 0, Flow > 0 ->
1188 active(State0);
1189 true ->
1190 State0
1191 end,
1192 commands(State#state{flow=Flow}, Tail);
1193 %% Error responses are sent only if a response wasn't sent already.
1194 commands(State=#state{out_state=wait},
1195 [{error_response, Status, Headers0, Body}|Tail]) ->
1196 %% We close the connection when the error response is 408, as it
1197 %% indicates a timeout and the RFC recommends that we stop here. (RFC7231 6.5.7)
1198 Headers = case Status of
1199 408 -> Headers0#{<<"connection">> => <<"close">>};
1200 <<"408", _/bits>> -> Headers0#{<<"connection">> => <<"close">>};
1201 _ -> Headers0
1202 end,
1203 commands(State, [{response, Status, Headers, Body}|Tail]);
1204 commands(State, [{error_response, _, _, _}|Tail]) ->
1205 commands(State, Tail);
1206 %% Send an informational response.
1207 commands(State0=#state{socket=Socket, transport=Transport, out_state=wait,
1208 stream=#stream{version=Version}},
1209 [{inform, StatusCode, Headers}|Tail]) ->
1210 case maybe_invalid_response_headers(Headers, State0) of
1211 error_terminate ->
1212 Reason = {internal_error, invalid_response_header,
1213 'An invalid response header was detected in an informational response.'},
1214 terminate(stream_terminate(State0, Reason), Reason);
1215 ok ->
1216 ok
1217 end,
1218 _ = case Version of
1219 'HTTP/1.1' ->
1220 ok = maybe_socket_error(State0, Transport:send(Socket,
1221 cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers))));
1222 %% Do not send informational responses to HTTP/1.0 clients. (RFC7231 6.2)
1223 'HTTP/1.0' ->
1224 ok
1225 end,
1226 State = maybe_reset_idle_timeout(State0),
1227 commands(State, Tail);
1228 %% Send a full response.
1229 %%
1230 %% @todo Kill the stream if it sent a response when one has already been sent.
1231 %% @todo Keep IsFin in the state.
1232 %% @todo Same two things above apply to DATA, possibly promise too.
1233 commands(State0=#state{socket=Socket, transport=Transport, out_state=wait},
1234 [{response, StatusCode, Headers0, Body}|Tail]) ->
1235 case maybe_invalid_response_headers(Headers0, State0) of
1236 error_terminate ->
1237 Reason = {internal_error, invalid_response_header,
1238 'An invalid response header was detected.'},
1239 terminate(stream_terminate(State0, Reason), Reason);
1240 ok ->
1241 ok
1242 end,
1243 {State1, Headers} = connection(State0, Headers0),
1244 State2 = State1#state{out_state=done},
1245 %% @todo Ensure content-length is set. 204 must never have content-length set.
1246 Response = cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers)),
1247 %% @todo 204 and 304 responses must not include a response body. (RFC7230 3.3.1, RFC7230 3.3.2)
1248 case Body of
1249 {sendfile, _, _, _} ->
1250 ok = maybe_socket_error(State2, Transport:send(Socket, Response)),
1251 sendfile(State2, Body);
1252 _ ->
1253 ok = maybe_socket_error(State2, Transport:send(Socket, [Response, Body]))
1254 end,
1255 State = maybe_reset_idle_timeout(State2),
1256 commands(State, Tail);
1257 %% Send response headers and initiate chunked encoding or streaming.
1258 commands(State0=#state{socket=Socket, transport=Transport,
1259 opts=Opts, overriden_opts=Override, stream=Stream0},
1260 [{headers, StatusCode, Headers0}|Tail]) ->
1261 case maybe_invalid_response_headers(Headers0, State0) of
1262 error_terminate ->
1263 Reason = {internal_error, invalid_response_header,
1264 'An invalid response header was detected.'},
1265 terminate(stream_terminate(State0, Reason), Reason);
1266 ok ->
1267 ok
1268 end,
1269 #stream{id=StreamID, version=Version} = Stream0,
1270 Status = cow_http:status_to_integer(StatusCode),
1271 ContentLength = maps:get(<<"content-length">>, Headers0, undefined),
1272 %% Chunked transfer-encoding can be disabled on a per-request basis.
1273 Chunked = case Override of
1274 #{chunked := Chunked0} -> Chunked0;
1275 _ -> maps:get(chunked, Opts, true)
1276 end,
1277 {State1, Headers1} = case {Status, ContentLength, Version} of
1278 {204, _, 'HTTP/1.1'} ->
1279 {State0#state{out_state=done}, Headers0};
1280 {304, _, 'HTTP/1.1'} ->
1281 {State0#state{out_state=done}, Headers0};
1282 {_, undefined, 'HTTP/1.1'} when Chunked ->
1283 {State0#state{out_state=chunked}, Headers0#{<<"transfer-encoding">> => <<"chunked">>}};
1284 %% Close the connection after streaming without content-length
1285 %% to all HTTP/1.0 clients and to HTTP/1.1 clients when chunked is disabled.
1286 {_, undefined, _} ->
1287 {State0#state{out_state=streaming, last_streamid=StreamID}, Headers0};
1288 %% Stream the response body without chunked transfer-encoding.
1289 _ ->
1290 ExpectedSize = cow_http_hd:parse_content_length(ContentLength),
1291 Stream = Stream0#stream{local_expected_size=ExpectedSize},
1292 {State0#state{out_state=streaming, stream=Stream}, Headers0}
1293 end,
1294 Headers2 = case stream_te(State1) of
1295 trailers -> Headers1;
1296 _ -> maps:remove(<<"trailer">>, Headers1)
1297 end,
1298 {State2, Headers} = connection(State1, Headers2),
1299 ok = maybe_socket_error(State2, Transport:send(Socket,
1300 cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers)))),
1301 State = maybe_reset_idle_timeout(State2),
1302 commands(State, Tail);
1303 %% Send a response body chunk.
1304 %% @todo We need to kill the stream if it tries to send data before headers.
1305 commands(State0=#state{socket=Socket, transport=Transport, stream=Stream0=#stream{method=Method}, out_state=OutState},
1306 [{data, IsFin, Data}|Tail]) ->
1307 %% Do not send anything when the user asks to send an empty
1308 %% data frame, as that would break the protocol.
1309 Size = case Data of
1310 {sendfile, _, B, _} -> B;
1311 _ -> iolist_size(Data)
1312 end,
1313 %% Depending on the current state we may need to send nothing,
1314 %% the last chunk, chunked data with/without the last chunk,
1315 %% or just the data as-is.
1316 Stream = if
1317 Method =:= <<"HEAD">> ->
1318 Stream0;
1319 Size =:= 0, IsFin =:= fin, OutState =:= chunked ->
1320 ok = maybe_socket_error(State0,
1321 Transport:send(Socket, <<"0\r\n\r\n">>)),
1322 Stream0;
1323 Size =:= 0 ->
1324 Stream0;
1325 is_tuple(Data), OutState =:= chunked ->
1326 ok = maybe_socket_error(State0,
1327 Transport:send(Socket, [integer_to_binary(Size, 16), <<"\r\n">>])),
1328 sendfile(State0, Data),
1329 ok = maybe_socket_error(State0,
1330 Transport:send(Socket,
1331 case IsFin of
1332 fin -> <<"\r\n0\r\n\r\n">>;
1333 nofin -> <<"\r\n">>
1334 end)
1335 ),
1336 Stream0;
1337 OutState =:= chunked ->
1338 ok = maybe_socket_error(State0,
1339 Transport:send(Socket, [
1340 integer_to_binary(Size, 16), <<"\r\n">>, Data,
1341 case IsFin of
1342 fin -> <<"\r\n0\r\n\r\n">>;
1343 nofin -> <<"\r\n">>
1344 end
1345 ])
1346 ),
1347 Stream0;
1348 OutState =:= streaming ->
1349 #stream{local_sent_size=SentSize0, local_expected_size=ExpectedSize} = Stream0,
1350 SentSize = SentSize0 + Size,
1351 if
1352 %% ExpectedSize may be undefined, which is > any integer value.
1353 SentSize > ExpectedSize ->
1354 terminate(State0, response_body_too_large);
1355 is_tuple(Data) ->
1356 sendfile(State0, Data);
1357 true ->
1358 ok = maybe_socket_error(State0, Transport:send(Socket, Data))
1359 end,
1360 Stream0#stream{local_sent_size=SentSize}
1361 end,
1362 State1 = case IsFin of
1363 fin -> State0#state{out_state=done};
1364 nofin -> State0
1365 end,
1366 State = maybe_reset_idle_timeout(State1),
1367 commands(State#state{stream=Stream}, Tail);
1368 commands(State0=#state{socket=Socket, transport=Transport},
1369 [{trailers, Trailers}|Tail]) ->
1370 case maybe_invalid_response_headers(Trailers, State0) of
1371 error_terminate ->
1372 %% When there are invalid trailer headers the only thing
1373 %% we can do is drop the connection.
1374 Reason = {internal_error, invalid_response_header,
1375 'An invalid response header was detected in trailers.'},
1376 terminate(State0, Reason);
1377 ok ->
1378 ok
1379 end,
1380 case stream_te(State0) of
1381 trailers ->
1382 ok = maybe_socket_error(State0,
1383 Transport:send(Socket, [
1384 <<"0\r\n">>,
1385 cow_http:headers(maps:to_list(Trailers)),
1386 <<"\r\n">>
1387 ])
1388 );
1389 no_trailers ->
1390 ok = maybe_socket_error(State0,
1391 Transport:send(Socket, <<"0\r\n\r\n">>));
1392 not_chunked ->
1393 ok
1394 end,
1395 State = maybe_reset_idle_timeout(State0#state{out_state=done}),
1396 commands(State, Tail);
1397 %% Protocol takeover.
1398 commands(State0=#state{ref=Ref, parent=Parent, socket=Socket, transport=Transport,
1399 out_state=OutState, buffer=Buffer, stream=Stream0, children=Children},
1400 [{switch_protocol, Headers, Protocol, InitialState}|_Tail]) ->
1401 case maybe_invalid_response_headers(Headers, State0) of
1402 error_terminate ->
1403 Reason = {internal_error, invalid_response_header,
1404 'An invalid response header was detected when switching protocol.'},
1405 terminate(stream_terminate(State0, Reason), Reason);
1406 ok ->
1407 ok
1408 end,
1409 State1 = cancel_timeout(State0),
1410 %% Before we send the 101 response we need to stop receiving data
1411 %% from the socket, otherwise the data might be receive before the
1412 %% call to flush/0 and we end up inadvertently dropping a packet.
1413 %%
1414 %% @todo Handle cases where the request came with a body. We need
1415 %% to process or skip the body before the upgrade can be completed.
1416 State = passive(State1),
1417 %% Send a 101 response if necessary, then terminate the stream.
1418 #stream{id=StreamID} = Stream0,
1419 #state{stream=Stream} = case OutState of
1420 wait -> info(State, StreamID, {inform, 101, Headers});
1421 _ -> State
1422 end,
1423 #stream{state=StreamState} = Stream,
1424 stream_call_terminate(StreamID, switch_protocol, StreamState, State),
1425 %% Terminate children processes and flush any remaining messages from the mailbox.
1426 cowboy_children:terminate(Children),
1427 flush(Parent),
1428 %% Turn off the trap_exit process flag
1429 %% since this process will no longer be a supervisor.
1430 process_flag(trap_exit, false),
1431 Protocol:takeover(Parent, Ref, Socket, Transport,
1432 opts_for_upgrade(State), Buffer, InitialState);
1433 %% Set options dynamically.
1434 commands(State0, [{set_options, SetOpts}|Tail]) ->
1435 State = maps:fold(fun
1436 (chunked, Chunked, StateF=#state{overriden_opts=Opts}) ->
1437 StateF#state{overriden_opts=Opts#{chunked => Chunked}};
1438 (idle_timeout, IdleTimeout, StateF=#state{overriden_opts=Opts}) ->
1439 set_timeout(StateF#state{overriden_opts=Opts#{idle_timeout => IdleTimeout}},
1440 idle_timeout);
1441 (_, _, StateF) ->
1442 StateF
1443 end, State0, SetOpts),
1444 commands(State, Tail);
1445 %% Stream shutdown.
1446 commands(State, [stop|_Tail]) ->
1447 %% @todo Do we want to run the commands after a stop?
1448 %% @todo We currently wait for the stop command before we
1449 %% continue with the next request/response. In theory, if
1450 %% the request body was read fully and the response body
1451 %% was sent fully we should be able to start working on
1452 %% the next request concurrently. This can be done as a
1453 %% future optimization.
1454 maybe_terminate(State);
1455 %% Log event.
1456 commands(State=#state{opts=Opts}, [Log={log, _, _, _}|Tail]) ->
1457 cowboy:log(Log, Opts),
1458 commands(State, Tail);
1459 %% HTTP/1.1 does not support push; ignore.
1460 commands(State, [{push, _, _, _, _, _, _, _}|Tail]) ->
1461 commands(State, Tail).
1462
1463 maybe_invalid_response_headers(Headers, #state{opts=Opts}) ->
1464 validate_response_headers(Headers, Opts).
1465
1466 -spec validate_response_headers(cowboy:http_headers(),
1467 #{invalid_response_headers => error_terminate | ignore})
1468 -> ok | error_terminate.
1469
1470 %% @todo This function is common to all HTTP versions.
1471
1472 validate_response_headers(Headers, Opts) ->
1473 case maps:get(invalid_response_headers, Opts, error_terminate) of
1474 error_terminate ->
1475 It = maps:iterator(Headers),
1476 validate_response_headers(maps:next(It));
1477 ignore ->
1478 ok
1479 end.
1480
1481 validate_response_headers({_, V, It}) when is_binary(V) ->
1482 case binary:match(V, [<<$\r>>, <<$\n>>]) of
1483 nomatch ->
1484 validate_response_headers(maps:next(It));
1485 _ ->
1486 error_terminate
1487 end;
1488 validate_response_headers({K, V, It}) ->
1489 %% We build a temporary binary for simplicity's sake
1490 %% when we have a list/iolist.
1491 validate_response_headers({K, iolist_to_binary(V), It});
1492 validate_response_headers(none) ->
1493 ok.
1494
1495 %% The set-cookie header is special; we can only send one cookie per header.
1496 headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
1497 Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
1498 Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
1499 headers_to_list(Headers) ->
1500 maps:to_list(Headers).
1501
1502 sendfile(State=#state{socket=Socket, transport=Transport, opts=Opts},
1503 {sendfile, Offset, Bytes, Path}) ->
1504 %% When sendfile is disabled we explicitly use the fallback.
1505 {ok, _} = maybe_socket_error(State,
1506 case maps:get(sendfile, Opts, true) of
1507 true -> Transport:sendfile(Socket, Path, Offset, Bytes);
1508 false -> ranch_transport:sendfile(Transport, Socket, Path, Offset, Bytes, [])
1509 end
1510 ),
1511 ok.
1512
1513 %% Flush messages specific to cowboy_http before handing over the
1514 %% connection to another protocol.
1515 flush(Parent) ->
1516 receive
1517 {timeout, _, _} ->
1518 flush(Parent);
1519 {{Pid, _}, _} when Pid =:= self() ->
1520 flush(Parent);
1521 {'EXIT', Pid, _} when Pid =/= Parent ->
1522 flush(Parent)
1523 after 0 ->
1524 ok
1525 end.
1526
1527 maybe_terminate(State=#state{last_streamid=StreamID, stream=#stream{id=StreamID}}) ->
1528 terminate(stream_terminate(State, normal), normal); %% @todo Reason ok?
1529 maybe_terminate(State) ->
1530 stream_terminate(State, normal).
1531
1532 stream_terminate(State0=#state{opts=Opts, active=Active,
1533 in_state=InState, out_state=OutState, stream=Stream0,
1534 children=Children0}, Reason) ->
1535 #stream{
1536 id=StreamID,
1537 version=Version,
1538 local_expected_size=ExpectedSize,
1539 local_sent_size=SentSize
1540 } = Stream0,
1541 %% Send a response or terminate chunks depending on the current output state.
1542 State1 = #state{stream=Stream} = case OutState of
1543 wait when element(1, Reason) =:= internal_error ->
1544 info(State0, StreamID, {response, 500, #{<<"content-length">> => <<"0">>}, <<>>});
1545 wait when element(1, Reason) =:= connection_error ->
1546 info(State0, StreamID, {response, 400, #{<<"content-length">> => <<"0">>}, <<>>});
1547 wait ->
1548 info(State0, StreamID, {response, 204, #{}, <<>>});
1549 chunked when Version =:= 'HTTP/1.1' ->
1550 info(State0, StreamID, {data, fin, <<>>});
1551 streaming when SentSize < ExpectedSize ->
1552 terminate(State0, response_body_too_small);
1553 _ -> %% done or Version =:= 'HTTP/1.0'
1554 State0
1555 end,
1556 %% Stop the stream, shutdown children and reset overriden options.
1557 #stream{state=StreamState} = Stream,
1558 stream_call_terminate(StreamID, Reason, StreamState, State1),
1559 Children = cowboy_children:shutdown(Children0, StreamID),
1560 State = State1#state{overriden_opts=#{}, stream=undefined, children=Children},
1561 %% We want to drop the connection if the body was not read fully
1562 %% and we don't know its length or more remains to be read than
1563 %% configuration allows.
1564 MaxSkipBodyLength = maps:get(max_skip_body_length, Opts, 1000000),
1565 case InState of
1566 #ps_body{length=undefined} ->
1567 terminate(State, skip_body_unknown_length);
1568 #ps_body{length=Len, received=Received}
1569 when Received + MaxSkipBodyLength < Len ->
1570 terminate(State, skip_body_too_large);
1571 _ ->
1572 %% Enable active mode again if it was disabled.
1573 StateN = case Active of
1574 true -> State;
1575 false -> active(State)
1576 end,
1577 StateN#state{out_state=wait, flow=infinity}
1578 end.
1579
1580 stream_call_terminate(StreamID, Reason, StreamState, #state{opts=Opts}) ->
1581 try
1582 cowboy_stream:terminate(StreamID, Reason, StreamState)
1583 catch Class:Exception:Stacktrace ->
1584 cowboy:log(cowboy_stream:make_error_log(terminate,
1585 [StreamID, Reason, StreamState],
1586 Class, Exception, Stacktrace), Opts)
1587 end.
1588
1589 maybe_req_close(#state{opts=#{http10_keepalive := false}}, _, 'HTTP/1.0') ->
1590 close;
1591 maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.0') ->
1592 try cow_http_hd:parse_connection(Conn) of
1593 Conns ->
1594 case lists:member(<<"keep-alive">>, Conns) of
1595 true -> keepalive;
1596 false -> close
1597 end
1598 catch _:_ ->
1599 bad_connection_header
1600 end;
1601 maybe_req_close(_, _, 'HTTP/1.0') ->
1602 close;
1603 maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.1') ->
1604 try connection_hd_is_close(Conn) of
1605 true -> close;
1606 false -> keepalive
1607 catch _:_ ->
1608 bad_connection_header
1609 end;
1610 maybe_req_close(_, _, _) ->
1611 keepalive.
1612
1613 connection(State=#state{last_streamid=StreamID, stream=#stream{id=StreamID}},
1614 Headers=#{<<"connection">> := Conn}) ->
1615 case connection_hd_is_close(Conn) of
1616 true -> {State, Headers};
1617 %% @todo Here we need to remove keep-alive and add close, not just add close.
1618 false -> {State, Headers#{<<"connection">> => [<<"close, ">>, Conn]}}
1619 end;
1620 connection(State=#state{last_streamid=StreamID, stream=#stream{id=StreamID}},
1621 Headers) ->
1622 {State, Headers#{<<"connection">> => <<"close">>}};
1623 connection(State=#state{stream=#stream{id=StreamID}},
1624 Headers=#{<<"connection">> := Conn}) ->
1625 case connection_hd_is_close(Conn) of
1626 true -> {State#state{last_streamid=StreamID}, Headers};
1627 %% @todo Here we need to set keep-alive only if it wasn't set before.
1628 false -> {State, Headers}
1629 end;
1630 connection(State=#state{stream=#stream{version='HTTP/1.0'}}, Headers) ->
1631 {State, Headers#{<<"connection">> => <<"keep-alive">>}};
1632 connection(State, Headers) ->
1633 {State, Headers}.
1634
1635 connection_hd_is_close(Conn) ->
1636 Conns = cow_http_hd:parse_connection(iolist_to_binary(Conn)),
1637 lists:member(<<"close">>, Conns).
1638
1639 stream_te(#state{out_state=streaming}) ->
1640 not_chunked;
1641 %% No TE header was sent.
1642 stream_te(#state{stream=#stream{te=undefined}}) ->
1643 no_trailers;
1644 stream_te(#state{stream=#stream{te=TE0}}) ->
1645 try cow_http_hd:parse_te(TE0) of
1646 {TE1, _} -> TE1
1647 catch _:_ ->
1648 %% If we can't parse the TE header, assume we can't send trailers.
1649 no_trailers
1650 end.
1651
1652 %% This function is only called when an error occurs on a new stream.
1653 -spec error_terminate(cowboy:http_status(), #state{}, _) -> no_return().
1654
1655 error_terminate(StatusCode, State=#state{ref=Ref, peer=Peer, in_state=StreamState}, Reason) ->
1656 PartialReq = case StreamState of
1657 #ps_request_line{} -> #{
1658 ref => Ref,
1659 peer => Peer
1660 };
1661 #ps_header{method=Method, path=Path, qs=Qs,
1662 version=Version, headers=ReqHeaders} -> #{
1663 ref => Ref,
1664 peer => Peer,
1665 method => Method,
1666 path => Path,
1667 qs => Qs,
1668 version => Version,
1669 headers => case ReqHeaders of
1670 undefined -> #{};
1671 _ -> ReqHeaders
1672 end
1673 }
1674 end,
1675 early_error(StatusCode, State, Reason, PartialReq, #{<<"connection">> => <<"close">>}),
1676 terminate(State, Reason).
1677
1678 early_error(StatusCode, State, Reason, PartialReq) ->
1679 early_error(StatusCode, State, Reason, PartialReq, #{}).
1680
1681 early_error(StatusCode, State=#state{opts=Opts, in_streamid=StreamID},
1682 Reason, PartialReq, RespHeaders0) ->
1683 RespHeaders1 = RespHeaders0#{<<"content-length">> => <<"0">>},
1684 Resp0 = {response, StatusCode, RespHeaders1, <<>>},
1685 try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp0, Opts) of
1686 Resp = {response, _, RespHeaders, _} ->
1687 case maybe_invalid_response_headers(RespHeaders, State) of
1688 error_terminate ->
1689 %% We still need to send an error response, so send what we
1690 %% initially wanted to send. It's better than nothing.
1691 early_error_resp(Resp0, State),
1692 Reason1 = {internal_error, invalid_response_header,
1693 'An invalid response header was detected.'},
1694 terminate(State, Reason1);
1695 ok ->
1696 ok
1697 end,
1698 %% @todo We shouldn't send the body when the method is HEAD.
1699 %% @todo Technically we allow the sendfile tuple.
1700 early_error_resp(Resp, State)
1701 catch Class:Exception:Stacktrace ->
1702 cowboy:log(cowboy_stream:make_error_log(early_error,
1703 [StreamID, Reason, PartialReq, Resp0, Opts],
1704 Class, Exception, Stacktrace), Opts),
1705 %% We still need to send an error response, so send what we
1706 %% initially wanted to send. It's better than nothing.
1707 early_error_resp(Resp0, State)
1708 end.
1709
1710 early_error_resp({response, StatusCode, RespHeaders, RespBody},
1711 State=#state{socket=Socket, transport=Transport}) ->
1712 ok = maybe_socket_error(State,
1713 Transport:send(Socket, [
1714 cow_http:response(StatusCode, 'HTTP/1.1', maps:to_list(RespHeaders)),
1715 RespBody
1716 ])
1717 ).
1718
1719 initiate_closing(State=#state{stream=undefined}, Reason) ->
1720 terminate(State, Reason);
1721 initiate_closing(State=#state{stream=#stream{id=LastStreamID}}, _Reason) ->
1722 State#state{last_streamid=LastStreamID}.
1723
1724 %% Function replicated in cowboy_http2.
1725 maybe_socket_error(State, {error, closed}) ->
1726 terminate(State, {socket_error, closed, 'The socket has been closed.'});
1727 maybe_socket_error(State, Reason) ->
1728 maybe_socket_error(State, Reason, 'An error has occurred on the socket.').
1729
1730 maybe_socket_error(_, Result = ok, _) ->
1731 Result;
1732 maybe_socket_error(_, Result = {ok, _}, _) ->
1733 Result;
1734 maybe_socket_error(State, {error, Reason}, Human) ->
1735 terminate(State, {socket_error, Reason, Human}).
1736
1737 -spec terminate(#state{} | undefined, _) -> no_return().
1738
1739 terminate(undefined, Reason) ->
1740 exit({shutdown, Reason});
1741 terminate(State=#state{children=Children}, Reason) ->
1742 terminate_last_stream(State, Reason),
1743 cowboy_children:terminate(Children),
1744 terminate_linger(State),
1745 exit({shutdown, Reason}).
1746
1747 terminate_last_stream(#state{stream=undefined}, _) ->
1748 ok;
1749 terminate_last_stream(State=#state{stream=#stream{id=StreamID, state=StreamState}}, Reason) ->
1750 stream_call_terminate(StreamID, Reason, StreamState, State),
1751 ok.
1752
1753 terminate_linger(State=#state{socket=Socket, transport=Transport, opts=Opts}) ->
1754 case Transport:shutdown(Socket, write) of
1755 ok ->
1756 case maps:get(linger_timeout, Opts, 1000) of
1757 0 ->
1758 ok;
1759 infinity ->
1760 terminate_linger_before_loop(State, undefined, Transport:messages());
1761 Timeout ->
1762 TimerRef = erlang:start_timer(Timeout, self(), linger_timeout),
1763 terminate_linger_before_loop(State, TimerRef, Transport:messages())
1764 end;
1765 {error, _} ->
1766 ok
1767 end.
1768
1769 terminate_linger_before_loop(State, TimerRef, Messages) ->
1770 %% We may already be in active mode when we do this
1771 %% but it's OK because we are shutting down anyway.
1772 %%
1773 %% We specially handle the socket error to terminate
1774 %% when an error occurs.
1775 case setopts_active(State) of
1776 ok ->
1777 terminate_linger_loop(State, TimerRef, Messages);
1778 {error, _} ->
1779 ok
1780 end.
1781
1782 terminate_linger_loop(State=#state{socket=Socket}, TimerRef, Messages) ->
1783 receive
1784 {OK, Socket, _} when OK =:= element(1, Messages) ->
1785 terminate_linger_loop(State, TimerRef, Messages);
1786 {Closed, Socket} when Closed =:= element(2, Messages) ->
1787 ok;
1788 {Error, Socket, _} when Error =:= element(3, Messages) ->
1789 ok;
1790 {Passive, Socket} when Passive =:= tcp_passive; Passive =:= ssl_passive ->
1791 terminate_linger_before_loop(State, TimerRef, Messages);
1792 {timeout, TimerRef, linger_timeout} ->
1793 ok;
1794 _ ->
1795 terminate_linger_loop(State, TimerRef, Messages)
1796 end.
1797
1798 %% System callbacks.
1799
1800 -spec system_continue(_, _, #state{}) -> no_return().
1801
1802 system_continue(_, _, State) ->
1803 before_loop(State).
1804
1805 -spec system_terminate(any(), _, _, #state{}) -> no_return().
1806
1807 system_terminate(Reason0, _, _, State) ->
1808 Reason = {stop, {exit, Reason0}, 'sys:terminate/2,3 was called.'},
1809 before_loop(initiate_closing(State, Reason)).
1810
1811 -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
1812
1813 system_code_change(Misc, _, _, _) ->
1814 {ok, Misc}.