mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Merge main into the AOL host branch (beside MSN Messenger)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRRm1WrfJdB863kw36V
This commit is contained in:
30 files changed
+3518
-11
No files matched your search
@@ -31,7 +31,7 @@ Main menu
|
||||
|
||||
- Message areas, private mail, chat, paging and doors (DOS doors in dosemu2, or Linux programs)
|
||||
- File areas with X/Y/ZMODEM, Kermit, IND$FILE and FTP
|
||||
- Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC, AIM and ICQ, and MRC
|
||||
- Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC, AIM and ICQ, MSN Messenger, and MRC
|
||||
- Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics
|
||||
- On the web: a forum, image boards, a web terminal and an HTTP API
|
||||
- SQLite, PostgreSQL, MySQL or MariaDB
|
||||
|
||||
@@ -680,6 +680,28 @@ address = 127.0.0.1:2513
|
||||
;max_clients = 256
|
||||
;max_per_ip = 4
|
||||
|
||||
; MSN Messenger: the chat for MSN Messenger 1.0 to 4.7 and Windows
|
||||
; Messenger 4.x (MSNP2 to 7), beside IRC and AIM. Users sign in as
|
||||
; name@domain with their BBS passwords; contacts are their friends list;
|
||||
; an IM is a private message (a PRIVMSG on IRC), kept for one away. The
|
||||
; clients must be pointed at this host (see the wiki page).
|
||||
; See docs/wiki/MSN-Messenger.md
|
||||
;[msn]
|
||||
;address = :1863
|
||||
; where clients are sent for conversations, host:port (default: the
|
||||
; address each one came to; set it behind NAT)
|
||||
;host = msn.example.org:1863
|
||||
; handles are name@domain (default bbs.invalid); clients may sign in with
|
||||
; any domain, as MSN 1.0's @hotmail.com
|
||||
;domain = msn.example.org
|
||||
;max_clients = 256
|
||||
; each conversation is a connection of its own
|
||||
;max_per_ip = 16
|
||||
; the name the BBS's notices come from
|
||||
;system = BBS
|
||||
; a web address the clients' links (inbox, profiles) open
|
||||
;site = https://bbs.example.org/
|
||||
|
||||
; Multi Relay Chat: the BBSes' chat network. Its rooms are the chat rooms
|
||||
; beginning mrc- here (mrc-lobby is its lobby), on terminals and IRC alike.
|
||||
; See docs/wiki/MRC.md
|
||||
|
||||
@@ -72,6 +72,7 @@ import (
|
||||
"github.com/D-Modem/bbs/internal/imageboard"
|
||||
"github.com/D-Modem/bbs/internal/ircd"
|
||||
"github.com/D-Modem/bbs/internal/mrc"
|
||||
"github.com/D-Modem/bbs/internal/msn"
|
||||
"github.com/D-Modem/bbs/internal/news"
|
||||
"github.com/D-Modem/bbs/internal/nntp"
|
||||
"github.com/D-Modem/bbs/internal/oscar"
|
||||
@@ -274,6 +275,9 @@ func main() {
|
||||
if a := cfg.AOL; a != nil {
|
||||
fmt.Printf("aol: %q\n", a.Address)
|
||||
}
|
||||
if m := cfg.MSN; m != nil {
|
||||
fmt.Printf("msn: %q, conversations at %q, handles @%s\n", m.Address, m.Host, m.Domain)
|
||||
}
|
||||
if cfg.Finger != nil {
|
||||
fmt.Printf("finger: %s (online %v, users %v)\n", cfg.Finger.Address, cfg.Finger.Online, cfg.Finger.Users)
|
||||
}
|
||||
@@ -499,6 +503,19 @@ func serve(cfg *server.Config, path string) int {
|
||||
}
|
||||
}()
|
||||
}
|
||||
if cfg.MSN != nil {
|
||||
msrv, err := msn.New(b, *cfg.MSN)
|
||||
if err != nil {
|
||||
lg.Printf("%v", err)
|
||||
return 1
|
||||
}
|
||||
go func() {
|
||||
if err := msrv.Run(ctx); err != nil {
|
||||
lg.Printf("%v", err)
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
}
|
||||
if cfg.Finger != nil {
|
||||
fs := &finger.Server{B: b, S: *cfg.Finger}
|
||||
go func() {
|
||||
|
||||
@@ -21,6 +21,7 @@ last caller leaves, unless the sysop has made it
|
||||
| `/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 |
|
||||
| `/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 |
|
||||
| `/quit` | leave the chat |
|
||||
| `/help` | these |
|
||||
@@ -47,10 +48,10 @@ 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.
|
||||
or [MSN](MSN-Messenger) 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
|
||||
AIM, ICQ or MSN. 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
|
||||
@@ -60,9 +61,18 @@ users in a conversation can read it back.
|
||||
|
||||
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).
|
||||
buddy list on [AIM and ICQ](AIM-and-ICQ#buddies), the contact list on
|
||||
[MSN](MSN-Messenger#contacts). A friend added on one shows on the others;
|
||||
an AIM or MSN client that is on gets them at once, in their group
|
||||
(`Friends` on AIM if they have none).
|
||||
|
||||
## Blocking
|
||||
|
||||
Every user also has one blocked list. `/block WHO` puts a user on it
|
||||
(and `/unblock WHO` takes them off), as does MSN's "Block". A blocked
|
||||
user's private messages are refused, however they send them (chat, IRC,
|
||||
AIM, MSN) and whether or not you are on, and MSN shows you offline to
|
||||
them.
|
||||
|
||||
## Paging the sysop
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ the file is laid out.
|
||||
| [`[irc]`](#irc) | IRC: the chat rooms as channels (#main ...), for IRC clients. |
|
||||
| [`[oscar]`](#oscar) | AIM and ICQ: the chat for AIM and ICQ clients (OSCAR), beside IRC. |
|
||||
| [`[aol]`](#aol) | AOL: a host for AOL's own clients (3.0, 4.0 and on, over TCP). |
|
||||
| [`[msn]`](#msn) | MSN Messenger: the chat for MSN Messenger 1.0 to 4.7 and Windows Messenger 4.x (MSNP2 to 7), beside IRC and AIM. |
|
||||
| [`[mrc]`](#mrc) | Multi Relay Chat: the BBSes' chat network. |
|
||||
| [`[finger]`](#finger) | finger: who is on ("finger @host"), and who a user is ("finger name@host"). |
|
||||
| [`[gopher]`](#gopher) | gopher: about the system, who is on, and what areas the sysop opens: no login, so anyone sees them. |
|
||||
@@ -461,6 +462,21 @@ AOL: a host for AOL's own clients (3.0, 4.0 and on, over TCP). Users sign on wi
|
||||
| `max_per_ip` | | | See the section above. Examples: `4`. |
|
||||
|
||||
|
||||
## `[msn]`
|
||||
|
||||
MSN Messenger: the chat for MSN Messenger 1.0 to 4.7 and Windows Messenger 4.x (MSNP2 to 7), beside IRC and AIM. Users sign in as name@domain with their BBS passwords; contacts are their friends list; an IM is a private message (a PRIVMSG on IRC), kept for one away. The clients must be pointed at this host (see the wiki page). See docs/wiki/MSN-Messenger.md.
|
||||
|
||||
| key | default | live | what it does |
|
||||
|---|---|---|---|
|
||||
| `address` | | | See the section above. Examples: `:1863`. |
|
||||
| `host` | | | where clients are sent for conversations, host:port (default: the address each one came to; set it behind NAT) Examples: `msn.example.org:1863`. |
|
||||
| `domain` | | | handles are name@domain (default bbs.invalid); clients may sign in with any domain, as MSN 1.0's @hotmail.com. Examples: `msn.example.org`. |
|
||||
| `max_clients` | | | handles are name@domain (default bbs.invalid); clients may sign in with any domain, as MSN 1.0's @hotmail.com. Examples: `256`. |
|
||||
| `max_per_ip` | | | each conversation is a connection of its own. Examples: `16`. |
|
||||
| `system` | | | the name the BBS's notices come from. Examples: `BBS`. |
|
||||
| `site` | | | a web address the clients' links (inbox, profiles) open. Examples: `https://bbs.example.org/`. |
|
||||
|
||||
|
||||
## `[mrc]`
|
||||
|
||||
Multi Relay Chat: the BBSes' chat network. Its rooms are the chat rooms beginning mrc- here (mrc-lobby is its lobby), on terminals and IRC alike. See docs/wiki/MRC.md.
|
||||
|
||||
+3
-1
@@ -79,7 +79,8 @@ which is generated from `bbs.conf.sample`.
|
||||
- [Newsgroups](Newsgroups-and-NNTP) served by NNTP and exchanged with other
|
||||
news servers
|
||||
- [IRC](IRC), where the chat rooms are channels, [AIM and ICQ](AIM-and-ICQ)
|
||||
for AIM and ICQ clients on the same chat, and [MRC](MRC), the chat
|
||||
for AIM and ICQ clients on the same chat, [MSN Messenger](MSN-Messenger)
|
||||
for MSN clients, and [MRC](MRC), the chat
|
||||
network shared with other BBSes
|
||||
- [Finger and gopher](Finger-and-Gopher)
|
||||
|
||||
@@ -136,6 +137,7 @@ which is generated from `bbs.conf.sample`.
|
||||
| [IRC](IRC) | the IRC server, with the chat rooms as channels |
|
||||
| [AIM and ICQ](AIM-and-ICQ) | the OSCAR server: AIM and ICQ clients, buddies, IMs and chat rooms |
|
||||
| [AOL clients](AOL) | a host for AOL's own clients (3.0, 4.0): sign-on with BBS accounts |
|
||||
| [MSN Messenger](MSN-Messenger) | the MSN server: MSN Messenger 1.0 to 4.7, contacts and IMs |
|
||||
| [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes |
|
||||
| [Finger and gopher](Finger-and-Gopher) | who is on, and the BBS in gopherspace |
|
||||
| [Web forum](Web-Forum) | the message areas as a web forum |
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
The BBS has an MSN Messenger server (MSNP, the protocol of Microsoft's
|
||||
MSN Messenger), beside its [IRC](IRC) and [AIM](AIM-and-ICQ) servers and
|
||||
on the same chat. Someone signed in with MSN Messenger 1.0 to 4.7 or
|
||||
Windows Messenger 4.x sees their BBS friends as contacts and IMs anyone on
|
||||
the BBS: other MSN users, IRC and AIM users, and callers on telnet, SSH,
|
||||
3270s and the web terminal.
|
||||
|
||||
```ini
|
||||
[msn]
|
||||
address = :1863
|
||||
host = msn.example.org:1863
|
||||
domain = msn.example.org
|
||||
```
|
||||
|
||||
| Setting | Default | What it sets |
|
||||
|---|---|---|
|
||||
| `address` | `:1863` | where to listen |
|
||||
| `host` | the address each client came to | where clients are sent for conversations (`host:port`); set it behind NAT |
|
||||
| `domain` | `bbs.invalid` | users' handles are `name@domain` |
|
||||
| `max_clients` | `256` | connections at once |
|
||||
| `max_per_ip` | `16` | from one address (each conversation is a connection) |
|
||||
| `system` | `BBS` | the name the BBS's notices come from |
|
||||
| `site` | none | a web address the client's links (inbox, profiles) open |
|
||||
|
||||
One port serves the whole of it: sign-in, the contact list and presence
|
||||
(the "notification server"), and the conversations ("switchboards").
|
||||
|
||||
## Versions served
|
||||
|
||||
MSNP2 to MSNP7: MSN Messenger 1.0 to 4.7, Windows Messenger 4.0 to 4.7,
|
||||
and third-party clients that speak those versions. They sign in by MD5
|
||||
(MSN 1.0 by the password itself) over plain TCP. MSN Messenger 5.0 and
|
||||
later, and Windows Live Messenger, sign in by Passport over HTTPS, which
|
||||
is not served yet: they are told the version is not supported, and the
|
||||
log says so.
|
||||
|
||||
## Pointing a client at the BBS
|
||||
|
||||
The clients were made for Microsoft's servers, so each must be pointed
|
||||
at the BBS:
|
||||
|
||||
- MSN Messenger 1.0 to 4.7: the `Server` value (a string) under
|
||||
`HKEY_CURRENT_USER\Software\Microsoft\MessengerService` in the
|
||||
registry, set to the BBS's host (with `:1863` if the port is another).
|
||||
A hosts file entry sending `messenger.hotmail.com` to the BBS may also
|
||||
work. Neither has been tried with the real clients yet.
|
||||
- Third-party clients (aMSN, Miranda, Trillian and others) take a server
|
||||
and port in the account's settings.
|
||||
|
||||
The deny list and bans in `[security]` apply as they do everywhere else.
|
||||
|
||||
## Signing in
|
||||
|
||||
Every MSN user is a BBS user. They sign in with `name@domain` as the
|
||||
e-mail address (a name with spaces may be typed with or without them,
|
||||
`CarolAnn@msn.example.org`) and their BBS password. The domain part is not
|
||||
checked, so a client that insists on `@hotmail.com` (MSN 1.0) works too.
|
||||
Failed sign-ins count towards the throttle and the hack log, like any
|
||||
other login, and the user's access level must allow chat. One account is
|
||||
signed in on one MSN client at a time: signing in again signs the older
|
||||
one out.
|
||||
|
||||
MSN clients send the password as an MD5 digest, which the BBS's password
|
||||
hashes can't check. So the BBS keeps each account's MSN digest too, made
|
||||
whenever the password is known: when the account is made, when its
|
||||
password is set, and at any login by password. An account from before
|
||||
`[msn]` was set up has none yet: its user logs in once some other way
|
||||
(telnet, SSH, IRC, AIM, the web) and can then sign in with MSN. The log
|
||||
says so when that is why a sign-in failed. The digest is kept only while
|
||||
`[msn]` is set up. MSN's challenge for an account is the same each time,
|
||||
as it was on Microsoft's servers, so anyone who saw a sign-in on the wire
|
||||
(or read the digest from the database) could sign in by MSN as that
|
||||
user. The connection is not encrypted.
|
||||
|
||||
## Contacts
|
||||
|
||||
The contact list is the user's [friends list](Chat-and-Paging#friends),
|
||||
the same list the BBS's chat, IRC and AIM show, with its groups (MSN
|
||||
Messenger 4.6 and later show them). A contact is always a BBS user;
|
||||
adding anyone else is refused. A friend added elsewhere comes to a
|
||||
client that is on at once, and one added or removed on MSN is on or off
|
||||
the list everywhere. Someone who adds an MSN user is on their reverse
|
||||
list, so the client asks "X has added you to their contact list".
|
||||
|
||||
The block list is the user's [blocked list](Chat-and-Paging#blocking),
|
||||
shared with the chat's `/block`: a blocked user's messages are refused
|
||||
however they come, and the user appears offline to them. "Only people on
|
||||
my Allow List can see my status" shows the user offline to those not on
|
||||
their friends list.
|
||||
|
||||
A contact is online while they are on the BBS by any route: with the
|
||||
status their MSN client set (busy, away, appearing offline...), or plain
|
||||
online on any other route.
|
||||
|
||||
## Conversations
|
||||
|
||||
An IM to an MSN user opens a conversation on their client as usual. An
|
||||
IM to a BBS user on another route puts them in the conversation at once:
|
||||
what is said reaches them as a private message (a `PRIVMSG` on IRC, an
|
||||
IM on AIM, a message line on a terminal), and what they send back comes
|
||||
into it. A private message from someone not on MSN opens a conversation
|
||||
with them on the client. Conversations of several MSN users work as they
|
||||
did on Microsoft's servers; typing notices and invitations pass between
|
||||
MSN clients, not to other routes.
|
||||
|
||||
Every line is [kept](Chat-and-Paging#private-messages). One to a user who
|
||||
isn't on is kept for them, and the sender told so (once); they get it
|
||||
when they next log in. Lines kept for an MSN user come when they sign in,
|
||||
in a conversation from each sender, marked with when they were sent. The
|
||||
BBS's notices (new mail, a page for the sysop) come from the `system`
|
||||
name. Calling someone who is offline is refused, as on Microsoft's
|
||||
servers: to leave a message for them, use their conversation while it is
|
||||
open, or another route.
|
||||
@@ -35,6 +35,7 @@
|
||||
- [IRC](IRC)
|
||||
- [AIM and ICQ](AIM-and-ICQ)
|
||||
- [AOL clients](AOL)
|
||||
- [MSN Messenger](MSN-Messenger)
|
||||
- [MRC](MRC)
|
||||
- [Finger and gopher](Finger-and-Gopher)
|
||||
- [Web forum](Web-Forum)
|
||||
|
||||
@@ -624,6 +624,7 @@ func (b *BBS) menuLogin(who, name, pw string) (*store.User, error) {
|
||||
b.Log.Printf("%s: %s's password by modemmenu (%s)", who, u.Name, backend)
|
||||
b.Store.KeepOSCARKeys(u.ID, pw) // for AIM's digest logins, if kept
|
||||
b.Store.KeepCISKey(u.ID, pw) // and CompuServe's
|
||||
b.Store.KeepMSNKey(u.ID, pw) // and MSN's
|
||||
return u, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -528,6 +528,9 @@ func (n *Node) Message(to int, text string) error {
|
||||
if o == nil || o.User() == nil || o == n {
|
||||
return ErrNoNode
|
||||
}
|
||||
if from := n.User(); from != nil && n.b.Blocks(o.User(), from) {
|
||||
return ErrBlocked
|
||||
}
|
||||
if n.flood() {
|
||||
return ErrFlood
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ var ChatHelp = []string{
|
||||
" /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",
|
||||
" /block WHO stop their messages /unblock WHO let them again",
|
||||
" /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",
|
||||
@@ -166,6 +167,23 @@ func (n *Node) ChatCommand(line string) (out []string, leave bool, err error) {
|
||||
return nil, false, err
|
||||
}
|
||||
return []string{f.Name + " is off your friends list."}, false, nil
|
||||
case "block", "unblock":
|
||||
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) == "block" {
|
||||
f, err := n.b.Block(u, arg)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return []string{f.Name + " is blocked: you will not get their messages."}, false, nil
|
||||
}
|
||||
f, err := n.b.Unblock(u, arg)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return []string{f.Name + " is no longer blocked."}, false, nil
|
||||
case "pages":
|
||||
ps := n.b.Pages()
|
||||
if len(ps) == 0 {
|
||||
|
||||
+65
-2
@@ -17,6 +17,9 @@ const historyLines = 500
|
||||
// ErrNoUser: there is no user of that name.
|
||||
var ErrNoUser = errors.New("there is no user of that name")
|
||||
|
||||
// ErrBlocked: the user blocks the sender.
|
||||
var ErrBlocked = errors.New("that user is not taking your messages")
|
||||
|
||||
// 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) {
|
||||
@@ -52,6 +55,9 @@ func (n *Node) TellUser(to *store.User, text string) (online bool, err error) {
|
||||
if text == "" {
|
||||
return false, errors.New("say something")
|
||||
}
|
||||
if from := n.User(); from != nil && n.b.Blocks(to, from) {
|
||||
return false, ErrBlocked
|
||||
}
|
||||
sent := false
|
||||
var lastErr error
|
||||
others := n.b.nodesOfUser(to.ID)
|
||||
@@ -198,8 +204,65 @@ func (b *BBS) RemoveFriend(u *store.User, name string) (*store.User, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// WatchFriends has fn told when a user's friends list changes, until the
|
||||
// returned func is called. fn must not block.
|
||||
// Blocks reports whether u blocks other.
|
||||
func (b *BBS) Blocks(u, other *store.User) bool {
|
||||
ok, err := b.Store.IsBlocked(u.ID, other.ID)
|
||||
if err != nil {
|
||||
b.Log.Printf("blocked list of %s: %v", u.Name, err)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// Blocked is a user's blocked list.
|
||||
func (b *BBS) Blocked(u *store.User) ([]store.Friend, error) { return b.Store.Blocked(u.ID) }
|
||||
|
||||
// Block puts the user of that name on u's blocked list (they can no
|
||||
// longer send u private messages, nor see u online where a front end
|
||||
// shows it); that user.
|
||||
func (b *BBS) Block(u *store.User, name string) (*store.User, error) {
|
||||
f, err := b.userNamed(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.ID == u.ID {
|
||||
return nil, errors.New("you cannot block yourself")
|
||||
}
|
||||
if err := b.Store.Block(u.ID, f.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.FriendsChanged(u.ID)
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Unblock takes the user of that name off u's blocked list; that user.
|
||||
func (b *BBS) Unblock(u *store.User, name string) (*store.User, error) {
|
||||
f, err := b.userNamed(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok, err := b.Store.IsBlocked(u.ID, f.ID); err != nil {
|
||||
return nil, err
|
||||
} else if !ok {
|
||||
return nil, errors.New(f.Name + " is not on your blocked list")
|
||||
}
|
||||
if err := b.Store.Unblock(u.ID, f.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.FriendsChanged(u.ID)
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// userNamed is the user of that name (ErrNoUser: none).
|
||||
func (b *BBS) userNamed(name string) (*store.User, error) {
|
||||
f, err := b.Store.UserByName(strings.TrimSpace(name))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, ErrNoUser
|
||||
}
|
||||
return f, err
|
||||
}
|
||||
|
||||
// WatchFriends has fn told when a user's friends list (or blocked 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()
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
)
|
||||
|
||||
// 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) {
|
||||
switch e.Kind {
|
||||
case bbs.Private:
|
||||
text := e.Text
|
||||
if e.Kept {
|
||||
text = "(" + e.Time.Format("Jan 2 15:04") + ", while you were away) " + text
|
||||
}
|
||||
u, err := ns.s.B.Store.UserByName(e.From)
|
||||
if err != nil {
|
||||
ns.s.deliverFrom(ns, nil, e.From+": "+text)
|
||||
return
|
||||
}
|
||||
if ns.s.B.Blocks(ns.u, u) {
|
||||
return
|
||||
}
|
||||
ns.s.deliverFrom(ns, u, text)
|
||||
return
|
||||
case bbs.Said, bbs.Emoted, bbs.Joined, bbs.Left, bbs.Topic:
|
||||
return // no rooms on MSN
|
||||
case bbs.Paged:
|
||||
text := fmt.Sprintf("%s (node %d) is paging you", e.From, e.Node)
|
||||
if e.Text != "" {
|
||||
text += ": " + e.Text
|
||||
}
|
||||
ns.s.deliverFrom(ns, nil, text+fmt.Sprintf(" (join the chat room sysop-%d to answer)", e.Node))
|
||||
return
|
||||
}
|
||||
ns.s.deliverFrom(ns, nil, e.String())
|
||||
}
|
||||
|
||||
// deliverKept gives the client the private messages kept for its user
|
||||
// while they were away.
|
||||
func (ns *nsSession) deliverKept() {
|
||||
ns.mu.Lock()
|
||||
sent := ns.keptSent
|
||||
ns.keptSent = true
|
||||
ns.mu.Unlock()
|
||||
if sent {
|
||||
return
|
||||
}
|
||||
for _, e := range ns.n.Kept() {
|
||||
ns.event(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
// The contact lists: the Forward List (FL) is the user's friends list; the
|
||||
// Block List (BL) their blocked list; the Reverse List (RL) those who have
|
||||
// them as a friend; the Allow List (AL), those not blocked who are on
|
||||
// either. A user who adds one is on their RL and not on their AL or BL,
|
||||
// which a client asks about ("X has added you...").
|
||||
|
||||
const maxGroups = 30 // MSNP7's group ids are 0 to 29
|
||||
|
||||
// loadLists reads the lists from the store into the session.
|
||||
func (ns *nsSession) loadLists() error {
|
||||
st := ns.s.B.Store
|
||||
fs, err := st.Friends(ns.u.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bs, err := st.Blocked(ns.u.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rs, err := st.FriendOf(ns.u.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
ns.fl = map[int64]store.Friend{}
|
||||
for _, f := range fs {
|
||||
ns.fl[f.ID] = f
|
||||
ns.groupIDLocked(f.Group)
|
||||
}
|
||||
ns.bl = map[int64]bool{}
|
||||
for _, b := range bs {
|
||||
ns.bl[b.ID] = true
|
||||
}
|
||||
ns.rl = map[int64]bool{}
|
||||
for _, r := range rs {
|
||||
ns.rl[r.ID] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// groupIDLocked is a group's id, given one if it has none. ns.mu is
|
||||
// held.
|
||||
func (ns *nsSession) groupIDLocked(name string) int {
|
||||
if name == "" {
|
||||
return 0
|
||||
}
|
||||
for id, g := range ns.groups {
|
||||
if g == name {
|
||||
return id
|
||||
}
|
||||
}
|
||||
for id := 1; id < maxGroups; id++ {
|
||||
if _, used := ns.groups[id]; !used {
|
||||
ns.groups[id] = name
|
||||
return id
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// entry is one on a list, as LST gives it.
|
||||
type entry struct {
|
||||
handle, name string
|
||||
group int
|
||||
}
|
||||
|
||||
// list is one of the lists, sorted by handle.
|
||||
func (ns *nsSession) list(which string) []entry {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
var out []entry
|
||||
add := func(id int64, name string, group int) {
|
||||
out = append(out, entry{handle: ns.s.handleOfName(name), name: name, group: group})
|
||||
}
|
||||
names := ns.namesLocked()
|
||||
switch which {
|
||||
case "FL":
|
||||
for _, f := range ns.fl {
|
||||
n := f.Name
|
||||
if f.Alias != "" {
|
||||
n = f.Alias
|
||||
}
|
||||
out = append(out, entry{handle: ns.s.handleOfName(f.Name), name: n, group: ns.groupIDLocked(f.Group)})
|
||||
}
|
||||
case "AL":
|
||||
seen := map[int64]bool{}
|
||||
for id := range ns.fl {
|
||||
if !ns.bl[id] {
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
for id := range ns.rl {
|
||||
if !ns.bl[id] {
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
for id := range seen {
|
||||
add(id, names[id], 0)
|
||||
}
|
||||
case "BL":
|
||||
for id := range ns.bl {
|
||||
add(id, names[id], 0)
|
||||
}
|
||||
case "RL":
|
||||
for id := range ns.rl {
|
||||
add(id, names[id], 0)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].handle < out[j].handle })
|
||||
return out
|
||||
}
|
||||
|
||||
// namesLocked are the names of everyone on the lists, by id. ns.mu is
|
||||
// held; the store is read for those not on the FL.
|
||||
func (ns *nsSession) namesLocked() map[int64]string {
|
||||
names := map[int64]string{}
|
||||
for id, f := range ns.fl {
|
||||
names[id] = f.Name
|
||||
}
|
||||
for _, m := range []map[int64]bool{ns.bl, ns.rl} {
|
||||
for id := range m {
|
||||
if _, ok := names[id]; ok {
|
||||
continue
|
||||
}
|
||||
if u, err := ns.s.B.Store.UserByID(id); err == nil {
|
||||
names[id] = u.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// handleOfName is the handle of a user of that name.
|
||||
func (s *Server) handleOfName(name string) string {
|
||||
return strings.ReplaceAll(name, " ", "") + "@" + s.S.Domain
|
||||
}
|
||||
|
||||
// syn sends the lists: the settings, the groups (MSNP7), each list. The
|
||||
// list version is always new, so the client takes all of it.
|
||||
func (ns *nsSession) syn(c *cmd) {
|
||||
if err := ns.loadLists(); err != nil {
|
||||
ns.s.B.Log.Printf("node %d: msn: lists: %v", ns.n.Num, err)
|
||||
ns.k.sendErr(errInternal, c.trid)
|
||||
return
|
||||
}
|
||||
have, _ := strconv.Atoi(c.arg(0))
|
||||
ns.mu.Lock()
|
||||
if ns.listVer <= have {
|
||||
ns.listVer = have + 1
|
||||
}
|
||||
ns.synced = true
|
||||
gtc, blp := ns.gtc, ns.blp
|
||||
ns.mu.Unlock()
|
||||
v := ns.verNow()
|
||||
ns.k.send("SYN", c.trid, v)
|
||||
ns.k.send("GTC", c.trid, v, gtc)
|
||||
ns.k.send("BLP", c.trid, v, blp)
|
||||
if ns.ver >= 7 {
|
||||
ns.sendGroups(c.trid, v)
|
||||
}
|
||||
for _, l := range []string{"FL", "AL", "BL", "RL"} {
|
||||
ns.sendList(c.trid, v, l)
|
||||
}
|
||||
}
|
||||
|
||||
// sendList sends a list as LST lines.
|
||||
func (ns *nsSession) sendList(trid, v, which string) {
|
||||
es := ns.list(which)
|
||||
if len(es) == 0 {
|
||||
ns.k.send("LST", trid, which, v, "0", "0")
|
||||
return
|
||||
}
|
||||
for i, e := range es {
|
||||
w := []string{"LST", trid, which, v, strconv.Itoa(i + 1), strconv.Itoa(len(es)), e.handle, encode(e.name)}
|
||||
if which == "FL" && ns.ver >= 7 {
|
||||
w = append(w, strconv.Itoa(e.group))
|
||||
}
|
||||
ns.k.send(w...)
|
||||
}
|
||||
}
|
||||
|
||||
// sendGroups sends the groups as LSG lines (Other Contacts, 0, first).
|
||||
func (ns *nsSession) sendGroups(trid, v string) {
|
||||
ns.mu.Lock()
|
||||
ids := make([]int, 0, len(ns.groups))
|
||||
for id := range ns.groups {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Ints(ids)
|
||||
names := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
names[i] = ns.groups[id]
|
||||
if id == 0 {
|
||||
names[i] = "Other Contacts"
|
||||
}
|
||||
}
|
||||
ns.mu.Unlock()
|
||||
for i, id := range ids {
|
||||
ns.k.send("LSG", trid, v, strconv.Itoa(i+1), strconv.Itoa(len(ids)), strconv.Itoa(id), encode(names[i]), "0")
|
||||
}
|
||||
}
|
||||
|
||||
// lst answers LST: one list.
|
||||
func (ns *nsSession) lst(c *cmd) {
|
||||
which := strings.ToUpper(c.arg(0))
|
||||
switch which {
|
||||
case "FL", "AL", "BL", "RL":
|
||||
ns.sendList(c.trid, ns.verNow(), which)
|
||||
default:
|
||||
ns.k.sendErr(errBadParam, c.trid)
|
||||
}
|
||||
}
|
||||
|
||||
// lsg answers LSG: the groups.
|
||||
func (ns *nsSession) lsg(c *cmd) {
|
||||
if ns.ver < 7 {
|
||||
ns.k.sendErr(errSyntax, c.trid)
|
||||
return
|
||||
}
|
||||
ns.sendGroups(c.trid, ns.verNow())
|
||||
}
|
||||
|
||||
// add is ADD: a friend (FL), one allowed (AL), one blocked (BL).
|
||||
func (ns *nsSession) add(c *cmd) {
|
||||
which, handle := strings.ToUpper(c.arg(0)), c.arg(1)
|
||||
k := ns.k
|
||||
t := ns.s.resolve(handle)
|
||||
switch {
|
||||
case which != "FL" && which != "AL" && which != "BL":
|
||||
k.sendErr(errBadParam, c.trid)
|
||||
return
|
||||
case !strings.Contains(handle, "@"):
|
||||
k.sendErr(errBadHandle, c.trid)
|
||||
return
|
||||
case t == nil:
|
||||
k.sendErr(errNoSuchUser, c.trid)
|
||||
return
|
||||
case t.ID == ns.u.ID:
|
||||
k.sendErr(errBadParam, c.trid)
|
||||
return
|
||||
}
|
||||
h := ns.s.handleOf(t)
|
||||
ns.mu.Lock()
|
||||
f, isFriend := ns.fl[t.ID]
|
||||
blocked := ns.bl[t.ID]
|
||||
ns.mu.Unlock()
|
||||
switch which {
|
||||
case "FL":
|
||||
group := ""
|
||||
gid := 0
|
||||
if ns.ver >= 7 && c.arg(3) != "" {
|
||||
var err error
|
||||
if gid, err = strconv.Atoi(c.arg(3)); err != nil {
|
||||
k.sendErr(errBadGroup, c.trid)
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
g, ok := ns.groups[gid]
|
||||
ns.mu.Unlock()
|
||||
if !ok {
|
||||
k.sendErr(errBadGroup, c.trid)
|
||||
return
|
||||
}
|
||||
group = g
|
||||
}
|
||||
if isFriend && (ns.ver < 7 || f.Group == group) {
|
||||
k.sendErr(errAlreadyThere, c.trid)
|
||||
return
|
||||
}
|
||||
nf := store.Friend{ID: t.ID, Name: t.Name, Group: group, Alias: f.Alias}
|
||||
ns.mu.Lock()
|
||||
ns.fl[t.ID] = nf // before the store tells of it, so it is not told twice
|
||||
ns.mu.Unlock()
|
||||
if err := ns.s.B.Store.PutFriend(ns.u.ID, nf); err != nil {
|
||||
ns.s.B.Log.Printf("node %d: msn: adding a friend: %v", ns.n.Num, err)
|
||||
k.sendErr(errInternal, c.trid)
|
||||
return
|
||||
}
|
||||
w := []string{"ADD", c.trid, "FL", ns.bumpVer(), h, encode(t.Name)}
|
||||
if ns.ver >= 7 {
|
||||
w = append(w, strconv.Itoa(gid))
|
||||
}
|
||||
k.send(w...)
|
||||
ns.s.B.FriendsChanged(ns.u.ID)
|
||||
if st := ns.s.statusFor(t, ns.u); st != "" {
|
||||
ns.mu.Lock()
|
||||
ns.told[t.ID] = st
|
||||
ns.mu.Unlock()
|
||||
k.send("ILN", c.trid, st, h, encode(ns.s.friendlyFor(t)))
|
||||
}
|
||||
case "AL":
|
||||
if blocked {
|
||||
k.sendErr(errInOpposite, c.trid)
|
||||
return
|
||||
}
|
||||
k.send("ADD", c.trid, "AL", ns.bumpVer(), h, encode(t.Name))
|
||||
case "BL":
|
||||
if blocked {
|
||||
k.sendErr(errAlreadyThere, c.trid)
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
ns.bl[t.ID] = true
|
||||
ns.mu.Unlock()
|
||||
if err := ns.s.B.Store.Block(ns.u.ID, t.ID); err != nil {
|
||||
k.sendErr(errInternal, c.trid)
|
||||
return
|
||||
}
|
||||
k.send("ADD", c.trid, "BL", ns.bumpVer(), h, encode(t.Name))
|
||||
ns.s.B.FriendsChanged(ns.u.ID)
|
||||
ns.s.changed(ns.u)
|
||||
}
|
||||
}
|
||||
|
||||
// rem is REM: off a list (or, MSNP7, out of a group).
|
||||
func (ns *nsSession) rem(c *cmd) {
|
||||
which, handle := strings.ToUpper(c.arg(0)), c.arg(1)
|
||||
k := ns.k
|
||||
t := ns.s.resolve(handle)
|
||||
if which != "FL" && which != "AL" && which != "BL" {
|
||||
k.sendErr(errBadParam, c.trid)
|
||||
return
|
||||
}
|
||||
if t == nil {
|
||||
k.sendErr(errNotOnList, c.trid)
|
||||
return
|
||||
}
|
||||
h := ns.s.handleOf(t)
|
||||
ns.mu.Lock()
|
||||
f, isFriend := ns.fl[t.ID]
|
||||
blocked := ns.bl[t.ID]
|
||||
ns.mu.Unlock()
|
||||
switch which {
|
||||
case "FL":
|
||||
if !isFriend {
|
||||
k.sendErr(errNotOnList, c.trid)
|
||||
return
|
||||
}
|
||||
if ns.ver >= 7 && c.arg(2) != "" {
|
||||
gid, err := strconv.Atoi(c.arg(2))
|
||||
ns.mu.Lock()
|
||||
g, ok := ns.groups[gid]
|
||||
ns.mu.Unlock()
|
||||
if err != nil || !ok {
|
||||
k.sendErr(errBadGroup, c.trid)
|
||||
return
|
||||
}
|
||||
if f.Group != g {
|
||||
k.sendErr(errNotInGroup, c.trid)
|
||||
return
|
||||
}
|
||||
if g != "" { // out of the group: into Other Contacts
|
||||
f.Group = ""
|
||||
ns.mu.Lock()
|
||||
ns.fl[t.ID] = f
|
||||
ns.mu.Unlock()
|
||||
ns.s.B.Store.PutFriend(ns.u.ID, f)
|
||||
ns.s.B.FriendsChanged(ns.u.ID)
|
||||
}
|
||||
k.send("REM", c.trid, "FL", ns.bumpVer(), h, c.arg(2))
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
delete(ns.fl, t.ID)
|
||||
delete(ns.told, t.ID)
|
||||
ns.mu.Unlock()
|
||||
if err := ns.s.B.Store.RemoveFriend(ns.u.ID, t.ID); err != nil {
|
||||
k.sendErr(errInternal, c.trid)
|
||||
return
|
||||
}
|
||||
k.send("REM", c.trid, "FL", ns.bumpVer(), h)
|
||||
ns.s.B.FriendsChanged(ns.u.ID)
|
||||
case "AL":
|
||||
k.send("REM", c.trid, "AL", ns.bumpVer(), h)
|
||||
case "BL":
|
||||
if !blocked {
|
||||
k.sendErr(errNotOnList, c.trid)
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
delete(ns.bl, t.ID)
|
||||
ns.mu.Unlock()
|
||||
ns.s.B.Store.Unblock(ns.u.ID, t.ID)
|
||||
k.send("REM", c.trid, "BL", ns.bumpVer(), h)
|
||||
ns.s.B.FriendsChanged(ns.u.ID)
|
||||
ns.s.changed(ns.u)
|
||||
}
|
||||
}
|
||||
|
||||
// rea is REA: its own display name, or one it keeps for a friend (the
|
||||
// friend's alias on the friends list).
|
||||
func (ns *nsSession) rea(c *cmd) {
|
||||
handle, name := c.arg(0), strings.TrimSpace(decode(c.arg(1)))
|
||||
k := ns.k
|
||||
if name == "" || len(name) > 129 {
|
||||
k.sendErr(errBadFriendly, c.trid)
|
||||
return
|
||||
}
|
||||
t := ns.s.resolve(handle)
|
||||
if t == nil {
|
||||
k.sendErr(errNotOnList, c.trid)
|
||||
return
|
||||
}
|
||||
if t.ID == ns.u.ID {
|
||||
ns.mu.Lock()
|
||||
ns.friendly = name
|
||||
ns.mu.Unlock()
|
||||
k.send("REA", c.trid, ns.bumpVer(), handle, encode(name))
|
||||
ns.s.renamed(ns.u)
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
f, ok := ns.fl[t.ID]
|
||||
if ok {
|
||||
f.Alias = name
|
||||
if name == t.Name {
|
||||
f.Alias = ""
|
||||
}
|
||||
ns.fl[t.ID] = f
|
||||
}
|
||||
ns.mu.Unlock()
|
||||
if !ok {
|
||||
k.sendErr(errNotOnList, c.trid)
|
||||
return
|
||||
}
|
||||
ns.s.B.Store.PutFriend(ns.u.ID, f)
|
||||
k.send("REA", c.trid, ns.bumpVer(), handle, encode(name))
|
||||
}
|
||||
|
||||
// group is ADG, RMG and REG (MSNP7): groups made, removed, renamed. A
|
||||
// group is its friends': one with none is forgotten at the next sign-in.
|
||||
func (ns *nsSession) group(c *cmd) {
|
||||
k := ns.k
|
||||
if ns.ver < 7 {
|
||||
k.sendErr(errSyntax, c.trid)
|
||||
return
|
||||
}
|
||||
st := ns.s.B.Store
|
||||
switch c.name {
|
||||
case "ADG":
|
||||
name := strings.TrimSpace(decode(c.arg(0)))
|
||||
if name == "" || len(name) > 61 || strings.EqualFold(name, "Other Contacts") {
|
||||
k.sendErr(errGroupName, c.trid)
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
for _, g := range ns.groups {
|
||||
if strings.EqualFold(g, name) {
|
||||
ns.mu.Unlock()
|
||||
k.sendErr(errGroupName, c.trid)
|
||||
return
|
||||
}
|
||||
}
|
||||
n := len(ns.groups)
|
||||
id := ns.groupIDLocked(name)
|
||||
ns.mu.Unlock()
|
||||
if n >= maxGroups || id == 0 {
|
||||
k.sendErr(errListFull, c.trid)
|
||||
return
|
||||
}
|
||||
k.send("ADG", c.trid, ns.bumpVer(), encode(name), strconv.Itoa(id), "0")
|
||||
case "RMG", "REG":
|
||||
id, err := strconv.Atoi(c.arg(0))
|
||||
ns.mu.Lock()
|
||||
old, ok := ns.groups[id]
|
||||
ns.mu.Unlock()
|
||||
if err != nil || !ok || id == 0 {
|
||||
k.sendErr(errBadGroup, c.trid)
|
||||
return
|
||||
}
|
||||
to := ""
|
||||
if c.name == "REG" {
|
||||
to = strings.TrimSpace(decode(c.arg(1)))
|
||||
if to == "" || len(to) > 61 {
|
||||
k.sendErr(errGroupName, c.trid)
|
||||
return
|
||||
}
|
||||
}
|
||||
ns.mu.Lock()
|
||||
var moved []store.Friend
|
||||
for fid, f := range ns.fl {
|
||||
if f.Group == old {
|
||||
f.Group = to
|
||||
ns.fl[fid] = f
|
||||
moved = append(moved, f)
|
||||
}
|
||||
}
|
||||
if c.name == "RMG" {
|
||||
delete(ns.groups, id)
|
||||
} else {
|
||||
ns.groups[id] = to
|
||||
}
|
||||
ns.mu.Unlock()
|
||||
for _, f := range moved {
|
||||
st.PutFriend(ns.u.ID, f)
|
||||
}
|
||||
if len(moved) > 0 {
|
||||
ns.s.B.FriendsChanged(ns.u.ID)
|
||||
}
|
||||
if c.name == "RMG" {
|
||||
k.send("RMG", c.trid, ns.bumpVer(), strconv.Itoa(id))
|
||||
} else {
|
||||
k.send("REG", c.trid, ns.bumpVer(), strconv.Itoa(id), encode(to), "0")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncLists has the client told of changes made to its friends and
|
||||
// blocked lists elsewhere (by AIM, IRC, the BBS).
|
||||
func (ns *nsSession) syncLists() {
|
||||
ns.mu.Lock()
|
||||
synced := ns.synced
|
||||
oldFL, oldBL := ns.fl, ns.bl
|
||||
ns.mu.Unlock()
|
||||
if !synced {
|
||||
return
|
||||
}
|
||||
if err := ns.loadLists(); err != nil {
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
newFL, newBL := ns.fl, ns.bl
|
||||
ns.mu.Unlock()
|
||||
for id, f := range newFL {
|
||||
if _, ok := oldFL[id]; !ok {
|
||||
w := []string{"ADD", "0", "FL", ns.bumpVer(), ns.s.handleOfName(f.Name), encode(f.Name)}
|
||||
if ns.ver >= 7 {
|
||||
ns.mu.Lock()
|
||||
w = append(w, strconv.Itoa(ns.groupIDLocked(f.Group)))
|
||||
ns.mu.Unlock()
|
||||
}
|
||||
ns.k.send(w...)
|
||||
if u, err := ns.s.B.Store.UserByID(id); err == nil {
|
||||
ns.contactChanged(u)
|
||||
}
|
||||
}
|
||||
}
|
||||
for id, f := range oldFL {
|
||||
if _, ok := newFL[id]; !ok {
|
||||
ns.k.send("REM", "0", "FL", ns.bumpVer(), ns.s.handleOfName(f.Name))
|
||||
ns.mu.Lock()
|
||||
delete(ns.told, id)
|
||||
ns.mu.Unlock()
|
||||
}
|
||||
}
|
||||
for id := range newBL {
|
||||
if !oldBL[id] {
|
||||
if u, err := ns.s.B.Store.UserByID(id); err == nil {
|
||||
ns.k.send("ADD", "0", "BL", ns.bumpVer(), ns.s.handleOf(u), encode(u.Name))
|
||||
}
|
||||
}
|
||||
}
|
||||
for id := range oldBL {
|
||||
if !newBL[id] {
|
||||
if u, err := ns.s.B.Store.UserByID(id); err == nil {
|
||||
ns.k.send("REM", "0", "BL", ns.bumpVer(), ns.s.handleOf(u))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reverseChanged: another user's lists changed: whether they have this
|
||||
// one as a friend (its RL), and what it sees of them.
|
||||
func (ns *nsSession) reverseChanged(u *store.User) {
|
||||
ns.mu.Lock()
|
||||
synced := ns.synced
|
||||
had := ns.rl[u.ID]
|
||||
ns.mu.Unlock()
|
||||
if synced {
|
||||
has, err := ns.s.B.Store.IsFriend(u.ID, ns.u.ID)
|
||||
if err == nil && has != had {
|
||||
ns.mu.Lock()
|
||||
if has {
|
||||
ns.rl[u.ID] = true
|
||||
} else {
|
||||
delete(ns.rl, u.ID)
|
||||
}
|
||||
ns.mu.Unlock()
|
||||
if has {
|
||||
ns.k.send("ADD", "0", "RL", ns.bumpVer(), ns.s.handleOf(u), encode(u.Name))
|
||||
} else {
|
||||
ns.k.send("REM", "0", "RL", ns.bumpVer(), ns.s.handleOf(u))
|
||||
}
|
||||
}
|
||||
}
|
||||
ns.contactChanged(u)
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/ircd"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
type syncBuf struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (s *syncBuf) Write(p []byte) (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.Write(p)
|
||||
}
|
||||
|
||||
func (s *syncBuf) String() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.String()
|
||||
}
|
||||
|
||||
type env struct {
|
||||
b *bbs.BBS
|
||||
srv *Server
|
||||
addr string // MSN's
|
||||
ircAddr string
|
||||
}
|
||||
|
||||
// freeAddr is a loopback address free to listen on.
|
||||
func freeAddr(t *testing.T) string {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
return ln.Addr().String()
|
||||
}
|
||||
|
||||
// start is a BBS (alice, bob, Carol Ann and sysop, all password1; old,
|
||||
// made before MSN digests were kept) with MSN and IRC servers.
|
||||
func start(t *testing.T) *env {
|
||||
t.Helper()
|
||||
store.BcryptCost = 4
|
||||
st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
if _, err := st.CreateUser("old", "password1", "", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st.SetKeepMSN(true)
|
||||
for _, name := range []string{"alice", "bob", "Carol Ann", "sysop"} {
|
||||
if _, err := st.CreateUser(name, "password1", "Here", name == "sysop"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s := bbs.Defaults()
|
||||
s.Name, s.FailDelay = "Test BBS", 0
|
||||
logs := &syncBuf{}
|
||||
b := bbs.New(s, st, log.New(logs, "", 0))
|
||||
e := &env{b: b, addr: freeAddr(t), ircAddr: freeAddr(t)}
|
||||
srv, err := New(b, Settings{Address: e.addr, Domain: "bbs.test", MaxPerIP: 50})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.srv = srv
|
||||
is, err := ircd.New(b, ircd.Settings{Address: e.ircAddr, ServerName: "irc.test", MaxClients: 10, MaxPerIP: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() { srv.Run(ctx); wg.Done() }()
|
||||
go func() { is.Run(ctx); wg.Done() }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
wg.Wait()
|
||||
if t.Failed() {
|
||||
t.Log("log:\n" + logs.String())
|
||||
}
|
||||
})
|
||||
for _, a := range []string{e.addr, e.ircAddr} {
|
||||
for i := 0; ; i++ {
|
||||
if c, err := net.Dial("tcp", a); err == nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
if i > 100 {
|
||||
t.Fatal("never listened")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// client is a scripted MSN client's connection (to the notification
|
||||
// server or a switchboard).
|
||||
type client struct {
|
||||
t *testing.T
|
||||
c net.Conn
|
||||
r *bufio.Reader
|
||||
trid int
|
||||
}
|
||||
|
||||
func dial(t *testing.T, addr string) *client {
|
||||
t.Helper()
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { c.Close() })
|
||||
return &client{t: t, c: c, r: bufio.NewReader(c)}
|
||||
}
|
||||
|
||||
// cmd sends a command with the next transaction id, which it gives.
|
||||
func (cl *client) cmd(name string, args ...string) string {
|
||||
cl.trid++
|
||||
id := strconv.Itoa(cl.trid)
|
||||
cl.c.Write([]byte(strings.Join(append([]string{name, id}, args...), " ") + "\r\n"))
|
||||
return id
|
||||
}
|
||||
|
||||
// msg sends a MSG with a text payload.
|
||||
func (cl *client) msg(ack, text string) string {
|
||||
cl.trid++
|
||||
id := strconv.Itoa(cl.trid)
|
||||
p := "MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n" + text
|
||||
fmt.Fprintf(cl.c, "MSG %s %s %d\r\n%s", id, ack, len(p), p)
|
||||
return id
|
||||
}
|
||||
|
||||
// line is the next line the server sends (and its payload, for a MSG).
|
||||
func (cl *client) line() (string, string, error) {
|
||||
cl.c.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
l, err := cl.r.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
l = strings.TrimRight(l, "\r\n")
|
||||
f := strings.Fields(l)
|
||||
if len(f) > 0 && (f[0] == "MSG" || f[0] == "NOT") {
|
||||
n, _ := strconv.Atoi(f[len(f)-1])
|
||||
p := make([]byte, n)
|
||||
if _, err := readFull(cl.r, p); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return l, string(p), nil
|
||||
}
|
||||
return l, "", nil
|
||||
}
|
||||
|
||||
// expect reads lines until one beginning with want; it and its payload.
|
||||
func (cl *client) expect(want string) (string, string) {
|
||||
cl.t.Helper()
|
||||
var seen []string
|
||||
for {
|
||||
l, p, err := cl.line()
|
||||
if err != nil {
|
||||
cl.t.Fatalf("waiting for %q: %v; saw %q", want, err, seen)
|
||||
}
|
||||
if strings.HasPrefix(l, want) {
|
||||
return l, p
|
||||
}
|
||||
seen = append(seen, l)
|
||||
}
|
||||
}
|
||||
|
||||
// quiet: nothing beginning with any of these comes for a moment.
|
||||
func (cl *client) quiet(not ...string) {
|
||||
cl.t.Helper()
|
||||
cl.c.SetReadDeadline(time.Now().Add(300 * time.Millisecond))
|
||||
for {
|
||||
l, _, err := cl.line()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, n := range not {
|
||||
if strings.HasPrefix(l, n) {
|
||||
cl.t.Errorf("unwanted %q", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func digest(salt, pw string) string {
|
||||
h := md5.Sum([]byte(salt + pw))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// signIn signs a client in by MD5 at MSNP ver; the USR's answer.
|
||||
func signIn(t *testing.T, addr, handle, pw string, ver int) (*client, string) {
|
||||
t.Helper()
|
||||
cl := dial(t, addr)
|
||||
cl.cmd("VER", fmt.Sprintf("MSNP%d", ver), "CVR0")
|
||||
if l, _ := cl.expect("VER "); l != fmt.Sprintf("VER 1 MSNP%d", ver) {
|
||||
t.Fatalf("version %q", l)
|
||||
}
|
||||
cl.cmd("INF")
|
||||
cl.expect("INF 2 MD5")
|
||||
cl.cmd("USR", "MD5", "I", handle)
|
||||
l, _ := cl.expect("USR 3 MD5 S ")
|
||||
salt := strings.Fields(l)[4]
|
||||
cl.cmd("USR", "MD5", "S", digest(salt, pw))
|
||||
l, _, err := cl.line()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cl, l
|
||||
}
|
||||
|
||||
// online signs a client in at MSNP7, takes its lists and sets it online.
|
||||
func online(t *testing.T, addr, name string) *client {
|
||||
t.Helper()
|
||||
cl, l := signIn(t, addr, name+"@bbs.test", "password1", 7)
|
||||
if !strings.HasPrefix(l, "USR 4 OK ") {
|
||||
t.Fatalf("%s: %q", name, l)
|
||||
}
|
||||
cl.expect("MSG Hotmail Hotmail ")
|
||||
cl.cmd("SYN", "0")
|
||||
cl.expect("LST 5 RL ")
|
||||
cl.cmd("CHG", "NLN")
|
||||
cl.expect("CHG 6 NLN")
|
||||
return cl
|
||||
}
|
||||
|
||||
// switchboard has cl ask for a conversation and join it.
|
||||
func (cl *client) switchboard(t *testing.T, handle string) *client {
|
||||
t.Helper()
|
||||
cl.cmd("XFR", "SB")
|
||||
l, _ := cl.expect("XFR ")
|
||||
f := strings.Fields(l)
|
||||
if len(f) != 6 || f[2] != "SB" || f[4] != "CKI" {
|
||||
t.Fatalf("xfr %q", l)
|
||||
}
|
||||
sc := dial(t, f[3])
|
||||
sc.cmd("USR", handle, f[5])
|
||||
sc.expect("USR 1 OK " + handle + " ")
|
||||
return sc
|
||||
}
|
||||
|
||||
// answer has cl answer a ring (an RNG line) as handle; its switchboard
|
||||
// connection, and the IRO lines it was told.
|
||||
func answer(t *testing.T, rng, handle string) (*client, []string) {
|
||||
t.Helper()
|
||||
f := strings.Fields(rng)
|
||||
if len(f) < 7 || f[0] != "RNG" || f[3] != "CKI" {
|
||||
t.Fatalf("rng %q", rng)
|
||||
}
|
||||
sc := dial(t, f[2])
|
||||
sc.cmd("ANS", handle, f[4], f[1])
|
||||
var iro []string
|
||||
for {
|
||||
l, _ := sc.expect("")
|
||||
if l == "ANS 1 OK" {
|
||||
return sc, iro
|
||||
}
|
||||
if !strings.HasPrefix(l, "IRO 1 ") {
|
||||
t.Fatalf("answering: %q", l)
|
||||
}
|
||||
iro = append(iro, l)
|
||||
}
|
||||
}
|
||||
|
||||
type ircConn struct {
|
||||
t *testing.T
|
||||
c net.Conn
|
||||
r *bufio.Reader
|
||||
}
|
||||
|
||||
func ircLogin(t *testing.T, addr, name string) *ircConn {
|
||||
t.Helper()
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { c.Close() })
|
||||
ic := &ircConn{t: t, c: c, r: bufio.NewReader(c)}
|
||||
ic.send("PASS "+name+":password1", "NICK "+ircd.Nick(name), "USER u 0 * :"+name)
|
||||
ic.expect(" 001 ")
|
||||
return ic
|
||||
}
|
||||
|
||||
func (ic *ircConn) send(lines ...string) {
|
||||
for _, l := range lines {
|
||||
ic.c.Write([]byte(l + "\r\n"))
|
||||
}
|
||||
}
|
||||
|
||||
func (ic *ircConn) expect(want string) string {
|
||||
ic.t.Helper()
|
||||
var seen []string
|
||||
for {
|
||||
ic.c.SetReadDeadline(time.Now().Add(3 * time.Second))
|
||||
l, err := ic.r.ReadString('\n')
|
||||
if err != nil {
|
||||
ic.t.Fatalf("waiting for %q: %v; saw %q", want, err, seen)
|
||||
}
|
||||
if strings.Contains(l, want) {
|
||||
return l
|
||||
}
|
||||
seen = append(seen, strings.TrimSpace(l))
|
||||
}
|
||||
}
|
||||
|
||||
func (e *env) user(t *testing.T, name string) *store.User {
|
||||
t.Helper()
|
||||
u, err := e.b.Store.UserByName(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// TestSignIn: an MD5 sign-in (the handle at any domain, the name with or
|
||||
// without its spaces), its profile and lists; a wrong password, an
|
||||
// unknown handle, a version not served; an account from before digests
|
||||
// were kept, until its password is used in the clear; MSN 1.0's CTP.
|
||||
func TestSignIn(t *testing.T) {
|
||||
e := start(t)
|
||||
cl, l := signIn(t, e.addr, "alice@hotmail.com", "password1", 7)
|
||||
if l != "USR 4 OK alice@hotmail.com alice 1" {
|
||||
t.Errorf("signed in: %q", l)
|
||||
}
|
||||
if _, p := cl.expect("MSG Hotmail Hotmail "); !strings.Contains(p, "text/x-msmsgsprofile") {
|
||||
t.Errorf("profile %q", p)
|
||||
}
|
||||
cl.cmd("SYN", "41")
|
||||
want := []string{"SYN 5 42", "GTC 5 42 A", "BLP 5 42 AL", "LSG 5 42 1 1 0 Other%20Contacts 0",
|
||||
"LST 5 FL 42 0 0", "LST 5 AL 42 0 0", "LST 5 BL 42 0 0", "LST 5 RL 42 0 0"}
|
||||
for _, w := range want {
|
||||
if l, _ := cl.expect(""); l != w {
|
||||
t.Errorf("got %q, want %q", l, w)
|
||||
}
|
||||
}
|
||||
|
||||
_, l = signIn(t, e.addr, "CarolAnn@bbs.test", "password1", 6)
|
||||
if l != "USR 4 OK CarolAnn@bbs.test Carol%20Ann 1" {
|
||||
t.Errorf("carol: %q", l)
|
||||
}
|
||||
if _, l = signIn(t, e.addr, "bob@bbs.test", "wrong", 5); l != "911 4" {
|
||||
t.Errorf("wrong password: %q", l)
|
||||
}
|
||||
if _, l = signIn(t, e.addr, "nobody@bbs.test", "password1", 5); l != "911 4" {
|
||||
t.Errorf("unknown: %q", l)
|
||||
}
|
||||
nc := dial(t, e.addr)
|
||||
nc.cmd("VER", "MSNP8", "CVR0")
|
||||
if l, _ := nc.expect("VER "); l != "VER 1 0" {
|
||||
t.Errorf("MSNP8: %q", l)
|
||||
}
|
||||
|
||||
if _, l = signIn(t, e.addr, "old@bbs.test", "password1", 7); l != "911 4" {
|
||||
t.Errorf("old, no digest: %q", l)
|
||||
}
|
||||
if _, err := e.b.Store.CheckPassword("old", "password1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, l = signIn(t, e.addr, "old@bbs.test", "password1", 7); !strings.HasPrefix(l, "USR 4 OK old@bbs.test old") {
|
||||
t.Errorf("old, with its digest: %q", l)
|
||||
}
|
||||
|
||||
// MSN 1.0: the password in the clear (MSNP2 only)
|
||||
cc := dial(t, e.addr)
|
||||
cc.cmd("VER", "MSNP2")
|
||||
cc.expect("VER 1 MSNP2")
|
||||
cc.cmd("USR", "CTP", "I", "sysop@hotmail.com", "password1")
|
||||
if l, _ := cc.expect("USR "); l != "USR 2 OK sysop@hotmail.com sysop" {
|
||||
t.Errorf("CTP: %q", l)
|
||||
}
|
||||
}
|
||||
|
||||
// TestContacts: adding a friend (the store's friends list, and online at
|
||||
// once), who sees one on their reverse list; status changes; a block, by
|
||||
// which one appears offline; removing.
|
||||
func TestContacts(t *testing.T) {
|
||||
e := start(t)
|
||||
alice := online(t, e.addr, "alice")
|
||||
bob := online(t, e.addr, "bob")
|
||||
aliceU, bobU := e.user(t, "alice"), e.user(t, "bob")
|
||||
|
||||
tr := alice.cmd("ADD", "FL", "bob@bbs.test", "bob", "0")
|
||||
if l, _ := alice.expect("ADD " + tr + " "); !strings.HasPrefix(l, "ADD "+tr+" FL ") || !strings.HasSuffix(l, " bob@bbs.test bob 0") {
|
||||
t.Errorf("add %q", l)
|
||||
}
|
||||
if l, _ := alice.expect("ILN " + tr); l != "ILN "+tr+" NLN bob@bbs.test bob" {
|
||||
t.Errorf("bob on: %q", l)
|
||||
}
|
||||
if ok, _ := e.b.Store.IsFriend(aliceU.ID, bobU.ID); !ok {
|
||||
t.Error("bob is not alice's friend in the store")
|
||||
}
|
||||
if l, _ := bob.expect("ADD 0 RL "); !strings.HasSuffix(l, " alice@bbs.test alice") {
|
||||
t.Errorf("bob's reverse list: %q", l)
|
||||
}
|
||||
tr = alice.cmd("ADD", "FL", "bob@bbs.test", "bob", "0")
|
||||
if l, _ := alice.expect(""); l != "215 "+tr {
|
||||
t.Errorf("twice: %q", l)
|
||||
}
|
||||
tr = alice.cmd("ADD", "FL", "nobody@bbs.test", "nobody", "0")
|
||||
if l, _ := alice.expect(""); l != "205 "+tr {
|
||||
t.Errorf("nobody: %q", l)
|
||||
}
|
||||
|
||||
// statuses and names
|
||||
bob.cmd("CHG", "BSY")
|
||||
if l, _ := alice.expect("NLN "); l != "NLN BSY bob@bbs.test bob" {
|
||||
t.Errorf("busy %q", l)
|
||||
}
|
||||
bob.cmd("REA", "bob@bbs.test", "Bobby%20B")
|
||||
bob.expect("REA ")
|
||||
if l, _ := alice.expect("NLN "); l != "NLN BSY bob@bbs.test Bobby%20B" {
|
||||
t.Errorf("renamed %q", l)
|
||||
}
|
||||
bob.cmd("CHG", "HDN")
|
||||
if l, _ := alice.expect("FLN "); l != "FLN bob@bbs.test" {
|
||||
t.Errorf("hidden %q", l)
|
||||
}
|
||||
bob.cmd("CHG", "NLN")
|
||||
alice.expect("NLN NLN bob@bbs.test")
|
||||
|
||||
// bob blocks alice: offline to her, in the store, her messages refused
|
||||
tr = bob.cmd("ADD", "BL", "alice@bbs.test", "alice")
|
||||
bob.expect("ADD " + tr + " BL ")
|
||||
if l, _ := alice.expect("FLN "); l != "FLN bob@bbs.test" {
|
||||
t.Errorf("blocked %q", l)
|
||||
}
|
||||
if !e.b.Blocks(bobU, aliceU) {
|
||||
t.Error("not blocked in the store")
|
||||
}
|
||||
tr = bob.cmd("REM", "BL", "alice@bbs.test")
|
||||
bob.expect("REM " + tr + " BL ")
|
||||
alice.expect("NLN NLN bob@bbs.test")
|
||||
|
||||
// a friend added from elsewhere (IRC, the terminal) comes to the list
|
||||
if _, err := e.b.AddFriend(aliceU, "Carol Ann"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l, _ := alice.expect("ADD 0 FL "); !strings.Contains(l, " CarolAnn@bbs.test Carol%20Ann") {
|
||||
t.Errorf("from elsewhere %q", l)
|
||||
}
|
||||
tr = alice.cmd("REM", "FL", "bob@bbs.test")
|
||||
alice.expect("REM " + tr + " FL ")
|
||||
if ok, _ := e.b.Store.IsFriend(aliceU.ID, bobU.ID); ok {
|
||||
t.Error("bob is still alice's friend")
|
||||
}
|
||||
bob.expect("REM 0 RL ")
|
||||
}
|
||||
|
||||
// TestConversation: two MSN clients in a switchboard: a call rung and
|
||||
// answered, a message both ways (acked, kept), one leaving.
|
||||
func TestConversation(t *testing.T) {
|
||||
e := start(t)
|
||||
alice := online(t, e.addr, "alice")
|
||||
bob := online(t, e.addr, "bob")
|
||||
as := alice.switchboard(t, "alice@bbs.test")
|
||||
tr := as.cmd("CAL", "bob@bbs.test")
|
||||
if l, _ := as.expect("CAL "); !strings.HasPrefix(l, "CAL "+tr+" RINGING ") {
|
||||
t.Fatalf("call %q", l)
|
||||
}
|
||||
rng, _ := bob.expect("RNG ")
|
||||
if !strings.HasSuffix(rng, " alice@bbs.test alice") {
|
||||
t.Errorf("rung %q", rng)
|
||||
}
|
||||
bs, iro := answer(t, rng, "bob@bbs.test")
|
||||
if len(iro) != 1 || iro[0] != "IRO 1 1 1 alice@bbs.test alice" {
|
||||
t.Errorf("iro %q", iro)
|
||||
}
|
||||
if l, _ := as.expect("JOI "); l != "JOI bob@bbs.test bob" {
|
||||
t.Errorf("joi %q", l)
|
||||
}
|
||||
tr = as.msg("A", "hello bob")
|
||||
if l, p := bs.expect("MSG "); !strings.HasPrefix(l, "MSG alice@bbs.test alice ") || !strings.HasSuffix(p, "\r\n\r\nhello bob") {
|
||||
t.Errorf("bob got %q %q", l, p)
|
||||
}
|
||||
if l, _ := as.expect(""); l != "ACK "+tr {
|
||||
t.Errorf("ack %q", l)
|
||||
}
|
||||
bs.msg("N", "hi alice")
|
||||
if _, p := as.expect("MSG bob@bbs.test "); !strings.HasSuffix(p, "hi alice") {
|
||||
t.Errorf("alice got %q", p)
|
||||
}
|
||||
cs, err := e.b.Store.ChatsBetween(e.user(t, "alice").ID, e.user(t, "bob").ID, 10)
|
||||
if err != nil || len(cs) != 2 || cs[0].Text != "hello bob" || !cs[1].Delivered {
|
||||
t.Errorf("kept %v %v", cs, err)
|
||||
}
|
||||
bs.cmd("OUT")
|
||||
if l, _ := as.expect("BYE "); l != "BYE bob@bbs.test" {
|
||||
t.Errorf("bye %q", l)
|
||||
}
|
||||
tr = as.cmd("CAL", "nobody@bbs.test")
|
||||
if l, _ := as.expect(""); l != "208 "+tr {
|
||||
t.Errorf("nobody %q", l)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIRC: an MSN client and an IRC user: she is in the conversation at
|
||||
// once, has its lines as PRIVMSGs, and hers come back into it; once it is
|
||||
// left, hers ring the client into a new one. One away has the client's
|
||||
// lines kept, and the client told so.
|
||||
func TestIRC(t *testing.T) {
|
||||
e := start(t)
|
||||
alice := online(t, e.addr, "alice")
|
||||
carol := ircLogin(t, e.ircAddr, "Carol Ann")
|
||||
as := alice.switchboard(t, "alice@bbs.test")
|
||||
as.cmd("CAL", "CarolAnn@bbs.test")
|
||||
as.expect("CAL ")
|
||||
if l, _ := as.expect("JOI "); l != "JOI CarolAnn@bbs.test Carol%20Ann" {
|
||||
t.Errorf("joi %q", l)
|
||||
}
|
||||
tr := as.msg("A", "hi carol")
|
||||
if l := carol.expect(" PRIVMSG Carol_Ann "); !strings.Contains(l, ":alice!") || !strings.HasSuffix(strings.TrimSpace(l), ":hi carol") {
|
||||
t.Errorf("carol got %q", l)
|
||||
}
|
||||
as.expect("ACK " + tr)
|
||||
carol.send("PRIVMSG alice :hi from IRC")
|
||||
if l, p := as.expect("MSG "); !strings.HasPrefix(l, "MSG CarolAnn@bbs.test Carol%20Ann ") || !strings.HasSuffix(p, "hi from IRC") {
|
||||
t.Errorf("alice got %q %q", l, p)
|
||||
}
|
||||
|
||||
as.cmd("OUT")
|
||||
carol.send("PRIVMSG alice :still there?")
|
||||
rng, _ := alice.expect("RNG ")
|
||||
if !strings.HasSuffix(rng, " CarolAnn@bbs.test Carol%20Ann") {
|
||||
t.Errorf("rung %q", rng)
|
||||
}
|
||||
as2, iro := answer(t, rng, "alice@bbs.test")
|
||||
if len(iro) != 1 || !strings.Contains(iro[0], " CarolAnn@bbs.test ") {
|
||||
t.Errorf("iro %q", iro)
|
||||
}
|
||||
if _, p := as2.expect("MSG CarolAnn@bbs.test "); !strings.HasSuffix(p, "still there?") {
|
||||
t.Errorf("queued %q", p)
|
||||
}
|
||||
|
||||
// carol goes: alice's lines are kept for her, and alice told once
|
||||
carol.send("QUIT")
|
||||
for i := 0; len(e.srv.nodesOf("Carol Ann")) > 0; i++ {
|
||||
if i > 300 {
|
||||
t.Fatal("carol never went")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
as2.msg("A", "bye then")
|
||||
if _, p := as2.expect("MSG BBS@bbs.test BBS "); !strings.Contains(p, "Carol Ann is not on now") {
|
||||
t.Errorf("told %q", p)
|
||||
}
|
||||
as2.expect("ACK ")
|
||||
if cs, _ := e.b.Store.KeptChats(e.user(t, "Carol Ann").ID); len(cs) != 1 || cs[0].Text != "bye then" {
|
||||
t.Errorf("kept %v", cs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestKept: lines kept while one was away come at their first status,
|
||||
// rung into a conversation, with their time; a blocked user's do not.
|
||||
func TestKept(t *testing.T) {
|
||||
e := start(t)
|
||||
carol := ircLogin(t, e.ircAddr, "Carol Ann")
|
||||
carol.send("PRIVMSG bob :are you there?")
|
||||
carol.expect(" 301 ")
|
||||
bobU, carolU := e.user(t, "bob"), e.user(t, "Carol Ann")
|
||||
|
||||
bob := online(t, e.addr, "bob")
|
||||
rng, _ := bob.expect("RNG ")
|
||||
bs, _ := answer(t, rng, "bob@bbs.test")
|
||||
if _, p := bs.expect("MSG CarolAnn@bbs.test "); !strings.Contains(p, "while you were away) are you there?") {
|
||||
t.Errorf("kept %q", p)
|
||||
}
|
||||
if cs, _ := e.b.Store.KeptChats(bobU.ID); len(cs) != 0 {
|
||||
t.Errorf("still kept %v", cs)
|
||||
}
|
||||
|
||||
// bob blocks carol: her messages are refused, now and while he is away
|
||||
tr := bob.cmd("ADD", "BL", "CarolAnn@bbs.test", "Carol%20Ann")
|
||||
bob.expect("ADD " + tr + " BL ")
|
||||
carol.send("PRIVMSG bob :hello?")
|
||||
if l := carol.expect(" 404 "); !strings.Contains(l, "not taking your messages") {
|
||||
t.Errorf("carol told %q", l)
|
||||
}
|
||||
bs.quiet("MSG CarolAnn")
|
||||
bob.quiet("RNG ")
|
||||
if !e.b.Blocks(bobU, carolU) {
|
||||
t.Error("not blocked")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
// statuses a client may set
|
||||
var statuses = map[string]string{"NLN": "online", "BSY": "busy", "IDL": "idle", "BRB": "be right back",
|
||||
"AWY": "away", "PHN": "on the phone", "LUN": "out to lunch", "HDN": "appearing offline"}
|
||||
|
||||
// nsSession is a client signed in to the notification server, on a node
|
||||
// of its own.
|
||||
type nsSession struct {
|
||||
s *Server
|
||||
k *conn
|
||||
host string
|
||||
ver int
|
||||
u *store.User
|
||||
n *bbs.Node
|
||||
handle string // as signed in
|
||||
|
||||
loginTrid string // its USR S's
|
||||
|
||||
todo chan func()
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
|
||||
mu sync.Mutex
|
||||
friendly string // its display name
|
||||
status string // "" until its first CHG
|
||||
blp string // AL: all may see it; BL: only its friends
|
||||
gtc string
|
||||
listVer int
|
||||
synced bool // has had its lists (SYN)
|
||||
fl map[int64]store.Friend // its friends, as last told
|
||||
rl map[int64]bool // who has it as a friend, as last told
|
||||
bl map[int64]bool // its blocked list, as last told
|
||||
groups map[int]string // MSNP7 group ids: names ("" is 0, Other Contacts)
|
||||
told map[int64]string // what it was last told of each friend's status ("": offline)
|
||||
noted map[int64]bool // told that these are away (their messages kept)
|
||||
keptSent bool
|
||||
}
|
||||
|
||||
// notification serves a notification session: the sign-in (begun with
|
||||
// first, a VER), then its commands until it goes.
|
||||
func (s *Server) notification(k *conn, host string, first *cmd) {
|
||||
ns := &nsSession{s: s, k: k, host: host, todo: make(chan func(), queueLen), done: make(chan struct{}),
|
||||
blp: "AL", gtc: "A", fl: map[int64]store.Friend{}, rl: map[int64]bool{}, bl: map[int64]bool{},
|
||||
groups: map[int]string{0: ""}, told: map[int64]string{}, noted: map[int64]bool{}}
|
||||
if !ns.signIn(first) {
|
||||
return
|
||||
}
|
||||
u := ns.u
|
||||
n, err := s.B.Enter(&bbs.Caller{Via: "msn", Listener: "msn", Remote: host, Source: "ip:" + host,
|
||||
Terminal: fmt.Sprintf("MSNP%d", ns.ver)}, ns.close)
|
||||
if err != nil {
|
||||
k.sendErr(errBusy, ns.loginTrid)
|
||||
return
|
||||
}
|
||||
ns.n = n
|
||||
n.SetUser(u)
|
||||
n.Doing("MSN")
|
||||
// one session an account (MSNP2-7 had no more): the older is told it
|
||||
// signed in elsewhere
|
||||
for _, o := range s.sessionsOf(u.ID) {
|
||||
o.do(func() {
|
||||
o.k.send("OUT", "OTH")
|
||||
o.close()
|
||||
})
|
||||
}
|
||||
if err := ns.loadLists(); err != nil {
|
||||
s.B.Log.Printf("node %d: msn: lists: %v", n.Num, err)
|
||||
}
|
||||
s.register(ns)
|
||||
s.B.Log.Printf("node %d: %s on MSN (%s, MSNP%d)", n.Num, u.Name, host, ns.ver)
|
||||
defer func() {
|
||||
ns.close()
|
||||
s.unregister(ns)
|
||||
s.leaveSwitchboards(ns)
|
||||
n.Leave()
|
||||
s.B.Log.Printf("node %d: gone (msn)", n.Num)
|
||||
s.changed(u)
|
||||
}()
|
||||
ok := []string{"USR", ns.loginTrid, "OK", ns.handle, encode(ns.friendly)}
|
||||
if ns.ver >= 6 {
|
||||
ok = append(ok, "1") // its e-mail address verified
|
||||
}
|
||||
ns.k.send(ok...)
|
||||
ns.profile()
|
||||
go ns.events()
|
||||
ns.serve()
|
||||
}
|
||||
|
||||
// signIn is VER, INF, CVR and USR, up to a user checked (false: it failed;
|
||||
// the connection is closed).
|
||||
func (ns *nsSession) signIn(c *cmd) bool {
|
||||
s := ns.s
|
||||
var salt string
|
||||
var target *store.User
|
||||
for range 12 {
|
||||
switch c.name {
|
||||
case "VER":
|
||||
ns.ver = 0
|
||||
for _, a := range c.args {
|
||||
if v, ok := strings.CutPrefix(strings.ToUpper(a), "MSNP"); ok {
|
||||
if n, err := strconv.Atoi(v); err == nil && n >= minVersion && n <= maxVersion && n > ns.ver {
|
||||
ns.ver = n
|
||||
}
|
||||
}
|
||||
}
|
||||
if ns.ver == 0 {
|
||||
ns.k.send("VER", c.trid, "0")
|
||||
s.B.Log.Printf("msn: %s: a client for %s, which is not served (MSNP%d to %d are)",
|
||||
ns.host, strings.Join(c.args, " "), minVersion, maxVersion)
|
||||
return false
|
||||
}
|
||||
ns.k.send("VER", c.trid, fmt.Sprintf("MSNP%d", ns.ver))
|
||||
case "INF":
|
||||
ns.k.send("INF", c.trid, "MD5")
|
||||
case "CVR", "CVQ":
|
||||
ns.cvr(c)
|
||||
case "USR":
|
||||
pkg, stage := strings.ToUpper(c.arg(0)), strings.ToUpper(c.arg(1))
|
||||
switch {
|
||||
case pkg == "MD5" && stage == "I":
|
||||
ns.handle = c.arg(2)
|
||||
target = s.resolve(ns.handle)
|
||||
if target != nil {
|
||||
var err error
|
||||
if salt, err = s.B.Store.MSNSalt(target.ID); err != nil {
|
||||
s.B.Log.Printf("msn: the salt of %s: %v", target.Name, err)
|
||||
}
|
||||
}
|
||||
if salt == "" {
|
||||
salt = randomHex(10) // an unknown handle is challenged too; its sign-in fails
|
||||
}
|
||||
ns.k.send("USR", c.trid, "MD5", "S", salt)
|
||||
case pkg == "MD5" && stage == "S" && salt != "":
|
||||
ns.loginTrid = c.trid
|
||||
u, err := ns.md5Login(target, salt, c.arg(2))
|
||||
return ns.signedIn(c.trid, u, err)
|
||||
case pkg == "CTP" && stage == "I" && ns.ver == 2:
|
||||
ns.handle = c.arg(2)
|
||||
ns.loginTrid = c.trid
|
||||
u, err := ns.passwordLogin(c.arg(2), decode(c.arg(3)))
|
||||
return ns.signedIn(c.trid, u, err)
|
||||
default:
|
||||
ns.k.sendErr(errAuth, c.trid)
|
||||
return false
|
||||
}
|
||||
case "OUT":
|
||||
return false
|
||||
default:
|
||||
ns.k.sendErr(errNotLoggedIn, c.trid)
|
||||
}
|
||||
var err error
|
||||
if c, err = ns.k.read(); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// signedIn finishes a sign-in: the user, or the error told (false).
|
||||
func (ns *nsSession) signedIn(trid string, u *store.User, err error) bool {
|
||||
if err == nil {
|
||||
err = ns.s.may(u)
|
||||
}
|
||||
if err != nil {
|
||||
code := errAuth
|
||||
if errors.Is(err, bbs.ErrNotAllowed) {
|
||||
code = errNotAllowed
|
||||
}
|
||||
ns.k.sendErr(code, trid)
|
||||
return false
|
||||
}
|
||||
ns.u = u
|
||||
ns.friendly = u.Name
|
||||
if !strings.Contains(ns.handle, "@") {
|
||||
ns.handle = ns.s.handleOf(u)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// md5Login checks an MD5 sign-in's digest against the account's.
|
||||
func (ns *nsSession) md5Login(target *store.User, salt, digest string) (*store.User, error) {
|
||||
s := ns.s
|
||||
name := ns.handle
|
||||
if target != nil {
|
||||
name = target.Name
|
||||
}
|
||||
var stale bool
|
||||
u, err := s.B.AuthenticateBy("msn", "ip:"+ns.host, name, func() (*store.User, error) {
|
||||
if target == nil {
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
ksalt, d, ok, err := s.B.Store.MSNKey(target.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok || ksalt != salt {
|
||||
stale = true
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(d), []byte(strings.ToLower(digest))) != 1 {
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
return target, nil
|
||||
})
|
||||
if stale && target != nil {
|
||||
s.B.Log.Printf("msn: %s: %s has no MSN password digest yet: log in once by another way "+
|
||||
"(telnet, IRC, AIM, the web) or set the password again", ns.host, target.Name)
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
|
||||
// passwordLogin checks a password sent in the clear (CTP, MSN 1.0).
|
||||
func (ns *nsSession) passwordLogin(handle, pw string) (*store.User, error) {
|
||||
name := handle
|
||||
if u := ns.s.resolve(handle); u != nil {
|
||||
name = u.Name
|
||||
}
|
||||
return ns.s.B.Authenticate("msn", "ip:"+ns.host, name, pw)
|
||||
}
|
||||
|
||||
// cvr answers a client's version: whatever it is, it is current.
|
||||
func (ns *nsSession) cvr(c *cmd) {
|
||||
v := c.arg(5)
|
||||
if v == "" {
|
||||
v = "1.0.0863"
|
||||
}
|
||||
site := ns.s.S.Site
|
||||
if site == "" {
|
||||
site = "http://" + ns.s.S.Domain + "/"
|
||||
}
|
||||
ns.k.send("CVR", c.trid, v, v, v, site, site)
|
||||
}
|
||||
|
||||
// profile is the initial profile message after sign-in.
|
||||
func (ns *nsSession) profile() {
|
||||
p := fmt.Sprintf("MIME-Version: 1.0\r\nContent-Type: text/x-msmsgsprofile; charset=UTF-8\r\n"+
|
||||
"LoginTime: %d\r\nEmailEnabled: 0\r\nMemberIdHigh: 0\r\nMemberIdLow: %d\r\n"+
|
||||
"lang_preference: 1033\r\npreferredEmail: \r\ncountry: \r\nPostalCode: \r\nGender: \r\n"+
|
||||
"Kid: 0\r\nAge: \r\nsid: 507\r\nkv: 2\r\nMSPAuth: %s\r\nClientIP: %s\r\nClientPort: 0\r\n\r\n",
|
||||
time.Now().Unix(), ns.u.ID, randomHex(16), ns.host)
|
||||
ns.k.sendPayload([]byte(p), "MSG", "Hotmail", "Hotmail")
|
||||
}
|
||||
|
||||
// closed reports that the session is over.
|
||||
func (ns *nsSession) closed() bool {
|
||||
select {
|
||||
case <-ns.done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// close ends the session.
|
||||
func (ns *nsSession) close() {
|
||||
ns.once.Do(func() {
|
||||
close(ns.done)
|
||||
ns.k.close()
|
||||
})
|
||||
}
|
||||
|
||||
// do has the session's goroutine do f (dropped if too much waits).
|
||||
func (ns *nsSession) do(f func()) {
|
||||
select {
|
||||
case ns.todo <- f:
|
||||
case <-ns.done:
|
||||
default:
|
||||
ns.s.B.Log.Printf("node %d: msn: too much waiting; dropped", ns.n.Num)
|
||||
}
|
||||
}
|
||||
|
||||
// online: it has set a status (its first CHG).
|
||||
func (ns *nsSession) online() bool {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
return ns.status != ""
|
||||
}
|
||||
|
||||
// statusNow is its status ("" before its first CHG).
|
||||
func (ns *nsSession) statusNow() string {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
return ns.status
|
||||
}
|
||||
|
||||
// friendlyName is its display name.
|
||||
func (ns *nsSession) friendlyName() string {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
return ns.friendly
|
||||
}
|
||||
|
||||
// events gives the client what its node is told, and does what the
|
||||
// server asks of the session, until it goes.
|
||||
func (ns *nsSession) events() {
|
||||
for {
|
||||
select {
|
||||
case <-ns.done:
|
||||
return
|
||||
case f := <-ns.todo:
|
||||
f()
|
||||
case <-ns.n.Wake():
|
||||
if !ns.online() {
|
||||
continue // held until it sets a status (its first CHG drains them)
|
||||
}
|
||||
ns.drain()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// drain gives the client the node's events waiting.
|
||||
func (ns *nsSession) drain() {
|
||||
for _, e := range ns.n.Pending() {
|
||||
ns.event(e)
|
||||
}
|
||||
}
|
||||
|
||||
// serve reads the client's commands until it goes.
|
||||
func (ns *nsSession) serve() {
|
||||
for {
|
||||
ns.k.c.SetDeadline(time.Now().Add(idleTimeout))
|
||||
c, err := ns.k.read()
|
||||
if err != nil {
|
||||
if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && !ns.closed() {
|
||||
ns.s.B.Log.Printf("node %d: msn: %v", ns.n.Num, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if c.name == "" {
|
||||
continue
|
||||
}
|
||||
if c.name == "OUT" {
|
||||
ns.k.send("OUT")
|
||||
return
|
||||
}
|
||||
done := make(chan struct{})
|
||||
ns.do(func() {
|
||||
defer close(done)
|
||||
ns.command(c)
|
||||
})
|
||||
select {
|
||||
case <-done:
|
||||
case <-ns.done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// command does a command (in the session's goroutine).
|
||||
func (ns *nsSession) command(c *cmd) {
|
||||
k := ns.k
|
||||
switch c.name {
|
||||
case "PNG":
|
||||
k.send("QNG")
|
||||
case "CVR", "CVQ":
|
||||
ns.cvr(c)
|
||||
case "INF":
|
||||
k.send("INF", c.trid, "MD5")
|
||||
case "SYN":
|
||||
ns.syn(c)
|
||||
case "LST":
|
||||
ns.lst(c)
|
||||
case "LSG":
|
||||
ns.lsg(c)
|
||||
case "CHG":
|
||||
ns.chg(c)
|
||||
case "ADD":
|
||||
ns.add(c)
|
||||
case "REM":
|
||||
ns.rem(c)
|
||||
case "REA":
|
||||
ns.rea(c)
|
||||
case "ADG", "RMG", "REG":
|
||||
ns.group(c)
|
||||
case "BLP":
|
||||
if m := strings.ToUpper(c.arg(0)); m == "AL" || m == "BL" {
|
||||
ns.mu.Lock()
|
||||
ns.blp = m
|
||||
ns.mu.Unlock()
|
||||
k.send("BLP", c.trid, ns.bumpVer(), m)
|
||||
ns.s.changed(ns.u)
|
||||
} else {
|
||||
k.sendErr(errBadParam, c.trid)
|
||||
}
|
||||
case "GTC":
|
||||
if m := strings.ToUpper(c.arg(0)); m == "A" || m == "N" {
|
||||
ns.mu.Lock()
|
||||
ns.gtc = m
|
||||
ns.mu.Unlock()
|
||||
k.send("GTC", c.trid, ns.bumpVer(), m)
|
||||
} else {
|
||||
k.sendErr(errBadParam, c.trid)
|
||||
}
|
||||
case "XFR":
|
||||
if strings.ToUpper(c.arg(0)) != "SB" {
|
||||
k.sendErr(errBadParam, c.trid)
|
||||
return
|
||||
}
|
||||
if st := ns.statusNow(); st == "" || st == "HDN" {
|
||||
k.sendErr(errNoSB, c.trid) // offline or hidden: no conversations
|
||||
return
|
||||
}
|
||||
sb := ns.s.newSwitchboard()
|
||||
ck := ns.s.newCookie(sb, ns, "")
|
||||
k.send("XFR", c.trid, "SB", ns.s.reachHost(k.c), "CKI", ck)
|
||||
case "QRY":
|
||||
k.send("QRY", c.trid)
|
||||
case "URL":
|
||||
if ns.s.S.Site == "" {
|
||||
k.sendErr(errDisabled, c.trid)
|
||||
return
|
||||
}
|
||||
k.send("URL", c.trid, ns.s.S.Site, ns.s.S.Site, "2")
|
||||
case "SND", "SDC", "FND", "PAG", "IMS":
|
||||
k.sendErr(errDisabled, c.trid)
|
||||
case "USR", "VER":
|
||||
k.sendErr(errSyntax, c.trid)
|
||||
default:
|
||||
k.sendErr(errSyntax, c.trid)
|
||||
}
|
||||
}
|
||||
|
||||
// chg sets its status; the first also tells it who of its friends is on,
|
||||
// and gives it what was kept for it.
|
||||
func (ns *nsSession) chg(c *cmd) {
|
||||
st := strings.ToUpper(c.arg(0))
|
||||
if st == "FLN" {
|
||||
st = "HDN"
|
||||
}
|
||||
if _, ok := statuses[st]; !ok {
|
||||
ns.k.sendErr(errBadParam, c.trid)
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
first := ns.status == ""
|
||||
ns.status = st
|
||||
ns.mu.Unlock()
|
||||
ns.k.send("CHG", c.trid, c.arg(0))
|
||||
doing := "MSN"
|
||||
if st != "NLN" {
|
||||
doing += " (" + statuses[st] + ")"
|
||||
}
|
||||
ns.n.Doing(doing)
|
||||
if first {
|
||||
ns.allContacts(c.trid)
|
||||
ns.drain()
|
||||
ns.deliverKept()
|
||||
}
|
||||
ns.s.changed(ns.u)
|
||||
}
|
||||
|
||||
// bumpVer is the list version after a change.
|
||||
func (ns *nsSession) bumpVer() string {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
ns.listVer++
|
||||
return strconv.Itoa(ns.listVer)
|
||||
}
|
||||
|
||||
// ver is the list version now.
|
||||
func (ns *nsSession) verNow() string {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
return strconv.Itoa(ns.listVer)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
// statusFor is the status viewer sees of u ("": offline). A user blocking
|
||||
// the viewer, appearing offline, or (BLP BL) not having the viewer as a
|
||||
// friend is offline to them; one on MSN has the status they set there;
|
||||
// one on the BBS by any other route is online.
|
||||
func (s *Server) statusFor(u, viewer *store.User) string {
|
||||
if s.B.Blocks(u, viewer) {
|
||||
return ""
|
||||
}
|
||||
best := ""
|
||||
for _, ns := range s.sessionsOf(u.ID) {
|
||||
ns.mu.Lock()
|
||||
st, blp := ns.status, ns.blp
|
||||
ns.mu.Unlock()
|
||||
if st == "" {
|
||||
continue
|
||||
}
|
||||
if st == "HDN" {
|
||||
return ""
|
||||
}
|
||||
if blp == "BL" {
|
||||
if ok, _ := s.B.Store.IsFriend(u.ID, viewer.ID); !ok {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
if best == "" || st == "NLN" {
|
||||
best = st
|
||||
}
|
||||
}
|
||||
if best != "" {
|
||||
return best
|
||||
}
|
||||
for _, n := range s.nodesOf(u.Name) {
|
||||
if s.onNode(n.Num) == nil {
|
||||
return "NLN"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// friendlyFor is u's display name: as set on MSN, or their name.
|
||||
func (s *Server) friendlyFor(u *store.User) string {
|
||||
for _, ns := range s.sessionsOf(u.ID) {
|
||||
if f := ns.friendlyName(); f != "" {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return u.Name
|
||||
}
|
||||
|
||||
// renamed: a user's display name changed: those watching them are told.
|
||||
func (s *Server) renamed(u *store.User) {
|
||||
for _, x := range s.all() {
|
||||
x.do(func() {
|
||||
x.mu.Lock()
|
||||
_, ok := x.fl[u.ID]
|
||||
st := x.told[u.ID]
|
||||
x.mu.Unlock()
|
||||
if ok && st != "" && x.online() {
|
||||
x.k.send("NLN", st, s.handleOf(u), encode(s.friendlyFor(u)))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// allContacts tells a client signing in which of its friends are on (ILN,
|
||||
// on its first CHG's transaction).
|
||||
func (ns *nsSession) allContacts(trid string) {
|
||||
ns.mu.Lock()
|
||||
fs := make([]store.Friend, 0, len(ns.fl))
|
||||
for _, f := range ns.fl {
|
||||
fs = append(fs, f)
|
||||
}
|
||||
ns.mu.Unlock()
|
||||
for _, f := range fs {
|
||||
u, err := ns.s.B.Store.UserByID(f.ID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
st := ns.s.statusFor(u, ns.u)
|
||||
ns.mu.Lock()
|
||||
ns.told[f.ID] = st
|
||||
ns.mu.Unlock()
|
||||
if st != "" {
|
||||
ns.k.send("ILN", trid, st, ns.s.handleOf(u), encode(ns.s.friendlyFor(u)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// contactChanged tells the client a friend's status, if it differs from
|
||||
// what it was last told.
|
||||
func (ns *nsSession) contactChanged(u *store.User) {
|
||||
if u.ID == ns.u.ID || !ns.online() {
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
_, ok := ns.fl[u.ID]
|
||||
was := ns.told[u.ID]
|
||||
ns.mu.Unlock()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st := ns.s.statusFor(u, ns.u)
|
||||
if st == was {
|
||||
return
|
||||
}
|
||||
ns.mu.Lock()
|
||||
ns.told[u.ID] = st
|
||||
ns.mu.Unlock()
|
||||
if st == "" {
|
||||
ns.k.send("FLN", ns.s.handleOf(u))
|
||||
return
|
||||
}
|
||||
ns.k.send("NLN", st, ns.s.handleOf(u), encode(ns.s.friendlyFor(u)))
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
// A switchboard is a conversation: the MSN clients joined to it, each by
|
||||
// a connection of its own, and the BBS users in it by other routes (IRC,
|
||||
// AIM, a terminal), who are "virtual": what is said goes to them as
|
||||
// private messages, and theirs comes back into it.
|
||||
|
||||
// switchboard is one conversation.
|
||||
type switchboard struct {
|
||||
id string
|
||||
s *Server
|
||||
|
||||
mu sync.Mutex
|
||||
joined []*sbConn
|
||||
virtual []*virtual
|
||||
invited map[int64]bool // users rung and not yet answered
|
||||
queue map[int64][][]byte // MSG lines waiting for a user to answer
|
||||
closed bool
|
||||
}
|
||||
|
||||
// virtual is one in a conversation by another route (u nil: the BBS's
|
||||
// notices).
|
||||
type virtual struct {
|
||||
u *store.User
|
||||
handle string
|
||||
friendly string
|
||||
}
|
||||
|
||||
// sbConn is an MSN client's connection to a switchboard.
|
||||
type sbConn struct {
|
||||
k *conn
|
||||
sb *switchboard
|
||||
ns *nsSession
|
||||
handle string
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// sbCookie lets a client join a switchboard: by USR (the one that asked
|
||||
// for it) or ANS (one rung).
|
||||
type sbCookie struct {
|
||||
sb *switchboard
|
||||
ns *nsSession
|
||||
answer bool
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// newSwitchboard makes a conversation.
|
||||
func (s *Server) newSwitchboard() *switchboard {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
sb := &switchboard{id: strconv.Itoa(s.nextSB), s: s, invited: map[int64]bool{}, queue: map[int64][][]byte{}}
|
||||
s.nextSB++
|
||||
s.sbs[sb.id] = sb
|
||||
return sb
|
||||
}
|
||||
|
||||
// newCookie is a cookie to join sb, for ns's client.
|
||||
func (s *Server) newCookie(sb *switchboard, ns *nsSession, kind string) string {
|
||||
ck := fmt.Sprintf("%d.%d", time.Now().UnixNano()%1000000000, randomNum())
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for key, v := range s.cookies {
|
||||
if time.Now().After(v.expires) {
|
||||
delete(s.cookies, key)
|
||||
}
|
||||
}
|
||||
s.cookies[ck] = &sbCookie{sb: sb, ns: ns, answer: kind == "ans", expires: time.Now().Add(cookieLife)}
|
||||
return ck
|
||||
}
|
||||
|
||||
// randomNum is a random decimal number of 10 digits.
|
||||
func randomNum() uint64 {
|
||||
h := randomHex(8)
|
||||
n, _ := strconv.ParseUint(h, 16, 64)
|
||||
return n%9000000000 + 1000000000
|
||||
}
|
||||
|
||||
// takeCookie spends a cookie (nil: none such, or expired).
|
||||
func (s *Server) takeCookie(ck string) *sbCookie {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
k := s.cookies[ck]
|
||||
delete(s.cookies, ck)
|
||||
if k == nil || time.Now().After(k.expires) {
|
||||
return nil
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
// switchboardConn serves a client's switchboard connection, begun with
|
||||
// first (USR or ANS).
|
||||
func (s *Server) switchboardConn(k *conn, host string, first *cmd) {
|
||||
var ck *sbCookie
|
||||
var handle string
|
||||
switch first.name {
|
||||
case "USR":
|
||||
handle = first.arg(0)
|
||||
ck = s.takeCookie(first.arg(1))
|
||||
if ck != nil && ck.answer {
|
||||
ck = nil
|
||||
}
|
||||
case "ANS":
|
||||
handle = first.arg(0)
|
||||
ck = s.takeCookie(first.arg(1))
|
||||
if ck != nil && (!ck.answer || ck.sb.id != first.arg(2)) {
|
||||
ck = nil
|
||||
}
|
||||
}
|
||||
if ck == nil || ck.ns.closed() {
|
||||
k.sendErr(errAuth, first.trid)
|
||||
return
|
||||
}
|
||||
if u := s.resolve(handle); u == nil || u.ID != ck.ns.u.ID {
|
||||
k.sendErr(errAuth, first.trid)
|
||||
return
|
||||
}
|
||||
sc := &sbConn{k: k, sb: ck.sb, ns: ck.ns, handle: ck.ns.handle}
|
||||
if !ck.sb.join(sc, first) {
|
||||
k.sendErr(errNoSB, first.trid)
|
||||
return
|
||||
}
|
||||
defer sc.leave(false)
|
||||
for {
|
||||
k.c.SetDeadline(time.Now().Add(sbIdle))
|
||||
c, err := k.read()
|
||||
if err != nil {
|
||||
var ne net.Error
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
sc.leave(true)
|
||||
} else if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) {
|
||||
s.B.Log.Printf("node %d: msn switchboard: %v", sc.ns.n.Num, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
switch c.name {
|
||||
case "":
|
||||
case "OUT":
|
||||
return
|
||||
case "CAL":
|
||||
sc.call(c)
|
||||
case "MSG":
|
||||
sc.msg(c)
|
||||
default:
|
||||
k.sendErr(errSyntax, c.trid)
|
||||
}
|
||||
if sc.ns.closed() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// join puts a client in the conversation: USR, the one that asked for
|
||||
// it; ANS, one rung, who is told who is there (IRO) and the others that
|
||||
// it came (JOI).
|
||||
func (sb *switchboard) join(sc *sbConn, first *cmd) bool {
|
||||
sb.mu.Lock()
|
||||
if sb.closed {
|
||||
sb.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
friendly := encode(sc.ns.friendlyName())
|
||||
uid := sc.ns.u.ID
|
||||
if first.name == "USR" {
|
||||
sb.joined = append(sb.joined, sc)
|
||||
sb.mu.Unlock()
|
||||
sc.k.send("USR", first.trid, "OK", sc.handle, friendly)
|
||||
return true
|
||||
}
|
||||
var others [][2]string
|
||||
for _, o := range sb.joined {
|
||||
others = append(others, [2]string{o.handle, encode(o.ns.friendlyName())})
|
||||
}
|
||||
for _, v := range sb.virtual {
|
||||
others = append(others, [2]string{v.handle, encode(v.friendly)})
|
||||
}
|
||||
tell := append([]*sbConn(nil), sb.joined...)
|
||||
sb.joined = append(sb.joined, sc)
|
||||
delete(sb.invited, uid)
|
||||
queued := sb.queue[uid]
|
||||
delete(sb.queue, uid)
|
||||
sb.mu.Unlock()
|
||||
for i, o := range others {
|
||||
sc.k.send("IRO", first.trid, strconv.Itoa(i+1), strconv.Itoa(len(others)), o[0], o[1])
|
||||
}
|
||||
sc.k.send("ANS", first.trid, "OK")
|
||||
for _, o := range tell {
|
||||
o.k.send("JOI", sc.handle, friendly)
|
||||
}
|
||||
for _, m := range queued {
|
||||
sc.k.write(m)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// leave takes a client out (timeout: for idling); the others are told,
|
||||
// and a conversation with no client left ends.
|
||||
func (sc *sbConn) leave(timeout bool) {
|
||||
sc.once.Do(func() {
|
||||
sb := sc.sb
|
||||
sb.mu.Lock()
|
||||
for i, o := range sb.joined {
|
||||
if o == sc {
|
||||
sb.joined = append(sb.joined[:i], sb.joined[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
rest := append([]*sbConn(nil), sb.joined...)
|
||||
empty := len(sb.joined) == 0 && len(sb.invited) == 0
|
||||
if empty {
|
||||
sb.closed = true
|
||||
}
|
||||
sb.mu.Unlock()
|
||||
for _, o := range rest {
|
||||
if timeout {
|
||||
o.k.send("BYE", sc.handle, "1")
|
||||
} else {
|
||||
o.k.send("BYE", sc.handle)
|
||||
}
|
||||
}
|
||||
if empty {
|
||||
sb.s.dropSwitchboard(sb)
|
||||
}
|
||||
sc.k.close()
|
||||
})
|
||||
}
|
||||
|
||||
// dropSwitchboard forgets a conversation.
|
||||
func (s *Server) dropSwitchboard(sb *switchboard) {
|
||||
s.mu.Lock()
|
||||
delete(s.sbs, sb.id)
|
||||
for key, v := range s.cookies {
|
||||
if v.sb == sb {
|
||||
delete(s.cookies, key)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// leaveSwitchboards takes a client that signed out out of its
|
||||
// conversations.
|
||||
func (s *Server) leaveSwitchboards(ns *nsSession) {
|
||||
s.mu.Lock()
|
||||
sbs := make([]*switchboard, 0, len(s.sbs))
|
||||
for _, sb := range s.sbs {
|
||||
sbs = append(sbs, sb)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, sb := range sbs {
|
||||
sb.mu.Lock()
|
||||
var mine []*sbConn
|
||||
for _, o := range sb.joined {
|
||||
if o.ns == ns {
|
||||
mine = append(mine, o)
|
||||
}
|
||||
}
|
||||
delete(sb.invited, ns.u.ID)
|
||||
delete(sb.queue, ns.u.ID)
|
||||
sb.mu.Unlock()
|
||||
for _, o := range mine {
|
||||
o.leave(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// has reports whether the user is in the conversation, joined, rung or
|
||||
// by another route.
|
||||
func (sb *switchboard) has(id int64) bool {
|
||||
for _, o := range sb.joined {
|
||||
if o.ns.u.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, v := range sb.virtual {
|
||||
if v.u != nil && v.u.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return sb.invited[id]
|
||||
}
|
||||
|
||||
// call is CAL: a user asked into the conversation. One on MSN is rung
|
||||
// (RNG) at each of their sessions; one on the BBS another way is in it at
|
||||
// once, by that route.
|
||||
func (sc *sbConn) call(c *cmd) {
|
||||
s := sc.sb.s
|
||||
t := s.resolve(c.arg(0))
|
||||
switch {
|
||||
case t == nil:
|
||||
sc.k.sendErr(errBadHandle, c.trid)
|
||||
return
|
||||
case t.ID == sc.ns.u.ID:
|
||||
sc.k.sendErr(errBadParam, c.trid)
|
||||
return
|
||||
}
|
||||
sb := sc.sb
|
||||
sb.mu.Lock()
|
||||
in := sb.has(t.ID)
|
||||
sb.mu.Unlock()
|
||||
if in {
|
||||
sc.k.sendErr(errAlreadyThere, c.trid)
|
||||
return
|
||||
}
|
||||
if s.statusFor(t, sc.ns.u) == "" {
|
||||
sc.k.sendErr(errNotOnline, c.trid)
|
||||
return
|
||||
}
|
||||
var ring []*nsSession
|
||||
for _, o := range s.sessionsOf(t.ID) {
|
||||
if st := o.statusNow(); st != "" && st != "HDN" {
|
||||
ring = append(ring, o)
|
||||
}
|
||||
}
|
||||
sc.k.send("CAL", c.trid, "RINGING", sb.id)
|
||||
if len(ring) > 0 {
|
||||
sb.mu.Lock()
|
||||
sb.invited[t.ID] = true
|
||||
sb.mu.Unlock()
|
||||
for _, o := range ring {
|
||||
sb.ring(o, sc.handle, sc.ns.friendlyName())
|
||||
}
|
||||
return
|
||||
}
|
||||
v := &virtual{u: t, handle: s.handleOf(t), friendly: t.Name}
|
||||
sb.mu.Lock()
|
||||
sb.virtual = append(sb.virtual, v)
|
||||
sb.mu.Unlock()
|
||||
sc.k.send("JOI", v.handle, encode(v.friendly))
|
||||
}
|
||||
|
||||
// ring has a client asked to answer the conversation (RNG), as from one
|
||||
// in it.
|
||||
func (sb *switchboard) ring(o *nsSession, fromHandle, fromFriendly string) {
|
||||
sb.expireInvite(o.u.ID)
|
||||
ck := sb.s.newCookie(sb, o, "ans")
|
||||
host := sb.s.reachHost(o.k.c)
|
||||
o.do(func() { o.k.send("RNG", sb.id, host, "CKI", ck, fromHandle, encode(fromFriendly)) })
|
||||
}
|
||||
|
||||
// msg is MSG: a message to the others. Text goes to each client in the
|
||||
// conversation and, as a private message, to those in it by other routes;
|
||||
// anything else (typing, invitations) only to the clients.
|
||||
func (sc *sbConn) msg(c *cmd) {
|
||||
ack := strings.ToUpper(c.arg(0))
|
||||
m := parseMIME(c.payload)
|
||||
text := ""
|
||||
if strings.HasPrefix(m.contentType(), "text/plain") {
|
||||
text = strings.Join(strings.Fields(strings.ReplaceAll(m.body, "\r\n", "\n")), " ")
|
||||
}
|
||||
sb := sc.sb
|
||||
sb.mu.Lock()
|
||||
var to []*sbConn
|
||||
for _, o := range sb.joined {
|
||||
if o != sc {
|
||||
to = append(to, o)
|
||||
}
|
||||
}
|
||||
vs := append([]*virtual(nil), sb.virtual...)
|
||||
sb.mu.Unlock()
|
||||
fail := func() {
|
||||
if ack == "A" || ack == "N" || ack == "D" {
|
||||
sc.k.send("NAK", c.trid)
|
||||
}
|
||||
}
|
||||
if len(to) == 0 && (text == "" || len(vs) == 0) {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
n := sc.ns.n
|
||||
if text != "" {
|
||||
if err := n.Throttle(); err != nil {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
}
|
||||
line := append([]byte(fmt.Sprintf("MSG %s %s %d\r\n", sc.handle, encode(sc.ns.friendlyName()), len(c.payload))),
|
||||
c.payload...)
|
||||
kept := map[int64]bool{}
|
||||
for _, o := range to {
|
||||
if text != "" && !kept[o.ns.u.ID] {
|
||||
kept[o.ns.u.ID] = true
|
||||
n.Keep(o.ns.u, text, true) // kept before it is seen
|
||||
}
|
||||
o.k.write(line)
|
||||
}
|
||||
ok := len(to) > 0
|
||||
for _, v := range vs {
|
||||
if v.u == nil || text == "" {
|
||||
continue
|
||||
}
|
||||
online, err := n.TellUser(v.u, text)
|
||||
switch {
|
||||
case errors.Is(err, bbs.ErrBlocked):
|
||||
continue
|
||||
case err != nil:
|
||||
sc.ns.s.B.Log.Printf("node %d: msn: to %s: %v", n.Num, v.u.Name, err)
|
||||
continue
|
||||
}
|
||||
ok = true
|
||||
if !online {
|
||||
sc.ns.noteAway(sc, v)
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
fail()
|
||||
return
|
||||
}
|
||||
if ack == "A" || ack == "D" {
|
||||
sc.k.send("ACK", c.trid)
|
||||
}
|
||||
}
|
||||
|
||||
// noteAway tells a client (once) that one it talks with went, and will
|
||||
// have its messages when they are next on.
|
||||
func (ns *nsSession) noteAway(sc *sbConn, v *virtual) {
|
||||
ns.mu.Lock()
|
||||
noted := ns.noted[v.u.ID]
|
||||
ns.noted[v.u.ID] = true
|
||||
ns.mu.Unlock()
|
||||
if noted {
|
||||
return
|
||||
}
|
||||
text := v.u.Name + " is not on now; they will have your messages when they next sign on."
|
||||
p := textPayload(text)
|
||||
sc.k.write(append([]byte(fmt.Sprintf("MSG %s %s %d\r\n", ns.s.systemHandle(), encode(ns.s.S.System), len(p))), p...))
|
||||
}
|
||||
|
||||
// fromOther gives a client a line from one in the conversation by another
|
||||
// route (or the BBS's notices): now if it has joined, else when it
|
||||
// answers.
|
||||
func (sb *switchboard) fromOther(ns *nsSession, v *virtual, text string) bool {
|
||||
p := textPayload(text)
|
||||
line := append([]byte(fmt.Sprintf("MSG %s %s %d\r\n", v.handle, encode(v.friendly), len(p))), p...)
|
||||
sb.mu.Lock()
|
||||
if sb.closed {
|
||||
sb.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
var to []*sbConn
|
||||
for _, o := range sb.joined {
|
||||
if o.ns == ns {
|
||||
to = append(to, o)
|
||||
}
|
||||
}
|
||||
if len(to) == 0 {
|
||||
if !sb.invited[ns.u.ID] {
|
||||
sb.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
sb.queue[ns.u.ID] = append(sb.queue[ns.u.ID], line)
|
||||
sb.mu.Unlock()
|
||||
return true
|
||||
}
|
||||
sb.mu.Unlock()
|
||||
for _, o := range to {
|
||||
o.k.write(line)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// virtualOf is the one by another route (handle) in the conversation
|
||||
// (nil: none).
|
||||
func (sb *switchboard) virtualOf(handle string) *virtual {
|
||||
for _, v := range sb.virtual {
|
||||
if strings.EqualFold(v.handle, handle) {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deliverFrom gives a client a line from one not on MSN (u nil: the BBS's
|
||||
// notices): into a conversation it has with them, or a new one it is rung
|
||||
// to.
|
||||
func (s *Server) deliverFrom(ns *nsSession, u *store.User, text string) {
|
||||
v := &virtual{handle: s.systemHandle(), friendly: s.S.System}
|
||||
if u != nil {
|
||||
v = &virtual{u: u, handle: s.handleOf(u), friendly: u.Name}
|
||||
}
|
||||
s.mu.Lock()
|
||||
var best *switchboard
|
||||
for _, sb := range s.sbs {
|
||||
sb.mu.Lock()
|
||||
mine := sb.invited[ns.u.ID]
|
||||
for _, o := range sb.joined {
|
||||
if o.ns == ns {
|
||||
mine = true
|
||||
}
|
||||
}
|
||||
if mine && sb.virtualOf(v.handle) != nil && !sb.closed {
|
||||
if best == nil || sbNewer(sb, best) {
|
||||
best = sb
|
||||
}
|
||||
}
|
||||
sb.mu.Unlock()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if best != nil {
|
||||
best.mu.Lock()
|
||||
if x := best.virtualOf(v.handle); x != nil {
|
||||
v = x
|
||||
}
|
||||
best.mu.Unlock()
|
||||
if best.fromOther(ns, v, text) {
|
||||
return
|
||||
}
|
||||
}
|
||||
sb := s.newSwitchboard()
|
||||
sb.mu.Lock()
|
||||
sb.virtual = append(sb.virtual, v)
|
||||
sb.invited[ns.u.ID] = true
|
||||
sb.mu.Unlock()
|
||||
sb.fromOther(ns, v, text)
|
||||
sb.expireInvite(ns.u.ID)
|
||||
ck := s.newCookie(sb, ns, "ans")
|
||||
ns.k.send("RNG", sb.id, s.reachHost(ns.k.c), "CKI", ck, v.handle, encode(v.friendly))
|
||||
}
|
||||
|
||||
// sbNewer: a was made after b.
|
||||
func sbNewer(a, b *switchboard) bool {
|
||||
x, _ := strconv.Atoi(a.id)
|
||||
y, _ := strconv.Atoi(b.id)
|
||||
return x > y
|
||||
}
|
||||
|
||||
// expireInvite forgets a user's invitation if they have not answered once
|
||||
// their cookie is spent; a conversation left with no one in it ends.
|
||||
func (sb *switchboard) expireInvite(id int64) {
|
||||
time.AfterFunc(cookieLife+time.Second, func() {
|
||||
sb.mu.Lock()
|
||||
if !sb.invited[id] || sb.closed {
|
||||
sb.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(sb.invited, id)
|
||||
delete(sb.queue, id)
|
||||
empty := len(sb.joined) == 0 && len(sb.invited) == 0
|
||||
if empty {
|
||||
sb.closed = true
|
||||
}
|
||||
sb.mu.Unlock()
|
||||
if empty {
|
||||
sb.s.dropSwitchboard(sb)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// Package msn is an MSN Messenger server (MSNP) for the BBS's chat, beside
|
||||
// its IRC and AIM servers: MSN Messenger clients sign in with BBS names
|
||||
// and passwords; their contact list is the user's friends list; an IM is
|
||||
// a private message (a PRIVMSG to an IRC user, a line on a caller's
|
||||
// terminal, an IM on AIM), kept for one away.
|
||||
//
|
||||
// It speaks MSNP2 to MSNP7: MSN Messenger 1.0 to 4.7 and Windows
|
||||
// Messenger 4.x, which sign in by MD5 (or, MSN 1.0, by the password in
|
||||
// the clear) over plain TCP. Later versions sign in by Passport over
|
||||
// HTTPS, not served here yet.
|
||||
//
|
||||
// One port (1863) serves the whole of it: the dispatch and notification
|
||||
// server (a client's first command is VER) and the switchboards, the
|
||||
// conversations (a client's first command is USR with a cookie, or ANS).
|
||||
package msn
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/sockets"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
"github.com/D-Modem/bbs/internal/tcpserv"
|
||||
)
|
||||
|
||||
// timeouts
|
||||
const (
|
||||
loginTimeout = time.Minute // to sign in, or to join a switchboard
|
||||
idleTimeout = 10 * time.Minute // without a command (clients PNG every 50 s or so)
|
||||
sbIdle = 30 * time.Minute // a switchboard connection without a command
|
||||
writeTimeout = 30 * time.Second
|
||||
cookieLife = 2 * time.Minute // a switchboard cookie is used within this
|
||||
queueLen = 512 // things waiting for a session's goroutine
|
||||
)
|
||||
|
||||
// the protocol versions served
|
||||
const (
|
||||
minVersion = 2
|
||||
maxVersion = 7
|
||||
)
|
||||
|
||||
// Settings are the [msn] section's.
|
||||
type Settings struct {
|
||||
Address string // where to listen
|
||||
// Host is where clients are sent for switchboards, host:port; "": the
|
||||
// address each one came to
|
||||
Host string
|
||||
// Domain makes users' handles: name@Domain. Clients may sign in with
|
||||
// any domain (MSN 1.0 only takes @hotmail.com).
|
||||
Domain string
|
||||
MaxClients int
|
||||
MaxPerIP int
|
||||
// System is the name the BBS's notices come from
|
||||
System string
|
||||
// Site is a web address for the client's links (its inbox, its
|
||||
// profile pages); "": none
|
||||
Site string
|
||||
}
|
||||
|
||||
// Server serves MSNP.
|
||||
type Server struct {
|
||||
B *bbs.BBS
|
||||
S Settings
|
||||
|
||||
mu sync.Mutex
|
||||
ns map[*nsSession]bool
|
||||
byNode map[int]*nsSession
|
||||
sbs map[string]*switchboard // by id
|
||||
cookies map[string]*sbCookie
|
||||
nextSB int
|
||||
}
|
||||
|
||||
// New checks the settings and makes the server.
|
||||
func New(b *bbs.BBS, s Settings) (*Server, error) {
|
||||
if s.Address == "" {
|
||||
return nil, errors.New("msn: no address to listen on")
|
||||
}
|
||||
if s.Host != "" {
|
||||
if _, _, err := net.SplitHostPort(s.Host); err != nil {
|
||||
return nil, fmt.Errorf("msn: host: %w", err)
|
||||
}
|
||||
}
|
||||
if s.Domain == "" {
|
||||
s.Domain = "bbs.invalid"
|
||||
}
|
||||
if s.System == "" {
|
||||
s.System = "BBS"
|
||||
}
|
||||
if s.MaxClients == 0 {
|
||||
s.MaxClients = 256
|
||||
}
|
||||
return &Server{B: b, S: s, ns: map[*nsSession]bool{}, byNode: map[int]*nsSession{},
|
||||
sbs: map[string]*switchboard{}, cookies: map[string]*sbCookie{}, nextSB: 1}, nil
|
||||
}
|
||||
|
||||
// Run listens until ctx is done.
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
ln, err := sockets.Listen("tcp", s.S.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("msn: %w", err)
|
||||
}
|
||||
return s.Serve(ctx, ln)
|
||||
}
|
||||
|
||||
// Serve answers on ln until ctx is done.
|
||||
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
||||
s.B.Store.SetKeepMSN(true)
|
||||
stop := s.B.WatchPresence(s.presence)
|
||||
defer stop()
|
||||
stopFriends := s.B.WatchFriends(s.friendsChanged)
|
||||
defer stopFriends()
|
||||
ts := &tcpserv.Server{Name: "msn", 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("msn", c.RemoteAddr()) }}
|
||||
return ts.Serve(ctx, ln)
|
||||
}
|
||||
|
||||
// Clients is how many are signed in.
|
||||
func (s *Server) Clients() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.ns)
|
||||
}
|
||||
|
||||
// handle serves a connection: a notification session, or a switchboard's.
|
||||
func (s *Server) handle(c net.Conn) {
|
||||
host, _, _ := net.SplitHostPort(c.RemoteAddr().String())
|
||||
k := newConn(c, bufio.NewReaderSize(c, 8192))
|
||||
c.SetDeadline(time.Now().Add(loginTimeout))
|
||||
first, err := k.read()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch first.name {
|
||||
case "VER":
|
||||
s.notification(k, host, first)
|
||||
case "USR", "ANS":
|
||||
s.switchboardConn(k, host, first)
|
||||
}
|
||||
}
|
||||
|
||||
// handleOf is a user's MSN handle: their name without its spaces, at the
|
||||
// domain.
|
||||
func (s *Server) handleOf(u *store.User) string {
|
||||
return strings.ReplaceAll(u.Name, " ", "") + "@" + s.S.Domain
|
||||
}
|
||||
|
||||
// systemHandle is the handle the BBS's notices come from.
|
||||
func (s *Server) systemHandle() string {
|
||||
return strings.ReplaceAll(s.S.System, " ", "") + "@" + s.S.Domain
|
||||
}
|
||||
|
||||
// resolve is the account a handle names: its part before the @, as a
|
||||
// name with or without its spaces, at any domain (nil: none).
|
||||
func (s *Server) resolve(handle string) *store.User {
|
||||
local, _, _ := strings.Cut(decode(handle), "@")
|
||||
local = strings.TrimSpace(local)
|
||||
if local == "" {
|
||||
return nil
|
||||
}
|
||||
u, err := s.B.Store.UserByScreenName(local)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// may: the user may use the chat.
|
||||
func (s *Server) may(u *store.User) error {
|
||||
if !s.B.LevelOf(u).Chat {
|
||||
return bbs.ErrNotAllowed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// register keeps a notification session on.
|
||||
func (s *Server) register(ns *nsSession) {
|
||||
s.mu.Lock()
|
||||
s.ns[ns] = true
|
||||
s.byNode[ns.n.Num] = ns
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// unregister forgets it.
|
||||
func (s *Server) unregister(ns *nsSession) {
|
||||
s.mu.Lock()
|
||||
delete(s.ns, ns)
|
||||
if s.byNode[ns.n.Num] == ns {
|
||||
delete(s.byNode, ns.n.Num)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// all are the notification sessions signed in.
|
||||
func (s *Server) all() []*nsSession {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]*nsSession, 0, len(s.ns))
|
||||
for ns := range s.ns {
|
||||
out = append(out, ns)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sessionsOf are a user's notification sessions.
|
||||
func (s *Server) sessionsOf(id int64) []*nsSession {
|
||||
var out []*nsSession
|
||||
for _, ns := range s.all() {
|
||||
if ns.u.ID == id {
|
||||
out = append(out, ns)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// onNode is the session on a node (nil: the node is another kind).
|
||||
func (s *Server) onNode(num int) *nsSession {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.byNode[num]
|
||||
}
|
||||
|
||||
// nodesOf are the nodes a user is on.
|
||||
func (s *Server) nodesOf(name string) []bbs.NodeInfo {
|
||||
var out []bbs.NodeInfo
|
||||
for _, n := range s.B.Nodes() {
|
||||
if n.User != "" && strings.EqualFold(n.User, name) {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// presence is told of a BBS user coming online or going.
|
||||
func (s *Server) presence(name string, online bool) {
|
||||
if len(s.all()) == 0 {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
u, err := s.B.Store.UserByName(name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.changed(u)
|
||||
}()
|
||||
}
|
||||
|
||||
// changed has every session told the user's state anew (where it
|
||||
// differs from what it was told).
|
||||
func (s *Server) changed(u *store.User) {
|
||||
for _, x := range s.all() {
|
||||
x.do(func() { x.contactChanged(u) })
|
||||
}
|
||||
}
|
||||
|
||||
// friendsChanged is told that a user's friends or blocked list changed:
|
||||
// their own sessions sync their lists, the others their reverse lists and
|
||||
// what they see of them.
|
||||
func (s *Server) friendsChanged(user int64) {
|
||||
go func() {
|
||||
u, err := s.B.Store.UserByID(user)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, x := range s.all() {
|
||||
if x.u.ID == user {
|
||||
x.do(x.syncLists)
|
||||
} else {
|
||||
x.do(func() { x.reverseChanged(u) })
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// randomHex is n random bytes, in hex.
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// reachHost is where a client on conn is sent for a switchboard.
|
||||
func (s *Server) reachHost(c net.Conn) string {
|
||||
if s.S.Host != "" {
|
||||
return s.S.Host
|
||||
}
|
||||
return c.LocalAddr().String()
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package msn
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// limits
|
||||
const (
|
||||
maxLine = 2048 // a command line's bytes
|
||||
maxPayload = 64 << 10 // a payload's (MSG, QRY)
|
||||
)
|
||||
|
||||
// cmd is a command a client sent: its name, transaction id and arguments,
|
||||
// and its payload, for those with one.
|
||||
type cmd struct {
|
||||
name string
|
||||
trid string
|
||||
args []string
|
||||
payload []byte
|
||||
}
|
||||
|
||||
// arg is the i'th argument ("": none).
|
||||
func (c *cmd) arg(i int) string {
|
||||
if i < len(c.args) {
|
||||
return c.args[i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// payloadCmds are those a client sends with a payload, its length last.
|
||||
var payloadCmds = map[string]bool{"MSG": true, "QRY": true, "UUX": true, "ADL": true, "RML": true,
|
||||
"UUN": true, "UUM": true, "PAG": true, "SDC": true, "NOT": true, "FQY": true}
|
||||
|
||||
var errLine = errors.New("msn: bad command line")
|
||||
|
||||
// conn is a client's connection: commands in, lines out.
|
||||
type conn struct {
|
||||
c net.Conn
|
||||
r *bufio.Reader
|
||||
mu sync.Mutex // writes
|
||||
}
|
||||
|
||||
func newConn(c net.Conn, r *bufio.Reader) *conn { return &conn{c: c, r: r} }
|
||||
|
||||
// read is the next command.
|
||||
func (k *conn) read() (*cmd, error) {
|
||||
line, err := k.r.ReadSlice('\n')
|
||||
if errors.Is(err, bufio.ErrBufferFull) || len(line) > maxLine {
|
||||
return nil, errLine
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f := strings.Fields(strings.TrimRight(string(line), "\r\n"))
|
||||
if len(f) == 0 {
|
||||
return &cmd{}, nil
|
||||
}
|
||||
c := &cmd{name: strings.ToUpper(f[0])}
|
||||
if len(f) > 1 {
|
||||
c.trid = f[1]
|
||||
c.args = f[2:]
|
||||
}
|
||||
if payloadCmds[c.name] && len(f) >= 3 {
|
||||
n, err := strconv.Atoi(f[len(f)-1])
|
||||
if err != nil || n < 0 || n > maxPayload {
|
||||
return nil, errLine
|
||||
}
|
||||
c.payload = make([]byte, n)
|
||||
if _, err := readFull(k.r, c.payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func readFull(r *bufio.Reader, b []byte) (int, error) {
|
||||
n := 0
|
||||
for n < len(b) {
|
||||
m, err := r.Read(b[n:])
|
||||
n += m
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// send writes a line (its words joined by spaces).
|
||||
func (k *conn) send(words ...string) error {
|
||||
return k.write([]byte(strings.Join(words, " ") + "\r\n"))
|
||||
}
|
||||
|
||||
// sendPayload writes a line ending in the payload's length, and the
|
||||
// payload.
|
||||
func (k *conn) sendPayload(payload []byte, words ...string) error {
|
||||
line := strings.Join(append(words, strconv.Itoa(len(payload))), " ") + "\r\n"
|
||||
return k.write(append([]byte(line), payload...))
|
||||
}
|
||||
|
||||
// sendErr writes an error's number for a transaction.
|
||||
func (k *conn) sendErr(code int, trid string) error { return k.send(strconv.Itoa(code), trid) }
|
||||
|
||||
func (k *conn) write(b []byte) error {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
k.c.SetWriteDeadline(time.Now().Add(writeTimeout))
|
||||
_, err := k.c.Write(b)
|
||||
return err
|
||||
}
|
||||
|
||||
func (k *conn) close() { k.c.Close() }
|
||||
|
||||
// error numbers
|
||||
const (
|
||||
errSyntax = 200
|
||||
errBadParam = 201
|
||||
errNoSuchUser = 205
|
||||
errNoDomain = 206
|
||||
errBadHandle = 208
|
||||
errBadFriendly = 209
|
||||
errListFull = 210
|
||||
errAlreadyThere = 215
|
||||
errNotOnList = 216
|
||||
errNotOnline = 217
|
||||
errInOpposite = 219
|
||||
errBadGroup = 224
|
||||
errNotInGroup = 225
|
||||
errGroupName = 228
|
||||
errNoSB = 280
|
||||
errNotLoggedIn = 302
|
||||
errInternal = 500
|
||||
errDisabled = 502
|
||||
errBusy = 600
|
||||
errRate = 800
|
||||
errAuth = 911
|
||||
errNotAllowed = 913
|
||||
)
|
||||
|
||||
// encode is a name as MSNP carries it: URL encoded (a space %20, every
|
||||
// byte that is not printable ASCII, and %).
|
||||
func encode(s string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c <= ' ' || c >= 0x7f || c == '%' {
|
||||
fmt.Fprintf(&b, "%%%02X", c)
|
||||
continue
|
||||
}
|
||||
b.WriteByte(c)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// decode is a URL-encoded name in the clear (as it was, if it is not
|
||||
// well encoded).
|
||||
func decode(s string) string {
|
||||
if !strings.Contains(s, "%") {
|
||||
return s
|
||||
}
|
||||
var b []byte
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '%' && i+2 < len(s) {
|
||||
if v, err := strconv.ParseUint(s[i+1:i+3], 16, 8); err == nil {
|
||||
b = append(b, byte(v))
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
}
|
||||
b = append(b, s[i])
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// mime is a MSG payload: its headers, by lower-case name, and its body.
|
||||
type mime struct {
|
||||
headers map[string]string
|
||||
body string
|
||||
}
|
||||
|
||||
// parseMIME reads a MSG payload.
|
||||
func parseMIME(p []byte) mime {
|
||||
m := mime{headers: map[string]string{}}
|
||||
s := string(p)
|
||||
head, body, ok := strings.Cut(s, "\r\n\r\n")
|
||||
if !ok {
|
||||
head, body, _ = strings.Cut(s, "\n\n")
|
||||
}
|
||||
m.body = body
|
||||
for _, l := range strings.Split(head, "\n") {
|
||||
k, v, ok := strings.Cut(strings.TrimRight(l, "\r"), ":")
|
||||
if ok {
|
||||
m.headers[strings.ToLower(strings.TrimSpace(k))] = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// contentType is the payload's media type, lower case, without its
|
||||
// parameters.
|
||||
func (m mime) contentType() string {
|
||||
t, _, _ := strings.Cut(m.headers["content-type"], ";")
|
||||
return strings.ToLower(strings.TrimSpace(t))
|
||||
}
|
||||
|
||||
// textPayload is a plain text message's payload.
|
||||
func textPayload(text string) []byte {
|
||||
return []byte("MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n" +
|
||||
"X-MMS-IM-Format: FN=MS%20Sans%20Serif; EF=; CO=0; CS=0; PF=0\r\n\r\n" + text)
|
||||
}
|
||||
@@ -176,6 +176,9 @@ func (ss *session) deliver(u *store.User, ck []byte, raw string, isHTML, auto bo
|
||||
if plain == "" {
|
||||
return nil
|
||||
}
|
||||
if ss.s.B.Blocks(u, ss.u) {
|
||||
return errOffline // on their blocked list (any front end's)
|
||||
}
|
||||
for _, o := range ss.s.sessionsOf(u.ID) {
|
||||
if o.blocks(ss.u) {
|
||||
return errOffline
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"github.com/D-Modem/bbs/internal/ircd"
|
||||
"github.com/D-Modem/bbs/internal/logo"
|
||||
"github.com/D-Modem/bbs/internal/mrc"
|
||||
"github.com/D-Modem/bbs/internal/msn"
|
||||
"github.com/D-Modem/bbs/internal/nntp"
|
||||
"github.com/D-Modem/bbs/internal/oscar"
|
||||
"github.com/D-Modem/bbs/internal/phone"
|
||||
@@ -63,6 +64,7 @@ type Config struct {
|
||||
IRC *ircd.Settings // nil: no IRC server
|
||||
OSCAR *oscar.Settings // nil: no AIM/ICQ server
|
||||
AOL *aol.Settings // nil: no host for AOL clients
|
||||
MSN *msn.Settings // nil: no MSN Messenger server
|
||||
MRC *mrc.Settings // nil: not on Multi Relay Chat
|
||||
Screens *screens.Set // nil: no screens of the sysop's
|
||||
ScriptsDir string // "": no scripts
|
||||
@@ -144,6 +146,9 @@ func load(cf *config.File) (*Config, error) {
|
||||
if err := c.aolSection(cf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.msnSection(cf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.mrcSection(cf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -213,7 +218,7 @@ func load(cf *config.File) (*Config, error) {
|
||||
}
|
||||
for _, s := range cf.Sections {
|
||||
switch s.Kind {
|
||||
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "oscar", "aol", "mrc", "menu", "strings", "http", "level", "chan":
|
||||
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "irc", "oscar", "aol", "msn", "mrc", "menu", "strings", "http", "level", "chan":
|
||||
default:
|
||||
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/config"
|
||||
"github.com/D-Modem/bbs/internal/msn"
|
||||
)
|
||||
|
||||
// msnSection reads [msn]: the MSN Messenger server for the chat.
|
||||
func (c *Config) msnSection(cf *config.File) error {
|
||||
s := cf.Get("msn", "")
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
err := func() error {
|
||||
m := &msn.Settings{Address: s.String("address", ":1863"), Host: s.String("host", ""),
|
||||
Domain: strings.ToLower(s.String("domain", "")), System: s.String("system", "BBS"),
|
||||
Site: s.String("site", "")}
|
||||
if _, _, err := net.SplitHostPort(m.Address); err != nil {
|
||||
return fmt.Errorf("address: %v", err)
|
||||
}
|
||||
if m.Host != "" {
|
||||
if _, _, err := net.SplitHostPort(m.Host); err != nil {
|
||||
return fmt.Errorf("host: %v (host:port, where clients are sent for conversations)", err)
|
||||
}
|
||||
}
|
||||
if m.Domain != "" && (strings.ContainsAny(m.Domain, "@ /") || !strings.Contains(m.Domain, ".")) {
|
||||
return fmt.Errorf("domain: a domain name, as msn.example.org (handles are name@domain)")
|
||||
}
|
||||
if m.System == "" || len(m.System) > 32 || strings.ContainsAny(m.System, "@ ") {
|
||||
return fmt.Errorf("system: a name of 1 to 32 letters and digits")
|
||||
}
|
||||
if m.Site != "" && !strings.HasPrefix(m.Site, "http://") && !strings.HasPrefix(m.Site, "https://") {
|
||||
return fmt.Errorf("site: a web address (http:// or https://)")
|
||||
}
|
||||
var err error
|
||||
if m.MaxClients, err = s.Int("max_clients", 256, 1, 100000); err != nil {
|
||||
return err
|
||||
}
|
||||
// each client opens a connection per conversation
|
||||
if m.MaxPerIP, err = s.Int("max_per_ip", 16, 0, 1000); err != nil {
|
||||
return err
|
||||
}
|
||||
c.MSN = m
|
||||
return nil
|
||||
}()
|
||||
if err != nil {
|
||||
return fmt.Errorf("[msn] %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package store
|
||||
|
||||
// A user's blocked list: BBS users who may not reach them nor see them
|
||||
// online, the one list every front end that has one shares (MSN's Block
|
||||
// List; AIM's deny list keeps its own, in the feedbag, for now).
|
||||
|
||||
// Blocked are the users a user blocks, by name (Group and Alias unused).
|
||||
func (s *Store) Blocked(user int64) ([]Friend, error) {
|
||||
return s.friendRows(`SELECT b.blocked_id, u.name, '', '', b.added
|
||||
FROM blocks b JOIN users u ON u.id = b.blocked_id WHERE b.user_id = ? ORDER BY u.name`, user)
|
||||
}
|
||||
|
||||
// IsBlocked reports whether user blocks other.
|
||||
func (s *Store) IsBlocked(user, other int64) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRow(`SELECT COUNT(*) FROM blocks WHERE user_id = ? AND blocked_id = ?`, user, other).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// Block puts other on user's blocked list.
|
||||
func (s *Store) Block(user, other int64) error {
|
||||
_, err := s.db.Exec(`INSERT OR IGNORE INTO blocks (user_id, blocked_id, added) VALUES (?, ?, ?)`, user, other, now())
|
||||
return err
|
||||
}
|
||||
|
||||
// Unblock takes other off user's blocked list.
|
||||
func (s *Store) Unblock(user, other int64) error {
|
||||
_, err := s.db.Exec(`DELETE FROM blocks WHERE user_id = ? AND blocked_id = ?`, user, other)
|
||||
return err
|
||||
}
|
||||
|
||||
// FriendOf are the users who have user on their friends list, by name
|
||||
// (Group and Alias theirs).
|
||||
func (s *Store) FriendOf(user int64) ([]Friend, error) {
|
||||
return s.friendRows(`SELECT f.user_id, u.name, f.grp, f.alias, f.added
|
||||
FROM friends f JOIN users u ON u.id = f.user_id WHERE f.friend_id = ? ORDER BY u.name`, user)
|
||||
}
|
||||
|
||||
// friendRows reads (id, name, group, alias, added) rows.
|
||||
func (s *Store) friendRows(q string, args ...any) ([]Friend, error) {
|
||||
rows, err := s.db.Query(q, args...)
|
||||
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()
|
||||
}
|
||||
@@ -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", "chats", "friends", "oscar_buddies"}
|
||||
"chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys", "chats", "friends", "oscar_buddies", "msn_keys", "blocks"}
|
||||
|
||||
var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`)
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// MSN Messenger's MD5 login (MSNP2 to MSNP7: MSN 1.0 to 4.7) proves the
|
||||
// password by MD5(salt + password), the salt the server's, which a bcrypt
|
||||
// hash cannot check. So each account gets a fixed salt and the digest of
|
||||
// its password with it, kept whenever the password is known in the clear
|
||||
// and bound to the password hash it was made with, as the AIM digests are
|
||||
// (oscar.go). A fixed salt makes the digest replayable: anyone who sees
|
||||
// a login can log in again. MSN 1.0 to 4.7 had no better way.
|
||||
|
||||
// MSNDigest is an MD5 login's answer: MD5(salt + password), in lowercase
|
||||
// hex.
|
||||
func MSNDigest(salt, pw string) string {
|
||||
h := md5.Sum([]byte(salt + pw))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// SetKeepMSN says whether to keep the digests: only with an MSN server,
|
||||
// as they would let anyone who read the database log in by MSN.
|
||||
func (s *Store) SetKeepMSN(on bool) { s.keepMSN.Store(on) }
|
||||
|
||||
// MSNKey is the account's MD5 login salt and digest; ok false: no current
|
||||
// digest (none kept, or the password changed since).
|
||||
func (s *Store) MSNKey(id int64) (salt, digest string, ok bool, err error) {
|
||||
var bound, hash string
|
||||
err = s.db.QueryRow(`SELECT m.salt, m.digest, m.bound, u.password FROM msn_keys m
|
||||
JOIN users u ON u.id = m.user_id WHERE m.user_id = ?`, id).Scan(&salt, &digest, &bound, &hash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", false, err
|
||||
}
|
||||
return salt, digest, bound == hash && digest != "", nil
|
||||
}
|
||||
|
||||
// MSNSalt is the salt an MD5 login gives the account: its kept one, or a
|
||||
// new one kept for it (with no digest yet).
|
||||
func (s *Store) MSNSalt(id int64) (string, error) {
|
||||
var salt string
|
||||
err := s.db.QueryRow(`SELECT salt FROM msn_keys WHERE user_id = ?`, id).Scan(&salt)
|
||||
if err == nil {
|
||||
return salt, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return "", err
|
||||
}
|
||||
b := make([]byte, 10)
|
||||
rand.Read(b)
|
||||
salt = hex.EncodeToString(b)
|
||||
if _, err := s.db.Exec(`INSERT OR IGNORE INTO msn_keys (user_id, salt, digest, bound) VALUES (?, ?, '', '')`, id, salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// another login may have made one meanwhile
|
||||
err = s.db.QueryRow(`SELECT salt FROM msn_keys WHERE user_id = ?`, id).Scan(&salt)
|
||||
return salt, err
|
||||
}
|
||||
|
||||
// KeepMSNKey makes the account's MD5 login digest of pw (its password,
|
||||
// just checked or set), bound to its password hash now, if the store keeps
|
||||
// them (SetKeepMSN). Nothing is written if it is current already.
|
||||
func (s *Store) KeepMSNKey(id int64, pw string) error {
|
||||
if !s.keepMSN.Load() || pw == "" {
|
||||
return nil
|
||||
}
|
||||
var hash string
|
||||
if err := s.db.QueryRow(`SELECT password FROM users WHERE id = ?`, id).Scan(&hash); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
salt, err := s.MSNSalt(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := MSNDigest(salt, pw)
|
||||
if _, old, ok, err := s.MSNKey(id); err == nil && ok && old == d {
|
||||
return nil
|
||||
}
|
||||
_, err = s.db.Exec(`UPDATE msn_keys SET digest = ?, bound = ? WHERE user_id = ?`, d, hash, id)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMSNKeys: digests kept only when asked, made at a password's check,
|
||||
// stale once the password changes, made again (same salt) when it is set.
|
||||
func TestMSNKeys(t *testing.T) {
|
||||
BcryptCost = 4
|
||||
s, err := Open(filepath.Join(t.TempDir(), "bbs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
u, _ := s.CreateUser("alice", "password1", "", false)
|
||||
if _, _, ok, _ := s.MSNKey(u.ID); ok {
|
||||
t.Fatal("kept without SetKeepMSN")
|
||||
}
|
||||
s.SetKeepMSN(true)
|
||||
if _, err := s.CheckPassword("alice", "password1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
salt, d, ok, err := s.MSNKey(u.ID)
|
||||
if err != nil || !ok || salt == "" || d != MSNDigest(salt, "password1") {
|
||||
t.Fatalf("key %q %q %v %v", salt, d, ok, err)
|
||||
}
|
||||
if again, _ := s.MSNSalt(u.ID); again != salt {
|
||||
t.Errorf("salt changed: %q %q", salt, again)
|
||||
}
|
||||
s.db.Exec(`UPDATE users SET password = ? WHERE id = ?`, "x", u.ID)
|
||||
if _, _, ok, _ := s.MSNKey(u.ID); ok {
|
||||
t.Error("stale digest used")
|
||||
}
|
||||
s.SetPassword(u.ID, "password2")
|
||||
if salt2, d2, ok, _ := s.MSNKey(u.ID); !ok || salt2 != salt || d2 != MSNDigest(salt, "password2") {
|
||||
t.Errorf("after set: %q %q %v", salt2, d2, ok)
|
||||
}
|
||||
if MSNDigest("prefix", "password") != "61ed83ed9d177e0c99b83a2138623a4b" {
|
||||
t.Error("digest form")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlocks: blocking, unblocking, and who has a user as a friend.
|
||||
func TestBlocks(t *testing.T) {
|
||||
BcryptCost = 4
|
||||
s, err := Open(filepath.Join(t.TempDir(), "bbs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
a, _ := s.CreateUser("alice", "pw", "", false)
|
||||
b, _ := s.CreateUser("bob", "pw", "", false)
|
||||
c, _ := s.CreateUser("carol", "pw", "", false)
|
||||
if err := s.Block(a.ID, b.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Block(a.ID, b.ID); err != nil {
|
||||
t.Fatal("twice:", err)
|
||||
}
|
||||
if ok, _ := s.IsBlocked(a.ID, b.ID); !ok {
|
||||
t.Error("not blocked")
|
||||
}
|
||||
if ok, _ := s.IsBlocked(b.ID, a.ID); ok {
|
||||
t.Error("blocked the other way")
|
||||
}
|
||||
bl, _ := s.Blocked(a.ID)
|
||||
if len(bl) != 1 || bl[0].Name != "bob" {
|
||||
t.Errorf("blocked %+v", bl)
|
||||
}
|
||||
s.Unblock(a.ID, b.ID)
|
||||
if ok, _ := s.IsBlocked(a.ID, b.ID); ok {
|
||||
t.Error("still blocked")
|
||||
}
|
||||
s.PutFriend(b.ID, Friend{ID: a.ID, Group: "Pals"})
|
||||
s.PutFriend(c.ID, Friend{ID: a.ID})
|
||||
of, _ := s.FriendOf(a.ID)
|
||||
if len(of) != 2 || of[0].Name != "bob" || of[0].Group != "Pals" || of[1].Name != "carol" {
|
||||
t.Errorf("friend of %+v", of)
|
||||
}
|
||||
}
|
||||
@@ -258,6 +258,18 @@ CREATE TABLE IF NOT EXISTS chats (
|
||||
created {int} NOT NULL,
|
||||
delivered {bool} NOT NULL DEFAULT FALSE
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS msn_keys (
|
||||
user_id {int} NOT NULL PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
salt {str} NOT NULL,
|
||||
digest {str} NOT NULL,
|
||||
bound {str} NOT NULL
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS blocks (
|
||||
user_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
blocked_id {int} NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
added {int} NOT NULL,
|
||||
PRIMARY KEY (user_id, blocked_id)
|
||||
)`, `
|
||||
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,
|
||||
|
||||
@@ -119,6 +119,8 @@ type Store struct {
|
||||
keepOSCAR atomic.Bool
|
||||
// keepCIS: and their CompuServe Secure Login keys (cis.go)
|
||||
keepCIS atomic.Bool
|
||||
// keepMSN: and their MSN MD5 login digests (msn.go)
|
||||
keepMSN atomic.Bool
|
||||
}
|
||||
|
||||
// Open opens (and makes, if need be) the database at addr: a file's path
|
||||
@@ -256,6 +258,7 @@ func (s *Store) CreateUser(name, password, location string, sysop bool) (*User,
|
||||
if password != "" {
|
||||
s.KeepOSCARKeys(id, password)
|
||||
s.KeepCISKey(id, password)
|
||||
s.KeepMSNKey(id, password)
|
||||
}
|
||||
return s.UserByID(id)
|
||||
}
|
||||
@@ -289,6 +292,7 @@ func (s *Store) CheckPassword(name, pw string) (*User, error) {
|
||||
}
|
||||
s.KeepOSCARKeys(u.ID, pw) // best effort: the login stands without them
|
||||
s.KeepCISKey(u.ID, pw)
|
||||
s.KeepMSNKey(u.ID, pw)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
@@ -304,6 +308,9 @@ func (s *Store) SetPassword(id int64, pw string) error {
|
||||
if err := s.KeepCISKey(id, pw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.KeepMSNKey(id, pw); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.KeepOSCARKeys(id, pw)
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ nav:
|
||||
- "Chat and paging": Chat-and-Paging.md
|
||||
- "IRC": IRC.md
|
||||
- "AIM and ICQ": AIM-and-ICQ.md
|
||||
- "MSN Messenger": MSN-Messenger.md
|
||||
- "MRC": MRC.md
|
||||
- "Finger and gopher": Finger-and-Gopher.md
|
||||
- "Web forum": Web-Forum.md
|
||||
|
||||
Reference in new issue
Block a user