1 /* lib.c - various reusable stuff.
2 *
3 * Copyright 2006 Rob Landley <rob@landley.net>
4 */
5
6 #include "toys.h"
7
verror_msg(char * msg,int err,va_list va)8 void verror_msg(char *msg, int err, va_list va)
9 {
10 char *s = ": %s";
11
12 fprintf(stderr, "%s: ", toys.which->name);
13 if (msg) vfprintf(stderr, msg, va);
14 else s+=2;
15 if (err) fprintf(stderr, s, strerror(err));
16 putc('\n', stderr);
17 if (!toys.exitval) toys.exitval++;
18 }
19
error_msg(char * msg,...)20 void error_msg(char *msg, ...)
21 {
22 va_list va;
23
24 va_start(va, msg);
25 verror_msg(msg, 0, va);
26 va_end(va);
27 }
28
perror_msg(char * msg,...)29 void perror_msg(char *msg, ...)
30 {
31 va_list va;
32
33 va_start(va, msg);
34 verror_msg(msg, errno, va);
35 va_end(va);
36 }
37
38 // Die with an error message.
error_exit(char * msg,...)39 void error_exit(char *msg, ...)
40 {
41 va_list va;
42
43 if (CFG_TOYBOX_HELP && toys.exithelp) show_help();
44
45 va_start(va, msg);
46 verror_msg(msg, 0, va);
47 va_end(va);
48
49 xexit();
50 }
51
52 // Die with an error message and strerror(errno)
perror_exit(char * msg,...)53 void perror_exit(char *msg, ...)
54 {
55 va_list va;
56
57 va_start(va, msg);
58 verror_msg(msg, errno, va);
59 va_end(va);
60
61 xexit();
62 }
63
64 // Keep reading until full or EOF
readall(int fd,void * buf,size_t len)65 ssize_t readall(int fd, void *buf, size_t len)
66 {
67 size_t count = 0;
68
69 while (count<len) {
70 int i = read(fd, (char *)buf+count, len-count);
71 if (!i) break;
72 if (i<0) return i;
73 count += i;
74 }
75
76 return count;
77 }
78
79 // Keep writing until done or EOF
writeall(int fd,void * buf,size_t len)80 ssize_t writeall(int fd, void *buf, size_t len)
81 {
82 size_t count = 0;
83 while (count<len) {
84 int i = write(fd, count+(char *)buf, len-count);
85 if (i<1) return i;
86 count += i;
87 }
88
89 return count;
90 }
91
92 // skip this many bytes of input. Return 0 for success, >0 means this much
93 // left after input skipped.
lskip(int fd,off_t offset)94 off_t lskip(int fd, off_t offset)
95 {
96 off_t cur = lseek(fd, 0, SEEK_CUR);
97
98 if (cur != -1) {
99 off_t end = lseek(fd, 0, SEEK_END) - cur;
100
101 if (end > 0 && end < offset) return offset - end;
102 end = offset+cur;
103 if (end == lseek(fd, end, SEEK_SET)) return 0;
104 perror_exit("lseek");
105 }
106
107 while (offset>0) {
108 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
109
110 or = readall(fd, libbuf, try);
111 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
112 else offset -= or;
113 if (or < try) break;
114 }
115
116 return offset;
117 }
118
119 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
120 // 2=make path (already exists is ok)
121 // 4=verbose
122 // returns 0 = path ok, 1 = error
mkpathat(int atfd,char * dir,mode_t lastmode,int flags)123 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
124 {
125 struct stat buf;
126 char *s;
127
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.
132
133 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
134 errno = EEXIST;
135 return 1;
136 }
137
138 for (s = dir; ;s++) {
139 char save = 0;
140 mode_t mode = (0777&~toys.old_umask)|0300;
141
142 // find next '/', but don't try to mkdir "" at start of absolute path
143 if (*s == '/' && (flags&2) && s != dir) {
144 save = *s;
145 *s = 0;
146 } else if (*s) continue;
147
148 // Use the mode from the -m option only for the last directory.
149 if (!save) {
150 if (flags&1) mode = lastmode;
151 else break;
152 }
153
154 if (mkdirat(atfd, dir, mode)) {
155 if (!(flags&2) || errno != EEXIST) return 1;
156 } else if (flags&4)
157 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
158
159 if (!(*s = save)) break;
160 }
161
162 return 0;
163 }
164
165 // Split a path into linked list of components, tracking head and tail of list.
166 // Filters out // entries with no contents.
splitpath(char * path,struct string_list ** list)167 struct string_list **splitpath(char *path, struct string_list **list)
168 {
169 char *new = path;
170
171 *list = 0;
172 do {
173 int len;
174
175 if (*path && *path != '/') continue;
176 len = path-new;
177 if (len > 0) {
178 *list = xmalloc(sizeof(struct string_list) + len + 1);
179 (*list)->next = 0;
180 memcpy((*list)->str, new, len);
181 (*list)->str[len] = 0;
182 list = &(*list)->next;
183 }
184 new = path+1;
185 } while (*path++);
186
187 return list;
188 }
189
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
192 // order.
193
find_in_path(char * path,char * filename)194 struct string_list *find_in_path(char *path, char *filename)
195 {
196 struct string_list *rlist = NULL, **prlist=&rlist;
197 char *cwd;
198
199 if (!path) return 0;
200
201 cwd = xgetcwd();
202 for (;;) {
203 char *next = strchr(path, ':');
204 int len = next ? next-path : strlen(path);
205 struct string_list *rnext;
206 struct stat st;
207
208 rnext = xmalloc(sizeof(void *) + strlen(filename)
209 + (len ? len : strlen(cwd)) + 2);
210 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
211 else {
212 char *res = rnext->str;
213
214 memcpy(res, path, len);
215 res += len;
216 *(res++) = '/';
217 strcpy(res, filename);
218 }
219
220 // Confirm it's not a directory.
221 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
222 *prlist = rnext;
223 rnext->next = NULL;
224 prlist = &(rnext->next);
225 } else free(rnext);
226
227 if (!next) break;
228 path += len;
229 path++;
230 }
231 free(cwd);
232
233 return rlist;
234 }
235
estrtol(char * str,char ** end,int base)236 long estrtol(char *str, char **end, int base)
237 {
238 errno = 0;
239
240 return strtol(str, end, base);
241 }
242
xstrtol(char * str,char ** end,int base)243 long xstrtol(char *str, char **end, int base)
244 {
245 long l = estrtol(str, end, base);
246
247 if (errno) perror_exit("%s", str);
248
249 return l;
250 }
251
252 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
253 // (zetta and yotta don't fit in 64 bits.)
atolx(char * numstr)254 long atolx(char *numstr)
255 {
256 char *c, *suffixes="cbkmgtpe", *end;
257 long val;
258
259 val = xstrtol(numstr, &c, 0);
260 if (*c) {
261 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
262 int shift = end-suffixes-2;
263 if (shift >= 0) val *= 1024L<<(shift*10);
264 } else {
265 while (isspace(*c)) c++;
266 if (*c) error_exit("not integer: %s", numstr);
267 }
268 }
269
270 return val;
271 }
272
atolx_range(char * numstr,long low,long high)273 long atolx_range(char *numstr, long low, long high)
274 {
275 long val = atolx(numstr);
276
277 if (val < low) error_exit("%ld < %ld", val, low);
278 if (val > high) error_exit("%ld > %ld", val, high);
279
280 return val;
281 }
282
stridx(char * haystack,char needle)283 int stridx(char *haystack, char needle)
284 {
285 char *off;
286
287 if (!needle) return -1;
288 off = strchr(haystack, needle);
289 if (!off) return -1;
290
291 return off-haystack;
292 }
293
unescape(char c)294 int unescape(char c)
295 {
296 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
297 int idx = stridx(from, c);
298
299 return (idx == -1) ? 0 : to[idx];
300 }
301
302 // If *a starts with b, advance *a past it and return 1, else return 0;
strstart(char ** a,char * b)303 int strstart(char **a, char *b)
304 {
305 int len = strlen(b), i = !strncmp(*a, b, len);
306
307 if (i) *a += len;
308
309 return i;
310 }
311
312 // Return how long the file at fd is, if there's any way to determine it.
fdlength(int fd)313 off_t fdlength(int fd)
314 {
315 struct stat st;
316 off_t base = 0, range = 1, expand = 1, old;
317
318 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
319
320 // If the ioctl works for this, return it.
321 // TODO: is blocksize still always 512, or do we stat for it?
322 // unsigned int size;
323 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
324
325 // If not, do a binary search for the last location we can read. (Some
326 // block devices don't do BLKGETSIZE right.) This should probably have
327 // a CONFIG option...
328
329 // If not, do a binary search for the last location we can read.
330
331 old = lseek(fd, 0, SEEK_CUR);
332 do {
333 char temp;
334 off_t pos = base + range / 2;
335
336 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
337 off_t delta = (pos + 1) - base;
338
339 base += delta;
340 if (expand) range = (expand <<= 1) - base;
341 else range -= delta;
342 } else {
343 expand = 0;
344 range = pos - base;
345 }
346 } while (range > 0);
347
348 lseek(fd, old, SEEK_SET);
349
350 return base;
351 }
352
353 // Read contents of file as a single nul-terminated string.
354 // malloc new one if buf=len=0
readfileat(int dirfd,char * name,char * ibuf,off_t len)355 char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
356 {
357 int fd;
358 char *buf;
359
360 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
361 if (len<1) {
362 len = fdlength(fd);
363 // proc files don't report a length, so try 1 page minimum.
364 if (len<4096) len = 4096;
365 }
366 if (!ibuf) buf = xmalloc(len+1);
367 else buf = ibuf;
368
369 len = readall(fd, buf, len-1);
370 close(fd);
371 if (len<0) {
372 if (ibuf != buf) free(buf);
373 buf = 0;
374 } else buf[len] = 0;
375
376 return buf;
377 }
378
readfile(char * name,char * ibuf,off_t len)379 char *readfile(char *name, char *ibuf, off_t len)
380 {
381 return readfileat(AT_FDCWD, name, ibuf, len);
382 }
383
384 // Sleep for this many thousandths of a second
msleep(long miliseconds)385 void msleep(long miliseconds)
386 {
387 struct timespec ts;
388
389 ts.tv_sec = miliseconds/1000;
390 ts.tv_nsec = (miliseconds%1000)*1000000;
391 nanosleep(&ts, &ts);
392 }
393
394 // Inefficient, but deals with unaligned access
peek_le(void * ptr,unsigned size)395 int64_t peek_le(void *ptr, unsigned size)
396 {
397 int64_t ret = 0;
398 char *c = ptr;
399 int i;
400
401 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
402
403 return ret;
404 }
405
peek_be(void * ptr,unsigned size)406 int64_t peek_be(void *ptr, unsigned size)
407 {
408 int64_t ret = 0;
409 char *c = ptr;
410
411 while (size--) ret = (ret<<8)|c[size];
412
413 return ret;
414 }
415
peek(void * ptr,unsigned size)416 int64_t peek(void *ptr, unsigned size)
417 {
418 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
419 }
420
poke(void * ptr,uint64_t val,int size)421 void poke(void *ptr, uint64_t val, int size)
422 {
423 if (size & 8) {
424 volatile uint64_t *p = (uint64_t *)ptr;
425 *p = val;
426 } else if (size & 4) {
427 volatile int *p = (int *)ptr;
428 *p = val;
429 } else if (size & 2) {
430 volatile short *p = (short *)ptr;
431 *p = val;
432 } else {
433 volatile char *p = (char *)ptr;
434 *p = val;
435 }
436 }
437
438 // Iterate through an array of files, opening each one and calling a function
439 // on that filehandle and name. The special filename "-" means stdin if
440 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
441 // function() on just stdin/stdout.
442 //
443 // Note: pass O_CLOEXEC to automatically close filehandles when function()
444 // returns, otherwise filehandles must be closed by function()
loopfiles_rw(char ** argv,int flags,int permissions,int failok,void (* function)(int fd,char * name))445 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
446 void (*function)(int fd, char *name))
447 {
448 int fd;
449
450 // If no arguments, read from stdin.
451 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
452 else do {
453 // Filename "-" means read from stdin.
454 // Inability to open a file prints a warning, but doesn't exit.
455
456 if (!strcmp(*argv, "-")) fd=0;
457 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
458 perror_msg("%s", *argv);
459 toys.exitval = 1;
460 continue;
461 }
462 function(fd, *argv);
463 if (flags & O_CLOEXEC) close(fd);
464 } while (*++argv);
465 }
466
467 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
loopfiles(char ** argv,void (* function)(int fd,char * name))468 void loopfiles(char **argv, void (*function)(int fd, char *name))
469 {
470 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
471 }
472
473 // Slow, but small.
474
get_rawline(int fd,long * plen,char end)475 char *get_rawline(int fd, long *plen, char end)
476 {
477 char c, *buf = NULL;
478 long len = 0;
479
480 for (;;) {
481 if (1>read(fd, &c, 1)) break;
482 if (!(len & 63)) buf=xrealloc(buf, len+65);
483 if ((buf[len++]=c) == end) break;
484 }
485 if (buf) buf[len]=0;
486 if (plen) *plen = len;
487
488 return buf;
489 }
490
get_line(int fd)491 char *get_line(int fd)
492 {
493 long len;
494 char *buf = get_rawline(fd, &len, '\n');
495
496 if (buf && buf[--len]=='\n') buf[len]=0;
497
498 return buf;
499 }
500
wfchmodat(int fd,char * name,mode_t mode)501 int wfchmodat(int fd, char *name, mode_t mode)
502 {
503 int rc = fchmodat(fd, name, mode, 0);
504
505 if (rc) {
506 perror_msg("chmod '%s' to %04o", name, mode);
507 toys.exitval=1;
508 }
509 return rc;
510 }
511
512 static char *tempfile2zap;
tempfile_handler(int i)513 static void tempfile_handler(int i)
514 {
515 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
516 _exit(1);
517 }
518
519 // Open a temporary file to copy an existing file into.
copy_tempfile(int fdin,char * name,char ** tempname)520 int copy_tempfile(int fdin, char *name, char **tempname)
521 {
522 struct stat statbuf;
523 int fd;
524
525 *tempname = xmprintf("%s%s", name, "XXXXXX");
526 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
527 if (!tempfile2zap) sigatexit(tempfile_handler);
528 tempfile2zap = *tempname;
529
530 // Set permissions of output file
531
532 fstat(fdin, &statbuf);
533 fchmod(fd, statbuf.st_mode);
534
535 return fd;
536 }
537
538 // Abort the copy and delete the temporary file.
delete_tempfile(int fdin,int fdout,char ** tempname)539 void delete_tempfile(int fdin, int fdout, char **tempname)
540 {
541 close(fdin);
542 close(fdout);
543 unlink(*tempname);
544 tempfile2zap = (char *)1;
545 free(*tempname);
546 *tempname = NULL;
547 }
548
549 // Copy the rest of the data and replace the original with the copy.
replace_tempfile(int fdin,int fdout,char ** tempname)550 void replace_tempfile(int fdin, int fdout, char **tempname)
551 {
552 char *temp = xstrdup(*tempname);
553
554 temp[strlen(temp)-6]=0;
555 if (fdin != -1) {
556 xsendfile(fdin, fdout);
557 xclose(fdin);
558 }
559 xclose(fdout);
560 rename(*tempname, temp);
561 tempfile2zap = (char *)1;
562 free(*tempname);
563 free(temp);
564 *tempname = NULL;
565 }
566
567 // Create a 256 entry CRC32 lookup table.
568
crc_init(unsigned int * crc_table,int little_endian)569 void crc_init(unsigned int *crc_table, int little_endian)
570 {
571 unsigned int i;
572
573 // Init the CRC32 table (big endian)
574 for (i=0; i<256; i++) {
575 unsigned int j, c = little_endian ? i : i<<24;
576 for (j=8; j; j--)
577 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
578 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
579 crc_table[i] = c;
580 }
581 }
582
583 // Init base64 table
584
base64_init(char * p)585 void base64_init(char *p)
586 {
587 int i;
588
589 for (i = 'A'; i != ':'; i++) {
590 if (i == 'Z'+1) i = 'a';
591 if (i == 'z'+1) i = '0';
592 *(p++) = i;
593 }
594 *(p++) = '+';
595 *(p++) = '/';
596 }
597
yesno(char * prompt,int def)598 int yesno(char *prompt, int def)
599 {
600 char buf;
601
602 fprintf(stderr, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
603 fflush(stderr);
604 while (fread(&buf, 1, 1, stdin)) {
605 int new;
606
607 // The letter changes the value, the newline (or space) returns it.
608 if (isspace(buf)) break;
609 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
610 }
611
612 return def;
613 }
614
615 struct signame {
616 int num;
617 char *name;
618 };
619
620 // Signals required by POSIX 2008:
621 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
622
623 #define SIGNIFY(x) {SIG##x, #x}
624
625 static struct signame signames[] = {
626 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
627 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
628 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
629 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
630 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
631
632 // Start of non-terminal signals
633
634 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
635 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
636 };
637
638 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
639 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
640
641 // Handler that sets toys.signal, and writes to toys.signalfd if set
generic_signal(int sig)642 void generic_signal(int sig)
643 {
644 if (toys.signalfd) {
645 char c = sig;
646
647 writeall(toys.signalfd, &c, 1);
648 }
649 toys.signal = sig;
650 }
651
652 // Install the same handler on every signal that defaults to killing the process
sigatexit(void * handler)653 void sigatexit(void *handler)
654 {
655 int i;
656 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
657 }
658
659 // Convert name to signal number. If name == NULL print names.
sig_to_num(char * pidstr)660 int sig_to_num(char *pidstr)
661 {
662 int i;
663
664 if (pidstr) {
665 char *s;
666
667 i = estrtol(pidstr, &s, 10);
668 if (!errno && !*s) return i;
669
670 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
671 }
672 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
673 if (!pidstr) xputs(signames[i].name);
674 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
675
676 return -1;
677 }
678
num_to_sig(int sig)679 char *num_to_sig(int sig)
680 {
681 int i;
682
683 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
684 if (signames[i].num == sig) return signames[i].name;
685 return NULL;
686 }
687
688 // premute mode bits based on posix mode strings.
string_to_mode(char * modestr,mode_t mode)689 mode_t string_to_mode(char *modestr, mode_t mode)
690 {
691 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
692 *s, *str = modestr;
693 mode_t extrabits = mode & ~(07777);
694
695 // Handle octal mode
696 if (isdigit(*str)) {
697 mode = estrtol(str, &s, 8);
698 if (errno || *s || (mode & ~(07777))) goto barf;
699
700 return mode | extrabits;
701 }
702
703 // Gaze into the bin of permission...
704 for (;;) {
705 int i, j, dowho, dohow, dowhat, amask;
706
707 dowho = dohow = dowhat = amask = 0;
708
709 // Find the who, how, and what stanzas, in that order
710 while (*str && (s = strchr(whos, *str))) {
711 dowho |= 1<<(s-whos);
712 str++;
713 }
714 // If who isn't specified, like "a" but honoring umask.
715 if (!dowho) {
716 dowho = 8;
717 umask(amask=umask(0));
718 }
719 if (!*str || !(s = strchr(hows, *str))) goto barf;
720 dohow = *(str++);
721
722 if (!dohow) goto barf;
723 while (*str && (s = strchr(whats, *str))) {
724 dowhat |= 1<<(s-whats);
725 str++;
726 }
727
728 // Convert X to x for directory or if already executable somewhere
729 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
730
731 // Copy mode from another category?
732 if (!dowhat && *str && (s = strchr(whys, *str))) {
733 dowhat = (mode>>(3*(s-whys)))&7;
734 str++;
735 }
736
737 // Are we ready to do a thing yet?
738 if (*str && *(str++) != ',') goto barf;
739
740 // Ok, apply the bits to the mode.
741 for (i=0; i<4; i++) {
742 for (j=0; j<3; j++) {
743 mode_t bit = 0;
744 int where = 1<<((3*i)+j);
745
746 if (amask & where) continue;
747
748 // Figure out new value at this location
749 if (i == 3) {
750 // suid/sticky bit.
751 if (j) {
752 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
753 } else if (dowhat & 16) bit++;
754 } else {
755 if (!(dowho&(8|(1<<i)))) continue;
756 if (dowhat&(1<<j)) bit++;
757 }
758
759 // When selection active, modify bit
760
761 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
762 if (bit && dohow != '-') mode |= where;
763 }
764 }
765
766 if (!*str) break;
767 }
768
769 return mode|extrabits;
770 barf:
771 error_exit("bad mode '%s'", modestr);
772 }
773
774 // Format access mode into a drwxrwxrwx string
mode_to_string(mode_t mode,char * buf)775 void mode_to_string(mode_t mode, char *buf)
776 {
777 char c, d;
778 int i, bit;
779
780 buf[10]=0;
781 for (i=0; i<9; i++) {
782 bit = mode & (1<<i);
783 c = i%3;
784 if (!c && (mode & (1<<((d=i/3)+9)))) {
785 c = "tss"[d];
786 if (!bit) c &= ~0x20;
787 } else c = bit ? "xwr"[c] : '-';
788 buf[9-i] = c;
789 }
790
791 if (S_ISDIR(mode)) c = 'd';
792 else if (S_ISBLK(mode)) c = 'b';
793 else if (S_ISCHR(mode)) c = 'c';
794 else if (S_ISLNK(mode)) c = 'l';
795 else if (S_ISFIFO(mode)) c = 'p';
796 else if (S_ISSOCK(mode)) c = 's';
797 else c = '-';
798 *buf = c;
799 }
800
801 // Execute a callback for each PID that matches a process name from a list.
names_to_pid(char ** names,int (* callback)(pid_t pid,char * name))802 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
803 {
804 DIR *dp;
805 struct dirent *entry;
806
807 if (!(dp = opendir("/proc"))) perror_exit("opendir");
808
809 while ((entry = readdir(dp))) {
810 unsigned u;
811 char *cmd, **curname;
812
813 if (!(u = atoi(entry->d_name))) continue;
814 sprintf(libbuf, "/proc/%u/cmdline", u);
815 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
816
817 for (curname = names; *curname; curname++)
818 if (**curname == '/' ? !strcmp(cmd, *curname)
819 : !strcmp(basename(cmd), basename(*curname)))
820 if (callback(u, *curname)) break;
821 if (*curname) break;
822 }
823 closedir(dp);
824 }
825
826 // display first few digits of number with power of two units, except we're
827 // actually just counting decimal digits and showing mil/bil/trillions.
human_readable(char * buf,unsigned long long num)828 int human_readable(char *buf, unsigned long long num)
829 {
830 int end, len;
831
832 len = sprintf(buf, "%lld", num)-1;
833 end = (len%3)+1;
834 len /= 3;
835
836 if (len && end == 1) {
837 buf[2] = buf[1];
838 buf[1] = '.';
839 end = 3;
840 }
841 buf[end++] = ' ';
842 if (len) buf[end++] = " KMGTPE"[len];
843 buf[end++] = 'B';
844 buf[end++] = 0;
845
846 return end;
847 }
848
849 // The qsort man page says you can use alphasort, the posix committee
850 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
851 // So just do our own. (The const is entirely to humor the stupid compiler.)
qstrcmp(const void * a,const void * b)852 int qstrcmp(const void *a, const void *b)
853 {
854 return strcmp(*(char **)a, *(char **)b);
855 }
856
xpoll(struct pollfd * fds,int nfds,int timeout)857 int xpoll(struct pollfd *fds, int nfds, int timeout)
858 {
859 int i;
860
861 for (;;) {
862 if (0>(i = poll(fds, nfds, timeout))) {
863 if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
864 else if (timeout>0) timeout--;
865 } else return i;
866 }
867 }
868