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 // Exit with an error message after showing help text.
53 void help_exit(char *msg, ...)
57 if (CFG_TOYBOX_HELP) show_help(stderr);
61 verror_msg(msg, 0, va);
68 // Die with an error message and strerror(errno)
69 void perror_exit(char *msg, ...)
74 verror_msg(msg, errno, va);
80 // Keep reading until full or EOF
81 ssize_t readall(int fd, void *buf, size_t len)
86 int i = read(fd, (char *)buf+count, len-count);
95 // Keep writing until done or EOF
96 ssize_t writeall(int fd, void *buf, size_t len)
100 int i = write(fd, count+(char *)buf, len-count);
108 // skip this many bytes of input. Return 0 for success, >0 means this much
109 // left after input skipped.
110 off_t lskip(int fd, off_t offset)
112 off_t cur = lseek(fd, 0, SEEK_CUR);
115 off_t end = lseek(fd, 0, SEEK_END) - cur;
117 if (end > 0 && end < offset) return offset - end;
119 if (end == lseek(fd, end, SEEK_SET)) return 0;
120 perror_exit("lseek");
124 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
126 or = readall(fd, libbuf, try);
127 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
135 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
136 // 2=make path (already exists is ok)
138 // returns 0 = path ok, 1 = error
139 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
144 // mkdir -p one/two/three is not an error if the path already exists,
145 // but is if "three" is a file. The others we dereference and catch
146 // not-a-directory along the way, but the last one we must explicitly
147 // test for. Might as well do it up front.
149 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
154 for (s = dir; ;s++) {
156 mode_t mode = (0777&~toys.old_umask)|0300;
158 // find next '/', but don't try to mkdir "" at start of absolute path
159 if (*s == '/' && (flags&2) && s != dir) {
162 } else if (*s) continue;
164 // Use the mode from the -m option only for the last directory.
166 if (flags&1) mode = lastmode;
170 if (mkdirat(atfd, dir, mode)) {
171 if (!(flags&2) || errno != EEXIST) return 1;
173 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
175 if (!(*s = save)) break;
181 // Split a path into linked list of components, tracking head and tail of list.
182 // Filters out // entries with no contents.
183 struct string_list **splitpath(char *path, struct string_list **list)
191 if (*path && *path != '/') continue;
194 *list = xmalloc(sizeof(struct string_list) + len + 1);
196 memcpy((*list)->str, new, len);
197 (*list)->str[len] = 0;
198 list = &(*list)->next;
206 // Find all file in a colon-separated path with access type "type" (generally
207 // X_OK or R_OK). Returns a list of absolute paths to each file found, in
210 struct string_list *find_in_path(char *path, char *filename)
212 struct string_list *rlist = NULL, **prlist=&rlist;
219 char *next = strchr(path, ':');
220 int len = next ? next-path : strlen(path);
221 struct string_list *rnext;
224 rnext = xmalloc(sizeof(void *) + strlen(filename)
225 + (len ? len : strlen(cwd)) + 2);
226 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
228 char *res = rnext->str;
230 memcpy(res, path, len);
233 strcpy(res, filename);
236 // Confirm it's not a directory.
237 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
240 prlist = &(rnext->next);
252 long estrtol(char *str, char **end, int base)
256 return strtol(str, end, base);
259 long xstrtol(char *str, char **end, int base)
261 long l = estrtol(str, end, base);
263 if (errno) perror_exit("%s", str);
268 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
269 // (zetta and yotta don't fit in 64 bits.)
270 long atolx(char *numstr)
272 char *c, *suffixes="cbkmgtpe", *end;
275 val = xstrtol(numstr, &c, 0);
277 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
278 int shift = end-suffixes-2;
279 if (shift >= 0) val *= 1024L<<(shift*10);
281 while (isspace(*c)) c++;
282 if (*c) error_exit("not integer: %s", numstr);
289 long atolx_range(char *numstr, long low, long high)
291 long val = atolx(numstr);
293 if (val < low) error_exit("%ld < %ld", val, low);
294 if (val > high) error_exit("%ld > %ld", val, high);
299 int stridx(char *haystack, char needle)
303 if (!needle) return -1;
304 off = strchr(haystack, needle);
310 char *strlower(char *s)
314 if (!CFG_TOYBOX_I18N) {
315 try = new = xstrdup(s);
316 for (; *s; s++) *(new++) = tolower(*s);
318 // I can't guarantee the string _won't_ expand during reencoding, so...?
319 try = new = xmalloc(strlen(s)*2+1);
323 int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
325 if (len < 1) *(new++) = *(s++);
328 // squash title case too
331 // if we had a valid utf8 sequence, convert it to lower case, and can't
332 // encode back to utf8, something is wrong with your libc. But just
333 // in case somebody finds an exploit...
334 len = wcrtomb(new, c, 0);
335 if (len < 1) error_exit("bad utf8 %x", (int)c);
347 char *p = strrchr(s, '\n');
355 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
356 int idx = stridx(from, c);
358 return (idx == -1) ? 0 : to[idx];
361 // If *a starts with b, advance *a past it and return 1, else return 0;
362 int strstart(char **a, char *b)
364 int len = strlen(b), i = !strncmp(*a, b, len);
371 // Return how long the file at fd is, if there's any way to determine it.
372 off_t fdlength(int fd)
375 off_t base = 0, range = 1, expand = 1, old;
377 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
379 // If the ioctl works for this, return it.
380 // TODO: is blocksize still always 512, or do we stat for it?
381 // unsigned int size;
382 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
384 // If not, do a binary search for the last location we can read. (Some
385 // block devices don't do BLKGETSIZE right.) This should probably have
386 // a CONFIG option...
388 // If not, do a binary search for the last location we can read.
390 old = lseek(fd, 0, SEEK_CUR);
393 off_t pos = base + range / 2;
395 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
396 off_t delta = (pos + 1) - base;
399 if (expand) range = (expand <<= 1) - base;
407 lseek(fd, old, SEEK_SET);
412 // Read contents of file as a single nul-terminated string.
413 // malloc new one if buf=len=0
414 char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
419 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
422 // proc files don't report a length, so try 1 page minimum.
423 if (len<4096) len = 4096;
425 if (!ibuf) buf = xmalloc(len+1);
428 len = readall(fd, buf, len-1);
431 if (ibuf != buf) free(buf);
438 char *readfile(char *name, char *ibuf, off_t len)
440 return readfileat(AT_FDCWD, name, ibuf, len);
443 // Sleep for this many thousandths of a second
444 void msleep(long miliseconds)
448 ts.tv_sec = miliseconds/1000;
449 ts.tv_nsec = (miliseconds%1000)*1000000;
453 // Inefficient, but deals with unaligned access
454 int64_t peek_le(void *ptr, unsigned size)
460 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
465 int64_t peek_be(void *ptr, unsigned size)
470 while (size--) ret = (ret<<8)|c[size];
475 int64_t peek(void *ptr, unsigned size)
477 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
480 void poke(void *ptr, uint64_t val, int size)
483 volatile uint64_t *p = (uint64_t *)ptr;
485 } else if (size & 4) {
486 volatile int *p = (int *)ptr;
488 } else if (size & 2) {
489 volatile short *p = (short *)ptr;
492 volatile char *p = (char *)ptr;
497 // Iterate through an array of files, opening each one and calling a function
498 // on that filehandle and name. The special filename "-" means stdin if
499 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
500 // function() on just stdin/stdout.
502 // Note: pass O_CLOEXEC to automatically close filehandles when function()
503 // returns, otherwise filehandles must be closed by function()
504 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
505 void (*function)(int fd, char *name))
509 // If no arguments, read from stdin.
510 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
512 // Filename "-" means read from stdin.
513 // Inability to open a file prints a warning, but doesn't exit.
515 if (!strcmp(*argv, "-")) fd=0;
516 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
517 perror_msg("%s", *argv);
522 if (flags & O_CLOEXEC) close(fd);
526 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
527 void loopfiles(char **argv, void (*function)(int fd, char *name))
529 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
534 char *get_rawline(int fd, long *plen, char end)
540 if (1>read(fd, &c, 1)) break;
541 if (!(len & 63)) buf=xrealloc(buf, len+65);
542 if ((buf[len++]=c) == end) break;
545 if (plen) *plen = len;
550 char *get_line(int fd)
553 char *buf = get_rawline(fd, &len, '\n');
555 if (buf && buf[--len]=='\n') buf[len]=0;
560 int wfchmodat(int fd, char *name, mode_t mode)
562 int rc = fchmodat(fd, name, mode, 0);
565 perror_msg("chmod '%s' to %04o", name, mode);
571 static char *tempfile2zap;
572 static void tempfile_handler(int i)
574 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
578 // Open a temporary file to copy an existing file into.
579 int copy_tempfile(int fdin, char *name, char **tempname)
584 *tempname = xmprintf("%s%s", name, "XXXXXX");
585 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
586 if (!tempfile2zap) sigatexit(tempfile_handler);
587 tempfile2zap = *tempname;
589 // Set permissions of output file
591 fstat(fdin, &statbuf);
592 fchmod(fd, statbuf.st_mode);
597 // Abort the copy and delete the temporary file.
598 void delete_tempfile(int fdin, int fdout, char **tempname)
602 if (*tempname) unlink(*tempname);
603 tempfile2zap = (char *)1;
608 // Copy the rest of the data and replace the original with the copy.
609 void replace_tempfile(int fdin, int fdout, char **tempname)
611 char *temp = xstrdup(*tempname);
613 temp[strlen(temp)-6]=0;
615 xsendfile(fdin, fdout);
619 rename(*tempname, temp);
620 tempfile2zap = (char *)1;
626 // Create a 256 entry CRC32 lookup table.
628 void crc_init(unsigned int *crc_table, int little_endian)
632 // Init the CRC32 table (big endian)
633 for (i=0; i<256; i++) {
634 unsigned int j, c = little_endian ? i : i<<24;
636 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
637 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
644 void base64_init(char *p)
648 for (i = 'A'; i != ':'; i++) {
649 if (i == 'Z'+1) i = 'a';
650 if (i == 'z'+1) i = '0';
661 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
663 while (fread(&buf, 1, 1, stdin)) {
666 // The letter changes the value, the newline (or space) returns it.
667 if (isspace(buf)) break;
668 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
679 // Signals required by POSIX 2008:
680 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
682 #define SIGNIFY(x) {SIG##x, #x}
684 static struct signame signames[] = {
685 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
686 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
687 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
688 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
689 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
691 // Start of non-terminal signals
693 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
694 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
697 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
698 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
700 // Handler that sets toys.signal, and writes to toys.signalfd if set
701 void generic_signal(int sig)
706 writeall(toys.signalfd, &c, 1);
711 // Install the same handler on every signal that defaults to killing the process
712 void sigatexit(void *handler)
715 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
718 // Convert name to signal number. If name == NULL print names.
719 int sig_to_num(char *pidstr)
726 i = estrtol(pidstr, &s, 10);
727 if (!errno && !*s) return i;
729 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
731 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
732 if (!pidstr) xputs(signames[i].name);
733 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
738 char *num_to_sig(int sig)
742 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
743 if (signames[i].num == sig) return signames[i].name;
747 // premute mode bits based on posix mode strings.
748 mode_t string_to_mode(char *modestr, mode_t mode)
750 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
752 mode_t extrabits = mode & ~(07777);
756 mode = estrtol(str, &s, 8);
757 if (errno || *s || (mode & ~(07777))) goto barf;
759 return mode | extrabits;
762 // Gaze into the bin of permission...
764 int i, j, dowho, dohow, dowhat, amask;
766 dowho = dohow = dowhat = amask = 0;
768 // Find the who, how, and what stanzas, in that order
769 while (*str && (s = strchr(whos, *str))) {
770 dowho |= 1<<(s-whos);
773 // If who isn't specified, like "a" but honoring umask.
776 umask(amask=umask(0));
778 if (!*str || !(s = strchr(hows, *str))) goto barf;
781 if (!dohow) goto barf;
782 while (*str && (s = strchr(whats, *str))) {
783 dowhat |= 1<<(s-whats);
787 // Convert X to x for directory or if already executable somewhere
788 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
790 // Copy mode from another category?
791 if (!dowhat && *str && (s = strchr(whys, *str))) {
792 dowhat = (mode>>(3*(s-whys)))&7;
796 // Are we ready to do a thing yet?
797 if (*str && *(str++) != ',') goto barf;
799 // Ok, apply the bits to the mode.
800 for (i=0; i<4; i++) {
801 for (j=0; j<3; j++) {
803 int where = 1<<((3*i)+j);
805 if (amask & where) continue;
807 // Figure out new value at this location
811 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
812 } else if (dowhat & 16) bit++;
814 if (!(dowho&(8|(1<<i)))) continue;
815 if (dowhat&(1<<j)) bit++;
818 // When selection active, modify bit
820 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
821 if (bit && dohow != '-') mode |= where;
828 return mode|extrabits;
830 error_exit("bad mode '%s'", modestr);
833 // Format access mode into a drwxrwxrwx string
834 void mode_to_string(mode_t mode, char *buf)
840 for (i=0; i<9; i++) {
843 if (!c && (mode & (1<<((d=i/3)+9)))) {
845 if (!bit) c &= ~0x20;
846 } else c = bit ? "xwr"[c] : '-';
850 if (S_ISDIR(mode)) c = 'd';
851 else if (S_ISBLK(mode)) c = 'b';
852 else if (S_ISCHR(mode)) c = 'c';
853 else if (S_ISLNK(mode)) c = 'l';
854 else if (S_ISFIFO(mode)) c = 'p';
855 else if (S_ISSOCK(mode)) c = 's';
860 char *basename_r(char *name)
862 char *s = strrchr(name, '/');
868 // Execute a callback for each PID that matches a process name from a list.
869 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
872 struct dirent *entry;
874 if (!(dp = opendir("/proc"))) perror_exit("opendir");
876 while ((entry = readdir(dp))) {
878 char *cmd, **curname;
880 if (!(u = atoi(entry->d_name))) continue;
881 sprintf(libbuf, "/proc/%u/cmdline", u);
882 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
884 for (curname = names; *curname; curname++)
885 if (**curname == '/' ? !strcmp(cmd, *curname)
886 : !strcmp(basename_r(cmd), basename_r(*curname)))
887 if (callback(u, *curname)) break;
893 // display first few digits of number with power of two units
894 int human_readable(char *buf, unsigned long long num, int style)
896 unsigned long long snap = 0;
897 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
899 // Divide rounding up until we have 3 or fewer digits. Since the part we
900 // print is decimal, the test is 999 even when we divide by 1024.
901 // We can't run out of units because 2<<64 is 18 exabytes.
902 // test 5675 is 5.5k not 5.6k.
903 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
904 len = sprintf(buf, "%llu", num);
905 if (unit && len == 1) {
906 // Redo rounding for 1.2M case, this works with and without HR_1000.
909 snap = ((snap*100)+50)/divisor;
911 len = sprintf(buf, "%llu.%llu", num, snap);
913 if (style & HR_SPACE) buf[len++] = ' ';
915 unit = " kMGTPE"[unit];
917 if (!(style&HR_1000)) unit = toupper(unit);
919 } else if (style & HR_B) buf[len++] = 'B';
925 // The qsort man page says you can use alphasort, the posix committee
926 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
927 // So just do our own. (The const is entirely to humor the stupid compiler.)
928 int qstrcmp(const void *a, const void *b)
930 return strcmp(*(char **)a, *(char **)b);
933 int xpoll(struct pollfd *fds, int nfds, int timeout)
938 if (0>(i = poll(fds, nfds, timeout))) {
939 if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
940 else if (timeout>0) timeout--;