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