OSDN Git Service

Teach date @unixtime[.fraction], switch -s to be -D (matching busybox and
[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");
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 // 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)
135 {
136   if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE) toy_exec(argv);
137   execvp(argv[0], argv);
138
139   perror_msg("exec %s", argv[0]);
140   toys.exitval = 127;
141   if (!CFG_TOYBOX_FORK) _exit(toys.exitval);
142   xexit();
143 }
144
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)
150 {
151   int cestnepasun[4], pid;
152
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]
155   if (pipes) {
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];
160     }
161   }
162
163   // Child process
164   if (!(pid = xfork())) {
165     // Dance of the stdin/stdout redirection.
166     if (pipes) {
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]);
175         }
176       }
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]);
181       }
182     }
183     if (argv) {
184       if (CFG_TOYBOX) toy_exec(argv);
185       execvp(argv[0], argv);
186       _exit(127);
187     }
188     return 0;
189
190   }
191
192   // Parent process
193   if (pipes) {
194     if (pipes[0] != -1) close(cestnepasun[0]);
195     if (pipes[1] != -1) close(cestnepasun[3]);
196   }
197
198   return pid;
199 }
200
201 int xpclose_both(pid_t pid, int *pipes)
202 {
203   int rc = 127;
204
205   if (pipes) {
206     close(pipes[0]);
207     close(pipes[1]);
208   }
209   waitpid(pid, &rc, 0);
210
211   return WIFEXITED(rc) ? WEXITSTATUS(rc) : WTERMSIG(rc) + 127;
212 }
213
214 // Wrapper to xpopen with a pipe for just one of stdin/stdout
215 pid_t xpopen(char **argv, int *pipe, int stdout)
216 {
217   int pipes[2], pid;
218
219   pipes[!stdout] = -1;
220   pipes[!!stdout] = 0;
221   pid = xpopen_both(argv, pipes);
222   *pipe = pid ? pipes[!!stdout] : -1;
223
224   return pid;
225 }
226
227 int xpclose(pid_t pid, int pipe)
228 {
229   close(pipe);
230
231   return xpclose_both(pid, 0);
232 }
233
234 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
235 int xrun(char **argv)
236 {
237   return xpclose_both(xpopen_both(argv, 0), 0);
238 }
239
240 void xaccess(char *path, int flags)
241 {
242   if (access(path, flags)) perror_exit("Can't access '%s'", path);
243 }
244
245 // Die unless we can delete a file.  (File must exist to be deleted.)
246 void xunlink(char *path)
247 {
248   if (unlink(path)) perror_exit("unlink '%s'", path);
249 }
250
251 // Die unless we can open/create a file, returning file descriptor.
252 int xcreate(char *path, int flags, int mode)
253 {
254   int fd = open(path, flags^O_CLOEXEC, mode);
255   if (fd == -1) perror_exit("%s", path);
256   return fd;
257 }
258
259 // Die unless we can open a file, returning file descriptor.
260 int xopen(char *path, int flags)
261 {
262   return xcreate(path, flags, 0);
263 }
264
265 void xclose(int fd)
266 {
267   if (close(fd)) perror_exit("xclose");
268 }
269
270 int xdup(int fd)
271 {
272   if (fd != -1) {
273     fd = dup(fd);
274     if (fd == -1) perror_exit("xdup");
275   }
276   return fd;
277 }
278
279 FILE *xfdopen(int fd, char *mode)
280 {
281   FILE *f = fdopen(fd, mode);
282
283   if (!f) perror_exit("xfdopen");
284
285   return f;
286 }
287
288 // Die unless we can open/create a file, returning FILE *.
289 FILE *xfopen(char *path, char *mode)
290 {
291   FILE *f = fopen(path, mode);
292   if (!f) perror_exit("No file %s", path);
293   return f;
294 }
295
296 // Die if there's an error other than EOF.
297 size_t xread(int fd, void *buf, size_t len)
298 {
299   ssize_t ret = read(fd, buf, len);
300   if (ret < 0) perror_exit("xread");
301
302   return ret;
303 }
304
305 void xreadall(int fd, void *buf, size_t len)
306 {
307   if (len != readall(fd, buf, len)) perror_exit("xreadall");
308 }
309
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
312 // somewhere.
313
314 void xwrite(int fd, void *buf, size_t len)
315 {
316   if (len != writeall(fd, buf, len)) perror_exit("xwrite");
317 }
318
319 // Die if lseek fails, probably due to being called on a pipe.
320
321 off_t xlseek(int fd, off_t offset, int whence)
322 {
323   offset = lseek(fd, offset, whence);
324   if (offset<0) perror_exit("lseek");
325
326   return offset;
327 }
328
329 char *xgetcwd(void)
330 {
331   char *buf = getcwd(NULL, 0);
332   if (!buf) perror_exit("xgetcwd");
333
334   return buf;
335 }
336
337 void xstat(char *path, struct stat *st)
338 {
339   if(stat(path, st)) perror_exit("Can't stat %s", path);
340 }
341
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)
345 {
346   struct string_list *todo, *done = 0;
347   int try = 9999, dirfd = open("/", 0);;
348   char buf[4096], *ret;
349
350   // If this isn't an absolute path, start with cwd.
351   if (*path != '/') {
352     char *temp = xgetcwd();
353
354     splitpath(path, splitpath(temp, &todo));
355     free(temp);
356   } else splitpath(path, &todo);
357
358   // Iterate through path components
359   while (todo) {
360     struct string_list *new = llist_pop(&todo), **tail;
361     ssize_t len;
362
363     if (!try--) {
364       errno = ELOOP;
365       goto error;
366     }
367
368     // Removable path componenents.
369     if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
370       int x = new->str[1];
371
372       free(new);
373       if (x) {
374         if (done) free(llist_pop(&done));
375         len = 0;
376       } else continue;
377
378     // Is this a symlink?
379     } else len=readlinkat(dirfd, new->str, buf, 4096);
380
381     if (len>4095) goto error;
382     if (len<1) {
383       int fd;
384       char *s = "..";
385
386       // For .. just move dirfd
387       if (len) {
388         // Not a symlink: add to linked list, move dirfd, fail if error
389         if ((exact || todo) && errno != EINVAL) goto error;
390         new->next = done;
391         done = new;
392         if (errno == EINVAL && !todo) break;
393         s = new->str;
394       }
395       fd = openat(dirfd, s, 0);
396       if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
397       close(dirfd);
398       dirfd = fd;
399       continue;
400     }
401
402     // If this symlink is to an absolute path, discard existing resolved path
403     buf[len] = 0;
404     if (*buf == '/') {
405       llist_traverse(done, free);
406       done=0;
407       close(dirfd);
408       dirfd = open("/", 0);
409     }
410     free(new);
411
412     // prepend components of new path. Note symlink to "/" will leave new NULL
413     tail = splitpath(buf, &new);
414
415     // symlink to "/" will return null and leave tail alone
416     if (new) {
417       *tail = todo;
418       todo = new;
419     }
420   }
421   close(dirfd);
422
423   // At this point done has the path, in reverse order. Reverse list while
424   // calculating buffer length.
425
426   try = 2;
427   while (done) {
428     struct string_list *temp = llist_pop(&done);;
429
430     if (todo) try++;
431     try += strlen(temp->str);
432     temp->next = todo;
433     todo = temp;
434   }
435
436   // Assemble return buffer
437
438   ret = xmalloc(try);
439   *ret = '/';
440   ret [try = 1] = 0;
441   while (todo) {
442     if (try>1) ret[try++] = '/';
443     try = stpcpy(ret+try, todo->str) - ret;
444     free(llist_pop(&todo));
445   }
446
447   return ret;
448
449 error:
450   close(dirfd);
451   llist_traverse(todo, free);
452   llist_traverse(done, free);
453
454   return NULL;
455 }
456
457 void xchdir(char *path)
458 {
459   if (chdir(path)) error_exit("chdir '%s'", path);
460 }
461
462 void xchroot(char *path)
463 {
464   if (chroot(path)) error_exit("chroot '%s'", path);
465   xchdir("/");
466 }
467
468 struct passwd *xgetpwuid(uid_t uid)
469 {
470   struct passwd *pwd = getpwuid(uid);
471   if (!pwd) error_exit("bad uid %ld", (long)uid);
472   return pwd;
473 }
474
475 struct group *xgetgrgid(gid_t gid)
476 {
477   struct group *group = getgrgid(gid);
478
479   if (!group) perror_exit("gid %ld", (long)gid);
480   return group;
481 }
482
483 struct passwd *xgetpwnamid(char *user)
484 {
485   struct passwd *up = getpwnam(user);
486   uid_t uid;
487
488   if (!up) {
489     char *s = 0;
490
491     uid = estrtol(user, &s, 10);
492     if (!errno && s && !*s) up = getpwuid(uid);
493   }
494   if (!up) perror_exit("user '%s'", user);
495
496   return up;
497 }
498
499 struct group *xgetgrnamid(char *group)
500 {
501   struct group *gr = getgrnam(group);
502   gid_t gid;
503
504   if (!gr) {
505     char *s = 0;
506
507     gid = estrtol(group, &s, 10);
508     if (!errno && s && !*s) gr = getgrgid(gid);
509   }
510   if (!gr) perror_exit("group '%s'", group);
511
512   return gr;
513 }
514
515 struct passwd *xgetpwnam(char *name)
516 {
517   struct passwd *up = getpwnam(name);
518
519   if (!up) perror_exit("user '%s'", name);
520   return up;
521 }
522
523 struct group *xgetgrnam(char *name)
524 {
525   struct group *gr = getgrnam(name);
526
527   if (!gr) perror_exit("group '%s'", name);
528   return gr;
529 }
530
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.
533
534 void xsetuser(struct passwd *pwd)
535 {
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);
538 }
539
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)
543 {
544   int len, size = 0;
545   char *buf = 0;
546
547   // Grow by 64 byte chunks until it's big enough.
548   for(;;) {
549     size +=64;
550     buf = xrealloc(buf, size);
551     len = readlink(name, buf, size);
552
553     if (len<0) {
554       free(buf);
555       return 0;
556     }
557     if (len<size) {
558       buf[len]=0;
559       return buf;
560     }
561   }
562 }
563
564 char *xreadfile(char *name, char *buf, off_t len)
565 {
566   if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
567
568   return buf;
569 }
570
571 int xioctl(int fd, int request, void *data)
572 {
573   int rc;
574
575   errno = 0;
576   rc = ioctl(fd, request, data);
577   if (rc == -1 && errno) perror_exit("ioctl %x", request);
578
579   return rc;
580 }
581
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)
585 {
586   char pidfile[256], spid[32];
587   int i, fd;
588   pid_t pid;
589
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);
594     if (fd != -1) break;
595
596     // If it already existed, read it.  Loop for race condition.
597     fd = open(pidfile, O_RDONLY);
598     if (fd == -1) continue;
599
600     // Is the old program still there?
601     spid[xread(fd, spid, sizeof(spid)-1)] = 0;
602     close(fd);
603     pid = atoi(spid);
604     if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
605
606     // An else with more sanity checking might be nice here.
607   }
608
609   if (i == 3) error_exit("xpidfile %s", name);
610
611   xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
612   close(fd);
613 }
614
615 // Copy the rest of in to out and close both files.
616
617 void xsendfile(int in, int out)
618 {
619   long len;
620
621   if (in<0) return;
622   for (;;) {
623     len = xread(in, libbuf, sizeof(libbuf));
624     if (len<1) break;
625     xwrite(out, libbuf, len);
626   }
627 }
628
629 // parse fractional seconds with optional s/m/h/d suffix
630 long xparsetime(char *arg, long units, long *fraction)
631 {
632   double d;
633   long l;
634
635   if (CFG_TOYBOX_FLOAT) d = strtod(arg, &arg);
636   else l = strtoul(arg, &arg, 10);
637
638   // Parse suffix
639   if (*arg) {
640     int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *arg);
641
642     if (i == -1) error_exit("Unknown suffix '%c'", *arg);
643     if (CFG_TOYBOX_FLOAT) d *= ismhd[i];
644     else l *= ismhd[i];
645   }
646
647   if (CFG_TOYBOX_FLOAT) {
648     l = (long)d;
649     if (fraction) *fraction = units*(d-l);
650   } else if (fraction) *fraction = 0;
651
652   return l;
653 }
654
655 // Compile a regular expression into a regex_t
656 void xregcomp(regex_t *preg, char *regex, int cflags)
657 {
658   int rc = regcomp(preg, regex, cflags);
659
660   if (rc) {
661     regerror(rc, preg, libbuf, sizeof(libbuf));
662     error_exit("xregcomp: %s", libbuf);
663   }
664 }
665
666 char *xtzset(char *new)
667 {
668   char *tz = getenv("TZ");
669
670   if (tz) tz = xstrdup(tz);
671   if (setenv("TZ", new, 1)) perror_exit("setenv");
672   tzset();
673
674   return tz;
675 }
676
677 // Set a signal handler
678 void xsignal(int signal, void *handler)
679 {
680   struct sigaction *sa = (void *)libbuf;
681
682   memset(sa, 0, sizeof(struct sigaction));
683   sa->sa_handler = handler;
684
685   if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
686 }