1 /*- 2 * Copyright (c) 1991, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Kenneth Almquist. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. Neither the name of the University nor the names of its contributors 17 * may be used to endorse or promote products derived from this software 18 * without specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 * SUCH DAMAGE. 31 */ 32 33 #ifndef lint 34 #if 0 35 static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95"; 36 #endif 37 #endif /* not lint */ 38 #include <sys/cdefs.h> 39 __FBSDID("$FreeBSD$"); 40 41 #include <sys/types.h> 42 #include <sys/stat.h> 43 #include <unistd.h> 44 #include <fcntl.h> 45 #include <errno.h> 46 #include <paths.h> 47 #include <stdbool.h> 48 #include <stdlib.h> 49 50 /* 51 * When commands are first encountered, they are entered in a hash table. 52 * This ensures that a full path search will not have to be done for them 53 * on each invocation. 54 * 55 * We should investigate converting to a linear search, even though that 56 * would make the command name "hash" a misnomer. 57 */ 58 59 #include "shell.h" 60 #include "main.h" 61 #include "nodes.h" 62 #include "parser.h" 63 #include "redir.h" 64 #include "eval.h" 65 #include "exec.h" 66 #include "builtins.h" 67 #include "var.h" 68 #include "options.h" 69 #include "input.h" 70 #include "output.h" 71 #include "syntax.h" 72 #include "memalloc.h" 73 #include "error.h" 74 #include "mystring.h" 75 #include "show.h" 76 #include "jobs.h" 77 #include "alias.h" 78 79 80 #define CMDTABLESIZE 31 /* should be prime */ 81 82 83 84 struct tblentry { 85 struct tblentry *next; /* next entry in hash chain */ 86 union param param; /* definition of builtin function */ 87 int special; /* flag for special builtin commands */ 88 signed char cmdtype; /* index identifying command */ 89 char cmdname[]; /* name of command */ 90 }; 91 92 93 static struct tblentry *cmdtable[CMDTABLESIZE]; 94 static int cmdtable_cd = 0; /* cmdtable contains cd-dependent entries */ 95 96 97 static void tryexec(char *, char **, char **); 98 static void printentry(struct tblentry *, int); 99 static struct tblentry *cmdlookup(const char *, int); 100 static void delete_cmd_entry(void); 101 static void addcmdentry(const char *, struct cmdentry *); 102 103 104 105 /* 106 * Exec a program. Never returns. If you change this routine, you may 107 * have to change the find_command routine as well. 108 * 109 * The argv array may be changed and element argv[-1] should be writable. 110 */ 111 112 void 113 shellexec(char **argv, char **envp, const char *path, int idx) 114 { 115 char *cmdname; 116 const char *opt; 117 int e; 118 119 if (strchr(argv[0], '/') != NULL) { 120 tryexec(argv[0], argv, envp); 121 e = errno; 122 } else { 123 e = ENOENT; 124 while ((cmdname = padvance(&path, &opt, argv[0])) != NULL) { 125 if (--idx < 0 && opt == NULL) { 126 tryexec(cmdname, argv, envp); 127 if (errno != ENOENT && errno != ENOTDIR) 128 e = errno; 129 if (e == ENOEXEC) 130 break; 131 } 132 stunalloc(cmdname); 133 } 134 } 135 136 /* Map to POSIX errors */ 137 if (e == ENOENT || e == ENOTDIR) 138 errorwithstatus(127, "%s: not found", argv[0]); 139 else 140 errorwithstatus(126, "%s: %s", argv[0], strerror(e)); 141 } 142 143 144 static bool 145 isbinary(const char *data, size_t len) 146 { 147 const char *nul, *p; 148 bool hasletter; 149 150 nul = memchr(data, '\0', len); 151 if (nul == NULL) 152 return false; 153 /* 154 * POSIX says we shall allow execution if the initial part intended 155 * to be parsed by the shell consists of characters and does not 156 * contain the NUL character. This allows concatenating a shell 157 * script (ending with exec or exit) and a binary payload. 158 * 159 * In order to reject common binary files such as PNG images, check 160 * that there is a lowercase letter or expansion before the last 161 * newline before the NUL character, in addition to the check for 162 * the newline character suggested by POSIX. 163 */ 164 hasletter = false; 165 for (p = data; *p != '\0'; p++) { 166 if ((*p >= 'a' && *p <= 'z') || *p == '$' || *p == '`') 167 hasletter = true; 168 if (hasletter && *p == '\n') 169 return false; 170 } 171 return true; 172 } 173 174 175 static void 176 tryexec(char *cmd, char **argv, char **envp) 177 { 178 int e, in; 179 ssize_t n; 180 char buf[256]; 181 182 execve(cmd, argv, envp); 183 e = errno; 184 if (e == ENOEXEC) { 185 INTOFF; 186 in = open(cmd, O_RDONLY | O_NONBLOCK); 187 if (in != -1) { 188 n = pread(in, buf, sizeof buf, 0); 189 close(in); 190 if (n > 0 && isbinary(buf, n)) { 191 errno = ENOEXEC; 192 return; 193 } 194 } 195 *argv = cmd; 196 *--argv = __DECONST(char *, _PATH_BSHELL); 197 execve(_PATH_BSHELL, argv, envp); 198 } 199 errno = e; 200 } 201 202 /* 203 * Do a path search. The variable path (passed by reference) should be 204 * set to the start of the path before the first call; padvance will update 205 * this value as it proceeds. Successive calls to padvance will return 206 * the possible path expansions in sequence. If popt is not NULL, options 207 * are processed: if an option (indicated by a percent sign) appears in 208 * the path entry then *popt will be set to point to it; else *popt will be 209 * set to NULL. If popt is NULL, percent signs are not special. 210 */ 211 212 char * 213 padvance(const char **path, const char **popt, const char *name) 214 { 215 const char *p, *start; 216 char *q; 217 size_t len, namelen; 218 219 if (*path == NULL) 220 return NULL; 221 start = *path; 222 if (popt != NULL) 223 for (p = start; *p && *p != ':' && *p != '%'; p++) 224 ; /* nothing */ 225 else 226 for (p = start; *p && *p != ':'; p++) 227 ; /* nothing */ 228 namelen = strlen(name); 229 len = p - start + namelen + 2; /* "2" is for '/' and '\0' */ 230 STARTSTACKSTR(q); 231 CHECKSTRSPACE(len, q); 232 if (p != start) { 233 memcpy(q, start, p - start); 234 q += p - start; 235 *q++ = '/'; 236 } 237 memcpy(q, name, namelen + 1); 238 if (popt != NULL) { 239 if (*p == '%') { 240 *popt = ++p; 241 while (*p && *p != ':') p++; 242 } else 243 *popt = NULL; 244 } 245 if (*p == ':') 246 *path = p + 1; 247 else 248 *path = NULL; 249 return stalloc(len); 250 } 251 252 253 254 /*** Command hashing code ***/ 255 256 257 int 258 hashcmd(int argc __unused, char **argv __unused) 259 { 260 struct tblentry **pp; 261 struct tblentry *cmdp; 262 int c; 263 int verbose; 264 struct cmdentry entry; 265 char *name; 266 int errors; 267 268 errors = 0; 269 verbose = 0; 270 while ((c = nextopt("rv")) != '\0') { 271 if (c == 'r') { 272 clearcmdentry(); 273 } else if (c == 'v') { 274 verbose++; 275 } 276 } 277 if (*argptr == NULL) { 278 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) { 279 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) { 280 if (cmdp->cmdtype == CMDNORMAL) 281 printentry(cmdp, verbose); 282 } 283 } 284 return 0; 285 } 286 while ((name = *argptr) != NULL) { 287 if ((cmdp = cmdlookup(name, 0)) != NULL 288 && cmdp->cmdtype == CMDNORMAL) 289 delete_cmd_entry(); 290 find_command(name, &entry, DO_ERR, pathval()); 291 if (entry.cmdtype == CMDUNKNOWN) 292 errors = 1; 293 else if (verbose) { 294 cmdp = cmdlookup(name, 0); 295 if (cmdp != NULL) 296 printentry(cmdp, verbose); 297 else { 298 outfmt(out2, "%s: not found\n", name); 299 errors = 1; 300 } 301 flushall(); 302 } 303 argptr++; 304 } 305 return errors; 306 } 307 308 309 static void 310 printentry(struct tblentry *cmdp, int verbose) 311 { 312 int idx; 313 const char *path, *opt; 314 char *name; 315 316 if (cmdp->cmdtype == CMDNORMAL) { 317 idx = cmdp->param.index; 318 path = pathval(); 319 do { 320 name = padvance(&path, &opt, cmdp->cmdname); 321 stunalloc(name); 322 } while (--idx >= 0); 323 out1str(name); 324 } else if (cmdp->cmdtype == CMDBUILTIN) { 325 out1fmt("builtin %s", cmdp->cmdname); 326 } else if (cmdp->cmdtype == CMDFUNCTION) { 327 out1fmt("function %s", cmdp->cmdname); 328 if (verbose) { 329 INTOFF; 330 name = commandtext(getfuncnode(cmdp->param.func)); 331 out1c(' '); 332 out1str(name); 333 ckfree(name); 334 INTON; 335 } 336 #ifdef DEBUG 337 } else { 338 error("internal error: cmdtype %d", cmdp->cmdtype); 339 #endif 340 } 341 out1c('\n'); 342 } 343 344 345 346 /* 347 * Resolve a command name. If you change this routine, you may have to 348 * change the shellexec routine as well. 349 */ 350 351 void 352 find_command(const char *name, struct cmdentry *entry, int act, 353 const char *path) 354 { 355 struct tblentry *cmdp, loc_cmd; 356 int idx; 357 const char *opt; 358 char *fullname; 359 struct stat statb; 360 int e; 361 int i; 362 int spec; 363 int cd; 364 365 /* If name contains a slash, don't use the hash table */ 366 if (strchr(name, '/') != NULL) { 367 entry->cmdtype = CMDNORMAL; 368 entry->u.index = 0; 369 entry->special = 0; 370 return; 371 } 372 373 cd = 0; 374 375 /* If name is in the table, we're done */ 376 if ((cmdp = cmdlookup(name, 0)) != NULL) { 377 if (cmdp->cmdtype == CMDFUNCTION && act & DO_NOFUNC) 378 cmdp = NULL; 379 else 380 goto success; 381 } 382 383 /* Check for builtin next */ 384 if ((i = find_builtin(name, &spec)) >= 0) { 385 INTOFF; 386 cmdp = cmdlookup(name, 1); 387 if (cmdp->cmdtype == CMDFUNCTION) 388 cmdp = &loc_cmd; 389 cmdp->cmdtype = CMDBUILTIN; 390 cmdp->param.index = i; 391 cmdp->special = spec; 392 INTON; 393 goto success; 394 } 395 396 /* We have to search path. */ 397 398 e = ENOENT; 399 idx = -1; 400 for (;(fullname = padvance(&path, &opt, name)) != NULL; 401 stunalloc(fullname)) { 402 idx++; 403 if (opt) { 404 if (strncmp(opt, "func", 4) == 0) { 405 /* handled below */ 406 } else { 407 continue; /* ignore unimplemented options */ 408 } 409 } 410 if (fullname[0] != '/') 411 cd = 1; 412 if (stat(fullname, &statb) < 0) { 413 if (errno != ENOENT && errno != ENOTDIR) 414 e = errno; 415 continue; 416 } 417 e = EACCES; /* if we fail, this will be the error */ 418 if (!S_ISREG(statb.st_mode)) 419 continue; 420 if (opt) { /* this is a %func directory */ 421 readcmdfile(fullname, -1 /* verify */); 422 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION) 423 error("%s not defined in %s", name, fullname); 424 stunalloc(fullname); 425 goto success; 426 } 427 #ifdef notdef 428 if (statb.st_uid == geteuid()) { 429 if ((statb.st_mode & 0100) == 0) 430 goto loop; 431 } else if (statb.st_gid == getegid()) { 432 if ((statb.st_mode & 010) == 0) 433 goto loop; 434 } else { 435 if ((statb.st_mode & 01) == 0) 436 goto loop; 437 } 438 #endif 439 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname)); 440 INTOFF; 441 stunalloc(fullname); 442 cmdp = cmdlookup(name, 1); 443 if (cmdp->cmdtype == CMDFUNCTION) 444 cmdp = &loc_cmd; 445 cmdp->cmdtype = CMDNORMAL; 446 cmdp->param.index = idx; 447 cmdp->special = 0; 448 INTON; 449 goto success; 450 } 451 452 if (act & DO_ERR) { 453 if (e == ENOENT || e == ENOTDIR) 454 outfmt(out2, "%s: not found\n", name); 455 else 456 outfmt(out2, "%s: %s\n", name, strerror(e)); 457 } 458 entry->cmdtype = CMDUNKNOWN; 459 entry->u.index = 0; 460 entry->special = 0; 461 return; 462 463 success: 464 if (cd) 465 cmdtable_cd = 1; 466 entry->cmdtype = cmdp->cmdtype; 467 entry->u = cmdp->param; 468 entry->special = cmdp->special; 469 } 470 471 472 473 /* 474 * Search the table of builtin commands. 475 */ 476 477 int 478 find_builtin(const char *name, int *special) 479 { 480 const unsigned char *bp; 481 size_t len; 482 483 len = strlen(name); 484 for (bp = builtincmd ; *bp ; bp += 2 + bp[0]) { 485 if (bp[0] == len && memcmp(bp + 2, name, len) == 0) { 486 *special = (bp[1] & BUILTIN_SPECIAL) != 0; 487 return bp[1] & ~BUILTIN_SPECIAL; 488 } 489 } 490 return -1; 491 } 492 493 494 495 /* 496 * Called when a cd is done. If any entry in cmdtable depends on the current 497 * directory, simply clear cmdtable completely. 498 */ 499 500 void 501 hashcd(void) 502 { 503 if (cmdtable_cd) 504 clearcmdentry(); 505 } 506 507 508 509 /* 510 * Called before PATH is changed. The argument is the new value of PATH; 511 * pathval() still returns the old value at this point. Called with 512 * interrupts off. 513 */ 514 515 void 516 changepath(const char *newval __unused) 517 { 518 clearcmdentry(); 519 } 520 521 522 /* 523 * Clear out cached utility locations. 524 */ 525 526 void 527 clearcmdentry(void) 528 { 529 struct tblentry **tblp; 530 struct tblentry **pp; 531 struct tblentry *cmdp; 532 533 INTOFF; 534 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) { 535 pp = tblp; 536 while ((cmdp = *pp) != NULL) { 537 if (cmdp->cmdtype == CMDNORMAL) { 538 *pp = cmdp->next; 539 ckfree(cmdp); 540 } else { 541 pp = &cmdp->next; 542 } 543 } 544 } 545 cmdtable_cd = 0; 546 INTON; 547 } 548 549 550 /* 551 * Locate a command in the command hash table. If "add" is nonzero, 552 * add the command to the table if it is not already present. The 553 * variable "lastcmdentry" is set to point to the address of the link 554 * pointing to the entry, so that delete_cmd_entry can delete the 555 * entry. 556 */ 557 558 static struct tblentry **lastcmdentry; 559 560 561 static struct tblentry * 562 cmdlookup(const char *name, int add) 563 { 564 unsigned int hashval; 565 const char *p; 566 struct tblentry *cmdp; 567 struct tblentry **pp; 568 size_t len; 569 570 p = name; 571 hashval = (unsigned char)*p << 4; 572 while (*p) 573 hashval += *p++; 574 pp = &cmdtable[hashval % CMDTABLESIZE]; 575 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) { 576 if (equal(cmdp->cmdname, name)) 577 break; 578 pp = &cmdp->next; 579 } 580 if (add && cmdp == NULL) { 581 INTOFF; 582 len = strlen(name); 583 cmdp = *pp = ckmalloc(sizeof (struct tblentry) + len + 1); 584 cmdp->next = NULL; 585 cmdp->cmdtype = CMDUNKNOWN; 586 memcpy(cmdp->cmdname, name, len + 1); 587 INTON; 588 } 589 lastcmdentry = pp; 590 return cmdp; 591 } 592 593 /* 594 * Delete the command entry returned on the last lookup. 595 */ 596 597 static void 598 delete_cmd_entry(void) 599 { 600 struct tblentry *cmdp; 601 602 INTOFF; 603 cmdp = *lastcmdentry; 604 *lastcmdentry = cmdp->next; 605 ckfree(cmdp); 606 INTON; 607 } 608 609 610 611 /* 612 * Add a new command entry, replacing any existing command entry for 613 * the same name. 614 */ 615 616 static void 617 addcmdentry(const char *name, struct cmdentry *entry) 618 { 619 struct tblentry *cmdp; 620 621 INTOFF; 622 cmdp = cmdlookup(name, 1); 623 if (cmdp->cmdtype == CMDFUNCTION) { 624 unreffunc(cmdp->param.func); 625 } 626 cmdp->cmdtype = entry->cmdtype; 627 cmdp->param = entry->u; 628 cmdp->special = entry->special; 629 INTON; 630 } 631 632 633 /* 634 * Define a shell function. 635 */ 636 637 void 638 defun(const char *name, union node *func) 639 { 640 struct cmdentry entry; 641 642 INTOFF; 643 entry.cmdtype = CMDFUNCTION; 644 entry.u.func = copyfunc(func); 645 entry.special = 0; 646 addcmdentry(name, &entry); 647 INTON; 648 } 649 650 651 /* 652 * Delete a function if it exists. 653 * Called with interrupts off. 654 */ 655 656 int 657 unsetfunc(const char *name) 658 { 659 struct tblentry *cmdp; 660 661 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) { 662 unreffunc(cmdp->param.func); 663 delete_cmd_entry(); 664 return (0); 665 } 666 return (0); 667 } 668 669 670 /* 671 * Check if a function by a certain name exists. 672 */ 673 int 674 isfunc(const char *name) 675 { 676 struct tblentry *cmdp; 677 cmdp = cmdlookup(name, 0); 678 return (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION); 679 } 680 681 682 static void 683 print_absolute_path(const char *name) 684 { 685 const char *pwd; 686 687 if (*name != '/' && (pwd = lookupvar("PWD")) != NULL && *pwd != '\0') { 688 out1str(pwd); 689 if (strcmp(pwd, "/") != 0) 690 outcslow('/', out1); 691 } 692 out1str(name); 693 outcslow('\n', out1); 694 } 695 696 697 /* 698 * Shared code for the following builtin commands: 699 * type, command -v, command -V 700 */ 701 702 int 703 typecmd_impl(int argc, char **argv, int cmd, const char *path) 704 { 705 struct cmdentry entry; 706 struct tblentry *cmdp; 707 const char *const *pp; 708 struct alias *ap; 709 int i; 710 int error1 = 0; 711 712 if (path != pathval()) 713 clearcmdentry(); 714 715 for (i = 1; i < argc; i++) { 716 /* First look at the keywords */ 717 for (pp = parsekwd; *pp; pp++) 718 if (**pp == *argv[i] && equal(*pp, argv[i])) 719 break; 720 721 if (*pp) { 722 if (cmd == TYPECMD_SMALLV) 723 out1fmt("%s\n", argv[i]); 724 else 725 out1fmt("%s is a shell keyword\n", argv[i]); 726 continue; 727 } 728 729 /* Then look at the aliases */ 730 if ((ap = lookupalias(argv[i], 1)) != NULL) { 731 if (cmd == TYPECMD_SMALLV) { 732 out1fmt("alias %s=", argv[i]); 733 out1qstr(ap->val); 734 outcslow('\n', out1); 735 } else 736 out1fmt("%s is an alias for %s\n", argv[i], 737 ap->val); 738 continue; 739 } 740 741 /* Then check if it is a tracked alias */ 742 if ((cmdp = cmdlookup(argv[i], 0)) != NULL) { 743 entry.cmdtype = cmdp->cmdtype; 744 entry.u = cmdp->param; 745 entry.special = cmdp->special; 746 } 747 else { 748 /* Finally use brute force */ 749 find_command(argv[i], &entry, 0, path); 750 } 751 752 switch (entry.cmdtype) { 753 case CMDNORMAL: { 754 if (strchr(argv[i], '/') == NULL) { 755 const char *path2 = path; 756 const char *opt2; 757 char *name; 758 int j = entry.u.index; 759 do { 760 name = padvance(&path2, &opt2, argv[i]); 761 stunalloc(name); 762 } while (--j >= 0); 763 if (cmd != TYPECMD_SMALLV) 764 out1fmt("%s is%s ", argv[i], 765 (cmdp && cmd == TYPECMD_TYPE) ? 766 " a tracked alias for" : ""); 767 print_absolute_path(name); 768 } else { 769 if (eaccess(argv[i], X_OK) == 0) { 770 if (cmd != TYPECMD_SMALLV) 771 out1fmt("%s is ", argv[i]); 772 print_absolute_path(argv[i]); 773 } else { 774 if (cmd != TYPECMD_SMALLV) 775 outfmt(out2, "%s: %s\n", 776 argv[i], strerror(errno)); 777 error1 |= 127; 778 } 779 } 780 break; 781 } 782 case CMDFUNCTION: 783 if (cmd == TYPECMD_SMALLV) 784 out1fmt("%s\n", argv[i]); 785 else 786 out1fmt("%s is a shell function\n", argv[i]); 787 break; 788 789 case CMDBUILTIN: 790 if (cmd == TYPECMD_SMALLV) 791 out1fmt("%s\n", argv[i]); 792 else if (entry.special) 793 out1fmt("%s is a special shell builtin\n", 794 argv[i]); 795 else 796 out1fmt("%s is a shell builtin\n", argv[i]); 797 break; 798 799 default: 800 if (cmd != TYPECMD_SMALLV) 801 outfmt(out2, "%s: not found\n", argv[i]); 802 error1 |= 127; 803 break; 804 } 805 } 806 807 if (path != pathval()) 808 clearcmdentry(); 809 810 return error1; 811 } 812 813 /* 814 * Locate and print what a word is... 815 */ 816 817 int 818 typecmd(int argc, char **argv) 819 { 820 if (argc > 2 && strcmp(argv[1], "--") == 0) 821 argc--, argv++; 822 return typecmd_impl(argc, argv, TYPECMD_TYPE, bltinlookup("PATH", 1)); 823 } 824