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