This is pound.info, produced by makeinfo version 7.2 from pound.texi.

Copyright © 2024-2026 Sergey Poznyakoff

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.3 or any later version published by the Free Software
     Foundation; with no Invariant Sections, no Front-Cover Texts, and
     no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."
INFO-DIR-SECTION Network applications
START-INFO-DIR-ENTRY
* pound: (pound).        Light-weight proxy server.
* poundctl: (pound).     Pound proxy server runtime control.
END-INFO-DIR-ENTRY


File: pound.info,  Node: Top,  Next: Overview,  Up: (dir)

Pound
*****

This edition of the ‘Pound Manual’, last updated 26 May 2026, documents
‘pound’ version 4.23.

   Copyright © 2024-2026 Sergey Poznyakoff

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.3 or any later version published by the Free Software
     Foundation; with no Invariant Sections, no Front-Cover Texts, and
     no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."

* Menu:

* Overview::
* Introduction::
* Usage::
* Simple Proxy::
* HTTPS::
* Balancer::
* Worker model::
* Lua::
* Tunnels::
* Logging::
* Configuration::
* poundctl::
* Emacs::
* Metric Families::
* Time and Date Formats::
* Old Control Format::
* GNU Free Documentation License::
* Example Lua modules::
* Index::

 -- The Detailed Node Listing --

Simple Proxy

* Service selection::
* Request modifications::
* Conditional branches::
* Modifying responses::
* Authentication::
* Rate-limiting::
* Redirects::
* Error responses::

Service Selection

* Regular Expressions::
* File-based Conditions::
* ACL::
* Detached Conditions::

HTTPS

* ACME::
* Redirect HTTP to HTTPS::
* HTTPS backends::

Request balancing

* Sessions::
* Balancer groups::
* Dynamic backends::

Extending ‘pound’ functionality with Lua

* LuaLoad::    Loading Lua sources.
* LuaMatch::   Lua conditionals.
* Constants::  Providing constants for Lua code.
* LuaModify::  Changing requests and responses in Lua.
* Resend::     Resending requests with Lua.
* Stash::      Sharing data between Lua functions.
* LuaBackend:: Lua backends.
* Lua API::

Changing requests and responses in Lua

* Cookie injection::

Configuration

* Lexical structure::
* Syntax::
* String Expansions::
* Global directives::
* Constant::
* File inclusion::
* Logging configuration::
* Management interface::
* Timeouts::
* ListenHTTP::
* ListenHTTPS::
* Service::
* resolver::

String Expansions

* Backreference Expansion::
* Request Accessors::

Global directives

* Runtime directives::
* Worker Settings::
* Proxy Tuning::
* SSL Settings::
* Regexp Settings::
* ACL definition::
* Condition::
* Lua Settings::

Management Interface

* Service Control::

ListenHTTP

* Listener address::
* Listener-specific limits::
* Error definitions::
* Listener logging::
* Request Modification::
* Response Modification::
* Error response rewriting::
* Listener constants::
* Service definitions::

Request Modification

* Rewrite::

Response Modification

* rewrite response::

Service

* Service Selection Statements::
* Service Request and Response Modification::
* Service Logging::
* Backends::
* Session::
* Other Statements::

Backends

* Backend::
* UseBackend::
* Special Backends::

poundctl

* poundctl commands::
* poundctl remote::
* poundctl config::
* poundctl options::
* poundctl template::

Configuring ‘poundctl’

* multiple servers::

‘poundctl’ template

* Template syntax::
* Pipelines::
* Variables::
* Input object::

Template syntax

* Actions::
* Arguments::

Input object

* Core listing::
* Full listing::
* Listener object::
* Service object::
* Backend object::

Example Lua modules

* jwt.lua::
* cookie.lua::
* wwwauth.lua::


File: pound.info,  Node: Overview,  Next: Introduction,  Prev: Top,  Up: Top

1 Overview
**********

‘Pound’ is a reverse proxy, load balancer and HTTPS front-end for Web
servers.  It was developed to provide for even distribution of load
between backend httpd servers and to allow for a convenient SSL wrapper
for those servers that do not offer it natively.

   The core principles of its design are simplicity and safety.  ‘Pound’
is a very small program, easily audited for security problems.  Normally
it runs as a non-privileged user, and can optionally be run in a
chrooted environment.  With several exceptions, it does not access the
hard disk during its runtime.  In short, it should pose no security
threat to the server it runs at.

   The original version of ‘pound’ was written by Robert Segall at Apsis
GmbH(1). In 2018, I added support for newer OpenSSL to the then current
version of the program (2.8).  This version of ‘pound’, hosted on
‘github’ was further modified by Rick O'Sullivan and Frank Schmirler,
who added WebSocket support.

   On April 2020, Apsis started development of ‘pound’ 3.0 - essentially
an attempt to rewrite program from scratch, introducing dependencies on
some third-party software.

   On 2022-09-19, the development and maintenance of ‘pound’ was
officially discontinued and Apsis GmbH was dissolved.  Following that, I
decided to continue development of the program taking my fork as a base.
I considered the branch 3.0, which emerged for a short time before the
original project was abandoned, to be a failed experiment.  To ensure
consistent versioning and avoid confusion, my versioning of ‘pound’
started at number 4.0.

   ---------- Footnotes ----------

   (1) <https://web.archive.org/web/20221202094441/https://apsis.ch/>


File: pound.info,  Node: Introduction,  Next: Usage,  Prev: Overview,  Up: Top

2 Introduction
**************

The job of a proxy server is to receive incoming HTTP or HTTPS requests,
route them to the corresponding web server (“backend”), wait for it to
reply and forward the response back to the querying party.  If more than
one backend is configured to serve requests, the proxy should distribute
requests evenly between them, so that each backend gets a share of
requests proportional to its capacity.

   ‘Pound’ gets information about backends and instructions on HTTP
request routing from its configuration file ‘pound.cfg’.  It is located
in the “system configuration directory”, which is normally ‘/etc’(1).
Syntactically, the configuration file is a sequence of “statements” and
“sections”, separated by arbitrary amount of empty lines and comments.
A “simple statement” occupies a single line and consists of a keyword
(“directive”) and one or more values separated by whitespace.  A
“section” is a compound statement that encloses other statements and
sections.  Sections begin with a keyword, optionally followed by
arguments, and end with a word ‘End’ on a line by itself.  All keywords
are case-insensitive.

   The configuration file defines three kinds of objects: “listeners”,
“services”, and “backends”.  These are defined as configuration
sections.

   A “listener” defines IP address (and optionally port), ‘pound’ will
be listening on for incoming requests.  It can also be regarded as a
frontend definition.  Listener declarations start with ‘ListenHTTP’ (for
plaintext HTTP frontends) or ‘ListenHTTPS’ (for HTTPS frontends)
keywords.

   “Service” sections define rules that decide to which backend to route
requests received by the listeners.  These rules normally involve
analysis of the requested URL or HTTP headers.  A service may also
contain statements that modify requests or responses.

   Services are normally declared inside listeners.  Thus, when a
listener receives a request, it iterates over its services (in the order
of their appearance in the configuration file) to find the one that
matches the request.  If such a service is found, it receives the
request and eventually passes it on to a backend.

   Services may also be declared outside any listeners, in the global
scope.  Such services are shared between all listeners.  They are tried
if none of the services declared within a listener match the incoming
request.

   Service declarations start with the ‘Service’ keyword.

   “Backends” are objects that actually handle requests and produce
responses.  Most often these are “regular backends”, which declare IP
addresses and ports of servers that are to handle the requests.
Backends are defined inside of services, so that the service that
matched the request routes it to its backend.  If more than one backend
is defined within a service, incoming requests will be distributed so
that each backend gets its share of the load.

   Several special backend types are provided, such as emergency
backends, redirects, etc.  Only one special backend can be declared for
a service, and it cannot be used together with other backend types.

   Thus, an average request processing looks as follows.  First, a
request is received by one of the listeners.  The listener then iterates
over its services, until it finds one that matches the request.  If no
such service was found, the listener retries the process with the
services defined in the global scope.  If no matching service is found,
a 503 error (‘Service Unavailable’) is returned.  Otherwise, if the
matching service was found, that service passes the request to one of
its backends.  It may modify the request before that, if it is
instructed so by the configuration.  Once the backend responds, the
service passes the response back to the listener (again, optionally
modifying it, if needed), which finally passes it back to the querying
party.

   ---------- Footnotes ----------

   (1) The exact location depends on compilation options.  When in
doubt, examine the output of ‘pound -V’.


File: pound.info,  Node: Usage,  Next: Simple Proxy,  Prev: Introduction,  Up: Top

3 Usage
*******

When started, ‘pound’ first parses its configuration file.  If any
errors are detected at this stage, it prints the appropriate diagnostics
on the standard error and exits with code 1.  Otherwise, if the
configuration file is OK, ‘pound’ opens sockets declared in the listener
sections, detaches itself from the controlling terminal and starts
serving incoming requests.  From that moment on, all diagnostic messages
are reported via ‘syslog’ (*note Logging::).

   To check whether the configuration file is correct, run ‘pound’ with
the ‘-c’ (for “check”) configuration option:

     pound -c

   Started this way, ‘pound’ will check the configuration file, report
any errors, if found, and exit with status 0 if there are no errors or 1
otherwise.  The option ‘-v’ can be used to increase the verbosity level.
In particular, it instructs ‘pound’ to print a confirmation message on
standard error, if no errors have been encountered (by default it would
exit silently in this case).

   To use alternative configuration file, supply its full pathname with
the ‘-f’ option, e.g.:

     pound -f /etc/pound/test.cfg

   If you are experimenting with new configurations, you might want to
run ‘pound’ in foreground mode and have it print its diagnostics on the
standard error.  This is done by the ‘-e’ option.  So, for testing
purposes, it is quite common to start it this way:

     pound -e

   Another option, ‘-F’, has similar effect, except that it honors
logging settings from the configuration file (*note Logging::), i.e.
when used with this option, ‘pound’ will remain in foreground, but will
report its messages in accordance with its configuration file.

   The following table summarizes all command line options:

‘-c’
     Check configuration file for syntax error and exit.  Exit code
     indicates whether the configuration is OK (0) or not (1).

‘-e’
     Start in foreground mode and log to standard error (or standard
     output, for messages with LOG_DEBUG and LOG_INFO severity levels).
     This option ignores the ‘LogLevel’ configuration setting (*note
     Logging::).

‘-F’
     Foreground mode.  Do not detach from the controlling terminal after
     startup, but remain in the foreground instead.  This overrides the
     ‘Daemon’ configuration setting (*note Daemon::).  The log stream
     (syslog facility or stderr) requested in the configuration file
     remains in effect.

‘-f FILE’
     Read configuration from the supplied FILE, instead of from the
     default location.

‘-h’
     Print short command line usage summary and exit.

‘-p FILE’
     Sets location of the “PID file”.  This is the file where ‘pound’
     will write its PID after startup.  This option overrides the value
     set by the ‘PIDFile’ configuration setting (*note PIDFile::).  Use
     ‘-p -’ to disable creation of PID file.

‘-v’
     Verbose mode.  During startup, error messages will be sent to
     stderr (stdout, for ‘LOG_DEBUG’ and ‘LOG_INFO’ severities).  If
     ‘pound’ is configured to log to syslog, error diagnostics will be
     duplicated there as well.  After startup the configuration settings
     take effect.

     When used with ‘-c’ this option also instructs ‘pound’ to print an
     extra confirmation message on standard error, if there are no
     errors in the configuration file.

‘-V’
     Print program version, licensing terms, and configuration flags and
     exit with status 0.  You can use this option, in particular, to get
     the default values ‘pound’ was built with, such as e.g.
     configuration file location.

‘-W FEATURE’
‘-W no-FEATURE’
     Enable or disable (if prefixed with ‘no-’) additional ‘pound’
     features.  As of version 4.23, the following features are
     implemented:

      -- Feature: dns
          Resolve host names found in configuration file and returned in
          the ‘Location:’ header.  This is the default.

          You can use ‘-W no-dns’ to disable it, in order to suppress
          potentially lengthy network host address lookups.  Make sure
          that your configuration file refers to backends only by their
          IP addresses in this case.

          This setting affects also redirection location rewriting:
          *Note RewriteLocation: Response Modification.

      -- Feature: include-dir=DIR
      -- Feature: no-include-dir
          This controls the “include directory”, i.e.  the directory
          where ‘pound’ looks for relative file names referred to in its
          configuration file.  *Note include directory::, for a detailed
          discussion of this feature.

          Using ‘-W include-dir=DIR’ sets the new value of the include
          directory.

          By default, the system configuration directory is used as
          include directory, so that any relative file names are looked
          up there.  To disable this, use the ‘-W no-include-dir’
          option.  This means that each relative filename used in
          arguments to the directives in the configuration file will be
          looked up in the current working directory.  This is useful
          mainly in testsuite.

      -- Feature: warn-deprecated
          When parsing the configuration file, warn if it uses any
          deprecated statements.  This is the default.  To suppress
          deprecation messages, use ‘-W no-warn-deprecated’.

      -- Feature: close-extra-fds
          At startup, ‘pound’ closes all inherited file descriptors
          numerically greater than 2.  If this is undesirable for some
          reason, use the ‘-Wno-close-extra-fds’ option.


File: pound.info,  Node: Simple Proxy,  Next: HTTPS,  Prev: Usage,  Up: Top

4 Simple Proxy
**************

In this chapter we will deploy several simplest proxying configurations
to illustrate the concepts introduced above.

   Suppose you have an HTTP server running on localhost port 8080, and
want to make it accessible from outside.  This is achieved by the
following configuration file:

     ListenHTTP
         Address 0.0.0.0
         Port 80
         Service
             Backend
                 Address 127.0.0.1
                 Port 8080
             End
         End
     End

   This configuration consists of three nested sections: ‘ListenHTTP’,
‘Service’, and ‘Backend’.  Each section ends with a keyword ‘End’ on a
line by itself.

   The first thing that draws attention are ‘Address’ and ‘Port’
statements appearing in both listener and backend sections.  In
‘ListenHTTP’ they specify the IP address and port to listen on for
incoming requests.  Address ‘0.0.0.0’ stands for all available IP
addresses(1).  In ‘Backend’ section, these keywords specify the address
and port of the remote server, where incoming requests are to be
forwarded.

   The ‘Service’ section has no conditional statements, so it will apply
to all requests.

* Menu:

* Service selection::
* Request modifications::
* Conditional branches::
* Modifying responses::
* Authentication::
* Rate-limiting::
* Redirects::
* Error responses::

   ---------- Footnotes ----------

   (1) Strictly speaking, for all available _IPv4_ addresses.  To bind
to all available IPv4 and IPv6 addresses, use ‘::0’.


File: pound.info,  Node: Service selection,  Next: Request modifications,  Up: Simple Proxy

4.1 Service Selection
=====================

Multiple services can be defined in order to route requests to different
servers, depending on the request content.  In this case, each service
has one or more “conditional statements” (“conditionals”, for short),
that define conditions which a request must match in order to be routed
to backends within that particular service.  Syntactically, such
conditionals have the form:

     KW [OPTIONS] "PATTERN"

where KW is a keyword specifying what part of the request is used in
comparison, PATTERN is a textual pattern which that part is matched
against, and OPTIONS are zero or more flags starting with a dash sign,
which define matching algorithm.

   Perhaps the most often used condition is ‘Host’, which compares the
value of the HTTP ‘Host’ header with the given pattern.  By default it
uses exact case-insensitive match:

     Host "example.com"

   To treat the pattern as a regular expression, use the ‘-re’ option,
as in:

     Host -re ".*\\.example\\.com"

   Whenever we speak about regular expression we usually mean POSIX
extended regular expressions (*note POSIX extended regular expressions:
(sed)Extended regexps.).  However, other regex types can also be used.
This is covered in *note Regular Expressions::.

   Notice the use of double backslashes in the above example.  The
backslash before each dot is needed to match it literally, while another
one protects the first one from being interpreted as an escape character
in string (*note Strings::).

   Other useful options are ‘-beg’ and ‘-end’, which enable exact
matching at the beginning and end of the value, correspondingly.  Thus,
the ‘Host’ statement above can be rewritten as:

     Host -end ".example.com"

   The set of options available for use in conditions is uniform.  *Note
conditional-option::, for a detailed discussion of available options.

   The following configuration snippet illustrates the use of conditions
to select appropriate service (and, correspondingly, backend).  It will
route all requests for ‘www.example.com’ to backend ‘192.0.2.1:8080’,
and requests for ‘admin.example.com’ to ‘192.0.2.4:8080’:

     ListenHTTP
         Address 0.0.0.0
         Port 80

         Service
             Host "www.example.com"
             Backend
                 Address 192.0.2.1
                 Port 8080
             End
         End

         Service
             Host "admin.example.com"
             Backend
                 Address 192.0.2.4
                 Port 8080
             End
         End
     End

   Other conditions use POSIX regexp matching by default.  These are:

‘Header’
     Compare HTTP header against a pattern.  E.g.

          Header "Content-Type:[[:space:]]*text/.*"

‘URL’
     Match URL:

          URL "/login/.*&name=.*"

‘Path’
     Match the path part of the URL:

          Path -beg "/login"

‘Query’
     Match the query part of the URL.

‘QueryParam’
     Match the value of a query parameter.  This statement takes two
     arguments: parameter name and pattern, e.g.:

          QueryParam "type" "(int)|(bool)"

   *Note Service Selection Statements::, for a detailed description of
these and other conditions.

   Multiple conditions can be used together.  Unless expressly specified
otherwise, they are joined by logical ‘and’ operation.  For example:

     Service
         Host "www.example.com"
         URL "^/admin(/.*)?"
         Backend
             Address 192.0.2.4
             Port 8080
         End
     End

   This service will be used for requests directed to host name
‘www.example.com’ whose URL begins with ‘/admin’, optionally followed by
more path components (such as, e.g.
‘http://www.example.com/admin/login’).

   To select a service that matches one of defined rules (i.e.  combine
the rules using logical ‘or’), enclose them in ‘Match OR’ block, as in:

     Match OR
         Host "example.com"
         Host "www.example.com"
     End

   The argument to ‘Match’ can be ‘OR’ or ‘AND’, specifying logical
operation to be used to join the enclosed statements.  The argument can
be omitted, in which case ‘AND’ is implied.  ‘Match’ statements can be
nested to arbitrary depth, which allows for defining criteria of
arbitrary complexity.  For example:

     Service
         Match OR
             Host "admin.example.com"
             Match AND
                 Host "www.example.com"
                 URL "^/admin(/.*)?"
             End
         End
         Backend
             Address 192.0.2.4
             Port 8080
         End
     End

* Menu:

* Regular Expressions::
* File-based Conditions::
* ACL::
* Detached Conditions::


File: pound.info,  Node: Regular Expressions,  Next: File-based Conditions,  Up: Service selection

4.1.1 Regular Expressions
-------------------------

Request matching directives use POSIX extended regular expressions by
default.  If ‘pound’ was compiled with ‘PCRE’ or ‘PCRE2’ library,
“Perl-compatible regular expressions” can be used instead.  This can be
done either globally or individually for a given directive.

   To change regular expression type globally, use the following
directive:

     RegexType pcre

   It affects all conditions that appear after it in the configuration
file, until next ‘RegexType’ directive or end of file, whichever occurs
first.  To change back to POSIX regular expressions, use ‘posix’
argument:

     RegexType posix

   Argument to the ‘RegexType’ directive is case-insensitive.

   Regular expression type can also be selected individually for a
directive, using ‘-posix’ or ‘-pcre’ flags.  For example:

     Host -pcre -icase "(?<!www\\.)example.org"


File: pound.info,  Node: File-based Conditions,  Next: ACL,  Prev: Regular Expressions,  Up: Service selection

4.1.2 File-based Conditions
---------------------------

Most conditional directives take ‘-file’ and ‘-filewatch’ options.  When
specified either option, the argument immediately following it is
treated as the name of a file from which to read the list of regular
expression patterns or other conditional parameters, depending on the
directive.  The file is read at startup and cached in memory, so that
applying the conditional does not result in disk accesses.

   If the ‘-file’ option is used, the file is read at startup and its
contents is remembered for the lifetime of the program.  It is an error
if the file does not exist.  Any errors in the file are treated as
configuration file errors and cause immediate program termination.

   In the contrast, if the ‘-filewatch’ option is used, the file is read
at startup and a file system monitor is set up to catch its
modifications.  Once a change to the file is detected, it will be
reloaded without interrupting the operation of the server.
Consequently, when the ‘-filewatch’ option is used, it is OK if the file
does not exist at startup.  Furthermore, any errors in the file contents
are reported, but don't cause program termination.

   The support for that option depends on the operating system.  On
GNU/Linux systems, ‘pound’ uses ‘inotify’ kernel API (1).  On BSD
systems (FreeBSD, OpenBSD, NetBSD, Darwin), it uses ‘kqueue’(2).  To
check which API your ‘pound’ binary is compiled with, examine the output
of ‘pound -V’.

   Both ‘inotify’ and ‘kqueue’ allow ‘pound’ to react immediately on
file system changes.  On systems that don't support either API, ‘pound’
falls back to periodic checking of file modification time (“mtime”).  In
that case, the reload is initiated if ‘mtime’ changes.  The interval
between two successive checks is defined by the ‘WatcherTTL’ statement
(*note WatcherTTL: Timeouts.) and defaults to 60 seconds.

   Following is a list of conditional statements that implement file
monitoring support: ‘BasicAuth’, ‘Header’, ‘Host’, ‘Path’, ‘Query’,
‘QueryParam’, ‘StringMatch’, ‘URL’.

   *Note request matching directives::, for a detailed discussion of
these.

   ---------- Footnotes ----------

   (1) *Note monitoring file system events: (inotify(7))inotify.

   (2) *note kernel event notification mechanism: (kqueue(2))kqueue.


File: pound.info,  Node: ACL,  Next: Detached Conditions,  Prev: File-based Conditions,  Up: Service selection

4.1.3 ACL
---------

Access control lists, or “ACLs”, are special conditional statements that
evaluate to true for requests originating from one of the predefined IP
addresses.  Access control lists are defined using the ‘ACL’ section
statement, which has three forms: anonymous, file reference, and ACL
reference.  In all three forms, the ‘ACL’ statement accepts optional
argument ‘-forwarded’, which indicates that the remote IP should be
determined from the ‘X-Forwarded-From’ IP address (*note %a::), instead
of using the actual originator IP.

   In “anonymous” form, the ‘ACL’ is a section statement: the keyword is
followed by a newline and a list of CIDRs, terminated with ‘End’ on a
separate line.  Each line in the list defines a single CIDR enclosed in
double quotes.  A “CIDR” consists of a “network address” (IPv4 or IPv6),
optionally followed by slash and “network mask length”, a decimal number
in the range [0,32] for IPv4 and [0,64] for IPv6.  For example:

     ACL
         "127.0.0.1/8"
         "192.0.2.0/25"
     End

   For convenience, ‘Include’ statements (*note File inclusion::) can
also be used between ‘ACL’ and ‘End’.

   In “file reference” form, the ACL syntax is:

     ACL -file "NAME"

or

     ACL -filewatch "NAME"

   Here, NAME is the name of a disk file with the ACL definition.  Its
syntax is similar to the contents of anonymous ACL definition, except
that CIDRs need not be quoted, and ‘Include’ statements are not allowed.
If the file name is relative, it is looked up in the *note include
directory::.

   If the ‘-file’ keyword is used, the file is read at startup and its
contents is remembered for the lifetime of the program.  It is an error
if the file does not exist.  Any errors in the file are treated as
configuration file errors and cause immediate program termination.

   If the ‘-filewatch’ keyword is used, the file is read at startup and
is then being monitored for changes during the runtime.  *Note
File-based Conditions::, for details.

   The third syntax form for ‘ACL’ statements is “ACL reference”.  As
its name implies, the ACL in this form refers to another “named ACL”,
defined elsewhere in the configuration files.  Syntactically, it is

     ACL "NAME"

where NAME is the name of the ACL to refer to.  This syntax makes it
possible to use a single ACL in multiple places of the configuration
file.

   Named access control lists are defined at the top level of a
configuration file.  Syntactically, the definition is similar to
anonymous or file reference forms of ACLs as discussed above, except
that the keyword ‘ACL’ is followed on the same line by the name to be
assigned to that ACL, in double quotes.  Thus the following are valid
named ACL declarations:

     ACL "secure" -file "aclfile"

     ACL "secure" -filewatch "aclfile"

     ACL "secure"
         "127.0.0.1/8"
         "192.0.2.0/25"
     End

   All three examples define a named ACL ‘secure’.  The former two read
its contents from the disk file ‘aclfile’.  The latter one provides its
definition in the form of a section.  This ACL can then be used in any
‘Service’ appearing after its definition by using the following
construct:

     ACL "secure"

   Consider for example the following service declaration:

     Service
         ACL "secure"
         Path -beg "/stat"
         Backend
             ...
         End
     End

   This service will handle requests whose URL starts with ‘/stat’, if
they came from one of the IP addresses mentioned in the access control
list with the name ‘secure’.  Effectively, this means that the access to
that URL is limited to these IP addresses.


File: pound.info,  Node: Detached Conditions,  Prev: ACL,  Up: Service selection

4.1.4 Detached Conditions
-------------------------

If a conditional statement is used in multiple places throughout the
configuration, it could be wise to rewrite it as a “detached condition”.
Detached condition is an abstract conditional statement, not connected
with any service or listener.  It is assigned a unique name that serves
as its identifier.  Syntactically, such conditional is defined using
‘Condition’ section in global scope of the configuration file:

     Condition "NAME"
       ...
     End

Here, the ellipsis represents any number of conditional statements
described above.

   Once defined, detached conditions can be “evaluated” in any number of
‘Service’ or ‘Rewrite’ sections, using the following construct:

     Eval "NAME"

   Evaluating a detached condition means applying its contents to the
incoming request.  In this regard, it can be seen as an equivalent to
including contents of the ‘Condition’ statement in place.  There are two
major differences, though.  First, any parenthesized groups in regular
expressions (*note parenthesized subexpression::) are visible only
within condition itself.  In other words, they cannot be referred to
from outside the ‘Condition’ block.  Secondly, and most importantly, no
matter how often used in the configuration, each detached condition is
evaluated only once.  All subsequent ‘Eval’ statements just return the
result of first evaluation.  This way, the use of detached conditions
can speed up request processing (and reduce the CPU load) for
conditionals that require a lot of calculations, such as long ACLs or
complex Lua functions (*note Lua::).

   Consider the following configuration snippet (irrelevant statements
being omitted):

     Condition "secure"
         ACL -file "secure.acl"
     End

     ListenHTTP
         ...
         Service "a"
             Host -re ".*\\.example\\.com"
             Eval "bigacl"
             Backend
                 Address 192.0.2.129
             End
         End
         Service "b"
             Host "example.com"
             Backend
                 Address 192.0.2.5
             End
         End
         Service "c"
             Host "bar.example.com"
             Eval "bigacl"
             Backend
                 Address 192.0.2.2
             End
         End
     End

   If a request comes for host ‘bar.example.com’ from an IP listed in
file ‘secure.acl’, it will be matched against conditionals in services
‘a’ and ‘b’ before selecting service ‘c’.  When processing ‘a’, the
‘Eval’ statement will scan the ACL, find that it matches the originator
IP and cache that value.  When the same statement is encountered in
service ‘c’, no actual ACL processing will take place, instead ‘pound’
will reuse the result cached earlier.  If ‘secure.acl’ contains a long
list of IP addresses, this can save a lot of time.


File: pound.info,  Node: Request modifications,  Next: Conditional branches,  Prev: Service selection,  Up: Simple Proxy

4.2 Request modifications
=========================

A service can modify requests before forwarding them to backends.
Several statements are provided for that purpose:

SetHeader
     Set a HTTP header.

DeleteHeader
     Delete a HTTP header.

SetURL
     Rewrite the request URL.

SetPath
     Rewrite the path part of the URL.

SetQuery
     Rewrite the query part of the URL.

DeleteQuery
     Delete the query part of the URL.

SetQueryParam
     Set or delete a single query parameter.

   For example, the following service declaration will add the header
‘X-Resent-By: pound’ to each request:

     Service
         SetHeader "X-Resent-By: pound"
         Backend
            ...
         End
     End

   Arguments to request modification statements are expanded before
actual use.  During expansion, references to “parenthesized
subexpressions” in conditionals are replaced with their actual values.
“Parenthesized subexpression” is a part of a regular expression enclosed
in parentheses.  It can be referred to in string arguments as ‘$N’,
where N is its ordinal number.  Numbers start at one, ‘$0’ referring to
the entire string that matched.

   The process of expanding parenthesized subexpressions is called
“backreference expansion”.

   For example, the following condition:

     Header "Content-Type: ([^/]+)/(.+)$"

has two subexpressions: ‘$1’ and ‘$2’.  The following fragment uses
these values to add two query parameters to the URL:

     SetQueryParam "type" "$1"
     SetQueryParam "subtype" "$2"

   As a more practical example, the following service rewrites the path
to JPEG and GIF images:

     Service
         Path "/([^/]+\\.(jpg|gif))$"
         SetPath "/images/$1"
         ...
     End

   When several conditions are used, these forms refer to the last
matched one.  Subexpressions in prior statements can be referred to
using the ‘$I(J)’ construct.  Here, J is either the “tag” of the
expression to refer to (if the statement was tagged, *note tag::), or
the 0-based number of the statement, counted from the last one upwards.
For example, consider the following statements:

     Host -tag "host" -re "(www\\.)?(.+)"
     Header -tag "type" -icase "^Content-Type:[[:space:]]*(([^/]+)/([^;]+)).*"
     Path -tag "dir" "^/static(/.*)?"

   If the incoming request was ‘GET /static/index.html’ with the two
headers

     Host: example.org
     Content-Type: text/html

then, the backreferences and the corresponding strings will be:

     $1 ⇒ /index.html
     $1(dir) ⇒ /index.html
     $1(1) ⇒ text/html
     $2(1) ⇒ text
     $3(1) ⇒ html
     $1(type) ⇒ text/html
     $2(type) ⇒ text
     $3(type) ⇒ html
     $1(2) ⇒ www.
     $2(2) ⇒ example.org
     $1(host) ⇒ www.
     $2(host) ⇒ example.org

   String arguments to ‘Set’ statements can also contain “request
accessors” - special constructs that are expanded to particular values
from the request.  Syntactically, a request accessor is ‘%[NAME]’, where
NAME denotes the request part to access.  For example, ‘%[url]’ expands
to entire URL, ‘%[path]’ to the path part of the URL, etc.

   Using request accessors, the above example of path modification can
be rewritten as:

     Path "\\.(jpg|gif)$"
     SetPath "/images%[path]"

   *Note Request Accessors::, for a detailed discussions of available
accessors.


File: pound.info,  Node: Conditional branches,  Next: Modifying responses,  Prev: Request modifications,  Up: Simple Proxy

4.3 Conditional branches
========================

Conditional request modifications can be organized in logical branches,
each branch being applied only if the request matches certain condition.
The ‘Rewrite’ section encloses a set of conditional statements followed
by one or more request modification statements, which will be applied if
the former match the request.  Optional ‘Else’ sub-section, which in
turn contains conditional and modification statements, will be tried if
those rules don't match.  Any number of ‘Else’ sub-sections is allowed,
each one being tried if the previous ones don't match.

   The example below illustrates this concept.  This configuration
snippet sets different paths depending on the file type and URL used:

     Service
         Rewrite
             Header "Content-Type:[[:space:]]+image/.*"
             SetPath "/images%[path]"
         Else
             Match AND
                 Host "example.org"
                 Path "\\.[^.]+$"
             End
             SetPath "/static%[path]"
         Else
             Path "\\.[^.]+$"
             SetPath "/assets%[path]"
         End
         ...
     End


File: pound.info,  Node: Modifying responses,  Next: Authentication,  Prev: Conditional branches,  Up: Simple Proxy

4.4 Modifying responses
=======================

The ‘rewrite’ statement can also be used to modify responses received
from backends before passing them back to the querying party.  To
indicate this intent, the ‘Rewrite’ statement must be followed by the
‘response’ keyword:

     Rewrite response
         SetHeader "X-Been-There: pound"
     End

   When modifying responses, only two request modification statements
are allowed: ‘SetHeader’ and ‘DeleteHeader’.  The list of conditionals
is limited as well: ‘Header’ and ‘StringMatch’, plus ‘Match’ and ‘Not’
directives.  Notice that these conditionals operate on the response, and
not on the request, as in previous chapters.  For example:

     Rewrite response
         Header "Content-Type:[[:space:]]+text/(.*)"
         SetHeader "X-Text-Type: $1"
     End

   This will insert an additional ‘X-Text-Type’ header into the
response.  It will contain the subtype value from the ‘Content-Type’
header of the original response.


File: pound.info,  Node: Authentication,  Next: Rate-limiting,  Prev: Modifying responses,  Up: Simple Proxy

4.5 Authentication
==================

Along with access control lists, introduced above (*note ACL::),
authentication provides another way to limit access to certain services.
‘Pound’ supports “basic authentication”, as defined in RFC 7617.

   This authentication method relies on the presence of the
‘Authorization’ header in the HTTP request.  If the header is present,
its value specifies the ‘Basic’ authorization method and contains
credentials (username and password) that match one of the users from the
server user database, the request is accepted.  Otherwise a 401
(‘Authentication Required’) or 407 (‘Proxy Authentication Required’)
response is returned with the ‘WWW-Authenticate’ header requesting basic
authentication.

   The ‘BasicAuth’ conditional statement verifies if the ‘Authorization’
header is present and provides correct credentials.  The statement
matches the request if so.

   The ‘BasicAuth’ statement takes a single argument, specifying the
name of a file containing “user database”.  This is a plain-text file
created with ‘htpasswd’ or similar utility, i.e.  each non-empty line of
it must contain username and password hash separated by a colon.
Password hash can be one of:

   • Password in plain text.
   • Hash created by the system ‘crypt’(3) function.
   • Password hashed using SHA1 algorithm and encoded in BASE64.  This
     hash must be prefixed by ‘{SHA}’.
   • ‘Apache’-style ‘APR1’ hash.

   Password file is read at startup, after which its contents is stored
in memory.  ‘Pound’ will re-read it if it notices that the file has
changed, so you need not restart the daemon if you do any changes to the
file.

   Thus, if you put the ‘BasicAuth’ statement in each service that must
be accessible to authorized users only, that would do the first and
principal part of the basic authentication scheme: access control.
There remains second part: returning properly formatted 401 response if
the request did not pass authorization.  That can be done using a
combination of the ‘Error’ internal backend (*note Error responses::)
and response modification techniques described in the previous section.

   However, instead of using ‘BasicAuth’ in each service requiring
limited access and placing a service generating the 401 response in the
end, it is simpler and less error-prone to use the following approach:

   Create a service with the following content:

     Service
         Not BasicAuth "pound/htpasswd"
         Rewrite response
             SetHeader "WWW-Authenticate: Basic realm=\"Restricted access\""
         End
         Error 401
     End

   Replace the file name (‘pound/htpasswd’) and realm name (‘Restricted
access’) with the actual values.

   Make sure that all services that need to be protected by basic
authentication are declared after that service.  This way, any request
that does not convey an ‘Authentication’ header with credentials
matching an entry from your password file will match this service, and
will be replied to with a properly formatted 401 response, which will
prompt the remote user to authenticate themselves.  On the other hand,
authorized requests will not match this service and will eventually be
handled by one of the services declared after it.


File: pound.info,  Node: Rate-limiting,  Next: Redirects,  Prev: Authentication,  Up: Simple Proxy

4.6 Rate-limiting
=================

Rate-limiting is a technique that controls the number of requests
processed by a service in a second.  ‘Pound’ contains mechanism to
implement rate-limiting using “token bucket filter” algorithm.

   The token bucket filter decides whether a request can be accepted
based on the presence of abstract entities called “tokens” in a
container called “bucket”.  Each token represents an ability to process
one incoming request.  The algorithm works as follows:

   • Tokens are added to the bucket at a constant rate of R tokens per
     second.
   • A bucket can host at most M tokens.  Any tokens arriving when the
     bucket is full are discarded.
   • If a request arrives when the bucket holds some tokens, one token
     is removed and the request is accepted.
   • If the bucket is empty, the request is not accepted.

   This algorithm makes sure requests are accepted at a constant rate or
R requests per seconds with bursts of up to M requests.  Such bursts
occur when no requests arrive for M/R or more seconds.

   The special conditional statement ‘TBF’ provides an interface to this
algorithm.  The statement takes three arguments: KEY, a string
identifying the bucket, and the values of R and M.  It evaluates to
“true” if the algorithm accepts the request and to “false” otherwise.
Placing that conditional in a ‘Service’ section ensures that requests
will be processed at the configured rate.  For each such service
section, there is normally another one to be used for requests that
arrive faster than allowed.  The selection criteria for the two sections
differ only by the absence of ‘TBF’ conditional in the second section.
Consider the following example:

     Service "git"
        Host "example.org"
        Path -re "^/git/([^/]+).*"
        TBF "$1" 5 10
        Backend
            Address 192.0.2.10
            Port 80
        End
     End
     Service "block"
        Host "example.org"
        Path -re "^/git/([^/]+).*"
        Error 429
     End

   This configuration limits request rate to any path beginning with
‘/git/’ (presumably, a ‘git’ repository) to 5 requests per second with
bursts of up to 10 requests.  The bucket to use is identified by the
first directory component after the ‘/git/’ prefix, so that rates are
computed for each repository individually.  Requests that conform to
that policy are routed to the backend at ‘192.0.2.10:80’.  This is
configured by the service section ‘git’.

   The requests that arrive quicker than permitted by that service will
be served by service ‘block’, which will respond to them with HTTP
status 429 (‘Too Many Requests’).  *Note Error: Special Backends, for a
discussion of ‘Error’ backend.

   To compute rates for each connection individually, use the ‘remoteip’
accessor (*note Request Accessors::).  In that case the corresponding
fragment from the example above becomes:

        Path -re "^/git/([^/]+).*"
        TBF "%[remoteip 0]-$1" 5 10

   If the rate limit should apply to several services, the recommended
course of action is to declare such “error” service first, using a
common subset of conditions for all services it is intended to cover and
a negation of ‘TBF’.  E.g.:

     Service "rate-limit"
        Host "example.org"
        Path -re "^/git/([^/]+).*"
        Not TBF "$1" 5 10
        Error 429
     End

   This service section shall be followed by the services it protects.


File: pound.info,  Node: Redirects,  Next: Error responses,  Prev: Rate-limiting,  Up: Simple Proxy

4.7 Redirects
=============

Apart from regular backends introduced in previous sections, ‘pound’
provides also several “special” or “internal” backends.  As their name
implies, such backends handle requests and generate responses
internally, without forwarding them to any external entities.

   One of such internal backends is ‘Redirect’.  It generates responses
redirecting the client to another location.  The statement takes two
arguments: a three-digit HTTP status code to return, and the URL to
redirect to:

     Service
         Redirect 301 "https://www.gnu.org"
     End

   Allowed values for the status code are 301, 302, 303, 307 and 308.
This argument is optional: if omitted, 302 is used.

   If the URL argument has no path component (as in the example above),
then the path (and query, if present) components from the original
request will be appended to it.  For example, if the original URL were
‘http://example.com/software’, the service above would redirect it
‘https://www.gnu.org/software’.

   Otherwise, if the path component is present in the URL argument (even
if it is a mere ‘/’), then the URL is used as is.  For example, the
following will drop any path and query components from the URL when
redirecting:

     Redirect 301 "https://www.gnu.org/"

   The URL argument is subject to backreference expansion and request
accessor interpretation (*note Request modifications::).  If any of
these are actually used, the above logic is disabled.

   String expansions make it possible to implement complex redirects.
For example, the following redirect swaps the first two path components
of the original URL:

     Service
         URL "^/([^/]+)/([^/]+)(/.*)?"
         Redirect "http://%[host]/$2/$1$3"
     End

   The following is a standard paradigm for redirecting requests from
HTTP to HTTPS:

     Service
         Redirect 301 "https://%[host]%[url]"
     End


File: pound.info,  Node: Error responses,  Prev: Redirects,  Up: Simple Proxy

4.8 Error responses
===================

Another type of internal backends is ‘Error’, a backend that generates
error responses.  It is useful, for instance, to provide a custom error
status and/or message when no service matches the request.  Normally,
for such cases ‘pound’ generates a standard 503 response (‘Service
Unavailable’) with the built-in error page.  You can customize this
behavior by using as the last service a ‘Service’ section with ‘Error’
backend.  For example:

     Service
         Error 404 "pound/404.html"
     End

   The first argument specifies the HTTP status code to return.  *Note
Error backend::, for more info.

   The second argument is optional.  It supplies the name of a file with
the error page to return along with the response.  The name may be
absolute or relative.  In the latter case, the file will be looked up in
the “include directory”, a special directory for storing pound-specific
files.  *Note include directory::.  The file will be read only once, at
program startup.  If you modify the file and want ‘pound’ to notice
changes, you will have to restart it.

   Unless the file begins with a newline or ‘<’ character, its initial
portion up to first empty line (inclusive) supplies headers that will be
sent with the response.  The following defaults will be used, unless
already defined in the file:

     Content-Type: text/html
     Expires: now
     Pragma: no-cache
     Cache-control: no-cache,no-store

   If the second argument is not supplied, the error text is determined
by the ‘ErrorFile CODE’ statement in the enclosing listener (where CODE
is the HTTP code in question).  If it is not supplied, the built-in
default text is used.  *Note Error definitions::.


File: pound.info,  Node: HTTPS,  Next: Balancer,  Prev: Simple Proxy,  Up: Top

5 HTTPS
*******

In the previous chapter we have described basic proxying techniques
using plain HTTP listener as an example.  Now we will discuss how to use
HTTPS both for listeners and backends.

   To accept HTTPS requests you need to declare ‘ListenHTTPS’ listener.
It is similar to plain ‘ListenHTTP’ described above, except that it
requires a “certificate” to be declared.  For example:

     ListenHTTPS
         Address 0.0.0.0
         Port 443
         Cert "/etc/ssl/priv/example.pem"
         Disable TLSv1
         Ciphers "HIGH:@STRENGTH:!RSA"
     End

   The ‘Cert’ statement supplies the name of the certificate file in PEM
format.  The file must contain the certificate, intermediate
certificates (if necessary), and certificate private key, in that order.

   The ‘Cert’ argument can also specify a directory, in which case
‘pound’ will scan that directory, trying to read the certificate from
each regular file encountered.  It will report an error if unable to
load the file, so this directory should contain only certificate files.
The order in which certificate files are read is not specified.

   Multiple ‘Cert’ statements are allowed.  When trying to find the
matching certificate, ‘pound’ will stop at the first one whose ‘CN’
matches the requested host name.  Thus, the ordering of ‘Cert’
statements is important.  Normally they should be placed in
most-specific to least-specific order, with wildcard certificates
appearing after host-specific ones.

   ‘Cert’ directives must precede all other SSL-specific directives.

   Another important directive is ‘Disable’.  It disables the use of the
specified TLS protocol as well as all protocols older than it.  Usually
it is used to disable obsolete protocols.  For example, the ‘Disable’
statement in the example above disables ‘TLSv1’, ‘SSLv3’, and ‘SSLv2’.

   To further tune the strength of your encryption use the ‘Ciphers’
directive.  It defins the list of ciphers (for TLSv2 and below) or
ciphersuites (for TLSv3) that will be accepted by the SSL connection.
*Note Ciphers::.

* Menu:

* ACME::
* Redirect HTTP to HTTPS::
* HTTPS backends::


File: pound.info,  Node: ACME,  Next: Redirect HTTP to HTTPS,  Up: HTTPS

5.1 ACME
========

Automatic Certificate Management Environment (“ACME”), is a protocol for
automated deployment of HTTPS certificates.  It is perhaps the most
often used method for obtaining SSL certificates nowadays.  In order to
issue certificate for a domain or domains, the protocol verifies that
the web server that is requesting a certificate actually owns these
domains.  This process is based on various “challenge types”.

   ‘Pound’ supports HTTP-01(1) challenge type.  When issuing a
certificate using this challenge type, the ACME client (a program
responsible for periodic certificate re-issuing) obtains from the
authority a challenge file, and stores it in a predefined “challenge
directory”.  The authority will then request this file from the
webserver using a predefined URL. It is supposed that the server will
serve it from the file that has been just written by the agent.  If the
server returns the file, its claim to own the domain is proved and the
certificate is issued.

   Configuring ‘pound’ to reply to challenge requests is as simple as
putting an ‘ACME’ statement to the ‘ListenHTTP’ section of its
configuration file.  The statement takes a single argument - name of the
challenge directory:

     ListenHTTP
         Address 0.0.0.0
         Port 80
         ACME "/var/lib/pound/.well-known/acme-challenge"
     End

   Needless to say, your ACME agent and ‘pound’ must agree on this
directory location.  Configuration of various ACME agents is beyond the
scope of this document.  Please refer to the documentation of your agent
for further details.

   ---------- Footnotes ----------

   (1) <https://letsencrypt.org/docs/challenge-types/#http-01-challenge>


File: pound.info,  Node: Redirect HTTP to HTTPS,  Next: HTTPS backends,  Prev: ACME,  Up: HTTPS

5.2 Redirect HTTP to HTTPS
==========================

Nowadays it is common to redirect all plain HTTP requests to HTTPS on
the same URL. The method of doing so was described in *note HTTP to
HTTPS: Redirects.  As an example, this section shows a working HTTPS
configuration with such redirect.

     ListenHTTP
         Address 0.0.0.0
         Port 80
         Service
             Redirect 301 "https://%[host]%[url]"
         End
     End

     ListenHTTPS
         Address 0.0.0.0
         Port 443
         Cert "/etc/ssl/priv/example.pem"
         Disable TLSv1
         Service
             Backend
                 Address 127.0.0.1
                 Port 8080
             End
         End
     End


File: pound.info,  Node: HTTPS backends,  Prev: Redirect HTTP to HTTPS,  Up: HTTPS

5.3 HTTPS backends
==================

Backends can use HTTPS as well.  To inform ‘pound’ that communication
with the backend goes over an encrypted channel, use the ‘HTTPS’
keyword.  The typical usage is:

     Backend
         Address 192.0.2.1
         Port 443
         HTTPS
     End

   Notice, that unlike other statements, ‘HTTPS’ is used without
arguments.

   Additional directives are available for fine-tuning the connection.
If used, they must appear after the ‘HTTPS’ directive,

   The ‘Cert’ directive specify the client certificate to use when
connecting.  Use it if the backend requires client authentication.

   The ‘Disable’ and ‘Ciphers’ directives are similar to those described
when discussing ‘ListenHTTPS’: the former disables the given TLS
protocol and all protocols prior to it, and the latter configures the
list of OpenSSL ciphers which the client wishes to use.  The actual
cipher to use will be selected from this list during negotiation with
the backend.

   The example below illustrates the use of these directives:

     Backend
         Address 192.0.2.1
         Port 443
         HTTPS
         Disable TLSv1_1
         Cert "/etc/pound/crt/b1.pem"
         Ciphers "HIGH:!RSA"
     End


File: pound.info,  Node: Balancer,  Next: Worker model,  Prev: HTTPS,  Up: Top

6 Request balancing
*******************

When several backends are defined in a service, incoming requests will
be distributed among them.  This process is called “balancing”.  By
default, requests are distributed equally.  This can be changed by
assigning them a “priority” - a positive integer which assigns a
relative weight of the given backend in the distribution algorithm.  The
greater the priority is, the more requests this backend gets from the
total flow.

   The distribution algorithm is defined by “balancing strategy”.  As of
version 4.23, ‘pound’ supports two strategies: “weighted random
balancing” and “interleaved weighted round robin balancing”.

“Weighted Random Balancing”

     This is the default strategy.  The backend to use for each request
     is determined at random, taking into account backend priorities, so
     that backends with numerically greater priorities have
     proportionally greater chances of being selected than the ones with
     lesser priorities.

“Interleaved Weighted Round Robin Balancing”

     This strategy cycles over all active backends, considering each one
     in its turn.  An integer ordinal number is assigned to each round,
     which is incremented (modulo number of backends) each time a new
     round is started.  A backend is assigned a request only if its
     priority is greater than the round number.

     This strategy offers several advantages compared with the previous
     one.  First, it results in a more even distribution of the
     requests.  Secondly, the resulting distribution is predictable.

   Overall, the share of requests a given backend receives can be
estimated as:

     P_{i} / S(P)

where P_{i} is the priority of the backend with index i, and S(P) is the
sum of all priorities.

   Weighted random balancing is used by default.  Each backend gets the
default priority 5, unless another value is expressly assigned using the
‘Priority’ statement, e.g.:

     Service
         Backend
             Address 192.168.0.1
             Port 80
             Priority 1
         End
         Backend
             Address 192.168.0.2
             Port 80
             Priority 9
         End
     End

   In this example, backend ‘192.168.0.2’ will receive roughly 9 times
more requests than backend ‘192.168.0.1’.

   The balancing strategy to use is defined by the ‘Balancer’ keyword,
which can appear either in the global scope or within a ‘Service’
section.  Its argument can be one of:

‘random’
     Use weighted random balancing (default).

‘iwrr’
     Use interleaved weighted round robin balancing.

   The ‘Balancer’ statement appearing in the global scope defines
balancing strategy for all services that don't have ‘Balancer’ statement
on their own.

* Menu:

* Sessions::
* Balancer groups::
* Dynamic backends::


File: pound.info,  Node: Sessions,  Next: Balancer groups,  Up: Balancer

6.1 Sessions
============

Some web applications attempt to introduce state persistence into the
stateless HTTP protocol, by defining “sessions” using various
mechanisms, such as specially defined headers, cookies, etc.  For such
applications it is critical that all requests that belong to a single
“session” be directed to the same server, i.e.  backend.  Clearly, this
disrupts the balancer logic, and requires that the proxy be able to
understand the backend's notion of session.

   ‘Pound’ is able to detect and track sessions identified by client
address, Basic authentication (user id/password), URL parameter, cookie,
HTTP parameter, and HTTP header value.

   Session tracking is enabled on a per-service basis by a ‘Session’
section.  The section must contain at least the ‘Type’ directive, which
specifies what type of session tracking to use, and the ‘TTL’ directive,
supplying session idle timeout in seconds.

   Session types are case-insensitive.  They are summarized in the table
below:

‘IP’
     The ‘IP’ session tracking type instructs ‘pound’ to forward all
     requests from the same client IP address to the same backend
     server:

          Session
              Type IP
              TTL  300
          End

‘Basic’
     Using this session tracking type, ‘pound’ parses the
     ‘Authentication’ header of each request.  If the header is present,
     and specifies the ‘Basic’ authentication type, user ID is extracted
     from it.  Requests with the same user ID are forwarded to the same
     backend server.

          Session
              Type Basic
              TTL  300
          End

‘URL’
     This tracking scheme uses the value of URL query parameter to
     define a session.  The parameter name is supplied using the ‘ID’
     directive:

          Session
              Type URL
              TTL  300
              ID   "sess"
          End

     In this example, sessions are identified by the ‘sess’ parameter,
     The request URL might look like ‘http://example.org?sess=123’.

‘Cookie’
     The ‘Cookie’ tracking type use a certain cookie to identify
     sessions.  The cookie name is given by the ‘ID’ directive:

          Session
              Type Cookie
              TTL  300
              ID   "sess"
          End

‘Header’
     Sessions are identified by the value of HTTP header whose name is
     given by the ‘ID’ directive, e.g.:

          Session
              Type Header
              ID   "X-Session"
              TTL  300
          End

‘Parm’
     This is the least useful scheme.  Sessions are identified by HTTP
     parameter - a string that appears after a semicolon in the URL,
     such as ‘bar’ in ‘http://foo.com;bar’

          Session
              Type PARM
              TTL  300
          End


File: pound.info,  Node: Balancer groups,  Next: Dynamic backends,  Prev: Sessions,  Up: Balancer

6.2 Balancer groups
===================

Backends within each service are grouped in “balancer groups”.  Each
such group is assigned a unique integer “priority”, which defines the
order in which groups are tried.  When selecting a backend, a group with
the numerically smallest priority is tried first and a suitable backend
is looked up among backends defined in that group, using one of the
balancing strategies discussed above.  If no backend can be selected
(e.g.  all backends are unavailable), next group is tried.  The process
continues until either a backend is chosen or the list of balancer
groups is exhausted.

   By default, backends declared using the ‘Backend’ keyword are
assigned to the balancer group 0.  These are backends used during normal
operation.  Backends declared using the ‘Emergency’ keyword (*note
Emergency::) are assigned to the balancer group 65535.  These backends
form a pool of “high availability” backends, which will be used if all
normal backends fail.

   More backend groups can be added using dynamic backends, discussed in
the next section.


File: pound.info,  Node: Dynamic backends,  Prev: Balancer groups,  Up: Balancer

6.3 Dynamic backends
====================

Normally, when a backend is declared in configuration file, the value
supplied with its ‘Address’ statement is resolved at once and the
resulting IP is associated with the backend.  Such backends are
“static”.  You can also instruct ‘pound’ to resolve the hostname and
create as many backends as are the IP addresses it resolves to.  Such
backends are called “dynamic”.(1)  When a dynamic backend is requested,
the ‘Backend’ statement defines a “matrix” which will be used as a
template to generate actual backends from the data in DNS. The TTL value
of the DNS record (or records) defines minimum time to live of the
generated backends.  When it expires, DNS will be queried again and
backends recreated according to the changes in its responses(2).

   In the simplest case, a dynamic backend can be created using ‘A’ or
‘AAAA’ DNS records.  If several records correspond to the hostname
defined in the ‘Address’ statement, ‘pound’ can either create a single
backend for each of them, or select one of them in round-robin fashion
and use it to create a backend.  Rest of backend parameters (port value,
priority, etc.)  will be taken from its matrix declaration.

   A more advanced way to create dynamic backends is using ‘SRV’
records.  Each ‘SRV’ record has four associated parameters: priority,
weight, target and port.  The “priority” value defines the ‘pound’
balancer group where to put generated backends.  “Weight” is assigned as
the priority for each generated backend(3).  Finally, “target” is used
as hostname to obtain IP addresses for the backends.  For example,
suppose the following DNS records are defined:

     $ORIGIN _tcp.example.org.
     ; _srv  TTL     SRV     prio    weight  port target.
     _proxy  60      SRV     10      40      8081 be0.example.org.
     _proxy  60      SRV     10      70      8082 be1.example.org.
     _proxy  60      SRV     20      10      8081 ha1.example.org.
     _proxy  60      SRV     20      10      8081 ha2.example.org.

   Assuming each of the target hostnames resolves to one IP address,
these records will produce two balancer groups of two backends each, and
will be roughly equivalent to the following statements:

     Backend
             Address "be0.example.org"
             Port 8081
             Priority 40
     End
     Backend
             Address "be1.example.org"
             Port 8082
             Priority 70
     End

     Emergency
             Address "ha1.example.org"
             Port 8081
             Priority 10
     End
     Emergency
             Address "ha2.example.org"
             Port 8081
             Priority 10
     End

   _Notice_, that an SRV record can have a weight of 0.  This will
translate to ‘pound’ backend priority 0, which is normally not allowed
(*note Balancer::).  According to RFC 2782, this is the preferred way of
defining weights where "there isn't any server selection to do", whereas
"[i]n the presence of records containing weights greater than 0, records
with weight 0 should have a very small chance of being selected".
‘Pound’ handles this as follows: if all ‘SRV’ records have zero weight,
priority of the resulting backends is set to 1.  This makes sure the
backend selection algorithm works and gives each backend equal chance of
being selected.  This translation does not take place, however, if at
least one of ‘SRV’ records has a weight greater than 0.  Another way to
handle such records is using the ‘IgnoreSRVWeight’ configuration
statement, which is discussed below.

   To declare backend as dynamic, use a symbolic host name in its
‘Address’ statement and add the ‘Resolve’ statement with one of the
following values:

 -- Dynamic Resolve: first
     Resolve the symbolic host name and use first IP from the DNS
     response as the address of the created dynamic backend.  Thus, this
     type will produce at most one dynamic backend.

 -- Dynamic Resolve: all
     Resolve the symbolic host name and create one backend for each
     address from the DNS response.  This enables load balancing between
     created backends.  Each backend will be assigned the same priority.

 -- Dynamic Resolve: srv
     Obtain ‘SRV’ records for the host name and use them to generate
     dynamic backends.  Each record produces new dynamic backend of
     ‘Resolve all’ type, which creates regular backends as described
     above.  The weight field of the ‘SRV’ record is mapped to the
     priority field of each generated backend.  The priority field
     determines the balancer group where the backend will be hosted.

   When resolving hostnames, both IPv4 and IPv6 addresses are looked
for.  You can select the specific address family using the ‘Family’
statement.  Its allowed values are:

‘any’
     Use all address families available.  This is the default.

‘inet’
     Use only IPv4 addresses (‘A’ DNS records).

‘inet6’
     Use only IPv6 addresses (‘AAAA’ DNS records).

   For example:

     Backend
             Address "_proxy._tcp.example.org"
             Resolve srv
             Family any
     End

   Notice, that you need not supply ‘Port’ statement for dynamic
backends of ‘srv’ resolve type.  Normally, you don't need to supply
‘Priority’, either.  However, you may do so, if you wish to override the
weight settings from ‘SRV’ records.  In that case, inform ‘pound’ about
your decision using the following statement in ‘Backend’ section:

     IgnoreSRVWeight true

   There are several possible scenarios when this may be needed.  One of
them is when all ‘SRV’ records have weight of 0 (see above) and your
configuration defines one or more regular backends in the same balancer
group as backends generated by those records.  In that case, the default
priority assigned by ‘pound’ to those generated backends (1) may prove
to be too low for adequate balancing.  Using ‘IgnoreSRVWeight’ allows
you to fix that.  For example:

     Service
             Backend
                     Address 192.0.2.15
                     Port 80
                     Priority 8
             End
             Backend
                     Address "_proxy._tcp.example.org"
                     Resolve srv
                     Family any
                     IgnoreSRVWeight true
                     Priority 5
             End
     End

   In this example, backends generated by ‘SRV’ records for domain
‘_proxy._tcp.example.org’ will be assigned priority 5, no matter what
the actual value of ‘SRV’ weight field.

   Dynamic backends will be updated periodically, when the TTL of the
corresponding DNS records expires.  If the hostname cannot be resolved
or a DNS failure occurs, next update will be scheduled in 600 seconds
after the failure.  This interval can be configured using the
‘RetryInterval’ statement in the ‘Backend’ section, or globally, in the
‘Resolver’ section (*note resolver::).

   ---------- Footnotes ----------

   (1) Support for dynamic backends is enabled at compile time and
requires the GNU adns library (http://www.gnu.org/software/adns).  If
unsure whether your ‘pound’ binary includes it, inspect the ‘pound -V’
output.

   (2) If necessary, the TTL value can be changed using the
‘OverrideTTL’ configuration directive.  *Note OverrideTTL: Backend.

   (3) Notice, that the ‘SRV’ terminology differs from what ‘pound’
uses.  What is called priority in ‘SRV’ defines the “weight” of the
backend group for ‘pound’, whereas what is called weight in ‘SRV’
defines the “priority” of a backend within a group.  This confusion is
due to historical reasons, and it would be hard to avoid it without
breaking backward compatibility.


File: pound.info,  Node: Worker model,  Next: Lua,  Prev: Balancer,  Up: Top

7 Worker model
**************

Each incoming connection is assigned to a specific “worker” - a thread
in the running program which becomes responsible for processing requests
that arrive through this connection.  The total number of running
workers is controlled by three configuration parameters:
‘WorkerMinCount’, ‘WorkerMaxCount’, and ‘WorkerIdleTimeout’.

   The value of ‘WorkerMinCount’ defines the minimum number of workers
that should always be running (5, by default).  Another parameter,
‘WorkerMaxCount’ sets the upper limit on the number of running workers
(it defaults to 128).

   At each given moment, a worker can be in one of two states: “idle” or
“active” (processing a connection).  If an incoming connection arrives
when all running workers are active, and total number of workers is less
than ‘WorkerMaxCount’, a new worker thread is started and the new
connection is assigned to it.  If the number of active workers has
already reached maximum, the connection enters the “connection queue”,
where it will wait for a worker to become available to process it.

   The third parameter, ‘WorkerIdleTimeout’, specifies maximum time a
thread is allowed to spend in the idle state.  If a worker remains idle
longer than that and total number of workers is greater than the
allotted minimum (‘WorkerMinCount’), this idle worker is terminated.

   Maximum capacity of the connection queue is computed as a function of
the system limit on the number of open files and the value of
‘WorkerMaxCount’.  You can define it explicitly using the
‘ConnectionQueueSize’ configuration statememt (*note
ConnectionQueueSize: Worker Settings.).

   If all workers are busy and the connection queue is filled up, the
program will stop accepting new connections until at least one worker
becomes available again.


File: pound.info,  Node: Lua,  Next: Tunnels,  Prev: Worker model,  Up: Top

8 Extending ‘pound’ functionality with Lua
******************************************

Lua (http://lua.org) is a lightweight extension language developed at
the Pontifical Catholic University of Rio de Janeiro.  Functions and
modules written in Lua can be used to implement new features in ‘pound’
without the need to modify its sources and recompile it.(1)

   Lua source files can be loaded using two distinct modes: “per-thread”
and “global”.  In per-thread mode, each Lua file is loaded into each
worker thread separately.  This is the default.  In global mode sources
are loaded only once and exist in one copy, available for use in all
threads.  No matter what mode is used, Lua sources are read and
interpreted only once, at program startup.

   The main advantage of per-thread mode is speed.  Each thread runs its
own copy of Lua interpreter and doesn't have to synchronize its actions
with other threads.  Its disadvantage is a bit higher memory usage.

   Sources loaded in global mode reside in one interpreter, common for
all threads.  Consequently, before calling a Lua function, the thread
must lock the interpreter for its use, and unlock it afterwards.  While
the interpreter is in use by a single thread, remaining threads must
wait for it to be released in order to use it.  This results in certain
performance penalty.

   Both modes can be used together.  No matter which mode is used, Lua
functions sharing the same mode can use a special global variable to
exchange data between them, if they are called in different stages of
request processing.  This way, for example, a Lua test can pass its
results to the Lua backend.

* Menu:

* LuaLoad::    Loading Lua sources.
* LuaMatch::   Lua conditionals.
* Constants::  Providing constants for Lua code.
* LuaModify::  Changing requests and responses in Lua.
* Resend::     Resending requests with Lua.
* Stash::      Sharing data between Lua invocations.
* LuaBackend:: Lua backends.
* Lua API::

   ---------- Footnotes ----------

   (1) To check if the binary supports Lua, run ‘pound -V’ and examine
its output.


File: pound.info,  Node: LuaLoad,  Next: LuaMatch,  Up: Lua

8.1 Global Lua Configuration
============================

Lua sources are loaded from the global ‘Lua’ section, using two
statements: ‘Load’ and ‘LoadGlobal’.  These take as argument the name of
a Lua source file to parse and load.  As usual, relative pathnames are
looked up in the *note include directory::.

   The ‘Load’ statement loads the file to per-thread Lua interpreters,
while ‘LoadGlobal’ loads it to the global one.  Example usage:

     Lua
         Load "auth-bearer.lua"
     End

   If the file ends with a ‘return’ statement, it is loaded as in Lua
‘require’.  The return value is then available in Lua global variable
whose name is obtained from the filename using the following procedure:

  1. Remove the ‘.lua’ suffix.

  2. Unless first character is a letter of latin alphabet or underscore,
     add underscore at the beginning.

  3. In the resulting string, replace each character other than letter,
     digit or underscore with an underscore.

   Thus, if the file ‘auth-bearer.lua’ ends with a ‘return’, the
returned value will be available in Lua as ‘auth_bearer’.

   You can also supply variable name explicitly, as second argument,
e.g.:

     Lua
         Load "auth-bearer.lua" "bearer"
     End

   Of course, you can use as many ‘Load’ (or ‘LoadGlobal’) statements as
there are files you wish to load.

   This section can also be used to modify Lua search paths.  Two
statements are provided for this purpose: ‘Path’ modifies search path
for Lua source files (‘package.path’), and ‘CPath’ modifies search path
for dynamic libraries (‘package.cpath’).  Both statements add their
argument at the beginning of the corresponding ‘package’ path.  For
example:

     Lua
         Path "/usr/share/pound/?.lua"
         Load "auth-bearer.lua" "bearer"
     End

   Notice that ‘Path’ statement has no effect on where ‘Load’ looks for
its argument (it always uses ‘pound’ include path to locate relative
file names).  Instead, it affects ‘require’ statements in loaded Lua
sources.


File: pound.info,  Node: LuaMatch,  Next: Constants,  Prev: LuaLoad,  Up: Lua

8.2 Lua conditionals
====================

Lua functions are most commonly used to implement new conditions, that
can be used to select the ‘Service’ section to use.  Such conditions are
applied using ‘LuaMatch’ statements in ‘Service’ sections.  The
‘LuaMatch’ statement takes at least one argument: the name of Lua
function to call.  It can be followed by any number of string values,
which will be passed to the function as its arguments.  Before being
passed to the function, these values undergo backreference expansion and
request accessor interpretation (*note Request modifications::).

   The first argument can be either an unqualified name, as ‘mycond’, or
a fully qualified one, as ‘modname.mycond’.  Use the latter form to call
functions defined in modules.

   Information about HTTP request is provided to Lua functions via the
built-in variable ‘http.req’, described in *note Lua API::.

   To illustrate the concept, here's the definition of a Lua test that
returns ‘true’ if the value of a header named in its first argument
matches any of its remaining arguments, treated as anchored Lua
patterns:

     function isheader(name, ...)
        local args = { ... }
        for _, pat in ipairs(args) do
           if string.find(http.req.headers[name], "^"..pat.."$") then
              return true
           end
        end
        return false
     end

   Supposing that this function is defined in file ‘isheader.lua’, it
can be used as follows:

     Lua
         Load "isheader.lua"
     End
     ListenHTTP
         ...
         Service
             LuaMatch "host" "foo[.]bar" "www[.]fo+[.]bar"
             Backend
                 ...
             End
         End
     End

   As a more practical example, the function below implements “Bearer”
authorization scheme.

     local bearer = {}
     local jwt = require 'jwt'

     function bearer.ok(secret)
        -- Read in the Authorization header.
        local bh = http.req.headers['Authorization']
        if bh == nil then
           return false
        end

        -- Check if it starts with "Bearer".
        local n, k = bh:find('%s+')
        if n == nil or bh:sub(1,n-1):lower() ~= 'bearer' then
           return false
        end

        -- Extract the token and parse it.
        local j, err = jwt.parse(bh:sub(k+1))
        if err ~= nil then
           return false
        end

        -- Verify the token.
        if not j:verify(secret) then
           return false
        end

        -- Check expiration time.
        if j.payload.exp ~= nil then
           local exp = tonumber(j.payload.exp)
           if exp == nil then
              return false
           elseif os.time() < j.payload.exp then
              return false
           end
        end

        return true
     end

     return bearer

*Note jwt.lua::, for the implementation of the ‘jwt’ module.

   The following configuration fragment uses ‘bearer.ok’ function as a
condition, to reject requests without a valid bearer token:

     Service
         Not LuaMatch "bearer.ok" "secret"
         Rewrite response
             SetHeader "WWW-Authenticate: Bearer realm=\"Restricted access\""
         End
         Error 401
     End


File: pound.info,  Node: Constants,  Next: LuaModify,  Prev: LuaMatch,  Up: Lua

8.3 Providing constants for Lua code
====================================

In the previous section we have used the ‘bearer.ok’ function to verify
the signature of a JWT token.  The function was invoked from a ‘LuaMath’
conditional and the shared secret used to verify signatures was given to
it as an argument:

       Not LuaMatch "bearer.ok" "SECRET"

   Keeping security-sensitive data, such as SECRET, in the configuration
file requires tightening the file permissions.  Depending on the
configuration, it can have other security implications as well.  All in
all, it is better to separate security-sensitive data and configuration.

   ‘Pound’ provides a way of doing so: the ‘Constant’ statement:

     Constant NAME -file FILE

   The content of the file FILE is read and assigned to the constant
NAME.  The constant can then be used in string expansions, using the
‘const’ accessor, or can be retrieved directly from the Lua code, using
the ‘http.const(name)’ function.

   Returning to our example from the previous section, to separate the
shared key value from the configuration text, we first store the value
of key in the file ‘secret.txt’.  For simplicity, let's suppose the file
is kept in the ‘pound’ include directory (*note include directory::).

   Then, let's define the constant ‘key’ and assign it the value of the
shared secret from this file.

   Finally, we pass its value to ‘bearer.ok’ using the ‘const’ accessor:

     Service
         Constant "key" -file "secret.txt"
         Not LuaMatch "bearer.ok" "%[const key]"
         Rewrite response
             SetHeader "WWW-Authenticate: Bearer realm=\"Restricted access\""
         End
         Error 401
     End

   Yet another way of achieving the same effect would be to modify the
‘bearer.ok’ function to take the constant name as its second argument
and retrieving its value using the ‘http:const’ method (*note const:
lua-http.).  This is left as an exercise for the reader.

   The ‘Constant’ statement normally reads the file verbatim and treats
its content as opaque binary data.  It is common, however, to keep
textual data there and to maintain it using a text editor.  In this case
you will need to remove the trailing newline character that most editors
will add to the end of file.  To do so, use the ‘-trim’ option, like
that:

         Constant "key" -file "secret.txt" -trim

   As with other configuration statements, in lieu of ‘-file’, you can
use ‘-filewatch’, the difference between the two being that the latter
will automatically update the value of the constant whenever the file
contents changes.  *Note File-based Conditions::, for a detailed
discussion of that.

   Finally, notice that ‘Constant’ can appear in several configuration
scopes, namely: at the top level, inside a ‘ListenHTTP’ (or
‘ListenHTTPS’), or inside a ‘Service’ section.  Defining the same
constant name inside a deeper scope silently overrides any definitions
in upper scopes.  For example, if you have

     Constant "key" -file "one.txt"
     ListenHTTP
         Constant "key" -file "another.txt"
         Service
             Constant "key" -file "yetanother.txt"
             LuaMatch "func" "%[const key]"
         ...

then the function ‘func’ in the last line will be called with the
contents of file ‘yetanother.txt’ as its argument.


File: pound.info,  Node: LuaModify,  Next: Resend,  Prev: Constants,  Up: Lua

8.4 Changing requests and responses in Lua
==========================================

The ‘LuaModify’ configuration statement instructs ‘pound’ to invoke a
Lua function, ignoring its return value.  In other words, the function
is called for its side effects, whatever they are.

   Syntactically, the statement is similar to ‘LuaMatch’, discussed in
the previous section: the function name is supplied as its first
parameter and the arguments, if any, as its remaining parameters.  Only
string arguments are allowed.

   ‘LuaModify’ can appear anyplace where other request modification
statements are allowed: i.e.  in ‘ListenHTTP’ (or ‘ListenHTTPS’),
‘Service’, ‘Match’ and ‘Rewrite’ sections.

   Most often this statement is used to modify the incoming request
before sending it out to the backend, or the response before returning
it back to the client.  To do so, the function invoked by ‘LuaMatch’ can
use the ‘http’ Lua module, discussed in *note lua-http::, in particular
its fields ‘http.req’ and ‘http.resp’.

* Menu:

* Cookie injection::


File: pound.info,  Node: Cookie injection,  Up: LuaModify

8.4.1 Cookie Injection
----------------------

Cookie injection is a special technique which ensures that requests from
a client are always forwarded to the same backend, even if the backend
server in question does not provide any mechanism for session tracking.
It works as follows.  Upon first connection, ‘pound’ adds to the backend
response a ‘Set-Cookie’ header with a unique cookie generated for this
purpose.  This ensures that further requests from that client will bear
this cookie.  Then, it will suffice to configure ‘pound’ to use that
cookie for session tracking (*note Sessions::), and all subsequent
requests from that client will go to the same backend.

   In this subsection we will show how to implement cookie injection in
Lua using ‘LuaModify’.

   Let's start from the Lua code.  We need a function that, being
invoked with the name of cookie as its argument, will check if that
cookie is present in the request and if not, will create it by adding a
‘Set-Cookie’ header to the response from backend:

     function inject(name, ttl)

   Here, NAME supplies the name of the cookie to check for, and TTL
provides its time-to-live in seconds, which is used if the cookie needs
to be set.

   Functions for operating on cookies are supplied by the ‘cookie.lua’
module, described in *note cookie.lua::.  To generate unique session
identifiers, we will use the lua-uuid
(https://luarocks.org/modules/luau-project/lua-uuid) module.

   The resulting Lua module can then be written as follows:

     local _M = {}

     local uuid = require('lua-uuid')
     local cookie = require('cookie')

     -- Unless cookie NAME is already set, create and initialize it
     -- to a unique session identifier.  TTL supplies Max-Age.
     function _M.inject(name, ttl)
        local cookie = cookie.get(name)
        if cookie == nil then
           cookie.set(name, tostring(uuid.new()), ttl)
        end
     end

     return _M

   Suppose this program is saved in file ‘mksess.lua’, located in
‘pound’ include path.  First, this program needs to be loaded to
‘pound’.  This is done in the global ‘Lua’ section:

     Lua
         Load "mksess.lua"
     End

   Then, the ‘Service’ section which should implement cookie injection,
must be configured to track sessions by the value of a cookie, and the
‘inject’ function must be called on each backend response.  Suppose the
cookie used for session tracking is named ‘poundsession’.  Then:

     Service
         Session
             Type Cookie
             TTL  300
             ID   "poundsession"
         End
         Rewrite response
             LuaModify "mksess.inject" "poundsession" "300"
         End
         ...
     End

Notice, that TTL argument to ‘mksess.inject’ matches that in the
‘Session’ section.


File: pound.info,  Node: Resend,  Next: Stash,  Prev: LuaModify,  Up: Lua

8.5 Resending requests with Lua
===============================

As of version 4.23, ‘pound’ makes it possible to resubmit a request if
the selected backend wasn't able to process it.  There are two major
cases: resending within the same service and sending the request to
another service within the same listener.

   Both cases are handled by a Lua function called via ‘LuaModify’
statement in a ‘Rewrite response’ section.

Resending to the Same Service
-----------------------------

The usual scenario for the first case is as follows.  ‘Pound’ receives a
request, selects the service and backend, and passes the request to that
backend.  The backend responds with a temporary error status, meaning
that the request doesn't satisfy some prerequisites for processing.
Then ‘pound’ calls a Lua function that analyzes the response, modifies
the request so as to satisfy those prerequisites and marks the request
for resending.  The processing occurs within the same service, so
normally the request will be sent to the same backend as previously,
unless the backend has closed the connection after responding, in which
case a new backend will be selected as described in *note Request
balancing: Balancer.

   As an example of such a scenario, suppose that the backend responds
with status 401 (‘Unauthorized’).  In this case, the Lua function could
look up the credentials, add the appropriate ‘WWW-Authenticate’ header
and then mark the request for resending.  To do that, the function
should assign a ‘true’ value to the variable ‘http.resend’.

   Below is an example implementation (module ‘auth.lua’).  It uses
three modules: ‘base64’, ‘wwwauth’, and ‘creds’.  The first is available
from <https://luarocks.org/modules/iskolbin/base64>.

   The ‘wwwauth’ module, described in detail in *note wwwauth.lua::,
provides a function for parsing the value of ‘WWW-Authenticate’ HTTP
header.

   Finally, the ‘creds’ module should provide the following function:

 -- Method on creds: find (HOST, REALM)
     Look up credentials for the given HOST and REALM.  On success,
     return a pair: USERNAME, PASSWORD.  If not found, return nil.

   Writing this module is left as an exercise for the reader.

   Given these, the ‘auth.lua’ module can be written as follows:

     local M = {}

     local b64 = require 'base64'
     local wwwauth = require 'wwwauth'
     local creds = require 'creds'

     function M.inject()
        if http.resp.code == 401 then
           # Authorization is required. First, check if we have already
           # processed this request.
           if http.resendcount > 0 then
              return
           end
           # Parse the header:
           scheme, params = wwwauth.parse(http.resp.headers['WWW-Authenticate'])
           if scheme == 'Basic' then
              # Only Basic scheme is supported.  Look up for credentials:
              user, pass = creds.find(http.req.headers.host, params.realm)
              if user ~= nil then
                 # Credentials found. Pack them into the Authorization
                 # header.
                 http.req.headers['Authorization'] = scheme .. " " ..
                    b64.encode(user .. ':' .. pass)
                 # Instruct pound to resend the request:
                 http.resend = true
              end
           else
              pound.log(pound.INFO, "Unsupported authorization scheme: "..scheme)
           end
        end
     end

     return M

   Notice the condition in line 11.  The ‘http.resendcount’ variable
contains the number of resends the request has already underwent.  Using
it allows us to avoid retrying the already failed authentication
attempt.  However, even in absence of such check, ‘pound’ will not allow
to do more than 4 resends of the same request.  This is a safety measure
to avoid dead loops.

   To use this module, add the following fragment to the ‘Service’
section:

     Rewrite response
         LuaModify "auth.inject"
     End

   This will work for requests that don't have a body, such as ‘GET’,
‘HEAD’, and the like.  For requests that do, such as ‘POST’ or ‘PUT’,
you will have to configure “request content capturing” as well.  You do
so using the ‘ContentCapture’ statement.  The statement takes a single
numeric argument specifying maximum size of the request content.  E.g.:

     ContentCapture 65536

Selecting backend balancer weight
---------------------------------

As noted above, the backend to serve the request is determined by
‘pound’.  You can, however, affect its decision by defining the
preferred “balancing weight” for the backend.  Recall, that backends are
grouped into balancer groups, each of which is assigned a unique numeric
weight (*note Balancer groups::).  When selecting the backend to use,
each group is visited in turn, in order of increasing weight, until a
suitable backend is found.  You can instruct ‘pound’ to start this
process at a particular weight, instead of the default 0, by setting the
‘http.balancer’ variable to the desired weight value.  The most obvious
use is to redirect the request to “emergency” backends (*note emergency
backends::), which are assigned to the balancer group 65535.  For
example, if the selected backend responds with 421 (‘Misdirected
Request’) status code, you can send it to your high availablility
backend using the following approach.

   First, define a Lua function that will select the emergency balancer
group, if the backend returned 421:

     function fallback()
       if http.resp.code == 421
         http.balancer = 65535
       end
     end

   Notice, that you need not set the ‘http.resend’ variable: it is
implied when you set ‘http.balancer’.

   Then, construct your service section as follows:

     Service
         Rewrite response
             LuaModify "fallback"
         End
         ContentCapture 16384
         Backend
             Address 10.1.0.1
             Port 80
         End
         Emergency
             Address 10.11.0.123
             Port 80
         End
     End

   Now, should the backend ‘10.1.0.1:80’ return 421, the request will be
sent to ‘10.11.0.123:80’ for processing.

   Notice, that it is only for the sake of an example that the above
service definition contains one backend in each balancer group.  It can,
of course, contain any number of these, in which case ‘pound’ will
select one of them using ‘http.balancer’ as a hint.

Resending to Another Service
----------------------------

Now let's examine the second case: sending request to another service.
This can be useful, for example, if the current service got a response
from the backend indicating that it was unable to handle the request,
and something in the response indicates that you have another service
that should be able to handle the request properly.  This too is done by
defining a Lua function and calling it from ‘Rewrite response’ section.
However, instead of ‘http.resend’, one will use the ‘http.service’
field.

   This field is a table containing two keys: ‘http.service.name’
contains the name of the currently selected service, and
‘http.service.locus’ gives its location in the configuration file.  The
latter field is read-only, while the former can be set to indicate the
service to resend the request to.

   Initializing ‘http.service.name’ to ‘nil’ clears the currently
selected service and instructs ‘pound’ to select another service using
the standard algorithm, described in *note Service selection::.  You can
control this process by adding or modifying request headers so as to
trigger the desired condition.

   Otherwise, you can initialize ‘http.service.name’ with the symbolic
name of the service you want to resend it to (*note Service::).  For
example, suppose there is a service whose definition within the listener
starts with:

     Service "default"

   To have ‘pound’ resend the request to that service, you would do the
following in your Lua function:

     http.service.name = "default"

   If the service is defined in the global scope, use its name prefixed
with a slash, i.e.:

     http.service.name = "/default"

   Notice, that the two variables ‘http.service.name’ and ‘http.resend’
are mutually exclusive.  In other words, setting ‘http.resend’ after
assigning to ‘http.service.name’ will clear the latter assignment and
vice-versa.

   To illustrate this, the following function instructs ‘Pound’ to
attempt a service named ‘fallback’ in case the backend returns 421
status code (‘Misdirected Request’):

     function resend_421()
       if http.resp.code == 421
         http.service.name = "fallback"
       end
     end

   Example usage:

     Service
         ContentCapture 65536
         Rewrite response
             LuaModify "resend_421"
         End
         ...
     End

   A final note: you can select both the service to use and the balancer
group within it:

     http.service.name = "fallback"
     http.balancer = 65535


File: pound.info,  Node: Stash,  Next: LuaBackend,  Prev: Resend,  Up: Lua

8.6 Sharing data between Lua invocations
========================================

Sometimes it is necessary to share data between Lua functions used as
conditions and modifiers in ‘pound’ configuration file.  An obvious way
of doing so is using Lua global variables.  This approach, however,
poses one major problem: values stored in globals will persist not only
when processing a single HTTP request, but also between different HTTP
requests, and this can cause undesirable side effects.

   To avoid this, ‘pound’ provides a special built-in variable ‘stash’.
Its value is a table whose contents persist only while a singe HTTP
request is being processed.  Applications can fill it with whatever
values they like.

   To illustrate its use let's change the ‘bearer’ module from *note
LuaMatch::, so it can be used to select the service to use based on JWT
claims.  First, the ‘bearer.ok’ function should store the parsed JWT
object in stash before returning.  Its last lines will then look like:

        stash.bearer = j
        return true
     end

   Then, we implement a new method, which checks if the hostname given
as its argument is listed in one of the JWT claims:

     function bearer.urlOK(host)
        return stash.bearer ~= nil and
               stash.bearer.payload['http://' .. host] == true
     end

   Now this method can be used as a conditional to select the service to
use as shown in the example below:

     Service "auth"
         Not LuaMatch "bearer.ok" "secret"
         Rewrite response
             SetHeader "WWW-Authenticate: Bearer realm=\"Restricted access\""
         End
         Error 401
     End

     Service "foo"
         LuaMatch "bearer.urlOK" "foo.com"
         Backend
             Address 127.0.0.1
             Port 8081
         End
     End

     Service "bar"
         LuaMatch "bearer.urlOK" "bar.com"
         ...
     End

   The service ‘auth’, same as in the previous example, verifies that
the request carries a valid bearer token and, if so, saves off the JWT
for further use.  Subsequent services make use of this saved value to
verify if the corresponding claim is true: the service ‘foo’ is selected
if the claim ‘http://foo.com’ is true, and so on.


File: pound.info,  Node: LuaBackend,  Next: Lua API,  Prev: Stash,  Up: Lua

8.7 Lua backends
================

Lua extensions can also be used to define new backends.  Similarly to
conditions, a function implementing a backend can have an arbitrary
number of arguments.  It is not supposed to return any values, though.
Instead, before returning, it should define the response to be returned
to the client.  It does so by initializing fields of the internal
variable ‘http.resp’:

‘code’
     This field must be assigned the HTTP status code (an integer value
     in the range 100 to 599).  If it is not initialized after the
     backend function returns, ‘pound’ will respond with the default
     ‘internal server error’ page.

‘reason’
     This is a textual reason corresponding to the status code.  This
     value is optional.  If not initialized, ‘pound’ will use the
     default value for the returned status code, if it is one of the
     codes supported internally (*note Error definitions::).  Otherwise
     the reason field will remain empty.

‘headers’
     A table of response HTTP headers.

‘body’
     Response body as a string.

   Here is an example of Lua backend function.  The function below can
be used to return meaningful error status if the JWT authorization
implemented in previous sections fails.  It supposes that function
‘bearer.ok’, before returning on error, initializes ‘stash’ fields
‘error’ and ‘error_description’ to the error code and textual
description, correspondingly.

     function bearer.error_backend()
        local text = 'Bearer realm="Restricted access"'
        if stash.bearer.error ~= nil then
           text = text .. ', error="' .. stash.bearer.error .. '"'
           if stash.bearer.error_description ~= nil then
              text = text .. ', error_description="' .. stash.bearer.error_description .. '"'
           end
        end

        http.resp.headers['WWW-Authenticate'] = text

        http.resp.code = 401
     end

   To use this backend, we modify the ‘auth’ service as follows:

     Service "auth"
         Not LuaMatch "bearer.ok" "secret"
         LuaBackend "bearer.error_backend"
     End


File: pound.info,  Node: Lua API,  Prev: LuaBackend,  Up: Lua

8.8 Lua API
===========

The ‘pound’ module.
-------------------

 -- Method on pound: string,err dump (arg)
     Dumps the value of its argument in a string form, suitable for
     using in Lua chunks.  On success, the function returns the
     resulting string and ‘nil’.  On error (ARG contained “userdata” or
     other data types that cannot be handled, the function returns ‘nil’
     and a textual message describing the reason for the failure.

     For the function to succeed, ARG must be of one of the following
     data types: ‘nil’, boolean, number, string, and table.  If it is a
     table, the same restriction applies to all its keys and values,
     recursively.

 -- field of pound: integer loadctx
     This variable is initialized when loading Lua source files to the
     ordinal number of the Lua “state” where the file is being loaded.
     For globally loaded sources (*note global lua loading::), this
     variable is set to 0.  For per-thread loading, it is set to a
     positive integer identifying the state.

 -- Method on pound: void log (int PRIO, string MESSAGE)
     Outputs MESSAGE to the logging channel PRIO.

   The following constants can be used for PRIO argument:

 -- Constant of pound: DEBUG
     Debug messages.

 -- Constant of pound: INFO
     Informative messages.

 -- Constant of pound: NOTICE
     Important notices.

 -- Constant of pound: WARNING
     Warning messages.

 -- Constant of pound: ERR
     Errors.

 -- Constant of pound: CRIT
     Critical errors.

 -- Constant of pound: ALERT
     Serious alerts.

 -- Constant of pound: EMERG
     Emergency messages

 -- Method on pound: integer tid ()
     Returns identifier of the current ‘pound’ thread.

 -- Method on pound: gcall (string FUNC, ...)
     Call function FUNC defined in a globally-loaded Lua module, passing
     it the remained arguments.  Return whatever values FUNC returns.

     This function makes it possible for a function in a per-thread
     module to invoke a function from global context.  Notice the
     following limitations:

       1. As for any function from globally-loaded module, the global
          Lua state will be locked until FUNC returns.

       2. Types of arguments that can be passed to FUNC and returned
          from it are limited to the following: ‘nil’, boolean, number,
          string, and table.  In the latter case, the same restriction
          applies to keys and values of the table.  Besides, tables
          cannot contain cyclic references.

       3. Calling this function from a globally-loaded module is also
          allowed.  It is equivalent to calling ‘FUNC(...)’.

The ‘http’ module.
------------------

This built-in module contains variables and methods describing the HTTP
request being handled.

 -- Method on http: string const name
     Retrieve the value of the configuration constant NAME.  *Note
     Constants::, for a detailed discussion of this feature.

     Example:

          local s = http:const("key")

 -- Field of http: string rmt_ip
     Request originator IP address.

 -- Field of http: string fwd_ip
     Request originator IP address determined from ‘X-Forwarded-For’ (or
     similar) header, as described in *note %a::.  If no ‘TrustedIP’ ACL
     is defined or if the request does not bear the ‘X-Forwarded-For’
     (or similar) header, this is equivalent to ‘http.rmt_ip’.

 -- Field of http: table req
     Returns a table describing the request.  This is a read-only table,
     whose fields and methods are described below.

      -- Field of req: string body
          Request body, in the raw form (as sent by the remote party).
          This field is present, only if “content capturing” is enabled
          in the ‘Service’ section for which the Lua code is executed
          (*note ContentCapture::), and the actual content length was
          less than or equal to the capture size limit.

      -- Field of req: string method
          HTTP method used in the request.

      -- Field of req: string line
          Request line, i.e.  part of the request between the method and
          HTTP version designator.

      -- Field of req: string url
          URL part of the request.

      -- Field of req: string path
          Pathname part of the request.

      -- Field of req: table version
          HTTP version of the request.  Used in string context, returns
          version as a string:

               tostring(http.req.version) ⇒ "1.1"

          Two variables are provided to access version parts:

           -- Field of version: integer major
               Major part or the version.

           -- Field of version: integer minor
               Minor part or the version.

      -- Field of req: table query
          Query part of the request.  Converted to string, returns the
          query in full:

               tostring(http.req.query) ⇒ "t=history&r1=10"

          Accessed as table, returns values of parameters used as keys:

               http.req.query['t'] ⇒ "history"
               http.req.query.r1 ⇒ "10"

      -- Field of req: table headers
          Returns headers of the request.  Converted to string, returns
          all headers as a (multiline) string, terminated with a
          newline.  Indexed as a table, returns values of fields used as
          keys.

               tostring(http.req.headers) ⇒ "Host: example.net\nContent-Type:text/plain\n"
               http.req.headers['Host'] ⇒ "example.net"

 -- Field of http: table resp
     A table describing the response.  It is meaningful only for
     functions invoked from ‘LuaBackend’ or Lua directives used in
     ‘Rewrite response’ context.  It is a read-write table.  Assigning
     to its fields modifies the response that will be sent out by
     ‘pound’ when the ‘LuaBackend’ function returns.

      -- Field of resp: integer code
          HTTP status code of the response.  An integer number in the
          range ‘[100,599]’.  The ‘LuaBackend’ function must set this
          field/

      -- Field of resp: string reason
          Textual reason describing the response.  Setting it is
          optional.  If not set, and the ‘resp.code’ is set to one of
          the values supported by ‘pound’ (*note Error definitions::),
          the standard reason will be used instead.

      -- Field of resp: table headers
          Headers of the response.  When read, these behave similarly to
          request headers, described above (*note http.req.headers::).
          Setting this field to ‘nil’ removes all headers.  Setting it
          to a table, fills all headers from it.  Otherwise, each header
          can be set separately, as

               http.resp.headers['Host'] = "example.org"

      -- Field of resp: string body
          The request body.

 -- Field of http: integer balancer
     Available for use in functions called from ‘Rewrite response’
     section (*note Resend::).  It contains the weight of the balancer
     group from which the current backend was selected (*note Balancer
     groups::).

     When assigned a value, instructs ‘pound’ to resend current request
     to another backend, selecting it from the balancer group with the
     weight greater than or equal to the assigned value.  *Note send to
     backend::, for a detailed discussion.

 -- Field of http: boolean resend
     This field is available only for functions invoked from ‘Rewrite
     response’.  Setting it to ‘true’ instructs ‘pound’ to resend
     current request to the backend.  Obviously, prior to setting it to
     ‘true’, the program is supposed to modify the request in some way.

     This approach can be used, for example, to react on 401 response
     from the backend, by re-sending it the request with properly
     constructed ‘Authorization’ header.  *Note Resend::, for a detailed
     discussion.

     To avoid dead loops, ‘pound’ limits the number of resending
     attempts to 4 per request.  The actual number of times the request
     has been resent is kept in the ‘http.resendcount’ variable (see
     below).

     Notice, that resending ‘POST’ requests requires request content
     capturing (*note ContentCapture::).

 -- Field of http: integer resendcount
     This read-only field is available only for functions invoked from
     ‘Rewrite response’.  It contains the number of times the current
     request was resent.  *Note Resend::, for a detailed discussion.

 -- Field of http: table service
     This field contains information about the currently selected
     service.  It is available only in functions called from the
     ‘Rewrite response’ section.  It contains the following fields:

      -- Field of service: string name
          The service name (*note Service::), or empty string, if the
          service is defined without a symbolic name.  Names of global
          services are prefixed with ‘/’.

          Assigning a string value to this field instructs ‘pound’ to
          redirect the request to the service with the given name.  If
          there is no service with such name, a runtime error will be
          signalled.  Setting this field to ‘nil’ instructs ‘pound’ to
          redirect the request to a service selected using the standard
          procedure (*note Service selection::).  *Note send to
          service::, for a detailed discussuion of this feature.

      -- Field of service: string locus
          Returns the location of the service in the configuration file.
          The location is formatted as follows:

               FILE:L1.C1-L2.C2

          where FILE is the configuration file name, L1 and L2 are line
          numbers of the beginning and end of the ‘Service’ section, and
          C1 and C2 are the corresponding column numbers.

The ‘stash’ table
-----------------

 -- Lua variable: table stash
     This global variable can be used to exchange data between Lua
     functions called within the same Lua “state”, but invoked from
     different ‘pound’ handlers.  For example, a test invoked by
     ‘LuaMatch’ directive can leave there some data for use by the
     backend (‘LuaBackend’).

     Upon receiving a new HTTP request, this table is guaranteed to be
     empty.  The values stored in it persist until the response is sent.

     Notice, that ‘stash’ is unique for each Lua state, so that it
     cannot be used to pass data from functions loaded globally to
     per-thread ones, and vice versa.  *Note gcall::, for a ways to
     interface between local and global contexts.


File: pound.info,  Node: Tunnels,  Next: Logging,  Prev: Lua,  Up: Top

9 Tunnels
*********

A “tunnel” is a transparent, protocol-agnostic communication channel
between two sockets.  When operating a tunnel, ‘pound’ sends packets
received from one end (client) to its peer (backend) and vice-versa
without analysing their content.  Thus, tunnels can be used to proxy any
protocol based on TCP/IP.

   Syntactically, a tunnel declaration is similar to ‘ListenHTTP’,
except that ‘Tunnel’ keyword is used instead, and only a limited subset
of statements is allowed within it:

     Tunnel ["NAME"]
         Address ADDR
         Port N
         Backend
             Address ADDR
             Port N
         End
     End

   Just as with ‘ListenHTTP’, ADDR can be any of: IPv4 address, IPv6
address, or a UNIX socket name in double quotes.  If an IP address is
used, ‘Port’ must be specified.  The ‘SocketFrom’ statement can be used
in lieu of ‘Address’ and ‘Pair’ in the ‘Tunnel’ section.  Conversely,
both ‘Address’ and ‘Port’ in ‘Backend’ section are mandatory.

   *Note Tunnel::, for a detailed discussion of the syntax of the
‘Tunnel’ statement.


File: pound.info,  Node: Logging,  Next: Configuration,  Prev: Tunnels,  Up: Top

10 Logging
**********

‘Pound’ can send its diagnostic messages to standard error, syslog, or
to both.

   Upon startup, while the configuration file is being parsed, the
diagnostics goes to the standard error.  Once it switches to the
operation mode and starts serving requests, diagnostic output is
switched to syslog.  The syslog facility to use is configured via the
‘LogFacility’ configuration directive.  By default, ‘daemon’ is used.

   When running in foreground mode, the ‘-e’ command line option
instructs ‘pound’ to use standard error for logging, thus overriding the
settings from the configuration file.

   Normally, ‘pound’ is not very loquacious in logging: only errors and
exceptional conditions are reported.  Messages concerning ‘pound’ itself
are reported to syslog facility ‘err’.  Messages that describe
exceptional conditions detected when serving requests are reported to
facility ‘notice’.  These latter have the following format:

     pound: (TID): CLIENT-IP: "REQUEST": MESSAGE
     or
     pound: (TID): eNNN: CLIENT-IP: "REQUEST": MESSAGE

where:

TID
     Thread identifier.

NNN
     Optional three-digit HTTP status code.

CLIENT-IP
     IP address of the client.

REQUEST
     HTTP request being served.

MESSAGE
     Message text.

   If the condition being reported concerns the backend, then the IP
address of the backend is included as well, e.g.(1):

     pound: (7fcb33924640): 192.0.20.3 => 10.0.0.1:8081:
             "POST /upload HTTP/1.1": error writing to backend

   The ‘=>’ marker between IP addresses indicates flow direction: from
‘pound’ to backend.  If an error occurs while transferring response from
backend to client, it is indicated by ‘<=’, as in:

     pound: (7fcb33924640): 192.0.20.3 <= 10.0.0.1:8081:
             "POST /upload HTTP/1.1": response read error

   Additionally, ‘pound’ can be instructed to log each processed
request.  These “access logs” are emitted for each processed request
_after a response was sent back to the client_, and go to the syslog
facility ‘info’.

   Such additional logging is configured using two directives:
‘LogLevel’ and ‘LogFormat’.  The ‘LogLevel’ directive can appear either
in listener scope, in which case it affects only this particular
listener, or in global scope, where it affects all listeners that don't
configure it on their own.  The value of this directive can be either an
integer number in range 0 through 5 (inclusive), or a quoted string.
Numeric value requests one of the “built-in log formats”.  String value
refers either to a built-in format name, or to a user-defined format
name.

   The built-in formats are:

0
null
     No request logging at all.

1
regular
     For each request, its source address, request line and response
     status are logged.

2
extended
     In addition to the above, the selected service and backend are
     shown.

3
vhost_combined
     Detailed request logging using Apache-style “Combined” log format.

4
combined
     Same as above, but without virtual host information.

5
detailed
     Same as ‘combined’, with additional information about the selected
     service and backend.

   If the string argument to ‘LogLevel’ is not one of the above, it must
refer to the name of a “custom format”, defined earlier using the
‘LogFormat’ statement.  This statement takes two string arguments: the
name to be assigned to the new format, and its definition.

   The “format definition” is a character string composed of ordinary
characters (not ‘%’), which are copied unchanged to the resulting log
message, and conversion specifications, each of which are replaced by a
corresponding piece of information about the request or reply.

   Conversion specifications are single characters prefixed with a
percent sign.  Depending on the specification, an optional “conversion
argument” in curly brackets may appear between ‘%’ and conversion
character.

   The following conversion characters are defined:

 -- Format specifier: %%
     Replaced with the percent sign.

 -- Format specifier: %a
     Originator IP address of the request.  If the request contains
     ‘X-Forwarded-For’ header and ‘TrustedIP’ ACL is defined, the value
     of the header is consulted to obtain the IP address.  The value
     must be a comma-delimited list of intermediate user-agent IP
     addresses.  To determine the actual user-agent IP, the list is
     traversed from right to left, until an IP is found that is not
     listed in ‘TrustedIP’ ACL.

     If ‘X-Forwarded-For’ is not present, or ‘TrustedIP’ is not defined,
     or the above algorithm does not return an IP address, ‘%a’ expands
     to the actual remote IP address the request came from (same as
     ‘%h’).

     The ‘TrustedIP’ ACL can be defined in global scope, or in
     ‘ListenHTTP’ (‘ListenHTTPS’) section, or in ‘Service’ section.
     Most-specific ACL overrides least-specific ones, that is a
     ‘TrustedIP’ defined in ‘Service’ will be used, if it is defined.
     If not, the one defined in listener will be used, etc.  The syntax
     of the ‘TrustedIP’ statement is the same as that of ‘ACL’, i.e.

          TrustedIP "NAME"

     refers to the named ACL NAME (which must be defined earlier, *note
     ACL::),

          TrustedIP
            "CIDR0"
            "CIDR1"
            ...
          End

     defines the list of trusted IPs in place, and

          TrustedIP -file "FILENAME"
          TrustedIP -filewatch "FILENAME"

     reads CIDR definitions from file FILENAME (*Note File-based
     Conditions::, for a discussion of the difference between ‘-file’
     and ‘-filewatch’).

     If needed, the ‘ForwardedHeader’ statement may be used to declare
     the name of the header to use instead of ‘X-Forwarded-For’.  As
     ‘TrustedIP’, this statement can appear in global, listener, or in
     service scope.

 -- Format specifier: %A
     Local IP address of the listener.

 -- Format specifier: %B
     Size of response in bytes, excluding headers.

 -- Format specifier: %b
     Same as ‘%B’, but in “CLF” format, i.e.  a dash is used when
     response size is zero.

 -- Format specifier: %D
     The time taken to serve the request, in microseconds.

 -- Format specifier: %h
     Client IP address of the request.

 -- Format specifier: %H
     The request protocol.

 -- Format specifier: %{HDR}i
     The contents of ‘HDR:’ header line in the request.  Changes made by
     header modification directives affect this.

 -- Format specifier: %{HDR}I
     Same as ‘%i’, except that if no such header is present in the
     request, a dash is substituted.

 -- Format specifier: %l
     Single dash.  This specifier is reserved for future use.

 -- Format specifier: %{OBJ}L
     Location of the ‘pound’ object that is involved in handling the
     request.  Valid values for OBJ are: ‘listener’, ‘service’, and
     ‘backend’.

     The location gives position in the configuration file where the
     object was defined, and is formatted as

          NAME:LN1.COL1-LN2.COL2

     where NAME is the configuration file name, LN1 and COL1 are line
     and column where the object definition begins, LN2 and COL2 are
     line and column where it ends.  Line and column numbers start with
     1.

 -- Format specifier: %m
     The request method.

 -- Format specifier: %{OBJ}N
     Name of ‘pound’ object that is involved in handling the request.
     Valid values for OBJ are: ‘listener’, ‘service’, and ‘backend’.

 -- Format specifier: %p
     Port number of the listener serving the request.

 -- Format specifier: %P
     Thread ID of the serving thread.

 -- Format specifier: %q
     The query string (prepended with a ‘?’) if it exists, otherwise an
     empty string.

 -- Format specifier: %r
     First line of request.

 -- Format specifier: %s
     Response status code.

 -- Format specifier: %>s
     First line of the response.

 -- Format specifier: %t
     Time the request was received, in the format ‘[18/Sep/2011:19:18:28
     -0400]’.  The last number indicates the timezone offset from UTC.

 -- Format specifier: %{FORMAT}t
     Time the request was received, in the format specified by the
     argument (*note Time and Date Formats::).  If the format starts
     with ‘begin:’ (default) the time is taken at the beginning of the
     request processing.  If it starts with ‘end:’, it is the time after
     the response from the backend has been sent back to the requester.
     In addition to ‘strftime’ formats, the following specifications are
     recognized:

     sec
          Number of seconds since the Epoch.
     msec
          Number of milliseconds since the Epoch.
     usec
          Number of microseconds since the Epoch.
     msec_frac
          Millisecond fraction of the time.
     usec_frac
          Microsecond fraction of the time.

 -- Format specifier: %T
     The time taken to process the request, in seconds.

 -- Format specifier: %{UNIT}T
     The time taken to process the request, in a time unit given by
     UNIT.  Valid units are ‘ms’ for milliseconds, ‘us’ for
     microseconds, ‘s’ for seconds, and ‘f’ for seconds with fractional
     part.  Using ‘s’ gives the same result as ‘%T’ without any format;
     using ‘us’ gives the same result as ‘%D’.

 -- Format specifier: %u
     Remote user if the request was authenticated.

 -- Format specifier: %U
     The URL path requested.  This is affected by request modification
     directives.

 -- Format specifier: %v
     Hostname used in the request (from the ‘Host’ header, without port
     number).

   The table below describes the built-in formats in terms of format
definitions:

0
null
          ""

1
regular
          "%a %r - %>s"

2
extended
          "%a %r - %>s (%{Host}i/%{service}N -> %{backend}N) %{f}T sec"

3
vhost_combined
          "%v:%p %a %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\""

4
combined
          "%a %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\""

5
detailed
     (Split in two lines for readability)
          "%v:%p %a %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"
          (%{service}N -> %{backend}N) %{f}T sec"

   ---------- Footnotes ----------

   (1) These example messages are split in two lines for readability


File: pound.info,  Node: Configuration,  Next: poundctl,  Prev: Logging,  Up: Top

11 Configuration
****************

A configuration file provides ‘pound’ with the information necessary for
performing its tasks.  Some configuration file statements can be
overridden from the command line.

* Menu:

* Lexical structure::
* Syntax::
* String Expansions::
* Global directives::
* Constant::
* File inclusion::
* Logging configuration::
* Management interface::
* Timeouts::
* ListenHTTP::
* ListenHTTPS::
* Tunnel::
* Service::
* resolver::


File: pound.info,  Node: Lexical structure,  Next: Syntax,  Up: Configuration

11.1 Lexical structure
======================

Lexically, the file contains tokens of three types: keywords, values,
and separators.  Blanks, tabs, newlines and comments, collectively
called “white space” are ignored except as they serve to separate
tokens.  Some white space is required to separate otherwise adjacent
keywords and values.

   “Comments” may appear anywhere where white space may appear in the
configuration file.  A comment begins with a hash sign (‘#’) and
continues to the end of the line.

   A “keyword” is a sequence of ASCII letters, digits and underscores
that begins with an ASCII letter or underscore.  Keywords are always
case-insensitive.

   There are three kinds of “values”: numeric values (or “numbers”),
boolean values, quoted strings, and IP addresses.

“Numbers”
     A “numeric value” is a sequence of decimal digits.

“Booleans”
     A “boolean” is one of the following: ‘yes’, ‘true’, ‘on’ or ‘1’,
     meaning “true”, and ‘no’, ‘false’, ‘off’, ‘0’ meaning “false”.

“Strings”
     A “quoted string” or “string”, for short, is a sequence of
     characters enclosed in a pair of double quotes.  A backslash (‘\’)
     appearing within a string acts as an “escape character”: if it is
     followed by a double-quote or another backslash, it forces the
     character that follows it to be treated as an ordinary one.  For
     example:

          "string with \" character"

     A backslash followed by any character other than ‘"’ or ‘\’ is
     removed and a warning to that effect is output.  For example, the
     following statement:

          user "r\oot"

     appearing at line 1 of file ‘pound.cfg’ will result in the
     following message:

          pound.cfg:1.8: unrecognized escape character

     and will be treated as

          user "root"

“IP addresses”
     IP addresses are IPv4 or IPv6 addresses in numeric form, or
     hostnames.


File: pound.info,  Node: Syntax,  Next: String Expansions,  Prev: Lexical structure,  Up: Configuration

11.2 Syntax
===========

Syntactically, ‘pound’ configuration is a sequence of statements of two
kinds: simple and compound.

   A “simple statement” or “directive” consists of a keyword followed by
a value, located on a single line.  For example:

     user "proxy"

   There are some simple statements that don't take any value and thus
consist only of a keyword, e.g.

     HTTPS

   A “compound statement” or “section” encloses one or more other
statements (both simple or compound).  It begins with a keyword,
optionally followed by a value, both located on a single line (similar
to simple directives), followed by any number of subordinate statements,
and ends with a keyword ‘End’ on a line by itself.  For example:

     Control
         Socket "/run/pound.sock"
         Mode 660
         ChangeOwner true
     End

   Unless specified otherwise, directives may appear in any order.


File: pound.info,  Node: String Expansions,  Next: Global directives,  Prev: Syntax,  Up: Configuration

11.3 String Expansions
======================

String arguments to some configuration statements undergo several
“expansions” before use.  The “backreference expansion” replaces special
notations in the string called “backreferences” with corresponding parts
of the request recently matched against a regular expression.  The
“request accessor interpretation” inserts some fragments of the request
URL into the string.

   These expansions are discussed in detail below.

* Menu:

* Backreference Expansion::
* Request Accessors::


File: pound.info,  Node: Backreference Expansion,  Next: Request Accessors,  Up: String Expansions

11.3.1 Backreference expansion
------------------------------

Backreference is a construct that refers to a “parenthesized group”
within a regular expression matched by one of service matching
directives (*note Service Selection Statements::).  During backreference
expansion, each occurrence of such construct is replaced with the actual
value of that parenthesized group.

   Syntactically, backreferences can take two forms.  The construct
‘$N’, where N is a decimal number, refers to Nth parenthesized
subexpression of the most recently matched statement, and the construct
‘$N(M)’ refers to Nth parenthesized subexpression in the Mth recently
matched statement.  Numbering of subexpressions starts at 1 (‘$0’ refers
to entire matching string).  Numbering of matches starts at 0.

   For example, given the following statements

     Host -re "www\\.(.+)"
     Header -re -icase "^Content-Type: *(.*)"
     Path "^/static(/.*)?"

‘$1’ refers to the subgroup of ‘Path’, ‘$1(1)’ refers to that of
‘Header’, and ‘$1(2)’ to that of ‘Host’.

   Conditional statements can also be tagged (*note tag::).  When
referring to a subexpression in such a statement, the form ‘$N(T)’ can
be used, where T is the tag.  For example, after tagging the statements
in the example above:

     Host -tag "host" -re "www\\.(.+)"
     Header -tag "type" -re -icase "^Content-Type: *(.*)"
     Path -tag "dir" "^/static(/.*)?"

the corresponding strings can be referred to as: ‘$1’ or ‘$1(dir)’,
‘$1(type)’, and ‘$1(host)’, correspondingly.

   Curly braces may be used to avoid incorrectly parsing text fragment
that follows the reference as being its part.  This is useful if the
reference is immediately followed by a decimal digit or opening
parenthesis, as in: ‘${1}(text)’.

   To insert a literal dollar or percent sign in the string, use ‘$$’ or
‘$%’, correspondingly.


File: pound.info,  Node: Request Accessors,  Prev: Backreference Expansion,  Up: String Expansions

11.3.2 Request Accessor Interpretation
--------------------------------------

“Request accessor” is a syntactical construct of the form:

     %[NAME]

where NAME denotes a part of the incoming request or configuration
setting to access and square brackets are part of the construct.
Accessors are interpreted and replaced with the value of the
corresponding part of the request.  Some accessors take an argument,
which is specified after accessor name and is delimited from it by one
or more whitespace characters.

   The following accessors are defined:

 -- Accessor: const NAME [ENCODE]
     Configuration constant NAME (*note Constants::).  Optional ENCODE
     defines the encoding in which to represent it.  Its possible values
     are:

     ‘none’
          Don't encode it.  This is the default if no ENCODE argument is
          present.

     ‘url’
          Encode the value using percent-encoding (RFC 3986).

     ‘base64’
          Encode the value using base64 encoding (RFC 3548).

 -- Accessor: url
     Request URL.

 -- Accessor: path
     Request path.

 -- Accessor: query
     Query part.

 -- Accessor: param NAME
     The value of the query parameter NAME.

 -- Accessor: header NAME
     The value of HTTP header NAME.

 -- Accessor: host
     Hostname part of the HOST header.  If the latter does not include
     port number, it is equivalent to ‘%[header host]’.

 -- Accessor: port
     If the value of the ‘Host’ header includes port number, ‘%[port]’
     expands to port number with the leading colon character.
     Otherwise, it expands to empty string.

 -- Accessor: remoteip FWD
     Expands to the request originator IP address.  If FWD is 0, expands
     to its real IP, otherwise expands to the IP determined from the
     ‘X-Forwarded-For’ (or similar) header.  *Note %a::, for details.

 -- Accessor: user
     If the request bears the ‘Authorization: Basic’ header, expands to
     the user name extracted from its value.  Otherwise, its expansion
     is empty.


File: pound.info,  Node: Global directives,  Next: File inclusion,  Prev: String Expansions,  Up: Configuration

11.4 Global directives
======================

Global directives configure the program operation as a whole.  They may
appear anywhere at the global scope of the configuration file, although
it is customary for them to be at its start.

* Menu:

* Runtime directives::
* Worker Settings::
* Proxy Tuning::
* SSL Settings::
* Regexp Settings::
* ACL definition::
* Condition::
* Lua Settings::


File: pound.info,  Node: Runtime directives,  Next: Worker Settings,  Up: Global directives

11.4.1 Runtime directives
-------------------------

 -- Global directive: Daemon BOOL
     When set to ‘true’ (the default), ‘pound’ will detach itself from
     the controlling terminal after successful parsing of the
     configuration file and continue operating in the background.

     When set to ‘false’, ‘pound’ will continue operating in the
     foreground.

     This setting can be overridden by the ‘-F’ and ‘-e’ command line
     options.

 -- Global directive: Group "GROUP_NAME"
     Sets the group ‘pound’ will run as.  If not set, the primary group
     of the user (as set by the ‘User’ directive) will be used.

 -- Global directive: PIDFile "FILENAME"
     Sets the name of the file where to store program PID. This can be
     also be set from command line, using ‘-p’ command line option
     (*note Usage::).

     Notice the following:

       1. Setting this directive to ‘-’ (a dash) turns creation of a PID
          file off.

       2. When running with a supervisor, this file holds PID of the
          supervisor process.  Otherwise, it holds PID of the main This
          means it is always suitable for signalling the program using
          the traditional ‘kill `cat filename`’ technique.

       3. Before shutting down, ‘pound’ removes this file.  However, it
          may fail to do so if it switches to privileges of another user
          after startup (at least one of ‘User’ or ‘Group’ are set in
          the configuration file) and the file is stored in a directory
          whose permissions forbid write access for that user.

 -- Global directive: Supervisor BOOL
     When running in daemon mode, start a “supervisor” process.  This
     process, in turn, will start main ‘pound’ process and will further
     monitor it, restarting it if it fails.

     The default is ‘true’.

 -- Global directive: LineBufferSize N
     Sets the line buffer size.  Line buffer is used when reading
     request line, backend response status line, and header fields in
     both requests and responses.  Thus, this value limits the maximum
     length allowed for these parts of HTTP messages.  By default, it is
     set to the internal buffer size (4096 bytes, configurable at
     compile time using the ‘--with-maxbuf’ option)(1), and it cannot be
     less than that default.

     Incoming requests with request line longer than that limit will get
     a 414 (‘URI Too Long’) response.  Requests with one of header
     fields longer than that will be responded with 413 (‘Payload Too
     Large’) code.

     This global setting can be overridden for each particular listener
     (*note Listener-specific limits::).

 -- Global directive: RootJail "DIRECTORY"
     If this directive is present, ‘pound’ will use the system ‘chroot’
     call to set the root directory of the process to that specified by
     DIRECTORY.  After that, the program won't be able to access any
     files outside that directory.

     Before chrooting, ‘pound’ makes the necessary preparations to be
     able to access the files it needs during operation, in particular
     user databases supplied with the ‘BasicAuth’ statements (*note
     Authentication::), and static file directories (*Note ACME::, and
     *note SendFile::).

 -- Global directive: User "USER_NAME"
     Configures the user ‘pound’ will run as.

   ---------- Footnotes ----------

   (1) To check the value your ‘pound’ is compiled with, run ‘pound -V’


File: pound.info,  Node: Worker Settings,  Next: Proxy Tuning,  Prev: Runtime directives,  Up: Global directives

11.4.2 Worker Settings
----------------------

 -- Global directive: WorkerMinCount N
     Sets minimum number of worker threads that must always be running.
     The default is 5.  *Note Worker model::.

 -- Global directive: WorkerMaxCount N
     Sets maximum number of worker threads.  The default is 128.  *Note
     Worker model::.

 -- Global directive: WorkerIdleTimeout N
     Sets idle timeout for a worker thread, in seconds.  Default is 30
     seconds.  *Note Worker model::.

 -- Global directive: WorkerStackSize N
     Sets worker stack size, in bytes.  The default size is 262144.

 -- Global directive: Threads N
     This statement, retained for backward compatibility with previous
     versions of pound, is equivalent to:

          WorkerMinCount N
          WorkerMaxCount N

 -- Global directive: ConnectionQueueSize N
     Sets size of the incoming connection queue (*note Worker model::).

     Unless defined explicitly, its value is computed as:

          R - (W_{max}*F_{wrk} + F_{ini} + F_{res})

     where R is the system limit on available file descriptors (as set,
     e.g.  by ‘ulimit -n’), W_{max} is the value of ‘WorkerMaxCount’
     setting, F_{wrk} is the number of file descriptors used per worker,
     F_{ini} is the number of file descriptors in use at program
     startup, and F_{res} is the number of reserved file descriptors.

     The value of F_{ini} is computed automatically and comprises the
     three standard I/O descriptors and any descriptors opened by
     ‘pound’ for listeners, watchers, etc.  Notice, that at startup
     ‘pound’ will close all inherited file descriptors above 2.  If, for
     some reson, you need to keep them, use the ‘-Wno-close-extra-fds’
     option.

     The value of F_{wrk} is normally 2 (two descriptors necessary for
     I/O).  Initial value of F_{res} is 3.  After parsing the
     configuration file, ‘pound’ may increase it (this happens, e.g.  if
     watchers are used).

     Both values may need a correction in complex configurations, in
     particular if they involve Lua functions that open files or network
     connections (*note Lua::).  Such a correction is done using the
     ‘ReserveFD’ configuration setting.

 -- Global directive: ReserveFD [-worker] N
     Increases default number of “reserved descriptors” by N.

     Used without options, this statement increases the number of
     descriptors reseved globally (see F_{res} above).  If given the
     ‘-worker’ option, it increases the number of descriptors reserved
     per worker (F_{wrk}).


File: pound.info,  Node: Proxy Tuning,  Next: SSL Settings,  Prev: Worker Settings,  Up: Global directives

11.4.3 Proxy Tuning Directives
------------------------------

 -- Global directive: BackendStats BOOL
     Whether to enable backend statistics collection.  Backend
     statistics consists of the following values:

       1. Total number of requests processed by this backend.
       2. Average time per request.
       3. Standard deviation of the average time per request.

     If enabled, these values are made available via ‘poundctl’ (*note
     poundctl list::) and telemetry output (*note Metrics::).

 -- Global directive: Balancer ALGO
     Sets the request balancing algorithm to use.  Allowed values for
     ALGO are:

     random
          Use weighted random balancing algorithm.

     iwrr
          Use interleaved weighted round robin balancing.

     *Note Balancer::, for a detailed discussion of these algorithms.

     The ‘Balancer’ statement in global scope applies to all ‘Service’
     definitions in the file that don't contain ‘Balancer’ definitions
     of their own.

 -- Global directive: HeaderOption OPT ...
     Sets default header addition options.  One or more arguments are
     allowed, each being one of:

     ‘none’
          Disable additional headers.

     ‘forwarded’
          Add ‘X-Forwarded-For’, ‘X-Forwarded-Proto’, and
          ‘X-Forwarded-Port’ headers.

     ‘ssl’
          Pass information about SSL certificates in a set of ‘X-SSL-*’
          headers.  This will add the following headers:

          X-SSL-Cipher
               SSL version followed by a slash and active cipher
               algorithm.

          X-SSL-Certificate
               The full client certificate (multi-line).

          X-SSL-Issuer
               Information about the certificate issuer (CA).

          X-SSL-Subject
               Information about the certificate owner.

          X-SSL-notAfter
               End of validity date for the certificate.

          X-SSL-notBefore
               Start of validity date for the certificate.

          X-SSL-serial
               Certificate serial number (in decimal).

     The options ‘forwarded’, and ‘ssl’ can be prefixed with ‘no-’ to
     disable their effect.

     The default is:

          HeaderOption forwarded ssl

     This setting can be overridden for a particular listener using the
     ‘HeadOption’ within it.

 -- Global directive: CombineHeaders
     HTTP protocol allows for certain headers to appear in the message
     multiple times.  Namely, multiple headers with the same header name
     are permitted if that header field is defined as a comma-separated
     list.

     The standard specifies that such fields can be combined in a single
     header line, by appending each subsequent field value to the
     combined field value in order, separated by a comma.

     The ‘CombineHeaders’ statement declares names of the headers to
     which ‘pound’ is to apply this operation.  Each header name should
     be listed on a separate line, enclosed in double-quotes.  The
     keyword ‘End’ on a line by itself ends the statement.  E.g.:

          CombineHeaders
              "Accept"
              "Allow"
              "Cache-Control"
          End

     The ‘include’ statement (*note File inclusion::) can be used in
     ‘CombineHeaders’ statement.

     ‘Pound’ distribution includes file ‘mvh.inc’, which declares all
     known multiple-value headers in a form suitable for inclusion to
     ‘pound.cfg’.  This file is installed in the package data directory,
     so that in order to use it, it suffices to add the following to the
     configuration file:

          CombineHeaders
              Include "mvh.inc"
          End


File: pound.info,  Node: SSL Settings,  Next: Regexp Settings,  Prev: Proxy Tuning,  Up: Global directives

11.4.4 SSL Settings
-------------------

 -- Global directive: SSLEngine "NAME"
     Use an OpenSSL hardware acceleration card called NAME.  Available
     only if OpenSSL-engine is installed on your system.


File: pound.info,  Node: Regexp Settings,  Next: ACL definition,  Prev: SSL Settings,  Up: Global directives

11.4.5 Regular Expression Settings
----------------------------------

 -- Global directive: RegexType TYPE
     Sets the type of regular expressions to use in conditional
     statements.  Allowed values for TYPE are: ‘posix’ and ‘pcre’ (or
     ‘perl’), case-insensitive.  The latter requires compilation time
     support.

     The selected regular expression type remains in effect for all
     conditionals that follow this statement, until next ‘RegexType’
     statement or end of the configuration file, whichever occurs first.

     Regular expression type can be set individually for a directive,
     using the ‘-pcre’ or ‘-posix’ option (*note conditional-option::).

     *Note Regular Expressions::, for a detailed discussion.

 -- Global directive: IgnoreCase BOOL
     Ignore case when doing regex matching (default: ‘false’).  This
     directive sets the default for the following conditionals: ‘URL’,
     ‘Path’, ‘QueryParam’, ‘Query’, ‘StringMatch’, as well as for the
     ‘DeleteHeader’ modification directive.  Its value can be overridden
     for specific services.

     This statement is deprecated and will be removed in future
     versions.  Please, use the ‘-icase’ option to the conditional
     instead (*note conditional-option::).


File: pound.info,  Node: ACL definition,  Next: Condition,  Prev: Regexp Settings,  Up: Global directives

11.4.6 ACL Definition
---------------------

 -- Global directive: ACL "NAME"
     Define a “named access control list”.  An “ACL” is a list of
     network addresses in CIDR notation.  Once defined, the ACL can be
     used in ‘Service’ statements to limit access to resources (*note
     ACL reference::).

     The statement has two forms: immediate and file reference ACL. In
     “immediate” form, the CIDR list follows the ‘ACL’ line and is
     terminated with an ‘End’ directive on a line by itself.  Each
     non-empty line contains a CIDR enclosed in double quotes.  Comments
     and ‘Include’ statements (*note File inclusion::) are allowed.  For
     example:

          ACL "secure"
             "192.0.2.0/26"
             "203.0.113.0/24"
          End

     The syntax of named “file reference” ACL is:

          ACL "NAME" -file "FILENAME"

     or

          ACL "NAME" -filewatch "FILENAME"

     If FILENAME is relative, it is looked up in the *note include
     directory::.  The syntax of the file is similar to the described
     above, except that CIDRs need not be quoted and ‘Include’
     statements are not allowed.  The form with ‘-file’ reads the file
     contents once, at the program startup.  The one with ‘-filewatch’
     reads it and then monitors that file for changes.  *Note File-based
     Conditions::, for a detailed discussion.


File: pound.info,  Node: Condition,  Next: Lua Settings,  Prev: ACL definition,  Up: Global directives

11.4.7 Condition
----------------

 -- Global directive: Condition "NAME"
     Defines a “detached condition” identified by NAME (which must be
     unique among conditions defined in the configuration file).  This
     line must be followed by one or more conditional directives (*note
     conditionals::) and terminated by an ‘End’.

   For example:

     Condition "a"
         ACL -file "secure"
         Path -beg "/admin/"
     End

   Detached conditions can be evaluated in ‘Service’ and ‘Rewrite’
statements using the ‘Eval’ statement (*note Eval statement::).  For a
detailed discussion, see *note Detached Conditions::.


File: pound.info,  Node: Lua Settings,  Next: Constant,  Prev: Condition,  Up: Global directives

11.4.8 The ‘Lua’ statement
--------------------------

Global Lua settings reside in ‘Lua’ section:

     Lua
        ...
     End

   Following statements are allowed for use in this section:

 -- Lua directive: Load "FILENAME"
     Load Lua source file FILENAME in per-thread mode.  Unless specified
     as an absolute pathname, the file will be looked in the “include
     directory” (*note include directory::).

 -- Lua directive: LoadGlobal "FILENAME"
     Load Lua source file FILENAME in global mode.  Unless specified as
     an absolute pathname, the file will be looked in the “include
     directory” (*note include directory::).

 -- Lua directive: Path "PATH"
     Prepend PATH to the Lua ‘package.path’.  This is a
     semicolon-delimited list of patterns that specifies where the Lua
     ‘require’ statement searches for Lua sources.  In patterns, the
     question mark serves as a wildcard and will be replaced by the name
     of the module being loaded.  The path is scanned from left to
     right.

     Multiple ‘Path’ statements are allowed.  After parsing, the values
     from all ‘Path’ statements are joined into a single prefix, which
     is then prepended to the default value of ‘package.path’.

 -- Lua directive: CPath "PATH"
     Similar to ‘Path’ (see above), but modifies ‘package.cpath’, a
     variable that controls where Lua looks for shared libraries.


File: pound.info,  Node: Constant,  Next: File inclusion,  Prev: Lua Settings,  Up: Global directives

11.4.9 The ‘Constant’ statement
-------------------------------

The ‘Constant’ statement defines a “configuration constant” for use in
string expansions and Lua code.  For a detailed description of
configuration constants and their use, *note Constants::,

 -- Global directive: Constant "NAME" "VAL"
     Define constant NAME to have the value VAL.

 -- Global directive: Constant "NAME" OPTIONS
     Define constant NAME and assign its value depending on OPTIONS, as
     described in the table below:

     ‘-file "FILENAME"’
          Read the contents of the file FILENAME, and assign it to the
          constant.  The contents is treated as an opaque binary string.
          The file is read exactly once, at program startup.

     ‘-filewatch "FILENAME"’
          Same as ‘-file’, except that the file is monitored for changes
          during the runtime.  Whenever the file changes, the constant
          will be updated, without the need to restart the program.
          *Note File-based Conditions::, for a detailed discussion of
          this feature.

     ‘-trim’
          Used with one of the above, instructs ‘pound’ to treat
          FILENAME as a plain text file, and remove from its contents
          all trailing whitespace characters, i.e.  horizontal
          tabulation (ASCII 9), newline (ASCII 10), vertical tabulation
          (ASCII 11), form feed (ASCII 12), carriage return (ASCII 13),
          and space (ASCII 32).


File: pound.info,  Node: File inclusion,  Next: Logging configuration,  Prev: Global directives,  Up: Configuration

11.5 File inclusion
===================

 -- Global directive: Include "FILE"
     Include FILE as if it were part of the configuration file.  If FILE
     is a relative file name, it will be looked in the “include
     directory” (see below).  If FILE is a shell globbing pattern, all
     regular files matching that pattern will be included, in
     lexicographical order.

     This directive is allowed both at topmost level and in any
     subsections of the configuration file.

 -- Global directive: IncludeDir "DIR"
     Set the “include directory”, i.e.  the directory where ‘pound’
     looks for relative file names that appear in other configuration
     directives: ‘Include’, ‘BasicAuth’, ‘ErrorFile’ (or ‘Err400’
     through ‘Err503’), as well as in the argument to ‘-file’
     (‘-filewatch’) option in conditionals (*Note -file::, and *note
     File-based Conditions::).

     This directive can appear multiple times.  In that case, the
     directory set by each ‘IncludeDir’ remains in effect until next one
     redefines it.

     The default value is the system configuration directory as set at
     compile time (you can check its value in the output of ‘pound -V’).
     This initial value can be changed in the command line using the ‘-W
     include-dir=DIR’ command line option or reset to the current
     working directory using the ‘-W no-include-dir’ option (*note
     Usage::).


File: pound.info,  Node: Logging configuration,  Next: Management interface,  Prev: File inclusion,  Up: Configuration

11.6 Logging configuration
==========================

 -- Global directive: LogFacility NAME
 -- Global directive: LogFacility -
     Sets the ‘syslog’ facility to use for logging.  Allowed names are:
     ‘auth’, ‘authpriv’, ‘cron’, ‘daemon’, ‘ftp’, ‘kern’, ‘lpr’.
     ‘mail’, ‘news’, ‘user’.  ‘uucp’, and ‘local0’ through ‘local7’.

     The second form configures “default log destination”.  If ‘pound’
     runs in foreground, log messages with priority ‘LOG_DEBUG’ and
     ‘LOG_INFO’ go to stdout, and messages with the remaining priorities
     are printed to stderr.  If ‘pound’ runs as a daemon, log messages
     go to the syslog facility ‘daemon’.

 -- Global directive: LogFormat "NAME" "FORMAT_DEF"
     Define request logging format.  NAME is a string uniquely
     identifying this format, and FORMAT_DEF is the format string
     definition.  *Note Logging::, for a detailed description of format
     definition syntax.

 -- Global directive: LogLevel "NAME"
 -- Global directive: LogLevel N
     Specify the format to use to log HTTP requests.  NAME is a name of
     a custom format, defined earlier using the ‘LogFormat’ directive,
     or one of six built-in format names.

     If numeric argument is used, it refers to a built-in format by its
     number (0 through 5).

     *Note Logging::, for a detailed description of HTTP request
     logging.

 -- Global directive: LogTag "STRING"
     Sets the string to tag syslog messages with.  By default, it is the
     name of the program (more precisely, the name which was used to
     start it).

 -- Global directive: ForwardedHeader "NAME"
     Defines the name of the HTTP header that carries the list of
     proxies the request has passed through.  Default value is
     ‘X-Forwarded-For’.  This header is used to determine the originator
     IP address for logging.  *Note %a::, for details.

 -- Global directive: TrustedIP
     Defines a list of “trusted proxy” IP addresses, which is used to
     determine the originator IP. *Note %a::, for details.

     This statement is a special form of ‘ACL’ statement, described in
     *note ACL::.  It can have in three forms: “anonymous ACL”, “file
     reference”, or “ACL reference”.

     Examples:

       1.      TrustedIP
                 "127.0.0.1/8"
                 "10.16.0.0/16"
               End
       2.      TrustedIP -filewatch "/etc/pound/trustip.acl"
       3.      TrustedIP "proxy_addresses"

 -- Global directive: Anonymise
 -- Global directive: Anonymize
     When logging, replace the last byte of client IP addresses with 0.

     Default: log the client address in full.


File: pound.info,  Node: Management interface,  Next: Timeouts,  Prev: Logging configuration,  Up: Configuration

11.7 Management Interface
=========================

‘Pound’ provides a management interface, which allows one to obtain
information about the running instance, change state of configured
listeners, services, and backends, etc.  These requests are normally
issued by the poundctl utility (*note poundctl::).

   The management interface is usually made available via a UNIX socket.
Properties of this “control socket” are configured via the ‘Control’
statement.  It has two forms: “directive” and “section”.

 -- Global directive: Control "FILENAME"
     Create a UNIX socket FILENAME and listen on it for management
     requests.  The file will be owned by the user that started ‘pound’
     (normally ‘root’) and have mode 0600.

   In section form, the ‘Control’ statement allows for specifying file
mode and, to certain extent, socket file ownership.  The section can
contain the following statements:

 -- Control statement: Socket "FILENAME"
     Specifies the name of the socket file to use.  This is the only
     mandatory statement in the section form.

 -- Control statement: Mode OCTAL
     Sets the mode of the socket file.

 -- Control statement: ChangeOwner BOOL
     This statement takes effect if at least one of ‘User’ or ‘Group’
     global statements is used.  When set to ‘true’ it will change the
     owner of the socket file to that specified by those two statements.

   An example of using the ‘Control’ section:

     Control
         Socket "/run/pound.sock"
         Mode 660
         ChangeOwner true
     End

* Menu:

* Service Control::


File: pound.info,  Node: Service Control,  Up: Management interface

11.7.1 Remote Access to Management Interface
--------------------------------------------

To make the management interface available remotely, use the ‘Control’
statement in a ‘Service’ section:

     ListenHTTP
         Address 192.0.2.1
         Port 80
         Service
             Control
         End
     End

   This configuration makes management interface accessible via
‘http://192.0.2.1/’.  Due to obvious security implications, you'd be
better off protecting the ‘Control’ endpoint using HTTPS, ACLs and/or
basic authorization.  The example below illustrates all these
techniques:

     ListenHTTPS
         Address 192.0.2.1
         Port 443
         Cert "/etc/ssl/priv/example.pem"
         Disable TLSv1

         Service
             Not BasicAuth "pound/htpasswd"
             Rewrite response
                 SetHeader "WWW-Authenticate: Basic realm=\"Restricted access\""
             End
             Error 401
         End

         Service
             ACL "secure"
             Control
         End
     End

   *Note Authentication::, for a discussion of ‘BasicAuth’ statement,
and see *note ACL:: for a discussion of access control lists (this
example assumes that the ACL ‘secure’ is defined elsewhere in the
configuration file).

   If you wish to make management interface available under a special
path, make sure the path prefix is stripped off, e.g.:

     Service
         URL -re "^/control(/.+)"
         SetURL "$1"
         Control
     End

   *Note Service Request and Response Modification::, for details about
‘SetURL’ statement and request modification in general.


File: pound.info,  Node: Timeouts,  Next: ListenHTTP,  Prev: Management interface,  Up: Configuration

11.8 Timeouts
=============

Directives discussed in this section set various timeout values.  Their
argument is an integer expressing the value in seconds.

 -- Global directive: Alive N
     Specify how often should ‘pound’ check for the status of backend
     servers marked as “dead” (i.e.  inaccessible).  It is a good idea
     to set this as low as possible - it will find resurrected hosts
     faster.  However, if you set it too low it will consume resources.

     Default is 30 seconds.

 -- Global directive: Client N
     Specify for how long ‘pound’ will wait for a client request
     (default: 10 seconds).  It will drop the connection if client
     doesn't send any data within this interval.

     This value can be overridden for specific listeners.

 -- Global directive: TimeOut N
     Specify for how long ‘pound’ will wait for the backend to respond
     (default: 15 seconds).

     This value can be overridden for specific backends.

 -- Global directive: ConnTO N
     Specify for how long ‘pound’ will wait for a connection to a
     backend to be established.  Default is the same as the ‘TimeOut’
     value.

     This value can be overridden for specific backends.

 -- Global directive: WatcherTTL N
     If file reference ACLs are used on a system that doesn't support
     ‘inotify’ API, this directive defines the interval between two
     successive checks of file modification times.  *Note ACL
     filewatch::, for a detailed discussion of this feature and
     situations when this setting might be useful.

     The default value is 60 seconds.

 -- Global directive: WSTimeOut N
     Specify for how long ‘pound’ will wait for data from either backend
     or client in a connection upgraded to WebSocket protocol.  Default
     is 600 seconds.

     This value can be overridden for specific backends.

 -- Global directive: Grace N
     How long should ‘pound’ continue to answer existing connections
     after a receiving a ‘INT’ or ‘HUP’ signal (default: 30 seconds).
     The configured listeners are closed immediately.  You can bypass
     this behaviour by stopping ‘pound’ with a ‘TERM’ or ‘QUIT’ signal,
     in which case the program exits without any delay.


File: pound.info,  Node: ListenHTTP,  Next: ListenHTTPS,  Prev: Timeouts,  Up: Configuration

11.9 ListenHTTP
===============

The ‘ListenHTTP’ section declares a listener operating in plaintext HTTP
mode.  The section declaration begins with the keyword ‘ListenHTTP’
optionally followed by a string supplying symbolic name for that
listener, e.g.:

     ListenHTTP "main"
       ...
     End

   The symbolic name can be used in log messages (*note ‘%{OBJ}N’: log
format.) and in ‘poundctl’ (*note poundctl::) requests to identify that
listener.  If the name is not supplied, the listener can be identified
by its ordinal number (0-based) in the configuration file.

* Menu:

* Listener address::
* Listener-specific limits::
* Error definitions::
* Listener logging::
* Request Modification::
* Response Modification::
* Error response rewriting::
* Listener constants::
* Service definitions::


File: pound.info,  Node: Listener address,  Next: Listener-specific limits,  Up: ListenHTTP

11.9.1 Listener address
-----------------------

 -- ListenHTTP directive: Address ADDRESS
     The IP address that ‘pound’ will listen on.  This can be a numeric
     IPv4 or IPv6 address, or a full pathname of a UNIX socket.  To
     listen on all available interfaces, use ‘0.0.0.0’ (for IPv4), or
     ‘::0’ (for both IPv4 and IPv6).

     If neither ‘Address’ or ‘SocketFrom’ are supplied, ‘::0’ is
     assumed.

 -- ListenHTTP directive: Port N
     The port number or service name (as per ‘/etc/services’) that this
     listener will listen on.

     If this directive is not given, the default port number is assumed
     (80 for ‘ListenHTTP’ and 443 for ‘ListenHTTPS’).

 -- ListenHTTP directive: SocketFrom "PATHNAME"
     Read the socket to listen on from the UNIX socket supplied by
     PATHNAME.  If this parameter is supplied, neither ‘Address’ nor
     ‘Port’ may be used.  This parameter is intended for use in ‘pound’
     testsuite.


File: pound.info,  Node: Listener-specific limits,  Next: Error definitions,  Prev: Listener address,  Up: ListenHTTP

11.9.2 Listener-specific limits
-------------------------------

 -- ListenHTTP directive: Client N
     Specify for how long ‘pound’ will wait for a client request
     (default: 10 seconds).  It will drop the connection if client
     doesn't send any data within this interval.

     This statement overrides the global timeout value (*note
     Timeouts::) for this particular listener.

 -- ListenHTTP directive: LineBufferSize N
     Sets the line buffer size.  Line buffer is used when reading
     request line, backend response status line, and header fields in
     both requests and responses.  Thus, this value limits the maximum
     length allowed for these parts of HTTP messages.  The default is
     inherited from the global directive (*note line buffer::).

 -- ListenHTTP directive: MaxRequest N
     Limits the maximum allowed size of incoming requests.  A request
     bigger than that will be responded with status 413.

     By default, there is no limit on the request size.

 -- ListenHTTP directive: MaxURI N
     Limits the maximum allowed length of incoming request URI. A
     request with an URI longer than that will be responded with status
     414 (‘URI Too Long’).

     By default, the limit is set to ‘LineBufferSize’ (*note line
     buffer::).

 -- ListenHTTP directive: CheckURL "PATTERN"
     Define a pattern that must be matched by each request sent to this
     listener.  A request that does not match will be returned a 501
     status.

 -- ListenHTTP directive: xHTTP N
     Defines which HTTP method are accepted.  The possible values are:

     0
          Accept only standard HTTP methods: ‘GET’, ‘POST’, ‘HEAD’.
          This is the default.

     1
          Allow also extended HTTP methods: ‘PUT’, ‘PATCH’, ‘DELETE’.

     2
          Additionally allow standard WebDAV methods: ‘LOCK’, ‘UNLOCK’,
          ‘PROPFIND’, ‘PROPPATCH’, ‘SEARCH’, ‘MKCOL’, ‘MOVE’, ‘COPY’,
          ‘OPTIONS’, ‘TRACE’, ‘MKACTIVITY’, ‘CHECKOUT’, ‘MERGE’,
          ‘REPORT’.

     3
          Additionally allow MS extension WebDAV methods: ‘SUBSCRIBE’,
          ‘UNSUBSCRIBE’, ‘NOTIFY’, ‘BPROPFIND’, ‘BPROPPATCH’, ‘POLL’,
          ‘BMOVE’, ‘BCOPY’, ‘BDELETE’, ‘CONNECT’.


File: pound.info,  Node: Error definitions,  Next: Listener logging,  Prev: Listener-specific limits,  Up: ListenHTTP

11.9.3 Error definitions
------------------------

When ‘pound’ returns an error status, it uses built-in error-specific
description code and status page template.  These values can be
customized using the ‘ErrorFile’ statement.

 -- ListenHTTP directive: ErrorFile CODE "FILENAME"
     Read HTML page for HTTP status code CODE from file FILENAME.

     The CODE argument is a three-digit HTTP response status, and
     FILENAME is the name of a file which supplies contents (and,
     optionally, HTTP headers) of the error response.  *Note Error
     responses::, for details about the file and its usage.

   For compatibility with ‘pound’ versions up to 4.11, the following
statement is also recognized:

     ErrNNN "FILENAME"

where NNN is a three-digit HTTP status code.  This statement is entirely
equivalent to

     ErrorFile NNN "FILENAME"

   ‘Pound’ produces only a subset of all possible status codes, so not
all NNN codes are allowed.  The discussion below lists available HTTP
codes, along with the error description and default error page text.

 -- HTTP status: 400
     ‘Bad Request’
          Your browser (or proxy) sent a request that this server could
          not understand.

 -- HTTP status: 401
     ‘Unauthorized’
          This server could not verify that you are authorized to access
          the document requested.  Either you supplied the wrong
          credentials (e.g., bad password), or your browser doesn't
          understand how to supply the credentials required.

 -- HTTP status: 403
     ‘Forbidden’
          You don't have permission to access this resource.  It is
          either read-protected or not readable by the server.

 -- HTTP status: 404
     ‘Not Found’
          The requested URL was not found on this server.

 -- HTTP status: 405
     ‘Method Not Allowed’
          The request method is not supported for the requested
          resource.

 -- HTTP status: 413
     ‘Payload Too Large’
          The request content is larger than the proxy server is able to
          process.

 -- HTTP status: 414
     ‘URI Too Long’
          The length of the requested URL exceeds the capacity limit for
          this server.

 -- HTTP status: 429
     ‘Too Many Requests’
          The remote party sent too many requests in a given amount of
          time.  ‘Pound’ never issues this error by itself.  This code
          is intended for implementing rate-limiting.  *Note
          Rate-limiting::.

 -- HTTP status: 500
     ‘Internal Server Error’
          The server encountered an internal error and was unable to
          complete your request.

 -- HTTP status: 501
     ‘Not Implemented’
          The server does not support the action requested.

 -- HTTP status: 503
     ‘Service Unavailable’
          The server is temporarily unable to service your request due
          to maintenance downtime or capacity problems.  Please try
          again later.


File: pound.info,  Node: Listener logging,  Next: Request Modification,  Prev: Error definitions,  Up: ListenHTTP

11.9.4 Listener logging
-----------------------

Following statements are similar to the ones described in *note Logging
configuration::, but apply only to the listener they appear in.

 -- ListenHTTP directive: LogLevel "NAME"
 -- ListenHTTP directive: LogLevel N
     Specify the format to use to log HTTP requests.  NAME is a name of
     a custom format, defined earlier using the ‘LogFormat’ directive,
     or one of six built-in format names.

     If numeric argument is used, it refers to a built-in format by its
     number (0 through 5).

     *Note Logging::, for a detailed description of HTTP request
     logging.

 -- ListenHTTP directive: ForwardedHeader "NAME"
     Defines the name of the HTTP header that carries the list of
     proxies the request has passed through.  Default value is
     ‘X-Forwarded-For’.  This header is used to determine the originator
     IP address for logging.  *Note %a::, for details.

 -- ListenHTTP directive: TrustedIP
     Defines a list of “trusted proxy” IP addresses, which is used to
     determine the originator IP. *Note %a::, for details.


File: pound.info,  Node: Request Modification,  Next: Response Modification,  Prev: Listener logging,  Up: ListenHTTP

11.9.5 Request Modification
---------------------------

The statements discussed in this subsection modify incoming requests
prior to passing them to the backend.  These same set of statements can
also be used in ‘Service’ section (*note Service::).  When appearing in
both sections, the directive from ‘ListenHTTP’ (‘ListenHTTPS’) section
are applied first, followed by directives from the ‘Service’ section.
Directives from the same section are applied in order of their
appearance.

 -- ListenHTTP Statement: LuaModify "FUNC" ["ARG"...]
     Run Lua function FUNC with supplied arguments.  The function is
     supposed to modify the request.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaModify::, for a detailed discussion.

 -- ListenHTTP directive: RewriteDestination BOOL
     If set to ‘true’, the ‘Destination:’ request header will be changed
     to point to the backend with the correct protocol.

 -- ListenHTTP directive: SetURL "URL"
     Set the URL of the incoming request to URL.

 -- ListenHTTP directive: SetPath [-encode] "VALUE"
     Set the path part of the URL to the given string.  If ‘-encode’
     option is given, the value will be percent-encoded prior to setting
     it.

 -- ListenHTTP directive: SetQuery "VALUE"
     Set the query part of the URL to the given string.  VALUE must be a
     valid query with the special characters properly encoded using
     percent encoding.

 -- ListenHTTP directive: DeleteQuery
     Delete query part of the URL.

 -- ListenHTTP directive: SetQueryParam "NAME" [-encode] "VALUE"
 -- ListenHTTP directive: SetQueryParam "NAME"
     Used with two arguments, sets query parameter NAME to the VALUE.
     If ‘-encode’ is given, VALUE will be percent-encoded prior to being
     assigned to the parameter.  Otherwise, it will be assigned
     verbatim.  The ‘-encode’ option is allowed before NAME argument as
     well.

     Used with one argument, deletes the parameter NAME.

 -- ListenHTTP directive: SetHeader "NAME: VALUE"
 -- ListenHTTP directive: HeaderAdd "NAME: VALUE"
 -- ListenHTTP directive: AddHeader "NAME: VALUE"
     Sets the HTTP header.  If the header NAME already exists, it will
     be overwritten.  Otherwise, new header will be added to the end of
     the header list.

     The ‘HeaderAdd’ and ‘AddHeader’ forms are retained for backward
     compatibility with earlier ‘pound’ versions.  You are advised
     against using them.

 -- ListenHTTP directive: DeleteHeader [OPTIONS] "PATTERN"
     Remove from the request all headers matching PATTERN.  The
     ‘HeaderRemove’ and ‘HeadRemove’ forms are retained for backward
     compatibility with earlier ‘pound’ versions.  You are advised
     against using them.

     By default, PATTERN is treated as extended POSIX regular
     expression.  The OPTIONS argument can be used to alter this.  It
     consists of zero or more option flags from the following list:

     Flag                   Meaning
                            
     --------------------------------------------------------------------------
     ‘-beg’                 Exact match at the beginning of string (prefix
                            match).
                            
     ‘-case’                Case-sensitive comparison.
                            
     ‘-contain’             Delete each header where "PATTERN" is a
                            substring.
                            
     ‘-end’                 Exact match at the end of string (suffix match).
                            
     ‘-exact’               Use exact string match.
                            
     ‘-icase’               Case-insensitive comparison.
                            
     ‘-pcre’                Use Perl-compatible regular expression.
                            *note Regular Expressions::.
                            
     ‘-perl’                Same as ‘-pcre’.
                            
     ‘-posix’               Use POSIX extended regular expression.
                            *note Regular Expressions::.
                            
     ‘-re’                  Use regular expression match.  This assumes the
                            default regular expression type, as set by the
                            ‘RegexType’ directive
                            (*note Regular Expressions::).

     Table 11.1: Header matching flags for ‘DeleteHeader’ directive

     The following options are mutually exclusive: ‘-beg’, ‘-contain’,
     ‘-end’, ‘-exact’, ‘-pcre’ (‘-perl’), ‘-posix’, ‘-re’.  If more than
     one of these are used, the last one takes effect.

 -- ListenHTTP directive: HeaderRemove "PATTERN"
 -- ListenHTTP directive: HeadRemove "PATTERN"
     These are obsolete keywords, equivalent to

          DeleteHeader -icase "PATTERN"

* Menu:

* Rewrite::


File: pound.info,  Node: Rewrite,  Up: Request Modification

11.9.5.1 The ‘rewrite’ statement
................................

The ‘Rewrite’ block statement associates one or more header modification
directives discussed above with “conditionals”, so that request
modification takes place only when the request matches certain
conditions.

   Syntactically, a ‘Rewrite’ section is:

       Rewrite [ request ]
         CONDITIONAL_DIRECTIVES...
         MODIFICATION_DIRECTIVES...
     [ Else
         CONDITIONAL_DIRECTIVES...
         MODIFICATION_DIRECTIVES... ]
       End

where CONDITIONAL_DIRECTIVES represents one or more “request
conditionals” described below and MODIFICATION_DIRECTIVES stands for one
or more header modification directives.  The ‘Else’ part is optional;
any number of ‘Else’ blocks can be supplied, thus providing for
conditional branching.

   The ‘Rewrite’ statement is processed sequentially until a branch is
found whose CONDITIONAL_DIRECTIVES yield ‘true’, or ‘End’ is
encountered.  If a matching branch is found, its MODIFICATION_DIRECTIVES
are applied to the request.

   “Request matching directives” or “request conditionals” are special
statements that, being applied to a HTTP request, yield ‘true’ or
‘false’ depending on whether the request satisfies the condition
described in the directive.

   All directive described below can read a list of conditions from a
disk file and reload that list upon any changes.  *Note File-based
Conditions::, for a detailed discussion of this feature.

   The following conditionals are available:

 -- Request Conditional: ACL [-forwarded] "NAME"
     Returns ‘true’ if the source IP matches one of the CIDRs from the
     named access control list NAME.  The ACL itself must have been
     defined earlier (*note ACL definition::).

     By default, ‘ACL’ operates on the actual originator IP address.
     This is changed if ‘-forwarded’ is specified, in which case it uses
     an IP determined from the ‘X-Forwarded-For’ (or similar) header
     (*note %a::).

     *Note ACL::, for a detailed discussion.

 -- Request Conditional: ACL [-forwarded]
     This statement defines an unnamed ACL to match the source IP
     against.  This line must be followed by one or more lines defining
     CIDRs, as described in *note ACL definition::.  The ACL definition
     is finished with an ‘End’ keyword on a line by itself.

     The ‘-forwarded’ option instructs ‘pound’ to use source IP address
     determined from the ‘X-Forwarded-For’ header (*note %a::), instead
     of the actual originator IP.

     Semantically, this statement is equivalent to the named ACL
     reference described above.

     *Note ACL::, for a detailed discussion.

 -- Request Conditional: ACL [-forwarded] -file "FILENAME"
 -- Request Conditional: ACL [-forwarded] -filewatch "FILENAME"
     Defines an unnamed ACL to match the source IP against.  The ACL
     definition is read from the file FILENAME, one CIDR per line.
     Empty lines and comments are allowed.  If FILENAME is relative, it
     is looked up in the *note include directory::.  The form with
     ‘-file’ reads the file contents once, at the program startup.  The
     one with ‘-filewatch’ reads it and then monitors that file for
     changes.  *Note File-based Conditions::, for a detailed discussion.

     The meaning of ‘-forwarded’ is as described above.

 -- Request Conditional: BasicAuth [OPTION] "FILENAME"
     Evaluates to ‘true’, if the incoming request passes basic
     authorization as described in RFC 7617.  FILENAME is the name of a
     plain text file containing usernames and passwords, created with
     ‘htpasswd’ or similar utility.  Unless the name starts with a
     slash, it is taken relative to the ‘IncludeDir’ directory (*note
     include directory::).  The file is cached in the memory at startup,
     so that further authorizations do not result in disk operations.
     The file will be reloaded if changed (*note File-based
     Conditions::).

     *Note Authentication::, for a detailed description.

     For consistency with other conditions, ‘BasicAuth’ accepts the
     following options: ‘-file’ and ‘-filewatch’.  The latter enables
     the default behavior and so need not be specified explicitly.  The
     former disables file change monitoring.

     Username from the ‘Authorization: Basic’ header is available in
     expansions via the ‘user’ accessor (*note Request Accessors::).

 -- Request Conditional: Eval "NAME"
     Evaluates the “detached condition” NAME.  The result is cached, so
     that each detached condition is evaluated at most once.  All ‘Eval’
     directives referring to its name will reuse the cached value.
     *Note Detached Conditions::, for a detailed discussion.

 -- Request Conditional: Header [OPTIONS] "PATTERN"
 -- Request Conditional: Header "FIELD" [OPTIONS] "PATTERN"
     Evaluates to ‘true’, if the request contains at least one header
     matching the given PATTERN.  The directive has two forms.  In its
     first form, the PATTERN is compared against entire header line.  In
     its second form, the FIELD argument supplies the header name, and
     PATTERN the pattern to match against its value (or the name of the
     file to read patterns from, if OPTIONS is ‘-file’ or ‘-filewatch’).

     An example of ‘Header’ statement in the first form:

          Header "^Content-Type:[[:space:]]*text/.+"

     Here's the corresponding statement in the second form:

          Header "Content-Type" "text/.+"

     In both forms, PATTERN is treated as case-insensitive POSIX
     extended regular expression.  This can be changed by OPTIONS,
     described below.

     In the first form, pattern modification options, such as ‘-beg’ or
     ‘-contain’ apply to entire header line.  In second form, they apply
     to header value only.  For example, you can write:

          Header "Content-Type" -beg "text/"

     to match a request whose ‘Content-Type’ header _value_ begins with
     ‘text/’, or

          Header -contain "forwarded"

     to match requests that contain any header with the word ‘forwarded’
     anywhere, be it header field name or its value.

 -- Request Conditional: Host [OPTIONS] "HOSTNAME"
     Evaluates to ‘true’, if the ‘Host’ header matches HOSTNAME.  In the
     absence of OPTIONS, case-insensitive exact match is assumed, i.e.
     this construct is equivalent to

          Header "Host" -exact "HOSTNAME"

     *Note conditional-option::, for a detailed discussion of OPTIONS
     and their effect on matching.

     This statement is provided to facilitate handling of “virtual
     hosts”.  *Note Service selection::, for details.

 -- Request Conditional: LuaMatch "FUNC" ["ARG"...]
     Run Lua function FUNC with the supplied arguments.  Use its return
     value (which must be boolean) as the result of the test.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaMatch::, for a detailed discussion.

 -- Request Conditional: Path [OPTIONS] "PATTERN"
     Returns ‘true’, if the path part of the incoming request matches
     PATTERN.

 -- Request Conditional: Query [OPTIONS] "PATTERN"
     Returns ‘true’, if the query part of the incoming request matches
     PATTERN.  The argument must be properly percent-encoded, if it
     contains whitespace or other non-printable characters.

     OPTIONS is zero or more conditional options, as discussed in *note
     conditional-option::.

 -- Request Conditional: QueryParam "NAME" [OPTIONS] "PATTERN"
     Returns ‘true’, if query parameter NAME is defined and its value
     matches PATTERN.

     OPTIONS is zero or more conditional options (*note
     conditional-option::), or ‘-decode’, which instructs the program to
     percent-decode the value prior to comparison.

 -- Request Conditional: StringMatch "STRING" [OPTIONS] "PATTERN"
     Expands STRING as described in *note String Expansions:: and
     matches the resulting value against PATTERN.

     *Note conditional-option::, for a detailed discussion of OPTIONS
     and their effect on matching.

 -- Request Conditional: TBF KEY RATE BURST
     Defines a “token bucket filter” condition.  *Note Rate-limiting::,
     for a detailed discussion.  Arguments are:

     KEY
          A string identifying the bucket.  It is subject to
          backreference expansion and request accessor interpretation,
          as described in *note String Expansions::.

     RATE
          Rate limit.  A single decimal number means requests per
          second.  To specify another time unit, follow the number with
          a slash, another number and optional unit specifier (‘s’ for
          seconds, ‘ms’ for milliseconds, and ‘us’ for microseconds).
          Examples:

               1/2s ⇒ "one request per two seconds"
               200/500ms ⇒ "200 requests per 500 milliseconds"

     BURST
          Burst value, i.e.  maximum number of tokens the bucket can
          contain.

 -- Request Conditional: URL [OPTIONS] "PATTERN"
     Matches URL of the request.  PATTERN is treated as case-sensitive
     extended regular expression, unless instructed otherwise by OPTIONS
     (see below).

   In these directives, OPTIONS is a whitespace-delimited list of zero
or more options discussed below:

 -- Conditional option: -beg
     Exact match at the beginning of string (prefix match).

 -- Conditional option: -case
     Case-sensitive comparison.

 -- Conditional option: -contain
     Match if PATTERN is a substring of the original value.

 -- Conditional option: -end
     Exact match at the end of string (suffix match).

 -- Conditional option: -exact
     Exact string match.

 -- Conditional option: -file
     Treat PATTERN as the name of a file to read patterns from.  If the
     name is relative, it will be looked up in the *note include
     directory::.  Patterns are read from the file line by line.
     Leading and trailing whitespace is removed.  Empty lines and
     comments (lines starting with ‘#’) are ignored.

 -- Conditional option: -filewatch
     Same as ‘-file’, but the file will be monitored for changes and
     reloaded as soon as such are detected.  *Note File-based
     Conditions::, for a detailed description.

 -- Conditional option: -icase
     Case-insensitive comparison.

 -- Conditional option: -pcre
 -- Conditional option: -perl
     Use Perl-compatible regular expression.  *Note Regular
     Expressions::.

 -- Conditional option: -posix
     Use POSIX extended regular expression.  *Note Regular
     Expressions::.

 -- Conditional option: -re
     Use regular expression match.  This assumes the default regular
     expression type, as set by the ‘RegexType’ directive (*note Regular
     Expressions::).

 -- Conditional option: -tag "T"
     Tag this conditional with string T.  The tag can be used by another
     statements to refer to substrings obtained when matching this
     pattern.

     For example:

          Host -tag host -re "(www\\.)?(example.(org|com))"
          Header "Content-Type" -tag "type" -re -icase "^application/(.+)"
          Path -tag "path" -re "/public/(.+)"
          SetPath "$3(host)/$1(type)$1(path)"

     *Note Backreference Expansion::, for a detailed discussion of how
     backreferences are expanded in strings.

   The following options are mutually exclusive: ‘-beg’, ‘-contain’,
‘-end’, ‘-exact’, ‘-pcre’ (‘-perl’), ‘-posix’, ‘-re’.  If more than one
of these are used, the last one takes effect.

   Placing the keyword ‘Not’ before a header matching directive reverts
its meaning.  For example, the following will match any request whose
URL does not begin with ‘/static/’:

     Not URL -beg "/static/"

   The ‘Match’ block statement can be used to join multiple conditional
statements.  Its syntax is:

     Match OP
       ...
     End

where ... stands for any number of conditionals, and OP is a boolean
operation: ‘AND’ or ‘OR’ (case-insensitive).  For example, the statement

     Match OR
       Host "www.example.net"
       Path -beg "/ssl"
     End

will match if the request ‘Host’ header has the value ‘www.example.net’,
or the path part of its URL starts with ‘/ssl’.  In contrast, the
statement below:

     Match AND
       Host "www.example.net"
       Path -beg "/ssl"
     End

will match only if both these conditions are met.  As a syntactical
short-cut, two or more conditionals appearing outside of ‘Match’ are
joined by an implicit logical ‘AND’, so that the latter example is
equivalent to:

     Host "www.example.net"
     Path -beg "/ssl"

   The ‘Match’ statement, like any other conditional, can be prefixed
with ‘Not’, which reverts its meaning.


File: pound.info,  Node: Response Modification,  Next: Error response rewriting,  Prev: Request Modification,  Up: ListenHTTP

11.9.6 Response Modification
----------------------------

 -- ListenHTTP directive: RewriteLocation N
     This statement controls whether ‘Location:’ and ‘Content-location:’
     headers in HTTP responses are modified before sending them back to
     the client.

     If N is 0, both headers are left intact.

     If N is 1, the headers are changed as follows.  If they point to
     the backend itself or to the listener (but with the wrong
     protocol), the request host name will be used instead.  This is the
     default.

     If N is 2, do the same, but compare only the backend address; this
     is useful for redirecting a request to an HTTPS listener on the
     same server as the HTTP listener.

     To check whether the location points to the listener or to the
     backend, its hostname part is resolved and the obtained IP address
     (or addresses) are compared with that of listener or backend.  This
     process is affected by the ‘dns’ feature setting (*note dns::).  If
     it is disabled (‘-W no-dns’ option is given), no resolving takes
     place.  In this case the location is deemed to point to the
     listener if its hostname part matches that of the incoming request.
     For backends, the hostname is compared with the value of the
     ‘ServerName’ setting of that backend (*note ServerName::), if any.

* Menu:

* rewrite response::


File: pound.info,  Node: rewrite response,  Up: Response Modification

11.9.6.1 The ‘Rewrite response’ statement.
..........................................

A special form of the ‘Rewrite’ statement is provided for modifying
headers in the response obtained from a regular backend or generated
with a ‘Error’ backend, before sending them back to the requesting
server:

       Rewrite response
         CONDITIONAL_DIRECTIVES...
         MODIFICATION_DIRECTIVES...
     [ Else
         CONDITIONAL_DIRECTIVES...
         MODIFICATION_DIRECTIVES... ]
       End

   The conditional directives allowed for use in this statement are:

 -- Rewrite response conditional: Eval "NAME"
     Evaluates the “detached condition” NAME.  The result is cached, so
     that each detached condition is evaluated at most once.  All ‘Eval’
     directives referring to its name will reuse the cached value.
     *Note Detached Conditions::, for a detailed discussion.

 -- Rewrite response conditional: Header [OPTIONS] "PATTERN"
     Returns ‘true’, if the response contains at least one header
     matching the given PATTERN.

 -- Rewrite response conditional: LuaMatch "FUNC" ["ARG"...]
     Run Lua function FUNC with the supplied arguments.  Use its return
     value (which must be boolean) as the result of the test.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaMatch::, for a detailed discussion.

 -- Rewrite response conditional: StringMatch "STRING" [OPTIONS]
          "PATTERN"
     Expands STRING as described in *note String Expansions::, and
     matches the resulting value against PATTERN.

     *Note conditional-option::, for a detailed discussion of OPTIONS
     and their effect on matching.

   Both conditionals treat their PATTERN argument as case-insensitive
POSIX extended regular expression.  *Note conditional-option::, for a
discussion of available OPTIONS.

   The following “response modification” directives are defined:

 -- Response modification: DeleteHeader [OPTIONS] "PATTERN"
     Remove matching headers from the response.  By default, PATTERN is
     treated as extended POSIX regular expression.  Use OPTIONS to alter
     this behavior.  *Note Table 11.1: deleteheader-option, for a list
     of available options.

 -- Response modification: LuaModify "FUNC" ["ARG"...]
     Run Lua function FUNC with supplied arguments.  The function is
     supposed to modify the response.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaModify::, for a detailed discussion.

 -- Response modification: SetHeader "NAME: VALUE"
     Sets the HTTP response header.  Argument undergoes string expansion
     (*Note String Expansions::).  If the header NAME already exists, it
     will be overwritten.  Otherwise, new header will be added to the
     end of the header list.


File: pound.info,  Node: Error response rewriting,  Next: Listener constants,  Prev: Response Modification,  Up: ListenHTTP

11.9.7 Rewriting error responses
--------------------------------

When a regular backend responds with an error, the content (body) of
that response can be replaced with an arbitrary custom page.  For this
to work, the following conditions should be met:

  1. Response status code is one of error codes that ‘pound’ itself can
     return.  These are listed in *note Error definitions::.
  2. A custom error page is defined for that status code using the
     ‘ErrorFile’ statement.
  3. Error response rewriting is explicitly enabled for the service that
     contains the backend from which the response is obtained, or for
     the listener where that service is located.  To do so use the
     following statement:

 -- ListenHTTP directive: RewriteErrors BOOL
     Enables or disables error response rewriting for that listener.

     The same statement is available for use within a service (see
     below).  The ‘RewriteErrors’ setting of a service overrides that of
     the listener.


File: pound.info,  Node: Listener constants,  Next: Service definitions,  Prev: Error response rewriting,  Up: ListenHTTP

11.9.8 Listener constants
-------------------------

The ‘Constant’ statement, as described in *note Constant::, can appear
in ‘ListenHTTP’ as well.  If ‘Constant’ in listener defines the same
NAME as was defined previously at the top level, the new definition
overrides the top-level one for all services defined in that listener.


File: pound.info,  Node: Service definitions,  Prev: Listener constants,  Up: ListenHTTP

11.9.9 Service definitions
--------------------------

The ‘Service’ section defines rules that decide to which backend to
route requests received by that listener.  Any number of ‘Service’
sections can be present.  When a request is received, the listener
iterates over all services in the order of their appearance in the
configuration and applies the section rules to the request.  If the
rules match the request, the request is forwarded to the backend defined
in that section.

   *Note Service::, for a detailed discussion of the ‘Service’
statement.

 -- ListenHTTP statement: ACME DIR
     This statement defines a special service with a built-in backend
     for handling ‘ACME’ challenge requests.  *Note ACME::, for a
     detailed discussion of its use.

     The DIR argument defines the directory where to look for challenge
     files.


File: pound.info,  Node: ListenHTTPS,  Next: Tunnel,  Prev: ListenHTTP,  Up: Configuration

11.10 ListenHTTPS
=================

The ‘ListenHTTPS’ section defines a listener that operates in HTTPS. The
section declaration begins with the keyword ‘ListenHTTPS’ optionally
followed by a string supplying symbolic name for that listener:

     ListenHTTPS "main"
       ...
     End

   The purpose of the symbolic name is the same as in ‘ListenHTTP’
statement.  All keywords defined for ‘ListenHTTP’ can be used for
‘ListenHTTPS’ as well.  *Note ListenHTTP::, for a detailed discussion of
these.

   Statements specific for this section are:

 -- ListenHTTPS: Cert "FILENAME"
     Specifies the server “certificate”.  FILENAME is either a
     certificate file name, or the name of a directory containing
     certificate files.

     A “certificate file” is a file containing the certificate, possibly
     a certificate chain and the signature for this server, in that
     order.

     This directive is mandatory within ‘ListenHTTPS’.

     Multiple ‘Cert’ directives are allowed.  If multiple directives are
     used, the first one is the default certificate, with additional
     certificates used if the client requests them.

     The ordering of the directives is important: the first certificate
     where the CN matches the client request will be used, so put your
     directives in the most-specific-to-least specific order (i.e.
     wildcard certificates after host-specific certificates).

     ‘Cert’ directives must precede all other SSL-specific directives.

 -- ListenHTTPS: ClientCert MODE DEPTH
     Specifies whether the listener must ask for the client's HTTPS
     certificate.  Allowed values for MODE are:

       0. Never ask for the certificate (the default).
       1. Ask for the client certificate.  It is OK if the client
          doesn't present it.
       2. Ask for the client certificate.  Fail if the client doesn't
          present it.
       3. Ask for the client certificate, but don't verify it.

     DEPTH is the depth of verification for a client certificate (up to
     9).  The default depth limit is 9, allowing for the peer
     certificate and additional 9 CA certificates that must be verified.

 -- ListenHTTPS: Disable PROTO
     Disable the SSL protocol PROTO and all lower protocols as well.
     Allowed values for PROTO are: ‘SSLv2’, ‘SSLv3’, ‘TLSv1’, ‘TLSv1_1’,
     ‘TLSv1_2’.

     For example:

          Disable TLSv1

     This disables SSLv2, SSLv3 and TLSv1, thus allowing only TLSv1_1
     and TLSv1_2.

 -- ListenHTTPS: Ciphers [TYPEOPT] "CIPHERS" ...
     Defines the list of ciphers (for TLSv2 and below) or ciphersuites
     (for TLSv3) that will be accepted by the SSL connection.  The
     TYPEOPT option defines how to interpret the CIPHERS argument that
     follows it:

     ‘-cipherlist’
          Sets the list of ciphers that affects only TLSv2 and prior
          protocols.  The syntax is the same as in ‘OpenSSL’ ‘ciphers’
          and ‘SSL_CTX_set_cipher_list’ functions.  *Note
          (ciphers(1))ciphers::, for a detailed discussion.

     ‘-ciphersuites’
          Sets the list of TLSv3 “ciphersuites”.  This list will be
          combined with any TLSv1.2 and below cipher lists that may have
          been configured.

          The format for CIPHERS is a simple colon separated list of
          TLSv1.3 ciphersuite names from the list below:

             • ‘TLS_AES_128_CCM_8_SHA256’
             • ‘TLS_AES_128_CCM_SHA256’
             • ‘TLS_AES_128_GCM_SHA256’
             • ‘TLS_AES_256_GCM_SHA384’
             • ‘TLS_CHACHA20_POLY1305_SHA256’

     If TYPEOPT is not supplied, ‘-cipherlist’ is assumed.

     Notice, that a single ‘Ciphers’ statement can set both TLSv2 and
     TLSv3 ciphersuites, e.g.:

          Ciphers "HIGH:@STRENGTH:!RSA" -ciphersuites "TLS_AES_256_GCM_SHA384"

 -- ListenHTTPS: SSLHonorCipherOrder BOOL
     If set ‘true’, the server will broadcast a preference to use
     ciphers in the order supplied in the ‘Ciphers’ directive.  If the
     value is ‘false’, the server will accept any cipher from the
     ‘Ciphers’ list.  Default value is ‘false’.

 -- ListenHTTPS: SSLAllowClientRenegotiation MODE
     If MODE is 0, client initiated renegotiation will be disabled.
     This will mitigate DoS exploits based on client renegotiation,
     regardless of the patch status of clients and servers related to
     “Secure renegotiation”.  If MODE is 1, secure renegotiation is
     supported.  If MODE value is 2, insecure renegotiation is
     supported.

     The default value is 0.

 -- ListenHTTPS: CAlist "FILENAME"
     Set the list of trusted CA's for this server.  The FILENAME is the
     name of a file containing a sequence of CA certificates (in PEM
     format).  The names of the defined CA certificates will be sent to
     the client on connection.

 -- ListenHTTPS: VerifyList "FILENAME"
     Set the certificate authority list.  The FILENAME is the name of a
     file with CA root certificates, in PEM format.

   _Please note_, that there is an important difference between the
‘CAlist’ and the ‘VerifyList’.  The ‘CAlist’ tells the client (browser)
which client certificates it should send.  The ‘VerifyList’ defines
which CAs are actually used for the verification of the returned
certificate.

 -- ListenHTTPS: CRLlist "FILENAME"
     Set the “Certificate Revocation List” file.  FILENAME is the name
     of a file that contains the CRLs (in PEM format).

 -- ListenHTTPS: NoHTTPS11 MODE
     Behave like an ‘HTTP/1.0’ server for HTTPS clients.  If MODE is 0,
     always conform to HTTPS/1.1.  If it is 1, do not allow multiple
     requests on SSL connections.  If the value is 2 (default), disable
     multiple requests on SSL connections only for MSIE clients.


File: pound.info,  Node: Tunnel,  Next: Service,  Prev: ListenHTTPS,  Up: Configuration

11.11 Tunnel
============

The ‘Tunnel’ statement defines a direct communication channel between
two network sockets.  This is described in detail in *note Tunnel::.

 -- Tunnel: Address ADDRESS
     The IP address that ‘pound’ will listen on.  This can be a numeric
     IPv4 or IPv6 address, or a full pathname of a UNIX socket.  To
     listen on all available interfaces, use ‘0.0.0.0’ (for IPv4), or
     ‘::0’ (for both IPv4 and IPv6).

     If neither ‘Address’ or ‘SocketFrom’ are supplied, ‘::0’ is
     assumed.

 -- Tunnel: Port N
     The port number or service name (as per ‘/etc/services’) that this
     listener will listen on.

 -- Tunnel: SocketFrom "PATHNAME"
     Read the socket to listen on from the UNIX socket supplied by
     PATHNAME.  If this parameter is supplied, neither ‘Address’ nor
     ‘Port’ may be used.  This parameter is intended for use in ‘pound’
     testsuite.

 -- Tunnel: Backend ... End
     Defines a “backend”, i.e.  the network socket to connect to the
     tunnel listener.  Exactly one ‘Backend’ statement must be present
     in the ‘Tunnel’ section.

     This is a simplified version of the statement described in *note
     Backend::.  The following statements can be used in it:

      -- Tunnel backend: Address IP
          IP address or host name of the backend server.  If the name
          cannot be resolved to a valid address, ‘pound’ will assume
          that it represents a path to a Unix-domain socket.

          This statement is mandatory.

      -- Tunnel backend: Port N
          Port number to connect to.

      -- Tunnel backend: TimeOut
          Sets the “response timeout”, i.e.  time to wait for a response
          from the backend (in seconds).  Default is 15.

      -- Tunnel backend: ConnTO
          Sets “connection timeout”, i.e.  time to wait for establishing
          connection with the backend (in seconds).

      -- Tunnel backend: Disabled
          Mark the backend as disabled.


File: pound.info,  Node: Service,  Next: resolver,  Prev: Tunnel,  Up: Configuration

11.12 Service
=============

The ‘Service’ statements define backends to use and conditions a request
should satisfy in order to be routed to these backends.  These
statements can appear both within ‘ListenHTTP’ (‘ListenHTTPS’) sections
and outside of them.  When processing an incoming request, the listener
will first try to match it against services defined within it.  If none
of these services matches the request, it will try to match it against
services defined in the top level.  If a matching service is found, it
will be used to process the request.  Otherwise a 503 (“Service
Unavailable”) response will be returned.

   A service is defined by a section statement that begins with the
‘Section’ keyword, followed by service definition statements and
terminated by ‘End’ on a line by itself:

     Service "NAME"
       ...
     End

   Optional NAME argument assigns a symbolic name to the service.  That
name is used to identify the service in diagnostic and access log
messages (*note ‘%{OBJ}N’: log format.), metric output (*note
Metrics::), and in ‘poundctl’ requests (*note poundctl::).  In the
absence of an assigned NAME, the ordinal number of the service in the
enclosing section is used as its identifier.  Service numbers start at
0.

   Following subsections discuss statements that can be used in
‘Service’ sections.

* Menu:

* Service Selection Statements::
* Service Request and Response Modification::
* Service Logging::
* Backends::
* Session::
* Other Statements::


File: pound.info,  Node: Service Selection Statements,  Next: Service Request and Response Modification,  Up: Service

11.12.1 Service Selection Statements
------------------------------------

Service selection statements define conditions an incoming request must
satisfy in order to be handled by this service.

 -- Service Conditional: ACL "NAME"
     Returns ‘true’ if the source IP of the request matches one of the
     CIDRs from the named access control list NAME.  The ACL itself must
     have been defined earlier (*note ACL definition::).

     *Note ACL::, for a detailed discussion.

 -- Service Conditional: ACL -file "FILENAME"
 -- Service Conditional: ACL -filewatch "FILENAME"
     Reads ACL definitions from the file FILENAME.  The file shall
     contain unquoted CIDR definitions, each one on a separate line.
     Empty lines and comments (starting with ‘#’ and ending at the
     nearest newline) are ignored.

     If the ‘-filewatch’ option is used, the file will be monitored and
     reloaded automatically as soon as it changes.  *Note File-based
     Conditions::, for a detailed discussion.

 -- Service Conditional: ACL
     This statement defines an unnamed ACL to match the source IP
     against.  This line must be followed by one or more lines defining
     CIDRs, as described in *note ACL definition::.  The ACL definition
     is finished with an ‘End’ keyword on a line by itself.

     Semantically, this statement is equivalent to the named ACL
     reference described above.

     *Note ACL::, for a detailed discussion.

 -- Service Conditional: BasicAuth [OPTION] "FILENAME"
     Evaluates to ‘true’, if the incoming request passes basic
     authorization as described in RFC 7617.  FILENAME is the name of a
     plain text file containing usernames and passwords, created with
     ‘htpasswd’ or similar utility.  Unless the name starts with a
     slash, it is taken relative to the ‘IncludeDir’ directory (*note
     include directory::).  The file is cached in the memory at startup,
     so that further authorizations do not result in disk operations.
     The file will be rescanned upon any change.  *Note File-based
     Conditions::, for a detailed description of this feature.

     *Note Authentication::, for a detailed description.

     For consistency with other conditions, ‘BasicAuth’ accepts the
     following options: ‘-file’ and ‘-filewatch’.  The latter enables
     the default behavior and so need not be specified explicitly.  The
     former disables file change monitoring.

 -- Service Conditional: ClientCert "FILENAME"
     Evaluates to ‘true’ if the client presents the certificate matching
     that from the file FILENAME (PEM format).

     This conditional cannot be used in standalone services (i.e.
     services that are defined in global scope).  It also cannot be used
     if the ‘ListenHTTPS’ section that hosts the service has the
     ‘ClientCert’ statement on its own.

 -- Service Conditional: Eval "NAME"
     Evaluates the “detached condition” NAME.  The result is cached, so
     that each detached condition is evaluated at most once.  All ‘Eval’
     directives referring to its name will reuse the cached value.
     *Note Detached Conditions::, for a detailed discussion.

 -- Service Conditional: Header [OPTIONS] "PATTERN"
     Evaluates to ‘true’, if the request contains at least one header
     matching the given PATTERN.  By default, PATTERN is treated as
     case-insensitive POSIX extended regular expression.  This can be
     changed by OPTIONS, described below.

 -- Request Conditional: Header "FIELD" [OPTIONS] "PATTERN"
     A “split form” of the ‘Header’ statement above.  It evaluates to
     ‘true’ if the request contains a header whose field name is equal
     to FIELD (case-insensitive) and value matches PATTERN.  The latter
     is treated as case-insensitive POSIX extended regular expression.
     Use OPTIONS (described below) to modify that.

 -- Service Conditional: Host [OPTIONS] "HOSTNAME"
     Evaluates to ‘true’, if the ‘Host’ header matches HOSTNAME.  In the
     absence of OPTIONS, case-insensitive exact match is assumed, i.e.
     this construct is equivalent to

          Header "Host:[[:space:]]*QHOST"

     where QHOST is the HOSTNAME argument in quoted form, i.e.  with all
     characters that have special meaning in regular expressions
     escaped.

     *Note conditional-option::, for a detailed discussion of OPTIONS
     and their effect on matching.

     This statement is provided to facilitate handling of “virtual
     hosts”.  *Note Service selection::, for details.

 -- Service Conditional: LuaMatch "FUNC" ["ARG"...]
     Run Lua function FUNC with the supplied arguments.  Use its return
     value (which must be boolean) as the result of the test.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaMatch::, for a detailed discussion.

 -- Service Conditional: Method [OPTIONS] "PATTERN"
     Returns ‘true’, if the request method matches PATTERN.

 -- Service Conditional: Path [OPTIONS] "PATTERN"
     Returns ‘true’, if the path part of the incoming request matches
     PATTERN.

 -- Service Conditional: Query [OPTIONS] "PATTERN"
     Returns ‘true’, if the query part of the incoming request matches
     PATTERN.  The argument must be properly percent-encoded, if it
     contains whitespace or other non-printable characters.

     *Note conditional-option::, for a detailed discussion of OPTIONS
     and their effect on matching.

 -- Service Conditional: QueryParam "NAME" [OPTIONS] "PATTERN"
     Returns ‘true’, if the value of the query parameter NAME matches
     PATTERN.

     OPTIONS is zero or more conditional options (*note
     conditional-option::), or ‘-decode’, which instructs the program to
     percent-decode the value prior to comparison.

 -- Service Conditional: StringMatch "STRING" [OPTIONS] "PATTERN"
     Expands STRING as described in *note String Expansions::, and
     matches the resulting value against PATTERN.

     *Note conditional-option::, for a detailed discussion of OPTIONS
     and their effect on matching.

 -- Service Conditional: URL [OPTIONS] "PATTERN"
     Matches URL of the request.  PATTERN is treated as case-sensitive
     extended regular expression, unless instructed otherwise by OPTIONS
     (see below).

   The OPTIONS argument in the directives discussed above defines the
comparison algorithm used.  It consists of one or more flags described
in *note conditional-option::.

   Placing the keyword ‘Not’ before a header matching directive reverts
its meaning.  For example, the following will match any request whose
URL does not begin with ‘/static/’:

     Not URL -beg "/static/"

   The ‘Match’ block statement can be used to join multiple header
matching directives.  Its syntax is:

     Match OP
       ...
     End

where ... stands for any number of conditionals, and OP is a boolean
operation: ‘AND’ or ‘OR’ (case-insensitive).  *Note Match in service
statement::, for a detailed discussion with examples.


File: pound.info,  Node: Service Request and Response Modification,  Next: Service Logging,  Prev: Service Selection Statements,  Up: Service

11.12.2 Request and Response Modification
-----------------------------------------

These statements modify incoming requests prior to passing them to the
backend.  A similar set of statements can be used in listeners (*note
Request Modification::).  In case both the listener and service contain
request modification statements, those from the listener are applied
first, followed by the ones from the service.

 -- Service directive: ContentCapture SIZE
     Instructs the service to capture at most SIZE bytes of the incoming
     request while sending it over to the backend.  The captured request
     can be used by Lua functions as ‘http.req.body’ (*note
     http.req.body: lua-http.).

 -- Service directive: SetURL "URL"
     Set the URL of the incoming request to URL.

 -- Service directive: SetPath [-encode] "VALUE"
     Set the path part of the URL to the given string.  If ‘-encode’
     option is given, the value will be percent-encoded prior to setting
     it.

 -- Service directive: SetQuery "VALUE"
     Set the query part of the URL to the given string.  VALUE must be a
     valid query with the special characters properly encoded using
     percent encoding.

 -- Service directive: DeleteQuery
     Delete query part of the URL.

 -- Service directive: SetQueryParam "NAME" [-encode] ["VALUE"]
     Used with two arguments, sets query parameter NAME to the VALUE.
     If ‘-encode’ is given, VALUE will be percent-encoded prior to being
     assigned to the parameter.  Otherwise, it will be assigned
     verbatim.  The ‘-encode’ option is allowed after NAME argument as
     well.

     Used with one argument, deletes the parameter NAME.  characters.

     Used with one argument, deletes the parameter NAME.

 -- Service directive: SetHeader "NAME: VALUE"
 -- Service directive: HeaderAdd "NAME: VALUE"
 -- Service directive: AddHeader "NAME: VALUE"
     Sets the HTTP header.  If the header NAME already exists, it will
     be overwritten.  Otherwise, new header will be added to the end of
     the header list.

     The ‘HeaderAdd’ and ‘AddHeader’ forms are retained for backward
     compatibility with earlier ‘pound’ versions.  You are advised
     against using them.

 -- Service directive: DeleteHeader [OPTIONS] "PATTERN"
 -- Service directive: HeaderRemove [OPTIONS] "PATTERN"
 -- Service directive: HeadRemove [OPTIONS] "PATTERN"
     Remove from the request all headers matching PATTERN.  The
     ‘HeaderRemove’ and ‘HeadRemove’ forms are retained for backward
     compatibility with earlier ‘pound’ versions.  You are advised
     against using them.

     By default, PATTERN is treated as extended POSIX regular
     expression.  The OPTIONS argument can be used to alter this.  It
     consists of zero or more option flags, described in *note Table
     11.1: deleteheader-option.

 -- Service Statement: LuaModify "FUNC" ["ARG"...]
     Run Lua function FUNC with supplied arguments.  The function is
     supposed to modify the request.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaModify::, for a detailed discussion.

 -- Service statement: Rewrite [ request | response ] ... End
     This block statement associates one or more header modification
     directives discussed above with “conditionals”, so that request
     modification takes place only when the request matches certain
     conditions.

     By default ‘Rewrite’ statements apply to incoming requests.  The
     subject of rewriting can also be specified explicitly after the
     ‘Rewrite’ keyword.

     *Note Rewrite::, for a detailed discussion of this statement.

     *Note Conditional branches::, for an in-depth discussion with
     examples.

     *Note Modifying responses::, for a discussion of the use of this
     statement to modify responses.

 -- Service directive: RewriteErrors BOOL
     Enables or disables error response rewriting for that service.
     *Note Error response rewriting::, for a detailed discussion.


File: pound.info,  Node: Service Logging,  Next: Backends,  Prev: Service Request and Response Modification,  Up: Service

11.12.3 Service Logging
-----------------------

 -- Service directive: ForwardedHeader "NAME"
     Defines the name of the HTTP header that carries the list of
     proxies the request has passed through.  Default value is
     ‘X-Forwarded-For’.  This header is used to determine the originator
     IP address for logging.  *Note %a::, for details.

 -- Service directive: TrustedIP
     Defines a list of “trusted proxy” IP addresses, which is used to
     determine the originator IP.

     *Note %a::, for a detailed discussion.

     This statement is a special form of ‘ACL’ statement, described in
     *note ACL::.  It can appear in three forms: “anonymous ACL”, “file
     reference”, or “ACL reference”.  Examples:

       1.      TrustedIP
                 "127.0.0.1/8"
                 "10.16.0.0/16"
               End
       2.      TrustedIP -filewatch "/etc/pound/trustip.acl"
       3.      TrustedIP "proxy_addresses"

 -- Service directive: LogSuppress CLASS [CLASS...]
     Suppresses HTTP logging for requests that resulted in status codes
     from the specified classes.  Valid classes are:

     info
     1
          ‘1xx’ response codes.

     success
     2
          ‘2xx’ response codes.

     redirect
     3
          ‘3xx’ response codes.

     clterr
     4
          ‘4xx’ response codes.

     srverr
     5
          ‘5xx’ response codes.

     all
          All response codes.

     This statement is designed for services that receive a constant
     stream of similar HTTP requests from a controlled set of IP
     addresses, such as e.g.  Openmetric services.  *Note Metrics::, for
     an example.


File: pound.info,  Node: Backends,  Next: Session,  Prev: Service Logging,  Up: Service

11.12.4 Backends
----------------

* Menu:

* Backend::
* UseBackend::
* Special Backends::


File: pound.info,  Node: Backend,  Next: UseBackend,  Up: Backends

11.12.4.1 Backend
.................

The ‘Backend’ section defines a regular backend.  The overall syntax, as
for any section statement, is:

     Backend [ "NAME" ]
       ...
     End

   Optional NAME argument assigns a symbolic name to the service.  That
name is used to identify the backend in diagnostic and access log
messages (*note ‘%{OBJ}N’: log format.), metric output (*note
Metrics::), and in ‘poundctl’ requests (*note poundctl::).  In the
absence of an assigned NAME, the ordinal (0-based) number of the backend
in the enclosing ‘Service’ is used as its identifier.

   The following statements can be used in a ‘Backend’ section:

 -- Backend directive: Address IP
     IP address or host name of the backend server.  If the name cannot
     be resolved to a valid address, ‘pound’ will assume that it
     represents a path to a Unix-domain socket.

     This directive is mandatory.

 -- Backend directive: Disabled BOOL
     Mark this backend as disabled.

     Backends can be enabled or disabled at runtime using the ‘poundctl’
     utility (*note enable: poundctl commands.).

     _Note:_ not to be confused with the ‘Disable’ statement, described
     below.

 -- Backend directive: Port N
     Sets the port number to connect to.  This directive must be present
     if the ‘Address’ statement contains an IP address.

 -- Backend directive: Priority N
     Sets numeric priority for this backend.  Priorities are used to
     control probability of receiving a request for handling in case of
     multiple backends.  *Note Balancer::, for a detailed discussion.

     Allowed values for N are 1 to 65535.

   Following directives configure “dynamic backends”.  *note Dynamic
backends::, for a detailed discussion:

 -- Backend directive: Family NAME
     Defines the address family to look for when resolving hostnames:

     ‘any’
          Use all address families available.  This is the default.

     ‘inet’
          Use only IPv4 addresses.

     ‘inet6’
          Use only IPv6 addresses.

 -- Backend directive: IgnoreSRVWeight BOOL
     When using ‘SRV’ records, ignore their weight fields.  Instead,
     copy priority of the producing backend to generated backends.

     This directive is valid when used together with ‘Resolve srv’ (see
     below).

 -- Backend directive: OverrideTTL N
     This directive configures update interval (in seconds) for dynamic
     backends (*note Dynamic backends::).  At the end of each update
     interval, the DNS be queried and dynamic backends reconfigured (if
     needed) according to its responses.  By default, the TTL value
     obtained from previous DNS response is used.

     To configure the interval to retry failed DNS lookups, see
     ‘RetryInterval’, below.

 -- Backend directive: Resolve TYPE
     Declares a dynamic backend.  Valid values for TYPE are

     ‘first’
          Resolve the symbolic host name and use first IP from the DNS
          response as the address of the created dynamic backend.  Thus,
          this type will produce at most one dynamic backend.

     ‘all’
          Resolve the symbolic host name and create one backend for each
          address from the DNS response.  This enables load balancing
          between created backends.  Each backend will be assigned the
          same priority.

     ‘srv’
          Obtain ‘SRV’ records for the host name and use them to
          generate dynamic backends.  Each record produces new dynamic
          backend of ‘Resolve all’ type, which creates regular backends
          as described above.  The weight field of the ‘SRV’ record is
          mapped to the priority field of each generated backend.  The
          priority field determines the balancer group where the backend
          will be hosted.

 -- Backend directive: RetryInterval N
     Retry failed DNS lookups in N seconds.  Default is 600.

     See also the ‘RetryInterval’ statement in ‘Resolver’ section (*note
     resolver::).

   The following three directives set various timeout parameters for
backend operations:

 -- Backend directive: ConnTO N
     Sets “connection timeout”, i.e.  time to wait for establishing
     connection with the backend (in seconds).

 -- Backend directive: TimeOut N
     Sets the “response timeout”, i.e.  time to wait for a response from
     the backend (in seconds).  Default is 15.

 -- Backend directive: WSTimeOut N
     Idle timeout for WebSocket operations, in seconds.  Default value:
     600 (10 minutes).

   Backend servers can use HTTPS as well as plaintext HTTP. The
following directives configure HTTPS backends:

 -- Backend directive: HTTPS
     This directive indicates that the remote server speaks HTTPS.

 -- Backend directive: Cert "FILENAME"
     This specifies the certificate that ‘pound’ will use as a client.
     The FILENAME is the name of a file containing the certificate,
     possibly a certificate chain and the signature.

 -- Backend directive: Ciphers [TYPEOPT] "CIPHERS" ...
     This is the list of ciphers (for TLSv2 and below) or ciphersuites
     (for TLSv3) that will be accepted by the SSL connection with the
     backend (for HTTPS backends).  *Note Ciphers::, for a detailed
     discussion of its arguments.

 -- Backend directive: Disable PROTO
     Disable the SSL protocol PROTO and all earlier protocols.  Allowed
     values for PROTO are: ‘SSLv2’, ‘SSLv3’, ‘TLSv1’, ‘TLSv1_1’,
     ‘TLSv1_2’.

     _Note:_ not to be confused with the ‘Disabled’ statement, described
     above.

 -- Backend directive: ServerName "NAME"
     This directive specifies the name to use for server name
     identification (“SNI”). It also rewrites the ‘Host:’ header for
     this particular backend.  This means you don't have to use
     ‘SetHeader’ in addition to it.


File: pound.info,  Node: UseBackend,  Next: Special Backends,  Prev: Backend,  Up: Backends

11.12.4.2 Globally Defined Backends
...................................

The ‘Backend’ section described above can also be used at the topmost
level of the configuration file.  Use this if you plan to use same
backend in several different services.

   When used globally the ‘Backend’ keyword must always be followed by
the backend name in double-quotes.  The assigned name must be unique
among all global backends.

   To include a globally defined backend in a service, use ‘UseBackend’
or ‘Backend’ keywords.

 -- Service directive: UseBackend "NAME"
     Use globally-defined backend NAME in this service.  The backend
     itself may be defined in global scope before or after the ‘Service’
     section that uses it.

   The ‘UseBackend’ keyword adds the backend to the service exactly as
it was defined.  However, it may sometimes be necessary to alter its
priority and state.  To do so, use the ‘Backend’ section.  If the name
argument specifies a globally-defined backend, the ‘Backend’ section can
contain only the ‘Priority’ and ‘Disable’ statements.


File: pound.info,  Node: Special Backends,  Prev: UseBackend,  Up: Backends

11.12.4.3 Special Backends
..........................

Special backends are backends that don't rely on an external server to
handle the response, but instead are served by ‘pound’ itself.

 -- Service directive: Control
     Defines a special backend that serves “pound management interface”.
     *Note Service Control::, for a detailed discussion of this feature.

 -- Service directive: Emergency ... End
     Defines an “emergency backend”, which will be used only if all
     other backends become unavailable.  *Note Backend::, for a
     discussion of directives that can be used within ‘Emergency’
     section.

     If multiple ‘Emergency’ sections are defined, an emergency backend
     to use will be selected using the usual balancing technique (*note
     Balancer::).

 -- Service directive: Error STATUS [FILE]
     Return a particular HTTP status.

     The STATUS argument supplies the HTTP status code to return.

     Optional FILE argument is the name of a disk file with the error
     page content.  If not supplied, the text is determined as usual:
     first the ‘ErrorFile STATUS’ statement from the enclosing listener
     is consulted.  If it is not present, the default error page is
     used.

     This directive is useful in a catch-all service, which outputs an
     error page if no service matching the incoming request was found.
     *Note Error responses::, for a discussion.

 -- Service directive: LuaBackend "FUNC" ["ARG"...]
     Run Lua function FUNC with the supplied arguments.  The function
     should set the response code (*note http.resp.code::) and fill the
     response body (*note http.resp.body::) prior to returning.  If it
     fails to do so, ‘pound’ will generate a standard 500 response.

     The FUNC can be either an unqualified function name, or function
     name with module qualifier (‘module.func’).

     Each ARG is subject to to backreference expansion and request
     accessor interpretation, as discussed in *note Request
     modifications::.

     This statement is available only if ‘pound’ was built with Lua
     support.  *Note LuaBackend::, for a detailed discussion.

 -- Service directive: Metrics
     This directive defines a special backend that generates Openmetric
     telemetry output on the given URL. Example usage:

          Service
              URL "/metrics"
              Metrics
          End

     To control access to the telemetry endpoint, use the ‘ACL’
     statement (*note ACL::).

     The ‘LogSuppress’ directive (*note LogSuppress::) is often used in
     openmetric services to suppress logging of served HTTP requests:

          Service
              URL "/metrics"
              Metrics
              ACL "secure"
              LogSuppress success
          End

     The metrics output is discussed in *note Metric Families::.

 -- Service directive: Redirect [CODE] "URL"
     Declares a special backend that responds to each request with a
     redirect response.

     Optional CODE can be one of: 301, 302 (the default), 303, 307, or
     308.

     The URL argument specifies the URL to redirect the request to.
     Before use it is expanded as described in *note String
     Expansions::.

     For compatibility with previous ‘pound’ versions, if no ‘$N’
     references are found in URL, the following logic is used: if it is
     a "pure" host (i.e.  with no path) then the client will be
     redirected to that host, with the original request path appended.
     If the URL does contain a path (even if it is just a ‘/’), then the
     request path is ignored.

     *Note Redirects::, for a detailed discussion of this backend and
     its use.

 -- Service directive: SendFile DIR
     Defines a special backend that serves static files from directory
     DIR.  Name of the file to serve is supplied by the request path,
     after applying usual request modifications (*note Request
     Modification::).  By default, the response bears ‘Content-Type:
     text/plain’ header.  To change this, use ‘SetHeader’ statement in
     response rewriting (*note rewrite response::).

     The following example defines a service which will serve requests
     to paths beginning with ‘/about/’ from directory
     ‘/var/lib/pound/static’.  Name of the file to serve is obtained by
     removing the ‘/about/’ prefix from the request pathname.  Content
     type is set to ‘text/html’:

          Service
              Path -re "/about/(.+)"
              SetPath "$1"
              Rewrite response
                   SetHeader "Content-Type: text/html"
              End
              SendFile "/var/lib/pound/static"
          End

     If DIR is not an absolute file name, it is resolved relative to
     ‘pound’ include directory (*note include directory::).

 -- Service directive: Success
     A “Success” backend always returns 200 response code.  It can be
     used for debugging or for side effects, e.g.  to answer ‘OPTIONS’
     requests by supplying response headers using ‘SetHeader’.

          Service
              Method "OPTIONS"
              Rewrite response
                  SetHeader "Access-Control-Allow-Origin: example.com"
                  SetHeader "Access-Control-Allow-Methods: GET,POST,PUT"
                  SetHeader "Access-Control-Max-Age: 1800"
              End
              Success
          End


File: pound.info,  Node: Session,  Next: Other Statements,  Prev: Backends,  Up: Service

11.12.5 Session
---------------

 -- Service directive: Session ... End
     Defines how a service deals with possible HTTP sessions.  Once a
     session is identified, ‘pound’ will attempt to send all requests
     within that session to the same backend server.

     *Note Sessions::, for a detailed discussion of HTTP sessions and
     their handling.

   The following directives are available for use in ‘Session’ section.

 -- Session directive: Type TYPE
     Defines the expected type of sessions to handle.  Allowed values
     for TYPE are:

     ‘IP’
          A session is defined by the source IP. All requests coming
          from the same IP are considered to be in the same session.
          The IP address is defined by the ‘ID’ statement (see below).

     ‘BASIC’
          A session is defined by the ‘Authentication’ HTTP header.  If
          the header is present, and specifies the ‘Basic’
          authentication type, user ID is extracted from it.

     ‘URL’
          A session is identified by the value of a particular query
          parameter.  The name of the parameter is given by the ‘ID’
          statement.

     ‘PARM’
          Sessions are identified by HTTP parameter - a string that
          appears after a semicolon in the URL, such as ‘bar’ in
          ‘http://foo.com;bar’.

     ‘COOKIE’
          Sessions are identified by the value of an HTTP cookie, whose
          name is given by the ‘ID’ directive.

     ‘HEADER’
          Sessions are identified by the value of HTTP header whose name
          is given by the ‘ID’ directive.

 -- Session directive: ID "NAME"
     Specifies the “session identifier”: IP address (for ‘Type IP’),
     query parameter name (for ‘Type URL’), cookie name (for ‘Type
     COOKIE’), or header name (for ‘Type HEADER’).

 -- Session directive: TTL N
     How long can a session be idle (in seconds).  A session that has
     been idle for longer than the specified number of seconds will be
     discarded.  This directive is mandatory.


File: pound.info,  Node: Other Statements,  Prev: Session,  Up: Service

11.12.6 Other Statements
------------------------

 -- Service directive: Constant "NAME" [OPTIONS] ["VAL"]
     Defines a per-service “configuration constant”.  *Note Constant::,
     for a detailed discussion of this statement and its parts, and
     *note Constants::, for examples of its use in configuration.

     Constants defined on service level override those defined in the
     enclosing listener and on the top-level.

 -- Service directive: Disabled BOOL
     If ‘true’, mark this service as disabled.  Disabled services are
     not used for request processing.  A service can be enabled or
     disabled at runtime using the ‘poundctl’ utility (*note enable:
     poundctl commands.).

 -- Service directive: Balancer ALGO
     Sets the request balancing algorithm to use.  Allowed values for
     ALGO are:

     random
          Use weighted random balancing algorithm.

     iwrr
          Use interleaved weighted round robin balancing.

     *Note Balancer::, for a detailed discussion of these algorithms.

     This statement overrides the global ‘Balancer’ statement (*note
     Balancer: Global directives.).

 -- Service directive: IgnoreCase BOOL
     Ignore case when doing regex matching (default: ‘false’).  This
     directive sets the default for the following service matching
     directives: ‘URL’, ‘Path’, ‘QueryParam’, ‘Query’, ‘StringMatch’, as
     well as for the ‘DeleteHeader’ modification directive.

     This statement is deprecated and will be removed in future
     versions.  Please, use the ‘-icase’ option with the conditional
     directive instead (*note conditional-option::).


File: pound.info,  Node: resolver,  Prev: Service,  Up: Configuration

11.13 Resolver
==============

The ‘Resolver’ section controls DNS lookups for dynamic backend
generation (*note Dynamic backends::).  It can contain the following
directives:

 -- Resolver: CNAMEChain N
     Maximum allowed length of a “CNAME chain”.  CNAME chains are formed
     by DNS CNAME records pointing to another CNAME. Although prohibited
     by the RFC, such usage occurs sometimes in the wild.  By default,
     ‘pound’ does not accept CNAME chains.  If you work with nameservers
     that declare such chains, set this statement to a small integer
     value, defining maximum number of CNAME records in the chain that
     ‘pound’ will accept.  The value of 2 or 3 should suffice in most
     cases.

 -- Resolver: ConfigFile FILE
     Read resolver configuration from FILE.  Default is
     ‘/etc/resolv.conf’.

 -- Resolver: ConfigText ... End
     The material within this section is read verbatim and used as the
     content of the resolver configuration file.  E.g.:

          Resolver
                  ConfigText
                          domain example.org
                          nameserver 192.0.2.1
                          nameserver 192.0.2.4
                  End
          End

     If both ‘ConfigFile’ and ‘ConfigText’ are used, the last statement
     used wins.

 -- Resolver: Debug BOOL
     If set to ‘true’, enables DNS debugging info.

 -- Resolver: RetryInterval N
     Interval in seconds, after which to retry failed DNS queries or
     queries that returned no RRs.  This value is used unless the
     backend defines its own retry interval value.


File: pound.info,  Node: poundctl,  Next: Emacs,  Prev: Configuration,  Up: Top

12 poundctl
***********

The ‘poundctl’ command displays status of various objects of the running
instance and allows you to change some of them.

   The program communicates with the running ‘pound’ daemon via a UNIX
socket or remotely, via HTTP or HTTPS. The URL of the communication
socket can be given explicitly by the ‘-s’ command line option, or
obtained from ‘poundctl’ or ‘pound’ configuration files.

   If the ‘.poundctl’ exists in the home directory, the configuration
will be obtained from it.  Otherwise, if ‘poundctl’ runs on the same
machine as the ‘pound’ daemon and communicates with it via the UNIX
socket, the program will scan the ‘pound.cfg’ file for the ‘Control’
statement (*note Control statement::) and read the socket file name from
it.  These ways of configuring ‘poundctl’ are discussed below, in *note
poundctl config::.  In examples below, it is assumed that the socket URL
is obtained from one of configuration files.

   The program invocation syntax is:

     poundctl [OPTIONS] COMMAND OBJECT [ARG]

Here, OPTIONS are command line options, COMMAND is a command verb that
instructs ‘poundctl’ what to do, OBJECT identifies the ‘pound’ object to
operate upon (*note objects::), and optional ARG supplies argument to
the command verb.

   Pound objects identifiers are formed in a path-like fashion:

     /LISTENER/SERVICE/BACKEND

where:

LISTENER
     Symbolic name of the listener or its ordinal number in the
     configuration.  If referring to a globally-defined service, or to a
     backend in such a service, a dash is used.

SERVICE
     Symbolic name or ordinal number of the service located in that
     listener.

BACKEND
     Ordinal number of backend in the service.

   Depending on the command, either ‘/BACKEND’ or both
‘/SERVICE/BACKEND’ may be omitted.

   For example, the following command will disable backend 2 in service
1 of listener 0:

     poundctl disable /0/1/2

   Assuming listener 0 is named ‘web’, this example can also be written
as:

     poundctl disable /web/1/2

   The following command disables the listener 0 itself:

     poundctl disable /0

   A dash in place of LISTENER refers to the global scope.  Thus, the
following disables service 1 defined in the global scope of ‘pound.cfg’:

     poundctl disable /-/1

* Menu:

* poundctl commands::
* poundctl remote::
* poundctl config::
* poundctl options::
* poundctl template::


File: pound.info,  Node: poundctl commands,  Next: poundctl remote,  Up: poundctl

12.1 ‘poundctl’ commands
========================

* Menu:

* poundctl list::    Show information about running instance.
* poundctl enable::  Enabling and disabling ‘pound’ entities.
* poundctl session:: Session management.
* poundctl log::     Inspect and change log level.


File: pound.info,  Node: poundctl list,  Next: poundctl enable,  Up: poundctl commands

12.1.1 Show Information About Running Instance
----------------------------------------------

 -- poundctl: core
     Display core statistics.  By default, it includes: server time,
     ‘pound’ daemon version, uptime, and PID, worker thread, and
     connection queue statistics.

 -- poundctl: list /L/S/B
 -- poundctl: list /L/S
 -- poundctl: list /L
 -- poundctl: list
     Lists status of the given object and its subordinates.  Without
     argument, shows core statistics (see above), all listeners and
     underlying objects, as well as all standalone services.


File: pound.info,  Node: poundctl enable,  Next: poundctl session,  Prev: poundctl list,  Up: poundctl commands

12.1.2 Enabling and Disabling Various ‘pound’ Entities
------------------------------------------------------

 -- poundctl: enable /L/S/B
 -- poundctl: enable /L/S
 -- poundctl: enable /L
 -- poundctl: on /L/S/B
 -- poundctl: on /L/S
 -- poundctl: on /L
     Enables listener, service, or backend.

 -- poundctl: disable /L/S/B
 -- poundctl: disable /L/S
 -- poundctl: disable /L
 -- poundctl: off /L/S/B
 -- poundctl: off /L/S
 -- poundctl: off /L
     Disables listener, service, or backend.


File: pound.info,  Node: poundctl session,  Next: poundctl log,  Prev: poundctl enable,  Up: poundctl commands

12.1.3 Session Management with ‘poundctl’
-----------------------------------------

 -- poundctl: add /L/S/B KEY
     Add a session with the given KEY.

 -- poundctl: delete /L/S KEY
     Delete the session with the given key.  Notice that backend may not
     be specified.


File: pound.info,  Node: poundctl log,  Prev: poundctl session,  Up: poundctl commands

12.1.4 Using ‘poundctl’ to Inspect and Change Log Levels
--------------------------------------------------------

The ‘poundctl log’ command is used to control log level (*note
Logging::) of the running instance of ‘pound’ or any of its listeners.

 -- poundctl: log [/]
 -- poundctl: log [/]L
     Used without arguments (or with ‘/’ as an argument), this command
     displays global log level.  Otherwise, it displays log level for
     listener L.  Notice, that leading slash in the argument is
     optional.

     If the default template is used, the command outputs symbolic name
     of the log level in use (*note log level::).  In the second form,
     if the listener L has no specific log level configured (i.e.  it
     uses the log level from the global settings), the name of the log
     level is followed by the word ‘global’ in parentheses.

 -- poundctl: log / F
 -- poundctl: log [/]L F
     The first form sets global log level F.  The second form,
     configures log level F for listener L.

     In both forms, F must be a symbolic name of an existing format
     (either built-in or user-defined), as described in *note log
     level::.

     On success, the command outputs the name of the configured format
     (F).

 -- poundctl: log -d [/]
 -- poundctl: log -d [/]L
     Deletes current log level setting.

     In the first form, the global log level is set to ‘null’ (*note
     null built-in format::).

     In the second form, it removes the log level setting for the
     listener L, resulting in global log level being used for it.

     The output is as described above.


File: pound.info,  Node: poundctl remote,  Next: poundctl config,  Prev: poundctl commands,  Up: poundctl

12.2 Using ‘poundctl’ for remote access
=======================================

Starting from version 4.14, ‘pound’ is able to provide its management
interface via HTTP (*note Service Control::).  To use remote management
interface, supply its URL with the ‘-s’ command line option.  The URL
syntax is:

     SCHEME://[USER[:PASSWORD]@]HOSTNAME[:PORT][/PATH]

where ‘[]’ denote optional parts.  Valid SCHEME values are ‘http’ and
‘https’.  Use USER and PASSWORD if the interface is protected by basic
authentication (*note Authentication::).

   When using ‘https’ protocol, you may need to supply the “certificate
authority” file using the ‘-C FILE’ option, where FILE is the name of
the file in PEM format.  This option can also take a directory name as
its argument.  In this case all PEM files from that directory will be
loaded.

   To disable peer certificate verification, use the ‘-k’ option.

   If ‘pound’ configuration requires the client to send its certificate
for authentication (*Note ClientCert::, or *note ClientCert
conditional::), use the ‘-K FILE’ option to supply it.  Its argument,
FILE, is the name of the file with the certificate and key in PEM
format.


File: pound.info,  Node: poundctl config,  Next: poundctl options,  Prev: poundctl remote,  Up: poundctl

12.3 Configuring ‘poundctl’
===========================

Upon startup, the program checks if the file ‘.poundctl’ exists in the
user's home directory.  If so, it reads its configuration from it.  The
location of the configuration file can be changed using the environment
variable ‘POUNDCTL_CONF’.  If it is defined and has a non-empty value,
its value is taken as the alternative file name to use.  It can be
either absolute file name, or a file name relative to the home
directory.  Setting ‘POUNDCTL_CONF’ to an empty value disables reading
the configuration.

   If the program cannot determine the socket URL from ‘.poundctl’, it
will attempt to scan ‘pound’ configuration file, on the assumption that
it runs on the same machine as the daemon and that its ‘pound.cfg’ file
contains a ‘Control’ statement (*note Control statement::).  If so, the
socket name is determined from it.

   Otherwise, the control URL has to be given explicitly using the ‘-s’
command line option.

   The ‘.poundctl’ file has the same syntax as ‘pound.cfg’: it is a
sequence of “statements” and “sections”, separated by arbitrary amount
of empty lines and comments.  A “simple statement” occupies a single
line and consists of a keyword (“directive”) and one or more values
separated by whitespace.  A “section” is a compound statement that
encloses other statements and sections.  Sections begin with a keyword,
optionally followed by arguments, and end with a word ‘End’ on a line by
itself.  All keywords are case-insensitive.

   The following keywords are available in the global scope:

 -- poundctl config: URL "URL"
     Sets the URL of the ‘pound’ management socket.  The value is either
     the file name of the UNIX socket file, or a remote URL, as
     described in *note poundctl remote::.

 -- poundctl config: CAFile "FILE"
     Name of the certificate authority file.  See also the ‘-C’ option,
     below.

 -- poundctl config: CAPath "DIR"
     Read certificate authority files from the directory DIR.

 -- poundctl config: ClientCert "FILE"
     Supplies the name of the file with client certificate and private
     key, for client authentication.  See also the ‘-K’ option, below.

 -- poundctl config: Verify BOOL
     Enables or disables peer certificate verification.  The default is
     ‘on’.  See also the ‘-k’ command line option.

 -- poundctl config: TemplateFile "FILE"
     Name of the template file (*note poundctl template::).

 -- poundctl config: TemplatePath "FILE"
     Search path for template files (*note poundctl template::).

 -- poundctl config: TemplateName "NAME"
     Name of the template to use (*note poundctl template::).

* Menu:

* multiple servers::


File: pound.info,  Node: multiple servers,  Up: poundctl config

12.3.1 Multiple Servers Configuration
-------------------------------------

The ‘Server’ section provides a way to organize management of multiple
‘pound’ servers.  The idea is that you define the configuration for each
particular ‘pound’ installation in a separate ‘Server’ section, and then
use the name of that section to identify the server of interest in the
command line, using the ‘-S’ option:

     poundctl -S web list

   The syntax of the ‘Server’ section is:

     Server "NAME"
       ...
     End

where NAME is a unique name assigned to that server.  It will be used as
argument to the ‘-S’ option to identify it.  The ellipsis denotes one or
more of the following statements:

 -- poundctl Server: URL URL
     Sets the URL of the ‘pound’ management socket for that server.  The
     value is either the file name of the UNIX socket file, or a remote
     URL, as described in *note poundctl remote::.

 -- poundctl Server: CAFile FILE
     Name of the certificate authority file.

 -- poundctl Server: CAPath DIR
     Read certificate authority files from the directory DIR.

 -- poundctl Server: ClientCert FILE
     Supplies the name of the file with client certificate and private
     key, for client authentication to that server.

 -- poundctl Server: Verify BOOL
     Enables or disables peer certificate verification.  The default is
     ‘on’.


File: pound.info,  Node: poundctl options,  Next: poundctl template,  Prev: poundctl config,  Up: poundctl

12.4 ‘poundctl’ options
=======================

The following options are understood by ‘poundctl’:

‘-C FILE’
‘-C DIR’
     Read certificate authority files from FILE or from files in DIR.
     *Note poundctl remote::.  This overrides the ‘CAFile’ or ‘CAPath’
     configuration settings (*note poundctl config::).

‘-f FILE’
     Read ‘pound’ configuration from FILE, instead of the default
     configuration file.

‘-i N’
     Sets indentation level for JSON output to N columns.

‘-j’
     Use JSON output format.

‘-K FILE’
     Read client certificate and private key from FILE.  *Note poundctl
     remote::.  This option overrides the ‘ClientCert’ configuration
     setting (*note poundctl config::).

‘-k’
     Disable peer certificate verification.  *Note poundctl remote::.
     This overrides the ‘Verify’ configuration setting (*note poundctl
     config::).

‘-h’
     Shows a short help output and exits.

‘-S NAME’
     Operate on server defined by ‘Section "NAME"’ in the ‘.poundctl’
     file.  *Note multiple servers::, for a detailed discussion.

‘-s SOCKET’
‘-s URL’
     Sets pathname of the control socket, or its URL (for remote access,
     *note poundctl remote::).  This overrides the ‘URL’ configuration
     setting (*note poundctl config::).

‘-T FILE’
     Sets the name of the template file to use.  Overrides the
     ‘TemplateFile’ configuration setting (*note poundctl config::).

‘-t NAME’
     Defines the name of the template to use, instead of the ‘default’.
     This overrides the ‘TemplateName’ configuration setting (*note
     poundctl config::).

‘-V’
     Prints program version, compilation settings, and exits.

‘-v’
     Increases output verbosity level.


File: pound.info,  Node: poundctl template,  Prev: poundctl options,  Up: poundctl

12.5 ‘poundctl’ template
========================

Information received from the ‘pound’ daemon is formatted as a JSON
object.  To produce human-readable output, ‘poundctl’ uses a “template”,
i.e.  a text written in a domain-specific language expressly designed
for that purpose.  The template language complies, in general, with the
specification in <https://pkg.go.dev/text/template>.  *Note Template
syntax::, for a detailed description.

   Templates are stored in template files, which are looked up in the
template search path.  The path is a column-delimited list of
directories or file names.  To locate the template file, the path is
scanned left-to right.  If an element is a regular file name (or a hard
or symbolic link to a regular file), ‘poundctl’ tries to open that file.
If an element is a directory name, the program tries to open the file
‘poundctl.tmpl’ in that directory.  If opening succeeds, further
scanning stops and templates are read from that file.

   The default template path is

     ~/.poundctl.tmpl:DATADIR/pound

where DATADIR stands for the program data directory(1).  That is, the
file ‘.poundctl.tmpl’ in the user home directory is searched first, then
the file ‘poundctl.tmpl’ (without the leading dot) is looked up in the
program data directory.

   The default search path can be changed in the configuration file,
using the ‘TemplatePath’ statement (*note poundctl config::), or by
setting the environment variable ‘POUND_TMPL_PATH’.

   To examine the default value of the search path, use the ‘-V’ command
line option.

   The template file to use can be requested from the command line using
the ‘-t’ option (or ‘TemplateFile’ configuration setting).  In this
case, template search path in not searched and the supplied file is used
verbatim.

   Unless instructed otherwise, ‘poundctl’ uses the template ‘default’.
You can request another template name using the ‘TemplateName’
configuration setting or the ‘-T’ command line option.

   The default ‘poundctl.tmpl’ file defines two templates: ‘default’ and
‘xml’.

* Menu:

* Template syntax::
* Pipelines::
* Variables::
* Input object::

   ---------- Footnotes ----------

   (1) It is determined at compile time.  Normally it is
‘/usr/share/pound’ or ‘/usr/local/share/pound’.


File: pound.info,  Node: Template syntax,  Next: Pipelines,  Up: poundctl template

12.5.1 Template syntax
----------------------

The syntax of ‘poundctl’ templates is modelled after and mostly
conforming to the specifications of the ‘golang’ template module(1).

   Templates are executed by applying them to a JSON object.
Annotations in a template refer to attributes of the object to control
execution and derive values to be displayed.  Execution of the template
walks the structure and sets the cursor, represented by a period (called
“dot”), to the value at the current location in the object as execution
proceeds.

   The input text for a template is as ASCII text is arbitrary format.

   Actions (data evaluations or control structures) are delimited by
‘{{’ and ‘}}’; all text outside actions is copied to the output
verbatim.

   To aid in formatting template source code, if ‘{{’ is followed
immediately by a minus sign and white space, all trailing white space is
trimmed from the immediately preceding text.  Similarly, if ‘}}’ is
preceded by white space and a minus sign, all leading white space is
trimmed from the immediately following text.  Notice that the presence
of the whitespace in these trim markers is mandatory: ‘{{- 3}}’ trims
the immediately preceding text and outputs ‘3’, while "‘{{-3}}’ parses
as an action containing the number ‘-3’.

* Menu:

* Actions::
* Arguments::

   ---------- Footnotes ----------

   (1) <https://pkg.go.dev/text/template>


File: pound.info,  Node: Actions,  Next: Arguments,  Up: Template syntax

12.5.1.1 Actions
................

Here is the list of actions.  “Arguments” and “pipelines” are
evaluations of data, defined in detail in the sections that follow.

‘{{ }}’
     Empty action is discarded.  It may be useful to trim the preceding
     or following whitespace, as in

          {{- -}}

‘{{/* a comment */}}’
     Comments are discarded.  They may span multiple lines of text.
     Comments do not nest and must start immediately after the opening
     delimiter (with optional dash and whitespace in between).  A
     comment may be followed by any action described below.

     Comments may be used to control trailing and leading whitespace as
     well:

          {{- a comment trimming the surrounding whitespace -}}

‘{{ PIPELINE }}’
     The PIPELINE is evaluated, and the default textual representation
     of its value is copied to the output.

‘{{if PIPELINE }} T1 {{end}}’
     If the value of the PIPELINE is empty, no output is generated;
     otherwise, T1 is executed.  The empty values are ‘null’, ‘false’,
     numeric 0, empty string (‘""’), array (‘[]’), or object (‘{}’).
     Dot is unaffected.

‘{{if PIPELINE }} T1 {{else}} T0 {{end}}’
     If the value of the pipeline is empty, T0 is executed; otherwise,
     T1 is executed.  Dot is unaffected.

‘{{if PIPELINE }} T1 {{else if PIPELINE }} T2 {{else}} T0 {{end}}’
     A shortcut to simplify writing the if-else chains.  Equivalent to
     (newlines added for readability):

          {{if PIPELINE }}
            T1
          {{else -}}
           {{if PIPELINE }}
             T2
           {{else}}
             T0
           {{end}}
          {{end}}

‘{{range PIPELINE }} T1 {{end}}’
     The value of PIPELINE must be an object or array.  If it is of
     length zero, nothing is output.  Otherwise, dot is set to the
     successive elements of the array or object and T1 is executed.  For
     objects, the elements will be visited in sorted key order.

‘{{range PIPELINE }} T1 {{else}} T0 {{end}}’
     Same as above, except that if the value of the PIPELINE is of
     length zero, T0 is executed with dot unaffected.

     Within the ‘{{range}}’ action, the following two keywords may
     appear:

     ‘{{break}}’
          The innermost ‘{{range PIPELINE}}’ loop is ended early,
          stopping the current iteration and bypassing all remaining
          iterations.

     ‘{{continue}}’
          The current iteration of the innermost ‘{{range PIPELINE}}’
          loop is stopped, and the loop starts the next iteration.

‘{{define "NAME"}} TEXT {{end}}’
     The TEXT is collected and stored for the further use as template
     with the given NAME.  It can be invoked using the ‘{{template}}’
     action (see below).

‘{{template "NAME"}}’
     The template with the specified NAME (see the ‘{{define}}’ above)
     is executed with dot set to ‘null’.

‘{{template "NAME" VALUE }}’
     The template with the specified NAME (see the ‘{{define}}’ above)
     is executed with dot set to VALUE.

‘{{block "NAME" PIPELINE }} T1 {{end}}’
     A block is shorthand for defining a template and then executing it
     in place:

          {{define "NAME"}} T1 {{end}}
          {{template "NAME" PIPELINE}}

‘{{with PIPELINE }} T1 {{end}}’
     If the value of the PIPELINE is empty, no output is generated;
     otherwise, dot is set to the value of the PIPELINE and T1 is
     executed.

‘{{with PIPELINE }} T1 {{else}} T0 {{end}}’
     Same as above, but if the value of the PIPELINE is empty, T0 is
     executed with dot unchanged.


File: pound.info,  Node: Arguments,  Prev: Actions,  Up: Template syntax

12.5.1.2 Arguments
..................

An “argument” is a simple value, i.e.  any of the following:

   • Numeric value (integer or floating point)
   • Boolean value: ‘true’ or ‘false’.
   • Quoted string.
   • A dot (‘.’) This represents the cursor value.
   • Attribute: ‘.ATTR’ This is the value of the attribute ATTR in the
     current value (dot).  Attribute references can be nested, as in
     ‘.Attr.Xattr.Yattr’.
   • A variable reference: ‘$VAR’.  Here, VAR is the name of the
     variable defined in the ‘range’ action.  *Note Variables::, below.

   • Function call in parentheses, for grouping.


File: pound.info,  Node: Pipelines,  Next: Variables,  Prev: Template syntax,  Up: poundctl template

12.5.2 Pipelines
----------------

A “pipeline” is a series of one or more “commands” delimited by pipe
sign (‘|’).  Each “command” is either an argument or a “function call”,
in form:

     FUNC ARG1 ARG2...

where FUNC is the name of one of the built-in functions discussed below.

   Pipelines are executed from left to right, with the result of the
previous command implicitly added to the list of arguments of each
subsequent command.  For example, the pipeline

     .attr | eq $x

is equivalent to

     eq $x .attr

i.e.  it calls the built-in function ‘eq’ with two arguments: the value
of the variable ‘x’ and attribute ‘attr’ of the cursor value.

   The following built-in functions are defined:

 -- Template built-in: and A1 A2
     Evaluates to ‘true’ if pipelines A1 and A2 both evaluate to ‘true’.
     Notice, that there is no boolean shortcut evaluation: both
     pipelines are evaluated prior to calling ‘and’.

 -- Template built-in: or A1 A2
     Evaluates to ‘true’ if at least one of the pipelines A1 and A2
     evaluates to ‘true’.  Notice, that there is no boolean shortcut
     evaluation: both pipelines are evaluated prior to calling ‘or’.

 -- Template built-in: index A1 A2...
     Returns the result of indexing its first argument by the following
     arguments.  Thus, if ‘.’ is an array, then:

          index . 5

     evaluates to its fifth element (‘.[5]’).

 -- Template built-in: len A1
     Returns the integer length of its argument.

 -- Template built-in: not A1
     Returns ‘true’ if its argument evaluates to ‘false’.

 -- Template built-in: eq A1 A2
     Returns ‘true’ if both its arguments are equal.  This applies only
     if both A1 and A2 are numeric or if they both are strings.

 -- Template built-in: ne A1 A2
     Returns ‘true’ if its arguments (both must be numeric or strings)
     are not equal.

 -- Template built-in: lt A1 A2
     Returns ‘true’ if A1 is numerically less than A2.

 -- Template built-in: le A1 A2
     Returns ‘true’ if A1 is numerically less than or equal to A2.

 -- Template built-in: gt A1 A2
     Returns ‘true’ if A1 is numerically greater than A2.

 -- Template built-in: ge A1 A2
     Returns ‘true’ if A1 is numerically greater than or equal to A2.

 -- Template built-in: even A1
     Returns ‘true’ if A1, which must evaluate to an integer value, is
     divisible by 2.

 -- Template built-in: printf FMT A1...
     Implements the ‘printf’ function.  FMT must evaluate to string.
     Rest of arguments is interpreted according to the conversion
     specifications in FMT.  The result is a formatted string.

     In addition to the standard conversion specifications, the ‘%v’
     specifier is implemented: it formats its argument in the best way,
     depending on its actual type.

 -- Template built-in: typeof A1
     Evaluates to the type of its argument, one of: ‘null’, ‘bool’,
     ‘number’, ‘integer’, ‘string’, ‘array’, and ‘object’.

 -- Template built-in: exists A1 A2
     A1 must evaluate to an object and A2 to string.  The function
     evaluates to ‘true’ if the attribute A2 is present in A1.

 -- Template built-in: add A1 A2...
     Returns the sum of its arguments.

 -- Template built-in: sub A1 A2
     Returns the difference ‘A1 - A2’.

 -- Template built-in: mul A1 A2
     Multiplies A1 by A2.

 -- Template built-in: div A1 A2
     Divides A1 by A2.


File: pound.info,  Node: Variables,  Next: Input object,  Prev: Pipelines,  Up: poundctl template

12.5.3 Variables
----------------

Variables (referred to as ‘$NAME’) can be defined in ‘range’ and ‘with’
actions.  For ‘range’, the syntax is:

     {{range $INDEX, $ELEMENT = PIPELINE }} T1 {{end}}

where INDEX and ELEMENT are arbitrary variable names.  When executing
this action, during each iteration $INDEX and $ELEMENT are set to the
index (attribute name) and value of each successive element.  Dot
remains unaffected.

   For ‘with’, the syntax is:

     {{with $VAR = PIPELINE }} T1 {{end}}

   PIPELINE is evaluated, its result is assigned to $VAR and the T1
block is executed with dot unchanged.

   A variable's scope extends to the ‘end’ action of the control
structure (‘with’ or ‘range’) in which it is declared.  This includes
any nested statements that may appear in between.


File: pound.info,  Node: Input object,  Prev: Variables,  Up: poundctl template

12.5.4 Input object
-------------------

Depending on the request issued by ‘poundctl’, the invoked template can
receive as its argument (“dot”) an object of one of the following types:
“core”, “full listing”, “listener”, “service”, or “backend”.  Each
object carries an explicit indication of its type in its ‘kind’
attribute.  Its possible values are:

‘backend’
     Backend statistics.
‘core’
     Core statistics.
‘listener’
     Listener statistics.
‘log’
     Log level information.
‘pound’
     Full listing.
‘service’
     Service statistics.

   Structures of each object are discussed in subsections that follow.

* Menu:

* Core listing::
* Log info::
* Full listing::
* Listener object::
* Service object::
* Backend object::


File: pound.info,  Node: Core listing,  Next: Log info,  Up: Input object

12.5.4.1 Core listing
.....................

A “core” object describes core ‘pound’ configuration.  It contains the
following attributes:

‘kind’
     Identifies the core listing object.  Its value is ‘core’.

‘pid’
     PID of the running ‘pound’ daemon.

‘version’
     ‘Pound’ version number (string).

‘workers’
     Workers statistics.  This is a JSON object with the following
     attributes:

     ‘active’
          Number of active threads.

     ‘count’
          Number of threads currently running.

     ‘max’
          Maximum number of threads.

     ‘min’
          Minimum number of threads.

     ‘timeout’
          Thread idle timeout.

‘queue_len’
     Number of incoming HTTP requests in the queue (integer).

‘timestamp’
     Current time on the server, formatted as ISO 8601 date-time with
     microsecond precision, e.g.: ‘2023-01-05T22:43:18.071559’.

‘uptime’
     Total running time of ‘pound’ daemon: number of microseconds
     elapsed since its startup.


File: pound.info,  Node: Log info,  Next: Full listing,  Prev: Core listing,  Up: Input object

12.5.4.2 Log info
.................

The ‘log’ object conveys information about log level settings (*note
poundctl log::.  It contains the following attributes:

‘kind’
     Identifies the full listing object.  The value if this attribute is
     ‘log’.

‘level’
     Symbolic name of the configured log level (*note log level::).

‘global’
     Symbolic name of the globally configured log level.

   If the object describes log settings of a listener, one of the
following attributes is also present:

‘listener_index’
     Index of the listener (0-based) in the configuration.

‘listener_name’
     Symbolic name of the listener.


File: pound.info,  Node: Full listing,  Next: Listener object,  Prev: Log info,  Up: Input object

12.5.4.3 Full listing
.....................

A full listing contains the following attributes.

‘kind’
     Identifies the full listing object.  The value if this attribute is
     ‘pound’.

‘core’
     Core listing.  *Note Core listing::.

‘listeners’
     An array of “listener” objects.  See below for a description.

‘services’
     An array of “service” objects, representing services defined in the
     global scope of the ‘pound’ configuration file.


File: pound.info,  Node: Listener object,  Next: Service object,  Prev: Full listing,  Up: Input object

12.5.4.4 Listener
.................

A “listener” object represents a single HTTP or HTTPS listener in
‘pound’ configuration.  It has the following attributes:

‘kind’
     Identifies the listener object.  The value of this attribute is
     ‘listener’.

‘address’
     Address of this listener.  A string formatted as ‘IP:PORT’.  for
     IPv4 and IPv6 addresses or containing a socket file name, for UNIX
     sockets.

‘protocol’
     Protocol used: either ‘http’ or ‘https’.

‘services’
     Array of “service” objects representing services defined in this
     listener.  See below for the definition of a “service” object.

‘enabled’
     Boolean.  Whether this listener is enabled or not.

‘nohttps11’
     Value of the ‘NoHTTPS11’ configuration statement for this listener
     (*note NoHTTPS11: ListenHTTPS.). One of: 0, 1, 2.


File: pound.info,  Node: Service object,  Next: Backend object,  Prev: Listener object,  Up: Input object

12.5.4.5 Service
................

A “service” object describes a single service.

‘kind’
     Identifies the service object.  The value of this attribute is
     ‘service’.

‘name’
     Symbolic name of this service.

‘enabled’
     Boolean.  Whether this service is enabled or not.

‘session_type’
     Name of the session handling algorithm for this service.  One of:
     ‘IP’, ‘BASIC’, ‘URL’, ‘PARM’, ‘COOKIE’, ‘HEADER’.

‘sessions’
     List of active sessions in this service.  Each session is
     represented as object with the following attributes:

     ‘key’
          Session key (string).

     ‘backend’
          Ordinal number of the backend assigned to handle requests with
          this session.

     ‘expire’
          Expiration time of this session, formatted as
          ‘1970-01-01T00:00:00.000000’ (with microsecond precision).

‘backends’
     List of “backends” defined for this service.

‘emergency’
     Emergency “backend” object, or ‘null’ if no such backend is
     defined.


File: pound.info,  Node: Backend object,  Prev: Service object,  Up: Input object

12.5.4.6 Backend
................

The following attributes are always present in each “backend” object:

‘kind’
     Identifies the backend object.  The value of this attribute is
     ‘backend’.

‘alive’
     Whether or not this backend is alive.

‘conn_to’
     Connection timeout for this backend (seconds).

‘enabled’
     Whether or not this backend is enabled.

‘io_to’
     I/O timeout for this backend (seconds).

‘priority’
     Priority value assigned to this backend.

‘protocol’
     Protocol used by this backend: either ‘http’ or ‘https’.

‘type’
     Backend type.  One of: ‘acme’, ‘backend’, ‘control’, ‘redirect’.

‘ws_to’
     Websocket timeout (seconds).

   Depending on the backend type, the following attributes may be
present:

‘acme’
     An object of the following structure:

     ‘path’
          Directory where ACME challenges are stored.

‘backend’
     Object:
     ‘address’
          Backend address.

‘redirect’
     Object:
     ‘url’
          URL to redirect to.
     ‘code’
          HTTP code for redirection responses.  One of: 301, 302, 307.
     ‘redir_req’
          Boolean: whether to append the original request path to the
          resulting location.

   If backend statistics is enabled (*note BackendStats::), the ‘stats’
object will be present, with the following attributes:

‘request_count’
     Total number of requests processed by this backend.
‘request_time_avg’
     Average time per request, in nanoseconds.
‘request_time_stddev’
     Standard deviation of the above.


File: pound.info,  Node: Emacs,  Next: Metric Families,  Prev: poundctl,  Up: Top

13 Emacs Major Mode
*******************

‘Pound’ is distributed with ‘pound-mode.el’, an Elisp source which
provides a major mode for editing ‘pound’ configuration files in GNU
Emacs.  The file is located in ‘src’ directory of the distribution.  To
install it, follow the instructions below.

   First, select the directory where to place the file.  The directory
must form a part of the ‘emacs’ ‘load-path’ (*note (elisp)Library
Search::) variable.  Then, copy ‘pound-mode.el’ to that directory.
Then, add the following statements to your ‘.emacs’ or site-wide
‘site-start.el’ file (*note The Emacs Initialization File: (emacs)Init
File.):

     (autoload 'pound-mode "pound-mode")
     (add-to-list 'auto-mode-alist
                  (cons (purecopy "pound\\.cfg\\'") 'pound-mode))

   The first statement loads ‘pound’ Emacs major mode.  The second one
associates file ‘pound.cfg’ with that mode, so that each time you load a
file with that name to your editor, it will automatically select
‘pound-mode’ as its default major mode.  Depending on your customs, you
may further modify ‘auto-mode-alist’ to associate ‘pound-mode’ with more
files.  For example, if your main configuration file includes files from
‘/etc/pound’ directory (*note File inclusion::), it might be a good idea
to add the following:

     (add-to-list 'auto-mode-alist
        (cons (purecopy "pound/.*\\.cfg\\'") 'pound-mode))

   Once these changes done, you can start ‘emacs’ to see if it correctly
selects the major mode for your ‘pound.cfg’.

   The ‘pound-mode’ major mode highlights ‘pound’ configuration keywords
and data types, and provides automatic indentation for the configuration
file.  It defines the following key bindings:

<C-M-a>
     Place cursor at the start of the enclosing section.

<C-M-e>
     Place cursor at the end of the enclosing section.

<C-M-\>
     Indent region.

<C-c C-c>
     Check the syntax of the current buffer by running ‘pound -c’ (*note
     lint::).

   The following customization variables are available:

 -- Customization Variable: pound-basic-offset
     Default indentation increment.  Each nesting level in the
     configuration file will be indented that amount of columns,
     relative to the enclosing section.

     The default value is 8.

 -- Customization Variable: pound-command
     Command line for starting the ‘pound’ daemon.  Default is ‘pound’.

     Use this variable to specify full pathname of the ‘pound’ binary,
     if it cannot be found using the ‘PATH’ shell variable, or to supply
     additional options to it.

 -- Customization Variable: pound-include-dir
     Defines ‘pound’ include directory (*note include directory::).


File: pound.info,  Node: Metric Families,  Next: Time and Date Formats,  Prev: Emacs,  Up: Top

Appendix A Metric Families
**************************

This appendix describes metric families returned in the output of
“openmetrics” ‘pound’ backends (*note Metrics::).

 -- Metric family: counter pound_uptime
     Number of milliseconds elapsed since ‘pound’ startup.

 -- Metric family: gauge pound_workers
     Number of pound workers (*note Worker model::).  Indexed by types:

     ‘active’
          Number of workers currently active.
     ‘count’
          Number of workers running (both idle and active).
     ‘min’
          Minimum number of workers as set by the ‘WorkerMinCount’
          configuration directive (*note WorkerMinCount: Global
          directives.).
     ‘max’
          Maximum number of workers as set by the ‘WorkerMaxCount’
          configuration directive (*note WorkerMaxCount: Global
          directives.).

     Example:

          pound_workers{type="active"} 2
          pound_workers{type="count"} 5
          pound_workers{type="max"} 128
          pound_workers{type="min"} 5

 -- Metric family: gauge pound_queue
     Connection queue statistics.  Indexed by types:

     ‘len’
          Current number of connections waiting in the queue.

     ‘max’
          Maximum allowed number of elements (queue capacity).

 -- Metric family: gauge pound_queue_len
     Number of connections waiting in the input queue.  This is the same
     as ‘pound_queue{type="len"}’, which is recommended to use instead.
     This value is retained for backward compatibility with ‘pound’
     versions 4.19 - 4.22.

 -- Metric family: stateset pound_listener_enabled
     State of a listener: enabled/disabled.  Indexed by the listener
     ordinal number and, if available, its name.

          pound_listener_enabled{listener="0"} 1
          pound_listener_enabled{listener="1",listener_name="plain"} 0
          pound_listener_enabled{listener="2",listener_name="tls"} 1

 -- Metric family: info pound_listener_info
     Description of a listener.  Each instance contains the following
     indices:

     ‘listener’
          Listener ordinal number.

     ‘listener_name’
          Listener name, if set in the ‘ListenHTTP’ or ‘ListenHTTPS’
          statement (*note ListenHTTP::).

     ‘address’
          Listener address.  For INET family, it is formatted as
          ‘IP:PORT’, for UNIX sockets, it is the pathname of the socket.

     ‘protocol’
          Protocol served by the listener: ‘http’, ‘https’, or ‘tunnel’.

     The value of this metrics is always ‘1’.

          pound_listener_info{listener="0",address="/run/pound.sock",protocol="http"} 1
          pound_listener_info{listener="1",listener_name="plain",address="0.0.0.0:80",protocol="http"} 1
          pound_listener_info{listener="2",listener_name="tls",address="0.0.0.0:443",protocol="https"} 1

 -- Metric family: stateset pound_service_enabled
     State of a particular service.

          pound_service_enabled{listener="0",service="0"} 1
          pound_service_enabled{listener="1",service="0"} 1
          pound_service_enabled{listener="1",listener_name="plain",service="0",service_name="redirect"} 0
          pound_service_enabled{listener="2",listener_name="tls",service="0",service_name="metrics"} 1
          pound_service_enabled{listener="2",listener_name="tls",service="1",service_name="web"} 1
          pound_service_enabled{service="0",service_name="fallback"} 1

 -- Metric family: gauge pound_backends
     Number of backends per service: total, alive, enabled, and active
     (both alive and enabled).  Indices:

     ‘listener’
          Listener ordinal number.  This index is absent for globally
          defined services.

     ‘listener_name’
          Name of the listener.  Present only if the name is set and not
          empty.

     ‘service’
          Index of the service in listener (or in global configuration,
          for globally defined services).

     ‘service_name’
          Name of the service.  Present only if the name is set and not
          empty.

     ‘state’
          Backend state: ‘total’, ‘alive’, ‘enabled’, or ‘active’.

     ‘service_name’
          Name of the service.  Present only if the name is set and not
          empty.

     Example:

          pound_backends{listener="0",listener_name="plain",service="0",service_name="web",state="total"} 5
          pound_backends{listener="0",listener_name="plain",,service="0",service_name="web",state="enabled"} 3
          pound_backends{listener="0",listener_name="plain",,service="0",service_name="web",state="alive"} 3
          pound_backends{service="0",state="total"} 1
          pound_backends{service="0",state="enabled"} 1
          pound_backends{service="0",state="alive"} 1

 -- Metric family: stateset pound_backend_state
     State of each backend.  Indices:

     ‘listener’
          Listener ordinal number.  This index is absent for globally
          defined services.

     ‘listener_name’
          Name of the listener.  Present only if the name is set and not
          empty.

     ‘service’
          Index of the service in listener (or in global configuration,
          for globally defined services).

     ‘service_name’
          Name of the service.  Present only if the name is set and not
          empty.

     ‘backend’
          Index of the backend in service.

     ‘state’
          ‘enabled’: whether the backend is enabled or not.
          ‘alive’: whether the backend is alive or not.

     Example:

          pound_backend_state{listener="0",service="0",backend="0",state="alive"} 1
          pound_backend_state{listener="0",service="0",backend="0",state="enabled"} 1
          pound_backend_state{listener="0",service="0",backend="1",state="alive"} 1
          pound_backend_state{listener="0",service="0",backend="1",state="enabled"} 0

 -- Metric family: gauge pound_backend_requests
     Number of requests processed by backend.  This metrics is available
     only if backend statistics is enabled (*note BackendStats::).

     Example:

          pound_backend_requests{listener="0",service="0",backend="0"} 40587
          pound_backend_requests{listener="1",service="0",backend="0"} 13858

 -- Metric family: gauge pound_backend_request_time_avg_nanoseconds
     Average time per request spent in backend (nanoseconds).  This
     metrics is available only if backend statistics is enabled (*note
     BackendStats::).

          pound_backend_request_time_avg_nanoseconds{listener="0",service="0",backend="0"} 156254
          pound_backend_request_time_avg_nanoseconds{listener="1",service="2",backend="0"} 26147

 -- Metric family: gauge pound_backend_request_stddev_nanoseconds
     Standard deviation of the average time per request.  This metrics
     is available only if backend statistics is enabled (*note
     BackendStats::).

          pound_backend_request_stddev_nanoseconds{listener="0",service="0",backend="0"} 0
          pound_backend_request_stddev_nanoseconds{listener="1",service="2",backend="0"} 59


File: pound.info,  Node: Time and Date Formats,  Next: Old Control Format,  Prev: Metric Families,  Up: Top

Appendix B Time and Date Formats
********************************

This appendix documents the time format specifications understood by the
‘%{FORMAT}t’ log format conversion.  Essentially, it is a reproduction
of the man page for GNU ‘strftime’ function.

   Ordinary characters placed in the format string are reproduced
without conversion.  Conversion specifiers are introduced by a ‘%’
character, and are replaced as follows:

%a             The abbreviated weekday name according to the
               current locale.
               
%A             The full weekday name according to the current
               locale.
               
%b             The abbreviated month name according to the
               current locale.
               
%B             The full month name according to the current
               locale.
               
               
%c             The preferred date and time representation for
               the current locale.
               
%C             The century number (year/100) as a 2-digit
               integer.
               
%d             The day of the month as a decimal number (range
               01 to 31).
               
%D             Equivalent to ‘%m/%d/%y’.
               
%e             Like ‘%d’, the day of the month as a decimal
               number, but a leading zero is replaced by a
               space.
               
%E             Modifier: use alternative format, see below
               (*note conversion specs::).
               
%F             Equivalent to ‘%Y-%m-%d’ (the ISO 8601 date
               format).
               
%G             The ISO 8601 year with century as a decimal
               number.  The 4-digit year corresponding to the
               ISO week number (see ‘%V’).  This has the same
               format and value as ‘%y’, except that if the ISO
               week number belongs to the previous or next
               year, that year is used instead.
               
%g             Like ‘%G’, but without century, i.e., with a
               2-digit year (00-99).
               
%h             Equivalent to ‘%b’.
               
%H             The hour as a decimal number using a 24-hour
               clock (range 00 to 23).
               
%I             The hour as a decimal number using a 12-hour
               clock (range 01 to 12).
               
%j             The day of the year as a decimal number (range
               001 to 366).
               
%k             The hour (24-hour clock) as a decimal number
               (range 0 to 23); single digits are preceded by a
               blank.  (See also ‘%H’.)
               
%l             The hour (12-hour clock) as a decimal number
               (range 1 to 12); single digits are preceded by a
               blank.  (See also ‘%I’.)
               
%m             The month as a decimal number (range 01 to 12).
               
%M             The minute as a decimal number (range 00 to 59).
               
%n             A newline character.
               
%O             Modifier: use alternative format, see below
               (*note conversion specs::).
               
%p             Either ‘AM’ or ‘PM’ according to the given time
               value, or the corresponding strings for the
               current locale.  Noon is treated as ‘pm’ and
               midnight as ‘am’.
               
%P             Like ‘%p’ but in lowercase: ‘am’ or ‘pm’ or a
               corresponding string for the current locale.
               
%r             The time in ‘a.m.’ or ‘p.m.’ notation.  In the
               POSIX locale this is equivalent to ‘%I:%M:%S
               %p’.
               
%R             The time in 24-hour notation (‘%H:%M’).  For a
               version including the seconds, see ‘%T’ below.
               
               
%s             The number of seconds since the Epoch, i.e.,
               since 1970-01-01 00:00:00 UTC.
               
%S             The second as a decimal number (range 00 to 61).
               
%t             A tab character.
               
%T             The time in 24-hour notation (‘%H:%M:%S’).
               
%u             The day of the week as a decimal, range 1 to 7,
               Monday being 1.  See also ‘%w’.
               
%U             The week number of the current year as a decimal
               number, range 00 to 53, starting with the first
               Sunday as the first day of week 01.  See also
               ‘%V’ and ‘%W’.
               
%V             The ISO 8601:1988 week number of the current
               year as a decimal number, range 01 to 53, where
               week 1 is the first week that has at least 4
               days in the current year, and with Monday as the
               first day of the week.  See also ‘%U’ and ‘%W’.
               
%w             The day of the week as a decimal, range 0 to 6,
               Sunday being 0.  See also ‘%u’.
               
%W             The week number of the current year as a decimal
               number, range 00 to 53, starting with the first
               Monday as the first day of week 01.
               
%x             The preferred date representation for the
               current locale without the time.
               
%X             The preferred time representation for the
               current locale without the date.
               
%y             The year as a decimal number without a century
               (range 00 to 99).
               
%Y             The year as a decimal number including the
               century.
               
%z             The time-zone as hour offset from GMT.  Required
               to emit RFC822-conformant dates (using ‘%a, %d
               %b %Y %H:%M:%S %z’)
               
%Z             The time zone or name or abbreviation.
               
%+             The date and time in ‘date(1)’ format.
               
%%             A literal ‘%’ character.

   Some conversion specifiers can be modified by preceding them by the
‘E’ or ‘O’ modifier to indicate that an alternative format should be
used.  If the alternative format or specification does not exist for the
current locale, the behaviour will be as if the unmodified conversion
specification were used.  The Single Unix Specification mentions ‘%Ec’,
‘%EC’, ‘%Ex’, ‘%EX’, ‘%Ry’, ‘%EY’, ‘%Od’, ‘%Oe’, ‘%OH’, ‘%OI’, ‘%Om’,
‘%OM’, ‘%OS’, ‘%Ou’, ‘%OU’, ‘%OV’, ‘%Ow’, ‘%OW’, ‘%Oy’, where the effect
of the ‘O’ modifier is to use alternative numeric symbols (say, roman
numerals), and that of the ‘E’ modifier is to use a locale-dependent
alternative representation.


File: pound.info,  Node: Old Control Format,  Next: Example Lua modules,  Prev: Time and Date Formats,  Up: Top

Appendix C Old Control Output Format
************************************

Prior to version 4.18, JSON output from ‘pound’ control interface
differred from the current format (*note Input object::) in several
important aspects:

  1. Objects didn't carry the ‘kind’ attribute.

  2. The “full listing” object incorporated attributes from the “core”
     listing directly, instead of storing them under the ‘core’
     attribute.

  3. The “core listing” object lacked ‘uptime’ attribute.

   In the absense of explicit indication of the object type being passed
(see pt.  1 above), templates were using an heuristics based on the
presence or absence of certain attribute to deduce the object type in
question.  This heuristic is described in the following pseudo-code
fragment:

     {{if exists . "listeners" }}
       {{/* This is a full listing, as requested by poundctl list. */}}
       ...
     {{else if exists . "services"}}
       {{/* Single listener, as requested by poundctl list /L.
            Notice that this attribute is present in the full listing as
            well, so presence of "listeners" should be checked first. */}}
       ...
     {{else if exists . "backends"}}
       {{/* Single service, as requested by poundctl list /L/S. */}}
       ...
     {{else if exists . "pid"}}
       {{/* Core statistics (poundctl core) */}}
       ...
     {{else}}
       {{/* Backend listing (poundctl list /L/I/B) */}}
       ...
     {{end}}

   For backward compatibility, template file shipped with ‘pound’
version 4.23 checks whether ‘kind’ attribute is present, and if it is
not, falls back to using the heuristics above.


File: pound.info,  Node: Example Lua modules,  Next: GNU Free Documentation License,  Prev: Old Control Format,  Up: Top

Appendix D Example Lua modules
******************************

This appendix provides implementations of some Lua modules used in this
manual.

* Menu:

* jwt.lua::
* cookie.lua::
* wwwauth.lua::


File: pound.info,  Node: jwt.lua,  Next: cookie.lua,  Up: Example Lua modules

D.1 jwt.lua
===========

This is the implementation of ‘jwt.lua’ module, used in examples in
*note LuaMatch::.  It provides the following methods:

 -- jwt: parse input
     Parse INPUT and build a new JWT object on success.  Return two
     values: the resulting object, and error message (on failure).

 -- jwt: new payload secret
     Create a new JWT object from PAYLOAD and encrypt it with the
     supplied SECRET.

   The JWT object returned by either of these functions has two methods:

 -- Method on jwt: sign secret
     Sign the object using SECRET.  Return the signed string suitable
     for use in ‘Authorization:’ HTTP header.

 -- Method on jwt: verify secret
     The reverse operation: verify if the signature of the object
     returned by ‘parse’ matches SECRET.  Return ‘true’ if it does and
     ‘false’ otherwise.

   The fields of a JWT object are:

 -- object field of jwt: header
     Header part of JWT, decoded into Lua table.

 -- object field of jwt: payload
     Payload part, decoded into Lua table.

 -- object field of jwt: signature
     Signature part, as a string.

 -- object field of jwt: raw
     A table containing original (undecoded) values of the three parts
     in its fields ‘header’, ‘payload’, and ‘signature’.

   Full text of ‘jwt.lua’ follows:

     -- Simple implementation of JWT for Pound documentation.
     -- Supports only HMAC signing algorithms.

     local jwt = {}

     local json = require 'dkjson'
     local base64 = require 'base64'

     local base64url_encoder = base64.makeencoder( '-', '_' )
     local base64url_decoder = base64.makedecoder( '-', '_' )

     -- base64url encoding. RFC 7515, Appendix C.
     local function base64url_encode(s)
        b = base64.encode(s, base64url_encoder)
        return b:gsub('=*$','')
     end

     -- base64url encoding. RFC 7515, Appendix C.
     local function base64url_decode(s)
        n = #s % 4
        if n == 3 then
           s = s .. '='
        elseif n == 2 then
           s = s .. '=='
        elseif n ~= 0 then
           return nil, 'invalid base64 encoding'
        end
        ok, val = pcall(base64.decode, s, base64url_decoder)
        if ok then
           return val
        else
           return nil, val
        end
     end

     local openssl = require 'openssl'

     -- Constant declarator
     local constant = {}
     function constant.declare(t)
        return setmetatable(t, {
     	 __index = function (table, key)
                 local v = rawget(t, key)
     	    if v ~= nil then
     	       return v
     	    else
     	       error("No such constant: "..tostring(key))
     	    end
     	 end;
     	 __newindex = function(table, key, value)
     	    error("Attempt to modify read-only table")
     	 end;
     	 __metatable = false;
        });
     end

     setmetatable(constant, {
     		__call = function(_, ...) return constant.declare(...) end
     })

     local S = constant {
        JWT = "JWT",
     }

     local function hmac(alg, secret, message)
        return openssl.hmac.hmac(alg, message, secret, true)
     end

     local sign_algo = constant {
        HS256 = function (secret, message)
     	 return hmac('SHA256', secret, message)
        end;
        HS384 = function (secret, message)
     	 return hmac('SHA384', secret, message)
        end;
        HS512 = function (secret, message)
     	 return hmac('SHA512', secret, message)
        end
     }

     -- Sign a JWT using supplied secret.
     local function jwt_sign(jwt, secret)
        input = jwt.raw.header .. '.' .. jwt.raw.payload
        return base64url_encode(sign_algo[jwt.header.alg](secret, input))
     end

     -- Verify JWT using supplied secret.  Cache result in the
     -- "verified" field.
     local function jwt_verify(jwt, secret)
        if jwt.verified == nil then
           jwt.verified = jwt_sign(jwt, secret) == jwt.raw.signature
        end
        return jwt.verified
     end

     local jwt_metatable = {
        __index = {
           sign = jwt_sign,
           verify = jwt_verify
        }
     }

     -- Create new JWT object from the encoded JWT input.
     -- Return the created object, or nil and textual error description on
     -- error.
     function jwt.parse(input)
        function split(s, n)
           i = s:find("[.]")
           if i == nil then
     	 return s, true
           elseif n == 0 then
     	 return s, false
           else
     	 return s:sub(1,i-1), split(s:sub(i+1),n-1)
           end
        end

        local r = {}
        r['header'], r['payload'], r['signature'], ok = split(input,2)
        if not ok then
           return nil, 'required JWT parts missing'
        end

        local j = { ['raw'] = r }
        local val, err = base64url_decode(r['header'], base64url_decoder)
        if err ~= nil then
           return nil, 'header fails to decode'
        end

        j['header'], _, err = json.decode(val)
        if err then
           return nil, 'malformed header JSON'
        end
        if j.header.typ ~= S.JWT then
           return nil, 'unsupported type'
        end

        val, err = base64url_decode(r['payload'], base64url_decoder)
        if err ~= nil then
           return nil, 'paiload fails to decode'
        end
        j['payload'], _, err = json.decode(val)
        if err then
           return nil, 'malformed payload JSON'
        end
        setmetatable(j, jwt_metatable)
        return j, nil
     end

     function jwt.new(payload, secret)
        local j = {}
        j.header = {
           typ = S.JWT,
           alg = "HS256"
        }
        j.payload = payload
        j.raw = {}
        j.raw.header = base64url_encode(json.encode(j.header))
        j.raw.payload = base64url_encode(json.encode(j.payload))
        return j.raw.header .. '.' .. j.raw.payload .. '.' .. jwt_sign(j,secret)
     end

     return jwt


File: pound.info,  Node: cookie.lua,  Next: wwwauth.lua,  Prev: jwt.lua,  Up: Example Lua modules

D.2 cookie.lua
==============

The ‘cookie’ module, used in *note Cookie injection::, provides the
following two methods:

 -- cookie: get name
     Return value of the cookie NAME from the incoming request, or nil
     if no such cookie is present.

 -- cookie: set name ttl
     Set cookie NAME in the response.  Second argument provides the
     value of ‘Max-Age’.

   Full text of ‘cookie.lua’ follows:

     local _M = {}

     -- Return the value of cookie NAME or nil if it is not set.
     function _M.get(name)
        -- Return true if string S begins with the NAME
        -- followed by an equals sign.
        function is_name(s)
           local i,j = s:find(name..'=', 1, true)
           if j ~= nil then
              return s:sub(j+1)
           else
              return nil
           end
        end
        -- Given partial value of the Cookie header COOKIE,
        -- find the cookie NAME and return its value.
        local function find_cookie(cookie, name)
           if cookie == nil then
              return nil
           end

           local i, j = cookie:find(";%s*")
           if i == nil then
              return is_name(cookie)
           else
              local s = is_name(cookie:sub(1, i-1))
              if s ~= nil then
                 return s
              else
                 return find_cookie(cookie:sub(j+1), name)
              end
           end
        end

        return find_cookie(http.req.headers['Cookie'], name)
     end

     -- Set cookie NAME to the given VALUE.  Use TTL
     -- as its Max-Age.
     function _M.set(name, value, ttl)
        cv = name .. '=' .. value .. '; Max-Age=' .. ttl
        cookie = http.resp.headers['Set-cookie']
        if cookie == nil then
           cookie = { cv }
        elseif type(cookie) == 'table' then
           table.insert(cookie, cv)
        else
           cookie = { cookie, cv }
        end
        http.resp.headers['Set-cookie'] = cookie
     end

     return _M

