1 /**	$MirOS: src/lib/libedit/readline.c,v 1.7 2005/04/19 19:30:35 tg Exp $ */
2 /*	$OpenBSD: readline.c,v 1.2 2003/11/25 20:12:38 otto Exp $ */
3 /*	$NetBSD: readline.c,v 1.52 2005/04/19 03:29:18 christos Exp $	*/
4 
5 /*-
6  * Copyright (c) 1997 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Jaromir Dolecek.
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 #include "config.h"
42 
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <stdio.h>
47 #include <dirent.h>
48 #include <string.h>
49 #include <pwd.h>
50 #include <ctype.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #ifdef HAVE_VIS_H
57 #include <vis.h>
58 #else
59 #include "np/vis.h"
60 #endif
61 #ifdef HAVE_ALLOCA_H
62 #include <alloca.h>
63 #endif
64 #include "el.h"
65 #include "fcns.h"		/* for EL_NUM_FCNS */
66 #include "histedit.h"
67 #include "term.h"
68 #include "readline/readline.h"
69 
70 __RCSID("$MirOS: src/lib/libedit/readline.c,v 1.7 2005/04/19 19:30:35 tg Exp $");
71 
72 /* for rl_complete() */
73 #define TAB		'\r'
74 
75 /* see comment at the #ifdef for sense of this */
76 /* #define GDB_411_HACK */
77 
78 /* readline compatibility stuff - look at readline sources/documentation */
79 /* to see what these variables mean */
80 const char *rl_library_version = "EditLine wrapper";
81 static char empty[] = { '\0' };
82 static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
83 static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
84     '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
85 char *rl_readline_name = empty;
86 FILE *rl_instream = NULL;
87 FILE *rl_outstream = NULL;
88 int rl_point = 0;
89 int rl_end = 0;
90 char *rl_line_buffer = NULL;
91 VFunctionC *rl_linefunc = NULL;
92 int rl_done = 0;
93 VFunction *rl_event_hook = NULL;
94 
95 int history_base = 1;		/* probably never subject to change */
96 int history_length = 0;
97 int max_input_history = 0;
98 char history_expansion_char = '!';
99 char history_subst_char = '^';
100 char *history_no_expand_chars = expand_chars;
101 Function *history_inhibit_expansion_function = NULL;
102 char *history_arg_extract(int start, int end, const char *str);
103 
104 int rl_inhibit_completion = 0;
105 int rl_attempted_completion_over = 0;
106 char *rl_basic_word_break_characters = break_chars;
107 char *rl_completer_word_break_characters = NULL;
108 char *rl_completer_quote_characters = NULL;
109 Function *rl_completion_entry_function = NULL;
110 CPPFunction *rl_attempted_completion_function = NULL;
111 Function *rl_pre_input_hook = NULL;
112 Function *rl_startup1_hook = NULL;
113 Function *rl_getc_function = NULL;
114 char *rl_terminal_name = NULL;
115 int rl_already_prompted = 0;
116 int rl_filename_completion_desired = 0;
117 int rl_ignore_completion_duplicates = 0;
118 int rl_catch_signals = 1;
119 VFunction *rl_redisplay_function = NULL;
120 Function *rl_startup_hook = NULL;
121 VFunction *rl_completion_display_matches_hook = NULL;
122 VFunction *rl_prep_term_function = NULL;
123 VFunction *rl_deprep_term_function = NULL;
124 
125 /*
126  * The current prompt string.
127  */
128 char *rl_prompt = NULL;
129 /*
130  * This is set to character indicating type of completion being done by
131  * rl_complete_internal(); this is available for application completion
132  * functions.
133  */
134 int rl_completion_type = 0;
135 
136 /*
137  * If more than this number of items results from query for possible
138  * completions, we ask user if they are sure to really display the list.
139  */
140 int rl_completion_query_items = 100;
141 
142 /*
143  * List of characters which are word break characters, but should be left
144  * in the parsed text when it is passed to the completion function.
145  * Shell uses this to help determine what kind of completing to do.
146  */
147 char *rl_special_prefixes = (char *)NULL;
148 
149 /*
150  * This is the character appended to the completed words if at the end of
151  * the line. Default is ' ' (a space).
152  */
153 int rl_completion_append_character = ' ';
154 
155 /* stuff below is used internally by libedit for readline emulation */
156 
157 /* if not zero, non-unique completions always show list of possible matches */
158 static int _rl_complete_show_all = 0;
159 
160 static History *h = NULL;
161 static EditLine *e = NULL;
162 static Function *map[256];
163 static int el_rl_complete_cmdnum = 0;
164 
165 /* internal functions */
166 static unsigned char	 _el_rl_complete(EditLine *, int);
167 static unsigned char	 _el_rl_tstp(EditLine *, int);
168 static char		*_get_prompt(EditLine *);
169 static HIST_ENTRY	*_move_history(int);
170 static int		 _history_expand_command(const char *, size_t, size_t,
171     char **);
172 static char		*_rl_compat_sub(const char *, const char *,
173     const char *, int);
174 static int		 _rl_complete_internal(int);
175 static int		 _rl_qsort_string_compare(const void *, const void *);
176 static int		 _rl_event_read_char(EditLine *, char *);
177 static void		 _rl_update_pos(void);
178 
179 
180 /* ARGSUSED */
181 static char *
_get_prompt(EditLine * el)182 _get_prompt(EditLine *el __attribute__((__unused__)))
183 {
184 	rl_already_prompted = 1;
185 	return (rl_prompt);
186 }
187 
188 
189 /*
190  * generic function for moving around history
191  */
192 static HIST_ENTRY *
_move_history(int op)193 _move_history(int op)
194 {
195 	HistEvent ev;
196 	static HIST_ENTRY rl_he;
197 
198 	if (history(h, &ev, op) != 0)
199 		return (HIST_ENTRY *) NULL;
200 
201 	rl_he.line = ev.str;
202 	rl_he.data = NULL;
203 
204 	return (&rl_he);
205 }
206 
207 
208 /*
209  * READLINE compatibility stuff
210  */
211 
212 /*
213  * initialize rl compat stuff
214  */
215 int
rl_initialize(void)216 rl_initialize(void)
217 {
218 	HistEvent ev;
219 	const LineInfo *li;
220 	int i;
221 	int editmode = 1;
222 	struct termios t;
223 
224 	if (e != NULL)
225 		el_end(e);
226 	if (h != NULL)
227 		history_end(h);
228 
229 	if (!rl_instream)
230 		rl_instream = stdin;
231 	if (!rl_outstream)
232 		rl_outstream = stdout;
233 
234 	/*
235 	 * See if we don't really want to run the editor
236 	 */
237 	if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
238 		editmode = 0;
239 
240 	e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
241 
242 	if (!editmode)
243 		el_set(e, EL_EDITMODE, 0);
244 
245 	h = history_init();
246 	if (!e || !h)
247 		return (-1);
248 
249 	history(h, &ev, H_SETSIZE, INT_MAX);	/* unlimited */
250 	history_length = 0;
251 	max_input_history = INT_MAX;
252 	el_set(e, EL_HIST, history, h);
253 
254 	/* for proper prompt printing in readline() */
255 	rl_prompt = strdup("");
256 	if (rl_prompt == NULL) {
257 		history_end(h);
258 		el_end(e);
259 		return -1;
260 	}
261 	el_set(e, EL_PROMPT, _get_prompt);
262 	el_set(e, EL_SIGNAL, rl_catch_signals);
263 
264 	/* set default mode to "emacs"-style and read setting afterwards */
265 	/* so this can be overriden */
266 	el_set(e, EL_EDITOR, "emacs");
267 	if (rl_terminal_name != NULL)
268 		el_set(e, EL_TERMINAL, rl_terminal_name);
269 	else
270 		el_get(e, EL_TERMINAL, &rl_terminal_name);
271 
272 	/*
273 	 * Word completion - this has to go AFTER rebinding keys
274 	 * to emacs-style.
275 	 */
276 	el_set(e, EL_ADDFN, "rl_complete",
277 	    "ReadLine compatible completion function",
278 	    _el_rl_complete);
279 	el_set(e, EL_BIND, "^I", "rl_complete", NULL);
280 
281 	/*
282 	 * Send TSTP when ^Z is pressed.
283 	 */
284 	el_set(e, EL_ADDFN, "rl_tstp",
285 	    "ReadLine compatible suspend function",
286 	    _el_rl_tstp);
287 	el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
288 
289 	/*
290 	 * Find out where the rl_complete function was added; this is
291 	 * used later to detect that lastcmd was also rl_complete.
292 	 */
293 	for(i=EL_NUM_FCNS; i < e->el_map.nfunc; i++) {
294 		if (e->el_map.func[i] == _el_rl_complete) {
295 			el_rl_complete_cmdnum = i;
296 			break;
297 		}
298 	}
299 
300 	/* read settings from configuration file */
301 	el_source(e, NULL);
302 
303 	/*
304 	 * Unfortunately, some applications really do use rl_point
305 	 * and rl_line_buffer directly.
306 	 */
307 	li = el_line(e);
308 	/* a cheesy way to get rid of const cast. */
309 	rl_line_buffer = memchr(li->buffer, *li->buffer, 1);
310 	_rl_update_pos();
311 
312 	if (rl_startup_hook)
313 		(*rl_startup_hook)(NULL, 0);
314 
315 	return (0);
316 }
317 
318 
319 /*
320  * read one line from input stream and return it, chomping
321  * trailing newline (if there is any)
322  */
323 char *
readline(const char * prompt)324 readline(const char *prompt)
325 {
326 	HistEvent ev;
327 	int count;
328 	const char *ret;
329 	char *buf;
330 	static int used_event_hook;
331 
332 	if (e == NULL || h == NULL)
333 		rl_initialize();
334 
335 	rl_done = 0;
336 
337 	/* update prompt accordingly to what has been passed */
338 	if (!prompt)
339 		prompt = "";
340 	if (strcmp(rl_prompt, prompt) != 0) {
341 		free(rl_prompt);
342 		rl_prompt = strdup(prompt);
343 		if (rl_prompt == NULL)
344 			return NULL;
345 	}
346 
347 	if (rl_pre_input_hook)
348 		(*rl_pre_input_hook)(NULL, 0);
349 
350 	if (rl_event_hook && !(e->el_flags&NO_TTY)) {
351 		el_set(e, EL_GETCFN, _rl_event_read_char);
352 		used_event_hook = 1;
353 	}
354 
355 	if (!rl_event_hook && used_event_hook) {
356 		el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
357 		used_event_hook = 0;
358 	}
359 
360 	rl_already_prompted = 0;
361 
362 	/* get one line from input stream */
363 	ret = el_gets(e, &count);
364 
365 	if (ret && count > 0) {
366 		int lastidx;
367 
368 		buf = strdup(ret);
369 		if (buf == NULL)
370 			return NULL;
371 		lastidx = count - 1;
372 		if (buf[lastidx] == '\n')
373 			buf[lastidx] = '\0';
374 	} else
375 		buf = NULL;
376 
377 	history(h, &ev, H_GETSIZE);
378 	history_length = ev.num;
379 
380 	return buf;
381 }
382 
383 /*
384  * history functions
385  */
386 
387 /*
388  * is normally called before application starts to use
389  * history expansion functions
390  */
391 void
using_history(void)392 using_history(void)
393 {
394 	if (h == NULL || e == NULL)
395 		rl_initialize();
396 }
397 
398 
399 /*
400  * substitute ``what'' with ``with'', returning resulting string; if
401  * globally == 1, substitutes all occurrences of what, otherwise only the
402  * first one
403  */
404 static char *
_rl_compat_sub(const char * str,const char * what,const char * with,int globally)405 _rl_compat_sub(const char *str, const char *what, const char *with,
406     int globally)
407 {
408 	const	char	*s;
409 	char	*r, *result;
410 	size_t	len, with_len, what_len;
411 
412 	len = strlen(str);
413 	with_len = strlen(with);
414 	what_len = strlen(what);
415 
416 	/* calculate length we need for result */
417 	s = str;
418 	while (*s) {
419 		if (*s == *what && !strncmp(s, what, what_len)) {
420 			len += with_len - what_len;
421 			if (!globally)
422 				break;
423 			s += what_len;
424 		} else
425 			s++;
426 	}
427 	len++;
428 	r = result = malloc(len);
429 	if (result == NULL)
430 		return NULL;
431 	s = str;
432 	while (*s) {
433 		if (*s == *what && !strncmp(s, what, what_len)) {
434 			(void)strncpy(r, with, with_len);
435 			r += with_len;
436 			len -= with_len;
437 			s += what_len;
438 			if (!globally) {
439 				(void)strlcpy(r, s, len);
440 				return(result);
441 			}
442 		} else
443 			*r++ = *s++;
444 	}
445 	*r = 0;
446 	return(result);
447 }
448 
449 static	char	*last_search_pat;	/* last !?pat[?] search pattern */
450 static	char	*last_search_match;	/* last !?pat[?] that matched */
451 
452 const char *
get_history_event(const char * cmd,int * cindex,int qchar)453 get_history_event(const char *cmd, int *cindex, int qchar)
454 {
455 	int idx, sign, sub, num, begin, ret;
456 	size_t len;
457 	char	*pat;
458 	const char *rptr;
459 	HistEvent ev;
460 
461 	idx = *cindex;
462 	if (cmd[idx++] != history_expansion_char)
463 		return(NULL);
464 
465 	/* find out which event to take */
466 	if (cmd[idx] == history_expansion_char || cmd[idx] == 0) {
467 		if (history(h, &ev, H_FIRST) != 0)
468 			return(NULL);
469 		*cindex = cmd[idx]? (idx + 1):idx;
470 		return(ev.str);
471 	}
472 	sign = 0;
473 	if (cmd[idx] == '-') {
474 		sign = 1;
475 		idx++;
476 	}
477 
478 	if ('0' <= cmd[idx] && cmd[idx] <= '9') {
479 		HIST_ENTRY *rl_he;
480 
481 		num = 0;
482 		while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
483 			num = num * 10 + cmd[idx] - '0';
484 			idx++;
485 		}
486 		if (sign)
487 			num = history_length - num + 1;
488 
489 		if (!(rl_he = history_get(num)))
490 			return(NULL);
491 
492 		*cindex = idx;
493 		return(rl_he->line);
494 	}
495 	sub = 0;
496 	if (cmd[idx] == '?') {
497 		sub = 1;
498 		idx++;
499 	}
500 	begin = idx;
501 	while (cmd[idx]) {
502 		if (cmd[idx] == '\n')
503 			break;
504 		if (sub && cmd[idx] == '?')
505 			break;
506 		if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
507 				    || cmd[idx] == '\t' || cmd[idx] == qchar))
508 			break;
509 		idx++;
510 	}
511 	len = idx - begin;
512 	if (sub && cmd[idx] == '?')
513 		idx++;
514 	if (sub && len == 0 && last_search_pat && *last_search_pat)
515 		pat = last_search_pat;
516 	else if (len == 0)
517 		return(NULL);
518 	else {
519 		if ((pat = malloc(len + 1)) == NULL)
520 			return NULL;
521 		(void)strncpy(pat, cmd + begin, len);
522 		pat[len] = '\0';
523 	}
524 
525 	if (history(h, &ev, H_CURR) != 0) {
526 		if (pat != last_search_pat)
527 			free(pat);
528 		return (NULL);
529 	}
530 	num = ev.num;
531 
532 	if (sub) {
533 		if (pat != last_search_pat) {
534 			if (last_search_pat)
535 				free(last_search_pat);
536 			last_search_pat = pat;
537 		}
538 		ret = history_search(pat, -1);
539 	} else
540 		ret = history_search_prefix(pat, -1);
541 
542 	if (ret == -1) {
543 		/* restore to end of list on failed search */
544 		history(h, &ev, H_FIRST);
545 		(void)fprintf(rl_outstream, "%s: Event not found\n", pat);
546 		if (pat != last_search_pat)
547 			free(pat);
548 		return(NULL);
549 	}
550 
551 	if (sub && len) {
552 		if (last_search_match && last_search_match != pat)
553 			free(last_search_match);
554 		last_search_match = pat;
555 	}
556 
557 	if (pat != last_search_pat)
558 		free(pat);
559 
560 	if (history(h, &ev, H_CURR) != 0)
561 		return(NULL);
562 	*cindex = idx;
563 	rptr = ev.str;
564 
565 	/* roll back to original position */
566 	(void)history(h, &ev, H_SET, num);
567 
568 	return rptr;
569 }
570 
571 /*
572  * the real function doing history expansion - takes as argument command
573  * to do and data upon which the command should be executed
574  * does expansion the way I've understood readline documentation
575  *
576  * returns 0 if data was not modified, 1 if it was and 2 if the string
577  * should be only printed and not executed; in case of error,
578  * returns -1 and *result points to NULL
579  * it's callers responsibility to free() string returned in *result
580  */
581 static int
_history_expand_command(const char * command,size_t offs,size_t cmdlen,char ** result)582 _history_expand_command(const char *command, size_t offs, size_t cmdlen,
583     char **result)
584 {
585 	char *tmp, *search = NULL, *aptr;
586 	const char *ptr, *cmd;
587 	static char *from = NULL, *to = NULL;
588 	int start, end, idx, has_mods = 0;
589 	int p_on = 0, g_on = 0;
590 
591 	*result = NULL;
592 	aptr = NULL;
593 	ptr = NULL;
594 
595 	/* First get event specifier */
596 	idx = 0;
597 
598 	if (strchr(":^*$", command[offs + 1])) {
599 		char str[4];
600 		/*
601 		* "!:" is shorthand for "!!:".
602 		* "!^", "!*" and "!$" are shorthand for
603 		* "!!:^", "!!:*" and "!!:$" respectively.
604 		*/
605 		str[0] = str[1] = '!';
606 		str[2] = '0';
607 		ptr = get_history_event(str, &idx, 0);
608 		idx = (command[offs + 1] == ':')? 1:0;
609 		has_mods = 1;
610 	} else {
611 		if (command[offs + 1] == '#') {
612 			/* use command so far */
613 			if ((aptr = malloc(offs + 1)) == NULL)
614 				return -1;
615 			(void)strncpy(aptr, command, offs);
616 			aptr[offs] = '\0';
617 			idx = 1;
618 		} else {
619 			int	qchar;
620 
621 			qchar = (offs > 0 && command[offs - 1] == '"')? '"':0;
622 			ptr = get_history_event(command + offs, &idx, qchar);
623 		}
624 		has_mods = command[offs + idx] == ':';
625 	}
626 
627 	if (ptr == NULL && aptr == NULL)
628 		return(-1);
629 
630 	if (!has_mods) {
631 		*result = strdup(aptr? aptr : ptr);
632 		if (aptr)
633 			free(aptr);
634 		return(1);
635 	}
636 
637 	cmd = command + offs + idx + 1;
638 
639 	/* Now parse any word designators */
640 
641 	if (*cmd == '%')	/* last word matched by ?pat? */
642 		tmp = strdup(last_search_match? last_search_match:"");
643 	else if (strchr("^*$-0123456789", *cmd)) {
644 		start = end = -1;
645 		if (*cmd == '^')
646 			start = end = 1, cmd++;
647 		else if (*cmd == '$')
648 			start = -1, cmd++;
649 		else if (*cmd == '*')
650 			start = 1, cmd++;
651 	       else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
652 			start = 0;
653 			while (*cmd && '0' <= *cmd && *cmd <= '9')
654 				start = start * 10 + *cmd++ - '0';
655 
656 			if (*cmd == '-') {
657 				if (isdigit((unsigned char) cmd[1])) {
658 					cmd++;
659 					end = 0;
660 					while (*cmd && '0' <= *cmd && *cmd <= '9')
661 						end = end * 10 + *cmd++ - '0';
662 				} else if (cmd[1] == '$') {
663 					cmd += 2;
664 					end = -1;
665 				} else {
666 					cmd++;
667 					end = -2;
668 				}
669 			} else if (*cmd == '*')
670 				end = -1, cmd++;
671 			else
672 				end = start;
673 		}
674 		tmp = history_arg_extract(start, end, aptr? aptr:ptr);
675 		if (tmp == NULL) {
676 			(void)fprintf(rl_outstream, "%s: Bad word specifier",
677 			    command + offs + idx);
678 			if (aptr)
679 				free(aptr);
680 			return(-1);
681 		}
682 	} else
683 		tmp = strdup(aptr? aptr:ptr);
684 
685 	if (aptr)
686 		free(aptr);
687 
688 	if (*cmd == 0 || (cmd - (command + offs) >= cmdlen)) {
689 		*result = tmp;
690 		return(1);
691 	}
692 
693 	for (; *cmd; cmd++) {
694 		if (*cmd == ':')
695 			continue;
696 		else if (*cmd == 'h') {		/* remove trailing path */
697 			if ((aptr = strrchr(tmp, '/')) != NULL)
698 				*aptr = 0;
699 		} else if (*cmd == 't') {	/* remove leading path */
700 			if ((aptr = strrchr(tmp, '/')) != NULL) {
701 				aptr = strdup(aptr + 1);
702 				free(tmp);
703 				tmp = aptr;
704 			}
705 		} else if (*cmd == 'r') {	/* remove trailing suffix */
706 			if ((aptr = strrchr(tmp, '.')) != NULL)
707 				*aptr = 0;
708 		} else if (*cmd == 'e') {	/* remove all but suffix */
709 			if ((aptr = strrchr(tmp, '.')) != NULL) {
710 				aptr = strdup(aptr);
711 				free(tmp);
712 				tmp = aptr;
713 			}
714 		} else if (*cmd == 'p')		/* print only */
715 			p_on = 1;
716 		else if (*cmd == 'g')
717 			g_on = 2;
718 		else if (*cmd == 's' || *cmd == '&') {
719 			char *what, *with, delim;
720 			size_t len, from_len;
721 			size_t size;
722 
723 			if (*cmd == '&' && (from == NULL || to == NULL))
724 				continue;
725 			else if (*cmd == 's') {
726 				delim = *(++cmd), cmd++;
727 				size = 16;
728 				what = realloc(from, size);
729 				if (what == NULL) {
730 					free(from);
731 					return 0;
732 				}
733 				len = 0;
734 				for (; *cmd && *cmd != delim; cmd++) {
735 					if (*cmd == '\\' && cmd[1] == delim)
736 						cmd++;
737 					if (len >= size) {
738 						char *nwhat;
739 						nwhat = realloc(what,
740 								(size <<= 1));
741 						if (nwhat == NULL) {
742 							free(what);
743 							return 0;
744 						}
745 						what = nwhat;
746 					}
747 					what[len++] = *cmd;
748 				}
749 				what[len] = '\0';
750 				from = what;
751 				if (*what == '\0') {
752 					free(what);
753 					if (search) {
754 						from = strdup(search);
755 						if (from == NULL)
756 							return 0;
757 					} else {
758 						from = NULL;
759 						return (-1);
760 					}
761 				}
762 				cmd++;	/* shift after delim */
763 				if (!*cmd)
764 					continue;
765 
766 				size = 16;
767 				with = realloc(to, size);
768 				if (with == NULL) {
769 					free(to);
770 					return -1;
771 				}
772 				len = 0;
773 				from_len = strlen(from);
774 				for (; *cmd && *cmd != delim; cmd++) {
775 					if (len + from_len + 1 >= size) {
776 						char *nwith;
777 						size += from_len + 1;
778 						nwith = realloc(with, size);
779 						if (nwith == NULL) {
780 							free(with);
781 							return -1;
782 						}
783 						with = nwith;
784 					}
785 					if (*cmd == '&') {
786 						(void)strlcpy(&with[len], from,
787 							size - len);
788 						len += from_len;
789 						continue;
790 					}
791 					if (*cmd == '\\'
792 					    && (*(cmd + 1) == delim
793 						|| *(cmd + 1) == '&'))
794 						cmd++;
795 					with[len++] = *cmd;
796 				}
797 				with[len] = '\0';
798 				to = with;
799 			}
800 
801 			aptr = _rl_compat_sub(tmp, from, to, g_on);
802 			if (aptr) {
803 				free(tmp);
804 				tmp = aptr;
805 			}
806 			g_on = 0;
807 		}
808 	}
809 	*result = tmp;
810 	return (p_on? 2:1);
811 }
812 
813 
814 /*
815  * csh-style history expansion
816  */
817 int
history_expand(char * str,char ** output)818 history_expand(char *str, char **output)
819 {
820 	int ret = 0;
821 	size_t idx, i, size;
822 	char *tmp, *result;
823 
824 	if (h == NULL || e == NULL)
825 		rl_initialize();
826 
827 	if (history_expansion_char == 0) {
828 		*output = strdup(str);
829 		return(0);
830 	}
831 
832 	*output = NULL;
833 	if (str[0] == history_subst_char) {
834 		/* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
835 		size_t sz = 4 + strlen(str) + 1;
836 		*output = malloc(sz);
837 		if (*output == NULL)
838 			return 0;
839 		(*output)[0] = (*output)[1] = history_expansion_char;
840 		(*output)[2] = ':';
841 		(*output)[3] = 's';
842 		(void)strlcpy((*output) + 4, str, sz - 4);
843 		str = *output;
844 	} else {
845 		*output = strdup(str);
846 		if (*output == NULL)
847 			return 0;
848 	}
849 
850 #define ADD_STRING(what, len)						\
851 	{								\
852 		if (idx + len + 1 > size) {				\
853 			char *nresult = realloc(result, (size += len + 1));\
854 			if (nresult == NULL) {				\
855 				free(*output);				\
856 				return 0;				\
857 			}						\
858 			result = nresult;				\
859 		}							\
860 		(void)strncpy(&result[idx], what, len);			\
861 		idx += len;						\
862 		result[idx] = '\0';					\
863 	}
864 
865 	result = NULL;
866 	size = idx = 0;
867 	for (i = 0; str[i];) {
868 		int qchar, loop_again;
869 		size_t len, start, j;
870 
871 		qchar = 0;
872 		loop_again = 1;
873 		start = j = i;
874 loop:
875 		for (; str[j]; j++) {
876 			if (str[j] == '\\' &&
877 			    str[j + 1] == history_expansion_char) {
878 				size_t sz = strlen(&str[j]) + 1;
879 				(void)strlcpy(&str[j], &str[j + 1], sz);
880 				continue;
881 			}
882 			if (!loop_again) {
883 				if (isspace((unsigned char) str[j])
884 				    || str[j] == qchar)
885 					break;
886 			}
887 			if (str[j] == history_expansion_char
888 			    && !strchr(history_no_expand_chars, str[j + 1])
889 			    && (!history_inhibit_expansion_function ||
890 			    (*history_inhibit_expansion_function)(str,
891 			    (int)j) == 0))
892 				break;
893 		}
894 
895 		if (str[j] && loop_again) {
896 			i = j;
897 			qchar = (j > 0 && str[j - 1] == '"' )? '"':0;
898 			j++;
899 			if (str[j] == history_expansion_char)
900 				j++;
901 			loop_again = 0;
902 			goto loop;
903 		}
904 		len = i - start;
905 		tmp = &str[start];
906 		ADD_STRING(tmp, len);
907 
908 		if (str[i] == '\0' || str[i] != history_expansion_char) {
909 			len = j - i;
910 			tmp = &str[i];
911 			ADD_STRING(tmp, len);
912 			if (start == 0)
913 				ret = 0;
914 			else
915 				ret = 1;
916 			break;
917 		}
918 		ret = _history_expand_command (str, i, (j - i), &tmp);
919 		if (ret > 0 && tmp) {
920 			len = strlen(tmp);
921 			ADD_STRING(tmp, len);
922 			free(tmp);
923 		}
924 		i = j;
925 	}
926 
927 	/* ret is 2 for "print only" option */
928 	if (ret == 2) {
929 		add_history(result);
930 #ifdef GDB_411_HACK
931 		/* gdb 4.11 has been shipped with readline, where */
932 		/* history_expand() returned -1 when the line	  */
933 		/* should not be executed; in readline 2.1+	  */
934 		/* it should return 2 in such a case		  */
935 		ret = -1;
936 #endif
937 	}
938 	free(*output);
939 	*output = result;
940 
941 	return (ret);
942 }
943 
944 /*
945 * Return a string consisting of arguments of "str" from "start" to "end".
946 */
947 char *
history_arg_extract(int start,int end,const char * str)948 history_arg_extract(int start, int end, const char *str)
949 {
950 	size_t  i, len, max;
951 	char	**arr, *result;
952 
953 	arr = history_tokenize(str);
954 	if (!arr)
955 		return(NULL);
956 	if (arr && *arr == NULL) {
957 		free(arr);
958 		return(NULL);
959 	}
960 
961 	for (max = 0; arr[max]; max++)
962 		continue;
963 	max--;
964 
965 	if (start == '$')
966 		start = max;
967 	if (end == '$')
968 		end = max;
969 	if (end < 0)
970 		end = max + end + 1;
971 	if (start < 0)
972 		start = end;
973 
974 	if (start < 0 || end < 0 || start > max || end > max || start > end)
975 		return(NULL);
976 
977 	for (i = start, len = 0; i <= end; i++)
978 		len += strlen(arr[i]) + 1;
979 	len++;
980 	max = len;
981 	result = malloc(len);
982 	if (result == NULL)
983 		return NULL;
984 
985 	for (i = start, len = 0; i <= end; i++) {
986 		(void)strlcpy(result + len, arr[i], max - len);
987 		len += strlen(arr[i]);
988 		if (i < end)
989 			result[len++] = ' ';
990 	}
991 	result[len] = 0;
992 
993 	for (i = 0; arr[i]; i++)
994 		free(arr[i]);
995 	free(arr);
996 
997 	return(result);
998 }
999 
1000 /*
1001  * Parse the string into individual tokens,
1002  * similar to how shell would do it.
1003  */
1004 char **
history_tokenize(const char * str)1005 history_tokenize(const char *str)
1006 {
1007 	int size = 1, idx = 0, i, start;
1008 	size_t len;
1009 	char **result = NULL, *temp, delim = '\0';
1010 
1011 	for (i = 0; str[i];) {
1012 		while (isspace((unsigned char) str[i]))
1013 			i++;
1014 		start = i;
1015 		for (; str[i];) {
1016 			if (str[i] == '\\') {
1017 				if (str[i+1] != '\0')
1018 					i++;
1019 			} else if (str[i] == delim)
1020 				delim = '\0';
1021 			else if (!delim &&
1022 				    (isspace((unsigned char) str[i]) ||
1023 				strchr("()<>;&|$", str[i])))
1024 				break;
1025 			else if (!delim && strchr("'`\"", str[i]))
1026 				delim = str[i];
1027 			if (str[i])
1028 				i++;
1029 		}
1030 
1031 		if (idx + 2 >= size) {
1032 			char **nresult;
1033 			size <<= 1;
1034 			nresult = realloc(result, size * sizeof(char *));
1035 			if (nresult == NULL) {
1036 				free(result);
1037 				return NULL;
1038 			}
1039 			result = nresult;
1040 		}
1041 		len = i - start;
1042 		temp = malloc(len + 1);
1043 		if (temp == NULL) {
1044 			for (i = 0; i < idx; i++)
1045 				free(result[i]);
1046 			free(result);
1047 			return NULL;
1048 		}
1049 		(void)strncpy(temp, &str[start], len);
1050 		temp[len] = '\0';
1051 		result[idx++] = temp;
1052 		result[idx] = NULL;
1053 		if (str[i])
1054 			i++;
1055 	}
1056 	return (result);
1057 }
1058 
1059 
1060 /*
1061  * limit size of history record to ``max'' events
1062  */
1063 void
stifle_history(int max)1064 stifle_history(int max)
1065 {
1066 	HistEvent ev;
1067 
1068 	if (h == NULL || e == NULL)
1069 		rl_initialize();
1070 
1071 	if (history(h, &ev, H_SETSIZE, max) == 0)
1072 		max_input_history = max;
1073 }
1074 
1075 
1076 /*
1077  * "unlimit" size of history - set the limit to maximum allowed int value
1078  */
1079 int
unstifle_history(void)1080 unstifle_history(void)
1081 {
1082 	HistEvent ev;
1083 	int omax;
1084 
1085 	history(h, &ev, H_SETSIZE, INT_MAX);
1086 	omax = max_input_history;
1087 	max_input_history = INT_MAX;
1088 	return (omax);		/* some value _must_ be returned */
1089 }
1090 
1091 
1092 int
history_is_stifled(void)1093 history_is_stifled(void)
1094 {
1095 
1096 	/* cannot return true answer */
1097 	return (max_input_history != INT_MAX);
1098 }
1099 
1100 
1101 /*
1102  * read history from a file given
1103  */
1104 int
read_history(const char * filename)1105 read_history(const char *filename)
1106 {
1107 	HistEvent ev;
1108 
1109 	if (h == NULL || e == NULL)
1110 		rl_initialize();
1111 	return (history(h, &ev, H_LOAD, filename));
1112 }
1113 
1114 
1115 /*
1116  * write history to a file given
1117  */
1118 int
write_history(const char * filename)1119 write_history(const char *filename)
1120 {
1121 	HistEvent ev;
1122 
1123 	if (h == NULL || e == NULL)
1124 		rl_initialize();
1125 	return (history(h, &ev, H_SAVE, filename));
1126 }
1127 
1128 
1129 /*
1130  * returns history ``num''th event
1131  *
1132  * returned pointer points to static variable
1133  */
1134 HIST_ENTRY *
history_get(int num)1135 history_get(int num)
1136 {
1137 	static HIST_ENTRY she;
1138 	HistEvent ev;
1139 	int curr_num;
1140 
1141 	if (h == NULL || e == NULL)
1142 		rl_initialize();
1143 
1144 	/* save current position */
1145 	if (history(h, &ev, H_CURR) != 0)
1146 		return (NULL);
1147 	curr_num = ev.num;
1148 
1149 	/* start from most recent */
1150 	if (history(h, &ev, H_FIRST) != 0)
1151 		return (NULL);	/* error */
1152 
1153 	/* look backwards for event matching specified offset */
1154 	if (history(h, &ev, H_NEXT_EVENT, num))
1155 		return (NULL);
1156 
1157 	she.line = ev.str;
1158 	she.data = NULL;
1159 
1160 	/* restore pointer to where it was */
1161 	(void)history(h, &ev, H_SET, curr_num);
1162 
1163 	return (&she);
1164 }
1165 
1166 
1167 /*
1168  * add the line to history table
1169  */
1170 int
add_history(const char * line)1171 add_history(const char *line)
1172 {
1173 	HistEvent ev;
1174 
1175 	if (h == NULL || e == NULL)
1176 		rl_initialize();
1177 
1178 	(void)history(h, &ev, H_ENTER, line);
1179 	if (history(h, &ev, H_GETSIZE) == 0)
1180 		history_length = ev.num;
1181 
1182 	return (!(history_length > 0)); /* return 0 if all is okay */
1183 }
1184 
1185 
1186 /*
1187  * clear the history list - delete all entries
1188  */
1189 void
clear_history(void)1190 clear_history(void)
1191 {
1192 	HistEvent ev;
1193 
1194 	history(h, &ev, H_CLEAR);
1195 }
1196 
1197 
1198 /*
1199  * returns offset of the current history event
1200  */
1201 int
where_history(void)1202 where_history(void)
1203 {
1204 	HistEvent ev;
1205 	int curr_num, off;
1206 
1207 	if (history(h, &ev, H_CURR) != 0)
1208 		return (0);
1209 	curr_num = ev.num;
1210 
1211 	history(h, &ev, H_FIRST);
1212 	off = 1;
1213 	while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
1214 		off++;
1215 
1216 	return (off);
1217 }
1218 
1219 
1220 /*
1221  * returns current history event or NULL if there is no such event
1222  */
1223 HIST_ENTRY *
current_history(void)1224 current_history(void)
1225 {
1226 
1227 	return (_move_history(H_CURR));
1228 }
1229 
1230 
1231 /*
1232  * returns total number of bytes history events' data are using
1233  */
1234 int
history_total_bytes(void)1235 history_total_bytes(void)
1236 {
1237 	HistEvent ev;
1238 	int curr_num, size;
1239 
1240 	if (history(h, &ev, H_CURR) != 0)
1241 		return (-1);
1242 	curr_num = ev.num;
1243 
1244 	history(h, &ev, H_FIRST);
1245 	size = 0;
1246 	do
1247 		size += strlen(ev.str);
1248 	while (history(h, &ev, H_NEXT) == 0);
1249 
1250 	/* get to the same position as before */
1251 	history(h, &ev, H_PREV_EVENT, curr_num);
1252 
1253 	return (size);
1254 }
1255 
1256 
1257 /*
1258  * sets the position in the history list to ``pos''
1259  */
1260 int
history_set_pos(int pos)1261 history_set_pos(int pos)
1262 {
1263 	HistEvent ev;
1264 	int curr_num;
1265 
1266 	if (pos > history_length || pos < 0)
1267 		return (-1);
1268 
1269 	history(h, &ev, H_CURR);
1270 	curr_num = ev.num;
1271 
1272 	if (history(h, &ev, H_SET, pos)) {
1273 		history(h, &ev, H_SET, curr_num);
1274 		return(-1);
1275 	}
1276 	return (0);
1277 }
1278 
1279 
1280 /*
1281  * returns previous event in history and shifts pointer accordingly
1282  */
1283 HIST_ENTRY *
previous_history(void)1284 previous_history(void)
1285 {
1286 
1287 	return (_move_history(H_PREV));
1288 }
1289 
1290 
1291 /*
1292  * returns next event in history and shifts pointer accordingly
1293  */
1294 HIST_ENTRY *
next_history(void)1295 next_history(void)
1296 {
1297 
1298 	return (_move_history(H_NEXT));
1299 }
1300 
1301 
1302 /*
1303  * searches for first history event containing the str
1304  */
1305 int
history_search(const char * str,int direction)1306 history_search(const char *str, int direction)
1307 {
1308 	HistEvent ev;
1309 	const char *strp;
1310 	int curr_num;
1311 
1312 	if (history(h, &ev, H_CURR) != 0)
1313 		return (-1);
1314 	curr_num = ev.num;
1315 
1316 	for (;;) {
1317 		if ((strp = strstr(ev.str, str)) != NULL)
1318 			return (int) (strp - ev.str);
1319 		if (history(h, &ev, direction < 0 ? H_NEXT:H_PREV) != 0)
1320 			break;
1321 	}
1322 	history(h, &ev, H_SET, curr_num);
1323 	return (-1);
1324 }
1325 
1326 
1327 /*
1328  * searches for first history event beginning with str
1329  */
1330 int
history_search_prefix(const char * str,int direction)1331 history_search_prefix(const char *str, int direction)
1332 {
1333 	HistEvent ev;
1334 
1335 	return (history(h, &ev, direction < 0? H_PREV_STR:H_NEXT_STR, str));
1336 }
1337 
1338 
1339 /*
1340  * search for event in history containing str, starting at offset
1341  * abs(pos); continue backward, if pos<0, forward otherwise
1342  */
1343 /* ARGSUSED */
1344 int
history_search_pos(const char * str,int direction,int pos)1345 history_search_pos(const char *str,
1346 		   int direction __attribute__((__unused__)), int pos)
1347 {
1348 	HistEvent ev;
1349 	int curr_num, off;
1350 
1351 	off = (pos > 0) ? pos : -pos;
1352 	pos = (pos > 0) ? 1 : -1;
1353 
1354 	if (history(h, &ev, H_CURR) != 0)
1355 		return (-1);
1356 	curr_num = ev.num;
1357 
1358 	if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1359 		return (-1);
1360 
1361 
1362 	for (;;) {
1363 		if (strstr(ev.str, str))
1364 			return (off);
1365 		if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1366 			break;
1367 	}
1368 
1369 	/* set "current" pointer back to previous state */
1370 	history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1371 
1372 	return (-1);
1373 }
1374 
1375 
1376 /********************************/
1377 /* completion functions */
1378 
1379 /*
1380  * does tilde expansion of strings of type ``~user/foo''
1381  * if ``user'' isn't valid user name or ``txt'' doesn't start
1382  * w/ '~', returns pointer to strdup()ed copy of ``txt''
1383  *
1384  * it's callers's responsibility to free() returned string
1385  */
1386 char *
tilde_expand(char * txt)1387 tilde_expand(char *txt)
1388 {
1389 	struct passwd *pass;
1390 	char *temp;
1391 	size_t len = 0;
1392 #ifdef __NetBSD__
1393 	struct passwd pwres;
1394 	char pwbuf[1024];
1395 #endif
1396 
1397 	if (txt[0] != '~')
1398 		return (strdup(txt));
1399 
1400 	temp = strchr(txt + 1, '/');
1401 	if (temp == NULL) {
1402 		temp = strdup(txt + 1);
1403 		if (temp == NULL)
1404 			return NULL;
1405 	} else {
1406 		len = temp - txt + 1;	/* text until string after slash */
1407 		temp = malloc(len);
1408 		if (temp == NULL)
1409 			return NULL;
1410 		(void)strncpy(temp, txt + 1, len - 2);
1411 		temp[len - 2] = '\0';
1412 	}
1413 #ifdef __NetBSD__
1414 	if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
1415 		pass = NULL;
1416 #else
1417 	pass = getpwnam(temp);
1418 #endif
1419 	free(temp);		/* value no more needed */
1420 	if (pass == NULL)
1421 		return (strdup(txt));
1422 
1423 	/* update pointer txt to point at string immedially following */
1424 	/* first slash */
1425 	txt += len;
1426 
1427 	len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
1428 	temp = malloc(len);
1429 	if (temp == NULL)
1430 		return NULL;
1431 	(void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
1432 
1433 	return (temp);
1434 }
1435 
1436 
1437 /*
1438  * return first found file name starting by the ``text'' or NULL if no
1439  * such file can be found
1440  * value of ``state'' is ignored
1441  *
1442  * it's caller's responsibility to free returned string
1443  */
1444 char *
rl_filename_completion_function(const char * text,int state)1445 rl_filename_completion_function(const char *text, int state)
1446 {
1447 	static DIR *dir = NULL;
1448 	static char *filename = NULL, *dirname = NULL;
1449 	static size_t filename_len = 0;
1450 	struct dirent *entry;
1451 	char *temp;
1452 	size_t len;
1453 
1454 	if (state == 0 || dir == NULL) {
1455 		temp = strrchr(text, '/');
1456 		if (temp) {
1457 			char *nptr;
1458 			size_t sz;
1459 			temp++;
1460 			sz = strlen(temp) + 1;
1461 			nptr = realloc(filename, sz);
1462 			if (nptr == NULL) {
1463 				free(filename);
1464 				return NULL;
1465 			}
1466 			filename = nptr;
1467 			(void)strlcpy(filename, temp, sz);
1468 			len = temp - text;	/* including last slash */
1469 			nptr = realloc(dirname, len + 1);
1470 			if (nptr == NULL) {
1471 				free(filename);
1472 				return NULL;
1473 			}
1474 			dirname = nptr;
1475 			(void)strncpy(dirname, text, len);
1476 			dirname[len] = '\0';
1477 		} else {
1478 			if (*text == 0)
1479 				filename = NULL;
1480 			else {
1481 				filename = strdup(text);
1482 				if (filename == NULL)
1483 					return NULL;
1484 			}
1485 			dirname = NULL;
1486 		}
1487 
1488 		/* support for ``~user'' syntax */
1489 		if (dirname && *dirname == '~') {
1490 			char *nptr;
1491 			size_t sz;
1492 			temp = tilde_expand(dirname);
1493 			if (temp == NULL)
1494 				return NULL;
1495 			sz =  strlen(temp) + 1;
1496 			nptr = realloc(dirname, sz);
1497 			if (nptr == NULL) {
1498 				free(dirname);
1499 				return NULL;
1500 			}
1501 			dirname = nptr;
1502 			(void)strlcpy(dirname, temp, sz);
1503 			free(temp);	/* no longer needed */
1504 		}
1505 		/* will be used in cycle */
1506 		filename_len = filename ? strlen(filename) : 0;
1507 
1508 		if (dir != NULL) {
1509 			(void)closedir(dir);
1510 			dir = NULL;
1511 		}
1512 		dir = opendir(dirname ? dirname : ".");
1513 		if (!dir)
1514 			return (NULL);	/* cannot open the directory */
1515 	}
1516 	/* find the match */
1517 	while ((entry = readdir(dir)) != NULL) {
1518 		/* skip . and .. */
1519 		if (entry->d_name[0] == '.' && (!entry->d_name[1]
1520 		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
1521 			continue;
1522 		if (filename_len == 0)
1523 			break;
1524 		/* otherwise, get first entry where first */
1525 		/* filename_len characters are equal	  */
1526 		if (entry->d_name[0] == filename[0]
1527 #if defined(__SVR4) || defined(__linux__)
1528 		    && strlen(entry->d_name) >= filename_len
1529 #else
1530 		    && entry->d_namlen >= filename_len
1531 #endif
1532 		    && strncmp(entry->d_name, filename,
1533 			filename_len) == 0)
1534 			break;
1535 	}
1536 
1537 	if (entry) {		/* match found */
1538 
1539 		struct stat stbuf;
1540 #if defined(__SVR4) || defined(__linux__)
1541 		len = strlen(entry->d_name) +
1542 #else
1543 		len = entry->d_namlen +
1544 #endif
1545 		    ((dirname) ? strlen(dirname) : 0) + 1 + 1;
1546 		temp = malloc(len);
1547 		if (temp == NULL)
1548 			return NULL;
1549 		(void)snprintf(temp, len, "%s%s",
1550 		    dirname ? dirname : "", entry->d_name);
1551 
1552 		/* test, if it's directory */
1553 		if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
1554 			strlcat(temp, "/", len);
1555 	} else {
1556 		(void)closedir(dir);
1557 		dir = NULL;
1558 		temp = NULL;
1559 	}
1560 
1561 	return (temp);
1562 }
1563 
1564 
1565 /*
1566  * a completion generator for usernames; returns _first_ username
1567  * which starts with supplied text
1568  * text contains a partial username preceded by random character
1569  * (usually '~'); state is ignored
1570  * it's callers responsibility to free returned value
1571  */
1572 char *
rl_username_completion_function(const char * text,int state)1573 rl_username_completion_function(const char *text, int state)
1574 {
1575 	struct passwd *pwd;
1576 #ifdef __NetBSD__
1577 	struct passwd pwres;
1578 	char pwbuf[1024];
1579 #endif
1580 
1581 	if (text[0] == '\0')
1582 		return (NULL);
1583 
1584 	if (*text == '~')
1585 		text++;
1586 
1587 	if (state == 0)
1588 		setpwent();
1589 
1590 #ifdef __NetBSD__
1591 	while (getpwent_r(&pwres, pwbuf, sizeof(pwbuf), &pwd) == 0
1592 	    && pwd != NULL && text[0] == pwd->pw_name[0]
1593 	    && strcmp(text, pwd->pw_name) == 0);
1594 #else
1595 	while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
1596 	    && strcmp(text, pwd->pw_name) == 0);
1597 #endif
1598 
1599 	if (pwd == NULL) {
1600 		endpwent();
1601 		return (NULL);
1602 	}
1603 	return (strdup(pwd->pw_name));
1604 }
1605 
1606 
1607 /*
1608  * el-compatible wrapper around rl_complete; needed for key binding
1609  */
1610 /* ARGSUSED */
1611 static unsigned char
_el_rl_complete(EditLine * el,int ch)1612 _el_rl_complete(EditLine *el __attribute__((__unused__)), int ch)
1613 {
1614 	return (unsigned char) rl_complete(0, ch);
1615 }
1616 
1617 /*
1618  * el-compatible wrapper to send TSTP on ^Z
1619  */
1620 /* ARGSUSED */
1621 static unsigned char
_el_rl_tstp(EditLine * el,int ch)1622 _el_rl_tstp(EditLine *el __attribute__((__unused__)), int ch __attribute__((__unused__)))
1623 {
1624 	(void)kill(0, SIGTSTP);
1625 	return CC_NORM;
1626 }
1627 
1628 /*
1629  * returns list of completions for text given
1630  */
1631 char **
completion_matches(const char * text,CPFunction * genfunc)1632 completion_matches(const char *text, CPFunction *genfunc)
1633 {
1634 	char **match_list = NULL, *retstr, *prevstr;
1635 	size_t match_list_len, max_equal, which, i;
1636 	size_t matches;
1637 
1638 	if (h == NULL || e == NULL)
1639 		rl_initialize();
1640 
1641 	matches = 0;
1642 	match_list_len = 1;
1643 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
1644 		/* allow for list terminator here */
1645 		if (matches + 3 >= match_list_len) {
1646 			char **nmatch_list;
1647 			while (matches + 3 >= match_list_len)
1648 				match_list_len <<= 1;
1649 			nmatch_list = realloc(match_list,
1650 			    match_list_len * sizeof(char *));
1651 			if (nmatch_list == NULL) {
1652 				free(match_list);
1653 				return NULL;
1654 			}
1655 			match_list = nmatch_list;
1656 
1657 		}
1658 		match_list[++matches] = retstr;
1659 	}
1660 
1661 	if (!match_list)
1662 		return NULL;	/* nothing found */
1663 
1664 	/* find least denominator and insert it to match_list[0] */
1665 	which = 2;
1666 	prevstr = match_list[1];
1667 	max_equal = strlen(prevstr);
1668 	for (; which <= matches; which++) {
1669 		for (i = 0; i < max_equal &&
1670 		    prevstr[i] == match_list[which][i]; i++)
1671 			continue;
1672 		max_equal = i;
1673 	}
1674 
1675 	retstr = malloc(max_equal + 1);
1676 	if (retstr == NULL) {
1677 		free(match_list);
1678 		return NULL;
1679 	}
1680 	(void)strncpy(retstr, match_list[1], max_equal);
1681 	retstr[max_equal] = '\0';
1682 	match_list[0] = retstr;
1683 
1684 	/* add NULL as last pointer to the array */
1685 	match_list[matches + 1] = (char *) NULL;
1686 
1687 	return (match_list);
1688 }
1689 
1690 /*
1691  * Sort function for qsort(). Just wrapper around strcasecmp().
1692  */
1693 static int
_rl_qsort_string_compare(i1,i2)1694 _rl_qsort_string_compare(i1, i2)
1695 	const void *i1, *i2;
1696 {
1697 	const char *s1 = ((const char * const *)i1)[0];
1698 	const char *s2 = ((const char * const *)i2)[0];
1699 
1700 	return strcasecmp(s1, s2);
1701 }
1702 
1703 /*
1704  * Display list of strings in columnar format on readline's output stream.
1705  * 'matches' is list of strings, 'len' is number of strings in 'matches',
1706  * 'max' is maximum length of string in 'matches'.
1707  */
1708 void
rl_display_match_list(matches,len,max)1709 rl_display_match_list (matches, len, max)
1710      char **matches;
1711      int len, max;
1712 {
1713 	int i, idx, limit, count;
1714 	int screenwidth = e->el_term.t_size.h;
1715 
1716 	/*
1717 	 * Find out how many entries can be put on one line, count
1718 	 * with two spaces between strings.
1719 	 */
1720 	limit = screenwidth / (max + 2);
1721 	if (limit == 0)
1722 		limit = 1;
1723 
1724 	/* how many lines of output */
1725 	count = len / limit;
1726 	if (count * limit < len)
1727 		count++;
1728 
1729 	/* Sort the items if they are not already sorted. */
1730 	qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
1731 	    _rl_qsort_string_compare);
1732 
1733 	idx = 1;
1734 	for(; count > 0; count--) {
1735 		for(i = 0; i < limit && matches[idx]; i++, idx++)
1736 			(void)fprintf(e->el_outfile, "%-*s  ", max,
1737 			    matches[idx]);
1738 		(void)fprintf(e->el_outfile, "\n");
1739 	}
1740 }
1741 
1742 /*
1743  * Complete the word at or before point, called by rl_complete()
1744  * 'what_to_do' says what to do with the completion.
1745  * `?' means list the possible completions.
1746  * TAB means do standard completion.
1747  * `*' means insert all of the possible completions.
1748  * `!' means to do standard completion, and list all possible completions if
1749  * there is more than one.
1750  *
1751  * Note: '*' support is not implemented
1752  */
1753 static int
_rl_complete_internal(int what_to_do)1754 _rl_complete_internal(int what_to_do)
1755 {
1756 	Function *complet_func;
1757 	const LineInfo *li;
1758 	char *temp, **matches;
1759 	const char *ctemp;
1760 	size_t len;
1761 
1762 	rl_completion_type = what_to_do;
1763 
1764 	if (h == NULL || e == NULL)
1765 		rl_initialize();
1766 
1767 	complet_func = rl_completion_entry_function;
1768 	if (!complet_func)
1769 		complet_func = (Function *)(void *)rl_filename_completion_function;
1770 
1771 	/* We now look backwards for the start of a filename/variable word */
1772 	li = el_line(e);
1773 	ctemp = (const char *) li->cursor;
1774 	while (ctemp > li->buffer
1775 	    && !strchr(rl_basic_word_break_characters, ctemp[-1])
1776 	    && (!rl_special_prefixes
1777 		|| !strchr(rl_special_prefixes, ctemp[-1]) ) )
1778 		ctemp--;
1779 
1780 	len = li->cursor - ctemp;
1781 	temp = alloca(len + 1);
1782 	(void)strncpy(temp, ctemp, len);
1783 	temp[len] = '\0';
1784 
1785 	/* these can be used by function called in completion_matches() */
1786 	/* or (*rl_attempted_completion_function)() */
1787 	_rl_update_pos();
1788 
1789 	if (rl_attempted_completion_function) {
1790 		int end = li->cursor - li->buffer;
1791 		matches = (*rl_attempted_completion_function) (temp, (int)
1792 		    (end - len), end);
1793 	} else
1794 		matches = 0;
1795 	if (!rl_attempted_completion_function ||
1796 	     (!rl_attempted_completion_over && !matches))
1797 		matches = completion_matches(temp, (CPFunction *)complet_func);
1798 
1799 	if (rl_attempted_completion_over)
1800 		rl_attempted_completion_over = 0;
1801 
1802 	if (matches) {
1803 		int i, retval = CC_REFRESH;
1804 		int matches_num, maxlen, match_len, match_display=1;
1805 
1806 		/*
1807 		 * Only replace the completed string with common part of
1808 		 * possible matches if there is possible completion.
1809 		 */
1810 		if (matches[0][0] != '\0') {
1811 			el_deletestr(e, (int) len);
1812 			el_insertstr(e, matches[0]);
1813 		}
1814 
1815 		if (what_to_do == '?')
1816 			goto display_matches;
1817 
1818 		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
1819 			/*
1820 			 * We found exact match. Add a space after
1821 			 * it, unless we do filename completion and the
1822 			 * object is a directory.
1823 			 */
1824 			size_t alen = strlen(matches[0]);
1825 			if ((complet_func !=
1826 			    (Function *)rl_filename_completion_function
1827 			      || (alen > 0 && (matches[0])[alen - 1] != '/'))
1828 			    && rl_completion_append_character) {
1829 				char buf[2];
1830 				buf[0] = rl_completion_append_character;
1831 				buf[1] = '\0';
1832 				el_insertstr(e, buf);
1833 			}
1834 		} else if (what_to_do == '!') {
1835     display_matches:
1836 			/*
1837 			 * More than one match and requested to list possible
1838 			 * matches.
1839 			 */
1840 
1841 			for(i=1, maxlen=0; matches[i]; i++) {
1842 				match_len = strlen(matches[i]);
1843 				if (match_len > maxlen)
1844 					maxlen = match_len;
1845 			}
1846 			matches_num = i - 1;
1847 
1848 			/* newline to get on next line from command line */
1849 			(void)fprintf(e->el_outfile, "\n");
1850 
1851 			/*
1852 			 * If there are too many items, ask user for display
1853 			 * confirmation.
1854 			 */
1855 			if (matches_num > rl_completion_query_items) {
1856 				(void)fprintf(e->el_outfile,
1857 				    "Display all %d possibilities? (y or n) ",
1858 				    matches_num);
1859 				(void)fflush(e->el_outfile);
1860 				if (getc(stdin) != 'y')
1861 					match_display = 0;
1862 				(void)fprintf(e->el_outfile, "\n");
1863 			}
1864 
1865 			if (match_display)
1866 				rl_display_match_list(matches, matches_num,
1867 					maxlen);
1868 			retval = CC_REDISPLAY;
1869 		} else if (matches[0][0]) {
1870 			/*
1871 			 * There was some common match, but the name was
1872 			 * not complete enough. Next tab will print possible
1873 			 * completions.
1874 			 */
1875 			el_beep(e);
1876 		} else {
1877 			/* lcd is not a valid object - further specification */
1878 			/* is needed */
1879 			el_beep(e);
1880 			retval = CC_NORM;
1881 		}
1882 
1883 		/* free elements of array and the array itself */
1884 		for (i = 0; matches[i]; i++)
1885 			free(matches[i]);
1886 		free(matches), matches = NULL;
1887 
1888 		return (retval);
1889 	}
1890 	return (CC_NORM);
1891 }
1892 
1893 
1894 /*
1895  * complete word at current point
1896  */
1897 int
1898 /*ARGSUSED*/
rl_complete(int ignore,int invoking_key)1899 rl_complete(int ignore, int invoking_key)
1900 {
1901 	if (h == NULL || e == NULL)
1902 		rl_initialize();
1903 
1904 	if (rl_inhibit_completion) {
1905 		char arr[2];
1906 		arr[0] = (char)invoking_key;
1907 		arr[1] = '\0';
1908 		el_insertstr(e, arr);
1909 		return (CC_REFRESH);
1910 	} else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
1911 		return _rl_complete_internal('?');
1912 	else if (_rl_complete_show_all)
1913 		return _rl_complete_internal('!');
1914 	else
1915 		return _rl_complete_internal(TAB);
1916 }
1917 
1918 
1919 /*
1920  * misc other functions
1921  */
1922 
1923 /*
1924  * bind key c to readline-type function func
1925  */
1926 int
rl_bind_key(int c,int func (int,int))1927 rl_bind_key(int c, int func(int, int))
1928 {
1929 	int retval = -1;
1930 
1931 	if (h == NULL || e == NULL)
1932 		rl_initialize();
1933 
1934 	if (func == rl_insert) {
1935 		/* XXX notice there is no range checking of ``c'' */
1936 		e->el_map.key[c] = ED_INSERT;
1937 		retval = 0;
1938 	}
1939 	return (retval);
1940 }
1941 
1942 
1943 /*
1944  * read one key from input - handles chars pushed back
1945  * to input stream also
1946  */
1947 int
rl_read_key(void)1948 rl_read_key(void)
1949 {
1950 	char fooarr[2 * sizeof(int)];
1951 
1952 	if (e == NULL || h == NULL)
1953 		rl_initialize();
1954 
1955 	return (el_getc(e, fooarr));
1956 }
1957 
1958 
1959 /*
1960  * reset the terminal
1961  */
1962 /* ARGSUSED */
1963 void
rl_reset_terminal(const char * p)1964 rl_reset_terminal(const char *p __attribute__((__unused__)))
1965 {
1966 
1967 	if (h == NULL || e == NULL)
1968 		rl_initialize();
1969 	el_reset(e);
1970 }
1971 
1972 
1973 /*
1974  * insert character ``c'' back into input stream, ``count'' times
1975  */
1976 int
rl_insert(int count,int c)1977 rl_insert(int count, int c)
1978 {
1979 	char arr[2];
1980 
1981 	if (h == NULL || e == NULL)
1982 		rl_initialize();
1983 
1984 	/* XXX - int -> char conversion can lose on multichars */
1985 	arr[0] = c;
1986 	arr[1] = '\0';
1987 
1988 	for (; count > 0; count--)
1989 		el_push(e, arr);
1990 
1991 	return (0);
1992 }
1993 
1994 /*ARGSUSED*/
1995 int
rl_newline(int count,int c)1996 rl_newline(int count, int c)
1997 {
1998 	/*
1999 	 * Readline-4.0 appears to ignore the args.
2000 	 */
2001 	return rl_insert(1, '\n');
2002 }
2003 
2004 /*ARGSUSED*/
2005 static unsigned char
rl_bind_wrapper(EditLine * el,unsigned char c)2006 rl_bind_wrapper(EditLine *el, unsigned char c)
2007 {
2008 	if (map[c] == NULL)
2009 	    return CC_ERROR;
2010 
2011 	_rl_update_pos();
2012 
2013 	(*map[c])(NULL, c);
2014 
2015 	/* If rl_done was set by the above call, deal with it here */
2016 	if (rl_done)
2017 		return CC_EOF;
2018 
2019 	return CC_NORM;
2020 }
2021 
2022 int
rl_add_defun(const char * name,Function * fun,int c)2023 rl_add_defun(const char *name, Function *fun, int c)
2024 {
2025 	char dest[8];
2026 	if (c >= sizeof(map) / sizeof(map[0]) || c < 0)
2027 		return -1;
2028 	map[(unsigned char)c] = fun;
2029 	el_set(e, EL_ADDFN, name, name, rl_bind_wrapper);
2030 	vis(dest, c, VIS_WHITE|VIS_NOSLASH, 0);
2031 	el_set(e, EL_BIND, dest, name);
2032 	return 0;
2033 }
2034 
2035 void
rl_callback_read_char()2036 rl_callback_read_char()
2037 {
2038 	int count = 0, done = 0;
2039 	const char *buf = el_gets(e, &count);
2040 	char *wbuf;
2041 
2042 	if (buf == NULL || count-- <= 0)
2043 		return;
2044 	if (count == 0 && buf[0] == CTRL('d'))
2045 		done = 1;
2046 	if (buf[count] == '\n' || buf[count] == '\r')
2047 		done = 2;
2048 
2049 	if (done && rl_linefunc != NULL) {
2050 		el_set(e, EL_UNBUFFERED, 0);
2051 		if (done == 2) {
2052 		    if ((wbuf = strdup(buf)) != NULL)
2053 			wbuf[count] = '\0';
2054 		} else
2055 			wbuf = NULL;
2056 		(*rl_linefunc)(wbuf);
2057 		el_set(e, EL_UNBUFFERED, 1);
2058 	}
2059 }
2060 
2061 void
rl_callback_handler_install(const char * prompt,VFunctionC * linefunc)2062 rl_callback_handler_install (const char *prompt, VFunctionC *linefunc)
2063 {
2064 	if (e == NULL) {
2065 		rl_initialize();
2066 	}
2067 	if (rl_prompt)
2068 		free(rl_prompt);
2069 	rl_prompt = prompt ? strdup(strchr(prompt, *prompt)) : NULL;
2070 	rl_linefunc = linefunc;
2071 	el_set(e, EL_UNBUFFERED, 1);
2072 }
2073 
2074 void
rl_callback_handler_remove(void)2075 rl_callback_handler_remove(void)
2076 {
2077 	el_set(e, EL_UNBUFFERED, 0);
2078 }
2079 
2080 void
rl_redisplay(void)2081 rl_redisplay(void)
2082 {
2083 	char a[2];
2084 	a[0] = CTRL('r');
2085 	a[1] = '\0';
2086 	el_push(e, a);
2087 }
2088 
2089 int
rl_get_previous_history(int count,int key)2090 rl_get_previous_history(int count, int key)
2091 {
2092 	char a[2];
2093 	a[0] = key;
2094 	a[1] = '\0';
2095 	while (count--)
2096 		el_push(e, a);
2097 	return 0;
2098 }
2099 
2100 void
2101 /*ARGSUSED*/
rl_prep_terminal(int meta_flag)2102 rl_prep_terminal(int meta_flag)
2103 {
2104 	el_set(e, EL_PREP_TERM, 1);
2105 }
2106 
2107 void
rl_deprep_terminal()2108 rl_deprep_terminal()
2109 {
2110 	el_set(e, EL_PREP_TERM, 0);
2111 }
2112 
2113 int
rl_read_init_file(const char * s)2114 rl_read_init_file(const char *s)
2115 {
2116 	return(el_source(e, s));
2117 }
2118 
2119 int
rl_parse_and_bind(const char * line)2120 rl_parse_and_bind(const char *line)
2121 {
2122 	const char **argv;
2123 	int argc;
2124 	Tokenizer *tok;
2125 
2126 	tok = tok_init(NULL);
2127 	tok_str(tok, line, &argc, &argv);
2128 	argc = el_parse(e, argc, argv);
2129 	tok_end(tok);
2130 	return (argc ? 1 : 0);
2131 }
2132 
2133 int
rl_variable_bind(const char * var,const char * value)2134 rl_variable_bind(const char *var, const char *value)
2135 {
2136 	/*
2137 	 * The proper return value is undocument, but this is what the
2138 	 * readline source seems to do.
2139 	 */
2140 	return ((el_set(e, EL_BIND, "", var, value) == -1) ? 1 : 0);
2141 }
2142 
2143 void
rl_stuff_char(int c)2144 rl_stuff_char(int c)
2145 {
2146 	char buf[2];
2147 
2148 	buf[0] = c;
2149 	buf[1] = '\0';
2150 	el_insertstr(e, buf);
2151 }
2152 
2153 static int
_rl_event_read_char(EditLine * el,char * cp)2154 _rl_event_read_char(EditLine *el, char *cp)
2155 {
2156 	int	n, num_read = 0;
2157 
2158 	*cp = 0;
2159 	while (rl_event_hook) {
2160 
2161 		(*rl_event_hook)();
2162 
2163 #if defined(FIONREAD)
2164 		if (ioctl(el->el_infd, FIONREAD, &n) < 0)
2165 			return(-1);
2166 		if (n)
2167 			num_read = read(el->el_infd, cp, 1);
2168 		else
2169 			num_read = 0;
2170 #elif defined(F_SETFL) && defined(O_NDELAY)
2171 		if ((n = fcntl(el->el_infd, F_GETFL, 0)) < 0)
2172 			return(-1);
2173 		if (fcntl(el->el_infd, F_SETFL, n|O_NDELAY) < 0)
2174 			return(-1);
2175 		num_read = read(el->el_infd, cp, 1);
2176 		if (fcntl(el->el_infd, F_SETFL, n))
2177 			return(-1);
2178 #else
2179 		/* not non-blocking, but what you gonna do? */
2180 		num_read = read(el->el_infd, cp, 1);
2181 		return(-1);
2182 #endif
2183 
2184 		if (num_read < 0 && errno == EAGAIN)
2185 			continue;
2186 		if (num_read == 0)
2187 			continue;
2188 		break;
2189 	}
2190 	if (!rl_event_hook)
2191 		el_set(el, EL_GETCFN, EL_BUILTIN_GETCFN);
2192 	return(num_read);
2193 }
2194 
2195 static void
_rl_update_pos(void)2196 _rl_update_pos(void)
2197 {
2198 	const LineInfo *li = el_line(e);
2199 
2200 	rl_point = li->cursor - li->buffer;
2201 	rl_end = li->lastchar - li->buffer;
2202 }
2203 
2204 void
rl_get_screen_size(int * lins,int * cols)2205 rl_get_screen_size (int *lins, int *cols)
2206 {
2207 	extern void _rl__term_get_size(EditLine *, int *, int *);
2208 
2209 	_rl__term_get_size(e, lins, cols);
2210 }
2211 
2212 void
rl_set_screen_size(int lins,int cols)2213 rl_set_screen_size(int lins, int cols)
2214 {
2215 	extern void _rl__term_change_size(EditLine *, int, int);
2216 
2217 	_rl__term_change_size(e, lins, cols);
2218 }
2219