Skip to content
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ Added:
- **Internet schedule** (new page). Turn the internet off at set times of the week for chosen people (all their devices) or single devices: bedtime on school nights, study time, meal times. One click starts from a ready plan ("School nights", "Every night", "Study time", "Meal times"); a schedule can have several times, a time can run past midnight, and dates can be marked as days off (holidays, Eid). **Bonus time** gives a few extra minutes without changing the schedule. **Always allowed** sites (a school platform, a study site) keep working during every schedule. While a schedule is on, the device's card shows when the internet comes back, the home network (printer, shared drives, the dashboard) keeps working, and the cut is done by the gateway itself, so it works on any phone, tablet, TV or console with no app. Each device gets its end time in the system kernel, so it comes back online on time even if the gateway service restarts or stops. Sites on the "always allowed" list only open on devices that look names up through the gateway; a phone with Private DNS (or a browser with secure DNS) turned on keeps them blocked during a schedule. Contributed by @amr-elgharip2006. Closes #32.

Fixed:
- A guest who typed a valid code could get an error even though the code was accepted, and then be told the code was already used. The approval now always comes back, and a guest who retries gets the same approval again. Contributed by @compnew2006.
- The security filter on the dashboard (for access from outside the home) now checks a request's size as it arrives and keeps its memory bounded, so a flood of large or never-ending requests can no longer slow the gateway down. Access from inside the home is unchanged. Contributed by @compnew2006.
- README: a one-line, safe way to back up the gateway's data while it runs, plus a restore guide. Contributed by @compnew2006.
- **Share** (files sent between devices at home) can no longer fill the gateway's disk: one file can be up to 4 GB, all shared files together up to 16 GB, and the gateway always keeps 1 GB free for itself. A file that does not fit is refused with a clear message instead of being half-saved. Contributed by @compnew2006.
- The guest waiting page: entering a guest code now also works when the same browser is logged in to the dashboard, the "start browsing" button gets the focus after approval, hidden parts stay hidden, and the pulsing animation stops for people who turned off motion on their device. Contributed by @compnew2006.
- Website block/allow rules were rebuilt every time the gateway started, so their numbers changed on each restart. They are now kept as they are. If an older version was interrupted in the middle of that rebuild (for example by a power cut), the rules it left behind are put back on the next start instead of being lost. Contributed by @compnew2006.
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,13 @@ sudo apt remove quota-manager # rem
sudo apt purge quota-manager # remove everything
```

Your data lives in `/var/lib/quota-gateway/quota.db` — copy it now and then as a backup.
Your data lives in `/var/lib/quota-gateway/quota.db`. To back it up (safe while the gateway is running):

```bash
sudo python3 -c "import sqlite3; sqlite3.connect('/var/lib/quota-gateway/quota.db').backup(sqlite3.connect('/root/netrex-backup.db'))"
```

Don't just copy `quota.db` with `cp` while the gateway runs: recent changes may still sit in a side file and the copy can come out broken. Restoring a backup is in the [backup and restore guide](Structure_README.md#sqlite-backup-and-restore).

## Troubleshooting

Expand Down
12 changes: 11 additions & 1 deletion README_AR.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,17 @@ sudo apt purge quota-manager # إ

<div dir="rtl">

بياناتك في `/var/lib/quota-gateway/quota.db` — انسخها من وقت للتاني كنسخة احتياطية.
بياناتك موجودة في `/var/lib/quota-gateway/quota.db`. عشان تاخد نسخة احتياطية منها (آمن والبوابة شغالة):

</div>

```bash
sudo python3 -c "import sqlite3; sqlite3.connect('/var/lib/quota-gateway/quota.db').backup(sqlite3.connect('/root/netrex-backup.db'))"
```

<div dir="rtl">

ما تنسخش `quota.db` بـ `cp` والبوابة شغالة: آخر التغييرات ممكن تكون لسه في ملف جانبي والنسخة تطلع بايظة. استرجاع النسخة موجود في [دليل النسخ والاسترجاع](Structure_README.md#sqlite-backup-and-restore).

## حل المشاكل

Expand Down
163 changes: 163 additions & 0 deletions Structure_README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ the project layout, tests, and the release process.
- [Topology: a one-armed gateway](#topology-a-one-armed-gateway)
- [The packet path (no Python)](#the-packet-path-no-python)
- [The maintenance loop](#the-maintenance-loop)
- [SQLite backup and restore](#sqlite-backup-and-restore)
- [Quota model](#quota-model)
- [Speed shaping](#speed-shaping)
- [DNS filtering (domain rules, presets, per-client DNS servers)](#dns-filtering-domain-rules-presets-per-client-dns-servers)
Expand Down Expand Up @@ -266,6 +267,146 @@ below.

---

## SQLite backup and restore

The runtime database is `/var/lib/quota-gateway/quota.db`; `Database.connect()`
opens it in WAL mode (`PRAGMA journal_mode=WAL`). While the service is running,
recent committed changes can still live in `quota.db-wal` and are not necessarily
checkpointed into `quota.db`. A plain `cp quota.db backup.db` is therefore not a
consistent live backup. Do not copy the main file and its `-wal`/`-shm` sidecars
separately while SQLite is open; writes and checkpoints can race that copy.

Use Python's standard-library `sqlite3.Connection.backup()` API. It takes a
consistent SQLite snapshot while writers continue and includes committed WAL
content visible to that snapshot (later writes are not included). After the
copy, switch the destination to rollback-journal `DELETE` mode and close it;
this checkpoints any destination WAL and makes the backup a standalone file
without sidecars. The script checks it with `PRAGMA integrity_check` before
reporting success and restricts its mode:

```bash
( set -eu
sudo install -d -m 700 /var/lib/quota-gateway/backups
BACKUP="/var/lib/quota-gateway/backups/quota-$(date +%F-%H%M%S).db"
sudo test ! -e "$BACKUP"
sudo python3 - "$BACKUP" <<'PY'
from contextlib import closing
import os
import sqlite3
import sys

destination = sys.argv[1]
with closing(sqlite3.connect(
"file:/var/lib/quota-gateway/quota.db?mode=ro", uri=True)) as source:
with closing(sqlite3.connect(destination)) as backup:
source.backup(backup)
mode = backup.execute("PRAGMA journal_mode=DELETE").fetchone()[0]
if mode.lower() != "delete":
raise SystemExit(f"Could not make backup standalone: {mode}")
check = backup.execute("PRAGMA integrity_check").fetchone()[0]
if check != "ok":
raise SystemExit(f"Backup validation failed: {check}")
os.chmod(destination, 0o600)
print(f"Backup saved and verified: {destination}")
PY
)
```

Restore only with the service stopped. Validate the standalone backup first;
then move the old database and any sidecars aside as one set before installing
the backup. Never put an old `quota.db-wal` beside a restored database. For
example:

```bash
( set -eu
DB_DIR=/var/lib/quota-gateway
BACKUP="/var/lib/quota-gateway/backups/quota-YYYY-MM-DD-HHMMSS.db"
STAMP="$(date +%F-%H%M%S)"
STAGED="$DB_DIR/.quota.db.restore-$STAMP-$$"
ARCHIVE="$DB_DIR/quota.db.pre-restore-$STAMP"
sudo test -f "$BACKUP"
sudo test ! -e "$STAGED"
sudo test ! -e "$ARCHIVE"
sudo python3 - "$BACKUP" <<'PY'
import sqlite3
import sys

with sqlite3.connect(
f"file:{sys.argv[1]}?mode=ro&immutable=1", uri=True) as backup:
check = backup.execute("PRAGMA integrity_check").fetchone()[0]
if check != "ok":
raise SystemExit(f"Backup validation failed: {check}")
print("Backup is valid")
PY
sudo install -o root -g root -m 600 "$BACKUP" "$STAGED"
sudo python3 - "$STAGED" <<'PY'
import sqlite3
import sys

with sqlite3.connect(
f"file:{sys.argv[1]}?mode=ro&immutable=1", uri=True) as staged:
check = staged.execute("PRAGMA integrity_check").fetchone()[0]
if check != "ok":
raise SystemExit(f"Staged database validation failed: {check}")
PY
sudo mkdir -m 700 "$ARCHIVE"
sudo systemctl stop quota-gateway
if sudo test -e "$DB_DIR/quota.db"; then
sudo mv "$DB_DIR/quota.db" "$ARCHIVE/quota.db"
fi
for suffix in -wal -shm; do
if sudo test -e "$DB_DIR/quota.db$suffix"; then
sudo mv "$DB_DIR/quota.db$suffix" "$ARCHIVE/quota.db$suffix"
fi
done
sudo mv "$STAGED" "$DB_DIR/quota.db"
printf 'Old database and sidecars are preserved in %s\n' "$ARCHIVE"
sudo systemctl start quota-gateway
)
```

The restore block uses `set -eu`: any failed validation, stop, move, or start
ends the block immediately. It validates a staged replacement before stopping
the service and uses unique paths that refuse to overwrite existing files. If
the service does not start after replacement, leave it stopped and restore the
preserved files. Substitute the exact archive path printed by the restore
block:

```bash
( set -eu
DB_DIR=/var/lib/quota-gateway
ARCHIVE="$DB_DIR/quota.db.pre-restore-YYYY-MM-DD-HHMMSS"
sudo systemctl stop quota-gateway
sudo test -f "$ARCHIVE/quota.db"
sudo test ! -e "$ARCHIVE/quota.db.failed-restore"
if sudo test -e "$DB_DIR/quota.db"; then
sudo mv "$DB_DIR/quota.db" "$ARCHIVE/quota.db.failed-restore"
fi
for suffix in -wal -shm; do
if sudo test -e "$DB_DIR/quota.db$suffix"; then
sudo test ! -e "$ARCHIVE/quota.db.failed-restore$suffix"
sudo mv "$DB_DIR/quota.db$suffix" \
"$ARCHIVE/quota.db.failed-restore$suffix"
fi
done
sudo mv "$ARCHIVE/quota.db" "$DB_DIR/quota.db"
for suffix in -wal -shm; do
if sudo test -e "$ARCHIVE/quota.db$suffix"; then
sudo mv "$ARCHIVE/quota.db$suffix" "$DB_DIR/quota.db$suffix"
fi
done
sudo systemctl start quota-gateway
)
```

Keep the backup file outside the live DB path. This procedure targets the
packaged systemd service and its default DB path; custom `db_path` or service
setups must use their configured path and unit name. An online DB backup does
not include unrelated files in the DB directory, such as `firewall_config.json`;
back up that file separately when needed.

---

## Quota model

The monthly allowance lives on a **user**, not a device (`users` table;
Expand Down Expand Up @@ -843,6 +984,28 @@ drops internet briefly) re-dials on its own. Both only run while ppp0 is
actually **up** (a dead dial has nothing to renew into), and the last-renewed
timestamp is persisted so a gateway restart never re-renews mid-schedule.

### Request body inspection by the WAF

`waf.max_body_bytes` (default 1 MiB) limits the bytes buffered to inspect
`POST`, `PUT`, `PATCH`, and `DELETE` bodies. The WAF checks the actual byte
count while reading, even when the client omits `Content-Length`. Strict mode
returns HTTP 413 for an oversized body before the route runs. Log mode records
the event and forwards the entire stream, including the bytes read before
the limit was reached, without auto-banning the client. The local-subnet exemption and WAF off mode
bypass inspection. Routes that accept large inputs still need their own limits
when WAF blocking is disabled or exempted.

In strict mode, the WAF keeps at most 4,096 active source/endpoint rate buckets
and 4,096 source histories for auto-ban. Rate buckets expire after each
endpoint's configured window. Auto-ban holds only the most recent
`waf.auto_ban_after` timestamps per source and drops hits outside
`waf.ban_window_seconds`. A five-second sweep removes expired state even
without incoming requests. When the rate table is full, an untracked source
on a rate-limited route receives 429 until a slot frees up. A full auto-ban
table keeps its active histories. New sources are still blocked for WAF
violations, but their hits do not accumulate toward a firewall ban until
space becomes available.

### Tailscale remote access

`quota/tailscale.py` (`TailscaleManager`) manages the official `tailscale`
Expand Down
Loading
Loading