xref: /freebsd/usr.bin/bluetooth/rfcomm_sppd/rfcomm_sppd.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
1 /*
2  * rfcomm_sppd.c
3  *
4  * Copyright (c) 2003 Maksim Yevmenkin <m_evmenkin@yahoo.com>
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  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $Id: rfcomm_sppd.c,v 1.4 2003/09/07 18:15:55 max Exp $
29  * $FreeBSD$
30  */
31 
32 #include <sys/stat.h>
33 #include <bluetooth.h>
34 #include <ctype.h>
35 #include <err.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <grp.h>
39 #include <limits.h>
40 #include <paths.h>
41 #include <sdp.h>
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <syslog.h>
48 #include <termios.h>
49 #include <unistd.h>
50 
51 #define SPPD_IDENT		"rfcomm_sppd"
52 #define SPPD_BUFFER_SIZE	1024
53 #define max(a, b)		(((a) > (b))? (a) : (b))
54 
55 int		rfcomm_channel_lookup	(bdaddr_t const *local,
56 					 bdaddr_t const *remote,
57 					 int service, int *channel, int *error);
58 
59 static int	sppd_ttys_open	(char const *tty, int *amaster, int *aslave);
60 static int	sppd_read	(int fd, char *buffer, int size);
61 static int	sppd_write	(int fd, char *buffer, int size);
62 static void	sppd_sighandler	(int s);
63 static void	usage		(void);
64 
65 static int	done;	/* are we done? */
66 
67 /* Main */
68 int
69 main(int argc, char *argv[])
70 {
71 	struct sigaction	 sa;
72 	struct sockaddr_rfcomm	 ra;
73 	bdaddr_t		 addr;
74 	int			 n, background, channel, service,
75 				 s, amaster, aslave, fd, doserver;
76 	fd_set			 rfd;
77 	char			*tty = NULL, *ep = NULL, buf[SPPD_BUFFER_SIZE];
78 
79 	memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr));
80 	background = channel = 0;
81 	service = SDP_SERVICE_CLASS_SERIAL_PORT;
82 	doserver = 0;
83 
84 	/* Parse command line options */
85 	while ((n = getopt(argc, argv, "a:bc:t:hS")) != -1) {
86 		switch (n) {
87 		case 'a': /* BDADDR */
88 			if (!bt_aton(optarg, &addr)) {
89 				struct hostent	*he = NULL;
90 
91 				if ((he = bt_gethostbyname(optarg)) == NULL)
92 					errx(1, "%s: %s", optarg, hstrerror(h_errno));
93 
94 				memcpy(&addr, he->h_addr, sizeof(addr));
95 			}
96 			break;
97 
98 		case 'c': /* RFCOMM channel */
99 			channel = strtoul(optarg, &ep, 10);
100 			if (*ep != '\0') {
101 				channel = 0;
102 				switch (tolower(optarg[0])) {
103 				case 'd': /* DialUp Networking */
104 					service = SDP_SERVICE_CLASS_DIALUP_NETWORKING;
105 					break;
106 
107 				case 'f': /* Fax */
108 					service = SDP_SERVICE_CLASS_FAX;
109 					break;
110 
111 				case 'l': /* LAN */
112 					service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP;
113 					break;
114 
115 				case 's': /* Serial Port */
116 					service = SDP_SERVICE_CLASS_SERIAL_PORT;
117 					break;
118 
119 				default:
120 					errx(1, "Unknown service name: %s",
121 						optarg);
122 					/* NOT REACHED */
123 				}
124 			}
125 			break;
126 
127 		case 'b': /* Run in background */
128 			background = 1;
129 			break;
130 
131 		case 't': /* Slave TTY name */
132 			if (optarg[0] != '/')
133 				asprintf(&tty, "%s%s", _PATH_DEV, optarg);
134 			else
135 				tty = optarg;
136 			break;
137 
138 		case 'S':
139 			doserver = 1;
140 			break;
141 
142 		case 'h':
143 		default:
144 			usage();
145 			/* NOT REACHED */
146 		}
147 	}
148 
149 	/* Check if we have everything we need */
150 	if (!doserver && memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0)
151 		usage();
152 		/* NOT REACHED */
153 
154 	/* Set signal handlers */
155 	memset(&sa, 0, sizeof(sa));
156 	sa.sa_handler = sppd_sighandler;
157 
158 	if (sigaction(SIGTERM, &sa, NULL) < 0)
159 		err(1, "Could not sigaction(SIGTERM)");
160 
161 	if (sigaction(SIGHUP, &sa, NULL) < 0)
162 		err(1, "Could not sigaction(SIGHUP)");
163 
164 	if (sigaction(SIGINT, &sa, NULL) < 0)
165 		err(1, "Could not sigaction(SIGINT)");
166 
167 	sa.sa_handler = SIG_IGN;
168 	sa.sa_flags = SA_NOCLDWAIT;
169 
170 	if (sigaction(SIGCHLD, &sa, NULL) < 0)
171 		err(1, "Could not sigaction(SIGCHLD)");
172 
173 	/* Open TTYs */
174 	if (tty == NULL) {
175 		if (background || doserver)
176 			usage();
177 
178 		amaster = STDIN_FILENO;
179 		fd = STDOUT_FILENO;
180 	} else {
181 		if (sppd_ttys_open(tty, &amaster, &aslave) < 0)
182 			exit(1);
183 
184 		fd = amaster;
185 	}
186 
187 	/* Open RFCOMM connection */
188 
189 	if (doserver) {
190 		struct sockaddr_rfcomm	 ma;
191 		bdaddr_t		 bt_addr_any;
192 		sdp_lan_profile_t	 lan;
193 		void			*ss;
194 		uint32_t		 sdp_handle;
195 		int			 acceptsock, aaddrlen;
196 
197 		if (channel == 0) {
198 			/* XXX: should check if selected channel is unused */
199 			channel = (getpid() % 30) + 1;
200 		}
201 		acceptsock = socket(PF_BLUETOOTH, SOCK_STREAM,
202 		    BLUETOOTH_PROTO_RFCOMM);
203 		if (acceptsock < 0)
204 			err(1, "Could not create socket");
205 
206 		memset(&ma, 0, sizeof(ma));
207 		ma.rfcomm_len = sizeof(ma);
208 		ma.rfcomm_family = AF_BLUETOOTH;
209 		ma.rfcomm_channel = channel;
210 
211 		if (bind(acceptsock, (struct sockaddr *)&ma, sizeof(ma)) < 0)
212 			err(1, "Could not bind socket -- channel %d in use?",
213 			    channel);
214 		listen(acceptsock, 10);
215 
216 		ss = sdp_open_local(NULL);
217 		if (ss == NULL)
218 			errx(1, "Unable to create local SDP session");
219 		if (sdp_error(ss) != 0)
220 			errx(1, "Unable to open local SDP session. %s (%d)",
221 			    strerror(sdp_error(ss)), sdp_error(ss));
222 		memset(&lan, 0, sizeof(lan));
223 		lan.server_channel = channel;
224 
225 		memcpy(&bt_addr_any, NG_HCI_BDADDR_ANY, sizeof(bt_addr_any));
226 		if (sdp_register_service(ss, service, &bt_addr_any,
227 		    (void *)&lan, sizeof(lan), &sdp_handle) != 0) {
228 			errx(1, "Unable to register LAN service with "
229 			    "local SDP daemon. %s (%d)",
230 			    strerror(sdp_error(ss)), sdp_error(ss));
231 		}
232 
233 		s = -1;
234 		while (s < 0) {
235 			aaddrlen = sizeof(ra);
236 			s = accept(acceptsock, (struct sockaddr *)&ra,
237 			    &aaddrlen);
238 			if (s < 0)
239 				err(1, "Unable to accept()");
240 			if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) &&
241 			    memcmp(&addr, &ra.rfcomm_bdaddr, sizeof(addr))) {
242 				warnx("Connect from wrong client");
243 				close(s);
244 				s = -1;
245 			}
246 		}
247 		sdp_unregister_service(ss, sdp_handle);
248 		sdp_close(ss);
249 		close(acceptsock);
250 	} else {
251 		/* Check channel, if was not set then obtain it via SDP */
252 		if (channel == 0 && service != 0)
253 			if (rfcomm_channel_lookup(NULL, &addr,
254 				    service, &channel, &n) != 0)
255 				errc(1, n, "Could not obtain RFCOMM channel");
256 		if (channel <= 0 || channel > 30)
257 			errx(1, "Invalid RFCOMM channel number %d", channel);
258 
259 		s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
260 		if (s < 0)
261 			err(1, "Could not create socket");
262 
263 		memset(&ra, 0, sizeof(ra));
264 		ra.rfcomm_len = sizeof(ra);
265 		ra.rfcomm_family = AF_BLUETOOTH;
266 
267 		if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
268 			err(1, "Could not bind socket");
269 
270 		memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
271 		ra.rfcomm_channel = channel;
272 
273 		if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
274 			err(1, "Could not connect socket");
275 	}
276 
277 	/* Became daemon if required */
278 	if (background) {
279 		switch (fork()) {
280 		case -1:
281 			err(1, "Could not fork()");
282 			/* NOT REACHED */
283 
284 		case 0:
285 			exit(0);
286 			/* NOT REACHED */
287 
288 		default:
289 			if (daemon(0, 0) < 0)
290 				err(1, "Could not daemon()");
291 			break;
292 		}
293 	}
294 
295 	openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
296 	syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout");
297 
298 	for (done = 0; !done; ) {
299 		FD_ZERO(&rfd);
300 		FD_SET(amaster, &rfd);
301 		FD_SET(s, &rfd);
302 
303 		n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
304 		if (n < 0) {
305 			if (errno == EINTR)
306 				continue;
307 
308 			syslog(LOG_ERR, "Could not select(). %s",
309 					strerror(errno));
310 			exit(1);
311 		}
312 
313 		if (n == 0)
314 			continue;
315 
316 		if (FD_ISSET(amaster, &rfd)) {
317 			n = sppd_read(amaster, buf, sizeof(buf));
318 			if (n < 0) {
319 				syslog(LOG_ERR, "Could not read master pty, " \
320 					"fd=%d. %s", amaster, strerror(errno));
321 				exit(1);
322 			}
323 
324 			if (n == 0)
325 				break; /* XXX */
326 
327 			if (sppd_write(s, buf, n) < 0) {
328 				syslog(LOG_ERR, "Could not write to socket, " \
329 					"fd=%d, size=%d. %s",
330 					s, n, strerror(errno));
331 				exit(1);
332 			}
333 		}
334 
335 		if (FD_ISSET(s, &rfd)) {
336 			n = sppd_read(s, buf, sizeof(buf));
337 			if (n < 0) {
338 				syslog(LOG_ERR, "Could not read socket, " \
339 					"fd=%d. %s", s, strerror(errno));
340 				exit(1);
341 			}
342 
343 			if (n == 0)
344 				break;
345 
346 			if (sppd_write(fd, buf, n) < 0) {
347 				syslog(LOG_ERR, "Could not write to master " \
348 					"pty, fd=%d, size=%d. %s",
349 					fd, n, strerror(errno));
350 				exit(1);
351 			}
352 		}
353 	}
354 
355 	syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout");
356 	closelog();
357 
358 	close(s);
359 
360 	if (tty != NULL) {
361 		close(aslave);
362 		close(amaster);
363 	}
364 
365 	return (0);
366 }
367 
368 /* Open TTYs */
369 static int
370 sppd_ttys_open(char const *tty, int *amaster, int *aslave)
371 {
372 	char		 pty[PATH_MAX], *slash;
373 	struct group	*gr = NULL;
374 	gid_t		 ttygid;
375 	struct termios	 tio;
376 
377 	/*
378 	 * Construct master PTY name. The slave tty name must be less then
379 	 * PATH_MAX characters in length, must contain '/' character and
380 	 * must not end with '/'.
381 	 */
382 
383 	if (strlen(tty) >= sizeof(pty)) {
384 		syslog(LOG_ERR, "Slave tty name is too long");
385 		return (-1);
386 	}
387 
388 	strlcpy(pty, tty, sizeof(pty));
389 	slash = strrchr(pty, '/');
390 	if (slash == NULL || slash[1] == '\0') {
391 		syslog(LOG_ERR, "Invalid slave tty name (%s)", tty);
392 		return (-1);
393 	}
394 
395 	slash[1] = 'p';
396 
397 	if (strcmp(pty, tty) == 0) {
398 		syslog(LOG_ERR, "Master and slave tty are the same (%s)", tty);
399 		return (-1);
400 	}
401 
402 	if ((*amaster = open(pty, O_RDWR, 0)) < 0) {
403 		syslog(LOG_ERR, "Could not open(%s). %s", pty, strerror(errno));
404 		return (-1);
405 	}
406 
407 	/*
408 	 * Slave TTY
409 	 */
410 
411 	if ((gr = getgrnam("tty")) != NULL)
412 		ttygid = gr->gr_gid;
413 	else
414 		ttygid = -1;
415 
416 	(void) chown(tty, getuid(), ttygid);
417 	(void) chmod(tty, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
418 	(void) revoke(tty);
419 
420 	if ((*aslave = open(tty, O_RDWR, 0)) < 0) {
421 		syslog(LOG_ERR, "Could not open(%s). %s", tty, strerror(errno));
422 		close(*amaster);
423 		return (-1);
424 	}
425 
426 	/*
427 	 * Make slave TTY raw
428 	 */
429 
430 	cfmakeraw(&tio);
431 
432 	if (tcsetattr(*aslave, TCSANOW, &tio) < 0) {
433 		syslog(LOG_ERR, "Could not tcsetattr(). %s", strerror(errno));
434 		close(*aslave);
435 		close(*amaster);
436 		return (-1);
437 	}
438 
439 	return (0);
440 } /* sppd_ttys_open */
441 
442 /* Read data */
443 static int
444 sppd_read(int fd, char *buffer, int size)
445 {
446 	int	n;
447 
448 again:
449 	n = read(fd, buffer, size);
450 	if (n < 0) {
451 		if (errno == EINTR)
452 			goto again;
453 
454 		return (-1);
455 	}
456 
457 	return (n);
458 } /* sppd_read */
459 
460 /* Write data */
461 static int
462 sppd_write(int fd, char *buffer, int size)
463 {
464 	int	n, wrote;
465 
466 	for (wrote = 0; size > 0; ) {
467 		n = write(fd, buffer, size);
468 		switch (n) {
469 		case -1:
470 			if (errno != EINTR)
471 				return (-1);
472 			break;
473 
474 		case 0:
475 			/* XXX can happen? */
476 			break;
477 
478 		default:
479 			wrote += n;
480 			buffer += n;
481 			size -= n;
482 			break;
483 		}
484 	}
485 
486 	return (wrote);
487 } /* sppd_write */
488 
489 /* Signal handler */
490 static void
491 sppd_sighandler(int s)
492 {
493 	syslog(LOG_INFO, "Signal %d received. Total %d signals received\n",
494 			s, ++ done);
495 } /* sppd_sighandler */
496 
497 /* Display usage and exit */
498 static void
499 usage(void)
500 {
501 	fprintf(stdout,
502 "Usage: %s options\n" \
503 "Where options are:\n" \
504 "\t-a address Peer address (required in client mode)\n" \
505 "\t-b         Run in background\n" \
506 "\t-c channel RFCOMM channel to connect to or listen on\n" \
507 "\t-t tty     TTY name (required in background or server mode)\n" \
508 "\t-S         Server mode\n" \
509 "\t-h         Display this message\n", SPPD_IDENT);
510 	exit(255);
511 } /* usage */
512 
513