mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Add a Gemini server: gopher's capsule and finger's users over TLS
[gemini] serves gemini:// on port 1965: the home page, About this system, Who's online, a user lookup (/users asks for a name; /~name) with finger's answer, and the message and file areas the sysop opens, as gopher shows them. Message lines are escaped so they cannot become links, headings or preformatting; files go as they are, typed by name. With no cert_file and key_file, a self-signed certificate for hostname is made beside the database at the first start and kept, since Gemini clients trust on first use; bbs check shows its fingerprint. Gopher's About, Who, Area and OpenFiles and finger's User are exported so Gemini shows the same content under the same rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRSz48BzvGbSP2U45F8
This commit is contained in:
22 files changed
+994
-44
No files matched your search
@@ -865,6 +865,25 @@ address = 127.0.0.1:2513
|
||||
; file areas listed and downloadable
|
||||
;files = no
|
||||
|
||||
; gemini: gopher's capsule over Gemini (gemini://, TLS): about the system,
|
||||
; who is on, users as finger tells of them, and what areas the sysop opens:
|
||||
; no login, so anyone sees them. Port 1965 needs no privilege
|
||||
;[gemini]
|
||||
;address = :1965
|
||||
; the name a certificate made here is for
|
||||
;hostname = bbs.example.org
|
||||
; the certificate and key (PEM); with neither, a self-signed one is made
|
||||
; beside the database (gemini-cert.pem, gemini-key.pem) at the first start
|
||||
; and kept: clients trust it on first use and warn if it ever changes
|
||||
;cert_file = /etc/bbs/gemini-cert.pem
|
||||
;key_file = /etc/bbs/gemini-key.pem
|
||||
; message areas shown (a wildmat of area names; "": none)
|
||||
;areas = general,announcements
|
||||
; file areas listed and downloadable
|
||||
;files = no
|
||||
; /users: look up a user, as finger tells of them
|
||||
;users = yes
|
||||
|
||||
; Time. The BBS's clock can follow time servers, and the BBS can be a
|
||||
; time server itself: NTP, NTS (NTP made secure with TLS keys) and PTP.
|
||||
; With no servers it tells of the system clock (kept by chrony, ntpd ...).
|
||||
|
||||
@@ -70,6 +70,7 @@ import (
|
||||
"github.com/D-Modem/bbs/internal/finger"
|
||||
"github.com/D-Modem/bbs/internal/ftn"
|
||||
"github.com/D-Modem/bbs/internal/ftp"
|
||||
"github.com/D-Modem/bbs/internal/gemini"
|
||||
"github.com/D-Modem/bbs/internal/gopher"
|
||||
"github.com/D-Modem/bbs/internal/imageboard"
|
||||
"github.com/D-Modem/bbs/internal/ircd"
|
||||
@@ -314,6 +315,10 @@ func main() {
|
||||
if g := cfg.Gopher; g != nil {
|
||||
fmt.Printf("gopher: %s as %s:%d, areas %q, files %v\n", g.Address, g.Host, g.Port, g.Areas, g.Files)
|
||||
}
|
||||
if g := cfg.Gemini; g != nil {
|
||||
fmt.Printf("gemini: %s, areas %q, files %v, users %v\n", g.Address, g.Areas, g.Files, g.Users)
|
||||
fmt.Printf("gemini certificate %s: %s\n", g.CertFile, gemini.CertInfo(g.CertFile, g.MakeCert))
|
||||
}
|
||||
for _, d := range cfg.Doors {
|
||||
if r := d.Remote; r != nil {
|
||||
fmt.Printf("[door %s] %s at %s, %v\n", d.Name, r.Kind, r.Address, d.TimeLimit)
|
||||
@@ -624,6 +629,15 @@ func serve(cfg *server.Config, path string) int {
|
||||
}
|
||||
}()
|
||||
}
|
||||
if cfg.Gemini != nil {
|
||||
gm := &gemini.Server{B: b, S: *cfg.Gemini}
|
||||
go func() {
|
||||
if err := gm.Run(ctx); err != nil {
|
||||
lg.Printf("%v", err)
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
}
|
||||
var fd *fido.Fido
|
||||
if cfg.Fido != nil {
|
||||
fd, err = fido.New(b, *cfg.Fido)
|
||||
|
||||
@@ -46,6 +46,7 @@ the file is laid out.
|
||||
| [`[mrc]`](#mrc) | Multi Relay Chat: the BBSes' chat network. |
|
||||
| [`[finger]`](#finger) | finger: who is on ("finger @host"), and who a user is ("finger name@host"). |
|
||||
| [`[gopher]`](#gopher) | gopher: about the system, who is on, and what areas the sysop opens: no login, so anyone sees them. |
|
||||
| [`[gemini]`](#gemini) | gemini: gopher's capsule over Gemini (gemini://, TLS): about the system, who is on, users as finger tells of them, and what areas the sysop opens: no login, so anyone sees them. |
|
||||
| [`[time]`](#time) | Time. |
|
||||
| [`[ntp]`](#ntp) | an NTP server (UDP). |
|
||||
| [`[nts]`](#nts) | an NTS-KE server (RFC 8915): TLS 1.3, its clients' keys and cookies for [ntp], which then answers NTS-secured requests too. |
|
||||
@@ -654,6 +655,21 @@ gopher: about the system, who is on, and what areas the sysop opens: no login, s
|
||||
| `files` | | | file areas listed and downloadable. Examples: `no`. |
|
||||
|
||||
|
||||
## `[gemini]`
|
||||
|
||||
gemini: gopher's capsule over Gemini (gemini://, TLS): about the system, who is on, users as finger tells of them, and what areas the sysop opens: no login, so anyone sees them. Port 1965 needs no privilege.
|
||||
|
||||
| key | default | live | what it does |
|
||||
|---|---|---|---|
|
||||
| `address` | | | See the section above. Examples: `:1965`. |
|
||||
| `hostname` | | | the name a certificate made here is for. Examples: `bbs.example.org`. |
|
||||
| `cert_file` | | | the certificate and key (PEM); with neither, a self-signed one is made beside the database (gemini-cert.pem, gemini-key.pem) at the first start and kept: clients trust it on first use and warn if it ever changes. Examples: `/etc/bbs/gemini-cert.pem`. |
|
||||
| `key_file` | | | the certificate and key (PEM); with neither, a self-signed one is made beside the database (gemini-cert.pem, gemini-key.pem) at the first start and kept: clients trust it on first use and warn if it ever changes. Examples: `/etc/bbs/gemini-key.pem`. |
|
||||
| `areas` | | | message areas shown (a wildmat of area names; "": none) Examples: `general,announcements`. |
|
||||
| `files` | | | file areas listed and downloadable. Examples: `no`. |
|
||||
| `users` | | | /users: look up a user, as finger tells of them. Examples: `yes`. |
|
||||
|
||||
|
||||
## `[time]`
|
||||
|
||||
Time. The BBS's clock can follow time servers, and the BBS can be a time server itself: NTP, NTS (NTP made secure with TLS keys) and PTP. With no servers it tells of the system clock (kept by chrony, ntpd ...).
|
||||
|
||||
@@ -45,7 +45,7 @@ whether terminals are asked what they are (see
|
||||
| `scripts_dir` (in `[general]`) | the sysop's JavaScript | [Scripting](Scripting) |
|
||||
| `[security]` | deny lists, bans, the hack log | [Security](Security) |
|
||||
| `[event NAME]` | scheduled programs | [Sysop tools](Sysop-Tools) |
|
||||
| `[finger]`, `[gopher]` | the finger and gopher servers | [Finger and gopher](Finger-and-Gopher) |
|
||||
| `[finger]`, `[gopher]`, `[gemini]` | the finger, gopher and Gemini servers | [Finger, gopher and Gemini](Finger-and-Gopher) |
|
||||
| `[irc]` | the IRC server for the chat rooms | [IRC](IRC) |
|
||||
| `[mrc]` | Multi Relay Chat | [MRC](MRC) |
|
||||
| `database` (in `[general]`) | SQLite's file, or a PostgreSQL, MySQL or MariaDB server | [Databases](Databases) |
|
||||
@@ -73,7 +73,7 @@ Configuration). They are full screen on ANSI terminals, use PF keys on a
|
||||
| Board configuration | the BBS's name, the sysop's, the location, postal address, dial-in numbers and internet addresses; the banner, message of the day, goodbye, logo; menus and prompts |
|
||||
| System configuration | the user and group it runs as; the database and log; where files are kept and how large they may be; deny lists, the hack log, bans; scheduled events; every section of the file as it is |
|
||||
| Connections and modems | modem lines and every listener; callers at once, logins, time-outs, lock-outs; passwords by modemmenu's auth socket ([Modem callers](Modem-Callers#the-same-password-for-telnet-ssh-and-the-web)); the caller ID country and GeoIP |
|
||||
| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors |
|
||||
| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, Gemini, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors |
|
||||
| Users and groups | the accounts (level, flags, sysop, locked, a new password; new ones; deleted ones) and the access levels |
|
||||
| Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups: one now, those made, `[backup]` ([Backups](Backups)) |
|
||||
|
||||
|
||||
@@ -40,10 +40,11 @@ cover.
|
||||
| `doors/dosemu2` | the Docker image DOS doors run in: dosemu2, its FOSSIL on COM1 |
|
||||
| `internal/finger` | the finger server |
|
||||
| `internal/gopher` | the gopher server |
|
||||
| `internal/gemini` | the Gemini server: gopher's capsule and finger's users, over TLS |
|
||||
| `internal/forum` | the web forum: its pages (html/template; `themes/NAME/` a theme's own, over its parent's and `templates/`), the themes' CSS (`static/`), sessions by the API's tokens |
|
||||
| `internal/api` | the HTTP API: REST, server-sent events, WebSockets, metrics, OpenAPI; the web terminal page (`web/`: xterm.js, the page) |
|
||||
| `proto` | the WebSocket protocol, `bbs.v1` (`make proto` regenerates `internal/api/pb`) |
|
||||
| `internal/tcpserv` | what finger and gopher share: limits, timeouts |
|
||||
| `internal/tcpserv` | what finger, gopher and Gemini share: limits, timeouts |
|
||||
| `internal/screens` | the sysop's display files: finding them, @-codes, 3270 colour tags |
|
||||
| `internal/xfer` | XMODEM, YMODEM, ZMODEM and Kermit, both ways |
|
||||
| `internal/logo` | the logo: a PNG, or the name in a pixel font |
|
||||
@@ -136,9 +137,9 @@ when the bbs-dosemu2 image is built, a real DOS door talking by FOSSIL in
|
||||
it. Chat: rooms, history, private rooms, flooding, node messages, paging
|
||||
and answering, the page command (and that it runs no shell); two callers
|
||||
chatting and paging on the text BBS; a 3270 (s3270) chatting with a text
|
||||
caller and getting a node message on its message line. Finger and
|
||||
gopher: their answers and refusals, with the finger program and curl as
|
||||
clients. Customization: finding display files by terminal, SAUCE,
|
||||
caller and getting a node message on its message line. Finger,
|
||||
gopher and Gemini: their answers and refusals, with the finger program and
|
||||
curl as clients, and Gemini's certificate made once and kept. Customization: finding display files by terminal, SAUCE,
|
||||
@-codes and widths, colour tags; menus and strings in the configuration
|
||||
and what it refuses; a text caller through an ANSI logon (CP437 as it
|
||||
is), the strings, a welcome screen, the sysop's menus and submenus, a
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
Two small servers tell the world about the BBS. Finger shows who is on
|
||||
Three small servers tell the world about the BBS. Finger shows who is on
|
||||
and who a user is. Gopher serves the system's own gopherspace, with the
|
||||
message and file areas the sysop opens to it. Both are off unless their
|
||||
section is in the configuration.
|
||||
message and file areas the sysop opens to it. Gemini serves the same
|
||||
capsule, and finger's users, over TLS. Each is off unless its section is
|
||||
in the configuration.
|
||||
|
||||
Their usual ports are below 1024, so either run the BBS with
|
||||
Finger's and gopher's usual ports are below 1024, so either run the BBS with
|
||||
`AmbientCapabilities=CAP_NET_BIND_SERVICE` (see
|
||||
[bbs.service.sample](https://github.com/D-Modem/bbs/blob/HEAD/bbs.service.sample)),
|
||||
or use another port.
|
||||
@@ -71,4 +72,48 @@ $ curl gopher://bbs.example.org/1/areas
|
||||
$ lynx gopher://bbs.example.org
|
||||
```
|
||||
|
||||
## Gemini
|
||||
|
||||
```
|
||||
[gemini]
|
||||
address = :1965
|
||||
hostname = bbs.example.org ; the name a certificate made here is for
|
||||
;cert_file = /etc/bbs/gemini-cert.pem ; or neither, for one made here
|
||||
;key_file = /etc/bbs/gemini-key.pem
|
||||
areas = general,announcements ; as gopher's
|
||||
files = no
|
||||
users = yes ; /users: look up a user, as finger does
|
||||
max_clients = 32
|
||||
max_per_ip = 8
|
||||
```
|
||||
|
||||
[Gemini](https://geminiprotocol.net/) is gopher's younger cousin: one
|
||||
request a connection, always over TLS, pages in gemtext. The capsule is
|
||||
gopher's: the home page links *About this system*, *Who's online*, *Look
|
||||
up a user* (it asks for a name and shows what finger would) and, if the
|
||||
sysop opened them, *Message areas* and *File areas*. `gemini://host/~alice`
|
||||
goes straight to a user. A message is a gemtext page with its headers
|
||||
first; its lines are shown as text, so a line in a message cannot become
|
||||
a link or a heading. A file goes as it is, typed by its name
|
||||
(`application/octet-stream` if the name says nothing).
|
||||
|
||||
Gemini clients trust a capsule's certificate the first time they see it
|
||||
and warn if it ever changes, so self-signed certificates are the usual
|
||||
thing. With no `cert_file` and `key_file`, the BBS makes one for
|
||||
`hostname` at its first start, beside the database (`gemini-cert.pem`,
|
||||
`gemini-key.pem`), and keeps it; `bbs check` shows its SHA-256
|
||||
fingerprint. Keep those two files with your backups: a new certificate
|
||||
makes every client that has been before warn. A certificate from a
|
||||
certificate authority (Let's Encrypt's, say) works too.
|
||||
|
||||
What gopher shows anyone, Gemini shows anyone: no areas and no files by
|
||||
default, `bbs check` warns when `areas` or `files` is set, and file areas
|
||||
with a download requirement are never shown. `users = no` turns off the
|
||||
user lookup. Port 1965 is above 1024 and needs no privilege.
|
||||
|
||||
```
|
||||
$ amfora gemini://bbs.example.org
|
||||
$ printf 'gemini://bbs.example.org/areas\r\n' | openssl s_client -quiet -connect bbs.example.org:1965
|
||||
```
|
||||
|
||||
**See also:** [Configuration](Configuration), [Security](Security)
|
||||
+2
-2
@@ -85,7 +85,7 @@ which is generated from `bbs.conf.sample`.
|
||||
for AIM and ICQ clients on the same chat, [MSN Messenger](MSN-Messenger)
|
||||
for MSN clients, and [MRC](MRC), the chat
|
||||
network shared with other BBSes
|
||||
- [Finger and gopher](Finger-and-Gopher)
|
||||
- [Finger, gopher and Gemini](Finger-and-Gopher)
|
||||
- [Time](Time): NTP, NTS and PTP, followed and served
|
||||
|
||||
**On the web**
|
||||
@@ -145,7 +145,7 @@ which is generated from `bbs.conf.sample`.
|
||||
| [AOL clients](AOL) | a host for AOL's own clients (3.0, 4.0): sign-on with BBS accounts |
|
||||
| [MSN Messenger](MSN-Messenger) | the MSN server: MSN Messenger 1.0 to 4.7, contacts and IMs |
|
||||
| [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes |
|
||||
| [Finger and gopher](Finger-and-Gopher) | who is on, and the BBS in gopherspace |
|
||||
| [Finger, gopher and Gemini](Finger-and-Gopher) | who is on, and the BBS in gopherspace and Geminispace |
|
||||
| [Time](Time) | NTP, NTS and PTP: the clock following time servers, and serving time |
|
||||
| [Web forum](Web-Forum) | the message areas as a web forum |
|
||||
| [Image boards](Image-Boards) | anonymous image boards, in the style of kusaba x and 4chan |
|
||||
|
||||
@@ -43,7 +43,7 @@ user = bbs
|
||||
|
||||
When it is started as root, `bbs serve` reads the configuration and binds
|
||||
every port and unix socket it listens on (the listeners, the HTTP API and
|
||||
metrics, FTP, NNTP, IRC, finger, gopher and binkp). Then it gives up root,
|
||||
metrics, FTP, NNTP, IRC, finger, gopher, Gemini and binkp). Then it gives up root,
|
||||
takes the user's supplementary groups (such as `socket_group`'s and
|
||||
docker's), and runs itself again as the user. It stays the same process,
|
||||
with the same PID for systemd and `systemctl reload`, and keeps the
|
||||
|
||||
@@ -65,8 +65,9 @@ over TLS.
|
||||
- Finger tells no addresses or caller IDs and forwards nothing; gopher
|
||||
shows no message or file area unless the sysop names it (and `bbs
|
||||
check` warns when they do), and its selectors are database records, not
|
||||
paths. Both limit connections at once and from one address, and both
|
||||
time out.
|
||||
paths. Gemini shows what gopher would, under its own `areas` and
|
||||
`files`, and finger's users. All three limit connections at once and
|
||||
from one address, and all time out.
|
||||
- The HTTP API: TLS by default (`bbs check` warns when it is off on an
|
||||
address others reach); tokens of 32 random bytes kept only as hashes,
|
||||
never in URLs, limited by scope (`sysop` only for sysops), expiring
|
||||
@@ -109,7 +110,7 @@ ban_minutes = 60 ; a throttled address is banned this long
|
||||
`198.51.100.0/24`, `2001:db8::/32`; `#` or `;` begins a comment). A
|
||||
connection from one is closed at once on every service: the terminal
|
||||
listeners and SSH, FTP, NNTP, the HTTP API and web terminal, finger,
|
||||
gopher and binkp. Callers through unix sockets (a modem server, an
|
||||
gopher, Gemini and binkp. Callers through unix sockets (a modem server, an
|
||||
upstream menu) are never refused. The file is read again when it
|
||||
changes; `bbs check` warns of lines that are not addresses.
|
||||
- Mail from the internet (`[mx]`) can also be checked against DNS
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
- [AOL clients](AOL)
|
||||
- [MSN Messenger](MSN-Messenger)
|
||||
- [MRC](MRC)
|
||||
- [Finger and gopher](Finger-and-Gopher)
|
||||
- [Finger, gopher and Gemini](Finger-and-Gopher)
|
||||
- [Time: NTP, NTS and PTP](Time)
|
||||
- [Web forum](Web-Forum)
|
||||
- [Image boards](Image-Boards)
|
||||
|
||||
@@ -187,6 +187,7 @@ func (e *Editor) servicesMenu() page {
|
||||
heading("Servers"),
|
||||
single("Finger", "finger"),
|
||||
single("Gopher", "gopher"),
|
||||
single("Gemini", "gemini"),
|
||||
single("FTP", "ftp"),
|
||||
single("IRC (ircd)", "irc"),
|
||||
menu("News (NNTP)", e.onOff(sec("nntp")), func() error { return e.show(e.newsPage()) }),
|
||||
|
||||
@@ -67,7 +67,7 @@ func (s *Server) handle(c net.Conn) {
|
||||
case q == "":
|
||||
out = s.online()
|
||||
default:
|
||||
out = s.user(q)
|
||||
out = s.User(q)
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, l := range out {
|
||||
@@ -103,8 +103,8 @@ func (s *Server) online() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// user tells of one user.
|
||||
func (s *Server) user(name string) []string {
|
||||
// User tells of one user.
|
||||
func (s *Server) User(name string) []string {
|
||||
if !s.S.Users {
|
||||
return []string{"Users are not told of by finger here."}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LoadCert loads the certificate and key; if mk is set and neither file
|
||||
// is there yet, it first makes them: a self-signed certificate for host,
|
||||
// good for 50 years. Gemini clients trust a capsule's certificate on first
|
||||
// use, so it is made once and kept, never made again behind the sysop's
|
||||
// back: a changed certificate is what clients warn of.
|
||||
func LoadCert(certFile, keyFile, host string, mk bool) (tls.Certificate, error) {
|
||||
_, cerr := os.Stat(certFile)
|
||||
_, kerr := os.Stat(keyFile)
|
||||
if mk && errors.Is(cerr, os.ErrNotExist) && errors.Is(kerr, os.ErrNotExist) {
|
||||
if err := MakeCert(certFile, keyFile, host); err != nil {
|
||||
return tls.Certificate{}, err
|
||||
}
|
||||
}
|
||||
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, fmt.Errorf("certificate: %w", err)
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
// MakeCert writes a new self-signed certificate for host and its key.
|
||||
func MakeCert(certFile, keyFile, host string) error {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: host},
|
||||
NotBefore: now.Add(-time.Hour),
|
||||
NotAfter: now.AddDate(50, 0, 0),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
tmpl.IPAddresses = []net.IP{ip}
|
||||
} else {
|
||||
tmpl.DNSNames = []string{host}
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kb, err := x509.MarshalPKCS8PrivateKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := write(keyFile, "PRIVATE KEY", kb, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := write(certFile, "CERTIFICATE", der, 0644); err != nil {
|
||||
os.Remove(keyFile)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// write writes one PEM block to a new file, not left half written.
|
||||
func write(name, kind string, b []byte, mode os.FileMode) error {
|
||||
f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = pem.Encode(f, &pem.Block{Type: kind, Bytes: b})
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// CertInfo describes the certificate for bbs check: whom it is for, until
|
||||
// when, and its SHA-256 fingerprint (what TOFU clients pin), or that it
|
||||
// will be made.
|
||||
func CertInfo(certFile string, mk bool) string {
|
||||
b, err := os.ReadFile(certFile)
|
||||
if errors.Is(err, os.ErrNotExist) && mk {
|
||||
return "none yet (made at the first start)"
|
||||
}
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
blk, _ := pem.Decode(b)
|
||||
if blk == nil {
|
||||
return "not a PEM certificate"
|
||||
}
|
||||
c, err := x509.ParseCertificate(blk.Bytes)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return fmt.Sprintf("%s until %s, SHA-256 %X", c.Subject.CommonName, c.NotAfter.Format("2006-01-02"), sha256.Sum256(c.Raw))
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
// Package gemini serves the BBS by Gemini (gemini://, TLS, port 1965): the
|
||||
// gopher server's capsule (what the system is, who is on, the message and
|
||||
// file areas the sysop opens to it) and finger's users, as gemtext. As
|
||||
// with gopher, paths name records in the BBS's store, not files on disk.
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/finger"
|
||||
"github.com/D-Modem/bbs/internal/gopher"
|
||||
"github.com/D-Modem/bbs/internal/sockets"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
"github.com/D-Modem/bbs/internal/tcpserv"
|
||||
)
|
||||
|
||||
// Settings are the [gemini] section's.
|
||||
type Settings struct {
|
||||
Address string
|
||||
Host string // the name the certificate is made for
|
||||
CertFile string // the certificate and its key (PEM)
|
||||
KeyFile string
|
||||
MakeCert bool // made, self-signed, if not there (no cert_file given)
|
||||
Areas string // wildmat of the message areas shown ("": none)
|
||||
Files bool // file areas listed and downloadable
|
||||
Users bool // /users: finger's answer for a user
|
||||
MaxClients int
|
||||
MaxPerIP int
|
||||
}
|
||||
|
||||
// Server serves Gemini.
|
||||
type Server struct {
|
||||
B *bbs.BBS
|
||||
S Settings
|
||||
|
||||
g *gopher.Server // what is shown, and how
|
||||
f *finger.Server
|
||||
}
|
||||
|
||||
// Gemini's status codes used here.
|
||||
const (
|
||||
statusInput = 10
|
||||
statusOK = 20
|
||||
statusRedirect = 31
|
||||
statusBusy = 41
|
||||
statusNotFound = 51
|
||||
statusNoProxy = 53
|
||||
statusBad = 59
|
||||
)
|
||||
|
||||
// MaxRequest is the longest URL a request may have (bytes).
|
||||
const MaxRequest = 1024
|
||||
|
||||
// Run listens until ctx is done.
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
cert, err := LoadCert(s.S.CertFile, s.S.KeyFile, s.S.Host, s.S.MakeCert)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gemini: %w", err)
|
||||
}
|
||||
ln, err := sockets.Listen("tcp", s.S.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gemini: %w", err)
|
||||
}
|
||||
return s.Serve(ctx, ln, cert)
|
||||
}
|
||||
|
||||
// Serve answers on ln, with TLS by cert, until ctx is done.
|
||||
func (s *Server) Serve(ctx context.Context, ln net.Listener, cert tls.Certificate) error {
|
||||
s.g = &gopher.Server{B: s.B, S: gopher.Settings{Areas: s.S.Areas, Files: s.S.Files}}
|
||||
s.f = &finger.Server{B: s.B, S: finger.Settings{Users: true}}
|
||||
tl := tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12})
|
||||
ts := &tcpserv.Server{Name: "gemini", MaxClients: s.S.MaxClients, MaxPerIP: s.S.MaxPerIP,
|
||||
Refuse: func(c net.Conn) bool { return s.B.Refuse("gemini", c.RemoteAddr()) },
|
||||
Timeout: 5 * time.Minute, Log: s.B.Log, Handle: s.handle,
|
||||
Busy: func(c net.Conn) { header(c, statusBusy, "Too busy; try again later.") }}
|
||||
return ts.Serve(ctx, tl)
|
||||
}
|
||||
|
||||
// header sends a response's header line.
|
||||
func header(c io.Writer, status int, meta string) {
|
||||
fmt.Fprintf(c, "%d %s\r\n", status, meta)
|
||||
}
|
||||
|
||||
// page is a gemtext document being made.
|
||||
type page struct{ strings.Builder }
|
||||
|
||||
// line adds a line of text, made safe: one line, valid UTF-8, and not
|
||||
// taken for a link, heading or preformatting toggle. Quotes (">") and
|
||||
// list items ("* ") are let be: they mean the same in gemtext.
|
||||
func (p *page) line(s string) {
|
||||
s = strings.ToValidUTF8(strings.TrimRight(s, "\r"), "?")
|
||||
s = strings.NewReplacer("\r", " ", "\n", " ").Replace(s)
|
||||
if strings.HasPrefix(s, "=>") || strings.HasPrefix(s, "#") || strings.HasPrefix(s, "```") {
|
||||
s = " " + s
|
||||
}
|
||||
p.WriteString(s + "\n")
|
||||
}
|
||||
|
||||
// heading adds a heading (level 1 to 3).
|
||||
func (p *page) heading(level int, s string) {
|
||||
p.WriteString(strings.Repeat("#", level) + " " + one(s) + "\n")
|
||||
}
|
||||
|
||||
// link adds a link line.
|
||||
func (p *page) link(to, text string) {
|
||||
p.WriteString("=> " + to + " " + one(text) + "\n")
|
||||
}
|
||||
|
||||
// pre adds lines as preformatted text (tables: who is on, a user).
|
||||
func (p *page) pre(alt string, lines []string) {
|
||||
p.WriteString("```" + one(alt) + "\n")
|
||||
for _, l := range lines {
|
||||
l = strings.ToValidUTF8(strings.TrimRight(l, "\r"), "?")
|
||||
if strings.HasPrefix(l, "```") {
|
||||
l = " " + l
|
||||
}
|
||||
p.WriteString(l + "\n")
|
||||
}
|
||||
p.WriteString("```\n")
|
||||
}
|
||||
|
||||
// one is text for a heading or link: one line, valid UTF-8.
|
||||
func one(s string) string {
|
||||
s = strings.ToValidUTF8(s, "?")
|
||||
return strings.Join(strings.Fields(s), " ")
|
||||
}
|
||||
|
||||
// send sends a gemtext page.
|
||||
func (p *page) send(c io.Writer) {
|
||||
header(c, statusOK, "text/gemini; charset=utf-8")
|
||||
io.WriteString(c, p.String())
|
||||
}
|
||||
|
||||
// handle answers one request: it reads the URL and sends what its path
|
||||
// names, or 51 for anything not open to Gemini.
|
||||
func (s *Server) handle(c net.Conn) {
|
||||
req, err := tcpserv.ReadLine(c, MaxRequest+1)
|
||||
if err != nil {
|
||||
if tc, ok := c.(*tls.Conn); ok && tc.ConnectionState().HandshakeComplete {
|
||||
header(c, statusBad, "Bad request")
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(req) > MaxRequest || !utf8.ValidString(req) {
|
||||
header(c, statusBad, "Bad request")
|
||||
return
|
||||
}
|
||||
u, err := url.Parse(req)
|
||||
if err != nil || !u.IsAbs() || u.Host == "" || u.User != nil || u.Fragment != "" {
|
||||
header(c, statusBad, "Bad request")
|
||||
return
|
||||
}
|
||||
if !strings.EqualFold(u.Scheme, "gemini") {
|
||||
header(c, statusNoProxy, "Only gemini:// is served here")
|
||||
return
|
||||
}
|
||||
p := u.Path
|
||||
if p == "" {
|
||||
header(c, statusRedirect, "/")
|
||||
return
|
||||
}
|
||||
if p != "/" && strings.HasSuffix(p, "/") {
|
||||
header(c, statusRedirect, strings.TrimRight(p, "/"))
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.Trim(p, "/"), "/")
|
||||
id := func(i int) int64 {
|
||||
if i >= len(parts) {
|
||||
return 0
|
||||
}
|
||||
n, err := strconv.ParseInt(parts[i], 10, 64)
|
||||
if err != nil || n < 1 {
|
||||
return -1
|
||||
}
|
||||
return n
|
||||
}
|
||||
switch {
|
||||
case p == "/":
|
||||
s.root(c)
|
||||
case p == "/about":
|
||||
s.about(c)
|
||||
case p == "/who":
|
||||
s.who(c)
|
||||
case p == "/users" && s.S.Users:
|
||||
s.user(c, u.RawQuery)
|
||||
case strings.HasPrefix(p, "/~") && len(parts) == 1 && s.S.Users:
|
||||
s.user(c, url.QueryEscape(parts[0][1:]))
|
||||
case p == "/areas" && s.S.Areas != "":
|
||||
s.areas(c)
|
||||
case parts[0] == "area" && (len(parts) == 2 || len(parts) == 3):
|
||||
if a := s.g.Area(id(1)); a != nil && id(2) >= 0 {
|
||||
s.messages(c, a, id(2))
|
||||
return
|
||||
}
|
||||
notFound(c)
|
||||
case parts[0] == "msg" && len(parts) == 2:
|
||||
s.message(c, id(1))
|
||||
case p == "/files" && s.S.Files:
|
||||
s.fileAreas(c)
|
||||
case parts[0] == "files" && len(parts) == 2 && s.S.Files:
|
||||
s.files(c, id(1))
|
||||
case parts[0] == "file" && (len(parts) == 2 || len(parts) == 3) && s.S.Files:
|
||||
s.download(c, id(1))
|
||||
default:
|
||||
notFound(c)
|
||||
}
|
||||
}
|
||||
|
||||
func notFound(c io.Writer) { header(c, statusNotFound, "Not here") }
|
||||
|
||||
// root is the capsule's home: the system's name and where it is, about
|
||||
// and who's online, users, and the areas where they are shown.
|
||||
func (s *Server) root(c io.Writer) {
|
||||
var p page
|
||||
p.heading(1, s.B.Conf().Name)
|
||||
if s.B.Conf().Location != "" {
|
||||
p.line(s.B.Conf().Location)
|
||||
}
|
||||
p.line("")
|
||||
p.link("/about", "About this system")
|
||||
p.link("/who", "Who's online")
|
||||
if s.S.Users {
|
||||
p.link("/users", "Look up a user")
|
||||
}
|
||||
if s.S.Areas != "" {
|
||||
p.link("/areas", "Message areas")
|
||||
}
|
||||
if s.S.Files && s.B.Files != nil {
|
||||
p.link("/files", "File areas")
|
||||
}
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// about is gopher's About this system.
|
||||
func (s *Server) about(c io.Writer) {
|
||||
var p page
|
||||
p.heading(1, "About "+s.B.Conf().Name)
|
||||
for _, l := range s.g.About() {
|
||||
p.line(l)
|
||||
}
|
||||
p.line("")
|
||||
p.link("/", "Back")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// who is gopher's Who's online, as a table.
|
||||
func (s *Server) who(c io.Writer) {
|
||||
var p page
|
||||
p.heading(1, "Who's online")
|
||||
w := s.g.Who()
|
||||
if len(w) == 1 {
|
||||
p.line(w[0])
|
||||
} else {
|
||||
p.pre("who is on", w)
|
||||
}
|
||||
p.line("")
|
||||
p.link("/", "Back")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// user asks for a name (an empty query), or tells finger's answer for it.
|
||||
func (s *Server) user(c io.Writer, query string) {
|
||||
name, err := url.QueryUnescape(query)
|
||||
if err != nil {
|
||||
header(c, statusBad, "Bad request")
|
||||
return
|
||||
}
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
header(c, statusInput, "User name")
|
||||
return
|
||||
}
|
||||
var p page
|
||||
p.heading(1, name)
|
||||
p.pre("user", s.f.User(name))
|
||||
p.line("")
|
||||
p.link("/users", "Look up another")
|
||||
p.link("/", "Back")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// areas lists the message areas Gemini shows.
|
||||
func (s *Server) areas(c io.Writer) {
|
||||
as, _ := s.B.Store.Areas()
|
||||
var p page
|
||||
p.heading(1, "Message areas of "+s.B.Conf().Name)
|
||||
for _, a := range as {
|
||||
if s.g.Area(a.ID) != nil {
|
||||
p.link(fmt.Sprintf("/area/%d", a.ID), fmt.Sprintf("%s (%d): %s", a.Name, a.Messages, a.Description))
|
||||
}
|
||||
}
|
||||
p.line("")
|
||||
p.link("/", "Back")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// messages lists an area's messages after one id, oldest first.
|
||||
func (s *Server) messages(c io.Writer, a *store.Area, after int64) {
|
||||
ms, _ := s.B.Store.Messages(a.ID, after, gopher.PerPage)
|
||||
var p page
|
||||
p.heading(1, a.Name)
|
||||
if a.Description != "" {
|
||||
p.line(a.Description)
|
||||
}
|
||||
p.line("")
|
||||
for _, m := range ms {
|
||||
p.link(fmt.Sprintf("/msg/%d", m.ID), fmt.Sprintf("#%d %s (%s, %s)", m.ID, bbs.Trunc(m.Subject, 60),
|
||||
bbs.Trunc(m.From, 30), m.Created.Format("2006-01-02")))
|
||||
}
|
||||
if len(ms) == 0 {
|
||||
p.line("(no messages)")
|
||||
}
|
||||
if len(ms) == gopher.PerPage {
|
||||
p.link(fmt.Sprintf("/area/%d/%d", a.ID, ms[len(ms)-1].ID), "More...")
|
||||
}
|
||||
p.line("")
|
||||
p.link("/areas", "Message areas")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// message sends a message, its headers first, if its area is shown.
|
||||
func (s *Server) message(c io.Writer, id int64) {
|
||||
if id < 1 {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
m, err := s.B.Store.Message(id)
|
||||
if err != nil {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
a := s.g.Area(m.AreaID)
|
||||
if a == nil {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
var p page
|
||||
p.heading(1, m.Subject)
|
||||
p.line("From: " + m.From)
|
||||
p.line("To: " + m.To)
|
||||
p.line("Date: " + m.Created.Format("2006-01-02 15:04"))
|
||||
p.line("")
|
||||
for _, l := range strings.Split(m.Body, "\n") {
|
||||
p.line(l)
|
||||
}
|
||||
p.line("")
|
||||
p.link(fmt.Sprintf("/area/%d", a.ID), "Back to "+a.Name)
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// fileAreas lists the file areas anyone may download from.
|
||||
func (s *Server) fileAreas(c io.Writer) {
|
||||
if s.B.Files == nil {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
fas, _ := s.B.Store.FileAreas()
|
||||
var p page
|
||||
p.heading(1, "File areas of "+s.B.Conf().Name)
|
||||
for _, fa := range fas {
|
||||
if gopher.OpenFiles(fa) {
|
||||
p.link(fmt.Sprintf("/files/%d", fa.ID), fmt.Sprintf("%s (%d): %s", fa.Name, fa.Files, fa.Description))
|
||||
}
|
||||
}
|
||||
p.line("")
|
||||
p.link("/", "Back")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// fileArea is the file area of the id, if Gemini shows it (nil: not).
|
||||
func (s *Server) fileArea(id int64) *store.FileArea {
|
||||
if s.B.Files == nil || id < 1 {
|
||||
return nil
|
||||
}
|
||||
fa, err := s.B.Store.FileArea(id)
|
||||
if err != nil || !gopher.OpenFiles(fa) {
|
||||
return nil
|
||||
}
|
||||
return fa
|
||||
}
|
||||
|
||||
// files lists a file area's files. Links end in the file's name, so
|
||||
// clients save it by that name.
|
||||
func (s *Server) files(c io.Writer, id int64) {
|
||||
fa := s.fileArea(id)
|
||||
if fa == nil {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
fs, _ := s.B.Store.Files(fa.ID)
|
||||
var p page
|
||||
p.heading(1, fa.Name)
|
||||
if fa.Description != "" {
|
||||
p.line(fa.Description)
|
||||
}
|
||||
p.line("")
|
||||
for _, f := range fs {
|
||||
p.link(fmt.Sprintf("/file/%d/%s", f.ID, url.PathEscape(f.Name)),
|
||||
fmt.Sprintf("%s (%s): %s", f.Name, size(f.Size), bbs.Trunc(f.Description, 50)))
|
||||
}
|
||||
if len(fs) == 0 {
|
||||
p.line("(no files)")
|
||||
}
|
||||
p.line("")
|
||||
p.link("/files", "File areas")
|
||||
p.send(c)
|
||||
}
|
||||
|
||||
// size is a file's size for people.
|
||||
func size(n int64) string {
|
||||
switch {
|
||||
case n >= 1<<20:
|
||||
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
|
||||
case n >= 1<<10:
|
||||
return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
|
||||
}
|
||||
return fmt.Sprintf("%d bytes", n)
|
||||
}
|
||||
|
||||
// mimeType is what a file is, by its name.
|
||||
func mimeType(name string) string {
|
||||
switch strings.ToLower(path.Ext(name)) {
|
||||
case ".txt", ".nfo", ".diz", ".asc", ".ans":
|
||||
return "text/plain"
|
||||
case ".gmi":
|
||||
return "text/gemini"
|
||||
}
|
||||
if t := mime.TypeByExtension(path.Ext(name)); t != "" {
|
||||
return t
|
||||
}
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
// download sends a file's bytes as they are, if its area is Gemini's,
|
||||
// counting a download if all of it went.
|
||||
func (s *Server) download(c io.Writer, id int64) {
|
||||
if s.B.Files == nil || id < 1 {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
f, err := s.B.Store.FileByID(id)
|
||||
if err != nil || s.fileArea(f.AreaID) == nil {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
r, err := s.B.Files.OpenFile(f)
|
||||
if err != nil {
|
||||
notFound(c)
|
||||
return
|
||||
}
|
||||
defer r.Close()
|
||||
header(c, statusOK, mimeType(f.Name))
|
||||
if n, err := io.Copy(c, r); err == nil && n == f.Size {
|
||||
s.B.Store.CountDownload(f.ID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/files"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
type site struct {
|
||||
b *bbs.BBS
|
||||
addr string
|
||||
file *store.File
|
||||
}
|
||||
|
||||
// setup is a Gemini server on a new BBS, with a certificate made for it,
|
||||
// serving until the test ends: areas General and Private with a message
|
||||
// each, a file area with a binary file; the message areas shown are those
|
||||
// matching areas, file areas if withFiles.
|
||||
func setup(t *testing.T, areas string, withFiles bool) *site {
|
||||
t.Helper()
|
||||
store.BcryptCost = 4
|
||||
dir := t.TempDir()
|
||||
st, err := store.Open(filepath.Join(dir, "bbs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
b := bbs.New(bbs.Defaults(), st, log.New(&bytes.Buffer{}, "", 0))
|
||||
b.Settings.Name = "Test BBS"
|
||||
u, _ := st.CreateUser("alice", "password1", "", true)
|
||||
pub, _ := st.CreateArea("General", "Talk", false)
|
||||
priv, _ := st.CreateArea("Private", "Members only", false)
|
||||
st.Post(&store.Message{AreaID: pub.ID, FromID: u.ID, From: "alice", To: "All", Subject: "Hello gemini",
|
||||
Body: "First line\n=> gemini://evil.example/ a link\n```\n# not a heading\n> a quote"})
|
||||
st.Post(&store.Message{AreaID: priv.ID, FromID: u.ID, From: "alice", To: "All", Subject: "Secret", Body: "hush"})
|
||||
s := &site{b: b}
|
||||
if b.Files, err = files.Open(st, filepath.Join(dir, "files"), 1<<20, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fa, _ := st.CreateFileArea("Uploads", "Things", false)
|
||||
up, err := b.Files.Upload(u, fa, "readme.bin", "A file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
up.Write([]byte("\x00binary\r\n.\r\n"))
|
||||
if s.file, err = up.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cert, err := LoadCert(filepath.Join(dir, "c.pem"), filepath.Join(dir, "k.pem"), "gemini.test", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go (&Server{B: b, S: Settings{Areas: areas, Files: withFiles, Users: true}}).Serve(ctx, ln, cert)
|
||||
s.addr = ln.Addr().String()
|
||||
return s
|
||||
}
|
||||
|
||||
// get sends a request line and is all that comes back.
|
||||
func (s *site) get(t *testing.T, req string) string {
|
||||
t.Helper()
|
||||
c, err := tls.Dial("tcp", s.addr, &tls.Config{InsecureSkipVerify: true, ServerName: "gemini.test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.Write([]byte(req + "\r\n"))
|
||||
b, _ := io.ReadAll(c)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// url is a request for a path.
|
||||
func (s *site) url(p string) string { return "gemini://" + s.addr + p }
|
||||
|
||||
// TestGemini: the home page, the areas shown (not others), a message whose
|
||||
// lines cannot be taken for links, headings or preformatting, users as
|
||||
// finger tells of them, refusals of what is not shown and of nonsense, a
|
||||
// file sent as it is and counted; and with nothing opened, no areas or
|
||||
// files at all.
|
||||
func TestGemini(t *testing.T) {
|
||||
s := setup(t, "general", true)
|
||||
root := s.get(t, s.url("/"))
|
||||
for _, want := range []string{"20 text/gemini; charset=utf-8\r\n# Test BBS\n", "=> /about About this system\n",
|
||||
"=> /who Who's online\n", "=> /users Look up a user\n", "=> /areas Message areas\n", "=> /files File areas\n"} {
|
||||
if !strings.Contains(root, want) {
|
||||
t.Errorf("root lacks %q:\n%s", want, root)
|
||||
}
|
||||
}
|
||||
if got := s.get(t, s.url("")); got != "31 /\r\n" {
|
||||
t.Errorf("no path: %q", got)
|
||||
}
|
||||
if got := s.get(t, s.url("/areas/")); got != "31 /areas\r\n" {
|
||||
t.Errorf("trailing slash: %q", got)
|
||||
}
|
||||
areas := s.get(t, s.url("/areas"))
|
||||
if !strings.Contains(areas, "=> /area/1 General (1): Talk\n") || strings.Contains(areas, "Private") {
|
||||
t.Errorf("areas:\n%s", areas)
|
||||
}
|
||||
if list := s.get(t, s.url("/area/1")); !strings.Contains(list, "=> /msg/1 #1 Hello gemini (alice, ") {
|
||||
t.Errorf("area:\n%s", list)
|
||||
}
|
||||
msg := s.get(t, s.url("/msg/1"))
|
||||
for _, want := range []string{"# Hello gemini\n", "From: alice\n", "\nFirst line\n => gemini://evil.example/ a link\n ```\n # not a heading\n> a quote\n"} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Errorf("message lacks %q:\n%s", want, msg)
|
||||
}
|
||||
}
|
||||
if got := s.get(t, s.url("/users")); got != "10 User name\r\n" {
|
||||
t.Errorf("users: %q", got)
|
||||
}
|
||||
if got := s.get(t, s.url("/users?alice")); !strings.Contains(got, "User: alice") {
|
||||
t.Errorf("alice:\n%s", got)
|
||||
}
|
||||
if got := s.get(t, s.url("/~alice")); !strings.Contains(got, "User: alice") {
|
||||
t.Errorf("~alice:\n%s", got)
|
||||
}
|
||||
if got := s.get(t, s.url("/users?nobody")); !strings.Contains(got, "No such user here.") {
|
||||
t.Errorf("nobody:\n%s", got)
|
||||
}
|
||||
// the area not opened to Gemini, and nonsense
|
||||
for _, p := range []string{"/msg/2", "/area/2", "/area/1/x", "/msg/-1", "/../../etc/passwd", "/file/99"} {
|
||||
if got := s.get(t, s.url(p)); got != "51 Not here\r\n" {
|
||||
t.Errorf("%s: %q", p, got)
|
||||
}
|
||||
}
|
||||
for _, req := range []string{"/", "gemini://user@" + s.addr + "/", "gemini:///", s.url("/#x"), s.url("/" + strings.Repeat("a", 1100))} {
|
||||
if got := s.get(t, req); !strings.HasPrefix(got, "59 ") {
|
||||
t.Errorf("%.40s: %q", req, got)
|
||||
}
|
||||
}
|
||||
if got := s.get(t, "https://"+s.addr+"/"); !strings.HasPrefix(got, "53 ") {
|
||||
t.Errorf("proxy: %q", got)
|
||||
}
|
||||
files := s.get(t, s.url("/files/1"))
|
||||
if !strings.Contains(files, "=> /file/1/readme.bin readme.bin (12 bytes): A file\n") {
|
||||
t.Errorf("files:\n%s", files)
|
||||
}
|
||||
if got := s.get(t, s.url("/file/1/readme.bin")); got != "20 application/octet-stream\r\n\x00binary\r\n.\r\n" {
|
||||
t.Errorf("download %q", got)
|
||||
}
|
||||
if f, _ := s.b.Store.FileByID(s.file.ID); f.Downloads != 1 {
|
||||
t.Errorf("downloads %d", f.Downloads)
|
||||
}
|
||||
// a restricted file area is not Gemini's
|
||||
s.b.Store.SetFileAreaRequire(s.file.AreaID, "20", "")
|
||||
for _, p := range []string{fmt.Sprintf("/files/%d", s.file.AreaID), fmt.Sprintf("/file/%d", s.file.ID)} {
|
||||
if got := s.get(t, s.url(p)); got != "51 Not here\r\n" {
|
||||
t.Errorf("restricted %s: %q", p, got)
|
||||
}
|
||||
}
|
||||
|
||||
// nothing opened: no areas, no files
|
||||
s = setup(t, "", false)
|
||||
root = s.get(t, s.url("/"))
|
||||
if strings.Contains(root, "Message areas") || strings.Contains(root, "File areas") {
|
||||
t.Errorf("closed root:\n%s", root)
|
||||
}
|
||||
for _, p := range []string{"/areas", "/area/1", "/msg/1", "/files", "/file/1"} {
|
||||
if got := s.get(t, s.url(p)); got != "51 Not here\r\n" {
|
||||
t.Errorf("closed %s: %q", p, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCert: a certificate is made once and then kept; with mk unset, none
|
||||
// is made; a key alone is not overwritten.
|
||||
func TestCert(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
c, k := filepath.Join(dir, "c.pem"), filepath.Join(dir, "k.pem")
|
||||
if _, err := LoadCert(c, k, "bbs.example.org", false); err == nil {
|
||||
t.Error("loaded nothing")
|
||||
}
|
||||
if got := CertInfo(c, true); !strings.Contains(got, "none yet") {
|
||||
t.Errorf("info %q", got)
|
||||
}
|
||||
a, err := LoadCert(c, k, "bbs.example.org", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := LoadCert(c, k, "bbs.example.org", true)
|
||||
if err != nil || !bytes.Equal(a.Certificate[0], b.Certificate[0]) {
|
||||
t.Errorf("made again: %v", err)
|
||||
}
|
||||
if got := CertInfo(c, true); !strings.HasPrefix(got, "bbs.example.org until ") || !strings.Contains(got, "SHA-256 ") {
|
||||
t.Errorf("info %q", got)
|
||||
}
|
||||
if fi, _ := os.Stat(k); fi.Mode().Perm() != 0600 {
|
||||
t.Errorf("key mode %v", fi.Mode())
|
||||
}
|
||||
os.Remove(c)
|
||||
if _, err := LoadCert(c, k, "bbs.example.org", true); err == nil {
|
||||
t.Error("made a certificate for a key left alone")
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -136,13 +136,13 @@ func (s *Server) handle(c net.Conn) {
|
||||
case sel == "" || sel == "/":
|
||||
s.root(c)
|
||||
case parts[0] == "about" && len(parts) == 1:
|
||||
text(c, s.about())
|
||||
text(c, s.About())
|
||||
case parts[0] == "who" && len(parts) == 1:
|
||||
text(c, s.who())
|
||||
text(c, s.Who())
|
||||
case parts[0] == "areas" && len(parts) == 1 && s.S.Areas != "":
|
||||
s.areas(c)
|
||||
case parts[0] == "area" && (len(parts) == 2 || len(parts) == 3):
|
||||
if a := s.area(id(1)); a != nil && id(2) >= 0 {
|
||||
if a := s.Area(id(1)); a != nil && id(2) >= 0 {
|
||||
s.messages(c, a, id(2))
|
||||
return
|
||||
}
|
||||
@@ -179,9 +179,9 @@ func (s *Server) root(c io.Writer) {
|
||||
s.menu(c, items)
|
||||
}
|
||||
|
||||
// about is what the system is: its name, place, sysop, how many users, and
|
||||
// About is what the system is: its name, place, sysop, how many users, and
|
||||
// the message of the day.
|
||||
func (s *Server) about() []string {
|
||||
func (s *Server) About() []string {
|
||||
out := []string{s.B.Conf().Name}
|
||||
if s.B.Conf().Location != "" {
|
||||
out = append(out, s.B.Conf().Location)
|
||||
@@ -199,8 +199,8 @@ func (s *Server) about() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// who is the callers on now, a line each under a heading.
|
||||
func (s *Server) who() []string {
|
||||
// Who is the callers on now, a line each under a heading.
|
||||
func (s *Server) Who() []string {
|
||||
out := []string{fmt.Sprintf("%4s %-24s %-12s %5s %s", "Node", "User", "Via", "On", "Doing")}
|
||||
on := 0
|
||||
for _, n := range s.B.Nodes() {
|
||||
@@ -222,8 +222,8 @@ func (s *Server) open(a *store.Area) bool {
|
||||
return s.S.Areas != "" && news.Wildmat(strings.ToLower(s.S.Areas), strings.ToLower(a.Name))
|
||||
}
|
||||
|
||||
// area is the message area of the id, if gopher shows it (nil: not).
|
||||
func (s *Server) area(id int64) *store.Area {
|
||||
// Area is the message area of the id, if gopher shows it (nil: not).
|
||||
func (s *Server) Area(id int64) *store.Area {
|
||||
if id < 1 {
|
||||
return nil
|
||||
}
|
||||
@@ -271,11 +271,11 @@ func (s *Server) message(c io.Writer, id int64) {
|
||||
return
|
||||
}
|
||||
m, err := s.B.Store.Message(id)
|
||||
if err != nil || s.area(m.AreaID) == nil {
|
||||
if err != nil || s.Area(m.AreaID) == nil {
|
||||
notFound(s, c)
|
||||
return
|
||||
}
|
||||
a := s.area(m.AreaID)
|
||||
a := s.Area(m.AreaID)
|
||||
out := []string{"Area: " + a.Name, "From: " + m.From, "To: " + m.To,
|
||||
"Subject: " + m.Subject, "Date: " + m.Created.Format("2006-01-02 15:04"), ""}
|
||||
out = append(out, strings.Split(m.Body, "\n")...)
|
||||
@@ -292,7 +292,7 @@ func (s *Server) fileAreas(c io.Writer) {
|
||||
fas, _ := s.B.Store.FileAreas()
|
||||
items := []item{{'i', "File areas of " + s.B.Conf().Name, ""}, {'i', "", ""}}
|
||||
for _, fa := range fas {
|
||||
if openFiles(fa) {
|
||||
if OpenFiles(fa) {
|
||||
items = append(items, item{'1', fmt.Sprintf("%s (%d) %s", fa.Name, fa.Files, fa.Description),
|
||||
fmt.Sprintf("/files/%d", fa.ID)})
|
||||
}
|
||||
@@ -300,9 +300,9 @@ func (s *Server) fileAreas(c io.Writer) {
|
||||
s.menu(c, items)
|
||||
}
|
||||
|
||||
// openFiles reports whether a file area is gopher's: gopher has no login,
|
||||
// OpenFiles reports whether a file area is gopher's: gopher has no login,
|
||||
// so only an area anyone may download from (no download requirement).
|
||||
func openFiles(fa *store.FileArea) bool {
|
||||
func OpenFiles(fa *store.FileArea) bool {
|
||||
return bbs.MustRequire(fa.DownloadReq).Allows(nil)
|
||||
}
|
||||
|
||||
@@ -325,7 +325,7 @@ func (s *Server) files(c io.Writer, id int64) {
|
||||
return
|
||||
}
|
||||
fa, err := s.B.Store.FileArea(id)
|
||||
if err != nil || !openFiles(fa) {
|
||||
if err != nil || !OpenFiles(fa) {
|
||||
notFound(s, c)
|
||||
return
|
||||
}
|
||||
@@ -353,7 +353,7 @@ func (s *Server) download(c io.Writer, id int64) {
|
||||
notFound(s, c)
|
||||
return
|
||||
}
|
||||
if fa, err := s.B.Store.FileArea(f.AreaID); err != nil || !openFiles(fa) {
|
||||
if fa, err := s.B.Store.FileArea(f.AreaID); err != nil || !OpenFiles(fa) {
|
||||
notFound(s, c)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -97,6 +97,9 @@ func Bind(cfg *Config) ([]sockets.Socket, error) {
|
||||
if cfg.Gopher != nil {
|
||||
addrs = append(addrs, cfg.Gopher.Address)
|
||||
}
|
||||
if cfg.Gemini != nil {
|
||||
addrs = append(addrs, cfg.Gemini.Address)
|
||||
}
|
||||
if cfg.Binkp != nil {
|
||||
addrs = append(addrs, cfg.Binkp.Address)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/D-Modem/bbs/internal/fido"
|
||||
"github.com/D-Modem/bbs/internal/finger"
|
||||
"github.com/D-Modem/bbs/internal/ftp"
|
||||
"github.com/D-Modem/bbs/internal/gemini"
|
||||
"github.com/D-Modem/bbs/internal/gopher"
|
||||
"github.com/D-Modem/bbs/internal/guard"
|
||||
"github.com/D-Modem/bbs/internal/imageboard"
|
||||
@@ -78,6 +79,7 @@ type Config struct {
|
||||
HTTP *api.Settings // nil: no HTTP API
|
||||
Chan imageboard.Settings
|
||||
Gopher *gopher.Settings // nil: no gopher server
|
||||
Gemini *gemini.Settings // nil: no Gemini server
|
||||
Time *TimeSettings // nil: no [time], [ntp], [nts] or [ptp]
|
||||
Database string
|
||||
Log string // syslog, stderr, none, or a file
|
||||
@@ -233,7 +235,7 @@ func load(cf *config.File) (*Config, error) {
|
||||
}
|
||||
for _, s := range cf.Sections {
|
||||
switch s.Kind {
|
||||
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "time", "ntp", "nts", "ptp", "irc", "oscar", "aol", "msn", "mrc", "irclink", "ircpeer", "menu", "strings", "http", "level", "chan",
|
||||
case "general", "security", "backup", "modemmenu", "event", "listen", "ftp", "news", "nntp", "peer", "qwknet", "fido", "binkp", "link", "door", "finger", "gopher", "gemini", "time", "ntp", "nts", "ptp", "irc", "oscar", "aol", "msn", "mrc", "irclink", "ircpeer", "menu", "strings", "http", "level", "chan",
|
||||
"mail", "smarthost", "pop3", "imap", "smtp", "mx", "lmtp":
|
||||
default:
|
||||
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/config"
|
||||
"github.com/D-Modem/bbs/internal/finger"
|
||||
"github.com/D-Modem/bbs/internal/gemini"
|
||||
"github.com/D-Modem/bbs/internal/gopher"
|
||||
)
|
||||
|
||||
// infoSections reads [finger] and [gopher].
|
||||
// infoSections reads [finger], [gopher] and [gemini].
|
||||
func (c *Config) infoSections(cf *config.File) error {
|
||||
var err error
|
||||
if s := cf.Get("finger", ""); s != nil {
|
||||
@@ -60,5 +63,39 @@ func (c *Config) infoSections(cf *config.File) error {
|
||||
}
|
||||
c.Gopher = g
|
||||
}
|
||||
if s := cf.Get("gemini", ""); s != nil {
|
||||
g := &gemini.Settings{Address: s.String("address", ":1965")}
|
||||
if _, _, err := net.SplitHostPort(g.Address); err != nil {
|
||||
return fmt.Errorf("[gemini] address: %v", err)
|
||||
}
|
||||
host, _ := os.Hostname()
|
||||
g.Host = s.String("hostname", host)
|
||||
g.CertFile, g.KeyFile = s.String("cert_file", ""), s.String("key_file", "")
|
||||
switch {
|
||||
case g.CertFile == "" && g.KeyFile == "":
|
||||
g.CertFile = filepath.Join(c.DataDir(), "gemini-cert.pem")
|
||||
g.KeyFile = filepath.Join(c.DataDir(), "gemini-key.pem")
|
||||
g.MakeCert = true
|
||||
case g.CertFile == "" || g.KeyFile == "":
|
||||
return errors.New("[gemini] cert_file and key_file go together (or neither, for a certificate made here)")
|
||||
}
|
||||
g.Areas = s.String("areas", "")
|
||||
if g.Files, err = s.Bool("files", false); err != nil {
|
||||
return fmt.Errorf("[gemini] %w", err)
|
||||
}
|
||||
if g.Users, err = s.Bool("users", true); err != nil {
|
||||
return fmt.Errorf("[gemini] %w", err)
|
||||
}
|
||||
if g.MaxClients, err = s.Int("max_clients", 32, 1, 1000); err != nil {
|
||||
return fmt.Errorf("[gemini] %w", err)
|
||||
}
|
||||
if g.MaxPerIP, err = s.Int("max_per_ip", 8, 0, 1000); err != nil {
|
||||
return fmt.Errorf("[gemini] %w", err)
|
||||
}
|
||||
if g.Areas != "" || g.Files {
|
||||
c.Warnings = append(c.Warnings, "[gemini] shows message or file areas to anyone, without a login")
|
||||
}
|
||||
c.Gemini = g
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -46,11 +46,25 @@ files = yes
|
||||
if err != nil || c.Gopher.Port != 70 || c.Gopher.Areas != "" || c.Gopher.Files {
|
||||
t.Errorf("defaults %+v %v", c.Gopher, err)
|
||||
}
|
||||
c, err = load("[general]\ndatabase = /var/lib/bbs/bbs.db\n[gemini]\nareas = *\n")
|
||||
if g := c.Gemini; err != nil || g.Address != ":1965" || !g.MakeCert || !g.Users || g.Areas != "*" ||
|
||||
g.CertFile != "/var/lib/bbs/gemini-cert.pem" || g.KeyFile != "/var/lib/bbs/gemini-key.pem" {
|
||||
t.Errorf("gemini %+v %v", g, err)
|
||||
}
|
||||
if !strings.Contains(strings.Join(c.Warnings, "\n"), "[gemini] shows message or file areas to anyone") {
|
||||
t.Errorf("no gemini warning: %v", c.Warnings)
|
||||
}
|
||||
c, err = load("[gemini]\naddress = :1966\ncert_file = /etc/c.pem\nkey_file = /etc/k.pem\nusers = no\n")
|
||||
if g := c.Gemini; err != nil || g.MakeCert || g.Users || g.CertFile != "/etc/c.pem" || len(c.Warnings) != 0 {
|
||||
t.Errorf("gemini %+v %v %v", g, err, c.Warnings)
|
||||
}
|
||||
for body, want := range map[string]string{
|
||||
"[finger]\naddress = 79\n": "[finger] address",
|
||||
"[gopher]\nport = 0\n": "[gopher]",
|
||||
"[general]\npage_command = 'x\n": "page_command",
|
||||
"[general]\nqwk_id = too-long-id\n": "qwk_id",
|
||||
"[finger]\naddress = 79\n": "[finger] address",
|
||||
"[gemini]\ncert_file = /etc/c.pem\n": "[gemini] cert_file",
|
||||
"[gemini]\naddress = x\n": "[gemini] address",
|
||||
"[gopher]\nport = 0\n": "[gopher]",
|
||||
"[general]\npage_command = 'x\n": "page_command",
|
||||
"[general]\nqwk_id = too-long-id\n": "qwk_id",
|
||||
} {
|
||||
if _, err := load(body); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%q: %v", body, err)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Package tcpserv serves small one-question protocols (finger, gopher):
|
||||
// Package tcpserv serves small one-question protocols (finger, gopher, Gemini):
|
||||
// connections limited at once and from one address, each with a time
|
||||
// limit, a panic in one not taking the rest down.
|
||||
package tcpserv
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ nav:
|
||||
- "AIM and ICQ": AIM-and-ICQ.md
|
||||
- "MSN Messenger": MSN-Messenger.md
|
||||
- "MRC": MRC.md
|
||||
- "Finger and gopher": Finger-and-Gopher.md
|
||||
- "Finger, gopher and Gemini": Finger-and-Gopher.md
|
||||
- "Time: NTP, NTS and PTP": Time.md
|
||||
- "Web forum": Web-Forum.md
|
||||
- "Image boards": Image-Boards.md
|
||||
|
||||
Reference in new issue
Block a user