main.c revision 36285
1185377Ssam/*
2185377Ssam *			User Process PPP
3185377Ssam *
4185377Ssam *	    Written by Toshiharu OHNO (tony-o@iij.ad.jp)
5185377Ssam *
6185377Ssam *   Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd.
7185377Ssam *
8185377Ssam * Redistribution and use in source and binary forms are permitted
9185377Ssam * provided that the above copyright notice and this paragraph are
10185377Ssam * duplicated in all such forms and that any documentation,
11185377Ssam * advertising materials, and other materials related to such
12185377Ssam * distribution and use acknowledge that the software was developed
13185377Ssam * by the Internet Initiative Japan, Inc.  The name of the
14185377Ssam * IIJ may not be used to endorse or promote products derived
15185377Ssam * from this software without specific prior written permission.
16185377Ssam * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17185377Ssam * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18185377Ssam * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19185377Ssam *
20185377Ssam * $Id: main.c,v 1.121.2.60 1998/05/15 18:21:38 brian Exp $
21185377Ssam *
22185377Ssam *	TODO:
23185377Ssam */
24185377Ssam
25185377Ssam#include <sys/param.h>
26185377Ssam#include <sys/socket.h>
27185377Ssam#include <netinet/in.h>
28185377Ssam#include <netinet/in_systm.h>
29185377Ssam#include <netinet/ip.h>
30185377Ssam#include <sys/un.h>
31185377Ssam#include <net/if_tun.h>
32185377Ssam
33185377Ssam#include <errno.h>
34185377Ssam#include <fcntl.h>
35185377Ssam#include <paths.h>
36185377Ssam#include <signal.h>
37185377Ssam#include <stdio.h>
38185377Ssam#include <string.h>
39185377Ssam#include <sys/time.h>
40185377Ssam#include <termios.h>
41185377Ssam#include <unistd.h>
42185377Ssam
43185377Ssam#include "mbuf.h"
44185377Ssam#include "log.h"
45185377Ssam#include "defs.h"
46185377Ssam#include "id.h"
47185377Ssam#include "timer.h"
48185377Ssam#include "fsm.h"
49185377Ssam#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, prompt, mode)) == NULL) {
334    log_Printf(LogWARN, "bundle_Create: %s\n", strerror(errno));
335    return EX_START;
336  }
337  SignalBundle = bundle;
338
339  if (system_Select(bundle, "default", CONFFILE, prompt) < 0)
340    prompt_Printf(prompt, "Warning: No default entry found in config file.\n");
341
342  sig_signal(SIGHUP, CloseSession);
343  sig_signal(SIGTERM, CloseSession);
344  sig_signal(SIGINT, CloseConnection);
345  sig_signal(SIGQUIT, CloseSession);
346  sig_signal(SIGALRM, SIG_IGN);
347  signal(SIGPIPE, SIG_IGN);
348
349  if (mode == PHYS_MANUAL)
350    sig_signal(SIGTSTP, TerminalStop);
351
352  sig_signal(SIGUSR2, BringDownServer);
353
354  if (label) {
355    /*
356     * Set label both before and after system_Select !
357     * This way, "set enddisc label" works during system_Select, and we
358     * also end up with the correct label if we have embedded load
359     * commands.
360     */
361    bundle_SetLabel(bundle, label);
362    if (system_Select(bundle, label, CONFFILE, prompt) < 0) {
363      prompt_Printf(prompt, "Destination system (%s) not found.\n", label);
364      AbortProgram(EX_START);
365    }
366    bundle_SetLabel(bundle, label);
367    if (mode == PHYS_DEMAND &&
368	bundle->ncp.ipcp.cfg.peer_range.ipaddr.s_addr == INADDR_ANY) {
369      prompt_Printf(prompt, "You must \"set ifaddr\" with a peer address "
370                    "in label %s for auto mode.\n", label);
371      AbortProgram(EX_START);
372    }
373  }
374
375  if (mode != PHYS_MANUAL) {
376    if (mode != PHYS_DIRECT) {
377      int bgpipe[2];
378      pid_t bgpid;
379
380      if (mode == PHYS_1OFF && 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_1OFF) {
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_1OFF) {
419	close(bgpipe[0]);
420        bundle->notify.fd = bgpipe[1];
421      }
422
423      /* -auto, -dedicated, -ddial & -background */
424      prompt_Destroy(prompt, 0);
425      close(STDOUT_FILENO);
426      close(STDERR_FILENO);
427      close(STDIN_FILENO);
428      setsid();
429    } else {
430      /* -direct: STDIN_FILENO gets used by modem_Open */
431      prompt_TtyInit(NULL);
432      close(STDOUT_FILENO);
433      close(STDERR_FILENO);
434    }
435  } else {
436    /* Interactive mode */
437    close(STDERR_FILENO);
438    prompt_TtyInit(prompt);
439    prompt_TtyCommandMode(prompt);
440    prompt_Required(prompt);
441  }
442
443  snprintf(pid_filename, sizeof pid_filename, "%stun%d.pid",
444           _PATH_VARRUN, bundle->unit);
445  lockfile = ID0fopen(pid_filename, "w");
446  if (lockfile != NULL) {
447    fprintf(lockfile, "%d\n", (int) getpid());
448    fclose(lockfile);
449  }
450#ifndef RELEASE_CRUNCH
451  else
452    log_Printf(LogALERT, "Warning: Can't create %s: %s\n",
453              pid_filename, strerror(errno));
454#endif
455
456  log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(mode));
457  DoLoop(bundle, prompt);
458  AbortProgram(EX_NORMAL);
459
460  return EX_NORMAL;
461}
462
463static void
464DoLoop(struct bundle *bundle, struct prompt *prompt)
465{
466  fd_set rfds, wfds, efds;
467  int i, nfds;
468
469  do {
470    nfds = 0;
471    FD_ZERO(&rfds);
472    FD_ZERO(&wfds);
473    FD_ZERO(&efds);
474
475    sig_Handle();
476
477    descriptor_UpdateSet(&bundle->desc, &rfds, &wfds, &efds, &nfds);
478    descriptor_UpdateSet(&server.desc, &rfds, &wfds, &efds, &nfds);
479
480    if (bundle_IsDead(bundle))
481      /* Don't select - we'll be here forever */
482      break;
483
484    i = select(nfds, &rfds, &wfds, &efds, NULL);
485
486    if (i == 0)
487      continue;
488    else if (i < 0) {
489      if (errno == EINTR)
490	continue;
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    for (i = 0; i <= nfds; i++)
529      if (FD_ISSET(i, &efds)) {
530        log_Printf(LogALERT, "Exception detected on descriptor %d\n", i);
531        break;
532      }
533
534    if (i <= nfds)
535      break;
536
537    if (descriptor_IsSet(&server.desc, &rfds))
538      descriptor_Read(&server.desc, bundle, &rfds);
539
540    if (descriptor_IsSet(&bundle->desc, &wfds))
541      descriptor_Write(&bundle->desc, bundle, &wfds);
542
543    if (descriptor_IsSet(&bundle->desc, &rfds))
544      descriptor_Read(&bundle->desc, bundle, &rfds);
545  } while (bundle_CleanDatalinks(bundle), !bundle_IsDead(bundle));
546
547  log_Printf(LogDEBUG, "DoLoop done.\n");
548}
549