This repository has been archived by the owner on Jun 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
packet_handler.go
390 lines (342 loc) · 13.2 KB
/
packet_handler.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package gomine
import (
"crypto/ecdsa"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"github.com/golang/geo/r3"
"github.com/irmine/gomine/net"
"github.com/irmine/gomine/net/info"
"github.com/irmine/gomine/net/packets"
"github.com/irmine/gomine/net/packets/bedrock"
"github.com/irmine/gomine/net/packets/data"
"github.com/irmine/gomine/net/packets/types"
"github.com/irmine/gomine/net/protocol"
"github.com/irmine/gomine/players"
"github.com/irmine/gomine/text"
"github.com/irmine/gomine/utils"
"github.com/irmine/worlds/blocks"
"github.com/irmine/worlds/chunks"
data2 "github.com/irmine/worlds/entities/data"
utils2 "github.com/irmine/worlds/utils"
"math/big"
"strings"
"time"
)
func NewClientHandshakeHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if _, ok := packet.(*bedrock.ClientHandshakePacket); ok {
session.SendPlayStatus(data.StatusLoginSuccess)
session.SendResourcePackInfo(server.Config.ForceResourcePacks, server.PackManager.GetResourceStack(), server.PackManager.GetBehaviorStack())
return true
}
return false
})
}
func NewCommandRequestHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if pk, ok := packet.(*bedrock.CommandRequestPacket); ok {
var args = strings.Split(pk.CommandText, " ")
var commandName = strings.TrimLeft(args[0], "/")
var i = 1
for !server.CommandManager.IsCommandRegistered(commandName) {
if i == len(args) {
break
}
commandName += " " + args[i]
i++
}
if !server.CommandManager.IsCommandRegistered(commandName) {
session.SendMessage("Command could not be found.")
return false
}
args = args[i:]
var command, _ = server.CommandManager.GetCommand(commandName)
command.Execute(session, args)
return true
}
return false
})
}
func NewLoginHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if loginPacket, ok := packet.(*bedrock.LoginPacket); ok {
var _, ok = server.SessionManager.GetSession(loginPacket.Username)
if ok {
return false
}
if loginPacket.Protocol > info.LatestProtocol {
session.Kick("Outdated server.", false, true)
return false
}
if loginPacket.Protocol < info.LatestProtocol {
session.Kick("Outdated client.", false, true)
return false
}
var successful, authenticated, pubKey = VerifyLoginRequest(loginPacket.Chains, server)
if !successful {
text.DefaultLogger.Debug(loginPacket.Username, "has joined with invalid login data.")
return true
}
if authenticated {
text.DefaultLogger.Debug(loginPacket.Username, "has joined while being logged into XBOX Live.")
} else {
if server.Config.XBOXLiveAuth {
text.DefaultLogger.Debug(loginPacket.Username, "has tried to join while not being logged into XBOX Live.")
session.Kick("XBOX Live account required.", false, false)
return true
}
text.DefaultLogger.Debug(loginPacket.Username, "has joined while not being logged into XBOX Live.")
}
session.SetData(server.PermissionManager, types.SessionData{ClientUUID: loginPacket.ClientUUID, ClientXUID: loginPacket.ClientXUID, ClientId: loginPacket.ClientId, ProtocolNumber: loginPacket.Protocol, GameVersion: loginPacket.ClientData.GameVersion, Language: loginPacket.Language, DeviceOS: loginPacket.ClientData.DeviceOS})
session.SetPlayer(players.NewPlayer(loginPacket.ClientUUID, loginPacket.ClientXUID, int32(loginPacket.ClientData.DeviceOS), loginPacket.Username))
session.GetEncryptionHandler().Data = &utils.EncryptionData{
ClientPublicKey: pubKey,
ServerPrivateKey: server.GetPrivateKey(),
ServerToken: server.GetServerToken(),
}
session.GetPlayer().SetName(loginPacket.Username)
session.GetPlayer().SetDisplayName(loginPacket.Username)
session.GetPlayer().SetSkinId(loginPacket.SkinId)
session.GetPlayer().SetSkinData(loginPacket.SkinData)
session.GetPlayer().SetCapeData(loginPacket.CapeData)
session.GetPlayer().SetGeometryName(loginPacket.GeometryName)
session.GetPlayer().SetGeometryData(loginPacket.GeometryData)
session.SetXBOXLiveAuthenticated(authenticated)
if server.Config.UseEncryption {
var jwt = utils.ConstructEncryptionJwt(server.GetPrivateKey(), server.GetServerToken())
session.SendServerHandshake(jwt)
session.EnableEncryption()
} else {
session.SendPlayStatus(data.StatusLoginSuccess)
session.SendResourcePackInfo(server.Config.ForceResourcePacks, server.PackManager.GetResourceStack(), server.PackManager.GetBehaviorStack())
}
server.SessionManager.AddMinecraftSession(session)
return true
}
return false
})
}
func NewMovePlayerHandler(_ *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if pk, ok := packet.(*bedrock.MovePlayerPacket); ok {
if session.GetPlayer().GetDimension() == nil {
return false
}
session.SyncMove(pk.Position.X, pk.Position.Y, pk.Position.Z, pk.Rotation.Pitch, pk.Rotation.Yaw, pk.Rotation.HeadYaw, pk.OnGround)
return true
}
return false
})
}
func NewRequestChunkRadiusHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if chunkRadiusPacket, ok := packet.(*bedrock.RequestChunkRadiusPacket); ok {
var viewDistance = server.GetAllowedViewDistance(chunkRadiusPacket.Radius)
session.SetViewDistance(viewDistance)
session.SendChunkRadiusUpdated(viewDistance)
var sessions = server.SessionManager.GetSessions()
var viewers = make(map[string]protocol.PlayerListEntry)
for name, online := range sessions {
if online.HasSpawned() {
viewers[name] = online.GetPlayer()
online.SendPlayerList(data.ListTypeAdd, map[string]protocol.PlayerListEntry{session.GetName(): session.GetPlayer()})
}
}
session.SendPlayerList(data.ListTypeAdd, viewers)
for _, online := range server.SessionManager.GetSessions() {
if session.GetUUID() != online.GetUUID() {
online.GetPlayer().SpawnPlayerTo(session)
online.GetPlayer().AddViewer(session)
session.GetPlayer().SpawnPlayerTo(online)
session.GetPlayer().AddViewer(online)
online.SendSkin(session)
session.SendSkin(online)
}
}
session.SendSetEntityData(session.GetPlayer().GetRuntimeId(), session.GetPlayer().GetEntityData())
session.SendUpdateAttributes(session.GetPlayer().GetRuntimeId(), session.GetPlayer().GetAttributeMap())
server.BroadcastMessage(text.Yellow+session.GetDisplayName(), "has joined the server")
session.SendPlayStatus(data.StatusSpawn)
session.Connected = true
return true
}
return false
})
}
func NewResourcePackChunkRequestHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if request, ok := packet.(*bedrock.ResourcePackChunkRequestPacket); ok {
if !server.PackManager.IsPackLoaded(request.PackUUID) {
// TODO: Kick the player. We can't kick yet.
return false
}
var pack = server.PackManager.GetPack(request.PackUUID)
session.SendResourcePackChunkData(request.PackUUID, request.ChunkIndex, int64(data.ResourcePackChunkSize*request.ChunkIndex), pack.GetChunk(int(data.ResourcePackChunkSize*request.ChunkIndex), data.ResourcePackChunkSize))
return true
}
return false
})
}
func NewResourcePackClientResponseHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if response, ok := packet.(*bedrock.ResourcePackClientResponsePacket); ok {
switch response.Status {
case data.StatusRefused:
// TODO: Kick the player. We can't kick yet.
return false
case data.StatusSendPacks:
for _, packUUID := range response.PackUUIDs {
if !server.PackManager.IsPackLoaded(packUUID) {
// TODO: Kick the player. We can't kick yet.
return false
}
session.SendResourcePackDataInfo(server.PackManager.GetPack(packUUID))
}
case data.StatusHaveAllPacks:
session.SendResourcePackStack(server.Config.ForceResourcePacks, server.PackManager.GetResourceStack(), server.PackManager.GetBehaviorStack())
case data.StatusCompleted:
server.LevelManager.GetDefaultLevel().GetDefaultDimension().LoadChunk(0, 0, func(chunk *chunks.Chunk) {
server.LevelManager.GetDefaultLevel().GetDefaultDimension().AddEntity(session.GetPlayer(), r3.Vector{X: 0, Y: 7, Z: 0})
server.LevelManager.GetDefaultLevel().GetDefaultDimension().AddViewer(session, r3.Vector{X: 0, Y: 7, Z: 0})
session.SendStartGame(session.GetPlayer(), blocks.GetRuntimeIdsTable())
session.SendCraftingData()
})
}
return true
}
return false
})
}
func NewTextHandler(server *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if textPacket, ok := packet.(*bedrock.TextPacket); ok {
if textPacket.TextType != data.TextChat {
return false
}
for _, receiver := range server.SessionManager.GetSessions() {
receiver.SendText(types.Text{
Message: "<" + session.GetDisplayName() + "> " + textPacket.Message,
PlatformChatId: textPacket.PlatformChatId,
SourceXUID: session.GetXUID(),
TextType: data.TextChat,
})
}
text.DefaultLogger.LogChat("<" + session.GetDisplayName() + "> " + textPacket.Message)
return true
}
return false
})
}
func NewInteractHandler(_ *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if /*interactPacket*/ _, ok := packet.(*bedrock.InteractPacket); ok {
}
return true
})
}
func NewPlayerActionHandler(_ *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
//TODO: fix sending to others
if playerAction, ok := packet.(*bedrock.PlayerActionPacket); ok {
switch playerAction.Action {
case bedrock.PlayerStartSneak:
session.GetPlayer().SetEntityProperty(data2.EntityDataSneaking, true)
break
case bedrock.PlayerStopSneak:
session.GetPlayer().SetEntityProperty(data2.EntityDataSneaking, false)
break
case bedrock.PlayerStartSprint:
session.GetPlayer().SetEntityProperty(data2.EntityDataSprinting, true)
break
case bedrock.PlayerStopSprint:
session.GetPlayer().SetEntityProperty(data2.EntityDataSprinting, false)
break
}
}
return true
})
}
func NewAnimateHandler(_ *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if animate, ok := packet.(*bedrock.AnimatePacket); ok {
for _, viewer := range session.GetPlayer().GetViewers() {
if viewer, ok := viewer.(*net.MinecraftSession); ok {
viewer.SendAnimate(animate.Action, animate.RuntimeId, animate.Float)
}
}
}
return true
})
}
func NewInventoryTransactionHandler(_ *Server) *net.PacketHandler {
return net.NewPacketHandler(func(packet packets.IPacket, session *net.MinecraftSession) bool {
if invTransaction, ok := packet.(*bedrock.InventoryTransactionPacket); ok {
var clickPos = invTransaction.BlockPosition
switch invTransaction.TransactionType {
case bedrock.UseItem:
switch invTransaction.ActionType {
case bedrock.ItemBreakBlock:
runtimeId, ok := blocks.GetRuntimeId(0, 0)
if ok {
var block= blocks.New(blocks.NewBlockState("air", int32(runtimeId), 0, 0))
session.GetPlayer().GetDimension().SetBlockAt(utils2.PositionToVector(clickPos), block)
}
break
case bedrock.ItemClickBlock:
// TODO: do block placing
break
}
break
}
}
return true
})
}
func VerifyLoginRequest(chains []types.Chain, _ *Server) (successful bool, authenticated bool, clientPublicKey *ecdsa.PublicKey) {
var publicKey *ecdsa.PublicKey
var publicKeyRaw string
for _, chain := range chains {
if publicKeyRaw == "" {
if chain.Header.X5u == "" {
return
}
publicKeyRaw = chain.Header.X5u
}
sig := []byte(chain.Signature)
d := []byte(chain.Header.Raw + "." + chain.Payload.Raw)
var b64, errB64 = base64.RawStdEncoding.DecodeString(publicKeyRaw)
text.DefaultLogger.LogError(errB64)
key, err := x509.ParsePKIXPublicKey(b64)
if err != nil {
text.DefaultLogger.LogError(err)
return
}
hash := sha512.New384()
hash.Write(d)
publicKey = key.(*ecdsa.PublicKey)
r := new(big.Int).SetBytes(sig[:len(sig)/2])
s := new(big.Int).SetBytes(sig[len(sig)/2:])
if !ecdsa.Verify(publicKey, hash.Sum(nil), r, s) {
return
}
if publicKeyRaw == data.MojangPublicKey {
authenticated = true
}
t := time.Now().Unix()
if chain.Payload.ExpirationTime <= t && chain.Payload.ExpirationTime != 0 || chain.Payload.NotBefore > t || chain.Payload.IssuedAt > chain.Payload.ExpirationTime {
return
}
publicKeyRaw = chain.Payload.IdentityPublicKey
}
var b64, errB64 = base64.RawStdEncoding.DecodeString(publicKeyRaw)
text.DefaultLogger.LogError(errB64)
key, err := x509.ParsePKIXPublicKey(b64)
if err != nil {
text.DefaultLogger.LogError(err)
return
}
clientPublicKey = key.(*ecdsa.PublicKey)
successful = true
return
}