shell.c 15.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 2010-2012, 2014-2017 Free Software Foundation, Inc.

   GNU Mailutils is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   GNU Mailutils is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Mailutils.  If not, see <http://www.gnu.org/licenses/>. */

#include "mu.h"
#include <signal.h>
#include "muaux.h"

#ifdef WITH_READLINE
# include <readline/readline.h>
# include <readline/history.h>
#endif

char *mutool_shell_prompt;
static mu_assoc_t mutool_prompt_assoc;
int mutool_shell_interactive;


static int got_signal = 0;

static void
_shell_sig (int sig)
{
  got_signal = sig;
}

#define shell_interrupted() (got_signal == SIGINT)

static void
report_signals ()
{
  switch (got_signal)
    {
    case 0:
      break;

    case SIGINT:
      mu_stream_printf (mu_strerr, _("Interrupt\n"));
      mu_stream_flush (mu_strerr);

    default:
      got_signal = 0;
    }
}

static int shell_exit (int, char **);
static int shell_help (int, char **);
static int shell_prompt (int, char **);
#ifdef WITH_READLINE
static int shell_history (int, char **);
#endif

struct mutool_command default_comtab[] = {
  { "prompt",     1, 2, 0, shell_prompt,
    N_("STRING"),
    N_("set command prompt") },
  { "exit",       1, 1, 0, shell_exit,    NULL,        N_("exit program") },
  { "help",       1, 2, 0, shell_help,
    N_("[COMMAND]"),
    N_("display this text") },
  { "?",          1, 1, 0, shell_help,
    N_("[COMMAND]"),
    N_("synonym for `help'") },
#ifdef WITH_READLINE
  { "history",    1, 1, 0, shell_history,
    NULL,
    N_("show command history") },
#endif
  { NULL }
};

#define DESCRCOL 25
#define NUMCOLS  80
#define DESCRWIDTH (NUMCOLS - DESCRCOL)

/* Print a single comtab entry */
static void
print_comtab (mu_stream_t stream, struct mutool_command *tab)
{
  size_t size = 0;
  const char *text;
  
  if (tab->docstring == NULL)
    return;

  mu_stream_printf (stream, "%s ", tab->name);
  size += strlen (tab->name) + 1;
  if (tab->argdoc)
    {
      text = gettext (tab->argdoc);
      mu_stream_printf (stream, "%s", text);
      size += strlen (text);
    }
  if (size >= DESCRCOL)
    mu_stream_printf (stream, "\n%-*s", DESCRCOL, "");
  else
    mu_stream_printf (stream, "%-*s", (int) (DESCRCOL - size), "");

  text = gettext (tab->docstring);
  size = strlen (text);
  
  while (*text)
    {
      size_t len = size;
      if (len > DESCRWIDTH)
	{
	  /* Fold the text */
	  size_t n = 0;
	  
	  while (n < len)
	    {
	      size_t delta;
	      char *p;
	      
	      p = mu_str_skip_cset_comp (text + n, " \t");
	      delta = p - (text + n);
	      if (n + delta > DESCRWIDTH)
		break;
	      n += delta;
	      
	      p = mu_str_skip_cset (text + n, " \t");
	      delta = p - (text + n);
	      if (n + delta > DESCRWIDTH)
		break;
	      n += delta;
	    }

	  len = n;
	}
      mu_stream_write (stream, text, len, NULL);
      text += len;
      size -= len;
      mu_stream_write (stream, "\n", 1, NULL);
      if (size)
	mu_stream_printf (stream, "%-*s", DESCRCOL, "");
    }
}  

/* Print a single comtab entry.
   FIXME: Way too primitive. Rewrite. */
int
print_help (mu_stream_t stream, struct mutool_command *tab, size_t n)
{
  if (n)
    {
      for (; n > 0 && tab->name; tab++, n--)
	print_comtab (stream, tab);
    }
  else
    {
      for (; tab->name; tab++)
	print_comtab (stream, tab);
    }
  return 0;
}

/* Print all commands from TAB matching NAME.
   FIXME: Way too primitive. Rewrite. */
void
list_commands (struct mutool_command *tab, const char *name)
{
  size_t namelen = strlen (name);
  int printed = 0;
  
  for (; tab->name; tab++)
    {
      /* Print in six columns. */
      if (printed == 6)
	{
	  printed = 0;
	  mu_printf ("\n");
	}
      if (mu_c_strncasecmp (tab->name, name, namelen) == 0)
	{
	  mu_printf ("%s\t", tab->name);
	  printed++;
	}
    }
  if (printed && printed < 6)
    mu_printf ("\n");
}

static struct mutool_command *
simple_find_command (struct mutool_command *cp, const char *name)
{
  for (; cp->name; cp++)
    if (strcmp (cp->name, name) == 0)
      return cp;
  return NULL;
}


static struct mutool_command *shell_comtab;
static size_t user_command_count;

static struct mutool_command *
find_command (const char *name)
{
  return simple_find_command (shell_comtab, name);
}

/* Print out help for ARG, or for all of the commands if ARG is
   not present. */
int
shell_help (int argc, char **argv)
{
  char *name = argv[1];
  
  if (name)
    {
      struct mutool_command *com = find_command (argv[1]);

      if (com)
	print_comtab (mu_strout, com);
      else
	{
	  mu_printf ("No commands match `%s'.  Possibilities are:\n", name);
	  list_commands (shell_comtab, name);
	}
    }
  else
    {
      mu_stream_t str = mutool_open_pager ();
      print_help (str, shell_comtab, user_command_count);
      mu_stream_printf (str, "\n");
      print_help (str, shell_comtab + user_command_count, 0);
      mu_stream_destroy (&str);
    }
  return 0;
}

static int
shell_prompt (int argc, char **argv)
{
  free (mutool_shell_prompt);
  mutool_shell_prompt = mu_strdup (argv[1]);
  return 0;
}

mu_stream_t
mutool_open_pager ()
{
  char *pager;
  if (mutool_shell_interactive && (pager = getenv ("PAGER")) != NULL)
    {
      mu_stream_t stream;
      int rc = mu_command_stream_create (&stream, pager, MU_STREAM_WRITE);
      if (rc == 0)
	return stream;
      mu_error (_("cannot start pager: %s"), mu_strerror (rc));
    }
  mu_stream_ref (mu_strout);
  return mu_strout;
}


#ifdef WITH_READLINE
#define HISTFILE_PREFIX "~/.mu_"
#define HISTFILE_SUFFIX "_history"

static char *
get_history_file_name ()
{
  static char *filename = NULL;

  if (!filename)
    {
      char *hname;
      
      hname = mu_alloc (sizeof HISTFILE_PREFIX + strlen (rl_readline_name) +
		        sizeof HISTFILE_SUFFIX - 1);
      strcpy (hname, HISTFILE_PREFIX);
      strcat (hname, rl_readline_name);
      strcat (hname, HISTFILE_SUFFIX);
      filename = mu_tilde_expansion (hname, MU_HIERARCHY_DELIMITER, NULL);
      free (hname);
    }
  return filename;
}

static int
_shell_getc (FILE *stream)
{
  unsigned char c;

  while (1)
    {
      if (read (fileno (stream), &c, 1) == 1)
	return c;
      if (errno == EINTR)
	{
	  if (shell_interrupted ())
	    break;
	  /* keep going if we handled the signal */
	}
      else
	break;
    }
  return EOF;
}

/* Interface to Readline Completion */

static char *shell_command_generator (const char *, int);
static char **shell_completion (char *, int, int);

/* Tell the GNU Readline library how to complete.  We want to try to complete
   on command names if this is the first word in the line, or on filenames
   if not. */
void
mutool_initialize_readline (const char *name)
{
  /* Allow conditional parsing of the ~/.inputrc file. */
  rl_readline_name = (char *) name;
  rl_attempted_completion_function =
    (rl_completion_func_t*) shell_completion;
  rl_getc_function = _shell_getc;
  read_history (get_history_file_name ());
}

static void
finish_readline ()
{
  write_history (get_history_file_name ());
}

/* Attempt to complete on the contents of TEXT.  START and END bound the
   region of rl_line_buffer that contains the word to complete.  TEXT is
   the word to complete.  We can use the entire contents of rl_line_buffer
   in case we want to do some simple parsing.  Return the array of matches,
   or NULL if there aren't any. */
static char **
shell_completion (char *text, int start, int end MU_ARG_UNUSED)
{
  char **matches;

  matches = (char **) NULL;

  /* If this word is at the start of the line, then it is a command
     to complete.  Otherwise it is the name of a file in the current
     directory. */
  if (start == 0)
    matches = rl_completion_matches (text, shell_command_generator);

  return (matches);
}

/* Generator function for command completion.  STATE lets us know whether
   to start from scratch; without any state (i.e. STATE == 0), then we
   start at the top of the list. */
static char *
shell_command_generator (const char *text, int state)
{
  const char *name;
  static int len;
  static struct mutool_command *cmd;

  /* If this is a new word to complete, initialize now.  This includes
     saving the length of TEXT for efficiency, and initializing the index
     variable to 0. */
  if (!state)
    {
      cmd = shell_comtab;
      len = strlen (text);
    }

  if (!cmd->name)
    return NULL;
    
  
  /* Return the next name which partially matches from the command list. */
  while ((name = cmd->name))
    {
      cmd++;
      if (strncmp (name, text, len) == 0)
	return mu_strdup (name);
    }

  /* If no names matched, then return NULL. */
  return NULL;
}

static char *pre_input_line;

static int
pre_input (void)
{
  rl_insert_text (pre_input_line);
  free (pre_input_line);
  rl_pre_input_hook = NULL;
  rl_redisplay ();
  return 0;
}

static int
retrieve_history (char *str)
{
  char *out;
  int rc;

  rc = history_expand (str, &out);
  switch (rc)
    {
    case -1:
      mu_error ("%s", out);
      free (out);
      return 1;

    case 0:
      break;

    case 1:
      pre_input_line = out;
      rl_pre_input_hook = pre_input;
      return 1;

    case 2:
      mu_printf ("%s\n", out);
      free (out);
      return 1;
    }
  return 0;
}

static int
shell_history (int argc, char **argv)
{
  int i;
  HIST_ENTRY **hlist;
  mu_stream_t out = mutool_open_pager ();
  
  hlist = history_list ();
  for (i = 0; i < history_length; i++)
    mu_stream_printf (out, "%4d) %s\n", i + 1, hlist[i]->line);

  mu_stream_destroy (&out);
  return 0;
}

#else
# define finish_readline()
# define mutool_initialize_readline(name)

char *
readline (char *prompt)
{
  static size_t size = 0;
  static char *buf = NULL;
  size_t n;

  if (prompt)
    {
      mu_printf ("%s", prompt);
      mu_stream_flush (mu_strout);
    }
  if (mu_stream_getline (mu_strin, &buf, &size, &n) || n == 0)
    {
      free (buf);
      buf = NULL;
      size = 0;
      return NULL;
    }
  return buf;
}

void
add_history (const char *s MU_ARG_UNUSED)
{
}
#endif

static int
next_arg (struct mu_wordsplit *ws)
{
  int rc = mu_wordsplit (NULL, ws, MU_WRDSF_INCREMENTAL);
  if (rc == MU_WRDSE_NOINPUT)
    {
      mu_error ("%s: too few arguments", ws->ws_wordv[0]);
      mu_wordsplit_free (ws);
      return -1;
    }
  else if (rc)
    {
      mu_error ("cannot parse input line: %s",
		mu_wordsplit_strerror (ws));
      return 1;
    }
  return 0;
}

/* Parse and execute a command line. */
int
execute_line (char *line)
{
  int rc;
  struct mu_wordsplit ws;
  struct mutool_command *cmd;
  int status = 0;
  
  ws.ws_comment = "#";
  ws.ws_escape[0] = ws.ws_escape[1] = "\\\\\"\"";
  rc = mu_wordsplit (line, &ws,
		     MU_WRDSF_DEFFLAGS|MU_WRDSF_COMMENT|MU_WRDSF_ESCAPE|
		     MU_WRDSF_INCREMENTAL|MU_WRDSF_APPEND);
  if (rc == MU_WRDSE_NOINPUT)
    {
      mu_wordsplit_free (&ws);
      return 0;
    }
  else if (rc)
    {
      mu_error ("cannot parse input line: %s", mu_wordsplit_strerror (&ws));
      return 0;
    }
  
  if (ws.ws_wordc)
    {
      int argmin;
      cmd = find_command (ws.ws_wordv[0]);

      if (!cmd)
	{
	  mu_error ("%s: no such command.", ws.ws_wordv[0]);
	  mu_wordsplit_free (&ws);
	  return 0;
	}

      argmin = cmd->argmin;
      if (cmd->flags & CMD_COALESCE_EXTRA_ARGS)
	--argmin;
      while (ws.ws_wordc < argmin)
	{
	  if (next_arg (&ws))
	    return 0;
	}

      if (cmd->flags & CMD_COALESCE_EXTRA_ARGS)
	{
	  ws.ws_flags |= MU_WRDSF_NOSPLIT;
	  if (next_arg (&ws))
	    return 0;
	}
      else
	{
	  for (;;)
	    {
	      if (cmd->argmax > 0 && ws.ws_wordc > cmd->argmax)
		{
		  mu_error ("%s: too many arguments", ws.ws_wordv[0]);
		  mu_wordsplit_free (&ws);
		  return 0;
		}
	      rc = mu_wordsplit (NULL, &ws, MU_WRDSF_INCREMENTAL);
	      if (rc == 0)
		continue;
	      else if (rc == MU_WRDSE_NOINPUT)
		break;
	      else
		{
		  mu_error ("cannot parse input line: %s",
			    mu_wordsplit_strerror (&ws));
		  return 0;
		}
	    }
	}

      status = cmd->func (ws.ws_wordc, ws.ws_wordv);
    }
  mu_wordsplit_free (&ws);
  return status;
}

static char *
input_line_interactive ()
{
  char *line, *prompt;
  int rc;
  
  report_signals ();
  rc = mu_str_expand (&prompt, mutool_shell_prompt, mutool_prompt_assoc);
  if (rc)
    {
      if (rc == MU_ERR_FAILURE)
	mu_error (_("cannot expand prompt: %s"), prompt);
      else
	mu_error (_("cannot expand prompt: %s"), mu_strerror (rc));
      exit (1);
    }

  line = readline (prompt);
  free (prompt);
  return line;
}

static char *
input_line_script ()
{
  size_t size = 0, n;
  char *buf = NULL;

  report_signals ();
  if (mu_stream_getline (mu_strin, &buf, &size, &n) || n == 0)
    return NULL;
  return buf;
}

static int done;

static int
shell_exit (int argc MU_ARG_UNUSED, char **argv MU_ARG_UNUSED)
{
  done = 1;
  return 0;
}

mu_assoc_t
mutool_shell_prompt_assoc (void)
{
  if (mutool_prompt_assoc)
    mu_assoc_clear (mutool_prompt_assoc);
  else
    {
      int rc = mu_assoc_create (&mutool_prompt_assoc, 0);
      if (rc)
	{
	  mu_diag_funcall (MU_DIAG_ERROR, "mu_assoc_create", NULL, rc);
	  exit (1);
	}
    }
  mu_assoc_install (mutool_prompt_assoc, "program-name", mu_program_name);
  mu_assoc_install (mutool_prompt_assoc, "canonical-program-name",
		    "mailutils");
  mu_assoc_install (mutool_prompt_assoc, "package", PACKAGE);
  mu_assoc_install (mutool_prompt_assoc, "version", PACKAGE_VERSION);

  return mutool_prompt_assoc;
}

int
mutool_shell (const char *name, struct mutool_command *cmd)
{
  size_t n;
  char *(*input_line) ();
  static int sigv[] = { SIGPIPE, SIGINT };
				   
  mutool_shell_interactive = isatty (0);
  input_line = mutool_shell_interactive ?
                             input_line_interactive : input_line_script;

  for (n = 0; cmd[n].name; n++)
    ;

  user_command_count = n;
  shell_comtab = mu_calloc (n + MU_ARRAY_SIZE (default_comtab),
			    sizeof (shell_comtab[0]));
  memcpy (shell_comtab, cmd, n * sizeof (shell_comtab[0]));
  memcpy (shell_comtab + n, default_comtab, sizeof (default_comtab));

  mutool_initialize_readline (name);
  mu_set_signals (_shell_sig, sigv, MU_ARRAY_SIZE (sigv));
  while (!done)
    {
      char *s, *line = input_line ();
      if (!line)
	{
	  if (shell_interrupted ())
	    {
	      report_signals ();
	      continue;
	    }
	  else
	    {
	      mu_printf ("\n");
	      break;
	    }
	}
      
      /* Remove leading and trailing whitespace from the line.
         Then, if there is anything left, add it to the history list
         and execute it. */
      s = mu_str_stripws (line);

      if (*s)
	{
	  int status;

#ifdef WITH_READLINE
	  if (mutool_shell_interactive)
	    {
	      if (retrieve_history (s))
		continue;
	      add_history (s);
	    }
#endif

	  status = execute_line (s);
	  if (status != 0)
	    mu_error ("Error: %s", mu_strerror (status));
	}

      free (line);
    }
  if (mutool_shell_interactive)
    finish_readline ();
  mu_stream_destroy (&mu_strin);
  mu_stream_destroy (&mu_strout);
  return 0;
}