View source with raw comments or as raw
    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)  2013-2018, 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(http_unix_daemon,
   38          [ http_daemon/0,
   39            http_daemon/1                       % +Options
   40          ]).   41:- use_module(library(error)).   42:- use_module(library(apply)).   43:- use_module(library(lists)).   44:- use_module(library(debug)).   45:- use_module(library(broadcast)).   46:- use_module(library(socket)).   47:- use_module(library(option)).   48:- use_module(library(uid)).   49:- use_module(library(unix)).   50:- use_module(library(syslog)).   51:- use_module(library(http/thread_httpd)).   52:- use_module(library(http/http_dispatch)).   53:- use_module(library(http/http_host)).   54:- use_module(library(main)).   55:- use_module(library(readutil)).   56
   57:- if(( exists_source(library(http/http_ssl_plugin)),
   58        \+ current_prolog_flag(pldoc_to_tex,true))).   59:- use_module(library(ssl)).   60:- use_module(library(http/http_ssl_plugin)).   61:- endif.   62
   63:- multifile
   64    http_server_hook/1,                     % +Options
   65    http_certificate_hook/3,                % +CertFile, +KeyFile, -Password
   66    http:sni_options/2.                     % +HostName, +SSLOptions
   67
   68:- initialization(http_daemon, main).

Run SWI-Prolog HTTP server as a Unix system daemon

This module provides the logic that is needed to integrate a process into the Unix service (daemon) architecture. It deals with the following aspects, all of which may be used/ignored and configured using commandline options:

The typical use scenario is to write a file that loads the following components:

  1. The application code, including http handlers (see http_handler/3).
  2. This library

In the code below, ?- [load]. loads the remainder of the webserver code. This is often a sequence of use_module/1 directives.

:- use_module(library(http/http_unix_daemon)).

:- [load].

The program entry point is http_daemon/0, declared using initialization/2. This may be overruled using a new declaration after loading this library. The new entry point will typically call http_daemon/1 to start the server in a preconfigured way.

:- use_module(library(http/http_unix_daemon)).
:- initialization(run, main).

run :-
    ...
    http_daemon(Options).

Now, the server may be started using the command below. See http_daemon/0 for supported options.

% [sudo] swipl mainfile.pl [option ...]

Below are some examples. Our first example is completely silent, running on port 80 as user www.

% swipl mainfile.pl --user=www --pidfile=/var/run/http.pid

Our second example logs HTTP interaction with the syslog daemon for debugging purposes. Note that the argument to --debug= is a Prolog term and must often be escaped to avoid misinterpretation by the Unix shell. The debug option can be repeated to log multiple debug topics.

% swipl mainfile.pl --user=www --pidfile=/var/run/http.pid \
        --debug='http(request)' --syslog=http

Broadcasting The library uses broadcast/1 to allow hooking certain events:

http(pre_server_start)
Run after fork, just before starting the HTTP server. Can be used to load additional files or perform additional initialisation, such as starting additional threads. Recall that it is not possible to start threads before forking.
http(post_server_start)
Run after starting the HTTP server.
See also
- The file <swi-home>/doc/packages/examples/http/linux-init-script provides a /etc/init.d script for controlling a server as a normal Unix service. */
To be done
- Cleanup issues wrt. loading and initialization of xpce.
  157:- debug(daemon).  158
  159% Do not run xpce in a thread. This disables forking. The problem here
  160% is that loading library(pce) starts the event dispatching thread. This
  161% should be handled lazily.
  162
  163:- set_prolog_flag(xpce_threaded,   false).  164:- set_prolog_flag(message_ide,     false). % cause xpce to trap messages
  165:- set_prolog_flag(message_context, [thread,time('%F %T.%3f')]).  166:- dynamic interactive/0.
 http_daemon
Start the HTTP server as a daemon process. This predicate processes the commandline arguments below. Commandline arguments that specify servers are processed in the order they appear using the following schema:
  1. Arguments that act as default for all servers.
  2. --http=Spec or --https=Spec is followed by arguments for that server until the next --http=Spec or --https=Spec or the end of the options.
  3. If no --http=Spec or --https=Spec appears, one HTTP server is created from the specified parameters.

    Examples:

    --workers=10 --http --https
    --http=8080 --https=8443
    --http=localhost:8080 --workers=1 --https=8443 --workers=25
--port=Port
Start HTTP server at Port. It requires root permission and the option --user=User to open ports below 1000. The default port is 80. If --https is used, the default port is 443.
--ip=IP
Only listen to the given IP address. Typically used as --ip=localhost to restrict access to connections from localhost if the server itself is behind an (Apache) proxy server running on the same host.
--debug=Topic
Enable debugging Topic. See debug/3.
--syslog=Ident
Write debug messages to the syslog daemon using Ident
--user=User
When started as root to open a port below 1000, this option must be provided to switch to the target user for operating the server. The following actions are performed as root, i.e., before switching to User:
  • open the socket(s)
  • write the pidfile
  • setup syslog interaction
  • Read the certificate, key and password file (--pwfile=File)
--group=Group
May be used in addition to --user. If omitted, the login group of the target user is used.
--pidfile=File
Write the PID of the daemon process to File.
--output=File
Send output of the process to File. By default, all Prolog console output is discarded.
--fork[=Bool]
If given as --no-fork or --fork=false, the process runs in the foreground.
--http[=(Bool|Port|BindTo:Port)]
Create a plain HTTP server. If the argument is missing or true, create at the specified or default address. Else use the given port and interface. Thus, --http creates a server at port 80, --http=8080 creates one at port 8080 and --http=localhost:8080 creates one at port 8080 that is only accessible from localhost.
--https[=(Bool|Port|BindTo:Port)]
As --http, but creates an HTTPS server. Use --certfile, --keyfile, -pwfile, --password and --cipherlist to configure SSL for this server.
--certfile=File
The server certificate for HTTPS.
--keyfile=File
The server private key for HTTPS.
--pwfile=File
File holding the password for accessing the private key. This is preferred over using --password=PW as it allows using file protection to avoid leaking the password. The file is read before the server drops privileges when started with the --user option.
--password=PW
The password for accessing the private key. See also `--pwfile`.
--cipherlist=Ciphers
One or more cipher strings separated by colons. See the OpenSSL documentation for more information. Starting with SWI-Prolog 7.5.11, the default value is always a set of ciphers that was considered secure enough to prevent all critical attacks at the time of the SWI-Prolog release.
--interactive[=Bool]
If true (default false) implies --no-fork and presents the Prolog toplevel after starting the server.
--gtrace=[Bool]
Use the debugger to trace http_daemon/1.
--sighup=Action
Action to perform on kill -HUP <pid>. Default is reload (running make/0). Alternative is quit, stopping the server.

Other options are converted by argv_options/3 and passed to http_server/1. For example, this allows for:

--workers=Count
Set the number of workers for the multi-threaded server.

http_daemon/0 is defined as below. The start code for a specific server can use this as a starting point, for example for specifying defaults.

http_daemon :-
    current_prolog_flag(argv, Argv),
    argv_options(Argv, _RestArgv, Options),
    http_daemon(Options).
See also
- http_daemon/1
  300http_daemon :-
  301    current_prolog_flag(argv, Argv),
  302    argv_options(Argv, _RestArgv, Options),
  303    http_daemon(Options).
 http_daemon(+Options)
Start the HTTP server as a daemon process. This predicate processes a Prolog option list. It is normally called from http_daemon/0, which derives the option list from the command line arguments.

Error handling depends on whether or not interactive(true) is in effect. If so, the error is printed before entering the toplevel. In non-interactive mode this predicate calls halt(1).

  315http_daemon(Options) :-
  316    catch(http_daemon_guarded(Options), Error, start_failed(Error)).
  317
  318start_failed(Error) :-
  319    interactive,
  320    !,
  321    print_message(warning, Error).
  322start_failed(Error) :-
  323    print_message(error, Error),
  324    halt(1).
 http_daemon_guarded(+Options)
Helper that is started from http_daemon/1. See http_daemon/1 for options that are processed.
  331http_daemon_guarded(Options) :-
  332    option(help(true), Options),
  333    !,
  334    print_message(information, http_daemon(help)),
  335    halt.
  336http_daemon_guarded(Options) :-
  337    setup_debug(Options),
  338    kill_x11(Options),
  339    option_servers(Options, Servers0),
  340    maplist(make_socket, Servers0, Servers),
  341    (   option(fork(true), Options, true),
  342        option(interactive(false), Options, false),
  343        can_switch_user(Options)
  344    ->  fork(Who),
  345        (   Who \== child
  346        ->  halt
  347        ;   disable_development_system,
  348            setup_syslog(Options),
  349            write_pid(Options),
  350            setup_output(Options),
  351            switch_user(Options),
  352            setup_signals(Options),
  353            start_servers(Servers),
  354            wait(Options)
  355        )
  356    ;   write_pid(Options),
  357        switch_user(Options),
  358        setup_signals(Options),
  359        start_servers(Servers),
  360        wait(Options)
  361    ).
 option_servers(+Options, -Sockets:list)
Find all sockets that must be created according to Options. Each socket is a term server(Scheme, Address, Opts), where Address is either a plain port (integer) or Host:Port. The latter binds the port to the interface belonging to Host. For example: socket(http, localhost:8080, Opts) creates an HTTP socket that binds to the localhost interface on port 80. Opts are the options specific for the given server.
  373option_servers(Options, Sockets) :-
  374    opt_sockets(Options, [], [], Sockets).
  375
  376opt_sockets([], Options, [], [Socket]) :-
  377    !,
  378    make_server(http(true), Options, Socket).
  379opt_sockets([], _, Sockets, Sockets).
  380opt_sockets([H|T], OptsH, Sockets0, Sockets) :-
  381    server_option(H),
  382    !,
  383    append(OptsH, [H], OptsH1),
  384    opt_sockets(T, OptsH1, Sockets0, Sockets).
  385opt_sockets([H|T0], Opts, Sockets0, Sockets) :-
  386    server_start_option(H),
  387    !,
  388    server_options(T0, T, Opts, SOpts),
  389    make_server(H, SOpts, Socket),
  390    append(Sockets0, [Socket], Sockets1),
  391    opt_sockets(T, Opts, Sockets1, Sockets).
  392opt_sockets([_|T], Opts, Sockets0, Sockets) :-
  393    opt_sockets(T, Opts, Sockets0, Sockets).
  394
  395server_options([], [], Options, Options).
  396server_options([H|T], Rest, Options0, Options) :-
  397    server_option(H),
  398    !,
  399    generalise_option(H, G),
  400    delete(Options0, G, Options1),
  401    append(Options1, [H], Options2),
  402    server_options(T, Rest, Options2, Options).
  403server_options([H|T], [H|T], Options, Options) :-
  404    server_start_option(H),
  405    !.
  406server_options([_|T0], Rest, Options0, Options) :-
  407    server_options(T0, Rest, Options0, Options).
  408
  409generalise_option(H, G) :-
  410    H =.. [Name,_],
  411    G =.. [Name,_].
  412
  413server_start_option(http(_)).
  414server_start_option(https(_)).
  415
  416server_option(port(_)).
  417server_option(ip(_)).
  418server_option(certfile(_)).
  419server_option(keyfile(_)).
  420server_option(pwfile(_)).
  421server_option(password(_)).
  422server_option(cipherlist(_)).
  423server_option(workers(_)).
  424server_option(redirect(_)).
  425server_option(timeout(_)).
  426server_option(keep_alive_timeout(_)).
  427
  428make_server(http(Address0), Options0, server(http, Address, Options)) :-
  429    make_address(Address0, 80, Address, Options0, Options).
  430make_server(https(Address0), Options0, server(https, Address, SSLOptions)) :-
  431    make_address(Address0, 443, Address, Options0, Options),
  432    merge_https_options(Options, SSLOptions).
  433
  434make_address(true, DefPort, Address, Options0, Options) :-
  435    !,
  436    option(port(Port), Options0, DefPort),
  437    (   option(ip(Bind), Options0)
  438    ->  Address = (Bind:Port)
  439    ;   Address = Port
  440    ),
  441    merge_options([port(Port)], Options0, Options).
  442make_address(Bind:Port, _, Bind:Port, Options0, Options) :-
  443    !,
  444    must_be(atom, Bind),
  445    must_be(integer, Port),
  446    merge_options([port(Port), ip(Bind)], Options0, Options).
  447make_address(Port, _, Address, Options0, Options) :-
  448    integer(Port),
  449    !,
  450    (   option(ip(Bind), Options0)
  451    ->  Address = (Bind:Port)
  452    ;   Address = Port,
  453        merge_options([port(Port)], Options0, Options)
  454    ).
  455make_address(Spec, _, Address, Options0, Options) :-
  456    atomic(Spec),
  457    split_string(Spec, ":", "", [BindString, PortString]),
  458    number_string(Port, PortString),
  459    !,
  460    atom_string(Bind, BindString),
  461    Address = (Bind:Port),
  462    merge_options([port(Port), ip(Bind)], Options0, Options).
  463make_address(Spec, _, _, _, _) :-
  464    domain_error(address, Spec).
  465
  466:- dynamic sni/3.  467
  468merge_https_options(Options, [SSL|Options]) :-
  469    (   option(certfile(CertFile), Options),
  470        option(keyfile(KeyFile), Options)
  471    ->  prepare_https_certificate(CertFile, KeyFile, Passwd0),
  472        read_file_to_string(CertFile, Certificate, []),
  473        read_file_to_string(KeyFile, Key, []),
  474        Pairs = [Certificate-Key]
  475    ;   Pairs = []
  476    ),
  477    ssl_secure_ciphers(SecureCiphers),
  478    option(cipherlist(CipherList), Options, SecureCiphers),
  479    (   string(Passwd0)
  480    ->  Passwd = Passwd0
  481    ;   options_password(Options, Passwd)
  482    ),
  483    findall(HostName-HostOptions, http:sni_options(HostName, HostOptions), SNIs),
  484    maplist(sni_contexts, SNIs),
  485    SSL = ssl([ certificate_key_pairs(Pairs),
  486                cipher_list(CipherList),
  487                password(Passwd),
  488                sni_hook(http_unix_daemon:sni)
  489              ]).
  490
  491sni_contexts(Host-Options) :-
  492    ssl_context(server, SSL, Options),
  493    assertz(sni(_, Host, SSL)).
 http_certificate_hook(+CertFile, +KeyFile, -Password) is semidet
Hook called before starting the server if the --https option is used. This hook may be used to create or refresh the certificate. If the hook binds Password to a string, this string will be used to decrypt the server private key as if the --password=Password option was given.
  503prepare_https_certificate(CertFile, KeyFile, Password) :-
  504    http_certificate_hook(CertFile, KeyFile, Password),
  505    !.
  506prepare_https_certificate(_, _, _).
  507
  508
  509options_password(Options, Passwd) :-
  510    option(password(Passwd), Options),
  511    !.
  512options_password(Options, Passwd) :-
  513    option(pwfile(File), Options),
  514    !,
  515    read_file_to_string(File, String, []),
  516    split_string(String, "", "\r\n\t ", [Passwd]).
  517options_password(_, '').
 start_server(+Server) is det
Start the HTTP server. It performs the following steps:
  1. Call broadcast(http(pre_server_start))
  2. Call http_server(http_dispatch, Options)
  3. Call broadcast(http(post_server_start))

This predicate can be hooked using http_server_hook/1. This predicate is executed after

  535start_servers(Servers) :-
  536    broadcast(http(pre_server_start)),
  537    maplist(start_server, Servers),
  538    broadcast(http(post_server_start)).
  539
  540start_server(server(_Scheme, Socket, Options)) :-
  541    option(redirect(To), Options),
  542    !,
  543    http_server(server_redirect(To), [tcp_socket(Socket)|Options]).
  544start_server(server(_Scheme, Socket, Options)) :-
  545    http_server_hook([tcp_socket(Socket)|Options]),
  546    !.
  547start_server(server(_Scheme, Socket, Options)) :-
  548    http_server(http_dispatch, [tcp_socket(Socket)|Options]).
  549
  550make_socket(server(Scheme, Address, Options),
  551            server(Scheme, Socket, Options)) :-
  552    tcp_socket(Socket),
  553    catch(bind_socket(Socket, Address), Error,
  554          make_socket_error(Error, Address)),
  555    debug(daemon(socket),
  556          'Created socket ~p, listening on ~p', [Socket, Address]).
  557
  558bind_socket(Socket, Address) :-
  559    tcp_setopt(Socket, reuseaddr),
  560    tcp_bind(Socket, Address),
  561    tcp_listen(Socket, 5).
  562
  563make_socket_error(error(socket_error(_,_), _), Address) :-
  564    address_port(Address, Port),
  565    integer(Port),
  566    Port =< 1000,
  567    !,
  568    verify_root(open_port(Port)).
  569make_socket_error(Error, _) :-
  570    throw(Error).
  571
  572address_port(_:Port, Port) :- !.
  573address_port(Port, Port).
 disable_development_system
Disable some development stuff.
  579disable_development_system :-
  580    set_prolog_flag(editor, '/bin/false').
 enable_development_system
Re-enable the development environment. Currently re-enables xpce if this was loaded, but not initialised and causes the interactive toplevel to be re-enabled.
  588enable_development_system :-
  589    assertz(interactive),
  590    set_prolog_flag(xpce_threaded, true),
  591    set_prolog_flag(message_ide, true),
  592    (   current_prolog_flag(xpce_version, _)
  593    ->  call(pce_dispatch([]))
  594    ;   true
  595    ),
  596    set_prolog_flag(toplevel_goal, prolog).
 setup_syslog(+Options) is det
Setup syslog interaction.
  602setup_syslog(Options) :-
  603    option(syslog(Ident), Options),
  604    !,
  605    openlog(Ident, [pid], user).
  606setup_syslog(_).
 setup_output(+Options) is det
Setup output from the daemon process. The default is to send all output to a null-stream (see open_null_stream/1). With the option output(File), all output is written to File.
  615setup_output(Options) :-
  616    option(output(File), Options),
  617    !,
  618    open(File, write, Out, [encoding(utf8)]),
  619    set_stream(Out, buffer(line)),
  620    detach_IO(Out).
  621setup_output(_) :-
  622    open_null_stream(Out),
  623    detach_IO(Out).
 write_pid(+Options) is det
If the option pidfile(File) is present, write the PID of the daemon to this file.
  631write_pid(Options) :-
  632    option(pidfile(File), Options),
  633    current_prolog_flag(pid, PID),
  634    !,
  635    setup_call_cleanup(
  636        open(File, write, Out),
  637        format(Out, '~d~n', [PID]),
  638        close(Out)),
  639    at_halt(catch(delete_file(File), _, true)).
  640write_pid(_).
 switch_user(+Options) is det
Switch to the target user and group. If the server is started as root, this option must be present.
  648switch_user(Options) :-
  649    option(user(User), Options),
  650    !,
  651    verify_root(switch_user(User)),
  652    (   option(group(Group), Options)
  653    ->  set_user_and_group(User, Group)
  654    ;   set_user_and_group(User)
  655    ),
  656    prctl(set_dumpable(true)).      % re-enable core dumps on Linux
  657switch_user(_Options) :-
  658    verify_no_root.
 can_switch_user(Options) is det
Verify the user options before forking, so we can print the message in time.
  665can_switch_user(Options) :-
  666    option(user(User), Options),
  667    !,
  668    verify_root(switch_user(User)).
  669can_switch_user(_Options) :-
  670    verify_no_root.
  671
  672verify_root(_Task) :-
  673    geteuid(0),
  674    !.
  675verify_root(Task) :-
  676    print_message(error, http_daemon(no_root(Task))),
  677    halt(1).
  678
  679verify_no_root :-
  680    geteuid(0),
  681    !,
  682    throw(error(permission_error(open, server, http),
  683                context('Refusing to run HTTP server as root', _))).
  684verify_no_root.
  685
  686:- if(\+current_predicate(prctl/1)).  687prctl(_).
  688:- endif.
 server_redirect(+To, +Request)
Redirect al requests for this server to the specified server. To is one of:
A port (integer)
Redirect to the server running on that port in the same Prolog process.
true
Results from just passing --redirect. Redirects to an HTTPS server in the same Prolog process.
A URL
Redirect to the the given URL + the request uri. This can be used if the server cannot find its public address. For example:
--http --redirect=https://myhost.org --https
  710server_redirect(Port, Request) :-
  711    integer(Port),
  712    http_server_property(Port, scheme(Scheme)),
  713    http_public_host(Request, Host, _Port, []),
  714    memberchk(request_uri(Location), Request),
  715    (   default_port(Scheme, Port)
  716    ->  format(string(To), '~w://~w~w', [Scheme, Host, Location])
  717    ;   format(string(To), '~w://~w:~w~w', [Scheme, Host, Port, Location])
  718    ),
  719    throw(http_reply(moved_temporary(To))).
  720server_redirect(true, Request) :-
  721    !,
  722    http_server_property(P, scheme(https)),
  723    server_redirect(P, Request).
  724server_redirect(URI, Request) :-
  725    memberchk(request_uri(Location), Request),
  726    atom_concat(URI, Location, To),
  727    throw(http_reply(moved_temporary(To))).
  728
  729default_port(http, 80).
  730default_port(https, 443).
 setup_debug(+Options) is det
Initialse debug/3 topics. The --debug option may be used multiple times.
  738setup_debug(Options) :-
  739    setup_trace(Options),
  740    nodebug(_),
  741    debug(daemon),
  742    enable_debug(Options).
  743
  744enable_debug([]).
  745enable_debug([debug(Topic)|T]) :-
  746    !,
  747    atom_to_term(Topic, Term, _),
  748    debug(Term),
  749    enable_debug(T).
  750enable_debug([_|T]) :-
  751    enable_debug(T).
  752
  753setup_trace(Options) :-
  754    option(gtrace(true), Options),
  755    !,
  756    gtrace.
  757setup_trace(_).
 kill_x11(+Options) is det
Get rid of X11 access if interactive is false.
  764kill_x11(Options) :-
  765    getenv('DISPLAY', Display),
  766    Display \== '',
  767    option(interactive(false), Options, false),
  768    !,
  769    setenv('DISPLAY', ''),
  770    set_prolog_flag(gui, false).
  771kill_x11(_).
 setup_signals(+Options)
Prepare the server for signal handling. By default SIGINT and SIGTERM terminate the server. SIGHUP causes the server to run make/0.
  780setup_signals(Options) :-
  781    option(interactive(true), Options, false),
  782    !.
  783setup_signals(Options) :-
  784    on_signal(int,  _, quit),
  785    on_signal(term, _, quit),
  786    option(sighup(Action), Options, reload),
  787    must_be(oneof([reload,quit]), Action),
  788    on_signal(usr1, _, logrotate),
  789    on_signal(hup,  _, Action).
  790
  791:- public
  792    quit/1,
  793    reload/1,
  794    logrotate/1.  795
  796quit(Signal) :-
  797    debug(daemon, 'Dying on signal ~w', [Signal]),
  798    thread_send_message(main, quit).
  799
  800reload(Signal) :-
  801    debug(daemon, 'Reload on signal ~w', [Signal]),
  802    thread_send_message(main, reload).
  803
  804logrotate(Signal) :-
  805    debug(daemon, 'Closing log files on signal ~w', [Signal]),
  806    thread_send_message(main, logrotate).
 wait(+Options)
This predicate runs in the main thread, waiting for messages send by signal handlers to control the server. In addition, it broadcasts maintenance(Interval, Deadline) messages every Interval seconds. These messages may be trapped using listen/2 for performing scheduled maintenance such as rotating log files, cleaning stale data, etc.
  817wait(Options) :-
  818    option(interactive(true), Options, false),
  819    !,
  820    enable_development_system.
  821wait(Options) :-
  822    thread_self(Me),
  823    option(maintenance_interval(Interval), Options, 300),
  824    Interval > 0,
  825    !,
  826    first_deadline(Interval, FirstDeadline),
  827    State = deadline(0),
  828    repeat,
  829        State = deadline(Count),
  830        Deadline is FirstDeadline+Count*Interval,
  831        (   thread_idle(thread_get_message(Me, Msg, [deadline(Deadline)]),
  832                        long)
  833        ->  catch(ignore(handle_message(Msg)), E,
  834                  print_message(error, E)),
  835            Msg == quit,
  836            halt(0)
  837        ;   Count1 is Count + 1,
  838            nb_setarg(1, State, Count1),
  839            catch(broadcast(maintenance(Interval, Deadline)), E,
  840                  print_message(error, E)),
  841            fail
  842        ).
  843wait(_) :-
  844    thread_self(Me),
  845    repeat,
  846        thread_idle(thread_get_message(Me, Msg), long),
  847        catch(ignore(handle_message(Msg)), E,
  848              print_message(error, E)),
  849        Msg == quit,
  850        !,
  851        halt(0).
  852
  853handle_message(reload) :-
  854    make,
  855    broadcast(logrotate).
  856handle_message(logrotate) :-
  857    broadcast(logrotate).
  858
  859first_deadline(Interval, Deadline) :-
  860    get_time(Now),
  861    Deadline is ((integer(Now) + Interval - 1)//Interval)*Interval.
  862
  863
  864                 /*******************************
  865                 *            HOOKS             *
  866                 *******************************/
 http_server_hook(+Options) is semidet
Hook that is called to start the HTTP server. This hook must be compatible to http_server(Handler, Options). The default is provided by start_server/1.
 http:sni_options(-HostName, -SSLOptions) is multi
Hook to provide Server Name Indication (SNI) for TLS servers. When starting an HTTPS server, all solutions of this predicate are collected and a suitable sni_hook/1 is defined for ssl_context/3 to use different contexts depending on the host name of the client request. This hook is executed before privileges are dropped.
  885                 /*******************************
  886                 *           MESSAGES           *
  887                 *******************************/
  888
  889:- multifile
  890    prolog:message//1.  891
  892prolog:message(http_daemon(help)) -->
  893    [ 'Usage: <program> option ...'-[], nl,
  894      'Options:'-[], nl, nl,
  895      '  --port=port        HTTP port to listen to'-[], nl,
  896      '  --ip=IP            Only listen to this ip (--ip=localhost)'-[], nl,
  897      '  --debug=topic      Print debug message for topic'-[], nl,
  898      '  --syslog=ident     Send output to syslog daemon as ident'-[], nl,
  899      '  --user=user        Run server under this user'-[], nl,
  900      '  --group=group      Run server under this group'-[], nl,
  901      '  --pidfile=path     Write PID to path'-[], nl,
  902      '  --output=file      Send output to file (instead of syslog)'-[], nl,
  903      '  --fork=bool        Do/do not fork'-[], nl,
  904      '  --http[=Address]   Create HTTP server'-[], nl,
  905      '  --https[=Address]  Create HTTPS server'-[], nl,
  906      '  --certfile=file    The server certificate'-[], nl,
  907      '  --keyfile=file     The server private key'-[], nl,
  908      '  --pwfile=file      File holding password for the private key'-[], nl,
  909      '  --password=pw      Password for the private key'-[], nl,
  910      '  --cipherlist=cs    Cipher strings separated by colons'-[], nl,
  911      '  --redirect=to      Redirect all requests to a URL or port'-[], nl,
  912      '  --interactive=bool Enter Prolog toplevel after starting server'-[], nl,
  913      '  --gtrace=bool      Start (graphical) debugger'-[], nl,
  914      '  --sighup=action    Action on SIGHUP: reload (default) or quit'-[], nl,
  915      '  --workers=count    Number of HTTP worker threads'-[], nl,
  916      '  --timeout=sec      Time to wait for client to complete request'-[], nl,
  917      '  --keep_alive_timeout=sec'-[], nl,
  918      '                     Time to wait for a new request'-[], nl,
  919      nl,
  920      'Boolean options may be written without value (true) or as --no-name (false)'-[], nl,
  921      'Address is a port number or host:port, e.g., 8080 or localhost:8080'-[], nl,
  922      'Multiple servers can be started by repeating --http and --https'-[], nl,
  923      'Each server merges the options before the first --http(s) and up the next'-[]
  924    ].
  925prolog:message(http_daemon(no_root(switch_user(User)))) -->
  926    [ 'Program must be started as root to use --user=~w.'-[User] ].
  927prolog:message(http_daemon(no_root(open_port(Port)))) -->
  928    [ 'Cannot open port ~w.  Only root can open ports below 1000.'-[Port] ]