diff --git a/usr.sbin/ppp/command.c b/usr.sbin/ppp/command.c index 8685bb49d383..4e510467bd1e 100644 --- a/usr.sbin/ppp/command.c +++ b/usr.sbin/ppp/command.c @@ -1,1206 +1,1206 @@ /* * PPP User command processing module * * Written by Toshiharu OHNO (tony-o@iij.ad.jp) * * Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the Internet Initiative Japan, Inc. The name of the * IIJ may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * - * $Id: command.c,v 1.44 1997/05/10 03:39:51 brian Exp $ + * $Id: command.c,v 1.45 1997/05/10 23:46:29 ache Exp $ * */ #include #include #include #include #include #include "fsm.h" #include "phase.h" #include "lcp.h" #include "ipcp.h" #include "modem.h" #include "filter.h" #include "command.h" #include "hdlc.h" #include "vars.h" #include "systems.h" #include "chat.h" #include #include #include #include #include "os.h" #include #include "chat.h" extern void Cleanup(), TtyTermMode(), PacketMode(); extern int EnableCommand(), DisableCommand(), DisplayCommand(); extern int AcceptCommand(), DenyCommand(); extern int LocalAuthCommand(); extern int LoadCommand(), SaveCommand(); extern int ChangeParity(char *); extern int SelectSystem(); extern int ShowRoute(); extern void TtyOldMode(), TtyCommandMode(); extern struct pppvars pppVars; extern struct cmdtab const SetCommands[]; extern char *IfDevName; struct in_addr ifnetmask; int randinit; static int ShowCommand(), TerminalCommand(), QuitCommand(); static int CloseCommand(), DialCommand(), DownCommand(); static int SetCommand(), AddCommand(), DeleteCommand(); static int ShellCommand(); static int HelpCommand(list, argc, argv, plist) struct cmdtab *list; int argc; char **argv; struct cmdtab *plist; { struct cmdtab *cmd; int n; char c; if (argc > 0) { for (cmd = plist; cmd->name; cmd++) { if (strcasecmp(cmd->name, *argv) == 0 && (cmd->lauth & VarLocalAuth)) { if (plist == SetCommands) printf("set "); printf("%s %s\n", cmd->name, cmd->syntax); return(1); } } return(1); } n = 0; for (cmd = plist; cmd->func; cmd++) { if (cmd->name && (cmd->lauth & VarLocalAuth)) { c = (n & 1)? '\n' : '\t'; printf(" %-8s: %-20s%c", cmd->name, cmd->helpmes, c); n++; } } if (n & 1) printf("\n"); return(1); } int IsInteractive() { char *mes = NULL; if (mode & MODE_DDIAL) mes = "Working in dedicated dial mode."; else if (mode & MODE_AUTO) mes = "Working in auto mode."; else if (mode & MODE_DIRECT) mes = "Working in direct mode."; else if (mode & MODE_DEDICATED) mes = "Working in dedicated mode."; if (mes) { printf("%s\n", mes); return(0); } return(1); } static int DialCommand(cmdlist, argc, argv) struct cmdtab *cmdlist; int argc; char **argv; { int tries; if (LcpFsm.state > ST_CLOSED) { printf("LCP state is [%s]\n", StateNames[LcpFsm.state]); return(1); } if (!IsInteractive()) return(1); if (argc > 0) { if (SelectSystem(*argv, CONFFILE) < 0) { printf("%s: not found.\n", *argv); return(1); } } tries = 0; do { - printf("Dial attempt %u\n", ++tries); + printf("Dial attempt %u of %d\n", ++tries, VarDialTries); modem = OpenModem(mode); if (modem < 0) { printf("failed to open modem.\n"); break; } if (DialModem()) { sleep(1); ModemTimeout(); PacketMode(); break; } } while (VarDialTries == 0 || tries < VarDialTries); return(1); } static int ShellCommand(cmdlist, argc, argv) struct cmdtab *cmdlist; int argc; char **argv; { const char *shell; pid_t shpid; if((shell = getenv("SHELL")) == 0) { shell = _PATH_BSHELL; } #ifdef SHELL_ONLY_INTERACTIVELY #ifndef HAVE_SHELL_CMD_WITH_ANY_MODE if( mode != MODE_INTER) { fprintf(stdout, "Can only start a shell in interactive mode\n"); return(1); } #else if(argc == 0 && !(mode & MODE_INTER)) { fprintf(stderr, "Can only start an interactive shell in interactive mode\n"); return(1); } #endif /* HAVE_SHELL_CMD_WITH_ANY_MODE */ #else if ((mode & (MODE_AUTO|MODE_INTER)) == (MODE_AUTO|MODE_INTER)) { fprintf(stdout, "Shell is not allowed interactively in auto mode\n"); return(1); } #endif /* SHELL_ONLY_INTERACTIVELY */ if((shpid = fork()) == 0) { int dtablesize, i ; for (dtablesize = getdtablesize(), i = 3; i < dtablesize; i++) (void)close(i); /* * We are running setuid, we should change to * real user for avoiding security problems. */ if (setgid(getgid()) < 0) { perror("setgid"); exit(1); } if (setuid(getuid()) < 0) { perror("setuid"); exit(1); } TtyOldMode(); if(argc > 0) { /* substitute pseudo args */ for (i=1; i 0? argv[0]: shell); exit(255); } if( shpid == (pid_t)-1 ) { fprintf(stdout, "Fork failed\n"); } else { int status; (void)waitpid(shpid, &status, 0); } TtyCommandMode(1); return(0); } static char StrOption[] = "option .."; static char StrRemote[] = "[remote]"; char StrNull[] = ""; struct cmdtab const Commands[] = { { "accept", NULL, AcceptCommand, LOCAL_AUTH, "accept option request", StrOption}, { "add", NULL, AddCommand, LOCAL_AUTH, "add route", "dest mask gateway"}, { "close", NULL, CloseCommand, LOCAL_AUTH, "Close connection", StrNull}, { "delete", NULL, DeleteCommand, LOCAL_AUTH, "delete route", "ALL | dest gateway [mask]"}, { "deny", NULL, DenyCommand, LOCAL_AUTH, "Deny option request", StrOption}, { "dial", "call", DialCommand, LOCAL_AUTH, "Dial and login", StrRemote}, { "disable", NULL, DisableCommand, LOCAL_AUTH, "Disable option", StrOption}, { "display", NULL, DisplayCommand, LOCAL_AUTH, "Display option configs", StrNull}, { "enable", NULL, EnableCommand, LOCAL_AUTH, "Enable option", StrOption}, { "passwd", NULL, LocalAuthCommand,LOCAL_NO_AUTH, "Password for manipulation", StrOption}, { "load", NULL, LoadCommand, LOCAL_AUTH, "Load settings", StrRemote}, { "save", NULL, SaveCommand, LOCAL_AUTH, "Save settings", StrNull}, { "set", "setup", SetCommand, LOCAL_AUTH, "Set parameters", "var value"}, { "shell", "!", ShellCommand, LOCAL_AUTH, "Run a subshell", "[sh command]"}, { "show", NULL, ShowCommand, LOCAL_AUTH, "Show status and statictics", "var"}, { "term", NULL, TerminalCommand,LOCAL_AUTH, "Enter to terminal mode", StrNull}, { "quit", "bye", QuitCommand, LOCAL_AUTH | LOCAL_NO_AUTH, "Quit PPP program", "[all]"}, { "help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH, "Display this message", "[command]", (void *)Commands }, { NULL, "down", DownCommand, LOCAL_AUTH, "Generate down event", StrNull}, { NULL, NULL, NULL }, }; extern int ReportCcpStatus(); extern int ReportLcpStatus(); extern int ReportIpcpStatus(); extern int ReportProtStatus(); extern int ReportCompress(); extern int ShowModemStatus(); extern int ReportHdlcStatus(); extern int ShowMemMap(); static char *LogLevelName[] = { LM_PHASE, LM_CHAT, LM_LQM, LM_LCP, LM_TCPIP, LM_HDLC, LM_ASYNC, LM_LINK, LM_CONNECT, LM_CARRIER, }; static int ShowDebugLevel() { int i; printf("%02x: ", loglevel); for (i = LOG_PHASE; i < MAXLOGLEVEL; i++) { if (loglevel & (1 << i)) printf("%s ", LogLevelName[i]); } printf("\n"); return(1); } static int ShowEscape() { int code, bit; if (EscMap[32]) { for (code = 0; code < 32; code++) { if (EscMap[code]) { for (bit = 0; bit < 8; bit++) { if (EscMap[code] & (1<= 0) { printf(" %d seconds, ", VarRedialTimeout); } else { printf(" Random 0 - %d seconds, ", REDIAL_PERIOD); } printf(" Redial Next Timer: "); if (VarRedialNextTimeout >= 0) { printf(" %d seconds, ", VarRedialNextTimeout); } else { printf(" Random 0 - %d seconds, ", REDIAL_PERIOD); } if (VarDialTries) printf("%d dial tries", VarDialTries); printf("\n"); return(1); } #ifdef MSEXT static int ShowMSExt() { printf(" MS PPP extention values \n" ); printf(" Primary NS : %s\n", inet_ntoa( ns_entries[0] )); printf(" Secondary NS : %s\n", inet_ntoa( ns_entries[1] )); printf(" Primary NBNS : %s\n", inet_ntoa( nbns_entries[0] )); printf(" Secondary NBNS : %s\n", inet_ntoa( nbns_entries[1] )); return(1); } #endif /* MSEXT */ extern int ShowIfilter(), ShowOfilter(), ShowDfilter(), ShowAfilter(); struct cmdtab const ShowCommands[] = { { "afilter", NULL, ShowAfilter, LOCAL_AUTH, "Show keep Alive filters", StrOption}, { "auth", NULL, ShowAuthKey, LOCAL_AUTH, "Show auth name/key", StrNull}, { "ccp", NULL, ReportCcpStatus, LOCAL_AUTH, "Show CCP status", StrNull}, { "compress", NULL, ReportCompress, LOCAL_AUTH, "Show compression statictics", StrNull}, { "debug", NULL, ShowDebugLevel, LOCAL_AUTH, "Show current debug level", StrNull}, { "dfilter", NULL, ShowDfilter, LOCAL_AUTH, "Show Demand filters", StrOption}, { "escape", NULL, ShowEscape, LOCAL_AUTH, "Show escape characters", StrNull}, { "hdlc", NULL, ReportHdlcStatus, LOCAL_AUTH, "Show HDLC error summary", StrNull}, { "ifilter", NULL, ShowIfilter, LOCAL_AUTH, "Show Input filters", StrOption}, { "ipcp", NULL, ReportIpcpStatus, LOCAL_AUTH, "Show IPCP status", StrNull}, { "lcp", NULL, ReportLcpStatus, LOCAL_AUTH, "Show LCP status", StrNull}, { "log", NULL, ShowLogList, LOCAL_AUTH, "Show log records", StrNull}, { "mem", NULL, ShowMemMap, LOCAL_AUTH, "Show memory map", StrNull}, { "modem", NULL, ShowModemStatus, LOCAL_AUTH, "Show modem setups", StrNull}, { "ofilter", NULL, ShowOfilter, LOCAL_AUTH, "Show Output filters", StrOption}, { "proto", NULL, ReportProtStatus, LOCAL_AUTH, "Show protocol summary", StrNull}, { "reconnect",NULL, ShowReconnect, LOCAL_AUTH, "Show Reconnect timer,tries", StrNull}, { "redial", NULL, ShowRedial, LOCAL_AUTH, "Show Redial timeout value", StrNull}, { "route", NULL, ShowRoute, LOCAL_AUTH, "Show routing table", StrNull}, { "timeout", NULL, ShowTimeout, LOCAL_AUTH, "Show Idle timeout value", StrNull}, #ifdef MSEXT { "msext", NULL, ShowMSExt, LOCAL_AUTH, "Show MS PPP extentions", StrNull}, #endif /* MSEXT */ { "version", NULL, ShowVersion, LOCAL_NO_AUTH | LOCAL_AUTH, "Show version string", StrNull}, { "help", "?", HelpCommand, LOCAL_NO_AUTH | LOCAL_AUTH, "Display this message", StrNull, (void *)ShowCommands}, { NULL, NULL, NULL }, }; struct cmdtab * FindCommand(cmds, str, pmatch) struct cmdtab *cmds; char *str; int *pmatch; { int nmatch = 0; int len = strlen(str); struct cmdtab *found = NULL; while (cmds->func) { if (cmds->name && strncasecmp(str, cmds->name, len) == 0) { nmatch++; found = cmds; } else if (cmds->alias && strncasecmp(str, cmds->alias, len) == 0) { nmatch++; found = cmds; } cmds++; } *pmatch = nmatch; return(found); } int FindExec(cmdlist, argc, argv) struct cmdtab *cmdlist; int argc; char **argv; { struct cmdtab *cmd; int val = 1; int nmatch; cmd = FindCommand(cmdlist, *argv, &nmatch); if (nmatch > 1) printf("Ambiguous.\n"); else if (cmd && ( cmd->lauth & VarLocalAuth ) ) val = (cmd->func)(cmd, --argc, ++argv, cmd->args); else printf("what?\n"); return(val); } int aft_cmd = 1; void Prompt() { char *pconnect, *pauth; if (!(mode & MODE_INTER)) return; if (!aft_cmd) printf("\n"); else aft_cmd = 0; if ( VarLocalAuth == LOCAL_AUTH ) pauth = " ON "; else pauth = " on "; if (IpcpFsm.state == ST_OPENED && phase == PHASE_NETWORK) pconnect = "PPP"; else pconnect = "ppp"; printf("%s%s%s> ", pconnect, pauth, VarShortHost); fflush(stdout); } void DecodeCommand(buff, nb, prompt) char *buff; int nb; int prompt; { char *vector[20]; char **argv; int argc, val; char *cp; val = 1; if (nb > 0) { cp = buff + strcspn(buff, "\r\n"); if (cp) *cp = '\0'; { argc = MakeArgs(buff, vector, VECSIZE(vector)); argv = vector; if (argc > 0) val = FindExec(Commands, argc, argv); } } if (val && prompt) Prompt(); } static int ShowCommand(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int val = 1; if (argc > 0) val = FindExec(ShowCommands, argc, argv); else printf("Use ``show ?'' to get a list.\n"); return(val); } static int TerminalCommand() { if (LcpFsm.state > ST_CLOSED) { printf("LCP state is [%s]\n", StateNames[LcpFsm.state]); return(1); } if (!IsInteractive()) return(1); modem = OpenModem(mode); if (modem < 0) { printf("failed to open modem.\n"); return(1); } printf("Enter to terminal mode.\n"); printf("Type `~?' for help.\n"); TtyTermMode(); return(0); } static int QuitCommand(list, argc, argv) struct cmdtab *list; int argc; char **argv; { if (mode & (MODE_DIRECT|MODE_DEDICATED|MODE_AUTO)) { if (argc > 0 && (VarLocalAuth & LOCAL_AUTH)) { Cleanup(EX_NORMAL); mode &= ~MODE_INTER; } else { LogPrintf(LOG_PHASE_BIT, "client connection closed.\n"); VarLocalAuth = LOCAL_NO_AUTH; close(netfd); close(1); dup2(2, 1); /* Have to have something here or the modem will be 1 */ netfd = -1; mode &= ~MODE_INTER; } } else Cleanup(EX_NORMAL); return(1); } static int CloseCommand() { LcpClose(); lostCarrier = 0; return(1); } static int DownCommand() { LcpDown(); return(1); } static int SetModemSpeed(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int speed; if (argc > 0) { if (strcmp(*argv, "sync") == 0) { VarSpeed = 0; return(1); } speed = atoi(*argv); if (IntToSpeed(speed) != B0) { VarSpeed = speed; return(1); } printf("invalid speed.\n"); } return(1); } static int SetReconnect(list, argc, argv) struct cmdtab *list; int argc; char **argv; { if (argc == 2) { VarReconnectTimer = atoi(argv[0]); VarReconnectTries = atoi(argv[1]); } else printf("Usage: %s %s\n", list->name, list->syntax); return(1); } static int SetRedialTimeout(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int timeout; int tries; char *dot; if (argc == 1 || argc == 2 ) { if (strncasecmp(argv[0], "random", 6) == 0 && (argv[0][6] == '\0' || argv[0][6] == '.')) { VarRedialTimeout = -1; printf("Using random redial timeout.\n"); if (!randinit) { randinit = 1; if (srandomdev() < 0) srandom((unsigned long)(time(NULL) ^ getpid())); } } else { timeout = atoi(argv[0]); if (timeout >= 0) { VarRedialTimeout = timeout; } else { printf("invalid redial timeout\n"); printf("Usage: %s %s\n", list->name, list->syntax); } } dot = index(argv[0],'.'); if (dot) { if (strcasecmp(++dot, "random") == 0) { VarRedialNextTimeout = -1; printf("Using random next redial timeout.\n"); if (!randinit) { randinit = 1; if (srandomdev() < 0) srandom((unsigned long)(time(NULL) ^ getpid())); } } else { timeout = atoi(dot); if (timeout >= 0) { VarRedialNextTimeout = timeout; } else { printf("invalid next redial timeout\n"); printf("Usage: %s %s\n", list->name, list->syntax); } } } else VarRedialNextTimeout = NEXT_REDIAL_PERIOD; /* Default next timeout */ if (argc == 2) { tries = atoi(argv[1]); if (tries >= 0) { VarDialTries = tries; } else { printf("invalid retry value\n"); printf("Usage: %s %s\n", list->name, list->syntax); } } } else { printf("Usage: %s %s\n", list->name, list->syntax); } return(1); } static int SetModemParity(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int parity; if (argc > 0) { parity = ChangeParity(*argv); if (parity < 0) printf("Invalid parity.\n"); else VarParity = parity; } return(1); } static int SetDebugLevel(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int level, w; for (level = 0; argc-- > 0; argv++) { if (isdigit(**argv)) { w = atoi(*argv); if (w < 0 || w >= MAXLOGLEVEL) { printf("invalid log level.\n"); break; } else level |= (1 << w); } else { for (w = 0; w < MAXLOGLEVEL; w++) { if (strcasecmp(*argv, LogLevelName[w]) == 0) { level |= (1 << w); continue; } } } } loglevel = level; return(1); } static int SetEscape(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int code; for (code = 0; code < 33; code++) EscMap[code] = 0; while (argc-- > 0) { sscanf(*argv++, "%x", &code); code &= 0xff; EscMap[code >> 3] |= (1 << (code&7)); EscMap[32] = 1; } return(1); } static int SetInitialMRU(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int mru; if (argc > 0) { mru = atoi(*argv); if (mru < 100) printf("given value is too small.\n"); else if (mru > MAX_MRU) printf("given value is too big.\n"); else VarMRU = mru; } return(1); } static int SetIdleTimeout(list, argc, argv) struct cmdtab *list; int argc; char **argv; { if (argc-- > 0) { VarIdleTimeout = atoi(*argv++); if (argc-- > 0) { VarLqrTimeout = atoi(*argv++); if (VarLqrTimeout < 1) VarLqrTimeout = 30; if (argc > 0) { VarRetryTimeout = atoi(*argv); if (VarRetryTimeout < 1 || VarRetryTimeout > 10) VarRetryTimeout = 3; } } } return(1); } struct in_addr GetIpAddr(cp) char *cp; { struct hostent *hp; struct in_addr ipaddr; hp = gethostbyname(cp); if (hp && hp->h_addrtype == AF_INET) bcopy(hp->h_addr, &ipaddr, hp->h_length); else if (inet_aton(cp, &ipaddr) == 0) ipaddr.s_addr = 0; return(ipaddr); } static int SetInterfaceAddr(list, argc, argv) struct cmdtab *list; int argc; char **argv; { DefMyAddress.ipaddr.s_addr = DefHisAddress.ipaddr.s_addr = 0L; if (argc > 4) { printf("set ifaddr: too many arguments (%d > 4)\n", argc); return(0); } if (argc > 0) { if (ParseAddr(argc, argv++, &DefMyAddress.ipaddr, &DefMyAddress.mask, &DefMyAddress.width) == 0) return(0); if (--argc > 0) { if (ParseAddr(argc, argv++, &DefHisAddress.ipaddr, &DefHisAddress.mask, &DefHisAddress.width) == 0) return(0); if (--argc > 0) { ifnetmask = GetIpAddr(*argv); if (--argc > 0) { if (ParseAddr(argc, argv++, &DefTriggerAddress.ipaddr, &DefTriggerAddress.mask, &DefTriggerAddress.width) == 0) return(0); } } } } /* * For backwards compatibility, 0.0.0.0 means any address. */ if (DefMyAddress.ipaddr.s_addr == 0) { DefMyAddress.mask.s_addr = 0; DefMyAddress.width = 0; } if (DefHisAddress.ipaddr.s_addr == 0) { DefHisAddress.mask.s_addr = 0; DefHisAddress.width = 0; } if ((mode & MODE_AUTO) || ((mode & MODE_DEDICATED) && dstsystem)) { if (OsSetIpaddress(DefMyAddress.ipaddr, DefHisAddress.ipaddr, ifnetmask) < 0) return(0); } return(1); } #ifdef MSEXT void SetMSEXT(pri_addr, sec_addr, argc, argv) struct in_addr *pri_addr; struct in_addr *sec_addr; int argc; char **argv; { int dummyint; struct in_addr dummyaddr; pri_addr->s_addr = sec_addr->s_addr = 0L; if( argc > 0 ) { ParseAddr(argc, argv++, pri_addr, &dummyaddr, &dummyint); if( --argc > 0 ) ParseAddr(argc, argv++, sec_addr, &dummyaddr, &dummyint); else sec_addr->s_addr = pri_addr->s_addr; } /* * if the primary/secondary ns entries are 0.0.0.0 we should * set them to either the localhost's ip, or the values in * /etc/resolv.conf ?? * * up to you if you want to implement this... */ } static int SetNS(list, argc, argv) struct cmdtab *list; int argc; char **argv; { SetMSEXT(&ns_entries[0], &ns_entries[1], argc, argv); return(1); } static int SetNBNS(list, argc, argv) struct cmdtab *list; int argc; char **argv; { SetMSEXT(&nbns_entries[0], &nbns_entries[1], argc, argv); return(1); } #endif /* MS_EXT */ #define VAR_AUTHKEY 0 #define VAR_DIAL 1 #define VAR_LOGIN 2 #define VAR_AUTHNAME 3 #define VAR_DEVICE 4 #define VAR_ACCMAP 5 #define VAR_PHONE 6 static int SetVariable(list, argc, argv, param) struct cmdtab *list; int argc; char **argv; int param; { u_long map; if (argc > 0) { switch (param) { case VAR_AUTHKEY: strncpy(VarAuthKey, *argv, sizeof(VarAuthKey)-1); VarAuthKey[sizeof(VarAuthKey)-1] = '\0'; break; case VAR_AUTHNAME: strncpy(VarAuthName, *argv, sizeof(VarAuthName)-1); VarAuthName[sizeof(VarAuthName)-1] = '\0'; break; case VAR_DIAL: strncpy(VarDialScript, *argv, sizeof(VarDialScript)-1); VarDialScript[sizeof(VarDialScript)-1] = '\0'; break; case VAR_LOGIN: strncpy(VarLoginScript, *argv, sizeof(VarLoginScript)-1); VarLoginScript[sizeof(VarLoginScript)-1] = '\0'; break; case VAR_DEVICE: strncpy(VarDevice, *argv, sizeof(VarDevice)-1); VarDevice[sizeof(VarDevice)-1] = '\0'; VarBaseDevice = rindex(VarDevice, '/'); VarBaseDevice = VarBaseDevice ? VarBaseDevice + 1 : ""; break; case VAR_ACCMAP: sscanf(*argv, "%lx", &map); VarAccmap = map; break; case VAR_PHONE: strncpy(VarPhoneList, *argv, sizeof(VarPhoneList)-1); VarPhoneList[sizeof(VarPhoneList)-1] = '\0'; strcpy(VarPhoneCopy, VarPhoneList); VarNextPhone = VarPhoneCopy; break; } } return(1); } static int SetCtsRts(list, argc, argv) struct cmdtab *list; int argc; char **argv; { if (argc > 0) { if (strcmp(*argv, "on") == 0) VarCtsRts = TRUE; else if (strcmp(*argv, "off") == 0) VarCtsRts = FALSE; else printf("usage: set ctsrts [on|off].\n"); } return(1); } static int SetOpenMode(list, argc, argv) struct cmdtab *list; int argc; char **argv; { if (argc > 0) { if (strcmp(*argv, "active") == 0) VarOpenMode = OPEN_ACTIVE; else if (strcmp(*argv, "passive") == 0) VarOpenMode = OPEN_PASSIVE; else printf("Invalid mode.\n"); } return(1); } static char StrChatStr[] = "chat-script"; static char StrValue[] = "value"; extern int SetIfilter(), SetOfilter(), SetDfilter(), SetAfilter(); struct cmdtab const SetCommands[] = { { "accmap", NULL, SetVariable, LOCAL_AUTH, "Set accmap value", "hex-value", (void *)VAR_ACCMAP}, { "afilter", NULL, SetAfilter, LOCAL_AUTH, "Set keep Alive filter", "..."}, { "authkey", "key", SetVariable, LOCAL_AUTH, "Set authentication key", "key", (void *)VAR_AUTHKEY}, { "authname", NULL, SetVariable, LOCAL_AUTH, "Set authentication name", "name", (void *)VAR_AUTHNAME}, { "ctsrts", NULL, SetCtsRts, LOCAL_AUTH, "Use CTS/RTS modem signalling", "[on|off]"}, { "debug", NULL, SetDebugLevel, LOCAL_AUTH, "Set debug level", StrValue}, { "device", "line", SetVariable, LOCAL_AUTH, "Set modem device name", "device-name", (void *)VAR_DEVICE}, { "dfilter", NULL, SetDfilter, LOCAL_AUTH, "Set demand filter", "..."}, { "dial", NULL, SetVariable, LOCAL_AUTH, "Set dialing script", StrChatStr, (void *)VAR_DIAL}, { "escape", NULL, SetEscape, LOCAL_AUTH, "Set escape characters", "hex-digit ..."}, { "ifaddr", NULL, SetInterfaceAddr, LOCAL_AUTH, "Set destination address", "[src-addr [dst-addr [netmask [trg-addr]]]]"}, { "ifilter", NULL, SetIfilter, LOCAL_AUTH, "Set input filter", "..."}, { "login", NULL, SetVariable, LOCAL_AUTH, "Set login script", StrChatStr, (void *)VAR_LOGIN }, { "mru", "mtu", SetInitialMRU, LOCAL_AUTH, "Set Initial MRU value", StrValue }, { "ofilter", NULL, SetOfilter, LOCAL_AUTH, "Set output filter", "..." }, { "openmode", NULL, SetOpenMode, LOCAL_AUTH, "Set open mode", "[active|passive]"}, { "parity", NULL, SetModemParity, LOCAL_AUTH, "Set modem parity", "[odd|even|none]"}, { "phone", NULL, SetVariable, LOCAL_AUTH, "Set telephone number(s)", "phone1[:phone2[...]]", (void *)VAR_PHONE }, { "reconnect",NULL, SetReconnect, LOCAL_AUTH, "Set Reconnect timeout", "value ntries"}, { "redial", NULL, SetRedialTimeout, LOCAL_AUTH, "Set Redial timeout", "value|random[.value|random] [dial_attempts]"}, { "speed", NULL, SetModemSpeed, LOCAL_AUTH, "Set modem speed", "speed"}, { "timeout", NULL, SetIdleTimeout, LOCAL_AUTH, "Set Idle timeout", StrValue}, #ifdef MSEXT { "ns", NULL, SetNS, LOCAL_AUTH, "Set NameServer", "pri-addr [sec-addr]"}, { "nbns", NULL, SetNBNS, LOCAL_AUTH, "Set NetBIOS NameServer", "pri-addr [sec-addr]"}, #endif /* MSEXT */ { "help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH, "Display this message", StrNull, (void *)SetCommands}, { NULL, NULL, NULL }, }; static int SetCommand(list, argc, argv) struct cmdtab *list; int argc; char **argv; { int val = 1; if (argc > 0) val = FindExec(SetCommands, argc, argv); else printf("Use `set ?' to get a list or `set ? ' for syntax help.\n"); return(val); } static int AddCommand(list, argc, argv) struct cmdtab *list; int argc; char **argv; { struct in_addr dest, gateway, netmask; if (argc == 3) { dest = GetIpAddr(argv[0]); netmask = GetIpAddr(argv[1]); if (strcasecmp(argv[2], "HISADDR") == 0) gateway = IpcpInfo.his_ipaddr; else gateway = GetIpAddr(argv[2]); OsSetRoute(RTM_ADD, dest, gateway, netmask); } else { printf("Usage: %s %s\n", list->name, list->syntax); } return(1); } static int DeleteCommand(list, argc, argv) struct cmdtab *list; int argc; char **argv; { struct in_addr dest, gateway, netmask; if (argc >= 2) { dest = GetIpAddr(argv[0]); if (strcasecmp(argv[1], "HISADDR") == 0) gateway = IpcpInfo.his_ipaddr; else gateway = GetIpAddr(argv[1]); netmask.s_addr = 0; if (argc == 3) { if (inet_aton(argv[1], &netmask) == 0) { printf("bad netmask value.\n"); return(1); } } OsSetRoute(RTM_DELETE, dest, gateway, netmask); } else if (argc == 1 && strcasecmp(argv[0], "ALL") == 0) { DeleteIfRoutes(0); } else { printf("Usage: %s %s\n", list->name, list->syntax); } return(1); } diff --git a/usr.sbin/ppp/main.c b/usr.sbin/ppp/main.c index e4403f5f0e85..052cad124e09 100644 --- a/usr.sbin/ppp/main.c +++ b/usr.sbin/ppp/main.c @@ -1,1023 +1,1027 @@ /* * User Process PPP * * Written by Toshiharu OHNO (tony-o@iij.ad.jp) * * Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the Internet Initiative Japan, Inc. The name of the * IIJ may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * - * $Id: main.c,v 1.48 1997/05/10 03:39:53 brian Exp $ + * $Id: main.c,v 1.49 1997/05/11 10:23:16 brian Exp $ * * TODO: * o Add commands for traffic summary, version display, etc. * o Add signal handler for misc controls. */ #include "fsm.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "modem.h" #include "os.h" #include "hdlc.h" #include "ccp.h" #include "lcp.h" #include "ipcp.h" #include "vars.h" #include "auth.h" #include "filter.h" #include "systems.h" #include "ip.h" #include "alias.h" #include "sig.h" #define LAUTH_M1 "Warning: No password entry for this host in ppp.secret\n" #define LAUTH_M2 "Warning: All manipulation is allowed by anyone in the world\n" #ifndef O_NONBLOCK #ifdef O_NDELAY #define O_NONBLOCK O_NDELAY #endif #endif extern void VjInit(), AsyncInit(); extern void AsyncInput(); extern int SelectSystem(); extern void DecodeCommand(), Prompt(); extern int aft_cmd; extern int IsInteractive(); static void DoLoop(void); static void TerminalStop(); static struct termios oldtio; /* Original tty mode */ static struct termios comtio; /* Command level tty mode */ int TermMode; static int server; static pid_t BGPid = 0; struct sockaddr_in ifsin; static char pid_filename[MAXPATHLEN]; static char if_filename[MAXPATHLEN]; int tunno; static void TtyInit() { struct termios newtio; int stat; stat = fcntl(0, F_GETFL, 0); if (stat > 0) { stat |= O_NONBLOCK; (void)fcntl(0, F_SETFL, stat); } newtio = oldtio; newtio.c_lflag &= ~(ECHO|ISIG|ICANON); newtio.c_iflag = 0; newtio.c_oflag &= ~OPOST; newtio.c_cc[VEOF] = _POSIX_VDISABLE; newtio.c_cc[VINTR] = _POSIX_VDISABLE; newtio.c_cc[VMIN] = 1; newtio.c_cc[VTIME] = 0; newtio.c_cflag |= CS8; tcsetattr(0, TCSADRAIN, &newtio); comtio = newtio; } /* * Set tty into command mode. We allow canonical input and echo processing. */ void TtyCommandMode(prompt) int prompt; { struct termios newtio; int stat; if (!(mode & MODE_INTER)) return; tcgetattr(0, &newtio); newtio.c_lflag |= (ECHO|ISIG|ICANON); newtio.c_iflag = oldtio.c_iflag; newtio.c_oflag |= OPOST; tcsetattr(0, TCSADRAIN, &newtio); stat = fcntl(0, F_GETFL, 0); if (stat > 0) { stat |= O_NONBLOCK; (void)fcntl(0, F_SETFL, stat); } TermMode = 0; if(prompt) Prompt(); } /* * Set tty into terminal mode which is used while we invoke term command. */ void TtyTermMode() { int stat; tcsetattr(0, TCSADRAIN, &comtio); stat = fcntl(0, F_GETFL, 0); if (stat > 0) { stat &= ~O_NONBLOCK; (void)fcntl(0, F_SETFL, stat); } TermMode = 1; } void TtyOldMode() { int stat; stat = fcntl(0, F_GETFL, 0); if (stat > 0) { stat &= ~O_NONBLOCK; (void)fcntl(0, F_SETFL, stat); } tcsetattr(0, TCSANOW, &oldtio); } void Cleanup(excode) int excode; { OsLinkdown(); OsCloseLink(1); sleep(1); if (mode & (MODE_AUTO | MODE_BACKGROUND)) DeleteIfRoutes(1); (void)unlink(pid_filename); (void)unlink(if_filename); OsInterfaceDown(1); if (mode & MODE_BACKGROUND && BGFiledes[1] != -1) { char c = EX_ERRDEAD; if (write(BGFiledes[1],&c,1) == 1) LogPrintf(LOG_PHASE_BIT,"Parent notified of failure.\n"); else LogPrintf(LOG_PHASE_BIT,"Failed to notify parent of failure.\n"); close(BGFiledes[1]); } LogPrintf(LOG_PHASE_BIT, "PPP Terminated %d.\n",excode); LogClose(); if (server >= 0) { close(server); server = -1; } TtyOldMode(); exit(excode); } static void Hangup(signo) int signo; { if (signo == SIGSEGV) { LogPrintf(LOG_PHASE_BIT, "Signal %d, core dump.\n", signo); LogClose(); abort(); } if (BGPid) { kill (BGPid, SIGTERM); exit (EX_HANGUP); } else { LogPrintf(LOG_PHASE_BIT, "Signal %d, hangup.\n", signo); Cleanup(EX_HANGUP); } } static void CloseSession(signo) int signo; { if (BGPid) { kill (BGPid, SIGINT); exit (EX_TERM); } else { LogPrintf(LOG_PHASE_BIT, "Signal %d, terminate.\n", signo); LcpClose(); Cleanup(EX_TERM); } } static void TerminalCont() { pending_signal(SIGCONT, SIG_DFL); pending_signal(SIGTSTP, TerminalStop); TtyCommandMode(getpgrp() == tcgetpgrp(0)); } static void TerminalStop(signo) int signo; { pending_signal(SIGCONT, TerminalCont); TtyOldMode(); pending_signal(SIGTSTP, SIG_DFL); kill(getpid(), signo); } void Usage() { fprintf(stderr, "Usage: ppp [-auto | -background | -direct | -dedicated | -ddial ] [ -alias ] [system]\n"); exit(EX_START); } void ProcessArgs(int argc, char **argv) { int optc; char *cp; optc = 0; while (argc > 0 && **argv == '-') { cp = *argv + 1; if (strcmp(cp, "auto") == 0) mode |= MODE_AUTO; else if (strcmp(cp, "background") == 0) mode |= MODE_BACKGROUND; else if (strcmp(cp, "direct") == 0) mode |= MODE_DIRECT; else if (strcmp(cp, "dedicated") == 0) mode |= MODE_DEDICATED; else if (strcmp(cp, "ddial") == 0) mode |= MODE_DDIAL|MODE_AUTO; else if (strcmp(cp, "alias") == 0) { mode |= MODE_ALIAS; optc--; /* this option isn't exclusive */ } else Usage(); optc++; argv++; argc--; } if (argc > 1) { fprintf(stderr, "specify only one system label.\n"); exit(EX_START); } if (argc == 1) dstsystem = *argv; if (optc > 1) { fprintf(stderr, "specify only one mode.\n"); exit(EX_START); } } static void Greetings() { printf("User Process PPP. Written by Toshiharu OHNO.\r\n"); fflush(stdout); } void main(argc, argv) int argc; char **argv; { FILE *lockfile; argc--; argv++; mode = MODE_INTER; /* default operation is interactive mode */ netfd = server = modem = tun_in = -1; ProcessArgs(argc, argv); Greetings(); GetUid(); IpcpDefAddress(); InitAlias(); if (SelectSystem("default", CONFFILE) < 0) { fprintf(stderr, "Warning: No default entry is given in config file.\n"); } switch ( LocalAuthInit() ) { case NOT_FOUND: fprintf(stderr,LAUTH_M1); fprintf(stderr,LAUTH_M2); fflush (stderr); /* Fall down */ case VALID: VarLocalAuth = LOCAL_AUTH; break; default: break; } if (OpenTunnel(&tunno) < 0) { perror("open_tun"); exit(EX_START); } if (mode & (MODE_AUTO|MODE_DIRECT|MODE_DEDICATED|MODE_BACKGROUND)) mode &= ~MODE_INTER; if (mode & MODE_INTER) { printf("Interactive mode\n"); netfd = STDIN_FILENO; } else if (mode & MODE_AUTO) { printf("Automatic Dialer mode\n"); if (dstsystem == NULL) { fprintf(stderr, "Destination system must be specified in auto or ddial mode.\n"); exit(EX_START); } } else if (mode & MODE_BACKGROUND) { printf("Background mode\n"); if (dstsystem == NULL) { fprintf(stderr, "Destination system must be specified in background mode.\n"); exit(EX_START); } } tcgetattr(0, &oldtio); /* Save original tty mode */ pending_signal(SIGHUP, LogReOpen); pending_signal(SIGTERM, CloseSession); pending_signal(SIGINT, CloseSession); pending_signal(SIGQUIT, CloseSession); #ifdef SIGSEGV signal(SIGSEGV, Hangup); #endif #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif #ifdef SIGALRM pending_signal(SIGALRM, SIG_IGN); #endif if(mode & MODE_INTER) { #ifdef SIGTSTP pending_signal(SIGTSTP, TerminalStop); #endif #ifdef SIGTTIN pending_signal(SIGTTIN, TerminalStop); #endif #ifdef SIGTTOU pending_signal(SIGTTOU, SIG_IGN); #endif } if (dstsystem) { if (SelectSystem(dstsystem, CONFFILE) < 0) { fprintf(stderr, "Destination system not found in conf file.\n"); Cleanup(EX_START); } if ((mode & MODE_AUTO) && DefHisAddress.ipaddr.s_addr == INADDR_ANY) { fprintf(stderr, "Must specify dstaddr with auto or ddial mode.\n"); Cleanup(EX_START); } } if (mode & MODE_DIRECT) printf("Packet mode enabled.\n"); if (!(mode & MODE_INTER)) { int port = SERVER_PORT + tunno; if (mode & MODE_BACKGROUND) { if (pipe (BGFiledes)) { perror("pipe"); Cleanup(EX_SOCK); } } else { /* * Create server socket and listen at there. */ server = socket(PF_INET, SOCK_STREAM, 0); if (server < 0) { perror("socket"); Cleanup(EX_SOCK); } ifsin.sin_family = AF_INET; ifsin.sin_addr.s_addr = INADDR_ANY; ifsin.sin_port = htons(port); if (bind(server, (struct sockaddr *) &ifsin, sizeof(ifsin)) < 0) { perror("bind"); if (errno == EADDRINUSE) fprintf(stderr, "Wait for a while, then try again.\n"); Cleanup(EX_SOCK); } if (listen(server, 5) != 0) { fprintf(stderr, "Unable to listen to socket - OS overload?\n"); } } DupLog(); if (!(mode & MODE_DIRECT)) { pid_t bgpid; bgpid = fork (); if (bgpid == -1) { perror ("fork"); Cleanup (EX_SOCK); } if (bgpid) { char c = EX_NORMAL; if (mode & MODE_BACKGROUND) { /* Wait for our child to close its pipe before we exit. */ BGPid = bgpid; close (BGFiledes[1]); if (read(BGFiledes[0], &c, 1) != 1) LogPrintf (LOG_PHASE_BIT, "Parent: Child exit, no status.\n"); else if (c == EX_NORMAL) LogPrintf (LOG_PHASE_BIT, "Parent: PPP enabled.\n"); else LogPrintf (LOG_PHASE_BIT, "Parent: Child failed %d.\n",(int)c); close (BGFiledes[0]); } exit(c); } else if (mode & MODE_BACKGROUND) close(BGFiledes[0]); } - snprintf(pid_filename, sizeof (pid_filename), "%s/tun%d.pid", + snprintf(pid_filename, sizeof (pid_filename), "%stun%d.pid", _PATH_VARRUN, tunno); (void)unlink(pid_filename); if ((lockfile = fopen(pid_filename, "w")) != NULL) { fprintf(lockfile, "%d\n", (int)getpid()); fclose(lockfile); } else logprintf("Warning: Can't create %s: %s\n", pid_filename, strerror(errno)); snprintf(if_filename, sizeof if_filename, "%s%s.if", _PATH_VARRUN, VarBaseDevice); (void)unlink(if_filename); if ((lockfile = fopen(if_filename, "w")) != NULL) { fprintf(lockfile, "tun%d\n", tunno); fclose(lockfile); } else logprintf("Warning: Can't create %s: %s\n", if_filename, strerror(errno)); if (server >= 0) LogPrintf(LOG_PHASE_BIT, "Listening at %d.\n", port); #ifdef DOTTYINIT if (mode & (MODE_DIRECT|MODE_DEDICATED)) { /* } */ #else if (mode & MODE_DIRECT) { #endif TtyInit(); } else { int fd; setsid(); /* detach control tty */ if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { (void)dup2(fd, STDIN_FILENO); (void)dup2(fd, STDOUT_FILENO); (void)dup2(fd, STDERR_FILENO); if (fd > 2) (void)close (fd); } } } else { TtyInit(); TtyCommandMode(1); } LogPrintf(LOG_PHASE_BIT, "PPP Started.\n"); do DoLoop(); while (mode & MODE_DEDICATED); Cleanup(EX_DONE); } /* * Turn into packet mode, where we speak PPP. */ void PacketMode() { if (RawModem(modem) < 0) { fprintf(stderr, "Not connected.\r\n"); return; } AsyncInit(); VjInit(); LcpInit(); IpcpInit(); CcpInit(); LcpUp(); if (mode & (MODE_DIRECT|MODE_DEDICATED)) LcpOpen(OPEN_ACTIVE); else LcpOpen(VarOpenMode); if ((mode & (MODE_INTER|MODE_AUTO)) == MODE_INTER) { TtyCommandMode(1); fprintf(stderr, "Packet mode.\r\n"); aft_cmd = 1; } } static void ShowHelp() { fprintf(stderr, "The following commands are available:\r\n"); fprintf(stderr, " ~p\tEnter to Packet mode\r\n"); fprintf(stderr, " ~-\tDecrease log level\r\n"); fprintf(stderr, " ~+\tIncrease log level\r\n"); fprintf(stderr, " ~.\tTerminate program\r\n"); fprintf(stderr, " ~?\tThis help\r\n"); } static void ReadTty() { int n; char ch; static int ttystate; #define MAXLINESIZE 200 char linebuff[MAXLINESIZE]; #ifdef DEBUG logprintf("termode = %d, netfd = %d, mode = %d\n", TermMode, netfd, mode); #endif if (!TermMode) { n = read(netfd, linebuff, sizeof(linebuff)-1); aft_cmd = 1; if (n > 0) { DecodeCommand(linebuff, n, 1); } else { LogPrintf(LOG_PHASE_BIT, "client connection closed.\n"); VarLocalAuth = LOCAL_NO_AUTH; close(netfd); close(1); dup2(2, 1); /* Have to have something here or the modem will be 1 */ netfd = -1; mode &= ~MODE_INTER; } return; } /* * We are in terminal mode, decode special sequences */ n = read(0, &ch, 1); #ifdef DEBUG logprintf("got %d bytes\n", n); #endif if (n > 0) { switch (ttystate) { case 0: if (ch == '~') ttystate++; else write(modem, &ch, n); break; case 1: switch (ch) { case '?': ShowHelp(); break; case '-': if (loglevel > 0) { loglevel--; fprintf(stderr, "New loglevel is %d\r\n", loglevel); } break; case '+': loglevel++; fprintf(stderr, "New loglevel is %d\r\n", loglevel); break; #ifdef DEBUG case 'm': ShowMemMap(); break; #endif case 'p': /* * XXX: Should check carrier. */ if (LcpFsm.state <= ST_CLOSED) { VarOpenMode = OPEN_ACTIVE; PacketMode(); } break; #ifdef DEBUG case 't': ShowTimers(); break; #endif case '.': TermMode = 1; TtyCommandMode(1); break; default: if (write(modem, &ch, n) < 0) fprintf(stderr, "err in write.\r\n"); break; } ttystate = 0; break; } } } /* * Here, we'll try to detect HDLC frame */ static char *FrameHeaders[] = { "\176\377\003\300\041", "\176\377\175\043\300\041", "\176\177\175\043\100\041", "\176\175\337\175\043\300\041", "\176\175\137\175\043\100\041", NULL, }; u_char * HdlcDetect(cp, n) u_char *cp; int n; { char *ptr, *fp, **hp; cp[n] = '\0'; /* be sure to null terminated */ ptr = NULL; for (hp = FrameHeaders; *hp; hp++) { fp = *hp; if (DEV_IS_SYNC) fp++; ptr = strstr((char *)cp, fp); if (ptr) break; } return((u_char *)ptr); } static struct pppTimer RedialTimer; static void RedialTimeout() { StopTimer(&RedialTimer); LogPrintf(LOG_PHASE_BIT, "Redialing timer expired.\n"); } static void StartRedialTimer(Timeout) int Timeout; { StopTimer(&RedialTimer); if (Timeout) { RedialTimer.state = TIMER_STOPPED; if (Timeout > 0) RedialTimer.load = Timeout * SECTICKS; else RedialTimer.load = (random() % REDIAL_PERIOD) * SECTICKS; LogPrintf(LOG_PHASE_BIT, "Enter pause (%d) for redialing.\n", RedialTimer.load / SECTICKS); RedialTimer.func = RedialTimeout; StartTimer(&RedialTimer); } } static void DoLoop() { fd_set rfds, wfds, efds; int pri, i, n, wfd, nfds; struct sockaddr_in hisaddr; struct timeval timeout, *tp; int ssize = sizeof(hisaddr); u_char *cp; u_char rbuff[MAX_MRU]; int dial_up; int tries; int qlen; pid_t pgroup; pgroup = getpgrp(); if (mode & (MODE_DIRECT|MODE_BACKGROUND)) { modem = OpenModem(mode); LogPrintf(LOG_PHASE_BIT, "Packet mode enabled\n"); fflush(stderr); PacketMode(); } else if (mode & MODE_DEDICATED) { if (modem < 0) modem = OpenModem(mode); } fflush(stdout); timeout.tv_sec = 0; timeout.tv_usec = 0; lostCarrier = 0; if (mode & MODE_BACKGROUND) dial_up = TRUE; /* Bring the line up */ else dial_up = FALSE; /* XXXX */ tries = 0; for (;;) { nfds = 0; FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&efds); /* * If the link is down and we're in DDIAL mode, bring it back * up. */ if (mode & MODE_DDIAL && LcpFsm.state <= ST_CLOSED) dial_up = TRUE; /* * If we lost carrier and want to re-establish the connection * due to the "set reconnect" value, we'd better bring the line * back up now. */ - if (LcpFsm.state <= ST_CLOSED && dial_up != TRUE - && lostCarrier && lostCarrier <= VarReconnectTries) { + if (LcpFsm.state <= ST_CLOSED && dial_up != TRUE && lostCarrier) + if (lostCarrier <= VarReconnectTries) { LogPrintf(LOG_PHASE_BIT, "Connection lost, re-establish (%d/%d)\n", lostCarrier, VarReconnectTries); StartRedialTimer(VarReconnectTimer); dial_up = TRUE; - } + } else { + LogPrintf(LOG_PHASE_BIT, "Connection lost, maximum (%d) times\n", + VarReconnectTries); + lostCarrier = 0; + } /* * If Ip packet for output is enqueued and require dial up, * Just do it! */ if ( dial_up && RedialTimer.state != TIMER_RUNNING ) { #ifdef DEBUG logprintf("going to dial: modem = %d\n", modem); #endif modem = OpenModem(mode); if (modem < 0) { StartRedialTimer(VarRedialTimeout); } else { tries++; /* Tries are per number, not per list of numbers. */ if (VarDialTries) LogPrintf(LOG_CHAT_BIT, "Dial attempt %u of %d\n", tries, VarDialTries); else LogPrintf(LOG_CHAT_BIT, "Dial attempt %u\n", tries); if (DialModem()) { sleep(1); /* little pause to allow peer starts */ ModemTimeout(); PacketMode(); dial_up = FALSE; tries = 0; } else { CloseModem(); if (mode & MODE_BACKGROUND) { if (VarNextPhone == NULL) Cleanup(EX_DIAL); /* Tried all numbers - no luck */ else /* Try all numbers in background mode */ StartRedialTimer(VarRedialNextTimeout); } else if (VarDialTries && tries >= VarDialTries) { /* I give up ! Can't get through :( */ StartRedialTimer(VarRedialTimeout); dial_up = FALSE; tries = 0; } else if (VarNextPhone == NULL) /* Dial failed. Keep quite during redial wait period. */ StartRedialTimer(VarRedialTimeout); else StartRedialTimer(VarRedialNextTimeout); } } } qlen = ModemQlen(); if (qlen == 0) { IpStartOutput(); qlen = ModemQlen(); } if (modem >= 0) { if (modem + 1 > nfds) nfds = modem + 1; FD_SET(modem, &rfds); FD_SET(modem, &efds); if (qlen > 0) { FD_SET(modem, &wfds); } } if (server >= 0) { if (server + 1 > nfds) nfds = server + 1; FD_SET(server, &rfds); } /* *** IMPORTANT *** * * CPU is serviced every TICKUNIT micro seconds. * This value must be chosen with great care. If this values is * too big, it results loss of characters from modem and poor responce. * If this values is too small, ppp process eats many CPU time. */ #ifndef SIGALRM usleep(TICKUNIT); TimerService(); #else handle_signals(); #endif /* If there are aren't many packets queued, look for some more. */ if (qlen < 20 && tun_in >= 0) { if (tun_in + 1 > nfds) nfds = tun_in + 1; FD_SET(tun_in, &rfds); } if (netfd >= 0) { if (netfd + 1 > nfds) nfds = netfd + 1; FD_SET(netfd, &rfds); FD_SET(netfd, &efds); } #ifndef SIGALRM /* * Normally, select() will not block because modem is writable. * In AUTO mode, select will block until we find packet from tun */ tp = (RedialTimer.state == TIMER_RUNNING)? &timeout : NULL; i = select(nfds, &rfds, &wfds, &efds, tp); #else /* * When SIGALRM timer is running, a select function will be * return -1 and EINTR after a Time Service signal hundler * is done. If the redial timer is not running and we are * trying to dial, poll with a 0 value timer. */ tp = (dial_up && RedialTimer.state != TIMER_RUNNING) ? &timeout : NULL; i = select(nfds, &rfds, &wfds, &efds, tp); #endif if ( i == 0 ) { continue; } if ( i < 0 ) { if ( errno == EINTR ) { handle_signals(); continue; } perror("select"); break; } if ((netfd >= 0 && FD_ISSET(netfd, &efds)) || (modem >= 0 && FD_ISSET(modem, &efds))) { logprintf("Exception detected.\n"); break; } if (server >= 0 && FD_ISSET(server, &rfds)) { LogPrintf(LOG_PHASE_BIT, "connected to client.\n"); wfd = accept(server, (struct sockaddr *)&hisaddr, &ssize); if (wfd < 0) { perror("accept"); continue; } if (netfd >= 0) { write(wfd, "already in use.\n", 16); close(wfd); continue; } else netfd = wfd; if (dup2(netfd, 1) < 0) { perror("dup2"); close(netfd); netfd = -1; continue; } mode |= MODE_INTER; Greetings(); switch ( LocalAuthInit() ) { case NOT_FOUND: fprintf(stdout,LAUTH_M1); fprintf(stdout,LAUTH_M2); fflush(stdout); /* Fall down */ case VALID: VarLocalAuth = LOCAL_AUTH; break; default: break; } (void) IsInteractive(); Prompt(); } if ((mode & MODE_INTER) && (netfd >= 0 && FD_ISSET(netfd, &rfds)) && ((mode & MODE_AUTO) || pgroup == tcgetpgrp(0))) { /* something to read from tty */ ReadTty(); } if (modem >= 0) { if (FD_ISSET(modem, &wfds)) { /* ready to write into modem */ ModemStartOutput(modem); } if (FD_ISSET(modem, &rfds)) { /* something to read from modem */ if (LcpFsm.state <= ST_CLOSED) usleep(10000); n = read(modem, rbuff, sizeof(rbuff)); if ((mode & MODE_DIRECT) && n <= 0) { DownConnection(); } else LogDumpBuff(LOG_ASYNC, "ReadFromModem", rbuff, n); if (LcpFsm.state <= ST_CLOSED) { /* * In dedicated mode, we just discard input until LCP is started. */ if (!(mode & MODE_DEDICATED)) { cp = HdlcDetect(rbuff, n); if (cp) { /* * LCP packet is detected. Turn ourselves into packet mode. */ if (cp != rbuff) { write(1, rbuff, cp - rbuff); write(1, "\r\n", 2); } PacketMode(); } else write(1, rbuff, n); } } else { if (n > 0) AsyncInput(rbuff, n); } } } if (tun_in >= 0 && FD_ISSET(tun_in, &rfds)) { /* something to read from tun */ n = read(tun_in, rbuff, sizeof(rbuff)); if (n < 0) { perror("read from tun"); continue; } /* * Process on-demand dialup. Output packets are queued within tunnel * device until IPCP is opened. */ if (LcpFsm.state <= ST_CLOSED && (mode & MODE_AUTO)) { pri = PacketCheck(rbuff, n, FL_DIAL); if (pri >= 0) { if (mode & MODE_ALIAS) { PacketAliasOut((struct ip *)rbuff); n = ntohs(((struct ip *)rbuff)->ip_len); } IpEnqueue(pri, rbuff, n); dial_up = TRUE; /* XXX */ } continue; } pri = PacketCheck(rbuff, n, FL_OUT); if (pri >= 0) { if (mode & MODE_ALIAS) { PacketAliasOut((struct ip *)rbuff); n = ntohs(((struct ip *)rbuff)->ip_len); } IpEnqueue(pri, rbuff, n); } } } logprintf("job done.\n"); }