blob: 64b183ff492dacc372df699e46bf9102e5f9a1e9 [file] [log] [blame]
Rob Landleyd3904932013-07-16 00:04:56 -05001/* xwrap.c - wrappers around existing library functions.
2 *
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.
6 *
7 * Copyright 2006 Rob Landley <rob@landley.net>
8 */
9
10#include "toys.h"
11
12// Strcpy with size checking: exit if there's not enough space for the string.
13void xstrncpy(char *dest, char *src, size_t size)
14{
Rob Landley3704f822013-11-02 14:24:54 -050015 if (strlen(src)+1 > size) error_exit("'%s' > %ld bytes", src, (long)size);
Rob Landleyd3904932013-07-16 00:04:56 -050016 strcpy(dest, src);
17}
18
19void xexit(void)
20{
21 if (toys.rebound) longjmp(*toys.rebound, 1);
22 else exit(toys.exitval);
23}
24
25// Die unless we can allocate memory.
26void *xmalloc(size_t size)
27{
28 void *ret = malloc(size);
29 if (!ret) error_exit("xmalloc");
30
31 return ret;
32}
33
34// Die unless we can allocate prezeroed memory.
35void *xzalloc(size_t size)
36{
37 void *ret = xmalloc(size);
38 memset(ret, 0, size);
39 return ret;
40}
41
42// Die unless we can change the size of an existing allocation, possibly
43// moving it. (Notice different arguments from libc function.)
44void *xrealloc(void *ptr, size_t size)
45{
46 ptr = realloc(ptr, size);
47 if (!ptr) error_exit("xrealloc");
48
49 return ptr;
50}
51
52// Die unless we can allocate a copy of this many bytes of string.
53char *xstrndup(char *s, size_t n)
54{
55 char *ret = xmalloc(++n);
56 strncpy(ret, s, n);
57 ret[--n]=0;
58
59 return ret;
60}
61
62// Die unless we can allocate a copy of this string.
63char *xstrdup(char *s)
64{
65 return xstrndup(s, strlen(s));
66}
67
68// Die unless we can allocate enough space to sprintf() into.
Rob Landley59d85e22014-01-16 09:26:50 -060069char *xmprintf(char *format, ...)
Rob Landleyd3904932013-07-16 00:04:56 -050070{
71 va_list va, va2;
72 int len;
73 char *ret;
74
75 va_start(va, format);
76 va_copy(va2, va);
77
78 // How long is it?
79 len = vsnprintf(0, 0, format, va);
80 len++;
81 va_end(va);
82
83 // Allocate and do the sprintf()
84 ret = xmalloc(len);
85 vsnprintf(ret, len, format, va2);
86 va_end(va2);
87
88 return ret;
89}
90
91void xprintf(char *format, ...)
92{
93 va_list va;
94 va_start(va, format);
95
96 vprintf(format, va);
Rob Landleyddbaa712014-05-26 12:25:47 -050097 if (fflush(stdout) || ferror(stdout)) perror_exit("write");
Rob Landleyd3904932013-07-16 00:04:56 -050098}
99
100void xputs(char *s)
101{
Rob Landleyddbaa712014-05-26 12:25:47 -0500102 if (EOF == puts(s) || fflush(stdout) || ferror(stdout)) perror_exit("write");
Rob Landleyd3904932013-07-16 00:04:56 -0500103}
104
105void xputc(char c)
106{
Rob Landleyddbaa712014-05-26 12:25:47 -0500107 if (EOF == fputc(c, stdout) || fflush(stdout) || ferror(stdout))
108 perror_exit("write");
Rob Landleyd3904932013-07-16 00:04:56 -0500109}
110
111void xflush(void)
112{
Rob Landleyddbaa712014-05-26 12:25:47 -0500113 if (fflush(stdout) || ferror(stdout)) perror_exit("write");;
Rob Landleyd3904932013-07-16 00:04:56 -0500114}
115
Rob Landleyd8872c42014-05-31 12:33:24 -0500116pid_t xfork(void)
117{
118 pid_t pid = fork();
119
120 if (pid < 0) perror_exit("fork");
121
122 return pid;
123}
124
Rob Landley72756672013-07-17 17:22:46 -0500125// Call xexec with a chunk of optargs, starting at skip. (You can't just
126// call xexec() directly because toy_init() frees optargs.)
127void xexec_optargs(int skip)
128{
129 char **s = toys.optargs;
130
131 toys.optargs = 0;
132 xexec(s+skip);
133}
134
135
Rob Landleyd3904932013-07-16 00:04:56 -0500136// Die unless we can exec argv[] (or run builtin command). Note that anything
137// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
138void xexec(char **argv)
139{
Rob Landleyd04dc1f2013-08-30 01:53:31 -0500140 if (CFG_TOYBOX) toy_exec(argv);
Rob Landleyd3904932013-07-16 00:04:56 -0500141 execvp(argv[0], argv);
142
143 perror_exit("exec %s", argv[0]);
144}
145
Rob Landley44e68a12014-06-03 06:27:24 -0500146// Spawn child process, capturing stdin/stdout.
147// argv[]: command to exec. If null, child returns to original program.
Rob Landley360d57f2014-09-14 12:29:44 -0500148// pipes[2]: stdin, stdout of new process. If -1 will not have pipe allocated.
Rob Landley44e68a12014-06-03 06:27:24 -0500149// return: pid of child process
Rob Landley360d57f2014-09-14 12:29:44 -0500150pid_t xpopen_both(char **argv, int *pipes)
Rob Landley44e68a12014-06-03 06:27:24 -0500151{
152 int cestnepasun[4], pid;
153
Rob Landley360d57f2014-09-14 12:29:44 -0500154 // Make the pipes? Not this won't set either pipe to 0 because if fds are
155 // allocated in order and if fd0 was free it would go to cestnepasun[0]
Rob Landley44e68a12014-06-03 06:27:24 -0500156 if (pipes) {
Rob Landley360d57f2014-09-14 12:29:44 -0500157 for (pid = 0; pid < 2; pid++) {
158 if (pipes[pid] == -1) continue;
159 if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
160 pipes[pid] = cestnepasun[pid+1];
161 }
Rob Landley44e68a12014-06-03 06:27:24 -0500162 }
163
164 // Child process
165 if (!(pid = xfork())) {
166 // Dance of the stdin/stdout redirection.
167 if (pipes) {
Rob Landley360d57f2014-09-14 12:29:44 -0500168 // if we had no stdin/out, pipe handles could overlap, so test for it
169 // and free up potentially overlapping pipe handles before reuse
170 if (pipes[1] != -1) close(cestnepasun[2]);
171 if (pipes[0] != -1) {
172 close(cestnepasun[1]);
173 if (cestnepasun[0]) {
174 dup2(cestnepasun[0], 0);
175 close(cestnepasun[0]);
176 }
Rob Landley44e68a12014-06-03 06:27:24 -0500177 }
Rob Landley360d57f2014-09-14 12:29:44 -0500178 if (pipes[1] != -1) {
179 dup2(cestnepasun[3], 1);
180 dup2(cestnepasun[3], 2);
181 if (cestnepasun[3] > 2 || !cestnepasun[3]) close(cestnepasun[3]);
182 }
Rob Landley44e68a12014-06-03 06:27:24 -0500183 }
184 if (argv) {
185 if (CFG_TOYBOX) toy_exec(argv);
186 execvp(argv[0], argv);
187 _exit(127);
188 }
189 return 0;
190
Rob Landley44e68a12014-06-03 06:27:24 -0500191 }
Rob Landley360d57f2014-09-14 12:29:44 -0500192
193 // Parent process
194 if (pipes) {
195 if (pipes[0] != -1) close(cestnepasun[0]);
196 if (pipes[1] != -1) close(cestnepasun[3]);
197 }
198
199 return pid;
Rob Landley44e68a12014-06-03 06:27:24 -0500200}
201
Rob Landley360d57f2014-09-14 12:29:44 -0500202int xpclose_both(pid_t pid, int *pipes)
Rob Landley44e68a12014-06-03 06:27:24 -0500203{
204 int rc = 127;
205
206 if (pipes) {
207 close(pipes[0]);
208 close(pipes[1]);
209 }
210 waitpid(pid, &rc, 0);
211
212 return WIFEXITED(rc) ? WEXITSTATUS(rc) : WTERMSIG(rc) + 127;
213}
214
Rob Landley360d57f2014-09-14 12:29:44 -0500215// Wrapper to xpopen with a pipe for just one of stdin/stdout
216pid_t xpopen(char **argv, int *pipe, int stdout)
217{
218 int pipes[2];
219
220 pipe[!stdout] = -1;
221 pipe[!!stdout] = 0;
222
223 return xpopen_both(argv, pipes);
224}
225
226int xpclose(pid_t pid, int pipe)
227{
228 close(pipe);
229
230 return xpclose_both(pid, 0);
231}
232
233// Call xpopen and wait for it to finish, keeping existing stdin/stdout.
234int xrun(char **argv)
235{
236 return xpclose_both(xpopen_both(argv, 0), 0);
237}
238
Rob Landleyd3904932013-07-16 00:04:56 -0500239void xaccess(char *path, int flags)
240{
241 if (access(path, flags)) perror_exit("Can't access '%s'", path);
242}
243
244// Die unless we can delete a file. (File must exist to be deleted.)
245void xunlink(char *path)
246{
247 if (unlink(path)) perror_exit("unlink '%s'", path);
248}
249
250// Die unless we can open/create a file, returning file descriptor.
251int xcreate(char *path, int flags, int mode)
252{
Rob Landleyccb73f82014-07-26 13:27:07 -0500253 int fd = open(path, flags^O_CLOEXEC, mode);
Rob Landleyd3904932013-07-16 00:04:56 -0500254 if (fd == -1) perror_exit("%s", path);
255 return fd;
256}
257
258// Die unless we can open a file, returning file descriptor.
259int xopen(char *path, int flags)
260{
261 return xcreate(path, flags, 0);
262}
263
264void xclose(int fd)
265{
266 if (close(fd)) perror_exit("xclose");
267}
268
269int xdup(int fd)
270{
271 if (fd != -1) {
272 fd = dup(fd);
273 if (fd == -1) perror_exit("xdup");
274 }
275 return fd;
276}
277
Rob Landley1aa75112013-08-07 12:19:51 -0500278FILE *xfdopen(int fd, char *mode)
279{
280 FILE *f = fdopen(fd, mode);
281
282 if (!f) perror_exit("xfdopen");
283
284 return f;
285}
286
Rob Landleyd3904932013-07-16 00:04:56 -0500287// Die unless we can open/create a file, returning FILE *.
288FILE *xfopen(char *path, char *mode)
289{
290 FILE *f = fopen(path, mode);
291 if (!f) perror_exit("No file %s", path);
292 return f;
293}
294
295// Die if there's an error other than EOF.
296size_t xread(int fd, void *buf, size_t len)
297{
298 ssize_t ret = read(fd, buf, len);
299 if (ret < 0) perror_exit("xread");
300
301 return ret;
302}
303
304void xreadall(int fd, void *buf, size_t len)
305{
306 if (len != readall(fd, buf, len)) perror_exit("xreadall");
307}
308
309// There's no xwriteall(), just xwrite(). When we read, there may or may not
310// be more data waiting. When we write, there is data and it had better go
311// somewhere.
312
313void xwrite(int fd, void *buf, size_t len)
314{
315 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
316}
317
318// Die if lseek fails, probably due to being called on a pipe.
319
320off_t xlseek(int fd, off_t offset, int whence)
321{
322 offset = lseek(fd, offset, whence);
323 if (offset<0) perror_exit("lseek");
324
325 return offset;
326}
327
328char *xgetcwd(void)
329{
330 char *buf = getcwd(NULL, 0);
331 if (!buf) perror_exit("xgetcwd");
332
333 return buf;
334}
335
336void xstat(char *path, struct stat *st)
337{
338 if(stat(path, st)) perror_exit("Can't stat %s", path);
339}
340
341// Cannonicalize path, even to file with one or more missing components at end.
342// if exact, require last path component to exist
343char *xabspath(char *path, int exact)
344{
345 struct string_list *todo, *done = 0;
346 int try = 9999, dirfd = open("/", 0);;
347 char buf[4096], *ret;
348
349 // If this isn't an absolute path, start with cwd.
350 if (*path != '/') {
351 char *temp = xgetcwd();
352
353 splitpath(path, splitpath(temp, &todo));
354 free(temp);
355 } else splitpath(path, &todo);
356
357 // Iterate through path components
358 while (todo) {
359 struct string_list *new = llist_pop(&todo), **tail;
360 ssize_t len;
361
362 if (!try--) {
363 errno = ELOOP;
364 goto error;
365 }
366
367 // Removable path componenents.
368 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
369 int x = new->str[1];
370
371 free(new);
372 if (x) {
373 if (done) free(llist_pop(&done));
374 len = 0;
375 } else continue;
376
377 // Is this a symlink?
378 } else len=readlinkat(dirfd, new->str, buf, 4096);
379
380 if (len>4095) goto error;
381 if (len<1) {
382 int fd;
383 char *s = "..";
384
385 // For .. just move dirfd
386 if (len) {
387 // Not a symlink: add to linked list, move dirfd, fail if error
388 if ((exact || todo) && errno != EINVAL) goto error;
389 new->next = done;
390 done = new;
391 if (errno == EINVAL && !todo) break;
392 s = new->str;
393 }
394 fd = openat(dirfd, s, 0);
395 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
396 close(dirfd);
397 dirfd = fd;
398 continue;
399 }
400
401 // If this symlink is to an absolute path, discard existing resolved path
402 buf[len] = 0;
403 if (*buf == '/') {
404 llist_traverse(done, free);
405 done=0;
406 close(dirfd);
407 dirfd = open("/", 0);
408 }
409 free(new);
410
411 // prepend components of new path. Note symlink to "/" will leave new NULL
412 tail = splitpath(buf, &new);
413
414 // symlink to "/" will return null and leave tail alone
415 if (new) {
416 *tail = todo;
417 todo = new;
418 }
419 }
420 close(dirfd);
421
422 // At this point done has the path, in reverse order. Reverse list while
423 // calculating buffer length.
424
425 try = 2;
426 while (done) {
427 struct string_list *temp = llist_pop(&done);;
428
429 if (todo) try++;
430 try += strlen(temp->str);
431 temp->next = todo;
432 todo = temp;
433 }
434
435 // Assemble return buffer
436
437 ret = xmalloc(try);
438 *ret = '/';
439 ret [try = 1] = 0;
440 while (todo) {
441 if (try>1) ret[try++] = '/';
442 try = stpcpy(ret+try, todo->str) - ret;
443 free(llist_pop(&todo));
444 }
445
446 return ret;
447
448error:
449 close(dirfd);
450 llist_traverse(todo, free);
451 llist_traverse(done, free);
452
453 return NULL;
454}
455
Rob Landleyd3904932013-07-16 00:04:56 -0500456void xchdir(char *path)
457{
458 if (chdir(path)) error_exit("chdir '%s'", path);
459}
460
Rob Landleyafba5b82013-12-23 06:49:38 -0600461void xchroot(char *path)
462{
463 if (chroot(path)) error_exit("chroot '%s'", path);
464 xchdir("/");
465}
466
Rob Landley9e44a582013-11-28 20:18:04 -0600467struct passwd *xgetpwuid(uid_t uid)
468{
469 struct passwd *pwd = getpwuid(uid);
Rob Landley5ec4ab32013-11-28 21:06:15 -0600470 if (!pwd) error_exit("bad uid %ld", (long)uid);
Rob Landley9e44a582013-11-28 20:18:04 -0600471 return pwd;
472}
473
474struct group *xgetgrgid(gid_t gid)
475{
476 struct group *group = getgrgid(gid);
Rob Landley4fd07e02014-07-21 19:57:36 -0500477
478 if (!group) perror_exit("gid %ld", (long)gid);
Rob Landley9e44a582013-11-28 20:18:04 -0600479 return group;
480}
481
Rob Landley5ec4ab32013-11-28 21:06:15 -0600482struct passwd *xgetpwnam(char *name)
483{
484 struct passwd *up = getpwnam(name);
Rob Landley4fd07e02014-07-21 19:57:36 -0500485
486 if (!up) perror_exit("user '%s'", name);
Rob Landley5ec4ab32013-11-28 21:06:15 -0600487 return up;
488}
489
Rob Landley60c35c42014-08-03 15:50:10 -0500490struct group *xgetgrnam(char *name)
491{
492 struct group *gr = getgrnam(name);
493
494 if (!gr) perror_exit("group '%s'", name);
495 return gr;
496}
497
Rob Landleyafba5b82013-12-23 06:49:38 -0600498// setuid() can fail (for example, too many processes belonging to that user),
499// which opens a security hole if the process continues as the original user.
500
501void xsetuser(struct passwd *pwd)
502{
503 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
504 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
505}
506
Rob Landleyd3904932013-07-16 00:04:56 -0500507// This can return null (meaning file not found). It just won't return null
508// for memory allocation reasons.
509char *xreadlink(char *name)
510{
511 int len, size = 0;
512 char *buf = 0;
513
514 // Grow by 64 byte chunks until it's big enough.
515 for(;;) {
516 size +=64;
517 buf = xrealloc(buf, size);
518 len = readlink(name, buf, size);
519
520 if (len<0) {
521 free(buf);
522 return 0;
523 }
524 if (len<size) {
525 buf[len]=0;
526 return buf;
527 }
528 }
529}
530
Rob Landleydc373172013-12-27 18:45:01 -0600531char *xreadfile(char *name, char *buf, off_t len)
Rob Landleyd3904932013-07-16 00:04:56 -0500532{
Rob Landleydc373172013-12-27 18:45:01 -0600533 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
534
Rob Landleyd3904932013-07-16 00:04:56 -0500535 return buf;
536}
537
538int xioctl(int fd, int request, void *data)
539{
540 int rc;
541
542 errno = 0;
543 rc = ioctl(fd, request, data);
544 if (rc == -1 && errno) perror_exit("ioctl %x", request);
545
546 return rc;
547}
548
549// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
550// exists and is this executable.
551void xpidfile(char *name)
552{
553 char pidfile[256], spid[32];
554 int i, fd;
555 pid_t pid;
556
557 sprintf(pidfile, "/var/run/%s.pid", name);
558 // Try three times to open the sucker.
559 for (i=0; i<3; i++) {
Felix Jandadccfb2a2013-08-26 21:55:33 +0200560 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
Rob Landleyd3904932013-07-16 00:04:56 -0500561 if (fd != -1) break;
562
563 // If it already existed, read it. Loop for race condition.
564 fd = open(pidfile, O_RDONLY);
565 if (fd == -1) continue;
566
567 // Is the old program still there?
568 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
569 close(fd);
570 pid = atoi(spid);
Rob Landley46e8e1d2013-09-06 04:45:36 -0500571 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
Rob Landleyd3904932013-07-16 00:04:56 -0500572
573 // An else with more sanity checking might be nice here.
574 }
575
576 if (i == 3) error_exit("xpidfile %s", name);
577
578 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
579 close(fd);
580}
581
582// Copy the rest of in to out and close both files.
583
584void xsendfile(int in, int out)
585{
586 long len;
587 char buf[4096];
588
589 if (in<0) return;
590 for (;;) {
591 len = xread(in, buf, 4096);
592 if (len<1) break;
593 xwrite(out, buf, len);
594 }
595}
Rob Landley72756672013-07-17 17:22:46 -0500596
597// parse fractional seconds with optional s/m/h/d suffix
598long xparsetime(char *arg, long units, long *fraction)
599{
600 double d;
601 long l;
602
603 if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
604 else l = strtoul(arg, &arg, 10);
605
606 // Parse suffix
607 if (*arg) {
608 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
609
610 if (i == -1) error_exit("Unknown suffix '%c'", *arg);
611 if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
612 else l *= ismhd[i];
613 }
614
615 if (CFG_TOYBOX_FLOAT) {
616 l = (long)d;
617 if (fraction) *fraction = units*(d-l);
618 } else if (fraction) *fraction = 0;
619
620 return l;
621}
Rob Landley5b405822014-03-29 18:11:00 -0500622
623// Compile a regular expression into a regex_t
624void xregcomp(regex_t *preg, char *regex, int cflags)
625{
626 int rc = regcomp(preg, regex, cflags);
627
628 if (rc) {
629 regerror(rc, preg, libbuf, sizeof(libbuf));
630 error_exit("xregcomp: %s", libbuf);
631 }
632}