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