1 /* lib.c - various reusable stuff.
3 * Copyright 2006 Rob Landley <rob@landley.net>
8 void verror_msg(char *msg, int err, va_list va)
12 fprintf(stderr, "%s: ", toys.which->name);
13 if (msg) vfprintf(stderr, msg, va);
15 if (err) fprintf(stderr, s, strerror(err));
16 if (msg || err) putc('\n', stderr);
17 if (!toys.exitval) toys.exitval++;
20 // These functions don't collapse together because of the va_stuff.
22 void error_msg(char *msg, ...)
27 verror_msg(msg, 0, va);
31 void perror_msg(char *msg, ...)
36 verror_msg(msg, errno, va);
40 // Die with an error message.
41 void error_exit(char *msg, ...)
46 verror_msg(msg, 0, va);
52 // Die with an error message and strerror(errno)
53 void perror_exit(char *msg, ...)
58 verror_msg(msg, errno, va);
64 // Exit with an error message after showing help text.
65 void help_exit(char *msg, ...)
69 if (CFG_TOYBOX_HELP) show_help(stderr);
73 verror_msg(msg, 0, va);
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)
89 void perror_msg_raw(char *msg)
91 perror_msg("%s", msg);
94 void error_exit_raw(char *msg)
96 error_exit("%s", msg);
99 void perror_exit_raw(char *msg)
101 perror_exit("%s", msg);
104 // Keep reading until full or EOF
105 ssize_t readall(int fd, void *buf, size_t len)
110 int i = read(fd, (char *)buf+count, len-count);
119 // Keep writing until done or EOF
120 ssize_t writeall(int fd, void *buf, size_t len)
124 int i = write(fd, count+(char *)buf, len-count);
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)
136 off_t cur = lseek(fd, 0, SEEK_CUR);
139 off_t end = lseek(fd, 0, SEEK_END) - cur;
141 if (end > 0 && end < offset) return offset - end;
143 if (end == lseek(fd, end, SEEK_SET)) return 0;
144 perror_exit("lseek");
148 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
150 or = readall(fd, libbuf, try);
151 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
159 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
160 // 2=make path (already exists is ok)
162 // returns 0 = path ok, 1 = error
163 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
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.
173 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
178 for (s = dir; ;s++) {
180 mode_t mode = (0777&~toys.old_umask)|0300;
182 // find next '/', but don't try to mkdir "" at start of absolute path
183 if (*s == '/' && (flags&2) && s != dir) {
186 } else if (*s) continue;
188 // Use the mode from the -m option only for the last directory.
190 if (flags&1) mode = lastmode;
194 if (mkdirat(atfd, dir, mode)) {
195 if (!(flags&2) || errno != EEXIST) return 1;
197 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
199 if (!(*s = save)) break;
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)
215 if (*path && *path != '/') continue;
218 *list = xmalloc(sizeof(struct string_list) + len + 1);
220 memcpy((*list)->str, new, len);
221 (*list)->str[len] = 0;
222 list = &(*list)->next;
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
234 struct string_list *find_in_path(char *path, char *filename)
236 struct string_list *rlist = NULL, **prlist=&rlist;
243 char *next = strchr(path, ':');
244 int len = next ? next-path : strlen(path);
245 struct string_list *rnext;
248 rnext = xmalloc(sizeof(void *) + strlen(filename)
249 + (len ? len : strlen(cwd)) + 2);
250 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
252 char *res = rnext->str;
254 memcpy(res, path, len);
257 strcpy(res, filename);
260 // Confirm it's not a directory.
261 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
264 prlist = &(rnext->next);
276 long estrtol(char *str, char **end, int base)
280 return strtol(str, end, base);
283 long xstrtol(char *str, char **end, int base)
285 long l = estrtol(str, end, base);
287 if (errno) perror_exit_raw(str);
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)
296 char *c, *suffixes="cbkmgtpe", *end;
299 val = xstrtol(numstr, &c, 0);
301 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
302 int shift = end-suffixes-2;
303 if (shift >= 0) val *= 1024L<<(shift*10);
305 while (isspace(*c)) c++;
306 if (*c) error_exit("not integer: %s", numstr);
313 long atolx_range(char *numstr, long low, long high)
315 long val = atolx(numstr);
317 if (val < low) error_exit("%ld < %ld", val, low);
318 if (val > high) error_exit("%ld > %ld", val, high);
323 int stridx(char *haystack, char needle)
327 if (!needle) return -1;
328 off = strchr(haystack, needle);
334 char *strlower(char *s)
338 if (!CFG_TOYBOX_I18N) {
339 try = new = xstrdup(s);
340 for (; *s; s++) *(new++) = tolower(*s);
342 // I can't guarantee the string _won't_ expand during reencoding, so...?
343 try = new = xmalloc(strlen(s)*2+1);
347 int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
349 if (len < 1) *(new++) = *(s++);
352 // squash title case too
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);
369 // strstr but returns pointer after match
370 char *strafter(char *haystack, char *needle)
372 char *s = strstr(haystack, needle);
374 return s ? s+strlen(needle) : s;
377 // Remove trailing \n
380 char *p = strrchr(s, '\n');
382 if (p && !p[1]) *p = 0;
388 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
389 int idx = stridx(from, c);
391 return (idx == -1) ? 0 : to[idx];
394 // If *a starts with b, advance *a past it and return 1, else return 0;
395 int strstart(char **a, char *b)
397 int len = strlen(b), i = !strncmp(*a, b, len);
404 // Return how long the file at fd is, if there's any way to determine it.
405 off_t fdlength(int fd)
408 off_t base = 0, range = 1, expand = 1, old;
410 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
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;
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...
421 // If not, do a binary search for the last location we can read.
423 old = lseek(fd, 0, SEEK_CUR);
426 off_t pos = base + range / 2;
428 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
429 off_t delta = (pos + 1) - base;
432 if (expand) range = (expand <<= 1) - base;
440 lseek(fd, old, SEEK_SET);
445 // Read contents of file as a single nul-terminated string.
446 // measure file size if !len, allocate buffer if !buf
447 // note: for existing buffers use len = size-1, will set buf[len] = 0
448 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
454 // Unsafe to probe for size with a supplied buffer, don't ever do that.
455 if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
457 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
459 // If we dunno the length, probe it. If we can't probe, start with 1 page.
461 if ((len = fdlength(fd))>0) *plen = len;
463 } else len = *plen-1;
465 if (!ibuf) buf = xmalloc(len+1);
469 rlen = readall(fd, rbuf, len);
470 if (*plen || rlen<len) break;
472 // If reading unknown size, expand buffer by 1.5 each time we fill it up.
474 buf = xrealloc(buf, len = (rlen*3)/2);
478 *plen = len = rlen+(buf-ibuf);
482 if (ibuf != buf) free(buf);
489 char *readfile(char *name, char *ibuf, off_t len)
491 return readfileat(AT_FDCWD, name, ibuf, &len);
494 // Sleep for this many thousandths of a second
495 void msleep(long miliseconds)
499 ts.tv_sec = miliseconds/1000;
500 ts.tv_nsec = (miliseconds%1000)*1000000;
504 // Inefficient, but deals with unaligned access
505 int64_t peek_le(void *ptr, unsigned size)
511 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
516 int64_t peek_be(void *ptr, unsigned size)
521 while (size--) ret = (ret<<8)|c[size];
526 int64_t peek(void *ptr, unsigned size)
528 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
531 void poke(void *ptr, uint64_t val, int size)
534 volatile uint64_t *p = (uint64_t *)ptr;
536 } else if (size & 4) {
537 volatile int *p = (int *)ptr;
539 } else if (size & 2) {
540 volatile short *p = (short *)ptr;
543 volatile char *p = (char *)ptr;
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.
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))
560 // If no arguments, read from stdin.
561 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
563 // Filename "-" means read from stdin.
564 // Inability to open a file prints a warning, but doesn't exit.
566 if (!strcmp(*argv, "-")) fd=0;
567 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
568 perror_msg_raw(*argv);
572 if (flags & O_CLOEXEC) close(fd);
576 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
577 void loopfiles(char **argv, void (*function)(int fd, char *name))
579 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
584 char *get_rawline(int fd, long *plen, char end)
590 if (1>read(fd, &c, 1)) break;
591 if (!(len & 63)) buf=xrealloc(buf, len+65);
592 if ((buf[len++]=c) == end) break;
595 if (plen) *plen = len;
600 char *get_line(int fd)
603 char *buf = get_rawline(fd, &len, '\n');
605 if (buf && buf[--len]=='\n') buf[len]=0;
610 int wfchmodat(int fd, char *name, mode_t mode)
612 int rc = fchmodat(fd, name, mode, 0);
615 perror_msg("chmod '%s' to %04o", name, mode);
621 static char *tempfile2zap;
622 static void tempfile_handler(int i)
624 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
628 // Open a temporary file to copy an existing file into.
629 int copy_tempfile(int fdin, char *name, char **tempname)
634 *tempname = xmprintf("%s%s", name, "XXXXXX");
635 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
636 if (!tempfile2zap) sigatexit(tempfile_handler);
637 tempfile2zap = *tempname;
639 // Set permissions of output file
641 fstat(fdin, &statbuf);
642 fchmod(fd, statbuf.st_mode);
647 // Abort the copy and delete the temporary file.
648 void delete_tempfile(int fdin, int fdout, char **tempname)
652 if (*tempname) unlink(*tempname);
653 tempfile2zap = (char *)1;
658 // Copy the rest of the data and replace the original with the copy.
659 void replace_tempfile(int fdin, int fdout, char **tempname)
661 char *temp = xstrdup(*tempname);
663 temp[strlen(temp)-6]=0;
665 xsendfile(fdin, fdout);
669 rename(*tempname, temp);
670 tempfile2zap = (char *)1;
676 // Create a 256 entry CRC32 lookup table.
678 void crc_init(unsigned int *crc_table, int little_endian)
682 // Init the CRC32 table (big endian)
683 for (i=0; i<256; i++) {
684 unsigned int j, c = little_endian ? i : i<<24;
686 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
687 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
694 void base64_init(char *p)
698 for (i = 'A'; i != ':'; i++) {
699 if (i == 'Z'+1) i = 'a';
700 if (i == 'z'+1) i = '0';
711 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
713 while (fread(&buf, 1, 1, stdin)) {
716 // The letter changes the value, the newline (or space) returns it.
717 if (isspace(buf)) break;
718 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
729 // Signals required by POSIX 2008:
730 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
732 #define SIGNIFY(x) {SIG##x, #x}
734 static struct signame signames[] = {
735 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
736 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
737 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
738 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
739 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
741 // Start of non-terminal signals
743 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
744 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
747 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
748 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
750 // Handler that sets toys.signal, and writes to toys.signalfd if set
751 void generic_signal(int sig)
756 writeall(toys.signalfd, &c, 1);
761 // Install the same handler on every signal that defaults to killing the process
762 void sigatexit(void *handler)
765 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
768 // Convert name to signal number. If name == NULL print names.
769 int sig_to_num(char *pidstr)
776 i = estrtol(pidstr, &s, 10);
777 if (!errno && !*s) return i;
779 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
781 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
782 if (!pidstr) xputs(signames[i].name);
783 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
788 char *num_to_sig(int sig)
792 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
793 if (signames[i].num == sig) return signames[i].name;
797 // premute mode bits based on posix mode strings.
798 mode_t string_to_mode(char *modestr, mode_t mode)
800 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
802 mode_t extrabits = mode & ~(07777);
806 mode = estrtol(str, &s, 8);
807 if (errno || *s || (mode & ~(07777))) goto barf;
809 return mode | extrabits;
812 // Gaze into the bin of permission...
814 int i, j, dowho, dohow, dowhat, amask;
816 dowho = dohow = dowhat = amask = 0;
818 // Find the who, how, and what stanzas, in that order
819 while (*str && (s = strchr(whos, *str))) {
820 dowho |= 1<<(s-whos);
823 // If who isn't specified, like "a" but honoring umask.
826 umask(amask=umask(0));
828 if (!*str || !(s = strchr(hows, *str))) goto barf;
831 if (!dohow) goto barf;
832 while (*str && (s = strchr(whats, *str))) {
833 dowhat |= 1<<(s-whats);
837 // Convert X to x for directory or if already executable somewhere
838 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
840 // Copy mode from another category?
841 if (!dowhat && *str && (s = strchr(whys, *str))) {
842 dowhat = (mode>>(3*(s-whys)))&7;
846 // Are we ready to do a thing yet?
847 if (*str && *(str++) != ',') goto barf;
849 // Ok, apply the bits to the mode.
850 for (i=0; i<4; i++) {
851 for (j=0; j<3; j++) {
853 int where = 1<<((3*i)+j);
855 if (amask & where) continue;
857 // Figure out new value at this location
861 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
862 } else if (dowhat & 16) bit++;
864 if (!(dowho&(8|(1<<i)))) continue;
865 if (dowhat&(1<<j)) bit++;
868 // When selection active, modify bit
870 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
871 if (bit && dohow != '-') mode |= where;
878 return mode|extrabits;
880 error_exit("bad mode '%s'", modestr);
883 // Format access mode into a drwxrwxrwx string
884 void mode_to_string(mode_t mode, char *buf)
890 for (i=0; i<9; i++) {
893 if (!c && (mode & (1<<((d=i/3)+9)))) {
895 if (!bit) c &= ~0x20;
896 } else c = bit ? "xwr"[c] : '-';
900 if (S_ISDIR(mode)) c = 'd';
901 else if (S_ISBLK(mode)) c = 'b';
902 else if (S_ISCHR(mode)) c = 'c';
903 else if (S_ISLNK(mode)) c = 'l';
904 else if (S_ISFIFO(mode)) c = 'p';
905 else if (S_ISSOCK(mode)) c = 's';
910 char *basename_r(char *name)
912 char *s = strrchr(name, '/');
918 // Execute a callback for each PID that matches a process name from a list.
919 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
922 struct dirent *entry;
924 if (!(dp = opendir("/proc"))) perror_exit("opendir");
926 while ((entry = readdir(dp))) {
928 char *cmd, **curname;
930 if (!(u = atoi(entry->d_name))) continue;
931 sprintf(libbuf, "/proc/%u/cmdline", u);
932 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
934 for (curname = names; *curname; curname++)
935 if (**curname == '/' ? !strcmp(cmd, *curname)
936 : !strcmp(basename_r(cmd), basename_r(*curname)))
937 if (callback(u, *curname)) break;
943 // display first few digits of number with power of two units
944 int human_readable(char *buf, unsigned long long num, int style)
946 unsigned long long snap = 0;
947 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
949 // Divide rounding up until we have 3 or fewer digits. Since the part we
950 // print is decimal, the test is 999 even when we divide by 1024.
951 // We can't run out of units because 2<<64 is 18 exabytes.
952 // test 5675 is 5.5k not 5.6k.
953 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
954 len = sprintf(buf, "%llu", num);
955 if (unit && len == 1) {
956 // Redo rounding for 1.2M case, this works with and without HR_1000.
959 snap = ((snap*100)+50)/divisor;
961 len = sprintf(buf, "%llu.%llu", num, snap);
963 if (style & HR_SPACE) buf[len++] = ' ';
965 unit = " kMGTPE"[unit];
967 if (!(style&HR_1000)) unit = toupper(unit);
969 } else if (style & HR_B) buf[len++] = 'B';
975 // The qsort man page says you can use alphasort, the posix committee
976 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
977 // So just do our own. (The const is entirely to humor the stupid compiler.)
978 int qstrcmp(const void *a, const void *b)
980 return strcmp(*(char **)a, *(char **)b);
983 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
984 // we should generate a uuid structure by reading a clock with 100 nanosecond
985 // precision, normalizing it to the start of the gregorian calendar in 1582,
986 // and looking up our eth0 mac address.
988 // On the other hand, we have 128 bits to come up with a unique identifier, of
989 // which 6 have a defined value. /dev/urandom it is.
991 void create_uuid(char *uuid)
993 // Read 128 random bits
994 int fd = xopen("/dev/urandom", O_RDONLY);
995 xreadall(fd, uuid, 16);
998 // Claim to be a DCE format UUID.
999 uuid[6] = (uuid[6] & 0x0F) | 0x40;
1000 uuid[8] = (uuid[8] & 0x3F) | 0x80;
1002 // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1003 // set bit 1 of the node ID, which is the mac multicast bit. This means we
1004 // should never collide with anybody actually using a macaddr.
1008 char *show_uuid(char *uuid)
1013 for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1019 // Returns pointer to letter at end, 0 if none. *start = initial %
1020 char *next_printf(char *s, char **start)
1023 if (*s != '%') continue;
1024 if (*++s == '%') continue;
1025 if (start) *start = s-1;
1026 while (0 <= stridx("0'#-+ ", *s)) s++;
1027 while (isdigit(*s)) s++;
1029 while (isdigit(*s)) s++;