1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
%% @copyright 2010 Mochi Media, Inc.
%% @doc MochiWeb socket - wrapper for plain and ssl sockets.
-module(mochiweb_socket).
-export([listen/4, accept/1, recv/3, send/2, close/1, port/1, peername/1,
setopts/2, type/1]).
-define(ACCEPT_TIMEOUT, 2000).
listen(Ssl, Port, Opts, SslOpts) ->
case Ssl of
true ->
case ssl:listen(Port, Opts ++ SslOpts) of
{ok, ListenSocket} ->
{ok, {ssl, ListenSocket}};
{error, _} = Err ->
Err
end;
false ->
gen_tcp:listen(Port, Opts)
end.
accept({ssl, ListenSocket}) ->
% There's a bug in ssl:transport_accept/2 at the moment, which is the
% reason for the try...catch block. Should be fixed in OTP R14.
try ssl:transport_accept(ListenSocket) of
{ok, Socket} ->
case ssl:ssl_accept(Socket) of
ok ->
{ok, {ssl, Socket}};
{error, _} = Err ->
Err
end;
{error, _} = Err ->
Err
catch
error:{badmatch, {error, Reason}} ->
{error, Reason}
end;
accept(ListenSocket) ->
gen_tcp:accept(ListenSocket, ?ACCEPT_TIMEOUT).
recv({ssl, Socket}, Length, Timeout) ->
ssl:recv(Socket, Length, Timeout);
recv(Socket, Length, Timeout) ->
gen_tcp:recv(Socket, Length, Timeout).
send({ssl, Socket}, Data) ->
ssl:send(Socket, Data);
send(Socket, Data) ->
gen_tcp:send(Socket, Data).
close({ssl, Socket}) ->
ssl:close(Socket);
close(Socket) ->
gen_tcp:close(Socket).
port({ssl, Socket}) ->
case ssl:sockname(Socket) of
{ok, {_, Port}} ->
{ok, Port};
{error, _} = Err ->
Err
end;
port(Socket) ->
inet:port(Socket).
peername({ssl, Socket}) ->
ssl:peername(Socket);
peername(Socket) ->
inet:peername(Socket).
setopts({ssl, Socket}, Opts) ->
ssl:setopts(Socket, Opts);
setopts(Socket, Opts) ->
inet:setopts(Socket, Opts).
type({ssl, _}) ->
ssl;
type(_) ->
plain.
|