filecomplete.c revision 1.49
1/*	$NetBSD: filecomplete.c,v 1.49 2018/05/02 08:45:03 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.49 2018/05/02 08:45:03 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
129static int
130needs_escaping(char c)
131{
132	switch (c) {
133	case '\'':
134	case '"':
135	case '(':
136	case ')':
137	case '\\':
138	case '<':
139	case '>':
140	case '$':
141	case '#':
142	case ' ':
143	case '\n':
144	case '\t':
145	case '?':
146	case ';':
147	case '`':
148	case '@':
149	case '=':
150	case '|':
151	case '{':
152	case '}':
153	case '&':
154	case '*':
155	case '[':
156		return 1;
157	default:
158		return 0;
159	}
160}
161
162static char *
163escape_filename(EditLine * el, const char *filename)
164{
165	size_t original_len = 0;
166	size_t escaped_character_count = 0;
167	size_t offset = 0;
168	size_t newlen;
169	const char *s;
170	char c;
171	size_t s_quoted = 0;	/* does the input contain a single quote */
172	size_t d_quoted = 0;	/* does the input contain a double quote */
173	char *escaped_str;
174	wchar_t *temp = el->el_line.buffer;
175
176	while (temp != el->el_line.cursor) {
177		/*
178		 * If we see a single quote but have not seen a double quote so far
179		 * set/unset s_quote
180		 */
181		if (temp[0] == '\'' && !d_quoted)
182			s_quoted = !s_quoted;
183		/*
184		 * vice versa to the above condition
185		 */
186		else if (temp[0] == '"' && !s_quoted)
187			d_quoted = !d_quoted;
188		temp++;
189	}
190
191	/* Count number of special characters so that we can calculate
192	 * number of extra bytes needed in the new string
193	 */
194	for (s = filename; *s; s++, original_len++) {
195		c = *s;
196		/* Inside a single quote only single quotes need escaping */
197		if (s_quoted && c == '\'') {
198			escaped_character_count += 3;
199			continue;
200		}
201		/* Inside double quotes only ", \, ` and $ need escaping */
202		if (d_quoted && (c == '"' || c == '\\' || c == '`' || c == '$')) {
203			escaped_character_count++;
204			continue;
205		}
206		if (!s_quoted && !d_quoted && needs_escaping(c))
207			escaped_character_count++;
208	}
209
210	newlen = original_len + escaped_character_count + 1;
211	if ((escaped_str = el_malloc(newlen)) == NULL)
212		return NULL;
213
214	for (s = filename; *s; s++) {
215		c = *s;
216		if (!needs_escaping(c)) {
217			/* no escaping is required continue as usual */
218			escaped_str[offset++] = c;
219			continue;
220		}
221
222		/* single quotes inside single quotes require special handling */
223		if (c == '\'' && s_quoted) {
224			escaped_str[offset++] = '\'';
225			escaped_str[offset++] = '\\';
226			escaped_str[offset++] = '\'';
227			escaped_str[offset++] = '\'';
228			continue;
229		}
230
231		/* Otherwise no escaping needed inside single quotes */
232		if (s_quoted) {
233			escaped_str[offset++] = c;
234			continue;
235		}
236
237		/* No escaping needed inside a double quoted string either
238		 * unless we see a '$', '\', '`', or '"' (itself)
239		 */
240		if (d_quoted && c != '"' && c != '$' && c != '\\' && c != '`') {
241			escaped_str[offset++] = c;
242			continue;
243		}
244
245		/* If we reach here that means escaping is actually needed */
246		escaped_str[offset++] = '\\';
247		escaped_str[offset++] = c;
248	}
249
250	/* close the quotes */
251	if (s_quoted)
252		escaped_str[offset++] = '\'';
253	else if (d_quoted)
254		escaped_str[offset++] = '"';
255
256	escaped_str[offset] = 0;
257	return escaped_str;
258}
259
260/*
261 * return first found file name starting by the ``text'' or NULL if no
262 * such file can be found
263 * value of ``state'' is ignored
264 *
265 * it's the caller's responsibility to free the returned string
266 */
267char *
268fn_filename_completion_function(const char *text, int state)
269{
270	static DIR *dir = NULL;
271	static char *filename = NULL, *dirname = NULL, *dirpath = NULL;
272	static size_t filename_len = 0;
273	struct dirent *entry;
274	char *temp;
275	size_t len;
276
277	if (state == 0 || dir == NULL) {
278		temp = strrchr(text, '/');
279		if (temp) {
280			char *nptr;
281			temp++;
282			nptr = el_realloc(filename, (strlen(temp) + 1) *
283			    sizeof(*nptr));
284			if (nptr == NULL) {
285				el_free(filename);
286				filename = NULL;
287				return NULL;
288			}
289			filename = nptr;
290			(void)strcpy(filename, temp);
291			len = (size_t)(temp - text);	/* including last slash */
292
293			nptr = el_realloc(dirname, (len + 1) *
294			    sizeof(*nptr));
295			if (nptr == NULL) {
296				el_free(dirname);
297				dirname = NULL;
298				return NULL;
299			}
300			dirname = nptr;
301			(void)strncpy(dirname, text, len);
302			dirname[len] = '\0';
303		} else {
304			el_free(filename);
305			if (*text == 0)
306				filename = NULL;
307			else {
308				filename = strdup(text);
309				if (filename == NULL)
310					return NULL;
311			}
312			el_free(dirname);
313			dirname = NULL;
314		}
315
316		if (dir != NULL) {
317			(void)closedir(dir);
318			dir = NULL;
319		}
320
321		/* support for ``~user'' syntax */
322
323		el_free(dirpath);
324		dirpath = NULL;
325		if (dirname == NULL) {
326			if ((dirname = strdup("")) == NULL)
327				return NULL;
328			dirpath = strdup("./");
329		} else if (*dirname == '~')
330			dirpath = fn_tilde_expand(dirname);
331		else
332			dirpath = strdup(dirname);
333
334		if (dirpath == NULL)
335			return NULL;
336
337		dir = opendir(dirpath);
338		if (!dir)
339			return NULL;	/* cannot open the directory */
340
341		/* will be used in cycle */
342		filename_len = filename ? strlen(filename) : 0;
343	}
344
345	/* find the match */
346	while ((entry = readdir(dir)) != NULL) {
347		/* skip . and .. */
348		if (entry->d_name[0] == '.' && (!entry->d_name[1]
349		    || (entry->d_name[1] == '.' && !entry->d_name[2])))
350			continue;
351		if (filename_len == 0)
352			break;
353		/* otherwise, get first entry where first */
354		/* filename_len characters are equal	  */
355		if (entry->d_name[0] == filename[0]
356#if HAVE_STRUCT_DIRENT_D_NAMLEN
357		    && entry->d_namlen >= filename_len
358#else
359		    && strlen(entry->d_name) >= filename_len
360#endif
361		    && strncmp(entry->d_name, filename,
362			filename_len) == 0)
363			break;
364	}
365
366	if (entry) {		/* match found */
367
368#if HAVE_STRUCT_DIRENT_D_NAMLEN
369		len = entry->d_namlen;
370#else
371		len = strlen(entry->d_name);
372#endif
373
374		len = strlen(dirname) + len + 1;
375		temp = el_malloc(len * sizeof(*temp));
376		if (temp == NULL)
377			return NULL;
378		(void)snprintf(temp, len, "%s%s", dirname, entry->d_name);
379	} else {
380		(void)closedir(dir);
381		dir = NULL;
382		temp = NULL;
383	}
384
385	return temp;
386}
387
388
389static const char *
390append_char_function(const char *name)
391{
392	struct stat stbuf;
393	char *expname = *name == '~' ? fn_tilde_expand(name) : NULL;
394	const char *rs = " ";
395
396	if (stat(expname ? expname : name, &stbuf) == -1)
397		goto out;
398	if (S_ISDIR(stbuf.st_mode))
399		rs = "/";
400out:
401	if (expname)
402		el_free(expname);
403	return rs;
404}
405/*
406 * returns list of completions for text given
407 * non-static for readline.
408 */
409char ** completion_matches(const char *, char *(*)(const char *, int));
410char **
411completion_matches(const char *text, char *(*genfunc)(const char *, int))
412{
413	char **match_list = NULL, *retstr, *prevstr;
414	size_t match_list_len, max_equal, which, i;
415	size_t matches;
416
417	matches = 0;
418	match_list_len = 1;
419	while ((retstr = (*genfunc) (text, (int)matches)) != NULL) {
420		/* allow for list terminator here */
421		if (matches + 3 >= match_list_len) {
422			char **nmatch_list;
423			while (matches + 3 >= match_list_len)
424				match_list_len <<= 1;
425			nmatch_list = el_realloc(match_list,
426			    match_list_len * sizeof(*nmatch_list));
427			if (nmatch_list == NULL) {
428				el_free(match_list);
429				return NULL;
430			}
431			match_list = nmatch_list;
432
433		}
434		match_list[++matches] = retstr;
435	}
436
437	if (!match_list)
438		return NULL;	/* nothing found */
439
440	/* find least denominator and insert it to match_list[0] */
441	which = 2;
442	prevstr = match_list[1];
443	max_equal = strlen(prevstr);
444	for (; which <= matches; which++) {
445		for (i = 0; i < max_equal &&
446		    prevstr[i] == match_list[which][i]; i++)
447			continue;
448		max_equal = i;
449	}
450
451	retstr = el_malloc((max_equal + 1) * sizeof(*retstr));
452	if (retstr == NULL) {
453		el_free(match_list);
454		return NULL;
455	}
456	(void)strncpy(retstr, match_list[1], max_equal);
457	retstr[max_equal] = '\0';
458	match_list[0] = retstr;
459
460	/* add NULL as last pointer to the array */
461	match_list[matches + 1] = NULL;
462
463	return match_list;
464}
465
466/*
467 * Sort function for qsort(). Just wrapper around strcasecmp().
468 */
469static int
470_fn_qsort_string_compare(const void *i1, const void *i2)
471{
472	const char *s1 = ((const char * const *)i1)[0];
473	const char *s2 = ((const char * const *)i2)[0];
474
475	return strcasecmp(s1, s2);
476}
477
478/*
479 * Display list of strings in columnar format on readline's output stream.
480 * 'matches' is list of strings, 'num' is number of strings in 'matches',
481 * 'width' is maximum length of string in 'matches'.
482 *
483 * matches[0] is not one of the match strings, but it is counted in
484 * num, so the strings are matches[1] *through* matches[num-1].
485 */
486void
487fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width,
488    const char *(*app_func) (const char *))
489{
490	size_t line, lines, col, cols, thisguy;
491	int screenwidth = el->el_terminal.t_size.h;
492	if (app_func == NULL)
493		app_func = append_char_function;
494
495	/* Ignore matches[0]. Avoid 1-based array logic below. */
496	matches++;
497	num--;
498
499	/*
500	 * Find out how many entries can be put on one line; count
501	 * with one space between strings the same way it's printed.
502	 */
503	cols = (size_t)screenwidth / (width + 1);
504	if (cols == 0)
505		cols = 1;
506
507	/* how many lines of output, rounded up */
508	lines = (num + cols - 1) / cols;
509
510	/* Sort the items. */
511	qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
512
513	/*
514	 * On the ith line print elements i, i+lines, i+lines*2, etc.
515	 */
516	for (line = 0; line < lines; line++) {
517		for (col = 0; col < cols; col++) {
518			thisguy = line + col * lines;
519			if (thisguy >= num)
520				break;
521			(void)fprintf(el->el_outfile, "%s%s%s",
522			    col == 0 ? "" : " ", matches[thisguy],
523				append_char_function(matches[thisguy]));
524			(void)fprintf(el->el_outfile, "%-*s",
525				(int) (width - strlen(matches[thisguy])), "");
526		}
527		(void)fprintf(el->el_outfile, "\n");
528	}
529}
530
531/*
532 * Complete the word at or before point,
533 * 'what_to_do' says what to do with the completion.
534 * \t   means do standard completion.
535 * `?' means list the possible completions.
536 * `*' means insert all of the possible completions.
537 * `!' means to do standard completion, and list all possible completions if
538 * there is more than one.
539 *
540 * Note: '*' support is not implemented
541 *       '!' could never be invoked
542 */
543int
544fn_complete(EditLine *el,
545	char *(*complet_func)(const char *, int),
546	char **(*attempted_completion_function)(const char *, int, int),
547	const wchar_t *word_break, const wchar_t *special_prefixes,
548	const char *(*app_func)(const char *), size_t query_items,
549	int *completion_type, int *over, int *point, int *end)
550{
551	const LineInfoW *li;
552	wchar_t *temp;
553	char **matches;
554	const wchar_t *ctemp;
555	size_t len;
556	int what_to_do = '\t';
557	int retval = CC_NORM;
558
559	if (el->el_state.lastcmd == el->el_state.thiscmd)
560		what_to_do = '?';
561
562	/* readline's rl_complete() has to be told what we did... */
563	if (completion_type != NULL)
564		*completion_type = what_to_do;
565
566	if (!complet_func)
567		complet_func = fn_filename_completion_function;
568	if (!app_func)
569		app_func = append_char_function;
570
571	/* We now look backwards for the start of a filename/variable word */
572	li = el_wline(el);
573	ctemp = li->cursor;
574	while (ctemp > li->buffer
575	    && !wcschr(word_break, ctemp[-1])
576	    && (!special_prefixes || !wcschr(special_prefixes, ctemp[-1]) ) )
577		ctemp--;
578
579	len = (size_t)(li->cursor - ctemp);
580	temp = el_malloc((len + 1) * sizeof(*temp));
581	if (temp == NULL)
582		goto out;
583	(void)wcsncpy(temp, ctemp, len);
584	temp[len] = '\0';
585
586	/* these can be used by function called in completion_matches() */
587	/* or (*attempted_completion_function)() */
588	if (point != NULL)
589		*point = (int)(li->cursor - li->buffer);
590	if (end != NULL)
591		*end = (int)(li->lastchar - li->buffer);
592
593	if (attempted_completion_function) {
594		int cur_off = (int)(li->cursor - li->buffer);
595		matches = (*attempted_completion_function)(
596		    ct_encode_string(temp, &el->el_scratch),
597		    cur_off - (int)len, cur_off);
598	} else
599		matches = NULL;
600	if (!attempted_completion_function ||
601	    (over != NULL && !*over && !matches))
602		matches = completion_matches(
603		    ct_encode_string(temp, &el->el_scratch), complet_func);
604
605	if (over != NULL)
606		*over = 0;
607
608	if (matches) {
609		int i;
610		size_t matches_num, maxlen, match_len, match_display=1;
611		int single_match = matches[2] == NULL &&
612			(matches[1] == NULL || strcmp(matches[0], matches[1]) == 0);
613
614		retval = CC_REFRESH;
615
616		if (matches[0][0] != '\0') {
617			el_deletestr(el, (int) len);
618			if (single_match) {
619				/*
620				 * We found exact match. Add a space after
621				 * it, unless we do filename completion and the
622				 * object is a directory. Also do necessary escape quoting
623				 */
624				char *escaped_completion = escape_filename(el, matches[0]);
625				if (escaped_completion == NULL)
626					goto out;
627				el_winsertstr(el,
628					ct_decode_string(escaped_completion, &el->el_scratch));
629				el_winsertstr(el,
630						ct_decode_string((*app_func)(escaped_completion),
631							&el->el_scratch));
632				free(escaped_completion);
633			} else {
634				/*
635				 * Only replace the completed string with common part of
636				 * possible matches if there is possible completion.
637				 */
638				el_winsertstr(el,
639					ct_decode_string(matches[0], &el->el_scratch));
640			}
641		}
642
643
644		if (!single_match && (what_to_do == '!' || what_to_do == '?')) {
645			/*
646			 * More than one match and requested to list possible
647			 * matches.
648			 */
649
650			for(i = 1, maxlen = 0; matches[i]; i++) {
651				match_len = strlen(matches[i]);
652				if (match_len > maxlen)
653					maxlen = match_len;
654			}
655			/* matches[1] through matches[i-1] are available */
656			matches_num = (size_t)(i - 1);
657
658			/* newline to get on next line from command line */
659			(void)fprintf(el->el_outfile, "\n");
660
661			/*
662			 * If there are too many items, ask user for display
663			 * confirmation.
664			 */
665			if (matches_num > query_items) {
666				(void)fprintf(el->el_outfile,
667				    "Display all %zu possibilities? (y or n) ",
668				    matches_num);
669				(void)fflush(el->el_outfile);
670				if (getc(stdin) != 'y')
671					match_display = 0;
672				(void)fprintf(el->el_outfile, "\n");
673			}
674
675			if (match_display) {
676				/*
677				 * Interface of this function requires the
678				 * strings be matches[1..num-1] for compat.
679				 * We have matches_num strings not counting
680				 * the prefix in matches[0], so we need to
681				 * add 1 to matches_num for the call.
682				 */
683				fn_display_match_list(el, matches,
684				    matches_num+1, maxlen, app_func);
685			}
686			retval = CC_REDISPLAY;
687		} else if (matches[0][0]) {
688			/*
689			 * There was some common match, but the name was
690			 * not complete enough. Next tab will print possible
691			 * completions.
692			 */
693			el_beep(el);
694		} else {
695			/* lcd is not a valid object - further specification */
696			/* is needed */
697			el_beep(el);
698			retval = CC_NORM;
699		}
700
701		/* free elements of array and the array itself */
702		for (i = 0; matches[i]; i++)
703			el_free(matches[i]);
704		el_free(matches);
705		matches = NULL;
706	}
707
708out:
709	el_free(temp);
710	return retval;
711}
712
713/*
714 * el-compatible wrapper around rl_complete; needed for key binding
715 */
716/* ARGSUSED */
717unsigned char
718_el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
719{
720	return (unsigned char)fn_complete(el, NULL, NULL,
721	    break_chars, NULL, NULL, (size_t)100,
722	    NULL, NULL, NULL, NULL);
723}
724