-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.go
More file actions
389 lines (321 loc) · 9.37 KB
/
Copy pathmain.go
File metadata and controls
389 lines (321 loc) · 9.37 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package main
import (
"crypto/rand"
"encoding/binary"
"log"
"net"
"sync"
"time"
)
const (
PORT = 62031
PARROT_TG = 9990
BUFFER_SIZE = 1024
REPLAY_DELAY = 1 * time.Second
SERVER_ID = 0xDEADBEEF // Our server ID
)
type Client struct {
ID uint32
Addr *net.UDPAddr
LastPing time.Time
Nonce []byte
Authenticated bool
Callsign string
}
type Recording struct {
Frames [][]byte
SrcID uint32
}
type ActiveStream struct {
StreamID uint32
SrcID uint32
DstID uint32
Originator *net.UDPAddr
}
type Server struct {
conn *net.UDPConn
clients map[string]*Client
mu sync.RWMutex
recordings map[uint32]*Recording
recMu sync.RWMutex
activeStreams map[uint32]*ActiveStream
streamMu sync.RWMutex
}
func main() {
log.Printf("Starting goDMRLink DMR Parrot on port %d", PORT)
log.Printf("Parrot TalkGroup: %d", PARROT_TG)
addr := net.UDPAddr{
Port: PORT,
IP: net.ParseIP("0.0.0.0"),
}
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
log.Fatal("Failed to bind UDP port:", err)
}
defer conn.Close()
server := &Server{
conn: conn,
clients: make(map[string]*Client),
recordings: make(map[uint32]*Recording),
activeStreams: make(map[uint32]*ActiveStream),
}
log.Println("Server started successfully")
server.run()
}
func (s *Server) run() {
buffer := make([]byte, BUFFER_SIZE)
for {
n, addr, err := s.conn.ReadFromUDP(buffer)
if err != nil {
log.Println("Read error:", err)
continue
}
if n < 4 {
continue
}
data := make([]byte, n)
copy(data, buffer[:n])
go s.handlePacket(data, addr)
}
}
func (s *Server) handlePacket(data []byte, addr *net.UDPAddr) {
signature := string(data[:4])
log.Printf("Received packet: type=%s len=%d from=%s hex=%x", signature, len(data), addr, data[:min(len(data), 12)])
switch signature {
case "DMRD":
s.handleDMRData(data, addr)
case "RPTL":
s.handleLogin(data, addr)
case "RPTK":
s.handleRepeaterKey(data, addr)
case "RPTP":
s.handlePing(data, addr)
case "RPTC":
s.handleConfig(data, addr)
default:
log.Printf("Unknown packet type: %s from %s", signature, addr)
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func (s *Server) handleLogin(data []byte, addr *net.UDPAddr) {
if len(data) < 8 {
return
}
clientKey := addr.String()
repeaterID := binary.LittleEndian.Uint32(data[4:8])
log.Printf("LOGIN (RPTL) from %s (ID: %d)", addr, repeaterID)
// Generate 4-byte nonce
nonce := make([]byte, 4)
rand.Read(nonce)
s.mu.Lock()
s.clients[clientKey] = &Client{
ID: repeaterID,
Addr: addr,
LastPing: time.Now(),
Nonce: nonce,
Authenticated: false,
}
s.mu.Unlock()
// Send MSTACK with SERVER ID + nonce (challenge)
response := []byte("RPTACK")
response = append(response, nonce...) // Just the salt/nonce
s.conn.WriteToUDP(response, addr)
log.Printf("Sent RPTACK with salt to repeater %d", repeaterID)
}
func (s *Server) handleRepeaterKey(data []byte, addr *net.UDPAddr) {
if len(data) < 12 {
return
}
clientKey := addr.String()
repeaterID := binary.LittleEndian.Uint32(data[4:8])
log.Printf("KEY (RPTK) from %s (ID: %d), len=%d", addr, repeaterID, len(data))
s.mu.Lock()
client, ok := s.clients[clientKey]
if !ok || client.Authenticated {
s.mu.Unlock()
log.Printf("Client %d not found or already authenticated", repeaterID)
return
}
// We accept any password, so just mark as authenticated
client.Authenticated = true
client.LastPing = time.Now()
s.mu.Unlock()
// Send final ACK with repeater ID
response := []byte("RPTACK")
response = append(response, data[4:8]...) // Echo back the repeater ID
s.conn.WriteToUDP(response, addr)
log.Printf("Client %d fully authenticated!", repeaterID)
}
func (s *Server) handlePing(data []byte, addr *net.UDPAddr) {
if len(data) < 8 {
return
}
clientKey := addr.String()
repeaterID := binary.LittleEndian.Uint32(data[4:8])
s.mu.Lock()
if client, ok := s.clients[clientKey]; ok {
client.LastPing = time.Now()
}
s.mu.Unlock()
// Send MSTPONG
response := []byte("MSTPONG")
response = append(response, data[4:8]...)
s.conn.WriteToUDP(response, addr)
log.Printf("PING from %d, sent PONG", repeaterID)
}
func (s *Server) handleConfig(data []byte, addr *net.UDPAddr) {
log.Printf("CONFIG from %s", addr)
// Just acknowledge config
response := []byte("RPTACK")
if len(data) >= 8 {
response = append(response, data[4:8]...)
}
s.conn.WriteToUDP(response, addr)
}
func (s *Server) handleDMRData(data []byte, addr *net.UDPAddr) {
if len(data) < 55 {
log.Printf("DMR packet too short: %d bytes", len(data))
return
}
// Parse DMR frame - DMR IDs are 24-bit big-endian
seqNum := data[4]
srcID := uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
dstID := uint32(data[8])<<16 | uint32(data[9])<<8 | uint32(data[10])
repeaterID := binary.LittleEndian.Uint32(data[11:15])
slotNo := (data[15] & 0x80) >> 7
callType := (data[15] & 0x40) >> 6 // 1=private, 0=group
frameType := data[15] & 0x3F
streamID := binary.BigEndian.Uint32(data[16:20])
callTypeStr := "group"
if callType == 1 {
callTypeStr = "private"
}
log.Printf("Received DMR: Seq=%d Src=%d Dst=%d Slot=%d CallType=%s (0x%02X) Type=0x%02X Stream=%d",
seqNum, srcID, dstID, slotNo, callTypeStr, data[15], frameType, streamID)
// TG 9990 is the parrot - handle it separately
if dstID == PARROT_TG {
s.recordFrame(srcID, streamID, data)
if frameType == 0x22 { // End of voice transmission
log.Printf("Parrot: End of transmission from %d, starting playback...", srcID)
go s.playbackRecording(srcID, repeaterID, slotNo, addr)
}
return
}
// For all other TGs, bridge to all connected clients
s.bridgeToClients(data, addr, streamID, srcID, dstID, frameType)
}
func (s *Server) recordFrame(srcID, streamID uint32, frame []byte) {
s.recMu.Lock()
defer s.recMu.Unlock()
if rec, exists := s.recordings[srcID]; exists {
rec.Frames = append(rec.Frames, frame)
} else {
s.recordings[srcID] = &Recording{
Frames: [][]byte{frame},
SrcID: srcID,
}
}
}
func (s *Server) playbackRecording(srcID, repeaterID uint32, slotNo byte, addr *net.UDPAddr) {
time.Sleep(REPLAY_DELAY)
s.recMu.Lock()
rec, exists := s.recordings[srcID]
if !exists || len(rec.Frames) == 0 {
s.recMu.Unlock()
return
}
frames := make([][]byte, len(rec.Frames))
copy(frames, rec.Frames)
delete(s.recordings, srcID)
s.recMu.Unlock()
log.Printf("Playing back %d frames to %d", len(frames), srcID)
newStreamID := uint32(time.Now().Unix())
for i, frame := range frames {
if len(frame) < 55 {
continue
}
// Create modified frame
playbackFrame := make([]byte, len(frame))
copy(playbackFrame, frame)
// Always swap header IDs (bytes 5-10)
playbackFrame[5] = byte((PARROT_TG >> 16) & 0xFF)
playbackFrame[6] = byte((PARROT_TG >> 8) & 0xFF)
playbackFrame[7] = byte(PARROT_TG & 0xFF)
playbackFrame[8] = byte((srcID >> 16) & 0xFF)
playbackFrame[9] = byte((srcID >> 8) & 0xFF)
playbackFrame[10] = byte(srcID & 0xFF)
// Change stream ID
binary.BigEndian.PutUint32(playbackFrame[16:20], newStreamID)
// For voice header frames (0x21), also modify the Full LC data
frameType := playbackFrame[15] & 0x3F
if frameType == 0x21 || frameType == 0x22 {
// Voice header/terminator contains Full LC in bytes 20-32
// LC format: [opcode][fid][so][dst:3][src:3][crc:2]
// Bytes 23-25 = DST, Bytes 26-28 = SRC
if len(playbackFrame) >= 33 {
// Swap IDs in the LC payload too
playbackFrame[23] = byte((srcID >> 16) & 0xFF)
playbackFrame[24] = byte((srcID >> 8) & 0xFF)
playbackFrame[25] = byte(srcID & 0xFF)
playbackFrame[26] = byte((PARROT_TG >> 16) & 0xFF)
playbackFrame[27] = byte((PARROT_TG >> 8) & 0xFF)
playbackFrame[28] = byte(PARROT_TG & 0xFF)
// Note: CRC at bytes 31-32 is now invalid, but radio may not check it
}
}
if i == 0 {
log.Printf("Playback: SRC=%d DST=%d (private call)", PARROT_TG, srcID)
}
s.conn.WriteToUDP(playbackFrame, addr)
time.Sleep(60 * time.Millisecond)
}
log.Printf("Playback complete for %d", srcID)
}
func (s *Server) bridgeToClients(data []byte, fromAddr *net.UDPAddr, streamID, srcID, dstID uint32, frameType byte) {
// Track active streams
if frameType == 0x21 || frameType == 0x01 { // Voice header or first burst
s.streamMu.Lock()
if _, exists := s.activeStreams[streamID]; !exists {
s.activeStreams[streamID] = &ActiveStream{
StreamID: streamID,
SrcID: srcID,
DstID: dstID,
Originator: fromAddr,
}
log.Printf("Bridge: New stream %d from %d to TG %d", streamID, srcID, dstID)
}
s.streamMu.Unlock()
}
// Forward to all authenticated clients except the originator
s.mu.RLock()
count := 0
for _, client := range s.clients {
// Skip if not authenticated
if !client.Authenticated {
continue
}
// Skip the originating client
if client.Addr.String() == fromAddr.String() {
continue
}
// Send the frame unchanged to this client
s.conn.WriteToUDP(data, client.Addr)
count++
}
s.mu.RUnlock()
if frameType == 0x21 { // Only log on voice header
log.Printf("Bridge: Forwarded TG %d from %d to %d clients", dstID, srcID, count)
}
// Clean up stream on terminator
if frameType == 0x22 {
s.streamMu.Lock()
delete(s.activeStreams, streamID)
s.streamMu.Unlock()
log.Printf("Bridge: Stream %d from %d to TG %d ended", streamID, srcID, dstID)
}
}