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