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