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