1 /*	$NetBSD: filecomplete.c,v 1.31 2011/09/16 16:13:16 plunky Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jaromir Dolecek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /* AIX requires this to be the first thing in the file.  */
33 #if defined (_AIX) && !defined (__GNUC__)
34  #pragma alloca
35 #endif
36 
37 #include "config.h"
38 
39 /* XXXMYSQL */
40 #ifdef __GNUC__
41 # undef alloca
42 # define alloca(n) __builtin_alloca (n)
43 #else
44 # ifdef HAVE_ALLOCA_H
45 #  include <alloca.h>
46 # else
47 #  ifndef _AIX
48 extern char *alloca ();
49 #  endif
50 # endif
51 #endif
52 
53 #if !defined(lint) && !defined(SCCSID)
54 #endif /* not lint && not SCCSID */
55 
56 #include <sys/types.h>
57 #include <sys/stat.h>
58 #include <stdio.h>
59 #include <dirent.h>
60 #include <string.h>
61 #include <pwd.h>
62 #include <ctype.h>
63 #include <stdlib.h>
64 #include <unistd.h>
65 #include <limits.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #ifdef HAVE_VIS_H
69 #include <vis.h>
70 #else
71 #include "np/vis.h"
72 #endif
73 #ifdef HAVE_ALLOCA_H
74 #include <alloca.h>
75 #endif
76 #include "el.h"
77 #include "fcns.h"		/* for EL_NUM_FCNS */
78 #include "histedit.h"
79 #include "filecomplete.h"
80 
81 static const Char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@',
82     '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' };
83 
84 
85 /********************************/
86 /* completion functions */
87 
88 /*
89  * does tilde expansion of strings of type ``~user/foo''
90  * if ``user'' isn't valid user name or ``txt'' doesn't start
91  * w/ '~', returns pointer to strdup()ed copy of ``txt''
92  *
93  * it's callers's responsibility to free() returned string
94  */
95 char *
fn_tilde_expand(const char * txt)96 fn_tilde_expand(const char *txt)
97 {
98 #if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT)
99 	struct passwd pwres;
100 	char pwbuf[1024];
101 #endif
102 	struct passwd *pass;
103 	char *temp;
104 	size_t len = 0;
105 
106 	if (txt[0] != '~')
107 		return strdup(txt);
108 
109 	temp = strchr(txt + 1, '/');
110 	if (temp == NULL) {
111 		temp = strdup(txt + 1);
112 		if (temp == NULL)
113 			return NULL;
114 	} else {
115 		/* text until string after slash */
116 		len = (size_t)(temp - txt + 1);
117 		temp = el_malloc(len * sizeof(*temp));
118 		if (temp == NULL)
119 			return NULL;
120 		(void)strncpy(temp, txt + 1, len - 2);
121 		temp[len - 2] = '\0';
122 	}
123 	if (temp[0] == 0) {
124 #ifdef HAVE_GETPW_R_POSIX
125  		if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf),
126 		    &pass) != 0)
127  			pass = NULL;
128 #elif HAVE_GETPW_R_DRAFT
129 		pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf));
130 #else
131 		pass = getpwuid(getuid());
132 #endif
133 	} else {
134 #ifdef HAVE_GETPW_R_POSIX
135 		if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0)
136 			pass = NULL;
137 #elif HAVE_GETPW_R_DRAFT
138 		pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf));
139 #else
140 		pass = getpwnam(temp);
141 #endif
142 	}
143 	el_free(temp);		/* value no more needed */
144 	if (pass == NULL)
145 		return strdup(txt);
146 
147 	/* update pointer txt to point at string immedially following */
148 	/* first slash */
149 	txt += len;
150 
151 	len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1;
152 	temp = el_malloc(len * sizeof(*temp));
153 	if (temp == NULL)
154 		return NULL;
155 	(void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt);
156 
157 	return temp;
158 }
159 
160 
161 /*
162  * return first found file name starting by the ``text'' or NULL if no
163  * such file can be found
164  * value of ``state'' is ignored
165  *
166  * it's caller's responsibility to free returned string
167  */
168 char *
fn_filename_completion_function(const char * text,int state)169 fn_filename_completion_function(const char *text, int state)
170 {
171 	static DIR *dir = NULL;
172 	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
173 	static size_t filename_len = 0;
174 	struct dirent *entry;
175 	char *temp;
176 	size_t len;
177 
178 	if (state == 0 || dir == NULL) {
179 		temp = strrchr(text, '/');
180 		if (temp) {
181 			char *nptr;
182 			temp++;
183 			nptr = el_realloc(filename, (strlen(temp) + 1) *
184 			    sizeof(*nptr));
185 			if (nptr == NULL) {
186 				el_free(filename);
187 				filename = NULL;
188 				return NULL;
189 			}
190 			filename = nptr;
191 			(void)strcpy(filename, temp);
192 			len = (size_t)(temp - text);	/* including last slash */
193 
194 			nptr = el_realloc(dirname, (len + 1) *
195 			    sizeof(*nptr));
196 			if (nptr == NULL) {
197 				el_free(dirname);
198 				dirname = NULL;
199 				return NULL;
200 			}
201 			dirname = nptr;
202 			(void)strncpy(dirname, text, len);
203 			dirname[len] = '\0';
204 		} else {
205 			el_free(filename);
206 			if (*text == 0)
207 				filename = NULL;
208 			else {
209 				filename = strdup(text);
210 				if (filename == NULL)
211 					return NULL;
212 			}
213 			el_free(dirname);
214 			dirname = NULL;
215 		}
216 
217 		if (dir != NULL) {
218 			(void)closedir(dir);
219 			dir = NULL;
220 		}
221 
222 		/* support for ``~user'' syntax */
223 
224 		el_free(dirpath);
225 		dirpath = NULL;
226 		if (dirname == NULL) {
227 			if ((dirname = strdup("")) == NULL)
228 				return NULL;
229 			dirpath = strdup("./");
230 		} else if (*dirname == '~')
231 			dirpath = fn_tilde_expand(dirname);
232 		else
233 			dirpath = strdup(dirname);
234 
235 		if (dirpath == NULL)
236 			return NULL;
237 
238 		dir = opendir(dirpath);
239 		if (!dir)
240 			return NULL;	/* cannot open the directory */
241 
242 		/* will be used in cycle */
243 		filename_len = filename ? strlen(filename) : 0;
244 	}
245 
246 	/* find the match */
247 	while ((entry = readdir(dir)) != NULL) {
248 		/* skip . and .. */
249 		if (entry->d_name[0] == '.' && (!entry->d_name[1]
250 		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
251 			continue;
252 		if (filename_len == 0)
253 			break;
254 		/* otherwise, get first entry where first */
255 		/* filename_len characters are equal	  */
256 		if (entry->d_name[0] == filename[0]
257 #if HAVE_STRUCT_DIRENT_D_NAMLEN
258 		    && entry->d_namlen >= filename_len
259 #else
260 		    && strlen(entry->d_name) >= filename_len
261 #endif
262 		    && strncmp(entry->d_name, filename,
263 			filename_len) == 0)
264 			break;
265 	}
266 
267 	if (entry) {		/* match found */
268 
269 #if HAVE_STRUCT_DIRENT_D_NAMLEN
270 		len = entry->d_namlen;
271 #else
272 		len = strlen(entry->d_name);
273 #endif
274 
275 		len = strlen(dirname) + len + 1;
276 		temp = el_malloc(len * sizeof(*temp));
277 		if (temp == NULL)
278 			return NULL;
279 		(void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
280 	} else {
281 		(void)closedir(dir);
282 		dir = NULL;
283 		temp = NULL;
284 	}
285 
286 	return temp;
287 }
288 
289 
290 static const char *
append_char_function(const char * name)291 append_char_function(const char *name)
292 {
293 	struct stat stbuf;
294 	char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
295 	const char *rs = " ";
296 
297 	if (stat(expname ? expname : name, &stbuf) == -1)
298 		goto out;
299 	if (S_ISDIR(stbuf.st_mode))
300 		rs = "/";
301 out:
302 	if (expname)
303 		el_free(expname);
304 	return rs;
305 }
306 /*
307  * returns list of completions for text given
308  * non-static for readline.
309  */
310 char ** completion_matches(const char *, char *(*)(const char *, int));
311 char **
completion_matches(const char * text,char * (* genfunc)(const char *,int))312 completion_matches(const char *text, char *(*genfunc)(const char *, int))
313 {
314 	char **match_list = NULL, *retstr, *prevstr;
315 	size_t match_list_len, max_equal, which, i;
316 	size_t matches;
317 
318 	matches = 0;
319 	match_list_len = 1;
320 	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
321 		/* allow for list terminator here */
322 		if (matches + 3 >= match_list_len) {
323 			char **nmatch_list;
324 			while (matches + 3 >= match_list_len)
325 				match_list_len <<= 1;
326 			nmatch_list = el_realloc(match_list,
327 			    match_list_len * sizeof(*nmatch_list));
328 			if (nmatch_list == NULL) {
329 				el_free(match_list);
330 				return NULL;
331 			}
332 			match_list = nmatch_list;
333 
334 		}
335 		match_list[++matches] = retstr;
336 	}
337 
338 	if (!match_list)
339 		return NULL;	/* nothing found */
340 
341 	/* find least denominator and insert it to match_list[0] */
342 	which = 2;
343 	prevstr = match_list[1];
344 	max_equal = strlen(prevstr);
345 	for (; which <= matches; which++) {
346 		for (i = 0; i < max_equal &&
347 		    prevstr[i] == match_list[which][i]; i++)
348 			continue;
349 		max_equal = i;
350 	}
351 
352 	retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
353 	if (retstr == NULL) {
354 		el_free(match_list);
355 		return NULL;
356 	}
357 	(void)strncpy(retstr, match_list[1], max_equal);
358 	retstr[max_equal] = '\0';
359 	match_list[0] = retstr;
360 
361 	/* add NULL as last pointer to the array */
362 	match_list[matches + 1] = NULL;
363 
364 	return match_list;
365 }
366 
367 /*
368  * Sort function for qsort(). Just wrapper around strcasecmp().
369  */
370 static int
_fn_qsort_string_compare(const void * i1,const void * i2)371 _fn_qsort_string_compare(const void *i1, const void *i2)
372 {
373 	const char *s1 = ((const char * const *)i1)[0];
374 	const char *s2 = ((const char * const *)i2)[0];
375 
376 	return strcasecmp(s1, s2);
377 }
378 
379 /*
380  * Display list of strings in columnar format on readline's output stream.
381  * 'matches' is list of strings, 'num' is number of strings in 'matches',
382  * 'width' is maximum length of string in 'matches'.
383  *
384  * matches[0] is not one of the match strings, but it is counted in
385  * num, so the strings are matches[1] *through* matches[num-1].
386  */
387 void
fn_display_match_list(EditLine * el,char ** matches,size_t num,size_t width)388 fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width)
389 {
390 	size_t line, lines, col, cols, thisguy;
391 	int screenwidth = el->el_terminal.t_size.h;
392 
393 	/* Ignore matches[0]. Avoid 1-based array logic below. */
394 	matches++;
395 	num--;
396 
397 	/*
398 	 * Find out how many entries can be put on one line; count
399 	 * with one space between strings the same way it's printed.
400 	 */
401 	cols = (size_t)screenwidth / (width + 1);
402 	if (cols == 0)
403 		cols = 1;
404 
405 	/* how many lines of output, rounded up */
406 	lines = (num + cols - 1) / cols;
407 
408 	/* Sort the items. */
409 	qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
410 
411 	/*
412 	 * On the ith line print elements i, i+lines, i+lines*2, etc.
413 	 */
414 	for (line = 0; line < lines; line++) {
415 		for (col = 0; col < cols; col++) {
416 			thisguy = line + col * lines;
417 			if (thisguy >= num)
418 				break;
419 			(void)fprintf(el->el_outfile, "%s%-*s",
420 			    col == 0 ? "" : " ", (int)width, matches[thisguy]);
421 		}
422 		(void)fprintf(el->el_outfile, "\n");
423 	}
424 }
425 
426 /*
427  * Complete the word at or before point,
428  * 'what_to_do' says what to do with the completion.
429  * \t   means do standard completion.
430  * `?' means list the possible completions.
431  * `*' means insert all of the possible completions.
432  * `!' means to do standard completion, and list all possible completions if
433  * there is more than one.
434  *
435  * Note: '*' support is not implemented
436  *       '!' could never be invoked
437  */
438 int
fn_complete(EditLine * el,char * (* complet_func)(const char *,int),char ** (* attempted_completion_function)(const char *,int,int),const Char * word_break,const Char * special_prefixes,const char * (* app_func)(const char *),size_t query_items,int * completion_type,int * over,int * point,int * end)439 fn_complete(EditLine *el,
440 	char *(*complet_func)(const char *, int),
441 	char **(*attempted_completion_function)(const char *, int, int),
442 	const Char *word_break, const Char *special_prefixes,
443 	const char *(*app_func)(const char *), size_t query_items,
444 	int *completion_type, int *over, int *point, int *end)
445 {
446 	const TYPE(LineInfo) *li;
447 	Char *temp;
448         char **matches;
449 	const Char *ctemp;
450 	size_t len;
451 	int what_to_do = '\t';
452 	int retval = CC_NORM;
453 
454 	if (el->el_state.lastcmd == el->el_state.thiscmd)
455 		what_to_do = '?';
456 
457 	/* readline's rl_complete() has to be told what we did... */
458 	if (completion_type != NULL)
459 		*completion_type = what_to_do;
460 
461 	if (!complet_func)
462 		complet_func = fn_filename_completion_function;
463 	if (!app_func)
464 		app_func = append_char_function;
465 
466 	/* We now look backwards for the start of a filename/variable word */
467 	li = FUN(el,line)(el);
468 	ctemp = li->cursor;
469 	while (ctemp > li->buffer
470 	    && !Strchr(word_break, ctemp[-1])
471 	    && (!special_prefixes || !Strchr(special_prefixes, ctemp[-1]) ) )
472 		ctemp--;
473 
474 	len = (size_t)(li->cursor - ctemp);
475 #if defined(__SSP__) || defined(__SSP_ALL__)
476 	temp = el_malloc((len + 1) * sizeof(*temp));
477 #else
478 	temp = alloca((len + 1) * sizeof(*temp));
479 #endif
480 	(void)Strncpy(temp, ctemp, len);
481 	temp[len] = '\0';
482 
483 	/* these can be used by function called in completion_matches() */
484 	/* or (*attempted_completion_function)() */
485 	if (point != 0)
486 		*point = (int)(li->cursor - li->buffer);
487 	if (end != NULL)
488 		*end = (int)(li->lastchar - li->buffer);
489 
490 	if (attempted_completion_function) {
491 		int cur_off = (int)(li->cursor - li->buffer);
492 		matches = (*attempted_completion_function)(
493 		    ct_encode_string(temp, &el->el_scratch),
494 		    cur_off - (int)len, cur_off);
495 	} else
496 		matches = 0;
497 	if (!attempted_completion_function ||
498 	    (over != NULL && !*over && !matches))
499 		matches = completion_matches(
500 		    ct_encode_string(temp, &el->el_scratch), complet_func);
501 
502 	if (over != NULL)
503 		*over = 0;
504 
505 	if (matches) {
506 		int i;
507 		size_t matches_num, maxlen, match_len, match_display=1;
508 
509 		retval = CC_REFRESH;
510 		/*
511 		 * Only replace the completed string with common part of
512 		 * possible matches if there is possible completion.
513 		 */
514 		if (matches[0][0] != '\0') {
515 			el_deletestr(el, (int) len);
516 			FUN(el,insertstr)(el,
517 			    ct_decode_string(matches[0], &el->el_scratch));
518 		}
519 
520 		if (what_to_do == '?')
521 			goto display_matches;
522 
523 		if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
524 			/*
525 			 * We found exact match. Add a space after
526 			 * it, unless we do filename completion and the
527 			 * object is a directory.
528 			 */
529 			FUN(el,insertstr)(el,
530 			    ct_decode_string((*app_func)(matches[0]),
531 			    &el->el_scratch));
532 		} else if (what_to_do == '!') {
533     display_matches:
534 			/*
535 			 * More than one match and requested to list possible
536 			 * matches.
537 			 */
538 
539 			for(i = 1, maxlen = 0; matches[i]; i++) {
540 				match_len = strlen(matches[i]);
541 				if (match_len > maxlen)
542 					maxlen = match_len;
543 			}
544 			/* matches[1] through matches[i-1] are available */
545 			matches_num = (size_t)(i - 1);
546 
547 			/* newline to get on next line from command line */
548 			(void)fprintf(el->el_outfile, "\n");
549 
550 			/*
551 			 * If there are too many items, ask user for display
552 			 * confirmation.
553 			 */
554 			if (matches_num > query_items) {
555 				(void)fprintf(el->el_outfile,
556 				    "Display all %zu possibilities? (y or n) ",
557 				    matches_num);
558 				(void)fflush(el->el_outfile);
559 				if (getc(stdin) != 'y')
560 					match_display = 0;
561 				(void)fprintf(el->el_outfile, "\n");
562 			}
563 
564 			if (match_display) {
565 				/*
566 				 * Interface of this function requires the
567 				 * strings be matches[1..num-1] for compat.
568 				 * We have matches_num strings not counting
569 				 * the prefix in matches[0], so we need to
570 				 * add 1 to matches_num for the call.
571 				 */
572 				fn_display_match_list(el, matches,
573 				    matches_num+1, maxlen);
574 			}
575 			retval = CC_REDISPLAY;
576 		} else if (matches[0][0]) {
577 			/*
578 			 * There was some common match, but the name was
579 			 * not complete enough. Next tab will print possible
580 			 * completions.
581 			 */
582 			el_beep(el);
583 		} else {
584 			/* lcd is not a valid object - further specification */
585 			/* is needed */
586 			el_beep(el);
587 			retval = CC_NORM;
588 		}
589 
590 		/* free elements of array and the array itself */
591 		for (i = 0; matches[i]; i++)
592 			el_free(matches[i]);
593 		el_free(matches);
594 		matches = NULL;
595 	}
596 #if defined(__SSP__) || defined(__SSP_ALL__)
597 	el_free(temp);
598 #endif
599 	return retval;
600 }
601 
602 /*
603  * el-compatible wrapper around rl_complete; needed for key binding
604  */
605 /* ARGSUSED */
606 unsigned char
_el_fn_complete(EditLine * el,int ch)607 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
608 {
609 	return (unsigned char)fn_complete(el, NULL, NULL,
610 	    break_chars, NULL, NULL, (size_t)100,
611 	    NULL, NULL, NULL, NULL);
612 }
613