xref: /freebsd/usr.sbin/ppp/main.c (revision 565e35e50e2cdac423588a3d18742544bde128b0)
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.121.2.47 1998/04/07 23:46:02 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 <termios.h>
38 #include <unistd.h>
39 
40 #include "mbuf.h"
41 #include "log.h"
42 #include "defs.h"
43 #include "id.h"
44 #include "timer.h"
45 #include "fsm.h"
46 #include "lqr.h"
47 #include "hdlc.h"
48 #include "lcp.h"
49 #include "ccp.h"
50 #include "iplist.h"
51 #include "throughput.h"
52 #include "slcompress.h"
53 #include "ipcp.h"
54 #include "filter.h"
55 #include "descriptor.h"
56 #include "link.h"
57 #include "mp.h"
58 #include "bundle.h"
59 #include "loadalias.h"
60 #include "vars.h"
61 #include "auth.h"
62 #include "systems.h"
63 #include "ip.h"
64 #include "sig.h"
65 #include "main.h"
66 #include "pathnames.h"
67 #include "tun.h"
68 #include "server.h"
69 #include "prompt.h"
70 #include "chat.h"
71 #include "chap.h"
72 #include "datalink.h"
73 
74 #ifndef O_NONBLOCK
75 #ifdef O_NDELAY
76 #define	O_NONBLOCK O_NDELAY
77 #endif
78 #endif
79 
80 static char pid_filename[MAXPATHLEN];
81 
82 static void DoLoop(struct bundle *, struct prompt *);
83 static void TerminalStop(int);
84 static const char *ex_desc(int);
85 
86 static struct bundle *SignalBundle;
87 static struct prompt *SignalPrompt;
88 
89 void
90 Cleanup(int excode)
91 {
92   SignalBundle->CleaningUp = 1;
93   if (bundle_Phase(SignalBundle) != PHASE_DEAD)
94     bundle_Close(SignalBundle, NULL, 1);
95 }
96 
97 void
98 AbortProgram(int excode)
99 {
100   ServerClose(SignalBundle);
101   ID0unlink(pid_filename);
102   LogPrintf(LogPHASE, "PPP Terminated (%s).\n", ex_desc(excode));
103   bundle_Close(SignalBundle, NULL, 1);
104   bundle_Destroy(SignalBundle);
105   LogClose();
106   exit(excode);
107 }
108 
109 static void
110 CloseConnection(int signo)
111 {
112   /* NOTE, these are manual, we've done a setsid() */
113   struct datalink *dl;
114 
115   pending_signal(SIGINT, SIG_IGN);
116   LogPrintf(LogPHASE, "Caught signal %d, abort connection(s)\n", signo);
117   for (dl = SignalBundle->links; dl; dl = dl->next)
118     datalink_Down(dl, 1);
119   pending_signal(SIGINT, CloseConnection);
120 }
121 
122 static void
123 CloseSession(int signo)
124 {
125   LogPrintf(LogPHASE, "Signal %d, terminate.\n", signo);
126   Cleanup(EX_TERM);
127 }
128 
129 static pid_t BGPid = 0;
130 
131 static void
132 KillChild(int signo)
133 {
134   LogPrintf(LogPHASE, "Parent: Signal %d\n", signo);
135   kill(BGPid, SIGINT);
136 }
137 
138 static void
139 TerminalCont(int signo)
140 {
141   signal(SIGCONT, SIG_DFL);
142   prompt_Continue(SignalPrompt);
143 }
144 
145 static void
146 TerminalStop(int signo)
147 {
148   prompt_Suspend(SignalPrompt);
149   signal(SIGCONT, TerminalCont);
150   raise(SIGSTOP);
151 }
152 
153 #if 0 /* What's our passwd :-O */
154 static void
155 SetUpServer(int signo)
156 {
157   int res;
158 
159   VarHaveLocalAuthKey = 0;
160   LocalAuthInit();
161   if ((res = ServerTcpOpen(SERVER_PORT + SignalBundle->unit)) != 0)
162     LogPrintf(LogERROR, "SIGUSR1: Failed %d to open port %d\n",
163 	      res, SERVER_PORT + SignalBundle->unit);
164 }
165 #endif
166 
167 static void
168 BringDownServer(int signo)
169 {
170   /* Drops all child prompts too ! */
171   ServerClose(SignalBundle);
172 }
173 
174 static const char *
175 ex_desc(int ex)
176 {
177   static char num[12];
178   static const char *desc[] = {
179     "normal", "start", "sock", "modem", "dial", "dead", "done",
180     "reboot", "errdead", "hangup", "term", "nodial", "nologin"
181   };
182 
183   if (ex >= 0 && ex < sizeof desc / sizeof *desc)
184     return desc[ex];
185   snprintf(num, sizeof num, "%d", ex);
186   return num;
187 }
188 
189 static void
190 Usage(void)
191 {
192   fprintf(stderr,
193 	  "Usage: ppp [-auto | -background | -direct | -dedicated | -ddial ]"
194 #ifndef NOALIAS
195           " [ -alias ]"
196 #endif
197           " [system]\n");
198   exit(EX_START);
199 }
200 
201 static char *
202 ProcessArgs(int argc, char **argv, int *mode)
203 {
204   int optc, labelrequired;
205   char *cp;
206 
207   optc = labelrequired = 0;
208   *mode = PHYS_MANUAL;
209   while (argc > 0 && **argv == '-') {
210     cp = *argv + 1;
211     if (strcmp(cp, "auto") == 0) {
212       *mode = PHYS_DEMAND;
213       labelrequired = 1;
214     } else if (strcmp(cp, "background") == 0) {
215       *mode = PHYS_1OFF;
216       labelrequired = 1;
217     } else if (strcmp(cp, "direct") == 0)
218       *mode = PHYS_STDIN;
219     else if (strcmp(cp, "dedicated") == 0)
220       *mode = PHYS_DEDICATED;
221     else if (strcmp(cp, "ddial") == 0) {
222       *mode = PHYS_PERM;
223       labelrequired = 1;
224     } else if (strcmp(cp, "alias") == 0) {
225 #ifndef NOALIAS
226       if (loadAliasHandlers() != 0)
227 #endif
228 	LogPrintf(LogWARN, "Cannot load alias library\n");
229       optc--;			/* this option isn't exclusive */
230     } else
231       Usage();
232     optc++;
233     argv++;
234     argc--;
235   }
236   if (argc > 1) {
237     fprintf(stderr, "You may specify only one system label.\n");
238     exit(EX_START);
239   }
240 
241   if (optc > 1) {
242     fprintf(stderr, "You may specify only one mode.\n");
243     exit(EX_START);
244   }
245 
246   if (labelrequired && argc != 1) {
247     fprintf(stderr, "Destination system must be specified in"
248             " auto, background or ddial mode.\n");
249     exit(EX_START);
250   }
251 
252   return argc == 1 ? *argv : NULL;	/* Don't SetLabel yet ! */
253 }
254 
255 int
256 main(int argc, char **argv)
257 {
258   FILE *lockfile;
259   char *name, *label;
260   int nfds, mode;
261   struct bundle *bundle;
262   struct prompt *prompt;
263 
264   nfds = getdtablesize();
265   if (nfds >= FD_SETSIZE)
266     /*
267      * If we've got loads of file descriptors, make sure they're all
268      * closed.  If they aren't, we may end up with a seg fault when our
269      * `fd_set's get too big when select()ing !
270      */
271     while (--nfds > 2)
272       close(nfds);
273 
274   name = strrchr(argv[0], '/');
275   LogOpen(name ? name + 1 : argv[0]);
276 
277   argc--;
278   argv++;
279   label = ProcessArgs(argc, argv, &mode);
280 
281 #ifdef __FreeBSD__
282   /*
283    * A FreeBSD hack to dodge a bug in the tty driver that drops output
284    * occasionally.... I must find the real reason some time.  To display
285    * the dodgy behaviour, comment out this bit, make yourself a large
286    * routing table and then run ppp in interactive mode.  The `show route'
287    * command will drop chunks of data !!!
288    */
289   if (mode == PHYS_MANUAL) {
290     close(STDIN_FILENO);
291     if (open(_PATH_TTY, O_RDONLY) != STDIN_FILENO) {
292       fprintf(stderr, "Cannot open %s for input !\n", _PATH_TTY);
293       return 2;
294     }
295   }
296 #endif
297 
298   /* Allow output for the moment (except in direct mode) */
299   if (mode == PHYS_STDIN)
300     prompt = NULL;
301   else {
302     const char *m;
303 
304     SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD);
305     if (mode == PHYS_PERM)
306       m = "direct dial";
307     else if (mode & PHYS_1OFF)
308       m = "background";
309     else if (mode & PHYS_DEMAND)
310       m = "auto";
311     else if (mode & PHYS_DEDICATED)
312       m = "dedicated";
313     else if (mode & PHYS_MANUAL)
314       m = "interactive";
315     else
316       m = NULL;
317 
318     if (m)
319       prompt_Printf(prompt, "Working in %s mode\n", m);
320   }
321 
322   ID0init();
323   if (ID0realuid() != 0) {
324     char conf[200], *ptr;
325 
326     snprintf(conf, sizeof conf, "%s/%s", _PATH_PPP, CONFFILE);
327     do {
328       if (!access(conf, W_OK)) {
329         LogPrintf(LogALERT, "ppp: Access violation: Please protect %s\n", conf);
330         return -1;
331       }
332       ptr = conf + strlen(conf)-2;
333       while (ptr > conf && *ptr != '/')
334         *ptr-- = '\0';
335     } while (ptr >= conf);
336   }
337 
338   if (!ValidSystem(label, prompt, mode)) {
339     fprintf(stderr, "You may not use ppp in this mode with this label\n");
340     if (mode == PHYS_STDIN) {
341       const char *l;
342       l = label ? label : "default";
343       LogPrintf(LogWARN, "Label %s rejected -direct connection\n", l);
344     }
345     LogClose();
346     return 1;
347   }
348 
349   if ((bundle = bundle_Create(TUN_PREFIX, prompt, mode)) == NULL) {
350     LogPrintf(LogWARN, "bundle_Create: %s\n", strerror(errno));
351     return EX_START;
352   }
353   SignalBundle = bundle;
354 
355   if (SelectSystem(bundle, "default", CONFFILE, prompt) < 0)
356     prompt_Printf(prompt, "Warning: No default entry found in config file.\n");
357 
358   pending_signal(SIGHUP, CloseSession);
359   pending_signal(SIGTERM, CloseSession);
360   pending_signal(SIGINT, CloseConnection);
361   pending_signal(SIGQUIT, CloseSession);
362   pending_signal(SIGALRM, SIG_IGN);
363   signal(SIGPIPE, SIG_IGN);
364 
365   if (mode == PHYS_MANUAL)
366     pending_signal(SIGTSTP, TerminalStop);
367 
368 #if 0 /* What's our passwd :-O */
369   pending_signal(SIGUSR1, SetUpServer);
370 #endif
371   pending_signal(SIGUSR2, BringDownServer);
372 
373   if (label) {
374     if (SelectSystem(bundle, label, CONFFILE, prompt) < 0) {
375       prompt_Printf(prompt, "Destination system (%s) not found.\n", label);
376       AbortProgram(EX_START);
377     }
378     /*
379      * We don't SetLabel() 'till now in case SelectSystem() has an
380      * embeded load "otherlabel" command.
381      */
382     SetLabel(label);
383     if (mode == PHYS_DEMAND &&
384 	bundle->ncp.ipcp.cfg.peer_range.ipaddr.s_addr == INADDR_ANY) {
385       prompt_Printf(prompt, "You must \"set ifaddr\" with a peer address "
386                     "in label %s for auto mode.\n", label);
387       AbortProgram(EX_START);
388     }
389   }
390 
391   if (mode != PHYS_MANUAL) {
392     if (mode != PHYS_STDIN) {
393       int bgpipe[2];
394       pid_t bgpid;
395 
396       if (mode == PHYS_1OFF && pipe(bgpipe)) {
397         LogPrintf(LogERROR, "pipe: %s\n", strerror(errno));
398 	AbortProgram(EX_SOCK);
399       }
400 
401       bgpid = fork();
402       if (bgpid == -1) {
403 	LogPrintf(LogERROR, "fork: %s\n", strerror(errno));
404 	AbortProgram(EX_SOCK);
405       }
406 
407       if (bgpid) {
408 	char c = EX_NORMAL;
409 
410 	if (mode == PHYS_1OFF) {
411 	  close(bgpipe[1]);
412 	  BGPid = bgpid;
413           /* If we get a signal, kill the child */
414           signal(SIGHUP, KillChild);
415           signal(SIGTERM, KillChild);
416           signal(SIGINT, KillChild);
417           signal(SIGQUIT, KillChild);
418 
419 	  /* Wait for our child to close its pipe before we exit */
420 	  if (read(bgpipe[0], &c, 1) != 1) {
421 	    prompt_Printf(prompt, "Child exit, no status.\n");
422 	    LogPrintf(LogPHASE, "Parent: Child exit, no status.\n");
423 	  } else if (c == EX_NORMAL) {
424 	    prompt_Printf(prompt, "PPP enabled.\n");
425 	    LogPrintf(LogPHASE, "Parent: PPP enabled.\n");
426 	  } else {
427 	    prompt_Printf(prompt, "Child failed (%s).\n", ex_desc((int) c));
428 	    LogPrintf(LogPHASE, "Parent: Child failed (%s).\n",
429 		      ex_desc((int) c));
430 	  }
431 	  close(bgpipe[0]);
432 	}
433 	return c;
434       } else if (mode == PHYS_1OFF) {
435 	close(bgpipe[0]);
436         bundle->notify.fd = bgpipe[1];
437       }
438 
439       /* -auto, -dedicated, -ddial & -background */
440       prompt_Destroy(prompt, 0);
441       close(STDOUT_FILENO);
442       close(STDERR_FILENO);
443       close(STDIN_FILENO);
444       setsid();
445     } else {
446       /* -direct: STDIN_FILENO gets used by modem_Open */
447       prompt_TtyInit(NULL);
448       close(STDOUT_FILENO);
449       close(STDERR_FILENO);
450     }
451   } else {
452     /* Interactive mode */
453     close(STDERR_FILENO);
454     prompt_TtyInit(prompt);
455     prompt_TtyCommandMode(prompt);
456     prompt_Required(prompt);
457   }
458 
459   snprintf(pid_filename, sizeof pid_filename, "%stun%d.pid",
460            _PATH_VARRUN, bundle->unit);
461   lockfile = ID0fopen(pid_filename, "w");
462   if (lockfile != NULL) {
463     fprintf(lockfile, "%d\n", (int) getpid());
464     fclose(lockfile);
465   }
466 #ifndef RELEASE_CRUNCH
467   else
468     LogPrintf(LogALERT, "Warning: Can't create %s: %s\n",
469               pid_filename, strerror(errno));
470 #endif
471 
472   LogPrintf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(mode));
473   DoLoop(bundle, prompt);
474   AbortProgram(EX_NORMAL);
475 
476   return EX_NORMAL;
477 }
478 
479 static void
480 DoLoop(struct bundle *bundle, struct prompt *prompt)
481 {
482   fd_set rfds, wfds, efds;
483   int pri, i, n, nfds;
484   int qlen;
485   struct tun_data tun;
486 
487   do {
488     nfds = 0;
489     FD_ZERO(&rfds);
490     FD_ZERO(&wfds);
491     FD_ZERO(&efds);
492 
493     qlen = bundle_FillQueues(bundle);
494 
495     handle_signals();
496 
497     descriptor_UpdateSet(&bundle->desc, &rfds, &wfds, &efds, &nfds);
498     descriptor_UpdateSet(&server.desc, &rfds, &wfds, &efds, &nfds);
499 
500     /* If there are aren't many packets queued, look for some more. */
501     if (qlen < 20 && bundle->tun_fd >= 0) {
502       if (bundle->tun_fd + 1 > nfds)
503 	nfds = bundle->tun_fd + 1;
504       FD_SET(bundle->tun_fd, &rfds);
505     }
506 
507     if (bundle_IsDead(bundle))
508       /* Don't select - we'll be here forever */
509       break;
510 
511     i = select(nfds, &rfds, &wfds, &efds, NULL);
512 
513     if (i == 0)
514       continue;
515 
516     if (i < 0) {
517       if (errno == EINTR) {
518 	handle_signals();
519 	continue;
520       }
521       LogPrintf(LogERROR, "DoLoop: select(): %s\n", strerror(errno));
522       break;
523     }
524 
525     for (i = 0; i <= nfds; i++)
526       if (FD_ISSET(i, &efds)) {
527         LogPrintf(LogALERT, "Exception detected on descriptor %d\n", i);
528         break;
529       }
530 
531     if (descriptor_IsSet(&server.desc, &rfds))
532       descriptor_Read(&server.desc, bundle, &rfds);
533 
534     if (descriptor_IsSet(&bundle->desc, &wfds))
535       descriptor_Write(&bundle->desc, bundle, &wfds);
536 
537     if (descriptor_IsSet(&bundle->desc, &rfds))
538       descriptor_Read(&bundle->desc, bundle, &rfds);
539 
540     if (bundle->tun_fd >= 0 && FD_ISSET(bundle->tun_fd, &rfds)) {
541       /* something to read from tun */
542       n = read(bundle->tun_fd, &tun, sizeof tun);
543       if (n < 0) {
544 	LogPrintf(LogERROR, "read from tun: %s\n", strerror(errno));
545 	continue;
546       }
547       n -= sizeof tun - sizeof tun.data;
548       if (n <= 0) {
549 	LogPrintf(LogERROR, "read from tun: Only %d bytes read\n", n);
550 	continue;
551       }
552       if (!tun_check_header(tun, AF_INET))
553           continue;
554       if (((struct ip *)tun.data)->ip_dst.s_addr ==
555           bundle->ncp.ipcp.my_ip.s_addr) {
556 	/* we've been asked to send something addressed *to* us :( */
557 	if (Enabled(ConfLoopback)) {
558 	  pri = PacketCheck(bundle, tun.data, n, &bundle->filter.in);
559 	  if (pri >= 0) {
560 	    struct mbuf *bp;
561 
562 #ifndef NOALIAS
563             if (AliasEnabled()) {
564 	      (*PacketAlias.In)(tun.data, sizeof tun.data);
565 	      n = ntohs(((struct ip *)tun.data)->ip_len);
566 	    }
567 #endif
568 	    bp = mballoc(n, MB_IPIN);
569 	    memcpy(MBUF_CTOP(bp), tun.data, n);
570 	    IpInput(bundle, bp);
571 	    LogPrintf(LogDEBUG, "Looped back packet addressed to myself\n");
572 	  }
573 	  continue;
574 	} else
575 	  LogPrintf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
576       }
577 
578       /*
579        * Process on-demand dialup. Output packets are queued within tunnel
580        * device until IPCP is opened.
581        */
582       if (bundle_Phase(bundle) == PHASE_DEAD)
583         /*
584          * Note, we must be in AUTO mode :-/ otherwise our interface should
585          * *not* be UP and we can't receive data
586          */
587         if ((pri = PacketCheck(bundle, tun.data, n, &bundle->filter.dial)) >= 0)
588           bundle_Open(bundle, NULL, PHYS_DEMAND);
589         else
590           /*
591            * Drop the packet.  If we were to queue it, we'd just end up with
592            * a pile of timed-out data in our output queue by the time we get
593            * around to actually dialing.  We'd also prematurely reach the
594            * threshold at which we stop select()ing to read() the tun
595            * device - breaking auto-dial.
596            */
597           continue;
598 
599       pri = PacketCheck(bundle, tun.data, n, &bundle->filter.out);
600       if (pri >= 0) {
601 #ifndef NOALIAS
602         if (AliasEnabled()) {
603 	  (*PacketAlias.Out)(tun.data, sizeof tun.data);
604 	  n = ntohs(((struct ip *)tun.data)->ip_len);
605 	}
606 #endif
607 	IpEnqueue(pri, tun.data, n);
608       }
609     }
610   } while (bundle_CleanDatalinks(bundle), !bundle_IsDead(bundle));
611 
612   LogPrintf(LogDEBUG, "DoLoop done.\n");
613 }
614