xref: /freebsd/usr.sbin/ppp/main.c (revision df7f5d4de4592a8948a25ce01e5bddfbb7ce39dc)
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.39 1997/03/13 14:53:55 brian Exp $
21  *
22  *	TODO:
23  *		o Add commands for traffic summary, version display, etc.
24  *		o Add signal handler for misc controls.
25  */
26 #include "fsm.h"
27 #include <fcntl.h>
28 #include <paths.h>
29 #include <sys/time.h>
30 #include <termios.h>
31 #include <signal.h>
32 #include <sys/wait.h>
33 #include <errno.h>
34 #include <netdb.h>
35 #include <unistd.h>
36 #include <sys/socket.h>
37 #include <arpa/inet.h>
38 #include <netinet/in_systm.h>
39 #include <netinet/ip.h>
40 #include "modem.h"
41 #include "os.h"
42 #include "hdlc.h"
43 #include "ccp.h"
44 #include "lcp.h"
45 #include "ipcp.h"
46 #include "vars.h"
47 #include "auth.h"
48 #include "filter.h"
49 #include "systems.h"
50 #include "ip.h"
51 #include "alias.h"
52 #include "sig.h"
53 
54 #define LAUTH_M1 "Warning: No password entry for this host in ppp.secret\n"
55 #define LAUTH_M2 "Warning: All manipulation is allowed by anyone in the world\n"
56 
57 #ifndef O_NONBLOCK
58 #ifdef O_NDELAY
59 #define	O_NONBLOCK O_NDELAY
60 #endif
61 #endif
62 
63 extern void VjInit(), AsyncInit();
64 extern void AsyncInput(), IpOutput();
65 extern int  SelectSystem();
66 
67 extern void DecodeCommand(), Prompt();
68 extern int aft_cmd;
69 extern int IsInteractive();
70 extern struct in_addr ifnetmask;
71 static void DoLoop(void);
72 static void TerminalStop();
73 
74 static struct termios oldtio;		/* Original tty mode */
75 static struct termios comtio;		/* Command level tty mode */
76 int TermMode;
77 static int server;
78 static pid_t BGPid = 0;
79 struct sockaddr_in ifsin;
80 char pid_filename[128];
81 
82 static void
83 TtyInit()
84 {
85   struct termios newtio;
86   int stat;
87 
88   stat = fcntl(0, F_GETFL, 0);
89   stat |= O_NONBLOCK;
90   fcntl(0, F_SETFL, stat);
91   newtio = oldtio;
92   newtio.c_lflag &= ~(ECHO|ISIG|ICANON);
93   newtio.c_iflag = 0;
94   newtio.c_oflag &= ~OPOST;
95   newtio.c_cc[VEOF] = _POSIX_VDISABLE;
96   newtio.c_cc[VINTR] = _POSIX_VDISABLE;
97   newtio.c_cc[VMIN] = 1;
98   newtio.c_cc[VTIME] = 0;
99   newtio.c_cflag |= CS8;
100   tcsetattr(0, TCSADRAIN, &newtio);
101   comtio = newtio;
102 }
103 
104 /*
105  *  Set tty into command mode. We allow canonical input and echo processing.
106  */
107 void
108 TtyCommandMode(prompt)
109 int prompt;
110 {
111   struct termios newtio;
112   int stat;
113 
114   if (!(mode & MODE_INTER))
115     return;
116   tcgetattr(0, &newtio);
117   newtio.c_lflag |= (ECHO|ISIG|ICANON);
118   newtio.c_iflag = oldtio.c_iflag;
119   newtio.c_oflag |= OPOST;
120   tcsetattr(0, TCSADRAIN, &newtio);
121   stat = fcntl(0, F_GETFL, 0);
122   stat |= O_NONBLOCK;
123   fcntl(0, F_SETFL, stat);
124   TermMode = 0;
125   if(prompt) Prompt(0);
126 }
127 
128 /*
129  * Set tty into terminal mode which is used while we invoke term command.
130  */
131 void
132 TtyTermMode()
133 {
134   int stat;
135 
136   tcsetattr(0, TCSADRAIN, &comtio);
137   stat = fcntl(0, F_GETFL, 0);
138   stat &= ~O_NONBLOCK;
139   fcntl(0, F_SETFL, stat);
140   TermMode = 1;
141 }
142 
143 void
144 TtyOldMode()
145 {
146   int stat;
147 
148   stat = fcntl(0, F_GETFL, 0);
149   stat &= ~O_NONBLOCK;
150   fcntl(0, F_SETFL, stat);
151   tcsetattr(0, TCSANOW, &oldtio);
152 }
153 
154 void
155 Cleanup(excode)
156 int excode;
157 {
158 
159   OsLinkdown();
160   OsCloseLink(1);
161   sleep(1);
162   if (mode & (MODE_AUTO | MODE_BACKGROUND)) {
163     DeleteIfRoutes(1);
164     unlink(pid_filename);
165   }
166   OsInterfaceDown(1);
167   if (mode & MODE_BACKGROUND && BGFiledes[1] != -1) {
168     char c = EX_ERRDEAD;
169     if (write(BGFiledes[1],&c,1) == 1)
170       LogPrintf(LOG_PHASE_BIT,"Parent notified of failure.\n");
171     else
172       LogPrintf(LOG_PHASE_BIT,"Failed to notify parent of failure.\n");
173     close(BGFiledes[1]);
174   }
175   LogPrintf(LOG_PHASE_BIT, "PPP Terminated.\n");
176   LogClose();
177   if (server >= 0) {
178     close(server);
179     server = -1;
180   }
181   TtyOldMode();
182 
183   exit(excode);
184 }
185 
186 static void
187 Hangup(signo)
188 int signo;
189 {
190   if (signo == SIGSEGV) {
191 	LogPrintf(LOG_PHASE_BIT, "Signal %d, core dump.\n", signo);
192 	LogClose();
193 	abort();
194   }
195   if (BGPid) {
196       kill (BGPid, SIGTERM);
197       exit (EX_HANGUP);
198   }
199   else {
200       LogPrintf(LOG_PHASE_BIT, "Signal %d, hangup.\n", signo);
201       Cleanup(EX_HANGUP);
202   }
203 }
204 
205 static void
206 CloseSession(signo)
207 int signo;
208 {
209    if (BGPid) {
210      kill (BGPid, SIGINT);
211      exit (EX_TERM);
212    }
213    else {
214      LogPrintf(LOG_PHASE_BIT, "Signal %d, terminate.\n", signo);
215      LcpClose();
216      Cleanup(EX_TERM);
217    }
218 }
219 
220 static void
221 TerminalCont()
222 {
223   pending_signal(SIGCONT, SIG_DFL);
224   pending_signal(SIGTSTP, TerminalStop);
225   TtyCommandMode(getpgrp() == tcgetpgrp(0));
226 }
227 
228 static void
229 TerminalStop(signo)
230 int signo;
231 {
232   pending_signal(SIGCONT, TerminalCont);
233   TtyOldMode();
234   pending_signal(SIGTSTP, SIG_DFL);
235   kill(getpid(), signo);
236 }
237 
238 
239 void
240 Usage()
241 {
242   fprintf(stderr,
243           "Usage: ppp [-auto | -background | -direct | -dedicated | -ddial ] [ -alias ] [system]\n");
244   exit(EX_START);
245 }
246 
247 void
248 ProcessArgs(int argc, char **argv)
249 {
250   int optc;
251   char *cp;
252 
253   optc = 0;
254   while (argc > 0 && **argv == '-') {
255     cp = *argv + 1;
256     if (strcmp(cp, "auto") == 0)
257       mode |= MODE_AUTO;
258     else if (strcmp(cp, "background") == 0)
259       mode |= MODE_BACKGROUND;
260     else if (strcmp(cp, "direct") == 0)
261       mode |= MODE_DIRECT;
262     else if (strcmp(cp, "dedicated") == 0)
263       mode |= MODE_DEDICATED;
264     else if (strcmp(cp, "ddial") == 0)
265       mode |= MODE_DDIAL|MODE_AUTO;
266     else if (strcmp(cp, "alias") == 0) {
267       mode |= MODE_ALIAS;
268       optc--;             /* this option isn't exclusive */
269     }
270     else
271       Usage();
272     optc++;
273     argv++; argc--;
274   }
275   if (argc > 1) {
276     fprintf(stderr, "specify only one system label.\n");
277     exit(EX_START);
278   }
279   if (argc == 1) dstsystem = *argv;
280 
281   if (optc > 1) {
282     fprintf(stderr, "specify only one mode.\n");
283     exit(EX_START);
284   }
285 }
286 
287 static void
288 Greetings()
289 {
290   printf("User Process PPP. Written by Toshiharu OHNO.\r\n");
291   fflush(stdout);
292 }
293 
294 void
295 main(argc, argv)
296 int argc;
297 char **argv;
298 {
299   int tunno;
300 
301   argc--; argv++;
302 
303   mode = MODE_INTER;		/* default operation is interactive mode */
304   netfd = server = modem = tun_in = -1;
305   ProcessArgs(argc, argv);
306   Greetings();
307   GetUid();
308   IpcpDefAddress();
309   InitAlias();
310 
311   if (SelectSystem("default", CONFFILE) < 0) {
312     fprintf(stderr, "Warning: No default entry is given in config file.\n");
313   }
314 
315   if (LogOpen())
316     exit(EX_START);
317 
318   switch ( LocalAuthInit() ) {
319     case NOT_FOUND:
320     	fprintf(stderr,LAUTH_M1);
321     	fprintf(stderr,LAUTH_M2);
322 	fflush (stderr);
323 	/* Fall down */
324     case VALID:
325 	VarLocalAuth = LOCAL_AUTH;
326 	break;
327     default:
328 	break;
329   }
330 
331   if (OpenTunnel(&tunno) < 0) {
332     perror("open_tun");
333     exit(EX_START);
334   }
335 
336   if (mode & (MODE_AUTO|MODE_DIRECT|MODE_DEDICATED|MODE_BACKGROUND))
337     mode &= ~MODE_INTER;
338   if (mode & MODE_INTER) {
339     printf("Interactive mode\n");
340     netfd = STDIN_FILENO;
341   } else if (mode & MODE_AUTO) {
342     printf("Automatic Dialer mode\n");
343     if (dstsystem == NULL) {
344       fprintf(stderr,
345               "Destination system must be specified in auto or ddial mode.\n");
346       exit(EX_START);
347     }
348   } else if (mode & MODE_BACKGROUND) {
349     printf("Background mode\n");
350     if (dstsystem == NULL) {
351       fprintf(stderr, "Destination system must be specified in background mode.\n");
352       exit(EX_START);
353     }
354   }
355 
356   tcgetattr(0, &oldtio);		/* Save original tty mode */
357 
358   pending_signal(SIGHUP, LogReOpen);
359   pending_signal(SIGTERM, CloseSession);
360   pending_signal(SIGINT, CloseSession);
361   pending_signal(SIGQUIT, CloseSession);
362 #ifdef SIGSEGV
363   signal(SIGSEGV, Hangup);
364 #endif
365 #ifdef SIGPIPE
366   signal(SIGPIPE, Hangup);
367 #endif
368 #ifdef SIGALRM
369   pending_signal(SIGALRM, SIG_IGN);
370 #endif
371   if(mode & MODE_INTER)
372     {
373 #ifdef SIGTSTP
374       pending_signal(SIGTSTP, TerminalStop);
375 #endif
376 #ifdef SIGTTIN
377       pending_signal(SIGTTIN, TerminalStop);
378 #endif
379 #ifdef SIGTTOU
380       pending_signal(SIGTTOU, SIG_IGN);
381 #endif
382     }
383 
384   if (dstsystem) {
385     if (SelectSystem(dstsystem, CONFFILE) < 0) {
386       fprintf(stderr, "Destination system not found in conf file.\n");
387       Cleanup(EX_START);
388     }
389     if ((mode & MODE_AUTO) && DefHisAddress.ipaddr.s_addr == INADDR_ANY) {
390       fprintf(stderr, "Must specify dstaddr with auto or ddial mode.\n");
391       Cleanup(EX_START);
392     }
393   }
394   if (mode & MODE_DIRECT)
395     printf("Packet mode enabled.\n");
396 
397 #ifdef notdef
398   if (mode & MODE_AUTO) {
399     OsSetIpaddress(IpcpInfo.want_ipaddr, IpcpInfo.his_ipaddr, ifnetmask);
400   }
401 #endif
402 
403   if (!(mode & MODE_INTER)) {
404     int port = SERVER_PORT + tunno;
405     if (mode & MODE_BACKGROUND) {
406       if (pipe (BGFiledes)) {
407 	perror("pipe");
408 	Cleanup(EX_SOCK);
409       }
410     }
411     else {
412       /*
413        *  Create server socket and listen at there.
414        */
415       server = socket(PF_INET, SOCK_STREAM, 0);
416       if (server < 0) {
417 	perror("socket");
418 	Cleanup(EX_SOCK);
419       }
420       ifsin.sin_family = AF_INET;
421       ifsin.sin_addr.s_addr = INADDR_ANY;
422       ifsin.sin_port = htons(port);
423       if (bind(server, (struct sockaddr *) &ifsin, sizeof(ifsin)) < 0) {
424 	perror("bind");
425 	if (errno == EADDRINUSE)
426 	  fprintf(stderr, "Wait for a while, then try again.\n");
427 	Cleanup(EX_SOCK);
428       }
429       listen(server, 5);
430     }
431 
432     DupLog();
433     if (!(mode & MODE_DIRECT)) {
434       int fd;
435       char pid[32];
436       pid_t bgpid;
437 
438       bgpid = fork ();
439       if (bgpid == -1) {
440 	perror ("fork");
441 	Cleanup (EX_SOCK);
442       }
443       if (bgpid) {
444 	char c = EX_NORMAL;
445 
446 	if (mode & MODE_BACKGROUND) {
447 	  /* Wait for our child to close its pipe before we exit. */
448 	  BGPid = bgpid;
449           close (BGFiledes[1]);
450 	  if (read(BGFiledes[0], &c, 1) != 1)
451 	    LogPrintf (LOG_PHASE_BIT, "Parent: Child exit, no status.\n");
452 	  else if (c == EX_NORMAL)
453 	    LogPrintf (LOG_PHASE_BIT, "Parent: PPP enabled.\n");
454 	  else
455 	    LogPrintf (LOG_PHASE_BIT, "Parent: Child failed %d.\n",(int)c);
456           close (BGFiledes[0]);
457 	}
458         exit(c);
459       } else if (mode & MODE_BACKGROUND)
460           close(BGFiledes[0]);
461 
462       snprintf(pid_filename, sizeof (pid_filename), "%s/ppp.tun%d.pid",
463 		  _PATH_VARRUN, tunno);
464       unlink(pid_filename);
465       snprintf(pid, sizeof(pid), "%d\n", (int)getpid());
466 
467       if ((fd = open(pid_filename, O_RDWR|O_CREAT, 0666)) != -1)
468       {
469 	  write(fd, pid, strlen(pid));
470 	  close(fd);
471       }
472     }
473     if (server >= 0)
474 	LogPrintf(LOG_PHASE_BIT, "Listening at %d.\n", port);
475 #ifdef DOTTYINIT
476     if (mode & (MODE_DIRECT|MODE_DEDICATED)) { /* } */
477 #else
478     if (mode & MODE_DIRECT) {
479 #endif
480       TtyInit();
481     } else {
482       int fd;
483 
484       setsid();			/* detach control tty */
485       if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
486 	(void)dup2(fd, STDIN_FILENO);
487 	(void)dup2(fd, STDOUT_FILENO);
488 	(void)dup2(fd, STDERR_FILENO);
489 	if (fd > 2)
490 		(void)close (fd);
491       }
492     }
493   } else {
494     TtyInit();
495     TtyCommandMode(1);
496   }
497   LogPrintf(LOG_PHASE_BIT, "PPP Started.\n");
498 
499 
500   do
501    DoLoop();
502   while (mode & MODE_DEDICATED);
503 
504   Cleanup(EX_DONE);
505 }
506 
507 /*
508  *  Turn into packet mode, where we speak PPP.
509  */
510 void
511 PacketMode()
512 {
513   if (RawModem(modem) < 0) {
514     fprintf(stderr, "Not connected.\r\n");
515     return;
516   }
517 
518   AsyncInit();
519   VjInit();
520   LcpInit();
521   IpcpInit();
522   CcpInit();
523   LcpUp();
524 
525   if (mode & (MODE_DIRECT|MODE_DEDICATED))
526     LcpOpen(OPEN_ACTIVE);
527   else
528     LcpOpen(VarOpenMode);
529   if ((mode & (MODE_INTER|MODE_AUTO)) == MODE_INTER) {
530     TtyCommandMode(1);
531     fprintf(stderr, "Packet mode.\r\n");
532     aft_cmd = 1;
533   }
534 }
535 
536 static void
537 ShowHelp()
538 {
539   fprintf(stderr, "The following commands are available:\r\n");
540   fprintf(stderr, " ~p\tEnter to Packet mode\r\n");
541   fprintf(stderr, " ~-\tDecrease log level\r\n");
542   fprintf(stderr, " ~+\tIncrease log level\r\n");
543   fprintf(stderr, " ~.\tTerminate program\r\n");
544   fprintf(stderr, " ~?\tThis help\r\n");
545 }
546 
547 static void
548 ReadTty()
549 {
550   int n;
551   char ch;
552   static int ttystate;
553 #define MAXLINESIZE 200
554   char linebuff[MAXLINESIZE];
555 
556 #ifdef DEBUG
557   logprintf("termode = %d, netfd = %d, mode = %d\n", TermMode, netfd, mode);
558 #endif
559   if (!TermMode) {
560     n = read(netfd, linebuff, sizeof(linebuff)-1);
561     aft_cmd = 1;
562     if (n > 0) {
563       DecodeCommand(linebuff, n, 1);
564     } else {
565 #ifdef DEBUG
566       logprintf("connection closed.\n");
567 #endif
568       close(netfd);
569       netfd = -1;
570       mode &= ~MODE_INTER;
571     }
572     return;
573   }
574 
575   /*
576    *  We are in terminal mode, decode special sequences
577    */
578   n = read(0, &ch, 1);
579 #ifdef DEBUG
580   logprintf("got %d bytes\n", n);
581 #endif
582 
583   if (n > 0) {
584     switch (ttystate) {
585     case 0:
586       if (ch == '~')
587 	ttystate++;
588       else
589 	write(modem, &ch, n);
590       break;
591     case 1:
592       switch (ch) {
593       case '?':
594 	ShowHelp();
595 	break;
596       case '-':
597 	if (loglevel > 0) {
598 	  loglevel--;
599 	  fprintf(stderr, "New loglevel is %d\r\n", loglevel);
600 	}
601 	break;
602       case '+':
603 	loglevel++;
604 	fprintf(stderr, "New loglevel is %d\r\n", loglevel);
605 	break;
606 #ifdef DEBUG
607       case 'm':
608 	ShowMemMap();
609 	break;
610 #endif
611       case 'p':
612 	/*
613 	 * XXX: Should check carrier.
614 	 */
615 	if (LcpFsm.state <= ST_CLOSED) {
616 	  VarOpenMode = OPEN_ACTIVE;
617 	  PacketMode();
618 	}
619 	break;
620 #ifdef DEBUG
621       case 't':
622 	ShowTimers();
623 	break;
624 #endif
625       case '.':
626 	TermMode = 1;
627 	TtyCommandMode(1);
628 	break;
629       default:
630 	if (write(modem, &ch, n) < 0)
631 	  fprintf(stderr, "err in write.\r\n");
632 	break;
633       }
634       ttystate = 0;
635       break;
636     }
637   }
638 }
639 
640 
641 /*
642  *  Here, we'll try to detect HDLC frame
643  */
644 
645 static char *FrameHeaders[] = {
646   "\176\377\003\300\041",
647   "\176\377\175\043\300\041",
648   "\176\177\175\043\100\041",
649   "\176\175\337\175\043\300\041",
650   "\176\175\137\175\043\100\041",
651   NULL,
652 };
653 
654 u_char *
655 HdlcDetect(cp, n)
656 u_char *cp;
657 int n;
658 {
659   char *ptr, *fp, **hp;
660 
661   cp[n] = '\0';	/* be sure to null terminated */
662   ptr = NULL;
663   for (hp = FrameHeaders; *hp; hp++) {
664     fp = *hp;
665     if (DEV_IS_SYNC)
666       fp++;
667     ptr = strstr((char *)cp, fp);
668     if (ptr)
669       break;
670   }
671   return((u_char *)ptr);
672 }
673 
674 static struct pppTimer RedialTimer;
675 
676 static void
677 RedialTimeout()
678 {
679   StopTimer(&RedialTimer);
680   LogPrintf(LOG_PHASE_BIT, "Redialing timer expired.\n");
681 }
682 
683 static void
684 StartRedialTimer()
685 {
686   StopTimer(&RedialTimer);
687 
688   if (VarRedialTimeout) {
689     LogPrintf(LOG_PHASE_BIT, "Enter pause for redialing.\n");
690     RedialTimer.state = TIMER_STOPPED;
691 
692     if (VarRedialTimeout > 0)
693 	RedialTimer.load = VarRedialTimeout * SECTICKS;
694     else
695 	RedialTimer.load = (random() % REDIAL_PERIOD) * SECTICKS;
696 
697     RedialTimer.func = RedialTimeout;
698     StartTimer(&RedialTimer);
699   }
700 }
701 
702 
703 static void
704 DoLoop()
705 {
706   fd_set rfds, wfds, efds;
707   int pri, i, n, wfd, nfds;
708   struct sockaddr_in hisaddr;
709   struct timeval timeout, *tp;
710   int ssize = sizeof(hisaddr);
711   u_char *cp;
712   u_char rbuff[MAX_MRU];
713   int dial_up;
714   int tries;
715   int qlen;
716   pid_t pgroup;
717 
718   pgroup = getpgrp();
719 
720   if (mode & (MODE_DIRECT|MODE_BACKGROUND)) {
721     modem = OpenModem(mode);
722     LogPrintf(LOG_PHASE_BIT, "Packet mode enabled\n");
723     fflush(stderr);
724     PacketMode();
725   } else if (mode & MODE_DEDICATED) {
726     if (modem < 0)
727       modem = OpenModem(mode);
728   }
729 
730   fflush(stdout);
731 
732   timeout.tv_sec = 0;
733   timeout.tv_usec = 0;
734 
735   if (mode & MODE_BACKGROUND)
736     dial_up = TRUE;			/* Bring the line up */
737   else
738     dial_up = FALSE;			/* XXXX */
739   tries = 0;
740   for (;;) {
741     nfds = 0;
742     FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&efds);
743 
744     /*
745      * If the link is down and we're in DDIAL mode, bring it back
746      * up.
747      */
748     if (mode & MODE_DDIAL && LcpFsm.state <= ST_CLOSED)
749         dial_up = TRUE;
750 
751    /*
752     * If Ip packet for output is enqueued and require dial up,
753     * Just do it!
754     */
755     if ( dial_up && RedialTimer.state != TIMER_RUNNING ) { /* XXX */
756 #ifdef DEBUG
757       logprintf("going to dial: modem = %d\n", modem);
758 #endif
759       modem = OpenModem(mode);
760       if (modem < 0) {
761 	StartRedialTimer();
762       } else {
763 	tries++;
764 	LogPrintf(LOG_CHAT_BIT, "Dial attempt %u\n", tries);
765 	if (DialModem()) {
766 	  sleep(1);	       /* little pause to allow peer starts */
767 	  ModemTimeout();
768 	  PacketMode();
769 	  dial_up = FALSE;
770 	  tries = 0;
771 	} else {
772 	  CloseModem();
773 	  /* Dial failed. Keep quite during redial wait period. */
774 	  StartRedialTimer();
775 
776 	  if (VarDialTries && tries >= VarDialTries) {
777 	      dial_up = FALSE;
778 	      tries = 0;
779 	  }
780 	}
781       }
782     }
783     qlen = ModemQlen();
784 
785     if (qlen == 0) {
786       IpStartOutput();
787       qlen = ModemQlen();
788     }
789 
790     if (modem >= 0) {
791       if (modem + 1 > nfds)
792 	nfds = modem + 1;
793       FD_SET(modem, &rfds);
794       FD_SET(modem, &efds);
795       if (qlen > 0) {
796 	FD_SET(modem, &wfds);
797       }
798     }
799     if (server >= 0) {
800       if (server + 1 > nfds)
801 	nfds = server + 1;
802       FD_SET(server, &rfds);
803     }
804 
805     /*  *** IMPORTANT ***
806      *
807      *  CPU is serviced every TICKUNIT micro seconds.
808      *	This value must be chosen with great care. If this values is
809      *  too big, it results loss of characters from modem and poor responce.
810      *  If this values is too small, ppp process eats many CPU time.
811      */
812 #ifndef SIGALRM
813     usleep(TICKUNIT);
814     TimerService();
815 #else
816     handle_signals();
817 #endif
818 
819     /* If there are aren't many packets queued, look for some more. */
820     if (qlen < 20 && tun_in >= 0) {
821       if (tun_in + 1 > nfds)
822 	nfds = tun_in + 1;
823       FD_SET(tun_in, &rfds);
824     }
825 
826     if (netfd >= 0) {
827       if (netfd + 1 > nfds)
828 	nfds = netfd + 1;
829       FD_SET(netfd, &rfds);
830       FD_SET(netfd, &efds);
831     }
832 
833 #ifndef SIGALRM
834     /*
835      *  Normally, select() will not block because modem is writable.
836      *  In AUTO mode, select will block until we find packet from tun
837      */
838     tp = (RedialTimer.state == TIMER_RUNNING)? &timeout : NULL;
839     i = select(nfds, &rfds, &wfds, &efds, tp);
840 #else
841     /*
842      * When SIGALRM timer is running, a select function will be
843      * return -1 and EINTR after a Time Service signal hundler
844      * is done.  If the redial timer is not running and we are
845      * trying to dial, poll with a 0 value timer.
846      */
847     tp = (dial_up && RedialTimer.state != TIMER_RUNNING) ? &timeout : NULL;
848     i = select(nfds, &rfds, &wfds, &efds, tp);
849 #endif
850 
851     if ( i == 0 ) {
852         continue;
853     }
854 
855     if ( i < 0 ) {
856        if ( errno == EINTR ) {
857           handle_signals();
858           continue;
859        }
860        perror("select");
861        break;
862     }
863 
864     if ((netfd >= 0 && FD_ISSET(netfd, &efds)) || (modem >= 0 && FD_ISSET(modem, &efds))) {
865       logprintf("Exception detected.\n");
866       break;
867     }
868 
869     if (server >= 0 && FD_ISSET(server, &rfds)) {
870 #ifdef DEBUG
871       logprintf("connected to client.\n");
872 #endif
873       wfd = accept(server, (struct sockaddr *)&hisaddr, &ssize);
874       if (netfd >= 0) {
875 	write(wfd, "already in use.\n", 16);
876 	close(wfd);
877 	continue;
878       } else
879 	netfd = wfd;
880       if (dup2(netfd, 1) < 0)
881 	perror("dup2");
882       mode |= MODE_INTER;
883       Greetings();
884       switch ( LocalAuthInit() ) {
885          case NOT_FOUND:
886     	    fprintf(stdout,LAUTH_M1);
887     	    fprintf(stdout,LAUTH_M2);
888             fflush(stdout);
889 	    /* Fall down */
890          case VALID:
891 	    VarLocalAuth = LOCAL_AUTH;
892 	    break;
893          default:
894 	    break;
895       }
896       (void) IsInteractive();
897       Prompt(0);
898     }
899 
900     if ((mode & MODE_INTER) && (netfd >= 0 && FD_ISSET(netfd, &rfds)) &&
901 	((mode & MODE_AUTO) || pgroup == tcgetpgrp(0))) {
902       /* something to read from tty */
903       ReadTty();
904     }
905     if (modem >= 0) {
906       if (FD_ISSET(modem, &wfds)) {	/* ready to write into modem */
907 	 ModemStartOutput(modem);
908       }
909       if (FD_ISSET(modem, &rfds)) {	/* something to read from modem */
910 	if (LcpFsm.state <= ST_CLOSED)
911 	  usleep(10000);
912 	n = read(modem, rbuff, sizeof(rbuff));
913 	if ((mode & MODE_DIRECT) && n <= 0) {
914 	  DownConnection();
915 	} else
916           LogDumpBuff(LOG_ASYNC, "ReadFromModem", rbuff, n);
917 
918 	if (LcpFsm.state <= ST_CLOSED) {
919 	  /*
920 	   *  In dedicated mode, we just discard input until LCP is started.
921 	   */
922 	  if (!(mode & MODE_DEDICATED)) {
923 	    cp = HdlcDetect(rbuff, n);
924 	    if (cp) {
925 	      /*
926 	       * LCP packet is detected. Turn ourselves into packet mode.
927 	       */
928 	      if (cp != rbuff) {
929 	        write(1, rbuff, cp - rbuff);
930 	        write(1, "\r\n", 2);
931 	      }
932 	      PacketMode();
933 #ifdef notdef
934 	      AsyncInput(cp, n - (cp - rbuff));
935 #endif
936 	    } else
937 	      write(1, rbuff, n);
938 	  }
939 	} else {
940 	  if (n > 0)
941 	    AsyncInput(rbuff, n);
942 #ifdef notdef
943 	  continue;			/* THIS LINE RESULT AS POOR PERFORMANCE */
944 #endif
945 	}
946       }
947     }
948 
949     if (tun_in >= 0 && FD_ISSET(tun_in, &rfds)) {       /* something to read from tun */
950       n = read(tun_in, rbuff, sizeof(rbuff));
951       if (n < 0) {
952 	perror("read from tun");
953 	continue;
954       }
955       /*
956        *  Process on-demand dialup. Output packets are queued within tunnel
957        *  device until IPCP is opened.
958        */
959       if (LcpFsm.state <= ST_CLOSED && (mode & MODE_AUTO)) {
960 	pri = PacketCheck(rbuff, n, FL_DIAL);
961 	if (pri >= 0) {
962 	  if (mode & MODE_ALIAS) {
963 	    PacketAliasOut((struct ip *)rbuff);
964 	    n = ntohs(((struct ip *)rbuff)->ip_len);
965 	  }
966 	  IpEnqueue(pri, rbuff, n);
967 	  dial_up = TRUE;		/* XXX */
968 	}
969 	continue;
970       }
971       pri = PacketCheck(rbuff, n, FL_OUT);
972       if (pri >= 0) {
973         if (mode & MODE_ALIAS) {
974           PacketAliasOut((struct ip *)rbuff);
975           n = ntohs(((struct ip *)rbuff)->ip_len);
976         }
977 	IpEnqueue(pri, rbuff, n);
978       }
979     }
980   }
981   logprintf("job done.\n");
982 }
983