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-2016, University of Amsterdam 7 VU University Amsterdam 8 All rights reserved. 9 10 Redistribution and use in source and binary forms, with or without 11 modification, are permitted provided that the following conditions 12 are met: 13 14 1. Redistributions of source code must retain the above copyright 15 notice, this list of conditions and the following disclaimer. 16 17 2. Redistributions in binary form must reproduce the above copyright 18 notice, this list of conditions and the following disclaimer in 19 the documentation and/or other materials provided with the 20 distribution. 21 22 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 25 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 26 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 27 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 28 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 29 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 30 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 31 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 32 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 33 POSSIBILITY OF SUCH DAMAGE. 34*/ 35 36:- module(socket, 37 [ tcp_socket/1, % -Socket 38 tcp_close_socket/1, % +Socket 39 tcp_open_socket/3, % +Socket, -Read, -Write 40 tcp_connect/2, % +Socket, +Address 41 tcp_connect/3, % +Socket, +Address, -StreamPair 42 tcp_connect/4, % +Socket, +Address, -Read, -Write) 43 tcp_bind/2, % +Socket, +Address 44 tcp_accept/3, % +Master, -Slave, -PeerName 45 tcp_listen/2, % +Socket, +BackLog 46 tcp_fcntl/3, % +Socket, +Command, ?Arg 47 tcp_setopt/2, % +Socket, +Option 48 tcp_host_to_address/2, % ?HostName, ?Ip-nr 49 tcp_select/3, % +Inputs, -Ready, +Timeout 50 gethostname/1, % -HostName 51 52 tcp_open_socket/2, % +Socket, -StreamPair 53 54 udp_socket/1, % -Socket 55 udp_receive/4, % +Socket, -Data, -Sender, +Options 56 udp_send/4, % +Socket, +Data, +Sender, +Options 57 58 negotiate_socks_connection/2% +DesiredEndpoint, +StreamPair 59 ]). 60:- use_module(library(shlib)). 61:- use_module(library(debug)). 62:- use_module(library(lists)).
151:- multifile 152 tcp_connect_hook/3, % +Socket, +Addr, -In, -Out 153 tcp_connect_hook/4, % +Socket, +Addr, -Stream 154 proxy_for_url/3, % +URL, +Host, -ProxyList 155 try_proxy/4. % +Proxy, +Addr, -Socket, -Stream 156 157:- predicate_options(tcp_connect/3, 3, 158 [ bypass_proxy(boolean), 159 nodelay(boolean) 160 ]). 161 162:- use_foreign_library(foreign(socket), install_socket). 163:- public tcp_debug/1. % set debugging.
197tcp_open_socket(Socket, Stream) :-
198 tcp_open_socket(Socket, In, Out),
199 ( var(Out)
200 -> Stream = In
201 ; stream_pair(Stream, In, Out)
202 ).
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.
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))
275 /******************************* 276 * HOOKABLE CONNECT * 277 *******************************/
:- 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).
300tcp_connect(Socket, Address, Read, Write) :- 301 tcp_connect_hook(Socket, Address, Read, Write), 302 !. 303tcp_connect(Socket, Address, Read, Write) :- 304 tcp_connect(Socket, Address), 305 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).
339% Main mode: +,-,+ 340tcp_connect(Address, StreamPair, Options) :- 341 var(StreamPair), 342 !, 343 ( memberchk(bypass_proxy(true), Options) 344 -> tcp_connect_direct(Address, Socket, StreamPair) 345 ; findall(Result, 346 try_a_proxy(Address, Result), 347 ResultList), 348 last(ResultList, Status) 349 -> ( Status = true(_Proxy, Socket, StreamPair) 350 -> true 351 ; throw(error(proxy_error(tried(ResultList)), _)) 352 ) 353 ; tcp_connect_direct(Address, Socket, StreamPair) 354 ), 355 ( memberchk(nodelay(true), Options) 356 -> tcp_setopt(Socket, nodelay) 357 ; true 358 ). 359% backward compatibility mode +,+,- 360tcp_connect(Socket, Address, StreamPair) :- 361 tcp_connect_hook(Socket, Address, StreamPair0), 362 !, 363 StreamPair = StreamPair0. 364tcp_connect(Socket, Address, StreamPair) :- 365 tcp_connect(Socket, Address, Read, Write), 366 stream_pair(StreamPair, Read, Write). 367 368 369tcp_connect_direct(Address, Socket, StreamPair):- 370 tcp_socket(Socket), 371 catch(tcp_connect(Socket, Address, StreamPair), 372 Error, 373 ( tcp_close_socket(Socket), 374 throw(Error) 375 )).
384:- if(\+predicate_property(tcp_select(_,_,_), defined)). 385tcp_select(ListOfStreams, ReadyList, TimeOut) :- 386 wait_for_input(ListOfStreams, ReadyList, TimeOut). 387:- endif. 388 389 390 /******************************* 391 * PROXY SUPPORT * 392 *******************************/ 393 394try_a_proxy(Address, Result) :- 395 format(atom(URL), 'socket://~w', [Address]), 396 ( Address = Host:_ 397 -> true 398 ; Host = Address 399 ), 400 proxy_for_url(URL, Host, Proxy), 401 debug(socket(proxy), 'Socket connecting via ~w~n', [Proxy]), 402 ( catch(try_proxy(Proxy, Address, Socket, Stream), E, true) 403 -> ( var(E) 404 -> !, Result = true(Proxy, Socket, Stream) 405 ; Result = error(Proxy, E) 406 ) 407 ; Result = false(Proxy) 408 ), 409 debug(socket(proxy), 'Socket: ~w: ~p', [Proxy, Result]).
library(http/http_open)
) collect the results of failed
proxies and raise an exception no proxy is capable of realizing
the connection.
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.
430:- multifile 431 try_proxy/4. 432 433try_proxy(direct, Address, Socket, StreamPair) :- 434 !, 435 tcp_connect_direct(Address, Socket, StreamPair). 436try_proxy(socks(Host, Port), Address, Socket, StreamPair) :- 437 !, 438 tcp_connect_direct(Host:Port, Socket, StreamPair), 439 catch(negotiate_socks_connection(Address, StreamPair), 440 Error, 441 ( close(StreamPair, [force(true)]), 442 throw(Error) 443 )).
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.
466:- multifile 467 proxy_for_url/3. 468 469 470 /******************************* 471 * OPTIONS * 472 *******************************/
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.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.
533tcp_fcntl(Socket, setfl, nonblock) :-
534 !,
535 tcp_setopt(Socket, nonblock).
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()
.557 /******************************* 558 * SOCKS * 559 *******************************/
ip(A,B,C,D)
: port571negotiate_socks_connection(Host:Port, StreamPair):- 572 format(StreamPair, '~s', [[0x5, % Version 5 573 0x1, % 1 auth method supported 574 0x0]]), % which is 'no auth' 575 flush_output(StreamPair), 576 get_byte(StreamPair, ServerVersion), 577 get_byte(StreamPair, AuthenticationMethod), 578 ( ServerVersion =\= 0x05 579 -> throw(error(socks_error(invalid_version(5, ServerVersion)), _)) 580 ; AuthenticationMethod =:= 0xff 581 -> throw(error(socks_error(invalid_authentication_method( 582 0xff, 583 AuthenticationMethod)), _)) 584 ; true 585 ), 586 ( Host = ip(A,B,C,D) 587 -> AddressType = 0x1, % IPv4 Address 588 format(atom(Address), '~s', [[A, B, C, D]]) 589 ; AddressType = 0x3, % Domain 590 atom_length(Host, Length), 591 format(atom(Address), '~s~w', [[Length], Host]) 592 ), 593 P1 is Port /\ 0xff, 594 P2 is Port >> 8, 595 format(StreamPair, '~s~w~s', [[0x5, % Version 5 596 0x1, % Please establish a connection 597 0x0, % reserved 598 AddressType], 599 Address, 600 [P2, P1]]), 601 flush_output(StreamPair), 602 get_byte(StreamPair, _EchoedServerVersion), 603 get_byte(StreamPair, Status), 604 ( Status =:= 0 % Established! 605 -> get_byte(StreamPair, _Reserved), 606 get_byte(StreamPair, EchoedAddressType), 607 ( EchoedAddressType =:= 0x1 608 -> get_byte(StreamPair, _), % read IP4 609 get_byte(StreamPair, _), 610 get_byte(StreamPair, _), 611 get_byte(StreamPair, _) 612 ; get_byte(StreamPair, Length), % read host name 613 forall(between(1, Length, _), 614 get_byte(StreamPair, _)) 615 ), 616 get_byte(StreamPair, _), % read port 617 get_byte(StreamPair, _) 618 ; throw(error(socks_error(negotiation_rejected(Status)), _)) 619 ). 620 621 622 /******************************* 623 * MESSAGES * 624 *******************************/ 625 626/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 627The C-layer generates exceptions of the following format, where Message 628is extracted from the operating system. 629 630 error(socket_error(Message), _) 631- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 632 633:- multifile 634 prolog:error_message//1. 635 636prologerror_message(socket_error(Message)) --> 637 [ 'Socket error: ~w'-[Message] ]. 638prologerror_message(socks_error(Error)) --> 639 socks_error(Error). 640prologerror_message(proxy_error(tried(Tried))) --> 641 [ 'Failed to connect using a proxy. Tried:'-[], nl], 642 proxy_tried(Tried). 643 644socks_error(invalid_version(Supported, Got)) --> 645 [ 'SOCKS: unsupported version: ~p (supported: ~p)'- 646 [ Got, Supported ] ]. 647socks_error(invalid_authentication_method(Supported, Got)) --> 648 [ 'SOCKS: unsupported authentication method: ~p (supported: ~p)'- 649 [ Got, Supported ] ]. 650socks_error(negotiation_rejected(Status)) --> 651 [ 'SOCKS: connection failed: ~p'-[Status] ]. 652 653proxy_tried([]) --> []. 654proxy_tried([H|T]) --> 655 proxy_tried(H), 656 proxy_tried(T). 657proxy_tried(error(Proxy, Error)) --> 658 [ '~w: '-[Proxy] ], 659 '$messages':translate_message(Error). 660proxy_tried(false(Proxy)) --> 661 [ '~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.
TCP socket predicates
*/