rfcomm_sppd.c revision 123676
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 123676 2003-12-19 18:15:56Z 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;
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 (tty == NULL || 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 (sppd_ttys_open(tty, &amaster, &aslave) < 0)
150		exit(1);
151
152	/* Open RFCOMM connection */
153	memset(&ra, 0, sizeof(ra));
154	ra.rfcomm_len = sizeof(ra);
155	ra.rfcomm_family = AF_BLUETOOTH;
156
157	s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
158	if (s < 0)
159		err(1, "Could not create socket");
160
161	if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
162		err(1, "Could not bind socket");
163
164	memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
165	ra.rfcomm_channel = channel;
166
167	if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
168		err(1, "Could not connect socket");
169
170	/* Became daemon if required */
171	if (background) {
172		switch (fork()) {
173		case -1:
174			err(1, "Could not fork()");
175			/* NOT REACHED */
176
177		case 0:
178			exit(0);
179			/* NOT REACHED */
180
181		default:
182			if (daemon(0, 0) < 0)
183				err(1, "Could not daemon()");
184			break;
185		}
186	}
187
188	openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
189	syslog(LOG_INFO, "Starting on %s...", tty);
190
191	for (done = 0; !done; ) {
192		FD_ZERO(&rfd);
193		FD_SET(amaster, &rfd);
194		FD_SET(s, &rfd);
195
196		n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
197		if (n < 0) {
198			if (errno == EINTR)
199				continue;
200
201			syslog(LOG_ERR, "Could not select(). %s",
202					strerror(errno));
203			exit(1);
204		}
205
206		if (n == 0)
207			continue;
208
209		if (FD_ISSET(amaster, &rfd)) {
210			n = sppd_read(amaster, buf, sizeof(buf));
211			if (n < 0) {
212				syslog(LOG_ERR, "Could not read master pty, " \
213					"fd=%d. %s", amaster, strerror(errno));
214				exit(1);
215			}
216
217			if (n == 0)
218				break; /* XXX */
219
220			if (sppd_write(s, buf, n) < 0) {
221				syslog(LOG_ERR, "Could not write to socket, " \
222					"fd=%d, size=%d. %s",
223					s, n, strerror(errno));
224				exit(1);
225			}
226		}
227
228		if (FD_ISSET(s, &rfd)) {
229			n = sppd_read(s, buf, sizeof(buf));
230			if (n < 0) {
231				syslog(LOG_ERR, "Could not read socket, " \
232					"fd=%d. %s", s, strerror(errno));
233				exit(1);
234			}
235
236			if (n == 0)
237				break;
238
239			if (sppd_write(amaster, buf, n) < 0) {
240				syslog(LOG_ERR, "Could not write to master " \
241					"pty, fd=%d, size=%d. %s",
242					amaster, n, strerror(errno));
243				exit(1);
244			}
245		}
246	}
247
248	syslog(LOG_INFO, "Completed on %s", tty);
249	closelog();
250
251	close(s);
252	close(aslave);
253	close(amaster);
254
255	return (0);
256}
257
258/* Open TTYs */
259static int
260sppd_ttys_open(char const *tty, int *amaster, int *aslave)
261{
262	char		 pty[PATH_MAX], *slash = NULL;
263	struct group	*gr = NULL;
264	gid_t		 ttygid;
265	struct termios	 tio;
266
267	/*
268	 * Construct master PTY name. The slave tty name must be less then
269	 * PATH_MAX characters in length, must contain '/' character and
270	 * must not end with '/'.
271	 */
272
273	if (strlen(tty) >= sizeof(pty)) {
274		syslog(LOG_ERR, "Slave tty name is too long");
275		return (-1);
276	}
277
278	strlcpy(pty, tty, sizeof(pty));
279	slash = strrchr(pty, '/');
280	if (slash == NULL || slash[1] == 0) {
281		syslog(LOG_ERR, "Invalid slave tty name (%s)", tty);
282		return (-1);
283	}
284
285	slash[1] = 'p';
286
287	if (strcmp(pty, tty) == 0) {
288		syslog(LOG_ERR, "Master and slave tty are the same (%s)", tty);
289		return (-1);
290	}
291
292	if ((*amaster = open(pty, O_RDWR, 0)) < 0) {
293		syslog(LOG_ERR, "Could not open(%s). %s", pty, strerror(errno));
294		return (-1);
295	}
296
297	/*
298	 * Slave TTY
299	 */
300
301	if ((gr = getgrnam("tty")) != NULL)
302		ttygid = gr->gr_gid;
303	else
304		ttygid = -1;
305
306	(void) chown(tty, getuid(), ttygid);
307	(void) chmod(tty, S_IRUSR|S_IWUSR|S_IWGRP);
308	(void) revoke(tty);
309
310	if ((*aslave = open(tty, O_RDWR, 0)) < 0) {
311		syslog(LOG_ERR, "Could not open(%s). %s", tty, strerror(errno));
312		close(*amaster);
313		return (-1);
314	}
315
316	/*
317	 * Make slave TTY raw
318	 */
319
320	cfmakeraw(&tio);
321
322	if (tcsetattr(*aslave, TCSANOW, &tio) < 0) {
323		syslog(LOG_ERR, "Could not tcsetattr(). %s", strerror(errno));
324		close(*aslave);
325		close(*amaster);
326		return (-1);
327	}
328
329	return (0);
330} /* sppd_ttys_open */
331
332/* Read data */
333static int
334sppd_read(int fd, char *buffer, int size)
335{
336	int	n;
337
338again:
339	n = read(fd, buffer, size);
340	if (n < 0) {
341		if (errno == EINTR)
342			goto again;
343
344		return (-1);
345	}
346
347	return (n);
348} /* sppd_read */
349
350/* Write data */
351static int
352sppd_write(int fd, char *buffer, int size)
353{
354	int	n, wrote;
355
356	for (wrote = 0; size > 0; ) {
357		n = write(fd, buffer, size);
358		switch (n) {
359		case -1:
360			if (errno != EINTR)
361				return (-1);
362			break;
363
364		case 0:
365			/* XXX can happen? */
366			break;
367
368		default:
369			wrote += n;
370			buffer += n;
371			size -= n;
372			break;
373		}
374	}
375
376	return (wrote);
377} /* sppd_write */
378
379/* Signal handler */
380static void
381sppd_sighandler(int s)
382{
383	syslog(LOG_INFO, "Signal %d received. Total %d signals received\n",
384			s, ++ done);
385} /* sppd_sighandler */
386
387/* Display usage and exit */
388static void
389usage(void)
390{
391	fprintf(stdout,
392"Usage: %s options\n" \
393"Where options are:\n" \
394"\t-a bdaddr  BDADDR to connect to (required)\n" \
395"\t-b         Run in background\n" \
396"\t-c channel RFCOMM channel to connect to\n" \
397"\t-t tty     TTY name\n" \
398"\t-h         Display this message\n", SPPD_IDENT);
399
400	exit(255);
401} /* usage */
402
403