xwrap.c 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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 && 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. // Move file descriptor above stdin/stdout/stderr, using /dev/null to consume
  377. // old one. (We should never be called with stdin/stdout/stderr closed, but...)
  378. int notstdio(int fd)
  379. {
  380. if (fd<0) return fd;
  381. while (fd<3) {
  382. int fd2 = xdup(fd);
  383. close(fd);
  384. xopen_stdio("/dev/null", O_RDWR);
  385. fd = fd2;
  386. }
  387. return fd;
  388. }
  389. void xrename(char *from, char *to)
  390. {
  391. if (rename(from, to)) perror_exit("rename %s -> %s", from, to);
  392. }
  393. int xtempfile(char *name, char **tempname)
  394. {
  395. int fd;
  396. *tempname = xmprintf("%s%s", name, "XXXXXX");
  397. if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
  398. return fd;
  399. }
  400. // Create a file but don't return stdin/stdout/stderr
  401. int xcreate(char *path, int flags, int mode)
  402. {
  403. return notstdio(xcreate_stdio(path, flags, mode));
  404. }
  405. // Open a file descriptor NOT in stdin/stdout/stderr
  406. int xopen(char *path, int flags)
  407. {
  408. return notstdio(xopen_stdio(path, flags));
  409. }
  410. // Open read only, treating "-" as a synonym for stdin, defaulting to warn only
  411. int openro(char *path, int flags)
  412. {
  413. if (!strcmp(path, "-")) return 0;
  414. return xopen(path, flags^WARN_ONLY);
  415. }
  416. // Open read only, treating "-" as a synonym for stdin.
  417. int xopenro(char *path)
  418. {
  419. return openro(path, O_RDONLY|WARN_ONLY);
  420. }
  421. FILE *xfdopen(int fd, char *mode)
  422. {
  423. FILE *f = fdopen(fd, mode);
  424. if (!f) perror_exit("xfdopen");
  425. return f;
  426. }
  427. // Die unless we can open/create a file, returning FILE *.
  428. FILE *xfopen(char *path, char *mode)
  429. {
  430. FILE *f = fopen(path, mode);
  431. if (!f) perror_exit("No file %s", path);
  432. return f;
  433. }
  434. // Die if there's an error other than EOF.
  435. size_t xread(int fd, void *buf, size_t len)
  436. {
  437. ssize_t ret = read(fd, buf, len);
  438. if (ret < 0) perror_exit("xread");
  439. return ret;
  440. }
  441. void xreadall(int fd, void *buf, size_t len)
  442. {
  443. if (len != readall(fd, buf, len)) perror_exit("xreadall");
  444. }
  445. // There's no xwriteall(), just xwrite(). When we read, there may or may not
  446. // be more data waiting. When we write, there is data and it had better go
  447. // somewhere.
  448. void xwrite(int fd, void *buf, size_t len)
  449. {
  450. if (len != writeall(fd, buf, len)) perror_exit("xwrite");
  451. }
  452. // Die if lseek fails, probably due to being called on a pipe.
  453. off_t xlseek(int fd, off_t offset, int whence)
  454. {
  455. offset = lseek(fd, offset, whence);
  456. if (offset<0) perror_exit("lseek");
  457. return offset;
  458. }
  459. char *xgetcwd(void)
  460. {
  461. char *buf = getcwd(NULL, 0);
  462. if (!buf) perror_exit("xgetcwd");
  463. return buf;
  464. }
  465. void xstat(char *path, struct stat *st)
  466. {
  467. if(stat(path, st)) perror_exit("Can't stat %s", path);
  468. }
  469. // Canonicalize path, even to file with one or more missing components at end.
  470. // Returns allocated string for pathname or NULL if doesn't exist. Flags are:
  471. // ABS_PATH:path to last component must exist ABS_FILE: whole path must exist
  472. // ABS_KEEP:keep symlinks in path ABS_LAST: keep symlink at end of path
  473. char *xabspath(char *path, int flags)
  474. {
  475. struct string_list *todo, *done = 0, *new, **tail;
  476. int fd, track, len, try = 9999, dirfd = -1, missing = 0;
  477. char *str;
  478. // If the last file must exist, path to it must exist.
  479. if (flags&ABS_FILE) flags |= ABS_PATH;
  480. // If we don't resolve path's symlinks, don't resolve last symlink.
  481. if (flags&ABS_KEEP) flags |= ABS_LAST;
  482. // If this isn't an absolute path, start with cwd or $PWD.
  483. if (*path != '/') {
  484. if ((flags & ABS_KEEP) && (str = getenv("PWD")))
  485. splitpath(path, splitpath(str, &todo));
  486. else {
  487. splitpath(path, splitpath(str = xgetcwd(), &todo));
  488. free(str);
  489. }
  490. } else splitpath(path, &todo);
  491. // Iterate through path components in todo, prepend processed ones to done.
  492. while (todo) {
  493. // break out of endless symlink loops
  494. if (!try--) {
  495. errno = ELOOP;
  496. goto error;
  497. }
  498. // Remove . or .. component, tracking dirfd back up tree as necessary
  499. str = (new = llist_pop(&todo))->str;
  500. // track dirfd if this component must exist or we're resolving symlinks
  501. track = ((flags>>!todo) & (ABS_PATH|ABS_KEEP)) ^ ABS_KEEP;
  502. if (!done && track) dirfd = open("/", O_PATH);
  503. if (*str=='.' && !str[1+((fd = str[1])=='.')]) {
  504. free(new);
  505. if (fd) {
  506. if (done) free(llist_pop(&done));
  507. if (missing) missing--;
  508. else if (track) {
  509. if (-1 == (fd = openat(dirfd, "..", O_PATH))) goto error;
  510. close(dirfd);
  511. dirfd = fd;
  512. }
  513. }
  514. continue;
  515. }
  516. // Is this a symlink?
  517. if (flags & (ABS_KEEP<<!todo)) len = 0, errno = EINVAL;
  518. else len = readlinkat(dirfd, str, libbuf, sizeof(libbuf));
  519. if (len>4095) goto error;
  520. // Not a symlink: add to linked list, move dirfd, fail if error
  521. if (len<1) {
  522. new->next = done;
  523. done = new;
  524. if (errno == ENOENT && !(flags & (ABS_PATH<<!todo))) missing++;
  525. else if (errno != EINVAL && (flags & (ABS_PATH<<!todo))) goto error;
  526. else if (track) {
  527. if (-1 == (fd = openat(dirfd, new->str, O_PATH))) goto error;
  528. close(dirfd);
  529. dirfd = fd;
  530. }
  531. continue;
  532. }
  533. // If this symlink is to an absolute path, discard existing resolved path
  534. libbuf[len] = 0;
  535. if (*libbuf == '/') {
  536. llist_traverse(done, free);
  537. done = 0;
  538. close(dirfd);
  539. dirfd = -1;
  540. }
  541. free(new);
  542. // prepend components of new path. Note symlink to "/" will leave new = NULL
  543. tail = splitpath(libbuf, &new);
  544. // symlink to "/" will return null and leave tail alone
  545. if (new) {
  546. *tail = todo;
  547. todo = new;
  548. }
  549. }
  550. xclose(dirfd);
  551. // At this point done has the path, in reverse order. Reverse list
  552. // (into todo) while calculating buffer length.
  553. try = 2;
  554. while (done) {
  555. struct string_list *temp = llist_pop(&done);
  556. if (todo) try++;
  557. try += strlen(temp->str);
  558. temp->next = todo;
  559. todo = temp;
  560. }
  561. // Assemble return buffer
  562. *(str = xmalloc(try)) = '/';
  563. str[try = 1] = 0;
  564. while (todo) {
  565. if (try>1) str[try++] = '/';
  566. try = stpcpy(str+try, todo->str) - str;
  567. free(llist_pop(&todo));
  568. }
  569. return str;
  570. error:
  571. xclose(dirfd);
  572. llist_traverse(todo, free);
  573. llist_traverse(done, free);
  574. return 0;
  575. }
  576. void xchdir(char *path)
  577. {
  578. if (chdir(path)) perror_exit("chdir '%s'", path);
  579. }
  580. void xchroot(char *path)
  581. {
  582. if (chroot(path)) error_exit("chroot '%s'", path);
  583. xchdir("/");
  584. }
  585. struct passwd *xgetpwuid(uid_t uid)
  586. {
  587. struct passwd *pwd = getpwuid(uid);
  588. if (!pwd) error_exit("bad uid %ld", (long)uid);
  589. return pwd;
  590. }
  591. struct group *xgetgrgid(gid_t gid)
  592. {
  593. struct group *group = getgrgid(gid);
  594. if (!group) perror_exit("gid %ld", (long)gid);
  595. return group;
  596. }
  597. unsigned xgetuid(char *name)
  598. {
  599. struct passwd *up = getpwnam(name);
  600. char *s = 0;
  601. long uid;
  602. if (up) return up->pw_uid;
  603. uid = estrtol(name, &s, 10);
  604. if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
  605. error_exit("bad user '%s'", name);
  606. }
  607. unsigned xgetgid(char *name)
  608. {
  609. struct group *gr = getgrnam(name);
  610. char *s = 0;
  611. long gid;
  612. if (gr) return gr->gr_gid;
  613. gid = estrtol(name, &s, 10);
  614. if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
  615. error_exit("bad group '%s'", name);
  616. }
  617. struct passwd *xgetpwnam(char *name)
  618. {
  619. struct passwd *up = getpwnam(name);
  620. if (!up) perror_exit("user '%s'", name);
  621. return up;
  622. }
  623. struct group *xgetgrnam(char *name)
  624. {
  625. struct group *gr = getgrnam(name);
  626. if (!gr) perror_exit("group '%s'", name);
  627. return gr;
  628. }
  629. // setuid() can fail (for example, too many processes belonging to that user),
  630. // which opens a security hole if the process continues as the original user.
  631. void xsetuser(struct passwd *pwd)
  632. {
  633. if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
  634. || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
  635. }
  636. // This can return null (meaning file not found). It just won't return null
  637. // for memory allocation reasons.
  638. char *xreadlinkat(int dir, char *name)
  639. {
  640. int len, size = 0;
  641. char *buf = 0;
  642. // Grow by 64 byte chunks until it's big enough.
  643. for(;;) {
  644. size +=64;
  645. buf = xrealloc(buf, size);
  646. len = readlinkat(dir, name, buf, size);
  647. if (len<0) {
  648. free(buf);
  649. return 0;
  650. }
  651. if (len<size) {
  652. buf[len]=0;
  653. return buf;
  654. }
  655. }
  656. }
  657. char *xreadlink(char *name)
  658. {
  659. return xreadlinkat(AT_FDCWD, name);
  660. }
  661. char *xreadfile(char *name, char *buf, off_t len)
  662. {
  663. if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
  664. return buf;
  665. }
  666. // The data argument to ioctl() is actually long, but it's usually used as
  667. // a pointer. If you need to feed in a number, do (void *)(long) typecast.
  668. int xioctl(int fd, int request, void *data)
  669. {
  670. int rc;
  671. errno = 0;
  672. rc = ioctl(fd, request, data);
  673. if (rc == -1 && errno) perror_exit("ioctl %x", request);
  674. return rc;
  675. }
  676. // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
  677. // exists and is this executable.
  678. void xpidfile(char *name)
  679. {
  680. char pidfile[256], spid[32];
  681. int i, fd;
  682. pid_t pid;
  683. sprintf(pidfile, "/var/run/%s.pid", name);
  684. // Try three times to open the sucker.
  685. for (i=0; i<3; i++) {
  686. fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
  687. if (fd != -1) break;
  688. // If it already existed, read it. Loop for race condition.
  689. fd = open(pidfile, O_RDONLY);
  690. if (fd == -1) continue;
  691. // Is the old program still there?
  692. spid[xread(fd, spid, sizeof(spid)-1)] = 0;
  693. close(fd);
  694. pid = atoi(spid);
  695. if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
  696. // An else with more sanity checking might be nice here.
  697. }
  698. if (i == 3) error_exit("xpidfile %s", name);
  699. xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
  700. close(fd);
  701. }
  702. // error_exit if we couldn't copy all bytes
  703. long long xsendfile_len(int in, int out, long long bytes)
  704. {
  705. long long len = sendfile_len(in, out, bytes, 0);
  706. if (bytes != -1 && bytes != len) {
  707. if (out == 1 && len<0) xexit();
  708. error_exit("short %s", (len<0) ? "write" : "read");
  709. }
  710. return len;
  711. }
  712. // warn and pad with zeroes if we couldn't copy all bytes
  713. void xsendfile_pad(int in, int out, long long len)
  714. {
  715. len -= xsendfile_len(in, out, len);
  716. if (len) {
  717. perror_msg("short read");
  718. memset(libbuf, 0, sizeof(libbuf));
  719. while (len) {
  720. int i = len>sizeof(libbuf) ? sizeof(libbuf) : len;
  721. xwrite(out, libbuf, i);
  722. len -= i;
  723. }
  724. }
  725. }
  726. // copy all of in to out
  727. long long xsendfile(int in, int out)
  728. {
  729. return xsendfile_len(in, out, -1);
  730. }
  731. double xstrtod(char *s)
  732. {
  733. char *end;
  734. double d;
  735. errno = 0;
  736. d = strtod(s, &end);
  737. if (!errno && *end) errno = E2BIG;
  738. if (errno) perror_exit("strtod %s", s);
  739. return d;
  740. }
  741. // parse fractional seconds with optional s/m/h/d suffix
  742. long xparsetime(char *arg, long zeroes, long *fraction)
  743. {
  744. long l, fr = 0, mask = 1;
  745. char *end;
  746. if (*arg != '.' && !isdigit(*arg)) error_exit("Not a number '%s'", arg);
  747. l = strtoul(arg, &end, 10);
  748. if (*end == '.') {
  749. end++;
  750. while (zeroes--) {
  751. fr *= 10;
  752. mask *= 10;
  753. if (isdigit(*end)) fr += *end++-'0';
  754. }
  755. while (isdigit(*end)) end++;
  756. }
  757. // Parse suffix
  758. if (*end) {
  759. int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *end);
  760. if (i == -1 || *(end+1)) error_exit("Unknown suffix '%s'", end);
  761. l *= ismhd[i];
  762. fr *= ismhd[i];
  763. l += fr/mask;
  764. fr %= mask;
  765. }
  766. if (fraction) *fraction = fr;
  767. return l;
  768. }
  769. long long xparsemillitime(char *arg)
  770. {
  771. long l, ll;
  772. l = xparsetime(arg, 3, &ll);
  773. return (l*1000LL)+ll;
  774. }
  775. void xparsetimespec(char *arg, struct timespec *ts)
  776. {
  777. ts->tv_sec = xparsetime(arg, 9, &ts->tv_nsec);
  778. }
  779. // Compile a regular expression into a regex_t
  780. void xregcomp(regex_t *preg, char *regex, int cflags)
  781. {
  782. int rc;
  783. // BSD regex implementations don't support the empty regex (which isn't
  784. // allowed in the POSIX grammar), but glibc does. Fake it for BSD.
  785. if (!*regex) {
  786. regex = "()";
  787. cflags |= REG_EXTENDED;
  788. }
  789. if ((rc = regcomp(preg, regex, cflags))) {
  790. regerror(rc, preg, libbuf, sizeof(libbuf));
  791. error_exit("bad regex '%s': %s", regex, libbuf);
  792. }
  793. }
  794. char *xtzset(char *new)
  795. {
  796. char *old = getenv("TZ");
  797. if (old) old = xstrdup(old);
  798. if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
  799. tzset();
  800. return old;
  801. }
  802. // Set a signal handler
  803. void xsignal_flags(int signal, void *handler, int flags)
  804. {
  805. struct sigaction *sa = (void *)libbuf;
  806. memset(sa, 0, sizeof(struct sigaction));
  807. sa->sa_handler = handler;
  808. sa->sa_flags = flags;
  809. if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
  810. }
  811. void xsignal(int signal, void *handler)
  812. {
  813. xsignal_flags(signal, handler, 0);
  814. }
  815. time_t xvali_date(struct tm *tm, char *str)
  816. {
  817. time_t t;
  818. if (tm && (unsigned)tm->tm_sec<=60 && (unsigned)tm->tm_min<=59
  819. && (unsigned)tm->tm_hour<=23 && tm->tm_mday && (unsigned)tm->tm_mday<=31
  820. && (unsigned)tm->tm_mon<=11 && (t = mktime(tm)) != -1) return t;
  821. error_exit("bad date %s", str);
  822. }
  823. // Parse date string (relative to current *t). Sets time_t and nanoseconds.
  824. void xparsedate(char *str, time_t *t, unsigned *nano, int endian)
  825. {
  826. struct tm tm;
  827. time_t now = *t;
  828. int len = 0, i = 0;
  829. long long ll;
  830. // Formats with seconds come first. Posix can't agree on whether 12 digits
  831. // has year before (touch -t) or year after (date), so support both.
  832. char *s = str, *p, *oldtz = 0, *formats[] = {"%Y-%m-%d %T", "%Y-%m-%dT%T",
  833. "%a %b %e %H:%M:%S %Z %Y", // date(1) output format in POSIX/C locale.
  834. "%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M", "%m%d%H%M",
  835. endian ? "%m%d%H%M%y" : "%y%m%d%H%M",
  836. endian ? "%m%d%H%M%C%y" : "%C%y%m%d%H%M"};
  837. *nano = 0;
  838. // Parse @UNIXTIME[.FRACTION]
  839. if (1 == sscanf(s, "@%lld%n", &ll, &len)) {
  840. if (*(s+=len)=='.') for (len = 0, s++; len<9; len++) {
  841. *nano *= 10;
  842. if (isdigit(*s)) *nano += *s++-'0';
  843. }
  844. // Can't be sure t is 64 bit (yet) for %lld above
  845. *t = ll;
  846. if (!*s) return;
  847. xvali_date(0, str);
  848. }
  849. // Try each format
  850. for (i = 0; i<ARRAY_LEN(formats); i++) {
  851. localtime_r(&now, &tm);
  852. tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
  853. tm.tm_isdst = -endian;
  854. if ((p = strptime(s, formats[i], &tm))) {
  855. // Handle optional fractional seconds.
  856. if (*p == '.') {
  857. p++;
  858. // If format didn't already specify seconds, grab seconds
  859. if (i>2) {
  860. len = 0;
  861. sscanf(p, "%2u%n", &tm.tm_sec, &len);
  862. p += len;
  863. }
  864. // nanoseconds
  865. for (len = 0; len<9; len++) {
  866. *nano *= 10;
  867. if (isdigit(*p)) *nano += *p++-'0';
  868. }
  869. }
  870. // Handle optional Z or +HH[[:]MM] timezone
  871. while (isspace(*p)) p++;
  872. if (*p && strchr("Z+-", *p)) {
  873. unsigned uu[3] = {0}, n = 0, nn = 0;
  874. char *tz = 0, sign = *p++;
  875. if (sign == 'Z') tz = "UTC0";
  876. else if (0<sscanf(p, " %u%n : %u%n : %u%n", uu,&n,uu+1,&nn,uu+2,&nn)) {
  877. if (n>2) {
  878. uu[1] += uu[0]%100;
  879. uu[0] /= 100;
  880. }
  881. if (n>nn) nn = n;
  882. if (!nn) continue;
  883. // flip sign because POSIX UTC offsets are backwards
  884. sprintf(tz = libbuf, "UTC%c%02u:%02u:%02u", "+-"[sign=='+'],
  885. uu[0], uu[1], uu[2]);
  886. p += nn;
  887. }
  888. if (!oldtz) {
  889. oldtz = getenv("TZ");
  890. if (oldtz) oldtz = xstrdup(oldtz);
  891. }
  892. if (tz) setenv("TZ", tz, 1);
  893. }
  894. while (isspace(*p)) p++;
  895. if (!*p) break;
  896. }
  897. }
  898. // Sanity check field ranges
  899. *t = xvali_date((i!=ARRAY_LEN(formats)) ? &tm : 0, str);
  900. if (oldtz) setenv("TZ", oldtz, 1);
  901. free(oldtz);
  902. }
  903. // Return line of text from file. Strips trailing newline (if any).
  904. char *xgetline(FILE *fp)
  905. {
  906. char *new = 0;
  907. size_t len = 0;
  908. long ll;
  909. errno = 0;
  910. if (1>(ll = getline(&new, &len, fp))) {
  911. if (errno && errno != EINTR) perror_msg("getline");
  912. new = 0;
  913. } else if (new[ll-1] == '\n') new[--ll] = 0;
  914. return new;
  915. }
  916. time_t xmktime(struct tm *tm, int utc)
  917. {
  918. char *old_tz = utc ? xtzset("UTC0") : 0;
  919. time_t result;
  920. if ((result = mktime(tm)) < 0) error_exit("mktime");
  921. if (utc) {
  922. free(xtzset(old_tz));
  923. free(old_tz);
  924. }
  925. return result;
  926. }