From 0d84eda41c460433baa93cd06cb82a3d47cf814c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Mon, 20 Aug 2012 12:44:53 +0200 Subject: Add the 'ranch_transport' behaviour At the same time we make the 'port' option optional, defaulting to 0. --- src/ranch.erl | 38 ++++++++++++++ src/ranch_ssl.erl | 137 +++++++++++++++++++++++------------------------- src/ranch_tcp.erl | 93 +++++++++++++++++--------------- src/ranch_transport.erl | 77 +++++++++++++++++++++++++++ 4 files changed, 231 insertions(+), 114 deletions(-) create mode 100644 src/ranch_transport.erl diff --git a/src/ranch.erl b/src/ranch.erl index 3360154..3a79312 100644 --- a/src/ranch.erl +++ b/src/ranch.erl @@ -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. %% @@ -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). diff --git a/src/ranch_ssl.erl b/src/ranch_ssl.erl index d85c05f..72b59db 100644 --- a/src/ranch_ssl.erl +++ b/src/ranch_ssl.erl @@ -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, ssl. --spec name() -> ssl. +%% @doc Name of this transport, ssl. 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: +%% %%
-%%
port
Mandatory. TCP port number to open.
%%
backlog
Maximum length of the pending connections queue. %% Defaults to 1024.
-%%
ip
Interface to listen on. Listen on all interfaces -%% by default.
+%%
cacertfile
Optional. Path to file containing PEM encoded +%% CA certificates (trusted certificates used for verifying a peer +%% certificate).
%%
certfile
Mandatory. Path to a file containing the user's %% certificate.
+%%
ciphers
Optional. The cipher suites that should be supported. +%% The function ssl:cipher_suites/0 can be used to find all available +%% ciphers.
+%%
ip
Interface to listen on. Listen on all interfaces +%% by default.
%%
keyfile
Optional. Path to the file containing the user's %% private PEM encoded key.
-%%
cacertfile
Optional. Path to file containing PEM encoded -%% CA certificates (trusted certificates used for verifying a peer -%% certificate).
%%
password
Optional. String containing the user's password. %% All private keyfiles must be password protected currently.
-%%
ciphers
Optional. The cipher suites that should be supported. -%% The function ssl:cipher_suites/0 can be used to find all available -%% ciphers.
+%%
port
TCP port number to open. Defaults to 0 (see below)
%%
%% +%% 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 @@ -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 Pid to Socket. +%% @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()}}. diff --git a/src/ranch_tcp.erl b/src/ranch_tcp.erl index 765da74..2a9ccd6 100644 --- a/src/ranch_tcp.erl +++ b/src/ranch_tcp.erl @@ -18,113 +18,122 @@ %% %% @see gen_tcp -module(ranch_tcp). +-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, tcp. --spec name() -> tcp. +%% @doc Name of this transport, tcp. name() -> tcp. -%% @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() -> {tcp, tcp_closed, tcp_error}. +%% @doc Atoms used to identify messages in {active, once | true} mode. messages() -> {tcp, tcp_closed, tcp_error}. -%% @private --spec connect(string(), inet:port_number(), any()) - -> {ok, inet:socket()} | {error, atom()}. -connect(Host, Port, Opts) when is_list(Host), is_integer(Port) -> - gen_tcp: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 +%% be passed to accept/2 to accept connections. %% %% The available options are: %%
-%%
port
Mandatory. TCP port number to open.
%%
backlog
Maximum length of the pending connections queue. %% Defaults to 1024.
%%
ip
Interface to listen on. Listen on all interfaces %% by default.
+%%
port
TCP port number to open. Defaults to 0 (see below).
%%
%% +%% 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 gen_tcp:listen/2 --spec listen([{port, inet:port_number()} | {ip, inet:ip_address()}]) +-spec listen([{backlog, non_neg_integer()} | {ip, inet:ip_address()} + | {port, inet:port_number()}]) -> {ok, inet:socket()} | {error, atom()}. listen(Opts) -> - {port, Port} = lists:keyfind(port, 1, Opts), - Backlog = proplists:get_value(backlog, Opts, 1024), - ListenOpts0 = [binary, {active, false}, - {backlog, Backlog}, {packet, raw}, {reuseaddr, true}], - ListenOpts = - case lists:keyfind(ip, 1, Opts) of - false -> ListenOpts0; - Ip -> [Ip|ListenOpts0] - end, - gen_tcp:listen(Port, ListenOpts). + 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. + gen_tcp:listen(0, ranch:filter_options(Opts2, [port, ip, backlog], + [binary, {active, false}, {packet, raw}, {reuseaddr, true}])). -%% @doc Accept an incoming connection on a listen socket. +%% @doc Accept connections with the given listening socket. %% @see gen_tcp:accept/2 -spec accept(inet:socket(), timeout()) -> {ok, inet:socket()} | {error, closed | timeout | atom()}. accept(LSocket, Timeout) -> gen_tcp:accept(LSocket, Timeout). -%% @doc Receive a packet from a socket in passive mode. +%% @private Experimental. Open a connection to the given host and port number. +%% @see gen_tcp: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) -> + gen_tcp:connect(Host, Port, + Opts ++ [binary, {active, false}, {packet, raw}]). + +%% @doc Receive data from a socket in passive mode. %% @see gen_tcp:recv/3 -spec recv(inet:socket(), non_neg_integer(), timeout()) -> {ok, any()} | {error, closed | atom()}. recv(Socket, Length, Timeout) -> gen_tcp:recv(Socket, Length, Timeout). -%% @doc Send a packet on a socket. +%% @doc Send data on a socket. %% @see gen_tcp:send/2 -spec send(inet:socket(), iolist()) -> ok | {error, atom()}. send(Socket, Packet) -> gen_tcp:send(Socket, Packet). -%% @doc Set one or more options for a socket. +%% @doc Set options on the given socket. %% @see inet:setopts/2 +%% @todo Probably filter Opts? -spec setopts(inet:socket(), list()) -> ok | {error, atom()}. setopts(Socket, Opts) -> inet:setopts(Socket, Opts). -%% @doc Assign a new controlling process Pid to Socket. +%% @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 gen_tcp:controlling_process/2 -spec controlling_process(inet:socket(), pid()) -> ok | {error, closed | not_owner | atom()}. controlling_process(Socket, Pid) -> gen_tcp: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 inet:peername/1 -spec peername(inet:socket()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}. peername(Socket) -> inet:peername(Socket). -%% @doc Close a TCP socket. -%% @see gen_tcp:close/1 --spec close(inet:socket()) -> ok. -close(Socket) -> - gen_tcp:close(Socket). - -%% @doc Get the local address and port of a socket +%% @doc Return the local address and port of the connection. %% @see inet:sockname/1 -spec sockname(inet:socket()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}. sockname(Socket) -> inet:sockname(Socket). + +%% @doc Close the given socket. +%% @see gen_tcp:close/1 +-spec close(inet:socket()) -> ok. +close(Socket) -> + gen_tcp:close(Socket). diff --git a/src/ranch_transport.erl b/src/ranch_transport.erl new file mode 100644 index 0000000..38dca5a --- /dev/null +++ b/src/ranch_transport.erl @@ -0,0 +1,77 @@ +%% Copyright (c) 2012, Loïc Hoguin +%% +%% Permission to use, copy, modify, and/or distribute this software for any +%% purpose with or without fee is hereby granted, provided that the above +%% copyright notice and this permission notice appear in all copies. +%% +%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +%% @private +-module(ranch_transport). + +-type socket() :: any(). +-type opts() :: any(). + +%% Name of the transport. +-callback name() -> atom(). + +%% @todo -callback caps(secure | sendfile) -> boolean(). + +%% Atoms used to identify messages in {active, once | true} mode. +-callback messages() -> {OK::atom(), Closed::atom(), Error::atom()}. + +%% Listen for connections on the given port number. +%% +%% Calling this function returns a listening socket that can then +%% be passed to accept/2 to accept connections. +%% +%% Available options may vary between transports. +%% +%% 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. +-callback listen(opts()) -> {ok, socket()} | {error, atom()}. + +%% Accept connections with the given listening socket. +-callback accept(socket(), timeout()) + -> {ok, socket()} | {error, closed | timeout | atom() | tuple()}. + +%% Experimental. Open a connection to the given host and port number. +-callback connect(string(), inet:port_number(), opts()) + -> {ok, socket()} | {error, atom()}. + +%% Receive data from a socket in passive mode. +-callback recv(socket(), non_neg_integer(), timeout()) + -> {ok, any()} | {error, closed | timeout | atom()}. + +%% Send data on a socket. +-callback send(socket(), iodata()) -> ok | {error, atom()}. + +%% Set options on the given socket. +-callback setopts(socket(), opts()) -> ok | {error, atom()}. + +%% 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. +-callback controlling_process(socket(), pid()) + -> ok | {error, closed | not_owner | atom()}. + +%% Return the remote address and port of the connection. +-callback peername(socket()) + -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}. + +%% Return the local address and port of the connection. +-callback sockname(socket()) + -> {ok, {inet:ip_address(), inet:port_number()}} | {error, atom()}. + +%% Close the given socket. +-callback close(socket()) -> ok. -- cgit v1.2.3