Skip to content

Commit

Permalink
Add the 'ranch_transport' behaviour
Browse files Browse the repository at this point in the history
At the same time we make the 'port' option optional, defaulting to 0.
  • Loading branch information
essen committed Aug 20, 2012
1 parent d8981b5 commit 0d84eda
Show file tree
Hide file tree
Showing 4 changed files with 231 additions and 114 deletions.
38 changes: 38 additions & 0 deletions src/ranch.erl
Expand Up @@ -22,6 +22,9 @@
-export([get_port/1]).
-export([get_protocol_options/1]).
-export([set_protocol_options/2]).
-export([filter_options/3]).
-export([set_option_default/3]).
-export([require/1]).

%% @doc Start a listener for the given transport and protocol.
%%
Expand Down Expand Up @@ -112,3 +115,38 @@ get_protocol_options(Ref) ->
set_protocol_options(Ref, ProtoOpts) ->
ListenerPid = ranch_server:lookup_listener(Ref),
ok = ranch_listener:set_protocol_options(ListenerPid, ProtoOpts).

%% @doc Filter a list of options and remove all unwanted values.
%%
%% It takes a list of options, a list of allowed keys and an accumulator.
%% This accumulator can be used to set default options that should never
%% be overriden.
-spec filter_options([{atom(), any()}], [atom()], Acc)
-> Acc when Acc :: [any()].
filter_options([], _, Acc) ->
Acc;
filter_options([Opt = {Key, _}|Tail], AllowedKeys, Acc) ->
case lists:member(Key, AllowedKeys) of
true -> filter_options(Tail, AllowedKeys, [Opt|Acc]);
false -> filter_options(Tail, AllowedKeys, Acc)
end.

%% @doc Add an option to a list, but only if it wasn't previously set.
-spec set_option_default(Opts, atom(), any())
-> Opts when Opts :: [{atom(), any()}].
set_option_default(Opts, Key, Value) ->
case lists:keymember(Key, 1, Opts) of
true -> Opts;
false -> [{Key, Value}|Opts]
end.

%% @doc Start the given applications if they were not already started.
-spec require(list(module())) -> ok.
require([]) ->
ok;
require([App|Tail]) ->
case application:start(App) of
ok -> ok;
{error, {already_started, App}} -> ok
end,
require(Tail).
137 changes: 65 additions & 72 deletions src/ranch_ssl.erl
Expand Up @@ -23,90 +23,79 @@
%%
%% @see ssl
-module(ranch_ssl).
-behaviour(ranch_transport).

-export([name/0]).
-export([messages/0]).
-export([connect/3]).
-export([listen/1]).
-export([accept/2]).
-export([connect/3]).
-export([recv/3]).
-export([send/2]).
-export([setopts/2]).
-export([controlling_process/2]).
-export([peername/1]).
-export([close/1]).
-export([sockname/1]).
-export([close/1]).

%% @doc Name of this transport API, <em>ssl</em>.
-spec name() -> ssl.
%% @doc Name of this transport, <em>ssl</em>.
name() -> ssl.

%% @doc Atoms used in the process messages sent by this API.
%%
%% They identify incoming data, closed connection and errors when receiving
%% data in active mode.
-spec messages() -> {ssl, ssl_closed, ssl_error}.
%% @doc Atoms used to identify messages in {active, once | true} mode.
messages() -> {ssl, ssl_closed, ssl_error}.

%% @private
%% @todo Probably filter Opts?
-spec connect(string(), inet:port_number(), any())
-> {ok, inet:socket()} | {error, atom()}.
connect(Host, Port, Opts) when is_list(Host), is_integer(Port) ->
ssl:connect(Host, Port,
Opts ++ [binary, {active, false}, {packet, raw}]).

%% @doc Setup a socket to listen on the given port on the local host.
%% @doc Listen for connections on the given port number.
%%
%% Calling this function returns a listening socket that can then
%% The available options are:
%%
%% <dl>
%% <dt>port</dt><dd>Mandatory. TCP port number to open.</dd>
%% <dt>backlog</dt><dd>Maximum length of the pending connections queue.
%% Defaults to 1024.</dd>
%% <dt>ip</dt><dd>Interface to listen on. Listen on all interfaces
%% by default.</dd>
%% <dt>cacertfile</dt><dd>Optional. Path to file containing PEM encoded
%% CA certificates (trusted certificates used for verifying a peer
%% certificate).</dd>
%% <dt>certfile</dt><dd>Mandatory. Path to a file containing the user's
%% certificate.</dd>
%% <dt>ciphers</dt><dd>Optional. The cipher suites that should be supported.
%% The function ssl:cipher_suites/0 can be used to find all available
%% ciphers.</dd>
%% <dt>ip</dt><dd>Interface to listen on. Listen on all interfaces
%% by default.</dd>
%% <dt>keyfile</dt><dd>Optional. Path to the file containing the user's
%% private PEM encoded key.</dd>
%% <dt>cacertfile</dt><dd>Optional. Path to file containing PEM encoded
%% CA certificates (trusted certificates used for verifying a peer
%% certificate).</dd>
%% <dt>password</dt><dd>Optional. String containing the user's password.
%% All private keyfiles must be password protected currently.</dd>
%% <dt>ciphers</dt><dd>Optional. The cipher suites that should be supported.
%% The function ssl:cipher_suites/0 can be used to find all available
%% ciphers.</dd>
%% <dt>port</dt><dd>TCP port number to open. Defaults to 0 (see below)</dd>
%% </dl>
%%
%% You can listen to a random port by setting the port option to 0.
%% It is then possible to retrieve this port number by calling
%% sockname/1 on the listening socket. If you are using Ranch's
%% listener API, then this port number can obtained through
%% ranch:get_port/1 instead.
%%
%% @see ssl:listen/2
-spec listen([{port, inet:port_number()} | {certfile, string()}
| {keyfile, string()} | {password, string()}
| {cacertfile, string()} | {ip, inet:ip_address()}])
-spec listen([{backlog, non_neg_integer()} | {cacertfile, string()}
| {certfile, string()} | {ciphers, [ssl:erl_cipher_suite()] | string()}
| {ip, inet:ip_address()} | {keyfile, string()} | {password, string()}
| {port, inet:port_number()}])
-> {ok, ssl:sslsocket()} | {error, atom()}.
listen(Opts) ->
require([crypto, public_key, ssl]),
{port, Port} = lists:keyfind(port, 1, Opts),
Backlog = proplists:get_value(backlog, Opts, 1024),
{certfile, CertFile} = lists:keyfind(certfile, 1, Opts),

ListenOpts0 = [binary, {active, false},
{backlog, Backlog}, {packet, raw}, {reuseaddr, true},
{certfile, CertFile}],
ListenOpts = lists:foldl(fun
({ip, _} = Ip, Acc) -> [Ip | Acc];
({keyfile, _} = KeyFile, Acc) -> [KeyFile | Acc];
({cacertfile, _} = CACertFile, Acc) -> [CACertFile | Acc];
({password, _} = Password, Acc) -> [Password | Acc];
({ciphers, _} = Ciphers, Acc) -> [Ciphers | Acc];
(_, Acc) -> Acc
end, ListenOpts0, Opts),
ssl:listen(Port, ListenOpts).

%% @doc Accept an incoming connection on a listen socket.
ranch:require([crypto, public_key, ssl]),
{certfile, _} = lists:keyfind(certfile, 1, Opts),
Opts2 = ranch:set_option_default(Opts, backlog, 1024),
%% We set the port to 0 because it is given in the Opts directly.
%% The port in the options takes precedence over the one in the
%% first argument.
ssl:listen(0, ranch:filter_options(Opts2,
[backlog, cacertfile, certfile, ciphers, ip, keyfile, password, port],
[binary, {active, false}, {packet, raw}, {reuseaddr, true}])).

%% @doc Accept connections with the given listening socket.
%%
%% Note that this function does both the transport accept and
%% the SSL handshake.
%% the SSL handshake. The returned socket is thus fully connected.
%%
%% @see ssl:transport_accept/2
%% @see ssl:ssl_accept/2
Expand All @@ -120,63 +109,67 @@ accept(LSocket, Timeout) ->
{error, Reason}
end.

%% @doc Receive a packet from a socket in passive mode.
%% @private Experimental. Open a connection to the given host and port number.
%% @see ssl:connect/3
%% @todo Probably filter Opts?
-spec connect(string(), inet:port_number(), any())
-> {ok, inet:socket()} | {error, atom()}.
connect(Host, Port, Opts) when is_list(Host), is_integer(Port) ->
ssl:connect(Host, Port,
Opts ++ [binary, {active, false}, {packet, raw}]).

%% @doc Receive data from a socket in passive mode.
%% @see ssl:recv/3
-spec recv(ssl:sslsocket(), non_neg_integer(), timeout())
-> {ok, any()} | {error, closed | atom()}.
recv(Socket, Length, Timeout) ->
ssl:recv(Socket, Length, Timeout).

%% @doc Send a packet on a socket.
%% @doc Send data on a socket.
%% @see ssl:send/2
-spec send(ssl:sslsocket(), iolist()) -> ok | {error, atom()}.
send(Socket, Packet) ->
ssl:send(Socket, Packet).

%% @doc Set one or more options for a socket.
%% @doc Set options on the given socket.
%% @see ssl:setopts/2
%% @todo Probably filter Opts?
-spec setopts(ssl:sslsocket(), list()) -> ok | {error, atom()}.
setopts(Socket, Opts) ->
ssl:setopts(Socket, Opts).

%% @doc Assign a new controlling process <em>Pid</em> to <em>Socket</em>.
%% @doc Give control of the socket to a new process.
%%
%% Must be called from the process currently controlling the socket,
%% otherwise an {error, not_owner} tuple will be returned.
%%
%% @see ssl:controlling_process/2
-spec controlling_process(ssl:sslsocket(), pid())
-> ok | {error, closed | not_owner | atom()}.
controlling_process(Socket, Pid) ->
ssl:controlling_process(Socket, Pid).

%% @doc Return the address and port for the other end of a connection.
%% @doc Return the remote address and port of the connection.
%% @see ssl:peername/1
-spec peername(ssl:sslsocket())
-> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
peername(Socket) ->
ssl:peername(Socket).

%% @doc Close a TCP socket.
%% @see ssl:close/1
-spec close(ssl:sslsocket()) -> ok.
close(Socket) ->
ssl:close(Socket).

%% @doc Get the local address and port of a socket
%% @doc Return the local address and port of the connection.
%% @see ssl:sockname/1
-spec sockname(ssl:sslsocket())
-> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}.
sockname(Socket) ->
ssl:sockname(Socket).

%% Internal.
%% @doc Close the given socket.
%% @see ssl:close/1
-spec close(ssl:sslsocket()) -> ok.
close(Socket) ->
ssl:close(Socket).

-spec require(list(module())) -> ok.
require([]) ->
ok;
require([App|Tail]) ->
case application:start(App) of
ok -> ok;
{error, {already_started, App}} -> ok
end,
require(Tail).
%% Internal.

-spec ssl_accept(ssl:sslsocket(), timeout())
-> {ok, ssl:sslsocket()} | {error, {ssl_accept, atom()}}.
Expand Down

0 comments on commit 0d84eda

Please sign in to comment.