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