/
client.go
365 lines (316 loc) · 8.83 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package homebrew
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"strings"
"time"
)
type authState uint8
const (
authNone authState = iota
authSentLogin
authSentKey
authDone
authFailed
)
// Client implementing the Homebrew protocol
type Client struct {
KeepAlive time.Duration
Timeout time.Duration
// Configuration of the repeater
Configuration *Configuration
// Description of the client
Description string
// URL of the client
URL string
conn net.Conn
data chan []byte
quit chan struct{}
errs chan error
password string
auth authState
hexid [8]byte
nonce [8]byte
pingSent time.Time
pingLatency time.Duration
}
// NewClient sets up a Homebrew protocol client with defaults configured.
func NewClient(cfg *Configuration, addr, password string) (*Client, error) {
if cfg == nil {
return nil, errors.New("homebrew: nil configuration")
}
if err := cfg.Check(); err != nil {
return nil, err
}
c := &Client{
KeepAlive: DefaultKeepAliveInterval,
Timeout: DefaultTimeout,
Configuration: cfg,
password: password,
}
if !strings.Contains(addr, ":") {
addr = fmt.Sprintf("%s:%d", addr, DefaultPort)
}
if Debug {
log.Printf("homebrew: connecting to udp://%s\n", addr)
}
var err error
if c.conn, err = net.Dial("udp", addr); err != nil {
return nil, err
}
return c, nil
}
// Close the client socket and stop the receiver loop after it has been started
// by ListenAndServe.
func (c *Client) Close() error {
if c.quit != nil {
c.quit <- struct{}{} // listen
c.quit <- struct{}{} // receive
}
return c.conn.Close()
}
// ListenAndServe starts the packet receiver and decoder
func (c *Client) ListenAndServe(f chan<- *DMRData) error {
c.quit = make(chan struct{}, 2)
c.data = make(chan []byte)
c.errs = make(chan error)
go c.receive()
if err := c.sendLogin(); err != nil {
return err
}
var (
timeout = time.NewTicker(c.Timeout)
last = time.Now()
)
for {
if c.auth == authDone && time.Since(c.pingSent) > c.KeepAlive {
if err := c.sendPing(); err != nil {
return err
}
}
select {
case data := <-c.data:
if err := c.parse(data, f); err != nil {
c.quit <- struct{}{} // signal receiver
return err
}
last = time.Now()
timeout.Stop()
timeout = time.NewTicker(c.Timeout)
case <-time.After(c.KeepAlive):
if c.auth == authDone {
if err := c.sendPing(); err != nil {
c.quit <- struct{}{} // signal receiver
return err
}
}
case <-timeout.C:
c.quit <- struct{}{} // signal receiver
return fmt.Errorf("timeout after %s", time.Since(last))
case <-c.quit:
return nil
case err := <-c.errs:
return err
}
}
}
// SendDMR sends a DMRData packet
func (c *Client) SendDMR(dmrData *DMRData) error {
copy(dmrData.Signature[:], []byte(SignDMRData))
return binary.Write(c.conn, binary.BigEndian, dmrData)
}
// SendInterrupt sends a call interrupt to a time slot (0 = DMO, 1 = ts1, 2 = ts2)
func (c *Client) SendInterrupt(slot uint8) error {
if slot > 2 {
return ErrInvalidSlot
}
var (
data = make([]byte, len(SignRepeaterInterrupt)+8)
n = copy(data, []byte(SignRepeaterInterrupt))
)
copy(data[n:], c.hexid[:])
data = append(data, []byte(fmt.Sprintf(":%d", slot))...)
_, err := c.conn.Write(data)
return err
}
// SendRSSI sends an RSSI report for a time slot (0 = DMO, 1 = ts1, 2 = ts2)
func (c *Client) SendRSSI(slot uint8, dBm float32) error {
if slot > 2 {
return ErrInvalidSlot
}
var (
data = make([]byte, len(SignRepeaterRSSI)+8)
n = copy(data, []byte(SignRepeaterRSSI))
)
copy(data[n:], c.hexid[:])
data = append(data, []byte(fmt.Sprintf(":%d%f", slot, dBm))...)
_, err := c.conn.Write(data)
return err
}
// SendIdle sends a Firebase idle message
func (c *Client) SendIdle(tokenID uint64, token string) error {
var (
data = make([]byte, len(SignRepeaterIdle)+8)
n = copy(data, []byte(SignRepeaterIdle))
)
copy(data[n:], c.hexid[:])
data = append(data, []byte(fmt.Sprintf(":%d:%s", tokenID, token))...)
_, err := c.conn.Write(data)
return err
}
// SendWake sends a Firebase wake message
func (c *Client) SendWake(tokenID uint64, token string) error {
var (
data = make([]byte, len(SignRepeaterWake)+8)
n = copy(data, []byte(SignRepeaterWake))
)
copy(data[n:], c.hexid[:])
data = append(data, []byte(fmt.Sprintf(":%d:%s", tokenID, token))...)
_, err := c.conn.Write(data)
return err
}
func (c *Client) parse(b []byte, f chan<- *DMRData) (err error) {
if len(b) < 3 {
return io.ErrShortBuffer
}
switch c.auth {
case authSentLogin:
// We expect MSTACK or MSTNAK
if bytes.Equal(b[:len(SignMasterNAK)], []byte(SignMasterNAK)) {
c.auth = authFailed
return ErrMasterRefusedLogin
} else if bytes.Equal(b[:len(SignMasterACK)], []byte(SignMasterACK)) {
if n := copy(c.nonce[:], b[len(SignMasterACK)+8:]); n != 8 {
c.auth = authFailed
return ErrMasterShortNonce
}
if Debug {
log.Println("homebrew: received nonce, sending password")
}
return c.sendKey()
}
// Ignored
log.Printf("homebrew: %q\n", b)
return nil
case authSentKey:
// We expect MSTACK or MSTNAK
if bytes.Equal(b[:len(SignMasterNAK)], []byte(SignMasterNAK)) {
c.auth = authFailed
return ErrMasterRefusedPassword
} else if bytes.Equal(b[:len(SignMasterACK)], []byte(SignMasterACK)) {
if Debug {
log.Println("homebrew: logged in, sending configuration")
}
c.auth = authDone
return c.sendConfiguration()
}
// Ignored
log.Printf("homebrew: %q\n", b)
return nil
}
switch {
case bytes.Equal(b[:len(SignDMRData)], []byte(SignDMRData)):
var dmrData DMRData
if derr := binary.Read(bytes.NewBuffer(b), binary.BigEndian, &dmrData); derr != nil {
log.Printf("homebrew: failed to decode %d bytes of DMRD: %v\n", len(b), derr)
return
}
f <- &dmrData
return nil
case bytes.Equal(b[:len(SignMasterClose)], []byte(SignMasterClose)):
return ErrMasterClose
case bytes.Equal(b[:len(SignMasterACK)], []byte(SignMasterACK)):
if Debug {
log.Println("homebrew: configuration accepted by master")
}
return c.sendPing()
case bytes.Equal(b[:len(SignMasterNAK)], []byte(SignMasterNAK)):
log.Println("homebrew: master dropped connection, logging in")
return c.sendLogin()
case bytes.Equal(b[:len(SignRepeaterPong)], []byte(SignRepeaterPong)):
c.pingLatency = time.Since(c.pingSent)
if Debug {
log.Printf("homebrew: ping RTT %s\n", c.pingLatency)
}
return nil
}
log.Printf("homebrew: %q\n", b)
return nil
}
func (c *Client) receive() {
for {
data := make([]byte, 128)
n, err := c.conn.Read(data)
if err != nil {
c.errs <- err
return
}
c.data <- data[:n]
}
}
func (c *Client) sendLogin() error {
copy(c.hexid[:], []byte(fmt.Sprintf("%08x", c.Configuration.ID)))
var (
data = make([]byte, len(SignRepeaterLogin)+8)
n = copy(data, SignRepeaterLogin)
)
copy(data[n:], c.hexid[:])
c.auth = authSentLogin
_, err := c.conn.Write(data)
return err
}
func (c *Client) sendKey() error {
var (
hash = sha256.Sum256(append(c.nonce[:], []byte(c.password)...))
data = make([]byte, len(SignRepeaterKey)+72)
n = copy(data, SignRepeaterKey)
)
n += copy(data[n:], c.hexid[:])
copy(data[n:], []byte(hex.EncodeToString(hash[:])))
c.auth = authSentKey
_, err := c.conn.Write(data)
return err
}
func (c *Client) sendConfiguration() error {
if err := c.Configuration.Check(); err != nil {
return err
}
var data []byte
data = []byte(SignRepeaterConfig)
data = append(data, []byte(fmt.Sprintf("%-8s", c.Configuration.Callsign))...)
data = append(data, []byte(fmt.Sprintf("%08x", c.Configuration.ID))...)
data = append(data, []byte(fmt.Sprintf("%09d", c.Configuration.RXFreq))...)
data = append(data, []byte(fmt.Sprintf("%09d", c.Configuration.TXFreq))...)
data = append(data, []byte(fmt.Sprintf("%02d", c.Configuration.TXPower))...)
data = append(data, []byte(fmt.Sprintf("%02d", c.Configuration.ColorCode))...)
data = append(data, []byte(fmt.Sprintf("%-08f", c.Configuration.Latitude)[:8])...)
data = append(data, []byte(fmt.Sprintf("%-09f", c.Configuration.Longitude)[:9])...)
data = append(data, []byte(fmt.Sprintf("%03d", c.Configuration.Height))...)
data = append(data, []byte(fmt.Sprintf("%-20s", c.Configuration.Location))...)
data = append(data, []byte(fmt.Sprintf("%-20s", c.Configuration.Description))...)
data = append(data, []byte(fmt.Sprintf("%-124s", c.Configuration.URL))...)
data = append(data, []byte(fmt.Sprintf("%-40s", c.Configuration.SoftwareID))...)
data = append(data, []byte(fmt.Sprintf("%-40s", c.Configuration.PackageID))...)
if Debug {
log.Printf("homebrew: sending %+v\n", c.Configuration)
}
_, err := c.conn.Write(data)
return err
}
func (c *Client) sendPing() error {
var (
data = make([]byte, len(SignMasterPing)+8)
n = copy(data, SignMasterPing)
)
copy(data[n:], c.hexid[:])
_, err := c.conn.Write(data)
c.pingSent = time.Now()
return err
}