xref: /freebsd/usr.bin/bluetooth/rfcomm_sppd/rfcomm_sppd.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
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 		if (listen(acceptsock, 10) != 0)
215 			err(1, "Could not listen on socket");
216 
217 		ss = sdp_open_local(NULL);
218 		if (ss == NULL)
219 			errx(1, "Unable to create local SDP session");
220 		if (sdp_error(ss) != 0)
221 			errx(1, "Unable to open local SDP session. %s (%d)",
222 			    strerror(sdp_error(ss)), sdp_error(ss));
223 		memset(&lan, 0, sizeof(lan));
224 		lan.server_channel = channel;
225 
226 		memcpy(&bt_addr_any, NG_HCI_BDADDR_ANY, sizeof(bt_addr_any));
227 		if (sdp_register_service(ss, service, &bt_addr_any,
228 		    (void *)&lan, sizeof(lan), &sdp_handle) != 0) {
229 			errx(1, "Unable to register LAN service with "
230 			    "local SDP daemon. %s (%d)",
231 			    strerror(sdp_error(ss)), sdp_error(ss));
232 		}
233 
234 		s = -1;
235 		while (s < 0) {
236 			aaddrlen = sizeof(ra);
237 			s = accept(acceptsock, (struct sockaddr *)&ra,
238 			    &aaddrlen);
239 			if (s < 0)
240 				err(1, "Unable to accept()");
241 			if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) &&
242 			    memcmp(&addr, &ra.rfcomm_bdaddr, sizeof(addr))) {
243 				warnx("Connect from wrong client");
244 				close(s);
245 				s = -1;
246 			}
247 		}
248 		sdp_unregister_service(ss, sdp_handle);
249 		sdp_close(ss);
250 		close(acceptsock);
251 	} else {
252 		/* Check channel, if was not set then obtain it via SDP */
253 		if (channel == 0 && service != 0)
254 			if (rfcomm_channel_lookup(NULL, &addr,
255 				    service, &channel, &n) != 0)
256 				errc(1, n, "Could not obtain RFCOMM channel");
257 		if (channel <= 0 || channel > 30)
258 			errx(1, "Invalid RFCOMM channel number %d", channel);
259 
260 		s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
261 		if (s < 0)
262 			err(1, "Could not create socket");
263 
264 		memset(&ra, 0, sizeof(ra));
265 		ra.rfcomm_len = sizeof(ra);
266 		ra.rfcomm_family = AF_BLUETOOTH;
267 
268 		if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
269 			err(1, "Could not bind socket");
270 
271 		memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
272 		ra.rfcomm_channel = channel;
273 
274 		if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
275 			err(1, "Could not connect socket");
276 	}
277 
278 	/* Became daemon if required */
279 	if (background) {
280 		switch (fork()) {
281 		case -1:
282 			err(1, "Could not fork()");
283 			/* NOT REACHED */
284 
285 		case 0:
286 			exit(0);
287 			/* NOT REACHED */
288 
289 		default:
290 			if (daemon(0, 0) < 0)
291 				err(1, "Could not daemon()");
292 			break;
293 		}
294 	}
295 
296 	openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
297 	syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout");
298 
299 	for (done = 0; !done; ) {
300 		FD_ZERO(&rfd);
301 		FD_SET(amaster, &rfd);
302 		FD_SET(s, &rfd);
303 
304 		n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
305 		if (n < 0) {
306 			if (errno == EINTR)
307 				continue;
308 
309 			syslog(LOG_ERR, "Could not select(). %s",
310 					strerror(errno));
311 			exit(1);
312 		}
313 
314 		if (n == 0)
315 			continue;
316 
317 		if (FD_ISSET(amaster, &rfd)) {
318 			n = sppd_read(amaster, buf, sizeof(buf));
319 			if (n < 0) {
320 				syslog(LOG_ERR, "Could not read master pty, " \
321 					"fd=%d. %s", amaster, strerror(errno));
322 				exit(1);
323 			}
324 
325 			if (n == 0)
326 				break; /* XXX */
327 
328 			if (sppd_write(s, buf, n) < 0) {
329 				syslog(LOG_ERR, "Could not write to socket, " \
330 					"fd=%d, size=%d. %s",
331 					s, n, strerror(errno));
332 				exit(1);
333 			}
334 		}
335 
336 		if (FD_ISSET(s, &rfd)) {
337 			n = sppd_read(s, buf, sizeof(buf));
338 			if (n < 0) {
339 				syslog(LOG_ERR, "Could not read socket, " \
340 					"fd=%d. %s", s, strerror(errno));
341 				exit(1);
342 			}
343 
344 			if (n == 0)
345 				break;
346 
347 			if (sppd_write(fd, buf, n) < 0) {
348 				syslog(LOG_ERR, "Could not write to master " \
349 					"pty, fd=%d, size=%d. %s",
350 					fd, n, strerror(errno));
351 				exit(1);
352 			}
353 		}
354 	}
355 
356 	syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout");
357 	closelog();
358 
359 	close(s);
360 
361 	if (tty != NULL) {
362 		close(aslave);
363 		close(amaster);
364 	}
365 
366 	return (0);
367 }
368 
369 /* Open TTYs */
370 static int
371 sppd_ttys_open(char const *tty, int *amaster, int *aslave)
372 {
373 	char		 pty[PATH_MAX], *slash;
374 	struct group	*gr = NULL;
375 	gid_t		 ttygid;
376 	struct termios	 tio;
377 
378 	/*
379 	 * Construct master PTY name. The slave tty name must be less then
380 	 * PATH_MAX characters in length, must contain '/' character and
381 	 * must not end with '/'.
382 	 */
383 
384 	if (strlen(tty) >= sizeof(pty)) {
385 		syslog(LOG_ERR, "Slave tty name is too long");
386 		return (-1);
387 	}
388 
389 	strlcpy(pty, tty, sizeof(pty));
390 	slash = strrchr(pty, '/');
391 	if (slash == NULL || slash[1] == '\0') {
392 		syslog(LOG_ERR, "Invalid slave tty name (%s)", tty);
393 		return (-1);
394 	}
395 
396 	slash[1] = 'p';
397 
398 	if (strcmp(pty, tty) == 0) {
399 		syslog(LOG_ERR, "Master and slave tty are the same (%s)", tty);
400 		return (-1);
401 	}
402 
403 	if ((*amaster = open(pty, O_RDWR, 0)) < 0) {
404 		syslog(LOG_ERR, "Could not open(%s). %s", pty, strerror(errno));
405 		return (-1);
406 	}
407 
408 	/*
409 	 * Slave TTY
410 	 */
411 
412 	if ((gr = getgrnam("tty")) != NULL)
413 		ttygid = gr->gr_gid;
414 	else
415 		ttygid = -1;
416 
417 	(void) chown(tty, getuid(), ttygid);
418 	(void) chmod(tty, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
419 	(void) revoke(tty);
420 
421 	if ((*aslave = open(tty, O_RDWR, 0)) < 0) {
422 		syslog(LOG_ERR, "Could not open(%s). %s", tty, strerror(errno));
423 		close(*amaster);
424 		return (-1);
425 	}
426 
427 	/*
428 	 * Make slave TTY raw
429 	 */
430 
431 	cfmakeraw(&tio);
432 
433 	if (tcsetattr(*aslave, TCSANOW, &tio) < 0) {
434 		syslog(LOG_ERR, "Could not tcsetattr(). %s", strerror(errno));
435 		close(*aslave);
436 		close(*amaster);
437 		return (-1);
438 	}
439 
440 	return (0);
441 } /* sppd_ttys_open */
442 
443 /* Read data */
444 static int
445 sppd_read(int fd, char *buffer, int size)
446 {
447 	int	n;
448 
449 again:
450 	n = read(fd, buffer, size);
451 	if (n < 0) {
452 		if (errno == EINTR)
453 			goto again;
454 
455 		return (-1);
456 	}
457 
458 	return (n);
459 } /* sppd_read */
460 
461 /* Write data */
462 static int
463 sppd_write(int fd, char *buffer, int size)
464 {
465 	int	n, wrote;
466 
467 	for (wrote = 0; size > 0; ) {
468 		n = write(fd, buffer, size);
469 		switch (n) {
470 		case -1:
471 			if (errno != EINTR)
472 				return (-1);
473 			break;
474 
475 		case 0:
476 			/* XXX can happen? */
477 			break;
478 
479 		default:
480 			wrote += n;
481 			buffer += n;
482 			size -= n;
483 			break;
484 		}
485 	}
486 
487 	return (wrote);
488 } /* sppd_write */
489 
490 /* Signal handler */
491 static void
492 sppd_sighandler(int s)
493 {
494 	syslog(LOG_INFO, "Signal %d received. Total %d signals received\n",
495 			s, ++ done);
496 } /* sppd_sighandler */
497 
498 /* Display usage and exit */
499 static void
500 usage(void)
501 {
502 	fprintf(stdout,
503 "Usage: %s options\n" \
504 "Where options are:\n" \
505 "\t-a address Peer address (required in client mode)\n" \
506 "\t-b         Run in background\n" \
507 "\t-c channel RFCOMM channel to connect to or listen on\n" \
508 "\t-t tty     TTY name (required in background or server mode)\n" \
509 "\t-S         Server mode\n" \
510 "\t-h         Display this message\n", SPPD_IDENT);
511 	exit(255);
512 } /* usage */
513 
514