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");
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 // Die unless we can exec argv[] (or run builtin command). Note that anything
133 // with a path isn't a builtin, so /bin/sh won't match the builtin sh.
134 void xexec(char **argv)
136 if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE) toy_exec(argv);
137 execvp(argv[0], argv);
139 perror_msg("exec %s", argv[0]);
141 if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
145 // Spawn child process, capturing stdin/stdout.
146 // argv[]: command to exec. If null, child returns to original program.
147 // pipes[2]: stdin, stdout of new process. If -1 will not have pipe allocated.
148 // return: pid of child process
149 pid_t xpopen_both(char **argv, int *pipes)
151 int cestnepasun[4], pid;
153 // Make the pipes? Not this won't set either pipe to 0 because if fds are
154 // allocated in order and if fd0 was free it would go to cestnepasun[0]
156 for (pid = 0; pid < 2; pid++) {
157 if (pipes[pid] == -1) continue;
158 if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
159 pipes[pid] = cestnepasun[pid+1];
164 if (!(pid = xfork())) {
165 // Dance of the stdin/stdout redirection.
167 // if we had no stdin/out, pipe handles could overlap, so test for it
168 // and free up potentially overlapping pipe handles before reuse
169 if (pipes[1] != -1) close(cestnepasun[2]);
170 if (pipes[0] != -1) {
171 close(cestnepasun[1]);
172 if (cestnepasun[0]) {
173 dup2(cestnepasun[0], 0);
174 close(cestnepasun[0]);
177 if (pipes[1] != -1) {
178 dup2(cestnepasun[3], 1);
179 dup2(cestnepasun[3], 2);
180 if (cestnepasun[3] > 2 || !cestnepasun[3]) close(cestnepasun[3]);
184 if (CFG_TOYBOX) toy_exec(argv);
185 execvp(argv[0], argv);
194 if (pipes[0] != -1) close(cestnepasun[0]);
195 if (pipes[1] != -1) close(cestnepasun[3]);
201 int xpclose_both(pid_t pid, int *pipes)
209 waitpid(pid, &rc, 0);
211 return WIFEXITED(rc) ? WEXITSTATUS(rc) : WTERMSIG(rc) + 127;
214 // Wrapper to xpopen with a pipe for just one of stdin/stdout
215 pid_t xpopen(char **argv, int *pipe, int stdout)
221 pid = xpopen_both(argv, pipes);
222 *pipe = pid ? pipes[!!stdout] : -1;
227 int xpclose(pid_t pid, int pipe)
231 return xpclose_both(pid, 0);
234 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
235 int xrun(char **argv)
237 return xpclose_both(xpopen_both(argv, 0), 0);
240 void xaccess(char *path, int flags)
242 if (access(path, flags)) perror_exit("Can't access '%s'", path);
245 // Die unless we can delete a file. (File must exist to be deleted.)
246 void xunlink(char *path)
248 if (unlink(path)) perror_exit("unlink '%s'", path);
251 // Die unless we can open/create a file, returning file descriptor.
252 int xcreate(char *path, int flags, int mode)
254 int fd = open(path, flags^O_CLOEXEC, mode);
255 if (fd == -1) perror_exit("%s", path);
259 // Die unless we can open a file, returning file descriptor.
260 int xopen(char *path, int flags)
262 return xcreate(path, flags, 0);
267 if (close(fd)) perror_exit("xclose");
274 if (fd == -1) perror_exit("xdup");
279 FILE *xfdopen(int fd, char *mode)
281 FILE *f = fdopen(fd, mode);
283 if (!f) perror_exit("xfdopen");
288 // Die unless we can open/create a file, returning FILE *.
289 FILE *xfopen(char *path, char *mode)
291 FILE *f = fopen(path, mode);
292 if (!f) perror_exit("No file %s", path);
296 // Die if there's an error other than EOF.
297 size_t xread(int fd, void *buf, size_t len)
299 ssize_t ret = read(fd, buf, len);
300 if (ret < 0) perror_exit("xread");
305 void xreadall(int fd, void *buf, size_t len)
307 if (len != readall(fd, buf, len)) perror_exit("xreadall");
310 // There's no xwriteall(), just xwrite(). When we read, there may or may not
311 // be more data waiting. When we write, there is data and it had better go
314 void xwrite(int fd, void *buf, size_t len)
316 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
319 // Die if lseek fails, probably due to being called on a pipe.
321 off_t xlseek(int fd, off_t offset, int whence)
323 offset = lseek(fd, offset, whence);
324 if (offset<0) perror_exit("lseek");
331 char *buf = getcwd(NULL, 0);
332 if (!buf) perror_exit("xgetcwd");
337 void xstat(char *path, struct stat *st)
339 if(stat(path, st)) perror_exit("Can't stat %s", path);
342 // Cannonicalize path, even to file with one or more missing components at end.
343 // if exact, require last path component to exist
344 char *xabspath(char *path, int exact)
346 struct string_list *todo, *done = 0;
347 int try = 9999, dirfd = open("/", 0);;
348 char buf[4096], *ret;
350 // If this isn't an absolute path, start with cwd.
352 char *temp = xgetcwd();
354 splitpath(path, splitpath(temp, &todo));
356 } else splitpath(path, &todo);
358 // Iterate through path components
360 struct string_list *new = llist_pop(&todo), **tail;
368 // Removable path componenents.
369 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
374 if (done) free(llist_pop(&done));
378 // Is this a symlink?
379 } else len=readlinkat(dirfd, new->str, buf, 4096);
381 if (len>4095) goto error;
386 // For .. just move dirfd
388 // Not a symlink: add to linked list, move dirfd, fail if error
389 if ((exact || todo) && errno != EINVAL) goto error;
392 if (errno == EINVAL && !todo) break;
395 fd = openat(dirfd, s, 0);
396 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
402 // If this symlink is to an absolute path, discard existing resolved path
405 llist_traverse(done, free);
408 dirfd = open("/", 0);
412 // prepend components of new path. Note symlink to "/" will leave new NULL
413 tail = splitpath(buf, &new);
415 // symlink to "/" will return null and leave tail alone
423 // At this point done has the path, in reverse order. Reverse list while
424 // calculating buffer length.
428 struct string_list *temp = llist_pop(&done);;
431 try += strlen(temp->str);
436 // Assemble return buffer
442 if (try>1) ret[try++] = '/';
443 try = stpcpy(ret+try, todo->str) - ret;
444 free(llist_pop(&todo));
451 llist_traverse(todo, free);
452 llist_traverse(done, free);
457 void xchdir(char *path)
459 if (chdir(path)) error_exit("chdir '%s'", path);
462 void xchroot(char *path)
464 if (chroot(path)) error_exit("chroot '%s'", path);
468 struct passwd *xgetpwuid(uid_t uid)
470 struct passwd *pwd = getpwuid(uid);
471 if (!pwd) error_exit("bad uid %ld", (long)uid);
475 struct group *xgetgrgid(gid_t gid)
477 struct group *group = getgrgid(gid);
479 if (!group) perror_exit("gid %ld", (long)gid);
483 struct passwd *xgetpwnamid(char *user)
485 struct passwd *up = getpwnam(user);
491 uid = estrtol(user, &s, 10);
492 if (!errno && s && !*s) up = getpwuid(uid);
494 if (!up) perror_exit("user '%s'", user);
499 struct group *xgetgrnamid(char *group)
501 struct group *gr = getgrnam(group);
507 gid = estrtol(group, &s, 10);
508 if (!errno && s && !*s) gr = getgrgid(gid);
510 if (!gr) perror_exit("group '%s'", group);
515 struct passwd *xgetpwnam(char *name)
517 struct passwd *up = getpwnam(name);
519 if (!up) perror_exit("user '%s'", name);
523 struct group *xgetgrnam(char *name)
525 struct group *gr = getgrnam(name);
527 if (!gr) perror_exit("group '%s'", name);
531 // setuid() can fail (for example, too many processes belonging to that user),
532 // which opens a security hole if the process continues as the original user.
534 void xsetuser(struct passwd *pwd)
536 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
537 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
540 // This can return null (meaning file not found). It just won't return null
541 // for memory allocation reasons.
542 char *xreadlink(char *name)
547 // Grow by 64 byte chunks until it's big enough.
550 buf = xrealloc(buf, size);
551 len = readlink(name, buf, size);
564 char *xreadfile(char *name, char *buf, off_t len)
566 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
571 int xioctl(int fd, int request, void *data)
576 rc = ioctl(fd, request, data);
577 if (rc == -1 && errno) perror_exit("ioctl %x", request);
582 // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
583 // exists and is this executable.
584 void xpidfile(char *name)
586 char pidfile[256], spid[32];
590 sprintf(pidfile, "/var/run/%s.pid", name);
591 // Try three times to open the sucker.
592 for (i=0; i<3; i++) {
593 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
596 // If it already existed, read it. Loop for race condition.
597 fd = open(pidfile, O_RDONLY);
598 if (fd == -1) continue;
600 // Is the old program still there?
601 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
604 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
606 // An else with more sanity checking might be nice here.
609 if (i == 3) error_exit("xpidfile %s", name);
611 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
615 // Copy the rest of in to out and close both files.
617 void xsendfile(int in, int out)
623 len = xread(in, libbuf, sizeof(libbuf));
625 xwrite(out, libbuf, len);
629 // parse fractional seconds with optional s/m/h/d suffix
630 long xparsetime(char *arg, long units, long *fraction)
635 if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
636 else l = strtoul(arg, &arg, 10);
640 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
642 if (i == -1) error_exit("Unknown suffix '%c'", *arg);
643 if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
647 if (CFG_TOYBOX_FLOAT) {
649 if (fraction) *fraction = units*(d-l);
650 } else if (fraction) *fraction = 0;
655 // Compile a regular expression into a regex_t
656 void xregcomp(regex_t *preg, char *regex, int cflags)
658 int rc = regcomp(preg, regex, cflags);
661 regerror(rc, preg, libbuf, sizeof(libbuf));
662 error_exit("xregcomp: %s", libbuf);
666 char *xtzset(char *new)
668 char *tz = getenv("TZ");
670 if (tz) tz = xstrdup(tz);
671 if (setenv("TZ", new, 1)) perror_exit("setenv");
677 // Set a signal handler
678 void xsignal(int signal, void *handler)
680 struct sigaction *sa = (void *)libbuf;
682 memset(sa, 0, sizeof(struct sigaction));
683 sa->sa_handler = handler;
685 if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);