Merge pull request #19 from D-Modem/claude/project-thread-p2z3e6

Kept private chats and one friends list, for every front end
This commit is contained in:
Neo authored and GitHub committed 2026-11-08 12:15:12 -08:00
commit aa2453bef3
23 files changed
+1608 -94

No files matched your search

+22 -11
View File
@@ -49,14 +49,22 @@ could sign on by AIM as that user, as with any AIM server.
## Buddies
The buddy list holds BBS names (or ICQ numbers). A buddy is online while
they are on the BBS by any route, and shown away when they are away on
AIM or IRC. Their profile is the one their AIM client set, or for someone
not on AIM their line about themselves, their location and what they are
doing on which node. The list itself is kept on the server (AIM 5's and
ICQ 2001's "server-stored" list) or by the client (older ones); both work.
Permit and deny lists, "allow only buddies" and ICQ's invisible status
hide the user and refuse their IMs, from AIM users and others alike.
The buddy list is the user's [friends list](Chat-and-Paging#friends):
the same list the BBS's chat and IRC show, so a buddy is always a BBS
user (by name, or ICQ number). Adding anyone else is refused. A friend
added by IRC or the BBS comes to an AIM client that is on at once, in
their group (`Friends` if they have none); one added or removed on AIM
is on or off the list everywhere. Groups and aliases are kept with the
friends list; the list's other items (permit and deny entries,
preferences) as the client sent them. A client that keeps its own list
(AIM 3 and 4) has its buddies put on the friends list as it sends them.
A buddy is online while they are on the BBS by any route, and shown away
when they are away on AIM or IRC. Their profile is the one their AIM
client set, or for someone not on AIM their line about themselves, their
location and what they are doing on which node. Permit and deny lists,
"allow only buddies" and ICQ's invisible status hide the user and refuse
their IMs, from AIM users and others alike.
## IMs
@@ -64,9 +72,12 @@ An IM to a BBS user reaches every node they are on: an AIM or ICQ client
gets it as an IM (from AIM to AIM with its fonts and colours), an IRC client
as a `PRIVMSG`, a caller on a terminal as a message line. What they send
back comes as an IM from them. Typing notices, file transfers and direct
connections pass between AIM clients. An IM to someone not online is
refused as AIM refused them ("not logged on"); there are no offline
messages. The BBS's notices (new mail, a page for the sysop) come as IMs
connections pass between AIM clients. IMs are [kept](Chat-and-Paging#private-messages).
An IM to a BBS user who isn't on is kept for them, and the sender told so
(once) by `OnlineHost`; they get it when they next sign on: on AIM as an
IM marked with when it was sent, on ICQ as an offline message, on IRC or
a terminal as a message line. An IM to a name that is no BBS user's is
refused ("not logged on"). The BBS's notices (new mail, a page for the sysop) come as IMs
from `OnlineHost`.
## Chat rooms
+28 -7
View File
@@ -1,5 +1,6 @@
Callers on different nodes can talk to each other in three ways: in chat
rooms, by sending a message to one node, and by paging the sysop.
rooms, by private messages, and by paging the sysop. Each user also keeps
a [friends list](#friends).
## Chat rooms
@@ -16,7 +17,10 @@ last caller leaves, unless the sysop has made it
| `/who` | who is in this room |
| `/rooms` | the rooms in use, and who is in them |
| `/join ROOM` | go to another room (letters, digits and `-`, up to 20) |
| `/msg NODE TEXT` | a line to one node, wherever its caller is |
| `/msg WHO TEXT` | a private message to a user (or to a node, by its number), [kept](#private-messages) if they are away |
| `/history [WHO]` | those you have talked with, or your last lines with one |
| `/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 |
| `/topic [TEXT]` | the room's topic; the sysop sets a [permanent room](IRC#permanent-rooms)'s |
| `/quit` | leave the chat |
| `/help` | these |
@@ -35,13 +39,30 @@ with other BBSes. The rooms are also channels on the BBS's [IRC](IRC)
server (`#main` and the rest), with IRC clients in them alongside the
callers.
## Messages to a node
## Private messages
On the text BBS, *Who's online* ends by offering to send a line to a
node, and `/msg NODE TEXT` does the same from chat (on a 3270 too). The
line reaches the caller wherever they are: on the text BBS, at whatever
prompt they are at; on a 3270, on the message line of their next screen
(with `(+N)` when more are waiting).
node, and `/msg WHO TEXT` sends one from chat (on a 3270 too), to a user
by name or to a node by its number. The line reaches the caller
wherever they are: on the text BBS, at whatever prompt they are at; on a
3270, on the message line of their next screen (with `(+N)` when more
are waiting); on [IRC](IRC) as a `PRIVMSG`; on [AIM or ICQ](AIM-and-ICQ)
as an IM.
Private messages are kept, however they were sent: the BBS's chat, IRC,
AIM or ICQ. A message to a user who isn't on is kept for them, and they
get it when they next log in, with the time it was sent (an ICQ client
gets them as its offline messages). `/history WHO` (on IRC, `/msg
BBSServ HISTORY nick`) shows your last lines with someone. Only the two
users in a conversation can read it back.
## Friends
Every user has one friends list, of BBS users. It is the same list
everywhere: `/friends` in chat, `FRIENDS` to BBSServ on IRC, and the
buddy list on [AIM and ICQ](AIM-and-ICQ#buddies). A friend added on one
shows on the others; an AIM client that is on gets them at once, in
their group (`Friends` if they have none).
## Paging the sysop
+7 -1
View File
@@ -54,7 +54,7 @@ up to 20 at once. Joining shows the room's last 20 lines.
|---|---|
| `PRIVMSG #room :text` | a line in the room |
| `/me waves` (CTCP ACTION) | `* alice waves` |
| `PRIVMSG nick :text` | a message to that user's nodes |
| `PRIVMSG nick :text` | a message to that user's nodes; to one not on, [kept](Chat-and-Paging#private-messages) for them (`301` says so) |
| a caller's node message | a `PRIVMSG` to you |
| `NAMES`, `WHO`, `WHOIS` | who is in a room, on which node and how (`bob!telnet@node3`) |
| `LIST` | the rooms in use |
@@ -68,6 +68,10 @@ stripped from lines going into the rooms.
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.
Messages kept for you while you were away come as `PRIVMSG`s once you
log in, each with its time: as `server-time` if your client takes it,
otherwise at the start of the line.
The server offers the IRCv3 capabilities `sasl`, `server-time` (the time
of each line, the history replayed on join included), `echo-message`,
`multi-prefix` and `userhost-in-names`.
@@ -117,6 +121,8 @@ answers come as notices.
| `KEYS`, `KEYS ADD` *password key*, `KEYS DEL` *n* | your [SSH keys](SSH). Adding one asks for your password, since a key opens your account |
| `TOKENS`, `TOKENS REVOKE` *id* | your [HTTP API](HTTP-API) tokens |
| `ROOMS`; `ROOM ADD`\|`DEL`\|`TOPIC` *#room* | the [permanent rooms](#permanent-rooms); making them (the sysop) |
| `FRIENDS`, `FRIENDS ADD`\|`DEL` *nick* | your [friends list](Chat-and-Paging#friends), and who on it is on |
| `HISTORY`, `HISTORY` *nick* [*lines*] | those you have talked with; your last lines with one (50, up to 500) |
The same checks apply as on the BBS: an alias that is someone's name is
refused, and so is a setting's wrong value. A wrong password (`KEYS
+14 -11
View File
@@ -184,17 +184,19 @@ 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
relay Relay // a chat network's rooms (MRC)
geoMu sync.Mutex
geo *geoip.File
presMu sync.Mutex
presence map[int]func(name string, online bool) // WatchPresence's
presNext int
mu sync.Mutex
nodes map[int]*Node
failures map[string][]time.Time
hubOnce sync.Once
chat *hub
relay Relay // a chat network's rooms (MRC)
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.
@@ -674,6 +676,7 @@ func (n *Node) loggedIn(u *store.User, how string) (*store.User, error) {
return nil, err
}
n.SetUser(u)
n.DeliverKept()
n.startClock(u)
if err := n.b.Store.AddCall(&store.Call{UserID: u.ID, Name: u.Name, Location: u.Location,
Via: n.Caller.Via, Node: n.Num}); err != nil {
+4
View File
@@ -35,6 +35,7 @@ type Event struct {
Node int
Text string
Time time.Time
Kept bool // a private message kept while its caller was away
// the CB handle the sender goes by ("": none; From is still the
// user's name, for those that do not show handles)
Handle string
@@ -52,6 +53,9 @@ func (e Event) String() string {
case Left:
return "<- " + e.From + " left"
case Private:
if e.Kept {
return fmt.Sprintf("Message from %s (%s, while you were away): %s", e.From, e.Time.Format("Jan 2 15:04"), e.Text)
}
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
+76 -7
View File
@@ -12,7 +12,9 @@ var ChatHelp = []string{
"Type to talk. Commands:",
" /who who is in this room /rooms the rooms in use",
" /join ROOM go to another room /me ACTION * you do something",
" /msg NODE TEXT a message to one node /topic this room's topic",
" /msg WHO TEXT to a user, kept if away /topic this room's topic",
" /history [WHO] your talks with a user /friends your friends list",
" /friend WHO put one on your list /unfriend WHO take one off it",
" /quit leave the chat",
"Sysops: /pages callers paging /answer [NODE] answer one /busy pages on or off",
" /topic TEXT set a permanent room's topic",
@@ -87,16 +89,83 @@ func (n *Node) ChatCommand(line string) (out []string, leave bool, err error) {
out = append(out, e.String())
}
return append(out, "You are in "+n.Room()+"."), false, nil
case "msg", "m":
case "msg", "m", "tell":
to, text, _ := strings.Cut(arg, " ")
num, err := strconv.Atoi(to)
if err != nil {
return nil, false, fmt.Errorf("/msg NODE TEXT: a node's number first")
if to == "" {
return nil, false, fmt.Errorf("/msg WHO TEXT: a user's name (or a node's number), then the message")
}
if err := n.Message(num, text); err != nil {
if num, err := strconv.Atoi(to); err == nil {
if err := n.Message(num, text); err != nil {
return nil, false, err
}
if o := n.b.node(num); o != nil {
n.Keep(o.User(), text, true)
}
return []string{fmt.Sprintf("Sent to node %d.", num)}, false, nil
}
u, err := n.b.Store.UserByName(to)
if err != nil {
return nil, false, ErrNoUser
}
online, err := n.TellUser(u, text)
if err != nil {
return nil, false, err
}
return []string{fmt.Sprintf("Sent to node %d.", num)}, false, nil
if !online {
return []string{u.Name + " is away; they will have it when they next log in."}, false, nil
}
return []string{"Sent to " + u.Name + "."}, false, nil
case "history":
if arg == "" {
ps, err := n.Conversations()
if err != nil {
return nil, false, err
}
if len(ps) == 0 {
return []string{"You have no conversations yet (/msg WHO TEXT starts one)."}, false, nil
}
out = append(out, "Your conversations (/history WHO to read one):")
for _, p := range ps {
out = append(out, fmt.Sprintf(" %-20s %d lines, the last %s", p.Name, p.Lines, p.Last.Format("Jan 2 15:04")))
}
return out, false, nil
}
u, err := n.b.Store.UserByName(arg)
if err != nil {
return nil, false, ErrNoUser
}
cs, err := n.History(u, 50)
if err != nil {
return nil, false, err
}
if len(cs) == 0 {
return []string{"You and " + u.Name + " have not talked yet."}, false, nil
}
return HistoryLines(cs), false, nil
case "friends":
u := n.User()
if u == nil {
return nil, false, ErrNoUser
}
lines, err := n.b.FriendLines(u)
return lines, false, err
case "friend", "unfriend":
u := n.User()
if u == nil || arg == "" {
return nil, false, fmt.Errorf("/%s WHO: a user's name", strings.ToLower(cmd))
}
if strings.ToLower(cmd) == "friend" {
f, err := n.b.AddFriend(u, arg)
if err != nil {
return nil, false, err
}
return []string{f.Name + " is on your friends list."}, false, nil
}
f, err := n.b.RemoveFriend(u, arg)
if err != nil {
return nil, false, err
}
return []string{f.Name + " is off your friends list."}, false, nil
case "pages":
ps := n.b.Pages()
if len(ps) == 0 {
+256
View File
@@ -0,0 +1,256 @@
package bbs
import (
"errors"
"strings"
"github.com/D-Modem/bbs/internal/store"
)
// Private messages between users are kept, whatever way they come (IRC,
// AIM, ICQ, the BBS's chat): one away gets them on their next login, and
// either may read their conversation back.
// historyLines are the lines of a conversation History gives at most.
const historyLines = 500
// ErrNoUser: there is no user of that name.
var ErrNoUser = errors.New("there is no user of that name")
// Keep keeps a private line from the node's user to another (delivered:
// they had it, on some node).
func (n *Node) Keep(to *store.User, text string, delivered bool) {
from := n.User()
text = Clean(text, MaxChatLine)
if from == nil || to == nil || text == "" {
return
}
if _, err := n.b.Store.AddChat(&store.Chat{FromID: from.ID, From: from.Name, ToID: to.ID, To: to.Name,
Text: text, Delivered: delivered}); err != nil {
n.b.Log.Printf("node %d: keeping a message: %v", n.Num, err)
}
}
// nodesOfUser are the nodes a user is on.
func (b *BBS) nodesOfUser(id int64) []*Node {
b.mu.Lock()
defer b.mu.Unlock()
var out []*Node
for _, o := range b.nodes {
if o.user != nil && o.user.ID == id {
out = append(out, o)
}
}
return out
}
// TellUser sends a private line to a user: to each node they are on
// (besides this one), or, if they are on none, kept for them. Online: it
// went to them now.
func (n *Node) TellUser(to *store.User, text string) (online bool, err error) {
text = Clean(text, MaxChatLine)
if text == "" {
return false, errors.New("say something")
}
sent := false
var lastErr error
others := n.b.nodesOfUser(to.ID)
for _, o := range others {
if o == n {
continue
}
if err := n.Message(o.Num, text); err != nil {
lastErr = err
} else {
sent = true
}
}
if !sent && lastErr != nil {
return false, lastErr
}
if len(others) == 0 {
if n.flood() {
return false, ErrFlood
}
}
n.Keep(to, text, len(others) > 0)
return len(others) > 0, nil
}
// Kept takes the private lines kept for the node's user while they were
// away, as events, and marks them had.
func (n *Node) Kept() []Event {
u := n.User()
if u == nil {
return nil
}
cs, err := n.b.Store.KeptChats(u.ID)
if err != nil {
n.b.Log.Printf("node %d: kept messages: %v", n.Num, err)
return nil
}
if len(cs) == 0 {
return nil
}
ids := make([]int64, len(cs))
out := make([]Event, len(cs))
for i, c := range cs {
ids[i] = c.ID
out[i] = Event{Kind: Private, From: c.From, Text: c.Text, Time: c.Sent, Kept: true}
}
if err := n.b.Store.ChatsDelivered(ids); err != nil {
n.b.Log.Printf("node %d: kept messages: %v", n.Num, err)
}
return out
}
// DeliverKept gives the node the private lines kept for its user, as its
// events.
func (n *Node) DeliverKept() {
for _, e := range n.Kept() {
n.deliver(e)
}
}
// History is the node's user's conversation with another user, oldest
// first (at most limit lines; 0: as many as History gives).
func (n *Node) History(with *store.User, limit int) ([]store.Chat, error) {
u := n.User()
if u == nil {
return nil, ErrNoUser
}
if limit <= 0 || limit > historyLines {
limit = historyLines
}
return n.b.Store.ChatsBetween(u.ID, with.ID, limit)
}
// Conversations are those the node's user has talked with, the latest
// first.
func (n *Node) Conversations() ([]store.ChatPartner, error) {
u := n.User()
if u == nil {
return nil, ErrNoUser
}
return n.b.Store.ChatPartners(u.ID, 50)
}
// HistoryLines is a conversation as lines to show.
func HistoryLines(cs []store.Chat) []string {
out := make([]string, 0, len(cs))
day := ""
for _, c := range cs {
if d := c.Sent.Format("Monday, January 2, 2006"); d != day {
day = d
out = append(out, "-- "+d+" --")
}
out = append(out, c.Sent.Format("15:04")+" <"+c.From+"> "+c.Text)
}
return out
}
// Friends is a user's friends list.
func (b *BBS) Friends(u *store.User) ([]store.Friend, error) { return b.Store.Friends(u.ID) }
// AddFriend puts the user of that name on u's friends list; that user.
func (b *BBS) AddFriend(u *store.User, name string) (*store.User, error) {
f, err := b.Store.UserByName(strings.TrimSpace(name))
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, ErrNoUser
}
return nil, err
}
if f.ID == u.ID {
return nil, errors.New("you are always your own friend")
}
if ok, err := b.Store.IsFriend(u.ID, f.ID); err != nil {
return nil, err
} else if ok {
return f, nil
}
if err := b.Store.PutFriend(u.ID, store.Friend{ID: f.ID}); err != nil {
return nil, err
}
b.FriendsChanged(u.ID)
return f, nil
}
// RemoveFriend takes the user of that name off u's friends list; that
// user.
func (b *BBS) RemoveFriend(u *store.User, name string) (*store.User, error) {
f, err := b.Store.UserByName(strings.TrimSpace(name))
if err != nil {
if errors.Is(err, store.ErrNotFound) {
return nil, ErrNoUser
}
return nil, err
}
if ok, err := b.Store.IsFriend(u.ID, f.ID); err != nil {
return nil, err
} else if !ok {
return nil, errors.New(f.Name + " is not on your friends list")
}
if err := b.Store.RemoveFriend(u.ID, f.ID); err != nil {
return nil, err
}
b.FriendsChanged(u.ID)
return f, nil
}
// WatchFriends has fn told when a user's friends list changes, until the
// returned func is called. fn must not block.
func (b *BBS) WatchFriends(fn func(user int64)) (stop func()) {
b.presMu.Lock()
defer b.presMu.Unlock()
if b.friendFns == nil {
b.friendFns = map[int]func(int64){}
}
b.friendNext++
id := b.friendNext
b.friendFns[id] = fn
return func() {
b.presMu.Lock()
delete(b.friendFns, id)
b.presMu.Unlock()
}
}
// FriendsChanged tells the watchers that a user's friends list changed.
func (b *BBS) FriendsChanged(user int64) {
b.presMu.Lock()
fns := make([]func(int64), 0, len(b.friendFns))
for _, fn := range b.friendFns {
fns = append(fns, fn)
}
b.presMu.Unlock()
for _, fn := range fns {
fn(user)
}
}
// FriendLines are a user's friends as lines to show: who is on, and how.
func (b *BBS) FriendLines(u *store.User) ([]string, error) {
fs, err := b.Friends(u)
if err != nil {
return nil, err
}
if len(fs) == 0 {
return []string{"Your friends list is empty."}, nil
}
out := []string{"Your friends:"}
for _, f := range fs {
var on []string
for _, n := range b.Nodes() {
if strings.EqualFold(n.User, f.Name) {
on = append(on, n.Via)
}
}
state := "away"
if len(on) > 0 {
state = "on (" + strings.Join(on, ", ") + ")"
}
out = append(out, " "+f.Name+" "+state)
}
return out, nil
}
+106
View File
@@ -117,6 +117,28 @@ DEL lets it go when its last caller leaves. ROOM TOPIC sets its topic
maxParams: 3,
unsplitFinalParam: true,
}
svc.Commands["friends"] = &serviceCommand{
handler: bsFriends,
help: `Syntax: $bFRIENDS [ADD|DEL <nick>]$b
FRIENDS lists your friends list, and who on it is on now. FRIENDS ADD
puts a BBS user on it, FRIENDS DEL takes one off. It is the same list
on the BBS, and your buddy list on AIM and ICQ.`,
helpShort: "$bFRIENDS$b lists, adds and removes your friends.",
maxParams: 2,
}
svc.Commands["history"] = &serviceCommand{
handler: bsHistory,
help: `Syntax: $bHISTORY [nick] [lines]$b
Private messages are kept. HISTORY alone lists those you have talked
with; HISTORY <nick> shows your last lines with them (50, or as many
as you ask, up to 500). A message to someone not on is kept for them,
and they have it when they next log in.`,
helpShort: "$bHISTORY$b shows your private conversations.",
maxParams: 2,
}
svc.Commands["friend"] = &serviceCommand{aliasOf: "friends"}
svc.Commands["channel"] = &serviceCommand{aliasOf: "room"}
svc.Commands["channels"] = &serviceCommand{aliasOf: "rooms"}
svc.Commands["account"] = &serviceCommand{aliasOf: "info"}
@@ -492,3 +514,87 @@ func bsRoom(svc *service, c *client, _ string, params []string) {
svc.notice(c, capital(err.Error())+".")
}
}
// bsFriends is FRIENDS: the friends list, ADD and DEL.
func bsFriends(svc *service, c *client, _ string, params []string) {
b := c.s.B
if len(params) == 0 {
lines, err := b.FriendLines(c.u)
if err != nil {
svc.notice(c, capital(err.Error())+".")
return
}
for _, l := range lines {
svc.notice(c, l)
}
return
}
if len(params) < 2 {
svc.notice(c, fmt.Sprintf("FRIENDS ADD or DEL a nick: /msg %s HELP FRIENDS", svc.Name))
return
}
name := params[1]
if u := c.userOfNick(name); u != nil {
name = u.Name
}
switch strings.ToLower(params[0]) {
case "add":
f, err := b.AddFriend(c.u, name)
if err != nil {
svc.notice(c, capital(err.Error())+".")
return
}
svc.notice(c, Nick(f.Name)+" is on your friends list.")
case "del", "delete", "remove":
f, err := b.RemoveFriend(c.u, name)
if err != nil {
svc.notice(c, capital(err.Error())+".")
return
}
svc.notice(c, Nick(f.Name)+" is off your friends list.")
default:
svc.notice(c, fmt.Sprintf("FRIENDS ADD or DEL a nick: /msg %s HELP FRIENDS", svc.Name))
}
}
// bsHistory is HISTORY: those talked with, or the last lines with one.
func bsHistory(svc *service, c *client, _ string, params []string) {
if len(params) == 0 {
ps, err := c.n.Conversations()
if err != nil {
svc.notice(c, capital(err.Error())+".")
return
}
if len(ps) == 0 {
svc.notice(c, "You have no conversations yet.")
return
}
for _, p := range ps {
svc.notice(c, fmt.Sprintf("%-20s %d lines, the last %s", Nick(p.Name), p.Lines, p.Last.Format("Jan 2 15:04")))
}
return
}
u := c.userOfNick(params[0])
if u == nil {
svc.notice(c, "There is no user of that nick.")
return
}
limit := 50
if len(params) > 1 {
if n, err := strconv.Atoi(params[1]); err == nil && n > 0 {
limit = n
}
}
cs, err := c.n.History(u, limit)
if err != nil {
svc.notice(c, capital(err.Error())+".")
return
}
if len(cs) == 0 {
svc.notice(c, "You and "+Nick(u.Name)+" have not talked yet.")
return
}
for _, l := range bbs.HistoryLines(cs) {
svc.notice(c, l)
}
}
+1
View File
@@ -427,6 +427,7 @@ func (c *client) login() bool {
c.send(nil, asked+"!irc@"+c.s.S.ServerName, "NICK", c.nick)
}
c.welcome()
n.DeliverKept() // messages kept while they were away, with their times
return true
}
+54 -7
View File
@@ -11,6 +11,7 @@ import (
"github.com/ergochat/irc-go/ircmsg"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
)
// command handles a registered client's line.
@@ -264,6 +265,26 @@ func (c *client) nodesOf(nick string) []bbs.NodeInfo {
return out
}
// 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) {
return nil
}
if u, err := c.s.B.Store.UserByName(nick); err == nil {
return u
}
us, err := c.s.B.Store.Users()
if err != nil {
return nil
}
for _, u := range us {
if fold(Nick(u.Name)) == fold(nick) {
return u
}
}
return nil
}
// who is WHO: a channel's members (and the service, in a permanent room),
// or a nick's nodes.
func (c *client) who(mask string) {
@@ -446,15 +467,32 @@ func (c *client) privmsg(command, target, text string) {
return
}
ns := c.nodesOf(target)
if len(ns) == 0 {
if !notice {
c.reply(ERR_NOSUCHNICK, target, "No such nick")
}
return
}
if emote {
text = "* " + c.u.Name + " " + text
}
if len(ns) == 0 {
// a user away: kept for them
u := c.userOfNick(target)
if u == nil {
if !notice {
c.reply(ERR_NOSUCHNICK, target, "No such nick")
}
return
}
if _, err := c.n.TellUser(u, text); err != nil {
if !notice {
c.reply(ERR_CANNOTSENDTOCHAN, target, "Cannot send: "+err.Error())
}
return
}
if c.caps["echo-message"] {
c.send(map[string]string{"time": stamp(time.Now())}, c.source(), command, target, text)
}
if !notice {
c.reply(RPL_AWAY, Nick(u.Name), "Not on now; they will have your message when they next log in")
}
return
}
sent := false
var lastErr error
for _, o := range ns {
@@ -467,6 +505,11 @@ func (c *client) privmsg(command, target, text string) {
sent = true
}
}
if sent {
if u, err := c.s.B.Store.UserByName(ns[0].User); err == nil {
c.n.Keep(u, text, true)
}
}
switch {
case sent && c.caps["echo-message"], !sent && lastErr == nil:
// echoed, or to yourself with no other node: back it comes, as IRC
@@ -533,7 +576,11 @@ func (c *client) event(e bbs.Event) {
case bbs.Topic:
c.send(tags, c.s.svc.source(c), "TOPIC", "#"+e.Room, e.Text)
case bbs.Private:
c.send(tags, c.sourceOf(e.From, e.Node), "PRIVMSG", c.nick, e.Text)
text := e.Text
if e.Kept && !c.caps["server-time"] {
text = "[" + e.Time.Format("Jan 2 15:04") + "] " + text
}
c.send(tags, c.sourceOf(e.From, e.Node), "PRIVMSG", c.nick, text)
case bbs.Paged:
text := fmt.Sprintf("%s (node %d) is paging you", e.From, e.Node)
if e.Text != "" {
+61
View File
@@ -464,3 +464,64 @@ func TestRelayedLines(t *testing.T) {
e.b.RelayEvent(bbs.Event{Kind: bbs.Notice, Room: "mrc-lobby", Text: "- dave has arrived."})
c.expect(":irc.test NOTICE #mrc-lobby :- dave has arrived.")
}
// TestKeptMessages: a PRIVMSG to a user not on is kept (301 says so), and
// given them when they come, by IRC (its time as server-time) or the
// terminal; a terminal's /msg by name, and the conversation read back.
func TestKeptMessages(t *testing.T) {
e := start(t)
a := e.dial(t)
a.login("alice", "alice")
a.send("PRIVMSG bob :are you there?")
if l := a.expect(" 301 "); !strings.Contains(l, "bob") {
t.Errorf("301 %q", l)
}
a.send("PRIVMSG nobody :hello")
a.expect(" 401 ")
// bob comes on a terminal, then talks back by /msg and his name
bob := e.caller(t, "bob")
bob.DeliverKept()
waitEvent(t, bob, "Message from alice")
if out, _, err := bob.ChatCommand("/msg alice yes, here"); err != nil || len(out) != 1 || out[0] != "Sent to alice." {
t.Errorf("/msg %q %v", out, err)
}
a.expect("PRIVMSG alice :yes, here")
if out, _, _ := bob.ChatCommand("/history alice"); len(out) != 3 || !strings.HasSuffix(out[1], "<alice> are you there?") {
t.Errorf("/history %q", out)
}
// Carol Ann, on IRC later: a line kept for her has its time
a.send("PRIVMSG Carol_Ann :for later")
a.expect(" 301 ")
c := e.dial(t)
c.send("CAP REQ :server-time", "CAP END")
c.login("Carol Ann", "Carol_Ann")
if l := c.expect("PRIVMSG Carol_Ann :for later"); !strings.HasPrefix(l, "@time=") {
t.Errorf("kept line %q", l)
}
}
// TestFriends: BBSServ FRIENDS adds, lists (who is on) and removes; the
// terminal's /friends shows the same list.
func TestFriends(t *testing.T) {
e := start(t)
a := e.dial(t)
a.login("alice", "alice")
a.send("PRIVMSG BBSServ :FRIENDS ADD bob")
a.expect("bob is on your friends list")
a.send("PRIVMSG BBSServ :FRIENDS ADD nobody")
a.expect("There is no user of that name")
e.caller(t, "bob")
a.send("PRIVMSG BBSServ :FRIENDS")
a.expect("bob on (telnet)")
n := e.caller(t, "alice")
if out, _, _ := n.ChatCommand("/friends"); len(out) != 2 || !strings.Contains(out[1], "bob") {
t.Errorf("/friends %q", out)
}
a.send("PRIVMSG BBSServ :FRIENDS DEL bob")
a.expect("bob is off your friends list")
if out, _, _ := n.ChatCommand("/friends"); out[0] != "Your friends list is empty." {
t.Errorf("/friends after %q", out)
}
}
+5 -1
View File
@@ -12,7 +12,11 @@ import (
func (ss *session) event(e bbs.Event) {
switch e.Kind {
case bbs.Private:
ss.imFrom(e.From, e.Text)
text := e.Text
if e.Kept {
text = "(" + e.Time.Format("Jan 2 15:04") + ", while you were away) " + text
}
ss.imFrom(e.From, text)
return
case bbs.Said, bbs.Emoted, bbs.Joined, bbs.Left, bbs.Topic:
if c := ss.chatOf(e.Room); c != nil {
+394 -33
View File
@@ -1,6 +1,9 @@
package oscar
import (
"encoding/binary"
"sort"
"strings"
"time"
"github.com/D-Modem/bbs/internal/store"
@@ -54,9 +57,11 @@ func itemBytes(b *buf, it store.FeedbagItem) {
b.raw(it.Attrs)
}
// feedbag is family 0x13: the buddy list kept on the server (SSI).
// feedbag is family 0x13: the buddy list kept on the server (SSI). Its
// buddies are the user's friends list, kept by the BBS: BBS users alone;
// its groups, permit and deny lists and preferences are kept as the
// client sent them.
func (ss *session) feedbag(h snacHeader, r *rd) {
st := ss.s.B.Store
switch h.sub {
case 0x0002: // rights
var t tlvs
@@ -85,12 +90,15 @@ func (ss *session) feedbag(h snacHeader, r *rd) {
t.addU16(0x000c, 200)
ss.snac(0x0013, 0x0003, h.req, t.bytes())
case 0x0004, 0x0005: // the list (5: if changed since; it is sent anyway)
items, err := st.Feedbag(ss.u.ID)
items, err := ss.bag()
if err != nil {
ss.s.B.Log.Printf("node %d: the feedbag: %v", ss.n.Num, err)
ss.fail(0x0013, h.req, 0x0005)
return
}
ss.mu.Lock()
ss.items, ss.bagSent = items, true
ss.mu.Unlock()
ss.feedbagLoaded(items)
// a long list goes in pieces, all but the last flagged as such
const per = 150
@@ -145,39 +153,325 @@ func (ss *session) feedbag(h snacHeader, r *rd) {
}
}
// friendsGroup is the group friends go in when they have none of their
// own (added elsewhere: by IRC, the BBS), made if the list has none.
const friendsGroup = "Friends"
// bag is the user's feedbag as the client is to have it: the items it
// keeps, and the friends list as its buddies. Friends not yet in the
// list (added elsewhere), or moved to another group elsewhere, are put
// in their group first, made if need be.
func (ss *session) bag() ([]store.FeedbagItem, error) {
ss.s.bagMu.Lock()
defer ss.s.bagMu.Unlock()
st := ss.s.B.Store
stored, err := st.Feedbag(ss.u.ID)
if err != nil {
return nil, err
}
var items, old []store.FeedbagItem // old: buddies kept as items before the friends list was
for _, it := range stored {
if it.ClassID == fbBuddy {
old = append(old, it)
} else {
items = append(items, it)
}
}
groups := map[uint16]int{} // group id → its item's index
for i, it := range items {
if it.ClassID == fbGroup {
groups[it.GroupID] = i
}
}
groupName := func(gid uint16) string {
if i, ok := groups[gid]; ok && gid != 0 {
return items[i].Name
}
return ""
}
if len(old) > 0 {
for _, it := range old {
u := ss.s.resolve(it.Name)
if u == nil || u.ID == ss.u.ID {
continue
}
if ok, err := st.IsFriend(ss.u.ID, u.ID); err != nil {
return nil, err
} else if !ok {
if err := st.PutFriend(ss.u.ID, store.Friend{ID: u.ID, Group: groupName(it.GroupID), Alias: alias(it.Attrs)}); err != nil {
return nil, err
}
if err := st.PutOSCARBuddy(ss.u.ID, store.OSCARBuddy{FriendID: u.ID, SN: it.Name, GroupID: it.GroupID,
ItemID: it.ItemID, Attrs: it.Attrs}); err != nil {
return nil, err
}
}
}
if err := st.DeleteFeedbag(ss.u.ID, old); err != nil {
return nil, err
}
}
fs, err := st.Friends(ss.u.ID)
if err != nil {
return nil, err
}
places, err := st.OSCARBuddies(ss.u.ID)
if err != nil {
return nil, err
}
used := map[[2]uint16]bool{}
for _, it := range items {
used[[2]uint16{it.GroupID, it.ItemID}] = true
}
// friends with a place in their group keep it
var unplaced []store.Friend
for _, f := range fs {
p, ok := places[f.ID]
k := [2]uint16{p.GroupID, p.ItemID}
_, group := groups[p.GroupID]
if ok && group && p.GroupID != 0 && p.ItemID != 0 && !used[k] &&
(f.Group == "" || strings.EqualFold(groupName(p.GroupID), f.Group)) {
used[k] = true
} else {
unplaced = append(unplaced, f)
}
}
changed := map[uint16]bool{} // groups whose order changed
for _, f := range unplaced {
name := f.Group
if name == "" {
name = friendsGroup
}
gid := uint16(0)
for id := range groups {
if id != 0 && strings.EqualFold(groupName(id), name) {
gid = id
}
}
if gid == 0 {
gid = freeID(func(id uint16) bool { _, ok := groups[id]; return ok })
items = append(items, store.FeedbagItem{Name: name, GroupID: gid, ClassID: fbGroup})
groups[gid] = len(items) - 1
if _, ok := groups[0]; !ok { // the root, which lists the groups
items = append(items, store.FeedbagItem{ClassID: fbGroup})
groups[0] = len(items) - 1
}
root := &items[groups[0]]
root.Attrs = withChild(root.Attrs, gid)
changed[0] = true
}
iid := freeID(func(id uint16) bool { return used[[2]uint16{gid, id}] })
used[[2]uint16{gid, iid}] = true
g := &items[groups[gid]]
g.Attrs = withChild(g.Attrs, iid)
changed[gid] = true
p := places[f.ID]
p.FriendID, p.GroupID, p.ItemID = f.ID, gid, iid
if err := st.PutOSCARBuddy(ss.u.ID, p); err != nil {
return nil, err
}
places[f.ID] = p
}
if len(changed) > 0 {
var put []store.FeedbagItem
for gid := range changed {
put = append(put, items[groups[gid]])
}
if err := st.PutFeedbag(ss.u.ID, put); err != nil {
return nil, err
}
}
for _, f := range fs {
p := places[f.ID]
items = append(items, store.FeedbagItem{Name: ss.friendName(f, p.SN), GroupID: p.GroupID, ItemID: p.ItemID,
ClassID: fbBuddy, Attrs: withAlias(p.Attrs, f.Alias)})
}
sort.Slice(items, func(i, j int) bool {
if items[i].GroupID != items[j].GroupID {
return items[i].GroupID < items[j].GroupID
}
return items[i].ItemID < items[j].ItemID
})
return items, nil
}
// friendName is a friend as the client names them: as it wrote them (sn),
// or (added elsewhere, or renamed since) their ICQ number on ICQ, their
// name on AIM.
func (ss *session) friendName(f store.Friend, sn string) string {
if sn != "" && isUIN(sn) == ss.icq && (isUIN(sn) || ident(sn) == ident(f.Name)) {
return sn
}
if ss.icq {
return ss.s.uinOf(f.ID)
}
return f.Name
}
// alias is a buddy's alias (TLV 0x131), "" if none.
func alias(attrs []byte) string { return parseTLVs(attrs).str(0x0131) }
// withAlias is a buddy's TLVs with its alias as the friends list has it.
func withAlias(attrs []byte, a string) []byte {
if alias(attrs) == a {
return attrs
}
var out tlvs
for _, x := range parseTLVs(attrs) {
if x.t != 0x0131 {
out = append(out, x)
}
}
if a != "" {
out.addStr(0x0131, a)
}
return out.bytes()
}
// freeID is the least id from 1 that taken says is not.
func freeID(taken func(uint16) bool) uint16 {
for id := uint16(1); id < 0x7fff; id++ {
if !taken(id) {
return id
}
}
return 0x7fff
}
// withChild is a group's attributes with an item id added to its order
// (TLV 0xC8, the ids it holds).
func withChild(attrs []byte, id uint16) []byte {
var out tlvs
found := false
for _, x := range parseTLVs(attrs) {
if x.t == 0x00c8 && !found {
found = true
if !holds(x.v, id) {
x = tlv{0x00c8, binary.BigEndian.AppendUint16(append([]byte(nil), x.v...), id)}
}
}
out = append(out, x)
}
if !found {
out = append(out, tlv{0x00c8, binary.BigEndian.AppendUint16(nil, id)})
}
return out.bytes()
}
// holds reports whether a list of ids has id.
func holds(ids []byte, id uint16) bool {
for i := 0; i+1 < len(ids); i += 2 {
if binary.BigEndian.Uint16(ids[i:]) == id {
return true
}
}
return false
}
// changeItems adds, updates or deletes feedbag items: each one's status.
// A buddy is a friend: one not a BBS user is refused.
func (ss *session) changeItems(sub uint16, items []store.FeedbagItem) []uint16 {
st := ss.s.B.Store
have, err := st.Feedbag(ss.u.ID)
if err != nil {
codes := make([]uint16, len(items))
fail := func(err error) []uint16 {
ss.s.B.Log.Printf("node %d: the feedbag: %v", ss.n.Num, err)
codes := make([]uint16, len(items))
for i := range codes {
codes[i] = fbInvalid
}
return codes
}
exists := map[[2]uint16]bool{}
have, err := ss.bag()
if err != nil {
return fail(err)
}
places, err := st.OSCARBuddies(ss.u.ID)
if err != nil {
return fail(err)
}
exists := map[[2]uint16]store.FeedbagItem{}
for _, it := range have {
exists[[2]uint16{it.GroupID, it.ItemID}] = true
exists[[2]uint16{it.GroupID, it.ItemID}] = it
}
friendAt := map[[2]uint16]int64{}
friend := map[int64][2]uint16{}
for id, p := range places {
friendAt[[2]uint16{p.GroupID, p.ItemID}] = id
friend[id] = [2]uint16{p.GroupID, p.ItemID}
}
groupName := func(gid uint16) string {
if g, ok := exists[[2]uint16{gid, 0}]; ok && g.ClassID == fbGroup && gid != 0 {
return g.Name
}
return ""
}
codes := make([]uint16, len(items))
var put, del []store.FeedbagItem
friendsChanged := false
for i, it := range items {
k := [2]uint16{it.GroupID, it.ItemID}
was, ok := exists[k]
buddy := it.ClassID == fbBuddy || ok && was.ClassID == fbBuddy
switch {
case sub == 0x0008 && exists[k]:
case sub == 0x0008 && ok:
codes[i] = fbExists
case sub == 0x0008 && len(have)+len(put) >= maxFeedbag:
codes[i] = 0x000c // over the limit
case sub != 0x0008 && !exists[k]:
case sub != 0x0008 && !ok:
codes[i] = fbNotFound
case buddy && sub == 0x000a:
if id, ok := friendAt[k]; ok {
if err := st.RemoveFriend(ss.u.ID, id); err != nil {
return fail(err)
}
delete(friend, id)
friendsChanged = true
}
delete(exists, k)
case buddy:
u := ss.s.resolve(it.Name)
if u == nil || u.ID == ss.u.ID || it.ClassID != fbBuddy {
codes[i] = fbInvalid // not a BBS user: no buddy
continue
}
if at, ok := friend[u.ID]; ok && at != k {
codes[i] = fbExists // on the list already, elsewhere
continue
}
if id, ok := friendAt[k]; ok && id != u.ID {
if err := st.RemoveFriend(ss.u.ID, id); err != nil {
return fail(err)
}
delete(friend, id)
}
if err := st.PutFriend(ss.u.ID, store.Friend{ID: u.ID, Group: groupName(it.GroupID), Alias: alias(it.Attrs)}); err != nil {
return fail(err)
}
if err := st.PutOSCARBuddy(ss.u.ID, store.OSCARBuddy{FriendID: u.ID, SN: it.Name, GroupID: it.GroupID,
ItemID: it.ItemID, Attrs: it.Attrs}); err != nil {
return fail(err)
}
friend[u.ID], friendAt[k] = k, u.ID
exists[k] = it
friendsChanged = true
case sub == 0x000a:
del = append(del, it)
delete(exists, k)
default:
if sub == 0x0009 && it.ClassID == fbGroup && it.GroupID != 0 && it.Name != was.Name {
// a group renamed: its friends' group is
for id, at := range friend {
if at[0] == it.GroupID {
if f, err := ss.friendOf(id); err == nil {
f.Group = it.Name
if err := st.PutFriend(ss.u.ID, f); err != nil {
return fail(err)
}
friendsChanged = true
}
}
}
}
put = append(put, it)
exists[k] = true
exists[k] = it
}
}
if len(put) > 0 {
@@ -187,35 +481,102 @@ func (ss *session) changeItems(sub uint16, items []store.FeedbagItem) []uint16 {
err = st.DeleteFeedbag(ss.u.ID, del)
}
if err != nil {
ss.s.B.Log.Printf("node %d: the feedbag: %v", ss.n.Num, err)
for i := range codes {
codes[i] = fbInvalid
}
return codes
return fail(err)
}
if now, err := st.Feedbag(ss.u.ID); err == nil {
if now, err := ss.bag(); err == nil {
ss.mu.Lock()
ss.items = now
ss.mu.Unlock()
ss.feedbagLoaded(now)
}
// the user's other sessions are told of the change
for _, o := range ss.s.sessionsOf(ss.u.ID) {
if o == ss {
continue
}
var b buf
for _, it := range items {
itemBytes(&b, it)
}
o.do(func() {
o.snac(0x0013, sub, 0, b)
if now, err := st.Feedbag(o.u.ID); err == nil {
o.feedbagLoaded(now)
}
})
if friendsChanged {
ss.s.B.FriendsChanged(ss.u.ID) // the user's other sessions, and the rest of the BBS
} else {
ss.s.friendsChanged(ss.u.ID)
}
ss.s.changed(ss.u)
return codes
}
// friendOf is the entry of one on the user's friends list.
func (ss *session) friendOf(id int64) (store.Friend, error) {
fs, err := ss.s.B.Store.Friends(ss.u.ID)
if err != nil {
return store.Friend{}, err
}
for _, f := range fs {
if f.ID == id {
return f, nil
}
}
return store.Friend{}, store.ErrNotFound
}
// friendsChanged has each session of the user bring its client's buddy
// list up to date.
func (s *Server) friendsChanged(user int64) {
for _, o := range s.all() {
if o.u.ID == user {
o.do(o.syncBag)
}
}
}
// syncBag sends the client what changed in its feedbag since it last had
// it (deleted, added, then updated items), and watches its buddies anew.
func (ss *session) syncBag() {
now, err := ss.bag()
if err != nil {
ss.s.B.Log.Printf("node %d: the feedbag: %v", ss.n.Num, err)
return
}
ss.mu.Lock()
old, sent := ss.items, ss.bagSent
if sent {
ss.items = now
}
ss.mu.Unlock()
if sent {
key := func(it store.FeedbagItem) [2]uint16 { return [2]uint16{it.GroupID, it.ItemID} }
was := map[[2]uint16]store.FeedbagItem{}
for _, it := range old {
was[key(it)] = it
}
is := map[[2]uint16]bool{}
var add, upd, del buf
for _, it := range now {
is[key(it)] = true
o, ok := was[key(it)]
switch {
case !ok:
itemBytes(&add, it)
case o.Name != it.Name || o.ClassID != it.ClassID || string(o.Attrs) != string(it.Attrs):
itemBytes(&upd, it)
}
}
for _, it := range old {
if !is[key(it)] {
itemBytes(&del, it)
}
}
if len(del)+len(add)+len(upd) > 0 {
ss.snac(0x0013, 0x0011, 0, nil)
for _, x := range []struct {
sub uint16
b buf
}{{0x000a, del}, {0x0008, add}, {0x0009, upd}} {
if len(x.b) > 0 {
ss.snac(0x0013, x.sub, 0, x.b)
}
}
ss.snac(0x0013, 0x0012, 0, nil)
}
ss.feedbagLoaded(now)
return
}
ss.rewatch() // a client with its own list: the friends watched
}
// feedbagLoaded takes the buddies and privacy of the list, and watches
// the buddies.
func (ss *session) feedbagLoaded(items []store.FeedbagItem) {
+30 -5
View File
@@ -37,7 +37,7 @@ func (ss *session) icbm(h snacHeader, r *rd) {
ss.fail(0x0004, h.req, icbmRefused)
case 0x000b: // the client's error or auto answer, for the sender
ss.relayToSender(h, r, 0x000b)
case 0x0010: // offline messages: none kept
case 0x0010: // offline messages: given as IMs once the client is ready
ss.snac(0x0004, 0x0017, h.req, nil)
case 0x0014: // typing
ss.relayToSender(h, r, 0x0014)
@@ -181,13 +181,32 @@ func (ss *session) deliver(u *store.User, ck []byte, raw string, isHTML, auto bo
return errOffline
}
}
nodes := ss.s.nodesOf(u.Name)
if len(nodes) == 0 {
return errOffline
}
if auto {
plain = "(auto reply) " + plain
}
nodes := ss.s.nodesOf(u.Name)
if len(nodes) == 0 {
if auto {
return nil // an auto reply is not kept
}
// kept for them, and the sender told so (once)
if err := ss.n.Throttle(); err != nil {
return err
}
ss.n.Keep(u, plain, false)
ss.mu.Lock()
noted := ss.noted[u.ID]
ss.noted[u.ID] = true
ss.mu.Unlock()
if !noted {
from := ss.systemName()
name := u.Name
ss.do(func() {
ss.imFrom(from, name+" is not on now; they will have your messages when they next sign on.")
})
}
return nil
}
native := false
var lastErr error
sent := false
@@ -224,6 +243,12 @@ func (ss *session) deliver(u *store.User, ck []byte, raw string, isHTML, auto bo
if native {
ss.s.B.Log.Printf("node %d: %s sent an IM to %s", ss.n.Num, ss.u.Name, u.Name)
}
if sent && !auto {
ss.n.Keep(u, plain, true)
ss.mu.Lock()
delete(ss.noted, u.ID)
ss.mu.Unlock()
}
if !sent && lastErr != nil {
return lastErr
}
+38 -4
View File
@@ -12,6 +12,7 @@ import (
// length, the client's UIN, a type, a sequence number, the request.
const (
icqOfflineReq = 0x003c
icqOfflineMsg = 0x0041
icqOfflineDone = 0x0042
icqOfflineAck = 0x003e
icqMetaReq = 0x07d0
@@ -48,7 +49,7 @@ func (r *lrd) str() string {
return strings.TrimRight(decodeText(r.take(int(r.u16())), csASCII), "\x00")
}
// icqMeta is family 0x15: offline messages (none are kept), and the
// icqMeta is family 0x15: offline messages (those kept), and the
// directory: users' info and searches.
func (ss *session) icqMeta(h snacHeader, r *rd) {
if h.sub != 0x0002 {
@@ -69,9 +70,7 @@ func (ss *session) icqMeta(h snacHeader, r *rd) {
}
switch kind {
case icqOfflineReq:
var b le
b.u8(0) // none dropped
ss.icqReply(h.req, icqOfflineDone, seq, b, false)
ss.icqOffline(h.req, seq)
case icqOfflineAck:
case icqMetaReq:
sub := q.u16()
@@ -79,6 +78,41 @@ func (ss *session) icqMeta(h snacHeader, r *rd) {
}
}
// icqOffline sends the messages kept while the user was away, each with
// its sender and time (GMT), then that there are no more.
func (ss *session) icqOffline(req uint32, seq uint16) {
st := ss.s.B.Store
cs, err := st.KeptChats(ss.u.ID)
if err != nil {
ss.s.B.Log.Printf("node %d: kept messages: %v", ss.n.Num, err)
}
ids := make([]int64, 0, len(cs))
for _, c := range cs {
if o, err := st.UserByID(c.FromID); err == nil && ss.blocks(o) {
continue // kept back: they are blocked
}
t := c.Sent.UTC()
var b le
b.u32(uint32(ss.s.S.UINBase) + uint32(c.FromID))
b.u16(uint16(t.Year()))
b.u8(byte(t.Month()))
b.u8(byte(t.Day()))
b.u8(byte(t.Hour()))
b.u8(byte(t.Minute()))
b.u8(0x01) // a text message
b.u8(0) // flags
b.str(c.Text)
ss.icqReply(req, icqOfflineMsg, seq, b, true)
ids = append(ids, c.ID)
}
if err := st.ChatsDelivered(ids); err != nil {
ss.s.B.Log.Printf("node %d: kept messages: %v", ss.n.Num, err)
}
var b le
b.u8(0) // none dropped
ss.icqReply(req, icqOfflineDone, seq, b, false)
}
// icqReply sends a reply of kind (with its sequence number) to the
// client; more: more replies follow.
func (ss *session) icqReply(req uint32, kind, seq uint16, body []byte, more bool) {
+149 -2
View File
@@ -8,6 +8,7 @@ import (
"log"
"net"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
@@ -418,10 +419,14 @@ func TestAIMToIRC(t *testing.T) {
t.Errorf("alice got %q %q", from, text)
}
// offline, and unknown: not logged on
// one away: the IM is kept, and alice told so; one unknown: not logged on
alice.sendIM("sysop", "anyone?", false)
if from, text := alice.recvIM(); from != "OnlineHost" || !strings.Contains(text, "sysop is not on now") {
t.Errorf("alice told %q %q", from, text)
}
alice.sendIM("nobody", "anyone?", false)
if r := (&rd{p: alice.expect(0x04, 0x01)}); r.u16() != icbmNotLoggedOn {
t.Error("no error to an offline user")
t.Error("no error to an unknown user")
}
// bob goes: alice is told
@@ -658,3 +663,145 @@ func TestP3(t *testing.T) {
t.Fatal("not given to P3")
}
}
// TestKeptIMs: IMs and PRIVMSGs to one away are kept, and given them when
// they come: on AIM as IMs after the client is ready, on ICQ as offline
// messages, on IRC as PRIVMSGs with their times; the conversation is
// there to read back by IRC.
func TestKeptIMs(t *testing.T) {
e := start(t)
host, ck, _ := login(t, e.addr, "alice", "password1", true)
alice := bos(t, host, ck)
alice.sendIM("bob", "<HTML>are you there?</HTML>", false)
alice.recvIM() // the note that bob is away
carol := ircLogin(t, e.ircAddr, "Carol Ann")
carol.send("PRIVMSG bob :hi from IRC")
if l := carol.expect(" 301 "); !strings.Contains(l, "next log in") {
t.Errorf("carol told %q", l)
}
// bob comes by AIM: both, as IMs, after his client is ready
host, ck, _ = login(t, e.addr, "bob", "password1", true)
bob := bos(t, host, ck)
got := map[string]string{}
for range 2 {
from, text := bob.recvIM()
got[from] = text
}
if !strings.Contains(got["alice"], "while you were away) are you there?") {
t.Errorf("from alice %q", got["alice"])
}
if !strings.Contains(got["CarolAnn"], "hi from IRC") && !strings.Contains(got["Carol Ann"], "hi from IRC") {
t.Errorf("from carol %v", got)
}
// read back, by IRC
carol.send("PRIVMSG BBSServ :HISTORY bob")
if l := carol.expect("<Carol Ann> hi from IRC"); !strings.Contains(l, "NOTICE") {
t.Errorf("history %q", l)
}
// ICQ: an offline message, with its sender and time
bob.c.Close()
for i := 0; len(e.srv.nodesOf("bob")) > 0; i++ {
if i > 300 {
t.Fatal("bob never went")
}
time.Sleep(10 * time.Millisecond)
}
alice.sendIM("bob", "for ICQ", true)
alice.expect(0x04, 0x0c) // kept; alice was told once already
bobU, _ := e.b.Store.UserByName("bob")
aliceU, _ := e.b.Store.UserByName("alice")
uin := e.srv.uinOf(bobU.ID)
host, ck, _ = roastedLogin(t, e.addr, uin, "password1")
icq := bos(t, host, ck)
var q le
q.u16(0)
q.u32(e.srv.S.UINBase + uint32(bobU.ID))
q.u16(icqOfflineReq)
q.u16(2)
binary.LittleEndian.PutUint16(q, uint16(len(q)-2))
var t1 tlvs
t1.add(0x0001, q)
icq.send(0x15, 0x02, t1.bytes())
v, _ := parseTLVs(icq.expect(0x15, 0x03)).get(0x0001)
r := &lrd{rd{p: v}}
r.u16()
r.u32()
if k := r.u16(); k != icqOfflineMsg {
t.Fatalf("kind %x", k)
}
r.u16()
if from := r.u32(); from != e.srv.S.UINBase+uint32(aliceU.ID) {
t.Errorf("from %d", from)
}
if y := r.u16(); y != uint16(time.Now().UTC().Year()) {
t.Errorf("year %d", y)
}
r.take(4)
r.take(2)
if text := r.str(); text != "for ICQ" {
t.Errorf("text %q", text)
}
v, _ = parseTLVs(icq.expect(0x15, 0x03)).get(0x0001)
r = &lrd{rd{p: v}}
r.u16()
r.u32()
if k := r.u16(); k != icqOfflineDone {
t.Errorf("then %x", k)
}
if cs, _ := e.b.Store.KeptChats(bobU.ID); len(cs) != 0 {
t.Errorf("still kept: %v", cs)
}
}
// TestFriendsList: the server-stored buddy list is the friends list: a
// buddy not a BBS user is refused, one added from IRC comes to the AIM
// client in a Friends group, one deleted by AIM is off the list.
func TestFriendsList(t *testing.T) {
e := start(t)
host, ck, _ := login(t, e.addr, "alice", "password1", true)
alice := bos(t, host, ck)
alice.send(0x13, 0x04, nil)
alice.expect(0x13, 0x06)
var b buf
itemBytes(&b, store.FeedbagItem{Name: "nobody", GroupID: 1, ItemID: 9, ClassID: fbBuddy})
alice.send(0x13, 0x08, b)
if c := alice.expect(0x13, 0x0e); !bytes.Equal(c, []byte{0, fbInvalid}) {
t.Errorf("a buddy not a user: %x", c)
}
ic := ircLogin(t, e.ircAddr, "alice")
ic.send("PRIVMSG BBSServ :FRIENDS ADD Carol_Ann")
ic.expect("is on your friends list")
alice.expect(0x13, 0x11)
add := &rd{p: alice.expect(0x13, 0x08)}
var names []string
var carolItem store.FeedbagItem
for _, it := range readItems(add) {
names = append(names, it.Name)
if it.ClassID == fbBuddy {
carolItem = it
}
}
if carolItem.Name != "Carol Ann" || !slices.Contains(names, "Friends") {
t.Fatalf("added %q", names)
}
aliceU, _ := e.b.Store.UserByName("alice")
if fs, _ := e.b.Store.Friends(aliceU.ID); len(fs) != 1 || fs[0].Name != "Carol Ann" {
t.Fatalf("friends %v", fs)
}
var d buf
itemBytes(&d, carolItem)
alice.send(0x13, 0x0a, d)
if c := alice.expect(0x13, 0x0e); !bytes.Equal(c, []byte{0, fbOK}) {
t.Errorf("delete: %x", c)
}
if fs, _ := e.b.Store.Friends(aliceU.ID); len(fs) != 0 {
t.Errorf("friends after: %v", fs)
}
ic.send("PRIVMSG BBSServ :FRIENDS")
ic.expect("Your friends list is empty")
}
+48
View File
@@ -252,6 +252,14 @@ func (ss *session) rewatch() {
watch[u.ID] = sn
}
}
// and the friends list, however the client keeps its list
if fs, err := ss.s.B.Store.Friends(ss.u.ID); err == nil {
for _, f := range fs {
if _, ok := watch[f.ID]; !ok {
watch[f.ID] = ss.friendName(f, "")
}
}
}
ss.mu.Lock()
var added []int64
for id := range watch {
@@ -278,25 +286,65 @@ func (ss *session) buddy(h snacHeader, r *rd) {
t.addU16(0x0004, 160)
ss.snac(0x0003, 0x0003, h.req, t.bytes())
case 0x0004, 0x0005:
var sns []string
ss.mu.Lock()
for r.left() > 0 {
sn := r.str8()
if r.bad || sn == "" {
break
}
sns = append(sns, sn)
if h.sub == 0x0004 {
ss.listed[ident(sn)] = sn
} else {
delete(ss.listed, ident(sn))
}
}
ssi := ss.bagSent
ss.mu.Unlock()
if !ssi {
// a client that keeps its own list: that list is the friends list
ss.listFriends(sns, h.sub == 0x0004)
}
ss.do(ss.rewatch)
default:
ss.fail(0x0003, h.req, 0x0008)
}
}
// listFriends puts the BBS users of a client's own buddy list on the
// friends list (add), or takes them off.
func (ss *session) listFriends(sns []string, add bool) {
st := ss.s.B.Store
changed := false
for _, sn := range sns {
u := ss.s.resolve(sn)
if u == nil || u.ID == ss.u.ID {
continue
}
ok, err := st.IsFriend(ss.u.ID, u.ID)
switch {
case err != nil:
ss.s.B.Log.Printf("node %d: the friends list: %v", ss.n.Num, err)
return
case add && !ok:
err = st.PutFriend(ss.u.ID, store.Friend{ID: u.ID})
case !add && ok:
err = st.RemoveFriend(ss.u.ID, u.ID)
default:
continue
}
if err != nil {
ss.s.B.Log.Printf("node %d: the friends list: %v", ss.n.Num, err)
return
}
changed = true
}
if changed {
ss.s.B.FriendsChanged(ss.u.ID)
}
}
// permitDeny is family 9: the client-side permit and deny lists.
func (ss *session) permitDeny(h snacHeader, r *rd) {
switch h.sub {
+3
View File
@@ -68,6 +68,7 @@ type Server struct {
sessions map[*session]bool
byNode map[int]*session
cookies map[string]*cookie
bagMu sync.Mutex // placing friends in buddy lists
}
// New checks the settings and makes the server.
@@ -107,6 +108,8 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
s.B.Store.SetKeepOSCAR(true)
stop := s.B.WatchPresence(s.presence)
defer stop()
stopFriends := s.B.WatchFriends(s.friendsChanged)
defer stopFriends()
ts := &tcpserv.Server{Name: "oscar", MaxClients: s.S.MaxClients, MaxPerIP: s.S.MaxPerIP, Log: s.B.Log,
Handle: s.handle,
Refuse: func(c net.Conn) bool { return s.B.Refuse("oscar", c.RemoteAddr()) }}
+23 -4
View File
@@ -52,7 +52,10 @@ type session struct {
pdMode byte // permit/deny mode (1 all ... 5 buddies only)
permit map[string]bool
deny map[string]bool
bagOn bool // the feedbag is in use
bagOn bool // the feedbag is in use
items []store.FeedbagItem // the feedbag as the client last had it
bagSent bool // the client asked for the feedbag
noted map[int64]bool // told that these are away (their IMs kept)
chats map[*chatConn]bool
nav []*flapConn // service connections without rooms (chat nav)
}
@@ -91,7 +94,7 @@ func (s *Server) bos(fc *flapConn, host string, k *cookie) {
signon: time.Now(), todo: make(chan func(), queueLen), done: make(chan struct{}),
versions: map[uint16]uint16{}, listed: map[string]string{}, bagged: map[string]string{},
watch: map[int64]string{}, permit: map[string]bool{}, deny: map[string]bool{},
pdMode: pdPermitAll, chats: map[*chatConn]bool{}}
pdMode: pdPermitAll, chats: map[*chatConn]bool{}, noted: map[int64]bool{}}
n, err := s.B.Enter(&bbs.Caller{Via: via, Listener: "oscar", Remote: host, Source: "ip:" + host,
Terminal: k.clientID}, ss.close)
if err != nil {
@@ -212,9 +215,10 @@ func (ss *session) events() {
case f := <-ss.todo:
f()
case <-ss.n.Wake():
for _, e := range ss.n.Pending() {
ss.event(e)
if !ss.ready() {
continue // held until the client is ready (online drains them)
}
ss.drain()
}
}
}
@@ -364,9 +368,24 @@ func (ss *session) online() {
ss.mu.Unlock()
ss.n.Doing(ss.doing())
ss.do(ss.allArrived)
ss.do(ss.drain)
if !ss.icq { // ICQ asks for its offline messages itself
ss.do(func() {
for _, e := range ss.n.Kept() {
ss.event(e)
}
})
}
ss.s.changed(ss.u)
}
// drain gives the client the node's events waiting.
func (ss *session) drain() {
for _, e := range ss.n.Pending() {
ss.event(e)
}
}
// doing is what who's online says of the session.
func (ss *session) doing() string {
ss.mu.Lock()
+122
View File
@@ -0,0 +1,122 @@
package store
import (
"strings"
"time"
)
// Chat is a private line one user sent another, kept: by IRC, AIM, ICQ
// or the BBS's own chat. Delivered: the one it was to has had it.
type Chat struct {
ID int64
FromID int64
From string
ToID int64
To string
Text string
Sent time.Time
Delivered bool
}
const chatCols = `id, from_id, from_name, to_id, to_name, body, created, delivered`
func scanChats(rows interface {
Next() bool
Scan(...any) error
Err() error
}) ([]Chat, error) {
var out []Chat
for rows.Next() {
var c Chat
var at int64
if err := rows.Scan(&c.ID, &c.FromID, &c.From, &c.ToID, &c.To, &c.Text, &at, &c.Delivered); err != nil {
return nil, err
}
c.Sent = unix(at)
out = append(out, c)
}
return out, rows.Err()
}
// AddChat keeps a line; its id.
func (s *Store) AddChat(c *Chat) (int64, error) {
at := c.Sent
if at.IsZero() {
at = time.Now()
}
return s.db.insertID(`INSERT INTO chats (from_id, from_name, to_id, to_name, body, created, delivered)
VALUES (?, ?, ?, ?, ?, ?, ?)`, c.FromID, c.From, c.ToID, c.To, c.Text, at.Unix(), c.Delivered)
}
// KeptChats are the lines to a user they have not had yet, oldest first.
func (s *Store) KeptChats(to int64) ([]Chat, error) {
rows, err := s.db.Query(`SELECT `+chatCols+` FROM chats WHERE to_id = ? AND delivered = FALSE ORDER BY id`, to)
if err != nil {
return nil, err
}
defer rows.Close()
return scanChats(rows)
}
// ChatsDelivered marks lines as had.
func (s *Store) ChatsDelivered(ids []int64) error {
if len(ids) == 0 {
return nil
}
args := make([]any, len(ids))
for i, id := range ids {
args[i] = id
}
_, err := s.db.Exec(`UPDATE chats SET delivered = TRUE WHERE id IN (?`+strings.Repeat(", ?", len(ids)-1)+`)`, args...)
return err
}
// ChatsBetween are the last lines (at most limit) between two users, either
// way, oldest first.
func (s *Store) ChatsBetween(a, b int64, limit int) ([]Chat, error) {
rows, err := s.db.Query(`SELECT `+chatCols+` FROM chats WHERE (from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?)
ORDER BY id DESC LIMIT ?`, a, b, b, a, limit)
if err != nil {
return nil, err
}
defer rows.Close()
cs, err := scanChats(rows)
for i, j := 0, len(cs)-1; i < j; i, j = i+1, j-1 {
cs[i], cs[j] = cs[j], cs[i]
}
return cs, err
}
// ChatPartner is one a user has talked with: their last line's time, and
// how many lines there are.
type ChatPartner struct {
ID int64
Name string
Last time.Time
Lines int
}
// ChatPartners are those a user has talked with, the latest first (at most
// limit).
func (s *Store) ChatPartners(user int64, limit int) ([]ChatPartner, error) {
rows, err := s.db.Query(`SELECT p.other, u.name, MAX(p.created), COUNT(*) FROM
(SELECT to_id AS other, created FROM chats WHERE from_id = ?
UNION ALL SELECT from_id AS other, created FROM chats WHERE to_id = ?) p
JOIN users u ON u.id = p.other
GROUP BY p.other, u.name ORDER BY MAX(p.created) DESC LIMIT ?`, user, user, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []ChatPartner
for rows.Next() {
var p ChatPartner
var at int64
if err := rows.Scan(&p.ID, &p.Name, &at, &p.Lines); err != nil {
return nil, err
}
p.Last = unix(at)
out = append(out, p)
}
return out, rows.Err()
}
+1 -1
View File
@@ -13,7 +13,7 @@ import (
// copyOrder is the tables in an order their references allow.
var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "file_areas", "files",
"history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs",
"chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys"}
"chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys", "chats", "friends", "oscar_buddies"}
var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`)
+137
View File
@@ -0,0 +1,137 @@
package store
import (
"time"
)
// Friend is one of the BBS users on a user's friends list: the one list
// every front end shows as its own (AIM and ICQ's buddy list, IRC's,
// the BBS's). Group and Alias are the user's own, for lists that have
// them ("": none).
type Friend struct {
ID int64 // the friend's user id
Name string // their name (read)
Group string
Alias string
Added time.Time
}
// Friends is a user's friends list, by name.
func (s *Store) Friends(user int64) ([]Friend, error) {
rows, err := s.db.Query(`SELECT f.friend_id, u.name, f.grp, f.alias, f.added
FROM friends f JOIN users u ON u.id = f.friend_id WHERE f.user_id = ? ORDER BY u.name`, user)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Friend
for rows.Next() {
var f Friend
var at int64
if err := rows.Scan(&f.ID, &f.Name, &f.Group, &f.Alias, &at); err != nil {
return nil, err
}
f.Added = unix(at)
out = append(out, f)
}
return out, rows.Err()
}
// IsFriend reports whether friend is on user's list.
func (s *Store) IsFriend(user, friend int64) (bool, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM friends WHERE user_id = ? AND friend_id = ?`, user, friend).Scan(&n)
return n > 0, err
}
// PutFriend adds a friend to a user's list, or sets their group and alias.
func (s *Store) PutFriend(user int64, f Friend) error {
t, err := s.db.Begin()
if err != nil {
return err
}
defer t.Rollback()
var n int
if err := t.QueryRow(`SELECT COUNT(*) FROM friends WHERE user_id = ? AND friend_id = ?`, user, f.ID).Scan(&n); err != nil {
return err
}
if n > 0 {
_, err = t.Exec(`UPDATE friends SET grp = ?, alias = ? WHERE user_id = ? AND friend_id = ?`, f.Group, f.Alias, user, f.ID)
} else {
_, err = t.Exec(`INSERT INTO friends (user_id, friend_id, grp, alias, added) VALUES (?, ?, ?, ?, ?)`,
user, f.ID, f.Group, f.Alias, now())
}
if err != nil {
return err
}
return t.Commit()
}
// RemoveFriend takes a friend off a user's list (and its place in any
// front end's list).
func (s *Store) RemoveFriend(user, friend int64) error {
t, err := s.db.Begin()
if err != nil {
return err
}
defer t.Rollback()
for _, q := range []string{`DELETE FROM friends WHERE user_id = ? AND friend_id = ?`,
`DELETE FROM oscar_buddies WHERE user_id = ? AND friend_id = ?`} {
if _, err := t.Exec(q, user, friend); err != nil {
return err
}
}
return t.Commit()
}
// OSCARBuddy is a friend's place in a user's AIM/ICQ buddy list: the name
// as the client wrote it, its group and item ids, its TLVs.
type OSCARBuddy struct {
FriendID int64
SN string
GroupID uint16
ItemID uint16
Attrs []byte
}
// OSCARBuddies are the places of a user's friends in their buddy list, by
// friend.
func (s *Store) OSCARBuddies(user int64) (map[int64]OSCARBuddy, error) {
rows, err := s.db.Query(`SELECT friend_id, sn, group_id, item_id, attrs FROM oscar_buddies WHERE user_id = ?`, user)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[int64]OSCARBuddy{}
for rows.Next() {
var b OSCARBuddy
var g, i int64
if err := rows.Scan(&b.FriendID, &b.SN, &g, &i, &b.Attrs); err != nil {
return nil, err
}
b.GroupID, b.ItemID = uint16(g), uint16(i)
out[b.FriendID] = b
}
return out, rows.Err()
}
// PutOSCARBuddy records a friend's place in a user's buddy list.
func (s *Store) PutOSCARBuddy(user int64, b OSCARBuddy) error {
t, err := s.db.Begin()
if err != nil {
return err
}
defer t.Rollback()
attrs := b.Attrs
if attrs == nil {
attrs = []byte{}
}
if _, err := t.Exec(`DELETE FROM oscar_buddies WHERE user_id = ? AND friend_id = ?`, user, b.FriendID); err != nil {
return err
}
if _, err := t.Exec(`INSERT INTO oscar_buddies (user_id, friend_id, sn, group_id, item_id, attrs) VALUES (?, ?, ?, ?, ?, ?)`,
user, b.FriendID, b.SN, int64(b.GroupID), int64(b.ItemID), attrs); err != nil {
return err
}
return t.Commit()
}
+29
View File
@@ -248,6 +248,33 @@ CREATE TABLE IF NOT EXISTS feedbag (
attrs {blob},
PRIMARY KEY (user_id, group_id, item_id)
)`, `
CREATE TABLE IF NOT EXISTS chats (
id {id},
from_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
from_name {str} NOT NULL,
to_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
to_name {str} NOT NULL,
body {text} NOT NULL,
created {int} NOT NULL,
delivered {bool} NOT NULL DEFAULT FALSE
)`, `
CREATE TABLE IF NOT EXISTS friends (
user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
friend_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
grp {str} NOT NULL DEFAULT '',
alias {str} NOT NULL DEFAULT '',
added {int} NOT NULL,
PRIMARY KEY (user_id, friend_id)
)`, `
CREATE TABLE IF NOT EXISTS oscar_buddies (
user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
friend_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
sn {str} NOT NULL,
group_id {int} NOT NULL,
item_id {int} NOT NULL,
attrs {blob},
PRIMARY KEY (user_id, friend_id)
)`, `
CREATE TABLE IF NOT EXISTS chan_boards (
id {id},
dir {name} NOT NULL UNIQUE,
@@ -365,6 +392,8 @@ var indexes = []struct {
{"chan_posts_md5", "chan_posts", "board_id, md5", false},
{"chan_posts_ip", "chan_posts", "ip, created", false},
{"chan_reports_post", "chan_reports", "board_id, num", false},
{"chats_to", "chats", "to_id, delivered", false},
{"chats_pair", "chats", "from_id, to_id, id", false},
}
// added are the columns added since the first schema: an older database