/ login-server / source / packets / DeclaredServerPacket.ts
DeclaredServerPacket.ts
 1  import { IServerPacket } from './IServerPacket'
 2  
 3  const enum PacketWritableChunks {
 4      C = 1,
 5      D = 4,
 6      F = 8,
 7      H = 2,
 8      Q = 8
 9  }
10  
11  const shortIntConverter = new Int16Array( 1 )
12  
13  export class DeclaredServerPacket implements IServerPacket {
14      buffer: Buffer
15      position: number = 2
16  
17      constructor( size: number ) {
18          /*
19              Login packets always contain checksum (four bytes) or (if first packet sent) XORPass information (eight bytes)
20              Hence, we must account for additional size. First packet will have already included additional bytes for its size, so
21              no special handling is needed.
22           */
23          let length = size + 4
24          let finalSize = 2 + length + 8 - ( length % 8 )
25          this.buffer = Buffer.allocUnsafe( finalSize )
26          this.buffer.writeUInt16LE( this.buffer.length , 0 )
27      }
28  
29      getBuffer(): Buffer {
30          return this.buffer
31      }
32  
33      writeB( value: Buffer ): IServerPacket {
34          value.copy( this.buffer, this.position )
35          this.position += value.length
36          return this
37      }
38  
39      writeC( value: number ): IServerPacket {
40          this.buffer.writeUInt8( value, this.position )
41          this.position += PacketWritableChunks.C
42          return this
43      }
44  
45      writeD( value: number ): IServerPacket {
46          this.buffer.writeInt32LE( value, this.position )
47          this.position += PacketWritableChunks.D
48          return this
49      }
50  
51      writeF( value: number ): IServerPacket {
52          this.buffer.writeDoubleLE( value, this.position )
53          this.position += PacketWritableChunks.F
54          return this
55      }
56  
57      writeH( value: number ): IServerPacket {
58          shortIntConverter[ 0 ] = value
59  
60          this.buffer.writeInt16LE( shortIntConverter[ 0 ], this.position )
61          this.position += PacketWritableChunks.H
62          return this
63      }
64  
65      writeQ( value: number ): IServerPacket {
66          this.buffer.writeBigInt64LE( BigInt( value ), this.position )
67          this.position += PacketWritableChunks.Q
68          return this
69      }
70  
71      writeS( messageString: string ): IServerPacket {
72          this.position += this.buffer.write( messageString, this.position, 'ucs2' )
73          this.buffer.writeInt16LE( 0, this.position )
74          this.position += 2
75  
76          return this
77      }
78  }
79  
80  export function getStringSize( message: string ): number {
81      return ( message.length + 1 ) * 2
82  }