From 217e67252246257241245f61248422f12ae6b661 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 16:22:05 +0000 Subject: [PATCH 1/2] IRC: ChanServ, with room registration, access lists and auto-op A user registers a room with ChanServ (/msg ChanServ REGISTER #room, or /cs REGISTER in the BBS's chat) and is its founder. Its access list takes Atheme's flags (v V o O t i r R f s A e b F, and the VOP, AOP, SOP and FOUNDER templates): those with O or V are opped or voiced on coming in, by any way in. A registered room's ops give and take ops and voice (MODE +o/-o/+v/-v), put people out (KICK, /kick on the BBS) and set the topic. ChanServ also has DROP, INFO, OP/DEOP/VOICE/DEVOICE, TOPIC, KICK, BAN/UNBAN (b on an entry: kept out), CLEAR #room USERS (everyone out but the one asking), SET (FOUNDER, GUARD, TOPICLOCK, PRIVATE, DESCRIPTION, URL, ENTRYMSG), LIST and WHY. Status, bans and kicks are the room's, in the shared chat code, so they hold for IRC, the text BBS, 3270s, AOL, Yahoo, AIM, MSN and CB alike; front ends that know only the older events get a notice and a leaving. Unregistered rooms are as before: no ops but sysops. Page rooms and rooms a linked network or MRC carries can't be registered. A room unused for chanserv_expire days (90) is dropped; a deleted founder's room passes to the next on its list. PREFIX is now (ov)@+. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRTXE7MNm3r3hHAmTG2 --- bbs.conf.sample | 6 + docs/wiki/Chat-and-Paging.md | 4 +- docs/wiki/Configuration-Reference.md | 2 + docs/wiki/IRC.md | 68 ++- internal/aol/session.go | 6 + internal/api/stream.go | 1 + internal/bbs/bbs.go | 30 +- internal/bbs/chanserv.go | 797 +++++++++++++++++++++++++++ internal/bbs/chat.go | 97 +++- internal/bbs/chatcmd.go | 21 +- internal/bbs/chatrooms.go | 44 +- internal/bbs/roomreg.go | 612 ++++++++++++++++++++ internal/ircd/chanserv.go | 98 ++++ internal/ircd/chanserv_test.go | 194 +++++++ internal/ircd/commands.go | 167 ++++-- internal/ircd/server.go | 34 +- internal/ircd/services.go | 7 + internal/ircd/services_test.go | 2 +- internal/marvel/chat.go | 5 +- internal/msn/events.go | 6 + internal/oscar/events.go | 6 + internal/server/ircconfig.go | 9 +- internal/store/copy.go | 2 +- internal/store/roomreg.go | 250 +++++++++ internal/store/schema.go | 22 + internal/store/store.go | 9 +- internal/ymsg/im.go | 6 + 27 files changed, 2391 insertions(+), 114 deletions(-) create mode 100644 internal/bbs/chanserv.go create mode 100644 internal/bbs/roomreg.go create mode 100644 internal/ircd/chanserv.go create mode 100644 internal/ircd/chanserv_test.go create mode 100644 internal/store/roomreg.go diff --git a/bbs.conf.sample b/bbs.conf.sample index 6b5a514..2c1d562 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -819,6 +819,12 @@ address = 127.0.0.1:2513 ;max_per_ip = 4 ; the services bot's nick: /msg BBSServ HELP (your account's settings) ;service = BBSServ +; the rooms' bot's nick: /msg ChanServ HELP (registering rooms, their +; access lists; the BBS chat's /cs too) +;chanserv = ChanServ +; days a registered room may go unused (no one on its access list coming +; in) before it is dropped; 0: never +;chanserv_expire = 90 ; AIM and ICQ: the chat for AIM and ICQ clients (OSCAR), beside IRC. Users ; sign on with their BBS names (or ICQ numbers: uin_base plus the account's diff --git a/docs/wiki/Chat-and-Paging.md b/docs/wiki/Chat-and-Paging.md index 2d05c71..5fbf79c 100644 --- a/docs/wiki/Chat-and-Paging.md +++ b/docs/wiki/Chat-and-Paging.md @@ -22,7 +22,9 @@ last caller leaves, unless the sysop has made it | `/friends` | your [friends list](#friends), and who on it is on | | `/friend WHO`, `/unfriend WHO` | put a user on your friends list, or take them off | | `/block WHO`, `/unblock WHO` | refuse a user's private messages, or take them again ([blocking](#blocking)) | -| `/topic [TEXT]` | the room's topic; the sysop sets a [permanent room](IRC#permanent-rooms)'s | +| `/topic [TEXT]` | the room's topic; a [registered room](IRC#chanserv)'s ops set it, the sysop a [permanent room](IRC#permanent-rooms)'s | +| `/cs COMMAND` | ChanServ: [register a room](IRC#chanserv), its access list (`/cs HELP`) | +| `/kick WHO [WHY]` | put one out of the room (a registered room's ops; `Carol_Ann` for Carol Ann) | | `/quit` | leave the chat | | `/help` | these | diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index e190b66..01db591 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -574,6 +574,8 @@ IRC: the chat rooms as channels (#main ...), for IRC clients. Users log in with | `max_clients` | | | IRC over TLS (and address = none for TLS only); with no tls_cert and tls_key, the [acme] certificates. Examples: `64`. | | `max_per_ip` | | | IRC over TLS (and address = none for TLS only); with no tls_cert and tls_key, the [acme] certificates. Examples: `4`. | | `service` | | | the services bot's nick: /msg BBSServ HELP (your account's settings) Examples: `BBSServ`. | +| `chanserv` | | | the rooms' bot's nick: /msg ChanServ HELP (registering rooms, their access lists; the BBS chat's /cs too) Examples: `ChanServ`. | +| `chanserv_expire` | | | days a registered room may go unused (no one on its access list coming in) before it is dropped; 0: never. Examples: `90`. | ## `[oscar]` diff --git a/docs/wiki/IRC.md b/docs/wiki/IRC.md index dba17e7..dccdd9c 100644 --- a/docs/wiki/IRC.md +++ b/docs/wiki/IRC.md @@ -20,6 +20,8 @@ tls_key = /etc/bbs/tls.key | `max_clients` | `64` | connections at once | | `max_per_ip` | `4` | from one address | | `service` | `BBSServ` | the [services bot](#bbsserv)'s nick | +| `chanserv` | `ChanServ` | the [rooms' bot](#chanserv)'s nick | +| `chanserv_expire` | `90` | days a registered room may go unused before it is dropped (`0`: never) | `bbs check` warns about a plain `address` without a `tls_address`, because passwords then travel in the clear. The deny list and bans in @@ -60,10 +62,14 @@ up to 20 at once. Joining shows the room's last 20 lines. | `LIST` | the rooms in use | | a page, mail, a notice | a `NOTICE` from the server | -Sysops show as channel operators (`@`), but there's little to operate: -rooms have no modes, kicks or bans, and only [permanent -rooms](#permanent-rooms) have topics. Colours and other formatting are -stripped from lines going into the rooms. +In a room no one has registered, sysops show as channel operators (`@`) +and no one else does. A user can [register a room](#chanserv) with +ChanServ: then its access list says who is opped or voiced on coming in, +and its ops can `MODE +o`/`-o`/`+v`/`-v`, `KICK` and set the topic. +[Permanent](#permanent-rooms) and registered rooms have topics; others +don't. Colours and other formatting are stripped from lines going into +the rooms. Channel modes besides `o` and `v` are not the BBS's yet: a +room is always `+nt`. A sysop is told of a page by a `NOTICE`. Joining `#sysop-N` answers the page from node N, just as `/answer` does in the BBS's chat. @@ -101,6 +107,60 @@ BBSServ, on the BBS as a line ("sysop set the topic: ..."). Changes made with the `bbs` command reach a running BBS at its next start; those made through BBSServ apply at once. +## ChanServ + +ChanServ looks after registered rooms: who founded each, and who has which +flags there. A room is registered by someone in it, who becomes its +founder and is opped. Like everything about rooms, it holds for every way +in: a caller on the text BBS, AOL, Yahoo or AIM is opped, voiced, kept out +or put out just as an IRC user is. Talk to it with `/msg ChanServ COMMAND` +or `/CS COMMAND`; on the text BBS, `/cs COMMAND` in chat. + +| Command | Needs | What it does | +|---|---|---| +| `REGISTER #room` | to be in it | makes the room yours | +| `DROP #room` | the founder | unregisters it | +| `INFO #room` | | its founder, when registered and last used, settings, topic | +| `FLAGS #room` | `A` | the access list | +| `FLAGS #room nick +flags-flags` | `f` | changes an entry; a template (`VOP`, `AOP`, `SOP`, `FOUNDER`) sets it, `-*` takes it off | +| `OP`, `DEOP #room [nick ...]` | `o` | ops you, or them | +| `VOICE`, `DEVOICE #room [nick ...]` | `v` | voices you, or them | +| `TOPIC #room [text]` | `t` | sets the topic | +| `KICK #room nick [reason]` | `r` | puts one out | +| `BAN`, `UNBAN #room nick` | `r` | keeps one out (`b` on their entry), or lets them in again | +| `CLEAR #room USERS [reason]` | `R` | puts everyone out but you | +| `SET #room FOUNDER nick` | the founder | gives the room away | +| `SET #room GUARD`, `TOPICLOCK`, `PRIVATE ON`\|`OFF` | `s` | ChanServ holds the room open; only `t` sets the topic; `INFO` shows little to those without `A` | +| `SET #room DESCRIPTION`, `URL`, `ENTRYMSG [text]` | `s` | the room's texts; the entry message is told to everyone coming in | +| `LIST` | | the rooms you have flags in (a sysop's `LIST ALL`: every room) | +| `WHY #room [nick]` | | what gives you (or them) their flags | + +The flags are Atheme's: + +| Flag | | Flag | | +|---|---|---|---| +| `v` | voice through ChanServ | `V` | voiced on coming in | +| `o` | ops through ChanServ | `O` | opped on coming in | +| `t` | sets the topic | `i` | invites (for the modes to come) | +| `r` | `KICK`, `BAN`, `UNBAN` | `R` | `CLEAR` | +| `f` | changes the access list | `s` | `SET` | +| `A` | sees the access list | `e` | not kept out by a ban | +| `b` | banned: kept out | `F` | founder: everything | + +Templates: `VOP` is `+AV`, `AOP` `+AOiortv`, `SOP` `+AORefiorstv`, and +`FOUNDER` `+AFORefiorstv`. Someone with `f` gives or takes only flags they +have; `F` is a founder's to give. A sysop acts as a founder in every room, +but is opped in a registered one only as anyone is. Only a sysop puts a +sysop out, and no one but a sysop puts out the founder. + +Page rooms (`sysop-N`) and rooms a [linked network](IRC-Linking) or MRC +carries can't be registered: the network's own services look after +those. A permanent room is registered by the sysop alone, who can then +give it away with `SET FOUNDER`. A room no one on its access list has +come into for `chanserv_expire` days is dropped. When a founder's account +is deleted, the room goes to the oldest entry with `F`, else with `f`, +else the oldest entry; with no one left, it is dropped. + ## BBSServ BBSServ is a services bot, like an IRC network's NickServ, for your BBS diff --git a/internal/aol/session.go b/internal/aol/session.go index 69abbdb..15fad0d 100644 --- a/internal/aol/session.go +++ b/internal/aol/session.go @@ -333,6 +333,12 @@ func (ss *session) events() { // event shows the client one thing its node is told. func (ss *session) event(e bbs.Event) { + if plain := bbs.Plain(e); plain != nil { // ops and kicks: as notices and leaving + for _, x := range plain { + ss.event(x) + } + return + } switch e.Kind { case bbs.Said, bbs.Emoted, bbs.Joined, bbs.Left, bbs.Topic: ss.roomEvent(e) diff --git a/internal/api/stream.go b/internal/api/stream.go index c089ab2..f97c200 100644 --- a/internal/api/stream.go +++ b/internal/api/stream.go @@ -28,6 +28,7 @@ var kinds = map[bbs.EventKind]pb.Event_Kind{ bbs.Said: pb.Event_SAID, bbs.Emoted: pb.Event_EMOTED, bbs.Joined: pb.Event_JOINED, bbs.Left: pb.Event_LEFT, bbs.Private: pb.Event_PRIVATE, bbs.Paged: pb.Event_PAGED, bbs.Notice: pb.Event_NOTICE, bbs.Mail: pb.Event_MAIL, bbs.Topic: pb.Event_NOTICE, + bbs.Mode: pb.Event_NOTICE, bbs.Kicked: pb.Event_NOTICE, } // pbEvent is e as the API's Event, with its line as a terminal shows it. diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index c88997f..d0740ed 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -218,19 +218,23 @@ type BBS struct { // sysopAway: the sysop is not to be paged (pages leave a message) sysopAway atomic.Bool - mu sync.Mutex - nodes map[int]*Node - failures map[string][]time.Time - hubOnce sync.Once - chat *hub - relays []Relay // chat networks' rooms (MRC, IRC links) - geoMu sync.Mutex - geo *geoip.File - presMu sync.Mutex - presence map[int]func(name string, online bool) // WatchPresence's - presNext int - friendFns map[int]func(user int64) // WatchFriends' - friendNext int + mu sync.Mutex + nodes map[int]*Node + failures map[string][]time.Time + hubOnce sync.Once + chat *hub + relays []Relay // chat networks' rooms (MRC, IRC links) + // the rooms' service's nick, and how long registered rooms may go unused + chanServ string + roomExpiry time.Duration + roomExpirySet bool + geoMu sync.Mutex + geo *geoip.File + presMu sync.Mutex + presence map[int]func(name string, online bool) // WatchPresence's + presNext int + friendFns map[int]func(user int64) // WatchFriends' + friendNext int } // New makes the BBS of the settings and store. diff --git a/internal/bbs/chanserv.go b/internal/bbs/chanserv.go new file mode 100644 index 0000000..7751fe2 --- /dev/null +++ b/internal/bbs/chanserv.go @@ -0,0 +1,797 @@ +package bbs + +import ( + "errors" + "fmt" + "sort" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/store" +) + +// ChanServ: rooms' registration and access lists, as a command language +// that IRC's ChanServ bot and the BBS chat's /cs both speak. Every +// command answers with lines for the one asking. + +// chanServCommand is one of ChanServ's commands. +type chanServCommand struct { + syntax string + short string + help string + run func(n *Node, u *store.User, args []string) ([]string, error) +} + +var chanServCommands map[string]*chanServCommand + +// chanServAliases are other names of commands. +var chanServAliases = map[string]string{"access": "flags", "unregister": "drop", "remove": "kick", "akick": "ban"} + +func init() { + chanServCommands = map[string]*chanServCommand{ + "register": {"REGISTER <#room>", "registers a room to you", + `REGISTER makes a room yours: you are its founder, with every flag on +its access list, and an operator there. Be in the room to register it. +A room no one on its access list comes into for 90 days is dropped.`, csRegister}, + "drop": {"DROP <#room>", "unregisters a room you founded", + `DROP unregisters a room: its access list, topic and settings go. +Only its founder (or a sysop) may.`, csDrop}, + "info": {"INFO <#room>", "shows a registered room", + `INFO shows a registered room: its founder, when it was registered and +last used, its settings and topic.`, csInfo}, + "flags": {"FLAGS <#room> [nick [+flags-flags|template]]", "shows or changes a room's access list", + `FLAGS alone lists a room's access list (needs A). With a nick, it shows +theirs; with changes, it changes them (needs f): +AO-v, a template +(VOP, AOP, SOP, FOUNDER), or -* to take them off the list. You may only +give or take flags you have yourself, unless you have F. + v voice through ChanServ V voiced on coming in + o ops through ChanServ O opped on coming in + t sets the topic i invites (to come) + r KICK, BAN, UNBAN R CLEAR + f changes the access list s SET + A sees the access list e not kept out by a ban + b banned: kept out F founder: everything +Templates: VOP +AV, AOP +AOiortv, SOP +AORefiorstv, FOUNDER +AFORefiorstv.`, csFlags}, + "op": {"OP <#room> [nick ...]", "gives ops (needs o)", + "OP makes you, or those named, operators in the room.", csStatus(true, true)}, + "deop": {"DEOP <#room> [nick ...]", "takes ops (needs o)", + "DEOP takes operator from you, or those named.", csStatus(true, false)}, + "voice": {"VOICE <#room> [nick ...]", "gives a voice (needs v)", + "VOICE gives you, or those named, a voice in the room.", csStatus(false, true)}, + "devoice": {"DEVOICE <#room> [nick ...]", "takes a voice (needs v)", + "DEVOICE takes the voice from you, or those named.", csStatus(false, false)}, + "topic": {"TOPIC <#room> [text]", "sets a room's topic (needs t)", + "TOPIC sets the room's topic; with no text, clears it.", csTopic}, + "kick": {"KICK <#room> [reason]", "puts one out of a room (needs r)", + "KICK puts someone out of the room, on every way in: IRC, the BBS and the rest.", csKick}, + "ban": {"BAN <#room> [reason]", "bans one from a room (needs r)", + `BAN puts b on someone's entry in the access list, keeping them out, +and puts them out if they are in. UNBAN takes it off.`, csBan}, + "unban": {"UNBAN <#room> ", "lets one banned in again (needs r)", + "UNBAN takes b off someone's entry, so they may come in again.", csUnban}, + "clear": {"CLEAR <#room> USERS [reason]", "puts everyone out of a room (needs R)", + "CLEAR USERS puts everyone out of the room but you.", csClear}, + "set": {"SET <#room> [value]", "changes a room's settings (needs s)", + `SET changes a registered room's settings: + FOUNDER gives the room to another (the founder alone) + GUARD ON|OFF ChanServ holds the room open, empty or not + TOPICLOCK ON|OFF only those with t set the topic, ops or not + PRIVATE ON|OFF INFO shows little to those without A + DESCRIPTION [text] what the room is for, in INFO + URL [text] a web page, in INFO + ENTRYMSG [text] told to everyone coming in +With no text (or -), a text is cleared.`, csSet}, + "list": {"LIST [ALL]", "lists the rooms you are on the access list of", + "LIST lists the rooms you have flags in. A sysop's LIST ALL lists every registered room.", csList}, + "why": {"WHY <#room> [nick]", "says why one has their status", + "WHY says what in the access list gives you (or someone) their flags.", csWhy}, + } +} + +// ChanServHelp is ChanServ's help: its commands, or one's. +func ChanServHelp(name, command string) []string { + if command == "" { + out := []string{ + name + " looks after registered rooms: who founded them, and who has", + "which flags there (ops and voice on coming in, ops' commands).", + "", + "The commands:", + } + var names []string + for k := range chanServCommands { + names = append(names, k) + } + sort.Strings(names) + for _, k := range names { + out = append(out, fmt.Sprintf(" %-9s %s", strings.ToUpper(k), chanServCommands[k].short)) + } + return append(out, "", "For a command's details: HELP ") + } + cmd := chanServLookup(command) + if cmd == nil { + return []string{"There is no such command: HELP lists them."} + } + return append([]string{"Syntax: " + cmd.syntax, ""}, strings.Split(cmd.help, "\n")...) +} + +func chanServLookup(name string) *chanServCommand { + name = strings.ToLower(name) + if a, ok := chanServAliases[name]; ok { + name = a + } + return chanServCommands[name] +} + +// ChanServ runs a ChanServ command line for the node's user, and gives the +// lines that answer it. +func (n *Node) ChanServ(line string) []string { + f := strings.Fields(line) + if len(f) == 0 || strings.EqualFold(f[0], "help") { + topic := "" + if len(f) > 1 { + topic = f[1] + } + return ChanServHelp(n.b.ChanServ(), topic) + } + cmd := chanServLookup(f[0]) + if cmd == nil { + return []string{"Unknown command. HELP lists them."} + } + u := n.User() + if u == nil { + return []string{"You are not logged in."} + } + n.b.expire() + out, err := cmd.run(n, u, f[1:]) + if err != nil { + if errors.Is(err, errSyntax) { + return []string{"Syntax: " + cmd.syntax} + } + s := err.Error() + return []string{strings.ToUpper(s[:1]) + s[1:] + "."} + } + return out +} + +var errSyntax = errors.New("syntax") + +// roomArg is a #room argument, lower-cased and without its #. +func roomArg(s string) string { return strings.ToLower(strings.TrimPrefix(s, "#")) } + +// regFor is a registered room the user has a flag in (any of need; "" +// needs none). +func (n *Node) regFor(arg string, u *store.User, need string) (*store.RoomReg, string, error) { + name := roomArg(arg) + reg := n.b.RoomReg(name) + if reg == nil { + return nil, "", fmt.Errorf("#%s is not registered", name) + } + flags := n.b.RoomFlags(name, u) + if need != "" && !strings.ContainsAny(flags, need) { + return nil, "", fmt.Errorf("you need the %s flag in #%s for that", need, name) + } + return reg, flags, nil +} + +func csRegister(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) != 1 { + return nil, errSyntax + } + name := roomArg(args[0]) + switch { + case !roomName.MatchString(name): + return nil, ErrNoRoom + case strings.HasPrefix(name, "sysop-"): + return nil, errors.New("page rooms can't be registered") + case n.b.relayFor(name) != nil: + return nil, errors.New("that room is a linked network's: its own services look after it") + case !u.Sysop && !n.b.LevelOf(u).Chat: + return nil, ErrNotAllowed + case !u.Sysop && !n.InRoom(name): + return nil, fmt.Errorf("come into #%s to register it", name) + } + if _, permanent := n.b.RoomTopic(name); permanent && !u.Sysop { + return nil, errors.New("that room is the sysop's, a permanent one") + } + if err := n.registerRoom(name, u); err != nil { + return nil, err + } + return []string{fmt.Sprintf("#%s is registered to you. FLAGS #%s NICK +flags gives others theirs.", name, name)}, nil +} + +func csDrop(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) != 1 { + return nil, errSyntax + } + reg, _, err := n.regFor(args[0], u, "") + if err != nil { + return nil, err + } + if reg.FounderID != u.ID && !u.Sysop { + return nil, errors.New("only the founder may drop a room") + } + if err := n.b.dropRoom(reg.Name); err != nil { + return nil, err + } + n.b.Log.Printf("chat: %s dropped #%s", u.Name, reg.Name) + return []string{fmt.Sprintf("#%s is unregistered.", reg.Name)}, nil +} + +func when(t time.Time) string { + if t.IsZero() { + return "never" + } + return t.Format("Jan 2 2006 15:04") +} + +func onOffWord(b bool) string { + if b { + return "on" + } + return "off" +} + +func csInfo(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) != 1 { + return nil, errSyntax + } + reg, flags, err := n.regFor(args[0], u, "") + if err != nil { + return nil, err + } + founder := reg.Founder + if founder == "" { + founder = "(gone)" + } else { + founder = Nick(founder) + } + out := []string{"Information on #" + reg.Name + ":", "Founder : " + founder, + "Registered : " + when(reg.Registered)} + if reg.Has("private") && !has(flags, FlagView) { + return append(out, "(The room is private.)"), nil + } + out = append(out, "Last used : "+when(reg.LastUsed)) + if reg.Descr != "" { + out = append(out, "Description : "+reg.Descr) + } + if reg.URL != "" { + out = append(out, "URL : "+reg.URL) + } + if reg.Topic != "" { + out = append(out, "Topic : "+reg.Topic, fmt.Sprintf("Topic set : by %s, %s", Nick(reg.TopicBy), when(reg.TopicAt))) + } + if reg.EntryMsg != "" { + out = append(out, "Entry msg : "+reg.EntryMsg) + } + var set []string + for _, s := range []string{"guard", "topiclock", "private"} { + if reg.Has(s) { + set = append(set, strings.ToUpper(s)) + } + } + if len(set) > 0 { + out = append(out, "Settings : "+strings.Join(set, " ")) + } + return out, nil +} + +// sortedFlags are flags, each once, in AllRoomFlags' order. +func sortedFlags(flags string) string { + var b strings.Builder + for _, f := range AllRoomFlags { + if strings.ContainsRune(flags, f) { + b.WriteRune(f) + } + } + return b.String() +} + +// applyFlags changes flags by a change (+AO-v, a template, -*); it gives +// the new flags, and those added and taken. +func applyFlags(flags, change string) (string, string, string, error) { + if t, ok := RoomTemplates[strings.ToUpper(change)]; ok { + var added, taken string + for _, f := range AllRoomFlags { + in, want := has(flags, f), has(t, f) + if want && !in { + added += string(f) + } + if in && !want && f != FlagBanned { + taken += string(f) + } + } + if has(flags, FlagBanned) { + t += "b" + } + return sortedFlags(t), added, taken, nil + } + if change == "-*" { + return "", "", flags, nil + } + if change == "" || change[0] != '+' && change[0] != '-' { + return "", "", "", errors.New("flags are +flags-flags, a template (VOP, AOP, SOP, FOUNDER) or -*") + } + add := true + var added, taken string + for _, f := range change { + switch { + case f == '+': + add = true + case f == '-': + add = false + case !strings.ContainsRune(AllRoomFlags, f): + return "", "", "", fmt.Errorf("there is no flag %c (HELP FLAGS)", f) + case add && !has(flags, f): + flags += string(f) + added += string(f) + case !add && has(flags, f): + flags = strings.ReplaceAll(flags, string(f), "") + taken += string(f) + } + } + return sortedFlags(flags), added, taken, nil +} + +func plusFlags(f string) string { + if f == "" { + return "(none)" + } + return "+" + f +} + +func csFlags(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 1 || len(args) > 3 { + return nil, errSyntax + } + reg, mine, err := n.regFor(args[0], u, "") + if err != nil { + return nil, err + } + if len(args) < 3 { + // shown: the list, or one entry (anyone may see their own) + if len(args) == 2 { + t, err := n.b.UserByNick(args[1]) + if err != nil { + return nil, err + } + if t.ID != u.ID && !has(mine, FlagView) { + return nil, fmt.Errorf("you need the A flag in #%s for that", reg.Name) + } + flags, err := n.b.Store.RoomFlags(reg.Name, t.ID) + if err != nil { + return nil, err + } + return []string{fmt.Sprintf("%s has %s in #%s.", Nick(t.Name), plusFlags(flags), reg.Name)}, nil + } + if !has(mine, FlagView) { + return nil, fmt.Errorf("you need the A flag in #%s for that", reg.Name) + } + list, err := n.b.Store.RoomAccessList(reg.Name) + if err != nil { + return nil, err + } + out := []string{"Access list of #" + reg.Name + ":"} + for i, a := range list { + who := Nick(a.Name) + if a.UserID == reg.FounderID { + who += " (founder)" + } + out = append(out, fmt.Sprintf("%3d %-24s +%-14s set by %s, %s", i+1, who, a.Flags, Nick(a.SetBy), a.SetAt.Format("Jan 2 2006"))) + } + return append(out, fmt.Sprintf("End of the list: %d entries.", len(list))), nil + } + if !has(mine, FlagAccess) { + return nil, fmt.Errorf("you need the f flag in #%s for that", reg.Name) + } + t, err := n.b.UserByNick(args[1]) + if err != nil { + return nil, err + } + was, err := n.b.Store.RoomFlags(reg.Name, t.ID) + if err != nil { + return nil, err + } + now, added, taken, err := applyFlags(was, args[2]) + if err != nil { + return nil, err + } + founder := has(mine, FlagFounder) + switch { + case t.ID == reg.FounderID && t.ID != u.ID && !u.Sysop: + return nil, errors.New("the founder's flags are the founder's to change") + case !founder && has(was, FlagFounder) && t.ID != u.ID: + return nil, errors.New("you need F to change a founder's flags") + case has(added+taken, FlagFounder) && !founder: + return nil, errors.New("only a founder gives or takes F") + } + if !founder && t.ID != u.ID { + for _, f := range added + taken { + if !has(mine, f) { + return nil, fmt.Errorf("you may only give or take flags you have (not %c)", f) + } + } + } + if t.ID == u.ID && !founder && added != "" { + return nil, errors.New("you can't give yourself flags") + } + if t.ID == reg.FounderID && !has(now, FlagFounder) { + now = sortedFlags(now + "F") + } + if err := n.b.Store.SetRoomAccess(reg.Name, t.ID, now, u.Name); err != nil { + return nil, err + } + n.b.Log.Printf("chat: %s set the flags of %s in #%s to %q", u.Name, t.Name, reg.Name, now) + if has(now, FlagBanned) && !has(now, FlagExempt) && !t.Sysop && t.ID != reg.FounderID { + n.b.kick(reg.Name, n.b.ChanServ(), 0, t, "banned by "+Nick(u.Name)) + } + if now == "" { + return []string{fmt.Sprintf("%s is off the access list of #%s.", Nick(t.Name), reg.Name)}, nil + } + return []string{fmt.Sprintf("%s has %s in #%s.", Nick(t.Name), plusFlags(now), reg.Name)}, nil +} + +// csStatus is OP, DEOP, VOICE and DEVOICE. +func csStatus(op, on bool) func(n *Node, u *store.User, args []string) ([]string, error) { + return func(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 1 { + return nil, errSyntax + } + need := string(FlagVoice) + if op { + need = string(FlagOp) + } + name := roomArg(args[0]) + who := args[1:] + if len(who) == 0 { + who = []string{u.Name} + } + self := len(args) == 1 + if !(self && !on) { // anyone may give up their own + if _, _, err := n.regFor(args[0], u, need); err != nil { + return nil, err + } + } else if n.b.RoomReg(name) == nil { + return nil, fmt.Errorf("#%s is not registered", name) + } + var out []string + for _, w := range who { + t, err := n.b.UserByNick(w) + if err != nil { + out = append(out, capital(err.Error())+".") + continue + } + if !n.b.inRoom(name, t.ID) { + out = append(out, Nick(t.Name)+" is not in #"+name+".") + continue + } + st := stVoice + if op { + st = stOp + } + n.b.give(name, n.b.ChanServ(), 0, t, st, on, false) + } + if len(out) == 0 { + out = append(out, "Done.") + } + return out, nil + } +} + +func capital(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} + +func csTopic(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 1 { + return nil, errSyntax + } + reg, _, err := n.regFor(args[0], u, string(FlagTopic)) + if err != nil { + return nil, err + } + if err := n.b.SetRoomTopic(reg.Name, strings.Join(args[1:], " "), u.Name); err != nil { + return nil, err + } + return []string{"The topic of #" + reg.Name + " is set."}, nil +} + +// victim is one an op would put out: not a sysop (but by a sysop), not the +// founder (but by a sysop or themselves). +func (n *Node) victim(reg *store.RoomReg, u *store.User, nick string) (*store.User, error) { + t, err := n.b.UserByNick(nick) + if err != nil { + return nil, err + } + if t.Sysop && !u.Sysop { + return nil, errors.New("the sysop can't be put out") + } + if t.ID == reg.FounderID && !u.Sysop && t.ID != u.ID { + return nil, errors.New("the founder can't be put out") + } + return t, nil +} + +func csKick(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 2 { + return nil, errSyntax + } + reg, _, err := n.regFor(args[0], u, string(FlagRemove)) + if err != nil { + return nil, err + } + t, err := n.victim(reg, u, args[1]) + if err != nil { + return nil, err + } + reason := strings.Join(args[2:], " ") + if reason == "" { + reason = "requested by " + Nick(u.Name) + } else { + reason += " (" + Nick(u.Name) + ")" + } + if n.b.kick(reg.Name, n.b.ChanServ(), 0, t, reason) == 0 { + return nil, fmt.Errorf("%s is not in #%s", Nick(t.Name), reg.Name) + } + return []string{Nick(t.Name) + " is put out of #" + reg.Name + "."}, nil +} + +func csBan(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 2 { + return nil, errSyntax + } + reg, mine, err := n.regFor(args[0], u, string(FlagRemove)) + if err != nil { + return nil, err + } + t, err := n.victim(reg, u, args[1]) + if err != nil { + return nil, err + } + if t.ID == reg.FounderID { + return nil, errors.New("the founder can't be banned") + } + flags, err := n.b.Store.RoomFlags(reg.Name, t.ID) + if err != nil { + return nil, err + } + if has(flags, FlagFounder) && !has(mine, FlagFounder) { + return nil, errors.New("you need F to ban a founder") + } + if err := n.b.Store.SetRoomAccess(reg.Name, t.ID, sortedFlags(flags+"b"), u.Name); err != nil { + return nil, err + } + reason := strings.Join(args[2:], " ") + if reason == "" { + reason = "banned by " + Nick(u.Name) + } else { + reason += " (" + Nick(u.Name) + ")" + } + n.b.kick(reg.Name, n.b.ChanServ(), 0, t, reason) + n.b.Log.Printf("chat: %s banned %s from #%s", u.Name, t.Name, reg.Name) + return []string{Nick(t.Name) + " is banned from #" + reg.Name + "."}, nil +} + +func csUnban(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) != 2 { + return nil, errSyntax + } + reg, _, err := n.regFor(args[0], u, string(FlagRemove)) + if err != nil { + return nil, err + } + t, err := n.b.UserByNick(args[1]) + if err != nil { + return nil, err + } + flags, err := n.b.Store.RoomFlags(reg.Name, t.ID) + if err != nil { + return nil, err + } + if !has(flags, FlagBanned) { + return nil, fmt.Errorf("%s is not banned from #%s", Nick(t.Name), reg.Name) + } + if err := n.b.Store.SetRoomAccess(reg.Name, t.ID, strings.ReplaceAll(flags, "b", ""), u.Name); err != nil { + return nil, err + } + return []string{Nick(t.Name) + " may come into #" + reg.Name + " again."}, nil +} + +func csClear(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 2 || !strings.EqualFold(args[1], "users") { + return nil, errSyntax + } + reg, _, err := n.regFor(args[0], u, string(FlagRecover)) + if err != nil { + return nil, err + } + reason := strings.Join(args[2:], " ") + if reason == "" { + reason = "CLEAR USERS by " + Nick(u.Name) + } else { + reason += " (" + Nick(u.Name) + ")" + } + seen := map[int64]bool{u.ID: true} + count := 0 + for _, m := range n.b.roomNodes(reg.Name) { + t := m.User() + if t == nil || seen[t.ID] { + continue + } + seen[t.ID] = true + if n.b.kick(reg.Name, n.b.ChanServ(), 0, t, reason) > 0 { + count++ + } + } + n.b.Log.Printf("chat: %s cleared #%s (%d put out)", u.Name, reg.Name, count) + return []string{fmt.Sprintf("#%s is cleared: %d put out.", reg.Name, count)}, nil +} + +func csSet(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 2 { + return nil, errSyntax + } + reg, _, err := n.regFor(args[0], u, string(FlagSet)) + if err != nil { + return nil, err + } + name := reg.Name + value := strings.Join(args[2:], " ") + b := n.b + switch setting := strings.ToLower(args[1]); setting { + case "founder": + if reg.FounderID != u.ID && !u.Sysop { + return nil, errors.New("only the founder gives the room away") + } + t, err := b.UserByNick(value) + if err != nil { + return nil, err + } + if err := b.Store.SetRoomFounder(name, t.ID); err != nil { + return nil, err + } + flags, _ := b.Store.RoomFlags(name, t.ID) + if err := b.Store.SetRoomAccess(name, t.ID, sortedFlags(strings.ReplaceAll(flags, "b", "")+founderFlags), u.Name); err != nil { + return nil, err + } + b.updateReg(name, func(r *store.RoomReg) { r.FounderID, r.Founder = t.ID, t.Name }) + b.Log.Printf("chat: %s gave #%s to %s", u.Name, name, t.Name) + return []string{fmt.Sprintf("#%s is %s's now.", name, Nick(t.Name))}, nil + case "guard", "topiclock", "private": + var on bool + switch strings.ToLower(value) { + case "on": + on = true + case "off": + default: + return nil, fmt.Errorf("SET #%s %s ON or OFF", name, strings.ToUpper(setting)) + } + words := map[string]bool{} + for _, w := range strings.Fields(reg.Settings) { + words[w] = true + } + words[setting] = on + var list []string + for w, ok := range words { + if ok { + list = append(list, w) + } + } + sort.Strings(list) + settings := strings.Join(list, " ") + if err := b.Store.SetRoomSettings(name, settings); err != nil { + return nil, err + } + h := b.hub() + h.mu.Lock() + if r := h.regs[name]; r != nil { + r.Settings = settings + } + if setting == "guard" { + r := h.rooms[name] + if on && r == nil { + h.rooms[name] = &room{members: map[*Node]bool{}} + } + if !on && r != nil && len(r.members) == 0 && !h.kept(name, r) { + delete(h.rooms, name) + } + } + h.mu.Unlock() + return []string{fmt.Sprintf("%s is %s for #%s.", strings.ToUpper(setting), onOffWord(on), name)}, nil + case "description", "desc", "url", "entrymsg": + field := map[string]string{"description": "descr", "desc": "descr", "url": "url", "entrymsg": "entrymsg"}[setting] + if value == "-" { + value = "" + } + value = Clean(value, MaxTopic) + if err := b.Store.SetRoomText(name, field, value); err != nil { + return nil, err + } + b.updateReg(name, func(r *store.RoomReg) { + switch field { + case "descr": + r.Descr = value + case "url": + r.URL = value + case "entrymsg": + r.EntryMsg = value + } + }) + if value == "" { + return []string{fmt.Sprintf("The %s of #%s is cleared.", strings.ToUpper(setting), name)}, nil + } + return []string{fmt.Sprintf("The %s of #%s is set.", strings.ToUpper(setting), name)}, nil + } + return nil, errors.New("SET's settings are FOUNDER, GUARD, TOPICLOCK, PRIVATE, DESCRIPTION, URL and ENTRYMSG") +} + +func csList(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) == 1 && strings.EqualFold(args[0], "all") { + if !u.Sysop { + return nil, errors.New("LIST ALL is the sysop's") + } + regs, err := n.b.Store.RoomRegs() + if err != nil { + return nil, err + } + out := []string{"The registered rooms:"} + for _, r := range regs { + out = append(out, fmt.Sprintf(" #%-20s %-20s last used %s", r.Name, Nick(r.Founder), when(r.LastUsed))) + } + return append(out, fmt.Sprintf("%d rooms.", len(regs))), nil + } + if len(args) > 0 { + return nil, errSyntax + } + list, err := n.b.Store.RoomsOf(u.ID) + if err != nil { + return nil, err + } + if len(list) == 0 { + return []string{"You are on no room's access list."}, nil + } + out := []string{"Your rooms:"} + for _, a := range list { + out = append(out, fmt.Sprintf(" #%-20s +%s", a.Room, a.Flags)) + } + return out, nil +} + +func csWhy(n *Node, u *store.User, args []string) ([]string, error) { + if len(args) < 1 || len(args) > 2 { + return nil, errSyntax + } + reg, mine, err := n.regFor(args[0], u, "") + if err != nil { + return nil, err + } + t := u + if len(args) == 2 { + if t, err = n.b.UserByNick(args[1]); err != nil { + return nil, err + } + if t.ID != u.ID && !has(mine, FlagView) { + return nil, fmt.Errorf("you need the A flag in #%s for that", reg.Name) + } + } + flags, err := n.b.Store.RoomFlags(reg.Name, t.ID) + if err != nil { + return nil, err + } + var why []string + if t.ID == reg.FounderID { + why = append(why, "the founder") + } + if flags != "" { + why = append(why, "on the access list with +"+flags) + } + if t.Sysop { + why = append(why, "a sysop (every flag)") + } + if len(why) == 0 { + return []string{fmt.Sprintf("%s has no flags in #%s.", Nick(t.Name), reg.Name)}, nil + } + return []string{fmt.Sprintf("%s in #%s: %s.", Nick(t.Name), reg.Name, strings.Join(why, "; "))}, nil +} diff --git a/internal/bbs/chat.go b/internal/bbs/chat.go index 87f13ac..80e2568 100644 --- a/internal/bbs/chat.go +++ b/internal/bbs/chat.go @@ -27,6 +27,8 @@ const ( Notice // from the system Mail // a new mail for the caller Topic // a room's topic (set, or shown on coming in) + Mode // ops or voice given or taken (Text "+o", Target whose) + Kicked // Target put out of the room by From (Text: why) ) // Event is something for a node to show its caller. @@ -44,6 +46,23 @@ type Event struct { // the sender as an IRC network names them (nick!user@host), for one // from a linked IRC network ("": none) Mask string + // whom a Mode or Kicked is about, and (Kicked) a node of theirs + Target string + TargetNode int +} + +// Plain is a Mode or Kicked as the events a front end that knows only +// the older ones shows: a notice in the room, and for a kick the one put +// out leaving it. Other events: nil. +func Plain(e Event) []Event { + switch e.Kind { + case Mode: + return []Event{{Kind: Notice, Room: e.Room, Text: e.String(), Time: e.Time}} + case Kicked: + return []Event{{Kind: Notice, Room: e.Room, Text: e.String(), Time: e.Time}, + {Kind: Left, Room: e.Room, From: e.Target, Node: e.TargetNode, Text: e.Text, Time: e.Time}} + } + return nil } // String is the event as a line for the caller. @@ -64,6 +83,21 @@ func (e Event) String() string { return fmt.Sprintf("Message from %s (node %d): %s", e.From, e.Node, e.Text) case Mail: return "New mail from " + e.From + ": " + e.Text + case Mode: + what := map[string]string{ + "+o": "made %s an operator", "-o": "took operator from %s", + "+v": "gave %s a voice", "-v": "took the voice from %s", + }[e.Text] + if what == "" { + return fmt.Sprintf("%s set %s %s", e.From, e.Text, e.Target) + } + return e.From + " " + fmt.Sprintf(what, e.Target) + " in " + e.Room + case Kicked: + s := e.From + " put " + e.Target + " out of " + e.Room + if e.Text != "" { + s += ": " + e.Text + } + return s case Topic: if e.From != "" { return e.From + " set the topic: " + e.Text @@ -109,12 +143,16 @@ type room struct { history []Event permanent bool // kept open when empty (store's chat_rooms) topic string // a permanent room's + // in a registered room, the users given ops or voice (stOp, stVoice) + status map[int64]uint8 } // hub is the BBS's chat: its rooms. type hub struct { mu sync.Mutex rooms map[string]*room + regs map[string]*store.RoomReg // the registered rooms (ChanServ's) + swept time.Time // when unused registrations were last dropped } // ErrChat are refusals of chat. @@ -132,7 +170,7 @@ var roomName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,19}$`) // store. func (b *BBS) hub() *hub { b.hubOnce.Do(func() { - b.chat = &hub{rooms: map[string]*room{}} + b.chat = &hub{rooms: map[string]*room{}, regs: map[string]*store.RoomReg{}} rs, err := b.Store.ChatRooms() if err != nil { b.Log.Printf("chat: the permanent rooms: %v", err) @@ -140,6 +178,16 @@ func (b *BBS) hub() *hub { for _, r := range rs { b.chat.rooms[r.Name] = &room{members: map[*Node]bool{}, permanent: true, topic: r.Topic} } + regs, err := b.Store.RoomRegs() + if err != nil { + b.Log.Printf("chat: the registered rooms: %v", err) + } + for _, r := range regs { + b.chat.regs[r.Name] = r + if r.Has("guard") && b.chat.rooms[r.Name] == nil { + b.chat.rooms[r.Name] = &room{members: map[*Node]bool{}} + } + } }) return b.chat } @@ -234,6 +282,9 @@ func (n *Node) mayJoin(name string) (string, error) { if r := n.b.relayFor(name); r != nil && !r.Allows(name, u) { return "", ErrNotAllowed } + if n.b.banned(name, u) { + return "", ErrBanned + } return name, nil } @@ -308,16 +359,30 @@ func (b *BBS) RoomMembers(name string) []RoomMember { h := b.hub() h.mu.Lock() var ns []*Node - if r := h.rooms[name]; r != nil { + status := map[int64]uint8{} + r := h.rooms[name] + if r != nil { ns = r.membersList() + for id, st := range r.status { + status[id] = st + } } + registered := h.regs[name] != nil h.mu.Unlock() out := make([]RoomMember, 0, len(ns)) for _, m := range ns { b.mu.Lock() - via := m.Caller.Via + via, u := m.Caller.Via, m.user b.mu.Unlock() - out = append(out, RoomMember{Name: m.name(), Node: m.Num, Via: via, Handle: m.Handle()}) + rm := RoomMember{Name: m.name(), Node: m.Num, Via: via, Handle: m.Handle()} + switch { + case u == nil: + case registered: + rm.Op, rm.Voice = status[u.ID]&stOp != 0, status[u.ID]&stVoice != 0 + default: + rm.Op = u.Sysop + } + out = append(out, rm) } sort.Slice(out, func(i, j int) bool { return out[i].Node < out[j].Node }) return append(out, b.remoteMembers(name)...) @@ -330,6 +395,8 @@ type RoomMember struct { Via string // how they came (for one elsewhere, the network's ident) Handle string // a CB handle ("": none) Host string // for one elsewhere, their host + Op bool // an operator in the room (a sysop, in one not registered) + Voice bool // given a voice in a registered room } // enter puts the node in a room's members, tells the others, and gives @@ -345,8 +412,8 @@ func (n *Node) enter(name string) []Event { others := r.membersList() r.members[n] = true var hist []Event - if r.topic != "" { - hist = append(hist, Event{Kind: Topic, Room: name, Text: r.topic, Time: time.Now()}) + if topic := h.topicOf(name, r); topic != "" { + hist = append(hist, Event{Kind: Topic, Room: name, Text: topic, Time: time.Now()}) } hist = append(hist, r.history...) h.mu.Unlock() @@ -357,6 +424,9 @@ func (n *Node) enter(name string) []Event { if r := n.b.relayFor(name); r != nil { r.Joined(name, n.name()) } + // ops and voice by the access list, after the room's lines + hist = append(hist, n.arrive(name, n.User())...) + go n.b.expire() return hist } @@ -383,6 +453,7 @@ func (n *Node) LeaveRoom() { // exit takes the node out of a room's members, and tells the others. func (n *Node) exit(name string) { + u := n.User() h := n.b.hub() h.mu.Lock() r := h.rooms[name] @@ -390,11 +461,19 @@ func (n *Node) exit(name string) { if r != nil { delete(r.members, n) others = r.membersList() - if len(r.members) == 0 && !r.permanent { + if len(r.members) == 0 && !h.kept(name, r) { delete(h.rooms, name) } } h.mu.Unlock() + if u != nil && !n.b.inRoom(name, u.ID) { + // a user's status goes with their last node there + h.mu.Lock() + if r != nil && r.status != nil { + delete(r.status, u.ID) + } + h.mu.Unlock() + } e := Event{Kind: Left, Room: name, From: n.name(), Node: n.Num, Time: time.Now(), Handle: n.Handle()} for _, o := range others { o.deliver(e) @@ -489,6 +568,8 @@ type RoomInfo struct { Users []string Permanent bool // kept open when empty Topic string + // Registered: the room is a user's (ChanServ's REGISTER) + Registered bool } // Rooms lists the chat rooms in use (private ones only to sysops and @@ -508,7 +589,7 @@ func (b *BBS) rooms(u *store.User, node int) []RoomInfo { if strings.HasPrefix(name, "sysop-") && (node == 0 || name != pageRoom(node)) && (u == nil || !u.Sysop) { continue } - ri := RoomInfo{Name: name, Permanent: r.permanent, Topic: r.topic} + ri := RoomInfo{Name: name, Permanent: r.permanent, Topic: h.topicOf(name, r), Registered: h.regs[name] != nil} for m := range r.members { ri.Users = append(ri.Users, fmt.Sprintf("%s (%d)", m.name(), m.Num)) } diff --git a/internal/bbs/chatcmd.go b/internal/bbs/chatcmd.go index 38c908e..2b8cc0b 100644 --- a/internal/bbs/chatcmd.go +++ b/internal/bbs/chatcmd.go @@ -18,6 +18,9 @@ var ChatHelp = []string{ " /block WHO stop their messages /unblock WHO let them again", " /msg NICK TEXT to someone on a linked IRC network", " /quit leave the chat", + " /cs COMMAND ChanServ: register a room, its access list (/cs HELP)", + " /topic TEXT set the topic (a registered room's ops)", + " /kick WHO [WHY] put one out of the room (its ops)", "Sysops: /pages callers paging /answer [NODE] answer one /busy pages on or off", " /topic TEXT set a permanent room's topic", } @@ -78,10 +81,22 @@ func (n *Node) ChatCommand(line string) (out []string, leave bool, err error) { } return []string{"Topic: " + topic}, false, nil } - if u := n.User(); u == nil || !u.Sysop { - return nil, false, fmt.Errorf("a topic is set by the sysop") + return nil, false, n.SetTopic(room, arg) + case "cs", "chanserv": + return n.ChanServ(arg), false, nil + case "kick": + room := n.Room() + if room == "" { + return nil, false, ErrNotInRoom } - return nil, false, n.b.SetRoomTopic(room, arg, n.name()) + who, reason, _ := strings.Cut(arg, " ") + if who == "" { + return nil, false, fmt.Errorf("/kick WHO [WHY]: a user's name (Carol_Ann for Carol Ann)") + } + if err := n.Kick(room, who, reason); err != nil { + return nil, false, err + } + return nil, false, nil case "join", "j": hist, err := n.JoinRoom(arg) if err != nil { diff --git a/internal/bbs/chatrooms.go b/internal/bbs/chatrooms.go index e070589..7adff41 100644 --- a/internal/bbs/chatrooms.go +++ b/internal/bbs/chatrooms.go @@ -58,7 +58,7 @@ func (b *BBS) RemovePermanentRoom(name, by string) error { h.mu.Lock() if r := h.rooms[name]; r != nil { r.permanent, r.topic = false, "" - if len(r.members) == 0 { + if len(r.members) == 0 && !h.kept(name, r) { delete(h.rooms, name) } } @@ -67,25 +67,42 @@ func (b *BBS) RemovePermanentRoom(name, by string) error { return nil } -// SetRoomTopic sets a permanent room's topic ("": none), and tells those -// in it. +// SetRoomTopic sets a permanent or registered room's topic ("": none), +// and tells those in it. func (b *BBS) SetRoomTopic(name, topic, by string) error { name = strings.ToLower(strings.TrimSpace(name)) topic = Clean(topic, MaxTopic) h := b.hub() h.mu.Lock() r := h.rooms[name] - if r == nil || !r.permanent { + reg := h.regs[name] + permanent := r != nil && r.permanent + if reg == nil && !permanent { h.mu.Unlock() return ErrNotPermanent } h.mu.Unlock() - if err := b.Store.SetChatTopic(name, topic); err != nil { - return err + if permanent { + if err := b.Store.SetChatTopic(name, topic); err != nil { + return err + } + } + if reg != nil { + if err := b.Store.SetRoomRegTopic(name, topic, by); err != nil { + return err + } } h.mu.Lock() - r.topic = topic - members := r.membersList() + if permanent { + r.topic = topic + } + if reg := h.regs[name]; reg != nil { + reg.Topic, reg.TopicBy, reg.TopicAt = topic, by, time.Now() + } + var members []*Node + if r != nil { + members = r.membersList() + } h.mu.Unlock() e := Event{Kind: Topic, Room: name, From: by, Text: topic, Time: time.Now()} for _, m := range members { @@ -95,15 +112,14 @@ func (b *BBS) SetRoomTopic(name, topic, by string) error { return nil } -// RoomTopic is a room's topic, and whether the room is permanent. +// RoomTopic is a room's topic (a registered room's own, else a permanent +// room's), and whether the room is permanent. func (b *BBS) RoomTopic(name string) (topic string, permanent bool) { h := b.hub() h.mu.Lock() defer h.mu.Unlock() - if r := h.rooms[name]; r != nil { - return r.topic, r.permanent - } - return "", false + r := h.rooms[name] + return h.topicOf(name, r), r != nil && r.permanent } // PermanentRooms are the permanent rooms, by name. @@ -114,7 +130,7 @@ func (b *BBS) PermanentRooms() []RoomInfo { var out []RoomInfo for name, r := range h.rooms { if r.permanent { - ri := RoomInfo{Name: name, Permanent: true, Topic: r.topic} + ri := RoomInfo{Name: name, Permanent: true, Topic: h.topicOf(name, r), Registered: h.regs[name] != nil} for m := range r.members { ri.Users = append(ri.Users, m.name()) } diff --git a/internal/bbs/roomreg.go b/internal/bbs/roomreg.go new file mode 100644 index 0000000..abeea29 --- /dev/null +++ b/internal/bbs/roomreg.go @@ -0,0 +1,612 @@ +package bbs + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/store" +) + +// Registered rooms: a room a user owns (ChanServ's REGISTER), with an +// access list of who has which flags there. In a registered room ops and +// voices are given out (by the flags, as people come in, or by those who +// may), and ops may put people out. An unregistered room has no ops but +// the sysops, as before. All of it is the room's, so it holds for every +// way in: IRC, the text BBS, AOL, Yahoo and the rest. + +// The access flags, as Atheme's ChanServ has them. +const ( + FlagVoice = 'v' // VOICE, DEVOICE through ChanServ + FlagAutoVoice = 'V' // voiced on coming in + FlagOp = 'o' // OP, DEOP through ChanServ + FlagAutoOp = 'O' // opped on coming in + FlagTopic = 't' // TOPIC through ChanServ, and in a TOPICLOCK room + FlagInvite = 'i' // INVITE, GETKEY (with the modes to come) + FlagRemove = 'r' // KICK, BAN, UNBAN + FlagRecover = 'R' // CLEAR + FlagAccess = 'f' // changes the access list + FlagSet = 's' // SET + FlagView = 'A' // sees the access list + FlagExempt = 'e' // not kept out by a ban + FlagBanned = 'b' // kept out + FlagFounder = 'F' // everything +) + +// AllRoomFlags are the flags, in the order they are shown. +const AllRoomFlags = "AFORefiorstvVb" + +// founderFlags are a founder's: everything but b. +const founderFlags = "AFORefiorstv" + +// RoomTemplates are the access lists' shorthands. +var RoomTemplates = map[string]string{ + "VOP": "AV", + "AOP": "AOiortv", + "SOP": "AORefiorstv", + "FOUNDER": founderFlags, +} + +// Room status: in a registered room, a user's. +const ( + stOp uint8 = 1 << iota + stVoice +) + +// ChanServName is the nick of the rooms' service, as events name it. +const defaultChanServ = "ChanServ" + +// RoomExpiry is how long a registered room may go unused (no one on its +// access list coming in) before it is dropped; 0: never. +const defaultRoomExpiry = 90 * 24 * time.Hour + +// Refusals of the rooms' service and of ops' commands. +var ( + ErrBanned = errors.New("you are banned from that room") + ErrNotRegistered = errors.New("that room is not registered") + ErrNoPrivs = errors.New("you are not an operator in that room") + ErrNotThere = errors.New("they are not in that room") + ErrNoOps = errors.New("only registered rooms have operators (/cs REGISTER #room)") +) + +// SetChanServ names the rooms' service (as events from it name it), and +// how long a registered room may go unused (0: for ever). +func (b *BBS) SetChanServ(name string, expiry time.Duration) { + b.mu.Lock() + b.chanServ, b.roomExpiry, b.roomExpirySet = name, expiry, true + b.mu.Unlock() +} + +// ChanServ is the rooms' service's nick. +func (b *BBS) ChanServ() string { + b.mu.Lock() + defer b.mu.Unlock() + if b.chanServ == "" { + return defaultChanServ + } + return b.chanServ +} + +func (b *BBS) expiry() time.Duration { + b.mu.Lock() + defer b.mu.Unlock() + if !b.roomExpirySet { + return defaultRoomExpiry + } + return b.roomExpiry +} + +// RoomReg is a registered room (nil: not registered). +func (b *BBS) RoomReg(name string) *store.RoomReg { + h := b.hub() + h.mu.Lock() + defer h.mu.Unlock() + if r := h.regs[name]; r != nil { + c := *r + return &c + } + return nil +} + +// RoomGuarded: ChanServ holds the room open (its GUARD setting). +func (b *BBS) RoomGuarded(name string) bool { + h := b.hub() + h.mu.Lock() + defer h.mu.Unlock() + r := h.regs[name] + return r != nil && r.Has("guard") +} + +// GuardedRooms are the rooms ChanServ holds open. +func (b *BBS) GuardedRooms() []string { + h := b.hub() + h.mu.Lock() + defer h.mu.Unlock() + var out []string + for name, r := range h.regs { + if r.Has("guard") { + out = append(out, name) + } + } + return out +} + +// kept: the room stays when empty. The hub's lock is held. +func (h *hub) kept(name string, r *room) bool { + return r.permanent || h.regs[name] != nil && h.regs[name].Has("guard") +} + +// topicOf is a room's topic: a registered room's own, else a permanent +// room's. The hub's lock is held. +func (h *hub) topicOf(name string, r *room) string { + if reg := h.regs[name]; reg != nil { + return reg.Topic + } + if r != nil { + return r.topic + } + return "" +} + +// RoomFlags are a user's flags in a registered room as they act: the +// founder's (or one with F) everything, a sysop's everything; "" in a +// room not registered. +func (b *BBS) RoomFlags(name string, u *store.User) string { + reg := b.RoomReg(name) + if reg == nil || u == nil { + return "" + } + if u.Sysop || reg.FounderID == u.ID { + return founderFlags + } + flags, err := b.Store.RoomFlags(name, u.ID) + if err != nil { + b.Log.Printf("chat: flags in #%s: %v", name, err) + return "" + } + if strings.ContainsRune(flags, FlagFounder) { + return founderFlags + } + return flags +} + +// ownFlags are a user's flags on the list itself (the founder's all of +// them): what they get on coming in. +func (b *BBS) ownFlags(reg *store.RoomReg, u *store.User) string { + flags, err := b.Store.RoomFlags(reg.Name, u.ID) + if err != nil { + b.Log.Printf("chat: flags in #%s: %v", reg.Name, err) + } + if reg.FounderID == u.ID || strings.ContainsRune(flags, FlagFounder) { + return founderFlags + } + return flags +} + +func has(flags string, f rune) bool { return strings.ContainsRune(flags, f) } + +// banned: u is kept out of the room by its access list. +func (b *BBS) banned(name string, u *store.User) bool { + reg := b.RoomReg(name) + if reg == nil || u.Sysop || reg.FounderID == u.ID { + return false + } + flags, _ := b.Store.RoomFlags(name, u.ID) + return has(flags, FlagBanned) && !has(flags, FlagExempt) && !has(flags, FlagFounder) +} + +// statusOf is u's status in a room: in a registered one as given, in +// another op for a sysop. The hub's lock is held. +func (h *hub) statusOf(name string, r *room, u *store.User) uint8 { + if u == nil { + return 0 + } + if h.regs[name] == nil { + if u.Sysop { + return stOp + } + return 0 + } + if r == nil { + return 0 + } + return r.status[u.ID] +} + +// IsOp: u is an operator in the room. +func (b *BBS) IsOp(name string, u *store.User) bool { + h := b.hub() + h.mu.Lock() + defer h.mu.Unlock() + return h.statusOf(name, h.rooms[name], u)&stOp != 0 +} + +// arrive gives one coming into a registered room what their flags give +// (ops, voice) and notes the room used; the events are the joiner's to see +// (the others are told). The hub's lock is not held. +func (n *Node) arrive(name string, u *store.User) []Event { + b := n.b + reg := b.RoomReg(name) + if reg == nil || u == nil { + return nil + } + flags := b.ownFlags(reg, u) + if flags != "" && time.Since(reg.LastUsed) > time.Hour { + if err := b.Store.RoomUsed(name); err == nil { + h := b.hub() + h.mu.Lock() + if r := h.regs[name]; r != nil { + r.LastUsed = time.Now() + } + h.mu.Unlock() + } + } + var out []Event + if has(flags, FlagAutoOp) { + out = append(out, b.give(name, b.ChanServ(), 0, u, stOp, true, true)...) + } + if has(flags, FlagAutoVoice) { + out = append(out, b.give(name, b.ChanServ(), 0, u, stVoice, true, true)...) + } + if reg.EntryMsg != "" { + out = append(out, Event{Kind: Notice, From: b.ChanServ(), Text: "[#" + name + "] " + reg.EntryMsg, Time: time.Now()}) + } + return out +} + +// give gives (on) or takes a status from u in a registered room, telling +// those in it; arriving, u's own nodes are not told, the event is returned +// instead (for the one coming in to see after the room). Nothing changes: +// no events. +func (b *BBS) give(name, by string, byNode int, u *store.User, st uint8, on, arriving bool) []Event { + h := b.hub() + h.mu.Lock() + r := h.rooms[name] + if r == nil || h.regs[name] == nil { + h.mu.Unlock() + return nil + } + if r.status == nil { + r.status = map[int64]uint8{} + } + was := r.status[u.ID] + now := was &^ st + if on { + now = was | st + } + if now == was { + h.mu.Unlock() + return nil + } + if now == 0 { + delete(r.status, u.ID) + } else { + r.status[u.ID] = now + } + members := r.membersList() + h.mu.Unlock() + mode := "o" + if st == stVoice { + mode = "v" + } + sign := "-" + if on { + sign = "+" + } + e := Event{Kind: Mode, Room: name, From: by, Node: byNode, Text: sign + mode, Target: u.Name, Time: time.Now()} + var own []Event + for _, m := range members { + if mu := m.User(); arriving && mu != nil && mu.ID == u.ID { + own = []Event{e} + continue + } + m.deliver(e) + } + return own +} + +// SetStatus is an op's MODE +o, -o, +v or -v on one in the room: by an +// op there, or a sysop. +func (n *Node) SetStatus(name, who string, op, on bool) error { + u := n.User() + if u == nil { + return ErrNoUser + } + if n.b.RoomReg(name) == nil { + return ErrNoOps + } + if !u.Sysop && !n.b.IsOp(name, u) { + return ErrNoPrivs + } + return n.setStatus(name, who, op, on) +} + +// setStatus is SetStatus once allowed. +func (n *Node) setStatus(name, who string, op, on bool) error { + t, err := n.b.UserByNick(who) + if err != nil { + return err + } + if !n.b.inRoom(name, t.ID) { + return ErrNotThere + } + st := stVoice + if op { + st = stOp + } + n.b.give(name, n.name(), n.Num, t, st, on, false) + return nil +} + +// inRoom: one of the user's nodes is in the room. +func (b *BBS) inRoom(name string, id int64) bool { + for _, m := range b.roomNodes(name) { + if u := m.User(); u != nil && u.ID == id { + return true + } + } + return false +} + +// roomNodes are the nodes in a room. +func (b *BBS) roomNodes(name string) []*Node { + h := b.hub() + h.mu.Lock() + defer h.mu.Unlock() + if r := h.rooms[name]; r != nil { + return r.membersList() + } + return nil +} + +// Kick is an op's putting one out of a room: by an op there (one with r, +// through the service) or a sysop. A sysop is put out only by a sysop. +func (n *Node) Kick(name, who, reason string) error { + u := n.User() + if u == nil { + return ErrNoUser + } + if !u.Sysop && !n.b.IsOp(name, u) { + return ErrNoPrivs + } + t, err := n.b.UserByNick(who) + if err != nil { + return err + } + if t.Sysop && !u.Sysop { + return errors.New("the sysop can't be put out") + } + if reg := n.b.RoomReg(name); reg != nil && reg.FounderID == t.ID && !u.Sysop && u.ID != t.ID { + return errors.New("the founder can't be put out") + } + if n.b.kick(name, n.name(), n.Num, t, reason) == 0 { + return ErrNotThere + } + return nil +} + +// kick puts a user's nodes out of a room, telling those in it and them; +// it gives how many nodes went. +func (b *BBS) kick(name, by string, byNode int, t *store.User, reason string) int { + reason = Clean(reason, MaxTopic) + var gone []*Node + for _, m := range b.roomNodes(name) { + if mu := m.User(); mu != nil && mu.ID == t.ID { + gone = append(gone, m) + } + } + if len(gone) == 0 { + return 0 + } + for _, m := range gone { + cs := m.chat() + cs.mu.Lock() + if cs.room == name { + cs.room = "" + } + delete(cs.also, name) + cs.mu.Unlock() + } + h := b.hub() + h.mu.Lock() + r := h.rooms[name] + var others []*Node + if r != nil { + for _, m := range gone { + delete(r.members, m) + } + delete(r.status, t.ID) + others = r.membersList() + if len(r.members) == 0 && !h.kept(name, r) { + delete(h.rooms, name) + } + } + h.mu.Unlock() + e := Event{Kind: Kicked, Room: name, From: by, Node: byNode, Target: t.Name, TargetNode: gone[0].Num, Text: reason, Time: time.Now()} + for _, m := range append(others, gone...) { + m.deliver(e) + } + if rl := b.relayFor(name); rl != nil { + rl.Left(name, t.Name) + } + b.Log.Printf("chat: %s put %s out of #%s: %s", by, t.Name, name, reason) + return len(gone) +} + +// SetTopic sets a room's topic: a registered room's by its ops (or those +// with t; with TOPICLOCK, only those), a permanent room's by the sysop. +func (n *Node) SetTopic(name, topic string) error { + u := n.User() + if u == nil { + return ErrNoUser + } + if reg := n.b.RoomReg(name); reg != nil { + flags := n.b.RoomFlags(name, u) + if !has(flags, FlagTopic) && (reg.Has("topiclock") || !n.b.IsOp(name, u)) { + return errors.New("you may not set that room's topic") + } + } else if _, permanent := n.b.RoomTopic(name); !permanent { + return errors.New("only permanent and registered rooms have topics") + } else if !u.Sysop { + return errors.New("a topic is set by the sysop") + } + return n.b.SetRoomTopic(name, topic, u.Name) +} + +// UserByNick is the BBS user of a name, or of a nick (IRC's: Carol_Ann for +// Carol Ann). +func (b *BBS) UserByNick(nick string) (*store.User, error) { + nick = strings.TrimSpace(nick) + if nick == "" { + return nil, ErrNoUser + } + if u, err := b.Store.UserByName(nick); err == nil { + return u, nil + } + us, err := b.Store.Users() + if err != nil { + return nil, err + } + for _, u := range us { + if strings.EqualFold(Nick(u.Name), nick) { + return u, nil + } + } + return nil, fmt.Errorf("%w: %s", ErrNoUser, nick) +} + +// Nick is a BBS name as an IRC nick: what nicks may not have (spaces, +// dots) as underscores. +func Nick(name string) string { + return strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_': + return r + } + return '_' + }, name) +} + +// expire drops the registered rooms unused too long, at most once an hour. +func (b *BBS) expire() { + ex := b.expiry() + if ex <= 0 { + return + } + h := b.hub() + h.mu.Lock() + if time.Since(h.swept) < time.Hour { + h.mu.Unlock() + return + } + h.swept = time.Now() + var old []string + for name, r := range h.regs { + if time.Since(r.LastUsed) > ex { + old = append(old, name) + } + } + h.mu.Unlock() + for _, name := range old { + if err := b.dropRoom(name); err == nil { + b.Log.Printf("chat: #%s dropped, unused for %d days", name, int(ex.Hours()/24)) + } + } +} + +// registerRoom registers a room to u, who is given ops if there. +func (n *Node) registerRoom(name string, u *store.User) error { + b := n.b + h := b.hub() + h.mu.Lock() + _, taken := h.regs[name] + topic := "" + if r := h.rooms[name]; r != nil && r.permanent { + topic = r.topic + } + h.mu.Unlock() + if taken { + return errors.New("that room is registered already") + } + if err := b.Store.RegisterRoom(name, u.ID, founderFlags, u.Name); err != nil { + if errors.Is(err, store.ErrExists) { + return errors.New("that room is registered already") + } + return err + } + if topic != "" { + _ = b.Store.SetRoomRegTopic(name, topic, u.Name) + } + reg, err := b.Store.RoomReg(name) + if err != nil { + return err + } + h.mu.Lock() + h.regs[name] = reg + if r := h.rooms[name]; r != nil { + r.status = map[int64]uint8{} + } + h.mu.Unlock() + b.Log.Printf("chat: %s registered #%s", u.Name, name) + b.give(name, b.ChanServ(), 0, u, stOp, true, false) + return nil +} + +// dropRoom unregisters a room: its ops and voices go (sysops are its ops +// again), and it goes if empty and not permanent. +func (b *BBS) dropRoom(name string) error { + if err := b.Store.DropRoom(name); err != nil && !errors.Is(err, store.ErrNotFound) { + return err + } + h := b.hub() + h.mu.Lock() + delete(h.regs, name) + r := h.rooms[name] + var members []*Node + var status map[int64]uint8 + if r != nil { + status, r.status = r.status, nil + members = r.membersList() + if len(r.members) == 0 && !r.permanent { + delete(h.rooms, name) + } + } + h.mu.Unlock() + cs := b.ChanServ() + seen := map[int64]bool{} + for _, m := range members { + u := m.User() + if u == nil || seen[u.ID] { + continue + } + seen[u.ID] = true + var es []Event + st := status[u.ID] + if st&stOp != 0 && !u.Sysop { + es = append(es, Event{Kind: Mode, Room: name, From: cs, Text: "-o", Target: u.Name, Time: time.Now()}) + } + if st&stOp == 0 && u.Sysop { + es = append(es, Event{Kind: Mode, Room: name, From: cs, Text: "+o", Target: u.Name, Time: time.Now()}) + } + if st&stVoice != 0 { + es = append(es, Event{Kind: Mode, Room: name, From: cs, Text: "-v", Target: u.Name, Time: time.Now()}) + } + for _, e := range es { + for _, o := range members { + o.deliver(e) + } + } + } + return nil +} + +// updateReg changes a registered room as cached, after the store. +func (b *BBS) updateReg(name string, f func(r *store.RoomReg)) { + h := b.hub() + h.mu.Lock() + if r := h.regs[name]; r != nil { + f(r) + } + h.mu.Unlock() +} diff --git a/internal/ircd/chanserv.go b/internal/ircd/chanserv.go new file mode 100644 index 0000000..24800f7 --- /dev/null +++ b/internal/ircd/chanserv.go @@ -0,0 +1,98 @@ +package ircd + +import ( + "errors" + "strings" + + "github.com/D-Modem/bbs/internal/bbs" +) + +// ChanServ: the rooms' registration and access lists. The commands are +// the BBS's own (bbs.Node.ChanServ, which the BBS chat's /cs runs too); +// here they come as messages to the bot, or its own IRC command (/CS). + +// newChanServ is the rooms' service under nick name. +func newChanServ(name string) *service { + short := "CS" + if fold(name) != "chanserv" { + short = strings.ToUpper(name) + } + return &service{Name: name, ShortName: short, CommandAliases: []string{strings.ToUpper(name), short}, + raw: csLine} +} + +// csLine runs a line sent to ChanServ, its answers as notices. +func csLine(svc *service, c *client, line string) { + for _, l := range c.n.ChanServ(line) { + if l == "" { + l = " " + } + svc.notice(c, l) + } +} + +// serviceReal is a service's real name, as WHO and WHOIS give it. +func (s *Server) serviceReal(svc *service) string { + if svc == s.cs { + return "The registered rooms and their access lists" + } + return "Your BBS account and the permanent rooms" +} + +// eventSource is who a Mode or Kicked came from: a service, or someone on +// a node. +func (c *client) eventSource(e bbs.Event) string { + if svc := c.s.service(e.From); svc != nil && e.Node == 0 { + return svc.source(c) + } + return c.sourceOf(e.From, e.Node) +} + +// nodeOfUser is a node a user is on (0: none). +func (c *client) nodeOfUser(name string) int { + for _, n := range c.s.B.Nodes() { + if n.User == name { + return n.Num + } + } + return 0 +} + +// chanMode is MODE #room with changes: +o, -o, +v and -v (up to MODES of +// them) by the room's ops; the rest are not the BBS's yet. +func (c *client) chanMode(name, modes string, args []string) { + on, changes := true, 0 + for _, m := range modes { + switch m { + case '+': + on = true + case '-': + on = false + case 'o', 'v': + if len(args) == 0 { + continue + } + nick := args[0] + args = args[1:] + if changes++; changes > 4 { + return + } + err := c.n.SetStatus(name, nick, m == 'o', on) + switch { + case err == nil: + case errors.Is(err, bbs.ErrNoUser): + c.reply(ERR_NOSUCHNICK, nick, "No such nick") + case errors.Is(err, bbs.ErrNotThere): + c.reply(ERR_USERNOTINCHANNEL, nick, "#"+name, "They aren't on that channel") + default: + c.reply(ERR_CHANOPRIVSNEEDED, "#"+name, capital(err.Error())) + } + case 'n', 't': + if !on { + c.reply(ERR_CHANOPRIVSNEEDED, "#"+name, "The BBS's rooms are always +nt") + } + default: + c.reply(ERR_UNKNOWNMODE, string(m), "is not a mode the BBS's rooms have") + } + } +} diff --git a/internal/ircd/chanserv_test.go b/internal/ircd/chanserv_test.go new file mode 100644 index 0000000..bd41f1b --- /dev/null +++ b/internal/ircd/chanserv_test.go @@ -0,0 +1,194 @@ +package ircd + +import ( + "strings" + "testing" + "time" +) + +// TestChanServ: a room registered by one in it, who is opped; the access +// list (FLAGS), auto-op and auto-voice on coming in, by IRC and from the +// BBS; ops' MODE and KICK; topics; BAN keeping one out; CLEAR USERS +// putting everyone out; DROP. +func TestChanServ(t *testing.T) { + e := start(t) + cs := ":ChanServ!ChanServ@irc.test NOTICE " + a := e.dial(t) + a.send("CAP REQ :multi-prefix") + a.expect("CAP * ACK") + a.send("CAP END") + a.login("alice", "alice") + b := e.dial(t) + b.login("bob", "bob") + + a.send("PRIVMSG ChanServ :REGISTER #den") + a.expect(cs + "alice :Come into #den to register it.") + a.send("JOIN #den") + a.expect("353 alice = #den :alice") + a.send("CS REGISTER #den") + a.expectAll(":ChanServ!ChanServ@irc.test MODE #den +o alice", cs+"alice :#den is registered to you.") + a.send("CS REGISTER #den") + a.expect(cs + "alice :That room is registered already.") + + // bob comes in with nothing; is opped by alice's MODE, and kicked + b.send("JOIN #den") + b.expect("353 bob = #den :") + a.expect(":bob!irc@node2 JOIN #den") + b.send("MODE #den +o bob") + b.expect("482 bob #den :You are not an operator in that room") + b.send("TOPIC #den :mine") + b.expect("482 bob #den :You may not set that room's topic") + a.send("MODE #den +v bob") + b.expect(":alice!irc@node1 MODE #den +v bob") + a.send("TOPIC #den :Welcome") + b.expect(":alice!irc@node1 TOPIC #den :Welcome") + a.send("KICK #den bob :out you go") + b.expect(":alice!irc@node1 KICK #den bob :out you go") + b.send("PRIVMSG #den :still here?") + b.expect(" 404 ") + + // the access list: bob as AOP is opped on coming in + a.send("CS FLAGS #den bob AOP") + a.expect(cs + "alice :bob has +AOiortv in #den.") + b.send("CS FLAGS #den bob +F") + b.expect(cs + "bob :You need the f flag in #den for that.") + b.send("JOIN #den") + b.expect("353 bob = #den :") + b.expect(":ChanServ!ChanServ@irc.test MODE #den +o bob") + a.expect(":ChanServ!ChanServ@irc.test MODE #den +o bob") + b.send("CS FLAGS #den") + b.expect(cs + "bob :Access list of #den:") + b.expect("alice (founder)") + b.expect(cs + "bob :End of the list: 2 entries.") + b.send("CS FLAGS #den bob +s") + b.expect(cs + "bob :You need the f flag in #den for that.") + + // a caller on the BBS: voiced on coming in, and sees ops as lines + carol := e.caller(t, "Carol Ann") + a.send("CS FLAGS #den Carol_Ann VOP") + a.expect(cs + "alice :Carol_Ann has +AV in #den.") + hist, err := carol.JoinRoom("den") + if err != nil { + t.Fatal(err) + } + var lines []string + for _, ev := range hist { + lines = append(lines, ev.String()) + } + if !strings.Contains(strings.Join(lines, "|"), "ChanServ gave Carol Ann a voice in den") { + t.Errorf("joining: %q", lines) + } + a.expect(":ChanServ!ChanServ@irc.test MODE #den +v Carol_Ann") + a.send("NAMES #den") + l := a.expect("353 alice = #den") + for _, want := range []string{"@alice", "@bob", "+Carol_Ann"} { + if !strings.Contains(l, want) { + t.Errorf("names %q: no %s", l, want) + } + } + if _, _, err := carol.ChatCommand("/kick bob"); err == nil || !strings.Contains(err.Error(), "not an operator") { + t.Errorf("a voice kicked: %v", err) + } + if out := carol.ChanServ("WHY #den"); len(out) != 1 || !strings.Contains(out[0], "+AV") { + t.Errorf("why: %q", out) + } + + // BAN keeps one out; UNBAN lets them in again + a.send("CS BAN #den Carol_Ann spam") + a.expectAll(":ChanServ!ChanServ@irc.test KICK #den Carol_Ann :spam (alice)", cs+"alice :Carol_Ann is banned from #den.") + waitEvent(t, carol, "ChanServ put Carol Ann out of den: spam (alice)") + if carol.InRoom("den") { + t.Error("banned, still in") + } + if _, err := carol.JoinRoom("den"); err == nil { + t.Error("banned, came in") + } + a.send("CS UNBAN #den Carol_Ann") + a.expect(cs + "alice :Carol_Ann may come into #den again.") + if _, err := carol.JoinRoom("den"); err != nil { + t.Errorf("unbanned: %v", err) + } + + // CLEAR USERS: everyone out but the one asking + b.send("CS CLEAR #den USERS") + b.expect(cs + "bob :You need the R flag in #den for that.") + a.send("CS CLEAR #den USERS closing time") + a.expectAll(":ChanServ!ChanServ@irc.test KICK #den bob :closing time (alice)", cs+"alice :#den is cleared: 2 put out.") + waitEvent(t, carol, "put Carol Ann out of den: closing time") + if ms := e.b.RoomMembers("den"); len(ms) != 1 || ms[0].Name != "alice" || carol.InRoom("den") { + t.Errorf("cleared, left %+v", ms) + } + + // settings, INFO, LIST; DROP by the founder alone + a.send("CS SET #den ENTRYMSG Be nice", "CS SET #den GUARD ON", "CS INFO #den") + a.expect(cs + "alice :The ENTRYMSG of #den is set.") + a.expect(cs + "alice :GUARD is on for #den.") + a.expect(cs + "alice :Founder : alice") + a.expect(cs + "alice :Topic : Welcome") + a.send("PART #den", "LIST") + a.expect("322 alice #den 1 :Welcome") + a.send("JOIN #den") + a.expect("353 alice = #den :@ChanServ @alice") + a.expect(cs + "alice :[#den] Be nice") + b.send("CS LIST", "CS DROP #den") + b.expect(cs + "bob : #den +AOiortv") + b.expect(cs + "bob :Only the founder may drop a room.") + a.send("CS DROP #den") + a.expectAll(":ChanServ!ChanServ@irc.test MODE #den -o alice", cs+"alice :#den is unregistered.") + a.send("CS INFO #den") + a.expect(cs + "alice :#den is not registered.") +} + +// TestChanServRules: page and linked rooms can't be registered; sysops +// act as founders; a deleted founder's room passes on. +func TestChanServRules(t *testing.T) { + e := start(t) + cs := ":ChanServ!ChanServ@irc.test NOTICE " + a := e.dial(t) + a.login("alice", "alice") + s := e.dial(t) + s.login("sysop", "sysop") + a.send("JOIN #sysop-1", "CS REGISTER #sysop-1") + a.expect(cs + "alice :Page rooms can't be registered.") + a.send("JOIN #room", "CS REGISTER #room", "CS FLAGS #room bob SOP") + a.expect(cs + "alice :bob has +AORefiorstv in #room.") + s.send("CS FLAGS #room", "CS SET #room TOPICLOCK ON") + s.expect(cs + "sysop :Access list of #room:") + s.expect(cs + "sysop :TOPICLOCK is on for #room.") + + // alice's account goes: bob, with the most flags, founds the room + alice, _ := e.b.Store.UserByName("alice") + if err := e.b.Store.DeleteUser(alice.ID); err != nil { + t.Fatal(err) + } + reg, err := e.b.Store.RoomReg("room") + if err != nil { + t.Fatal(err) + } + if reg.Founder != "bob" { + t.Errorf("founder %q", reg.Founder) + } +} + +// expectAll reads lines until each of wants has been in one, in any order +// (a service's notices and the room's events come by different ways). +func (c *conn) expectAll(wants ...string) { + c.t.Helper() + left := append([]string(nil), wants...) + var seen []string + for len(left) > 0 { + c.c.SetReadDeadline(time.Now().Add(3 * time.Second)) + l, err := c.r.ReadString('\n') + if err != nil { + c.t.Fatalf("waiting for %q: %v; got %q", left, err, seen) + } + l = strings.TrimRight(l, "\r\n") + seen = append(seen, l) + for i, w := range left { + if strings.Contains(l, w) { + left = append(left[:i], left[i+1:]...) + break + } + } + } +} diff --git a/internal/ircd/commands.go b/internal/ircd/commands.go index 7518594..221221f 100644 --- a/internal/ircd/commands.go +++ b/internal/ircd/commands.go @@ -70,7 +70,7 @@ func (c *client) command(m *ircmsg.Message) { var on []string for _, nick := range m.Params { for _, w := range strings.Fields(nick) { - if _, remote := c.s.B.LookupRemote(w); len(c.nodesOf(w)) > 0 || remote || fold(w) == fold(c.s.svc.Name) { + if _, remote := c.s.B.LookupRemote(w); len(c.nodesOf(w)) > 0 || remote || c.s.service(w) != nil { on = append(on, w) } } @@ -98,12 +98,16 @@ func (c *client) command(m *ircmsg.Message) { case "INFO": c.reply(RPL_INFO, c.s.B.Conf().Name+": the BBS's chat rooms are its channels") c.reply(RPL_ENDOFINFO, "End of INFO") - case "KICK", "INVITE", "OPER", "KILL", "KNOCK": - c.reply(ERR_NOPRIVILEGES, "Permission denied: the BBS's rooms are everyone's") + case "KICK": + c.kick(param(m, 0), param(m, 1), param(m, 2)) + case "INVITE", "OPER", "KILL", "KNOCK": + c.reply(ERR_NOPRIVILEGES, "Permission denied") default: - if slices.Contains(c.s.svc.CommandAliases, m.Command) { - c.s.svc.command(c, m.Params) - return + for _, svc := range []*service{c.s.svc, c.s.cs} { + if slices.Contains(svc.CommandAliases, m.Command) { + svc.command(c, m.Params) + return + } } c.reply(ERR_UNKNOWNCOMMAND, m.Command, "Unknown command") } @@ -169,6 +173,9 @@ func (c *client) join(list string) { case errors.Is(err, bbs.ErrNoRoom): c.reply(ERR_BADCHANMASK, ch, "A channel is # and 1 to 20 letters, digits or -") continue + case errors.Is(err, bbs.ErrBanned): + c.reply(ERR_BANNEDFROMCHAN, ch, "Cannot join channel (+b): "+err.Error()) + continue case errors.Is(err, bbs.ErrNotYours), errors.Is(err, bbs.ErrNotAllowed): c.reply(ERR_INVITEONLYCHAN, ch, "Cannot join channel: "+err.Error()) continue @@ -200,18 +207,35 @@ func (c *client) part(ch string) { } // member is a room member as NAMES and WHO give one: nick, user (how they -// came), host (their node), and op for a sysop (@). -func (c *client) member(m bbs.RoomMember) (nick, user, host string, op bool) { +// came), host (their node), and their prefixes (@ an op, + a voice; with +// multi-prefix both, else the highest). +func (c *client) member(m bbs.RoomMember) (nick, user, host, prefix string) { if m.Node == 0 { // on a linked network: as it names them - return m.Name, m.Via, m.Host, false + return m.Name, m.Via, m.Host, "" } nick, user, host = Nick(m.Name), m.Via, fmt.Sprintf("node%d", m.Node) - if u, err := c.s.B.Store.UserByName(m.Name); err == nil && u.Sysop { - op = true + if m.Op { + prefix = "@" + } + if m.Voice && (prefix == "" || c.caps["multi-prefix"]) { + prefix += "+" } return } +// roomServices are the services sitting in a room: BBSServ in a permanent +// one, ChanServ in a guarded one. +func (c *client) roomServices(name string) []*service { + var out []*service + if _, permanent := c.s.B.RoomTopic(name); permanent { + out = append(out, c.s.svc) + } + if c.s.B.RoomGuarded(name) { + out = append(out, c.s.cs) + } + return out +} + // names is NAMES for one channel: the service first in a permanent room, // sysops as ops; a sysop- room's only to those in it. func (c *client) names(ch string) { @@ -219,16 +243,16 @@ func (c *client) names(ch string) { if name != "" && (c.n.InRoom(name) || !strings.HasPrefix(name, "sysop-")) { var line []string seen := map[string]bool{} - if _, permanent := c.s.B.RoomTopic(name); permanent { - // the service holds the permanent rooms open - entry := c.s.svc.Name + for _, svc := range c.roomServices(name) { + // the services hold permanent and guarded rooms open + entry := svc.Name if c.caps["userhost-in-names"] { - entry = c.s.svc.source(c) + entry = svc.source(c) } line = append(line, "@"+entry) } for _, m := range c.s.B.RoomMembers(name) { - nick, user, host, op := c.member(m) + nick, user, host, prefix := c.member(m) entry := nick if c.caps["userhost-in-names"] { entry = nick + "!" + user + "@" + host @@ -237,9 +261,7 @@ func (c *client) names(ch string) { continue } seen[entry] = true - if op { - entry = "@" + entry - } + entry = prefix + entry line = append(line, entry) if len(strings.Join(line, " ")) > 350 { c.reply(RPL_NAMREPLY, "=", "#"+name, strings.Join(line, " ")) @@ -256,7 +278,7 @@ func (c *client) names(ch string) { // nodesOf are the nodes online of a nick's user (none for the service's // nick, which is the service's). func (c *client) nodesOf(nick string) []bbs.NodeInfo { - if fold(nick) == fold(c.s.svc.Name) { + if c.s.service(nick) != nil { return nil } var out []bbs.NodeInfo @@ -270,7 +292,7 @@ func (c *client) nodesOf(nick string) []bbs.NodeInfo { // userOfNick is the BBS user a nick is of, on or not (nil: none). func (c *client) userOfNick(nick string) *store.User { - if fold(nick) == fold(c.s.svc.Name) { + if c.s.service(nick) != nil { return nil } if u, err := c.s.B.Store.UserByName(nick); err == nil { @@ -293,17 +315,13 @@ func (c *client) userOfNick(nick string) *store.User { func (c *client) who(mask string) { if name := room(mask); name != "" { if c.n.InRoom(name) || !strings.HasPrefix(name, "sysop-") { - if _, permanent := c.s.B.RoomTopic(name); permanent { - svc := c.s.svc + for _, svc := range c.roomServices(name) { c.reply(RPL_WHOREPLY, "#"+name, svc.Name, c.s.S.ServerName, c.s.S.ServerName, svc.Name, "H@", - "0 Your BBS account and the permanent rooms") + "0 "+c.s.serviceReal(svc)) } for _, m := range c.s.B.RoomMembers(name) { - nick, user, host, op := c.member(m) - flags := "H" - if op { - flags += "@" - } + nick, user, host, prefix := c.member(m) + flags := "H" + prefix c.reply(RPL_WHOREPLY, "#"+name, user, host, c.s.S.ServerName, nick, flags, "0 "+m.Name) } } @@ -319,12 +337,19 @@ func (c *client) who(mask string) { // whois is WHOIS: the service, or a nick's user, their nodes and what each // is doing, whether they are the sysop, and how long since they came on. func (c *client) whois(nick string) { - if svc := c.s.svc; fold(nick) == fold(svc.Name) { + if svc := c.s.service(nick); svc != nil { c.reply(RPL_WHOISUSER, svc.Name, svc.Name, c.s.S.ServerName, "*", - fmt.Sprintf("Your BBS account: /msg %s HELP", svc.Name)) + fmt.Sprintf("%s: /msg %s HELP", c.s.serviceReal(svc), svc.Name)) var chans []string - for _, r := range c.s.B.PermanentRooms() { - chans = append(chans, "@#"+r.Name) + if svc == c.s.svc { + for _, r := range c.s.B.PermanentRooms() { + chans = append(chans, "@#"+r.Name) + } + } else { + for _, r := range c.s.B.GuardedRooms() { + chans = append(chans, "@#"+r) + } + slices.Sort(chans) } if len(chans) > 0 { c.reply(RPL_WHOISCHANNELS, svc.Name, strings.Join(chans, " ")) @@ -382,37 +407,55 @@ func (c *client) whoisRemote(r bbs.RemoteUser) { c.reply(RPL_ENDOFWHOIS, r.Nick, "End of /WHOIS list") } -// list is LIST: the rooms, their numbers of callers (the service counted -// in a permanent room) and their topics. +// list is LIST: the rooms, their numbers of callers (the services counted +// in the rooms they hold) and their topics. func (c *client) list() { c.reply(RPL_LISTSTART, "Channel", "Users Name") for _, r := range c.n.Rooms() { - users := len(r.Users) - if r.Permanent { - users++ // the service - } + users := len(r.Users) + len(c.roomServices(r.Name)) // the services holding it open c.reply(RPL_LIST, "#"+r.Name, strconv.Itoa(users), r.Topic) } c.reply(RPL_LISTEND, "End of /LIST") } -// topic is TOPIC: a room's topic shown; set it only if it is permanent and -// the user is the sysop. +// topic is TOPIC: a room's topic shown, or set: a registered room's by +// its ops, a permanent room's by the sysop. func (c *client) topic(ch, text string, set bool) { name := room(ch) _, permanent := c.s.B.RoomTopic(name) switch { - case name == "" || !c.n.InRoom(name) && !permanent: + case name == "" || !c.n.InRoom(name) && !permanent && c.s.B.RoomReg(name) == nil: c.reply(ERR_NOTONCHANNEL, ch, "You're not on that channel") case !set: c.sendTopic("#"+name, name) - case !permanent: - c.reply(ERR_CHANOPRIVSNEEDED, ch, fmt.Sprintf("Only permanent rooms have topics (/msg %s HELP ROOM)", c.s.svc.Name)) - case !c.u.Sysop: - c.reply(ERR_CHANOPRIVSNEEDED, ch, "A topic is set by the sysop") default: - if err := c.s.B.SetRoomTopic(name, text, c.u.Name); err != nil { - c.reply(ERR_UNKNOWNERROR, "TOPIC", err.Error()) + if err := c.n.SetTopic(name, text); err != nil { + c.reply(ERR_CHANOPRIVSNEEDED, "#"+name, capital(err.Error())) + } + } +} + +// kick is KICK: ops put people out (a list of nicks, parted by commas). +func (c *client) kick(ch, nicks, reason string) { + name := room(ch) + if name == "" || nicks == "" { + c.reply(ERR_NEEDMOREPARAMS, "KICK", "Not enough parameters") + return + } + if !c.n.InRoom(name) && !c.u.Sysop { + c.reply(ERR_NOTONCHANNEL, ch, "You're not on that channel") + return + } + for _, nick := range strings.Split(nicks, ",") { + err := c.n.Kick(name, nick, reason) + switch { + case err == nil: + case errors.Is(err, bbs.ErrNoUser): + c.reply(ERR_NOSUCHNICK, nick, "No such nick") + case errors.Is(err, bbs.ErrNotThere): + c.reply(ERR_USERNOTINCHANNEL, nick, "#"+name, "They aren't on that channel") + default: + c.reply(ERR_CHANOPRIVSNEEDED, "#"+name, capital(err.Error())) } } } @@ -426,7 +469,8 @@ func (c *client) sendTopic(ch, name string) { } } -// mode is MODE: a channel's are +nt and never change; a user's own is +i. +// mode is MODE: a channel's are +nt; its ops give and take o and v (in a +// registered room). A user's own is +i. func (c *client) mode(m *ircmsg.Message) { target := param(m, 0) if name := room(target); name != "" { @@ -436,7 +480,7 @@ func (c *client) mode(m *ircmsg.Message) { case strings.Trim(param(m, 1), "+") == "b": c.reply(RPL_ENDOFBANLIST, "#"+name, "End of channel ban list") default: - c.reply(ERR_CHANOPRIVSNEEDED, target, "The BBS's rooms have no modes to change") + c.chanMode(name, m.Params[1], m.Params[2:]) } return } @@ -461,9 +505,9 @@ func (c *client) privmsg(command, target, text string) { } return } - if fold(target) == fold(c.s.svc.Name) { + if svc := c.s.service(target); svc != nil { if !notice { // a NOTICE to a bot is never answered - c.s.svc.privmsg(c, stripped(text)) + svc.privmsg(c, stripped(text)) } return } @@ -624,7 +668,18 @@ func (c *client) event(e bbs.Event) { c.send(tags, c.sourceOfEvent(e), "PART", "#"+e.Room) } case bbs.Topic: - c.send(tags, c.s.svc.source(c), "TOPIC", "#"+e.Room, e.Text) + source := c.s.svc.source(c) + if c.s.B.RoomReg(e.Room) != nil { + source = c.s.cs.source(c) + if e.From != "" && e.From != c.s.cs.Name { + source = c.sourceOf(e.From, c.nodeOfUser(e.From)) + } + } + c.send(tags, source, "TOPIC", "#"+e.Room, e.Text) + case bbs.Mode: + c.send(tags, c.eventSource(e), "MODE", "#"+e.Room, e.Text, Nick(e.Target)) + case bbs.Kicked: + c.send(tags, c.eventSource(e), "KICK", "#"+e.Room, Nick(e.Target), e.Text) case bbs.Private: text := e.Text if e.Kept && !c.caps["server-time"] { @@ -642,7 +697,11 @@ func (c *client) event(e bbs.Event) { c.send(tags, "", "NOTICE", "#"+e.Room, e.Text) // the room's, from a chat network return } - c.send(tags, "", "NOTICE", c.nick, e.String()) + source := "" + if svc := c.s.service(e.From); svc != nil { + source = svc.source(c) // a room's entry message, from ChanServ + } + c.send(tags, source, "NOTICE", c.nick, e.String()) default: c.send(tags, "", "NOTICE", c.nick, e.String()) } diff --git a/internal/ircd/server.go b/internal/ircd/server.go index 9856c34..d424acc 100644 --- a/internal/ircd/server.go +++ b/internal/ircd/server.go @@ -38,6 +38,10 @@ type Settings struct { MaxClients int MaxPerIP int Service string // the services bot's nick (default BBSServ) + ChanServ string // the rooms' service's nick (default ChanServ) + // ChanServExpire: days a registered room may go unused before it is + // dropped (0: never) + ChanServExpire int } // Server serves IRC. @@ -48,6 +52,7 @@ type Server struct { created time.Time support *isupport.List svc *service // BBSServ + cs *service // ChanServ mu sync.Mutex clients map[*client]bool } @@ -82,7 +87,14 @@ func New(b *bbs.BBS, s Settings) (*Server, error) { if !ValidNick(s.Service) { return nil, fmt.Errorf("irc: service %q: a nick is letters, digits, - and _", s.Service) } - srv := &Server{B: b, S: s, created: time.Now(), clients: map[*client]bool{}, svc: newBBSServ(s.Service)} + if s.ChanServ == "" { + s.ChanServ = "ChanServ" + } + if !ValidNick(s.ChanServ) || fold(s.ChanServ) == fold(s.Service) { + return nil, fmt.Errorf("irc: chanserv %q: a nick is letters, digits, - and _, and not the other service's", s.ChanServ) + } + b.SetChanServ(s.ChanServ, time.Duration(s.ChanServExpire)*24*time.Hour) + srv := &Server{B: b, S: s, created: time.Now(), clients: map[*client]bool{}, svc: newBBSServ(s.Service), cs: newChanServ(s.ChanServ)} srv.support = isupport.NewList() for k, v := range map[string]string{ "CASEMAPPING": "ascii", @@ -91,9 +103,9 @@ func New(b *bbs.BBS, s Settings) (*Server, error) { "CHANLIMIT": "#:20", "NICKLEN": strconv.Itoa(bbs.MaxNameLen), "NETWORK": s.Network, - "PREFIX": "(o)@", + "PREFIX": "(ov)@+", "CHANMODES": ",,,nt", - "MODES": "1", + "MODES": "4", "TOPICLEN": "0", "TARGMAX": "PRIVMSG:1,NOTICE:1,JOIN:,PART:,NAMES:1,WHOIS:1", "LINELEN": "512", @@ -163,14 +175,16 @@ func (s *Server) Clients() int { // Nick is a BBS name as an IRC nick: what nicks may not have (spaces, // dots) as underscores. -func Nick(name string) string { - return strings.Map(func(r rune) rune { - switch { - case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_': - return r +func Nick(name string) string { return bbs.Nick(name) } + +// service is the services bot of a nick (nil: none). +func (s *Server) service(nick string) *service { + for _, svc := range []*service{s.svc, s.cs} { + if fold(nick) == fold(svc.Name) { + return svc } - return '_' - }, name) + } + return nil } // numerics ergo's list lacks diff --git a/internal/ircd/services.go b/internal/ircd/services.go index e242723..76f393d 100644 --- a/internal/ircd/services.go +++ b/internal/ircd/services.go @@ -21,6 +21,9 @@ type service struct { CommandAliases []string // IRC commands that talk to it Commands map[string]*serviceCommand HelpBanner string + // raw, if set, runs every line sent to the service (but CTCPs), in + // place of its command table + raw func(svc *service, c *client, line string) } // serviceCommand is one of a service's commands. @@ -87,6 +90,10 @@ func (svc *service) privmsg(c *client, message string) { svc.ctcp(c, message) return } + if svc.raw != nil { + svc.raw(svc, c, message) + return + } params := strings.Fields(message) if len(params) == 0 { return diff --git a/internal/ircd/services_test.go b/internal/ircd/services_test.go index faf8c63..c7258e6 100644 --- a/internal/ircd/services_test.go +++ b/internal/ircd/services_test.go @@ -182,7 +182,7 @@ func TestPermanentChannels(t *testing.T) { a.send("TOPIC #lobby") a.expect("331 alice #lobby :No topic is set") a.send("JOIN #other", "TOPIC #other :x") - a.expect(" 482 alice #other :Only permanent rooms have topics") + a.expect(" 482 alice #other :Only permanent and registered rooms have topics") // a caller on the BBS sees it too bob := e.caller(t, "bob") diff --git a/internal/marvel/chat.go b/internal/marvel/chat.go index 7e44a63..35ed480 100644 --- a/internal/marvel/chat.go +++ b/internal/marvel/chat.go @@ -341,7 +341,10 @@ func (ch *chat) relay(n *bbs.Node, stop chan struct{}) { from := ch.participantID(e.From, e.Node) ch.mu.Unlock() ch.event(evJoined, from, rec) - case bbs.Left: + case bbs.Left, bbs.Kicked: + if e.Kind == bbs.Kicked { + e.From, e.Node = e.Target, e.TargetNode + } ch.mu.Lock() from := ch.participantID(e.From, e.Node) delete(ch.ids, strings.ToLower(e.From)) diff --git a/internal/msn/events.go b/internal/msn/events.go index 9e89a77..36e434f 100644 --- a/internal/msn/events.go +++ b/internal/msn/events.go @@ -9,6 +9,12 @@ import ( // event is something the node is told: a private message, as an IM from // its sender; anything else as an IM from the BBS. func (ns *nsSession) event(e bbs.Event) { + if plain := bbs.Plain(e); plain != nil { // ops and kicks: as notices and leaving + for _, x := range plain { + ns.event(x) + } + return + } switch e.Kind { case bbs.Private: text := e.Text diff --git a/internal/oscar/events.go b/internal/oscar/events.go index 048e056..a5aa68d 100644 --- a/internal/oscar/events.go +++ b/internal/oscar/events.go @@ -10,6 +10,12 @@ import ( // room's line to its chat connection, anything else as an IM from the // system. func (ss *session) event(e bbs.Event) { + if plain := bbs.Plain(e); plain != nil { // ops and kicks: as notices and leaving + for _, x := range plain { + ss.event(x) + } + return + } switch e.Kind { case bbs.Private: text := e.Text diff --git a/internal/server/ircconfig.go b/internal/server/ircconfig.go index 6967591..2a6e109 100644 --- a/internal/server/ircconfig.go +++ b/internal/server/ircconfig.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net" + "strings" "github.com/D-Modem/bbs/internal/config" "github.com/D-Modem/bbs/internal/ircd" @@ -19,10 +20,13 @@ func (c *Config) ircSection(cf *config.File) error { i := &ircd.Settings{Address: s.String("address", ":6667"), TLSAddress: s.String("tls_address", ""), CertFile: s.String("tls_cert", ""), KeyFile: s.String("tls_key", ""), ServerName: s.String("server_name", ""), Network: s.String("network", ""), - Service: s.String("service", "BBSServ")} + Service: s.String("service", "BBSServ"), ChanServ: s.String("chanserv", "ChanServ")} if !ircd.ValidNick(i.Service) { return errors.New("service: the bot's nick, a letter then letters, digits, - and _") } + if !ircd.ValidNick(i.ChanServ) || strings.EqualFold(i.ChanServ, i.Service) { + return errors.New("chanserv: the rooms' bot's nick, a letter then letters, digits, - and _ (not service's)") + } if i.Address == "none" { // TLS only i.Address = "" } @@ -50,6 +54,9 @@ func (c *Config) ircSection(cf *config.File) error { if i.MaxPerIP, err = s.Int("max_per_ip", 4, 0, 1000); err != nil { return err } + if i.ChanServExpire, err = s.Int("chanserv_expire", 90, 0, 100000); err != nil { + return err + } if i.Address != "" && i.TLSAddress == "" { c.Warnings = append(c.Warnings, "[irc] passwords go in the clear: give it a tls_address too") } diff --git a/internal/store/copy.go b/internal/store/copy.go index 3a34fd2..5cf6b07 100644 --- a/internal/store/copy.go +++ b/internal/store/copy.go @@ -12,7 +12,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", "mailbox", "mail_uids", "mail_queue", "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", "fido_subs", + "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "room_reg", "room_access", "topic_read", "fido_subs", "chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys", "chats", "friends", "oscar_buddies", "msn_keys", "blocks", "address_book", "ntlm_keys", "ymsg_keys"} var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`) diff --git a/internal/store/roomreg.go b/internal/store/roomreg.go new file mode 100644 index 0000000..01b9782 --- /dev/null +++ b/internal/store/roomreg.go @@ -0,0 +1,250 @@ +package store + +import ( + "database/sql" + "errors" + "strings" + "time" +) + +// Registered chat rooms (ChanServ's): a room a user owns, its settings +// and topic, and its access list: who has which flags there. + +// RoomReg is a registered room. +type RoomReg struct { + Name string + FounderID int64 + Founder string // the founder's name ("": the account is gone) + Registered time.Time + LastUsed time.Time + Settings string // words: "guard private topiclock" + Descr string + URL string + EntryMsg string + Topic string + TopicBy string + TopicAt time.Time +} + +// Has: the room has that setting on. +func (r *RoomReg) Has(setting string) bool { + for _, w := range strings.Fields(r.Settings) { + if w == setting { + return true + } + } + return false +} + +// RoomAccess is one on a registered room's access list. +type RoomAccess struct { + Room string + UserID int64 + Name string // the user's name + Flags string + SetBy string + SetAt time.Time +} + +const roomRegCols = `r.name, r.founder_id, COALESCE(u.name, ''), r.registered, r.last_used, r.settings, r.descr, r.url, r.entrymsg, r.topic, r.topic_by, r.topic_at` + +func scanRoomReg(sc interface{ Scan(...any) error }) (*RoomReg, error) { + var r RoomReg + var reg, used, tat int64 + if err := sc.Scan(&r.Name, &r.FounderID, &r.Founder, ®, &used, &r.Settings, &r.Descr, &r.URL, &r.EntryMsg, &r.Topic, &r.TopicBy, &tat); err != nil { + return nil, err + } + r.Registered, r.LastUsed, r.TopicAt = unix(reg), unix(used), unix(tat) + return &r, nil +} + +// RoomRegs are the registered rooms, by name. +func (s *Store) RoomRegs() ([]*RoomReg, error) { + rows, err := s.db.Query(`SELECT ` + roomRegCols + ` FROM room_reg r LEFT JOIN users u ON u.id = r.founder_id ORDER BY r.name`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*RoomReg + for rows.Next() { + r, err := scanRoomReg(rows) + if err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +// RoomReg is a registered room; ErrNotFound if it is not registered. +func (s *Store) RoomReg(name string) (*RoomReg, error) { + r, err := scanRoomReg(s.db.QueryRow(`SELECT `+roomRegCols+` FROM room_reg r LEFT JOIN users u ON u.id = r.founder_id WHERE r.name = ?`, name)) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return r, err +} + +// RegisterRoom registers a room to its founder, who is put on its access +// list with flags; ErrExists if it is registered already. +func (s *Store) RegisterRoom(name string, founder int64, flags, by string) error { + t := now() + _, err := s.db.Exec(`INSERT INTO room_reg (name, founder_id, registered, last_used) VALUES (?, ?, ?, ?)`, name, founder, t, t) + if isUnique(err) { + return ErrExists + } + if err != nil { + return err + } + _, _ = s.db.Exec(`DELETE FROM room_access WHERE room = ?`, name) // left over + return s.SetRoomAccess(name, founder, flags, by) +} + +// DropRoom unregisters a room, and empties its access list. +func (s *Store) DropRoom(name string) error { + if err := s.exec1(`DELETE FROM room_reg WHERE name = ?`, name); err != nil { + return err + } + _, err := s.db.Exec(`DELETE FROM room_access WHERE room = ?`, name) + return err +} + +// SetRoomFounder gives a registered room to another user. +func (s *Store) SetRoomFounder(name string, founder int64) error { + _, err := s.db.Exec(`UPDATE room_reg SET founder_id = ? WHERE name = ?`, founder, name) + return err +} + +// SetRoomSettings sets a registered room's settings (words). +func (s *Store) SetRoomSettings(name, settings string) error { + _, err := s.db.Exec(`UPDATE room_reg SET settings = ? WHERE name = ?`, settings, name) + return err +} + +// SetRoomText sets one of a registered room's texts: "descr", "url" or +// "entrymsg". +func (s *Store) SetRoomText(name, field, text string) error { + switch field { + case "descr", "url", "entrymsg": + default: + return ErrNotFound + } + _, err := s.db.Exec(`UPDATE room_reg SET `+field+` = ? WHERE name = ?`, text, name) + return err +} + +// SetRoomRegTopic sets a registered room's topic. +func (s *Store) SetRoomRegTopic(name, topic, by string) error { + _, err := s.db.Exec(`UPDATE room_reg SET topic = ?, topic_by = ?, topic_at = ? WHERE name = ?`, topic, by, now(), name) + return err +} + +// RoomUsed notes that a registered room was used now. +func (s *Store) RoomUsed(name string) error { + _, err := s.db.Exec(`UPDATE room_reg SET last_used = ? WHERE name = ?`, now(), name) + return err +} + +const roomAccessCols = `a.room, a.user_id, COALESCE(u.name, ''), a.flags, a.set_by, a.set_at` + +func (s *Store) roomAccessList(where string, args ...any) ([]*RoomAccess, error) { + rows, err := s.db.Query(`SELECT `+roomAccessCols+` FROM room_access a LEFT JOIN users u ON u.id = a.user_id WHERE `+where+` ORDER BY a.room, a.set_at, a.user_id`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []*RoomAccess + for rows.Next() { + var a RoomAccess + var at int64 + if err := rows.Scan(&a.Room, &a.UserID, &a.Name, &a.Flags, &a.SetBy, &at); err != nil { + return nil, err + } + a.SetAt = unix(at) + out = append(out, &a) + } + return out, rows.Err() +} + +// RoomAccessList is a registered room's access list, oldest first. +func (s *Store) RoomAccessList(name string) ([]*RoomAccess, error) { + return s.roomAccessList(`a.room = ?`, name) +} + +// RoomsOf are the access entries a user has, in every room. +func (s *Store) RoomsOf(user int64) ([]*RoomAccess, error) { + return s.roomAccessList(`a.user_id = ?`, user) +} + +// RoomFlags are a user's flags in a room ("": none). +func (s *Store) RoomFlags(name string, user int64) (string, error) { + var flags string + err := s.db.QueryRow(`SELECT flags FROM room_access WHERE room = ? AND user_id = ?`, name, user).Scan(&flags) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + return flags, err +} + +// SetRoomAccess sets a user's flags in a room ("": off the list). +func (s *Store) SetRoomAccess(name string, user int64, flags, by string) error { + if flags == "" { + _, err := s.db.Exec(`DELETE FROM room_access WHERE room = ? AND user_id = ?`, name, user) + return err + } + _, err := s.db.Exec(`INSERT INTO room_access (room, user_id, flags, set_by, set_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (room, user_id) DO UPDATE SET flags = excluded.flags, set_by = excluded.set_by, set_at = excluded.set_at`, + name, user, flags, by, now()) + return err +} + +// roomsGone takes a deleted user off the access lists. A room they +// founded goes to the oldest entry with F, else with f, else the oldest +// entry; with none left, it is dropped. +func (s *Store) roomsGone(user int64) error { + if _, err := s.db.Exec(`DELETE FROM room_access WHERE user_id = ?`, user); err != nil { + return err + } + var rooms []string + rows, err := s.db.Query(`SELECT name FROM room_reg WHERE founder_id = ?`, user) + if err != nil { + return err + } + for rows.Next() { + var n string + if err := rows.Scan(&n); err != nil { + rows.Close() + return err + } + rooms = append(rooms, n) + } + rows.Close() + for _, name := range rooms { + list, err := s.RoomAccessList(name) + if err != nil { + return err + } + var heir *RoomAccess + for _, want := range []string{"F", "f", ""} { + for _, a := range list { + if a.Name != "" && strings.Contains(a.Flags, want) { + heir = a + break + } + } + if heir != nil { + break + } + } + if heir == nil { + if err := s.DropRoom(name); err != nil { + return err + } + continue + } + if err := s.SetRoomFounder(name, heir.UserID); err != nil { + return err + } + } + return nil +} diff --git a/internal/store/schema.go b/internal/store/schema.go index 56a566a..665593d 100644 --- a/internal/store/schema.go +++ b/internal/store/schema.go @@ -113,6 +113,27 @@ CREATE TABLE IF NOT EXISTS chat_rooms ( created_by {str} NOT NULL DEFAULT '', created {int} NOT NULL )`, ` +CREATE TABLE IF NOT EXISTS room_reg ( + name {key} PRIMARY KEY, + founder_id {int} NOT NULL, + registered {int} NOT NULL, + last_used {int} NOT NULL DEFAULT 0, + settings {str} NOT NULL DEFAULT '', + descr {str} NOT NULL DEFAULT '', + url {str} NOT NULL DEFAULT '', + entrymsg {str} NOT NULL DEFAULT '', + topic {str} NOT NULL DEFAULT '', + topic_by {str} NOT NULL DEFAULT '', + topic_at {int} NOT NULL DEFAULT 0 +)`, ` +CREATE TABLE IF NOT EXISTS room_access ( + room {key} NOT NULL, + user_id {int} NOT NULL, + flags {str} NOT NULL DEFAULT '', + set_by {str} NOT NULL DEFAULT '', + set_at {int} NOT NULL, + PRIMARY KEY (room, user_id) +)`, ` CREATE TABLE IF NOT EXISTS qwk_msgs ( net {key} NOT NULL, number {int} NOT NULL, @@ -468,6 +489,7 @@ var indexes = []struct { {"chan_posts_ip", "chan_posts", "ip, created", false}, {"chan_reports_post", "chan_reports", "board_id, num", false}, {"chats_to", "chats", "to_id, delivered", false}, + {"room_access_user", "room_access", "user_id", false}, {"chats_pair", "chats", "from_id, to_id, id", false}, } diff --git a/internal/store/store.go b/internal/store/store.go index 7c96da3..f627a12 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -395,13 +395,16 @@ func (s *Store) SetLocked(id int64, locked bool) error { return s.exec1(`UPDATE users SET locked = ? WHERE id = ?`, locked, id) } -// DeleteUser removes an account and its mail; its messages stay. +// DeleteUser removes an account and its mail; its messages stay. Rooms +// it founded pass to another on their access lists. func (s *Store) DeleteUser(id int64) error { if err := s.exec1(`DELETE FROM users WHERE id = ?`, id); err != nil { return err } - _, err := s.db.Exec(`DELETE FROM script_data WHERE user_id = ?`, id) - return err + if _, err := s.db.Exec(`DELETE FROM script_data WHERE user_id = ?`, id); err != nil { + return err + } + return s.roomsGone(id) } // LoggedIn counts a login. diff --git a/internal/ymsg/im.go b/internal/ymsg/im.go index 6417cd2..f4a2aa1 100644 --- a/internal/ymsg/im.go +++ b/internal/ymsg/im.go @@ -15,6 +15,12 @@ import ( // its sender, a room's line to the chat room or conference it is, anything // else as an IM from the BBS. func (ss *session) event(e bbs.Event) { + if plain := bbs.Plain(e); plain != nil { // ops and kicks: as notices and leaving + for _, x := range plain { + ss.event(x) + } + return + } switch e.Kind { case bbs.Private: text := e.Text From ef1b9ef0354988db6909e44c3c38d62655c25fce Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 16:28:10 +0000 Subject: [PATCH 2/2] Quotes: TestAlpacaStream on a clock of its own The test's stream trades are Monday 2026-11-09's, and it took the session from the real clock: since that Monday's close the session reads closed, the last trade stands for the close, and the test failed (on main too). Alpaca takes a Now for its clock, and the test sets Monday before the open, so it passes whatever day it is run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRTXE7MNm3r3hHAmTG2 --- internal/quotes/alpaca.go | 15 +++++++++++++-- internal/quotes/alpaca_test.go | 5 ++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/internal/quotes/alpaca.go b/internal/quotes/alpaca.go index 48df5ee..0c34927 100644 --- a/internal/quotes/alpaca.go +++ b/internal/quotes/alpaca.go @@ -40,6 +40,9 @@ type Alpaca struct { StreamURL string // AlpacaStream if "" (the feed is added) DataURL string // AlpacaData if "" Log func(format string, args ...any) + // Now is the time, by which the session is open or over (nil: + // time.Now; a test's clock) + Now func() time.Time mu sync.Mutex wanted map[string]time.Time // when each symbol was last wanted @@ -49,6 +52,14 @@ type Alpaca struct { err error // the stream's last failure (nil: connected) } +// now is the time by a's clock. +func (a *Alpaca) now() time.Time { + if a.Now != nil { + return a.Now() + } + return time.Now() +} + func (a *Alpaca) init() { if a.wanted == nil { a.wanted, a.fetched, a.subbed = map[string]time.Time{}, map[string]time.Time{}, map[string]bool{} @@ -255,7 +266,7 @@ func (a *Alpaca) fetch(ctx context.Context, syms []string) error { if err := json.Unmarshal(body, &snaps); err != nil { return fmt.Errorf("Alpaca: %w", err) } - now := time.Now() + now := a.now() a.mu.Lock() for _, s := range syms { a.fetched[s] = now @@ -358,7 +369,7 @@ func (a *Alpaca) clock(ctx context.Context) { defer t.Stop() n := 0 for { - a.Book.Clock(time.Now()) + a.Book.Clock(a.now()) if n++; n%5 == 0 { var syms []string for s := range a.following() { diff --git a/internal/quotes/alpaca_test.go b/internal/quotes/alpaca_test.go index 6bf3d42..c28fb92 100644 --- a/internal/quotes/alpaca_test.go +++ b/internal/quotes/alpaca_test.go @@ -121,8 +121,11 @@ func TestAlpacaSnapshots(t *testing.T) { func TestAlpacaStream(t *testing.T) { srv, subs := fakeAlpaca(t) ws := "ws" + strings.TrimPrefix(srv.URL, "http") + "/v2/" + // Monday before the open, whenever the test is run: the session not + // over, so no close yet + monday := time.Date(2026, 11, 9, 9, 0, 0, 0, eastern) a := &Alpaca{Key: "KEY", Secret: "SECRET", Book: NewBook(nil), Pinned: []string{"AAPL"}, - DataURL: srv.URL + "/v2/", StreamURL: ws} + DataURL: srv.URL + "/v2/", StreamURL: ws, Now: func() time.Time { return monday }} ctx, cancel := context.WithCancel(context.Background()) defer cancel() go a.Run(ctx)