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