httpd(3)

πŸ“¦
version 29.0.6 Β· 3 versions
, in ubuntu stonking

✨ httpd ✨

okay bestie, welcome to httpd(3), the Erlang Module Definition for the HTTP server API πŸ’– this is part 1 of 5, so buckle up, hydrate, and let's get into it 🫢


🌸 NAME 🌸

httpd β€” HTTP server API πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

It's an implementation of an HTTP 1.1 compliant web server, exactly as defined in RFC 2616 ✨. It hands you web server start options, administrative functions, and an Erlang callback API. No cap, that's the whole vibe πŸ‘‘

🌈 Data types 🌈

These are the type definitions that show up more than once in this module, so like, learn them once and you're set πŸ’…:

  • boolean() = true | false
  • string/0 = list of ASCII characters
  • path() = string() representing a file or a directory path
  • ip_address() = {N1,N2,N3,N4} % IPv4 | {K1,K2,K3,K4,K5,K6,K7,K8} % IPv6
  • hostname() = string() representing a host, for example, "foo.bar.com"
  • property() = atom()

πŸŽ€ HTTP server service start & stop πŸŽ€

A web server can be configured to start when you start the Inets application, or dynamically at runtime by calling the Inets application API like inets:start(httpd, ServiceConfig) or inets:start(httpd, ServiceConfig, How) β€” see inets for that πŸ’–. The configuration options, which we also call properties, go like this:

🌸 File Properties 🌸

When the web server starts at application start time, the properties get fetched from a configuration file. That file can be a regular Erlang property list, that is, [{Option, Value}], where Option = property() and Value = term(), followed by a full stop. And if the web server is started dynamically at runtime, you can still specify a file, but you can also just hand over the complete property list, no biggie ✨

  • {proplist_file, path()} β€” If this property is defined, Inets expects to find all the other properties defined in this file. The file must include all properties listed under mandatory properties, or it's not gonna slay.
NOTE: support for the legacy configuration file with Apache syntax is dropped in OTP-23. it's giving deprecated, bestie, let it go πŸ’€

πŸ”₯ Mandatory Properties πŸ”₯

These ones are literally not optional, periodt:

  • {port, integer()} β€” The port that the HTTP server listens to. If you specify zero as the port, an arbitrary available port gets picked, and then httpd:info/2 can be used to figure out which port it actually chose πŸ‘‘
  • {server_root, path()} β€” Defines the home directory of the server, where log files and so on can be stored. Relative paths you specify in other properties refer to this directory 🌸
  • {document_root, path()} β€” Defines the top directory for the documents that are available on the HTTP server πŸ“

πŸ¦‹ Communication Properties πŸ¦‹

  • {bind_address, ip_address() | hostname() | any} β€” Default is any
  • {server_name, string()} β€” The name of your server, normally a fully qualified domain name.

If it's not given, this defaults to net_adm:localhost().

  • {profile, atom()} β€” Used together with bind_address and port to uniquely identify a HTTP server. This is useful in a virtualized environment, where there can be more than one server that has the same bind_address and port. If this property is not explicitly set, it is assumed that the bind_address and port uniquely identify the HTTP server πŸ’…
  • {socket_type, ip_comm | {ip_comm, Config::proplist()} | {ssl, Config::proplist()}} β€” For ip_comm configuration options, see gen_tcp:listen/2; some options that are used internally by httpd cannot be set.

For SSL configuration options, see ssl:listen/2.

Default is ip_comm.

NOTE: OTP-25 deprecates the communication properties {socket_type, ip_comm | {ip_comm, Config::proplist()} | {essl, Config::proplist()}}, replacing it by {socket_type, ip_comm | {ip_comm, Config::proplist()} | {ssl, Config::proplist()}}. so like, essl is old news, move on ✨
  • {ipfamily, inet | inet6} β€” Default is inet. The legacy option inet6fb4 no longer makes sense and will be translated to inet πŸ™ˆ
  • {minimum_bytes_per_second, integer()} β€” If given, sets a minimum of bytes per second value for connections.

If the value is unreached, the socket closes for that connection.

This option is good for reducing the risk of "slow DoS" attacks πŸ›‘οΈ

πŸ‘‘ Erlang Web Server API Modules πŸ‘‘

  • {modules, [atom()]} β€” Defines which modules the HTTP server uses when handling requests. Default is [mod_alias, mod_auth, mod_esi, mod_dir, mod_get, mod_head, mod_log, mod_disk_log]. Notice that some mod-modules are dependent on others, so the order cannot be entirely arbitrary. See the Inets Web Server Modules in the User's Guide for details πŸŽ€

πŸ’œ Limit properties πŸ’œ

  • {customize, atom()} β€” A callback module to customize the inets HTTP servers behaviour, see httpd_custom_api
  • {disable_chunked_transfer_encoding_send, boolean()} β€” Allows you to disable chunked transfer-encoding when sending a response to an HTTP/1.1 client. Default is false.
  • {keep_alive, boolean()} β€” Instructs the server whether to use persistent connections when the client claims to be HTTP/1.1 compliant. Default is true.
  • {keep_alive_timeout, integer() | infinity} β€” The number of seconds the server waits for a subsequent request from the client before closing the connection. This timer covers the waiting time for the request to arrive, starting from the connection opening or the moment the server sent a response to a previous request. Default is 150 seconds ⏳
  • {max_body_size, integer() | nolimit} β€” Limits the size of the message body of an HTTP request. Default is no limit.
  • {request_timeout, pos_integer() | infinity} β€” Limits the time the server is allowed to be idle waiting for the next chunk of an HTTP request. Refreshes on every incoming chunk within the same request. Default is 60 seconds.
  • {max_clients, integer()} β€” Limits the number of simultaneous requests that can be supported. Default is 150.
  • {max_header_size, integer()} β€” Limits the size of the message header of an HTTP request. Default is 10240.
  • {max_content_length, integer()} β€” Maximum content-length in an incoming request, in bytes. Requests with content larger than this are answered with status 413. Default is 100000000 (100 MB).
  • {max_uri_size, integer() | nolimit} β€” Limits the size of the HTTP request URI. Default is no limit.
  • {max_keep_alive_request, integer()} β€” The number of requests that a client can do on one connection. When the server has responded to the number of requests defined by max_keep_alive_requests, the server closes the connection. The server closes it even if there are queued request. Default is no limit.
  • {max_client_body_chunk, integer()} β€” Enforces chunking of a HTTP PUT or POST body data to be delivered to the mod_esi callback. Note this is not supported for mod_cgi. Default is no limit, e.i the whole body is delivered as one entity, which could be very memory consuming. mod_esi.

🌈 Administrative Properties 🌈

  • {mime_types, [{MimeType, Extension}] | path()} β€” MimeType = string() and Extension = string(). Files delivered to the client are MIME typed according to RFC 1590. File suffixes are mapped to MIME types before file delivery. The mapping between file suffixes and MIME types can be specified in the property list.

Mime types can also be read from a file. The file should contain lines in the form MediaType [Extensions...], such as text/html html htm. To configure this, specify the path to it, such as {mime_types, "/etc/mime.types"}.

If unset, conf/mime.types under server_root will be used if it exists, otherwise, the default is [{"html","text/html"},{"htm","text/html"}] πŸ’…

  • {mime_type, string()} β€” When the server is asked to provide a document type that cannot be determined by the MIME Type Settings, the server uses this default type.
  • {server_admin, string()} β€” Defines the email-address of the server administrator to be included in any error messages returned by the server πŸ“§
  • {server_tokens, none|prod|major|minor|minimal|os|full|{private, string()}} β€” Defines the look of the value of the server header.

Example: Assuming the version of Inets is 5.8.1, the server header string can look as follows for the different values of server-tokens:

  • none
"" % A Server: header will not be generated
  • prod
"inets"
  • major
"inets/5"
  • minor
"inets/5.8"
  • minimal
"inets/5.8.1"
  • os
"inets/5.8.1 (unix)"
  • full
"inets/5.8.1 (unix/linux) OTP/R15B"
  • {private, "foo/bar"}
"foo/bar"

By default, the value is as before, that is, minimal.

  • {logger, Options::list()} β€” Currently only one option is supported:
    • {error, ServerID::atom()} Produces logger events on logger level error under the hierarchical logger domain: [otp, inets, httpd, ServerID, error]. The built in logger formatting function produces log entries from the error reports:
#{server_name => string()
  protocol => internal | 'TCP' | 'TLS' | 'HTTP',
  transport => "TCP" | "TLS", %% Present when protocol = 'HTTP'
  uri => string(), %% Present when protocol = 'HTTP' and URI is valid
  peer => inet:peername(),
  host => inet:hostname(),
  reason => term()
}

An example of a log entry with only default settings of logger

=ERROR REPORT==== 9-Oct-2019::09:33:27.350235 ===
   Server: My Server
 Protocol: HTTP
Transport: TLS
      URI: /not_there
     Host: 127.0.1.1:80
     Peer: 127.0.0.1:45253
   Reason: [{statuscode,404},{description,"Object Not Found"}]

Using this option makes mod_log and mod_disk_log error logs redundant.

Add the filter

{fun logger_filters:domain/2,
     {log,equal,[otp,inets, httpd, ServerID, error]}

to appropriate logger handler to handle the events. For example to write the error log from an httpd server with a ServerID of my_server to a file you can use the following sys.config:

[{kernel,
 [{logger,
  [{handler, http_error_test, logger_std_h,
    #{config => #{ file => "log/http_error.log" },
      filters => [{inets_httpd, {fun logger_filters:domain/2,
                                 {log, equal,
                                  [otp, inets, httpd, my_server, error]
                                 }}}],
      filter_default => stop }}]}]}].

or if you want to add it to the default logger via an API:

  • {log_format, common | combined} β€” tells the server whether access logs get written in the common log format or the extended common log format. πŸ’…

The common format is literally one line that looks like this:

remotehost rfc931 authuser [date] "request" status bytes

and breaking down every single field bestie:

  • remotehost β€” Remote.
  • rfc931 β€” The remote username of the client (RFC 931).
  • authuser β€” The username used for authentication.
  • [date] β€” Date and time of the request (RFC 1123).
  • "request" β€” The request line as it came from the client (RFC 1945).
  • status β€” The HTTP status code returned to the client (RFC 1945).
  • bytes β€” The content-length of the document transferred.

The combined format is one line looking like:

remotehost rfc931 authuser [date] "request" status bytes "referer" "user_agent"

and on top of everything above, you also get:

  • "referer" β€” The URL the client was on before requesting the URL (if it could not be determined, a minus sign is placed in this field).
  • "user_agent" β€” The software the client claims to be using (if it could not be determined, a minus sign is placed in this field).

This affects the access logs written by mod_log and mod_disk_log. no cap. ✨

  • {error_log_format, pretty | compact} β€” Default is pretty. If the error log is meant to be read directly by a human, pretty is the best option. πŸ’–

pretty has a format corresponding to:

io:format("[~s] ~s, reason: ~n ~p ~n~n", [Date, Msg, Reason]).

compact has a format corresponding to:

io:format("[~s] ~s, reason: ~w ~n", [Date, Msg, Reason]).

This affects the error logs written by mod_log and mod_disk_log.


🌸 URL Aliasing Properties - Requires mod_alias 🌸

  • {alias, {Alias, RealName}} β€” Alias = string() and RealName = string(). alias allows documents to be stored in the local file system instead of the document_root location. URLs with a path beginning with url-path is mapped to local files beginning with directory-filename, for example:
{alias, {"/image", "/ftp/pub/image"}}

Access to http://your.server.org/image/foo.gif would refer to the file /ftp/pub/image/foo.gif. iconic behavior tbh. πŸ¦‹

  • {re_write, {Re, Replacement}} β€” Re = string() and Replacement = string(). re_write allows documents to be stored in the local file system instead of the document_root location. URLs are rewritten by re:replace/3 to produce a path in the local file-system, for example:
{re_write, {"^/[~]([^/]+)(.*)$", "/home/\\1/public\\2"}}

Access to http://your.server.org/~bob/foo.gif would refer to the file /home/bob/public/foo.gif. regex girlies rise 🧚

  • {directory_index, [string()]} β€” directory_index specifies a list of resources to look for if a client requests a directory using a / at the end of the directory name. file depicts the name of a file in the directory. Several files can be given, in which case the server returns the first it finds, for example:
{directory_index, ["index.html", "welcome.html"]}

Access to http://your.server.org/docs/ would return http://your.server.org/docs/index.html or http://your.server.org/docs/welcome.html if index.html does not exist. πŸ’–


πŸŽ€ CGI Properties - Requires mod_cgi πŸŽ€

NOTE: mod_cgi and mod_actions are deprecated since OTP 29 and will be removed in OTP 30. Use mod_esi instead for dynamic page generation. fr fr do not build new stuff on these bestie πŸ’€
  • {script_alias, {Alias, RealName}} β€” Alias = string() and RealName = string(). Have the same behavior as property alias, except that they also mark the target directory as containing CGI scripts. URLs with a path beginning with url-path are mapped to scripts beginning with directory-filename, for example:
{script_alias, {"/cgi-bin/", "/web/cgi-bin/"}}

Access to http://your.server.org/cgi-bin/foo would cause the server to run the script /web/cgi-bin/foo.

NOTE: When using script_alias with directory-based authentication (see directory), ensure that authentication rules reference the actual filesystem path (RealName), not the URL path (Alias). The server correctly resolves script_alias paths for authentication checks. πŸ‘‘
  • {script_re_write, {Re, Replacement}} β€” Re = string() and Replacement = string(). Have the same behavior as property re_write, except that they also mark the target directory as containing CGI scripts. URLs with a path beginning with url-path are mapped to scripts beginning with directory-filename, for example:
{script_re_write, {"^/cgi-bin/(\\d+)/", "/web/\\1/cgi-bin/"}}

Access to http://your.server.org/cgi-bin/17/foo would cause the server to run the script /web/17/cgi-bin/foo.

  • {script_nocache, boolean()} β€” If script_nocache is set to true, the HTTP server by default adds the header fields necessary to prevent proxies from caching the page. Generally this is preferred. Default to false.
  • {script_timeout, integer()} β€” The time in seconds the web server waits between each chunk of data from the script. If the CGI script does not deliver any data before the timeout, the connection to the client is closed. Default is 15. ⏰
  • {action, {MimeType, CgiScript}} - requires mod_actions β€” MimeType = string() and CgiScript = string(). action adds an action activating a CGI script whenever a file of a certain MIME type is requested. It propagates the URL and file path of the requested document using the standard CGI PATH_INFO and PATH_TRANSLATED environment variables.

Example:

{action, {"text/plain", "/cgi-bin/log_and_deliver_text"}}
NOTE: mod_cgi and mod_actions are deprecated since OTP 29 and will be removed in OTP 30. Use mod_esi instead for dynamic page generation. πŸ’€
  • {script, {Method, CgiScript}} - requires mod_actions β€” Method = string() and CgiScript = string(). script adds an action activating a CGI script whenever a file is requested using a certain HTTP method. The method is either GET or POST, as defined in RFC 1945. It propagates the URL and file path of the requested document using the standard CGI PATH_INFO and PATH_TRANSLATED environment variables.

Example:

{script, {"PUT", "/cgi-bin/put"}}
NOTE: mod_cgi and mod_actions are deprecated since OTP 29 and will be removed in OTP 30. Use mod_esi instead for dynamic page generation. (yes again bestie, they really want u to know 😭)

✨ ESI Properties - Requires mod_esi ✨

  • {erl_script_alias, {URLPath, [AllowedModule]}} β€” URLPath = string() and AllowedModule = atom(). erl_script_alias marks all URLs matching url-path as erl scheme scripts. A matching URL is mapped into a specific module and function, for example:
{erl_script_alias, {"/cgi-bin/example", [httpd_example]}}

A request to http://your.server.org/cgi-bin/example/httpd_example:yahoo would refer to httpd_example:yahoo/3 or, if that does not exist, httpd_example:yahoo/2 and http://your.server.org/cgi-bin/example/other:yahoo would not be allowed to execute. gatekeeping at its finest πŸšͺ

  • {erl_script_nocache, boolean()} β€” If erl_script_nocache is set to true, the server adds HTTP header fields preventing proxies from caching the page. This is generally a good idea for dynamic content, as the content often varies between each request. Default is false.
  • {erl_script_timeout, integer()} β€” If erl_script_timeout sets the time in seconds the server waits between each chunk of data to be delivered through mod_esi:deliver/2. Default is 15. This is only relevant for scripts that use the erl scheme.

πŸ’œ Log Properties - Requires mod_log πŸ’œ

  • {error_log, path()} β€” Defines the filename of the error log file to be used to log server errors. If the filename does not begin with a slash (/), it is assumed to be relative to the server_root.
  • {security_log, path()} β€” Defines the filename of the access log file to be used to log security events. If the filename does not begin with a slash (/), it is assumed to be relative to the server_root.
  • {transfer_log, path()} β€” Defines the filename of the access log file to be used to log incoming requests. If the filename does not begin with a slash (/), it is assumed to be relative to the server_root.

🌈 Disk Log Properties - Requires mod_disk_log 🌈

  • {disk_log_format, internal | external} β€” Defines the file format of the log files. See disk_log for details. If the internal file format is used, the log file is repaired after a crash. When a log file is repaired, data can disappear. When the external file format is used, httpd does not start if the log file is broken. Default is external.
heads up bestie: with internal, data can literally vanish on repair. with external, a broken log file means httpd will not start at all. pick your chaos 🌸
  • {error_disk_log, path()} β€” Defines the filename of the (disk_log) error log file to be used to log server errors. If the filename does not begin with a slash (/), it is assumed to be relative to the server_root.
  • {error_disk_log_size, {MaxBytes, MaxFiles}} β€” MaxBytes = integer() and MaxFiles = integer(). Defines the properties of the (disk_log) error log file. This file is of type wrap log and max bytes is written to each file and max files is used before the first file is truncated and reused.
  • {security_disk_log, path()} β€” Defines the filename of the (disk_log) access log file logging incoming security events, that is, authenticated requests. If the filename does not begin with a slash (/), it is assumed to be relative to the server_root.
  • {security_disk_log_size, {MaxBytes, MaxFiles}} β€” MaxBytes = integer() and MaxFiles = integer(). Defines the properties of the disk_log access log file. This file is of type wrap log and max bytes is written to each file and max files is used before the first file is truncated and reused.
  • {transfer_disk_log, path()} β€” Defines the filename of the (disk_log) access log file logging incoming requests. If the filename does not begin with a slash (/), it is assumed to be relative to the server_root.
  • {transfer_disk_log_size, {MaxBytes, MaxFiles}} β€” MaxBytes = integer() and MaxFiles = integer(). Defines the properties of the disk_log access log file. This file is of type wrap log and max bytes is written to each file and max files is used before the first file is truncated and reused. πŸŽ€

πŸ‘‘ Authentication Properties - Requires mod_auth πŸ‘‘

{directory, {path(), [{property(), term()}]}}

The properties for directories are as follows: πŸ‘‡

  • {allow_from, all | [RegxpHostString]} β€” lists the hosts that are allowed to get into a given directory, like a lil VIP list bestie. Example:
{allow_from, ["123.34.56.11", "150.100.23"]}

so the host 123.34.56.11 and every single machine on the 150.100.23 subnet get the green light. 🎟️

  • {deny_from, all | [RegxpHostString]} β€” the opposite energy: names the hosts that are not allowed into a given directory. Example:
{deny_from, ["123.34.56.11", "150.100.23"]}

so the host 123.34.56.11 and all machines on the 150.100.23 subnet are locked out. 🚫

  • {auth_type, plain | dets | mnesia} β€” picks which authentication database this directory uses. The big difference between the methods: dynamic data can actually be saved when you use Mnesia and Dets. ✨
  • {auth_user_file, path()} β€” names the file holding the user + password list for user auth. The filename can be absolute or relative to the server_root. If you're on the plain storage method, this file is a plain text file where each line is a username, then a colon, then the non-encrypted password. If usernames get duplicated, the behavior is undefined (so like, don't πŸ™ˆ).

Example:

ragnar:s7Xxv7
edward:wwjau8

If you're on the Dets storage method instead, the user database is maintained by Dets and you must not edit it by hand β€” use the API functions in module mod_auth to create/edit the user database. This directive is ignored if the Mnesia storage method is used. And for security reasons, make sure auth_user_file lives outside the document tree of the web server β€” because if it's sitting in the very directory it protects, clients can just download it. 😭

  • {auth_group_file, path()} β€” names the file holding the user group list for user auth. The filename can be absolute or relative to the server_root. On the plain storage method, the group file is a plain text file where each line is a group name, then a colon, then the members' usernames separated by spaces.

Example:

group1: bob joe ante

If you're using the Dets storage method, the group database is maintained by Dets and must not be edited by hand β€” use the API for module mod_auth to create/edit the group database. This directive is ignored if the Mnesia storage method is used. And for security reasons, make sure auth_group_file is stored outside the document tree of the web server. If it's in the directory it protects, clients can download it. πŸ’€

  • {auth_name, string()} β€” sets the name of the authorization realm (auth-domain) for a directory. This string is basically the heads-up to the client about which username and password to use. πŸͺͺ
  • {auth_access_password, string()} β€” if this is set to anything other than "NoPassword", the password is required for all API calls. If the password is set to "DummyPassword", it must be changed before any other API calls happen. To secure the authenticating data, you have to change the password after the web server is started β€” otherwise it gets written in clear text in the configuration file. πŸ‘€
  • {require_user, [string()]} β€” defines the users granted access to a given directory using a secret password. 🀫
  • {require_group, [string()]} β€” defines the users granted access to a given directory using a secret password. πŸ‘―

πŸ” Security Properties β€” Requires mod_security

{security_directory, {path(), [{property(), term()}]}}

The properties for the security directories are as follows:

  • {data_file, path()} β€” the name of the security data file. The filename can be absolute or relative to the server_root. This file stores persistent data for module mod_security. πŸ’Ύ
  • {max_retries, integer()} β€” how many attempts at authenticating a user are allowed before that user gets blocked out. If a user successfully authenticates while blocked, they get a 403 (Forbidden) response from the server. If the user makes a failed attempt while blocked, the server returns 401 (Unauthorized) β€” for security reasons. Default is 3. Can be set to infinity. πŸ”₯
  • {block_time, integer()} β€” how many minutes a user stays blocked. Once that time has passed, the user automatically regains access. Default is 60. ⏳
  • {fail_expire_time, integer()} β€” how many minutes a failed user authentication is remembered for. If a user authenticates after this time has passed, the previous failed authentications are forgotten (clean slate, love that for them ✨). Default is 30.
  • {auth_timeout, integer()} β€” how many seconds a successful user authentication is remembered. After this time has passed, the authentication is no longer reported. Default is 30.

πŸ› οΈ Web server API data types

The Erlang web server API data types are as follows:

ModData = #mod{}

-record(mod, {
    data = [],
    socket_type = ip_comm,
    socket,
    config_db,
    method,
    absolute_uri,
    request_uri,
    http_version,
    request_line,
    parsed_header = [],
    entity_body,
    connection
}).

To access the record in your callback-module use:

-include_lib("inets/include/httpd.hrl").

The fields of record mod have the following meaning:

  • data β€” type [{InteractionKey,InteractionValue}], used to propagate data between modules. Depicted interaction_data() in function type declarations. 🫱🫲
  • socket_type β€” socket_type() indicates whether it's an IP socket or an ssl socket.
  • socket β€” the socket, in format ip_comm or ssl, depending on socket_type. πŸ”Œ
  • config_db β€” the config file directives stored as key-value tuples in an ETS table. Depicted config_db() in function type declarations.
  • method β€” type "GET" | "POST" | "HEAD" | "TRACE", that is, the HTTP method.
  • absolute_uri β€” if the request is an HTTP/1.1 request, the URI can be in the absolute URI format. In that case, httpd saves the absolute URI in this field. An example of an absolute URI is "http://ServerName:Part/cgi-bin/find.pl?person=jocke".
  • request_uri β€” the Request-URI as defined in RFC 1945, for example, "/cgi-bin/find.pl?person=jocke".
  • http_version β€” the HTTP version of the request, that is, "HTTP/1.0", or "HTTP/1.1".
  • request_line β€” the Request-Line as defined in RFC 1945, for example, "GET /cgi-bin/find.pl?person=jocke HTTP/1.0".
  • parsed_header β€” type [{HeaderKey,HeaderValue}]. parsed_header contains all HTTP header fields from the HTTP request, stored in a list as key-value tuples. See RFC 2616 for a listing of all header fields. For example, the date field is stored as {"date","Wed, 15 Oct 1997 14:35:17 GMT"}. RFC 2616 defines that HTTP is a case-insensitive protocol and the header fields can be in lower case or upper case β€” httpd makes sure all header field names are in lower case. πŸ’…
  • entity_body β€” the entity-Body as defined in RFC 2616, for example, data sent from a CGI script using the POST method.
  • connection β€” true | false. If set to true, the connection to the client is a persistent connection and is not closed when the request is served. 🀝

πŸ‘€ See also

RFC 2616, inets, ssl


🧬 DATA TYPES

property() :: atom().

socket_type() :: ip_comm | ssl.

✨ FUNCTIONS ✨

okay bestie, buckle up, this is the part where we actually do stuff πŸŽ€ These are the functions you call. No cap, some of these are iconic and one of them is deprecated (we'll get there, I'll be dramatic about it).


🌸 info(Pid, Properties) -> HttpInformation

info(Pid, Properties) -> HttpInformation
              when
                  Pid :: pid(),
                  Properties :: [atom()],
                  HttpInformation ::
                      [CommonOption] |
                      [CommunicationOption] |
                      [ModOption] |
                      [LimitOption] |
                      [AdminOption],
                  CommonOption ::
                      {port, non_neg_integer()} |
                      {server_name, string()} |
                      {server_root, Path} |
                      {document_root, Path},
                  CommunicationOption ::
                      {bind_address,
                       inet:ip_address() | inet:hostname() | any} |
                      {profile, atom()} |
                      {socket_type,
                       ip_comm |
                       {ip_comm, ssl:tls_option() | gen_tcp:option()} |
                       {ssl, ssl:tls_option() | gen_tcp:option()}} |
                      {ipfamily, inet | inet6} |
                      {minimum_bytes_per_second, integer()},
                  ModOption :: {modules, atom()},
                  LimitOption ::
                      {customize, atom()} |
                      {disable_chunked_transfer_encoding_send,
                       boolean()} |
                      {keep_alive, boolean()} |
                      {keep_alive_timeout, integer() | infinity} |
                      {max_body_size, integer()} |
                      {request_timeout, pos_integer() | infinity} |
                      {max_clients, integer()} |
                      {max_header_size, integer()} |
                      {max_content_length, integer()} |
                      {max_uri_size, integer()} |
                      {max_keep_alive_request, integer()} |
                      {max_client_body_chunk, integer()},
                  AdminOption ::
                      {mime_types,
                       [{MimeType :: string(), Extension :: string()}] |
                       Path} |
                      {mime_type, string()} |
                      {server_admin, string()} |
                      {server_tokens,
                       none | prod | major | minor | minimal | os |
                       full |
                       {private, string()}} |
                      {logger, Options :: list()} |
                      {log_format, common | combined} |
                      {error_log_format, pretty | compact};
              (Address, Port) -> HttpInformation
                  when
                      Address :: inet:ip_address(),
                      Port :: integer(),
                      Path :: file:name_all(),
                      HttpInformation ::
                          [CommonOption] |
                          [CommunicationOption] |
                          [ModOption] |
                          [LimitOption] |
                          [AdminOption],
                      CommonOption ::
                          {port, non_neg_integer()} |
                          {server_name, string()} |
                          {server_root, Path} |
                          {document_root, Path},
                      CommunicationOption ::
                          {bind_address,
                           inet:ip_address() | inet:hostname() | any} |
                          {profile, atom()} |
                          {socket_type,
                           ip_comm |
                           {ip_comm, ssl:tls_option() | gen_tcp:option()} |
                           {ssl, ssl:tls_option() | gen_tcp:option()}} |
                          {ipfamily, inet | inet6} |
                          {minimum_bytes_per_second, integer()},
                      ModOption :: {modules, atom()},
                      LimitOption ::
                          {customize, atom()} |
                          {disable_chunked_transfer_encoding_send,
                           boolean()} |
                          {keep_alive, boolean()} |
                          {keep_alive_timeout, integer() | infinity} |
                          {max_body_size, integer()} |
                          {request_timeout, pos_integer() | infinity} |
                          {max_clients, integer()} |
                          {max_header_size, integer()} |
                          {max_content_length, integer()} |
                          {max_uri_size, integer()} |
                          {max_keep_alive_request, integer()} |
                          {max_client_body_chunk, integer()},
                      AdminOption ::
                          {mime_types,
                           [{MimeType :: string(), Extension :: string()}] |
                           Path} |
                          {mime_type, string()} |
                          {server_admin, string()} |
                          {server_tokens,
                           none | prod | major | minor | minimal | os |
                           full |
                           {private, string()}} |
                          {logger, Options :: list()} |
                          {log_format, common | combined} |
                          {error_log_format, pretty | compact}.

Fetches information about the HTTP server. πŸ’– It's basically the "hey what's your deal rn" function.

  • Call it with only the pid and it fetches all the properties. Everything. The whole vibe. No filter, no chill.
  • Call it with a list of specific properties and it fetches just those, bestie. Picky, and we love that for you.

The available properties are the same as the start options of the server. Like, literally the same list you'd start it with, so iykyk 🫢

NOTE: Pid is the pid returned from inets:start/[2,3]. You can also get it from inets:services/0 and inets:services_info/0 β€” go see inets for the deets. πŸ”

πŸ¦‹ info(Address, Port, Profile, Properties) -> HttpInformation

info(Address, Port, Profile, Properties) -> HttpInformation
              when
                  Address :: inet:ip_address() | any,
                  Port :: integer(),
                  Profile :: atom(),
                  Properties :: [atom()],
                  Path :: file:name_all(),
                  HttpInformation ::
                      [CommonOption] |
                      [CommunicationOption] |
                      [ModOption] |
                      [LimitOption] |
                      [AdminOption],
                  CommonOption ::
                      {port, non_neg_integer()} |
                      {server_name, string()} |
                      {server_root, Path} |
                      {document_root, Path},
                  CommunicationOption ::
                      {bind_address,
                       inet:ip_address() | inet:hostname() | any} |
                      {profile, atom()} |
                      {socket_type,
                       ip_comm |
                       {ip_comm, ssl:tls_option() | gen_tcp:option()} |
                       {ssl, ssl:tls_option() | gen_tcp:option()}} |
                      {ipfamily, inet | inet6} |
                      {minimum_bytes_per_second, integer()},
                  ModOption :: {modules, atom()},
                  LimitOption ::
                      {customize, atom()} |
                      {disable_chunked_transfer_encoding_send,
                       boolean()} |
                      {keep_alive, boolean()} |
                      {keep_alive_timeout, integer() | infinity} |
                      {max_body_size, integer()} |
                      {request_timeout, pos_integer() | infinity} |
                      {max_clients, integer()} |
                      {max_header_size, integer()} |
                      {max_content_length, integer()} |
                      {max_uri_size, integer()} |
                      {max_keep_alive_request, integer()} |
                      {max_client_body_chunk, integer()},
                  AdminOption ::
                      {mime_types,
                       [{MimeType :: string(), Extension :: string()}] |
                       Path} |
                      {mime_type, string()} |
                      {server_admin, string()} |
                      {server_tokens,
                       none | prod | major | minor | minimal | os |
                       full |
                       {private, string()}} |
                      {logger, Options :: list()} |
                      {log_format, common | combined} |
                      {error_log_format, pretty | compact}.

Fetches information about the HTTP server. Same energy, different door πŸ’…

  • Call it with only Address and Port and boom, all the properties get fetched. The full tea β˜•οΈ
  • Call it with a list of specific properties and you get exactly those. Curated. Main character behavior only.

The available properties are, again, the same as the start options of the server. Consistency, periodt. ✨

NOTE: The Address must be the IP address and cannot be the hostname. Like, do not try it with a hostname, it will not go the way you want it to, ngl. 🚫

πŸŽ€ parse_query(QueryString) -> QueryList | uri_string:error()

parse_query(QueryString) -> QueryList | uri_string:error()
                            when
                                QueryString :: string(),
                                QueryList ::
                                    [{unicode:chardata(),
                                      unicode:chardata() | true}].
Deprecated: httpd:parse_query/1 is deprecated, bestie β€” use uri_string:dissect_query/1 instead. 😭 It's giving "still here but we don't talk about her".

parse_query/1 parses incoming data to erl and eval scripts (see mod_esi) as defined in the standard URL format. So it's doing the classics:

  • '+' becomes 'space' πŸ‘€
  • and it decodes hexadecimal characters (%xx) πŸ”’

πŸ’œ reload_config(Config, Mode) -> ok | {error, Reason} | no_return()

reload_config(Config, Mode) -> ok | {error, Reason} | no_return()
                        when
                            Config :: file:name_all() | [{Option, Value}],
                            Mode :: non_disturbing | disturbing | blocked,
                            Option :: atom(),
                            Value :: term(),
                            Reason :: term().

Reloads the HTTP server configuration without restarting the server. ✨ Glow-up in place, no reboot required, we LOVE a transformation arc.

While the reload is happening, incoming requests get answered with a temporary down message during the reload time. So like, hold please, she's changing πŸ™ˆ

NOTE: Available properties are the same as the start options of the server, but the properties bind_address and port cannot be changed. Those two are locked, no negotiation, that's just the rules. πŸ”’

And now, the modes β€” pick your fighter:

  • disturbing β€” the server gets blocked forcefully, all ongoing requests terminate, and the reload starts immediately. Brutal. No survivors. πŸ’€
  • non-disturbing β€” no new connections are accepted, but ongoing requests are allowed to complete before the reload is done. Gentle queen energy, everyone finishes their sentence first 🫢
  • blocked β€” no explanation given for this one, it's just sitting there in the list like πŸ‘‘ (it's a Mode value, that's all the page says, I'm not making things up for you bestie)

πŸ’– CALLBACKS πŸ’–


do(ModData) ✨

okay so when a valid request actually reaches httpd, it calls do/1 in every module, and which modules those are is decided by the configuration option of Module. bestie, this function is where the magic happens: it can generate data for other modules, or generate a response that gets sent straight back to the client. 🫢

The field data in ModData is a list. Specifically, it's the list returned from the last call to do/1. so it's like the baton being passed around the relay race of your modules πŸƒβ€β™€οΈ

Body is the body of the HTTP response that gets sent back to the client. An appropriate header is appended to the message. πŸ’…

StatusCode is the status code of the response β€” go peep RFC 2616 for the appropriate values. πŸ‘‘

Head is a key value list of HTTP header fields. The server constructs an HTTP header from this data. See RFC 2616 for the appropriate value for each header field. And listen: if the client is an HTTP/1.0 client, the server filters the list so that only HTTP/1.0 header fields are sent back to the client. no cap, it's doing a whole vibe check on your headers. 🌈

If Body is returned and equal to {Fun,Arg}, the web server tries apply/2 on Fun with Arg as argument. The web server expects that the fun either returns a list (Body) that is an HTTP response, or the atom sent if the HTTP response is sent back to the client. And if close is returned from the fun? 😭 something has gone wrong and the server signals this to the client by closing the connection. literally the server hanging up the phone on them.

NOTE: It is strongly advised to use NewDataFormat in the return value of do/1 β€” it relies on a newer mechanism for parsing and sending headers, provides more accurate status codes, and supports a wider range of Body formats. bestie please use NewDataFormat, it's giving main character energy and the old way is not it. πŸ™ˆ

remove(ConfigDB) πŸŽ€

When httpd is shut down, it tries to execute remove/1 in each Erlang web server callback module. The programmer can use this function to clean up resources created in the store function. it's the "okay bye, let me tidy up before I go" function 🧹✨


store/2 πŸ¦‹

Checks the validity of the configuration options before saving them in the internal database. This function can also have a side effect, that is, setup of necessary extra resources implied by the configuration option. It can also resolve possible dependencies among configuration options by changing the value of the option. And this function only needs clauses for the options implemented by this particular callback module β€” no need to overcommit, bestie, just do your part. πŸ’œ


and that's a wrap on httpd(3) fr fr πŸ’– this one's from Ericsson AB, inets 9.7.2, and it's dated httpd(3) β€” go forth and callback responsibly, you absolute icon πŸ‘‘βœ¨

πŸ“¦ where this page comes from