Debian Codegraph @

linux/evt/evt.go

raw symbols SCIP
1 package evt
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8
9 "github.com/bettercap/gatt/linux/util"
10 )
11
12 type EventHandler interface {
13 HandleEvent([]byte) error
14 }
15
16 type HandlerFunc func(b []byte) error
17
18 func (f HandlerFunc) HandleEvent(b []byte) error {
19 return f(b)
20 }
21
22 type Evt struct {
23 evtHandlers map[int]EventHandler
24 }
25
26 func NewEvt() *Evt {
27 return &Evt{
28 evtHandlers: map[int]EventHandler{},
29 }
30 }
31
32 func (e *Evt) HandleEvent(c int, h EventHandler) {
33 e.evtHandlers[c] = h
34 }
35
36 func (e *Evt) Dispatch(b []byte) error {
37 h := &EventHeader{}
38 if err := h.Unmarshal(b); err != nil {
39 return err
40 }
41 b = b[2:] // Skip Event Header (uint8 + uint8)
42 if f, found := e.evtHandlers[h.code]; found {
43 e.trace("> HCI Event: %s (0x%02X) plen %d: [ % X ])\n", h.code, uint8(h.code), h.plen, b)
44 return f.HandleEvent(b)
45 }
46 e.trace("> HCI Event: no handler for %s (0x%02X)\n", h.code, uint8(h.code))
47 return nil
48 }
49
50 func (e *Evt) trace(fmt string, v ...interface{}) {}
51
52 const (
53 InquiryComplete = 0x01 // Inquiry Complete
54 InquiryResult = 0x02 // Inquiry Result
55 ConnectionComplete = 0x03 // Connection Complete
56 ConnectionRequest = 0x04 // Connection Request
57 DisconnectionComplete = 0x05 // Disconnection Complete
58 AuthenticationComplete = 0x06 // Authentication
59 RemoteNameReqComplete = 0x07 // Remote Name Request Complete
60 EncryptionChange = 0x08 // Encryption Change
61 ChangeConnectionLinkKeyComplete = 0x09 // Change Conection Link Key Complete
62 MasterLinkKeyComplete = 0x0A // Master Link Keye Complete
63 ReadRemoteSupportedFeaturesComplete = 0x0B // Read Remote Supported Features Complete
64 ReadRemoteVersionInformationComplete = 0x0C // Read Remote Version Information Complete
65 QoSSetupComplete = 0x0D // QoSSetupComplete
66 CommandComplete = 0x0E // Command Complete
67 CommandStatus = 0x0F // Command status
68 HardwareError = 0x10 // Hardware Error
69 FlushOccurred = 0x11 // Flush Occured
70 RoleChange = 0x12 // Role Change
71 NumberOfCompletedPkts = 0x13 // Number Of Completed Packets
72 ModeChange = 0x14 // Mode Change
73 ReturnLinkKeys = 0x15 // Return Link Keys
74 PinCodeRequest = 0x16 // PIN Code Request
75 LinkKeyRequest = 0x17 // Link Key Request
76 LinkKeyNotification = 0x18 // Link Key Notification
77 LoopbackCommand = 0x19 // Loopback Command
78 DataBufferOverflow = 0x1A // Data Buffer Overflow
79 MaxSlotsChange = 0x1B // Max Slots Change
80 ReadClockOffsetComplete = 0x1C // Read Clock Offset Complete
81 ConnectionPtypeChanged = 0x1D // Connection Packet Type Changed
82 QoSViolation = 0x1E // QoS Violation
83 PageScanRepetitionModeChange = 0x20 // Page Scan Repetition Mode Change
84 FlowSpecificationComplete = 0x21 // Flow Specification
85 InquiryResultWithRssi = 0x22 // Inquery Result with RSSI
86 ReadRemoteExtendedFeaturesComplete = 0x23 // Read Remote Extended Features Complete
87 SyncConnectionComplete = 0x2C // Synchronous Connection Complete
88 SyncConnectionChanged = 0x2D // Synchronous Connection Changed
89 SniffSubrating = 0x2E // Sniff Subrating
90 ExtendedInquiryResult = 0x2F // Extended Inquiry Result
91 EncryptionKeyRefreshComplete = 0x30 // Encryption Key Refresh Complete
92 IOCapabilityRequest = 0x31 // IO Capability Request
93 IOCapabilityResponse = 0x32 // IO Capability Changed
94 UserConfirmationRequest = 0x33 // User Confirmation Request
95 UserPasskeyRequest = 0x34 // User Passkey Request
96 RemoteOOBDataRequest = 0x35 // Remote OOB Data
97 SimplePairingComplete = 0x36 // Simple Pairing Complete
98 LinkSupervisionTimeoutChanged = 0x38 // Link Supervision Timeout Changed
99 EnhancedFlushComplete = 0x39 // Enhanced Flush Complete
100 UserPasskeyNotify = 0x3B // User Passkey Notification
101 KeypressNotify = 0x3C // Keypass Notification
102 RemoteHostFeaturesNotify = 0x3D // Remote Host Supported Features Notification
103 LEMeta = 0x3E // LE Meta
104 PhysicalLinkComplete = 0x40 // Physical Link Complete
105 ChannelSelected = 0x41 // Channel Selected
106 DisconnectionPhysicalLinkComplete = 0x42 // Disconnection Physical Link Complete
107 PhysicalLinkLossEarlyWarning = 0x43 // Physical Link Loss Early Warning
108 PhysicalLinkRecovery = 0x44 // Physical Link Recovery
109 LogicalLinkComplete = 0x45 // Logical Link Complete
110 DisconnectionLogicalLinkComplete = 0x46 // Disconnection Logical Link Complete
111 FlowSpecModifyComplete = 0x47 // Flow Spec Modify Complete
112 NumberOfCompletedBlocks = 0x48 // Number Of Completed Data Blocks
113 AMPStartTest = 0x49 // AMP Start Test
114 AMPTestEnd = 0x4A // AMP Test End
115 AMPReceiverReport = 0x4b // AMP Receiver Report
116 AMPStatusChange = 0x4D // AMP status Change
117 TriggeredClockCapture = 0x4e // Triggered Clock Capture
118 SynchronizationTrainComplete = 0x4F // Synchronization Train Complete
119 SynchronizationTrainReceived = 0x50 // Synchronization Train Received
120 ConnectionlessSlaveBroadcastReceive = 0x51 // Connectionless Slave Broadcast Receive
121 ConnectionlessSlaveBroadcastTimeout = 0x52 // Connectionless Slave Broadcast Timeout
122 TruncatedPageComplete = 0x53 // Truncated Page Complete
123 SlavePageResponseTimeout = 0x54 // Slave Page Response Timeout
124 ConnectionlessSlaveBroadcastChannelMapChange = 0x55 // Connectionless Slave Broadcast Channel Map Change
125 InquiryResponseNotification = 0x56 // Inquiry Response Notification
126 AuthenticatedPayloadTimeoutExpired = 0x57 // Authenticated Payload Timeout Expired
127 )
128
129 type LEEventCode int
130
131 const (
132 LEConnectionComplete LEEventCode = 0x01 // LE Connection Complete
133 LEAdvertisingReport = 0x02 // LE Advertising Report
134 LEConnectionUpdateComplete = 0x03 // LE Connection Update Complete
135 LEReadRemoteUsedFeaturesComplete = 0x04 // LE Read Remote Used Features Complete
136 LELTKRequest = 0x05 // LE LTK Request
137 LERemoteConnectionParameterRequest = 0x06 // LE Remote Connection Parameter Request
138 )
139
140 type EventHeader struct {
141 code int
142 plen uint8
143 }
144
145 func (h *EventHeader) Unmarshal(b []byte) error {
146 if len(b) < 2 {
147 return errors.New("malformed header")
148 }
149 h.code = int(b[0])
150 h.plen = b[1]
151 if uint8(len(b)) != 2+h.plen {
152 return errors.New("wrong length")
153 }
154 return nil
155 }
156
157 var o = util.Order
158
159 // Event Parameters
160
161 type InquiryCompleteEP struct {
162 Status uint8
163 }
164
165 type InquiryResultEP struct {
166 NumResponses uint8
167 BDAddr [][6]byte
168 PageScanRepetitionMode []uint8
169 Reserved1 []byte
170 Reserved2 []byte
171 ClassOfDevice [][3]byte
172 ClockOffset []uint16
173 }
174
175 type ConnectionCompleteEP struct {
176 Status uint8
177 ConnectionHandle uint16
178 BDAddr [6]byte
179 LinkType uint8
180 EncryptionEnabled uint8
181 }
182
183 type ConnectionRequestEP struct {
184 BDAddr [6]byte
185 ClassofDevice [3]byte
186 LinkType uint8
187 }
188
189 type DisconnectionCompleteEP struct {
190 Status uint8
191 ConnectionHandle uint16
192 Reason uint8
193 }
194
195 func (e *DisconnectionCompleteEP) Unmarshal(b []byte) error {
196 buf := bytes.NewBuffer(b)
197 binary.Read(buf, binary.LittleEndian, &e.Status)
198 binary.Read(buf, binary.LittleEndian, &e.ConnectionHandle)
199 return binary.Read(buf, binary.LittleEndian, &e.Reason)
200 }
201
202 type CommandCompleteEP struct {
203 NumHCICommandPackets uint8
204 CommandOPCode uint16
205 ReturnParameters []byte
206 }
207
208 func (e *CommandCompleteEP) Unmarshal(b []byte) error {
209 buf := bytes.NewBuffer(b)
210 if err := binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets); err != nil {
211 return err
212 }
213 if err := binary.Read(buf, binary.LittleEndian, &e.CommandOPCode); err != nil {
214 return err
215 }
216 e.ReturnParameters = buf.Bytes()
217 return nil
218 }
219
220 type CommandStatusEP struct {
221 Status uint8
222 NumHCICommandPackets uint8
223 CommandOpcode uint16
224 }
225
226 func (e *CommandStatusEP) Unmarshal(b []byte) error {
227 buf := bytes.NewBuffer(b)
228 binary.Read(buf, binary.LittleEndian, &e.Status)
229 binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets)
230 return binary.Read(buf, binary.LittleEndian, &e.CommandOpcode)
231 }
232
233 type NumOfCompletedPkt struct {
234 ConnectionHandle uint16
235 NumOfCompletedPkts uint16
236 }
237
238 type NumberOfCompletedPktsEP struct {
239 NumberOfHandles uint8
240 Packets []NumOfCompletedPkt
241 }
242
243 func (e *NumberOfCompletedPktsEP) Unmarshal(b []byte) error {
244 e.NumberOfHandles = b[0]
245 n := int(e.NumberOfHandles)
246 buf := bytes.NewBuffer(b[1:])
247 e.Packets = make([]NumOfCompletedPkt, n)
248 for i := 0; i < n; i++ {
249 binary.Read(buf, binary.LittleEndian, &e.Packets[i].ConnectionHandle)
250 binary.Read(buf, binary.LittleEndian, &e.Packets[i].NumOfCompletedPkts)
251
252 e.Packets[i].ConnectionHandle &= 0xfff
253 }
254 return nil
255 }
256
257 // LE Meta Subevents
258 type LEConnectionCompleteEP struct {
259 SubeventCode uint8
260 Status uint8
261 ConnectionHandle uint16
262 Role uint8
263 PeerAddressType uint8
264 PeerAddress [6]byte
265 ConnInterval uint16
266 ConnLatency uint16
267 SupervisionTimeout uint16
268 MasterClockAccuracy uint8
269 }
270
271 func (e *LEConnectionCompleteEP) Unmarshal(b []byte) error {
272 if len(b) < 18 {
273 return fmt.Errorf("expected at least 18 bytes, got %d", len(b))
274 }
275 e.SubeventCode = o.Uint8(b[0:])
276 e.Status = o.Uint8(b[1:])
277 e.ConnectionHandle = o.Uint16(b[2:])
278 e.Role = o.Uint8(b[4:])
279 e.PeerAddressType = o.Uint8(b[5:])
280 e.PeerAddress = o.MAC(b[6:])
281 e.ConnInterval = o.Uint16(b[12:])
282 e.ConnLatency = o.Uint16(b[14:])
283 e.SupervisionTimeout = o.Uint16(b[16:])
284 e.MasterClockAccuracy = o.Uint8(b[17:])
285 return nil
286 }
287
288 type LEAdvertisingReportEP struct {
289 SubeventCode uint8
290 NumReports uint8
291 EventType []uint8
292 AddressType []uint8
293 Address [][6]byte
294 Length []uint8
295 Data [][]byte
296 RSSI []int8
297 }
298
299 func (e *LEAdvertisingReportEP) Unmarshal(b []byte) error {
300 if len(b) < 2 {
301 return errors.New("expected at least 2 bytes")
302 }
303 e.SubeventCode = o.Uint8(b)
304 b = b[1:]
305 e.NumReports = o.Uint8(b)
306 b = b[1:]
307 n := int(e.NumReports)
308
309 e.EventType = make([]uint8, n)
310 e.AddressType = make([]uint8, n)
311 e.Address = make([][6]byte, n)
312 e.Length = make([]uint8, n)
313 e.Data = make([][]byte, n)
314 e.RSSI = make([]int8, n)
315
316 if len(b) < (1+1+6+1)*n {
317 return fmt.Errorf("expected %d more bytes, got %d", (1+1+6+1)*n, len(b))
318 }
319
320 for i := 0; i < n; i++ {
321 e.EventType[i] = o.Uint8(b)
322 b = b[1:]
323 }
324 for i := 0; i < n; i++ {
325 e.AddressType[i] = o.Uint8(b)
326 b = b[1:]
327 }
328 for i := 0; i < n; i++ {
329 e.Address[i] = o.MAC(b)
330 b = b[6:]
331 }
332 var sumLength int
333 for i := 0; i < n; i++ {
334 e.Length[i] = o.Uint8(b)
335 sumLength += int(e.Length[i])
336 b = b[1:]
337 }
338
339 if len(b) < sumLength+(1)*n {
340 return fmt.Errorf("expected %d more bytes, got %d", sumLength+(1)*n, len(b))
341 }
342
343 for i := 0; i < n; i++ {
344 e.Data[i] = make([]byte, e.Length[i])
345 copy(e.Data[i], b)
346 b = b[e.Length[i]:]
347 }
348 for i := 0; i < n; i++ {
349 e.RSSI[i] = o.Int8(b)
350 b = b[1:]
351 }
352 return nil
353 }
354
355 type LEConnectionUpdateCompleteEP struct {
356 SubeventCode uint8
357 Status uint8
358 ConnectionHandle uint16
359 ConnInterval uint16
360 ConnLatency uint16
361 SupervisionTimeout uint16
362 }
363
364 func (e *LEConnectionUpdateCompleteEP) Unmarshal(b []byte) error {
365 return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
366 }
367
368 type LEReadRemoteUsedFeaturesCompleteEP struct {
369 SubeventCode uint8
370 Status uint8
371 ConnectionHandle uint16
372 LEFeatures uint64
373 }
374
375 func (e *LEReadRemoteUsedFeaturesCompleteEP) Unmarshal(b []byte) error {
376 return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
377 }
378
379 type LELTKRequestEP struct {
380 SubeventCode uint8
381 ConnectionHandle uint16
382 RandomNumber uint64
383 EncryptionDiversifier uint16
384 }
385
386 func (e *LELTKRequestEP) Unmarshal(b []byte) error {
387 return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
388 }
389
390 type LERemoteConnectionParameterRequestEP struct {
391 SubeventCode uint8
392 ConnectionHandle uint16
393 IntervalMin uint16
394 IntervalMax uint16
395 Latency uint16
396 Timeout uint16
397 }
398
399 func (e *LERemoteConnectionParameterRequestEP) Unmarshal(b []byte) error {
400 return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
401 }