cowboy_spdy.erl 16 KB

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