/
packet.go
829 lines (732 loc) · 17.5 KB
/
packet.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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
package mcc
import (
"bytes"
"encoding/binary"
"log"
"math"
"strings"
"time"
)
const (
CpeClickDistance = iota
CpeCustomBlocks
CpeHeldBlock
CpeTextHotKey
CpeExtPlayerList
CpeEnvColors
CpeSelectionCuboid
CpeBlockPermissions
CpeChangeModel
CpeEnvWeatherType
CpeHackControl
CpeMessageTypes
CpePlayerClick
CpeLongerMessages
CpeBlockDefinitions
CpeBlockDefinitionsExt
CpeBulkBlockUpdate
CpeTextColors
CpeEnvMapAspect
CpeEntityProperty
CpeExtEntityPositions
CpeTwoWayPing
CpeInventoryOrder
CpeInstantMOTD
CpeFastMap
CpeExtendedTextures
CpeMax = CpeExtendedTextures
CpeCount = CpeMax + 1
)
type ExtEntry struct {
Name string
Version int
}
var Extensions = [CpeCount]ExtEntry{
{"ClickDistance", 1},
{"CustomBlocks", 1},
{"HeldBlock", 1},
{"TextHotKey", 1},
{"ExtPlayerList", 2},
{"EnvColors", 1},
{"SelectionCuboid", 1},
{"BlockPermissions", 1},
{"ChangeModel", 1},
{"EnvWeatherType", 1},
{"HackControl", 1},
{"MessageTypes", 1},
{"PlayerClick", 1},
{"LongerMessages", 1},
{"BlockDefinitions", 1},
{"BlockDefinitionsExt", 2},
{"BulkBlockUpdate", 1},
{"TextColors", 1},
{"EnvMapAspect", 1},
{"EntityProperty", 1},
{"ExtEntityPositions", 1},
{"TwoWayPing", 1},
{"InventoryOrder", 1},
{"InstantMOTD", 1},
{"FastMap", 1},
{"ExtendedTextures", 1},
}
const (
packetTypeIdentification = 0x00
packetTypePing = 0x01
packetTypeLevelInitialize = 0x02
packetTypeLevelDataChunk = 0x03
packetTypeLevelFinalize = 0x04
packetTypeSetBlockClient = 0x05
packetTypeSetBlock = 0x06
packetTypeAddEntity = 0x07
packetTypePlayerTeleport = 0x08
packetTypePositionOrientationUpdate = 0x09
packetTypePositionUpdate = 0x0a
packetTypeOrientationUpdate = 0x0b
packetTypeRemoveEntity = 0x0c
packetTypeMessage = 0x0d
packetTypeKick = 0x0e
packetTypeUpdateUserType = 0x0f
packetTypeExtInfo = 0x10
packetTypeExtEntry = 0x11
packetTypeSetClickDistance = 0x12
packetTypeCustomBlockSupportLevel = 0x13
packetTypeHoldThis = 0x14
packetTypeSetTextHotKey = 0x15
packetTypeExtAddPlayerName = 0x16
packetTypeExtRemovePlayerName = 0x18
packetTypeEnvSetColor = 0x19
packetTypeMakeSelection = 0x1a
packetTypeRemoveSelection = 0x1b
packetTypeSetBlockPermission = 0x1c
packetTypeChangeModel = 0x1d
packetTypeEnvSetWeatherType = 0x1f
packetTypeHackControl = 0x20
packetTypeExtAddEntity2 = 0x21
packetTypePlayerClicked = 0x22
packetTypeDefineBlock = 0x23
packetTypeRemoveBlockDefinition = 0x24
packetTypeDefineBlockExt = 0x25
packetTypeBulkBlockUpdate = 0x26
packetTypeSetTextColor = 0x27
packetTypeSetMapEnvUrl = 0x28
packetTypeSetMapEnvProperty = 0x29
packetTypeSetEntityProperty = 0x2a
packetTypeTwoWayPing = 0x2b
packetTypeSetInventoryOrder = 0x2c
)
func padString(str string) [64]byte {
var result [64]byte
copy(result[:], str)
if len(str) < 64 {
copy(result[len(str):], bytes.Repeat([]byte{' '}, 64-len(str)))
}
return result
}
func trimString(str [64]byte) string {
return strings.TrimRight(string(str[:]), " ")
}
type packet struct {
bytes.Buffer
}
func (packet *packet) marshal(v interface{}) {
if err := binary.Write(packet, binary.BigEndian, v); err != nil {
log.Printf("packet: %s\n", err)
}
}
func (packet *packet) position(location Location, extPos bool) {
if extPos {
packet.marshal(struct{ X, Y, Z int32 }{
int32(location.X * 32),
int32(location.Y * 32),
int32(location.Z * 32),
})
} else {
packet.marshal(struct{ X, Y, Z int16 }{
int16(location.X * 32),
int16(location.Y * 32),
int16(location.Z * 32),
})
}
}
func (packet *packet) textureID(textureID int, extTex bool) {
if extTex {
packet.marshal(int16(textureID))
} else {
packet.WriteByte(byte(textureID))
}
}
func (packet *packet) motd(player *Player, motd string, op bool) {
userType := byte(0x00)
if op {
userType = 0x64
}
packet.marshal(struct {
PacketID byte
ProtocolVersion byte
Name [64]byte
MOTD [64]byte
UserType byte
}{
packetTypeIdentification,
0x07,
padString(player.server.Config.Name),
padString(motd),
userType,
})
}
func (packet *packet) ping() {
packet.WriteByte(packetTypePing)
}
func (packet *packet) levelInitialize() {
packet.WriteByte(packetTypeLevelInitialize)
}
func (packet *packet) levelInitializeExt(size int) {
packet.marshal(struct {
PacketID byte
Size int32
}{packetTypeLevelInitialize, int32(size)})
}
func (packet *packet) levelFinalize(x, y, z int) {
packet.marshal(struct {
PacketID byte
X, Y, Z int16
}{packetTypeLevelFinalize, int16(x), int16(y), int16(z)})
}
func (packet *packet) setBlock(x, y, z int, block byte) {
packet.marshal(struct {
PacketID byte
X, Y, Z int16
BlockType byte
}{packetTypeSetBlock, int16(x), int16(y), int16(z), block})
}
func (packet *packet) addEntity(entity *Entity, self bool, extPos bool) {
id := entity.id
if self {
id = 0xff
}
location := entity.location
packet.marshal(struct {
PacketID byte
PlayerID byte
Name [64]byte
}{packetTypeAddEntity, id, padString(entity.DisplayName)})
packet.position(location, extPos)
packet.marshal(struct{ Yaw, Pitch byte }{
byte(location.Yaw * 256 / 360),
byte(location.Pitch * 256 / 360),
})
}
func (packet *packet) teleport(entity *Entity, self bool, extPos bool) {
id := entity.id
if self {
id = 0xff
}
location := entity.location
packet.marshal(struct {
PacketID byte
PlayerID byte
}{packetTypePlayerTeleport, id})
packet.position(location, extPos)
packet.marshal(struct{ Yaw, Pitch byte }{
byte(location.Yaw * 256 / 360),
byte(location.Pitch * 256 / 360),
})
}
func (packet *packet) positionOrientationUpdate(entity *Entity) {
location := entity.location
lastLocation := entity.lastLocation
packet.marshal(struct {
PacketID byte
PlayerID byte
X, Y, Z byte
Yaw, Pitch byte
}{
packetTypePositionOrientationUpdate,
entity.id,
byte((location.X - lastLocation.X) * 32),
byte((location.Y - lastLocation.Y) * 32),
byte((location.Z - lastLocation.Z) * 32),
byte(location.Yaw * 256 / 360),
byte(location.Pitch * 256 / 360),
})
}
func (packet *packet) positionUpdate(entity *Entity) {
location := entity.location
lastLocation := entity.lastLocation
packet.marshal(struct {
PacketID byte
PlayerID byte
X, Y, Z byte
}{
packetTypePositionUpdate,
entity.id,
byte((location.X - lastLocation.X) * 32),
byte((location.Y - lastLocation.Y) * 32),
byte((location.Z - lastLocation.Z) * 32),
})
}
func (packet *packet) orientationUpdate(entity *Entity) {
location := entity.location
packet.marshal(struct {
PacketID byte
PlayerID byte
Yaw, Pitch byte
}{
packetTypeOrientationUpdate,
entity.id,
byte(location.Yaw * 256 / 360),
byte(location.Pitch * 256 / 360),
})
}
func (packet *packet) removeEntity(entity *Entity, self bool) {
id := entity.id
if self {
id = 0xff
}
packet.marshal(struct {
PacketID byte
PlayerID byte
}{packetTypeRemoveEntity, id})
}
func (packet *packet) message(msgType int, message string) {
packet.marshal(struct {
PacketID byte
PlayerID byte
Message [64]byte
}{packetTypeMessage, byte(msgType), padString(message)})
}
func (packet *packet) kick(reason string) {
packet.marshal(struct {
PacketID byte
Reason [64]byte
}{packetTypeKick, padString(reason)})
}
func (packet *packet) updateUserType(op bool) {
userType := byte(0x00)
if op {
userType = 0x64
}
packet.marshal(struct {
PacketID byte
UserType byte
}{packetTypeUpdateUserType, userType})
}
func (packet *packet) extInfo() {
packet.marshal(struct {
PacketID byte
AppName [64]byte
ExtensionCount int16
}{packetTypeExtInfo, padString(ServerSoftware), int16(len(Extensions))})
}
func (packet *packet) extEntry(entry *ExtEntry) {
packet.marshal(struct {
PacketID byte
ExtName [64]byte
Version int32
}{packetTypeExtEntry, padString(entry.Name), int32(entry.Version)})
}
func (packet *packet) clickDistance(dist float64) {
packet.marshal(struct {
PacketID byte
Distance int16
}{packetTypeSetClickDistance, int16(dist * 32)})
}
func (packet *packet) customBlockSupportLevel(level byte) {
packet.marshal(struct {
PacketID byte
SupportLevel byte
}{packetTypeCustomBlockSupportLevel, level})
}
func (packet *packet) holdThis(block byte, lock bool) {
preventChange := byte(0)
if lock {
preventChange = 1
}
packet.marshal(struct {
PacketID byte
BlockToHold byte
PreventChange byte
}{packetTypeHoldThis, block, preventChange})
}
func (packet *packet) setTextHotKey(hotkey *HotkeyDesc) {
packet.marshal(struct {
PacketID byte
Label [64]byte
Action [64]byte
KeyCode int32
KeyMods byte
}{
packetTypeSetTextHotKey,
padString(hotkey.Label),
padString(hotkey.Action),
int32(hotkey.Key),
hotkey.KeyMods,
})
}
func (packet *packet) extAddPlayerName(entity *Entity, self bool) {
id := int16(entity.id)
if self {
id = 0xff
}
packet.marshal(struct {
PacketID byte
NameID int16
PlayerName [64]byte
ListName [64]byte
GroupName [64]byte
GroupRank byte
}{
packetTypeExtAddPlayerName,
id,
padString(entity.name),
padString(entity.ListName),
padString(entity.GroupName),
entity.GroupRank,
})
}
func (packet *packet) extRemovePlayerName(entity *Entity, self bool) {
id := int16(entity.id)
if self {
id = 0xff
}
packet.marshal(struct {
PacketID byte
NameID int16
}{packetTypeExtRemovePlayerName, id})
}
func (packet *packet) makeSelection(id byte, label string, box AABB, color RGBA) {
packet.marshal(struct {
PacketID byte
SelectionID byte
Label [64]byte
StartX, StartY, StartZ int16
EndX, EndY, Endz int16
R, G, B, Opacity int16
}{
packetTypeMakeSelection,
id,
padString(label),
int16(box.Min.X), int16(box.Min.Y), int16(box.Min.Z),
int16(box.Max.X), int16(box.Max.Y), int16(box.Max.Z),
int16(color.R), int16(color.G), int16(color.B), int16(color.A),
})
}
func (packet *packet) removeSelection(id byte) {
packet.marshal(struct {
PacketID byte
SelectionID byte
}{packetTypeRemoveSelection, id})
}
func (packet *packet) envSetColor(id byte, color NullRGB) {
data := struct {
packetId byte
Variable byte
R, G, B int16
}{packetTypeEnvSetColor, id, -1, -1, -1}
if color.Valid {
data.R = int16(color.R)
data.G = int16(color.G)
data.B = int16(color.B)
}
packet.marshal(data)
}
func (packet *packet) setBlockPermission(id byte, canPlace, canBreak bool) {
data := struct {
PacketID byte
BlockType byte
AllowPlacement byte
AllowDeletion byte
}{packetTypeSetBlockPermission, id, 0, 0}
if canPlace {
data.AllowPlacement = 1
}
if canBreak {
data.AllowDeletion = 1
}
packet.marshal(data)
}
func (packet *packet) changeModel(entity *Entity, self bool) {
id := entity.id
if self {
id = 0xff
}
packet.marshal(struct {
PacketID byte
EntityID byte
ModelName [64]byte
}{packetTypeChangeModel, id, padString(entity.Model)})
}
func (packet *packet) envWeatherType(weather byte) {
packet.marshal(struct {
PacketID byte
WeatherType byte
}{packetTypeEnvSetWeatherType, weather})
}
func (packet *packet) hackControl(config *HackConfig) {
data := struct {
PacketID byte
Flying byte
NoClip byte
Speeding byte
SpawnControl byte
ThirdPersonView byte
JumpHeight int16
}{packetTypeHackControl, 0, 0, 0, 0, 0, -1}
if config.Flying {
data.Flying = 1
}
if config.NoClip {
data.NoClip = 1
}
if config.Speeding {
data.Speeding = 1
}
if config.SpawnControl {
data.SpawnControl = 1
}
if config.ThirdPersonView {
data.ThirdPersonView = 1
}
if config.JumpHeight >= 0 {
data.JumpHeight = int16(config.JumpHeight * 32)
}
packet.marshal(data)
}
func (packet *packet) extAddEntity2(entity *Entity, self bool, extPos bool) {
id := entity.id
if self {
id = 0xff
}
location := entity.location
packet.marshal(struct {
PacketID byte
EntityID byte
DisplayName [64]byte
SkinName [64]byte
}{
packetTypeExtAddEntity2,
id,
padString(entity.DisplayName),
padString(entity.SkinName),
})
packet.position(location, extPos)
packet.marshal(struct{ Yaw, Pitch byte }{
byte(location.Yaw * 256 / 360),
byte(location.Pitch * 256 / 360),
})
}
func (packet *packet) defineBlock(id byte, block *BlockDefinition, ext bool, extTex bool) {
packetID := byte(packetTypeDefineBlock)
if ext {
packetID = packetTypeDefineBlockExt
}
packet.marshal(struct {
PacketID byte
BlockID byte
Name [64]byte
Solidity byte
MovementSpeed byte
}{
packetID,
id,
padString(block.Name),
block.CollideMode,
byte(64*math.Log2(block.Speed) + 128),
})
packet.textureID(block.Textures[FacePosY], extTex)
if ext {
packet.textureID(block.Textures[FaceNegX], extTex)
packet.textureID(block.Textures[FacePosX], extTex)
packet.textureID(block.Textures[FaceNegZ], extTex)
packet.textureID(block.Textures[FacePosZ], extTex)
} else {
packet.textureID(block.Textures[FacePosX], extTex)
}
packet.textureID(block.Textures[FaceNegY], extTex)
transmitsLight := byte(1)
if block.BlockLight {
transmitsLight = 0
}
fullBright := byte(0)
if block.FullBright {
fullBright = 1
}
packet.marshal(struct {
TransmitsLight byte
WalkSound byte
FullBright byte
}{transmitsLight, block.WalkSound, fullBright})
if ext {
aabb := block.AABB
packet.marshal(struct {
MinX, MinY, MinZ byte
MaxX, MaxY, MaxZ byte
}{
byte(aabb.Min.X), byte(aabb.Min.Y), byte(aabb.Min.Z),
byte(aabb.Max.X), byte(aabb.Max.Y), byte(aabb.Max.Z),
})
} else {
packet.WriteByte(block.Shape)
}
packet.marshal(struct {
BlockDraw byte
FogDensity byte
FogR, FogG, FogB byte
}{
block.DrawMode,
block.FogDensity,
block.Fog.R, block.Fog.G, block.Fog.B,
})
}
func (packet *packet) removeBlockDefinition(id byte) {
packet.marshal(struct {
PacketID byte
BlockID byte
}{packetTypeRemoveBlockDefinition, id})
}
func (packet *packet) bulkBlockUpdate(indices []int32, blocks []byte) {
data := struct {
PacketID byte
Count byte
Indices [256]int32
Blocks [256]byte
}{
packetTypeBulkBlockUpdate,
byte(len(indices)),
[256]int32{},
[256]byte{},
}
copy(data.Indices[:], indices)
copy(data.Blocks[:], blocks)
packet.marshal(data)
}
func (packet *packet) setTextColor(color *ColorDesc) {
packet.marshal(struct {
PacketID byte
R, G, B, A byte
Code byte
}{
packetTypeSetTextColor,
color.R, color.G, color.B, color.A,
color.Code,
})
}
func (packet *packet) mapEnvUrl(texturePack string) {
packet.marshal(struct {
PacketID byte
TexturePackURL [64]byte
}{packetTypeSetMapEnvUrl, padString(texturePack)})
}
func (packet *packet) mapEnvProperty(id byte, value int32) {
packet.marshal(struct {
PacketID byte
Type byte
Value int32
}{packetTypeSetMapEnvProperty, id, value})
}
func (packet *packet) entityProperty(entity *Entity, self bool, prop byte, value int32) {
id := entity.id
if self {
id = 0xff
}
packet.marshal(struct {
PacketID byte
EntityID byte
Type byte
Value int32
}{packetTypeSetEntityProperty, id, prop, value})
}
func (packet *packet) twoWayPing(dir byte, data int16) {
packet.marshal(struct {
PacketID byte
Direction byte
Data int16
}{packetTypeTwoWayPing, dir, data})
}
func (packet *packet) setInventoryOrder(order byte, block byte) {
packet.marshal(struct {
PacketID byte
Order byte
BlockID byte
}{packetTypeSetInventoryOrder, order, block})
}
type levelStream struct {
player *Player
packet packet
index int
percent byte
}
func (stream *levelStream) reset() {
stream.packet.Reset()
stream.packet.Write([]byte{packetTypeLevelDataChunk, 0, 0})
stream.index = 0
}
func (stream *levelStream) send() {
if stream.index < 1024 {
stream.packet.Write(make([]byte, 1024-stream.index))
}
stream.packet.Write([]byte{stream.percent})
buf := stream.packet.Bytes()
binary.BigEndian.PutUint16(buf[1:], uint16(stream.index))
stream.player.sendPacket(stream.packet)
stream.reset()
}
func (stream *levelStream) Close() {
if stream.index > 0 {
stream.send()
}
}
func (stream *levelStream) Write(p []byte) (int, error) {
offset := 0
count := len(p)
for count > 0 {
size := min(1024-stream.index, count)
stream.packet.Write(p[offset : offset+size])
stream.index += size
offset += size
count -= size
if stream.index == 1024 {
stream.send()
}
}
return len(p), nil
}
type pingEntry struct {
data int16
sent, received time.Time
}
type pingBuffer struct {
entries [10]pingEntry
index int
}
func (buf *pingBuffer) next() int16 {
data := buf.entries[buf.index].data + 1
buf.index = (buf.index + 1) % len(buf.entries)
buf.entries[buf.index] = pingEntry{
data: data,
sent: time.Now(),
}
return data
}
func (buf *pingBuffer) update(data int16) {
for i, entry := range buf.entries {
if entry.data == data {
buf.entries[i].received = time.Now()
break
}
}
}
func (buf *pingBuffer) average() (d time.Duration) {
count := int64(0)
var sum time.Duration
for _, entry := range buf.entries {
if entry.received.After(entry.sent) {
sum += entry.received.Sub(entry.sent)
count++
}
}
if count > 0 {
return time.Duration(int64(sum) / (2 * count))
}
return
}