Home | History | Annotate | Line # | Download | only in rfcomm_sppd
rfcomm_sppd.c revision 1.3
      1 /*	$NetBSD: rfcomm_sppd.c,v 1.3 2007/03/01 21:44:30 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  * rfcomm_sppd.c
     33  *
     34  * Copyright (c) 2007 Iain Hibbert
     35  * Copyright (c) 2003 Maksim Yevmenkin <m_evmenkin (at) yahoo.com>
     36  * All rights reserved.
     37  *
     38  * Redistribution and use in source and binary forms, with or without
     39  * modification, are permitted provided that the following conditions
     40  * are met:
     41  * 1. Redistributions of source code must retain the above copyright
     42  *    notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *    notice, this list of conditions and the following disclaimer in the
     45  *    documentation and/or other materials provided with the distribution.
     46  *
     47  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     48  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     50  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     51  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     52  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     53  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     54  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     55  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     56  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     57  * SUCH DAMAGE.
     58  */
     59 
     60 #include <sys/cdefs.h>
     61 __COPYRIGHT("@(#) Copyright (c) 2007 Iain Hibbert\n"
     62 	    "@(#) Copyright (c) 2006 Itronix, Inc.\n"
     63 	    "@(#) Copyright (c) 2003 Maksim Yevmenkin <m_evmenkin (at) yahoo.com>\n"
     64 	    "All rights reserved.\n");
     65 __RCSID("$NetBSD: rfcomm_sppd.c,v 1.3 2007/03/01 21:44:30 plunky Exp $");
     66 
     67 #include <bluetooth.h>
     68 #include <ctype.h>
     69 #include <err.h>
     70 #include <errno.h>
     71 #include <fcntl.h>
     72 #include <grp.h>
     73 #include <limits.h>
     74 #include <paths.h>
     75 #include <sdp.h>
     76 #include <signal.h>
     77 #include <stdarg.h>
     78 #include <stdio.h>
     79 #include <stdlib.h>
     80 #include <string.h>
     81 #include <syslog.h>
     82 #include <termios.h>
     83 #include <unistd.h>
     84 
     85 #include "rfcomm_sdp.h"
     86 
     87 #define max(a, b)	((a) > (b) ? (a) : (b))
     88 
     89 int open_tty(const char *);
     90 int open_client(bdaddr_t *, bdaddr_t *, const char *);
     91 int open_server(bdaddr_t *, uint8_t, const char *);
     92 void copy_data(int, int);
     93 void sighandler(int);
     94 void usage(void);
     95 void reset_tio(void);
     96 
     97 int done;		/* got a signal */
     98 struct termios tio;	/* stored termios for reset on exit */
     99 
    100 struct service {
    101 	const char	*name;
    102 	const char	*description;
    103 	uint16_t	class;
    104 	int		pdulen;
    105 } services[] = {
    106 	{ "DUN",	"Dialup Networking",
    107 	  SDP_SERVICE_CLASS_DIALUP_NETWORKING,
    108 	  sizeof(struct sdp_dun_profile)
    109 	},
    110 	{ "LAN",	"Lan access using PPP",
    111 	  SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP,
    112 	  sizeof(struct sdp_lan_profile)
    113 	},
    114 	{ "SP",		"Serial Port",
    115 	  SDP_SERVICE_CLASS_SERIAL_PORT,
    116 	  sizeof(struct sdp_sp_profile)
    117 	},
    118 	{ NULL }
    119 };
    120 
    121 int
    122 main(int argc, char *argv[])
    123 {
    124 	struct termios		t;
    125 	bdaddr_t		laddr, raddr;
    126 	fd_set			rdset;
    127 	char			*ep, *service, *tty;
    128 	int			n, rfcomm, tty_in, tty_out;
    129 	uint8_t			channel;
    130 
    131 	bdaddr_copy(&laddr, BDADDR_ANY);
    132 	bdaddr_copy(&raddr, BDADDR_ANY);
    133 	service = "SP";
    134 	tty = NULL;
    135 	channel = 0;
    136 
    137 	/* Parse command line options */
    138 	while ((n = getopt(argc, argv, "a:c:d:hs:t:")) != -1) {
    139 		switch (n) {
    140 		case 'a': /* remote device address */
    141 			if (!bt_aton(optarg, &raddr)) {
    142 				struct hostent	*he = NULL;
    143 
    144 				if ((he = bt_gethostbyname(optarg)) == NULL)
    145 					errx(EXIT_FAILURE, "%s: %s", optarg,
    146 					    hstrerror(h_errno));
    147 
    148 				bdaddr_copy(&raddr, (bdaddr_t *)he->h_addr);
    149 			}
    150 			break;
    151 
    152 		case 'c': /* RFCOMM channel */
    153 			channel = strtoul(optarg, &ep, 10);
    154 			if (*ep != '\0' || channel < 1 || channel > 30)
    155 				errx(EXIT_FAILURE, "Invalid channel: %s", optarg);
    156 
    157 			break;
    158 
    159 		case 'd': /* local device address */
    160 			if (!bt_devaddr(optarg, &laddr))
    161 				err(EXIT_FAILURE, "%s", optarg);
    162 
    163 			break;
    164 
    165 		case 's': /* service class */
    166 			service = optarg;
    167 			break;
    168 
    169 		case 't': /* Slave TTY name */
    170 			if (optarg[0] != '/')
    171 				asprintf(&tty, "%s%s", _PATH_DEV, optarg);
    172 			else
    173 				tty = optarg;
    174 
    175 			break;
    176 
    177 		case 'h':
    178 		default:
    179 			usage();
    180 			/* NOT REACHED */
    181 		}
    182 	}
    183 
    184 	/*
    185 	 * validate options:
    186 	 *	must have channel or remote address but not both
    187 	 */
    188 	if ((channel == 0 && bdaddr_any(&raddr))
    189 	    || (channel != 0 && !bdaddr_any(&raddr)))
    190 		usage();
    191 
    192 	/*
    193 	 * grab ttys before we start the bluetooth
    194 	 */
    195 	if (tty == NULL) {
    196 		tty_in = STDIN_FILENO;
    197 		tty_out = STDOUT_FILENO;
    198 	} else {
    199 		tty_in = open_tty(tty);
    200 		tty_out = tty_in;
    201 	}
    202 
    203 	/* open RFCOMM */
    204 	if (channel == 0)
    205 		rfcomm = open_client(&laddr, &raddr, service);
    206 	else
    207 		rfcomm = open_server(&laddr, channel, service);
    208 
    209 	/*
    210 	 * now we are ready to go, so either detach or turn
    211 	 * off some input processing, so that rfcomm_sppd can
    212 	 * be used directly with stdio
    213 	 */
    214 	if (tty == NULL) {
    215 		if (tcgetattr(tty_in, &t) < 0)
    216 			err(EXIT_FAILURE, "tcgetattr");
    217 
    218 		memcpy(&tio, &t, sizeof(tio));
    219 		t.c_lflag &= ~(ECHO | ICANON);
    220 		t.c_iflag &= ~(ICRNL);
    221 
    222 		if (tcsetattr(tty_in, TCSANOW, &t) < 0)
    223 			err(EXIT_FAILURE, "tcsetattr");
    224 
    225 		atexit(reset_tio);
    226 	} else {
    227 		if (daemon(0, 0) < 0)
    228 			err(EXIT_FAILURE, "daemon() failed");
    229 	}
    230 
    231 	/* catch signals */
    232 	done = 0;
    233 	(void)signal(SIGHUP, sighandler);
    234 	(void)signal(SIGINT, sighandler);
    235 	(void)signal(SIGPIPE, sighandler);
    236 	(void)signal(SIGTERM, sighandler);
    237 
    238 	openlog(getprogname(), LOG_PERROR | LOG_PID, LOG_DAEMON);
    239 	syslog(LOG_INFO, "Starting on %s...", (tty ? tty : "stdio"));
    240 
    241 	n = max(tty_in, rfcomm) + 1;
    242 	while (!done) {
    243 		FD_ZERO(&rdset);
    244 		FD_SET(tty_in, &rdset);
    245 		FD_SET(rfcomm, &rdset);
    246 
    247 		if (select(n, &rdset, NULL, NULL, NULL) < 0) {
    248 			if (errno == EINTR)
    249 				continue;
    250 
    251 			syslog(LOG_ERR, "select error: %m");
    252 			exit(EXIT_FAILURE);
    253 		}
    254 
    255 		if (FD_ISSET(tty_in, &rdset))
    256 			copy_data(tty_in, rfcomm);
    257 
    258 		if (FD_ISSET(rfcomm, &rdset))
    259 			copy_data(rfcomm, tty_out);
    260 	}
    261 
    262 	syslog(LOG_INFO, "Completed on %s", (tty ? tty : "stdio"));
    263 	exit(EXIT_SUCCESS);
    264 }
    265 
    266 int
    267 open_tty(const char *tty)
    268 {
    269 	char		 pty[PATH_MAX], *slash;
    270 	struct group	*gr = NULL;
    271 	gid_t		 ttygid;
    272 	int		 master;
    273 
    274 	/*
    275 	 * Construct master PTY name. The slave tty name must be less then
    276 	 * PATH_MAX characters in length, must contain '/' character and
    277 	 * must not end with '/'.
    278 	 */
    279 	if (strlen(tty) >= sizeof(pty))
    280 		errx(EXIT_FAILURE, ": tty name too long");
    281 
    282 	strlcpy(pty, tty, sizeof(pty));
    283 	slash = strrchr(pty, '/');
    284 	if (slash == NULL || slash[1] == '\0')
    285 		errx(EXIT_FAILURE, "%s: invalid tty", tty);
    286 
    287 	slash[1] = 'p';
    288 	if (strcmp(pty, tty) == 0)
    289 		errx(EXIT_FAILURE, "Master and slave tty are the same (%s)", tty);
    290 
    291 	if ((master = open(pty, O_RDWR, 0)) < 0)
    292 		err(EXIT_FAILURE, "%s", pty);
    293 
    294 	/*
    295 	 * Slave TTY
    296 	 */
    297 
    298 	if ((gr = getgrnam("tty")) != NULL)
    299 		ttygid = gr->gr_gid;
    300 	else
    301 		ttygid = (gid_t)-1;
    302 
    303 	(void)chown(tty, getuid(), ttygid);
    304 	(void)chmod(tty, S_IRUSR | S_IWUSR | S_IWGRP);
    305 	(void)revoke(tty);
    306 
    307 	return master;
    308 }
    309 
    310 int
    311 open_client(bdaddr_t *laddr, bdaddr_t *raddr, const char *service)
    312 {
    313 	struct sockaddr_bt sa;
    314 	struct service *s;
    315 	struct linger l;
    316 	char *ep;
    317 	int fd;
    318 	uint8_t channel;
    319 
    320 	for (s = services ; ; s++) {
    321 		if (s->name == NULL) {
    322 			channel = strtoul(optarg, &ep, 10);
    323 			if (*ep != '\0' || channel < 1 || channel > 30)
    324 				errx(EXIT_FAILURE, "Invalid service: %s", service);
    325 
    326 			break;
    327 		}
    328 
    329 		if (strcasecmp(s->name, service) == 0) {
    330 			if (rfcomm_channel_lookup(laddr, raddr, s->class, &channel, &errno) < 0)
    331 				err(EXIT_FAILURE, "%s", s->name);
    332 
    333 			break;
    334 		}
    335 	}
    336 
    337 	memset(&sa, 0, sizeof(sa));
    338 	sa.bt_len = sizeof(sa);
    339 	sa.bt_family = AF_BLUETOOTH;
    340 	bdaddr_copy(&sa.bt_bdaddr, laddr);
    341 
    342 	fd = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    343 	if (fd < 0)
    344 		err(EXIT_FAILURE, "socket()");
    345 
    346 	if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
    347 		err(EXIT_FAILURE, "bind(%s)", bt_ntoa(laddr, NULL));
    348 
    349 	memset(&l, 0, sizeof(l));
    350 	l.l_onoff = 1;
    351 	l.l_linger = 5;
    352 	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0)
    353 		err(EXIT_FAILURE, "linger()");
    354 
    355 	sa.bt_channel = channel;
    356 	bdaddr_copy(&sa.bt_bdaddr, raddr);
    357 
    358 	if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
    359 		err(EXIT_FAILURE, "connect(%s, %d)", bt_ntoa(raddr, NULL),
    360 						     channel);
    361 
    362 	return fd;
    363 }
    364 
    365 /*
    366  * In all the profiles we currently support registering, the channel
    367  * is the first octet in the PDU, and it seems all the rest can be
    368  * zero, so we just use an array of uint8_t big enough to store the
    369  * largest, currently LAN. See <sdp.h> for definitions..
    370  */
    371 #define pdu_len		sizeof(struct sdp_lan_profile)
    372 
    373 int
    374 open_server(bdaddr_t *laddr, uint8_t channel, const char *service)
    375 {
    376 	struct sockaddr_bt sa;
    377 	struct linger l;
    378 	socklen_t len;
    379 	void *ss;
    380 	int sv, fd, n;
    381 	uint8_t pdu[pdu_len];
    382 
    383 	memset(&sa, 0, sizeof(sa));
    384 	sa.bt_len = sizeof(sa);
    385 	sa.bt_family = AF_BLUETOOTH;
    386 	bdaddr_copy(&sa.bt_bdaddr, laddr);
    387 	sa.bt_channel = channel;
    388 
    389 	sv = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    390 	if (sv < 0)
    391 		err(EXIT_FAILURE, "socket()");
    392 
    393 	if (bind(sv, (struct sockaddr *)&sa, sizeof(sa)) < 0)
    394 		err(EXIT_FAILURE, "bind(%s, %d)", bt_ntoa(laddr, NULL),
    395 						  channel);
    396 
    397 	if (listen(sv, 1) < 0)
    398 		err(EXIT_FAILURE, "listen()");
    399 
    400 	/* Register service with SDP server */
    401 	for (n = 0 ; ; n++) {
    402 		if (services[n].name == NULL)
    403 			usage();
    404 
    405 		if (strcasecmp(services[n].name, service) == 0)
    406 			break;
    407 	}
    408 
    409 	memset(pdu, 0, pdu_len);
    410 	pdu[0] = channel;
    411 
    412 	ss = sdp_open_local(NULL);
    413 	if (ss == NULL || (errno = sdp_error(ss)) != 0)
    414 		err(EXIT_FAILURE, "sdp_open_local");
    415 
    416 	if (sdp_register_service(ss, services[n].class, laddr,
    417 		    pdu, services[n].pdulen, NULL) != 0) {
    418 		errno = sdp_error(ss);
    419 		err(EXIT_FAILURE, "sdp_register_service");
    420 	}
    421 
    422 	len = sizeof(sa);
    423 	fd = accept(sv, (struct sockaddr *)&sa, &len);
    424 	if (fd < 0)
    425 		err(EXIT_FAILURE, "accept");
    426 
    427 	memset(&l, 0, sizeof(l));
    428 	l.l_onoff = 1;
    429 	l.l_linger = 5;
    430 	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0)
    431 		err(EXIT_FAILURE, "linger()");
    432 
    433 	close(sv);
    434 	return fd;
    435 }
    436 
    437 void
    438 copy_data(int src, int dst)
    439 {
    440 	static char	buf[BUFSIZ];
    441 	ssize_t		nr, nw, off;
    442 
    443 	while ((nr = read(src, buf, sizeof(buf))) == -1) {
    444 		if (errno != EINTR) {
    445 			syslog(LOG_ERR, "read failed: %m");
    446 			exit(EXIT_FAILURE);
    447 		}
    448 	}
    449 
    450 	if (nr == 0)	/* reached EOF */
    451 		done++;
    452 
    453 	for (off = 0 ; nr ; nr -= nw, off += nw) {
    454 		if ((nw = write(dst, buf + off, (size_t)nr)) == -1) {
    455 			syslog(LOG_ERR, "write failed: %m");
    456 			exit(EXIT_FAILURE);
    457 		}
    458 	}
    459 }
    460 
    461 void
    462 sighandler(int s)
    463 {
    464 
    465 	done++;
    466 }
    467 
    468 void
    469 reset_tio(void)
    470 {
    471 
    472 	tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
    473 }
    474 
    475 void
    476 usage(void)
    477 {
    478 	struct service *s;
    479 
    480 	fprintf(stderr, "Usage: %s  [-d device] [-s service] [-t tty] -a bdaddr | -c channel\n"
    481 			"\n"
    482 			"Where:\n"
    483 			"\t-a bdaddr    remote device address\n"
    484 			"\t-c channel   local RFCOMM channel\n"
    485 			"\t-d device    local device address\n"
    486 			"\t-s service   service class\n"
    487 			"\t-t tty       run in background using pty\n"
    488 			"\n", getprogname());
    489 
    490 	fprintf(stderr, "Known service classes:\n");
    491 	for (s = services ; s->name != NULL ; s++)
    492 		fprintf(stderr, "\t%-13s%s\n", s->name, s->description);
    493 
    494 	exit(EXIT_FAILURE);
    495 }
    496