1 /*        $NetBSD: sdp.c,v 1.12 2021/12/12 22:20:52 andvar Exp $      */
2 
3 /*-
4  * Copyright (c) 2006 Itronix Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of Itronix Inc. may not be used to endorse
16  *    or promote products derived from this software without specific
17  *    prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 /*
32  * Copyright (c) 2009 The NetBSD Foundation, Inc.
33  * Copyright (c) 2004 Maksim Yevmenkin <m_evmenkin@yahoo.com>
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 #include <sys/cdefs.h>
59 __RCSID("$NetBSD: sdp.c,v 1.12 2021/12/12 22:20:52 andvar Exp $");
60 
61 #include <sys/types.h>
62 
63 #include <dev/bluetooth/btdev.h>
64 #include <dev/bluetooth/bthidev.h>
65 #include <dev/bluetooth/btsco.h>
66 #include <dev/usb/usb.h>
67 #include <dev/usb/usbhid.h>
68 #include <dev/hid/hid.h>
69 
70 #include <prop/proplib.h>
71 
72 #include <bluetooth.h>
73 #include <err.h>
74 #include <errno.h>
75 #include <sdp.h>
76 #include <stdlib.h>
77 #include <strings.h>
78 #include <usbhid.h>
79 
80 #include "btdevctl.h"
81 
82 static bool parse_hid_descriptor(sdp_data_t *);
83 static int32_t parse_boolean(sdp_data_t *);
84 static int32_t parse_pdl_param(sdp_data_t *, uint16_t);
85 static int32_t parse_pdl(sdp_data_t *, uint16_t);
86 static int32_t parse_apdl(sdp_data_t *, uint16_t);
87 
88 static int config_pnp(prop_dictionary_t, sdp_data_t *);
89 static int config_hid(prop_dictionary_t, sdp_data_t *);
90 static int config_hset(prop_dictionary_t, sdp_data_t *);
91 static int config_hf(prop_dictionary_t, sdp_data_t *);
92 
93 uint16_t pnp_services[] = {
94           SDP_SERVICE_CLASS_PNP_INFORMATION,
95 };
96 
97 uint16_t hid_services[] = {
98           SDP_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE,
99 };
100 
101 uint16_t hset_services[] = {
102           SDP_SERVICE_CLASS_HEADSET,
103 };
104 
105 uint16_t hf_services[] = {
106           SDP_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY,
107 };
108 
109 static struct {
110           const char                    *name;
111           int                           (*handler)(prop_dictionary_t, sdp_data_t *);
112           const char                    *description;
113           uint16_t            *services;
114           size_t                        nservices;
115 } cfgtype[] = {
116     {
117           "HID",              config_hid,         "Human Interface Device",
118           hid_services,       __arraycount(hid_services),
119     },
120     {
121           "HSET",             config_hset,        "Headset",
122           hset_services,      __arraycount(hset_services),
123     },
124     {
125           "HF",               config_hf,          "Handsfree",
126           hf_services,        __arraycount(hf_services),
127     },
128 };
129 
130 #define MAX_SSP               (2 + 1 * 3)         /* largest nservices is 1 */
131 
132 static bool
cfg_ssa(sdp_session_t ss,uint16_t * services,size_t nservices,sdp_data_t * rsp)133 cfg_ssa(sdp_session_t ss, uint16_t *services, size_t nservices, sdp_data_t *rsp)
134 {
135           uint8_t buf[MAX_SSP];
136           sdp_data_t ssp;
137           size_t i;
138 
139           ssp.next = buf;
140           ssp.end = buf + sizeof(buf);
141 
142           for (i = 0; i < nservices; i++)
143                     sdp_put_uuid16(&ssp, services[i]);
144 
145           ssp.end = ssp.next;
146           ssp.next = buf;
147 
148           return sdp_service_search_attribute(ss, &ssp, NULL, rsp);
149 }
150 
151 static bool
cfg_search(sdp_session_t ss,int i,prop_dictionary_t dict)152 cfg_search(sdp_session_t ss, int i, prop_dictionary_t dict)
153 {
154           sdp_data_t rsp, rec;
155 
156           /* check PnP Information first */
157           if (!cfg_ssa(ss, pnp_services, __arraycount(pnp_services), &rsp))
158                     return false;
159 
160           while (sdp_get_seq(&rsp, &rec)) {
161                     if (config_pnp(dict, &rec) == 0)
162                               break;
163           }
164 
165           /* then requested service */
166           if (!cfg_ssa(ss, cfgtype[i].services, cfgtype[i].nservices, &rsp))
167                     return false;
168 
169           while (sdp_get_seq(&rsp, &rec)) {
170                     errno = (*cfgtype[i].handler)(dict, &rec);
171                     if (errno == 0)
172                               return true;
173           }
174 
175           return false;
176 }
177 
178 prop_dictionary_t
cfg_query(bdaddr_t * laddr,bdaddr_t * raddr,const char * service)179 cfg_query(bdaddr_t *laddr, bdaddr_t *raddr, const char *service)
180 {
181           prop_dictionary_t dict;
182           sdp_session_t ss;
183           size_t i;
184 
185           dict = prop_dictionary_create();
186           if (dict == NULL)
187                     err(EXIT_FAILURE, "prop_dictionary_create()");
188 
189           for (i = 0; i < __arraycount(cfgtype); i++) {
190                     if (strcasecmp(service, cfgtype[i].name) == 0) {
191                               ss = sdp_open(laddr, raddr);
192                               if (ss == NULL)
193                                         err(EXIT_FAILURE, "SDP connection failed");
194 
195                               if (!cfg_search(ss, i, dict))
196                                         errx(EXIT_FAILURE, "service %s not found", service);
197 
198                               sdp_close(ss);
199                               return dict;
200                     }
201           }
202 
203           printf("Known config types:\n");
204           for (i = 0; i < __arraycount(cfgtype); i++)
205                     printf("\t%s\t%s\n", cfgtype[i].name, cfgtype[i].description);
206 
207           exit(EXIT_FAILURE);
208 }
209 
210 /*
211  * Configure PnP Information results
212  */
213 static int
config_pnp(prop_dictionary_t dict,sdp_data_t * rec)214 config_pnp(prop_dictionary_t dict, sdp_data_t *rec)
215 {
216           sdp_data_t value;
217           uintmax_t v;
218           uint16_t attr;
219           int vendor, product, source;
220 
221           vendor = -1;
222           product = -1;
223           source = -1;
224 
225           while (sdp_get_attr(rec, &attr, &value)) {
226                     switch (attr) {
227                     case 0x0201:        /* Vendor ID */
228                               if (sdp_get_uint(&value, &v)
229                                   && v <= UINT16_MAX)
230                                         vendor = (int)v;
231 
232                               break;
233 
234                     case 0x0202:        /* Product ID */
235                               if (sdp_get_uint(&value, &v)
236                                   && v <= UINT16_MAX)
237                                         product = (int)v;
238 
239                               break;
240 
241                     case 0x0205:        /* Vendor ID Source */
242                               if (sdp_get_uint(&value, &v)
243                                   && v <= UINT16_MAX)
244                                         source = (int)v;
245 
246                               break;
247 
248                     default:
249                               break;
250                     }
251           }
252 
253           if (vendor == -1 || product == -1)
254                     return ENOATTR;
255 
256           if (source != 0x0002)         /* "USB Implementers Forum" */
257                     return ENOATTR;
258 
259           if (!prop_dictionary_set_uint16(dict, BTDEVvendor, (uint16_t)vendor))
260                     return errno;
261 
262           if (!prop_dictionary_set_uint16(dict, BTDEVproduct, (uint16_t)product))
263                     return errno;
264 
265           return 0;
266 }
267 
268 /*
269  * Configure HID results
270  */
271 static int
config_hid(prop_dictionary_t dict,sdp_data_t * rec)272 config_hid(prop_dictionary_t dict, sdp_data_t *rec)
273 {
274           prop_object_t obj;
275           int32_t control_psm, interrupt_psm,
276                     reconnect_initiate, hid_length;
277           uint8_t *hid_descriptor;
278           sdp_data_t value;
279           const char *mode;
280           uint16_t attr;
281 
282           control_psm = -1;
283           interrupt_psm = -1;
284           reconnect_initiate = -1;
285           hid_descriptor = NULL;
286           hid_length = -1;
287 
288           while (sdp_get_attr(rec, &attr, &value)) {
289                     switch (attr) {
290                     case SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST:
291                               control_psm = parse_pdl(&value, SDP_UUID_PROTOCOL_L2CAP);
292                               break;
293 
294                     case SDP_ATTR_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS:
295                               interrupt_psm = parse_apdl(&value, SDP_UUID_PROTOCOL_L2CAP);
296                               break;
297 
298                     case 0x0205: /* HIDReconnectInitiate */
299                               reconnect_initiate = parse_boolean(&value);
300                               break;
301 
302                     case 0x0206: /* HIDDescriptorList */
303                               if (parse_hid_descriptor(&value)) {
304                                         hid_descriptor = value.next;
305                                         hid_length = value.end - value.next;
306                               }
307                               break;
308 
309                     default:
310                               break;
311                     }
312           }
313 
314           if (control_psm == -1
315               || interrupt_psm == -1
316               || reconnect_initiate == -1
317               || hid_descriptor == NULL
318               || hid_length == -1)
319                     return ENOATTR;
320 
321           if (!prop_dictionary_set_string_nocopy(dict, BTDEVtype, "bthidev"))
322                     return errno;
323 
324           if (!prop_dictionary_set_int32(dict, BTHIDEVcontrolpsm, control_psm) ||
325               !prop_dictionary_set_int32(dict, BTHIDEVinterruptpsm,
326                                                interrupt_psm))
327                     return errno;
328 
329           obj = prop_data_create_copy(hid_descriptor, hid_length);
330           if (obj == NULL || !prop_dictionary_set(dict, BTHIDEVdescriptor, obj))
331                     return errno;
332 
333           mode = hid_mode(obj);
334           prop_object_release(obj);
335 
336           if (!prop_dictionary_set_string_nocopy(dict, BTDEVmode, mode))
337                     return errno;
338 
339           if (!reconnect_initiate) {
340                     if (!prop_dictionary_set_bool(dict, BTHIDEVreconnect, true))
341                               return errno;
342           }
343 
344           return 0;
345 }
346 
347 /*
348  * Configure HSET results
349  */
350 static int
config_hset(prop_dictionary_t dict,sdp_data_t * rec)351 config_hset(prop_dictionary_t dict, sdp_data_t *rec)
352 {
353           sdp_data_t value;
354           int32_t channel;
355           uint16_t attr;
356 
357           channel = -1;
358 
359           while (sdp_get_attr(rec, &attr, &value)) {
360                     switch (attr) {
361                     case SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST:
362                               channel = parse_pdl(&value, SDP_UUID_PROTOCOL_RFCOMM);
363                               break;
364 
365                     default:
366                               break;
367                     }
368           }
369 
370           if (channel == -1)
371                     return ENOATTR;
372 
373           if (!prop_dictionary_set_string_nocopy(dict, BTDEVtype, "btsco"))
374                     return errno;
375 
376           if (!prop_dictionary_set_int32(dict, BTSCOchannel, channel))
377                     return errno;
378 
379           return 0;
380 }
381 
382 /*
383  * Configure HF results
384  */
385 static int
config_hf(prop_dictionary_t dict,sdp_data_t * rec)386 config_hf(prop_dictionary_t dict, sdp_data_t *rec)
387 {
388           sdp_data_t value;
389           int32_t channel;
390           uint16_t attr;
391 
392           channel = -1;
393 
394           while (sdp_get_attr(rec, &attr, &value)) {
395                     switch (attr) {
396                     case SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST:
397                               channel = parse_pdl(&value, SDP_UUID_PROTOCOL_RFCOMM);
398                               break;
399 
400                     default:
401                               break;
402                     }
403           }
404 
405           if (channel == -1)
406                     return ENOATTR;
407 
408           if (!prop_dictionary_set_string_nocopy(dict, BTDEVtype, "btsco"))
409                     return errno;
410 
411           if (!prop_dictionary_set_bool(dict, BTSCOlisten, true))
412                     return errno;
413 
414           if (!prop_dictionary_set_int32(dict, BTSCOchannel, channel))
415                     return errno;
416 
417           return 0;
418 }
419 
420 /*
421  * Parse HIDDescriptorList . This is a sequence of HIDDescriptors, of which
422  * each is a data element sequence containing, minimally, a ClassDescriptorType
423  * and ClassDescriptorData containing a byte array of data. Any extra elements
424  * should be ignored.
425  *
426  * If a ClassDescriptorType "Report" is found, set SDP data value to the
427  * ClassDescriptorData content and return true. Note that we don't need to
428  * extract the actual length as the SDP data is guaranteed valid.
429  */
430 
431 static bool
parse_hid_descriptor(sdp_data_t * value)432 parse_hid_descriptor(sdp_data_t *value)
433 {
434           sdp_data_t list, desc;
435           uintmax_t type;
436           char *str;
437           size_t len;
438 
439           if (!sdp_get_seq(value, &list))
440                     return false;
441 
442           while (sdp_get_seq(&list, &desc)) {
443                     if (sdp_get_uint(&desc, &type)
444                         && type == UDESC_REPORT
445                         && sdp_get_str(&desc, &str, &len)) {
446                               value->next = (uint8_t *)str;
447                               value->end = (uint8_t *)(str + len);
448                               return true;
449                     }
450           }
451 
452           return false;
453 }
454 
455 static int32_t
parse_boolean(sdp_data_t * value)456 parse_boolean(sdp_data_t *value)
457 {
458           bool bv;
459 
460           if (!sdp_get_bool(value, &bv))
461                     return -1;
462 
463           return bv;
464 }
465 
466 /*
467  * The ProtocolDescriptorList attribute describes one or
468  * more protocol stacks that may be used to gain access to
469  * the service described by the service record.
470  *
471  * If the ProtocolDescriptorList describes a single stack,
472  * the attribute value takes the form of a data element
473  * sequence in which each element of the sequence is a
474  * protocol descriptor.
475  *
476  *        seq
477  *          <list>
478  *
479  * If it is possible for more than one kind of protocol
480  * stack to be used to gain access to the service, the
481  * ProtocolDescriptorList takes the form of a data element
482  * alternative where each member is a data element sequence
483  * consisting of a list of sequences describing each protocol
484  *
485  *        alt
486  *          seq
487  *            <list>
488  *          seq
489  *            <list>
490  *
491  * Each ProtocolDescriptorList is a list containing a sequence for
492  * each protocol, where each sequence contains the protocol UUUID
493  * and any protocol specific parameters.
494  *
495  *        seq
496  *          uuid              L2CAP
497  *          uint16  psm
498  *        seq
499  *          uuid              RFCOMM
500  *          uint8             channel
501  *
502  * We want to extract the ProtocolSpecificParameter#1 for the
503  * given protocol, which will be an unsigned int.
504  */
505 static int32_t
parse_pdl_param(sdp_data_t * pdl,uint16_t proto)506 parse_pdl_param(sdp_data_t *pdl, uint16_t proto)
507 {
508           sdp_data_t seq;
509           uintmax_t param;
510 
511           while (sdp_get_seq(pdl, &seq)) {
512                     if (!sdp_match_uuid16(&seq, proto))
513                               continue;
514 
515                     if (sdp_get_uint(&seq, &param))
516                               return param;
517 
518                     break;
519           }
520 
521           return -1;
522 }
523 
524 static int32_t
parse_pdl(sdp_data_t * value,uint16_t proto)525 parse_pdl(sdp_data_t *value, uint16_t proto)
526 {
527           sdp_data_t seq;
528           int32_t param = -1;
529 
530           sdp_get_alt(value, value);    /* strip any alt header */
531 
532           while (param == -1 && sdp_get_seq(value, &seq))
533                     param = parse_pdl_param(&seq, proto);
534 
535           return param;
536 }
537 
538 /*
539  * Parse AdditionalProtocolDescriptorList
540  */
541 static int32_t
parse_apdl(sdp_data_t * value,uint16_t proto)542 parse_apdl(sdp_data_t *value, uint16_t proto)
543 {
544           sdp_data_t seq;
545           int32_t param = -1;
546 
547           sdp_get_seq(value, value);    /* strip seq header */
548 
549           while (param == -1 && sdp_get_seq(value, &seq))
550                     param = parse_pdl_param(&seq, proto);
551 
552           return param;
553 }
554 
555 /*
556  * return appropriate mode for HID descriptor
557  */
558 const char *
hid_mode(prop_data_t desc)559 hid_mode(prop_data_t desc)
560 {
561           report_desc_t r;
562           hid_data_t d;
563           struct hid_item h;
564           const char *mode;
565 
566           hid_init(NULL);
567 
568           mode = BTDEVauth;   /* default */
569 
570           r = hid_use_report_desc(prop_data_value(desc),
571                                         prop_data_size(desc));
572           if (r == NULL)
573                     err(EXIT_FAILURE, "hid_use_report_desc");
574 
575           d = hid_start_parse(r, ~0, -1);
576           while (hid_get_item(d, &h) > 0) {
577                     if (h.kind == hid_collection
578                         && HID_PAGE(h.usage) == HUP_GENERIC_DESKTOP
579                         && HID_USAGE(h.usage) == HUG_KEYBOARD)
580                               mode = BTDEVencrypt;
581           }
582 
583           hid_end_parse(d);
584           hid_dispose_report_desc(r);
585 
586           return mode;
587 }
588