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

CallWhat 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>

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)

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

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
Session ids are passwords

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.

Limits

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

NameValueMeaning
HTTP_SESSION_ID_LEN64Hexadecimal digits in a session id.
HTTP_SESSION_HEADER_SIZE64Bytes at the start of the session table: the lock, the number of sessions and the operation in progress.
HTTP_SESSION_SLOT_SIZE512Bytes of one slot of the session table.
HTTP_SESSION_DATA_OFF96Where the data starts inside a slot.
HTTP_SESSION_DATA_MAX416Bytes available for the data of one session.
HTTP_LOCK_WAITERS1073741824Bit of the session lock set when a worker may be waiting for it.
HTTP_LOCK_PID_MASK1073741823Bits of the session lock that hold the pid of the worker that has it.
HTTP_SESSION_DIRTY1req.session_flags: the data changed.
HTTP_SESSION_REGENERATE2req.session_flags: sessionRegenerate was called.
HTTP_SESSION_DESTROY4req.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

def HttpServerEnableSessions(self: HttpServer, capacity: long) -> None
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.
def HttpServerSetSessionTimeouts(self: HttpServer, idle_ms: long, max_ms: long) -> None
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.
def HttpServerGetSessionCount(self: HttpServer) -> long
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.
def HttpServerDumpSessions(self: HttpServer, full: int) -> None
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.
def HttpRequestSessionId(self: HttpRequest) -> str
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.
def HttpRequestSessionGet(self: HttpRequest, key: str) -> str
req.sessionGet(key): a value of the session, "" if the key is absent.
def HttpRequestSessionHas(self: HttpRequest, key: str) -> int
req.sessionHas(key): 1 if the session has the key, 0 otherwise (also when there is no session).
def HttpRequestSessionSet(self: HttpRequest, key: str, value: str) -> int
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.
def HttpRequestSessionDel(self: HttpRequest, key: str) -> None
req.sessionDel(key): removes a key from the session; nothing happens if it is absent.
def HttpRequestSessionRegenerate(self: HttpRequest) -> None
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.
def HttpRequestSessionDestroy(self: HttpRequest) -> 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.