-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathmain.go
More file actions
1745 lines (1442 loc) · 57.2 KB
/
Copy pathmain.go
File metadata and controls
1745 lines (1442 loc) · 57.2 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:generate go run cmd/generate/module-imports.go
package main
import (
"fmt"
"net"
"os"
"path"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/GoMudEngine/GoMud/internal/audio"
"github.com/GoMudEngine/GoMud/internal/buffs"
"github.com/GoMudEngine/GoMud/internal/characters"
"github.com/GoMudEngine/GoMud/internal/colorpatterns"
"github.com/GoMudEngine/GoMud/internal/configs"
"github.com/GoMudEngine/GoMud/internal/connections"
"github.com/GoMudEngine/GoMud/internal/conversations"
"github.com/GoMudEngine/GoMud/internal/copyover"
"github.com/GoMudEngine/GoMud/internal/events"
"github.com/GoMudEngine/GoMud/internal/flags"
"github.com/GoMudEngine/GoMud/internal/gametime"
"github.com/GoMudEngine/GoMud/internal/hooks"
"github.com/GoMudEngine/GoMud/internal/inputhandlers"
"github.com/GoMudEngine/GoMud/internal/integrations/discord"
"github.com/GoMudEngine/GoMud/internal/items"
"github.com/GoMudEngine/GoMud/internal/keywords"
"github.com/GoMudEngine/GoMud/internal/language"
"github.com/GoMudEngine/GoMud/internal/migration"
"github.com/GoMudEngine/GoMud/internal/modmanager"
"github.com/GoMudEngine/GoMud/internal/usercommands"
"github.com/GoMudEngine/GoMud/internal/version"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh"
"github.com/GoMudEngine/GoMud/internal/mapper"
"github.com/GoMudEngine/GoMud/internal/mobs"
"github.com/GoMudEngine/GoMud/internal/mudlog"
"github.com/GoMudEngine/GoMud/internal/mutators"
"github.com/GoMudEngine/GoMud/internal/pets"
"github.com/GoMudEngine/GoMud/internal/plugins"
"github.com/GoMudEngine/GoMud/internal/quests"
"github.com/GoMudEngine/GoMud/internal/races"
"github.com/GoMudEngine/GoMud/internal/rooms"
"github.com/GoMudEngine/GoMud/internal/scripting"
"github.com/GoMudEngine/GoMud/internal/skills"
"github.com/GoMudEngine/GoMud/internal/spells"
"github.com/GoMudEngine/GoMud/internal/suggestions"
"github.com/GoMudEngine/GoMud/internal/telemetry"
"github.com/GoMudEngine/GoMud/internal/templates"
"github.com/GoMudEngine/GoMud/internal/term"
"github.com/GoMudEngine/GoMud/internal/users"
"github.com/GoMudEngine/GoMud/internal/util"
"github.com/GoMudEngine/GoMud/internal/web"
_ "github.com/GoMudEngine/GoMud/modules"
textLang "golang.org/x/text/language"
)
// Version of the binary
// Should be kept in lockstep with github releases
// When updating this version:
// 1. Expect to update the github release version
// 2. Consider whether any migration code is needed for breaking changes, particularly in datafiles (see internal/migration)
const VERSION = "0.9.10"
var (
sigChan = make(chan os.Signal, 1)
workerShutdownChan = make(chan bool, 1)
serverAlive atomic.Bool
worldManager = NewWorld(sigChan)
// Start a pool of worker goroutines
wg sync.WaitGroup
)
func main() {
// Dispatch the module manager subcommand before any server initialisation.
if len(os.Args) >= 2 && os.Args[1] == "module" {
modmanager.Run(os.Args[2:])
return
}
serverStartTime := time.Now()
// Capture panic and write msg/stack to logs
defer func() {
if r := recover(); r != nil {
mudlog.Error("PANIC", "error", r)
s := string(debug.Stack())
for _, str := range strings.Split(s, "\n") {
mudlog.Error("PANIC", "stack", str)
}
}
}()
// Setup logging
mudlog.SetupLogger(
events.GetLogger(),
os.Getenv(`LOG_LEVEL`),
os.Getenv(`LOG_PATH`),
os.Getenv(`LOG_NOCOLOR`) == ``,
)
flags.HandleFlags(VERSION)
// Register copyover contributors (must happen before Restore is called).
copyover.Register(connections.CopyoverContributor())
copyover.Register(users.CopyoverContributor())
copyover.Register(util.CopyoverContributor())
copyover.Register(gametime.CopyoverContributor())
copyover.Register(copyover.TokenContributor())
// Wire up the reconnect-token issuer so that connections can issue tokens
// for WebSocket clients without creating an import cycle.
connections.IssueWebSocketReconnectToken = func(connectionId connections.ConnectionId) (string, error) {
u := users.GetByConnectionId(connectionId)
if u == nil {
return "", fmt.Errorf("no user for connection %d", connectionId)
}
return copyover.IssueReconnectToken(u.UserId)
}
configs.ReloadConfig()
c := configs.GetConfig()
lastKnownVersion, err := version.Parse(string(configs.GetServerConfig().CurrentVersion))
if err != nil {
mudlog.Error("Versioning", "error", err)
os.Exit(1)
}
currentVersion, _ := version.Parse(VERSION)
// if no copyover FD, run any migrations
if flags.CopyoverFd() < 0 {
if err = migration.Run(lastKnownVersion, currentVersion); err != nil {
mudlog.Error("migration.Run()", "error", err)
os.Exit(1)
}
}
// Default i18n localize folders
if len(c.Translation.LanguagePaths) == 0 {
c.Translation.LanguagePaths = []string{
path.Join("_datafiles", "localize"),
path.Join(c.FilePaths.DataFiles.String(), "localize"),
}
}
mudlog.Info(`========================`)
//
mudlog.Info(` _____ `)
mudlog.Info(` / ____| `)
mudlog.Info(`| | __ ___ `)
mudlog.Info(`| | |_ |/ _ \ `)
mudlog.Info(`| |__| | (_) | `)
mudlog.Info(` \_____|\___/ `)
mudlog.Info(` __ __ _ `)
mudlog.Info(`| \/ | | |`)
mudlog.Info(`| \ / |_ _ __| |`)
mudlog.Info(`| |\/| | | | |/ _' |`)
mudlog.Info(`| | | | |_| | (_| |`)
mudlog.Info(`|_| |_|\__,_|\__,_|`)
//
mudlog.Info(`========================`)
//
/*
cfgData := c.AllConfigData()
cfgKeys := make([]string, 0, len(cfgData))
for k := range cfgData {
cfgKeys = append(cfgKeys, k)
}
// sort the keys
slices.Sort(cfgKeys)
for _, k := range cfgKeys {
mudlog.Info("Config", "name", k, "value", cfgData[k])
}
//
mudlog.Info(`========================`)
*/
// Older versions of GoMud may not have this folder present.
// Also deleting the folder is a quick way to reset instance state, so this corrects that if it happens.
os.Mkdir(util.FilePath(configs.GetFilePathsConfig().DataFiles.String(), `/`, `rooms.instances`), os.ModeDir|0755)
// Register the plugin filesystem with the template system
templates.RegisterFS(plugins.GetPluginRegistry())
items.RegisterFS(plugins.GetPluginRegistry())
mutators.RegisterFS(plugins.GetPluginRegistry())
buffs.RegisterFS(plugins.GetPluginRegistry())
buffs.RegisterFlagFS(plugins.GetPluginRegistry())
pets.RegisterFS(plugins.GetPluginRegistry())
quests.RegisterFS(plugins.GetPluginRegistry())
mobs.RegisterFS(plugins.GetPluginRegistry())
conversations.RegisterFS(plugins.GetPluginRegistry())
usercommands.AddFunctionExporter(plugins.GetPluginRegistry())
users.AddFunctionExporter(plugins.GetPluginRegistry())
usercommands.SetRoomTagProvider(plugins.GetRegisteredRoomTags)
web.SetRoomTagProvider(plugins.GetRegisteredRoomTags)
inputhandlers.AddIACHandler(plugins.GetPluginRegistry())
inputhandlers.AddTextPrefixHandler(plugins.GetPluginRegistry())
//
// System Configurations
runtime.GOMAXPROCS(int(c.Server.MaxCPUCores))
// Validate chosen world:
if err := util.ValidateWorldFiles(`_datafiles/world/default`, c.FilePaths.DataFiles.String()); err != nil {
mudlog.Error("World Validation", "error", err)
os.Exit(1)
}
language.InitTranslation(language.BundleCfg{
DefaultLanguage: textLang.Make(c.Translation.DefaultLanguage.String()),
Language: textLang.Make(c.Translation.Language.String()),
LanguagePaths: c.Translation.LanguagePaths,
})
hooks.RegisterListeners()
telemetry.Load(configs.GetFilePathsConfig().DataFiles.String())
telemetry.RegisterListeners()
// Discord integration
if webhookUrl := string(c.Integrations.Discord.WebhookUrl); webhookUrl != "" {
discord.Init(webhookUrl)
mudlog.Info("Discord", "info", "integration is enabled")
} else {
mudlog.Warn("Discord", "info", "integration is disabled")
}
mudlog.Info(
"Starting server",
"name", string(c.Server.MudName),
)
mudlog.Info(`========================`)
// Load all the data files up front.
loadAllDataFiles(false)
mudlog.Info(`========================`)
mudlog.Info("Mapper", "status", "precaching")
timeStart := time.Now()
mapper.PreCacheMaps()
mudlog.Info("Mapper", "status", "done", "time taken", time.Since(timeStart))
mudlog.Info(`========================`)
// Create the user index
isCopyover := flags.CopyoverFd() >= 0
if !isCopyover {
timeStart := time.Now()
idx := users.InitUserIndex()
if !idx.Exists() {
// Since it doesn't exist yet, that's a good indication we should do a quick format migration check
users.DoUserMigrations()
}
if idx.IsUpToDate() {
mudlog.Info("UserIndex", "info", "User index up to date.", "users", idx.GetMetaData().RecordCount, "time taken", time.Since(timeStart))
} else {
idx.Create()
idx.Rebuild()
mudlog.Info("UserIndex", "info", "User index recreated.", "users", idx.GetMetaData().RecordCount, "time taken", time.Since(timeStart))
}
}
users.GetCharacterIndex().Rebuild()
mudlog.Info("CharacterIndex", "info", "Active character names indexed.", "characters", users.GetCharacterIndex().Len())
// Load the round count from the file
if !isCopyover {
if util.LoadRoundCount(util.FilePath(c.FilePaths.DataFiles.String()+`/`+util.RoundCountFilename)) == util.RoundCountMinimum {
gametime.SetToDay(-3)
}
}
if isCopyover {
if err := copyover.Restore(flags.CopyoverFd()); err != nil {
mudlog.Error("copyover.Restore()", "error", err)
os.Exit(1)
}
mudlog.Info("Copyover", "status", "state restored")
}
gametime.GetZodiac(1) // The first time this is called it randomizes all zodiacs
scripting.Setup(int(c.Scripting.LoadTimeoutMs), int(c.Scripting.RoomTimeoutMs))
mudlog.Info(`========================`)
// Wire module admin registrar before loading plugins so that any admin
// pages and API endpoints registered by modules are available immediately.
plugins.SetAdminRegistrar(web.GetAdminRegistrar())
// Trigger the load plugins event
plugins.Load(
configs.GetFilePathsConfig().DataFiles.String(),
)
mudlog.Info("CharacterIndex", "info", "Character name index complete.", "characters", users.GetCharacterIndex().Len())
web.SetWebPlugin(plugins.GetPluginRegistry())
//
// Capture OS signals to gracefully shutdown the server
registerShutdownSignals(sigChan)
// for testing purposes, enable event debugging
//events.SetDebug(true)
//
// Spin up server listeners
//
// Set the server to be alive
serverAlive.Store(true)
mudlog.Info(`========================`)
web.Listen(&wg, HandleWebSocketConnection)
allServerListeners := make([]net.Listener, 0, len(c.Network.TelnetPort))
for _, port := range c.Network.TelnetPort {
if p, err := strconv.Atoi(port); err == nil && p > 0 {
if s := TelnetListenOnPort(``, p, &wg, int(c.Network.MaxTelnetConnections), connections.ConnHuman); s != nil {
allServerListeners = append(allServerListeners, s)
}
}
}
if c.Network.LocalPort > 0 {
TelnetListenOnPort(`127.0.0.1`, int(c.Network.LocalPort), &wg, 0, connections.ConnHuman)
}
if c.Network.AI.Port > 0 {
if s := TelnetListenOnPort(``, int(c.Network.AI.Port), &wg, int(c.Network.AI.MaxConnections), connections.ConnAI); s != nil {
allServerListeners = append(allServerListeners, s)
}
}
if sshPort := int(c.Network.SSHPort); sshPort > 0 {
hostKeyPath := c.FilePaths.SSHHostKeyFile.String()
if hostKeyPath == `` {
mudlog.Error("SSH", "error", "SSHPort is set but SSHHostKeyFile is not configured; SSH disabled")
} else {
hostKeyBytes, err := util.ReadFile(hostKeyPath)
if err != nil {
mudlog.Error("SSH", "error", "failed to read SSH host key", "path", hostKeyPath, "details", err)
} else {
signer, err := ssh.ParsePrivateKey(hostKeyBytes)
if err != nil {
mudlog.Error("SSH", "error", "failed to parse SSH host key", "details", err)
} else {
sshConfig := &ssh.ServerConfig{
NoClientAuth: true,
}
sshConfig.AddHostKey(signer)
if s := SSHListenOnPort(sshPort, sshConfig, &wg, int(c.Network.MaxSSHConnections)); s != nil {
allServerListeners = append(allServerListeners, s)
}
}
}
}
}
go worldManager.InputWorker(workerShutdownChan, &wg)
go worldManager.MainWorker(workerShutdownChan, &wg)
startCopyoverSignalHandler()
usercommands.SetCopyoverFunc(triggerCopyover)
if isCopyover {
for _, connId := range connections.GetAllConnectionIds() {
cd := connections.Get(connId)
if cd == nil || cd.State() != connections.LoggedIn {
continue
}
u := users.GetByConnectionId(connId)
if u == nil {
continue
}
wg.Add(1)
go resumeRestoredConnection(cd, u, &wg)
}
connections.Broadcast([]byte("\r\nCopyover complete.\r\n"))
mudlog.Info("Copyover", "status", "complete")
}
mudlog.Info("Server Ready", "Time Taken", time.Since(serverStartTime))
// block until a signal comes in
<-sigChan
tplTxt, err := templates.Process("goodbye", nil)
if err != nil {
mudlog.Error("Template Error", "error", err)
}
events.AddToQueue(events.Broadcast{
Text: templates.AnsiParse(tplTxt),
})
serverAlive.Store(false) // immediately stop processing incoming connections
util.SaveRoundCount(util.FilePath(c.FilePaths.DataFiles.String() + `/` + util.RoundCountFilename))
// some last minute stats reporting
totalConnections, totalDisconnections := connections.Stats()
mudlog.Info(
"Stopping server",
"LifetimeConnections", totalConnections,
"LifetimeDisconnects", totalDisconnections,
"ActiveConnections", totalConnections-totalDisconnections,
)
// cleanup all connections
connections.Cleanup()
for _, s := range allServerListeners {
s.Close()
}
web.Shutdown()
// Final plugin save before shutting down
plugins.Save()
// Just a goroutine that spins its wheels until the program shuts down")
go func() {
for {
mudlog.Warn("Waiting on workers")
// sleep for 3 seconds
time.Sleep(time.Duration(3) * time.Second)
}
}()
// Close the channel, signalling to the worker threads to shutdown.
close(workerShutdownChan)
// Wait for all workers to finish their tasks.
// Otherwise we end up getting flushed file saves incomplete.
wg.Wait()
// Give it a second to disaptch any final messages in the event queue
// Example: discord server shutdown
time.Sleep(1 * time.Second)
}
func resumeRestoredConnection(connDetails *connections.ConnectionDetails, userObject *users.UserRecord, wg *sync.WaitGroup) {
defer wg.Done()
mudlog.Info("Copyover", "resuming connection", connDetails.ConnectionId(), "userId", userObject.UserId)
var sharedState map[string]any = make(map[string]any)
connDetails.AddInputHandler("TelnetIACHandler", inputhandlers.TelnetIACHandler)
connDetails.AddInputHandler("AnsiHandler", inputhandlers.AnsiHandler)
connDetails.AddInputHandler("CleanserInputHandler", inputhandlers.CleanserInputHandler)
connDetails.AddInputHandler("TextPrefixHandler", inputhandlers.TextPrefixHandler)
connDetails.AddInputHandler("EchoInputHandler", inputhandlers.EchoInputHandler)
connDetails.AddInputHandler("HistoryInputHandler", inputhandlers.HistoryInputHandler)
if userObject.Role == users.RoleAdmin {
connDetails.AddInputHandler("SystemCommandInputHandler", inputhandlers.SystemCommandInputHandler)
}
connDetails.AddInputHandler("SignalHandler", inputhandlers.SignalHandler, "AnsiHandler")
worldManager.SendEnterWorld(userObject.UserId, userObject.Character.RoomId)
inputBuffer := make([]byte, connections.ReadBufferSize)
clientInput := &connections.ClientInput{
ConnectionId: connDetails.ConnectionId(),
DataIn: []byte{},
Buffer: make([]byte, 0, connections.ReadBufferSize),
EnterPressed: false,
Clipboard: []byte{},
History: connections.InputHistory{},
}
var sug suggestions.Suggestions
lastInput := time.Now()
c := configs.GetConfig()
for {
clientInput.EnterPressed = false
clientInput.TabPressed = false
clientInput.BSPressed = false
n, err := connDetails.Read(inputBuffer)
if err != nil {
userObject.EventLog.Add(`conn`, `Disconnected`)
if c.Network.LinkDeadSeconds > 0 {
connDetails.SetState(connections.LinkDead)
worldManager.SendSetLinkDead(userObject.UserId, true)
} else {
worldManager.SendLeaveWorld(userObject.UserId)
worldManager.SendLogoutConnectionId(connDetails.ConnectionId())
}
mudlog.Warn("Telnet", "connectionID", connDetails.ConnectionId(), "error", err)
connections.Remove(connDetails.ConnectionId())
break
}
if connDetails.InputDisabled() {
continue
}
clientInput.DataIn = inputBuffer[:n]
okContinue, lastHandlerName, err := connDetails.HandleInput(clientInput, sharedState)
if err != nil {
mudlog.Warn("InputHandler Error", "handler", lastHandlerName, "error", err)
continue
}
if !okContinue {
_, suggested := userObject.GetUnsentText()
redrawPrompt := false
if clientInput.TabPressed {
if sug.Count() < 1 {
sug.Set(worldManager.GetAutoComplete(userObject.UserId, string(clientInput.Buffer)))
}
if sug.Count() > 0 {
suggested = sug.Next()
userObject.SetUnsentText(string(clientInput.Buffer), suggested)
redrawPrompt = true
}
} else if clientInput.BSPressed {
userObject.SetUnsentText(string(clientInput.Buffer), ``)
if suggested != `` {
suggested = ``
sug.Clear()
redrawPrompt = true
}
} else {
if suggested != `` {
if len(clientInput.Buffer) > 0 && clientInput.Buffer[len(clientInput.Buffer)-1] == term.ASCII_SPACE {
clientInput.Buffer = append(clientInput.Buffer[0:len(clientInput.Buffer)-1], []byte(suggested)...)
clientInput.Buffer = append(clientInput.Buffer[0:len(clientInput.Buffer)], []byte(` `)...)
redrawPrompt = true
userObject.SetUnsentText(string(clientInput.Buffer), ``)
sug.Clear()
} else {
suggested = ``
sug.Clear()
userObject.SetUnsentText(string(clientInput.Buffer), suggested)
redrawPrompt = true
}
}
userObject.SetUnsentText(string(clientInput.Buffer), suggested)
}
if redrawPrompt {
pTxt := userObject.GetCommandPrompt()
connections.SendTo([]byte(templates.AnsiParse(pTxt)), clientInput.ConnectionId)
}
continue
}
if clientInput.EnterPressed {
c = configs.GetConfig()
if time.Since(lastInput) < time.Duration(c.Timing.TurnMs)*time.Millisecond {
clientInput.Reset()
userObject.SetUnsentText(``, ``)
} else {
_, suggested := userObject.GetUnsentText()
if len(suggested) > 0 {
clientInput.Buffer = append(clientInput.Buffer, []byte(suggested)...)
sug.Clear()
userObject.SetUnsentText(string(clientInput.Buffer), ``)
connections.SendTo([]byte(templates.AnsiParse(userObject.GetCommandPrompt())), clientInput.ConnectionId)
}
wi := WorldInput{
FromId: userObject.UserId,
InputText: string(clientInput.Buffer),
}
worldManager.SendInput(wi)
clientInput.Reset()
userObject.SetUnsentText(``, ``)
lastInput = time.Now()
}
time.Sleep(time.Duration(10) * time.Millisecond)
}
}
}
// Bounds for the connect-time client-type detection probe.
const (
clientDetectTimeout = 2 * time.Second // overall budget before defaulting to non-Mudlet
clientDetectReadDeadline = 200 * time.Millisecond // per-read slice so we can re-check the budget
)
// detectClientType probes a raw telnet client with an MNES NEW-ENVIRON request
// and synchronously waits (with a bounded timeout) for the reply so the caller
// can choose the correct echo baseline before the first prompt is shown.
//
// Replies are fed through the normal input handler chain, where TelnetIACHandler
// performs the NEW-ENVIRON negotiation and records IsMudlet/DetectionComplete on
// the connection's client settings. The login handler is intentionally not in
// the chain yet, so stray pre-login input is simply buffered (not echoed) and is
// preserved for the main loop. On timeout the client defaults to non-Mudlet.
//
// AI connections skip the probe entirely and keep the historical raw-telnet
// baseline, so automated clients are not delayed by the detection window.
func detectClientType(connDetails *connections.ConnectionDetails, clientInput *connections.ClientInput, sharedState map[string]any) {
connId := connDetails.ConnectionId()
if connDetails.ConnType() == connections.ConnAI {
cs := connections.GetClientSettings(connId)
cs.DetectionComplete = true
connections.OverwriteClientSettings(connId, cs)
return
}
// Ask the client to enable NEW-ENVIRON. A Mudlet client replies WILL, which
// TelnetIACHandler answers with the MNES SEND request; Mudlet then returns
// its CLIENT_NAME. Non-Mudlet clients reply WONT (or never reply -> timeout).
connections.SendTo(term.TelnetRequestNewEnviron.BytesWithPayload(nil), connId)
buf := make([]byte, connections.ReadBufferSize)
deadline := time.Now().Add(clientDetectTimeout)
for {
if connections.GetClientSettings(connId).DetectionComplete {
break
}
if !time.Now().Before(deadline) {
break
}
_ = connDetails.SetReadDeadline(time.Now().Add(clientDetectReadDeadline))
n, err := connDetails.Read(buf)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Timeout() {
continue // no data this slice; re-check the overall budget
}
break // a real read error; let the main loop surface it
}
if n == 0 {
continue
}
clientInput.DataIn = buf[:n]
if _, lastHandler, herr := connDetails.HandleInput(clientInput, sharedState); herr != nil {
mudlog.Warn("Client detection input", "handler", lastHandler, "connectionId", connId, "error", herr)
}
}
// Restore blocking reads for the main loop.
_ = connDetails.SetReadDeadline(time.Time{})
// Ensure detection is flagged complete even if we timed out.
cs := connections.GetClientSettings(connId)
if !cs.DetectionComplete {
cs.DetectionComplete = true
connections.OverwriteClientSettings(connId, cs)
}
}
func handleTelnetConnection(connDetails *connections.ConnectionDetails, wg *sync.WaitGroup) {
defer func() {
wg.Done()
}()
mudlog.Info("New Connection", "connectionID", connDetails.ConnectionId(), "remoteAddr", connDetails.RemoteAddr().String())
// Setup shared state map for this connection's handlers
// Needs to be created BEFORE the first handler call
var sharedState map[string]any = make(map[string]any)
// Add starting handlers
// Special escape handlers
connDetails.AddInputHandler("TelnetIACHandler", inputhandlers.TelnetIACHandler)
connDetails.AddInputHandler("AnsiHandler", inputhandlers.AnsiHandler)
// Consider a macro handler at this point?
// Text Processing
connDetails.AddInputHandler("CleanserInputHandler", inputhandlers.CleanserInputHandler)
connDetails.AddInputHandler("TextPrefixHandler", inputhandlers.TextPrefixHandler)
// Get the configured login handler func. It is added to the input handler
// chain further down, AFTER client-type detection, so that the connect-time
// echo baseline is correct before the very first (username) prompt is shown.
loginHandler := inputhandlers.GetLoginPromptHandler()
// Turn off "line at a time", send chars as typed
connections.SendTo(
term.TelnetWILL(term.TELNET_OPT_SUP_GO_AHD),
connDetails.ConnectionId(),
)
// Tell the client we expect chars as they are typed
connections.SendTo(
term.TelnetWONT(term.TELNET_OPT_LINE_MODE),
connDetails.ConnectionId(),
)
// NOTE: The echo negotiation (WILL/WONT ECHO) is deliberately NOT sent here.
// It depends on the client type, which we detect below before showing the
// first prompt. Raw telnet clients rely on server-side echo (WILL ECHO),
// while local-echo clients such as Mudlet must start at WONT ECHO. See the
// detection block further down.
// Request that the client report window size changes as they happen
connections.SendTo(
term.TelnetDO(term.TELNET_OPT_NAWS),
connDetails.ConnectionId(),
)
// Send request to change charset
connections.SendTo(
term.TelnetRequestChangeCharset.BytesWithPayload(nil),
connDetails.ConnectionId(),
)
// Send request to enable MSP
connections.SendTo(
term.MspEnable.BytesWithPayload(nil),
connDetails.ConnectionId(),
)
connections.SendTo(
term.TelnetSuppressGoAhead.BytesWithPayload(nil),
connDetails.ConnectionId(),
)
// Offer EOR (End Of Record) support. Mudlet prefers EOR over GA and uses it
// to delimit prompts; without it (and with SUPPRESS-GO-AHEAD set) Mudlet has
// no prompt anchor, which can prevent its input-line password masking from
// engaging even though it honors the ECHO option.
connections.SendTo(
term.TelnetWILL(term.TELNET_OPT_EOR),
connDetails.ConnectionId(),
)
clientSetupCommands := "" + //term.AnsiAltModeStart.String() + // alternative mode (No scrollback)
//term.AnsiCursorHide.String() + // Hide Cursor (Because we will manually echo back)
//term.AnsiCharSetUTF8.String() + // UTF8 mode
//term.AnsiReportMouseClick.String() + // Request client to capture and report mouse clicks
term.AnsiRequestResolution.String() // Request resolution
//""
connections.SendTo(
[]byte(clientSetupCommands),
connDetails.ConnectionId(),
)
plugins.OnNetConnect(connDetails)
// an input buffer for reading data sent over the network
inputBuffer := make([]byte, connections.ReadBufferSize)
// Describes whatever the client sent us
clientInput := &connections.ClientInput{
ConnectionId: connDetails.ConnectionId(),
DataIn: []byte{},
Buffer: make([]byte, 0, connections.ReadBufferSize), // DataIn is appended to this buffer after processing
EnterPressed: false,
Clipboard: []byte{},
History: connections.InputHistory{},
}
if audioConfig := audio.GetFile(`intro`); audioConfig.FilePath != `` {
v := 100
if audioConfig.Volume > 0 && audioConfig.Volume <= 100 {
v = audioConfig.Volume
}
connections.SendTo(
term.MspCommand.BytesWithPayload([]byte("!!MUSIC("+audioConfig.FilePath+" V="+strconv.Itoa(v)+" L=-1 C=1)")),
clientInput.ConnectionId,
)
}
// --- Send Initial Welcome/Splash ---
// (This part was mostly correct before)
splashTxt, _ := templates.Process("login/connect-splash", nil)
connections.SendTo([]byte(templates.AnsiParse(splashTxt)), connDetails.ConnectionId())
if connDetails.ConnType() == connections.ConnAI {
connections.SendTo([]byte("\r\nThis port is for AI clients. Human players, please use the standard telnet port.\r\n\r\n"), connDetails.ConnectionId())
}
// --- Detect the client type and pick the connect-time echo baseline ---
// Local-echo clients such as Mudlet echo input themselves and read telnet
// ECHO purely as a "mask this field" hint, so they must start at WONT ECHO
// (and only see WILL ECHO transiently around password prompts). Raw telnet
// clients rely on server-side echo, so they keep the historical WILL ECHO.
detectClientType(connDetails, clientInput, sharedState)
clientCS := connections.GetClientSettings(connDetails.ConnectionId())
if clientCS.IsMudlet {
// Mudlet does its own local echo -> baseline is WONT ECHO.
connections.SendTo(term.TelnetWONT(term.TELNET_OPT_ECHO), connDetails.ConnectionId())
} else {
// Raw telnet keeps server-side echo (unchanged behavior).
connections.SendTo(term.TelnetWILL(term.TELNET_OPT_ECHO), connDetails.ConnectionId())
}
// Now that the echo baseline is correct, add the login handler so the first
// prompt is rendered with the right masking behavior.
connDetails.AddInputHandler("LoginPromptHandler", loginHandler)
// --- Trigger the Prompt Handler to initialize state and send the FIRST prompt ---
// Create a dummy input that signifies "start the process" but has no actual user data/control codes.
initialTriggerInput := &connections.ClientInput{
ConnectionId: connDetails.ConnectionId(),
// Ensure flags like EnterPressed are false
}
// Call the handler function directly ONCE.
// This executes the `!ok` block inside the handler, which:
// 1. Creates the PromptHandlerState in sharedState.
// 2. Calls advanceAndSendPromptCustom -> sendPromptFunc for the *first* step (username).
// 3. Returns false (which we ignore here, as we aren't in the main loop yet).
loginHandler(initialTriggerInput, sharedState)
var userObject *users.UserRecord
var sug suggestions.Suggestions
lastInput := time.Now()
c := configs.GetConfig()
for {
clientInput.EnterPressed = false // Default state is always false
clientInput.TabPressed = false // Default state is always false
clientInput.BSPressed = false // Default state is always false
n, err := connDetails.Read(inputBuffer)
if err != nil {
// If failed to read from the connection, switch to linkdead state
if userObject != nil {
userObject.EventLog.Add(`conn`, `Disconnected`)
if c.Network.LinkDeadSeconds > 0 {
connDetails.SetState(connections.LinkDead)
worldManager.SendSetLinkDead(userObject.UserId, true)
} else {
worldManager.SendLeaveWorld(userObject.UserId)
worldManager.SendLogoutConnectionId(connDetails.ConnectionId())
}
}
mudlog.Warn("Telnet", "connectionID", connDetails.ConnectionId(), "error", err)
connections.Remove(connDetails.ConnectionId())
break
}
if connDetails.InputDisabled() {
continue
}
clientInput.DataIn = inputBuffer[:n]
// Input handler processes any special commands, transforms input, sets flags from input, etc
okContinue, lastHandlerName, err := connDetails.HandleInput(clientInput, sharedState)
// Was there an error? If so, we should probably just stop processing input
if err != nil {
mudlog.Warn("InputHandler Error", "handler", lastHandlerName, "error", err)
// Decide if disconnect is needed based on error type
continue
}
// If a handler aborted processing, just keep track of where we are so
// far and jump back to waiting.
if !okContinue {
// if no user signed in, loop back
if userObject == nil {
continue
}
_, suggested := userObject.GetUnsentText()
redrawPrompt := false
if clientInput.TabPressed {
if sug.Count() < 1 {
sug.Set(worldManager.GetAutoComplete(userObject.UserId, string(clientInput.Buffer)))
}
if sug.Count() > 0 {
suggested = sug.Next()
userObject.SetUnsentText(string(clientInput.Buffer), suggested)
redrawPrompt = true
}
} else if clientInput.BSPressed {
// If a suggestion is pending, remove it
// otherwise just do a normal backspace operation
userObject.SetUnsentText(string(clientInput.Buffer), ``)
if suggested != `` {
suggested = ``
sug.Clear()
redrawPrompt = true
}
} else {
if suggested != `` {
// If they hit space, accept the suggestion
if len(clientInput.Buffer) > 0 && clientInput.Buffer[len(clientInput.Buffer)-1] == term.ASCII_SPACE {
clientInput.Buffer = append(clientInput.Buffer[0:len(clientInput.Buffer)-1], []byte(suggested)...)
clientInput.Buffer = append(clientInput.Buffer[0:len(clientInput.Buffer)], []byte(` `)...)
redrawPrompt = true
userObject.SetUnsentText(string(clientInput.Buffer), ``)
sug.Clear()
} else {
suggested = ``
sug.Clear()
// Otherwise, just keep the suggestion
userObject.SetUnsentText(string(clientInput.Buffer), suggested)
redrawPrompt = true
}
}
userObject.SetUnsentText(string(clientInput.Buffer), suggested)
}
if redrawPrompt {
pTxt := userObject.GetCommandPrompt()
if connections.IsWebsocket(clientInput.ConnectionId) {
connections.SendTo([]byte(pTxt), clientInput.ConnectionId)
} else {
connections.SendTo([]byte(templates.AnsiParse(pTxt)), clientInput.ConnectionId)
}
}
continue
}
// The prompt handler returns 'true' from its HandleInput func only when
// the entire sequence is complete *and* successful (e.g., login or creation ok).
// If it returns true, it means we should proceed to the logged-in state.
if okContinue && lastHandlerName == "LoginPromptHandler" {
// Prompt sequence finished successfully
// Stop intro music if playing
connections.SendTo(
term.MspCommand.BytesWithPayload([]byte("!!MUSIC(Off)")),
clientInput.ConnectionId,
)
// Retrieve the UserObject stored by the completion function
if uo, exists := sharedState["UserObject"]; exists {
var ok bool
userObject, ok = uo.(*users.UserRecord)
if !ok {
mudlog.Error("UserObject type assertion failed", "connectionId", clientInput.ConnectionId)
connections.Remove(clientInput.ConnectionId)
break
}
// Remove it from shared state if no longer needed there
delete(sharedState, "UserObject")
} else {
// This shouldn't happen if the completion function worked correctly
mudlog.Error("Login process completed but UserObject not found in sharedState", "connectionId", clientInput.ConnectionId)
connections.Remove(clientInput.ConnectionId) // Disconnect problematic connection
break // Exit the read loop for this connection
}
// Remove the prompt handler (it signaled completion by returning true)
connDetails.RemoveInputHandler("LoginPromptHandler")
// Replace it with a regular echo handler.
connDetails.AddInputHandler("EchoInputHandler", inputhandlers.EchoInputHandler)
// Add admin command handler
connDetails.AddInputHandler("HistoryInputHandler", inputhandlers.HistoryInputHandler) // Put history tracking after login handling, since login handling aborts input until complete
if userObject.Role == users.RoleAdmin {
connDetails.AddInputHandler("SystemCommandInputHandler", inputhandlers.SystemCommandInputHandler)