cowboy_spdy.erl 14 KB

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