toybox/lib/lib.c
<<
>>
Prefs
   1/* lib.c - various reusable stuff.
   2 *
   3 * Copyright 2006 Rob Landley <rob@landley.net>
   4 */
   5
   6#define SYSLOG_NAMES
   7#include "toys.h"
   8
   9void verror_msg(char *msg, int err, va_list va)
  10{
  11  char *s = ": %s";
  12
  13  fprintf(stderr, "%s: ", toys.which->name);
  14  if (msg) vfprintf(stderr, msg, va);
  15  else s+=2;
  16  if (err>0) fprintf(stderr, s, strerror(err));
  17  if (err<0 && CFG_TOYBOX_HELP)
  18    fprintf(stderr, " (see \"%s --help\")", toys.which->name);
  19  if (msg || err) putc('\n', stderr);
  20  if (!toys.exitval) toys.exitval++;
  21}
  22
  23// These functions don't collapse together because of the va_stuff.
  24
  25void error_msg(char *msg, ...)
  26{
  27  va_list va;
  28
  29  va_start(va, msg);
  30  verror_msg(msg, 0, va);
  31  va_end(va);
  32}
  33
  34void perror_msg(char *msg, ...)
  35{
  36  va_list va;
  37
  38  va_start(va, msg);
  39  verror_msg(msg, errno, va);
  40  va_end(va);
  41}
  42
  43// Die with an error message.
  44void error_exit(char *msg, ...)
  45{
  46  va_list va;
  47
  48  va_start(va, msg);
  49  verror_msg(msg, 0, va);
  50  va_end(va);
  51
  52  xexit();
  53}
  54
  55// Die with an error message and strerror(errno)
  56void perror_exit(char *msg, ...)
  57{
  58  // Die silently if our pipeline exited.
  59  if (errno != EPIPE) {
  60    va_list va;
  61
  62    va_start(va, msg);
  63    verror_msg(msg, errno, va);
  64    va_end(va);
  65  }
  66
  67  xexit();
  68}
  69
  70// Exit with an error message after showing help text.
  71void help_exit(char *msg, ...)
  72{
  73  va_list va;
  74
  75  if (!msg) show_help(stdout, 1);
  76  else {
  77    va_start(va, msg);
  78    verror_msg(msg, -1, va);
  79    va_end(va);
  80  }
  81
  82  xexit();
  83}
  84
  85// If you want to explicitly disable the printf() behavior (because you're
  86// printing user-supplied data, or because android's static checker produces
  87// false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
  88// -Werror there for policy reasons).
  89void error_msg_raw(char *msg)
  90{
  91  error_msg("%s", msg);
  92}
  93
  94void perror_msg_raw(char *msg)
  95{
  96  perror_msg("%s", msg);
  97}
  98
  99void error_exit_raw(char *msg)
 100{
 101  error_exit("%s", msg);
 102}
 103
 104void perror_exit_raw(char *msg)
 105{
 106  perror_exit("%s", msg);
 107}
 108
 109// Keep reading until full or EOF
 110ssize_t readall(int fd, void *buf, size_t len)
 111{
 112  size_t count = 0;
 113
 114  while (count<len) {
 115    int i = read(fd, (char *)buf+count, len-count);
 116    if (!i) break;
 117    if (i<0) return i;
 118    count += i;
 119  }
 120
 121  return count;
 122}
 123
 124// Keep writing until done or EOF
 125ssize_t writeall(int fd, void *buf, size_t len)
 126{
 127  size_t count = 0;
 128
 129  while (count<len) {
 130    int i = write(fd, count+(char *)buf, len-count);
 131    if (i<1) return i;
 132    count += i;
 133  }
 134
 135  return count;
 136}
 137
 138// skip this many bytes of input. Return 0 for success, >0 means this much
 139// left after input skipped.
 140off_t lskip(int fd, off_t offset)
 141{
 142  off_t cur = lseek(fd, 0, SEEK_CUR);
 143
 144  if (cur != -1) {
 145    off_t end = lseek(fd, 0, SEEK_END) - cur;
 146
 147    if (end > 0 && end < offset) return offset - end;
 148    end = offset+cur;
 149    if (end == lseek(fd, end, SEEK_SET)) return 0;
 150    perror_exit("lseek");
 151  }
 152
 153  while (offset>0) {
 154    int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
 155
 156    or = readall(fd, libbuf, try);
 157    if (or < 0) perror_exit("lskip to %lld", (long long)offset);
 158    else offset -= or;
 159    if (or < try) break;
 160  }
 161
 162  return offset;
 163}
 164
 165// flags:
 166// MKPATHAT_MKLAST  make last dir (with mode lastmode, else skips last part)
 167// MKPATHAT_MAKE    make leading dirs (it's ok if they already exist)
 168// MKPATHAT_VERBOSE Print what got created to stderr
 169// returns 0 = path ok, 1 = error
 170int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
 171{
 172  struct stat buf;
 173  char *s;
 174
 175  // mkdir -p one/two/three is not an error if the path already exists,
 176  // but is if "three" is a file. The others we dereference and catch
 177  // not-a-directory along the way, but the last one we must explicitly
 178  // test for. Might as well do it up front.
 179
 180  if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
 181    errno = EEXIST;
 182    return 1;
 183  }
 184
 185  for (s = dir; ;s++) {
 186    char save = 0;
 187    mode_t mode = (0777&~toys.old_umask)|0300;
 188
 189    // find next '/', but don't try to mkdir "" at start of absolute path
 190    if (*s == '/' && (flags&MKPATHAT_MAKE) && s != dir) {
 191      save = *s;
 192      *s = 0;
 193    } else if (*s) continue;
 194
 195    // Use the mode from the -m option only for the last directory.
 196    if (!save) {
 197      if (flags&MKPATHAT_MKLAST) mode = lastmode;
 198      else break;
 199    }
 200
 201    if (mkdirat(atfd, dir, mode)) {
 202      if (!(flags&MKPATHAT_MAKE) || errno != EEXIST) return 1;
 203    } else if (flags&MKPATHAT_VERBOSE)
 204      fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
 205
 206    if (!(*s = save)) break;
 207  }
 208
 209  return 0;
 210}
 211
 212// The common case
 213int mkpath(char *dir)
 214{
 215  return mkpathat(AT_FDCWD, dir, 0, MKPATHAT_MAKE);
 216}
 217
 218// Split a path into linked list of components, tracking head and tail of list.
 219// Assigns head of list to *list, returns address of ->next entry to extend list
 220// Filters out // entries with no contents.
 221struct string_list **splitpath(char *path, struct string_list **list)
 222{
 223  char *new = path;
 224
 225  *list = 0;
 226  do {
 227    int len;
 228
 229    if (*path && *path != '/') continue;
 230    len = path-new;
 231    if (len > 0) {
 232      *list = xmalloc(sizeof(struct string_list) + len + 1);
 233      (*list)->next = 0;
 234      memcpy((*list)->str, new, len);
 235      (*list)->str[len] = 0;
 236      list = &(*list)->next;
 237    }
 238    new = path+1;
 239  } while (*path++);
 240
 241  return list;
 242}
 243
 244// Find all file in a colon-separated path with access type "type" (generally
 245// X_OK or R_OK).  Returns a list of absolute paths to each file found, in
 246// order.
 247
 248struct string_list *find_in_path(char *path, char *filename)
 249{
 250  struct string_list *rlist = NULL, **prlist=&rlist;
 251  char *cwd;
 252
 253  if (!path) return 0;
 254
 255  cwd = xgetcwd();
 256  for (;;) {
 257    char *res, *next = strchr(path, ':');
 258    int len = next ? next-path : strlen(path);
 259    struct string_list *rnext;
 260    struct stat st;
 261
 262    rnext = xmalloc(sizeof(void *) + strlen(filename)
 263      + (len ? len : strlen(cwd)) + 2);
 264    if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
 265    else {
 266      memcpy(res = rnext->str, path, len);
 267      res += len;
 268      *(res++) = '/';
 269      strcpy(res, filename);
 270    }
 271
 272    // Confirm it's not a directory.
 273    if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
 274      *prlist = rnext;
 275      rnext->next = NULL;
 276      prlist = &(rnext->next);
 277    } else free(rnext);
 278
 279    if (!next) break;
 280    path += len;
 281    path++;
 282  }
 283  free(cwd);
 284
 285  return rlist;
 286}
 287
 288long long estrtol(char *str, char **end, int base)
 289{
 290  errno = 0;
 291
 292  return strtoll(str, end, base);
 293}
 294
 295long long xstrtol(char *str, char **end, int base)
 296{
 297  long long l = estrtol(str, end, base);
 298
 299  if (errno) perror_exit_raw(str);
 300
 301  return l;
 302}
 303
 304// atol() with the kilo/mega/giga/tera/peta/exa extensions, plus word and block.
 305// (zetta and yotta don't fit in 64 bits.)
 306long long atolx(char *numstr)
 307{
 308  char *c = numstr, *suffixes="cwbkmgtpe", *end;
 309  long long val;
 310
 311  val = xstrtol(numstr, &c, 0);
 312  if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) {
 313    int shift = end-suffixes-2;
 314    ++c;
 315    if (shift==-1) val *= 2;
 316    else if (!shift) val *= 512;
 317    else if (shift>0) {
 318      if (*c && tolower(*c++)=='d') while (shift--) val *= 1000;
 319      else val *= 1LL<<(shift*10);
 320    }
 321  }
 322  while (isspace(*c)) c++;
 323  if (c==numstr || *c) error_exit("not integer: %s", numstr);
 324
 325  return val;
 326}
 327
 328long long atolx_range(char *numstr, long long low, long long high)
 329{
 330  long long val = atolx(numstr);
 331
 332  if (val < low) error_exit("%lld < %lld", val, low);
 333  if (val > high) error_exit("%lld > %lld", val, high);
 334
 335  return val;
 336}
 337
 338int stridx(char *haystack, char needle)
 339{
 340  char *off;
 341
 342  if (!needle) return -1;
 343  off = strchr(haystack, needle);
 344  if (!off) return -1;
 345
 346  return off-haystack;
 347}
 348
 349// Convert utf8 sequence to a unicode wide character
 350// returns bytes consumed, or -1 if err, or -2 if need more data.
 351int utf8towc(wchar_t *wc, char *str, unsigned len)
 352{
 353  unsigned result, mask, first;
 354  char *s, c;
 355
 356  // fast path ASCII
 357  if (len && *str<128) return !!(*wc = *str);
 358
 359  result = first = *(s = str++);
 360  if (result<0xc2 || result>0xf4) return -1;
 361  for (mask = 6; (first&0xc0)==0xc0; mask += 5, first <<= 1) {
 362    if (!--len) return -2;
 363    if (((c = *(str++))&0xc0) != 0x80) return -1;
 364    result = (result<<6)|(c&0x3f);
 365  }
 366  result &= (1<<mask)-1;
 367  c = str-s;
 368
 369  // Avoid overlong encodings
 370  if (result<(unsigned []){0x80,0x800,0x10000}[c-2]) return -1;
 371
 372  // Limit unicode so it can't encode anything UTF-16 can't.
 373  if (result>0x10ffff || (result>=0xd800 && result<=0xdfff)) return -1;
 374  *wc = result;
 375
 376  return str-s;
 377}
 378
 379char *strlower(char *s)
 380{
 381  char *try, *new;
 382
 383  if (!CFG_TOYBOX_I18N) {
 384    try = new = xstrdup(s);
 385    for (; *s; s++) *(new++) = tolower(*s);
 386  } else {
 387    // I can't guarantee the string _won't_ expand during reencoding, so...?
 388    try = new = xmalloc(strlen(s)*2+1);
 389
 390    while (*s) {
 391      wchar_t c;
 392      int len = utf8towc(&c, s, MB_CUR_MAX);
 393
 394      if (len < 1) *(new++) = *(s++);
 395      else {
 396        s += len;
 397        // squash title case too
 398        c = towlower(c);
 399
 400        // if we had a valid utf8 sequence, convert it to lower case, and can't
 401        // encode back to utf8, something is wrong with your libc. But just
 402        // in case somebody finds an exploit...
 403        len = wcrtomb(new, c, 0);
 404        if (len < 1) error_exit("bad utf8 %x", (int)c);
 405        new += len;
 406      }
 407    }
 408    *new = 0;
 409  }
 410
 411  return try;
 412}
 413
 414// strstr but returns pointer after match
 415char *strafter(char *haystack, char *needle)
 416{
 417  char *s = strstr(haystack, needle);
 418
 419  return s ? s+strlen(needle) : s;
 420}
 421
 422// Remove trailing \n
 423char *chomp(char *s)
 424{
 425  char *p = strrchr(s, '\n');
 426
 427  if (p && !p[1]) *p = 0;
 428  return s;
 429}
 430
 431int unescape(char c)
 432{
 433  char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
 434  int idx = stridx(from, c);
 435
 436  return (idx == -1) ? 0 : to[idx];
 437}
 438
 439// parse next character advancing pointer. echo requires leading 0 in octal esc
 440int unescape2(char **c, int echo)
 441{
 442  int idx = *((*c)++), i, off;
 443
 444  if (idx != '\\' || !**c) return idx;
 445  if (**c == 'c') return 31&*(++*c);
 446  for (i = 0; i<4; i++) {
 447    if (sscanf(*c, (char *[]){"0%3o%n"+!echo, "x%2x%n", "u%4x%n", "U%6x%n"}[i],
 448        &idx, &off))
 449    {
 450      *c += off;
 451
 452      return idx;
 453    }
 454  }
 455
 456  if (-1 == (idx = stridx("\\abeEfnrtv'\"?", **c))) return '\\';
 457  ++*c;
 458
 459  return "\\\a\b\033\033\f\n\r\t\v'\"?"[idx];
 460}
 461
 462// If string ends with suffix return pointer to start of suffix in string,
 463// else NULL
 464char *strend(char *str, char *suffix)
 465{
 466  long a = strlen(str), b = strlen(suffix);
 467
 468  if (a>b && !strcmp(str += a-b, suffix)) return str;
 469
 470  return 0;
 471}
 472
 473// If *a starts with b, advance *a past it and return 1, else return 0;
 474int strstart(char **a, char *b)
 475{
 476  char *c = *a;
 477
 478  while (*b && *c == *b) b++, c++;
 479  if (!*b) *a = c;
 480
 481  return !*b;
 482}
 483
 484// If *a starts with b, advance *a past it and return 1, else return 0;
 485int strcasestart(char **a, char *b)
 486{
 487  int len = strlen(b), i = !strncasecmp(*a, b, len);
 488
 489  if (i) *a += len;
 490
 491  return i;
 492}
 493
 494// Return how long the file at fd is, if there's any way to determine it.
 495off_t fdlength(int fd)
 496{
 497  struct stat st;
 498  off_t base = 0, range = 1, expand = 1, old;
 499  unsigned long long size;
 500
 501  if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
 502
 503  // If the ioctl works for this, return it.
 504  if (get_block_device_size(fd, &size)) return size;
 505
 506  // If not, do a binary search for the last location we can read.  (Some
 507  // block devices don't do BLKGETSIZE right.)  This should probably have
 508  // a CONFIG option...
 509  old = lseek(fd, 0, SEEK_CUR);
 510  do {
 511    char temp;
 512    off_t pos = base + range / 2;
 513
 514    if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
 515      off_t delta = (pos + 1) - base;
 516
 517      base += delta;
 518      if (expand) range = (expand <<= 1) - base;
 519      else range -= delta;
 520    } else {
 521      expand = 0;
 522      range = pos - base;
 523    }
 524  } while (range > 0);
 525
 526  lseek(fd, old, SEEK_SET);
 527
 528  return base;
 529}
 530
 531char *readfd(int fd, char *ibuf, off_t *plen)
 532{
 533  off_t len, rlen;
 534  char *buf, *rbuf;
 535
 536  // Unsafe to probe for size with a supplied buffer, don't ever do that.
 537  if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
 538
 539  // If we dunno the length, probe it. If we can't probe, start with 1 page.
 540  if (!*plen) {
 541    if ((len = fdlength(fd))>0) *plen = len;
 542    else len = 4096;
 543  } else len = *plen-1;
 544
 545  if (!ibuf) buf = xmalloc(len+1);
 546  else buf = ibuf;
 547
 548  for (rbuf = buf;;) {
 549    rlen = readall(fd, rbuf, len);
 550    if (*plen || rlen<len) break;
 551
 552    // If reading unknown size, expand buffer by 1.5 each time we fill it up.
 553    rlen += rbuf-buf;
 554    buf = xrealloc(buf, len = (rlen*3)/2);
 555    rbuf = buf+rlen;
 556    len -= rlen;
 557  }
 558  *plen = len = rlen+(rbuf-buf);
 559
 560  if (rlen<0) {
 561    if (ibuf != buf) free(buf);
 562    buf = 0;
 563  } else buf[len] = 0;
 564
 565  return buf;
 566}
 567
 568// Read contents of file as a single nul-terminated string.
 569// measure file size if !len, allocate buffer if !buf
 570// Existing buffers need len in *plen
 571// Returns amount of data read in *plen
 572char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
 573{
 574  if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0;
 575
 576  ibuf = readfd(dirfd, ibuf, plen);
 577  close(dirfd);
 578
 579  return ibuf;
 580}
 581
 582char *readfile(char *name, char *ibuf, off_t len)
 583{
 584  return readfileat(AT_FDCWD, name, ibuf, &len);
 585}
 586
 587// Sleep for this many thousandths of a second
 588void msleep(long milliseconds)
 589{
 590  struct timespec ts;
 591
 592  ts.tv_sec = milliseconds/1000;
 593  ts.tv_nsec = (milliseconds%1000)*1000000;
 594  nanosleep(&ts, &ts);
 595}
 596
 597// Adjust timespec by nanosecond offset
 598void nanomove(struct timespec *ts, long long offset)
 599{
 600  long long nano = ts->tv_nsec + offset, secs = nano/1000000000;
 601
 602  ts->tv_sec += secs;
 603  nano %= 1000000000;
 604  if (nano<0) {
 605    ts->tv_sec--;
 606    nano += 1000000000;
 607  }
 608  ts->tv_nsec = nano;
 609}
 610
 611// return difference between two timespecs in nanosecs
 612long long nanodiff(struct timespec *old, struct timespec *new)
 613{
 614  return (new->tv_sec - old->tv_sec)*1000000000LL+(new->tv_nsec - old->tv_nsec);
 615}
 616
 617// return 1<<x of highest bit set
 618int highest_bit(unsigned long l)
 619{
 620  int i;
 621
 622  for (i = 0; l; i++) l >>= 1;
 623
 624  return i-1;
 625}
 626
 627// Inefficient, but deals with unaligned access
 628int64_t peek_le(void *ptr, unsigned size)
 629{
 630  int64_t ret = 0;
 631  char *c = ptr;
 632  int i;
 633
 634  for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
 635  return ret;
 636}
 637
 638int64_t peek_be(void *ptr, unsigned size)
 639{
 640  int64_t ret = 0;
 641  char *c = ptr;
 642  int i;
 643
 644  for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
 645  return ret;
 646}
 647
 648int64_t peek(void *ptr, unsigned size)
 649{
 650  return (IS_BIG_ENDIAN ? peek_be : peek_le)(ptr, size);
 651}
 652
 653void poke_le(void *ptr, long long val, unsigned size)
 654{
 655  char *c = ptr;
 656
 657  while (size--) {
 658    *c++ = val&255;
 659    val >>= 8;
 660  }
 661}
 662
 663void poke_be(void *ptr, long long val, unsigned size)
 664{
 665  char *c = ptr + size;
 666
 667  while (size--) {
 668    *--c = val&255;
 669    val >>=8;
 670  }
 671}
 672
 673void poke(void *ptr, long long val, unsigned size)
 674{
 675  (IS_BIG_ENDIAN ? poke_be : poke_le)(ptr, val, size);
 676}
 677
 678// Iterate through an array of files, opening each one and calling a function
 679// on that filehandle and name. The special filename "-" means stdin if
 680// flags is O_RDONLY, stdout otherwise. An empty argument list calls
 681// function() on just stdin/stdout.
 682//
 683// Note: pass O_CLOEXEC to automatically close filehandles when function()
 684// returns, otherwise filehandles must be closed by function().
 685// pass WARN_ONLY to produce warning messages about files it couldn't
 686// open/create, and skip them. Otherwise function is called with fd -1.
 687void loopfiles_rw(char **argv, int flags, int permissions,
 688  void (*function)(int fd, char *name))
 689{
 690  int fd, failok = !(flags&WARN_ONLY);
 691
 692  flags &= ~WARN_ONLY;
 693
 694  // If no arguments, read from stdin.
 695  if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
 696  else do {
 697    // Filename "-" means read from stdin.
 698    // Inability to open a file prints a warning, but doesn't exit.
 699
 700    if (!strcmp(*argv, "-")) fd = 0;
 701    else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
 702      perror_msg_raw(*argv);
 703      continue;
 704    }
 705    function(fd, *argv);
 706    if ((flags & O_CLOEXEC) && fd) close(fd);
 707  } while (*++argv);
 708}
 709
 710// Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
 711void loopfiles(char **argv, void (*function)(int fd, char *name))
 712{
 713  loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
 714}
 715
 716// glue to call dl_lines() from loopfiles
 717static void (*do_lines_bridge)(char **pline, long len);
 718static void loopfile_lines_bridge(int fd, char *name)
 719{
 720  do_lines(fd, '\n', do_lines_bridge);
 721}
 722
 723void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
 724{
 725  do_lines_bridge = function;
 726  // No O_CLOEXEC because we need to call fclose.
 727  loopfiles_rw(argv, O_RDONLY|WARN_ONLY, 0, loopfile_lines_bridge);
 728}
 729
 730// Slow, but small.
 731char *get_line(int fd)
 732{
 733  char c, *buf = NULL;
 734  long len = 0;
 735
 736  for (;;) {
 737    if (1>read(fd, &c, 1)) break;
 738    if (!(len & 63)) buf=xrealloc(buf, len+65);
 739    if ((buf[len++]=c) == '\n') break;
 740  }
 741  if (buf) {
 742    buf[len]=0;
 743    if (buf[--len]=='\n') buf[len]=0;
 744  }
 745
 746  return buf;
 747}
 748
 749int wfchmodat(int fd, char *name, mode_t mode)
 750{
 751  int rc = fchmodat(fd, name, mode, 0);
 752
 753  if (rc) {
 754    perror_msg("chmod '%s' to %04o", name, mode);
 755    toys.exitval=1;
 756  }
 757  return rc;
 758}
 759
 760static char *tempfile2zap;
 761static void tempfile_handler(void)
 762{
 763  if (1 < (long)tempfile2zap) unlink(tempfile2zap);
 764}
 765
 766// Open a temporary file to copy an existing file into.
 767int copy_tempfile(int fdin, char *name, char **tempname)
 768{
 769  struct stat statbuf;
 770  int fd = xtempfile(name, tempname), ignored __attribute__((__unused__));
 771
 772  // Record tempfile for exit cleanup if interrupted
 773  if (!tempfile2zap) sigatexit(tempfile_handler);
 774  tempfile2zap = *tempname;
 775
 776  // Set permissions of output file.
 777  if (!fstat(fdin, &statbuf)) fchmod(fd, statbuf.st_mode);
 778
 779  // We chmod before chown, which strips the suid bit. Caller has to explicitly
 780  // switch it back on if they want to keep suid.
 781
 782  // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
 783  // this but it's _supposed_ to fail when we're not root.
 784  ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
 785
 786  return fd;
 787}
 788
 789// Abort the copy and delete the temporary file.
 790void delete_tempfile(int fdin, int fdout, char **tempname)
 791{
 792  close(fdin);
 793  close(fdout);
 794  if (*tempname) unlink(*tempname);
 795  tempfile2zap = (char *)1;
 796  free(*tempname);
 797  *tempname = NULL;
 798}
 799
 800// Copy the rest of the data and replace the original with the copy.
 801void replace_tempfile(int fdin, int fdout, char **tempname)
 802{
 803  char *temp = xstrdup(*tempname);
 804
 805  temp[strlen(temp)-6]=0;
 806  if (fdin != -1) {
 807    xsendfile(fdin, fdout);
 808    xclose(fdin);
 809  }
 810  xclose(fdout);
 811  xrename(*tempname, temp);
 812  tempfile2zap = (char *)1;
 813  free(*tempname);
 814  free(temp);
 815  *tempname = NULL;
 816}
 817
 818// Create a 256 entry CRC32 lookup table.
 819
 820void crc_init(unsigned int *crc_table, int little_endian)
 821{
 822  unsigned int i;
 823
 824  // Init the CRC32 table (big endian)
 825  for (i=0; i<256; i++) {
 826    unsigned int j, c = little_endian ? i : i<<24;
 827    for (j=8; j; j--)
 828      if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
 829      else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
 830    crc_table[i] = c;
 831  }
 832}
 833
 834// Init base64 table
 835
 836void base64_init(char *p)
 837{
 838  int i;
 839
 840  for (i = 'A'; i != ':'; i++) {
 841    if (i == 'Z'+1) i = 'a';
 842    if (i == 'z'+1) i = '0';
 843    *(p++) = i;
 844  }
 845  *(p++) = '+';
 846  *(p++) = '/';
 847}
 848
 849int yesno(int def)
 850{
 851  return fyesno(stdin, def);
 852}
 853
 854int fyesno(FILE *in, int def)
 855{
 856  char buf;
 857
 858  fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
 859  fflush(stderr);
 860  while (fread(&buf, 1, 1, in)) {
 861    int new;
 862
 863    // The letter changes the value, the newline (or space) returns it.
 864    if (isspace(buf)) break;
 865    if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
 866  }
 867
 868  return def;
 869}
 870
 871// Handler that sets toys.signal, and writes to toys.signalfd if set
 872void generic_signal(int sig)
 873{
 874  if (toys.signalfd) {
 875    char c = sig;
 876
 877    writeall(toys.signalfd, &c, 1);
 878  }
 879  toys.signal = sig;
 880}
 881
 882void exit_signal(int sig)
 883{
 884  if (sig) toys.exitval = sig|128;
 885  xexit();
 886}
 887
 888// Install the same handler on every signal that defaults to killing the
 889// process, calling the handler on the way out. Calling multiple times
 890// adds the handlers to a list, to be called in order.
 891void sigatexit(void *handler)
 892{
 893  xsignal_all_killers(handler ? exit_signal : SIG_DFL);
 894
 895  if (handler) {
 896    struct arg_list *al = xmalloc(sizeof(struct arg_list));
 897
 898    al->next = toys.xexit;
 899    al->arg = handler;
 900    toys.xexit = al;
 901  } else {
 902    llist_traverse(toys.xexit, free);
 903    toys.xexit = 0;
 904  }
 905}
 906
 907// Output a nicely formatted 80-column table of all the signals.
 908void list_signals()
 909{
 910  int i = 0, count = 0;
 911  char *name;
 912
 913  for (; i<=NSIG; i++) {
 914    if ((name = num_to_sig(i))) {
 915      printf("%2d) SIG%-9s", i, name);
 916      if (++count % 5 == 0) putchar('\n');
 917    }
 918  }
 919  putchar('\n');
 920}
 921
 922// premute mode bits based on posix mode strings.
 923mode_t string_to_mode(char *modestr, mode_t mode)
 924{
 925  char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
 926       *s, *str = modestr;
 927  mode_t extrabits = mode & ~(07777);
 928
 929  // Handle octal mode
 930  if (isdigit(*str)) {
 931    mode = estrtol(str, &s, 8);
 932    if (errno || *s || (mode & ~(07777))) goto barf;
 933
 934    return mode | extrabits;
 935  }
 936
 937  // Gaze into the bin of permission...
 938  for (;;) {
 939    int i, j, dowho, dohow, dowhat, amask;
 940
 941    dowho = dohow = dowhat = amask = 0;
 942
 943    // Find the who, how, and what stanzas, in that order
 944    while (*str && (s = strchr(whos, *str))) {
 945      dowho |= 1<<(s-whos);
 946      str++;
 947    }
 948    // If who isn't specified, like "a" but honoring umask.
 949    if (!dowho) {
 950      dowho = 8;
 951      umask(amask = umask(0));
 952    }
 953
 954    if (!*str || !(s = strchr(hows, *str))) goto barf;
 955    if (!(dohow = *(str++))) goto barf;
 956
 957    while (*str && (s = strchr(whats, *str))) {
 958      dowhat |= 1<<(s-whats);
 959      str++;
 960    }
 961
 962    // Convert X to x for directory or if already executable somewhere
 963    if ((dowhat&32) &&  (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
 964
 965    // Copy mode from another category?
 966    if (!dowhat && *str && (s = strchr(whys, *str))) {
 967      dowhat = (mode>>(3*(s-whys)))&7;
 968      str++;
 969    }
 970
 971    // Are we ready to do a thing yet?
 972    if (*str && *(str++) != ',') goto barf;
 973
 974    // Loop through what=xwrs and who=ogu to apply bits to the mode.
 975    for (i=0; i<4; i++) {
 976      for (j=0; j<3; j++) {
 977        mode_t bit = 0;
 978        int where = 1<<((3*i)+j);
 979
 980        if (amask & where) continue;
 981
 982        // Figure out new value at this location
 983        if (i == 3) {
 984          // suid and sticky
 985          if (!j) bit = dowhat&16; // o+s = t
 986          else if ((dowhat&8) && (dowho&(8|(1<<j)))) bit++;
 987        } else {
 988          if (!(dowho&(8|(1<<i)))) continue;
 989          else if (dowhat&(1<<j)) bit++;
 990        }
 991
 992        // When selection active, modify bit
 993
 994        if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
 995        if (bit && dohow != '-') mode |= where;
 996      }
 997    }
 998
 999    if (!*str) break;
1000  }
1001
1002  return mode|extrabits;
1003barf:
1004  error_exit("bad mode '%s'", modestr);
1005}
1006
1007// Format access mode into a drwxrwxrwx string
1008void mode_to_string(mode_t mode, char *buf)
1009{
1010  char c, d;
1011  int i, bit;
1012
1013  buf[10]=0;
1014  for (i=0; i<9; i++) {
1015    bit = mode & (1<<i);
1016    c = i%3;
1017    if (!c && (mode & (1<<((d=i/3)+9)))) {
1018      c = "tss"[d];
1019      if (!bit) c &= ~0x20;
1020    } else c = bit ? "xwr"[c] : '-';
1021    buf[9-i] = c;
1022  }
1023
1024  if (S_ISDIR(mode)) c = 'd';
1025  else if (S_ISBLK(mode)) c = 'b';
1026  else if (S_ISCHR(mode)) c = 'c';
1027  else if (S_ISLNK(mode)) c = 'l';
1028  else if (S_ISFIFO(mode)) c = 'p';
1029  else if (S_ISSOCK(mode)) c = 's';
1030  else c = '-';
1031  *buf = c;
1032}
1033
1034// basename() can modify its argument or return a pointer to a constant string
1035// This just gives after the last '/' or the whole stirng if no /
1036char *getbasename(char *name)
1037{
1038  char *s = strrchr(name, '/');
1039
1040  if (s) return s+1;
1041
1042  return name;
1043}
1044
1045// Return pointer to xabspath(file) if file is under dir, else 0
1046char *fileunderdir(char *file, char *dir)
1047{
1048  char *s1 = xabspath(dir, 1), *s2 = xabspath(file, -1), *ss = s2;
1049  int rc = s1 && s2 && strstart(&ss, s1) && (!s1[1] || s2[strlen(s1)] == '/');
1050
1051  free(s1);
1052  if (!rc) free(s2);
1053
1054  return rc ? s2 : 0;
1055}
1056
1057// return (malloced) relative path to get from "from" to "to"
1058char *relative_path(char *from, char *to)
1059{
1060  char *s, *ret = 0;
1061  int i, j, k;
1062
1063  if (!(from = xabspath(from, -1))) return 0;
1064  if (!(to = xabspath(to, -1))) goto error;
1065
1066  // skip common directories from root
1067  for (i = j = 0; from[i] && from[i] == to[i]; i++) if (to[i] == '/') j = i+1;
1068
1069  // count remaining destination directories
1070  for (i = j, k = 0; from[i]; i++) if (from[i] == '/') k++;
1071
1072  if (!k) ret = xstrdup(to+j);
1073  else {
1074    s = ret = xmprintf("%*c%s", 3*k, ' ', to+j);
1075    while (k--) memcpy(s+3*k, "../", 3);
1076  }
1077
1078error:
1079  free(from);
1080  free(to);
1081
1082  return ret;
1083}
1084
1085// Execute a callback for each PID that matches a process name from a list.
1086void names_to_pid(char **names, int (*callback)(pid_t pid, char *name),
1087    int scripts)
1088{
1089  DIR *dp;
1090  struct dirent *entry;
1091
1092  if (!(dp = opendir("/proc"))) perror_exit("no /proc");
1093
1094  while ((entry = readdir(dp))) {
1095    unsigned u = atoi(entry->d_name);
1096    char *cmd = 0, *comm = 0, **cur;
1097    off_t len;
1098
1099    if (!u) continue;
1100
1101    // Comm is original name of executable (argv[0] could be #! interpreter)
1102    // but it's limited to 15 characters
1103    if (scripts) {
1104      sprintf(libbuf, "/proc/%u/comm", u);
1105      len = sizeof(libbuf);
1106      if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
1107        continue;
1108      if (libbuf[len-1] == '\n') libbuf[--len] = 0;
1109    }
1110
1111    for (cur = names; *cur; cur++) {
1112      struct stat st1, st2;
1113      char *bb = getbasename(*cur);
1114      off_t len = strlen(bb);
1115
1116      // Fast path: only matching a filename (no path) that fits in comm.
1117      // `len` must be 14 or less because with a full 15 bytes we don't
1118      // know whether the name fit or was truncated.
1119      if (scripts && len<=14 && bb==*cur && !strcmp(comm, bb)) goto match;
1120
1121      // If we have a path to existing file only match if same inode
1122      if (bb!=*cur && !stat(*cur, &st1)) {
1123        char buf[32];
1124
1125        sprintf(buf, "/proc/%u/exe", u);
1126        if (stat(buf, &st2)) continue;
1127        if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) continue;
1128        goto match;
1129      }
1130
1131      // Nope, gotta read command line to confirm
1132      if (!cmd) {
1133        sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1134        len = sizeof(libbuf)-17;
1135        if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1136        // readfile only guarantees one null terminator and we need two
1137        // (yes the kernel should do this for us, don't care)
1138        cmd[len] = 0;
1139      }
1140      if (!strcmp(bb, getbasename(cmd))) goto match;
1141      if (scripts && !strcmp(bb, getbasename(cmd+strlen(cmd)+1))) goto match;
1142      continue;
1143match:
1144      if (callback(u, *cur)) break;
1145    }
1146  }
1147  closedir(dp);
1148}
1149
1150// display first "dgt" many digits of number plus unit (kilo-exabytes)
1151int human_readable_long(char *buf, unsigned long long num, int dgt, int style)
1152{
1153  unsigned long long snap = 0;
1154  int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
1155
1156  // Divide rounding up until we have 3 or fewer digits. Since the part we
1157  // print is decimal, the test is 999 even when we divide by 1024.
1158  // We can't run out of units because 1<<64 is 18 exabytes.
1159  for (unit = 0; snprintf(0, 0, "%llu", num)>dgt; unit++)
1160    num = ((snap = num)+(divisor/2))/divisor;
1161  len = sprintf(buf, "%llu", num);
1162  if (unit && len == 1) {
1163    // Redo rounding for 1.2M case, this works with and without HR_1000.
1164    num = snap/divisor;
1165    snap -= num*divisor;
1166    snap = ((snap*100)+50)/divisor;
1167    snap /= 10;
1168    len = sprintf(buf, "%llu.%llu", num, snap);
1169  }
1170  if (style & HR_SPACE) buf[len++] = ' ';
1171  if (unit) {
1172    unit = " kMGTPE"[unit];
1173
1174    if (!(style&HR_1000)) unit = toupper(unit);
1175    buf[len++] = unit;
1176  } else if (style & HR_B) buf[len++] = 'B';
1177  buf[len] = 0;
1178
1179  return len;
1180}
1181
1182// Give 3 digit estimate + units ala 999M or 1.7T
1183int human_readable(char *buf, unsigned long long num, int style)
1184{
1185  return human_readable_long(buf, num, 3, style);
1186}
1187
1188// The qsort man page says you can use alphasort, the posix committee
1189// disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1190// So just do our own. (The const is entirely to humor the stupid compiler.)
1191int qstrcmp(const void *a, const void *b)
1192{
1193  return strcmp(*(char **)a, *(char **)b);
1194}
1195
1196// See https://tools.ietf.org/html/rfc4122, specifically section 4.4
1197// "Algorithms for Creating a UUID from Truly Random or Pseudo-Random
1198// Numbers".
1199void create_uuid(char *uuid)
1200{
1201  // "Set all the ... bits to randomly (or pseudo-randomly) chosen values".
1202  xgetrandom(uuid, 16, 0);
1203
1204  // "Set the four most significant bits ... of the time_hi_and_version
1205  // field to the 4-bit version number [4]".
1206  uuid[6] = (uuid[6] & 0x0F) | 0x40;
1207  // "Set the two most significant bits (bits 6 and 7) of
1208  // clock_seq_hi_and_reserved to zero and one, respectively".
1209  uuid[8] = (uuid[8] & 0x3F) | 0x80;
1210}
1211
1212char *show_uuid(char *uuid)
1213{
1214  char *out = libbuf;
1215  int i;
1216
1217  for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1218  *out = 0;
1219
1220  return libbuf;
1221}
1222
1223// Returns pointer to letter at end, 0 if none. *start = initial %
1224char *next_printf(char *s, char **start)
1225{
1226  for (; *s; s++) {
1227    if (*s != '%') continue;
1228    if (*++s == '%') continue;
1229    if (start) *start = s-1;
1230    while (0 <= stridx("0'#-+ ", *s)) s++;
1231    while (isdigit(*s)) s++;
1232    if (*s == '.') s++;
1233    while (isdigit(*s)) s++;
1234
1235    return s;
1236  }
1237
1238  return 0;
1239}
1240
1241// Return cached passwd entries.
1242struct passwd *bufgetpwuid(uid_t uid)
1243{
1244  struct pwuidbuf_list {
1245    struct pwuidbuf_list *next;
1246    struct passwd pw;
1247  } *list = 0;
1248  struct passwd *temp;
1249  static struct pwuidbuf_list *pwuidbuf;
1250  unsigned size = 256;
1251
1252  // If we already have this one, return it.
1253  for (list = pwuidbuf; list; list = list->next)
1254    if (list->pw.pw_uid == uid) return &(list->pw);
1255
1256  for (;;) {
1257    list = xrealloc(list, size *= 2);
1258    errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1259      size-sizeof(*list), &temp);
1260    if (errno != ERANGE) break;
1261  }
1262
1263  if (!temp) {
1264    free(list);
1265
1266    return 0;
1267  }
1268  list->next = pwuidbuf;
1269  pwuidbuf = list;
1270
1271  return &list->pw;
1272}
1273
1274// Return cached group entries.
1275struct group *bufgetgrgid(gid_t gid)
1276{
1277  struct grgidbuf_list {
1278    struct grgidbuf_list *next;
1279    struct group gr;
1280  } *list = 0;
1281  struct group *temp;
1282  static struct grgidbuf_list *grgidbuf;
1283  unsigned size = 256;
1284
1285  for (list = grgidbuf; list; list = list->next)
1286    if (list->gr.gr_gid == gid) return &(list->gr);
1287
1288  for (;;) {
1289    list = xrealloc(list, size *= 2);
1290    errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1291      size-sizeof(*list), &temp);
1292    if (errno != ERANGE) break;
1293  }
1294  if (!temp) {
1295    free(list);
1296
1297    return 0;
1298  }
1299  list->next = grgidbuf;
1300  grgidbuf = list;
1301
1302  return &list->gr;
1303}
1304
1305// Always null terminates, returns 0 for failure, len for success
1306int readlinkat0(int dirfd, char *path, char *buf, int len)
1307{
1308  if (!len) return 0;
1309
1310  len = readlinkat(dirfd, path, buf, len-1);
1311  if (len<0) len = 0;
1312  buf[len] = 0;
1313
1314  return len;
1315}
1316
1317int readlink0(char *path, char *buf, int len)
1318{
1319  return readlinkat0(AT_FDCWD, path, buf, len);
1320}
1321
1322// Do regex matching with len argument to handle embedded NUL bytes in string
1323int regexec0(regex_t *preg, char *string, long len, int nmatch,
1324  regmatch_t *pmatch, int eflags)
1325{
1326  regmatch_t backup;
1327
1328  if (!nmatch) pmatch = &backup;
1329  pmatch->rm_so = 0;
1330  pmatch->rm_eo = len;
1331  return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
1332}
1333
1334// Return user name or string representation of number, returned buffer
1335// lasts until next call.
1336char *getusername(uid_t uid)
1337{
1338  struct passwd *pw = bufgetpwuid(uid);
1339  static char unum[12];
1340
1341  sprintf(unum, "%u", (unsigned)uid);
1342  return pw ? pw->pw_name : unum;
1343}
1344
1345// Return group name or string representation of number, returned buffer
1346// lasts until next call.
1347char *getgroupname(gid_t gid)
1348{
1349  struct group *gr = bufgetgrgid(gid);
1350  static char gnum[12];
1351
1352  sprintf(gnum, "%u", (unsigned)gid);
1353  return gr ? gr->gr_name : gnum;
1354}
1355
1356// Iterate over lines in file, calling function. Function can write 0 to
1357// the line pointer if they want to keep it, or 1 to terminate processing,
1358// otherwise line is freed. Passed file descriptor is closed at the end.
1359// At EOF calls function(0, 0)
1360void do_lines(int fd, char delim, void (*call)(char **pline, long len))
1361{
1362  FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1363
1364  for (;;) {
1365    char *line = 0;
1366    ssize_t len;
1367
1368    len = getdelim(&line, (void *)&len, delim, fp);
1369    if (len > 0) {
1370      call(&line, len);
1371      if (line == (void *)1) break;
1372      free(line);
1373    } else break;
1374  }
1375  call(0, 0);
1376
1377  if (fd) fclose(fp);
1378}
1379
1380// Return unix time in milliseconds
1381long long millitime(void)
1382{
1383  struct timespec ts;
1384
1385  clock_gettime(CLOCK_MONOTONIC, &ts);
1386  return ts.tv_sec*1000+ts.tv_nsec/1000000;
1387}
1388
1389// Formats `ts` in ISO format ("2018-06-28 15:08:58.846386216 -0700").
1390char *format_iso_time(char *buf, size_t len, struct timespec *ts)
1391{
1392  char *s = buf;
1393
1394  s += strftime(s, len, "%F %T", localtime(&(ts->tv_sec)));
1395  s += sprintf(s, ".%09ld ", ts->tv_nsec);
1396  s += strftime(s, len-strlen(buf), "%z", localtime(&(ts->tv_sec)));
1397
1398  return buf;
1399}
1400
1401// Syslog with the openlog/closelog, autodetecting daemon status via no tty
1402
1403void loggit(int priority, char *format, ...)
1404{
1405  int i, facility = LOG_DAEMON;
1406  va_list va;
1407
1408  for (i = 0; i<3; i++) if (isatty(i)) facility = LOG_AUTH;
1409  openlog(toys.which->name, LOG_PID, facility);
1410  va_start(va, format);
1411  vsyslog(priority, format, va);
1412  va_end(va);
1413  closelog();
1414}
1415
1416// Calculate tar packet checksum, with cksum field treated as 8 spaces
1417unsigned tar_cksum(void *data)
1418{
1419  unsigned i, cksum = 8*' ';
1420
1421  for (i = 0; i<500; i += (i==147) ? 9 : 1) cksum += ((char *)data)[i];
1422
1423  return cksum;
1424}
1425
1426// is this a valid tar header?
1427int is_tar_header(void *pkt)
1428{
1429  char *p = pkt;
1430  int i = 0;
1431
1432  if (p[257] && memcmp("ustar", p+257, 5)) return 0;
1433  if (p[148] != '0' && p[148] != ' ') return 0;
1434  sscanf(p+148, "%8o", &i);
1435
1436  return i && tar_cksum(pkt) == i;
1437}
1438
1439char *elf_arch_name(int type)
1440{
1441  int i;
1442  // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
1443  // Names are linux/arch/ directory (sometimes before 32/64 bit merges)
1444  struct {int val; char *name;} types[] = {{0x9026, "alpha"}, {93, "arc"},
1445    {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
1446    {247, "bpf"}, {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
1447    {252, "csky"}, {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"},
1448    {50, "ia64"}, {88, "m32r"}, {0x9041, "m32r"}, {4, "m68k"}, {174, "metag"},
1449    {189, "microblaze"}, {0xbaab, "microblaze-old"}, {8, "mips"},
1450    {10, "mips-old"}, {89, "mn10300"}, {0xbeef, "mn10300-old"}, {113, "nios2"},
1451    {92, "openrisc"}, {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"},
1452    {21, "ppc64"}, {243, "riscv"}, {22, "s390"}, {0xa390, "s390-old"},
1453    {135, "score"}, {42, "sh"}, {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"},
1454    {188, "tile"}, {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"},
1455    {94, "xtensa"}, {0xabc7, "xtensa-old"}
1456  };
1457
1458  for (i = 0; i<ARRAY_LEN(types); i++) {
1459    if (type==types[i].val) return types[i].name;
1460  }
1461  sprintf(libbuf, "unknown arch %d", type);
1462  return libbuf;
1463}
1464