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