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