xref: /freebsd/usr.bin/bluetooth/rfcomm_sppd/rfcomm_sppd.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
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 <sys/types.h>
36 #define L2CAP_SOCKET_CHECKED
37 #include <bluetooth.h>
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <grp.h>
43 #include <limits.h>
44 #include <paths.h>
45 #include <sdp.h>
46 #include <signal.h>
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <syslog.h>
52 #include <termios.h>
53 #include <unistd.h>
54 #include <libutil.h>
55 
56 #define SPPD_IDENT		"rfcomm_sppd"
57 #define SPPD_BUFFER_SIZE	1024
58 #define max(a, b)		(((a) > (b))? (a) : (b))
59 
60 int		rfcomm_channel_lookup	(bdaddr_t const *local,
61 					 bdaddr_t const *remote,
62 					 int service, int *channel, int *error);
63 
64 static int	sppd_ttys_open	(char **tty, int *amaster, int *aslave);
65 static int	sppd_read	(int fd, char *buffer, int size);
66 static int	sppd_write	(int fd, char *buffer, int size);
67 static void	sppd_sighandler	(int s);
68 static void	usage		(void);
69 
70 static int	done;	/* are we done? */
71 
72 /* Main */
73 int
74 main(int argc, char *argv[])
75 {
76 	struct sigaction	 sa;
77 	struct sockaddr_rfcomm	 ra;
78 	bdaddr_t		 addr;
79 	int			 n, background, channel, service,
80 				 s, amaster, aslave, fd, doserver,
81 				 dopty;
82 	fd_set			 rfd;
83 	char			*tty = NULL, *ep = NULL, buf[SPPD_BUFFER_SIZE];
84 
85 	memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr));
86 	background = channel = 0;
87 	service = SDP_SERVICE_CLASS_SERIAL_PORT;
88 	doserver = 0;
89 	dopty = 0;
90 
91 	/* Parse command line options */
92 	while ((n = getopt(argc, argv, "a:bc:thS")) != -1) {
93 		switch (n) {
94 		case 'a': /* BDADDR */
95 			if (!bt_aton(optarg, &addr)) {
96 				struct hostent	*he = NULL;
97 
98 				if ((he = bt_gethostbyname(optarg)) == NULL)
99 					errx(1, "%s: %s", optarg, hstrerror(h_errno));
100 
101 				memcpy(&addr, he->h_addr, sizeof(addr));
102 			}
103 			break;
104 
105 		case 'c': /* RFCOMM channel */
106 			channel = strtoul(optarg, &ep, 10);
107 			if (*ep != '\0') {
108 				channel = 0;
109 				switch (tolower(optarg[0])) {
110 				case 'd': /* DialUp Networking */
111 					service = SDP_SERVICE_CLASS_DIALUP_NETWORKING;
112 					break;
113 
114 				case 'f': /* Fax */
115 					service = SDP_SERVICE_CLASS_FAX;
116 					break;
117 
118 				case 'l': /* LAN */
119 					service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP;
120 					break;
121 
122 				case 's': /* Serial Port */
123 					service = SDP_SERVICE_CLASS_SERIAL_PORT;
124 					break;
125 
126 				default:
127 					errx(1, "Unknown service name: %s",
128 						optarg);
129 					/* NOT REACHED */
130 				}
131 			}
132 			break;
133 
134 		case 'b': /* Run in background */
135 			background = 1;
136 			break;
137 
138 		case 't': /* Open pseudo TTY */
139 			dopty = 1;
140 			break;
141 
142 		case 'S':
143 			doserver = 1;
144 			break;
145 
146 		case 'h':
147 		default:
148 			usage();
149 			/* NOT REACHED */
150 		}
151 	}
152 
153 	/* Check if we have everything we need */
154 	if (!doserver && memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0)
155 		usage();
156 		/* NOT REACHED */
157 
158 	/* Set signal handlers */
159 	memset(&sa, 0, sizeof(sa));
160 	sa.sa_handler = sppd_sighandler;
161 
162 	if (sigaction(SIGTERM, &sa, NULL) < 0)
163 		err(1, "Could not sigaction(SIGTERM)");
164 
165 	if (sigaction(SIGHUP, &sa, NULL) < 0)
166 		err(1, "Could not sigaction(SIGHUP)");
167 
168 	if (sigaction(SIGINT, &sa, NULL) < 0)
169 		err(1, "Could not sigaction(SIGINT)");
170 
171 	sa.sa_handler = SIG_IGN;
172 	sa.sa_flags = SA_NOCLDWAIT;
173 
174 	if (sigaction(SIGCHLD, &sa, NULL) < 0)
175 		err(1, "Could not sigaction(SIGCHLD)");
176 
177 	/* Open TTYs */
178 	if (dopty) {
179 		if (sppd_ttys_open(&tty, &amaster, &aslave) < 0)
180 			exit(1);
181 
182 		fd = amaster;
183 	} else {
184 		if (background)
185 			usage();
186 
187 		amaster = STDIN_FILENO;
188 		fd = STDOUT_FILENO;
189 	}
190 
191 	/* Open RFCOMM connection */
192 
193 	if (doserver) {
194 		struct sockaddr_rfcomm	 ma;
195 		bdaddr_t		 bt_addr_any;
196 		sdp_sp_profile_t	 sp;
197 		void			*ss;
198 		uint32_t		 sdp_handle;
199 		int			 acceptsock, aaddrlen;
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 		memcpy(&bt_addr_any, NG_HCI_BDADDR_ANY, sizeof(bt_addr_any));
207 
208 		memset(&ma, 0, sizeof(ma));
209 		ma.rfcomm_len = sizeof(ma);
210 		ma.rfcomm_family = AF_BLUETOOTH;
211 		memcpy(&ma.rfcomm_bdaddr, &bt_addr_any, sizeof(bt_addr_any));
212 		ma.rfcomm_channel = channel;
213 
214 		if (bind(acceptsock, (struct sockaddr *)&ma, sizeof(ma)) < 0)
215 			err(1, "Could not bind socket on channel %d", channel);
216 		if (listen(acceptsock, 10) != 0)
217 			err(1, "Could not listen on socket");
218 
219 		aaddrlen = sizeof(ma);
220 		if (getsockname(acceptsock, (struct sockaddr *)&ma, &aaddrlen) < 0)
221 			err(1, "Could not get socket name");
222 		channel = ma.rfcomm_channel;
223 
224 		ss = sdp_open_local(NULL);
225 		if (ss == NULL)
226 			errx(1, "Unable to create local SDP session");
227 		if (sdp_error(ss) != 0)
228 			errx(1, "Unable to open local SDP session. %s (%d)",
229 			    strerror(sdp_error(ss)), sdp_error(ss));
230 		memset(&sp, 0, sizeof(sp));
231 		sp.server_channel = channel;
232 
233 		if (sdp_register_service(ss, SDP_SERVICE_CLASS_SERIAL_PORT,
234 				&bt_addr_any, (void *)&sp, sizeof(sp),
235 				&sdp_handle) != 0) {
236 			errx(1, "Unable to register LAN service with "
237 			    "local SDP daemon. %s (%d)",
238 			    strerror(sdp_error(ss)), sdp_error(ss));
239 		}
240 
241 		s = -1;
242 		while (s < 0) {
243 			aaddrlen = sizeof(ra);
244 			s = accept(acceptsock, (struct sockaddr *)&ra,
245 			    &aaddrlen);
246 			if (s < 0)
247 				err(1, "Unable to accept()");
248 			if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) &&
249 			    memcmp(&addr, &ra.rfcomm_bdaddr, sizeof(addr))) {
250 				warnx("Connect from wrong client");
251 				close(s);
252 				s = -1;
253 			}
254 		}
255 		sdp_unregister_service(ss, sdp_handle);
256 		sdp_close(ss);
257 		close(acceptsock);
258 	} else {
259 		/* Check channel, if was not set then obtain it via SDP */
260 		if (channel == 0 && service != 0)
261 			if (rfcomm_channel_lookup(NULL, &addr,
262 				    service, &channel, &n) != 0)
263 				errc(1, n, "Could not obtain RFCOMM channel");
264 		if (channel <= 0 || channel > 30)
265 			errx(1, "Invalid RFCOMM channel number %d", channel);
266 
267 		s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
268 		if (s < 0)
269 			err(1, "Could not create socket");
270 
271 		memset(&ra, 0, sizeof(ra));
272 		ra.rfcomm_len = sizeof(ra);
273 		ra.rfcomm_family = AF_BLUETOOTH;
274 
275 		if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
276 			err(1, "Could not bind socket");
277 
278 		memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
279 		ra.rfcomm_channel = channel;
280 
281 		if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
282 			err(1, "Could not connect socket");
283 	}
284 
285 	/* Became daemon if required */
286 	if (background && daemon(0, 0) < 0)
287 		err(1, "Could not daemon()");
288 
289 	openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
290 	syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout");
291 
292 	/* Print used tty on stdout for wrappers to pick up */
293 	if (!background)
294 		fprintf(stdout, "%s\n", tty);
295 
296 	for (done = 0; !done; ) {
297 		FD_ZERO(&rfd);
298 		FD_SET(amaster, &rfd);
299 		FD_SET(s, &rfd);
300 
301 		n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
302 		if (n < 0) {
303 			if (errno == EINTR)
304 				continue;
305 
306 			syslog(LOG_ERR, "Could not select(). %s",
307 					strerror(errno));
308 			exit(1);
309 		}
310 
311 		if (n == 0)
312 			continue;
313 
314 		if (FD_ISSET(amaster, &rfd)) {
315 			n = sppd_read(amaster, buf, sizeof(buf));
316 			if (n < 0) {
317 				syslog(LOG_ERR, "Could not read master pty, " \
318 					"fd=%d. %s", amaster, strerror(errno));
319 				exit(1);
320 			}
321 
322 			if (n == 0)
323 				break; /* XXX */
324 
325 			if (sppd_write(s, buf, n) < 0) {
326 				syslog(LOG_ERR, "Could not write to socket, " \
327 					"fd=%d, size=%d. %s",
328 					s, n, strerror(errno));
329 				exit(1);
330 			}
331 		}
332 
333 		if (FD_ISSET(s, &rfd)) {
334 			n = sppd_read(s, buf, sizeof(buf));
335 			if (n < 0) {
336 				syslog(LOG_ERR, "Could not read socket, " \
337 					"fd=%d. %s", s, strerror(errno));
338 				exit(1);
339 			}
340 
341 			if (n == 0)
342 				break;
343 
344 			if (sppd_write(fd, buf, n) < 0) {
345 				syslog(LOG_ERR, "Could not write to master " \
346 					"pty, fd=%d, size=%d. %s",
347 					fd, n, strerror(errno));
348 				exit(1);
349 			}
350 		}
351 	}
352 
353 	syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout");
354 	closelog();
355 
356 	close(s);
357 
358 	if (tty != NULL) {
359 		close(aslave);
360 		close(amaster);
361 	}
362 
363 	return (0);
364 }
365 
366 /* Open TTYs */
367 static int
368 sppd_ttys_open(char **tty, int *amaster, int *aslave)
369 {
370 	char		 pty[PATH_MAX];
371 	struct termios	 tio;
372 
373 	cfmakeraw(&tio);
374 
375 	if (openpty(amaster, aslave, pty, &tio, NULL) == -1) {
376 		syslog(LOG_ERR, "Could not openpty(). %s", strerror(errno));
377 		return (-1);
378 	}
379 
380 	if ((*tty = strdup(pty)) == NULL) {
381 		syslog(LOG_ERR, "Could not strdup(). %s", strerror(errno));
382 		close(*aslave);
383 		close(*amaster);
384 		return (-1);
385 	}
386 
387 	return (0);
388 } /* sppd_ttys_open */
389 
390 /* Read data */
391 static int
392 sppd_read(int fd, char *buffer, int size)
393 {
394 	int	n;
395 
396 again:
397 	n = read(fd, buffer, size);
398 	if (n < 0) {
399 		if (errno == EINTR)
400 			goto again;
401 
402 		return (-1);
403 	}
404 
405 	return (n);
406 } /* sppd_read */
407 
408 /* Write data */
409 static int
410 sppd_write(int fd, char *buffer, int size)
411 {
412 	int	n, wrote;
413 
414 	for (wrote = 0; size > 0; ) {
415 		n = write(fd, buffer, size);
416 		switch (n) {
417 		case -1:
418 			if (errno != EINTR)
419 				return (-1);
420 			break;
421 
422 		case 0:
423 			/* XXX can happen? */
424 			break;
425 
426 		default:
427 			wrote += n;
428 			buffer += n;
429 			size -= n;
430 			break;
431 		}
432 	}
433 
434 	return (wrote);
435 } /* sppd_write */
436 
437 /* Signal handler */
438 static void
439 sppd_sighandler(int s)
440 {
441 	syslog(LOG_INFO, "Signal %d received. Total %d signals received\n",
442 			s, ++ done);
443 } /* sppd_sighandler */
444 
445 /* Display usage and exit */
446 static void
447 usage(void)
448 {
449 	fprintf(stdout,
450 "Usage: %s options\n" \
451 "Where options are:\n" \
452 "\t-a address Peer address (required in client mode)\n" \
453 "\t-b         Run in background\n" \
454 "\t-c channel RFCOMM channel to connect to or listen on\n" \
455 "\t-t         use slave pseudo tty (required in background mode)\n" \
456 "\t-S         Server mode\n" \
457 "\t-h         Display this message\n", SPPD_IDENT);
458 	exit(255);
459 } /* usage */
460 
461