toybox/lib/xwrap.c
<<
>>
Prefs
   1/* xwrap.c - wrappers around existing library functions.
   2 *
   3 * Functions with the x prefix are wrappers that either succeed or kill the
   4 * program with an error message, but never return failure. They usually have
   5 * the same arguments and return value as the function they wrap.
   6 *
   7 * Copyright 2006 Rob Landley <rob@landley.net>
   8 */
   9
  10#include "toys.h"
  11
  12// strcpy and strncat with size checking. Size is the total space in "dest",
  13// including null terminator. Exit if there's not enough space for the string
  14// (including space for the null terminator), because silently truncating is
  15// still broken behavior. (And leaving the string unterminated is INSANE.)
  16void xstrncpy(char *dest, char *src, size_t size)
  17{
  18  if (strlen(src)+1 > size) error_exit("'%s' > %ld bytes", src, (long)size);
  19  strcpy(dest, src);
  20}
  21
  22void xstrncat(char *dest, char *src, size_t size)
  23{
  24  long len = strlen(dest);
  25
  26  if (len+strlen(src)+1 > size)
  27    error_exit("'%s%s' > %ld bytes", dest, src, (long)size);
  28  strcpy(dest+len, src);
  29}
  30
  31// We replaced exit(), _exit(), and atexit() with xexit(), _xexit(), and
  32// sigatexit(). This gives _xexit() the option to siglongjmp(toys.rebound, 1)
  33// instead of exiting, lets xexit() report stdout flush failures to stderr
  34// and change the exit code to indicate error, lets our toys.exit function
  35// change happen for signal exit paths and lets us remove the functions
  36// after we've called them.
  37
  38void _xexit(void)
  39{
  40  if (toys.rebound) siglongjmp(*toys.rebound, 1);
  41
  42  _exit(toys.exitval);
  43}
  44
  45void xexit(void)
  46{
  47  // Call toys.xexit functions in reverse order added.
  48  while (toys.xexit) {
  49    // This is typecasting xexit->arg to a function pointer,then calling it.
  50    // Using the invalid signal number 0 lets the signal handlers distinguish
  51    // an actual signal from a regular exit.
  52    ((void (*)(int))(toys.xexit->arg))(0);
  53
  54    free(llist_pop(&toys.xexit));
  55  }
  56  if (fflush(NULL) || ferror(stdout))
  57    if (!toys.exitval) perror_msg("write");
  58  _xexit();
  59}
  60
  61void *xmmap(void *addr, size_t length, int prot, int flags, int fd, off_t off)
  62{
  63  void *ret = mmap(addr, length, prot, flags, fd, off);
  64  if (ret == MAP_FAILED) perror_exit("mmap");
  65  return ret;
  66}
  67
  68// Die unless we can allocate memory.
  69void *xmalloc(size_t size)
  70{
  71  void *ret = malloc(size);
  72  if (!ret) error_exit("xmalloc(%ld)", (long)size);
  73
  74  return ret;
  75}
  76
  77// Die unless we can allocate prezeroed memory.
  78void *xzalloc(size_t size)
  79{
  80  void *ret = xmalloc(size);
  81  memset(ret, 0, size);
  82  return ret;
  83}
  84
  85// Die unless we can change the size of an existing allocation, possibly
  86// moving it.  (Notice different arguments from libc function.)
  87void *xrealloc(void *ptr, size_t size)
  88{
  89  ptr = realloc(ptr, size);
  90  if (!ptr) error_exit("xrealloc");
  91
  92  return ptr;
  93}
  94
  95// Die unless we can allocate a copy of this many bytes of string.
  96char *xstrndup(char *s, size_t n)
  97{
  98  char *ret = strndup(s, ++n);
  99
 100  if (!ret) error_exit("xstrndup");
 101  ret[--n] = 0;
 102
 103  return ret;
 104}
 105
 106// Die unless we can allocate a copy of this string.
 107char *xstrdup(char *s)
 108{
 109  return xstrndup(s, strlen(s));
 110}
 111
 112void *xmemdup(void *s, long len)
 113{
 114  void *ret = xmalloc(len);
 115  memcpy(ret, s, len);
 116
 117  return ret;
 118}
 119
 120// Die unless we can allocate enough space to sprintf() into.
 121char *xmprintf(char *format, ...)
 122{
 123  va_list va, va2;
 124  int len;
 125  char *ret;
 126
 127  va_start(va, format);
 128  va_copy(va2, va);
 129
 130  // How long is it?
 131  len = vsnprintf(0, 0, format, va);
 132  len++;
 133  va_end(va);
 134
 135  // Allocate and do the sprintf()
 136  ret = xmalloc(len);
 137  vsnprintf(ret, len, format, va2);
 138  va_end(va2);
 139
 140  return ret;
 141}
 142
 143void xprintf(char *format, ...)
 144{
 145  va_list va;
 146  va_start(va, format);
 147
 148  vprintf(format, va);
 149  va_end(va);
 150  if (fflush(stdout) || ferror(stdout)) perror_exit("write");
 151}
 152
 153void xputs(char *s)
 154{
 155  if (EOF == puts(s) || fflush(stdout) || ferror(stdout)) perror_exit("write");
 156}
 157
 158void xputc(char c)
 159{
 160  if (EOF == fputc(c, stdout) || fflush(stdout) || ferror(stdout))
 161    perror_exit("write");
 162}
 163
 164void xflush(void)
 165{
 166  if (fflush(stdout) || ferror(stdout)) perror_exit("write");;
 167}
 168
 169// This is called through the XVFORK macro because parent/child of vfork
 170// share a stack, so child returning from a function would stomp the return
 171// address parent would need. Solution: make vfork() an argument so processes
 172// diverge before function gets called.
 173pid_t __attribute__((returns_twice)) xvforkwrap(pid_t pid)
 174{
 175  if (pid == -1) perror_exit("vfork");
 176
 177  // Signal to xexec() and friends that we vforked so can't recurse
 178  toys.stacktop = 0;
 179
 180  return pid;
 181}
 182
 183// Die unless we can exec argv[] (or run builtin command).  Note that anything
 184// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
 185void xexec(char **argv)
 186{
 187  // Only recurse to builtin when we have multiplexer and !vfork context.
 188  if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE && toys.stacktop) toy_exec(argv);
 189  execvp(argv[0], argv);
 190
 191  perror_msg("exec %s", argv[0]);
 192  toys.exitval = 127;
 193  if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
 194  xexit();
 195}
 196
 197// Spawn child process, capturing stdin/stdout.
 198// argv[]: command to exec. If null, child re-runs original program with
 199//         toys.stacktop zeroed.
 200// pipes[2]: stdin, stdout of new process, only allocated if zero on way in,
 201//           pass NULL to skip pipe allocation entirely.
 202// return: pid of child process
 203pid_t xpopen_both(char **argv, int *pipes)
 204{
 205  int cestnepasun[4], pid;
 206
 207  // Make the pipes? Note this won't set either pipe to 0 because if fds are
 208  // allocated in order and if fd0 was free it would go to cestnepasun[0]
 209  if (pipes) {
 210    for (pid = 0; pid < 2; pid++) {
 211      if (pipes[pid] != 0) continue;
 212      if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
 213      pipes[pid] = cestnepasun[pid+1];
 214    }
 215  }
 216
 217  // Child process.
 218  if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
 219    // Dance of the stdin/stdout redirection.
 220    if (pipes) {
 221      // if we had no stdin/out, pipe handles could overlap, so test for it
 222      // and free up potentially overlapping pipe handles before reuse
 223      if (pipes[1] != -1) close(cestnepasun[2]);
 224      if (pipes[0] != -1) {
 225        close(cestnepasun[1]);
 226        if (cestnepasun[0]) {
 227          dup2(cestnepasun[0], 0);
 228          close(cestnepasun[0]);
 229        }
 230      }
 231      if (pipes[1] != -1) {
 232        dup2(cestnepasun[3], 1);
 233        dup2(cestnepasun[3], 2);
 234        if (cestnepasun[3] > 2 || !cestnepasun[3]) close(cestnepasun[3]);
 235      }
 236    }
 237    if (argv) xexec(argv);
 238
 239    // In fork() case, force recursion because we know it's us.
 240    if (CFG_TOYBOX_FORK) {
 241      toy_init(toys.which, toys.argv);
 242      toys.stacktop = 0;
 243      toys.which->toy_main();
 244      xexit();
 245    // In vfork() case, exec /proc/self/exe with high bit of first letter set
 246    // to tell main() we reentered.
 247    } else {
 248      char *s = "/proc/self/exe";
 249
 250      // We did a nommu-friendly vfork but must exec to continue.
 251      // setting high bit of argv[0][0] to let new process know
 252      **toys.argv |= 0x80;
 253      execv(s, toys.argv);
 254      perror_msg_raw(s);
 255
 256      _exit(127);
 257    }
 258  }
 259
 260  // Parent process
 261  if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
 262  if (pipes) {
 263    if (pipes[0] != -1) close(cestnepasun[0]);
 264    if (pipes[1] != -1) close(cestnepasun[3]);
 265  }
 266
 267  return pid;
 268}
 269
 270// Wait for child process to exit, then return adjusted exit code.
 271int xwaitpid(pid_t pid)
 272{
 273  int status;
 274
 275  while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
 276
 277  return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+127;
 278}
 279
 280int xpclose_both(pid_t pid, int *pipes)
 281{
 282  if (pipes) {
 283    close(pipes[0]);
 284    close(pipes[1]);
 285  }
 286
 287  return xwaitpid(pid);
 288}
 289
 290// Wrapper to xpopen with a pipe for just one of stdin/stdout
 291pid_t xpopen(char **argv, int *pipe, int isstdout)
 292{
 293  int pipes[2], pid;
 294
 295  pipes[!isstdout] = -1;
 296  pipes[!!isstdout] = 0;
 297  pid = xpopen_both(argv, pipes);
 298  *pipe = pid ? pipes[!!isstdout] : -1;
 299
 300  return pid;
 301}
 302
 303int xpclose(pid_t pid, int pipe)
 304{
 305  close(pipe);
 306
 307  return xpclose_both(pid, 0);
 308}
 309
 310// Call xpopen and wait for it to finish, keeping existing stdin/stdout.
 311int xrun(char **argv)
 312{
 313  return xpclose_both(xpopen_both(argv, 0), 0);
 314}
 315
 316void xaccess(char *path, int flags)
 317{
 318  if (access(path, flags)) perror_exit("Can't access '%s'", path);
 319}
 320
 321// Die unless we can delete a file.  (File must exist to be deleted.)
 322void xunlink(char *path)
 323{
 324  if (unlink(path)) perror_exit("unlink '%s'", path);
 325}
 326
 327// Die unless we can open/create a file, returning file descriptor.
 328// The meaning of O_CLOEXEC is reversed (it defaults on, pass it to disable)
 329// and WARN_ONLY tells us not to exit.
 330int xcreate_stdio(char *path, int flags, int mode)
 331{
 332  int fd = open(path, (flags^O_CLOEXEC)&~WARN_ONLY, mode);
 333
 334  if (fd == -1) ((mode&WARN_ONLY) ? perror_msg_raw : perror_exit_raw)(path);
 335  return fd;
 336}
 337
 338// Die unless we can open a file, returning file descriptor.
 339int xopen_stdio(char *path, int flags)
 340{
 341  return xcreate_stdio(path, flags, 0);
 342}
 343
 344void xpipe(int *pp)
 345{
 346  if (pipe(pp)) perror_exit("xpipe");
 347}
 348
 349void xclose(int fd)
 350{
 351  if (close(fd)) perror_exit("xclose");
 352}
 353
 354int xdup(int fd)
 355{
 356  if (fd != -1) {
 357    fd = dup(fd);
 358    if (fd == -1) perror_exit("xdup");
 359  }
 360  return fd;
 361}
 362
 363// Move file descriptor above stdin/stdout/stderr, using /dev/null to consume
 364// old one. (We should never be called with stdin/stdout/stderr closed, but...)
 365int notstdio(int fd)
 366{
 367  if (fd<0) return fd;
 368
 369  while (fd<3) {
 370    int fd2 = xdup(fd);
 371
 372    close(fd);
 373    xopen_stdio("/dev/null", O_RDWR);
 374    fd = fd2;
 375  }
 376
 377  return fd;
 378}
 379
 380int xtempfile(char *name, char **tempname)
 381{
 382  int fd;
 383
 384   *tempname = xmprintf("%s%s", name, "XXXXXX");
 385  if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
 386
 387  return fd;
 388}
 389
 390// Create a file but don't return stdin/stdout/stderr
 391int xcreate(char *path, int flags, int mode)
 392{
 393  return notstdio(xcreate_stdio(path, flags, mode));
 394}
 395
 396// Open a file descriptor NOT in stdin/stdout/stderr
 397int xopen(char *path, int flags)
 398{
 399  return notstdio(xopen_stdio(path, flags));
 400}
 401
 402// Open read only, treating "-" as a synonym for stdin, defaulting to warn only
 403int openro(char *path, int flags)
 404{
 405  if (!strcmp(path, "-")) return 0;
 406
 407  return xopen(path, flags^WARN_ONLY);
 408}
 409
 410// Open read only, treating "-" as a synonym for stdin.
 411int xopenro(char *path)
 412{
 413  return openro(path, O_RDONLY|WARN_ONLY);
 414}
 415
 416FILE *xfdopen(int fd, char *mode)
 417{
 418  FILE *f = fdopen(fd, mode);
 419
 420  if (!f) perror_exit("xfdopen");
 421
 422  return f;
 423}
 424
 425// Die unless we can open/create a file, returning FILE *.
 426FILE *xfopen(char *path, char *mode)
 427{
 428  FILE *f = fopen(path, mode);
 429  if (!f) perror_exit("No file %s", path);
 430  return f;
 431}
 432
 433// Die if there's an error other than EOF.
 434size_t xread(int fd, void *buf, size_t len)
 435{
 436  ssize_t ret = read(fd, buf, len);
 437  if (ret < 0) perror_exit("xread");
 438
 439  return ret;
 440}
 441
 442void xreadall(int fd, void *buf, size_t len)
 443{
 444  if (len != readall(fd, buf, len)) perror_exit("xreadall");
 445}
 446
 447// There's no xwriteall(), just xwrite().  When we read, there may or may not
 448// be more data waiting.  When we write, there is data and it had better go
 449// somewhere.
 450
 451void xwrite(int fd, void *buf, size_t len)
 452{
 453  if (len != writeall(fd, buf, len)) perror_exit("xwrite");
 454}
 455
 456// Die if lseek fails, probably due to being called on a pipe.
 457
 458off_t xlseek(int fd, off_t offset, int whence)
 459{
 460  offset = lseek(fd, offset, whence);
 461  if (offset<0) perror_exit("lseek");
 462
 463  return offset;
 464}
 465
 466char *xgetcwd(void)
 467{
 468  char *buf = getcwd(NULL, 0);
 469  if (!buf) perror_exit("xgetcwd");
 470
 471  return buf;
 472}
 473
 474void xstat(char *path, struct stat *st)
 475{
 476  if(stat(path, st)) perror_exit("Can't stat %s", path);
 477}
 478
 479// Cannonicalize path, even to file with one or more missing components at end.
 480// if exact, require last path component to exist
 481char *xabspath(char *path, int exact)
 482{
 483  struct string_list *todo, *done = 0;
 484  int try = 9999, dirfd = open("/", 0), missing = 0;
 485  char *ret;
 486
 487  // If this isn't an absolute path, start with cwd.
 488  if (*path != '/') {
 489    char *temp = xgetcwd();
 490
 491    splitpath(path, splitpath(temp, &todo));
 492    free(temp);
 493  } else splitpath(path, &todo);
 494
 495  // Iterate through path components in todo, prepend processed ones to done.
 496  while (todo) {
 497    struct string_list *new = llist_pop(&todo), **tail;
 498    ssize_t len;
 499
 500    // Eventually break out of endless loops
 501    if (!try--) {
 502      errno = ELOOP;
 503      goto error;
 504    }
 505
 506    // Removable path componenents.
 507    if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
 508      int x = new->str[1];
 509
 510      free(new);
 511      if (!x) continue;
 512      if (done) free(llist_pop(&done));
 513      len = 0;
 514
 515      if (missing) missing--;
 516      else {
 517        if (-1 == (x = openat(dirfd, "..", 0))) goto error;
 518        close(dirfd);
 519        dirfd = x;
 520      }
 521      continue;
 522    }
 523
 524    // Is this a symlink?
 525    len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
 526    if (len>4095) goto error;
 527
 528    // Not a symlink: add to linked list, move dirfd, fail if error
 529    if (len<1) {
 530      int fd;
 531
 532      new->next = done;
 533      done = new;
 534      if (errno == EINVAL && !todo) break;
 535      if (errno == ENOENT && exact<0) {
 536        missing++;
 537        continue;
 538      }
 539      if (errno != EINVAL && (exact || todo)) goto error;
 540
 541      fd = openat(dirfd, new->str, 0);
 542      if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
 543      close(dirfd);
 544      dirfd = fd;
 545      continue;
 546    }
 547
 548    // If this symlink is to an absolute path, discard existing resolved path
 549    libbuf[len] = 0;
 550    if (*libbuf == '/') {
 551      llist_traverse(done, free);
 552      done=0;
 553      close(dirfd);
 554      dirfd = open("/", 0);
 555    }
 556    free(new);
 557
 558    // prepend components of new path. Note symlink to "/" will leave new NULL
 559    tail = splitpath(libbuf, &new);
 560
 561    // symlink to "/" will return null and leave tail alone
 562    if (new) {
 563      *tail = todo;
 564      todo = new;
 565    }
 566  }
 567  close(dirfd);
 568
 569  // At this point done has the path, in reverse order. Reverse list while
 570  // calculating buffer length.
 571
 572  try = 2;
 573  while (done) {
 574    struct string_list *temp = llist_pop(&done);;
 575
 576    if (todo) try++;
 577    try += strlen(temp->str);
 578    temp->next = todo;
 579    todo = temp;
 580  }
 581
 582  // Assemble return buffer
 583
 584  ret = xmalloc(try);
 585  *ret = '/';
 586  ret [try = 1] = 0;
 587  while (todo) {
 588    if (try>1) ret[try++] = '/';
 589    try = stpcpy(ret+try, todo->str) - ret;
 590    free(llist_pop(&todo));
 591  }
 592
 593  return ret;
 594
 595error:
 596  close(dirfd);
 597  llist_traverse(todo, free);
 598  llist_traverse(done, free);
 599
 600  return 0;
 601}
 602
 603void xchdir(char *path)
 604{
 605  if (chdir(path)) error_exit("chdir '%s'", path);
 606}
 607
 608void xchroot(char *path)
 609{
 610  if (chroot(path)) error_exit("chroot '%s'", path);
 611  xchdir("/");
 612}
 613
 614struct passwd *xgetpwuid(uid_t uid)
 615{
 616  struct passwd *pwd = getpwuid(uid);
 617  if (!pwd) error_exit("bad uid %ld", (long)uid);
 618  return pwd;
 619}
 620
 621struct group *xgetgrgid(gid_t gid)
 622{
 623  struct group *group = getgrgid(gid);
 624
 625  if (!group) perror_exit("gid %ld", (long)gid);
 626  return group;
 627}
 628
 629unsigned xgetuid(char *name)
 630{
 631  struct passwd *up = getpwnam(name);
 632  char *s = 0;
 633  long uid;
 634
 635  if (up) return up->pw_uid;
 636
 637  uid = estrtol(name, &s, 10);
 638  if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
 639
 640  error_exit("bad user '%s'", name);
 641}
 642
 643unsigned xgetgid(char *name)
 644{
 645  struct group *gr = getgrnam(name);
 646  char *s = 0;
 647  long gid;
 648
 649  if (gr) return gr->gr_gid;
 650
 651  gid = estrtol(name, &s, 10);
 652  if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
 653
 654  error_exit("bad group '%s'", name);
 655}
 656
 657struct passwd *xgetpwnam(char *name)
 658{
 659  struct passwd *up = getpwnam(name);
 660
 661  if (!up) perror_exit("user '%s'", name);
 662  return up;
 663}
 664
 665struct group *xgetgrnam(char *name)
 666{
 667  struct group *gr = getgrnam(name);
 668
 669  if (!gr) perror_exit("group '%s'", name);
 670  return gr;
 671}
 672
 673// setuid() can fail (for example, too many processes belonging to that user),
 674// which opens a security hole if the process continues as the original user.
 675
 676void xsetuser(struct passwd *pwd)
 677{
 678  if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
 679      || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
 680}
 681
 682// This can return null (meaning file not found).  It just won't return null
 683// for memory allocation reasons.
 684char *xreadlink(char *name)
 685{
 686  int len, size = 0;
 687  char *buf = 0;
 688
 689  // Grow by 64 byte chunks until it's big enough.
 690  for(;;) {
 691    size +=64;
 692    buf = xrealloc(buf, size);
 693    len = readlink(name, buf, size);
 694
 695    if (len<0) {
 696      free(buf);
 697      return 0;
 698    }
 699    if (len<size) {
 700      buf[len]=0;
 701      return buf;
 702    }
 703  }
 704}
 705
 706char *xreadfile(char *name, char *buf, off_t len)
 707{
 708  if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
 709
 710  return buf;
 711}
 712
 713// The data argument to ioctl() is actually long, but it's usually used as
 714// a pointer. If you need to feed in a number, do (void *)(long) typecast.
 715int xioctl(int fd, int request, void *data)
 716{
 717  int rc;
 718
 719  errno = 0;
 720  rc = ioctl(fd, request, data);
 721  if (rc == -1 && errno) perror_exit("ioctl %x", request);
 722
 723  return rc;
 724}
 725
 726// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
 727// exists and is this executable.
 728void xpidfile(char *name)
 729{
 730  char pidfile[256], spid[32];
 731  int i, fd;
 732  pid_t pid;
 733
 734  sprintf(pidfile, "/var/run/%s.pid", name);
 735  // Try three times to open the sucker.
 736  for (i=0; i<3; i++) {
 737    fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
 738    if (fd != -1) break;
 739
 740    // If it already existed, read it.  Loop for race condition.
 741    fd = open(pidfile, O_RDONLY);
 742    if (fd == -1) continue;
 743
 744    // Is the old program still there?
 745    spid[xread(fd, spid, sizeof(spid)-1)] = 0;
 746    close(fd);
 747    pid = atoi(spid);
 748    if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
 749
 750    // An else with more sanity checking might be nice here.
 751  }
 752
 753  if (i == 3) error_exit("xpidfile %s", name);
 754
 755  xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
 756  close(fd);
 757}
 758
 759// Copy the rest of in to out and close both files.
 760
 761long long xsendfile(int in, int out)
 762{
 763  long long total = 0;
 764  long len;
 765
 766  if (in<0) return 0;
 767  for (;;) {
 768    len = xread(in, libbuf, sizeof(libbuf));
 769    if (len<1) break;
 770    xwrite(out, libbuf, len);
 771    total += len;
 772  }
 773
 774  return total;
 775}
 776
 777double xstrtod(char *s)
 778{
 779  char *end;
 780  double d;
 781
 782  errno = 0;
 783  d = strtod(s, &end);
 784  if (!errno && *end) errno = E2BIG;
 785  if (errno) perror_exit("strtod %s", s);
 786
 787  return d;
 788}
 789
 790// parse fractional seconds with optional s/m/h/d suffix
 791long xparsetime(char *arg, long units, long *fraction)
 792{
 793  double d;
 794  long l;
 795  char *end;
 796
 797  if (CFG_TOYBOX_FLOAT) d = strtod(arg, &end);
 798  else l = strtoul(arg, &end, 10);
 799
 800  if (end == arg) error_exit("Not a number '%s'", arg);
 801  arg = end;
 802
 803  // Parse suffix
 804  if (*arg) {
 805    int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
 806
 807    if (i == -1 || *(arg+1)) error_exit("Unknown suffix '%s'", arg);
 808    if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
 809    else l *= ismhd[i];
 810  }
 811
 812  if (CFG_TOYBOX_FLOAT) {
 813    l = (long)d;
 814    if (fraction) *fraction = units*(d-l);
 815  } else if (fraction) *fraction = 0;
 816
 817  return l;
 818}
 819
 820// Compile a regular expression into a regex_t
 821void xregcomp(regex_t *preg, char *regex, int cflags)
 822{
 823  int rc = regcomp(preg, regex, cflags);
 824
 825  if (rc) {
 826    regerror(rc, preg, libbuf, sizeof(libbuf));
 827    error_exit("xregcomp: %s", libbuf);
 828  }
 829}
 830
 831char *xtzset(char *new)
 832{
 833  char *old = getenv("TZ");
 834
 835  if (old) old = xstrdup(old);
 836  if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
 837  tzset();
 838
 839  return old;
 840}
 841
 842// Set a signal handler
 843void xsignal(int signal, void *handler)
 844{
 845  struct sigaction *sa = (void *)libbuf;
 846
 847  memset(sa, 0, sizeof(struct sigaction));
 848  sa->sa_handler = handler;
 849
 850  if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
 851}
 852