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