Home | History | Annotate | Line # | Download | only in rfcomm_sppd
rfcomm_sppd.c revision 1.11
      1 /*	$NetBSD: rfcomm_sppd.c,v 1.11 2009/05/21 14:44:01 plunky 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) 2007 Iain Hibbert
     34  * Copyright (c) 2003 Maksim Yevmenkin <m_evmenkin (at) yahoo.com>
     35  * All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  *
     46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     49  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     56  * SUCH DAMAGE.
     57  */
     58 
     59 #include <sys/cdefs.h>
     60 __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc.\
     61   Copyright (c) 2007 Iain Hibbert.\
     62   Copyright (c) 2006 Itronix, Inc.\
     63   Copyright (c) 2003 Maksim Yevmenkin m_evmenkin (at) yahoo.com.\
     64   All rights reserved.");
     65 __RCSID("$NetBSD: rfcomm_sppd.c,v 1.11 2009/05/21 14:44:01 plunky Exp $");
     66 
     67 #include <sys/param.h>
     68 
     69 #include <bluetooth.h>
     70 #include <ctype.h>
     71 #include <err.h>
     72 #include <errno.h>
     73 #include <fcntl.h>
     74 #include <grp.h>
     75 #include <limits.h>
     76 #include <paths.h>
     77 #include <sdp.h>
     78 #include <signal.h>
     79 #include <stdarg.h>
     80 #include <stdio.h>
     81 #include <stdlib.h>
     82 #include <string.h>
     83 #include <syslog.h>
     84 #include <termios.h>
     85 #include <unistd.h>
     86 
     87 #include <netbt/rfcomm.h>
     88 
     89 int open_tty(const char *);
     90 int open_client(bdaddr_t *, bdaddr_t *, int, const char *);
     91 int open_server(bdaddr_t *, uint8_t, int, const char *);
     92 void copy_data(int, int);
     93 int channel_lookup(const bdaddr_t *, const bdaddr_t *, uint16_t, uintmax_t *);
     94 void sighandler(int);
     95 void usage(void);
     96 void reset_tio(void);
     97 
     98 int done;		/* got a signal */
     99 struct termios tio;	/* stored termios for reset on exit */
    100 
    101 struct service {
    102 	const char *	name;
    103 	const char *	description;
    104 	uint16_t	class;
    105 } services[] = {
    106 	{ "DUN",	"Dialup Networking",
    107 	    SDP_SERVICE_CLASS_DIALUP_NETWORKING		},
    108 	{ "LAN",	"LAN access using PPP",
    109 	    SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP	},
    110 	{ "SP",		"Serial Port",
    111 	    SDP_SERVICE_CLASS_SERIAL_PORT		},
    112 	{ NULL,		NULL,		0		}
    113 };
    114 
    115 int
    116 main(int argc, char *argv[])
    117 {
    118 	struct termios		t;
    119 	bdaddr_t		laddr, raddr;
    120 	fd_set			rdset;
    121 	const char		*service;
    122 	char			*ep, *tty;
    123 	int			lm, n, rfcomm, tty_in, tty_out;
    124 	uint8_t			channel;
    125 
    126 	bdaddr_copy(&laddr, BDADDR_ANY);
    127 	bdaddr_copy(&raddr, BDADDR_ANY);
    128 	service = "SP";
    129 	tty = NULL;
    130 	channel = 0;
    131 	lm = 0;
    132 
    133 	/* Parse command line options */
    134 	while ((n = getopt(argc, argv, "a:c:d:hm:s:t:")) != -1) {
    135 		switch (n) {
    136 		case 'a': /* remote device address */
    137 			if (!bt_aton(optarg, &raddr)) {
    138 				struct hostent	*he = NULL;
    139 
    140 				if ((he = bt_gethostbyname(optarg)) == NULL)
    141 					errx(EXIT_FAILURE, "%s: %s", optarg,
    142 					    hstrerror(h_errno));
    143 
    144 				bdaddr_copy(&raddr, (bdaddr_t *)he->h_addr);
    145 			}
    146 			break;
    147 
    148 		case 'c': /* RFCOMM channel */
    149 			channel = strtoul(optarg, &ep, 10);
    150 			if (*ep != '\0' || channel < 1 || channel > 30)
    151 				errx(EXIT_FAILURE, "Invalid channel: %s", optarg);
    152 
    153 			break;
    154 
    155 		case 'd': /* local device address */
    156 			if (!bt_devaddr(optarg, &laddr))
    157 				err(EXIT_FAILURE, "%s", optarg);
    158 
    159 			break;
    160 
    161 		case 'm': /* Link Mode */
    162 			if (strcasecmp(optarg, "auth") == 0)
    163 				lm = RFCOMM_LM_AUTH;
    164 			else if (strcasecmp(optarg, "encrypt") == 0)
    165 				lm = RFCOMM_LM_ENCRYPT;
    166 			else if (strcasecmp(optarg, "secure") == 0)
    167 				lm = RFCOMM_LM_SECURE;
    168 			else
    169 				errx(EXIT_FAILURE, "%s: unknown mode", optarg);
    170 
    171 			break;
    172 
    173 		case 's': /* service class */
    174 			service = optarg;
    175 			break;
    176 
    177 		case 't': /* Slave TTY name */
    178 			if (optarg[0] != '/')
    179 				asprintf(&tty, "%s%s", _PATH_DEV, optarg);
    180 			else
    181 				tty = optarg;
    182 
    183 			break;
    184 
    185 		case 'h':
    186 		default:
    187 			usage();
    188 			/* NOT REACHED */
    189 		}
    190 	}
    191 
    192 	/*
    193 	 * validate options:
    194 	 *	must have channel or remote address but not both
    195 	 */
    196 	if ((channel == 0 && bdaddr_any(&raddr))
    197 	    || (channel != 0 && !bdaddr_any(&raddr)))
    198 		usage();
    199 
    200 	/*
    201 	 * grab ttys before we start the bluetooth
    202 	 */
    203 	if (tty == NULL) {
    204 		tty_in = STDIN_FILENO;
    205 		tty_out = STDOUT_FILENO;
    206 	} else {
    207 		tty_in = open_tty(tty);
    208 		tty_out = tty_in;
    209 	}
    210 
    211 	/* open RFCOMM */
    212 	if (channel == 0)
    213 		rfcomm = open_client(&laddr, &raddr, lm, service);
    214 	else
    215 		rfcomm = open_server(&laddr, channel, lm, service);
    216 
    217 	/*
    218 	 * now we are ready to go, so either detach or maybe turn
    219 	 * off some input processing, so that rfcomm_sppd can
    220 	 * be used directly with stdio
    221 	 */
    222 	if (tty == NULL) {
    223 		if (tcgetattr(tty_in, &t) < 0)
    224 			err(EXIT_FAILURE, "tcgetattr");
    225 
    226 		memcpy(&tio, &t, sizeof(tio));
    227 		t.c_lflag &= ~(ECHO | ICANON);
    228 		t.c_iflag &= ~(ICRNL);
    229 
    230 		if (memcmp(&tio, &t, sizeof(tio))) {
    231 			if (tcsetattr(tty_in, TCSANOW, &t) < 0)
    232 				err(EXIT_FAILURE, "tcsetattr");
    233 
    234 			atexit(reset_tio);
    235 		}
    236 	} else {
    237 		if (daemon(0, 0) < 0)
    238 			err(EXIT_FAILURE, "daemon() failed");
    239 	}
    240 
    241 	/* catch signals */
    242 	done = 0;
    243 	(void)signal(SIGHUP, sighandler);
    244 	(void)signal(SIGINT, sighandler);
    245 	(void)signal(SIGPIPE, sighandler);
    246 	(void)signal(SIGTERM, sighandler);
    247 
    248 	openlog(getprogname(), LOG_PERROR | LOG_PID, LOG_DAEMON);
    249 	syslog(LOG_INFO, "Starting on %s...", (tty ? tty : "stdio"));
    250 
    251 	n = MAX(tty_in, rfcomm) + 1;
    252 	while (!done) {
    253 		FD_ZERO(&rdset);
    254 		FD_SET(tty_in, &rdset);
    255 		FD_SET(rfcomm, &rdset);
    256 
    257 		if (select(n, &rdset, NULL, NULL, NULL) < 0) {
    258 			if (errno == EINTR)
    259 				continue;
    260 
    261 			syslog(LOG_ERR, "select error: %m");
    262 			exit(EXIT_FAILURE);
    263 		}
    264 
    265 		if (FD_ISSET(tty_in, &rdset))
    266 			copy_data(tty_in, rfcomm);
    267 
    268 		if (FD_ISSET(rfcomm, &rdset))
    269 			copy_data(rfcomm, tty_out);
    270 	}
    271 
    272 	syslog(LOG_INFO, "Completed on %s", (tty ? tty : "stdio"));
    273 	exit(EXIT_SUCCESS);
    274 }
    275 
    276 int
    277 open_tty(const char *tty)
    278 {
    279 	char		 pty[PATH_MAX], *slash;
    280 	struct group	*gr = NULL;
    281 	gid_t		 ttygid;
    282 	int		 master;
    283 
    284 	/*
    285 	 * Construct master PTY name. The slave tty name must be less then
    286 	 * PATH_MAX characters in length, must contain '/' character and
    287 	 * must not end with '/'.
    288 	 */
    289 	if (strlen(tty) >= sizeof(pty))
    290 		errx(EXIT_FAILURE, ": tty name too long");
    291 
    292 	strlcpy(pty, tty, sizeof(pty));
    293 	slash = strrchr(pty, '/');
    294 	if (slash == NULL || slash[1] == '\0')
    295 		errx(EXIT_FAILURE, "%s: invalid tty", tty);
    296 
    297 	slash[1] = 'p';
    298 	if (strcmp(pty, tty) == 0)
    299 		errx(EXIT_FAILURE, "Master and slave tty are the same (%s)", tty);
    300 
    301 	if ((master = open(pty, O_RDWR, 0)) < 0)
    302 		err(EXIT_FAILURE, "%s", pty);
    303 
    304 	/*
    305 	 * Slave TTY
    306 	 */
    307 
    308 	if ((gr = getgrnam("tty")) != NULL)
    309 		ttygid = gr->gr_gid;
    310 	else
    311 		ttygid = (gid_t)-1;
    312 
    313 	(void)chown(tty, getuid(), ttygid);
    314 	(void)chmod(tty, S_IRUSR | S_IWUSR | S_IWGRP);
    315 	(void)revoke(tty);
    316 
    317 	return master;
    318 }
    319 
    320 int
    321 open_client(bdaddr_t *laddr, bdaddr_t *raddr, int lm, const char *service)
    322 {
    323 	struct sockaddr_bt sa;
    324 	struct service *s;
    325 	struct linger l;
    326 	char *ep;
    327 	int fd, error;
    328 	uintmax_t channel;
    329 
    330 	for (s = services ; ; s++) {
    331 		if (s->name == NULL) {
    332 			channel = strtoul(service, &ep, 10);
    333 			if (*ep != '\0')
    334 				errx(EXIT_FAILURE, "Unknown service: %s", service);
    335 
    336 			break;
    337 		}
    338 
    339 		if (strcasecmp(s->name, service) == 0) {
    340 			error = channel_lookup(laddr, raddr, s->class, &channel);
    341 			if (error != 0)
    342 				errx(EXIT_FAILURE, "%s: %s", s->name, strerror(error));
    343 
    344 			break;
    345 		}
    346 	}
    347 
    348 	if (channel < RFCOMM_CHANNEL_MIN || channel > RFCOMM_CHANNEL_MAX)
    349 		errx(EXIT_FAILURE, "Invalid channel %"PRIuMAX, channel);
    350 
    351 	memset(&sa, 0, sizeof(sa));
    352 	sa.bt_len = sizeof(sa);
    353 	sa.bt_family = AF_BLUETOOTH;
    354 	bdaddr_copy(&sa.bt_bdaddr, laddr);
    355 
    356 	fd = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    357 	if (fd < 0)
    358 		err(EXIT_FAILURE, "socket()");
    359 
    360 	if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
    361 		err(EXIT_FAILURE, "bind(%s)", bt_ntoa(laddr, NULL));
    362 
    363 	memset(&l, 0, sizeof(l));
    364 	l.l_onoff = 1;
    365 	l.l_linger = 5;
    366 	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0)
    367 		err(EXIT_FAILURE, "linger()");
    368 
    369 	if (setsockopt(fd, BTPROTO_RFCOMM, SO_RFCOMM_LM, &lm, sizeof(lm)) < 0)
    370 		err(EXIT_FAILURE, "link mode");
    371 
    372 	sa.bt_channel = channel;
    373 	bdaddr_copy(&sa.bt_bdaddr, raddr);
    374 
    375 	if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
    376 		err(EXIT_FAILURE, "connect(%s, %"PRIuMAX")", bt_ntoa(raddr, NULL),
    377 						     channel);
    378 
    379 	return fd;
    380 }
    381 
    382 int
    383 open_server(bdaddr_t *laddr, uint8_t channel, int lm, const char *service)
    384 {
    385 	uint8_t	buffer[256];
    386 	struct sockaddr_bt sa;
    387 	struct service *s;
    388 	struct linger l;
    389 	socklen_t len;
    390 	sdp_session_t ss;
    391 	sdp_data_t rec;
    392 	int sv, fd;
    393 
    394 	for (s = services; ; s++) {
    395 		if (s->name == NULL)
    396 			usage();
    397 
    398 		if (strcasecmp(s->name, service) == 0)
    399 			break;
    400 	}
    401 
    402 	/* Open server socket */
    403 	sv = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    404 	if (sv < 0)
    405 		err(EXIT_FAILURE, "socket()");
    406 
    407 	memset(&sa, 0, sizeof(sa));
    408 	sa.bt_len = sizeof(sa);
    409 	sa.bt_family = AF_BLUETOOTH;
    410 	sa.bt_channel = channel;
    411 	bdaddr_copy(&sa.bt_bdaddr, laddr);
    412 	if (bind(sv, (struct sockaddr *)&sa, sizeof(sa)) < 0)
    413 		err(EXIT_FAILURE, "bind(%s, %d)", bt_ntoa(laddr, NULL),
    414 						  channel);
    415 
    416 	if (setsockopt(sv, BTPROTO_RFCOMM, SO_RFCOMM_LM, &lm, sizeof(lm)) < 0)
    417 		err(EXIT_FAILURE, "link mode");
    418 
    419 	if (listen(sv, 1) < 0)
    420 		err(EXIT_FAILURE, "listen()");
    421 
    422 	/* Build SDP record */
    423 	rec.next = buffer;
    424 	rec.end = buffer + sizeof(buffer);
    425 
    426 	sdp_put_uint16(&rec, SDP_ATTR_SERVICE_RECORD_HANDLE);
    427 	sdp_put_uint32(&rec, 0x00000000);
    428 
    429 	sdp_put_uint16(&rec, SDP_ATTR_SERVICE_CLASS_ID_LIST);
    430 	sdp_put_seq(&rec, 3);
    431 	sdp_put_uuid16(&rec, s->class);
    432 
    433 	sdp_put_uint16(&rec, SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST);
    434 	sdp_put_seq(&rec, 12);
    435 	sdp_put_seq(&rec, 3);
    436 	sdp_put_uuid16(&rec, SDP_UUID_PROTOCOL_L2CAP);
    437 	sdp_put_seq(&rec, 5);
    438 	sdp_put_uuid16(&rec, SDP_UUID_PROTOCOL_RFCOMM);
    439 	sdp_put_uint8(&rec, channel);
    440 
    441 	sdp_put_uint16(&rec, SDP_ATTR_BROWSE_GROUP_LIST);
    442 	sdp_put_seq(&rec, 3);
    443 	sdp_put_uuid16(&rec, SDP_SERVICE_CLASS_PUBLIC_BROWSE_GROUP);
    444 
    445 	sdp_put_uint16(&rec, SDP_ATTR_LANGUAGE_BASE_ATTRIBUTE_ID_LIST);
    446 	sdp_put_seq(&rec, 9);
    447 	sdp_put_uint16(&rec, 0x656e);	/* "en" */
    448 	sdp_put_uint16(&rec, 106);	/* UTF-8 */
    449 	sdp_put_uint16(&rec, SDP_ATTR_PRIMARY_LANGUAGE_BASE_ID);
    450 
    451 	if (s->class == SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP) {
    452 		sdp_put_uint16(&rec, SDP_ATTR_SERVICE_AVAILABILITY);
    453 		sdp_put_uint8(&rec, 0x00);
    454 	}
    455 
    456 	sdp_put_uint16(&rec, SDP_ATTR_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
    457 	sdp_put_seq(&rec, 8);
    458 	sdp_put_seq(&rec, 6);
    459 	sdp_put_uuid16(&rec, s->class);
    460 	sdp_put_uint16(&rec, 0x0100);	/* v1.0 */
    461 
    462 	sdp_put_uint16(&rec, SDP_ATTR_PRIMARY_LANGUAGE_BASE_ID
    463 	    + SDP_ATTR_SERVICE_NAME_OFFSET);
    464 	sdp_put_str(&rec, s->description, -1);
    465 
    466 	if (s->class == SDP_SERVICE_CLASS_DIALUP_NETWORKING) {
    467 		sdp_put_uint16(&rec, SDP_ATTR_AUDIO_FEEDBACK_SUPPORT);
    468 		sdp_put_bool(&rec, false);
    469 	}
    470 
    471 #if 0
    472 	if (s->class == SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP) {
    473 		sdp_put_uint16(&rec, SDP_ATTR_IP_SUBNET);	/* TODO */
    474 		sdp_put_str(&rec, "0.0.0.0/0", -1);
    475 	}
    476 #endif
    477 
    478 	rec.end = rec.next;
    479 	rec.next = buffer;
    480 
    481 	/* Register service with SDP server */
    482 	ss = sdp_open_local(NULL);
    483 	if (ss == NULL)
    484 		err(EXIT_FAILURE, "sdp_open_local");
    485 
    486 	if (!sdp_record_insert(ss, laddr, NULL, &rec))
    487 		err(EXIT_FAILURE, "sdp_record_insert");
    488 
    489 	/* Accept client connection */
    490 	len = sizeof(sa);
    491 	fd = accept(sv, (struct sockaddr *)&sa, &len);
    492 	if (fd < 0)
    493 		err(EXIT_FAILURE, "accept");
    494 
    495 	memset(&l, 0, sizeof(l));
    496 	l.l_onoff = 1;
    497 	l.l_linger = 5;
    498 	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0)
    499 		err(EXIT_FAILURE, "linger()");
    500 
    501 	close(sv);
    502 	return fd;
    503 }
    504 
    505 void
    506 copy_data(int src, int dst)
    507 {
    508 	static char	buf[BUFSIZ];
    509 	ssize_t		nr, nw, off;
    510 
    511 	while ((nr = read(src, buf, sizeof(buf))) == -1) {
    512 		if (errno != EINTR) {
    513 			syslog(LOG_ERR, "read failed: %m");
    514 			exit(EXIT_FAILURE);
    515 		}
    516 	}
    517 
    518 	if (nr == 0)	/* reached EOF */
    519 		done++;
    520 
    521 	for (off = 0 ; nr ; nr -= nw, off += nw) {
    522 		if ((nw = write(dst, buf + off, (size_t)nr)) == -1) {
    523 			syslog(LOG_ERR, "write failed: %m");
    524 			exit(EXIT_FAILURE);
    525 		}
    526 	}
    527 }
    528 
    529 int
    530 channel_lookup(bdaddr_t const *laddr, bdaddr_t const *raddr,
    531     uint16_t class, uintmax_t *channel)
    532 {
    533 	uint8_t		buffer[6];	/* SSP (3 bytes) + AIL (3 bytes) */
    534 	sdp_session_t	ss;
    535 	sdp_data_t	ail, ssp, rsp, rec, value, pdl, seq;
    536 	uint16_t	attr;
    537 	bool		rv;
    538 
    539 	seq.next = buffer;
    540 	seq.end = buffer + sizeof(buffer);
    541 
    542 	/*
    543 	 * build ServiceSearchPattern (3 bytes)
    544 	 */
    545 	ssp.next = seq.next;
    546 	sdp_put_uuid16(&seq, class);
    547 	ssp.end = seq.next;
    548 
    549 	/*
    550 	 * build AttributeIDList (3 bytes)
    551 	 */
    552 	ail.next = seq.next;
    553 	sdp_put_uint16(&seq, SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST);
    554 	ail.end = seq.next;
    555 
    556 	ss = sdp_open(laddr, raddr);
    557 	if (ss == NULL)
    558 		return errno;
    559 
    560 	rv = sdp_service_search_attribute(ss, &ssp, &ail, &rsp);
    561 	if (!rv) {
    562 		sdp_close(ss);
    563 		return errno;
    564 	}
    565 
    566 	/*
    567 	 * The response will be a list of records that matched our
    568 	 * ServiceSearchPattern, where each record is a sequence
    569 	 * containing a single ProtocolDescriptorList attribute and
    570 	 * value
    571 	 *
    572 	 *	seq
    573 	 *	  uint16	ProtocolDescriptorList
    574 	 *	  value
    575 	 *	seq
    576 	 *	  uint16	ProtocolDescriptorList
    577 	 *	  value
    578 	 *
    579 	 * If the ProtocolDescriptorList describes a single stack,
    580 	 * the attribute value takes the form of a single Data Element
    581 	 * Sequence where each member is a protocol descriptor.
    582 	 *
    583 	 *	seq
    584 	 *	  list
    585 	 *
    586 	 * If it is possible for more than one kind of protocol
    587 	 * stack to be used to gain access to the service, the
    588 	 * ProtocolDescriptorList takes the form of a Data Element
    589 	 * Alternative where each member is a Data Element Sequence
    590 	 * describing an alternative protocol stack.
    591 	 *
    592 	 *	alt
    593 	 *	  seq
    594 	 *	    list
    595 	 *	  seq
    596 	 *	    list
    597 	 *
    598 	 * Each protocol stack description contains a sequence for each
    599 	 * protocol, where each sequence contains the protocol UUID as
    600 	 * the first element, and any ProtocolSpecificParameters. We are
    601 	 * interested in the RFCOMM channel number, stored as parameter#1.
    602 	 *
    603 	 *	seq
    604 	 *	  uuid		L2CAP
    605 	 *	  uint16	psm
    606 	 *	seq
    607 	 *	  uuid		RFCOMM
    608 	 *	  uint8		channel
    609 	 */
    610 
    611 	rv = false;
    612 	while (!rv && sdp_get_seq(&rsp, &rec)) {
    613 		if (!sdp_get_attr(&rec, &attr, &value)
    614 		    || attr != SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST)
    615 			continue;
    616 
    617 		sdp_get_alt(&value, &value);	/* strip any alt container */
    618 		while (!rv && sdp_get_seq(&value, &pdl)) {
    619 			if (sdp_get_seq(&pdl, &seq)
    620 			    && sdp_match_uuid16(&seq, SDP_UUID_PROTOCOL_L2CAP)
    621 			    && sdp_get_seq(&pdl, &seq)
    622 			    && sdp_match_uuid16(&seq, SDP_UUID_PROTOCOL_RFCOMM)
    623 			    && sdp_get_uint(&seq, channel))
    624 				rv = true;
    625 		}
    626 	}
    627 
    628 	sdp_close(ss);
    629 	return (rv) ? 0 : ENOATTR;
    630 }
    631 
    632 void
    633 sighandler(int s)
    634 {
    635 
    636 	done++;
    637 }
    638 
    639 void
    640 reset_tio(void)
    641 {
    642 
    643 	tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
    644 }
    645 
    646 void
    647 usage(void)
    648 {
    649 	const char *cmd = getprogname();
    650 	struct service *s;
    651 
    652 	fprintf(stderr, "Usage: %s [-d device] [-m mode] [-s service] [-t tty]\n"
    653 			"       %*s {-a bdaddr | -c channel}\n"
    654 			"\n"
    655 			"Where:\n"
    656 			"\t-a bdaddr    remote device address\n"
    657 			"\t-c channel   local RFCOMM channel\n"
    658 			"\t-d device    local device address\n"
    659 			"\t-m mode      link mode\n"
    660 			"\t-s service   service class\n"
    661 			"\t-t tty       run in background using pty\n"
    662 			"\n", cmd, (int)strlen(cmd), "");
    663 
    664 	fprintf(stderr, "Known service classes:\n");
    665 	for (s = services ; s->name != NULL ; s++)
    666 		fprintf(stderr, "\t%-13s%s\n", s->name, s->description);
    667 
    668 	exit(EXIT_FAILURE);
    669 }
    670