]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - 6/usr.bin/bluetooth/rfcomm_sppd/rfcomm_sppd.c
merge fix for boot-time hang on centos' xen
[FreeBSD/FreeBSD.git] / 6 / usr.bin / bluetooth / rfcomm_sppd / rfcomm_sppd.c
1 /*
2  * rfcomm_sppd.c
3  */
4
5 /*-
6  * Copyright (c) 2003 Maksim Yevmenkin <m_evmenkin@yahoo.com>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $Id: rfcomm_sppd.c,v 1.4 2003/09/07 18:15:55 max Exp $
31  * $FreeBSD$
32  */
33
34 #include <sys/stat.h>
35 #include <bluetooth.h>
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <grp.h>
41 #include <limits.h>
42 #include <paths.h>
43 #include <sdp.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <syslog.h>
50 #include <termios.h>
51 #include <unistd.h>
52
53 #define SPPD_IDENT              "rfcomm_sppd"
54 #define SPPD_BUFFER_SIZE        1024
55 #define max(a, b)               (((a) > (b))? (a) : (b))
56
57 int             rfcomm_channel_lookup   (bdaddr_t const *local,
58                                          bdaddr_t const *remote, 
59                                          int service, int *channel, int *error);
60
61 static int      sppd_ttys_open  (char const *tty, int *amaster, int *aslave);
62 static int      sppd_read       (int fd, char *buffer, int size);
63 static int      sppd_write      (int fd, char *buffer, int size);
64 static void     sppd_sighandler (int s);
65 static void     usage           (void);
66
67 static int      done;   /* are we done? */
68
69 /* Main */
70 int
71 main(int argc, char *argv[]) 
72 {
73         struct sigaction         sa;
74         struct sockaddr_rfcomm   ra;
75         bdaddr_t                 addr;
76         int                      n, background, channel, service,
77                                  s, amaster, aslave, fd, doserver;
78         fd_set                   rfd;
79         char                    *tty = NULL, *ep = NULL, buf[SPPD_BUFFER_SIZE];
80
81         memcpy(&addr, NG_HCI_BDADDR_ANY, sizeof(addr));
82         background = channel = 0;
83         service = SDP_SERVICE_CLASS_SERIAL_PORT;
84         doserver = 0;
85
86         /* Parse command line options */
87         while ((n = getopt(argc, argv, "a:bc:t:hS")) != -1) {
88                 switch (n) { 
89                 case 'a': /* BDADDR */
90                         if (!bt_aton(optarg, &addr)) {
91                                 struct hostent  *he = NULL;
92
93                                 if ((he = bt_gethostbyname(optarg)) == NULL)
94                                         errx(1, "%s: %s", optarg, hstrerror(h_errno));
95
96                                 memcpy(&addr, he->h_addr, sizeof(addr));
97                         }
98                         break;
99
100                 case 'c': /* RFCOMM channel */
101                         channel = strtoul(optarg, &ep, 10);
102                         if (*ep != '\0') {
103                                 channel = 0;
104                                 switch (tolower(optarg[0])) {
105                                 case 'd': /* DialUp Networking */
106                                         service = SDP_SERVICE_CLASS_DIALUP_NETWORKING;
107                                         break;
108
109                                 case 'f': /* Fax */
110                                         service = SDP_SERVICE_CLASS_FAX;
111                                         break;
112
113                                 case 'l': /* LAN */
114                                         service = SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP;
115                                         break;
116
117                                 case 's': /* Serial Port */
118                                         service = SDP_SERVICE_CLASS_SERIAL_PORT;
119                                         break;
120
121                                 default:
122                                         errx(1, "Unknown service name: %s",
123                                                 optarg);
124                                         /* NOT REACHED */
125                                 }
126                         }
127                         break;
128
129                 case 'b': /* Run in background */
130                         background = 1;
131                         break;
132
133                 case 't': /* Slave TTY name */
134                         if (optarg[0] != '/')
135                                 asprintf(&tty, "%s%s", _PATH_DEV, optarg);
136                         else
137                                 tty = optarg;
138                         break;
139
140                 case 'S':
141                         doserver = 1;
142                         break;
143
144                 case 'h':
145                 default:
146                         usage();
147                         /* NOT REACHED */
148                 }
149         }
150
151         /* Check if we have everything we need */
152         if (!doserver && memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) == 0)
153                 usage();
154                 /* NOT REACHED */
155
156         /* Set signal handlers */
157         memset(&sa, 0, sizeof(sa));
158         sa.sa_handler = sppd_sighandler;
159
160         if (sigaction(SIGTERM, &sa, NULL) < 0)
161                 err(1, "Could not sigaction(SIGTERM)");
162  
163         if (sigaction(SIGHUP, &sa, NULL) < 0)
164                 err(1, "Could not sigaction(SIGHUP)");
165  
166         if (sigaction(SIGINT, &sa, NULL) < 0)
167                 err(1, "Could not sigaction(SIGINT)");
168
169         sa.sa_handler = SIG_IGN;
170         sa.sa_flags = SA_NOCLDWAIT;
171
172         if (sigaction(SIGCHLD, &sa, NULL) < 0)
173                 err(1, "Could not sigaction(SIGCHLD)");
174
175         /* Open TTYs */
176         if (tty == NULL) {
177                 if (background)
178                         usage();
179
180                 amaster = STDIN_FILENO;
181                 fd = STDOUT_FILENO;
182         } else {
183                 if (sppd_ttys_open(tty, &amaster, &aslave) < 0)
184                         exit(1);
185                 
186                 fd = amaster;
187         }               
188
189         /* Open RFCOMM connection */
190
191         if (doserver) {
192                 struct sockaddr_rfcomm   ma;
193                 bdaddr_t                 bt_addr_any;
194                 sdp_sp_profile_t         sp;
195                 void                    *ss;
196                 uint32_t                 sdp_handle;
197                 int                      acceptsock, aaddrlen;
198
199                 acceptsock = socket(PF_BLUETOOTH, SOCK_STREAM,
200                                         BLUETOOTH_PROTO_RFCOMM);
201                 if (acceptsock < 0)
202                         err(1, "Could not create socket");
203
204                 memcpy(&bt_addr_any, NG_HCI_BDADDR_ANY, sizeof(bt_addr_any));
205
206                 memset(&ma, 0, sizeof(ma));
207                 ma.rfcomm_len = sizeof(ma);
208                 ma.rfcomm_family = AF_BLUETOOTH;
209                 memcpy(&ma.rfcomm_bdaddr, &bt_addr_any, sizeof(bt_addr_any));
210                 ma.rfcomm_channel = channel;
211
212                 if (bind(acceptsock, (struct sockaddr *)&ma, sizeof(ma)) < 0)
213                         err(1, "Could not bind socket on channel %d", channel);
214                 if (listen(acceptsock, 10) != 0)
215                         err(1, "Could not listen on socket");
216
217                 aaddrlen = sizeof(ma);
218                 if (getsockname(acceptsock, (struct sockaddr *)&ma, &aaddrlen) < 0)
219                         err(1, "Could not get socket name");
220                 channel = ma.rfcomm_channel;
221
222                 ss = sdp_open_local(NULL);
223                 if (ss == NULL)
224                         errx(1, "Unable to create local SDP session");
225                 if (sdp_error(ss) != 0)
226                         errx(1, "Unable to open local SDP session. %s (%d)",
227                             strerror(sdp_error(ss)), sdp_error(ss));
228                 memset(&sp, 0, sizeof(sp));
229                 sp.server_channel = channel;
230
231                 if (sdp_register_service(ss, SDP_SERVICE_CLASS_SERIAL_PORT,
232                                 &bt_addr_any, (void *)&sp, sizeof(sp),
233                                 &sdp_handle) != 0) {
234                         errx(1, "Unable to register LAN service with "
235                             "local SDP daemon. %s (%d)",
236                             strerror(sdp_error(ss)), sdp_error(ss));
237                 }
238
239                 s = -1;
240                 while (s < 0) {
241                         aaddrlen = sizeof(ra);
242                         s = accept(acceptsock, (struct sockaddr *)&ra,
243                             &aaddrlen);
244                         if (s < 0)
245                                 err(1, "Unable to accept()");
246                         if (memcmp(&addr, NG_HCI_BDADDR_ANY, sizeof(addr)) &&
247                             memcmp(&addr, &ra.rfcomm_bdaddr, sizeof(addr))) {
248                                 warnx("Connect from wrong client");
249                                 close(s);
250                                 s = -1;
251                         }
252                 }
253                 sdp_unregister_service(ss, sdp_handle);
254                 sdp_close(ss);
255                 close(acceptsock);
256         } else {
257                 /* Check channel, if was not set then obtain it via SDP */
258                 if (channel == 0 && service != 0)
259                         if (rfcomm_channel_lookup(NULL, &addr,
260                                     service, &channel, &n) != 0)
261                                 errc(1, n, "Could not obtain RFCOMM channel");
262                 if (channel <= 0 || channel > 30)
263                         errx(1, "Invalid RFCOMM channel number %d", channel);
264
265                 s = socket(PF_BLUETOOTH, SOCK_STREAM, BLUETOOTH_PROTO_RFCOMM);
266                 if (s < 0)
267                         err(1, "Could not create socket");
268
269                 memset(&ra, 0, sizeof(ra));
270                 ra.rfcomm_len = sizeof(ra);
271                 ra.rfcomm_family = AF_BLUETOOTH;
272
273                 if (bind(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
274                         err(1, "Could not bind socket");
275
276                 memcpy(&ra.rfcomm_bdaddr, &addr, sizeof(ra.rfcomm_bdaddr));
277                 ra.rfcomm_channel = channel;
278
279                 if (connect(s, (struct sockaddr *) &ra, sizeof(ra)) < 0)
280                         err(1, "Could not connect socket");
281         }
282
283         /* Became daemon if required */
284         if (background) {
285                 switch (fork()) {
286                 case -1:
287                         err(1, "Could not fork()");
288                         /* NOT REACHED */
289
290                 case 0:
291                         exit(0);
292                         /* NOT REACHED */
293
294                 default:
295                         if (daemon(0, 0) < 0)
296                                 err(1, "Could not daemon()");
297                         break;
298                 }
299         }
300
301         openlog(SPPD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);
302         syslog(LOG_INFO, "Starting on %s...", (tty != NULL)? tty : "stdin/stdout");
303
304         for (done = 0; !done; ) {
305                 FD_ZERO(&rfd);
306                 FD_SET(amaster, &rfd);
307                 FD_SET(s, &rfd);
308
309                 n = select(max(amaster, s) + 1, &rfd, NULL, NULL, NULL);
310                 if (n < 0) {
311                         if (errno == EINTR)
312                                 continue;
313
314                         syslog(LOG_ERR, "Could not select(). %s",
315                                         strerror(errno));
316                         exit(1);
317                 }
318
319                 if (n == 0)
320                         continue;
321
322                 if (FD_ISSET(amaster, &rfd)) {
323                         n = sppd_read(amaster, buf, sizeof(buf));
324                         if (n < 0) {
325                                 syslog(LOG_ERR, "Could not read master pty, " \
326                                         "fd=%d. %s", amaster, strerror(errno));
327                                 exit(1);
328                         }
329
330                         if (n == 0)
331                                 break; /* XXX */
332
333                         if (sppd_write(s, buf, n) < 0) {
334                                 syslog(LOG_ERR, "Could not write to socket, " \
335                                         "fd=%d, size=%d. %s",
336                                         s, n, strerror(errno));
337                                 exit(1);
338                         }
339                 }
340
341                 if (FD_ISSET(s, &rfd)) {
342                         n = sppd_read(s, buf, sizeof(buf));
343                         if (n < 0) {
344                                 syslog(LOG_ERR, "Could not read socket, " \
345                                         "fd=%d. %s", s, strerror(errno));
346                                 exit(1);
347                         }
348
349                         if (n == 0)
350                                 break;
351
352                         if (sppd_write(fd, buf, n) < 0) {
353                                 syslog(LOG_ERR, "Could not write to master " \
354                                         "pty, fd=%d, size=%d. %s",
355                                         fd, n, strerror(errno));
356                                 exit(1);
357                         }
358                 }
359         }
360
361         syslog(LOG_INFO, "Completed on %s", (tty != NULL)? tty : "stdin/stdout");
362         closelog();
363
364         close(s);
365
366         if (tty != NULL) {
367                 close(aslave);
368                 close(amaster);
369         }       
370
371         return (0);
372 }
373
374 /* Open TTYs */
375 static int
376 sppd_ttys_open(char const *tty, int *amaster, int *aslave)
377 {
378         char             pty[PATH_MAX], *slash;
379         struct group    *gr = NULL;
380         gid_t            ttygid;
381         struct termios   tio;
382
383         /*
384          * Construct master PTY name. The slave tty name must be less then
385          * PATH_MAX characters in length, must contain '/' character and 
386          * must not end with '/'.
387          */
388
389         if (strlen(tty) >= sizeof(pty)) {
390                 syslog(LOG_ERR, "Slave tty name is too long");
391                 return (-1);
392         }
393
394         strlcpy(pty, tty, sizeof(pty));
395         slash = strrchr(pty, '/');
396         if (slash == NULL || slash[1] == '\0') {
397                 syslog(LOG_ERR, "Invalid slave tty name (%s)", tty);
398                 return (-1);
399         }
400
401         slash[1] = 'p';
402         
403         if (strcmp(pty, tty) == 0) {
404                 syslog(LOG_ERR, "Master and slave tty are the same (%s)", tty);
405                 return (-1);
406         }
407
408         if ((*amaster = open(pty, O_RDWR, 0)) < 0) {
409                 syslog(LOG_ERR, "Could not open(%s). %s", pty, strerror(errno));
410                 return (-1);
411         }
412
413         /*
414          * Slave TTY
415          */
416
417         if ((gr = getgrnam("tty")) != NULL)
418                 ttygid = gr->gr_gid;
419         else
420                 ttygid = -1;
421
422         (void) chown(tty, getuid(), ttygid);
423         (void) chmod(tty, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);
424         (void) revoke(tty);
425
426         if ((*aslave = open(tty, O_RDWR, 0)) < 0) {
427                 syslog(LOG_ERR, "Could not open(%s). %s", tty, strerror(errno));
428                 close(*amaster);
429                 return (-1);
430         }
431
432         /*
433          * Make slave TTY raw
434          */
435
436         cfmakeraw(&tio);
437
438         if (tcsetattr(*aslave, TCSANOW, &tio) < 0) {
439                 syslog(LOG_ERR, "Could not tcsetattr(). %s", strerror(errno));
440                 close(*aslave);
441                 close(*amaster);
442                 return (-1);
443         }
444
445         return (0);
446 } /* sppd_ttys_open */
447
448 /* Read data */
449 static int
450 sppd_read(int fd, char *buffer, int size)
451 {
452         int     n;
453
454 again:
455         n = read(fd, buffer, size);
456         if (n < 0) {
457                 if (errno == EINTR)
458                         goto again;
459
460                 return (-1);
461         }
462
463         return (n);
464 } /* sppd_read */
465
466 /* Write data */
467 static int
468 sppd_write(int fd, char *buffer, int size)
469 {
470         int     n, wrote;
471
472         for (wrote = 0; size > 0; ) {
473                 n = write(fd, buffer, size);
474                 switch (n) {
475                 case -1:
476                         if (errno != EINTR)
477                                 return (-1);
478                         break;
479
480                 case 0: 
481                         /* XXX can happen? */
482                         break;
483
484                 default:
485                         wrote += n;
486                         buffer += n;
487                         size -= n;
488                         break;
489                 }
490         }
491
492         return (wrote);
493 } /* sppd_write */
494
495 /* Signal handler */
496 static void
497 sppd_sighandler(int s)
498 {
499         syslog(LOG_INFO, "Signal %d received. Total %d signals received\n",
500                         s, ++ done);
501 } /* sppd_sighandler */
502  
503 /* Display usage and exit */
504 static void
505 usage(void)
506 {
507         fprintf(stdout,
508 "Usage: %s options\n" \
509 "Where options are:\n" \
510 "\t-a address Peer address (required in client mode)\n" \
511 "\t-b         Run in background\n" \
512 "\t-c channel RFCOMM channel to connect to or listen on\n" \
513 "\t-t tty     TTY name (required in background mode)\n" \
514 "\t-S         Server mode\n" \
515 "\t-h         Display this message\n", SPPD_IDENT);
516         exit(255);
517 } /* usage */
518