ranch_ssl.erl 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. -behaviour(ranch_transport).
  26. -export([name/0]).
  27. -export([messages/0]).
  28. -export([listen/1]).
  29. -export([accept/2]).
  30. -export([connect/3]).
  31. -export([recv/3]).
  32. -export([send/2]).
  33. -export([sendfile/2]).
  34. -export([setopts/2]).
  35. -export([controlling_process/2]).
  36. -export([peername/1]).
  37. -export([sockname/1]).
  38. -export([close/1]).
  39. %% @doc Name of this transport, <em>ssl</em>.
  40. name() -> ssl.
  41. %% @doc Atoms used to identify messages in {active, once | true} mode.
  42. messages() -> {ssl, ssl_closed, ssl_error}.
  43. %% @doc Listen for connections on the given port number.
  44. %%
  45. %% Calling this function returns a listening socket that can then
  46. %% The available options are:
  47. %%
  48. %% <dl>
  49. %% <dt>backlog</dt><dd>Maximum length of the pending connections queue.
  50. %% Defaults to 1024.</dd>
  51. %% <dt>cacertfile</dt><dd>Optional. Path to file containing PEM encoded
  52. %% CA certificates (trusted certificates used for verifying a peer
  53. %% certificate).</dd>
  54. %% <dt>certfile</dt><dd>Mandatory. Path to a file containing the user's
  55. %% certificate.</dd>
  56. %% <dt>ciphers</dt><dd>Optional. The cipher suites that should be supported.
  57. %% The function ssl:cipher_suites/0 can be used to find all available
  58. %% ciphers.</dd>
  59. %% <dt>ip</dt><dd>Interface to listen on. Listen on all interfaces
  60. %% by default.</dd>
  61. %% <dt>keyfile</dt><dd>Optional. Path to the file containing the user's
  62. %% private PEM encoded key.</dd>
  63. %% <dt>nodelay</dt><dd>Optional. Enable TCP_NODELAY. Enabled by default.</dd>
  64. %% <dt>password</dt><dd>Optional. String containing the user's password.
  65. %% All private keyfiles must be password protected currently.</dd>
  66. %% <dt>port</dt><dd>TCP port number to open. Defaults to 0 (see below)</dd>
  67. %% <dt>verify</dt><dd>Optional. If set to verify_peer, performs an x509-path
  68. %% validation and request the client for a certificate.</dd>
  69. %% </dl>
  70. %%
  71. %% You can listen to a random port by setting the port option to 0.
  72. %% It is then possible to retrieve this port number by calling
  73. %% sockname/1 on the listening socket. If you are using Ranch's
  74. %% listener API, then this port number can obtained through
  75. %% ranch:get_port/1 instead.
  76. %%
  77. %% @see ssl:listen/2
  78. -spec listen([{backlog, non_neg_integer()} | {cacertfile, string()}
  79. | {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()}
  80. | {ip, inet:ip_address()} | {keyfile, string()} | {nodelay, boolean()}
  81. | {password, string()} | {port, inet:port_number()}
  82. | {verify, ssl:verify_type()}])
  83. -> {ok, ssl:sslsocket()} | {error, atom()}.
  84. listen(Opts) ->
  85. ranch:require([crypto, public_key, ssl]),
  86. {certfile, _} = lists:keyfind(certfile, 1, Opts),
  87. Opts2 = ranch:set_option_default(Opts, backlog, 1024),
  88. %% We set the port to 0 because it is given in the Opts directly.
  89. %% The port in the options takes precedence over the one in the
  90. %% first argument.
  91. ssl:listen(0, ranch:filter_options(Opts2,
  92. [backlog, cacertfile, certfile, ciphers, ip,
  93. keyfile, nodelay, password, port, verify],
  94. [binary, {active, false}, {packet, raw},
  95. {reuseaddr, true}, {nodelay, true}])).
  96. %% @doc Accept connections with the given listening socket.
  97. %%
  98. %% Note that this function does both the transport accept and
  99. %% the SSL handshake. The returned socket is thus fully connected.
  100. %%
  101. %% @see ssl:transport_accept/2
  102. %% @see ssl:ssl_accept/2
  103. -spec accept(ssl:sslsocket(), timeout())
  104. -> {ok, ssl:sslsocket()} | {error, closed | timeout | atom() | tuple()}.
  105. accept(LSocket, Timeout) ->
  106. case ssl:transport_accept(LSocket, Timeout) of
  107. {ok, CSocket} ->
  108. ssl_accept(CSocket, Timeout);
  109. {error, Reason} ->
  110. {error, Reason}
  111. end.
  112. %% @private Experimental. Open a connection to the given host and port number.
  113. %% @see ssl:connect/3
  114. %% @todo Probably filter Opts?
  115. -spec connect(inet:ip_address() | inet:hostname(),
  116. inet:port_number(), any())
  117. -> {ok, inet:socket()} | {error, atom()}.
  118. connect(Host, Port, Opts) when is_integer(Port) ->
  119. ssl:connect(Host, Port,
  120. Opts ++ [binary, {active, false}, {packet, raw}]).
  121. %% @doc Receive data from a socket in passive mode.
  122. %% @see ssl:recv/3
  123. -spec recv(ssl:sslsocket(), non_neg_integer(), timeout())
  124. -> {ok, any()} | {error, closed | atom()}.
  125. recv(Socket, Length, Timeout) ->
  126. ssl:recv(Socket, Length, Timeout).
  127. %% @doc Send data on a socket.
  128. %% @see ssl:send/2
  129. -spec send(ssl:sslsocket(), iodata()) -> ok | {error, atom()}.
  130. send(Socket, Packet) ->
  131. ssl:send(Socket, Packet).
  132. %% @doc Send a file on a socket.
  133. %%
  134. %% Unlike with TCP, no syscall can be used here, so sending files
  135. %% through SSL will be much slower in comparison.
  136. %%
  137. %% @see file:sendfile/2
  138. -spec sendfile(ssl:sslsocket(), file:name())
  139. -> {ok, non_neg_integer()} | {error, atom()}.
  140. sendfile(Socket, Filepath) ->
  141. {ok, IoDevice} = file:open(Filepath, [read, binary, raw]),
  142. sendfile(Socket, IoDevice, 0).
  143. -spec sendfile(ssl:sslsocket(), file:io_device(), non_neg_integer())
  144. -> {ok, non_neg_integer()} | {error, atom()}.
  145. sendfile(Socket, IoDevice, Sent) ->
  146. case file:read(IoDevice, 16#1FFF) of
  147. eof ->
  148. ok = file:close(IoDevice),
  149. {ok, Sent};
  150. {ok, Bin} ->
  151. case send(Socket, Bin) of
  152. ok ->
  153. sendfile(Socket, IoDevice, Sent + byte_size(Bin));
  154. {error, Reason} ->
  155. {error, Reason}
  156. end
  157. end.
  158. %% @doc Set options on the given socket.
  159. %% @see ssl:setopts/2
  160. %% @todo Probably filter Opts?
  161. -spec setopts(ssl:sslsocket(), list()) -> ok | {error, atom()}.
  162. setopts(Socket, Opts) ->
  163. ssl:setopts(Socket, Opts).
  164. %% @doc Give control of the socket to a new process.
  165. %%
  166. %% Must be called from the process currently controlling the socket,
  167. %% otherwise an {error, not_owner} tuple will be returned.
  168. %%
  169. %% @see ssl:controlling_process/2
  170. -spec controlling_process(ssl:sslsocket(), pid())
  171. -> ok | {error, closed | not_owner | atom()}.
  172. controlling_process(Socket, Pid) ->
  173. ssl:controlling_process(Socket, Pid).
  174. %% @doc Return the remote address and port of the connection.
  175. %% @see ssl:peername/1
  176. -spec peername(ssl:sslsocket())
  177. -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
  178. peername(Socket) ->
  179. ssl:peername(Socket).
  180. %% @doc Return the local address and port of the connection.
  181. %% @see ssl:sockname/1
  182. -spec sockname(ssl:sslsocket())
  183. -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
  184. sockname(Socket) ->
  185. ssl:sockname(Socket).
  186. %% @doc Close the given socket.
  187. %% @see ssl:close/1
  188. -spec close(ssl:sslsocket()) -> ok.
  189. close(Socket) ->
  190. ssl:close(Socket).
  191. %% Internal.
  192. -spec ssl_accept(ssl:sslsocket(), timeout())
  193. -> {ok, ssl:sslsocket()} | {error, {ssl_accept, atom()}}.
  194. ssl_accept(Socket, Timeout) ->
  195. case ssl:ssl_accept(Socket, Timeout) of
  196. ok ->
  197. {ok, Socket};
  198. {error, Reason} ->
  199. {error, {ssl_accept, Reason}}
  200. end.