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