-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.go
More file actions
247 lines (216 loc) · 6.81 KB
/
proxy.go
File metadata and controls
247 lines (216 loc) · 6.81 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
package main
import (
"bufio"
"context"
"errors"
"fmt"
"log/slog"
"os"
"os/signal"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/cooldogedev/spectrum"
"github.com/cooldogedev/spectrum/server"
"github.com/cooldogedev/spectrum/session"
"github.com/cooldogedev/spectrum/util"
"github.com/getsentry/sentry-go"
"github.com/oomph-ac/oconfig"
"github.com/oomph-ac/oomph/oerror"
"github.com/oomph-ac/oomph/player"
"github.com/oomph-ac/oomph/utils"
"github.com/oomph-ac/oomph/world"
"github.com/sandertv/gophertunnel/minecraft"
"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
"github.com/sandertv/gophertunnel/minecraft/resource"
"github.com/sandertv/gophertunnel/minecraft/text"
"net/http"
_ "net/http/pprof"
_ "github.com/oomph-ac/oomph"
)
var (
proxy *spectrum.Spectrum
moderators = make(map[string]struct{})
)
func init() {
// Configure slog with text handler
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
})))
if err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
EnableTracing: false,
Debug: false,
}); err != nil {
slog.Error("failed to initialize sentry", "error", err)
os.Exit(1)
}
f, err := os.OpenFile("moderators.list", os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
slog.Error("failed to read moderators list", "error", err)
os.Exit(1)
}
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
if line == "" {
continue
}
moderators[line] = struct{}{}
}
}
func main() {
if err := oconfig.ParseJSON("oomph_config.hjson"); err != nil {
slog.Error("unable to parse config", "error", err)
os.Exit(1)
}
/* if codeSec[0] == 0x1 {
os.Exit(1)
} */
_ = os.Mkdir("./logs", 0644)
if os.Getenv("PPROF_ENABLED") != "" {
go http.ListenAndServe(os.Getenv("PPROF_ADDRESS"), nil)
}
gcPct := oconfig.Global.GCPercent
if gcPct < 100 && gcPct != -1 {
slog.Warn("GCPercent is set to a value which will cause high CPU usage. We have automatically adjusted this value back to 100. Please refer to https://tip.golang.org/doc/gc-guide for more information.")
gcPct = 100
}
debug.SetGCPercent(gcPct)
debug.SetMemoryLimit(int64(oconfig.Global.MemThreshold) * 1024 * 1024) // Convert MB to bytes
opts := util.DefaultOpts()
opts.ClientDecode = player.ClientDecode
opts.AutoLogin = false
opts.Addr = oconfig.Global.LocalAddress
opts.SyncProtocol = false
opts.ShutdownMessage = oconfig.Global.ShutdownMessage
//opts.Token = oconfig.Global.SpectrumKey
statusProvider, err := minecraft.NewForeignStatusProvider(oconfig.Global.RemoteAddress)
if err != nil {
panic(err)
}
packs := []*resource.Pack{}
if oconfig.Global.Resource.ResourceFolder != "" {
newPacks, err := utils.ResourcePacks(oconfig.Global.Resource.ResourceFolder, "content_keys.json")
if err != nil {
slog.Error("unable to load resource packs", "error", err)
time.Sleep(3 * time.Second)
} else {
packs = newPacks
}
}
// Register custom blocks here before calling these two functions.
world.FinalizeBlockRegistry()
utils.InitializeBlockNameMapping()
proxy = spectrum.NewSpectrum(
server.NewStaticDiscovery(oconfig.Global.RemoteAddress, oconfig.Global.BackupAddress),
slog.Default(),
opts,
nil,
)
if err := proxy.Listen(minecraft.ListenConfig{
ResourcePacks: packs,
TexturePacksRequired: oconfig.Global.Resource.RequirePacks,
StatusProvider: statusProvider,
FlushRate: -1,
//AcceptedProtocols: legacyver.All(false),
}); err != nil {
slog.Error("unable to listen", "address", oconfig.Global.LocalAddress, "error", err)
os.Exit(1)
}
go handleConnections()
slog.Info("Oomph proxy is running", "address", oconfig.Global.LocalAddress)
interruptChan := make(chan os.Signal, 1)
signal.Notify(interruptChan, os.Interrupt)
<-interruptChan
address, port, validBackupAddr := "", uint16(0), false
if oconfig.Global.BackupAddress != "" {
split := strings.Split(oconfig.Global.BackupAddress, ":")
if len(split) != 2 {
slog.Warn("invalid backup address - expected two items when splitting address and port", "address", oconfig.Global.BackupAddress)
} else {
address = split[0]
prt, err := strconv.ParseInt(split[1], 10, 16)
if err != nil {
slog.Warn("invalid backup address - expected a valid port number", "address", oconfig.Global.BackupAddress)
} else {
port = uint16(prt)
validBackupAddr = true
}
}
}
for _, s := range proxy.Registry().GetSessions() {
if !validBackupAddr {
s.Disconnect(oconfig.Global.ShutdownMessage)
} else {
s.Client().WritePacket(&packet.Transfer{
Address: address,
Port: port,
ReloadWorld: false,
})
s.Client().Flush()
}
}
}
func handleConnections() {
defer func() {
if v := recover(); v != nil {
hub := sentry.CurrentHub().Clone()
sentryErrID := hub.Recover(oerror.New("handleConnections goroutine crashed: %v", v))
_ = hub.Flush(time.Second * 10)
// Because we're in production and don't want the whole proxy program to crash, we will just restart the goroutine.
slog.Warn("handleConnections goroutine crashed", "errorID", *sentryErrID)
go handleConnections()
}
}()
for {
s, err := proxy.Accept()
if err != nil {
slog.Error("failed to accept session", "error", err)
continue
}
go acceptSession(s)
}
}
func acceptSession(s *session.Session) {
defer func(xuid string) {
if v := recover(); v != nil {
hub := sentry.CurrentHub().Clone()
hub.WithScope(func(scope *sentry.Scope) {
scope.SetTag("xuid", xuid)
})
sentryErrID := hub.Recover(oerror.New("acceptSession goroutine crashed: %v", v))
_ = hub.Flush(time.Second * 10)
slog.Warn("acceptSession goroutine crashed", "errorID", *sentryErrID)
s.Disconnect(text.Colourf("<red><bold>An error occured while processing your connection.</bold></red>\nError ID: %s", *sentryErrID))
}
}(s.Client().IdentityData().XUID)
// Disable auto-login so that Oomph's processor can modify the StartGame data to allow server-authoritative movement.
f, err := os.OpenFile(fmt.Sprintf("logs/%s.log", s.Client().IdentityData().DisplayName), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0744)
if err != nil {
s.Disconnect("failed to create log file")
return
}
playerLog := slog.New(slog.NewTextHandler(f, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
proc := NewOomphProcessor(s, proxy.Registry(), proxy.Listener(), playerLog)
pl := proc.Player()
pl.SetRecoverFunc(recoverPlayerFn)
pl.HandleEvents(oomphHandler)
if _, ok := moderators[pl.Name()]; ok {
pl.AddPerm(player.PermissionAlerts)
pl.AddPerm(player.PermissionLogs)
pl.AddPerm(player.PermissionDebug)
}
s.SetProcessor(proc)
if err := s.Login(); err != nil {
s.Disconnect(err.Error())
if !errors.Is(err, context.Canceled) {
slog.Error("session failed to login", "error", err)
}
return
}
proc.Player().SetServerConn(s.Server())
}