OSDN Git Service

Somebody asked a FAQ on irc, so answer it.
[android-x86/external-toybox.git] / lib / xwrap.c
1 /* 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 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)
17 {
18   if (strlen(src)+1 > size) error_exit("'%s' > %ld bytes", src, (long)size);
19   strcpy(dest, src);
20 }
21
22 void xstrncat(char *dest, char *src, size_t size)
23 {
24   long len = strlen(dest);
25
26   if (len+strlen(src)+1 > size)
27     error_exit("'%s%s' > %ld bytes", dest, src, (long)size);
28   strcpy(dest+len, src);
29 }
30
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.
37
38 void _xexit(void)
39 {
40   if (toys.rebound) siglongjmp(*toys.rebound, 1);
41
42   _exit(toys.exitval);
43 }
44
45 void xexit(void)
46 {
47   // Call toys.xexit functions in reverse order added.
48   while (toys.xexit) {
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);
53
54     free(llist_pop(&toys.xexit));
55   }
56   if (fflush(NULL) || ferror(stdout))
57     if (!toys.exitval) perror_msg("write");
58   _xexit();
59 }
60
61 // Die unless we can allocate memory.
62 void *xmalloc(size_t size)
63 {
64   void *ret = malloc(size);
65   if (!ret) error_exit("xmalloc(%ld)", (long)size);
66
67   return ret;
68 }
69
70 // Die unless we can allocate prezeroed memory.
71 void *xzalloc(size_t size)
72 {
73   void *ret = xmalloc(size);
74   memset(ret, 0, size);
75   return ret;
76 }
77
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)
81 {
82   ptr = realloc(ptr, size);
83   if (!ptr) error_exit("xrealloc");
84
85   return ptr;
86 }
87
88 // Die unless we can allocate a copy of this many bytes of string.
89 char *xstrndup(char *s, size_t n)
90 {
91   char *ret = strndup(s, ++n);
92
93   if (!ret) error_exit("xstrndup");
94   ret[--n] = 0;
95
96   return ret;
97 }
98
99 // Die unless we can allocate a copy of this string.
100 char *xstrdup(char *s)
101 {
102   return xstrndup(s, strlen(s));
103 }
104
105 void *xmemdup(void *s, long len)
106 {
107   void *ret = xmalloc(len);
108   memcpy(ret, s, len);
109
110   return ret;
111 }
112
113 // Die unless we can allocate enough space to sprintf() into.
114 char *xmprintf(char *format, ...)
115 {
116   va_list va, va2;
117   int len;
118   char *ret;
119
120   va_start(va, format);
121   va_copy(va2, va);
122
123   // How long is it?
124   len = vsnprintf(0, 0, format, va);
125   len++;
126   va_end(va);
127
128   // Allocate and do the sprintf()
129   ret = xmalloc(len);
130   vsnprintf(ret, len, format, va2);
131   va_end(va2);
132
133   return ret;
134 }
135
136 void xprintf(char *format, ...)
137 {
138   va_list va;
139   va_start(va, format);
140
141   vprintf(format, va);
142   va_end(va);
143   if (fflush(stdout) || ferror(stdout)) perror_exit("write");
144 }
145
146 void xputs(char *s)
147 {
148   if (EOF == puts(s) || fflush(stdout) || ferror(stdout)) perror_exit("write");
149 }
150
151 void xputc(char c)
152 {
153   if (EOF == fputc(c, stdout) || fflush(stdout) || ferror(stdout))
154     perror_exit("write");
155 }
156
157 void xflush(void)
158 {
159   if (fflush(stdout) || ferror(stdout)) perror_exit("write");;
160 }
161
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)
167 {
168   if (pid == -1) perror_exit("vfork");
169
170   // Signal to xexec() and friends that we vforked so can't recurse
171   toys.stacktop = 0;
172
173   return pid;
174 }
175
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)
179 {
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);
183
184   perror_msg("exec %s", argv[0]);
185   toys.exitval = 127;
186   if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
187   xexit();
188 }
189
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)
197 {
198   int cestnepasun[4], pid;
199
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]
202   if (pipes) {
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];
207     }
208   }
209
210   // Child process.
211   if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
212     // Dance of the stdin/stdout redirection.
213     if (pipes) {
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]);
222         }
223       }
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]);
228       }
229     }
230     if (argv) xexec(argv);
231
232     // In fork() case, force recursion because we know it's us.
233     if (CFG_TOYBOX_FORK) {
234       toy_init(toys.which, toys.argv);
235       toys.stacktop = 0;
236       toys.which->toy_main();
237       xexit();
238     // In vfork() case, exec /proc/self/exe with high bit of first letter set
239     // to tell main() we reentered.
240     } else {
241       char *s = "/proc/self/exe";
242
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
245       **toys.argv |= 0x80;
246       execv(s, toys.argv);
247       perror_msg_raw(s);
248
249       _exit(127);
250     }
251   }
252
253   // Parent process
254   if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
255   if (pipes) {
256     if (pipes[0] != -1) close(cestnepasun[0]);
257     if (pipes[1] != -1) close(cestnepasun[3]);
258   }
259
260   return pid;
261 }
262
263 // Wait for child process to exit, then return adjusted exit code.
264 int xwaitpid(pid_t pid)
265 {
266   int status;
267
268   while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
269
270   return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+127;
271 }
272
273 int xpclose_both(pid_t pid, int *pipes)
274 {
275   if (pipes) {
276     close(pipes[0]);
277     close(pipes[1]);
278   }
279
280   return xwaitpid(pid);
281 }
282
283 // Wrapper to xpopen with a pipe for just one of stdin/stdout
284 pid_t xpopen(char **argv, int *pipe, int stdout)
285 {
286   int pipes[2], pid;
287
288   pipes[!stdout] = -1;
289   pipes[!!stdout] = 0;
290   pid = xpopen_both(argv, pipes);
291   *pipe = pid ? pipes[!!stdout] : -1;
292
293   return pid;
294 }
295
296 int xpclose(pid_t pid, int pipe)
297 {
298   close(pipe);
299
300   return xpclose_both(pid, 0);
301 }
302
303 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
304 int xrun(char **argv)
305 {
306   return xpclose_both(xpopen_both(argv, 0), 0);
307 }
308
309 void xaccess(char *path, int flags)
310 {
311   if (access(path, flags)) perror_exit("Can't access '%s'", path);
312 }
313
314 // Die unless we can delete a file.  (File must exist to be deleted.)
315 void xunlink(char *path)
316 {
317   if (unlink(path)) perror_exit("unlink '%s'", path);
318 }
319
320 // Die unless we can open/create a file, returning file descriptor.
321 int xcreate(char *path, int flags, int mode)
322 {
323   int fd = open(path, flags^O_CLOEXEC, mode);
324   if (fd == -1) perror_exit_raw(path);
325   return fd;
326 }
327
328 // Die unless we can open a file, returning file descriptor.
329 int xopen(char *path, int flags)
330 {
331   return xcreate(path, flags, 0);
332 }
333
334 void xpipe(int *pp)
335 {
336   if (pipe(pp)) perror_exit("xpipe");
337 }
338
339 void xclose(int fd)
340 {
341   if (close(fd)) perror_exit("xclose");
342 }
343
344 int xdup(int fd)
345 {
346   if (fd != -1) {
347     fd = dup(fd);
348     if (fd == -1) perror_exit("xdup");
349   }
350   return fd;
351 }
352
353 FILE *xfdopen(int fd, char *mode)
354 {
355   FILE *f = fdopen(fd, mode);
356
357   if (!f) perror_exit("xfdopen");
358
359   return f;
360 }
361
362 // Die unless we can open/create a file, returning FILE *.
363 FILE *xfopen(char *path, char *mode)
364 {
365   FILE *f = fopen(path, mode);
366   if (!f) perror_exit("No file %s", path);
367   return f;
368 }
369
370 // Die if there's an error other than EOF.
371 size_t xread(int fd, void *buf, size_t len)
372 {
373   ssize_t ret = read(fd, buf, len);
374   if (ret < 0) perror_exit("xread");
375
376   return ret;
377 }
378
379 void xreadall(int fd, void *buf, size_t len)
380 {
381   if (len != readall(fd, buf, len)) perror_exit("xreadall");
382 }
383
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
386 // somewhere.
387
388 void xwrite(int fd, void *buf, size_t len)
389 {
390   if (len != writeall(fd, buf, len)) perror_exit("xwrite");
391 }
392
393 // Die if lseek fails, probably due to being called on a pipe.
394
395 off_t xlseek(int fd, off_t offset, int whence)
396 {
397   offset = lseek(fd, offset, whence);
398   if (offset<0) perror_exit("lseek");
399
400   return offset;
401 }
402
403 char *xgetcwd(void)
404 {
405   char *buf = getcwd(NULL, 0);
406   if (!buf) perror_exit("xgetcwd");
407
408   return buf;
409 }
410
411 void xstat(char *path, struct stat *st)
412 {
413   if(stat(path, st)) perror_exit("Can't stat %s", path);
414 }
415
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)
419 {
420   struct string_list *todo, *done = 0;
421   int try = 9999, dirfd = open("/", 0);;
422   char *ret;
423
424   // If this isn't an absolute path, start with cwd.
425   if (*path != '/') {
426     char *temp = xgetcwd();
427
428     splitpath(path, splitpath(temp, &todo));
429     free(temp);
430   } else splitpath(path, &todo);
431
432   // Iterate through path components
433   while (todo) {
434     struct string_list *new = llist_pop(&todo), **tail;
435     ssize_t len;
436
437     if (!try--) {
438       errno = ELOOP;
439       goto error;
440     }
441
442     // Removable path componenents.
443     if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
444       int x = new->str[1];
445
446       free(new);
447       if (x) {
448         if (done) free(llist_pop(&done));
449         len = 0;
450       } else continue;
451
452     // Is this a symlink?
453     } else len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
454
455     if (len>4095) goto error;
456     if (len<1) {
457       int fd;
458       char *s = "..";
459
460       // For .. just move dirfd
461       if (len) {
462         // Not a symlink: add to linked list, move dirfd, fail if error
463         if ((exact || todo) && errno != EINVAL) goto error;
464         new->next = done;
465         done = new;
466         if (errno == EINVAL && !todo) break;
467         s = new->str;
468       }
469       fd = openat(dirfd, s, 0);
470       if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
471       close(dirfd);
472       dirfd = fd;
473       continue;
474     }
475
476     // If this symlink is to an absolute path, discard existing resolved path
477     libbuf[len] = 0;
478     if (*libbuf == '/') {
479       llist_traverse(done, free);
480       done=0;
481       close(dirfd);
482       dirfd = open("/", 0);
483     }
484     free(new);
485
486     // prepend components of new path. Note symlink to "/" will leave new NULL
487     tail = splitpath(libbuf, &new);
488
489     // symlink to "/" will return null and leave tail alone
490     if (new) {
491       *tail = todo;
492       todo = new;
493     }
494   }
495   close(dirfd);
496
497   // At this point done has the path, in reverse order. Reverse list while
498   // calculating buffer length.
499
500   try = 2;
501   while (done) {
502     struct string_list *temp = llist_pop(&done);;
503
504     if (todo) try++;
505     try += strlen(temp->str);
506     temp->next = todo;
507     todo = temp;
508   }
509
510   // Assemble return buffer
511
512   ret = xmalloc(try);
513   *ret = '/';
514   ret [try = 1] = 0;
515   while (todo) {
516     if (try>1) ret[try++] = '/';
517     try = stpcpy(ret+try, todo->str) - ret;
518     free(llist_pop(&todo));
519   }
520
521   return ret;
522
523 error:
524   close(dirfd);
525   llist_traverse(todo, free);
526   llist_traverse(done, free);
527
528   return NULL;
529 }
530
531 void xchdir(char *path)
532 {
533   if (chdir(path)) error_exit("chdir '%s'", path);
534 }
535
536 void xchroot(char *path)
537 {
538   if (chroot(path)) error_exit("chroot '%s'", path);
539   xchdir("/");
540 }
541
542 struct passwd *xgetpwuid(uid_t uid)
543 {
544   struct passwd *pwd = getpwuid(uid);
545   if (!pwd) error_exit("bad uid %ld", (long)uid);
546   return pwd;
547 }
548
549 struct group *xgetgrgid(gid_t gid)
550 {
551   struct group *group = getgrgid(gid);
552
553   if (!group) perror_exit("gid %ld", (long)gid);
554   return group;
555 }
556
557 struct passwd *xgetpwnamid(char *user)
558 {
559   struct passwd *up = getpwnam(user);
560   uid_t uid;
561
562   if (!up) {
563     char *s = 0;
564
565     uid = estrtol(user, &s, 10);
566     if (!errno && s && !*s) up = getpwuid(uid);
567   }
568   if (!up) perror_exit("user '%s'", user);
569
570   return up;
571 }
572
573 struct group *xgetgrnamid(char *group)
574 {
575   struct group *gr = getgrnam(group);
576   gid_t gid;
577
578   if (!gr) {
579     char *s = 0;
580
581     gid = estrtol(group, &s, 10);
582     if (!errno && s && !*s) gr = getgrgid(gid);
583   }
584   if (!gr) perror_exit("group '%s'", group);
585
586   return gr;
587 }
588
589 struct passwd *xgetpwnam(char *name)
590 {
591   struct passwd *up = getpwnam(name);
592
593   if (!up) perror_exit("user '%s'", name);
594   return up;
595 }
596
597 struct group *xgetgrnam(char *name)
598 {
599   struct group *gr = getgrnam(name);
600
601   if (!gr) perror_exit("group '%s'", name);
602   return gr;
603 }
604
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.
607
608 void xsetuser(struct passwd *pwd)
609 {
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);
612 }
613
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)
617 {
618   int len, size = 0;
619   char *buf = 0;
620
621   // Grow by 64 byte chunks until it's big enough.
622   for(;;) {
623     size +=64;
624     buf = xrealloc(buf, size);
625     len = readlink(name, buf, size);
626
627     if (len<0) {
628       free(buf);
629       return 0;
630     }
631     if (len<size) {
632       buf[len]=0;
633       return buf;
634     }
635   }
636 }
637
638 char *xreadfile(char *name, char *buf, off_t len)
639 {
640   if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
641
642   return buf;
643 }
644
645 int xioctl(int fd, int request, void *data)
646 {
647   int rc;
648
649   errno = 0;
650   rc = ioctl(fd, request, data);
651   if (rc == -1 && errno) perror_exit("ioctl %x", request);
652
653   return rc;
654 }
655
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)
659 {
660   char pidfile[256], spid[32];
661   int i, fd;
662   pid_t pid;
663
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);
668     if (fd != -1) break;
669
670     // If it already existed, read it.  Loop for race condition.
671     fd = open(pidfile, O_RDONLY);
672     if (fd == -1) continue;
673
674     // Is the old program still there?
675     spid[xread(fd, spid, sizeof(spid)-1)] = 0;
676     close(fd);
677     pid = atoi(spid);
678     if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
679
680     // An else with more sanity checking might be nice here.
681   }
682
683   if (i == 3) error_exit("xpidfile %s", name);
684
685   xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
686   close(fd);
687 }
688
689 // Copy the rest of in to out and close both files.
690
691 void xsendfile(int in, int out)
692 {
693   long len;
694
695   if (in<0) return;
696   for (;;) {
697     len = xread(in, libbuf, sizeof(libbuf));
698     if (len<1) break;
699     xwrite(out, libbuf, len);
700   }
701 }
702
703 // parse fractional seconds with optional s/m/h/d suffix
704 long xparsetime(char *arg, long units, long *fraction)
705 {
706   double d;
707   long l;
708
709   if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
710   else l = strtoul(arg, &arg, 10);
711
712   // Parse suffix
713   if (*arg) {
714     int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
715
716     if (i == -1) error_exit("Unknown suffix '%c'", *arg);
717     if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
718     else l *= ismhd[i];
719   }
720
721   if (CFG_TOYBOX_FLOAT) {
722     l = (long)d;
723     if (fraction) *fraction = units*(d-l);
724   } else if (fraction) *fraction = 0;
725
726   return l;
727 }
728
729 // Compile a regular expression into a regex_t
730 void xregcomp(regex_t *preg, char *regex, int cflags)
731 {
732   int rc = regcomp(preg, regex, cflags);
733
734   if (rc) {
735     regerror(rc, preg, libbuf, sizeof(libbuf));
736     error_exit("xregcomp: %s", libbuf);
737   }
738 }
739
740 char *xtzset(char *new)
741 {
742   char *old = getenv("TZ");
743
744   if (old) old = xstrdup(old);
745   if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
746   tzset();
747
748   return old;
749 }
750
751 // Set a signal handler
752 void xsignal(int signal, void *handler)
753 {
754   struct sigaction *sa = (void *)libbuf;
755
756   memset(sa, 0, sizeof(struct sigaction));
757   sa->sa_handler = handler;
758
759   if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
760 }