-
Notifications
You must be signed in to change notification settings - Fork 0
/
nns_packet.go
55 lines (50 loc) · 1.22 KB
/
nns_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
package nns
import (
"bytes"
"encoding/binary"
"errors"
"io"
"log"
)
// NNSPacket is a raw NNS packet before any decryption
type DataPacket struct {
Size uint32
Payload []byte
}
// Bytes corrects the size and returns an NNS packet as bytes
func (dp DataPacket) Bytes() []byte {
buffer := bytes.NewBuffer([]byte{})
dp.WriteTo(buffer)
return buffer.Bytes()
}
// Bytes corrects the size and returns an NNS packet as bytes
func (dp DataPacket) WriteTo(writer io.Writer) error {
dp.Size = uint32(len(dp.Payload))
err := binary.Write(writer, binary.LittleEndian, dp.Size)
if err != nil {
return err
}
n, err := writer.Write(dp.Payload)
if err != nil {
return err
}
if n != len(dp.Payload) {
return errors.New("failed to write full data packet")
}
return nil
}
// UnmarshalNNSPacket reads an NNS packet
func UnmarshalNNSPacket(reader io.Reader) (packet DataPacket, err error) {
err = binary.Read(reader, binary.LittleEndian, &packet.Size)
if err != nil {
return packet, err
}
log.Printf("NNS packet size : %s", packet.Size)
buffer := bytes.NewBuffer([]byte{})
_, err = io.CopyN(buffer, reader, int64(packet.Size))
if err != nil {
return packet, err
}
packet.Payload = buffer.Bytes()
return packet, nil
}