command.c revision 49976
1/*
2 *		PPP User command processing module
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: command.c,v 1.205 1999/08/05 10:32:09 brian Exp $
21 *
22 */
23#include <sys/param.h>
24#include <netinet/in_systm.h>
25#include <netinet/in.h>
26#include <netinet/ip.h>
27#include <arpa/inet.h>
28#include <sys/socket.h>
29#include <net/route.h>
30#include <netdb.h>
31#include <sys/un.h>
32
33#include <ctype.h>
34#include <errno.h>
35#include <fcntl.h>
36#include <paths.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sys/wait.h>
41#include <termios.h>
42#include <unistd.h>
43
44#ifndef NOALIAS
45#ifdef __FreeBSD__
46#include <alias.h>
47#else
48#include "alias.h"
49#endif
50#endif
51#include "layer.h"
52#include "defs.h"
53#include "command.h"
54#include "mbuf.h"
55#include "log.h"
56#include "timer.h"
57#include "fsm.h"
58#include "lcp.h"
59#include "iplist.h"
60#include "throughput.h"
61#include "slcompress.h"
62#include "lqr.h"
63#include "hdlc.h"
64#include "ipcp.h"
65#ifndef NOALIAS
66#include "alias_cmd.h"
67#endif
68#include "systems.h"
69#include "filter.h"
70#include "descriptor.h"
71#include "main.h"
72#include "route.h"
73#include "ccp.h"
74#include "auth.h"
75#include "async.h"
76#include "link.h"
77#include "physical.h"
78#include "mp.h"
79#ifndef NORADIUS
80#include "radius.h"
81#endif
82#include "bundle.h"
83#include "server.h"
84#include "prompt.h"
85#include "chat.h"
86#include "chap.h"
87#include "cbcp.h"
88#include "datalink.h"
89#include "iface.h"
90
91/* ``set'' values */
92#define	VAR_AUTHKEY	0
93#define	VAR_DIAL	1
94#define	VAR_LOGIN	2
95#define	VAR_AUTHNAME	3
96#define	VAR_AUTOLOAD	4
97#define	VAR_WINSIZE	5
98#define	VAR_DEVICE	6
99#define	VAR_ACCMAP	7
100#define	VAR_MRRU	8
101#define	VAR_MRU		9
102#define	VAR_MTU		10
103#define	VAR_OPENMODE	11
104#define	VAR_PHONE	12
105#define	VAR_HANGUP	13
106#define	VAR_IDLETIMEOUT	14
107#define	VAR_LQRPERIOD	15
108#define	VAR_LCPRETRY	16
109#define	VAR_CHAPRETRY	17
110#define	VAR_PAPRETRY	18
111#define	VAR_CCPRETRY	19
112#define	VAR_IPCPRETRY	20
113#define	VAR_DNS		21
114#define	VAR_NBNS	22
115#define	VAR_MODE	23
116#define	VAR_CALLBACK	24
117#define	VAR_CBCP	25
118#define	VAR_CHOKED	26
119#define	VAR_SENDPIPE	27
120#define	VAR_RECVPIPE	28
121#define	VAR_RADIUS	29
122#define	VAR_CD		30
123#define	VAR_PARITY	31
124#define VAR_CRTSCTS	32
125
126/* ``accept|deny|disable|enable'' masks */
127#define NEG_HISMASK (1)
128#define NEG_MYMASK (2)
129
130/* ``accept|deny|disable|enable'' values */
131#define NEG_ACFCOMP	40
132#define NEG_CHAP05	41
133#define NEG_CHAP80	42
134#define NEG_CHAP80LM	43
135#define NEG_DEFLATE	44
136#define NEG_DNS		45
137#define NEG_ENDDISC	46
138#define NEG_LQR		47
139#define NEG_PAP		48
140#define NEG_PPPDDEFLATE	49
141#define NEG_PRED1	50
142#define NEG_PROTOCOMP	51
143#define NEG_SHORTSEQ	52
144#define NEG_VJCOMP	53
145
146const char Version[] = "2.23";
147const char VersionDate[] = "$Date: 1999/08/05 10:32:09 $";
148
149static int ShowCommand(struct cmdargs const *);
150static int TerminalCommand(struct cmdargs const *);
151static int QuitCommand(struct cmdargs const *);
152static int OpenCommand(struct cmdargs const *);
153static int CloseCommand(struct cmdargs const *);
154static int DownCommand(struct cmdargs const *);
155static int SetCommand(struct cmdargs const *);
156static int LinkCommand(struct cmdargs const *);
157static int AddCommand(struct cmdargs const *);
158static int DeleteCommand(struct cmdargs const *);
159static int NegotiateCommand(struct cmdargs const *);
160static int ClearCommand(struct cmdargs const *);
161static int RunListCommand(struct cmdargs const *);
162static int IfaceAddCommand(struct cmdargs const *);
163static int IfaceDeleteCommand(struct cmdargs const *);
164static int IfaceClearCommand(struct cmdargs const *);
165static int SetProcTitle(struct cmdargs const *);
166#ifndef NOALIAS
167static int AliasEnable(struct cmdargs const *);
168static int AliasOption(struct cmdargs const *);
169#endif
170
171static const char *
172showcx(struct cmdtab const *cmd)
173{
174  if (cmd->lauth & LOCAL_CX)
175    return "(c)";
176  else if (cmd->lauth & LOCAL_CX_OPT)
177    return "(o)";
178
179  return "";
180}
181
182static int
183HelpCommand(struct cmdargs const *arg)
184{
185  struct cmdtab const *cmd;
186  int n, cmax, dmax, cols, cxlen;
187  const char *cx;
188
189  if (!arg->prompt) {
190    log_Printf(LogWARN, "help: Cannot help without a prompt\n");
191    return 0;
192  }
193
194  if (arg->argc > arg->argn) {
195    for (cmd = arg->cmdtab; cmd->name || cmd->alias; cmd++)
196      if ((cmd->lauth & arg->prompt->auth) &&
197          ((cmd->name && !strcasecmp(cmd->name, arg->argv[arg->argn])) ||
198           (cmd->alias && !strcasecmp(cmd->alias, arg->argv[arg->argn])))) {
199	prompt_Printf(arg->prompt, "%s %s\n", cmd->syntax, showcx(cmd));
200	return 0;
201      }
202    return -1;
203  }
204
205  cmax = dmax = 0;
206  for (cmd = arg->cmdtab; cmd->func; cmd++)
207    if (cmd->name && (cmd->lauth & arg->prompt->auth)) {
208      if ((n = strlen(cmd->name) + strlen(showcx(cmd))) > cmax)
209        cmax = n;
210      if ((n = strlen(cmd->helpmes)) > dmax)
211        dmax = n;
212    }
213
214  cols = 80 / (dmax + cmax + 3);
215  n = 0;
216  prompt_Printf(arg->prompt, "(o) = Optional context,"
217                " (c) = Context required\n");
218  for (cmd = arg->cmdtab; cmd->func; cmd++)
219    if (cmd->name && (cmd->lauth & arg->prompt->auth)) {
220      cx = showcx(cmd);
221      cxlen = cmax - strlen(cmd->name);
222      if (n % cols != 0)
223        prompt_Printf(arg->prompt, " ");
224      prompt_Printf(arg->prompt, "%s%-*.*s: %-*.*s",
225              cmd->name, cxlen, cxlen, cx, dmax, dmax, cmd->helpmes);
226      if (++n % cols == 0)
227        prompt_Printf(arg->prompt, "\n");
228    }
229  if (n % cols != 0)
230    prompt_Printf(arg->prompt, "\n");
231
232  return 0;
233}
234
235static int
236CloneCommand(struct cmdargs const *arg)
237{
238  char namelist[LINE_LEN];
239  char *name;
240  int f;
241
242  if (arg->argc == arg->argn)
243    return -1;
244
245  namelist[sizeof namelist - 1] = '\0';
246  for (f = arg->argn; f < arg->argc; f++) {
247    strncpy(namelist, arg->argv[f], sizeof namelist - 1);
248    for(name = strtok(namelist, ", "); name; name = strtok(NULL,", "))
249      bundle_DatalinkClone(arg->bundle, arg->cx, name);
250  }
251
252  return 0;
253}
254
255static int
256RemoveCommand(struct cmdargs const *arg)
257{
258  if (arg->argc != arg->argn)
259    return -1;
260
261  if (arg->cx->state != DATALINK_CLOSED) {
262    log_Printf(LogWARN, "remove: Cannot delete links that aren't closed\n");
263    return 2;
264  }
265
266  bundle_DatalinkRemove(arg->bundle, arg->cx);
267  return 0;
268}
269
270static int
271RenameCommand(struct cmdargs const *arg)
272{
273  if (arg->argc != arg->argn + 1)
274    return -1;
275
276  if (bundle_RenameDatalink(arg->bundle, arg->cx, arg->argv[arg->argn]))
277    return 0;
278
279  log_Printf(LogWARN, "%s -> %s: target name already exists\n",
280             arg->cx->name, arg->argv[arg->argn]);
281  return 1;
282}
283
284int
285LoadCommand(struct cmdargs const *arg)
286{
287  const char *err;
288  int n, mode;
289
290  mode = arg->bundle->phys_type.all;
291
292  if (arg->argn < arg->argc) {
293    for (n = arg->argn; n < arg->argc; n++)
294      if ((err = system_IsValid(arg->argv[n], arg->prompt, mode)) != NULL) {
295        log_Printf(LogWARN, "%s: %s\n", arg->argv[n], err);
296        return 1;
297      }
298
299    for (n = arg->argn; n < arg->argc; n++) {
300      bundle_SetLabel(arg->bundle, arg->argv[arg->argc - 1]);
301      system_Select(arg->bundle, arg->argv[n], CONFFILE, arg->prompt, arg->cx);
302    }
303    bundle_SetLabel(arg->bundle, arg->argv[arg->argc - 1]);
304  } else if ((err = system_IsValid("default", arg->prompt, mode)) != NULL) {
305    log_Printf(LogWARN, "default: %s\n", err);
306    return 1;
307  } else {
308    bundle_SetLabel(arg->bundle, "default");
309    system_Select(arg->bundle, "default", CONFFILE, arg->prompt, arg->cx);
310    bundle_SetLabel(arg->bundle, "default");
311  }
312
313  return 0;
314}
315
316int
317SaveCommand(struct cmdargs const *arg)
318{
319  log_Printf(LogWARN, "save command is not implemented (yet).\n");
320  return 1;
321}
322
323static int
324DialCommand(struct cmdargs const *arg)
325{
326  int res;
327
328  if ((arg->cx && !(arg->cx->physical->type & (PHYS_INTERACTIVE|PHYS_AUTO)))
329      || (!arg->cx &&
330          (arg->bundle->phys_type.all & ~(PHYS_INTERACTIVE|PHYS_AUTO)))) {
331    log_Printf(LogWARN, "Manual dial is only available for auto and"
332              " interactive links\n");
333    return 1;
334  }
335
336  if (arg->argc > arg->argn && (res = LoadCommand(arg)) != 0)
337    return res;
338
339  bundle_Open(arg->bundle, arg->cx ? arg->cx->name : NULL, PHYS_ALL, 1);
340
341  return 0;
342}
343
344#define isinword(ch) (isalnum(ch) || (ch) == '_')
345
346static char *
347strstrword(char *big, const char *little)
348{
349  /* Get the first occurance of the word ``little'' in ``big'' */
350  char *pos;
351  int len;
352
353  pos = big;
354  len = strlen(little);
355
356  while ((pos = strstr(pos, little)) != NULL)
357    if ((pos != big && isinword(pos[-1])) || isinword(pos[len]))
358      pos++;
359    else if (pos != big && pos[-1] == '\\')
360      memmove(pos - 1, pos, strlen(pos) + 1);
361    else
362      break;
363
364  return pos;
365}
366
367static char *
368subst(char *tgt, const char *oldstr, const char *newstr)
369{
370  /* tgt is a malloc()d area... realloc() as necessary */
371  char *word, *ntgt;
372  int ltgt, loldstr, lnewstr, pos;
373
374  if ((word = strstrword(tgt, oldstr)) == NULL)
375    return tgt;
376
377  ltgt = strlen(tgt) + 1;
378  loldstr = strlen(oldstr);
379  lnewstr = strlen(newstr);
380  do {
381    pos = word - tgt;
382    if (loldstr > lnewstr)
383      bcopy(word + loldstr, word + lnewstr, ltgt - pos - loldstr);
384    if (loldstr != lnewstr) {
385      ntgt = realloc(tgt, ltgt += lnewstr - loldstr);
386      if (ntgt == NULL)
387        break;			/* Oh wonderful ! */
388      word = ntgt + pos;
389      tgt = ntgt;
390    }
391    if (lnewstr > loldstr)
392      bcopy(word + loldstr, word + lnewstr, ltgt - pos - loldstr);
393    bcopy(newstr, word, lnewstr);
394  } while ((word = strstrword(word, oldstr)));
395
396  return tgt;
397}
398
399void
400command_Expand(char **nargv, int argc, char const *const *oargv,
401               struct bundle *bundle, int inc0, pid_t pid)
402{
403  int arg;
404  char pidstr[12];
405
406  if (inc0)
407    arg = 0;		/* Start at arg 0 */
408  else {
409    nargv[0] = strdup(oargv[0]);
410    arg = 1;
411  }
412  snprintf(pidstr, sizeof pidstr, "%d", (int)pid);
413  for (; arg < argc; arg++) {
414    nargv[arg] = strdup(oargv[arg]);
415    nargv[arg] = subst(nargv[arg], "HISADDR",
416                       inet_ntoa(bundle->ncp.ipcp.peer_ip));
417    nargv[arg] = subst(nargv[arg], "AUTHNAME", bundle->cfg.auth.name);
418    nargv[arg] = subst(nargv[arg], "INTERFACE", bundle->iface->name);
419    nargv[arg] = subst(nargv[arg], "MYADDR", inet_ntoa(bundle->ncp.ipcp.my_ip));
420    nargv[arg] = subst(nargv[arg], "USER", bundle->ncp.mp.peer.authname);
421    nargv[arg] = subst(nargv[arg], "PEER_ENDDISC",
422                       mp_Enddisc(bundle->ncp.mp.peer.enddisc.class,
423                                  bundle->ncp.mp.peer.enddisc.address,
424                                  bundle->ncp.mp.peer.enddisc.len));
425    nargv[arg] = subst(nargv[arg], "ENDDISC",
426                       mp_Enddisc(bundle->ncp.mp.cfg.enddisc.class,
427                                  bundle->ncp.mp.cfg.enddisc.address,
428                                  bundle->ncp.mp.cfg.enddisc.len));
429    nargv[arg] = subst(nargv[arg], "PROCESSID", pidstr);
430    nargv[arg] = subst(nargv[arg], "LABEL", bundle_GetLabel(bundle));
431  }
432  nargv[arg] = NULL;
433}
434
435static int
436ShellCommand(struct cmdargs const *arg, int bg)
437{
438  const char *shell;
439  pid_t shpid, pid;
440
441#ifdef SHELL_ONLY_INTERACTIVELY
442  /* we're only allowed to shell when we run ppp interactively */
443  if (arg->prompt && arg->prompt->owner) {
444    log_Printf(LogWARN, "Can't start a shell from a network connection\n");
445    return 1;
446  }
447#endif
448
449  if (arg->argc == arg->argn) {
450    if (!arg->prompt) {
451      log_Printf(LogWARN, "Can't start an interactive shell from"
452                " a config file\n");
453      return 1;
454    } else if (arg->prompt->owner) {
455      log_Printf(LogWARN, "Can't start an interactive shell from"
456                " a socket connection\n");
457      return 1;
458    } else if (bg) {
459      log_Printf(LogWARN, "Can only start an interactive shell in"
460		" the foreground mode\n");
461      return 1;
462    }
463  }
464
465  pid = getpid();
466  if ((shpid = fork()) == 0) {
467    int i, fd;
468
469    if ((shell = getenv("SHELL")) == 0)
470      shell = _PATH_BSHELL;
471
472    timer_TermService();
473
474    if (arg->prompt)
475      fd = arg->prompt->fd_out;
476    else if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
477      log_Printf(LogALERT, "Failed to open %s: %s\n",
478                _PATH_DEVNULL, strerror(errno));
479      exit(1);
480    }
481    dup2(fd, STDIN_FILENO);
482    dup2(fd, STDOUT_FILENO);
483    dup2(fd, STDERR_FILENO);
484    for (i = getdtablesize(); i > STDERR_FILENO; i--)
485      fcntl(i, F_SETFD, 1);
486
487    setuid(geteuid());
488    if (arg->argc > arg->argn) {
489      /* substitute pseudo args */
490      char *argv[MAXARGS];
491      int argc = arg->argc - arg->argn;
492
493      if (argc >= sizeof argv / sizeof argv[0]) {
494        argc = sizeof argv / sizeof argv[0] - 1;
495        log_Printf(LogWARN, "Truncating shell command to %d args\n", argc);
496      }
497      command_Expand(argv, argc, arg->argv + arg->argn, arg->bundle, 0, pid);
498      if (bg) {
499	pid_t p;
500
501	p = getpid();
502	if (daemon(1, 1) == -1) {
503	  log_Printf(LogERROR, "%d: daemon: %s\n", (int)p, strerror(errno));
504	  exit(1);
505	}
506      } else if (arg->prompt)
507        printf("ppp: Pausing until %s finishes\n", arg->argv[arg->argn]);
508      execvp(argv[0], argv);
509    } else {
510      if (arg->prompt)
511        printf("ppp: Pausing until %s finishes\n", shell);
512      prompt_TtyOldMode(arg->prompt);
513      execl(shell, shell, NULL);
514    }
515
516    log_Printf(LogWARN, "exec() of %s failed: %s\n",
517              arg->argc > arg->argn ? arg->argv[arg->argn] : shell,
518              strerror(errno));
519    _exit(255);
520  }
521
522  if (shpid == (pid_t) - 1)
523    log_Printf(LogERROR, "Fork failed: %s\n", strerror(errno));
524  else {
525    int status;
526    waitpid(shpid, &status, 0);
527  }
528
529  if (arg->prompt && !arg->prompt->owner)
530    prompt_TtyCommandMode(arg->prompt);
531
532  return 0;
533}
534
535static int
536BgShellCommand(struct cmdargs const *arg)
537{
538  if (arg->argc == arg->argn)
539    return -1;
540  return ShellCommand(arg, 1);
541}
542
543static int
544FgShellCommand(struct cmdargs const *arg)
545{
546  return ShellCommand(arg, 0);
547}
548
549#ifndef NOALIAS
550static struct cmdtab const AliasCommands[] =
551{
552  {"addr", NULL, alias_RedirectAddr, LOCAL_AUTH,
553   "static address translation", "alias addr [addr_local addr_alias]"},
554  {"deny_incoming", NULL, AliasOption, LOCAL_AUTH,
555   "stop incoming connections", "alias deny_incoming [yes|no]",
556   (const void *) PKT_ALIAS_DENY_INCOMING},
557  {"enable", NULL, AliasEnable, LOCAL_AUTH,
558   "enable IP aliasing", "alias enable [yes|no]"},
559  {"log", NULL, AliasOption, LOCAL_AUTH,
560   "log aliasing link creation", "alias log [yes|no]",
561   (const void *) PKT_ALIAS_LOG},
562  {"port", NULL, alias_RedirectPort, LOCAL_AUTH, "port redirection",
563   "alias port proto localaddr:port[-port] aliasport[-aliasport]"},
564  {"pptp", NULL, alias_Pptp, LOCAL_AUTH,
565   "Set the PPTP address", "alias pptp IP"},
566  {"proxy", NULL, alias_ProxyRule, LOCAL_AUTH,
567   "proxy control", "alias proxy server host[:port] ..."},
568  {"same_ports", NULL, AliasOption, LOCAL_AUTH,
569   "try to leave port numbers unchanged", "alias same_ports [yes|no]",
570   (const void *) PKT_ALIAS_SAME_PORTS},
571  {"unregistered_only", NULL, AliasOption, LOCAL_AUTH,
572   "alias unregistered (private) IP address space only",
573   "alias unregistered_only [yes|no]",
574   (const void *) PKT_ALIAS_UNREGISTERED_ONLY},
575  {"use_sockets", NULL, AliasOption, LOCAL_AUTH,
576   "allocate host sockets", "alias use_sockets [yes|no]",
577   (const void *) PKT_ALIAS_USE_SOCKETS},
578  {"help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
579   "Display this message", "alias help|? [command]", AliasCommands},
580  {NULL, NULL, NULL},
581};
582#endif
583
584static struct cmdtab const AllowCommands[] = {
585  {"modes", "mode", AllowModes, LOCAL_AUTH,
586  "Only allow certain ppp modes", "allow modes mode..."},
587  {"users", "user", AllowUsers, LOCAL_AUTH,
588  "Only allow ppp access to certain users", "allow users logname..."},
589  {"help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
590  "Display this message", "allow help|? [command]", AllowCommands},
591  {NULL, NULL, NULL},
592};
593
594static struct cmdtab const IfaceCommands[] =
595{
596  {"add", NULL, IfaceAddCommand, LOCAL_AUTH,
597   "Add iface address", "iface add addr[/bits| mask] peer", NULL},
598  {NULL, "add!", IfaceAddCommand, LOCAL_AUTH,
599   "Add or change an iface address", "iface add! addr[/bits| mask] peer",
600   (void *)1},
601  {"clear", NULL, IfaceClearCommand, LOCAL_AUTH,
602   "Clear iface address(es)", "iface clear"},
603  {"delete", "rm", IfaceDeleteCommand, LOCAL_AUTH,
604   "Delete iface address", "iface delete addr", NULL},
605  {NULL, "rm!", IfaceDeleteCommand, LOCAL_AUTH,
606   "Delete iface address", "iface delete addr", (void *)1},
607  {NULL, "delete!", IfaceDeleteCommand, LOCAL_AUTH,
608   "Delete iface address", "iface delete addr", (void *)1},
609  {"show", NULL, iface_Show, LOCAL_AUTH,
610   "Show iface address(es)", "iface show"},
611  {"help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
612   "Display this message", "alias help|? [command]", IfaceCommands},
613  {NULL, NULL, NULL},
614};
615
616static struct cmdtab const Commands[] = {
617  {"accept", NULL, NegotiateCommand, LOCAL_AUTH | LOCAL_CX_OPT,
618  "accept option request", "accept option .."},
619  {"add", NULL, AddCommand, LOCAL_AUTH,
620  "add route", "add dest mask gateway", NULL},
621  {NULL, "add!", AddCommand, LOCAL_AUTH,
622  "add or change route", "add! dest mask gateway", (void *)1},
623#ifndef NOALIAS
624  {"alias", NULL, RunListCommand, LOCAL_AUTH,
625  "alias control", "alias option [yes|no]", AliasCommands},
626#endif
627  {"allow", "auth", RunListCommand, LOCAL_AUTH,
628  "Allow ppp access", "allow users|modes ....", AllowCommands},
629  {"bg", "!bg", BgShellCommand, LOCAL_AUTH,
630  "Run a background command", "[!]bg command"},
631  {"clear", NULL, ClearCommand, LOCAL_AUTH | LOCAL_CX_OPT,
632  "Clear throughput statistics",
633  "clear ipcp|physical [current|overall|peak]..."},
634  {"clone", NULL, CloneCommand, LOCAL_AUTH | LOCAL_CX,
635  "Clone a link", "clone newname..."},
636  {"close", NULL, CloseCommand, LOCAL_AUTH | LOCAL_CX_OPT,
637  "Close an FSM", "close [lcp|ccp]"},
638  {"delete", NULL, DeleteCommand, LOCAL_AUTH,
639  "delete route", "delete dest", NULL},
640  {NULL, "delete!", DeleteCommand, LOCAL_AUTH,
641  "delete a route if it exists", "delete! dest", (void *)1},
642  {"deny", NULL, NegotiateCommand, LOCAL_AUTH | LOCAL_CX_OPT,
643  "Deny option request", "deny option .."},
644  {"dial", "call", DialCommand, LOCAL_AUTH | LOCAL_CX_OPT,
645  "Dial and login", "dial|call [system ...]", NULL},
646  {"disable", NULL, NegotiateCommand, LOCAL_AUTH | LOCAL_CX_OPT,
647  "Disable option", "disable option .."},
648  {"down", NULL, DownCommand, LOCAL_AUTH | LOCAL_CX_OPT,
649  "Generate a down event", "down [ccp|lcp]"},
650  {"enable", NULL, NegotiateCommand, LOCAL_AUTH | LOCAL_CX_OPT,
651  "Enable option", "enable option .."},
652  {"iface", "interface", RunListCommand, LOCAL_AUTH,
653  "interface control", "iface option ...", IfaceCommands},
654  {"link", "datalink", LinkCommand, LOCAL_AUTH,
655  "Link specific commands", "link name command ..."},
656  {"load", NULL, LoadCommand, LOCAL_AUTH | LOCAL_CX_OPT,
657  "Load settings", "load [system ...]"},
658  {"open", NULL, OpenCommand, LOCAL_AUTH | LOCAL_CX_OPT,
659  "Open an FSM", "open! [lcp|ccp|ipcp]", (void *)1},
660  {"passwd", NULL, PasswdCommand, LOCAL_NO_AUTH,
661  "Password for manipulation", "passwd LocalPassword"},
662  {"quit", "bye", QuitCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
663  "Quit PPP program", "quit|bye [all]"},
664  {"remove", "rm", RemoveCommand, LOCAL_AUTH | LOCAL_CX,
665  "Remove a link", "remove"},
666  {"rename", "mv", RenameCommand, LOCAL_AUTH | LOCAL_CX,
667  "Rename a link", "rename name"},
668  {"save", NULL, SaveCommand, LOCAL_AUTH,
669  "Save settings", "save"},
670  {"set", "setup", SetCommand, LOCAL_AUTH | LOCAL_CX_OPT,
671  "Set parameters", "set[up] var value"},
672  {"shell", "!", FgShellCommand, LOCAL_AUTH,
673  "Run a subshell", "shell|! [sh command]"},
674  {"show", NULL, ShowCommand, LOCAL_AUTH | LOCAL_CX_OPT,
675  "Show status and stats", "show var"},
676  {"term", NULL, TerminalCommand, LOCAL_AUTH | LOCAL_CX,
677  "Enter terminal mode", "term"},
678  {"help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
679  "Display this message", "help|? [command]", Commands},
680  {NULL, NULL, NULL},
681};
682
683static int
684ShowEscape(struct cmdargs const *arg)
685{
686  if (arg->cx->physical->async.cfg.EscMap[32]) {
687    int code, bit;
688    const char *sep = "";
689
690    for (code = 0; code < 32; code++)
691      if (arg->cx->physical->async.cfg.EscMap[code])
692	for (bit = 0; bit < 8; bit++)
693	  if (arg->cx->physical->async.cfg.EscMap[code] & (1 << bit)) {
694	    prompt_Printf(arg->prompt, "%s0x%02x", sep, (code << 3) + bit);
695            sep = ", ";
696          }
697    prompt_Printf(arg->prompt, "\n");
698  }
699  return 0;
700}
701
702static int
703ShowTimerList(struct cmdargs const *arg)
704{
705  timer_Show(0, arg->prompt);
706  return 0;
707}
708
709static int
710ShowStopped(struct cmdargs const *arg)
711{
712  prompt_Printf(arg->prompt, " Stopped Timer:  LCP: ");
713  if (!arg->cx->physical->link.lcp.fsm.StoppedTimer.load)
714    prompt_Printf(arg->prompt, "Disabled");
715  else
716    prompt_Printf(arg->prompt, "%ld secs",
717                  arg->cx->physical->link.lcp.fsm.StoppedTimer.load / SECTICKS);
718
719  prompt_Printf(arg->prompt, ", CCP: ");
720  if (!arg->cx->physical->link.ccp.fsm.StoppedTimer.load)
721    prompt_Printf(arg->prompt, "Disabled");
722  else
723    prompt_Printf(arg->prompt, "%ld secs",
724                  arg->cx->physical->link.ccp.fsm.StoppedTimer.load / SECTICKS);
725
726  prompt_Printf(arg->prompt, "\n");
727
728  return 0;
729}
730
731static int
732ShowVersion(struct cmdargs const *arg)
733{
734  prompt_Printf(arg->prompt, "PPP Version %s - %s\n", Version, VersionDate);
735  return 0;
736}
737
738static int
739ShowProtocolStats(struct cmdargs const *arg)
740{
741  struct link *l = command_ChooseLink(arg);
742
743  prompt_Printf(arg->prompt, "%s:\n", l->name);
744  link_ReportProtocolStatus(l, arg->prompt);
745  return 0;
746}
747
748static struct cmdtab const ShowCommands[] = {
749  {"bundle", NULL, bundle_ShowStatus, LOCAL_AUTH,
750  "bundle details", "show bundle"},
751  {"ccp", NULL, ccp_ReportStatus, LOCAL_AUTH | LOCAL_CX_OPT,
752  "CCP status", "show cpp"},
753  {"compress", NULL, sl_Show, LOCAL_AUTH,
754  "VJ compression stats", "show compress"},
755  {"escape", NULL, ShowEscape, LOCAL_AUTH | LOCAL_CX,
756  "escape characters", "show escape"},
757  {"filter", NULL, filter_Show, LOCAL_AUTH,
758  "packet filters", "show filter [in|out|dial|alive]"},
759  {"hdlc", NULL, hdlc_ReportStatus, LOCAL_AUTH | LOCAL_CX,
760  "HDLC errors", "show hdlc"},
761  {"iface", "interface", iface_Show, LOCAL_AUTH,
762  "Interface status", "show iface"},
763  {"ipcp", NULL, ipcp_Show, LOCAL_AUTH,
764  "IPCP status", "show ipcp"},
765  {"layers", NULL, link_ShowLayers, LOCAL_AUTH | LOCAL_CX_OPT,
766  "Protocol layers", "show layers"},
767  {"lcp", NULL, lcp_ReportStatus, LOCAL_AUTH | LOCAL_CX,
768  "LCP status", "show lcp"},
769  {"link", "datalink", datalink_Show, LOCAL_AUTH | LOCAL_CX,
770  "(high-level) link info", "show link"},
771  {"links", NULL, bundle_ShowLinks, LOCAL_AUTH,
772  "available link names", "show links"},
773  {"log", NULL, log_ShowLevel, LOCAL_AUTH,
774  "log levels", "show log"},
775  {"mem", NULL, mbuf_Show, LOCAL_AUTH,
776  "mbuf allocations", "show mem"},
777  {"physical", NULL, physical_ShowStatus, LOCAL_AUTH | LOCAL_CX,
778  "(low-level) link info", "show physical"},
779  {"mp", "multilink", mp_ShowStatus, LOCAL_AUTH,
780  "multilink setup", "show mp"},
781  {"proto", NULL, ShowProtocolStats, LOCAL_AUTH | LOCAL_CX_OPT,
782  "protocol summary", "show proto"},
783  {"route", NULL, route_Show, LOCAL_AUTH,
784  "routing table", "show route"},
785  {"stopped", NULL, ShowStopped, LOCAL_AUTH | LOCAL_CX,
786  "STOPPED timeout", "show stopped"},
787  {"timers", NULL, ShowTimerList, LOCAL_AUTH,
788  "alarm timers", "show timers"},
789  {"version", NULL, ShowVersion, LOCAL_NO_AUTH | LOCAL_AUTH,
790  "version string", "show version"},
791  {"who", NULL, log_ShowWho, LOCAL_AUTH,
792  "client list", "show who"},
793  {"help", "?", HelpCommand, LOCAL_NO_AUTH | LOCAL_AUTH,
794  "Display this message", "show help|? [command]", ShowCommands},
795  {NULL, NULL, NULL},
796};
797
798static struct cmdtab const *
799FindCommand(struct cmdtab const *cmds, const char *str, int *pmatch)
800{
801  int nmatch;
802  int len;
803  struct cmdtab const *found;
804
805  found = NULL;
806  len = strlen(str);
807  nmatch = 0;
808  while (cmds->func) {
809    if (cmds->name && strncasecmp(str, cmds->name, len) == 0) {
810      if (cmds->name[len] == '\0') {
811	*pmatch = 1;
812	return cmds;
813      }
814      nmatch++;
815      found = cmds;
816    } else if (cmds->alias && strncasecmp(str, cmds->alias, len) == 0) {
817      if (cmds->alias[len] == '\0') {
818	*pmatch = 1;
819	return cmds;
820      }
821      nmatch++;
822      found = cmds;
823    }
824    cmds++;
825  }
826  *pmatch = nmatch;
827  return found;
828}
829
830static const char *
831mkPrefix(int argc, char const *const *argv, char *tgt, int sz)
832{
833  int f, tlen, len;
834
835  tlen = 0;
836  for (f = 0; f < argc && tlen < sz - 2; f++) {
837    if (f)
838      tgt[tlen++] = ' ';
839    len = strlen(argv[f]);
840    if (len > sz - tlen - 1)
841      len = sz - tlen - 1;
842    strncpy(tgt+tlen, argv[f], len);
843    tlen += len;
844  }
845  tgt[tlen] = '\0';
846  return tgt;
847}
848
849static int
850FindExec(struct bundle *bundle, struct cmdtab const *cmds, int argc, int argn,
851         char const *const *argv, struct prompt *prompt, struct datalink *cx)
852{
853  struct cmdtab const *cmd;
854  int val = 1;
855  int nmatch;
856  struct cmdargs arg;
857  char prefix[100];
858
859  cmd = FindCommand(cmds, argv[argn], &nmatch);
860  if (nmatch > 1)
861    log_Printf(LogWARN, "%s: Ambiguous command\n",
862              mkPrefix(argn+1, argv, prefix, sizeof prefix));
863  else if (cmd && (!prompt || (cmd->lauth & prompt->auth))) {
864    if ((cmd->lauth & LOCAL_CX) && !cx)
865      /* We've got no context, but we require it */
866      cx = bundle2datalink(bundle, NULL);
867
868    if ((cmd->lauth & LOCAL_CX) && !cx)
869      log_Printf(LogWARN, "%s: No context (use the `link' command)\n",
870                mkPrefix(argn+1, argv, prefix, sizeof prefix));
871    else {
872      if (cx && !(cmd->lauth & (LOCAL_CX|LOCAL_CX_OPT))) {
873        log_Printf(LogWARN, "%s: Redundant context (%s) ignored\n",
874                  mkPrefix(argn+1, argv, prefix, sizeof prefix), cx->name);
875        cx = NULL;
876      }
877      arg.cmdtab = cmds;
878      arg.cmd = cmd;
879      arg.argc = argc;
880      arg.argn = argn+1;
881      arg.argv = argv;
882      arg.bundle = bundle;
883      arg.cx = cx;
884      arg.prompt = prompt;
885      val = (*cmd->func) (&arg);
886    }
887  } else
888    log_Printf(LogWARN, "%s: Invalid command\n",
889              mkPrefix(argn+1, argv, prefix, sizeof prefix));
890
891  if (val == -1)
892    log_Printf(LogWARN, "Usage: %s\n", cmd->syntax);
893  else if (val)
894    log_Printf(LogWARN, "%s: Failed %d\n",
895              mkPrefix(argn+1, argv, prefix, sizeof prefix), val);
896
897  return val;
898}
899
900int
901command_Interpret(char *buff, int nb, char *argv[MAXARGS])
902{
903  char *cp;
904
905  if (nb > 0) {
906    cp = buff + strcspn(buff, "\r\n");
907    if (cp)
908      *cp = '\0';
909    return MakeArgs(buff, argv, MAXARGS);
910  }
911  return 0;
912}
913
914static int
915arghidden(int argc, char const *const *argv, int n)
916{
917  /* Is arg n of the given command to be hidden from the log ? */
918
919  /* set authkey xxxxx */
920  /* set key xxxxx */
921  if (n == 2 && !strncasecmp(argv[0], "se", 2) &&
922      (!strncasecmp(argv[1], "authk", 5) || !strncasecmp(argv[1], "ke", 2)))
923    return 1;
924
925  /* passwd xxxxx */
926  if (n == 1 && !strncasecmp(argv[0], "p", 1))
927    return 1;
928
929  /* set server port xxxxx .... */
930  if (n == 3 && !strncasecmp(argv[0], "se", 2) &&
931      !strncasecmp(argv[1], "se", 2))
932    return 1;
933
934  return 0;
935}
936
937void
938command_Run(struct bundle *bundle, int argc, char const *const *argv,
939           struct prompt *prompt, const char *label, struct datalink *cx)
940{
941  if (argc > 0) {
942    if (log_IsKept(LogCOMMAND)) {
943      char buf[LINE_LEN];
944      int f, n;
945
946      if (label) {
947        strncpy(buf, label, sizeof buf - 3);
948        buf[sizeof buf - 3] = '\0';
949        strcat(buf, ": ");
950        n = strlen(buf);
951      } else {
952        *buf = '\0';
953        n = 0;
954      }
955      buf[sizeof buf - 1] = '\0';	/* In case we run out of room in buf */
956
957      for (f = 0; f < argc; f++) {
958        if (n < sizeof buf - 1 && f)
959          buf[n++] = ' ';
960        if (arghidden(argc, argv, f))
961          strncpy(buf+n, "********", sizeof buf - n - 1);
962        else
963          strncpy(buf+n, argv[f], sizeof buf - n - 1);
964        n += strlen(buf+n);
965      }
966      log_Printf(LogCOMMAND, "%s\n", buf);
967    }
968    FindExec(bundle, Commands, argc, 0, argv, prompt, cx);
969  }
970}
971
972void
973command_Decode(struct bundle *bundle, char *buff, int nb, struct prompt *prompt,
974              const char *label)
975{
976  int argc;
977  char *argv[MAXARGS];
978
979  argc = command_Interpret(buff, nb, argv);
980  command_Run(bundle, argc, (char const *const *)argv, prompt, label, NULL);
981}
982
983static int
984ShowCommand(struct cmdargs const *arg)
985{
986  if (!arg->prompt)
987    log_Printf(LogWARN, "show: Cannot show without a prompt\n");
988  else if (arg->argc > arg->argn)
989    FindExec(arg->bundle, ShowCommands, arg->argc, arg->argn, arg->argv,
990             arg->prompt, arg->cx);
991  else
992    prompt_Printf(arg->prompt, "Use ``show ?'' to get a list.\n");
993
994  return 0;
995}
996
997static int
998TerminalCommand(struct cmdargs const *arg)
999{
1000  if (!arg->prompt) {
1001    log_Printf(LogWARN, "term: Need a prompt\n");
1002    return 1;
1003  }
1004
1005  if (arg->cx->physical->link.lcp.fsm.state > ST_CLOSED) {
1006    prompt_Printf(arg->prompt, "LCP state is [%s]\n",
1007                  State2Nam(arg->cx->physical->link.lcp.fsm.state));
1008    return 1;
1009  }
1010
1011  datalink_Up(arg->cx, 0, 0);
1012  prompt_TtyTermMode(arg->prompt, arg->cx);
1013  return 0;
1014}
1015
1016static int
1017QuitCommand(struct cmdargs const *arg)
1018{
1019  if (!arg->prompt || prompt_IsController(arg->prompt) ||
1020      (arg->argc > arg->argn && !strcasecmp(arg->argv[arg->argn], "all") &&
1021       (arg->prompt->auth & LOCAL_AUTH)))
1022    Cleanup(EX_NORMAL);
1023  if (arg->prompt)
1024    prompt_Destroy(arg->prompt, 1);
1025
1026  return 0;
1027}
1028
1029static int
1030OpenCommand(struct cmdargs const *arg)
1031{
1032  if (arg->argc == arg->argn)
1033    bundle_Open(arg->bundle, arg->cx ? arg->cx->name : NULL, PHYS_ALL, 1);
1034  else if (arg->argc == arg->argn + 1) {
1035    if (!strcasecmp(arg->argv[arg->argn], "lcp")) {
1036      struct datalink *cx = arg->cx ?
1037        arg->cx : bundle2datalink(arg->bundle, NULL);
1038      if (cx) {
1039        if (cx->physical->link.lcp.fsm.state == ST_OPENED)
1040          fsm_Reopen(&cx->physical->link.lcp.fsm);
1041        else
1042          bundle_Open(arg->bundle, cx->name, PHYS_ALL, 1);
1043      } else
1044        log_Printf(LogWARN, "open lcp: You must specify a link\n");
1045    } else if (!strcasecmp(arg->argv[arg->argn], "ccp")) {
1046      struct fsm *fp;
1047
1048      fp = &command_ChooseLink(arg)->ccp.fsm;
1049      if (fp->link->lcp.fsm.state != ST_OPENED)
1050        log_Printf(LogWARN, "open: LCP must be open before opening CCP\n");
1051      else if (fp->state == ST_OPENED)
1052        fsm_Reopen(fp);
1053      else {
1054        fp->open_mode = 0;	/* Not passive any more */
1055        if (fp->state == ST_STOPPED) {
1056          fsm_Down(fp);
1057          fsm_Up(fp);
1058        } else {
1059          fsm_Up(fp);
1060          fsm_Open(fp);
1061        }
1062      }
1063    } else if (!strcasecmp(arg->argv[arg->argn], "ipcp")) {
1064      if (arg->cx)
1065        log_Printf(LogWARN, "open ipcp: You need not specify a link\n");
1066      if (arg->bundle->ncp.ipcp.fsm.state == ST_OPENED)
1067        fsm_Reopen(&arg->bundle->ncp.ipcp.fsm);
1068      else
1069        bundle_Open(arg->bundle, NULL, PHYS_ALL, 1);
1070    } else
1071      return -1;
1072  } else
1073    return -1;
1074
1075  return 0;
1076}
1077
1078static int
1079CloseCommand(struct cmdargs const *arg)
1080{
1081  if (arg->argc == arg->argn)
1082    bundle_Close(arg->bundle, arg->cx ? arg->cx->name : NULL, CLOSE_STAYDOWN);
1083  else if (arg->argc == arg->argn + 1) {
1084    if (!strcasecmp(arg->argv[arg->argn], "lcp"))
1085      bundle_Close(arg->bundle, arg->cx ? arg->cx->name : NULL, CLOSE_LCP);
1086    else if (!strcasecmp(arg->argv[arg->argn], "ccp") ||
1087             !strcasecmp(arg->argv[arg->argn], "ccp!")) {
1088      struct fsm *fp;
1089
1090      fp = &command_ChooseLink(arg)->ccp.fsm;
1091      if (fp->state == ST_OPENED) {
1092        fsm_Close(fp);
1093        if (arg->argv[arg->argn][3] == '!')
1094          fp->open_mode = 0;		/* Stay ST_CLOSED */
1095        else
1096          fp->open_mode = OPEN_PASSIVE;	/* Wait for the peer to start */
1097      }
1098    } else
1099      return -1;
1100  } else
1101    return -1;
1102
1103  return 0;
1104}
1105
1106static int
1107DownCommand(struct cmdargs const *arg)
1108{
1109  if (arg->argc == arg->argn) {
1110      if (arg->cx)
1111        datalink_Down(arg->cx, CLOSE_STAYDOWN);
1112      else
1113        bundle_Down(arg->bundle, CLOSE_STAYDOWN);
1114  } else if (arg->argc == arg->argn + 1) {
1115    if (!strcasecmp(arg->argv[arg->argn], "lcp")) {
1116      if (arg->cx)
1117        datalink_Down(arg->cx, CLOSE_LCP);
1118      else
1119        bundle_Down(arg->bundle, CLOSE_LCP);
1120    } else if (!strcasecmp(arg->argv[arg->argn], "ccp")) {
1121      struct fsm *fp = arg->cx ? &arg->cx->physical->link.ccp.fsm :
1122                                 &arg->bundle->ncp.mp.link.ccp.fsm;
1123      fsm2initial(fp);
1124    } else
1125      return -1;
1126  } else
1127    return -1;
1128
1129  return 0;
1130}
1131
1132static int
1133SetModemSpeed(struct cmdargs const *arg)
1134{
1135  long speed;
1136  char *end;
1137
1138  if (arg->argc > arg->argn && *arg->argv[arg->argn]) {
1139    if (arg->argc > arg->argn+1) {
1140      log_Printf(LogWARN, "SetModemSpeed: Too many arguments");
1141      return -1;
1142    }
1143    if (strcasecmp(arg->argv[arg->argn], "sync") == 0) {
1144      physical_SetSync(arg->cx->physical);
1145      return 0;
1146    }
1147    end = NULL;
1148    speed = strtol(arg->argv[arg->argn], &end, 10);
1149    if (*end) {
1150      log_Printf(LogWARN, "SetModemSpeed: Bad argument \"%s\"",
1151                arg->argv[arg->argn]);
1152      return -1;
1153    }
1154    if (physical_SetSpeed(arg->cx->physical, speed))
1155      return 0;
1156    log_Printf(LogWARN, "%s: Invalid speed\n", arg->argv[arg->argn]);
1157  } else
1158    log_Printf(LogWARN, "SetModemSpeed: No speed specified\n");
1159
1160  return -1;
1161}
1162
1163static int
1164SetStoppedTimeout(struct cmdargs const *arg)
1165{
1166  struct link *l = &arg->cx->physical->link;
1167
1168  l->lcp.fsm.StoppedTimer.load = 0;
1169  l->ccp.fsm.StoppedTimer.load = 0;
1170  if (arg->argc <= arg->argn+2) {
1171    if (arg->argc > arg->argn) {
1172      l->lcp.fsm.StoppedTimer.load = atoi(arg->argv[arg->argn]) * SECTICKS;
1173      if (arg->argc > arg->argn+1)
1174        l->ccp.fsm.StoppedTimer.load = atoi(arg->argv[arg->argn+1]) * SECTICKS;
1175    }
1176    return 0;
1177  }
1178  return -1;
1179}
1180
1181#define ismask(x) \
1182  (*x == '0' && strlen(x) == 4 && strspn(x+1, "0123456789.") == 3)
1183
1184static int
1185SetServer(struct cmdargs const *arg)
1186{
1187  int res = -1;
1188
1189  if (arg->argc > arg->argn && arg->argc < arg->argn+4) {
1190    const char *port, *passwd, *mask;
1191
1192    /* What's what ? */
1193    port = arg->argv[arg->argn];
1194    if (arg->argc == arg->argn + 2) {
1195      passwd = arg->argv[arg->argn+1];
1196      mask = NULL;
1197    } else if (arg->argc == arg->argn + 3) {
1198      passwd = arg->argv[arg->argn+1];
1199      mask = arg->argv[arg->argn+2];
1200      if (!ismask(mask))
1201        return -1;
1202    } else if (strcasecmp(port, "none") == 0) {
1203      if (server_Close(arg->bundle))
1204        log_Printf(LogPHASE, "Disabled server port.\n");
1205      return 0;
1206    } else
1207      return -1;
1208
1209    strncpy(server.passwd, passwd, sizeof server.passwd - 1);
1210    server.passwd[sizeof server.passwd - 1] = '\0';
1211
1212    if (*port == '/') {
1213      mode_t imask;
1214      char *ptr, name[LINE_LEN + 12];
1215
1216      if (mask != NULL) {
1217	unsigned m;
1218
1219	if (sscanf(mask, "%o", &m) == 1)
1220	  imask = m;
1221        else
1222          return -1;
1223      } else
1224        imask = (mode_t)-1;
1225
1226      ptr = strstr(port, "%d");
1227      if (ptr) {
1228        snprintf(name, sizeof name, "%.*s%d%s",
1229                 (int)(ptr - port), port, arg->bundle->unit, ptr + 2);
1230        port = name;
1231      }
1232      res = server_LocalOpen(arg->bundle, port, imask);
1233    } else {
1234      int iport, add = 0;
1235
1236      if (mask != NULL)
1237        return -1;
1238
1239      if (*port == '+') {
1240        port++;
1241        add = 1;
1242      }
1243      if (strspn(port, "0123456789") != strlen(port)) {
1244        struct servent *s;
1245
1246        if ((s = getservbyname(port, "tcp")) == NULL) {
1247	  iport = 0;
1248	  log_Printf(LogWARN, "%s: Invalid port or service\n", port);
1249	} else
1250	  iport = ntohs(s->s_port);
1251      } else
1252        iport = atoi(port);
1253
1254      if (iport) {
1255        if (add)
1256          iport += arg->bundle->unit;
1257        res = server_TcpOpen(arg->bundle, iport);
1258      } else
1259        res = -1;
1260    }
1261  }
1262
1263  return res;
1264}
1265
1266static int
1267SetEscape(struct cmdargs const *arg)
1268{
1269  int code;
1270  int argc = arg->argc - arg->argn;
1271  char const *const *argv = arg->argv + arg->argn;
1272
1273  for (code = 0; code < 33; code++)
1274    arg->cx->physical->async.cfg.EscMap[code] = 0;
1275
1276  while (argc-- > 0) {
1277    sscanf(*argv++, "%x", &code);
1278    code &= 0xff;
1279    arg->cx->physical->async.cfg.EscMap[code >> 3] |= (1 << (code & 7));
1280    arg->cx->physical->async.cfg.EscMap[32] = 1;
1281  }
1282  return 0;
1283}
1284
1285static int
1286SetInterfaceAddr(struct cmdargs const *arg)
1287{
1288  struct ipcp *ipcp = &arg->bundle->ncp.ipcp;
1289  const char *hisaddr;
1290
1291  if (arg->argc > arg->argn + 4)
1292    return -1;
1293
1294  hisaddr = NULL;
1295  memset(&ipcp->cfg.my_range, '\0', sizeof ipcp->cfg.my_range);
1296  memset(&ipcp->cfg.peer_range, '\0', sizeof ipcp->cfg.peer_range);
1297  ipcp->cfg.HaveTriggerAddress = 0;
1298  ipcp->cfg.netmask.s_addr = INADDR_ANY;
1299  iplist_reset(&ipcp->cfg.peer_list);
1300
1301  if (arg->argc > arg->argn) {
1302    if (!ParseAddr(ipcp, arg->argv[arg->argn],
1303                   &ipcp->cfg.my_range.ipaddr, &ipcp->cfg.my_range.mask,
1304                   &ipcp->cfg.my_range.width))
1305      return 1;
1306    if (arg->argc > arg->argn+1) {
1307      hisaddr = arg->argv[arg->argn+1];
1308      if (arg->argc > arg->argn+2) {
1309        ipcp->ifmask = ipcp->cfg.netmask = GetIpAddr(arg->argv[arg->argn+2]);
1310	if (arg->argc > arg->argn+3) {
1311	  ipcp->cfg.TriggerAddress = GetIpAddr(arg->argv[arg->argn+3]);
1312	  ipcp->cfg.HaveTriggerAddress = 1;
1313	}
1314      }
1315    }
1316  }
1317
1318  /* 0.0.0.0 means any address (0 bits) */
1319  if (ipcp->cfg.my_range.ipaddr.s_addr == INADDR_ANY) {
1320    ipcp->cfg.my_range.mask.s_addr = INADDR_ANY;
1321    ipcp->cfg.my_range.width = 0;
1322  }
1323  ipcp->my_ip.s_addr = ipcp->cfg.my_range.ipaddr.s_addr;
1324  bundle_AdjustFilters(arg->bundle, &ipcp->my_ip, NULL);
1325
1326  if (hisaddr && !ipcp_UseHisaddr(arg->bundle, hisaddr,
1327                                  arg->bundle->phys_type.all & PHYS_AUTO))
1328    return 4;
1329
1330  return 0;
1331}
1332
1333static int
1334SetRetry(int argc, char const *const *argv, u_int *timeout, u_int *maxreq,
1335          u_int *maxtrm, int def)
1336{
1337  if (argc == 0) {
1338    *timeout = DEF_FSMRETRY;
1339    *maxreq = def;
1340    if (maxtrm != NULL)
1341      *maxtrm = def;
1342  } else {
1343    long l = atol(argv[0]);
1344
1345    if (l < MIN_FSMRETRY) {
1346      log_Printf(LogWARN, "%ld: Invalid FSM retry period - min %d\n",
1347                 l, MIN_FSMRETRY);
1348      return 1;
1349    } else
1350      *timeout = l;
1351
1352    if (argc > 1) {
1353      l = atol(argv[1]);
1354      if (l < 1) {
1355        log_Printf(LogWARN, "%ld: Invalid FSM REQ tries - changed to 1\n", l);
1356        l = 1;
1357      }
1358      *maxreq = l;
1359
1360      if (argc > 2 && maxtrm != NULL) {
1361        l = atol(argv[2]);
1362        if (l < 1) {
1363          log_Printf(LogWARN, "%ld: Invalid FSM TRM tries - changed to 1\n", l);
1364          l = 1;
1365        }
1366        *maxtrm = l;
1367      }
1368    }
1369  }
1370
1371  return 0;
1372}
1373
1374static int
1375SetVariable(struct cmdargs const *arg)
1376{
1377  long long_val, param = (long)arg->cmd->args;
1378  int mode, dummyint;
1379  const char *argp;
1380  struct datalink *cx = arg->cx;	/* LOCAL_CX uses this */
1381  const char *err = NULL;
1382  struct link *l = command_ChooseLink(arg);	/* LOCAL_CX_OPT uses this */
1383  struct in_addr dummyaddr, *addr;
1384
1385  if (arg->argc > arg->argn)
1386    argp = arg->argv[arg->argn];
1387  else
1388    argp = "";
1389
1390  if ((arg->cmd->lauth & LOCAL_CX) && !cx) {
1391    log_Printf(LogWARN, "set %s: No context (use the `link' command)\n",
1392              arg->cmd->name);
1393    return 1;
1394  } else if (cx && !(arg->cmd->lauth & (LOCAL_CX|LOCAL_CX_OPT))) {
1395    log_Printf(LogWARN, "set %s: Redundant context (%s) ignored\n",
1396              arg->cmd->name, cx->name);
1397    cx = NULL;
1398  }
1399
1400  switch (param) {
1401  case VAR_AUTHKEY:
1402    switch (bundle_Phase(arg->bundle)) {
1403      case PHASE_DEAD:
1404      case PHASE_ESTABLISH:
1405        strncpy(arg->bundle->cfg.auth.key, argp,
1406                sizeof arg->bundle->cfg.auth.key - 1);
1407        arg->bundle->cfg.auth.key[sizeof arg->bundle->cfg.auth.key - 1] = '\0';
1408        break;
1409      default:
1410        err = "set authkey: Only available at phase DEAD/ESTABLISH\n";
1411        log_Printf(LogWARN, err);
1412        break;
1413    }
1414    break;
1415
1416  case VAR_AUTHNAME:
1417    switch (bundle_Phase(arg->bundle)) {
1418      case PHASE_DEAD:
1419      case PHASE_ESTABLISH:
1420        strncpy(arg->bundle->cfg.auth.name, argp,
1421                sizeof arg->bundle->cfg.auth.name - 1);
1422        arg->bundle->cfg.auth.name[sizeof arg->bundle->cfg.auth.name-1] = '\0';
1423        break;
1424      default:
1425        err = "set authname: Only available at phase DEAD/ESTABLISH\n";
1426        log_Printf(LogWARN, err);
1427        break;
1428    }
1429    break;
1430
1431  case VAR_AUTOLOAD:
1432    if (arg->argc == arg->argn + 3) {
1433      int v1, v2, v3;
1434      char *end;
1435
1436      v1 = strtol(arg->argv[arg->argn], &end, 0);
1437      if (v1 < 0 || *end) {
1438        log_Printf(LogWARN, "autoload: %s: Invalid min percentage\n",
1439                   arg->argv[arg->argn]);
1440        return 1;
1441      }
1442
1443      v2 = strtol(arg->argv[arg->argn + 1], &end, 0);
1444      if (v2 < 0 || *end) {
1445        log_Printf(LogWARN, "autoload: %s: Invalid max percentage\n",
1446                   arg->argv[arg->argn + 1]);
1447        return 1;
1448      }
1449      if (v2 < v1) {
1450        v3 = v1;
1451        v1 = v2;
1452        v2 = v3;
1453      }
1454
1455      v3 = strtol(arg->argv[arg->argn + 2], &end, 0);
1456      if (v3 <= 0 || *end) {
1457        log_Printf(LogWARN, "autoload: %s: Invalid throughput period\n",
1458                   arg->argv[arg->argn + 2]);
1459        return 1;
1460      }
1461
1462      arg->bundle->ncp.mp.cfg.autoload.min = v1;
1463      arg->bundle->ncp.mp.cfg.autoload.max = v2;
1464      arg->bundle->ncp.mp.cfg.autoload.period = v3;
1465      mp_RestartAutoloadTimer(&arg->bundle->ncp.mp);
1466    } else {
1467      err = "Set autoload requires three arguments\n";
1468      log_Printf(LogWARN, err);
1469    }
1470    break;
1471
1472  case VAR_DIAL:
1473    strncpy(cx->cfg.script.dial, argp, sizeof cx->cfg.script.dial - 1);
1474    cx->cfg.script.dial[sizeof cx->cfg.script.dial - 1] = '\0';
1475    break;
1476
1477  case VAR_LOGIN:
1478    strncpy(cx->cfg.script.login, argp, sizeof cx->cfg.script.login - 1);
1479    cx->cfg.script.login[sizeof cx->cfg.script.login - 1] = '\0';
1480    break;
1481
1482  case VAR_WINSIZE:
1483    if (arg->argc > arg->argn) {
1484      l->ccp.cfg.deflate.out.winsize = atoi(arg->argv[arg->argn]);
1485      if (l->ccp.cfg.deflate.out.winsize < 8 ||
1486          l->ccp.cfg.deflate.out.winsize > 15) {
1487          log_Printf(LogWARN, "%d: Invalid outgoing window size\n",
1488                    l->ccp.cfg.deflate.out.winsize);
1489          l->ccp.cfg.deflate.out.winsize = 15;
1490      }
1491      if (arg->argc > arg->argn+1) {
1492        l->ccp.cfg.deflate.in.winsize = atoi(arg->argv[arg->argn+1]);
1493        if (l->ccp.cfg.deflate.in.winsize < 8 ||
1494            l->ccp.cfg.deflate.in.winsize > 15) {
1495            log_Printf(LogWARN, "%d: Invalid incoming window size\n",
1496                      l->ccp.cfg.deflate.in.winsize);
1497            l->ccp.cfg.deflate.in.winsize = 15;
1498        }
1499      } else
1500        l->ccp.cfg.deflate.in.winsize = 0;
1501    } else {
1502      err = "No window size specified\n";
1503      log_Printf(LogWARN, err);
1504    }
1505    break;
1506
1507  case VAR_DEVICE:
1508    physical_SetDeviceList(cx->physical, arg->argc - arg->argn,
1509                           arg->argv + arg->argn);
1510    break;
1511
1512  case VAR_ACCMAP:
1513    if (arg->argc > arg->argn) {
1514      u_long ulong_val;
1515      sscanf(argp, "%lx", &ulong_val);
1516      cx->physical->link.lcp.cfg.accmap = (u_int32_t)ulong_val;
1517    } else {
1518      err = "No accmap specified\n";
1519      log_Printf(LogWARN, err);
1520    }
1521    break;
1522
1523  case VAR_MODE:
1524    mode = Nam2mode(argp);
1525    if (mode == PHYS_NONE || mode == PHYS_ALL) {
1526      log_Printf(LogWARN, "%s: Invalid mode\n", argp);
1527      return -1;
1528    }
1529    bundle_SetMode(arg->bundle, cx, mode);
1530    break;
1531
1532  case VAR_MRRU:
1533    switch (bundle_Phase(arg->bundle)) {
1534      case PHASE_DEAD:
1535        break;
1536      case PHASE_ESTABLISH:
1537        /* Make sure none of our links are DATALINK_LCP or greater */
1538        if (bundle_HighestState(arg->bundle) >= DATALINK_LCP) {
1539          log_Printf(LogWARN, "mrru: Only changable before LCP negotiations\n");
1540          return 1;
1541        }
1542        break;
1543      default:
1544        log_Printf(LogWARN, "mrru: Only changable at phase DEAD/ESTABLISH\n");
1545        return 1;
1546    }
1547    long_val = atol(argp);
1548    if (long_val && long_val < MIN_MRU) {
1549      log_Printf(LogWARN, "MRRU %ld: too small - min %d\n", long_val, MIN_MRU);
1550      return 1;
1551    } else if (long_val > MAX_MRU) {
1552      log_Printf(LogWARN, "MRRU %ld: too big - max %d\n", long_val, MAX_MRU);
1553      return 1;
1554    } else
1555      arg->bundle->ncp.mp.cfg.mrru = long_val;
1556    break;
1557
1558  case VAR_MRU:
1559    long_val = atol(argp);
1560    if (long_val == 0)
1561      l->lcp.cfg.mru = DEF_MRU;
1562    else if (long_val < MIN_MRU) {
1563      log_Printf(LogWARN, "MRU %ld: too small - min %d\n", long_val, MIN_MRU);
1564      return 1;
1565    } else if (long_val > MAX_MRU) {
1566      log_Printf(LogWARN, "MRU %ld: too big - max %d\n", long_val, MAX_MRU);
1567      return 1;
1568    } else
1569      l->lcp.cfg.mru = long_val;
1570    break;
1571
1572  case VAR_MTU:
1573    long_val = atol(argp);
1574    if (long_val && long_val < MIN_MTU) {
1575      log_Printf(LogWARN, "MTU %ld: too small - min %d\n", long_val, MIN_MTU);
1576      return 1;
1577    } else if (long_val > MAX_MTU) {
1578      log_Printf(LogWARN, "MTU %ld: too big - max %d\n", long_val, MAX_MTU);
1579      return 1;
1580    } else
1581      arg->bundle->cfg.mtu = long_val;
1582    break;
1583
1584  case VAR_OPENMODE:
1585    if (strcasecmp(argp, "active") == 0)
1586      cx->physical->link.lcp.cfg.openmode = arg->argc > arg->argn+1 ?
1587        atoi(arg->argv[arg->argn+1]) : 1;
1588    else if (strcasecmp(argp, "passive") == 0)
1589      cx->physical->link.lcp.cfg.openmode = OPEN_PASSIVE;
1590    else {
1591      err = "%s: Invalid openmode\n";
1592      log_Printf(LogWARN, err, argp);
1593    }
1594    break;
1595
1596  case VAR_PHONE:
1597    strncpy(cx->cfg.phone.list, argp, sizeof cx->cfg.phone.list - 1);
1598    cx->cfg.phone.list[sizeof cx->cfg.phone.list - 1] = '\0';
1599    cx->phone.alt = cx->phone.next = NULL;
1600    break;
1601
1602  case VAR_HANGUP:
1603    strncpy(cx->cfg.script.hangup, argp, sizeof cx->cfg.script.hangup - 1);
1604    cx->cfg.script.hangup[sizeof cx->cfg.script.hangup - 1] = '\0';
1605    break;
1606
1607  case VAR_IDLETIMEOUT:
1608    if (arg->argc > arg->argn+1)
1609      err = "Too many idle timeout values\n";
1610    else if (arg->argc == arg->argn+1)
1611      bundle_SetIdleTimer(arg->bundle, atoi(argp));
1612    if (err)
1613      log_Printf(LogWARN, err);
1614    break;
1615
1616  case VAR_LQRPERIOD:
1617    long_val = atol(argp);
1618    if (long_val < MIN_LQRPERIOD) {
1619      log_Printf(LogWARN, "%ld: Invalid lqr period - min %d\n",
1620                 long_val, MIN_LQRPERIOD);
1621      return 1;
1622    } else
1623      l->lcp.cfg.lqrperiod = long_val;
1624    break;
1625
1626  case VAR_LCPRETRY:
1627    return SetRetry(arg->argc - arg->argn, arg->argv + arg->argn,
1628                    &cx->physical->link.lcp.cfg.fsm.timeout,
1629                    &cx->physical->link.lcp.cfg.fsm.maxreq,
1630                    &cx->physical->link.lcp.cfg.fsm.maxtrm, DEF_FSMTRIES);
1631    break;
1632
1633  case VAR_CHAPRETRY:
1634    return SetRetry(arg->argc - arg->argn, arg->argv + arg->argn,
1635                    &cx->chap.auth.cfg.fsm.timeout,
1636                    &cx->chap.auth.cfg.fsm.maxreq, NULL, DEF_FSMAUTHTRIES);
1637    break;
1638
1639  case VAR_PAPRETRY:
1640    return SetRetry(arg->argc - arg->argn, arg->argv + arg->argn,
1641                    &cx->pap.cfg.fsm.timeout, &cx->pap.cfg.fsm.maxreq,
1642                    NULL, DEF_FSMAUTHTRIES);
1643    break;
1644
1645  case VAR_CCPRETRY:
1646    return SetRetry(arg->argc - arg->argn, arg->argv + arg->argn,
1647                    &l->ccp.cfg.fsm.timeout, &l->ccp.cfg.fsm.maxreq,
1648                    &l->ccp.cfg.fsm.maxtrm, DEF_FSMTRIES);
1649    break;
1650
1651  case VAR_IPCPRETRY:
1652    return SetRetry(arg->argc - arg->argn, arg->argv + arg->argn,
1653                    &arg->bundle->ncp.ipcp.cfg.fsm.timeout,
1654                    &arg->bundle->ncp.ipcp.cfg.fsm.maxreq,
1655                    &arg->bundle->ncp.ipcp.cfg.fsm.maxtrm, DEF_FSMTRIES);
1656    break;
1657
1658  case VAR_NBNS:
1659  case VAR_DNS:
1660    if (param == VAR_DNS)
1661      addr = arg->bundle->ncp.ipcp.cfg.ns.dns;
1662    else
1663      addr = arg->bundle->ncp.ipcp.cfg.ns.nbns;
1664
1665    addr[0].s_addr = addr[1].s_addr = INADDR_ANY;
1666
1667    if (arg->argc > arg->argn) {
1668      ParseAddr(&arg->bundle->ncp.ipcp, arg->argv[arg->argn],
1669                addr, &dummyaddr, &dummyint);
1670      if (arg->argc > arg->argn+1)
1671        ParseAddr(&arg->bundle->ncp.ipcp, arg->argv[arg->argn + 1],
1672                  addr + 1, &dummyaddr, &dummyint);
1673
1674      if (addr[1].s_addr == INADDR_ANY)
1675        addr[1].s_addr = addr[0].s_addr;
1676      if (addr[0].s_addr == INADDR_ANY)
1677        addr[0].s_addr = addr[1].s_addr;
1678    }
1679    break;
1680
1681  case VAR_CALLBACK:
1682    cx->cfg.callback.opmask = 0;
1683    for (dummyint = arg->argn; dummyint < arg->argc; dummyint++) {
1684      if (!strcasecmp(arg->argv[dummyint], "auth"))
1685        cx->cfg.callback.opmask |= CALLBACK_BIT(CALLBACK_AUTH);
1686      else if (!strcasecmp(arg->argv[dummyint], "cbcp"))
1687        cx->cfg.callback.opmask |= CALLBACK_BIT(CALLBACK_CBCP);
1688      else if (!strcasecmp(arg->argv[dummyint], "e.164")) {
1689        if (dummyint == arg->argc - 1)
1690          log_Printf(LogWARN, "No E.164 arg (E.164 ignored) !\n");
1691        else {
1692          cx->cfg.callback.opmask |= CALLBACK_BIT(CALLBACK_E164);
1693          strncpy(cx->cfg.callback.msg, arg->argv[++dummyint],
1694                  sizeof cx->cfg.callback.msg - 1);
1695          cx->cfg.callback.msg[sizeof cx->cfg.callback.msg - 1] = '\0';
1696        }
1697      } else if (!strcasecmp(arg->argv[dummyint], "none"))
1698        cx->cfg.callback.opmask |= CALLBACK_BIT(CALLBACK_NONE);
1699      else
1700        return -1;
1701    }
1702    if (cx->cfg.callback.opmask == CALLBACK_BIT(CALLBACK_NONE))
1703      cx->cfg.callback.opmask = 0;
1704    break;
1705
1706  case VAR_CBCP:
1707    cx->cfg.cbcp.delay = 0;
1708    *cx->cfg.cbcp.phone = '\0';
1709    cx->cfg.cbcp.fsmretry = DEF_FSMRETRY;
1710    if (arg->argc > arg->argn) {
1711      strncpy(cx->cfg.cbcp.phone, arg->argv[arg->argn],
1712              sizeof cx->cfg.cbcp.phone - 1);
1713      cx->cfg.cbcp.phone[sizeof cx->cfg.cbcp.phone - 1] = '\0';
1714      if (arg->argc > arg->argn + 1) {
1715        cx->cfg.cbcp.delay = atoi(arg->argv[arg->argn + 1]);
1716        if (arg->argc > arg->argn + 2) {
1717          long_val = atol(arg->argv[arg->argn + 2]);
1718          if (long_val < MIN_FSMRETRY)
1719            log_Printf(LogWARN, "%ld: Invalid CBCP FSM retry period - min %d\n",
1720                       long_val, MIN_FSMRETRY);
1721          else
1722            cx->cfg.cbcp.fsmretry = long_val;
1723        }
1724      }
1725    }
1726    break;
1727
1728  case VAR_CHOKED:
1729    arg->bundle->cfg.choked.timeout = atoi(argp);
1730    if (arg->bundle->cfg.choked.timeout <= 0)
1731      arg->bundle->cfg.choked.timeout = CHOKED_TIMEOUT;
1732    break;
1733
1734  case VAR_SENDPIPE:
1735    long_val = atol(argp);
1736    arg->bundle->ncp.ipcp.cfg.sendpipe = long_val;
1737    break;
1738
1739  case VAR_RECVPIPE:
1740    long_val = atol(argp);
1741    arg->bundle->ncp.ipcp.cfg.recvpipe = long_val;
1742    break;
1743
1744#ifndef NORADIUS
1745  case VAR_RADIUS:
1746    if (!*argp)
1747      *arg->bundle->radius.cfg.file = '\0';
1748    else if (access(argp, R_OK)) {
1749      log_Printf(LogWARN, "%s: %s\n", argp, strerror(errno));
1750      return 1;
1751    } else {
1752      strncpy(arg->bundle->radius.cfg.file, argp,
1753              sizeof arg->bundle->radius.cfg.file - 1);
1754      arg->bundle->radius.cfg.file
1755        [sizeof arg->bundle->radius.cfg.file - 1] = '\0';
1756    }
1757    break;
1758#endif
1759
1760  case VAR_CD:
1761    if (*argp) {
1762      long_val = atol(argp);
1763      if (long_val < 0)
1764        long_val = 0;
1765      cx->physical->cfg.cd.delay = long_val;
1766      cx->physical->cfg.cd.required = argp[strlen(argp)-1] == '!';
1767    } else {
1768      cx->physical->cfg.cd.delay = DEF_CDDELAY;
1769      cx->physical->cfg.cd.required = 0;
1770    }
1771    break;
1772
1773  case VAR_PARITY:
1774    if (arg->argc == arg->argn + 1)
1775      return physical_SetParity(arg->cx->physical, argp);
1776    else {
1777      err = "Parity value must be odd, even or none\n";
1778      log_Printf(LogWARN, err);
1779    }
1780    break;
1781
1782  case VAR_CRTSCTS:
1783    if (strcasecmp(argp, "on") == 0)
1784      physical_SetRtsCts(arg->cx->physical, 1);
1785    else if (strcasecmp(argp, "off") == 0)
1786      physical_SetRtsCts(arg->cx->physical, 0);
1787    else {
1788      err = "RTS/CTS value must be on or off\n";
1789      log_Printf(LogWARN, err);
1790    }
1791    break;
1792  }
1793
1794  return err ? 1 : 0;
1795}
1796
1797static struct cmdtab const SetCommands[] = {
1798  {"accmap", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX,
1799  "accmap value", "set accmap hex-value", (const void *)VAR_ACCMAP},
1800  {"authkey", "key", SetVariable, LOCAL_AUTH,
1801  "authentication key", "set authkey|key key", (const void *)VAR_AUTHKEY},
1802  {"authname", NULL, SetVariable, LOCAL_AUTH,
1803  "authentication name", "set authname name", (const void *)VAR_AUTHNAME},
1804  {"autoload", NULL, SetVariable, LOCAL_AUTH,
1805  "auto link [de]activation", "set autoload maxtime maxload mintime minload",
1806  (const void *)VAR_AUTOLOAD},
1807  {"callback", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX,
1808  "callback control", "set callback [none|auth|cbcp|"
1809  "E.164 *|number[,number]...]...", (const void *)VAR_CALLBACK},
1810  {"cbcp", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX,
1811  "CBCP control", "set cbcp [*|phone[,phone...] [delay [timeout]]]",
1812  (const void *)VAR_CBCP},
1813  {"ccpretry", "ccpretries", SetVariable, LOCAL_AUTH | LOCAL_CX_OPT,
1814   "CCP retries", "set ccpretry value [attempts]", (const void *)VAR_CCPRETRY},
1815  {"cd", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX, "Carrier delay requirement",
1816   "set cd value[!]", (const void *)VAR_CD},
1817  {"chapretry", "chapretries", SetVariable, LOCAL_AUTH | LOCAL_CX,
1818   "CHAP retries", "set chapretry value [attempts]",
1819   (const void *)VAR_CHAPRETRY},
1820  {"choked", NULL, SetVariable, LOCAL_AUTH,
1821  "choked timeout", "set choked [secs]", (const void *)VAR_CHOKED},
1822  {"ctsrts", "crtscts", SetVariable, LOCAL_AUTH | LOCAL_CX,
1823   "Use hardware flow control", "set ctsrts [on|off]",
1824   (const char *)VAR_CRTSCTS},
1825  {"deflate", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX_OPT,
1826  "deflate window sizes", "set deflate out-winsize in-winsize",
1827  (const void *) VAR_WINSIZE},
1828  {"device", "line", SetVariable, LOCAL_AUTH | LOCAL_CX,
1829  "physical device name", "set device|line device-name[,device-name]",
1830  (const void *) VAR_DEVICE},
1831  {"dial", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX,
1832  "dialing script", "set dial chat-script", (const void *) VAR_DIAL},
1833  {"dns", NULL, SetVariable, LOCAL_AUTH, "Domain Name Server",
1834  "set dns pri-addr [sec-addr]", (const void *)VAR_DNS},
1835  {"enddisc", NULL, mp_SetEnddisc, LOCAL_AUTH,
1836  "Endpoint Discriminator", "set enddisc [IP|magic|label|psn value]"},
1837  {"escape", NULL, SetEscape, LOCAL_AUTH | LOCAL_CX,
1838  "escape characters", "set escape hex-digit ..."},
1839  {"filter", NULL, filter_Set, LOCAL_AUTH,
1840  "packet filters", "set filter alive|dial|in|out rule-no permit|deny "
1841  "[src_addr[/width]] [dst_addr[/width]] [tcp|udp|icmp|ospf|igmp "
1842  "[src [lt|eq|gt port]] [dst [lt|eq|gt port]] [estab] [syn] [finrst]]"},
1843  {"hangup", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX,
1844  "hangup script", "set hangup chat-script", (const void *) VAR_HANGUP},
1845  {"ifaddr", NULL, SetInterfaceAddr, LOCAL_AUTH, "destination address",
1846  "set ifaddr [src-addr [dst-addr [netmask [trg-addr]]]]"},
1847  {"ipcpretry", "ipcpretries", SetVariable, LOCAL_AUTH, "IPCP retries",
1848   "set ipcpretry value [attempts]", (const void *)VAR_IPCPRETRY},
1849  {"lcpretry", "lcpretries", SetVariable, LOCAL_AUTH | LOCAL_CX, "LCP retries",
1850   "set lcpretry value [attempts]", (const void *)VAR_LCPRETRY},
1851  {"log", NULL, log_SetLevel, LOCAL_AUTH, "log level",
1852  "set log [local] [+|-]async|cbcp|ccp|chat|command|connect|debug|hdlc|id0|"
1853  "ipcp|lcp|lqm|phase|physical|sync|tcp/ip|timer|tun..."},
1854  {"login", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX,
1855  "login script", "set login chat-script", (const void *) VAR_LOGIN},
1856  {"lqrperiod", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX_OPT,
1857  "LQR period", "set lqrperiod value", (const void *)VAR_LQRPERIOD},
1858  {"mode", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX, "mode value",
1859  "set mode interactive|auto|ddial|background", (const void *)VAR_MODE},
1860  {"mrru", NULL, SetVariable, LOCAL_AUTH, "MRRU value",
1861  "set mrru value", (const void *)VAR_MRRU},
1862  {"mru", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX_OPT,
1863  "MRU value", "set mru value", (const void *)VAR_MRU},
1864  {"mtu", NULL, SetVariable, LOCAL_AUTH,
1865  "interface MTU value", "set mtu value", (const void *)VAR_MTU},
1866  {"nbns", NULL, SetVariable, LOCAL_AUTH, "NetBIOS Name Server",
1867  "set nbns pri-addr [sec-addr]", (const void *)VAR_NBNS},
1868  {"openmode", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX, "open mode",
1869  "set openmode active|passive [secs]", (const void *)VAR_OPENMODE},
1870  {"papretry", "papretries", SetVariable, LOCAL_AUTH | LOCAL_CX, "PAP retries",
1871   "set papretry value [attempts]", (const void *)VAR_PAPRETRY},
1872  {"parity", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX, "serial parity",
1873   "set parity [odd|even|none]", (const void *)VAR_PARITY},
1874  {"phone", NULL, SetVariable, LOCAL_AUTH | LOCAL_CX, "telephone number(s)",
1875  "set phone phone1[:phone2[...]]", (const void *)VAR_PHONE},
1876  {"proctitle", "title", SetProcTitle, LOCAL_AUTH,
1877  "Process title", "set proctitle [value]"},
1878#ifndef NORADIUS
1879  {"radius", NULL, SetVariable, LOCAL_AUTH,
1880  "RADIUS Config", "set radius cfgfile", (const void *)VAR_RADIUS},
1881#endif
1882  {"reconnect", NULL, datalink_SetReconnect, LOCAL_AUTH | LOCAL_CX,
1883  "Reconnect timeout", "set reconnect value ntries"},
1884  {"recvpipe", NULL, SetVariable, LOCAL_AUTH,
1885  "RECVPIPE value", "set recvpipe value", (const void *)VAR_RECVPIPE},
1886  {"redial", NULL, datalink_SetRedial, LOCAL_AUTH | LOCAL_CX,
1887  "Redial timeout", "set redial secs[+inc[-incmax]][.next] [attempts]"},
1888  {"sendpipe", NULL, SetVariable, LOCAL_AUTH,
1889  "SENDPIPE value", "set sendpipe value", (const void *)VAR_SENDPIPE},
1890  {"server", "socket", SetServer, LOCAL_AUTH,
1891  "server port", "set server|socket TcpPort|LocalName|none password [mask]"},
1892  {"speed", NULL, SetModemSpeed, LOCAL_AUTH | LOCAL_CX,
1893  "physical speed", "set speed value|sync"},
1894  {"stopped", NULL, SetStoppedTimeout, LOCAL_AUTH | LOCAL_CX,
1895  "STOPPED timeouts", "set stopped [LCPseconds [CCPseconds]]"},
1896  {"timeout", NULL, SetVariable, LOCAL_AUTH, "Idle timeout",
1897  "set timeout idletime", (const void *)VAR_IDLETIMEOUT},
1898  {"vj", NULL, ipcp_vjset, LOCAL_AUTH,
1899  "vj values", "set vj slots|slotcomp [value]"},
1900  {"bandwidth", NULL, mp_SetDatalinkBandwidth, LOCAL_AUTH | LOCAL_CX,
1901  "datalink bandwidth", "set bandwidth value"},
1902  {"help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
1903  "Display this message", "set help|? [command]", SetCommands},
1904  {NULL, NULL, NULL},
1905};
1906
1907static int
1908SetCommand(struct cmdargs const *arg)
1909{
1910  if (arg->argc > arg->argn)
1911    FindExec(arg->bundle, SetCommands, arg->argc, arg->argn, arg->argv,
1912             arg->prompt, arg->cx);
1913  else if (arg->prompt)
1914    prompt_Printf(arg->prompt, "Use `set ?' to get a list or `set ? <var>' for"
1915	    " syntax help.\n");
1916  else
1917    log_Printf(LogWARN, "set command must have arguments\n");
1918
1919  return 0;
1920}
1921
1922static int
1923AddCommand(struct cmdargs const *arg)
1924{
1925  struct in_addr dest, gateway, netmask;
1926  int gw, addrs;
1927
1928  if (arg->argc != arg->argn+3 && arg->argc != arg->argn+2)
1929    return -1;
1930
1931  addrs = 0;
1932  if (arg->argc == arg->argn+2) {
1933    if (!strcasecmp(arg->argv[arg->argn], "default"))
1934      dest.s_addr = netmask.s_addr = INADDR_ANY;
1935    else {
1936      int width;
1937
1938      if (!ParseAddr(&arg->bundle->ncp.ipcp, arg->argv[arg->argn],
1939	             &dest, &netmask, &width))
1940        return -1;
1941      if (!strncasecmp(arg->argv[arg->argn], "MYADDR", 6))
1942        addrs = ROUTE_DSTMYADDR;
1943      else if (!strncasecmp(arg->argv[arg->argn], "HISADDR", 7))
1944        addrs = ROUTE_DSTHISADDR;
1945    }
1946    gw = 1;
1947  } else {
1948    if (strcasecmp(arg->argv[arg->argn], "MYADDR") == 0) {
1949      addrs = ROUTE_DSTMYADDR;
1950      dest = arg->bundle->ncp.ipcp.my_ip;
1951    } else if (strcasecmp(arg->argv[arg->argn], "HISADDR") == 0) {
1952      addrs = ROUTE_DSTHISADDR;
1953      dest = arg->bundle->ncp.ipcp.peer_ip;
1954    } else
1955      dest = GetIpAddr(arg->argv[arg->argn]);
1956    netmask = GetIpAddr(arg->argv[arg->argn+1]);
1957    gw = 2;
1958  }
1959
1960  if (strcasecmp(arg->argv[arg->argn+gw], "HISADDR") == 0) {
1961    gateway = arg->bundle->ncp.ipcp.peer_ip;
1962    addrs |= ROUTE_GWHISADDR;
1963  } else
1964    gateway = GetIpAddr(arg->argv[arg->argn+gw]);
1965
1966  if (bundle_SetRoute(arg->bundle, RTM_ADD, dest, gateway, netmask,
1967                  arg->cmd->args ? 1 : 0, (addrs & ROUTE_GWHISADDR) ? 1 : 0)
1968      && addrs != ROUTE_STATIC)
1969    route_Add(&arg->bundle->ncp.ipcp.route, addrs, dest, netmask, gateway);
1970
1971  return 0;
1972}
1973
1974static int
1975DeleteCommand(struct cmdargs const *arg)
1976{
1977  struct in_addr dest, none;
1978  int addrs;
1979
1980  if (arg->argc == arg->argn+1) {
1981    if(strcasecmp(arg->argv[arg->argn], "all") == 0) {
1982      route_IfDelete(arg->bundle, 0);
1983      route_DeleteAll(&arg->bundle->ncp.ipcp.route);
1984    } else {
1985      addrs = 0;
1986      if (strcasecmp(arg->argv[arg->argn], "MYADDR") == 0) {
1987        dest = arg->bundle->ncp.ipcp.my_ip;
1988        addrs = ROUTE_DSTMYADDR;
1989      } else if (strcasecmp(arg->argv[arg->argn], "HISADDR") == 0) {
1990        dest = arg->bundle->ncp.ipcp.peer_ip;
1991        addrs = ROUTE_DSTHISADDR;
1992      } else {
1993        dest = GetIpAddr(arg->argv[arg->argn]);
1994        if (dest.s_addr == INADDR_NONE) {
1995          log_Printf(LogWARN, "%s: Invalid IP address\n", arg->argv[arg->argn]);
1996          return -1;
1997        }
1998        addrs = ROUTE_STATIC;
1999      }
2000      none.s_addr = INADDR_ANY;
2001      bundle_SetRoute(arg->bundle, RTM_DELETE, dest, none, none,
2002                      arg->cmd->args ? 1 : 0, 0);
2003      route_Delete(&arg->bundle->ncp.ipcp.route, addrs, dest);
2004    }
2005  } else
2006    return -1;
2007
2008  return 0;
2009}
2010
2011#ifndef NOALIAS
2012static int
2013AliasEnable(struct cmdargs const *arg)
2014{
2015  if (arg->argc == arg->argn+1) {
2016    if (strcasecmp(arg->argv[arg->argn], "yes") == 0) {
2017      if (!arg->bundle->AliasEnabled) {
2018        if (arg->bundle->ncp.ipcp.fsm.state == ST_OPENED)
2019          PacketAliasSetAddress(arg->bundle->ncp.ipcp.my_ip);
2020        arg->bundle->AliasEnabled = 1;
2021      }
2022      return 0;
2023    } else if (strcasecmp(arg->argv[arg->argn], "no") == 0) {
2024      arg->bundle->AliasEnabled = 0;
2025      arg->bundle->cfg.opt &= ~OPT_IFACEALIAS;
2026      /* Don't iface_Clear() - there may be manually configured addresses */
2027      return 0;
2028    }
2029  }
2030
2031  return -1;
2032}
2033
2034
2035static int
2036AliasOption(struct cmdargs const *arg)
2037{
2038  long param = (long)arg->cmd->args;
2039
2040  if (arg->argc == arg->argn+1) {
2041    if (strcasecmp(arg->argv[arg->argn], "yes") == 0) {
2042      if (arg->bundle->AliasEnabled) {
2043	PacketAliasSetMode(param, param);
2044	return 0;
2045      }
2046      log_Printf(LogWARN, "alias not enabled\n");
2047    } else if (strcmp(arg->argv[arg->argn], "no") == 0) {
2048      if (arg->bundle->AliasEnabled) {
2049	PacketAliasSetMode(0, param);
2050	return 0;
2051      }
2052      log_Printf(LogWARN, "alias not enabled\n");
2053    }
2054  }
2055  return -1;
2056}
2057#endif /* #ifndef NOALIAS */
2058
2059static int
2060LinkCommand(struct cmdargs const *arg)
2061{
2062  if (arg->argc > arg->argn+1) {
2063    char namelist[LINE_LEN];
2064    struct datalink *cx;
2065    char *name;
2066    int result = 0;
2067
2068    if (!strcmp(arg->argv[arg->argn], "*")) {
2069      struct datalink *dl;
2070
2071      cx = arg->bundle->links;
2072      while (cx) {
2073        /* Watch it, the command could be a ``remove'' */
2074        dl = cx->next;
2075        FindExec(arg->bundle, Commands, arg->argc, arg->argn+1, arg->argv,
2076                 arg->prompt, cx);
2077        for (cx = arg->bundle->links; cx; cx = cx->next)
2078          if (cx == dl)
2079            break;		/* Pointer's still valid ! */
2080      }
2081    } else {
2082      strncpy(namelist, arg->argv[arg->argn], sizeof namelist - 1);
2083      namelist[sizeof namelist - 1] = '\0';
2084      for(name = strtok(namelist, ", "); name; name = strtok(NULL,", "))
2085        if (!bundle2datalink(arg->bundle, name)) {
2086          log_Printf(LogWARN, "link: %s: Invalid link name\n", name);
2087          return 1;
2088        }
2089
2090      strncpy(namelist, arg->argv[arg->argn], sizeof namelist - 1);
2091      namelist[sizeof namelist - 1] = '\0';
2092      for(name = strtok(namelist, ", "); name; name = strtok(NULL,", ")) {
2093        cx = bundle2datalink(arg->bundle, name);
2094        if (cx)
2095          FindExec(arg->bundle, Commands, arg->argc, arg->argn+1, arg->argv,
2096                   arg->prompt, cx);
2097        else {
2098          log_Printf(LogWARN, "link: %s: Invalidated link name !\n", name);
2099          result++;
2100        }
2101      }
2102    }
2103    return result;
2104  }
2105
2106  log_Printf(LogWARN, "Usage: %s\n", arg->cmd->syntax);
2107  return 2;
2108}
2109
2110struct link *
2111command_ChooseLink(struct cmdargs const *arg)
2112{
2113  if (arg->cx)
2114    return &arg->cx->physical->link;
2115  else if (!arg->bundle->ncp.mp.cfg.mrru) {
2116    struct datalink *dl = bundle2datalink(arg->bundle, NULL);
2117    if (dl)
2118      return &dl->physical->link;
2119  }
2120  return &arg->bundle->ncp.mp.link;
2121}
2122
2123static const char *
2124ident_cmd(const char *cmd, unsigned *keep, unsigned *add)
2125{
2126  const char *result;
2127
2128  switch (*cmd) {
2129    case 'A':
2130    case 'a':
2131      result = "accept";
2132      *keep = NEG_MYMASK;
2133      *add = NEG_ACCEPTED;
2134      break;
2135    case 'D':
2136    case 'd':
2137      switch (cmd[1]) {
2138        case 'E':
2139        case 'e':
2140          result = "deny";
2141          *keep = NEG_MYMASK;
2142          *add = 0;
2143          break;
2144        case 'I':
2145        case 'i':
2146          result = "disable";
2147          *keep = NEG_HISMASK;
2148          *add = 0;
2149          break;
2150        default:
2151          return NULL;
2152      }
2153      break;
2154    case 'E':
2155    case 'e':
2156      result = "enable";
2157      *keep = NEG_HISMASK;
2158      *add = NEG_ENABLED;
2159      break;
2160    default:
2161      return NULL;
2162  }
2163
2164  return result;
2165}
2166
2167static int
2168OptSet(struct cmdargs const *arg)
2169{
2170  int bit = (int)(long)arg->cmd->args;
2171  const char *cmd;
2172  unsigned keep;			/* Keep these bits */
2173  unsigned add;				/* Add these bits */
2174
2175  if ((cmd = ident_cmd(arg->argv[arg->argn-2], &keep, &add)) == NULL)
2176    return 1;
2177
2178  if (add)
2179    arg->bundle->cfg.opt |= bit;
2180  else
2181    arg->bundle->cfg.opt &= ~bit;
2182  return 0;
2183}
2184
2185static int
2186IfaceAliasOptSet(struct cmdargs const *arg)
2187{
2188  unsigned save = arg->bundle->cfg.opt;
2189  int result = OptSet(arg);
2190
2191  if (result == 0)
2192    if (Enabled(arg->bundle, OPT_IFACEALIAS) && !arg->bundle->AliasEnabled) {
2193      arg->bundle->cfg.opt = save;
2194      log_Printf(LogWARN, "Cannot enable iface-alias without IP aliasing\n");
2195      result = 2;
2196    }
2197
2198  return result;
2199}
2200
2201static int
2202NegotiateSet(struct cmdargs const *arg)
2203{
2204  long param = (long)arg->cmd->args;
2205  struct link *l = command_ChooseLink(arg);	/* LOCAL_CX_OPT uses this */
2206  struct datalink *cx = arg->cx;	/* LOCAL_CX uses this */
2207  const char *cmd;
2208  unsigned keep;			/* Keep these bits */
2209  unsigned add;				/* Add these bits */
2210
2211  if ((cmd = ident_cmd(arg->argv[arg->argn-2], &keep, &add)) == NULL)
2212    return 1;
2213
2214  if ((arg->cmd->lauth & LOCAL_CX) && !cx) {
2215    log_Printf(LogWARN, "%s %s: No context (use the `link' command)\n",
2216              cmd, arg->cmd->name);
2217    return 2;
2218  } else if (cx && !(arg->cmd->lauth & (LOCAL_CX|LOCAL_CX_OPT))) {
2219    log_Printf(LogWARN, "%s %s: Redundant context (%s) ignored\n",
2220              cmd, arg->cmd->name, cx->name);
2221    cx = NULL;
2222  }
2223
2224  switch (param) {
2225    case NEG_ACFCOMP:
2226      cx->physical->link.lcp.cfg.acfcomp &= keep;
2227      cx->physical->link.lcp.cfg.acfcomp |= add;
2228      break;
2229    case NEG_CHAP05:
2230      cx->physical->link.lcp.cfg.chap05 &= keep;
2231      cx->physical->link.lcp.cfg.chap05 |= add;
2232      break;
2233#ifdef HAVE_DES
2234    case NEG_CHAP80:
2235      cx->physical->link.lcp.cfg.chap80nt &= keep;
2236      cx->physical->link.lcp.cfg.chap80nt |= add;
2237      break;
2238    case NEG_CHAP80LM:
2239      cx->physical->link.lcp.cfg.chap80lm &= keep;
2240      cx->physical->link.lcp.cfg.chap80lm |= add;
2241      break;
2242#endif
2243    case NEG_DEFLATE:
2244      l->ccp.cfg.neg[CCP_NEG_DEFLATE] &= keep;
2245      l->ccp.cfg.neg[CCP_NEG_DEFLATE] |= add;
2246      break;
2247    case NEG_DNS:
2248      arg->bundle->ncp.ipcp.cfg.ns.dns_neg &= keep;
2249      arg->bundle->ncp.ipcp.cfg.ns.dns_neg |= add;
2250      break;
2251    case NEG_ENDDISC:
2252      arg->bundle->ncp.mp.cfg.negenddisc &= keep;
2253      arg->bundle->ncp.mp.cfg.negenddisc |= add;
2254      break;
2255    case NEG_LQR:
2256      cx->physical->link.lcp.cfg.lqr &= keep;
2257      cx->physical->link.lcp.cfg.lqr |= add;
2258      break;
2259    case NEG_PAP:
2260      cx->physical->link.lcp.cfg.pap &= keep;
2261      cx->physical->link.lcp.cfg.pap |= add;
2262      break;
2263    case NEG_PPPDDEFLATE:
2264      l->ccp.cfg.neg[CCP_NEG_DEFLATE24] &= keep;
2265      l->ccp.cfg.neg[CCP_NEG_DEFLATE24] |= add;
2266      break;
2267    case NEG_PRED1:
2268      l->ccp.cfg.neg[CCP_NEG_PRED1] &= keep;
2269      l->ccp.cfg.neg[CCP_NEG_PRED1] |= add;
2270      break;
2271    case NEG_PROTOCOMP:
2272      cx->physical->link.lcp.cfg.protocomp &= keep;
2273      cx->physical->link.lcp.cfg.protocomp |= add;
2274      break;
2275    case NEG_SHORTSEQ:
2276      switch (bundle_Phase(arg->bundle)) {
2277        case PHASE_DEAD:
2278          break;
2279        case PHASE_ESTABLISH:
2280          /* Make sure none of our links are DATALINK_LCP or greater */
2281          if (bundle_HighestState(arg->bundle) >= DATALINK_LCP) {
2282            log_Printf(LogWARN, "shortseq: Only changable before"
2283                       " LCP negotiations\n");
2284            return 1;
2285          }
2286          break;
2287        default:
2288          log_Printf(LogWARN, "shortseq: Only changable at phase"
2289                     " DEAD/ESTABLISH\n");
2290          return 1;
2291      }
2292      arg->bundle->ncp.mp.cfg.shortseq &= keep;
2293      arg->bundle->ncp.mp.cfg.shortseq |= add;
2294      break;
2295    case NEG_VJCOMP:
2296      arg->bundle->ncp.ipcp.cfg.vj.neg &= keep;
2297      arg->bundle->ncp.ipcp.cfg.vj.neg |= add;
2298      break;
2299  }
2300
2301  return 0;
2302}
2303
2304static struct cmdtab const NegotiateCommands[] = {
2305  {"idcheck", NULL, OptSet, LOCAL_AUTH, "Check FSM reply ids",
2306  "disable|enable", (const void *)OPT_IDCHECK},
2307  {"iface-alias", NULL, IfaceAliasOptSet, LOCAL_AUTH,
2308   "retain interface addresses", "disable|enable",
2309   (const void *)OPT_IFACEALIAS},
2310  {"keep-session", NULL, OptSet, LOCAL_AUTH, "Retain device session leader",
2311  "disable|enable", (const void *)OPT_KEEPSESSION},
2312  {"loopback", NULL, OptSet, LOCAL_AUTH, "Loop packets for local iface",
2313  "disable|enable", (const void *)OPT_LOOPBACK},
2314  {"passwdauth", NULL, OptSet, LOCAL_AUTH, "Use passwd file",
2315  "disable|enable", (const void *)OPT_PASSWDAUTH},
2316  {"proxy", NULL, OptSet, LOCAL_AUTH, "Create a proxy ARP entry",
2317  "disable|enable", (const void *)OPT_PROXY},
2318  {"proxyall", NULL, OptSet, LOCAL_AUTH, "Proxy ARP for all remote hosts",
2319  "disable|enable", (const void *)OPT_PROXYALL},
2320  {"sroutes", NULL, OptSet, LOCAL_AUTH, "Use sticky routes",
2321  "disable|enable", (const void *)OPT_SROUTES},
2322  {"throughput", NULL, OptSet, LOCAL_AUTH, "Rolling throughput",
2323  "disable|enable", (const void *)OPT_THROUGHPUT},
2324  {"utmp", NULL, OptSet, LOCAL_AUTH, "Log connections in utmp",
2325  "disable|enable", (const void *)OPT_UTMP},
2326
2327#define OPT_MAX 10	/* accept/deny allowed below and not above */
2328
2329  {"acfcomp", NULL, NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2330  "Address & Control field compression", "accept|deny|disable|enable",
2331  (const void *)NEG_ACFCOMP},
2332  {"chap", "chap05", NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2333  "Challenge Handshake Authentication Protocol", "accept|deny|disable|enable",
2334  (const void *)NEG_CHAP05},
2335#ifdef HAVE_DES
2336  {"mschap", "chap80nt", NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2337  "Microsoft (NT) CHAP", "accept|deny|disable|enable",
2338  (const void *)NEG_CHAP80},
2339  {"LANMan", "chap80lm", NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2340  "Microsoft (NT) CHAP", "accept|deny|disable|enable",
2341  (const void *)NEG_CHAP80LM},
2342#endif
2343  {"deflate", NULL, NegotiateSet, LOCAL_AUTH | LOCAL_CX_OPT,
2344  "Deflate compression", "accept|deny|disable|enable",
2345  (const void *)NEG_DEFLATE},
2346  {"deflate24", NULL, NegotiateSet, LOCAL_AUTH | LOCAL_CX_OPT,
2347  "Deflate (type 24) compression", "accept|deny|disable|enable",
2348  (const void *)NEG_PPPDDEFLATE},
2349  {"dns", NULL, NegotiateSet, LOCAL_AUTH,
2350  "DNS specification", "accept|deny|disable|enable", (const void *)NEG_DNS},
2351  {"enddisc", NULL, NegotiateSet, LOCAL_AUTH, "ENDDISC negotiation",
2352  "accept|deny|disable|enable", (const void *)NEG_ENDDISC},
2353  {"lqr", NULL, NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2354  "Link Quality Reports", "accept|deny|disable|enable",
2355  (const void *)NEG_LQR},
2356  {"pap", NULL, NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2357  "Password Authentication protocol", "accept|deny|disable|enable",
2358  (const void *)NEG_PAP},
2359  {"pred1", "predictor1", NegotiateSet, LOCAL_AUTH | LOCAL_CX_OPT,
2360  "Predictor 1 compression", "accept|deny|disable|enable",
2361  (const void *)NEG_PRED1},
2362  {"protocomp", NULL, NegotiateSet, LOCAL_AUTH | LOCAL_CX,
2363  "Protocol field compression", "accept|deny|disable|enable",
2364  (const void *)NEG_PROTOCOMP},
2365  {"shortseq", NULL, NegotiateSet, LOCAL_AUTH,
2366  "MP Short Sequence Numbers", "accept|deny|disable|enable",
2367  (const void *)NEG_SHORTSEQ},
2368  {"vjcomp", NULL, NegotiateSet, LOCAL_AUTH,
2369  "Van Jacobson header compression", "accept|deny|disable|enable",
2370  (const void *)NEG_VJCOMP},
2371  {"help", "?", HelpCommand, LOCAL_AUTH | LOCAL_NO_AUTH,
2372  "Display this message", "accept|deny|disable|enable help|? [value]",
2373  NegotiateCommands},
2374  {NULL, NULL, NULL},
2375};
2376
2377static int
2378NegotiateCommand(struct cmdargs const *arg)
2379{
2380  if (arg->argc > arg->argn) {
2381    char const *argv[3];
2382    unsigned keep, add;
2383    int n;
2384
2385    if ((argv[0] = ident_cmd(arg->argv[arg->argn-1], &keep, &add)) == NULL)
2386      return -1;
2387    argv[2] = NULL;
2388
2389    for (n = arg->argn; n < arg->argc; n++) {
2390      argv[1] = arg->argv[n];
2391      FindExec(arg->bundle, NegotiateCommands + (keep == NEG_HISMASK ?
2392               0 : OPT_MAX), 2, 1, argv, arg->prompt, arg->cx);
2393    }
2394  } else if (arg->prompt)
2395    prompt_Printf(arg->prompt, "Use `%s ?' to get a list.\n",
2396	    arg->argv[arg->argn-1]);
2397  else
2398    log_Printf(LogWARN, "%s command must have arguments\n",
2399              arg->argv[arg->argn] );
2400
2401  return 0;
2402}
2403
2404const char *
2405command_ShowNegval(unsigned val)
2406{
2407  switch (val&3) {
2408    case 1: return "disabled & accepted";
2409    case 2: return "enabled & denied";
2410    case 3: return "enabled & accepted";
2411  }
2412  return "disabled & denied";
2413}
2414
2415static int
2416ClearCommand(struct cmdargs const *arg)
2417{
2418  struct pppThroughput *t;
2419  struct datalink *cx;
2420  int i, clear_type;
2421
2422  if (arg->argc < arg->argn + 1)
2423    return -1;
2424
2425  if (strcasecmp(arg->argv[arg->argn], "physical") == 0) {
2426    cx = arg->cx;
2427    if (!cx)
2428      cx = bundle2datalink(arg->bundle, NULL);
2429    if (!cx) {
2430      log_Printf(LogWARN, "A link must be specified for ``clear physical''\n");
2431      return 1;
2432    }
2433    t = &cx->physical->link.throughput;
2434  } else if (strcasecmp(arg->argv[arg->argn], "ipcp") == 0)
2435    t = &arg->bundle->ncp.ipcp.throughput;
2436  else
2437    return -1;
2438
2439  if (arg->argc > arg->argn + 1) {
2440    clear_type = 0;
2441    for (i = arg->argn + 1; i < arg->argc; i++)
2442      if (strcasecmp(arg->argv[i], "overall") == 0)
2443        clear_type |= THROUGHPUT_OVERALL;
2444      else if (strcasecmp(arg->argv[i], "current") == 0)
2445        clear_type |= THROUGHPUT_CURRENT;
2446      else if (strcasecmp(arg->argv[i], "peak") == 0)
2447        clear_type |= THROUGHPUT_PEAK;
2448      else
2449        return -1;
2450  } else
2451    clear_type = THROUGHPUT_ALL;
2452
2453  throughput_clear(t, clear_type, arg->prompt);
2454  return 0;
2455}
2456
2457static int
2458RunListCommand(struct cmdargs const *arg)
2459{
2460  const char *cmd = arg->argc ? arg->argv[arg->argc - 1] : "???";
2461
2462  if (arg->argc > arg->argn)
2463    FindExec(arg->bundle, arg->cmd->args, arg->argc, arg->argn, arg->argv,
2464             arg->prompt, arg->cx);
2465  else if (arg->prompt)
2466    prompt_Printf(arg->prompt, "Use `%s help' to get a list or `%s help"
2467                  " <option>' for syntax help.\n", cmd, cmd);
2468  else
2469    log_Printf(LogWARN, "%s command must have arguments\n", cmd);
2470
2471  return 0;
2472}
2473
2474static int
2475IfaceAddCommand(struct cmdargs const *arg)
2476{
2477  int bits, n, how;
2478  struct in_addr ifa, mask, brd;
2479
2480  if (arg->argc == arg->argn + 1) {
2481    if (!ParseAddr(NULL, arg->argv[arg->argn], &ifa, NULL, NULL))
2482      return -1;
2483    mask.s_addr = brd.s_addr = INADDR_BROADCAST;
2484  } else {
2485    if (arg->argc == arg->argn + 2) {
2486      if (!ParseAddr(NULL, arg->argv[arg->argn], &ifa, &mask, &bits))
2487        return -1;
2488      n = 1;
2489    } else if (arg->argc == arg->argn + 3) {
2490      if (!ParseAddr(NULL, arg->argv[arg->argn], &ifa, NULL, NULL))
2491        return -1;
2492      if (!ParseAddr(NULL, arg->argv[arg->argn + 1], &mask, NULL, NULL))
2493        return -1;
2494      n = 2;
2495    } else
2496      return -1;
2497
2498    if (!ParseAddr(NULL, arg->argv[arg->argn + n], &brd, NULL, NULL))
2499      return -1;
2500  }
2501
2502  how = IFACE_ADD_LAST;
2503  if (arg->cmd->args)
2504    how |= IFACE_FORCE_ADD;
2505
2506  return !iface_inAdd(arg->bundle->iface, ifa, mask, brd, how);
2507}
2508
2509static int
2510IfaceDeleteCommand(struct cmdargs const *arg)
2511{
2512  struct in_addr ifa;
2513  int ok;
2514
2515  if (arg->argc != arg->argn + 1)
2516    return -1;
2517
2518  if (!ParseAddr(NULL, arg->argv[arg->argn], &ifa, NULL, NULL))
2519    return -1;
2520
2521  if (arg->bundle->ncp.ipcp.fsm.state == ST_OPENED &&
2522      arg->bundle->ncp.ipcp.my_ip.s_addr == ifa.s_addr) {
2523    log_Printf(LogWARN, "%s: Cannot remove active interface address\n",
2524               inet_ntoa(ifa));
2525    return 1;
2526  }
2527
2528  ok = iface_inDelete(arg->bundle->iface, ifa);
2529  if (!ok) {
2530    if (arg->cmd->args)
2531      ok = 1;
2532    else if (arg->prompt)
2533      prompt_Printf(arg->prompt, "%s: No such address\n", inet_ntoa(ifa));
2534    else
2535      log_Printf(LogWARN, "%s: No such address\n", inet_ntoa(ifa));
2536  }
2537
2538  return !ok;
2539}
2540
2541static int
2542IfaceClearCommand(struct cmdargs const *arg)
2543{
2544  int how;
2545
2546  if (arg->argc != arg->argn)
2547    return -1;
2548
2549  how = arg->bundle->ncp.ipcp.fsm.state == ST_OPENED ||
2550        arg->bundle->phys_type.all & PHYS_AUTO ?
2551        IFACE_CLEAR_ALIASES : IFACE_CLEAR_ALL;
2552  iface_Clear(arg->bundle->iface, how);
2553
2554  return 0;
2555}
2556
2557static int
2558SetProcTitle(struct cmdargs const *arg)
2559{
2560  static char title[LINE_LEN];
2561  char *argv[MAXARGS], *ptr;
2562  int len, remaining, f, argc = arg->argc - arg->argn;
2563
2564  if (arg->argc == arg->argn) {
2565    arg->bundle->argv[0] = arg->bundle->argv0;
2566    arg->bundle->argv[1] = arg->bundle->argv1;
2567    return 0;
2568  }
2569
2570  if (argc >= sizeof argv / sizeof argv[0]) {
2571    argc = sizeof argv / sizeof argv[0] - 1;
2572    log_Printf(LogWARN, "Truncating proc title to %d args\n", argc);
2573  }
2574  command_Expand(argv, argc, arg->argv + arg->argn, arg->bundle, 1, getpid());
2575
2576  ptr = title;
2577  remaining = sizeof title - 1;
2578  for (f = 0; f < argc && remaining; f++) {
2579    if (f) {
2580      *ptr++ = ' ';
2581      remaining--;
2582    }
2583    len = strlen(argv[f]);
2584    if (len > remaining)
2585      len = remaining;
2586    memcpy(ptr, argv[f], len);
2587    remaining -= len;
2588    ptr += len;
2589  }
2590  *ptr = '\0';
2591
2592  arg->bundle->argv[0] = title;
2593  arg->bundle->argv[1] = NULL;
2594
2595  return 0;
2596}
2597