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