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));
17 if (!toys.exitval) toys.exitval++;
20 void error_msg(char *msg, ...)
25 verror_msg(msg, 0, va);
29 void perror_msg(char *msg, ...)
34 verror_msg(msg, errno, va);
38 // Die with an error message.
39 void error_exit(char *msg, ...)
43 if (CFG_TOYBOX_HELP && toys.exithelp) show_help();
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 // Keep reading until full or EOF
65 ssize_t readall(int fd, void *buf, size_t len)
70 int i = read(fd, (char *)buf+count, len-count);
79 // Keep writing until done or EOF
80 ssize_t writeall(int fd, void *buf, size_t len)
84 int i = write(fd, count+(char *)buf, len-count);
92 // skip this many bytes of input. Return 0 for success, >0 means this much
93 // left after input skipped.
94 off_t lskip(int fd, off_t offset)
96 off_t cur = lseek(fd, 0, SEEK_CUR);
99 off_t end = lseek(fd, 0, SEEK_END) - cur;
101 if (end > 0 && end < offset) return offset - end;
103 if (end == lseek(fd, end, SEEK_SET)) return 0;
104 perror_exit("lseek");
108 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
110 or = readall(fd, libbuf, try);
111 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
119 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
120 // 2=make path (already exists is ok)
122 // returns 0 = path ok, 1 = error
123 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
128 // mkdir -p one/two/three is not an error if the path already exists,
129 // but is if "three" is a file. The others we dereference and catch
130 // not-a-directory along the way, but the last one we must explicitly
131 // test for. Might as well do it up front.
133 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
138 for (s = dir; ;s++) {
140 mode_t mode = (0777&~toys.old_umask)|0300;
142 // find next '/', but don't try to mkdir "" at start of absolute path
143 if (*s == '/' && (flags&2) && s != dir) {
146 } else if (*s) continue;
148 // Use the mode from the -m option only for the last directory.
150 if (flags&1) mode = lastmode;
154 if (mkdirat(atfd, dir, mode)) {
155 if (!(flags&2) || errno != EEXIST) return 1;
157 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
159 if (!(*s = save)) break;
165 // Split a path into linked list of components, tracking head and tail of list.
166 // Filters out // entries with no contents.
167 struct string_list **splitpath(char *path, struct string_list **list)
175 if (*path && *path != '/') continue;
178 *list = xmalloc(sizeof(struct string_list) + len + 1);
180 memcpy((*list)->str, new, len);
181 (*list)->str[len] = 0;
182 list = &(*list)->next;
190 // Find all file in a colon-separated path with access type "type" (generally
191 // X_OK or R_OK). Returns a list of absolute paths to each file found, in
194 struct string_list *find_in_path(char *path, char *filename)
196 struct string_list *rlist = NULL, **prlist=&rlist;
203 char *next = strchr(path, ':');
204 int len = next ? next-path : strlen(path);
205 struct string_list *rnext;
208 rnext = xmalloc(sizeof(void *) + strlen(filename)
209 + (len ? len : strlen(cwd)) + 2);
210 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
212 char *res = rnext->str;
214 memcpy(res, path, len);
217 strcpy(res, filename);
220 // Confirm it's not a directory.
221 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
224 prlist = &(rnext->next);
236 long estrtol(char *str, char **end, int base)
240 return strtol(str, end, base);
243 long xstrtol(char *str, char **end, int base)
245 long l = estrtol(str, end, base);
247 if (errno) perror_exit("%s", str);
252 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
253 // (zetta and yotta don't fit in 64 bits.)
254 long atolx(char *numstr)
256 char *c, *suffixes="cbkmgtpe", *end;
259 val = xstrtol(numstr, &c, 0);
261 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
262 int shift = end-suffixes-2;
263 if (shift >= 0) val *= 1024L<<(shift*10);
265 while (isspace(*c)) c++;
266 if (*c) error_exit("not integer: %s", numstr);
273 long atolx_range(char *numstr, long low, long high)
275 long val = atolx(numstr);
277 if (val < low) error_exit("%ld < %ld", val, low);
278 if (val > high) error_exit("%ld > %ld", val, high);
283 int stridx(char *haystack, char needle)
287 if (!needle) return -1;
288 off = strchr(haystack, needle);
294 char *strlower(char *s)
298 if (!CFG_TOYBOX_I18N) {
299 try = new = xstrdup(s);
300 for (; *s; s++) *(new++) = tolower(*s);
302 // I can't guarantee the string _won't_ expand during reencoding, so...?
303 try = new = xmalloc(strlen(s)*2+1);
307 int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
309 if (len < 1) *(new++) = *(s++);
312 // squash title case too
315 // if we had a valid utf8 sequence, convert it to lower case, and can't
316 // encode back to utf8, something is wrong with your libc. But just
317 // in case somebody finds an exploit...
318 len = wcrtomb(new, c, 0);
319 if (len < 1) error_exit("bad utf8 %x", (int)c);
331 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
332 int idx = stridx(from, c);
334 return (idx == -1) ? 0 : to[idx];
337 // If *a starts with b, advance *a past it and return 1, else return 0;
338 int strstart(char **a, char *b)
340 int len = strlen(b), i = !strncmp(*a, b, len);
347 // Return how long the file at fd is, if there's any way to determine it.
348 off_t fdlength(int fd)
351 off_t base = 0, range = 1, expand = 1, old;
353 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
355 // If the ioctl works for this, return it.
356 // TODO: is blocksize still always 512, or do we stat for it?
357 // unsigned int size;
358 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
360 // If not, do a binary search for the last location we can read. (Some
361 // block devices don't do BLKGETSIZE right.) This should probably have
362 // a CONFIG option...
364 // If not, do a binary search for the last location we can read.
366 old = lseek(fd, 0, SEEK_CUR);
369 off_t pos = base + range / 2;
371 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
372 off_t delta = (pos + 1) - base;
375 if (expand) range = (expand <<= 1) - base;
383 lseek(fd, old, SEEK_SET);
388 // Read contents of file as a single nul-terminated string.
389 // malloc new one if buf=len=0
390 char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
395 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
398 // proc files don't report a length, so try 1 page minimum.
399 if (len<4096) len = 4096;
401 if (!ibuf) buf = xmalloc(len+1);
404 len = readall(fd, buf, len-1);
407 if (ibuf != buf) free(buf);
414 char *readfile(char *name, char *ibuf, off_t len)
416 return readfileat(AT_FDCWD, name, ibuf, len);
419 // Sleep for this many thousandths of a second
420 void msleep(long miliseconds)
424 ts.tv_sec = miliseconds/1000;
425 ts.tv_nsec = (miliseconds%1000)*1000000;
429 // Inefficient, but deals with unaligned access
430 int64_t peek_le(void *ptr, unsigned size)
436 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
441 int64_t peek_be(void *ptr, unsigned size)
446 while (size--) ret = (ret<<8)|c[size];
451 int64_t peek(void *ptr, unsigned size)
453 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
456 void poke(void *ptr, uint64_t val, int size)
459 volatile uint64_t *p = (uint64_t *)ptr;
461 } else if (size & 4) {
462 volatile int *p = (int *)ptr;
464 } else if (size & 2) {
465 volatile short *p = (short *)ptr;
468 volatile char *p = (char *)ptr;
473 // Iterate through an array of files, opening each one and calling a function
474 // on that filehandle and name. The special filename "-" means stdin if
475 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
476 // function() on just stdin/stdout.
478 // Note: pass O_CLOEXEC to automatically close filehandles when function()
479 // returns, otherwise filehandles must be closed by function()
480 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
481 void (*function)(int fd, char *name))
485 // If no arguments, read from stdin.
486 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
488 // Filename "-" means read from stdin.
489 // Inability to open a file prints a warning, but doesn't exit.
491 if (!strcmp(*argv, "-")) fd=0;
492 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
493 perror_msg("%s", *argv);
498 if (flags & O_CLOEXEC) close(fd);
502 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
503 void loopfiles(char **argv, void (*function)(int fd, char *name))
505 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
510 char *get_rawline(int fd, long *plen, char end)
516 if (1>read(fd, &c, 1)) break;
517 if (!(len & 63)) buf=xrealloc(buf, len+65);
518 if ((buf[len++]=c) == end) break;
521 if (plen) *plen = len;
526 char *get_line(int fd)
529 char *buf = get_rawline(fd, &len, '\n');
531 if (buf && buf[--len]=='\n') buf[len]=0;
536 int wfchmodat(int fd, char *name, mode_t mode)
538 int rc = fchmodat(fd, name, mode, 0);
541 perror_msg("chmod '%s' to %04o", name, mode);
547 static char *tempfile2zap;
548 static void tempfile_handler(int i)
550 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
554 // Open a temporary file to copy an existing file into.
555 int copy_tempfile(int fdin, char *name, char **tempname)
560 *tempname = xmprintf("%s%s", name, "XXXXXX");
561 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
562 if (!tempfile2zap) sigatexit(tempfile_handler);
563 tempfile2zap = *tempname;
565 // Set permissions of output file
567 fstat(fdin, &statbuf);
568 fchmod(fd, statbuf.st_mode);
573 // Abort the copy and delete the temporary file.
574 void delete_tempfile(int fdin, int fdout, char **tempname)
578 if (*tempname) unlink(*tempname);
579 tempfile2zap = (char *)1;
584 // Copy the rest of the data and replace the original with the copy.
585 void replace_tempfile(int fdin, int fdout, char **tempname)
587 char *temp = xstrdup(*tempname);
589 temp[strlen(temp)-6]=0;
591 xsendfile(fdin, fdout);
595 rename(*tempname, temp);
596 tempfile2zap = (char *)1;
602 // Create a 256 entry CRC32 lookup table.
604 void crc_init(unsigned int *crc_table, int little_endian)
608 // Init the CRC32 table (big endian)
609 for (i=0; i<256; i++) {
610 unsigned int j, c = little_endian ? i : i<<24;
612 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
613 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
620 void base64_init(char *p)
624 for (i = 'A'; i != ':'; i++) {
625 if (i == 'Z'+1) i = 'a';
626 if (i == 'z'+1) i = '0';
633 int yesno(char *prompt, int def)
637 fprintf(stderr, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
639 while (fread(&buf, 1, 1, stdin)) {
642 // The letter changes the value, the newline (or space) returns it.
643 if (isspace(buf)) break;
644 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
655 // Signals required by POSIX 2008:
656 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
658 #define SIGNIFY(x) {SIG##x, #x}
660 static struct signame signames[] = {
661 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
662 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
663 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
664 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
665 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
667 // Start of non-terminal signals
669 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
670 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
673 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
674 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
676 // Handler that sets toys.signal, and writes to toys.signalfd if set
677 void generic_signal(int sig)
682 writeall(toys.signalfd, &c, 1);
687 // Install the same handler on every signal that defaults to killing the process
688 void sigatexit(void *handler)
691 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
694 // Convert name to signal number. If name == NULL print names.
695 int sig_to_num(char *pidstr)
702 i = estrtol(pidstr, &s, 10);
703 if (!errno && !*s) return i;
705 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
707 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
708 if (!pidstr) xputs(signames[i].name);
709 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
714 char *num_to_sig(int sig)
718 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
719 if (signames[i].num == sig) return signames[i].name;
723 // premute mode bits based on posix mode strings.
724 mode_t string_to_mode(char *modestr, mode_t mode)
726 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
728 mode_t extrabits = mode & ~(07777);
732 mode = estrtol(str, &s, 8);
733 if (errno || *s || (mode & ~(07777))) goto barf;
735 return mode | extrabits;
738 // Gaze into the bin of permission...
740 int i, j, dowho, dohow, dowhat, amask;
742 dowho = dohow = dowhat = amask = 0;
744 // Find the who, how, and what stanzas, in that order
745 while (*str && (s = strchr(whos, *str))) {
746 dowho |= 1<<(s-whos);
749 // If who isn't specified, like "a" but honoring umask.
752 umask(amask=umask(0));
754 if (!*str || !(s = strchr(hows, *str))) goto barf;
757 if (!dohow) goto barf;
758 while (*str && (s = strchr(whats, *str))) {
759 dowhat |= 1<<(s-whats);
763 // Convert X to x for directory or if already executable somewhere
764 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
766 // Copy mode from another category?
767 if (!dowhat && *str && (s = strchr(whys, *str))) {
768 dowhat = (mode>>(3*(s-whys)))&7;
772 // Are we ready to do a thing yet?
773 if (*str && *(str++) != ',') goto barf;
775 // Ok, apply the bits to the mode.
776 for (i=0; i<4; i++) {
777 for (j=0; j<3; j++) {
779 int where = 1<<((3*i)+j);
781 if (amask & where) continue;
783 // Figure out new value at this location
787 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
788 } else if (dowhat & 16) bit++;
790 if (!(dowho&(8|(1<<i)))) continue;
791 if (dowhat&(1<<j)) bit++;
794 // When selection active, modify bit
796 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
797 if (bit && dohow != '-') mode |= where;
804 return mode|extrabits;
806 error_exit("bad mode '%s'", modestr);
809 // Format access mode into a drwxrwxrwx string
810 void mode_to_string(mode_t mode, char *buf)
816 for (i=0; i<9; i++) {
819 if (!c && (mode & (1<<((d=i/3)+9)))) {
821 if (!bit) c &= ~0x20;
822 } else c = bit ? "xwr"[c] : '-';
826 if (S_ISDIR(mode)) c = 'd';
827 else if (S_ISBLK(mode)) c = 'b';
828 else if (S_ISCHR(mode)) c = 'c';
829 else if (S_ISLNK(mode)) c = 'l';
830 else if (S_ISFIFO(mode)) c = 'p';
831 else if (S_ISSOCK(mode)) c = 's';
836 char *basename_r(char *name)
838 char *s = strrchr(name, '/');
844 // Execute a callback for each PID that matches a process name from a list.
845 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
848 struct dirent *entry;
850 if (!(dp = opendir("/proc"))) perror_exit("opendir");
852 while ((entry = readdir(dp))) {
854 char *cmd, **curname;
856 if (!(u = atoi(entry->d_name))) continue;
857 sprintf(libbuf, "/proc/%u/cmdline", u);
858 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
860 for (curname = names; *curname; curname++)
861 if (**curname == '/' ? !strcmp(cmd, *curname)
862 : !strcmp(basename_r(cmd), basename_r(*curname)))
863 if (callback(u, *curname)) break;
869 // display first few digits of number with power of two units, except we're
870 // actually just counting decimal digits and showing mil/bil/trillions.
871 int human_readable(char *buf, unsigned long long num, int style)
875 len = sprintf(buf, "%lld", num)-1;
879 if (len && end == 1) {
884 if (style & HR_SPACE) buf[end++] = ' ';
885 if (len) buf[end++] = " KMGTPE"[len];
886 if (style & HR_B) buf[end++] = 'B';
892 // The qsort man page says you can use alphasort, the posix committee
893 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
894 // So just do our own. (The const is entirely to humor the stupid compiler.)
895 int qstrcmp(const void *a, const void *b)
897 return strcmp(*(char **)a, *(char **)b);
900 int xpoll(struct pollfd *fds, int nfds, int timeout)
905 if (0>(i = poll(fds, nfds, timeout))) {
906 if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
907 else if (timeout>0) timeout--;