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 = [] :: [{pid(), cowboy_stream:streamid()}],
  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. {timeout, TRef, preface_timeout} ->
  176. case PS of
  177. {preface, _, TRef} ->
  178. terminate(State, {connection_error, protocol_error,
  179. 'The preface was not received in a reasonable amount of time.'});
  180. _ ->
  181. loop(State, Buffer)
  182. end;
  183. %% Messages pertaining to a stream.
  184. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  185. loop(info(State, StreamID, Msg), Buffer);
  186. %% Exit signal from children.
  187. Msg = {'EXIT', Pid, _} ->
  188. loop(down(State, Pid, Msg), Buffer);
  189. %% Calls from supervisor module.
  190. {'$gen_call', {From, Tag}, which_children} ->
  191. Workers = [{?MODULE, Pid, worker, [?MODULE]} || {Pid, _} <- Children],
  192. From ! {Tag, Workers},
  193. loop(State, Buffer);
  194. {'$gen_call', {From, Tag}, count_children} ->
  195. NbChildren = length(Children),
  196. Counts = [{specs, 1}, {active, NbChildren},
  197. {supervisors, 0}, {workers, NbChildren}],
  198. From ! {Tag, Counts},
  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_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_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_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 lists:keytake(Pid, 1, Children0) of
  398. {value, {_, StreamID}, Children} ->
  399. info(State#state{children=Children}, StreamID, Msg);
  400. false ->
  401. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.", [Msg, Pid]),
  402. State
  403. end.
  404. info(State=#state{streams=Streams}, StreamID, Msg) ->
  405. case lists:keyfind(StreamID, #stream.id, Streams) of
  406. Stream = #stream{state=StreamState0} ->
  407. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  408. {Commands, StreamState} ->
  409. commands(State, Stream#stream{state=StreamState}, Commands)
  410. catch Class:Reason ->
  411. error_logger:error_msg("Exception occurred in "
  412. "cowboy_stream:info(~p, ~p, ~p) with reason ~p:~p.",
  413. [StreamID, Msg, StreamState0, Class, Reason]),
  414. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  415. 'Exception occurred in cowboy_stream:info/3.'})
  416. end;
  417. false ->
  418. error_logger:error_msg("Received message ~p for unknown stream ~p.", [Msg, StreamID]),
  419. State
  420. end.
  421. commands(State, Stream, []) ->
  422. after_commands(State, Stream);
  423. %% Error responses are sent only if a response wasn't sent already.
  424. commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  425. commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
  426. commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
  427. commands(State, Stream, Tail);
  428. %% Send response headers.
  429. %%
  430. %% @todo Kill the stream if it sent a response when one has already been sent.
  431. %% @todo Keep IsFin in the state.
  432. %% @todo Same two things above apply to DATA, possibly promise too.
  433. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  434. Stream=#stream{id=StreamID, local=idle}, [{response, StatusCode, Headers0, Body}|Tail]) ->
  435. Headers = Headers0#{<<":status">> => status(StatusCode)},
  436. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  437. case Body of
  438. <<>> ->
  439. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  440. commands(State#state{encode_state=EncodeState}, Stream#stream{local=fin}, Tail);
  441. {sendfile, O, B, P} ->
  442. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  443. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin},
  444. [{sendfile, fin, O, B, P}|Tail]);
  445. _ ->
  446. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  447. {State1, Stream1} = send_data(State, Stream#stream{local=nofin}, fin, Body),
  448. commands(State1#state{encode_state=EncodeState}, Stream1, Tail)
  449. end;
  450. %% @todo response when local!=idle
  451. %% Send response headers and initiate chunked encoding.
  452. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  453. Stream=#stream{id=StreamID, local=idle}, [{headers, StatusCode, Headers0}|Tail]) ->
  454. Headers = Headers0#{<<":status">> => status(StatusCode)},
  455. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  456. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  457. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin}, Tail);
  458. %% @todo headers when local!=idle
  459. %% Send a response body chunk.
  460. %%
  461. %% @todo WINDOW_UPDATE stuff require us to buffer some data.
  462. %%
  463. %% When the body is sent using sendfile, the current solution is not
  464. %% very good. The body could be too large, blocking the connection.
  465. %% Also sendfile technically only works over TCP, so it's not that
  466. %% useful for HTTP/2. At the very least the sendfile call should be
  467. %% split into multiple calls and flow control should be used to make
  468. %% sure we only send as fast as the client can receive and don't block
  469. %% anything.
  470. commands(State0, Stream0=#stream{local=nofin}, [{data, IsFin, Data}|Tail]) ->
  471. {State, Stream} = send_data(State0, Stream0, IsFin, Data),
  472. commands(State, Stream, Tail);
  473. %% @todo data when local!=nofin
  474. %% Send a file.
  475. %%
  476. %% @todo This implementation is terrible. A good implementation would
  477. %% need to check that Bytes is exact (or we need to document that we
  478. %% trust it to be exact), and would need to send the file asynchronously
  479. %% in many data frames. Perhaps a sendfile call should result in a
  480. %% process being created specifically for this purpose. Or perhaps
  481. %% the protocol should be "dumb" and the stream handler be the one
  482. %% to ensure the file is sent in chunks (which would require a better
  483. %% flow control at the stream handler level). One thing for sure, the
  484. %% implementation necessarily varies between HTTP/1.1 and HTTP/2.
  485. commands(State0, Stream0=#stream{local=nofin},
  486. [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  487. {State, Stream} = send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
  488. commands(State, Stream, Tail);
  489. %% @todo sendfile when local!=nofin
  490. %% Send a push promise.
  491. %%
  492. %% @todo We need to keep track of what promises we made so that we don't
  493. %% end up with an infinite loop of promises.
  494. commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
  495. encode_state=EncodeState0}, Stream=#stream{id=StreamID},
  496. [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  497. Authority = case {Scheme, Port} of
  498. {<<"http">>, 80} -> Host;
  499. {<<"https">>, 443} -> Host;
  500. _ -> [Host, $:, integer_to_binary(Port)]
  501. end,
  502. PathWithQs = case Qs of
  503. <<>> -> Path;
  504. _ -> [Path, $?, Qs]
  505. end,
  506. Headers = Headers0#{<<":method">> => Method,
  507. <<":scheme">> => Scheme,
  508. <<":authority">> => Authority,
  509. <<":path">> => PathWithQs},
  510. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  511. Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
  512. %% @todo iolist_to_binary(HeaderBlock) isn't optimal. Need a shortcut.
  513. State = stream_init(State0#state{server_streamid=PromisedStreamID + 2, encode_state=EncodeState},
  514. PromisedStreamID, fin, iolist_to_binary(HeaderBlock)),
  515. commands(State, Stream, Tail);
  516. commands(State=#state{socket=Socket, transport=Transport, remote_window=ConnWindow},
  517. Stream=#stream{id=StreamID, remote_window=StreamWindow},
  518. [{flow, Size}|Tail]) ->
  519. Transport:send(Socket, [
  520. cow_http2:window_update(Size),
  521. cow_http2:window_update(StreamID, Size)
  522. ]),
  523. commands(State#state{remote_window=ConnWindow + Size},
  524. Stream#stream{remote_window=StreamWindow + Size}, Tail);
  525. %% Supervise a child process.
  526. commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
  527. [{spawn, Pid, _Shutdown}|Tail]) -> %% @todo Shutdown
  528. commands(State#state{children=[{Pid, StreamID}|Children]}, Stream, Tail);
  529. %% Error handling.
  530. commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
  531. %% @todo Do we want to run the commands after an internal_error?
  532. %% @todo Do we even allow commands after?
  533. %% @todo Only reset when the stream still exists.
  534. stream_reset(after_commands(State, Stream), StreamID, Error);
  535. %% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
  536. commands(State=#state{socket=Socket, transport=Transport},
  537. Stream=#stream{local=upgrade}, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
  538. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
  539. commands(State, Stream#stream{local=idle}, Tail);
  540. %% HTTP/2 has no support for the Upgrade mechanism.
  541. commands(State, Stream, [{switch_protocol, _Headers, _Mod, _ModState}|Tail]) ->
  542. %% @todo This is an error. Not sure what to do here yet.
  543. commands(State, Stream, Tail);
  544. commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
  545. %% @todo Do we want to run the commands after a stop?
  546. %% @todo Do we even allow commands after?
  547. stream_terminate(after_commands(State, Stream), StreamID, normal).
  548. after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
  549. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  550. State#state{streams=Streams}.
  551. status(Status) when is_integer(Status) ->
  552. integer_to_binary(Status);
  553. status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
  554. << H, T, U >>.
  555. %% @todo Should we ever want to implement the PRIORITY mechanism,
  556. %% this would be the place to do it. Right now, we just go over
  557. %% all streams and send what we can until either everything is
  558. %% sent or we run out of space in the window.
  559. send_data(State=#state{streams=Streams}) ->
  560. resume_streams(State, Streams, []).
  561. %% @todo When streams terminate we need to remove the stream.
  562. resume_streams(State, [], Acc) ->
  563. State#state{streams=lists:reverse(Acc)};
  564. %% While technically we should never get < 0 here, let's be on the safe side.
  565. resume_streams(State=#state{local_window=ConnWindow}, Streams, Acc)
  566. when ConnWindow =< 0 ->
  567. State#state{streams=lists:reverse(Acc, Streams)};
  568. %% We rely on send_data/2 to do all the necessary checks about the stream.
  569. resume_streams(State0, [Stream0|Tail], Acc) ->
  570. {State, Stream} = send_data(State0, Stream0),
  571. resume_streams(State, Tail, [Stream|Acc]).
  572. %% @todo We might want to print an error if local=fin.
  573. %%
  574. %% @todo It's possible that the stream terminates. We must remove it.
  575. send_data(State=#state{local_window=ConnWindow},
  576. Stream=#stream{local=IsFin, local_window=StreamWindow, local_buffer_size=BufferSize})
  577. when ConnWindow =< 0; IsFin =:= fin; StreamWindow =< 0; BufferSize =:= 0 ->
  578. {State, Stream};
  579. send_data(State0, Stream0=#stream{local_buffer=Q0, local_buffer_size=BufferSize}) ->
  580. %% We know there is an item in the queue.
  581. {{value, {IsFin, DataSize, Data}}, Q} = queue:out(Q0),
  582. {State, Stream} = send_data(State0,
  583. Stream0#stream{local_buffer=Q, local_buffer_size=BufferSize - DataSize},
  584. IsFin, Data),
  585. send_data(State, Stream).
  586. %% Send data immediately if we can, buffer otherwise.
  587. %% @todo We might want to print an error if local=fin.
  588. send_data(State=#state{local_window=ConnWindow},
  589. Stream=#stream{local_window=StreamWindow}, IsFin, Data)
  590. when ConnWindow =< 0; StreamWindow =< 0 ->
  591. {State, queue_data(Stream, IsFin, Data)};
  592. send_data(State=#state{socket=Socket, transport=Transport, local_window=ConnWindow},
  593. Stream=#stream{id=StreamID, local_window=StreamWindow}, IsFin, Data) ->
  594. MaxFrameSize = 16384, %% @todo Use the real SETTINGS_MAX_FRAME_SIZE set by the client.
  595. MaxSendSize = min(min(ConnWindow, StreamWindow), MaxFrameSize),
  596. case Data of
  597. {sendfile, Offset, Bytes, Path} when Bytes =< MaxSendSize ->
  598. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  599. Transport:sendfile(Socket, Path, Offset, Bytes),
  600. {State#state{local_window=ConnWindow - Bytes},
  601. Stream#stream{local=IsFin, local_window=StreamWindow - Bytes}};
  602. {sendfile, Offset, Bytes, Path} ->
  603. Transport:send(Socket, cow_http2:data_header(StreamID, nofin, MaxSendSize)),
  604. Transport:sendfile(Socket, Path, Offset, MaxSendSize),
  605. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  606. Stream#stream{local_window=StreamWindow - MaxSendSize},
  607. IsFin, {sendfile, Offset + MaxSendSize, Bytes - MaxSendSize, Path});
  608. Iolist0 ->
  609. IolistSize = iolist_size(Iolist0),
  610. if
  611. IolistSize =< MaxSendSize ->
  612. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Iolist0)),
  613. {State#state{local_window=ConnWindow - IolistSize},
  614. Stream#stream{local=IsFin, local_window=StreamWindow - IolistSize}};
  615. true ->
  616. {Iolist, More} = cowboy_iolists:split(MaxSendSize, Iolist0),
  617. Transport:send(Socket, cow_http2:data(StreamID, nofin, Iolist)),
  618. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  619. Stream#stream{local_window=StreamWindow - MaxSendSize},
  620. IsFin, More)
  621. end
  622. end.
  623. queue_data(Stream=#stream{local_buffer=Q0, local_buffer_size=Size0}, IsFin, Data) ->
  624. DataSize = case Data of
  625. {sendfile, _, Bytes, _} -> Bytes;
  626. Iolist -> iolist_size(Iolist)
  627. end,
  628. Q = queue:in({IsFin, DataSize, Data}, Q0),
  629. Stream#stream{local_buffer=Q, local_buffer_size=Size0 + DataSize}.
  630. -spec terminate(#state{}, _) -> no_return().
  631. terminate(undefined, Reason) ->
  632. exit({shutdown, Reason});
  633. terminate(#state{socket=Socket, transport=Transport, client_streamid=LastStreamID,
  634. streams=Streams, children=Children}, Reason) ->
  635. %% @todo We might want to optionally send the Reason value
  636. %% as debug data in the GOAWAY frame here. Perhaps more.
  637. Transport:send(Socket, cow_http2:goaway(LastStreamID, terminate_reason(Reason), <<>>)),
  638. terminate_all_streams(Streams, Reason, Children),
  639. Transport:close(Socket),
  640. exit({shutdown, Reason}).
  641. terminate_reason({connection_error, Reason, _}) -> Reason;
  642. terminate_reason({stop, _, _}) -> no_error;
  643. terminate_reason({socket_error, _, _}) -> internal_error;
  644. terminate_reason({internal_error, _, _}) -> internal_error.
  645. terminate_all_streams([], _, []) ->
  646. ok;
  647. %% This stream was already terminated and is now just flushing the data out. Skip it.
  648. terminate_all_streams([#stream{state=flush}|Tail], Reason, Children) ->
  649. terminate_all_streams(Tail, Reason, Children);
  650. terminate_all_streams([#stream{id=StreamID, state=StreamState}|Tail], Reason, Children0) ->
  651. stream_call_terminate(StreamID, Reason, StreamState),
  652. Children = stream_terminate_children(Children0, StreamID, []),
  653. terminate_all_streams(Tail, Reason, Children).
  654. %% Stream functions.
  655. stream_init(State0=#state{ref=Ref, socket=Socket, transport=Transport, peer=Peer, decode_state=DecodeState0},
  656. StreamID, IsFin, HeaderBlock) ->
  657. %% @todo Add clause for CONNECT requests (no scheme/path).
  658. try headers_decode(HeaderBlock, DecodeState0) of
  659. {Headers0=#{
  660. <<":method">> := Method,
  661. <<":scheme">> := Scheme,
  662. <<":authority">> := Authority,
  663. <<":path">> := PathWithQs}, DecodeState} ->
  664. State = State0#state{decode_state=DecodeState},
  665. Headers = maps:without([<<":method">>, <<":scheme">>, <<":authority">>, <<":path">>], Headers0),
  666. BodyLength = case Headers of
  667. _ when IsFin =:= fin ->
  668. 0;
  669. #{<<"content-length">> := <<"0">>} ->
  670. 0;
  671. #{<<"content-length">> := BinLength} ->
  672. Length = try
  673. cow_http_hd:parse_content_length(BinLength)
  674. catch _:_ ->
  675. terminate(State0, {stream_error, StreamID, protocol_error,
  676. 'The content-length header is invalid. (RFC7230 3.3.2)'})
  677. %% @todo Err should terminate here...
  678. end,
  679. Length;
  680. _ ->
  681. undefined
  682. end,
  683. {Host, Port} = cow_http_hd:parse_host(Authority),
  684. {Path, Qs} = cow_http:parse_fullpath(PathWithQs),
  685. Req = #{
  686. ref => Ref,
  687. pid => self(),
  688. streamid => StreamID,
  689. peer => Peer,
  690. method => Method,
  691. scheme => Scheme,
  692. host => Host,
  693. port => Port,
  694. path => Path,
  695. qs => Qs,
  696. version => 'HTTP/2',
  697. headers => Headers,
  698. has_body => IsFin =:= nofin,
  699. body_length => BodyLength
  700. },
  701. stream_handler_init(State, StreamID, IsFin, idle, Req);
  702. {_, DecodeState} ->
  703. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  704. State0#state{decode_state=DecodeState}
  705. catch _:_ ->
  706. terminate(State0, {connection_error, compression_error,
  707. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  708. end.
  709. stream_handler_init(State=#state{opts=Opts,
  710. local_settings=#{initial_window_size := RemoteWindow},
  711. remote_settings=#{initial_window_size := LocalWindow}},
  712. StreamID, RemoteIsFin, LocalIsFin, Req) ->
  713. try cowboy_stream:init(StreamID, Req, Opts) of
  714. {Commands, StreamState} ->
  715. commands(State#state{client_streamid=StreamID},
  716. #stream{id=StreamID, state=StreamState,
  717. remote=RemoteIsFin, local=LocalIsFin,
  718. local_window=LocalWindow, remote_window=RemoteWindow},
  719. Commands)
  720. catch Class:Reason ->
  721. error_logger:error_msg("Exception occurred in "
  722. "cowboy_stream:init(~p, ~p, ~p) with reason ~p:~p.",
  723. [StreamID, Req, Opts, Class, Reason]),
  724. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  725. 'Exception occurred in cowboy_stream:init/3.'})
  726. end.
  727. %% @todo We might need to keep track of which stream has been reset so we don't send lots of them.
  728. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID,
  729. StreamError={internal_error, _, _}) ->
  730. Transport:send(Socket, cow_http2:rst_stream(StreamID, internal_error)),
  731. stream_terminate(State, StreamID, StreamError);
  732. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID,
  733. StreamError={stream_error, Reason, _}) ->
  734. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  735. stream_terminate(State, StreamID, StreamError).
  736. stream_terminate(State=#state{socket=Socket, transport=Transport,
  737. streams=Streams0, children=Children0}, StreamID, Reason) ->
  738. case lists:keytake(StreamID, #stream.id, Streams0) of
  739. %% When the stream terminates normally (without sending RST_STREAM)
  740. %% and no response was sent, we need to send a proper response back to the client.
  741. {value, #stream{state=StreamState, local=idle}, Streams} when Reason =:= normal ->
  742. State1 = info(State, StreamID, {response, 204, #{}, <<>>}),
  743. stream_call_terminate(StreamID, Reason, StreamState),
  744. Children = stream_terminate_children(Children0, StreamID, []),
  745. State1#state{streams=Streams, children=Children};
  746. %% When a response was sent but not terminated, we need to close the stream.
  747. {value, #stream{state=StreamState, local=nofin, local_buffer_size=0}, Streams}
  748. when Reason =:= normal ->
  749. Transport:send(Socket, cow_http2:data(StreamID, fin, <<>>)),
  750. stream_call_terminate(StreamID, Reason, StreamState),
  751. Children = stream_terminate_children(Children0, StreamID, []),
  752. State#state{streams=Streams, children=Children};
  753. %% Unless there is still data in the buffer. We can however reset
  754. %% a few fields and set a special local state to avoid confusion.
  755. {value, Stream=#stream{state=StreamState, local=nofin}, Streams} ->
  756. stream_call_terminate(StreamID, Reason, StreamState),
  757. Children = stream_terminate_children(Children0, StreamID, []),
  758. State#state{streams=[Stream#stream{state=flush, local=flush}|Streams],
  759. children=Children};
  760. %% Otherwise we sent an RST_STREAM and/or the stream is already closed.
  761. {value, #stream{state=StreamState}, Streams} ->
  762. stream_call_terminate(StreamID, Reason, StreamState),
  763. Children = stream_terminate_children(Children0, StreamID, []),
  764. State#state{streams=Streams, children=Children};
  765. false ->
  766. %% @todo Unknown stream. Not sure what to do here. Check again once all
  767. %% terminate calls have been written.
  768. State
  769. end.
  770. stream_call_terminate(StreamID, Reason, StreamState) ->
  771. try
  772. cowboy_stream:terminate(StreamID, Reason, StreamState)
  773. catch Class:Reason ->
  774. error_logger:error_msg("Exception occurred in "
  775. "cowboy_stream:terminate(~p, ~p, ~p) with reason ~p:~p.",
  776. [StreamID, Reason, StreamState, Class, Reason])
  777. end.
  778. stream_terminate_children([], _, Acc) ->
  779. Acc;
  780. stream_terminate_children([{Pid, StreamID}|Tail], StreamID, Acc) ->
  781. %% We unlink and flush the mailbox to avoid receiving a stray message.
  782. unlink(Pid),
  783. receive {'EXIT', Pid, _} -> ok after 0 -> ok end,
  784. exit(Pid, kill),
  785. stream_terminate_children(Tail, StreamID, Acc);
  786. stream_terminate_children([Child|Tail], StreamID, Acc) ->
  787. stream_terminate_children(Tail, StreamID, [Child|Acc]).
  788. %% Headers encode/decode.
  789. headers_decode(HeaderBlock, DecodeState0) ->
  790. {Headers, DecodeState} = cow_hpack:decode(HeaderBlock, DecodeState0),
  791. {headers_to_map(Headers, #{}), DecodeState}.
  792. %% This function is necessary to properly handle duplicate headers
  793. %% and the special-case cookie header.
  794. headers_to_map([], Acc) ->
  795. Acc;
  796. headers_to_map([{Name, Value}|Tail], Acc0) ->
  797. Acc = case Acc0 of
  798. %% The cookie header does not use proper HTTP header lists.
  799. #{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  800. #{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  801. _ -> Acc0#{Name => Value}
  802. end,
  803. headers_to_map(Tail, Acc).
  804. %% The set-cookie header is special; we can only send one cookie per header.
  805. headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
  806. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  807. Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
  808. cow_hpack:encode(Headers, EncodeState);
  809. headers_encode(Headers0, EncodeState) ->
  810. Headers = maps:to_list(Headers0),
  811. cow_hpack:encode(Headers, EncodeState).
  812. %% System callbacks.
  813. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  814. system_continue(_, _, {State, Buffer}) ->
  815. loop(State, Buffer).
  816. -spec system_terminate(any(), _, _, _) -> no_return().
  817. system_terminate(Reason, _, _, _) ->
  818. exit(Reason).
  819. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  820. system_code_change(Misc, _, _, _) ->
  821. {ok, Misc}.