code.pablomurad.com

bbs-hammer

SSH BBS with forums, chat, door games, retro terminals and a weather service, written in Go

internal/bbs/server.go raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package bbs

import (
	"crypto/ed25519"
	"crypto/rand"
	"encoding/pem"
	"errors"
	"fmt"
	"log"
	"net"
	"os"
	"path/filepath"
	"time"

	"github.com/gliderlabs/ssh"
	gossh "golang.org/x/crypto/ssh"

	"github.com/runawaydevil/hammer/internal/awards"
	"github.com/runawaydevil/hammer/internal/community"
	"github.com/runawaydevil/hammer/internal/dispatch"
	"github.com/runawaydevil/hammer/internal/domain"
	"github.com/runawaydevil/hammer/internal/door"
	"github.com/runawaydevil/hammer/internal/forum"
	"github.com/runawaydevil/hammer/internal/jobs"
	"github.com/runawaydevil/hammer/internal/localization"
	"github.com/runawaydevil/hammer/internal/mrc"
	"github.com/runawaydevil/hammer/internal/postcards"
	"github.com/runawaydevil/hammer/internal/radio"
	"github.com/runawaydevil/hammer/internal/ratelimit"
	"github.com/runawaydevil/hammer/internal/tools"
	"github.com/runawaydevil/hammer/internal/weather"
)

const (
	idleTimeout = 5 * time.Minute
	maxTimeout  = 30 * time.Minute
)

type ipDataLocator interface {
	GetIPData(ip string) (*domain.IPData, error)
}

type fingerprintKey struct{}

type Server struct {
	cfg       *Config
	adapter   *WeatherAdapter
	almanacs  almanacCache
	store     *ProfileStore
	ip        ipDataLocator
	tools     *tools.Registry
	langs     []localization.Info
	localizer localization.Localizer
	storage   *storageAccountant
	conns     *connLimiter
	purgeTTL  time.Duration
	catalog   *dispatch.Catalog
	jobs      *jobs.Manager
	calls     *ratelimit.Limiter // tool calls per identity (dispatcher)

	arts *artLibrary

	communityCfg communitySettings
	presence     *community.Presence
	wall         *community.Wall
	chat         *community.Hub
	cstore       *community.Store // bans, chat log, last callers
	forums       *forum.Store

	doors       []*doorEntry   // the [d] menu; empty when none can run
	linecast    *linecastSetup // [k] sky & almanac; nil when off
	radio       *radio.Client  // [o] on the air; nil when off
	radioCfg    *RadioConfig
	radioFavs   *radio.Favorites
	radioPicks  *radio.Picks
	npLimit     npLimiter
	dosbox      string             // the DOSBox program, "" when DOS doors are off
	doorServers *DoorServersConfig // credentials for remote door servers
	mrc         *mrc.Client        // the inter-BBS chat; nil when off
	fido        *fidoNode          // the FidoNet node; nil when off
	qwk         *qwkNode           // the QWK node; nil when off
	live        liveStreams        // open /:live event streams
	awards      *awards.Store      // nil when bbs.awards is off
	postcards   *postcards.Store   // nil when bbs.postcards is off
	pngCache    pngCache           // rendered postcards

	games     *gamesSettings // nil when games are off or the door is missing
	gameSlots *door.Slots    // nodes, one per person playing
}

func New(cfg *Config, ws *weather.WeatherService, ip ipDataLocator) (*Server, error) {
	if err := cfg.Validate(); err != nil {
		return nil, fmt.Errorf("bbs config: %w", err)
	}

	store, err := NewProfileStore(cfg.ProfilesDB)
	if err != nil {
		return nil, fmt.Errorf("bbs profiles db: %w", err)
	}

	var langs []localization.Info
	var loc localization.Localizer
	if ws != nil && ws.Localizer != nil {
		langs = ws.Localizer.Languages()
		loc = ws.Localizer
	}

	s, err := newServer(cfg, NewWeatherAdapter(ws, ws.Locator), store, ip)
	if err != nil {
		store.Close()

		return nil, err
	}
	s.langs, s.localizer = langs, loc

	return s, nil
}

// newServer wires everything except the localizer; tests build servers with
// it directly around fake weather and a temporary profile store.
func newServer(cfg *Config, adapter *WeatherAdapter, store *ProfileStore, ip ipDataLocator) (*Server, error) {
	reg := tools.NewRegistry(cfg.toolsConfig())
	s := &Server{
		cfg:      cfg,
		adapter:  adapter,
		store:    store,
		ip:       ip,
		tools:    reg,
		storage:  newStorageAccountant(cfg.QuotaBytes(), cfg.FilesDir()),
		conns:    newConnLimiter(cfg.MaxConnectionsPerIP()),
		purgeTTL: cfg.QuotaTTL(),
		jobs:     jobs.New(cfg.jobsConfig()),
		calls:    ratelimit.New(cfg.DispatchLimits()),
	}

	s.arts = loadArtLibrary()
	s.communityCfg = cfg.community()
	s.presence = community.NewPresence()
	cst, err := community.NewStore(store.SQL())
	if err != nil {
		return nil, fmt.Errorf("community store: %w", err)
	}
	cc := s.communityCfg
	s.cstore = cst
	s.wall = community.NewWall(cst, cc.wallMaxLen, cc.wallCooldown)
	s.chat = community.NewHub(cst, cc.chatMaxLen, cc.chatPerMinute, cc.chatBurst)
	s.chat.SetKeep(cc.chatKeep)
	if s.forums, err = openForums(store.SQL(), cfg.Forums); err != nil {
		return nil, fmt.Errorf("forums: %w", err)
	}
	if cfg.PostcardsEnabled() {
		if s.postcards, err = postcards.NewStore(store.SQL()); err != nil {
			return nil, fmt.Errorf("postcards: %w", err)
		}
	}
	if cfg.Awards != nil && cfg.Awards.Enabled {
		if s.awards, err = awards.NewStore(store.SQL()); err != nil {
			return nil, fmt.Errorf("awards: %w", err)
		}
	}
	if cfg.RadioEnabled() {
		s.radioCfg = cfg.Radio
		s.radio = radio.New(cfg.Radio.API, radioUserAgent, nil)
		if s.radioFavs, err = radio.NewFavorites(store.SQL()); err != nil {
			return nil, fmt.Errorf("radio: %w", err)
		}
		if s.radioPicks, err = radio.NewPicks(store.SQL()); err != nil {
			return nil, fmt.Errorf("radio: %w", err)
		}
	}

	s.setGames(resolveGames(cfg.Games))
	s.dosbox = resolveDOSBox(cfg.DOSBox)
	s.doorServers = cfg.DoorServers
	s.doors = s.resolveDoors(cfg.Doors)
	s.linecast = resolveLinecast(cfg.Linecast)
	s.mrc = newMRC(cfg.MRC)
	if s.fido, err = newFidoNode(cfg.Echomail, s.forums, cfg.Version); err != nil {
		return nil, fmt.Errorf("echomail: %w", err)
	}
	if s.qwk, err = newQWKNode(cfg.Echomail, s.forums); err != nil {
		return nil, fmt.Errorf("echomail: %w", err)
	}

	catalog, err := dispatch.NewCatalog(s.dispatchTools()...)
	if err != nil {
		return nil, err
	}
	s.catalog = catalog

	return s, nil
}

func (s *Server) sshServer() (*ssh.Server, error) {
	signer, err := s.hostKey()
	if err != nil {
		return nil, fmt.Errorf("bbs host key: %w", err)
	}

	srv := &ssh.Server{
		Addr:        fmt.Sprintf(":%d", s.cfg.ListenPort()),
		Handler:     s.handleSession,
		IdleTimeout: idleTimeout,
		MaxTimeout:  maxTimeout,
		PublicKeyHandler: func(ctx ssh.Context, key ssh.PublicKey) bool {
			ctx.SetValue(fingerprintKey{}, gossh.FingerprintSHA256(key))

			return true
		},
		SubsystemHandlers: map[string]ssh.SubsystemHandler{
			"sftp": s.handleSFTP,
		},
	}

	// Keyless entry: when anonymous access is on, accept keyboard-interactive
	// and password auth with no challenge, so `ssh -p PORT guest@host` gets in
	// without a key. PublicKeyHandler stays, so keyed clients are unchanged.
	if s.cfg.IsAnonymousAllowed() {
		srv.KeyboardInteractiveHandler = func(ssh.Context, gossh.KeyboardInteractiveChallenge) bool {
			return true
		}
		srv.PasswordHandler = func(ssh.Context, string) bool {
			return true
		}
	}

	srv.AddHostKey(signer)

	return srv, nil
}

func (s *Server) ListenAndServe() error {
	srv, err := s.sshServer()
	if err != nil {
		return err
	}

	go s.sweepStorageLoop()
	s.startMRC()
	s.startFidoNet()
	s.startQWK()
	s.startFTP()
	s.startPETSCII()

	if port := s.cfg.rloginPort(); port > 0 {
		go func() {
			if err := s.listenRlogin(port); err != nil {
				log.Println("bbs: rlogin:", err)
			}
		}()
	}
	if port := s.cfg.telnetPort(); port > 0 {
		go func() {
			if err := s.listenTelnet(port); err != nil {
				log.Println("bbs: telnet:", err)
			}
		}()
	}

	log.Printf("hammer listening on %s\n", srv.Addr)

	return srv.ListenAndServe()
}

// sweepStorageLoop purges files older than the storage TTL every minute, which
// is what drains the global quota.
func (s *Server) sweepStorageLoop() {
	_ = os.MkdirAll(s.cfg.FilesDir(), 0o700)

	s.storage.sweep(s.purgeTTL, time.Now())
	t := time.NewTicker(time.Minute)
	defer t.Stop()

	for range t.C {
		s.storage.sweep(s.purgeTTL, time.Now())
	}
}

func (s *Server) hostKey() (ssh.Signer, error) {
	data, err := os.ReadFile(s.cfg.HostKeyPath)
	if err != nil {
		if !errors.Is(err, os.ErrNotExist) {
			return nil, err
		}

		data, err = generateHostKey(s.cfg.HostKeyPath)
		if err != nil {
			return nil, err
		}
	}

	return gossh.ParsePrivateKey(data)
}

func generateHostKey(path string) ([]byte, error) {
	_, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		return nil, err
	}

	block, err := gossh.MarshalPrivateKey(priv, "")
	if err != nil {
		return nil, err
	}

	data := pem.EncodeToMemory(block)

	if dir := filepath.Dir(path); dir != "" && dir != "." {
		if err := os.MkdirAll(dir, 0o700); err != nil {
			return nil, err
		}
	}

	if err := os.WriteFile(path, data, 0o600); err != nil {
		return nil, err
	}

	return data, nil
}

func (s *Server) geoCity(remoteAddr string) string {
	if s.ip == nil {
		return ""
	}

	host, _, err := net.SplitHostPort(remoteAddr)
	if err != nil {
		host = remoteAddr
	}

	data, err := s.ip.GetIPData(host)
	if err != nil || data == nil {
		return ""
	}

	return data.City
}

// defaultProfile is what a new identity starts with, seeded with the city
// GeoIP guesses for the connecting address.
func (s *Server) defaultProfile(identity, remoteAddr string) *Profile {
	p := &Profile{
		Fingerprint: identity,
		Units:       "m",
		Lang:        "en",
		View:        "card",
		Emoji:       "unicode",
	}
	if city := s.geoCity(remoteAddr); city != "" {
		p.DefaultCity = city
		p.Cities = city
	}

	return p
}

// loadOrCreateProfile returns identity's saved profile, creating it on first
// use. Anonymous identities get a fresh profile that is never stored. A
// profile without a nickname (new, or saved before nicknames existed) gets
// one, suggested by the SSH user name.
func (s *Server) loadOrCreateProfile(identity, remoteAddr, sshUser string) (*Profile, error) {
	if isAnonymous(identity) {
		p := s.defaultProfile(identity, remoteAddr)
		s.assignNick(p, sshUser)

		return p, nil
	}

	p, err := s.store.Get(identity)
	switch {
	case errors.Is(err, ErrProfileNotFound):
		p = s.defaultProfile(identity, remoteAddr)
	case err != nil:
		return nil, err
	case p.Nick != "":
		return p, nil
	}

	s.assignNick(p, sshUser)
	if err := s.store.Save(p); errors.Is(err, ErrNickTaken) {
		// Lost a race for the name: fall back to the guest name, widened.
		p.Nick = ""
		s.assignNick(p, "")
		err = s.store.Save(p)
		if err != nil {
			return nil, err
		}
	} else if err != nil {
		return nil, err
	}

	return p, nil
}

func (s *Server) Close() error {
	s.jobs.Close()
	if s.mrc != nil {
		s.mrc.Close()
	}
	if s.fido != nil {
		s.fido.close()
	}
	if s.qwk != nil {
		s.qwk.close()
	}

	return s.store.Close()
}