libstd/http
An HTTP/1.1 server: routes that map a path to a TryC function, static files read from a base directory, custom error pages, middleware, cookies, sessions shared by all workers, keep-alive and pipelining. On Linux a supervisor process starts one worker per setNumCoworker, each serving many connections at once with epoll on non-blocking sockets, and replaces any worker that crashes. A bad request, a client that disappears or a slow client costs at most its own connection, never a worker. The server that serves this documentation is written with it (esempio/server.tryc).
#include <libstd/http>
Includes libstd/mem, libstd/random, libstd/cpuinfo, libstd/net, libstd/stdio, libstd/string, libstd/file, libstd/dict, libstd/list, libstd/process, libstd/sync, libstd/type, libstd/time. Cookies and sessions are two parts of it, with their own pages: libstd/http/cookies and libstd/http/session.
Example
#include <libstd/http>
#include <libstd/cpuinfo>
def home(self: HttpServer, req: HttpRequest) -> str:
return self.page(req, "index.html")
def hello(self: HttpServer, req: HttpRequest) -> str:
req.content_type = "text/plain"
return "hello " + req.getQuery() + "\n"
def log_requests(self: HttpServer, req: HttpRequest) -> HttpRequest:
if req.phase == HTTP_PHASE_AFTER:
print(req.getAction() + " " + req.getPath() + " -> " + itoa(req.status) + "\n")
return req
server = HttpServer(127, 0, 0, 1, 8000)
server.setBaseDir("./templates")
server.addMapsFunction("/", home)
server.addMapsFunction("/hello", hello)
server.addMapFile("/favicon.ico", "img/favicon.ico")
server.addMapCss("/style.css", "css/style.css")
server.setErrorPage(404, "404.html")
server.addMiddleWare("log", log_requests)
server.setNumCoworker(logical_cpu_count() as long)
server.run()
Routes and responses
A route maps an exact path to a function &(HttpServer, HttpRequest) -> str, passed by name to addMapsFunction. The string it returns is the response body. The response starts as 200 with Content-Type: text/html; charset=utf-8; the function changes either by setting req.status or req.content_type before it returns:
def new_item(self: HttpServer, req: HttpRequest) -> str:
if req.getAction() != "POST":
req.status = 405
return "use POST\n"
req.status = 201
req.content_type = "text/plain"
return "stored " + itoa(strlen(req.body)) + " bytes\n"
- The path is matched exactly and as sent, without percent-decoding:
/doc/home/and/doc/homeare two different routes. The query string is not part of the path:/hello?x=1reaches/hello, andreq.getQuery()returnsx=1. addMapCss,addMapJsandaddMapFileserve a file from disk, read at every request (see Site files and error pages below). If the file is missing the answer is404; the worker keeps running.- A path with no route gets
404and the page ofsetErrorPage(404, file), or the bodyerror404, page not found!if there is none, unless a middleware writes another one. - A
HEADrequest runs the same route and gets the same headers, without the body. - Bodies are binary-safe: a route can return the bytes of a PNG or an icon (
readfilekeeps the exact length), andreq.bodycan contain any byte. - A route that calls
readfileon a file that does not exist stops its worker (readfileexits on error). The supervisor starts a new one, but the client gets no answer.self.page(req, name)answers404instead.
The request is in the HttpRequest: getAction() (the method, GET, POST, ...), getPath(), getQuery(), getVersion(), getHeader(name) (any case, "" if absent), req.cookies (see Cookies below), and req.body, the request body (its length is the request's Content-Length).
Site files and error pages
setBaseDir(dir) sets the directory that holds the site's files, like BASE_DIR in Django. Every relative file name given to addMapCss, addMapJs, addMapFile, setErrorPage and page is looked up inside it; an absolute one (/srv/site/a.css, C:\site\a.css) is used as it is, as with Python's os.path.join. Without a base directory, relative names start from the working directory of the process. The path is built at every request, so setBaseDir can come before or after the other calls.
As in Django, pages and static files can live in two directories of their own, both relative to the base directory: setBaseDirTemplate(dir) for the names given to page and setErrorPage (Django's template directory), setBaseDirStatic(dir) for the files of addMapCss, addMapJs and addMapFile (Django's STATIC_ROOT). Each setter stores the directory as given; getBaseDirTemplate() and getBaseDirStatic() return it joined to the base directory, so the order of the calls does not matter here either. Left unset, both are the base directory itself.
run() checks the three directories before it binds the port (is_dir from libstd/file): one that does not exist, or is a file, prints http: setBaseDirStatic: site/statik non e' una cartella and exits with 1. A typo, or a server started from the wrong working directory, shows up at start instead of as a 404 on every request. The check runs once the configuration is complete, so the order of the calls still does not matter. It does not look at the single files: a file registered with addMapFile and then moved still gets a 404.
addMapFile(path, file)serves any file at an exact path, with theContent-Typeof its extension (http_guess_content_type). The request path never becomes part of a file name: each path serves only the file registered for it, so/img/../server.trycis just a path with no route.self.page(req, name)reads a file of the template directory for a route:return self.page(req, "index.html"). The name cannot leave the template directory: an absolute name, or one with a..part (with/or\), is treated as a missing file. A missing file setsreq.statusto404and returns"", and the worker keeps running. TheContent-Typestays the route's own,text/htmlunless the route sets another.setErrorPage(status, file), for a status from 400 to 599, chooses the body of the responses with that status and an empty body: a path with no route, a static file that cannot be read,pageon a missing file, a route that setsreq.statusand returns"". A route that returns its own text keeps it. The page gets theContent-Typeof its extension and is read again at every response; if it cannot be read, a404falls back toerror404, page not found!. Error pages do not apply to the answers the server sends by itself to malformed requests (see Limits and errors).
server.setBaseDir("/srv/site")
server.setBaseDirTemplate("templates") // /srv/site/templates
server.setBaseDirStatic("static") // /srv/site/static
server.addMapFile("/img/logo.svg", "img/logo.svg")
server.setErrorPage(404, "errors/404.html")
server.setErrorPage(403, "errors/403.html")
def admin(self: HttpServer, req: HttpRequest) -> str:
if not req.sessionHas("admin"):
req.status = 403
return ""
return self.page(req, "admin.html")
Cookies
Every request has a Cookies object in req.cookies. get(name) and has(name) read the cookies the browser sent. set(name, value, max_age, flags) and remove(name) add Set-Cookie headers to the response, with HttpOnly and SameSite=Lax unless the flags say otherwise. Routes and middleware, in both phases, use them the same way. Lifetimes, flags, validation and examples are in libstd/http/cookies.
Response headers
req.setResponseHeader(name, value) adds a header to one response, from a route or a middleware in either phase. A second call with the same name, in any case, replaces the first. req.hasResponseHeader(name) tells whether the response already has one. server.setDefaultHeader(name, value) adds a header to every response of the server. Call it before run(). Its lines are written once, when it is called, and copied into each response as they are, so a default header costs nothing per request. A route that sets the same name with setResponseHeader replaces the default for its own response. hasResponseHeader does not see the defaults.
def report(self: HttpServer, req: HttpRequest) -> str:
req.setResponseHeader("Cache-Control", "no-store")
return self.page(req, "report.html")
server.setDefaultHeader("X-Content-Type-Options", "nosniff")
Both return 1 when the header is added, or 0 when they refuse it. They refuse:
- a name that is not a token (letters, digits and
!#$%&'*+-.^_`|~); - the headers the library writes itself:
Content-Type,Content-Length,Connection,Transfer-Encoding,Set-CookieandLocation. Usereq.content_type,req.cookiesandreq.redirectinstead; - a value with a control character other than tab. A line break would end the header, and a value copied from the request could then add headers or a body to the response (response splitting).
The error responses the server sends without a route (400, 408, 413, 431, 501) carry no added headers.
libstd/http/security turns on the browser security headers with one call before run():
#include <libstd/http>
#include <libstd/http/security>
http_security_headers(server)
| Header | Value | Effect |
|---|---|---|
X-Content-Type-Options | nosniff | The browser uses the Content-Type it receives instead of guessing it from the content. |
X-Frame-Options | DENY | No site can show the pages in a frame (clickjacking). For old browsers. |
Content-Security-Policy | frame-ancestors 'none' | The same, for current browsers. A CSP in a <meta http-equiv> tag cannot contain frame-ancestors; it applies together with this one. |
Referrer-Policy | strict-origin-when-cross-origin | Other sites get only the domain of the page that links them, not its path. |
Permissions-Policy | camera=(), microphone=(), geolocation=() | Turns off the camera, the microphone and geolocation. |
A route that sends its own Content-Security-Policy replaces the default one, so it must include frame-ancestors itself. Strict-Transport-Security is not set: it only means something over HTTPS, which ends at the reverse proxy, so it belongs there. These headers are server defaults, not a middleware: in a one-worker test, a middleware that added the same five headers to every response cut throughput by 20-37%, while the defaults cost about 2%.
Middleware
A middleware is a function &(HttpServer, HttpRequest) -> HttpRequest registered with a name. Every request goes through each middleware twice:
req.phase == HTTP_PHASE_BEFORE: before the route, in the order the middleware were added. It can read and change the request (for example rewritereq.path).req.phase == HTTP_PHASE_AFTER: after the route, in the opposite order.req.status,req.content_typeandreq.response_bodyalready hold the response and can still be changed (add a footer, replace an error page, log the status).
It returns the request it was given, or another one. delMiddleWare(name) removes it.
Sessions
A session keeps data on the server for one browser, across requests; the browser only holds a random id in the sid cookie, and the data lives in one table shared by all the workers. Turn sessions on before run(), then use them from any route or middleware through the request:
def profile(self: HttpServer, req: HttpRequest) -> str:
if not req.sessionHas("user"):
req.status = 401
return "log in first\n"
return "hello " + req.sessionGet("user") + "\n"
server.enableSessions(1000 as long)
libstd/http/session explains how sessions are created, saved and expire, and what happens when a worker dies. It also has complete examples: login and logout, a protected section, a shopping cart, CSRF tokens and messages shown once.
Workers and the supervisor
run() binds the address, starts ncoworker worker processes (at least one) with fork, and never returns. The process that called it becomes the supervisor: it serves no request, it waits for its workers.
- One worker per CPU is the right number: a worker serves many connections at once, so more workers than CPUs only add processes.
setNumCoworker(logical_cpu_count() as long)(fromlibstd/cpuinfo) does that. - Load balancing (Linux). Each worker opens its own listening socket on the same port with
SO_REUSEPORT, and the kernel spreads new connections across them. A worker keeps a connection until it closes. - A worker that crashes (a failed bounds check, a
SIGSEGV, anexitin a route) is replaced at once. If it held the lock of the session table, the supervisor first repairs the table and frees the lock (seelibstd/http/session). More thanncoworkerrestarts withinHTTP_RESPAWN_WINDOW_MSmeans something kills every worker: the supervisor then waits for the rest of the window before starting the next. - Stopping the server. A worker stopped from outside with
SIGTERMorSIGINTstops the whole server: the supervisor exits, and on Linux each worker receivesSIGTERMwhen its supervisor ends (PR_SET_PDEATHSIG).SIGKILLstops the server only when it kills every worker at once, asfuser -k 8000/tcp(which kills every process holding the port) andpkill -9do. So Ctrl+C,killon the supervisor andfuser -kall stop everything and free the port. - Out of memory. When memory runs out the kernel kills workers with
SIGKILL, sometimes nearly all of them within a few milliseconds, because they grow together. The supervisor waits until no more workers die (rounds ofHTTP_KILL_SETTLE_MS, at mostHTTP_KILL_SETTLE_MAX_MS) and reads the kernel'soom_killcounter in/proc/vmstat: if it grew by at least the number of dead workers, they are replaced, even when all of them died. ASIGKILLthat hits only some of the workers always replaces them. With a single worker, aSIGKILLthat is not an out-of-memory kill stops the server, asfuser -kwould. - Windows has no
epolland noSO_REUSEPORT: the workers share the supervisor's listening socket and each serves one connection at a time, with blocking sockets.
The arena allocator behind new, string + and readfile is global and not thread-safe (see libstd/thread): a thread may not allocate. Every request allocates strings, so the workers are processes, each with its own arena. Routes and middleware run inside a worker and can allocate freely.
Connections and timeouts
An HTTP/1.1 connection stays open after a response (keep-alive) unless the client sends Connection: close; an HTTP/1.0 one only with Connection: keep-alive. A client can also send several requests at once (pipelining): they are answered in order, the next one when the previous response has left. A client that closes its sending side still receives the answers to what it already sent.
Each worker checks its connections every HTTP_SWEEP_MS and closes:
- a connection with no activity for
getIdleTimeout()milliseconds (default 15 s), including one waiting for its next keep-alive request or a client that stopped reading its response; - a connection whose current request has not arrived in full within
getRequestTimeout()milliseconds of its first byte (default 10 s), with a408. A client that sends one byte every few seconds does not hold the connection forever; - a new connection that has sent nothing for
getFirstByteTimeout()milliseconds (default 5 s), without a response. Connections opened and left silent hold a slot for 5 s instead of 15. A browser's speculative connection that stays unused longer is closed too, and the browser opens a new one.
setIdleTimeout(0), setRequestTimeout(0) and setFirstByteTimeout(0) remove the limits. On Windows only the idle limit applies, as the socket's receive timeout.
Limits and errors
A request the server cannot serve gets an error response and its connection is closed:
| Status | When |
|---|---|
400 | Malformed request line or header (a line without :, a space or a control character in a header name, a folded header line, a 0 byte in the headers), a Content-Length that is not a number, or two Content-Length headers. |
408 | The request did not arrive in full within the request timeout. |
413 | The request (headers and body together) is larger than HTTP_MAX_REQUEST bytes (64 KiB). |
431 | More than HTTP_MAX_HEADERS headers (100). |
501 | A Transfer-Encoding header: request bodies sent in chunks are not supported. |
The strict rules on Content-Length, Transfer-Encoding and header names are not pedantry: behind a proxy, a header that the proxy and the server read differently lets a client hide a second request inside the first (request smuggling). Refusing them closes that door.
- Not supported: HTTPS (put the server behind a proxy that terminates TLS), chunked request bodies,
Expect: 100-continue(the client sends the body after a short wait anyway), bodies larger than 64 KiB. - Each worker accepts descriptors below
HTTP_MAX_FDS(4096) and closes the others at once. Before forking,run()raises the soft limit on open descriptors (RLIMIT_NOFILE, 1024 by default on many systems) to 4096, within the hard limit. A worker that still runs out of descriptors accepts each waiting client and closes it at once, through a spare descriptor kept open on/dev/null, instead of spinning onacceptat 100% CPU. Each worker reads every request into one shared 64 KiB buffer. A connection gets a buffer of its own only when part of a request is left at the end of a read (a request split across packets, or pipelined requests waiting behind a response), so an idle connection, silent or keep-alive, only takes its slot. A descriptor closed for more thanHTTP_RBUF_KEEP_MSgives its own buffer back to the arena. - A
Content-Typeset by a route or a middleware that contains a line break is replaced withapplication/octet-stream: a value copied from the request could otherwise add headers to the response. - A session holds at most
HTTP_SESSION_DATA_MAX(416) bytes of data, and at mostenableSessions(n)sessions exist at once. - Only the first
HTTP_MAX_COOKIES(50) cookies of a request are read; the rest of theCookieheader is ignored.
Constants
| Name | Value | Meaning |
|---|---|---|
HTTP_MAX_REQUEST | 65536 | Largest request in bytes, headers and body together; larger ones get 413. |
HTTP_MAX_FDS | 4096 | Connections per worker: a worker closes at once a client whose descriptor is not below this. |
HTTP_MAX_EVENTS | 64 | Events read by one epoll_pwait. |
HTTP_MAX_HEADERS | 100 | Most headers in a request; more get 431. |
HTTP_DEFAULT_SESSION_IDLE_MS | 1800000 | Default idle limit of a session (30 minutes). |
HTTP_DEFAULT_SESSION_MAX_MS | 86400000 | Default maximum lifetime of a session (24 hours). |
HTTP_DEFAULT_BACKLOG | 511 | listen queue when setListen is not called. |
HTTP_DEFAULT_IDLE_TIMEOUT_MS | 15000 | Default of setIdleTimeout, in milliseconds. |
HTTP_DEFAULT_REQUEST_TIMEOUT_MS | 10000 | Default of setRequestTimeout, in milliseconds. |
HTTP_DEFAULT_FIRST_BYTE_TIMEOUT_MS | 5000 | Default of setFirstByteTimeout, in milliseconds. |
HTTP_SWEEP_MS | 1000 | How often a worker looks for expired connections. |
HTTP_RBUF_KEEP_MS | 5000 | How long a closed descriptor keeps its own receive buffer, in milliseconds. |
HTTP_KILL_SETTLE_MS | 100 | After a worker killed by SIGKILL, how long each round waits for the others that die with it. |
HTTP_KILL_SETTLE_MAX_MS | 2000 | The longest the supervisor waits before deciding. |
HTTP_RESPAWN_WINDOW_MS | 1000 | Restarts of crashed workers beyond ncoworker within this window wait for the window to end. |
HTTP_PHASE_BEFORE | 0 | req.phase while a middleware runs before the route. |
HTTP_PHASE_AFTER | 1 | req.phase while a middleware runs after the route. |
HTTP_EINTR | -4 | |
HTTP_EAGAIN | -11 | |
HTTP_EPOLLIN | 1 | |
HTTP_EPOLLOUT | 4 | |
HTTP_EPOLLERR | 8 | |
HTTP_EPOLLHUP | 16 | |
HTTP_EPOLLRDHUP | 8192 | |
HTTP_EPOLLEXCLUSIVE | 268435456 | |
HTTP_EPOLL_CTL_ADD | 1 | |
HTTP_EPOLL_CTL_DEL | 2 | |
HTTP_EPOLL_CTL_MOD | 3 | |
HTTP_O_NONBLOCK | 2048 | |
HTTP_CLOEXEC | 524288 | |
HTTP_EPOLL_EVENT_SIZE | aarch64 16, 12 | |
HTTP_EPOLL_DATA_OFF | aarch64 8, 4 |
The constants of cookies and sessions are on the pages of libstd/http/cookies and libstd/http/session.
Classes
One request, passed to routes and middleware. The request: action (the method), path, query, version, headers (an sdict with lower-case names; read it with getHeader), cookies (the request's Cookies, which also collects the cookies to send back), body, keep_alive. The session: session_id, session_data, session_size, session_flags; use the session* methods instead of the fields. The response, which routes and middleware may change: status, content_type, response_body, and response_headers (fill it with setResponseHeader; its table stays 0 until the first header). phase is the middleware phase. req_http holds the raw headers.
req_http str
size_pack int
fd_sock SOCKET
action str
version str
path str
query str
body str
headers str
cookies Cookies
keep_alive int
bad int
session_on int
session_id str
session_data Sdict
session_size long
session_flags int
status int
content_type str
response_body str
response_headers Sdict
phase int
getSock &HttpRequestGetSock
getVersion &HttpRequestGetVersion
getAction &HttpRequestGetAction
getPath &HttpRequestGetPath
getQuery &HttpRequestGetQuery
getHeader &HttpRequestGetHeader
close &HttpRequestCloseSock
setResponseHeader &HttpRequestSetResponseHeader
hasResponseHeader &HttpRequestHasResponseHeader
sessionId &HttpRequestSessionId
sessionGet &HttpRequestSessionGet
sessionHas &HttpRequestSessionHas
sessionSet &HttpRequestSessionSet
sessionDel &HttpRequestSessionDel
sessionRegenerate &HttpRequestSessionRegenerate
sessionDestroy &HttpRequestSessionDestroyThe server: create it with HttpServer(a, b, c, d, port), configure it with its methods, then call run().
fd_sock SOCKET
saddr_in Sockaddr_in
len_queue int
door int
ip int[4]
map_middleware str
order_middleware List
map_path_function str
map_css_files str
map_js_files str
map_files str
error_pages str
default_headers str
default_header_lines str
base_dir str
template_dir str
static_dir str
ncoworker long
supervisor_pid int
worker_pid int
idle_timeout_ms long
request_timeout_ms long
first_byte_timeout_ms long
now_ms long
sessions str
session_capacity long
session_slots long
session_idle_ms long
session_max_ms long
setNumCoworker &HttpServerSetNumCoworker
getNumCoworker &HttpServerGetNumCoworker
addMiddleWare &HttpServerAddMiddleWare
delMiddleWare &HttpServerDelMiddleWare
addMapsFunction &HttpServerMapsFunctionAdd
delMapsFunction &HttpServerMapsFunctionDel
addMapJs &HttpServerMapsStaticJsAdd
delMapJs &HttpServerMapsStaticJsDel
addMapCss &HttpServerMapsStaticCssAdd
delMapCss &HttpServerMapsStaticCssDel
addMapFile &HttpServerMapsStaticFileAdd
delMapFile &HttpServerMapsStaticFileDel
getBaseDirTemplate &HttpServerGetTemplates
setBaseDirTemplate &HttpServerSetTemplates
getBaseDirStatic &HttpServerGetStatics
setBaseDirStatic &HttpServerSetStatics
setBaseDir &HttpServerSetBaseDir
getBaseDir &HttpServerGetBaseDir
setErrorPage &HttpServerSetErrorPage
setDefaultHeader &HttpServerSetDefaultHeader
page &HttpServerPage
setDoor &HttpServerSetDoor
getDoor &HttpServerGetDoor
getIp &HttpServerGetIp
setIp &HttpServerSetIp
setListen &HttpServerSetListen
getListen &HttpServerGetListen
setIdleTimeout &HttpServerSetIdleTimeout
getIdleTimeout &HttpServerGetIdleTimeout
setRequestTimeout &HttpServerSetRequestTimeout
getRequestTimeout &HttpServerGetRequestTimeout
setFirstByteTimeout &HttpServerSetFirstByteTimeout
getFirstByteTimeout &HttpServerGetFirstByteTimeout
setBind &HttpServerSetBind
enableSessions &HttpServerEnableSessions
setSessionTimeouts &HttpServerSetSessionTimeouts
getSessionCount &HttpServerGetSessionCount
dumpSessions &HttpServerDumpSessions
elaborateReq &HttpRequestElaborateReq
init_workers &HttpServerInitWorkers
own_listener &HttpServerOwnListener
run &HttpServerRun
close &HttpServerCloseSockInternal: the state of one open connection in a worker (receive buffer, response being sent, timestamps for the timeouts).
fd SOCKET
rbuf str
rlen long
wbuf str
wlen long
woff long
close_after int
want_out int
active int
last_ms long
req_start_ms long
eof int
scratch int
fresh intFunctions
The reason phrase of a status code (404 -> "Not Found"), "Unknown" for a code it does not know.
The Content-Type for a file name from its extension (.html, .css, .js, .json, .png, .jpg, .svg, .ico, .pdf, .txt), application/octet-stream otherwise. For routes that serve files: req.content_type = http_guess_content_type(file).
server.setNumCoworker(n): number of worker processes started by run() (at least 1). One per CPU is usually right.server.getNumCoworker(): the number of workers set.server.addMapJs(path, file): serves file as application/javascript at path. A path already mapped is an error: it prints a message and exits.server.delMapJs(path): removes a JavaScript mapping; an unknown path prints a message and exits.server.addMapCss(path, file): serves file as text/css at path. A path already mapped is an error: it prints a message and exits.server.delMapCss(path): removes a CSS mapping; an unknown path prints a message and exits.server.addMapFile(path, file): serves file at path, with the Content-Type of its extension. A relative file is looked up in the base directory. A path already mapped is an error: it prints a message and exits.server.delMapFile(path): removes a file mapping; an unknown path prints a message and exits.server.setBaseDir(dir): the directory where relative file names are looked up; "" (the default) for the working directory.server.getBaseDir(): the base directory, "" if none was set.server.setBaseDirTemplate(dir): the directory of the pages read by page and setErrorPage, relative to the base directory or absolute; "" (the default) for the base directory itself.server.getBaseDirTemplate(): the template directory joined to the base directory.server.setBaseDirStatic(dir): the directory of the files of addMapCss, addMapJs and addMapFile, relative to the base directory or absolute; "" (the default) for the base directory itself.server.getBaseDirStatic(): the static directory joined to the base directory.server.setErrorPage(status, file): the page used as the body of responses with status and an empty body. A status outside 400-599 prints a message and exits.server.setDefaultHeader(name, value): adds a header to every response, or replaces the one with the same name (any case). Call it before run(). Returns 0 and adds nothing for an invalid name, a header the library writes itself or a value with control characters (see Response headers above).self.page(req, name): the content of name in the base directory, to return from a route. A missing file, or a name that would leave the base directory, sets req.status to 404 and returns "".server.addMiddleWare(name, function): adds a middleware &(HttpServer, HttpRequest) -> HttpRequest after the existing ones (see Middleware above). A name already in use prints a message and exits.server.delMiddleWare(name): removes a middleware, keeping the order of the others. An unknown name prints a message and exits.server.elaborateReq(req): runs middleware and route for a parsed request and returns the whole response, headers and body. Called by the workers; useful to test routes without a socket.server.init_workers(): called by run(). Starts the workers and returns their number (1, 2, ...) in each of them; in the supervisor it never returns.server.own_listener(): called by run() in each Linux worker: replaces the inherited listening socket with the worker's own (SO_REUSEPORT).server.run(): checks that the base, template and static directories exist, then binds and listens (on error it prints a message and exits), starts the workers and serves forever. Never returns: in the calling process it runs the supervisor.server.addMapsFunction(path, function): function answers requests for exactly path. Adding the same path again replaces the function.server.delMapsFunction(path): removes a route; nothing happens if there is none.server.getIp(): the address as text, "127.0.0.1".server.setIp(a, b, c, d): the address to listen on; each octet must be 0-255, otherwise it prints a message and exits.server.setDoor(port): the port to listen on (0-65535).server.getDoor(): the port.server.setListen(n): the listen queue of each listening socket (default HTTP_DEFAULT_BACKLOG).server.getListen(): the listen queue.server.setIdleTimeout(ms): closes connections with no activity for ms milliseconds, keep-alive ones included. 0 removes the limit.server.getIdleTimeout(): the idle limit in milliseconds.server.setRequestTimeout(ms): a request must arrive in full within ms milliseconds of its first byte, otherwise the client gets 408 and the connection is closed. 0 removes the limit.server.getRequestTimeout(): the request limit in milliseconds.server.setFirstByteTimeout(ms): closes a new connection that has sent nothing for ms milliseconds. After the first byte the request and idle limits apply. 0 removes the limit. Linux only.server.getFirstByteTimeout(): the first-byte limit in milliseconds.server.setBind(addr): copies family, port and address from a Sockaddr_in prepared by hand.server.close(): closes the server's listening socket.Creates the server on the IPv4 address first.second.third.fourth and door (the port), with the default backlog and timeouts. The socket is created here and bound by run().
req.close(): closes the client's socket. Routes do not need it: the server closes connections itself.req.getVersion(): "HTTP/1.1" or "HTTP/1.0".req.getSock(): the client's socket.req.getAction(): the method, "GET", "POST", ...req.getPath(): the path, without the query string and not percent-decoded.req.getQuery(): what follows ? in the target, "" if nothing; not decoded.req.getHeader(name): the value of a request header, whatever the case of name; "" if absent. With a header repeated, the last one, except Cookie: repeated Cookie headers are joined with "; ".req.setResponseHeader(name, value): adds a header to this response, or replaces the one with the same name (any case), including a server default. Returns 0 and adds nothing for an invalid name, a header the library writes itself or a value with control characters (see Response headers above).req.hasResponseHeader(name): 1 if setResponseHeader already added a header with this name (any case) to the response. It does not see the server defaults.Builds a request from its headers, everything before \r\n\r\n. When the request cannot be served, req.bad holds the status to answer (400, 431 or 501), otherwise 0. The workers call it for every request.
Internal helpers
Used by the functions above; not meant to be called directly.
- def http_now_ms(tp: Timespec) -> long
- def http_try_readfile(path: str) -> (int, str)
- def http_is_absolute(name: str) -> int
- def http_name_escapes(name: str) -> int
- def http_join(directory: str, name: str) -> str
- def http_template_file(server: HttpServer, name: str) -> str
- def http_static_file(server: HttpServer, name: str) -> str
- def http_check_dir(setter: str, directory: str) -> None
- def http_check_dirs(self: HttpServer) -> None
- def http_serve_static(server: HttpServer, req: HttpRequest) -> int
- def http_error_page(server: HttpServer, req: HttpRequest) -> int
- def http_fill_error_body(server: HttpServer, req: HttpRequest) -> None
- def http_write_all(fd: SOCKET, data: str, length: long) -> int
- def http_run_middleware(self: HttpServer, req: HttpRequest, phase: int) -> HttpRequest
- def http_error_response(status: int) -> str
- def http_header_lines(table: str, skip: str) -> str
- def http_response_header_lines(server: HttpServer, req: HttpRequest) -> str
- def http_header_valid_value(value: str) -> int
- def http_header_reserved(lower: str) -> int
- def http_header_allowed(name: str, lower: str, value: str) -> int
- def http_describe_status(status: int) -> str
- def http_valid_header_name(line: str, name_len: long) -> int
- def http_format_ms(ms: long) -> str
- def http_content_length(req: HttpRequest) -> long
- def http_conn_handle_one(self: HttpServer, c: HttpConn) -> long
- def http_epoll_ctl(ep: int, op: int, fd: SOCKET, events: int) -> int
- def http_conn_close(ep: int, c: HttpConn) -> None
- def http_conn_flush(ep: int, c: HttpConn) -> int
- def http_conn_process(self: HttpServer, ep: int, c: HttpConn) -> None
- def http_conn_read(self: HttpServer, ep: int, c: HttpConn) -> None
- def http_accept_all(self: HttpServer, ep: int, listen_fd: SOCKET, conns: HttpConn[4096]) -> int
- def http_conn_stash(c: HttpConn) -> None
- def http_conn_own_rbuf(c: HttpConn) -> None
- def http_shed_one(listen_fd: SOCKET) -> int
- def http_raise_fd_limit() -> None
- def http_sweep(self: HttpServer, ep: int, conns: HttpConn[4096], max_fd: int) -> None
- def http_conn_drop_rbuf(c: HttpConn, now: long) -> None
- def http_serve_epoll(self: HttpServer) -> None
- def http_serve_blocking(self: HttpServer) -> None