xref: /aosp_15_r20/external/toybox/lib/lib.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* lib.c - various reusable stuff.
2  *
3  * Copyright 2006 Rob Landley <[email protected]>
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 
525 // return length of match found at this point (try is null terminated array)
anystart(char * s,char ** try)526 int anystart(char *s, char **try)
527 {
528   char *ss = s;
529 
530   while (*try) if (strstart(&s, *try++)) return s-ss;
531 
532   return 0;
533 }
534 
same_file(struct stat * st1,struct stat * st2)535 int same_file(struct stat *st1, struct stat *st2)
536 {
537   return st1->st_ino==st2->st_ino && st1->st_dev==st2->st_dev;
538 }
539 
same_dev_ino(struct stat * st,struct dev_ino * di)540 int same_dev_ino(struct stat *st, struct dev_ino *di)
541 {
542   return st->st_ino==di->ino && st->st_dev==di->dev;
543 }
544 
545 
546 
547 // Return how long the file at fd is, if there's any way to determine it.
fdlength(int fd)548 off_t fdlength(int fd)
549 {
550   struct stat st;
551   off_t base = 0, range = 1, expand = 1, old;
552   unsigned long long size;
553 
554   if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
555 
556   // If the ioctl works for this, return it.
557   if (get_block_device_size(fd, &size)) return size;
558 
559   // If not, do a binary search for the last location we can read.  (Some
560   // block devices don't do BLKGETSIZE right.)  This should probably have
561   // a CONFIG option...
562   old = lseek(fd, 0, SEEK_CUR);
563   do {
564     char temp;
565     off_t pos = base + range / 2;
566 
567     if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
568       off_t delta = (pos + 1) - base;
569 
570       base += delta;
571       if (expand) range = (expand <<= 1) - base;
572       else range -= delta;
573     } else {
574       expand = 0;
575       range = pos - base;
576     }
577   } while (range > 0);
578 
579   lseek(fd, old, SEEK_SET);
580 
581   return base;
582 }
583 
readfd(int fd,char * ibuf,off_t * plen)584 char *readfd(int fd, char *ibuf, off_t *plen)
585 {
586   off_t len, rlen;
587   char *buf, *rbuf;
588 
589   // Unsafe to probe for size with a supplied buffer, don't ever do that.
590   if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
591 
592   // If we dunno the length, probe it. If we can't probe, start with 1 page.
593   if (!*plen) {
594     if ((len = fdlength(fd))>0) *plen = len;
595     else len = 4096;
596   } else len = *plen-1;
597 
598   if (!ibuf) buf = xmalloc(len+1);
599   else buf = ibuf;
600 
601   for (rbuf = buf;;) {
602     rlen = readall(fd, rbuf, len);
603     if (*plen || rlen<len) break;
604 
605     // If reading unknown size, expand buffer by 1.5 each time we fill it up.
606     rlen += rbuf-buf;
607     buf = xrealloc(buf, len = (rlen*3)/2);
608     rbuf = buf+rlen;
609     len -= rlen;
610   }
611   *plen = len = rlen+(rbuf-buf);
612 
613   if (rlen<0) {
614     if (ibuf != buf) free(buf);
615     buf = 0;
616   } else buf[len] = 0;
617 
618   return buf;
619 }
620 
621 // Read contents of file as a single nul-terminated string.
622 // measure file size if !len, allocate buffer if !buf
623 // Existing buffers need len in *plen
624 // Returns amount of data read in *plen
readfileat(int dirfd,char * name,char * ibuf,off_t * plen)625 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
626 {
627   if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0;
628 
629   ibuf = readfd(dirfd, ibuf, plen);
630   close(dirfd);
631 
632   return ibuf;
633 }
634 
readfile(char * name,char * ibuf,off_t len)635 char *readfile(char *name, char *ibuf, off_t len)
636 {
637   return readfileat(AT_FDCWD, name, ibuf, &len);
638 }
639 
640 // Sleep for this many thousandths of a second
msleep(long milliseconds)641 void msleep(long milliseconds)
642 {
643   struct timespec ts;
644 
645   ts.tv_sec = milliseconds/1000;
646   ts.tv_nsec = (milliseconds%1000)*1000000;
647   nanosleep(&ts, &ts);
648 }
649 
650 // Adjust timespec by nanosecond offset
nanomove(struct timespec * ts,long long offset)651 void nanomove(struct timespec *ts, long long offset)
652 {
653   long long nano = ts->tv_nsec + offset, secs = nano/1000000000;
654 
655   ts->tv_sec += secs;
656   nano %= 1000000000;
657   if (nano<0) {
658     ts->tv_sec--;
659     nano += 1000000000;
660   }
661   ts->tv_nsec = nano;
662 }
663 
664 // return difference between two timespecs in nanosecs
nanodiff(struct timespec * old,struct timespec * new)665 long long nanodiff(struct timespec *old, struct timespec *new)
666 {
667   return (new->tv_sec - old->tv_sec)*1000000000LL+(new->tv_nsec - old->tv_nsec);
668 }
669 
670 // return 1<<x of highest bit set
highest_bit(unsigned long l)671 int highest_bit(unsigned long l)
672 {
673   int i;
674 
675   for (i = 0; l; i++) l >>= 1;
676 
677   return i-1;
678 }
679 
680 // Inefficient, but deals with unaligned access
peek_le(void * ptr,unsigned size)681 long long peek_le(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 |= ((long long)c[i])<<(i*8);
688   return ret;
689 }
690 
peek_be(void * ptr,unsigned size)691 long long peek_be(void *ptr, unsigned size)
692 {
693   long long ret = 0;
694   char *c = ptr;
695   int i;
696 
697   for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
698   return ret;
699 }
700 
peek(void * ptr,unsigned size)701 long long peek(void *ptr, unsigned size)
702 {
703   return (IS_BIG_ENDIAN ? peek_be : peek_le)(ptr, size);
704 }
705 
poke_le(void * ptr,long long val,unsigned size)706 void poke_le(void *ptr, long long val, unsigned size)
707 {
708   char *c = ptr;
709 
710   while (size--) {
711     *c++ = val&255;
712     val >>= 8;
713   }
714 }
715 
poke_be(void * ptr,long long val,unsigned size)716 void poke_be(void *ptr, long long val, unsigned size)
717 {
718   char *c = ptr + size;
719 
720   while (size--) {
721     *--c = val&255;
722     val >>=8;
723   }
724 }
725 
poke(void * ptr,long long val,unsigned size)726 void poke(void *ptr, long long val, unsigned size)
727 {
728   (IS_BIG_ENDIAN ? poke_be : poke_le)(ptr, val, size);
729 }
730 
731 // Iterate through an array of files, opening each one and calling a function
732 // on that filehandle and name. The special filename "-" means stdin if
733 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
734 // function() on just stdin/stdout.
735 //
736 // Note: pass O_CLOEXEC to automatically close filehandles when function()
737 // returns, otherwise filehandles must be closed by function().
738 // pass WARN_ONLY to produce warning messages about files it couldn't
739 // 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))740 void loopfiles_rw(char **argv, int flags, int permissions,
741   void (*function)(int fd, char *name))
742 {
743   int fd, failok = !(flags&WARN_ONLY), anyway = flags & LOOPFILES_ANYWAY;
744 
745   flags &= ~(WARN_ONLY|LOOPFILES_ANYWAY);
746 
747   // If no arguments, read from stdin.
748   if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
749   else do {
750     // Filename "-" means read from stdin.
751     // Inability to open a file prints a warning, but doesn't exit.
752 
753     if (!strcmp(*argv, "-")) fd = 0;
754     else if (0>(fd = xnotstdio(open(*argv, flags, permissions))) && !failok) {
755       perror_msg_raw(*argv);
756       if (!anyway) continue;
757     }
758     function(fd, *argv);
759     if ((flags & O_CLOEXEC) && fd>0) close(fd);
760   } while (*++argv);
761 }
762 
763 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
loopfiles(char ** argv,void (* function)(int fd,char * name))764 void loopfiles(char **argv, void (*function)(int fd, char *name))
765 {
766   loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
767 }
768 
769 // glue to call do_lines() from loopfiles
770 static void (*do_lines_bridge)(char **pline, long len);
loopfile_lines_bridge(int fd,char * name)771 static void loopfile_lines_bridge(int fd, char *name)
772 {
773   do_lines(fd, '\n', do_lines_bridge);
774 }
775 
loopfiles_lines(char ** argv,void (* function)(char ** pline,long len))776 void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
777 {
778   do_lines_bridge = function;
779   // No O_CLOEXEC because we need to call fclose.
780   loopfiles_rw(argv, O_RDONLY|WARN_ONLY, 0, loopfile_lines_bridge);
781 }
782 
wfchmodat(int fd,char * name,mode_t mode)783 int wfchmodat(int fd, char *name, mode_t mode)
784 {
785   int rc = fchmodat(fd, name, mode, 0);
786 
787   if (rc) {
788     perror_msg("chmod '%s' to %04o", name, mode);
789     toys.exitval=1;
790   }
791   return rc;
792 }
793 
794 static char *tempfile2zap;
tempfile_handler(void)795 static void tempfile_handler(void)
796 {
797   if (1 < (long)tempfile2zap) unlink(tempfile2zap);
798 }
799 
800 // Open a temporary file to copy an existing file into.
copy_tempfile(int fdin,char * name,char ** tempname)801 int copy_tempfile(int fdin, char *name, char **tempname)
802 {
803   struct stat statbuf;
804   int fd = xtempfile(name, tempname), ignored __attribute__((__unused__));
805 
806   // Record tempfile for exit cleanup if interrupted
807   if (!tempfile2zap) sigatexit(tempfile_handler);
808   tempfile2zap = *tempname;
809 
810   // Set permissions of output file.
811   if (!fstat(fdin, &statbuf)) fchmod(fd, statbuf.st_mode);
812 
813   // We chmod before chown, which strips the suid bit. Caller has to explicitly
814   // switch it back on if they want to keep suid.
815 
816   // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
817   // this but it's _supposed_ to fail when we're not root.
818   ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
819 
820   return fd;
821 }
822 
823 // Abort the copy and delete the temporary file.
delete_tempfile(int fdin,int fdout,char ** tempname)824 void delete_tempfile(int fdin, int fdout, char **tempname)
825 {
826   close(fdin);
827   close(fdout);
828   if (*tempname) unlink(*tempname);
829   tempfile2zap = (char *)1;
830   free(*tempname);
831   *tempname = NULL;
832 }
833 
834 // Copy the rest of the data and replace the original with the copy.
replace_tempfile(int fdin,int fdout,char ** tempname)835 void replace_tempfile(int fdin, int fdout, char **tempname)
836 {
837   char *temp = xstrdup(*tempname);
838 
839   temp[strlen(temp)-6]=0;
840   if (fdin != -1) {
841     xsendfile(fdin, fdout);
842     xclose(fdin);
843   }
844   xclose(fdout);
845   xrename(*tempname, temp);
846   tempfile2zap = (char *)1;
847   free(*tempname);
848   free(temp);
849   *tempname = NULL;
850 }
851 
852 // Create a 256 entry CRC32 lookup table.
853 
crc_init(unsigned * crc_table,int little_endian)854 void crc_init(unsigned *crc_table, int little_endian)
855 {
856   unsigned int i;
857 
858   // Init the CRC32 table (big endian)
859   for (i=0; i<256; i++) {
860     unsigned int j, c = little_endian ? i : i<<24;
861     for (j=8; j; j--)
862       if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
863       else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
864     crc_table[i] = c;
865   }
866 }
867 
868 // Init base64 table
869 
base64_init(char * p)870 void base64_init(char *p)
871 {
872   int i;
873 
874   for (i = 'A'; i != ':'; i++) {
875     if (i == 'Z'+1) i = 'a';
876     if (i == 'z'+1) i = '0';
877     *(p++) = i;
878   }
879   *(p++) = '+';
880   *(p++) = '/';
881 }
882 
yesno(int def)883 int yesno(int def)
884 {
885   return fyesno(stdin, def);
886 }
887 
fyesno(FILE * in,int def)888 int fyesno(FILE *in, int def)
889 {
890   char buf;
891 
892   fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
893   fflush(stderr);
894   while (fread(&buf, 1, 1, in)) {
895     int new;
896 
897     // The letter changes the value, the newline (or space) returns it.
898     if (isspace(buf)) break;
899     if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
900   }
901 
902   return def;
903 }
904 
905 // Handler that sets toys.signal, and writes to toys.signalfd if set
generic_signal(int sig)906 void generic_signal(int sig)
907 {
908   if (toys.signalfd) {
909     char c = sig;
910 
911     writeall(toys.signalfd, &c, 1);
912   }
913   toys.signal = sig;
914 }
915 
916 // More or less SIG_DFL that runs our atexit list and can siglongjmp.
exit_signal(int sig)917 void exit_signal(int sig)
918 {
919   sigset_t sigset;
920 
921   if (sig) toys.exitval = sig|128;
922   sigfillset(&sigset);
923   sigprocmask(SIG_BLOCK, &sigset, 0);
924   xexit();
925 }
926 
927 // Install an atexit handler. Also install the same handler on every signal
928 // that defaults to killing the process, calling the handler on the way out.
929 // Calling multiple times adds the handlers to a list, to be called in LIFO
930 // order.
sigatexit(void * handler)931 void sigatexit(void *handler)
932 {
933   struct arg_list *al = 0;
934 
935   xsignal_all_killers(handler ? exit_signal : SIG_DFL);
936   if (handler) {
937     al = xmalloc(sizeof(struct arg_list));
938     al->next = toys.xexit;
939     al->arg = handler;
940   } else llist_traverse(toys.xexit, free);
941   toys.xexit = al;
942 }
943 
944 // Output a nicely formatted table of all the signals.
list_signals(void)945 void list_signals(void)
946 {
947   int i = 1, count = 0;
948   unsigned cols = 80;
949   char *name;
950 
951   terminal_size(&cols, 0);
952   cols /= 16;
953   for (; i<=NSIG; i++) {
954     if ((name = num_to_sig(i))) {
955       printf("%2d) SIG%-9s", i, name);
956       if (++count % cols == 0) putchar('\n');
957     }
958   }
959   putchar('\n');
960 }
961 
962 // premute mode bits based on posix mode strings.
string_to_mode(char * modestr,unsigned mode)963 unsigned string_to_mode(char *modestr, unsigned mode)
964 {
965   char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
966        *s, *str = modestr;
967   unsigned extrabits = mode & ~(07777), bit;
968 
969   // Handle octal mode
970   if (isdigit(*str)) {
971     mode = estrtol(str, &s, 8);
972     if (errno || *s || (mode & ~(07777))) goto barf;
973 
974     return mode | extrabits;
975   }
976 
977   // Gaze into the bin of permission...
978   for (;;) {
979     int i, j, dowho = 0, dohow = 0, dowhat, amask = 0;
980 
981     // Find the who, how, and what stanzas, in that order
982     while (*str && (s = strchr(whos, *str))) {
983       dowho |= 1<<(s-whos);
984       str++;
985     }
986     // If who isn't specified, like "a" but honoring umask.
987     if (!dowho) {
988       dowho = 8;
989       umask(amask = umask(0));
990     }
991 
992     // Repeated "hows" are allowed; something like "a=r+w+s" is valid.
993     for (;;) {
994       if (-1 == stridx(hows, dohow = *str)) goto barf;
995       dowhat = 0;
996       while (*++str && (s = strchr(whats, *str))) dowhat |= 1<<(s-whats);
997 
998       // Convert X to x for directory or if already executable somewhere
999       if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
1000 
1001       // Copy mode from another category?
1002       if (!dowhat && -1 != (i = stridx(whys, *str))) {
1003         dowhat = (mode>>(3*i))&7;
1004         str++;
1005       }
1006 
1007       // Loop through what=xwrs and who=ogu to apply bits to the mode.
1008       for (i=0; i<4; i++) {
1009         for (j=0; j<3; j++) {
1010           int where = 1<<((3*i)+j);
1011 
1012           if (amask & where) continue;
1013 
1014           // Figure out new value at this location
1015           bit = 0;
1016           if (i == 3) {
1017             // suid and sticky
1018             if (!j) bit = dowhat&16; // o+s = t but a+s doesn't set t, hence t
1019             else if ((dowhat&8) && (dowho&(8|(1<<j)))) bit++;
1020           } else {
1021             if (!(dowho&(8|(1<<i)))) continue;
1022             else if (dowhat&(1<<j)) bit++;
1023           }
1024 
1025           // When selection active, modify bit
1026           if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
1027           if (bit && dohow != '-') mode |= where;
1028         }
1029       }
1030       if (!*str) return mode|extrabits;
1031       if (*str == ',') {
1032         str++;
1033         break;
1034       }
1035     }
1036   }
1037 
1038 barf:
1039   error_exit("bad mode '%s'", modestr);
1040 }
1041 
1042 // Format access mode into a drwxrwxrwx string
mode_to_string(unsigned mode,char * buf)1043 void mode_to_string(unsigned mode, char *buf)
1044 {
1045   char c, d;
1046   int i, bit;
1047 
1048   buf[10]=0;
1049   for (i=0; i<9; i++) {
1050     bit = mode & (1<<i);
1051     c = i%3;
1052     if (!c && (mode & (1<<((d=i/3)+9)))) {
1053       c = "tss"[d];
1054       if (!bit) c &= ~0x20;
1055     } else c = bit ? "xwr"[c] : '-';
1056     buf[9-i] = c;
1057   }
1058 
1059   if (S_ISDIR(mode)) c = 'd';
1060   else if (S_ISBLK(mode)) c = 'b';
1061   else if (S_ISCHR(mode)) c = 'c';
1062   else if (S_ISLNK(mode)) c = 'l';
1063   else if (S_ISFIFO(mode)) c = 'p';
1064   else if (S_ISSOCK(mode)) c = 's';
1065   else c = '-';
1066   *buf = c;
1067 }
1068 
1069 // basename() can modify its argument or return a pointer to a constant string
1070 // This just gives after the last '/' or the whole stirng if no /
getbasename(char * name)1071 char *getbasename(char *name)
1072 {
1073   char *s = strrchr(name, '/');
1074 
1075   if (s) return s+1;
1076 
1077   return name;
1078 }
1079 
1080 // Return pointer to xabspath(file) if file is under dir, else 0
fileunderdir(char * file,char * dir)1081 char *fileunderdir(char *file, char *dir)
1082 {
1083   char *s1 = xabspath(dir, ABS_FILE), *s2 = xabspath(file, 0), *ss = s2;
1084   int rc = s1 && s2 && strstart(&ss, s1) && (!s1[1] || s2[strlen(s1)] == '/');
1085 
1086   free(s1);
1087   if (!rc) free(s2);
1088 
1089   return rc ? s2 : 0;
1090 }
1091 
mepcpy(void * to,void * from,unsigned long len)1092 void *mepcpy(void *to, void *from, unsigned long len)
1093 {
1094   memcpy(to, from, len);
1095 
1096   return ((char *)to)+len;
1097 }
1098 
1099 // return (malloced) relative path to get between two normalized absolute paths
1100 // normalized: no duplicate / or trailing / or .. or . (symlinks optional)
relative_path(char * from,char * to,int abs)1101 char *relative_path(char *from, char *to, int abs)
1102 {
1103   char *s, *ret = 0;
1104   int i, j, k;
1105 
1106   if (abs) {
1107     if (!(from = xabspath(from, 0))) return 0;
1108     if (!(to = xabspath(to, 0))) goto error;
1109   }
1110 
1111   for (i = j = 0;; i++) {
1112     if (!from[i] || !to[i]) {
1113       if (from[i]=='/' || to[i]=='/' || from[i]==to[i]) j = i;
1114       break;
1115     }
1116     if (from[i] != to[i]) break;
1117     if (from[i] == '/') j = i;
1118   }
1119 
1120   // count remaining destination directories
1121   for (i = j, k = 0; from[i]; i++) if (from[i] == '/') k++;
1122   if (!k) {
1123     if (to[j]=='/') j++;
1124     ret = xstrdup(to[j] ? to+j : ".");
1125   } else {
1126     s = ret = xmprintf("%*c%s", 3*k-!!k, ' ', to+j);
1127     for (i = 0; i<k; i++) s = mepcpy(s, "/.."+!i, 3-!i);
1128   }
1129 
1130 error:
1131   if (abs) {
1132     free(from);
1133     free(to);
1134   }
1135 
1136   return ret;
1137 }
1138 
1139 // 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)1140 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name),
1141     int scripts)
1142 {
1143   DIR *dp;
1144   struct dirent *entry;
1145 
1146   if (!(dp = opendir("/proc"))) perror_exit("no /proc");
1147 
1148   while ((entry = readdir(dp))) {
1149     unsigned u = atoi(entry->d_name);
1150     char *cmd = 0, *comm = 0, **cur;
1151     off_t len;
1152 
1153     if (!u) continue;
1154 
1155     // Comm is original name of executable (argv[0] could be #! interpreter)
1156     // but it's limited to 15 characters
1157     if (scripts) {
1158       sprintf(libbuf, "/proc/%u/comm", u);
1159       len = sizeof(libbuf);
1160       if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
1161         continue;
1162       if (libbuf[len-1] == '\n') libbuf[--len] = 0;
1163     }
1164 
1165     for (cur = names; *cur; cur++) {
1166       struct stat st1, st2;
1167       char *bb = getbasename(*cur);
1168       off_t len = strlen(bb);
1169 
1170       // Fast path: only matching a filename (no path) that fits in comm.
1171       // `len` must be 14 or less because with a full 15 bytes we don't
1172       // know whether the name fit or was truncated.
1173       if (scripts && len<=14 && bb==*cur && !strcmp(comm, bb)) goto match;
1174 
1175       // If we have a path to existing file only match if same inode
1176       if (bb!=*cur && !stat(*cur, &st1)) {
1177         char buf[32];
1178 
1179         sprintf(buf, "/proc/%u/exe", u);
1180         if (stat(buf, &st2) || !same_file(&st1, &st2)) continue;
1181         goto match;
1182       }
1183 
1184       // Nope, gotta read command line to confirm
1185       if (!cmd) {
1186         sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1187         len = sizeof(libbuf)-17;
1188         if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1189         // readfile only guarantees one null terminator and we need two
1190         // (yes the kernel should do this for us, don't care)
1191         cmd[len] = 0;
1192       }
1193       if (!strcmp(bb, getbasename(cmd))) goto match;
1194       if (scripts && !strcmp(bb, getbasename(cmd+strlen(cmd)+1))) goto match;
1195       continue;
1196 match:
1197       if (callback(u, *cur)) goto done;
1198     }
1199   }
1200 done:
1201   closedir(dp);
1202 }
1203 
1204 // 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)1205 int human_readable_long(char *buf, unsigned long long num, int dgt, int unit,
1206   int style)
1207 {
1208   unsigned long long snap = 0;
1209   int len, divisor = (style&HR_1000) ? 1000 : 1024;
1210 
1211   // Divide rounding up until we have 3 or fewer digits. Since the part we
1212   // print is decimal, the test is 999 even when we divide by 1024.
1213   // The largest unit we can detect is 1<<64 = 18 Exabytes, but we added
1214   // Zettabyte and Yottabyte in case "unit" starts above zero.
1215   for (;;unit++) {
1216     if ((len = snprintf(0, 0, "%llu", num))<=dgt) break;
1217     num = ((snap = num)+(divisor/2))/divisor;
1218   }
1219   if (CFG_TOYBOX_DEBUG && unit>8) return sprintf(buf, "%.*s", dgt, "TILT");
1220 
1221   len = sprintf(buf, "%llu", num);
1222   if (!(style & HR_NODOT) && unit && len == 1) {
1223     // Redo rounding for 1.2M case, this works with and without HR_1000.
1224     num = snap/divisor;
1225     snap -= num*divisor;
1226     snap = ((snap*100)+50)/divisor;
1227     snap /= 10;
1228     len = sprintf(buf, "%llu.%llu", num, snap);
1229   }
1230   if (style & HR_SPACE) buf[len++] = ' ';
1231   if (unit) {
1232     unit = " kMGTPEZY"[unit];
1233 
1234     if (!(style&HR_1000)) unit = toupper(unit);
1235     buf[len++] = unit;
1236   } else if (style & HR_B) buf[len++] = 'B';
1237   buf[len] = 0;
1238 
1239   return len;
1240 }
1241 
1242 // Give 3 digit estimate + units ala 999M or 1.7T
human_readable(char * buf,unsigned long long num,int style)1243 int human_readable(char *buf, unsigned long long num, int style)
1244 {
1245   return human_readable_long(buf, num, 3, 0, style);
1246 }
1247 
1248 // The qsort man page says you can use alphasort, the posix committee
1249 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1250 // So just do our own. (The const is entirely to humor the stupid compiler.)
qstrcmp(const void * a,const void * b)1251 int qstrcmp(const void *a, const void *b)
1252 {
1253   return strcmp(*(char **)a, *(char **)b);
1254 }
1255 
1256 // See https://tools.ietf.org/html/rfc4122, specifically section 4.4
1257 // "Algorithms for Creating a UUID from Truly Random or Pseudo-Random
1258 // Numbers".
create_uuid(char * uuid)1259 void create_uuid(char *uuid)
1260 {
1261   // "Set all the ... bits to randomly (or pseudo-randomly) chosen values".
1262   xgetrandom(uuid, 16);
1263 
1264   // "Set the four most significant bits ... of the time_hi_and_version
1265   // field to the 4-bit version number [4]".
1266   uuid[6] = (uuid[6] & 0x0F) | 0x40;
1267   // "Set the two most significant bits (bits 6 and 7) of
1268   // clock_seq_hi_and_reserved to zero and one, respectively".
1269   uuid[8] = (uuid[8] & 0x3F) | 0x80;
1270 }
1271 
show_uuid(char * uuid)1272 char *show_uuid(char *uuid)
1273 {
1274   char *out = libbuf;
1275   int i;
1276 
1277   for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1278   *out = 0;
1279 
1280   return libbuf;
1281 }
1282 
1283 // Returns pointer to letter at end, 0 if none. *start = initial %
next_printf(char * s,char ** start)1284 char *next_printf(char *s, char **start)
1285 {
1286   for (; *s; s++) {
1287     if (*s != '%') continue;
1288     if (*++s == '%') continue;
1289     if (start) *start = s-1;
1290     while (0 <= stridx("0'#-+ ", *s)) s++;
1291     while (isdigit(*s)) s++;
1292     if (*s == '.') s++;
1293     while (isdigit(*s)) s++;
1294 
1295     return s;
1296   }
1297 
1298   return 0;
1299 }
1300 
1301 // Return cached passwd entries.
bufgetpwnamuid(char * name,uid_t uid)1302 struct passwd *bufgetpwnamuid(char *name, uid_t uid)
1303 {
1304   struct pwuidbuf_list {
1305     struct pwuidbuf_list *next;
1306     struct passwd pw;
1307   } *list = 0;
1308   struct passwd *temp;
1309   static struct pwuidbuf_list *pwuidbuf;
1310   unsigned size = 256;
1311 
1312   // If we already have this one, return it.
1313   for (list = pwuidbuf; list; list = list->next)
1314     if (name ? !strcmp(name, list->pw.pw_name) : list->pw.pw_uid==uid)
1315       return &(list->pw);
1316 
1317   for (;;) {
1318     list = xrealloc(list, size *= 2);
1319     if (name) errno = getpwnam_r(name, &list->pw, sizeof(*list)+(char *)list,
1320       size-sizeof(*list), &temp);
1321     else errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1322       size-sizeof(*list), &temp);
1323     if (errno != ERANGE) break;
1324   }
1325 
1326   if (!temp) {
1327     free(list);
1328 
1329     return 0;
1330   }
1331   list->next = pwuidbuf;
1332   pwuidbuf = list;
1333 
1334   return &list->pw;
1335 }
1336 
bufgetpwuid(uid_t uid)1337 struct passwd *bufgetpwuid(uid_t uid)
1338 {
1339   return bufgetpwnamuid(0, uid);
1340 }
1341 
1342 // Return cached group entries.
bufgetgrnamgid(char * name,gid_t gid)1343 struct group *bufgetgrnamgid(char *name, gid_t gid)
1344 {
1345   struct grgidbuf_list {
1346     struct grgidbuf_list *next;
1347     struct group gr;
1348   } *list = 0;
1349   struct group *temp;
1350   static struct grgidbuf_list *grgidbuf;
1351   unsigned size = 256;
1352 
1353   for (list = grgidbuf; list; list = list->next)
1354     if (name ? !strcmp(name, list->gr.gr_name) : list->gr.gr_gid==gid)
1355       return &(list->gr);
1356 
1357   for (;;) {
1358     list = xrealloc(list, size *= 2);
1359     if (name) errno = getgrnam_r(name, &list->gr, sizeof(*list)+(char *)list,
1360       size-sizeof(*list), &temp);
1361     else errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1362       size-sizeof(*list), &temp);
1363     if (errno != ERANGE) break;
1364   }
1365   if (!temp) {
1366     free(list);
1367 
1368     return 0;
1369   }
1370   list->next = grgidbuf;
1371   grgidbuf = list;
1372 
1373   return &list->gr;
1374 }
1375 
bufgetgrgid(gid_t gid)1376 struct group *bufgetgrgid(gid_t gid)
1377 {
1378   return bufgetgrnamgid(0, gid);
1379 }
1380 
1381 
1382 // Always null terminates, returns 0 for failure, len for success
readlinkat0(int dirfd,char * path,char * buf,int len)1383 int readlinkat0(int dirfd, char *path, char *buf, int len)
1384 {
1385   if (!len) return 0;
1386 
1387   len = readlinkat(dirfd, path, buf, len-1);
1388   if (len<0) len = 0;
1389   buf[len] = 0;
1390 
1391   return len;
1392 }
1393 
readlink0(char * path,char * buf,int len)1394 int readlink0(char *path, char *buf, int len)
1395 {
1396   return readlinkat0(AT_FDCWD, path, buf, len);
1397 }
1398 
1399 // 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)1400 int regexec0(regex_t *preg, char *string, long len, int nmatch,
1401   regmatch_t *pmatch, int eflags)
1402 {
1403   regmatch_t backup;
1404 
1405   if (!nmatch) pmatch = &backup;
1406   pmatch->rm_so = 0;
1407   pmatch->rm_eo = len;
1408   return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
1409 }
1410 
1411 // Return user name or string representation of number, returned buffer
1412 // lasts until next call.
getusername(uid_t uid)1413 char *getusername(uid_t uid)
1414 {
1415   struct passwd *pw = bufgetpwuid(uid);
1416   static char unum[12];
1417 
1418   sprintf(unum, "%u", (unsigned)uid);
1419   return pw ? pw->pw_name : unum;
1420 }
1421 
1422 // Return group name or string representation of number, returned buffer
1423 // lasts until next call.
getgroupname(gid_t gid)1424 char *getgroupname(gid_t gid)
1425 {
1426   struct group *gr = bufgetgrgid(gid);
1427   static char gnum[12];
1428 
1429   sprintf(gnum, "%u", (unsigned)gid);
1430   return gr ? gr->gr_name : gnum;
1431 }
1432 
1433 // Iterate over lines in file, calling function. Function can write 0 to
1434 // the line pointer if they want to keep it, or 1 to terminate processing,
1435 // otherwise line is freed. Passed file descriptor is closed at the end.
1436 // At EOF calls function(0, 0)
do_lines(int fd,char delim,void (* call)(char ** pline,long len))1437 void do_lines(int fd, char delim, void (*call)(char **pline, long len))
1438 {
1439   FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1440 
1441   for (;;) {
1442     char *line = 0;
1443     ssize_t len;
1444 
1445     len = getdelim(&line, (void *)&len, delim, fp);
1446     if (len > 0) {
1447       call(&line, len);
1448       if (line == (void *)1) break;
1449       free(line);
1450     } else break;
1451   }
1452   call(0, 0);
1453 
1454   if (fd) fclose(fp);
1455 }
1456 
1457 // Return unix time in milliseconds
millitime(void)1458 long long millitime(void)
1459 {
1460   struct timespec ts;
1461 
1462   clock_gettime(CLOCK_MONOTONIC, &ts);
1463   return ts.tv_sec*1000+ts.tv_nsec/1000000;
1464 }
1465 
1466 // Formats `ts` in ISO format ("2018-06-28 15:08:58.846386216 -0700").
format_iso_time(char * buf,size_t len,struct timespec * ts)1467 char *format_iso_time(char *buf, size_t len, struct timespec *ts)
1468 {
1469   char *s = buf;
1470 
1471   s += strftime(s, len, "%F %T", localtime(&(ts->tv_sec)));
1472   s += sprintf(s, ".%09ld ", ts->tv_nsec);
1473   s += strftime(s, len-strlen(buf), "%z", localtime(&(ts->tv_sec)));
1474 
1475   return buf;
1476 }
1477 
1478 // Syslog with the openlog/closelog, autodetecting daemon status via no tty
1479 
loggit(int priority,char * format,...)1480 void loggit(int priority, char *format, ...)
1481 {
1482   int i, facility = LOG_DAEMON;
1483   va_list va;
1484 
1485   for (i = 0; i<3; i++) if (isatty(i)) facility = LOG_AUTH;
1486   openlog(toys.which->name, LOG_PID, facility);
1487   va_start(va, format);
1488   vsyslog(priority, format, va);
1489   va_end(va);
1490   closelog();
1491 }
1492 
1493 // Calculate tar packet checksum, with cksum field treated as 8 spaces
tar_cksum(void * data)1494 unsigned tar_cksum(void *data)
1495 {
1496   unsigned i, cksum = 8*' ';
1497 
1498   for (i = 0; i<500; i += (i==147) ? 9 : 1) cksum += ((char *)data)[i];
1499 
1500   return cksum;
1501 }
1502 
1503 // is this a valid tar header?
is_tar_header(void * pkt)1504 int is_tar_header(void *pkt)
1505 {
1506   char *p = pkt;
1507   int i = 0;
1508 
1509   if (p[257] && smemcmp("ustar", p+257, 5)) return 0;
1510   if (p[148] != '0' && p[148] != ' ') return 0;
1511   sscanf(p+148, "%8o", &i);
1512 
1513   return i && tar_cksum(pkt) == i;
1514 }
1515 
1516 // Remove octal escapes from string (common in kernel exports)
octal_deslash(char * s)1517 void octal_deslash(char *s)
1518 {
1519   char *o = s;
1520 
1521   while (*s) {
1522     if (*s == '\\') {
1523       int i, oct = 0;
1524 
1525       for (i = 1; i < 4; i++) {
1526         if (!isdigit(s[i])) break;
1527         oct = (oct<<3)+s[i]-'0';
1528       }
1529       if (i == 4) {
1530         *o++ = oct;
1531         s += i;
1532         continue;
1533       }
1534     }
1535     *o++ = *s++;
1536   }
1537 
1538   *o = 0;
1539 }
1540 
1541 // ASAN flips out about memcmp("a", "abc", 4) but the result is well-defined.
1542 // This one's guaranteed to stop at len _or_ the first difference.
smemcmp(char * one,char * two,unsigned long len)1543 int smemcmp(char *one, char *two, unsigned long len)
1544 {
1545   int ii = 0;
1546 
1547   // NULL sorts after anything else
1548   if (one == two) return 0;
1549   if (!one) return 1;
1550   if (!two) return -1;
1551 
1552   while (len--) if ((ii = *one++ - *two++)) break;
1553 
1554   return ii;
1555 }
1556 
1557