-
Notifications
You must be signed in to change notification settings - Fork 59
/
session_out_bridge.go
360 lines (344 loc) · 13.6 KB
/
session_out_bridge.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
package proxy
import (
"bytes"
"fmt"
"github.com/LilyPad/GoLilyPad/packet"
"github.com/LilyPad/GoLilyPad/packet/minecraft"
mc17 "github.com/LilyPad/GoLilyPad/packet/minecraft/v17"
mc19 "github.com/LilyPad/GoLilyPad/packet/minecraft/v19"
"github.com/LilyPad/GoLilyPad/server/proxy/api"
"github.com/LilyPad/GoLilyPad/server/proxy/connect"
uuid "github.com/satori/go.uuid"
"net"
"strconv"
"time"
)
type SessionOutBridge struct {
session *Session
protocol *minecraft.Version
server *connect.Server
conn net.Conn
connCodec *packet.PacketConnCodec
pipeline *packet.PacketPipeline
apiOutBridge api.OutBridge
compressionThreshold int
remoteIp string
remotePort string
state SessionState
disconnectErr error
}
func NewSessionOutBridge(session *Session, server *connect.Server, conn net.Conn) (this *SessionOutBridge) {
this = new(SessionOutBridge)
this.session = session
this.protocol = this.session.protocol
this.server = server
this.conn = conn
this.apiOutBridge = &apiOutBridge{this}
this.compressionThreshold = -1
this.remoteIp, this.remotePort, _ = net.SplitHostPort(conn.RemoteAddr().String())
this.state = STATE_DISCONNECTED
return
}
func (this *SessionOutBridge) Serve() {
this.session.activeServersLock.Lock()
if _, ok := this.session.activeServers[this.server.Name]; ok {
this.conn.Close()
this.session.activeServersLock.Unlock()
return
}
this.session.activeServers[this.server.Name] = struct{}{}
this.session.activeServersLock.Unlock()
this.pipeline = packet.NewPacketPipeline()
this.pipeline.AddLast("varIntLength", packet.NewPacketCodecVarIntLength())
this.pipeline.AddLast("registry", minecraft.HandshakePacketClientCodec)
this.connCodec = packet.NewPacketConnCodec(this.conn, this.pipeline, 20*time.Second)
inRemotePort, _ := strconv.ParseUint(this.session.remotePort, 10, 16)
outRemotePort, _ := strconv.ParseUint(this.remotePort, 10, 16)
loginPayload := LoginPayload{
SecurityKey: this.server.SecurityKey,
Host: this.session.rawServerAddress,
RealIp: this.session.remoteIp,
RealPort: int(inRemotePort),
Name: this.session.name,
UUID: this.session.profile.Id,
Properties: make([]LoginPayloadProperty, 0),
}
for _, property := range this.session.profile.Properties {
loginPayload.Properties = append(loginPayload.Properties, LoginPayloadProperty{property.Name, property.Value, property.Signature})
}
this.Write(minecraft.NewPacketServerHandshake(this.session.protocolVersion, EncodeLoginPayload(loginPayload), uint16(outRemotePort), 2))
this.pipeline.Replace("registry", this.protocol.LoginClientCodec)
this.Write(minecraft.NewPacketServerLoginStart(this.protocol.IdMap, this.session.name, &this.session.uuid))
this.state = STATE_LOGIN
go this.connCodec.ReadConn(this)
}
func (this *SessionOutBridge) Write(packet packet.Packet) (err error) {
event := this.session.server.apiEventBus.fireEventSessionPacket(this.session, &packet, api.PacketStagePre, api.PacketSubjectOutBridge, api.PacketDirectionWrite)
if event.IsCancelled() {
return
}
err = this.connCodec.Write(packet)
if err != nil {
return
}
this.session.server.apiEventBus.fireEventSessionPacket(this.session, &packet, api.PacketStageMonitor, api.PacketSubjectOutBridge, api.PacketDirectionWrite)
return
}
func (this *SessionOutBridge) EnsureCompression() {
this.SetCompression(this.compressionThreshold)
}
func (this *SessionOutBridge) SetCompression(threshold int) {
if this.state == STATE_INIT || this.state == STATE_CONNECTED {
this.session.SetCompression(threshold)
}
if this.compressionThreshold == threshold {
return
}
this.compressionThreshold = threshold
if threshold == -1 {
this.pipeline.Remove("zlib")
return
} else {
codec := packet.NewPacketCodecZlib(threshold)
if this.pipeline.HasName("zlib") {
this.pipeline.Replace("zlib", codec)
} else {
this.pipeline.AddBefore("zlib", "registry", codec)
}
}
}
func (this *SessionOutBridge) HandlePacket(packet packet.Packet) (err error) {
if !this.session.Authenticated() {
this.conn.Close()
return
}
event := this.session.server.apiEventBus.fireEventSessionPacket(this.session, &packet, api.PacketStagePre, api.PacketSubjectOutBridge, api.PacketDirectionRead)
if event.IsCancelled() {
return
}
err = this.handlePacket(packet)
if err != nil {
return
}
this.session.server.apiEventBus.fireEventSessionPacket(this.session, &packet, api.PacketStageMonitor, api.PacketSubjectOutBridge, api.PacketDirectionRead)
return
}
func (this *SessionOutBridge) handlePacket(packet packet.Packet) (err error) {
switch this.state {
case STATE_LOGIN:
if packet.Id() == this.protocol.IdMap.PacketClientLoginSuccess {
this.session.redirectMutex.Lock() // Prevent other outbridges from connecting
this.state = STATE_INIT
this.session.redirecting = true
this.EnsureCompression()
this.pipeline.Replace("registry", this.protocol.PlayClientCodec)
} else if packet.Id() == this.protocol.IdMap.PacketClientLoginDisconnect {
this.session.DisconnectJson(packet.(*minecraft.PacketClientLoginDisconnect).Json)
this.conn.Close()
} else if packet.Id() == this.protocol.IdMap.PacketClientLoginSetCompression {
this.SetCompression(packet.(*minecraft.PacketClientLoginSetCompression).Threshold)
} else {
if this.session.Initializing() {
this.session.Disconnect(fmt.Sprintf("Error: Outbound Protocol Mismatch: %d", packet.Id()))
}
this.conn.Close()
}
case STATE_INIT:
if packet.Id() == this.protocol.IdMap.PacketClientPlayerPositionandLook {
this.session.outBridge = this
this.session.redirecting = false
this.session.SetState(STATE_CONNECTED)
this.state = STATE_CONNECTED
this.session.redirectMutex.Unlock()
}
fallthrough
case STATE_CONNECTED:
if this.state == STATE_CONNECTED {
this.session.redirectMutex.Lock() // Ensure we are the current outbridge
if this.session.outBridge == this {
err = this.handlePacketConnected(packet)
} else {
// If not, close ourself
this.session.outBridge.EnsureCompression()
this.conn.Close()
}
this.session.redirectMutex.Unlock()
} else {
err = this.handlePacketConnected(packet)
}
}
return
}
func (this *SessionOutBridge) handlePacketConnected(packet packet.Packet) (err error) {
id := packet.Id()
if id == this.protocol.IdMap.PacketClientJoinGame {
joinGamePacket := packet.(*minecraft.PacketClientJoinGame)
if this.session.mcBrand != nil {
this.Write(this.session.mcBrand)
}
if this.session.clientSettings != nil {
this.Write(this.session.clientSettings)
}
this.session.serverEntityId = joinGamePacket.EntityId
if this.session.state == STATE_INIT {
this.session.clientEntityId = joinGamePacket.EntityId
} else {
if joinGamePacket.DimensionCodec != nil {
// 1.16+
this.session.Write(joinGamePacket)
this.session.clientEntityId = joinGamePacket.EntityId
} else {
var swapDimension int32
if joinGamePacket.Dimension == 0 {
swapDimension = 1
} else {
swapDimension = 0
}
swapRespawn := minecraft.NewPacketClientRespawnFrom(this.protocol.IdMap, joinGamePacket)
swapRespawn.Dimension = swapDimension
this.session.Write(swapRespawn)
this.session.Write(minecraft.NewPacketClientRespawnFrom(this.protocol.IdMap, joinGamePacket))
}
if this.protocol.IdMap.PacketClientUpdateViewDistance != -1 {
this.session.Write(minecraft.NewPacketClientViewDistance(this.protocol.IdMap, joinGamePacket.ViewDistance))
}
if len(this.session.playerList) > 0 {
if this.protocol == mc17.Version {
for player := range this.session.playerList {
this.session.Write(mc17.NewPacketClientPlayerListRemove(player))
}
} else if this.session.protocolVersion < 761 { // < 1.19.3
items := make([]minecraft.PacketClientPlayerListItem, 0, len(this.session.playerList))
for uuidString := range this.session.playerList {
uuid, _ := uuid.FromBytes([]byte(uuidString))
items = append(items, minecraft.PacketClientPlayerListItem{UUID: uuid})
}
this.session.Write(minecraft.NewPacketClientPlayerList(this.protocol.IdMap, minecraft.PACKET_CLIENT_PLAYER_LIST_ACTION_REMOVE, items))
} else {
uuids := make([]uuid.UUID, 0, len(this.session.playerList))
for uuidString := range this.session.playerList {
uuid, _ := uuid.FromBytes([]byte(uuidString))
uuids = append(uuids, uuid)
}
this.session.Write(minecraft.NewPacketClientPlayerInfoRemove(this.protocol.IdMap, uuids))
}
this.session.playerList = make(map[string]struct{})
}
if len(this.session.scoreboards) > 0 {
for scoreboard := range this.session.scoreboards {
this.session.Write(minecraft.NewPacketClientScoreboardObjectiveRemove(this.protocol.IdMap, scoreboard))
}
this.session.scoreboards = make(map[string]struct{})
}
if len(this.session.teams) > 0 {
for team := range this.session.teams {
this.session.Write(minecraft.NewPacketClientTeamsRemove(this.protocol.IdMap, team))
}
this.session.teams = make(map[string]struct{})
}
if len(this.session.pluginChannels) > 0 {
channels := make([][]byte, 0, len(this.session.pluginChannels))
for channel := range this.session.pluginChannels {
channels = append(channels, []byte(channel))
}
this.Write(minecraft.NewPacketServerPluginMessage(this.protocol.IdMap, "REGISTER", bytes.Join(channels, []byte{0})))
}
if len(this.session.bossBars) > 0 {
for uuidString := range this.session.bossBars {
uuid, _ := uuid.FromBytes([]byte(uuidString))
this.session.Write(mc19.NewPacketClientBossBarRemove(this.protocol.IdMap, uuid))
}
}
if joinGamePacket.DimensionCodec != nil {
// 1.16+
respawn := minecraft.NewPacketClientRespawnFrom(this.protocol.IdMap, joinGamePacket)
respawn.CopyMetadata = false
this.session.Write(respawn)
}
return
}
} else if id == this.protocol.IdMap.PacketClientPlayerList {
if this.protocol == mc17.Version {
playerListPacket := packet.(*mc17.PacketClientPlayerList)
if playerListPacket.Online {
this.session.playerList[playerListPacket.Name] = struct{}{}
} else {
delete(this.session.playerList, playerListPacket.Name)
}
} else {
playerListPacket := packet.(*minecraft.PacketClientPlayerList)
if playerListPacket.Action == minecraft.PACKET_CLIENT_PLAYER_LIST_ACTION_ADD {
for _, item := range playerListPacket.Items {
this.session.playerList[string(item.UUID[:])] = struct{}{}
}
} else if playerListPacket.Action == minecraft.PACKET_CLIENT_PLAYER_LIST_ACTION_REMOVE {
for _, item := range playerListPacket.Items {
delete(this.session.playerList, string(item.UUID[:]))
}
}
}
} else if id == this.protocol.IdMap.PacketClientPlayerInfoRemove {
playerInfoRemovePacket := packet.(*minecraft.PacketClientPlayerInfoRemove)
for _, uuid := range playerInfoRemovePacket.UUIDs {
delete(this.session.playerList, string(uuid[:]))
}
} else if id == this.protocol.IdMap.PacketClientPlayerInfoUpdate {
playerInfoUpdatePacket := packet.(*minecraft.PacketClientPlayerInfoUpdate)
for _, item := range playerInfoUpdatePacket.Items {
for _, action := range playerInfoUpdatePacket.Actions {
if action == minecraft.PACKET_CLIENT_PLAYER_INFO_UPDATE_ACTION_ADD_PLAYER {
this.session.playerList[string(item.UUID[:])] = struct{}{}
}
}
}
} else if id == this.protocol.IdMap.PacketClientScoreboardObjective {
scoreboardPacket := packet.(*minecraft.PacketClientScoreboardObjective)
if scoreboardPacket.Action == minecraft.PACKET_CLIENT_SCOREBOARD_OBJECTIVE_ACTION_ADD {
this.session.scoreboards[scoreboardPacket.Name] = struct{}{}
} else if scoreboardPacket.Action == minecraft.PACKET_CLIENT_SCOREBOARD_OBJECTIVE_ACTION_REMOVE {
delete(this.session.scoreboards, scoreboardPacket.Name)
}
} else if id == this.protocol.IdMap.PacketClientTeams {
teamPacket := packet.(*minecraft.PacketClientTeams)
if teamPacket.Action == minecraft.PACKET_CLIENT_TEAMS_ACTION_ADD {
this.session.teams[teamPacket.Name] = struct{}{}
} else if teamPacket.Action == minecraft.PACKET_CLIENT_TEAMS_ACTION_REMOVE {
delete(this.session.teams, teamPacket.Name)
}
} else if id == this.protocol.IdMap.PacketClientBossBar {
bossBarPacket := packet.(*mc19.PacketClientBossBar)
if bossBarPacket.Action == mc19.PACKET_CLIENT_BOSS_BAR_ACTION_ADD {
this.session.bossBars[string(bossBarPacket.UUID[:])] = struct{}{}
} else if bossBarPacket.Action == mc19.PACKET_CLIENT_BOSS_BAR_ACTION_REMOVE {
delete(this.session.bossBars, string(bossBarPacket.UUID[:]))
}
} else if id == this.protocol.IdMap.PacketClientDisconnect {
this.state = STATE_DISCONNECTED
this.session.DisconnectJson(packet.(*minecraft.PacketClientDisconnect).Json)
return
} else if id == this.protocol.IdMap.PacketClientSetCompression {
this.SetCompression(packet.(*minecraft.PacketClientSetCompression).Threshold)
return
} else {
if genericPacket, ok := packet.(*minecraft.PacketGeneric); ok {
genericPacket.SwapEntities(this.session.clientEntityId, this.session.serverEntityId, true)
}
}
this.session.Write(packet)
return
}
func (this *SessionOutBridge) ErrorCaught(err error) {
this.session.activeServersLock.Lock()
delete(this.session.activeServers, this.server.Name)
this.session.activeServersLock.Unlock()
if this.state == STATE_INIT {
this.session.redirecting = false
this.session.redirectMutex.Unlock() // Unprevent other outbridges from connecting
}
this.disconnectErr = err
if this.state != STATE_DISCONNECTED && this.session.outBridge == this {
this.session.Disconnect(minecraft.Colorize(this.session.server.localizer.LocaleLostConn()))
}
this.state = STATE_DISCONNECTED
this.conn.Close()
}