]> git.r.bdr.sh - rbdr/mobius/blame - hotline/tracker.go
Update README.md
[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
6eaf9391 21 Password string // Tracker password, if required by tracker
45ca5d60
JH
22
23 readOffset int // Internal offset to track read progress
6988a057
JH
24}
25
9a75b7cb
JH
26// Read implements io.Reader to write tracker registration payload bytes to slice
27func (tr *TrackerRegistration) Read(p []byte) (int, error) {
6988a057
JH
28 userCount := make([]byte, 2)
29 binary.BigEndian.PutUint16(userCount, uint16(tr.UserCount))
30
45ca5d60 31 buf := slices.Concat(
9a75b7cb 32 []byte{0x00, 0x01}, // Magic number, always 1
40414f92 33 tr.Port[:],
6988a057 34 userCount,
9a75b7cb
JH
35 []byte{0x00, 0x00}, // Magic number, always 0
36 tr.PassID[:],
6988a057
JH
37 []byte{uint8(len(tr.Name))},
38 []byte(tr.Name),
39 []byte{uint8(len(tr.Description))},
40 []byte(tr.Description),
6eaf9391
JH
41 []byte{uint8(len(tr.Password))},
42 []byte(tr.Password),
45ca5d60
JH
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
6988a057
JH
53}
54
a2ef262a
JH
55// Dialer interface to abstract the dialing operation
56type Dialer interface {
57 Dial(network, address string) (net.Conn, error)
58}
59
60// RealDialer is the real implementation of the Dialer interface
61type RealDialer struct{}
62
63func (d *RealDialer) Dial(network, address string) (net.Conn, error) {
64 return net.Dial(network, address)
65}
66
67func register(dialer Dialer, tracker string, tr io.Reader) error {
68 conn, err := dialer.Dial("udp", tracker)
6988a057 69 if err != nil {
d9bc63a1 70 return fmt.Errorf("failed to dial tracker: %v", err)
6988a057 71 }
9a75b7cb 72 defer conn.Close()
6988a057 73
9a75b7cb
JH
74 if _, err := io.Copy(conn, tr); err != nil {
75 return fmt.Errorf("failed to write to connection: %w", err)
6988a057
JH
76 }
77
78 return nil
79}
80
6988a057
JH
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
a2ef262a 88// TrackerHeader is sent in reply Reply received from the tracker starts with a header:
6988a057
JH
89type TrackerHeader struct {
90 Protocol [4]byte // "HTRK" 0x4854524B
91 Version [2]byte // Old protocol (1) or new (2)
92}
93
6988a057 94type ServerInfoHeader struct {
a2ef262a 95 MsgType [2]byte // Always has value of 1
6988a057
JH
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
a2ef262a 101// ServerRecord is a tracker listing for a single server
6988a057 102type ServerRecord struct {
c5d9af5a
JH
103 IPAddr [4]byte
104 Port [2]byte
105 NumUsers [2]byte // Number of users connected to this particular server
106 Unused [2]byte
95159e55
JH
107 NameSize byte // Length of Name string
108 Name []byte // Server Name
6988a057
JH
109 DescriptionSize byte
110 Description []byte
111}
112
a2ef262a 113func GetListing(conn io.ReadWriteCloser) ([]ServerRecord, error) {
0203a8c5
JH
114 defer func() { _ = conn.Close() }()
115
a2ef262a 116 _, err := conn.Write(
6988a057
JH
117 []byte{
118 0x48, 0x54, 0x52, 0x4B, // HTRK
119 0x00, 0x01, // Version
120 },
121 )
122 if err != nil {
123 return nil, err
124 }
125
6988a057 126 var th TrackerHeader
8ff2b66d 127 if err := binary.Read(conn, binary.BigEndian, &th); err != nil {
6988a057
JH
128 return nil, err
129 }
130
131 var info ServerInfoHeader
8ff2b66d 132 if err := binary.Read(conn, binary.BigEndian, &info); err != nil {
6988a057
JH
133 return nil, err
134 }
135
6988a057
JH
136 totalSrv := int(binary.BigEndian.Uint16(info.SrvCount[:]))
137
8ff2b66d
JH
138 scanner := bufio.NewScanner(conn)
139 scanner.Split(serverScanner)
6988a057
JH
140
141 var servers []ServerRecord
142 for {
8ff2b66d 143 scanner.Scan()
a55350da 144
7c005672
JH
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
6988a057 150 var srv ServerRecord
7c005672 151 _, err = srv.Write(buf)
04f40273
JH
152 if err != nil {
153 return nil, err
154 }
0203a8c5 155
8ff2b66d 156 servers = append(servers, srv)
6988a057 157 if len(servers) == totalSrv {
8ff2b66d 158 break
6988a057 159 }
8ff2b66d 160 }
6988a057 161
8ff2b66d
JH
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 |
174func serverScanner(data []byte, _ bool) (advance int, token []byte, err error) {
04f40273
JH
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.
8ff2b66d
JH
177 if len(data) < 10 {
178 return 0, nil, nil
6988a057 179 }
8ff2b66d
JH
180
181 // A server entry has two variable length fields: the name and description.
04f40273 182 // To get the token length, we first need the name length from the 10th byte
8ff2b66d
JH
183 nameLen := int(data[10])
184
04f40273
JH
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
8ff2b66d
JH
191 // Next we need the description length from the 11+nameLen byte:
192 descLen := int(data[11+nameLen])
193
04f40273
JH
194 if len(data) < 12+nameLen+descLen {
195 return 0, nil, nil
196 }
197
8ff2b66d 198 return 12 + nameLen + descLen, data[0 : 12+nameLen+descLen], nil
6988a057
JH
199}
200
95159e55
JH
201// Write implements io.Writer for ServerRecord
202func (s *ServerRecord) Write(b []byte) (n int, err error) {
a2ef262a
JH
203 if len(b) < 13 {
204 return 0, errors.New("too few bytes")
205 }
c5d9af5a
JH
206 copy(s.IPAddr[:], b[0:4])
207 copy(s.Port[:], b[4:6])
208 copy(s.NumUsers[:], b[6:8])
a2ef262a 209 s.NameSize = b[10]
6988a057 210 nameLen := int(b[10])
c5d9af5a 211
6988a057
JH
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
6988a057
JH
219func (s *ServerRecord) Addr() string {
220 return fmt.Sprintf("%s:%s",
c5d9af5a
JH
221 net.IP(s.IPAddr[:]),
222 strconv.Itoa(int(binary.BigEndian.Uint16(s.Port[:]))),
6988a057
JH
223 )
224}