1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2000-2020, University of Amsterdam 7 VU University Amsterdam 8 CWI, Amsterdam 9 All rights reserved. 10 11 Redistribution and use in source and binary forms, with or without 12 modification, are permitted provided that the following conditions 13 are met: 14 15 1. Redistributions of source code must retain the above copyright 16 notice, this list of conditions and the following disclaimer. 17 18 2. Redistributions in binary form must reproduce the above copyright 19 notice, this list of conditions and the following disclaimer in 20 the documentation and/or other materials provided with the 21 distribution. 22 23 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 26 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 27 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 28 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 29 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 31 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 33 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 POSSIBILITY OF SUCH DAMAGE. 35*/ 36 37:- module(socket, 38 [ tcp_socket/1, % -Socket 39 tcp_close_socket/1, % +Socket 40 tcp_open_socket/3, % +Socket, -Read, -Write 41 tcp_connect/2, % +Socket, +Address 42 tcp_connect/3, % +Socket, +Address, -StreamPair 43 tcp_connect/4, % +Socket, +Address, -Read, -Write) 44 tcp_bind/2, % +Socket, +Address 45 tcp_accept/3, % +Master, -Slave, -PeerName 46 tcp_listen/2, % +Socket, +BackLog 47 tcp_fcntl/3, % +Socket, +Command, ?Arg 48 tcp_setopt/2, % +Socket, +Option 49 tcp_getopt/2, % +Socket, ?Option 50 tcp_host_to_address/2, % ?HostName, ?Ip-nr 51 tcp_select/3, % +Inputs, -Ready, +Timeout 52 gethostname/1, % -HostName 53 54 tcp_open_socket/2, % +Socket, -StreamPair 55 56 udp_socket/1, % -Socket 57 udp_receive/4, % +Socket, -Data, -Sender, +Options 58 udp_send/4, % +Socket, +Data, +Sender, +Options 59 60 negotiate_socks_connection/2% +DesiredEndpoint, +StreamPair 61 ]). 62:- autoload(library(debug),[debug/3]). 63:- autoload(library(lists),[last/2]).
171:- multifile 172 tcp_connect_hook/3, % +Socket, +Addr, -In, -Out 173 tcp_connect_hook/4, % +Socket, +Addr, -Stream 174 proxy_for_url/3, % +URL, +Host, -ProxyList 175 try_proxy/4. % +Proxy, +Addr, -Socket, -Stream 176 177:- predicate_options(tcp_connect/3, 3, 178 [ bypass_proxy(boolean), 179 nodelay(boolean) 180 ]). 181 182:- use_foreign_library(foreign(socket), install_socket). 183:- public tcp_debug/1. % set debugging. 184 185:- if(current_predicate(unix_domain_socket/1)). 186:- export(unix_domain_socket/1). % -Socket 187:- endif.
221tcp_open_socket(Socket, Stream) :-
222 tcp_open_socket(Socket, In, Out),
223 ( var(Out)
224 -> Stream = In
225 ; stream_pair(Stream, In, Out)
226 ).
tcp_bind(Socket, localhost:8080)
If Port is unbound, the system picks an arbitrary free port and unifies Port with the selected port number. Port is either an integer or the name of a registered service. See also tcp_connect/4.
af_unix
if Socket is an AF_UNIX socket (see
unix_domain_socket/1).tcp_socket(Socket), tcp_connect(Socket, Host:Port), tcp_open_socket(Socket, StreamPair)
Typical client applications should use the high level interface provided by tcp_connect/3 which avoids resource leaking if a step in the process fails, and can be hooked to support proxies. For example:
setup_call_cleanup( tcp_connect(Host:Port, StreamPair, []), talk(StreamPair), close(StreamPair))
If SocketId is an AF_UNIX socket (see unix_domain_socket/1), Address is an atom or string denoting a file name.
303 /******************************* 304 * HOOKABLE CONNECT * 305 *******************************/
:- multifile socket:tcp_connect_hook/4. socket:tcp_connect_hook(Socket, Address, Read, Write) :- proxy(ProxyAdress), tcp_connect(Socket, ProxyAdress), tcp_open_socket(Socket, Read, Write), proxy_connect(Address, Read, Write).
328tcp_connect(Socket, Address, Read, Write) :- 329 tcp_connect_hook(Socket, Address, Read, Write), 330 !. 331tcp_connect(Socket, Address, Read, Write) :- 332 tcp_connect(Socket, Address), 333 tcp_open_socket(Socket, Read, Write).
false
. If true
, do not attempt to use any
proxies to obtain the connectionfalse
. If true
, set nodelay on the
resulting socket using tcp_setopt(Socket, nodelay)
The +,+,- mode is deprecated and does not support proxies. It behaves like tcp_connect/4, but creates a stream pair (see stream_pair/3).
370% Main mode: +,-,+ 371tcp_connect(Address, StreamPair, Options) :- 372 var(StreamPair), 373 !, 374 ( memberchk(bypass_proxy(true), Options) 375 -> tcp_connect_direct(Address, Socket, StreamPair) 376 ; findall(Result, 377 try_a_proxy(Address, Result), 378 ResultList), 379 last(ResultList, Status) 380 -> ( Status = true(_Proxy, Socket, StreamPair) 381 -> true 382 ; throw(error(proxy_error(tried(ResultList)), _)) 383 ) 384 ; tcp_connect_direct(Address, Socket, StreamPair) 385 ), 386 ( memberchk(nodelay(true), Options) 387 -> tcp_setopt(Socket, nodelay) 388 ; true 389 ). 390% backward compatibility mode +,+,- 391tcp_connect(Socket, Address, StreamPair) :- 392 tcp_connect_hook(Socket, Address, StreamPair0), 393 !, 394 StreamPair = StreamPair0. 395tcp_connect(Socket, Address, StreamPair) :- 396 tcp_connect(Socket, Address, Read, Write), 397 stream_pair(StreamPair, Read, Write). 398 399 400tcp_connect_direct(Address, Socket, StreamPair):- 401 make_socket(Address, Socket), 402 catch(tcp_connect(Socket, Address, StreamPair), 403 Error, 404 ( tcp_close_socket(Socket), 405 throw(Error) 406 )). 407 408:- if(current_predicate(unix_domain_socket/1)). 409make_socket(Address, Socket) :- 410 ( atom(Address) 411 ; string(Address) 412 ), 413 !, 414 unix_domain_socket(Socket). 415:- endif. 416make_socket(_Address, Socket) :- 417 tcp_socket(Socket).
select()
call
underlying wait_for_input/3. As input multiplexing typically happens
in a background thread anyway we accept the loss of timeouts and
interrupts.
431tcp_select(ListOfStreams, ReadyList, TimeOut) :- 432 wait_for_input(ListOfStreams, ReadyList, TimeOut). 433 434 435 /******************************* 436 * PROXY SUPPORT * 437 *******************************/ 438 439try_a_proxy(Address, Result) :- 440 format(atom(URL), 'socket://~w', [Address]), 441 ( Address = Host:_ 442 -> true 443 ; Host = Address 444 ), 445 proxy_for_url(URL, Host, Proxy), 446 debug(socket(proxy), 'Socket connecting via ~w~n', [Proxy]), 447 ( catch(try_proxy(Proxy, Address, Socket, Stream), E, true) 448 -> ( var(E) 449 -> !, Result = true(Proxy, Socket, Stream) 450 ; Result = error(Proxy, E) 451 ) 452 ; Result = false(Proxy) 453 ), 454 debug(socket(proxy), 'Socket: ~w: ~p', [Proxy, Result]).
The default implementation recognises the values for Proxy
described below. The library(http/http_proxy) adds
proxy(Host,Port)
which allows for HTTP proxies using the
CONNECT
method.
475:- multifile 476 try_proxy/4. 477 478try_proxy(direct, Address, Socket, StreamPair) :- 479 !, 480 tcp_connect_direct(Address, Socket, StreamPair). 481try_proxy(socks(Host, Port), Address, Socket, StreamPair) :- 482 !, 483 tcp_connect_direct(Host:Port, Socket, StreamPair), 484 catch(negotiate_socks_connection(Address, StreamPair), 485 Error, 486 ( close(StreamPair, [force(true)]), 487 throw(Error) 488 )).
These correspond to the proxy methods defined by PAC Proxy auto-config. Additional methods can be returned if suitable clauses for http:http_connection_over_proxy/6 or try_proxy/4 are defined.
511:- multifile 512 proxy_for_url/3. 513 514 515 /******************************* 516 * OPTIONS * 517 *******************************/
setsockopt()
and the socket interface (e.g.,
socket(7)
on Linux) for details.
tcp_socket(Socket), tcp_setopt(Socket, bindtodevice(lo))
true
, disable the Nagle optimization on this socket,
which is enabled by default on almost all modern TCP/IP
stacks. The Nagle optimization joins small packages, which is
generally desirable, but sometimes not. Please note that the
underlying TCP_NODELAY setting to setsockopt()
is not
available on all platforms and systems may require additional
privileges to change this option. If the option is not
supported, tcp_setopt/2 raises a domain_error exception. See
Wikipedia
for details.setsockopt()
with the
corresponding arguments.swipl-win.exe
executable) this flags defines whether or not any events are
dispatched on behalf of the user interface. Default is
true
. Only very specific situations require setting
this to false
.fcntl()
call. Currently only suitable to deal
switch stream to non-blocking mode using:
tcp_fcntl(Stream, setfl, nonblock),
An attempt to read from a non-blocking stream while there is no
data available returns -1 (or end_of_file
for read/1), but
at_end_of_stream/1 fails. On actual end-of-input,
at_end_of_stream/1 succeeds.
595tcp_fcntl(Socket, setfl, nonblock) :-
596 !,
597 tcp_setopt(Socket, nonblock).
domain_error
exception.
getaddrinfo()
and the
IP-number is unified to Address using a term of the format
ip(Byte1,Byte2,Byte3,Byte4)
. Otherwise, if Address is bound to
an ip(Byte1,Byte2,Byte3,Byte4)
term, it is resolved by
gethostbyaddr()
and the canonical hostname is unified with
HostName.
gethostname()
and return the canonical name
returned by getaddrinfo()
.628 /******************************* 629 * SOCKS * 630 *******************************/
ip(A,B,C,D)
: port642negotiate_socks_connection(Host:Port, StreamPair):- 643 format(StreamPair, '~s', [[0x5, % Version 5 644 0x1, % 1 auth method supported 645 0x0]]), % which is 'no auth' 646 flush_output(StreamPair), 647 get_byte(StreamPair, ServerVersion), 648 get_byte(StreamPair, AuthenticationMethod), 649 ( ServerVersion =\= 0x05 650 -> throw(error(socks_error(invalid_version(5, ServerVersion)), _)) 651 ; AuthenticationMethod =:= 0xff 652 -> throw(error(socks_error(invalid_authentication_method( 653 0xff, 654 AuthenticationMethod)), _)) 655 ; true 656 ), 657 ( Host = ip(A,B,C,D) 658 -> AddressType = 0x1, % IPv4 Address 659 format(atom(Address), '~s', [[A, B, C, D]]) 660 ; AddressType = 0x3, % Domain 661 atom_length(Host, Length), 662 format(atom(Address), '~s~w', [[Length], Host]) 663 ), 664 P1 is Port /\ 0xff, 665 P2 is Port >> 8, 666 format(StreamPair, '~s~w~s', [[0x5, % Version 5 667 0x1, % Please establish a connection 668 0x0, % reserved 669 AddressType], 670 Address, 671 [P2, P1]]), 672 flush_output(StreamPair), 673 get_byte(StreamPair, _EchoedServerVersion), 674 get_byte(StreamPair, Status), 675 ( Status =:= 0 % Established! 676 -> get_byte(StreamPair, _Reserved), 677 get_byte(StreamPair, EchoedAddressType), 678 ( EchoedAddressType =:= 0x1 679 -> get_byte(StreamPair, _), % read IP4 680 get_byte(StreamPair, _), 681 get_byte(StreamPair, _), 682 get_byte(StreamPair, _) 683 ; get_byte(StreamPair, Length), % read host name 684 forall(between(1, Length, _), 685 get_byte(StreamPair, _)) 686 ), 687 get_byte(StreamPair, _), % read port 688 get_byte(StreamPair, _) 689 ; throw(error(socks_error(negotiation_rejected(Status)), _)) 690 ). 691 692 693 /******************************* 694 * MESSAGES * 695 *******************************/ 696 697/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 698The C-layer generates exceptions of the following format, where Message 699is extracted from the operating system. 700 701 error(socket_error(Code, Message), _) 702- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 703 704:- multifile 705 prolog:error_message//1. 706 707prologerror_message(socket_error(_Code, Message)) --> 708 [ 'Socket error: ~w'-[Message] ]. 709prologerror_message(socks_error(Error)) --> 710 socks_error(Error). 711prologerror_message(proxy_error(tried(Tried))) --> 712 [ 'Failed to connect using a proxy. Tried:'-[], nl], 713 proxy_tried(Tried). 714 715socks_error(invalid_version(Supported, Got)) --> 716 [ 'SOCKS: unsupported version: ~p (supported: ~p)'- 717 [ Got, Supported ] ]. 718socks_error(invalid_authentication_method(Supported, Got)) --> 719 [ 'SOCKS: unsupported authentication method: ~p (supported: ~p)'- 720 [ Got, Supported ] ]. 721socks_error(negotiation_rejected(Status)) --> 722 [ 'SOCKS: connection failed: ~p'-[Status] ]. 723 724proxy_tried([]) --> []. 725proxy_tried([H|T]) --> 726 proxy_tried(H), 727 proxy_tried(T). 728proxy_tried(error(Proxy, Error)) --> 729 [ '~w: '-[Proxy] ], 730 '$messages':translate_message(Error). 731proxy_tried(false(Proxy)) --> 732 [ '~w: failed with unspecified error'-[Proxy] ]
Network socket (TCP and UDP) library
The library(socket) provides TCP and UDP inet-domain sockets from SWI-Prolog, both client and server-side communication. The interface of this library is very close to the Unix socket interface, also supported by the MS-Windows winsock API. SWI-Prolog applications that wish to communicate with multiple sources have three options:
socket
which synchronises socket events in the GUI event-loop.Client applications
Using this library to establish a TCP connection to a server is as simple as opening a file. See also http_open/3.
To deal with timeouts and multiple connections, threads, wait_for_input/3 and/or non-blocking streams (see tcp_fcntl/3) can be used.
Server applications
The typical sequence for generating a server application is given below. To close the server, use close/1 on AcceptFd.
There are various options for <dispatch>. The most commonly used option is to start a Prolog thread to handle the connection. Alternatively, input from multiple clients can be handled in a single thread by listening to these clients using wait_for_input/3. Finally, on Unix systems, we can use fork/1 to handle the connection in a new process. Note that fork/1 and threads do not cooperate well. Combinations can be realised but require good understanding of POSIX thread and fork-semantics.
Below is the typical example using a thread. Note the use of setup_call_cleanup/3 to guarantee that all resources are reclaimed, also in case of failure or exceptions.
Socket exceptions
Errors that are trapped by the low-level library are mapped to an exception of the shape below. In this term, Code is a lower case atom that corresponds to the C macro name, e.g.,
epipe
for a broken pipe. Message is the human readable string for the error code returned by the OS or the same as Code if the OS does not provide this functionality. Note that Code is derived from a static set of macros that may or may not be defines for the target OS. If the macro name is not known, Code isERROR_nnn
, where nnn is an integer.Note that on Windows Code is a
wsa*
code which makes it hard to write portable code that handles specific socket errors. Even on POSIX systems the exact set of errors produced by the network stack is not defined.TCP socket predicates
*/