% This LaTeX document was generated using the LaTeX backend of PlDoc,
% The SWI-Prolog documentation system



\subsubsection{library(http/http_unix_daemon): Run SWI-Prolog HTTP server as a Unix system daemon}

\label{sec:httpunixdaemon}

\begin{tags}
    \tag{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.
    \tag{To be done}
Cleanup issues wrt. loading and initialization of xpce.
\end{tags}

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:

\begin{itemize}
    \item Select the \verb$port(s)$ to be used by the server
    \item Run the startup of the process as root to perform privileged
tasks and the server itself as unpriviledged user, for example
to open ports below 1000.
    \item Fork and detach from the controlling terminal
    \item Handle console and debug output using a file and/or the syslog
daemon.
    \item Manage a \textit{pid file}
\end{itemize}

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

\begin{enumerate}
    \item The application code, including http handlers (see \predref{http_handler}{3}).
    \item This library
\end{enumerate}

In the code below, \verb$?- [load].$ loads the remainder of the webserver
code. This is often a sequence of \predref{use_module}{1} directives.

\begin{code}
:- use_module(library(http/http_unix_daemon)).

:- [load].
\end{code}

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

\begin{code}
:- use_module(library(http/http_unix_daemon)).
:- initialization(run, main).

run :-
    ...
    http_daemon(Options).
\end{code}

Now, the server may be started using the command below. See
\predref{http_daemon}{0} for supported options.

\begin{code}
% [sudo] swipl mainfile.pl [option ...]
\end{code}

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

\begin{code}
% swipl mainfile.pl --user=www --pidfile=/var/run/http.pid
\end{code}

Our second example logs HTTP interaction with the syslog daemon for
debugging purposes. Note that the argument to \verb$--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.

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

\textbf{Broadcasting} The library uses \predref{broadcast}{1} to allow hooking certain
events:

\begin{description}
    \termitem{http}{pre_server_start}
Run \textit{after} \textit{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 \textit{before} forking.
    \termitem{http}{post_server_start}
Run \textit{after} starting the HTTP server.
\end{description}

\vspace{0.7cm}

\begin{description}
    \predicate{http_daemon}{0}{}
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:

\begin{enumerate}
    \item Arguments that act as default for all servers.
    \item \verb$--http=Spec$ or \verb$--https=Spec$ is followed by
arguments for that server until the next \verb$--http=Spec$
or \verb$--https=Spec$ or the end of the options.
    \item If no \verb$--http=Spec$ or \verb$--https=Spec$ appears, one
HTTP server is created from the specified parameters.

Examples:

\begin{code}
--workers=10 --http --https
--http=8080 --https=8443
--http=localhost:8080 --workers=1 --https=8443 --workers=25
\end{code}

\end{enumerate}

\begin{description}
    \item[--port=Port] 
Start HTTP server at Port. It requires root permission and the
option \verb$--user=User$ to open ports below 1000. The default
port is 80. If \verb$--https$ is used, the default port is 443.
    \item[--ip=IP] 
Only listen to the given IP address. Typically used as
\verb$--ip=localhost$ to restrict access to connections from
\textit{localhost} if the server itself is behind an (Apache)
proxy server running on the same host.
    \item[--debug=Topic] 
Enable debugging Topic. See \predref{debug}{3}.
    \item[--syslog=Ident] 
Write debug messages to the syslog daemon using Ident
    \item[--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.,
\textit{before} switching to User:

\begin{shortlist}
    \item open the \verb$socket(s)$
    \item write the pidfile
    \item setup syslog interaction
    \item Read the certificate, key and password file (\verb$--pwfile=File$)
\end{shortlist}

    \item[--group=Group] 
May be used in addition to \verb$--user$. If omitted, the login
group of the target user is used.
    \item[--pidfile=File] 
Write the PID of the daemon process to File.
    \item[--output=File] 
Send output of the process to File. By default, all
Prolog console output is discarded.
    \item[--fork[=Bool]] 
If given as \verb$--no-fork$ or \verb$--fork=false$, the process
runs in the foreground.
    \item[--http[=(Bool\Sbar{}Port\Sbar{}BindTo:Port)]] 
Create a plain HTTP server. If the argument is missing or
\const{true}, create at the specified or default address. Else
use the given port and interface. Thus, \verb$--http$ creates
a server at port 80, \verb$--http=8080$ creates one at port
8080 and \verb$--http=localhost:8080$ creates one at port
8080 that is only accessible from \const{localhost}.
    \item[--https[=(Bool\Sbar{}Port\Sbar{}BindTo:Port)]] 
As \verb$--http$, but creates an HTTPS server.
Use \verb$--certfile$, \verb$--keyfile$, \verb$-pwfile$,
\verb$--password$ and \verb$--cipherlist$ to configure SSL for
this server.
    \item[--certfile=File] 
The server certificate for HTTPS.
    \item[--keyfile=File] 
The server private key for HTTPS.
    \item[--pwfile=File] 
File holding the password for accessing the private key. This
is preferred over using \verb$--password=PW$ as it allows using
file protection to avoid leaking the password. The file is
read \textit{before} the server drops privileges when started with
the \verb$--user$ option.
    \item[--password=PW] 
The password for accessing the private key. See also `--pwfile`.
    \item[--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.
    \item[--interactive[=Bool]] 
If \const{true} (default \const{false}) implies \verb$--no-fork$ and presents
the Prolog toplevel after starting the server.
    \item[--gtrace=[Bool]] 
Use the debugger to trace \predref{http_daemon}{1}.
    \item[--sighup=Action] 
Action to perform on \verb$kill -HUP <pid>$. Default is \const{reload}
(running \predref{make}{0}). Alternative is \const{quit}, stopping the server.
\end{description}

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

\begin{description}
    \item[--workers=Count] 
Set the number of workers for the multi-threaded server.
\end{description}

\predref{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.

\begin{code}
http_daemon :-
    current_prolog_flag(argv, Argv),
    argv_options(Argv, _RestArgv, Options),
    http_daemon(Options).
\end{code}

\begin{tags}
    \tag{See also}
\predref{http_daemon}{1}
\end{tags}

    \predicate{http_daemon}{1}{+Options}
Start the HTTP server as a daemon process. This predicate processes
a Prolog option list. It is normally called from \predref{http_daemon}{0},
which derives the option list from the command line arguments.

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

    \predicate[semidet,multifile]{http_certificate_hook}{3}{+CertFile, +KeyFile, -Password}
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 \arg{Password} to a string, this string
will be used to decrypt the server private key as if the
--password=\arg{Password} option was given.

    \predicate[semidet,multifile]{http_server_hook}{1}{+Options}
Hook that is called to start the HTTP server. This hook must be
compatible to \verb$http_server(Handler, Options)$. The default is
provided by \predref{start_server}{1}.

\qpredicate[multi,multifile]{http}{sni_options}{2}{-HostName, -SSLOptions}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 \predref{sni_hook}{1} is defined
for \predref{ssl_context}{3} to use different contexts depending on the
host name of the client request. This hook is executed
\textit{before} privileges are dropped.
\end{description}

