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