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:- use_module(library(ssl)).   59:- use_module(library(http/http_ssl_plugin)).   60:- endif.   61
   62:- multifile
   63    http_server_hook/1,                     % +Options
   64    http_certificate_hook/3,                % +CertFile, +KeyFile, -Password
   65    http:sni_options/2.                     % +HostName, +SSLOptions
   66
   67:- 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.
  156:- debug(daemon).  157
  158% Do not run xpce in a thread. This disables forking. The problem here
  159% is that loading library(pce) starts the event dispatching thread. This
  160% should be handled lazily.
  161
  162:- set_prolog_flag(xpce_threaded,   false).  163:- set_prolog_flag(message_ide,     false). % cause xpce to trap messages
  164:- set_prolog_flag(message_context, [thread,time('%F %T.%3f')]).  165:- 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
  299http_daemon :-
  300    current_prolog_flag(argv, Argv),
  301    argv_options(Argv, _RestArgv, Options),
  302    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).

  314http_daemon(Options) :-
  315    catch(http_daemon_guarded(Options), Error, start_failed(Error)).
  316
  317start_failed(Error) :-
  318    interactive,
  319    !,
  320    print_message(warning, Error).
  321start_failed(Error) :-
  322    print_message(error, Error),
  323    halt(1).
 http_daemon_guarded(+Options)
Helper that is started from http_daemon/1. See http_daemon/1 for options that are processed.
  330http_daemon_guarded(Options) :-
  331    option(help(true), Options),
  332    !,
  333    print_message(information, http_daemon(help)),
  334    halt.
  335http_daemon_guarded(Options) :-
  336    setup_debug(Options),
  337    kill_x11(Options),
  338    option_servers(Options, Servers0),
  339    maplist(make_socket, Servers0, Servers),
  340    (   option(fork(true), Options, true),
  341        option(interactive(false), Options, false),
  342        can_switch_user(Options)
  343    ->  fork(Who),
  344        (   Who \== child
  345        ->  halt
  346        ;   disable_development_system,
  347            setup_syslog(Options),
  348            write_pid(Options),
  349            setup_output(Options),
  350            switch_user(Options),
  351            setup_signals(Options),
  352            start_servers(Servers),
  353            wait(Options)
  354        )
  355    ;   write_pid(Options),
  356        switch_user(Options),
  357        setup_signals(Options),
  358        start_servers(Servers),
  359        wait(Options)
  360    ).
 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.
  372option_servers(Options, Sockets) :-
  373    opt_sockets(Options, [], [], Sockets).
  374
  375opt_sockets([], Options, [], [Socket]) :-
  376    !,
  377    make_server(http(true), Options, Socket).
  378opt_sockets([], _, Sockets, Sockets).
  379opt_sockets([H|T], OptsH, Sockets0, Sockets) :-
  380    server_option(H),
  381    !,
  382    append(OptsH, [H], OptsH1),
  383    opt_sockets(T, OptsH1, Sockets0, Sockets).
  384opt_sockets([H|T0], Opts, Sockets0, Sockets) :-
  385    server_start_option(H),
  386    !,
  387    server_options(T0, T, Opts, SOpts),
  388    make_server(H, SOpts, Socket),
  389    append(Sockets0, [Socket], Sockets1),
  390    opt_sockets(T, Opts, Sockets1, Sockets).
  391opt_sockets([_|T], Opts, Sockets0, Sockets) :-
  392    opt_sockets(T, Opts, Sockets0, Sockets).
  393
  394server_options([], [], Options, Options).
  395server_options([H|T], Rest, Options0, Options) :-
  396    server_option(H),
  397    !,
  398    generalise_option(H, G),
  399    delete(Options0, G, Options1),
  400    append(Options1, [H], Options2),
  401    server_options(T, Rest, Options2, Options).
  402server_options([H|T], [H|T], Options, Options) :-
  403    server_start_option(H),
  404    !.
  405server_options([_|T0], Rest, Options0, Options) :-
  406    server_options(T0, Rest, Options0, Options).
  407
  408generalise_option(H, G) :-
  409    H =.. [Name,_],
  410    G =.. [Name,_].
  411
  412server_start_option(http(_)).
  413server_start_option(https(_)).
  414
  415server_option(port(_)).
  416server_option(ip(_)).
  417server_option(certfile(_)).
  418server_option(keyfile(_)).
  419server_option(pwfile(_)).
  420server_option(password(_)).
  421server_option(cipherlist(_)).
  422server_option(workers(_)).
  423server_option(redirect(_)).
  424server_option(timeout(_)).
  425server_option(keep_alive_timeout(_)).
  426
  427make_server(http(Address0), Options0, server(http, Address, Options)) :-
  428    make_address(Address0, 80, Address, Options0, Options).
  429make_server(https(Address0), Options0, server(https, Address, SSLOptions)) :-
  430    make_address(Address0, 443, Address, Options0, Options),
  431    merge_https_options(Options, SSLOptions).
  432
  433make_address(true, DefPort, Address, Options0, Options) :-
  434    !,
  435    option(port(Port), Options0, DefPort),
  436    (   option(ip(Bind), Options0)
  437    ->  Address = (Bind:Port)
  438    ;   Address = Port
  439    ),
  440    merge_options([port(Port)], Options0, Options).
  441make_address(Bind:Port, _, Bind:Port, Options0, Options) :-
  442    !,
  443    must_be(atom, Bind),
  444    must_be(integer, Port),
  445    merge_options([port(Port), ip(Bind)], Options0, Options).
  446make_address(Port, _, Address, Options0, Options) :-
  447    integer(Port),
  448    !,
  449    (   option(ip(Bind), Options0)
  450    ->  Address = (Bind:Port)
  451    ;   Address = Port,
  452        merge_options([port(Port)], Options0, Options)
  453    ).
  454make_address(Spec, _, Address, Options0, Options) :-
  455    atomic(Spec),
  456    split_string(Spec, ":", "", [BindString, PortString]),
  457    number_string(Port, PortString),
  458    !,
  459    atom_string(Bind, BindString),
  460    Address = (Bind:Port),
  461    merge_options([port(Port), ip(Bind)], Options0, Options).
  462make_address(Spec, _, _, _, _) :-
  463    domain_error(address, Spec).
  464
  465:- dynamic sni/3.  466
  467merge_https_options(Options, [SSL|Options]) :-
  468    (   option(certfile(CertFile), Options),
  469        option(keyfile(KeyFile), Options)
  470    ->  prepare_https_certificate(CertFile, KeyFile, Passwd0),
  471        read_file_to_string(CertFile, Certificate, []),
  472        read_file_to_string(KeyFile, Key, []),
  473        Pairs = [Certificate-Key]
  474    ;   Pairs = []
  475    ),
  476    ssl_secure_ciphers(SecureCiphers),
  477    option(cipherlist(CipherList), Options, SecureCiphers),
  478    (   string(Passwd0)
  479    ->  Passwd = Passwd0
  480    ;   options_password(Options, Passwd)
  481    ),
  482    findall(HostName-HostOptions, http:sni_options(HostName, HostOptions), SNIs),
  483    maplist(sni_contexts, SNIs),
  484    SSL = ssl([ certificate_key_pairs(Pairs),
  485                cipher_list(CipherList),
  486                password(Passwd),
  487                sni_hook(http_unix_daemon:sni)
  488              ]).
  489
  490sni_contexts(Host-Options) :-
  491    ssl_context(server, SSL, Options),
  492    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.
  502prepare_https_certificate(CertFile, KeyFile, Password) :-
  503    http_certificate_hook(CertFile, KeyFile, Password),
  504    !.
  505prepare_https_certificate(_, _, _).
  506
  507
  508options_password(Options, Passwd) :-
  509    option(password(Passwd), Options),
  510    !.
  511options_password(Options, Passwd) :-
  512    option(pwfile(File), Options),
  513    !,
  514    read_file_to_string(File, String, []),
  515    split_string(String, "", "\r\n\t ", [Passwd]).
  516options_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

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