cowboy_spdy.erl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. %% Copyright (c) 2013, 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. %% @doc SPDY protocol handler.
  15. %%
  16. %% Note that there is no need to monitor these processes when using Cowboy as
  17. %% an application as it already supervises them under the listener supervisor.
  18. -module(cowboy_spdy).
  19. %% API.
  20. -export([start_link/4]).
  21. %% Internal.
  22. -export([init/5]).
  23. -export([system_continue/3]).
  24. -export([system_terminate/4]).
  25. -export([system_code_change/4]).
  26. %% Internal request process.
  27. -export([request_init/11]).
  28. -export([resume/5]).
  29. -export([reply/4]).
  30. -export([stream_reply/3]).
  31. -export([stream_data/2]).
  32. -export([stream_close/1]).
  33. %% Internal transport functions.
  34. -export([name/0]).
  35. -export([recv/3]).
  36. -export([send/2]).
  37. -export([sendfile/2]).
  38. -record(child, {
  39. streamid :: non_neg_integer(),
  40. pid :: pid(),
  41. input = nofin :: fin | nofin,
  42. in_buffer = <<>> :: binary(),
  43. is_recv = false :: {true, {non_neg_integer(), pid()},
  44. pid(), non_neg_integer(), reference()} | false,
  45. output = nofin :: fin | nofin
  46. }).
  47. -record(state, {
  48. parent = undefined :: pid(),
  49. socket,
  50. transport,
  51. buffer = <<>> :: binary(),
  52. middlewares,
  53. env,
  54. onrequest,
  55. onresponse,
  56. peer,
  57. zdef,
  58. zinf,
  59. last_streamid = 0 :: non_neg_integer(),
  60. children = [] :: [#child{}]
  61. }).
  62. -type opts() :: [{env, cowboy_middleware:env()}
  63. | {middlewares, [module()]}
  64. | {onrequest, cowboy:onrequest_fun()}
  65. | {onresponse, cowboy:onresponse_fun()}].
  66. -export_type([opts/0]).
  67. %% API.
  68. %% @doc Start a SPDY protocol process.
  69. -spec start_link(any(), inet:socket(), module(), any()) -> {ok, pid()}.
  70. start_link(Ref, Socket, Transport, Opts) ->
  71. proc_lib:start_link(?MODULE, init,
  72. [self(), Ref, Socket, Transport, Opts]).
  73. %% Internal.
  74. %% @doc Faster alternative to proplists:get_value/3.
  75. %% @private
  76. get_value(Key, Opts, Default) ->
  77. case lists:keyfind(Key, 1, Opts) of
  78. {_, Value} -> Value;
  79. _ -> Default
  80. end.
  81. %% @private
  82. -spec init(pid(), ranch:ref(), inet:socket(), module(), opts()) -> ok.
  83. init(Parent, Ref, Socket, Transport, Opts) ->
  84. process_flag(trap_exit, true),
  85. ok = proc_lib:init_ack(Parent, {ok, self()}),
  86. {ok, Peer} = Transport:peername(Socket),
  87. Middlewares = get_value(middlewares, Opts, [cowboy_router, cowboy_handler]),
  88. Env = [{listener, Ref}|get_value(env, Opts, [])],
  89. OnRequest = get_value(onrequest, Opts, undefined),
  90. OnResponse = get_value(onresponse, Opts, undefined),
  91. Zdef = cow_spdy:deflate_init(),
  92. Zinf = cow_spdy:inflate_init(),
  93. ok = ranch:accept_ack(Ref),
  94. loop(#state{parent=Parent, socket=Socket, transport=Transport,
  95. middlewares=Middlewares, env=Env, onrequest=OnRequest,
  96. onresponse=OnResponse, peer=Peer, zdef=Zdef, zinf=Zinf}).
  97. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  98. buffer=Buffer, zinf=Zinf, children=Children}) ->
  99. {OK, Closed, Error} = Transport:messages(),
  100. Transport:setopts(Socket, [{active, once}]),
  101. receive
  102. {OK, Socket, Data} ->
  103. Data2 = << Buffer/binary, Data/binary >>,
  104. case cow_spdy:split(Data2) of
  105. {true, Frame, Rest} ->
  106. P = cow_spdy:parse(Frame, Zinf),
  107. handle_frame(State#state{buffer=Rest}, P);
  108. false ->
  109. loop(State#state{buffer=Data2})
  110. end;
  111. {Closed, Socket} ->
  112. terminate(State);
  113. {Error, Socket, _Reason} ->
  114. terminate(State);
  115. {recv, FromSocket = {Pid, StreamID}, FromPid, Length, Timeout}
  116. when Pid =:= self() ->
  117. Child = #child{in_buffer=InBuffer, is_recv=false}
  118. = get_child(StreamID, State),
  119. if
  120. Length =:= 0, InBuffer =/= <<>> ->
  121. FromPid ! {recv, FromSocket, {ok, InBuffer}},
  122. loop(replace_child(Child#child{in_buffer= <<>>}, State));
  123. byte_size(InBuffer) >= Length ->
  124. << Data:Length/binary, Rest/binary >> = InBuffer,
  125. FromPid ! {recv, FromSocket, {ok, Data}},
  126. loop(replace_child(Child#child{in_buffer=Rest}, State));
  127. true ->
  128. TRef = erlang:send_after(Timeout, self(),
  129. {recv_timeout, FromSocket}),
  130. loop(replace_child(Child#child{
  131. is_recv={true, FromSocket, FromPid, Length, TRef}},
  132. State))
  133. end;
  134. {recv_timeout, {Pid, StreamID}}
  135. when Pid =:= self() ->
  136. Child = #child{is_recv={true, FromSocket, FromPid, _, _}}
  137. = get_child(StreamID, State),
  138. FromPid ! {recv, FromSocket, {error, timeout}},
  139. loop(replace_child(Child#child{is_recv=false}, State));
  140. {reply, {Pid, StreamID}, Status, Headers}
  141. when Pid =:= self() ->
  142. Child = #child{output=nofin} = get_child(StreamID, State),
  143. syn_reply(State, StreamID, true, Status, Headers),
  144. loop(replace_child(Child#child{output=fin}, State));
  145. {reply, {Pid, StreamID}, Status, Headers, Body}
  146. when Pid =:= self() ->
  147. Child = #child{output=nofin} = get_child(StreamID, State),
  148. syn_reply(State, StreamID, false, Status, Headers),
  149. data(State, StreamID, true, Body),
  150. loop(replace_child(Child#child{output=fin}, State));
  151. {stream_reply, {Pid, StreamID}, Status, Headers}
  152. when Pid =:= self() ->
  153. #child{output=nofin} = get_child(StreamID, State),
  154. syn_reply(State, StreamID, false, Status, Headers),
  155. loop(State);
  156. {stream_data, {Pid, StreamID}, Data}
  157. when Pid =:= self() ->
  158. #child{output=nofin} = get_child(StreamID, State),
  159. data(State, StreamID, false, Data),
  160. loop(State);
  161. {stream_close, {Pid, StreamID}}
  162. when Pid =:= self() ->
  163. Child = #child{output=nofin} = get_child(StreamID, State),
  164. data(State, StreamID, true, <<>>),
  165. loop(replace_child(Child#child{output=fin}, State));
  166. {sendfile, {Pid, StreamID}, Filepath}
  167. when Pid =:= self() ->
  168. Child = #child{output=nofin} = get_child(StreamID, State),
  169. data_from_file(State, StreamID, Filepath),
  170. loop(replace_child(Child#child{output=fin}, State));
  171. {'EXIT', Parent, Reason} ->
  172. exit(Reason);
  173. {'EXIT', Pid, _} ->
  174. %% @todo Report the error if any.
  175. loop(delete_child(Pid, State));
  176. {system, From, Request} ->
  177. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], State);
  178. %% Calls from the supervisor module.
  179. {'$gen_call', {To, Tag}, which_children} ->
  180. Workers = [{?MODULE, Pid, worker, [?MODULE]}
  181. || #child{pid=Pid} <- Children],
  182. To ! {Tag, Workers},
  183. loop(State);
  184. {'$gen_call', {To, Tag}, count_children} ->
  185. NbChildren = length(Children),
  186. Counts = [{specs, 1}, {active, NbChildren},
  187. {supervisors, 0}, {workers, NbChildren}],
  188. To ! {Tag, Counts},
  189. loop(State);
  190. {'$gen_call', {To, Tag}, _} ->
  191. To ! {Tag, {error, ?MODULE}},
  192. loop(State)
  193. after 60000 ->
  194. goaway(State, ok),
  195. terminate(State)
  196. end.
  197. system_continue(_, _, State) ->
  198. loop(State).
  199. -spec system_terminate(any(), _, _, _) -> no_return().
  200. system_terminate(Reason, _, _, _) ->
  201. exit(Reason).
  202. system_code_change(Misc, _, _, _) ->
  203. {ok, Misc}.
  204. %% FLAG_UNIDIRECTIONAL can only be set by the server.
  205. handle_frame(State, {syn_stream, StreamID, _, _, true,
  206. _, _, _, _, _, _, _}) ->
  207. rst_stream(State, StreamID, protocol_error),
  208. loop(State);
  209. %% We do not support Associated-To-Stream-ID.
  210. handle_frame(State, {syn_stream, StreamID, AssocToStreamID,
  211. _, _, _, _, _, _, _, _, _}) when AssocToStreamID =/= 0 ->
  212. rst_stream(State, StreamID, internal_error),
  213. loop(State);
  214. %% SYN_STREAM.
  215. %%
  216. %% Erlang does not allow us to control the priority of processes
  217. %% so we ignore that value entirely.
  218. handle_frame(State=#state{middlewares=Middlewares, env=Env,
  219. onrequest=OnRequest, onresponse=OnResponse, peer=Peer},
  220. {syn_stream, StreamID, _, IsFin, _, _,
  221. Method, _, Host, Path, Version, Headers}) ->
  222. Pid = spawn_link(?MODULE, request_init, [
  223. {self(), StreamID}, Peer, OnRequest, OnResponse,
  224. Env, Middlewares, Method, Host, Path, Version, Headers
  225. ]),
  226. loop(new_child(State, StreamID, Pid, IsFin));
  227. %% RST_STREAM.
  228. handle_frame(State, {rst_stream, StreamID, Status}) ->
  229. error_logger:error_msg("Received RST_STREAM frame ~p ~p",
  230. [StreamID, Status]),
  231. %% @todo Stop StreamID.
  232. loop(State);
  233. %% PING initiated by the server; ignore, we don't send any.
  234. handle_frame(State, {ping, PingID}) when PingID rem 2 =:= 0 ->
  235. error_logger:error_msg("Ignored PING control frame: ~p~n", [PingID]),
  236. loop(State);
  237. %% PING initiated by the client; send it back.
  238. handle_frame(State=#state{socket=Socket, transport=Transport},
  239. {ping, PingID}) ->
  240. Transport:send(Socket, cow_spdy:ping(PingID)),
  241. loop(State);
  242. %% Data received for a stream.
  243. handle_frame(State, {data, StreamID, IsFin, Data}) ->
  244. Child = #child{input=nofin, in_buffer=Buffer, is_recv=IsRecv}
  245. = get_child(StreamID, State),
  246. Data2 = << Buffer/binary, Data/binary >>,
  247. IsFin2 = if IsFin -> fin; true -> nofin end,
  248. Child2 = case IsRecv of
  249. {true, FromSocket, FromPid, 0, TRef} ->
  250. FromPid ! {recv, FromSocket, {ok, Data2}},
  251. cancel_recv_timeout(StreamID, TRef),
  252. Child#child{input=IsFin2, in_buffer= <<>>, is_recv=false};
  253. {true, FromSocket, FromPid, Length, TRef}
  254. when byte_size(Data2) >= Length ->
  255. << Data3:Length/binary, Rest/binary >> = Data2,
  256. FromPid ! {recv, FromSocket, {ok, Data3}},
  257. cancel_recv_timeout(StreamID, TRef),
  258. Child#child{input=IsFin2, in_buffer=Rest, is_recv=false};
  259. _ ->
  260. Child#child{input=IsFin2, in_buffer=Data2}
  261. end,
  262. loop(replace_child(Child2, State));
  263. %% General error, can't recover.
  264. handle_frame(State, {error, badprotocol}) ->
  265. goaway(State, protocol_error),
  266. terminate(State);
  267. %% Ignore all other frames for now.
  268. handle_frame(State, Frame) ->
  269. error_logger:error_msg("Ignored frame ~p", [Frame]),
  270. loop(State).
  271. cancel_recv_timeout(StreamID, TRef) ->
  272. _ = erlang:cancel_timer(TRef),
  273. receive
  274. {recv_timeout, {Pid, StreamID}}
  275. when Pid =:= self() ->
  276. ok
  277. after 0 ->
  278. ok
  279. end.
  280. %% @todo We must wait for the children to finish here,
  281. %% but only up to N milliseconds. Then we shutdown.
  282. terminate(_State) ->
  283. ok.
  284. syn_reply(#state{socket=Socket, transport=Transport, zdef=Zdef},
  285. StreamID, IsFin, Status, Headers) ->
  286. Transport:send(Socket, cow_spdy:syn_reply(Zdef, StreamID, IsFin,
  287. Status, <<"HTTP/1.1">>, Headers)).
  288. rst_stream(#state{socket=Socket, transport=Transport}, StreamID, Status) ->
  289. Transport:send(Socket, cow_spdy:rst_stream(StreamID, Status)).
  290. goaway(#state{socket=Socket, transport=Transport, last_streamid=LastStreamID},
  291. Status) ->
  292. Transport:send(Socket, cow_spdy:goaway(LastStreamID, Status)).
  293. data(#state{socket=Socket, transport=Transport}, StreamID, IsFin, Data) ->
  294. Transport:send(Socket, cow_spdy:data(StreamID, IsFin, Data)).
  295. data_from_file(#state{socket=Socket, transport=Transport},
  296. StreamID, Filepath) ->
  297. {ok, IoDevice} = file:open(Filepath, [read, binary, raw]),
  298. data_from_file(Socket, Transport, StreamID, IoDevice).
  299. data_from_file(Socket, Transport, StreamID, IoDevice) ->
  300. case file:read(IoDevice, 16#1fff) of
  301. eof ->
  302. _ = Transport:send(Socket, cow_spdy:data(StreamID, true, <<>>)),
  303. ok;
  304. {ok, Data} ->
  305. case Transport:send(Socket, cow_spdy:data(StreamID, false, Data)) of
  306. ok ->
  307. data_from_file(Socket, Transport, StreamID, IoDevice);
  308. {error, _} ->
  309. ok
  310. end
  311. end.
  312. %% Children.
  313. new_child(State=#state{children=Children}, StreamID, Pid, IsFin) ->
  314. IsFin2 = if IsFin -> fin; true -> nofin end,
  315. State#state{last_streamid=StreamID,
  316. children=[#child{streamid=StreamID,
  317. pid=Pid, input=IsFin2}|Children]}.
  318. get_child(StreamID, #state{children=Children}) ->
  319. lists:keyfind(StreamID, #child.streamid, Children).
  320. replace_child(Child=#child{streamid=StreamID},
  321. State=#state{children=Children}) ->
  322. Children2 = lists:keyreplace(StreamID, #child.streamid, Children, Child),
  323. State#state{children=Children2}.
  324. delete_child(Pid, State=#state{children=Children}) ->
  325. Children2 = lists:keydelete(Pid, #child.pid, Children),
  326. State#state{children=Children2}.
  327. %% Request process.
  328. request_init(FakeSocket, Peer, OnRequest, OnResponse,
  329. Env, Middlewares, Method, Host, Path, Version, Headers) ->
  330. {Host2, Port} = cow_http:parse_fullhost(Host),
  331. {Path2, Qs} = cow_http:parse_fullpath(Path),
  332. Version2 = cow_http:parse_version(Version),
  333. Req = cowboy_req:new(FakeSocket, ?MODULE, Peer,
  334. Method, Path2, Qs, Version2, Headers,
  335. Host2, Port, <<>>, true, false, OnResponse),
  336. case OnRequest of
  337. undefined ->
  338. execute(Req, Env, Middlewares);
  339. _ ->
  340. Req2 = OnRequest(Req),
  341. case cowboy_req:get(resp_state, Req2) of
  342. waiting -> execute(Req2, Env, Middlewares);
  343. _ -> ok
  344. end
  345. end.
  346. -spec execute(cowboy_req:req(), cowboy_middleware:env(), [module()])
  347. -> ok.
  348. execute(Req, _, []) ->
  349. cowboy_req:ensure_response(Req, 204);
  350. execute(Req, Env, [Middleware|Tail]) ->
  351. case Middleware:execute(Req, Env) of
  352. {ok, Req2, Env2} ->
  353. execute(Req2, Env2, Tail);
  354. {suspend, Module, Function, Args} ->
  355. erlang:hibernate(?MODULE, resume,
  356. [Env, Tail, Module, Function, Args]);
  357. {halt, Req2} ->
  358. cowboy_req:ensure_response(Req2, 204);
  359. {error, Status, Req2} ->
  360. cowboy_req:maybe_reply(Status, Req2)
  361. end.
  362. %% @private
  363. -spec resume(cowboy_middleware:env(), [module()],
  364. module(), module(), [any()]) -> ok.
  365. resume(Env, Tail, Module, Function, Args) ->
  366. case apply(Module, Function, Args) of
  367. {ok, Req2, Env2} ->
  368. execute(Req2, Env2, Tail);
  369. {suspend, Module2, Function2, Args2} ->
  370. erlang:hibernate(?MODULE, resume,
  371. [Env, Tail, Module2, Function2, Args2]);
  372. {halt, Req2} ->
  373. cowboy_req:ensure_response(Req2, 204);
  374. {error, Status, Req2} ->
  375. cowboy_req:maybe_reply(Status, Req2)
  376. end.
  377. %% Reply functions used by cowboy_req.
  378. reply(Socket = {Pid, _}, Status, Headers, Body) ->
  379. _ = case iolist_size(Body) of
  380. 0 -> Pid ! {reply, Socket, Status, Headers};
  381. _ -> Pid ! {reply, Socket, Status, Headers, Body}
  382. end,
  383. ok.
  384. stream_reply(Socket = {Pid, _}, Status, Headers) ->
  385. _ = Pid ! {stream_reply, Socket, Status, Headers},
  386. ok.
  387. stream_data(Socket = {Pid, _}, Data) ->
  388. _ = Pid ! {stream_data, Socket, Data},
  389. ok.
  390. stream_close(Socket = {Pid, _}) ->
  391. _ = Pid ! {stream_close, Socket},
  392. ok.
  393. %% Internal transport functions.
  394. name() ->
  395. spdy.
  396. recv(Socket = {Pid, _}, Length, Timeout) ->
  397. _ = Pid ! {recv, Socket, self(), Length, Timeout},
  398. receive
  399. {recv, Socket, Ret} ->
  400. Ret
  401. end.
  402. send(Socket, Data) ->
  403. stream_data(Socket, Data).
  404. %% We don't wait for the result of the actual sendfile call,
  405. %% therefore we can't know how much was actually sent.
  406. %% This isn't a problem as we don't use this value in Cowboy.
  407. sendfile(Socket = {Pid, _}, Filepath) ->
  408. _ = Pid ! {sendfile, Socket, Filepath},
  409. {ok, undefined}.