-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.go
More file actions
438 lines (379 loc) · 11.2 KB
/
proxy.go
File metadata and controls
438 lines (379 loc) · 11.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
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"sync"
"time"
"github.com/stewi1014/mcproxy/protocol"
)
type ProxyConfig struct {
Domains []string
Destination_Ip string
Destination_Port int
Destination_Protocol int
Destination_Version string
Shutdown_Timeout int
Ec2_Server *EC2Config
Logger *log.Logger
}
func NewProxy(config ProxyConfig) (*Proxy, error) {
var proxy Proxy
proxy.log = config.Logger
proxy.domains = config.Domains
proxy.destination_ip = config.Destination_Ip
proxy.destination_port = config.Destination_Port
proxy.status.protocolVersion = config.Destination_Protocol
proxy.status.versionName = config.Destination_Version
proxy.shutdown_timeout = time.Duration(config.Shutdown_Timeout) * time.Second
if config.Ec2_Server != nil {
server, err := NewEC2Server(*config.Ec2_Server)
if err != nil {
return nil, err
}
proxy.server = server
} else {
return nil, errors.New("no backend provided for proxy")
}
proxy.shutdownTimer = time.NewTimer(proxy.shutdown_timeout)
go proxy.stopWhenEmpty()
go func() {
status, mcErr := proxy.getServerStatus(time.Second * 10)
if mcErr == nil {
proxy.log.Printf(
"running version %v: \"%v\"\n",
status.JSONResponse.Version.Name,
status.JSONResponse.Description,
)
} else {
proxy.log.Println("server didn't respond")
}
}()
return &proxy, nil
}
type Proxy struct {
log *log.Logger
domains []string
destination_ip string
destination_port int
shutdown_timeout time.Duration
startMutex sync.Mutex
server Server
mutex sync.Mutex
players int
shutdownTimer *time.Timer
shutdownTime time.Time
lastStart time.Time
lastStartDuration time.Duration
status struct {
maxPlayers int
description string
versionName string
protocolVersion int
favicon string
enforceSecureChat bool
}
}
func (p *Proxy) startServer() error {
p.startMutex.Lock()
defer p.startMutex.Unlock()
state, err := p.server.State(context.Background())
if err != nil {
return err
}
if state != ServerStateOff {
p.log.Println("not starting, server already on")
return nil
}
p.log.Println("starting server")
p.mutex.Lock()
p.lastStart = time.Now()
p.mutex.Unlock()
err = p.server.StartServer(context.Background())
if err != nil {
return err
}
go func() {
for now := range time.NewTicker(time.Second * 2).C {
_, err := p.getServerStatus(time.Second * 10)
if err == nil {
p.log.Println("server has started")
p.mutex.Lock()
p.lastStartDuration = now.Sub(p.lastStart)
p.mutex.Unlock()
return
}
state, err := p.server.State(context.Background())
if err != nil {
p.log.Println(err)
return
} else {
if state != ServerStateStarting && state != ServerStateOn {
p.log.Println("server shutdown before mc server could be connected to")
return
}
}
}
}()
return nil
}
func (p *Proxy) stopWhenEmpty() {
for range p.shutdownTimer.C {
state, stateErr := p.server.State(context.Background())
if stateErr != nil {
p.log.Println("failed to get server state: ", stateErr)
} else if state != ServerStateStarting && state != ServerStateOn {
p.log.Println("server shut down externally")
continue
}
err := p.server.StopServer(context.Background())
if err != nil {
p.log.Println("error stopping server:", err)
} else {
p.log.Println("stopping server")
}
}
}
func (p *Proxy) HandleStatus(conn *protocol.Conn) error {
for {
packet, err := conn.ReadPacket(
&protocol.StatusRequest{},
&protocol.PingRequest{},
)
if err != nil {
return err
}
switch packet := packet.(type) {
case *protocol.StatusRequest:
state, stateErr := p.server.State(context.Background())
if stateErr != nil {
p.log.Println("failed to read server state:", stateErr)
status, statusErr := p.getServerStatus(time.Second * 10)
if statusErr == nil {
err := conn.WritePacket(status)
if err != nil {
return err
}
}
return statusErr
}
p.mutex.Lock()
pStatus := p.status
lastStartDuration := p.lastStartDuration
lastStart := p.lastStart
p.mutex.Unlock()
var resp protocol.StatusResponse
resp.JSONResponse.Players.Online = 0
resp.JSONResponse.Players.Max = pStatus.maxPlayers
resp.JSONResponse.Version.Name = pStatus.versionName
resp.JSONResponse.Version.Protocol = pStatus.protocolVersion
resp.JSONResponse.Favicon = pStatus.favicon
resp.JSONResponse.EnforceSecureChat = pStatus.enforceSecureChat
switch state {
case ServerStateOff:
resp.JSONResponse.Description = fmt.Sprintf("(sleeping) %v", pStatus.description)
case ServerStateStarting:
if !lastStart.IsZero() && lastStartDuration != 0 {
resp.JSONResponse.Description = fmt.Sprintf(
"(starting approx %v) %v",
lastStart.Add(lastStartDuration).Sub(time.Now()).Round(time.Second),
pStatus.description,
)
} else {
resp.JSONResponse.Description = fmt.Sprintf("(starting) %v", pStatus.description)
}
case ServerStateOn:
status, err := p.getServerStatus(time.Second)
if err == nil {
resp = *status
p.mutex.Lock()
if !p.shutdownTime.IsZero() {
resp.JSONResponse.Description = fmt.Sprintf("(shutdown in %v) %v", p.shutdownTime.Sub(time.Now()).Round(time.Second), status.JSONResponse.Description)
}
p.mutex.Unlock()
} else {
if lastStart.Add(lastStartDuration).Before(time.Now()) { //don't mind if these are both nil
resp.JSONResponse.Description = fmt.Sprintf("(not responding) %v", pStatus.description)
} else {
if !lastStart.IsZero() && lastStartDuration != 0 {
resp.JSONResponse.Description = fmt.Sprintf(
"(starting approx %v) %v",
lastStart.Add(lastStartDuration).Sub(time.Now()).Round(time.Second),
pStatus.description,
)
} else {
resp.JSONResponse.Description = fmt.Sprintf("(starting) %v", pStatus.description)
}
}
}
case ServerStateStopping:
resp.JSONResponse.Description = fmt.Sprintf("(stopping) %v", pStatus.description)
}
err = conn.WritePacket(&resp)
if err != nil {
return err
}
case *protocol.PingRequest:
var pongResponse protocol.PongResponse
pongResponse.Payload = packet.Payload
err := conn.WritePacket(&pongResponse)
if err != nil {
return err
}
}
}
}
func (p *Proxy) HandleLogin(handshake *protocol.HandshakeIntention, mcconn *protocol.Conn, raddr net.Addr) error {
p.log.Println("login from", raddr)
p.mutex.Lock()
p.players++
p.shutdownTime = time.Time{}
if p.shutdownTimer.Stop() {
p.log.Println("canceled shutdown")
}
p.mutex.Unlock()
defer func() {
p.mutex.Lock()
p.players--
if p.players == 0 {
p.shutdownTime = time.Now().Add(p.shutdown_timeout)
p.log.Println("scheduling shutdown for", p.shutdownTime.Round(time.Second))
p.shutdownTimer.Reset(p.shutdown_timeout)
}
p.mutex.Unlock()
}()
serverState, err := p.server.State(context.Background())
if err != nil {
p.log.Println(err)
_, mcErr := p.getServerStatus(time.Second * 10)
if mcErr == nil {
return p.pipeClient(handshake, mcconn)
} else {
var disconect protocol.Disconnect
disconect.JSONTextComponent.Text = "Server is f**ked. Sorry choom."
return mcconn.WritePacket(&disconect)
}
}
switch serverState {
case ServerStateOff:
var disconnect protocol.Disconnect
err := p.startServer()
if err != nil {
disconnect.JSONTextComponent.Text = fmt.Sprintf("Failed to start server: %v", err)
} else {
time.Sleep(time.Second * 10)
p.mutex.Lock()
lastStart := p.lastStart
lastStartDuration := p.lastStartDuration
p.mutex.Unlock()
if !lastStart.IsZero() && lastStartDuration != 0 {
disconnect.JSONTextComponent.Text = fmt.Sprintf(
"Server is started. Should be up in approx %v",
lastStart.Add(lastStartDuration).Sub(time.Now()).Round(time.Second),
)
} else {
disconnect.JSONTextComponent.Text = "Server has been started"
}
}
return mcconn.WritePacket(&disconnect)
case ServerStateStarting:
start := time.Now()
t := time.NewTicker(time.Second)
for now := range t.C {
_, err := p.getServerStatus(time.Second * 10)
if err == nil {
return p.pipeClient(handshake, mcconn)
}
if start.Add(time.Second * 10).Before(now) {
break
}
}
var disconect protocol.Disconnect
p.mutex.Lock()
lastStartDuration := p.lastStartDuration
lastStart := p.lastStart
p.mutex.Unlock()
if !lastStart.IsZero() && lastStartDuration != 0 {
disconect.JSONTextComponent.Text = fmt.Sprintf(
"Server is starting. Should be up in approx %v",
lastStart.Add(lastStartDuration).Sub(time.Now()),
)
} else {
disconect.JSONTextComponent.Text = "Server is starting"
}
return mcconn.WritePacket(&disconect)
case ServerStateOn:
for range 10 {
_, err := p.getServerStatus(time.Second * 10)
if err == nil {
return p.pipeClient(handshake, mcconn)
}
time.Sleep(time.Second * 2)
}
return p.pipeClient(handshake, mcconn)
case ServerStateStopping:
var disconect protocol.Disconnect
disconect.JSONTextComponent.Text = "Try again soon (server is halfway through shutting down)"
return mcconn.WritePacket(&disconect)
}
var disconect protocol.Disconnect
disconect.JSONTextComponent.Text = "This should never happen"
return mcconn.WritePacket(&disconect)
}
func (p *Proxy) pipeClient(handshake *protocol.HandshakeIntention, mcconn *protocol.Conn) error {
conn, err := net.Dial("tcp", fmt.Sprintf("%v:%v", p.destination_ip, p.destination_port))
if err != nil {
return err
}
return mcconn.PipeTo(context.Background(), handshake, conn)
}
func (p *Proxy) getServerStatus(timeout time.Duration) (*protocol.StatusResponse, error) {
conn, err := net.DialTimeout(
"tcp",
fmt.Sprintf("%v:%v", p.destination_ip, p.destination_port),
timeout,
)
if err != nil {
return &protocol.StatusResponse{}, err
}
defer conn.Close()
err = conn.SetDeadline(time.Now().Add(time.Second * 3))
if err != nil {
return &protocol.StatusResponse{}, err
}
p.mutex.Lock()
protocolVersion := p.status.protocolVersion
p.mutex.Unlock()
mcconn := protocol.NewConn(conn)
err = mcconn.WritePacket(&protocol.HandshakeIntention{
ProtocolVersion: protocol.VarInt(protocolVersion),
ServerAddress: protocol.String255(p.destination_ip),
ServerPort: protocol.UShort(p.destination_port),
NextState: protocol.StateStatus,
})
if err != nil {
return &protocol.StatusResponse{}, err
}
err = mcconn.WritePacket(&protocol.StatusRequest{})
if err != nil {
return &protocol.StatusResponse{}, err
}
resposePacket, err := mcconn.ReadPacket(&protocol.StatusResponse{})
if err != nil {
return &protocol.StatusResponse{}, err
}
statusResponse := resposePacket.(*protocol.StatusResponse)
go func() {
p.mutex.Lock()
p.status.description = statusResponse.JSONResponse.Description
p.status.enforceSecureChat = statusResponse.JSONResponse.EnforceSecureChat
p.status.favicon = statusResponse.JSONResponse.Favicon
p.status.maxPlayers = statusResponse.JSONResponse.Players.Max
p.status.protocolVersion = statusResponse.JSONResponse.Version.Protocol
p.status.versionName = statusResponse.JSONResponse.Version.Name
p.mutex.Unlock()
}()
return statusResponse, err
}