This repository has been archived by the owner on Mar 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
371 lines (319 loc) · 7.59 KB
/
main.go
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"runtime"
"strings"
"time"
)
type ConnectionRequest struct {
Log *Logger `json:"-"`
Client string `json:"client"`
ClientAddr string `json:"client_address"`
Version string `json:"version"`
Username string `json:"username"`
TargetHost string `json:"target_host"`
ReplyKey string `json:"reply_key"`
}
type ConnectionRequestReply struct {
Host string `json:"host"`
Port int `json:"port"`
Failed string `json:"failed"`
}
type Init func(net.Conn)
type Approved func(net.Conn, Init, string, string, string)
type Denied func(net.Conn, string)
type Timeout func(net.Conn)
var redisClient *RedisClient
var log *Logger
var prismId string
func handleConnection(c net.Conn) {
r := NewMcReader(c)
header, err := r.Header()
if err != nil {
log.Warn(map[string]interface{}{
"event": "header read failed",
})
}
if header == 0xFE {
handleServerPing(c)
} else if header == 0x02 {
if !maintenanceMode(c) {
handleLogin(c)
}
}
}
func maintenanceMode(c net.Conn) bool {
msg := redisClient.GetMaintenenceMsg()
if msg == "" {
return false
}
defer c.Close()
w := NewMcWriter(c)
w.KickPacket(KickPacket{
Reason: msg,
})
return true
}
func handleLogin(c net.Conn) {
buf := new(bytes.Buffer)
tee := io.TeeReader(c, buf)
client := "minecraft"
var version string
var username string
var targetHost string
var connInit Init
r := NewMcReader(tee)
pkt, err := r.HandshakePacket()
if err != nil {
// try old handshake packet
r = NewMcReader(buf)
oldPkt, err := r.OldHandshakePacket()
if err != nil {
log.Error(err, map[string]interface{}{
"event": "bad handshake",
})
c.Close()
return
}
version = "1.2.5"
// username in old packet looks like this:
// whatupdave;4.foldserver.com:25565
parts := strings.Split(oldPkt.Username, ";")
if len(parts) < 2 {
log.Error(err, map[string]interface{}{
"event": "bad handshake",
"username": oldPkt.Username,
})
c.Close()
return
}
username = parts[0]
parts = strings.Split(parts[1], ":")
targetHost = parts[0]
connInit = func(remote net.Conn) {
w := NewMcWriter(remote)
w.OldHandshakePacket(*oldPkt)
}
} else {
version = fmt.Sprintf("%v", pkt.ProtocolVersion)
username = pkt.Username
targetHost = pkt.Host
connInit = func(remote net.Conn) {
w := NewMcWriter(remote)
w.HandshakePacket(*pkt)
}
}
clientAddr := c.RemoteAddr().String()
req := NewConnectionRequest(client, version, clientAddr, username, targetHost)
req.Process(c, connInit)
}
func NewConnectionRequest(client, version, clientAddr, username, targetHost string) *ConnectionRequest {
req := &ConnectionRequest{
Client: client,
Version: version,
ClientAddr: clientAddr,
Username: username,
TargetHost: targetHost,
}
req.Log = NewLog(map[string]interface{}{
"version": req.Version,
"client_addr": req.ClientAddr,
"username": req.Username,
"target_host": req.TargetHost,
})
return req
}
func sendKeepAlive(c net.Conn) error {
w := NewMcWriter(c)
w.KeepAlivePacket(KeepAlivePacket{
Id: 1337,
})
// read keepalive response from client to get it off the
// connection
r := NewMcReader(c)
_, err := r.Header()
if err != nil {
return err
}
_, err = r.KeepAlive()
return err
}
func (req *ConnectionRequest) Process(c net.Conn, init Init) {
req.Log.Info(map[string]interface{}{
"event": "login_request",
})
work := func() {
conn := NewRedisConnection(prismId)
defer conn.Quit()
sub, err := conn.ConnectionReqReply(req.Username)
defer sub.Close()
if err != nil {
req.Log.Error(err, map[string]interface{}{
"event": "redis_subscribe",
})
return
}
connEnded := make(chan int, 1)
// keep connection alive for 5 minute
timeoutCb := time.After(5 * time.Minute)
// send keepalive packets to client every 15 seconds
keepalive := time.NewTicker(15 * time.Second)
defer keepalive.Stop()
go func() {
for _ = range keepalive.C {
err := sendKeepAlive(c)
if err != nil {
req.Log.Info(map[string]interface{}{
"event": "disconnected",
})
connEnded <- 1
break
}
}
}()
select {
case message := <-sub.Messages:
// connection request reply from brain/prism-buddy
// will have failed: reason if bad
// otherwise it's approved
var reply ConnectionRequestReply
err := json.Unmarshal(message.Elem.Bytes(), &reply)
if err != nil {
req.Log.Error(err, map[string]interface{}{
"event": "bad_req_reply",
"reply": message.Elem.String(),
})
c.Close()
} else if reply.Failed != "" {
req.Denied(c, reply.Failed)
} else {
remoteAddr := fmt.Sprintf("%s:%d", reply.Host, reply.Port)
req.Approved(c, init, remoteAddr)
}
case <-timeoutCb:
req.Timeout(c)
case <-connEnded:
}
}
go work()
// send connection request to brain/prism-buddy
redisClient.PushConnectionReq(req)
}
func (req *ConnectionRequest) Approved(c net.Conn, init Init, remoteAddr string) {
req.Log.Info(map[string]interface{}{
"event": "login_request_approved",
"remote": remoteAddr,
})
// send keepalive to see if the client is still connected
err := sendKeepAlive(c)
if err != nil {
return
}
go req.ProxyConnection(c, remoteAddr, init)
}
func (req *ConnectionRequest) Denied(c net.Conn, reason string) {
defer c.Close()
req.Log.Info(map[string]interface{}{
"event": "login_request_denied",
"reason": reason,
})
w := NewMcWriter(c)
w.KickPacket(KickPacket{
Reason: reason,
})
}
func (req *ConnectionRequest) Timeout(c net.Conn) {
defer c.Close()
req.Log.Error(errors.New("timeout"), map[string]interface{}{
"event": "login_request_timeout",
})
w := NewMcWriter(c)
w.KickPacket(KickPacket{
Reason: "Minefold is having technical difficulties. Please try again",
})
}
func handleServerPing(c net.Conn) {
defer c.Close()
w := NewMcWriter(c)
w.KickPacket(KickPacket{
Reason: fmt.Sprintf(
"§1\000%s\000%s\000%s\000-1\000-1",
redisClient.Protocol(),
redisClient.BadProtocolMsg(),
redisClient.Motd()),
})
}
func (req *ConnectionRequest) ProxyConnection(client net.Conn, remoteAddr string, init Init) {
defer client.Close()
defer redisClient.RemovePlayer(req.Username)
redisClient.AddPlayer(req.Username)
remote, err := net.Dial("tcp", remoteAddr)
if remote == nil || err != nil {
req.Log.Error(err, map[string]interface{}{
"event": "failed_connection",
"remote": remoteAddr,
})
return
}
req.Log.Info(map[string]interface{}{
"event": "start_proxy",
"remote": remoteAddr,
})
init(remote)
go io.Copy(client, remote)
io.Copy(remote, client)
req.Log.Info(map[string]interface{}{
"event": "stop_proxy",
"remote": remoteAddr,
})
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
prismId = os.Args[1]
redisClient = NewRedisConnection(prismId)
redisClient.ClearPlayerSet()
if redisClient.Protocol() == "" {
fmt.Println("set", redisClient.protocolKey)
os.Exit(1)
}
if redisClient.BadProtocolMsg() == "" {
fmt.Println("set", redisClient.badProtocolKey)
os.Exit(1)
}
if redisClient.Motd() == "" {
fmt.Println("set", redisClient.motdKey)
os.Exit(1)
}
port := os.Getenv("PORT")
if port == "" {
port = "25565"
}
log = NewLog(map[string]interface{}{
"prism": prismId,
})
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
panic(err)
}
log.Info(map[string]interface{}{
"event": "listening",
"port": port,
"gomaxprocs": runtime.GOMAXPROCS(-1),
})
for {
conn, err := ln.Accept()
if err != nil {
log.Error(err, map[string]interface{}{
"event": "socket_accept",
})
continue
}
go handleConnection(conn)
}
}