Home | History | Annotate | Line # | Download | only in mail
complete.c revision 1.9
      1 /*	$NetBSD: complete.c,v 1.9 2006/10/21 21:37:20 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2000,2005,2006 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Luke Mewburn.
      9  *
     10  * Additions by Anon Ymous. (2006)
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the NetBSD
     23  *	Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /* Most of this is derived or copied from src/usr.bin/ftp/complete.c (1.41). */
     42 
     43 
     44 #ifdef USE_EDITLINE
     45 #undef NO_EDITCOMPLETE
     46 
     47 #include <sys/cdefs.h>
     48 #ifndef lint
     49 __RCSID("$NetBSD: complete.c,v 1.9 2006/10/21 21:37:20 christos Exp $");
     50 #endif /* not lint */
     51 
     52 /*
     53  * FTP user program - command and file completion routines
     54  */
     55 
     56 #include <sys/stat.h>
     57 
     58 #include <ctype.h>
     59 #include <err.h>
     60 #include <dirent.h>
     61 #include <glob.h>
     62 #include <stdio.h>
     63 #include <stdlib.h>
     64 #include <string.h>
     65 #include <sys/param.h>
     66 #include <stringlist.h>
     67 #include <util.h>
     68 
     69 #include "rcv.h"			/* includes "glob.h" */
     70 #include "extern.h"
     71 #include "complete.h"
     72 #ifdef MIME_SUPPORT
     73 #include "mime.h"
     74 #endif
     75 
     76 /*
     77  * Global variables
     78  */
     79 static int doglob = 1;			/* glob local file names */
     80 
     81 #define ttyout stdout
     82 #define ttywidth screenwidth		/* in "glob.h" */
     83 #define ttyheight screenheight		/* in "glob.h" */
     84 
     85 
     86 /* This should find the first command that matches the name given or
     87  * NULL if none.  Use the routine from mail in lex.c.
     88  */
     89 #define getcmd(w) lex(w)
     90 
     91 /************************************************************************/
     92 /* from src/usr.bin/ftp/utils.h (1.135) - begin */
     93 
     94 /*
     95  * List words in stringlist, vertically arranged
     96  */
     97 static void
     98 list_vertical(StringList *sl)
     99 {
    100 	int i, j;
    101 	int columns, lines;
    102 	char *p;
    103 	size_t w, width;
    104 
    105 	width = 0;
    106 
    107 	for (i = 0; i < sl->sl_cur; i++) {
    108 		w = strlen(sl->sl_str[i]);
    109 		if (w > width)
    110 			width = w;
    111 	}
    112 	width = (width + 8) &~ 7;
    113 
    114 	columns = ttywidth / width;
    115 	if (columns == 0)
    116 		columns = 1;
    117 	lines = (sl->sl_cur + columns - 1) / columns;
    118 	for (i = 0; i < lines; i++) {
    119 		for (j = 0; j < columns; j++) {
    120 			p = sl->sl_str[j * lines + i];
    121 			if (p)
    122 				(void)fputs(p, ttyout);
    123 			if (j * lines + i + lines >= sl->sl_cur) {
    124 				(void)putc('\n', ttyout);
    125 				break;
    126 			}
    127 			if (p) {
    128 				w = strlen(p);
    129 				while (w < width) {
    130 					w = (w + 8) &~ 7;
    131 					(void)putc('\t', ttyout);
    132 				}
    133 			}
    134 		}
    135 	}
    136 }
    137 
    138 /*
    139  * Copy characters from src into dst, \ quoting characters that require it
    140  */
    141 static void
    142 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
    143 {
    144 	int	di, si;
    145 
    146 	for (di = si = 0;
    147 	    src[si] != '\0' && di < dstlen && si < srclen;
    148 	    di++, si++) {
    149 		switch (src[si]) {
    150 		case '\\':
    151 		case ' ':
    152 		case '\t':
    153 		case '\r':
    154 		case '\n':
    155 		case '"':
    156 			dst[di++] = '\\';
    157 			if (di >= dstlen)
    158 				break;
    159 			/* FALLTHROUGH */
    160 		default:
    161 			dst[di] = src[si];
    162 		}
    163 	}
    164 	dst[di] = '\0';
    165 }
    166 
    167 /*
    168  * sl_init() with inbuilt error checking
    169  */
    170 static StringList *
    171 mail_sl_init(void)
    172 {
    173 	StringList *p;
    174 
    175 	p = sl_init();
    176 	if (p == NULL)
    177 		err(1, "Unable to allocate memory for stringlist");
    178 	return (p);
    179 }
    180 
    181 
    182 /*
    183  * sl_add() with inbuilt error checking
    184  */
    185 static void
    186 mail_sl_add(StringList *sl, char *i)
    187 {
    188 
    189 	if (sl_add(sl, i) == -1)
    190 		err(1, "Unable to add `%s' to stringlist", i);
    191 }
    192 
    193 
    194 /*
    195  * Glob a local file name specification with the expectation of a single
    196  * return value. Can't control multiple values being expanded from the
    197  * expression, we return only the first.
    198  * Returns NULL on error, or a pointer to a buffer containing the filename
    199  * that's the caller's responsiblity to free(3) when finished with.
    200  */
    201 static char *
    202 globulize(const char *pattern)
    203 {
    204 	glob_t gl;
    205 	int flags;
    206 	char *p;
    207 
    208 	if (!doglob)
    209 		return estrdup(pattern);
    210 
    211 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    212 	(void)memset(&gl, 0, sizeof(gl));
    213 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
    214 		warnx("%s: not found", pattern);
    215 		globfree(&gl);
    216 		return (NULL);
    217 	}
    218 	p = estrdup(gl.gl_pathv[0]);
    219 	globfree(&gl);
    220 	return (p);
    221 }
    222 
    223 /* from src/usr.bin/ftp/utils.h (1.135) - end */
    224 /************************************************************************/
    225 
    226 static int
    227 comparstr(const void *a, const void *b)
    228 {
    229 	return (strcmp(*(const char * const *)a, *(const char * const *)b));
    230 }
    231 
    232 /*
    233  * Determine if complete is ambiguous. If unique, insert.
    234  * If no choices, error. If unambiguous prefix, insert that.
    235  * Otherwise, list choices. words is assumed to be filtered
    236  * to only contain possible choices.
    237  * Args:
    238  *	word	word which started the match
    239  *	dolist	list by default
    240  *	words	stringlist containing possible matches
    241  * Returns a result as per el_set(EL_ADDFN, ...)
    242  */
    243 static unsigned char
    244 complete_ambiguous(EditLine *el, char *word, int dolist, StringList *words)
    245 {
    246 	char insertstr[MAXPATHLEN];
    247 	char *lastmatch, *p;
    248 	int i, j;
    249 	size_t matchlen, wordlen;
    250 
    251 	wordlen = strlen(word);
    252 	if (words->sl_cur == 0)
    253 		return (CC_ERROR);	/* no choices available */
    254 
    255 	if (words->sl_cur == 1) {	/* only once choice available */
    256 		p = words->sl_str[0] + wordlen;
    257 		if (*p == '\0')		/* at end of word? */
    258 			return (CC_REFRESH);
    259 		ftpvis(insertstr, sizeof(insertstr), p, strlen(p));
    260 		if (el_insertstr(el, insertstr) == -1)
    261 			return (CC_ERROR);
    262 		else
    263 			return (CC_REFRESH);
    264 	}
    265 
    266 	if (!dolist) {
    267 		matchlen = 0;
    268 		lastmatch = words->sl_str[0];
    269 		matchlen = strlen(lastmatch);
    270 		for (i = 1; i < words->sl_cur; i++) {
    271 			for (j = wordlen; j < strlen(words->sl_str[i]); j++)
    272 				if (lastmatch[j] != words->sl_str[i][j])
    273 					break;
    274 			if (j < matchlen)
    275 				matchlen = j;
    276 		}
    277 		if (matchlen > wordlen) {
    278 			ftpvis(insertstr, sizeof(insertstr),
    279 			    lastmatch + wordlen, matchlen - wordlen);
    280 			if (el_insertstr(el, insertstr) == -1)
    281 				return (CC_ERROR);
    282 			else
    283 				return (CC_REFRESH_BEEP);
    284 		}
    285 	}
    286 
    287 	(void)putc('\n', ttyout);
    288 	qsort(words->sl_str, words->sl_cur, sizeof(char *), comparstr);
    289 	list_vertical(words);
    290 	return (CC_REDISPLAY);
    291 }
    292 
    293 /*
    294  * Complete a mail command.
    295  */
    296 static unsigned char
    297 complete_command(EditLine *el, char *word, int dolist)
    298 {
    299 	const struct cmd *c;
    300 	StringList *words;
    301 	size_t wordlen;
    302 	unsigned char rv;
    303 
    304 	words = mail_sl_init();
    305 	wordlen = strlen(word);
    306 
    307 	for (c = cmdtab; c->c_name != NULL; c++) {
    308 		if (wordlen > strlen(c->c_name))
    309 			continue;
    310 		if (strncmp(word, c->c_name, wordlen) == 0)
    311 			mail_sl_add(words, __UNCONST(c->c_name));
    312 	}
    313 
    314 	rv = complete_ambiguous(el, word, dolist, words);
    315 	if (rv == CC_REFRESH) {
    316 		if (el_insertstr(el, " ") == -1)
    317 			rv = CC_ERROR;
    318 	}
    319 	sl_free(words, 0);
    320 	return (rv);
    321 }
    322 
    323 /*
    324  * Complete a local filename.
    325  */
    326 static unsigned char
    327 complete_filename(EditLine *el, char *word, int dolist)
    328 {
    329 	StringList *words;
    330 	char dir[MAXPATHLEN];
    331 	char *fname;
    332 	DIR *dd;
    333 	struct dirent *dp;
    334 	unsigned char rv;
    335 	size_t len;
    336 
    337 	if ((fname = strrchr(word, '/')) == NULL) {
    338 		dir[0] = '.';
    339 		dir[1] = '\0';
    340 		fname = word;
    341 	} else {
    342 		if (fname == word) {
    343 			dir[0] = '/';
    344 			dir[1] = '\0';
    345 		} else {
    346 			len = fname - word + 1;
    347 			(void)estrlcpy(dir, word, sizeof(dir));
    348 			dir[len] = '\0';
    349 		}
    350 		fname++;
    351 	}
    352 	if (dir[0] == '~') {
    353 		char *p;
    354 
    355 		if ((p = globulize(dir)) == NULL)
    356 			return (CC_ERROR);
    357 		(void)estrlcpy(dir, p, sizeof(dir));
    358 		free(p);
    359 	}
    360 
    361 	if ((dd = opendir(dir)) == NULL)
    362 		return (CC_ERROR);
    363 
    364 	words = mail_sl_init();
    365 	len = strlen(fname);
    366 
    367 	for (dp = readdir(dd); dp != NULL; dp = readdir(dd)) {
    368 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
    369 			continue;
    370 
    371 #if defined(DIRENT_MISSING_D_NAMLEN)
    372 		if (len > strlen(dp->d_name))
    373 			continue;
    374 #else
    375 		if (len > dp->d_namlen)
    376 			continue;
    377 #endif
    378 		if (strncmp(fname, dp->d_name, len) == 0) {
    379 			char *tcp;
    380 
    381 			tcp = estrdup(dp->d_name);
    382 			mail_sl_add(words, tcp);
    383 		}
    384 	}
    385 	(void)closedir(dd);
    386 
    387 	rv = complete_ambiguous(el, fname, dolist, words);
    388 	if (rv == CC_REFRESH) {
    389 		struct stat sb;
    390 		char path[MAXPATHLEN];
    391 
    392 		(void)estrlcpy(path, dir,		sizeof(path));
    393 		(void)estrlcat(path, "/",		sizeof(path));
    394 		(void)estrlcat(path, words->sl_str[0],	sizeof(path));
    395 
    396 		if (stat(path, &sb) >= 0) {
    397 			char suffix[2] = " ";
    398 
    399 			if (S_ISDIR(sb.st_mode))
    400 				suffix[0] = '/';
    401 			if (el_insertstr(el, suffix) == -1)
    402 				rv = CC_ERROR;
    403 		}
    404 	}
    405 	sl_free(words, 1);
    406 	return (rv);
    407 }
    408 
    409 static int
    410 find_execs(char *word, char *path, StringList *list)
    411 {
    412 	char *sep;
    413 	char *dir=path;
    414 	DIR *dd;
    415 	struct dirent *dp;
    416 	size_t len = strlen(word);
    417 	uid_t uid = getuid();
    418 	gid_t gid = getgid();
    419 
    420 	for (sep = dir; sep; dir = sep + 1) {
    421 		if ((sep=strchr(dir, ':')) != NULL) {
    422 			*sep=0;
    423 		}
    424 
    425 		if ((dd = opendir(dir)) == NULL) {
    426 			perror("dir");
    427 			return -1;
    428 		}
    429 
    430 		for (dp = readdir(dd); dp != NULL; dp = readdir(dd)) {
    431 
    432 			if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
    433 				continue;
    434 
    435 #if defined(DIRENT_MISSING_D_NAMLEN)
    436 			if (len > strlen(dp->d_name))
    437 				continue;
    438 #else
    439 			if (len > dp->d_namlen)
    440 				continue;
    441 #endif
    442 
    443 			if (strncmp(word, dp->d_name, len) == 0) {
    444 				struct stat sb;
    445 				char pathname[ MAXPATHLEN ];
    446 				unsigned mask;
    447 
    448 				(void)snprintf(pathname, sizeof(pathname),
    449 				    "%s/%s", dir, dp->d_name);
    450 				if (stat(pathname, &sb) != 0) {
    451 					perror(pathname);
    452 					continue;
    453 				}
    454 
    455 				mask = 0001;
    456 				if (sb.st_uid == uid)	mask |= 0100;
    457 				if (sb.st_gid == gid)	mask |= 0010;
    458 
    459 				if ((sb.st_mode & mask) != 0) {
    460 					char *tcp;
    461 					tcp = estrdup(dp->d_name);
    462 					mail_sl_add(list, tcp);
    463 				}
    464 			}
    465 
    466 		}
    467 
    468 		(void)closedir(dd);
    469 	}
    470 
    471 	return 0;
    472 }
    473 
    474 
    475 /*
    476  * Complete a local executable
    477  */
    478 static unsigned char
    479 complete_executable(EditLine *el, char *word, int dolist)
    480 {
    481 	StringList *words;
    482 	char dir[ MAXPATHLEN ];
    483 	char *fname;
    484 	unsigned char rv;
    485 	size_t len;
    486 	int error;
    487 
    488 	if ((fname = strrchr(word, '/')) == NULL) {
    489 		dir[0] = '\0';		/* walk the path */
    490 		fname = word;
    491 	} else {
    492 		if (fname == word) {
    493 			dir[0] = '/';
    494 			dir[1] = '\0';
    495 		} else {
    496 			len = fname - word;
    497 			(void)strncpy(dir, word, len);
    498 			dir[fname - word] = '\0';
    499 		}
    500 		fname++;
    501 	}
    502 
    503 	words = sl_init();
    504 
    505 	if (*dir == '\0') {		/* walk path */
    506 		char *env;
    507 		char *path;
    508 		env = getenv("PATH");
    509 		len = strlen(env);
    510 		path = salloc(len + 1);
    511 		(void)strcpy(path, env);
    512 		error = find_execs(word, path, words);
    513 	}
    514 	else {		/* check specified dir only */
    515 		error = find_execs(word, dir, words);
    516 	}
    517 	if (error != 0)
    518 		return CC_ERROR;
    519 
    520 	rv = complete_ambiguous(el, fname, dolist, words);
    521 
    522 	if (rv == CC_REFRESH)
    523 		if (el_insertstr(el, " ") == -1)
    524 			rv = CC_ERROR;
    525 
    526 	sl_free(words, 1);
    527 
    528 	return (rv);
    529 }
    530 
    531 
    532 static unsigned
    533 char complete_set(EditLine *el, char *word, int dolist)
    534 {
    535 	struct var *vp;
    536 	char **ap;
    537 	char **p;
    538 	int h;
    539 	int s;
    540 	size_t len = strlen(word);
    541 	StringList *words;
    542 	unsigned char rv;
    543 
    544 	words = sl_init();
    545 
    546 	/* allocate space for variables table */
    547 	for (h = 0, s = 1; h < HSHSIZE; h++)
    548 		for (vp = variables[h]; vp != NULL; vp = vp->v_link)
    549 			s++;
    550 	ap = (char **) salloc(s * sizeof *ap);
    551 
    552 	/* save pointers */
    553 	for (h = 0, p = ap; h < HSHSIZE; h++)
    554 		for (vp = variables[h]; vp != NULL; vp = vp->v_link)
    555 			*p++ = vp->v_name;
    556 	*p = NULL;
    557 
    558 	/* sort pointers */
    559 	sort(ap);
    560 
    561 	/* complete on list */
    562 	for (p = ap; *p != NULL; p++) {
    563 		if (len == 0 || strncmp(*p, word, len) == 0) {
    564 			char *tcp;
    565 			tcp = estrdup(*p);
    566 			mail_sl_add(words, tcp);
    567 		}
    568 	}
    569 
    570 	rv = complete_ambiguous(el, word, dolist, words);
    571 
    572 	sl_free(words, 1);
    573 
    574 	return(rv);
    575 }
    576 
    577 
    578 
    579 
    580 
    581 static unsigned char
    582 complete_alias(EditLine *el, char *word, int dolist)
    583 {
    584 	struct grouphead *gh;
    585 	char **ap;
    586 	char **p;
    587 	int h;
    588 	int s;
    589 	size_t len = strlen(word);
    590 	StringList *words;
    591 	unsigned char rv;
    592 
    593 	words = sl_init();
    594 
    595 	/* allocate space for alias table */
    596 	for (h = 0, s = 1; h < HSHSIZE; h++)
    597 		for (gh = groups[h]; gh != NULL; gh = gh->g_link)
    598 			s++;
    599 	ap = (char **) salloc(s * sizeof *ap);
    600 
    601 	/* save pointers */
    602 	for (h = 0, p = ap; h < HSHSIZE; h++)
    603 		for (gh = groups[h]; gh != NULL; gh = gh->g_link)
    604 			*p++ = gh->g_name;
    605 	*p = NULL;
    606 
    607 	/* sort pointers */
    608 	sort(ap);
    609 
    610 	/* complete on list */
    611 	for (p = ap; *p != NULL; p++) {
    612 		if (len == 0 || strncmp(*p, word, len) == 0) {
    613 			char *tcp;
    614 			tcp = estrdup(*p);
    615 			mail_sl_add(words, tcp);
    616 		}
    617 	}
    618 
    619 	rv = complete_ambiguous(el, word, dolist, words);
    620 	if (rv == CC_REFRESH)
    621 		if (el_insertstr(el, " ") == -1)
    622 			rv = CC_ERROR;
    623 
    624 	sl_free(words, 1);
    625 
    626 	return(rv);
    627 }
    628 
    629 
    630 
    631 static char	*stringbase;	/* current scan point in line buffer */
    632 static char	*argbase;	/* current storage point in arg buffer */
    633 static StringList *marg_sl;	/* stringlist containing margv */
    634 static int	margc;		/* count of arguments on input line */
    635 #define margv (marg_sl->sl_str)	/* args parsed from input line */
    636 
    637 static char *cursor_pos;
    638 static int   cursor_argc;
    639 static int   cursor_argo;
    640 
    641 static void
    642 init_complete(void)
    643 {
    644 	marg_sl = sl_init();
    645 	return;
    646 }
    647 
    648 
    649 
    650 /************************************************************************/
    651 /* from /usr/src/usr.bin/ftp/main.c(1.101) - begin */
    652 
    653 static int   slrflag;
    654 #ifdef NEED_ALTARG
    655 static char *altarg;		/* argv[1] with no shell-like preprocessing  */
    656 #endif
    657 
    658 #ifdef NO_EDITCOMPLETE
    659 #define	INC_CHKCURSOR(x)	(x)++
    660 #else  /* !NO_EDITCOMPLETE */
    661 #define	INC_CHKCURSOR(x)				\
    662 	do {						\
    663 		(x)++;					\
    664 		if (x == cursor_pos) {			\
    665 			cursor_argc = margc;		\
    666 			cursor_argo = ap - argbase;	\
    667 			cursor_pos  = NULL;		\
    668 		}					\
    669 	} while(/* CONSTCOND */ 0)
    670 #endif /* !NO_EDITCOMPLETE */
    671 
    672 /*
    673  * Parse string into argbuf;
    674  * implemented with FSM to
    675  * handle quoting and strings
    676  */
    677 static char *
    678 slurpstring(void)
    679 {
    680 	int got_one = 0;
    681 	char *sb = stringbase;
    682 	char *ap = argbase;
    683 	char *tmp = argbase;		/* will return this if token found */
    684 
    685 	if (*sb == '!' || *sb == '$') {	/* recognize ! as a token for shell */
    686 		switch (slrflag) {	/* and $ as token for macro invoke */
    687 			case 0:
    688 				slrflag++;
    689 				INC_CHKCURSOR(stringbase);
    690 				return __UNCONST((*sb == '!') ? "!" : "$");
    691 				/* NOTREACHED */
    692 			case 1:
    693 				slrflag++;
    694 #ifdef NEED_ALTARG
    695 				altarg = stringbase;
    696 #endif
    697 				break;
    698 			default:
    699 				break;
    700 		}
    701 	}
    702 
    703 S0:
    704 	switch (*sb) {
    705 
    706 	case '\0':
    707 		goto OUT;
    708 
    709 	case ' ':
    710 	case '\t':
    711 		INC_CHKCURSOR(sb);
    712 		goto S0;
    713 
    714 	default:
    715 		switch (slrflag) {
    716 			case 0:
    717 				slrflag++;
    718 				break;
    719 			case 1:
    720 				slrflag++;
    721 #ifdef NEED_ALTARG
    722 				altarg = sb;
    723 #endif
    724 				break;
    725 			default:
    726 				break;
    727 		}
    728 		goto S1;
    729 	}
    730 
    731 S1:
    732 	switch (*sb) {
    733 
    734 	case ' ':
    735 	case '\t':
    736 	case '\0':
    737 		goto OUT;	/* end of token */
    738 
    739 	case '\\':
    740 		INC_CHKCURSOR(sb);
    741 		goto S2;	/* slurp next character */
    742 
    743 	case '"':
    744 		INC_CHKCURSOR(sb);
    745 		goto S3;	/* slurp quoted string */
    746 
    747 	default:
    748 		/* the first arg (command) is special - see execute() in lex.c */
    749 		if (margc == 0 && got_one &&
    750 		    strchr(" \t0123456789$^.:/-+*'\"", *sb))
    751 			goto OUT;
    752 
    753 		*ap = *sb;	/* add character to token */
    754 		ap++;
    755 		INC_CHKCURSOR(sb);
    756 		got_one = 1;
    757 		goto S1;
    758 	}
    759 
    760 S2:
    761 	switch (*sb) {
    762 
    763 	case '\0':
    764 		goto OUT;
    765 
    766 	default:
    767 		*ap = *sb;
    768 		ap++;
    769 		INC_CHKCURSOR(sb);
    770 		got_one = 1;
    771 		goto S1;
    772 	}
    773 
    774 S3:
    775 	switch (*sb) {
    776 
    777 	case '\0':
    778 		goto OUT;
    779 
    780 	case '"':
    781 		INC_CHKCURSOR(sb);
    782 		goto S1;
    783 
    784 	default:
    785 		*ap = *sb;
    786 		ap++;
    787 		INC_CHKCURSOR(sb);
    788 		got_one = 1;
    789 		goto S3;
    790 	}
    791 
    792 OUT:
    793 	if (got_one)
    794 		*ap++ = '\0';
    795 	argbase = ap;			/* update storage pointer */
    796 	stringbase = sb;		/* update scan pointer */
    797 	if (got_one) {
    798 		return (tmp);
    799 	}
    800 	switch (slrflag) {
    801 		case 0:
    802 			slrflag++;
    803 			break;
    804 		case 1:
    805 			slrflag++;
    806 #ifdef NEED_ALTARG
    807 			altarg = NULL;
    808 #endif
    809 			break;
    810 		default:
    811 			break;
    812 	}
    813 	return (NULL);
    814 }
    815 
    816 
    817 /*
    818  * Slice a string up into argc/argv.
    819  */
    820 static void
    821 makeargv(char *line)
    822 {
    823 	static char argbuf[ LINESIZE ];	/* argument storage buffer */
    824 	char *argp;
    825 
    826 	stringbase = line;		/* scan from first of buffer */
    827 	argbase = argbuf;		/* store from first of buffer */
    828 	slrflag = 0;
    829 	marg_sl->sl_cur = 0;		/* reset to start of marg_sl */
    830 	for (margc = 0; /* EMPTY */; margc++) {
    831 		argp = slurpstring();
    832 		mail_sl_add(marg_sl, argp);
    833 		if (argp == NULL)
    834 			break;
    835 	}
    836 #ifndef NO_EDITCOMPLETE
    837 	if (cursor_pos == line) {
    838 		cursor_argc = 0;
    839 		cursor_argo = 0;
    840 	} else if (cursor_pos != NULL) {
    841 		cursor_argc = margc;
    842 		cursor_argo = strlen(margv[margc-1]);
    843 	}
    844 #endif /* !NO_EDITCOMPLETE */
    845 }
    846 
    847 /* from /usr/src/usr.bin/ftp/main.c(1.101) - end */
    848 /************************************************************************/
    849 
    850 /* Some people like to bind file completion to CTRL-D.  In emacs mode,
    851  * CTRL-D is also used to delete the current character, we have to
    852  * special case this situation.
    853  */
    854 #define EMACS_CTRL_D_BINDING_HACK
    855 
    856 #ifdef EMACS_CTRL_D_BINDING_HACK
    857 static int
    858 is_emacs_mode(EditLine *el)
    859 {
    860 	char *mode;
    861 	if (el_get(el, EL_EDITOR, &mode) == -1)
    862 		return 0;
    863 	return equal(mode, "emacs");
    864 }
    865 
    866 static int
    867 emacs_ctrl_d(EditLine *el, const LineInfo *lf, int ch, size_t len)
    868 {
    869 	static char delunder[3] = { CTRL('f'), CTRL('h'), '\0' };
    870 	if (ch == CTRL('d') && is_emacs_mode(el)) {	/* CTRL-D is special */
    871 		if (len == 0)
    872 			return (CC_EOF);
    873 		if (lf->lastchar != lf->cursor) { /* delete without using ^D */
    874 			el_push(el, delunder); /* ^F^H */
    875 			return (CC_NORM);
    876 		}
    877 	}
    878 	return -1;
    879 }
    880 #endif /* EMACS_CTRL_D_BINDING_HACK */
    881 
    882 /*
    883  * Generic complete routine
    884  */
    885 static unsigned char
    886 mail_complete(EditLine *el, int ch)
    887 {
    888 	static char line[LINESIZE];	/* input line buffer */
    889 	static char word[LINESIZE];
    890 	static int lastc_argc, lastc_argo;
    891 
    892 	const struct cmd *c;
    893 	const LineInfo *lf;
    894 	int celems, dolist, cmpltype;
    895 	size_t len;
    896 
    897 	lf = el_line(el);
    898 	len = lf->lastchar - lf->buffer;
    899 
    900 #ifdef EMACS_CTRL_D_BINDING_HACK
    901 	{
    902 		int cc_ret;
    903 		if ((cc_ret = emacs_ctrl_d(el, lf, ch, len)) != -1)
    904 			return cc_ret;
    905 	}
    906 #endif /* EMACS_CTRL_D_BINDING_HACK */
    907 
    908 	if (len >= sizeof(line) - 1)
    909 		return (CC_ERROR);
    910 
    911 	(void)strlcpy(line, lf->buffer, len + 1); /* do not use estrlcpy here! */
    912 	cursor_pos = line + (lf->cursor - lf->buffer);
    913 	lastc_argc = cursor_argc;	/* remember last cursor pos */
    914 	lastc_argo = cursor_argo;
    915 	makeargv(line);			/* build argc/argv of current line */
    916 
    917 	if (cursor_argo >= sizeof(word) - 1)
    918 		return (CC_ERROR);
    919 
    920 	dolist = 0;
    921 	/* if cursor and word are the same, list alternatives */
    922 	if (lastc_argc == cursor_argc && lastc_argo == cursor_argo
    923 	    && strncmp(word, margv[cursor_argc] ? margv[cursor_argc] : "",
    924 		(size_t)cursor_argo) == 0)
    925 		dolist = 1;
    926 	else if (cursor_argc < margc)
    927 		(void)strlcpy(word, margv[cursor_argc], (size_t)cursor_argo + 1); /* do not use estrlcpy() here */
    928 	word[cursor_argo] = '\0';
    929 
    930 	if (cursor_argc == 0)
    931 		return (complete_command(el, word, dolist));
    932 
    933 	c = getcmd(margv[0]);
    934 	if (c == NULL)
    935 		return (CC_ERROR);
    936 	celems = strlen(c->c_complete);
    937 
    938 		/* check for 'continuation' completes (which are uppercase) */
    939 	if ((cursor_argc > celems) && (celems > 0)
    940 	    && isupper((unsigned char) c->c_complete[celems-1]))
    941 		cursor_argc = celems;
    942 
    943 	if (cursor_argc > celems)
    944 		return (CC_ERROR);
    945 
    946 	cmpltype = c->c_complete[cursor_argc - 1];
    947 	switch (cmpltype) {
    948 		case 'a':			/* alias complete */
    949 		case 'A':
    950 			return (complete_alias(el, word, dolist));
    951 
    952 		case 'c':			/* command complete */
    953 		case 'C':
    954 			return (complete_command(el, word, dolist));
    955 
    956 		case 'f':			/* filename complete */
    957 		case 'F':
    958 			return (complete_filename(el, word, dolist));
    959 
    960 		case 'n':			/* no complete */
    961 		case 'N':			/* no complete */
    962 			return (CC_ERROR);
    963 
    964 		case 's':
    965 		case 'S':
    966 			return (complete_set(el, word, dolist));
    967 
    968 		case 'x':			/* executable complete */
    969 		case 'X':
    970 			return (complete_executable(el, word, dolist));
    971 
    972 		default:
    973 			errx(1, "unknown complete type `%c'", cmpltype);
    974 			return (CC_ERROR);
    975 	}
    976 	/* NOTREACHED */
    977 }
    978 
    979 
    980 /*
    981  * Generic file completion routine
    982  */
    983 static unsigned char
    984 file_complete(EditLine *el, int ch)
    985 {
    986 	static char word[LINESIZE];
    987 
    988 	const LineInfo *lf;
    989 	size_t len, word_len;
    990 
    991 	lf = el_line(el);
    992 	len = lf->lastchar - lf->buffer;
    993 
    994 #ifdef EMACS_CTRL_D_BINDING_HACK
    995 	{
    996 		int cc_ret;
    997 		if ((cc_ret = emacs_ctrl_d(el, lf, ch, len)) != -1)
    998 			return cc_ret;
    999 	}
   1000 #endif /* EMACS_CTRL_D_BINDING_HACK */
   1001 
   1002 	if (len >= sizeof(word) - 1)
   1003 		return (CC_ERROR);
   1004 
   1005 	word_len = lf->cursor - lf->buffer;
   1006 	(void)strlcpy(word, lf->buffer, word_len + 1);	/* do not use estrlcpy here! */
   1007 	return complete_filename(el, word, len != word_len);
   1008 }
   1009 
   1010 
   1011 #ifdef MIME_SUPPORT
   1012 /*
   1013  * Complete mime_transfer_encoding type
   1014  */
   1015 static unsigned char
   1016 mime_enc_complete(EditLine *el, int ch)
   1017 {
   1018 	static char word[LINESIZE];
   1019 	StringList *words;
   1020 	unsigned char rv;
   1021 	const LineInfo *lf;
   1022 	size_t len, word_len;
   1023 
   1024 	lf = el_line(el);
   1025 	len = lf->lastchar - lf->buffer;
   1026 
   1027 #ifdef EMACS_CTRL_D_BINDING_HACK
   1028 	{
   1029 		int cc_ret;
   1030 		if ((cc_ret = emacs_ctrl_d(el, lf, ch, len)) != -1)
   1031 			return cc_ret;
   1032 	}
   1033 #endif /* EMACS_CTRL_D_BINDING_HACK */
   1034 
   1035 	if (len >= sizeof(word) - 1)
   1036 		return (CC_ERROR);
   1037 
   1038 	words = mail_sl_init();
   1039 	word_len = lf->cursor - lf->buffer;
   1040 	{
   1041 		const char *ename;
   1042 		const void *cookie;
   1043 		cookie = NULL;
   1044 		for (ename = mime_next_encoding_name(&cookie);
   1045 		     ename;
   1046 		     ename = mime_next_encoding_name(&cookie))
   1047 			if (word_len == 0 ||
   1048 			    strncmp(lf->buffer, ename, word_len) == 0) {
   1049 				char *cp;
   1050 				cp = estrdup(ename);
   1051 				mail_sl_add(words, cp);
   1052 			}
   1053 	}
   1054 	(void)strlcpy(word, lf->buffer, word_len + 1);	/* do not use estrlcpy here */
   1055 
   1056 	rv = complete_ambiguous(el, word, len != word_len, words);
   1057 
   1058 	sl_free(words, 1);
   1059 	return (rv);
   1060 }
   1061 #endif /* MIME_SUPPORT */
   1062 
   1063 /*************************************************************************
   1064  * Our public interface to el_gets():
   1065  *
   1066  * init_editline()
   1067  *    Initializes of all editline and completion data strutures.
   1068  *
   1069  * my_gets()
   1070  *    Returns the next line of input as a NULL termnated string without
   1071  *    the trailing newline.
   1072  */
   1073 
   1074 static const char *el_prompt;
   1075 
   1076 /*ARGSUSED*/
   1077 static const char *
   1078 show_prompt(EditLine *e __unused)
   1079 {
   1080 	return el_prompt;
   1081 }
   1082 
   1083 char *
   1084 my_gets(el_mode_t *em, const char *prompt, char *string)
   1085 {
   1086 	int cnt;
   1087 	size_t len;
   1088 	const char *buf;
   1089 	HistEvent ev;
   1090 	static char line[LINE_MAX];
   1091 
   1092 	el_prompt = prompt;
   1093 
   1094 	if (string)
   1095 		el_push(em->el, string);
   1096 
   1097 	buf = el_gets(em->el, &cnt);
   1098 
   1099 	if (buf == NULL || cnt <= 0) {
   1100 		if (cnt == 0)
   1101 			(void)putc('\n', stdout);
   1102 		return NULL;
   1103 	}
   1104 
   1105 	cnt--;	/* trash the trailing LF */
   1106 	len = MIN(sizeof(line) - 1, cnt);
   1107 	(void)memcpy(line, buf, len);
   1108 	line[cnt] = '\0';
   1109 
   1110 	/* enter non-empty lines into history */
   1111 	if (em->hist) {
   1112 		const char *p;
   1113 		p = skip_white(line);
   1114 		if (*p && history(em->hist, &ev, H_ENTER, line) == 0)
   1115 			(void)printf("Failed history entry: %s", line);
   1116 	}
   1117 	return line;
   1118 }
   1119 
   1120 static el_mode_t
   1121 init_el_mode(
   1122 	const char *el_editor,
   1123 	unsigned char (*completer)(EditLine *, int),
   1124 	struct name *keys,
   1125 	int history_size)
   1126 {
   1127 	el_mode_t em;
   1128 	(void)memset(&em, 0, sizeof(em));
   1129 
   1130 	em.el  = el_init(getprogname(), stdin, stdout, stderr);
   1131 
   1132 	(void)el_set(em.el, EL_PROMPT, show_prompt);
   1133 	(void)el_set(em.el, EL_SIGNAL, SIGHUP);
   1134 
   1135 	if (el_editor)
   1136 		(void)el_set(em.el, EL_EDITOR, el_editor);
   1137 
   1138 	if (completer) {
   1139 		struct name *np;
   1140 		(void)el_set(em.el, EL_ADDFN, "mail-complete",
   1141 		    "Context sensitive argument completion", completer);
   1142 		for (np = keys; np; np = np->n_flink)
   1143 			(void)el_set(em.el, EL_BIND, np->n_name,
   1144 			    "mail-complete", NULL);
   1145 	}
   1146 
   1147 	if (history_size) {
   1148 		HistEvent ev;
   1149 		em.hist = history_init();
   1150 		if (history(em.hist, &ev, H_SETSIZE, history_size))
   1151 			(void)printf("history: %s\n", ev.str);
   1152 		(void)el_set(em.el, EL_HIST, history, em.hist);
   1153 	}
   1154 
   1155 	(void)el_source(em.el, NULL);		/* read ~/.editrc */
   1156 
   1157 	return em;
   1158 }
   1159 
   1160 
   1161 struct el_modes_s elm = {
   1162 	.command  = { .el = NULL, .hist = NULL, },
   1163 	.string   = { .el = NULL, .hist = NULL, },
   1164 	.filec    = { .el = NULL, .hist = NULL, },
   1165 #ifdef MIME_SUPPORT
   1166 	.mime_enc = { .el = NULL, .hist = NULL, },
   1167 #endif
   1168 };
   1169 
   1170 void
   1171 init_editline(void)
   1172 {
   1173 	const char *mode;
   1174 	int hist_size;
   1175 	struct name *keys;
   1176 	char *cp;
   1177 
   1178 	mode = value(ENAME_EL_EDITOR);
   1179 
   1180 	cp = value(ENAME_EL_HISTORY_SIZE);
   1181 	hist_size = cp ? atoi(cp) : 0;
   1182 
   1183 	cp = value(ENAME_EL_COMPLETION_KEYS);
   1184 	keys = cp && *cp ? lexpand(cp, 0) : NULL;
   1185 
   1186 	elm.command  = init_el_mode(mode, mail_complete,     keys, hist_size);
   1187 	elm.filec    = init_el_mode(mode, file_complete,     keys, 0);
   1188 	elm.string   = init_el_mode(mode, NULL,              NULL, 0);
   1189 #ifdef MIME_SUPPORT
   1190 	elm.mime_enc = init_el_mode(mode, mime_enc_complete, keys, 0);
   1191 #endif
   1192 	init_complete();
   1193 
   1194 	return;
   1195 }
   1196 
   1197 #endif /* USE_EDITLINE */
   1198