filecomplete.c revision 1.45 1 /* $NetBSD: filecomplete.c,v 1.45 2017/04/21 05:38: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.45 2017/04/21 05:38: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
52 static 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 */
64 char *
65 fn_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 */
137 char *
138 fn_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
259 static const char *
260 append_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 = "/";
270 out:
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 */
279 char ** completion_matches(const char *, char *(*)(const char *, int));
280 char **
281 completion_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 */
339 static 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 */
356 void
357 fn_display_match_list(EditLine * el, char **matches, size_t num, size_t width,
358 const char *(*app_func) (const char *))
359 {
360 size_t line, lines, col, cols, thisguy;
361 int screenwidth = el->el_terminal.t_size.h;
362 if (app_func == NULL)
363 app_func = append_char_function;
364
365 /* Ignore matches[0]. Avoid 1-based array logic below. */
366 matches++;
367 num--;
368
369 /*
370 * Find out how many entries can be put on one line; count
371 * with one space between strings the same way it's printed.
372 */
373 cols = (size_t)screenwidth / (width + 1);
374 if (cols == 0)
375 cols = 1;
376
377 /* how many lines of output, rounded up */
378 lines = (num + cols - 1) / cols;
379
380 /* Sort the items. */
381 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare);
382
383 /*
384 * On the ith line print elements i, i+lines, i+lines*2, etc.
385 */
386 for (line = 0; line < lines; line++) {
387 for (col = 0; col < cols; col++) {
388 thisguy = line + col * lines;
389 if (thisguy >= num)
390 break;
391 (void)fprintf(el->el_outfile, "%s%s%s",
392 col == 0 ? "" : " ", matches[thisguy],
393 append_char_function(matches[thisguy]));
394 (void)fprintf(el->el_outfile, "%-*s",
395 (int) (width - strlen(matches[thisguy])), "");
396 }
397 (void)fprintf(el->el_outfile, "\n");
398 }
399 }
400
401 /*
402 * Complete the word at or before point,
403 * 'what_to_do' says what to do with the completion.
404 * \t means do standard completion.
405 * `?' means list the possible completions.
406 * `*' means insert all of the possible completions.
407 * `!' means to do standard completion, and list all possible completions if
408 * there is more than one.
409 *
410 * Note: '*' support is not implemented
411 * '!' could never be invoked
412 */
413 int
414 fn_complete(EditLine *el,
415 char *(*complet_func)(const char *, int),
416 char **(*attempted_completion_function)(const char *, int, int),
417 const wchar_t *word_break, const wchar_t *special_prefixes,
418 const char *(*app_func)(const char *), size_t query_items,
419 int *completion_type, int *over, int *point, int *end)
420 {
421 const LineInfoW *li;
422 wchar_t *temp;
423 char **matches;
424 const wchar_t *ctemp;
425 size_t len;
426 int what_to_do = '\t';
427 int retval = CC_NORM;
428
429 if (el->el_state.lastcmd == el->el_state.thiscmd)
430 what_to_do = '?';
431
432 /* readline's rl_complete() has to be told what we did... */
433 if (completion_type != NULL)
434 *completion_type = what_to_do;
435
436 if (!complet_func)
437 complet_func = fn_filename_completion_function;
438 if (!app_func)
439 app_func = append_char_function;
440
441 /* We now look backwards for the start of a filename/variable word */
442 li = el_wline(el);
443 ctemp = li->cursor;
444 while (ctemp > li->buffer
445 && !wcschr(word_break, ctemp[-1])
446 && (!special_prefixes || !wcschr(special_prefixes, ctemp[-1]) ) )
447 ctemp--;
448
449 len = (size_t)(li->cursor - ctemp);
450 temp = el_malloc((len + 1) * sizeof(*temp));
451 (void)wcsncpy(temp, ctemp, len);
452 temp[len] = '\0';
453
454 /* these can be used by function called in completion_matches() */
455 /* or (*attempted_completion_function)() */
456 if (point != NULL)
457 *point = (int)(li->cursor - li->buffer);
458 if (end != NULL)
459 *end = (int)(li->lastchar - li->buffer);
460
461 if (attempted_completion_function) {
462 int cur_off = (int)(li->cursor - li->buffer);
463 matches = (*attempted_completion_function)(
464 ct_encode_string(temp, &el->el_scratch),
465 cur_off - (int)len, cur_off);
466 } else
467 matches = NULL;
468 if (!attempted_completion_function ||
469 (over != NULL && !*over && !matches))
470 matches = completion_matches(
471 ct_encode_string(temp, &el->el_scratch), complet_func);
472
473 if (over != NULL)
474 *over = 0;
475
476 if (matches) {
477 int i;
478 size_t matches_num, maxlen, match_len, match_display=1;
479
480 retval = CC_REFRESH;
481 /*
482 * Only replace the completed string with common part of
483 * possible matches if there is possible completion.
484 */
485 if (matches[0][0] != '\0') {
486 el_deletestr(el, (int) len);
487 el_winsertstr(el,
488 ct_decode_string(matches[0], &el->el_scratch));
489 }
490
491
492 if (matches[2] == NULL &&
493 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0)) {
494 /*
495 * We found exact match. Add a space after
496 * it, unless we do filename completion and the
497 * object is a directory.
498 */
499 el_winsertstr(el,
500 ct_decode_string((*app_func)(matches[0]),
501 &el->el_scratch));
502 } else if (what_to_do == '!' || what_to_do == '?') {
503 /*
504 * More than one match and requested to list possible
505 * matches.
506 */
507
508 for(i = 1, maxlen = 0; matches[i]; i++) {
509 match_len = strlen(matches[i]);
510 if (match_len > maxlen)
511 maxlen = match_len;
512 }
513 /* matches[1] through matches[i-1] are available */
514 matches_num = (size_t)(i - 1);
515
516 /* newline to get on next line from command line */
517 (void)fprintf(el->el_outfile, "\n");
518
519 /*
520 * If there are too many items, ask user for display
521 * confirmation.
522 */
523 if (matches_num > query_items) {
524 (void)fprintf(el->el_outfile,
525 "Display all %zu possibilities? (y or n) ",
526 matches_num);
527 (void)fflush(el->el_outfile);
528 if (getc(stdin) != 'y')
529 match_display = 0;
530 (void)fprintf(el->el_outfile, "\n");
531 }
532
533 if (match_display) {
534 /*
535 * Interface of this function requires the
536 * strings be matches[1..num-1] for compat.
537 * We have matches_num strings not counting
538 * the prefix in matches[0], so we need to
539 * add 1 to matches_num for the call.
540 */
541 fn_display_match_list(el, matches,
542 matches_num+1, maxlen, app_func);
543 }
544 retval = CC_REDISPLAY;
545 } else if (matches[0][0]) {
546 /*
547 * There was some common match, but the name was
548 * not complete enough. Next tab will print possible
549 * completions.
550 */
551 el_beep(el);
552 } else {
553 /* lcd is not a valid object - further specification */
554 /* is needed */
555 el_beep(el);
556 retval = CC_NORM;
557 }
558
559 /* free elements of array and the array itself */
560 for (i = 0; matches[i]; i++)
561 el_free(matches[i]);
562 el_free(matches);
563 matches = NULL;
564 }
565 el_free(temp);
566 return retval;
567 }
568
569 /*
570 * el-compatible wrapper around rl_complete; needed for key binding
571 */
572 /* ARGSUSED */
573 unsigned char
574 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__)))
575 {
576 return (unsigned char)fn_complete(el, NULL, NULL,
577 break_chars, NULL, NULL, (size_t)100,
578 NULL, NULL, NULL, NULL);
579 }
580