View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker & Steve Prior
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           https://www.swi-prolog.org
    6    Copyright (c)  2004-2026, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9                              SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module(prolog_server,
   39          [ prolog_server/2             % +Port, +Options
   40          ]).   41
   42:- autoload(library(option), [option/2]).   43:- autoload(library(socket),
   44            [ tcp_socket/1,
   45              tcp_setopt/2,
   46              tcp_bind/2,
   47              tcp_listen/2,
   48              tcp_accept/3,
   49              tcp_open_socket/3,
   50              tcp_host_to_address/2,
   51              ip_name/2
   52            ]).   53
   54
   55%!  prolog_server(?Port, +Options)
   56%
   57%   Create a TCP/IP based server  on  the   given  Port,  so you can
   58%   telnet into Prolog and run an  interactive session. This library
   59%   is intended to provide access for   debugging  and management of
   60%   embedded servers.
   61%
   62%   Currently defined options are:
   63%
   64%     - allow(IPOrList)
   65%       Allow access from IP, a term of the format ip(A,B,C,D), (IPv4)
   66%       or ip(A, B, C, D, E, F, G, H) (IPv6). Access is granted if the
   67%       `Peer` address as returned by tcp_accept/3 _unifies_ with
   68%       IPOrList or, if IPOrList is a list, with a member of this list.
   69%       If no allow option is provided access is only granted from
   70%       ip(127,0,0,1) (localhost). <br>
   71%       __note__ Older versions allowed for repeating this option rather
   72%       than providing a list.
   73%
   74%   For example:
   75%
   76%   ```
   77%   ?- prolog_server(4000, []).
   78%
   79%   % ncat localhost 4000
   80%   Welcome to the SWI-Prolog server on thread client@127.0.0.1
   81%
   82%   1 ?-
   83%   ```
   84%
   85%   @bug  As  the connection  does  not  involve a  terminal,  command
   86%   history and  completion are  not provided. Neither  are interrupts
   87%   (Control-C).  The Prolog shell can be terminated if `netcat` shuts
   88%   down the socket on ^D (using the `-N` option).  Otherwise one must
   89%   enter the command "end_of_file."
   90%   @see The  add-on `libssh` provides  an embedded SSH  server.  This
   91%   provides encryption  as well as  a _pseudo terminal_, providing
   92%   full commandline editing, history and interrupt processing.
   93
   94prolog_server(Port, Options) :-
   95    tcp_socket(ServerSocket),
   96    tcp_setopt(ServerSocket, reuseaddr),
   97    tcp_bind(ServerSocket, Port),
   98    tcp_listen(ServerSocket, 5),
   99    thread_create(server_loop(ServerSocket, Options), _,
  100                  [ alias(prolog_server)
  101                  ]).
  102
  103server_loop(ServerSocket, Options) :-
  104    tcp_accept(ServerSocket, Slave, Peer),
  105    tcp_open_socket(Slave, InStream, OutStream),
  106    set_stream(InStream, close_on_abort(false)),
  107    set_stream(OutStream, close_on_abort(false)),
  108    catch(tcp_host_to_address(Host, Peer),
  109          error(socket_error(_,_),_),
  110          ip_name(Peer, Host)),
  111    (   Postfix = []
  112    ;   between(2, 1000, Num),
  113        Postfix = [-, Num]
  114    ),
  115    atomic_list_concat(['client@', Host | Postfix], Alias),
  116    catch(thread_create(
  117              service_client(InStream, OutStream, Peer, Options),
  118              _,
  119              [ alias(Alias),
  120                detached(true)
  121              ]),
  122          error(permission_error(create, thread, Alias), _),
  123          fail),
  124    !,
  125    server_loop(ServerSocket, Options).
  126
  127service_client(InStream, OutStream, Peer, Options) :-
  128    allow(Peer, Options),
  129    !,
  130    thread_self(Id),
  131    set_prolog_IO(InStream, OutStream, OutStream),
  132    set_stream(InStream, tty(true)),
  133    set_prolog_flag(tty_control, false),
  134    current_prolog_flag(encoding, Enc),
  135    set_stream(user_input, encoding(Enc)),
  136    set_stream(user_output, encoding(Enc)),
  137    set_stream(user_error, encoding(Enc)),
  138    set_stream(user_input, newline(detect)),
  139    set_stream(user_output, newline(dos)),
  140    set_stream(user_error, newline(dos)),
  141    format(user_error,
  142           'Welcome to the SWI-Prolog server on thread ~w~n~n',
  143           [Id]),
  144    call_cleanup(prolog,
  145                 ( close(InStream, [force(true)]),
  146                   close(OutStream, [force(true)]))).
  147service_client(InStream, OutStream, _, _):-
  148    thread_self(Id),
  149    format(OutStream, 'Go away!!~n', []),
  150    close(InStream),
  151    close(OutStream),
  152    thread_detach(Id).
  153
  154
  155allow(Peer, Options) :-
  156    (   option(allow(Allow), Options)
  157    ->  (   is_list(Allow)
  158        ->  memberchk(Peer, Allow)
  159        ;   Peer = Allow
  160        )
  161    ;   Peer = ip(127,0,0,1)
  162    )