]> git.r.bdr.sh - rbdr/mobius/blob - hotline/tracker.go
Fix io.Reader implementations and wrap more errors
[rbdr/mobius] / hotline / tracker.go
1 package hotline
2
3 import (
4 "bufio"
5 "encoding/binary"
6 "fmt"
7 "io"
8 "net"
9 "slices"
10 "strconv"
11 "time"
12 )
13
14 // TrackerRegistration represents the payload a Hotline server sends to a Tracker to register
15 type TrackerRegistration struct {
16 Port [2]byte // Server's listening TCP port number
17 UserCount int // Number of users connected to this particular server
18 PassID [4]byte // Random number generated by the server
19 Name string // Server Name
20 Description string // Description of the server
21
22 readOffset int // Internal offset to track read progress
23 }
24
25 // Read implements io.Reader to write tracker registration payload bytes to slice
26 func (tr *TrackerRegistration) Read(p []byte) (int, error) {
27 userCount := make([]byte, 2)
28 binary.BigEndian.PutUint16(userCount, uint16(tr.UserCount))
29
30 buf := slices.Concat(
31 []byte{0x00, 0x01}, // Magic number, always 1
32 tr.Port[:],
33 userCount,
34 []byte{0x00, 0x00}, // Magic number, always 0
35 tr.PassID[:],
36 []byte{uint8(len(tr.Name))},
37 []byte(tr.Name),
38 []byte{uint8(len(tr.Description))},
39 []byte(tr.Description),
40 )
41
42 if tr.readOffset >= len(buf) {
43 return 0, io.EOF // All bytes have been read
44 }
45
46 n := copy(p, buf[tr.readOffset:])
47 tr.readOffset += n
48
49 return n, nil
50 }
51
52 func register(tracker string, tr *TrackerRegistration) error {
53 conn, err := net.Dial("udp", tracker)
54 if err != nil {
55 return fmt.Errorf("failed to dial tracker: %w", err)
56 }
57 defer conn.Close()
58
59 if _, err := io.Copy(conn, tr); err != nil {
60 return fmt.Errorf("failed to write to connection: %w", err)
61 }
62
63 return nil
64 }
65
66 const trackerTimeout = 5 * time.Second
67
68 // All string values use 8-bit ASCII character set encoding.
69 // Client Interface with Tracker
70 // After establishing a connection with tracker, the following information is sent:
71 // Description Size Data Note
72 // Magic number 4 ‘HTRK’
73 // Version 2 1 or 2 Old protocol (1) or new (2)
74
75 // Reply received from the tracker starts with a header:
76 type TrackerHeader struct {
77 Protocol [4]byte // "HTRK" 0x4854524B
78 Version [2]byte // Old protocol (1) or new (2)
79 }
80
81 // Message type 2 1 Sending list of servers
82 // Message data size 2 Remaining size of this request
83 // Number of servers 2 Number of servers in the server list
84 // Number of servers 2 Same as previous field
85 type ServerInfoHeader struct {
86 MsgType [2]byte // always has value of 1
87 MsgDataSize [2]byte // Remaining size of request
88 SrvCount [2]byte // Number of servers in the server list
89 SrvCountDup [2]byte // Same as previous field ¯\_(ツ)_/¯
90 }
91
92 type ServerRecord struct {
93 IPAddr [4]byte
94 Port [2]byte
95 NumUsers [2]byte // Number of users connected to this particular server
96 Unused [2]byte
97 NameSize byte // Length of Name string
98 Name []byte // Server Name
99 DescriptionSize byte
100 Description []byte
101 }
102
103 func GetListing(addr string) ([]ServerRecord, error) {
104 conn, err := net.DialTimeout("tcp", addr, trackerTimeout)
105 if err != nil {
106 return []ServerRecord{}, err
107 }
108 defer func() { _ = conn.Close() }()
109
110 _, err = conn.Write(
111 []byte{
112 0x48, 0x54, 0x52, 0x4B, // HTRK
113 0x00, 0x01, // Version
114 },
115 )
116 if err != nil {
117 return nil, err
118 }
119
120 var th TrackerHeader
121 if err := binary.Read(conn, binary.BigEndian, &th); err != nil {
122 return nil, err
123 }
124
125 var info ServerInfoHeader
126 if err := binary.Read(conn, binary.BigEndian, &info); err != nil {
127 return nil, err
128 }
129
130 totalSrv := int(binary.BigEndian.Uint16(info.SrvCount[:]))
131
132 scanner := bufio.NewScanner(conn)
133 scanner.Split(serverScanner)
134
135 var servers []ServerRecord
136 for {
137 scanner.Scan()
138 var srv ServerRecord
139 _, err = srv.Write(scanner.Bytes())
140 if err != nil {
141 return nil, err
142 }
143
144 servers = append(servers, srv)
145 if len(servers) == totalSrv {
146 break
147 }
148 }
149
150 return servers, nil
151 }
152
153 // serverScanner implements bufio.SplitFunc for parsing the tracker list into ServerRecords tokens
154 // Example payload:
155 // 00000000 18 05 30 63 15 7c 00 02 00 00 10 54 68 65 20 4d |..0c.|.....The M|
156 // 00000010 6f 62 69 75 73 20 53 74 72 69 70 40 48 6f 6d 65 |obius Strip@Home|
157 // 00000020 20 6f 66 20 74 68 65 20 4d 6f 62 69 75 73 20 48 | of the Mobius H|
158 // 00000030 6f 74 6c 69 6e 65 20 73 65 72 76 65 72 20 61 6e |otline server an|
159 // 00000040 64 20 63 6c 69 65 6e 74 20 7c 20 54 52 54 50 48 |d client | TRTPH|
160 // 00000050 4f 54 4c 2e 63 6f 6d 3a 35 35 30 30 2d 4f 3a b2 |OTL.com:5500-O:.|
161 // 00000060 15 7c 00 00 00 00 08 53 65 6e 65 63 74 75 73 20 |.|.....Senectus |
162 func serverScanner(data []byte, _ bool) (advance int, token []byte, err error) {
163 // The name length field is the 11th byte of the server record. If we don't have that many bytes,
164 // return nil token so the Scanner reads more data and continues scanning.
165 if len(data) < 10 {
166 return 0, nil, nil
167 }
168
169 // A server entry has two variable length fields: the name and description.
170 // To get the token length, we first need the name length from the 10th byte
171 nameLen := int(data[10])
172
173 // The description length field is at the 12th + nameLen byte of the server record.
174 // If we don't have that many bytes, return nil token so the Scanner reads more data and continues scanning.
175 if len(data) < 11+nameLen {
176 return 0, nil, nil
177 }
178
179 // Next we need the description length from the 11+nameLen byte:
180 descLen := int(data[11+nameLen])
181
182 if len(data) < 12+nameLen+descLen {
183 return 0, nil, nil
184 }
185
186 return 12 + nameLen + descLen, data[0 : 12+nameLen+descLen], nil
187 }
188
189 // Write implements io.Writer for ServerRecord
190 func (s *ServerRecord) Write(b []byte) (n int, err error) {
191 copy(s.IPAddr[:], b[0:4])
192 copy(s.Port[:], b[4:6])
193 copy(s.NumUsers[:], b[6:8])
194 nameLen := int(b[10])
195
196 s.Name = b[11 : 11+nameLen]
197 s.DescriptionSize = b[11+nameLen]
198 s.Description = b[12+nameLen : 12+nameLen+int(s.DescriptionSize)]
199
200 return 12 + nameLen + int(s.DescriptionSize), nil
201 }
202
203 func (s *ServerRecord) Addr() string {
204 return fmt.Sprintf("%s:%s",
205 net.IP(s.IPAddr[:]),
206 strconv.Itoa(int(binary.BigEndian.Uint16(s.Port[:]))),
207 )
208 }