xref: /freebsd/usr.bin/bluetooth/rfcomm_sppd/rfcomm_sppd.c (revision 87569f75a91f298c52a71823c04d41cf53c88889)
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;
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 
83 	/* Parse command line options */
84 	while ((n = getopt(argc, argv, "a:bc:t:h")) != -1) {
85 		switch (n) {
86 		case 'a': /* BDADDR */
87 			if (!bt_aton(optarg, &addr)) {
88 				struct hostent	*he = NULL;
89 
90 				if ((he = bt_gethostbyname(optarg)) == NULL)
91 					errx(1, "%s: %s", optarg, hstrerror(h_errno));
92 
93 				memcpy(&addr, he->h_addr, sizeof(addr));
94 			}
95 			break;
96 
97 		case 'c': /* RFCOMM channel */
98 			channel = strtoul(optarg, &ep, 10);
99 			if (*ep != '\0') {
100 				channel = 0;
101 				switch (tolower(optarg[0])) {
102 				case 'd': /* DialUp Networking */
103 					service = SDP_SERVICE_CLASS_DIALUP_NETWORKING;
104 					break;
105 
106 				case 'f': /* Fax */
107 					service = SDP_SERVICE_CLASS_FAX;
108 					break;
109 
110 				case 'l': /* LAN */
111 					service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP;
112 					break;
113 
114 				case 's': /* Serial Port */
115 					service = SDP_SERVICE_CLASS_SERIAL_PORT;
116 					break;
117 
118 				default:
119 					errx(1, "Unknown service name: %s",
120 						optarg);
121 					/* NOT REACHED */
122 				}
123 			}
124 			break;
125 
126 		case 'b': /* Run in background */
127 			background = 1;
128 			break;
129 
130 		case 't': /* Slave TTY name */
131 			if (optarg[0] != '/')
132 				asprintf(&tty, "%s%s", _PATH_DEV, optarg);
133 			else
134 				tty = optarg;
135 			break;
136 
137 		case 'h':
138 		default:
139 			usage();
140 			/* NOT REACHED */
141 		}
142 	}
143 
144 	/* Check if we have everything we need */
145 	if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0)
146 		usage();
147 		/* NOT REACHED */
148 
149 	/* Set signal handlers */
150 	memset(&sa, 0, sizeof(sa));
151 	sa.sa_handler = sppd_sighandler;
152 
153 	if (sigaction(SIGTERM, &sa, NULL) < 0)
154 		err(1, "Could not sigaction(SIGTERM)");
155 
156 	if (sigaction(SIGHUP, &sa, NULL) < 0)
157 		err(1, "Could not sigaction(SIGHUP)");
158 
159 	if (sigaction(SIGINT, &sa, NULL) < 0)
160 		err(1, "Could not sigaction(SIGINT)");
161 
162 	sa.sa_handler = SIG_IGN;
163 	sa.sa_flags = SA_NOCLDWAIT;
164 
165 	if (sigaction(SIGCHLD, &sa, NULL) < 0)
166 		err(1, "Could not sigaction(SIGCHLD)");
167 
168 	/* Check channel, if was not set then obtain it via SDP */
169 	if (channel == 0 && service != 0)
170 		if (rfcomm_channel_lookup(NULL, &addr,
171 			    service, &channel, &n) != 0)
172 			errc(1, n, "Could not obtain RFCOMM channel");
173 	if (channel <= 0 || channel > 30)
174 		errx(1, "Invalid RFCOMM channel number %d", channel);
175 
176 	/* Open TTYs */
177 	if (tty == NULL) {
178 		if (background)
179 			usage();
180 
181 		amaster = STDIN_FILENO;
182 		fd = STDOUT_FILENO;
183 	} else {
184 		if (sppd_ttys_open(tty, &amaster, &aslave) < 0)
185 			exit(1);
186 
187 		fd = amaster;
188 	}
189 
190 
191 	/* Open RFCOMM connection */
192 	memset(&ra, 0, sizeof(ra));
193 	ra.rfcomm_len = sizeof(ra);
194 	ra.rfcomm_family = AF_BLUETOOTH;
195 
196 	s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
197 	if (s < 0)
198 		err(1, "Could not create socket");
199 
200 	if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
201 		err(1, "Could not bind socket");
202 
203 	memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
204 	ra.rfcomm_channel = channel;
205 
206 	if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
207 		err(1, "Could not connect socket");
208 
209 	/* Became daemon if required */
210 	if (background) {
211 		switch (fork()) {
212 		case -1:
213 			err(1, "Could not fork()");
214 			/* NOT REACHED */
215 
216 		case 0:
217 			exit(0);
218 			/* NOT REACHED */
219 
220 		default:
221 			if (daemon(0, 0) < 0)
222 				err(1, "Could not daemon()");
223 			break;
224 		}
225 	}
226 
227 	openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
228 	syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout");
229 
230 	for (done = 0; !done; ) {
231 		FD_ZERO(&rfd);
232 		FD_SET(amaster, &rfd);
233 		FD_SET(s, &rfd);
234 
235 		n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
236 		if (n < 0) {
237 			if (errno == EINTR)
238 				continue;
239 
240 			syslog(LOG_ERR, "Could not select(). %s",
241 					strerror(errno));
242 			exit(1);
243 		}
244 
245 		if (n == 0)
246 			continue;
247 
248 		if (FD_ISSET(amaster, &rfd)) {
249 			n = sppd_read(amaster, buf, sizeof(buf));
250 			if (n < 0) {
251 				syslog(LOG_ERR, "Could not read master pty, " \
252 					"fd=%d. %s", amaster, strerror(errno));
253 				exit(1);
254 			}
255 
256 			if (n == 0)
257 				break; /* XXX */
258 
259 			if (sppd_write(s, buf, n) < 0) {
260 				syslog(LOG_ERR, "Could not write to socket, " \
261 					"fd=%d, size=%d. %s",
262 					s, n, strerror(errno));
263 				exit(1);
264 			}
265 		}
266 
267 		if (FD_ISSET(s, &rfd)) {
268 			n = sppd_read(s, buf, sizeof(buf));
269 			if (n < 0) {
270 				syslog(LOG_ERR, "Could not read socket, " \
271 					"fd=%d. %s", s, strerror(errno));
272 				exit(1);
273 			}
274 
275 			if (n == 0)
276 				break;
277 
278 			if (sppd_write(fd, buf, n) < 0) {
279 				syslog(LOG_ERR, "Could not write to master " \
280 					"pty, fd=%d, size=%d. %s",
281 					fd, n, strerror(errno));
282 				exit(1);
283 			}
284 		}
285 	}
286 
287 	syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout");
288 	closelog();
289 
290 	close(s);
291 
292 	if (tty != NULL) {
293 		close(aslave);
294 		close(amaster);
295 	}
296 
297 	return (0);
298 }
299 
300 /* Open TTYs */
301 static int
302 sppd_ttys_open(char const *tty, int *amaster, int *aslave)
303 {
304 	char		 pty[PATH_MAX], *slash;
305 	struct group	*gr = NULL;
306 	gid_t		 ttygid;
307 	struct termios	 tio;
308 
309 	/*
310 	 * Construct master PTY name. The slave tty name must be less then
311 	 * PATH_MAX characters in length, must contain '/' character and
312 	 * must not end with '/'.
313 	 */
314 
315 	if (strlen(tty) >= sizeof(pty)) {
316 		syslog(LOG_ERR, "Slave tty name is too long");
317 		return (-1);
318 	}
319 
320 	strlcpy(pty, tty, sizeof(pty));
321 	slash = strrchr(pty, '/');
322 	if (slash == NULL || slash[1] == '\0') {
323 		syslog(LOG_ERR, "Invalid slave tty name (%s)", tty);
324 		return (-1);
325 	}
326 
327 	slash[1] = 'p';
328 
329 	if (strcmp(pty, tty) == 0) {
330 		syslog(LOG_ERR, "Master and slave tty are the same (%s)", tty);
331 		return (-1);
332 	}
333 
334 	if ((*amaster = open(pty, O_RDWR, 0)) < 0) {
335 		syslog(LOG_ERR, "Could not open(%s). %s", pty, strerror(errno));
336 		return (-1);
337 	}
338 
339 	/*
340 	 * Slave TTY
341 	 */
342 
343 	if ((gr = getgrnam("tty")) != NULL)
344 		ttygid = gr->gr_gid;
345 	else
346 		ttygid = -1;
347 
348 	(void) chown(tty, getuid(), ttygid);
349 	(void) chmod(tty, S_IRUSR|S_IWUSR|S_IWGRP);
350 	(void) revoke(tty);
351 
352 	if ((*aslave = open(tty, O_RDWR, 0)) < 0) {
353 		syslog(LOG_ERR, "Could not open(%s). %s", tty, strerror(errno));
354 		close(*amaster);
355 		return (-1);
356 	}
357 
358 	/*
359 	 * Make slave TTY raw
360 	 */
361 
362 	cfmakeraw(&tio);
363 
364 	if (tcsetattr(*aslave, TCSANOW, &tio) < 0) {
365 		syslog(LOG_ERR, "Could not tcsetattr(). %s", strerror(errno));
366 		close(*aslave);
367 		close(*amaster);
368 		return (-1);
369 	}
370 
371 	return (0);
372 } /* sppd_ttys_open */
373 
374 /* Read data */
375 static int
376 sppd_read(int fd, char *buffer, int size)
377 {
378 	int	n;
379 
380 again:
381 	n = read(fd, buffer, size);
382 	if (n < 0) {
383 		if (errno == EINTR)
384 			goto again;
385 
386 		return (-1);
387 	}
388 
389 	return (n);
390 } /* sppd_read */
391 
392 /* Write data */
393 static int
394 sppd_write(int fd, char *buffer, int size)
395 {
396 	int	n, wrote;
397 
398 	for (wrote = 0; size > 0; ) {
399 		n = write(fd, buffer, size);
400 		switch (n) {
401 		case -1:
402 			if (errno != EINTR)
403 				return (-1);
404 			break;
405 
406 		case 0:
407 			/* XXX can happen? */
408 			break;
409 
410 		default:
411 			wrote += n;
412 			buffer += n;
413 			size -= n;
414 			break;
415 		}
416 	}
417 
418 	return (wrote);
419 } /* sppd_write */
420 
421 /* Signal handler */
422 static void
423 sppd_sighandler(int s)
424 {
425 	syslog(LOG_INFO, "Signal %d received. Total %d signals received\n",
426 			s, ++ done);
427 } /* sppd_sighandler */
428 
429 /* Display usage and exit */
430 static void
431 usage(void)
432 {
433 	fprintf(stdout,
434 "Usage: %s options\n" \
435 "Where options are:\n" \
436 "\t-a address Address to connect to (required)\n" \
437 "\t-b         Run in background\n" \
438 "\t-c channel RFCOMM channel to connect to\n" \
439 "\t-t tty     TTY name (required in background mode)\n" \
440 "\t-h         Display this message\n", SPPD_IDENT);
441 
442 	exit(255);
443 } /* usage */
444 
445