toybox/lib/xwrap.c
<<
>>
Prefs
   1/* xwrap.c - library function wrappers that exit instead of returning error
   2 *
   3 * Functions with the x prefix either succeed or kill the program with an
   4 * error message, so the caller doesn't have to check for failure. They
   5 * usually have 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    struct arg_list *al = llist_pop(&toys.xexit);
  50
  51    // typecast xexit->arg to a function pointer, then call it using invalid
  52    // signal 0 to let signal handlers tell actual signal from regular exit.
  53    ((void (*)(int))(al->arg))(0);
  54
  55    free(al);
  56  }
  57  xflush(1);
  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  if (!ret) error_exit("xstrndup");
 100
 101  return ret;
 102}
 103
 104// Die unless we can allocate a copy of this string.
 105char *xstrdup(char *s)
 106{
 107  long len = strlen(s);
 108  char *c = xmalloc(++len);
 109
 110  memcpy(c, s, len);
 111
 112  return c;
 113}
 114
 115void *xmemdup(void *s, long len)
 116{
 117  void *ret = xmalloc(len);
 118  memcpy(ret, s, len);
 119
 120  return ret;
 121}
 122
 123// Die unless we can allocate enough space to sprintf() into.
 124char *xmprintf(char *format, ...)
 125{
 126  va_list va, va2;
 127  int len;
 128  char *ret;
 129
 130  va_start(va, format);
 131  va_copy(va2, va);
 132
 133  // How long is it?
 134  len = vsnprintf(0, 0, format, va)+1;
 135  va_end(va);
 136
 137  // Allocate and do the sprintf()
 138  ret = xmalloc(len);
 139  vsnprintf(ret, len, format, va2);
 140  va_end(va2);
 141
 142  return ret;
 143}
 144
 145// if !flush just check for error on stdout without flushing 
 146void xflush(int flush)
 147{
 148  if ((flush && fflush(0)) || ferror(stdout))
 149    if (!toys.exitval) perror_msg("write");
 150}
 151
 152void xprintf(char *format, ...)
 153{
 154  va_list va;
 155  va_start(va, format);
 156
 157  vprintf(format, va);
 158  va_end(va);
 159  xflush(0);
 160}
 161
 162// Put string with length (does not append newline)
 163void xputsl(char *s, int len)
 164{
 165  xflush(1);
 166  xwrite(1, s, len);
 167}
 168
 169// xputs with no newline
 170void xputsn(char *s)
 171{
 172  xputsl(s, strlen(s));
 173}
 174
 175// Write string to stdout with newline, flushing and checking for errors
 176void xputs(char *s)
 177{
 178  puts(s);
 179  xflush(0);
 180}
 181
 182void xputc(char c)
 183{
 184  if (EOF == fputc(c, stdout)) perror_exit("write");
 185  xflush(0);
 186}
 187
 188// daemonize via vfork(). Does not chdir("/"), caller should do that first
 189// note: restarts process from command_main()
 190void xvdaemon(void)
 191{
 192  int fd;
 193
 194  // vfork and exec /proc/self/exe
 195  if (toys.stacktop) {
 196    xpopen_both(0, 0);
 197    _exit(0);
 198  }
 199
 200  // new session id, point fd 0-2 at /dev/null, detach from tty
 201  setsid();
 202  close(0);
 203  xopen_stdio("/dev/null", O_RDWR);
 204  dup2(0, 1);
 205  if (-1 != (fd = open("/dev/tty", O_RDONLY))) {
 206    ioctl(fd, TIOCNOTTY);
 207    close(fd);
 208  }
 209  dup2(0, 2);
 210}
 211
 212// This is called through the XVFORK macro because parent/child of vfork
 213// share a stack, so child returning from a function would stomp the return
 214// address parent would need. Solution: make vfork() an argument so processes
 215// diverge before function gets called.
 216pid_t __attribute__((returns_twice)) xvforkwrap(pid_t pid)
 217{
 218  if (pid == -1) perror_exit("vfork");
 219
 220  // Signal to xexec() and friends that we vforked so can't recurse
 221  if (!pid) toys.stacktop = 0;
 222
 223  return pid;
 224}
 225
 226// Die unless we can exec argv[] (or run builtin command).  Note that anything
 227// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
 228void xexec(char **argv)
 229{
 230  // Only recurse to builtin when we have multiplexer and !vfork context.
 231  if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE)
 232    if (toys.stacktop && !strchr(*argv, '/')) toy_exec(argv);
 233  execvp(argv[0], argv);
 234
 235  toys.exitval = 126+(errno == ENOENT);
 236  perror_msg("exec %s", argv[0]);
 237  if (!toys.stacktop) _exit(toys.exitval);
 238  xexit();
 239}
 240
 241// Spawn child process, capturing stdin/stdout.
 242// argv[]: command to exec. If null, child re-runs original program with
 243//         toys.stacktop zeroed.
 244// pipes[2]: Filehandle to move to stdin/stdout of new process.
 245//           If -1, replace with pipe handle connected to stdin/stdout.
 246//           NULL treated as {0, 1}, I.E. leave stdin/stdout as is
 247// return: pid of child process
 248pid_t xpopen_setup(char **argv, int *pipes, void (*callback)(char **argv))
 249{
 250  int cestnepasun[4], pid;
 251
 252  // Make the pipes?
 253  memset(cestnepasun, 0, sizeof(cestnepasun));
 254  if (pipes) for (pid = 0; pid < 2; pid++)
 255    if (pipes[pid]==-1 && pipe(cestnepasun+(2*pid))) perror_exit("pipe");
 256
 257  if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
 258    // Child process: Dance of the stdin/stdout redirection.
 259    // cestnepasun[1]->cestnepasun[0] and cestnepasun[3]->cestnepasun[2]
 260    if (pipes) {
 261      // if we had no stdin/out, pipe handles could overlap, so test for it
 262      // and free up potentially overlapping pipe handles before reuse
 263
 264      // in child, close read end of output pipe, use write end as new stdout
 265      if (cestnepasun[2]) {
 266        close(cestnepasun[2]);
 267        pipes[1] = cestnepasun[3];
 268      }
 269
 270      // in child, close write end of input pipe, use read end as new stdin
 271      if (cestnepasun[1]) {
 272        close(cestnepasun[1]);
 273        pipes[0] = cestnepasun[0];
 274      }
 275
 276      // If swapping stdin/stdout, dup a filehandle that gets closed before use
 277      if (!pipes[1]) pipes[1] = dup(0);
 278
 279      // Are we redirecting stdin?
 280      if (pipes[0]) {
 281        dup2(pipes[0], 0);
 282        close(pipes[0]);
 283      }
 284
 285      // Are we redirecting stdout?
 286      if (pipes[1] != 1) {
 287        dup2(pipes[1], 1);
 288        close(pipes[1]);
 289      }
 290    }
 291    if (callback) callback(argv);
 292    if (argv) xexec(argv);
 293
 294    // In fork() case, force recursion because we know it's us.
 295    if (CFG_TOYBOX_FORK) {
 296      toy_init(toys.which, toys.argv);
 297      toys.stacktop = 0;
 298      toys.which->toy_main();
 299      xexit();
 300    // In vfork() case, exec /proc/self/exe with high bit of first letter set
 301    // to tell main() we reentered.
 302    } else {
 303      char *s = "/proc/self/exe";
 304
 305      // We did a nommu-friendly vfork but must exec to continue.
 306      // setting high bit of argv[0][0] to let new process know
 307      **toys.argv |= 0x80;
 308      execv(s, toys.argv);
 309      if ((s = getenv("_"))) execv(s, toys.argv);
 310      perror_msg_raw(s);
 311
 312      _exit(127);
 313    }
 314  }
 315
 316  // Parent process: vfork had a shared environment, clean up.
 317  if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
 318
 319  if (pipes) {
 320    if (cestnepasun[1]) {
 321      pipes[0] = cestnepasun[1];
 322      close(cestnepasun[0]);
 323    }
 324    if (cestnepasun[2]) {
 325      pipes[1] = cestnepasun[2];
 326      close(cestnepasun[3]);
 327    }
 328  }
 329
 330  return pid;
 331}
 332
 333pid_t xpopen_both(char **argv, int *pipes)
 334{
 335  return xpopen_setup(argv, pipes, 0);
 336}
 337
 338
 339// Wait for child process to exit, then return adjusted exit code.
 340int xwaitpid(pid_t pid)
 341{
 342  int status;
 343
 344  while (-1 == waitpid(pid, &status, 0) && errno == EINTR) errno = 0;
 345
 346  return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+128;
 347}
 348
 349int xpclose_both(pid_t pid, int *pipes)
 350{
 351  if (pipes) {
 352    if (pipes[0]) close(pipes[0]);
 353    if (pipes[1]>1) close(pipes[1]);
 354  }
 355
 356  return xwaitpid(pid);
 357}
 358
 359// Wrapper to xpopen with a pipe for just one of stdin/stdout
 360pid_t xpopen(char **argv, int *pipe, int isstdout)
 361{
 362  int pipes[2], pid;
 363
 364  pipes[0] = isstdout ? 0 : -1;
 365  pipes[1] = isstdout ? -1 : 1;
 366  pid = xpopen_both(argv, pipes);
 367  *pipe = pid ? pipes[!!isstdout] : -1;
 368
 369  return pid;
 370}
 371
 372int xpclose(pid_t pid, int pipe)
 373{
 374  close(pipe);
 375
 376  return xpclose_both(pid, 0);
 377}
 378
 379// Call xpopen and wait for it to finish, keeping existing stdin/stdout.
 380int xrun(char **argv)
 381{
 382  return xpclose_both(xpopen_both(argv, 0), 0);
 383}
 384
 385// Run child, writing "stdin", returning stdout or NULL, pass through stderr
 386char *xrunread(char *argv[], char *stdin)
 387{
 388  char *result = 0;
 389  int pipe[] = {-1, -1}, total = 0, len;
 390  pid_t pid;
 391
 392  pid = xpopen_both(argv, pipe);
 393  if (stdin && *stdin) writeall(*pipe, stdin, strlen(stdin));
 394  close(*pipe);
 395  for (;;) {
 396    if (0>=(len = readall(pipe[1], libbuf, sizeof(libbuf)))) break;
 397    memcpy((result = xrealloc(result, 1+total+len))+total, libbuf, len);
 398    total += len;
 399    if (len != sizeof(libbuf)) break;
 400  }
 401  if (result) result[total] = 0;
 402  close(pipe[1]);
 403
 404  if (xwaitpid(pid)) {
 405    free(result);
 406
 407    return 0;
 408  }
 409
 410  return result;
 411}
 412
 413void xaccess(char *path, int flags)
 414{
 415  if (access(path, flags)) perror_exit("Can't access '%s'", path);
 416}
 417
 418// Die unless we can delete a file.  (File must exist to be deleted.)
 419void xunlink(char *path)
 420{
 421  if (unlink(path)) perror_exit("unlink '%s'", path);
 422}
 423
 424// Die unless we can open/create a file, returning file descriptor.
 425// The meaning of O_CLOEXEC is reversed (it defaults on, pass it to disable)
 426// and WARN_ONLY tells us not to exit.
 427int xcreate_stdio(char *path, int flags, int mode)
 428{
 429  int fd = open(path, (flags^O_CLOEXEC)&~WARN_ONLY, mode);
 430
 431  if (fd == -1) ((flags&WARN_ONLY) ? perror_msg_raw : perror_exit_raw)(path);
 432  return fd;
 433}
 434
 435// Die unless we can open a file, returning file descriptor.
 436int xopen_stdio(char *path, int flags)
 437{
 438  return xcreate_stdio(path, flags, 0);
 439}
 440
 441void xpipe(int *pp)
 442{
 443  if (pipe(pp)) perror_exit("xpipe");
 444}
 445
 446void xclose(int fd)
 447{
 448  if (fd != -1 && close(fd)) perror_exit("xclose");
 449}
 450
 451int xdup(int fd)
 452{
 453  if (fd != -1) {
 454    fd = dup(fd);
 455    if (fd == -1) perror_exit("xdup");
 456  }
 457  return fd;
 458}
 459
 460// Move file descriptor above stdin/stdout/stderr, using /dev/null to consume
 461// old one. (We should never be called with stdin/stdout/stderr closed, but...)
 462int notstdio(int fd)
 463{
 464  if (fd<0) return fd;
 465
 466  while (fd<3) {
 467    int fd2 = xdup(fd);
 468
 469    close(fd);
 470    xopen_stdio("/dev/null", O_RDWR);
 471    fd = fd2;
 472  }
 473
 474  return fd;
 475}
 476
 477void xrename(char *from, char *to)
 478{
 479  if (rename(from, to)) perror_exit("rename %s -> %s", from, to);
 480}
 481
 482int xtempfile(char *name, char **tempname)
 483{
 484  int fd;
 485
 486   *tempname = xmprintf("%s%s", name, "XXXXXX");
 487  if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
 488
 489  return fd;
 490}
 491
 492// Create a file but don't return stdin/stdout/stderr
 493int xcreate(char *path, int flags, int mode)
 494{
 495  return notstdio(xcreate_stdio(path, flags, mode));
 496}
 497
 498// Open a file descriptor NOT in stdin/stdout/stderr
 499int xopen(char *path, int flags)
 500{
 501  return notstdio(xopen_stdio(path, flags));
 502}
 503
 504// Open read only, treating "-" as a synonym for stdin, defaulting to warn only
 505int openro(char *path, int flags)
 506{
 507  if (!strcmp(path, "-")) return 0;
 508
 509  return xopen(path, flags^WARN_ONLY);
 510}
 511
 512// Open read only, treating "-" as a synonym for stdin.
 513int xopenro(char *path)
 514{
 515  return openro(path, O_RDONLY|WARN_ONLY);
 516}
 517
 518FILE *xfdopen(int fd, char *mode)
 519{
 520  FILE *f = fdopen(fd, mode);
 521
 522  if (!f) perror_exit("xfdopen");
 523
 524  return f;
 525}
 526
 527// Die unless we can open/create a file, returning FILE *.
 528FILE *xfopen(char *path, char *mode)
 529{
 530  FILE *f = fopen(path, mode);
 531  if (!f) perror_exit("No file %s", path);
 532  return f;
 533}
 534
 535// Die if there's an error other than EOF.
 536size_t xread(int fd, void *buf, size_t len)
 537{
 538  ssize_t ret = read(fd, buf, len);
 539  if (ret < 0) perror_exit("xread");
 540
 541  return ret;
 542}
 543
 544void xreadall(int fd, void *buf, size_t len)
 545{
 546  if (len != readall(fd, buf, len)) perror_exit("xreadall");
 547}
 548
 549// There's no xwriteall(), just xwrite().  When we read, there may or may not
 550// be more data waiting.  When we write, there is data and it had better go
 551// somewhere.
 552
 553void xwrite(int fd, void *buf, size_t len)
 554{
 555  if (len != writeall(fd, buf, len)) perror_exit("xwrite");
 556}
 557
 558// Die if lseek fails, probably due to being called on a pipe.
 559
 560off_t xlseek(int fd, off_t offset, int whence)
 561{
 562  offset = lseek(fd, offset, whence);
 563  if (offset<0) perror_exit("lseek");
 564
 565  return offset;
 566}
 567
 568char *xgetcwd(void)
 569{
 570  char *buf = getcwd(NULL, 0);
 571  if (!buf) perror_exit("xgetcwd");
 572
 573  return buf;
 574}
 575
 576void xstat(char *path, struct stat *st)
 577{
 578  if(stat(path, st)) perror_exit("Can't stat %s", path);
 579}
 580
 581// Canonicalize path, even to file with one or more missing components at end.
 582// Returns allocated string for pathname or NULL if doesn't exist. Flags are:
 583// ABS_PATH:path to last component must exist ABS_FILE: whole path must exist
 584// ABS_KEEP:keep symlinks in path ABS_LAST: keep symlink at end of path
 585char *xabspath(char *path, int flags)
 586{
 587  struct string_list *todo, *done = 0, *new, **tail;
 588  int fd, track, len, try = 9999, dirfd = -1, missing = 0;
 589  char *str;
 590
 591  // If the last file must exist, path to it must exist.
 592  if (flags&ABS_FILE) flags |= ABS_PATH;
 593  // If we don't resolve path's symlinks, don't resolve last symlink.
 594  if (flags&ABS_KEEP) flags |= ABS_LAST;
 595
 596  // If this isn't an absolute path, start with cwd or $PWD.
 597  if (*path != '/') {
 598    if ((flags & ABS_KEEP) && (str = getenv("PWD")))
 599      splitpath(path, splitpath(str, &todo));
 600    else {
 601      splitpath(path, splitpath(str = xgetcwd(), &todo));
 602      free(str);
 603    }
 604  } else splitpath(path, &todo);
 605
 606  // Iterate through path components in todo, prepend processed ones to done.
 607  while (todo) {
 608    // break out of endless symlink loops
 609    if (!try--) {
 610      errno = ELOOP;
 611      goto error;
 612    }
 613
 614    // Remove . or .. component, tracking dirfd back up tree as necessary
 615    str = (new = llist_pop(&todo))->str;
 616    // track dirfd if this component must exist or we're resolving symlinks
 617    track = ((flags>>!todo) & (ABS_PATH|ABS_KEEP)) ^ ABS_KEEP;
 618    if (!done && track) dirfd = open("/", O_PATH);
 619    if (*str=='.' && !str[1+((fd = str[1])=='.')]) {
 620      free(new);
 621      if (fd) {
 622        if (done) free(llist_pop(&done));
 623        if (missing) missing--;
 624        else if (track) {
 625          if (-1 == (fd = openat(dirfd, "..", O_PATH))) goto error;
 626          close(dirfd);
 627          dirfd = fd;
 628        }
 629      }
 630      continue;
 631    }
 632
 633    // Is this a symlink?
 634    if (flags & (ABS_KEEP<<!todo)) errno = len = 0;
 635    else len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
 636    if (len>4095) goto error;
 637
 638    // Not a symlink: add to linked list, move dirfd, fail if error
 639    if (len<1) {
 640      new->next = done;
 641      done = new;
 642      if (errno == ENOENT && !(flags & (ABS_PATH<<!todo))) missing++;
 643      else if (errno != EINVAL && (flags & (ABS_PATH<<!todo))) goto error;
 644      else if (track) {
 645        if (-1 == (fd = openat(dirfd, new->str, O_PATH))) goto error;
 646        close(dirfd);
 647        dirfd = fd;
 648      }
 649      continue;
 650    }
 651
 652    // If this symlink is to an absolute path, discard existing resolved path
 653    libbuf[len] = 0;
 654    if (*libbuf == '/') {
 655      llist_traverse(done, free);
 656      done = 0;
 657      close(dirfd);
 658      dirfd = -1;
 659    }
 660    free(new);
 661
 662    // prepend components of new path. Note symlink to "/" will leave new = NULL
 663    tail = splitpath(libbuf, &new);
 664
 665    // symlink to "/" will return null and leave tail alone
 666    if (new) {
 667      *tail = todo;
 668      todo = new;
 669    }
 670  }
 671  xclose(dirfd);
 672
 673  // At this point done has the path, in reverse order. Reverse list
 674  // (into todo) while calculating buffer length.
 675  try = 2;
 676  while (done) {
 677    struct string_list *temp = llist_pop(&done);
 678
 679    if (todo) try++;
 680    try += strlen(temp->str);
 681    temp->next = todo;
 682    todo = temp;
 683  }
 684
 685  // Assemble return buffer
 686  *(str = xmalloc(try)) = '/';
 687  str[try = 1] = 0;
 688  while (todo) {
 689    if (try>1) str[try++] = '/';
 690    try = stpcpy(str+try, todo->str) - str;
 691    free(llist_pop(&todo));
 692  }
 693
 694  return str;
 695
 696error:
 697  xclose(dirfd);
 698  llist_traverse(todo, free);
 699  llist_traverse(done, free);
 700
 701  return 0;
 702}
 703
 704void xchdir(char *path)
 705{
 706  if (chdir(path)) perror_exit("chdir '%s'", path);
 707}
 708
 709void xchroot(char *path)
 710{
 711  if (chroot(path)) error_exit("chroot '%s'", path);
 712  xchdir("/");
 713}
 714
 715struct passwd *xgetpwuid(uid_t uid)
 716{
 717  struct passwd *pwd = getpwuid(uid);
 718  if (!pwd) error_exit("bad uid %ld", (long)uid);
 719  return pwd;
 720}
 721
 722struct group *xgetgrgid(gid_t gid)
 723{
 724  struct group *group = getgrgid(gid);
 725
 726  if (!group) perror_exit("gid %ld", (long)gid);
 727  return group;
 728}
 729
 730unsigned xgetuid(char *name)
 731{
 732  struct passwd *up = getpwnam(name);
 733  char *s = 0;
 734  long uid;
 735
 736  if (up) return up->pw_uid;
 737
 738  uid = estrtol(name, &s, 10);
 739  if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
 740
 741  error_exit("bad user '%s'", name);
 742}
 743
 744unsigned xgetgid(char *name)
 745{
 746  struct group *gr = getgrnam(name);
 747  char *s = 0;
 748  long gid;
 749
 750  if (gr) return gr->gr_gid;
 751
 752  gid = estrtol(name, &s, 10);
 753  if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
 754
 755  error_exit("bad group '%s'", name);
 756}
 757
 758struct passwd *xgetpwnam(char *name)
 759{
 760  struct passwd *up = getpwnam(name);
 761
 762  if (!up) perror_exit("user '%s'", name);
 763  return up;
 764}
 765
 766struct group *xgetgrnam(char *name)
 767{
 768  struct group *gr = getgrnam(name);
 769
 770  if (!gr) perror_exit("group '%s'", name);
 771  return gr;
 772}
 773
 774// setuid() can fail (for example, too many processes belonging to that user),
 775// which opens a security hole if the process continues as the original user.
 776
 777void xsetuser(struct passwd *pwd)
 778{
 779  if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
 780      || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
 781}
 782
 783// This can return null (meaning file not found).  It just won't return null
 784// for memory allocation reasons.
 785char *xreadlinkat(int dir, char *name)
 786{
 787  int len, size = 0;
 788  char *buf = 0;
 789
 790  // Grow by 64 byte chunks until it's big enough.
 791  for(;;) {
 792    size +=64;
 793    buf = xrealloc(buf, size);
 794    len = readlinkat(dir, name, buf, size);
 795
 796    if (len<0) {
 797      free(buf);
 798      return 0;
 799    }
 800    if (len<size) {
 801      buf[len]=0;
 802      return buf;
 803    }
 804  }
 805}
 806
 807char *xreadlink(char *name)
 808{
 809  return xreadlinkat(AT_FDCWD, name);
 810}
 811
 812
 813char *xreadfile(char *name, char *buf, off_t len)
 814{
 815  if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
 816
 817  return buf;
 818}
 819
 820// The data argument to ioctl() is actually long, but it's usually used as
 821// a pointer. If you need to feed in a number, do (void *)(long) typecast.
 822int xioctl(int fd, int request, void *data)
 823{
 824  int rc;
 825
 826  errno = 0;
 827  rc = ioctl(fd, request, data);
 828  if (rc == -1 && errno) perror_exit("ioctl %x", request);
 829
 830  return rc;
 831}
 832
 833// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
 834// exists and is this executable.
 835void xpidfile(char *name)
 836{
 837  char pidfile[256], spid[32];
 838  int i, fd;
 839  pid_t pid;
 840
 841  sprintf(pidfile, "/var/run/%s.pid", name);
 842  // Try three times to open the sucker.
 843  for (i=0; i<3; i++) {
 844    fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
 845    if (fd != -1) break;
 846
 847    // If it already existed, read it.  Loop for race condition.
 848    fd = open(pidfile, O_RDONLY);
 849    if (fd == -1) continue;
 850
 851    // Is the old program still there?
 852    spid[xread(fd, spid, sizeof(spid)-1)] = 0;
 853    close(fd);
 854    pid = atoi(spid);
 855    if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
 856
 857    // An else with more sanity checking might be nice here.
 858  }
 859
 860  if (i == 3) error_exit("xpidfile %s", name);
 861
 862  xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
 863  close(fd);
 864}
 865
 866// error_exit if we couldn't copy all bytes
 867long long xsendfile_len(int in, int out, long long bytes)
 868{
 869  long long len = sendfile_len(in, out, bytes, 0);
 870
 871  if (bytes != -1 && bytes != len) {
 872    if (out == 1 && len<0) xexit();
 873    error_exit("short %s", (len<0) ? "write" : "read");
 874  }
 875
 876  return len;
 877}
 878
 879// warn and pad with zeroes if we couldn't copy all bytes
 880void xsendfile_pad(int in, int out, long long len)
 881{
 882  len -= xsendfile_len(in, out, len);
 883  if (len) {
 884    perror_msg("short read");
 885    memset(libbuf, 0, sizeof(libbuf));
 886    while (len) {
 887      int i = len>sizeof(libbuf) ? sizeof(libbuf) : len;
 888
 889      xwrite(out, libbuf, i);
 890      len -= i;
 891    }
 892  }
 893}
 894
 895// copy all of in to out
 896long long xsendfile(int in, int out)
 897{
 898  return xsendfile_len(in, out, -1);
 899}
 900
 901double xstrtod(char *s)
 902{
 903  char *end;
 904  double d;
 905
 906  errno = 0;
 907  d = strtod(s, &end);
 908  if (!errno && *end) errno = E2BIG;
 909  if (errno) perror_exit("strtod %s", s);
 910
 911  return d;
 912}
 913
 914// parse fractional seconds with optional s/m/h/d suffix
 915long xparsetime(char *arg, long zeroes, long *fraction)
 916{
 917  long l, fr = 0, mask = 1;
 918  char *end;
 919
 920  if (*arg != '.' && !isdigit(*arg)) error_exit("Not a number '%s'", arg);
 921  l = strtoul(arg, &end, 10);
 922  if (*end == '.') {
 923    end++;
 924    while (zeroes--) {
 925      fr *= 10;
 926      mask *= 10;
 927      if (isdigit(*end)) fr += *end++-'0';
 928    }
 929    while (isdigit(*end)) end++;
 930  }
 931
 932  // Parse suffix
 933  if (*end) {
 934    int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *end);
 935
 936    if (i == -1 || *(end+1)) error_exit("Unknown suffix '%s'", end);
 937    l *= ismhd[i];
 938    fr *= ismhd[i];
 939    l += fr/mask;
 940    fr %= mask;
 941  }
 942  if (fraction) *fraction = fr;
 943
 944  return l;
 945}
 946
 947long long xparsemillitime(char *arg)
 948{
 949  long l, ll;
 950
 951  l = xparsetime(arg, 3, &ll);
 952
 953  return (l*1000LL)+ll;
 954}
 955
 956void xparsetimespec(char *arg, struct timespec *ts)
 957{
 958  ts->tv_sec = xparsetime(arg, 9, &ts->tv_nsec);
 959}
 960
 961
 962// Compile a regular expression into a regex_t
 963void xregcomp(regex_t *preg, char *regex, int cflags)
 964{
 965  int rc;
 966
 967  // BSD regex implementations don't support the empty regex (which isn't
 968  // allowed in the POSIX grammar), but glibc does. Fake it for BSD.
 969  if (!*regex) {
 970    regex = "()";
 971    cflags |= REG_EXTENDED;
 972  }
 973
 974  if ((rc = regcomp(preg, regex, cflags))) {
 975    regerror(rc, preg, libbuf, sizeof(libbuf));
 976    error_exit("bad regex '%s': %s", regex, libbuf);
 977  }
 978}
 979
 980char *xtzset(char *new)
 981{
 982  char *old = getenv("TZ");
 983
 984  if (old) old = xstrdup(old);
 985  if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
 986  tzset();
 987
 988  return old;
 989}
 990
 991// Set a signal handler
 992void xsignal_flags(int signal, void *handler, int flags)
 993{
 994  struct sigaction *sa = (void *)libbuf;
 995
 996  memset(sa, 0, sizeof(struct sigaction));
 997  sa->sa_handler = handler;
 998  sa->sa_flags = flags;
 999
1000  if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
1001}
1002
1003void xsignal(int signal, void *handler)
1004{
1005  xsignal_flags(signal, handler, 0);
1006}
1007
1008
1009time_t xvali_date(struct tm *tm, char *str)
1010{
1011  time_t t;
1012
1013  if (tm && (unsigned)tm->tm_sec<=60 && (unsigned)tm->tm_min<=59
1014     && (unsigned)tm->tm_hour<=23 && tm->tm_mday && (unsigned)tm->tm_mday<=31
1015     && (unsigned)tm->tm_mon<=11 && (t = mktime(tm)) != -1) return t;
1016
1017  error_exit("bad date %s", str);
1018}
1019
1020// Parse date string (relative to current *t). Sets time_t and nanoseconds.
1021void xparsedate(char *str, time_t *t, unsigned *nano, int endian)
1022{
1023  struct tm tm;
1024  time_t now = *t;
1025  int len = 0, i = 0;
1026  long long ll;
1027  // Formats with seconds come first. Posix can't agree on whether 12 digits
1028  // has year before (touch -t) or year after (date), so support both.
1029  char *s = str, *p, *oldtz = 0, *formats[] = {"%Y-%m-%d %T", "%Y-%m-%dT%T",
1030    "%a %b %e %H:%M:%S %Z %Y", // date(1) output format in POSIX/C locale.
1031    "%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M", "%m%d%H%M",
1032    endian ? "%m%d%H%M%y" : "%y%m%d%H%M",
1033    endian ? "%m%d%H%M%C%y" : "%C%y%m%d%H%M"};
1034
1035  *nano = 0;
1036
1037  // Parse @UNIXTIME[.FRACTION]
1038  if (1 == sscanf(s, "@%lld%n", &ll, &len)) {
1039    if (*(s+=len)=='.') for (len = 0, s++; len<9; len++) {
1040      *nano *= 10;
1041      if (isdigit(*s)) *nano += *s++-'0';
1042    }
1043    // Can't be sure t is 64 bit (yet) for %lld above
1044    *t = ll;
1045    if (!*s) return;
1046    xvali_date(0, str);
1047  }
1048
1049  // Try each format
1050  for (i = 0; i<ARRAY_LEN(formats); i++) {
1051    localtime_r(&now, &tm);
1052    tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
1053    tm.tm_isdst = -endian;
1054
1055    if ((p = strptime(s, formats[i], &tm))) {
1056      // Handle optional fractional seconds.
1057      if (*p == '.') {
1058        p++;
1059        // If format didn't already specify seconds, grab seconds
1060        if (i>2) {
1061          len = 0;
1062          sscanf(p, "%2u%n", &tm.tm_sec, &len);
1063          p += len;
1064        }
1065        // nanoseconds
1066        for (len = 0; len<9; len++) {
1067          *nano *= 10;
1068          if (isdigit(*p)) *nano += *p++-'0';
1069        }
1070      }
1071
1072      // Handle optional Z or +HH[[:]MM] timezone
1073      while (isspace(*p)) p++;
1074      if (*p && strchr("Z+-", *p)) {
1075        unsigned uu[3] = {0}, n = 0, nn = 0;
1076        char *tz = 0, sign = *p++;
1077
1078        if (sign == 'Z') tz = "UTC0";
1079        else if (0<sscanf(p, " %u%n : %u%n : %u%n", uu,&n,uu+1,&nn,uu+2,&nn)) {
1080          if (n>2) {
1081            uu[1] += uu[0]%100;
1082            uu[0] /= 100;
1083          }
1084          if (n>nn) nn = n;
1085          if (!nn) continue;
1086
1087          // flip sign because POSIX UTC offsets are backwards
1088          sprintf(tz = libbuf, "UTC%c%02u:%02u:%02u", "+-"[sign=='+'],
1089            uu[0], uu[1], uu[2]);
1090          p += nn;
1091        }
1092
1093        if (!oldtz) {
1094          oldtz = getenv("TZ");
1095          if (oldtz) oldtz = xstrdup(oldtz);
1096        }
1097        if (tz) setenv("TZ", tz, 1);
1098      }
1099      while (isspace(*p)) p++;
1100
1101      if (!*p) break;
1102    }
1103  }
1104
1105  // Sanity check field ranges
1106  *t = xvali_date((i!=ARRAY_LEN(formats)) ? &tm : 0, str);
1107
1108  if (oldtz) setenv("TZ", oldtz, 1);
1109  free(oldtz);
1110}
1111
1112// Return line of text from file. Strips trailing newline (if any).
1113char *xgetline(FILE *fp)
1114{
1115  char *new = 0;
1116  size_t len = 0;
1117  long ll;
1118
1119  errno = 0;
1120  if (1>(ll = getline(&new, &len, fp))) {
1121    if (errno && errno != EINTR) perror_msg("getline");
1122    new = 0;
1123  } else if (new[ll-1] == '\n') new[--ll] = 0;
1124
1125  return new;
1126}
1127
1128time_t xmktime(struct tm *tm, int utc)
1129{
1130  char *old_tz = utc ? xtzset("UTC0") : 0;
1131  time_t result;
1132
1133  if ((result = mktime(tm)) < 0) error_exit("mktime");
1134  if (utc) {
1135    free(xtzset(old_tz));
1136    free(old_tz);
1137  }
1138  return result;
1139}
1140