Backups: the configuration, database and files, daily or now

bbs backup makes one archive (bbs-YYYYMMDD-HHMMSS.tar.gz) of bbs.conf,
the database and the files' directories, while callers are on: the
database as a SQLite file whatever its engine, taken whole at one moment
(SQLite's by VACUUM INTO, a server's in one read-only repeatable-read
transaction: store.Snapshot).  It is written beside its final name and
renamed when whole; past [backup] keep the oldest go.

[backup] says where (beside an SQLite database by default), when (at =
HH:MM, daily, in serve), how many, and whether the files go too; it is
live at a reload.  bbs backup list, and bbs backup restore ARCHIVE -yes
with the BBS stopped: each thing put where this system's configuration
says, what is there renamed aside (.before-restore-STAMP), a server's
database copied into a new empty one; an archive whose names climb out
is refused before anything changes.

The configuration screens' Maintenance has Back up now, the backups
made, and [backup]'s keys.

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-14 20:10:27 +00:00
1 parent d0cb9fdaae
commit 0944798461
25 files changed
+1257 -41

No files matched your search

+1
View File
@@ -122,6 +122,7 @@ The documentation is in the [wiki](https://github.com/Neo-Desktop/bbs-sec/wiki/)
| [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, MariaDB; moving between them |
| [Backups](https://github.com/Neo-Desktop/bbs-sec/wiki/Backups) | the configuration, database and files, daily or now; putting one back |
| [Configuration](https://github.com/Neo-Desktop/bbs-sec/wiki/Configuration) | bbs.conf: its sections, listeners; the configuration screens, reloading |
| [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 |
+19 -3
View File
@@ -155,11 +155,27 @@ throttle_time = 600
; scheduled events: a program (no shell), daily at a time or every N
; minutes; see the wiki's Sysop tools
;[event backup]
;command = /usr/local/bin/bbs-backup --to /var/backups/bbs
;at = 03:30
;[event poll]
;command = /usr/local/bin/poll-something
;every = 60
;timeout = 600
; Backups: this file, the database (a SQLite file, whatever the engine,
; taken whole at one moment while callers are on) and the files' directories
; (file areas, image boards, FidoNet, screens, scripts), one archive
; (bbs-YYYYMMDD-HHMMSS.tar.gz) a backup. bbs backup makes one now; bbs
; backup restore ARCHIVE puts one back. See docs/wiki/Backups.md
;[backup]
; where the archives go (by default backups beside an SQLite database; a
; server's database needs one said). Keep it on another disk if you can
;dir = /var/backups/bbs
; daily, at this time (none: only when asked)
;at = 03:30
; archives kept, the oldest taken away (0: all)
;keep = 7
; the files' directories too (no: the configuration and database alone)
;files = yes
; telnet and TN3270, for everyone (port 23 needs root or
; CAP_NET_BIND_SERVICE)
[listen telnet]
+82
View File
@@ -0,0 +1,82 @@
package main
import (
"fmt"
"os"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/backup"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/server"
)
// backupCmd makes a backup, lists them, or puts one back.
func backupCmd(cfg *server.Config, path string, args []string) {
words, flags := split(args)
switch {
case len(words) == 0:
st := open(cfg)
defer st.Close()
b := bbs.New(cfg.Settings, st, nil)
a, err := server.NewBackups(cfg, path, b).Run()
if err != nil {
fatal(err)
}
fmt.Printf("%s %s\n", a.Path, size(a.Size))
case words[0] == "list" && len(words) == 1:
as, err := backup.List(cfg.Settings.Backup.Dir)
if err != nil {
fatal(err)
}
if len(as) == 0 {
fmt.Println("no backups in", cfg.Settings.Backup.Dir)
}
for _, a := range as {
fmt.Printf("%s %s %s\n", a.Time.Format("2006-01-02 15:04"), size(a.Size), a.Path)
}
case words[0] == "restore" && len(words) == 2:
m, err := backup.Manifest(words[1])
if err != nil {
fatal(err)
}
to := backup.Targets{Config: path, Database: cfg.Database, Dirs: map[string]string{}}
for _, s := range server.Sources(cfg) {
to.Dirs[s.Name] = s.Path
}
fmt.Printf("%s: made %s (database %s)\n", words[1], m["made"], m["database"])
fmt.Printf(" configuration -> %s\n database -> %s\n", or(to.Config, "(none: no -config)"), cfg.Database)
for _, s := range server.Sources(cfg) {
if m[s.Name] != "" {
fmt.Printf(" %s -> %s\n", s.Name, s.Path)
}
}
if !flags["yes"] {
fmt.Println("with the BBS stopped, again with -yes to put it back (what is there now is renamed aside)")
os.Exit(2)
}
err = backup.Restore(words[1], to, time.Now(), func(s string) { fmt.Println(s) })
if err != nil {
fatal(err)
}
fmt.Println("restored")
default:
usage()
}
}
func or(s, def string) string {
if s == "" {
return def
}
return s
}
func size(n int64) string {
switch {
case n >= 1<<30:
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
}
return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
}
+36 -16
View File
@@ -11,6 +11,7 @@ import (
"golang.org/x/term"
"github.com/Neo-Desktop/bbs-sec/internal/backup"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/confedit"
"github.com/Neo-Desktop/bbs-sec/internal/confui"
@@ -126,24 +127,43 @@ func configScreens(path string) {
t.Cols, t.Rows = cols, rows
}
var st *store.Store
ed := &confui.Editor{UI: textui.Console(b, n, t),
Tools: bbs.ConfigTools{Path: path, Check: server.Check},
Open: func() (*bbs.BBS, error) {
// the database the file names, as it was read
cfg, err := server.Load(path)
if err != nil {
return nil, err
var ob *bbs.BBS // the BBS of the file as it was read, its database open
var ocfg *server.Config
openBBS := func() (*bbs.BBS, error) {
if ob != nil {
return ob, nil
}
cfg, err := server.Load(path)
if err != nil {
return nil, err
}
if p := strings.TrimPrefix(cfg.Database, "sqlite:"); store.IsFile(cfg.Database) {
if _, err := os.Stat(p); err != nil {
return nil, fmt.Errorf("%s: no database yet (bbs init makes it)", p)
}
if p := strings.TrimPrefix(cfg.Database, "sqlite:"); store.IsFile(cfg.Database) {
if _, err := os.Stat(p); err != nil {
return nil, fmt.Errorf("%s: no database yet (bbs init makes it)", p)
}
if st, err = store.Open(cfg.Database); err != nil {
return nil, err
}
ob, ocfg = bbs.New(cfg.Settings, st, log.New(io.Discard, "", 0)), cfg
return ob, nil
}
ed := &confui.Editor{UI: textui.Console(b, n, t), Open: openBBS,
Tools: bbs.ConfigTools{Path: path, Check: server.Check,
Backup: func() (*backup.Archive, error) {
b, err := openBBS()
if err != nil {
return nil, err
}
}
if st, err = store.Open(cfg.Database); err != nil {
return nil, err
}
return bbs.New(cfg.Settings, st, log.New(io.Discard, "", 0)), nil
}}
return server.NewBackups(ocfg, path, b).Run()
},
Backups: func() ([]backup.Archive, error) {
cfg, err := server.Load(path)
if err != nil {
return nil, err
}
return backup.List(cfg.Settings.Backup.Dir)
}}}
err = ed.Run()
if st != nil {
st.Close()
+9 -1
View File
@@ -4,6 +4,7 @@
// bbs [-config FILE] [serve] answer callers
// bbs [-config FILE] check check the configuration
// bbs -config FILE config [get|set|unset SECTION KEY [VALUE]] edit it
// bbs [-config FILE] backup [list | restore ARCHIVE -yes]
// bbs [-config FILE] init make the database, with a first area
// bbs [-config FILE] user add NAME [-sysop]
// bbs [-config FILE] user passwd|lock|unlock|sysop|unsysop|del NAME
@@ -85,6 +86,9 @@ func usage() {
bbs -config FILE config set SECTION KEY VALUE (SECTION: general, "listen telnet" ...)
bbs -config FILE config unset SECTION KEY checked as the BBS would read it; kill -HUP
(systemctl reload bbs) puts the live keys in force
bbs [-config FILE] backup a backup now: the configuration, database, files ([backup])
bbs [-config FILE] backup list the backups there are
bbs [-config FILE] backup restore ARCHIVE -yes put one back, the BBS stopped (what is there renamed aside)
bbs [-config FILE] init make the database, with a first area
bbs [-config FILE] user add NAME [-sysop]
bbs [-config FILE] user passwd|lock|unlock|sysop|unsysop|del NAME
@@ -288,6 +292,8 @@ func main() {
sshKeyCmd(cfg, args)
case "db":
dbCmd(cfg, args)
case "backup":
backupCmd(cfg, *configPath, args)
case "filearea":
fileAreaCmd(cfg, args)
case "file":
@@ -504,7 +510,9 @@ func serve(cfg *server.Config, path string) int {
if as != nil {
rl.Forum = as.ReconfigureForum
}
b.Config = &bbs.ConfigTools{Path: path, Check: server.Check, Reload: rl.Reload}
bk := server.NewBackups(cfg, path, b)
b.Config = &bbs.ConfigTools{Path: path, Check: server.Check, Reload: rl.Reload, Backup: bk.Run, Backups: bk.List}
go bk.Schedule(ctx)
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
go func() {
+60
View File
@@ -0,0 +1,60 @@
The BBS backs itself up: this configuration file, the database and the
files, one archive a backup, while callers are on.
```
bbs -config /etc/bbs/bbs.conf backup # one now
bbs -config /etc/bbs/bbs.conf backup list # those there are, the newest first
bbs -config /etc/bbs/bbs.conf backup restore ARCHIVE # what it would put back, and where
bbs -config /etc/bbs/bbs.conf backup restore ARCHIVE -yes
```
The [configuration screens](Configuration#editing-it-the-configuration-screens)'
Maintenance menu has the same: Back up now, the backups made, and
`[backup]`'s settings.
## What a backup has
Each is `bbs-YYYYMMDD-HHMMSS.tar.gz` in the backup directory:
| in it | |
|---|---|
| `MANIFEST` | when it was made, the database's engine, where each thing was |
| `bbs.conf` | the configuration file the BBS runs by |
| `database.db` | the database as a SQLite file, whatever its engine, taken whole at one moment: SQLite's by `VACUUM INTO`, a PostgreSQL or MySQL server's copied in one read-only transaction that sees nothing written after it began. Callers may go on as it is taken |
| `files/`, `chan/`, `fido/`, `screens/`, `scripts/` | the file areas', image boards', FidoNet's, display files' and scripts' directories (with `files = yes`) |
An archive is written beside its final name and renamed to it when it is
whole: one there is one made. Past `keep`, the oldest are taken away.
## [backup]
| key | default | |
|---|---|---|
| `dir` | `backups` beside an SQLite database | where the archives go: better on another disk, or copied off the machine (a server's database has no default: say one) |
| `at` | none | daily, at this time (`03:30`) |
| `keep` | `7` | archives kept (0: all) |
| `files` | `yes` | the files' directories too; `no`: the configuration and the database alone |
They take effect at a reload (`systemctl reload bbs`) or when the
Configuration screen saves them.
## Putting one back
`bbs backup restore ARCHIVE` says what the archive has and where each
thing would go: where *this* system's configuration says (so a backup
moves to another machine), not where it was. With the BBS stopped, `-yes`
puts it back:
- each file or directory there now is renamed aside first,
`NAME.before-restore-YYYYMMDD-HHMMSS`, never written over (take them
away when all is well);
- an SQLite database is put in the database's place;
- a PostgreSQL, MySQL or MariaDB database must be new and empty (made as
for `bbs db copy`): the archive's is copied into it;
- what the archive does not have (the files, with `files = no`) is left
as it is.
An archive whose names would climb out of where they go is refused before
anything is changed.
**See also:** [Databases](Databases), [Configuration](Configuration), [Sysop tools](Sysop-Tools)
+4 -3
View File
@@ -60,10 +60,10 @@ terminal with neither.
| Connections and modems | modem lines and every listener; callers at once, logins, time-outs, lock-outs; the caller ID country and GeoIP |
| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors |
| Users and groups | the accounts (level, flags, sysop, locked, a new password; new ones; deleted ones) and the access levels |
| Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups |
| Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups: one now, those made, `[backup]` ([Backups](Backups)) |
Running as another user and group, PAM and LDAP logins, and backups of
the database and files are shown as not available yet: they are to come.
Running as another user and group, and PAM and LDAP logins, are shown as
not available yet: they are to come.
| key | |
|---|---|
@@ -114,6 +114,7 @@ rest, which wait for a restart:
|---|---|
| `[general]` | `name`, `sysop`, `location`, `postal_address`, `phone`, `addresses`, `banner`, `banner_file`, `motd`, `motd_file`, `goodbye`, `new_users`, `max_nodes`, `attempts`, `fail_delay`, `login_timeout`, `idle_timeout`, `throttle_failures`, `throttle_time`, `page_command`, `qwk_id`, `geoip`, `geoip_credit`, `geoip_credit_url`, `phone_country`, `new_user_level`, `validated_level` |
| `[level N]` | all, and levels added or taken out |
| `[backup]` | all ([Backups](Backups)) |
| `[menu NAME]`, `[strings]` | all (a caller in a menu has it until they leave it) |
| `[chan]` | all but `dir` |
| `[http]` | `forum_guests`, `forum_theme`, `forum_flags` |
+4 -5
View File
@@ -65,10 +65,9 @@ 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.
`bbs backup` (and `[backup]`'s `at`, daily) takes the database whole while
callers are on, with the configuration and the files: see
[Backups](Backups). A server's own tools do as well: `pg_dump`,
`mysqldump --single-transaction`.
**See also:** [Configuration](Configuration), [Running](Running), [Development](Development)
+1
View File
@@ -6,6 +6,7 @@
| `internal/server` | listeners, session headers, rlogin, SSH, telling 3270s from the rest |
| `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 |
| `internal/confedit` | bbs.conf edited as a sysop would by hand, comments kept; the catalog of keys read from bbs.conf.sample (embedded by the root package), and which take effect at a reload |
| `internal/backup` | backups: the configuration, a database snapshot and the files in one tar.gz; listing, pruning, restoring |
| `internal/confui` | the configuration menus (sheets of internal/view), for `bbs config` and the sysop's tools: changes held until saved |
| `internal/view` | what the screens show, described once: menus, tables, messages, forms, panels, drafts |
| `internal/script` | the sysop's JavaScript (goja): screens of internal/view, the BBS as the caller, data kept, the time a script may compute |
+7 -5
View File
@@ -20,14 +20,16 @@ Validating new users stays on the main menu (`V`, when some wait).
```
; bbs.conf
[event backup]
command = /usr/local/bin/bbs-backup --to "/var/backups/bbs"
at = 03:30 ; every day, at this local time
; every day, at this local time
[event nodelist]
command = /usr/local/bin/get-nodelist --to "/var/lib/bbs/fido/nodelist"
at = 03:30
; every 60 minutes, for at most 300 seconds (default 600)
[event fidopoll]
command = /usr/local/bin/bbs fido poll
every = 60 ; minutes
timeout = 300 ; seconds it may take (default 600)
every = 60
timeout = 300
```
An event is a program and its arguments (words parted by spaces; `"..."`
+1
View File
@@ -7,6 +7,7 @@
- [Sysop tools](Sysop-Tools)
- [Configuration](Configuration)
- [Databases](Databases)
- [Backups](Backups)
- [Customization](Customization)
- [Scripting](Scripting)
- [Access levels](Access-Levels)
+308
View File
@@ -0,0 +1,308 @@
// Package backup keeps copies of the BBS: the configuration file, the
// database (as a SQLite file, whatever its engine, taken whole at one
// moment while callers are on) and the directories of files, in one
// gzipped tar archive a backup, the oldest taken away past a number kept.
// Restore puts an archive back where this system's configuration says,
// what is there renamed aside, never written over.
package backup
import (
"archive/tar"
"bufio"
"compress/gzip"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// Source is a directory of the BBS's files: its name in the archive, and
// where it is.
type Source struct {
Name string // files, chan, fido, screens, scripts
Path string
}
// Plan is what a backup takes, and where it goes.
type Plan struct {
Dir string // where the archives are kept
Keep int // archives kept (0: all)
Config string // the configuration file ("": none)
Store *store.Store // the database (nil: none)
Dirs []Source // the files' directories (none: the files are not taken)
}
// Archive is a backup made.
type Archive struct {
Path string
Time time.Time
Size int64
}
// Name is an archive's name for a time.
func Name(t time.Time) string { return "bbs-" + t.Format("20060102-150405") + ".tar.gz" }
const manifest = "MANIFEST"
// Run makes a backup now: written beside its final name and renamed to it
// when whole, so a backup there is a backup made. Then the oldest past
// Keep are taken away.
func (p *Plan) Run(now time.Time) (*Archive, error) {
if p.Dir == "" {
return nil, errors.New("no backup directory")
}
if err := os.MkdirAll(p.Dir, 0o700); err != nil {
return nil, err
}
final := filepath.Join(p.Dir, Name(now))
if _, err := os.Stat(final); err == nil {
return nil, fmt.Errorf("%s is there already", final)
}
tmp, err := os.CreateTemp(p.Dir, ".backup-*")
if err != nil {
return nil, err
}
defer os.Remove(tmp.Name())
if err := p.write(tmp, now); err != nil {
tmp.Close()
return nil, err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return nil, err
}
if err := tmp.Close(); err != nil {
return nil, err
}
if err := os.Rename(tmp.Name(), final); err != nil {
return nil, err
}
fi, err := os.Stat(final)
if err != nil {
return nil, err
}
if p.Keep > 0 {
if err := Prune(p.Dir, p.Keep); err != nil {
return nil, fmt.Errorf("made %s, but the old ones: %w", final, err)
}
}
return &Archive{Path: final, Time: now, Size: fi.Size()}, nil
}
func (p *Plan) write(w io.Writer, now time.Time) error {
gz := gzip.NewWriter(w)
tw := tar.NewWriter(gz)
var m strings.Builder
fmt.Fprintf(&m, "bbs backup\nmade = %s\n", now.Format(time.RFC3339))
if p.Config != "" {
fmt.Fprintf(&m, "config = %s\n", p.Config)
}
if p.Store != nil {
fmt.Fprintf(&m, "database = %s\n", p.Store.Engine())
}
for _, d := range p.Dirs {
if _, err := os.Stat(d.Path); err == nil {
fmt.Fprintf(&m, "%s = %s\n", d.Name, d.Path)
}
}
if err := addBytes(tw, manifest, []byte(m.String()), now); err != nil {
return err
}
if p.Config != "" {
if err := addFile(tw, "bbs.conf", p.Config); err != nil {
return fmt.Errorf("the configuration: %w", err)
}
}
if p.Store != nil {
dir, err := os.MkdirTemp(p.Dir, ".snapshot-")
if err != nil {
return err
}
defer os.RemoveAll(dir)
snap := filepath.Join(dir, "database.db")
if err := p.Store.Snapshot(snap); err != nil {
return fmt.Errorf("the database: %w", err)
}
if err := addFile(tw, "database.db", snap); err != nil {
return fmt.Errorf("the database: %w", err)
}
}
for _, d := range p.Dirs {
if err := addDir(tw, d.Name, d.Path, p.Dir); err != nil {
return fmt.Errorf("%s: %w", d.Name, err)
}
}
if err := tw.Close(); err != nil {
return err
}
return gz.Close()
}
func addBytes(tw *tar.Writer, name string, data []byte, t time.Time) error {
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(data)), ModTime: t,
Typeflag: tar.TypeReg}); err != nil {
return err
}
_, err := tw.Write(data)
return err
}
func addFile(tw *tar.Writer, name, src string) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: int64(fi.Mode().Perm()), Size: fi.Size(),
ModTime: fi.ModTime(), Typeflag: tar.TypeReg}); err != nil {
return err
}
// a file that grows while it is read: what it had at the start
_, err = io.CopyN(tw, f, fi.Size())
return err
}
// addDir adds a directory's files and directories under name (not one it
// is in itself: a backup directory kept among the files).
func addDir(tw *tar.Writer, name, dir, skip string) error {
if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
return nil // nothing there yet
}
skipAbs, _ := filepath.Abs(skip)
return filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if abs, _ := filepath.Abs(p); abs == skipAbs {
return filepath.SkipDir
}
rel, err := filepath.Rel(dir, p)
if err != nil {
return err
}
arc := path.Join(name, filepath.ToSlash(rel))
switch {
case d.IsDir():
fi, err := d.Info()
if err != nil {
return err
}
return tw.WriteHeader(&tar.Header{Name: arc + "/", Mode: int64(fi.Mode().Perm()), ModTime: fi.ModTime(),
Typeflag: tar.TypeDir})
case d.Type().IsRegular():
return addFile(tw, arc, p)
}
return nil // sockets, links: not the BBS's files
})
}
// List is the archives in dir, the newest first.
func List(dir string) ([]Archive, error) {
ents, err := os.ReadDir(dir)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []Archive
for _, e := range ents {
t, ok := timeOf(e.Name())
if !ok || !e.Type().IsRegular() {
continue
}
fi, err := e.Info()
if err != nil {
continue
}
out = append(out, Archive{Path: filepath.Join(dir, e.Name()), Time: t, Size: fi.Size()})
}
sort.Slice(out, func(i, j int) bool { return out[i].Time.After(out[j].Time) })
return out, nil
}
func timeOf(name string) (time.Time, bool) {
if !strings.HasPrefix(name, "bbs-") || !strings.HasSuffix(name, ".tar.gz") {
return time.Time{}, false
}
t, err := time.ParseInLocation("20060102-150405", strings.TrimSuffix(strings.TrimPrefix(name, "bbs-"), ".tar.gz"), time.Local)
return t, err == nil
}
// Prune takes away all but the keep newest archives in dir.
func Prune(dir string, keep int) error {
as, err := List(dir)
if err != nil {
return err
}
for i := keep; i < len(as); i++ {
if err := os.Remove(as[i].Path); err != nil {
return err
}
}
return nil
}
// Manifest is what an archive says it has: name = value lines (made,
// config, database, and each directory's name and where it was).
func Manifest(archive string) (map[string]string, error) {
out := map[string]string{}
err := walk(archive, func(h *tar.Header, r io.Reader) error {
if h.Name != manifest {
return nil
}
sc := bufio.NewScanner(r)
for sc.Scan() {
if k, v, ok := strings.Cut(sc.Text(), " = "); ok {
out[k] = v
}
}
return errStop
})
if err != nil && !errors.Is(err, errStop) {
return nil, err
}
if out["made"] == "" {
return nil, fmt.Errorf("%s: not a BBS backup", archive)
}
return out, nil
}
var errStop = errors.New("stop")
func walk(archive string, f func(h *tar.Header, r io.Reader) error) error {
file, err := os.Open(archive)
if err != nil {
return err
}
defer file.Close()
gz, err := gzip.NewReader(file)
if err != nil {
return fmt.Errorf("%s: %w", archive, err)
}
tr := tar.NewReader(gz)
for {
h, err := tr.Next()
if err == io.EOF {
return nil
}
if err != nil {
return fmt.Errorf("%s: %w", archive, err)
}
if err := f(h, tr); err != nil {
return err
}
}
}
+143
View File
@@ -0,0 +1,143 @@
package backup
import (
"archive/tar"
"compress/gzip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// system is a BBS's files: a configuration, a database, file areas.
func system(t *testing.T, dir string) (conf, db, files string, st *store.Store) {
conf = filepath.Join(dir, "bbs.conf")
db = filepath.Join(dir, "bbs.db")
files = filepath.Join(dir, "files")
os.WriteFile(conf, []byte("[general]\nname = Test\n"), 0o640)
os.MkdirAll(filepath.Join(files, "1"), 0o700)
os.WriteFile(filepath.Join(files, "1", "7"), []byte("a file"), 0o600)
var err error
if st, err = store.Open("sqlite:" + db); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
st.CreateUser("alice", "alicepass1", "", false)
return
}
func TestBackupAndRestore(t *testing.T) {
dir := t.TempDir()
conf, db, files, st := system(t, dir)
backups := filepath.Join(dir, "backups")
p := &Plan{Dir: backups, Keep: 2, Config: conf, Store: st, Dirs: []Source{{"files", files}, {"chan", filepath.Join(dir, "none")}}}
t0 := time.Date(2026, 10, 14, 3, 30, 0, 0, time.Local)
a, err := p.Run(t0)
if err != nil {
t.Fatal(err)
}
if filepath.Base(a.Path) != "bbs-20261014-033000.tar.gz" || a.Size == 0 {
t.Errorf("archive %+v", a)
}
m, err := Manifest(a.Path)
if err != nil || m["database"] != "sqlite" || m["files"] != files || m["config"] != conf {
t.Errorf("manifest %v %v", m, err)
}
// two more: the oldest goes
p.Run(t0.Add(time.Hour))
p.Run(t0.Add(2 * time.Hour))
as, _ := List(backups)
if len(as) != 2 || !as[0].Time.Equal(t0.Add(2*time.Hour)) {
t.Errorf("kept %+v", as)
}
if _, err := p.Run(t0.Add(2 * time.Hour)); err == nil {
t.Error("made over one there")
}
// the system changed since; then restored
st.CreateUser("bob", "bobpass123", "", false)
st.Close()
os.WriteFile(conf, []byte("[general]\nname = Changed\n"), 0o640)
os.WriteFile(filepath.Join(files, "1", "8"), []byte("new"), 0o600)
var said []string
now := t0.Add(5 * time.Hour)
err = Restore(as[1].Path, Targets{Config: conf, Database: db, Dirs: map[string]string{"files": files}}, now,
func(s string) { said = append(said, s) })
if err != nil {
t.Fatal(err)
}
if data, _ := os.ReadFile(conf); string(data) != "[general]\nname = Test\n" {
t.Errorf("config %q", data)
}
if data, _ := os.ReadFile(filepath.Join(files, "1", "7")); string(data) != "a file" {
t.Errorf("file %q", data)
}
if _, err := os.Stat(filepath.Join(files, "1", "8")); err == nil {
t.Error("a file made since is there")
}
stamp := ".before-restore-20261014-083000"
if data, _ := os.ReadFile(conf + stamp); string(data) != "[general]\nname = Changed\n" {
t.Errorf("the config set aside: %q", data)
}
if _, err := os.Stat(filepath.Join(files+stamp, "1", "8")); err != nil {
t.Errorf("the files set aside: %v", err)
}
st2, err := store.Open("sqlite:" + db)
if err != nil {
t.Fatal(err)
}
defer st2.Close()
if _, err := st2.UserByName("alice"); err != nil {
t.Error("alice is not there")
}
if _, err := st2.UserByName("bob"); err == nil {
t.Error("bob, made since, is there")
}
if !strings.Contains(strings.Join(said, "\n"), "database restored to "+db) {
t.Errorf("said %q", said)
}
}
// TestRestoreRefuses: an archive with a name that climbs out is refused
// before anything is changed.
func TestRestoreRefuses(t *testing.T) {
dir := t.TempDir()
evil := filepath.Join(dir, "bbs-20260101-000000.tar.gz")
f, _ := os.Create(evil)
gz := gzip.NewWriter(f)
tw := tar.NewWriter(gz)
for _, e := range []struct{ name, body string }{{"MANIFEST", "made = now\n"}, {"files/../../escaped", "x"}} {
tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o600, Size: int64(len(e.body)), Typeflag: tar.TypeReg})
tw.Write([]byte(e.body))
}
tw.Close()
gz.Close()
f.Close()
files := filepath.Join(dir, "files")
os.MkdirAll(files, 0o700)
err := Restore(evil, Targets{Dirs: map[string]string{"files": files}}, time.Now(), func(string) {})
if err == nil || !strings.Contains(err.Error(), "not a name a backup has") {
t.Fatalf("restored: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "..", "escaped")); err == nil {
t.Error("written outside")
}
if _, err := os.Stat(files); err != nil {
t.Error("the files were moved")
}
if _, err := Manifest(filepath.Join(dir, "nothing.tar.gz")); err == nil {
t.Error("a manifest of nothing")
}
}
func TestClean(t *testing.T) {
for name, ok := range map[string]bool{"files/1/7": true, "files/": true, "bbs.conf": true,
"../x": false, "/etc/passwd": false, "files/../../x": false, "files/./x": false, "": false, "a\\b": false} {
if clean(name) != ok {
t.Errorf("clean(%q) = %v", name, !ok)
}
}
}
+210
View File
@@ -0,0 +1,210 @@
package backup
import (
"archive/tar"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// Targets are where a restore puts what an archive has: this system's
// places, as its configuration says (not the archive's: it may be another
// machine's).
type Targets struct {
Config string // the configuration file ("": not restored)
Database string // the database's address ("": not restored)
Dirs map[string]string // each directory's place, by its name (one not here: not restored)
}
// Restore puts an archive back, the BBS stopped. Each file or directory
// there now is renamed aside first (NAME.before-restore-STAMP), never
// written over; a server's database must be new and empty, and the
// archive's is copied into it. say is told what is done.
func Restore(archive string, to Targets, now time.Time, say func(string)) error {
if _, err := Manifest(archive); err != nil {
return err
}
// first: every name in it one that stays where it is put
if err := walk(archive, func(h *tar.Header, r io.Reader) error {
if !clean(h.Name) {
return fmt.Errorf("%s: %q: not a name a backup has", archive, h.Name)
}
if h.Typeflag != tar.TypeReg && h.Typeflag != tar.TypeDir {
return fmt.Errorf("%s: %q: not a file or a directory", archive, h.Name)
}
return nil
}); err != nil {
return err
}
stamp := ".before-restore-" + now.Format("20060102-150405")
work, err := os.MkdirTemp("", "bbs-restore-")
if err != nil {
return err
}
defer os.RemoveAll(work)
// each thing read into a staging place beside where it goes (a rename
// then puts it there), the database into work
staged := map[string]string{} // top-level name: its staging path
stage := func(top string) (string, error) {
if s, ok := staged[top]; ok {
return s, nil
}
var s string
switch {
case top == "bbs.conf":
s = to.Config + ".restore-tmp"
case top == "database.db":
s = filepath.Join(work, "database.db")
default:
s = to.Dirs[top] + ".restore-tmp"
os.RemoveAll(s) // a restore's that stopped half way
if err := os.MkdirAll(s, 0o700); err != nil {
return "", err
}
}
staged[top] = s
return s, nil
}
defer func() {
for top, s := range staged {
if top != "database.db" {
os.RemoveAll(s)
}
}
}()
err = walk(archive, func(h *tar.Header, r io.Reader) error {
top, rest, _ := strings.Cut(strings.TrimSuffix(h.Name, "/"), "/")
switch {
case top == manifest:
return nil
case top == "bbs.conf" && to.Config == "", top == "database.db" && to.Database == "":
return nil
case top != "bbs.conf" && top != "database.db" && to.Dirs[top] == "":
return nil
}
s, err := stage(top)
if err != nil {
return err
}
dst := s
if rest != "" {
dst = filepath.Join(s, filepath.FromSlash(rest))
}
if h.Typeflag == tar.TypeDir {
return os.MkdirAll(dst, 0o700)
}
if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil {
return err
}
f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(h.Mode).Perm()|0o600)
if err != nil {
return err
}
if _, err := io.Copy(f, r); err != nil {
f.Close()
return err
}
return f.Close()
})
if err != nil {
return err
}
// the database first: a server's may refuse (not empty), and then
// nothing else is changed
if s, ok := staged["database.db"]; ok {
if err := restoreDB(s, to.Database, stamp, say); err != nil {
return fmt.Errorf("the database: %w", err)
}
}
for top, s := range staged {
if top == "database.db" {
continue
}
dst := to.Config
if top != "bbs.conf" {
dst = to.Dirs[top]
}
if err := aside(dst, stamp, say); err != nil {
return err
}
if err := os.Rename(s, dst); err != nil {
return err
}
say(fmt.Sprintf("%s restored to %s", top, dst))
}
return nil
}
// clean: a relative name of the archive's that goes nowhere above it
func clean(name string) bool {
n := strings.TrimSuffix(name, "/")
return n != "" && !strings.HasPrefix(n, "/") && !strings.Contains(n, "\\") &&
path.Clean(n) == n && n != ".." && !strings.HasPrefix(n, "../")
}
// aside renames what is at p (if anything) to p+stamp.
func aside(p, stamp string, say func(string)) error {
if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) {
return nil
}
if err := os.Rename(p, p+stamp); err != nil {
return err
}
say(fmt.Sprintf("%s was there: now %s", p, p+stamp))
return nil
}
func restoreDB(snap, addr, stamp string, say func(string)) error {
if store.IsFile(addr) {
p := strings.TrimPrefix(addr, "sqlite:")
for _, x := range []string{p, p + "-wal", p + "-shm"} {
if err := aside(x, stamp, say); err != nil {
return err
}
}
if err := copyFile(snap, p); err != nil {
return err
}
say("database restored to " + p)
return nil
}
src, err := store.Open("sqlite:" + snap)
if err != nil {
return err
}
defer src.Close()
dst, err := store.Open(addr)
if err != nil {
return err
}
defer dst.Close()
if err := store.Copy(src, dst, nil); err != nil {
return err
}
say("database restored into " + store.Describe(addr))
return nil
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
}
+10
View File
@@ -52,11 +52,21 @@ type Settings struct {
GeoCreditURL string // and where it links
PhoneCountry string // the country (ISO 3166) whose national caller IDs these are ("": none)
Backup BackupSettings // [backup]
Levels []Level // [level N], by number
NewUserLevel int // a new user's level
ValidatedLevel int // a validated user's
}
// BackupSettings are [backup]'s: where backups go, when, how many kept.
type BackupSettings struct {
Dir string // where the archives are kept
At string // HH:MM, daily ("": only when asked)
Keep int // archives kept (0: all)
Files bool // the file areas', image boards', FidoNet's files too
}
// Defaults are the settings without a configuration.
func Defaults() Settings {
return Settings{
+6
View File
@@ -1,5 +1,7 @@
package bbs
import "github.com/Neo-Desktop/bbs-sec/internal/backup"
// Conf is the settings in force: those the BBS began with, or the last
// Reconfigure's. It is not to be changed: Reconfigure makes another.
func (b *BBS) Conf() *Settings {
@@ -54,4 +56,8 @@ type ConfigTools struct {
// Reload puts the file in force again (nil: the BBS is not running):
// the changes that took effect, and those that wait for a restart
Reload func() (applied, restart []string, err error)
// Backup makes a backup now; Backups lists those there are, the
// newest first (nil: none here)
Backup func() (*backup.Archive, error)
Backups func() ([]backup.Archive, error)
}
+1 -1
View File
@@ -255,7 +255,7 @@ var liveKeys = map[string]map[string]bool{
}
// kinds all of whose keys are live (but chan's dir)
var liveKinds = set("level", "menu", "strings", "chan")
var liveKinds = set("level", "menu", "strings", "chan", "backup")
func set(ks ...string) map[string]bool {
m := map[string]bool{}
+38
View File
@@ -8,8 +8,10 @@ import (
"path/filepath"
"strings"
"testing"
"time"
bbssec "github.com/Neo-Desktop/bbs-sec"
"github.com/Neo-Desktop/bbs-sec/internal/backup"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
"github.com/Neo-Desktop/bbs-sec/internal/view"
@@ -382,3 +384,39 @@ func TestEveryMenu(t *testing.T) {
}
var currentUI *script
// TestBackUpNow: Back up now makes one at once (nothing to save), and
// Backups made lists them; [backup]'s keys wait for the save as any.
func TestBackUpNow(t *testing.T) {
p := writeConf(t)
var made []backup.Archive
tools := bbs.ConfigTools{Path: p,
Backup: func() (*backup.Archive, error) {
a := backup.Archive{Path: "/b/bbs-20261014-033000.tar.gz", Time: time.Date(2026, 10, 14, 3, 30, 0, 0, time.Local), Size: 2048}
made = append(made, a)
return &a, nil
},
Backups: func() ([]backup.Archive, error) { return made, nil }}
ui := &script{t: t, steps: []step{
open("Maintenance"),
expect("Backups made", "none yet", false, open("Back up now")),
func(t *testing.T, sh *view.Sheet) view.SheetResult {
if !strings.Contains(sh.Status, "Backed up: bbs-20261014-033000.tar.gz, 2.0 KB.") {
t.Errorf("status %q", sh.Status)
}
return expect("Backups made", "1, the last 2026-10-14 03:30", false, open("Backups made"))(t, sh)
},
expect("2026-10-14 03:30", "2.0 KB bbs-20261014-033000.tar.gz", false, back),
set("Daily at (HH:MM)", "04:15"), back,
save,
}}
if err := (&Editor{UI: ui, Tools: tools}).Run(); err != nil {
t.Fatal(err)
}
if len(made) != 1 {
t.Errorf("%d backups", len(made))
}
if data, _ := os.ReadFile(p); !strings.Contains(string(data), "[backup]\nat = 04:15\n") {
t.Errorf("written:\n%s", data)
}
}
+2
View File
@@ -74,6 +74,8 @@ var labels = map[string]string{
"security.deny_file": "Addresses refused (file)", "security.name_deny_file": "Names refused (file)",
"security.hack_log": "Hack log", "security.ban_minutes": "Ban after a lock-out (min)",
"chan.dir": "Image boards' files", "fido.dir": "FidoNet's packets",
"backup.dir": "Backup directory", "backup.at": "Daily at (HH:MM)", "backup.keep": "Backups kept",
"backup.files": "With the files",
}
func labelOf(kind, key string) string {
+53 -5
View File
@@ -37,15 +37,63 @@ func (e *Editor) maintenanceMenu() page {
return nil
}
out = append(out, purge, e.field(sec("chan"), "archive_days", "Image boards' archive (days)"))
out = append(out, heading("Backups"),
item{Entry: view.Entry{Kind: view.EntryInfo, Label: "Configuration",
Value: filepath.Base(e.Tools.Path) + ".bak, at each save"}},
notYet("Database", "A copy of the database, now or on a schedule: to come. Today: bbs db copy."),
notYet("Files", "A copy of the file areas', image boards' and FidoNet's files: to come."))
out = append(out, heading("Backups: the configuration, the database, the files"))
now := action("Back up now", e.backupNow)
now.Help = "Made at once (it changes nothing to save), as the saved [backup] says."
if e.Tools.Backup == nil {
now.Disabled, now.Note = true, "not here"
}
out = append(out, now)
if e.Tools.Backups != nil {
v := ""
if as, err := e.Tools.Backups(); err == nil && len(as) > 0 {
v = fmt.Sprintf("%d, the last %s", len(as), as[0].Time.Format("2006-01-02 15:04"))
} else if err == nil {
v = "none yet"
}
out = append(out, menu("Backups made", v, func() error { return e.show(e.backupsPage()) }))
}
b := sec("backup")
out = append(out, e.fields(b, "dir", "at", "keep", "files")...)
out = append(out, item{Entry: view.Entry{Kind: view.EntryInfo, Label: "Configuration's last",
Value: filepath.Base(e.Tools.Path) + ".bak, at each save"}})
return out
}}
}
// backupNow makes a backup at once.
func (e *Editor) backupNow() error {
a, err := e.Tools.Backup()
if err != nil {
e.say(view.Bad, "No backup: "+err.Error()+".")
return nil
}
e.log("backup by %s: %s", e.who(), a.Path)
e.say(view.Good, fmt.Sprintf("Backed up: %s, %s.", filepath.Base(a.Path), bytesText(a.Size)))
return nil
}
// backupsPage is the backups there are, the newest first.
func (e *Editor) backupsPage() page {
return page{title: "Backups made",
note: []view.Line{view.T(view.Dim, "To put one back: bbs backup restore ARCHIVE, with the BBS stopped.")},
items: func() []item {
as, err := e.Tools.Backups()
if err != nil {
return []item{{Entry: view.Entry{Kind: view.EntryInfo, Label: "Backups", Value: err.Error(), Disabled: true}}}
}
var out []item
for _, a := range as {
out = append(out, item{Entry: view.Entry{Kind: view.EntryInfo, Label: a.Time.Format("2006-01-02 15:04"),
Value: bytesText(a.Size) + " " + filepath.Base(a.Path)}})
}
if len(out) == 0 {
out = append(out, item{Entry: view.Entry{Kind: view.EntryInfo, Label: "None yet."}})
}
return out
}}
}
// retentionPage is each message area's keeping: the newest N, N days.
func (e *Editor) retentionPage() page {
return page{title: "Message areas: what they keep", items: func() []item {
+90
View File
@@ -0,0 +1,90 @@
package server
import (
"context"
"errors"
"sync"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/backup"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
)
// Backups makes the BBS's backups ([backup]): the configuration file, the
// database and the files' directories, now or daily.
type Backups struct {
B *bbs.BBS
Config string // the configuration file ("": none)
Dirs []backup.Source // the files' directories, as the BBS began with them
mu sync.Mutex // one at a time
}
// NewBackups are the backups of a BBS begun with cfg (from the file at
// path).
func NewBackups(cfg *Config, path string, b *bbs.BBS) *Backups {
return &Backups{B: b, Config: path, Dirs: Sources(cfg)}
}
// Sources are the directories of files a configuration has.
func Sources(cfg *Config) []backup.Source {
out := []backup.Source{{Name: "files", Path: cfg.FilesDir}, {Name: "chan", Path: cfg.Chan.Dir}}
if cfg.Fido != nil {
out = append(out, backup.Source{Name: "fido", Path: cfg.Fido.Dir})
}
if cfg.Screens != nil && cfg.Screens.Dir != "" {
out = append(out, backup.Source{Name: "screens", Path: cfg.Screens.Dir})
}
if cfg.ScriptsDir != "" {
out = append(out, backup.Source{Name: "scripts", Path: cfg.ScriptsDir})
}
return out
}
// Run makes a backup now, as [backup] says.
func (k *Backups) Run() (*backup.Archive, error) {
k.mu.Lock()
defer k.mu.Unlock()
s := k.B.Conf().Backup
if s.Dir == "" {
return nil, errors.New("no backup directory: [backup] dir")
}
p := &backup.Plan{Dir: s.Dir, Keep: s.Keep, Config: k.Config, Store: k.B.Store}
if s.Files {
p.Dirs = k.Dirs
}
start := time.Now()
a, err := p.Run(start)
if err != nil {
k.B.Log.Printf("backup: %v", err)
return nil, err
}
k.B.Log.Printf("backup: %s, %d bytes, in %v", a.Path, a.Size, time.Since(start).Round(time.Second))
return a, nil
}
// List is the backups there are, the newest first.
func (k *Backups) List() ([]backup.Archive, error) {
return backup.List(k.B.Conf().Backup.Dir)
}
// Schedule makes a backup each day at [backup]'s at (read again each
// minute: a reload changes it), until ctx is done.
func (k *Backups) Schedule(ctx context.Context) {
t := time.NewTicker(time.Minute)
defer t.Stop()
done := ""
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
at := k.B.Conf().Backup.At
day := now.Format("2006-01-02")
if at != "" && now.Format("15:04") == at && done != day {
done = day
k.Run()
}
}
}
}
+83
View File
@@ -0,0 +1,83 @@
package server
import (
"io"
"log"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Neo-Desktop/bbs-sec/internal/backup"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
func TestBackupConfig(t *testing.T) {
dir := t.TempDir()
load := func(body string) (*Config, error) {
p := filepath.Join(dir, "bbs.conf")
writeFile(p, "[general]\ndatabase = "+filepath.Join(dir, "bbs.db")+"\n[listen t]\ntype = telnet\naddress = :2300\n"+body)
return Load(p)
}
c, err := load("")
if err != nil {
t.Fatal(err)
}
if b := c.Settings.Backup; b.Dir != filepath.Join(dir, "backups") || b.Keep != 7 || !b.Files || b.At != "" {
t.Errorf("defaults %+v", b)
}
c, err = load("[backup]\ndir = /srv/b\nat = 03:30\nkeep = 0\nfiles = no\n")
if b := c.Settings.Backup; err != nil || b.Dir != "/srv/b" || b.At != "03:30" || b.Keep != 0 || b.Files {
t.Errorf("%+v %v", b, err)
}
if _, err := load("[backup]\nat = 3pm\n"); err == nil || !strings.Contains(err.Error(), "at") {
t.Errorf("at = 3pm: %v", err)
}
}
// TestBackups: a backup of a running BBS as [backup] says (the files
// left out when it says so), listed.
func TestBackups(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "bbs.conf")
files := filepath.Join(dir, "files")
os.MkdirAll(files, 0o700)
os.WriteFile(filepath.Join(files, "1"), []byte("x"), 0o600)
writeFile(p, "[general]\ndatabase = "+filepath.Join(dir, "bbs.db")+"\nfiles_dir = "+files+
"\n[listen t]\ntype = telnet\naddress = :2300\n[backup]\nkeep = 1\n")
cfg, err := Load(p)
if err != nil {
t.Fatal(err)
}
st, err := store.Open(cfg.Database)
if err != nil {
t.Fatal(err)
}
defer st.Close()
b := bbs.New(cfg.Settings, st, log.New(io.Discard, "", 0))
k := NewBackups(cfg, p, b)
a, err := k.Run()
if err != nil {
t.Fatal(err)
}
m, _ := backup.Manifest(a.Path)
if m["files"] != files || m["config"] != p || m["database"] != "sqlite" {
t.Errorf("manifest %v", m)
}
// files = no, put in force by a reload: the next has none
s := cfg.Settings
s.Backup.Files = false
b.Reconfigure(s)
os.Rename(a.Path, filepath.Join(filepath.Dir(a.Path), "bbs-20000101-000000.tar.gz")) // older: kept 1 takes it away
a2, err := k.Run()
if err != nil {
t.Fatal(err)
}
if m, _ := backup.Manifest(a2.Path); m["files"] != "" {
t.Errorf("files taken: %v", m)
}
if as, _ := k.List(); len(as) != 1 || as[0].Path != a2.Path {
t.Errorf("list %+v", as)
}
}
+28 -1
View File
@@ -155,6 +155,9 @@ func load(cf *config.File) (*Config, error) {
if err := c.securitySection(cf.Get("security", "")); err != nil {
return nil, fmt.Errorf("[security] %w", err)
}
if err := c.backupSection(cf.Get("backup", "")); err != nil {
return nil, fmt.Errorf("[backup] %w", err)
}
for _, sec := range cf.All("event") {
e, err := c.event(sec)
if err != nil {
@@ -191,7 +194,7 @@ func load(cf *config.File) (*Config, error) {
}
for _, s := range cf.Sections {
switch s.Kind {
case "general", "security", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "mrc", "menu", "strings", "http", "level", "chan":
case "general", "security", "backup", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "mrc", "menu", "strings", "http", "level", "chan":
default:
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
}
@@ -342,6 +345,30 @@ func (c *Config) event(sec *config.Section) (*events.Event, error) {
return e, nil
}
// backupSection reads [backup]: where backups go (beside an SQLite
// database by default), when, how many are kept.
func (c *Config) backupSection(sec *config.Section) error {
b := &c.Settings.Backup
def := "" // a server's database: none, said when one is made
if store.IsFile(c.Database) {
def = filepath.Join(c.DataDir(), "backups")
}
b.Dir = sec.String("dir", def)
if b.At = sec.String("at", ""); b.At != "" {
if err := events.ParseAt(b.At); err != nil {
return fmt.Errorf("at: %w", err)
}
}
var err error
if b.Keep, err = sec.Int("keep", 7, 0, 10000); err != nil {
return err
}
if b.Files, err = sec.Bool("files", true); err != nil {
return err
}
return nil
}
// securitySection reads [security]: the deny files, the hack log, bans.
func (c *Config) securitySection(sec *config.Section) error {
g := &guard.Guard{}
+34 -1
View File
@@ -1,8 +1,11 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"regexp"
"strings"
)
@@ -35,6 +38,11 @@ func columns(table string) ([]string, map[string]string) {
// 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 {
return copyTables(src.db.Query, dst, progress)
}
// copyTables copies every table read by query into dst.
func copyTables(query func(string, ...any) (*sql.Rows, error), 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
@@ -49,7 +57,7 @@ func Copy(src, dst *Store, progress func(table string, rows int)) error {
defer t.Rollback()
for _, table := range copyOrder {
cols, kinds := columns(table)
rows, err := src.db.Query(`SELECT ` + strings.Join(cols, ", ") + ` FROM ` + table)
rows, err := query(`SELECT ` + strings.Join(cols, ", ") + ` FROM ` + table)
if err != nil {
return fmt.Errorf("%s: %w", table, err)
}
@@ -122,3 +130,28 @@ func convert(v any, kind string) any {
}
return v
}
// Snapshot writes the whole database as it is at one moment into a new
// SQLite file at path (not there yet), while it is in use: SQLite's by
// VACUUM INTO, a server's copied in one read-only transaction that sees
// nothing written after it began.
func (s *Store) Snapshot(path string) error {
if _, err := os.Stat(path); err == nil {
return fmt.Errorf("%s is there already", path)
}
if s.db.d.name == SQLite {
_, err := s.db.DB.Exec(`VACUUM INTO ?`, path)
return err
}
dst, err := Open("sqlite:" + path)
if err != nil {
return err
}
defer dst.Close()
t, err := s.db.DB.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
if err != nil {
return err
}
defer t.Rollback()
return copyTables(func(q string, args ...any) (*sql.Rows, error) { return t.Query(s.db.d.query(q), args...) }, dst, nil)
}
+27
View File
@@ -517,3 +517,30 @@ func TestMessageBaseDepth(t *testing.T) {
t.Error("an old one kept")
}
}
// TestSnapshot: a database (whatever its engine: open's) written whole
// into a SQLite file, which opens as the same; not over a file there.
func TestSnapshot(t *testing.T) {
src := open(t)
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>"})
p := filepath.Join(t.TempDir(), "snap.db")
if err := src.Snapshot(p); err != nil {
t.Fatal(err)
}
if err := src.Snapshot(p); err == nil {
t.Error("written over a file there")
}
snap, err := Open("sqlite:" + p)
if err != nil {
t.Fatal(err)
}
defer snap.Close()
if _, err := snap.CheckPassword("Alice", "alicepass1"); err != nil {
t.Errorf("password: %v", err)
}
if m, err := snap.MessageByMessageID("<m@x>"); err != nil || m.Body != "b" {
t.Errorf("message: %+v %v", m, err)
}
}