libstd/http/session
Sessions keep data on the server for one browser, across requests: who is logged in, what is in a cart, the token of the next form. The browser only holds a random identifier in the sid cookie. The data lives in one table of fixed size in shared memory, which every worker process reads and writes: a session works whichever worker answers the request, and it survives the crash of a worker.
#include <libstd/http>
Part of libstd/http, which includes it (the source is libstd/http/session.tryc). The sid cookie goes through libstd/http/cookies.
Quick start
Turn sessions on before run(), then read and write them through the request, in any route or middleware. This counter counts the visits of each browser separately:
#include <libstd/http>
def visits(self: HttpServer, req: HttpRequest) -> str:
n = str_to_long(req.sessionGet("visits")) + 1
req.sessionSet("visits", itoa(n))
req.content_type = "text/plain; charset=utf-8"
return "visit number " + itoa(n) + "\n"
server = HttpServer(127, 0, 0, 1, 8000)
server.enableSessions(1000 as long) // room for 1000 sessions at once
server.addMapsFunction("/visits", visits)
server.run()
curl -c jar -b jar http://127.0.0.1:8000/visits
curl -c jar -b jar http://127.0.0.1:8000/visits
visit number 1
visit number 2
A missing key reads as "", and str_to_long("") is 0, so the first visit counts 1. The first sessionSet creates the session, and that response carries Set-Cookie: sid=.... curl keeps the cookie in the file jar and sends it back, as a browser does. Without -b jar every request would be a new visitor.
The interface
| Call | What it does |
|---|---|
server.enableSessions(n) | Turns sessions on, with room for n sessions at once. Call it before run(). |
server.setSessionTimeouts(idle, max) | A session expires after idle milliseconds without requests, and in any case max milliseconds after it was created. 0 removes a limit. The defaults are 30 minutes and 24 hours. |
req.sessionGet(key) | A value of the session, "" if the key is absent or the request has no session. |
req.sessionHas(key) | 1 if the session has the key. |
req.sessionSet(key, value) | Stores a value, and creates the session if the request has none. -1 if the data would not fit. |
req.sessionDel(key) | Removes a key. |
req.sessionRegenerate() | Gives the session a new id, with the same data. Call it at login. |
req.sessionDestroy() | Deletes the session and tells the browser to delete the cookie. Call it at logout. |
req.sessionId() | The session id, "" if the request has no session. |
server.getSessionCount() | The live sessions of the whole server. |
server.dumpSessions(full) | Prints the live sessions, for debugging. |
Keys and values are strings: store a number with itoa and read it back with str_to_long. Changes made by a request reach the table after its last middleware, so the other requests see them from then on.
Examples
Every example below was compiled and run as it appears here. The first one shows the whole program; the others show their routes and the lines that register them, to add to the same server.
Login, a private page and logout
The login form posts a user name and a password. When they are right, the route stores the user in the session; every later request of that browser finds it there, until logout:
#include <libstd/http>
// the value of one field of a form ("user=alice&password=..."),
// "" if it is missing; %XX sequences are not decoded
def form_value(data: str, name: str) -> str:
offset = 0 as long
while offset >= 0:
offset, pair = split_next(data, "&", offset)
eq = find_char(pair, '=')
if eq > 0 and get_chars_in_range(pair, 0, eq) == name:
return get_chars_in_range(pair, eq + 1, strlen(pair))
return ""
// stands in for a real check against the password hashes you store
def check_password(user: str, password: str) -> int:
if user == "alice" and password == "wonderland":
return 1
if user == "bob" and password == "builder":
return 1
return 0
def login(self: HttpServer, req: HttpRequest) -> str:
if req.getAction() != "POST":
return (
"<form method=\"post\" action=\"/login\">" +
"<input name=\"user\"> <input name=\"password\" type=\"password\">" +
"<button>Log in</button></form>"
)
user = form_value(req.body, "user")
if not check_password(user, form_value(req.body, "password")):
req.status = 403
return "<p>Wrong user or password. <a href=\"/login\">Try again</a></p>"
req.sessionRegenerate() // a new id for the logged-in user
req.sessionSet("user", user)
return "<p>Welcome, " + user + ". <a href=\"/profile\">Your profile</a></p>"
def profile(self: HttpServer, req: HttpRequest) -> str:
if not req.sessionHas("user"):
req.status = 401
return "<p><a href=\"/login\">Log in</a> first.</p>"
return "<p>Hello " + req.sessionGet("user") + ". <a href=\"/logout\">Log out</a></p>"
def logout(self: HttpServer, req: HttpRequest) -> str:
req.sessionDestroy()
return "<p>Bye. <a href=\"/login\">Log in again</a></p>"
server = HttpServer(127, 0, 0, 1, 8000)
server.enableSessions(1000 as long)
server.setSessionTimeouts(900000 as long, 28800000 as long) // 15 minutes idle, 8 hours at most
server.addMapsFunction("/login", login)
server.addMapsFunction("/profile", profile)
server.addMapsFunction("/logout", logout)
server.run()
curl -i -c jar -d "user=alice&password=wonderland" http://127.0.0.1:8000/login
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 58
Connection: keep-alive
Set-Cookie: sid=c50468cba749cbd43b930de7b5d38097b78f19be01fe7489d9df6a33418f0235; Path=/; Max-Age=28800; HttpOnly; SameSite=Lax
<p>Welcome, alice. <a href="/profile">Your profile</a></p>
curl -b jar http://127.0.0.1:8000/profile
<p>Hello alice. <a href="/logout">Log out</a></p>
curl -i -b jar -c jar http://127.0.0.1:8000/logout
curl -b jar http://127.0.0.1:8000/profile
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 45
Connection: keep-alive
Set-Cookie: sid=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax
<p>Bye. <a href="/login">Log in again</a></p>
<p><a href="/login">Log in</a> first.</p>
sessionRegenerate()at login. The browser may have had a session before logging in, and someone else may know its id: it was used on a shared computer, or an attacker got a valid id from the server and planted it in the browser. AftersessionRegenerate()the data of that session, if any, moves to a new id and the old id stops working, so knowing it gives no access to the logged-in session. That attack is called session fixation.- A wrong password creates nothing. The route returns before any
sessionSet, so no session and no cookie are created: failed logins and bots do not fill the table. sessionDestroy()at logout. The data and the id are deleted on the server, not only the cookie in the browser: a copy of the old cookie no longer works either.- The page shows only checked names.
userreaches the page only aftercheck_passwordaccepted it, and the session holds nothing else. Never put a raw form field or cookie into HTML. form_valuedoes not decode%XXand+: it is enough for names and passwords made of letters and digits.
Protecting a whole section
Instead of checking the session in every route under /admin/, a middleware checks it once, before the route runs. A visitor who is not logged in gets the path rewritten to a route that answers 401, so the protected route never runs for them:
def require_login(self: HttpServer, req: HttpRequest) -> HttpRequest:
if req.phase == HTTP_PHASE_BEFORE and startswith(req.getPath(), "/admin/") and not req.sessionHas("user"):
req.path = "/login-required"
return req
def login_required(self: HttpServer, req: HttpRequest) -> str:
req.status = 401
return "<p>This page needs a login: <a href=\"/login\">log in</a>.</p>"
def admin_home(self: HttpServer, req: HttpRequest) -> str:
return "<p>Admin area of " + req.sessionGet("user") + ". Live sessions: " + itoa(self.getSessionCount()) + "</p>"
server.addMiddleWare("login", require_login)
server.addMapsFunction("/login-required", login_required)
server.addMapsFunction("/admin/", admin_home)
The session is already loaded when the middleware runs in the before phase, so sessionHas works there as in a route. A route added later under /admin/ is protected without changes. Routes are matched exactly, so /admin/ and /admin/users are separate routes: the middleware protects every path that starts with /admin/.
A shopping cart
A cart for a small catalogue: one key per product, holding the quantity. The visitor does not need to log in, since the session starts with the first product added:
def cart_add(self: HttpServer, req: HttpRequest) -> str:
req.content_type = "text/plain; charset=utf-8"
item = req.getQuery() // /cart/add?book
if item != "book" and item != "pen" and item != "mug":
req.status = 404
return "unknown product\n"
n = str_to_long(req.sessionGet("qty_" + item)) + 1
if req.sessionSet("qty_" + item, itoa(n)) < 0:
req.status = 413
return "the cart is full\n"
return "added " + item + ", now " + itoa(n) + "\n"
def cart_line(req: HttpRequest, item: str) -> str:
n = req.sessionGet("qty_" + item)
if n == "":
return ""
return item + " x " + n + "\n"
def cart(self: HttpServer, req: HttpRequest) -> str:
req.content_type = "text/plain; charset=utf-8"
out = cart_line(req, "book") + cart_line(req, "pen") + cart_line(req, "mug")
if out == "":
return "the cart is empty\n"
return out
def cart_clear(self: HttpServer, req: HttpRequest) -> str:
req.sessionDel("qty_book")
req.sessionDel("qty_pen")
req.sessionDel("qty_mug")
req.content_type = "text/plain; charset=utf-8"
return "the cart is empty\n"
server.addMapsFunction("/cart/add", cart_add)
server.addMapsFunction("/cart", cart)
server.addMapsFunction("/cart/clear", cart_clear)
curl -c jar -b jar 'http://127.0.0.1:8000/cart/add?book'
curl -c jar -b jar 'http://127.0.0.1:8000/cart/add?book'
curl -c jar -b jar 'http://127.0.0.1:8000/cart/add?pen'
curl -c jar -b jar http://127.0.0.1:8000/cart
added book, now 1
added book, now 2
added pen, now 1
book x 2
pen x 1
All the data of one session must fit in HTTP_SESSION_DATA_MAX bytes (416). sessionSet refuses a value that would not fit and leaves the session as it was, which cart_add turns into a 413. A cart with many products, or with prices and names, belongs in a database: the session then holds only the id of the cart.
A token against forged forms (CSRF)
A page on another site can make the browser of a logged-in user post a form to this server. If the session cookie went along, the post would act as that user. A form protected with a token carries a hidden field whose value is known only to the session. The other site cannot read it, so its post is refused:
def csrf_token(req: HttpRequest) -> str:
if not req.sessionHas("csrf"):
req.sessionSet("csrf", long_to_hex(random_seed_from_os(), 16) + long_to_hex(random_seed_from_os(), 16))
return req.sessionGet("csrf")
def settings(self: HttpServer, req: HttpRequest) -> str:
if not req.sessionHas("user"):
req.status = 401
return "<p><a href=\"/login\">Log in</a> first.</p>"
if req.getAction() == "POST":
token = req.sessionGet("csrf")
if token == "" or form_value(req.body, "csrf") != token:
req.status = 403
return "<p>This form has expired: <a href=\"/settings\">reload it</a>.</p>"
theme = form_value(req.body, "theme")
if theme != "light" and theme != "dark":
req.status = 400
return "<p>Unknown theme.</p>"
req.sessionSet("theme", theme)
req.sessionSet("flash", "Theme saved.")
return "<p>Done. <a href=\"/dashboard\">Go to the dashboard</a></p>"
return (
"<form method=\"post\" action=\"/settings\">" +
"<input type=\"hidden\" name=\"csrf\" value=\"" + csrf_token(req) + "\">" +
"<select name=\"theme\"><option>light</option><option>dark</option></select>" +
"<button>Save</button></form>"
)
server.addMapsFunction("/settings", settings)
- The token is made once per session, from 128 random bits of the operating system (
random_seed_from_osfromlibstd/random, twice), and stays the same for all the forms of that session. - The post is refused when the session has no token: an empty token would otherwise match a form without the field.
- The values read from the form are checked before they are stored:
themecan only belightordark. - The
sidcookie isSameSite=Lax, so most browsers already leave it out of a post that another site starts. The token is the usual second defence, and it also protects browsers that ignoreSameSite.
A message shown once
After a form is saved, the next page shows a short confirmation, once. settings above stores it in flash; the dashboard shows it and deletes it:
def dashboard(self: HttpServer, req: HttpRequest) -> str:
page = "<h1>Dashboard</h1>"
msg = req.sessionGet("flash")
if msg != "":
req.sessionDel("flash")
page = page + "<p class=\"flash\">" + msg + "</p>"
return page
server.addMapsFunction("/dashboard", dashboard)
The first visit to /dashboard after saving shows Theme saved.; reloading the page does not. sessionDel changes the session, so the removal is written back like any other change.
How a session lives
- Creation. A request without a session gets one the first time a route or middleware writes to it, with
sessionSetorsessionRegenerate. The response then carriesSet-Cookie: sid=...withHttpOnly,SameSite=Laxand aMax-Ageequal to the maximum lifetime of a session (noMax-Agewhen that limit is0). A request that only reads creates nothing, so crawlers and one-off visits do not fill the table. - Loading and saving. The data is loaded before the first middleware and written back after the last one, and only if something changed. A request that only reads writes nothing.
- Two requests at once. Two requests of the same session served at the same time, by two workers, each work on their own copy of the data, and the one that finishes last wins. A value that must never lose an update, such as a balance, belongs in a database.
- Identifiers. An id is 64 hexadecimal digits made from 32 random bytes of the operating system (
getrandom). Asidcookie that does not have that form, or that names no live session, is ignored: the request simply has no session, and the server never adopts an id chosen by the client. - New id.
sessionRegenerate()moves the data to a new id after the response, and the old id stops working. Call it whenever the identity or the privileges of the user change (login, a switch to an administrator account).req.sessionId()shows the new id only from the next request. - End.
sessionDestroy()deletes the data and the id, and tells the browser to delete the cookie. AsessionSetlater in the same request starts a new session. - Expiry. A session expires after
HTTP_DEFAULT_SESSION_IDLE_MS(30 minutes) without requests, and in any caseHTTP_DEFAULT_SESSION_MAX_MS(24 hours) after it was created;setSessionTimeouts(idle_ms, max_ms)changes both limits, and0removes one. Each request of the session restarts the idle time. Expired sessions are removed when they are looked up, when they are counted, and when the table is full. - Size. All the pairs of one session must fit in
HTTP_SESSION_DATA_MAXbytes (416), each pair takingstrlen(key) + strlen(value) + 2. Store ids, names, roles and tokens, not documents.
Where sessions live
run() creates one table before starting the workers, in memory mapped with MAP_SHARED. Every worker, including those the supervisor restarts, sees the same table, so a session created by one worker is found by all the others. The table has a fixed size: enableSessions(n) reserves room for n sessions, about HTTP_SESSION_SLOT_SIZE * 5 / 4 bytes each (640 KB for 1000 sessions). Memory does not grow with traffic or with the number of workers. When n sessions exist and a new one is needed, the expired ones are removed first. If none has expired, the least recently used session makes room.
When a worker dies
A futex lock that works across processes protects the table, and it holds the pid of the worker that has it. A worker that dies while holding it (a crash, or an exit during a session operation) therefore does not block the others. When the supervisor collects the dead worker, it finds that pid in the lock, takes the lock over, puts the table back in order and releases it, before starting the replacement. A removal that was cut short is finished, and a write that was cut short is undone: the session keeps the data it had before that request. The sessions are then counted again. The log of the server records it:
http: worker 6992 terminato (uscita 3), ne avvio un altro
http: il worker 6992 aveva il lock delle sessioni: tabella rimessa in ordine
Watching them while debugging
getSessionCount() returns the number of live sessions of the whole server. dumpSessions(0) prints one line per session with the first 8 digits of its id, how long it has been idle, when it expires and how many bytes of data it holds. Both can be called from any route:
http: 2 sessioni attive su 1000 (processo 40134)
5f207c69... inattiva da 12s scade tra 29m48s dati 20 B
becd6d42... inattiva da 3m05s scade tra 26m55s dati 11 B
Anyone who reads a session id can use the session until it expires. dumpSessions(1) prints whole ids: use it only in development, and never expose either function through a route that clients can reach. Over plain HTTP the cookie travels in clear: put a TLS proxy in front of a server with logins, and the session cookie will travel encrypted.
On Windows the table is private to each worker, because the emulated fork copies memory instead of sharing it: use setNumCoworker(1) there if you need sessions.
Constants
| Name | Value | Meaning |
|---|---|---|
HTTP_SESSION_ID_LEN | 64 | Hexadecimal digits in a session id. |
HTTP_SESSION_HEADER_SIZE | 64 | Bytes at the start of the session table: the lock, the number of sessions and the operation in progress. |
HTTP_SESSION_SLOT_SIZE | 512 | Bytes of one slot of the session table. |
HTTP_SESSION_DATA_OFF | 96 | Where the data starts inside a slot. |
HTTP_SESSION_DATA_MAX | 416 | Bytes available for the data of one session. |
HTTP_LOCK_WAITERS | 1073741824 | Bit of the session lock set when a worker may be waiting for it. |
HTTP_LOCK_PID_MASK | 1073741823 | Bits of the session lock that hold the pid of the worker that has it. |
HTTP_SESSION_DIRTY | 1 | req.session_flags: the data changed. |
HTTP_SESSION_REGENERATE | 2 | req.session_flags: sessionRegenerate was called. |
HTTP_SESSION_DESTROY | 4 | req.session_flags: sessionDestroy was called. |
The default timeouts HTTP_DEFAULT_SESSION_IDLE_MS (1800000, 30 minutes) and HTTP_DEFAULT_SESSION_MAX_MS (86400000, 24 hours) are defined in libstd/http. The cookie name HTTP_SESSION_COOKIE ("sid") is defined in libstd/http/cookies.
Functions
server.enableSessions(n): turns sessions on, with room for n sessions at once; run() creates the shared table. Called after run(), or with n below 1, it prints a message and exits.server.setSessionTimeouts(idle_ms, max_ms): a session expires after idle_ms milliseconds without requests and max_ms milliseconds after its creation; 0 removes a limit.server.getSessionCount(): the live sessions of the whole server, after removing the expired ones; 0 when sessions are off or run() has not created the table yet.server.dumpSessions(full): prints the live sessions for debugging, one per line: the id (first 8 digits, or the whole id with full = 1), idle time, time left and bytes of data.req.sessionId(): the id of the request's session, "" if it has none. A session created or regenerated by this request gets its id only after the response.req.sessionGet(key): a value of the session, "" if the key is absent.req.sessionHas(key): 1 if the session has the key, 0 otherwise (also when there is no session).req.sessionSet(key, value): stores a value, creating the session if needed. Returns 0, or -1 if sessions are off, the key is empty or the data would exceed HTTP_SESSION_DATA_MAX bytes; the session is then unchanged.req.sessionDel(key): removes a key from the session; nothing happens if it is absent.req.sessionRegenerate(): moves the session to a new id after the response, and the old id stops working. Call it at login and whenever privileges change. It creates the session if there is none.req.sessionDestroy(): logout. It deletes the session and its id and tells the browser to delete the cookie. A sessionSet later in the same request starts a new session.Internal helpers
Used by the functions above and by libstd/http; not meant to be called directly.
- def http_sessions_open(self: HttpServer) -> None
- def http_sessions_ready(self: HttpServer) -> int
- def http_lock(word: str, owner: int) -> None
- def http_unlock(word: str) -> None
- def http_session_slot(self: HttpServer, i: long) -> str
- def http_session_home(id: str, slots: long) -> long
- def http_session_valid_id(id: str) -> int
- def http_session_matches(slot: str, id: str) -> int
- def http_session_expired(self: HttpServer, slot: str, now: long) -> int
- def http_session_delete_at(self: HttpServer, i: long) -> None
- def http_session_find_at(self: HttpServer, id: str, now: long) -> long
- def http_session_purge(self: HttpServer, now: long) -> None
- def http_session_oldest(self: HttpServer) -> long
- def http_session_repair(self: HttpServer) -> None
- def http_sessions_recover(self: HttpServer, pid: int) -> int
- def http_session_create(self: HttpServer) -> str
- def http_session_touch(self: HttpServer, id: str) -> int
- def http_session_destroy(self: HttpServer, id: str) -> int
- def http_session_pair_size(key: str, value: str) -> long
- def http_raw_len(data: str, pos: long, end: long) -> long
- def http_session_begin(self: HttpServer, req: HttpRequest) -> None
- def http_session_store(self: HttpServer, id: str, req: HttpRequest) -> int
- def http_session_end(self: HttpServer, req: HttpRequest) -> None