diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index 2854811..2b8c9ad 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -19,6 +19,8 @@ // bbs [-config FILE] area purge // bbs [-config FILE] fido poll|scan|toss [LINK] // bbs [-config FILE] fido node ADDRESS | nodes WORDS... +// bbs [-config FILE] fido areafix|filefix LINK COMMAND... +// bbs [-config FILE] fido subs LINK | link|unlink|filelink|fileunlink LINK TAG... // bbs [-config FILE] user qwknode|unqwknode NAME // bbs [-config FILE] qwknet call [NET] // bbs [-config FILE] room list|add|del|topic [ROOM] [TOPIC] @@ -96,6 +98,9 @@ func usage() { bbs [-config FILE] fido poll [LINK] call links (with a host) now bbs [-config FILE] fido scan|toss [LINK] pack new mail, or take in what came bbs [-config FILE] fido node ADDRESS a system in the nodelist + bbs [-config FILE] fido areafix|filefix LINK CMD... a request to a link's AreaFix (FileFix) + bbs [-config FILE] fido subs LINK the echoes and file echoes a link has + bbs [-config FILE] fido link|unlink LINK TAG... link it to echoes (filelink, fileunlink) bbs [-config FILE] fido nodes WORDS... systems found by name, place, sysop bbs [-config FILE] user qwknode|unqwknode NAME an account for another BBS, a QWK network node bbs [-config FILE] qwknet call [NET] call QWK networks' hubs now @@ -1061,10 +1066,14 @@ func fidoCmd(cfg *server.Config, args []string) { usage() } switch words[0] { - case "node", "nodes": + case "node", "nodes", "subs": if len(words) < 2 { usage() } + case "areafix", "filefix", "link", "unlink", "filelink", "fileunlink": + if len(words) < 3 { + usage() + } default: if len(words) > 2 { usage() @@ -1086,6 +1095,9 @@ func fidoCmd(cfg *server.Config, args []string) { case "node", "nodes": nodelistCmd(fd, words) return + case "areafix", "filefix", "link", "unlink", "filelink", "fileunlink", "subs": + fixCmd(fd, words) + return } var links []*fido.Link for _, l := range cfg.Fido.Links { @@ -1136,6 +1148,48 @@ func fidoCmd(cfg *server.Config, args []string) { } } +// fixCmd: requests to a link's AreaFix or FileFix; a link's echoes and +// file echoes, linked and unlinked by hand. +func fixCmd(fd *fido.Fido, words []string) { + l := fd.Link(words[1]) + if l == nil { + fatal(fmt.Errorf("no link %s", words[1])) + } + kind := fido.Echoes + if strings.HasPrefix(words[0], "file") { + kind = fido.FileEchos + } + switch words[0] { + case "areafix", "filefix": + if err := fd.FixRequest(l, kind, words[2:]); err != nil { + fatal(err) + } + fmt.Printf("queued for %s at %s: sent at the next call\n", map[string]string{fido.Echoes: "AreaFix", fido.FileEchos: "FileFix"}[kind], l.Addr) + case "subs": + for _, k := range []string{fido.Echoes, fido.FileEchos} { + tags, err := fd.Carried(l, k) + if err != nil { + fatal(err) + } + fmt.Printf("%s %ss (%d): %s\n", l.Name, k, len(tags), strings.Join(tags, " ")) + } + if !l.AreaFix { + fmt.Println("(by its echoes and fileechoes: areafix = no)") + } + default: + if !l.AreaFix { + fatal(fmt.Errorf("%s has areafix = no: its echoes and fileechoes say what it has", l.Name)) + } + out, err := fd.Subscribe(l, kind, !strings.Contains(words[0], "unlink"), words[2:]) + for _, o := range out { + fmt.Println(o) + } + if err != nil { + fatal(err) + } + } +} + // nodelistCmd: a node of the nodelist, or the nodes found by words. func nodelistCmd(fd *fido.Fido, words []string) { nl := fd.Nodelist() diff --git a/internal/fido/areafix.go b/internal/fido/areafix.go new file mode 100644 index 0000000..c78b773 --- /dev/null +++ b/internal/fido/areafix.go @@ -0,0 +1,308 @@ +package fido + +import ( + "errors" + "fmt" + "sort" + "strings" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/ftn" + "github.com/Neo-Desktop/bbs-sec/internal/news" + "github.com/Neo-Desktop/bbs-sec/internal/store" +) + +// Kinds of subscription: echomail areas (AreaFix), file echoes (FileFix). +const ( + Echoes = "echo" + FileEchos = "file" +) + +// allows reports whether a link may have a tag at all: its echoes (or +// fileechoes) wildmat. +func (l *Link) allows(kind, tag string) bool { + pat := l.Echoes + if kind == FileEchos { + pat = l.FileEchoes + } + return pat != "" && news.Wildmat(strings.ToUpper(pat), strings.ToUpper(tag)) +} + +// carries reports whether a link exchanges an echo (or a file echo): +// one it may have and, if it manages its own by AreaFix, has asked for. +func (f *Fido) carries(l *Link, kind, tag string) bool { + if !l.allows(kind, tag) { + return false + } + if !l.AreaFix { + return true + } + ok, err := f.B.Store.FidoSubscribed(l.Name, kind, strings.ToUpper(tag)) + return err == nil && ok +} + +// fixKind is the kind a robot's name manages ("": not a robot's name). +func fixKind(to string) string { + switch strings.ToLower(strings.TrimSpace(to)) { + case "areafix", "areamgr", "arealink", "areafix!": + return Echoes + case "filefix", "filemgr", "allfix", "raid", "ticfix": + return FileEchos + } + return "" +} + +// available is what a link may subscribe to of a kind: the echoes (or +// file echoes) here that it is allowed, by tag. +func (f *Fido) available(l *Link, kind string) ([]string, error) { + var tags []string + if kind == Echoes { + as, err := f.B.Store.EchoAreas() + if err != nil { + return nil, err + } + for _, a := range as { + if l.allows(kind, a.EchoTag) { + tags = append(tags, strings.ToUpper(a.EchoTag)) + } + } + } else { + fas, err := f.B.Store.FileEchoAreas() + if err != nil { + return nil, err + } + for _, a := range fas { + if l.allows(kind, a.FileEcho) { + tags = append(tags, strings.ToUpper(a.FileEcho)) + } + } + } + sort.Strings(tags) + return tags, nil +} + +// Subscribe subscribes a link to the tags (wildmats too) it may have of +// a kind, or unsubscribes it; it says what it did, a line each. +func (f *Fido) Subscribe(l *Link, kind string, on bool, patterns []string) ([]string, error) { + avail, err := f.available(l, kind) + if err != nil { + return nil, err + } + subs, err := f.B.Store.FidoSubs(l.Name, kind) + if err != nil { + return nil, err + } + have := map[string]bool{} + for _, s := range subs { + have[s] = true + } + var out []string + for _, p := range patterns { + p = strings.ToUpper(strings.TrimSpace(p)) + if p == "" { + continue + } + if p == "ALL" { + p = "*" + } + matched := 0 + // what may be had; and when unsubscribing, what is had (an area + // gone, or no longer allowed, can still be dropped) + cands := avail + if !on { + cands = append(append([]string{}, avail...), subs...) + } + done := map[string]bool{} + for _, tag := range cands { + if done[tag] || !news.Wildmat(p, tag) { + continue + } + done[tag] = true + matched++ + switch { + case on && have[tag]: + out = append(out, tag+": already linked") + case on: + if err := f.B.Store.SetFidoSub(l.Name, kind, tag, true); err != nil { + return out, err + } + have[tag] = true + out = append(out, tag+": linked") + case have[tag]: + if err := f.B.Store.SetFidoSub(l.Name, kind, tag, false); err != nil { + return out, err + } + delete(have, tag) + out = append(out, tag+": unlinked") + default: + if p == tag { + out = append(out, tag+": was not linked") + } + } + } + if matched == 0 { + out = append(out, p+": no such "+kindWord(kind)+" here") + } + } + return out, nil +} + +func kindWord(kind string) string { + if kind == FileEchos { + return "file echo" + } + return "echo" +} + +// robotName is the robot's name of a kind, as replies are signed. +func robotName(kind string) string { + if kind == FileEchos { + return "FileFix" + } + return "AreaFix" +} + +// fixRequest answers a request to AreaFix or FileFix from a link's +// sysop: its commands, a line each, done; the answer goes back by +// netmail. Requests from systems that are not links are dropped. +func (f *Fido) fixRequest(orig ftn.Addr, from, robot, subject string, lines []string, msgid string) error { + kind := fixKind(robot) + l := f.linkByAddr(orig) + if l == nil { + f.B.Log.Printf("fido: %s request from %s, not a link: dropped", robotName(kind), orig) + return nil + } + reply := func(body []string) error { + n := &store.Netmail{From: robotName(kind), To: bbs.Clean(from, bbs.MaxFTNNameLen), + ToAddr: orig.String4D(), Subject: robotName(kind) + " reply", Body: strings.Join(body, "\n"), + MsgID: ftn.NewMSGID(f.Main()), Reply: msgid} + if n.To == "" { + n.To = "Sysop" + } + if _, err := f.B.Store.QueueNetmail(n); err != nil { + return err + } + f.Kick() + return nil + } + if !l.AreaFix { + f.B.Log.Printf("fido: %s request from %s: not open to it", robotName(kind), l.Name) + return reply([]string{robotName(kind) + " is not open to " + l.Addr.String() + ": ask the sysop."}) + } + password, _, _ := strings.Cut(strings.TrimSpace(subject), " ") + if l.AreafixPassword == "" || !strings.EqualFold(password, l.AreafixPassword) { + f.B.Log.Printf("fido: %s request from %s: wrong password", robotName(kind), l.Name) + return reply([]string{"Wrong password: nothing done."}) + } + out := []string{fmt.Sprintf("%s, %s here: your request for %s.", robotName(kind), f.Main(), l.Addr), ""} + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" || line[0] == 1 { + continue + } + if strings.HasPrefix(line, "---") || strings.HasPrefix(line, "* Origin:") { + break + } + cmd := strings.ToUpper(line) + switch { + case cmd == "%HELP": + out = append(out, fixHelp(kind)...) + case cmd == "%LIST", cmd == "%QUERY", cmd == "%LINKED", cmd == "%UNLINKED": + avail, err := f.available(l, kind) + if err != nil { + return err + } + subs, err := f.B.Store.FidoSubs(l.Name, kind) + if err != nil { + return err + } + have := map[string]bool{} + for _, s := range subs { + have[s] = true + } + title := map[string]string{"%LIST": "Available (* linked):", "%QUERY": "Linked:", + "%LINKED": "Linked:", "%UNLINKED": "Not linked:"}[cmd] + out = append(out, title) + n := 0 + for _, tag := range avail { + switch { + case cmd == "%LIST" && have[tag]: + out = append(out, "* "+tag) + case cmd == "%LIST", cmd == "%UNLINKED" && !have[tag]: + out = append(out, " "+tag) + case (cmd == "%QUERY" || cmd == "%LINKED") && have[tag]: + out = append(out, " "+tag) + default: + continue + } + n++ + } + out = append(out, fmt.Sprintf("(%d)", n), "") + case strings.HasPrefix(cmd, "%"): + out = append(out, line+": not done here") + case strings.HasPrefix(cmd, "-"): + r, err := f.Subscribe(l, kind, false, []string{cmd[1:]}) + if err != nil { + return err + } + out = append(out, r...) + default: + r, err := f.Subscribe(l, kind, true, []string{strings.TrimLeft(cmd, "+=")}) + if err != nil { + return err + } + out = append(out, r...) + } + } + f.B.Log.Printf("fido: %s request from %s done", robotName(kind), l.Name) + return reply(out) +} + +func fixHelp(kind string) []string { + w := kindWord(kind) + return []string{ + "Write to " + robotName(kind) + " with your password as the subject, and a", + "command to a line:", + " +TAG or TAG link the " + w + " (a pattern too: +FSX_*)", + " -TAG unlink it; -ALL unlinks every one", + " %LIST the " + w + "s you may have, * where linked", + " %QUERY the ones linked", + " %UNLINKED the ones not linked", + " %HELP this", + "", + } +} + +// FixRequest sends a request to a link's AreaFix (or FileFix): our +// commands, with the password we share. +func (f *Fido) FixRequest(l *Link, kind string, commands []string) error { + if l.AreafixPassword == "" { + return errors.New("[link " + l.Name + "] has no areafix_password") + } + n := &store.Netmail{From: bbs.Clean(f.S.Sysop, bbs.MaxFTNNameLen), To: robotName(kind), ToAddr: l.Addr.String4D(), + Subject: l.AreafixPassword, Body: strings.Join(commands, "\n"), MsgID: ftn.NewMSGID(f.Main())} + if n.From == "" { + n.From = "Sysop" + } + if _, err := f.B.Store.QueueNetmail(n); err != nil { + return err + } + f.Kick() + return nil +} + +// Carried are the tags of a kind a link has: here, allowed, and (if it +// manages its own) linked. +func (f *Fido) Carried(l *Link, kind string) ([]string, error) { + avail, err := f.available(l, kind) + if err != nil { + return nil, err + } + var out []string + for _, t := range avail { + if f.carries(l, kind, t) { + out = append(out, t) + } + } + return out, nil +} diff --git a/internal/fido/areafix_test.go b/internal/fido/areafix_test.go new file mode 100644 index 0000000..e48c1ee --- /dev/null +++ b/internal/fido/areafix_test.go @@ -0,0 +1,82 @@ +package fido + +import ( + "strings" + "testing" +) + +// TestAreaFix: a node asks its hub's AreaFix for echoes; the hub links +// it, says so by netmail, and sends it what is posted there; the node, +// with create = yes, makes the area it lacked. +func TestAreaFix(t *testing.T) { + down := &Link{Name: "n200", Addr: mustAddr("21:1/200"), Password: "pw", Echoes: "*", + AreaFix: true, AreafixPassword: "FIXIT"} + hub := newSystem(t, "21:1/100", down) + gen, _ := hub.f.B.Store.CreateArea("Gen", "General chat", false) + hub.f.B.Store.SetEchoTag(gen.ID, "FSX_GEN") + up := &Link{Name: "hub", Addr: mustAddr("21:1/100"), Host: hub.host, Password: "pw", Echoes: "*", + AreafixPassword: "FIXIT", Create: true, Route: true} + n200 := newSystem(t, "21:1/200", up) + for _, s := range []*system{hub, n200} { + s.f.ScanAll() + } + // linked to nothing yet: nothing goes to it + if tags, _ := hub.f.Carried(down, Echoes); len(tags) != 0 { + t.Fatalf("carried before: %v", tags) + } + + if err := n200.f.FixRequest(up, Echoes, []string{"%LIST", "+FSX_GEN", "+NOPE", "TEST"}); err != nil { + t.Fatal(err) + } + n200.call(t, up, hub) + if tags, _ := hub.f.Carried(down, Echoes); strings.Join(tags, " ") != "FSX_GEN TEST" { + t.Fatalf("carried: %v", tags) + } + // the answer, by netmail, to the node's sysop + n200.call(t, up, hub) + sysop, _ := n200.f.B.Store.UserByName("sysop") + in, _ := n200.f.B.Store.Inbox(sysop.ID) + if len(in) != 1 || in[0].From != "AreaFix@21:1/100" || in[0].Subject != "AreaFix reply" { + t.Fatalf("inbox: %+v", in) + } + for _, want := range []string{"Available (* linked):", " FSX_GEN", "FSX_GEN: linked", "NOPE: no such echo here", "TEST: linked"} { + if !strings.Contains(in[0].Body, want) { + t.Errorf("no %q in the answer:\n%s", want, in[0].Body) + } + } + + // echomail in FSX_GEN at the hub reaches the node, which makes the area + if _, err := hub.node(t, "alice").Post(gen, "All", "Kia ora", []string{"From the hub"}, 0); err != nil { + t.Fatal(err) + } + n200.call(t, up, hub) + a, err := n200.f.B.Store.AreaByEchoTag("FSX_GEN") + if err != nil { + t.Fatalf("no area made: %v\n%s", err, n200.log) + } + if ms, _ := n200.f.B.Store.Messages(a.ID, 0, 10); len(ms) != 1 || ms[0].Subject != "Kia ora" { + t.Fatalf("FSX_GEN at the node: %+v", ms) + } + + // unlinked: no more + n200.f.FixRequest(up, Echoes, []string{"-ALL"}) + n200.call(t, up, hub) + if tags, _ := hub.f.Carried(down, Echoes); len(tags) != 0 { + t.Fatalf("carried after -ALL: %v", tags) + } + hub.node(t, "alice").Post(gen, "All", "Anyone?", []string{"x"}, 0) + if n, _ := hub.f.Scan(down); n != 1 { // only AreaFix's answer + t.Errorf("packed %d for the node", n) + } + + // a wrong password does nothing + up.AreafixPassword = "WRONG" + n200.f.FixRequest(up, Echoes, []string{"+*"}) + n200.call(t, up, hub) + if tags, _ := hub.f.Carried(down, Echoes); len(tags) != 0 { + t.Fatalf("carried after a wrong password: %v", tags) + } + if !strings.Contains(hub.log.String(), "AreaFix request from n200: wrong password") { + t.Error("not logged") + } +} diff --git a/internal/fido/fido.go b/internal/fido/fido.go index c45a7da..0c94e34 100644 --- a/internal/fido/fido.go +++ b/internal/fido/fido.go @@ -18,7 +18,6 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/archive" "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/ftn" - "github.com/Neo-Desktop/bbs-sec/internal/news" "github.com/Neo-Desktop/bbs-sec/internal/store" ) @@ -38,17 +37,22 @@ type Settings struct { // Link is a system we exchange mail with. type Link struct { - Name string - Addr ftn.Addr - Host string // host:port to call it ("": it calls us) - Password string // binkp session password - PlainOK bool // the password may be sent in the clear (no CRAM-MD5) - PktPassword string // packets' password ("": not checked, none sent) - Echoes string // wildmat of the echo tags exchanged - Route bool // netmail for nodes that are not links goes here - Packer archive.Kind // bundles' format (ARCmail): ZIP, ARC, ARJ, LHA ("": bare packets) - Poll time.Duration - AKA ftn.Addr // ours to use with it (zero: by its zone) + Name string + Addr ftn.Addr + Host string // host:port to call it ("": it calls us) + Password string // binkp session password + PlainOK bool // the password may be sent in the clear (no CRAM-MD5) + PktPassword string // packets' password ("": not checked, none sent) + Echoes string // wildmat of the echo tags exchanged + FileEchoes string // wildmat of the file echoes exchanged (TIC; "": none) + AreaFix bool // it manages its echoes and file echoes here, by AreaFix and FileFix + AreafixPassword string // between us for AreaFix and FileFix, its to ours and ours to its + TicPassword string // the TIC files' password ("": not checked, none sent) + Create bool // echoes (and file echoes) it sends that are not here are made + Route bool // netmail for nodes that are not links goes here + Packer archive.Kind // bundles' format (ARCmail): ZIP, ARC, ARJ, LHA ("": bare packets) + Poll time.Duration + AKA ftn.Addr // ours to use with it (zero: by its zone) } // Fido is the BBS on FidoNet. @@ -193,11 +197,6 @@ func (f *Fido) linkByAddr(a ftn.Addr) *Link { return nil } -// carries reports whether a link exchanges an echo. -func (l *Link) carries(tag string) bool { - return news.Wildmat(strings.ToUpper(l.Echoes), strings.ToUpper(tag)) -} - // origin is how messages from a link are marked in the store. func (l *Link) origin() string { return "ftn:" + l.Name } diff --git a/internal/fido/scan.go b/internal/fido/scan.go index 0b69fdd..8ae3d33 100644 --- a/internal/fido/scan.go +++ b/internal/fido/scan.go @@ -67,7 +67,7 @@ func (f *Fido) scan(l *Link) (int, error) { var ids []int64 byID := map[int64]*store.Area{} for _, a := range areas { - if l.carries(a.EchoTag) { + if f.carries(l, Echoes, a.EchoTag) { ids = append(ids, a.ID) byID[a.ID] = a } @@ -190,7 +190,7 @@ func (f *Fido) echomail(l *Link, a *store.Area, m *store.Message) (*ftn.Message, seen := append([]ftn.Net2D{}, em.SeenBy...) seen = append(seen, ftn.Net2D{Net: me.Net, Node: me.Node}) for _, o := range f.S.Links { - if o.Addr.Point == 0 && o.Addr.Zone == me.Zone && o.carries(a.EchoTag) { + if o.Addr.Point == 0 && o.Addr.Zone == me.Zone && f.carries(o, Echoes, a.EchoTag) { seen = append(seen, ftn.Net2D{Net: o.Addr.Net, Node: o.Addr.Node}) } } diff --git a/internal/fido/toss.go b/internal/fido/toss.go index ea910ba..f2da22e 100644 --- a/internal/fido/toss.go +++ b/internal/fido/toss.go @@ -206,7 +206,10 @@ func text(m *ftn.Message, dec func(string) string) string { func (f *Fido) tossEcho(l *Link, h *ftn.Header, m *ftn.Message, st *TossStats) error { area, err := f.B.Store.AreaByEchoTag(m.Area) - if errors.Is(err, store.ErrNotFound) || err == nil && !l.carries(m.Area) { + if errors.Is(err, store.ErrNotFound) && l.Create && l.allows(Echoes, m.Area) { + area, err = f.createEcho(l, m.Area) + } + if errors.Is(err, store.ErrNotFound) || err == nil && !f.carries(l, Echoes, m.Area) { f.B.Log.Printf("fido: %s sent echomail in %s, which is not exchanged with it: dropped", l.Name, m.Area) st.Bad++ return nil @@ -387,6 +390,15 @@ func (f *Fido) tossNetmail(l *Link, h *ftn.Header, m *ftn.Message, st *TossStats } dec := m.Decoder() to := strings.TrimSpace(dec(m.To)) + if fixKind(to) != "" { + // a request for AreaFix or FileFix: answered, not delivered + if err := f.fixRequest(orig, dec(m.From), to, dec(m.Subject), strings.Split(text(m, dec), "\n"), msgid); err != nil { + return err + } + f.B.Store.Remember(mid) + st.Netmail++ + return nil + } rcpt, err := f.B.Store.UserByName(to) if errors.Is(err, store.ErrNotFound) { rcpt, err = f.sysop() @@ -432,3 +444,31 @@ func (f *Fido) sysop() (*store.User, error) { } return nil, store.ErrNotFound } + +// validTag is an echo's or file echo's tag as FTN software makes them. +var validTag = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.!&+-]{0,39}$`) + +// createEcho makes a message area for an echo a link sent that is not +// here (create = yes), named after it; a link that manages its echoes by +// AreaFix is linked to it. +func (f *Fido) createEcho(l *Link, tag string) (*store.Area, error) { + tag = strings.ToUpper(tag) + if !validTag.MatchString(tag) { + return nil, store.ErrNotFound + } + a, err := f.B.Store.CreateArea(tag, "FidoNet echo "+tag, false) + if errors.Is(err, store.ErrExists) { + return nil, fmt.Errorf("an area is called %s but is not its echo: make it the echo (bbs area echo) or rename it", tag) + } + if err != nil { + return nil, err + } + if err := f.B.Store.SetEchoTag(a.ID, tag); err != nil { + return nil, err + } + if l.AreaFix { + f.B.Store.SetFidoSub(l.Name, Echoes, tag, true) + } + f.B.Log.Printf("fido: made the area %s for the echo %s, which %s sent", tag, tag, l.Name) + return f.B.Store.AreaByEchoTag(tag) +} diff --git a/internal/server/fidoconfig.go b/internal/server/fidoconfig.go index a86a33d..82f66be 100644 --- a/internal/server/fidoconfig.go +++ b/internal/server/fidoconfig.go @@ -148,6 +148,21 @@ func link(s *config.Section) (*fido.Link, error) { return nil, errors.New("packet_password: 8 characters at most") } l.Echoes = s.String("echoes", "*") + l.FileEchoes = s.String("fileechoes", "") + if l.AreaFix, err = s.Bool("areafix", false); err != nil { + return nil, err + } + l.AreafixPassword = s.String("areafix_password", "") + if l.AreaFix && l.AreafixPassword == "" { + return nil, errors.New("areafix = yes needs an areafix_password") + } + if strings.ContainsAny(l.AreafixPassword, " \t") { + return nil, errors.New("areafix_password: one word") + } + l.TicPassword = s.String("tic_password", "") + if l.Create, err = s.Bool("create", false); err != nil { + return nil, err + } if l.Route, err = s.Bool("route", false); err != nil { return nil, err } diff --git a/internal/server/fidoconfig_test.go b/internal/server/fidoconfig_test.go index ade75c6..933d3fc 100644 --- a/internal/server/fidoconfig_test.go +++ b/internal/server/fidoconfig_test.go @@ -30,6 +30,15 @@ route = yes poll = 3600 [link other] address = 2:5020/1 +packer = arj +host = nodelist +fileechoes = FSX* +areafix = yes +areafix_password = FIXME +tic_password = TIC +create = yes +[link third] +address = 2:5020/3 packer = none `) if err != nil { @@ -43,11 +52,18 @@ packer = none if hub.Host != "hub.example:24554" || hub.Packer != archive.ZIP || !hub.Route || hub.Poll != time.Hour || hub.PktPassword != "PKT" { t.Fatalf("%+v", hub) } - if f.Links[1].Packer != "" || !strings.Contains(strings.Join(c.Warnings, "\n"), "[link other] has no password") { - t.Fatalf("%+v %v", f.Links[1], c.Warnings) + o := f.Links[1] + if o.Packer != archive.ARJ || o.Host != "nodelist" || o.FileEchoes != "FSX*" || !o.AreaFix || o.AreafixPassword != "FIXME" || + o.TicPassword != "TIC" || !o.Create || hub.AreaFix || hub.Create || hub.FileEchoes != "" { + t.Fatalf("%+v", o) + } + if f.Links[2].Packer != "" || !strings.Contains(strings.Join(c.Warnings, "\n"), "[link other] has no password") { + t.Fatalf("%+v %v", f.Links[2], c.Warnings) } for body, want := range map[string]string{ - "[fido]\n": "[fido] address", + "[fido]\n": "[fido] address", + "[fido]\naddress = 1:1/1\n[link x]\naddress = 1:1/2\nareafix = yes\n": "needs an areafix_password", + "[fido]\naddress = 1:1/1\n[link x]\naddress = 1:1/2\npacker = rar\n": "packer", "[fido]\naddress = 21:1\n": "not an FTN address", "[link x]\naddress = 1:1/1\n": "need a [fido] section", "[fido]\naddress = 1:1/1\n[link x]\n": "address", diff --git a/internal/store/copy.go b/internal/store/copy.go index 4460cf9..47b5e42 100644 --- a/internal/store/copy.go +++ b/internal/store/copy.go @@ -9,7 +9,7 @@ import ( // copyOrder is the tables in an order their references allow. var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "file_areas", "files", - "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read"} + "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs"} var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`) diff --git a/internal/store/fido.go b/internal/store/fido.go index dc017cc..edc7fcc 100644 --- a/internal/store/fido.go +++ b/internal/store/fido.go @@ -149,3 +149,94 @@ func (s *Store) NetmailPacked(id int64) error { _, err := s.db.Exec(`UPDATE netmail_out SET packed = ? WHERE id = ?`, now(), id) return err } + +// FidoSubs lists what a link has subscribed to, by AreaFix ("echo") or +// FileFix ("file"), by tag. +func (s *Store) FidoSubs(link, kind string) ([]string, error) { + rows, err := s.db.Query(`SELECT tag FROM fido_subs WHERE link = ? AND kind = ? ORDER BY tag`, link, kind) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var t string + if err := rows.Scan(&t); err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} + +// FidoSubscribed reports whether a link has subscribed to a tag. +func (s *Store) FidoSubscribed(link, kind, tag string) (bool, error) { + var n int + err := s.db.QueryRow(`SELECT COUNT(*) FROM fido_subs WHERE link = ? AND kind = ? AND tag = ?`, link, kind, tag).Scan(&n) + return n > 0, err +} + +// SetFidoSub subscribes a link to a tag (or no more). +func (s *Store) SetFidoSub(link, kind, tag string, on bool) error { + if !on { + _, err := s.db.Exec(`DELETE FROM fido_subs WHERE link = ? AND kind = ? AND tag = ?`, link, kind, tag) + return err + } + _, err := s.db.Exec(`INSERT OR IGNORE INTO fido_subs (link, kind, tag) VALUES (?, ?, ?)`, link, kind, tag) + return err +} + +// SetFileEcho makes a file area a FidoNet file echo ("": not one any more). +func (s *Store) SetFileEcho(area int64, tag string) error { + _, err := s.db.Exec(`UPDATE file_areas SET fileecho = ? WHERE id = ?`, nullString(tag), area) + if err != nil && isUnique(err) { + return ErrExists + } + return err +} + +// FileAreaByEcho finds a file area by its file echo's tag. +func (s *Store) FileAreaByEcho(tag string) (*FileArea, error) { + return scanFileArea(s.db.QueryRow(fileAreaQuery+` WHERE a.fileecho = ?`, tag)) +} + +// FileEchoAreas lists the file areas that are file echoes, by tag. +func (s *Store) FileEchoAreas() ([]*FileArea, error) { + rows, err := s.db.Query(fileAreaQuery + ` WHERE a.fileecho IS NOT NULL ORDER BY a.fileecho`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*FileArea + for rows.Next() { + a, err := scanFileArea(rows) + if err != nil { + return nil, err + } + out = append(out, a) + } + return out, rows.Err() +} + +// FilesToHatch lists files after id in the given areas that were added +// here (not by a file echo), for sending out. +func (s *Store) FilesToHatch(after int64, areas []int64, limit int) ([]*File, error) { + if len(areas) == 0 { + return nil, nil + } + q := `SELECT ` + fileCols + ` FROM files WHERE id > ? AND origin = '' + AND area_id IN (?` + strings.Repeat(",?", len(areas)-1) + `) ORDER BY id LIMIT ?` + args := []any{after} + for _, a := range areas { + args = append(args, a) + } + args = append(args, limit) + return s.fileList(q, args...) +} + +// MaxFileID is the newest file's id (0: none). +func (s *Store) MaxFileID() (int64, error) { + var n sql.NullInt64 + err := s.db.QueryRow(`SELECT MAX(id) FROM files`).Scan(&n) + return n.Int64, err +} diff --git a/internal/store/schema.go b/internal/store/schema.go index 2639e20..9674e7a 100644 --- a/internal/store/schema.go +++ b/internal/store/schema.go @@ -153,7 +153,8 @@ CREATE TABLE IF NOT EXISTS file_areas ( description {str} NOT NULL DEFAULT '', sysop_upload {bool} NOT NULL DEFAULT FALSE, download_req {str} NOT NULL DEFAULT '', - upload_req {str} NOT NULL DEFAULT '' + upload_req {str} NOT NULL DEFAULT '', + fileecho {key} )`, ` CREATE TABLE IF NOT EXISTS files ( id {id}, @@ -167,6 +168,7 @@ CREATE TABLE IF NOT EXISTS files ( created {int} NOT NULL, downloads {int} NOT NULL DEFAULT 0, long_desc {text}, + origin {str} NOT NULL DEFAULT '', UNIQUE (area_id, name) )`, ` CREATE TABLE IF NOT EXISTS history ( @@ -207,6 +209,12 @@ CREATE TABLE IF NOT EXISTS api_tokens ( expires {int} NOT NULL DEFAULT 0, last_used {int} NOT NULL DEFAULT 0 )`, ` +CREATE TABLE IF NOT EXISTS fido_subs ( + link {key} NOT NULL, + kind {key} NOT NULL, + tag {key} NOT NULL, + PRIMARY KEY (link, kind, tag) +)`, ` CREATE TABLE IF NOT EXISTS ssh_keys ( id {id}, user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE, @@ -240,6 +248,7 @@ var indexes = []struct { {"ssh_keys_user", "ssh_keys", "user_id", false}, {"qwk_msgs_message", "qwk_msgs", "message_id", false}, {"messages_thread", "messages", "thread", false}, + {"file_areas_fileecho", "file_areas", "fileecho", true}, } // added are the columns added since the first schema: an older database @@ -275,6 +284,8 @@ var added = []struct{ table, column, decl string }{ {"areas", "max_days", "{int} NOT NULL DEFAULT 0"}, {"users", "qwk_node", "{bool} NOT NULL DEFAULT FALSE"}, {"messages", "thread", "{int} NOT NULL DEFAULT 0"}, + {"file_areas", "fileecho", "{key}"}, + {"files", "origin", "{str} NOT NULL DEFAULT ''"}, } // migrate makes the schema, or brings an older database up to it. diff --git a/internal/store/store.go b/internal/store/store.go index e05f757..ad847a2 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -646,6 +646,7 @@ type FileArea struct { SysopUpload bool // only sysops upload DownloadReq string // the access requirement to download ("": anyone) UploadReq string // and to upload + FileEcho string // its FidoNet file echo's tag ("": not one) Files int Bytes int64 } @@ -664,6 +665,7 @@ type File struct { Created time.Time Downloads int LongDesc string // more lines of description (a FILE_ID.DIZ's) + Origin string // where it came from ("ftn:LINK" by a file echo; "": here) } // CreateFileArea adds a file area. @@ -691,14 +693,14 @@ func (s *Store) DeleteFileArea(id int64) error { return s.exec1(`DELETE FROM file_areas WHERE id = ?`, id) } -const fileAreaQuery = `SELECT a.id, a.name, a.description, a.sysop_upload, a.download_req, a.upload_req, +const fileAreaQuery = `SELECT a.id, a.name, a.description, a.sysop_upload, a.download_req, a.upload_req, COALESCE(a.fileecho, ''), (SELECT COUNT(*) FROM files f WHERE f.area_id = a.id), (SELECT COALESCE(SUM(f.size), 0) FROM files f WHERE f.area_id = a.id) FROM file_areas a` func scanFileArea(row interface{ Scan(...any) error }) (*FileArea, error) { var a FileArea - err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopUpload, &a.DownloadReq, &a.UploadReq, &a.Files, &a.Bytes) + err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopUpload, &a.DownloadReq, &a.UploadReq, &a.FileEcho, &a.Files, &a.Bytes) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } @@ -734,13 +736,13 @@ func (s *Store) FileAreaByName(name string) (*FileArea, error) { } const fileCols = `id, area_id, name, description, size, sha256, uploader_id, uploader, created, downloads, - COALESCE(long_desc, '')` + COALESCE(long_desc, ''), origin` func scanFile(row interface{ Scan(...any) error }) (*File, error) { var f File var created int64 err := row.Scan(&f.ID, &f.AreaID, &f.Name, &f.Description, &f.Size, &f.SHA256, - &f.UploaderID, &f.Uploader, &created, &f.Downloads, &f.LongDesc) + &f.UploaderID, &f.Uploader, &created, &f.Downloads, &f.LongDesc, &f.Origin) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } @@ -750,9 +752,9 @@ 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) { - id, err := s.db.insertID(`INSERT INTO files (area_id, name, description, size, sha256, uploader_id, uploader, created, long_desc) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, f.AreaID, f.Name, f.Description, f.Size, f.SHA256, - f.UploaderID, f.Uploader, now(), f.LongDesc) + id, err := s.db.insertID(`INSERT INTO files (area_id, name, description, size, sha256, uploader_id, uploader, created, long_desc, origin) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, f.AreaID, f.Name, f.Description, f.Size, f.SHA256, + f.UploaderID, f.Uploader, now(), f.LongDesc, f.Origin) if err != nil { if isUnique(err) { return 0, ErrExists