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