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