xref: /freebsd/usr.sbin/ppp/main.c (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1 /*-
2  * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
3  *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
4  *                           Internet Initiative Japan, Inc (IIJ)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 #include <sys/param.h>
32 #include <netinet/in.h>
33 #include <netinet/in_systm.h>
34 #include <netinet/ip.h>
35 #include <sys/un.h>
36 #include <sys/socket.h>
37 #include <net/route.h>
38 
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <paths.h>
42 #include <signal.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <sys/time.h>
48 #include <termios.h>
49 #include <unistd.h>
50 #include <sys/stat.h>
51 
52 #ifndef NONAT
53 #ifdef LOCALNAT
54 #include "alias.h"
55 #else
56 #include <alias.h>
57 #endif
58 #endif
59 
60 #include "layer.h"
61 #include "probe.h"
62 #include "mbuf.h"
63 #include "log.h"
64 #include "defs.h"
65 #include "id.h"
66 #include "timer.h"
67 #include "fsm.h"
68 #include "lqr.h"
69 #include "hdlc.h"
70 #include "lcp.h"
71 #include "ccp.h"
72 #include "iplist.h"
73 #include "throughput.h"
74 #include "slcompress.h"
75 #include "ncpaddr.h"
76 #include "ipcp.h"
77 #include "filter.h"
78 #include "descriptor.h"
79 #include "link.h"
80 #include "mp.h"
81 #ifndef NORADIUS
82 #include "radius.h"
83 #endif
84 #include "ipv6cp.h"
85 #include "ncp.h"
86 #include "bundle.h"
87 #include "auth.h"
88 #include "systems.h"
89 #include "sig.h"
90 #include "main.h"
91 #include "server.h"
92 #include "prompt.h"
93 #include "chat.h"
94 #include "chap.h"
95 #include "cbcp.h"
96 #include "datalink.h"
97 #include "iface.h"
98 
99 #ifndef O_NONBLOCK
100 #ifdef O_NDELAY
101 #define	O_NONBLOCK O_NDELAY
102 #endif
103 #endif
104 
105 static void DoLoop(struct bundle *);
106 static void TerminalStop(int);
107 
108 static struct bundle *SignalBundle;
109 static struct prompt *SignalPrompt;
110 struct libalias *la;
111 
112 void
113 Cleanup()
114 {
115   SignalBundle->CleaningUp = 1;
116   bundle_Close(SignalBundle, NULL, CLOSE_STAYDOWN);
117 }
118 
119 void
120 AbortProgram(int excode)
121 {
122   if (SignalBundle)
123     server_Close(SignalBundle);
124   log_Printf(LogPHASE, "PPP Terminated (%s).\n", ex_desc(excode));
125   if (SignalBundle) {
126     bundle_Close(SignalBundle, NULL, CLOSE_STAYDOWN);
127     bundle_Destroy(SignalBundle);
128   }
129   log_Close();
130   exit(excode);
131 }
132 
133 static void
134 CloseConnection(int signo)
135 {
136   /* NOTE, these are manual, we've done a setsid() */
137   sig_signal(SIGINT, SIG_IGN);
138   log_Printf(LogPHASE, "Caught signal %d, abort connection(s)\n", signo);
139   bundle_Down(SignalBundle, CLOSE_STAYDOWN);
140   sig_signal(SIGINT, CloseConnection);
141 }
142 
143 static void
144 CloseSession(int signo)
145 {
146   log_Printf(LogPHASE, "Signal %d, terminate.\n", signo);
147   Cleanup();
148 }
149 
150 static pid_t BGPid = 0;
151 
152 static void
153 KillChild(int signo)
154 {
155   signal(signo, SIG_IGN);
156   log_Printf(LogPHASE, "Parent: Signal %d\n", signo);
157   kill(BGPid, SIGINT);
158 }
159 
160 static void
161 TerminalCont(int signo __unused)
162 {
163   signal(SIGCONT, SIG_DFL);
164   prompt_Continue(SignalPrompt);
165 }
166 
167 static void
168 TerminalStop(int signo __unused)
169 {
170   prompt_Suspend(SignalPrompt);
171   signal(SIGCONT, TerminalCont);
172   raise(SIGSTOP);
173 }
174 
175 static void
176 BringDownServer(int signo __unused)
177 {
178   /* Drops all child prompts too ! */
179   if (server_Close(SignalBundle))
180     log_Printf(LogPHASE, "Closed server socket\n");
181 }
182 
183 static void
184 RestartServer(int signo __unused)
185 {
186   /* Drops all child prompts and re-opens the socket */
187   server_Reopen(SignalBundle);
188 }
189 
190 static void
191 Usage(void)
192 {
193   fprintf(stderr, "usage: ppp [-auto | -foreground | -background | -direct |"
194           " -dedicated | -ddial | -interactive]"
195 #ifndef NONAT
196           " [-nat]"
197 #endif
198           " [-quiet] [-unit N] [system ...]\n");
199   exit(EX_START);
200 }
201 
202 struct switches {
203   unsigned nat : 1;
204   unsigned fg : 1;
205   unsigned quiet : 1;
206   int mode;
207   int unit;
208 };
209 
210 static int
211 ProcessArgs(int argc, char **argv, struct switches *sw)
212 {
213   int optc, newmode, arg;
214   char *cp;
215 
216   optc = 0;
217   memset(sw, '\0', sizeof *sw);
218   sw->mode = PHYS_INTERACTIVE;
219   sw->unit = -1;
220 
221   for (arg = 1; arg < argc && *argv[arg] == '-'; arg++, optc++) {
222     cp = argv[arg] + 1;
223     newmode = Nam2mode(cp);
224     switch (newmode) {
225       case PHYS_NONE:
226         if (strcmp(cp, "nat") == 0) {
227 #ifdef NONAT
228           log_Printf(LogWARN, "%s ignored: NAT is compiled out\n", argv[arg]);
229 #else
230           sw->nat = 1;
231 #endif
232           optc--;			/* this option isn't exclusive */
233         } else if (strcmp(cp, "alias") == 0) {
234 #ifdef NONAT
235           log_Printf(LogWARN, "%s ignored: NAT is compiled out\n", argv[arg]);
236           fprintf(stderr, "%s ignored: NAT is compiled out\n", argv[arg]);
237 #else
238           log_Printf(LogWARN, "%s is deprecated\n", argv[arg]);
239           fprintf(stderr, "%s is deprecated\n", argv[arg]);
240           sw->nat = 1;
241 #endif
242           optc--;			/* this option isn't exclusive */
243         } else if (strncmp(cp, "unit", 4) == 0) {
244           optc--;			/* this option isn't exclusive */
245           if (cp[4] == '\0') {
246             optc--;			/* nor is the argument */
247             if (++arg == argc) {
248               fprintf(stderr, "-unit: Expected unit number\n");
249               Usage();
250             } else
251               sw->unit = atoi(argv[arg]);
252           } else
253             sw->unit = atoi(cp + 4);
254         } else if (strcmp(cp, "quiet") == 0) {
255           sw->quiet = 1;
256           optc--;			/* this option isn't exclusive */
257         } else
258           Usage();
259         break;
260 
261       case PHYS_ALL:
262         Usage();
263         break;
264 
265       default:
266         sw->mode = newmode;
267         if (newmode == PHYS_FOREGROUND)
268           sw->fg = 1;
269     }
270   }
271 
272   if (optc > 1) {
273     fprintf(stderr, "You may specify only one mode.\n");
274     exit(EX_START);
275   }
276 
277   if (sw->mode == PHYS_AUTO && arg == argc) {
278     fprintf(stderr, "A system must be specified in auto mode.\n");
279     exit(EX_START);
280   }
281 
282   return arg;		/* Don't SetLabel yet ! */
283 }
284 
285 static void
286 CheckLabel(const char *label, struct prompt *prompt, int mode)
287 {
288   const char *err;
289 
290   if ((err = system_IsValid(label, prompt, mode)) != NULL) {
291     fprintf(stderr, "%s: %s\n", label, err);
292     if (mode == PHYS_DIRECT)
293       log_Printf(LogWARN, "Label %s rejected -direct connection: %s\n",
294                  label, err);
295     log_Close();
296     exit(1);
297   }
298 }
299 
300 
301 int
302 main(int argc, char **argv)
303 {
304   char *name;
305   const char *lastlabel;
306   int arg, holdfd[3], label;
307   unsigned f;
308   struct bundle *bundle;
309   struct prompt *prompt;
310   struct switches sw;
311 
312   probe_Init();
313 
314   /*
315    * We open 3 descriptors to ensure that STDIN_FILENO, STDOUT_FILENO and
316    * STDERR_FILENO are always open.  These are closed before DoLoop(),
317    * but *after* we've avoided the possibility of erroneously closing
318    * an important descriptor with close(STD{IN,OUT,ERR}_FILENO).
319    */
320   if ((holdfd[0] = open(_PATH_DEVNULL, O_RDWR)) == -1) {
321     fprintf(stderr, "Cannot open %s !\n", _PATH_DEVNULL);
322     return 2;
323   }
324   for (f = 1; f < sizeof holdfd / sizeof *holdfd; f++)
325     holdfd[f] = dup(holdfd[0]);
326 
327   name = strrchr(argv[0], '/');
328   log_Open(name ? name + 1 : argv[0]);
329 
330 #ifndef NONAT
331   la = LibAliasInit(NULL);
332 #endif
333   label = ProcessArgs(argc, argv, &sw);
334 
335   /*
336    * A FreeBSD & OpenBSD hack to dodge a bug in the tty driver that drops
337    * output occasionally.... I must find the real reason some time.  To
338    * display the dodgy behaviour, comment out this bit, make yourself a large
339    * routing table and then run ppp in interactive mode.  The `show route'
340    * command will drop chunks of data !!!
341    */
342   if (sw.mode == PHYS_INTERACTIVE) {
343     close(STDIN_FILENO);
344     if (open(_PATH_TTY, O_RDONLY) != STDIN_FILENO) {
345       fprintf(stderr, "Cannot open %s for input !\n", _PATH_TTY);
346       return 2;
347     }
348   }
349 
350   /* Allow output for the moment (except in direct mode) */
351   if (sw.mode == PHYS_DIRECT)
352     prompt = NULL;
353   else
354     SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD);
355 
356   ID0init();
357   if (ID0realuid() != 0) {
358     char conf[200], *ptr;
359 
360     snprintf(conf, sizeof conf, "%s/%s", PPP_CONFDIR, CONFFILE);
361     do {
362       struct stat sb;
363 
364       if (stat(conf, &sb) == 0 && sb.st_mode & S_IWOTH) {
365         log_Printf(LogALERT, "ppp: Access violation: Please protect %s\n",
366                    conf);
367         return -1;
368       }
369       ptr = conf + strlen(conf)-2;
370       while (ptr > conf && *ptr != '/')
371         *ptr-- = '\0';
372     } while (ptr >= conf);
373   }
374 
375   if (label < argc)
376     for (arg = label; arg < argc; arg++)
377       CheckLabel(argv[arg], prompt, sw.mode);
378   else
379     CheckLabel("default", prompt, sw.mode);
380 
381   if (!sw.quiet)
382     prompt_Printf(prompt, "Working in %s mode\n", mode2Nam(sw.mode));
383 
384   if ((bundle = bundle_Create(TUN_PREFIX, sw.mode, sw.unit)) == NULL)
385     return EX_START;
386 
387   /* NOTE:  We may now have changed argv[1] via a ``set proctitle'' */
388 
389   SignalBundle = bundle;
390   bundle->NatEnabled = sw.nat;
391   if (sw.nat)
392     opt_enable(bundle, OPT_IFACEALIAS);
393 
394   if (system_Select(bundle, "default", CONFFILE, prompt, NULL) < 0)
395     prompt_Printf(prompt, "Warning: No default entry found in config file.\n");
396 
397   sig_signal(SIGHUP, CloseSession);
398   sig_signal(SIGTERM, CloseSession);
399   sig_signal(SIGINT, CloseConnection);
400   sig_signal(SIGQUIT, CloseSession);
401   sig_signal(SIGALRM, SIG_IGN);
402   signal(SIGPIPE, SIG_IGN);
403 
404   if (sw.mode == PHYS_INTERACTIVE)
405     sig_signal(SIGTSTP, TerminalStop);
406 
407   sig_signal(SIGUSR1, RestartServer);
408   sig_signal(SIGUSR2, BringDownServer);
409 
410   lastlabel = argv[argc - 1];
411   for (arg = label; arg < argc; arg++) {
412     /* In case we use LABEL or ``set enddisc label'' */
413     bundle_SetLabel(bundle, lastlabel);
414     system_Select(bundle, argv[arg], CONFFILE, prompt, NULL);
415   }
416 
417   if (label < argc)
418     /* In case the last label did a ``load'' */
419     bundle_SetLabel(bundle, lastlabel);
420 
421   if (sw.mode == PHYS_AUTO &&
422       ncprange_family(&bundle->ncp.ipcp.cfg.peer_range) == AF_UNSPEC) {
423     prompt_Printf(prompt, "You must ``set ifaddr'' with a peer address "
424                   "in auto mode.\n");
425     AbortProgram(EX_START);
426   }
427 
428   if (prompt) {
429     prompt->bundle = bundle;	/* couldn't do it earlier */
430     if (!sw.quiet)
431       prompt_Printf(prompt, "Using interface: %s\n", bundle->iface->name);
432   }
433 
434   if (sw.mode != PHYS_INTERACTIVE) {
435     if (sw.mode != PHYS_DIRECT) {
436       if (!sw.fg) {
437         int bgpipe[2];
438         pid_t bgpid;
439 
440         if (sw.mode == PHYS_BACKGROUND && pipe(bgpipe)) {
441           log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
442 	  AbortProgram(EX_SOCK);
443         }
444 
445         bgpid = fork();
446         if (bgpid == -1) {
447 	  log_Printf(LogERROR, "fork: %s\n", strerror(errno));
448 	  AbortProgram(EX_SOCK);
449         }
450 
451         if (bgpid) {
452 	  char c = EX_NORMAL;
453           int ret;
454 
455 	  if (sw.mode == PHYS_BACKGROUND) {
456 	    close(bgpipe[1]);
457 	    BGPid = bgpid;
458             /* If we get a signal, kill the child */
459             signal(SIGHUP, KillChild);
460             signal(SIGTERM, KillChild);
461             signal(SIGINT, KillChild);
462             signal(SIGQUIT, KillChild);
463 
464 	    /* Wait for our child to close its pipe before we exit */
465             while ((ret = read(bgpipe[0], &c, 1)) == 1) {
466               switch (c) {
467                 case EX_NORMAL:
468                   if (!sw.quiet) {
469 	            prompt_Printf(prompt, "PPP enabled\n");
470 	            log_Printf(LogPHASE, "Parent: PPP enabled\n");
471                   }
472 	          break;
473                 case EX_REDIAL:
474                   if (!sw.quiet)
475 	            prompt_Printf(prompt, "Attempting redial\n");
476                   continue;
477                 case EX_RECONNECT:
478                   if (!sw.quiet)
479 	            prompt_Printf(prompt, "Attempting reconnect\n");
480                   continue;
481 	        default:
482 	          prompt_Printf(prompt, "Child failed (%s)\n",
483                                 ex_desc((int)c));
484 	          log_Printf(LogPHASE, "Parent: Child failed (%s)\n",
485 		             ex_desc((int) c));
486 	      }
487 	      break;
488             }
489             if (ret != 1) {
490 	      prompt_Printf(prompt, "Child exit, no status.\n");
491 	      log_Printf(LogPHASE, "Parent: Child exit, no status.\n");
492 	    }
493 	    close(bgpipe[0]);
494 	  }
495 	  return c;
496         } else if (sw.mode == PHYS_BACKGROUND) {
497 	  close(bgpipe[0]);
498           bundle->notify.fd = bgpipe[1];
499         }
500 
501         bundle_ChangedPID(bundle);
502         bundle_LockTun(bundle);	/* we have a new pid */
503       }
504 
505       /* -auto, -dedicated, -ddial, -foreground & -background */
506       prompt_Destroy(prompt, 0);
507       close(STDOUT_FILENO);
508       close(STDERR_FILENO);
509       close(STDIN_FILENO);
510       if (!sw.fg)
511         setsid();
512     } else {
513       /*
514        * -direct - STDIN_FILENO gets used by physical_Open.  STDOUT_FILENO
515        * *may* get used in exec/pipe mode.
516        */
517       prompt_TtyInit(NULL);
518       close(STDERR_FILENO);
519     }
520   } else {
521     /* -interactive */
522     close(STDERR_FILENO);
523     prompt_TtyInit(prompt);
524     prompt_TtyCommandMode(prompt);
525     prompt_Required(prompt);
526   }
527 
528   /* We can get rid of these now */
529   for (f = 0; f < sizeof holdfd / sizeof *holdfd; f++)
530     close(holdfd[f]);
531 
532   log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(sw.mode));
533   DoLoop(bundle);
534   AbortProgram(EX_NORMAL);
535 
536   return EX_NORMAL;
537 }
538 
539 static void
540 DoLoop(struct bundle *bundle)
541 {
542   fd_set *rfds, *wfds, *efds;
543   int i, nfds, nothing_done;
544 
545   if ((rfds = mkfdset()) == NULL) {
546     log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n");
547     return;
548   }
549 
550   if ((wfds = mkfdset()) == NULL) {
551     log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n");
552     free(rfds);
553     return;
554   }
555 
556   if ((efds = mkfdset()) == NULL) {
557     log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n");
558     free(rfds);
559     free(wfds);
560     return;
561   }
562 
563   for (; !bundle_IsDead(bundle); bundle_CleanDatalinks(bundle)) {
564     nfds = 0;
565     zerofdset(rfds);
566     zerofdset(wfds);
567     zerofdset(efds);
568 
569     /* All our datalinks, the tun device and the MP socket */
570     descriptor_UpdateSet(&bundle->desc, rfds, wfds, efds, &nfds);
571 
572     /* All our prompts and the diagnostic socket */
573     descriptor_UpdateSet(&server.desc, rfds, NULL, NULL, &nfds);
574 
575     bundle_CleanDatalinks(bundle);
576     if (bundle_IsDead(bundle))
577       /* Don't select - we'll be here forever */
578       break;
579 
580     /*
581      * It's possible that we've had a signal since we last checked.  If
582      * we don't check again before calling select(), we may end up stuck
583      * after having missed the event.... sig_Handle() tries to be as
584      * quick as possible if nothing is likely to have happened.
585      * This is only really likely if we block in open(... O_NONBLOCK)
586      * which will happen with a misconfigured device.
587      */
588     if (sig_Handle())
589       continue;
590 
591     i = select(nfds, rfds, wfds, efds, NULL);
592 
593     if (i < 0 && errno != EINTR) {
594       log_Printf(LogERROR, "DoLoop: select(): %s\n", strerror(errno));
595       if (log_IsKept(LogTIMER)) {
596         struct timeval t;
597 
598         for (i = 0; i <= nfds; i++) {
599           if (FD_ISSET(i, rfds)) {
600             log_Printf(LogTIMER, "Read set contains %d\n", i);
601             FD_CLR(i, rfds);
602             t.tv_sec = t.tv_usec = 0;
603             if (select(nfds, rfds, wfds, efds, &t) != -1) {
604               log_Printf(LogTIMER, "The culprit !\n");
605               break;
606             }
607           }
608           if (FD_ISSET(i, wfds)) {
609             log_Printf(LogTIMER, "Write set contains %d\n", i);
610             FD_CLR(i, wfds);
611             t.tv_sec = t.tv_usec = 0;
612             if (select(nfds, rfds, wfds, efds, &t) != -1) {
613               log_Printf(LogTIMER, "The culprit !\n");
614               break;
615             }
616           }
617           if (FD_ISSET(i, efds)) {
618             log_Printf(LogTIMER, "Error set contains %d\n", i);
619             FD_CLR(i, efds);
620             t.tv_sec = t.tv_usec = 0;
621             if (select(nfds, rfds, wfds, efds, &t) != -1) {
622               log_Printf(LogTIMER, "The culprit !\n");
623               break;
624             }
625           }
626         }
627       }
628       break;
629     }
630 
631     log_Printf(LogTIMER, "Select returns %d\n", i);
632 
633     sig_Handle();
634 
635     if (i <= 0)
636       continue;
637 
638     for (i = 0; i <= nfds; i++)
639       if (FD_ISSET(i, efds)) {
640         log_Printf(LogPHASE, "Exception detected on descriptor %d\n", i);
641         /* We deal gracefully with link descriptor exceptions */
642         if (!bundle_Exception(bundle, i)) {
643           log_Printf(LogERROR, "Exception cannot be handled !\n");
644           break;
645         }
646       }
647 
648     if (i <= nfds)
649       break;
650 
651     nothing_done = 1;
652 
653     if (descriptor_IsSet(&server.desc, rfds)) {
654       descriptor_Read(&server.desc, bundle, rfds);
655       nothing_done = 0;
656     }
657 
658     if (descriptor_IsSet(&bundle->desc, rfds)) {
659       descriptor_Read(&bundle->desc, bundle, rfds);
660       nothing_done = 0;
661     }
662 
663     if (descriptor_IsSet(&bundle->desc, wfds))
664       if (descriptor_Write(&bundle->desc, bundle, wfds) <= 0 && nothing_done) {
665         /*
666          * This is disastrous.  The OS has told us that something is
667          * writable, and all our write()s have failed.  Rather than
668          * going back immediately to do our UpdateSet()s and select(),
669          * we sleep for a bit to avoid gobbling up all cpu time.
670          */
671         struct timeval t;
672 
673         t.tv_sec = 0;
674         t.tv_usec = 100000;
675         select(0, NULL, NULL, NULL, &t);
676       }
677   }
678 
679   log_Printf(LogDEBUG, "DoLoop done.\n");
680 }
681