cowboy_tls.erl 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. -behavior(ranch_protocol).
  16. -export([start_link/4]).
  17. -export([proc_lib_hack/5]).
  18. -spec start_link(ranch:ref(), inet:socket(), module(), cowboy:opts()) -> {ok, pid()}.
  19. start_link(Ref, Socket, Transport, Opts) ->
  20. Pid = proc_lib:spawn_link(?MODULE, proc_lib_hack, [self(), Ref, Socket, Transport, Opts]),
  21. {ok, Pid}.
  22. -spec proc_lib_hack(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  23. proc_lib_hack(Parent, Ref, Socket, Transport, Opts) ->
  24. try
  25. init(Parent, Ref, Socket, Transport, Opts)
  26. catch
  27. _:normal -> exit(normal);
  28. _:shutdown -> exit(shutdown);
  29. _:Reason = {shutdown, _} -> exit(Reason);
  30. _:Reason -> exit({Reason, erlang:get_stacktrace()})
  31. end.
  32. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  33. init(Parent, Ref, Socket, Transport, Opts) ->
  34. ok = ranch:accept_ack(Ref),
  35. case ssl:negotiated_protocol(Socket) of
  36. {ok, <<"h2">>} ->
  37. init(Parent, Ref, Socket, Transport, Opts, cowboy_http2);
  38. _ -> %% http/1.1 or no protocol negotiated.
  39. init(Parent, Ref, Socket, Transport, Opts, cowboy_http)
  40. end.
  41. init(Parent, Ref, Socket, Transport, Opts, Protocol) ->
  42. {Handler, Type} = maps:get(stream_handler, Opts, {cowboy_stream_h, supervisor}),
  43. _ = case Type of
  44. worker -> ok;
  45. supervisor -> process_flag(trap_exit, true)
  46. end,
  47. Protocol:init(Parent, Ref, Socket, Transport, Opts, Handler).