aboutsummaryrefslogtreecommitdiffstats
path: root/lib/inets/src/http_lib/http_transport.erl
blob: 5eb827032f4532700436463761a0f182c3b73cd3 (plain) (blame)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2004-2011. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%

-module(http_transport).

% Internal application API
-export([
	 start/1, 
	 connect/3, connect/4, 
	 listen/2, listen/3, listen/4, 
	 accept/2, accept/3, 
	 close/2,
	 send/3, 
	 controlling_process/3, 
	 setopts/3, getopts/2, getopts/3, 
	 getstat/2, 
	 peername/2, sockname/2, 
	 resolve/0
	]).
-export([negotiate/3]).
-export([ipv4_name/1, ipv6_name/1]).

-include_lib("inets/src/inets_app/inets_internal.hrl").
-include("http_internal.hrl").

-define(SERVICE, httpl).
-define(hlri(Label, Content), ?report_important(Label, ?SERVICE, Content)).
-define(hlrv(Label, Content), ?report_verbose(Label,   ?SERVICE, Content)).
-define(hlrd(Label, Content), ?report_debug(Label,     ?SERVICE, Content)).
-define(hlrt(Label, Content), ?report_trace(Label,     ?SERVICE, Content)).


%%%=========================================================================
%%%  Internal application API
%%%=========================================================================

%%-------------------------------------------------------------------------
%% start(SocketType) -> ok | {error, Reason}
%%      SocketType = ip_comm | {ssl, _}  
%%                                   
%% Description: Makes sure inet_db or ssl is started. 
%%-------------------------------------------------------------------------
start(ip_comm) ->
    do_start_ip_comm();

%% This is just for backward compatibillity
start({ssl, _}) ->
    do_start_ssl();
start({essl, _}) ->
    do_start_ssl().


do_start_ip_comm() ->
    case inet_db:start() of
	{ok, _} ->
	    ok;
	{error, {already_started, _}} ->
	    ok;
	Error ->
	    Error
    end.

do_start_ssl() ->
    case ssl:start() of
	ok ->
	    ok;
	{error, {already_started,_}} ->
	    ok;
	Error ->
	    Error
    end.


%%-------------------------------------------------------------------------
%% connect(SocketType, Address, Options, Timeout) ->
%%                                            {ok, Socket} | {error, Reason}
%%      SocketType = ip_comm | {ssl, SslConfig}  
%%      Address = {Host, Port}
%%      Options = [option()]
%%      Socket = socket()
%%      option() = ipfamily() | {ip, ip_address()} | {port, integer()}
%%      ipfamily() = inet | inet6 
%%                                   
%% Description: Connects to the Host and Port specified in HTTPRequest.
%%-------------------------------------------------------------------------

connect(SocketType, Address, Opts) ->
    connect(SocketType, Address, Opts, infinity).

connect(ip_comm = _SocketType, {Host, Port}, Opts0, Timeout) 
  when is_list(Opts0) ->
    Opts = [binary, {packet, 0}, {active, false}, {reuseaddr, true} | Opts0],
    ?hlrt("connect using gen_tcp", 
	  [{host, Host}, {port, Port}, {opts, Opts}, {timeout, Timeout}]),
    try gen_tcp:connect(Host, Port, Opts, Timeout) of
	{ok, _} = OK ->
	    OK;
	{error, _} = ERROR ->
	    ERROR
    catch 
	exit:{badarg, _} ->
	    {error, {eoptions, Opts}};
	exit:badarg ->
	    {error, {eoptions, Opts}}
    end;

%% Wrapper for backaward compatibillity
connect({ssl, SslConfig}, Address, Opts, Timeout) ->
    connect({?HTTP_DEFAULT_SSL_KIND, SslConfig}, Address, Opts, Timeout);

connect({essl, SslConfig}, {Host, Port}, Opts0, Timeout) -> 
    Opts = [binary, {active, false}, {ssl_imp, new} | Opts0] ++ SslConfig,
    ?hlrt("connect using essl", 
	  [{host,       Host}, 
	   {port,       Port}, 
	   {ssl_config, SslConfig}, 
	   {timeout,    Timeout}]),
    case (catch ssl:connect(Host, Port, Opts, Timeout)) of
	{'EXIT', Reason} ->
	    {error, {eoptions, Reason}};
	{ok, _} = OK ->
	    OK;
	{error, _} = ERROR ->
	    ERROR
    end.


%%-------------------------------------------------------------------------
%% listen(SocketType, Addr, Port, Fd) -> {ok, Socket} | {error, Reason}
%%      SocketType = ip_comm | {ssl, SSLConfig}  
%%      Port = integer() 
%%      Socket = socket()
%%      Fd = undefined | fd()
%%
%% Description: Sets up socket to listen on the port Port on the local
%% host using either gen_tcp or ssl. In the gen_tcp case the port
%% might allready have been initiated by a wrapper-program and is
%% given as an Fd that can be retrieved by init:get_argument. The
%% reason for this to enable a HTTP-server not running as root to use
%% port 80.
%%-------------------------------------------------------------------------
listen(SocketType, Port) ->
    listen(SocketType, undefined, Port).

listen(ip_comm = _SocketType, Addr, Port) ->
    listen_ip_comm(Addr, Port, undefined);

%% Wrapper for backaward compatibillity
listen({ssl, SSLConfig}, Addr, Port) ->
    ?hlrt("listen (wrapper)", 
	  [{addr,       Addr}, 
	   {port,       Port}, 
	   {ssl_config, SSLConfig}]),
    listen({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Addr, Port);

listen({essl, SSLConfig}, Addr, Port) ->
    ?hlrt("listen (essl)", 
	  [{addr,       Addr}, 
	   {port,       Port}, 
	   {ssl_config, SSLConfig}]),
    listen_ssl(Addr, Port, [{ssl_imp, new}, {reuseaddr, true} | SSLConfig]).


listen(ip_comm, Addr, Port, Fd) ->
    listen_ip_comm(Addr, Port, Fd).

listen_ip_comm(Addr, Port, Fd) ->
    case (catch do_listen_ip_comm(Addr, Port, Fd)) of
	{'EXIT', Reason} ->
	    {error, {exit, Reason}};
	Else ->
	    Else
    end.

do_listen_ip_comm(Addr, Port, Fd) ->
    {NewPort, Opts, IpFamily} = get_socket_info(Addr, Port, Fd),
    case IpFamily of
	inet6fb4 -> 
	    Opts2 = [inet6 | Opts], 
	    ?hlrt("try ipv6 listen", [{port, NewPort}, {opts, Opts2}]),
	    case (catch gen_tcp:listen(NewPort, Opts2)) of
		{error, Reason} when ((Reason =:= nxdomain) orelse 
				      (Reason =:= eafnosupport)) ->
		    Opts3 = [inet | Opts], 
		    ?hlrt("ipv6 listen failed - try ipv4 instead", 
			  [{reason, Reason}, {port, NewPort}, {opts, Opts3}]),
		    gen_tcp:listen(NewPort, Opts3);

		%% This is when a given hostname has resolved to a 
		%% IPv4-address. The inet6-option together with a 
		%% {ip, IPv4} option results in badarg
		{'EXIT', Reason} -> 
		    Opts3 = [inet | Opts], 
		    ?hlrt("ipv6 listen exit - try ipv4 instead", 
			  [{reason, Reason}, {port, NewPort}, {opts, Opts3}]),
		    gen_tcp:listen(NewPort, Opts3); 

		Other ->
		    ?hlrt("ipv6 listen done", [{other, Other}]),
		    Other
	    end;
	_ ->
	    Opts2 = [IpFamily | Opts],
	    ?hlrt("listen", [{port, NewPort}, {opts, Opts2}]),
	    gen_tcp:listen(NewPort, Opts2)
    end.


listen_ssl(Addr, Port, Opts0) ->
    IpFamily = ipfamily_default(Addr, Port), 
    BaseOpts = [{backlog, 128}, {reuseaddr, true} | Opts0], 
    Opts     = sock_opts(Addr, BaseOpts),
    case IpFamily of
	inet6fb4 -> 
	    Opts2 = [inet6 | Opts], 
	    ?hlrt("try ipv6 listen", [{opts, Opts2}]),
	    case (catch ssl:listen(Port, Opts2)) of
		{error, Reason} when ((Reason =:= nxdomain) orelse 
				      (Reason =:= eafnosupport)) ->
		    Opts3 = [inet | Opts], 
		    ?hlrt("ipv6 listen failed - try ipv4 instead", 
			  [{reason, Reason}, {opts, Opts3}]),
		    ssl:listen(Port, Opts3);
		
		{'EXIT', Reason} -> 
		    Opts3 = [inet | Opts], 
		    ?hlrt("ipv6 listen exit - try ipv4 instead", 
			  [{reason, Reason}, {opts, Opts3}]),
		    ssl:listen(Port, Opts3); 
		
		Other ->
		    ?hlrt("ipv6 listen done", [{other, Other}]),
		    Other
	    end;
	
	_ ->
	    Opts2 = [IpFamily | Opts],
	    ?hlrt("listen", [{opts, Opts2}]),
	    ssl:listen(Port, Opts2)
    end.


ipfamily_default(Addr, Port) ->
    httpd_conf:lookup(Addr, Port, ipfamily, inet6fb4).

get_socket_info(Addr, Port, Fd0) ->
    BaseOpts        = [{backlog, 128}, {reuseaddr, true}], 
    IpFamilyDefault = ipfamily_default(Addr, Port), 
    %% The presence of a file descriptor takes precedence
    case get_fd(Port, Fd0, IpFamilyDefault) of
	{Fd, IpFamily} -> 
	    {0, sock_opts(Addr, [{fd, Fd} | BaseOpts]), IpFamily};
	undefined ->
	    {Port, sock_opts(Addr, BaseOpts), IpFamilyDefault}
    end.
	    
get_fd(Port, undefined = _Fd, IpFamilyDefault) ->
    FdKey = list_to_atom("httpd_" ++ integer_to_list(Port)),
    case init:get_argument(FdKey) of
	{ok, [[Value]]} ->
	    case string:tokens(Value, [$|]) of
		[FdStr, IpFamilyStr] ->
		    {fd_of(FdStr), ip_family_of(IpFamilyStr)};
		[FdStr] ->
		    {fd_of(FdStr), IpFamilyDefault};
		_ ->
		    throw({error, {bad_descriptor, Value}})
	    end;
	error ->
	    undefined
    end;
get_fd(_Port, Fd, IpFamilyDefault) ->
    {Fd, IpFamilyDefault}.

    
fd_of(FdStr) ->
    case (catch list_to_integer(FdStr)) of
	Fd when is_integer(Fd) ->
	    Fd;
	_ ->
	    throw({error, {bad_descriptor, FdStr}})
    end.

ip_family_of(IpFamilyStr) ->
    IpFamily = list_to_atom(IpFamilyStr),
    case lists:member(IpFamily, [inet, inet6, inet6fb4]) of
	true ->
	    IpFamily;
	false ->
	    throw({error, {bad_ipfamily, IpFamilyStr}})
    end.


%%-------------------------------------------------------------------------
%% accept(SocketType, ListenSocket) -> {ok, Socket} | {error, Reason}
%% accept(SocketType, ListenSocket, Timeout) -> ok | {error, Reason}
%%   SocketType = ip_comm | {ssl, SSLConfig}  
%%   ListenSocket = socket()    
%%   Timeout = infinity | integer() >= 0
%%   Socket = socket()
%%                                   
%% Description: Accepts an incoming connection request on a listen socket,
%% using either gen_tcp or ssl.
%%-------------------------------------------------------------------------
accept(SocketType, ListenSocket) ->
    accept(SocketType, ListenSocket, infinity).

accept(ip_comm, ListenSocket, Timeout) ->
    gen_tcp:accept(ListenSocket, Timeout);

%% Wrapper for backaward compatibillity
accept({ssl, SSLConfig}, ListenSocket, Timeout) ->
    accept({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, ListenSocket, Timeout);

accept({essl, _SSLConfig}, ListenSocket, Timeout) ->
    ssl:transport_accept(ListenSocket, Timeout).


%%-------------------------------------------------------------------------
%% controlling_process(SocketType, Socket, NewOwner) -> ok | {error, Reason}
%%   SocketType = ip_comm | {ssl, _}  
%%   Socket = socket()        
%%   NewOwner = pid()
%%                                
%% Description: Assigns a new controlling process to Socket. 
%%-------------------------------------------------------------------------
controlling_process(ip_comm, Socket, NewOwner) ->
    gen_tcp:controlling_process(Socket, NewOwner);

%% Wrapper for backaward compatibillity
controlling_process({ssl, SSLConfig}, Socket, NewOwner) ->
    controlling_process({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket, NewOwner);

controlling_process({essl, _}, Socket, NewOwner) ->
    ssl:controlling_process(Socket, NewOwner).


%%-------------------------------------------------------------------------
%% setopts(SocketType, Socket, Options) -> ok | {error, Reason}
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket()
%%     Options = list()                              
%% Description: Sets one or more options for a socket, using either
%% gen_tcp or ssl.
%%-------------------------------------------------------------------------
setopts(ip_comm, Socket, Options) ->
    ?hlrt("ip_comm setopts", [{socket, Socket}, {options, Options}]),
    inet:setopts(Socket, Options);

%% Wrapper for backaward compatibillity
setopts({ssl, SSLConfig}, Socket, Options) ->
    setopts({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket, Options);

setopts({essl, _}, Socket, Options) ->
    ?hlrt("[e]ssl setopts", [{socket, Socket}, {options, Options}]),
    Reason = (catch ssl:setopts(Socket, Options)),
    ?hlrt("[e]ssl setopts result", [{reason, Reason}]),
    Reason.


%%-------------------------------------------------------------------------
%% getopts(SocketType, Socket [, Opts]) -> ok | {error, Reason}
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket()
%%     Opts   = socket_options()
%% Description: Gets the values for some options. 
%%-------------------------------------------------------------------------
getopts(SocketType, Socket) ->
    Opts = [packet, packet_size, recbuf, sndbuf, priority, tos, send_timeout], 
    getopts(SocketType, Socket, Opts).

getopts(ip_comm, Socket, Options) ->
    ?hlrt("ip_comm getopts", [{socket, Socket}, {options, Options}]),
    case inet:getopts(Socket, Options) of
	{ok, SocketOpts} ->
	    SocketOpts;
	{error, _} -> 
	    []
    end;

%% Wrapper for backaward compatibillity
getopts({ssl, SSLConfig}, Socket, Options) ->
    getopts({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket, Options);

getopts({essl, _}, Socket, Options) ->
    ?hlrt("essl getopts", [{socket, Socket}, {options, Options}]),
    getopts_ssl(Socket, Options).

getopts_ssl(Socket, Options) ->
    case ssl:getopts(Socket, Options) of
	{ok, SocketOpts} ->
	    SocketOpts;
	{error, _} -> 
	    []
    end.
    

%%-------------------------------------------------------------------------
%% getstat(SocketType, Socket) -> socket_stats()
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket()
%%     socket_stats() = list()
%% Description: Gets the socket stats values for the socket
%%-------------------------------------------------------------------------
getstat(ip_comm = _SocketType, Socket) ->
    ?hlrt("ip_comm getstat", [{socket, Socket}]),
    case inet:getstat(Socket) of
	{ok, Stats} ->
	    Stats;
	{error, _} ->
	    []
    end;

%% Wrapper for backaward compatibillity
getstat({ssl, SSLConfig}, Socket) ->
    getstat({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket);

getstat({essl, _} = _SocketType, _Socket) ->
    [].


%%-------------------------------------------------------------------------
%% send(RequestOrSocketType, Socket, Message) -> ok | {error, Reason}
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket()
%%     Message = list() | binary()                           
%% Description: Sends a packet on a socket, using either gen_tcp or ssl.
%%-------------------------------------------------------------------------
send(ip_comm, Socket, Message) ->
    gen_tcp:send(Socket, Message);

%% Wrapper for backaward compatibillity
send({ssl, SSLConfig}, Socket, Message) ->
    send({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket, Message);

send({essl, _}, Socket, Message) ->
    ssl:send(Socket, Message).


%%-------------------------------------------------------------------------
%% close(SocketType, Socket) -> ok | {error, Reason}
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket()  
%%                                   
%% Description: Closes a socket, using either gen_tcp or ssl.
%%-------------------------------------------------------------------------
close(ip_comm, Socket) ->
    gen_tcp:close(Socket);

%% Wrapper for backaward compatibillity
close({ssl, SSLConfig}, Socket) ->
    close({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket);

close({essl, _}, Socket) ->
    ssl:close(Socket).


%%-------------------------------------------------------------------------
%% peername(SocketType, Socket) -> {Port, SockName}
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket() 
%%     Port = integer()  (-1 if error occured)
%%     PeerName = string()
%%                          
%% Description: Returns the address and port for the other end of a
%% connection, usning either gen_tcp or ssl.
%%-------------------------------------------------------------------------
peername(ip_comm, Socket) ->
    do_peername(inet:peername(Socket));

%% Wrapper for backaward compatibillity
peername({ssl, SSLConfig}, Socket) ->
    peername({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket);

peername({essl, _}, Socket) ->
    do_peername(ssl:peername(Socket)).

do_peername({ok, {Addr, Port}}) 
  when is_tuple(Addr) andalso (size(Addr) =:= 4) ->
    PeerName = ipv4_name(Addr), 
    {Port, PeerName};
do_peername({ok, {Addr, Port}}) 
  when is_tuple(Addr) andalso (size(Addr) =:= 8) ->
    PeerName = ipv6_name(Addr), 
    {Port, PeerName};
do_peername({error, _}) ->
    {-1, "unknown"}.


%%-------------------------------------------------------------------------
%% sockname(SocketType, Socket) -> {Port, SockName}
%%     SocketType = ip_comm | {ssl, _}
%%     Socket = socket() 
%%     Port = integer()  (-1 if error occured)
%%     SockName = string()
%%                          
%% Description: Returns the address and port for the local (our) end 
%% other end of connection, using either gen_tcp or ssl.
%%-------------------------------------------------------------------------
sockname(ip_comm, Socket) ->
    do_sockname(inet:sockname(Socket));

%% Wrapper for backaward compatibillity
sockname({ssl, SSLConfig}, Socket) ->
    sockname({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket);

sockname({essl, _}, Socket) ->
    do_sockname(ssl:sockname(Socket)).

do_sockname({ok, {Addr, Port}}) 
  when is_tuple(Addr) andalso (size(Addr) =:= 4) ->
    SockName = ipv4_name(Addr), 
    {Port, SockName};
do_sockname({ok, {Addr, Port}}) 
  when is_tuple(Addr) andalso (size(Addr) =:= 8) ->
    SockName = ipv6_name(Addr), 
    {Port, SockName};
do_sockname({error, _}) ->
    {-1, "unknown"}.


%%-------------------------------------------------------------------------
%% resolve() -> HostName
%%     HostName = string()
%%     
%% Description: Returns the local hostname. 
%%-------------------------------------------------------------------------
resolve() ->
    {ok, Name} = inet:gethostname(),
    Name.


%%-------------------------------------------------------------------------
%% ipv4_name(Ipv4Addr) -> string()
%% ipv6_name(Ipv6Addr) -> string()
%%     Ipv4Addr = ip4_address()
%%     Ipv6Addr = ip6_address()
%%     
%% Description: Returns the local hostname. 
%%-------------------------------------------------------------------------
ipv4_name({A, B, C, D}) ->
    integer_to_list(A) ++ "." ++
	integer_to_list(B) ++ "." ++
	integer_to_list(C) ++ "." ++
	integer_to_list(D).

ipv6_name({A, B, C, D, E, F, G, H}) ->
    http_util:integer_to_hexlist(A) ++ ":"++ 
	http_util:integer_to_hexlist(B) ++ ":" ++  
	http_util:integer_to_hexlist(C) ++ ":" ++ 
	http_util:integer_to_hexlist(D) ++ ":" ++  
	http_util:integer_to_hexlist(E) ++ ":" ++  
	http_util:integer_to_hexlist(F) ++ ":" ++  
	http_util:integer_to_hexlist(G) ++ ":" ++  
	http_util:integer_to_hexlist(H).


%%%========================================================================
%%% Internal functions
%%%========================================================================

%% -- sock_opts --
%% Address any comes from directive: BindAddress "*"
sock_opts(undefined, Opts) -> 
    sock_opts(Opts);
sock_opts(any = Addr, Opts) -> 
    sock_opts([{ip, Addr} | Opts]);
sock_opts(Addr, Opts) ->
    sock_opts([{ip, Addr} | Opts]).

sock_opts(Opts) ->
    [{packet, 0}, {active, false} | Opts].


%% -- negotiate --
negotiate(ip_comm,_,_) ->
    ?hlrt("negotiate(ip_comm)", []),
    ok;
negotiate({ssl, SSLConfig}, Socket, Timeout) ->
    ?hlrt("negotiate(ssl)", []),
    negotiate({?HTTP_DEFAULT_SSL_KIND, SSLConfig}, Socket, Timeout);
negotiate({essl, _}, Socket, Timeout) ->
    ?hlrt("negotiate(essl)", []),
    negotiate_ssl(Socket, Timeout).

negotiate_ssl(Socket, Timeout) ->
    ?hlrt("negotiate_ssl", [{socket, Socket}, {timeout, Timeout}]),
    case ssl:ssl_accept(Socket, Timeout) of
	ok ->
	    ok;
	{error, Reason} ->
	    ?hlrd("negotiate_ssl - accept failed", [{reason, Reason}]),
	    %% Look for "valid" error reasons
	    ValidReasons = [timeout, econnreset, esslaccept, esslerrssl], 
	    case lists:member(Reason, ValidReasons) of
		true ->
		    {error, normal};
		false ->
		    {error, Reason}
           end
    end.