Debian Codegraph @

central_linux.go

raw symbols SCIP
1 package gatt
2
3 import (
4 "encoding/binary"
5 "io"
6 "net"
7 "sync"
8 )
9
10 type security int
11
12 const (
13 securityLow = iota
14 securityMed
15 securityHigh
16 )
17
18 type central struct {
19 attrs *attrRange
20 mtu uint16
21 addr net.HardwareAddr
22 security security
23 l2conn io.ReadWriteCloser
24 notifiers map[uint16]*notifier
25 notifiersmu *sync.Mutex
26 }
27
28 func newCentral(a *attrRange, addr net.HardwareAddr, l2conn io.ReadWriteCloser) *central {
29 return &central{
30 attrs: a,
31 mtu: 23,
32 addr: addr,
33 security: securityLow,
34 l2conn: l2conn,
35 notifiers: make(map[uint16]*notifier),
36 notifiersmu: &sync.Mutex{},
37 }
38 }
39
40 func (c *central) ID() string {
41 return c.addr.String()
42 }
43
44 func (c *central) Close() error {
45 c.notifiersmu.Lock()
46 defer c.notifiersmu.Unlock()
47 for _, n := range c.notifiers {
48 n.stop()
49 }
50 return c.l2conn.Close()
51 }
52
53 func (c *central) MTU() int {
54 return int(c.mtu)
55 }
56
57 func (c *central) loop() {
58 for {
59 // L2CAP implementations shall support a minimum MTU size of 48 bytes.
60 // The default value is 672 bytes
61 b := make([]byte, 672)
62 n, err := c.l2conn.Read(b)
63 if n == 0 || err != nil {
64 c.Close()
65 break
66 }
67 if rsp := c.handleReq(b[:n]); rsp != nil {
68 c.l2conn.Write(rsp)
69 }
70 }
71 }
72
73 // handleReq dispatches a raw request from the central shim
74 // to an appropriate handler, based on its type.
75 // It panics if len(b) == 0.
76 func (c *central) handleReq(b []byte) []byte {
77 var resp []byte
78 switch reqType, req := b[0], b[1:]; reqType {
79 case attOpMtuReq:
80 resp = c.handleMTU(req)
81 case attOpFindInfoReq:
82 resp = c.handleFindInfo(req)
83 case attOpFindByTypeValueReq:
84 resp = c.handleFindByTypeValue(req)
85 case attOpReadByTypeReq:
86 resp = c.handleReadByType(req)
87 case attOpReadReq:
88 resp = c.handleRead(req)
89 case attOpReadBlobReq:
90 resp = c.handleReadBlob(req)
91 case attOpReadByGroupReq:
92 resp = c.handleReadByGroup(req)
93 case attOpWriteReq, attOpWriteCmd:
94 resp = c.handleWrite(reqType, req)
95 case attOpReadMultiReq, attOpPrepWriteReq, attOpExecWriteReq, attOpSignedWriteCmd:
96 fallthrough
97 default:
98 resp = attErrorRsp(reqType, 0x0000, attEcodeReqNotSupp)
99 }
100 return resp
101 }
102
103 func (c *central) handleMTU(b []byte) []byte {
104 c.mtu = binary.LittleEndian.Uint16(b[:2])
105 if c.mtu < 23 {
106 c.mtu = 23
107 }
108 if c.mtu >= 256 {
109 c.mtu = 256
110 }
111 return []byte{attOpMtuRsp, uint8(c.mtu), uint8(c.mtu >> 8)}
112 }
113
114 // REQ: FindInfoReq(0x04), StartHandle, EndHandle
115 // RSP: FindInfoRsp(0x05), UUIDFormat, Handle, UUID, Handle, UUID, ...
116 func (c *central) handleFindInfo(b []byte) []byte {
117 start, end := readHandleRange(b[:4])
118
119 w := newL2capWriter(c.mtu)
120 w.WriteByteFit(attOpFindInfoRsp)
121
122 uuidLen := -1
123 for _, a := range c.attrs.Subrange(start, end) {
124 if uuidLen == -1 {
125 uuidLen = a.typ.Len()
126 if uuidLen == 2 {
127 w.WriteByteFit(0x01) // TODO: constants for 16bit vs 128bit uuid magic numbers here
128 } else {
129 w.WriteByteFit(0x02)
130 }
131 }
132 if a.typ.Len() != uuidLen {
133 break
134 }
135 w.Chunk()
136 w.WriteUint16Fit(a.h)
137 w.WriteUUIDFit(a.typ)
138 if ok := w.Commit(); !ok {
139 break
140 }
141 }
142
143 if uuidLen == -1 {
144 return attErrorRsp(attOpFindInfoReq, start, attEcodeAttrNotFound)
145 }
146 return w.Bytes()
147 }
148
149 // REQ: FindByTypeValueReq(0x06), StartHandle, EndHandle, Type(UUID), Value
150 // RSP: FindByTypeValueRsp(0x07), AttrHandle, GroupEndHandle, AttrHandle, GroupEndHandle, ...
151 func (c *central) handleFindByTypeValue(b []byte) []byte {
152 start, end := readHandleRange(b[:4])
153 t := UUID{b[4:6]}
154 u := UUID{b[6:]}
155
156 // Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
157 // More sepcifically, the "Discover Primary Services By Service UUID" sub-procedure
158 if !t.Equal(attrPrimaryServiceUUID) {
159 return attErrorRsp(attOpFindByTypeValueReq, start, attEcodeAttrNotFound)
160 }
161
162 w := newL2capWriter(c.mtu)
163 w.WriteByteFit(attOpFindByTypeValueRsp)
164
165 var wrote bool
166 for _, a := range c.attrs.Subrange(start, end) {
167 if !a.typ.Equal(attrPrimaryServiceUUID) {
168 continue
169 }
170 if !(UUID{a.value}.Equal(u)) {
171 continue
172 }
173 s := a.pvt.(*Service)
174 w.Chunk()
175 w.WriteUint16Fit(s.h)
176 w.WriteUint16Fit(s.endh)
177 if ok := w.Commit(); !ok {
178 break
179 }
180 wrote = true
181 }
182 if !wrote {
183 return attErrorRsp(attOpFindByTypeValueReq, start, attEcodeAttrNotFound)
184 }
185
186 return w.Bytes()
187 }
188
189 // REQ: ReadByType(0x08), StartHandle, EndHandle, Type(UUID)
190 // RSP: ReadByType(0x09), LenOfEachDataField, DataField, DataField, ...
191 func (c *central) handleReadByType(b []byte) []byte {
192 start, end := readHandleRange(b[:4])
193 t := UUID{b[4:]}
194
195 w := newL2capWriter(c.mtu)
196 w.WriteByteFit(attOpReadByTypeRsp)
197 uuidLen := -1
198 for _, a := range c.attrs.Subrange(start, end) {
199 if !a.typ.Equal(t) {
200 continue
201 }
202 if (a.secure&CharRead) != 0 && c.security > securityLow {
203 return attErrorRsp(attOpReadByTypeReq, start, attEcodeAuthentication)
204 }
205 v := a.value
206 if v == nil {
207 rsp := newResponseWriter(int(c.mtu - 1))
208 req := &ReadRequest{
209 Request: Request{Central: c},
210 Cap: int(c.mtu - 1),
211 Offset: 0,
212 }
213 if c, ok := a.pvt.(*Characteristic); ok {
214 c.rhandler.ServeRead(rsp, req)
215 } else if d, ok := a.pvt.(*Descriptor); ok {
216 d.rhandler.ServeRead(rsp, req)
217 }
218 v = rsp.bytes()
219 }
220 if uuidLen == -1 {
221 uuidLen = len(v)
222 w.WriteByteFit(byte(uuidLen) + 2)
223 }
224 if len(v) != uuidLen {
225 break
226 }
227 w.Chunk()
228 w.WriteUint16Fit(a.h)
229 w.WriteFit(v)
230 if ok := w.Commit(); !ok {
231 break
232 }
233 }
234 if uuidLen == -1 {
235 return attErrorRsp(attOpReadByTypeReq, start, attEcodeAttrNotFound)
236 }
237 return w.Bytes()
238 }
239
240 // REQ: ReadReq(0x0A), Handle
241 // RSP: ReadRsp(0x0B), Value
242 func (c *central) handleRead(b []byte) []byte {
243 h := binary.LittleEndian.Uint16(b)
244 a, ok := c.attrs.At(h)
245 if !ok {
246 return attErrorRsp(attOpReadReq, h, attEcodeInvalidHandle)
247 }
248 if a.props&CharRead == 0 {
249 return attErrorRsp(attOpReadReq, h, attEcodeReadNotPerm)
250 }
251 if a.secure&CharRead != 0 && c.security > securityLow {
252 return attErrorRsp(attOpReadReq, h, attEcodeAuthentication)
253 }
254 v := a.value
255 if v == nil {
256 req := &ReadRequest{
257 Request: Request{Central: c},
258 Cap: int(c.mtu - 1),
259 Offset: 0,
260 }
261 rsp := newResponseWriter(int(c.mtu - 1))
262 if c, ok := a.pvt.(*Characteristic); ok {
263 c.rhandler.ServeRead(rsp, req)
264 } else if d, ok := a.pvt.(*Descriptor); ok {
265 d.rhandler.ServeRead(rsp, req)
266 }
267 v = rsp.bytes()
268 }
269
270 w := newL2capWriter(c.mtu)
271 w.WriteByteFit(attOpReadRsp)
272 w.Chunk()
273 w.WriteFit(v)
274 w.CommitFit()
275 return w.Bytes()
276 }
277
278 // FIXME: check this, untested, might be broken
279 func (c *central) handleReadBlob(b []byte) []byte {
280 h := binary.LittleEndian.Uint16(b)
281 offset := binary.LittleEndian.Uint16(b[2:])
282 a, ok := c.attrs.At(h)
283 if !ok {
284 return attErrorRsp(attOpReadBlobReq, h, attEcodeInvalidHandle)
285 }
286 if a.props&CharRead == 0 {
287 return attErrorRsp(attOpReadBlobReq, h, attEcodeReadNotPerm)
288 }
289 if a.secure&CharRead != 0 && c.security > securityLow {
290 return attErrorRsp(attOpReadBlobReq, h, attEcodeAuthentication)
291 }
292 v := a.value
293 if v == nil {
294 req := &ReadRequest{
295 Request: Request{Central: c},
296 Cap: int(c.mtu - 1),
297 Offset: int(offset),
298 }
299 rsp := newResponseWriter(int(c.mtu - 1))
300 if c, ok := a.pvt.(*Characteristic); ok {
301 c.rhandler.ServeRead(rsp, req)
302 } else if d, ok := a.pvt.(*Descriptor); ok {
303 d.rhandler.ServeRead(rsp, req)
304 }
305 v = rsp.bytes()
306 offset = 0 // the server has already adjusted for the offset
307 }
308 w := newL2capWriter(c.mtu)
309 w.WriteByteFit(attOpReadBlobRsp)
310 w.Chunk()
311 w.WriteFit(v)
312 if ok := w.ChunkSeek(offset); !ok {
313 return attErrorRsp(attOpReadBlobReq, h, attEcodeInvalidOffset)
314 }
315 w.CommitFit()
316 return w.Bytes()
317 }
318
319 func (c *central) handleReadByGroup(b []byte) []byte {
320 start, end := readHandleRange(b)
321 t := UUID{b[4:]}
322
323 // Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
324 // More specifically, the "Discover All Primary Services" sub-procedure.
325 if !t.Equal(attrPrimaryServiceUUID) {
326 return attErrorRsp(attOpReadByGroupReq, start, attEcodeUnsuppGrpType)
327 }
328
329 w := newL2capWriter(c.mtu)
330 w.WriteByteFit(attOpReadByGroupRsp)
331 uuidLen := -1
332 for _, a := range c.attrs.Subrange(start, end) {
333 if !a.typ.Equal(attrPrimaryServiceUUID) {
334 continue
335 }
336 if uuidLen == -1 {
337 uuidLen = len(a.value)
338 w.WriteByteFit(byte(uuidLen + 4))
339 }
340 if uuidLen != len(a.value) {
341 break
342 }
343 s := a.pvt.(*Service)
344 w.Chunk()
345 w.WriteUint16Fit(s.h)
346 w.WriteUint16Fit(s.endh)
347 w.WriteFit(a.value)
348 if ok := w.Commit(); !ok {
349 break
350 }
351 }
352 if uuidLen == -1 {
353 return attErrorRsp(attOpReadByGroupReq, start, attEcodeAttrNotFound)
354 }
355 return w.Bytes()
356 }
357
358 func (c *central) handleWrite(reqType byte, b []byte) []byte {
359 h := binary.LittleEndian.Uint16(b[:2])
360 value := b[2:]
361
362 a, ok := c.attrs.At(h)
363 if !ok {
364 return attErrorRsp(reqType, h, attEcodeInvalidHandle)
365 }
366
367 noRsp := reqType == attOpWriteCmd
368 charFlag := CharWrite
369 if noRsp {
370 charFlag = CharWriteNR
371 }
372 if a.props&charFlag == 0 {
373 return attErrorRsp(reqType, h, attEcodeWriteNotPerm)
374 }
375 if a.secure&charFlag == 0 && c.security > securityLow {
376 return attErrorRsp(reqType, h, attEcodeAuthentication)
377 }
378
379 // Props of Service and Characteristic declration are read only.
380 // So we only need deal with writable descriptors here.
381 // (Characteristic's value is implemented with descriptor)
382 if !a.typ.Equal(attrClientCharacteristicConfigUUID) {
383 // Regular write, not CCC
384 r := Request{Central: c}
385 if c, ok := a.pvt.(*Characteristic); ok {
386 c.whandler.ServeWrite(r, value)
387 } else if d, ok := a.pvt.(*Characteristic); ok {
388 d.whandler.ServeWrite(r, value)
389 }
390 if noRsp {
391 return nil
392 } else {
393 return []byte{attOpWriteRsp}
394 }
395 }
396
397 // CCC/descriptor write
398 if len(value) != 2 {
399 return attErrorRsp(reqType, h, attEcodeInvalAttrValueLen)
400 }
401 ccc := binary.LittleEndian.Uint16(value)
402 // char := a.pvt.(*Descriptor).char
403 if ccc&(gattCCCNotifyFlag|gattCCCIndicateFlag) != 0 {
404 c.startNotify(&a, int(c.mtu-3))
405 } else {
406 c.stopNotify(&a)
407 }
408 if noRsp {
409 return nil
410 }
411 return []byte{attOpWriteRsp}
412 }
413
414 func (c *central) sendNotification(a *attr, data []byte) (int, error) {
415 w := newL2capWriter(c.mtu)
416 w.WriteByteFit(attOpHandleNotify)
417 w.WriteUint16Fit(a.pvt.(*Descriptor).char.vh)
418 w.WriteFit(data)
419 return c.l2conn.Write(w.Bytes())
420 }
421
422 func readHandleRange(b []byte) (start, end uint16) {
423 return binary.LittleEndian.Uint16(b), binary.LittleEndian.Uint16(b[2:])
424 }
425
426 func (c *central) startNotify(a *attr, maxlen int) {
427 c.notifiersmu.Lock()
428 defer c.notifiersmu.Unlock()
429 if _, found := c.notifiers[a.h]; found {
430 return
431 }
432 char := a.pvt.(*Descriptor).char
433 n := newNotifier(c, a, maxlen)
434 c.notifiers[a.h] = n
435 go char.nhandler.ServeNotify(Request{Central: c}, n)
436 }
437
438 func (c *central) stopNotify(a *attr) {
439 c.notifiersmu.Lock()
440 defer c.notifiersmu.Unlock()
441 // char := a.pvt.(*Characteristic)
442 if n, found := c.notifiers[a.h]; found {
443 n.stop()
444 delete(c.notifiers, a.h)
445 }
446 }