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