-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
102 lines (91 loc) · 1.95 KB
/
client.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
package gorcon
import (
"encoding/binary"
"errors"
"net"
)
const (
RequestIDStart int32 = 6516583
)
var (
MCEndian binary.ByteOrder = binary.LittleEndian
ErrInvalidPassword error = errors.New("invalid RCON password")
counter int32 = 0
)
type RCONClient struct {
Address string
RequestID int32
Connection net.Conn
}
func NewRCONClient(address string) *RCONClient {
counter++
return &RCONClient{
Address: address,
RequestID: RequestIDStart + counter - 1,
}
}
func (client *RCONClient) SendPacket(packet Packet) error {
_, err := WritePacket(client.Connection, packet)
return err
}
func (client *RCONClient) RecvPacket() (*Packet, error) {
return ReadPacket(client.Connection)
}
func (client *RCONClient) Connect(address string) error {
connection, err := net.Dial("tcp", client.Address)
if err != nil {
return err
}
client.Connection = connection
return nil
}
func (client *RCONClient) Login(password string) error {
if err := client.SendPacket(Packet{
RequestID: client.RequestID,
Type: PacketTypeLogin,
Body: password,
}); err != nil {
return err
}
packet, err := client.RecvPacket()
if err != nil {
return err
}
switch packet.Type {
case PacketTypeCommand:
if packet.RequestID != client.RequestID {
if err = client.Close(); err != nil {
return err
}
return ErrInvalidPassword
}
}
return nil
}
func (client *RCONClient) SendCommand(command string) (string, error) {
if err := client.SendPacket(Packet{
RequestID: client.RequestID,
Type: PacketTypeCommand,
Body: command,
}); err != nil {
return "", err
}
res := ""
for {
packet, err := client.RecvPacket()
if err != nil {
return res, err
}
if packet.Type != PacketTypeResponse {
continue
}
res += string(packet.Body)
if len(packet.Body) < PayloadChunkLength {
break
}
}
return res, nil
}
func (client *RCONClient) Close() error {
return client.Connection.Close()
}