cowboy_http2.erl 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. %% Copyright (c) 2015-2017, Loïc Hoguin <essen@ninenines.eu>
  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. -module(cowboy_http2).
  15. -export([init/5]).
  16. -export([init/7]).
  17. -export([init/9]).
  18. -export([system_continue/3]).
  19. -export([system_terminate/4]).
  20. -export([system_code_change/4]).
  21. -type opts() :: #{
  22. connection_type => worker | supervisor,
  23. env => cowboy_middleware:env(),
  24. inactivity_timeout => timeout(),
  25. middlewares => [module()],
  26. preface_timeout => timeout(),
  27. shutdown_timeout => timeout(),
  28. stream_handlers => [module()]
  29. }.
  30. -export_type([opts/0]).
  31. -record(stream, {
  32. id = undefined :: cowboy_stream:streamid(),
  33. %% Stream handlers and their state.
  34. state = undefined :: {module(), any()} | flush,
  35. %% Whether we finished sending data.
  36. local = idle :: idle | upgrade | cowboy_stream:fin() | flush,
  37. %% Local flow control window (how much we can send).
  38. local_window :: integer(),
  39. %% Buffered data waiting for the flow control window to increase.
  40. local_buffer = queue:new() :: queue:queue(
  41. {cowboy_stream:fin(), non_neg_integer(), iolist()
  42. | {sendfile, non_neg_integer(), pos_integer(), file:name_all()}}),
  43. local_buffer_size = 0 :: non_neg_integer(),
  44. %% Whether we finished receiving data.
  45. remote = nofin :: cowboy_stream:fin(),
  46. %% Remote flow control window (how much we accept to receive).
  47. remote_window :: integer(),
  48. %% Request body length.
  49. body_length = 0 :: non_neg_integer()
  50. }).
  51. -type stream() :: #stream{}.
  52. -record(state, {
  53. parent = undefined :: pid(),
  54. ref :: ranch:ref(),
  55. socket = undefined :: inet:socket(),
  56. transport :: module(),
  57. opts = #{} :: opts(),
  58. %% Remote address and port for the connection.
  59. peer = undefined :: {inet:ip_address(), inet:port_number()},
  60. %% Settings are separate for each endpoint. In addition, settings
  61. %% must be acknowledged before they can be expected to be applied.
  62. %%
  63. %% @todo Since the ack is required, we must timeout if we don't receive it.
  64. %% @todo I haven't put as much thought as I should have on this,
  65. %% the final settings handling will be very different.
  66. local_settings = #{
  67. % header_table_size => 4096,
  68. % enable_push => false, %% We are the server. Push is never enabled.
  69. % max_concurrent_streams => infinity,
  70. initial_window_size => 65535,
  71. max_frame_size => 16384
  72. % max_header_list_size => infinity
  73. } :: map(),
  74. %% @todo We need a TimerRef to do SETTINGS_TIMEOUT errors.
  75. %% We need to be careful there. It's well possible that we send
  76. %% two SETTINGS frames before we receive a SETTINGS ack.
  77. next_settings = #{} :: undefined | map(), %% @todo perhaps set to undefined by default
  78. remote_settings = #{
  79. initial_window_size => 65535
  80. } :: map(),
  81. %% Connection-wide flow control window.
  82. local_window = 65535 :: integer(), %% How much we can send.
  83. remote_window = 65535 :: integer(), %% How much we accept to receive.
  84. %% Stream identifiers.
  85. client_streamid = 0 :: non_neg_integer(),
  86. server_streamid = 2 :: pos_integer(),
  87. %% Currently active HTTP/2 streams. Streams may be initiated either
  88. %% by the client or by the server through PUSH_PROMISE frames.
  89. streams = [] :: [stream()],
  90. %% Streams can spawn zero or more children which are then managed
  91. %% by this module if operating as a supervisor.
  92. children = cowboy_children:init() :: cowboy_children:children(),
  93. %% The client starts by sending a sequence of bytes as a preface,
  94. %% followed by a potentially empty SETTINGS frame. Then the connection
  95. %% is established and continues normally. An exception is when a HEADERS
  96. %% frame is sent followed by CONTINUATION frames: no other frame can be
  97. %% sent in between.
  98. parse_state = undefined :: {preface, sequence, reference()}
  99. | {preface, settings, reference()}
  100. | normal
  101. | {continuation, cowboy_stream:streamid(), cowboy_stream:fin(), binary()},
  102. %% HPACK decoding and encoding state.
  103. decode_state = cow_hpack:init() :: cow_hpack:state(),
  104. encode_state = cow_hpack:init() :: cow_hpack:state()
  105. }).
  106. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  107. init(Parent, Ref, Socket, Transport, Opts) ->
  108. case Transport:peername(Socket) of
  109. {ok, Peer} ->
  110. init(Parent, Ref, Socket, Transport, Opts, Peer, <<>>);
  111. {error, Reason} ->
  112. %% Couldn't read the peer address; connection is gone.
  113. terminate(undefined, {socket_error, Reason, 'An error has occurred on the socket.'})
  114. end.
  115. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  116. {inet:ip_address(), inet:port_number()}, binary()) -> ok.
  117. init(Parent, Ref, Socket, Transport, Opts, Peer, Buffer) ->
  118. State = #state{parent=Parent, ref=Ref, socket=Socket,
  119. transport=Transport, opts=Opts, peer=Peer,
  120. parse_state={preface, sequence, preface_timeout(Opts)}},
  121. preface(State),
  122. case Buffer of
  123. <<>> -> before_loop(State, Buffer);
  124. _ -> parse(State, Buffer)
  125. end.
  126. %% @todo Add an argument for the request body.
  127. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  128. {inet:ip_address(), inet:port_number()}, binary(), map() | undefined, cowboy_req:req()) -> ok.
  129. init(Parent, Ref, Socket, Transport, Opts, Peer, Buffer, _Settings, Req) ->
  130. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  131. transport=Transport, opts=Opts, peer=Peer,
  132. parse_state={preface, sequence, preface_timeout(Opts)}},
  133. %% @todo Apply settings.
  134. %% StreamID from HTTP/1.1 Upgrade requests is always 1.
  135. %% The stream is always in the half-closed (remote) state.
  136. State1 = stream_handler_init(State0, 1, fin, upgrade, Req),
  137. %% We assume that the upgrade will be applied. A stream handler
  138. %% must not prevent the normal operations of the server.
  139. State = info(State1, 1, {switch_protocol, #{
  140. <<"connection">> => <<"Upgrade">>,
  141. <<"upgrade">> => <<"h2c">>
  142. }, ?MODULE, undefined}), %% @todo undefined or #{}?
  143. preface(State),
  144. case Buffer of
  145. <<>> -> before_loop(State, Buffer);
  146. _ -> parse(State, Buffer)
  147. end.
  148. preface(#state{socket=Socket, transport=Transport, next_settings=Settings}) ->
  149. %% We send next_settings and use defaults until we get a ack.
  150. ok = Transport:send(Socket, cow_http2:settings(Settings)).
  151. preface_timeout(Opts) ->
  152. PrefaceTimeout = maps:get(preface_timeout, Opts, 5000),
  153. erlang:start_timer(PrefaceTimeout, self(), preface_timeout).
  154. %% @todo Add the timeout for last time since we heard of connection.
  155. before_loop(State, Buffer) ->
  156. loop(State, Buffer).
  157. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  158. opts=Opts, children=Children, parse_state=PS}, Buffer) ->
  159. Transport:setopts(Socket, [{active, once}]),
  160. {OK, Closed, Error} = Transport:messages(),
  161. InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
  162. receive
  163. %% Socket messages.
  164. {OK, Socket, Data} ->
  165. parse(State, << Buffer/binary, Data/binary >>);
  166. {Closed, Socket} ->
  167. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  168. {Error, Socket, Reason} ->
  169. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  170. %% System messages.
  171. {'EXIT', Parent, Reason} ->
  172. exit(Reason);
  173. {system, From, Request} ->
  174. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  175. %% Timeouts.
  176. {timeout, Ref, {shutdown, Pid}} ->
  177. cowboy_children:shutdown_timeout(Children, Ref, Pid),
  178. loop(State, Buffer);
  179. {timeout, TRef, preface_timeout} ->
  180. case PS of
  181. {preface, _, TRef} ->
  182. terminate(State, {connection_error, protocol_error,
  183. 'The preface was not received in a reasonable amount of time.'});
  184. _ ->
  185. loop(State, Buffer)
  186. end;
  187. %% Messages pertaining to a stream.
  188. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  189. loop(info(State, StreamID, Msg), Buffer);
  190. %% Exit signal from children.
  191. Msg = {'EXIT', Pid, _} ->
  192. loop(down(State, Pid, Msg), Buffer);
  193. %% Calls from supervisor module.
  194. {'$gen_call', {From, Tag}, which_children} ->
  195. From ! {Tag, cowboy_children:which_children(Children, ?MODULE)},
  196. loop(State, Buffer);
  197. {'$gen_call', {From, Tag}, count_children} ->
  198. From ! {Tag, cowboy_children:count_children(Children)},
  199. loop(State, Buffer);
  200. {'$gen_call', {From, Tag}, _} ->
  201. From ! {Tag, {error, ?MODULE}},
  202. loop(State, Buffer);
  203. Msg ->
  204. error_logger:error_msg("Received stray message ~p.", [Msg]),
  205. loop(State, Buffer)
  206. after InactivityTimeout ->
  207. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  208. end.
  209. parse(State=#state{socket=Socket, transport=Transport, parse_state={preface, sequence, TRef}}, Data) ->
  210. case Data of
  211. << "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", Rest/bits >> ->
  212. parse(State#state{parse_state={preface, settings, TRef}}, Rest);
  213. _ when byte_size(Data) >= 24 ->
  214. Transport:close(Socket),
  215. exit({shutdown, {connection_error, protocol_error,
  216. 'The connection preface was invalid. (RFC7540 3.5)'}});
  217. _ ->
  218. Len = byte_size(Data),
  219. << Preface:Len/binary, _/bits >> = <<"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n">>,
  220. case Data of
  221. Preface ->
  222. %% @todo OK we should have a timeout when waiting for the preface.
  223. before_loop(State, Data);
  224. _ ->
  225. Transport:close(Socket),
  226. exit({shutdown, {connection_error, protocol_error,
  227. 'The connection preface was invalid. (RFC7540 3.5)'}})
  228. end
  229. end;
  230. %% @todo Perhaps instead of just more we can have {more, Len} to avoid all the checks.
  231. parse(State=#state{local_settings=#{max_frame_size := MaxFrameSize},
  232. parse_state=ParseState}, Data) ->
  233. case cow_http2:parse(Data, MaxFrameSize) of
  234. {ok, Frame, Rest} ->
  235. case ParseState of
  236. normal ->
  237. parse(frame(State, Frame), Rest);
  238. {preface, settings, TRef} ->
  239. parse_settings_preface(State, Frame, Rest, TRef);
  240. {continuation, _, _, _} ->
  241. parse(continuation_frame(State, Frame), Rest)
  242. end;
  243. {ignore, Rest} ->
  244. parse(State, Rest);
  245. {stream_error, StreamID, Reason, Human, Rest} ->
  246. parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
  247. Error = {connection_error, _, _} ->
  248. terminate(State, Error);
  249. more ->
  250. before_loop(State, Data)
  251. end.
  252. parse_settings_preface(State, Frame={settings, _}, Rest, TRef) ->
  253. _ = erlang:cancel_timer(TRef, [{async, true}, {info, false}]),
  254. parse(frame(State#state{parse_state=normal}, Frame), Rest);
  255. parse_settings_preface(State, _, _, _) ->
  256. terminate(State, {connection_error, protocol_error,
  257. 'The preface sequence must be followed by a SETTINGS frame. (RFC7540 3.5)'}).
  258. %% @todo When we get a 'fin' we need to check if the stream had a 'fin' sent back
  259. %% and terminate the stream if this is the end of it.
  260. %% DATA frame.
  261. frame(State=#state{client_streamid=LastStreamID}, {data, StreamID, _, _})
  262. when StreamID > LastStreamID ->
  263. terminate(State, {connection_error, protocol_error,
  264. 'DATA frame received on a stream in idle state. (RFC7540 5.1)'});
  265. frame(State0=#state{remote_window=ConnWindow, streams=Streams},
  266. {data, StreamID, IsFin0, Data}) ->
  267. DataLen = byte_size(Data),
  268. State = State0#state{remote_window=ConnWindow - DataLen},
  269. case lists:keyfind(StreamID, #stream.id, Streams) of
  270. Stream = #stream{state=StreamState0, remote=nofin,
  271. remote_window=StreamWindow, body_length=Len0} ->
  272. Len = Len0 + DataLen,
  273. IsFin = case IsFin0 of
  274. fin -> {fin, Len};
  275. nofin -> nofin
  276. end,
  277. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  278. {Commands, StreamState} ->
  279. commands(State,
  280. Stream#stream{state=StreamState, remote_window=StreamWindow - DataLen,
  281. body_length=Len}, Commands)
  282. catch Class:Reason ->
  283. error_logger:error_msg("Exception occurred in "
  284. "cowboy_stream:data(~p, ~p, ~p, ~p) with reason ~p:~p.",
  285. [StreamID, IsFin0, Data, StreamState0, Class, Reason]),
  286. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  287. 'Exception occurred in cowboy_stream:data/4.'})
  288. end;
  289. #stream{remote=fin} ->
  290. stream_reset(State, StreamID, {stream_error, stream_closed,
  291. 'DATA frame received for a half-closed (remote) stream. (RFC7540 5.1)'});
  292. false ->
  293. %% @todo What about RST_STREAM? Sigh.
  294. terminate(State, {connection_error, stream_closed,
  295. 'DATA frame received for a closed stream. (RFC7540 5.1)'})
  296. end;
  297. %% HEADERS frame with invalid even-numbered streamid.
  298. frame(State, {headers, StreamID, _, _, _}) when StreamID rem 2 =:= 0 ->
  299. terminate(State, {connection_error, protocol_error,
  300. 'HEADERS frame received with even-numbered streamid. (RFC7540 5.1.1)'});
  301. %% HEADERS frame received on (half-)closed stream.
  302. frame(State=#state{client_streamid=LastStreamID}, {headers, StreamID, _, _, _})
  303. when StreamID =< LastStreamID ->
  304. stream_reset(State, StreamID, {stream_error, stream_closed,
  305. 'HEADERS frame received on a stream in closed or half-closed state. (RFC7540 5.1)'});
  306. %% Single HEADERS frame headers block.
  307. frame(State, {headers, StreamID, IsFin, head_fin, HeaderBlock}) ->
  308. %% @todo We probably need to validate StreamID here and in 4 next clauses.
  309. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  310. %% HEADERS frame starting a headers block. Enter continuation mode.
  311. frame(State, {headers, StreamID, IsFin, head_nofin, HeaderBlockFragment}) ->
  312. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  313. %% Single HEADERS frame headers block with priority.
  314. frame(State, {headers, StreamID, IsFin, head_fin,
  315. _IsExclusive, _DepStreamID, _Weight, HeaderBlock}) ->
  316. %% @todo Handle priority.
  317. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  318. %% HEADERS frame starting a headers block. Enter continuation mode.
  319. frame(State, {headers, StreamID, IsFin, head_nofin,
  320. _IsExclusive, _DepStreamID, _Weight, HeaderBlockFragment}) ->
  321. %% @todo Handle priority.
  322. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  323. %% PRIORITY frame.
  324. frame(State, {priority, _StreamID, _IsExclusive, _DepStreamID, _Weight}) ->
  325. %% @todo Validate StreamID?
  326. %% @todo Handle priority.
  327. State;
  328. %% RST_STREAM frame.
  329. frame(State=#state{client_streamid=LastStreamID}, {rst_stream, StreamID, _})
  330. when StreamID > LastStreamID ->
  331. terminate(State, {connection_error, protocol_error,
  332. 'RST_STREAM frame received on a stream in idle state. (RFC7540 5.1)'});
  333. frame(State, {rst_stream, StreamID, Reason}) ->
  334. stream_terminate(State, StreamID, {stream_error, Reason, 'Stream reset requested by client.'});
  335. %% SETTINGS frame.
  336. frame(State=#state{socket=Socket, transport=Transport, remote_settings=Settings0},
  337. {settings, Settings}) ->
  338. Transport:send(Socket, cow_http2:settings_ack()),
  339. State#state{remote_settings=maps:merge(Settings0, Settings)};
  340. %% Ack for a previously sent SETTINGS frame.
  341. frame(State=#state{next_settings=_NextSettings}, settings_ack) ->
  342. %% @todo Apply SETTINGS that require synchronization.
  343. State;
  344. %% Unexpected PUSH_PROMISE frame.
  345. frame(State, {push_promise, _, _, _, _}) ->
  346. terminate(State, {connection_error, protocol_error,
  347. 'PUSH_PROMISE frames MUST only be sent on a peer-initiated stream. (RFC7540 6.6)'});
  348. %% PING frame.
  349. frame(State=#state{socket=Socket, transport=Transport}, {ping, Opaque}) ->
  350. Transport:send(Socket, cow_http2:ping_ack(Opaque)),
  351. State;
  352. %% Ack for a previously sent PING frame.
  353. %%
  354. %% @todo Might want to check contents but probably a waste of time.
  355. frame(State, {ping_ack, _Opaque}) ->
  356. State;
  357. %% GOAWAY frame.
  358. frame(State, Frame={goaway, _, _, _}) ->
  359. terminate(State, {stop, Frame, 'Client is going away.'});
  360. %% Connection-wide WINDOW_UPDATE frame.
  361. frame(State=#state{local_window=ConnWindow}, {window_update, Increment}) ->
  362. send_data(State#state{local_window=ConnWindow + Increment});
  363. %% Stream-specific WINDOW_UPDATE frame.
  364. frame(State=#state{client_streamid=LastStreamID}, {window_update, StreamID, _})
  365. when StreamID > LastStreamID ->
  366. terminate(State, {connection_error, protocol_error,
  367. 'WINDOW_UPDATE frame received on a stream in idle state. (RFC7540 5.1)'});
  368. frame(State0=#state{streams=Streams0}, {window_update, StreamID, Increment}) ->
  369. case lists:keyfind(StreamID, #stream.id, Streams0) of
  370. Stream0 = #stream{local_window=StreamWindow} ->
  371. {State, Stream} = send_data(State0,
  372. Stream0#stream{local_window=StreamWindow + Increment}),
  373. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  374. State#state{streams=Streams};
  375. %% @todo We must reject WINDOW_UPDATE frames on RST_STREAM closed streams.
  376. false ->
  377. %% WINDOW_UPDATE frames may be received for a short period of time
  378. %% after a stream is closed. They must be ignored.
  379. State0
  380. end;
  381. %% Unexpected CONTINUATION frame.
  382. frame(State, {continuation, _, _, _}) ->
  383. terminate(State, {connection_error, protocol_error,
  384. 'CONTINUATION frames MUST be preceded by a HEADERS frame. (RFC7540 6.10)'}).
  385. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  386. {continuation, StreamID, head_fin, HeaderBlockFragment1}) ->
  387. stream_decode_init(State#state{parse_state=normal}, StreamID, IsFin,
  388. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>);
  389. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  390. {continuation, StreamID, head_nofin, HeaderBlockFragment1}) ->
  391. State#state{parse_state={continuation, StreamID, IsFin,
  392. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>}};
  393. continuation_frame(State, _) ->
  394. terminate(State, {connection_error, protocol_error,
  395. 'An invalid frame was received while expecting a CONTINUATION frame. (RFC7540 6.2)'}).
  396. down(State=#state{children=Children0}, Pid, Msg) ->
  397. case cowboy_children:down(Children0, Pid) of
  398. %% The stream was terminated already.
  399. {ok, undefined, Children} ->
  400. State#state{children=Children};
  401. %% The stream is still running.
  402. {ok, StreamID, Children} ->
  403. info(State#state{children=Children}, StreamID, Msg);
  404. %% The process was unknown.
  405. error ->
  406. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.~n", [Msg, Pid]),
  407. State
  408. end.
  409. info(State=#state{streams=Streams}, StreamID, Msg) ->
  410. case lists:keyfind(StreamID, #stream.id, Streams) of
  411. Stream = #stream{state=StreamState0} ->
  412. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  413. {Commands, StreamState} ->
  414. commands(State, Stream#stream{state=StreamState}, Commands)
  415. catch Class:Reason ->
  416. error_logger:error_msg("Exception occurred in "
  417. "cowboy_stream:info(~p, ~p, ~p) with reason ~p:~p.",
  418. [StreamID, Msg, StreamState0, Class, Reason]),
  419. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  420. 'Exception occurred in cowboy_stream:info/3.'})
  421. end;
  422. false ->
  423. error_logger:error_msg("Received message ~p for unknown stream ~p.", [Msg, StreamID]),
  424. State
  425. end.
  426. commands(State, Stream, []) ->
  427. after_commands(State, Stream);
  428. %% Error responses are sent only if a response wasn't sent already.
  429. commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  430. commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
  431. commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
  432. commands(State, Stream, Tail);
  433. %% Send response headers.
  434. %%
  435. %% @todo Kill the stream if it sent a response when one has already been sent.
  436. %% @todo Keep IsFin in the state.
  437. %% @todo Same two things above apply to DATA, possibly promise too.
  438. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  439. Stream=#stream{id=StreamID, local=idle}, [{response, StatusCode, Headers0, Body}|Tail]) ->
  440. Headers = Headers0#{<<":status">> => status(StatusCode)},
  441. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  442. case Body of
  443. <<>> ->
  444. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  445. commands(State#state{encode_state=EncodeState}, Stream#stream{local=fin}, Tail);
  446. {sendfile, O, B, P} ->
  447. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  448. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin},
  449. [{sendfile, fin, O, B, P}|Tail]);
  450. _ ->
  451. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  452. {State1, Stream1} = send_data(State, Stream#stream{local=nofin}, fin, Body),
  453. commands(State1#state{encode_state=EncodeState}, Stream1, Tail)
  454. end;
  455. %% @todo response when local!=idle
  456. %% Send response headers and initiate chunked encoding.
  457. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  458. Stream=#stream{id=StreamID, local=idle}, [{headers, StatusCode, Headers0}|Tail]) ->
  459. Headers = Headers0#{<<":status">> => status(StatusCode)},
  460. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  461. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  462. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin}, Tail);
  463. %% @todo headers when local!=idle
  464. %% Send a response body chunk.
  465. %%
  466. %% @todo WINDOW_UPDATE stuff require us to buffer some data.
  467. %%
  468. %% When the body is sent using sendfile, the current solution is not
  469. %% very good. The body could be too large, blocking the connection.
  470. %% Also sendfile technically only works over TCP, so it's not that
  471. %% useful for HTTP/2. At the very least the sendfile call should be
  472. %% split into multiple calls and flow control should be used to make
  473. %% sure we only send as fast as the client can receive and don't block
  474. %% anything.
  475. commands(State0, Stream0=#stream{local=nofin}, [{data, IsFin, Data}|Tail]) ->
  476. {State, Stream} = send_data(State0, Stream0, IsFin, Data),
  477. commands(State, Stream, Tail);
  478. %% @todo data when local!=nofin
  479. %% Send a file.
  480. %%
  481. %% @todo This implementation is terrible. A good implementation would
  482. %% need to check that Bytes is exact (or we need to document that we
  483. %% trust it to be exact), and would need to send the file asynchronously
  484. %% in many data frames. Perhaps a sendfile call should result in a
  485. %% process being created specifically for this purpose. Or perhaps
  486. %% the protocol should be "dumb" and the stream handler be the one
  487. %% to ensure the file is sent in chunks (which would require a better
  488. %% flow control at the stream handler level). One thing for sure, the
  489. %% implementation necessarily varies between HTTP/1.1 and HTTP/2.
  490. commands(State0, Stream0=#stream{local=nofin},
  491. [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  492. {State, Stream} = send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
  493. commands(State, Stream, Tail);
  494. %% @todo sendfile when local!=nofin
  495. %% Send a push promise.
  496. %%
  497. %% @todo We need to keep track of what promises we made so that we don't
  498. %% end up with an infinite loop of promises.
  499. commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
  500. encode_state=EncodeState0}, Stream=#stream{id=StreamID},
  501. [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  502. Authority = case {Scheme, Port} of
  503. {<<"http">>, 80} -> Host;
  504. {<<"https">>, 443} -> Host;
  505. _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
  506. end,
  507. PathWithQs = case Qs of
  508. <<>> -> Path;
  509. _ -> [Path, $?, Qs]
  510. end,
  511. %% We need to make sure the header value is binary before we can
  512. %% pass it to stream_req_init, as it expects them to be flat.
  513. Headers1 = maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0),
  514. Headers = Headers1#{
  515. <<":method">> => Method,
  516. <<":scheme">> => Scheme,
  517. <<":authority">> => Authority,
  518. <<":path">> => iolist_to_binary(PathWithQs)},
  519. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  520. Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
  521. State = stream_req_init(State0#state{server_streamid=PromisedStreamID + 2,
  522. encode_state=EncodeState}, PromisedStreamID, fin, Headers),
  523. commands(State, Stream, Tail);
  524. commands(State=#state{socket=Socket, transport=Transport, remote_window=ConnWindow},
  525. Stream=#stream{id=StreamID, remote_window=StreamWindow},
  526. [{flow, Size}|Tail]) ->
  527. Transport:send(Socket, [
  528. cow_http2:window_update(Size),
  529. cow_http2:window_update(StreamID, Size)
  530. ]),
  531. commands(State#state{remote_window=ConnWindow + Size},
  532. Stream#stream{remote_window=StreamWindow + Size}, Tail);
  533. %% Supervise a child process.
  534. commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
  535. [{spawn, Pid, Shutdown}|Tail]) ->
  536. commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
  537. Stream, Tail);
  538. %% Error handling.
  539. commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
  540. %% @todo Do we want to run the commands after an internal_error?
  541. %% @todo Do we even allow commands after?
  542. %% @todo Only reset when the stream still exists.
  543. stream_reset(after_commands(State, Stream), StreamID, Error);
  544. %% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
  545. commands(State=#state{socket=Socket, transport=Transport},
  546. Stream=#stream{local=upgrade}, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
  547. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
  548. commands(State, Stream#stream{local=idle}, Tail);
  549. %% HTTP/2 has no support for the Upgrade mechanism.
  550. commands(State, Stream, [{switch_protocol, _Headers, _Mod, _ModState}|Tail]) ->
  551. %% @todo This is an error. Not sure what to do here yet.
  552. commands(State, Stream, Tail);
  553. commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
  554. %% @todo Do we want to run the commands after a stop?
  555. %% @todo Do we even allow commands after?
  556. stream_terminate(after_commands(State, Stream), StreamID, normal).
  557. after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
  558. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  559. State#state{streams=Streams}.
  560. status(Status) when is_integer(Status) ->
  561. integer_to_binary(Status);
  562. status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
  563. << H, T, U >>.
  564. %% @todo Should we ever want to implement the PRIORITY mechanism,
  565. %% this would be the place to do it. Right now, we just go over
  566. %% all streams and send what we can until either everything is
  567. %% sent or we run out of space in the window.
  568. send_data(State=#state{streams=Streams}) ->
  569. resume_streams(State, Streams, []).
  570. %% @todo When streams terminate we need to remove the stream.
  571. resume_streams(State, [], Acc) ->
  572. State#state{streams=lists:reverse(Acc)};
  573. %% While technically we should never get < 0 here, let's be on the safe side.
  574. resume_streams(State=#state{local_window=ConnWindow}, Streams, Acc)
  575. when ConnWindow =< 0 ->
  576. State#state{streams=lists:reverse(Acc, Streams)};
  577. %% We rely on send_data/2 to do all the necessary checks about the stream.
  578. resume_streams(State0, [Stream0|Tail], Acc) ->
  579. {State, Stream} = send_data(State0, Stream0),
  580. resume_streams(State, Tail, [Stream|Acc]).
  581. %% @todo We might want to print an error if local=fin.
  582. %%
  583. %% @todo It's possible that the stream terminates. We must remove it.
  584. send_data(State=#state{local_window=ConnWindow},
  585. Stream=#stream{local=IsFin, local_window=StreamWindow, local_buffer_size=BufferSize})
  586. when ConnWindow =< 0; IsFin =:= fin; StreamWindow =< 0; BufferSize =:= 0 ->
  587. {State, Stream};
  588. send_data(State0, Stream0=#stream{local_buffer=Q0, local_buffer_size=BufferSize}) ->
  589. %% We know there is an item in the queue.
  590. {{value, {IsFin, DataSize, Data}}, Q} = queue:out(Q0),
  591. {State, Stream} = send_data(State0,
  592. Stream0#stream{local_buffer=Q, local_buffer_size=BufferSize - DataSize},
  593. IsFin, Data, in_r),
  594. send_data(State, Stream).
  595. send_data(State, Stream, IsFin, Data) ->
  596. send_data(State, Stream, IsFin, Data, in).
  597. %% Send data immediately if we can, buffer otherwise.
  598. %% @todo We might want to print an error if local=fin.
  599. send_data(State=#state{local_window=ConnWindow},
  600. Stream=#stream{local_window=StreamWindow}, IsFin, Data, In)
  601. when ConnWindow =< 0; StreamWindow =< 0 ->
  602. {State, queue_data(Stream, IsFin, Data, In)};
  603. send_data(State=#state{socket=Socket, transport=Transport, local_window=ConnWindow},
  604. Stream=#stream{id=StreamID, local_window=StreamWindow}, IsFin, Data, In) ->
  605. MaxFrameSize = 16384, %% @todo Use the real SETTINGS_MAX_FRAME_SIZE set by the client.
  606. MaxSendSize = min(min(ConnWindow, StreamWindow), MaxFrameSize),
  607. case Data of
  608. {sendfile, Offset, Bytes, Path} when Bytes =< MaxSendSize ->
  609. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  610. Transport:sendfile(Socket, Path, Offset, Bytes),
  611. {State#state{local_window=ConnWindow - Bytes},
  612. Stream#stream{local=IsFin, local_window=StreamWindow - Bytes}};
  613. {sendfile, Offset, Bytes, Path} ->
  614. Transport:send(Socket, cow_http2:data_header(StreamID, nofin, MaxSendSize)),
  615. Transport:sendfile(Socket, Path, Offset, MaxSendSize),
  616. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  617. Stream#stream{local_window=StreamWindow - MaxSendSize},
  618. IsFin, {sendfile, Offset + MaxSendSize, Bytes - MaxSendSize, Path}, In);
  619. Iolist0 ->
  620. IolistSize = iolist_size(Iolist0),
  621. if
  622. IolistSize =< MaxSendSize ->
  623. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Iolist0)),
  624. {State#state{local_window=ConnWindow - IolistSize},
  625. Stream#stream{local=IsFin, local_window=StreamWindow - IolistSize}};
  626. true ->
  627. {Iolist, More} = cowboy_iolists:split(MaxSendSize, Iolist0),
  628. Transport:send(Socket, cow_http2:data(StreamID, nofin, Iolist)),
  629. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  630. Stream#stream{local_window=StreamWindow - MaxSendSize},
  631. IsFin, More, In)
  632. end
  633. end.
  634. queue_data(Stream=#stream{local_buffer=Q0, local_buffer_size=Size0}, IsFin, Data, In) ->
  635. DataSize = case Data of
  636. {sendfile, _, Bytes, _} -> Bytes;
  637. Iolist -> iolist_size(Iolist)
  638. end,
  639. Q = queue:In({IsFin, DataSize, Data}, Q0),
  640. Stream#stream{local_buffer=Q, local_buffer_size=Size0 + DataSize}.
  641. -spec terminate(#state{}, _) -> no_return().
  642. terminate(undefined, Reason) ->
  643. exit({shutdown, Reason});
  644. terminate(#state{socket=Socket, transport=Transport, client_streamid=LastStreamID,
  645. streams=Streams, children=Children}, Reason) ->
  646. %% @todo We might want to optionally send the Reason value
  647. %% as debug data in the GOAWAY frame here. Perhaps more.
  648. Transport:send(Socket, cow_http2:goaway(LastStreamID, terminate_reason(Reason), <<>>)),
  649. terminate_all_streams(Streams, Reason),
  650. cowboy_children:terminate(Children),
  651. Transport:close(Socket),
  652. exit({shutdown, Reason}).
  653. terminate_reason({connection_error, Reason, _}) -> Reason;
  654. terminate_reason({stop, _, _}) -> no_error;
  655. terminate_reason({socket_error, _, _}) -> internal_error;
  656. terminate_reason({internal_error, _, _}) -> internal_error.
  657. terminate_all_streams([], _) ->
  658. ok;
  659. %% This stream was already terminated and is now just flushing the data out. Skip it.
  660. terminate_all_streams([#stream{state=flush}|Tail], Reason) ->
  661. terminate_all_streams(Tail, Reason);
  662. terminate_all_streams([#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
  663. stream_call_terminate(StreamID, Reason, StreamState),
  664. terminate_all_streams(Tail, Reason).
  665. %% Stream functions.
  666. stream_decode_init(State=#state{socket=Socket, transport=Transport,
  667. decode_state=DecodeState0}, StreamID, IsFin, HeaderBlock) ->
  668. %% @todo Add clause for CONNECT requests (no scheme/path).
  669. try headers_decode(HeaderBlock, DecodeState0) of
  670. {Headers=#{<<":method">> := _, <<":scheme">> := _,
  671. <<":authority">> := _, <<":path">> := _}, DecodeState} ->
  672. stream_req_init(State#state{decode_state=DecodeState}, StreamID, IsFin, Headers);
  673. {_, DecodeState} ->
  674. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  675. State#state{decode_state=DecodeState}
  676. catch _:_ ->
  677. terminate(State, {connection_error, compression_error,
  678. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  679. end.
  680. stream_req_init(State=#state{ref=Ref, peer=Peer}, StreamID, IsFin, Headers0=#{
  681. <<":method">> := Method, <<":scheme">> := Scheme,
  682. <<":authority">> := Authority, <<":path">> := PathWithQs}) ->
  683. Headers = maps:without([<<":method">>, <<":scheme">>, <<":authority">>, <<":path">>], Headers0),
  684. BodyLength = case Headers of
  685. _ when IsFin =:= fin ->
  686. 0;
  687. #{<<"content-length">> := <<"0">>} ->
  688. 0;
  689. #{<<"content-length">> := BinLength} ->
  690. try
  691. cow_http_hd:parse_content_length(BinLength)
  692. catch _:_ ->
  693. terminate(State, {stream_error, StreamID, protocol_error,
  694. 'The content-length header is invalid. (RFC7230 3.3.2)'})
  695. end;
  696. _ ->
  697. undefined
  698. end,
  699. {Host, Port} = cow_http_hd:parse_host(Authority),
  700. {Path, Qs} = cow_http:parse_fullpath(PathWithQs),
  701. Req = #{
  702. ref => Ref,
  703. pid => self(),
  704. streamid => StreamID,
  705. peer => Peer,
  706. method => Method,
  707. scheme => Scheme,
  708. host => Host,
  709. port => Port,
  710. path => Path,
  711. qs => Qs,
  712. version => 'HTTP/2',
  713. headers => Headers,
  714. has_body => IsFin =:= nofin,
  715. body_length => BodyLength
  716. },
  717. stream_handler_init(State, StreamID, IsFin, idle, Req).
  718. stream_handler_init(State=#state{opts=Opts,
  719. local_settings=#{initial_window_size := RemoteWindow},
  720. remote_settings=#{initial_window_size := LocalWindow}},
  721. StreamID, RemoteIsFin, LocalIsFin, Req) ->
  722. try cowboy_stream:init(StreamID, Req, Opts) of
  723. {Commands, StreamState} ->
  724. commands(State#state{client_streamid=StreamID},
  725. #stream{id=StreamID, state=StreamState,
  726. remote=RemoteIsFin, local=LocalIsFin,
  727. local_window=LocalWindow, remote_window=RemoteWindow},
  728. Commands)
  729. catch Class:Reason ->
  730. error_logger:error_msg("Exception occurred in "
  731. "cowboy_stream:init(~p, ~p, ~p) with reason ~p:~p.",
  732. [StreamID, Req, Opts, Class, Reason]),
  733. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  734. 'Exception occurred in cowboy_stream:init/3.'})
  735. end.
  736. %% @todo We might need to keep track of which stream has been reset so we don't send lots of them.
  737. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID,
  738. StreamError={internal_error, _, _}) ->
  739. Transport:send(Socket, cow_http2:rst_stream(StreamID, internal_error)),
  740. stream_terminate(State, StreamID, StreamError);
  741. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID,
  742. StreamError={stream_error, Reason, _}) ->
  743. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  744. stream_terminate(State, StreamID, StreamError).
  745. stream_terminate(State=#state{socket=Socket, transport=Transport,
  746. streams=Streams0, children=Children0}, StreamID, Reason) ->
  747. case lists:keytake(StreamID, #stream.id, Streams0) of
  748. %% When the stream terminates normally (without sending RST_STREAM)
  749. %% and no response was sent, we need to send a proper response back to the client.
  750. {value, #stream{state=StreamState, local=idle}, Streams} when Reason =:= normal ->
  751. State1 = info(State, StreamID, {response, 204, #{}, <<>>}),
  752. stream_call_terminate(StreamID, Reason, StreamState),
  753. Children = cowboy_children:shutdown(Children0, StreamID),
  754. State1#state{streams=Streams, children=Children};
  755. %% When a response was sent but not terminated, we need to close the stream.
  756. {value, #stream{state=StreamState, local=nofin, local_buffer_size=0}, Streams}
  757. when Reason =:= normal ->
  758. Transport:send(Socket, cow_http2:data(StreamID, fin, <<>>)),
  759. stream_call_terminate(StreamID, Reason, StreamState),
  760. Children = cowboy_children:shutdown(Children0, StreamID),
  761. State#state{streams=Streams, children=Children};
  762. %% Unless there is still data in the buffer. We can however reset
  763. %% a few fields and set a special local state to avoid confusion.
  764. {value, Stream=#stream{state=StreamState, local=nofin}, Streams} ->
  765. stream_call_terminate(StreamID, Reason, StreamState),
  766. Children = cowboy_children:shutdown(Children0, StreamID),
  767. State#state{streams=[Stream#stream{state=flush, local=flush}|Streams],
  768. children=Children};
  769. %% Otherwise we sent an RST_STREAM and/or the stream is already closed.
  770. {value, #stream{state=StreamState}, Streams} ->
  771. stream_call_terminate(StreamID, Reason, StreamState),
  772. Children = cowboy_children:shutdown(Children0, StreamID),
  773. State#state{streams=Streams, children=Children};
  774. false ->
  775. %% @todo Unknown stream. Not sure what to do here. Check again once all
  776. %% terminate calls have been written.
  777. State
  778. end.
  779. stream_call_terminate(StreamID, Reason, StreamState) ->
  780. try
  781. cowboy_stream:terminate(StreamID, Reason, StreamState)
  782. catch Class:Reason ->
  783. error_logger:error_msg("Exception occurred in "
  784. "cowboy_stream:terminate(~p, ~p, ~p) with reason ~p:~p.",
  785. [StreamID, Reason, StreamState, Class, Reason])
  786. end.
  787. %% Headers encode/decode.
  788. headers_decode(HeaderBlock, DecodeState0) ->
  789. {Headers, DecodeState} = cow_hpack:decode(HeaderBlock, DecodeState0),
  790. {headers_to_map(Headers, #{}), DecodeState}.
  791. %% This function is necessary to properly handle duplicate headers
  792. %% and the special-case cookie header.
  793. headers_to_map([], Acc) ->
  794. Acc;
  795. headers_to_map([{Name, Value}|Tail], Acc0) ->
  796. Acc = case Acc0 of
  797. %% The cookie header does not use proper HTTP header lists.
  798. #{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  799. #{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  800. _ -> Acc0#{Name => Value}
  801. end,
  802. headers_to_map(Tail, Acc).
  803. %% The set-cookie header is special; we can only send one cookie per header.
  804. headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
  805. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  806. Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
  807. cow_hpack:encode(Headers, EncodeState);
  808. headers_encode(Headers0, EncodeState) ->
  809. Headers = maps:to_list(Headers0),
  810. cow_hpack:encode(Headers, EncodeState).
  811. %% System callbacks.
  812. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  813. system_continue(_, _, {State, Buffer}) ->
  814. loop(State, Buffer).
  815. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  816. system_terminate(Reason, _, _, {State, _}) ->
  817. terminate(State, Reason).
  818. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  819. system_code_change(Misc, _, _, _) ->
  820. {ok, Misc}.