Remove empty line.
[dragonfly.git] / usr.sbin / rfcomm_sppd / rfcomm_sppd.c
1 /* $NetBSD: rfcomm_sppd.c,v 1.8 2007/04/21 10:39:30 dsl Exp $ */
2 /* $DragonFly: src/usr.sbin/rfcomm_sppd/Attic/rfcomm_sppd.c,v 1.1 2008/01/30 14:25:35 hasso Exp $ */
3
4 /*-
5  * Copyright (c) 2006 Itronix Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of Itronix Inc. may not be used to endorse
17  *    or promote products derived from this software without specific
18  *    prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
24  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27  * ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 /*
33  * rfcomm_sppd.c
34  *
35  * Copyright (c) 2007 Iain Hibbert
36  * Copyright (c) 2003 Maksim Yevmenkin <m_evmenkin@yahoo.com>
37  * All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60
61 #include <bluetooth.h>
62 #include <ctype.h>
63 #include <err.h>
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <grp.h>
67 #include <limits.h>
68 #include <paths.h>
69 #include <sdp.h>
70 #include <signal.h>
71 #include <stdarg.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <syslog.h>
76 #include <termios.h>
77 #include <unistd.h>
78 #include <sys/stat.h>
79
80 #include <netbt/rfcomm.h>
81
82 #include "rfcomm_sdp.h"
83
84 #define max(a, b)       ((a) > (b) ? (a) : (b))
85
86 int open_tty(const char *);
87 int open_client(bdaddr_t *, bdaddr_t *, int, const char *);
88 int open_server(bdaddr_t *, uint8_t, int, const char *);
89 void copy_data(int, int);
90 void sighandler(int);
91 void usage(void);
92 void reset_tio(void);
93
94 int done;               /* got a signal */
95 struct termios tio;     /* stored termios for reset on exit */
96
97 struct service {
98         const char      *name;
99         const char      *description;
100         uint16_t        class;
101         int             pdulen;
102 } services[] = {
103         { "DUN",        "Dialup Networking",
104           SDP_SERVICE_CLASS_DIALUP_NETWORKING,
105           sizeof(struct sdp_dun_profile)
106         },
107         { "LAN",        "Lan access using PPP",
108           SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP,
109           sizeof(struct sdp_lan_profile)
110         },
111         { "SP",         "Serial Port",
112           SDP_SERVICE_CLASS_SERIAL_PORT,
113           sizeof(struct sdp_sp_profile)
114         },
115         { NULL,         NULL,
116           0,
117           0
118         }
119 };
120
121 int
122 main(int argc, char *argv[])
123 {
124         struct termios          t;
125         bdaddr_t                laddr, raddr;
126         fd_set                  rdset;
127         const char              *service;
128         char                    *ep, *tty;
129         int                     lm, n, rfcomm, tty_in, tty_out;
130         uint8_t                 channel;
131
132         bdaddr_copy(&laddr, BDADDR_ANY);
133         bdaddr_copy(&raddr, BDADDR_ANY);
134         service = "SP";
135         tty = NULL;
136         channel = 0;
137         lm = 0;
138
139         /* Parse command line options */
140         while ((n = getopt(argc, argv, "a:c:d:hm:s:t:")) != -1) {
141                 switch (n) {
142                 case 'a': /* remote device address */
143                         if (!bt_aton(optarg, &raddr)) {
144                                 struct hostent  *he = NULL;
145
146                                 if ((he = bt_gethostbyname(optarg)) == NULL)
147                                         errx(EXIT_FAILURE, "%s: %s", optarg,
148                                             hstrerror(h_errno));
149
150                                 bdaddr_copy(&raddr, (bdaddr_t *)he->h_addr);
151                         }
152                         break;
153
154                 case 'c': /* RFCOMM channel */
155                         channel = strtoul(optarg, &ep, 10);
156                         if (*ep != '\0' || channel < 1 || channel > 30)
157                                 errx(EXIT_FAILURE, "Invalid channel: %s", optarg);
158
159                         break;
160
161                 case 'd': /* local device address */
162                         if (!bt_devaddr(optarg, &laddr))
163                                 err(EXIT_FAILURE, "%s", optarg);
164
165                         break;
166
167                 case 'm': /* Link Mode */
168                         if (strcasecmp(optarg, "auth") == 0)
169                                 lm = RFCOMM_LM_AUTH;
170                         else if (strcasecmp(optarg, "encrypt") == 0)
171                                 lm = RFCOMM_LM_ENCRYPT;
172                         else if (strcasecmp(optarg, "secure") == 0)
173                                 lm = RFCOMM_LM_SECURE;
174                         else
175                                 errx(EXIT_FAILURE, "%s: unknown mode", optarg);
176
177                         break;
178
179                 case 's': /* service class */
180                         service = optarg;
181                         break;
182
183                 case 't': /* Slave TTY name */
184                         if (optarg[0] != '/')
185                                 asprintf(&tty, "%s%s", _PATH_DEV, optarg);
186                         else
187                                 tty = optarg;
188
189                         break;
190
191                 case 'h':
192                 default:
193                         usage();
194                         /* NOT REACHED */
195                 }
196         }
197
198         /*
199          * validate options:
200          *      must have channel or remote address but not both
201          */
202         if ((channel == 0 && bdaddr_any(&raddr))
203             || (channel != 0 && !bdaddr_any(&raddr)))
204                 usage();
205
206         /*
207          * grab ttys before we start the bluetooth
208          */
209         if (tty == NULL) {
210                 tty_in = STDIN_FILENO;
211                 tty_out = STDOUT_FILENO;
212         } else {
213                 tty_in = open_tty(tty);
214                 tty_out = tty_in;
215         }
216
217         /* open RFCOMM */
218         if (channel == 0)
219                 rfcomm = open_client(&laddr, &raddr, lm, service);
220         else
221                 rfcomm = open_server(&laddr, channel, lm, service);
222
223         /*
224          * now we are ready to go, so either detach or maybe turn
225          * off some input processing, so that rfcomm_sppd can
226          * be used directly with stdio
227          */
228         if (tty == NULL) {
229                 if (tcgetattr(tty_in, &t) < 0)
230                         err(EXIT_FAILURE, "tcgetattr");
231
232                 memcpy(&tio, &t, sizeof(tio));
233                 t.c_lflag &= ~(ECHO | ICANON);
234                 t.c_iflag &= ~(ICRNL);
235
236                 if (memcmp(&tio, &t, sizeof(tio))) {
237                         if (tcsetattr(tty_in, TCSANOW, &t) < 0)
238                                 err(EXIT_FAILURE, "tcsetattr");
239
240                         atexit(reset_tio);
241                 }
242         } else {
243                 if (daemon(0, 0) < 0)
244                         err(EXIT_FAILURE, "daemon() failed");
245         }
246
247         /* catch signals */
248         done = 0;
249         (void)signal(SIGHUP, sighandler);
250         (void)signal(SIGINT, sighandler);
251         (void)signal(SIGPIPE, sighandler);
252         (void)signal(SIGTERM, sighandler);
253
254         openlog(getprogname(), LOG_PERROR | LOG_PID, LOG_DAEMON);
255         syslog(LOG_INFO, "Starting on %s...", (tty ? tty : "stdio"));
256
257         n = max(tty_in, rfcomm) + 1;
258         while (!done) {
259                 FD_ZERO(&rdset);
260                 FD_SET(tty_in, &rdset);
261                 FD_SET(rfcomm, &rdset);
262
263                 if (select(n, &rdset, NULL, NULL, NULL) < 0) {
264                         if (errno == EINTR)
265                                 continue;
266
267                         syslog(LOG_ERR, "select error: %m");
268                         exit(EXIT_FAILURE);
269                 }
270
271                 if (FD_ISSET(tty_in, &rdset))
272                         copy_data(tty_in, rfcomm);
273
274                 if (FD_ISSET(rfcomm, &rdset))
275                         copy_data(rfcomm, tty_out);
276         }
277
278         syslog(LOG_INFO, "Completed on %s", (tty ? tty : "stdio"));
279         exit(EXIT_SUCCESS);
280 }
281
282 int
283 open_tty(const char *tty)
284 {
285         char             pty[PATH_MAX], *slash;
286         struct group    *gr = NULL;
287         gid_t            ttygid;
288         int              master;
289
290         /*
291          * Construct master PTY name. The slave tty name must be less then
292          * PATH_MAX characters in length, must contain '/' character and
293          * must not end with '/'.
294          */
295         if (strlen(tty) >= sizeof(pty))
296                 errx(EXIT_FAILURE, ": tty name too long");
297
298         strlcpy(pty, tty, sizeof(pty));
299         slash = strrchr(pty, '/');
300         if (slash == NULL || slash[1] == '\0')
301                 errx(EXIT_FAILURE, "%s: invalid tty", tty);
302
303         slash[1] = 'p';
304         if (strcmp(pty, tty) == 0)
305                 errx(EXIT_FAILURE, "Master and slave tty are the same (%s)", tty);
306
307         if ((master = open(pty, O_RDWR, 0)) < 0)
308                 err(EXIT_FAILURE, "%s", pty);
309
310         /*
311          * Slave TTY
312          */
313
314         if ((gr = getgrnam("tty")) != NULL)
315                 ttygid = gr->gr_gid;
316         else
317                 ttygid = (gid_t)-1;
318
319         (void)chown(tty, getuid(), ttygid);
320         (void)chmod(tty, S_IRUSR | S_IWUSR | S_IWGRP);
321         (void)revoke(tty);
322
323         return master;
324 }
325
326 int
327 open_client(bdaddr_t *laddr, bdaddr_t *raddr, int lm, const char *service)
328 {
329         struct sockaddr_bt sa;
330         struct service *s;
331         struct linger l;
332         char *ep;
333         int fd;
334         uint8_t channel;
335
336         for (s = services ; ; s++) {
337                 if (s->name == NULL) {
338                         channel = strtoul(service, &ep, 10);
339                         if (*ep != '\0' || channel < 1 || channel > 30)
340                                 errx(EXIT_FAILURE, "Invalid service: %s", service);
341
342                         break;
343                 }
344
345                 if (strcasecmp(s->name, service) == 0) {
346                         if (rfcomm_channel_lookup(laddr, raddr, s->class, &channel, &errno) < 0)
347                                 err(EXIT_FAILURE, "%s", s->name);
348
349                         break;
350                 }
351         }
352
353         memset(&sa, 0, sizeof(sa));
354         sa.bt_len = sizeof(sa);
355         sa.bt_family = AF_BLUETOOTH;
356         bdaddr_copy(&sa.bt_bdaddr, laddr);
357
358         fd = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
359         if (fd < 0)
360                 err(EXIT_FAILURE, "socket()");
361
362         if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
363                 err(EXIT_FAILURE, "bind(%s)", bt_ntoa(laddr, NULL));
364
365         memset(&l, 0, sizeof(l));
366         l.l_onoff = 1;
367         l.l_linger = 5;
368         if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0)
369                 err(EXIT_FAILURE, "linger()");
370
371         if (setsockopt(fd, BTPROTO_RFCOMM, SO_RFCOMM_LM, &lm, sizeof(lm)) < 0)
372                 err(EXIT_FAILURE, "link mode");
373
374         sa.bt_channel = channel;
375         bdaddr_copy(&sa.bt_bdaddr, raddr);
376
377         if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)
378                 err(EXIT_FAILURE, "connect(%s, %d)", bt_ntoa(raddr, NULL),
379                                                      channel);
380
381         return fd;
382 }
383
384 /*
385  * In all the profiles we currently support registering, the channel
386  * is the first octet in the PDU, and it seems all the rest can be
387  * zero, so we just use an array of uint8_t big enough to store the
388  * largest, currently LAN. See <sdp.h> for definitions..
389  */
390 #define pdu_len         sizeof(struct sdp_lan_profile)
391
392 int
393 open_server(bdaddr_t *laddr, uint8_t channel, int lm, const char *service)
394 {
395         struct sockaddr_bt sa;
396         struct linger l;
397         socklen_t len;
398         void *ss;
399         int sv, fd, n;
400         uint8_t pdu[pdu_len];
401
402         memset(&sa, 0, sizeof(sa));
403         sa.bt_len = sizeof(sa);
404         sa.bt_family = AF_BLUETOOTH;
405         bdaddr_copy(&sa.bt_bdaddr, laddr);
406         sa.bt_channel = channel;
407
408         sv = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
409         if (sv < 0)
410                 err(EXIT_FAILURE, "socket()");
411
412         if (bind(sv, (struct sockaddr *)&sa, sizeof(sa)) < 0)
413                 err(EXIT_FAILURE, "bind(%s, %d)", bt_ntoa(laddr, NULL),
414                                                   channel);
415
416         if (setsockopt(sv, BTPROTO_RFCOMM, SO_RFCOMM_LM, &lm, sizeof(lm)) < 0)
417                 err(EXIT_FAILURE, "link mode");
418
419         if (listen(sv, 1) < 0)
420                 err(EXIT_FAILURE, "listen()");
421
422         /* Register service with SDP server */
423         for (n = 0 ; ; n++) {
424                 if (services[n].name == NULL)
425                         usage();
426
427                 if (strcasecmp(services[n].name, service) == 0)
428                         break;
429         }
430
431         memset(pdu, 0, pdu_len);
432         pdu[0] = channel;
433
434         ss = sdp_open_local(NULL);
435         if (ss == NULL || (errno = sdp_error(ss)) != 0)
436                 err(EXIT_FAILURE, "sdp_open_local");
437
438         if (sdp_register_service(ss, services[n].class, laddr,
439                     pdu, services[n].pdulen, NULL) != 0) {
440                 errno = sdp_error(ss);
441                 err(EXIT_FAILURE, "sdp_register_service");
442         }
443
444         len = sizeof(sa);
445         fd = accept(sv, (struct sockaddr *)&sa, &len);
446         if (fd < 0)
447                 err(EXIT_FAILURE, "accept");
448
449         memset(&l, 0, sizeof(l));
450         l.l_onoff = 1;
451         l.l_linger = 5;
452         if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof(l)) < 0)
453                 err(EXIT_FAILURE, "linger()");
454
455         close(sv);
456         return fd;
457 }
458
459 void
460 copy_data(int src, int dst)
461 {
462         static char     buf[BUFSIZ];
463         ssize_t         nr, nw, off;
464
465         while ((nr = read(src, buf, sizeof(buf))) == -1) {
466                 if (errno != EINTR) {
467                         syslog(LOG_ERR, "read failed: %m");
468                         exit(EXIT_FAILURE);
469                 }
470         }
471
472         if (nr == 0)    /* reached EOF */
473                 done++;
474
475         for (off = 0 ; nr ; nr -= nw, off += nw) {
476                 if ((nw = write(dst, buf + off, (size_t)nr)) == -1) {
477                         syslog(LOG_ERR, "write failed: %m");
478                         exit(EXIT_FAILURE);
479                 }
480         }
481 }
482
483 void
484 sighandler(int s)
485 {
486
487         done++;
488 }
489
490 void
491 reset_tio(void)
492 {
493
494         tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
495 }
496
497 void
498 usage(void)
499 {
500         const char *cmd = getprogname();
501         struct service *s;
502
503         fprintf(stderr, "Usage: %s [-d device] [-m mode] [-s service] [-t tty]\n"
504                         "       %*s {-a bdaddr | -c channel}\n"
505                         "\n"
506                         "Where:\n"
507                         "\t-a bdaddr    remote device address\n"
508                         "\t-c channel   local RFCOMM channel\n"
509                         "\t-d device    local device address\n"
510                         "\t-m mode      link mode\n"
511                         "\t-s service   service class\n"
512                         "\t-t tty       run in background using pty\n"
513                         "\n", cmd, (int)strlen(cmd), "");
514
515         fprintf(stderr, "Known service classes:\n");
516         for (s = services ; s->name != NULL ; s++)
517                 fprintf(stderr, "\t%-13s%s\n", s->name, s->description);
518
519         exit(EXIT_FAILURE);
520 }