cowboy_tls.erl 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. %% Copyright (c) 2015, 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_tls).
  15. -export([start_link/4]).
  16. -export([init/5]).
  17. -spec start_link(ranch:ref(), inet:socket(), module(), cowboy:opts()) -> {ok, pid()}.
  18. start_link(Ref, Socket, Transport, Opts) ->
  19. Pid = proc_lib:spawn_link(?MODULE, init, [self(), Ref, Socket, Transport, Opts]),
  20. {ok, Pid}.
  21. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  22. init(Parent, Ref, Socket, Transport, Opts) ->
  23. ok = ranch:accept_ack(Ref),
  24. case ssl:negotiated_protocol(Socket) of
  25. {ok, <<"h2">>} ->
  26. init(Parent, Ref, Socket, Transport, Opts, cowboy_http2);
  27. %% @todo Implement cowboy_spdy and cowboy_http.
  28. {ok, <<"spdy/3">>} ->
  29. init(Parent, Ref, Socket, Transport, Opts, cowboy_spdy);
  30. _ -> %% http/1.1 or no protocol negotiated.
  31. init(Parent, Ref, Socket, Transport, Opts, cowboy_http)
  32. end.
  33. init(Parent, Ref, Socket, Transport, Opts, Protocol) ->
  34. {Handler, Type} = maps:get(stream_handler, Opts, {cowboy_stream_h, supervisor}),
  35. _ = case Type of
  36. worker -> ok;
  37. supervisor -> process_flag(trap_exit, true)
  38. end,
  39. Protocol:init(Parent, Ref, Socket, Transport, Opts, Handler).