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