Debian Codegraph @

src/cowboy_stream_h.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 -module(cowboy_stream_h).
16 -behavior(cowboy_stream).
17
18 -export([init/3]).
19 -export([data/4]).
20 -export([info/3]).
21 -export([terminate/3]).
22 -export([early_error/5]).
23
24 -export([request_process/3]).
25 -export([resume/5]).
26
27 -record(state, {
28 next :: any(),
29 ref = undefined :: ranch:ref(),
30 pid = undefined :: pid(),
31 expect = undefined :: undefined | continue,
32 read_body_pid = undefined :: pid() | undefined,
33 read_body_ref = undefined :: reference() | undefined,
34 read_body_timer_ref = undefined :: reference() | undefined,
35 read_body_length = 0 :: non_neg_integer() | infinity | auto,
36 read_body_is_fin = nofin :: nofin | {fin, non_neg_integer()},
37 read_body_buffer = <<>> :: binary(),
38 body_length = 0 :: non_neg_integer(),
39 stream_body_pid = undefined :: pid() | undefined,
40 stream_body_status = normal :: normal | blocking | blocked
41 }).
42
43 -spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts())
44 -> {[{spawn, pid(), timeout()}], #state{}}.
45 init(StreamID, Req=#{ref := Ref}, Opts) ->
46 Env = maps:get(env, Opts, #{}),
47 Middlewares = maps:get(middlewares, Opts, [cowboy_router, cowboy_handler]),
48 Shutdown = maps:get(shutdown_timeout, Opts, 5000),
49 Pid = proc_lib:spawn_link(?MODULE, request_process, [Req, Env, Middlewares]),
50 Expect = expect(Req),
51 {Commands, Next} = cowboy_stream:init(StreamID, Req, Opts),
52 {[{spawn, Pid, Shutdown}|Commands],
53 #state{next=Next, ref=Ref, pid=Pid, expect=Expect}}.
54
55 %% Ignore the expect header in HTTP/1.0.
56 expect(#{version := 'HTTP/1.0'}) ->
57 undefined;
58 expect(Req) ->
59 try cowboy_req:parse_header(<<"expect">>, Req) of
60 Expect ->
61 Expect
62 catch _:_ ->
63 undefined
64 end.
65
66 %% If we receive data and stream is waiting for data:
67 %% If we accumulated enough data or IsFin=fin, send it.
68 %% If we are in auto mode, send it and update flow control.
69 %% If not, buffer it.
70 %% If not, buffer it.
71 %%
72 %% We always reset the expect field when we receive data,
73 %% since the client started sending the request body before
74 %% we could send a 100 continue response.
75
76 -spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State)
77 -> {cowboy_stream:commands(), State} when State::#state{}.
78 %% Stream isn't waiting for data.
79 data(StreamID, IsFin, Data, State=#state{
80 read_body_ref=undefined, read_body_buffer=Buffer, body_length=BodyLen}) ->
81 do_data(StreamID, IsFin, Data, [], State#state{
82 expect=undefined,
83 read_body_is_fin=IsFin,
84 read_body_buffer= << Buffer/binary, Data/binary >>,
85 body_length=BodyLen + byte_size(Data)
86 });
87 %% Stream is waiting for data using auto mode.
88 %%
89 %% There is no buffering done in auto mode.
90 data(StreamID, IsFin, Data, State=#state{read_body_pid=Pid, read_body_ref=Ref,
91 read_body_length=auto, body_length=BodyLen}) ->
92 send_request_body(Pid, Ref, IsFin, BodyLen, Data),
93 do_data(StreamID, IsFin, Data, [{flow, byte_size(Data)}], State#state{
94 read_body_ref=undefined,
95 %% @todo This is wrong, it's missing byte_size(Data).
96 body_length=BodyLen
97 });
98 %% Stream is waiting for data but we didn't receive enough to send yet.
99 data(StreamID, IsFin=nofin, Data, State=#state{
100 read_body_length=ReadLen, read_body_buffer=Buffer, body_length=BodyLen})
101 when byte_size(Data) + byte_size(Buffer) < ReadLen ->
102 do_data(StreamID, IsFin, Data, [], State#state{
103 expect=undefined,
104 read_body_buffer= << Buffer/binary, Data/binary >>,
105 body_length=BodyLen + byte_size(Data)
106 });
107 %% Stream is waiting for data and we received enough to send.
108 data(StreamID, IsFin, Data, State=#state{read_body_pid=Pid, read_body_ref=Ref,
109 read_body_timer_ref=TRef, read_body_buffer=Buffer, body_length=BodyLen0}) ->
110 BodyLen = BodyLen0 + byte_size(Data),
111 ok = erlang:cancel_timer(TRef, [{async, true}, {info, false}]),
112 send_request_body(Pid, Ref, IsFin, BodyLen, <<Buffer/binary, Data/binary>>),
113 do_data(StreamID, IsFin, Data, [], State#state{
114 expect=undefined,
115 read_body_ref=undefined,
116 read_body_timer_ref=undefined,
117 read_body_buffer= <<>>,
118 body_length=BodyLen
119 }).
120
121 do_data(StreamID, IsFin, Data, Commands1, State=#state{next=Next0}) ->
122 {Commands2, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0),
123 {Commands1 ++ Commands2, State#state{next=Next}}.
124
125 -spec info(cowboy_stream:streamid(), any(), State)
126 -> {cowboy_stream:commands(), State} when State::#state{}.
127 info(StreamID, Info={'EXIT', Pid, normal}, State=#state{pid=Pid}) ->
128 do_info(StreamID, Info, [stop], State);
129 info(StreamID, Info={'EXIT', Pid, {{request_error, Reason, _HumanReadable}, _}},
130 State=#state{pid=Pid}) ->
131 Status = case Reason of
132 timeout -> 408;
133 payload_too_large -> 413;
134 _ -> 400
135 end,
136 %% @todo Headers? Details in body? Log the crash? More stuff in debug only?
137 do_info(StreamID, Info, [
138 {error_response, Status, #{<<"content-length">> => <<"0">>}, <<>>},
139 stop
140 ], State);
141 info(StreamID, Exit={'EXIT', Pid, Reason}, State=#state{ref=Ref, pid=Pid}) ->
142 Commands0 = [{internal_error, Exit, 'Stream process crashed.'}],
143 Commands = case Reason of
144 normal -> Commands0;
145 shutdown -> Commands0;
146 {shutdown, _} -> Commands0;
147 _ -> [{log, error,
148 "Ranch listener ~p, connection process ~p, stream ~p "
149 "had its request process ~p exit with reason ~0p~n",
150 [Ref, self(), StreamID, Pid, Reason]}
151 |Commands0]
152 end,
153 %% @todo We are trying to send a 500 response before resetting
154 %% the stream. But due to the way the RESET_STREAM frame
155 %% works in QUIC the data may be lost. The problem is
156 %% known and a draft RFC exists at
157 %% https://www.ietf.org/id/draft-ietf-quic-reliable-stream-reset-03.html
158 do_info(StreamID, Exit, [
159 {error_response, 500, #{<<"content-length">> => <<"0">>}, <<>>}
160 |Commands], State);
161 %% Request body, auto mode, no body buffered.
162 info(StreamID, Info={read_body, Pid, Ref, auto, infinity}, State=#state{read_body_buffer= <<>>}) ->
163 do_info(StreamID, Info, [], State#state{
164 read_body_pid=Pid,
165 read_body_ref=Ref,
166 read_body_length=auto
167 });
168 %% Request body, auto mode, body buffered or complete.
169 info(StreamID, Info={read_body, Pid, Ref, auto, infinity}, State=#state{
170 read_body_is_fin=IsFin, read_body_buffer=Buffer, body_length=BodyLen}) ->
171 send_request_body(Pid, Ref, IsFin, BodyLen, Buffer),
172 do_info(StreamID, Info, [{flow, byte_size(Buffer)}],
173 State#state{read_body_buffer= <<>>});
174 %% Request body, body buffered large enough or complete.
175 %%
176 %% We do not send a 100 continue response if the client
177 %% already started sending the body.
178 info(StreamID, Info={read_body, Pid, Ref, Length, _}, State=#state{
179 read_body_is_fin=IsFin, read_body_buffer=Buffer, body_length=BodyLen})
180 when IsFin =:= fin; byte_size(Buffer) >= Length ->
181 send_request_body(Pid, Ref, IsFin, BodyLen, Buffer),
182 do_info(StreamID, Info, [], State#state{read_body_buffer= <<>>});
183 %% Request body, not enough to send yet.
184 info(StreamID, Info={read_body, Pid, Ref, Length, Period}, State=#state{expect=Expect}) ->
185 Commands = case Expect of
186 continue -> [{inform, 100, #{}}, {flow, Length}];
187 undefined -> [{flow, Length}]
188 end,
189 TRef = erlang:send_after(Period, self(), {{self(), StreamID}, {read_body_timeout, Ref}}),
190 do_info(StreamID, Info, Commands, State#state{
191 read_body_pid=Pid,
192 read_body_ref=Ref,
193 read_body_timer_ref=TRef,
194 read_body_length=Length
195 });
196 %% Request body reading timeout; send what we got.
197 info(StreamID, Info={read_body_timeout, Ref}, State=#state{read_body_pid=Pid, read_body_ref=Ref,
198 read_body_is_fin=IsFin, read_body_buffer=Buffer, body_length=BodyLen}) ->
199 send_request_body(Pid, Ref, IsFin, BodyLen, Buffer),
200 do_info(StreamID, Info, [], State#state{
201 read_body_ref=undefined,
202 read_body_timer_ref=undefined,
203 read_body_buffer= <<>>
204 });
205 info(StreamID, Info={read_body_timeout, _}, State) ->
206 do_info(StreamID, Info, [], State);
207 %% Response.
208 %%
209 %% We reset the expect field when a 100 continue response
210 %% is sent or when any final response is sent.
211 info(StreamID, Inform={inform, Status, _}, State0) ->
212 State = case cow_http:status_to_integer(Status) of
213 100 -> State0#state{expect=undefined};
214 _ -> State0
215 end,
216 do_info(StreamID, Inform, [Inform], State);
217 info(StreamID, Response={response, _, _, _}, State) ->
218 do_info(StreamID, Response, [Response], State#state{expect=undefined});
219 info(StreamID, Headers={headers, _, _}, State) ->
220 do_info(StreamID, Headers, [Headers], State#state{expect=undefined});
221 %% Sending data involves the data message, the stream_buffer_full alarm
222 %% and the connection_buffer_full alarm. We stop sending acks when an alarm is on.
223 %%
224 %% We only apply backpressure when the message includes a pid. Otherwise
225 %% it is a message from Cowboy, or the user circumventing the backpressure.
226 %%
227 %% We currently do not support sending data from multiple processes concurrently.
228 info(StreamID, Data={data, _, _}, State) ->
229 do_info(StreamID, Data, [Data], State);
230 info(StreamID, Data0={data, Pid, _, _}, State0=#state{stream_body_status=Status}) ->
231 State = case Status of
232 normal ->
233 Pid ! {data_ack, self()},
234 State0;
235 blocking ->
236 State0#state{stream_body_pid=Pid, stream_body_status=blocked};
237 blocked ->
238 State0
239 end,
240 Data = erlang:delete_element(2, Data0),
241 do_info(StreamID, Data, [Data], State);
242 info(StreamID, Alarm={alarm, Name, on}, State0=#state{stream_body_status=Status})
243 when Name =:= connection_buffer_full; Name =:= stream_buffer_full ->
244 State = case Status of
245 normal -> State0#state{stream_body_status=blocking};
246 _ -> State0
247 end,
248 do_info(StreamID, Alarm, [], State);
249 info(StreamID, Alarm={alarm, Name, off}, State=#state{stream_body_pid=Pid, stream_body_status=Status})
250 when Name =:= connection_buffer_full; Name =:= stream_buffer_full ->
251 _ = case Status of
252 normal -> ok;
253 blocking -> ok;
254 blocked -> Pid ! {data_ack, self()}
255 end,
256 do_info(StreamID, Alarm, [], State#state{stream_body_pid=undefined, stream_body_status=normal});
257 info(StreamID, Trailers={trailers, _}, State) ->
258 do_info(StreamID, Trailers, [Trailers], State);
259 info(StreamID, Push={push, _, _, _, _, _, _, _}, State) ->
260 do_info(StreamID, Push, [Push], State);
261 info(StreamID, SwitchProtocol={switch_protocol, _, _, _}, State) ->
262 do_info(StreamID, SwitchProtocol, [SwitchProtocol], State#state{expect=undefined});
263 %% Convert the set_options message to a command.
264 info(StreamID, SetOptions={set_options, _}, State) ->
265 do_info(StreamID, SetOptions, [SetOptions], State);
266 %% Unknown message, either stray or meant for a handler down the line.
267 info(StreamID, Info, State) ->
268 do_info(StreamID, Info, [], State).
269
270 do_info(StreamID, Info, Commands1, State0=#state{next=Next0}) ->
271 {Commands2, Next} = cowboy_stream:info(StreamID, Info, Next0),
272 {Commands1 ++ Commands2, State0#state{next=Next}}.
273
274 -spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> ok.
275 terminate(StreamID, Reason, #state{next=Next}) ->
276 cowboy_stream:terminate(StreamID, Reason, Next).
277
278 -spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(),
279 cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp
280 when Resp::cowboy_stream:resp_command().
281 early_error(StreamID, Reason, PartialReq, Resp, Opts) ->
282 cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts).
283
284 send_request_body(Pid, Ref, nofin, _, Data) ->
285 Pid ! {request_body, Ref, nofin, Data},
286 ok;
287 send_request_body(Pid, Ref, fin, BodyLen, Data) ->
288 Pid ! {request_body, Ref, fin, BodyLen, Data},
289 ok.
290
291 %% Request process.
292
293 %% We add the stacktrace to exit exceptions here in order
294 %% to simplify the debugging of errors. The proc_lib library
295 %% already adds the stacktrace to other types of exceptions.
296 -spec request_process(cowboy_req:req(), cowboy_middleware:env(), [module()]) -> ok.
297 request_process(Req, Env, Middlewares) ->
298 try
299 execute(Req, Env, Middlewares)
300 catch
301 exit:Reason={shutdown, _}:Stacktrace ->
302 erlang:raise(exit, Reason, Stacktrace);
303 exit:Reason:Stacktrace when Reason =/= normal, Reason =/= shutdown ->
304 erlang:raise(exit, {Reason, Stacktrace}, Stacktrace)
305 end.
306
307 execute(_, _, []) ->
308 ok;
309 execute(Req, Env, [Middleware|Tail]) ->
310 case Middleware:execute(Req, Env) of
311 {ok, Req2, Env2} ->
312 execute(Req2, Env2, Tail);
313 {suspend, Module, Function, Args} ->
314 proc_lib:hibernate(?MODULE, resume, [Env, Tail, Module, Function, Args]);
315 {stop, _Req2} ->
316 ok
317 end.
318
319 -spec resume(cowboy_middleware:env(), [module()], module(), atom(), [any()]) -> ok.
320 resume(Env, Tail, Module, Function, Args) ->
321 case apply(Module, Function, Args) of
322 {ok, Req2, Env2} ->
323 execute(Req2, Env2, Tail);
324 {suspend, Module2, Function2, Args2} ->
325 proc_lib:hibernate(?MODULE, resume, [Env, Tail, Module2, Function2, Args2]);
326 {stop, _Req2} ->
327 ok
328 end.