1 /* lib.c - various reusable stuff.
3 * Copyright 2006 Rob Landley <rob@landley.net>
9 void verror_msg(char *msg, int err, va_list va)
13 fprintf(stderr, "%s: ", toys.which->name);
14 if (msg) vfprintf(stderr, msg, va);
16 if (err>0) fprintf(stderr, s, strerror(err));
17 if (err<0 && CFG_TOYBOX_HELP)
18 fprintf(stderr, " (see \"%s --help\")", toys.which->name);
19 if (msg || err) putc('\n', stderr);
20 if (!toys.exitval) toys.exitval++;
23 // These functions don't collapse together because of the va_stuff.
25 void error_msg(char *msg, ...)
30 verror_msg(msg, 0, va);
34 void perror_msg(char *msg, ...)
39 verror_msg(msg, errno, va);
43 // Die with an error message.
44 void error_exit(char *msg, ...)
49 verror_msg(msg, 0, va);
55 // Die with an error message and strerror(errno)
56 void perror_exit(char *msg, ...)
61 verror_msg(msg, errno, va);
67 // Exit with an error message after showing help text.
68 void help_exit(char *msg, ...)
72 if (!msg) show_help(stdout);
75 verror_msg(msg, -1, va);
82 // If you want to explicitly disable the printf() behavior (because you're
83 // printing user-supplied data, or because android's static checker produces
84 // false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
85 // -Werror there for policy reasons).
86 void error_msg_raw(char *msg)
91 void perror_msg_raw(char *msg)
93 perror_msg("%s", msg);
96 void error_exit_raw(char *msg)
98 error_exit("%s", msg);
101 void perror_exit_raw(char *msg)
103 perror_exit("%s", msg);
106 // Keep reading until full or EOF
107 ssize_t readall(int fd, void *buf, size_t len)
112 int i = read(fd, (char *)buf+count, len-count);
121 // Keep writing until done or EOF
122 ssize_t writeall(int fd, void *buf, size_t len)
126 int i = write(fd, count+(char *)buf, len-count);
134 // skip this many bytes of input. Return 0 for success, >0 means this much
135 // left after input skipped.
136 off_t lskip(int fd, off_t offset)
138 off_t cur = lseek(fd, 0, SEEK_CUR);
141 off_t end = lseek(fd, 0, SEEK_END) - cur;
143 if (end > 0 && end < offset) return offset - end;
145 if (end == lseek(fd, end, SEEK_SET)) return 0;
146 perror_exit("lseek");
150 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
152 or = readall(fd, libbuf, try);
153 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
161 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
162 // 2=make path (already exists is ok)
164 // returns 0 = path ok, 1 = error
165 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
170 // mkdir -p one/two/three is not an error if the path already exists,
171 // but is if "three" is a file. The others we dereference and catch
172 // not-a-directory along the way, but the last one we must explicitly
173 // test for. Might as well do it up front.
175 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
180 for (s = dir; ;s++) {
182 mode_t mode = (0777&~toys.old_umask)|0300;
184 // find next '/', but don't try to mkdir "" at start of absolute path
185 if (*s == '/' && (flags&2) && s != dir) {
188 } else if (*s) continue;
190 // Use the mode from the -m option only for the last directory.
192 if (flags&1) mode = lastmode;
196 if (mkdirat(atfd, dir, mode)) {
197 if (!(flags&2) || errno != EEXIST) return 1;
199 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
201 if (!(*s = save)) break;
207 // Split a path into linked list of components, tracking head and tail of list.
208 // Filters out // entries with no contents.
209 struct string_list **splitpath(char *path, struct string_list **list)
217 if (*path && *path != '/') continue;
220 *list = xmalloc(sizeof(struct string_list) + len + 1);
222 memcpy((*list)->str, new, len);
223 (*list)->str[len] = 0;
224 list = &(*list)->next;
232 // Find all file in a colon-separated path with access type "type" (generally
233 // X_OK or R_OK). Returns a list of absolute paths to each file found, in
236 struct string_list *find_in_path(char *path, char *filename)
238 struct string_list *rlist = NULL, **prlist=&rlist;
245 char *next = strchr(path, ':');
246 int len = next ? next-path : strlen(path);
247 struct string_list *rnext;
250 rnext = xmalloc(sizeof(void *) + strlen(filename)
251 + (len ? len : strlen(cwd)) + 2);
252 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
254 char *res = rnext->str;
256 memcpy(res, path, len);
259 strcpy(res, filename);
262 // Confirm it's not a directory.
263 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
266 prlist = &(rnext->next);
278 long long estrtol(char *str, char **end, int base)
282 return strtoll(str, end, base);
285 long long xstrtol(char *str, char **end, int base)
287 long long l = estrtol(str, end, base);
289 if (errno) perror_exit_raw(str);
294 // atol() with the kilo/mega/giga/tera/peta/exa extensions, plus word and block.
295 // (zetta and yotta don't fit in 64 bits.)
296 long long atolx(char *numstr)
298 char *c = numstr, *suffixes="cwbkmgtpe", *end;
301 val = xstrtol(numstr, &c, 0);
302 if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) {
303 int shift = end-suffixes-2;
305 if (shift==-1) val *= 2;
306 if (!shift) val *= 512;
308 if (toupper(*++c)=='d') while (shift--) val *= 1000;
309 else val *= 1LL<<(shift*10);
312 while (isspace(*c)) c++;
313 if (c==numstr || *c) error_exit("not integer: %s", numstr);
318 long long atolx_range(char *numstr, long long low, long long high)
320 long long val = atolx(numstr);
322 if (val < low) error_exit("%lld < %lld", val, low);
323 if (val > high) error_exit("%lld > %lld", val, high);
328 int stridx(char *haystack, char needle)
332 if (!needle) return -1;
333 off = strchr(haystack, needle);
339 // Convert utf8 sequence to a unicode wide character
340 int utf8towc(wchar_t *wc, char *str, unsigned len)
342 unsigned result, mask, first;
346 if (len && *str<128) return !!(*wc = *str);
348 result = first = *(s = str++);
349 if (result<0xc2 || result>0xf4) return -1;
350 for (mask = 6; (first&0xc0)==0xc0; mask += 5, first <<= 1) {
351 if (!--len) return -2;
352 if (((c = *(str++))&0xc0) != 0x80) return -1;
353 result = (result<<6)|(c&0x3f);
355 result &= (1<<mask)-1;
358 // Avoid overlong encodings
359 if (result<(unsigned []){0x80,0x800,0x10000}[c-2]) return -1;
361 // Limit unicode so it can't encode anything UTF-16 can't.
362 if (result>0x10ffff || (result>=0xd800 && result<=0xdfff)) return -1;
368 char *strlower(char *s)
372 if (!CFG_TOYBOX_I18N) {
373 try = new = xstrdup(s);
374 for (; *s; s++) *(new++) = tolower(*s);
376 // I can't guarantee the string _won't_ expand during reencoding, so...?
377 try = new = xmalloc(strlen(s)*2+1);
381 int len = utf8towc(&c, s, MB_CUR_MAX);
383 if (len < 1) *(new++) = *(s++);
386 // squash title case too
389 // if we had a valid utf8 sequence, convert it to lower case, and can't
390 // encode back to utf8, something is wrong with your libc. But just
391 // in case somebody finds an exploit...
392 len = wcrtomb(new, c, 0);
393 if (len < 1) error_exit("bad utf8 %x", (int)c);
403 // strstr but returns pointer after match
404 char *strafter(char *haystack, char *needle)
406 char *s = strstr(haystack, needle);
408 return s ? s+strlen(needle) : s;
411 // Remove trailing \n
414 char *p = strrchr(s, '\n');
416 if (p && !p[1]) *p = 0;
422 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
423 int idx = stridx(from, c);
425 return (idx == -1) ? 0 : to[idx];
428 // If string ends with suffix return pointer to start of suffix in string,
430 char *strend(char *str, char *suffix)
432 long a = strlen(str), b = strlen(suffix);
434 if (a>b && !strcmp(str += a-b, suffix)) return str;
439 // If *a starts with b, advance *a past it and return 1, else return 0;
440 int strstart(char **a, char *b)
442 int len = strlen(b), i = !strncmp(*a, b, len);
449 // Return how long the file at fd is, if there's any way to determine it.
450 off_t fdlength(int fd)
453 off_t base = 0, range = 1, expand = 1, old;
455 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
457 // If the ioctl works for this, return it.
458 // TODO: is blocksize still always 512, or do we stat for it?
459 // unsigned int size;
460 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
462 // If not, do a binary search for the last location we can read. (Some
463 // block devices don't do BLKGETSIZE right.) This should probably have
464 // a CONFIG option...
466 // If not, do a binary search for the last location we can read.
468 old = lseek(fd, 0, SEEK_CUR);
471 off_t pos = base + range / 2;
473 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
474 off_t delta = (pos + 1) - base;
477 if (expand) range = (expand <<= 1) - base;
485 lseek(fd, old, SEEK_SET);
490 // Read contents of file as a single nul-terminated string.
491 // measure file size if !len, allocate buffer if !buf
492 // Existing buffers need len in *plen
493 // Returns amount of data read in *plen
494 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
500 // Unsafe to probe for size with a supplied buffer, don't ever do that.
501 if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
503 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
505 // If we dunno the length, probe it. If we can't probe, start with 1 page.
507 if ((len = fdlength(fd))>0) *plen = len;
509 } else len = *plen-1;
511 if (!ibuf) buf = xmalloc(len+1);
515 rlen = readall(fd, rbuf, len);
516 if (*plen || rlen<len) break;
518 // If reading unknown size, expand buffer by 1.5 each time we fill it up.
520 buf = xrealloc(buf, len = (rlen*3)/2);
524 *plen = len = rlen+(rbuf-buf);
528 if (ibuf != buf) free(buf);
535 char *readfile(char *name, char *ibuf, off_t len)
537 return readfileat(AT_FDCWD, name, ibuf, &len);
540 // Sleep for this many thousandths of a second
541 void msleep(long miliseconds)
545 ts.tv_sec = miliseconds/1000;
546 ts.tv_nsec = (miliseconds%1000)*1000000;
550 // return 1<<x of highest bit set
551 int highest_bit(unsigned long l)
555 for (i = 0; l; i++) l >>= 1;
560 // Inefficient, but deals with unaligned access
561 int64_t peek_le(void *ptr, unsigned size)
567 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
571 int64_t peek_be(void *ptr, unsigned size)
577 for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
581 int64_t peek(void *ptr, unsigned size)
583 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
586 void poke(void *ptr, uint64_t val, int size)
589 volatile uint64_t *p = (uint64_t *)ptr;
591 } else if (size & 4) {
592 volatile int *p = (int *)ptr;
594 } else if (size & 2) {
595 volatile short *p = (short *)ptr;
598 volatile char *p = (char *)ptr;
603 // Iterate through an array of files, opening each one and calling a function
604 // on that filehandle and name. The special filename "-" means stdin if
605 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
606 // function() on just stdin/stdout.
608 // Note: pass O_CLOEXEC to automatically close filehandles when function()
609 // returns, otherwise filehandles must be closed by function().
610 // pass WARN_ONLY to produce warning messages about files it couldn't
611 // open/create, and skip them. Otherwise function is called with fd -1.
612 void loopfiles_rw(char **argv, int flags, int permissions,
613 void (*function)(int fd, char *name))
615 int fd, failok = !(flags&WARN_ONLY);
619 // If no arguments, read from stdin.
620 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
622 // Filename "-" means read from stdin.
623 // Inability to open a file prints a warning, but doesn't exit.
625 if (!strcmp(*argv, "-")) fd = 0;
626 else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
627 perror_msg_raw(*argv);
631 if ((flags & O_CLOEXEC) && fd) close(fd);
635 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
636 void loopfiles(char **argv, void (*function)(int fd, char *name))
638 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
641 // call loopfiles with do_lines()
642 static void (*do_lines_bridge)(char **pline, long len);
643 static void loopfile_lines_bridge(int fd, char *name)
645 do_lines(fd, do_lines_bridge);
648 void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
650 do_lines_bridge = function;
651 loopfiles(argv, loopfile_lines_bridge);
656 char *get_rawline(int fd, long *plen, char end)
662 if (1>read(fd, &c, 1)) break;
663 if (!(len & 63)) buf=xrealloc(buf, len+65);
664 if ((buf[len++]=c) == end) break;
667 if (plen) *plen = len;
672 char *get_line(int fd)
675 char *buf = get_rawline(fd, &len, '\n');
677 if (buf && buf[--len]=='\n') buf[len]=0;
682 int wfchmodat(int fd, char *name, mode_t mode)
684 int rc = fchmodat(fd, name, mode, 0);
687 perror_msg("chmod '%s' to %04o", name, mode);
693 static char *tempfile2zap;
694 static void tempfile_handler(void)
696 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
699 // Open a temporary file to copy an existing file into.
700 int copy_tempfile(int fdin, char *name, char **tempname)
704 int ignored __attribute__((__unused__));
706 *tempname = xmprintf("%s%s", name, "XXXXXX");
707 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
708 if (!tempfile2zap) sigatexit(tempfile_handler);
709 tempfile2zap = *tempname;
711 // Set permissions of output file (ignoring errors, usually due to nonroot)
713 fstat(fdin, &statbuf);
714 fchmod(fd, statbuf.st_mode);
716 // We chmod before chown, which strips the suid bit. Caller has to explicitly
717 // switch it back on if they want to keep suid.
719 // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
720 // this but it's _supposed_ to fail when we're not root.
721 ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
726 // Abort the copy and delete the temporary file.
727 void delete_tempfile(int fdin, int fdout, char **tempname)
731 if (*tempname) unlink(*tempname);
732 tempfile2zap = (char *)1;
737 // Copy the rest of the data and replace the original with the copy.
738 void replace_tempfile(int fdin, int fdout, char **tempname)
740 char *temp = xstrdup(*tempname);
742 temp[strlen(temp)-6]=0;
744 xsendfile(fdin, fdout);
748 rename(*tempname, temp);
749 tempfile2zap = (char *)1;
755 // Create a 256 entry CRC32 lookup table.
757 void crc_init(unsigned int *crc_table, int little_endian)
761 // Init the CRC32 table (big endian)
762 for (i=0; i<256; i++) {
763 unsigned int j, c = little_endian ? i : i<<24;
765 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
766 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
773 void base64_init(char *p)
777 for (i = 'A'; i != ':'; i++) {
778 if (i == 'Z'+1) i = 'a';
779 if (i == 'z'+1) i = '0';
790 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
792 while (fread(&buf, 1, 1, stdin)) {
795 // The letter changes the value, the newline (or space) returns it.
796 if (isspace(buf)) break;
797 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
808 // Signals required by POSIX 2008:
809 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
811 #define SIGNIFY(x) {SIG##x, #x}
813 static struct signame signames[] = {
814 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
815 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
816 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
817 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
818 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
820 // Start of non-terminal signals
822 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
823 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
826 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
827 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
829 // Handler that sets toys.signal, and writes to toys.signalfd if set
830 void generic_signal(int sig)
835 writeall(toys.signalfd, &c, 1);
840 void exit_signal(int sig)
842 if (sig) toys.exitval = sig|128;
846 // Install the same handler on every signal that defaults to killing the
847 // process, calling the handler on the way out. Calling multiple times
848 // adds the handlers to a list, to be called in order.
849 void sigatexit(void *handler)
851 struct arg_list *al = xmalloc(sizeof(struct arg_list));
854 for (i=0; signames[i].num != SIGCHLD; i++)
855 signal(signames[i].num, exit_signal);
856 al->next = toys.xexit;
861 // Convert name to signal number. If name == NULL print names.
862 int sig_to_num(char *pidstr)
869 i = estrtol(pidstr, &s, 10);
870 if (!errno && !*s) return i;
872 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
874 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
875 if (!pidstr) xputs(signames[i].name);
876 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
881 char *num_to_sig(int sig)
885 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
886 if (signames[i].num == sig) return signames[i].name;
890 // premute mode bits based on posix mode strings.
891 mode_t string_to_mode(char *modestr, mode_t mode)
893 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
895 mode_t extrabits = mode & ~(07777);
899 mode = estrtol(str, &s, 8);
900 if (errno || *s || (mode & ~(07777))) goto barf;
902 return mode | extrabits;
905 // Gaze into the bin of permission...
907 int i, j, dowho, dohow, dowhat, amask;
909 dowho = dohow = dowhat = amask = 0;
911 // Find the who, how, and what stanzas, in that order
912 while (*str && (s = strchr(whos, *str))) {
913 dowho |= 1<<(s-whos);
916 // If who isn't specified, like "a" but honoring umask.
919 umask(amask=umask(0));
921 if (!*str || !(s = strchr(hows, *str))) goto barf;
924 if (!dohow) goto barf;
925 while (*str && (s = strchr(whats, *str))) {
926 dowhat |= 1<<(s-whats);
930 // Convert X to x for directory or if already executable somewhere
931 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
933 // Copy mode from another category?
934 if (!dowhat && *str && (s = strchr(whys, *str))) {
935 dowhat = (mode>>(3*(s-whys)))&7;
939 // Are we ready to do a thing yet?
940 if (*str && *(str++) != ',') goto barf;
942 // Ok, apply the bits to the mode.
943 for (i=0; i<4; i++) {
944 for (j=0; j<3; j++) {
946 int where = 1<<((3*i)+j);
948 if (amask & where) continue;
950 // Figure out new value at this location
954 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
955 } else if (dowhat & 16) bit++;
957 if (!(dowho&(8|(1<<i)))) continue;
958 if (dowhat&(1<<j)) bit++;
961 // When selection active, modify bit
963 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
964 if (bit && dohow != '-') mode |= where;
971 return mode|extrabits;
973 error_exit("bad mode '%s'", modestr);
976 // Format access mode into a drwxrwxrwx string
977 void mode_to_string(mode_t mode, char *buf)
983 for (i=0; i<9; i++) {
986 if (!c && (mode & (1<<((d=i/3)+9)))) {
988 if (!bit) c &= ~0x20;
989 } else c = bit ? "xwr"[c] : '-';
993 if (S_ISDIR(mode)) c = 'd';
994 else if (S_ISBLK(mode)) c = 'b';
995 else if (S_ISCHR(mode)) c = 'c';
996 else if (S_ISLNK(mode)) c = 'l';
997 else if (S_ISFIFO(mode)) c = 'p';
998 else if (S_ISSOCK(mode)) c = 's';
1003 // basename() can modify its argument or return a pointer to a constant string
1004 // This just gives after the last '/' or the whole stirng if no /
1005 char *getbasename(char *name)
1007 char *s = strrchr(name, '/');
1014 // Execute a callback for each PID that matches a process name from a list.
1015 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
1018 struct dirent *entry;
1020 if (!(dp = opendir("/proc"))) perror_exit("no /proc");
1022 while ((entry = readdir(dp))) {
1023 unsigned u = atoi(entry->d_name);
1024 char *cmd = 0, *comm, **cur;
1029 // Comm is original name of executable (argv[0] could be #! interpreter)
1030 // but it's limited to 15 characters
1031 sprintf(libbuf, "/proc/%u/comm", u);
1032 len = sizeof(libbuf);
1033 if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
1035 if (libbuf[len-1] == '\n') libbuf[--len] = 0;
1037 for (cur = names; *cur; cur++) {
1038 struct stat st1, st2;
1039 char *bb = basename(*cur);
1042 // fast path: only matching a filename (no path) that fits in comm
1043 if (strncmp(comm, bb, 15)) continue;
1045 if (bb==*cur && len<16) goto match;
1047 // If we have a path to existing file only match if same inode
1048 if (bb!=*cur && !stat(*cur, &st1)) {
1051 sprintf(buf, "/proc/%u/exe", u);
1052 if (stat(buf, &st1)) continue;
1053 if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) continue;
1057 // Nope, gotta read command line to confirm
1059 sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1060 len = sizeof(libbuf)-17;
1061 if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1062 // readfile only guarnatees one null terminator and we need two
1063 // (yes the kernel should do this for us, don't care)
1066 if (!strcmp(bb, basename(cmd))) goto match;
1067 if (bb!=*cur && !strcmp(bb, basename(cmd+strlen(cmd)+1))) goto match;
1070 if (callback(u, *cur)) break;
1076 // display first few digits of number with power of two units
1077 int human_readable(char *buf, unsigned long long num, int style)
1079 unsigned long long snap = 0;
1080 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
1082 // Divide rounding up until we have 3 or fewer digits. Since the part we
1083 // print is decimal, the test is 999 even when we divide by 1024.
1084 // We can't run out of units because 2<<64 is 18 exabytes.
1085 // test 5675 is 5.5k not 5.6k.
1086 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
1087 len = sprintf(buf, "%llu", num);
1088 if (unit && len == 1) {
1089 // Redo rounding for 1.2M case, this works with and without HR_1000.
1091 snap -= num*divisor;
1092 snap = ((snap*100)+50)/divisor;
1094 len = sprintf(buf, "%llu.%llu", num, snap);
1096 if (style & HR_SPACE) buf[len++] = ' ';
1098 unit = " kMGTPE"[unit];
1100 if (!(style&HR_1000)) unit = toupper(unit);
1102 } else if (style & HR_B) buf[len++] = 'B';
1108 // The qsort man page says you can use alphasort, the posix committee
1109 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1110 // So just do our own. (The const is entirely to humor the stupid compiler.)
1111 int qstrcmp(const void *a, const void *b)
1113 return strcmp(*(char **)a, *(char **)b);
1116 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
1117 // we should generate a uuid structure by reading a clock with 100 nanosecond
1118 // precision, normalizing it to the start of the gregorian calendar in 1582,
1119 // and looking up our eth0 mac address.
1121 // On the other hand, we have 128 bits to come up with a unique identifier, of
1122 // which 6 have a defined value. /dev/urandom it is.
1124 void create_uuid(char *uuid)
1126 // Read 128 random bits
1127 int fd = xopenro("/dev/urandom");
1128 xreadall(fd, uuid, 16);
1131 // Claim to be a DCE format UUID.
1132 uuid[6] = (uuid[6] & 0x0F) | 0x40;
1133 uuid[8] = (uuid[8] & 0x3F) | 0x80;
1135 // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1136 // set bit 1 of the node ID, which is the mac multicast bit. This means we
1137 // should never collide with anybody actually using a macaddr.
1141 char *show_uuid(char *uuid)
1146 for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1152 // Returns pointer to letter at end, 0 if none. *start = initial %
1153 char *next_printf(char *s, char **start)
1156 if (*s != '%') continue;
1157 if (*++s == '%') continue;
1158 if (start) *start = s-1;
1159 while (0 <= stridx("0'#-+ ", *s)) s++;
1160 while (isdigit(*s)) s++;
1162 while (isdigit(*s)) s++;
1170 // Posix inexplicably hasn't got this, so find str in line.
1171 char *strnstr(char *line, char *str)
1173 long len = strlen(str);
1176 for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break;
1181 int dev_minor(int dev)
1183 return ((dev&0xfff00000)>>12)|(dev&0xff);
1186 int dev_major(int dev)
1188 return (dev&0xfff00)>>8;
1191 int dev_makedev(int major, int minor)
1193 return (minor&0xff)|((major&0xfff)<<8)|((minor&0xfff00)<<12);
1196 // Return cached passwd entries.
1197 struct passwd *bufgetpwuid(uid_t uid)
1199 struct pwuidbuf_list {
1200 struct pwuidbuf_list *next;
1203 struct passwd *temp;
1204 static struct pwuidbuf_list *pwuidbuf;
1206 for (list = pwuidbuf; list; list = list->next)
1207 if (list->pw.pw_uid == uid) return &(list->pw);
1209 list = xmalloc(512);
1210 list->next = pwuidbuf;
1212 errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1213 512-sizeof(*list), &temp);
1224 // Return cached passwd entries.
1225 struct group *bufgetgrgid(gid_t gid)
1227 struct grgidbuf_list {
1228 struct grgidbuf_list *next;
1232 static struct grgidbuf_list *grgidbuf;
1234 for (list = grgidbuf; list; list = list->next)
1235 if (list->gr.gr_gid == gid) return &(list->gr);
1237 list = xmalloc(512);
1238 list->next = grgidbuf;
1240 errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1241 512-sizeof(*list), &temp);
1252 // Always null terminates, returns 0 for failure, len for success
1253 int readlinkat0(int dirfd, char *path, char *buf, int len)
1257 len = readlinkat(dirfd, path, buf, len-1);
1258 if (len<1) return 0;
1264 int readlink0(char *path, char *buf, int len)
1266 return readlinkat0(AT_FDCWD, path, buf, len);
1269 // Do regex matching handling embedded NUL bytes in string (hence extra len
1270 // argument). Note that neither the pattern nor the match can currently include
1271 // NUL bytes (even with wildcards) and string must be null terminated at
1272 // string[len]. But this can find a match after the first NUL.
1273 int regexec0(regex_t *preg, char *string, long len, int nmatch,
1274 regmatch_t pmatch[], int eflags)
1282 while (len && !*s) {
1286 while (s[ll] && ll<len) ll++;
1288 rc = regexec(preg, s, nmatch, pmatch, eflags);
1290 for (rc = 0; rc<nmatch && pmatch[rc].rm_so!=-1; rc++) {
1291 pmatch[rc].rm_so += s-string;
1292 pmatch[rc].rm_eo += s-string;
1297 if (ll==len) return rc;
1304 // Return user name or string representation of number, returned buffer
1305 // lasts until next call.
1306 char *getusername(uid_t uid)
1308 struct passwd *pw = bufgetpwuid(uid);
1309 static char unum[12];
1311 sprintf(unum, "%u", (unsigned)uid);
1312 return pw ? pw->pw_name : unum;
1315 // Return group name or string representation of number, returned buffer
1316 // lasts until next call.
1317 char *getgroupname(gid_t gid)
1319 struct group *gr = bufgetgrgid(gid);
1320 static char gnum[12];
1322 sprintf(gnum, "%u", (unsigned)gid);
1323 return gr ? gr->gr_name : gnum;
1326 // Iterate over lines in file, calling function. Function can write 0 to
1327 // the line pointer if they want to keep it, or 1 to terminate processing,
1328 // otherwise line is freed. Passed file descriptor is closed at the end.
1329 void do_lines(int fd, void (*call)(char **pline, long len))
1331 FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1337 len = getline(&line, (void *)&len, fp);
1340 if (line == (void *)1) break;
1348 // Returns the number of bytes taken by the environment variables. For use
1349 // when calculating the maximum bytes of environment+argument data that can
1350 // be passed to exec for find(1) and xargs(1).
1351 long environ_bytes()
1353 long bytes = sizeof(char *);
1356 for (ev = environ; *ev; ev++)
1357 bytes += sizeof(char *) + strlen(*ev) + 1;