Merge pull request #41 from D-Modem/claude/project-thread-6i32bn

Setup screens in the style of 1990s BBS setup programs
This commit is contained in:
Neo authored and GitHub committed 2026-11-08 23:18:43 -08:00
commit 4b3c132920
40 files changed
+5840 -325

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 295 KiB

+1 -1
View File
@@ -32,7 +32,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
- E-mail: IMAP, POP3 and SMTP, to and from the internet, directly or through a smarthost
- Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC (and linking into an IRC network as a TS6 or P10 hub server), AIM and ICQ, MSN Messenger, and MRC
- Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC (and linking into an IRC network as a TS6 or P10 hub server), AIM and ICQ, MSN Messenger, Yahoo! 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
- Time: follows NTP, NTS and PTP servers, and serves all three
+25
View File
@@ -845,6 +845,31 @@ address = 127.0.0.1:2513
;max_clients = 64
;max_per_ip = 4
; Yahoo! Messenger: the chat for Yahoo! Messenger clients (YMSG 9 to 16),
; beside IRC, AIM and MSN. Users sign in with their BBS names (without
; spaces) and passwords; the buddy list is their friends list and the
; ignore list their blocked list; an IM is a private message, kept for one
; away; Yahoo chat rooms are the chat rooms, and a conference a room of
; its own. The clients must be pointed at this host (see the wiki page).
; See docs/wiki/Yahoo-Messenger.md
;[ymsg]
;address = :5050
; the web half, for Y!M 9 and later and the room list: point
; vcs1.msg.yahoo.com, vcs2.msg.yahoo.com and insider.msg.yahoo.com here
;http_address = :80
; Y!M 9's login, its password over HTTPS: point login.yahoo.com here, with
; a certificate for it the client trusts
;https_address = :443
;tls_cert = /etc/bbs/login.yahoo.com.crt
;tls_key = /etc/bbs/login.yahoo.com.key
; the pager's address the web half gives Y!M 9 (default: the address each
; one asked on; set it behind NAT)
;host = 203.0.113.5
;max_clients = 256
;max_per_ip = 4
; the Yahoo ID the BBS's notices come from
;system = bbs
; 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
+17
View File
@@ -86,6 +86,7 @@ import (
"github.com/D-Modem/bbs/internal/server"
"github.com/D-Modem/bbs/internal/sockets"
"github.com/D-Modem/bbs/internal/store"
"github.com/D-Modem/bbs/internal/ymsg"
"github.com/D-Modem/menu/authd"
)
@@ -312,6 +313,9 @@ func main() {
if m := cfg.Marvel; m != nil {
fmt.Printf("marvel: %q\n", m.Address)
}
if y := cfg.YMSG; y != nil {
fmt.Printf("ymsg: %q, web %q, https %q\n", y.Address, y.HTTPAddress, y.HTTPSAddress)
}
if cfg.Finger != nil {
fmt.Printf("finger: %s (online %v, users %v)\n", cfg.Finger.Address, cfg.Finger.Online, cfg.Finger.Users)
}
@@ -628,6 +632,19 @@ func serve(cfg *server.Config, path string) int {
}
}()
}
if cfg.YMSG != nil {
ysrv, err := ymsg.New(b, *cfg.YMSG)
if err != nil {
lg.Printf("%v", err)
return 1
}
go func() {
if err := ysrv.Run(ctx); err != nil {
lg.Printf("%v", err)
stop()
}
}()
}
if cfg.Finger != nil {
fs := &finger.Server{B: b, S: *cfg.Finger}
go func() {
+8 -7
View File
@@ -50,10 +50,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)
or [MSN](MSN-Messenger) as an IM.
or [MSN](MSN-Messenger) or [Yahoo](Yahoo-Messenger) as an IM.
Private messages are kept, however they were sent: the BBS's chat, IRC,
AIM, ICQ or MSN. A message to a user who isn't on is kept for them, and they
AIM, ICQ, MSN or Yahoo. 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
@@ -64,17 +64,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), 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
[MSN](MSN-Messenger#contacts) and [Yahoo](Yahoo-Messenger#buddies). A friend added on one shows on the others;
an AIM, MSN or Yahoo 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
(and `/unblock WHO` takes them off), as do MSN's "Block" and Yahoo's
ignore list. 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.
AIM, MSN, Yahoo) and whether or not you are on, and MSN and Yahoo show
you offline to them.
## Paging the sysop
+18
View File
@@ -44,6 +44,7 @@ the file is laid out.
| [`[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. |
| [`[marvel]`](#marvel) | The Microsoft Network of 1995 to 1998, for the MSN client that came with Windows 95: users sign in with their BBS names and passwords, the message areas are its Categories, and each area is an MSN bulletin board to read and post in. |
| [`[ymsg]`](#ymsg) | Yahoo! Messenger: the chat for Yahoo! Messenger clients (YMSG 9 to 16), beside IRC, AIM and MSN. |
| [`[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. |
@@ -627,6 +628,23 @@ The Microsoft Network of 1995 to 1998, for the MSN client that came with Windows
| `max_per_ip` | | | See the section above. Examples: `4`. |
## `[ymsg]`
Yahoo! Messenger: the chat for Yahoo! Messenger clients (YMSG 9 to 16), beside IRC, AIM and MSN. Users sign in with their BBS names (without spaces) and passwords; the buddy list is their friends list and the ignore list their blocked list; an IM is a private message, kept for one away; Yahoo chat rooms are the chat rooms, and a conference a room of its own. The clients must be pointed at this host (see the wiki page). See docs/wiki/Yahoo-Messenger.md.
| key | default | live | what it does |
|---|---|---|---|
| `address` | | | See the section above. Examples: `:5050`. |
| `http_address` | | | the web half, for Y!M 9 and later and the room list: point vcs1.msg.yahoo.com, vcs2.msg.yahoo.com and insider.msg.yahoo.com here. Examples: `:80`. |
| `https_address` | | | Y!M 9's login, its password over HTTPS: point login.yahoo.com here, with a certificate for it the client trusts. Examples: `:443`. |
| `tls_cert` | | | Y!M 9's login, its password over HTTPS: point login.yahoo.com here, with a certificate for it the client trusts. Examples: `/etc/bbs/login.yahoo.com.crt`. |
| `tls_key` | | | Y!M 9's login, its password over HTTPS: point login.yahoo.com here, with a certificate for it the client trusts. Examples: `/etc/bbs/login.yahoo.com.key`. |
| `host` | | | the pager's address the web half gives Y!M 9 (default: the address each one asked on; set it behind NAT) Examples: `203.0.113.5`. |
| `max_clients` | | | the pager's address the web half gives Y!M 9 (default: the address each one asked on; set it behind NAT) Examples: `256`. |
| `max_per_ip` | | | the pager's address the web half gives Y!M 9 (default: the address each one asked on; set it behind NAT) Examples: `4`. |
| `system` | | | the Yahoo ID the BBS's notices come from. Examples: `bbs`. |
## `[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.
+31 -8
View File
@@ -62,21 +62,36 @@ password.
## Editing it: the configuration screens
`bbs -config /etc/bbs/bbs.conf config` opens full-screen menus on your
`bbs -config /etc/bbs/bbs.conf config` opens the setup screens on your
terminal for editing the file and the accounts, whether or not the BBS is
running. The same menus are in the [sysop tools](Sysop-Tools) (`F`,
Configuration). They are full screen on ANSI terminals, use PF keys on a
3270, and become numbered lines on a terminal with neither.
running. The same screens are in the [sysop tools](Sysop-Tools) (`F`,
Configuration). On an ANSI terminal they look like the BBS setup programs
of the 1990s: a menu bar of pull-down menus, a shaded blue desk, each menu
a window over the one it was opened from, the line's help in a box below,
and values changed in boxes that pop up. They use PF keys on a 3270, and
become numbered lines on a terminal with neither.
<img src="https://raw.githubusercontent.com/D-Modem/bbs/main/.github/config-screens.png" alt="The setup screens: the Online pull-down menu over the main menu" width="100%">
| Menu | What is in it |
|---|---|
| Board configuration | the BBS's name, the sysop's, the location, postal address, dial-in numbers and internet addresses; the banner, message of the day, goodbye, logo; menus and prompts |
| System configuration | the user and group it runs as; the database and log; where files are kept and how large they may be; deny lists, the hack log, bans; scheduled events; every section of the file as it is |
| Connections and modems | modem lines and every listener; callers at once, logins, time-outs, lock-outs; passwords by modemmenu's auth socket ([Modem callers](Modem-Callers#the-same-password-for-telnet-ssh-and-the-web)); the caller ID country and GeoIP |
| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, Gemini, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors |
| Internet services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, Gemini, FTP, news, the web (API, forum, image boards) |
| Online services | [AOL](AOL), [CompuServe](CompuServe) (its listeners) and [The Microsoft Network](MSN-Classic) (its TCP host and dial-in listeners) |
| Messengers and chat | [AIM and ICQ](AIM-and-ICQ), [MSN Messenger](MSN-Messenger), [Yahoo! Messenger](Yahoo-Messenger), the [IRC](IRC) server, [IRC network links](IRC-Linking) and their peers, [MRC](MRC) |
| E-mail | [`[mail]`](E-mail), the smarthost, POP3, IMAP, SMTP submission, MX and LMTP |
| Networks and doors | [FidoNet](FidoNet) and binkp, QWK networks, doors |
| Time | the clock and its sources, and the NTP, NTS-KE and PTP servers ([Time](Time)) |
| Users and groups | the accounts (level, flags, sysop, locked, a new password; new ones; deleted ones) and the access levels |
| Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups: one now, those made, `[backup]` ([Backups](Backups)) |
The menu bar's pull-down menus (`/`, F12, or Alt and the menu's red
letter) go straight to any of these from anywhere: File (review, check,
save, quit), Setup, Lines, Internet, Online (the online services and the
messengers), Mail, Networks, Time and Help.
System passwords (PAM, LDAP) are checked by modemmenu, which logs callers
in and hands them to the BBS (see [Modem callers](Modem-Callers)). Running
the BBS as a user of its own (System configuration's Run as user) is
@@ -85,13 +100,21 @@ covered in [Running](Running#running-as-a-user-of-its-own).
| Key | What it does |
|---|---|
| arrows, PgUp, PgDn, Home, End | move (a letter goes to the next line beginning with it) |
| Enter | open a menu, change a value (typed on the foot line, Enter to keep it), do an action |
| Enter | open a menu, change a value (typed in a box that pops up, or picked from a list of its choices), do an action |
| Space | turn a yes/no over, or go to the next choice |
| Esc, left arrow | back |
| Esc, left arrow | back a window |
| `/`, F12, Alt+letter | the menu bar's pull-down menus (arrows between them, Enter to go) |
| F1 or `?` | the whole help for the line (from bbs.conf.sample) |
| F9 | quit without saving (after a yes, if anything changed) |
| F10 | save and exit |
| `A`, `D` | add one (a listener, a door, a user ...), delete it |
| Ctrl-L | draw the screen again |
In a box where a value is typed, the arrows, Home and End move, Ctrl-U
clears it, Enter keeps it and Esc leaves the value as it was. The screens
are sent a changed cell at a time, so moving the bar costs a modem caller
a few bytes, and a terminal without UTF-8 gets code page 437's lines and
shading.
On a 3270, type `S` beside a menu to open it, type over values and send
them with Enter; PF1 is help, PF3 goes back, and PF9 and PF10 work like F9
@@ -99,7 +122,7 @@ and F10. On a terminal without ANSI, type a line's number to open or change
it, `S` to save and exit, or `X` to leave without saving.
Nothing changes until you save. A changed line is marked `*`, and the
bottom line counts the unsaved changes. The main menu's Review changes
help box counts the unsaved changes. The main menu's Review changes
lists them all, and Check the configuration reads the file as the BBS
would.
+2 -1
View File
@@ -83,7 +83,7 @@ which is generated from `bbs.conf.sample`.
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, [MSN Messenger](MSN-Messenger)
for MSN clients, and [MRC](MRC), the chat
for MSN clients, [Yahoo! Messenger](Yahoo-Messenger) for Yahoo clients, and [MRC](MRC), the chat
network shared with other BBSes
- [Finger, gopher and Gemini](Finger-and-Gopher)
- [Time](Time): NTP, NTS and PTP, followed and served
@@ -145,6 +145,7 @@ which is generated from `bbs.conf.sample`.
| [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 |
| [MSN Classic](MSN-Classic) | The Microsoft Network for Windows 95's client: sign-in, the areas as Categories, bulletin boards |
| [Yahoo! Messenger](Yahoo-Messenger) | the Yahoo server: YMSG 9 to 16, buddies, IMs, chat rooms and conferences |
| [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes |
| [Finger, gopher and Gemini](Finger-and-Gopher) | who is on, and the BBS in gopherspace and Geminispace |
| [Time](Time) | NTP, NTS and PTP: the clock following time servers, and serving time |
+1 -1
View File
@@ -11,7 +11,7 @@ any terminal, although watching a node needs a text terminal.
| statistics | `S` | totals (users, messages, mail, files; logins, posts, pages and failed logins since the start), and calls, new users, posts and uploads for each of the last 14 days, as bars |
| hack log and bans | `H` | the addresses banned now (a number lifts its ban), and `L` the [hack log](Security#keeping-callers-out)'s last 100 lines |
| scheduled events | `E` | the events, when they run next and how their last run went; one's command and output, and `R` runs it now |
| configuration | `F` | the configuration menus: the board, the system, connections, services, users and groups, maintenance; nothing changes until F10 saves (F9 quits), and then what may change while callers are on is put in force at once ([Configuration](Configuration#editing-it-the-configuration-screens)). Shown when the BBS runs with `-config` |
| configuration | `F` | the setup screens (blue windows and pull-down menus on ANSI terminals): the board, the system, connections, internet and online services, messengers, e-mail, networks, time, users and groups, maintenance; nothing changes until F10 saves (F9 quits), and then what may change while callers are on is put in force at once ([Configuration](Configuration#editing-it-the-configuration-screens)). Shown when the BBS runs with `-config` |
| available | `A` | whether pages reach you; when not, a caller who pages is told you are not available and may leave you a message |
Validating new users stays on the main menu (`V`, when some wait).
+131
View File
@@ -0,0 +1,131 @@
The BBS has a Yahoo! Messenger server (YMSG, the protocol of Yahoo's
pager), beside its [IRC](IRC), [AIM](AIM-and-ICQ) and
[MSN](MSN-Messenger) servers and on the same chat. Someone signed in with
Yahoo! Messenger sees their BBS friends as buddies, IMs anyone on the BBS
(other Yahoo users, IRC, AIM and MSN users, and callers on telnet, SSH,
3270s and the web terminal), and joins the BBS's chat rooms as Yahoo chat
rooms.
```ini
[ymsg]
address = :5050
http_address = :80
```
| Setting | Default | What it sets |
|---|---|---|
| `address` | `:5050` | where the pager listens |
| `http_address` | none | the web half (the capacity lookup and the room list), plain HTTP |
| `https_address` | none | the web half over HTTPS: the login of Y!M 9 and later |
| `tls_cert`, `tls_key` | none | the certificate for `https_address` (for `login.yahoo.com`) |
| `host` | the address each client asked on | the pager's address the capacity lookup gives; set it behind NAT |
| `max_clients` | `256` | connections at once |
| `max_per_ip` | `4` | from one address |
| `system` | `bbs` | the Yahoo ID the BBS's notices come from |
## Versions served
YMSG 9 to 16. Two logins are served:
- **The challenge login** (YMSG 9 to 15): Yahoo! Messenger 5.x, and
third-party clients of that time (Gaim, Kopete, libyahoo2's), which
take the login type the server offers. Yahoo! Messenger 6 to 8 used a
later challenge ("auth type 1") that is not served; whether they take
the older one when it is offered has not been tried yet.
- **The token login** (YMSG 16): Yahoo! Messenger 9 and later, and
the later Pidgin 2.x releases. The client sends the password over HTTPS to
`login.yahoo.com`, gets a token, and proves it on the pager. This
needs `https_address`.
## Pointing a client at the BBS
The clients were made for Yahoo's servers, so each must be pointed at
the BBS. None of this has been tried with the real clients yet.
- Yahoo! Messenger 5 to 8: under `HKEY_CURRENT_USER\Software\Yahoo\Pager`
in the registry, set the string values `socket server` and
`IPLookup` to the BBS's host (community guides also set `Conn Server`
and `Host Name`). Or send `scs.msg.yahoo.com` and
`scsa.msg.yahoo.com` to the BBS in the machine's hosts file.
- Yahoo! Messenger 9 and later: the hosts file sends
`vcs1.msg.yahoo.com`, `vcs2.msg.yahoo.com`, `scsa.msg.yahoo.com` and
`login.yahoo.com` to the BBS; the machine must trust the certificate
given in `tls_cert` for `login.yahoo.com` (make a small certificate
authority of your own and add its certificate to the machine's trusted
roots). The HTTPS server takes the TLS 1.0 and old ciphers Windows XP
has.
- `insider.msg.yahoo.com` sent to the BBS gives the chat room browser
the BBS's rooms.
- Third-party clients (Pidgin, Kopete, Miranda, Trillian) take a pager
server in the account's settings.
The deny list and bans in `[security]` apply as they do everywhere else.
## Signing in
Every Yahoo user is a BBS user. Their Yahoo ID is their BBS name in lower
case without its spaces (`carolann` is Carol Ann), and the password is
their BBS password. 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 Yahoo client at a time: signing in
again signs the older one out.
The challenge login proves the password by two digests of it, which the
BBS's password hashes can't check. So the BBS keeps each account's Yahoo
digests 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 `[ymsg]` 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
Yahoo. The log says so when that is why a sign-in failed. The digests are
kept only while `[ymsg]` is set up; anyone who read them from the
database could sign in by Yahoo as that user. The token login checks the
password itself, as any login does. The pager's connection is not
encrypted.
## Buddies
The buddy list is the user's [friends list](Chat-and-Paging#friends),
the same list the BBS's chat, IRC, AIM and MSN show, with its groups
(`Friends` for friends in none). A buddy is always a BBS user: adding
anyone else is refused, and the BBS says so. Adding a buddy asks no one's
permission. A friend added or moved elsewhere comes to a client that is
on at once, and one added, moved or removed on Yahoo is changed
everywhere.
The ignore list is the user's [blocked list](Chat-and-Paging#blocking):
a blocked user's messages are refused however they come, and the user
appears offline to them.
A buddy is online while they are on the BBS by any route: with the
status their Yahoo client set (busy, be right back, a custom message,
invisible), or, on another route, with "on the BBS by telnet" (or IRC,
AIM, MSN...) as their status message.
## IMs
An IM to a BBS user is a [private
message](Chat-and-Paging#private-messages): a `PRIVMSG` on IRC, an IM on
AIM or MSN, a message line on a terminal. Yahoo's colours and fonts are
taken off. Typing notices pass between Yahoo clients only.
Every line is kept. One to a user who isn't on is kept for them; they
get it when they next log in. Lines kept for a Yahoo user come when they
sign in, marked with when they were sent. The BBS's notices (new mail, a
page for the sysop, errors) come from the `system` ID.
Sending files is not served: the client is told to use the BBS's file
areas.
## Chat rooms and conferences
A Yahoo chat room is a BBS [chat room](Chat-and-Paging): "Linux, FreeBSD,
Solaris:1" is the room `linux-freebsd-solari` (lower case, letters and
digits, the lobby number dropped, at most 20 characters), the same room
IRC calls `#linux-freebsd-solari`. The room browser lists the rooms in
use and the permanent ones.
A conference (Yahoo's invited group IM) is a BBS room of its own, `yc-`
and the conference's name. Yahoo users invited are asked by their
clients; anyone else invited gets a private message naming the room,
which they join from wherever they are. Anyone told the room's name can
join it.
+1
View File
@@ -39,6 +39,7 @@
- [AOL clients](AOL)
- [MSN Messenger](MSN-Messenger)
- [MSN Classic (1995)](MSN-Classic)
- [Yahoo! Messenger](Yahoo-Messenger)
- [MRC](MRC)
- [Finger, gopher and Gemini](Finger-and-Gopher)
- [Time: NTP, NTS and PTP](Time)
+1
View File
@@ -631,6 +631,7 @@ func (b *BBS) menuLogin(who, name, pw string) (*store.User, error) {
b.Store.KeepCISKey(u.ID, pw) // and CompuServe's
b.Store.KeepMSNKey(u.ID, pw) // and MSN's
b.Store.KeepNTLMKey(u.ID, pw) // and MSN Classic's
b.Store.KeepYMSGKeys(u.ID, pw) // and Yahoo's
return u, nil
}
+13 -5
View File
@@ -9,6 +9,8 @@ import (
"strings"
"sync"
"time"
"github.com/D-Modem/bbs/internal/store"
)
// EventKind says what an Event is.
@@ -491,13 +493,19 @@ type RoomInfo struct {
// Rooms lists the chat rooms in use (private ones only to sysops and
// their own caller).
func (n *Node) Rooms() []RoomInfo {
u := n.User()
h := n.b.hub()
func (n *Node) Rooms() []RoomInfo { return n.b.rooms(n.User(), n.Num) }
// PublicRooms lists the chat rooms in use but the private ones (for a
// list shown to anyone, as a Yahoo client's room browser).
func (b *BBS) PublicRooms() []RoomInfo { return b.rooms(nil, 0) }
// rooms lists the chat rooms in use, as u on node sees them.
func (b *BBS) rooms(u *store.User, node int) []RoomInfo {
h := b.hub()
h.mu.Lock()
var out []RoomInfo
for name, r := range h.rooms {
if strings.HasPrefix(name, "sysop-") && name != pageRoom(n.Num) && (u == nil || !u.Sysop) {
if strings.HasPrefix(name, "sysop-") && (node == 0 || name != pageRoom(node)) && (u == nil || !u.Sysop) {
continue
}
ri := RoomInfo{Name: name, Permanent: r.permanent, Topic: r.topic}
@@ -509,7 +517,7 @@ func (n *Node) Rooms() []RoomInfo {
}
h.mu.Unlock()
for i := range out {
for _, m := range n.b.remoteMembers(out[i].Name) {
for _, m := range b.remoteMembers(out[i].Name) {
out[i].Users = append(out[i].Users, m.Name+" ("+m.Via+")")
}
}
+82 -6
View File
@@ -41,7 +41,10 @@ type Editor struct {
db *data // the accounts and areas, as read and as changed (nil: not read yet)
crumbs []string
flash string // a word for the next screen's foot
trail []string // the label of the item each page in crumbs was opened by ("": the first, or not by one)
via string // the label of the item opening a page now
jump []string // where a pull-down menu's item goes: labels of items to open from the first page
flash string // a word for the next screen's foot
}
var (
@@ -53,11 +56,14 @@ var (
// Run shows the screens until the sysop saves or leaves.
func (e *Editor) Run() error {
e.cat = confedit.NewCatalog(bbssec.Sample)
if se, ok := e.UI.(view.SheetEnder); ok {
defer se.EndSheets()
}
if ok, err := e.load(); err != nil || !ok {
return err
}
for {
e.crumbs = nil
e.crumbs, e.trail, e.jump = nil, nil, nil
err := e.show(e.mainMenu())
switch {
case err == nil || errors.Is(err, errQuit):
@@ -121,6 +127,7 @@ func (e *Editor) load() (bool, error) {
type item struct {
view.Entry
open func() error // EntryMenu: another page
sub func() page // and that page, where it is known (for the pull-down menus)
set func(v string) error // a value's
do func() error // EntryAction
help string // the whole help, for F1 (Entry.Help: its first line)
@@ -141,12 +148,61 @@ type page struct {
// back a page (nil).
func (e *Editor) show(p page) error {
e.crumbs = append(e.crumbs, p.title)
defer func() { e.crumbs = e.crumbs[:len(e.crumbs)-1] }()
e.trail = append(e.trail, e.via)
e.via = ""
defer func() {
e.crumbs = e.crumbs[:len(e.crumbs)-1]
e.trail = e.trail[:len(e.trail)-1]
}()
cursor := 0
for {
its := p.items()
if e.jump != nil {
// a pull-down's item: back to where its path and this page's
// meet, then on down it
at := e.trail[1:]
if len(at) > len(e.jump) || !prefix(at, e.jump) {
return nil
}
if len(at) == len(e.jump) {
e.jump = nil
} else {
next, last := e.jump[len(at)], len(at) == len(e.jump)-1
i := -1
for j, it := range its {
if it.Label == next && it.Choosable() {
i = j
break
}
}
if i < 0 {
e.jump = nil
} else {
cursor = i
var err error
switch it := its[i]; {
case it.open != nil:
e.via = it.Label
err = it.open()
e.via = ""
case it.do != nil && last:
e.jump = nil
err = it.do()
default:
e.jump = nil
}
if errors.Is(err, errClose) {
return nil
}
if err != nil {
return err
}
continue
}
}
}
sh := &view.Sheet{Title: p.title, Crumbs: strings.Join(e.crumbs, " > "), Note: p.note,
Cursor: cursor, Keys: p.keys, Status: e.status()}
Cursor: cursor, Keys: p.keys, Status: e.status(), Menus: e.pullDowns()}
for _, it := range its {
sh.Entries = append(sh.Entries, it.Entry)
}
@@ -164,6 +220,11 @@ func (e *Editor) show(p page) error {
return errSave
case view.SheetQuit:
return errQuit
case view.SheetJump:
e.jump = r.Jump
if len(e.jump) == 0 {
e.jump = nil
}
case view.SheetHelp:
if r.Entry >= 0 && r.Entry < len(its) {
err = e.helpOf(its[r.Entry])
@@ -174,7 +235,9 @@ func (e *Editor) show(p page) error {
}
switch it := its[r.Entry]; {
case it.open != nil:
e.via = it.Label
err = it.open()
e.via = ""
case it.do != nil:
err = it.do()
}
@@ -202,6 +265,19 @@ func (e *Editor) show(p page) error {
}
}
// prefix is whether a begins b.
func prefix(a, b []string) bool {
if len(a) > len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// helpOf shows an item's whole help (F1), wrapped to the screen, and when a
// change to it takes effect.
func (e *Editor) helpOf(it item) error {
@@ -358,8 +434,8 @@ func (e *Editor) save() (bool, error) {
if len(ch) > 0 {
if e.Tools.Reload == nil {
lines = append(lines, view.L(""),
view.L("A BBS running puts the green changes in force at a reload (systemctl reload"),
view.L("bbs, or SIGHUP); the yellow ones when it starts again."), view.L(""))
view.L("A BBS running puts the green changes in force at a reload (systemctl reload bbs, or SIGHUP); the yellow ones when it starts again."),
view.L(""))
lines = append(lines, e.diffLines(ch)...)
} else {
applied, restart, err := e.Tools.Reload()
+86 -1
View File
@@ -13,6 +13,7 @@ import (
bbssec "github.com/D-Modem/bbs"
"github.com/D-Modem/bbs/internal/backup"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/confedit"
"github.com/D-Modem/bbs/internal/store"
"github.com/D-Modem/bbs/internal/view"
)
@@ -291,7 +292,7 @@ func TestServices(t *testing.T) {
p := writeConf(t)
os.WriteFile(p, []byte(file+"\n; finger\n;[finger]\n;address = :79\n"), 0o600)
ui := &script{t: t, forms: []map[string]string{{"name": "ssh"}}, steps: []step{
open("Services"),
open("Internet services"),
open("Finger"), expect("Enabled", "no", false, set("Enabled", "yes")), set("online", "no"), back,
open("SSH"), key("add"),
expect("type", "ssh", true, set("address", ":2222")), back, back,
@@ -451,3 +452,87 @@ func TestBackUpNow(t *testing.T) {
t.Errorf("written:\n%s", data)
}
}
// jump is a step that picks a pull-down menu's item (by the menu's label
// and the item's), checking the sheet has it.
func jump(menu, item string) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult {
t.Helper()
for _, m := range sh.Menus {
if m.Label != menu {
continue
}
for _, it := range m.Items {
if it.Label == item && !it.Heading {
if it.Action != "" {
return view.SheetResult{Action: it.Action}
}
return view.SheetResult{Action: view.SheetJump, Jump: it.Path}
}
}
}
t.Fatalf("%s: no %s > %s in the menus", sh.Crumbs, menu, item)
return view.SheetResult{}
}
}
// at is a step that checks the sheet is the one crumbs names, then does
// then.
func at(crumbs string, then step) step {
return func(t *testing.T, sh *view.Sheet) view.SheetResult {
t.Helper()
if sh.Crumbs != crumbs {
t.Fatalf("at %q, not %q", sh.Crumbs, crumbs)
}
return then(t, sh)
}
}
// TestPullDowns: a pull-down menu's item goes from deep in one menu to a
// page of another, by the pages between; every front end is on a menu.
func TestPullDowns(t *testing.T) {
p := writeConf(t)
ui := &script{t: t, steps: []step{
open("Internet services"), open("Finger"),
jump("Online", "America Online (AOL)"),
at("Configuration > Online services > America Online (AOL)", set("Enabled", "yes")),
jump("Online", "Yahoo! Messenger"),
at("Configuration > Messengers and chat > Yahoo! Messenger", set("Enabled", "yes")),
jump("Time", "NTP server"),
at("Configuration > Time > NTP server", back),
at("Configuration > Time", back),
at("Configuration", jump("File", "Save and exit F10")),
}}
if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(p)
for _, want := range []string{"[aol]", "[ymsg]"} {
if !strings.Contains(string(data), want) {
t.Errorf("no %q in:\n%s", want, data)
}
}
// every kind of section the sample has is on a menu's page
e := &Editor{UI: ui}
e.cat = confeditCatalog()
e.doc, _ = confeditParse(nil)
e.orig, _ = confeditParse(nil)
var labels []string
for _, m := range e.pullDowns() {
for _, it := range m.Items {
labels = append(labels, it.Label)
}
}
all := strings.Join(labels, "|")
for _, want := range []string{"America Online (AOL)", "CompuServe (CIS)", "The Microsoft Network (MSN 1995)",
"AIM and ICQ (OSCAR)", "MSN Messenger", "Yahoo! Messenger", "IRC server", "IRC network links", "Multi Relay Chat",
"POP3", "IMAP", "Smarthost (send through)", "Gopher", "Gemini", "Finger", "NTP server", "PTP grandmaster", "FidoNet", "Doors"} {
if !strings.Contains("|"+all+"|", "|"+want+"|") {
t.Errorf("no %q in the pull-down menus: %s", want, all)
}
}
}
func confeditCatalog() *confedit.Catalog { return confedit.NewCatalog(bbssec.Sample) }
func confeditParse(b []byte) (*confedit.Doc, error) { return confedit.Parse(b) }
+265 -28
View File
@@ -10,31 +10,139 @@ import (
// The menus, by what a sysop looks for.
// The first page's menus, by their labels (the pull-down menus' paths
// name them).
const (
mBoard = "Board configuration"
mSystem = "System configuration"
mLines = "Connections and modems"
mInternet = "Internet services"
mOnline = "Online services"
mChat = "Messengers and chat"
mMail = "E-mail"
mNetworks = "Networks and doors"
mTime = "Time"
mUsers = "Users and groups"
mMaint = "Maintenance"
mReview = "Review changes"
mCheck = "Check the configuration"
)
// mainMenu is the first page: the menus, then review, check, save and quit.
func (e *Editor) mainMenu() page {
return page{title: "Configuration", items: func() []item {
g := sec("general")
name, _ := e.doc.Get(g, "name")
n := e.changes()
review := menu("Review changes", fmt.Sprintf("%d not saved", n), e.review)
review.Kind = view.EntryAction
review.do, review.open = e.review, nil
review := action(mReview, e.review)
review.Value = fmt.Sprintf("%d not saved", n)
return []item{
menu("Board configuration", name, func() error { return e.show(e.boardMenu()) }),
menu("System configuration", "", func() error { return e.show(e.systemMenu()) }),
menu("Connections and modems", e.count("listen", nil, "listener"), func() error { return e.show(e.connectionsMenu()) }),
menu("Services", "", func() error { return e.show(e.servicesMenu()) }),
menu("Users and groups", "", func() error { return e.show(e.usersMenu()) }),
menu("Maintenance", "", func() error { return e.show(e.maintenanceMenu()) }),
withHelp(e.submenu(mBoard, name, e.boardMenu), "The BBS's name, sysop and where it is; what callers see; the menus and prompts."),
withHelp(e.submenu(mSystem, "", e.systemMenu), "The database and log, where files are kept, security, the user it runs as, scheduled events, and every section of the file."),
withHelp(e.submenu(mLines, e.count("listen", nil, "listener"), e.connectionsMenu), "Modem lines and listeners (the ports callers come in by), callers' limits, modemmenu's passwords, caller ID."),
heading("What callers reach"),
withHelp(e.submenu(mInternet, "", e.servicesMenu), "Telnet, TN3270, SSH and RLogin for terminals; finger, gopher, Gemini, FTP, news and the web."),
withHelp(e.submenu(mOnline, e.onCount("aol", "marvel"), e.onlineMenu), "The BBS as America Online, CompuServe and The Microsoft Network, for their own 1990s client programs."),
withHelp(e.submenu(mChat, e.onCount("oscar", "msn", "ymsg", "irc", "irclink", "mrc"), e.chatMenu), "AIM and ICQ, MSN Messenger, Yahoo! Messenger, the IRC server and its network links, Multi Relay Chat."),
withHelp(e.submenu(mMail, e.onOff(sec("mail")), e.mailMenu), "Each user's e-mail: the domain, sending (direct or by a smarthost), POP3, IMAP, SMTP, MX and LMTP."),
withHelp(e.submenu(mNetworks, "", e.networksMenu), "FidoNet and binkp, QWK networks, and the doors."),
withHelp(e.submenu(mTime, e.onCount("time", "ntp", "nts", "ptp"), e.timeMenu), "The clock the BBS follows (NTP, NTS, PTP servers) and the time servers it can be."),
heading("Accounts and upkeep"),
withHelp(e.submenu(mUsers, "", e.usersMenu), "User accounts, access levels and flags."),
withHelp(e.submenu(mMaint, "", e.maintenanceMenu), "Disk space, what the message areas keep, backups."),
heading(""),
review,
action("Check the configuration", e.check),
action(mCheck, e.check),
action("Save and exit (F10)", func() error { return errSave }),
action("Quit without saving (F9)", func() error { return errQuit }),
}
}}
}
// withHelp is it with its help.
func withHelp(it item, help string) item {
it.Help = help
return it
}
// submenu is an item that opens the page p makes.
func (e *Editor) submenu(label, value string, p func() page) item {
it := menu(label, value, func() error { return e.show(p()) })
it.sub = p
return it
}
// onCount is how many of the sections of kinds the file has, in words.
func (e *Editor) onCount(kinds ...string) string {
n := 0
for _, k := range kinds {
if e.doc.Has(sec(k)) {
n++
}
}
if n == 0 {
return "off"
}
return fmt.Sprintf("%d on", n)
}
// pullDowns are the menu bar's menus: File, then the first page's menus
// gathered under short names, each item a jump to its page.
func (e *Editor) pullDowns() []view.PullDown {
tops := map[string]item{}
for _, it := range e.mainMenu().items() {
tops[it.Label] = it
}
// expand is a first-page menu's own menus, under a heading of it
expand := func(label string, head bool) []view.PullItem {
var out []view.PullItem
top, ok := tops[label]
if !ok || top.sub == nil {
return nil
}
if head {
out = append(out, view.PullItem{Label: label, Heading: true})
}
for _, it := range top.sub().items() {
switch {
case it.Kind == view.EntryHeading:
if len(out) > 0 && !out[len(out)-1].Heading {
out = append(out, view.PullItem{Label: it.Label, Heading: true})
}
case it.Kind == view.EntryMenu && !it.Disabled:
out = append(out, view.PullItem{Label: it.Label, Path: []string{label, it.Label}})
}
}
for len(out) > 0 && out[len(out)-1].Heading {
out = out[:len(out)-1]
}
return out
}
page := func(label string) view.PullItem { return view.PullItem{Label: label, Path: []string{label}} }
pd := func(label string, items ...[]view.PullItem) view.PullDown {
m := view.PullDown{Label: label}
for _, its := range items {
m.Items = append(m.Items, its...)
}
return m
}
one := func(its ...view.PullItem) []view.PullItem { return its }
rule := view.PullItem{Heading: true}
return []view.PullDown{
pd("File", one(page(mReview), page(mCheck), rule,
view.PullItem{Label: "Save and exit F10", Action: view.SheetSave},
view.PullItem{Label: "Quit without saving F9", Action: view.SheetQuit})),
pd("Setup", one(page(mBoard), page(mSystem), page(mUsers), page(mMaint), rule,
view.PullItem{Label: "All settings, by section", Path: []string{mSystem, "All settings, by section"}})),
pd("Lines", one(page(mLines), rule), expand(mLines, false)),
pd("Internet", one(page(mInternet), rule), expand(mInternet, false)),
pd("Online", expand(mOnline, true), expand(mChat, true)),
pd("Mail", one(page(mMail), rule), expand(mMail, false)),
pd("Networks", one(page(mNetworks), rule), expand(mNetworks, false)),
pd("Time", one(page(mTime), rule), expand(mTime, false)),
}
}
// count is how many sections of a kind there are, in words.
func (e *Editor) count(kind string, keep func(confedit.Section) bool, noun string) string {
n := len(e.instances(kind, keep))
@@ -163,21 +271,40 @@ func (e *Editor) onOff(s confedit.Section) string {
return "off"
}
// servicesMenu is Services: listeners by type, the servers whose section
// turns them on, and the networks and doors.
func (e *Editor) servicesMenu() page {
ofType := func(t string) func(confedit.Section) bool {
return func(s confedit.Section) bool { return listenType(e, s) == t }
// ofType keeps the listeners of a type.
func (e *Editor) ofType(t string) func(confedit.Section) bool {
return func(s confedit.Section) bool { return listenType(e, s) == t }
}
// ofFrontEnd keeps the listeners that answer as a front end (compuserve,
// marvel).
func (e *Editor) ofFrontEnd(f string) func(confedit.Section) bool {
return func(s confedit.Section) bool {
v, _ := e.doc.Get(s, "frontend")
return v == f
}
}
// single is an item for a section whose being there turns a server on:
// its page has Enabled and its keys.
func (e *Editor) single(label, kind string) item {
it := menu(label, e.onOff(sec(kind)), func() error { return e.show(e.sectionPage(sec(kind), label, true)) })
if k := e.cat.Kind(kind); k != nil {
it.Help = firstSentence(k.Help)
it.help = k.Help
}
return it
}
// servicesMenu is Internet services: the terminals' listeners by type, and
// the servers whose section turns them on.
func (e *Editor) servicesMenu() page {
listeners := func(label, t, addr string) item {
return menu(label, e.count("listen", ofType(t), "listener"), func() error {
return e.show(e.listeners(ofType(t), label, map[string]string{"type": t, "address": addr}))
return menu(label, e.count("listen", e.ofType(t), "listener"), func() error {
return e.show(e.listeners(e.ofType(t), label, map[string]string{"type": t, "address": addr}))
})
}
single := func(label, kind string) item {
return menu(label, e.onOff(sec(kind)), func() error { return e.show(e.sectionPage(sec(kind), label, true)) })
}
return page{title: "Services", items: func() []item {
return page{title: mInternet, items: func() []item {
return []item{
heading("Callers' terminals"),
listeners("Telnet", "telnet", ":23"),
@@ -185,15 +312,112 @@ func (e *Editor) servicesMenu() page {
listeners("SSH", "ssh", ":22"),
listeners("RLogin", "rlogin", "127.0.0.1:513"),
heading("Servers"),
single("Finger", "finger"),
single("Gopher", "gopher"),
single("Gemini", "gemini"),
single("FTP", "ftp"),
single("IRC (ircd)", "irc"),
e.single("Finger", "finger"),
e.single("Gopher", "gopher"),
e.single("Gemini", "gemini"),
e.single("FTP", "ftp"),
menu("News (NNTP)", e.onOff(sec("nntp")), func() error { return e.show(e.newsPage()) }),
menu("Web: API, forum, image boards", e.onOff(sec("http")), func() error { return e.show(e.webPage()) }),
heading("Networks and doors"),
single("Multi Relay Chat", "mrc"),
}
}}
}
// onlineMenu is Online services: the dial-up services of the 1990s the BBS
// answers as, for their own client programs.
func (e *Editor) onlineMenu() page {
return page{title: mOnline,
note: []view.Line{view.T(view.Dim, "The BBS as the online services, for their own client programs.")},
items: func() []item {
return []item{
e.single("America Online (AOL)", "aol"),
menu("CompuServe (CIS)", e.count("listen", e.ofFrontEnd("compuserve"), "listener"), func() error {
return e.show(e.frontEndListeners("CompuServe (CIS)", "compuserve",
"Listeners with frontend = compuserve answer as CompuServe.",
map[string]string{"type": "telnet", "address": ":2324", "frontend": "compuserve"}))
}),
menu("The Microsoft Network (MSN 1995)", e.onOff(sec("marvel")), func() error { return e.show(e.marvelPage()) }),
}
}}
}
// frontEndListeners is the listeners that answer as a front end, with a
// word on it; added ones get the keys of with.
func (e *Editor) frontEndListeners(title, frontend, note string, with map[string]string) page {
p := e.listeners(e.ofFrontEnd(frontend), title, with)
p.note = []view.Line{view.T(view.Dim, note)}
return p
}
// marvelPage is MSN Classic: its TCP host, and its dial-in listeners.
func (e *Editor) marvelPage() page {
return page{title: "The Microsoft Network (MSN 1995)", items: func() []item {
out := []item{e.enabled(sec("marvel"), "Over TCP (port 569)")}
out = append(out, e.sectionFields(sec("marvel"))...)
out = append(out, heading("Modem callers"),
menu("Listeners with frontend = marvel", e.count("listen", e.ofFrontEnd("marvel"), "listener"), func() error {
return e.show(e.frontEndListeners("MSN dial-in listeners", "marvel",
"Windows 95's MSN client dialing in comes through these.",
map[string]string{"type": "raw", "address": "127.0.0.1:2325", "frontend": "marvel"}))
}))
return out
}}
}
// chatMenu is Messengers and chat: the instant messengers, IRC and its
// links, Multi Relay Chat.
func (e *Editor) chatMenu() page {
return page{title: mChat, items: func() []item {
return []item{
heading("Instant messengers"),
e.single("AIM and ICQ (OSCAR)", "oscar"),
e.single("MSN Messenger", "msn"),
e.single("Yahoo! Messenger", "ymsg"),
heading("IRC"),
e.single("IRC server", "irc"),
menu("IRC network links", e.onOff(sec("irclink")), func() error { return e.show(e.ircLinkPage()) }),
heading("Between BBSes"),
e.single("Multi Relay Chat", "mrc"),
}
}}
}
// ircLinkPage is IRC server linking: [irclink] and the [ircpeer]s.
func (e *Editor) ircLinkPage() page {
return page{title: "IRC network links", items: func() []item {
out := []item{e.enabled(sec("irclink"), "Linked to a network")}
out = append(out, e.sectionFields(sec("irclink"))...)
out = append(out, heading("Servers linked with"), menu("Peer servers", e.count("ircpeer", nil, "server"), func() error {
return e.show(e.listPage("Peer servers", "ircpeer", "server", nil, func(s confedit.Section) string {
a, _ := e.doc.Get(s, "address")
return a
}, nil))
}))
return out
}}
}
// mailMenu is E-mail: [mail], the smarthost, and each mail server.
func (e *Editor) mailMenu() page {
return page{title: mMail, items: func() []item {
out := []item{e.enabled(sec("mail"), "E-mail")}
out = append(out, e.sectionFields(sec("mail"))...)
out = append(out,
heading("Sending"),
e.single("Smarthost (send through)", "smarthost"),
heading("Servers"),
e.single("POP3", "pop3"),
e.single("IMAP", "imap"),
e.single("SMTP submission", "smtp"),
e.single("MX (mail from the internet)", "mx"),
e.single("LMTP (from a mail server)", "lmtp"))
return out
}}
}
// networksMenu is Networks and doors: FidoNet, QWK, the doors.
func (e *Editor) networksMenu() page {
return page{title: mNetworks, items: func() []item {
return []item{
menu("FidoNet", e.onOff(sec("fido")), func() error { return e.show(e.fidoPage()) }),
menu("QWK networks", e.count("qwknet", nil, "network"), func() error {
return e.show(e.listPage("QWK networks", "qwknet", "network", nil, func(s confedit.Section) string {
@@ -211,6 +435,19 @@ func (e *Editor) servicesMenu() page {
}}
}
// timeMenu is Time: the clock the BBS follows, and its time servers.
func (e *Editor) timeMenu() page {
return page{title: mTime, items: func() []item {
return []item{
e.single("Clock and time sources", "time"),
heading("Time servers"),
e.single("NTP server", "ntp"),
e.single("NTS-KE server (secure NTP)", "nts"),
e.single("PTP grandmaster", "ptp"),
}
}}
}
// tn3270Page is TN3270: the 3270 pictures and logo, and the tn3270 key of
// each telnet listener.
func (e *Editor) tn3270Page() page {
+6 -1
View File
@@ -42,6 +42,7 @@ import (
"github.com/D-Modem/bbs/internal/sockets"
"github.com/D-Modem/bbs/internal/store"
"github.com/D-Modem/bbs/internal/ui3270"
"github.com/D-Modem/bbs/internal/ymsg"
)
// Config is the whole configuration.
@@ -72,6 +73,7 @@ type Config struct {
AOL *aol.Settings // nil: no host for AOL clients
MSN *msn.Settings // nil: no MSN Messenger server
Marvel *marvel.Settings // nil: no host for the MSN (1995) client over TCP
YMSG *ymsg.Settings // nil: no Yahoo! Messenger server
MRC *mrc.Settings // nil: not on Multi Relay Chat
IRCLink *irclink.Settings // nil: not linked to an IRC network
Screens *screens.Set // nil: no screens of the sysop's
@@ -159,6 +161,9 @@ func load(cf *config.File) (*Config, error) {
if err := c.aolSection(cf); err != nil {
return nil, err
}
if err := c.ymsgSection(cf); err != nil {
return nil, err
}
if err := c.msnSection(cf); err != nil {
return nil, err
}
@@ -240,7 +245,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", "gemini", "time", "ntp", "nts", "ptp", "irc", "oscar", "aol", "msn", "marvel", "mrc", "irclink", "ircpeer", "menu", "strings", "http", "level", "chan",
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "gemini", "time", "ntp", "nts", "ptp", "irc", "oscar", "aol", "msn", "marvel", "ymsg", "mrc", "irclink", "ircpeer", "menu", "strings", "http", "level", "chan",
"mail", "smarthost", "pop3", "imap", "smtp", "mx", "lmtp":
default:
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
+7 -7
View File
@@ -133,19 +133,19 @@ func TestConfigScreens(t *testing.T) {
saved(t, e, p)
}
// TestConfigScreensANSI: on an ANSI terminal, the full screen: the arrow
// keys, Enter to change a value, F10 to save and leave.
// TestConfigScreensANSI: on an ANSI terminal, the setup screens: the arrow
// keys, Enter to change a value in its box, F10 to save and leave.
func TestConfigScreensANSI(t *testing.T) {
e, p := configEnv(t, "yes")
s := ansiLogin(e)
s.send("*")
s.expect("Configuration")
s.send("F")
s.expect("F10 save+exit")
s.expect("Messengers and chat")
s.send("\x1b[B\x1b[A\r") // down, up: Board configuration
s.expect("Configuration > Board configuration")
s.expect("Sysop's name")
s.send("\r")
s.expect("BBS name: ")
s.expect("Clear") // the box the name is typed in
s.send("\x15Renamed BBS\r")
s.expect("1 change not saved")
s.send("\x1b[21~") // F10
@@ -158,9 +158,9 @@ func TestConfigQuit(t *testing.T) {
e, p := configEnv(t, "yes")
s := ansiLogin(e)
s.send("*F")
s.expect("F10 save+exit")
s.expect("Messengers and chat")
s.send("\r\r")
s.expect("BBS name: ")
s.expect("Clear")
s.send("\x15Not Saved\r")
s.expect("1 change not saved")
s.send("\x1b[20~") // F9
+64
View File
@@ -0,0 +1,64 @@
package server
import (
"crypto/tls"
"errors"
"fmt"
"net"
"strings"
"github.com/D-Modem/bbs/internal/config"
"github.com/D-Modem/bbs/internal/ymsg"
)
// ymsgSection reads [ymsg]: the Yahoo! Messenger server for the chat.
func (c *Config) ymsgSection(cf *config.File) error {
s := cf.Get("ymsg", "")
if s == nil {
return nil
}
err := func() error {
y := &ymsg.Settings{Address: s.String("address", ":5050"), HTTPAddress: s.String("http_address", ""),
HTTPSAddress: s.String("https_address", ""), CertFile: s.String("tls_cert", ""),
KeyFile: s.String("tls_key", ""), Host: s.String("host", ""), System: s.String("system", "bbs")}
for _, a := range []struct{ key, v string }{{"address", y.Address}, {"http_address", y.HTTPAddress},
{"https_address", y.HTTPSAddress}} {
if a.v == "" {
continue
}
if _, _, err := net.SplitHostPort(a.v); err != nil {
return fmt.Errorf("%s: %v", a.key, err)
}
}
if y.Address == "" {
return errors.New("address: where the pager listens (:5050)")
}
if y.HTTPSAddress != "" {
if y.CertFile == "" || y.KeyFile == "" {
return errors.New("https_address needs tls_cert and tls_key")
}
if _, err := tls.LoadX509KeyPair(y.CertFile, y.KeyFile); err != nil {
return fmt.Errorf("tls_cert, tls_key: %v", err)
}
}
if y.Host != "" && strings.ContainsAny(y.Host, ":/ ") && net.ParseIP(y.Host) == nil {
return errors.New("host: the pager's IP address or host name, without a port")
}
if y.System == "" || len(y.System) > 32 || strings.ContainsAny(y.System, "@ ") {
return errors.New("system: a Yahoo ID of 1 to 32 letters and digits")
}
var err error
if y.MaxClients, err = s.Int("max_clients", 256, 1, 100000); err != nil {
return err
}
if y.MaxPerIP, err = s.Int("max_per_ip", 4, 0, 1000); err != nil {
return err
}
c.YMSG = y
return nil
}()
if err != nil {
return fmt.Errorf("[ymsg] %w", err)
}
return nil
}
+1 -1
View File
@@ -13,7 +13,7 @@ import (
// copyOrder is the tables in an order their references allow.
var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "mailbox", "mail_uids", "mail_queue", "file_areas", "files",
"history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs",
"chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys", "chats", "friends", "oscar_buddies", "msn_keys", "blocks", "address_book", "ntlm_keys"}
"chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys", "chats", "friends", "oscar_buddies", "msn_keys", "blocks", "address_book", "ntlm_keys", "ymsg_keys"}
var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`)
+6
View File
@@ -302,6 +302,12 @@ CREATE TABLE IF NOT EXISTS msn_keys (
digest {str} NOT NULL,
bound {str} NOT NULL
)`, `
CREATE TABLE IF NOT EXISTS ymsg_keys (
user_id {int} NOT NULL PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
pass {str} NOT NULL,
crypt {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,
+7
View File
@@ -132,6 +132,8 @@ type Store struct {
keepMSN atomic.Bool
// keepNTLM: and their LM and NT hashes, for MSN Classic's 1996 client (ntlm.go)
keepNTLM atomic.Bool
// keepYMSG: and their Yahoo! Messenger digests (ymsg.go)
keepYMSG atomic.Bool
}
// Open opens (and makes, if need be) the database at addr: a file's path
@@ -271,6 +273,7 @@ func (s *Store) CreateUser(name, password, location string, sysop bool) (*User,
s.KeepCISKey(id, password)
s.KeepMSNKey(id, password)
s.KeepNTLMKey(id, password)
s.KeepYMSGKeys(id, password)
}
return s.UserByID(id)
}
@@ -306,6 +309,7 @@ func (s *Store) CheckPassword(name, pw string) (*User, error) {
s.KeepCISKey(u.ID, pw)
s.KeepMSNKey(u.ID, pw)
s.KeepNTLMKey(u.ID, pw)
s.KeepYMSGKeys(u.ID, pw)
return u, nil
}
@@ -327,6 +331,9 @@ func (s *Store) SetPassword(id int64, pw string) error {
if err := s.KeepNTLMKey(id, pw); err != nil {
return err
}
if err := s.KeepYMSGKeys(id, pw); err != nil {
return err
}
return s.KeepOSCARKeys(id, pw)
}
+166
View File
@@ -0,0 +1,166 @@
package store
import (
"crypto/md5"
"database/sql"
"errors"
)
// Yahoo! Messenger's challenge login (Y!M 5.x, auth type 0) proves the
// password by two digests of it mixed with the server's challenge:
// MD5(password) and MD5(md5crypt(password, "$1$_2S43d5f$")), each in
// Yahoo's base 64. The salt is fixed, so both are kept, made whenever the
// password is known in the clear and bound to the password hash they were
// made with, as the AIM and MSN digests are (oscar.go, msn.go). Either
// is as good as the password to a Yahoo client: anyone who read them
// from the database could sign in by Yahoo as that user.
// YMSGKeys are an account's two Yahoo digests, in Yahoo's base 64.
type YMSGKeys struct {
Pass string // Y64(MD5(password))
Crypt string // Y64(MD5(md5crypt(password, "$1$_2S43d5f$")))
}
// YMSGDigests are the digests of pw.
func YMSGDigests(pw string) YMSGKeys {
p := md5.Sum([]byte(pw))
c := md5.Sum([]byte(MD5Crypt(pw, "_2S43d5f")))
return YMSGKeys{Pass: Y64(p[:]), Crypt: Y64(c[:])}
}
// y64digits are Yahoo's base 64 digits: "+/=" are "._-".
const y64digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._"
// Y64 is b in Yahoo's base 64 (padded with '-').
func Y64(b []byte) string {
out := make([]byte, 0, (len(b)+2)/3*4)
for ; len(b) >= 3; b = b[3:] {
out = append(out, y64digits[b[0]>>2], y64digits[(b[0]<<4&0x30)|b[1]>>4],
y64digits[(b[1]<<2&0x3c)|b[2]>>6], y64digits[b[2]&0x3f])
}
switch len(b) {
case 1:
out = append(out, y64digits[b[0]>>2], y64digits[b[0]<<4&0x30], '-', '-')
case 2:
out = append(out, y64digits[b[0]>>2], y64digits[(b[0]<<4&0x30)|b[1]>>4], y64digits[b[1]<<2&0x3c], '-')
}
return string(out)
}
// MD5Crypt is the FreeBSD MD5 crypt of pw with salt (at most 8
// characters): "$1$salt$hash".
func MD5Crypt(pw, salt string) string {
if len(salt) > 8 {
salt = salt[:8]
}
p, s := []byte(pw), []byte(salt)
alt := md5.New()
alt.Write(p)
alt.Write(s)
alt.Write(p)
final := alt.Sum(nil)
h := md5.New()
h.Write(p)
h.Write([]byte("$1$"))
h.Write(s)
for n := len(p); n > 0; n -= 16 {
h.Write(final[:min(n, 16)])
}
for n := len(p); n > 0; n >>= 1 {
if n&1 != 0 {
h.Write([]byte{0})
} else {
h.Write(p[:1])
}
}
final = h.Sum(nil)
for i := range 1000 {
r := md5.New()
if i&1 != 0 {
r.Write(p)
} else {
r.Write(final)
}
if i%3 != 0 {
r.Write(s)
}
if i%7 != 0 {
r.Write(p)
}
if i&1 != 0 {
r.Write(final)
} else {
r.Write(p)
}
final = r.Sum(nil)
}
const itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
out := []byte("$1$" + salt + "$")
put := func(v uint32, n int) {
for ; n > 0; n-- {
out = append(out, itoa64[v&0x3f])
v >>= 6
}
}
f := final
put(uint32(f[0])<<16|uint32(f[6])<<8|uint32(f[12]), 4)
put(uint32(f[1])<<16|uint32(f[7])<<8|uint32(f[13]), 4)
put(uint32(f[2])<<16|uint32(f[8])<<8|uint32(f[14]), 4)
put(uint32(f[3])<<16|uint32(f[9])<<8|uint32(f[15]), 4)
put(uint32(f[4])<<16|uint32(f[10])<<8|uint32(f[5]), 4)
put(uint32(f[11]), 2)
return string(out)
}
// SetKeepYMSG says whether to keep the digests: only with a Yahoo
// server, as they would let anyone who read the database sign in by
// Yahoo.
func (s *Store) SetKeepYMSG(on bool) { s.keepYMSG.Store(on) }
// YMSGKeys are the account's digests; ok false: none current (none kept,
// or the password changed since).
func (s *Store) YMSGKeys(id int64) (k YMSGKeys, ok bool, err error) {
var bound, hash string
err = s.db.QueryRow(`SELECT y.pass, y.crypt, y.bound, u.password FROM ymsg_keys y
JOIN users u ON u.id = y.user_id WHERE y.user_id = ?`, id).Scan(&k.Pass, &k.Crypt, &bound, &hash)
if errors.Is(err, sql.ErrNoRows) {
return YMSGKeys{}, false, nil
}
if err != nil {
return YMSGKeys{}, false, err
}
return k, bound == hash && k.Pass != "", nil
}
// KeepYMSGKeys makes the account's digests of pw (its password, just
// checked or set), bound to its password hash now, if the store keeps
// them (SetKeepYMSG). Nothing is written if they are current already.
func (s *Store) KeepYMSGKeys(id int64, pw string) error {
if !s.keepYMSG.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
}
k := YMSGDigests(pw)
if old, ok, err := s.YMSGKeys(id); err == nil && ok && old == k {
return nil
}
t, err := s.db.Begin()
if err != nil {
return err
}
defer t.Rollback()
if _, err := t.Exec(`DELETE FROM ymsg_keys WHERE user_id = ?`, id); err != nil {
return err
}
if _, err := t.Exec(`INSERT INTO ymsg_keys (user_id, pass, crypt, bound) VALUES (?, ?, ?, ?)`,
id, k.Pass, k.Crypt, hash); err != nil {
return err
}
return t.Commit()
}
+47
View File
@@ -0,0 +1,47 @@
package store
import (
"path/filepath"
"testing"
)
// TestYMSGKeys: the digests' forms, kept only when asked, stale once the
// password changes.
func TestYMSGKeys(t *testing.T) {
// openssl passwd -1 -salt _2S43d5f password
if got := MD5Crypt("password", "_2S43d5f"); got != "$1$_2S43d5f$Cb/MEl/9lyqcT5fwKLPnX0" {
t.Errorf("md5crypt: %s", got)
}
if got := Y64([]byte{0xfb, 0xff, 0x01}); got != "._8B" {
t.Errorf("y64: %s", got)
}
if got := Y64([]byte{0xff}); got != "_w--" {
t.Errorf("y64 padding: %s", got)
}
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.YMSGKeys(u.ID); ok {
t.Fatal("kept without SetKeepYMSG")
}
s.SetKeepYMSG(true)
if _, err := s.CheckPassword("alice", "password1"); err != nil {
t.Fatal(err)
}
k, ok, err := s.YMSGKeys(u.ID)
if err != nil || !ok || k != YMSGDigests("password1") {
t.Fatalf("keys %+v %v %v", k, ok, err)
}
s.db.Exec(`UPDATE users SET password = ? WHERE id = ?`, "x", u.ID)
if _, ok, _ := s.YMSGKeys(u.ID); ok {
t.Error("stale digests used")
}
s.SetPassword(u.ID, "password2")
if k, ok, _ := s.YMSGKeys(u.ID); !ok || k != YMSGDigests("password2") {
t.Errorf("after set: %+v %v", k, ok)
}
}
+297
View File
@@ -0,0 +1,297 @@
package textui
import (
"strconv"
"strings"
"unicode/utf8"
)
// The desk: a full screen drawn in character cells, as the setup programs
// of the 1990s drew theirs (blue windows over a shaded desktop, a menu bar,
// a bar of keys). What is drawn is kept, and only the cells that changed
// are sent, so that a caller at 2400 bit/s is not sent the whole screen for
// a moved bar.
// The sixteen colors of a PC's text mode: 0-7 as backgrounds too.
const (
cBlack = iota
cBlue
cGreen
cCyan
cRed
cMagenta
cBrown
cLightGray
cDarkGray
cLightBlue
cLightGreen
cLightCyan
cLightRed
cLightMagenta
cYellow
cWhite
)
// attr is a cell's colors: foreground (0-15) and background (0-7).
type attr struct{ fg, bg uint8 }
// cell is a character cell.
type cell struct {
r rune
a attr
}
// screen is a screen's cells.
type screen struct {
cols, rows int
c []cell
}
func newScreen(cols, rows int) *screen {
s := &screen{cols: cols, rows: rows, c: make([]cell, cols*rows)}
for i := range s.c {
s.c[i] = cell{' ', attr{cLightGray, cBlack}}
}
return s
}
// clone is a copy of s.
func (s *screen) clone() *screen {
n := &screen{cols: s.cols, rows: s.rows, c: make([]cell, len(s.c))}
copy(n.c, s.c)
return n
}
// at is the cell at row and column (from 0), nil off the screen.
func (s *screen) at(row, col int) *cell {
if row < 0 || col < 0 || row >= s.rows || col >= s.cols {
return nil
}
return &s.c[row*s.cols+col]
}
// put writes str from row, col in a, cut at the screen's edge; how many
// cells it took.
func (s *screen) put(row, col int, str string, a attr) int {
n := 0
for _, r := range str {
if c := s.at(row, col+n); c != nil {
*c = cell{r, a}
}
n++
}
return n
}
// putw writes str in exactly w cells: cut, or padded with spaces.
func (s *screen) putw(row, col, w int, str string, a attr) {
s.put(row, col, fit(str, w), a)
}
// fill fills a rectangle with r in a.
func (s *screen) fill(row, col, h, w int, r rune, a attr) {
for y := row; y < row+h; y++ {
for x := col; x < col+w; x++ {
if c := s.at(y, x); c != nil {
*c = cell{r, a}
}
}
}
}
// paint sets the colors of a rectangle, keeping its characters.
func (s *screen) paint(row, col, h, w int, a attr) {
for y := row; y < row+h; y++ {
for x := col; x < col+w; x++ {
if c := s.at(y, x); c != nil {
c.a = a
}
}
}
}
// boxStyle is a box's lines: corners, sides and the joins of a line
// across it.
type boxStyle struct{ tl, tr, bl, br, h, v, lj, rj rune }
var (
boxDouble = boxStyle{'╔', '╗', '╚', '╝', '═', '║', '╟', '╢'}
boxSingle = boxStyle{'┌', '┐', '└', '┘', '─', '│', '├', '┤'}
)
// box draws a box's frame and fills its inside.
func (s *screen) box(row, col, h, w int, st boxStyle, frame, inside attr) {
s.fill(row+1, col+1, h-2, w-2, ' ', inside)
for x := col + 1; x < col+w-1; x++ {
s.put(row, x, string(st.h), frame)
s.put(row+h-1, x, string(st.h), frame)
}
for y := row + 1; y < row+h-1; y++ {
s.put(y, col, string(st.v), frame)
s.put(y, col+w-1, string(st.v), frame)
}
s.put(row, col, string(st.tl), frame)
s.put(row, col+w-1, string(st.tr), frame)
s.put(row+h-1, col, string(st.bl), frame)
s.put(row+h-1, col+w-1, string(st.br), frame)
}
// rule draws a line across a box at row, joined to its sides.
func (s *screen) rule(row, col, w int, st boxStyle, a attr) {
s.put(row, col, string(st.lj), a)
for x := col + 1; x < col+w-1; x++ {
s.put(row, x, "─", a)
}
s.put(row, col+w-1, string(st.rj), a)
}
// title puts a title in a box's top line, centered: "[ Title ]".
func (s *screen) title(row, col, w int, t string, a attr) {
t = " " + trunc(t, w-6) + " "
s.put(row, col+(w-len([]rune(t)))/2, t, a)
}
// shadow darkens the cells to the right of and below a rectangle, as a
// window's shadow on the desk.
func (s *screen) shadow(row, col, h, w int) {
dark := attr{cDarkGray, cBlack}
s.paint(row+1, col+w, h, 2, dark)
s.paint(row+h, col+2, 1, w, dark)
}
// render is what turns the terminal's screen, old (nil: unknown), into s:
// each changed run of cells, with its colors. The last cell of the last
// line is left alone (writing it scrolls some terminals).
func (s *screen) render(old *screen, mono bool) string {
var b strings.Builder
if old == nil || old.cols != s.cols || old.rows != s.rows {
b.WriteString("\x1b[0m\x1b[2J")
old = nil
}
cur := attr{255, 255}
for y := 0; y < s.rows; y++ {
last := s.cols
if y == s.rows-1 {
last--
}
at := -1 // where the cursor is after the last cell written (-1: unknown)
for x := 0; x < last; x++ {
c := s.c[y*s.cols+x]
if old != nil && old.c[y*s.cols+x] == c {
// unchanged: skipped, unless a change follows so near
// that writing the cells costs less than moving
if at != x || !s.changedWithin(old, y, x, last, 8) {
continue
}
}
if at != x {
b.WriteString("\x1b[" + strconv.Itoa(y+1) + ";" + strconv.Itoa(x+1) + "H")
}
if c.a != cur {
b.WriteString(sgr(c.a, mono))
cur = c.a
}
r := c.r
if r < ' ' || r == 0x7f || !utf8.ValidRune(r) {
r = ' '
}
b.WriteRune(r)
at = x + 1
}
}
return b.String()
}
// changedWithin is whether a cell of row y from x, before last, within n
// of x, differs from old's.
func (s *screen) changedWithin(old *screen, y, x, last, n int) bool {
for i := x; i < min(x+n, last); i++ {
if old.c[y*s.cols+i] != s.c[y*s.cols+i] {
return true
}
}
return false
}
// sgr is the escape that gives a's colors (in mono: bright as bold, a light
// background as reverse).
func sgr(a attr, mono bool) string {
if mono {
s := "\x1b[0"
if a.fg >= 8 {
s += ";1"
}
if a.bg == cLightGray || a.bg == cCyan || a.bg == cGreen {
s += ";7"
}
return s + "m"
}
ansi := []int{0, 4, 2, 6, 1, 5, 3, 7} // the PC's order to ANSI's
s := "\x1b[0"
if a.fg >= 8 {
s += ";1"
}
return s + ";" + strconv.Itoa(30+ansi[a.fg%8]) + ";" + strconv.Itoa(40+ansi[a.bg%8]) + "m"
}
// fit is s cut or padded with spaces to exactly w runes.
func fit(s string, w int) string {
if w <= 0 {
return ""
}
r := []rune(s)
if len(r) > w {
return string(r[:w])
}
return s + strings.Repeat(" ", w-len(r))
}
// trunc is s cut to w runes, with "…" where it was cut.
func trunc(s string, w int) string {
r := []rune(s)
if w <= 0 {
return ""
}
if len(r) <= w {
return s
}
if w == 1 {
return string(r[:1])
}
return string(r[:w-1]) + "…"
}
// wrapText breaks s into lines of at most w runes, at spaces where it can.
func wrapText(s string, w int) []string {
var out []string
for _, para := range strings.Split(s, "\n") {
words := strings.Fields(para)
if len(words) == 0 {
out = append(out, "")
continue
}
line := ""
for _, wd := range words {
for len([]rune(wd)) > w {
if line != "" {
out = append(out, line)
line = ""
}
r := []rune(wd)
out = append(out, string(r[:w]))
wd = string(r[w:])
}
switch {
case line == "":
line = wd
case len([]rune(line))+1+len([]rune(wd)) <= w:
line += " " + wd
default:
out = append(out, line)
line = wd
}
}
out = append(out, line)
}
return out
}
+143
View File
@@ -0,0 +1,143 @@
package textui
import (
"bytes"
"strings"
"testing"
"time"
"github.com/D-Modem/bbs/internal/view"
)
// keyConn is a terminal whose keys are given and whose output is kept.
type keyConn struct {
in *bytes.Reader
out bytes.Buffer
}
func (c *keyConn) Read(p []byte) (int, error) { return c.in.Read(p) }
func (c *keyConn) Write(p []byte) (int, error) { return c.out.Write(p) }
func (c *keyConn) SetReadDeadline(time.Time) error { return nil }
func deskTerm(keys string, utf8 bool) (*session, *keyConn) {
c := &keyConn{in: bytes.NewReader([]byte(keys))}
t := NewTerm(c)
t.ANSI, t.UTF8, t.Cols, t.Rows = true, utf8, 80, 25
return &session{t: t}, c
}
// sample is a sheet of each kind of entry, with a pull-down menu.
func sample() *view.Sheet {
return &view.Sheet{Title: "Services", Crumbs: "Configuration > Services",
Entries: []view.Entry{
{ID: "h", Kind: view.EntryHeading, Label: "Servers"},
{ID: "name", Kind: view.EntryText, Label: "BBS name", Value: "Old", Help: "the name"},
{ID: "on", Kind: view.EntryBool, Label: "Enabled", Value: "no"},
{ID: "tls", Kind: view.EntryChoice, Label: "TLS", Choices: []string{"no", "optional", "required"}, Value: "no"},
{ID: "aol", Kind: view.EntryMenu, Label: "AOL"},
},
Menus: []view.PullDown{{Label: "File", Items: []view.PullItem{{Label: "Save", Action: view.SheetSave}}},
{Label: "Online", Items: []view.PullItem{{Label: "Online services", Heading: true},
{Label: "America Online", Path: []string{"Online services", "America Online"}},
{Label: "CompuServe", Path: []string{"Online services", "CompuServe"}}}}}}
}
// TestDeskSheet: a value typed in its box, a yes/no turned over, a choice
// picked from its list, a menu opened, a pull-down's item.
func TestDeskSheet(t *testing.T) {
for _, c := range []struct {
name, keys string
want view.SheetResult
}{
{"text", "\r\x15New\r", view.SheetResult{Action: view.SheetSet, Entry: 1, Values: map[string]string{"name": "New"}}},
{"bool", "\x1b[B\r", view.SheetResult{Action: view.SheetSet, Entry: 2, Values: map[string]string{"on": "yes"}}},
{"choice", "\x1b[B\x1b[B\r\x1b[B\x1b[B\r", view.SheetResult{Action: view.SheetSet, Entry: 3, Values: map[string]string{"tls": "required"}}},
{"menu", "A\r", view.SheetResult{Action: view.Pick, Entry: 4}},
{"save", "\x1b[21~", view.SheetResult{Action: view.SheetSave, Entry: 1}},
{"pull-down", "/\x1b[C\x1b[B\r", view.SheetResult{Action: view.SheetJump, Entry: 1, Jump: []string{"Online services", "CompuServe"}}},
{"pull-down action", "/\r", view.SheetResult{Action: view.SheetSave, Entry: 1}},
} {
s, conn := deskTerm(c.keys, true)
r, err := s.Sheet(sample())
if err != nil {
t.Errorf("%s: %v", c.name, err)
continue
}
if r.Action != c.want.Action || r.Entry != c.want.Entry || len(r.Values) != len(c.want.Values) ||
strings.Join(r.Jump, ">") != strings.Join(c.want.Jump, ">") {
t.Errorf("%s: %+v, not %+v", c.name, r, c.want)
}
for k, v := range c.want.Values {
if r.Values[k] != v {
t.Errorf("%s: %s = %q, not %q", c.name, k, r.Values[k], v)
}
}
out := conn.out.String()
for _, want := range []string{"╔", "Services", "░", "nline"} {
if !strings.Contains(out, want) {
t.Errorf("%s: no %q drawn", c.name, want)
}
}
}
}
// TestDeskCP437: a terminal without UTF-8 gets the lines and shading in
// code page 437, not question marks.
func TestDeskCP437(t *testing.T) {
s, conn := deskTerm("\x1b[21~", false)
if _, err := s.Sheet(sample()); err != nil {
t.Fatal(err)
}
out := conn.out.Bytes()
for _, b := range []byte{0xC9, 0xBB, 0xB0, 0xCD} { // ╔ ╗ ░ ═
if !bytes.Contains(out, []byte{b}) {
t.Errorf("no %#x", b)
}
}
if !bytes.Contains(out, []byte{0x10}) { // ►
t.Errorf("no ►")
}
if bytes.Contains(bytes.ReplaceAll(out, []byte("\x1b[?25l"), nil), []byte("?")) {
t.Errorf("a ? in %q", out)
}
}
// TestDeskDialogs: with the desk up, a question and help come up as
// dialogs over it; EndSheets clears it.
func TestDeskDialogs(t *testing.T) {
s, conn := deskTerm("\x1b[21~"+"y"+"\r", true)
if _, err := s.Sheet(sample()); err != nil {
t.Fatal(err)
}
yes, err := s.Confirm("Leave without saving 3 changes?", false)
if err != nil || !yes {
t.Fatalf("confirm: %v %v", yes, err)
}
if err := s.Show("Check", []view.Line{view.T(view.Good, "As the BBS would take it.")}); err != nil {
t.Fatal(err)
}
if !strings.Contains(conn.out.String(), "Confirm") || !strings.Contains(conn.out.String(), "As the BBS would take it.") {
t.Errorf("no dialogs in %q", conn.out.String())
}
s.EndSheets()
if s.desk != nil || !strings.HasSuffix(conn.out.String(), "\x1b[0m\x1b[2J\x1b[H\x1b[?25h") {
t.Errorf("desk not ended")
}
}
// TestRender: only what changed is sent again.
func TestRender(t *testing.T) {
a := newScreen(20, 5)
a.put(1, 1, "hello", attr{cYellow, cBlue})
first := a.render(nil, false)
if !strings.Contains(first, "\x1b[2J") || !strings.Contains(first, "hello") {
t.Errorf("first %q", first)
}
b := a.clone()
b.put(1, 1, "j", attr{cYellow, cBlue})
if got := b.render(a, false); got != "\x1b[2;2H\x1b[0;1;33;44mj" {
t.Errorf("diff %q", got)
}
if got := b.render(b, false); got != "" {
t.Errorf("no change %q", got)
}
}
+1313 -249
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -28,7 +28,8 @@ type session struct {
o Options
user *store.User
chatting bool // in a chat room: its lines shown as such
chatting bool // in a chat room: its lines shown as such
desk *desk // the full screen kept up between sheets (sheet.go), if it is up
}
// errHangup: the caller logged off.
+18
View File
@@ -111,6 +111,7 @@ func (s *session) Narrow() bool { return s.t.Narrow() }
// a key until it is an item's. It is that item's key; "" for Enter (none
// chosen: the caller shows its menu again, or goes back if it will).
func (s *session) Menu(m *view.Menu) (string, error) {
s.EndSheets()
t := s.t
if len(m.Intro) > 0 {
t.Println("")
@@ -164,6 +165,7 @@ func (s *session) Menu(m *view.Menu) (string, error) {
// action's key, More at Enter if there is more, or Back. With nothing to
// pick or do it pauses at the end and is Back.
func (s *session) Table(tb *view.Table) (view.Choice, error) {
s.EndSheets()
t := s.t
t.Println("")
t.Println(t.C(Cyan, tb.Title))
@@ -272,6 +274,7 @@ func (s *session) Table(tb *view.Table) (view.Choice, error) {
// picture, its body a page at a time; then waits for an action's key (Q:
// Quit, Enter or space: Default, each Back if unset).
func (s *session) Message(m *view.Message) (string, error) {
s.EndSheets()
t := s.t
t.Clear()
t.Println(t.C(Dim, m.Where))
@@ -319,6 +322,9 @@ func (s *session) Message(m *view.Message) (string, error) {
// Form asks for each field in turn, Enter keeping its value; nothing typed
// for a first field with no value is giving up (false).
func (s *session) Form(f *view.Form) (map[string]string, bool, error) {
if s.desk != nil && len(f.Fields) > 0 {
return s.formBox(s.deskBase(), f)
}
t := s.t
for _, l := range f.Intro {
t.Println(s.line(l))
@@ -365,6 +371,7 @@ func (s *session) Form(f *view.Form) (map[string]string, bool, error) {
// Panel shows a panel's title, picture and lines, and reads a key: an
// action's ID, Back for Q or Enter, "" for any other.
func (s *session) Panel(p *view.Panel) (string, error) {
s.EndSheets()
t := s.t
t.Println("")
t.Println(t.C(Cyan, p.Title))
@@ -399,6 +406,7 @@ func (s *session) Panel(p *view.Panel) (string, error) {
// line editor; true if it was sent. An error sending is told the caller,
// and is false.
func (s *session) Edit(d *view.Draft) (bool, error) {
s.EndSheets()
t := s.t
t.Println("")
to := d.To
@@ -466,12 +474,19 @@ func (s *session) Edit(d *view.Draft) (bool, error) {
// Confirm asks a yes or no question, def at Enter.
func (s *session) Confirm(question string, def bool) (bool, error) {
if s.desk != nil {
return s.confirmBox(s.deskBase(), question, def)
}
return s.t.YesNo(question, def)
}
// Say prints msg in its tone; a Bright one as a heading, after a blank
// line.
func (s *session) Say(tn view.Tone, msg string) {
if s.desk != nil {
s.desk.flash = msg // at the foot of the next screen
return
}
if tn == view.Bright {
s.t.Println("")
s.t.Println(s.t.C(Cyan, msg))
@@ -483,6 +498,9 @@ func (s *session) Say(tn view.Tone, msg string) {
// Show shows a title and lines a page at a time, and waits for a key at
// the end (not if the caller quit before it).
func (s *session) Show(title string, ls []view.Line) error {
if s.desk != nil {
return s.messageBox(s.deskBase(), title, ls)
}
t := s.t
t.Println("")
t.Println(t.C(Cyan, title))
+17 -8
View File
@@ -25,15 +25,24 @@ func TestKeyLabel(t *testing.T) {
}
}
// TestSheetFoot: the key line names a sheet's keys, leaving out those with
// TestSheetFoot: the key bar names a sheet's keys, leaving out those with
// a 3270 PF key alone (no NUL for them).
func TestSheetFoot(t *testing.T) {
term, c := ansiTerm()
d := &sheetDraw{t: term, sh: &view.Sheet{Keys: []view.Action{{Key: 'A', Label: "Add"}, {PF: 5, Label: "PFonly"}}}, cur: -1}
d.drawFoot()
term.Flush()
out := c.String()
if strings.Contains(out, "\x00") || strings.Contains(out, "PFonly") || !strings.Contains(out, "A Add Enter change") {
t.Errorf("foot %q", out)
term, _ := ansiTerm()
s := &session{t: term}
s.startDesk()
w := &sheetWin{s: s, sh: &view.Sheet{Title: "T", Keys: []view.Action{{Key: 'A', Label: "Add"}, {PF: 5, Label: "PFonly"}}}, cur: -1}
bar := screenRow(w.frame(), term.Rows-1)
if strings.Contains(bar, "\x00") || strings.Contains(bar, "PFonly") || !strings.Contains(bar, "A Add F9 Quit") {
t.Errorf("key bar %q", bar)
}
}
// screenRow is a screen's row as text.
func screenRow(scr *screen, row int) string {
var b strings.Builder
for x := 0; x < scr.cols; x++ {
b.WriteRune(scr.at(row, x).r)
}
return b.String()
}
+30
View File
@@ -16,6 +16,24 @@ type Sheet struct {
Cursor int // the entry the cursor begins on
Keys []Action // more keys (A Add, D Delete ...), with PF keys on a 3270
Status string // the foot's left: "3 changes not saved"
// Menus are the pull-down menus of a menu bar, where the front end
// draws one (a text terminal's full screen): picking an item jumps
// to its Path, or does its Action
Menus []PullDown
}
// PullDown is a pull-down menu of a menu bar.
type PullDown struct {
Label string
Items []PullItem
}
// PullItem is a pull-down menu's line.
type PullItem struct {
Label string
Path []string // where it jumps: the labels of the entries to open, from the first sheet
Action string // or what it does (SheetSave, SheetQuit), as a sheet's result
Heading bool // a line between groups (Label: its words, if any)
}
// EntryKind is what an entry is.
@@ -61,6 +79,18 @@ type SheetResult struct {
Action string // Pick (a Menu or Action entry chosen), SheetSet, SheetSave, SheetQuit, Back, a Keys ID
Entry int // the entry the cursor was on
Values map[string]string // SheetSet: entries' new values by ID (a 3270 sends all it changed at once)
Jump []string // SheetJump: a pull-down item's Path
}
// SheetJump is a sheet's result when a pull-down item was picked: go to
// its Path.
const SheetJump = "jump"
// SheetEnder is a front end that keeps its full screen up between sheets
// (to put questions and help over it): EndSheets puts it away when they
// are done.
type SheetEnder interface {
EndSheets()
}
// SheetUI is a front end that draws sheets full-screen.
+287
View File
@@ -0,0 +1,287 @@
package ymsg
import (
"context"
"crypto/tls"
"encoding/xml"
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/sockets"
)
// The web half: what a Yahoo client asks of Yahoo's web servers, once
// their names are pointed here.
//
// /capacity (vcs1.msg.yahoo.com): where the pager is, for Y!M 9 and later
// /config/pwtoken_get, /config/pwtoken_login (login.yahoo.com, HTTPS):
// the YMSG 16 login: the password, then the token it gave
// /ycontent/ (insider.msg.yahoo.com): the chat room list
// serveWeb serves the web half until ctx is done.
func (s *Server) serveWeb(ctx context.Context) error {
errs := make(chan error, 2)
var srvs []*http.Server
start := func(addr string, cfg *tls.Config) error {
ln, err := sockets.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("ymsg: %w", err)
}
if cfg != nil {
ln = tls.NewListener(ln, cfg)
}
hs := &http.Server{Handler: s, ReadHeaderTimeout: 30 * time.Second, WriteTimeout: time.Minute,
ErrorLog: nil}
srvs = append(srvs, hs)
go func() {
if err := hs.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
errs <- fmt.Errorf("ymsg: web: %w", err)
}
}()
return nil
}
if s.S.HTTPAddress != "" {
if err := start(s.S.HTTPAddress, nil); err != nil {
return err
}
}
if s.S.HTTPSAddress != "" {
cert, err := tls.LoadX509KeyPair(s.S.CertFile, s.S.KeyFile)
if err != nil {
return fmt.Errorf("ymsg: tls_cert, tls_key: %w", err)
}
if err := start(s.S.HTTPSAddress, tlsConfig(cert)); err != nil {
return err
}
}
select {
case <-ctx.Done():
case err := <-errs:
for _, hs := range srvs {
hs.Close()
}
return err
}
for _, hs := range srvs {
hs.Close()
}
return nil
}
// tlsConfig takes the old clients: Windows XP's TLS 1.0, with RSA key
// exchange and 3DES or RC4 (all it has), as well as current ones.
func tlsConfig(cert tls.Certificate) *tls.Config {
return &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS10,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_RC4_128_SHA,
}}
}
// ServeHTTP answers the web half.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
host, _, _ := net.SplitHostPort(r.RemoteAddr)
if s.B.Refuse("ymsg", addr(r.RemoteAddr)) {
http.Error(w, "refused", http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "text/plain")
switch {
case r.URL.Path == "/capacity":
w.Write([]byte("COLO_CAPACITY=1\r\nCS_IP_ADDRESS=" + s.pagerHost(r) + "\r\n"))
case r.URL.Path == "/config/pwtoken_get":
s.pwtokenGet(w, r, host)
case r.URL.Path == "/config/pwtoken_login":
s.pwtokenLogin(w, r)
case strings.HasPrefix(r.URL.Path, "/ycontent"):
s.roomList(w, r)
default:
http.NotFound(w, r)
}
}
// addr is an address as a net.Addr.
type addr string
func (a addr) Network() string { return "tcp" }
func (a addr) String() string { return string(a) }
// pagerHost is the pager's IP address for a client: Host's, or the one
// it asked on.
func (s *Server) pagerHost(r *http.Request) string {
h := s.S.Host
if h == "" {
if la, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
h, _, _ = net.SplitHostPort(la.String())
}
}
if ip := net.ParseIP(h); ip != nil {
return ip.String()
}
if ips, err := net.LookupIP(h); err == nil {
for _, ip := range ips {
if ip.To4() != nil {
return ip.String()
}
}
}
return h
}
// body writes a login answer as Yahoo's did: CRLF lines, chunked (one
// library reads the chunk's length line as part of it).
func body(w http.ResponseWriter, lines ...string) {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
w.Write([]byte(strings.Join(lines, "\r\n") + "\r\n"))
}
// pwtokenGet checks a YMSG 16 client's password: the token for
// pwtoken_login, or Yahoo's error number.
func (s *Server) pwtokenGet(w http.ResponseWriter, r *http.Request, host string) {
q := r.URL.Query()
login, pw := strings.TrimSpace(q.Get("login")), q.Get("passwd")
if login == "" || pw == "" {
body(w, "100")
return
}
name := login
if t := s.resolve(login); t != nil {
name = t.Name
}
u, err := s.B.Authenticate("ymsg", "ip:"+host, name, pw)
if err == nil {
err = s.may(u)
}
if err != nil {
switch {
case errors.Is(err, bbs.ErrThrottled):
body(w, "1213")
case errors.Is(err, bbs.ErrLocked), errors.Is(err, bbs.ErrNotAllowed):
body(w, "1218")
default:
body(w, "1212")
}
return
}
tk := randomString(48)
s.mu.Lock()
s.expire()
s.tokens[tk] = &token{u: u, expires: time.Now().Add(tokenLife)}
s.mu.Unlock()
body(w, "0", "ymsgr="+tk, "partnerid="+randomString(16))
}
// pwtokenLogin spends a token: the crumb and cookies the client proves on
// the pager.
func (s *Server) pwtokenLogin(w http.ResponseWriter, r *http.Request) {
tk := r.URL.Query().Get("token")
s.mu.Lock()
s.expire()
t := s.tokens[tk]
delete(s.tokens, tk)
if t != nil {
t.crumb = randomString(16)
t.y = "v=1&n=" + randomString(26) + "&l=" + idOf(t.u) + "/o&p=" + randomString(20) + "&r=" + randomString(3) + "&lg=us&intl=us"
t.t = "z=" + randomString(24) + "&a=" + randomString(12) + "&sk=" + randomString(24) + "&d=" + randomString(30)
t.expires = time.Now().Add(tokenLife)
s.cookies[t.t] = t
}
s.mu.Unlock()
if t == nil {
body(w, "100")
return
}
const tail = "; path=/; domain=.yahoo.com"
w.Header().Add("Set-Cookie", "Y="+t.y+tail)
w.Header().Add("Set-Cookie", "T="+t.t+tail)
w.Header().Add("Set-Cookie", "B="+randomString(20)+"&b=3&s="+randomString(2)+tail)
body(w, "0", "crumb="+t.crumb, "Y="+t.y+tail, "T="+t.t+tail, "cookievalidfor=86400")
}
// cookie is the login a T cookie is from (nil: none, or expired), spent.
func (s *Server) cookie(v string) *token {
v = strings.TrimPrefix(strings.TrimSpace(v), "T=")
if i := strings.IndexByte(v, ';'); i >= 0 {
v = v[:i]
}
s.mu.Lock()
defer s.mu.Unlock()
s.expire()
t := s.cookies[v]
delete(s.cookies, v)
return t
}
// expire forgets old tokens (s.mu held).
func (s *Server) expire() {
now := time.Now()
for k, t := range s.tokens {
if now.After(t.expires) {
delete(s.tokens, k)
}
}
for k, t := range s.cookies {
if now.After(t.expires) {
delete(s.cookies, k)
}
}
}
// roomCategory is the one category the room list has.
const roomCategory = "1600000002"
// roomList is the chat room browser's: one category, the BBS's rooms in
// it (those in use, and the permanent ones).
func (s *Server) roomList(w http.ResponseWriter, r *http.Request) {
type lobby struct {
Count int `xml:"count,attr"`
Users int `xml:"users,attr"`
Voices int `xml:"voices,attr"`
Webcams int `xml:"webcams,attr"`
}
type room struct {
Type string `xml:"type,attr"`
ID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Topic string `xml:"topic,attr"`
Lobby lobby `xml:"lobby"`
}
type category struct {
ID string `xml:"id,attr"`
Name string `xml:"name,attr"`
}
type content struct {
XMLName xml.Name `xml:"content"`
Time int64 `xml:"time,attr"`
Categories []category `xml:"chatCategories>category,omitempty"`
Rooms []room `xml:"chatRooms>room,omitempty"`
}
c := content{Time: time.Now().Unix()}
q := r.URL.RawQuery
if strings.Contains(q, "chatroom_") {
for i, ri := range s.B.PublicRooms() {
if strings.HasPrefix(ri.Name, "yc-") {
continue // conferences
}
c.Rooms = append(c.Rooms, room{Type: "yahoo", ID: i + 1, Name: ri.Name, Topic: ri.Topic,
Lobby: lobby{Count: 1, Users: len(ri.Users)}})
}
} else {
c.Categories = []category{{ID: roomCategory, Name: s.S.System + " chat rooms"}}
}
w.Header().Set("Content-Type", "text/xml")
b, _ := xml.Marshal(c)
w.Write([]byte(xml.Header))
w.Write(b)
}
+185
View File
@@ -0,0 +1,185 @@
package ymsg
import (
"fmt"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/D-Modem/bbs/internal/bbs"
"golang.org/x/text/encoding/charmap"
)
// event is something the node is told: a private message as an IM from
// its sender, a room's line to the chat room or conference it is, anything
// else as an IM from the BBS.
func (ss *session) event(e bbs.Event) {
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
}
if u, err := ss.s.B.Store.UserByName(e.From); err == nil {
if ss.s.B.Blocks(ss.u, u) {
return
}
ss.im(idOf(u), text, e.Time)
return
}
ss.im(ss.s.systemID(), e.From+": "+text, e.Time)
return
case bbs.Said, bbs.Emoted, bbs.Joined, bbs.Left, bbs.Topic:
ss.roomEvent(e, false)
return
case bbs.Notice:
if e.Room != "" && ss.roomEvent(e, false) {
return
}
case bbs.Paged:
text := fmt.Sprintf("%s (node %d) is paging you", e.From, e.Node)
if e.Text != "" {
text += ": " + e.Text
}
ss.system(text + fmt.Sprintf(" (join the chat room sysop-%d to answer)", e.Node))
return
}
ss.system(e.String())
}
// deliverKept gives the client the private messages kept for its user
// while they were away.
func (ss *session) deliverKept() {
ss.mu.Lock()
sent := ss.keptSent
ss.keptSent = true
ss.mu.Unlock()
if sent {
return
}
for _, e := range ss.n.Kept() {
ss.event(e)
}
}
// utf8OK: the client takes UTF-8 (key 97), Y!M 6 and later.
func (ss *session) utf8OK() bool { return ss.ver >= 11 }
// toClient is text for the client: UTF-8 if it takes it, else Windows-1252.
func (ss *session) toClient(text string) string {
if ss.utf8OK() {
return text
}
out, err := charmap.Windows1252.NewEncoder().String(strings.Map(func(r rune) rune {
if _, ok := charmap.Windows1252.EncodeRune(r); ok {
return r
}
return '?'
}, text))
if err != nil {
return text
}
return out
}
// im sends the client an IM.
func (ss *session) im(from, text string, at time.Time) {
p := &packet{service: svcMessage, status: stServerAck}
p.add(5, ss.id).add(4, from).add(14, ss.toClient(text))
if !at.IsZero() {
p.addInt(15, at.Unix())
}
if ss.utf8OK() {
p.add(97, "1")
}
ss.k.write(p)
}
var (
ansiCode = regexp.MustCompile(`\x1b\[[^m]{0,16}m`)
tags = regexp.MustCompile(`(?i)</?(font|fade|alt|b|i|u|s)(\s[^>]*)?>`)
)
// fromYahoo is a line from a client as plain text: UTF-8 (utf8 says it
// is; else it is Windows-1252 unless it reads as UTF-8), without its
// colour codes and font tags.
func fromYahoo(s string, isUTF8 bool) string {
if !isUTF8 && !utf8.ValidString(s) {
if d, err := charmap.Windows1252.NewDecoder().String(s); err == nil {
s = d
}
}
s = ansiCode.ReplaceAllString(s, "")
s = tags.ReplaceAllString(s, "")
return s
}
// message is MESSAGE: an IM to a BBS user.
func (ss *session) message(p *packet) {
to := p.get(5)
text := bbs.Clean(fromYahoo(p.get(14), p.get(97) == "1"), bbs.MaxChatLine*4)
if to == "" || text == "" {
return
}
t := ss.s.resolve(to)
if t == nil {
ss.system(to + " is not a user here.")
return
}
if t.ID == ss.u.ID {
return
}
for _, line := range splitLines(text) {
if _, err := ss.n.TellUser(t, line); err != nil {
ss.system("Your message to " + idOf(t) + " was not sent: " + err.Error())
return
}
}
}
// splitLines cuts text into lines the chat takes (at most MaxChatLine
// runes each).
func splitLines(text string) []string {
var out []string
for _, l := range strings.Split(text, "\n") {
r := []rune(strings.TrimSpace(l))
for len(r) > bbs.MaxChatLine {
cut := bbs.MaxChatLine
for i := cut; i > cut/2; i-- {
if r[i] == ' ' {
cut = i
break
}
}
out = append(out, string(r[:cut]))
r = []rune(strings.TrimSpace(string(r[cut:])))
}
if len(r) > 0 {
out = append(out, string(r))
}
}
return out
}
// notify is NOTIFY: typing (only Yahoo clients are told).
func (ss *session) notify(p *packet) {
if !strings.EqualFold(p.get(49), "TYPING") {
return
}
t := ss.s.resolve(p.get(5))
if t == nil || ss.s.B.Blocks(t, ss.u) {
return
}
on := p.get(13)
if on != "1" {
on = "0"
}
for _, x := range ss.s.sessionsOf(t.ID) {
x.do(func() {
if x.isOnline() {
x.k.send(svcNotify, stNotify, kv(5, x.id), kv(4, ss.id), kv(14, " "), kv(13, on), kv(49, "TYPING"))
}
})
}
}
+507
View File
@@ -0,0 +1,507 @@
package ymsg
import (
"sort"
"strconv"
"strings"
"time"
"github.com/D-Modem/bbs/internal/store"
)
// defaultGroup holds friends in no group.
const defaultGroup = "Friends"
// loadLists reads the user's friends and blocked lists.
func (ss *session) loadLists() {
st := ss.s.B.Store
fs, err := st.Friends(ss.u.ID)
if err != nil {
ss.s.B.Log.Printf("node %d: ymsg: friends: %v", ss.n.Num, err)
}
bs, err := st.Blocked(ss.u.ID)
if err != nil {
ss.s.B.Log.Printf("node %d: ymsg: blocked: %v", ss.n.Num, err)
}
ss.mu.Lock()
ss.friends = map[int64]store.Friend{}
for _, f := range fs {
ss.friends[f.ID] = f
}
ss.blocked = map[int64]string{}
for _, b := range bs {
ss.blocked[b.ID] = idOfName(b.Name)
}
ss.mu.Unlock()
}
// groupOf is a friend's group, as the client shows it.
func groupOf(f store.Friend) string {
if f.Group == "" {
return defaultGroup
}
return f.Group
}
// grouped are the friends by group, groups and friends in order.
func (ss *session) grouped() ([]string, map[string][]string) {
ss.mu.Lock()
defer ss.mu.Unlock()
by := map[string][]string{}
for _, f := range ss.friends {
g := groupOf(f)
by[g] = append(by[g], idOfName(f.Name))
}
var groups []string
for g := range by {
groups = append(groups, g)
sort.Strings(by[g])
}
sort.Strings(groups)
return groups, by
}
// ignored are the blocked list's IDs, in order.
func (ss *session) ignored() []string {
ss.mu.Lock()
defer ss.mu.Unlock()
var out []string
for _, id := range ss.blocked {
out = append(out, id)
}
sort.Strings(out)
return out
}
// cookies are the Y and T cookies the client is given (only what the
// client keeps, for its web links; nothing checks them).
func (ss *session) cookies() (string, string) {
y := "v=1&n=" + randomString(26) + "&l=" + ss.id + "/o&p=" + randomString(20) + "&r=" + randomString(3) +
"&lg=us&intl=us&np=1"
t := "z=" + randomString(24) + "&a=" + randomString(12) + "&sk=" + randomString(24) + "&d=" + randomString(30)
return y, t
}
// sendLists sends the buddy list and ignore list: in LIST, and for
// YMSG 15 and later in LIST_15 too.
func (ss *session) sendLists() {
groups, by := ss.grouped()
ign := ss.ignored()
p := &packet{service: svcList, status: stOK}
if ss.ver < 15 {
var b strings.Builder
for _, g := range groups {
b.WriteString(g + ":" + strings.Join(by[g], ",") + "\n")
}
if b.Len() > 0 {
p.add(87, b.String())
}
if len(ign) > 0 {
p.add(88, strings.Join(ign, ","))
}
}
y, t := ss.cookies()
p.add(89, ss.id).add(59, "Y\t"+y+"; expires=Thu, 15 Apr 2030 20:00:00 GMT; path=/; domain=.yahoo.com").
add(59, "T\t"+t+"; expires=Thu, 15 Apr 2030 20:00:00 GMT; path=/; domain=.yahoo.com").
add(90, "1").add(100, "0").add(101, "").add(102, "").add(93, "86400").add(3, ss.id)
ss.k.write(p)
if ss.ver < 15 {
return
}
l := &packet{service: svcList15, status: stOK}
l.add(302, "318")
for _, g := range groups {
l.add(300, "318").add(65, g).add(302, "319")
for _, id := range by[g] {
l.add(300, "319").add(7, id).add(301, "319")
}
l.add(303, "319").add(301, "318")
}
if len(ign) > 0 {
l.add(302, "320")
for _, id := range ign {
l.add(300, "320").add(7, id).add(301, "320")
}
l.add(303, "320")
}
l.add(303, "318")
ss.k.write(l)
}
// buddyState is how a buddy shows to the client: its status, custom
// message, and away flag; "" key: offline.
type buddyState struct {
status int
msg string
away bool
}
func (b buddyState) key() string {
a := "0"
if b.away {
a = "1"
}
return strconv.Itoa(b.status) + "|" + a + "|" + b.msg
}
// stateFor is what viewer sees of u (ok false: offline). A user blocking
// the viewer, or invisible, is offline to them; one on Yahoo has the
// status they set there; one on the BBS by any other route is available,
// with what they are doing as a custom message.
func (s *Server) stateFor(u, viewer *store.User) (buddyState, bool) {
if s.B.Blocks(u, viewer) {
return buddyState{}, false
}
var best *buddyState
for _, x := range s.sessionsOf(u.ID) {
x.mu.Lock()
st := buddyState{status: x.status, msg: x.msg, away: x.away}
inv, on := x.invisible, x.online
x.mu.Unlock()
if inv {
return buddyState{}, false
}
if on && (best == nil || st.status == statusAvailable) {
best = &st
}
}
if best != nil {
return *best, true
}
for _, n := range s.nodesOf(u.Name) {
if s.onNode(n.Num) == nil {
msg := ""
if n.Via != "" {
msg = "on the BBS by " + n.Via
}
return buddyState{status: statusCustom, msg: msg}, true
}
}
return buddyState{}, false
}
// buddyPairs are a buddy's entry in a status packet.
func buddyPairs(id string, b buddyState) []pair {
ps := []pair{kv(7, id), kn(10, int64(b.status))}
if b.status == statusCustom {
ps = append(ps, kv(19, b.msg))
}
away := "0"
if b.away {
away = "1"
}
return append(ps, kv(47, away), kv(11, "0"), kv(17, "0"), kv(13, "1"), kv(97, "1"))
}
// sendStatuses tells the client which of its buddies are on: LOGON (with
// itself in keys 0 and 1, which completes an older client's sign-in), and
// STATUS_15 for YMSG 15 and later.
func (ss *session) sendStatuses() {
ss.mu.Lock()
ids := make([]int64, 0, len(ss.friends))
for id := range ss.friends {
ids = append(ids, id)
}
ss.mu.Unlock()
type on struct {
id string
b buddyState
}
var ons []on
for _, fid := range ids {
u, err := ss.s.B.Store.UserByID(fid)
if err != nil {
continue
}
b, ok := ss.s.stateFor(u, ss.u)
ss.mu.Lock()
if ok {
ss.told[fid] = b.key()
} else {
ss.told[fid] = ""
}
ss.mu.Unlock()
if ok {
ons = append(ons, on{idOf(u), b})
}
}
sort.Slice(ons, func(i, j int) bool { return ons[i].id < ons[j].id })
if ss.ver >= 15 {
p := &packet{service: svcStatus15, status: stOK}
p.add(0, ss.id).add(1, ss.id)
if len(ons) > 0 {
p.add(302, "315")
for _, o := range ons {
p.add(300, "315")
p.pairs = append(p.pairs, buddyPairs(o.id, o.b)...)
p.add(301, "315")
}
p.add(303, "315")
}
ss.k.write(p)
return
}
p := &packet{service: svcLogon, status: stOK}
p.add(0, ss.id).add(1, ss.id).addInt(8, int64(len(ons)))
for _, o := range ons {
p.pairs = append(p.pairs, buddyPairs(o.id, o.b)...)
}
ss.k.write(p)
}
// buddyChanged tells the client a buddy's state, if it differs from what
// it was last told.
func (ss *session) buddyChanged(u *store.User) {
if u.ID == ss.u.ID || !ss.isOnline() {
return
}
ss.mu.Lock()
_, ok := ss.friends[u.ID]
was := ss.told[u.ID]
ss.mu.Unlock()
if !ok {
return
}
b, on := ss.s.stateFor(u, ss.u)
now := ""
if on {
now = b.key()
}
if now == was {
return
}
ss.mu.Lock()
ss.told[u.ID] = now
ss.mu.Unlock()
id := idOf(u)
switch {
case !on:
ss.k.send(svcLogoff, stOK, kv(7, id), kv(10, "0"), kv(13, "0"))
case was == "":
svc := uint16(svcLogon)
if ss.ver >= 15 {
svc = svcStatus15
}
ss.k.send(svc, stOK, buddyPairs(id, b)...)
default:
svc := uint16(svcIsAway)
switch {
case ss.ver >= 15:
svc = svcStatus15
case ss.ver >= 13:
svc = svcStatusUpdate
case b.status == statusAvailable:
svc = svcIsBack
}
ss.k.send(svc, stOK, buddyPairs(id, b)...)
}
}
// syncLists has the client's lists match the store's: friends added or
// moved elsewhere are added (ADDBUDDY), those gone removed (REMBUDDY),
// the ignore list likewise.
func (ss *session) syncLists() {
if !ss.isOnline() {
return
}
ss.mu.Lock()
oldF := ss.friends
oldB := ss.blocked
ss.mu.Unlock()
ss.loadLists()
ss.mu.Lock()
newF, newB := ss.friends, ss.blocked
ss.mu.Unlock()
for id, f := range oldF {
if g, ok := newF[id]; !ok || groupOf(g) != groupOf(f) {
ss.k.send(svcRemBuddy, stOK, kv(1, ss.id), kv(7, idOfName(f.Name)), kv(65, groupOf(f)), kv(66, "0"))
ss.mu.Lock()
delete(ss.told, id)
ss.mu.Unlock()
}
}
for id, f := range newF {
if o, ok := oldF[id]; !ok || groupOf(o) != groupOf(f) {
ss.k.send(svcAddBuddy, stOK, kv(1, ss.id), kv(7, idOfName(f.Name)), kv(65, groupOf(f)), kv(66, "0"))
if u, err := ss.s.B.Store.UserByID(id); err == nil {
ss.buddyChanged(u)
}
}
}
for id, name := range oldB {
if _, ok := newB[id]; !ok {
ss.k.send(svcIgnoreContact, stOK, kv(0, ss.id), kv(7, name), kv(13, "2"), kv(66, "0"))
}
}
for id, name := range newB {
if _, ok := oldB[id]; !ok {
ss.k.send(svcIgnoreContact, stOK, kv(0, ss.id), kv(7, name), kv(13, "1"), kv(66, "0"))
}
}
}
// addBuddy is ADDBUDDY: a friend added (or, already one, moved to the
// group).
func (ss *session) addBuddy(p *packet) {
who, group := p.get(7), strings.TrimSpace(p.get(65))
if group == "" {
group = defaultGroup
}
t := ss.s.resolve(who)
if t == nil || t.ID == ss.u.ID {
ss.k.send(svcAddBuddy, stOK, kv(1, ss.id), kv(7, who), kv(65, group), kv(66, "3"))
ss.k.send(svcRemBuddy, stOK, kv(1, ss.id), kv(7, who), kv(65, group), kv(66, "0"))
ss.system(who + " is not a user here: only the BBS's users can be on your list.")
return
}
g := group
if g == defaultGroup {
g = ""
}
ss.mu.Lock()
f := ss.friends[t.ID]
ss.mu.Unlock()
f.ID, f.Name, f.Group = t.ID, t.Name, g
if err := ss.s.B.Store.PutFriend(ss.u.ID, f); err != nil {
ss.s.B.Log.Printf("node %d: ymsg: adding a friend: %v", ss.n.Num, err)
ss.k.send(svcAddBuddy, stOK, kv(1, ss.id), kv(7, who), kv(65, group), kv(66, "1"))
return
}
ss.mu.Lock()
ss.friends[t.ID] = store.Friend{ID: t.ID, Name: t.Name, Group: g, Added: time.Now()}
delete(ss.told, t.ID)
ss.mu.Unlock()
id := idOf(t)
ss.k.send(svcAddBuddy, stOK, kv(1, ss.id), kv(7, id), kv(65, group), kv(66, "0"))
if ss.ver >= 13 {
// "may I add you": every BBS user may be, so it is granted
ss.k.send(svcAuthReq15, stOK, kv(4, id), kv(5, ss.id), kv(13, "1"))
}
ss.buddyChanged(t)
ss.s.B.FriendsChanged(ss.u.ID)
}
// remBuddy is REMBUDDY: a friend taken off.
func (ss *session) remBuddy(p *packet) {
who, group := p.get(7), p.get(65)
t := ss.s.resolve(who)
if t != nil {
if err := ss.s.B.Store.RemoveFriend(ss.u.ID, t.ID); err != nil {
ss.s.B.Log.Printf("node %d: ymsg: removing a friend: %v", ss.n.Num, err)
}
ss.mu.Lock()
delete(ss.friends, t.ID)
delete(ss.told, t.ID)
ss.mu.Unlock()
who = idOf(t)
}
ss.k.send(svcRemBuddy, stOK, kv(1, ss.id), kv(7, who), kv(65, group), kv(66, "0"))
if t != nil {
ss.s.B.FriendsChanged(ss.u.ID)
}
}
// renameGroup is GROUPRENAME: 65 the old name, 67 the new (some clients
// the other way about: the old is the one that exists).
func (ss *session) renameGroup(p *packet) {
a, b := p.get(65), p.get(67)
groups, _ := ss.grouped()
has := func(g string) bool {
for _, x := range groups {
if x == g {
return true
}
}
return false
}
from, to := a, b
if !has(a) && has(b) {
from, to = b, a
}
to = strings.TrimSpace(to)
if to == "" || !has(from) {
return
}
g := to
if g == defaultGroup {
g = ""
}
ss.mu.Lock()
var fs []store.Friend
for id, f := range ss.friends {
if groupOf(f) == from {
f.Group = g
ss.friends[id] = f
fs = append(fs, f)
}
}
ss.mu.Unlock()
for _, f := range fs {
if err := ss.s.B.Store.PutFriend(ss.u.ID, f); err != nil {
ss.s.B.Log.Printf("node %d: ymsg: renaming a group: %v", ss.n.Num, err)
}
}
ss.k.send(svcGroupRename, stOK, kv(1, ss.id), kv(65, to), kv(66, "0"), kv(67, from))
ss.s.B.FriendsChanged(ss.u.ID)
}
// changeGroup is YMSG 15's move of a buddy: 7 the buddy, 224 the old
// group, 264 the new.
func (ss *session) changeGroup(p *packet) {
t := ss.s.resolve(p.get(7))
to := strings.TrimSpace(p.get(264))
if t == nil || to == "" {
return
}
ss.mu.Lock()
f, ok := ss.friends[t.ID]
ss.mu.Unlock()
if !ok {
return
}
f.Group = to
if to == defaultGroup {
f.Group = ""
}
if err := ss.s.B.Store.PutFriend(ss.u.ID, f); err != nil {
ss.s.B.Log.Printf("node %d: ymsg: moving a friend: %v", ss.n.Num, err)
return
}
ss.mu.Lock()
ss.friends[t.ID] = f
ss.mu.Unlock()
ss.k.send(svcChangeGroup15, stOK, kv(0, ss.id), kv(302, "240"), kv(300, "240"), kv(7, idOf(t)),
kv(224, p.get(224)), kv(264, to), kv(301, "240"), kv(303, "240"))
ss.s.B.FriendsChanged(ss.u.ID)
}
// ignore is IGNORECONTACT: 13 is 1 to ignore one, 2 to stop.
func (ss *session) ignore(p *packet) {
who := p.get(7)
t := ss.s.resolve(who)
if t == nil || t.ID == ss.u.ID {
ss.k.send(svcIgnoreContact, stOK, kv(0, ss.id), kv(7, who), kv(13, p.get(13)), kv(66, "3"))
return
}
var err error
if p.get(13) == "2" {
err = ss.s.B.Store.Unblock(ss.u.ID, t.ID)
} else {
err = ss.s.B.Store.Block(ss.u.ID, t.ID)
}
if err != nil {
ss.s.B.Log.Printf("node %d: ymsg: ignore list: %v", ss.n.Num, err)
ss.k.send(svcIgnoreContact, stOK, kv(0, ss.id), kv(7, who), kv(13, p.get(13)), kv(66, "1"))
return
}
ss.mu.Lock()
if p.get(13) == "2" {
delete(ss.blocked, t.ID)
} else {
ss.blocked[t.ID] = idOf(t)
}
ss.mu.Unlock()
ss.k.send(svcIgnoreContact, stOK, kv(0, ss.id), kv(7, idOf(t)), kv(13, p.get(13)), kv(66, "0"))
ss.s.B.FriendsChanged(ss.u.ID)
ss.s.changed(ss.u)
}
+379
View File
@@ -0,0 +1,379 @@
package ymsg
import (
"regexp"
"strings"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
)
// A Yahoo chat room is a BBS chat room (an IRC channel, an AIM chat room):
// "Linux, FreeBSD, Solaris:1" is the room linux-freebsd-solar. A
// conference, Yahoo's invited group IM, is a BBS room of its own, yc- and
// the conference's name: those invited are asked to it, and anyone on the
// BBS who is told its name may join it.
var notRoom = regexp.MustCompile(`[^a-z0-9]+`)
// roomFor is the BBS room a Yahoo room name is.
func roomFor(name string) string {
name = strings.ToLower(name)
if i := strings.LastIndexByte(name, ':'); i > 0 {
name = name[:i] // "Lobby:3": the room's numbered lobbies are one room
}
r := strings.Trim(notRoom.ReplaceAllString(name, "-"), "-")
if len(r) > 20 {
r = strings.TrimRight(r[:20], "-")
}
if r == "" {
r = "lobby"
}
return r
}
// confRoom is the BBS room a conference is.
func confRoom(name string) string {
r := strings.Trim(notRoom.ReplaceAllString(strings.ToLower(name), "-"), "-")
if r == "" {
r = "conf"
}
r = "yc-" + r
if len(r) > 20 {
r = strings.TrimRight(r[:20], "-")
}
return r
}
// roomEvent gives the client a line, a coming or a going in a room it is
// in (hist: from the room's history, on coming in). False: it is in no
// such room.
func (ss *session) roomEvent(e bbs.Event, hist bool) bool {
ss.mu.Lock()
chat, isChat := ss.chats[e.Room]
conf, isConf := ss.confs[e.Room]
ss.mu.Unlock()
if !isChat && !isConf {
return false
}
mine := e.Node == ss.n.Num
from := idOfName(e.From)
if e.Node == 0 && e.Kind != bbs.Said && e.Kind != bbs.Emoted {
from = ss.s.systemID()
}
text := e.Text
switch e.Kind {
case bbs.Said, bbs.Emoted:
if mine && !hist {
return true // the client shows its own lines
}
case bbs.Topic:
from, text = ss.s.systemID(), "Topic: "+e.Text
case bbs.Notice:
from = ss.s.systemID()
case bbs.Joined, bbs.Left:
if mine || hist {
return true
}
if ss.inRoomElsewhere(e) {
return true
}
}
if isConf {
switch e.Kind {
case bbs.Joined:
ss.k.send(svcConfLogon, stOK, kv(1, ss.id), kv(53, from), kv(57, conf))
case bbs.Left:
ss.k.send(svcConfLogoff, stOK, kv(1, ss.id), kv(56, from), kv(57, conf))
default:
if e.Kind == bbs.Emoted {
text = "* " + e.From + " " + text
}
ss.k.send(svcConfMsg, stOK, kv(1, ss.id), kv(3, from), kv(57, conf), kv(14, ss.toClient(text)), kv(97, "1"))
}
return true
}
switch e.Kind {
case bbs.Joined:
ss.k.send(svcChatJoin, stServerAck, append([]pair{kv(1, ss.id), kv(104, chat)}, memberPairs(from, e.From)...)...)
case bbs.Left:
ss.k.send(svcChatExit, stServerAck, kv(1, ss.id), kv(104, chat), kv(109, from))
default:
kind := "1"
if e.Kind == bbs.Emoted {
kind = "2"
}
ss.k.send(svcComment, stServerAck, kv(1, ss.id), kv(104, chat), kv(109, from),
kv(117, ss.toClient(text)), kv(124, kind), kv(97, "1"))
}
return true
}
// inRoomElsewhere: the one coming or going is in the room by another node
// as well (so has not come or gone).
func (ss *session) inRoomElsewhere(e bbs.Event) bool {
for _, m := range ss.s.B.RoomMembers(e.Room) {
if strings.EqualFold(m.Name, e.From) && m.Node != e.Node {
return true
}
}
return false
}
// memberPairs are a chat room member's entry (CHATJOIN).
func memberPairs(id, name string) []pair {
return []pair{kv(109, id), kv(110, "0"), kv(141, name), kv(113, "0"), kv(142, "")}
}
// chatJoin is CHATJOIN (or CHATGOTO): into a chat room, told who is in it
// and its last lines.
func (ss *session) chatJoin(p *packet) {
name := strings.TrimSpace(p.get(104))
if name == "" {
return
}
room := roomFor(name)
ss.mu.Lock()
_, in := ss.chats[room]
ss.mu.Unlock()
if in {
return
}
hist, err := ss.n.JoinAlso(room)
if err != nil {
ss.k.send(svcChatJoin, stDisconnected, kv(1, ss.id), kv(104, name), kv(114, "-1"))
ss.system("You cannot go into the room " + room + ": " + err.Error())
return
}
ss.mu.Lock()
ss.chats[room] = name
ss.mu.Unlock()
topic := ""
for _, r := range ss.n.Rooms() {
if r.Name == room {
topic = r.Topic
}
}
reply := &packet{service: svcChatJoin, status: stServerAck}
reply.add(1, ss.id).add(104, name).add(105, ss.toClient(topic)).add(128, "0").add(129, "0").add(126, "328704")
seen := map[string]bool{}
var members []pair
for _, m := range ss.s.B.RoomMembers(room) {
id := idOfName(m.Name)
if seen[id] {
continue
}
seen[id] = true
members = append(members, memberPairs(id, m.Name)...)
}
if !seen[ss.id] {
members = append(members, memberPairs(ss.id, ss.u.Name)...)
seen[ss.id] = true
}
reply.addInt(108, int64(len(seen)))
reply.pairs = append(reply.pairs, members...)
reply.add(130, "1")
ss.k.write(reply)
for _, e := range hist {
ss.roomEvent(e, true)
}
}
// chatSay is COMMENT: a line in a chat room.
func (ss *session) chatSay(p *packet) {
room := roomFor(p.get(104))
ss.mu.Lock()
_, in := ss.chats[room]
ss.mu.Unlock()
if !in {
ss.k.send(svcComment, stDisconnected, kv(1, ss.id), kv(114, "-1"))
return
}
text := fromYahoo(p.get(117), p.get(97) == "1")
if err := ss.n.SayIn(room, text, p.get(124) == "2"); err != nil {
ss.system("Room " + room + ": " + err.Error())
}
}
// chatLeave is CHATLEAVE or CHATEXIT: out of a chat room.
func (ss *session) chatLeave(p *packet) {
room := roomFor(p.get(104))
ss.mu.Lock()
name, in := ss.chats[room]
delete(ss.chats, room)
ss.mu.Unlock()
if !in {
return
}
ss.n.Part(room)
ss.k.send(svcChatExit, stServerAck, kv(1, ss.id), kv(104, name), kv(109, ss.id))
}
// chatLogout is CHATLOGOUT: out of every chat room.
func (ss *session) chatLogout() {
ss.mu.Lock()
rooms := make([]string, 0, len(ss.chats))
for r := range ss.chats {
rooms = append(rooms, r)
}
ss.chats = map[string]string{}
ss.mu.Unlock()
for _, r := range rooms {
ss.n.Part(r)
}
ss.k.send(svcChatLogout, stServerAck, kv(1, ss.id))
}
// chatInvite is CHATADDINVITE: a user asked to the chat room, as a
// private message (whatever way they are on).
func (ss *session) chatInvite(p *packet) {
t := ss.s.resolve(p.get(118))
room := roomFor(p.get(104))
if t == nil {
return
}
text := ss.u.Name + " invites you to the chat room " + room
if m := fromYahoo(p.get(117), p.get(97) == "1"); strings.TrimSpace(m) != "" {
text += ": " + m
}
if _, err := ss.n.TellUser(t, text); err != nil {
ss.system("Your invitation to " + idOf(t) + " was not sent: " + err.Error())
}
}
// confInvite is CONFINVITE or CONFADDINVITE: a conference begun (or more
// asked to it). Its host goes into its room; Yahoo users invited are
// asked by their clients, the others by a private message.
func (ss *session) confInvite(p *packet) {
name := strings.TrimSpace(p.get(57))
if name == "" {
return
}
room := confRoom(name)
ss.mu.Lock()
_, in := ss.confs[room]
ss.mu.Unlock()
if !in {
if _, err := ss.n.JoinAlso(room); err != nil {
ss.system("You cannot begin a conference: " + err.Error())
return
}
ss.mu.Lock()
ss.confs[room] = name
ss.mu.Unlock()
}
invitees := p.all(52)
if p.service == svcConfAddInvite {
invitees = p.all(51)
}
msg := fromYahoo(p.get(58), p.get(97) == "1")
var asked []*store.User
for _, id := range invitees {
if t := ss.s.resolve(id); t != nil && t.ID != ss.u.ID && !ss.s.B.Blocks(t, ss.u) {
asked = append(asked, t)
}
}
for _, t := range asked {
xs := ss.s.sessionsOf(t.ID)
if len(xs) == 0 {
text := ss.u.Name + " invites you to a conference: join the chat room " + room
if strings.TrimSpace(msg) != "" {
text += " (" + msg + ")"
}
ss.n.TellUser(t, text)
continue
}
// the others it is with, as Yahoo IDs
var with []pair
for _, m := range ss.s.B.RoomMembers(room) {
if id := idOfName(m.Name); id != idOf(t) && id != ss.id {
with = append(with, kv(52, id))
}
}
for _, o := range asked {
if o.ID != t.ID {
with = append(with, kv(52, idOf(o)))
}
}
for _, x := range xs {
x.do(func() {
x.mu.Lock()
x.confs[room] = name // so its answer finds the room
x.mu.Unlock()
ps := append([]pair{kv(1, x.id), kv(50, ss.id)}, with...)
ps = append(ps, kv(57, name), kv(58, x.toClient(msg)), kv(13, "0"), kv(97, "1"))
x.k.send(svcConfInvite, stOK, ps...)
})
}
}
}
// confLogon is CONFLOGON: into a conference the client was asked to.
func (ss *session) confLogon(p *packet) {
name := strings.TrimSpace(p.get(57))
if name == "" {
return
}
room := confRoom(name)
if _, err := ss.n.JoinAlso(room); err != nil {
ss.system("You cannot join the conference: " + err.Error())
return
}
ss.mu.Lock()
ss.confs[room] = name
ss.mu.Unlock()
}
// confDecline is CONFDECLINE: those in it (key 3) are told.
func (ss *session) confDecline(p *packet) {
name := p.get(57)
room := confRoom(name)
ss.mu.Lock()
delete(ss.confs, room)
ss.mu.Unlock()
msg := fromYahoo(p.get(14), p.get(97) == "1")
for _, m := range ss.s.B.RoomMembers(room) {
x := ss.s.onNode(m.Node)
if x == nil {
continue
}
x.do(func() {
x.mu.Lock()
conf, ok := x.confs[room]
x.mu.Unlock()
if ok {
x.k.send(svcConfDecline, stOK, kv(1, x.id), kv(54, ss.id), kv(57, conf), kv(14, x.toClient(msg)))
}
})
}
}
// confLogoff is CONFLOGOFF: out of a conference.
func (ss *session) confLogoff(p *packet) {
room := confRoom(p.get(57))
ss.mu.Lock()
_, in := ss.confs[room]
delete(ss.confs, room)
ss.mu.Unlock()
if in {
ss.n.Part(room)
}
}
// confMsg is CONFMSG: a line in a conference.
func (ss *session) confMsg(p *packet) {
room := confRoom(p.get(57))
ss.mu.Lock()
_, in := ss.confs[room]
ss.mu.Unlock()
if !in || !ss.n.InRoom(room) {
return
}
text := fromYahoo(p.get(14), p.get(97) == "1")
for _, line := range splitLines(text) {
if err := ss.n.SayIn(room, line, false); err != nil {
ss.system("Conference: " + err.Error())
return
}
}
}
+281
View File
@@ -0,0 +1,281 @@
// Package ymsg is a Yahoo! Messenger server (YMSG) for the BBS's chat,
// beside its IRC, AIM and MSN servers: Yahoo! Messenger clients sign in
// with BBS names and passwords; their buddy list is the user's friends
// list and their ignore list the blocked list; an IM is a private message
// (a PRIVMSG to an IRC user, a line on a caller's terminal, an IM on AIM
// or MSN), kept for one away; a Yahoo chat room is a BBS chat room, and a
// conference a room of its own.
//
// It speaks YMSG 9 to 16. Clients before YMSG 16 (Y!M 5.x, and those
// that take the login the server offers) sign in by the challenge login
// whose digests the store keeps (auth type 0); YMSG 16 clients (Y!M 9 and
// later) send the password over HTTPS to "login.yahoo.com", which the web
// half of the server answers (http.go), and then prove the token it gave.
package ymsg
import (
"context"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"math/big"
"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
idleTimeout = 15 * time.Minute // clients PING or KEEPALIVE every minute or so
writeTimeout = 30 * time.Second
tokenLife = 5 * time.Minute // from pwtoken_get to the sign-in
queueLen = 512
)
// Settings are the [ymsg] section's.
type Settings struct {
Address string // the pager, where to listen (":5050")
// HTTPAddress and HTTPSAddress serve the web half: the capacity
// lookup, the room list and (HTTPS) the YMSG 16 login ("": none)
HTTPAddress string
HTTPSAddress string
CertFile string
KeyFile string
// Host is the address the capacity lookup gives clients for the pager
// ("": the address each one asked on)
Host string
MaxClients int
MaxPerIP int
// System is the Yahoo ID the BBS's notices come from
System string
}
// Server serves YMSG.
type Server struct {
B *bbs.BBS
S Settings
mu sync.Mutex
sessions map[*session]bool
byNode map[int]*session
tokens map[string]*token // pwtoken_get's, by token
cookies map[string]*token // pwtoken_login's, by T cookie
}
// token is a YMSG 16 login in progress: the user whose password was
// checked, and what pwtoken_login gave.
type token struct {
u *store.User
crumb string
y, t string
expires time.Time
}
// New checks the settings and makes the server.
func New(b *bbs.BBS, s Settings) (*Server, error) {
if s.Address == "" {
return nil, errors.New("ymsg: no address to listen on")
}
if s.System == "" {
s.System = "bbs"
}
if s.MaxClients == 0 {
s.MaxClients = 256
}
return &Server{B: b, S: s, sessions: map[*session]bool{}, byNode: map[int]*session{},
tokens: map[string]*token{}, cookies: map[string]*token{}}, nil
}
// Run listens until ctx is done: the pager, and the web half if set.
func (s *Server) Run(ctx context.Context) error {
ln, err := sockets.Listen("tcp", s.S.Address)
if err != nil {
return fmt.Errorf("ymsg: %w", err)
}
errs := make(chan error, 3)
if s.S.HTTPAddress != "" || s.S.HTTPSAddress != "" {
go func() { errs <- s.serveWeb(ctx) }()
}
go func() { errs <- s.Serve(ctx, ln) }()
return <-errs
}
// Serve answers the pager on ln until ctx is done.
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
s.B.Store.SetKeepYMSG(true)
stop := s.B.WatchPresence(s.presence)
defer stop()
stopFriends := s.B.WatchFriends(s.friendsChanged)
defer stopFriends()
ts := &tcpserv.Server{Name: "ymsg", 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("ymsg", 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.sessions)
}
// idOf is a user's Yahoo ID: their name in lower case, without spaces.
func idOf(u *store.User) string { return idOfName(u.Name) }
// idOfName is the Yahoo ID for a BBS name.
func idOfName(name string) string { return strings.ToLower(strings.ReplaceAll(name, " ", "")) }
// systemID is the ID the BBS's notices come from.
func (s *Server) systemID() string { return idOfName(s.S.System) }
// resolve is the account a Yahoo ID names (nil: none): a name with or
// without its spaces, in any case, without any "@yahoo.com".
func (s *Server) resolve(id string) *store.User {
id = strings.TrimSpace(id)
if i := strings.IndexByte(id, '@'); i >= 0 {
id = id[:i]
}
if id == "" {
return nil
}
u, err := s.B.Store.UserByScreenName(id)
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
}
func (s *Server) register(ss *session) {
s.mu.Lock()
s.sessions[ss] = true
s.byNode[ss.n.Num] = ss
s.mu.Unlock()
}
func (s *Server) unregister(ss *session) {
s.mu.Lock()
delete(s.sessions, ss)
if s.byNode[ss.n.Num] == ss {
delete(s.byNode, ss.n.Num)
}
s.mu.Unlock()
}
// all are the sessions signed in.
func (s *Server) all() []*session {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]*session, 0, len(s.sessions))
for ss := range s.sessions {
out = append(out, ss)
}
return out
}
// sessionsOf are a user's sessions.
func (s *Server) sessionsOf(id int64) []*session {
var out []*session
for _, ss := range s.all() {
if ss.u.ID == id {
out = append(out, ss)
}
}
return out
}
// onNode is the session on a node (nil: the node is another kind).
func (s *Server) onNode(num int) *session {
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.buddyChanged(u) })
}
}
// friendsChanged is told that a user's friends or blocked list changed:
// their own sessions sync their lists; the others 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.buddyChanged(u) })
}
}
}()
}
// randomString is n random letters and digits.
func randomString(n int) string {
const digits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
for i := range b {
x, _ := rand.Int(rand.Reader, big.NewInt(int64(len(digits))))
b[i] = digits[x.Int64()]
}
return string(b)
}
// randomSession is a session id (never 0).
func randomSession() uint32 {
var b [4]byte
for {
rand.Read(b[:])
if v := binary.BigEndian.Uint32(b[:]) & 0x7fffffff; v != 0 {
return v
}
}
}
+471
View File
@@ -0,0 +1,471 @@
package ymsg
import (
"crypto/md5"
"crypto/subtle"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
)
// login failures (AUTHRESP key 66)
const (
loginBadName = 3
loginBadPassword = 13
loginLocked = 14
)
// Yahoo statuses (key 10)
const (
statusAvailable = 0
statusBRB = 1
statusInvisible = 12
statusCustom = 99
statusIdle = 999
)
// statusNames are the statuses a client may set, as the BBS shows them.
var statusNames = map[int]string{0: "", 1: "be right back", 2: "busy", 3: "not at home", 4: "not at desk",
5: "not in office", 6: "on the phone", 7: "on vacation", 8: "out to lunch", 9: "stepped out",
12: "", 99: "", 999: "idle"}
// session is a client signed in, on a node of its own.
type session struct {
s *Server
k *conn
host string
u *store.User
n *bbs.Node
id string // its Yahoo ID, as it signed in
ver int
todo chan func()
done chan struct{}
once sync.Once
mu sync.Mutex
online bool // signed in and told its list
status int
msg string // custom status message
away bool
invisible bool
friends map[int64]store.Friend // its buddy list, as last told
blocked map[int64]string // its ignore list, as last told (by id: Yahoo ID)
told map[int64]string // what it was last told of each buddy ("": offline)
chats map[string]string // its chat rooms: BBS room -> name as the client calls it
confs map[string]string // its conferences: BBS room -> conference name
keptSent bool
}
// handle serves a pager connection: the sign-in, then its packets.
func (s *Server) handle(c net.Conn) {
host, _, _ := net.SplitHostPort(c.RemoteAddr().String())
k := newConn(c)
c.SetDeadline(time.Now().Add(loginTimeout))
ss := &session{s: s, k: k, host: host, todo: make(chan func(), queueLen), done: make(chan struct{}),
friends: map[int64]store.Friend{}, blocked: map[int64]string{}, told: map[int64]string{},
chats: map[string]string{}, confs: map[string]string{}}
initial, ok := ss.signIn()
if !ok {
return
}
u := ss.u
n, err := s.B.Enter(&bbs.Caller{Via: "ymsg", Listener: "ymsg", Remote: host, Source: "ip:" + host,
Terminal: fmt.Sprintf("YMSG%d", ss.ver)}, ss.close)
if err != nil {
k.send(svcAuthResp, stDisconnected, kv(0, ss.id), kv(1, ss.id), kn(66, loginLocked))
return
}
ss.n = n
n.SetUser(u)
n.Doing("Yahoo! Messenger")
// one session an account, as on Yahoo's servers: the older is told it
// signed in elsewhere
for _, o := range s.sessionsOf(u.ID) {
o.do(func() {
o.k.send(svcLogoff, stDisconnected)
o.close()
})
}
if initial == statusInvisible {
ss.invisible = true
}
s.register(ss)
s.B.Log.Printf("node %d: %s on Yahoo (%s, YMSG%d)", n.Num, u.Name, host, ss.ver)
defer func() {
ss.close()
s.unregister(ss)
n.Leave()
s.B.Log.Printf("node %d: gone (ymsg)", n.Num)
s.changed(u)
}()
c.SetDeadline(time.Time{})
ss.loadLists()
ss.sendLists()
ss.sendStatuses()
ss.mu.Lock()
ss.online = true
ss.mu.Unlock()
ss.drain()
ss.deliverKept()
s.changed(u)
go ss.events()
ss.serve()
}
// signIn is VERIFY, AUTH and AUTHRESP, up to a user checked (false: it
// failed; the connection is closed). The initial status is AUTHRESP's.
func (ss *session) signIn() (initial uint32, ok bool) {
s := ss.s
k := ss.k
var seed string
authType := 0
for range 8 {
p, err := k.read()
if err != nil {
return 0, false
}
k.version = p.version
ss.ver = int(p.version)
switch p.service {
case svcVerify:
k.send(svcVerify, stServerAck)
case svcAuth:
ss.id = strings.TrimSpace(p.get(1))
if ss.id == "" {
return 0, false
}
k.session = randomSession()
if ss.ver >= 16 {
authType = 2
seed = randomString(24)
} else {
seed = randomString(24)
}
k.send(svcAuth, stServerAck, kv(1, ss.id), kv(94, seed), kn(13, int64(authType)))
case svcAuthResp:
if seed == "" {
return 0, false
}
var u *store.User
var err error
if authType == 2 {
u, err = ss.tokenLogin(p, seed)
} else {
u, err = ss.challengeLogin(p, seed)
}
if err == nil {
err = s.may(u)
}
if err != nil {
code := loginBadPassword
if errors.Is(err, bbs.ErrNotAllowed) || errors.Is(err, bbs.ErrLocked) {
code = loginLocked
}
k.send(svcAuthResp, stDisconnected, kv(0, ss.id), kv(1, ss.id), kn(66, int64(code)))
return 0, false
}
ss.u = u
ss.id = idOf(u)
return p.status, true
case svcLogoff:
return 0, false
}
}
return 0, false
}
// challengeLogin checks auth type 0's answers (keys 6 and 96) against the
// account's kept digests.
func (ss *session) challengeLogin(p *packet, seed string) (*store.User, error) {
s := ss.s
user := p.get(0)
if user == "" {
user = p.get(1)
}
if user == "" {
user = ss.id
}
target := s.resolve(user)
name := user
if target != nil {
name = target.Name
}
var stale bool
u, err := s.B.AuthenticateBy("ymsg", "ip:"+ss.host, name, func() (*store.User, error) {
if target == nil {
return nil, store.ErrNotFound
}
keys, ok, err := s.B.Store.YMSGKeys(target.ID)
if err != nil {
return nil, err
}
if !ok {
stale = true
return nil, store.ErrNotFound
}
want6, want96 := challengeAnswers(keys, user, seed)
got6, got96 := p.get(6), p.get(96)
if got6 == "" || subtle.ConstantTimeCompare([]byte(want6), []byte(got6)) != 1 {
return nil, store.ErrNotFound
}
if got96 != "" && subtle.ConstantTimeCompare([]byte(want96), []byte(got96)) != 1 {
return nil, store.ErrNotFound
}
return target, nil
})
if stale && target != nil {
s.B.Log.Printf("ymsg: %s: %s has no Yahoo password digests yet: log in once by another way "+
"(telnet, IRC, AIM, the web) or set the password again", ss.host, target.Name)
}
return u, err
}
// challengeAnswers are auth type 0's two answers (keys 6 and 96) for an
// account's digests, the ID as the client typed it, and the challenge.
func challengeAnswers(k store.YMSGKeys, user, seed string) (string, string) {
for len(seed) < 16 {
seed += "0"
}
sv := int(seed[15]) % 8 % 5
var check byte
order := func(hash string) string { return "" }
switch sv {
case 0:
check = seed[int(seed[7])%16]
order = func(h string) string { return h + user + seed }
case 1:
check = seed[int(seed[9])%16]
order = func(h string) string { return user + seed + h }
case 2:
check = seed[int(seed[15])%16]
order = func(h string) string { return seed + h + user }
case 3:
check = seed[int(seed[1])%16]
order = func(h string) string { return user + h + seed }
case 4:
check = seed[int(seed[3])%16]
order = func(h string) string { return h + seed + user }
}
p := md5.Sum([]byte(string(check) + order(k.Pass)))
c := md5.Sum([]byte(string(check) + order(k.Crypt)))
return store.Y64(p[:]), store.Y64(c[:])
}
// tokenLogin checks a YMSG 16 sign-in: the T cookie pwtoken_login gave,
// and key 307, MD5(crumb + challenge) in Yahoo's base 64.
func (ss *session) tokenLogin(p *packet, seed string) (*store.User, error) {
s := ss.s
t := s.cookie(p.get(278))
name := ss.id
if t != nil {
name = t.u.Name
}
return s.B.AuthenticateBy("ymsg", "ip:"+ss.host, name, func() (*store.User, error) {
if t == nil {
return nil, store.ErrNotFound
}
if u := s.resolve(ss.id); u == nil || u.ID != t.u.ID {
return nil, store.ErrNotFound
}
h := md5.Sum([]byte(t.crumb + seed))
if subtle.ConstantTimeCompare([]byte(store.Y64(h[:])), []byte(p.get(307))) != 1 {
return nil, store.ErrNotFound
}
return t.u, nil
})
}
// closed reports that the session is over.
func (ss *session) closed() bool {
select {
case <-ss.done:
return true
default:
return false
}
}
// close ends the session.
func (ss *session) close() {
ss.once.Do(func() {
close(ss.done)
ss.k.close()
})
}
// do has the session's goroutine do f (dropped if too much waits).
func (ss *session) do(f func()) {
select {
case ss.todo <- f:
case <-ss.done:
default:
ss.s.B.Log.Printf("node %d: ymsg: too much waiting; dropped", ss.n.Num)
}
}
// isOnline: signed in and told its list.
func (ss *session) isOnline() bool {
ss.mu.Lock()
defer ss.mu.Unlock()
return ss.online
}
// events gives the client what its node is told, and does what the
// server asks of the session, until it goes.
func (ss *session) events() {
for {
select {
case <-ss.done:
return
case f := <-ss.todo:
f()
case <-ss.n.Wake():
ss.drain()
}
}
}
// drain gives the client the node's events waiting.
func (ss *session) drain() {
for _, e := range ss.n.Pending() {
ss.event(e)
}
}
// serve reads the client's packets until it goes.
func (ss *session) serve() {
for {
ss.k.c.SetReadDeadline(time.Now().Add(idleTimeout))
p, err := ss.k.read()
if err != nil {
if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && !ss.closed() {
ss.s.B.Log.Printf("node %d: ymsg: %v", ss.n.Num, err)
}
return
}
if p.service == svcLogoff {
return
}
done := make(chan struct{})
ss.do(func() {
defer close(done)
ss.packet(p)
})
select {
case <-done:
case <-ss.done:
return
}
}
}
// packet does what a packet asks (in the session's goroutine).
func (ss *session) packet(p *packet) {
switch p.service {
case svcPing, svcKeepAlive, svcChatPing, svcIdle:
// keeping the connection up
case svcList:
ss.sendLists()
case svcUserStat:
ss.sendStatuses()
case svcIsAway, svcIsBack, svcStatusUpdate:
ss.setStatus(p)
case svcVisibleToggle:
ss.mu.Lock()
ss.invisible = p.get(13) == "2"
ss.mu.Unlock()
ss.s.changed(ss.u)
case svcMessage:
ss.message(p)
case svcNotify:
ss.notify(p)
case svcAddBuddy:
ss.addBuddy(p)
case svcRemBuddy:
ss.remBuddy(p)
case svcGroupRename:
ss.renameGroup(p)
case svcChangeGroup15:
ss.changeGroup(p)
case svcIgnoreContact:
ss.ignore(p)
case svcAuthReq15, svcAuthBuddy, svcRejectContact:
// answers to "may I add you": every BBS user may be added
case svcConfInvite, svcConfAddInvite:
ss.confInvite(p)
case svcConfLogon:
ss.confLogon(p)
case svcConfDecline:
ss.confDecline(p)
case svcConfLogoff:
ss.confLogoff(p)
case svcConfMsg:
ss.confMsg(p)
case svcChatOnline:
ss.k.send(svcChatOnline, stServerAck, kv(1, ss.id), kv(109, ss.id))
case svcChatJoin, svcChatGoto:
ss.chatJoin(p)
case svcComment:
ss.chatSay(p)
case svcChatLeave, svcChatExit:
ss.chatLeave(p)
case svcChatLogout:
ss.chatLogout()
case svcChatAddInvite:
ss.chatInvite(p)
case svcFileTransfer, svcP2PFileXfer, svcFileTrans15, svcFileTransInfo15, svcFileTransAcc15, svcPeerToPeer:
if to := p.get(5); to != "" && p.service != svcPeerToPeer {
ss.system("Sending files by Yahoo! Messenger isn't available here: upload the file to " +
"the BBS's file areas instead.")
}
}
}
// setStatus is ISAWAY, ISBACK or Y6_STATUS_UPDATE: the client's status.
func (ss *session) setStatus(p *packet) {
st := statusAvailable
if v := p.get(10); v != "" {
fmt.Sscan(v, &st)
} else if p.service == svcIsAway {
st = int(p.status)
}
if _, ok := statusNames[st]; !ok {
st = statusCustom
}
msg := ""
if st == statusCustom {
msg = bbs.Clean(fromYahoo(p.get(19), p.get(97) == "1"), 255)
}
ss.mu.Lock()
ss.status = st
ss.msg = msg
ss.away = p.get(47) == "1" || (st != statusAvailable && st != statusCustom && st != statusInvisible)
switch {
case st == statusInvisible:
ss.invisible = true
case p.service != svcStatusUpdate:
ss.invisible = false // the older clients' only way back from invisible
}
ss.mu.Unlock()
doing := "Yahoo! Messenger"
if d := statusNames[st]; d != "" {
doing += " (" + d + ")"
} else if msg != "" {
doing += " (" + msg + ")"
}
ss.n.Doing(doing)
ss.s.changed(ss.u)
}
// system sends the client an IM from the BBS.
func (ss *session) system(text string) {
ss.im(ss.s.systemID(), text, time.Time{})
}
+277
View File
@@ -0,0 +1,277 @@
package ymsg
import (
"bufio"
"encoding/binary"
"errors"
"io"
"net"
"strconv"
"sync"
"time"
)
// A YMSG packet: a 20-byte header, then key/value pairs, each key (a
// decimal number) and each value ending in 0xC0 0x80. Numbers are big
// endian.
//
// 0 "YMSG"
// 4 version (2), vendor id (2)
// 8 length of what follows the header (2)
// 10 service (2)
// 12 status (4)
// 16 session id (4)
// services
const (
svcLogon = 0x01
svcLogoff = 0x02
svcIsAway = 0x03
svcIsBack = 0x04
svcIdle = 0x05
svcMessage = 0x06
svcUserStat = 0x0a
svcNewMail = 0x0b
svcChatInvite = 0x0c
svcNewContact = 0x0f
svcAddIgnore = 0x11
svcPing = 0x12
svcSysMessage = 0x14
svcConfInvite = 0x18
svcConfLogon = 0x19
svcConfDecline = 0x1a
svcConfLogoff = 0x1b
svcConfAddInvite = 0x1c
svcConfMsg = 0x1d
svcChatLogon = 0x1e
svcChatLogoff = 0x1f
svcChatMsg = 0x20
svcFileTransfer = 0x46
svcNotify = 0x4b
svcVerify = 0x4c
svcP2PFileXfer = 0x4d
svcPeerToPeer = 0x4f
svcAuthResp = 0x54
svcList = 0x55
svcAuth = 0x57
svcAuthBuddy = 0x6d
svcAddBuddy = 0x83
svcRemBuddy = 0x84
svcIgnoreContact = 0x85
svcRejectContact = 0x86
svcGroupRename = 0x89
svcKeepAlive = 0x8a
svcChatOnline = 0x96
svcChatGoto = 0x97
svcChatJoin = 0x98
svcChatLeave = 0x99
svcChatExit = 0x9b
svcChatAddInvite = 0x9d
svcChatLogout = 0xa0
svcChatPing = 0xa1
svcComment = 0xa8
svcVisibleToggle = 0xc5
svcStatusUpdate = 0xc6
svcAuthReq15 = 0xd6
svcFileTrans15 = 0xdc
svcFileTransInfo15 = 0xdd
svcFileTransAcc15 = 0xde
svcChangeGroup15 = 0xe7
svcStatus15 = 0xf0
svcList15 = 0xf1
svcMessageAck = 0xfb
)
// packet statuses
const (
stOK = 0
stServerAck = 1
stNotify = 0x16
stOffline = 0x5a55aa56
stDisconnected = 0xffffffff
)
// limits
const (
maxData = 64 << 10
)
var sep = []byte{0xc0, 0x80}
var errPacket = errors.New("ymsg: bad packet")
// pair is one key and value.
type pair struct {
k int
v string
}
// packet is one YMSG packet.
type packet struct {
version uint16
vendor uint16
service uint16
status uint32
session uint32
pairs []pair
}
// get is the first value of key ("": none).
func (p *packet) get(k int) string {
for _, x := range p.pairs {
if x.k == k {
return x.v
}
}
return ""
}
// has: the key is there.
func (p *packet) has(k int) bool {
for _, x := range p.pairs {
if x.k == k {
return true
}
}
return false
}
// all are every value of key, in order.
func (p *packet) all(k int) []string {
var out []string
for _, x := range p.pairs {
if x.k == k {
out = append(out, x.v)
}
}
return out
}
// add appends a pair.
func (p *packet) add(k int, v string) *packet {
p.pairs = append(p.pairs, pair{k, v})
return p
}
// addInt appends a pair with a number.
func (p *packet) addInt(k int, v int64) *packet { return p.add(k, strconv.FormatInt(v, 10)) }
// encode is the packet's bytes.
func (p *packet) encode() []byte {
var data []byte
for _, x := range p.pairs {
data = strconv.AppendInt(data, int64(x.k), 10)
data = append(data, sep...)
data = append(data, x.v...)
data = append(data, sep...)
}
b := make([]byte, 20, 20+len(data))
copy(b, "YMSG")
binary.BigEndian.PutUint16(b[4:], p.version)
binary.BigEndian.PutUint16(b[6:], p.vendor)
binary.BigEndian.PutUint16(b[8:], uint16(len(data)))
binary.BigEndian.PutUint16(b[10:], p.service)
binary.BigEndian.PutUint32(b[12:], p.status)
binary.BigEndian.PutUint32(b[16:], p.session)
return append(b, data...)
}
// readPacket reads one packet.
func readPacket(r io.Reader) (*packet, error) {
var h [20]byte
if _, err := io.ReadFull(r, h[:]); err != nil {
return nil, err
}
if string(h[:4]) != "YMSG" {
return nil, errPacket
}
p := &packet{version: binary.BigEndian.Uint16(h[4:]), vendor: binary.BigEndian.Uint16(h[6:]),
service: binary.BigEndian.Uint16(h[10:]), status: binary.BigEndian.Uint32(h[12:]),
session: binary.BigEndian.Uint32(h[16:])}
n := int(binary.BigEndian.Uint16(h[8:]))
data := make([]byte, n)
if _, err := io.ReadFull(r, data); err != nil {
return nil, err
}
p.pairs = decodePairs(data)
return p, nil
}
// decodePairs splits data into its pairs (a key that is not a number is
// skipped, with its value).
func decodePairs(data []byte) []pair {
var fields [][]byte
for len(data) > 0 {
i := indexSep(data)
if i < 0 {
fields = append(fields, data)
break
}
fields = append(fields, data[:i])
data = data[i+2:]
}
var out []pair
for i := 0; i+1 < len(fields); i += 2 {
k, err := strconv.Atoi(string(fields[i]))
if err != nil {
continue
}
out = append(out, pair{k, string(fields[i+1])})
}
return out
}
func indexSep(b []byte) int {
for i := 0; i+1 < len(b); i++ {
if b[i] == 0xc0 && b[i+1] == 0x80 {
return i
}
}
return -1
}
// conn is a client's connection.
type conn struct {
c net.Conn
r *bufio.Reader
mu sync.Mutex
version uint16 // the client's (packets to it go in it)
session uint32
}
func newConn(c net.Conn) *conn { return &conn{c: c, r: bufio.NewReaderSize(c, 8192)} }
// read is the client's next packet.
func (k *conn) read() (*packet, error) { return readPacket(k.r) }
// send sends a packet of a service, with a status, in the client's
// version and session.
func (k *conn) send(service uint16, status uint32, pairs ...pair) {
p := &packet{service: service, status: status, pairs: pairs}
k.write(p)
}
// write sends p, in the client's version and session.
func (k *conn) write(p *packet) {
k.mu.Lock()
defer k.mu.Unlock()
p.version, p.session = k.version, k.session
if p.version == 0 {
p.version = 16
}
b := p.encode()
if len(b) > 20+0xffff {
return
}
k.c.SetWriteDeadline(time.Now().Add(writeTimeout))
k.c.Write(b)
}
func (k *conn) close() { k.c.Close() }
// kv makes a pair.
func kv(k int, v string) pair { return pair{k, v} }
// kn makes a pair with a number.
func kn(k int, v int64) pair { return pair{k, strconv.FormatInt(v, 10)} }
+646
View File
@@ -0,0 +1,646 @@
package ymsg
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io"
"log"
"math/big"
"net"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/D-Modem/bbs/internal/bbs"
"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
st *store.Store
srv *Server
addr string // the pager's
web string // the web half's (plain HTTP, for the test)
}
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 Yahoo digests were kept) with a Yahoo server.
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.SetKeepYMSG(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, st: st, addr: freeAddr(t), web: freeAddr(t)}
srv, err := New(b, Settings{Address: e.addr, HTTPAddress: e.web, MaxPerIP: 50, Host: "127.0.0.1"})
if err != nil {
t.Fatal(err)
}
e.srv = srv
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { srv.Run(ctx); close(done) }()
t.Cleanup(func() {
cancel()
<-done
if t.Failed() {
t.Log("log:\n" + logs.String())
}
})
for _, a := range []string{e.addr, e.web} {
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 Yahoo client.
type client struct {
t *testing.T
c net.Conn
r *bufio.Reader
ver uint16
session uint32
id string
ch chan *packet
}
func dial(t *testing.T, e *env, ver uint16) *client {
t.Helper()
c, err := net.Dial("tcp", e.addr)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { c.Close() })
cl := &client{t: t, c: c, r: bufio.NewReader(c), ver: ver, ch: make(chan *packet, 256)}
go func() {
defer close(cl.ch)
for {
p, err := readPacket(cl.r)
if err != nil {
return
}
cl.ch <- p
}
}()
return cl
}
func (cl *client) send(service uint16, status uint32, ps ...pair) {
p := &packet{version: cl.ver, service: service, status: status, session: cl.session, pairs: ps}
if _, err := cl.c.Write(p.encode()); err != nil {
cl.t.Fatal(err)
}
}
// expect waits for a packet of the service that match says is the one
// (nil: any of it), passing over others.
func (cl *client) expect(service uint16, match func(*packet) bool) *packet {
cl.t.Helper()
timeout := time.After(3 * time.Second)
for {
select {
case p, ok := <-cl.ch:
if !ok {
cl.t.Fatalf("closed, waiting for service %#x", service)
}
if p.service == service && (match == nil || match(p)) {
if p.session != 0 {
cl.session = p.session
}
return p
}
case <-timeout:
cl.t.Fatalf("no service %#x", service)
}
}
}
// quiet: nothing of the service comes for a while.
func (cl *client) quiet(service uint16, match func(*packet) bool) {
cl.t.Helper()
timeout := time.After(300 * time.Millisecond)
for {
select {
case p, ok := <-cl.ch:
if !ok {
return
}
if p.service == service && (match == nil || match(p)) {
cl.t.Fatalf("unexpected %#x: %v", service, p.pairs)
}
case <-timeout:
return
}
}
}
func y64(b []byte) string { return store.Y64(b) }
// answers are what libyahoo2's pre-0x0b login sends for a password.
func answers(user, pw, seed string) (string, string) {
p := md5.Sum([]byte(pw))
c := md5.Sum([]byte(store.MD5Crypt(pw, "_2S43d5f")))
ph, ch := y64(p[:]), y64(c[:])
sv := seed[15] % 8 % 5
var hp, hc string
switch sv {
case 0:
k := seed[seed[7]%16]
hp, hc = fmt.Sprintf("%c%s%s%s", k, ph, user, seed), fmt.Sprintf("%c%s%s%s", k, ch, user, seed)
case 1:
k := seed[seed[9]%16]
hp, hc = fmt.Sprintf("%c%s%s%s", k, user, seed, ph), fmt.Sprintf("%c%s%s%s", k, user, seed, ch)
case 2:
k := seed[seed[15]%16]
hp, hc = fmt.Sprintf("%c%s%s%s", k, seed, ph, user), fmt.Sprintf("%c%s%s%s", k, seed, ch, user)
case 3:
k := seed[seed[1]%16]
hp, hc = fmt.Sprintf("%c%s%s%s", k, user, ph, seed), fmt.Sprintf("%c%s%s%s", k, user, ch, seed)
case 4:
k := seed[seed[3]%16]
hp, hc = fmt.Sprintf("%c%s%s%s", k, ph, seed, user), fmt.Sprintf("%c%s%s%s", k, ch, seed, user)
}
r6, r96 := md5.Sum([]byte(hp)), md5.Sum([]byte(hc))
return y64(r6[:]), y64(r96[:])
}
// login signs in by the challenge (YMSG 9 to 15): ok false, it was
// refused (the AUTHRESP's key 66 in code).
func (cl *client) login(user, pw string) (code string, ok bool) {
cl.t.Helper()
cl.id = user
cl.send(svcVerify, 0)
cl.expect(svcVerify, nil)
cl.send(svcAuth, 0, kv(1, user))
a := cl.expect(svcAuth, nil)
if a.get(13) != "0" || len(a.get(94)) < 16 {
cl.t.Fatalf("auth: %v", a.pairs)
}
r6, r96 := answers(user, pw, a.get(94))
cl.send(svcAuthResp, 0, kv(0, user), kv(6, r6), kv(96, r96), kv(1, user))
for {
select {
case p, ok := <-cl.ch:
if !ok {
return "closed", false
}
if p.service == svcAuthResp {
return p.get(66), false
}
if p.service == svcList {
return "", true
}
case <-time.After(3 * time.Second):
cl.t.Fatal("no answer to the login")
}
}
}
// signedIn is a client signed in.
func signedIn(t *testing.T, e *env, user string, ver uint16) *client {
t.Helper()
cl := dial(t, e, ver)
if code, ok := cl.login(user, "password1"); !ok {
t.Fatalf("%s: refused (%s)", user, code)
}
if ver >= 15 {
cl.expect(svcStatus15, nil)
} else {
cl.expect(svcLogon, func(p *packet) bool { return p.get(0) == user })
}
return cl
}
func TestChallengeLogin(t *testing.T) {
e := start(t)
cl := dial(t, e, 10)
if code, ok := cl.login("alice", "password1"); !ok {
t.Fatalf("refused: %s", code)
}
logon := cl.expect(svcLogon, nil)
if logon.get(0) != "alice" || logon.get(1) != "alice" {
t.Errorf("logon: %v", logon.pairs)
}
if cl.session == 0 {
t.Error("no session id")
}
// a name with spaces, without them; a wrong password; an account with
// no digests yet
if _, ok := dial(t, e, 10).login("carolann", "password1"); !ok {
t.Error("Carol Ann refused")
}
if code, ok := dial(t, e, 10).login("bob", "wrong"); ok || code != "13" {
t.Errorf("wrong password: %q %v", code, ok)
}
if code, ok := dial(t, e, 10).login("old", "password1"); ok || code != "13" {
t.Errorf("no digests: %q %v", code, ok)
}
if code, ok := dial(t, e, 10).login("nobody", "password1"); ok || code != "13" {
t.Errorf("no such user: %q %v", code, ok)
}
// once logged in some other way, old has digests
if _, err := e.b.Authenticate("test", "", "old", "password1"); err != nil {
t.Fatal(err)
}
if _, ok := dial(t, e, 10).login("old", "password1"); !ok {
t.Error("old refused after a password login")
}
}
// httpGet is a GET of the web half: the body's lines.
func httpGet(t *testing.T, e *env, path string) []string {
t.Helper()
r, err := http.Get("http://" + e.web + path)
if err != nil {
t.Fatal(err)
}
defer r.Body.Close()
b, _ := io.ReadAll(r.Body)
return strings.Split(strings.TrimRight(string(b), "\r\n"), "\r\n")
}
func TestTokenLogin(t *testing.T) {
e := start(t)
if l := httpGet(t, e, "/capacity"); len(l) != 2 || l[0] != "COLO_CAPACITY=1" || l[1] != "CS_IP_ADDRESS=127.0.0.1" {
t.Errorf("capacity: %q", l)
}
cl := dial(t, e, 16)
cl.send(svcAuth, 0, kv(1, "alice"))
a := cl.expect(svcAuth, nil)
if a.get(13) != "2" {
t.Fatalf("auth type: %v", a.pairs)
}
seed := a.get(94)
if l := httpGet(t, e, "/config/pwtoken_get?src=ymsgr&ts=&login=alice&passwd=wrong&chal="+url.QueryEscape(seed)); l[0] != "1212" {
t.Errorf("wrong password: %q", l)
}
l := httpGet(t, e, "/config/pwtoken_get?src=ymsgr&ts=&login=alice&passwd=password1&chal="+url.QueryEscape(seed))
if len(l) < 2 || l[0] != "0" || !strings.HasPrefix(l[1], "ymsgr=") {
t.Fatalf("token: %q", l)
}
l = httpGet(t, e, "/config/pwtoken_login?src=ymsgr&ts=&token="+url.QueryEscape(strings.TrimPrefix(l[1], "ymsgr=")))
if len(l) < 4 || l[0] != "0" || !strings.HasPrefix(l[1], "crumb=") || !strings.HasPrefix(l[3], "T=") {
t.Fatalf("crumb: %q", l)
}
crumb := strings.TrimPrefix(l[1], "crumb=")
y := strings.SplitN(strings.TrimPrefix(l[2], "Y="), ";", 2)[0]
tc := strings.SplitN(strings.TrimPrefix(l[3], "T="), ";", 2)[0]
h := md5.Sum([]byte(crumb + seed))
cl.send(svcAuthResp, 0, kv(1, "alice"), kv(0, "alice"), kv(277, y), kv(278, tc), kv(307, y64(h[:])),
kv(244, "4194239"), kv(2, "alice"), kv(2, "1"), kv(98, "us"), kv(135, "9.0.0.2162"))
cl.expect(svcList, nil)
list := cl.expect(svcList15, nil)
if list.get(303) == "" {
t.Errorf("list 15: %v", list.pairs)
}
cl.expect(svcStatus15, nil)
// the cookie is spent
c2 := dial(t, e, 16)
c2.send(svcAuth, 0, kv(1, "alice"))
a = c2.expect(svcAuth, nil)
h = md5.Sum([]byte(crumb + a.get(94)))
c2.send(svcAuthResp, 0, kv(1, "alice"), kv(0, "alice"), kv(278, tc), kv(307, y64(h[:])))
if r := c2.expect(svcAuthResp, nil); r.status != stDisconnected || r.get(66) != "13" {
t.Errorf("spent cookie: %v", r.pairs)
}
}
func TestBuddiesAndIMs(t *testing.T) {
e := start(t)
alice := signedIn(t, e, "alice", 10)
alice.send(svcAddBuddy, 0, kv(1, "alice"), kv(7, "bob"), kv(65, "Pals"), kv(14, ""))
alice.expect(svcAddBuddy, func(p *packet) bool { return p.get(7) == "bob" && p.get(66) == "0" })
alice.send(svcAddBuddy, 0, kv(1, "alice"), kv(7, "nobody"), kv(65, "Pals"))
alice.expect(svcRemBuddy, func(p *packet) bool { return p.get(7) == "nobody" })
a, _ := e.st.UserByName("alice")
bobU, _ := e.st.UserByName("bob")
fs, _ := e.st.Friends(a.ID)
if len(fs) != 1 || fs[0].Name != "bob" || fs[0].Group != "Pals" {
t.Fatalf("friends: %+v", fs)
}
// bob comes on: alice is told; IMs both ways
bob := signedIn(t, e, "bob", 12)
alice.expect(svcLogon, func(p *packet) bool { return p.get(7) == "bob" && p.get(13) == "1" })
alice.send(svcMessage, stOffline, kv(1, "alice"), kv(5, "bob"),
kv(14, "\x1b[1m<font face=\"Arial\" size=\"10\">hello bob</font>"), kv(97, "1"))
m := bob.expect(svcMessage, nil)
if m.get(4) != "alice" || m.get(14) != "hello bob" || m.get(97) != "1" {
t.Errorf("to bob: %v", m.pairs)
}
bob.send(svcMessage, stOffline, kv(1, "bob"), kv(5, "alice"), kv(14, "caf\xe9")) // Windows-1252
if m := alice.expect(svcMessage, nil); m.get(14) != "caf\xe9" {
t.Errorf("to alice (YMSG 10, Windows-1252): %q", m.get(14))
}
if cs, _ := e.st.ChatsBetween(a.ID, bobU.ID, 10); len(cs) != 2 || cs[1].Text != "café" {
t.Errorf("kept: %+v", cs)
}
// bob's status
bob.send(svcIsAway, 99, kv(10, "99"), kv(19, "out walking"), kv(47, "1"))
if p := alice.expect(svcIsAway, nil); p.get(7) != "bob" || p.get(19) != "out walking" || p.get(47) != "1" {
t.Errorf("away: %v", p.pairs)
}
bob.send(svcIsBack, 0, kv(10, "0"))
alice.expect(svcIsBack, func(p *packet) bool { return p.get(7) == "bob" && p.get(10) == "0" })
// typing
alice.send(svcNotify, stNotify, kv(4, "alice"), kv(5, "bob"), kv(14, " "), kv(13, "1"), kv(49, "TYPING"))
bob.expect(svcNotify, func(p *packet) bool { return p.get(4) == "alice" && p.get(13) == "1" })
// ignored: bob sees alice go offline, and her IMs are refused
alice.send(svcIgnoreContact, 0, kv(1, "alice"), kv(7, "bob"), kv(13, "1"))
alice.expect(svcIgnoreContact, func(p *packet) bool { return p.get(66) == "0" })
if ok, _ := e.st.IsBlocked(a.ID, bobU.ID); !ok {
t.Error("not blocked")
}
bob.send(svcMessage, stOffline, kv(1, "bob"), kv(5, "alice"), kv(14, "still there?"))
bob.expect(svcMessage, func(p *packet) bool { return p.get(4) == "bbs" && strings.Contains(p.get(14), "not sent") })
alice.quiet(svcMessage, nil)
alice.send(svcIgnoreContact, 0, kv(1, "alice"), kv(7, "bob"), kv(13, "2"))
alice.expect(svcIgnoreContact, func(p *packet) bool { return p.get(13) == "2" })
// bob goes
bob.send(svcLogoff, 0)
alice.expect(svcLogoff, func(p *packet) bool { return p.get(7) == "bob" })
}
func TestKeptAndOtherRoutes(t *testing.T) {
e := start(t)
alice := signedIn(t, e, "alice", 16-4)
alice.send(svcAddBuddy, 0, kv(1, "alice"), kv(7, "Carol Ann"), kv(65, "Friends"))
alice.expect(svcAddBuddy, func(p *packet) bool { return p.get(7) == "carolann" })
alice.send(svcMessage, stOffline, kv(1, "alice"), kv(5, "carolann"), kv(14, "call me"), kv(97, "1"))
carol, _ := e.st.UserByName("Carol Ann")
for i := 0; ; i++ {
if cs, _ := e.st.KeptChats(carol.ID); len(cs) == 1 {
break
}
if i > 100 {
t.Fatal("not kept")
}
time.Sleep(10 * time.Millisecond)
}
// Carol Ann on a terminal: alice sees her on; she has what was kept,
// then IMs alice
n, err := e.b.Enter(&bbs.Caller{Via: "telnet"}, func() {})
if err != nil {
t.Fatal(err)
}
n.SetUser(carol)
alice.expect(svcLogon, func(p *packet) bool { return p.get(7) == "carolann" && strings.Contains(p.get(19), "telnet") })
kept := n.Kept()
if len(kept) != 1 || kept[0].Text != "call me" {
t.Errorf("kept: %+v", kept)
}
a, _ := e.st.UserByName("alice")
if _, err := n.TellUser(a, "hi from the terminal"); err != nil {
t.Fatal(err)
}
if m := alice.expect(svcMessage, nil); m.get(4) != "carolann" || m.get(14) != "hi from the terminal" {
t.Errorf("from the terminal: %v", m.pairs)
}
n.Leave()
alice.expect(svcLogoff, func(p *packet) bool { return p.get(7) == "carolann" })
// bob IMs alice while she is away: she has it when she signs in
alice.send(svcLogoff, 0)
time.Sleep(50 * time.Millisecond)
bob, _ := e.st.UserByName("bob")
nb, _ := e.b.Enter(&bbs.Caller{Via: "telnet"}, func() {})
nb.SetUser(bob)
nb.TellUser(a, "are you there")
nb.Leave()
again := dial(t, e, 16-4)
if _, ok := again.login("alice", "password1"); !ok {
t.Fatal("refused")
}
if m := again.expect(svcMessage, nil); m.get(4) != "bob" || !strings.Contains(m.get(14), "while you were away) are you there") || m.get(15) == "" {
t.Errorf("kept for alice: %v", m.pairs)
}
}
func TestListFormats(t *testing.T) {
e := start(t)
a, _ := e.st.UserByName("alice")
b, _ := e.st.UserByName("bob")
c, _ := e.st.UserByName("Carol Ann")
e.st.PutFriend(a.ID, store.Friend{ID: b.ID, Group: "Pals"})
e.st.PutFriend(a.ID, store.Friend{ID: c.ID})
e.st.Block(a.ID, b.ID)
old := dial(t, e, 10)
old.login("alice", "password1")
// login returned at LIST; fetch again to read it
old.send(svcList, 0, kv(1, "alice"))
l := old.expect(svcList, func(p *packet) bool { return p.has(87) })
if l.get(87) != "Friends:carolann\nPals:bob\n" || l.get(88) != "bob" {
t.Errorf("list: %q %q", l.get(87), l.get(88))
}
nw := dial(t, e, 15)
nw.login("alice", "password1")
l15 := nw.expect(svcList15, nil)
var got []string
for _, x := range l15.pairs {
if x.k == 65 || x.k == 7 {
got = append(got, fmt.Sprintf("%d=%s", x.k, x.v))
}
}
if strings.Join(got, " ") != "65=Friends 7=carolann 65=Pals 7=bob 7=bob" || l15.all(303)[len(l15.all(303))-1] != "318" {
t.Errorf("list 15: %v", l15.pairs)
}
}
func TestChatRoom(t *testing.T) {
e := start(t)
alice := signedIn(t, e, "alice", 12)
bob, _ := e.st.UserByName("bob")
n, _ := e.b.Enter(&bbs.Caller{Via: "telnet"}, func() {})
n.SetUser(bob)
if _, err := n.JoinRoom("lobby"); err != nil {
t.Fatal(err)
}
n.Say("before alice", false)
alice.send(svcChatOnline, 0, kv(1, "alice"), kv(109, "alice"), kv(6, "abcde"))
alice.expect(svcChatOnline, nil)
alice.send(svcChatJoin, 0, kv(1, "alice"), kv(104, "Lobby:1"), kv(129, "0"), kv(62, "2"))
j := alice.expect(svcChatJoin, func(p *packet) bool { return p.get(130) == "1" })
if j.get(104) != "Lobby:1" || j.get(108) != "2" || !strings.Contains(fmt.Sprint(j.all(109)), "bob") {
t.Errorf("join: %v", j.pairs)
}
alice.expect(svcComment, func(p *packet) bool { return p.get(109) == "bob" && p.get(117) == "before alice" })
n.Say("hi alice", false)
alice.expect(svcComment, func(p *packet) bool { return p.get(109) == "bob" && p.get(117) == "hi alice" })
alice.send(svcComment, 0, kv(1, "alice"), kv(104, "Lobby:1"), kv(117, "hi bob"), kv(124, "1"))
time.Sleep(100 * time.Millisecond)
found := false
for _, ev := range n.Pending() {
if ev.Kind == bbs.Said && ev.From == "alice" && ev.Text == "hi bob" {
found = true
}
}
if !found {
t.Error("bob did not hear alice")
}
n.LeaveRoom()
alice.expect(svcChatExit, func(p *packet) bool { return p.get(109) == "bob" })
alice.send(svcChatLogout, 0, kv(1, "alice"))
alice.expect(svcChatLogout, nil)
if len(e.b.RoomMembers("lobby")) != 0 {
t.Errorf("still in: %v", e.b.RoomMembers("lobby"))
}
l := httpGet(t, e, "/ycontent/?chatcat=0")
if !strings.Contains(strings.Join(l, ""), "<category") {
t.Errorf("categories: %q", l)
}
}
func TestConference(t *testing.T) {
e := start(t)
alice := signedIn(t, e, "alice", 12)
bob := signedIn(t, e, "bob", 12)
alice.send(svcConfInvite, 0, kv(1, "alice"), kv(50, "alice"), kv(52, "bob"), kv(52, "carolann"),
kv(57, "alice-1234"), kv(58, "let's talk"), kv(13, "0"))
inv := bob.expect(svcConfInvite, nil)
if inv.get(50) != "alice" || inv.get(57) != "alice-1234" || inv.get(58) != "let's talk" {
t.Errorf("invite: %v", inv.pairs)
}
// Carol Ann, not on Yahoo, has it as a private message
carol, _ := e.st.UserByName("Carol Ann")
if cs, _ := e.st.KeptChats(carol.ID); len(cs) != 1 || !strings.Contains(cs[0].Text, "yc-alice-1234") {
t.Errorf("Carol Ann's invitation: %+v", cs)
}
bob.send(svcConfLogon, 0, kv(1, "bob"), kv(3, "alice"), kv(57, "alice-1234"))
alice.expect(svcConfLogon, func(p *packet) bool { return p.get(53) == "bob" })
alice.send(svcConfMsg, 0, kv(1, "alice"), kv(53, "bob"), kv(57, "alice-1234"), kv(14, "first"), kv(97, "1"))
bob.expect(svcConfMsg, func(p *packet) bool { return p.get(3) == "alice" && p.get(14) == "first" })
alice.quiet(svcConfMsg, nil) // her own line is not echoed
bob.send(svcConfLogoff, 0, kv(1, "bob"), kv(3, "alice"), kv(57, "alice-1234"))
alice.expect(svcConfLogoff, func(p *packet) bool { return p.get(56) == "bob" })
}
func TestText(t *testing.T) {
if got := fromYahoo("\x1b[1m\x1b[#ff0000m<font face=\"Times\">hi</font> <FADE #ff0000,#0000ff>there</FADE>", true); got != "hi there" {
t.Errorf("markup: %q", got)
}
for in, want := range map[string]string{"Lobby:1": "lobby", "Linux, FreeBSD, Solaris:2": "linux-freebsd-solari",
"!!!": "lobby", "General Chat": "general-chat"} {
if got := roomFor(in); got != want {
t.Errorf("roomFor(%q) = %q, want %q", in, got, want)
}
}
p := &packet{version: 10, service: svcMessage, status: 1, session: 99}
p.add(1, "a").add(14, "").add(97, "1")
q, err := readPacket(bytes.NewReader(p.encode()))
if err != nil || q.service != svcMessage || q.session != 99 || len(q.pairs) != 3 || q.get(1) != "a" || !q.has(14) {
t.Errorf("round trip: %+v %v", q, err)
}
}
// TestOldTLS: the HTTPS login takes Windows XP's TLS 1.0 with RSA key
// exchange and 3DES.
func TestOldTLS(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "login.yahoo.com"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), DNSNames: []string{"login.yahoo.com"}}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
cert := tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
ln, err := tls.Listen("tcp", "127.0.0.1:0", tlsConfig(cert))
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
c.(*tls.Conn).Handshake()
c.Close()
}
}()
for _, cs := range []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_RC4_128_SHA} {
c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{InsecureSkipVerify: true,
MinVersion: tls.VersionTLS10, MaxVersion: tls.VersionTLS10, CipherSuites: []uint16{cs}})
if err != nil {
t.Errorf("%s: %v", tls.CipherSuiteName(cs), err)
continue
}
c.Close()
}
}
+1
View File
@@ -53,6 +53,7 @@ nav:
- "IRC server linking": IRC-Linking.md
- "AIM and ICQ": AIM-and-ICQ.md
- "MSN Messenger": MSN-Messenger.md
- "Yahoo! Messenger": Yahoo-Messenger.md
- "MRC": MRC.md
- "Finger, gopher and Gemini": Finger-and-Gopher.md
- "Time: NTP, NTS and PTP": Time.md