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