A BBS for telnet, TN3270 and modem callers

One telnet port serves both kinds of terminal: a client that says it is
a 3270 (IBM-327x, IBM-DYNAMIC) is handed to go3270 and gets full 3270
screens with PF keys; any other gets a text BBS with ANSI color where
the terminal has it.  Modem callers come through the D-Modem suite:
app_dmodem's mode = tcp on a raw port, or modemmenu by rlogin, telnet,
or a unix socket whose session header (MODEM_*/DMODEM_*) gives the
call's details and, trusted, the user modemmenu logged in.

Message areas, private mail, who's online, the user list, profiles and
self-service sign-up, in SQLite.  User text is cleaned of escape
sequences and control characters before it is stored and shown;
passwords are bcrypt; logins are delayed, limited and throttled per
address or caller ID; every step has a size limit and a timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-10 16:57:31 +00:00
commit 486ea73b1c
23 files changed
+6707

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
/bbs
*.db
*.db-wal
*.db-shm
+22
View File
@@ -0,0 +1,22 @@
PREFIX ?= /usr/local
GO ?= go
all: bbs
bbs:
$(GO) build -o bbs ./cmd/bbs
test:
$(GO) vet ./...
$(GO) test -race ./...
install: bbs
install -D -m 0755 bbs $(DESTDIR)$(PREFIX)/bin/bbs
@if [ ! -e $(DESTDIR)/etc/bbs/bbs.conf ]; then \
install -D -m 0640 bbs.conf.sample $(DESTDIR)/etc/bbs/bbs.conf; \
fi
clean:
rm -f bbs
.PHONY: all bbs test install clean
+284
View File
@@ -0,0 +1,284 @@
# bbs: a bulletin board for telnet, TN3270 and modem callers
`bbs` is a bulletin board system in Go. One telnet port serves both kinds
of terminal: a TN3270 client (x3270, c3270, wc3270, Vista, PCOMM) gets
full 3270 screens with PF keys, through
[go3270](https://github.com/racingmars/go3270); any other telnet client
gets a text BBS with ANSI color where the terminal has it. Modem callers
come in through the D-Modem suite: [app_dmodem](https://github.com/Neo-Desktop/D-Modem-RE)
straight from Asterisk, or [modemmenu](https://github.com/Neo-Desktop/PBX-Modem)
after its login.
```
D-Modem BBS
Node 2, modem at 26400 bit/s
Name (or NEW): alice
Password: **********
Welcome, alice.
Main menu
[M] Message areas [E] E-mail (1 new)
[W] Who's online [U] User list
[P] Your profile [I] System info
[G] Goodbye
```
The same caller on a 3270:
```
D-Modem BBS Main menu Node 1
Welcome, alice.
1 Message areas
2 E-mail (1 new)
3 Who's online
4 User list
5 Your profile
6 System info
X Log off
Option ===>
Enter=Select PF3=Log off
```
What there is:
- message areas: read new, list, read by number, post, reply (quoting),
reply by mail; areas only the sysop posts in; authors and the sysop
delete messages
- private mail: inbox, read, reply, delete
- who's online (and how each caller came: telnet, tn3270, rlogin, modem
with its rate), the user list, system info
- your profile: where you call from, your password, ANSI and UTF-8
- new users sign themselves up (or not: `new_users = no`)
- SQLite storage, one file
## Building
Go 1.22 or later:
```
make # or: go build ./cmd/bbs
make test
make install # /usr/local/bin/bbs, and /etc/bbs/bbs.conf if there is none
```
There is no cgo: SQLite is [modernc.org/sqlite](https://modernc.org/sqlite).
## Starting
```
bbs -config /etc/bbs/bbs.conf check # the configuration, its warnings
bbs -config /etc/bbs/bbs.conf init # the database, with two areas
bbs -config /etc/bbs/bbs.conf user add sysop -sysop
bbs -config /etc/bbs/bbs.conf serve
```
[bbs.service.sample](bbs.service.sample) runs it under systemd as its own
user, with the database in `/var/lib/bbs` and sockets in `/run/bbs`.
Without `-config` it runs with the defaults: telnet and TN3270 on port
2300, modem callers raw on 127.0.0.1:2323, the database `bbs.db` here.
### Looking after it
```
bbs user list
bbs user add NAME [-sysop] # asks for the password (or reads it from a pipe)
bbs user passwd NAME
bbs user lock NAME # and unlock
bbs user sysop NAME # and unsysop
bbs user del NAME # their mail goes; their messages stay
bbs area list
bbs area add NAME "DESCRIPTION" [-sysop-only]
bbs area del NAME # and its messages
```
A sysop also adds areas from the BBS (`+` in the message areas) and
deletes any message.
## Configuration
[bbs.conf.sample](bbs.conf.sample) has every option. `[general]` is the
system (name, database, log, banner, message of the day, timeouts, limits);
each `[listen NAME]` is a port or unix socket:
| `type` | what comes in |
|---|---|
| `telnet` | a telnet client; with `tn3270 = yes` (the default) 3270s get 3270 screens |
| `raw` | bytes as they come: app_dmodem's `mode = tcp`, a modemmenu `tcp` or `unix` item |
| `rlogin` | RFC 1282, as modemmenu's `rlogin` items speak it |
`address` is `host:port`, or a path for a unix socket (`socket_mode`,
`socket_group`). Any listener may read a session header first (`header =
yes`), and with `trust_user = yes` take the caller as logged in already;
see below.
## Modem callers
### Straight from app_dmodem
app_dmodem's `[bbs]` profile hands each call to a TCP server, raw. The
`[listen modem]` of the sample is that server:
```
; dmodem.conf
[bbs]
mode = tcp
host = 127.0.0.1
port = 2323
; bbs.conf
[listen modem]
type = raw
address = 127.0.0.1:2323
```
The caller logs in to the BBS (or signs up). Over a raw line the BBS
asks the terminal for its cursor position: an ANSI terminal (SyncTERM,
Telix, Qmodem, HyperTerminal in ANSI mode) answers, and the answer gives
its size too; anything else gets plain text. Text is 7-bit ASCII unless
the caller turns UTF-8 on. An app_dmodem that sends a session header
(`header = yes`) gives the BBS the call's rate and caller ID: set `header
= yes` on the listener too.
### Behind modemmenu
modemmenu logs the caller in first and offers the BBS in its menu. Three
ways to hand the caller over, from the simplest to the closest:
**rlogin**, modemmenu's default for a BBS: it sends the caller's password
as the rlogin client user and the name as the server user (Synchronet's
convention). The BBS checks them against its own accounts; if they are
not right there (a user with no account here, or another password) the
caller is asked to log in, with the name typed in already.
```
; modemmenu.conf
[item bbs]
key = B
label = Bulletin board
mode = rlogin
host = 127.0.0.1
port = 2513
after = menu
; bbs.conf
[listen rlogin]
type = rlogin
address = 127.0.0.1:2513
```
**A unix socket with the session header**: modemmenu has checked the
caller, and the BBS believes it (`trust_user`). Callers need no account
of their own here first: `create_users = yes` makes one for each new name
(it has no password; it logs in only this way). The header's rate,
caller ID and number show in the log and who's online.
```
; modemmenu.conf
[item bbs]
key = B
label = Bulletin board
mode = unix
path = /run/bbs/menu.sock
header = yes
pass_password = no
after = menu
; bbs.conf
[listen menu]
type = raw
address = /run/bbs/menu.sock
header = yes
trust_user = yes
create_users = yes
socket_mode = 0660
socket_group = asterisk
```
`trust_user` believes whoever can connect: keep the socket to modemmenu's
user (Asterisk's group, mode 0660, or 0600 and the same user). `bbs
check` warns about a trusting socket or port that others can reach.
**telnet** works too (`mode = telnet`, `port = 2300`): modemmenu's telnet
client says it is an `ANSI` terminal, and the caller logs in again.
## TN3270
A 3270 client connects to the telnet listener like any other. The BBS
asks every client for its terminal type; one that says `IBM-3278-*`,
`IBM-3279-*`, `IBM-3277-*` or `IBM-DYNAMIC` is turned over to go3270,
which negotiates binary and end-of-record, finds the screen size (24x80
up to the model 5's 27x132, or what IBM-DYNAMIC says) and the code page,
and the caller gets the 3270 screens:
| key | |
|---|---|
| Enter | log on, select (type `S` by a line), save |
| PF3 | back, log off |
| PF5 | new user (at the logon); read new (in an area); send (in the editor) |
| PF6 | post (in an area), new mail (in the mail) |
| PF7 / PF8 | up / down a page |
| PF4 | reply; PF5 in a message: reply by mail |
| PF9 | delete |
| PF10 / PF11 | previous / next message |
```
c3270 localhost:2300
x3270 -model 3279-4 localhost:2300
```
`tn3270 = no` on a listener sends 3270s the text BBS (which they cannot
show).
## Security
- Passwords are bcrypt (cost 12); unknown users take as long to refuse as
wrong passwords; failures wait `fail_delay`; `attempts` failures hang
up; `throttle_failures` turns away an address or caller ID that keeps
failing (or signing up).
- Everything users write is cleaned before it is stored and again before
it is shown: no escape sequences, control characters, C1 controls,
bidirectional overrides or invalid UTF-8 reach another caller's
terminal. On a 3270 these would become 3270 orders once in EBCDIC; go3270
does not filter them itself.
- Limits everywhere: name, subject and line lengths, message size, telnet
subnegotiations, session headers, rlogin fields, 64 KB for a 3270
screen's answer; timeouts for every step (telnet and TN3270 negotiation,
headers, the login, idle callers, writes to callers who stopped
reading); `max_nodes` callers at once and `max_per_ip` from one address.
- The database is created 0600; unix sockets are made private and then
opened to `socket_mode`, never wider in between.
- Private mail is read only by its recipient (every query asks for the
user's own); a locked account is said to be locked only to someone who
knows its password.
- Telnet and rlogin carry passwords in the clear, as they always have:
keep rlogin to 127.0.0.1 or a socket, and put telnet behind a VPN or an
SSH tunnel where that matters. A modem line is as private as the phone
network.
- The log has logins, failures, posts and mail sent (never passwords or
message text).
## Layout
| | |
|---|---|
| `cmd/bbs` | the command: serve, check, init, user and area administration |
| `internal/server` | listeners, session headers, rlogin, telling 3270s from the rest |
| `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 |
| `internal/textui` | the text BBS: line editing, ANSI detection, paging, the menus |
| `internal/ui3270` | the 3270 BBS: screens and PF keys on go3270 |
| `internal/bbs` | the BBS itself: nodes, logins, new users, posting, cleaning text |
| `internal/store` | the SQLite database |
| `internal/config` | the configuration file |
## Tests
`make test` runs the unit tests (text cleaning, names and passwords, the
configuration, telnet negotiation and the 3270 handoff) and whole sessions
against a running server on unix sockets: a modem caller with a trusted
modemmenu header, one whose header is not trusted, a login and a post, a
new user, rlogin with a right and a wrong password and trusted, throttling
by caller ID, all lines busy, a telnet ANSI client, and a TN3270 client
taken through go3270's negotiation to the logon screen and out with PF3.
+101
View File
@@ -0,0 +1,101 @@
;
; bbs.conf - a BBS for telnet, TN3270 and modem callers
;
; bbs -config /etc/bbs/bbs.conf check checks this file
;
; Comments (; or #) go on lines of their own. Values may be "quoted" to
; keep spaces at their ends; in quoted values \r \n \t \e and \xHH are those
; bytes.
[general]
name = D-Modem BBS
sysop = Sysop
;location = Somewhere, Earth
; the database: users, messages, mail (made 0600)
database = /var/lib/bbs/bbs.db
; syslog (daemon facility), stderr, none, or a file
log = syslog
; shown before the login (text, or a file)
;banner = "Call us at 555-1000, 300 to 33600 bit/s."
;banner_file = /etc/bbs/banner.txt
; the message of the day, after the login: motd, then the file (read at
; each login)
;motd = "The line is down for maintenance on Sunday."
;motd_file = /etc/bbs/motd.txt
goodbye = Thanks for calling.
; callers may make their own accounts (NEW at the login, PF5 on a 3270)
new_users = yes
; callers at once, on all listeners together
max_nodes = 32
; logins before hanging up, seconds after a wrong one
attempts = 3
fail_delay = 3
; seconds to log in, and for a key once logged in
login_timeout = 120
idle_timeout = 600
; this many failed logins (or new accounts) from one IP address or caller
; ID within throttle_time seconds turn it away until they age out
; (0: never). Callers with neither (a modem server's, no caller ID) are
; not throttled: one would lock out all
throttle_failures = 10
throttle_time = 600
; A listener:
; type = telnet a telnet server; with tn3270 = yes (the default),
; a client that says it is a 3270 (IBM-3278-2-E,
; IBM-DYNAMIC) gets the 3270 screens
; raw the caller's bytes as they come, no protocol:
; app_dmodem's mode = tcp, modemmenu tcp/unix items
; rlogin RFC 1282, as modemmenu's rlogin items speak it
; address = host:port or a unix socket's path (/run/bbs/bbs.sock)
; via = ... how its callers came, in who's online
; (telnet, modem, rlogin by type)
; ansi = auto the terminal's ANSI color: auto asks the terminal
; (or believes its terminal type), yes, no
; utf8 = auto UTF-8 both ways: auto by the terminal type (xterm
; and friends yes; "ansi" BBS terminals no), yes, no
; max_per_ip = 4 connections at once from one address (loopback
; and unix sockets: no limit, they are modem servers)
; header = no yes: a session header comes first, NAME=value lines
; and an empty line: app_dmodem's DMODEM_* or a
; modemmenu item's MODEM_* (rate, caller ID, number)
; header_timeout = 10 seconds for the header
; trust_user = no yes: the header's MODEM_USER (an rlogin's server
; user) is logged in without a password. Only where
; nothing but trusted menus can connect
; create_users = no yes, with trust_user: a user unknown here gets an
; account (with no password of its own)
; socket_mode = 0660 a unix socket's permissions
; socket_group = ... and its group
; telnet and TN3270, for everyone (port 23 needs root or
; CAP_NET_BIND_SERVICE)
[listen telnet]
type = telnet
address = :2300
tn3270 = yes
max_per_ip = 4
; app_dmodem's [bbs] profile (mode = tcp, host = 127.0.0.1, port = 2323):
; modem callers, raw. Keep it to 127.0.0.1
[listen modem]
type = raw
address = 127.0.0.1:2323
; modemmenu's rlogin item: the caller's modemmenu login and password are
; checked here (the same accounts on both, or the caller logs in again)
[listen rlogin]
type = rlogin
address = 127.0.0.1:2513
; modemmenu's unix item with header = yes: modemmenu has logged the caller
; in, and the BBS believes it. Only modemmenu may connect: the socket's
; group is Asterisk's (which modemmenu runs as)
;[listen menu]
;type = raw
;address = /run/bbs/menu.sock
;header = yes
;trust_user = yes
;create_users = yes
;socket_mode = 0660
;socket_group = asterisk
+34
View File
@@ -0,0 +1,34 @@
[Unit]
Description=BBS for telnet, TN3270 and modem callers
After=network.target
[Service]
ExecStart=/usr/local/bin/bbs -config /etc/bbs/bbs.conf serve
User=bbs
Group=bbs
# for [listen menu]'s socket_group = asterisk
SupplementaryGroups=asterisk
RuntimeDirectory=bbs
RuntimeDirectoryMode=0750
StateDirectory=bbs
StateDirectoryMode=0700
UMask=0077
Restart=on-failure
# port 23 without root
#AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
+334
View File
@@ -0,0 +1,334 @@
// Command bbs is a bulletin board system for telnet, TN3270 and modem
// callers.
//
// bbs [-config FILE] [serve] answer callers
// bbs [-config FILE] check check the configuration
// bbs [-config FILE] init make the database, with a first area
// bbs [-config FILE] user add NAME [-sysop]
// bbs [-config FILE] user passwd|lock|unlock|sysop|unsysop|del NAME
// bbs [-config FILE] user list
// bbs [-config FILE] area add NAME [DESCRIPTION] [-sysop-only]
// bbs [-config FILE] area del NAME
// bbs [-config FILE] area list
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"log/syslog"
"os"
"os/signal"
"strings"
"syscall"
"golang.org/x/term"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/server"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
func usage() {
fmt.Fprint(os.Stderr, `usage:
bbs [-config FILE] [serve] answer callers
bbs [-config FILE] check check the configuration
bbs [-config FILE] init make the database, with a first area
bbs [-config FILE] user add NAME [-sysop]
bbs [-config FILE] user passwd|lock|unlock|sysop|unsysop|del NAME
bbs [-config FILE] user list
bbs [-config FILE] area add NAME [DESCRIPTION] [-sysop-only]
bbs [-config FILE] area del NAME
bbs [-config FILE] area list
`)
os.Exit(2)
}
func main() {
configPath := flag.String("config", "", "the configuration file (none: the defaults)")
flag.Usage = usage
flag.Parse()
args := flag.Args()
cfg, err := server.Load(*configPath)
if err != nil {
fatal(err)
}
cmd := "serve"
if len(args) > 0 {
cmd, args = args[0], args[1:]
}
switch cmd {
case "serve":
os.Exit(serve(cfg))
case "check":
for _, w := range cfg.Warnings {
fmt.Println("warning:", w)
}
for _, l := range cfg.Listeners {
extra := ""
if l.Kind == "telnet" && l.TN3270 {
extra = " + tn3270"
}
if l.Header {
extra += ", header"
}
if l.TrustUser {
extra += ", trust_user"
}
fmt.Printf("[listen %s] %s %s%s\n", l.Name, l.Kind, l.Address, extra)
}
fmt.Println("database:", cfg.Database)
fmt.Println("configuration OK")
case "init":
st := open(cfg)
defer st.Close()
if areas, _ := st.Areas(); len(areas) == 0 {
if _, err := st.CreateArea("General", "Talk about anything", false); err != nil {
fatal(err)
}
if _, err := st.CreateArea("Announcements", "News from the sysop", true); err != nil {
fatal(err)
}
}
fmt.Println("database ready:", cfg.Database)
fmt.Println("make the sysop's account with: bbs user add NAME -sysop")
case "user":
userCmd(cfg, args)
case "area":
areaCmd(cfg, args)
default:
usage()
}
}
func fatal(err error) {
fmt.Fprintln(os.Stderr, "bbs:", err)
os.Exit(1)
}
func open(cfg *server.Config) *store.Store {
st, err := store.Open(cfg.Database)
if err != nil {
fatal(err)
}
return st
}
func logger(spec string) (*log.Logger, error) {
switch spec {
case "", "stderr":
return log.New(os.Stderr, "bbs: ", log.LstdFlags), nil
case "none":
return log.New(io.Discard, "", 0), nil
case "syslog":
w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_INFO, "bbs")
if err != nil {
return nil, err
}
return log.New(w, "", 0), nil
}
f, err := os.OpenFile(spec, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
if err != nil {
return nil, err
}
return log.New(f, "bbs: ", log.LstdFlags), nil
}
func serve(cfg *server.Config) int {
lg, err := logger(cfg.Log)
if err != nil {
fmt.Fprintln(os.Stderr, "bbs: log:", err)
return 1
}
for _, w := range cfg.Warnings {
lg.Printf("warning: %s", w)
}
st := open(cfg)
defer st.Close()
b := bbs.New(cfg.Settings, st, lg)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
if err := server.New(b, cfg.Listeners).Run(ctx); err != nil {
lg.Printf("%v", err)
return 1
}
return 0
}
// readPassword reads a new password twice from the terminal, or once from
// a pipe.
func readPassword(name string) string {
fd := int(os.Stdin.Fd())
if !term.IsTerminal(fd) {
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && line == "" {
fatal(errors.New("no password on stdin"))
}
pw := strings.TrimRight(line, "\r\n")
if msg := bbs.ValidPassword(pw, name); msg != "" {
fatal(errors.New(msg))
}
return pw
}
for {
fmt.Fprint(os.Stderr, "Password for "+name+": ")
a, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
if err != nil {
fatal(err)
}
if msg := bbs.ValidPassword(string(a), name); msg != "" {
fmt.Fprintln(os.Stderr, msg)
continue
}
fmt.Fprint(os.Stderr, "Again: ")
b, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
if err != nil {
fatal(err)
}
if string(a) != string(b) {
fmt.Fprintln(os.Stderr, "They differ.")
continue
}
return string(a)
}
}
// flags split from words: -sysop and -sysop-only may come anywhere
func split(args []string) (words []string, flags map[string]bool) {
flags = map[string]bool{}
for _, a := range args {
if strings.HasPrefix(a, "-") {
flags[strings.TrimLeft(a, "-")] = true
} else {
words = append(words, a)
}
}
return words, flags
}
func userCmd(cfg *server.Config, args []string) {
words, flags := split(args)
if len(words) == 0 {
usage()
}
st := open(cfg)
defer st.Close()
if words[0] == "list" {
us, err := st.Users()
if err != nil {
fatal(err)
}
for _, u := range us {
var tags []string
if u.Sysop {
tags = append(tags, "sysop")
}
if u.Locked {
tags = append(tags, "locked")
}
if u.External {
tags = append(tags, "external")
}
fmt.Printf("%-24s %5d calls %5d posts %s\n", u.Name, u.Logins, u.Posts, strings.Join(tags, " "))
}
return
}
if len(words) != 2 {
usage()
}
name := words[1]
if words[0] == "add" {
// a sysop may take a reserved name such as "sysop"
if msg := bbs.ValidName(name); msg != "" && !(flags["sysop"] && bbs.Reserved(name)) {
fatal(errors.New(msg))
}
pw := readPassword(name)
u, err := st.CreateUser(name, pw, "", flags["sysop"])
if err != nil {
fatal(err)
}
fmt.Printf("added %s%s\n", u.Name, map[bool]string{true: " (sysop)"}[u.Sysop])
return
}
u, err := st.UserByName(name)
if err != nil {
fatal(fmt.Errorf("%s: %w", name, err))
}
switch words[0] {
case "passwd":
err = st.SetPassword(u.ID, readPassword(u.Name))
case "lock":
err = st.SetLocked(u.ID, true)
case "unlock":
err = st.SetLocked(u.ID, false)
case "sysop":
err = st.SetSysop(u.ID, true)
case "unsysop":
err = st.SetSysop(u.ID, false)
case "del":
err = st.DeleteUser(u.ID)
default:
usage()
}
if err != nil {
fatal(err)
}
fmt.Println("done")
}
func areaCmd(cfg *server.Config, args []string) {
words, flags := split(args)
if len(words) == 0 {
usage()
}
st := open(cfg)
defer st.Close()
switch words[0] {
case "list":
as, err := st.Areas()
if err != nil {
fatal(err)
}
for _, a := range as {
only := ""
if a.SysopOnly {
only = " (sysop posts only)"
}
fmt.Printf("%-20s %5d messages %s%s\n", a.Name, a.Messages, a.Description, only)
}
case "add":
if len(words) < 2 || len(words) > 3 {
usage()
}
desc := ""
if len(words) == 3 {
desc = words[2]
}
a, err := st.CreateArea(bbs.Clean(words[1], 30), bbs.Clean(desc, 60), flags["sysop-only"])
if err != nil {
fatal(err)
}
fmt.Println("added", a.Name)
case "del":
if len(words) != 2 {
usage()
}
a, err := st.AreaByName(words[1])
if err != nil {
fatal(fmt.Errorf("%s: %w", words[1], err))
}
if err := st.DeleteArea(a.ID); err != nil {
fatal(err)
}
fmt.Println("deleted", a.Name, "and its", a.Messages, "messages")
default:
usage()
}
}
+26
View File
@@ -0,0 +1,26 @@
module github.com/Neo-Desktop/bbs-sec
go 1.22
require (
github.com/racingmars/go3270 v0.9.13
golang.org/x/crypto v0.31.0
golang.org/x/term v0.27.0
modernc.org/sqlite v1.33.1
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.28.0 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect
modernc.org/strutil v1.2.0 // indirect
modernc.org/token v1.1.0 // indirect
)
+55
View File
@@ -0,0 +1,55 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/racingmars/go3270 v0.9.13 h1:qFjzx6zUMR0u1dFN3Wv17D5sXdX/PUqBTt77/4angZk=
github.com/racingmars/go3270 v0.9.13/go.mod h1:JCzKbsCGdevsd+2iLMRw3Cd+Wk7vmBeGlnfHmeJEcsU=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM=
modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
+500
View File
@@ -0,0 +1,500 @@
// Package bbs is the BBS itself, whatever the terminal: the settings, the
// nodes (callers online), logins and new users. The text and 3270 front
// ends (textui, ui3270) call into it.
package bbs
import (
"errors"
"fmt"
"log"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// Settings are the [general] options.
type Settings struct {
Name string // the system's name
Sysop string // the sysop's name, for the system info
Location string // where the system is
Banner string // shown on connect, before the login
MOTD string // shown after the login (text or file)
MOTDFile string // read at each login
Goodbye string // shown on logoff
NewUsers bool // callers may make accounts
MaxNodes int // callers at once
Attempts int // logins before hanging up
FailDelay time.Duration // after a failed login
LoginTimeout time.Duration // to log in
IdleTimeout time.Duration // for a key once logged in
ThrottleFails int // failures from one source ...
ThrottleTime time.Duration // ... within this lock it out for this
}
// Defaults are the settings without a configuration.
func Defaults() Settings {
return Settings{
Name: "Go BBS",
Sysop: "Sysop",
Banner: "",
Goodbye: "Thanks for calling.",
NewUsers: true,
MaxNodes: 32,
Attempts: 3,
FailDelay: 3 * time.Second,
LoginTimeout: 2 * time.Minute,
IdleTimeout: 10 * time.Minute,
ThrottleFails: 10,
ThrottleTime: 10 * time.Minute,
}
}
// Caller is what is known of a connection before the login: how it came,
// and from a modem, the call's details.
type Caller struct {
Via string // telnet, tn3270, rlogin, modem, socket
Listener string // the [listen NAME]
Remote string // the peer's address, or the caller ID
Source string // what throttling counts failures against
Terminal string // terminal type, if told
Rate string // modem: tx/rx bit/s
CallerID string // modem: the caller's number
Dialed string // modem: the number dialed
Channel string // modem: the Asterisk channel
// an upstream menu has logged the caller in already (a trusted
// header's MODEM_USER, a trusted rlogin's server user)
TrustedUser string
// credentials to try before asking: rlogin's server user, and its
// client user as the password (the BBS convention)
LoginUser string
LoginPassword string
}
// Baud is the connect rate towards the caller, from Rate ("tx/rx").
func (c *Caller) Baud() string {
tx, _, _ := strings.Cut(c.Rate, "/")
return strings.TrimSpace(tx)
}
// Describe is the connection in a few words, for the log and who's online.
func (c *Caller) Describe() string {
s := c.Via
if b := c.Baud(); b != "" {
s += " " + b
}
return s
}
// BBS is the running system.
type BBS struct {
Settings
Store *store.Store
Log *log.Logger
mu sync.Mutex
nodes map[int]*Node
failures map[string][]time.Time
}
// New makes the BBS of the settings and store.
func New(s Settings, st *store.Store, logger *log.Logger) *BBS {
if logger == nil {
logger = log.New(os.Stderr, "bbs: ", log.LstdFlags)
}
return &BBS{Settings: s, Store: st, Log: logger,
nodes: map[int]*Node{}, failures: map[string][]time.Time{}}
}
// Node is a caller online.
type Node struct {
Num int
Caller *Caller
Since time.Time
b *BBS
user *store.User
activity string
kick func()
}
// ErrBusy: every node is taken.
var ErrBusy = errors.New("all lines are busy")
// Enter takes a node for a caller; kick is called to throw the caller off
// (on shutdown). The node must be left with Leave.
func (b *BBS) Enter(c *Caller, kick func()) (*Node, error) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.nodes) >= b.MaxNodes {
return nil, ErrBusy
}
n := 1
for b.nodes[n] != nil {
n++
}
node := &Node{Num: n, Caller: c, Since: time.Now(), b: b,
activity: "Logging in", kick: kick}
b.nodes[n] = node
return node, nil
}
// Leave gives the node back.
func (n *Node) Leave() {
n.b.mu.Lock()
delete(n.b.nodes, n.Num)
n.b.mu.Unlock()
}
// User is the node's user, nil before the login.
func (n *Node) User() *store.User {
n.b.mu.Lock()
defer n.b.mu.Unlock()
return n.user
}
// SetUser records the login.
func (n *Node) SetUser(u *store.User) {
n.b.mu.Lock()
n.user = u
n.b.mu.Unlock()
}
// Doing sets what the caller is doing, for who's online.
func (n *Node) Doing(what string) {
n.b.mu.Lock()
n.activity = what
n.b.mu.Unlock()
}
// NodeInfo is a snapshot of a node.
type NodeInfo struct {
Num int
User string
Via string
Since time.Time
Activity string
}
// Nodes lists the callers online.
func (b *BBS) Nodes() []NodeInfo {
b.mu.Lock()
defer b.mu.Unlock()
var out []NodeInfo
for _, n := range b.nodes {
name := ""
if n.user != nil {
name = n.user.Name
}
out = append(out, NodeInfo{n.Num, name, n.Caller.Describe(), n.Since, n.activity})
}
sort.Slice(out, func(i, j int) bool { return out[i].Num < out[j].Num })
return out
}
// KickAll throws every caller off.
func (b *BBS) KickAll() {
b.mu.Lock()
var kicks []func()
for _, n := range b.nodes {
if n.kick != nil {
kicks = append(kicks, n.kick)
}
}
b.mu.Unlock()
for _, k := range kicks {
k()
}
}
// Errors of logins.
var (
ErrBadLogin = errors.New("wrong name or password")
ErrLocked = errors.New("this account is locked")
ErrThrottled = errors.New("too many failed logins; try again later")
ErrNoNew = errors.New("new accounts are not taken")
)
// throttled reports whether source has failed too often lately.
func (b *BBS) throttled(source string) bool {
if source == "" || b.ThrottleFails <= 0 {
return false
}
b.mu.Lock()
defer b.mu.Unlock()
cut := time.Now().Add(-b.ThrottleTime)
f := b.failures[source]
for len(f) > 0 && f[0].Before(cut) {
f = f[1:]
}
if len(f) == 0 {
delete(b.failures, source)
} else {
b.failures[source] = f
}
return len(f) >= b.ThrottleFails
}
func (b *BBS) failed(source string) {
if source == "" {
return
}
b.mu.Lock()
defer b.mu.Unlock()
b.failures[source] = append(b.failures[source], time.Now())
// keep the map small: forget the oldest sources
if len(b.failures) > 10000 {
for k := range b.failures {
delete(b.failures, k)
if len(b.failures) <= 5000 {
break
}
}
}
}
// Login checks a name and password for the node. A failure is delayed by
// FailDelay; a source that fails too often is turned away for a while.
func (n *Node) Login(name, pw string) (*store.User, error) {
b := n.b
c := n.Caller
if b.throttled(c.Source) {
b.Log.Printf("node %d: %s: login refused, throttled", n.Num, c.Source)
time.Sleep(b.FailDelay)
return nil, ErrThrottled
}
u, err := b.Store.CheckPassword(name, pw)
if errors.Is(err, store.ErrNotFound) {
b.failed(c.Source)
b.Log.Printf("node %d: %s: failed login as %q", n.Num, c.Source, Clean(name, MaxNameLen))
time.Sleep(b.FailDelay)
return nil, ErrBadLogin
}
if err != nil {
b.Log.Printf("node %d: login: %v", n.Num, err)
return nil, errors.New("the system is in trouble; try again later")
}
if u.Locked {
b.Log.Printf("node %d: %s: %s is locked", n.Num, c.Source, u.Name)
time.Sleep(b.FailDelay)
return nil, ErrLocked
}
return n.loggedIn(u, "password")
}
// LoginTrusted logs in a user an upstream menu vouched for (Caller's
// TrustedUser). With create, a user unknown here gets an external account.
func (n *Node) LoginTrusted(name string, create bool) (*store.User, error) {
b := n.b
u, err := b.Store.UserByName(name)
if errors.Is(err, store.ErrNotFound) && create {
if msg := ValidName(name); msg != "" {
return nil, fmt.Errorf("%s: %s", name, msg)
}
u, err = b.Store.CreateUser(name, "", "", false)
if err == nil {
b.Log.Printf("node %d: new external user %s", n.Num, u.Name)
}
}
if err != nil {
return nil, err
}
if u.Locked {
return nil, ErrLocked
}
return n.loggedIn(u, "upstream")
}
func (n *Node) loggedIn(u *store.User, how string) (*store.User, error) {
if err := n.b.Store.LoggedIn(u.ID); err != nil {
return nil, err
}
n.SetUser(u)
n.Doing("Main menu")
n.b.Log.Printf("node %d: %s logged in (%s, %s from %s)", n.Num, u.Name, how,
n.Caller.Describe(), n.Caller.Remote)
return u, nil
}
// Register makes a new account for the node's caller and logs it in.
func (n *Node) Register(name, pw, location string) (*store.User, error) {
b := n.b
if !b.NewUsers {
return nil, ErrNoNew
}
if msg := ValidName(name); msg != "" {
return nil, errors.New(msg)
}
if msg := ValidPassword(pw, name); msg != "" {
return nil, errors.New(msg)
}
if b.throttled(n.Caller.Source) {
return nil, ErrThrottled
}
u, err := b.Store.CreateUser(name, pw, Clean(location, MaxLocationLen), false)
if errors.Is(err, store.ErrExists) {
return nil, errors.New("that name is taken")
}
if err != nil {
return nil, err
}
// a new account counts against the source like a failure, so that
// one caller cannot make thousands
b.failed(n.Caller.Source)
b.Log.Printf("node %d: new user %s", n.Num, u.Name)
return n.loggedIn(u, "new user")
}
// MOTDText is the message of the day: MOTD, then MOTDFile.
func (b *BBS) MOTDText() string {
text := b.MOTD
if b.MOTDFile != "" {
if data, err := os.ReadFile(b.MOTDFile); err == nil {
if len(data) > 8192 {
data = data[:8192]
}
if text != "" {
text += "\n"
}
text += string(data)
}
}
return text
}
// CanPost reports whether u may post in area a.
func CanPost(u *store.User, a *store.Area) bool {
return !a.SysopOnly || u.Sysop
}
// Post cleans and posts a message.
func (n *Node) Post(a *store.Area, to, subject string, body []string, replyTo int64) (int64, error) {
u := n.User()
if u == nil {
return 0, errors.New("not logged in")
}
if !CanPost(u, a) {
return 0, errors.New("only the sysop posts here")
}
m := &store.Message{AreaID: a.ID, FromID: u.ID, From: u.Name,
To: Clean(to, MaxNameLen), Subject: Clean(subject, MaxSubjectLen),
Body: CleanBody(body), ReplyTo: replyTo}
if m.To == "" {
m.To = "All"
}
if m.Subject == "" {
return 0, errors.New("a message needs a subject")
}
if m.Body == "" {
return 0, errors.New("the message is empty")
}
id, err := n.b.Store.Post(m)
if err == nil {
n.b.Log.Printf("node %d: %s posted #%d in %s", n.Num, u.Name, id, a.Name)
}
return id, err
}
// SendMail cleans and sends a private message.
func (n *Node) SendMail(to, subject string, body []string, replyTo int64) error {
u := n.User()
if u == nil {
return errors.New("not logged in")
}
rcpt, err := n.b.Store.UserByName(strings.TrimSpace(to))
if errors.Is(err, store.ErrNotFound) {
return fmt.Errorf("there is no user %q", Clean(to, MaxNameLen))
}
if err != nil {
return err
}
m := &store.Message{FromID: u.ID, From: u.Name, ToID: rcpt.ID, To: rcpt.Name,
Subject: Clean(subject, MaxSubjectLen), Body: CleanBody(body), ReplyTo: replyTo}
if m.Subject == "" {
return errors.New("a message needs a subject")
}
if m.Body == "" {
return errors.New("the message is empty")
}
if _, err := n.b.Store.SendMail(m); err != nil {
return err
}
n.b.Log.Printf("node %d: %s sent mail to %s", n.Num, u.Name, rcpt.Name)
return nil
}
// ChangePassword checks the old password and sets the new.
func (n *Node) ChangePassword(old, pw string) error {
u := n.User()
if u == nil {
return errors.New("not logged in")
}
if u.External {
return errors.New("your password is kept by the system you came from")
}
if _, err := n.b.Store.CheckPassword(u.Name, old); err != nil {
time.Sleep(n.b.FailDelay)
return errors.New("that is not your password")
}
if msg := ValidPassword(pw, u.Name); msg != "" {
return errors.New(msg)
}
if err := n.b.Store.SetPassword(u.ID, pw); err != nil {
return err
}
n.b.Log.Printf("node %d: %s changed their password", n.Num, u.Name)
return nil
}
// Refresh rereads the node's user (post counts, sysop rights).
func (n *Node) Refresh() *store.User {
u := n.User()
if u == nil {
return nil
}
if fresh, err := n.b.Store.UserByID(u.ID); err == nil {
n.SetUser(fresh)
return fresh
}
return u
}
// DeleteMessage removes a message: its author's, or any for a sysop.
func (n *Node) DeleteMessage(m *store.Message) error {
u := n.User()
if u == nil || !(u.Sysop || u.ID == m.FromID) {
return errors.New("only its author or the sysop deletes a message")
}
if err := n.b.Store.DeleteMessage(m.ID); err != nil {
return err
}
n.b.Log.Printf("node %d: %s deleted message #%d", n.Num, u.Name, m.ID)
return nil
}
// AreaNew is an area with the user's count of new messages.
type AreaNew struct {
*store.Area
New int
}
// AreasFor lists the areas with u's new counts.
func (b *BBS) AreasFor(u *store.User) ([]AreaNew, error) {
areas, err := b.Store.Areas()
if err != nil {
return nil, err
}
out := make([]AreaNew, len(areas))
for i, a := range areas {
n, err := b.Store.NewCount(u.ID, a.ID)
if err != nil {
return nil, err
}
out[i] = AreaNew{a, n}
}
return out, nil
}
+221
View File
@@ -0,0 +1,221 @@
package bbs
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
// Limits on what users write.
const (
MaxNameLen = 24
MaxLocationLen = 40
MaxSubjectLen = 60
MaxLineLen = 79
MaxBodyLines = 200
MaxBodyBytes = 16 * 1024
MinPasswordLen = 8
MaxPasswordLen = 72 // bcrypt's limit
)
var namePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9 ._-]*[A-Za-z0-9]$`)
// reserved names: what the menus take as commands, and names that could
// pass for the system
var reserved = map[string]bool{
"new": true, "all": true, "sysop": true, "guest": true, "root": true,
"admin": true, "system": true, "bbs": true, "off": true, "bye": true,
}
// Reserved reports whether name is kept from callers (the sysop may take
// one).
func Reserved(name string) bool { return reserved[strings.ToLower(name)] }
// ValidName checks a new user name: letters, digits and a few separators,
// starting with a letter, 2 to MaxNameLen long, no doubled spaces.
func ValidName(name string) string {
switch {
case len(name) < 2 || len(name) > MaxNameLen:
return "A name is 2 to 24 characters long."
case !namePattern.MatchString(name) || strings.Contains(name, " "):
return "Use letters, digits, spaces, dots, dashes and underscores; start with a letter."
case reserved[strings.ToLower(name)]:
return "That name is reserved."
}
return ""
}
// ValidPassword checks a new password.
func ValidPassword(pw, name string) string {
switch {
case len(pw) < MinPasswordLen:
return "A password is at least 8 characters long."
case len(pw) > MaxPasswordLen:
return "A password is at most 72 characters long."
case strings.EqualFold(pw, name):
return "The password cannot be your name."
}
for _, r := range pw {
if r < 0x20 || r == 0x7f {
return "The password has a control character in it."
}
}
return ""
}
// Clean makes one line of user text safe to show on any terminal: no
// control characters (escape sequences, 3270 orders once in EBCDIC, bell),
// no C1 controls, no bidirectional overrides, no invalid UTF-8; tabs become
// spaces. The result is at most max runes, spaces trimmed.
func Clean(s string, max int) string {
var b strings.Builder
n := 0
for i := 0; i < len(s) && n < max; {
r, size := utf8.DecodeRuneInString(s[i:])
i += size
switch {
case r == utf8.RuneError:
// invalid UTF-8, or U+FFFD itself (go3270 stops encoding at it)
r = '?'
case r == '\t':
r = ' '
case !safeRune(r):
continue
}
b.WriteRune(r)
n++
}
return strings.TrimSpace(b.String())
}
func safeRune(r rune) bool {
switch {
case r < 0x20, r == 0x7f, r >= 0x80 && r < 0xa0:
return false
case r >= 0x202a && r <= 0x202e, r >= 0x2066 && r <= 0x2069,
r == 0x200e, r == 0x200f, r == 0x061c:
// bidirectional overrides and marks: text that reads otherwise
// than it is
return false
case r == 0xfeff, r >= 0xfff9 && r <= 0xfffb:
return false
case unicode.Is(unicode.Co, r), unicode.Is(unicode.Cs, r):
return false
}
return true
}
// CleanBody cleans a message body line by line: each line as Clean (but
// keeping leading spaces), at most MaxBodyLines lines and MaxBodyBytes,
// trailing empty lines dropped.
func CleanBody(lines []string) string {
var out []string
size := 0
for _, l := range lines {
if len(out) == MaxBodyLines {
break
}
indent := len(l) - len(strings.TrimLeft(l, " "))
c := strings.Repeat(" ", min(indent, MaxLineLen)) + Clean(l, MaxLineLen)
if size += len(c) + 1; size > MaxBodyBytes {
break
}
out = append(out, strings.TrimRight(c, " "))
}
for len(out) > 0 && out[len(out)-1] == "" {
out = out[:len(out)-1]
}
return strings.Join(out, "\n")
}
// Wrap breaks text (lines separated by \n) into lines of at most width
// runes, at spaces where it can.
func Wrap(text string, width int) []string {
if width < 10 {
width = 10
}
var out []string
for _, para := range strings.Split(text, "\n") {
r := []rune(para)
for len(r) > width {
cut := width
for i := width; i > width/2; i-- {
if r[i] == ' ' {
cut = i
break
}
}
out = append(out, strings.TrimRight(string(r[:cut]), " "))
r = r[cut:]
if len(r) > 0 && r[0] == ' ' {
r = r[1:]
}
}
out = append(out, string(r))
}
return out
}
// Fit pads or cuts s to exactly width runes.
func Fit(s string, width int) string {
r := []rune(s)
if len(r) > width {
return string(r[:width])
}
return s + strings.Repeat(" ", width-len(r))
}
// Trunc cuts s to at most width runes.
func Trunc(s string, width int) string {
r := []rune(s)
if len(r) > width {
return string(r[:width])
}
return s
}
// ReplySubject is "Re: subject", without piling up Re:s.
func ReplySubject(s string) string {
if len(s) >= 3 && strings.EqualFold(s[:3], "re:") {
return Trunc(s, MaxSubjectLen)
}
return Trunc("Re: "+s, MaxSubjectLen)
}
// Quote quotes a message for a reply: "> " lines, at most n of them. The
// lines of a paragraph are joined before they are wrapped again, so that
// lines the editor wrapped do not leave a word on a line of its own.
func Quote(from, body string, n int) []string {
var paras []string
var cur []string
flush := func() {
if len(cur) > 0 {
paras = append(paras, strings.Join(cur, " "))
cur = nil
}
}
for _, l := range strings.Split(body, "\n") {
t := strings.TrimSpace(l)
switch {
case t == "":
flush()
paras = append(paras, "")
case strings.HasPrefix(t, ">") || strings.HasPrefix(l, " "):
// quotes and indented lines keep their lines
flush()
paras = append(paras, l)
default:
cur = append(cur, t)
}
}
flush()
out := []string{from + " wrote:"}
for _, l := range Wrap(strings.Join(paras, "\n"), MaxLineLen-2) {
if len(out) > n {
break
}
out = append(out, Trunc(">"+strings.TrimRight(" "+l, " "), MaxLineLen))
}
return append(out, "")
}
+104
View File
@@ -0,0 +1,104 @@
package bbs
import (
"strings"
"testing"
)
func TestClean(t *testing.T) {
cases := []struct{ in, want string }{
{"hello", "hello"},
{" pad ", "pad"},
{"\x1b[31mred\x1b[0m", "[31mred[0m"},
{"bell\x07 and nul\x00", "bell and nul"},
{"tab\there", "tab here"},
{"c1\u009b2J", "c12J"},
{"bidi‮gnp.exe", "bidignp.exe"},
{"bad\xffutf8", "bad?utf8"},
{"fffd�x", "fffd?x"},
{"été", "été"},
}
for _, c := range cases {
if got := Clean(c.in, 100); got != c.want {
t.Errorf("Clean(%q) = %q, want %q", c.in, got, c.want)
}
}
if got := Clean(strings.Repeat("x", 50), 10); got != strings.Repeat("x", 10) {
t.Errorf("Clean did not cut: %q", got)
}
}
func TestValidName(t *testing.T) {
for _, ok := range []string{"alice", "Bob Smith", "x.y-z_1", "ab"} {
if msg := ValidName(ok); msg != "" {
t.Errorf("ValidName(%q) = %q", ok, msg)
}
}
for _, bad := range []string{"a", "1abc", "new", "SysOp", "a b", "bad\x1bname", "trailing ",
strings.Repeat("a", 25), "émile"} {
if ValidName(bad) == "" {
t.Errorf("ValidName(%q) took it", bad)
}
}
}
func TestValidPassword(t *testing.T) {
if ValidPassword("short", "x") == "" {
t.Error("took a short password")
}
if ValidPassword("alicealice", "AliceAlice") == "" {
t.Error("took the name as password")
}
if ValidPassword("good password", "alice") != "" {
t.Error("refused a good password")
}
if ValidPassword(strings.Repeat("x", 73), "alice") == "" {
t.Error("took a password bcrypt would cut")
}
}
func TestWrap(t *testing.T) {
got := Wrap("the quick brown fox jumps over the lazy dog", 15)
for _, l := range got {
if len(l) > 15 {
t.Errorf("line too long: %q", l)
}
}
if strings.Join(got, " ") != "the quick brown fox jumps over the lazy dog" {
t.Errorf("Wrap lost words: %q", got)
}
if got := Wrap(strings.Repeat("x", 25), 10); len(got) != 3 {
t.Errorf("a long word: %q", got)
}
}
func TestCleanBody(t *testing.T) {
body := CleanBody([]string{" indented", "esc\x1b[2Jape", "", "", ""})
if body != " indented\nesc[2Jape" {
t.Errorf("CleanBody = %q", body)
}
many := make([]string, MaxBodyLines+10)
for i := range many {
many[i] = "line"
}
if n := strings.Count(CleanBody(many), "\n") + 1; n != MaxBodyLines {
t.Errorf("CleanBody kept %d lines", n)
}
}
func TestReplySubject(t *testing.T) {
if ReplySubject("hello") != "Re: hello" || ReplySubject("RE: hello") != "RE: hello" {
t.Error("ReplySubject")
}
}
func TestQuote(t *testing.T) {
body := strings.Repeat("word ", 15) + "end\nnext line\n\n> old quote"
got := Quote("bob", body, 10)
want := []string{"bob wrote:",
"> " + strings.TrimSpace(strings.Repeat("word ", 15)), "> end next line",
">", "> > old quote", ""}
if strings.Join(got, "|") != strings.Join(want, "|") {
t.Errorf("Quote =\n%q\nwant\n%q", got, want)
}
}
+243
View File
@@ -0,0 +1,243 @@
// Package config reads the BBS configuration: an INI file in the style of
// modemmenu.conf.
//
// [general]
// name = D-Modem BBS
//
// [listen telnet]
// type = telnet
// address = :2300
//
// Comments (; or #) go on lines of their own. Values may be "quoted" to
// keep spaces at their ends; in quoted values \r \n \t \e \\ \" and \xHH
// are those bytes.
package config
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
)
// Section is one [section] of the file.
type Section struct {
Kind string // "general", "listen", ...
Name string // the second word of the header, if any
Line int
keys map[string]string
used map[string]bool
ord []string
}
// File is a parsed configuration file.
type File struct {
Path string
Sections []*Section
}
// Load reads and parses the file at path.
func Load(path string) (*File, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
cf, err := Parse(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
cf.Path = path
return cf, nil
}
// Parse parses a configuration from r.
func Parse(r io.Reader) (*File, error) {
cf := &File{}
var cur *Section
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 64*1024), 1024*1024)
n := 0
for sc.Scan() {
n++
line := strings.TrimSpace(sc.Text())
if line == "" || line[0] == ';' || line[0] == '#' {
continue
}
if line[0] == '[' {
if !strings.HasSuffix(line, "]") {
return nil, fmt.Errorf("line %d: bad section header", n)
}
words := strings.Fields(line[1 : len(line)-1])
if len(words) == 0 || len(words) > 2 {
return nil, fmt.Errorf("line %d: bad section header", n)
}
cur = &Section{Kind: strings.ToLower(words[0]), Line: n,
keys: map[string]string{}, used: map[string]bool{}}
if len(words) == 2 {
cur.Name = words[1]
}
cf.Sections = append(cf.Sections, cur)
continue
}
if cur == nil {
return nil, fmt.Errorf("line %d: a value outside of any section", n)
}
k, v, ok := strings.Cut(line, "=")
if !ok {
return nil, fmt.Errorf("line %d: no = in %q", n, line)
}
k = strings.ToLower(strings.TrimSpace(k))
v, err := unquote(strings.TrimSpace(v))
if err != nil {
return nil, fmt.Errorf("line %d: %v", n, err)
}
if _, dup := cur.keys[k]; dup {
return nil, fmt.Errorf("line %d: %s given twice", n, k)
}
cur.keys[k] = v
cur.ord = append(cur.ord, k)
}
if err := sc.Err(); err != nil {
return nil, err
}
return cf, nil
}
func unquote(v string) (string, error) {
if len(v) < 2 || v[0] != '"' || v[len(v)-1] != '"' {
return v, nil
}
v = v[1 : len(v)-1]
var b strings.Builder
for i := 0; i < len(v); i++ {
c := v[i]
if c != '\\' || i+1 == len(v) {
b.WriteByte(c)
continue
}
i++
switch v[i] {
case 'r':
b.WriteByte('\r')
case 'n':
b.WriteByte('\n')
case 't':
b.WriteByte('\t')
case 'e':
b.WriteByte(0x1b)
case '\\', '"':
b.WriteByte(v[i])
case 'x':
if i+2 >= len(v) {
return "", fmt.Errorf("short \\x escape")
}
x, err := strconv.ParseUint(v[i+1:i+3], 16, 8)
if err != nil {
return "", fmt.Errorf("bad \\x escape")
}
b.WriteByte(byte(x))
i += 2
default:
b.WriteByte('\\')
b.WriteByte(v[i])
}
}
return b.String(), nil
}
// Get finds the first section of kind (and name, if not empty).
func (cf *File) Get(kind, name string) *Section {
for _, s := range cf.Sections {
if s.Kind == kind && (name == "" || s.Name == name) {
return s
}
}
return nil
}
// All returns the sections of kind, in file order.
func (cf *File) All(kind string) []*Section {
var out []*Section
for _, s := range cf.Sections {
if s.Kind == kind {
out = append(out, s)
}
}
return out
}
// Unused lists the keys nothing asked for: misspelt options.
func (cf *File) Unused() []string {
var out []string
for _, s := range cf.Sections {
for _, k := range s.ord {
if !s.used[k] {
where := "[" + s.Kind
if s.Name != "" {
where += " " + s.Name
}
out = append(out, fmt.Sprintf("%s] %s (section at line %d)", where, k, s.Line))
}
}
}
return out
}
// Has reports whether key is set.
func (s *Section) Has(key string) bool {
if s == nil {
return false
}
_, ok := s.keys[key]
return ok
}
// String returns key's value, or def.
func (s *Section) String(key, def string) string {
if s == nil {
return def
}
v, ok := s.keys[key]
s.used[key] = true
if !ok {
return def
}
return v
}
// Bool returns key as yes/no, true/false, on/off or 1/0.
func (s *Section) Bool(key string, def bool) (bool, error) {
v := strings.ToLower(s.String(key, ""))
switch v {
case "":
return def, nil
case "yes", "true", "on", "1":
return true, nil
case "no", "false", "off", "0":
return false, nil
}
return false, fmt.Errorf("%s: %q is not yes or no", key, v)
}
// Int returns key as an integer in [min, max].
func (s *Section) Int(key string, def, min, max int) (int, error) {
v := s.String(key, "")
if v == "" {
return def, nil
}
n, err := strconv.ParseInt(v, 0, 64)
if err != nil || n < int64(min) || n > int64(max) {
return 0, fmt.Errorf("%s: %q is not a number from %d to %d", key, v, min, max)
}
return int(n), nil
}
// Seconds returns key, a number of seconds, as a duration.
func (s *Section) Seconds(key string, def, min, max int) (time.Duration, error) {
n, err := s.Int(key, def, min, max)
return time.Duration(n) * time.Second, err
}
+65
View File
@@ -0,0 +1,65 @@
package config
import (
"strings"
"testing"
)
func TestParse(t *testing.T) {
cf, err := Parse(strings.NewReader(`
; a comment
[general]
name = My BBS
banner = "\r\n Welcome \x41\e[0m "
max = 12
[listen telnet]
address = :23
`))
if err != nil {
t.Fatal(err)
}
g := cf.Get("general", "")
if g.String("name", "") != "My BBS" {
t.Error("name")
}
if got := g.String("banner", ""); got != "\r\n Welcome A\x1b[0m " {
t.Errorf("banner = %q", got)
}
if n, err := g.Int("max", 0, 0, 10); err == nil {
t.Errorf("max out of range taken: %d", n)
}
l := cf.Get("listen", "telnet")
if l == nil || l.String("address", "") != ":23" {
t.Error("listen telnet")
}
if u := cf.Unused(); len(u) != 0 {
t.Errorf("unused: %v", u)
}
l.String("address", "")
if cf.Get("listen", "nope") != nil {
t.Error("found a missing section")
}
}
func TestParseErrors(t *testing.T) {
for _, bad := range []string{
"key = value", // outside a section
"[general\nx = 1", // bad header
"[general]\nno equals", // no =
"[general]\na = 1\na = 2", // twice
`[general]` + "\n" + `a = "\x4"`,
} {
if _, err := Parse(strings.NewReader(bad)); err == nil {
t.Errorf("took %q", bad)
}
}
}
func TestUnused(t *testing.T) {
cf, _ := Parse(strings.NewReader("[general]\nnmae = x\n"))
cf.Get("general", "").String("name", "")
if u := cf.Unused(); len(u) != 1 || !strings.Contains(u[0], "nmae") {
t.Errorf("unused = %v", u)
}
}
+236
View File
@@ -0,0 +1,236 @@
package server
import (
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/config"
)
// Config is the whole configuration.
type Config struct {
Settings bbs.Settings
Database string
Log string // syslog, stderr, none, or a file
Listeners []*Listener
Warnings []string
}
// DefaultListeners are used when the file has no [listen] section: telnet
// (and TN3270) for everyone, and app_dmodem's [bbs] default, a raw port on
// 127.0.0.1:2323, for modem callers.
func DefaultListeners() []*Listener {
return []*Listener{
{Name: "telnet", Kind: "telnet", Address: ":2300", Via: "telnet", TN3270: true,
ANSI: "auto", UTF8: "auto", MaxPerIP: 4},
{Name: "modem", Kind: "raw", Address: "127.0.0.1:2323", Via: "modem",
ANSI: "auto", UTF8: "no", HeaderTimeout: 10 * time.Second},
}
}
// Load reads the configuration file (path "" for none: the defaults).
func Load(path string) (*Config, error) {
cf := &config.File{}
if path != "" {
var err error
if cf, err = config.Load(path); err != nil {
return nil, err
}
}
c := &Config{Settings: bbs.Defaults(), Database: "bbs.db", Log: "stderr"}
if err := c.general(cf.Get("general", "")); err != nil {
return nil, fmt.Errorf("[general] %w", err)
}
names := map[string]bool{}
for _, sec := range cf.All("listen") {
l, err := listener(sec)
if err != nil {
return nil, fmt.Errorf("[listen %s] %w", sec.Name, err)
}
if names[l.Name] {
return nil, fmt.Errorf("[listen %s] given twice", l.Name)
}
names[l.Name] = true
c.Listeners = append(c.Listeners, l)
c.warn(l)
}
if len(cf.Sections) > 0 && len(c.Listeners) == 0 {
return nil, errors.New("no [listen ...] section: nothing to answer")
}
if len(c.Listeners) == 0 {
c.Listeners = DefaultListeners()
}
for _, s := range cf.Sections {
if s.Kind != "general" && s.Kind != "listen" {
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
}
}
for _, u := range cf.Unused() {
c.Warnings = append(c.Warnings, "unknown option "+u)
}
return c, nil
}
func (c *Config) general(g *config.Section) error {
s := &c.Settings
var err error
c.Database = g.String("database", c.Database)
c.Log = g.String("log", c.Log)
s.Name = g.String("name", s.Name)
s.Sysop = g.String("sysop", s.Sysop)
s.Location = g.String("location", s.Location)
s.Banner = g.String("banner", s.Banner)
if f := g.String("banner_file", ""); f != "" {
data, err := os.ReadFile(f)
if err != nil {
return err
}
s.Banner = strings.TrimRight(string(data), "\n")
}
s.MOTD = g.String("motd", s.MOTD)
s.MOTDFile = g.String("motd_file", s.MOTDFile)
s.Goodbye = g.String("goodbye", s.Goodbye)
if s.NewUsers, err = g.Bool("new_users", s.NewUsers); err != nil {
return err
}
ints := []struct {
key string
p *int
min, max int
}{
{"max_nodes", &s.MaxNodes, 1, 1000},
{"attempts", &s.Attempts, 1, 10},
{"throttle_failures", &s.ThrottleFails, 0, 1000},
}
for _, i := range ints {
if *i.p, err = g.Int(i.key, *i.p, i.min, i.max); err != nil {
return err
}
}
durs := []struct {
key string
p *time.Duration
min, max int
}{
{"fail_delay", &s.FailDelay, 0, 60},
{"login_timeout", &s.LoginTimeout, 10, 3600},
{"idle_timeout", &s.IdleTimeout, 30, 86400},
{"throttle_time", &s.ThrottleTime, 1, 86400},
}
for _, d := range durs {
if *d.p, err = g.Seconds(d.key, int(*d.p/time.Second), d.min, d.max); err != nil {
return err
}
}
return nil
}
func listener(sec *config.Section) (*Listener, error) {
if sec.Name == "" {
return nil, errors.New("a listener needs a name: [listen NAME]")
}
l := &Listener{Name: sec.Name, Kind: strings.ToLower(sec.String("type", "telnet"))}
switch l.Kind {
case "telnet", "raw", "rlogin":
default:
return nil, fmt.Errorf("type: %q is not telnet, raw or rlogin", l.Kind)
}
l.Address = sec.String("address", "")
if l.Address == "" {
return nil, errors.New("address: none given")
}
if !l.Unix() {
if _, _, err := net.SplitHostPort(l.Address); err != nil {
return nil, fmt.Errorf("address: %v", err)
}
}
via := map[string]string{"telnet": "telnet", "raw": "modem", "rlogin": "rlogin"}[l.Kind]
l.Via = sec.String("via", via)
var err error
if l.TN3270, err = sec.Bool("tn3270", true); err != nil {
return nil, err
}
if sec.Has("tn3270") && l.Kind != "telnet" {
return nil, errors.New("tn3270: only for type = telnet")
}
for _, o := range []struct {
key string
p *string
def string
}{{"ansi", &l.ANSI, "auto"}, {"utf8", &l.UTF8, map[bool]string{true: "auto", false: "no"}[l.Kind == "telnet"]}} {
*o.p = strings.ToLower(sec.String(o.key, o.def))
switch *o.p {
case "auto", "yes", "no":
default:
return nil, fmt.Errorf("%s: %q is not auto, yes or no", o.key, *o.p)
}
}
if l.Header, err = sec.Bool("header", false); err != nil {
return nil, err
}
if l.HeaderTimeout, err = sec.Seconds("header_timeout", 10, 1, 300); err != nil {
return nil, err
}
if l.TrustUser, err = sec.Bool("trust_user", false); err != nil {
return nil, err
}
if l.TrustUser && !l.Header && l.Kind != "rlogin" {
return nil, errors.New("trust_user: needs header = yes (or type = rlogin)")
}
if l.CreateUsers, err = sec.Bool("create_users", false); err != nil {
return nil, err
}
if l.CreateUsers && !l.TrustUser {
return nil, errors.New("create_users: only with trust_user = yes")
}
if l.MaxPerIP, err = sec.Int("max_per_ip", 4, 0, 1000); err != nil {
return nil, err
}
mode := sec.String("socket_mode", "0660")
m, err := strconv.ParseUint(mode, 8, 32)
if err != nil || m > 0777 {
return nil, fmt.Errorf("socket_mode: %q is not an octal mode", mode)
}
l.SocketMode = os.FileMode(m)
l.SocketGroup = sec.String("socket_group", "")
if (sec.Has("socket_mode") || l.SocketGroup != "") && !l.Unix() {
return nil, errors.New("socket_mode, socket_group: only for a unix socket")
}
return l, nil
}
// warn notes what is dangerous in a listener.
func (c *Config) warn(l *Listener) {
w := func(s string) { c.Warnings = append(c.Warnings, fmt.Sprintf("[listen %s] %s", l.Name, s)) }
if l.TrustUser {
switch {
case l.Unix() && l.SocketMode&0007 != 0:
w("trust_user with a socket anyone can connect to: anyone logs in as anyone")
case !l.Unix() && !loopback(l.Address):
w("trust_user on a port others can reach: anyone logs in as anyone; keep it to 127.0.0.1 or a unix socket")
case !l.Unix():
w("trust_user on a TCP port: every local user can log in as anyone; a unix socket's permissions are safer")
}
}
if l.Kind == "rlogin" && !l.TrustUser && !l.Unix() && !loopback(l.Address) {
w("rlogin sends the password in the clear")
}
}
func loopback(addr string) bool {
h, _, err := net.SplitHostPort(addr)
if err != nil {
return false
}
if h == "localhost" {
return true
}
ip := net.ParseIP(h)
return ip != nil && ip.IsLoopback()
}
+82
View File
@@ -0,0 +1,82 @@
package server
import (
"errors"
"fmt"
"net"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
)
// The session header, as modemmenu (server.go) and app_dmodem write it:
// KEY=value lines, then an empty line, then the caller's bytes.
const (
headerMaxLines = 64
headerMaxBytes = 8192
)
// ReadHeader reads a session header from c, a byte at a time so that
// nothing of the caller's is read with it.
func ReadHeader(c net.Conn, timeout time.Duration) (map[string]string, error) {
c.SetReadDeadline(time.Now().Add(timeout))
defer c.SetReadDeadline(time.Time{})
h := map[string]string{}
var line []byte
b := make([]byte, 1)
for total := 0; ; total++ {
if total >= headerMaxBytes {
return nil, errors.New("header: too long")
}
if _, err := c.Read(b); err != nil {
return nil, fmt.Errorf("header: %w", err)
}
if b[0] != '\n' {
line = append(line, b[0])
continue
}
s := strings.TrimSuffix(string(line), "\r")
line = line[:0]
if s == "" {
return h, nil
}
if len(h) >= headerMaxLines {
return nil, errors.New("header: too many lines")
}
k, v, ok := strings.Cut(s, "=")
if !ok {
return nil, fmt.Errorf("header: no = in %q", bbs.Clean(s, 40))
}
h[strings.ToUpper(strings.TrimSpace(k))] = v
}
}
// pick is the first of the keys the header has.
func pick(h map[string]string, keys ...string) string {
for _, k := range keys {
if v, ok := h[k]; ok {
return bbs.Clean(v, 64)
}
}
return ""
}
// applyHeader puts what a header says of the call into c; with trust its
// MODEM_USER is the caller, logged in already.
func applyHeader(c *bbs.Caller, h map[string]string, trust bool) {
c.Rate = pick(h, "DMODEM_RATE", "MODEM_RATE")
c.CallerID = pick(h, "DMODEM_CALLERID", "MODEM_CALLERID")
c.Dialed = pick(h, "DMODEM_DIALED", "MODEM_DIALED")
c.Channel = pick(h, "DMODEM_CHANNEL", "MODEM_CHANNEL")
if c.Rate != "" || c.Channel != "" {
c.Via = "modem"
}
if c.CallerID != "" {
c.Remote = c.CallerID
}
if trust {
c.TrustedUser = strings.TrimSpace(pick(h, "MODEM_USER"))
}
}
+475
View File
@@ -0,0 +1,475 @@
// Package server takes the BBS's callers: it listens, works out what kind
// of terminal each one has and hands it to the text or 3270 front end.
//
// A listener is one of:
//
// - telnet: a telnet server. A client that says it is a 3270
// (IBM-3278-2-E, IBM-DYNAMIC, ...) is negotiated into TN3270 by go3270
// and gets the 3270 screens; any other gets the text BBS.
// - raw: no protocol, the caller's bytes as they come: app_dmodem's
// mode = tcp, a modemmenu tcp or unix item, a terminal on a serial line
// server.
// - rlogin: RFC 1282, as modemmenu's rlogin items speak it: the server
// user is the name, the client user the password (Synchronet's
// convention), or with trust_user the name alone logs in.
//
// Any of them may read a session header first: NAME=value lines and an
// empty line, the DMODEM_* of app_dmodem's header = yes or the MODEM_* of
// a modemmenu item's header = yes, with the call's rate, caller ID and
// number dialed, and with trust_user the user modemmenu logged in.
package server
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"os/user"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/racingmars/go3270"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/telnet"
"github.com/Neo-Desktop/bbs-sec/internal/textui"
"github.com/Neo-Desktop/bbs-sec/internal/ui3270"
)
// Listener is a [listen NAME] section.
type Listener struct {
Name string
Kind string // telnet, raw, rlogin
Address string // host:port, or a unix socket's path
Via string // how its callers came, for who's online
TN3270 bool // telnet: take 3270 clients
ANSI string // auto, yes, no: the terminal's ANSI, if not told
UTF8 string // auto, yes, no
Header bool // read a session header first
HeaderTimeout time.Duration
TrustUser bool // the header's MODEM_USER (rlogin's server user) is logged in
CreateUsers bool // and gets an account if it has none
MaxPerIP int // connections at once from one address (not loopback)
SocketMode os.FileMode
SocketGroup string
}
// Unix reports whether the listener is on a unix socket.
func (l *Listener) Unix() bool {
return strings.HasPrefix(l.Address, "/") || strings.HasPrefix(l.Address, "unix:")
}
func (l *Listener) path() string { return strings.TrimPrefix(l.Address, "unix:") }
// Server runs the listeners.
type Server struct {
B *bbs.BBS
Listeners []*Listener
mu sync.Mutex
perIP map[string]int
conns map[net.Conn]bool
wg sync.WaitGroup
}
// New makes a server.
func New(b *bbs.BBS, ls []*Listener) *Server {
return &Server{B: b, Listeners: ls, perIP: map[string]int{}, conns: map[net.Conn]bool{}}
}
// Run listens until ctx is done, then hangs up every caller.
func (s *Server) Run(ctx context.Context) error {
var lns []net.Listener
closeAll := func() {
for _, ln := range lns {
ln.Close()
}
}
for _, l := range s.Listeners {
ln, err := s.listen(l)
if err != nil {
closeAll()
return fmt.Errorf("[listen %s] %s: %w", l.Name, l.Address, err)
}
lns = append(lns, ln)
s.B.Log.Printf("listening on %s (%s)", l.Address, l.Kind)
}
for i, l := range s.Listeners {
go s.accept(lns[i], l)
}
<-ctx.Done()
s.B.Log.Printf("stopping")
closeAll()
for _, l := range s.Listeners {
if l.Unix() {
os.Remove(l.path())
}
}
s.B.KickAll()
s.mu.Lock()
for c := range s.conns {
c.Close()
}
s.mu.Unlock()
done := make(chan struct{})
go func() { s.wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
}
return nil
}
func (s *Server) listen(l *Listener) (net.Listener, error) {
if !l.Unix() {
return net.Listen("tcp", l.Address)
}
path := l.path()
if _, err := os.Lstat(path); err == nil {
// a live server keeps its socket; a dead one's is replaced
if c, err := net.DialTimeout("unix", path, time.Second); err == nil {
c.Close()
return nil, errors.New("another server is listening there")
}
if err := os.Remove(path); err != nil {
return nil, err
}
}
// made private, then opened up to socket_mode: no moment in between
// when others could connect
old := syscall.Umask(0177)
ln, err := net.Listen("unix", path)
syscall.Umask(old)
if err != nil {
return nil, err
}
if err := os.Chmod(path, l.SocketMode); err != nil {
ln.Close()
return nil, err
}
if l.SocketGroup != "" {
g, err := user.LookupGroup(l.SocketGroup)
if err == nil {
gid, _ := strconv.Atoi(g.Gid)
err = os.Chown(path, -1, gid)
}
if err != nil {
ln.Close()
return nil, fmt.Errorf("socket_group %s: %w", l.SocketGroup, err)
}
}
return ln, nil
}
func (s *Server) accept(ln net.Listener, l *Listener) {
for {
c, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
s.B.Log.Printf("[listen %s] accept: %v", l.Name, err)
time.Sleep(100 * time.Millisecond)
continue
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.handle(c, l)
}()
}
}
// host is a TCP peer's address without the port, "" for loopback and unix
// peers (which are modem servers and menus: every call comes from them).
func host(c net.Conn) string {
a, ok := c.RemoteAddr().(*net.TCPAddr)
if !ok || a.IP.IsLoopback() {
return ""
}
return a.IP.String()
}
func (s *Server) track(c net.Conn, l *Listener) bool {
s.mu.Lock()
defer s.mu.Unlock()
h := host(c)
if h != "" && l.MaxPerIP > 0 && s.perIP[h] >= l.MaxPerIP {
return false
}
if h != "" {
s.perIP[h]++
}
s.conns[c] = true
return true
}
func (s *Server) untrack(c net.Conn) {
s.mu.Lock()
defer s.mu.Unlock()
if h := host(c); h != "" {
if s.perIP[h]--; s.perIP[h] <= 0 {
delete(s.perIP, h)
}
}
delete(s.conns, c)
}
// writeTimeout: how long a write may wait for a caller who reads nothing
const writeTimeout = 2 * time.Minute
// timedConn gives every write a deadline, so that a caller who stops
// reading does not hold a session (and its node) for ever.
type timedConn struct{ net.Conn }
func (c timedConn) Write(p []byte) (int, error) {
c.Conn.SetWriteDeadline(time.Now().Add(writeTimeout))
return c.Conn.Write(p)
}
func (s *Server) handle(nc net.Conn, l *Listener) {
defer nc.Close()
c := timedConn{nc}
remote := "local"
if c.RemoteAddr() != nil && c.RemoteAddr().String() != "" && c.RemoteAddr().String() != "@" {
remote = c.RemoteAddr().String()
}
if !s.track(c, l) {
s.B.Log.Printf("[listen %s] %s: too many connections from there", l.Name, remote)
c.SetWriteDeadline(time.Now().Add(5 * time.Second))
io.WriteString(c, "\r\nToo many connections from your address.\r\n")
return
}
defer s.untrack(c)
caller := &bbs.Caller{Via: l.Via, Listener: l.Name, Remote: remote}
if h := host(c); h != "" {
caller.Source = "ip:" + h
}
if l.Header {
h, err := ReadHeader(c, l.HeaderTimeout)
if err != nil {
s.B.Log.Printf("[listen %s] %s: %v", l.Name, remote, err)
return
}
applyHeader(caller, h, l.TrustUser)
}
if caller.Source == "" && caller.CallerID != "" {
caller.Source = "cid:" + caller.CallerID
}
// a caller with neither (a modem server's, with no caller ID) is not
// throttled: they all come from the same place, and one caller's
// failures would lock out every other. Each call still has its
// attempts and fail_delay.
node, err := s.B.Enter(caller, func() { c.Close() })
if err != nil {
s.B.Log.Printf("[listen %s] %s: %v", l.Name, remote, err)
c.SetWriteDeadline(time.Now().Add(5 * time.Second))
io.WriteString(c, "\r\nAll lines are busy; please call again later.\r\n")
return
}
defer node.Leave()
s.B.Log.Printf("node %d: %s on [listen %s]%s", node.Num, remote, l.Name, callDetails(caller))
switch l.Kind {
case "telnet":
err = s.telnet(c, l, node)
case "rlogin":
err = s.rlogin(c, l, node)
default:
err = s.text(c, c, l, node, "")
}
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) {
s.B.Log.Printf("node %d: %v", node.Num, err)
}
s.B.Log.Printf("node %d: gone", node.Num)
}
func callDetails(c *bbs.Caller) string {
var parts []string
if c.Rate != "" {
parts = append(parts, "rate "+c.Rate)
}
if c.CallerID != "" {
parts = append(parts, "from "+c.CallerID)
}
if c.Dialed != "" {
parts = append(parts, "to "+c.Dialed)
}
if c.TrustedUser != "" {
parts = append(parts, "as "+c.TrustedUser)
}
if len(parts) == 0 {
return ""
}
return ": " + strings.Join(parts, ", ")
}
// telnet: a 3270 to go3270, anything else to the text BBS
func (s *Server) telnet(c net.Conn, l *Listener, node *bbs.Node) error {
tc := telnet.New(c)
tt, err := tc.ProbeTermType(3 * time.Second)
if err != nil {
return err
}
node.Caller.Terminal = tt
if l.TN3270 && telnet.Is3270(tt) {
return s.tn3270(tc, l, node)
}
if !tc.Spoke() {
// not a telnet client at all: a raw terminal
return s.text(tc, c, l, node, "")
}
if err := tc.StartNVT(true, 2*time.Second); err != nil {
return err
}
return s.text(tc, c, l, node, tt)
}
func (s *Server) tn3270(tc *telnet.Conn, l *Listener, node *bbs.Node) error {
raw, err := tc.Handoff3270(2 * time.Second)
if err != nil {
return err
}
// go3270 negotiates without deadlines of its own: a client that
// stops answering is hung up
watchdog := time.AfterFunc(30*time.Second, func() { raw.Close() })
dev, err := go3270.NegotiateTelnet(raw)
if !watchdog.Stop() {
return errors.New("tn3270: negotiation timed out")
}
if err != nil {
return fmt.Errorf("tn3270: %w", err)
}
node.Caller.Via = "tn3270"
node.Caller.Terminal = dev.TerminalType()
rows, cols := dev.AltDimensions()
s.B.Log.Printf("node %d: tn3270 %s, %dx%d", node.Num, dev.TerminalType(), cols, rows)
return ui3270.Run(s.B, node, raw, dev, ui3270.Options{CreateTrusted: l.CreateUsers})
}
// what terminal types say about ANSI and UTF-8
func ansiTerm(tt string) (ansi, known bool) {
tt = strings.ToLower(tt)
for _, p := range []string{"ansi", "xterm", "vt1", "vt2", "vt3", "vt4", "vt5", "linux",
"screen", "tmux", "rxvt", "putty", "syncterm", "konsole", "gnome", "alacritty",
"kitty", "foot", "wezterm", "cygwin", "eterm", "iterm", "st-", "pcansi", "qansi"} {
if strings.HasPrefix(tt, p) {
return true, true
}
}
if tt == "st" {
return true, true
}
for _, p := range []string{"dumb", "tty", "vt52", "glasstty", "ascii", "network"} {
if strings.HasPrefix(tt, p) {
return false, true
}
}
return false, false
}
func utf8Term(tt string) bool {
tt = strings.ToLower(tt)
// BBS terminals that say "ansi" want CP437, not UTF-8
for _, p := range []string{"xterm", "linux", "screen", "tmux", "rxvt", "putty", "konsole",
"gnome", "alacritty", "kitty", "foot", "wezterm", "iterm", "st-"} {
if strings.HasPrefix(tt, p) {
return true
}
}
return tt == "st"
}
// text: the text BBS on rw (c for deadlines), tt the terminal type if told
func (s *Server) text(rw io.ReadWriter, c net.Conn, l *Listener, node *bbs.Node, tt string) error {
conn := struct {
io.ReadWriter
deadliner
}{rw, c}
t := textui.NewTerm(conn)
if tc, ok := rw.(*telnet.Conn); ok {
if cols, rows := tc.Size(); cols > 0 {
t.Cols, t.Rows = cols, rows
}
}
ansi, known := ansiTerm(tt)
switch l.ANSI {
case "yes":
t.ANSI = true
case "no":
t.ANSI = false
default:
if known {
t.ANSI = ansi
} else {
got, err := t.DetectANSI(2 * time.Second)
if err != nil {
return err
}
t.ANSI = got
}
}
switch l.UTF8 {
case "yes":
t.UTF8 = true
case "no":
t.UTF8 = false
default:
t.UTF8 = utf8Term(tt)
}
return textui.Run(s.B, node, t, textui.Options{CreateTrusted: l.CreateUsers})
}
type deadliner interface{ SetReadDeadline(time.Time) error }
// rlogin: RFC 1282's start, then the text BBS
func (s *Server) rlogin(c net.Conn, l *Listener, node *bbs.Node) error {
c.SetReadDeadline(time.Now().Add(10 * time.Second))
var fields []string
var cur []byte
b := make([]byte, 1)
for len(fields) < 4 {
if _, err := c.Read(b); err != nil {
return fmt.Errorf("rlogin: %w", err)
}
if b[0] != 0 {
if len(cur) >= 256 {
return errors.New("rlogin: a field is too long")
}
cur = append(cur, b[0])
continue
}
fields = append(fields, string(cur))
cur = cur[:0]
}
c.SetReadDeadline(time.Time{})
// fields[0] is empty: the protocol starts with a NUL
client, server, term := fields[1], fields[2], fields[3]
if _, err := c.Write([]byte{0}); err != nil {
return err
}
tt, speed, _ := strings.Cut(term, "/")
caller := node.Caller
caller.Terminal = tt
if caller.Rate == "" && speed != "" {
if n, err := strconv.Atoi(speed); err == nil && n > 0 {
caller.Rate = speed + "/" + speed
}
}
server = strings.TrimSpace(server)
if l.TrustUser && server != "" {
if caller.TrustedUser == "" {
caller.TrustedUser = server
}
} else {
caller.LoginUser, caller.LoginPassword = server, client
}
return s.text(c, c, l, node, tt)
}
+427
View File
@@ -0,0 +1,427 @@
package server
import (
"bytes"
"context"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/racingmars/go3270"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
func init() { store.BcryptCost = 4 } // fast hashes for tests
type env struct {
t *testing.T
b *bbs.BBS
dir string
}
// start runs a BBS with the listeners (their Address a socket name in a
// temporary directory) and two users, alice and sysop.
func start(t *testing.T, tweak func(*bbs.Settings), ls ...*Listener) *env {
t.Helper()
dir, err := os.MkdirTemp("", "bbs")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
st, err := store.Open(filepath.Join(dir, "bbs.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
if _, err := st.CreateUser("alice", "alicepass1", "Here", false); err != nil {
t.Fatal(err)
}
if _, err := st.CreateUser("sysop", "sysoppass1", "", true); err != nil {
t.Fatal(err)
}
if _, err := st.CreateArea("General", "Talk", false); err != nil {
t.Fatal(err)
}
s := bbs.Defaults()
s.Name = "Test BBS"
s.FailDelay = 0
if tweak != nil {
tweak(&s)
}
var logbuf bytes.Buffer
b := bbs.New(s, st, log.New(&logbuf, "", 0))
for _, l := range ls {
l.Address = filepath.Join(dir, l.Address)
l.SocketMode = 0600
if l.HeaderTimeout == 0 {
l.HeaderTimeout = 2 * time.Second
}
if l.Via == "" {
l.Via = l.Kind
}
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
New(b, ls).Run(ctx)
close(done)
}()
t.Cleanup(func() {
cancel()
<-done
if t.Failed() {
t.Log("log:\n" + logbuf.String())
}
})
for _, l := range ls {
for i := 0; ; i++ {
if _, err := os.Stat(l.Address); err == nil {
break
}
if i > 200 {
t.Fatalf("%s never listened", l.Address)
}
time.Sleep(10 * time.Millisecond)
}
}
return &env{t, b, dir}
}
// dialog is a connection to the BBS, read as text.
type dialog struct {
t *testing.T
c net.Conn
got []byte
}
func (e *env) dial(name string) *dialog {
c, err := net.Dial("unix", filepath.Join(e.dir, name))
if err != nil {
e.t.Fatal(err)
}
e.t.Cleanup(func() { c.Close() })
return &dialog{t: e.t, c: c}
}
func (d *dialog) send(s string) {
d.t.Helper()
if _, err := io.WriteString(d.c, s); err != nil {
d.t.Fatalf("send %q: %v", s, err)
}
}
// expect reads until want comes (and drops what came up to it).
func (d *dialog) expect(want string) {
d.t.Helper()
deadline := time.Now().Add(5 * time.Second)
buf := make([]byte, 4096)
for {
if i := bytes.Index(d.got, []byte(want)); i >= 0 {
d.got = d.got[i+len(want):]
return
}
d.c.SetReadDeadline(deadline)
n, err := d.c.Read(buf)
d.got = append(d.got, buf[:n]...)
if err != nil {
d.t.Fatalf("waiting for %q: %v; got %q", want, err, d.got)
}
}
}
func TestHeaderTrust(t *testing.T) {
e := start(t, nil, &Listener{Name: "menu", Kind: "raw", Address: "menu.sock", ANSI: "no",
Header: true, TrustUser: true, CreateUsers: true})
d := e.dial("menu.sock")
d.send("MODEM_USER=erin\nMODEM_AUTH=pam\nMODEM_RATE=26400/31200\nMODEM_CALLERID=5551234\n\n")
d.expect("modem at 26400 bit/s")
d.expect("Welcome, erin.")
d.expect("Command: ")
d.send("W")
d.expect("erin")
d.expect("modem 26400")
d.send("x")
d.expect("Command: ")
d.send("GY")
d.expect("Thanks for calling.")
u, err := e.b.Store.UserByName("erin")
if err != nil || !u.External {
t.Fatalf("erin: %+v, %v", u, err)
}
// an external account cannot log in by password
if _, err := e.b.Store.CheckPassword("erin", ""); err == nil {
t.Error("external account logged in with no password")
}
}
func TestHeaderUntrusted(t *testing.T) {
// without trust_user a header's user is not believed
e := start(t, nil, &Listener{Name: "menu", Kind: "raw", Address: "menu.sock", ANSI: "no", Header: true})
d := e.dial("menu.sock")
d.send("MODEM_USER=sysop\nDMODEM_RATE=33600/33600\n\n")
d.expect("Name (or NEW): ")
}
func TestLoginAndPost(t *testing.T) {
e := start(t, nil, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"})
d := e.dial("modem.sock")
d.expect("Name (or NEW): ")
d.send("alice\r")
d.expect("Password: ")
d.send("alicepass1\r")
d.expect("Welcome, alice.")
d.expect("Command: ")
d.send("M")
d.expect("[Q]uit: ")
d.send("1\r")
d.expect("[P]ost, [Q]uit: ")
d.send("P\r")
d.expect("To [All]: ")
d.send("\r")
d.expect("Subject: ")
d.send("Hi \x1b[2Jthere\r")
d.expect("clears all.")
d.send("First line\r\x1b]0;title\x07Second\r/s\r")
d.expect("Posted as #1.")
m, err := e.b.Store.Message(1)
if err != nil {
t.Fatal(err)
}
if m.To != "All" || m.From != "alice" || strings.ContainsAny(m.Subject+m.Body, "\x1b\x07") {
t.Errorf("message: %+v", m)
}
}
func TestRLogin(t *testing.T) {
e := start(t, nil, &Listener{Name: "rlogin", Kind: "rlogin", Address: "rlogin.sock", ANSI: "auto"})
d := e.dial("rlogin.sock")
d.send("\x00alicepass1\x00alice\x00ansi/9600\x00")
d.expect("\x00")
d.expect("rlogin at 9600 bit/s")
d.expect("Welcome, ")
d.expect("alice")
// a wrong password: asked again, the name typed in already
d = e.dial("rlogin.sock")
d.send("\x00wrong\x00alice\x00vt100/2400\x00")
d.expect("Name")
d.expect("alice")
d.send("\r")
d.expect("Password: ")
}
func TestRLoginTrust(t *testing.T) {
e := start(t, nil, &Listener{Name: "rlogin", Kind: "rlogin", Address: "rlogin.sock", ANSI: "no", TrustUser: true})
d := e.dial("rlogin.sock")
d.send("\x00\x00alice\x00dumb/33600\x00")
d.expect("Welcome, alice.")
}
func TestThrottle(t *testing.T) {
e := start(t, func(s *bbs.Settings) { s.ThrottleFails = 2; s.Attempts = 5 },
&Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no", Header: true})
// failures count against the caller ID
d := e.dial("modem.sock")
d.send("DMODEM_CALLERID=5550001\n\n")
for i := 0; i < 2; i++ {
d.expect("Name (or NEW): ")
d.send("alice\rwrong-pass\r")
d.expect("wrong name or password.")
}
d.expect("Name (or NEW): ")
d.send("alice\ralicepass1\r")
d.expect("too many failed logins")
// another caller is not locked out
d = e.dial("modem.sock")
d.send("DMODEM_CALLERID=5550002\n\n")
d.expect("Name (or NEW): ")
d.send("alice\ralicepass1\r")
d.expect("Welcome, alice.")
}
func TestBusy(t *testing.T) {
e := start(t, func(s *bbs.Settings) { s.MaxNodes = 1 },
&Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"})
d1 := e.dial("modem.sock")
d1.expect("Node 1")
d2 := e.dial("modem.sock")
d2.expect("All lines are busy")
}
func TestNewUser(t *testing.T) {
e := start(t, nil, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"})
d := e.dial("modem.sock")
d.expect("Name (or NEW): ")
d.send("new\r")
d.expect("give up): ")
d.send("alice\r")
d.expect("That name is taken.")
d.send("Zed\r")
d.expect("Password (8 or more characters): ")
d.send("zedpassword\rzedpassword\r")
d.expect("calling from? ")
d.send("Mars\r")
d.expect("Welcome, Zed.")
if u, err := e.b.Store.CheckPassword("zed", "zedpassword"); err != nil || u.Location != "Mars" {
t.Errorf("Zed: %+v, %v", u, err)
}
}
func TestTelnetANSI(t *testing.T) {
e := start(t, nil, &Listener{Name: "telnet", Kind: "telnet", Address: "telnet.sock",
TN3270: true, ANSI: "auto", UTF8: "auto"})
c, err := net.Dial("unix", filepath.Join(e.dir, "telnet.sock"))
if err != nil {
t.Fatal(err)
}
defer c.Close()
tc := &tnClient{c: c, ttype: "ANSI"}
tc.expect(t, "\x1b[1;36mTest BBS")
tc.expect(t, "Name")
}
// tnClient is a telnet client that answers the server and keeps the data.
type tnClient struct {
c net.Conn
ttype string
got []byte
recs [][]byte // 3270 records, split at IAC EOR
cur []byte
}
const (
iac, sb, se, will, wont, do, dont, eor = 255, 250, 240, 251, 252, 253, 254, 239
)
func (tc *tnClient) read(t *testing.T) {
t.Helper()
buf := make([]byte, 4096)
tc.c.SetReadDeadline(time.Now().Add(5 * time.Second))
n, err := tc.c.Read(buf)
if err != nil {
t.Fatalf("read: %v; got %q", err, tc.got)
}
b := buf[:n]
for i := 0; i < len(b); i++ {
if b[i] != iac {
tc.got = append(tc.got, b[i])
tc.cur = append(tc.cur, b[i])
continue
}
// a command split across reads: IAC x, or IAC x option
need := func() int {
if i+1 < len(b) && b[i+1] != iac && b[i+1] != eor {
return 2
}
return 1
}
for i+need() >= len(b) {
m, err := tc.c.Read(buf[n:])
if err != nil {
t.Fatal(err)
}
n += m
b = buf[:n]
}
switch b[i+1] {
case iac:
tc.got = append(tc.got, iac)
tc.cur = append(tc.cur, iac)
i++
case eor:
tc.recs = append(tc.recs, tc.cur)
tc.cur = nil
i++
case do:
switch b[i+2] {
case 24, 25, 0, 3, 31:
tc.c.Write([]byte{iac, will, b[i+2]})
default:
tc.c.Write([]byte{iac, wont, b[i+2]})
}
i += 2
case will:
tc.c.Write([]byte{iac, do, b[i+2]})
i += 2
case dont:
tc.c.Write([]byte{iac, wont, b[i+2]})
i += 2
case wont:
i += 2
case sb:
j := bytes.Index(b[i:], []byte{iac, se})
if j < 0 {
t.Fatal("split subnegotiation")
}
if b[i+2] == 24 && b[i+3] == 1 {
msg := append([]byte{iac, sb, 24, 0}, tc.ttype...)
tc.c.Write(append(msg, iac, se))
}
i += j + 1
default:
i++
}
}
}
func (tc *tnClient) expect(t *testing.T, want string) {
t.Helper()
for !bytes.Contains(tc.got, []byte(want)) {
tc.read(t)
}
}
// record waits for the next 3270 record.
func (tc *tnClient) record(t *testing.T) []byte {
t.Helper()
for len(tc.recs) == 0 {
tc.read(t)
}
r := tc.recs[0]
tc.recs = tc.recs[1:]
return r
}
func TestTN3270(t *testing.T) {
e := start(t, nil, &Listener{Name: "telnet", Kind: "telnet", Address: "telnet.sock",
TN3270: true, ANSI: "auto", UTF8: "auto"})
c, err := net.Dial("unix", filepath.Join(e.dir, "telnet.sock"))
if err != nil {
t.Fatal(err)
}
defer c.Close()
tc := &tnClient{c: c, ttype: "IBM-3278-2-E"}
cp := go3270.Codepage1047()
// go3270 clears the screen, then asks what the terminal is: no
// answer but an empty query reply
var screen string
for i := 0; i < 5 && !strings.Contains(screen, "Logon"); i++ {
rec := tc.record(t)
if len(rec) > 0 && rec[0] == 0xf3 { // write structured field: the query
tc.c.Write([]byte{0x88, iac, eor})
continue
}
screen = cp.Decode(rec)
}
if !strings.Contains(screen, "Logon") || !strings.Contains(screen, "Test BBS") {
t.Fatalf("no logon screen: %q", screen)
}
// PF3: exit
tc.c.Write([]byte{0xf3, 0x40, 0x40, iac, eor})
bye := cp.Decode(tc.record(t))
if !strings.Contains(bye, "Thanks for calling.") {
t.Errorf("goodbye screen: %q", bye)
}
nodes := e.b.Nodes()
if len(nodes) > 1 {
t.Errorf("nodes: %+v", nodes)
}
}
+540
View File
@@ -0,0 +1,540 @@
// Package store keeps the BBS in an SQLite database: users, message
// areas and their messages, private mail, and what each user has read.
package store
import (
"database/sql"
"errors"
"fmt"
"os"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
_ "modernc.org/sqlite"
)
// ErrNotFound: no such user, area, message or mail.
var ErrNotFound = errors.New("not found")
// ErrExists: the name is taken.
var ErrExists = errors.New("already exists")
// NoPassword is the stored password of an account that cannot log in by
// password: one an upstream menu (modemmenu) logs in.
const NoPassword = "!"
// BcryptCost is the cost of new password hashes.
var BcryptCost = 12
// User is an account.
type User struct {
ID int64
Name string
Location string
Sysop bool
Locked bool
External bool // logged in by an upstream menu, no password here
Created time.Time
LastLogin time.Time
Logins int
Posts int
}
// Area is a message area.
type Area struct {
ID int64
Name string
Description string
SysopOnly bool // only sysops post
Messages int
LastID int64
}
// Message is a public message in an area, or a private mail.
type Message struct {
ID int64
AreaID int64 // 0 for mail
FromID int64
From string
ToID int64 // mail only
To string
Subject string
Body string
ReplyTo int64
Created time.Time
Read bool // mail only
}
// Store is the database.
type Store struct {
db *sql.DB
// a hash to check against for unknown users, so that they take as
// long as known ones
dummy []byte
}
const schema = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
password TEXT NOT NULL,
location TEXT NOT NULL DEFAULT '',
sysop INTEGER NOT NULL DEFAULT 0,
locked INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL,
last_login INTEGER NOT NULL DEFAULT 0,
logins INTEGER NOT NULL DEFAULT 0,
posts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS areas (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
description TEXT NOT NULL DEFAULT '',
sysop_only INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY,
area_id INTEGER NOT NULL REFERENCES areas(id) ON DELETE CASCADE,
from_id INTEGER NOT NULL,
from_name TEXT NOT NULL,
to_name TEXT NOT NULL DEFAULT 'All',
subject TEXT NOT NULL,
body TEXT NOT NULL,
reply_to INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_area ON messages(area_id, id);
CREATE TABLE IF NOT EXISTS lastread (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
area_id INTEGER NOT NULL REFERENCES areas(id) ON DELETE CASCADE,
message_id INTEGER NOT NULL,
PRIMARY KEY (user_id, area_id)
);
CREATE TABLE IF NOT EXISTS mail (
id INTEGER PRIMARY KEY,
from_id INTEGER NOT NULL,
from_name TEXT NOT NULL,
to_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
to_name TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT NOT NULL,
reply_to INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL,
read INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS mail_to ON mail(to_id, id);
`
// Open opens (and creates, if need be) the database at path.
func Open(path string) (*Store, error) {
// passwords and private mail: for the BBS's user alone (SQLite gives
// the -wal and -shm files the database's permissions)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
f.Close()
dsn := "file:" + path + "?_pragma=busy_timeout(5000)" +
"&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)" +
"&_pragma=synchronous(NORMAL)"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
}
// one connection: SQLite takes one writer at a time anyway, and a BBS
// is not busy enough to want more
db.SetMaxOpenConns(1)
if _, err := db.Exec(schema); err != nil {
db.Close()
return nil, fmt.Errorf("%s: %w", path, err)
}
dummy, err := bcrypt.GenerateFromPassword([]byte("not a password"), BcryptCost)
if err != nil {
db.Close()
return nil, err
}
return &Store{db: db, dummy: dummy}, nil
}
// Close closes the database.
func (s *Store) Close() error { return s.db.Close() }
func now() int64 { return time.Now().Unix() }
func unix(t int64) time.Time {
if t == 0 {
return time.Time{}
}
return time.Unix(t, 0)
}
// HashPassword returns the bcrypt hash of pw.
func HashPassword(pw string) (string, error) {
h, err := bcrypt.GenerateFromPassword([]byte(pw), BcryptCost)
return string(h), err
}
const userCols = `id, name, password, location, sysop, locked, created, last_login, logins, posts`
func scanUser(row interface{ Scan(...any) error }) (*User, string, error) {
var u User
var pw string
var created, last int64
err := row.Scan(&u.ID, &u.Name, &pw, &u.Location, &u.Sysop, &u.Locked,
&created, &last, &u.Logins, &u.Posts)
if errors.Is(err, sql.ErrNoRows) {
return nil, "", ErrNotFound
}
if err != nil {
return nil, "", err
}
u.Created, u.LastLogin = unix(created), unix(last)
u.External = pw == NoPassword
return &u, pw, nil
}
// CreateUser adds an account. password "" makes an external account (no
// password: only an upstream menu logs it in).
func (s *Store) CreateUser(name, password, location string, sysop bool) (*User, error) {
hash := NoPassword
if password != "" {
h, err := HashPassword(password)
if err != nil {
return nil, err
}
hash = h
}
res, err := s.db.Exec(`INSERT INTO users (name, password, location, sysop, created)
VALUES (?, ?, ?, ?, ?)`, name, hash, location, sysop, now())
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
return nil, ErrExists
}
return nil, err
}
id, _ := res.LastInsertId()
return s.UserByID(id)
}
// UserByName finds an account by name, in any case.
func (s *Store) UserByName(name string) (*User, error) {
u, _, err := scanUser(s.db.QueryRow(`SELECT `+userCols+` FROM users WHERE name = ?`, name))
return u, err
}
// UserByID finds an account by id.
func (s *Store) UserByID(id int64) (*User, error) {
u, _, err := scanUser(s.db.QueryRow(`SELECT `+userCols+` FROM users WHERE id = ?`, id))
return u, err
}
// CheckPassword returns the user if name exists and pw is its password,
// ErrNotFound otherwise. It takes as long for unknown users and external
// accounts as for a wrong password.
func (s *Store) CheckPassword(name, pw string) (*User, error) {
u, hash, err := scanUser(s.db.QueryRow(`SELECT `+userCols+` FROM users WHERE name = ?`, name))
if err != nil && !errors.Is(err, ErrNotFound) {
return nil, err
}
if u == nil || hash == NoPassword {
bcrypt.CompareHashAndPassword(s.dummy, []byte(pw))
return nil, ErrNotFound
}
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw)) != nil {
return nil, ErrNotFound
}
return u, nil
}
// SetPassword changes a user's password.
func (s *Store) SetPassword(id int64, pw string) error {
h, err := HashPassword(pw)
if err != nil {
return err
}
return s.exec1(`UPDATE users SET password = ? WHERE id = ?`, h, id)
}
// SetLocation changes a user's location.
func (s *Store) SetLocation(id int64, loc string) error {
return s.exec1(`UPDATE users SET location = ? WHERE id = ?`, loc, id)
}
// SetSysop gives or takes a user's sysop rights.
func (s *Store) SetSysop(id int64, sysop bool) error {
return s.exec1(`UPDATE users SET sysop = ? WHERE id = ?`, sysop, id)
}
// SetLocked locks a user out, or lets them in again.
func (s *Store) SetLocked(id int64, locked bool) error {
return s.exec1(`UPDATE users SET locked = ? WHERE id = ?`, locked, id)
}
// DeleteUser removes an account and its mail; its messages stay.
func (s *Store) DeleteUser(id int64) error {
return s.exec1(`DELETE FROM users WHERE id = ?`, id)
}
// LoggedIn counts a login.
func (s *Store) LoggedIn(id int64) error {
return s.exec1(`UPDATE users SET logins = logins + 1, last_login = ? WHERE id = ?`, now(), id)
}
// Users lists the accounts by name.
func (s *Store) Users() ([]*User, error) {
rows, err := s.db.Query(`SELECT ` + userCols + ` FROM users ORDER BY name`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*User
for rows.Next() {
u, _, err := scanUser(rows)
if err != nil {
return nil, err
}
out = append(out, u)
}
return out, rows.Err()
}
func (s *Store) exec1(q string, args ...any) error {
res, err := s.db.Exec(q, args...)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// CreateArea adds a message area.
func (s *Store) CreateArea(name, desc string, sysopOnly bool) (*Area, error) {
res, err := s.db.Exec(`INSERT INTO areas (name, description, sysop_only) VALUES (?, ?, ?)`,
name, desc, sysopOnly)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
return nil, ErrExists
}
return nil, err
}
id, _ := res.LastInsertId()
return s.Area(id)
}
// DeleteArea removes an area and its messages.
func (s *Store) DeleteArea(id int64) error {
return s.exec1(`DELETE FROM areas WHERE id = ?`, id)
}
const areaQuery = `SELECT a.id, a.name, a.description, a.sysop_only,
(SELECT COUNT(*) FROM messages m WHERE m.area_id = a.id),
(SELECT COALESCE(MAX(m.id), 0) FROM messages m WHERE m.area_id = a.id)
FROM areas a`
func scanArea(row interface{ Scan(...any) error }) (*Area, error) {
var a Area
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopOnly, &a.Messages, &a.LastID)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return &a, err
}
// Areas lists the message areas.
func (s *Store) Areas() ([]*Area, error) {
rows, err := s.db.Query(areaQuery + ` ORDER BY a.id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Area
for rows.Next() {
a, err := scanArea(rows)
if err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
// Area finds an area by id.
func (s *Store) Area(id int64) (*Area, error) {
return scanArea(s.db.QueryRow(areaQuery+` WHERE a.id = ?`, id))
}
// AreaByName finds an area by name.
func (s *Store) AreaByName(name string) (*Area, error) {
return scanArea(s.db.QueryRow(areaQuery+` WHERE a.name = ?`, name))
}
const msgCols = `id, area_id, from_id, from_name, to_name, subject, body, reply_to, created`
func scanMessage(row interface{ Scan(...any) error }) (*Message, error) {
var m Message
var created int64
err := row.Scan(&m.ID, &m.AreaID, &m.FromID, &m.From, &m.To, &m.Subject,
&m.Body, &m.ReplyTo, &created)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
m.Created = unix(created)
return &m, err
}
// Post adds a message to an area.
func (s *Store) Post(m *Message) (int64, error) {
tx, err := s.db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
res, err := tx.Exec(`INSERT INTO messages (area_id, from_id, from_name, to_name, subject, body, reply_to, created)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, m.AreaID, m.FromID, m.From, m.To, m.Subject, m.Body, m.ReplyTo, now())
if err != nil {
return 0, err
}
if _, err := tx.Exec(`UPDATE users SET posts = posts + 1 WHERE id = ?`, m.FromID); err != nil {
return 0, err
}
id, _ := res.LastInsertId()
return id, tx.Commit()
}
// Message finds a message by id.
func (s *Store) Message(id int64) (*Message, error) {
return scanMessage(s.db.QueryRow(`SELECT `+msgCols+` FROM messages WHERE id = ?`, id))
}
// Messages lists up to limit messages of an area, from id after on
// (exclusive), oldest first.
func (s *Store) Messages(area, after int64, limit int) ([]*Message, error) {
rows, err := s.db.Query(`SELECT `+msgCols+` FROM messages WHERE area_id = ? AND id > ?
ORDER BY id LIMIT ?`, area, after, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Message
for rows.Next() {
m, err := scanMessage(rows)
if err != nil {
return nil, err
}
out = append(out, m)
}
return out, rows.Err()
}
// Neighbour finds the message of the same area just after id (next) or
// just before it.
func (s *Store) Neighbour(area, id int64, next bool) (*Message, error) {
q := `SELECT ` + msgCols + ` FROM messages WHERE area_id = ? AND id < ? ORDER BY id DESC LIMIT 1`
if next {
q = `SELECT ` + msgCols + ` FROM messages WHERE area_id = ? AND id > ? ORDER BY id LIMIT 1`
}
return scanMessage(s.db.QueryRow(q, area, id))
}
// DeleteMessage removes a message.
func (s *Store) DeleteMessage(id int64) error {
return s.exec1(`DELETE FROM messages WHERE id = ?`, id)
}
// LastRead is the last message of an area the user has read.
func (s *Store) LastRead(user, area int64) (int64, error) {
var id int64
err := s.db.QueryRow(`SELECT message_id FROM lastread WHERE user_id = ? AND area_id = ?`,
user, area).Scan(&id)
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return id, err
}
// SetLastRead moves the user's last read message of an area forward to id.
func (s *Store) SetLastRead(user, area, id int64) error {
_, err := s.db.Exec(`INSERT INTO lastread (user_id, area_id, message_id) VALUES (?, ?, ?)
ON CONFLICT (user_id, area_id) DO UPDATE SET message_id = MAX(message_id, excluded.message_id)`,
user, area, id)
return err
}
// NewCount counts the messages of an area the user has not read.
func (s *Store) NewCount(user, area int64) (int, error) {
last, err := s.LastRead(user, area)
if err != nil {
return 0, err
}
var n int
err = s.db.QueryRow(`SELECT COUNT(*) FROM messages WHERE area_id = ? AND id > ?`,
area, last).Scan(&n)
return n, err
}
const mailCols = `id, from_id, from_name, to_id, to_name, subject, body, reply_to, created, read`
func scanMail(row interface{ Scan(...any) error }) (*Message, error) {
var m Message
var created int64
err := row.Scan(&m.ID, &m.FromID, &m.From, &m.ToID, &m.To, &m.Subject,
&m.Body, &m.ReplyTo, &created, &m.Read)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
m.Created = unix(created)
return &m, err
}
// SendMail delivers a private message.
func (s *Store) SendMail(m *Message) (int64, error) {
res, err := s.db.Exec(`INSERT INTO mail (from_id, from_name, to_id, to_name, subject, body, reply_to, created)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, m.FromID, m.From, m.ToID, m.To, m.Subject, m.Body, m.ReplyTo, now())
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// Inbox lists a user's mail, oldest first.
func (s *Store) Inbox(user int64) ([]*Message, error) {
rows, err := s.db.Query(`SELECT `+mailCols+` FROM mail WHERE to_id = ? ORDER BY id`, user)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Message
for rows.Next() {
m, err := scanMail(rows)
if err != nil {
return nil, err
}
out = append(out, m)
}
return out, rows.Err()
}
// Mail finds a mail of user's by id: no one reads another's mail.
func (s *Store) Mail(user, id int64) (*Message, error) {
return scanMail(s.db.QueryRow(`SELECT `+mailCols+` FROM mail WHERE id = ? AND to_id = ?`, id, user))
}
// MarkMailRead marks a mail of user's read.
func (s *Store) MarkMailRead(user, id int64) error {
return s.exec1(`UPDATE mail SET read = 1 WHERE id = ? AND to_id = ?`, id, user)
}
// DeleteMail deletes a mail of user's.
func (s *Store) DeleteMail(user, id int64) error {
return s.exec1(`DELETE FROM mail WHERE id = ? AND to_id = ?`, id, user)
}
// UnreadMail counts a user's unread mail.
func (s *Store) UnreadMail(user int64) (int, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM mail WHERE to_id = ? AND read = 0`, user).Scan(&n)
return n, err
}
+472
View File
@@ -0,0 +1,472 @@
// Package telnet is the server side of the telnet protocol, enough for a
// BBS: echo and suppress go-ahead for character-at-a-time input, the
// terminal type and window size, binary, and telling TN3270 clients from
// the rest so they can be handed to go3270.
package telnet
import (
"bufio"
"errors"
"net"
"os"
"regexp"
"strings"
"sync"
"time"
)
// Commands and options.
const (
SE = 240
NOP = 241
GA = 249
SB = 250
WILL = 251
WONT = 252
DO = 253
DONT = 254
IAC = 255
OptBinary = 0
OptEcho = 1
OptSGA = 3
OptTType = 24
OptEOR = 25
OptNAWS = 31
ttypeIs = 0
ttypeSend = 1
)
const (
maxSub = 256 // longest subnegotiation kept
maxEarly = 4096 // data kept while negotiating
)
// Conn is a telnet connection: Read returns the client's data with the
// commands taken out (and answered), Write escapes IAC.
type Conn struct {
net.Conn
r *bufio.Reader
wmu sync.Mutex
mu sync.Mutex
us, him [256]bool // options in effect: we do, the client does
askUs [256]bool // a WILL or WONT of ours is unanswered
askHim [256]bool // a DO or DONT of ours is unanswered
ttype string
cols int
rows int
gotType bool
sawIAC bool
state int
cmd byte
sub []byte
lastCR bool
early []byte // data that came while negotiating
out []byte // answers to send, in order
}
const (
stData = iota
stIAC
stOpt
stSub
stSubIAC
)
// New wraps a connection.
func New(c net.Conn) *Conn {
return &Conn{Conn: c, r: bufio.NewReaderSize(c, 4096)}
}
// TermType is the terminal type the client gave ("" if none).
func (c *Conn) TermType() string {
c.mu.Lock()
defer c.mu.Unlock()
return c.ttype
}
// Size is the window size the client gave (0, 0 if none).
func (c *Conn) Size() (cols, rows int) {
c.mu.Lock()
defer c.mu.Unlock()
return c.cols, c.rows
}
// Spoke reports whether the client has sent any telnet command: false for
// a raw client (a terminal program on a modem, netcat) on a telnet port.
func (c *Conn) Spoke() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.sawIAC
}
// Binary reports whether both directions are binary (8-bit clean).
func (c *Conn) Binary() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.us[OptBinary] && c.him[OptBinary]
}
// Read returns the client's data.
func (c *Conn) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
c.mu.Lock()
if len(c.early) > 0 {
n := copy(p, c.early)
c.early = c.early[n:]
c.mu.Unlock()
return n, nil
}
c.mu.Unlock()
n := 0
for n == 0 || (n < len(p) && c.r.Buffered() > 0) {
b, err := c.r.ReadByte()
if err != nil {
if n > 0 {
return n, nil
}
return 0, err
}
d, ok := c.input(b)
if err := c.flush(); err != nil {
return n, err
}
if ok {
p[n] = d
n++
}
}
return n, nil
}
// flush sends the answers input queued.
func (c *Conn) flush() error {
c.mu.Lock()
out := c.out
c.out = nil
c.mu.Unlock()
if len(out) == 0 {
return nil
}
_, err := c.send(out)
return err
}
// Write sends data, IAC doubled.
func (c *Conn) Write(p []byte) (int, error) {
out := p
for i, b := range p {
if b == IAC {
out = make([]byte, 0, len(p)+8)
out = append(out, p[:i]...)
for _, b := range p[i:] {
out = append(out, b)
if b == IAC {
out = append(out, IAC)
}
}
break
}
}
if _, err := c.send(out); err != nil {
return 0, err
}
return len(p), nil
}
func (c *Conn) send(b []byte) (int, error) {
c.wmu.Lock()
defer c.wmu.Unlock()
return c.Conn.Write(b)
}
// input runs one byte through the protocol: the data byte, if it is one.
func (c *Conn) input(b byte) (byte, bool) {
c.mu.Lock()
defer c.mu.Unlock()
switch c.state {
case stData:
if b == IAC {
c.sawIAC = true
c.state = stIAC
return 0, false
}
// CR NUL is a bare CR; CR LF is passed as it is
if b == 0 && c.lastCR {
c.lastCR = false
return 0, false
}
c.lastCR = b == '\r'
return b, true
case stIAC:
switch b {
case IAC:
c.state = stData
c.lastCR = false
return IAC, true
case WILL, WONT, DO, DONT:
c.cmd, c.state = b, stOpt
case SB:
c.sub, c.state = c.sub[:0], stSub
default: // NOP, GA, AYT, ...: nothing to do
c.state = stData
}
case stOpt:
c.option(c.cmd, b)
c.state = stData
case stSub:
if b == IAC {
c.state = stSubIAC
} else if len(c.sub) < maxSub {
c.sub = append(c.sub, b)
}
case stSubIAC:
switch b {
case SE:
c.subneg()
c.state = stData
case IAC:
if len(c.sub) < maxSub {
c.sub = append(c.sub, IAC)
}
c.state = stSub
default:
// a broken subnegotiation: drop it
c.state = stData
}
}
return 0, false
}
// what the client may do, and what we will do when asked
func acceptHim(opt byte) bool {
return opt == OptTType || opt == OptNAWS || opt == OptSGA || opt == OptBinary
}
func acceptUs(opt byte) bool {
return opt == OptEcho || opt == OptSGA || opt == OptBinary
}
// option handles WILL, WONT, DO and DONT, so that no answer is sent to an
// answer (RFC 854's rule against loops). c.mu is held.
func (c *Conn) option(cmd, opt byte) {
switch cmd {
case WILL:
switch {
case c.askHim[opt]:
c.askHim[opt] = false
c.him[opt] = true
case c.him[opt]:
return
case acceptHim(opt):
c.him[opt] = true
c.queue(IAC, DO, opt)
default:
c.queue(IAC, DONT, opt)
}
if opt == OptTType && c.him[opt] {
c.queue(IAC, SB, OptTType, ttypeSend, IAC, SE)
}
case WONT:
if c.askHim[opt] {
c.askHim[opt] = false
} else if c.him[opt] {
c.queue(IAC, DONT, opt)
}
c.him[opt] = false
if opt == OptTType {
c.gotType = true // refused: nothing is coming
}
case DO:
switch {
case c.askUs[opt]:
c.askUs[opt] = false
c.us[opt] = true
case c.us[opt]:
case acceptUs(opt):
c.us[opt] = true
c.queue(IAC, WILL, opt)
default:
c.queue(IAC, WONT, opt)
}
case DONT:
if c.askUs[opt] {
c.askUs[opt] = false
} else if c.us[opt] {
c.queue(IAC, WONT, opt)
}
c.us[opt] = false
}
}
// queue an answer, sent once the byte that asked is handled. c.mu is held.
func (c *Conn) queue(b ...byte) {
if len(c.out) < 1024 {
c.out = append(c.out, b...)
}
}
func (c *Conn) subneg() {
if len(c.sub) == 0 {
return
}
switch c.sub[0] {
case OptTType:
if len(c.sub) >= 2 && c.sub[1] == ttypeIs && !c.gotType {
t := make([]byte, 0, 40)
for _, b := range c.sub[2:] {
if b > ' ' && b < 0x7f && len(t) < 40 {
t = append(t, b)
}
}
c.ttype = strings.ToUpper(string(t))
c.gotType = true
}
case OptNAWS:
if len(c.sub) == 5 {
w := int(c.sub[1])<<8 | int(c.sub[2])
h := int(c.sub[3])<<8 | int(c.sub[4])
if w >= 20 && w <= 500 {
c.cols = w
}
if h >= 5 && h <= 300 {
c.rows = h
}
}
}
}
// ask sends a request of ours: DO or DONT for the client's options, WILL or
// WONT for ours, unless it is in effect (or asked) already.
func (c *Conn) ask(cmd, opt byte) {
c.mu.Lock()
defer c.mu.Unlock()
c.askLocked(cmd, opt)
}
func (c *Conn) askLocked(cmd, opt byte) {
switch cmd {
case DO:
if c.him[opt] || c.askHim[opt] {
return
}
c.askHim[opt] = true
case DONT:
if !c.him[opt] || c.askHim[opt] {
return
}
c.askHim[opt] = true
c.him[opt] = false
case WILL:
if c.us[opt] || c.askUs[opt] {
return
}
c.askUs[opt] = true
case WONT:
if !c.us[opt] || c.askUs[opt] {
return
}
c.askUs[opt] = true
c.us[opt] = false
}
c.queue(IAC, cmd, opt)
}
// pump reads and handles the client's bytes until done says so or the
// deadline passes; data is kept for Read.
func (c *Conn) pump(deadline time.Time, done func() bool) error {
if err := c.flush(); err != nil {
return err
}
c.Conn.SetReadDeadline(deadline)
defer c.Conn.SetReadDeadline(time.Time{})
for {
c.mu.Lock()
ok := done()
c.mu.Unlock()
if ok {
return nil
}
b, err := c.r.ReadByte()
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
return nil
}
return err
}
d, ok := c.input(b)
if err := c.flush(); err != nil {
return err
}
if ok {
c.mu.Lock()
if len(c.early) < maxEarly {
c.early = append(c.early, d)
}
c.mu.Unlock()
}
}
}
// ProbeTermType asks the client for its terminal type and waits up to
// timeout for it. "" means the client gave none: it refused, or it does
// not speak telnet at all.
func (c *Conn) ProbeTermType(timeout time.Duration) (string, error) {
c.ask(DO, OptTType)
err := c.pump(time.Now().Add(timeout), func() bool { return c.gotType })
return c.TermType(), err
}
var tn3270Pattern = regexp.MustCompile(`^IBM-(327[789]|DYNAMIC)`)
// Is3270 reports whether a terminal type is a 3270's (IBM-3278-2-E,
// IBM-DYNAMIC, ...). IBM-3151 and other ASCII IBM terminals are not.
func Is3270(ttype string) bool {
return tn3270Pattern.MatchString(strings.ToUpper(ttype))
}
// StartNVT sets the connection up for a text BBS: the server echoes,
// character at a time, and asks for the window size (waiting up to
// timeout for it). With binary, 8-bit data is asked for both ways.
func (c *Conn) StartNVT(binary bool, timeout time.Duration) error {
c.ask(WILL, OptEcho)
c.ask(WILL, OptSGA)
c.ask(DO, OptSGA)
c.ask(DO, OptNAWS)
if binary {
c.ask(WILL, OptBinary)
c.ask(DO, OptBinary)
}
return c.pump(time.Now().Add(timeout), func() bool {
return !c.askHim[OptNAWS] && !c.askUs[OptEcho] && !c.askHim[OptSGA] &&
!c.askHim[OptBinary] && !c.askUs[OptBinary]
})
}
// Handoff3270 undoes the terminal type option (go3270 negotiates it again
// from the start) and returns the connection for go3270, the client's
// pending bytes included. The Conn must not be used after.
func (c *Conn) Handoff3270(timeout time.Duration) (net.Conn, error) {
c.ask(DONT, OptTType)
if err := c.pump(time.Now().Add(timeout), func() bool { return !c.askHim[OptTType] }); err != nil {
return nil, err
}
// let stragglers come and be answered
if err := c.pump(time.Now().Add(100*time.Millisecond), func() bool { return false }); err != nil {
return nil, err
}
return &rawConn{c.Conn, c.r}, nil
}
// rawConn is the connection under a Conn, its buffered bytes first.
type rawConn struct {
net.Conn
r *bufio.Reader
}
func (r *rawConn) Read(p []byte) (int, error) { return r.r.Read(p) }
+156
View File
@@ -0,0 +1,156 @@
package telnet
import (
"bytes"
"io"
"net"
"testing"
"time"
)
func TestIs3270(t *testing.T) {
for tt, want := range map[string]bool{
"IBM-3278-2-E": true, "IBM-3279-4-E": true, "IBM-DYNAMIC": true, "ibm-3277-2": true,
"IBM-3151": false, "XTERM": false, "ANSI": false, "": false,
} {
if Is3270(tt) != want {
t.Errorf("Is3270(%q) != %v", tt, want)
}
}
}
// client plays a telnet client on c: it answers the server's requests and
// gives ttype as its terminal type; what it gets as data goes to data.
func client(c net.Conn, ttype string, data chan<- []byte) {
buf := make([]byte, 1024)
var got []byte
for {
n, err := c.Read(buf)
if err != nil {
data <- got
return
}
b := buf[:n]
for i := 0; i < len(b); i++ {
if b[i] != IAC || i+1 >= len(b) {
got = append(got, b[i])
continue
}
switch b[i+1] {
case IAC:
got = append(got, IAC)
i++
case DO:
switch b[i+2] {
case OptTType, OptNAWS, OptSGA, OptBinary:
c.Write([]byte{IAC, WILL, b[i+2]})
if b[i+2] == OptNAWS {
c.Write([]byte{IAC, SB, OptNAWS, 0, 132, 0, 50, IAC, SE})
}
default:
c.Write([]byte{IAC, WONT, b[i+2]})
}
i += 2
case WILL:
c.Write([]byte{IAC, DO, b[i+2]})
i += 2
case DONT:
c.Write([]byte{IAC, WONT, b[i+2]})
i += 2
case WONT:
i += 2
case SB:
// SB TTYPE SEND IAC SE
if b[i+2] == OptTType && b[i+3] == ttypeSend {
msg := append([]byte{IAC, SB, OptTType, ttypeIs}, ttype...)
c.Write(append(msg, IAC, SE))
}
for i < len(b) && b[i] != SE {
i++
}
}
}
}
}
func TestNegotiate(t *testing.T) {
srv, cli := net.Pipe()
data := make(chan []byte, 1)
go client(cli, "xterm-256color", data)
c := New(srv)
tt, err := c.ProbeTermType(2 * time.Second)
if err != nil || tt != "XTERM-256COLOR" {
t.Fatalf("ProbeTermType = %q, %v", tt, err)
}
if !c.Spoke() {
t.Error("Spoke false")
}
if err := c.StartNVT(true, 2*time.Second); err != nil {
t.Fatal(err)
}
if cols, rows := c.Size(); cols != 132 || rows != 50 {
t.Errorf("Size = %d, %d", cols, rows)
}
if !c.Binary() {
t.Error("not binary")
}
c.Write([]byte{'a', IAC, 'b'})
srv.Close()
got := <-data
if !bytes.HasSuffix(got, []byte{'a', IAC, 'b'}) {
t.Errorf("client got %q", got)
}
}
func TestReadStripsCommands(t *testing.T) {
srv, cli := net.Pipe()
c := New(srv)
go func() {
// data, a NOP, an escaped IAC, CR NUL, a subnegotiation, more data
cli.Write([]byte{'h', 'i', IAC, NOP, IAC, IAC, '\r', 0, IAC, SB, OptNAWS, 0, 80, 0, 24, IAC, SE, '!'})
cli.Close()
}()
// answers to nothing are never sent, so nothing reads cli
got, err := io.ReadAll(c)
if err != nil && err != io.EOF {
t.Fatal(err)
}
if want := []byte{'h', 'i', IAC, '\r', '!'}; !bytes.Equal(got, want) {
t.Errorf("Read = %q, want %q", got, want)
}
}
func TestProbeRawClient(t *testing.T) {
srv, cli := net.Pipe()
go io.Copy(io.Discard, cli) // a client that never answers
c := New(srv)
start := time.Now()
tt, err := c.ProbeTermType(200 * time.Millisecond)
if err != nil || tt != "" || c.Spoke() {
t.Errorf("raw client: %q, %v, spoke %v", tt, err, c.Spoke())
}
if time.Since(start) > 2*time.Second {
t.Error("probe did not time out")
}
srv.Close()
}
func TestHandoff3270(t *testing.T) {
srv, cli := net.Pipe()
data := make(chan []byte, 1)
go client(cli, "IBM-3278-2-E", data)
c := New(srv)
tt, _ := c.ProbeTermType(2 * time.Second)
if !Is3270(tt) {
t.Fatalf("ttype %q", tt)
}
raw, err := c.Handoff3270(2 * time.Second)
if err != nil {
t.Fatal(err)
}
// the option is off again: go3270 can ask for it from the start
if c.him[OptTType] || c.askHim[OptTType] {
t.Error("TTYPE still on")
}
raw.Close()
}
+416
View File
@@ -0,0 +1,416 @@
// Package textui is the BBS on a character terminal: a telnet client, or a
// caller's terminal program over a modem. The server echoes and edits
// what the caller types; ANSI color and cursor movement are used only when
// the terminal has them.
package textui
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
// ErrIdle: the caller typed nothing for too long.
var ErrIdle = errors.New("idle timeout")
// Conn is what a terminal runs on: a net.Conn, or a telnet.Conn.
type Conn interface {
io.ReadWriter
SetReadDeadline(time.Time) error
}
// Term is the caller's terminal.
type Term struct {
c Conn
r *bufio.Reader
w *bufio.Writer
ANSI bool // color and cursor movement
UTF8 bool // UTF-8 both ways; otherwise 7-bit ASCII
Cols int
Rows int
Idle time.Duration // for each key
deadline time.Time // a hard limit for keys (the login's)
lastCR bool
}
// NewTerm makes a terminal on c, 80x24 plain ASCII until told otherwise.
func NewTerm(c Conn) *Term {
return &Term{c: c, r: bufio.NewReaderSize(c, 1024), w: bufio.NewWriterSize(c, 4096),
Cols: 80, Rows: 24, Idle: 10 * time.Minute}
}
// SetDeadline sets a limit for every key from now on (zero: none).
func (t *Term) SetDeadline(d time.Time) { t.deadline = d }
// Colors, for C.
const (
Reset = "0"
Bold = "1"
Red = "1;31"
Green = "1;32"
Yellow = "1;33"
Blue = "1;34"
Magenta = "1;35"
Cyan = "1;36"
White = "1;37"
Dim = "0;37"
)
// C wraps s in a color, on an ANSI terminal.
func (t *Term) C(color, s string) string {
if !t.ANSI {
return s
}
return "\x1b[" + color + "m" + s + "\x1b[0m"
}
// Print writes s: \n as CR LF, and on an ASCII terminal anything else as ?.
// Our own escape sequences (from C) pass; text from users never has them
// (bbs.Clean took them out).
func (t *Term) Print(s string) {
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
i += size
switch {
case r == '\n':
t.w.WriteString("\r\n")
case r < 0x80:
t.w.WriteByte(byte(r))
case t.UTF8 && r != utf8.RuneError:
t.w.WriteRune(r)
default:
t.w.WriteByte('?')
}
}
}
// Printf prints a formatted string.
func (t *Term) Printf(format string, a ...any) { t.Print(fmt.Sprintf(format, a...)) }
// Println prints s and a new line.
func (t *Term) Println(s string) { t.Print(s + "\n") }
// Flush sends what is printed.
func (t *Term) Flush() error { return t.w.Flush() }
// Clear clears the screen (a blank line on a plain terminal).
func (t *Term) Clear() {
if t.ANSI {
t.w.WriteString("\x1b[2J\x1b[H")
} else {
t.w.WriteString("\r\n")
}
}
// readRune reads one key: a rune, with arrow keys and other escape
// sequences dropped and CR LF taken as one CR.
func (t *Term) readRune() (rune, error) {
if err := t.Flush(); err != nil {
return 0, err
}
for {
d := time.Now().Add(t.Idle)
if !t.deadline.IsZero() && t.deadline.Before(d) {
d = t.deadline
}
t.c.SetReadDeadline(d)
r, err := t.next()
t.c.SetReadDeadline(time.Time{})
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
return 0, ErrIdle
}
return 0, err
}
if r == '\n' && t.lastCR {
t.lastCR = false
continue
}
t.lastCR = r == '\r'
if r == 0x1b {
if err := t.skipEscape(); err != nil {
return 0, err
}
continue
}
return r, nil
}
}
func (t *Term) next() (rune, error) {
if t.UTF8 {
r, _, err := t.r.ReadRune()
return r, err
}
b, err := t.r.ReadByte()
if b >= 0x80 {
return utf8.RuneError, err
}
return rune(b), err
}
// skipEscape drops the rest of an escape sequence (ESC [ ... final, or
// ESC O x), waiting briefly: a lone ESC is dropped by itself.
func (t *Term) skipEscape() error {
t.c.SetReadDeadline(time.Now().Add(300 * time.Millisecond))
defer t.c.SetReadDeadline(time.Time{})
b, err := t.r.ReadByte()
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
return nil
}
return err
}
switch b {
case '[':
for i := 0; i < 16; i++ {
b, err := t.r.ReadByte()
if err != nil {
return nil
}
if b >= 0x40 && b <= 0x7e {
return nil
}
}
case 'O':
t.r.ReadByte()
default:
t.r.UnreadByte()
}
return nil
}
// Key reads one key, upper-cased; Enter is '\r'.
func (t *Term) Key() (rune, error) {
for {
r, err := t.readRune()
if err != nil {
return 0, err
}
if r == '\n' {
r = '\r'
}
if r == '\r' || unicode.IsPrint(r) {
return unicode.ToUpper(r), nil
}
}
}
// LineOpts are ReadLine's options.
type LineOpts struct {
Max int // runes, at most
Mask bool // echo * (passwords)
Initial string // already typed
Wrap bool // at Max, a word being typed goes to the next line (Carry)
}
// Line is a line read: the text, and the word that wrapped to the next.
type Line struct {
Text string
Carry string
}
// ReadLine reads a line, echoing and editing it: backspace or delete
// erase, ^U erases the line, ^W the last word.
func (t *Term) ReadLine(o LineOpts) (Line, error) {
if o.Max <= 0 {
o.Max = 79
}
buf := []rune(o.Initial)
if len(buf) > o.Max {
buf = buf[:o.Max]
}
t.Print(string(buf))
echo := func(r rune) {
if o.Mask {
t.Print("*")
} else {
t.Print(string(r))
}
}
erase := func(n int) {
for i := 0; i < n; i++ {
t.w.WriteString("\b \b")
}
}
for {
r, err := t.readRune()
if err != nil {
return Line{}, err
}
switch {
case r == '\r' || r == '\n':
t.Print("\n")
return Line{Text: string(buf)}, nil
case r == 8 || r == 0x7f:
if len(buf) > 0 {
buf = buf[:len(buf)-1]
erase(1)
}
case r == 0x15: // ^U
erase(len(buf))
buf = buf[:0]
case r == 0x17: // ^W
n := len(buf)
for n > 0 && buf[n-1] == ' ' {
n--
}
for n > 0 && buf[n-1] != ' ' {
n--
}
erase(len(buf) - n)
buf = buf[:n]
case r == '\t':
if len(buf) < o.Max {
buf = append(buf, ' ')
echo(' ')
}
case r == utf8.RuneError || !unicode.IsPrint(r):
// nothing
case len(buf) < o.Max:
buf = append(buf, r)
echo(r)
case o.Wrap:
// the line is full: the word being typed goes on the next
if r == ' ' {
t.Print("\n")
return Line{Text: string(buf)}, nil
}
cut := len(buf)
for cut > 0 && buf[cut-1] != ' ' {
cut--
}
if cut == 0 || len(buf)-cut > o.Max/2 {
cut = len(buf) // one long word: break it
}
carry := string(buf[cut:]) + string(r)
erase(len(buf) - cut)
t.Print("\n")
return Line{Text: strings.TrimRight(string(buf[:cut]), " "), Carry: carry}, nil
}
}
}
// Input prints a prompt and reads a line of at most max runes.
func (t *Term) Input(prompt string, max int) (string, error) {
t.Print(prompt)
l, err := t.ReadLine(LineOpts{Max: max})
return strings.TrimSpace(l.Text), err
}
// Password prints a prompt and reads a masked line.
func (t *Term) Password(prompt string) (string, error) {
t.Print(prompt)
l, err := t.ReadLine(LineOpts{Max: 72, Mask: true})
return l.Text, err
}
// YesNo asks a question; Enter is def.
func (t *Term) YesNo(prompt string, def bool) (bool, error) {
hint := " [y/N] "
if def {
hint = " [Y/n] "
}
t.Print(prompt + hint)
for {
k, err := t.Key()
if err != nil {
return false, err
}
switch k {
case 'Y':
t.Println("Yes")
return true, nil
case 'N':
t.Println("No")
return false, nil
case '\r':
if def {
t.Println("Yes")
} else {
t.Println("No")
}
return def, nil
}
}
}
// Pause waits for a key.
func (t *Term) Pause() error {
t.Print(t.C(Dim, "[Press a key]"))
_, err := t.Key()
t.Print("\r" + strings.Repeat(" ", 13) + "\r")
return err
}
// Page shows lines a screen at a time; false if the caller quit.
func (t *Term) Page(lines []string) (bool, error) {
per := t.Rows - 2
if per < 5 {
per = 5
}
for i, l := range lines {
if i > 0 && i%per == 0 {
t.Print(t.C(Dim, "-- More -- [Enter] continue, [Q]uit "))
k, err := t.Key()
t.Print("\r" + strings.Repeat(" ", 37) + "\r")
if err != nil {
return false, err
}
if k == 'Q' {
return false, nil
}
}
t.Println(l)
}
return true, nil
}
var cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`)
// DetectANSI asks the terminal where its cursor is, after moving it as far
// down and right as it goes: an ANSI terminal answers, and the answer is
// its size. A terminal that does not answer within timeout is not ANSI.
func (t *Term) DetectANSI(timeout time.Duration) (bool, error) {
t.w.WriteString("\x1b7\x1b[999;999H\x1b[6n\x1b8")
if err := t.Flush(); err != nil {
return false, err
}
var got []byte
end := time.Now().Add(timeout)
for time.Now().Before(end) && len(got) < 64 {
t.c.SetReadDeadline(end)
b, err := t.r.ReadByte()
t.c.SetReadDeadline(time.Time{})
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
break
}
return false, err
}
got = append(got, b)
if m := cprPattern.FindSubmatch(got); m != nil {
rows, _ := strconv.Atoi(string(m[1]))
cols, _ := strconv.Atoi(string(m[2]))
if rows >= 10 && rows <= 200 {
t.Rows = rows
}
if cols >= 40 && cols <= 300 {
t.Cols = cols
}
return true, nil
}
}
// a plain terminal shows the request as text: wipe it
t.w.WriteString("\r" + strings.Repeat(" ", 20) + "\r")
return false, nil
}
+932
View File
@@ -0,0 +1,932 @@
package textui
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// Options are a session's settings from its listener.
type Options struct {
// a trusted user unknown here gets an account of its own
CreateTrusted bool
}
type session struct {
b *bbs.BBS
n *bbs.Node
t *Term
c *bbs.Caller
o Options
user *store.User
}
// errHangup: the caller logged off.
var errHangup = errors.New("logged off")
// Run is a caller's session on a text terminal, from the banner to the
// goodbye. It returns when the caller logs off or goes away.
func Run(b *bbs.BBS, n *bbs.Node, t *Term, o Options) error {
s := &session{b: b, n: n, t: t, c: n.Caller, o: o}
t.Idle = b.IdleTimeout
err := s.run()
if errors.Is(err, errHangup) {
err = nil
}
if errors.Is(err, ErrIdle) {
t.Println("\n" + t.C(Red, "Timed out. Goodbye."))
}
t.Flush()
return err
}
func (s *session) run() error {
t := s.t
t.Clear()
t.Println(t.C(Cyan, s.b.Name))
if s.b.Banner != "" {
t.Println(s.b.Banner)
}
via := "Node " + strconv.Itoa(s.n.Num) + ", " + s.c.Via
if baud := s.c.Baud(); baud != "" {
via += " at " + baud + " bit/s"
}
t.Println(t.C(Dim, via))
t.Println("")
if err := s.login(); err != nil {
return err
}
s.welcome()
return s.mainMenu()
}
// login: as vouched for, with the credentials given, or by asking
func (s *session) login() error {
t := s.t
if s.c.TrustedUser != "" {
u, err := s.n.LoginTrusted(s.c.TrustedUser, s.o.CreateTrusted)
if err == nil {
s.user = u
return nil
}
s.b.Log.Printf("node %d: upstream user %q: %v", s.n.Num, s.c.TrustedUser, err)
t.Println(t.C(Red, "You could not be logged in: "+err.Error()))
return errHangup
}
if s.c.LoginUser != "" && s.c.LoginPassword != "" {
if u, err := s.n.Login(s.c.LoginUser, s.c.LoginPassword); err == nil {
s.user = u
return nil
}
}
t.SetDeadline(time.Now().Add(s.b.LoginTimeout))
defer t.SetDeadline(time.Time{})
newHint := ""
if s.b.NewUsers {
newHint = t.C(Dim, " (or NEW)")
}
for try := 0; try < s.b.Attempts; try++ {
t.Print("Name" + newHint + ": ")
l, err := t.ReadLine(LineOpts{Max: bbs.MaxNameLen, Initial: s.c.LoginUser})
s.c.LoginUser = ""
if err != nil {
return err
}
name := strings.TrimSpace(l.Text)
if name == "" {
try--
continue
}
if strings.EqualFold(name, "new") {
if !s.b.NewUsers {
t.Println(t.C(Red, "This system takes no new users."))
continue
}
ok, err := s.register()
if err != nil || ok {
return err
}
continue
}
pw, err := t.Password("Password: ")
if err != nil {
return err
}
t.Print(t.C(Dim, "Checking..."))
t.Flush()
u, err := s.n.Login(name, pw)
t.Print("\r \r")
if err == nil {
s.user = u
return nil
}
t.Println(t.C(Red, err.Error()+"."))
if errors.Is(err, bbs.ErrThrottled) {
break
}
}
t.Println("Goodbye.")
return errHangup
}
// register: a new user's account; false if they gave up
func (s *session) register() (bool, error) {
t := s.t
t.Println("")
t.Println(t.C(Cyan, "New user"))
t.Println("Pick a name: letters, digits, spaces, dots and dashes, 2 to 24 long.")
var name string
for {
var err error
name, err = t.Input("Name (Enter to give up): ", bbs.MaxNameLen)
if err != nil || name == "" {
return false, err
}
if msg := bbs.ValidName(name); msg != "" {
t.Println(t.C(Red, msg))
continue
}
if _, err := s.b.Store.UserByName(name); err == nil {
t.Println(t.C(Red, "That name is taken."))
continue
}
break
}
var pw string
for {
var err error
pw, err = t.Password("Password (8 or more characters): ")
if err != nil {
return false, err
}
if pw == "" {
return false, nil
}
if msg := bbs.ValidPassword(pw, name); msg != "" {
t.Println(t.C(Red, msg))
continue
}
again, err := t.Password("Again: ")
if err != nil {
return false, err
}
if again != pw {
t.Println(t.C(Red, "They differ."))
continue
}
break
}
loc, err := t.Input("Where are you calling from? ", bbs.MaxLocationLen)
if err != nil {
return false, err
}
u, err := s.n.Register(name, pw, loc)
if err != nil {
t.Println(t.C(Red, err.Error()+"."))
return false, nil
}
s.user = u
return true, nil
}
func (s *session) welcome() {
t := s.t
u := s.user
t.Println("")
t.Println("Welcome, " + t.C(Yellow, u.Name) + ".")
if !u.LastLogin.IsZero() {
t.Println(t.C(Dim, "Your last call was "+u.LastLogin.Format("2006-01-02 15:04")+"."))
}
if motd := s.b.MOTDText(); motd != "" {
t.Println("")
var lines []string
for _, l := range strings.Split(strings.TrimRight(motd, "\n"), "\n") {
lines = append(lines, bbs.Clean(l, 200))
}
t.Page(lines)
}
s.user = s.n.Refresh()
}
func (s *session) mainMenu() error {
t := s.t
for {
u := s.n.Refresh()
s.user = u
s.n.Doing("Main menu")
unread, _ := s.b.Store.UnreadMail(u.ID)
mail := "E-mail"
if unread > 0 {
mail += fmt.Sprintf(" (%d new)", unread)
}
t.Println("")
t.Println(t.C(Cyan, "Main menu"))
item := func(k, label string) string {
return t.C(Yellow, "["+k+"]") + " " + bbs.Fit(label, 22)
}
t.Println(" " + item("M", "Message areas") + item("E", mail))
t.Println(" " + item("W", "Who's online") + item("U", "User list"))
t.Println(" " + item("P", "Your profile") + item("I", "System info"))
t.Println(" " + item("G", "Goodbye"))
t.Print("\nCommand: ")
k, err := t.Key()
if err != nil {
return err
}
if k != '\r' {
t.Println(string(k))
} else {
t.Println("")
}
switch k {
case 'M':
err = s.areas()
case 'E':
err = s.mail()
case 'W':
err = s.who()
case 'U':
err = s.users()
case 'P':
err = s.profile()
case 'I':
err = s.info()
case 'G', 'Q':
ok, err := t.YesNo("Log off?", true)
if err != nil {
return err
}
if ok {
t.Println("")
t.Println(s.b.Goodbye)
s.b.Log.Printf("node %d: %s logged off", s.n.Num, u.Name)
return errHangup
}
}
if err != nil {
return err
}
}
}
func date(tm time.Time) string { return tm.Format("2006-01-02 15:04") }
// areas: the list of message areas
func (s *session) areas() error {
t := s.t
for {
s.n.Doing("Message areas")
areas, err := s.b.AreasFor(s.user)
if err != nil {
return err
}
t.Println("")
t.Println(t.C(Cyan, "Message areas"))
if len(areas) == 0 {
t.Println("There are no message areas yet.")
}
var lines []string
for i, a := range areas {
newMark := ""
if a.New > 0 {
newMark = t.C(Green, fmt.Sprintf(" %d new", a.New))
}
lines = append(lines, fmt.Sprintf("%s %s %s%s", t.C(Yellow, fmt.Sprintf("%3d", i+1)),
bbs.Fit(a.Name, 20), t.C(Dim, bbs.Fit(bbs.Trunc(a.Description, 36), 36)),
fmt.Sprintf(" %4d", a.Messages)+newMark))
}
t.Page(lines)
prompt := "\nArea number, [N]ew scan, [Q]uit: "
if s.user.Sysop {
prompt = "\nArea number, [N]ew scan, [+] add area, [Q]uit: "
}
cmd, err := t.Input(prompt, 6)
if err != nil {
return err
}
switch strings.ToUpper(cmd) {
case "", "Q":
return nil
case "N":
for _, a := range areas {
if a.New > 0 {
t.Println(t.C(Cyan, "\n"+a.Name))
if quit, err := s.readNew(a.Area); err != nil || quit {
return err
}
}
}
t.Println("No more new messages.")
continue
case "+":
if s.user.Sysop {
if err := s.addArea(); err != nil {
return err
}
}
continue
}
i, err := strconv.Atoi(cmd)
if err != nil || i < 1 || i > len(areas) {
t.Println(t.C(Red, "No such area."))
continue
}
if err := s.area(areas[i-1].Area); err != nil {
return err
}
}
}
func (s *session) addArea() error {
t := s.t
name, err := t.Input("Name of the new area: ", 30)
if err != nil || name == "" {
return err
}
desc, err := t.Input("Description: ", 60)
if err != nil {
return err
}
only, err := t.YesNo("Only the sysop posts?", false)
if err != nil {
return err
}
a, err := s.b.Store.CreateArea(bbs.Clean(name, 30), bbs.Clean(desc, 60), only)
if err != nil {
t.Println(t.C(Red, err.Error()))
return nil
}
s.b.Log.Printf("node %d: %s added area %s", s.n.Num, s.user.Name, a.Name)
return nil
}
// area: one message area's menu
func (s *session) area(a *store.Area) error {
t := s.t
for {
s.n.Doing("In " + a.Name)
a2, err := s.b.Store.Area(a.ID)
if err != nil {
return err
}
a = a2
nw, _ := s.b.Store.NewCount(s.user.ID, a.ID)
t.Println("")
t.Printf("%s: %d messages, %d new\n", t.C(Cyan, a.Name), a.Messages, nw)
menu := "[R]ead new, [L]ist, [#] read a number, "
if bbs.CanPost(s.user, a) {
menu += "[P]ost, "
}
cmd, err := t.Input(menu+"[Q]uit: ", 10)
if err != nil {
return err
}
switch strings.ToUpper(cmd) {
case "", "Q":
return nil
case "R":
if _, err := s.readNew(a); err != nil {
return err
}
case "L":
if err := s.list(a); err != nil {
return err
}
case "P":
if bbs.CanPost(s.user, a) {
if err := s.post(a, "All", "", nil, 0); err != nil {
return err
}
}
default:
id, err := strconv.ParseInt(strings.TrimPrefix(cmd, "#"), 10, 64)
if err != nil {
t.Println(t.C(Red, "What?"))
continue
}
m, err := s.b.Store.Message(id)
if err != nil || m.AreaID != a.ID {
t.Println(t.C(Red, "No such message here."))
continue
}
if _, err := s.read(a, m); err != nil {
return err
}
}
}
}
// readNew reads an area from the first unread message; true if the caller
// quit.
func (s *session) readNew(a *store.Area) (bool, error) {
last, err := s.b.Store.LastRead(s.user.ID, a.ID)
if err != nil {
return false, err
}
ms, err := s.b.Store.Messages(a.ID, last, 1)
if err != nil {
return false, err
}
if len(ms) == 0 {
s.t.Println("No new messages.")
return false, nil
}
return s.read(a, ms[0])
}
// list: an area's messages, a screen at a time
func (s *session) list(a *store.Area) error {
t := s.t
var after int64
per := t.Rows - 3
if per < 5 {
per = 5
}
for {
ms, err := s.b.Store.Messages(a.ID, after, per)
if err != nil {
return err
}
if len(ms) == 0 {
t.Println("No more messages.")
return nil
}
t.Println(t.C(Dim, fmt.Sprintf("%6s %-16s %-36s %s", "#", "From", "Subject", "Date")))
for _, m := range ms {
t.Printf("%s %s %s %s\n", t.C(Yellow, fmt.Sprintf("%6d", m.ID)), bbs.Fit(m.From, 16),
bbs.Fit(m.Subject, 36), m.Created.Format("01-02 15:04"))
after = m.ID
}
cmd, err := t.Input("Number to read, Enter for more, [Q]uit: ", 10)
if err != nil {
return err
}
switch strings.ToUpper(cmd) {
case "":
continue
case "Q":
return nil
}
id, err := strconv.ParseInt(strings.TrimPrefix(cmd, "#"), 10, 64)
if err != nil {
continue
}
m, err := s.b.Store.Message(id)
if err != nil || m.AreaID != a.ID {
t.Println(t.C(Red, "No such message here."))
continue
}
_, err = s.read(a, m)
return err
}
}
func (s *session) showMessage(m *store.Message, where string) error {
t := s.t
t.Clear()
t.Println(t.C(Dim, where))
t.Println(t.C(Cyan, "From: ") + t.C(Yellow, m.From) + " " + t.C(Cyan, "To: ") + m.To)
t.Println(t.C(Cyan, "Subj: ") + t.C(White, m.Subject))
t.Println(t.C(Cyan, "Date: ") + date(m.Created))
t.Println(t.C(Dim, strings.Repeat("-", min(t.Cols-1, 79))))
_, err := t.Page(bbs.Wrap(m.Body, t.Cols-1))
return err
}
// read: messages of an area from m on; true if the caller quit
func (s *session) read(a *store.Area, m *store.Message) (bool, error) {
t := s.t
for {
s.n.Doing("Reading " + a.Name)
where := fmt.Sprintf("%s #%d", a.Name, m.ID)
if err := s.showMessage(m, where); err != nil {
return false, err
}
s.b.Store.SetLastRead(s.user.ID, a.ID, m.ID)
canDelete := s.user.Sysop || s.user.ID == m.FromID
prompt := "\n[N]ext, [P]revious, "
if bbs.CanPost(s.user, a) {
prompt += "[R]eply, "
}
prompt += "[M]ail reply, "
if canDelete {
prompt += "[D]elete, "
}
t.Print(prompt + "[Q]uit: ")
k, err := t.Key()
if err != nil {
return false, err
}
t.Println("")
switch k {
case 'N', '\r', ' ':
next, err := s.b.Store.Neighbour(a.ID, m.ID, true)
if errors.Is(err, store.ErrNotFound) {
t.Println("That was the last message.")
return false, nil
} else if err != nil {
return false, err
}
m = next
case 'P', '-':
prev, err := s.b.Store.Neighbour(a.ID, m.ID, false)
if errors.Is(err, store.ErrNotFound) {
t.Println("That is the first message.")
continue
} else if err != nil {
return false, err
}
m = prev
case 'R':
if bbs.CanPost(s.user, a) {
if err := s.post(a, m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 8), m.ID); err != nil {
return false, err
}
}
case 'M':
if err := s.compose(m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 8), 0); err != nil {
return false, err
}
case 'D':
if canDelete {
ok, err := t.YesNo("Delete this message?", false)
if err != nil {
return false, err
}
if ok {
if err := s.n.DeleteMessage(m); err != nil {
t.Println(t.C(Red, err.Error()))
}
return false, nil
}
}
case 'Q':
return true, nil
}
}
}
// edit: the line editor. lines are the start (a quote); nil if the
// caller gave up.
func (s *session) edit(lines []string) ([]string, error) {
t := s.t
width := min(t.Cols-1, bbs.MaxLineLen)
t.Println(t.C(Dim, "Type your message. On a line of its own: /S saves, /A gives up,"))
t.Println(t.C(Dim, "/L lists what you have, /D deletes the last line, /C clears all."))
t.Println(t.C(Dim, strings.Repeat("-", width)))
for _, l := range lines {
t.Println(l)
}
carry := ""
for {
if len(lines) >= bbs.MaxBodyLines {
t.Println(t.C(Red, "That is as long as a message gets."))
carry = ""
}
l, err := t.ReadLine(LineOpts{Max: width, Initial: carry, Wrap: true})
if err != nil {
return nil, err
}
carry = l.Carry
if l.Carry == "" && len(l.Text) == 2 && l.Text[0] == '/' {
switch strings.ToUpper(l.Text[1:]) {
case "S":
return lines, nil
case "A":
ok, err := t.YesNo("Give up this message?", false)
if err != nil {
return nil, err
}
if ok {
return nil, nil
}
continue
case "L":
t.Println(t.C(Dim, strings.Repeat("-", width)))
t.Page(lines)
continue
case "D":
if len(lines) > 0 {
lines = lines[:len(lines)-1]
t.Println(t.C(Dim, "(the last line is gone)"))
}
continue
case "C":
lines = nil
t.Println(t.C(Dim, "(cleared)"))
continue
}
}
if len(lines) < bbs.MaxBodyLines {
lines = append(lines, l.Text)
}
}
}
// post: a message to an area
func (s *session) post(a *store.Area, to, subject string, quote []string, replyTo int64) error {
t := s.t
s.n.Doing("Writing in " + a.Name)
t.Println("")
who, err := t.Input("To ["+to+"]: ", bbs.MaxNameLen)
if err != nil {
return err
}
if who != "" {
to = who
}
t.Print("Subject: ")
l, err := t.ReadLine(LineOpts{Max: bbs.MaxSubjectLen, Initial: subject})
if err != nil {
return err
}
subject = strings.TrimSpace(l.Text)
if subject == "" {
t.Println("No subject: given up.")
return nil
}
body, err := s.edit(quote)
if err != nil || body == nil {
return err
}
id, err := s.n.Post(a, to, subject, body, replyTo)
if err != nil {
t.Println(t.C(Red, err.Error()+"."))
return nil
}
t.Println(t.C(Green, fmt.Sprintf("Posted as #%d.", id)))
return nil
}
// compose: a private mail
func (s *session) compose(to, subject string, quote []string, replyTo int64) error {
t := s.t
s.n.Doing("Writing mail")
t.Println("")
for {
prompt := "To (user name, Enter to give up): "
if to != "" {
prompt = "To [" + to + "]: "
}
who, err := t.Input(prompt, bbs.MaxNameLen)
if err != nil {
return err
}
if who != "" {
to = who
}
if to == "" {
return nil
}
if _, err := s.b.Store.UserByName(to); err != nil {
t.Println(t.C(Red, "There is no such user."))
to = ""
continue
}
break
}
t.Print("Subject: ")
l, err := t.ReadLine(LineOpts{Max: bbs.MaxSubjectLen, Initial: subject})
if err != nil {
return err
}
subject = strings.TrimSpace(l.Text)
if subject == "" {
t.Println("No subject: given up.")
return nil
}
body, err := s.edit(quote)
if err != nil || body == nil {
return err
}
if err := s.n.SendMail(to, subject, body, replyTo); err != nil {
t.Println(t.C(Red, err.Error()+"."))
return nil
}
t.Println(t.C(Green, "Sent."))
return nil
}
// mail: the inbox
func (s *session) mail() error {
t := s.t
for {
s.n.Doing("Reading mail")
inbox, err := s.b.Store.Inbox(s.user.ID)
if err != nil {
return err
}
t.Println("")
t.Println(t.C(Cyan, "Your mail"))
if len(inbox) == 0 {
t.Println("You have no mail.")
}
var lines []string
for i, m := range inbox {
flag := " "
if !m.Read {
flag = t.C(Green, "N")
}
lines = append(lines, fmt.Sprintf("%s %s %s %s %s", t.C(Yellow, fmt.Sprintf("%3d", i+1)), flag,
bbs.Fit(m.From, 16), bbs.Fit(m.Subject, 40), m.Created.Format("01-02 15:04")))
}
t.Page(lines)
cmd, err := t.Input("\nNumber to read, [S]end, [Q]uit: ", 6)
if err != nil {
return err
}
switch strings.ToUpper(cmd) {
case "", "Q":
return nil
case "S":
if err := s.compose("", "", nil, 0); err != nil {
return err
}
continue
}
i, err := strconv.Atoi(cmd)
if err != nil || i < 1 || i > len(inbox) {
t.Println(t.C(Red, "No such mail."))
continue
}
if err := s.readMail(inbox, i-1); err != nil {
return err
}
}
}
func (s *session) readMail(inbox []*store.Message, i int) error {
t := s.t
for i < len(inbox) {
m := inbox[i]
if err := s.showMessage(m, fmt.Sprintf("Mail %d of %d", i+1, len(inbox))); err != nil {
return err
}
s.b.Store.MarkMailRead(s.user.ID, m.ID)
t.Print("\n[N]ext, [R]eply, [D]elete, [Q]uit: ")
k, err := t.Key()
if err != nil {
return err
}
t.Println("")
switch k {
case 'N', '\r', ' ':
i++
case 'R':
if err := s.compose(m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 8), m.ID); err != nil {
return err
}
case 'D':
if err := s.b.Store.DeleteMail(s.user.ID, m.ID); err != nil {
return err
}
t.Println("Deleted.")
return nil
case 'Q':
return nil
}
}
t.Println("No more mail.")
return nil
}
func (s *session) who() error {
t := s.t
t.Println("")
t.Println(t.C(Cyan, "Who's online"))
t.Println(t.C(Dim, fmt.Sprintf("%4s %-20s %-16s %-6s %s", "Node", "User", "Via", "Time", "Doing")))
for _, n := range s.b.Nodes() {
name := n.User
if name == "" {
name = "(logging in)"
}
mins := int(time.Since(n.Since).Minutes())
t.Printf("%4d %s %s %-6s %s\n", n.Num, bbs.Fit(name, 20), bbs.Fit(n.Via, 16),
fmt.Sprintf("%dm", mins), bbs.Trunc(n.Activity, t.Cols-52))
}
return t.Pause()
}
func (s *session) users() error {
t := s.t
us, err := s.b.Store.Users()
if err != nil {
return err
}
t.Println("")
lines := []string{t.C(Dim, fmt.Sprintf("%-24s %-26s %6s %s", "User", "From", "Posts", "Last call"))}
for _, u := range us {
last := "never"
if !u.LastLogin.IsZero() {
last = u.LastLogin.Format("2006-01-02")
}
name := bbs.Fit(u.Name, 24)
if u.Sysop {
name = t.C(Yellow, name)
}
lines = append(lines, fmt.Sprintf("%s %s %6d %s", name, bbs.Fit(u.Location, 26), u.Posts, last))
}
if ok, err := t.Page(lines); err != nil || !ok {
return err
}
return t.Pause()
}
func (s *session) profile() error {
t := s.t
for {
u := s.n.Refresh()
s.user = u
s.n.Doing("Profile")
t.Println("")
t.Println(t.C(Cyan, "Your profile"))
t.Printf(" Name: %s\n", u.Name)
t.Printf(" From: %s\n", u.Location)
t.Printf(" Member: since %s, %d calls, %d posts\n", u.Created.Format("2006-01-02"), u.Logins, u.Posts)
onOff := map[bool]string{true: "on", false: "off"}
t.Printf(" Terminal: %dx%d, ANSI %s, UTF-8 %s\n", t.Cols, t.Rows, onOff[t.ANSI], onOff[t.UTF8])
menu := "\n[L]ocation, [A]NSI on/off, [8]-bit UTF-8 on/off, "
if !u.External {
menu += "[P]assword, "
}
t.Print(menu + "[Q]uit: ")
k, err := t.Key()
if err != nil {
return err
}
t.Println("")
switch k {
case 'L':
loc, err := t.Input("Where are you calling from? ", bbs.MaxLocationLen)
if err != nil {
return err
}
if err := s.b.Store.SetLocation(u.ID, bbs.Clean(loc, bbs.MaxLocationLen)); err != nil {
return err
}
case 'A':
t.ANSI = !t.ANSI
case '8':
t.UTF8 = !t.UTF8
case 'P':
if u.External {
continue
}
old, err := t.Password("Your password now: ")
if err != nil {
return err
}
pw, err := t.Password("The new one: ")
if err != nil {
return err
}
again, err := t.Password("Again: ")
if err != nil {
return err
}
if pw != again {
t.Println(t.C(Red, "They differ."))
continue
}
if err := s.n.ChangePassword(old, pw); err != nil {
t.Println(t.C(Red, err.Error()+"."))
continue
}
t.Println(t.C(Green, "Changed."))
case 'Q', '\r':
return nil
}
}
}
func (s *session) info() error {
t := s.t
b := s.b
areas, _ := b.Store.Areas()
msgs := 0
for _, a := range areas {
msgs += a.Messages
}
us, _ := b.Store.Users()
t.Println("")
t.Println(t.C(Cyan, b.Name))
if b.Location != "" {
t.Println(" Location: " + b.Location)
}
t.Println(" Sysop: " + b.Sysop)
t.Printf(" Users: %d\n", len(us))
t.Printf(" Messages: %d in %d areas\n", msgs, len(areas))
t.Printf(" Nodes: %d of %d in use\n", len(b.Nodes()), b.MaxNodes)
t.Println(" Software: bbs-sec, with telnet, TN3270, rlogin and modem callers")
return t.Pause()
}
+978
View File
@@ -0,0 +1,978 @@
// Package ui3270 is the BBS on a 3270 terminal (a TN3270 client such as
// x3270, c3270, wc3270 or Vista): full screens of fields, sent and read
// whole by go3270, PF keys to move about.
package ui3270
import (
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/racingmars/go3270"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// ErrIdle: the caller pressed nothing for too long.
var ErrIdle = errors.New("idle timeout")
// errLogoff: the caller logged off.
var errLogoff = errors.New("logged off")
// maxResponse is the most a client may send for one screen; a real one
// sends a few kilobytes at most.
const maxResponse = 64 * 1024
// Options are a session's settings from its listener.
type Options struct {
// a trusted user unknown here gets an account of its own
CreateTrusted bool
}
// guard limits what is read for one screen.
type guard struct {
net.Conn
n int
}
var errTooMuch = errors.New("3270: too much data from the client")
func (g *guard) Read(p []byte) (int, error) {
if g.n >= maxResponse {
return 0, errTooMuch
}
if len(p) > maxResponse-g.n {
p = p[:maxResponse-g.n]
}
n, err := g.Conn.Read(p)
g.n += n
return n, err
}
type ui struct {
b *bbs.BBS
n *bbs.Node
g *guard
dev go3270.DevInfo
rows int
cols int
o Options
user *store.User
deadline time.Time // the login's limit
}
// Run is a caller's session on a 3270, from the logon screen to the
// goodbye. dev is go3270's NegotiateTelnet's.
func Run(b *bbs.BBS, n *bbs.Node, conn net.Conn, dev go3270.DevInfo, o Options) error {
u := &ui{b: b, n: n, g: &guard{Conn: conn}, dev: dev, o: o}
u.rows, u.cols = dev.AltDimensions()
if u.rows < 24 || u.cols < 80 {
u.rows, u.cols = 24, 80
}
err := u.run()
if errors.Is(err, errLogoff) {
err = nil
}
if errors.Is(err, ErrIdle) {
u.goodbye("Timed out. Goodbye.")
}
return err
}
func (u *ui) run() error {
if err := u.logon(); err != nil {
return err
}
return u.mainMenu()
}
// show sends a screen and returns the caller's answer, the values merged
// over vals. Clear and the PA keys show the screen again.
func (u *ui) show(scr go3270.Screen, vals map[string]string) (go3270.Response, map[string]string, error) {
crow, ccol := 1, 1
for _, f := range scr {
if f.Write {
crow, ccol = f.Row, f.Col+1
break
}
}
for {
u.g.n = 0
d := time.Now().Add(u.b.IdleTimeout)
if !u.deadline.IsZero() && u.deadline.Before(d) {
d = u.deadline
}
u.g.SetReadDeadline(d)
resp, err := go3270.ShowScreenOpts(scr, vals, u.g, go3270.ScreenOpts{
AltScreen: u.dev, Codepage: u.dev.Codepage(),
CursorRow: crow, CursorCol: ccol,
})
u.g.SetReadDeadline(time.Time{})
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
return resp, nil, ErrIdle
}
return resp, nil, err
}
switch resp.AID {
case go3270.AIDClear, go3270.AIDPA1, go3270.AIDPA2, go3270.AIDPA3:
continue
}
out := map[string]string{}
for k, v := range vals {
out[k] = v
}
for k, v := range resp.Values {
out[k] = v
}
return resp, out, nil
}
}
// goodbye shows a last screen, not waiting for an answer.
func (u *ui) goodbye(msg string) {
scr := u.frame("Goodbye", "", "")
scr = append(scr, u.text(u.rows/2, 2, msg, go3270.White, true))
u.g.SetWriteDeadline(time.Now().Add(10 * time.Second))
go3270.ShowScreenOpts(scr, nil, u.g, go3270.ScreenOpts{AltScreen: u.dev,
Codepage: u.dev.Codepage(), NoResponse: true})
u.g.SetWriteDeadline(time.Time{})
}
// text is a protected field of text at row, col (the attribute there, the
// text from col+1), cut to the screen.
func (u *ui) text(row, col int, s string, color go3270.Color, intense bool) go3270.Field {
return go3270.Field{Row: row, Col: col, Content: bbs.Trunc(s, u.cols-col-1),
Color: color, Intense: intense}
}
// input is a field to type in, width wide, and the attribute that ends it.
func (u *ui) input(row, col, width int, name string, hidden bool) []go3270.Field {
if col+1+width > u.cols-1 {
width = u.cols - 2 - col
}
return []go3270.Field{
{Row: row, Col: col, Write: true, Name: name, Hidden: hidden,
Color: go3270.Green, Highlighting: go3270.Underscore},
{Row: row, Col: col + 1 + width, Autoskip: true},
}
}
// frame is a screen's title line, message line and key line.
func (u *ui) frame(title, keys, msg string) go3270.Screen {
node := "Node " + strconv.Itoa(u.n.Num)
name := bbs.Trunc(u.b.Name, 30)
mid := u.cols - 1 - 30 - len(node)
head := bbs.Fit(name, 30) + bbs.Fit(centre(title, mid), mid) + node
return go3270.Screen{
u.text(0, 0, head, go3270.Turquoise, true),
{Row: u.rows - 2, Col: 0, Name: "msg", Content: bbs.Trunc(msg, u.cols-2),
Color: go3270.Red, Intense: true},
u.text(u.rows-1, 0, keys, go3270.Blue, false),
}
}
func centre(s string, w int) string {
s = bbs.Trunc(s, w)
return strings.Repeat(" ", (w-len([]rune(s)))/2) + s
}
// logon: the logon screen, or the upstream menu's word for who it is
func (u *ui) logon() error {
c := u.n.Caller
if c.TrustedUser != "" {
user, err := u.n.LoginTrusted(c.TrustedUser, u.o.CreateTrusted)
if err != nil {
u.goodbye("You could not be logged in: " + err.Error())
return errLogoff
}
u.user = user
return nil
}
u.deadline = time.Now().Add(u.b.LoginTimeout)
defer func() { u.deadline = time.Time{} }()
msg := ""
vals := map[string]string{}
for try := 0; try < u.b.Attempts; {
keys := "Enter=Log on PF3=Exit"
if u.b.NewUsers {
keys += " PF5=New user"
}
scr := u.frame("Logon", keys, msg)
row := 2
for _, l := range strings.Split(strings.TrimRight(u.b.Banner, "\n"), "\n") {
if row > u.rows-10 {
break
}
if l = bbs.Clean(l, u.cols-4); l != "" || row > 2 {
scr = append(scr, u.text(row, 2, l, go3270.White, false))
row++
}
}
via := "Connected by " + c.Via
if u.dev.TerminalType() != "" {
via += " as " + u.dev.TerminalType()
}
scr = append(scr, u.text(row+1, 2, via, go3270.Blue, false))
r := row + 3
scr = append(scr, u.text(r, 2, "Name ===>", go3270.Turquoise, false))
scr = append(scr, u.input(r, 16, bbs.MaxNameLen, "name", false)...)
scr = append(scr, u.text(r+1, 2, "Password ===>", go3270.Turquoise, false))
scr = append(scr, u.input(r+1, 16, 32, "password", true)...)
if u.b.NewUsers {
scr = append(scr, u.text(r+3, 2, "New here? Press PF5 to make an account.", go3270.White, false))
}
vals["password"] = ""
resp, v, err := u.show(scr, vals)
if err != nil {
return err
}
vals = map[string]string{"name": v["name"]}
switch resp.AID {
case go3270.AIDPF3:
u.goodbye(u.b.Goodbye)
return errLogoff
case go3270.AIDPF5:
if !u.b.NewUsers {
continue
}
ok, err := u.register()
if err != nil || ok {
return err
}
msg = ""
continue
case go3270.AIDEnter:
default:
continue
}
if v["name"] == "" {
msg = "Type your name and password."
continue
}
try++
user, err := u.n.Login(v["name"], v["password"])
if err == nil {
u.user = user
return nil
}
msg = err.Error() + "."
if errors.Is(err, bbs.ErrThrottled) {
break
}
}
u.goodbye(msg + " Goodbye.")
return errLogoff
}
// register: the new user screen; false if the caller went back
func (u *ui) register() (bool, error) {
msg := ""
vals := map[string]string{}
for {
scr := u.frame("New user", "Enter=Make the account PF3=Back", msg)
scr = append(scr,
u.text(2, 2, "Pick a name: letters, digits, spaces, dots and dashes, 2 to 24 long,", go3270.White, false),
u.text(3, 2, "and a password of 8 or more characters.", go3270.White, false),
u.text(5, 2, "Name ===>", go3270.Turquoise, false),
u.text(6, 2, "Password ===>", go3270.Turquoise, false),
u.text(7, 2, "Again ===>", go3270.Turquoise, false),
u.text(8, 2, "Calling from ==>", go3270.Turquoise, false))
scr = append(scr, u.input(5, 19, bbs.MaxNameLen, "name", false)...)
scr = append(scr, u.input(6, 19, 32, "pw", true)...)
scr = append(scr, u.input(7, 19, 32, "again", true)...)
scr = append(scr, u.input(8, 19, bbs.MaxLocationLen, "location", false)...)
vals["pw"], vals["again"] = "", ""
resp, v, err := u.show(scr, vals)
if err != nil {
return false, err
}
vals = map[string]string{"name": v["name"], "location": v["location"]}
switch resp.AID {
case go3270.AIDPF3:
return false, nil
case go3270.AIDEnter:
default:
continue
}
if v["pw"] != v["again"] {
msg = "The passwords differ."
continue
}
user, err := u.n.Register(v["name"], v["pw"], v["location"])
if err != nil {
msg = err.Error() + "."
continue
}
u.user = user
return true, nil
}
}
func (u *ui) mainMenu() error {
msg := ""
first := true
for {
u.user = u.n.Refresh()
u.n.Doing("Main menu")
unread, _ := u.b.Store.UnreadMail(u.user.ID)
mail := "E-mail"
if unread > 0 {
mail += fmt.Sprintf(" (%d new)", unread)
}
scr := u.frame("Main menu", "Enter=Select PF3=Log off", msg)
msg = ""
scr = append(scr, u.text(2, 2, "Welcome, "+u.user.Name+".", go3270.White, true))
if first && !u.user.LastLogin.IsZero() {
scr = append(scr, u.text(3, 2, "Your last call was "+
u.user.LastLogin.Format("2006-01-02 15:04")+".", go3270.Blue, false))
}
items := []string{"Message areas", mail, "Who's online", "User list", "Your profile", "System info"}
for i, it := range items {
scr = append(scr, u.text(5+i, 4, strconv.Itoa(i+1), go3270.Yellow, true),
u.text(5+i, 7, it, go3270.Green, false))
}
scr = append(scr, u.text(5+len(items), 4, "X", go3270.Yellow, true),
u.text(5+len(items), 7, "Log off", go3270.Green, false))
row := 6 + len(items) + 1
if motd := u.b.MOTDText(); motd != "" && first {
for _, l := range strings.Split(strings.TrimRight(motd, "\n"), "\n") {
if row >= u.rows-4 {
break
}
scr = append(scr, u.text(row, 2, bbs.Clean(l, u.cols-4), go3270.White, false))
row++
}
}
first = false
scr = append(scr, u.text(u.rows-3, 2, "Option ===>", go3270.Turquoise, false))
scr = append(scr, u.input(u.rows-3, 14, 2, "opt", false)...)
resp, v, err := u.show(scr, nil)
if err != nil {
return err
}
if resp.AID == go3270.AIDPF3 {
v["opt"] = "X"
} else if resp.AID != go3270.AIDEnter {
continue
}
switch strings.ToUpper(v["opt"]) {
case "":
case "1":
err = u.areas()
case "2":
err = u.mail()
case "3":
err = u.who()
case "4":
err = u.users()
case "5":
err = u.profile()
case "6":
err = u.info()
case "X":
u.b.Log.Printf("node %d: %s logged off", u.n.Num, u.user.Name)
u.goodbye(u.b.Goodbye)
return errLogoff
default:
msg = "Choose 1 to 6, or X."
}
if err != nil {
return err
}
}
}
// table is a page of selectable lines: an S field before each, the column
// heading above. It returns the index chosen (-1 for none), the AID, and
// the page's first index after paging keys.
type table struct {
title, heading, keys string
lines []string
top int
}
func (u *ui) perPage() int { return u.rows - 6 }
func (u *ui) pickFrom(tb *table, msg string) (int, go3270.AID, error) {
for {
per := u.perPage()
scr := u.frame(tb.title, tb.keys, msg)
msg = ""
scr = append(scr, u.text(2, 0, " "+tb.heading, go3270.Turquoise, false))
for i := 0; i < per && tb.top+i < len(tb.lines); i++ {
name := "s" + strconv.Itoa(i)
scr = append(scr, go3270.Field{Row: 3 + i, Col: 0, Write: true, Name: name,
Color: go3270.Green, Highlighting: go3270.Underscore})
scr = append(scr, u.text(3+i, 2, tb.lines[tb.top+i], go3270.Green, false))
}
if len(tb.lines) == 0 {
scr = append(scr, u.text(4, 2, "Nothing here yet.", go3270.White, false))
}
resp, v, err := u.show(scr, nil)
if err != nil {
return -1, resp.AID, err
}
switch resp.AID {
case go3270.AIDPF7:
if tb.top -= per; tb.top < 0 {
tb.top = 0
}
continue
case go3270.AIDPF8:
if tb.top+per < len(tb.lines) {
tb.top += per
} else {
msg = "That is the end."
}
continue
case go3270.AIDEnter:
for i := 0; i < per && tb.top+i < len(tb.lines); i++ {
if v["s"+strconv.Itoa(i)] != "" {
return tb.top + i, resp.AID, nil
}
}
return -1, resp.AID, nil
}
return -1, resp.AID, nil
}
}
func (u *ui) areas() error {
msg := ""
top := 0
for {
u.n.Doing("Message areas")
areas, err := u.b.AreasFor(u.user)
if err != nil {
return err
}
tb := &table{title: "Message areas", top: top,
heading: fmt.Sprintf("%-20s %-38s %6s %5s", "Area", "Description", "Msgs", "New"),
keys: "Type S by an area, Enter PF3=Back PF7=Up PF8=Down"}
for _, a := range areas {
tb.lines = append(tb.lines, fmt.Sprintf("%s %s %6d %5d", bbs.Fit(a.Name, 20),
bbs.Fit(a.Description, 38), a.Messages, a.New))
}
i, aid, err := u.pickFrom(tb, msg)
top = tb.top
msg = ""
if err != nil {
return err
}
if aid == go3270.AIDPF3 {
return nil
}
if i >= 0 {
if err := u.area(areas[i].Area); err != nil {
return err
}
}
}
}
// area: an area's messages, a page at a time
func (u *ui) area(a *store.Area) error {
starts := []int64{0}
msg := ""
for {
u.n.Doing("In " + a.Name)
last, err := u.b.Store.LastRead(u.user.ID, a.ID)
if err != nil {
return err
}
per := u.perPage()
ms, err := u.b.Store.Messages(a.ID, starts[len(starts)-1], per)
if err != nil {
return err
}
keys := "S+Enter=Read PF3=Back PF5=Read new PF7=Up PF8=Down"
if bbs.CanPost(u.user, a) {
keys += " PF6=Post"
}
tb := &table{title: a.Name, keys: keys,
heading: fmt.Sprintf("%7s %-16s %-38s %s", "#", "From", "Subject", "Date")}
for _, m := range ms {
mark := " "
if m.ID > last {
mark = "*"
}
tb.lines = append(tb.lines, fmt.Sprintf("%s%6d %s %s %s", mark, m.ID, bbs.Fit(m.From, 16),
bbs.Fit(m.Subject, 38), m.Created.Format("01-02 15:04")))
}
i, aid, err := u.pickFrom(tb, msg)
msg = ""
if err != nil {
return err
}
switch aid {
case go3270.AIDPF3:
return nil
case go3270.AIDPF5:
nm, err := u.b.Store.Messages(a.ID, last, 1)
if err != nil {
return err
}
if len(nm) == 0 {
msg = "No new messages."
continue
}
if err := u.read(a, nm[0]); err != nil {
return err
}
case go3270.AIDPF6:
if bbs.CanPost(u.user, a) {
if msg, err = u.post(a, "All", "", nil, 0); err != nil {
return err
}
}
case go3270.AIDPF7:
if len(starts) > 1 {
starts = starts[:len(starts)-1]
}
case go3270.AIDPF8:
if len(ms) == per {
starts = append(starts, ms[len(ms)-1].ID)
} else {
msg = "That is the end."
}
case go3270.AIDEnter:
if i >= 0 {
if err := u.read(a, ms[i]); err != nil {
return err
}
}
}
}
}
// messageScreen: a message's headers and a window of its body from off
func (u *ui) messageScreen(m *store.Message, title, keys, msg string, off int) (go3270.Screen, int) {
scr := u.frame(title, keys, msg)
scr = append(scr,
u.text(1, 0, "From:", go3270.Turquoise, false),
u.text(1, 6, bbs.Fit(m.From, 24), go3270.Yellow, true),
u.text(1, 32, "To:", go3270.Turquoise, false),
u.text(1, 36, bbs.Fit(m.To, 24), go3270.Green, false),
u.text(2, 0, "Subj:", go3270.Turquoise, false),
u.text(2, 6, m.Subject, go3270.White, true),
u.text(3, 0, "Date:", go3270.Turquoise, false),
u.text(3, 6, m.Created.Format("2006-01-02 15:04"), go3270.Green, false),
u.text(4, 0, strings.Repeat("-", u.cols-2), go3270.Blue, false))
// the body as written: lines of up to 79, the width of the text editor
width := min(u.cols-1, bbs.MaxLineLen)
lines := bbs.Wrap(m.Body, width)
room := u.rows - 7
for i := 0; i < room && off+i < len(lines); i++ {
scr = append(scr, u.text(5+i, 0, bbs.Clean(lines[off+i], width), go3270.Green, false))
}
return scr, len(lines)
}
// scroll moves a body window by a PF7 or PF8; the new offset, and false if
// the key was not a scroll.
func (u *ui) scroll(aid go3270.AID, off, total int) (int, bool) {
room := u.rows - 7
switch aid {
case go3270.AIDPF7:
return max(0, off-room), true
case go3270.AIDPF8:
if off+room < total {
return off + room, true
}
return off, true
}
return off, false
}
// read: messages of an area, from m on
func (u *ui) read(a *store.Area, m *store.Message) error {
off := 0
msg := ""
for {
u.n.Doing("Reading " + a.Name)
u.b.Store.SetLastRead(u.user.ID, a.ID, m.ID)
canDelete := u.user.Sysop || u.user.ID == m.FromID
keys := "PF3=Back PF7/8=Scroll PF10=Prev PF11=Next"
if bbs.CanPost(u.user, a) {
keys += " PF4=Reply"
}
keys += " PF5=Mail"
if canDelete {
keys += " PF9=Del"
}
scr, total := u.messageScreen(m, fmt.Sprintf("%s #%d", a.Name, m.ID), keys, msg, off)
msg = ""
resp, _, err := u.show(scr, nil)
if err != nil {
return err
}
if o, ok := u.scroll(resp.AID, off, total); ok {
off = o
continue
}
switch resp.AID {
case go3270.AIDPF3:
return nil
case go3270.AIDPF10, go3270.AIDPF11, go3270.AIDEnter:
next := resp.AID != go3270.AIDPF10
nm, err := u.b.Store.Neighbour(a.ID, m.ID, next)
if errors.Is(err, store.ErrNotFound) {
if next {
msg = "That was the last message."
} else {
msg = "That is the first message."
}
continue
} else if err != nil {
return err
}
m, off = nm, 0
case go3270.AIDPF4:
if bbs.CanPost(u.user, a) {
if msg, err = u.post(a, m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 6), m.ID); err != nil {
return err
}
}
case go3270.AIDPF5:
if msg, err = u.compose(m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 6), 0); err != nil {
return err
}
case go3270.AIDPF9:
if canDelete {
if err := u.n.DeleteMessage(m); err != nil {
msg = err.Error()
continue
}
return nil
}
}
}
}
// editor: To, Subject and a screen of body lines. ok is false if the
// caller gave up; check is called on PF5 and its error shown.
func (u *ui) editor(title, to, subject string, body []string,
check func(to, subject string, body []string) error) (bool, error) {
width := min(u.cols-1, bbs.MaxLineLen)
room := u.rows - 7
vals := map[string]string{"to": to, "subject": subject}
for i := 0; i < room && i < len(body); i++ {
vals["l"+strconv.Itoa(i)] = body[i]
}
msg := ""
for {
scr := u.frame(title, "PF5=Send PF3=Give up", msg)
scr = append(scr,
u.text(1, 0, "To ===>", go3270.Turquoise, false),
u.text(2, 0, "Subject ===>", go3270.Turquoise, false),
u.text(3, 0, strings.Repeat("-", u.cols-2), go3270.Blue, false))
scr = append(scr, u.input(1, 13, bbs.MaxNameLen, "to", false)...)
scr = append(scr, u.input(2, 13, bbs.MaxSubjectLen, "subject", false)...)
for i := 0; i < room; i++ {
scr = append(scr, go3270.Field{Row: 4 + i, Col: 0, Write: true,
Name: "l" + strconv.Itoa(i), KeepSpaces: true, Color: go3270.Green})
if 1+width < u.cols {
scr = append(scr, go3270.Field{Row: 4 + i, Col: 1 + width, Autoskip: true})
}
}
// the last line ends here, not at the message line
scr = append(scr, go3270.Field{Row: 4 + room, Col: 0, Autoskip: true})
resp, v, err := u.show(scr, vals)
if err != nil {
return false, err
}
vals = v
switch resp.AID {
case go3270.AIDPF3:
return false, nil
case go3270.AIDPF5:
default:
msg = "Press PF5 to send, PF3 to give up."
continue
}
var lines []string
for i := 0; i < room; i++ {
lines = append(lines, strings.TrimRight(v["l"+strconv.Itoa(i)], " \x00"))
}
if err := check(v["to"], v["subject"], lines); err != nil {
msg = err.Error() + "."
continue
}
return true, nil
}
}
// post: a message to an area; the message for the screen after
func (u *ui) post(a *store.Area, to, subject string, quote []string, replyTo int64) (string, error) {
u.n.Doing("Writing in " + a.Name)
var id int64
ok, err := u.editor("Post in "+a.Name, to, subject, quote, func(to, subject string, body []string) error {
var err error
id, err = u.n.Post(a, to, subject, body, replyTo)
return err
})
if err != nil || !ok {
return "", err
}
return fmt.Sprintf("Posted as #%d.", id), nil
}
// compose: a private mail; the message for the screen after
func (u *ui) compose(to, subject string, quote []string, replyTo int64) (string, error) {
u.n.Doing("Writing mail")
ok, err := u.editor("New mail", to, subject, quote, func(to, subject string, body []string) error {
return u.n.SendMail(to, subject, body, replyTo)
})
if err != nil || !ok {
return "", err
}
return "Sent.", nil
}
func (u *ui) mail() error {
msg := ""
top := 0
for {
u.n.Doing("Reading mail")
inbox, err := u.b.Store.Inbox(u.user.ID)
if err != nil {
return err
}
tb := &table{title: "Your mail", top: top,
keys: "S+Enter=Read PF3=Back PF6=New mail PF7=Up PF8=Down",
heading: fmt.Sprintf(" %-20s %-40s %s", "From", "Subject", "Date")}
for _, m := range inbox {
mark := " "
if !m.Read {
mark = "*"
}
tb.lines = append(tb.lines, fmt.Sprintf("%s%s %s %s", mark, bbs.Fit(m.From, 20),
bbs.Fit(m.Subject, 40), m.Created.Format("01-02 15:04")))
}
i, aid, err := u.pickFrom(tb, msg)
top = tb.top
msg = ""
if err != nil {
return err
}
switch aid {
case go3270.AIDPF3:
return nil
case go3270.AIDPF6:
if msg, err = u.compose("", "", nil, 0); err != nil {
return err
}
case go3270.AIDEnter:
if i >= 0 {
if msg, err = u.readMail(inbox, i); err != nil {
return err
}
}
}
}
}
func (u *ui) readMail(inbox []*store.Message, i int) (string, error) {
off := 0
msg := ""
for {
m := inbox[i]
u.b.Store.MarkMailRead(u.user.ID, m.ID)
scr, total := u.messageScreen(m, fmt.Sprintf("Mail %d of %d", i+1, len(inbox)),
"PF3=Back PF4=Reply PF7/8=Scroll PF9=Delete PF10=Prev PF11=Next", msg, off)
msg = ""
resp, _, err := u.show(scr, nil)
if err != nil {
return "", err
}
if o, ok := u.scroll(resp.AID, off, total); ok {
off = o
continue
}
switch resp.AID {
case go3270.AIDPF3:
return "", nil
case go3270.AIDPF4:
if msg, err = u.compose(m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 6), m.ID); err != nil {
return "", err
}
case go3270.AIDPF9:
if err := u.b.Store.DeleteMail(u.user.ID, m.ID); err != nil {
return "", err
}
return "Deleted.", nil
case go3270.AIDPF10:
if i > 0 {
i, off = i-1, 0
} else {
msg = "That is the first."
}
case go3270.AIDPF11, go3270.AIDEnter:
if i+1 < len(inbox) {
i, off = i+1, 0
} else {
msg = "That was the last."
}
}
}
}
// list shows lines a page at a time until PF3
func (u *ui) list(title, heading string, lines []string) error {
top := 0
msg := ""
for {
scr := u.frame(title, "PF3=Back PF7=Up PF8=Down", msg)
msg = ""
scr = append(scr, u.text(2, 0, heading, go3270.Turquoise, false))
per := u.perPage()
for i := 0; i < per && top+i < len(lines); i++ {
scr = append(scr, u.text(3+i, 0, lines[top+i], go3270.Green, false))
}
resp, _, err := u.show(scr, nil)
if err != nil {
return err
}
switch resp.AID {
case go3270.AIDPF3, go3270.AIDEnter:
return nil
case go3270.AIDPF7:
top = max(0, top-per)
case go3270.AIDPF8:
if top+per < len(lines) {
top += per
} else {
msg = "That is the end."
}
}
}
}
func (u *ui) who() error {
u.n.Doing("Who's online")
var lines []string
for _, n := range u.b.Nodes() {
name := n.User
if name == "" {
name = "(logging in)"
}
lines = append(lines, fmt.Sprintf("%4d %s %s %5dm %s", n.Num, bbs.Fit(name, 20),
bbs.Fit(n.Via, 16), int(time.Since(n.Since).Minutes()), n.Activity))
}
return u.list("Who's online", fmt.Sprintf("%4s %-20s %-16s %6s %s", "Node", "User", "Via", "Time", "Doing"), lines)
}
func (u *ui) users() error {
u.n.Doing("User list")
us, err := u.b.Store.Users()
if err != nil {
return err
}
var lines []string
for _, x := range us {
last := "never"
if !x.LastLogin.IsZero() {
last = x.LastLogin.Format("2006-01-02")
}
mark := " "
if x.Sysop {
mark = "*"
}
lines = append(lines, fmt.Sprintf("%s%s %s %6d %s", mark, bbs.Fit(x.Name, 24),
bbs.Fit(x.Location, 26), x.Posts, last))
}
return u.list("User list", fmt.Sprintf(" %-24s %-26s %6s %s", "User", "From", "Posts", "Last call"), lines)
}
func (u *ui) profile() error {
msg := ""
for {
u.user = u.n.Refresh()
x := u.user
u.n.Doing("Profile")
scr := u.frame("Your profile", "Enter=Save PF3=Back", msg)
msg = ""
rows, cols := u.dev.AltDimensions()
cp := "default"
if c := u.dev.Codepage(); c != nil {
cp = c.ID()
}
scr = append(scr,
u.text(2, 2, "Name: "+x.Name, go3270.White, true),
u.text(3, 2, fmt.Sprintf("Member: since %s, %d calls, %d posts",
x.Created.Format("2006-01-02"), x.Logins, x.Posts), go3270.Green, false),
u.text(4, 2, fmt.Sprintf("Terminal: %s, %dx%d, code page %s",
u.dev.TerminalType(), cols, rows, cp), go3270.Green, false),
u.text(6, 2, "Calling from ===>", go3270.Turquoise, false))
scr = append(scr, u.input(6, 20, bbs.MaxLocationLen, "location", false)...)
if !x.External {
scr = append(scr,
u.text(8, 2, "To change your password:", go3270.White, false),
u.text(9, 2, "Password now ===>", go3270.Turquoise, false),
u.text(10, 2, "New password ===>", go3270.Turquoise, false),
u.text(11, 2, "Again ===>", go3270.Turquoise, false))
scr = append(scr, u.input(9, 20, 32, "old", true)...)
scr = append(scr, u.input(10, 20, 32, "new", true)...)
scr = append(scr, u.input(11, 20, 32, "again", true)...)
}
resp, v, err := u.show(scr, map[string]string{"location": x.Location})
if err != nil {
return err
}
if resp.AID == go3270.AIDPF3 {
return nil
}
if resp.AID != go3270.AIDEnter {
continue
}
loc := bbs.Clean(v["location"], bbs.MaxLocationLen)
if loc != x.Location {
if err := u.b.Store.SetLocation(x.ID, loc); err != nil {
return err
}
msg = "Saved."
}
if v["old"] != "" || v["new"] != "" {
if v["new"] != v["again"] {
msg = "The new passwords differ."
continue
}
if err := u.n.ChangePassword(v["old"], v["new"]); err != nil {
msg = err.Error() + "."
continue
}
msg = "Your password is changed."
}
}
}
func (u *ui) info() error {
b := u.b
areas, _ := b.Store.Areas()
msgs := 0
for _, a := range areas {
msgs += a.Messages
}
us, _ := b.Store.Users()
lines := []string{b.Name, ""}
if b.Location != "" {
lines = append(lines, "Location: "+b.Location)
}
lines = append(lines,
"Sysop: "+b.Sysop,
fmt.Sprintf("Users: %d", len(us)),
fmt.Sprintf("Messages: %d in %d areas", msgs, len(areas)),
fmt.Sprintf("Nodes: %d of %d in use", len(b.Nodes()), b.MaxNodes),
"Software: bbs-sec, with telnet, TN3270, rlogin and modem callers")
return u.list("System info", "", lines)
}