# Running on Linux

PhotonHTTP builds and runs on Linux with **HTTP/1.1 and HTTP/2, cleartext and over TLS, and
HTTP/3** (M19). TLS and the built-in ACME client (`tls.acme`, #0165) use OpenSSL 3.
HTTP/3 runs on [ngtcp2](https://github.com/ngtcp2/ngtcp2) (MIT, vendored in `Sources/CNGTCP2`)
over OpenSSL 3.5's QUIC TLS API (#0162). Certificates come from `tls.acme` or certbot.
It is tested on a Raspberry Pi 5 (aarch64, Debian 13, Swift 6.4.3) and cross-compiled from a
Mac with the Swift Static Linux SDK.

## What works

| Feature | Linux | Notes |
|---|---|---|
| HTTP/1.1 (keep-alive, pipelining, chunked, Range, conditional requests) | yes | `"transport": "bsd"` (the default), an epoll event loop |
| Static files, `sendfile(2)`, error pages, virtual hosts, router, auth, access log, reverse proxy | yes | Access log `"destination": "oslog"` writes to stderr |
| Compression | gzip, deflate | Brotli comes from Apple's libcompression; listing `"br"` warns and it is skipped |
| `photon check`, `status`, `reload` (SIGHUP), `restart` (SIGUSR2), SIGTERM/SIGINT drain | yes | |
| Config file watching | yes | |
| TLS (HTTPS), HTTP/2 by ALPN | yes | System OpenSSL 3 (`libssl-dev` to build); TLS 1.2 and 1.3; PEM (`tls.identity` + `tls.key`) or PKCS#12; SIGHUP swaps the certificate |
| HTTP/3 | yes | ngtcp2 + OpenSSL 3.5 or later (#0162); same `http3` config as macOS, UDP on the TLS port, `Alt-Svc` on HTTPS. With an older OpenSSL the build still works and `http3` fails at startup with a message. Not in the static binary (no OpenSSL) |
| `tls.acme` | yes | OpenSSL backend (#0165): P-256/RSA-2048 keys, HTTP-01 on the cleartext port. A private CA's `caCertificates` are checked in process over OpenSSL; Let's Encrypt uses `URLSession` and the system CA bundle (`ca-certificates`). `startup: "wait"` needs a graceful restart, which cannot share a port on Linux yet. Not in builds without the `OpenSSL` trait (the static binary): rejected at startup |
| `"transport": "nw"` | no | Network.framework only |
| `sws-bench` | no | Its load client uses Network.framework (#0156) |

## Two ways to build

### 1. A static binary from the Mac (recommended for deploying)

The Static Linux SDK links everything, the Swift runtime and Foundation included, into one
musl executable with no runtime dependencies. It needs a swift.org toolchain whose version
matches the SDK exactly; Xcode's toolchain cannot use it. This is a one-time setup, done as
your user (no sudo, and no shell-profile edits):

```bash
# swiftly, without touching ~/.zshrc
~/.swiftly/bin/swiftly init --no-modify-profile --skip-install
~/.swiftly/bin/swiftly install 6.4.3
# The matching SDK: URL and checksum from
# https://www.swift.org/documentation/articles/static-linux-getting-started.html
~/Library/Developer/Toolchains/swift-6.4.3-RELEASE.xctoolchain/usr/bin/swift sdk install <URL> --checksum <SHA256>
```

Then build:

```bash
scripts/linux/build-static.sh aarch64 release photon      # or x86_64
# → .build/out/Products/Release-staticlinux-aarch64/photon (about 150 MB, static)
```

Deploy it to a host you reach over ssh (for yoyo: `ssh yoyo`, over Tailscale). From the Mac,
only use ssh aliases or Tailscale names, never LAN addresses, which trigger the Local Network
privacy prompt (AGENTS.md):

```bash
scripts/linux/deploy.sh yoyo                                  # installs ~/photon/bin/photon
scripts/linux/deploy.sh yoyo --run /srv/site 8080 60          # and serves for 60 s under timeout
```

Check a deployed binary on the host with the HTTP/1.1 validation script. It covers index, MIME,
404, 405, HEAD, ETag/304, Range, keep-alive, pipelining, a 256 MiB download with flat memory,
the slow-header timeout, 2,000 parallel requests, descriptor leaks and a clean SIGTERM:

```bash
scp scripts/linux/validate-h1.sh yoyo:
ssh yoyo 'bash validate-h1.sh ~/photon/bin/photon ~/Developer/PhotonHTTP/Root/Public'
```

### 2. Natively on the Linux host (for tests)

Install Swift with swiftly on the host, then from the Mac:

```bash
scripts/linux/test-remote.sh yoyo                     # git archive HEAD → build → swift test
scripts/linux/test-remote.sh yoyo --filter HTTP1Tests
```

On a Pi, keep `-j` at 2 or 3: a full debug build with tests needs several GB of RAM.

The manifest is evaluated on the build host. On a Linux host it leaves out `sws-bench`. The
`ACME` target builds everywhere: with the `OpenSSL` trait (the default) its crypto is OpenSSL;
without it (the static binary) it has no crypto backend and `tls.acme` is rejected at startup.

## HTTPS with certbot

The static binary from the Mac has no TLS, because the Static Linux SDK has no OpenSSL. For HTTPS,
cross-compile on the Mac for Ubuntu 24.04 (or Debian 13):

```bash
scripts/linux/build-ubuntu.sh x86_64      # or aarch64
# → .build/ubuntu-24.04-x86_64/out/Products/Release-linux-x86_64/photon
```

The first run makes a Swift SDK with swiftlang's swift-sdk-generator and adds Ubuntu 24.04's
own `libssl-dev` to it (cached in `.build/linux-sdk`), and builds OpenSSL 3.5 from source
(`scripts/linux/build-openssl.sh`, cached in `.build/openssl`). Photon links that OpenSSL
statically, without exporting its symbols, so HTTP/3 works on Ubuntu 24.04, whose own OpenSSL
(3.0) has no QUIC API. The binary carries the Swift runtime and needs only `libcurl4t64` (for the
ACME client), zlib and glibc, all part of a stock Ubuntu 24.04 install. (Building on the server
works too: `apt install libssl-dev`, Swift from swiftly, `swift build -c release --product photon`;
HTTP/3 then needs the distribution's OpenSSL to be 3.5 or later, as on Debian 13.) Serve the site on port 80 first, so certbot can
answer its HTTP-01 challenge through Photon (`/.well-known/acme-challenge/` is served from the
root):

```bash
certbot certonly --webroot -w /srv/site -d example.com \
  --deploy-hook "systemctl reload photon"
```

Then add TLS to the config. Photon reads certbot's files directly, and the deploy hook's reload
(SIGHUP) swaps in each renewed certificate without dropping connections:

```json
{
  "root": "/srv/site", "host": "0.0.0.0", "port": 80,
  "tls": {"identity": "/etc/letsencrypt/live/example.com/fullchain.pem",
          "key": "/etc/letsencrypt/live/example.com/privkey.pem", "port": 443},
  "http2": {"enabled": true},
  "http3": {}
}
```

`http3` listens on UDP at the TLS port and advertises itself with `Alt-Svc`. Open **UDP** 443 as
well as TCP 443 in every firewall in front of the host (ufw, a cloud firewall): HTTP/3 is QUIC
over UDP, and a TCP-only rule silently leaves browsers on HTTP/2. Check it from outside with a
curl that has HTTP/3 (`curl -V` lists `HTTP3`; macOS's own curl does not):
`curl -s -o /dev/null -w '%{http_version}\n' --http3-only https://example.com/` prints `3`.

Ports below 1024 need `AmbientCapabilities=CAP_NET_BIND_SERVICE` in the systemd unit. The
key file must be readable by the user Photon runs as.

## Tests on Linux

The suite builds and runs on Linux: about 1,500 tests in 20 test targets (macOS runs about 2,000). Tests that need
Network.framework, Security.framework, CryptoKit, URLSession WebSockets, `sws-bench` or
libmalloc's `malloc_logger` are compiled out with
`#if canImport(Network)` / `canImport(Darwin)`. Each such file names the reason on its first
line. Brotli cases are skipped with `.enabled(if: ContentCoding.brotli.isAvailable)`.
`BSDSocketTransportTests` exercises the epoll loop directly: echo, a 16 MiB transfer under
back-pressure, half-close, cancellation, `sendfile`, 400 short connections, and a write to a
reset peer. `LinuxHTTP3Tests` runs `photon` with `http3` against `curl --http3-only` when the
build has OpenSSL 3.5 and curl has HTTP/3 (Debian 13 does): `Alt-Svc`, a download, 20
concurrent handshakes, a certificate reload and SIGTERM.

## Running as a service

Serve on a non-privileged port and bind `127.0.0.1` behind a reverse proxy, or bind a public
address on a server you control. Ports below 1024 need `CAP_NET_BIND_SERVICE`. A systemd user
unit:

```ini
# ~/.config/systemd/user/photon.service
[Unit]
Description=PhotonHTTP

[Service]
ExecStart=%h/photon/bin/photon --config %h/photon/http-config.json
ExecReload=/bin/kill -HUP $MAINPID
KillSignal=SIGTERM
Restart=on-failure

[Install]
WantedBy=default.target
```

```bash
systemctl --user daemon-reload && systemctl --user enable --now photon
loginctl enable-linger "$USER"     # keep it running when you are logged out
```

The status file defaults to `run/status.json` next to the config, as on macOS. `photon status`,
`reload` and `restart` find the server through it.

## Implementation notes

- **Event loop:** `BSDEventLoop` uses epoll on Linux and kqueue on Apple platforms, chosen at
  compile time. Each descriptor is registered once, edge-triggered
  (`EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLET`). An edge that arrives while no task is waiting
  is remembered in `SocketCore`, so the next wait returns at once. A descriptor is removed from
  epoll before it is closed. Its retain is released on the loop thread, which an `eventfd`
  wakes, so a late event can never reach a freed object.
- **SIGPIPE** is ignored process-wide when the loops start (Linux has no `SO_NOSIGPIPE`).
- **Crypto:** SHA-1 (WebSocket handshake), SHA-256, HMAC and PBKDF2 (Auth, status file) use
  small dependency-free implementations on Linux. They are checked against FIPS, RFC 4231 and
  RFC 6070 vectors and against CommonCrypto on macOS.
- **zlib** comes from the system (`zlib1g-dev` for native builds; bundled in the static SDK).
- **QUIC (HTTP/3):** `QUICListener`, `QUICConnection` and `QUICStreamTransport` have the macOS
  API, so `HTTP3` and `photon` use them unchanged. ngtcp2 does no I/O and is not thread-safe, so
  one engine thread per listener owns the UDP socket and every `ngtcp2_conn`: it routes
  datagrams by connection ID (registered as ngtcp2 issues and retires them), runs the timers and
  writes packets, sleeping in `poll` on the socket and an `eventfd`. Tasks queue work on it or
  move bytes through each stream's bounded buffers; receive credit is returned only as the
  reader consumes. The C glue in `Sources/CNGTCP2/wrappers/photon_quic.c` makes a TLS 1.3
  `SSL_CTX` for QUIC from the HTTPS identity and receives and sends with packet-info control
  messages, so a listener on `::` or `0.0.0.0` replies from the address each datagram reached.
  There is no QUIC Retry, and the socket does not use `recvmmsg`/GSO yet (#0172).
- **curl on Debian 13** uses OpenSSL's own QUIC client for HTTP/3. Under packet loss it can stop
  extending a stream's receive window, and a download then stalls until curl times out; the
  server is waiting on flow control (an aioquic client under the same loss is unaffected). Use
  it for checks, not load tests.
- `Sources/CLinuxSystem` exposes `epoll`, `eventfd` and `sendfile`, which the Glibc module does
  not export.
