xref: /freebsd/usr.sbin/ppp/main.c (revision a1a4f1a0d87b594d3f17a97dc0127eec1417e6f6)
1 /*
2  *			User Process PPP
3  *
4  *	    Written by Toshiharu OHNO (tony-o@iij.ad.jp)
5  *
6  *   Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd.
7  *
8  * Redistribution and use in source and binary forms are permitted
9  * provided that the above copyright notice and this paragraph are
10  * duplicated in all such forms and that any documentation,
11  * advertising materials, and other materials related to such
12  * distribution and use acknowledge that the software was developed
13  * by the Internet Initiative Japan, Inc.  The name of the
14  * IIJ may not be used to endorse or promote products derived
15  * from this software without specific prior written permission.
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19  *
20  * $FreeBSD$
21  *
22  *	TODO:
23  */
24 
25 #include <sys/param.h>
26 #include <netinet/in.h>
27 #include <netinet/in_systm.h>
28 #include <netinet/ip.h>
29 #include <sys/un.h>
30 
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <paths.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <sys/time.h>
38 #include <termios.h>
39 #include <unistd.h>
40 #include <sys/stat.h>
41 
42 #ifndef NONAT
43 #ifdef __FreeBSD__
44 #include <alias.h>
45 #else
46 #include "alias.h"
47 #endif
48 #endif
49 #include "layer.h"
50 #include "probe.h"
51 #include "mbuf.h"
52 #include "log.h"
53 #include "defs.h"
54 #include "id.h"
55 #include "timer.h"
56 #include "fsm.h"
57 #include "lqr.h"
58 #include "hdlc.h"
59 #include "lcp.h"
60 #include "ccp.h"
61 #include "iplist.h"
62 #include "throughput.h"
63 #include "slcompress.h"
64 #include "ipcp.h"
65 #include "filter.h"
66 #include "descriptor.h"
67 #include "link.h"
68 #include "mp.h"
69 #ifndef NORADIUS
70 #include "radius.h"
71 #endif
72 #include "bundle.h"
73 #include "auth.h"
74 #include "systems.h"
75 #include "sig.h"
76 #include "main.h"
77 #include "server.h"
78 #include "prompt.h"
79 #include "chat.h"
80 #include "chap.h"
81 #include "cbcp.h"
82 #include "datalink.h"
83 #include "iface.h"
84 
85 #ifndef O_NONBLOCK
86 #ifdef O_NDELAY
87 #define	O_NONBLOCK O_NDELAY
88 #endif
89 #endif
90 
91 static void DoLoop(struct bundle *);
92 static void TerminalStop(int);
93 static const char *ex_desc(int);
94 
95 static struct bundle *SignalBundle;
96 static struct prompt *SignalPrompt;
97 
98 void
99 Cleanup(int excode)
100 {
101   SignalBundle->CleaningUp = 1;
102   bundle_Close(SignalBundle, NULL, CLOSE_STAYDOWN);
103 }
104 
105 void
106 AbortProgram(int excode)
107 {
108   server_Close(SignalBundle);
109   log_Printf(LogPHASE, "PPP Terminated (%s).\n", ex_desc(excode));
110   bundle_Close(SignalBundle, NULL, CLOSE_STAYDOWN);
111   bundle_Destroy(SignalBundle);
112   log_Close();
113   exit(excode);
114 }
115 
116 static void
117 CloseConnection(int signo)
118 {
119   /* NOTE, these are manual, we've done a setsid() */
120   sig_signal(SIGINT, SIG_IGN);
121   log_Printf(LogPHASE, "Caught signal %d, abort connection(s)\n", signo);
122   bundle_Down(SignalBundle, CLOSE_STAYDOWN);
123   sig_signal(SIGINT, CloseConnection);
124 }
125 
126 static void
127 CloseSession(int signo)
128 {
129   log_Printf(LogPHASE, "Signal %d, terminate.\n", signo);
130   Cleanup(EX_TERM);
131 }
132 
133 static pid_t BGPid = 0;
134 
135 static void
136 KillChild(int signo)
137 {
138   signal(signo, SIG_IGN);
139   log_Printf(LogPHASE, "Parent: Signal %d\n", signo);
140   kill(BGPid, SIGINT);
141 }
142 
143 static void
144 TerminalCont(int signo)
145 {
146   signal(SIGCONT, SIG_DFL);
147   prompt_Continue(SignalPrompt);
148 }
149 
150 static void
151 TerminalStop(int signo)
152 {
153   prompt_Suspend(SignalPrompt);
154   signal(SIGCONT, TerminalCont);
155   raise(SIGSTOP);
156 }
157 
158 static void
159 BringDownServer(int signo)
160 {
161   /* Drops all child prompts too ! */
162   server_Close(SignalBundle);
163 }
164 
165 static const char *
166 ex_desc(int ex)
167 {
168   static char num[12];		/* Used immediately if returned */
169   static const char *desc[] = {
170     "normal", "start", "sock", "modem", "dial", "dead", "done",
171     "reboot", "errdead", "hangup", "term", "nodial", "nologin"
172   };
173 
174   if (ex >= 0 && ex < sizeof desc / sizeof *desc)
175     return desc[ex];
176   snprintf(num, sizeof num, "%d", ex);
177   return num;
178 }
179 
180 static void
181 Usage(void)
182 {
183   fprintf(stderr,
184 	  "Usage: ppp [-auto | -foreground | -background | -direct | -dedicated | -ddial | -interactive]"
185 #ifndef NOALIAS
186           " [-nat]"
187 #endif
188           " [system ...]\n");
189   exit(EX_START);
190 }
191 
192 static int
193 ProcessArgs(int argc, char **argv, int *mode, int *nat, int *fg, int *quiet)
194 {
195   int optc, newmode, arg;
196   char *cp;
197 
198   optc = 0;
199   *mode = PHYS_INTERACTIVE;
200   *nat = 0;
201   *fg = 0;
202   *quiet = 0;
203   for (arg = 1; arg < argc && *argv[arg] == '-'; arg++, optc++) {
204     cp = argv[arg] + 1;
205     newmode = Nam2mode(cp);
206     switch (newmode) {
207       case PHYS_NONE:
208         if (strcmp(cp, "nat") == 0 || strcmp(cp, "alias") == 0) {
209 #ifdef NONAT
210           log_Printf(LogWARN, "Cannot load libalias (compiled out)\n");
211 #else
212           *nat = 1;
213 #endif
214           optc--;			/* this option isn't exclusive */
215         } else if (strcmp(cp, "quiet") == 0) {
216           *quiet = 1;
217           optc--;			/* this option isn't exclusive */
218         } else if (strcmp(cp, "foreground") == 0) {
219           *mode = PHYS_BACKGROUND;	/* Kinda like background mode */
220           *fg = 1;
221         } else
222           Usage();
223         break;
224 
225       case PHYS_ALL:
226         Usage();
227         break;
228 
229       default:
230         *mode = newmode;
231     }
232   }
233 
234   if (optc > 1) {
235     fprintf(stderr, "You may specify only one mode.\n");
236     exit(EX_START);
237   }
238 
239   if (*mode == PHYS_AUTO && arg == argc) {
240     fprintf(stderr, "A system must be specified in auto mode.\n");
241     exit(EX_START);
242   }
243 
244   return arg;		/* Don't SetLabel yet ! */
245 }
246 
247 static void
248 CheckLabel(const char *label, struct prompt *prompt, int mode)
249 {
250   const char *err;
251 
252   if ((err = system_IsValid(label, prompt, mode)) != NULL) {
253     fprintf(stderr, "%s: %s\n", label, err);
254     if (mode == PHYS_DIRECT)
255       log_Printf(LogWARN, "Label %s rejected -direct connection: %s\n",
256                  label, err);
257     log_Close();
258     exit(1);
259   }
260 }
261 
262 
263 int
264 main(int argc, char **argv)
265 {
266   char *name;
267   const char *lastlabel;
268   int nfds, mode, nat, fg, quiet, label, arg;
269   struct bundle *bundle;
270   struct prompt *prompt;
271 
272   nfds = getdtablesize();
273   if (nfds >= FD_SETSIZE)
274     /*
275      * If we've got loads of file descriptors, make sure they're all
276      * closed.  If they aren't, we may end up with a seg fault when our
277      * `fd_set's get too big when select()ing !
278      */
279     while (--nfds > 2)
280       close(nfds);
281 
282   name = strrchr(argv[0], '/');
283   log_Open(name ? name + 1 : argv[0]);
284 
285 #ifndef NONAT
286   PacketAliasInit();
287 #endif
288   label = ProcessArgs(argc, argv, &mode, &nat, &fg, &quiet);
289 
290   /*
291    * A FreeBSD & OpenBSD hack to dodge a bug in the tty driver that drops
292    * output occasionally.... I must find the real reason some time.  To
293    * display the dodgy behaviour, comment out this bit, make yourself a large
294    * routing table and then run ppp in interactive mode.  The `show route'
295    * command will drop chunks of data !!!
296    */
297   if (mode == PHYS_INTERACTIVE) {
298     close(STDIN_FILENO);
299     if (open(_PATH_TTY, O_RDONLY) != STDIN_FILENO) {
300       fprintf(stderr, "Cannot open %s for input !\n", _PATH_TTY);
301       return 2;
302     }
303   }
304 
305   /* Allow output for the moment (except in direct mode) */
306   if (mode == PHYS_DIRECT)
307     prompt = NULL;
308   else
309     SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD);
310 
311   ID0init();
312   if (ID0realuid() != 0) {
313     char conf[200], *ptr;
314 
315     snprintf(conf, sizeof conf, "%s/%s", _PATH_PPP, CONFFILE);
316     do {
317       struct stat sb;
318 
319       if (stat(conf, &sb) == 0 && sb.st_mode & S_IWOTH) {
320         log_Printf(LogALERT, "ppp: Access violation: Please protect %s\n",
321                    conf);
322         return -1;
323       }
324       ptr = conf + strlen(conf)-2;
325       while (ptr > conf && *ptr != '/')
326         *ptr-- = '\0';
327     } while (ptr >= conf);
328   }
329 
330   if (label < argc)
331     for (arg = label; arg < argc; arg++)
332       CheckLabel(argv[arg], prompt, mode);
333   else
334     CheckLabel("default", prompt, mode);
335 
336   if (!quiet)
337     prompt_Printf(prompt, "Working in %s mode\n", mode2Nam(mode));
338 
339   if ((bundle = bundle_Create(TUN_PREFIX, mode, (const char **)argv)) == NULL) {
340     log_Printf(LogWARN, "bundle_Create: %s\n", strerror(errno));
341     return EX_START;
342   }
343 
344   /* NOTE:  We may now have changed argv[1] via a ``set proctitle'' */
345 
346   if (prompt) {
347     prompt->bundle = bundle;	/* couldn't do it earlier */
348     if (!quiet)
349       prompt_Printf(prompt, "Using interface: %s\n", bundle->iface->name);
350   }
351   SignalBundle = bundle;
352   bundle->NatEnabled = nat;
353   if (nat)
354     bundle->cfg.opt |= OPT_IFACEALIAS;
355 
356   if (system_Select(bundle, "default", CONFFILE, prompt, NULL) < 0)
357     prompt_Printf(prompt, "Warning: No default entry found in config file.\n");
358 
359   sig_signal(SIGHUP, CloseSession);
360   sig_signal(SIGTERM, CloseSession);
361   sig_signal(SIGINT, CloseConnection);
362   sig_signal(SIGQUIT, CloseSession);
363   sig_signal(SIGALRM, SIG_IGN);
364   signal(SIGPIPE, SIG_IGN);
365 
366   if (mode == PHYS_INTERACTIVE)
367     sig_signal(SIGTSTP, TerminalStop);
368 
369   sig_signal(SIGUSR2, BringDownServer);
370 
371   lastlabel = argc == 2 ? bundle->argv1 : argv[argc - 1];
372   for (arg = label; arg < argc; arg++) {
373     /* In case we use LABEL or ``set enddisc label'' */
374     bundle_SetLabel(bundle, lastlabel);
375     system_Select(bundle, arg == 1 ? bundle->argv1 : argv[arg],
376                   CONFFILE, prompt, NULL);
377   }
378 
379   if (label < argc)
380     /* In case the last label did a ``load'' */
381     bundle_SetLabel(bundle, lastlabel);
382 
383   if (mode == PHYS_AUTO &&
384       bundle->ncp.ipcp.cfg.peer_range.ipaddr.s_addr == INADDR_ANY) {
385     prompt_Printf(prompt, "You must ``set ifaddr'' with a peer address "
386                   "in auto mode.\n");
387     AbortProgram(EX_START);
388   }
389 
390   if (mode != PHYS_INTERACTIVE) {
391     if (mode != PHYS_DIRECT) {
392       if (!fg) {
393         int bgpipe[2];
394         pid_t bgpid;
395 
396         if (mode == PHYS_BACKGROUND && pipe(bgpipe)) {
397           log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
398 	  AbortProgram(EX_SOCK);
399         }
400 
401         bgpid = fork();
402         if (bgpid == -1) {
403 	  log_Printf(LogERROR, "fork: %s\n", strerror(errno));
404 	  AbortProgram(EX_SOCK);
405         }
406 
407         if (bgpid) {
408 	  char c = EX_NORMAL;
409 
410 	  if (mode == PHYS_BACKGROUND) {
411 	    close(bgpipe[1]);
412 	    BGPid = bgpid;
413             /* If we get a signal, kill the child */
414             signal(SIGHUP, KillChild);
415             signal(SIGTERM, KillChild);
416             signal(SIGINT, KillChild);
417             signal(SIGQUIT, KillChild);
418 
419 	    /* Wait for our child to close its pipe before we exit */
420 	    if (read(bgpipe[0], &c, 1) != 1) {
421 	      prompt_Printf(prompt, "Child exit, no status.\n");
422 	      log_Printf(LogPHASE, "Parent: Child exit, no status.\n");
423 	    } else if (c == EX_NORMAL) {
424 	      prompt_Printf(prompt, "PPP enabled.\n");
425 	      log_Printf(LogPHASE, "Parent: PPP enabled.\n");
426 	    } else {
427 	      prompt_Printf(prompt, "Child failed (%s).\n", ex_desc((int) c));
428 	      log_Printf(LogPHASE, "Parent: Child failed (%s).\n",
429 		         ex_desc((int) c));
430 	    }
431 	    close(bgpipe[0]);
432 	  }
433 	  return c;
434         } else if (mode == PHYS_BACKGROUND) {
435 	  close(bgpipe[0]);
436           bundle->notify.fd = bgpipe[1];
437         }
438 
439         bundle_LockTun(bundle);	/* we have a new pid */
440       }
441 
442       /* -auto, -dedicated, -ddial, -foreground & -background */
443       prompt_Destroy(prompt, 0);
444       close(STDOUT_FILENO);
445       close(STDERR_FILENO);
446       close(STDIN_FILENO);
447       if (!fg)
448         setsid();
449     } else {
450       /* -direct - STDIN_FILENO gets used by physical_Open */
451       prompt_TtyInit(NULL);
452       close(STDOUT_FILENO);
453       close(STDERR_FILENO);
454     }
455   } else {
456     /* -interactive */
457     close(STDERR_FILENO);
458     prompt_TtyInit(prompt);
459     prompt_TtyCommandMode(prompt);
460     prompt_Required(prompt);
461   }
462 
463   log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(mode));
464   DoLoop(bundle);
465   AbortProgram(EX_NORMAL);
466 
467   return EX_NORMAL;
468 }
469 
470 static void
471 DoLoop(struct bundle *bundle)
472 {
473   fd_set rfds, wfds, efds;
474   int i, nfds, nothing_done;
475   struct probe probe;
476 
477   probe_Init(&probe);
478 
479   do {
480     nfds = 0;
481     FD_ZERO(&rfds);
482     FD_ZERO(&wfds);
483     FD_ZERO(&efds);
484 
485     /* All our datalinks, the tun device and the MP socket */
486     descriptor_UpdateSet(&bundle->desc, &rfds, &wfds, &efds, &nfds);
487 
488     /* All our prompts and the diagnostic socket */
489     descriptor_UpdateSet(&server.desc, &rfds, NULL, NULL, &nfds);
490 
491     if (bundle_IsDead(bundle))
492       /* Don't select - we'll be here forever */
493       break;
494 
495     /*
496      * It's possible that we've had a signal since we last checked.  If
497      * we don't check again before calling select(), we may end up stuck
498      * after having missed the event.... sig_Handle() tries to be as
499      * quick as possible if nothing is likely to have happened.
500      * This is only really likely if we block in open(... O_NONBLOCK)
501      * which will happen with a misconfigured device.
502      */
503     if (sig_Handle())
504       continue;
505 
506     i = select(nfds, &rfds, &wfds, &efds, NULL);
507 
508     if (i < 0 && errno != EINTR) {
509       log_Printf(LogERROR, "DoLoop: select(): %s\n", strerror(errno));
510       if (log_IsKept(LogTIMER)) {
511         struct timeval t;
512 
513         for (i = 0; i <= nfds; i++) {
514           if (FD_ISSET(i, &rfds)) {
515             log_Printf(LogTIMER, "Read set contains %d\n", i);
516             FD_CLR(i, &rfds);
517             t.tv_sec = t.tv_usec = 0;
518             if (select(nfds, &rfds, &wfds, &efds, &t) != -1) {
519               log_Printf(LogTIMER, "The culprit !\n");
520               break;
521             }
522           }
523           if (FD_ISSET(i, &wfds)) {
524             log_Printf(LogTIMER, "Write set contains %d\n", i);
525             FD_CLR(i, &wfds);
526             t.tv_sec = t.tv_usec = 0;
527             if (select(nfds, &rfds, &wfds, &efds, &t) != -1) {
528               log_Printf(LogTIMER, "The culprit !\n");
529               break;
530             }
531           }
532           if (FD_ISSET(i, &efds)) {
533             log_Printf(LogTIMER, "Error set contains %d\n", i);
534             FD_CLR(i, &efds);
535             t.tv_sec = t.tv_usec = 0;
536             if (select(nfds, &rfds, &wfds, &efds, &t) != -1) {
537               log_Printf(LogTIMER, "The culprit !\n");
538               break;
539             }
540           }
541         }
542       }
543       break;
544     }
545 
546     log_Printf(LogTIMER, "Select returns %d\n", i);
547 
548     sig_Handle();
549 
550     if (i <= 0)
551       continue;
552 
553     for (i = 0; i <= nfds; i++)
554       if (FD_ISSET(i, &efds)) {
555         log_Printf(LogPHASE, "Exception detected on descriptor %d\n", i);
556         /* We deal gracefully with link descriptor exceptions */
557         if (!bundle_Exception(bundle, i)) {
558           log_Printf(LogERROR, "Exception cannot be handled !\n");
559           break;
560         }
561       }
562 
563     if (i <= nfds)
564       break;
565 
566     nothing_done = 1;
567 
568     if (descriptor_IsSet(&server.desc, &rfds)) {
569       descriptor_Read(&server.desc, bundle, &rfds);
570       nothing_done = 0;
571     }
572 
573     if (descriptor_IsSet(&bundle->desc, &rfds)) {
574       descriptor_Read(&bundle->desc, bundle, &rfds);
575       nothing_done = 0;
576     }
577 
578     if (descriptor_IsSet(&bundle->desc, &wfds))
579       if (!descriptor_Write(&bundle->desc, bundle, &wfds) && nothing_done) {
580         /*
581          * This is disasterous.  The OS has told us that something is
582          * writable, and all our write()s have failed.  Rather than
583          * going back immediately to do our UpdateSet()s and select(),
584          * we sleep for a bit to avoid gobbling up all cpu time.
585          */
586         struct timeval t;
587 
588         t.tv_sec = 0;
589         t.tv_usec = 100000;
590         select(0, NULL, NULL, NULL, &t);
591       }
592   } while (bundle_CleanDatalinks(bundle), !bundle_IsDead(bundle));
593 
594   log_Printf(LogDEBUG, "DoLoop done.\n");
595 }
596