Run on SQLite, PostgreSQL or MySQL

[general] database = takes SQLite's file as before, or a server's
address: postgres://... (pgx) or mysql://... / mysql:DSN
(go-sql-driver).  The store's SQL is written once; internal/store's
dialect gives each engine its forms of what differs: ? placeholders
($1 for PostgreSQL), ids returned by RETURNING or LastInsertId, upserts
(ON DUPLICATE KEY UPDATE), INSERT OR IGNORE, GREATEST, booleans, unique
violations, column checks for migrations, indexes.  The schema is one
list with types per engine: names match in any case (NOCASE, an ICU
collation made on PostgreSQL, utf8mb4_0900_as_ci), MySQL keeps indexed
text in VARCHARs and connects with the SQL mode the store wants (ANSI
quotes for "read" and "key", strict, rows matched not changed).
Existing SQLite databases are kept as they are.

bbs db copy DATABASE copies every table into a new database of any
engine, keeping ids (PostgreSQL's sequences set after).  Logs and bbs
check never show a server's password.

Under go test, BBS_TEST_DATABASE puts every test's store on a
PostgreSQL or MySQL server (a schema or database each, dropped after):
the whole suite passes on PostgreSQL 16 and MySQL 8.4 as on SQLite.
The store's own tests check what the engines do differently, and
copying from SQLite into each.

Also: the FTP tests' readiness probe now waits to be counted out, so the
per-address limit test no longer fails at random.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-12 09:09:42 +00:00
1 parent b41f59ec55
commit 2861ba44f0
28 files changed
+1336 -247

No files matched your search

+2 -1
View File
@@ -74,7 +74,7 @@ What there is:
- [customization](https://github.com/Neo-Desktop/bbs-sec/wiki/Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words
- [access levels](https://github.com/Neo-Desktop/bbs-sec/wiki/Access-Levels): levels and flags, areas, doors and menus that require them, time and download limits a day, new users validated by the sysop
- new users sign themselves up (or not: `new_users = no`)
- SQLite storage, one file
- [SQLite, PostgreSQL or MySQL](https://github.com/Neo-Desktop/bbs-sec/wiki/Databases), and `bbs db copy` between them
## Quick start
@@ -102,6 +102,7 @@ The documentation is in the [wiki](https://github.com/Neo-Desktop/bbs-sec/wiki/)
| [Building](https://github.com/Neo-Desktop/bbs-sec/wiki/Building) | Go, the go3270-sec fork, make |
| [Running](https://github.com/Neo-Desktop/bbs-sec/wiki/Running) | first start, systemd, the defaults |
| [Administration](https://github.com/Neo-Desktop/bbs-sec/wiki/Administration) | the bbs command: users, areas, files, mail exchange |
| [Databases](https://github.com/Neo-Desktop/bbs-sec/wiki/Databases) | SQLite, PostgreSQL, MySQL; moving between them |
| [Configuration](https://github.com/Neo-Desktop/bbs-sec/wiki/Configuration) | bbs.conf: its sections, listeners |
| [Access levels](https://github.com/Neo-Desktop/bbs-sec/wiki/Access-Levels) | levels, flags, what areas, doors and menus require, daily limits, validation |
| [Customization](https://github.com/Neo-Desktop/bbs-sec/wiki/Customization) | screens (ANSI art, 3270), menus, prompts |
+5 -1
View File
@@ -11,8 +11,12 @@
name = D-Modem BBS
sysop = Sysop
;location = Somewhere, Earth
; the database: users, messages, mail (made 0600)
; the database: SQLite's file, or a PostgreSQL or MySQL server (whose
; password then lives here: keep this file 0640). bbs db copy moves one
; into another. See docs/wiki/Databases.md
database = /var/lib/bbs/bbs.db
;database = postgres://bbs:PASSWORD@db.example.org/bbs
;database = mysql://bbs:PASSWORD@db.example.org:3306/bbs
; syslog (daemon facility), stderr, none, or a file
log = syslog
; shown before the login (text, or a file)
+26 -2
View File
@@ -82,6 +82,8 @@ func usage() {
[-expires DAYS] [-name NAME] an API key (printed once)
bbs [-config FILE] token list [USER]
bbs [-config FILE] token revoke ID
bbs [-config FILE] db copy DATABASE copy the database into a new one
(a path, postgres://user:password@host/db, mysql://user:password@host/db)
bbs [-config FILE] sshkey add USER FILE|- SSH keys (authorized_keys lines) to log in with
bbs [-config FILE] sshkey list [USER]
bbs [-config FILE] sshkey del ID
@@ -133,7 +135,7 @@ func main() {
fmt.Printf(" host key %s: %s\n", k, server.HostKeyInfo(k))
}
}
fmt.Println("database:", cfg.Database)
fmt.Println("database:", store.Describe(cfg.Database))
fmt.Println("files:", cfg.FilesDir)
if cfg.FTP != nil {
fmt.Printf("ftp: %s, tls %s\n", cfg.FTP.Address, cfg.FTP.TLS)
@@ -203,7 +205,7 @@ func main() {
fatal(err)
}
}
fmt.Println("database ready:", cfg.Database)
fmt.Println("database ready:", store.Describe(cfg.Database))
fmt.Println("make the sysop's account with: bbs user add NAME -sysop")
case "user":
userCmd(cfg, args)
@@ -217,6 +219,8 @@ func main() {
tokenCmd(cfg, args)
case "sshkey":
sshKeyCmd(cfg, args)
case "db":
dbCmd(cfg, args)
case "filearea":
fileAreaCmd(cfg, args)
case "file":
@@ -270,6 +274,7 @@ func serve(cfg *server.Config) int {
}
st := open(cfg)
defer st.Close()
lg.Printf("database: %s (%s)", store.Describe(cfg.Database), st.Engine())
b := bbs.New(cfg.Settings, st, lg)
b.News = cfg.News
b.Doors = cfg.Doors
@@ -1098,3 +1103,22 @@ func requireArg(s string) string {
}
return r.String()
}
func dbCmd(cfg *server.Config, args []string) {
if len(args) != 2 || args[0] != "copy" {
usage()
}
src := open(cfg)
defer src.Close()
dst, err := store.Open(args[1])
if err != nil {
fatal(err)
}
defer dst.Close()
fmt.Printf("copying %s (%s) into %s (%s)\n", store.Describe(cfg.Database), src.Engine(),
store.Describe(args[1]), dst.Engine())
if err := store.Copy(src, dst, func(table string, n int) { fmt.Printf(" %-12s %d\n", table, n) }); err != nil {
fatal(err)
}
fmt.Println("done: set database = in the configuration to the new one")
}
+8
View File
@@ -13,6 +13,14 @@ bbs user sysop NAME # and unsysop
bbs user del NAME # their mail goes; their messages stay
```
## The database
```
bbs db copy DATABASE # into a new one: a path, postgres://..., mysql://...
```
See [Databases](Databases).
## Access
```
+1 -1
View File
@@ -6,7 +6,7 @@ make test
make install # /usr/local/bin/bbs, and /etc/bbs/bbs.conf if there is none
```
There is no cgo: SQLite is [modernc.org/sqlite](https://modernc.org/sqlite).
There is no cgo: SQLite is [modernc.org/sqlite](https://modernc.org/sqlite); PostgreSQL is [pgx](https://github.com/jackc/pgx), MySQL [go-sql-driver](https://github.com/go-sql-driver/mysql), all built in.
go3270 is replaced (in `go.mod`) by the
[go3270-sec](https://github.com/Neo-Desktop/go3270-sec) fork, which adds
+1
View File
@@ -28,6 +28,7 @@ whether terminals are asked what they are: [Terminal identification](Terminal-Id
| `[door NAME]` | a door program | [Doors](Doors) |
| `screens_dir` (in `[general]`), `[menu NAME]`, `[strings]` | the sysop's screens, menus and prompts | [Customization](Customization) |
| `[finger]`, `[gopher]` | the finger and gopher servers | [Finger and gopher](Finger-and-Gopher) |
| `database` (in `[general]`) | SQLite's file, or a PostgreSQL or MySQL server | [Databases](Databases) |
| `[level N]`, `new_user_level`, `validated_level` (in `[general]`) | access levels | [Access levels](Access-Levels) |
| `[http]` | the HTTP API, its WebSockets, the web terminal and metrics | [HTTP API](HTTP-API) |
| `page_command` (in `[general]`) | telling the sysop of a page when they are not on | [Chat and paging](Chat-and-Paging) |
+66
View File
@@ -0,0 +1,66 @@
The BBS keeps its users, messages, mail, file records, FidoNet and news
state, tokens and keys in one database: **SQLite** (the default, one file,
nothing to run), **PostgreSQL** (12 or later) or **MySQL** (8.0 or later).
File areas' files are kept on disk in every case (`files_dir`). Tested with
PostgreSQL 16 and MySQL 8.4; MariaDB is not one of them (it lacks MySQL
8's collations).
```ini
[general]
database = /var/lib/bbs/bbs.db ; SQLite
;database = postgres://bbs:PASSWORD@db.example.org/bbs ; PostgreSQL
;database = mysql://bbs:PASSWORD@db.example.org:3306/bbs ; MySQL
```
| `database` | |
|---|---|
| a path (or `sqlite:PATH`) | SQLite: the file is made (0600) if it is not there |
| `postgres://` or `postgresql://` | PostgreSQL, in pgx's form: `?sslmode=require`, `?search_path=bbs` and the like after it |
| `mysql://user:password@host:port/db` | MySQL; `?tls=true` and go-sql-driver's other options after it |
| `mysql:DSN` | MySQL in go-sql-driver's own form, for a unix socket: `mysql:bbs:PASSWORD@unix(/run/mysqld/mysqld.sock)/bbs` |
The BBS makes its tables (and adds columns later versions bring) when it
starts, or with `bbs init`. The database (PostgreSQL's, or MySQL's) must
be there, and the user own it or have `CREATE` in it; on PostgreSQL the
BBS also makes a collation, `nocase`, for names that match in any case.
Logs and `bbs check` show the address with its password as `xxxxx`. The
configuration file has it in the clear: keep it 0640, the BBS's group's.
## What differs
Little, by design: the BBS writes its SQL once, and each engine is given
its own forms of what differs (ids, placeholders, upserts, booleans, what
counts as a duplicate).
- **Names** (users, areas, files) match in any case on all three; letters
with accents are not their plain letters (René is not Rene). SQLite
folds the case of ASCII letters only: `RENÉ` finds René on PostgreSQL
and MySQL, not on SQLite.
- **MySQL** keeps names, Message-IDs and other indexed text in
`VARCHAR(255)`, descriptions and the like in `VARCHAR(1024)`, messages
in `MEDIUMTEXT` (16 MB). The BBS's connection sets the SQL mode it
needs (`ANSI_QUOTES`, strict), whatever the server's default.
- **SQLite** uses one connection (it takes one writer at a time); the
servers up to ten.
## Moving to another engine
```
bbs db copy postgres://bbs:PASSWORD@db.example.org/bbs
```
copies the configured database, every table, into a new, empty one (made
as `bbs init` would), keeping ids, then says so; then set `database =` to
the new one. The BBS should be stopped while it copies. It goes any way:
SQLite to PostgreSQL, MySQL to SQLite, PostgreSQL to MySQL.
## Backups
- SQLite: `sqlite3 bbs.db ".backup bbs-backup.db"` (or copy the file while
the BBS is stopped); `bbs db copy /path/to/backup.db` does it too.
- PostgreSQL: `pg_dump`; MySQL: `mysqldump --single-transaction`.
And `files_dir`, in every case.
**See also:** [Configuration](Configuration), [Running](Running), [Development](Development)
+14 -1
View File
@@ -28,11 +28,24 @@
| `internal/xfer` | XMODEM, YMODEM, ZMODEM and Kermit, both ways |
| `internal/logo` | the logo: a PNG, or the name in a pixel font |
| `internal/bbs` | the BBS itself: nodes, logins, new users, posting, cleaning text |
| `internal/store` | the SQLite database |
| `internal/store` | the database: SQLite, PostgreSQL or MySQL (`dialect.go` what differs, `schema.go` the tables), copying between them |
| `internal/config` | the configuration file |
## Tests
With `BBS_TEST_DATABASE` set to a PostgreSQL or MySQL server, every test's
store is a database of its own there (a schema on PostgreSQL, a database
on MySQL, dropped after), so the whole suite runs on that engine:
```
BBS_TEST_DATABASE='postgres://bbs:PASSWORD@127.0.0.1/bbs?sslmode=disable' go test ./...
BBS_TEST_DATABASE='mysql://bbs:PASSWORD@127.0.0.1:3306/bbs' go test ./...
```
(the user may `CREATE SCHEMA`, or `CREATE DATABASE`). The store's own
tests check what the engines do differently: names in any case, ids,
upserts, booleans, bytes, long text, cascades, copying from SQLite.
`make test` runs the unit tests (text cleaning, names and passwords, the
configuration, telnet negotiation and the 3270 handoff) and whole sessions
against a running server on unix sockets: a modem caller with a trusted
+2 -1
View File
@@ -72,7 +72,7 @@ What there is:
- [customization](Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words
- [access levels](Access-Levels): levels and flags, areas, doors and menus that require them, time and download limits a day, new users validated by the sysop
- new users sign themselves up (or not: `new_users = no`)
- SQLite storage, one file
- [SQLite, PostgreSQL or MySQL](Databases), and `bbs db copy` between them
## The pages
@@ -81,6 +81,7 @@ What there is:
| [Building](Building) | Go, the go3270-sec fork, `make` |
| [Running](Running) | first start, systemd, the defaults |
| [Administration](Administration) | the `bbs` command: users, areas, files, mail exchange |
| [Databases](Databases) | SQLite, PostgreSQL, MySQL; moving between them |
| [Configuration](Configuration) | `bbs.conf`: its sections, listeners |
| [Access levels](Access-Levels) | levels, flags, what areas, doors and menus require, daily limits, validation |
| [Customization](Customization) | screens (ANSI art, 3270), menus, prompts |
+2 -1
View File
@@ -9,7 +9,8 @@ bbs -config /etc/bbs/bbs.conf serve
user, with the database in `/var/lib/bbs` and sockets in `/run/bbs`.
Without `-config` it runs with the defaults: telnet and TN3270 on port
2300, modem callers raw on 127.0.0.1:2323, the database `bbs.db` here.
2300, modem callers raw on 127.0.0.1:2323, the database `bbs.db` here. The database can as well
be PostgreSQL or MySQL: see [Databases](Databases).
Day to day: [Administration](Administration).
+3
View File
@@ -67,6 +67,9 @@
and revocable; rate limits per token and per address; JSON bodies
limited and strict; one CORS origin at most, and WebSockets only from
it and the API's own host. Metrics are on an address of their own.
- Databases: SQLite's file is made 0600; a server's password is never
logged (`bbs check` and the log show `xxxxx`); the configuration file
holding it should be 0640. Every query takes its values as parameters.
- Access levels: checked in the BBS's core, so the text BBS, 3270s, FTP,
NNTP and the API keep them alike; an area a user may not read is not
listed, opened, or found by a message's number or Message-ID; no user
+1
View File
@@ -5,6 +5,7 @@
- [Running](Running)
- [Administration](Administration)
- [Configuration](Configuration)
- [Databases](Databases)
- [Customization](Customization)
- [Access levels](Access-Levels)
+7
View File
@@ -7,6 +7,8 @@ toolchain go1.24.7
require (
github.com/coder/websocket v1.8.13
github.com/fclairamb/ftpserverlib v0.30.0
github.com/go-sql-driver/mysql v1.8.1
github.com/jackc/pgx/v5 v5.7.2
github.com/jlaffaye/ftp v0.2.0
github.com/racingmars/go3270 v0.9.13
github.com/spf13/afero v1.15.0
@@ -20,14 +22,19 @@ require (
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sync v0.16.0 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
+18
View File
@@ -1,13 +1,18 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f h1:Bt6G332gAcwKuDK+WBYMx6MgAsAbjEwBPb0fSxwQch8=
github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f/go.mod h1:JCzKbsCGdevsd+2iLMRw3Cd+Wk7vmBeGlnfHmeJEcsU=
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/fclairamb/ftpserverlib v0.30.0 h1:caB9sDn1Au//q0j2ev/icPn388qPuk4k1ajSvglDcMQ=
github.com/fclairamb/ftpserverlib v0.30.0/go.mod h1:QmogtltTOgkihyKza0GNo37Mu4AEzbJ+sH6W9Y0MBIQ=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
@@ -20,6 +25,14 @@ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+l
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jlaffaye/ftp v0.2.0 h1:lXNvW7cBu7R/68bknOX3MrRIIqZ61zELs1P2RAiA3lg=
github.com/jlaffaye/ftp v0.2.0/go.mod h1:is2Ds5qkhceAPy2xD6RLI6hmp/qysSoymZ+Z2uTnspI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
@@ -34,6 +47,9 @@ github.com/secsy/goftp v0.0.0-20200609142545-aa2de14babf4 h1:PT+ElG/UUFMfqy5HrxJ
github.com/secsy/goftp v0.0.0-20200609142545-aa2de14babf4/go.mod h1:MnkX001NG75g3p8bhFycnyIjeQoOjGL6CEIsdE/nKSY=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
@@ -57,6 +73,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IV
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
+18
View File
@@ -1,6 +1,7 @@
package ftp
import (
"bufio"
"bytes"
"context"
"crypto/ecdsa"
@@ -104,6 +105,9 @@ func start(t *testing.T, tweak func(*Settings)) *env {
})
for i := 0; ; i++ {
if c, err := net.Dial("tcp", set.Address); err == nil {
// the greeting comes once the server has counted it
c.SetReadDeadline(time.Now().Add(5 * time.Second))
bufio.NewReader(c).ReadString('\n')
c.Close()
break
}
@@ -112,6 +116,20 @@ func start(t *testing.T, tweak func(*Settings)) *env {
}
time.Sleep(20 * time.Millisecond)
}
// the probe is counted against its address until the server sees it
// gone: wait, or a test of the limit finds it still there
for i := 0; ; i++ {
srv.mu.Lock()
n := srv.clients
srv.mu.Unlock()
if n == 0 {
break
}
if i > 100 {
t.Fatal("the probe connection never went")
}
time.Sleep(10 * time.Millisecond)
}
return &env{addr: set.Address, b: b, log: &logbuf}
}
+11 -1
View File
@@ -21,6 +21,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/logo"
"github.com/Neo-Desktop/bbs-sec/internal/nntp"
"github.com/Neo-Desktop/bbs-sec/internal/screens"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/ui3270"
)
@@ -118,7 +119,7 @@ func Load(path string) (*Config, error) {
}
names[l.Name] = true
if l.Kind == "ssh" && len(l.HostKeys) == 0 {
l.HostKeys = DefaultHostKeys(filepath.Dir(c.Database))
l.HostKeys = DefaultHostKeys(c.DataDir())
}
c.Listeners = append(c.Listeners, l)
c.warn(l)
@@ -142,6 +143,15 @@ func Load(path string) (*Config, error) {
return c, nil
}
// DataDir is where the BBS keeps what it makes (host keys): beside an
// SQLite database, or here for a server's.
func (c *Config) DataDir() string {
if store.IsFile(c.Database) {
return filepath.Dir(strings.TrimPrefix(c.Database, "sqlite:"))
}
return "."
}
func (c *Config) general(g *config.Section) error {
s := &c.Settings
var err error
+1 -1
View File
@@ -62,7 +62,7 @@ func (s *Store) SetFileAreaRequire(id int64, download, upload string) error {
// UsersBelow lists the users whose level is under level (and are not
// sysops or locked): those waiting to be validated.
func (s *Store) UsersBelow(level int) ([]*User, error) {
rows, err := s.db.Query(`SELECT `+userCols+` FROM users WHERE level < ? AND sysop = 0 AND locked = 0 ORDER BY id`, level)
rows, err := s.db.Query(`SELECT `+userCols+` FROM users WHERE level < ? AND sysop = FALSE AND locked = FALSE ORDER BY id`, level)
if err != nil {
return nil, err
}
+123
View File
@@ -0,0 +1,123 @@
package store
import (
"errors"
"fmt"
"regexp"
"strings"
)
// copyOrder is the tables in an order their references allow.
var copyOrder = []string{"users", "areas", "messages", "lastread", "mail", "file_areas", "files",
"history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys"}
var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`)
// columns are a table's columns and their schema types ({int}, {bool}...),
// as tables has them.
func columns(table string) ([]string, map[string]string) {
for _, t := range tables {
if !strings.Contains(t, "EXISTS "+table+" (") {
continue
}
var names []string
kinds := map[string]string{}
for _, m := range columnPat.FindAllStringSubmatch(t, -1) {
names = append(names, m[1])
kinds[m[1]] = m[2]
}
return names, kinds
}
return nil, nil
}
// Copy copies every table of src into dst, which must be empty (a new
// database: Open makes its tables). progress is told each table's rows.
func Copy(src, dst *Store, progress func(table string, rows int)) error {
var n int
if err := dst.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil {
return err
}
if n > 0 {
return errors.New("the database to copy into has users already: it must be new")
}
t, err := dst.db.Begin()
if err != nil {
return err
}
defer t.Rollback()
for _, table := range copyOrder {
cols, kinds := columns(table)
rows, err := src.db.Query(`SELECT ` + strings.Join(cols, ", ") + ` FROM ` + table)
if err != nil {
return fmt.Errorf("%s: %w", table, err)
}
ins := `INSERT INTO ` + table + ` (` + strings.Join(cols, ", ") + `) VALUES (?` +
strings.Repeat(", ?", len(cols)-1) + `)`
count := 0
for rows.Next() {
vals := make([]any, len(cols))
ptrs := make([]any, len(cols))
for i := range vals {
ptrs[i] = &vals[i]
}
if err := rows.Scan(ptrs...); err != nil {
rows.Close()
return fmt.Errorf("%s: %w", table, err)
}
for i, c := range cols {
vals[i] = convert(vals[i], kinds[c])
}
if _, err := t.Exec(ins, vals...); err != nil {
rows.Close()
return fmt.Errorf("%s: %w", table, err)
}
count++
}
rows.Close()
if err := rows.Err(); err != nil {
return fmt.Errorf("%s: %w", table, err)
}
if progress != nil {
progress(table, count)
}
}
if err := t.Commit(); err != nil {
return err
}
// ids go on from the copied ones
if dst.db.d.name == Postgres {
for _, table := range copyOrder {
if cols, _ := columns(table); len(cols) > 0 && cols[0] == "id" {
if _, err := dst.db.Exec(`SELECT setval(pg_get_serial_sequence('` + table + `', 'id'),
COALESCE((SELECT MAX(id) FROM ` + table + `), 0) + 1, false)`); err != nil {
return fmt.Errorf("%s: %w", table, err)
}
}
}
}
return nil
}
// convert makes a value read from one engine one the other takes for its
// column: booleans from 0 and 1, strings from bytes (but bytes' columns).
func convert(v any, kind string) any {
switch kind {
case "{bool}":
switch b := v.(type) {
case int64:
return b != 0
case []byte:
return string(b) == "1" || strings.EqualFold(string(b), "true")
}
case "{blob}":
if s, ok := v.(string); ok {
return []byte(s)
}
default:
if b, ok := v.([]byte); ok {
return string(b)
}
}
return v
}
+319
View File
@@ -0,0 +1,319 @@
package store
import (
"database/sql"
"errors"
"fmt"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/go-sql-driver/mysql"
_ "github.com/jackc/pgx/v5/stdlib" // "pgx"
_ "modernc.org/sqlite" // "sqlite"
)
// The engines the store runs on.
const (
SQLite = "sqlite"
Postgres = "postgres"
MySQL = "mysql"
)
// dialect is what differs between the engines: the store's SQL is written
// once, with ? placeholders and SQLite's forms, and made the engine's here.
type dialect struct {
name string
// the schema's types
types map[string]string
}
var dialects = map[string]*dialect{
SQLite: {name: SQLite, types: map[string]string{
"{id}": "INTEGER PRIMARY KEY", "{int}": "INTEGER", "{bool}": "INTEGER",
"{name}": "TEXT COLLATE NOCASE", "{key}": "TEXT", "{str}": "TEXT", "{text}": "TEXT", "{blob}": "BLOB",
}},
// names: a case-insensitive ICU collation (made in Open)
Postgres: {name: Postgres, types: map[string]string{
"{id}": "BIGSERIAL PRIMARY KEY", "{int}": "BIGINT", "{bool}": "BOOLEAN",
"{name}": "TEXT COLLATE nocase", "{key}": "TEXT", "{str}": "TEXT", "{text}": "TEXT", "{blob}": "BYTEA",
}},
// indexed strings are VARCHARs; names case-insensitive, not accent-
// insensitive; keys (Message-IDs, hashes) exact
MySQL: {name: MySQL, types: map[string]string{
"{id}": "BIGINT AUTO_INCREMENT PRIMARY KEY", "{int}": "BIGINT", "{bool}": "BOOLEAN",
"{name}": "VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_as_ci",
"{key}": "VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin",
"{str}": "VARCHAR(1024) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_as_cs",
"{text}": "MEDIUMTEXT CHARACTER SET utf8mb4", "{blob}": "LONGBLOB",
}},
}
// ddl is a schema statement in the engine's types.
func (d *dialect) ddl(s string) string {
for k, v := range d.types {
s = strings.ReplaceAll(s, k, v)
}
return s
}
var (
conflictPat = regexp.MustCompile(`(?s)ON CONFLICT \([^)]*\) DO UPDATE SET`)
excludedPat = regexp.MustCompile(`excluded\.(\w+)`)
)
// query is a statement in the engine's SQL: its placeholders ($1 ... for
// PostgreSQL), INSERT OR IGNORE, upserts, {greatest}.
func (d *dialect) query(q string) string {
switch d.name {
case SQLite:
return strings.ReplaceAll(q, "{greatest}", "MAX")
case MySQL:
q = strings.ReplaceAll(q, "{greatest}", "GREATEST")
q = strings.Replace(q, "INSERT OR IGNORE INTO", "INSERT IGNORE INTO", 1)
if conflictPat.MatchString(q) {
q = conflictPat.ReplaceAllString(q, "ON DUPLICATE KEY UPDATE")
q = excludedPat.ReplaceAllString(q, "VALUES($1)")
}
return q
}
q = strings.ReplaceAll(q, "{greatest}", "GREATEST")
if strings.HasPrefix(q, "INSERT OR IGNORE INTO") {
q = "INSERT INTO" + strings.TrimPrefix(q, "INSERT OR IGNORE INTO") + " ON CONFLICT DO NOTHING"
}
return rebind(q)
}
// rebind numbers the ? placeholders, outside quotes.
func rebind(q string) string {
var b strings.Builder
n := 0
quote := byte(0)
for i := 0; i < len(q); i++ {
c := q[i]
switch {
case quote != 0:
if c == quote {
quote = 0
}
case c == '\'' || c == '"':
quote = c
case c == '?':
n++
b.WriteString("$" + strconv.Itoa(n))
continue
}
b.WriteByte(c)
}
return b.String()
}
// isUnique reports a unique constraint's violation, in any engine's words.
func isUnique(err error) bool {
if err == nil {
return false
}
var me *mysql.MySQLError
if errors.As(err, &me) {
return me.Number == 1062
}
s := err.Error()
return strings.Contains(s, "UNIQUE") || strings.Contains(s, "SQLSTATE 23505") ||
strings.Contains(s, "duplicate key value")
}
// db is the database, its statements made the engine's.
type db struct {
*sql.DB
d *dialect
}
func (x *db) Exec(q string, args ...any) (sql.Result, error) {
return x.DB.Exec(x.d.query(q), args...)
}
func (x *db) Query(q string, args ...any) (*sql.Rows, error) {
return x.DB.Query(x.d.query(q), args...)
}
func (x *db) QueryRow(q string, args ...any) *sql.Row {
return x.DB.QueryRow(x.d.query(q), args...)
}
func (x *db) Begin() (*tx, error) {
t, err := x.DB.Begin()
if err != nil {
return nil, err
}
return &tx{Tx: t, d: x.d}, nil
}
// insertID runs an INSERT and returns the new row's id.
func (x *db) insertID(q string, args ...any) (int64, error) {
return insertID(x.d, x.DB.Exec, x.DB.QueryRow, q, args)
}
// tx is a transaction, its statements made the engine's.
type tx struct {
*sql.Tx
d *dialect
}
func (t *tx) Exec(q string, args ...any) (sql.Result, error) {
return t.Tx.Exec(t.d.query(q), args...)
}
func (t *tx) insertID(q string, args ...any) (int64, error) {
return insertID(t.d, t.Tx.Exec, t.Tx.QueryRow, q, args)
}
func insertID(d *dialect, exec func(string, ...any) (sql.Result, error),
row func(string, ...any) *sql.Row, q string, args []any) (int64, error) {
if d.name == MySQL {
res, err := exec(d.query(q), args...)
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// SQLite (3.35 and later) and PostgreSQL say it themselves
var id int64
err := row(d.query(q+" RETURNING id"), args...).Scan(&id)
return id, err
}
// hasColumn reports whether a table has a column (for migrations).
func (x *db) hasColumn(table, column string) (bool, error) {
var q string
switch x.d.name {
case SQLite:
q = `SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?`
case Postgres:
q = `SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?`
case MySQL:
q = `SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`
}
var n int
err := x.QueryRow(q, table, column).Scan(&n)
return n > 0, err
}
// index makes an index if there is none of that name.
func (x *db) index(name, table, cols string, unique bool) error {
kind := "INDEX"
if unique {
kind = "UNIQUE INDEX"
}
if x.d.name == MySQL {
var n int
if err := x.QueryRow(`SELECT COUNT(*) FROM information_schema.statistics
WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?`, table, name).Scan(&n); err != nil {
return err
}
if n > 0 {
return nil
}
_, err := x.Exec(fmt.Sprintf("CREATE %s %s ON %s (%s)", kind, name, table, cols))
return err
}
_, err := x.Exec(fmt.Sprintf("CREATE %s IF NOT EXISTS %s ON %s (%s)", kind, name, table, cols))
return err
}
// openDB opens a database by its address: a path (SQLite), postgres://
// or postgresql:// (PostgreSQL, as pgx takes it), mysql://user:pass@host:port/db
// or mysql:DSN (MySQL, go-sql-driver's form).
func openDB(addr string) (*db, error) {
switch {
case strings.HasPrefix(addr, "postgres://"), strings.HasPrefix(addr, "postgresql://"):
sdb, err := sql.Open("pgx", addr)
if err != nil {
return nil, err
}
sdb.SetMaxOpenConns(10)
return &db{DB: sdb, d: dialects[Postgres]}, nil
case strings.HasPrefix(addr, "mysql:"):
cfg, err := mysqlConfig(addr)
if err != nil {
return nil, err
}
sdb, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, err
}
sdb.SetMaxOpenConns(10)
return &db{DB: sdb, d: dialects[MySQL]}, nil
}
return nil, nil // SQLite: Open does it
}
// mysqlConfig reads mysql://user:password@host:port/database?params, or
// mysql:DSN; with the SQL mode the store's SQL wants (ANSI quotes, strict).
func mysqlConfig(addr string) (*mysql.Config, error) {
var cfg *mysql.Config
if strings.HasPrefix(addr, "mysql://") {
u, err := url.Parse(addr)
if err != nil {
return nil, fmt.Errorf("database: %w", err)
}
cfg = mysql.NewConfig()
cfg.User = u.User.Username()
cfg.Passwd, _ = u.User.Password()
cfg.Net, cfg.Addr = "tcp", u.Host
if !strings.Contains(u.Host, ":") {
cfg.Addr += ":3306"
}
cfg.DBName = strings.TrimPrefix(u.Path, "/")
for k, v := range u.Query() {
if cfg.Params == nil {
cfg.Params = map[string]string{}
}
cfg.Params[k] = v[0]
}
} else {
var err error
if cfg, err = mysql.ParseDSN(strings.TrimPrefix(addr, "mysql:")); err != nil {
return nil, fmt.Errorf("database: %w", err)
}
}
if cfg.DBName == "" {
return nil, errors.New("database: a MySQL database's name: mysql://user:password@host/bbs")
}
if cfg.Params == nil {
cfg.Params = map[string]string{}
}
cfg.Params["sql_mode"] = "'ANSI_QUOTES,STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"
cfg.Params["charset"] = "utf8mb4"
// rows matched, not changed, as the others count them (an UPDATE to the
// same value is not "not found")
cfg.ClientFoundRows = true
return cfg, nil
}
// IsFile reports whether a database address is a file's (SQLite), not a
// server's.
func IsFile(addr string) bool {
return !strings.HasPrefix(addr, "postgres://") && !strings.HasPrefix(addr, "postgresql://") &&
!strings.HasPrefix(addr, "mysql:")
}
// Engine is the store's: SQLite, Postgres or MySQL.
func (s *Store) Engine() string { return s.db.d.name }
// Describe is the database's address without its password, for logs.
func Describe(addr string) string {
if u, err := url.Parse(addr); err == nil && u.User != nil {
if _, set := u.User.Password(); set {
u.User = url.UserPassword(u.User.Username(), "xxxxx")
return u.String()
}
}
if strings.HasPrefix(addr, "mysql:") && !strings.HasPrefix(addr, "mysql://") {
if cfg, err := mysql.ParseDSN(strings.TrimPrefix(addr, "mysql:")); err == nil && cfg.Passwd != "" {
cfg.Passwd = "xxxxx"
return "mysql:" + cfg.FormatDSN()
}
}
return addr
}
+62
View File
@@ -0,0 +1,62 @@
package store
import (
"strings"
"testing"
)
func TestQuery(t *testing.T) {
pg, my, lite := dialects[Postgres], dialects[MySQL], dialects[SQLite]
q := `SELECT a FROM t WHERE x = ? AND y = '?' AND "z?" = ? LIMIT ?`
if got := pg.query(q); got != `SELECT a FROM t WHERE x = $1 AND y = '?' AND "z?" = $2 LIMIT $3` {
t.Errorf("rebind: %s", got)
}
if lite.query(q) != q || my.query(q) != q {
t.Error("? changed for SQLite or MySQL")
}
ins := `INSERT OR IGNORE INTO history (message_id, seen) VALUES (?, ?)`
if got := pg.query(ins); got != `INSERT INTO history (message_id, seen) VALUES ($1, $2) ON CONFLICT DO NOTHING` {
t.Errorf("pg ignore: %s", got)
}
if got := my.query(ins); got != `INSERT IGNORE INTO history (message_id, seen) VALUES (?, ?)` {
t.Errorf("mysql ignore: %s", got)
}
up := `INSERT INTO lastread (user_id, area_id, message_id) VALUES (?, ?, ?)
ON CONFLICT (user_id, area_id) DO UPDATE SET message_id = {greatest}(lastread.message_id, excluded.message_id)`
if got := my.query(up); !strings.Contains(got, "ON DUPLICATE KEY UPDATE message_id = GREATEST(lastread.message_id, VALUES(message_id))") {
t.Errorf("mysql upsert: %s", got)
}
if got := lite.query(up); !strings.Contains(got, "MAX(lastread.message_id, excluded.message_id)") {
t.Errorf("sqlite upsert: %s", got)
}
if got := pg.query(up); !strings.Contains(got, "GREATEST(lastread.message_id, excluded.message_id)") || !strings.Contains(got, "$3") {
t.Errorf("pg upsert: %s", got)
}
if got := my.ddl("id {id}, n {name} NOT NULL UNIQUE, b {bool}"); !strings.Contains(got, "AUTO_INCREMENT") || !strings.Contains(got, "utf8mb4_0900_as_ci") {
t.Errorf("mysql ddl: %s", got)
}
}
func TestAddresses(t *testing.T) {
for addr, want := range map[string]string{
"postgres://bbs:secret@db/bbs": "postgres://bbs:xxxxx@db/bbs",
"mysql://bbs:secret@db:3306/bbs": "mysql://bbs:xxxxx@db:3306/bbs",
"mysql:bbs:secret@unix(/run/my.sock)/b": "mysql:bbs:xxxxx@unix(/run/my.sock)/b",
"/var/lib/bbs/bbs.db": "/var/lib/bbs/bbs.db",
} {
if got := Describe(addr); !strings.HasPrefix(got, want) || strings.Contains(got, "secret") {
t.Errorf("%s: %s", addr, got)
}
}
cfg, err := mysqlConfig("mysql://bbs:pw@db.example/bbs?tls=true")
if err != nil || cfg.Addr != "db.example:3306" || cfg.User != "bbs" || cfg.Passwd != "pw" || cfg.DBName != "bbs" ||
!strings.Contains(cfg.Params["sql_mode"], "ANSI_QUOTES") || !cfg.ClientFoundRows {
t.Errorf("mysql config: %+v %v", cfg, err)
}
if _, err := mysqlConfig("mysql://bbs:pw@db/"); err == nil {
t.Error("no database name taken")
}
if !IsFile("bbs.db") || !IsFile("sqlite:x.db") || IsFile("postgresql://x/y") || IsFile("mysql:u@/d") {
t.Error("IsFile")
}
}
+3 -3
View File
@@ -17,7 +17,7 @@ func nullString(s string) any {
// SetEchoTag makes an area a FidoNet echo ("": not one any more).
func (s *Store) SetEchoTag(area int64, tag string) error {
_, err := s.db.Exec(`UPDATE areas SET echotag = ? WHERE id = ?`, nullString(tag), area)
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
if err != nil && isUnique(err) {
return ErrExists
}
return err
@@ -114,12 +114,12 @@ type Netmail struct {
// QueueNetmail queues a netmail.
func (s *Store) QueueNetmail(n *Netmail) (int64, error) {
res, err := s.db.Exec(`INSERT INTO netmail_out (from_id, from_name, to_name, to_addr, subject, body, msgid, reply, created)
id, err := s.db.insertID(`INSERT INTO netmail_out (from_id, from_name, to_name, to_addr, subject, body, msgid, reply, created)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, n.FromID, n.From, n.To, n.ToAddr, n.Subject, n.Body, n.MsgID, n.Reply, now())
if err != nil {
return 0, err
}
return res.LastInsertId()
return id, nil
}
// PendingNetmail lists netmail not yet packed.
+1 -79
View File
@@ -3,88 +3,10 @@ package store
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
)
// migrate brings an older database up to date: columns added since.
func migrate(db *sql.DB) error {
add := []struct{ table, column, decl string }{
{"areas", "newsgroup", "TEXT"},
{"messages", "message_id", "TEXT"},
{"messages", "origin", "TEXT NOT NULL DEFAULT ''"},
{"messages", "raw", "BLOB"},
{"areas", "echotag", "TEXT"},
{"messages", "ftn_msgid", "TEXT"},
{"messages", "ftn", "BLOB"},
{"mail", "ftn_msgid", "TEXT"},
{"users", "level", "INTEGER NOT NULL DEFAULT 20"},
{"users", "flags", "TEXT NOT NULL DEFAULT ''"},
{"users", "time_day", "INTEGER NOT NULL DEFAULT 0"},
{"users", "time_used", "INTEGER NOT NULL DEFAULT 0"},
{"users", "dl_day", "INTEGER NOT NULL DEFAULT 0"},
{"users", "dl_count", "INTEGER NOT NULL DEFAULT 0"},
{"areas", "read_req", "TEXT NOT NULL DEFAULT ''"},
{"areas", "post_req", "TEXT NOT NULL DEFAULT ''"},
{"file_areas", "download_req", "TEXT NOT NULL DEFAULT ''"},
{"file_areas", "upload_req", "TEXT NOT NULL DEFAULT ''"},
}
for _, a := range add {
var n int
if err := db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?`,
a.table, a.column).Scan(&n); err != nil {
return err
}
if n == 0 {
if _, err := db.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, a.table, a.column, a.decl)); err != nil {
return err
}
}
}
if _, err := db.Exec(tokenSchema); err != nil {
return err
}
if _, err := db.Exec(sshKeySchema); err != nil {
return err
}
_, err := db.Exec(`
CREATE UNIQUE INDEX IF NOT EXISTS areas_newsgroup ON areas(newsgroup) WHERE newsgroup IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS messages_message_id ON messages(message_id) WHERE message_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS history (
message_id TEXT PRIMARY KEY,
seen INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS peer_groups (
peer TEXT NOT NULL,
newsgroup TEXT NOT NULL,
last INTEGER NOT NULL,
PRIMARY KEY (peer, newsgroup)
);
CREATE TABLE IF NOT EXISTS peer_push (
peer TEXT PRIMARY KEY,
last_id INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_created ON messages(created);
CREATE UNIQUE INDEX IF NOT EXISTS areas_echotag ON areas(echotag) WHERE echotag IS NOT NULL;
CREATE INDEX IF NOT EXISTS messages_ftn_msgid ON messages(ftn_msgid) WHERE ftn_msgid IS NOT NULL;
CREATE TABLE IF NOT EXISTS netmail_out (
id INTEGER PRIMARY KEY,
from_id INTEGER NOT NULL,
from_name TEXT NOT NULL,
to_name TEXT NOT NULL,
to_addr TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT NOT NULL,
msgid TEXT NOT NULL,
reply TEXT NOT NULL DEFAULT '',
created INTEGER NOT NULL,
packed INTEGER NOT NULL DEFAULT 0
);
`)
return err
}
// SetNewsgroup makes an area a newsgroup ("": not one any more).
func (s *Store) SetNewsgroup(area int64, group string) error {
var g any
@@ -92,7 +14,7 @@ func (s *Store) SetNewsgroup(area int64, group string) error {
g = group
}
_, err := s.db.Exec(`UPDATE areas SET newsgroup = ? WHERE id = ?`, g, area)
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
if err != nil && isUnique(err) {
return ErrExists
}
return err
+218
View File
@@ -0,0 +1,218 @@
package store
import (
"fmt"
)
// tables is the schema, in the dialect's types: {id} an id that counts
// itself, {int} an integer (unix seconds too), {bool}, {name} a name that
// matches in any case, {key} an indexed string matched exactly, {str} a
// short string, {text} a long one, {blob} bytes. "read" and "key" are
// quoted: MySQL keeps them for itself.
var tables = []string{`
CREATE TABLE IF NOT EXISTS users (
id {id},
name {name} NOT NULL UNIQUE,
password {str} NOT NULL,
location {str} NOT NULL DEFAULT '',
sysop {bool} NOT NULL DEFAULT FALSE,
locked {bool} NOT NULL DEFAULT FALSE,
created {int} NOT NULL,
last_login {int} NOT NULL DEFAULT 0,
logins {int} NOT NULL DEFAULT 0,
posts {int} NOT NULL DEFAULT 0,
level {int} NOT NULL DEFAULT 20,
flags {str} NOT NULL DEFAULT '',
time_day {int} NOT NULL DEFAULT 0,
time_used {int} NOT NULL DEFAULT 0,
dl_day {int} NOT NULL DEFAULT 0,
dl_count {int} NOT NULL DEFAULT 0
)`, `
CREATE TABLE IF NOT EXISTS areas (
id {id},
name {name} NOT NULL UNIQUE,
description {str} NOT NULL DEFAULT '',
sysop_only {bool} NOT NULL DEFAULT FALSE,
newsgroup {key},
echotag {key},
read_req {str} NOT NULL DEFAULT '',
post_req {str} NOT NULL DEFAULT ''
)`, `
CREATE TABLE IF NOT EXISTS messages (
id {id},
area_id {int} NOT NULL REFERENCES areas(id) ON DELETE CASCADE,
from_id {int} NOT NULL,
from_name {str} NOT NULL,
to_name {str} NOT NULL DEFAULT 'All',
subject {str} NOT NULL,
body {text} NOT NULL,
reply_to {int} NOT NULL DEFAULT 0,
created {int} NOT NULL,
message_id {key},
origin {str} NOT NULL DEFAULT '',
raw {blob},
ftn_msgid {key},
ftn {blob}
)`, `
CREATE TABLE IF NOT EXISTS lastread (
user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
area_id {int} NOT NULL REFERENCES areas(id) ON DELETE CASCADE,
message_id {int} NOT NULL,
PRIMARY KEY (user_id, area_id)
)`, `
CREATE TABLE IF NOT EXISTS mail (
id {id},
from_id {int} NOT NULL,
from_name {str} NOT NULL,
to_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
to_name {str} NOT NULL,
subject {str} NOT NULL,
body {text} NOT NULL,
reply_to {int} NOT NULL DEFAULT 0,
created {int} NOT NULL,
"read" {bool} NOT NULL DEFAULT FALSE,
ftn_msgid {key}
)`, `
CREATE TABLE IF NOT EXISTS file_areas (
id {id},
name {name} NOT NULL UNIQUE,
description {str} NOT NULL DEFAULT '',
sysop_upload {bool} NOT NULL DEFAULT FALSE,
download_req {str} NOT NULL DEFAULT '',
upload_req {str} NOT NULL DEFAULT ''
)`, `
CREATE TABLE IF NOT EXISTS files (
id {id},
area_id {int} NOT NULL REFERENCES file_areas(id),
name {name} NOT NULL,
description {str} NOT NULL DEFAULT '',
size {int} NOT NULL,
sha256 {key} NOT NULL,
uploader_id {int} NOT NULL,
uploader {str} NOT NULL,
created {int} NOT NULL,
downloads {int} NOT NULL DEFAULT 0,
UNIQUE (area_id, name)
)`, `
CREATE TABLE IF NOT EXISTS history (
message_id {key} PRIMARY KEY,
seen {int} NOT NULL
)`, `
CREATE TABLE IF NOT EXISTS peer_groups (
peer {key} NOT NULL,
newsgroup {key} NOT NULL,
last {int} NOT NULL,
PRIMARY KEY (peer, newsgroup)
)`, `
CREATE TABLE IF NOT EXISTS peer_push (
peer {key} PRIMARY KEY,
last_id {int} NOT NULL
)`, `
CREATE TABLE IF NOT EXISTS netmail_out (
id {id},
from_id {int} NOT NULL,
from_name {str} NOT NULL,
to_name {str} NOT NULL,
to_addr {str} NOT NULL,
subject {str} NOT NULL,
body {text} NOT NULL,
msgid {str} NOT NULL,
reply {str} NOT NULL DEFAULT '',
created {int} NOT NULL,
packed {int} NOT NULL DEFAULT 0
)`, `
CREATE TABLE IF NOT EXISTS api_tokens (
id {id},
user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name {str} NOT NULL,
hash {key} NOT NULL UNIQUE,
scopes {str} NOT NULL,
session {bool} NOT NULL DEFAULT FALSE,
created {int} NOT NULL,
expires {int} NOT NULL DEFAULT 0,
last_used {int} NOT NULL DEFAULT 0
)`, `
CREATE TABLE IF NOT EXISTS ssh_keys (
id {id},
user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type {str} NOT NULL,
fingerprint {key} NOT NULL UNIQUE,
"key" {text} NOT NULL,
comment {str} NOT NULL DEFAULT '',
created {int} NOT NULL,
last_used {int} NOT NULL DEFAULT 0
)`,
}
// indexes are made if missing. NULLs do not clash in unique ones, in
// any of the engines.
var indexes = []struct {
name, table, cols string
unique bool
}{
{"messages_area", "messages", "area_id, id", false},
{"mail_to", "mail", "to_id, id", false},
{"files_uploader", "files", "uploader_id, created", false},
{"areas_newsgroup", "areas", "newsgroup", true},
{"messages_message_id", "messages", "message_id", true},
{"messages_created", "messages", "created", false},
{"areas_echotag", "areas", "echotag", true},
{"messages_ftn_msgid", "messages", "ftn_msgid", false},
{"api_tokens_user", "api_tokens", "user_id", false},
{"ssh_keys_user", "ssh_keys", "user_id", false},
}
// added are the columns added since the first schema: an older database
// (SQLite, from before) gets them.
var added = []struct{ table, column, decl string }{
{"areas", "newsgroup", "{key}"},
{"messages", "message_id", "{key}"},
{"messages", "origin", "{str} NOT NULL DEFAULT ''"},
{"messages", "raw", "{blob}"},
{"areas", "echotag", "{key}"},
{"messages", "ftn_msgid", "{key}"},
{"messages", "ftn", "{blob}"},
{"mail", "ftn_msgid", "{key}"},
{"users", "level", "{int} NOT NULL DEFAULT 20"},
{"users", "flags", "{str} NOT NULL DEFAULT ''"},
{"users", "time_day", "{int} NOT NULL DEFAULT 0"},
{"users", "time_used", "{int} NOT NULL DEFAULT 0"},
{"users", "dl_day", "{int} NOT NULL DEFAULT 0"},
{"users", "dl_count", "{int} NOT NULL DEFAULT 0"},
{"areas", "read_req", "{str} NOT NULL DEFAULT ''"},
{"areas", "post_req", "{str} NOT NULL DEFAULT ''"},
{"file_areas", "download_req", "{str} NOT NULL DEFAULT ''"},
{"file_areas", "upload_req", "{str} NOT NULL DEFAULT ''"},
}
// migrate makes the schema, or brings an older database up to it.
func migrate(x *db) error {
if x.d.name == Postgres {
// names that match in any case: ICU's, at strength 2
if _, err := x.Exec(`CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)`); err != nil {
return fmt.Errorf("the nocase collation: %w", err)
}
}
for _, t := range tables {
if _, err := x.Exec(x.d.ddl(t)); err != nil {
return err
}
}
for _, a := range added {
ok, err := x.hasColumn(a.table, a.column)
if err != nil {
return err
}
if !ok {
if _, err := x.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, a.table, a.column, x.d.ddl(a.decl))); err != nil {
return err
}
}
}
for _, i := range indexes {
if err := x.index(i.name, i.table, i.cols, i.unique); err != nil {
return fmt.Errorf("index %s: %w", i.name, err)
}
}
return nil
}
+3 -17
View File
@@ -19,20 +19,6 @@ type SSHKey struct {
LastUsed time.Time
}
const sshKeySchema = `
CREATE TABLE IF NOT EXISTS ssh_keys (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type TEXT NOT NULL,
fingerprint TEXT NOT NULL UNIQUE,
key TEXT NOT NULL,
comment TEXT NOT NULL DEFAULT '',
created INTEGER NOT NULL,
last_used INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS ssh_keys_user ON ssh_keys(user_id);
`
// ErrKeyTaken: the key is someone's already (a key logs in one user).
var ErrKeyTaken = errors.New("that key is already in use")
@@ -45,15 +31,15 @@ func (s *Store) AddSSHKey(k *SSHKey) (int64, error) {
if n > 0 {
return 0, ErrKeyTaken
}
res, err := s.db.Exec(`INSERT INTO ssh_keys (user_id, type, fingerprint, key, comment, created)
id, err := s.db.insertID(`INSERT INTO ssh_keys (user_id, type, fingerprint, "key", comment, created)
VALUES (?, ?, ?, ?, ?, ?)`, k.UserID, k.Type, k.Fingerprint, k.Key, k.Comment, now())
if err != nil {
return 0, err
}
return res.LastInsertId()
return id, nil
}
const sshKeyCols = `k.id, k.user_id, u.name, k.type, k.fingerprint, k.key, k.comment, k.created, k.last_used`
const sshKeyCols = `k.id, k.user_id, u.name, k.type, k.fingerprint, k."key", k.comment, k.created, k.last_used`
func scanSSHKey(row interface{ Scan(...any) error }) (*SSHKey, error) {
var k SSHKey
+74 -121
View File
@@ -1,5 +1,6 @@
// Package store keeps the BBS in an SQLite database: users, message
// areas and their messages, private mail, and what each user has read.
// Package store keeps the BBS in a database, SQLite, PostgreSQL or MySQL:
// users, message areas and their messages, private mail, what each user
// has read, files' records, FidoNet's and news' state, tokens and keys.
package store
import (
@@ -11,7 +12,6 @@ import (
"time"
"golang.org/x/crypto/bcrypt"
_ "modernc.org/sqlite"
)
// ErrNotFound: no such user, area, message or mail.
@@ -89,121 +89,78 @@ type Message struct {
// Store is the database.
type Store struct {
db *sql.DB
db *db
drop func() // a test's database, dropped at Close
// a hash to check against for unknown users, so that they take as
// long as known ones
dummy []byte
}
const schema = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
password TEXT NOT NULL,
location TEXT NOT NULL DEFAULT '',
sysop INTEGER NOT NULL DEFAULT 0,
locked INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL,
last_login INTEGER NOT NULL DEFAULT 0,
logins INTEGER NOT NULL DEFAULT 0,
posts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS areas (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
description TEXT NOT NULL DEFAULT '',
sysop_only INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY,
area_id INTEGER NOT NULL REFERENCES areas(id) ON DELETE CASCADE,
from_id INTEGER NOT NULL,
from_name TEXT NOT NULL,
to_name TEXT NOT NULL DEFAULT 'All',
subject TEXT NOT NULL,
body TEXT NOT NULL,
reply_to INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_area ON messages(area_id, id);
CREATE TABLE IF NOT EXISTS lastread (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
area_id INTEGER NOT NULL REFERENCES areas(id) ON DELETE CASCADE,
message_id INTEGER NOT NULL,
PRIMARY KEY (user_id, area_id)
);
CREATE TABLE IF NOT EXISTS mail (
id INTEGER PRIMARY KEY,
from_id INTEGER NOT NULL,
from_name TEXT NOT NULL,
to_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
to_name TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT NOT NULL,
reply_to INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL,
read INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS mail_to ON mail(to_id, id);
CREATE TABLE IF NOT EXISTS file_areas (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
description TEXT NOT NULL DEFAULT '',
sysop_upload INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY,
area_id INTEGER NOT NULL REFERENCES file_areas(id),
name TEXT NOT NULL COLLATE NOCASE,
description TEXT NOT NULL DEFAULT '',
size INTEGER NOT NULL,
sha256 TEXT NOT NULL,
uploader_id INTEGER NOT NULL,
uploader TEXT NOT NULL,
created INTEGER NOT NULL,
downloads INTEGER NOT NULL DEFAULT 0,
UNIQUE (area_id, name)
);
CREATE INDEX IF NOT EXISTS files_uploader ON files(uploader_id, created);
`
// Open opens (and creates, if need be) the database at path.
func Open(path string) (*Store, error) {
// passwords and private mail: for the BBS's user alone (SQLite gives
// the -wal and -shm files the database's permissions)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
// Open opens (and makes, if need be) the database at addr: a file's path
// (SQLite; "sqlite:" before it may say so), or a PostgreSQL or MySQL
// server's address: postgres://user:password@host/bbs,
// mysql://user:password@host:3306/bbs.
func Open(addr string) (*Store, error) {
var drop func()
// (tests' plain paths only: "sqlite:" is SQLite whatever the test)
if IsFile(addr) && !strings.HasPrefix(addr, "sqlite:") {
test, d, err := testDatabase()
if err != nil {
return nil, err
}
if test != "" {
addr, drop = test, d
}
}
x, err := openDB(addr)
if err != nil {
return nil, err
}
f.Close()
dsn := "file:" + path + "?_pragma=busy_timeout(5000)" +
"&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)" +
"&_pragma=synchronous(NORMAL)"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
if x == nil {
path := strings.TrimPrefix(addr, "sqlite:")
// passwords and private mail: for the BBS's user alone (SQLite
// gives the -wal and -shm files the database's permissions)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
f.Close()
dsn := "file:" + path + "?_pragma=busy_timeout(5000)" +
"&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)" +
"&_pragma=synchronous(NORMAL)"
sdb, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
}
// one connection: SQLite takes one writer at a time anyway, and a
// BBS is not busy enough to want more
sdb.SetMaxOpenConns(1)
x = &db{DB: sdb, d: dialects[SQLite]}
}
// one connection: SQLite takes one writer at a time anyway, and a BBS
// is not busy enough to want more
db.SetMaxOpenConns(1)
if _, err := db.Exec(schema); err != nil {
db.Close()
return nil, fmt.Errorf("%s: %w", path, err)
if err := x.Ping(); err != nil {
x.Close()
return nil, fmt.Errorf("%s: %w", Describe(addr), err)
}
if err := migrate(db); err != nil {
db.Close()
return nil, fmt.Errorf("%s: %w", path, err)
if err := migrate(x); err != nil {
x.Close()
return nil, fmt.Errorf("%s: %w", Describe(addr), err)
}
dummy, err := bcrypt.GenerateFromPassword([]byte("not a password"), BcryptCost)
if err != nil {
db.Close()
x.Close()
return nil, err
}
return &Store{db: db, dummy: dummy}, nil
return &Store{db: x, dummy: dummy, drop: drop}, nil
}
// Close closes the database.
func (s *Store) Close() error { return s.db.Close() }
func (s *Store) Close() error {
err := s.db.Close()
if s.drop != nil {
s.drop()
}
return err
}
func now() int64 { return time.Now().Unix() }
@@ -251,15 +208,14 @@ func (s *Store) CreateUser(name, password, location string, sysop bool) (*User,
}
hash = h
}
res, err := s.db.Exec(`INSERT INTO users (name, password, location, sysop, created)
id, err := s.db.insertID(`INSERT INTO users (name, password, location, sysop, created)
VALUES (?, ?, ?, ?, ?)`, name, hash, location, sysop, now())
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
if isUnique(err) {
return nil, ErrExists
}
return nil, err
}
id, _ := res.LastInsertId()
return s.UserByID(id)
}
@@ -358,15 +314,14 @@ func (s *Store) exec1(q string, args ...any) error {
// CreateArea adds a message area.
func (s *Store) CreateArea(name, desc string, sysopOnly bool) (*Area, error) {
res, err := s.db.Exec(`INSERT INTO areas (name, description, sysop_only) VALUES (?, ?, ?)`,
id, err := s.db.insertID(`INSERT INTO areas (name, description, sysop_only) VALUES (?, ?, ?)`,
name, desc, sysopOnly)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
if isUnique(err) {
return nil, ErrExists
}
return nil, err
}
id, _ := res.LastInsertId()
return s.Area(id)
}
@@ -446,12 +401,12 @@ func (s *Store) Post(m *Message) (int64, error) {
if m.MessageID != "" {
msgid = m.MessageID
}
res, err := tx.Exec(`INSERT INTO messages (area_id, from_id, from_name, to_name, subject, body, reply_to, created,
id, err := tx.insertID(`INSERT INTO messages (area_id, from_id, from_name, to_name, subject, body, reply_to, created,
message_id, origin, raw, ftn_msgid, ftn)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.AreaID, m.FromID, m.From, m.To, m.Subject, m.Body, m.ReplyTo, now(),
msgid, m.Origin, m.Raw, nullString(m.FTNMsgID), m.FTN)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
if isUnique(err) {
return 0, ErrExists
}
return 0, err
@@ -467,7 +422,6 @@ func (s *Store) Post(m *Message) (int64, error) {
return 0, err
}
}
id, _ := res.LastInsertId()
return id, tx.Commit()
}
@@ -525,7 +479,7 @@ func (s *Store) LastRead(user, area int64) (int64, error) {
// SetLastRead moves the user's last read message of an area forward to id.
func (s *Store) SetLastRead(user, area, id int64) error {
_, err := s.db.Exec(`INSERT INTO lastread (user_id, area_id, message_id) VALUES (?, ?, ?)
ON CONFLICT (user_id, area_id) DO UPDATE SET message_id = MAX(message_id, excluded.message_id)`,
ON CONFLICT (user_id, area_id) DO UPDATE SET message_id = {greatest}(lastread.message_id, excluded.message_id)`,
user, area, id)
return err
}
@@ -542,7 +496,7 @@ func (s *Store) NewCount(user, area int64) (int, error) {
return n, err
}
const mailCols = `id, from_id, from_name, to_id, to_name, subject, body, reply_to, created, read,
const mailCols = `id, from_id, from_name, to_id, to_name, subject, body, reply_to, created, "read",
COALESCE(ftn_msgid, '')`
func scanMail(row interface{ Scan(...any) error }) (*Message, error) {
@@ -559,14 +513,14 @@ func scanMail(row interface{ Scan(...any) error }) (*Message, error) {
// SendMail delivers a private message.
func (s *Store) SendMail(m *Message) (int64, error) {
res, err := s.db.Exec(`INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, reply_to, created,
id, err := s.db.insertID(`INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, reply_to, created,
ftn_msgid)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.FromID, m.From, m.ToID, m.To, m.Subject, m.Body, m.ReplyTo, now(),
nullString(m.FTNMsgID))
if err != nil {
return 0, err
}
return res.LastInsertId()
return id, nil
}
// Inbox lists a user's mail, oldest first.
@@ -594,7 +548,7 @@ func (s *Store) Mail(user, id int64) (*Message, error) {
// MarkMailRead marks a mail of user's read.
func (s *Store) MarkMailRead(user, id int64) error {
return s.exec1(`UPDATE mail SET read = 1 WHERE id = ? AND to_id = ?`, id, user)
return s.exec1(`UPDATE mail SET "read" = TRUE WHERE id = ? AND to_id = ?`, id, user)
}
// DeleteMail deletes a mail of user's.
@@ -605,7 +559,7 @@ func (s *Store) DeleteMail(user, id int64) error {
// UnreadMail counts a user's unread mail.
func (s *Store) UnreadMail(user int64) (int, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM mail WHERE to_id = ? AND read = 0`, user).Scan(&n)
err := s.db.QueryRow(`SELECT COUNT(*) FROM mail WHERE to_id = ? AND "read" = FALSE`, user).Scan(&n)
return n, err
}
@@ -638,15 +592,14 @@ type File struct {
// CreateFileArea adds a file area.
func (s *Store) CreateFileArea(name, desc string, sysopUpload bool) (*FileArea, error) {
res, err := s.db.Exec(`INSERT INTO file_areas (name, description, sysop_upload) VALUES (?, ?, ?)`,
id, err := s.db.insertID(`INSERT INTO file_areas (name, description, sysop_upload) VALUES (?, ?, ?)`,
name, desc, sysopUpload)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
if isUnique(err) {
return nil, ErrExists
}
return nil, err
}
id, _ := res.LastInsertId()
return s.FileArea(id)
}
@@ -720,16 +673,16 @@ func scanFile(row interface{ Scan(...any) error }) (*File, error) {
// AddFile records a file; ErrExists if the area has one of that name.
func (s *Store) AddFile(f *File) (int64, error) {
res, err := s.db.Exec(`INSERT INTO files (area_id, name, description, size, sha256, uploader_id, uploader, created)
id, err := s.db.insertID(`INSERT INTO files (area_id, name, description, size, sha256, uploader_id, uploader, created)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, f.AreaID, f.Name, f.Description, f.Size, f.SHA256,
f.UploaderID, f.Uploader, now())
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
if isUnique(err) {
return 0, ErrExists
}
return 0, err
}
return res.LastInsertId()
return id, nil
}
// Files lists an area's files by name.
+272
View File
@@ -0,0 +1,272 @@
package store
import (
"bytes"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
)
// open is a fresh store: SQLite here, or the engine of BBS_TEST_DATABASE.
func open(t *testing.T) *Store {
t.Helper()
BcryptCost = 4
s, err := Open(filepath.Join(t.TempDir(), "bbs.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
return s
}
// TestEngine: what the engines do differently, done alike.
func TestEngine(t *testing.T) {
s := open(t)
t.Logf("engine %s", s.Engine())
// names: any case finds one; a name in another case is taken; accents
// are not case
u, err := s.CreateUser("Alice", "alicepass1", "Here", false)
if err != nil || u.ID == 0 || u.Name != "Alice" || u.Level != 20 || u.Sysop {
t.Fatalf("create: %+v %v", u, err)
}
if got, err := s.UserByName("aLiCe"); err != nil || got.ID != u.ID {
t.Fatalf("by name in another case: %v %v", got, err)
}
if _, err := s.CreateUser("ALICE", "x", "", false); !errors.Is(err, ErrExists) {
t.Fatalf("ALICE again: %v", err)
}
r1, err1 := s.CreateUser("Rene", "renepass1", "", false)
r2, err2 := s.CreateUser("René", "renepass1", "", false)
if err1 != nil || err2 != nil || r1.ID == r2.ID {
t.Fatalf("Rene and René: %v %v", err1, err2)
}
if got, _ := s.UserByName("rené"); got == nil || got.ID != r2.ID {
// SQLite's NOCASE folds ASCII only: René is found as written
if s.Engine() != SQLite {
t.Errorf("rené: %v", got)
}
}
sysop, _ := s.CreateUser("sysop", "sysoppass1", "", true)
if !sysop.Sysop || sysop.ID <= u.ID {
t.Errorf("sysop: %+v", sysop)
}
// booleans both ways
if err := s.SetLocked(u.ID, true); err != nil {
t.Fatal(err)
}
if got, _ := s.UserByID(u.ID); !got.Locked {
t.Error("not locked")
}
s.SetLocked(u.ID, false)
if w, err := s.UsersBelow(30); err != nil || len(w) != 3 {
t.Errorf("below 30: %d %v", len(w), err)
}
// an update to the same value is no "not found"
if err := s.SetLevel(u.ID, 20); err != nil {
t.Errorf("same level: %v", err)
}
if err := s.SetLevel(99999, 20); !errors.Is(err, ErrNotFound) {
t.Errorf("no user: %v", err)
}
// areas, messages, ids, blobs, long text
a, err := s.CreateArea("General", "Talk", false)
if err != nil {
t.Fatal(err)
}
if _, err := s.CreateArea("general", "", false); !errors.Is(err, ErrExists) {
t.Errorf("area again: %v", err)
}
raw := []byte{0, 1, 2, 0xff, 0xfe, '\n', 0x80}
body := strings.Repeat("A line of a long message, with ünïcødé and 'quotes' and ? marks.\n", 2000)
id1, err := s.Post(&Message{AreaID: a.ID, FromID: u.ID, From: u.Name, To: "All", Subject: "First?",
Body: body, MessageID: "<1@test>", Raw: raw})
if err != nil {
t.Fatal(err)
}
id2, err := s.Post(&Message{AreaID: a.ID, FromID: u.ID, From: u.Name, To: "All", Subject: "Second", Body: "b"})
if err != nil || id2 <= id1 {
t.Fatalf("second: %d %v", id2, err)
}
if _, err := s.Post(&Message{AreaID: a.ID, From: "x", Subject: "dup", Body: "b", MessageID: "<1@test>"}); !errors.Is(err, ErrExists) {
t.Errorf("a Message-ID twice: %v", err)
}
m, err := s.Message(id1)
if err != nil || m.Body != body || m.Subject != "First?" || m.MessageID != "<1@test>" {
t.Fatalf("message: %v", err)
}
if got, err := s.MessageByMessageID("<1@test>"); err != nil || got.ID != id1 {
t.Errorf("by Message-ID: %v", err)
}
if r, err := s.Raw(id1); err != nil || !bytes.Equal(r, raw) {
t.Errorf("raw: %x %v", r, err)
}
if seen, _ := s.Seen("<1@test>"); !seen {
t.Error("not in the history")
}
if err := s.Remember("<1@test>"); err != nil {
t.Errorf("remember again: %v", err)
}
if got, _ := s.UserByID(u.ID); got.Posts != 2 {
t.Errorf("posts %d", got.Posts)
}
// the last read only goes forward (upsert, greatest)
for _, id := range []int64{id2, id1} {
if err := s.SetLastRead(u.ID, a.ID, id); err != nil {
t.Fatal(err)
}
}
if lr, _ := s.LastRead(u.ID, a.ID); lr != id2 {
t.Errorf("last read %d, want %d", lr, id2)
}
if n, _ := s.NewCount(u.ID, a.ID); n != 0 {
t.Errorf("new %d", n)
}
// newsgroups, peers (upserts)
if err := s.SetNewsgroup(a.ID, "bbs.general"); err != nil {
t.Fatal(err)
}
b, _ := s.CreateArea("Other", "", false)
if err := s.SetNewsgroup(b.ID, "bbs.general"); !errors.Is(err, ErrExists) {
t.Errorf("a newsgroup twice: %v", err)
}
s.SetNewsgroup(b.ID, "") // NULLs do not clash
c, _ := s.CreateArea("Third", "", false)
if err := s.SetNewsgroup(c.ID, ""); err != nil {
t.Errorf("two areas with no newsgroup: %v", err)
}
for _, last := range []int64{5, 9} {
if err := s.SetPeerLast("peer", "bbs.general", last); err != nil {
t.Fatal(err)
}
if err := s.SetPeerPushed("peer", last); err != nil {
t.Fatal(err)
}
}
if n, ok, _ := s.PeerLast("peer", "bbs.general"); !ok || n != 9 {
t.Errorf("peer last %d %v", n, ok)
}
if n, ok, _ := s.PeerPushed("peer"); !ok || n != 9 {
t.Errorf("peer pushed %d %v", n, ok)
}
// mail, "read"
if _, err := s.SendMail(&Message{FromID: sysop.ID, From: "sysop", ToID: u.ID, To: u.Name, Subject: "hi", Body: "b"}); err != nil {
t.Fatal(err)
}
if n, _ := s.UnreadMail(u.ID); n != 1 {
t.Errorf("unread %d", n)
}
inbox, _ := s.Inbox(u.ID)
if err := s.MarkMailRead(u.ID, inbox[0].ID); err != nil {
t.Fatal(err)
}
if n, _ := s.UnreadMail(u.ID); n != 0 {
t.Errorf("unread after reading %d", n)
}
// tokens and keys ("key")
if _, err := s.AddToken(&Token{UserID: u.ID, Name: "t", Hash: "h1", Scopes: "read", Session: true}); err != nil {
t.Fatal(err)
}
if tk, err := s.TokenByHash("h1"); err != nil || !tk.Session || tk.User != "Alice" {
t.Errorf("token: %+v %v", tk, err)
}
k := &SSHKey{UserID: u.ID, Type: "ssh-ed25519", Fingerprint: "SHA256:x", Key: "ssh-ed25519 AAAA c"}
if _, err := s.AddSSHKey(k); err != nil {
t.Fatal(err)
}
if got, err := s.SSHKeyByFingerprint("SHA256:x"); err != nil || got.Key != k.Key {
t.Errorf("key: %+v %v", got, err)
}
// file areas and files, the day's counts
fa, err := s.CreateFileArea("Uploads", "", false)
if err != nil {
t.Fatal(err)
}
fid, err := s.AddFile(&File{AreaID: fa.ID, Name: "a.zip", Size: 10, SHA256: "ab", UploaderID: u.ID, Uploader: u.Name})
if err != nil {
t.Fatal(err)
}
if _, err := s.AddFile(&File{AreaID: fa.ID, Name: "A.ZIP", Size: 1, SHA256: "cd", UploaderID: u.ID, Uploader: u.Name}); !errors.Is(err, ErrExists) {
t.Errorf("a file name twice: %v", err)
}
s.CountDownload(fid)
s.CountUserDownload(u.ID)
s.AddTime(u.ID, 90)
s.AddTime(u.ID, 30)
if got, _ := s.UserByID(u.ID); got.DownloadsToday() != 1 || got.TimeToday() != 120 {
t.Errorf("today: %d downloads, %d s", got.DownloadsToday(), got.TimeToday())
}
if fas, _ := s.FileAreas(); len(fas) != 1 || fas[0].Files != 1 || fas[0].Bytes != 10 {
t.Errorf("file areas: %+v", fas[0])
}
// netmail
if _, err := s.QueueNetmail(&Netmail{FromID: u.ID, From: u.Name, To: "Bob", ToAddr: "1:2/3",
Subject: "s", Body: "b", MsgID: "1:2/4 1"}); err != nil {
t.Fatal(err)
}
// deleting a user takes their mail, tokens and keys with them
if err := s.DeleteUser(u.ID); err != nil {
t.Fatal(err)
}
if ts, _ := s.Tokens(u.ID); len(ts) != 0 {
t.Errorf("tokens left: %d", len(ts))
}
if _, err := s.SSHKeyByFingerprint("SHA256:x"); !errors.Is(err, ErrNotFound) {
t.Errorf("key left: %v", err)
}
}
// TestCopy: a database copied into another (SQLite into the test engine,
// or into SQLite again): everything there, and ids going on after.
func TestCopy(t *testing.T) {
src, err := Open("sqlite:" + filepath.Join(t.TempDir(), "src.db"))
if err != nil {
t.Fatal(err)
}
defer src.Close()
u, _ := src.CreateUser("Alice", "alicepass1", "Here", true)
a, _ := src.CreateArea("General", "", false)
src.Post(&Message{AreaID: a.ID, FromID: u.ID, From: "Alice", Subject: "s", Body: "b", MessageID: "<m@x>", Raw: []byte{0, 0xff}})
src.SendMail(&Message{FromID: u.ID, From: "Alice", ToID: u.ID, To: "Alice", Subject: "s", Body: "b"})
src.AddToken(&Token{UserID: u.ID, Name: "t", Hash: "h", Scopes: "read", Session: true})
src.SetPeerLast("p", "g", 3)
dst := open(t)
var tables []string
if err := Copy(src, dst, func(table string, n int) { tables = append(tables, fmt.Sprintf("%s %d", table, n)) }); err != nil {
t.Fatal(err)
}
if !strings.Contains(strings.Join(tables, ","), "users 1,areas 1,messages 1") {
t.Errorf("copied: %v", tables)
}
got, err := dst.UserByName("alice")
if err != nil || !got.Sysop || got.Location != "Here" {
t.Fatalf("user: %+v %v", got, err)
}
if _, err := dst.CheckPassword("Alice", "alicepass1"); err != nil {
t.Errorf("password: %v", err)
}
m, _ := dst.MessageByMessageID("<m@x>")
if raw, _ := dst.Raw(m.ID); !bytes.Equal(raw, []byte{0, 0xff}) {
t.Errorf("raw %x", raw)
}
if tk, _ := dst.TokenByHash("h"); tk == nil || !tk.Session {
t.Errorf("token %+v", tk)
}
// new rows get new ids
b, err := dst.CreateUser("Bob", "bobpass123", "", false)
if err != nil || b.ID <= got.ID {
t.Errorf("a new user after the copy: %+v %v", b, err)
}
if err := Copy(src, dst, nil); err == nil {
t.Error("copied into a database with users")
}
}
+73
View File
@@ -0,0 +1,73 @@
package store
import (
"crypto/rand"
"database/sql"
"encoding/hex"
"fmt"
"net/url"
"os"
"strings"
"testing"
)
// testDatabase is, under go test with BBS_TEST_DATABASE set to a
// PostgreSQL or MySQL server's address, a database of its own there for
// each store the tests open (in place of their SQLite files): so that the
// whole suite runs on that engine. It returns the address, and what drops
// the database after.
func testDatabase() (string, func(), error) {
base := os.Getenv("BBS_TEST_DATABASE")
if base == "" || !testing.Testing() {
return "", nil, nil
}
var b [6]byte
rand.Read(b[:])
name := "bbs_test_" + hex.EncodeToString(b[:])
switch {
case strings.HasPrefix(base, "postgres"):
admin, err := sql.Open("pgx", base)
if err != nil {
return "", nil, err
}
defer admin.Close()
if _, err := admin.Exec("CREATE SCHEMA " + name); err != nil {
return "", nil, err
}
u, err := url.Parse(base)
if err != nil {
return "", nil, err
}
q := u.Query()
q.Set("search_path", name)
u.RawQuery = q.Encode()
return u.String(), func() { dropTest("pgx", base, "DROP SCHEMA "+name+" CASCADE") }, nil
case strings.HasPrefix(base, "mysql"):
cfg, err := mysqlConfig(base)
if err != nil {
return "", nil, err
}
admin, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return "", nil, err
}
defer admin.Close()
if _, err := admin.Exec("CREATE DATABASE " + name); err != nil {
return "", nil, err
}
cfg.DBName = name
return "mysql:" + cfg.FormatDSN(), func() {
c := *cfg
c.DBName = ""
dropTest("mysql", c.FormatDSN(), "DROP DATABASE "+name)
}, nil
}
return "", nil, fmt.Errorf("BBS_TEST_DATABASE: %q is not postgres:// or mysql://", base)
}
func dropTest(driver, dsn, stmt string) {
if d, err := sql.Open(driver, dsn); err == nil {
d.Exec(stmt)
d.Close()
}
}
+2 -17
View File
@@ -21,33 +21,18 @@ type Token struct {
LastUsed time.Time
}
const tokenSchema = `
CREATE TABLE IF NOT EXISTS api_tokens (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
hash TEXT NOT NULL UNIQUE,
scopes TEXT NOT NULL,
session INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL,
expires INTEGER NOT NULL DEFAULT 0,
last_used INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS api_tokens_user ON api_tokens(user_id);
`
// AddToken records a token.
func (s *Store) AddToken(t *Token) (int64, error) {
exp := int64(0)
if !t.Expires.IsZero() {
exp = t.Expires.Unix()
}
res, err := s.db.Exec(`INSERT INTO api_tokens (user_id, name, hash, scopes, session, created, expires)
id, err := s.db.insertID(`INSERT INTO api_tokens (user_id, name, hash, scopes, session, created, expires)
VALUES (?, ?, ?, ?, ?, ?, ?)`, t.UserID, t.Name, t.Hash, t.Scopes, t.Session, now(), exp)
if err != nil {
return 0, err
}
return res.LastInsertId()
return id, nil
}
const tokenCols = `t.id, t.user_id, u.name, t.name, t.hash, t.scopes, t.session, t.created, t.expires, t.last_used`