· 9 years ago · Oct 17, 2016, 05:30 AM
1external/toybox/lib/lib.c:938:21: error: implicit declaration of function 'basename_r' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
2 : !strcmp(basename_r(cmd), basename_r(*curname)))
3 ^
4external/toybox/lib/lib.c:938:21: note: did you mean 'ptsname_r'?
5bionic/libc/include/stdlib.h:135:5: note: 'ptsname_r' declared here
6int ptsname_r(int, char*, size_t);
7 ^
8external/toybox/lib/lib.c:938:21: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Werror,-Wint-conversion]
9 : !strcmp(basename_r(cmd), basename_r(*curname)))
10 ^~~~~~~~~~~~~~~
11bionic/libc/include/string.h:70:34: note: passing argument to parameter here
12extern int strcmp(const char *, const char *) __purefunc;
13 ^
14external/toybox/lib/lib.c:938:38: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Werror,-Wint-conversion]
15 : !strcmp(basename_r(cmd), basename_r(*curname)))
16 ^~~~~~~~~~~~~~~~~~~~
17bionic/libc/include/string.h:70:48: note: passing argument to parameter here
18extern int strcmp(const char *, const char *) __purefunc;
19
20
21 /* lib.c - various reusable stuff.
22 *
23 * Copyright 2006 Rob Landley <rob@landley.net>
24 */
25
26 #include "toys.h"
27
28 void verror_msg(char *msg, int err, va_list va)
29 {
30 char *s = ": %s";
31
32 fprintf(stderr, "%s: ", toys.which->name);
33 if (msg) vfprintf(stderr, msg, va);
34 else s+=2;
35 if (err) fprintf(stderr, s, strerror(err));
36 if (msg || err) putc('\n', stderr);
37 if (!toys.exitval) toys.exitval++;
38 }
39
40 // These functions don't collapse together because of the va_stuff.
41
42 void error_msg(char *msg, ...)
43 {
44 va_list va;
45
46 va_start(va, msg);
47 verror_msg(msg, 0, va);
48 va_end(va);
49 }
50
51 void perror_msg(char *msg, ...)
52 {
53 va_list va;
54
55 va_start(va, msg);
56 verror_msg(msg, errno, va);
57 va_end(va);
58 }
59
60 // Die with an error message.
61 void error_exit(char *msg, ...)
62 {
63 va_list va;
64
65 va_start(va, msg);
66 verror_msg(msg, 0, va);
67 va_end(va);
68
69 xexit();
70 }
71
72 // Die with an error message and strerror(errno)
73 void perror_exit(char *msg, ...)
74 {
75 va_list va;
76
77 va_start(va, msg);
78 verror_msg(msg, errno, va);
79 va_end(va);
80
81 xexit();
82 }
83
84 // Exit with an error message after showing help text.
85 void help_exit(char *msg, ...)
86 {
87 va_list va;
88
89 if (CFG_TOYBOX_HELP) show_help(stderr);
90
91 if (msg) {
92 va_start(va, msg);
93 verror_msg(msg, 0, va);
94 va_end(va);
95 }
96
97 xexit();
98 }
99
100 // If you want to explicitly disable the printf() behavior (because you're
101 // printing user-supplied data, or because android's static checker produces
102 // false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
103 // -Werror there for policy reasons).
104 void error_msg_raw(char *msg)
105 {
106 error_msg("%s", msg);
107 }
108
109 void perror_msg_raw(char *msg)
110 {
111 perror_msg("%s", msg);
112 }
113
114 void error_exit_raw(char *msg)
115 {
116 error_exit("%s", msg);
117 }
118
119 void perror_exit_raw(char *msg)
120 {
121 perror_exit("%s", msg);
122 }
123
124 // Keep reading until full or EOF
125 ssize_t readall(int fd, void *buf, size_t len)
126 {
127 size_t count = 0;
128
129 while (count<len) {
130 int i = read(fd, (char *)buf+count, len-count);
131 if (!i) break;
132 if (i<0) return i;
133 count += i;
134 }
135
136 return count;
137 }
138
139 // Keep writing until done or EOF
140 ssize_t writeall(int fd, void *buf, size_t len)
141 {
142 size_t count = 0;
143 while (count<len) {
144 int i = write(fd, count+(char *)buf, len-count);
145 if (i<1) return i;
146 count += i;
147 }
148
149 return count;
150 }
151
152 // skip this many bytes of input. Return 0 for success, >0 means this much
153 // left after input skipped.
154 off_t lskip(int fd, off_t offset)
155 {
156 off_t cur = lseek(fd, 0, SEEK_CUR);
157
158 if (cur != -1) {
159 off_t end = lseek(fd, 0, SEEK_END) - cur;
160
161 if (end > 0 && end < offset) return offset - end;
162 end = offset+cur;
163 if (end == lseek(fd, end, SEEK_SET)) return 0;
164 perror_exit("lseek");
165 }
166
167 while (offset>0) {
168 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
169
170 or = readall(fd, libbuf, try);
171 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
172 else offset -= or;
173 if (or < try) break;
174 }
175
176 return offset;
177 }
178
179 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
180 // 2=make path (already exists is ok)
181 // 4=verbose
182 // returns 0 = path ok, 1 = error
183 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
184 {
185 struct stat buf;
186 char *s;
187
188 // mkdir -p one/two/three is not an error if the path already exists,
189 // but is if "three" is a file. The others we dereference and catch
190 // not-a-directory along the way, but the last one we must explicitly
191 // test for. Might as well do it up front.
192
193 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
194 errno = EEXIST;
195 return 1;
196 }
197
198 for (s = dir; ;s++) {
199 char save = 0;
200 mode_t mode = (0777&~toys.old_umask)|0300;
201
202 // find next '/', but don't try to mkdir "" at start of absolute path
203 if (*s == '/' && (flags&2) && s != dir) {
204 save = *s;
205 *s = 0;
206 } else if (*s) continue;
207
208 // Use the mode from the -m option only for the last directory.
209 if (!save) {
210 if (flags&1) mode = lastmode;
211 else break;
212 }
213
214 if (mkdirat(atfd, dir, mode)) {
215 if (!(flags&2) || errno != EEXIST) return 1;
216 } else if (flags&4)
217 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
218
219 if (!(*s = save)) break;
220 }
221
222 return 0;
223 }
224
225 // Split a path into linked list of components, tracking head and tail of list.
226 // Filters out // entries with no contents.
227 struct string_list **splitpath(char *path, struct string_list **list)
228 {
229 char *new = path;
230
231 *list = 0;
232 do {
233 int len;
234
235 if (*path && *path != '/') continue;
236 len = path-new;
237 if (len > 0) {
238 *list = xmalloc(sizeof(struct string_list) + len + 1);
239 (*list)->next = 0;
240 memcpy((*list)->str, new, len);
241 (*list)->str[len] = 0;
242 list = &(*list)->next;
243 }
244 new = path+1;
245 } while (*path++);
246
247 return list;
248 }
249
250 // Find all file in a colon-separated path with access type "type" (generally
251 // X_OK or R_OK). Returns a list of absolute paths to each file found, in
252 // order.
253
254 struct string_list *find_in_path(char *path, char *filename)
255 {
256 struct string_list *rlist = NULL, **prlist=&rlist;
257 char *cwd;
258
259 if (!path) return 0;
260
261 cwd = xgetcwd();
262 for (;;) {
263 char *next = strchr(path, ':');
264 int len = next ? next-path : strlen(path);
265 struct string_list *rnext;
266 struct stat st;
267
268 rnext = xmalloc(sizeof(void *) + strlen(filename)
269 + (len ? len : strlen(cwd)) + 2);
270 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
271 else {
272 char *res = rnext->str;
273
274 memcpy(res, path, len);
275 res += len;
276 *(res++) = '/';
277 strcpy(res, filename);
278 }
279
280 // Confirm it's not a directory.
281 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
282 *prlist = rnext;
283 rnext->next = NULL;
284 prlist = &(rnext->next);
285 } else free(rnext);
286
287 if (!next) break;
288 path += len;
289 path++;
290 }
291 free(cwd);
292
293 return rlist;
294 }
295
296 long estrtol(char *str, char **end, int base)
297 {
298 errno = 0;
299
300 return strtol(str, end, base);
301 }
302
303 long xstrtol(char *str, char **end, int base)
304 {
305 long l = estrtol(str, end, base);
306
307 if (errno) perror_exit_raw(str);
308
309 return l;
310 }
311
312 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
313 // (zetta and yotta don't fit in 64 bits.)
314 long atolx(char *numstr)
315 {
316 char *c, *suffixes="cbkmgtpe", *end;
317 long val;
318
319 val = xstrtol(numstr, &c, 0);
320 if (*c) {
321 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
322 int shift = end-suffixes-2;
323 if (shift >= 0) val *= 1024L<<(shift*10);
324 } else {
325 while (isspace(*c)) c++;
326 if (*c) error_exit("not integer: %s", numstr);
327 }
328 }
329
330 return val;
331 }
332
333 long atolx_range(char *numstr, long low, long high)
334 {
335 long val = atolx(numstr);
336
337 if (val < low) error_exit("%ld < %ld", val, low);
338 if (val > high) error_exit("%ld > %ld", val, high);
339
340 return val;
341 }
342
343 int stridx(char *haystack, char needle)
344 {
345 char *off;
346
347 if (!needle) return -1;
348 off = strchr(haystack, needle);
349 if (!off) return -1;
350
351 return off-haystack;
352 }
353
354 char *strlower(char *s)
355 {
356 char *try, *new;
357
358 if (!CFG_TOYBOX_I18N) {
359 try = new = xstrdup(s);
360 for (; *s; s++) *(new++) = tolower(*s);
361 } else {
362 // I can't guarantee the string _won't_ expand during reencoding, so...?
363 try = new = xmalloc(strlen(s)*2+1);
364
365 while (*s) {
366 wchar_t c;
367 int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
368
369 if (len < 1) *(new++) = *(s++);
370 else {
371 s += len;
372 // squash title case too
373 c = towlower(c);
374
375 // if we had a valid utf8 sequence, convert it to lower case, and can't
376 // encode back to utf8, something is wrong with your libc. But just
377 // in case somebody finds an exploit...
378 len = wcrtomb(new, c, 0);
379 if (len < 1) error_exit("bad utf8 %x", (int)c);
380 new += len;
381 }
382 }
383 *new = 0;
384 }
385
386 return try;
387 }
388
389 // strstr but returns pointer after match
390 char *strafter(char *haystack, char *needle)
391 {
392 char *s = strstr(haystack, needle);
393
394 return s ? s+strlen(needle) : s;
395 }
396
397 // Remove trailing \n
398 char *chomp(char *s)
399 {
400 char *p = strrchr(s, '\n');
401
402 if (p && !p[1]) *p = 0;
403 return s;
404 }
405
406 int unescape(char c)
407 {
408 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
409 int idx = stridx(from, c);
410
411 return (idx == -1) ? 0 : to[idx];
412 }
413
414 // If *a starts with b, advance *a past it and return 1, else return 0;
415 int strstart(char **a, char *b)
416 {
417 int len = strlen(b), i = !strncmp(*a, b, len);
418
419 if (i) *a += len;
420
421 return i;
422 }
423
424 // Return how long the file at fd is, if there's any way to determine it.
425 off_t fdlength(int fd)
426 {
427 struct stat st;
428 off_t base = 0, range = 1, expand = 1, old;
429
430 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
431
432 // If the ioctl works for this, return it.
433 // TODO: is blocksize still always 512, or do we stat for it?
434 // unsigned int size;
435 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
436
437 // If not, do a binary search for the last location we can read. (Some
438 // block devices don't do BLKGETSIZE right.) This should probably have
439 // a CONFIG option...
440
441 // If not, do a binary search for the last location we can read.
442
443 old = lseek(fd, 0, SEEK_CUR);
444 do {
445 char temp;
446 off_t pos = base + range / 2;
447
448 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
449 off_t delta = (pos + 1) - base;
450
451 base += delta;
452 if (expand) range = (expand <<= 1) - base;
453 else range -= delta;
454 } else {
455 expand = 0;
456 range = pos - base;
457 }
458 } while (range > 0);
459
460 lseek(fd, old, SEEK_SET);
461
462 return base;
463 }
464
465 // Read contents of file as a single nul-terminated string.
466 // measure file size if !len, allocate buffer if !buf
467 // note: for existing buffers use len = size-1, will set buf[len] = 0
468 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
469 {
470 off_t len, rlen;
471 int fd;
472 char *buf, *rbuf;
473
474 // Unsafe to probe for size with a supplied buffer, don't ever do that.
475 if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
476
477 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
478
479 // If we dunno the length, probe it. If we can't probe, start with 1 page.
480 if (!*plen) {
481 if ((len = fdlength(fd))>0) *plen = len;
482 else len = 4096;
483 } else len = *plen-1;
484
485 if (!ibuf) buf = xmalloc(len+1);
486 else buf = ibuf;
487
488 for (rbuf = buf;;) {
489 rlen = readall(fd, rbuf, len);
490 if (*plen || rlen<len) break;
491
492 // If reading unknown size, expand buffer by 1.5 each time we fill it up.
493 rlen += rbuf-buf;
494 buf = xrealloc(buf, len = (rlen*3)/2);
495 rbuf = buf+rlen;
496 len -= rlen;
497 }
498 *plen = len = rlen+(rbuf-buf);
499 close(fd);
500
501 if (rlen<0) {
502 if (ibuf != buf) free(buf);
503 buf = 0;
504 } else buf[len] = 0;
505
506 return buf;
507 }
508
509 char *readfile(char *name, char *ibuf, off_t len)
510 {
511 return readfileat(AT_FDCWD, name, ibuf, &len);
512 }
513
514 // Sleep for this many thousandths of a second
515 void msleep(long miliseconds)
516 {
517 struct timespec ts;
518
519 ts.tv_sec = miliseconds/1000;
520 ts.tv_nsec = (miliseconds%1000)*1000000;
521 nanosleep(&ts, &ts);
522 }
523
524 // Inefficient, but deals with unaligned access
525 int64_t peek_le(void *ptr, unsigned size)
526 {
527 int64_t ret = 0;
528 char *c = ptr;
529 int i;
530
531 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
532 return ret;
533 }
534
535 int64_t peek_be(void *ptr, unsigned size)
536 {
537 int64_t ret = 0;
538 char *c = ptr;
539 int i;
540
541 for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
542 return ret;
543 }
544
545 int64_t peek(void *ptr, unsigned size)
546 {
547 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
548 }
549
550 void poke(void *ptr, uint64_t val, int size)
551 {
552 if (size & 8) {
553 volatile uint64_t *p = (uint64_t *)ptr;
554 *p = val;
555 } else if (size & 4) {
556 volatile int *p = (int *)ptr;
557 *p = val;
558 } else if (size & 2) {
559 volatile short *p = (short *)ptr;
560 *p = val;
561 } else {
562 volatile char *p = (char *)ptr;
563 *p = val;
564 }
565 }
566
567 // Iterate through an array of files, opening each one and calling a function
568 // on that filehandle and name. The special filename "-" means stdin if
569 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
570 // function() on just stdin/stdout.
571 //
572 // Note: pass O_CLOEXEC to automatically close filehandles when function()
573 // returns, otherwise filehandles must be closed by function()
574 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
575 void (*function)(int fd, char *name))
576 {
577 int fd;
578
579 // If no arguments, read from stdin.
580 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
581 else do {
582 // Filename "-" means read from stdin.
583 // Inability to open a file prints a warning, but doesn't exit.
584
585 if (!strcmp(*argv, "-")) fd=0;
586 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
587 perror_msg_raw(*argv);
588 continue;
589 }
590 function(fd, *argv);
591 if (flags & O_CLOEXEC) close(fd);
592 } while (*++argv);
593 }
594
595 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
596 void loopfiles(char **argv, void (*function)(int fd, char *name))
597 {
598 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
599 }
600
601 // Slow, but small.
602
603 char *get_rawline(int fd, long *plen, char end)
604 {
605 char c, *buf = NULL;
606 long len = 0;
607
608 for (;;) {
609 if (1>read(fd, &c, 1)) break;
610 if (!(len & 63)) buf=xrealloc(buf, len+65);
611 if ((buf[len++]=c) == end) break;
612 }
613 if (buf) buf[len]=0;
614 if (plen) *plen = len;
615
616 return buf;
617 }
618
619 char *get_line(int fd)
620 {
621 long len;
622 char *buf = get_rawline(fd, &len, '\n');
623
624 if (buf && buf[--len]=='\n') buf[len]=0;
625
626 return buf;
627 }
628
629 int wfchmodat(int fd, char *name, mode_t mode)
630 {
631 int rc = fchmodat(fd, name, mode, 0);
632
633 if (rc) {
634 perror_msg("chmod '%s' to %04o", name, mode);
635 toys.exitval=1;
636 }
637 return rc;
638 }
639
640 static char *tempfile2zap;
641 static void tempfile_handler(int i)
642 {
643 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
644 _exit(1);
645 }
646
647 // Open a temporary file to copy an existing file into.
648 int copy_tempfile(int fdin, char *name, char **tempname)
649 {
650 struct stat statbuf;
651 int fd;
652
653 *tempname = xmprintf("%s%s", name, "XXXXXX");
654 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
655 if (!tempfile2zap) sigatexit(tempfile_handler);
656 tempfile2zap = *tempname;
657
658 // Set permissions of output file
659
660 fstat(fdin, &statbuf);
661 fchmod(fd, statbuf.st_mode);
662
663 return fd;
664 }
665
666 // Abort the copy and delete the temporary file.
667 void delete_tempfile(int fdin, int fdout, char **tempname)
668 {
669 close(fdin);
670 close(fdout);
671 if (*tempname) unlink(*tempname);
672 tempfile2zap = (char *)1;
673 free(*tempname);
674 *tempname = NULL;
675 }
676
677 // Copy the rest of the data and replace the original with the copy.
678 void replace_tempfile(int fdin, int fdout, char **tempname)
679 {
680 char *temp = xstrdup(*tempname);
681
682 temp[strlen(temp)-6]=0;
683 if (fdin != -1) {
684 xsendfile(fdin, fdout);
685 xclose(fdin);
686 }
687 xclose(fdout);
688 rename(*tempname, temp);
689 tempfile2zap = (char *)1;
690 free(*tempname);
691 free(temp);
692 *tempname = NULL;
693 }
694
695 // Create a 256 entry CRC32 lookup table.
696
697 void crc_init(unsigned int *crc_table, int little_endian)
698 {
699 unsigned int i;
700
701 // Init the CRC32 table (big endian)
702 for (i=0; i<256; i++) {
703 unsigned int j, c = little_endian ? i : i<<24;
704 for (j=8; j; j--)
705 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
706 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
707 crc_table[i] = c;
708 }
709 }
710
711 // Init base64 table
712
713 void base64_init(char *p)
714 {
715 int i;
716
717 for (i = 'A'; i != ':'; i++) {
718 if (i == 'Z'+1) i = 'a';
719 if (i == 'z'+1) i = '0';
720 *(p++) = i;
721 }
722 *(p++) = '+';
723 *(p++) = '/';
724 }
725
726 int yesno(int def)
727 {
728 char buf;
729
730 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
731 fflush(stderr);
732 while (fread(&buf, 1, 1, stdin)) {
733 int new;
734
735 // The letter changes the value, the newline (or space) returns it.
736 if (isspace(buf)) break;
737 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
738 }
739
740 return def;
741 }
742
743 struct signame {
744 int num;
745 char *name;
746 };
747
748 // Signals required by POSIX 2008:
749 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
750
751 #define SIGNIFY(x) {SIG##x, #x}
752
753 static struct signame signames[] = {
754 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
755 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
756 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
757 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
758 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
759
760 // Start of non-terminal signals
761
762 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
763 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
764 };
765
766 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
767 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
768
769 // Handler that sets toys.signal, and writes to toys.signalfd if set
770 void generic_signal(int sig)
771 {
772 if (toys.signalfd) {
773 char c = sig;
774
775 writeall(toys.signalfd, &c, 1);
776 }
777 toys.signal = sig;
778 }
779
780 // Install the same handler on every signal that defaults to killing the process
781 void sigatexit(void *handler)
782 {
783 int i;
784 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
785 }
786
787 // Convert name to signal number. If name == NULL print names.
788 int sig_to_num(char *pidstr)
789 {
790 int i;
791
792 if (pidstr) {
793 char *s;
794
795 i = estrtol(pidstr, &s, 10);
796 if (!errno && !*s) return i;
797
798 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
799 }
800 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
801 if (!pidstr) xputs(signames[i].name);
802 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
803
804 return -1;
805 }
806
807 char *num_to_sig(int sig)
808 {
809 int i;
810
811 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
812 if (signames[i].num == sig) return signames[i].name;
813 return NULL;
814 }
815
816 // premute mode bits based on posix mode strings.
817 mode_t string_to_mode(char *modestr, mode_t mode)
818 {
819 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
820 *s, *str = modestr;
821 mode_t extrabits = mode & ~(07777);
822
823 // Handle octal mode
824 if (isdigit(*str)) {
825 mode = estrtol(str, &s, 8);
826 if (errno || *s || (mode & ~(07777))) goto barf;
827
828 return mode | extrabits;
829 }
830
831 // Gaze into the bin of permission...
832 for (;;) {
833 int i, j, dowho, dohow, dowhat, amask;
834
835 dowho = dohow = dowhat = amask = 0;
836
837 // Find the who, how, and what stanzas, in that order
838 while (*str && (s = strchr(whos, *str))) {
839 dowho |= 1<<(s-whos);
840 str++;
841 }
842 // If who isn't specified, like "a" but honoring umask.
843 if (!dowho) {
844 dowho = 8;
845 umask(amask=umask(0));
846 }
847 if (!*str || !(s = strchr(hows, *str))) goto barf;
848 dohow = *(str++);
849
850 if (!dohow) goto barf;
851 while (*str && (s = strchr(whats, *str))) {
852 dowhat |= 1<<(s-whats);
853 str++;
854 }
855
856 // Convert X to x for directory or if already executable somewhere
857 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
858
859 // Copy mode from another category?
860 if (!dowhat && *str && (s = strchr(whys, *str))) {
861 dowhat = (mode>>(3*(s-whys)))&7;
862 str++;
863 }
864
865 // Are we ready to do a thing yet?
866 if (*str && *(str++) != ',') goto barf;
867
868 // Ok, apply the bits to the mode.
869 for (i=0; i<4; i++) {
870 for (j=0; j<3; j++) {
871 mode_t bit = 0;
872 int where = 1<<((3*i)+j);
873
874 if (amask & where) continue;
875
876 // Figure out new value at this location
877 if (i == 3) {
878 // suid/sticky bit.
879 if (j) {
880 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
881 } else if (dowhat & 16) bit++;
882 } else {
883 if (!(dowho&(8|(1<<i)))) continue;
884 if (dowhat&(1<<j)) bit++;
885 }
886
887 // When selection active, modify bit
888
889 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
890 if (bit && dohow != '-') mode |= where;
891 }
892 }
893
894 if (!*str) break;
895 }
896
897 return mode|extrabits;
898 barf:
899 error_exit("bad mode '%s'", modestr);
900 }
901
902 // Format access mode into a drwxrwxrwx string
903 void mode_to_string(mode_t mode, char *buf)
904 {
905 char c, d;
906 int i, bit;
907
908 buf[10]=0;
909 for (i=0; i<9; i++) {
910 bit = mode & (1<<i);
911 c = i%3;
912 if (!c && (mode & (1<<((d=i/3)+9)))) {
913 c = "tss"[d];
914 if (!bit) c &= ~0x20;
915 } else c = bit ? "xwr"[c] : '-';
916 buf[9-i] = c;
917 }
918
919 if (S_ISDIR(mode)) c = 'd';
920 else if (S_ISBLK(mode)) c = 'b';
921 else if (S_ISCHR(mode)) c = 'c';
922 else if (S_ISLNK(mode)) c = 'l';
923 else if (S_ISFIFO(mode)) c = 'p';
924 else if (S_ISSOCK(mode)) c = 's';
925 else c = '-';
926 *buf = c;
927 }
928
929 // basename() can modify its argument or return a pointer to a constant string
930 // This just gives after the last '/' or the whole stirng if no /
931 char *getbasename(char *name)
932 {
933 char *s = strrchr(name, '/');
934
935 if (s) return s+1;
936
937 return name;
938 }
939
940 // Execute a callback for each PID that matches a process name from a list.
941 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
942 {
943 DIR *dp;
944 struct dirent *entry;
945
946 if (!(dp = opendir("/proc"))) perror_exit("opendir");
947
948 while ((entry = readdir(dp))) {
949 unsigned u;
950 char *cmd, **curname;
951
952 if (!(u = atoi(entry->d_name))) continue;
953 sprintf(libbuf, "/proc/%u/cmdline", u);
954 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
955
956 for (curname = names; *curname; curname++)
957 if (**curname == '/' ? !strcmp(cmd, *curname)
958 : !strcmp(basename_r(cmd), basename_r(*curname)))
959 if (callback(u, *curname)) break;
960 if (*curname) break;
961 }
962 closedir(dp);
963 }
964
965 // display first few digits of number with power of two units
966 int human_readable(char *buf, unsigned long long num, int style)
967 {
968 unsigned long long snap = 0;
969 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
970
971 // Divide rounding up until we have 3 or fewer digits. Since the part we
972 // print is decimal, the test is 999 even when we divide by 1024.
973 // We can't run out of units because 2<<64 is 18 exabytes.
974 // test 5675 is 5.5k not 5.6k.
975 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
976 len = sprintf(buf, "%llu", num);
977 if (unit && len == 1) {
978 // Redo rounding for 1.2M case, this works with and without HR_1000.
979 num = snap/divisor;
980 snap -= num*divisor;
981 snap = ((snap*100)+50)/divisor;
982 snap /= 10;
983 len = sprintf(buf, "%llu.%llu", num, snap);
984 }
985 if (style & HR_SPACE) buf[len++] = ' ';
986 if (unit) {
987 unit = " kMGTPE"[unit];
988
989 if (!(style&HR_1000)) unit = toupper(unit);
990 buf[len++] = unit;
991 } else if (style & HR_B) buf[len++] = 'B';
992 buf[len] = 0;
993
994 return len;
995 }
996
997 // The qsort man page says you can use alphasort, the posix committee
998 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
999 // So just do our own. (The const is entirely to humor the stupid compiler.)
1000 int qstrcmp(const void *a, const void *b)
1001 {
1002 return strcmp(*(char **)a, *(char **)b);
1003 }
1004
1005 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
1006 // we should generate a uuid structure by reading a clock with 100 nanosecond
1007 // precision, normalizing it to the start of the gregorian calendar in 1582,
1008 // and looking up our eth0 mac address.
1009 //
1010 // On the other hand, we have 128 bits to come up with a unique identifier, of
1011 // which 6 have a defined value. /dev/urandom it is.
1012
1013 void create_uuid(char *uuid)
1014 {
1015 // Read 128 random bits
1016 int fd = xopen("/dev/urandom", O_RDONLY);
1017 xreadall(fd, uuid, 16);
1018 close(fd);
1019
1020 // Claim to be a DCE format UUID.
1021 uuid[6] = (uuid[6] & 0x0F) | 0x40;
1022 uuid[8] = (uuid[8] & 0x3F) | 0x80;
1023
1024 // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1025 // set bit 1 of the node ID, which is the mac multicast bit. This means we
1026 // should never collide with anybody actually using a macaddr.
1027 uuid[11] |= 128;
1028 }
1029
1030 char *show_uuid(char *uuid)
1031 {
1032 char *out = libbuf;
1033 int i;
1034
1035 for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1036 *out = 0;
1037
1038 return libbuf;
1039 }
1040
1041 // Returns pointer to letter at end, 0 if none. *start = initial %
1042 char *next_printf(char *s, char **start)
1043 {
1044 for (; *s; s++) {
1045 if (*s != '%') continue;
1046 if (*++s == '%') continue;
1047 if (start) *start = s-1;
1048 while (0 <= stridx("0'#-+ ", *s)) s++;
1049 while (isdigit(*s)) s++;
1050 if (*s == '.') s++;
1051 while (isdigit(*s)) s++;
1052
1053 return s;
1054 }
1055
1056 return 0;
1057 }
1058
1059 // Posix inexplicably hasn't got this, so find str in line.
1060 char *strnstr(char *line, char *str)
1061 {
1062 long len = strlen(str);
1063 char *s;
1064
1065 for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break;
1066
1067 return *s ? s : 0;
1068 }