Add newsgroups: an NNTP server and peer syncing

Message areas given a newsgroup name are served over NNTP (RFC 3977,
AUTHINFO, STARTTLS/implicit TLS) to newsreaders, and exchanged with peer
news servers: pulled by GROUP/OVER/ARTICLE, pushed by IHAVE (POST
fallback), fed by IHAVE from accept_from addresses.  Loops are stopped by
a Message-ID history and Path; BBS posts become MIME articles, incoming
articles are kept raw and shown decoded and cleaned.  bbs area newsgroup
and bbs news sync administer it.  Tested with nntplib, two peered BBSes
and INN.

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 18:51:31 +00:00
1 parent cce9bfbf9f
commit aa4fcd2c16
18 files changed
+3411 -17

No files matched your search

+97 -1
View File
@@ -54,6 +54,8 @@ What there is:
SHA-256, moved by XMODEM, YMODEM, ZMODEM or Kermit on the text BBS, by
IND$FILE on a 3270, or by FTP (FTPS); deleted by their uploader or the
sysop
- newsgroups: message areas given a newsgroup name are served by NNTP to
newsreaders and exchanged with other news servers (INN and the like)
- new users sign themselves up (or not: `new_users = no`)
- SQLite storage, one file
@@ -374,6 +376,83 @@ graphics (see PCOMM's *3270 Emulator User's Reference*, "Host Graphics"). The f
[3270 Data Stream Programmer's Reference, GA23-0059-07](https://bitsavers.org/pdf/ibm/3174/GA23-0059-07_3270_Data_Stream_Programmers_Reference_199206.pdf)
and Greg Price's [3270 Graphics](https://www.prycroft6.com.au/misc/3270grfx.html).
## Newsgroups and NNTP
A message area becomes a newsgroup when it is given a newsgroup name. Its
messages are then articles: newsreaders (Thunderbird, slrn, tin, Pan) read
and post them through the BBS's NNTP server, and peer news servers swap
them with it, so a message posted from a modem shows up on INN and a reply
from Usenet-style readers shows up on the 3270.
```
bbs area newsgroup General bbs.general
bbs area newsgroup General - ; no longer a newsgroup
bbs news sync ; sync with every peer now
bbs news sync upstream ; or one
```
```
; bbs.conf
[news]
hostname = news.example.org ; this site in Path and Message-IDs
organization = D-Modem BBS
max_article = 64K
[nntp]
address = :563
tls = implicit ; or required: STARTTLS before AUTHINFO
cert_file = /etc/bbs/cert.pem
key_file = /etc/bbs/key.pem
read = anyone ; or users: log in first
post = yes
[peer upstream]
address = news.example.net:119
tls = starttls
username = bbs
password = secret
groups = bbs.*
accept_from = news.example.net ; may feed us by IHAVE
```
**The server** speaks RFC 3977 with the readers' commands (`GROUP`,
`LISTGROUP`, `ARTICLE`/`HEAD`/`BODY`/`STAT`, `NEXT`/`LAST`, `OVER`/`XOVER`,
`HDR`/`XHDR`, `LIST ACTIVE`/`NEWSGROUPS`/`OVERVIEW.FMT`, `NEWNEWS`, `POST`),
`IHAVE` for peers, `AUTHINFO USER/PASS` (RFC 4643) with the BBS's login,
failure delay and throttling, and `STARTTLS` (RFC 4642). Every message has
a Message-ID; a message posted on the BBS is made into an article (From,
Date, Path, References from the thread it replies to, MIME UTF-8 text).
An article that came from elsewhere is kept exactly as it came and shown on
the BBS as text: its poster, subject and body decoded (quoted-printable,
base64, the charset, the text part of a multipart) and cleaned like
anything else a caller writes.
**Peers** are synced every `interval` seconds, and by `bbs news sync`:
- *pull*: for each of our newsgroups the peer carries (and `groups`
matches: a wildmat, `bbs.*,!bbs.test`), the articles after the last one
fetched, by `OVER` and `ARTICLE`. The first time, only the latest
`initial` of each group.
- *push*: our articles posted since the last push (on the BBS, by a reader,
or from another peer, never back to the peer they came from), by `IHAVE`;
a server that refuses `IHAVE` to us (a reader-only account) gets `POST`.
The first time only records where to start: the history is not dumped
on a new peer.
- the peer may *feed* us by `IHAVE` from the addresses in `accept_from`;
nobody else may use `IHAVE`.
An article is taken once (a history of Message-IDs, also of those refused),
never if this site is in its Path already (so two peers that both carry a
group do not loop), and stored in the first of its newsgroups carried here;
this site's name goes at the head of its Path. It was tried against INN
2.7 both ways: pushing to it, pulling from it, and innxmit feeding the BBS.
What is not done: control messages (cancel, newgroup, rmgroup) are refused,
not acted on, and deleting a message on the BBS does not cancel it
elsewhere; a crossposted article lives in one area here; there is no
`NEWGROUPS` (newsgroups are made by the sysop) and no streaming
(`CHECK`/`TAKETHIS`), which suits a BBS's volume.
## Security
- Passwords are bcrypt (cost 12); unknown users take as long to refuse as
@@ -399,6 +478,15 @@ and Greg Price's [3270 Graphics](https://www.prycroft6.com.au/misc/3270grfx.html
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.
- News: a reader's article is posted as its user whatever its From says,
with the BBS's own Message-ID, Date and Path; only the headers a reader
may choose (Subject, References, the body) are kept. `IHAVE` is taken
only from a peer's `accept_from` addresses, and peers' articles are
checked (the headers RFC 5536 requires, sizes of the article, its
headers and lines) and cleaned before a caller sees them. `tls =
required` refuses `AUTHINFO` before `STARTTLS`; `no` and `optional` make
`bbs check` warn. Commands, lines and articles are limited, and so are
clients at once and from one address.
- The log has logins, failures, posts and mail sent (never passwords or
message text).
@@ -414,6 +502,8 @@ and Greg Price's [3270 Graphics](https://www.prycroft6.com.au/misc/3270grfx.html
| `internal/sixel` | the sixel encoder |
| `internal/files` | file areas' storage: names, uploads, limits |
| `internal/ftp` | the FTP server: the file areas as a file system |
| `internal/news` | articles: parsing, checking, making, decoding; wildmats |
| `internal/nntp` | the NNTP server and the peers' client |
| `internal/xfer` | XMODEM, YMODEM, ZMODEM and Kermit, both ways |
| `internal/logo` | the logo: a PNG, or the name in a pixel font |
| `internal/bbs` | the BBS itself: nodes, logins, new users, posting, cleaning text |
@@ -440,4 +530,10 @@ access, TLS required and explicit TLS, the size limit, the per-address
limit), telnet terminals with and without sixel, the sixel encoder checked by
decoding its output with ImageMagick (when installed), and TN3270
clients that report programmed symbols (the logo is loaded and
shown), vector graphics (the logo is drawn) or neither (nothing is sent).
shown), vector graphics (the logo is drawn) or neither (nothing is sent),
articles (parsing, limits, decoding, wildmats), the NNTP server with
Python's nntplib as a newsreader (login, reading, overview, posting), its
refusals (posting without a login, AUTHINFO before STARTTLS, forged
headers, control messages, oversized articles, IHAVE from a stranger), two
BBSes peered both ways, and IHAVE. With `BBS_TEST_INN=host:port` it also
syncs with a running INN.
+45
View File
@@ -142,3 +142,48 @@ address = 127.0.0.1:2513
;idle_timeout = 300
; the address users are told, in the file areas
;advertise = bbs.example.org:2121
; Newsgroups: a message area with a newsgroup name (bbs area newsgroup
; General bbs.general) is a newsgroup, served by NNTP to newsreaders and
; kept in step with peer news servers. [news] names this site in Path and
; Message-IDs; it defaults to the machine's name
;[news]
;hostname = news.example.org
;domain = news.example.org
;organization = D-Modem BBS
; the largest article taken (from readers and peers)
;max_article = 64K
; The NNTP server. Without this section there is none (peers still sync)
;[nntp]
;address = :1119
; no, optional (STARTTLS), required (no AUTHINFO before STARTTLS), implicit
; (TLS from the first byte, NNTPS: usually port 563)
;tls = required
;cert_file = /etc/bbs/cert.pem
;key_file = /etc/bbs/key.pem
; read = anyone, or users: AUTHINFO first. post = yes: logged-in users post
;read = anyone
;post = yes
;max_clients = 32
;max_per_ip = 8
;idle_timeout = 600
; A peer news server, one section each. pull: its new articles in our
; newsgroups are fetched (GROUP, OVER, ARTICLE); push: our new articles are
; offered (IHAVE, or POST if it refuses IHAVE). accept_from: the addresses
; it may send us articles from by IHAVE (nothing else may)
;[peer upstream]
;address = news.example.net:119
;tls = starttls
;ca_file = /etc/bbs/peer-ca.pem
;username = bbs
;password = secret
;groups = bbs.*,!bbs.test
;pull = yes
;push = yes
;interval = 600
;max_per_run = 1000
; on first contact, how many of each group's latest articles to fetch
;initial = 100
;accept_from = news.example.net
+86
View File
@@ -10,6 +10,8 @@
// bbs [-config FILE] area add NAME [DESCRIPTION] [-sysop-only]
// bbs [-config FILE] area del NAME
// bbs [-config FILE] area list
// bbs [-config FILE] area newsgroup AREA GROUP|-
// bbs [-config FILE] news sync [PEER]
// bbs [-config FILE] filearea add NAME [DESCRIPTION] [-sysop-upload]
// bbs [-config FILE] filearea del|list [NAME]
// bbs [-config FILE] file add AREA PATH [DESCRIPTION] [-as NAME]
@@ -37,6 +39,8 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/files"
"github.com/Neo-Desktop/bbs-sec/internal/ftp"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/nntp"
"github.com/Neo-Desktop/bbs-sec/internal/server"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
@@ -52,6 +56,8 @@ func usage() {
bbs [-config FILE] area add NAME [DESCRIPTION] [-sysop-only]
bbs [-config FILE] area del NAME
bbs [-config FILE] area list
bbs [-config FILE] area newsgroup AREA GROUP|- (- : not a newsgroup)
bbs [-config FILE] news sync [PEER] exchange articles with peers now
bbs [-config FILE] filearea add NAME [DESCRIPTION] [-sysop-upload]
bbs [-config FILE] filearea del NAME
bbs [-config FILE] filearea list
@@ -101,6 +107,14 @@ func main() {
if cfg.FTP != nil {
fmt.Printf("ftp: %s, tls %s\n", cfg.FTP.Address, cfg.FTP.TLS)
}
fmt.Printf("news: %s\n", cfg.News.PathHost)
if cfg.NNTP != nil {
fmt.Printf("nntp: %s, tls %s\n", cfg.NNTP.Address, cfg.NNTP.TLS)
}
for _, p := range cfg.Peers {
fmt.Printf("[peer %s] %s, groups %s, pull %v, push %v, every %v\n", p.Name, p.Address,
p.Groups, p.Pull, p.Push, p.Interval)
}
fmt.Println("configuration OK")
case "init":
st := open(cfg)
@@ -124,6 +138,8 @@ func main() {
userCmd(cfg, args)
case "area":
areaCmd(cfg, args)
case "news":
newsCmd(cfg, args)
case "filearea":
fileAreaCmd(cfg, args)
case "file":
@@ -178,12 +194,28 @@ func serve(cfg *server.Config) int {
st := open(cfg)
defer st.Close()
b := bbs.New(cfg.Settings, st, lg)
b.News = cfg.News
if b.Files, err = files.Open(st, cfg.FilesDir, cfg.MaxFileSize, cfg.UploadQuota); err != nil {
lg.Printf("files: %v", err)
return 1
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
svc := &nntp.Service{B: b, MaxArticle: int(cfg.MaxArticle)}
if cfg.NNTP != nil {
ns, err := nntp.NewServer(svc, *cfg.NNTP, cfg.Peers)
if err != nil {
lg.Printf("%v", err)
return 1
}
go func() {
if err := ns.Run(ctx); err != nil {
lg.Printf("%v", err)
stop()
}
}()
}
svc.RunPeers(ctx, cfg.Peers)
if cfg.FTP != nil {
fs, err := ftp.New(b, *cfg.FTP)
if err != nil {
@@ -351,6 +383,9 @@ func areaCmd(cfg *server.Config, args []string) {
if a.SysopOnly {
only = " (sysop posts only)"
}
if a.Newsgroup != "" {
only += " [" + a.Newsgroup + "]"
}
fmt.Printf("%-20s %5d messages %s%s\n", a.Name, a.Messages, a.Description, only)
}
case "add":
@@ -366,6 +401,28 @@ func areaCmd(cfg *server.Config, args []string) {
fatal(err)
}
fmt.Println("added", a.Name)
case "newsgroup":
if len(words) != 3 {
usage()
}
a, err := st.AreaByName(words[1])
if err != nil {
fatal(fmt.Errorf("%s: %w", words[1], err))
}
group := words[2]
if group == "-" {
group = ""
} else if !news.ValidGroup(group) {
fatal(errors.New("a newsgroup name is lower case words with dots: bbs.general"))
}
if err := st.SetNewsgroup(a.ID, group); err != nil {
fatal(err)
}
if group == "" {
fmt.Println(a.Name, "is no longer a newsgroup")
} else {
fmt.Println(a.Name, "is", group)
}
case "del":
if len(words) != 2 {
usage()
@@ -507,3 +564,32 @@ func firstSysop(st *store.Store) *store.User {
fatal(errors.New("there is no sysop: bbs user add NAME -sysop"))
return nil
}
func newsCmd(cfg *server.Config, args []string) {
words, _ := split(args)
if len(words) == 0 || words[0] != "sync" || len(words) > 2 {
usage()
}
st := open(cfg)
defer st.Close()
lg := log.New(os.Stderr, "bbs: ", log.LstdFlags)
b := bbs.New(cfg.Settings, st, lg)
b.News = cfg.News
svc := &nntp.Service{B: b, MaxArticle: int(cfg.MaxArticle)}
n := 0
for _, p := range cfg.Peers {
if len(words) == 2 && p.Name != words[1] {
continue
}
n++
pushed, pulled, err := svc.Sync(p)
fmt.Printf("%s: %d sent, %d taken", p.Name, pushed, pulled)
if err != nil {
fmt.Printf(": %v", err)
}
fmt.Println()
}
if n == 0 {
fatal(errors.New("no such peer"))
}
}
+1 -1
View File
@@ -12,6 +12,7 @@ require (
golang.org/x/crypto v0.31.0
golang.org/x/image v0.23.0
golang.org/x/term v0.27.0
golang.org/x/text v0.28.0
modernc.org/sqlite v1.33.1
)
@@ -25,7 +26,6 @@ require (
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.40.0 // indirect
golang.org/x/text 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
+3
View File
@@ -99,6 +99,8 @@ type BBS struct {
Log *log.Logger
// FTPAddress is where users are told to fetch files ("": no FTP)
FTPAddress string
// News is how articles made here are signed (newsgroup areas)
News NewsSettings
mu sync.Mutex
nodes map[int]*Node
@@ -406,6 +408,7 @@ func (n *Node) Post(a *store.Area, to, subject string, body []string, replyTo in
if m.Body == "" {
return 0, errors.New("the message is empty")
}
n.b.MakeArticle(u, a, m)
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)
+62
View File
@@ -0,0 +1,62 @@
package bbs
import (
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// NewsSettings are what articles made here say of the system.
type NewsSettings struct {
PathHost string // this site in Path headers
Domain string // of Message-IDs and posters' addresses
Organization string
}
// localPart is a user name as an address's local part: what is not a
// letter, digit or one of ._- becomes a dot.
func localPart(name string) string {
out := strings.Map(func(r rune) rune {
if r < 0x80 && (r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("._-", r)) {
return r
}
return '.'
}, name)
out = strings.Trim(out, ".")
for strings.Contains(out, "..") {
out = strings.ReplaceAll(out, "..", ".")
}
if out == "" {
out = "user"
}
return strings.ToLower(out)
}
// MakeArticle makes m (by u, in newsgroup area a) an article: its
// Message-ID and its raw form, with References to what it answers.
func (b *BBS) MakeArticle(u *store.User, a *store.Area, m *store.Message) {
ns := b.News
if a.Newsgroup == "" || ns.PathHost == "" {
return
}
var refs []string
if m.ReplyTo > 0 {
if parent, err := b.Store.Message(m.ReplyTo); err == nil && parent.MessageID != "" {
if raw, err := b.Store.Raw(parent.ID); err == nil {
if pa, err := news.Parse(raw, len(raw)); err == nil {
refs = strings.Fields(pa.Get("References"))
}
}
refs = append(refs, parent.MessageID)
if len(refs) > 10 {
refs = append(refs[:1], refs[len(refs)-9:]...)
}
}
}
m.MessageID = news.NewMessageID(ns.Domain)
art := news.New(news.Local{Name: u.Name, Address: localPart(u.Name) + "@" + ns.Domain,
Group: a.Newsgroup, Subject: m.Subject, Body: m.Body, References: refs,
MessageID: m.MessageID, PathHost: ns.PathHost, Organization: ns.Organization})
m.Raw = art.Bytes()
}
+434
View File
@@ -0,0 +1,434 @@
// Package news is Usenet articles (RFC 5536, on RFC 5322): reading one
// that came in, checking it, making one of a BBS message, and what the
// BBS shows of one.
package news
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/mail"
"regexp"
"strings"
"time"
"unicode/utf8"
"golang.org/x/text/encoding/htmlindex"
)
// Limits on articles.
const (
MaxHeaderFields = 200
MaxHeaderBytes = 32 * 1024
MaxLineBytes = 4096 // longer than RFC 5322's 998, for what is out there
)
// Field is a header field.
type Field struct {
Name string
Value string // unfolded
}
// Article is an article: its header, in order, and its body (CRLF lines).
type Article struct {
Header []Field
Body []byte
}
// Errors of articles.
var (
ErrMalformed = errors.New("malformed article")
ErrTooLarge = errors.New("article too large")
)
// Parse reads an article: header, empty line, body; lines may end in CRLF
// or LF. The body is kept as it is, with CRLF line ends.
func Parse(raw []byte, max int) (*Article, error) {
if len(raw) > max {
return nil, ErrTooLarge
}
a := &Article{}
rest := raw
var cur *Field
hdrBytes := 0
for {
i := bytes.IndexByte(rest, '\n')
var line []byte
if i < 0 {
line, rest = rest, nil
} else {
line, rest = rest[:i], rest[i+1:]
}
line = bytes.TrimSuffix(line, []byte("\r"))
if len(line) > MaxLineBytes {
return nil, fmt.Errorf("%w: header line too long", ErrMalformed)
}
if hdrBytes += len(line); hdrBytes > MaxHeaderBytes {
return nil, fmt.Errorf("%w: header too long", ErrMalformed)
}
if len(line) == 0 {
break
}
if line[0] == ' ' || line[0] == '\t' {
if cur == nil {
return nil, fmt.Errorf("%w: continuation before a field", ErrMalformed)
}
cur.Value += " " + strings.TrimSpace(string(line))
continue
}
name, value, ok := bytes.Cut(line, []byte(":"))
if !ok || len(name) == 0 || bytes.ContainsAny(name, " \t") {
return nil, fmt.Errorf("%w: bad header line", ErrMalformed)
}
if len(a.Header) >= MaxHeaderFields {
return nil, fmt.Errorf("%w: too many header fields", ErrMalformed)
}
a.Header = append(a.Header, Field{Name: string(name), Value: strings.TrimSpace(string(value))})
cur = &a.Header[len(a.Header)-1]
if rest == nil {
break
}
}
// the body, with CRLF line ends
var b bytes.Buffer
for len(rest) > 0 {
i := bytes.IndexByte(rest, '\n')
var line []byte
if i < 0 {
line, rest = rest, nil
} else {
line, rest = rest[:i], rest[i+1:]
}
b.Write(bytes.TrimSuffix(line, []byte("\r")))
b.WriteString("\r\n")
}
a.Body = b.Bytes()
return a, nil
}
// Get is the first field of that name (any case), "" if none.
func (a *Article) Get(name string) string {
for _, f := range a.Header {
if strings.EqualFold(f.Name, name) {
return f.Value
}
}
return ""
}
// Set replaces the first field of that name, or adds it.
func (a *Article) Set(name, value string) {
for i, f := range a.Header {
if strings.EqualFold(f.Name, name) {
a.Header[i].Value = value
return
}
}
a.Header = append(a.Header, Field{name, value})
}
// Bytes is the article as it is sent and kept: CRLF lines.
func (a *Article) Bytes() []byte {
var b bytes.Buffer
for _, f := range a.Header {
b.WriteString(f.Name + ": " + f.Value + "\r\n")
}
b.WriteString("\r\n")
b.Write(a.Body)
return b.Bytes()
}
// HeaderBytes is the header alone (for HEAD).
func (a *Article) HeaderBytes() []byte {
var b bytes.Buffer
for _, f := range a.Header {
b.WriteString(f.Name + ": " + f.Value + "\r\n")
}
return b.Bytes()
}
var msgidPattern = regexp.MustCompile(`^<[\x21-\x3b\x3d\x3f-\x7e]+@[\x21-\x3b\x3d\x3f-\x7e]+>$`)
// ValidMessageID checks a Message-ID: <left@right>, printable, no spaces,
// at most 250 characters.
func ValidMessageID(id string) bool {
return len(id) <= 250 && msgidPattern.MatchString(id)
}
var groupPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9+_-]*(\.[a-z0-9][a-z0-9+_-]*)+$`)
// ValidGroup checks a newsgroup name: lower case components with dots,
// at least two, at most 80 characters.
func ValidGroup(name string) bool {
return len(name) <= 80 && groupPattern.MatchString(name)
}
// NewMessageID makes a Message-ID at domain.
func NewMessageID(domain string) string {
var r [9]byte
rand.Read(r[:])
return fmt.Sprintf("<%s.%s@%s>", strings.ToLower(base32(time.Now().UnixNano())), hex.EncodeToString(r[:]), domain)
}
func base32(n int64) string {
const digits = "0123456789abcdefghijklmnopqrstuv"
var b []byte
for n > 0 {
b = append([]byte{digits[n%32]}, b...)
n /= 32
}
return string(b)
}
// Groups splits a Newsgroups field.
func Groups(field string) []string {
var out []string
for _, g := range strings.Split(field, ",") {
if g = strings.TrimSpace(g); g != "" {
out = append(out, g)
}
}
return out
}
// Path elements of an article, first (newest) first.
func Path(a *Article) []string {
var out []string
for _, p := range strings.Split(a.Get("Path"), "!") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// Check checks an article that came in: the fields RFC 5536 wants, a good
// Message-ID (and, if id is given, the same), no control messages.
func Check(a *Article, id string) error {
for _, f := range []string{"From", "Newsgroups", "Subject", "Message-ID", "Date"} {
if a.Get(f) == "" {
return fmt.Errorf("%w: no %s", ErrMalformed, f)
}
}
mid := a.Get("Message-ID")
if !ValidMessageID(mid) {
return fmt.Errorf("%w: bad Message-ID", ErrMalformed)
}
if id != "" && id != mid {
return fmt.Errorf("%w: Message-ID %s, offered as %s", ErrMalformed, mid, id)
}
if _, err := mail.ParseDate(a.Get("Date")); err != nil {
return fmt.Errorf("%w: bad Date", ErrMalformed)
}
if a.Get("Control") != "" || strings.HasPrefix(strings.ToLower(a.Get("Subject")), "cmsg ") {
return fmt.Errorf("%w: control messages are not taken", ErrMalformed)
}
for _, g := range Groups(a.Get("Newsgroups")) {
if !ValidGroup(g) {
return fmt.Errorf("%w: bad newsgroup %q", ErrMalformed, g)
}
}
return nil
}
// Local is what a local article is made of.
type Local struct {
Name string // the poster's name
Address string // and address
Group string
Subject string
Body string // lines separated by \n
References []string
MessageID string
PathHost string
Organization string
}
// New makes an article of a BBS message.
func New(l Local) *Article {
a := &Article{}
from := (&mail.Address{Name: l.Name, Address: l.Address}).String()
a.Header = []Field{
{"Path", l.PathHost + "!not-for-mail"},
{"From", from},
{"Newsgroups", l.Group},
{"Subject", mime.QEncoding.Encode("utf-8", l.Subject)},
{"Date", time.Now().UTC().Format(time.RFC1123Z)},
{"Message-ID", l.MessageID},
}
if len(l.References) > 0 {
a.Header = append(a.Header, Field{"References", strings.Join(l.References, " ")})
}
if l.Organization != "" {
a.Header = append(a.Header, Field{"Organization", mime.QEncoding.Encode("utf-8", l.Organization)})
}
a.Header = append(a.Header,
Field{"MIME-Version", "1.0"},
Field{"Content-Type", "text/plain; charset=UTF-8"},
Field{"Content-Transfer-Encoding", "8bit"},
Field{"User-Agent", "bbs-sec"})
var b bytes.Buffer
for _, line := range strings.Split(strings.TrimRight(l.Body, "\n"), "\n") {
b.WriteString(strings.TrimRight(line, "\r") + "\r\n")
}
a.Body = b.Bytes()
return a
}
var decoder = &mime.WordDecoder{CharsetReader: charsetReader}
func charsetReader(charset string, r io.Reader) (io.Reader, error) {
switch strings.ToLower(charset) {
case "utf-8", "us-ascii", "ascii", "":
return r, nil
}
enc, err := htmlindex.Get(charset)
if err != nil {
return nil, err
}
return enc.NewDecoder().Reader(r), nil
}
// decodeWords undoes RFC 2047 encoded words, as best it can.
func decodeWords(s string) string {
if out, err := decoder.DecodeHeader(s); err == nil {
return out
}
return s
}
// Poster is who wrote it, for showing: the name, else the address.
func Poster(a *Article) string {
from := a.Get("From")
if addr, err := (&mail.AddressParser{WordDecoder: decoder}).Parse(from); err == nil {
if addr.Name != "" {
return addr.Name
}
return addr.Address
}
return decodeWords(from)
}
// Subject is the subject, decoded.
func Subject(a *Article) string { return decodeWords(a.Get("Subject")) }
// Text is the body as text: transfer encoding undone, in UTF-8, the first
// text/plain part of a multipart article.
func Text(a *Article) string {
ct := a.Get("Content-Type")
if ct == "" {
ct = "text/plain"
}
return text(ct, a.Get("Content-Transfer-Encoding"), a.Body, 0)
}
func text(ctype, cte string, body []byte, depth int) string {
media, params, err := mime.ParseMediaType(ctype)
if err != nil {
media, params = "text/plain", map[string]string{}
}
if strings.HasPrefix(media, "multipart/") && depth < 3 {
mr := multipart.NewReader(bytes.NewReader(body), params["boundary"])
for {
p, err := mr.NextRawPart()
if err != nil {
return "[a MIME message without a text part]"
}
pct := p.Header.Get("Content-Type")
if pct == "" {
pct = "text/plain"
}
if m, _, _ := mime.ParseMediaType(pct); m == "text/plain" || strings.HasPrefix(m, "multipart/") {
data, _ := io.ReadAll(io.LimitReader(p, int64(len(body))))
return text(pct, p.Header.Get("Content-Transfer-Encoding"), data, depth+1)
}
}
}
if media != "text/plain" {
return fmt.Sprintf("[a %s message: read it with a newsreader]", media)
}
var r io.Reader = bytes.NewReader(body)
switch strings.ToLower(strings.TrimSpace(cte)) {
case "quoted-printable":
r = quotedprintable.NewReader(r)
case "base64":
r = base64.NewDecoder(base64.StdEncoding, &stripNL{r: r})
}
if cr, err := charsetReader(params["charset"], r); err == nil {
r = cr
}
data, _ := io.ReadAll(io.LimitReader(r, 1<<20))
s := strings.ReplaceAll(string(data), "\r\n", "\n")
if !utf8.ValidString(s) {
s = strings.ToValidUTF8(s, "?")
}
return s
}
// stripNL drops line ends, for base64.
type stripNL struct{ r io.Reader }
func (s *stripNL) Read(p []byte) (int, error) {
n, err := s.r.Read(p)
j := 0
for _, c := range p[:n] {
if c != '\r' && c != '\n' {
p[j] = c
j++
}
}
return j, err
}
// Wildmat matches a name against an RFC 3977 wildmat: patterns separated
// by commas, * and ? wild, a leading ! excluding; the last that matches
// decides.
func Wildmat(pattern, name string) bool {
match := false
for _, p := range strings.Split(pattern, ",") {
p = strings.TrimSpace(p)
neg := strings.HasPrefix(p, "!")
if neg {
p = p[1:]
}
if glob(p, name) {
match = !neg
}
}
return match
}
// glob matches * and ?, without the exponential cost of a pattern such
// as *a*a*a*a*b: one backtrack point, the last star.
func glob(p, s string) bool {
pr, sr := []rune(p), []rune(s)
pi, si := 0, 0
star, mark := -1, 0
for si < len(sr) {
switch {
case pi < len(pr) && (pr[pi] == '?' || pr[pi] == sr[si]):
pi++
si++
case pi < len(pr) && pr[pi] == '*':
star, mark = pi, si
pi++
case star >= 0:
pi = star + 1
mark++
si = mark
default:
return false
}
}
for pi < len(pr) && pr[pi] == '*' {
pi++
}
return pi == len(pr)
}
+137
View File
@@ -0,0 +1,137 @@
package news
import (
"strings"
"testing"
"time"
)
const sample = "Path: a.example!b.example!not-for-mail\r\n" +
"From: =?ISO-8859-1?Q?J=F6rg_Schmidt?= <joerg@example.org>\r\n" +
"Newsgroups: bbs.general,bbs.test\r\n" +
"Subject: =?UTF-8?B?w4ljaG8=?= and\r\n" +
"\tmore\r\n" +
"Date: Sat, 10 Oct 2026 12:00:00 +0000\r\n" +
"Message-ID: <abc.123@example.org>\r\n" +
"Content-Type: text/plain; charset=iso-8859-1\r\n" +
"Content-Transfer-Encoding: quoted-printable\r\n" +
"\r\n" +
"Gr=FC=DFe\r\n" +
".dot line\r\n"
func TestParse(t *testing.T) {
a, err := Parse([]byte(sample), 1<<20)
if err != nil {
t.Fatal(err)
}
if err := Check(a, "<abc.123@example.org>"); err != nil {
t.Fatal(err)
}
if got := Poster(a); got != "Jörg Schmidt" {
t.Errorf("poster %q", got)
}
if got := Subject(a); got != "Écho and more" {
t.Errorf("subject %q", got)
}
if got := Text(a); got != "Grüße\n.dot line\n" {
t.Errorf("text %q", got)
}
if p := Path(a); len(p) != 3 || p[0] != "a.example" {
t.Errorf("path %v", p)
}
if g := Groups(a.Get("Newsgroups")); len(g) != 2 || g[1] != "bbs.test" {
t.Errorf("groups %v", g)
}
// round trip
b, _ := Parse(a.Bytes(), 1<<20)
if string(b.Bytes()) != string(a.Bytes()) {
t.Error("not stable")
}
}
func TestCheck(t *testing.T) {
base := func() *Article { a, _ := Parse([]byte(sample), 1<<20); return a }
for what, f := range map[string]func(*Article){
"no from": func(a *Article) { a.Set("From", "") },
"bad id": func(a *Article) { a.Set("Message-ID", "<no at sign>") },
"bad date": func(a *Article) { a.Set("Date", "yesterday") },
"control": func(a *Article) { a.Set("Control", "cancel <x@y>") },
"bad group": func(a *Article) { a.Set("Newsgroups", "Bad Group") },
"other msg id": func(a *Article) { a.Set("Message-ID", "<other@example.org>") },
} {
a := base()
f(a)
if Check(a, "<abc.123@example.org>") == nil {
t.Errorf("%s: taken", what)
}
}
if _, err := Parse([]byte(strings.Repeat("X-A: b\r\n", MaxHeaderFields+1)+"\r\n"), 1<<20); err == nil {
t.Error("too many fields taken")
}
if _, err := Parse([]byte(sample), 100); err == nil {
t.Error("too large taken")
}
}
func TestNew(t *testing.T) {
id := NewMessageID("bbs.example")
if !ValidMessageID(id) {
t.Fatalf("id %q", id)
}
a := New(Local{Name: "Ålice", Address: "alice@bbs.example", Group: "bbs.general",
Subject: "Grüße", Body: "line one\nline two", MessageID: id, PathHost: "bbs.example",
References: []string{"<x@y>"}})
b, err := Parse(a.Bytes(), 1<<20)
if err != nil {
t.Fatal(err)
}
if err := Check(b, id); err != nil {
t.Fatal(err)
}
if Poster(b) != "Ålice" || Subject(b) != "Grüße" || Text(b) != "line one\nline two\n" {
t.Errorf("%q %q %q", Poster(b), Subject(b), Text(b))
}
if b.Get("Path") != "bbs.example!not-for-mail" || b.Get("References") != "<x@y>" {
t.Errorf("path %q refs %q", b.Get("Path"), b.Get("References"))
}
if _, err := time.Parse(time.RFC1123Z, b.Get("Date")); err != nil {
t.Error(err)
}
}
func TestMultipart(t *testing.T) {
raw := "From: x@y.z\r\nNewsgroups: a.b\r\nSubject: s\r\nDate: Sat, 10 Oct 2026 12:00:00 +0000\r\n" +
"Message-ID: <m@y.z>\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=XX\r\n\r\n" +
"--XX\r\nContent-Type: text/html\r\n\r\n<b>no</b>\r\n--XX\r\nContent-Type: text/plain; charset=utf-8\r\n" +
"Content-Transfer-Encoding: base64\r\n\r\naGVsbG8g\r\nd29ybGQ=\r\n--XX--\r\n"
a, err := Parse([]byte(raw), 1<<20)
if err != nil {
t.Fatal(err)
}
if got := Text(a); got != "hello world" {
t.Errorf("text %q", got)
}
}
func TestWildmat(t *testing.T) {
cases := []struct {
p, s string
ok bool
}{
{"*", "bbs.general", true},
{"bbs.*", "bbs.general", true},
{"bbs.*,!bbs.test", "bbs.test", false},
{"bbs.*,!bbs.test", "bbs.tests", true},
{"comp.?ang.go", "comp.lang.go", true},
{"alt.*", "bbs.x", false},
{"*a*a*a*a*a*a*a*a*a*a*b", strings.Repeat("a", 80), false},
}
for _, c := range cases {
if Wildmat(c.p, c.s) != c.ok {
t.Errorf("%q %q", c.p, c.s)
}
}
if !ValidGroup("bbs.general") || ValidGroup("general") || ValidGroup("BBS.General") || ValidGroup("a..b") {
t.Error("ValidGroup")
}
}
+65
View File
@@ -0,0 +1,65 @@
package nntp
import (
"os"
"strings"
"testing"
"time"
)
// with INN (BBS_TEST_INN=host:port, bbs.general there, this host a peer
// of it): our article goes to INN by IHAVE, one posted at INN comes back
// by pull, and INN serves ours to readers
func TestINN(t *testing.T) {
addr := os.Getenv("BBS_TEST_INN")
if addr == "" {
t.Skip("BBS_TEST_INN not set")
}
a := newSite(t, "news.bbs.test", ServerSettings{Post: true}, nil)
inn := &Peer{Name: "inn", Address: addr, TLS: "no", Groups: "bbs.general", Push: true, Pull: true,
MaxPerRun: 100, Initial: 0}
if _, _, err := a.svc.Sync(inn); err != nil { // starting points
t.Fatal(err)
}
ours := a.post(t, "alice", "To INN", "Sent from the BBS by IHAVE.\n.dot", 0)
pushed, _, err := a.svc.Sync(inn)
if err != nil || pushed != 1 {
t.Fatalf("push: %d, %v\n%s", pushed, err, a.log)
}
// a newsreader at INN reads ours and posts its own
cv := dialConv(t, addr)
cv.send("MODE READER")
cv.expect("20")
cv.send("ARTICLE " + ours.MessageID)
cv.expect("220")
text := cv.block()
if !strings.Contains(text, "Sent from the BBS by IHAVE.") || !strings.Contains(text, "news.bbs.test!not-for-mail") {
t.Fatalf("at INN:\n%s", text)
}
cv.send("POST")
cv.expect("340")
subject := "From INN " + time.Now().Format("150405.000")
cv.send("From: Inn User <user@inn.example.test>\r\nNewsgroups: bbs.general\r\nSubject: " + subject +
"\r\n\r\nPosted at INN.\r\n.")
cv.expect("240")
cv.send("QUIT")
_, pulled, err := a.svc.Sync(inn)
if err != nil || pulled < 1 {
t.Fatalf("pull: %d, %v\n%s", pulled, err, a.log)
}
ms, _ := a.b.Store.Messages(a.area.ID, 0, 100)
found := false
for _, m := range ms {
if m.Subject == subject && m.From == "Inn User" && m.Origin == "inn" {
found = true
}
if m.Subject == "To INN" && m.Origin != "" {
t.Errorf("our own came back: %+v", m)
}
}
if !found {
t.Errorf("INN's article not pulled; have %d", len(ms))
}
}
+402
View File
@@ -0,0 +1,402 @@
package nntp
import (
"bufio"
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
func init() { store.BcryptCost = 4 }
type site struct {
b *bbs.BBS
svc *Service
addr string
area *store.Area
log *bytes.Buffer
}
func freeAddr(t *testing.T) string {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
return ln.Addr().String()
}
func selfSigned(t *testing.T, dir string) (string, string) {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "news"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}}
der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
kd, _ := x509.MarshalECPrivateKey(key)
c, k := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
os.WriteFile(c, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0600)
os.WriteFile(k, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kd}), 0600)
return c, k
}
// newSite runs a BBS's news server, with users alice and sysop and an
// area General as bbs.general.
func newSite(t *testing.T, host string, set ServerSettings, peers []*Peer) *site {
t.Helper()
dir := t.TempDir()
st, err := store.Open(filepath.Join(dir, "bbs.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
st.CreateUser("alice", "alicepass1", "", false)
st.CreateUser("sysop", "sysoppass1", "", true)
a, _ := st.CreateArea("General", "Talk", false)
st.SetNewsgroup(a.ID, "bbs.general")
area, _ := st.Area(a.ID)
s := bbs.Defaults()
s.Name = host
s.FailDelay = 0
var logbuf bytes.Buffer
b := bbs.New(s, st, log.New(&logbuf, "", 0))
b.News = bbs.NewsSettings{PathHost: host, Domain: host}
svc := &Service{B: b, MaxArticle: 64 * 1024}
set.Address = freeAddr(t)
if set.TLS == "" {
set.TLS = TLSNo
}
if set.TLS != TLSNo {
set.CertFile, set.KeyFile = selfSigned(t, dir)
}
if set.IdleTimeout == 0 {
set.IdleTimeout = time.Minute
}
srv, err := NewServer(svc, set, peers)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { srv.Run(ctx); close(done) }()
t.Cleanup(func() {
cancel()
<-done
if t.Failed() {
t.Logf("%s log:\n%s", host, logbuf.String())
}
})
for i := 0; ; i++ {
if c, err := net.Dial("tcp", set.Address); err == nil {
c.Close()
break
}
if i > 100 {
t.Fatal("never listened")
}
time.Sleep(20 * time.Millisecond)
}
return &site{b: b, svc: svc, addr: set.Address, area: area, log: &logbuf}
}
// post posts a message as a BBS user would.
func (s *site) post(t *testing.T, user, subject, body string, replyTo int64) *store.Message {
t.Helper()
u, err := s.b.Store.UserByName(user)
if err != nil {
t.Fatal(err)
}
node, err := s.b.Enter(&bbs.Caller{Via: "test"}, nil)
if err != nil {
t.Fatal(err)
}
defer node.Leave()
node.SetUser(u)
id, err := node.Post(s.area, "All", subject, strings.Split(body, "\n"), replyTo)
if err != nil {
t.Fatal(err)
}
m, _ := s.b.Store.Message(id)
return m
}
// conv is a raw NNTP conversation.
type conv struct {
t *testing.T
c net.Conn
r *bufio.Reader
}
func dialConv(t *testing.T, addr string) *conv {
c, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { c.Close() })
cv := &conv{t: t, c: c, r: bufio.NewReader(c)}
cv.expect("20")
return cv
}
func (cv *conv) expect(prefix string) string {
cv.t.Helper()
cv.c.SetReadDeadline(time.Now().Add(5 * time.Second))
line, err := cv.r.ReadString('\n')
if err != nil {
cv.t.Fatalf("waiting for %s: %v", prefix, err)
}
if !strings.HasPrefix(line, prefix) {
cv.t.Fatalf("got %q, want %s...", line, prefix)
}
return strings.TrimSpace(line)
}
func (cv *conv) send(s string) { fmt.Fprintf(cv.c, "%s\r\n", s) }
func (cv *conv) block() string {
var b strings.Builder
for {
line, err := cv.r.ReadString('\n')
if err != nil {
cv.t.Fatal(err)
}
if line == ".\r\n" {
return b.String()
}
b.WriteString(line)
}
}
// Python's nntplib, a newsreader of someone else's making, reads, posts and
// follows a thread
func TestNewsreader(t *testing.T) {
if exec.Command("python3", "-c", "import nntplib").Run() != nil {
t.Skip("no nntplib")
}
s := newSite(t, "news.a.test", ServerSettings{Post: true, ReadUsers: true}, nil)
first := s.post(t, "sysop", "Welcome", "Hello from the BBS.\n.a line with a dot", 0)
host, port, _ := net.SplitHostPort(s.addr)
script := fmt.Sprintf(`
import nntplib, io, sys
s = nntplib.NNTP(%q, %s, readermode=True, usenetrc=False)
caps = s.getcapabilities()
assert 'OVER' in caps and 'POST' in caps, caps
try:
s.group('bbs.general')
raise SystemExit('read without login')
except nntplib.NNTPTemporaryError as e:
assert str(e).startswith('480'), e
s.login('alice', 'alicepass1')
resp, count, first, last, name = s.group('bbs.general')
assert count == 1 and name == 'bbs.general', (count, name)
resp, info = s.article(first)
lines = [l.decode() for l in info.lines]
assert 'Hello from the BBS.' in lines and '.a line with a dot' in lines, lines
resp, overviews = s.over((first, last))
num, ov = overviews[0]
assert ov['subject'] == 'Welcome' and ov['message-id'] == %q, ov
art = b"From: someone@else.example\r\nNewsgroups: bbs.general\r\nSubject: Re: Welcome\r\nReferences: %s\r\n\r\nA reply from a newsreader.\r\n..and a dot\r\n"
s.post(io.BytesIO(art))
resp, count, first, last, name = s.group('bbs.general')
assert count == 2, count
resp, info = s.article(last)
text = b"\n".join(info.lines).decode()
assert 'From: "alice" <alice@news.a.test>' in text, text
assert 'References: %s' in text, text
assert '.and a dot' in text, text
resp, groups = s.list()
assert groups[0].group == 'bbs.general', groups
resp, hdrs = s.xhdr('subject', '%%d-%%d' %% (first, last))
assert [h[1] for h in hdrs] == ['Welcome', 'Re: Welcome'], hdrs
s.quit()
print('ok')
`, host, port, first.MessageID, first.MessageID, first.MessageID)
out, err := exec.Command("python3", "-W", "ignore", "-c", script).CombinedOutput()
if err != nil || !strings.Contains(string(out), "ok") {
t.Fatalf("nntplib: %v\n%s", err, out)
}
// the reply is a BBS message, answering the first
ms, _ := s.b.Store.Messages(s.area.ID, 0, 10)
if len(ms) != 2 || ms[1].From != "alice" || ms[1].ReplyTo != first.ID {
t.Errorf("messages %+v", ms[1])
}
}
// two BBSs keep bbs.general in step: B pushes to A by IHAVE, A pulls
// from B, nothing comes back round
func TestPeering(t *testing.T) {
a := newSite(t, "news.a.test", ServerSettings{Post: true}, []*Peer{
{Name: "b", AcceptFrom: []net.IP{net.ParseIP("127.0.0.1")}}})
b := newSite(t, "news.b.test", ServerSettings{Post: true}, []*Peer{
{Name: "a", AcceptFrom: []net.IP{net.ParseIP("127.0.0.1")}}})
toA := &Peer{Name: "a", Address: a.addr, TLS: "no", Groups: "bbs.*", Push: true, Pull: true,
MaxPerRun: 100, Initial: 10}
toB := &Peer{Name: "b", Address: b.addr, TLS: "no", Groups: "bbs.*", Push: true, Pull: true,
MaxPerRun: 100, Initial: 10}
// first runs set the starting points
if _, _, err := b.svc.Sync(toA); err != nil {
t.Fatal(err)
}
if _, _, err := a.svc.Sync(toB); err != nil {
t.Fatal(err)
}
mb := b.post(t, "alice", "From B", "Written at B.", 0)
pushed, _, err := b.svc.Sync(toA) // B offers it to A
if err != nil || pushed != 1 {
t.Fatalf("push: %d, %v", pushed, err)
}
ma, err := a.b.Store.MessageByMessageID(mb.MessageID)
if err != nil || ma.Origin != "b" || ma.Subject != "From B" {
t.Fatalf("at A: %+v, %v", ma, err)
}
raw, _ := a.b.Store.Raw(ma.ID)
if !bytes.Contains(raw, []byte("Path: news.a.test!news.b.test!not-for-mail")) {
t.Errorf("path:\n%s", raw)
}
// A's own post, and a reply to B's
a.post(t, "sysop", "From A", "Written at A.", 0)
reply := a.post(t, "alice", "Re: From B", "A reply at A.", ma.ID)
// B pulls from A
_, pulled, err := b.svc.Sync(toA)
if err != nil || pulled != 2 {
t.Fatalf("pull: %d, %v", pulled, err)
}
rb, err := b.b.Store.MessageByMessageID(reply.MessageID)
if err != nil || rb.ReplyTo != mb.ID {
t.Errorf("reply at B: %+v, %v", rb, err)
}
// nothing goes back: A gets nothing new from B
pushed, pulled, err = a.svc.Sync(toB)
if err != nil {
t.Fatal(err)
}
if pushed != 0 || pulled != 0 {
t.Errorf("round again: %d pushed, %d pulled", pushed, pulled)
}
n := 0
ms, _ := a.b.Store.Messages(a.area.ID, 0, 100)
n = len(ms)
if n != 3 {
t.Errorf("A has %d messages", n)
}
}
func TestAccess(t *testing.T) {
s := newSite(t, "news.a.test", ServerSettings{Post: true, TLS: TLSRequired}, nil)
cv := dialConv(t, s.addr)
cv.send("IHAVE <x@y.z>")
cv.expect("502")
cv.send("POST")
cv.expect("480")
cv.send("AUTHINFO USER alice")
cv.expect("483")
cv.send("GROUP bbs.general")
cv.expect("211 0")
cv.send("ARTICLE <nope@x.y>")
cv.expect("430")
cv.send("ARTICLE 1")
cv.expect("423")
cv.send(strings.Repeat("X", 600))
cv.expect("501")
cv.send("FROB")
cv.expect("500")
// STARTTLS, then the login and a post
cv.send("STARTTLS")
cv.expect("382")
tc := tls.Client(cv.c, &tls.Config{InsecureSkipVerify: true})
if err := tc.Handshake(); err != nil {
t.Fatal(err)
}
cv.c, cv.r = tc, bufio.NewReader(tc)
cv.send("AUTHINFO USER alice")
cv.expect("381")
cv.send("AUTHINFO PASS wrong")
cv.expect("481")
cv.send("AUTHINFO USER alice")
cv.expect("381")
cv.send("AUTHINFO PASS alicepass1")
cv.expect("281")
cv.send("POST")
cv.expect("340")
cv.send("From: forged@elsewhere.example\r\nNewsgroups: bbs.general\r\nSubject: hi\r\nPath: forged!path\r\n\r\nbody\r\n.")
id := strings.Fields(cv.expect("240"))[3]
m, err := s.b.Store.MessageByMessageID(id)
if err != nil || m.From != "alice" {
t.Fatalf("posted %+v, %v", m, err)
}
raw, _ := s.b.Store.Raw(m.ID)
if bytes.Contains(raw, []byte("forged")) {
t.Errorf("forged headers kept:\n%s", raw)
}
// a control message, and one too large
cv.send("POST")
cv.expect("340")
cv.send("Newsgroups: bbs.general\r\nSubject: x\r\nControl: cancel <a@b>\r\n\r\nx\r\n.")
cv.expect("441")
cv.send("POST")
cv.expect("340")
cv.send("Newsgroups: bbs.general\r\nSubject: big\r\n\r\n" + strings.Repeat("x\r\n", 40000) + ".")
cv.expect("441")
cv.send("QUIT")
cv.expect("205")
}
func TestIHAVE(t *testing.T) {
s := newSite(t, "news.a.test", ServerSettings{}, []*Peer{
{Name: "p", AcceptFrom: []net.IP{net.ParseIP("127.0.0.1")}}})
cv := dialConv(t, s.addr)
art := func(id, path, extra string) string {
return "Path: " + path + "\r\nFrom: Bob <bob@far.example>\r\nNewsgroups: bbs.general,far.misc\r\n" +
"Subject: far away\r\nDate: Sat, 10 Oct 2026 12:00:00 +0000\r\nMessage-ID: " + id + "\r\n" + extra +
"\r\nA line.\r\n..dotted\r\n."
}
cv.send("IHAVE <1@far.example>")
cv.expect("335")
cv.send(art("<1@far.example>", "far.example!not-for-mail", ""))
cv.expect("235")
cv.send("IHAVE <1@far.example>")
cv.expect("435")
// one that has been here (our host in its Path)
cv.send("IHAVE <2@far.example>")
cv.expect("335")
cv.send(art("<2@far.example>", "far.example!news.a.test!not-for-mail", ""))
cv.expect("437")
// one for no group of ours
cv.send("IHAVE <3@far.example>")
cv.expect("335")
cv.send(strings.Replace(art("<3@far.example>", "far.example", ""), "bbs.general,far.misc", "far.misc", 1))
cv.expect("437")
// refused ones are remembered
cv.send("IHAVE <3@far.example>")
cv.expect("435")
// offered as one, is another
cv.send("IHAVE <4@far.example>")
cv.expect("335")
cv.send(art("<5@far.example>", "far.example", ""))
cv.expect("437")
m, err := s.b.Store.MessageByMessageID("<1@far.example>")
if err != nil || m.From != "Bob" || m.Origin != "p" || !strings.Contains(m.Body, ".dotted") {
t.Fatalf("%+v, %v", m, err)
}
}
+519
View File
@@ -0,0 +1,519 @@
package nntp
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// Peer is a news server this one exchanges newsgroups with ([peer NAME]).
type Peer struct {
Name string
Address string // host:port
TLS string // no, starttls, implicit
CAFile string // a CA for its certificate (else the system's)
Username string // AUTHINFO, if it wants it
Password string
Groups string // wildmat of the newsgroups exchanged
Pull bool // fetch its new articles
Push bool // offer it ours (IHAVE, or POST if it takes no IHAVE)
Interval time.Duration
// addresses it connects from: it may IHAVE (and read)
AcceptFrom []net.IP
// the most articles a run takes or gives, each way
MaxPerRun int
// articles fetched of a group the first time (its newest)
Initial int
}
const peerTimeout = 60 * time.Second
// client is a connection to a peer.
type client struct {
c net.Conn
r *bufio.Reader
w *bufio.Writer
}
func (p *Peer) tlsConfig() (*tls.Config, error) {
host, _, _ := net.SplitHostPort(p.Address)
cfg := &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
if p.CAFile != "" {
pem, err := os.ReadFile(p.CAFile)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
return nil, errors.New("no certificates in " + p.CAFile)
}
cfg.RootCAs = pool
}
return cfg, nil
}
// dial connects, with TLS and AUTHINFO as the peer wants; reader asks for
// MODE READER (for pulling).
func (p *Peer) dial(reader bool) (*client, error) {
d := net.Dialer{Timeout: 30 * time.Second}
c, err := d.Dial("tcp", p.Address)
if err != nil {
return nil, err
}
if p.TLS == "implicit" {
cfg, err := p.tlsConfig()
if err != nil {
c.Close()
return nil, err
}
tc := tls.Client(c, cfg)
tc.SetDeadline(time.Now().Add(30 * time.Second))
if err := tc.Handshake(); err != nil {
c.Close()
return nil, err
}
tc.SetDeadline(time.Time{})
c = tc
}
cl := &client{c: c, r: bufio.NewReaderSize(c, 16384), w: bufio.NewWriter(c)}
code, msg, err := cl.response()
if err != nil {
c.Close()
return nil, err
}
if code != 200 && code != 201 {
c.Close()
return nil, fmt.Errorf("greeting: %d %s", code, msg)
}
if p.TLS == "starttls" {
if code, msg, err := cl.cmd("STARTTLS"); err != nil || code != 382 {
c.Close()
return nil, fmt.Errorf("STARTTLS: %d %s %v", code, msg, err)
}
cfg, err := p.tlsConfig()
if err != nil {
c.Close()
return nil, err
}
tc := tls.Client(c, cfg)
tc.SetDeadline(time.Now().Add(30 * time.Second))
if err := tc.Handshake(); err != nil {
c.Close()
return nil, err
}
tc.SetDeadline(time.Time{})
cl.c, cl.r, cl.w = tc, bufio.NewReaderSize(tc, 16384), bufio.NewWriter(tc)
}
if reader {
cl.cmd("MODE READER") // servers that are readers anyway may say 5xx
}
if p.Username != "" {
code, msg, err := cl.cmd("AUTHINFO USER " + p.Username)
if err == nil && code == 381 {
code, msg, err = cl.cmd("AUTHINFO PASS " + p.Password)
}
if err != nil || code != 281 {
cl.close()
return nil, fmt.Errorf("AUTHINFO: %d %s %v", code, msg, err)
}
}
return cl, nil
}
func (cl *client) close() {
cl.cmd("QUIT")
cl.c.Close()
}
func (cl *client) response() (int, string, error) {
cl.c.SetReadDeadline(time.Now().Add(peerTimeout))
defer cl.c.SetReadDeadline(time.Time{})
line, err := cl.r.ReadString('\n')
if err != nil {
return 0, "", err
}
if len(line) > 4096 {
return 0, "", errors.New("response line too long")
}
line = strings.TrimRight(line, "\r\n")
code, msg, _ := strings.Cut(line, " ")
n, err := strconv.Atoi(code)
if err != nil {
return 0, "", fmt.Errorf("bad response %q", line)
}
return n, msg, nil
}
func (cl *client) cmd(line string) (int, string, error) {
cl.c.SetWriteDeadline(time.Now().Add(peerTimeout))
if _, err := cl.w.WriteString(line + "\r\n"); err != nil {
return 0, "", err
}
if err := cl.w.Flush(); err != nil {
return 0, "", err
}
return cl.response()
}
// block reads a dot-terminated block of at most max bytes.
func (cl *client) block(max int) ([]byte, error) {
var b bytes.Buffer
tooBig := false
for {
cl.c.SetReadDeadline(time.Now().Add(peerTimeout))
line, err := cl.r.ReadBytes('\n')
cl.c.SetReadDeadline(time.Time{})
if err != nil {
return nil, err
}
if bytes.Equal(line, []byte(".\r\n")) || bytes.Equal(line, []byte(".\n")) {
if tooBig {
return nil, news.ErrTooLarge
}
return b.Bytes(), nil
}
if line[0] == '.' {
line = line[1:]
}
if b.Len()+len(line) > max {
tooBig = true
continue
}
b.Write(line)
}
}
// send sends an article, dot-stuffed and ended.
func (cl *client) send(raw []byte) (int, string, error) {
cl.c.SetWriteDeadline(time.Now().Add(peerTimeout))
for len(raw) > 0 {
i := bytes.IndexByte(raw, '\n')
var line []byte
if i < 0 {
line, raw = raw, nil
} else {
line, raw = raw[:i], raw[i+1:]
}
line = bytes.TrimSuffix(line, []byte("\r"))
if len(line) > 0 && line[0] == '.' {
cl.w.WriteByte('.')
}
cl.w.Write(line)
cl.w.WriteString("\r\n")
}
cl.w.WriteString(".\r\n")
if err := cl.w.Flush(); err != nil {
return 0, "", err
}
return cl.response()
}
// groupsFor are the local newsgroups exchanged with p.
func (s *Service) groupsFor(p *Peer) ([]*store.Area, error) {
all, err := s.B.Store.Newsgroups()
if err != nil {
return nil, err
}
var out []*store.Area
for _, a := range all {
if news.Wildmat(p.Groups, a.Newsgroup) {
out = append(out, a)
}
}
return out, nil
}
// Sync runs one exchange with a peer: ours to it, then its to us.
func (s *Service) Sync(p *Peer) (pushed, pulled int, err error) {
if p.Push {
pushed, err = s.push(p)
if err != nil {
return pushed, 0, fmt.Errorf("push: %w", err)
}
}
if p.Pull {
pulled, err = s.pull(p)
if err != nil {
return pushed, pulled, fmt.Errorf("pull: %w", err)
}
}
return pushed, pulled, nil
}
// push offers the peer what came here (from here, or other peers) since
// the last run. The first run only starts the count: the peer is not
// sent what was here before it was one.
func (s *Service) push(p *Peer) (int, error) {
st := s.B.Store
after, known, err := st.PeerPushed(p.Name)
if err != nil {
return 0, err
}
if !known {
max, err := st.MaxMessageID()
if err != nil {
return 0, err
}
return 0, st.SetPeerPushed(p.Name, max)
}
areas, err := s.groupsFor(p)
if err != nil || len(areas) == 0 {
return 0, err
}
var ids []int64
for _, a := range areas {
ids = append(ids, a.ID)
}
ms, err := st.ToPush(p.Name, after, ids, p.MaxPerRun)
if err != nil || len(ms) == 0 {
// nothing to give: still move past what was skipped
return 0, err
}
cl, err := p.dial(false)
if err != nil {
return 0, err
}
defer cl.close()
usePost := false
n := 0
for _, m := range ms {
raw, err := st.Raw(m.ID)
if err != nil || len(raw) == 0 {
continue
}
if !usePost {
code, msg, err := cl.cmd("IHAVE " + m.MessageID)
if err != nil {
return n, err
}
switch code {
case 335:
code, msg, err = cl.send(raw)
if err != nil {
return n, err
}
if code == 436 {
return n, fmt.Errorf("%s: try again later: %s", m.MessageID, msg)
}
if code == 235 {
n++
}
// 437: refused for good; on to the next
case 435:
// it has it
case 436:
return n, fmt.Errorf("IHAVE %s: try again later: %s", m.MessageID, msg)
case 480, 500, 502:
usePost = true
default:
return n, fmt.Errorf("IHAVE: %d %s", code, msg)
}
}
if usePost {
code, msg, err := cl.cmd("POST")
if err != nil {
return n, err
}
if code != 340 {
return n, fmt.Errorf("POST: %d %s", code, msg)
}
code, _, err = cl.send(raw)
if err != nil {
return n, err
}
if code == 240 {
n++
}
}
if err := st.SetPeerPushed(p.Name, m.ID); err != nil {
return n, err
}
}
return n, nil
}
// pull fetches the peer's new articles of the newsgroups exchanged, by
// article number since the last run (the newest Initial ones the first
// time).
func (s *Service) pull(p *Peer) (int, error) {
areas, err := s.groupsFor(p)
if err != nil || len(areas) == 0 {
return 0, err
}
cl, err := p.dial(true)
if err != nil {
return 0, err
}
defer cl.close()
st := s.B.Store
total := 0
for _, a := range areas {
if total >= p.MaxPerRun {
break
}
code, msg, err := cl.cmd("GROUP " + a.Newsgroup)
if err != nil {
return total, err
}
if code == 411 {
continue // not there
}
if code != 211 {
return total, fmt.Errorf("GROUP %s: %d %s", a.Newsgroup, code, msg)
}
f := strings.Fields(msg)
if len(f) < 3 {
return total, fmt.Errorf("GROUP %s: %q", a.Newsgroup, msg)
}
lo, _ := strconv.ParseInt(f[1], 10, 64)
hi, _ := strconv.ParseInt(f[2], 10, 64)
last, known, err := st.PeerLast(p.Name, a.Newsgroup)
if err != nil {
return total, err
}
if !known {
// the first time: from the newest Initial on, remembered
// even if there is nothing to take yet
last = max(hi-int64(p.Initial), lo-1, 0)
if err := st.SetPeerLast(p.Name, a.Newsgroup, last); err != nil {
return total, err
}
}
if hi < last {
last = lo - 1 // the peer renumbered
}
if hi <= last {
continue
}
to := min(hi, last+int64(p.MaxPerRun-total))
nums, err := cl.overview(last+1, to)
if err != nil {
return total, err
}
for _, item := range nums {
if item.id != "" {
if want, err := s.Wanted(item.id); err != nil {
return total, err
} else if !want {
continue
}
}
code, msg, err := cl.cmd(fmt.Sprintf("ARTICLE %d", item.n))
if err != nil {
return total, err
}
if code == 423 || code == 430 {
continue
}
if code != 220 {
return total, fmt.Errorf("ARTICLE %d: %d %s", item.n, code, msg)
}
raw, err := cl.block(s.MaxArticle)
if errors.Is(err, news.ErrTooLarge) {
if item.id != "" {
st.Remember(item.id)
}
continue
}
if err != nil {
return total, err
}
if _, err := s.Accept(raw, item.id, p.Name); err == nil {
total++
} else if !errors.Is(err, ErrHave) {
s.B.Log.Printf("nntp: peer %s: %s article %d: %v", p.Name, a.Newsgroup, item.n, err)
}
}
if err := st.SetPeerLast(p.Name, a.Newsgroup, to); err != nil {
return total, err
}
}
return total, nil
}
type overItem struct {
n int64
id string
}
// overview lists the articles from lo to hi with their Message-IDs (OVER,
// or XOVER; failing both, the numbers alone).
func (cl *client) overview(lo, hi int64) ([]overItem, error) {
for _, cmd := range []string{"OVER", "XOVER"} {
code, _, err := cl.cmd(fmt.Sprintf("%s %d-%d", cmd, lo, hi))
if err != nil {
return nil, err
}
if code == 423 || code == 420 {
return nil, nil
}
if code != 224 {
continue
}
data, err := cl.block(64 << 20)
if err != nil {
return nil, err
}
var out []overItem
for _, line := range strings.Split(string(data), "\n") {
f := strings.Split(strings.TrimRight(line, "\r"), "\t")
if len(f) < 5 {
continue
}
n, err := strconv.ParseInt(f[0], 10, 64)
if err != nil {
continue
}
id := strings.TrimSpace(f[4])
if !news.ValidMessageID(id) {
id = ""
}
out = append(out, overItem{n, id})
}
return out, nil
}
var out []overItem
for n := lo; n <= hi; n++ {
out = append(out, overItem{n: n})
}
return out, nil
}
// RunPeers syncs with each peer at its interval until ctx is done.
func (s *Service) RunPeers(ctx context.Context, peers []*Peer) {
for _, p := range peers {
if !p.Pull && !p.Push {
continue
}
go func(p *Peer) {
t := time.NewTimer(5 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
pushed, pulled, err := s.Sync(p)
if err != nil {
s.B.Log.Printf("nntp: peer %s: %v", p.Name, err)
} else if pushed+pulled > 0 {
s.B.Log.Printf("nntp: peer %s: %d sent, %d taken", p.Name, pushed, pulled)
}
t.Reset(p.Interval)
}
}(p)
}
}
+926
View File
@@ -0,0 +1,926 @@
package nntp
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// TLS modes of the server.
const (
TLSNo = "no" // none: passwords in the clear
TLSOptional = "optional" // STARTTLS offered
TLSRequired = "required" // STARTTLS before AUTHINFO and POST
TLSImplicit = "implicit" // TLS from the first byte (port 563)
)
// ServerSettings are [nntp]'s.
type ServerSettings struct {
Address string
TLS string
CertFile string
KeyFile string
ReadUsers bool // only logged-in users (and peers) read
Post bool // users may post
MaxClients int
MaxPerIP int
IdleTimeout time.Duration
}
// Server is the NNTP server.
type Server struct {
Svc *Service
Set ServerSettings
Peers []*Peer // those whose addresses may IHAVE (and read)
tlsConfig *tls.Config
mu sync.Mutex
clients int
perIP map[string]int
conns map[net.Conn]bool
}
// NewServer makes the server, loading the certificate if TLS is on.
func NewServer(svc *Service, set ServerSettings, peers []*Peer) (*Server, error) {
s := &Server{Svc: svc, Set: set, Peers: peers, perIP: map[string]int{}, conns: map[net.Conn]bool{}}
if set.TLS != TLSNo {
cert, err := tls.LoadX509KeyPair(set.CertFile, set.KeyFile)
if err != nil {
return nil, fmt.Errorf("nntp: certificate: %w", err)
}
s.tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12}
}
return s, nil
}
// Run serves until ctx is done.
func (s *Server) Run(ctx context.Context) error {
ln, err := net.Listen("tcp", s.Set.Address)
if err != nil {
return fmt.Errorf("nntp: %w", err)
}
s.Svc.B.Log.Printf("nntp: listening on %s (tls %s)", s.Set.Address, s.Set.TLS)
go func() {
<-ctx.Done()
ln.Close()
s.mu.Lock()
for c := range s.conns {
c.Close()
}
s.mu.Unlock()
}()
for {
c, err := ln.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
if errors.Is(err, net.ErrClosed) {
return nil
}
time.Sleep(100 * time.Millisecond)
continue
}
go s.serve(c)
}
}
func hostOf(a net.Addr) string {
if t, ok := a.(*net.TCPAddr); ok {
return t.IP.String()
}
return ""
}
func (s *Server) admit(c net.Conn) (string, bool) {
h := hostOf(c.RemoteAddr())
s.mu.Lock()
defer s.mu.Unlock()
if s.Set.MaxClients > 0 && s.clients >= s.Set.MaxClients {
return "400 Too many readers; try again later", false
}
if s.Set.MaxPerIP > 0 && s.perIP[h] >= s.Set.MaxPerIP {
return "400 Too many connections from your address", false
}
s.clients++
s.perIP[h]++
s.conns[c] = true
return "", true
}
func (s *Server) release(c net.Conn) {
h := hostOf(c.RemoteAddr())
s.mu.Lock()
defer s.mu.Unlock()
s.clients--
if s.perIP[h]--; s.perIP[h] <= 0 {
delete(s.perIP, h)
}
delete(s.conns, c)
}
// peerAt is the peer whose address c comes from, if any.
func (s *Server) peerAt(c net.Conn) *Peer {
ip := net.ParseIP(hostOf(c.RemoteAddr()))
for _, p := range s.Peers {
for _, a := range p.AcceptFrom {
if a.Equal(ip) {
return p
}
}
}
return nil
}
// session is a client's connection.
type session struct {
s *Server
c net.Conn
r *bufio.Reader
w *bufio.Writer
tls bool
who string
user *store.User
name string // AUTHINFO USER, waiting for PASS
peer *Peer
group *store.Area
cur int64
}
const maxLine = 512 // RFC 3977: a command line, CRLF included
func (s *Server) serve(c net.Conn) {
defer c.Close()
defer func() {
if r := recover(); r != nil {
s.Svc.B.Log.Printf("nntp: panic: %v", r)
}
}()
if msg, ok := s.admit(c); !ok {
c.SetWriteDeadline(time.Now().Add(5 * time.Second))
io.WriteString(c, msg+"\r\n")
return
}
defer s.release(c)
ss := &session{s: s, c: c, peer: s.peerAt(c), who: "nntp " + c.RemoteAddr().String()}
if s.Set.TLS == TLSImplicit {
tc := tls.Server(c, s.tlsConfig)
tc.SetDeadline(time.Now().Add(30 * time.Second))
if err := tc.Handshake(); err != nil {
return
}
tc.SetDeadline(time.Time{})
ss.c, ss.tls = tc, true
}
ss.r = bufio.NewReaderSize(ss.c, 4096)
ss.w = bufio.NewWriterSize(ss.c, 16384)
if ss.canPost() {
ss.reply(200, s.Svc.B.Name+" news server ready, posting allowed")
} else {
ss.reply(201, s.Svc.B.Name+" news server ready, no posting")
}
for {
ss.w.Flush()
line, err := ss.readLine()
if err != nil {
if errors.Is(err, errLineTooLong) {
ss.reply(501, "Command line too long")
continue
}
return
}
cmd, args := splitCommand(line)
if cmd == "QUIT" {
ss.reply(205, "Goodbye")
ss.w.Flush()
return
}
ss.command(cmd, args)
}
}
var errLineTooLong = errors.New("line too long")
func (ss *session) readLine() (string, error) {
ss.c.SetReadDeadline(time.Now().Add(ss.s.Set.IdleTimeout))
defer ss.c.SetReadDeadline(time.Time{})
var line []byte
for {
chunk, isPrefix, err := ss.r.ReadLine()
if err != nil {
return "", err
}
line = append(line, chunk...)
if len(line) > maxLine {
for isPrefix {
if _, isPrefix, err = ss.r.ReadLine(); err != nil {
return "", err
}
}
return "", errLineTooLong
}
if !isPrefix {
return string(line), nil
}
}
}
func splitCommand(line string) (string, []string) {
f := strings.Fields(line)
if len(f) == 0 {
return "", nil
}
return strings.ToUpper(f[0]), f[1:]
}
func (ss *session) reply(code int, msg string) {
fmt.Fprintf(ss.w, "%d %s\r\n", code, msg)
}
// lines sends a multi-line block, dot-stuffed and ended by ".".
func (ss *session) lines(data []byte) {
for len(data) > 0 {
i := bytes.IndexByte(data, '\n')
var line []byte
if i < 0 {
line, data = data, nil
} else {
line, data = data[:i], data[i+1:]
}
line = bytes.TrimSuffix(line, []byte("\r"))
if len(line) > 0 && line[0] == '.' {
ss.w.WriteByte('.')
}
ss.w.Write(line)
ss.w.WriteString("\r\n")
}
}
func (ss *session) end() { ss.w.WriteString(".\r\n") }
func (ss *session) canPost() bool { return ss.s.Set.Post }
// mayRead: reading needs a login, unless anyone may (peers always may)
func (ss *session) mayRead() bool {
return !ss.s.Set.ReadUsers || ss.user != nil || ss.peer != nil
}
func (ss *session) command(cmd string, args []string) {
switch cmd {
case "CAPABILITIES":
ss.capabilities()
return
case "MODE":
if len(args) == 1 && strings.EqualFold(args[0], "READER") {
if ss.canPost() {
ss.reply(200, "Posting allowed")
} else {
ss.reply(201, "Posting prohibited")
}
return
}
ss.reply(501, "Unknown MODE")
return
case "DATE":
ss.reply(111, time.Now().UTC().Format("20060102150405"))
return
case "HELP":
ss.reply(100, "Help text follows")
ss.w.WriteString("ARTICLE BODY CAPABILITIES DATE GROUP HDR HEAD HELP IHAVE LAST LIST LISTGROUP\r\n" +
"MODE NEWGROUPS NEWNEWS NEXT OVER POST QUIT STAT AUTHINFO STARTTLS\r\n")
ss.end()
return
case "STARTTLS":
ss.starttls()
return
case "AUTHINFO":
ss.authinfo(args)
return
}
if !ss.mayRead() {
ss.reply(480, "Authentication required")
return
}
switch cmd {
case "LIST":
ss.list(args)
case "GROUP":
ss.groupCmd(args, false)
case "LISTGROUP":
ss.groupCmd(args, true)
case "NEXT", "LAST":
ss.nextLast(cmd == "NEXT")
case "ARTICLE", "HEAD", "BODY", "STAT":
ss.article(cmd, args)
case "OVER", "XOVER":
ss.over(args)
case "HDR", "XHDR":
ss.hdr(args)
case "NEWGROUPS":
ss.reply(231, "List of new newsgroups follows")
ss.end()
case "NEWNEWS":
ss.newnews(args)
case "POST":
ss.post()
case "IHAVE":
ss.ihave(args)
default:
ss.reply(500, "Unknown command")
}
}
func (ss *session) capabilities() {
ss.reply(101, "Capability list:")
caps := []string{"VERSION 2", "READER", "LIST ACTIVE NEWSGROUPS OVERVIEW.FMT", "OVER", "HDR",
"NEWNEWS", "IMPLEMENTATION bbs-sec"}
if ss.canPost() {
caps = append(caps, "POST")
}
if ss.peer != nil {
caps = append(caps, "IHAVE")
}
if ss.user == nil && (ss.tls || ss.s.Set.TLS != TLSRequired) {
caps = append(caps, "AUTHINFO USER")
}
if !ss.tls && (ss.s.Set.TLS == TLSOptional || ss.s.Set.TLS == TLSRequired) {
caps = append(caps, "STARTTLS")
}
for _, c := range caps {
ss.w.WriteString(c + "\r\n")
}
ss.end()
}
func (ss *session) starttls() {
switch {
case ss.tls:
ss.reply(502, "Already using TLS")
return
case ss.s.tlsConfig == nil || ss.s.Set.TLS == TLSImplicit:
ss.reply(580, "TLS not available")
return
case ss.user != nil:
ss.reply(502, "Already authenticated")
return
}
ss.reply(382, "Continue with TLS negotiation")
ss.w.Flush()
if ss.r.Buffered() > 0 {
// nothing may come before the handshake: an injection attempt
ss.c.Close()
return
}
tc := tls.Server(ss.c, ss.s.tlsConfig)
tc.SetDeadline(time.Now().Add(30 * time.Second))
if err := tc.Handshake(); err != nil {
ss.c.Close()
return
}
tc.SetDeadline(time.Time{})
ss.c, ss.tls = tc, true
ss.r = bufio.NewReaderSize(tc, 4096)
ss.w = bufio.NewWriterSize(tc, 16384)
ss.name, ss.group, ss.cur = "", nil, 0
}
func (ss *session) authinfo(args []string) {
if len(args) < 2 {
ss.reply(501, "AUTHINFO USER name, then AUTHINFO PASS password")
return
}
if ss.user != nil {
ss.reply(502, "Already authenticated")
return
}
if !ss.tls && ss.s.Set.TLS == TLSRequired {
ss.reply(483, "Use STARTTLS first")
return
}
switch strings.ToUpper(args[0]) {
case "USER":
ss.name = strings.Join(args[1:], " ")
ss.reply(381, "Password required")
case "PASS":
if ss.name == "" {
ss.reply(482, "AUTHINFO USER first")
return
}
source := ""
if a, ok := ss.c.RemoteAddr().(*net.TCPAddr); ok && !a.IP.IsLoopback() {
source = "ip:" + a.IP.String()
}
u, err := ss.s.Svc.B.Authenticate(ss.who, source, ss.name, strings.Join(args[1:], " "))
ss.name = ""
if err != nil {
ss.reply(481, "Authentication failed")
return
}
ss.user = u
ss.s.Svc.B.Log.Printf("%s: %s logged in", ss.who, u.Name)
ss.reply(281, "Authentication accepted")
default:
ss.reply(501, "AUTHINFO USER or PASS")
}
}
// groups are the newsgroups (areas that are)
func (ss *session) groups() []*store.Area {
gs, err := ss.s.Svc.B.Store.Newsgroups()
if err != nil {
return nil
}
return gs
}
func status(a *store.Area, post bool) string {
if !post || a.SysopOnly {
return "n"
}
return "y"
}
func (ss *session) list(args []string) {
kw := "ACTIVE"
if len(args) > 0 {
kw = strings.ToUpper(args[0])
}
pattern := "*"
if len(args) > 1 {
pattern = args[1]
}
switch kw {
case "ACTIVE":
ss.reply(215, "List of newsgroups follows")
for _, a := range ss.groups() {
if news.Wildmat(pattern, a.Newsgroup) {
hi, lo := a.LastID, a.FirstID
if a.Messages == 0 {
hi, lo = 0, 1
}
fmt.Fprintf(ss.w, "%s %d %d %s\r\n", a.Newsgroup, hi, lo, status(a, ss.canPost()))
}
}
ss.end()
case "NEWSGROUPS":
ss.reply(215, "Descriptions follow")
for _, a := range ss.groups() {
if news.Wildmat(pattern, a.Newsgroup) {
fmt.Fprintf(ss.w, "%s\t%s\r\n", a.Newsgroup, oneLine(a.Description))
}
}
ss.end()
case "OVERVIEW.FMT":
ss.reply(215, "Order of fields in overview database")
ss.w.WriteString("Subject:\r\nFrom:\r\nDate:\r\nMessage-ID:\r\nReferences:\r\n:bytes\r\n:lines\r\n")
ss.end()
default:
ss.reply(503, "That LIST is not here")
}
}
func oneLine(s string) string {
return strings.Map(func(r rune) rune {
if r == '\t' || r == '\r' || r == '\n' || r == 0 {
return ' '
}
return r
}, s)
}
func (ss *session) groupCmd(args []string, list bool) {
if len(args) == 0 {
if !list || ss.group == nil {
ss.reply(412, "No newsgroup selected")
return
}
} else {
a, err := ss.s.Svc.B.Store.AreaByNewsgroup(args[0])
if err != nil {
ss.reply(411, "No such newsgroup")
return
}
ss.group = a
}
a := ss.group
ss.cur = a.FirstID
hi, lo := a.LastID, a.FirstID
if a.Messages == 0 {
hi, lo, ss.cur = 0, 1, 0
}
ss.reply(211, fmt.Sprintf("%d %d %d %s", a.Messages, lo, hi, a.Newsgroup))
if !list {
return
}
from, to := lo, hi
if len(args) > 1 {
var ok bool
if from, to, ok = parseRange(args[1], hi); !ok {
// the 211 has gone; the list is empty
from, to = 1, 0
}
}
for from <= to {
ms, err := ss.s.Svc.B.Store.Articles(a.ID, from, to, 1000)
if err != nil || len(ms) == 0 {
break
}
for _, m := range ms {
fmt.Fprintf(ss.w, "%d\r\n", m.ID)
}
from = ms[len(ms)-1].ID + 1
}
ss.end()
}
// parseRange reads "n", "n-" or "n-m".
func parseRange(r string, hi int64) (int64, int64, bool) {
a, b, dash := strings.Cut(r, "-")
lo, err := strconv.ParseInt(a, 10, 64)
if err != nil || lo < 0 {
return 0, 0, false
}
if !dash {
return lo, lo, true
}
if b == "" {
return lo, hi, true
}
up, err := strconv.ParseInt(b, 10, 64)
if err != nil {
return 0, 0, false
}
return lo, up, true
}
func (ss *session) nextLast(next bool) {
if ss.group == nil {
ss.reply(412, "No newsgroup selected")
return
}
if ss.cur == 0 {
ss.reply(420, "No current article")
return
}
m, err := ss.s.Svc.B.Store.Neighbour(ss.group.ID, ss.cur, next)
for err == nil && m.MessageID == "" {
m, err = ss.s.Svc.B.Store.Neighbour(ss.group.ID, m.ID, next)
}
if err != nil {
if next {
ss.reply(421, "No next article")
} else {
ss.reply(422, "No previous article")
}
return
}
ss.cur = m.ID
ss.reply(223, fmt.Sprintf("%d %s", m.ID, m.MessageID))
}
// selectArticle finds the article an ARTICLE-like command names: by
// Message-ID (number 0), by number in the group, or the current one.
func (ss *session) selectArticle(args []string) (*store.Message, int64, bool) {
st := ss.s.Svc.B.Store
if len(args) > 0 && strings.HasPrefix(args[0], "<") {
m, err := st.MessageByMessageID(args[0])
if err == nil {
if a, err := st.Area(m.AreaID); err == nil && a.Newsgroup != "" {
return m, 0, true
}
}
ss.reply(430, "No article with that message-id")
return nil, 0, false
}
if ss.group == nil {
ss.reply(412, "No newsgroup selected")
return nil, 0, false
}
n := ss.cur
if len(args) > 0 {
v, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
ss.reply(501, "Bad article number")
return nil, 0, false
}
n = v
} else if n == 0 {
ss.reply(420, "No current article")
return nil, 0, false
}
m, err := st.Message(n)
if err != nil || m.AreaID != ss.group.ID || m.MessageID == "" {
if len(args) == 0 {
ss.reply(420, "Current article number is invalid")
} else {
ss.reply(423, "No article with that number")
}
return nil, 0, false
}
ss.cur = n
return m, n, true
}
func (ss *session) article(cmd string, args []string) {
m, n, ok := ss.selectArticle(args)
if !ok {
return
}
head := fmt.Sprintf("%d %s", n, m.MessageID)
if cmd == "STAT" {
ss.reply(223, head)
return
}
raw, err := ss.s.Svc.B.Store.Raw(m.ID)
if err != nil {
ss.reply(403, "Cannot read the article")
return
}
a, err := news.Parse(raw, len(raw)+1)
if err != nil {
ss.reply(403, "Cannot read the article")
return
}
switch cmd {
case "ARTICLE":
ss.reply(220, head)
ss.lines(a.HeaderBytes())
ss.w.WriteString("\r\n")
ss.lines(a.Body)
case "HEAD":
ss.reply(221, head)
ss.lines(a.HeaderBytes())
case "BODY":
ss.reply(222, head)
ss.lines(a.Body)
}
ss.end()
}
// overview is an article's overview fields.
func overview(raw []byte) (map[string]string, int, int) {
a, err := news.Parse(raw, len(raw)+1)
if err != nil {
return map[string]string{}, len(raw), 0
}
f := map[string]string{}
for _, h := range []string{"Subject", "From", "Date", "Message-ID", "References", "Xref", "Newsgroups"} {
f[strings.ToLower(h)] = oneLine(a.Get(h))
}
return f, len(raw), bytes.Count(a.Body, []byte("\n"))
}
// selectRange finds the articles OVER and HDR name: one by Message-ID,
// a range of the group, or the current article. byID: numbers are 0.
func (ss *session) selectRange(args []string) ([]*store.Message, bool, bool) {
st := ss.s.Svc.B.Store
if len(args) > 0 && strings.HasPrefix(args[0], "<") {
m, err := st.MessageByMessageID(args[0])
if err != nil || m.MessageID == "" {
ss.reply(430, "No article with that message-id")
return nil, false, false
}
return []*store.Message{m}, true, true
}
if ss.group == nil {
ss.reply(412, "No newsgroup selected")
return nil, false, false
}
lo, hi := ss.cur, ss.cur
if len(args) > 0 {
var ok bool
if lo, hi, ok = parseRange(args[0], ss.group.LastID); !ok {
ss.reply(501, "Bad range")
return nil, false, false
}
} else if ss.cur == 0 {
ss.reply(420, "No current article")
return nil, false, false
}
ms, err := st.Articles(ss.group.ID, lo, hi, 10000)
if err != nil {
ss.reply(403, "Cannot read the overview")
return nil, false, false
}
if len(ms) == 0 {
ss.reply(423, "No articles in that range")
return nil, false, false
}
return ms, false, true
}
func (ss *session) over(args []string) {
ms, byID, ok := ss.selectRange(args)
if !ok {
return
}
ss.reply(224, "Overview information follows")
for _, m := range ms {
raw, _ := ss.s.Svc.B.Store.Raw(m.ID)
f, size, lines := overview(raw)
n := m.ID
if byID {
n = 0
}
fmt.Fprintf(ss.w, "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%d\r\n", n, f["subject"], f["from"], f["date"],
f["message-id"], f["references"], size, lines)
}
ss.end()
}
func (ss *session) hdr(args []string) {
if len(args) == 0 {
ss.reply(501, "HDR field [range|message-id]")
return
}
field := strings.ToLower(args[0])
ms, byID, ok := ss.selectRange(args[1:])
if !ok {
return
}
ss.reply(225, "Headers follow")
for _, m := range ms {
raw, _ := ss.s.Svc.B.Store.Raw(m.ID)
f, size, lines := overview(raw)
var v string
switch field {
case ":bytes":
v = strconv.Itoa(size)
case ":lines":
v = strconv.Itoa(lines)
default:
if a, err := news.Parse(raw, len(raw)+1); err == nil {
v = oneLine(a.Get(field))
} else {
v = f[field]
}
}
n := m.ID
if byID {
n = 0
}
fmt.Fprintf(ss.w, "%d %s\r\n", n, v)
}
ss.end()
}
func (ss *session) newnews(args []string) {
if len(args) < 3 {
ss.reply(501, "NEWNEWS wildmat date time [GMT]")
return
}
since, ok := parseDateTime(args[1], args[2])
if !ok {
ss.reply(501, "Bad date or time")
return
}
var ids []int64
for _, a := range ss.groups() {
if news.Wildmat(args[0], a.Newsgroup) {
ids = append(ids, a.ID)
}
}
list, err := ss.s.Svc.B.Store.ArticlesSince(since, ids, 100000)
if err != nil {
ss.reply(403, "Cannot list")
return
}
ss.reply(230, "List of new articles follows")
for _, id := range list {
ss.w.WriteString(id + "\r\n")
}
ss.end()
}
// parseDateTime reads NEWNEWS's yyyymmdd (or yymmdd) hhmmss, in UTC.
func parseDateTime(d, t string) (time.Time, bool) {
layout := "20060102 150405"
if len(d) == 6 {
layout = "060102 150405"
}
v, err := time.Parse(layout, d+" "+t)
return v, err == nil
}
// readArticle reads a dot-terminated article of at most max bytes; one
// too large is read to its end and refused.
func (ss *session) readArticle(max int) ([]byte, error) {
var b bytes.Buffer
tooBig := false
atStart := true // at the start of a line: where dots are stuffed
for {
ss.c.SetReadDeadline(time.Now().Add(ss.s.Set.IdleTimeout))
line, err := ss.r.ReadSlice('\n')
ss.c.SetReadDeadline(time.Time{})
if err != nil && !errors.Is(err, bufio.ErrBufferFull) {
return nil, err
}
if atStart && (bytes.Equal(line, []byte(".\r\n")) || bytes.Equal(line, []byte(".\n"))) {
if tooBig {
return nil, news.ErrTooLarge
}
return b.Bytes(), nil
}
if atStart && len(line) > 0 && line[0] == '.' {
line = line[1:]
}
atStart = err == nil // a whole line ended in LF
if b.Len()+len(line) > max {
tooBig = true
continue
}
b.Write(line)
}
}
func (ss *session) post() {
if !ss.canPost() {
ss.reply(440, "Posting not permitted")
return
}
if ss.user == nil {
ss.reply(480, "Authentication required to post")
return
}
if !ss.tls && ss.s.Set.TLS == TLSRequired {
ss.reply(483, "Use STARTTLS first")
return
}
ss.reply(340, "Send article to be posted")
ss.w.Flush()
raw, err := ss.readArticle(ss.s.Svc.MaxArticle)
if err != nil {
if errors.Is(err, news.ErrTooLarge) {
ss.reply(441, "Article too large")
return
}
ss.c.Close()
return
}
m, err := ss.s.Svc.PostLocal(raw, ss.user)
if err != nil {
ss.reply(441, "Posting failed: "+oneLine(err.Error()))
return
}
ss.s.Svc.B.Log.Printf("%s: %s posted %s", ss.who, ss.user.Name, m.MessageID)
ss.reply(240, "Article received "+m.MessageID)
}
func (ss *session) ihave(args []string) {
if ss.peer == nil {
ss.reply(502, "IHAVE is for peers")
return
}
if len(args) != 1 {
ss.reply(501, "IHAVE message-id")
return
}
id := args[0]
want, err := ss.s.Svc.Wanted(id)
if err != nil {
ss.reply(436, "Transfer not possible; try again later")
return
}
if !want {
ss.reply(435, "Article not wanted")
return
}
ss.reply(335, "Send it; end with <CR-LF>.<CR-LF>")
ss.w.Flush()
raw, err := ss.readArticle(ss.s.Svc.MaxArticle)
if err != nil {
if errors.Is(err, news.ErrTooLarge) {
ss.s.Svc.B.Store.Remember(id)
ss.reply(437, "Article too large")
return
}
ss.c.Close()
return
}
if _, err := ss.s.Svc.Accept(raw, id, ss.peer.Name); err != nil {
switch {
case errors.Is(err, ErrHave):
ss.reply(435, "Duplicate")
case errors.Is(err, news.ErrMalformed), errors.Is(err, ErrNotHere), errors.Is(err, ErrLoop),
errors.Is(err, news.ErrTooLarge):
ss.reply(437, "Rejected: "+oneLine(err.Error()))
default:
ss.s.Svc.B.Log.Printf("%s: IHAVE %s: %v", ss.who, id, err)
ss.reply(436, "Transfer failed; try again later")
}
return
}
ss.reply(235, "Article transferred OK")
}
+183
View File
@@ -0,0 +1,183 @@
// Package nntp is the BBS's news: an NNTP server (RFC 3977) for
// newsreaders and peers, and a client that keeps newsgroups in step with
// peer servers (pulling by article number, pushing by IHAVE). Newsgroups
// are the message areas that have a newsgroup name; an article is a
// message.
package nntp
import (
"errors"
"fmt"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// Results of offering an article.
var (
ErrHave = errors.New("already have it")
ErrNotHere = errors.New("no newsgroup of it is carried here")
ErrLoop = errors.New("it has been here before (Path)")
ErrRejected = errors.New("rejected")
)
// Service takes and gives articles for the server and the peers.
type Service struct {
B *bbs.BBS
MaxArticle int // bytes
}
// Wanted reports whether an article of that Message-ID would be taken (by
// its Message-ID alone: IHAVE's question).
func (s *Service) Wanted(id string) (bool, error) {
if !news.ValidMessageID(id) {
return false, nil
}
seen, err := s.B.Store.Seen(id)
return !seen, err
}
// Accept takes an article from a peer (origin: its name), offered as id
// ("" if not said): checked, stored in the first of its newsgroups carried
// here with this site at the head of its Path. A refused article is
// remembered, so it is not offered again.
func (s *Service) Accept(raw []byte, id, origin string) (*store.Message, error) {
a, err := news.Parse(raw, s.MaxArticle)
if err != nil {
if id != "" {
s.B.Store.Remember(id)
}
return nil, err
}
if err := news.Check(a, id); err != nil {
if id != "" {
s.B.Store.Remember(id)
}
return nil, err
}
mid := a.Get("Message-ID")
if seen, err := s.B.Store.Seen(mid); err != nil {
return nil, err
} else if seen {
return nil, ErrHave
}
host := s.B.News.PathHost
for _, p := range news.Path(a) {
if strings.EqualFold(p, host) {
s.B.Store.Remember(mid)
return nil, ErrLoop
}
}
var area *store.Area
for _, g := range news.Groups(a.Get("Newsgroups")) {
if ar, err := s.B.Store.AreaByNewsgroup(g); err == nil {
area = ar
break
}
}
if area == nil {
s.B.Store.Remember(mid)
return nil, ErrNotHere
}
path := a.Get("Path")
if path == "" {
path = "not-for-mail"
}
a.Set("Path", host+"!"+path)
m := s.message(a, area)
m.Origin = origin
m.Raw = a.Bytes()
if _, err := s.B.Store.Post(m); err != nil {
if errors.Is(err, store.ErrExists) {
return nil, ErrHave
}
return nil, err
}
return m, nil
}
// message is what the BBS shows of an article.
func (s *Service) message(a *news.Article, area *store.Area) *store.Message {
m := &store.Message{AreaID: area.ID, From: bbs.Clean(news.Poster(a), 60), To: "All",
Subject: bbs.Clean(news.Subject(a), bbs.MaxSubjectLen), MessageID: a.Get("Message-ID")}
if m.Subject == "" {
m.Subject = "(no subject)"
}
if m.From == "" {
m.From = "(unknown)"
}
lines := strings.Split(news.Text(a), "\n")
body := bbs.CleanBody(lines)
if strings.Count(body, "\n")+1 < len(lines)-1 || len(body) >= bbs.MaxBodyBytes-200 {
body += "\n\n[The article goes on: read it whole with a newsreader.]"
}
if body == "" {
body = "(empty)"
}
m.Body = body
// a reply: to the last of its References that is here
refs := strings.Fields(a.Get("References"))
for i := len(refs) - 1; i >= 0; i-- {
if p, err := s.B.Store.MessageByMessageID(refs[i]); err == nil {
m.ReplyTo = p.ID
if p.FromID > 0 {
if u, err := s.B.Store.UserByID(p.FromID); err == nil {
m.To = u.Name
}
} else {
m.To = p.From
}
break
}
}
return m
}
// PostLocal takes an article a newsreader posted, for user u: the poster
// is u, whatever its From says; Message-ID, Date and Path are this site's.
func (s *Service) PostLocal(raw []byte, u *store.User) (*store.Message, error) {
a, err := news.Parse(raw, s.MaxArticle)
if err != nil {
return nil, err
}
if a.Get("Control") != "" {
return nil, fmt.Errorf("%w: control messages are not taken", news.ErrMalformed)
}
var area *store.Area
for _, g := range news.Groups(a.Get("Newsgroups")) {
if ar, err := s.B.Store.AreaByNewsgroup(g); err == nil {
area = ar
break
}
}
if area == nil {
return nil, ErrNotHere
}
if !bbs.CanPost(u, area) {
return nil, fmt.Errorf("%w: only the sysop posts in %s", ErrRejected, area.Newsgroup)
}
m := s.message(a, area)
if strings.TrimSpace(news.Subject(a)) == "" {
return nil, fmt.Errorf("%w: no Subject", news.ErrMalformed)
}
m.FromID, m.From = u.ID, u.Name
// made again as ours: the poster, the ids and Path are not the
// newsreader's to choose; the text and the References (if sound) are
s.B.MakeArticle(u, area, m)
if refs := strings.Fields(a.Get("References")); len(refs) > 0 && len(refs) <= 20 {
ok := true
for _, r := range refs {
ok = ok && news.ValidMessageID(r)
}
if na, err := news.Parse(m.Raw, len(m.Raw)); ok && err == nil {
na.Set("References", strings.Join(refs, " "))
m.Raw = na.Bytes()
}
}
if _, err := s.B.Store.Post(m); err != nil {
return nil, err
}
return m, nil
}
+16 -5
View File
@@ -13,6 +13,7 @@ import (
"github.com/Neo-Desktop/bbs-sec/internal/config"
"github.com/Neo-Desktop/bbs-sec/internal/ftp"
"github.com/Neo-Desktop/bbs-sec/internal/logo"
"github.com/Neo-Desktop/bbs-sec/internal/nntp"
"github.com/Neo-Desktop/bbs-sec/internal/ui3270"
)
@@ -27,10 +28,15 @@ type Config struct {
UploadQuota int64 // a user's uploads a day (0: no limit)
FTP *ftp.Settings // nil: no FTP server
FTPAdvertise string // the FTP server's address, as users are told it
Database string
Log string // syslog, stderr, none, or a file
Listeners []*Listener
Warnings []string
News bbs.NewsSettings
MaxArticle int64
NNTP *nntp.ServerSettings // nil: no NNTP server
Peers []*nntp.Peer
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
@@ -61,6 +67,9 @@ func Load(path string) (*Config, error) {
if err := c.files(cf.Get("general", "")); err != nil {
return nil, fmt.Errorf("[general] %w", err)
}
if err := c.newsSections(cf); err != nil {
return nil, err
}
if err := c.ftpSection(cf.Get("ftp", "")); err != nil {
return nil, fmt.Errorf("[ftp] %w", err)
}
@@ -84,7 +93,9 @@ func Load(path string) (*Config, error) {
c.Listeners = DefaultListeners()
}
for _, s := range cf.Sections {
if s.Kind != "general" && s.Kind != "listen" && s.Kind != "ftp" {
switch s.Kind {
case "general", "listen", "ftp", "news", "nntp", "peer":
default:
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
}
}
+147
View File
@@ -0,0 +1,147 @@
package server
import (
"errors"
"fmt"
"net"
"os"
"strings"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/config"
"github.com/Neo-Desktop/bbs-sec/internal/news"
"github.com/Neo-Desktop/bbs-sec/internal/nntp"
)
// newsSections reads [news], [nntp] and the [peer NAME]s.
func (c *Config) newsSections(cf *config.File) error {
n := cf.Get("news", "")
host := n.String("hostname", "")
if host == "" {
host, _ = os.Hostname()
if !strings.Contains(host, ".") {
host += ".invalid"
}
}
c.News = bbs.NewsSettings{PathHost: host, Domain: n.String("domain", host),
Organization: n.String("organization", c.Settings.Name)}
if strings.ContainsAny(c.News.PathHost, "! \t") || !news.ValidMessageID("<x@"+c.News.Domain+">") {
return errors.New("[news] hostname, domain: a host name, like news.example.org")
}
var err error
if c.MaxArticle, err = parseSize(n, "max_article", 64<<10); err != nil {
return fmt.Errorf("[news] %w", err)
}
if s := cf.Get("nntp", ""); s != nil {
set := &nntp.ServerSettings{Address: s.String("address", ":1119")}
if _, _, err := net.SplitHostPort(set.Address); err != nil {
return fmt.Errorf("[nntp] address: %v", err)
}
set.TLS = strings.ToLower(s.String("tls", nntp.TLSNo))
switch set.TLS {
case nntp.TLSNo:
c.Warnings = append(c.Warnings, "[nntp] tls = no: AUTHINFO passwords go in the clear")
case nntp.TLSOptional:
c.Warnings = append(c.Warnings, "[nntp] tls = optional: readers that do not STARTTLS send passwords in the clear")
case nntp.TLSRequired, nntp.TLSImplicit:
default:
return fmt.Errorf("[nntp] tls: %q is not no, optional, required or implicit", set.TLS)
}
set.CertFile = s.String("cert_file", "")
set.KeyFile = s.String("key_file", "")
if set.TLS != nntp.TLSNo && (set.CertFile == "" || set.KeyFile == "") {
return errors.New("[nntp] cert_file and key_file are needed for TLS")
}
switch r := strings.ToLower(s.String("read", "anyone")); r {
case "anyone":
case "users":
set.ReadUsers = true
default:
return fmt.Errorf("[nntp] read: %q is not anyone or users", r)
}
if set.Post, err = s.Bool("post", true); err != nil {
return fmt.Errorf("[nntp] %w", err)
}
if set.MaxClients, err = s.Int("max_clients", 32, 1, 10000); err != nil {
return fmt.Errorf("[nntp] %w", err)
}
if set.MaxPerIP, err = s.Int("max_per_ip", 8, 0, 1000); err != nil {
return fmt.Errorf("[nntp] %w", err)
}
if set.IdleTimeout, err = s.Seconds("idle_timeout", 600, 30, 86400); err != nil {
return fmt.Errorf("[nntp] %w", err)
}
c.NNTP = set
}
names := map[string]bool{}
for _, s := range cf.All("peer") {
p, err := peer(s)
if err != nil {
return fmt.Errorf("[peer %s] %w", s.Name, err)
}
if names[p.Name] {
return fmt.Errorf("[peer %s] given twice", p.Name)
}
names[p.Name] = true
if p.TLS == "no" && p.Password != "" {
c.Warnings = append(c.Warnings, fmt.Sprintf("[peer %s] its password goes in the clear (tls = no)", p.Name))
}
c.Peers = append(c.Peers, p)
}
return nil
}
func peer(s *config.Section) (*nntp.Peer, error) {
if s.Name == "" {
return nil, errors.New("a peer needs a name: [peer NAME]")
}
p := &nntp.Peer{Name: s.Name, Address: s.String("address", "")}
var err error
if p.Pull, err = s.Bool("pull", true); err != nil {
return nil, err
}
if p.Push, err = s.Bool("push", true); err != nil {
return nil, err
}
if (p.Pull || p.Push) && p.Address == "" {
return nil, errors.New("address: none given (or pull = no and push = no)")
}
if p.Address != "" {
if _, _, err := net.SplitHostPort(p.Address); err != nil {
return nil, fmt.Errorf("address: %v", err)
}
}
p.TLS = strings.ToLower(s.String("tls", "no"))
switch p.TLS {
case "no", "starttls", "implicit":
default:
return nil, fmt.Errorf("tls: %q is not no, starttls or implicit", p.TLS)
}
p.CAFile = s.String("ca_file", "")
p.Username = s.String("username", "")
p.Password = s.String("password", "")
p.Groups = s.String("groups", "*")
if p.Interval, err = s.Seconds("interval", 600, 60, 86400); err != nil {
return nil, err
}
if p.MaxPerRun, err = s.Int("max_per_run", 1000, 1, 100000); err != nil {
return nil, err
}
if p.Initial, err = s.Int("initial", 100, 0, 100000); err != nil {
return nil, err
}
for _, h := range strings.Fields(strings.ReplaceAll(s.String("accept_from", ""), ",", " ")) {
if ip := net.ParseIP(h); ip != nil {
p.AcceptFrom = append(p.AcceptFrom, ip)
continue
}
ips, err := net.LookupIP(h)
if err != nil {
return nil, fmt.Errorf("accept_from %s: %v", h, err)
}
p.AcceptFrom = append(p.AcceptFrom, ips...)
}
return p, nil
}
+242
View File
@@ -0,0 +1,242 @@
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
)
// migrate brings an older database up to date: columns added since.
func migrate(db *sql.DB) error {
add := []struct{ table, column, decl string }{
{"areas", "newsgroup", "TEXT"},
{"messages", "message_id", "TEXT"},
{"messages", "origin", "TEXT NOT NULL DEFAULT ''"},
{"messages", "raw", "BLOB"},
}
for _, a := range add {
var n int
if err := db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?`,
a.table, a.column).Scan(&n); err != nil {
return err
}
if n == 0 {
if _, err := db.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, a.table, a.column, a.decl)); err != nil {
return err
}
}
}
_, err := db.Exec(`
CREATE UNIQUE INDEX IF NOT EXISTS areas_newsgroup ON areas(newsgroup) WHERE newsgroup IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS messages_message_id ON messages(message_id) WHERE message_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS history (
message_id TEXT PRIMARY KEY,
seen INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS peer_groups (
peer TEXT NOT NULL,
newsgroup TEXT NOT NULL,
last INTEGER NOT NULL,
PRIMARY KEY (peer, newsgroup)
);
CREATE TABLE IF NOT EXISTS peer_push (
peer TEXT PRIMARY KEY,
last_id INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_created ON messages(created);
`)
return err
}
// SetNewsgroup makes an area a newsgroup ("": not one any more).
func (s *Store) SetNewsgroup(area int64, group string) error {
var g any
if group != "" {
g = group
}
_, err := s.db.Exec(`UPDATE areas SET newsgroup = ? WHERE id = ?`, g, area)
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
return ErrExists
}
return err
}
// AreaByNewsgroup finds an area by its newsgroup.
func (s *Store) AreaByNewsgroup(group string) (*Area, error) {
return scanArea(s.db.QueryRow(areaQuery+` WHERE a.newsgroup = ?`, group))
}
// Newsgroups lists the areas that are newsgroups, by name.
func (s *Store) Newsgroups() ([]*Area, error) {
rows, err := s.db.Query(areaQuery + ` WHERE a.newsgroup IS NOT NULL ORDER BY a.newsgroup`)
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()
}
// MessageByMessageID finds an article by its Message-ID.
func (s *Store) MessageByMessageID(id string) (*Message, error) {
return scanMessage(s.db.QueryRow(`SELECT `+msgCols+` FROM messages WHERE message_id = ?`, id))
}
// Raw is an article as it is sent.
func (s *Store) Raw(id int64) ([]byte, error) {
var raw []byte
err := s.db.QueryRow(`SELECT raw FROM messages WHERE id = ?`, id).Scan(&raw)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return raw, err
}
// Seen reports whether a Message-ID has been here: taken, or turned away.
func (s *Store) Seen(id string) (bool, error) {
var n int
err := s.db.QueryRow(`SELECT COUNT(*) FROM history WHERE message_id = ?`, id).Scan(&n)
return n > 0, err
}
// Remember notes a Message-ID as seen (an article refused, so that it is
// not offered again and again).
func (s *Store) Remember(id string) error {
_, err := s.db.Exec(`INSERT OR IGNORE INTO history (message_id, seen) VALUES (?, ?)`, id, now())
return err
}
// ExpireHistory forgets Message-IDs seen before t that are no longer here.
func (s *Store) ExpireHistory(t time.Time) error {
_, err := s.db.Exec(`DELETE FROM history WHERE seen < ? AND message_id NOT IN
(SELECT message_id FROM messages WHERE message_id IS NOT NULL)`, t.Unix())
return err
}
// Articles lists up to limit articles of an area numbered from lo to hi
// (inclusive; article numbers are message ids), without their raw form.
func (s *Store) Articles(area, lo, hi int64, limit int) ([]*Message, error) {
rows, err := s.db.Query(`SELECT `+msgCols+` FROM messages WHERE area_id = ? AND id >= ? AND id <= ?
AND message_id IS NOT NULL ORDER BY id LIMIT ?`, area, lo, hi, 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()
}
// ArticlesSince lists the Message-IDs of articles that came since t, in
// the given areas.
func (s *Store) ArticlesSince(t time.Time, areas []int64, limit int) ([]string, error) {
if len(areas) == 0 {
return nil, nil
}
q := `SELECT message_id FROM messages WHERE created >= ? AND message_id IS NOT NULL AND area_id IN (?` +
strings.Repeat(",?", len(areas)-1) + `) ORDER BY id LIMIT ?`
args := []any{t.Unix()}
for _, a := range areas {
args = append(args, a)
}
args = append(args, limit)
rows, err := s.db.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}
// PeerLast is the last article number of a peer's newsgroup we have taken.
func (s *Store) PeerLast(peer, group string) (int64, bool, error) {
var n int64
err := s.db.QueryRow(`SELECT last FROM peer_groups WHERE peer = ? AND newsgroup = ?`, peer, group).Scan(&n)
if errors.Is(err, sql.ErrNoRows) {
return 0, false, nil
}
return n, err == nil, err
}
// SetPeerLast records it.
func (s *Store) SetPeerLast(peer, group string, last int64) error {
_, err := s.db.Exec(`INSERT INTO peer_groups (peer, newsgroup, last) VALUES (?, ?, ?)
ON CONFLICT (peer, newsgroup) DO UPDATE SET last = excluded.last`, peer, group, last)
return err
}
// PeerPushed is the last message id offered to a peer.
func (s *Store) PeerPushed(peer string) (int64, bool, error) {
var n int64
err := s.db.QueryRow(`SELECT last_id FROM peer_push WHERE peer = ?`, peer).Scan(&n)
if errors.Is(err, sql.ErrNoRows) {
return 0, false, nil
}
return n, err == nil, err
}
// SetPeerPushed records it.
func (s *Store) SetPeerPushed(peer string, id int64) error {
_, err := s.db.Exec(`INSERT INTO peer_push (peer, last_id) VALUES (?, ?)
ON CONFLICT (peer) DO UPDATE SET last_id = excluded.last_id`, peer, id)
return err
}
// ToPush lists articles after id in the given areas, not from the peer
// itself, for offering to it.
func (s *Store) ToPush(peer string, after int64, areas []int64, limit int) ([]*Message, error) {
if len(areas) == 0 {
return nil, nil
}
q := `SELECT ` + msgCols + ` FROM messages WHERE id > ? AND message_id IS NOT NULL AND origin != ?
AND area_id IN (?` + strings.Repeat(",?", len(areas)-1) + `) ORDER BY id LIMIT ?`
args := []any{after, peer}
for _, a := range areas {
args = append(args, a)
}
args = append(args, limit)
rows, err := s.db.Query(q, args...)
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()
}
// MaxMessageID is the highest message id there is.
func (s *Store) MaxMessageID() (int64, error) {
var n int64
err := s.db.QueryRow(`SELECT COALESCE(MAX(id), 0) FROM messages`).Scan(&n)
return n, err
}
+41 -9
View File
@@ -46,8 +46,10 @@ type Area struct {
ID int64
Name string
Description string
SysopOnly bool // only sysops post
SysopOnly bool // only sysops post
Newsgroup string // its newsgroup ("": not one)
Messages int
FirstID int64
LastID int64
}
@@ -64,6 +66,12 @@ type Message struct {
ReplyTo int64
Created time.Time
Read bool // mail only
// a newsgroup's article: its Message-ID, where it came from ("" from
// here, else the peer's name) and the article as it is sent
MessageID string
Origin string
Raw []byte
}
// Store is the database.
@@ -169,6 +177,10 @@ func Open(path string) (*Store, error) {
db.Close()
return nil, fmt.Errorf("%s: %w", path, err)
}
if err := migrate(db); 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()
@@ -349,14 +361,16 @@ 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,
const areaQuery = `SELECT a.id, a.name, a.description, a.sysop_only, COALESCE(a.newsgroup, ''),
(SELECT COUNT(*) FROM messages m WHERE m.area_id = a.id),
(SELECT COALESCE(MIN(m.id), 0) 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)
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopOnly, &a.Newsgroup, &a.Messages,
&a.FirstID, &a.LastID)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
@@ -391,13 +405,14 @@ 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`
const msgCols = `id, area_id, from_id, from_name, to_name, subject, body, reply_to, created,
COALESCE(message_id, ''), origin`
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)
&m.Body, &m.ReplyTo, &created, &m.MessageID, &m.Origin)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
@@ -412,13 +427,30 @@ func (s *Store) Post(m *Message) (int64, error) {
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())
var msgid any
if m.MessageID != "" {
msgid = m.MessageID
}
res, err := tx.Exec(`INSERT INTO messages (area_id, from_id, from_name, to_name, subject, body, reply_to, created,
message_id, origin, raw)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, m.AreaID, m.FromID, m.From, m.To, m.Subject, m.Body, m.ReplyTo, now(),
msgid, m.Origin, m.Raw)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
return 0, ErrExists
}
return 0, err
}
if _, err := tx.Exec(`UPDATE users SET posts = posts + 1 WHERE id = ?`, m.FromID); err != nil {
return 0, err
if m.MessageID != "" {
if _, err := tx.Exec(`INSERT OR IGNORE INTO history (message_id, seen) VALUES (?, ?)`,
m.MessageID, now()); err != nil {
return 0, err
}
}
if m.FromID > 0 {
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()
+5 -1
View File
@@ -392,7 +392,11 @@ func (s *session) area(a *store.Area) error {
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)
group := ""
if a.Newsgroup != "" {
group = t.C(Dim, " ("+a.Newsgroup+")")
}
t.Printf("%s%s: %d messages, %d new\n", t.C(Cyan, a.Name), group, a.Messages, nw)
menu := "[R]ead new, [L]ist, [#] read a number, "
if bbs.CanPost(s.user, a) {
menu += "[P]ost, "