1 /* lib.c - various reusable stuff. 2 * 3 * Copyright 2006 Rob Landley <rob (at) landley.net> 4 */ 5 6 #include "toys.h" 7 8 void verror_msg(char *msg, int err, va_list va) 9 { 10 char *s = ": %s"; 11 12 fprintf(stderr, "%s: ", toys.which->name); 13 if (msg) vfprintf(stderr, msg, va); 14 else s+=2; 15 if (err) fprintf(stderr, s, strerror(err)); 16 if (msg || err) putc('\n', stderr); 17 if (!toys.exitval) toys.exitval++; 18 } 19 20 // These functions don't collapse together because of the va_stuff. 21 22 void error_msg(char *msg, ...) 23 { 24 va_list va; 25 26 va_start(va, msg); 27 verror_msg(msg, 0, va); 28 va_end(va); 29 } 30 31 void perror_msg(char *msg, ...) 32 { 33 va_list va; 34 35 va_start(va, msg); 36 verror_msg(msg, errno, va); 37 va_end(va); 38 } 39 40 // Die with an error message. 41 void error_exit(char *msg, ...) 42 { 43 va_list va; 44 45 va_start(va, msg); 46 verror_msg(msg, 0, va); 47 va_end(va); 48 49 xexit(); 50 } 51 52 // Die with an error message and strerror(errno) 53 void perror_exit(char *msg, ...) 54 { 55 va_list va; 56 57 va_start(va, msg); 58 verror_msg(msg, errno, va); 59 va_end(va); 60 61 xexit(); 62 } 63 64 // Exit with an error message after showing help text. 65 void help_exit(char *msg, ...) 66 { 67 va_list va; 68 69 if (CFG_TOYBOX_HELP) show_help(stderr); 70 71 if (msg) { 72 va_start(va, msg); 73 verror_msg(msg, 0, va); 74 va_end(va); 75 } 76 77 xexit(); 78 } 79 80 // If you want to explicitly disable the printf() behavior (because you're 81 // printing user-supplied data, or because android's static checker produces 82 // false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's 83 // -Werror there for policy reasons). 84 void error_msg_raw(char *msg) 85 { 86 error_msg("%s", msg); 87 } 88 89 void perror_msg_raw(char *msg) 90 { 91 perror_msg("%s", msg); 92 } 93 94 void error_exit_raw(char *msg) 95 { 96 error_exit("%s", msg); 97 } 98 99 void perror_exit_raw(char *msg) 100 { 101 perror_exit("%s", msg); 102 } 103 104 // Keep reading until full or EOF 105 ssize_t readall(int fd, void *buf, size_t len) 106 { 107 size_t count = 0; 108 109 while (count<len) { 110 int i = read(fd, (char *)buf+count, len-count); 111 if (!i) break; 112 if (i<0) return i; 113 count += i; 114 } 115 116 return count; 117 } 118 119 // Keep writing until done or EOF 120 ssize_t writeall(int fd, void *buf, size_t len) 121 { 122 size_t count = 0; 123 while (count<len) { 124 int i = write(fd, count+(char *)buf, len-count); 125 if (i<1) return i; 126 count += i; 127 } 128 129 return count; 130 } 131 132 // skip this many bytes of input. Return 0 for success, >0 means this much 133 // left after input skipped. 134 off_t lskip(int fd, off_t offset) 135 { 136 off_t cur = lseek(fd, 0, SEEK_CUR); 137 138 if (cur != -1) { 139 off_t end = lseek(fd, 0, SEEK_END) - cur; 140 141 if (end > 0 && end < offset) return offset - end; 142 end = offset+cur; 143 if (end == lseek(fd, end, SEEK_SET)) return 0; 144 perror_exit("lseek"); 145 } 146 147 while (offset>0) { 148 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or; 149 150 or = readall(fd, libbuf, try); 151 if (or < 0) perror_exit("lskip to %lld", (long long)offset); 152 else offset -= or; 153 if (or < try) break; 154 } 155 156 return offset; 157 } 158 159 // flags: 1=make last dir (with mode lastmode, otherwise skips last component) 160 // 2=make path (already exists is ok) 161 // 4=verbose 162 // returns 0 = path ok, 1 = error 163 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags) 164 { 165 struct stat buf; 166 char *s; 167 168 // mkdir -p one/two/three is not an error if the path already exists, 169 // but is if "three" is a file. The others we dereference and catch 170 // not-a-directory along the way, but the last one we must explicitly 171 // test for. Might as well do it up front. 172 173 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) { 174 errno = EEXIST; 175 return 1; 176 } 177 178 for (s = dir; ;s++) { 179 char save = 0; 180 mode_t mode = (0777&~toys.old_umask)|0300; 181 182 // find next '/', but don't try to mkdir "" at start of absolute path 183 if (*s == '/' && (flags&2) && s != dir) { 184 save = *s; 185 *s = 0; 186 } else if (*s) continue; 187 188 // Use the mode from the -m option only for the last directory. 189 if (!save) { 190 if (flags&1) mode = lastmode; 191 else break; 192 } 193 194 if (mkdirat(atfd, dir, mode)) { 195 if (!(flags&2) || errno != EEXIST) return 1; 196 } else if (flags&4) 197 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir); 198 199 if (!(*s = save)) break; 200 } 201 202 return 0; 203 } 204 205 // Split a path into linked list of components, tracking head and tail of list. 206 // Filters out // entries with no contents. 207 struct string_list **splitpath(char *path, struct string_list **list) 208 { 209 char *new = path; 210 211 *list = 0; 212 do { 213 int len; 214 215 if (*path && *path != '/') continue; 216 len = path-new; 217 if (len > 0) { 218 *list = xmalloc(sizeof(struct string_list) + len + 1); 219 (*list)->next = 0; 220 memcpy((*list)->str, new, len); 221 (*list)->str[len] = 0; 222 list = &(*list)->next; 223 } 224 new = path+1; 225 } while (*path++); 226 227 return list; 228 } 229 230 // Find all file in a colon-separated path with access type "type" (generally 231 // X_OK or R_OK). Returns a list of absolute paths to each file found, in 232 // order. 233 234 struct string_list *find_in_path(char *path, char *filename) 235 { 236 struct string_list *rlist = NULL, **prlist=&rlist; 237 char *cwd; 238 239 if (!path) return 0; 240 241 cwd = xgetcwd(); 242 for (;;) { 243 char *next = strchr(path, ':'); 244 int len = next ? next-path : strlen(path); 245 struct string_list *rnext; 246 struct stat st; 247 248 rnext = xmalloc(sizeof(void *) + strlen(filename) 249 + (len ? len : strlen(cwd)) + 2); 250 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename); 251 else { 252 char *res = rnext->str; 253 254 memcpy(res, path, len); 255 res += len; 256 *(res++) = '/'; 257 strcpy(res, filename); 258 } 259 260 // Confirm it's not a directory. 261 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) { 262 *prlist = rnext; 263 rnext->next = NULL; 264 prlist = &(rnext->next); 265 } else free(rnext); 266 267 if (!next) break; 268 path += len; 269 path++; 270 } 271 free(cwd); 272 273 return rlist; 274 } 275 276 long long estrtol(char *str, char **end, int base) 277 { 278 errno = 0; 279 280 return strtoll(str, end, base); 281 } 282 283 long long xstrtol(char *str, char **end, int base) 284 { 285 long long l = estrtol(str, end, base); 286 287 if (errno) perror_exit_raw(str); 288 289 return l; 290 } 291 292 // atol() with the kilo/mega/giga/tera/peta/exa extensions. 293 // (zetta and yotta don't fit in 64 bits.) 294 long long atolx(char *numstr) 295 { 296 char *c = numstr, *suffixes="cbkmgtpe", *end; 297 long long val; 298 299 val = xstrtol(numstr, &c, 0); 300 if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) { 301 int shift = end-suffixes-2; 302 303 if (shift >= 0) { 304 if (toupper(*++c)=='d') do val *= 1000; while (shift--); 305 else val *= 1024LL<<(shift*10); 306 } 307 } 308 while (isspace(*c)) c++; 309 if (c==numstr || *c) error_exit("not integer: %s", numstr); 310 311 return val; 312 } 313 314 long long atolx_range(char *numstr, long long low, long long high) 315 { 316 long long val = atolx(numstr); 317 318 if (val < low) error_exit("%lld < %lld", val, low); 319 if (val > high) error_exit("%lld > %lld", val, high); 320 321 return val; 322 } 323 324 int stridx(char *haystack, char needle) 325 { 326 char *off; 327 328 if (!needle) return -1; 329 off = strchr(haystack, needle); 330 if (!off) return -1; 331 332 return off-haystack; 333 } 334 335 char *strlower(char *s) 336 { 337 char *try, *new; 338 339 if (!CFG_TOYBOX_I18N) { 340 try = new = xstrdup(s); 341 for (; *s; s++) *(new++) = tolower(*s); 342 } else { 343 // I can't guarantee the string _won't_ expand during reencoding, so...? 344 try = new = xmalloc(strlen(s)*2+1); 345 346 while (*s) { 347 wchar_t c; 348 int len = mbrtowc(&c, s, MB_CUR_MAX, 0); 349 350 if (len < 1) *(new++) = *(s++); 351 else { 352 s += len; 353 // squash title case too 354 c = towlower(c); 355 356 // if we had a valid utf8 sequence, convert it to lower case, and can't 357 // encode back to utf8, something is wrong with your libc. But just 358 // in case somebody finds an exploit... 359 len = wcrtomb(new, c, 0); 360 if (len < 1) error_exit("bad utf8 %x", (int)c); 361 new += len; 362 } 363 } 364 *new = 0; 365 } 366 367 return try; 368 } 369 370 // strstr but returns pointer after match 371 char *strafter(char *haystack, char *needle) 372 { 373 char *s = strstr(haystack, needle); 374 375 return s ? s+strlen(needle) : s; 376 } 377 378 // Remove trailing \n 379 char *chomp(char *s) 380 { 381 char *p = strrchr(s, '\n'); 382 383 if (p && !p[1]) *p = 0; 384 return s; 385 } 386 387 int unescape(char c) 388 { 389 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v"; 390 int idx = stridx(from, c); 391 392 return (idx == -1) ? 0 : to[idx]; 393 } 394 395 // If *a starts with b, advance *a past it and return 1, else return 0; 396 int strstart(char **a, char *b) 397 { 398 int len = strlen(b), i = !strncmp(*a, b, len); 399 400 if (i) *a += len; 401 402 return i; 403 } 404 405 // Return how long the file at fd is, if there's any way to determine it. 406 off_t fdlength(int fd) 407 { 408 struct stat st; 409 off_t base = 0, range = 1, expand = 1, old; 410 411 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size; 412 413 // If the ioctl works for this, return it. 414 // TODO: is blocksize still always 512, or do we stat for it? 415 // unsigned int size; 416 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L; 417 418 // If not, do a binary search for the last location we can read. (Some 419 // block devices don't do BLKGETSIZE right.) This should probably have 420 // a CONFIG option... 421 422 // If not, do a binary search for the last location we can read. 423 424 old = lseek(fd, 0, SEEK_CUR); 425 do { 426 char temp; 427 off_t pos = base + range / 2; 428 429 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) { 430 off_t delta = (pos + 1) - base; 431 432 base += delta; 433 if (expand) range = (expand <<= 1) - base; 434 else range -= delta; 435 } else { 436 expand = 0; 437 range = pos - base; 438 } 439 } while (range > 0); 440 441 lseek(fd, old, SEEK_SET); 442 443 return base; 444 } 445 446 // Read contents of file as a single nul-terminated string. 447 // measure file size if !len, allocate buffer if !buf 448 // Existing buffers need len in *plen 449 // Returns amount of data read in *plen 450 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen) 451 { 452 off_t len, rlen; 453 int fd; 454 char *buf, *rbuf; 455 456 // Unsafe to probe for size with a supplied buffer, don't ever do that. 457 if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat"); 458 459 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0; 460 461 // If we dunno the length, probe it. If we can't probe, start with 1 page. 462 if (!*plen) { 463 if ((len = fdlength(fd))>0) *plen = len; 464 else len = 4096; 465 } else len = *plen-1; 466 467 if (!ibuf) buf = xmalloc(len+1); 468 else buf = ibuf; 469 470 for (rbuf = buf;;) { 471 rlen = readall(fd, rbuf, len); 472 if (*plen || rlen<len) break; 473 474 // If reading unknown size, expand buffer by 1.5 each time we fill it up. 475 rlen += rbuf-buf; 476 buf = xrealloc(buf, len = (rlen*3)/2); 477 rbuf = buf+rlen; 478 len -= rlen; 479 } 480 *plen = len = rlen+(rbuf-buf); 481 close(fd); 482 483 if (rlen<0) { 484 if (ibuf != buf) free(buf); 485 buf = 0; 486 } else buf[len] = 0; 487 488 return buf; 489 } 490 491 char *readfile(char *name, char *ibuf, off_t len) 492 { 493 return readfileat(AT_FDCWD, name, ibuf, &len); 494 } 495 496 // Sleep for this many thousandths of a second 497 void msleep(long miliseconds) 498 { 499 struct timespec ts; 500 501 ts.tv_sec = miliseconds/1000; 502 ts.tv_nsec = (miliseconds%1000)*1000000; 503 nanosleep(&ts, &ts); 504 } 505 506 // Inefficient, but deals with unaligned access 507 int64_t peek_le(void *ptr, unsigned size) 508 { 509 int64_t ret = 0; 510 char *c = ptr; 511 int i; 512 513 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8); 514 return ret; 515 } 516 517 int64_t peek_be(void *ptr, unsigned size) 518 { 519 int64_t ret = 0; 520 char *c = ptr; 521 int i; 522 523 for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff); 524 return ret; 525 } 526 527 int64_t peek(void *ptr, unsigned size) 528 { 529 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size); 530 } 531 532 void poke(void *ptr, uint64_t val, int size) 533 { 534 if (size & 8) { 535 volatile uint64_t *p = (uint64_t *)ptr; 536 *p = val; 537 } else if (size & 4) { 538 volatile int *p = (int *)ptr; 539 *p = val; 540 } else if (size & 2) { 541 volatile short *p = (short *)ptr; 542 *p = val; 543 } else { 544 volatile char *p = (char *)ptr; 545 *p = val; 546 } 547 } 548 549 // Iterate through an array of files, opening each one and calling a function 550 // on that filehandle and name. The special filename "-" means stdin if 551 // flags is O_RDONLY, stdout otherwise. An empty argument list calls 552 // function() on just stdin/stdout. 553 // 554 // Note: pass O_CLOEXEC to automatically close filehandles when function() 555 // returns, otherwise filehandles must be closed by function(). 556 // pass WARN_ONLY to produce warning messages about files it couldn't 557 // open/create, and skip them. Otherwise function is called with fd -1. 558 void loopfiles_rw(char **argv, int flags, int permissions, 559 void (*function)(int fd, char *name)) 560 { 561 int fd, failok = !(flags&WARN_ONLY); 562 563 flags &= ~WARN_ONLY; 564 565 // If no arguments, read from stdin. 566 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-"); 567 else do { 568 // Filename "-" means read from stdin. 569 // Inability to open a file prints a warning, but doesn't exit. 570 571 if (!strcmp(*argv, "-")) fd = 0; 572 else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) { 573 perror_msg_raw(*argv); 574 continue; 575 } 576 function(fd, *argv); 577 if ((flags & O_CLOEXEC) && fd) close(fd); 578 } while (*++argv); 579 } 580 581 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case) 582 void loopfiles(char **argv, void (*function)(int fd, char *name)) 583 { 584 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function); 585 } 586 587 // Slow, but small. 588 589 char *get_rawline(int fd, long *plen, char end) 590 { 591 char c, *buf = NULL; 592 long len = 0; 593 594 for (;;) { 595 if (1>read(fd, &c, 1)) break; 596 if (!(len & 63)) buf=xrealloc(buf, len+65); 597 if ((buf[len++]=c) == end) break; 598 } 599 if (buf) buf[len]=0; 600 if (plen) *plen = len; 601 602 return buf; 603 } 604 605 char *get_line(int fd) 606 { 607 long len; 608 char *buf = get_rawline(fd, &len, '\n'); 609 610 if (buf && buf[--len]=='\n') buf[len]=0; 611 612 return buf; 613 } 614 615 int wfchmodat(int fd, char *name, mode_t mode) 616 { 617 int rc = fchmodat(fd, name, mode, 0); 618 619 if (rc) { 620 perror_msg("chmod '%s' to %04o", name, mode); 621 toys.exitval=1; 622 } 623 return rc; 624 } 625 626 static char *tempfile2zap; 627 static void tempfile_handler(void) 628 { 629 if (1 < (long)tempfile2zap) unlink(tempfile2zap); 630 } 631 632 // Open a temporary file to copy an existing file into. 633 int copy_tempfile(int fdin, char *name, char **tempname) 634 { 635 struct stat statbuf; 636 int fd; 637 int ignored __attribute__((__unused__)); 638 639 *tempname = xmprintf("%s%s", name, "XXXXXX"); 640 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file"); 641 if (!tempfile2zap) sigatexit(tempfile_handler); 642 tempfile2zap = *tempname; 643 644 // Set permissions of output file (ignoring errors, usually due to nonroot) 645 646 fstat(fdin, &statbuf); 647 fchmod(fd, statbuf.st_mode); 648 649 // We chmod before chown, which strips the suid bit. Caller has to explicitly 650 // switch it back on if they want to keep suid. 651 652 // Suppress warn-unused-result. Both gcc and clang clutch their pearls about 653 // this but it's _supposed_ to fail when we're not root. 654 ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid); 655 656 return fd; 657 } 658 659 // Abort the copy and delete the temporary file. 660 void delete_tempfile(int fdin, int fdout, char **tempname) 661 { 662 close(fdin); 663 close(fdout); 664 if (*tempname) unlink(*tempname); 665 tempfile2zap = (char *)1; 666 free(*tempname); 667 *tempname = NULL; 668 } 669 670 // Copy the rest of the data and replace the original with the copy. 671 void replace_tempfile(int fdin, int fdout, char **tempname) 672 { 673 char *temp = xstrdup(*tempname); 674 675 temp[strlen(temp)-6]=0; 676 if (fdin != -1) { 677 xsendfile(fdin, fdout); 678 xclose(fdin); 679 } 680 xclose(fdout); 681 rename(*tempname, temp); 682 tempfile2zap = (char *)1; 683 free(*tempname); 684 free(temp); 685 *tempname = NULL; 686 } 687 688 // Create a 256 entry CRC32 lookup table. 689 690 void crc_init(unsigned int *crc_table, int little_endian) 691 { 692 unsigned int i; 693 694 // Init the CRC32 table (big endian) 695 for (i=0; i<256; i++) { 696 unsigned int j, c = little_endian ? i : i<<24; 697 for (j=8; j; j--) 698 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1; 699 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1); 700 crc_table[i] = c; 701 } 702 } 703 704 // Init base64 table 705 706 void base64_init(char *p) 707 { 708 int i; 709 710 for (i = 'A'; i != ':'; i++) { 711 if (i == 'Z'+1) i = 'a'; 712 if (i == 'z'+1) i = '0'; 713 *(p++) = i; 714 } 715 *(p++) = '+'; 716 *(p++) = '/'; 717 } 718 719 int yesno(int def) 720 { 721 char buf; 722 723 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N'); 724 fflush(stderr); 725 while (fread(&buf, 1, 1, stdin)) { 726 int new; 727 728 // The letter changes the value, the newline (or space) returns it. 729 if (isspace(buf)) break; 730 if (-1 != (new = stridx("ny", tolower(buf)))) def = new; 731 } 732 733 return def; 734 } 735 736 struct signame { 737 int num; 738 char *name; 739 }; 740 741 // Signals required by POSIX 2008: 742 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html 743 744 #define SIGNIFY(x) {SIG##x, #x} 745 746 static struct signame signames[] = { 747 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS), 748 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL), 749 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM), 750 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP), 751 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ), 752 753 // Start of non-terminal signals 754 755 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP), 756 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG) 757 }; 758 759 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR) 760 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL) 761 762 // Handler that sets toys.signal, and writes to toys.signalfd if set 763 void generic_signal(int sig) 764 { 765 if (toys.signalfd) { 766 char c = sig; 767 768 writeall(toys.signalfd, &c, 1); 769 } 770 toys.signal = sig; 771 } 772 773 void exit_signal(int sig) 774 { 775 if (sig) toys.exitval = sig|128; 776 xexit(); 777 } 778 779 // Install the same handler on every signal that defaults to killing the 780 // process, calling the handler on the way out. Calling multiple times 781 // adds the handlers to a list, to be called in order. 782 void sigatexit(void *handler) 783 { 784 struct arg_list *al = xmalloc(sizeof(struct arg_list)); 785 int i; 786 787 for (i=0; signames[i].num != SIGCHLD; i++) 788 signal(signames[i].num, exit_signal); 789 al->next = toys.xexit; 790 al->arg = handler; 791 toys.xexit = al; 792 } 793 794 // Convert name to signal number. If name == NULL print names. 795 int sig_to_num(char *pidstr) 796 { 797 int i; 798 799 if (pidstr) { 800 char *s; 801 802 i = estrtol(pidstr, &s, 10); 803 if (!errno && !*s) return i; 804 805 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3; 806 } 807 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++) 808 if (!pidstr) xputs(signames[i].name); 809 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num; 810 811 return -1; 812 } 813 814 char *num_to_sig(int sig) 815 { 816 int i; 817 818 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++) 819 if (signames[i].num == sig) return signames[i].name; 820 return NULL; 821 } 822 823 // premute mode bits based on posix mode strings. 824 mode_t string_to_mode(char *modestr, mode_t mode) 825 { 826 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu", 827 *s, *str = modestr; 828 mode_t extrabits = mode & ~(07777); 829 830 // Handle octal mode 831 if (isdigit(*str)) { 832 mode = estrtol(str, &s, 8); 833 if (errno || *s || (mode & ~(07777))) goto barf; 834 835 return mode | extrabits; 836 } 837 838 // Gaze into the bin of permission... 839 for (;;) { 840 int i, j, dowho, dohow, dowhat, amask; 841 842 dowho = dohow = dowhat = amask = 0; 843 844 // Find the who, how, and what stanzas, in that order 845 while (*str && (s = strchr(whos, *str))) { 846 dowho |= 1<<(s-whos); 847 str++; 848 } 849 // If who isn't specified, like "a" but honoring umask. 850 if (!dowho) { 851 dowho = 8; 852 umask(amask=umask(0)); 853 } 854 if (!*str || !(s = strchr(hows, *str))) goto barf; 855 dohow = *(str++); 856 857 if (!dohow) goto barf; 858 while (*str && (s = strchr(whats, *str))) { 859 dowhat |= 1<<(s-whats); 860 str++; 861 } 862 863 // Convert X to x for directory or if already executable somewhere 864 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1; 865 866 // Copy mode from another category? 867 if (!dowhat && *str && (s = strchr(whys, *str))) { 868 dowhat = (mode>>(3*(s-whys)))&7; 869 str++; 870 } 871 872 // Are we ready to do a thing yet? 873 if (*str && *(str++) != ',') goto barf; 874 875 // Ok, apply the bits to the mode. 876 for (i=0; i<4; i++) { 877 for (j=0; j<3; j++) { 878 mode_t bit = 0; 879 int where = 1<<((3*i)+j); 880 881 if (amask & where) continue; 882 883 // Figure out new value at this location 884 if (i == 3) { 885 // suid/sticky bit. 886 if (j) { 887 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++; 888 } else if (dowhat & 16) bit++; 889 } else { 890 if (!(dowho&(8|(1<<i)))) continue; 891 if (dowhat&(1<<j)) bit++; 892 } 893 894 // When selection active, modify bit 895 896 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where; 897 if (bit && dohow != '-') mode |= where; 898 } 899 } 900 901 if (!*str) break; 902 } 903 904 return mode|extrabits; 905 barf: 906 error_exit("bad mode '%s'", modestr); 907 } 908 909 // Format access mode into a drwxrwxrwx string 910 void mode_to_string(mode_t mode, char *buf) 911 { 912 char c, d; 913 int i, bit; 914 915 buf[10]=0; 916 for (i=0; i<9; i++) { 917 bit = mode & (1<<i); 918 c = i%3; 919 if (!c && (mode & (1<<((d=i/3)+9)))) { 920 c = "tss"[d]; 921 if (!bit) c &= ~0x20; 922 } else c = bit ? "xwr"[c] : '-'; 923 buf[9-i] = c; 924 } 925 926 if (S_ISDIR(mode)) c = 'd'; 927 else if (S_ISBLK(mode)) c = 'b'; 928 else if (S_ISCHR(mode)) c = 'c'; 929 else if (S_ISLNK(mode)) c = 'l'; 930 else if (S_ISFIFO(mode)) c = 'p'; 931 else if (S_ISSOCK(mode)) c = 's'; 932 else c = '-'; 933 *buf = c; 934 } 935 936 // basename() can modify its argument or return a pointer to a constant string 937 // This just gives after the last '/' or the whole stirng if no / 938 char *getbasename(char *name) 939 { 940 char *s = strrchr(name, '/'); 941 942 if (s) return s+1; 943 944 return name; 945 } 946 947 // Execute a callback for each PID that matches a process name from a list. 948 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name)) 949 { 950 DIR *dp; 951 struct dirent *entry; 952 953 if (!(dp = opendir("/proc"))) perror_exit("opendir"); 954 955 while ((entry = readdir(dp))) { 956 unsigned u; 957 char *cmd, **curname; 958 959 if (!(u = atoi(entry->d_name))) continue; 960 sprintf(libbuf, "/proc/%u/cmdline", u); 961 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue; 962 963 for (curname = names; *curname; curname++) 964 if (**curname == '/' ? !strcmp(cmd, *curname) 965 : !strcmp(getbasename(cmd), getbasename(*curname))) 966 if (callback(u, *curname)) break; 967 if (*curname) break; 968 } 969 closedir(dp); 970 } 971 972 // display first few digits of number with power of two units 973 int human_readable(char *buf, unsigned long long num, int style) 974 { 975 unsigned long long snap = 0; 976 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024; 977 978 // Divide rounding up until we have 3 or fewer digits. Since the part we 979 // print is decimal, the test is 999 even when we divide by 1024. 980 // We can't run out of units because 2<<64 is 18 exabytes. 981 // test 5675 is 5.5k not 5.6k. 982 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor; 983 len = sprintf(buf, "%llu", num); 984 if (unit && len == 1) { 985 // Redo rounding for 1.2M case, this works with and without HR_1000. 986 num = snap/divisor; 987 snap -= num*divisor; 988 snap = ((snap*100)+50)/divisor; 989 snap /= 10; 990 len = sprintf(buf, "%llu.%llu", num, snap); 991 } 992 if (style & HR_SPACE) buf[len++] = ' '; 993 if (unit) { 994 unit = " kMGTPE"[unit]; 995 996 if (!(style&HR_1000)) unit = toupper(unit); 997 buf[len++] = unit; 998 } else if (style & HR_B) buf[len++] = 'B'; 999 buf[len] = 0; 1000 1001 return len; 1002 } 1003 1004 // The qsort man page says you can use alphasort, the posix committee 1005 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142 1006 // So just do our own. (The const is entirely to humor the stupid compiler.) 1007 int qstrcmp(const void *a, const void *b) 1008 { 1009 return strcmp(*(char **)a, *(char **)b); 1010 } 1011 1012 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm 1013 // we should generate a uuid structure by reading a clock with 100 nanosecond 1014 // precision, normalizing it to the start of the gregorian calendar in 1582, 1015 // and looking up our eth0 mac address. 1016 // 1017 // On the other hand, we have 128 bits to come up with a unique identifier, of 1018 // which 6 have a defined value. /dev/urandom it is. 1019 1020 void create_uuid(char *uuid) 1021 { 1022 // Read 128 random bits 1023 int fd = xopenro("/dev/urandom"); 1024 xreadall(fd, uuid, 16); 1025 close(fd); 1026 1027 // Claim to be a DCE format UUID. 1028 uuid[6] = (uuid[6] & 0x0F) | 0x40; 1029 uuid[8] = (uuid[8] & 0x3F) | 0x80; 1030 1031 // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should 1032 // set bit 1 of the node ID, which is the mac multicast bit. This means we 1033 // should never collide with anybody actually using a macaddr. 1034 uuid[11] |= 128; 1035 } 1036 1037 char *show_uuid(char *uuid) 1038 { 1039 char *out = libbuf; 1040 int i; 1041 1042 for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]); 1043 *out = 0; 1044 1045 return libbuf; 1046 } 1047 1048 // Returns pointer to letter at end, 0 if none. *start = initial % 1049 char *next_printf(char *s, char **start) 1050 { 1051 for (; *s; s++) { 1052 if (*s != '%') continue; 1053 if (*++s == '%') continue; 1054 if (start) *start = s-1; 1055 while (0 <= stridx("0'#-+ ", *s)) s++; 1056 while (isdigit(*s)) s++; 1057 if (*s == '.') s++; 1058 while (isdigit(*s)) s++; 1059 1060 return s; 1061 } 1062 1063 return 0; 1064 } 1065 1066 // Posix inexplicably hasn't got this, so find str in line. 1067 char *strnstr(char *line, char *str) 1068 { 1069 long len = strlen(str); 1070 char *s; 1071 1072 for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break; 1073 1074 return *s ? s : 0; 1075 } 1076 1077 int dev_minor(int dev) 1078 { 1079 return ((dev&0xfff00000)>>12)|(dev&0xff); 1080 } 1081 1082 int dev_major(int dev) 1083 { 1084 return (dev&0xfff00)>>8; 1085 } 1086 1087 int dev_makedev(int major, int minor) 1088 { 1089 return (minor&0xff)|((major&0xfff)<<8)|((minor&0xfff00)<<12); 1090 } 1091 1092 // Return cached passwd entries. 1093 struct passwd *bufgetpwuid(uid_t uid) 1094 { 1095 struct pwuidbuf_list { 1096 struct pwuidbuf_list *next; 1097 struct passwd pw; 1098 } *list; 1099 struct passwd *temp; 1100 static struct pwuidbuf_list *pwuidbuf; 1101 1102 for (list = pwuidbuf; list; list = list->next) 1103 if (list->pw.pw_uid == uid) return &(list->pw); 1104 1105 list = xmalloc(512); 1106 list->next = pwuidbuf; 1107 1108 errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list, 1109 512-sizeof(*list), &temp); 1110 if (!temp) { 1111 free(list); 1112 1113 return 0; 1114 } 1115 pwuidbuf = list; 1116 1117 return &list->pw; 1118 } 1119 1120 // Return cached passwd entries. 1121 struct group *bufgetgrgid(gid_t gid) 1122 { 1123 struct grgidbuf_list { 1124 struct grgidbuf_list *next; 1125 struct group gr; 1126 } *list; 1127 struct group *temp; 1128 static struct grgidbuf_list *grgidbuf; 1129 1130 for (list = grgidbuf; list; list = list->next) 1131 if (list->gr.gr_gid == gid) return &(list->gr); 1132 1133 list = xmalloc(512); 1134 list->next = grgidbuf; 1135 1136 errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list, 1137 512-sizeof(*list), &temp); 1138 if (!temp) { 1139 free(list); 1140 1141 return 0; 1142 } 1143 grgidbuf = list; 1144 1145 return &list->gr; 1146 } 1147 1148 // Always null terminates, returns 0 for failure, len for success 1149 int readlinkat0(int dirfd, char *path, char *buf, int len) 1150 { 1151 if (!len) return 0; 1152 1153 len = readlinkat(dirfd, path, buf, len-1); 1154 if (len<1) return 0; 1155 buf[len] = 0; 1156 1157 return len; 1158 } 1159 1160 int readlink0(char *path, char *buf, int len) 1161 { 1162 return readlinkat0(AT_FDCWD, path, buf, len); 1163 } 1164 1165 // Do regex matching handling embedded NUL bytes in string (hence extra len 1166 // argument). Note that neither the pattern nor the match can currently include 1167 // NUL bytes (even with wildcards) and string must be null terminated at 1168 // string[len]. But this can find a match after the first NUL. 1169 int regexec0(regex_t *preg, char *string, long len, int nmatch, 1170 regmatch_t pmatch[], int eflags) 1171 { 1172 char *s = string; 1173 1174 for (;;) { 1175 long ll = 0; 1176 int rc; 1177 1178 while (len && !*s) { 1179 s++; 1180 len--; 1181 } 1182 while (s[ll] && ll<len) ll++; 1183 1184 rc = regexec(preg, s, nmatch, pmatch, eflags); 1185 if (!rc) { 1186 for (rc = 0; rc<nmatch && pmatch[rc].rm_so!=-1; rc++) { 1187 pmatch[rc].rm_so += s-string; 1188 pmatch[rc].rm_eo += s-string; 1189 } 1190 1191 return 0; 1192 } 1193 if (ll==len) return rc; 1194 1195 s += ll; 1196 len -= ll; 1197 } 1198 } 1199 1200 // Return user name or string representation of number, returned buffer 1201 // lasts until next call. 1202 char *getusername(uid_t uid) 1203 { 1204 struct passwd *pw = bufgetpwuid(uid); 1205 static char unum[12]; 1206 1207 sprintf(unum, "%u", (unsigned)uid); 1208 return pw ? pw->pw_name : unum; 1209 } 1210 1211 // Return group name or string representation of number, returned buffer 1212 // lasts until next call. 1213 char *getgroupname(gid_t gid) 1214 { 1215 struct group *gr = bufgetgrgid(gid); 1216 static char gnum[12]; 1217 1218 sprintf(gnum, "%u", (unsigned)gid); 1219 return gr ? gr->gr_name : gnum; 1220 } 1221 1222 // Iterate over lines in file, calling function. Function can write 0 to 1223 // the line pointer if they want to keep it, or 1 to terminate processing, 1224 // otherwise line is freed. Passed file descriptor is closed at the end. 1225 void do_lines(int fd, void (*call)(char **pline, long len)) 1226 { 1227 FILE *fp = fd ? xfdopen(fd, "r") : stdin; 1228 1229 for (;;) { 1230 char *line = 0; 1231 ssize_t len; 1232 1233 len = getline(&line, (void *)&len, fp); 1234 if (len > 0) { 1235 call(&line, len); 1236 if (line == (void *)1) break; 1237 free(line); 1238 } else break; 1239 } 1240 1241 if (fd) fclose(fp); 1242 } 1243