ranch_ssl.erl 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. %% Copyright (c) 2011-2012, 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 SSL transport API.
  15. %%
  16. %% Wrapper around <em>ssl</em> implementing the Ranch transport API.
  17. %%
  18. %% This transport requires the <em>crypto</em>, <em>public_key</em>
  19. %% and <em>ssl</em> applications to be started. If they aren't started,
  20. %% it will try to start them itself before opening a port to listen.
  21. %% Applications aren't stopped when the listening socket is closed, though.
  22. %%
  23. %% @see ssl
  24. -module(ranch_ssl).
  25. -export([name/0]).
  26. -export([messages/0]).
  27. -export([connect/3]).
  28. -export([listen/1]).
  29. -export([accept/2]).
  30. -export([recv/3]).
  31. -export([send/2]).
  32. -export([setopts/2]).
  33. -export([controlling_process/2]).
  34. -export([peername/1]).
  35. -export([close/1]).
  36. -export([sockname/1]).
  37. %% @doc Name of this transport API, <em>ssl</em>.
  38. -spec name() -> ssl.
  39. name() -> ssl.
  40. %% @doc Atoms used in the process messages sent by this API.
  41. %%
  42. %% They identify incoming data, closed connection and errors when receiving
  43. %% data in active mode.
  44. -spec messages() -> {ssl, ssl_closed, ssl_error}.
  45. messages() -> {ssl, ssl_closed, ssl_error}.
  46. %% @private
  47. %% @todo Probably filter Opts?
  48. -spec connect(string(), inet:port_number(), any())
  49. -> {ok, inet:socket()} | {error, atom()}.
  50. connect(Host, Port, Opts) when is_list(Host), is_integer(Port) ->
  51. ssl:connect(Host, Port,
  52. Opts ++ [binary, {active, false}, {packet, raw}]).
  53. %% @doc Setup a socket to listen on the given port on the local host.
  54. %%
  55. %% The available options are:
  56. %% <dl>
  57. %% <dt>port</dt><dd>Mandatory. TCP port number to open.</dd>
  58. %% <dt>backlog</dt><dd>Maximum length of the pending connections queue.
  59. %% Defaults to 1024.</dd>
  60. %% <dt>ip</dt><dd>Interface to listen on. Listen on all interfaces
  61. %% by default.</dd>
  62. %% <dt>certfile</dt><dd>Mandatory. Path to a file containing the user's
  63. %% certificate.</dd>
  64. %% <dt>keyfile</dt><dd>Optional. Path to the file containing the user's
  65. %% private PEM encoded key.</dd>
  66. %% <dt>cacertfile</dt><dd>Optional. Path to file containing PEM encoded
  67. %% CA certificates (trusted certificates used for verifying a peer
  68. %% certificate).</dd>
  69. %% <dt>password</dt><dd>Optional. String containing the user's password.
  70. %% All private keyfiles must be password protected currently.</dd>
  71. %% <dt>ciphers</dt><dd>Optional. The cipher suites that should be supported.
  72. %% The function ssl:cipher_suites/0 can be used to find all available
  73. %% ciphers.</dd>
  74. %% </dl>
  75. %%
  76. %% @see ssl:listen/2
  77. -spec listen([{port, inet:port_number()} | {certfile, string()}
  78. | {keyfile, string()} | {password, string()}
  79. | {cacertfile, string()} | {ip, inet:ip_address()}])
  80. -> {ok, ssl:sslsocket()} | {error, atom()}.
  81. listen(Opts) ->
  82. require([crypto, public_key, ssl]),
  83. {port, Port} = lists:keyfind(port, 1, Opts),
  84. Backlog = proplists:get_value(backlog, Opts, 1024),
  85. {certfile, CertFile} = lists:keyfind(certfile, 1, Opts),
  86. ListenOpts0 = [binary, {active, false},
  87. {backlog, Backlog}, {packet, raw}, {reuseaddr, true},
  88. {certfile, CertFile}],
  89. ListenOpts = lists:foldl(fun
  90. ({ip, _} = Ip, Acc) -> [Ip | Acc];
  91. ({keyfile, _} = KeyFile, Acc) -> [KeyFile | Acc];
  92. ({cacertfile, _} = CACertFile, Acc) -> [CACertFile | Acc];
  93. ({password, _} = Password, Acc) -> [Password | Acc];
  94. ({ciphers, _} = Ciphers, Acc) -> [Ciphers | Acc];
  95. (_, Acc) -> Acc
  96. end, ListenOpts0, Opts),
  97. ssl:listen(Port, ListenOpts).
  98. %% @doc Accept an incoming connection on a listen socket.
  99. %%
  100. %% Note that this function does both the transport accept and
  101. %% the SSL handshake.
  102. %%
  103. %% @see ssl:transport_accept/2
  104. %% @see ssl:ssl_accept/2
  105. -spec accept(ssl:sslsocket(), timeout())
  106. -> {ok, ssl:sslsocket()} | {error, closed | timeout | atom() | tuple()}.
  107. accept(LSocket, Timeout) ->
  108. case ssl:transport_accept(LSocket, Timeout) of
  109. {ok, CSocket} ->
  110. ssl_accept(CSocket, Timeout);
  111. {error, Reason} ->
  112. {error, Reason}
  113. end.
  114. %% @doc Receive a packet from a socket in passive mode.
  115. %% @see ssl:recv/3
  116. -spec recv(ssl:sslsocket(), non_neg_integer(), timeout())
  117. -> {ok, any()} | {error, closed | atom()}.
  118. recv(Socket, Length, Timeout) ->
  119. ssl:recv(Socket, Length, Timeout).
  120. %% @doc Send a packet on a socket.
  121. %% @see ssl:send/2
  122. -spec send(ssl:sslsocket(), iolist()) -> ok | {error, atom()}.
  123. send(Socket, Packet) ->
  124. ssl:send(Socket, Packet).
  125. %% @doc Set one or more options for a socket.
  126. %% @see ssl:setopts/2
  127. -spec setopts(ssl:sslsocket(), list()) -> ok | {error, atom()}.
  128. setopts(Socket, Opts) ->
  129. ssl:setopts(Socket, Opts).
  130. %% @doc Assign a new controlling process <em>Pid</em> to <em>Socket</em>.
  131. %% @see ssl:controlling_process/2
  132. -spec controlling_process(ssl:sslsocket(), pid())
  133. -> ok | {error, closed | not_owner | atom()}.
  134. controlling_process(Socket, Pid) ->
  135. ssl:controlling_process(Socket, Pid).
  136. %% @doc Return the address and port for the other end of a connection.
  137. %% @see ssl:peername/1
  138. -spec peername(ssl:sslsocket())
  139. -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
  140. peername(Socket) ->
  141. ssl:peername(Socket).
  142. %% @doc Close a TCP socket.
  143. %% @see ssl:close/1
  144. -spec close(ssl:sslsocket()) -> ok.
  145. close(Socket) ->
  146. ssl:close(Socket).
  147. %% @doc Get the local address and port of a socket
  148. %% @see ssl:sockname/1
  149. -spec sockname(ssl:sslsocket())
  150. -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
  151. sockname(Socket) ->
  152. ssl:sockname(Socket).
  153. %% Internal.
  154. -spec require(list(module())) -> ok.
  155. require([]) ->
  156. ok;
  157. require([App|Tail]) ->
  158. case application:start(App) of
  159. ok -> ok;
  160. {error, {already_started, App}} -> ok
  161. end,
  162. require(Tail).
  163. -spec ssl_accept(ssl:sslsocket(), timeout())
  164. -> {ok, ssl:sslsocket()} | {error, {ssl_accept, atom()}}.
  165. ssl_accept(Socket, Timeout) ->
  166. case ssl:ssl_accept(Socket, Timeout) of
  167. ok ->
  168. {ok, Socket};
  169. {error, Reason} ->
  170. {error, {ssl_accept, Reason}}
  171. end.