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