blob: 7e495cafcc2676a81dcfdb689fd36d32e17291bd [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.
148// pipes[]: stdin, stdout of new process. If null, block and wait for child.
149// return: pid of child process
150pid_t xpopen(char **argv, int *pipes)
151{
152 int cestnepasun[4], pid;
153
154 // Make the pipes?
155 if (pipes) {
156 if (pipe(cestnepasun) || pipe(cestnepasun+2)) perror_exit("pipe");
157 pipes[0] = cestnepasun[1];
158 pipes[1] = cestnepasun[2];
159 }
160
161 // Child process
162 if (!(pid = xfork())) {
163 // Dance of the stdin/stdout redirection.
164 if (pipes) {
165 close(cestnepasun[1]);
166 close(cestnepasun[2]);
167 // if we had no stdin/out, pipe handles could overlap, so test for that
168 if (cestnepasun[0]) {
169 dup2(cestnepasun[0], 0);
170 close(cestnepasun[0]);
171 }
172 dup2(cestnepasun[3], 1);
173 dup2(cestnepasun[3], 2);
174 if (cestnepasun[3] > 2) close(cestnepasun[3]);
175 }
176 if (argv) {
177 if (CFG_TOYBOX) toy_exec(argv);
178 execvp(argv[0], argv);
179 _exit(127);
180 }
181 return 0;
182
183 // Parent process
184 } else {
185 if (pipes) {
186 close(cestnepasun[0]);
187 close(cestnepasun[3]);
188 }
189
190 return pid;
191 }
192}
193
194int xpclose(pid_t pid, int *pipes)
195{
196 int rc = 127;
197
198 if (pipes) {
199 close(pipes[0]);
200 close(pipes[1]);
201 }
202 waitpid(pid, &rc, 0);
203
204 return WIFEXITED(rc) ? WEXITSTATUS(rc) : WTERMSIG(rc) + 127;
205}
206
Rob Landleyd3904932013-07-16 00:04:56 -0500207void xaccess(char *path, int flags)
208{
209 if (access(path, flags)) perror_exit("Can't access '%s'", path);
210}
211
212// Die unless we can delete a file. (File must exist to be deleted.)
213void xunlink(char *path)
214{
215 if (unlink(path)) perror_exit("unlink '%s'", path);
216}
217
218// Die unless we can open/create a file, returning file descriptor.
219int xcreate(char *path, int flags, int mode)
220{
221 int fd = open(path, flags, mode);
222 if (fd == -1) perror_exit("%s", path);
223 return fd;
224}
225
226// Die unless we can open a file, returning file descriptor.
227int xopen(char *path, int flags)
228{
229 return xcreate(path, flags, 0);
230}
231
232void xclose(int fd)
233{
234 if (close(fd)) perror_exit("xclose");
235}
236
237int xdup(int fd)
238{
239 if (fd != -1) {
240 fd = dup(fd);
241 if (fd == -1) perror_exit("xdup");
242 }
243 return fd;
244}
245
Rob Landley1aa75112013-08-07 12:19:51 -0500246FILE *xfdopen(int fd, char *mode)
247{
248 FILE *f = fdopen(fd, mode);
249
250 if (!f) perror_exit("xfdopen");
251
252 return f;
253}
254
Rob Landleyd3904932013-07-16 00:04:56 -0500255// Die unless we can open/create a file, returning FILE *.
256FILE *xfopen(char *path, char *mode)
257{
258 FILE *f = fopen(path, mode);
259 if (!f) perror_exit("No file %s", path);
260 return f;
261}
262
263// Die if there's an error other than EOF.
264size_t xread(int fd, void *buf, size_t len)
265{
266 ssize_t ret = read(fd, buf, len);
267 if (ret < 0) perror_exit("xread");
268
269 return ret;
270}
271
272void xreadall(int fd, void *buf, size_t len)
273{
274 if (len != readall(fd, buf, len)) perror_exit("xreadall");
275}
276
277// There's no xwriteall(), just xwrite(). When we read, there may or may not
278// be more data waiting. When we write, there is data and it had better go
279// somewhere.
280
281void xwrite(int fd, void *buf, size_t len)
282{
283 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
284}
285
286// Die if lseek fails, probably due to being called on a pipe.
287
288off_t xlseek(int fd, off_t offset, int whence)
289{
290 offset = lseek(fd, offset, whence);
291 if (offset<0) perror_exit("lseek");
292
293 return offset;
294}
295
296char *xgetcwd(void)
297{
298 char *buf = getcwd(NULL, 0);
299 if (!buf) perror_exit("xgetcwd");
300
301 return buf;
302}
303
304void xstat(char *path, struct stat *st)
305{
306 if(stat(path, st)) perror_exit("Can't stat %s", path);
307}
308
309// Cannonicalize path, even to file with one or more missing components at end.
310// if exact, require last path component to exist
311char *xabspath(char *path, int exact)
312{
313 struct string_list *todo, *done = 0;
314 int try = 9999, dirfd = open("/", 0);;
315 char buf[4096], *ret;
316
317 // If this isn't an absolute path, start with cwd.
318 if (*path != '/') {
319 char *temp = xgetcwd();
320
321 splitpath(path, splitpath(temp, &todo));
322 free(temp);
323 } else splitpath(path, &todo);
324
325 // Iterate through path components
326 while (todo) {
327 struct string_list *new = llist_pop(&todo), **tail;
328 ssize_t len;
329
330 if (!try--) {
331 errno = ELOOP;
332 goto error;
333 }
334
335 // Removable path componenents.
336 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
337 int x = new->str[1];
338
339 free(new);
340 if (x) {
341 if (done) free(llist_pop(&done));
342 len = 0;
343 } else continue;
344
345 // Is this a symlink?
346 } else len=readlinkat(dirfd, new->str, buf, 4096);
347
348 if (len>4095) goto error;
349 if (len<1) {
350 int fd;
351 char *s = "..";
352
353 // For .. just move dirfd
354 if (len) {
355 // Not a symlink: add to linked list, move dirfd, fail if error
356 if ((exact || todo) && errno != EINVAL) goto error;
357 new->next = done;
358 done = new;
359 if (errno == EINVAL && !todo) break;
360 s = new->str;
361 }
362 fd = openat(dirfd, s, 0);
363 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
364 close(dirfd);
365 dirfd = fd;
366 continue;
367 }
368
369 // If this symlink is to an absolute path, discard existing resolved path
370 buf[len] = 0;
371 if (*buf == '/') {
372 llist_traverse(done, free);
373 done=0;
374 close(dirfd);
375 dirfd = open("/", 0);
376 }
377 free(new);
378
379 // prepend components of new path. Note symlink to "/" will leave new NULL
380 tail = splitpath(buf, &new);
381
382 // symlink to "/" will return null and leave tail alone
383 if (new) {
384 *tail = todo;
385 todo = new;
386 }
387 }
388 close(dirfd);
389
390 // At this point done has the path, in reverse order. Reverse list while
391 // calculating buffer length.
392
393 try = 2;
394 while (done) {
395 struct string_list *temp = llist_pop(&done);;
396
397 if (todo) try++;
398 try += strlen(temp->str);
399 temp->next = todo;
400 todo = temp;
401 }
402
403 // Assemble return buffer
404
405 ret = xmalloc(try);
406 *ret = '/';
407 ret [try = 1] = 0;
408 while (todo) {
409 if (try>1) ret[try++] = '/';
410 try = stpcpy(ret+try, todo->str) - ret;
411 free(llist_pop(&todo));
412 }
413
414 return ret;
415
416error:
417 close(dirfd);
418 llist_traverse(todo, free);
419 llist_traverse(done, free);
420
421 return NULL;
422}
423
424// Resolve all symlinks, returning malloc() memory.
425char *xrealpath(char *path)
426{
427 char *new = realpath(path, NULL);
428 if (!new) perror_exit("realpath '%s'", path);
429 return new;
430}
431
432void xchdir(char *path)
433{
434 if (chdir(path)) error_exit("chdir '%s'", path);
435}
436
Rob Landleyafba5b82013-12-23 06:49:38 -0600437void xchroot(char *path)
438{
439 if (chroot(path)) error_exit("chroot '%s'", path);
440 xchdir("/");
441}
442
Rob Landley9e44a582013-11-28 20:18:04 -0600443struct passwd *xgetpwuid(uid_t uid)
444{
445 struct passwd *pwd = getpwuid(uid);
Rob Landley5ec4ab32013-11-28 21:06:15 -0600446 if (!pwd) error_exit("bad uid %ld", (long)uid);
Rob Landley9e44a582013-11-28 20:18:04 -0600447 return pwd;
448}
449
450struct group *xgetgrgid(gid_t gid)
451{
452 struct group *group = getgrgid(gid);
Rob Landley5ec4ab32013-11-28 21:06:15 -0600453 if (!group) error_exit("bad gid %ld", (long)gid);
Rob Landley9e44a582013-11-28 20:18:04 -0600454 return group;
455}
456
Rob Landley5ec4ab32013-11-28 21:06:15 -0600457struct passwd *xgetpwnam(char *name)
458{
459 struct passwd *up = getpwnam(name);
460 if (!up) error_exit("bad user '%s'", name);
461 return up;
462}
463
Rob Landleyafba5b82013-12-23 06:49:38 -0600464// setuid() can fail (for example, too many processes belonging to that user),
465// which opens a security hole if the process continues as the original user.
466
467void xsetuser(struct passwd *pwd)
468{
469 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
470 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
471}
472
Rob Landleyd3904932013-07-16 00:04:56 -0500473// This can return null (meaning file not found). It just won't return null
474// for memory allocation reasons.
475char *xreadlink(char *name)
476{
477 int len, size = 0;
478 char *buf = 0;
479
480 // Grow by 64 byte chunks until it's big enough.
481 for(;;) {
482 size +=64;
483 buf = xrealloc(buf, size);
484 len = readlink(name, buf, size);
485
486 if (len<0) {
487 free(buf);
488 return 0;
489 }
490 if (len<size) {
491 buf[len]=0;
492 return buf;
493 }
494 }
495}
496
Rob Landleydc373172013-12-27 18:45:01 -0600497char *xreadfile(char *name, char *buf, off_t len)
Rob Landleyd3904932013-07-16 00:04:56 -0500498{
Rob Landleydc373172013-12-27 18:45:01 -0600499 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
500
Rob Landleyd3904932013-07-16 00:04:56 -0500501 return buf;
502}
503
504int xioctl(int fd, int request, void *data)
505{
506 int rc;
507
508 errno = 0;
509 rc = ioctl(fd, request, data);
510 if (rc == -1 && errno) perror_exit("ioctl %x", request);
511
512 return rc;
513}
514
515// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
516// exists and is this executable.
517void xpidfile(char *name)
518{
519 char pidfile[256], spid[32];
520 int i, fd;
521 pid_t pid;
522
523 sprintf(pidfile, "/var/run/%s.pid", name);
524 // Try three times to open the sucker.
525 for (i=0; i<3; i++) {
Felix Jandadccfb2a2013-08-26 21:55:33 +0200526 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
Rob Landleyd3904932013-07-16 00:04:56 -0500527 if (fd != -1) break;
528
529 // If it already existed, read it. Loop for race condition.
530 fd = open(pidfile, O_RDONLY);
531 if (fd == -1) continue;
532
533 // Is the old program still there?
534 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
535 close(fd);
536 pid = atoi(spid);
Rob Landley46e8e1d2013-09-06 04:45:36 -0500537 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
Rob Landleyd3904932013-07-16 00:04:56 -0500538
539 // An else with more sanity checking might be nice here.
540 }
541
542 if (i == 3) error_exit("xpidfile %s", name);
543
544 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
545 close(fd);
546}
547
548// Copy the rest of in to out and close both files.
549
550void xsendfile(int in, int out)
551{
552 long len;
553 char buf[4096];
554
555 if (in<0) return;
556 for (;;) {
557 len = xread(in, buf, 4096);
558 if (len<1) break;
559 xwrite(out, buf, len);
560 }
561}
Rob Landley72756672013-07-17 17:22:46 -0500562
563// parse fractional seconds with optional s/m/h/d suffix
564long xparsetime(char *arg, long units, long *fraction)
565{
566 double d;
567 long l;
568
569 if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
570 else l = strtoul(arg, &arg, 10);
571
572 // Parse suffix
573 if (*arg) {
574 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
575
576 if (i == -1) error_exit("Unknown suffix '%c'", *arg);
577 if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
578 else l *= ismhd[i];
579 }
580
581 if (CFG_TOYBOX_FLOAT) {
582 l = (long)d;
583 if (fraction) *fraction = units*(d-l);
584 } else if (fraction) *fraction = 0;
585
586 return l;
587}
Rob Landley5b405822014-03-29 18:11:00 -0500588
589// Compile a regular expression into a regex_t
590void xregcomp(regex_t *preg, char *regex, int cflags)
591{
592 int rc = regcomp(preg, regex, cflags);
593
594 if (rc) {
595 regerror(rc, preg, libbuf, sizeof(libbuf));
596 error_exit("xregcomp: %s", libbuf);
597 }
598}