OSDN Git Service

Merge remote-tracking branch \\\'toybox/master\\\' into HEAD am: 0803f535c0 am: 09246...
[android-x86/external-toybox.git] / lib / lib.c
1 /* lib.c - various reusable stuff.
2  *
3  * Copyright 2006 Rob Landley <rob@landley.net>
4  */
5
6 #include "toys.h"
7
8 void verror_msg(char *msg, int err, va_list va)
9 {
10   char *s = ": %s";
11
12   fprintf(stderr, "%s: ", toys.which->name);
13   if (msg) vfprintf(stderr, msg, va);
14   else s+=2;
15   if (err) fprintf(stderr, s, strerror(err));
16   if (msg || err) putc('\n', stderr);
17   if (!toys.exitval) toys.exitval++;
18 }
19
20 // These functions don't collapse together because of the va_stuff.
21
22 void error_msg(char *msg, ...)
23 {
24   va_list va;
25
26   va_start(va, msg);
27   verror_msg(msg, 0, va);
28   va_end(va);
29 }
30
31 void perror_msg(char *msg, ...)
32 {
33   va_list va;
34
35   va_start(va, msg);
36   verror_msg(msg, errno, va);
37   va_end(va);
38 }
39
40 // Die with an error message.
41 void error_exit(char *msg, ...)
42 {
43   va_list va;
44
45   va_start(va, msg);
46   verror_msg(msg, 0, va);
47   va_end(va);
48
49   xexit();
50 }
51
52 // Die with an error message and strerror(errno)
53 void perror_exit(char *msg, ...)
54 {
55   va_list va;
56
57   va_start(va, msg);
58   verror_msg(msg, errno, va);
59   va_end(va);
60
61   xexit();
62 }
63
64 // Exit with an error message after showing help text.
65 void help_exit(char *msg, ...)
66 {
67   va_list va;
68
69   if (CFG_TOYBOX_HELP) show_help(stderr);
70
71   if (msg) {
72     va_start(va, msg);
73     verror_msg(msg, 0, va);
74     va_end(va);
75   }
76
77   xexit();
78 }
79
80 // If you want to explicitly disable the printf() behavior (because you're
81 // printing user-supplied data, or because android's static checker produces
82 // false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
83 // -Werror there for policy reasons).
84 void error_msg_raw(char *msg)
85 {
86   error_msg("%s", msg);
87 }
88
89 void perror_msg_raw(char *msg)
90 {
91   perror_msg("%s", msg);
92 }
93
94 void error_exit_raw(char *msg)
95 {
96   error_exit("%s", msg);
97 }
98
99 void perror_exit_raw(char *msg)
100 {
101   perror_exit("%s", msg);
102 }
103
104 // Keep reading until full or EOF
105 ssize_t readall(int fd, void *buf, size_t len)
106 {
107   size_t count = 0;
108
109   while (count<len) {
110     int i = read(fd, (char *)buf+count, len-count);
111     if (!i) break;
112     if (i<0) return i;
113     count += i;
114   }
115
116   return count;
117 }
118
119 // Keep writing until done or EOF
120 ssize_t writeall(int fd, void *buf, size_t len)
121 {
122   size_t count = 0;
123   while (count<len) {
124     int i = write(fd, count+(char *)buf, len-count);
125     if (i<1) return i;
126     count += i;
127   }
128
129   return count;
130 }
131
132 // skip this many bytes of input. Return 0 for success, >0 means this much
133 // left after input skipped.
134 off_t lskip(int fd, off_t offset)
135 {
136   off_t cur = lseek(fd, 0, SEEK_CUR);
137
138   if (cur != -1) {
139     off_t end = lseek(fd, 0, SEEK_END) - cur;
140
141     if (end > 0 && end < offset) return offset - end;
142     end = offset+cur;
143     if (end == lseek(fd, end, SEEK_SET)) return 0;
144     perror_exit("lseek");
145   }
146
147   while (offset>0) {
148     int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
149
150     or = readall(fd, libbuf, try);
151     if (or < 0) perror_exit("lskip to %lld", (long long)offset);
152     else offset -= or;
153     if (or < try) break;
154   }
155
156   return offset;
157 }
158
159 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
160 //        2=make path (already exists is ok)
161 //        4=verbose
162 // returns 0 = path ok, 1 = error
163 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
164 {
165   struct stat buf;
166   char *s;
167
168   // mkdir -p one/two/three is not an error if the path already exists,
169   // but is if "three" is a file. The others we dereference and catch
170   // not-a-directory along the way, but the last one we must explicitly
171   // test for. Might as well do it up front.
172
173   if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
174     errno = EEXIST;
175     return 1;
176   }
177
178   for (s = dir; ;s++) {
179     char save = 0;
180     mode_t mode = (0777&~toys.old_umask)|0300;
181
182     // find next '/', but don't try to mkdir "" at start of absolute path
183     if (*s == '/' && (flags&2) && s != dir) {
184       save = *s;
185       *s = 0;
186     } else if (*s) continue;
187
188     // Use the mode from the -m option only for the last directory.
189     if (!save) {
190       if (flags&1) mode = lastmode;
191       else break;
192     }
193
194     if (mkdirat(atfd, dir, mode)) {
195       if (!(flags&2) || errno != EEXIST) return 1;
196     } else if (flags&4)
197       fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
198
199     if (!(*s = save)) break;
200   }
201
202   return 0;
203 }
204
205 // Split a path into linked list of components, tracking head and tail of list.
206 // Filters out // entries with no contents.
207 struct string_list **splitpath(char *path, struct string_list **list)
208 {
209   char *new = path;
210
211   *list = 0;
212   do {
213     int len;
214
215     if (*path && *path != '/') continue;
216     len = path-new;
217     if (len > 0) {
218       *list = xmalloc(sizeof(struct string_list) + len + 1);
219       (*list)->next = 0;
220       memcpy((*list)->str, new, len);
221       (*list)->str[len] = 0;
222       list = &(*list)->next;
223     }
224     new = path+1;
225   } while (*path++);
226
227   return list;
228 }
229
230 // Find all file in a colon-separated path with access type "type" (generally
231 // X_OK or R_OK).  Returns a list of absolute paths to each file found, in
232 // order.
233
234 struct string_list *find_in_path(char *path, char *filename)
235 {
236   struct string_list *rlist = NULL, **prlist=&rlist;
237   char *cwd;
238
239   if (!path) return 0;
240
241   cwd = xgetcwd();
242   for (;;) {
243     char *next = strchr(path, ':');
244     int len = next ? next-path : strlen(path);
245     struct string_list *rnext;
246     struct stat st;
247
248     rnext = xmalloc(sizeof(void *) + strlen(filename)
249       + (len ? len : strlen(cwd)) + 2);
250     if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
251     else {
252       char *res = rnext->str;
253
254       memcpy(res, path, len);
255       res += len;
256       *(res++) = '/';
257       strcpy(res, filename);
258     }
259
260     // Confirm it's not a directory.
261     if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
262       *prlist = rnext;
263       rnext->next = NULL;
264       prlist = &(rnext->next);
265     } else free(rnext);
266
267     if (!next) break;
268     path += len;
269     path++;
270   }
271   free(cwd);
272
273   return rlist;
274 }
275
276 long estrtol(char *str, char **end, int base)
277 {
278   errno = 0;
279
280   return strtol(str, end, base);
281 }
282
283 long xstrtol(char *str, char **end, int base)
284 {
285   long l = estrtol(str, end, base);
286
287   if (errno) perror_exit_raw(str);
288
289   return l;
290 }
291
292 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
293 // (zetta and yotta don't fit in 64 bits.)
294 long atolx(char *numstr)
295 {
296   char *c, *suffixes="cbkmgtpe", *end;
297   long val;
298
299   val = xstrtol(numstr, &c, 0);
300   if (*c) {
301     if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
302       int shift = end-suffixes-2;
303       if (shift >= 0) val *= 1024L<<(shift*10);
304     } else {
305       while (isspace(*c)) c++;
306       if (*c) error_exit("not integer: %s", numstr);
307     }
308   }
309
310   return val;
311 }
312
313 long atolx_range(char *numstr, long low, long high)
314 {
315   long val = atolx(numstr);
316
317   if (val < low) error_exit("%ld < %ld", val, low);
318   if (val > high) error_exit("%ld > %ld", val, high);
319
320   return val;
321 }
322
323 int stridx(char *haystack, char needle)
324 {
325   char *off;
326
327   if (!needle) return -1;
328   off = strchr(haystack, needle);
329   if (!off) return -1;
330
331   return off-haystack;
332 }
333
334 char *strlower(char *s)
335 {
336   char *try, *new;
337
338   if (!CFG_TOYBOX_I18N) {
339     try = new = xstrdup(s);
340     for (; *s; s++) *(new++) = tolower(*s);
341   } else {
342     // I can't guarantee the string _won't_ expand during reencoding, so...?
343     try = new = xmalloc(strlen(s)*2+1);
344
345     while (*s) {
346       wchar_t c;
347       int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
348
349       if (len < 1) *(new++) = *(s++);
350       else {
351         s += len;
352         // squash title case too
353         c = towlower(c);
354
355         // if we had a valid utf8 sequence, convert it to lower case, and can't
356         // encode back to utf8, something is wrong with your libc. But just
357         // in case somebody finds an exploit...
358         len = wcrtomb(new, c, 0);
359         if (len < 1) error_exit("bad utf8 %x", (int)c);
360         new += len;
361       }
362     }
363     *new = 0;
364   }
365
366   return try;
367 }
368
369 // strstr but returns pointer after match
370 char *strafter(char *haystack, char *needle)
371 {
372   char *s = strstr(haystack, needle);
373
374   return s ? s+strlen(needle) : s;
375 }
376
377 // Remove trailing \n
378 char *chomp(char *s)
379 {
380   char *p = strrchr(s, '\n');
381
382   if (p && !p[1]) *p = 0;
383   return s;
384 }
385
386 int unescape(char c)
387 {
388   char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
389   int idx = stridx(from, c);
390
391   return (idx == -1) ? 0 : to[idx];
392 }
393
394 // If *a starts with b, advance *a past it and return 1, else return 0;
395 int strstart(char **a, char *b)
396 {
397   int len = strlen(b), i = !strncmp(*a, b, len);
398
399   if (i) *a += len;
400
401   return i;
402 }
403
404 // Return how long the file at fd is, if there's any way to determine it.
405 off_t fdlength(int fd)
406 {
407   struct stat st;
408   off_t base = 0, range = 1, expand = 1, old;
409
410   if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
411
412   // If the ioctl works for this, return it.
413   // TODO: is blocksize still always 512, or do we stat for it?
414   // unsigned int size;
415   // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
416
417   // If not, do a binary search for the last location we can read.  (Some
418   // block devices don't do BLKGETSIZE right.)  This should probably have
419   // a CONFIG option...
420
421   // If not, do a binary search for the last location we can read.
422
423   old = lseek(fd, 0, SEEK_CUR);
424   do {
425     char temp;
426     off_t pos = base + range / 2;
427
428     if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
429       off_t delta = (pos + 1) - base;
430
431       base += delta;
432       if (expand) range = (expand <<= 1) - base;
433       else range -= delta;
434     } else {
435       expand = 0;
436       range = pos - base;
437     }
438   } while (range > 0);
439
440   lseek(fd, old, SEEK_SET);
441
442   return base;
443 }
444
445 // Read contents of file as a single nul-terminated string.
446 // measure file size if !len, allocate buffer if !buf
447 // Existing buffers need len in *plen
448 // Returns amount of data read in *plen
449 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
450 {
451   off_t len, rlen;
452   int fd;
453   char *buf, *rbuf;
454
455   // Unsafe to probe for size with a supplied buffer, don't ever do that.
456   if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
457
458   if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
459
460   // If we dunno the length, probe it. If we can't probe, start with 1 page.
461   if (!*plen) {
462     if ((len = fdlength(fd))>0) *plen = len;
463     else len = 4096;
464   } else len = *plen-1;
465
466   if (!ibuf) buf = xmalloc(len+1);
467   else buf = ibuf;
468
469   for (rbuf = buf;;) {
470     rlen = readall(fd, rbuf, len);
471     if (*plen || rlen<len) break;
472
473     // If reading unknown size, expand buffer by 1.5 each time we fill it up.
474     rlen += rbuf-buf;
475     buf = xrealloc(buf, len = (rlen*3)/2);
476     rbuf = buf+rlen;
477     len -= rlen;
478   }
479   *plen = len = rlen+(rbuf-buf);
480   close(fd);
481
482   if (rlen<0) {
483     if (ibuf != buf) free(buf);
484     buf = 0;
485   } else buf[len] = 0;
486
487   return buf;
488 }
489
490 char *readfile(char *name, char *ibuf, off_t len)
491 {
492   return readfileat(AT_FDCWD, name, ibuf, &len);
493 }
494
495 // Sleep for this many thousandths of a second
496 void msleep(long miliseconds)
497 {
498   struct timespec ts;
499
500   ts.tv_sec = miliseconds/1000;
501   ts.tv_nsec = (miliseconds%1000)*1000000;
502   nanosleep(&ts, &ts);
503 }
504
505 // Inefficient, but deals with unaligned access
506 int64_t peek_le(void *ptr, unsigned size)
507 {
508   int64_t ret = 0;
509   char *c = ptr;
510   int i;
511
512   for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
513   return ret;
514 }
515
516 int64_t peek_be(void *ptr, unsigned size)
517 {
518   int64_t ret = 0;
519   char *c = ptr;
520   int i;
521
522   for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
523   return ret;
524 }
525
526 int64_t peek(void *ptr, unsigned size)
527 {
528   return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
529 }
530
531 void poke(void *ptr, uint64_t val, int size)
532 {
533   if (size & 8) {
534     volatile uint64_t *p = (uint64_t *)ptr;
535     *p = val;
536   } else if (size & 4) {
537     volatile int *p = (int *)ptr;
538     *p = val;
539   } else if (size & 2) {
540     volatile short *p = (short *)ptr;
541     *p = val;
542   } else {
543     volatile char *p = (char *)ptr;
544     *p = val;
545   }
546 }
547
548 // Iterate through an array of files, opening each one and calling a function
549 // on that filehandle and name.  The special filename "-" means stdin if
550 // flags is O_RDONLY, stdout otherwise.  An empty argument list calls
551 // function() on just stdin/stdout.
552 //
553 // Note: pass O_CLOEXEC to automatically close filehandles when function()
554 // returns, otherwise filehandles must be closed by function()
555 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
556   void (*function)(int fd, char *name))
557 {
558   int fd;
559
560   // If no arguments, read from stdin.
561   if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
562   else do {
563     // Filename "-" means read from stdin.
564     // Inability to open a file prints a warning, but doesn't exit.
565
566     if (!strcmp(*argv, "-")) fd=0;
567     else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
568       perror_msg_raw(*argv);
569       continue;
570     }
571     function(fd, *argv);
572     if (flags & O_CLOEXEC) close(fd);
573   } while (*++argv);
574 }
575
576 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
577 void loopfiles(char **argv, void (*function)(int fd, char *name))
578 {
579   loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
580 }
581
582 // Slow, but small.
583
584 char *get_rawline(int fd, long *plen, char end)
585 {
586   char c, *buf = NULL;
587   long len = 0;
588
589   for (;;) {
590     if (1>read(fd, &c, 1)) break;
591     if (!(len & 63)) buf=xrealloc(buf, len+65);
592     if ((buf[len++]=c) == end) break;
593   }
594   if (buf) buf[len]=0;
595   if (plen) *plen = len;
596
597   return buf;
598 }
599
600 char *get_line(int fd)
601 {
602   long len;
603   char *buf = get_rawline(fd, &len, '\n');
604
605   if (buf && buf[--len]=='\n') buf[len]=0;
606
607   return buf;
608 }
609
610 int wfchmodat(int fd, char *name, mode_t mode)
611 {
612   int rc = fchmodat(fd, name, mode, 0);
613
614   if (rc) {
615     perror_msg("chmod '%s' to %04o", name, mode);
616     toys.exitval=1;
617   }
618   return rc;
619 }
620
621 static char *tempfile2zap;
622 static void tempfile_handler(void)
623 {
624   if (1 < (long)tempfile2zap) unlink(tempfile2zap);
625 }
626
627 // Open a temporary file to copy an existing file into.
628 int copy_tempfile(int fdin, char *name, char **tempname)
629 {
630   struct stat statbuf;
631   int fd;
632
633   *tempname = xmprintf("%s%s", name, "XXXXXX");
634   if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
635   if (!tempfile2zap) sigatexit(tempfile_handler);
636   tempfile2zap = *tempname;
637
638   // Set permissions of output file
639
640   fstat(fdin, &statbuf);
641   fchmod(fd, statbuf.st_mode);
642
643   return fd;
644 }
645
646 // Abort the copy and delete the temporary file.
647 void delete_tempfile(int fdin, int fdout, char **tempname)
648 {
649   close(fdin);
650   close(fdout);
651   if (*tempname) unlink(*tempname);
652   tempfile2zap = (char *)1;
653   free(*tempname);
654   *tempname = NULL;
655 }
656
657 // Copy the rest of the data and replace the original with the copy.
658 void replace_tempfile(int fdin, int fdout, char **tempname)
659 {
660   char *temp = xstrdup(*tempname);
661
662   temp[strlen(temp)-6]=0;
663   if (fdin != -1) {
664     xsendfile(fdin, fdout);
665     xclose(fdin);
666   }
667   xclose(fdout);
668   rename(*tempname, temp);
669   tempfile2zap = (char *)1;
670   free(*tempname);
671   free(temp);
672   *tempname = NULL;
673 }
674
675 // Create a 256 entry CRC32 lookup table.
676
677 void crc_init(unsigned int *crc_table, int little_endian)
678 {
679   unsigned int i;
680
681   // Init the CRC32 table (big endian)
682   for (i=0; i<256; i++) {
683     unsigned int j, c = little_endian ? i : i<<24;
684     for (j=8; j; j--)
685       if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
686       else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
687     crc_table[i] = c;
688   }
689 }
690
691 // Init base64 table
692
693 void base64_init(char *p)
694 {
695   int i;
696
697   for (i = 'A'; i != ':'; i++) {
698     if (i == 'Z'+1) i = 'a';
699     if (i == 'z'+1) i = '0';
700     *(p++) = i;
701   }
702   *(p++) = '+';
703   *(p++) = '/';
704 }
705
706 int yesno(int def)
707 {
708   char buf;
709
710   fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
711   fflush(stderr);
712   while (fread(&buf, 1, 1, stdin)) {
713     int new;
714
715     // The letter changes the value, the newline (or space) returns it.
716     if (isspace(buf)) break;
717     if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
718   }
719
720   return def;
721 }
722
723 struct signame {
724   int num;
725   char *name;
726 };
727
728 // Signals required by POSIX 2008:
729 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
730
731 #define SIGNIFY(x) {SIG##x, #x}
732
733 static struct signame signames[] = {
734   SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
735   SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
736   SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
737   SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
738   SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
739
740   // Start of non-terminal signals
741
742   SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
743   SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
744 };
745
746 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
747 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
748
749 // Handler that sets toys.signal, and writes to toys.signalfd if set
750 void generic_signal(int sig)
751 {
752   if (toys.signalfd) {
753     char c = sig;
754
755     writeall(toys.signalfd, &c, 1);
756   }
757   toys.signal = sig;
758 }
759
760 void exit_signal(int sig)
761 {
762   if (sig) toys.exitval = sig|128;
763   xexit();
764 }
765
766 // Install the same handler on every signal that defaults to killing the
767 // process, calling the handler on the way out. Calling multiple times
768 // adds the handlers to a list, to be called in order.
769 void sigatexit(void *handler)
770 {
771   struct arg_list *al = xmalloc(sizeof(struct arg_list));
772   int i;
773
774   for (i=0; signames[i].num != SIGCHLD; i++)
775     signal(signames[i].num, exit_signal);
776   al->next = toys.xexit;
777   al->arg = handler;
778   toys.xexit = al;
779 }
780
781 // Convert name to signal number.  If name == NULL print names.
782 int sig_to_num(char *pidstr)
783 {
784   int i;
785
786   if (pidstr) {
787     char *s;
788
789     i = estrtol(pidstr, &s, 10);
790     if (!errno && !*s) return i;
791
792     if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
793   }
794   for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
795     if (!pidstr) xputs(signames[i].name);
796     else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
797
798   return -1;
799 }
800
801 char *num_to_sig(int sig)
802 {
803   int i;
804
805   for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
806     if (signames[i].num == sig) return signames[i].name;
807   return NULL;
808 }
809
810 // premute mode bits based on posix mode strings.
811 mode_t string_to_mode(char *modestr, mode_t mode)
812 {
813   char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
814        *s, *str = modestr;
815   mode_t extrabits = mode & ~(07777);
816
817   // Handle octal mode
818   if (isdigit(*str)) {
819     mode = estrtol(str, &s, 8);
820     if (errno || *s || (mode & ~(07777))) goto barf;
821
822     return mode | extrabits;
823   }
824
825   // Gaze into the bin of permission...
826   for (;;) {
827     int i, j, dowho, dohow, dowhat, amask;
828
829     dowho = dohow = dowhat = amask = 0;
830
831     // Find the who, how, and what stanzas, in that order
832     while (*str && (s = strchr(whos, *str))) {
833       dowho |= 1<<(s-whos);
834       str++;
835     }
836     // If who isn't specified, like "a" but honoring umask.
837     if (!dowho) {
838       dowho = 8;
839       umask(amask=umask(0));
840     }
841     if (!*str || !(s = strchr(hows, *str))) goto barf;
842     dohow = *(str++);
843
844     if (!dohow) goto barf;
845     while (*str && (s = strchr(whats, *str))) {
846       dowhat |= 1<<(s-whats);
847       str++;
848     }
849
850     // Convert X to x for directory or if already executable somewhere
851     if ((dowhat&32) &&  (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
852
853     // Copy mode from another category?
854     if (!dowhat && *str && (s = strchr(whys, *str))) {
855       dowhat = (mode>>(3*(s-whys)))&7;
856       str++;
857     }
858
859     // Are we ready to do a thing yet?
860     if (*str && *(str++) != ',') goto barf;
861
862     // Ok, apply the bits to the mode.
863     for (i=0; i<4; i++) {
864       for (j=0; j<3; j++) {
865         mode_t bit = 0;
866         int where = 1<<((3*i)+j);
867
868         if (amask & where) continue;
869
870         // Figure out new value at this location
871         if (i == 3) {
872           // suid/sticky bit.
873           if (j) {
874             if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
875           } else if (dowhat & 16) bit++;
876         } else {
877           if (!(dowho&(8|(1<<i)))) continue;
878           if (dowhat&(1<<j)) bit++;
879         }
880
881         // When selection active, modify bit
882
883         if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
884         if (bit && dohow != '-') mode |= where;
885       }
886     }
887
888     if (!*str) break;
889   }
890
891   return mode|extrabits;
892 barf:
893   error_exit("bad mode '%s'", modestr);
894 }
895
896 // Format access mode into a drwxrwxrwx string
897 void mode_to_string(mode_t mode, char *buf)
898 {
899   char c, d;
900   int i, bit;
901
902   buf[10]=0;
903   for (i=0; i<9; i++) {
904     bit = mode & (1<<i);
905     c = i%3;
906     if (!c && (mode & (1<<((d=i/3)+9)))) {
907       c = "tss"[d];
908       if (!bit) c &= ~0x20;
909     } else c = bit ? "xwr"[c] : '-';
910     buf[9-i] = c;
911   }
912
913   if (S_ISDIR(mode)) c = 'd';
914   else if (S_ISBLK(mode)) c = 'b';
915   else if (S_ISCHR(mode)) c = 'c';
916   else if (S_ISLNK(mode)) c = 'l';
917   else if (S_ISFIFO(mode)) c = 'p';
918   else if (S_ISSOCK(mode)) c = 's';
919   else c = '-';
920   *buf = c;
921 }
922
923 // basename() can modify its argument or return a pointer to a constant string
924 // This just gives after the last '/' or the whole stirng if no /
925 char *getbasename(char *name)
926 {
927   char *s = strrchr(name, '/');
928
929   if (s) return s+1;
930
931   return name;
932 }
933
934 // Execute a callback for each PID that matches a process name from a list.
935 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
936 {
937   DIR *dp;
938   struct dirent *entry;
939
940   if (!(dp = opendir("/proc"))) perror_exit("opendir");
941
942   while ((entry = readdir(dp))) {
943     unsigned u;
944     char *cmd, **curname;
945
946     if (!(u = atoi(entry->d_name))) continue;
947     sprintf(libbuf, "/proc/%u/cmdline", u);
948     if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
949
950     for (curname = names; *curname; curname++)
951       if (**curname == '/' ? !strcmp(cmd, *curname)
952           : !strcmp(getbasename(cmd), getbasename(*curname)))
953         if (callback(u, *curname)) break;
954     if (*curname) break;
955   }
956   closedir(dp);
957 }
958
959 // display first few digits of number with power of two units
960 int human_readable(char *buf, unsigned long long num, int style)
961 {
962   unsigned long long snap = 0;
963   int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
964
965   // Divide rounding up until we have 3 or fewer digits. Since the part we
966   // print is decimal, the test is 999 even when we divide by 1024.
967   // We can't run out of units because 2<<64 is 18 exabytes.
968   // test 5675 is 5.5k not 5.6k.
969   for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
970   len = sprintf(buf, "%llu", num);
971   if (unit && len == 1) {
972     // Redo rounding for 1.2M case, this works with and without HR_1000.
973     num = snap/divisor;
974     snap -= num*divisor;
975     snap = ((snap*100)+50)/divisor;
976     snap /= 10;
977     len = sprintf(buf, "%llu.%llu", num, snap);
978   }
979   if (style & HR_SPACE) buf[len++] = ' ';
980   if (unit) {
981     unit = " kMGTPE"[unit];
982
983     if (!(style&HR_1000)) unit = toupper(unit);
984     buf[len++] = unit;
985   } else if (style & HR_B) buf[len++] = 'B';
986   buf[len] = 0;
987
988   return len;
989 }
990
991 // The qsort man page says you can use alphasort, the posix committee
992 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
993 // So just do our own. (The const is entirely to humor the stupid compiler.)
994 int qstrcmp(const void *a, const void *b)
995 {
996   return strcmp(*(char **)a, *(char **)b);
997 }
998
999 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
1000 // we should generate a uuid structure by reading a clock with 100 nanosecond
1001 // precision, normalizing it to the start of the gregorian calendar in 1582,
1002 // and looking up our eth0 mac address.
1003 //
1004 // On the other hand, we have 128 bits to come up with a unique identifier, of
1005 // which 6 have a defined value.  /dev/urandom it is.
1006
1007 void create_uuid(char *uuid)
1008 {
1009   // Read 128 random bits
1010   int fd = xopen("/dev/urandom", O_RDONLY);
1011   xreadall(fd, uuid, 16);
1012   close(fd);
1013
1014   // Claim to be a DCE format UUID.
1015   uuid[6] = (uuid[6] & 0x0F) | 0x40;
1016   uuid[8] = (uuid[8] & 0x3F) | 0x80;
1017
1018   // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1019   // set bit 1 of the node ID, which is the mac multicast bit.  This means we
1020   // should never collide with anybody actually using a macaddr.
1021   uuid[11] |= 128;
1022 }
1023
1024 char *show_uuid(char *uuid)
1025 {
1026   char *out = libbuf;
1027   int i;
1028
1029   for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1030   *out = 0;
1031
1032   return libbuf;
1033 }
1034
1035 // Returns pointer to letter at end, 0 if none. *start = initial %
1036 char *next_printf(char *s, char **start)
1037 {
1038   for (; *s; s++) {
1039     if (*s != '%') continue;
1040     if (*++s == '%') continue;
1041     if (start) *start = s-1;
1042     while (0 <= stridx("0'#-+ ", *s)) s++;
1043     while (isdigit(*s)) s++;
1044     if (*s == '.') s++;
1045     while (isdigit(*s)) s++;
1046
1047     return s;
1048   }
1049
1050   return 0;
1051 }
1052
1053 // Posix inexplicably hasn't got this, so find str in line.
1054 char *strnstr(char *line, char *str)
1055 {
1056   long len = strlen(str);
1057   char *s;
1058
1059   for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break;
1060
1061   return *s ? s : 0;
1062 }
1063
1064 int dev_minor(int dev)
1065 {
1066   return ((dev&0xfff00000)>>12)|(dev&0xff);
1067 }
1068
1069 int dev_major(int dev)
1070 {
1071   return (dev&0xfff00)>>8;
1072 }
1073
1074 int dev_makedev(int major, int minor)
1075 {
1076   return (minor&0xff)|((major&0xfff)<<8)|((minor&0xfff00)<<12);
1077 }
1078
1079 // Return cached passwd entries.
1080 struct passwd *bufgetpwuid(uid_t uid)
1081 {
1082   struct pwuidbuf_list {
1083     struct pwuidbuf_list *next;
1084     struct passwd pw;
1085   } *list;
1086   struct passwd *temp;
1087   static struct pwuidbuf_list *pwuidbuf;
1088
1089   for (list = pwuidbuf; list; list = list->next)
1090     if (list->pw.pw_uid == uid) return &(list->pw);
1091
1092   list = xmalloc(512);
1093   list->next = pwuidbuf;
1094
1095   errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1096     512-sizeof(*list), &temp);
1097   if (!temp) {
1098     free(list);
1099
1100     return 0;
1101   }
1102   pwuidbuf = list;
1103
1104   return &list->pw;
1105 }
1106
1107 // Return cached passwd entries.
1108 struct group *bufgetgrgid(gid_t gid)
1109 {
1110   struct grgidbuf_list {
1111     struct grgidbuf_list *next;
1112     struct group gr;
1113   } *list;
1114   struct group *temp;
1115   static struct grgidbuf_list *grgidbuf;
1116
1117   for (list = grgidbuf; list; list = list->next)
1118     if (list->gr.gr_gid == gid) return &(list->gr);
1119
1120   list = xmalloc(512);
1121   list->next = grgidbuf;
1122
1123   errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1124     512-sizeof(*list), &temp);
1125   if (!temp) {
1126     free(list);
1127
1128     return 0;
1129   }
1130   grgidbuf = list;
1131
1132   return &list->gr;
1133 }
1134
1135 // Always null terminates, returns 0 for failure, len for success
1136 int readlinkat0(int dirfd, char *path, char *buf, int len)
1137 {
1138   if (!len) return 0;
1139
1140   len = readlinkat(dirfd, path, buf, len-1);
1141   if (len<1) return 0;
1142   buf[len] = 0;
1143
1144   return len;
1145 }
1146
1147 int readlink0(char *path, char *buf, int len)
1148 {
1149   return readlinkat0(AT_FDCWD, path, buf, len);
1150 }