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 // Die unless we can allocate memory.
62 void *xmalloc(size_t size)
64 void *ret = malloc(size);
65 if (!ret) error_exit("xmalloc(%ld)", (long)size);
70 // Die unless we can allocate prezeroed memory.
71 void *xzalloc(size_t size)
73 void *ret = xmalloc(size);
78 // Die unless we can change the size of an existing allocation, possibly
79 // moving it. (Notice different arguments from libc function.)
80 void *xrealloc(void *ptr, size_t size)
82 ptr = realloc(ptr, size);
83 if (!ptr) error_exit("xrealloc");
88 // Die unless we can allocate a copy of this many bytes of string.
89 char *xstrndup(char *s, size_t n)
91 char *ret = strndup(s, ++n);
93 if (!ret) error_exit("xstrndup");
99 // Die unless we can allocate a copy of this string.
100 char *xstrdup(char *s)
102 return xstrndup(s, strlen(s));
105 void *xmemdup(void *s, long len)
107 void *ret = xmalloc(len);
113 // Die unless we can allocate enough space to sprintf() into.
114 char *xmprintf(char *format, ...)
120 va_start(va, format);
124 len = vsnprintf(0, 0, format, va);
128 // Allocate and do the sprintf()
130 vsnprintf(ret, len, format, va2);
136 void xprintf(char *format, ...)
139 va_start(va, format);
143 if (fflush(stdout) || ferror(stdout)) perror_exit("write");
148 if (EOF == puts(s) || fflush(stdout) || ferror(stdout)) perror_exit("write");
153 if (EOF == fputc(c, stdout) || fflush(stdout) || ferror(stdout))
154 perror_exit("write");
159 if (fflush(stdout) || ferror(stdout)) perror_exit("write");;
162 // This is called through the XVFORK macro because parent/child of vfork
163 // share a stack, so child returning from a function would stomp the return
164 // address parent would need. Solution: make vfork() an argument so processes
165 // diverge before function gets called.
166 pid_t xvforkwrap(pid_t pid)
168 if (pid == -1) perror_exit("vfork");
170 // Signal to xexec() and friends that we vforked so can't recurse
176 // Die unless we can exec argv[] (or run builtin command). Note that anything
177 // with a path isn't a builtin, so /bin/sh won't match the builtin sh.
178 void xexec(char **argv)
180 // Only recurse to builtin when we have multiplexer and !vfork context.
181 if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE && toys.stacktop) toy_exec(argv);
182 execvp(argv[0], argv);
184 perror_msg("exec %s", argv[0]);
186 if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
190 // Spawn child process, capturing stdin/stdout.
191 // argv[]: command to exec. If null, child re-runs original program with
192 // toys.stacktop zeroed.
193 // pipes[2]: stdin, stdout of new process, only allocated if zero on way in,
194 // pass NULL to skip pipe allocation entirely.
195 // return: pid of child process
196 pid_t xpopen_both(char **argv, int *pipes)
198 int cestnepasun[4], pid;
200 // Make the pipes? Note this won't set either pipe to 0 because if fds are
201 // allocated in order and if fd0 was free it would go to cestnepasun[0]
203 for (pid = 0; pid < 2; pid++) {
204 if (pipes[pid] != 0) continue;
205 if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
206 pipes[pid] = cestnepasun[pid+1];
211 if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
212 // Dance of the stdin/stdout redirection.
214 // if we had no stdin/out, pipe handles could overlap, so test for it
215 // and free up potentially overlapping pipe handles before reuse
216 if (pipes[1] != -1) close(cestnepasun[2]);
217 if (pipes[0] != -1) {
218 close(cestnepasun[1]);
219 if (cestnepasun[0]) {
220 dup2(cestnepasun[0], 0);
221 close(cestnepasun[0]);
224 if (pipes[1] != -1) {
225 dup2(cestnepasun[3], 1);
226 dup2(cestnepasun[3], 2);
227 if (cestnepasun[3] > 2 || !cestnepasun[3]) close(cestnepasun[3]);
230 if (argv) xexec(argv);
232 // In fork() case, force recursion because we know it's us.
233 if (CFG_TOYBOX_FORK) {
234 toy_init(toys.which, toys.argv);
236 toys.which->toy_main();
238 // In vfork() case, exec /proc/self/exe with high bit of first letter set
239 // to tell main() we reentered.
241 char *s = "/proc/self/exe";
243 // We did a nommu-friendly vfork but must exec to continue.
244 // setting high bit of argv[0][0] to let new process know
254 if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
256 if (pipes[0] != -1) close(cestnepasun[0]);
257 if (pipes[1] != -1) close(cestnepasun[3]);
263 // Wait for child process to exit, then return adjusted exit code.
264 int xwaitpid(pid_t pid)
268 while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
270 return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+127;
273 int xpclose_both(pid_t pid, int *pipes)
280 return xwaitpid(pid);
283 // Wrapper to xpopen with a pipe for just one of stdin/stdout
284 pid_t xpopen(char **argv, int *pipe, int stdout)
290 pid = xpopen_both(argv, pipes);
291 *pipe = pid ? pipes[!!stdout] : -1;
296 int xpclose(pid_t pid, int pipe)
300 return xpclose_both(pid, 0);
303 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
304 int xrun(char **argv)
306 return xpclose_both(xpopen_both(argv, 0), 0);
309 void xaccess(char *path, int flags)
311 if (access(path, flags)) perror_exit("Can't access '%s'", path);
314 // Die unless we can delete a file. (File must exist to be deleted.)
315 void xunlink(char *path)
317 if (unlink(path)) perror_exit("unlink '%s'", path);
320 // Die unless we can open/create a file, returning file descriptor.
321 int xcreate(char *path, int flags, int mode)
323 int fd = open(path, flags^O_CLOEXEC, mode);
324 if (fd == -1) perror_exit_raw(path);
328 // Die unless we can open a file, returning file descriptor.
329 int xopen(char *path, int flags)
331 return xcreate(path, flags, 0);
336 if (pipe(pp)) perror_exit("xpipe");
341 if (close(fd)) perror_exit("xclose");
348 if (fd == -1) perror_exit("xdup");
353 FILE *xfdopen(int fd, char *mode)
355 FILE *f = fdopen(fd, mode);
357 if (!f) perror_exit("xfdopen");
362 // Die unless we can open/create a file, returning FILE *.
363 FILE *xfopen(char *path, char *mode)
365 FILE *f = fopen(path, mode);
366 if (!f) perror_exit("No file %s", path);
370 // Die if there's an error other than EOF.
371 size_t xread(int fd, void *buf, size_t len)
373 ssize_t ret = read(fd, buf, len);
374 if (ret < 0) perror_exit("xread");
379 void xreadall(int fd, void *buf, size_t len)
381 if (len != readall(fd, buf, len)) perror_exit("xreadall");
384 // There's no xwriteall(), just xwrite(). When we read, there may or may not
385 // be more data waiting. When we write, there is data and it had better go
388 void xwrite(int fd, void *buf, size_t len)
390 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
393 // Die if lseek fails, probably due to being called on a pipe.
395 off_t xlseek(int fd, off_t offset, int whence)
397 offset = lseek(fd, offset, whence);
398 if (offset<0) perror_exit("lseek");
405 char *buf = getcwd(NULL, 0);
406 if (!buf) perror_exit("xgetcwd");
411 void xstat(char *path, struct stat *st)
413 if(stat(path, st)) perror_exit("Can't stat %s", path);
416 // Cannonicalize path, even to file with one or more missing components at end.
417 // if exact, require last path component to exist
418 char *xabspath(char *path, int exact)
420 struct string_list *todo, *done = 0;
421 int try = 9999, dirfd = open("/", 0);;
424 // If this isn't an absolute path, start with cwd.
426 char *temp = xgetcwd();
428 splitpath(path, splitpath(temp, &todo));
430 } else splitpath(path, &todo);
432 // Iterate through path components
434 struct string_list *new = llist_pop(&todo), **tail;
442 // Removable path componenents.
443 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
448 if (done) free(llist_pop(&done));
452 // Is this a symlink?
453 } else len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
455 if (len>4095) goto error;
460 // For .. just move dirfd
462 // Not a symlink: add to linked list, move dirfd, fail if error
463 if ((exact || todo) && errno != EINVAL) goto error;
466 if (errno == EINVAL && !todo) break;
469 fd = openat(dirfd, s, 0);
470 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
476 // If this symlink is to an absolute path, discard existing resolved path
478 if (*libbuf == '/') {
479 llist_traverse(done, free);
482 dirfd = open("/", 0);
486 // prepend components of new path. Note symlink to "/" will leave new NULL
487 tail = splitpath(libbuf, &new);
489 // symlink to "/" will return null and leave tail alone
497 // At this point done has the path, in reverse order. Reverse list while
498 // calculating buffer length.
502 struct string_list *temp = llist_pop(&done);;
505 try += strlen(temp->str);
510 // Assemble return buffer
516 if (try>1) ret[try++] = '/';
517 try = stpcpy(ret+try, todo->str) - ret;
518 free(llist_pop(&todo));
525 llist_traverse(todo, free);
526 llist_traverse(done, free);
531 void xchdir(char *path)
533 if (chdir(path)) error_exit("chdir '%s'", path);
536 void xchroot(char *path)
538 if (chroot(path)) error_exit("chroot '%s'", path);
542 struct passwd *xgetpwuid(uid_t uid)
544 struct passwd *pwd = getpwuid(uid);
545 if (!pwd) error_exit("bad uid %ld", (long)uid);
549 struct group *xgetgrgid(gid_t gid)
551 struct group *group = getgrgid(gid);
553 if (!group) perror_exit("gid %ld", (long)gid);
557 struct passwd *xgetpwnamid(char *user)
559 struct passwd *up = getpwnam(user);
565 uid = estrtol(user, &s, 10);
566 if (!errno && s && !*s) up = getpwuid(uid);
568 if (!up) perror_exit("user '%s'", user);
573 struct group *xgetgrnamid(char *group)
575 struct group *gr = getgrnam(group);
581 gid = estrtol(group, &s, 10);
582 if (!errno && s && !*s) gr = getgrgid(gid);
584 if (!gr) perror_exit("group '%s'", group);
589 struct passwd *xgetpwnam(char *name)
591 struct passwd *up = getpwnam(name);
593 if (!up) perror_exit("user '%s'", name);
597 struct group *xgetgrnam(char *name)
599 struct group *gr = getgrnam(name);
601 if (!gr) perror_exit("group '%s'", name);
605 // setuid() can fail (for example, too many processes belonging to that user),
606 // which opens a security hole if the process continues as the original user.
608 void xsetuser(struct passwd *pwd)
610 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
611 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
614 // This can return null (meaning file not found). It just won't return null
615 // for memory allocation reasons.
616 char *xreadlink(char *name)
621 // Grow by 64 byte chunks until it's big enough.
624 buf = xrealloc(buf, size);
625 len = readlink(name, buf, size);
638 char *xreadfile(char *name, char *buf, off_t len)
640 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
645 int xioctl(int fd, int request, void *data)
650 rc = ioctl(fd, request, data);
651 if (rc == -1 && errno) perror_exit("ioctl %x", request);
656 // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
657 // exists and is this executable.
658 void xpidfile(char *name)
660 char pidfile[256], spid[32];
664 sprintf(pidfile, "/var/run/%s.pid", name);
665 // Try three times to open the sucker.
666 for (i=0; i<3; i++) {
667 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
670 // If it already existed, read it. Loop for race condition.
671 fd = open(pidfile, O_RDONLY);
672 if (fd == -1) continue;
674 // Is the old program still there?
675 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
678 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
680 // An else with more sanity checking might be nice here.
683 if (i == 3) error_exit("xpidfile %s", name);
685 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
689 // Copy the rest of in to out and close both files.
691 void xsendfile(int in, int out)
697 len = xread(in, libbuf, sizeof(libbuf));
699 xwrite(out, libbuf, len);
703 // parse fractional seconds with optional s/m/h/d suffix
704 long xparsetime(char *arg, long units, long *fraction)
709 if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
710 else l = strtoul(arg, &arg, 10);
714 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
716 if (i == -1) error_exit("Unknown suffix '%c'", *arg);
717 if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
721 if (CFG_TOYBOX_FLOAT) {
723 if (fraction) *fraction = units*(d-l);
724 } else if (fraction) *fraction = 0;
729 // Compile a regular expression into a regex_t
730 void xregcomp(regex_t *preg, char *regex, int cflags)
732 int rc = regcomp(preg, regex, cflags);
735 regerror(rc, preg, libbuf, sizeof(libbuf));
736 error_exit("xregcomp: %s", libbuf);
740 char *xtzset(char *new)
742 char *old = getenv("TZ");
744 if (old) old = xstrdup(old);
745 if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
751 // Set a signal handler
752 void xsignal(int signal, void *handler)
754 struct sigaction *sa = (void *)libbuf;
756 memset(sa, 0, sizeof(struct sigaction));
757 sa->sa_handler = handler;
759 if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);