1 /* vi: set sw=4 ts=4 :*/
2 /* lib.c - reusable stuff.
4 * Functions with the x prefix are wrappers for library functions. They either
5 * succeed or kill the program with an error message, but never return failure.
6 * They usually have the same arguments and return value as the function they
9 * Copyright 2006 Rob Landley <rob@landley.net>
14 // Strcpy with size checking: exit if there's not enough space for the string.
15 void xstrcpy(char *dest, char *src, size_t size)
17 if (strlen(src)+1 > size) error_exit("xstrcpy");
21 void verror_msg(char *msg, int err, va_list va)
25 fprintf(stderr, "%s: ", toys.which->name);
26 if (msg) vfprintf(stderr, msg, va);
28 if (err) fprintf(stderr, s, strerror(err));
32 void error_msg(char *msg, ...)
37 verror_msg(msg, 0, va);
41 void perror_msg(char *msg, ...)
46 verror_msg(msg, errno, va);
50 // Die with an error message.
51 void error_exit(char *msg, ...)
55 if (CFG_HELP && toys.exithelp) {
56 *toys.optargs=*toys.argv;
57 USE_HELP(help_main();) // dear gcc: shut up.
62 verror_msg(msg, 0, va);
65 exit(!toys.exitval ? 1 : toys.exitval);
69 // Die with an error message and strerror(errno)
70 void perror_exit(char *msg, ...)
75 verror_msg(msg, errno, va);
78 exit(!toys.exitval ? 1 : toys.exitval);
81 // Die unless we can allocate memory.
82 void *xmalloc(size_t size)
84 void *ret = malloc(size);
85 if (!ret) error_exit("xmalloc");
90 // Die unless we can allocate prezeroed memory.
91 void *xzalloc(size_t size)
93 void *ret = xmalloc(size);
98 // Die unless we can change the size of an existing allocation, possibly
99 // moving it. (Notice different arguments from libc function.)
100 void *xrealloc(void *ptr, size_t size)
102 ptr = realloc(ptr, size);
103 if (!ptr) error_exit("xrealloc");
108 // Die unless we can allocate a copy of this many bytes of string.
109 char *xstrndup(char *s, size_t n)
111 char *ret = xmalloc(++n);
118 // Die unless we can allocate a copy of this string.
119 char *xstrdup(char *s)
121 return xstrndup(s, strlen(s));
124 // Die unless we can allocate enough space to sprintf() into.
125 char *xmsprintf(char *format, ...)
131 va_start(va, format);
135 len = vsnprintf(0, 0, format, va);
139 // Allocate and do the sprintf()
141 vsnprintf(ret, len, format, va2);
147 void xprintf(char *format, ...)
150 va_start(va, format);
153 if (ferror(stdout)) perror_exit("write");
158 if (EOF == puts(s)) perror_exit("write");
163 if (EOF == fputc(c, stdout) || fflush(stdout)) perror_exit("write");
168 if (fflush(stdout)) perror_exit("write");;
171 // Die unless we can exec argv[] (or run builtin command). Note that anything
172 // with a path isn't a builtin, so /bin/sh won't match the builtin sh.
173 void xexec(char **argv)
176 execvp(argv[0], argv);
178 perror_exit("exec %s", argv[0]);
181 void xaccess(char *path, int flags)
183 if (access(path, flags)) perror_exit("Can't access '%s'", path);
186 // Die unless we can delete a file. (File must exist to be deleted.)
187 void xunlink(char *path)
189 if (unlink(path)) perror_exit("unlink '%s'", path);
192 // Die unless we can open/create a file, returning file descriptor.
193 int xcreate(char *path, int flags, int mode)
195 int fd = open(path, flags, mode);
196 if (fd == -1) perror_exit("%s", path);
200 // Die unless we can open a file, returning file descriptor.
201 int xopen(char *path, int flags)
203 return xcreate(path, flags, 0);
208 if (close(fd)) perror_exit("xclose");
215 if (fd == -1) perror_exit("xdup");
220 // Die unless we can open/create a file, returning FILE *.
221 FILE *xfopen(char *path, char *mode)
223 FILE *f = fopen(path, mode);
224 if (!f) perror_exit("No file %s", path);
228 // Keep reading until full or EOF
229 ssize_t readall(int fd, void *buf, size_t len)
234 int i = read(fd, buf+count, len-count);
243 // Keep writing until done or EOF
244 ssize_t writeall(int fd, void *buf, size_t len)
248 int i = write(fd, buf+count, len-count);
256 // Die if there's an error other than EOF.
257 size_t xread(int fd, void *buf, size_t len)
259 ssize_t ret = read(fd, buf, len);
260 if (ret < 0) perror_exit("xread");
265 void xreadall(int fd, void *buf, size_t len)
267 if (len != readall(fd, buf, len)) perror_exit("xreadall");
270 // There's no xwriteall(), just xwrite(). When we read, there may or may not
271 // be more data waiting. When we write, there is data and it had better go
274 void xwrite(int fd, void *buf, size_t len)
276 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
279 // Die if lseek fails, probably due to being called on a pipe.
281 off_t xlseek(int fd, off_t offset, int whence)
283 offset = lseek(fd, offset, whence);
284 if (offset<0) perror_exit("lseek");
289 off_t lskip(int fd, off_t offset)
291 off_t and = lseek(fd, offset, SEEK_CUR);
293 if (and != -1 && offset >= lseek(fd, offset, SEEK_END)
294 && offset+and == lseek(fd, offset+and, SEEK_SET)) return 0;
298 int try = offset>sizeof(buf) ? sizeof(buf) : offset, or;
300 or = readall(fd, buf, try);
301 if (or < 0) perror_msg("lskip to %lld", (long long)offset);
312 char *buf = getcwd(NULL, 0);
313 if (!buf) perror_exit("xgetcwd");
318 void xstat(char *path, struct stat *st)
320 if(stat(path, st)) perror_exit("Can't stat %s", path);
323 // Cannonicalizes path by removing ".", "..", and "//" elements. This is not
324 // the same as realpath(), where "dir/.." could wind up somewhere else by
325 // following symlinks.
326 char *xabspath(char *path)
330 // If this isn't an absolute path, make it one with cwd.
333 path = xmsprintf("%s/%s", cwd, path);
335 } else path = xstrdup(path);
337 // Loop through path elements
341 // Continue any current path component.
347 // Skip duplicate slashes.
348 while (*from=='/') from++;
350 // Start of a new filename. Handle . and ..
353 if (from[1]=='/') from += 2;
354 else if (!from[1]) from++;
356 else if (from[1]=='.') {
357 if (from[2]=='/') from +=3;
358 else if(!from[2]) from+=2;
360 while (to>path && *(--to)!='/');
363 // Add directory separator slash.
371 // Resolve all symlinks, returning malloc() memory.
372 char *xrealpath(char *path)
374 char *new = realpath(path, NULL);
375 if (!new) perror_exit("realpath '%s'", path);
379 void xchdir(char *path)
381 if (chdir(path)) error_exit("chdir '%s'", path);
384 // Ensure entire path exists.
385 // If mode != -1 set permissions on newly created dirs.
386 // Requires that path string be writable (for temporary null terminators).
387 void xmkpath(char *path, int mode)
394 for (p = path; ; p++) {
395 if (!*p || *p == '/') {
398 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
401 rc = mkdir(path, mode);
403 } else rc = mkdir(path, 0777);
406 if(rc) perror_exit("mkpath '%s'", path);
412 // setuid() can fail (for example, too many processes belonging to that user),
413 // which opens a security hole if the process continues as the original user.
415 void xsetuid(uid_t uid)
417 if (setuid(uid)) perror_exit("xsetuid");
421 // Find all file in a colon-separated path with access type "type" (generally
422 // X_OK or R_OK). Returns a list of absolute paths to each file found, in
425 struct string_list *find_in_path(char *path, char *filename)
427 struct string_list *rlist = NULL, **prlist=&rlist;
428 char *cwd = xgetcwd();
431 char *next = path ? strchr(path, ':') : NULL;
432 int len = next ? next-path : strlen(path);
433 struct string_list *rnext;
436 rnext = xmalloc(sizeof(void *) + strlen(filename)
437 + (len ? len : strlen(cwd)) + 2);
438 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
440 char *res = rnext->str;
441 strncpy(res, path, len);
444 strcpy(res, filename);
447 // Confirm it's not a directory.
448 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
451 prlist = &(rnext->next);
463 // Convert unsigned int to ascii, writing into supplied buffer. A truncated
464 // result contains the first few digits of the result ala strncpy, and is
465 // always null terminated (unless buflen is 0).
466 void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
471 for (i=1000000000; i; i/=10) {
474 if ((res || out || i == 1) && --buflen>0) {
484 // Convert signed integer to ascii, using utoa_to_buf()
485 void itoa_to_buf(int n, char *buf, unsigned buflen)
492 utoa_to_buf((unsigned)n, buf, buflen);
495 // This static buffer is used by both utoa() and itoa(), calling either one a
496 // second time will overwrite the previous results.
498 // The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
499 // Note that int is always 32 bits on any remotely unix-like system, see
500 // http://www.unix.org/whitepapers/64bit.html for details.
502 static char itoa_buf[12];
504 // Convert unsigned integer to ascii, returning a static buffer.
505 char *utoa(unsigned n)
507 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
514 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
519 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
520 // (zetta and yotta don't fit in 64 bits.)
521 long atolx(char *numstr)
523 char *c, *suffixes="bkmgtpe", *end;
524 long val = strtol(numstr, &c, 0);
527 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
528 int shift = end-suffixes;
529 if (shift--) val *= 1024L<<(shift*10);
531 while (isspace(*c)) c++;
532 if (*c) error_exit("not integer: %s", numstr);
549 int stridx(char *haystack, char needle)
553 if (!needle) return -1;
554 off = strchr(haystack, needle);
560 // Return how long the file at fd is, if there's any way to determine it.
561 off_t fdlength(int fd)
563 off_t bottom = 0, top = 0, pos, old;
566 // If the ioctl works for this, return it.
568 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
570 // If not, do a binary search for the last location we can read. (Some
571 // block devices don't do BLKGETSIZE right.) This should probably have
572 // a CONFIG option...
574 old = lseek(fd, 0, SEEK_CUR);
578 pos = bottom + (top - bottom) / 2;
580 // If we can read from the current location, it's bigger.
582 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
583 if (bottom == top) bottom = top = (top+1) * 2;
586 // If we can't, it's smaller.
594 } while (bottom + 1 != top);
596 lseek(fd, old, SEEK_SET);
601 // This can return null (meaning file not found). It just won't return null
602 // for memory allocation reasons.
603 char *xreadlink(char *name)
608 // Grow by 64 byte chunks until it's big enough.
611 buf = xrealloc(buf, size);
612 len = readlink(name, buf, size);
626 This might be of use or might not. Unknown yet...
628 // Read contents of file as a single freshly allocated nul-terminated string.
629 char *readfile(char *name)
635 fd = open(name, O_RDONLY);
636 if (fd == -1) return 0;
638 buf = xmalloc(len+1);
639 buf[readall(fd, buf, len)] = 0;
644 char *xreadfile(char *name)
646 char *buf = readfile(name);
647 if (!buf) perror_exit("xreadfile %s", name);
653 // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
654 // exists and is this executable.
655 void xpidfile(char *name)
657 char pidfile[256], spid[32];
661 sprintf(pidfile, "/var/run/%s.pid", name);
662 // Try three times to open the sucker.
663 for (i=0; i<3; i++) {
664 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
667 // If it already existed, read it. Loop for race condition.
668 fd = open(pidfile, O_RDONLY);
669 if (fd == -1) continue;
671 // Is the old program still there?
672 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
675 if (fd < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
677 // An else with more sanity checking might be nice here.
680 if (i == 3) error_exit("xpidfile %s", name);
682 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
686 // Iterate through an array of files, opening each one and calling a function
687 // on that filehandle and name. The special filename "-" means stdin if
688 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
689 // function() on just stdin/stdout.
691 // Note: read only filehandles are automatically closed when function()
692 // returns, but writeable filehandles must be close by function()
693 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
694 void (*function)(int fd, char *name))
698 // If no arguments, read from stdin.
699 if (!*argv) function(flags ? 1 : 0, "-");
701 // Filename "-" means read from stdin.
702 // Inability to open a file prints a warning, but doesn't exit.
704 if (!strcmp(*argv,"-")) fd=0;
705 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
706 perror_msg("%s", *argv);
711 if (!flags) close(fd);
715 // Call loopfiles_rw with O_RDONLY and !failok (common case).
716 void loopfiles(char **argv, void (*function)(int fd, char *name))
718 loopfiles_rw(argv, O_RDONLY, 0, 0, function);
723 char *get_rawline(int fd, long *plen, char end)
729 if (1>read(fd, &c, 1)) break;
730 if (!(len & 63)) buf=xrealloc(buf, len+65);
731 if ((buf[len++]=c) == end) break;
734 if (plen) *plen = len;
739 char *get_line(int fd)
742 char *buf = get_rawline(fd, &len, '\n');
744 if (buf && buf[--len]=='\n') buf[len]=0;
749 // Copy the rest of in to out and close both files.
751 void xsendfile(int in, int out)
758 len = xread(in, buf, 4096);
760 xwrite(out, buf, len);
764 int wfchmodat(int fd, char *name, mode_t mode)
766 int rc = fchmodat(fd, name, mode, 0);
769 perror_msg("chmod '%s' to %04o", name, mode);
775 // Open a temporary file to copy an existing file into.
776 int copy_tempfile(int fdin, char *name, char **tempname)
781 *tempname = xstrndup(name, strlen(name)+6);
782 strcat(*tempname,"XXXXXX");
783 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
785 // Set permissions of output file
787 fstat(fdin, &statbuf);
788 fchmod(fd, statbuf.st_mode);
793 // Abort the copy and delete the temporary file.
794 void delete_tempfile(int fdin, int fdout, char **tempname)
803 // Copy the rest of the data and replace the original with the copy.
804 void replace_tempfile(int fdin, int fdout, char **tempname)
806 char *temp = xstrdup(*tempname);
808 temp[strlen(temp)-6]=0;
810 xsendfile(fdin, fdout);
814 rename(*tempname, temp);
820 // Create a 256 entry CRC32 lookup table.
822 void crc_init(unsigned int *crc_table, int little_endian)
826 // Init the CRC32 table (big endian)
827 for (i=0; i<256; i++) {
828 unsigned int j, c = little_endian ? i : i<<24;
830 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
831 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
836 // Quick and dirty query size of terminal, doesn't do ANSI probe fallback.
837 // set *x=0 and *y=0 before calling to detect failure to set either, or
838 // x=80 y=25 to provide defaults
840 void terminal_size(unsigned *x, unsigned *y)
845 //memset(&ws, 0, sizeof(ws));
846 for (i=0; i<3; i++) {
847 if (ioctl(i, TIOCGWINSZ, &ws)) continue;
848 if (x) *x = ws.ws_col;
849 if (y) *y = ws.ws_row;
852 char *s = getenv("COLUMNS");
858 char *s = getenv("ROWS");
865 // This should use a raw tty, fixit later.
866 int yesno(char *prompt, int def)
868 FILE *fps[] = {stdin, stdout, stderr};
872 for (i=0; i<3; i++) if (isatty(i)) break;
873 if (i == 3) return 1;
875 fprintf(fps[i], "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
877 while (fread(&buf, 1, 1, fps[i])) {
878 if (tolower(buf) == 'y') def = 1;
879 if (tolower(buf) == 'n') def = 0;
880 else if (!isspace(buf)) continue;
888 // Execute a callback for each PID that matches a process name from a list.
889 void for_each_pid_with_name_in(char **names, void (*callback)(pid_t pid))
892 struct dirent *entry;
893 char cmd[sizeof(toybuf)], path[64];
896 if (!(dp = opendir("/proc"))) perror_exit("opendir");
898 while ((entry = readdir(dp))) {
901 if (!isdigit(*entry->d_name)) continue;
903 if (sizeof(path) <= snprintf(path, sizeof(path), "/proc/%s/cmdline",
904 entry->d_name)) continue;
906 if (-1 == (fd=open(path, O_RDONLY))) continue;
907 n = read(fd, cmd, sizeof(cmd));
911 for (curname = names; *curname; curname++)
912 if (!strcmp(basename(cmd), *curname))
913 callback(atol(entry->d_name));
924 // Signals required by POSIX 2008:
925 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
927 #define SIGNIFY(x) {SIG##x, #x}
929 static struct signame signames[] = {
930 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS), SIGNIFY(CHLD), SIGNIFY(CONT),
931 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
932 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(STOP), SIGNIFY(TERM),
933 SIGNIFY(TSTP), SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(USR1), SIGNIFY(USR2),
934 SIGNIFY(SYS), SIGNIFY(TRAP), SIGNIFY(URG), SIGNIFY(VTALRM), SIGNIFY(XCPU),
938 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
939 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
941 // Convert name to signal number. If name == NULL print names.
942 int sig_to_num(char *pidstr)
948 i = strtol(pidstr, &s, 10);
951 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
953 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
954 if (!pidstr) xputs(signames[i].name);
955 else if (!strcasecmp(pidstr, signames[i].name))
956 return signames[i].num;
961 char *num_to_sig(int sig)
965 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
966 if (signames[i].num == sig) return signames[i].name;
971 mode_t string_to_mode(char *modestr, mode_t mode)
973 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu";
974 char *s, *str = modestr;
978 mode = strtol(str, &s, 8);
979 if (*s || (mode & ~(07777))) goto barf;
984 // Gaze into the bin of permission...
986 int i, j, dowho, dohow, dowhat, amask;
988 dowho = dohow = dowhat = amask = 0;
990 // Find the who, how, and what stanzas, in that order
991 while (*str && (s = strchr(whos, *str))) {
992 dowho |= 1<<(s-whos);
995 // If who isn't specified, like "a" but honoring umask.
998 umask(amask=umask(0));
1000 if (!*str || !(s = strchr(hows, *str))) goto barf;
1003 if (!dohow) goto barf;
1004 while (*str && (s = strchr(whats, *str))) {
1005 dowhat |= 1<<(s-whats);
1009 // Convert X to x for directory or if already executable somewhere
1010 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
1012 // Copy mode from another category?
1013 if (!dowhat && *str && (s = strchr(whys, *str))) {
1014 dowhat = (mode>>(3*(s-whys)))&7;
1018 // Are we ready to do a thing yet?
1019 if (*str && *(str++) != ',') goto barf;
1021 // Ok, apply the bits to the mode.
1022 for (i=0; i<4; i++) {
1023 for (j=0; j<3; j++) {
1025 int where = 1<<((3*i)+j);
1027 if (amask & where) continue;
1029 // Figure out new value at this location
1033 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
1034 } else if (dowhat & 16) bit++;
1036 if (!(dowho&(8|(1<<i)))) continue;
1037 if (dowhat&(1<<j)) bit++;
1040 // When selection active, modify bit
1042 if (dohow == '=' || (bit && dohow == '-'))
1044 if (bit && dohow != '-') mode |= where;
1052 error_exit("bad mode '%s'", modestr);