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