1
0

xwrap.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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 <[email protected]>
  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 && pipe(cestnepasun+(2*pid))) perror_exit("pipe");
  211. if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
  212. // Child process: Dance of the stdin/stdout redirection.
  213. // cestnepasun[1]->cestnepasun[0] and cestnepasun[3]->cestnepasun[2]
  214. if (pipes) {
  215. // if we had no stdin/out, pipe handles could overlap, so test for it
  216. // and free up potentially overlapping pipe handles before reuse
  217. // in child, close read end of output pipe, use write end as new stdout
  218. if (cestnepasun[2]) {
  219. close(cestnepasun[2]);
  220. pipes[1] = cestnepasun[3];
  221. }
  222. // in child, close write end of input pipe, use read end as new stdin
  223. if (cestnepasun[1]) {
  224. close(cestnepasun[1]);
  225. pipes[0] = cestnepasun[0];
  226. }
  227. // If swapping stdin/stdout, dup a filehandle that gets closed before use
  228. if (!pipes[1]) pipes[1] = dup(0);
  229. // Are we redirecting stdin?
  230. if (pipes[0]) {
  231. dup2(pipes[0], 0);
  232. close(pipes[0]);
  233. }
  234. // Are we redirecting stdout?
  235. if (pipes[1] != 1) {
  236. dup2(pipes[1], 1);
  237. close(pipes[1]);
  238. }
  239. }
  240. if (callback) callback(argv);
  241. if (argv) xexec(argv);
  242. // In fork() case, force recursion because we know it's us.
  243. if (CFG_TOYBOX_FORK) {
  244. toy_init(toys.which, toys.argv);
  245. toys.stacktop = 0;
  246. toys.which->toy_main();
  247. xexit();
  248. // In vfork() case, exec /proc/self/exe with high bit of first letter set
  249. // to tell main() we reentered.
  250. } else {
  251. char *s = "/proc/self/exe";
  252. // We did a nommu-friendly vfork but must exec to continue.
  253. // setting high bit of argv[0][0] to let new process know
  254. **toys.argv |= 0x80;
  255. execv(s, toys.argv);
  256. if ((s = getenv("_"))) execv(s, toys.argv);
  257. perror_msg_raw(s);
  258. _exit(127);
  259. }
  260. }
  261. // Parent process: vfork had a shared environment, clean up.
  262. if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
  263. if (pipes) {
  264. if (cestnepasun[1]) {
  265. pipes[0] = cestnepasun[1];
  266. close(cestnepasun[0]);
  267. }
  268. if (cestnepasun[2]) {
  269. pipes[1] = cestnepasun[2];
  270. close(cestnepasun[3]);
  271. }
  272. }
  273. return pid;
  274. }
  275. pid_t xpopen_both(char **argv, int *pipes)
  276. {
  277. return xpopen_setup(argv, pipes, 0);
  278. }
  279. // Wait for child process to exit, then return adjusted exit code.
  280. int xwaitpid(pid_t pid)
  281. {
  282. int status = 127<<8;
  283. while (-1 == waitpid(pid, &status, 0) && errno == EINTR) errno = 0;
  284. return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+128;
  285. }
  286. int xpclose_both(pid_t pid, int *pipes)
  287. {
  288. if (pipes) {
  289. if (pipes[0]) close(pipes[0]);
  290. if (pipes[1]>1) close(pipes[1]);
  291. }
  292. return xwaitpid(pid);
  293. }
  294. // Wrapper to xpopen with a pipe for just one of stdin/stdout
  295. pid_t xpopen(char **argv, int *pipe, int isstdout)
  296. {
  297. int pipes[2], pid;
  298. pipes[0] = isstdout ? 0 : -1;
  299. pipes[1] = isstdout ? -1 : 1;
  300. pid = xpopen_both(argv, pipes);
  301. *pipe = pid ? pipes[!!isstdout] : -1;
  302. return pid;
  303. }
  304. int xpclose(pid_t pid, int pipe)
  305. {
  306. close(pipe);
  307. return xpclose_both(pid, 0);
  308. }
  309. // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
  310. int xrun(char **argv)
  311. {
  312. return xpclose_both(xpopen_both(argv, 0), 0);
  313. }
  314. // Run child, writing to_stdin, returning stdout or NULL, pass through stderr
  315. char *xrunread(char *argv[], char *to_stdin)
  316. {
  317. char *result = 0;
  318. int pipe[] = {-1, -1}, total = 0, len;
  319. pid_t pid;
  320. pid = xpopen_both(argv, pipe);
  321. if (to_stdin && *to_stdin) writeall(*pipe, to_stdin, strlen(to_stdin));
  322. close(*pipe);
  323. for (;;) {
  324. if (0>=(len = readall(pipe[1], libbuf, sizeof(libbuf)))) break;
  325. memcpy((result = xrealloc(result, 1+total+len))+total, libbuf, len);
  326. total += len;
  327. if (len != sizeof(libbuf)) break;
  328. }
  329. if (result) result[total] = 0;
  330. close(pipe[1]);
  331. if (xwaitpid(pid)) {
  332. free(result);
  333. return 0;
  334. }
  335. return result;
  336. }
  337. void xaccess(char *path, int flags)
  338. {
  339. if (access(path, flags)) perror_exit("Can't access '%s'", path);
  340. }
  341. // Die unless we can delete a file. (File must exist to be deleted.)
  342. void xunlink(char *path)
  343. {
  344. if (unlink(path)) perror_exit("unlink '%s'", path);
  345. }
  346. // Die unless we can open/create a file, returning file descriptor.
  347. // The meaning of O_CLOEXEC is reversed (it defaults on, pass it to disable)
  348. // and WARN_ONLY tells us not to exit.
  349. int xcreate_stdio(char *path, int flags, int mode)
  350. {
  351. int fd = open(path, (flags^O_CLOEXEC)&~WARN_ONLY, mode);
  352. if (fd == -1) ((flags&WARN_ONLY) ? perror_msg_raw : perror_exit_raw)(path);
  353. return fd;
  354. }
  355. // Die unless we can open a file, returning file descriptor.
  356. int xopen_stdio(char *path, int flags)
  357. {
  358. return xcreate_stdio(path, flags, 0);
  359. }
  360. void xpipe(int *pp)
  361. {
  362. if (pipe(pp)) perror_exit("xpipe");
  363. }
  364. void xclose(int fd)
  365. {
  366. if (fd != -1 && close(fd)) perror_exit("xclose");
  367. }
  368. int xdup(int fd)
  369. {
  370. if (fd != -1) {
  371. fd = dup(fd);
  372. if (fd == -1) perror_exit("xdup");
  373. }
  374. return fd;
  375. }
  376. int xnotstdio(int fd)
  377. {
  378. if (fd<0) return fd;
  379. while (fd<3) {
  380. int fd2 = xdup(fd);
  381. close(fd);
  382. xopen_stdio("/dev/null", O_RDWR);
  383. fd = fd2;
  384. }
  385. return fd;
  386. }
  387. void xrename(char *from, char *to)
  388. {
  389. if (rename(from, to)) perror_exit("rename %s -> %s", from, to);
  390. }
  391. int xtempfile(char *name, char **tempname)
  392. {
  393. int fd;
  394. *tempname = xmprintf("%s%s", name, "XXXXXX");
  395. if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
  396. return fd;
  397. }
  398. // Create a file but don't return stdin/stdout/stderr
  399. int xcreate(char *path, int flags, int mode)
  400. {
  401. return xnotstdio(xcreate_stdio(path, flags, mode));
  402. }
  403. // Open a file descriptor NOT in stdin/stdout/stderr
  404. int xopen(char *path, int flags)
  405. {
  406. return xnotstdio(xopen_stdio(path, flags));
  407. }
  408. // Open read only, treating "-" as a synonym for stdin, defaulting to warn only
  409. int openro(char *path, int flags)
  410. {
  411. if (!strcmp(path, "-")) return 0;
  412. return xopen(path, flags^WARN_ONLY);
  413. }
  414. // Open read only, treating "-" as a synonym for stdin.
  415. int xopenro(char *path)
  416. {
  417. return openro(path, O_RDONLY|WARN_ONLY);
  418. }
  419. FILE *xfdopen(int fd, char *mode)
  420. {
  421. FILE *f = fdopen(fd, mode);
  422. if (!f) perror_exit("xfdopen");
  423. return f;
  424. }
  425. // Die unless we can open/create a file, returning FILE *.
  426. FILE *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. // Die if there's an error other than EOF.
  433. size_t xread(int fd, void *buf, size_t len)
  434. {
  435. ssize_t ret = read(fd, buf, len);
  436. if (ret < 0) perror_exit("xread");
  437. return ret;
  438. }
  439. void xreadall(int fd, void *buf, size_t len)
  440. {
  441. if (len != readall(fd, buf, len)) perror_exit("xreadall");
  442. }
  443. // There's no xwriteall(), just xwrite(). When we read, there may or may not
  444. // be more data waiting. When we write, there is data and it had better go
  445. // somewhere.
  446. void xwrite(int fd, void *buf, size_t len)
  447. {
  448. if (len != writeall(fd, buf, len)) perror_exit("xwrite");
  449. }
  450. // Die if lseek fails, probably due to being called on a pipe.
  451. off_t xlseek(int fd, off_t offset, int whence)
  452. {
  453. offset = lseek(fd, offset, whence);
  454. if (offset<0) perror_exit("lseek");
  455. return offset;
  456. }
  457. char *xgetcwd(void)
  458. {
  459. char *buf = getcwd(NULL, 0);
  460. if (!buf) perror_exit("xgetcwd");
  461. return buf;
  462. }
  463. void xstat(char *path, struct stat *st)
  464. {
  465. if(stat(path, st)) perror_exit("Can't stat %s", path);
  466. }
  467. // Canonicalize path, even to file with one or more missing components at end.
  468. // Returns allocated string for pathname or NULL if doesn't exist. Flags are:
  469. // ABS_PATH:path to last component must exist ABS_FILE: whole path must exist
  470. // ABS_KEEP:keep symlinks in path ABS_LAST: keep symlink at end of path
  471. char *xabspath(char *path, int flags)
  472. {
  473. struct string_list *todo, *done = 0, *new, **tail;
  474. int fd, track, len, try = 9999, dirfd = -1, missing = 0;
  475. char *str;
  476. // If the last file must exist, path to it must exist.
  477. if (flags&ABS_FILE) flags |= ABS_PATH;
  478. // If we don't resolve path's symlinks, don't resolve last symlink.
  479. if (flags&ABS_KEEP) flags |= ABS_LAST;
  480. // If this isn't an absolute path, start with cwd or $PWD.
  481. if (*path != '/') {
  482. if ((flags & ABS_KEEP) && (str = getenv("PWD")))
  483. splitpath(path, splitpath(str, &todo));
  484. else {
  485. splitpath(path, splitpath(str = xgetcwd(), &todo));
  486. free(str);
  487. }
  488. } else splitpath(path, &todo);
  489. // Iterate through path components in todo, prepend processed ones to done.
  490. while (todo) {
  491. // break out of endless symlink loops
  492. if (!try--) {
  493. errno = ELOOP;
  494. goto error;
  495. }
  496. // Remove . or .. component, tracking dirfd back up tree as necessary
  497. str = (new = llist_pop(&todo))->str;
  498. // track dirfd if this component must exist or we're resolving symlinks
  499. track = ((flags>>!todo) & (ABS_PATH|ABS_KEEP)) ^ ABS_KEEP;
  500. if (!done && track) dirfd = open("/", O_PATH);
  501. if (*str=='.' && !str[1+((fd = str[1])=='.')]) {
  502. free(new);
  503. if (fd) {
  504. if (done) free(llist_pop(&done));
  505. if (missing) missing--;
  506. else if (track) {
  507. if (-1 == (fd = openat(dirfd, "..", O_PATH))) goto error;
  508. close(dirfd);
  509. dirfd = fd;
  510. }
  511. }
  512. continue;
  513. }
  514. // Is this a symlink?
  515. if (flags & (ABS_KEEP<<!todo)) len = 0, errno = EINVAL;
  516. else len = readlinkat(dirfd, str, libbuf, sizeof(libbuf));
  517. if (len>4095) goto error;
  518. // Not a symlink: add to linked list, move dirfd, fail if error
  519. if (len<1) {
  520. new->next = done;
  521. done = new;
  522. if (errno == ENOENT && !(flags & (ABS_PATH<<!todo))) missing++;
  523. else if (errno != EINVAL && (flags & (ABS_PATH<<!todo))) goto error;
  524. else if (track) {
  525. if (-1 == (fd = openat(dirfd, new->str, O_PATH))) goto error;
  526. close(dirfd);
  527. dirfd = fd;
  528. }
  529. continue;
  530. }
  531. // If this symlink is to an absolute path, discard existing resolved path
  532. libbuf[len] = 0;
  533. if (*libbuf == '/') {
  534. llist_traverse(done, free);
  535. done = 0;
  536. close(dirfd);
  537. dirfd = -1;
  538. }
  539. free(new);
  540. // prepend components of new path. Note symlink to "/" will leave new = NULL
  541. tail = splitpath(libbuf, &new);
  542. // symlink to "/" will return null and leave tail alone
  543. if (new) {
  544. *tail = todo;
  545. todo = new;
  546. }
  547. }
  548. xclose(dirfd);
  549. // At this point done has the path, in reverse order. Reverse list
  550. // (into todo) while calculating buffer length.
  551. try = 2;
  552. while (done) {
  553. struct string_list *temp = llist_pop(&done);
  554. if (todo) try++;
  555. try += strlen(temp->str);
  556. temp->next = todo;
  557. todo = temp;
  558. }
  559. // Assemble return buffer
  560. *(str = xmalloc(try)) = '/';
  561. str[try = 1] = 0;
  562. while (todo) {
  563. if (try>1) str[try++] = '/';
  564. try = stpcpy(str+try, todo->str) - str;
  565. free(llist_pop(&todo));
  566. }
  567. return str;
  568. error:
  569. xclose(dirfd);
  570. llist_traverse(todo, free);
  571. llist_traverse(done, free);
  572. return 0;
  573. }
  574. void xchdir(char *path)
  575. {
  576. if (chdir(path)) perror_exit("chdir '%s'", path);
  577. }
  578. void xchroot(char *path)
  579. {
  580. if (chroot(path)) error_exit("chroot '%s'", path);
  581. xchdir("/");
  582. }
  583. struct passwd *xgetpwuid(uid_t uid)
  584. {
  585. struct passwd *pwd = getpwuid(uid);
  586. if (!pwd) error_exit("bad uid %ld", (long)uid);
  587. return pwd;
  588. }
  589. struct group *xgetgrgid(gid_t gid)
  590. {
  591. struct group *group = getgrgid(gid);
  592. if (!group) perror_exit("gid %ld", (long)gid);
  593. return group;
  594. }
  595. unsigned xgetuid(char *name)
  596. {
  597. struct passwd *up = getpwnam(name);
  598. char *s = 0;
  599. long uid;
  600. if (up) return up->pw_uid;
  601. uid = estrtol(name, &s, 10);
  602. if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
  603. error_exit("bad user '%s'", name);
  604. }
  605. unsigned xgetgid(char *name)
  606. {
  607. struct group *gr = getgrnam(name);
  608. char *s = 0;
  609. long gid;
  610. if (gr) return gr->gr_gid;
  611. gid = estrtol(name, &s, 10);
  612. if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
  613. error_exit("bad group '%s'", name);
  614. }
  615. struct passwd *xgetpwnam(char *name)
  616. {
  617. struct passwd *up = getpwnam(name);
  618. if (!up) perror_exit("user '%s'", name);
  619. return up;
  620. }
  621. struct group *xgetgrnam(char *name)
  622. {
  623. struct group *gr = getgrnam(name);
  624. if (!gr) perror_exit("group '%s'", name);
  625. return gr;
  626. }
  627. // setuid() can fail (for example, too many processes belonging to that user),
  628. // which opens a security hole if the process continues as the original user.
  629. void xsetuser(struct passwd *pwd)
  630. {
  631. if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
  632. || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
  633. }
  634. // This can return null (meaning file not found). It just won't return null
  635. // for memory allocation reasons.
  636. char *xreadlinkat(int dir, char *name)
  637. {
  638. int len, size = 0;
  639. char *buf = 0;
  640. // Grow by 64 byte chunks until it's big enough.
  641. for(;;) {
  642. size +=64;
  643. buf = xrealloc(buf, size);
  644. len = readlinkat(dir, name, buf, size);
  645. if (len<0) {
  646. free(buf);
  647. return 0;
  648. }
  649. if (len<size) {
  650. buf[len]=0;
  651. return buf;
  652. }
  653. }
  654. }
  655. char *xreadlink(char *name)
  656. {
  657. return xreadlinkat(AT_FDCWD, name);
  658. }
  659. char *xreadfile(char *name, char *buf, off_t len)
  660. {
  661. if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
  662. return buf;
  663. }
  664. // The data argument to ioctl() is actually long, but it's usually used as
  665. // a pointer. If you need to feed in a number, do (void *)(long) typecast.
  666. int xioctl(int fd, int request, void *data)
  667. {
  668. int rc;
  669. errno = 0;
  670. rc = ioctl(fd, request, data);
  671. if (rc == -1 && errno) perror_exit("ioctl %x", request);
  672. return rc;
  673. }
  674. // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
  675. // exists and is this executable.
  676. void xpidfile(char *name)
  677. {
  678. char pidfile[256], spid[32];
  679. int i, fd;
  680. pid_t pid;
  681. sprintf(pidfile, "/var/run/%s.pid", name);
  682. // Try three times to open the sucker.
  683. for (i=0; i<3; i++) {
  684. fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
  685. if (fd != -1) break;
  686. // If it already existed, read it. Loop for race condition.
  687. fd = open(pidfile, O_RDONLY);
  688. if (fd == -1) continue;
  689. // Is the old program still there?
  690. spid[xread(fd, spid, sizeof(spid)-1)] = 0;
  691. close(fd);
  692. pid = atoi(spid);
  693. if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
  694. // An else with more sanity checking might be nice here.
  695. }
  696. if (i == 3) error_exit("xpidfile %s", name);
  697. xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
  698. close(fd);
  699. }
  700. // error_exit if we couldn't copy all bytes
  701. long long xsendfile_len(int in, int out, long long bytes)
  702. {
  703. long long len = sendfile_len(in, out, bytes, 0);
  704. if (bytes != -1 && bytes != len) {
  705. if (out == 1 && len<0) xexit();
  706. error_exit("short %s", (len<0) ? "write" : "read");
  707. }
  708. return len;
  709. }
  710. // warn and pad with zeroes if we couldn't copy all bytes
  711. void xsendfile_pad(int in, int out, long long len)
  712. {
  713. len -= xsendfile_len(in, out, len);
  714. if (len) {
  715. perror_msg("short read");
  716. memset(libbuf, 0, sizeof(libbuf));
  717. while (len) {
  718. int i = len>sizeof(libbuf) ? sizeof(libbuf) : len;
  719. xwrite(out, libbuf, i);
  720. len -= i;
  721. }
  722. }
  723. }
  724. // copy all of in to out
  725. long long xsendfile(int in, int out)
  726. {
  727. return xsendfile_len(in, out, -1);
  728. }
  729. double xstrtod(char *s)
  730. {
  731. char *end;
  732. double d;
  733. errno = 0;
  734. d = strtod(s, &end);
  735. if (!errno && *end) errno = E2BIG;
  736. if (errno) perror_exit("strtod %s", s);
  737. return d;
  738. }
  739. // parse fractional seconds with optional s/m/h/d suffix
  740. long xparsetime(char *arg, long zeroes, long *fraction)
  741. {
  742. long l, fr = 0, mask = 1;
  743. char *end;
  744. if (*arg != '.' && !isdigit(*arg)) error_exit("Not a number '%s'", arg);
  745. l = strtoul(arg, &end, 10);
  746. if (*end == '.') {
  747. end++;
  748. while (zeroes--) {
  749. fr *= 10;
  750. mask *= 10;
  751. if (isdigit(*end)) fr += *end++-'0';
  752. }
  753. while (isdigit(*end)) end++;
  754. }
  755. // Parse suffix
  756. if (*end) {
  757. int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *end);
  758. if (i == -1 || *(end+1)) error_exit("Unknown suffix '%s'", end);
  759. l *= ismhd[i];
  760. fr *= ismhd[i];
  761. l += fr/mask;
  762. fr %= mask;
  763. }
  764. if (fraction) *fraction = fr;
  765. return l;
  766. }
  767. long long xparsemillitime(char *arg)
  768. {
  769. long l, ll;
  770. l = xparsetime(arg, 3, &ll);
  771. return (l*1000LL)+ll;
  772. }
  773. void xparsetimespec(char *arg, struct timespec *ts)
  774. {
  775. ts->tv_sec = xparsetime(arg, 9, &ts->tv_nsec);
  776. }
  777. // Compile a regular expression into a regex_t
  778. void xregcomp(regex_t *preg, char *regex, int cflags)
  779. {
  780. int rc;
  781. // BSD regex implementations don't support the empty regex (which isn't
  782. // allowed in the POSIX grammar), but glibc does. Fake it for BSD.
  783. if (!*regex) {
  784. regex = "()";
  785. cflags |= REG_EXTENDED;
  786. }
  787. if ((rc = regcomp(preg, regex, cflags))) {
  788. regerror(rc, preg, libbuf, sizeof(libbuf));
  789. error_exit("bad regex '%s': %s", regex, libbuf);
  790. }
  791. }
  792. char *xtzset(char *new)
  793. {
  794. char *old = getenv("TZ");
  795. if (old) old = xstrdup(old);
  796. if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
  797. tzset();
  798. return old;
  799. }
  800. // Set a signal handler
  801. void xsignal_flags(int signal, void *handler, int flags)
  802. {
  803. struct sigaction *sa = (void *)libbuf;
  804. memset(sa, 0, sizeof(struct sigaction));
  805. sa->sa_handler = handler;
  806. sa->sa_flags = flags;
  807. if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
  808. }
  809. void xsignal(int signal, void *handler)
  810. {
  811. xsignal_flags(signal, handler, 0);
  812. }
  813. time_t xvali_date(struct tm *tm, char *str)
  814. {
  815. time_t t;
  816. if (tm && (unsigned)tm->tm_sec<=60 && (unsigned)tm->tm_min<=59
  817. && (unsigned)tm->tm_hour<=23 && tm->tm_mday && (unsigned)tm->tm_mday<=31
  818. && (unsigned)tm->tm_mon<=11 && (t = mktime(tm)) != -1) return t;
  819. error_exit("bad date %s", str);
  820. }
  821. // Parse date string (relative to current *t). Sets time_t and nanoseconds.
  822. void xparsedate(char *str, time_t *t, unsigned *nano, int endian)
  823. {
  824. struct tm tm;
  825. time_t now = *t;
  826. int len = 0, i = 0;
  827. long long ll;
  828. // Formats with seconds come first. Posix can't agree on whether 12 digits
  829. // has year before (touch -t) or year after (date), so support both.
  830. char *s = str, *p, *oldtz = 0, *formats[] = {"%Y-%m-%d %T", "%Y-%m-%dT%T",
  831. "%a %b %e %H:%M:%S %Z %Y", // date(1) output format in POSIX/C locale.
  832. "%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M", "%m%d%H%M",
  833. endian ? "%m%d%H%M%y" : "%y%m%d%H%M",
  834. endian ? "%m%d%H%M%C%y" : "%C%y%m%d%H%M"};
  835. *nano = 0;
  836. // Parse @UNIXTIME[.FRACTION]
  837. if (1 == sscanf(s, "@%lld%n", &ll, &len)) {
  838. if (*(s+=len)=='.') for (len = 0, s++; len<9; len++) {
  839. *nano *= 10;
  840. if (isdigit(*s)) *nano += *s++-'0';
  841. }
  842. // Can't be sure t is 64 bit (yet) for %lld above
  843. *t = ll;
  844. if (!*s) return;
  845. xvali_date(0, str);
  846. }
  847. // Try each format
  848. for (i = 0; i<ARRAY_LEN(formats); i++) {
  849. localtime_r(&now, &tm);
  850. tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
  851. tm.tm_isdst = -endian;
  852. if ((p = strptime(s, formats[i], &tm))) {
  853. // Handle optional fractional seconds.
  854. if (*p == '.') {
  855. p++;
  856. // If format didn't already specify seconds, grab seconds
  857. if (i>2) {
  858. len = 0;
  859. sscanf(p, "%2u%n", &tm.tm_sec, &len);
  860. p += len;
  861. }
  862. // nanoseconds
  863. for (len = 0; len<9; len++) {
  864. *nano *= 10;
  865. if (isdigit(*p)) *nano += *p++-'0';
  866. }
  867. }
  868. // Handle optional Z or +HH[[:]MM] timezone
  869. while (isspace(*p)) p++;
  870. if (*p && strchr("Z+-", *p)) {
  871. unsigned uu[3] = {0}, n = 0, nn = 0;
  872. char *tz = 0, sign = *p++;
  873. if (sign == 'Z') tz = "UTC0";
  874. else if (0<sscanf(p, " %u%n : %u%n : %u%n", uu,&n,uu+1,&nn,uu+2,&nn)) {
  875. if (n>2) {
  876. uu[1] += uu[0]%100;
  877. uu[0] /= 100;
  878. }
  879. if (n>nn) nn = n;
  880. if (!nn) continue;
  881. // flip sign because POSIX UTC offsets are backwards
  882. sprintf(tz = libbuf, "UTC%c%02u:%02u:%02u", "+-"[sign=='+'],
  883. uu[0], uu[1], uu[2]);
  884. p += nn;
  885. }
  886. if (!oldtz) {
  887. oldtz = getenv("TZ");
  888. if (oldtz) oldtz = xstrdup(oldtz);
  889. }
  890. if (tz) setenv("TZ", tz, 1);
  891. }
  892. while (isspace(*p)) p++;
  893. if (!*p) break;
  894. }
  895. }
  896. // Sanity check field ranges
  897. *t = xvali_date((i!=ARRAY_LEN(formats)) ? &tm : 0, str);
  898. if (oldtz) setenv("TZ", oldtz, 1);
  899. free(oldtz);
  900. }
  901. // Return line of text from file. Strips trailing newline (if any).
  902. char *xgetline(FILE *fp)
  903. {
  904. char *new = 0;
  905. size_t len = 0;
  906. long ll;
  907. errno = 0;
  908. if (1>(ll = getline(&new, &len, fp))) {
  909. if (errno && errno != EINTR) perror_msg("getline");
  910. new = 0;
  911. } else if (new[ll-1] == '\n') new[--ll] = 0;
  912. return new;
  913. }
  914. time_t xmktime(struct tm *tm, int utc)
  915. {
  916. char *old_tz = utc ? xtzset("UTC0") : 0;
  917. time_t result;
  918. if ((result = mktime(tm)) < 0) error_exit("mktime");
  919. if (utc) {
  920. free(xtzset(old_tz));
  921. free(old_tz);
  922. }
  923. return result;
  924. }