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(src);
26 if (len+strlen(dest)+1 > size)
27 error_exit("'%s%s' > %ld bytes", dest, src, (long)size);
28 strcpy(dest+len, src);
33 if (toys.rebound) longjmp(*toys.rebound, 1);
34 if (fflush(NULL) || ferror(stdout))
35 if (!toys.exitval) perror_msg("write");
39 // Die unless we can allocate memory.
40 void *xmalloc(size_t size)
42 void *ret = malloc(size);
43 if (!ret) error_exit("xmalloc(%ld)", (long)size);
48 // Die unless we can allocate prezeroed memory.
49 void *xzalloc(size_t size)
51 void *ret = xmalloc(size);
56 // Die unless we can change the size of an existing allocation, possibly
57 // moving it. (Notice different arguments from libc function.)
58 void *xrealloc(void *ptr, size_t size)
60 ptr = realloc(ptr, size);
61 if (!ptr) error_exit("xrealloc");
66 // Die unless we can allocate a copy of this many bytes of string.
67 char *xstrndup(char *s, size_t n)
69 char *ret = strndup(s, ++n);
71 if (!ret) error_exit("xstrndup");
77 // Die unless we can allocate a copy of this string.
78 char *xstrdup(char *s)
80 return xstrndup(s, strlen(s));
83 // Die unless we can allocate enough space to sprintf() into.
84 char *xmprintf(char *format, ...)
94 len = vsnprintf(0, 0, format, va);
98 // Allocate and do the sprintf()
100 vsnprintf(ret, len, format, va2);
106 void xprintf(char *format, ...)
109 va_start(va, format);
113 if (fflush(stdout) || ferror(stdout)) perror_exit("write");
118 if (EOF == puts(s) || fflush(stdout) || ferror(stdout)) perror_exit("write");
123 if (EOF == fputc(c, stdout) || fflush(stdout) || ferror(stdout))
124 perror_exit("write");
129 if (fflush(stdout) || ferror(stdout)) perror_exit("write");;
132 // This is called through the XVFORK macro because parent/child of vfork
133 // share a stack, so child returning from a function would stomp the return
134 // address parent would need. Solution: make vfork() an argument so processes
135 // diverge before function gets called.
136 pid_t xvforkwrap(pid_t pid)
138 if (pid == -1) perror_exit("vfork");
140 // Signal to xexec() and friends that we vforked so can't recurse
146 // Die unless we can exec argv[] (or run builtin command). Note that anything
147 // with a path isn't a builtin, so /bin/sh won't match the builtin sh.
148 void xexec(char **argv)
150 // Only recurse to builtin when we have multiplexer and !vfork context.
151 if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE && toys.stacktop) toy_exec(argv);
152 execvp(argv[0], argv);
154 perror_msg("exec %s", argv[0]);
156 if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
160 // Spawn child process, capturing stdin/stdout.
161 // argv[]: command to exec. If null, child re-runs original program with
162 // toys.stacktop zeroed.
163 // pipes[2]: stdin, stdout of new process, only allocated if zero on way in,
164 // pass NULL to skip pipe allocation entirely.
165 // return: pid of child process
166 pid_t xpopen_both(char **argv, int *pipes)
168 int cestnepasun[4], pid;
170 // Make the pipes? Note this won't set either pipe to 0 because if fds are
171 // allocated in order and if fd0 was free it would go to cestnepasun[0]
173 for (pid = 0; pid < 2; pid++) {
174 if (pipes[pid] != 0) continue;
175 if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
176 pipes[pid] = cestnepasun[pid+1];
181 if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
182 // Dance of the stdin/stdout redirection.
184 // if we had no stdin/out, pipe handles could overlap, so test for it
185 // and free up potentially overlapping pipe handles before reuse
186 if (pipes[1] != -1) close(cestnepasun[2]);
187 if (pipes[0] != -1) {
188 close(cestnepasun[1]);
189 if (cestnepasun[0]) {
190 dup2(cestnepasun[0], 0);
191 close(cestnepasun[0]);
194 if (pipes[1] != -1) {
195 dup2(cestnepasun[3], 1);
196 dup2(cestnepasun[3], 2);
197 if (cestnepasun[3] > 2 || !cestnepasun[3]) close(cestnepasun[3]);
200 if (argv) xexec(argv);
202 // In fork() case, force recursion because we know it's us.
203 if (CFG_TOYBOX_FORK) {
204 toy_init(toys.which, toys.argv);
206 toys.which->toy_main();
208 // In vfork() case, exec /proc/self/exe with high bit of first letter set
209 // to tell main() we reentered.
211 char *s = "/proc/self/exe";
213 // We did a nommu-friendly vfork but must exec to continue.
214 // setting high bit of argv[0][0] to let new process know
224 if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
226 if (pipes[0] != -1) close(cestnepasun[0]);
227 if (pipes[1] != -1) close(cestnepasun[3]);
233 // Wait for child process to exit, then return adjusted exit code.
234 int xwaitpid(pid_t pid)
238 while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
240 return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+127;
243 int xpclose_both(pid_t pid, int *pipes)
250 return xwaitpid(pid);
253 // Wrapper to xpopen with a pipe for just one of stdin/stdout
254 pid_t xpopen(char **argv, int *pipe, int stdout)
260 pid = xpopen_both(argv, pipes);
261 *pipe = pid ? pipes[!!stdout] : -1;
266 int xpclose(pid_t pid, int pipe)
270 return xpclose_both(pid, 0);
273 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
274 int xrun(char **argv)
276 return xpclose_both(xpopen_both(argv, 0), 0);
279 void xaccess(char *path, int flags)
281 if (access(path, flags)) perror_exit("Can't access '%s'", path);
284 // Die unless we can delete a file. (File must exist to be deleted.)
285 void xunlink(char *path)
287 if (unlink(path)) perror_exit("unlink '%s'", path);
290 // Die unless we can open/create a file, returning file descriptor.
291 int xcreate(char *path, int flags, int mode)
293 int fd = open(path, flags^O_CLOEXEC, mode);
294 if (fd == -1) perror_exit_raw(path);
298 // Die unless we can open a file, returning file descriptor.
299 int xopen(char *path, int flags)
301 return xcreate(path, flags, 0);
306 if (close(fd)) perror_exit("xclose");
313 if (fd == -1) perror_exit("xdup");
318 FILE *xfdopen(int fd, char *mode)
320 FILE *f = fdopen(fd, mode);
322 if (!f) perror_exit("xfdopen");
327 // Die unless we can open/create a file, returning FILE *.
328 FILE *xfopen(char *path, char *mode)
330 FILE *f = fopen(path, mode);
331 if (!f) perror_exit("No file %s", path);
335 // Die if there's an error other than EOF.
336 size_t xread(int fd, void *buf, size_t len)
338 ssize_t ret = read(fd, buf, len);
339 if (ret < 0) perror_exit("xread");
344 void xreadall(int fd, void *buf, size_t len)
346 if (len != readall(fd, buf, len)) perror_exit("xreadall");
349 // There's no xwriteall(), just xwrite(). When we read, there may or may not
350 // be more data waiting. When we write, there is data and it had better go
353 void xwrite(int fd, void *buf, size_t len)
355 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
358 // Die if lseek fails, probably due to being called on a pipe.
360 off_t xlseek(int fd, off_t offset, int whence)
362 offset = lseek(fd, offset, whence);
363 if (offset<0) perror_exit("lseek");
370 char *buf = getcwd(NULL, 0);
371 if (!buf) perror_exit("xgetcwd");
376 void xstat(char *path, struct stat *st)
378 if(stat(path, st)) perror_exit("Can't stat %s", path);
381 // Cannonicalize path, even to file with one or more missing components at end.
382 // if exact, require last path component to exist
383 char *xabspath(char *path, int exact)
385 struct string_list *todo, *done = 0;
386 int try = 9999, dirfd = open("/", 0);;
387 char buf[4096], *ret;
389 // If this isn't an absolute path, start with cwd.
391 char *temp = xgetcwd();
393 splitpath(path, splitpath(temp, &todo));
395 } else splitpath(path, &todo);
397 // Iterate through path components
399 struct string_list *new = llist_pop(&todo), **tail;
407 // Removable path componenents.
408 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
413 if (done) free(llist_pop(&done));
417 // Is this a symlink?
418 } else len=readlinkat(dirfd, new->str, buf, 4096);
420 if (len>4095) goto error;
425 // For .. just move dirfd
427 // Not a symlink: add to linked list, move dirfd, fail if error
428 if ((exact || todo) && errno != EINVAL) goto error;
431 if (errno == EINVAL && !todo) break;
434 fd = openat(dirfd, s, 0);
435 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
441 // If this symlink is to an absolute path, discard existing resolved path
444 llist_traverse(done, free);
447 dirfd = open("/", 0);
451 // prepend components of new path. Note symlink to "/" will leave new NULL
452 tail = splitpath(buf, &new);
454 // symlink to "/" will return null and leave tail alone
462 // At this point done has the path, in reverse order. Reverse list while
463 // calculating buffer length.
467 struct string_list *temp = llist_pop(&done);;
470 try += strlen(temp->str);
475 // Assemble return buffer
481 if (try>1) ret[try++] = '/';
482 try = stpcpy(ret+try, todo->str) - ret;
483 free(llist_pop(&todo));
490 llist_traverse(todo, free);
491 llist_traverse(done, free);
496 void xchdir(char *path)
498 if (chdir(path)) error_exit("chdir '%s'", path);
501 void xchroot(char *path)
503 if (chroot(path)) error_exit("chroot '%s'", path);
507 struct passwd *xgetpwuid(uid_t uid)
509 struct passwd *pwd = getpwuid(uid);
510 if (!pwd) error_exit("bad uid %ld", (long)uid);
514 struct group *xgetgrgid(gid_t gid)
516 struct group *group = getgrgid(gid);
518 if (!group) perror_exit("gid %ld", (long)gid);
522 struct passwd *xgetpwnamid(char *user)
524 struct passwd *up = getpwnam(user);
530 uid = estrtol(user, &s, 10);
531 if (!errno && s && !*s) up = getpwuid(uid);
533 if (!up) perror_exit("user '%s'", user);
538 struct group *xgetgrnamid(char *group)
540 struct group *gr = getgrnam(group);
546 gid = estrtol(group, &s, 10);
547 if (!errno && s && !*s) gr = getgrgid(gid);
549 if (!gr) perror_exit("group '%s'", group);
554 struct passwd *xgetpwnam(char *name)
556 struct passwd *up = getpwnam(name);
558 if (!up) perror_exit("user '%s'", name);
562 struct group *xgetgrnam(char *name)
564 struct group *gr = getgrnam(name);
566 if (!gr) perror_exit("group '%s'", name);
570 // setuid() can fail (for example, too many processes belonging to that user),
571 // which opens a security hole if the process continues as the original user.
573 void xsetuser(struct passwd *pwd)
575 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
576 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
579 // This can return null (meaning file not found). It just won't return null
580 // for memory allocation reasons.
581 char *xreadlink(char *name)
586 // Grow by 64 byte chunks until it's big enough.
589 buf = xrealloc(buf, size);
590 len = readlink(name, buf, size);
603 char *xreadfile(char *name, char *buf, off_t len)
605 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
610 int xioctl(int fd, int request, void *data)
615 rc = ioctl(fd, request, data);
616 if (rc == -1 && errno) perror_exit("ioctl %x", request);
621 // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
622 // exists and is this executable.
623 void xpidfile(char *name)
625 char pidfile[256], spid[32];
629 sprintf(pidfile, "/var/run/%s.pid", name);
630 // Try three times to open the sucker.
631 for (i=0; i<3; i++) {
632 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
635 // If it already existed, read it. Loop for race condition.
636 fd = open(pidfile, O_RDONLY);
637 if (fd == -1) continue;
639 // Is the old program still there?
640 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
643 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
645 // An else with more sanity checking might be nice here.
648 if (i == 3) error_exit("xpidfile %s", name);
650 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
654 // Copy the rest of in to out and close both files.
656 void xsendfile(int in, int out)
662 len = xread(in, libbuf, sizeof(libbuf));
664 xwrite(out, libbuf, len);
668 // parse fractional seconds with optional s/m/h/d suffix
669 long xparsetime(char *arg, long units, long *fraction)
674 if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
675 else l = strtoul(arg, &arg, 10);
679 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
681 if (i == -1) error_exit("Unknown suffix '%c'", *arg);
682 if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
686 if (CFG_TOYBOX_FLOAT) {
688 if (fraction) *fraction = units*(d-l);
689 } else if (fraction) *fraction = 0;
694 // Compile a regular expression into a regex_t
695 void xregcomp(regex_t *preg, char *regex, int cflags)
697 int rc = regcomp(preg, regex, cflags);
700 regerror(rc, preg, libbuf, sizeof(libbuf));
701 error_exit("xregcomp: %s", libbuf);
705 char *xtzset(char *new)
707 char *old = getenv("TZ");
709 if (old) old = xstrdup(old);
710 if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
716 // Set a signal handler
717 void xsignal(int signal, void *handler)
719 struct sigaction *sa = (void *)libbuf;
721 memset(sa, 0, sizeof(struct sigaction));
722 sa->sa_handler = handler;
724 if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);