Merge branch 'vendor/OPENSSH'
[dragonfly.git] / sbin / slattach / slattach.c
1 /*
2  * Copyright (c) 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Adams.
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#) Copyright (c) 1988 Regents of the University of California. All rights reserved.
37  * @(#)slattach.c       4.6 (Berkeley) 6/1/90
38  * $FreeBSD: src/sbin/slattach/slattach.c,v 1.36 1999/08/28 00:14:25 peter Exp $
39  * $DragonFly: src/sbin/slattach/slattach.c,v 1.6 2005/02/02 07:59:48 cpressey Exp $
40  */
41
42 #include <sys/types.h>
43 #include <sys/ioctl.h>
44 #include <sys/socket.h>
45
46 #include <err.h>
47 #include <fcntl.h>
48 #include <libutil.h>
49 #include <paths.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <syslog.h>
55 #include <termios.h>
56 #include <unistd.h>
57
58 #include <net/if.h>
59 #include <net/slip.h>
60
61 #define DEFAULT_BAUD    9600
62
63 static void sighup_handler(int);        /* SIGHUP handler */
64 static void sigint_handler(int);        /* SIGINT handler */
65 static void sigterm_handler(int);       /* SIGTERM handler */
66 static void sigurg_handler(int);        /* SIGURG handler */
67 static void exit_handler(int);          /* run exit_cmd iff specified upon exit. */
68 static void setup_line(int);            /* configure terminal settings */
69 static void slip_discipline(void);      /* switch to slip line discipline */
70 static void configure_network(void);    /* configure slip interface */
71 static void acquire_line(void);         /* get tty device as controlling terminal */
72 static void usage(void);
73
74 int     fd = -1;
75 char    *dev = NULL;    /* path name of the tty (e.g. /dev/tty01) */
76 char    *dvname;                /* basename of dev */
77 int     locked = 0;             /* uucp lock active */
78 int     flow_control = 0;       /* non-zero to enable hardware flow control. */
79 int     modem_control = HUPCL;  /* !CLOCAL+HUPCL iff we watch carrier. */
80 int     comstate;               /* TIOCMGET current state of serial driver */
81 int     redial_on_startup = 0;  /* iff non-zero execute redial_cmd on startup */
82 speed_t speed = DEFAULT_BAUD;   /* baud rate of tty */
83 int     slflags = 0;            /* compression flags */
84 int     unit = -1;              /* slip device unit number */
85 int     foreground = 0;         /* act as demon if zero, else don't fork. */
86 int     keepal = 0;             /* keepalive timeout */
87 int     outfill = 0;            /* outfill timeout */
88 int     sl_unit = -1;           /* unit number */
89 int     uucp_lock = 0;          /* do uucp locking */
90 int     exiting = 0;            /* already running exit_handler */
91
92 struct  termios tty;            /* tty configuration/state */
93
94 char    tty_path[32];           /* path name of the tty (e.g. /dev/tty01) */
95 char    pidfilename[40];        /* e.g. /var/run/slattach.tty01.pid */
96 char    *redial_cmd = 0;        /* command to exec upon shutdown. */
97 char    *config_cmd = 0;        /* command to exec if slip unit changes. */
98 char    *exit_cmd = 0;          /* command to exec before exiting. */
99
100 static void
101 usage(void)
102 {
103         fprintf(stderr, "%s\n%s\n",
104 "usage: slattach [-acfhlnz] [-e command] [-r command] [-s speed] [-u command]",
105 "                [-L] [-K timeout] [-O timeout] [-S unit] device");
106         /* do not exit here */
107 }
108
109 int
110 main(int argc, char **argv)
111 {
112         int option;
113
114         while ((option = getopt(argc, argv, "ace:fhlnr:s:u:zLK:O:S:")) != -1) {
115                 switch (option) {
116                 case 'a':
117                         slflags |= IFF_LINK2;
118                         slflags &= ~IFF_LINK0;
119                         break;
120                 case 'c':
121                         slflags |= IFF_LINK0;
122                         slflags &= ~IFF_LINK2;
123                         break;
124                 case 'e':
125                         exit_cmd = (char*) strdup (optarg);
126                         break;
127                 case 'f':
128                         foreground = 1;
129                         break;
130                 case 'h':
131                         flow_control |= CRTSCTS;
132                         break;
133                 case 'l':
134                         modem_control = CLOCAL; /* clear HUPCL too */
135                         break;
136                 case 'n':
137                         slflags |= IFF_LINK1;
138                         break;
139                 case 'r':
140                         redial_cmd = (char*) strdup (optarg);
141                         break;
142                 case 's':
143                         speed = atoi(optarg);
144                         break;
145                 case 'u':
146                         config_cmd = (char*) strdup (optarg);
147                         break;
148                 case 'z':
149                         redial_on_startup = 1;
150                         break;
151                 case 'L':
152                         uucp_lock = 1;
153                         break;
154                 case 'K':
155                         keepal = atoi(optarg);
156                         break;
157                 case 'O':
158                         outfill = atoi(optarg);
159                         break;
160                 case 'S':
161                         sl_unit = atoi(optarg);
162                         break;
163                 case '?':
164                 default:
165                         usage();
166                         exit_handler(1);
167                 }
168         }
169
170         if (optind == argc - 1)
171                 dev = argv[optind];
172
173         if (optind < (argc - 1))
174             warnx("too many args, first='%s'", argv[optind]);
175         if (optind > (argc - 1))
176             warnx("not enough args");
177         if (dev == NULL) {
178                 usage();
179                 exit_handler(2);
180         }
181         if (strncmp(_PATH_DEV, dev, sizeof(_PATH_DEV) - 1)) {
182                 strcpy(tty_path, _PATH_DEV);
183                 strcat(tty_path, "/");
184                 strncat(tty_path, dev, 10);
185                 dev = tty_path;
186         }
187         dvname = strrchr(dev, '/'); /* always succeeds */
188         dvname++;                   /* trailing tty pathname component */
189         snprintf(pidfilename, sizeof(pidfilename),
190             "%sslattach.%s.pid", _PATH_VARRUN, dvname);
191         printf("%s\n",pidfilename);
192
193         if (!foreground)
194                 daemon(0,0);    /* fork, setsid, chdir /, and close std*. */
195         /* daemon() closed stderr, so log errors from here on. */
196         openlog("slattach",LOG_CONS|LOG_PID,LOG_DAEMON);
197
198         acquire_line();         /* get tty device as controlling terminal */
199         setup_line(0);          /* configure for slip line discipline */
200         slip_discipline();      /* switch to slip line discipline */
201
202         /* upon INT log a timestamp and exit.  */
203         if (signal(SIGINT,sigint_handler) == SIG_ERR)
204                 syslog(LOG_NOTICE,"cannot install SIGINT handler: %m");
205         /* upon TERM log a timestamp and exit.  */
206         if (signal(SIGTERM,sigterm_handler) == SIG_ERR)
207                 syslog(LOG_NOTICE,"cannot install SIGTERM handler: %m");
208         /* upon HUP redial and reconnect.  */
209         if (signal(SIGHUP,sighup_handler) == SIG_ERR)
210                 syslog(LOG_NOTICE,"cannot install SIGHUP handler: %m");
211
212         if (redial_on_startup)
213                 sighup_handler(0);
214         else if (!(modem_control & CLOCAL)) {
215                 if (ioctl(fd, TIOCMGET, &comstate) < 0)
216                         syslog(LOG_NOTICE,"cannot get carrier state: %m");
217                 if (!(comstate & TIOCM_CD)) { /* check for carrier */
218                         /* force a redial if no carrier */
219                         kill (getpid(), SIGHUP);
220                 } else
221                         configure_network();
222         } else
223                 configure_network(); /* configure the network if needed. */
224
225         for (;;) {
226                 sigset_t mask;
227                 sigemptyset(&mask);
228                 sigsuspend(&mask);
229         }
230 }
231
232 /* Close all FDs, fork, reopen tty port as 0-2, and make it the
233    controlling terminal for our process group. */
234 static void
235 acquire_line(void)
236 {
237         int ttydisc = TTYDISC;
238         int oflags;
239         FILE *pid_file;
240
241         /* reset to tty discipline */
242         if (fd >= 0 && ioctl(fd, TIOCSETD, &ttydisc) < 0) {
243                 syslog(LOG_ERR, "ioctl(TIOCSETD): %m");
244                 exit_handler(1);
245         }
246
247         close(STDIN_FILENO); /* close FDs before forking. */
248         close(STDOUT_FILENO);
249         close(STDERR_FILENO);
250         if (fd > 2)
251                 close(fd);
252
253         signal(SIGHUP, SIG_IGN); /* ignore HUP signal when parent dies. */
254         if (daemon(0,0)) {       /* fork, setsid, chdir /, and close std*. */
255                 syslog(LOG_ERR, "daemon(0,0): %m");
256                 exit_handler(1);
257         }
258
259         while (getppid () != 1)
260                 sleep (1);      /* Wait for parent to die. */
261
262         /* create PID file */
263         if((pid_file = fopen(pidfilename, "w"))) {
264                 fprintf(pid_file, "%ld\n", (long)getpid());
265                 fclose(pid_file);
266         }
267
268         if (signal(SIGHUP,sighup_handler) == SIG_ERR) /* Re-enable HUP signal */
269                 syslog(LOG_NOTICE,"cannot install SIGHUP handler: %m");
270
271         if (uucp_lock) {
272                 /* unlock not needed here, always re-lock with new pid */
273                 int res;
274                 if ((res = uu_lock(dvname)) != UU_LOCK_OK) {
275                         if (res != UU_LOCK_INUSE)
276                                 syslog(LOG_ERR, "uu_lock: %s", uu_lockerr(res));
277                         syslog(LOG_ERR, "can't lock %s", dev);
278                         exit_handler(1);
279                 }
280                 locked = 1;
281         }
282
283         if ((fd = open(dev, O_RDWR | O_NONBLOCK, 0)) < 0) {
284                 syslog(LOG_ERR, "open(%s) %m", dev);
285                 exit_handler(1);
286         }
287         /* Turn off O_NONBLOCK for dumb redialers, if any. */
288         if ((oflags = fcntl(fd, F_GETFL)) == -1) {
289                 syslog(LOG_ERR, "fcntl(F_GETFL) failed: %m");
290                 exit_handler(1);
291         }
292         if (fcntl(fd, F_SETFL, oflags & ~O_NONBLOCK) == -1) {
293                 syslog(LOG_ERR, "fcntl(F_SETFL) failed: %m");
294                 exit_handler(1);
295         }
296         dup2(fd, STDIN_FILENO);
297         dup2(fd, STDOUT_FILENO);
298         dup2(fd, STDERR_FILENO);
299         if (fd > 2)
300                 close (fd);
301         fd = STDIN_FILENO;
302
303         /* acquire the serial line as a controlling terminal. */
304         if (ioctl(fd, TIOCSCTTY, 0) < 0) {
305                 syslog(LOG_ERR,"ioctl(TIOCSCTTY): %m");
306                 exit_handler(1);
307         }
308         /* Make us the foreground process group associated with the
309            slip line which is our controlling terminal. */
310         if (tcsetpgrp(fd, getpid()) < 0)
311                 syslog(LOG_NOTICE,"tcsetpgrp failed: %m");
312 }
313
314 /* Set the tty flags and set DTR. */
315 /* Call as setup_line(CLOCAL) to force clocal assertion. */
316 static void
317 setup_line(int cflag)
318 {
319         tty.c_lflag = tty.c_iflag = tty.c_oflag = 0;
320         tty.c_cflag = CREAD | CS8 | flow_control | modem_control | cflag;
321         cfsetispeed(&tty, speed);
322         cfsetospeed(&tty, speed);
323         /* set the line speed and flow control */
324         if (tcsetattr(fd, TCSAFLUSH, &tty) < 0) {
325                 syslog(LOG_ERR, "tcsetattr(TCSAFLUSH): %m");
326                 exit_handler(1);
327         }
328         /* set data terminal ready */
329         if (ioctl(fd, TIOCSDTR) < 0) {
330                 syslog(LOG_ERR, "ioctl(TIOCSDTR): %m");
331                 exit_handler(1);
332         }
333 }
334
335 /* Put the line in slip discipline. */
336 static void
337 slip_discipline(void)
338 {
339         struct ifreq ifr;
340         int slipdisc = SLIPDISC;
341         int s, tmp_unit = -1;
342
343         /* Switch to slip line discipline. */
344         if (ioctl(fd, TIOCSETD, &slipdisc) < 0) {
345                 syslog(LOG_ERR, "ioctl(TIOCSETD): %m");
346                 exit_handler(1);
347         }
348
349         if (sl_unit >= 0 && ioctl(fd, SLIOCSUNIT, &sl_unit) < 0) {
350                 syslog(LOG_ERR, "ioctl(SLIOCSUNIT): %m");
351                 exit_handler(1);
352         }
353
354         /* find out what unit number we were assigned */
355         if (ioctl(fd, SLIOCGUNIT, (caddr_t)&tmp_unit) < 0) {
356                 syslog(LOG_ERR, "ioctl(SLIOCGUNIT): %m");
357                 exit_handler(1);
358         }
359
360         if (tmp_unit < 0) {
361                 syslog(LOG_ERR, "bad unit (%d) from ioctl(SLIOCGUNIT)",tmp_unit);
362                 exit_handler(1);
363         }
364
365         if (keepal > 0) {
366                 signal(SIGURG, sigurg_handler);
367                 if (ioctl(fd, SLIOCSKEEPAL, &keepal) < 0) {
368                         syslog(LOG_ERR, "ioctl(SLIOCSKEEPAL): %m");
369                         exit_handler(1);
370                 }
371         }
372         if (outfill > 0 && ioctl(fd, SLIOCSOUTFILL, &outfill) < 0) {
373                 syslog(LOG_ERR, "ioctl(SLIOCSOUTFILL): %m");
374                 exit_handler(1);
375         }
376
377         /* open a socket as the handle to the interface */
378         s = socket(AF_INET, SOCK_DGRAM, 0);
379         if (s < 0) {
380                 syslog(LOG_ERR, "socket: %m");
381                 exit_handler(1);
382         }
383         sprintf(ifr.ifr_name, "sl%d", tmp_unit);
384
385         /* get the flags for the interface */
386         if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) < 0) {
387                 syslog(LOG_ERR, "ioctl (SIOCGIFFLAGS): %m");
388                 exit_handler(1);
389         }
390
391         /* Assert any compression or no-icmp flags. */
392 #define SLMASK (~(IFF_LINK0 | IFF_LINK1 | IFF_LINK2))
393         ifr.ifr_flags &= SLMASK;
394         ifr.ifr_flags |= slflags;
395         if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&ifr) < 0) {
396                 syslog(LOG_ERR, "ioctl (SIOCSIFFLAGS): %m");
397                 exit_handler(1);
398         }
399         close(s);
400 }
401
402 /* configure the interface, e.g. by passing the unit number to a script. */
403 static void
404 configure_network(void)
405 {
406         int new_unit;
407
408         /* find out what unit number we were assigned */
409         if (ioctl(fd, SLIOCGUNIT, (caddr_t)&new_unit) < 0) {
410                 syslog(LOG_ERR, "ioctl(SLIOCGUNIT): %m");
411                 exit_handler(1);
412         }
413         /* iff the unit number changes either invoke config_cmd or punt. */
414         if (config_cmd) {
415                 char *s;
416                 s = (char*) malloc(strlen(config_cmd) + 32);
417                 if (s == NULL) {
418                         syslog(LOG_ERR, "malloc failed");
419                         exit(1);
420                 }
421                 sprintf (s, "%s %d %d", config_cmd, unit, new_unit);
422                 syslog(LOG_NOTICE, "configuring %s (sl%d):", dev, unit);
423                 syslog(LOG_NOTICE, "  '%s'", s);
424                 system(s);
425                 free (s);
426                 unit = new_unit;
427         } else {
428                 /* don't compare unit numbers if this is the first time to attach. */
429                 if (unit < 0)
430                         unit = new_unit;
431                 if (new_unit != unit) {
432                         syslog(LOG_ERR,
433         "slip unit changed from sl%d to sl%d, but no -u CMD was specified!",
434                             unit, new_unit);
435                         exit_handler(1);
436                 }
437                 syslog(LOG_NOTICE,"sl%d connected to %s at %d baud",unit,dev,speed);
438         }
439 }
440
441 /* sighup_handler() is invoked when carrier drops, eg. before redial. */
442 static void
443 sighup_handler(int signo __unused)
444 {
445         if(exiting) return;
446
447         if (redial_cmd == NULL) {
448                 syslog(LOG_NOTICE,"SIGHUP on %s (sl%d); exiting", dev, unit);
449                 exit_handler(1);
450         }
451 again:
452         /* invoke a shell for redial_cmd or punt. */
453         if (*redial_cmd) { /* Non-empty redial command */
454                 syslog(LOG_NOTICE,"SIGHUP on %s (sl%d); running '%s'",
455                        dev, unit, redial_cmd);
456                 acquire_line(); /* reopen dead line */
457                 setup_line(CLOCAL);
458                 if (locked) {
459                         if (uucp_lock)
460                                 uu_unlock(dvname);      /* for redial */
461                         locked = 0;
462                 }
463                 if (system(redial_cmd))
464                         goto again;
465                 if (uucp_lock) {
466                         int res;
467                         if ((res = uu_lock(dvname)) != UU_LOCK_OK) {
468                                 if (res != UU_LOCK_INUSE)
469                                         syslog(LOG_ERR, "uu_lock: %s", uu_lockerr(res));
470                                 syslog(LOG_ERR, "can't relock %s after %s, aborting",
471                                         dev, redial_cmd);
472                                 exit_handler(1);
473                         }
474                         locked = 1;
475                 }
476                 /* Now check again for carrier (dial command is done): */
477                 if (!(modem_control & CLOCAL)) {
478                         tty.c_cflag &= ~CLOCAL;
479                         if (tcsetattr(fd, TCSAFLUSH, &tty) < 0) {
480                                 syslog(LOG_ERR, "tcsetattr(TCSAFLUSH): %m");
481                                 exit_handler(1);
482                         }
483                         ioctl(fd, TIOCMGET, &comstate);
484                         if (!(comstate & TIOCM_CD)) { /* check for carrier */
485                                 /* force a redial if no carrier */
486                                 goto again;
487                         }
488                 } else
489                         setup_line(0);
490         } else {        /* Empty redial command */
491                 syslog(LOG_NOTICE,"SIGHUP on %s (sl%d); reestablish connection",
492                         dev, unit);
493                 acquire_line(); /* reopen dead line */
494                 setup_line(0);  /* restore ospeed from hangup (B0) */
495                 /* If modem control, just wait for carrier before attaching.
496                    If no modem control, just fall through immediately. */
497                 if (!(modem_control & CLOCAL)) {
498                         int carrier = 0;
499
500                         syslog(LOG_NOTICE, "waiting for carrier on %s (sl%d)",
501                                dev, unit);
502                         /* Now wait for carrier before attaching line. */
503                         /* We must poll since CLOCAL prevents signal. */
504                         while (! carrier) {
505                                 sleep(2);
506                                 ioctl(fd, TIOCMGET, &comstate);
507                                 if (comstate & TIOCM_CD)
508                                         carrier = 1;
509                         }
510                         syslog(LOG_NOTICE, "carrier now present on %s (sl%d)",
511                                dev, unit);
512                 }
513         }
514         slip_discipline();
515         configure_network();
516 }
517
518 /* Signal handler for SIGINT.  We just log and exit. */
519 static void
520 sigint_handler(int signo __unused)
521 {
522         if(exiting) return;
523         syslog(LOG_NOTICE,"SIGINT on %s (sl%d); exiting",dev,unit);
524         exit_handler(0);
525 }
526
527 /* Signal handler for SIGURG. */
528 static void
529 sigurg_handler(int signo __unused)
530 {
531         int ttydisc = TTYDISC;
532
533         signal(SIGURG, SIG_IGN);
534         if(exiting) return;
535         syslog(LOG_NOTICE,"SIGURG on %s (sl%d); hangup",dev,unit);
536         if (ioctl(fd, TIOCSETD, &ttydisc) < 0) {
537                 syslog(LOG_ERR, "ioctl(TIOCSETD): %m");
538                 exit_handler(1);
539         }
540         cfsetospeed(&tty, B0);
541         if (tcsetattr(fd, TCSANOW, &tty) < 0) {
542                 syslog(LOG_ERR, "tcsetattr(TCSANOW): %m");
543                 exit_handler(1);
544         }
545         /* Need to go to sighup handler in any case */
546         if (modem_control & CLOCAL)
547                 kill (getpid(), SIGHUP);
548
549 }
550
551 /* Signal handler for SIGTERM.  We just log and exit. */
552 static void
553 sigterm_handler(int signo __unused)
554 {
555         if(exiting) return;
556         syslog(LOG_NOTICE,"SIGTERM on %s (sl%d); exiting",dev,unit);
557         exit_handler(0);
558 }
559
560 /* Run config_cmd if specified before exiting. */
561 static void
562 exit_handler(int ret)
563 {
564         if(exiting) return;
565         exiting = 1;
566         /*
567          * First close the slip line in case exit_cmd wants it (like to hang
568          * up a modem or something).
569          */
570         if (fd != -1)
571                 close(fd);
572         if (uucp_lock && locked)
573                 uu_unlock(dvname);
574
575         /* Remove the PID file */
576         unlink(pidfilename);
577
578         if (config_cmd) {
579                 char *s;
580                 s = (char*) malloc(strlen(config_cmd) + 32);
581                 if (s == NULL) {
582                         syslog(LOG_ERR, "malloc failed");
583                         exit(1);
584                 }
585                 sprintf (s, "%s %d -1", config_cmd, unit);
586                 syslog(LOG_NOTICE, "deconfiguring %s (sl%d):", dev, unit);
587                 syslog(LOG_NOTICE, "  '%s'", s);
588                 system(s);
589                 free (s);
590         }
591         /* invoke a shell for exit_cmd. */
592         if (exit_cmd) {
593                 syslog(LOG_NOTICE,"exiting after running %s", exit_cmd);
594                 system(exit_cmd);
595         }
596         exit(ret);
597 }
598
599 /* local variables: */
600 /* c-indent-level: 8 */
601 /* c-argdecl-indent: 0 */
602 /* c-label-offset: -8 */
603 /* c-continued-statement-offset: 8 */
604 /* c-brace-offset: 0 */
605 /* comment-column: 32 */
606 /* end: */