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