xwrap.c 26 KB

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