aboutsummaryrefslogtreecommitdiff
path: root/internal/net/server.go
blob: 731beef2164dcf3d3401a8b7685fa64a25e84b43 (plain)
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
409
410
411
412
413
package net

import (
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"net/http"
	"sync"

	"thehouseoficarus/internal/behavior"
	"thehouseoficarus/internal/color"
	"thehouseoficarus/internal/config"
	"thehouseoficarus/internal/player"
)

type SessionState int

const (
	StateAccountName SessionState = iota
	StatePassword
	StateNewAccountPass
	StateNewAccount
	StateMenu
	StateNewCharName
	StateNewCharConfirm
	StateRenameAccount
	StateRenameChar
	StateRenameCharName
	StateDeleteChar
	StatePurgeAccount
	StateGame
	StateChangeDesc
	StateTalk
	StateTalkSequence
	StateDropAllConfirm
	StateRecipeChoice
	StateHowMany
	StateSmithProduct
	StateFletchProduct
	StateCraftProduct
	StateProductChoice
	StateColorChoice
	StateShop
	StateBank
	StateHacking
	StateDangerConfirm
)

type Session struct {
	Conn              Conn
	State             SessionState
	Account           *player.Account
	Player            *player.Player
	PendingChar       string
	PendingPass       string
	PendingMenu       []map[string]string
	PendingItemID     string
	PendingSkill      string
	PendingLastFlag   string
	PendingBackground bool
	Disconnecting     bool
	DisconnectTicks   int
	Shop              *behavior.ShopConfig
	promptVisible     bool
	writeMu           sync.Mutex
}

type Server struct {
	config      *config.Config
	telnetLn    net.Listener
	telnetTLSLn net.Listener
	httpServer  *http.Server
	httpsServer *http.Server
	hub         *Hub
	handler     func(*Session, string)
}

type Hub struct {
	mu       sync.Mutex
	sessions map[*Session]bool
	rooms    map[int]map[*Session]bool
	onRemove func(*Session)
}

func NewHub() *Hub {
	return &Hub{
		sessions: make(map[*Session]bool),
		rooms:    make(map[int]map[*Session]bool),
	}
}

func (h *Hub) OnRemove(cb func(*Session)) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.onRemove = cb
}

func (h *Hub) Add(s *Session) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.sessions[s] = true
}

func (h *Hub) Remove(s *Session) {
	h.mu.Lock()
	defer h.mu.Unlock()
	if s.Player != nil && s.State == StateGame && !s.Disconnecting {
		s.Disconnecting = true
		s.DisconnectTicks = 10
		return
	}
	h.hardRemoveLocked(s)
}

func (h *Hub) HardRemove(s *Session) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.hardRemoveLocked(s)
}

func (h *Hub) hardRemoveLocked(s *Session) {
	delete(h.sessions, s)
	for _, room := range h.rooms {
		delete(room, s)
	}
	if h.onRemove != nil {
		h.onRemove(s)
	}
}

func (h *Hub) EnterRoom(s *Session, roomID int) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.leaveRoomLocked(s)
	if h.rooms[roomID] == nil {
		h.rooms[roomID] = make(map[*Session]bool)
	}
	h.rooms[roomID][s] = true
}

func (h *Hub) LeaveRoom(s *Session) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.leaveRoomLocked(s)
}

func (h *Hub) leaveRoomLocked(s *Session) {
	for _, room := range h.rooms {
		delete(room, s)
	}
}

func (h *Hub) AllSessions() []*Session {
	h.mu.Lock()
	defer h.mu.Unlock()
	var out []*Session
	for s := range h.sessions {
		out = append(out, s)
	}
	return out
}

func (h *Hub) PlayersInRoom(roomID int) []*Session {
	h.mu.Lock()
	defer h.mu.Unlock()
	var out []*Session
	if room, ok := h.rooms[roomID]; ok {
		for s := range room {
			out = append(out, s)
		}
	}
	return out
}

func NewServer(cfg *config.Config) (*Server, error) {
	s := &Server{
		config: cfg,
		hub:    NewHub(),
	}

	if cfg.Telnet.Enabled {
		addr := fmt.Sprintf(":%d", cfg.Telnet.Port)
		ln, err := net.Listen("tcp", addr)
		if err != nil {
			return nil, fmt.Errorf("telnet listen: %w", err)
		}
		s.telnetLn = ln
	}

	if cfg.TelnetTLS.Enabled {
		if cfg.TelnetTLS.CertFile == "" || cfg.TelnetTLS.KeyFile == "" {
			return nil, fmt.Errorf("telnet_tls enabled but cert_file and key_file are required")
		}
		cert, err := tls.LoadX509KeyPair(cfg.TelnetTLS.CertFile, cfg.TelnetTLS.KeyFile)
		if err != nil {
			return nil, fmt.Errorf("telnet_tls cert: %w", err)
		}
		tlsCfg := &tls.Config{
			Certificates: []tls.Certificate{cert},
			MinVersion:   tls.VersionTLS12,
		}
		addr := fmt.Sprintf(":%d", cfg.TelnetTLS.Port)
		ln, err := net.Listen("tcp", addr)
		if err != nil {
			return nil, fmt.Errorf("telnet_tls listen: %w", err)
		}
		s.telnetTLSLn = tls.NewListener(ln, tlsCfg)
	}

	if cfg.HTTP.Enabled {
		s.httpServer = &http.Server{
			Addr:    fmt.Sprintf(":%d", cfg.HTTP.Port),
			Handler: newHTTPMux(s),
		}
	}

	if cfg.HTTPS.Enabled {
		if cfg.HTTPS.CertFile == "" || cfg.HTTPS.KeyFile == "" {
			return nil, fmt.Errorf("https enabled but cert_file and key_file are required")
		}
		s.httpsServer = &http.Server{
			Addr:      fmt.Sprintf(":%d", cfg.HTTPS.Port),
			Handler:   newHTTPMux(s),
			TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
		}
	}

	return s, nil
}

func (s *Server) Hub() *Hub {
	return s.hub
}

func (s *Server) ListenAndServe(handler func(*Session, string)) error {
	s.handler = handler

	if s.telnetLn != nil {
		go s.serveTelnet()
	}

	if s.telnetTLSLn != nil {
		go s.serveTelnetTLS()
	}

	if s.httpServer != nil {
		go s.serveHTTP()
	}

	if s.httpsServer != nil {
		go s.serveHTTPS()
	}

	if s.telnetLn == nil && s.telnetTLSLn == nil && s.httpServer == nil && s.httpsServer == nil {
		return fmt.Errorf("no listeners configured")
	}

	select {}
}

func (s *Server) serveTelnet() {
	for {
		conn, err := s.telnetLn.Accept()
		if err != nil {
			return
		}
		sess := &Session{
			Conn:  newTCPConn(conn),
			State: StateAccountName,
		}
		s.hub.Add(sess)
		go s.handleSession(sess, s.handler)
	}
}

func (s *Server) serveTelnetTLS() {
	for {
		conn, err := s.telnetTLSLn.Accept()
		if err != nil {
			return
		}
		sess := &Session{
			Conn:  newTCPConn(conn),
			State: StateAccountName,
		}
		s.hub.Add(sess)
		go s.handleSession(sess, s.handler)
	}
}

func (s *Server) serveHTTP() {
	err := s.httpServer.ListenAndServe()
	if err != nil && err != http.ErrServerClosed {
		log.Printf("http server error: %v", err)
	}
}

func (s *Server) serveHTTPS() {
	err := s.httpsServer.ListenAndServeTLS(s.config.HTTPS.CertFile, s.config.HTTPS.KeyFile)
	if err != nil && err != http.ErrServerClosed {
		log.Printf("https server error: %v", err)
	}
}

func (s *Server) handleSession(sess *Session, handler func(*Session, string)) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("session panic: %v", r)
		}
		s.hub.Remove(sess)
		sess.Close()
	}()

	sess.Conn.Write([]byte("\033[2J\033[H"))

	sess.Write(WelcomeBanner())
	sess.Write("What's your account name? ")

	for {
		line, err := sess.Conn.ReadMessage()
		if err != nil {
			log.Printf("session read error: %v", err)
			return
		}
		if len(line) > 1024 {
			line = line[:1024]
		}
		handler(sess, line)
	}
}

// wrap applies the player's wrap_width option to outgoing text. It is a no-op
// before login (no Player) so the welcome banner is never reflowed. The width
// is clamped to a minimum of 80 columns.
func (sess *Session) wrap(msg string) string {
	if sess.Player == nil {
		return msg
	}
	width := sess.Player.OptionInt("wrap_width")
	if width < 80 {
		width = 80
	}
	return color.WrapANSI(msg, width)
}

// Write sends raw text with no wrapping. Used for prompts and partial lines.
func (sess *Session) Write(msg string) {
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	if sess.promptVisible {
		sess.Conn.Write([]byte("\r\n"))
		sess.promptVisible = false
	}
	sess.Conn.Write([]byte(msg))
}

func (sess *Session) WriteLine(msg string) {
	msg = sess.wrap(msg)
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	if sess.promptVisible {
		sess.Conn.Write([]byte("\r\n"))
		sess.promptVisible = false
	}
	sess.Conn.Write([]byte(msg + "\r\n"))
}

func (sess *Session) WriteLines(lines ...string) {
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	for i, l := range lines {
		if i == 0 && sess.promptVisible {
			sess.Conn.Write([]byte("\r\n"))
			sess.promptVisible = false
		}
		sess.Conn.Write([]byte(sess.wrap(l) + "\r\n"))
	}
}

func (sess *Session) Writef(format string, args ...interface{}) {
	msg := sess.wrap(fmt.Sprintf(format, args...))
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	if sess.promptVisible {
		sess.Conn.Write([]byte("\r\n"))
		sess.promptVisible = false
	}
	sess.Conn.Write([]byte(msg))
}

func (sess *Session) WritePrompt(prompt string) {
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	if sess.promptVisible {
		return
	}
	sess.Conn.Write([]byte(prompt))
	sess.promptVisible = true
}

func (sess *Session) Reprompt(prompt string) {
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	sess.Conn.Write([]byte(prompt))
	sess.promptVisible = true
}

func (sess *Session) Close() error {
	sess.writeMu.Lock()
	defer sess.writeMu.Unlock()
	return sess.Conn.Close()
}