OSDN Git Service

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