prompt.c revision 37141
1/*-
2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 *	$Id: prompt.c,v 1.7 1998/06/16 19:40:40 brian Exp $
27 */
28
29#include <sys/param.h>
30#include <netinet/in.h>
31#include <netinet/in_systm.h>
32#include <netinet/ip.h>
33#include <sys/un.h>
34
35#include <errno.h>
36#include <stdarg.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <sys/fcntl.h>
41#include <termios.h>
42#include <unistd.h>
43
44#include "defs.h"
45#include "timer.h"
46#include "command.h"
47#include "log.h"
48#include "descriptor.h"
49#include "prompt.h"
50#include "fsm.h"
51#include "lcp.h"
52#include "auth.h"
53#include "iplist.h"
54#include "throughput.h"
55#include "slcompress.h"
56#include "ipcp.h"
57#include "filter.h"
58#include "lqr.h"
59#include "hdlc.h"
60#include "async.h"
61#include "mbuf.h"
62#include "ccp.h"
63#include "link.h"
64#include "physical.h"
65#include "mp.h"
66#include "bundle.h"
67#include "chat.h"
68#include "chap.h"
69#include "datalink.h"
70#include "server.h"
71
72static void
73prompt_Display(struct prompt *p)
74{
75  /* XXX: See Index2Nam() - should we only figure this out once ? */
76  static char shostname[MAXHOSTNAMELEN];
77  const char *pconnect, *pauth;
78
79  if (p->TermMode || !p->needprompt)
80    return;
81
82  p->needprompt = 0;
83
84  if (p->nonewline)
85    p->nonewline = 0;
86  else
87    fprintf(p->Term, "\n");
88
89  if (p->auth == LOCAL_AUTH)
90    pauth = " ON ";
91  else
92    pauth = " on ";
93
94  if (p->bundle->ncp.ipcp.fsm.state == ST_OPENED)
95    pconnect = "PPP";
96  else if (bundle_Phase(p->bundle) == PHASE_NETWORK)
97    pconnect = "PPp";
98  else if (bundle_Phase(p->bundle) == PHASE_AUTHENTICATE)
99    pconnect = "Ppp";
100  else
101    pconnect = "ppp";
102
103  if (*shostname == '\0') {
104    char *dot;
105
106    if (gethostname(shostname, sizeof shostname))
107      strcpy(shostname, "localhost");
108    else if ((dot = strchr(shostname, '.')))
109      *dot = '\0';
110  }
111
112  fprintf(p->Term, "%s%s%s> ", pconnect, pauth, shostname);
113  fflush(p->Term);
114}
115
116static int
117prompt_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
118{
119  struct prompt *p = descriptor2prompt(d);
120  int sets;
121
122  sets = 0;
123
124  if (!p->active)
125    return sets;
126
127  if (p->fd_in >= 0) {
128    if (r) {
129      FD_SET(p->fd_in, r);
130      log_Printf(LogTIMER, "prompt %s: fdset(r) %d\n", p->src.from, p->fd_in);
131      sets++;
132    }
133    if (e) {
134      FD_SET(p->fd_in, e);
135      log_Printf(LogTIMER, "prompt %s: fdset(e) %d\n", p->src.from, p->fd_in);
136      sets++;
137    }
138    if (sets && *n < p->fd_in + 1)
139      *n = p->fd_in + 1;
140  }
141
142  prompt_Display(p);
143
144  return sets;
145}
146
147static int
148prompt_IsSet(struct descriptor *d, const fd_set *fdset)
149{
150  struct prompt *p = descriptor2prompt(d);
151  return p->fd_in >= 0 && FD_ISSET(p->fd_in, fdset);
152}
153
154
155static void
156prompt_ShowHelp(struct prompt *p)
157{
158  prompt_Printf(p, "The following commands are available:\n");
159  prompt_Printf(p, " ~p\tEnter Packet mode\n");
160  prompt_Printf(p, " ~t\tShow timers\n");
161  prompt_Printf(p, " ~m\tShow memory map\n");
162  prompt_Printf(p, " ~.\tTerminate program\n");
163  prompt_Printf(p, " ~?\tThis help\n");
164}
165
166static void
167prompt_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
168{
169  struct prompt *p = descriptor2prompt(d);
170  int n;
171  char ch;
172  char linebuff[LINE_LEN];
173
174  if (p->TermMode == NULL) {
175    n = read(p->fd_in, linebuff, sizeof linebuff - 1);
176    if (n > 0) {
177      if (linebuff[n-1] == '\n')
178        linebuff[--n] = '\0';
179      else
180        linebuff[n] = '\0';
181      p->nonewline = 1;		/* Maybe command_Decode does a prompt */
182      prompt_Required(p);
183      if (n)
184        command_Decode(bundle, linebuff, n, p, p->src.from);
185    } else if (n <= 0) {
186      log_Printf(LogPHASE, "%s: Client connection closed.\n", p->src.from);
187      prompt_Destroy(p, 0);
188    }
189    return;
190  }
191
192  switch (p->TermMode->state) {
193    case DATALINK_CLOSED:
194      prompt_Printf(p, "Link lost, terminal mode.\n");
195      prompt_TtyCommandMode(p);
196      p->nonewline = 0;
197      prompt_Required(p);
198      return;
199
200    case DATALINK_READY:
201      break;
202
203    case DATALINK_OPEN:
204      prompt_Printf(p, "\nPacket mode detected.\n");
205      prompt_TtyCommandMode(p);
206      p->nonewline = 0;
207      /* We'll get a prompt because of our status change */
208      /* Fall through */
209
210    default:
211      /* Wait 'till we're in a state we care about */
212      return;
213  }
214
215  /*
216   * We are in terminal mode, decode special sequences
217   */
218  n = read(p->fd_in, &ch, 1);
219  log_Printf(LogDEBUG, "Got %d bytes (reading from the terminal)\n", n);
220
221  if (n > 0) {
222    switch (p->readtilde) {
223    case 0:
224      if (ch == '~')
225        p->readtilde = 1;
226      else
227	if (physical_Write(p->TermMode->physical, &ch, n) < 0) {
228	  log_Printf(LogWARN, "error writing to modem: %s\n", strerror(errno));
229          prompt_TtyCommandMode(p);
230        }
231      break;
232    case 1:
233      switch (ch) {
234      case '?':
235	prompt_ShowHelp(p);
236	break;
237      case 'p':
238        datalink_Up(p->TermMode, 0, 1);
239        prompt_Printf(p, "\nPacket mode.\n");
240	prompt_TtyCommandMode(p);
241        break;
242      case '.':
243	prompt_TtyCommandMode(p);
244        p->nonewline = 0;
245        prompt_Required(p);
246	break;
247      case 't':
248	timer_Show(0, p);
249	break;
250      case 'm':
251        {
252          struct cmdargs arg;
253
254          arg.cmdtab = NULL;
255          arg.cmd = NULL;
256          arg.argc = 0;
257          arg.argn = 0;
258          arg.argv = NULL;
259          arg.bundle = bundle;
260          arg.cx = p->TermMode;
261          arg.prompt = p;
262
263	  mbuf_Show(&arg);
264        }
265	break;
266      default:
267	if (physical_Write(p->TermMode->physical, &ch, n) < 0) {
268	  log_Printf(LogWARN, "error writing to modem: %s\n", strerror(errno));
269          prompt_TtyCommandMode(p);
270        }
271	break;
272      }
273      p->readtilde = 0;
274      break;
275    }
276  }
277}
278
279static int
280prompt_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
281{
282  /* We never want to write here ! */
283  log_Printf(LogALERT, "prompt_Write: Internal error: Bad call !\n");
284  return 0;
285}
286
287struct prompt *
288prompt_Create(struct server *s, struct bundle *bundle, int fd)
289{
290  struct prompt *p = (struct prompt *)malloc(sizeof(struct prompt));
291
292  if (p != NULL) {
293    p->desc.type = PROMPT_DESCRIPTOR;
294    p->desc.UpdateSet = prompt_UpdateSet;
295    p->desc.IsSet = prompt_IsSet;
296    p->desc.Read = prompt_Read;
297    p->desc.Write = prompt_Write;
298
299    if (fd == PROMPT_STD) {
300      char *tty = ttyname(STDIN_FILENO);
301
302      if (!tty) {
303        free(p);
304        return NULL;
305      }
306      p->fd_in = STDIN_FILENO;
307      p->fd_out = STDOUT_FILENO;
308      p->Term = stdout;
309      p->owner = NULL;
310      p->auth = LOCAL_AUTH;
311      p->src.type = "Controller";
312      strncpy(p->src.from, tty, sizeof p->src.from - 1);
313      p->src.from[sizeof p->src.from - 1] = '\0';
314      tcgetattr(p->fd_in, &p->oldtio);	/* Save original tty mode */
315    } else {
316      p->fd_in = p->fd_out = fd;
317      p->Term = fdopen(fd, "a+");
318      p->owner = s;
319      p->auth = *s->passwd ? LOCAL_NO_AUTH : LOCAL_AUTH;
320      p->src.type = "unknown";
321      *p->src.from = '\0';
322    }
323    p->TermMode = NULL;
324    p->nonewline = 1;
325    p->needprompt = 1;
326    p->readtilde = 0;
327    p->bundle = bundle;
328    log_RegisterPrompt(p);
329  }
330
331  return p;
332}
333
334void
335prompt_Destroy(struct prompt *p, int verbose)
336{
337  if (p) {
338    if (p->Term != stdout) {
339      fclose(p->Term);
340      close(p->fd_in);
341      if (p->fd_out != p->fd_in)
342        close(p->fd_out);
343      if (verbose)
344        log_Printf(LogPHASE, "%s: Client connection dropped.\n", p->src.from);
345    } else
346      prompt_TtyOldMode(p);
347
348    log_UnRegisterPrompt(p);
349    free(p);
350  }
351}
352
353void
354prompt_Printf(struct prompt *p, const char *fmt,...)
355{
356  if (p && p->active) {
357    va_list ap;
358
359    va_start(ap, fmt);
360    prompt_vPrintf(p, fmt, ap);
361    va_end(ap);
362  }
363}
364
365void
366prompt_vPrintf(struct prompt *p, const char *fmt, va_list ap)
367{
368  if (p && p->active) {
369    char nfmt[LINE_LEN];
370    const char *pfmt;
371
372    if (p->TermMode) {
373      /* Stuff '\r' in front of '\n' 'cos we're in raw mode */
374      int len = strlen(fmt);
375
376      if (len && len < sizeof nfmt - 1 && fmt[len-1] == '\n') {
377        strcpy(nfmt, fmt);
378        strcpy(nfmt + len - 1, "\r\n");
379        pfmt = nfmt;
380      } else
381        pfmt = fmt;
382    } else
383      pfmt = fmt;
384    vfprintf(p->Term, pfmt, ap);
385    fflush(p->Term);
386    p->nonewline = 1;
387  }
388}
389
390void
391prompt_TtyInit(struct prompt *p)
392{
393  int stat, fd = p ? p->fd_in : STDIN_FILENO;
394  struct termios newtio;
395
396  stat = fcntl(fd, F_GETFL, 0);
397  if (stat > 0) {
398    stat |= O_NONBLOCK;
399    fcntl(fd, F_SETFL, stat);
400  }
401
402  if (p)
403    newtio = p->oldtio;
404  else
405    tcgetattr(fd, &newtio);
406
407  newtio.c_lflag &= ~(ECHO | ISIG | ICANON);
408  newtio.c_iflag = 0;
409  newtio.c_oflag &= ~OPOST;
410  newtio.c_cc[VEOF] = _POSIX_VDISABLE;
411  if (!p)
412    newtio.c_cc[VINTR] = _POSIX_VDISABLE;
413  newtio.c_cc[VMIN] = 1;
414  newtio.c_cc[VTIME] = 0;
415  newtio.c_cflag |= CS8;
416  tcsetattr(fd, TCSANOW, &newtio);
417  if (p)
418    p->comtio = newtio;
419}
420
421/*
422 *  Set tty into command mode. We allow canonical input and echo processing.
423 */
424void
425prompt_TtyCommandMode(struct prompt *p)
426{
427  struct termios newtio;
428  int stat;
429
430  tcgetattr(p->fd_in, &newtio);
431  newtio.c_lflag |= (ECHO | ISIG | ICANON);
432  newtio.c_iflag = p->oldtio.c_iflag;
433  newtio.c_oflag |= OPOST;
434  tcsetattr(p->fd_in, TCSADRAIN, &newtio);
435
436  stat = fcntl(p->fd_in, F_GETFL, 0);
437  if (stat > 0) {
438    stat |= O_NONBLOCK;
439    fcntl(p->fd_in, F_SETFL, stat);
440  }
441
442  p->TermMode = NULL;
443}
444
445/*
446 * Set tty into terminal mode which is used while we invoke term command.
447 */
448void
449prompt_TtyTermMode(struct prompt *p, struct datalink *dl)
450{
451  int stat;
452
453  prompt_Printf(p, "Entering terminal mode on %s.\n", dl->name);
454  prompt_Printf(p, "Type `~?' for help.\n");
455
456  if (p->Term == stdout)
457    tcsetattr(p->fd_in, TCSADRAIN, &p->comtio);
458
459  stat = fcntl(p->fd_in, F_GETFL, 0);
460  if (stat > 0) {
461    stat &= ~O_NONBLOCK;
462    fcntl(p->fd_in, F_SETFL, stat);
463  }
464  p->TermMode = dl;
465}
466
467void
468prompt_TtyOldMode(struct prompt *p)
469{
470  int stat;
471
472  stat = fcntl(p->fd_in, F_GETFL, 0);
473  if (stat > 0) {
474    stat &= ~O_NONBLOCK;
475    fcntl(p->fd_in, F_SETFL, stat);
476  }
477
478  if (p->Term == stdout)
479    tcsetattr(p->fd_in, TCSADRAIN, &p->oldtio);
480}
481
482pid_t
483prompt_pgrp(struct prompt *p)
484{
485  return tcgetpgrp(p->fd_in);
486}
487
488int
489PasswdCommand(struct cmdargs const *arg)
490{
491  const char *pass;
492
493  if (!arg->prompt) {
494    log_Printf(LogWARN, "passwd: Cannot specify without a prompt\n");
495    return 0;
496  }
497
498  if (arg->prompt->owner == NULL) {
499    log_Printf(LogWARN, "passwd: Not required\n");
500    return 0;
501  }
502
503  if (arg->argc == arg->argn)
504    pass = "";
505  else if (arg->argc > arg->argn+1)
506    return -1;
507  else
508    pass = arg->argv[arg->argn];
509
510  if (!strcmp(arg->prompt->owner->passwd, pass))
511    arg->prompt->auth = LOCAL_AUTH;
512  else
513    arg->prompt->auth = LOCAL_NO_AUTH;
514
515  return 0;
516}
517
518static struct pppTimer bgtimer;
519
520static void
521prompt_TimedContinue(void *v)
522{
523  prompt_Continue((struct prompt *)v);
524}
525
526void
527prompt_Continue(struct prompt *p)
528{
529  timer_Stop(&bgtimer);
530  if (getpgrp() == prompt_pgrp(p)) {
531    prompt_TtyCommandMode(p);
532    p->nonewline = 1;
533    prompt_Required(p);
534    log_ActivatePrompt(p);
535  } else if (!p->owner) {
536    bgtimer.func = prompt_TimedContinue;
537    bgtimer.name = "prompt bg";
538    bgtimer.load = SECTICKS;
539    bgtimer.arg = p;
540    timer_Start(&bgtimer);
541  }
542}
543
544void
545prompt_Suspend(struct prompt *p)
546{
547  if (getpgrp() == prompt_pgrp(p)) {
548    prompt_TtyOldMode(p);
549    log_DeactivatePrompt(p);
550  }
551}
552