-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
320 lines (270 loc) · 8.28 KB
/
proxy.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
package main
import (
"bufio"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
)
const (
NetDeadline = time.Second * 5
DialTimeout = time.Second * 5
ProxyBind = ""
)
func startMinecraftProxy() {
listener, err := net.Listen("tcp", cfg.Listen)
if err != nil {
fmt.Println("Error starting server:", err)
return
}
defer listener.Close()
fmt.Println("Proxy server listening on ", cfg.Listen)
for {
clientConn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(clientConn)
}
}
func handleConnection(clientConn net.Conn) {
reader := bufio.NewReader(clientConn)
// Установка таймаута для предотвращения зависания при ожидании данных
clientConn.SetDeadline(time.Now().Add(NetDeadline))
// Попробуем прочитать первую строку как HTTP запрос
firstLine, err := reader.Peek(7) // GET или HTTP
if err == nil && (strings.HasPrefix(string(firstLine), "GET") || strings.HasPrefix(string(firstLine), "HTTP")) {
handleResourcePackRequest(clientConn, reader)
return
}
// Read handshake
packet, err := ReadPacket(reader)
if err != nil {
log.Println("Error reading handshake:", err)
clientConn.Close()
return
}
handshake, err := DecodeServerBoundHandshake(packet)
if err != nil {
log.Printf("error while parsing handshake: %v\n", err)
clientConn.Close()
return
}
// Check access
userInfo := getUserInfoByHostname(handshake.Address)
if userInfo == nil {
clientConn.Close()
return
}
// Reset deadline
clientConn.SetDeadline(time.Time{})
if handshake.NextState == HandshakeStatus {
handleStatusRequest(clientConn, handshake)
} else if handshake.NextState == HandshakeLogin {
handleLoginRequest(clientConn, handshake, userInfo)
} else {
log.Printf("Unknown handshake.NextState: %v\n", err)
clientConn.Close()
}
}
func handleStatusRequest(clientConn net.Conn, handshake ServerBoundHandshake) {
err := ProxyConnection(clientConn, cfg.MinecraftServer, handshake.ToPacket().Encode())
if err != nil {
var packet Packet
packet.ID = 0
status := StatusJSON{
Version: StatusVersionJSON{
Name: "Some server",
Protocol: int(handshake.ProtocolVersion),
},
Description: StatusDescriptionJSON{
Text: "Offline",
},
}
statusBytes, err := json.Marshal(status)
if err != nil {
clientConn.Close()
return
}
packet.Data = McString(statusBytes).Encode()
clientConn.Write(packet.Encode())
}
}
func handleLoginRequest(clientConn net.Conn, handshake ServerBoundHandshake, userInfo *StorageRecord) {
peekedData := handshake.ToPacket().Encode()
packet, err := ReadPacket(bufio.NewReader(clientConn))
if err != nil {
log.Println("Error reading LoginStart:", err)
clientConn.Close()
return
}
var passedUsername string
switch handshake.ProtocolVersion {
// 1.18.2 and older
default:
var login ServerLoginStartOLD
login, err = DecodeServerBoundLoginStartOLD(packet)
passedUsername = string(login.Nickname)
login.Nickname = McString(userInfo.Nickname)
peekedData = append(peekedData, login.ToPacket().Encode()...)
// 1.19 - 1.19.2
case 759: // 1.19
fallthrough
case 760: // 1.19.2
var login ServerLoginStart759
login, err = DecodeServerBoundLoginStart759(packet)
passedUsername = string(login.Nickname)
login.HasUUID = 1
login.Nickname = McString(userInfo.Nickname)
login.UUID = generateUUID(string(login.Nickname))
peekedData = append(peekedData, login.ToPacket().Encode()...)
// 1.19.3 - 1.20.1
case 761: // 1.19.3
fallthrough
case 762: // 1.19.4
fallthrough
case 763: // 1.20 - 1.20.1
var login ServerLoginStart761
login, err = DecodeServerBoundLoginStart761(packet)
passedUsername = string(login.Nickname)
login.HasUUID = 1
login.Nickname = McString(userInfo.Nickname)
login.UUID = generateUUID(string(login.Nickname))
peekedData = append(peekedData, login.ToPacket().Encode()...)
// 1.20.2 - last
case 764: // 1.20.2
fallthrough
case 765: // 1.20.3 - 1.20.4
fallthrough
case 766: // 1.20.5 - 1.20.6
fallthrough
case 767: // 1.21.1
fallthrough
case 768: // 1.21.2
var login ServerLoginStart764
login, err = DecodeServerBoundLoginStart764(packet)
passedUsername = string(login.Nickname)
login.Nickname = McString(userInfo.Nickname)
login.UUID = generateUUID(string(login.Nickname))
peekedData = append(peekedData, login.ToPacket().Encode()...)
}
if err != nil {
log.Printf("error while parsing LoginStart: %v\n", err)
clientConn.Close()
return
}
addPlayer(userInfo.Nickname)
updateOnlineMessage()
log.Printf("User %s connected to %s from %s. Nickname %s -> %s\n", userInfo.TgName, cfg.BaseDomain, clientConn.RemoteAddr().String(), passedUsername, userInfo.Nickname)
ProxyConnection(clientConn, cfg.MinecraftServer, peekedData)
removePlayer(userInfo.Nickname)
updateOnlineMessage()
log.Printf("User %s disconnected. Nickname: %s\n", userInfo.TgName, userInfo.Nickname)
}
func handleResourcePackRequest(clientConn net.Conn, reader *bufio.Reader) {
// Читаем HTTP запрос
request, err := http.ReadRequest(reader)
if err != nil {
log.Printf("Error reading HTTP request: %v\n", err)
clientConn.Close()
return
}
userInfo := getUserInfoByHostname(request.Host)
if userInfo == nil {
log.Printf("Reject HTTP request to: %s\n", request.URL.String())
clientConn.Close()
return
}
log.Printf("Transferring resource pack `%s` to %s", request.URL.String(), userInfo.TgName)
// Создаем HTTP клиент для проксирования запроса
httpClient := &http.Client{
Timeout: time.Second * 30,
}
// Создаем новый запрос к целевому серверу
proxyURL := "http://" + cfg.MinecraftServer + request.URL.Path
proxyReq, err := http.NewRequest(request.Method, proxyURL, request.Body)
if err != nil {
log.Printf("Error creating proxy request: %v\n", err)
clientConn.Close()
return
}
// Копируем заголовки
proxyReq.Header = request.Header
// Выполняем запрос
response, err := httpClient.Do(proxyReq)
if err != nil {
log.Printf("Error making proxy request: %v\n", err)
clientConn.Close()
return
}
defer response.Body.Close()
// Отправляем ответ клиенту
err = response.Write(clientConn)
if err != nil {
log.Printf("Error writing response: %v\n", err)
}
clientConn.Close()
}
///////////////////////////////////////////////////////////////////////////////
func generateUUID(username string) McUUID {
username = "OfflinePlayer:" + username
return NameUUIDFromBytes([]byte(username))
}
// https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/9a91972c76ddda5c1ce28b50ca38cbd8a30b7a72/jdk/src/share/classes/java/util/UUID.java#L153-L175
func NameUUIDFromBytes(name []byte) McUUID {
var uuid McUUID
// Вычисляем MD5 хэш от входных данных.
hash := md5.Sum(name)
// Устанавливаем версию UUID (версия 3).
hash[6] &= 0x0f // Очистка верхних 4 бит.
hash[6] |= 0x30 // Установка версии 3 (0011).
// Устанавливаем вариант UUID (IETF).
hash[8] &= 0x3f // Очистка верхних 2 бит.
hash[8] |= 0x80 // Установка варианта (10).
// Копируем хэш в UUID.
copy(uuid[:], hash[:])
return uuid
}
///////////////////////////////////////////////////////////////////////////////
var bufferPool = sync.Pool{
New: func() interface{} {
return make([]byte, 32*1024)
},
}
func ProxyConnection(clientConn net.Conn, serverAddr string, peekedData []byte) (err error) {
dialer := net.Dialer{
Timeout: DialTimeout,
LocalAddr: &net.TCPAddr{
IP: net.ParseIP(ProxyBind),
},
}
serverConn, err := dialer.Dial("tcp", serverAddr)
if err != nil {
return err
}
_, err = serverConn.Write(peekedData)
if err != nil {
log.Printf("Error writing to server connection: %v\n", err)
clientConn.Close()
serverConn.Close()
return err
}
go func() {
buffer := bufferPool.Get().([]byte)
defer bufferPool.Put(buffer)
io.CopyBuffer(serverConn, clientConn, buffer)
clientConn.Close()
}()
buffer := bufferPool.Get().([]byte)
defer bufferPool.Put(buffer)
io.CopyBuffer(clientConn, serverConn, buffer)
serverConn.Close()
return nil
}