main.c revision 36314
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.123 1998/05/21 21:46:40 brian Exp $
21 *
22 *	TODO:
23 */
24
25#include <sys/param.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 char pid_filename[MAXPATHLEN];
82
83static void DoLoop(struct bundle *, struct prompt *);
84static void TerminalStop(int);
85static const char *ex_desc(int);
86
87static struct bundle *SignalBundle;
88static struct prompt *SignalPrompt;
89
90void
91Cleanup(int excode)
92{
93  SignalBundle->CleaningUp = 1;
94  if (bundle_Phase(SignalBundle) != PHASE_DEAD)
95    bundle_Close(SignalBundle, NULL, 1);
96}
97
98void
99AbortProgram(int excode)
100{
101  server_Close(SignalBundle);
102  ID0unlink(pid_filename);
103  log_Printf(LogPHASE, "PPP Terminated (%s).\n", ex_desc(excode));
104  bundle_Close(SignalBundle, NULL, 1);
105  bundle_Destroy(SignalBundle);
106  log_Close();
107  exit(excode);
108}
109
110static void
111CloseConnection(int signo)
112{
113  /* NOTE, these are manual, we've done a setsid() */
114  sig_signal(SIGINT, SIG_IGN);
115  log_Printf(LogPHASE, "Caught signal %d, abort connection(s)\n", signo);
116  bundle_Down(SignalBundle);
117  sig_signal(SIGINT, CloseConnection);
118}
119
120static void
121CloseSession(int signo)
122{
123  log_Printf(LogPHASE, "Signal %d, terminate.\n", signo);
124  Cleanup(EX_TERM);
125}
126
127static pid_t BGPid = 0;
128
129static void
130KillChild(int signo)
131{
132  log_Printf(LogPHASE, "Parent: Signal %d\n", signo);
133  kill(BGPid, SIGINT);
134}
135
136static void
137TerminalCont(int signo)
138{
139  signal(SIGCONT, SIG_DFL);
140  prompt_Continue(SignalPrompt);
141}
142
143static void
144TerminalStop(int signo)
145{
146  prompt_Suspend(SignalPrompt);
147  signal(SIGCONT, TerminalCont);
148  raise(SIGSTOP);
149}
150
151static void
152BringDownServer(int signo)
153{
154  /* Drops all child prompts too ! */
155  server_Close(SignalBundle);
156}
157
158static const char *
159ex_desc(int ex)
160{
161  static char num[12];
162  static const char *desc[] = {
163    "normal", "start", "sock", "modem", "dial", "dead", "done",
164    "reboot", "errdead", "hangup", "term", "nodial", "nologin"
165  };
166
167  if (ex >= 0 && ex < sizeof desc / sizeof *desc)
168    return desc[ex];
169  snprintf(num, sizeof num, "%d", ex);
170  return num;
171}
172
173static void
174Usage(void)
175{
176  fprintf(stderr,
177	  "Usage: ppp [-auto | -background | -direct | -dedicated | -ddial ]"
178#ifndef NOALIAS
179          " [ -alias ]"
180#endif
181          " [system]\n");
182  exit(EX_START);
183}
184
185static char *
186ProcessArgs(int argc, char **argv, int *mode)
187{
188  int optc, labelrequired;
189  char *cp;
190
191  optc = labelrequired = 0;
192  *mode = PHYS_MANUAL;
193  while (argc > 0 && **argv == '-') {
194    cp = *argv + 1;
195    if (strcmp(cp, "auto") == 0) {
196      *mode = PHYS_DEMAND;
197      labelrequired = 1;
198    } else if (strcmp(cp, "background") == 0) {
199      *mode = PHYS_1OFF;
200      labelrequired = 1;
201    } else if (strcmp(cp, "direct") == 0)
202      *mode = PHYS_DIRECT;
203    else if (strcmp(cp, "dedicated") == 0)
204      *mode = PHYS_DEDICATED;
205    else if (strcmp(cp, "ddial") == 0) {
206      *mode = PHYS_PERM;
207      labelrequired = 1;
208    } else if (strcmp(cp, "alias") == 0) {
209#ifndef NOALIAS
210      if (alias_Load() != 0)
211#endif
212	log_Printf(LogWARN, "Cannot load alias library\n");
213      optc--;			/* this option isn't exclusive */
214    } else
215      Usage();
216    optc++;
217    argv++;
218    argc--;
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  FILE *lockfile;
243  char *name, *label;
244  int nfds, mode;
245  struct bundle *bundle;
246  struct prompt *prompt;
247
248  nfds = getdtablesize();
249  if (nfds >= FD_SETSIZE)
250    /*
251     * If we've got loads of file descriptors, make sure they're all
252     * closed.  If they aren't, we may end up with a seg fault when our
253     * `fd_set's get too big when select()ing !
254     */
255    while (--nfds > 2)
256      close(nfds);
257
258  name = strrchr(argv[0], '/');
259  log_Open(name ? name + 1 : argv[0]);
260
261  argc--;
262  argv++;
263  label = ProcessArgs(argc, argv, &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_MANUAL) {
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    const char *m;
287
288    SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD);
289    if (mode == PHYS_PERM)
290      m = "direct dial";
291    else if (mode & PHYS_1OFF)
292      m = "background";
293    else if (mode & PHYS_DEMAND)
294      m = "auto";
295    else if (mode & PHYS_DEDICATED)
296      m = "dedicated";
297    else if (mode & PHYS_MANUAL)
298      m = "interactive";
299    else
300      m = NULL;
301
302    if (m)
303      prompt_Printf(prompt, "Working in %s mode\n", m);
304  }
305
306  ID0init();
307  if (ID0realuid() != 0) {
308    char conf[200], *ptr;
309
310    snprintf(conf, sizeof conf, "%s/%s", _PATH_PPP, CONFFILE);
311    do {
312      if (!access(conf, W_OK)) {
313        log_Printf(LogALERT, "ppp: Access violation: Please protect %s\n", conf);
314        return -1;
315      }
316      ptr = conf + strlen(conf)-2;
317      while (ptr > conf && *ptr != '/')
318        *ptr-- = '\0';
319    } while (ptr >= conf);
320  }
321
322  if (!system_IsValid(label, prompt, mode)) {
323    fprintf(stderr, "You may not use ppp in this mode with this label\n");
324    if (mode == PHYS_DIRECT) {
325      const char *l;
326      l = label ? label : "default";
327      log_Printf(LogWARN, "Label %s rejected -direct connection\n", l);
328    }
329    log_Close();
330    return 1;
331  }
332
333  if ((bundle = bundle_Create(TUN_PREFIX, mode)) == NULL) {
334    log_Printf(LogWARN, "bundle_Create: %s\n", strerror(errno));
335    return EX_START;
336  }
337  if (prompt) {
338    prompt->bundle = bundle;	/* couldn't do it earlier */
339    prompt_Printf(prompt, "Using interface: %s\n", bundle->ifp.Name);
340  }
341  SignalBundle = bundle;
342
343  if (system_Select(bundle, "default", CONFFILE, prompt) < 0)
344    prompt_Printf(prompt, "Warning: No default entry found in config file.\n");
345
346  sig_signal(SIGHUP, CloseSession);
347  sig_signal(SIGTERM, CloseSession);
348  sig_signal(SIGINT, CloseConnection);
349  sig_signal(SIGQUIT, CloseSession);
350  sig_signal(SIGALRM, SIG_IGN);
351  signal(SIGPIPE, SIG_IGN);
352
353  if (mode == PHYS_MANUAL)
354    sig_signal(SIGTSTP, TerminalStop);
355
356  sig_signal(SIGUSR2, BringDownServer);
357
358  if (label) {
359    /*
360     * Set label both before and after system_Select !
361     * This way, "set enddisc label" works during system_Select, and we
362     * also end up with the correct label if we have embedded load
363     * commands.
364     */
365    bundle_SetLabel(bundle, label);
366    if (system_Select(bundle, label, CONFFILE, prompt) < 0) {
367      prompt_Printf(prompt, "Destination system (%s) not found.\n", label);
368      AbortProgram(EX_START);
369    }
370    bundle_SetLabel(bundle, label);
371    if (mode == PHYS_DEMAND &&
372	bundle->ncp.ipcp.cfg.peer_range.ipaddr.s_addr == INADDR_ANY) {
373      prompt_Printf(prompt, "You must \"set ifaddr\" with a peer address "
374                    "in label %s for auto mode.\n", label);
375      AbortProgram(EX_START);
376    }
377  }
378
379  if (mode != PHYS_MANUAL) {
380    if (mode != PHYS_DIRECT) {
381      int bgpipe[2];
382      pid_t bgpid;
383
384      if (mode == PHYS_1OFF && pipe(bgpipe)) {
385        log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
386	AbortProgram(EX_SOCK);
387      }
388
389      bgpid = fork();
390      if (bgpid == -1) {
391	log_Printf(LogERROR, "fork: %s\n", strerror(errno));
392	AbortProgram(EX_SOCK);
393      }
394
395      if (bgpid) {
396	char c = EX_NORMAL;
397
398	if (mode == PHYS_1OFF) {
399	  close(bgpipe[1]);
400	  BGPid = bgpid;
401          /* If we get a signal, kill the child */
402          signal(SIGHUP, KillChild);
403          signal(SIGTERM, KillChild);
404          signal(SIGINT, KillChild);
405          signal(SIGQUIT, KillChild);
406
407	  /* Wait for our child to close its pipe before we exit */
408	  if (read(bgpipe[0], &c, 1) != 1) {
409	    prompt_Printf(prompt, "Child exit, no status.\n");
410	    log_Printf(LogPHASE, "Parent: Child exit, no status.\n");
411	  } else if (c == EX_NORMAL) {
412	    prompt_Printf(prompt, "PPP enabled.\n");
413	    log_Printf(LogPHASE, "Parent: PPP enabled.\n");
414	  } else {
415	    prompt_Printf(prompt, "Child failed (%s).\n", ex_desc((int) c));
416	    log_Printf(LogPHASE, "Parent: Child failed (%s).\n",
417		      ex_desc((int) c));
418	  }
419	  close(bgpipe[0]);
420	}
421	return c;
422      } else if (mode == PHYS_1OFF) {
423	close(bgpipe[0]);
424        bundle->notify.fd = bgpipe[1];
425      }
426
427      /* -auto, -dedicated, -ddial & -background */
428      prompt_Destroy(prompt, 0);
429      close(STDOUT_FILENO);
430      close(STDERR_FILENO);
431      close(STDIN_FILENO);
432      setsid();
433    } else {
434      /* -direct: STDIN_FILENO gets used by modem_Open */
435      prompt_TtyInit(NULL);
436      close(STDOUT_FILENO);
437      close(STDERR_FILENO);
438    }
439  } else {
440    /* Interactive mode */
441    close(STDERR_FILENO);
442    prompt_TtyInit(prompt);
443    prompt_TtyCommandMode(prompt);
444    prompt_Required(prompt);
445  }
446
447  snprintf(pid_filename, sizeof pid_filename, "%stun%d.pid",
448           _PATH_VARRUN, bundle->unit);
449  lockfile = ID0fopen(pid_filename, "w");
450  if (lockfile != NULL) {
451    fprintf(lockfile, "%d\n", (int) getpid());
452    fclose(lockfile);
453  }
454#ifndef RELEASE_CRUNCH
455  else
456    log_Printf(LogALERT, "Warning: Can't create %s: %s\n",
457              pid_filename, strerror(errno));
458#endif
459
460  log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(mode));
461  DoLoop(bundle, prompt);
462  AbortProgram(EX_NORMAL);
463
464  return EX_NORMAL;
465}
466
467static void
468DoLoop(struct bundle *bundle, struct prompt *prompt)
469{
470  fd_set rfds, wfds, efds;
471  int i, nfds;
472
473  do {
474    nfds = 0;
475    FD_ZERO(&rfds);
476    FD_ZERO(&wfds);
477    FD_ZERO(&efds);
478
479    sig_Handle();
480
481    /* All our datalinks, the tun device and the MP socket */
482    descriptor_UpdateSet(&bundle->desc, &rfds, &wfds, &efds, &nfds);
483
484    /* All our prompts and the diagnostic socket */
485    descriptor_UpdateSet(&server.desc, &rfds, NULL, NULL, &nfds);
486
487    if (bundle_IsDead(bundle))
488      /* Don't select - we'll be here forever */
489      break;
490
491    i = select(nfds, &rfds, &wfds, &efds, NULL);
492
493    if (i == 0)
494      continue;
495    else if (i < 0) {
496      if (errno == EINTR)
497	continue;
498      log_Printf(LogERROR, "DoLoop: select(): %s\n", strerror(errno));
499      if (log_IsKept(LogTIMER)) {
500        struct timeval t;
501
502        for (i = 0; i <= nfds; i++) {
503          if (FD_ISSET(i, &rfds)) {
504            log_Printf(LogTIMER, "Read set contains %d\n", i);
505            FD_CLR(i, &rfds);
506            t.tv_sec = t.tv_usec = 0;
507            if (select(nfds, &rfds, &wfds, &efds, &t) != -1) {
508              log_Printf(LogTIMER, "The culprit !\n");
509              break;
510            }
511          }
512          if (FD_ISSET(i, &wfds)) {
513            log_Printf(LogTIMER, "Write set contains %d\n", i);
514            FD_CLR(i, &wfds);
515            t.tv_sec = t.tv_usec = 0;
516            if (select(nfds, &rfds, &wfds, &efds, &t) != -1) {
517              log_Printf(LogTIMER, "The culprit !\n");
518              break;
519            }
520          }
521          if (FD_ISSET(i, &efds)) {
522            log_Printf(LogTIMER, "Error set contains %d\n", i);
523            FD_CLR(i, &efds);
524            t.tv_sec = t.tv_usec = 0;
525            if (select(nfds, &rfds, &wfds, &efds, &t) != -1) {
526              log_Printf(LogTIMER, "The culprit !\n");
527              break;
528            }
529          }
530        }
531      }
532      break;
533    }
534
535    for (i = 0; i <= nfds; i++)
536      if (FD_ISSET(i, &efds)) {
537        log_Printf(LogALERT, "Exception detected on descriptor %d\n", i);
538        break;
539      }
540
541    if (i <= nfds)
542      break;
543
544    if (descriptor_IsSet(&server.desc, &rfds))
545      descriptor_Read(&server.desc, bundle, &rfds);
546
547    if (descriptor_IsSet(&bundle->desc, &wfds))
548      descriptor_Write(&bundle->desc, bundle, &wfds);
549
550    if (descriptor_IsSet(&bundle->desc, &rfds))
551      descriptor_Read(&bundle->desc, bundle, &rfds);
552  } while (bundle_CleanDatalinks(bundle), !bundle_IsDead(bundle));
553
554  log_Printf(LogDEBUG, "DoLoop done.\n");
555}
556