1 /* xwrap.c - wrappers around existing library functions.
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.
7 * Copyright 2006 Rob Landley <rob@landley.net>
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.)
16 void xstrncpy(char *dest, char *src, size_t size)
18 if (strlen(src)+1 > size) error_exit("'%s' > %ld bytes", src, (long)size);
22 void xstrncat(char *dest, char *src, size_t size)
24 long len = strlen(dest);
26 if (len+strlen(src)+1 > size)
27 error_exit("'%s%s' > %ld bytes", dest, src, (long)size);
28 strcpy(dest+len, src);
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.
40 if (toys.rebound) siglongjmp(*toys.rebound, 1);
47 // Call toys.xexit functions in reverse order added.
49 // This is typecasting xexit->arg to a function pointer,then calling it.
50 // Using the invalid signal number 0 lets the signal handlers distinguish
51 // an actual signal from a regular exit.
52 ((void (*)(int))(toys.xexit->arg))(0);
54 free(llist_pop(&toys.xexit));
56 if (fflush(NULL) || ferror(stdout))
57 if (!toys.exitval) perror_msg("write");
61 void *xmmap(void *addr, size_t length, int prot, int flags, int fd, off_t off)
63 void *ret = mmap(addr, length, prot, flags, fd, off);
64 if (ret == MAP_FAILED) perror_exit("mmap");
68 // Die unless we can allocate memory.
69 void *xmalloc(size_t size)
71 void *ret = malloc(size);
72 if (!ret) error_exit("xmalloc(%ld)", (long)size);
77 // Die unless we can allocate prezeroed memory.
78 void *xzalloc(size_t size)
80 void *ret = xmalloc(size);
85 // Die unless we can change the size of an existing allocation, possibly
86 // moving it. (Notice different arguments from libc function.)
87 void *xrealloc(void *ptr, size_t size)
89 ptr = realloc(ptr, size);
90 if (!ptr) error_exit("xrealloc");
95 // Die unless we can allocate a copy of this many bytes of string.
96 char *xstrndup(char *s, size_t n)
98 char *ret = strndup(s, ++n);
100 if (!ret) error_exit("xstrndup");
106 // Die unless we can allocate a copy of this string.
107 char *xstrdup(char *s)
109 return xstrndup(s, strlen(s));
112 void *xmemdup(void *s, long len)
114 void *ret = xmalloc(len);
120 // Die unless we can allocate enough space to sprintf() into.
121 char *xmprintf(char *format, ...)
127 va_start(va, format);
131 len = vsnprintf(0, 0, format, va);
135 // Allocate and do the sprintf()
137 vsnprintf(ret, len, format, va2);
143 void xprintf(char *format, ...)
146 va_start(va, format);
150 if (fflush(stdout) || ferror(stdout)) perror_exit("write");
155 if (EOF == puts(s) || fflush(stdout) || ferror(stdout)) perror_exit("write");
160 if (EOF == fputc(c, stdout) || fflush(stdout) || ferror(stdout))
161 perror_exit("write");
166 if (fflush(stdout) || ferror(stdout)) perror_exit("write");;
169 // This is called through the XVFORK macro because parent/child of vfork
170 // share a stack, so child returning from a function would stomp the return
171 // address parent would need. Solution: make vfork() an argument so processes
172 // diverge before function gets called.
173 pid_t __attribute__((returns_twice)) xvforkwrap(pid_t pid)
175 if (pid == -1) perror_exit("vfork");
177 // Signal to xexec() and friends that we vforked so can't recurse
183 // Die unless we can exec argv[] (or run builtin command). Note that anything
184 // with a path isn't a builtin, so /bin/sh won't match the builtin sh.
185 void xexec(char **argv)
187 // Only recurse to builtin when we have multiplexer and !vfork context.
188 if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE && toys.stacktop) toy_exec(argv);
189 execvp(argv[0], argv);
191 perror_msg("exec %s", argv[0]);
193 if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
197 // Spawn child process, capturing stdin/stdout.
198 // argv[]: command to exec. If null, child re-runs original program with
199 // toys.stacktop zeroed.
200 // pipes[2]: stdin, stdout of new process, only allocated if zero on way in,
201 // pass NULL to skip pipe allocation entirely.
202 // return: pid of child process
203 pid_t xpopen_both(char **argv, int *pipes)
205 int cestnepasun[4], pid;
207 // Make the pipes? Note this won't set either pipe to 0 because if fds are
208 // allocated in order and if fd0 was free it would go to cestnepasun[0]
210 for (pid = 0; pid < 2; pid++) {
211 if (pipes[pid] != 0) continue;
212 if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
213 pipes[pid] = cestnepasun[pid+1];
218 if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
219 // Dance of the stdin/stdout redirection.
221 // if we had no stdin/out, pipe handles could overlap, so test for it
222 // and free up potentially overlapping pipe handles before reuse
223 if (pipes[1] != -1) close(cestnepasun[2]);
224 if (pipes[0] != -1) {
225 close(cestnepasun[1]);
226 if (cestnepasun[0]) {
227 dup2(cestnepasun[0], 0);
228 close(cestnepasun[0]);
231 if (pipes[1] != -1) {
232 dup2(cestnepasun[3], 1);
233 dup2(cestnepasun[3], 2);
234 if (cestnepasun[3] > 2 || !cestnepasun[3]) close(cestnepasun[3]);
237 if (argv) xexec(argv);
239 // In fork() case, force recursion because we know it's us.
240 if (CFG_TOYBOX_FORK) {
241 toy_init(toys.which, toys.argv);
243 toys.which->toy_main();
245 // In vfork() case, exec /proc/self/exe with high bit of first letter set
246 // to tell main() we reentered.
248 char *s = "/proc/self/exe";
250 // We did a nommu-friendly vfork but must exec to continue.
251 // setting high bit of argv[0][0] to let new process know
261 if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
263 if (pipes[0] != -1) close(cestnepasun[0]);
264 if (pipes[1] != -1) close(cestnepasun[3]);
270 // Wait for child process to exit, then return adjusted exit code.
271 int xwaitpid(pid_t pid)
275 while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
277 return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+127;
280 int xpclose_both(pid_t pid, int *pipes)
287 return xwaitpid(pid);
290 // Wrapper to xpopen with a pipe for just one of stdin/stdout
291 pid_t xpopen(char **argv, int *pipe, int isstdout)
295 pipes[!isstdout] = -1;
296 pipes[!!isstdout] = 0;
297 pid = xpopen_both(argv, pipes);
298 *pipe = pid ? pipes[!!isstdout] : -1;
303 int xpclose(pid_t pid, int pipe)
307 return xpclose_both(pid, 0);
310 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
311 int xrun(char **argv)
313 return xpclose_both(xpopen_both(argv, 0), 0);
316 void xaccess(char *path, int flags)
318 if (access(path, flags)) perror_exit("Can't access '%s'", path);
321 // Die unless we can delete a file. (File must exist to be deleted.)
322 void xunlink(char *path)
324 if (unlink(path)) perror_exit("unlink '%s'", path);
327 // Die unless we can open/create a file, returning file descriptor.
328 // The meaning of O_CLOEXEC is reversed (it defaults on, pass it to disable)
329 // and WARN_ONLY tells us not to exit.
330 int xcreate_stdio(char *path, int flags, int mode)
332 int fd = open(path, (flags^O_CLOEXEC)&~WARN_ONLY, mode);
334 if (fd == -1) ((mode&WARN_ONLY) ? perror_msg_raw : perror_exit_raw)(path);
338 // Die unless we can open a file, returning file descriptor.
339 int xopen_stdio(char *path, int flags)
341 return xcreate_stdio(path, flags, 0);
346 if (pipe(pp)) perror_exit("xpipe");
351 if (close(fd)) perror_exit("xclose");
358 if (fd == -1) perror_exit("xdup");
363 // Move file descriptor above stdin/stdout/stderr, using /dev/null to consume
364 // old one. (We should never be called with stdin/stdout/stderr closed, but...)
373 xopen_stdio("/dev/null", O_RDWR);
380 // Create a file but don't return stdin/stdout/stderr
381 int xcreate(char *path, int flags, int mode)
383 return notstdio(xcreate_stdio(path, flags, mode));
386 // Open a file descriptor NOT in stdin/stdout/stderr
387 int xopen(char *path, int flags)
389 return notstdio(xopen_stdio(path, flags));
392 // Open read only, treating "-" as a synonym for stdin, defaulting to warn only
393 int openro(char *path, int flags)
395 if (!strcmp(path, "-")) return 0;
397 return xopen(path, flags^WARN_ONLY);
400 // Open read only, treating "-" as a synonym for stdin.
401 int xopenro(char *path)
403 return openro(path, O_RDONLY|WARN_ONLY);
406 FILE *xfdopen(int fd, char *mode)
408 FILE *f = fdopen(fd, mode);
410 if (!f) perror_exit("xfdopen");
415 // Die unless we can open/create a file, returning FILE *.
416 FILE *xfopen(char *path, char *mode)
418 FILE *f = fopen(path, mode);
419 if (!f) perror_exit("No file %s", path);
423 // Die if there's an error other than EOF.
424 size_t xread(int fd, void *buf, size_t len)
426 ssize_t ret = read(fd, buf, len);
427 if (ret < 0) perror_exit("xread");
432 void xreadall(int fd, void *buf, size_t len)
434 if (len != readall(fd, buf, len)) perror_exit("xreadall");
437 // There's no xwriteall(), just xwrite(). When we read, there may or may not
438 // be more data waiting. When we write, there is data and it had better go
441 void xwrite(int fd, void *buf, size_t len)
443 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
446 // Die if lseek fails, probably due to being called on a pipe.
448 off_t xlseek(int fd, off_t offset, int whence)
450 offset = lseek(fd, offset, whence);
451 if (offset<0) perror_exit("lseek");
458 char *buf = getcwd(NULL, 0);
459 if (!buf) perror_exit("xgetcwd");
464 void xstat(char *path, struct stat *st)
466 if(stat(path, st)) perror_exit("Can't stat %s", path);
469 // Cannonicalize path, even to file with one or more missing components at end.
470 // if exact, require last path component to exist
471 char *xabspath(char *path, int exact)
473 struct string_list *todo, *done = 0;
474 int try = 9999, dirfd = open("/", 0);;
477 // If this isn't an absolute path, start with cwd.
479 char *temp = xgetcwd();
481 splitpath(path, splitpath(temp, &todo));
483 } else splitpath(path, &todo);
485 // Iterate through path components
487 struct string_list *new = llist_pop(&todo), **tail;
495 // Removable path componenents.
496 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
501 if (done) free(llist_pop(&done));
505 // Is this a symlink?
506 } else len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
508 if (len>4095) goto error;
513 // For .. just move dirfd
515 // Not a symlink: add to linked list, move dirfd, fail if error
516 if ((exact || todo) && errno != EINVAL) goto error;
519 if (errno == EINVAL && !todo) break;
522 fd = openat(dirfd, s, 0);
523 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
529 // If this symlink is to an absolute path, discard existing resolved path
531 if (*libbuf == '/') {
532 llist_traverse(done, free);
535 dirfd = open("/", 0);
539 // prepend components of new path. Note symlink to "/" will leave new NULL
540 tail = splitpath(libbuf, &new);
542 // symlink to "/" will return null and leave tail alone
550 // At this point done has the path, in reverse order. Reverse list while
551 // calculating buffer length.
555 struct string_list *temp = llist_pop(&done);;
558 try += strlen(temp->str);
563 // Assemble return buffer
569 if (try>1) ret[try++] = '/';
570 try = stpcpy(ret+try, todo->str) - ret;
571 free(llist_pop(&todo));
578 llist_traverse(todo, free);
579 llist_traverse(done, free);
584 void xchdir(char *path)
586 if (chdir(path)) error_exit("chdir '%s'", path);
589 void xchroot(char *path)
591 if (chroot(path)) error_exit("chroot '%s'", path);
595 struct passwd *xgetpwuid(uid_t uid)
597 struct passwd *pwd = getpwuid(uid);
598 if (!pwd) error_exit("bad uid %ld", (long)uid);
602 struct group *xgetgrgid(gid_t gid)
604 struct group *group = getgrgid(gid);
606 if (!group) perror_exit("gid %ld", (long)gid);
610 unsigned xgetuid(char *name)
612 struct passwd *up = getpwnam(name);
616 if (up) return up->pw_uid;
618 uid = estrtol(name, &s, 10);
619 if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
621 error_exit("bad user '%s'", name);
624 unsigned xgetgid(char *name)
626 struct group *gr = getgrnam(name);
630 if (gr) return gr->gr_gid;
632 gid = estrtol(name, &s, 10);
633 if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
635 error_exit("bad group '%s'", name);
638 struct passwd *xgetpwnam(char *name)
640 struct passwd *up = getpwnam(name);
642 if (!up) perror_exit("user '%s'", name);
646 struct group *xgetgrnam(char *name)
648 struct group *gr = getgrnam(name);
650 if (!gr) perror_exit("group '%s'", name);
654 // setuid() can fail (for example, too many processes belonging to that user),
655 // which opens a security hole if the process continues as the original user.
657 void xsetuser(struct passwd *pwd)
659 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
660 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
663 // This can return null (meaning file not found). It just won't return null
664 // for memory allocation reasons.
665 char *xreadlink(char *name)
670 // Grow by 64 byte chunks until it's big enough.
673 buf = xrealloc(buf, size);
674 len = readlink(name, buf, size);
687 char *xreadfile(char *name, char *buf, off_t len)
689 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
694 // The data argument to ioctl() is actually long, but it's usually used as
695 // a pointer. If you need to feed in a number, do (void *)(long) typecast.
696 int xioctl(int fd, int request, void *data)
701 rc = ioctl(fd, request, data);
702 if (rc == -1 && errno) perror_exit("ioctl %x", request);
707 // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
708 // exists and is this executable.
709 void xpidfile(char *name)
711 char pidfile[256], spid[32];
715 sprintf(pidfile, "/var/run/%s.pid", name);
716 // Try three times to open the sucker.
717 for (i=0; i<3; i++) {
718 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
721 // If it already existed, read it. Loop for race condition.
722 fd = open(pidfile, O_RDONLY);
723 if (fd == -1) continue;
725 // Is the old program still there?
726 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
729 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
731 // An else with more sanity checking might be nice here.
734 if (i == 3) error_exit("xpidfile %s", name);
736 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
740 // Copy the rest of in to out and close both files.
742 long long xsendfile(int in, int out)
749 len = xread(in, libbuf, sizeof(libbuf));
751 xwrite(out, libbuf, len);
758 // parse fractional seconds with optional s/m/h/d suffix
759 long xparsetime(char *arg, long units, long *fraction)
764 if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
765 else l = strtoul(arg, &arg, 10);
769 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
771 if (i == -1) error_exit("Unknown suffix '%c'", *arg);
772 if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
776 if (CFG_TOYBOX_FLOAT) {
778 if (fraction) *fraction = units*(d-l);
779 } else if (fraction) *fraction = 0;
784 // Compile a regular expression into a regex_t
785 void xregcomp(regex_t *preg, char *regex, int cflags)
787 int rc = regcomp(preg, regex, cflags);
790 regerror(rc, preg, libbuf, sizeof(libbuf));
791 error_exit("xregcomp: %s", libbuf);
795 char *xtzset(char *new)
797 char *old = getenv("TZ");
799 if (old) old = xstrdup(old);
800 if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
806 // Set a signal handler
807 void xsignal(int signal, void *handler)
809 struct sigaction *sa = (void *)libbuf;
811 memset(sa, 0, sizeof(struct sigaction));
812 sa->sa_handler = handler;
814 if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);