• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* lib.c - various reusable stuff.
2  *
3  * Copyright 2006 Rob Landley <rob@landley.net>
4  */
5 
6 #define SYSLOG_NAMES
7 #include "toys.h"
8 
verror_msg(char * msg,int err,va_list va)9 void verror_msg(char *msg, int err, va_list va)
10 {
11   char *s = ": %s";
12 
13   // Exit silently in a pipeline
14   if (err != EPIPE) {
15     fprintf(stderr, "%s: ", toys.which->name);
16     if (msg) vfprintf(stderr, msg, va);
17     else s+=2;
18     if (err>0) fprintf(stderr, s, strerror(err));
19     if (err<0 && CFG_TOYBOX_HELP)
20       fprintf(stderr, " (see \"%s --help\")", toys.which->name);
21     if (msg || err) putc('\n', stderr);
22   }
23   if (!toys.exitval) toys.exitval = (toys.which->flags>>24) ? : 1;
24 }
25 
26 // These functions don't collapse together because of the va_stuff.
27 
error_msg(char * msg,...)28 void error_msg(char *msg, ...)
29 {
30   va_list va;
31 
32   va_start(va, msg);
33   verror_msg(msg, 0, va);
34   va_end(va);
35 }
36 
perror_msg(char * msg,...)37 void perror_msg(char *msg, ...)
38 {
39   va_list va;
40 
41   va_start(va, msg);
42   verror_msg(msg, errno, va);
43   va_end(va);
44 }
45 
46 // Die with an error message.
error_exit(char * msg,...)47 void error_exit(char *msg, ...)
48 {
49   va_list va;
50 
51   va_start(va, msg);
52   verror_msg(msg, 0, va);
53   va_end(va);
54 
55   xexit();
56 }
57 
58 // Die with an error message and strerror(errno)
perror_exit(char * msg,...)59 void perror_exit(char *msg, ...)
60 {
61   va_list va;
62 
63   va_start(va, msg);
64   verror_msg(msg, errno, va);
65   va_end(va);
66 
67   xexit();
68 }
69 
70 // Exit with an error message after showing help text.
help_exit(char * msg,...)71 void help_exit(char *msg, ...)
72 {
73   va_list va;
74 
75   if (!msg) show_help(stdout, 1);
76   else {
77     va_start(va, msg);
78     verror_msg(msg, -1, va);
79     va_end(va);
80   }
81 
82   xexit();
83 }
84 
85 // If you want to explicitly disable the printf() behavior (because you're
86 // printing user-supplied data, or because android's static checker produces
87 // false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
88 // -Werror there for policy reasons).
error_msg_raw(char * msg)89 void error_msg_raw(char *msg)
90 {
91   error_msg("%s", msg);
92 }
93 
perror_msg_raw(char * msg)94 void perror_msg_raw(char *msg)
95 {
96   perror_msg("%s", msg);
97 }
98 
error_exit_raw(char * msg)99 void error_exit_raw(char *msg)
100 {
101   error_exit("%s", msg);
102 }
103 
perror_exit_raw(char * msg)104 void perror_exit_raw(char *msg)
105 {
106   perror_exit("%s", msg);
107 }
108 
109 // Keep reading until full or EOF. Note: assumes sigaction(SA_RESTART),
110 // otherwise SIGSTOP/SIGCONT can return 0 from read/write without EOF.
readall(int fd,void * buf,size_t len)111 ssize_t readall(int fd, void *buf, size_t len)
112 {
113   size_t count = 0;
114 
115   while (count<len) {
116     int i = read(fd, (char *)buf+count, len-count);
117     if (!i) break;
118     if (i<0) return i;
119     count += i;
120   }
121 
122   return count;
123 }
124 
125 // Keep writing until done or EOF
writeall(int fd,void * buf,size_t len)126 ssize_t writeall(int fd, void *buf, size_t len)
127 {
128   size_t count = 0;
129 
130   while (count<len) {
131     int i = write(fd, count+(char *)buf, len-count);
132     if (i<1) return i;
133     count += i;
134   }
135 
136   return count;
137 }
138 
139 // skip this many bytes of input. Return 0 for success, >0 means this much
140 // left after input skipped.
lskip(int fd,off_t offset)141 off_t lskip(int fd, off_t offset)
142 {
143   off_t cur = lseek(fd, 0, SEEK_CUR);
144 
145   if (cur != -1) {
146     off_t end = lseek(fd, 0, SEEK_END) - cur;
147 
148     if (end > 0 && end < offset) return offset - end;
149     end = offset+cur;
150     if (end == lseek(fd, end, SEEK_SET)) return 0;
151     perror_exit("lseek");
152   }
153 
154   while (offset>0) {
155     int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
156 
157     or = readall(fd, libbuf, try);
158     if (or < 0) perror_exit("lskip to %lld", (long long)offset);
159     else offset -= or;
160     if (or < try) break;
161   }
162 
163   return offset;
164 }
165 
166 // flags:
167 // MKPATHAT_MKLAST  make last dir (with mode lastmode, else skips last part)
168 // MKPATHAT_MAKE    make leading dirs (it's ok if they already exist)
169 // MKPATHAT_VERBOSE Print what got created to stderr
170 // returns 0 = path ok, 1 = error
mkpathat(int atfd,char * dir,mode_t lastmode,int flags)171 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
172 {
173   struct stat buf;
174   char *s;
175 
176   // mkdir -p one/two/three is not an error if the path already exists,
177   // but is if "three" is a file. The others we dereference and catch
178   // not-a-directory along the way, but the last one we must explicitly
179   // test for. Might as well do it up front.
180 
181   if (!fstatat(atfd, dir, &buf, 0)) {
182     // Note that mkdir should return EEXIST for already existed directory/file.
183     if (!(flags&MKPATHAT_MAKE) || ((flags&MKPATHAT_MKLAST) && !S_ISDIR(buf.st_mode))) {
184       errno = EEXIST;
185       return 1;
186     } else return 0;
187   }
188 
189   for (s = dir; ;s++) {
190     char save = 0;
191     mode_t mode = (0777&~toys.old_umask)|0300;
192 
193     // find next '/', but don't try to mkdir "" at start of absolute path
194     if (*s == '/' && (flags&MKPATHAT_MAKE) && s != dir) {
195       save = *s;
196       *s = 0;
197     } else if (*s) continue;
198 
199     // Use the mode from the -m option only for the last directory.
200     if (!save) {
201       if (flags&MKPATHAT_MKLAST) mode = lastmode;
202       else break;
203     }
204 
205     if (mkdirat(atfd, dir, mode)) {
206       if (!(flags&MKPATHAT_MAKE) || errno != EEXIST) return 1;
207     } else if (flags&MKPATHAT_VERBOSE)
208       fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
209 
210     if (!(*s = save)) break;
211   }
212 
213   return 0;
214 }
215 
216 // The common case
mkpath(char * dir)217 int mkpath(char *dir)
218 {
219   return mkpathat(AT_FDCWD, dir, 0, MKPATHAT_MAKE);
220 }
221 
222 // Split a path into linked list of components, tracking head and tail of list.
223 // Assigns head of list to *list, returns address of ->next entry to extend list
224 // Filters out // entries with no contents.
splitpath(char * path,struct string_list ** list)225 struct string_list **splitpath(char *path, struct string_list **list)
226 {
227   char *new = path;
228 
229   *list = 0;
230   do {
231     int len;
232 
233     if (*path && *path != '/') continue;
234     len = path-new;
235     if (len > 0) {
236       *list = xmalloc(sizeof(struct string_list) + len + 1);
237       (*list)->next = 0;
238       memcpy((*list)->str, new, len);
239       (*list)->str[len] = 0;
240       list = &(*list)->next;
241     }
242     new = path+1;
243   } while (*path++);
244 
245   return list;
246 }
247 
248 // Find all file in a colon-separated path with access type "type" (generally
249 // X_OK or R_OK).  Returns a list of absolute paths to each file found, in
250 // order.
251 
find_in_path(char * path,char * filename)252 struct string_list *find_in_path(char *path, char *filename)
253 {
254   struct string_list *rlist = NULL, **prlist=&rlist;
255   char *cwd;
256 
257   if (!path) return 0;
258 
259   cwd = xgetcwd();
260   for (;;) {
261     char *res, *next = strchr(path, ':');
262     int len = next ? next-path : strlen(path);
263     struct string_list *rnext;
264     struct stat st;
265 
266     rnext = xmalloc(sizeof(void *) + strlen(filename)
267       + (len ? len : strlen(cwd)) + 2);
268     if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
269     else {
270       memcpy(res = rnext->str, path, len);
271       res += len;
272       *(res++) = '/';
273       strcpy(res, filename);
274     }
275 
276     // Confirm it's not a directory.
277     if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
278       *prlist = rnext;
279       rnext->next = NULL;
280       prlist = &(rnext->next);
281     } else free(rnext);
282 
283     if (!next) break;
284     path += len;
285     path++;
286   }
287   free(cwd);
288 
289   return rlist;
290 }
291 
estrtol(char * str,char ** end,int base)292 long long estrtol(char *str, char **end, int base)
293 {
294   errno = 0;
295 
296   return strtoll(str, end, base);
297 }
298 
xstrtol(char * str,char ** end,int base)299 long long xstrtol(char *str, char **end, int base)
300 {
301   long long l = estrtol(str, end, base);
302 
303   if (errno) perror_exit_raw(str);
304 
305   return l;
306 }
307 
308 // atol() with the kilo/mega/giga/tera/peta/exa extensions, plus word and block.
309 // (zetta and yotta don't fit in 64 bits.)
atolx(char * numstr)310 long long atolx(char *numstr)
311 {
312   char *c = numstr, *suffixes="cwbkmgtpe", *end;
313   long long val;
314 
315   val = xstrtol(numstr, &c, 0);
316   if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) {
317     int shift = end-suffixes-2;
318     ++c;
319     if (shift==-1) val *= 2;
320     else if (!shift) val *= 512;
321     else if (shift>0) {
322       if (*c && tolower(*c)=='d') {
323         c++;
324         while (shift--) val *= 1000;
325       } else val *= 1LL<<(shift*10);
326     }
327   }
328   while (isspace(*c)) c++;
329   if (c==numstr || *c) error_exit("not integer: %s", numstr);
330 
331   return val;
332 }
333 
atolx_range(char * numstr,long long low,long long high)334 long long atolx_range(char *numstr, long long low, long long high)
335 {
336   long long val = atolx(numstr);
337 
338   if (val < low) error_exit("%lld < %lld", val, low);
339   if (val > high) error_exit("%lld > %lld", val, high);
340 
341   return val;
342 }
343 
stridx(char * haystack,char needle)344 int stridx(char *haystack, char needle)
345 {
346   char *off;
347 
348   if (!needle) return -1;
349   off = strchr(haystack, needle);
350   if (!off) return -1;
351 
352   return off-haystack;
353 }
354 
355 // Convert wc to utf8, returning bytes written. Does not null terminate.
wctoutf8(char * s,unsigned wc)356 int wctoutf8(char *s, unsigned wc)
357 {
358   int len = (wc>0x7ff)+(wc>0xffff), i;
359 
360   if (wc<128) {
361     *s = wc;
362     return 1;
363   } else {
364     i = len;
365     do {
366       s[1+i] = 0x80+(wc&0x3f);
367       wc >>= 6;
368     } while (i--);
369     *s = (((signed char) 0x80) >> (len+1)) | wc;
370   }
371 
372   return 2+len;
373 }
374 
375 // Convert utf8 sequence to a unicode wide character
376 // returns bytes consumed, or -1 if err, or -2 if need more data.
utf8towc(unsigned * wc,char * str,unsigned len)377 int utf8towc(unsigned *wc, char *str, unsigned len)
378 {
379   unsigned result, mask, first;
380   char *s, c;
381 
382   // fast path ASCII
383   if (len && *str<128) return !!(*wc = *str);
384 
385   result = first = *(s = str++);
386   if (result<0xc2 || result>0xf4) return -1;
387   for (mask = 6; (first&0xc0)==0xc0; mask += 5, first <<= 1) {
388     if (!--len) return -2;
389     if (((c = *(str++))&0xc0) != 0x80) return -1;
390     result = (result<<6)|(c&0x3f);
391   }
392   result &= (1<<mask)-1;
393   c = str-s;
394 
395   // Avoid overlong encodings
396   if (result<(unsigned []){0x80,0x800,0x10000}[c-2]) return -1;
397 
398   // Limit unicode so it can't encode anything UTF-16 can't.
399   if (result>0x10ffff || (result>=0xd800 && result<=0xdfff)) return -1;
400   *wc = result;
401 
402   return str-s;
403 }
404 
405 // Convert string to lower case, utf8 aware.
strlower(char * s)406 char *strlower(char *s)
407 {
408   char *try, *new;
409   int len, mlen = (strlen(s)|7)+9;
410   unsigned c;
411 
412   try = new = xmalloc(mlen);
413 
414   while (*s) {
415 
416     if (1>(len = utf8towc(&c, s, MB_CUR_MAX))) {
417       *(new++) = *(s++);
418 
419       continue;
420     }
421 
422     s += len;
423     // squash title case too
424     c = towlower(c);
425 
426     // if we had a valid utf8 sequence, convert it to lower case, and can't
427     // encode back to utf8, something is wrong with your libc. But just
428     // in case somebody finds an exploit...
429     len = wcrtomb(new, c, 0);
430     if (len < 1) error_exit("bad utf8 %x", (int)c);
431     new += len;
432 
433     // Case conversion can expand utf8 representation, but with extra mlen
434     // space above we should basically never need to realloc
435     if (mlen > (len = new-try)+4) continue;
436     try = xrealloc(try, mlen = len+16);
437     new = try+len;
438   }
439   *new = 0;
440 
441   return try;
442 }
443 
444 // strstr but returns pointer after match
strafter(char * haystack,char * needle)445 char *strafter(char *haystack, char *needle)
446 {
447   char *s = strstr(haystack, needle);
448 
449   return s ? s+strlen(needle) : s;
450 }
451 
452 // Remove trailing \n
chomp(char * s)453 char *chomp(char *s)
454 {
455   char *p;
456 
457   if (s) for (p = s+strlen(s); p>s && (p[-1]=='\r' || p[-1]=='\n'); *--p = 0);
458 
459   return s;
460 }
461 
unescape(char c)462 int unescape(char c)
463 {
464   char *from = "\\abefnrtv", *to = "\\\a\b\e\f\n\r\t\v";
465   int idx = stridx(from, c);
466 
467   return (idx == -1) ? 0 : to[idx];
468 }
469 
470 // parse next character advancing pointer. echo requires leading 0 in octal esc
unescape2(char ** c,int echo)471 int unescape2(char **c, int echo)
472 {
473   int idx = *((*c)++), i, off;
474 
475   if (idx != '\\' || !**c) return idx;
476   if (**c == 'c') return 31&*(++*c);
477   for (i = 0; i<4; i++) {
478     if (sscanf(*c, (char *[]){"0%3o%n"+!echo, "x%2x%n", "u%4x%n", "U%6x%n"}[i],
479         &idx, &off) > 0)
480     {
481       *c += off;
482 
483       return idx;
484     }
485   }
486 
487   if (-1 == (idx = stridx("\\abeEfnrtv'\"?0", **c))) return '\\';
488   ++*c;
489 
490   return "\\\a\b\e\e\f\n\r\t\v'\"?"[idx];
491 }
492 
493 // If string ends with suffix return pointer to start of suffix in string,
494 // else NULL
strend(char * str,char * suffix)495 char *strend(char *str, char *suffix)
496 {
497   long a = strlen(str), b = strlen(suffix);
498 
499   if (a>b && !strcmp(str += a-b, suffix)) return str;
500 
501   return 0;
502 }
503 
504 // If *a starts with b, advance *a past it and return 1, else return 0;
strstart(char ** a,char * b)505 int strstart(char **a, char *b)
506 {
507   char *c = *a;
508 
509   while (*b && *c == *b) b++, c++;
510   if (!*b) *a = c;
511 
512   return !*b;
513 }
514 
515 // If *a starts with b, advance *a past it and return 1, else return 0;
strcasestart(char ** a,char * b)516 int strcasestart(char **a, char *b)
517 {
518   int len = strlen(b), i = !strncasecmp(*a, b, len);
519 
520   if (i) *a += len;
521 
522   return i;
523 }
524 
same_file(struct stat * st1,struct stat * st2)525 int same_file(struct stat *st1, struct stat *st2)
526 {
527   return st1->st_ino==st2->st_ino && st1->st_dev==st2->st_dev;
528 }
529 
same_dev_ino(struct stat * st,struct dev_ino * di)530 int same_dev_ino(struct stat *st, struct dev_ino *di)
531 {
532   return st->st_ino==di->ino && st->st_dev==di->dev;
533 }
534 
535 
536 
537 // Return how long the file at fd is, if there's any way to determine it.
fdlength(int fd)538 off_t fdlength(int fd)
539 {
540   struct stat st;
541   off_t base = 0, range = 1, expand = 1, old;
542   unsigned long long size;
543 
544   if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
545 
546   // If the ioctl works for this, return it.
547   if (get_block_device_size(fd, &size)) return size;
548 
549   // If not, do a binary search for the last location we can read.  (Some
550   // block devices don't do BLKGETSIZE right.)  This should probably have
551   // a CONFIG option...
552   old = lseek(fd, 0, SEEK_CUR);
553   do {
554     char temp;
555     off_t pos = base + range / 2;
556 
557     if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
558       off_t delta = (pos + 1) - base;
559 
560       base += delta;
561       if (expand) range = (expand <<= 1) - base;
562       else range -= delta;
563     } else {
564       expand = 0;
565       range = pos - base;
566     }
567   } while (range > 0);
568 
569   lseek(fd, old, SEEK_SET);
570 
571   return base;
572 }
573 
readfd(int fd,char * ibuf,off_t * plen)574 char *readfd(int fd, char *ibuf, off_t *plen)
575 {
576   off_t len, rlen;
577   char *buf, *rbuf;
578 
579   // Unsafe to probe for size with a supplied buffer, don't ever do that.
580   if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
581 
582   // If we dunno the length, probe it. If we can't probe, start with 1 page.
583   if (!*plen) {
584     if ((len = fdlength(fd))>0) *plen = len;
585     else len = 4096;
586   } else len = *plen-1;
587 
588   if (!ibuf) buf = xmalloc(len+1);
589   else buf = ibuf;
590 
591   for (rbuf = buf;;) {
592     rlen = readall(fd, rbuf, len);
593     if (*plen || rlen<len) break;
594 
595     // If reading unknown size, expand buffer by 1.5 each time we fill it up.
596     rlen += rbuf-buf;
597     buf = xrealloc(buf, len = (rlen*3)/2);
598     rbuf = buf+rlen;
599     len -= rlen;
600   }
601   *plen = len = rlen+(rbuf-buf);
602 
603   if (rlen<0) {
604     if (ibuf != buf) free(buf);
605     buf = 0;
606   } else buf[len] = 0;
607 
608   return buf;
609 }
610 
611 // Read contents of file as a single nul-terminated string.
612 // measure file size if !len, allocate buffer if !buf
613 // Existing buffers need len in *plen
614 // Returns amount of data read in *plen
readfileat(int dirfd,char * name,char * ibuf,off_t * plen)615 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
616 {
617   if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0;
618 
619   ibuf = readfd(dirfd, ibuf, plen);
620   close(dirfd);
621 
622   return ibuf;
623 }
624 
readfile(char * name,char * ibuf,off_t len)625 char *readfile(char *name, char *ibuf, off_t len)
626 {
627   return readfileat(AT_FDCWD, name, ibuf, &len);
628 }
629 
630 // Sleep for this many thousandths of a second
msleep(long milliseconds)631 void msleep(long milliseconds)
632 {
633   struct timespec ts;
634 
635   ts.tv_sec = milliseconds/1000;
636   ts.tv_nsec = (milliseconds%1000)*1000000;
637   nanosleep(&ts, &ts);
638 }
639 
640 // Adjust timespec by nanosecond offset
nanomove(struct timespec * ts,long long offset)641 void nanomove(struct timespec *ts, long long offset)
642 {
643   long long nano = ts->tv_nsec + offset, secs = nano/1000000000;
644 
645   ts->tv_sec += secs;
646   nano %= 1000000000;
647   if (nano<0) {
648     ts->tv_sec--;
649     nano += 1000000000;
650   }
651   ts->tv_nsec = nano;
652 }
653 
654 // return difference between two timespecs in nanosecs
nanodiff(struct timespec * old,struct timespec * new)655 long long nanodiff(struct timespec *old, struct timespec *new)
656 {
657   return (new->tv_sec - old->tv_sec)*1000000000LL+(new->tv_nsec - old->tv_nsec);
658 }
659 
660 // return 1<<x of highest bit set
highest_bit(unsigned long l)661 int highest_bit(unsigned long l)
662 {
663   int i;
664 
665   for (i = 0; l; i++) l >>= 1;
666 
667   return i-1;
668 }
669 
670 // Inefficient, but deals with unaligned access
peek_le(void * ptr,unsigned size)671 long long peek_le(void *ptr, unsigned size)
672 {
673   long long ret = 0;
674   char *c = ptr;
675   int i;
676 
677   for (i=0; i<size; i++) ret |= ((long long)c[i])<<(i*8);
678   return ret;
679 }
680 
peek_be(void * ptr,unsigned size)681 long long peek_be(void *ptr, unsigned size)
682 {
683   long long ret = 0;
684   char *c = ptr;
685   int i;
686 
687   for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
688   return ret;
689 }
690 
peek(void * ptr,unsigned size)691 long long peek(void *ptr, unsigned size)
692 {
693   return (IS_BIG_ENDIAN ? peek_be : peek_le)(ptr, size);
694 }
695 
poke_le(void * ptr,long long val,unsigned size)696 void poke_le(void *ptr, long long val, unsigned size)
697 {
698   char *c = ptr;
699 
700   while (size--) {
701     *c++ = val&255;
702     val >>= 8;
703   }
704 }
705 
poke_be(void * ptr,long long val,unsigned size)706 void poke_be(void *ptr, long long val, unsigned size)
707 {
708   char *c = ptr + size;
709 
710   while (size--) {
711     *--c = val&255;
712     val >>=8;
713   }
714 }
715 
poke(void * ptr,long long val,unsigned size)716 void poke(void *ptr, long long val, unsigned size)
717 {
718   (IS_BIG_ENDIAN ? poke_be : poke_le)(ptr, val, size);
719 }
720 
721 // Iterate through an array of files, opening each one and calling a function
722 // on that filehandle and name. The special filename "-" means stdin if
723 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
724 // function() on just stdin/stdout.
725 //
726 // Note: pass O_CLOEXEC to automatically close filehandles when function()
727 // returns, otherwise filehandles must be closed by function().
728 // pass WARN_ONLY to produce warning messages about files it couldn't
729 // open/create, and skip them. Otherwise function is called with fd -1.
loopfiles_rw(char ** argv,int flags,int permissions,void (* function)(int fd,char * name))730 void loopfiles_rw(char **argv, int flags, int permissions,
731   void (*function)(int fd, char *name))
732 {
733   int fd, failok = !(flags&WARN_ONLY), anyway = flags & LOOPFILES_ANYWAY;
734 
735   flags &= ~(WARN_ONLY|LOOPFILES_ANYWAY);
736 
737   // If no arguments, read from stdin.
738   if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
739   else do {
740     // Filename "-" means read from stdin.
741     // Inability to open a file prints a warning, but doesn't exit.
742 
743     if (!strcmp(*argv, "-")) fd = 0;
744     else if (0>(fd = xnotstdio(open(*argv, flags, permissions))) && !failok) {
745       perror_msg_raw(*argv);
746       if (!anyway) continue;
747     }
748     function(fd, *argv);
749     if ((flags & O_CLOEXEC) && fd>0) close(fd);
750   } while (*++argv);
751 }
752 
753 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
loopfiles(char ** argv,void (* function)(int fd,char * name))754 void loopfiles(char **argv, void (*function)(int fd, char *name))
755 {
756   loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
757 }
758 
759 // glue to call do_lines() from loopfiles
760 static void (*do_lines_bridge)(char **pline, long len);
loopfile_lines_bridge(int fd,char * name)761 static void loopfile_lines_bridge(int fd, char *name)
762 {
763   do_lines(fd, '\n', do_lines_bridge);
764 }
765 
loopfiles_lines(char ** argv,void (* function)(char ** pline,long len))766 void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
767 {
768   do_lines_bridge = function;
769   // No O_CLOEXEC because we need to call fclose.
770   loopfiles_rw(argv, O_RDONLY|WARN_ONLY, 0, loopfile_lines_bridge);
771 }
772 
wfchmodat(int fd,char * name,mode_t mode)773 int wfchmodat(int fd, char *name, mode_t mode)
774 {
775   int rc = fchmodat(fd, name, mode, 0);
776 
777   if (rc) {
778     perror_msg("chmod '%s' to %04o", name, mode);
779     toys.exitval=1;
780   }
781   return rc;
782 }
783 
784 static char *tempfile2zap;
tempfile_handler(void)785 static void tempfile_handler(void)
786 {
787   if (1 < (long)tempfile2zap) unlink(tempfile2zap);
788 }
789 
790 // Open a temporary file to copy an existing file into.
copy_tempfile(int fdin,char * name,char ** tempname)791 int copy_tempfile(int fdin, char *name, char **tempname)
792 {
793   struct stat statbuf;
794   int fd = xtempfile(name, tempname), ignored __attribute__((__unused__));
795 
796   // Record tempfile for exit cleanup if interrupted
797   if (!tempfile2zap) sigatexit(tempfile_handler);
798   tempfile2zap = *tempname;
799 
800   // Set permissions of output file.
801   if (!fstat(fdin, &statbuf)) fchmod(fd, statbuf.st_mode);
802 
803   // We chmod before chown, which strips the suid bit. Caller has to explicitly
804   // switch it back on if they want to keep suid.
805 
806   // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
807   // this but it's _supposed_ to fail when we're not root.
808   ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
809 
810   return fd;
811 }
812 
813 // Abort the copy and delete the temporary file.
delete_tempfile(int fdin,int fdout,char ** tempname)814 void delete_tempfile(int fdin, int fdout, char **tempname)
815 {
816   close(fdin);
817   close(fdout);
818   if (*tempname) unlink(*tempname);
819   tempfile2zap = (char *)1;
820   free(*tempname);
821   *tempname = NULL;
822 }
823 
824 // Copy the rest of the data and replace the original with the copy.
replace_tempfile(int fdin,int fdout,char ** tempname)825 void replace_tempfile(int fdin, int fdout, char **tempname)
826 {
827   char *temp = xstrdup(*tempname);
828 
829   temp[strlen(temp)-6]=0;
830   if (fdin != -1) {
831     xsendfile(fdin, fdout);
832     xclose(fdin);
833   }
834   xclose(fdout);
835   xrename(*tempname, temp);
836   tempfile2zap = (char *)1;
837   free(*tempname);
838   free(temp);
839   *tempname = NULL;
840 }
841 
842 // Create a 256 entry CRC32 lookup table.
843 
crc_init(unsigned * crc_table,int little_endian)844 void crc_init(unsigned *crc_table, int little_endian)
845 {
846   unsigned int i;
847 
848   // Init the CRC32 table (big endian)
849   for (i=0; i<256; i++) {
850     unsigned int j, c = little_endian ? i : i<<24;
851     for (j=8; j; j--)
852       if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
853       else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
854     crc_table[i] = c;
855   }
856 }
857 
858 // Init base64 table
859 
base64_init(char * p)860 void base64_init(char *p)
861 {
862   int i;
863 
864   for (i = 'A'; i != ':'; i++) {
865     if (i == 'Z'+1) i = 'a';
866     if (i == 'z'+1) i = '0';
867     *(p++) = i;
868   }
869   *(p++) = '+';
870   *(p++) = '/';
871 }
872 
yesno(int def)873 int yesno(int def)
874 {
875   return fyesno(stdin, def);
876 }
877 
fyesno(FILE * in,int def)878 int fyesno(FILE *in, int def)
879 {
880   char buf;
881 
882   fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
883   fflush(stderr);
884   while (fread(&buf, 1, 1, in)) {
885     int new;
886 
887     // The letter changes the value, the newline (or space) returns it.
888     if (isspace(buf)) break;
889     if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
890   }
891 
892   return def;
893 }
894 
895 // Handler that sets toys.signal, and writes to toys.signalfd if set
generic_signal(int sig)896 void generic_signal(int sig)
897 {
898   if (toys.signalfd) {
899     char c = sig;
900 
901     writeall(toys.signalfd, &c, 1);
902   }
903   toys.signal = sig;
904 }
905 
906 // More or less SIG_DFL that runs our atexit list and can siglongjmp.
exit_signal(int sig)907 void exit_signal(int sig)
908 {
909   sigset_t sigset;
910 
911   if (sig) toys.exitval = sig|128;
912   sigfillset(&sigset);
913   sigprocmask(SIG_BLOCK, &sigset, 0);
914   xexit();
915 }
916 
917 // Install an atexit handler. Also install the same handler on every signal
918 // that defaults to killing the process, calling the handler on the way out.
919 // Calling multiple times adds the handlers to a list, to be called in LIFO
920 // order.
sigatexit(void * handler)921 void sigatexit(void *handler)
922 {
923   struct arg_list *al = 0;
924 
925   xsignal_all_killers(handler ? exit_signal : SIG_DFL);
926   if (handler) {
927     al = xmalloc(sizeof(struct arg_list));
928     al->next = toys.xexit;
929     al->arg = handler;
930   } else llist_traverse(toys.xexit, free);
931   toys.xexit = al;
932 }
933 
934 // Output a nicely formatted table of all the signals.
list_signals(void)935 void list_signals(void)
936 {
937   int i = 1, count = 0;
938   unsigned cols = 80;
939   char *name;
940 
941   terminal_size(&cols, 0);
942   cols /= 16;
943   for (; i<=NSIG; i++) {
944     if ((name = num_to_sig(i))) {
945       printf("%2d) SIG%-9s", i, name);
946       if (++count % cols == 0) putchar('\n');
947     }
948   }
949   putchar('\n');
950 }
951 
952 // premute mode bits based on posix mode strings.
string_to_mode(char * modestr,unsigned mode)953 unsigned string_to_mode(char *modestr, unsigned mode)
954 {
955   char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
956        *s, *str = modestr;
957   unsigned extrabits = mode & ~(07777), bit;
958 
959   // Handle octal mode
960   if (isdigit(*str)) {
961     mode = estrtol(str, &s, 8);
962     if (errno || *s || (mode & ~(07777))) goto barf;
963 
964     return mode | extrabits;
965   }
966 
967   // Gaze into the bin of permission...
968   for (;;) {
969     int i, j, dowho = 0, dohow = 0, dowhat, amask = 0;
970 
971     // Find the who, how, and what stanzas, in that order
972     while (*str && (s = strchr(whos, *str))) {
973       dowho |= 1<<(s-whos);
974       str++;
975     }
976     // If who isn't specified, like "a" but honoring umask.
977     if (!dowho) {
978       dowho = 8;
979       umask(amask = umask(0));
980     }
981 
982     // Repeated "hows" are allowed; something like "a=r+w+s" is valid.
983     for (;;) {
984       if (-1 == stridx(hows, dohow = *str)) goto barf;
985       dowhat = 0;
986       while (*++str && (s = strchr(whats, *str))) dowhat |= 1<<(s-whats);
987 
988       // Convert X to x for directory or if already executable somewhere
989       if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
990 
991       // Copy mode from another category?
992       if (!dowhat && -1 != (i = stridx(whys, *str))) {
993         dowhat = (mode>>(3*i))&7;
994         str++;
995       }
996 
997       // Loop through what=xwrs and who=ogu to apply bits to the mode.
998       for (i=0; i<4; i++) {
999         for (j=0; j<3; j++) {
1000           int where = 1<<((3*i)+j);
1001 
1002           if (amask & where) continue;
1003 
1004           // Figure out new value at this location
1005           bit = 0;
1006           if (i == 3) {
1007             // suid and sticky
1008             if (!j) bit = dowhat&16; // o+s = t but a+s doesn't set t, hence t
1009             else if ((dowhat&8) && (dowho&(8|(1<<j)))) bit++;
1010           } else {
1011             if (!(dowho&(8|(1<<i)))) continue;
1012             else if (dowhat&(1<<j)) bit++;
1013           }
1014 
1015           // When selection active, modify bit
1016           if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
1017           if (bit && dohow != '-') mode |= where;
1018         }
1019       }
1020       if (!*str) return mode|extrabits;
1021       if (*str == ',') {
1022         str++;
1023         break;
1024       }
1025     }
1026   }
1027 
1028 barf:
1029   error_exit("bad mode '%s'", modestr);
1030 }
1031 
1032 // Format access mode into a drwxrwxrwx string
mode_to_string(unsigned mode,char * buf)1033 void mode_to_string(unsigned mode, char *buf)
1034 {
1035   char c, d;
1036   int i, bit;
1037 
1038   buf[10]=0;
1039   for (i=0; i<9; i++) {
1040     bit = mode & (1<<i);
1041     c = i%3;
1042     if (!c && (mode & (1<<((d=i/3)+9)))) {
1043       c = "tss"[d];
1044       if (!bit) c &= ~0x20;
1045     } else c = bit ? "xwr"[c] : '-';
1046     buf[9-i] = c;
1047   }
1048 
1049   if (S_ISDIR(mode)) c = 'd';
1050   else if (S_ISBLK(mode)) c = 'b';
1051   else if (S_ISCHR(mode)) c = 'c';
1052   else if (S_ISLNK(mode)) c = 'l';
1053   else if (S_ISFIFO(mode)) c = 'p';
1054   else if (S_ISSOCK(mode)) c = 's';
1055   else c = '-';
1056   *buf = c;
1057 }
1058 
1059 // basename() can modify its argument or return a pointer to a constant string
1060 // This just gives after the last '/' or the whole stirng if no /
getbasename(char * name)1061 char *getbasename(char *name)
1062 {
1063   char *s = strrchr(name, '/');
1064 
1065   if (s) return s+1;
1066 
1067   return name;
1068 }
1069 
1070 // Return pointer to xabspath(file) if file is under dir, else 0
fileunderdir(char * file,char * dir)1071 char *fileunderdir(char *file, char *dir)
1072 {
1073   char *s1 = xabspath(dir, ABS_FILE), *s2 = xabspath(file, 0), *ss = s2;
1074   int rc = s1 && s2 && strstart(&ss, s1) && (!s1[1] || s2[strlen(s1)] == '/');
1075 
1076   free(s1);
1077   if (!rc) free(s2);
1078 
1079   return rc ? s2 : 0;
1080 }
1081 
mepcpy(void * to,void * from,unsigned long len)1082 void *mepcpy(void *to, void *from, unsigned long len)
1083 {
1084   memcpy(to, from, len);
1085 
1086   return ((char *)to)+len;
1087 }
1088 
1089 // return (malloced) relative path to get between two normalized absolute paths
1090 // normalized: no duplicate / or trailing / or .. or . (symlinks optional)
relative_path(char * from,char * to,int abs)1091 char *relative_path(char *from, char *to, int abs)
1092 {
1093   char *s, *ret = 0;
1094   int i, j, k;
1095 
1096   if (abs) {
1097     if (!(from = xabspath(from, 0))) return 0;
1098     if (!(to = xabspath(to, 0))) goto error;
1099   }
1100 
1101   for (i = j = 0;; i++) {
1102     if (!from[i] || !to[i]) {
1103       if (from[i]=='/' || to[i]=='/' || from[i]==to[i]) j = i;
1104       break;
1105     }
1106     if (from[i] != to[i]) break;
1107     if (from[i] == '/') j = i;
1108   }
1109 
1110   // count remaining destination directories
1111   for (i = j, k = 0; from[i]; i++) if (from[i] == '/') k++;
1112   if (!k) {
1113     if (to[j]=='/') j++;
1114     ret = xstrdup(to[j] ? to+j : ".");
1115   } else {
1116     s = ret = xmprintf("%*c%s", 3*k-!!k, ' ', to+j);
1117     for (i = 0; i<k; i++) s = mepcpy(s, "/.."+!i, 3-!i);
1118   }
1119 
1120 error:
1121   if (abs) {
1122     free(from);
1123     free(to);
1124   }
1125 
1126   return ret;
1127 }
1128 
1129 // 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),int scripts)1130 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name),
1131     int scripts)
1132 {
1133   DIR *dp;
1134   struct dirent *entry;
1135 
1136   if (!(dp = opendir("/proc"))) perror_exit("no /proc");
1137 
1138   while ((entry = readdir(dp))) {
1139     unsigned u = atoi(entry->d_name);
1140     char *cmd = 0, *comm = 0, **cur;
1141     off_t len;
1142 
1143     if (!u) continue;
1144 
1145     // Comm is original name of executable (argv[0] could be #! interpreter)
1146     // but it's limited to 15 characters
1147     if (scripts) {
1148       sprintf(libbuf, "/proc/%u/comm", u);
1149       len = sizeof(libbuf);
1150       if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
1151         continue;
1152       if (libbuf[len-1] == '\n') libbuf[--len] = 0;
1153     }
1154 
1155     for (cur = names; *cur; cur++) {
1156       struct stat st1, st2;
1157       char *bb = getbasename(*cur);
1158       off_t len = strlen(bb);
1159 
1160       // Fast path: only matching a filename (no path) that fits in comm.
1161       // `len` must be 14 or less because with a full 15 bytes we don't
1162       // know whether the name fit or was truncated.
1163       if (scripts && len<=14 && bb==*cur && !strcmp(comm, bb)) goto match;
1164 
1165       // If we have a path to existing file only match if same inode
1166       if (bb!=*cur && !stat(*cur, &st1)) {
1167         char buf[32];
1168 
1169         sprintf(buf, "/proc/%u/exe", u);
1170         if (stat(buf, &st2) || !same_file(&st1, &st2)) continue;
1171         goto match;
1172       }
1173 
1174       // Nope, gotta read command line to confirm
1175       if (!cmd) {
1176         sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1177         len = sizeof(libbuf)-17;
1178         if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1179         // readfile only guarantees one null terminator and we need two
1180         // (yes the kernel should do this for us, don't care)
1181         cmd[len] = 0;
1182       }
1183       if (!strcmp(bb, getbasename(cmd))) goto match;
1184       if (scripts && !strcmp(bb, getbasename(cmd+strlen(cmd)+1))) goto match;
1185       continue;
1186 match:
1187       if (callback(u, *cur)) goto done;
1188     }
1189   }
1190 done:
1191   closedir(dp);
1192 }
1193 
1194 // display first "dgt" many digits of number plus unit (kilo-exabytes)
human_readable_long(char * buf,unsigned long long num,int dgt,int unit,int style)1195 int human_readable_long(char *buf, unsigned long long num, int dgt, int unit,
1196   int style)
1197 {
1198   unsigned long long snap = 0;
1199   int len, divisor = (style&HR_1000) ? 1000 : 1024;
1200 
1201   // Divide rounding up until we have 3 or fewer digits. Since the part we
1202   // print is decimal, the test is 999 even when we divide by 1024.
1203   // The largest unit we can detect is 1<<64 = 18 Exabytes, but we added
1204   // Zettabyte and Yottabyte in case "unit" starts above zero.
1205   for (;;unit++) {
1206     if ((len = snprintf(0, 0, "%llu", num))<=dgt) break;
1207     num = ((snap = num)+(divisor/2))/divisor;
1208   }
1209   if (CFG_TOYBOX_DEBUG && unit>8) return sprintf(buf, "%.*s", dgt, "TILT");
1210 
1211   len = sprintf(buf, "%llu", num);
1212   if (!(style & HR_NODOT) && unit && len == 1) {
1213     // Redo rounding for 1.2M case, this works with and without HR_1000.
1214     num = snap/divisor;
1215     snap -= num*divisor;
1216     snap = ((snap*100)+50)/divisor;
1217     snap /= 10;
1218     len = sprintf(buf, "%llu.%llu", num, snap);
1219   }
1220   if (style & HR_SPACE) buf[len++] = ' ';
1221   if (unit) {
1222     unit = " kMGTPEZY"[unit];
1223 
1224     if (!(style&HR_1000)) unit = toupper(unit);
1225     buf[len++] = unit;
1226   } else if (style & HR_B) buf[len++] = 'B';
1227   buf[len] = 0;
1228 
1229   return len;
1230 }
1231 
1232 // Give 3 digit estimate + units ala 999M or 1.7T
human_readable(char * buf,unsigned long long num,int style)1233 int human_readable(char *buf, unsigned long long num, int style)
1234 {
1235   return human_readable_long(buf, num, 3, 0, style);
1236 }
1237 
1238 // The qsort man page says you can use alphasort, the posix committee
1239 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1240 // So just do our own. (The const is entirely to humor the stupid compiler.)
qstrcmp(const void * a,const void * b)1241 int qstrcmp(const void *a, const void *b)
1242 {
1243   return strcmp(*(char **)a, *(char **)b);
1244 }
1245 
1246 // See https://tools.ietf.org/html/rfc4122, specifically section 4.4
1247 // "Algorithms for Creating a UUID from Truly Random or Pseudo-Random
1248 // Numbers".
create_uuid(char * uuid)1249 void create_uuid(char *uuid)
1250 {
1251   // "Set all the ... bits to randomly (or pseudo-randomly) chosen values".
1252   xgetrandom(uuid, 16);
1253 
1254   // "Set the four most significant bits ... of the time_hi_and_version
1255   // field to the 4-bit version number [4]".
1256   uuid[6] = (uuid[6] & 0x0F) | 0x40;
1257   // "Set the two most significant bits (bits 6 and 7) of
1258   // clock_seq_hi_and_reserved to zero and one, respectively".
1259   uuid[8] = (uuid[8] & 0x3F) | 0x80;
1260 }
1261 
show_uuid(char * uuid)1262 char *show_uuid(char *uuid)
1263 {
1264   char *out = libbuf;
1265   int i;
1266 
1267   for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1268   *out = 0;
1269 
1270   return libbuf;
1271 }
1272 
1273 // Returns pointer to letter at end, 0 if none. *start = initial %
next_printf(char * s,char ** start)1274 char *next_printf(char *s, char **start)
1275 {
1276   for (; *s; s++) {
1277     if (*s != '%') continue;
1278     if (*++s == '%') continue;
1279     if (start) *start = s-1;
1280     while (0 <= stridx("0'#-+ ", *s)) s++;
1281     while (isdigit(*s)) s++;
1282     if (*s == '.') s++;
1283     while (isdigit(*s)) s++;
1284 
1285     return s;
1286   }
1287 
1288   return 0;
1289 }
1290 
1291 // Return cached passwd entries.
bufgetpwnamuid(char * name,uid_t uid)1292 struct passwd *bufgetpwnamuid(char *name, uid_t uid)
1293 {
1294   struct pwuidbuf_list {
1295     struct pwuidbuf_list *next;
1296     struct passwd pw;
1297   } *list = 0;
1298   struct passwd *temp;
1299   static struct pwuidbuf_list *pwuidbuf;
1300   unsigned size = 256;
1301 
1302   // If we already have this one, return it.
1303   for (list = pwuidbuf; list; list = list->next)
1304     if (name ? !strcmp(name, list->pw.pw_name) : list->pw.pw_uid==uid)
1305       return &(list->pw);
1306 
1307   for (;;) {
1308     list = xrealloc(list, size *= 2);
1309     if (name) errno = getpwnam_r(name, &list->pw, sizeof(*list)+(char *)list,
1310       size-sizeof(*list), &temp);
1311     else errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1312       size-sizeof(*list), &temp);
1313     if (errno != ERANGE) break;
1314   }
1315 
1316   if (!temp) {
1317     free(list);
1318 
1319     return 0;
1320   }
1321   list->next = pwuidbuf;
1322   pwuidbuf = list;
1323 
1324   return &list->pw;
1325 }
1326 
bufgetpwuid(uid_t uid)1327 struct passwd *bufgetpwuid(uid_t uid)
1328 {
1329   return bufgetpwnamuid(0, uid);
1330 }
1331 
1332 // Return cached group entries.
bufgetgrnamgid(char * name,gid_t gid)1333 struct group *bufgetgrnamgid(char *name, gid_t gid)
1334 {
1335   struct grgidbuf_list {
1336     struct grgidbuf_list *next;
1337     struct group gr;
1338   } *list = 0;
1339   struct group *temp;
1340   static struct grgidbuf_list *grgidbuf;
1341   unsigned size = 256;
1342 
1343   for (list = grgidbuf; list; list = list->next)
1344     if (name ? !strcmp(name, list->gr.gr_name) : list->gr.gr_gid==gid)
1345       return &(list->gr);
1346 
1347   for (;;) {
1348     list = xrealloc(list, size *= 2);
1349     if (name) errno = getgrnam_r(name, &list->gr, sizeof(*list)+(char *)list,
1350       size-sizeof(*list), &temp);
1351     else errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1352       size-sizeof(*list), &temp);
1353     if (errno != ERANGE) break;
1354   }
1355   if (!temp) {
1356     free(list);
1357 
1358     return 0;
1359   }
1360   list->next = grgidbuf;
1361   grgidbuf = list;
1362 
1363   return &list->gr;
1364 }
1365 
bufgetgrgid(gid_t gid)1366 struct group *bufgetgrgid(gid_t gid)
1367 {
1368   return bufgetgrnamgid(0, gid);
1369 }
1370 
1371 
1372 // Always null terminates, returns 0 for failure, len for success
readlinkat0(int dirfd,char * path,char * buf,int len)1373 int readlinkat0(int dirfd, char *path, char *buf, int len)
1374 {
1375   if (!len) return 0;
1376 
1377   len = readlinkat(dirfd, path, buf, len-1);
1378   if (len<0) len = 0;
1379   buf[len] = 0;
1380 
1381   return len;
1382 }
1383 
readlink0(char * path,char * buf,int len)1384 int readlink0(char *path, char *buf, int len)
1385 {
1386   return readlinkat0(AT_FDCWD, path, buf, len);
1387 }
1388 
1389 // Do regex matching with len argument to handle embedded NUL bytes in string
regexec0(regex_t * preg,char * string,long len,int nmatch,regmatch_t * pmatch,int eflags)1390 int regexec0(regex_t *preg, char *string, long len, int nmatch,
1391   regmatch_t *pmatch, int eflags)
1392 {
1393   regmatch_t backup;
1394 
1395   if (!nmatch) pmatch = &backup;
1396   pmatch->rm_so = 0;
1397   pmatch->rm_eo = len;
1398   return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
1399 }
1400 
1401 // Return user name or string representation of number, returned buffer
1402 // lasts until next call.
getusername(uid_t uid)1403 char *getusername(uid_t uid)
1404 {
1405   struct passwd *pw = bufgetpwuid(uid);
1406   static char unum[12];
1407 
1408   sprintf(unum, "%u", (unsigned)uid);
1409   return pw ? pw->pw_name : unum;
1410 }
1411 
1412 // Return group name or string representation of number, returned buffer
1413 // lasts until next call.
getgroupname(gid_t gid)1414 char *getgroupname(gid_t gid)
1415 {
1416   struct group *gr = bufgetgrgid(gid);
1417   static char gnum[12];
1418 
1419   sprintf(gnum, "%u", (unsigned)gid);
1420   return gr ? gr->gr_name : gnum;
1421 }
1422 
1423 // Iterate over lines in file, calling function. Function can write 0 to
1424 // the line pointer if they want to keep it, or 1 to terminate processing,
1425 // otherwise line is freed. Passed file descriptor is closed at the end.
1426 // At EOF calls function(0, 0)
do_lines(int fd,char delim,void (* call)(char ** pline,long len))1427 void do_lines(int fd, char delim, void (*call)(char **pline, long len))
1428 {
1429   FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1430 
1431   for (;;) {
1432     char *line = 0;
1433     ssize_t len;
1434 
1435     len = getdelim(&line, (void *)&len, delim, fp);
1436     if (len > 0) {
1437       call(&line, len);
1438       if (line == (void *)1) break;
1439       free(line);
1440     } else break;
1441   }
1442   call(0, 0);
1443 
1444   if (fd) fclose(fp);
1445 }
1446 
1447 // Return unix time in milliseconds
millitime(void)1448 long long millitime(void)
1449 {
1450   struct timespec ts;
1451 
1452   clock_gettime(CLOCK_MONOTONIC, &ts);
1453   return ts.tv_sec*1000+ts.tv_nsec/1000000;
1454 }
1455 
1456 // Formats `ts` in ISO format ("2018-06-28 15:08:58.846386216 -0700").
format_iso_time(char * buf,size_t len,struct timespec * ts)1457 char *format_iso_time(char *buf, size_t len, struct timespec *ts)
1458 {
1459   char *s = buf;
1460 
1461   s += strftime(s, len, "%F %T", localtime(&(ts->tv_sec)));
1462   s += sprintf(s, ".%09ld ", ts->tv_nsec);
1463   s += strftime(s, len-strlen(buf), "%z", localtime(&(ts->tv_sec)));
1464 
1465   return buf;
1466 }
1467 
1468 // Syslog with the openlog/closelog, autodetecting daemon status via no tty
1469 
loggit(int priority,char * format,...)1470 void loggit(int priority, char *format, ...)
1471 {
1472   int i, facility = LOG_DAEMON;
1473   va_list va;
1474 
1475   for (i = 0; i<3; i++) if (isatty(i)) facility = LOG_AUTH;
1476   openlog(toys.which->name, LOG_PID, facility);
1477   va_start(va, format);
1478   vsyslog(priority, format, va);
1479   va_end(va);
1480   closelog();
1481 }
1482 
1483 // Calculate tar packet checksum, with cksum field treated as 8 spaces
tar_cksum(void * data)1484 unsigned tar_cksum(void *data)
1485 {
1486   unsigned i, cksum = 8*' ';
1487 
1488   for (i = 0; i<500; i += (i==147) ? 9 : 1) cksum += ((char *)data)[i];
1489 
1490   return cksum;
1491 }
1492 
1493 // is this a valid tar header?
is_tar_header(void * pkt)1494 int is_tar_header(void *pkt)
1495 {
1496   char *p = pkt;
1497   int i = 0;
1498 
1499   if (p[257] && smemcmp("ustar", p+257, 5)) return 0;
1500   if (p[148] != '0' && p[148] != ' ') return 0;
1501   sscanf(p+148, "%8o", &i);
1502 
1503   return i && tar_cksum(pkt) == i;
1504 }
1505 
1506 // Remove octal escapes from string (common in kernel exports)
octal_deslash(char * s)1507 void octal_deslash(char *s)
1508 {
1509   char *o = s;
1510 
1511   while (*s) {
1512     if (*s == '\\') {
1513       int i, oct = 0;
1514 
1515       for (i = 1; i < 4; i++) {
1516         if (!isdigit(s[i])) break;
1517         oct = (oct<<3)+s[i]-'0';
1518       }
1519       if (i == 4) {
1520         *o++ = oct;
1521         s += i;
1522         continue;
1523       }
1524     }
1525     *o++ = *s++;
1526   }
1527 
1528   *o = 0;
1529 }
1530 
1531 // ASAN flips out about memcmp("a", "abc", 4) but the result is well-defined.
1532 // This one's guaranteed to stop at len _or_ the first difference.
smemcmp(char * one,char * two,unsigned long len)1533 int smemcmp(char *one, char *two, unsigned long len)
1534 {
1535   int ii = 0;
1536 
1537   // NULL sorts after anything else
1538   if (one == two) return 0;
1539   if (!one) return 1;
1540   if (!two) return -1;
1541 
1542   while (len--) if ((ii = *one++ - *two++)) break;
1543 
1544   return ii;
1545 }
1546 
1547