1 /* $NetBSD: filecomplete.c,v 1.51 2018/05/04 20:38:26 christos 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.51 2018/05/04 20:38:26 christos 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 static int 130 needs_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 162 static char * 163 escape_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 */ 267 char * 268 fn_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 389 static const char * 390 append_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 = "/"; 400 out: 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 */ 409 char ** completion_matches(const char *, char *(*)(const char *, int)); 410 char ** 411 completion_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 */ 469 static 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 */ 486 void 487 fn_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 static wchar_t * 532 find_word_to_complete(const wchar_t * cursor, const wchar_t * buffer, 533 const wchar_t * word_break, const wchar_t * special_prefixes, size_t * length) 534 { 535 /* We now look backwards for the start of a filename/variable word */ 536 const wchar_t *ctemp = cursor; 537 int cursor_at_quote; 538 size_t len; 539 wchar_t *temp; 540 541 /* if the cursor is placed at a slash or a quote, we need to find the 542 * word before it 543 */ 544 if (ctemp > buffer) { 545 switch (ctemp[-1]) { 546 case '\\': 547 case '\'': 548 case '"': 549 cursor_at_quote = 1; 550 ctemp--; 551 break; 552 default: 553 cursor_at_quote = 0; 554 } 555 } else 556 cursor_at_quote = 0; 557 558 while (ctemp > buffer 559 && !wcschr(word_break, ctemp[-1]) 560 && (!special_prefixes || !wcschr(special_prefixes, ctemp[-1]))) 561 ctemp--; 562 563 len = (size_t) (cursor - ctemp - cursor_at_quote); 564 temp = el_malloc((len + 1) * sizeof(*temp)); 565 if (temp == NULL) 566 return NULL; 567 (void) wcsncpy(temp, ctemp, len); 568 temp[len] = '\0'; 569 if (cursor_at_quote) 570 len++; 571 *length = len; 572 return temp; 573 } 574 575 /* 576 * Complete the word at or before point, 577 * 'what_to_do' says what to do with the completion. 578 * \t means do standard completion. 579 * `?' means list the possible completions. 580 * `*' means insert all of the possible completions. 581 * `!' means to do standard completion, and list all possible completions if 582 * there is more than one. 583 * 584 * Note: '*' support is not implemented 585 * '!' could never be invoked 586 */ 587 int 588 fn_complete(EditLine *el, 589 char *(*complet_func)(const char *, int), 590 char **(*attempted_completion_function)(const char *, int, int), 591 const wchar_t *word_break, const wchar_t *special_prefixes, 592 const char *(*app_func)(const char *), size_t query_items, 593 int *completion_type, int *over, int *point, int *end) 594 { 595 const LineInfoW *li; 596 wchar_t *temp; 597 char **matches; 598 size_t len; 599 int what_to_do = '\t'; 600 int retval = CC_NORM; 601 602 if (el->el_state.lastcmd == el->el_state.thiscmd) 603 what_to_do = '?'; 604 605 /* readline's rl_complete() has to be told what we did... */ 606 if (completion_type != NULL) 607 *completion_type = what_to_do; 608 609 if (!complet_func) 610 complet_func = fn_filename_completion_function; 611 if (!app_func) 612 app_func = append_char_function; 613 614 li = el_wline(el); 615 temp = find_word_to_complete(li->cursor, 616 li->buffer, word_break, special_prefixes, &len); 617 if (temp == NULL) 618 goto out; 619 620 /* these can be used by function called in completion_matches() */ 621 /* or (*attempted_completion_function)() */ 622 if (point != NULL) 623 *point = (int)(li->cursor - li->buffer); 624 if (end != NULL) 625 *end = (int)(li->lastchar - li->buffer); 626 627 if (attempted_completion_function) { 628 int cur_off = (int)(li->cursor - li->buffer); 629 matches = (*attempted_completion_function)( 630 ct_encode_string(temp, &el->el_scratch), 631 cur_off - (int)len, cur_off); 632 } else 633 matches = NULL; 634 if (!attempted_completion_function || 635 (over != NULL && !*over && !matches)) 636 matches = completion_matches( 637 ct_encode_string(temp, &el->el_scratch), complet_func); 638 639 if (over != NULL) 640 *over = 0; 641 642 if (matches) { 643 int i; 644 size_t matches_num, maxlen, match_len, match_display=1; 645 int single_match = matches[2] == NULL && 646 (matches[1] == NULL || strcmp(matches[0], matches[1]) == 0); 647 648 retval = CC_REFRESH; 649 650 if (matches[0][0] != '\0') { 651 el_deletestr(el, (int) len); 652 if (single_match) { 653 /* 654 * We found exact match. Add a space after 655 * it, unless we do filename completion and the 656 * object is a directory. Also do necessary escape quoting 657 */ 658 char *escaped_completion = escape_filename(el, matches[0]); 659 if (escaped_completion == NULL) 660 goto out; 661 el_winsertstr(el, 662 ct_decode_string(escaped_completion, &el->el_scratch)); 663 el_winsertstr(el, 664 ct_decode_string((*app_func)(escaped_completion), 665 &el->el_scratch)); 666 free(escaped_completion); 667 } else { 668 /* 669 * Only replace the completed string with common part of 670 * possible matches if there is possible completion. 671 */ 672 el_winsertstr(el, 673 ct_decode_string(matches[0], &el->el_scratch)); 674 } 675 } 676 677 678 if (!single_match && (what_to_do == '!' || what_to_do == '?')) { 679 /* 680 * More than one match and requested to list possible 681 * matches. 682 */ 683 684 for(i = 1, maxlen = 0; matches[i]; i++) { 685 match_len = strlen(matches[i]); 686 if (match_len > maxlen) 687 maxlen = match_len; 688 } 689 /* matches[1] through matches[i-1] are available */ 690 matches_num = (size_t)(i - 1); 691 692 /* newline to get on next line from command line */ 693 (void)fprintf(el->el_outfile, "\n"); 694 695 /* 696 * If there are too many items, ask user for display 697 * confirmation. 698 */ 699 if (matches_num > query_items) { 700 (void)fprintf(el->el_outfile, 701 "Display all %zu possibilities? (y or n) ", 702 matches_num); 703 (void)fflush(el->el_outfile); 704 if (getc(stdin) != 'y') 705 match_display = 0; 706 (void)fprintf(el->el_outfile, "\n"); 707 } 708 709 if (match_display) { 710 /* 711 * Interface of this function requires the 712 * strings be matches[1..num-1] for compat. 713 * We have matches_num strings not counting 714 * the prefix in matches[0], so we need to 715 * add 1 to matches_num for the call. 716 */ 717 fn_display_match_list(el, matches, 718 matches_num+1, maxlen, app_func); 719 } 720 retval = CC_REDISPLAY; 721 } else if (matches[0][0]) { 722 /* 723 * There was some common match, but the name was 724 * not complete enough. Next tab will print possible 725 * completions. 726 */ 727 el_beep(el); 728 } else { 729 /* lcd is not a valid object - further specification */ 730 /* is needed */ 731 el_beep(el); 732 retval = CC_NORM; 733 } 734 735 /* free elements of array and the array itself */ 736 for (i = 0; matches[i]; i++) 737 el_free(matches[i]); 738 el_free(matches); 739 matches = NULL; 740 } 741 742 out: 743 el_free(temp); 744 return retval; 745 } 746 747 /* 748 * el-compatible wrapper around rl_complete; needed for key binding 749 */ 750 /* ARGSUSED */ 751 unsigned char 752 _el_fn_complete(EditLine *el, int ch __attribute__((__unused__))) 753 { 754 return (unsigned char)fn_complete(el, NULL, NULL, 755 break_chars, NULL, NULL, (size_t)100, 756 NULL, NULL, NULL, NULL); 757 } 758