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