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