1 /* lib.c - various reusable stuff.
2 *
3 * Copyright 2006 Rob Landley <rob@landley.net>
4 */
5
6 #include "toys.h"
7
verror_msg(char * msg,int err,va_list va)8 void verror_msg(char *msg, int err, va_list va)
9 {
10 char *s = ": %s";
11
12 fprintf(stderr, "%s: ", toys.which->name);
13 if (msg) vfprintf(stderr, msg, va);
14 else s+=2;
15 if (err) fprintf(stderr, s, strerror(err));
16 if (msg || err) putc('\n', stderr);
17 if (!toys.exitval) toys.exitval++;
18 }
19
20 // These functions don't collapse together because of the va_stuff.
21
error_msg(char * msg,...)22 void error_msg(char *msg, ...)
23 {
24 va_list va;
25
26 va_start(va, msg);
27 verror_msg(msg, 0, va);
28 va_end(va);
29 }
30
perror_msg(char * msg,...)31 void perror_msg(char *msg, ...)
32 {
33 va_list va;
34
35 va_start(va, msg);
36 verror_msg(msg, errno, va);
37 va_end(va);
38 }
39
40 // Die with an error message.
error_exit(char * msg,...)41 void error_exit(char *msg, ...)
42 {
43 va_list va;
44
45 va_start(va, msg);
46 verror_msg(msg, 0, va);
47 va_end(va);
48
49 xexit();
50 }
51
52 // Die with an error message and strerror(errno)
perror_exit(char * msg,...)53 void perror_exit(char *msg, ...)
54 {
55 va_list va;
56
57 va_start(va, msg);
58 verror_msg(msg, errno, va);
59 va_end(va);
60
61 xexit();
62 }
63
64 // Exit with an error message after showing help text.
help_exit(char * msg,...)65 void help_exit(char *msg, ...)
66 {
67 va_list va;
68
69 if (CFG_TOYBOX_HELP)
70 fprintf(stderr, "See %s --help\n", toys.which->name);
71
72 if (msg) {
73 va_start(va, msg);
74 verror_msg(msg, 0, va);
75 va_end(va);
76 }
77
78 xexit();
79 }
80
81 // If you want to explicitly disable the printf() behavior (because you're
82 // printing user-supplied data, or because android's static checker produces
83 // false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
84 // -Werror there for policy reasons).
error_msg_raw(char * msg)85 void error_msg_raw(char *msg)
86 {
87 error_msg("%s", msg);
88 }
89
perror_msg_raw(char * msg)90 void perror_msg_raw(char *msg)
91 {
92 perror_msg("%s", msg);
93 }
94
error_exit_raw(char * msg)95 void error_exit_raw(char *msg)
96 {
97 error_exit("%s", msg);
98 }
99
perror_exit_raw(char * msg)100 void perror_exit_raw(char *msg)
101 {
102 perror_exit("%s", msg);
103 }
104
105 // Keep reading until full or EOF
readall(int fd,void * buf,size_t len)106 ssize_t readall(int fd, void *buf, size_t len)
107 {
108 size_t count = 0;
109
110 while (count<len) {
111 int i = read(fd, (char *)buf+count, len-count);
112 if (!i) break;
113 if (i<0) return i;
114 count += i;
115 }
116
117 return count;
118 }
119
120 // Keep writing until done or EOF
writeall(int fd,void * buf,size_t len)121 ssize_t writeall(int fd, void *buf, size_t len)
122 {
123 size_t count = 0;
124 while (count<len) {
125 int i = write(fd, count+(char *)buf, len-count);
126 if (i<1) return i;
127 count += i;
128 }
129
130 return count;
131 }
132
133 // skip this many bytes of input. Return 0 for success, >0 means this much
134 // left after input skipped.
lskip(int fd,off_t offset)135 off_t lskip(int fd, off_t offset)
136 {
137 off_t cur = lseek(fd, 0, SEEK_CUR);
138
139 if (cur != -1) {
140 off_t end = lseek(fd, 0, SEEK_END) - cur;
141
142 if (end > 0 && end < offset) return offset - end;
143 end = offset+cur;
144 if (end == lseek(fd, end, SEEK_SET)) return 0;
145 perror_exit("lseek");
146 }
147
148 while (offset>0) {
149 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
150
151 or = readall(fd, libbuf, try);
152 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
153 else offset -= or;
154 if (or < try) break;
155 }
156
157 return offset;
158 }
159
160 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
161 // 2=make path (already exists is ok)
162 // 4=verbose
163 // returns 0 = path ok, 1 = error
mkpathat(int atfd,char * dir,mode_t lastmode,int flags)164 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
165 {
166 struct stat buf;
167 char *s;
168
169 // mkdir -p one/two/three is not an error if the path already exists,
170 // but is if "three" is a file. The others we dereference and catch
171 // not-a-directory along the way, but the last one we must explicitly
172 // test for. Might as well do it up front.
173
174 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
175 errno = EEXIST;
176 return 1;
177 }
178
179 for (s = dir; ;s++) {
180 char save = 0;
181 mode_t mode = (0777&~toys.old_umask)|0300;
182
183 // find next '/', but don't try to mkdir "" at start of absolute path
184 if (*s == '/' && (flags&2) && s != dir) {
185 save = *s;
186 *s = 0;
187 } else if (*s) continue;
188
189 // Use the mode from the -m option only for the last directory.
190 if (!save) {
191 if (flags&1) mode = lastmode;
192 else break;
193 }
194
195 if (mkdirat(atfd, dir, mode)) {
196 if (!(flags&2) || errno != EEXIST) return 1;
197 } else if (flags&4)
198 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
199
200 if (!(*s = save)) break;
201 }
202
203 return 0;
204 }
205
206 // Split a path into linked list of components, tracking head and tail of list.
207 // Filters out // entries with no contents.
splitpath(char * path,struct string_list ** list)208 struct string_list **splitpath(char *path, struct string_list **list)
209 {
210 char *new = path;
211
212 *list = 0;
213 do {
214 int len;
215
216 if (*path && *path != '/') continue;
217 len = path-new;
218 if (len > 0) {
219 *list = xmalloc(sizeof(struct string_list) + len + 1);
220 (*list)->next = 0;
221 memcpy((*list)->str, new, len);
222 (*list)->str[len] = 0;
223 list = &(*list)->next;
224 }
225 new = path+1;
226 } while (*path++);
227
228 return list;
229 }
230
231 // Find all file in a colon-separated path with access type "type" (generally
232 // X_OK or R_OK). Returns a list of absolute paths to each file found, in
233 // order.
234
find_in_path(char * path,char * filename)235 struct string_list *find_in_path(char *path, char *filename)
236 {
237 struct string_list *rlist = NULL, **prlist=&rlist;
238 char *cwd;
239
240 if (!path) return 0;
241
242 cwd = xgetcwd();
243 for (;;) {
244 char *next = strchr(path, ':');
245 int len = next ? next-path : strlen(path);
246 struct string_list *rnext;
247 struct stat st;
248
249 rnext = xmalloc(sizeof(void *) + strlen(filename)
250 + (len ? len : strlen(cwd)) + 2);
251 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
252 else {
253 char *res = rnext->str;
254
255 memcpy(res, path, len);
256 res += len;
257 *(res++) = '/';
258 strcpy(res, filename);
259 }
260
261 // Confirm it's not a directory.
262 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
263 *prlist = rnext;
264 rnext->next = NULL;
265 prlist = &(rnext->next);
266 } else free(rnext);
267
268 if (!next) break;
269 path += len;
270 path++;
271 }
272 free(cwd);
273
274 return rlist;
275 }
276
estrtol(char * str,char ** end,int base)277 long long estrtol(char *str, char **end, int base)
278 {
279 errno = 0;
280
281 return strtoll(str, end, base);
282 }
283
xstrtol(char * str,char ** end,int base)284 long long xstrtol(char *str, char **end, int base)
285 {
286 long long l = estrtol(str, end, base);
287
288 if (errno) perror_exit_raw(str);
289
290 return l;
291 }
292
293 // atol() with the kilo/mega/giga/tera/peta/exa extensions, plus word and block.
294 // (zetta and yotta don't fit in 64 bits.)
atolx(char * numstr)295 long long atolx(char *numstr)
296 {
297 char *c = numstr, *suffixes="cwbkmgtpe", *end;
298 long long val;
299
300 val = xstrtol(numstr, &c, 0);
301 if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) {
302 int shift = end-suffixes-2;
303
304 if (shift==-1) val *= 2;
305 if (!shift) val *= 512;
306 else if (shift>0) {
307 if (toupper(*++c)=='d') while (shift--) val *= 1000;
308 else val *= 1LL<<(shift*10);
309 }
310 }
311 while (isspace(*c)) c++;
312 if (c==numstr || *c) error_exit("not integer: %s", numstr);
313
314 return val;
315 }
316
atolx_range(char * numstr,long long low,long long high)317 long long atolx_range(char *numstr, long long low, long long high)
318 {
319 long long val = atolx(numstr);
320
321 if (val < low) error_exit("%lld < %lld", val, low);
322 if (val > high) error_exit("%lld > %lld", val, high);
323
324 return val;
325 }
326
stridx(char * haystack,char needle)327 int stridx(char *haystack, char needle)
328 {
329 char *off;
330
331 if (!needle) return -1;
332 off = strchr(haystack, needle);
333 if (!off) return -1;
334
335 return off-haystack;
336 }
337
strlower(char * s)338 char *strlower(char *s)
339 {
340 char *try, *new;
341
342 if (!CFG_TOYBOX_I18N) {
343 try = new = xstrdup(s);
344 for (; *s; s++) *(new++) = tolower(*s);
345 } else {
346 // I can't guarantee the string _won't_ expand during reencoding, so...?
347 try = new = xmalloc(strlen(s)*2+1);
348
349 while (*s) {
350 wchar_t c;
351 int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
352
353 if (len < 1) *(new++) = *(s++);
354 else {
355 s += len;
356 // squash title case too
357 c = towlower(c);
358
359 // if we had a valid utf8 sequence, convert it to lower case, and can't
360 // encode back to utf8, something is wrong with your libc. But just
361 // in case somebody finds an exploit...
362 len = wcrtomb(new, c, 0);
363 if (len < 1) error_exit("bad utf8 %x", (int)c);
364 new += len;
365 }
366 }
367 *new = 0;
368 }
369
370 return try;
371 }
372
373 // strstr but returns pointer after match
strafter(char * haystack,char * needle)374 char *strafter(char *haystack, char *needle)
375 {
376 char *s = strstr(haystack, needle);
377
378 return s ? s+strlen(needle) : s;
379 }
380
381 // Remove trailing \n
chomp(char * s)382 char *chomp(char *s)
383 {
384 char *p = strrchr(s, '\n');
385
386 if (p && !p[1]) *p = 0;
387 return s;
388 }
389
unescape(char c)390 int unescape(char c)
391 {
392 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
393 int idx = stridx(from, c);
394
395 return (idx == -1) ? 0 : to[idx];
396 }
397
398 // If string ends with suffix return pointer to start of suffix in string,
399 // else NULL
strend(char * str,char * suffix)400 char *strend(char *str, char *suffix)
401 {
402 long a = strlen(str), b = strlen(suffix);
403
404 if (a>b && !strcmp(str += a-b, suffix)) return str;
405
406 return 0;
407 }
408
409 // If *a starts with b, advance *a past it and return 1, else return 0;
strstart(char ** a,char * b)410 int strstart(char **a, char *b)
411 {
412 int len = strlen(b), i = !strncmp(*a, b, len);
413
414 if (i) *a += len;
415
416 return i;
417 }
418
419 // Return how long the file at fd is, if there's any way to determine it.
fdlength(int fd)420 off_t fdlength(int fd)
421 {
422 struct stat st;
423 off_t base = 0, range = 1, expand = 1, old;
424
425 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
426
427 // If the ioctl works for this, return it.
428 // TODO: is blocksize still always 512, or do we stat for it?
429 // unsigned int size;
430 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
431
432 // If not, do a binary search for the last location we can read. (Some
433 // block devices don't do BLKGETSIZE right.) This should probably have
434 // a CONFIG option...
435
436 // If not, do a binary search for the last location we can read.
437
438 old = lseek(fd, 0, SEEK_CUR);
439 do {
440 char temp;
441 off_t pos = base + range / 2;
442
443 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
444 off_t delta = (pos + 1) - base;
445
446 base += delta;
447 if (expand) range = (expand <<= 1) - base;
448 else range -= delta;
449 } else {
450 expand = 0;
451 range = pos - base;
452 }
453 } while (range > 0);
454
455 lseek(fd, old, SEEK_SET);
456
457 return base;
458 }
459
460 // Read contents of file as a single nul-terminated string.
461 // measure file size if !len, allocate buffer if !buf
462 // Existing buffers need len in *plen
463 // Returns amount of data read in *plen
readfileat(int dirfd,char * name,char * ibuf,off_t * plen)464 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
465 {
466 off_t len, rlen;
467 int fd;
468 char *buf, *rbuf;
469
470 // Unsafe to probe for size with a supplied buffer, don't ever do that.
471 if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
472
473 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
474
475 // If we dunno the length, probe it. If we can't probe, start with 1 page.
476 if (!*plen) {
477 if ((len = fdlength(fd))>0) *plen = len;
478 else len = 4096;
479 } else len = *plen-1;
480
481 if (!ibuf) buf = xmalloc(len+1);
482 else buf = ibuf;
483
484 for (rbuf = buf;;) {
485 rlen = readall(fd, rbuf, len);
486 if (*plen || rlen<len) break;
487
488 // If reading unknown size, expand buffer by 1.5 each time we fill it up.
489 rlen += rbuf-buf;
490 buf = xrealloc(buf, len = (rlen*3)/2);
491 rbuf = buf+rlen;
492 len -= rlen;
493 }
494 *plen = len = rlen+(rbuf-buf);
495 close(fd);
496
497 if (rlen<0) {
498 if (ibuf != buf) free(buf);
499 buf = 0;
500 } else buf[len] = 0;
501
502 return buf;
503 }
504
readfile(char * name,char * ibuf,off_t len)505 char *readfile(char *name, char *ibuf, off_t len)
506 {
507 return readfileat(AT_FDCWD, name, ibuf, &len);
508 }
509
510 // Sleep for this many thousandths of a second
msleep(long miliseconds)511 void msleep(long miliseconds)
512 {
513 struct timespec ts;
514
515 ts.tv_sec = miliseconds/1000;
516 ts.tv_nsec = (miliseconds%1000)*1000000;
517 nanosleep(&ts, &ts);
518 }
519
520 // return 1<<x of highest bit set
highest_bit(unsigned long l)521 int highest_bit(unsigned long l)
522 {
523 int i;
524
525 for (i = 0; l; i++) l >>= 1;
526
527 return i-1;
528 }
529
530 // Inefficient, but deals with unaligned access
peek_le(void * ptr,unsigned size)531 int64_t peek_le(void *ptr, unsigned size)
532 {
533 int64_t ret = 0;
534 char *c = ptr;
535 int i;
536
537 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
538 return ret;
539 }
540
peek_be(void * ptr,unsigned size)541 int64_t peek_be(void *ptr, unsigned size)
542 {
543 int64_t ret = 0;
544 char *c = ptr;
545 int i;
546
547 for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
548 return ret;
549 }
550
peek(void * ptr,unsigned size)551 int64_t peek(void *ptr, unsigned size)
552 {
553 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
554 }
555
poke(void * ptr,uint64_t val,int size)556 void poke(void *ptr, uint64_t val, int size)
557 {
558 if (size & 8) {
559 volatile uint64_t *p = (uint64_t *)ptr;
560 *p = val;
561 } else if (size & 4) {
562 volatile int *p = (int *)ptr;
563 *p = val;
564 } else if (size & 2) {
565 volatile short *p = (short *)ptr;
566 *p = val;
567 } else {
568 volatile char *p = (char *)ptr;
569 *p = val;
570 }
571 }
572
573 // Iterate through an array of files, opening each one and calling a function
574 // on that filehandle and name. The special filename "-" means stdin if
575 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
576 // function() on just stdin/stdout.
577 //
578 // Note: pass O_CLOEXEC to automatically close filehandles when function()
579 // returns, otherwise filehandles must be closed by function().
580 // pass WARN_ONLY to produce warning messages about files it couldn't
581 // 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))582 void loopfiles_rw(char **argv, int flags, int permissions,
583 void (*function)(int fd, char *name))
584 {
585 int fd, failok = !(flags&WARN_ONLY);
586
587 flags &= ~WARN_ONLY;
588
589 // If no arguments, read from stdin.
590 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
591 else do {
592 // Filename "-" means read from stdin.
593 // Inability to open a file prints a warning, but doesn't exit.
594
595 if (!strcmp(*argv, "-")) fd = 0;
596 else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
597 perror_msg_raw(*argv);
598 continue;
599 }
600 function(fd, *argv);
601 if ((flags & O_CLOEXEC) && fd) close(fd);
602 } while (*++argv);
603 }
604
605 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
loopfiles(char ** argv,void (* function)(int fd,char * name))606 void loopfiles(char **argv, void (*function)(int fd, char *name))
607 {
608 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
609 }
610
611 // Slow, but small.
612
get_rawline(int fd,long * plen,char end)613 char *get_rawline(int fd, long *plen, char end)
614 {
615 char c, *buf = NULL;
616 long len = 0;
617
618 for (;;) {
619 if (1>read(fd, &c, 1)) break;
620 if (!(len & 63)) buf=xrealloc(buf, len+65);
621 if ((buf[len++]=c) == end) break;
622 }
623 if (buf) buf[len]=0;
624 if (plen) *plen = len;
625
626 return buf;
627 }
628
get_line(int fd)629 char *get_line(int fd)
630 {
631 long len;
632 char *buf = get_rawline(fd, &len, '\n');
633
634 if (buf && buf[--len]=='\n') buf[len]=0;
635
636 return buf;
637 }
638
wfchmodat(int fd,char * name,mode_t mode)639 int wfchmodat(int fd, char *name, mode_t mode)
640 {
641 int rc = fchmodat(fd, name, mode, 0);
642
643 if (rc) {
644 perror_msg("chmod '%s' to %04o", name, mode);
645 toys.exitval=1;
646 }
647 return rc;
648 }
649
650 static char *tempfile2zap;
tempfile_handler(void)651 static void tempfile_handler(void)
652 {
653 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
654 }
655
656 // Open a temporary file to copy an existing file into.
copy_tempfile(int fdin,char * name,char ** tempname)657 int copy_tempfile(int fdin, char *name, char **tempname)
658 {
659 struct stat statbuf;
660 int fd;
661 int ignored __attribute__((__unused__));
662
663 *tempname = xmprintf("%s%s", name, "XXXXXX");
664 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
665 if (!tempfile2zap) sigatexit(tempfile_handler);
666 tempfile2zap = *tempname;
667
668 // Set permissions of output file (ignoring errors, usually due to nonroot)
669
670 fstat(fdin, &statbuf);
671 fchmod(fd, statbuf.st_mode);
672
673 // We chmod before chown, which strips the suid bit. Caller has to explicitly
674 // switch it back on if they want to keep suid.
675
676 // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
677 // this but it's _supposed_ to fail when we're not root.
678 ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
679
680 return fd;
681 }
682
683 // Abort the copy and delete the temporary file.
delete_tempfile(int fdin,int fdout,char ** tempname)684 void delete_tempfile(int fdin, int fdout, char **tempname)
685 {
686 close(fdin);
687 close(fdout);
688 if (*tempname) unlink(*tempname);
689 tempfile2zap = (char *)1;
690 free(*tempname);
691 *tempname = NULL;
692 }
693
694 // Copy the rest of the data and replace the original with the copy.
replace_tempfile(int fdin,int fdout,char ** tempname)695 void replace_tempfile(int fdin, int fdout, char **tempname)
696 {
697 char *temp = xstrdup(*tempname);
698
699 temp[strlen(temp)-6]=0;
700 if (fdin != -1) {
701 xsendfile(fdin, fdout);
702 xclose(fdin);
703 }
704 xclose(fdout);
705 rename(*tempname, temp);
706 tempfile2zap = (char *)1;
707 free(*tempname);
708 free(temp);
709 *tempname = NULL;
710 }
711
712 // Create a 256 entry CRC32 lookup table.
713
crc_init(unsigned int * crc_table,int little_endian)714 void crc_init(unsigned int *crc_table, int little_endian)
715 {
716 unsigned int i;
717
718 // Init the CRC32 table (big endian)
719 for (i=0; i<256; i++) {
720 unsigned int j, c = little_endian ? i : i<<24;
721 for (j=8; j; j--)
722 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
723 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
724 crc_table[i] = c;
725 }
726 }
727
728 // Init base64 table
729
base64_init(char * p)730 void base64_init(char *p)
731 {
732 int i;
733
734 for (i = 'A'; i != ':'; i++) {
735 if (i == 'Z'+1) i = 'a';
736 if (i == 'z'+1) i = '0';
737 *(p++) = i;
738 }
739 *(p++) = '+';
740 *(p++) = '/';
741 }
742
yesno(int def)743 int yesno(int def)
744 {
745 char buf;
746
747 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
748 fflush(stderr);
749 while (fread(&buf, 1, 1, stdin)) {
750 int new;
751
752 // The letter changes the value, the newline (or space) returns it.
753 if (isspace(buf)) break;
754 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
755 }
756
757 return def;
758 }
759
760 struct signame {
761 int num;
762 char *name;
763 };
764
765 // Signals required by POSIX 2008:
766 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
767
768 #define SIGNIFY(x) {SIG##x, #x}
769
770 static struct signame signames[] = {
771 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
772 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
773 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
774 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
775 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
776
777 // Start of non-terminal signals
778
779 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
780 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
781 };
782
783 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
784 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
785
786 // Handler that sets toys.signal, and writes to toys.signalfd if set
generic_signal(int sig)787 void generic_signal(int sig)
788 {
789 if (toys.signalfd) {
790 char c = sig;
791
792 writeall(toys.signalfd, &c, 1);
793 }
794 toys.signal = sig;
795 }
796
exit_signal(int sig)797 void exit_signal(int sig)
798 {
799 if (sig) toys.exitval = sig|128;
800 xexit();
801 }
802
803 // Install the same handler on every signal that defaults to killing the
804 // process, calling the handler on the way out. Calling multiple times
805 // adds the handlers to a list, to be called in order.
sigatexit(void * handler)806 void sigatexit(void *handler)
807 {
808 struct arg_list *al = xmalloc(sizeof(struct arg_list));
809 int i;
810
811 for (i=0; signames[i].num != SIGCHLD; i++)
812 signal(signames[i].num, exit_signal);
813 al->next = toys.xexit;
814 al->arg = handler;
815 toys.xexit = al;
816 }
817
818 // Convert name to signal number. If name == NULL print names.
sig_to_num(char * pidstr)819 int sig_to_num(char *pidstr)
820 {
821 int i;
822
823 if (pidstr) {
824 char *s;
825
826 i = estrtol(pidstr, &s, 10);
827 if (!errno && !*s) return i;
828
829 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
830 }
831 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
832 if (!pidstr) xputs(signames[i].name);
833 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
834
835 return -1;
836 }
837
num_to_sig(int sig)838 char *num_to_sig(int sig)
839 {
840 int i;
841
842 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
843 if (signames[i].num == sig) return signames[i].name;
844 return NULL;
845 }
846
847 // premute mode bits based on posix mode strings.
string_to_mode(char * modestr,mode_t mode)848 mode_t string_to_mode(char *modestr, mode_t mode)
849 {
850 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
851 *s, *str = modestr;
852 mode_t extrabits = mode & ~(07777);
853
854 // Handle octal mode
855 if (isdigit(*str)) {
856 mode = estrtol(str, &s, 8);
857 if (errno || *s || (mode & ~(07777))) goto barf;
858
859 return mode | extrabits;
860 }
861
862 // Gaze into the bin of permission...
863 for (;;) {
864 int i, j, dowho, dohow, dowhat, amask;
865
866 dowho = dohow = dowhat = amask = 0;
867
868 // Find the who, how, and what stanzas, in that order
869 while (*str && (s = strchr(whos, *str))) {
870 dowho |= 1<<(s-whos);
871 str++;
872 }
873 // If who isn't specified, like "a" but honoring umask.
874 if (!dowho) {
875 dowho = 8;
876 umask(amask=umask(0));
877 }
878 if (!*str || !(s = strchr(hows, *str))) goto barf;
879 dohow = *(str++);
880
881 if (!dohow) goto barf;
882 while (*str && (s = strchr(whats, *str))) {
883 dowhat |= 1<<(s-whats);
884 str++;
885 }
886
887 // Convert X to x for directory or if already executable somewhere
888 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
889
890 // Copy mode from another category?
891 if (!dowhat && *str && (s = strchr(whys, *str))) {
892 dowhat = (mode>>(3*(s-whys)))&7;
893 str++;
894 }
895
896 // Are we ready to do a thing yet?
897 if (*str && *(str++) != ',') goto barf;
898
899 // Ok, apply the bits to the mode.
900 for (i=0; i<4; i++) {
901 for (j=0; j<3; j++) {
902 mode_t bit = 0;
903 int where = 1<<((3*i)+j);
904
905 if (amask & where) continue;
906
907 // Figure out new value at this location
908 if (i == 3) {
909 // suid/sticky bit.
910 if (j) {
911 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
912 } else if (dowhat & 16) bit++;
913 } else {
914 if (!(dowho&(8|(1<<i)))) continue;
915 if (dowhat&(1<<j)) bit++;
916 }
917
918 // When selection active, modify bit
919
920 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
921 if (bit && dohow != '-') mode |= where;
922 }
923 }
924
925 if (!*str) break;
926 }
927
928 return mode|extrabits;
929 barf:
930 error_exit("bad mode '%s'", modestr);
931 }
932
933 // Format access mode into a drwxrwxrwx string
mode_to_string(mode_t mode,char * buf)934 void mode_to_string(mode_t mode, char *buf)
935 {
936 char c, d;
937 int i, bit;
938
939 buf[10]=0;
940 for (i=0; i<9; i++) {
941 bit = mode & (1<<i);
942 c = i%3;
943 if (!c && (mode & (1<<((d=i/3)+9)))) {
944 c = "tss"[d];
945 if (!bit) c &= ~0x20;
946 } else c = bit ? "xwr"[c] : '-';
947 buf[9-i] = c;
948 }
949
950 if (S_ISDIR(mode)) c = 'd';
951 else if (S_ISBLK(mode)) c = 'b';
952 else if (S_ISCHR(mode)) c = 'c';
953 else if (S_ISLNK(mode)) c = 'l';
954 else if (S_ISFIFO(mode)) c = 'p';
955 else if (S_ISSOCK(mode)) c = 's';
956 else c = '-';
957 *buf = c;
958 }
959
960 // basename() can modify its argument or return a pointer to a constant string
961 // This just gives after the last '/' or the whole stirng if no /
getbasename(char * name)962 char *getbasename(char *name)
963 {
964 char *s = strrchr(name, '/');
965
966 if (s) return s+1;
967
968 return name;
969 }
970
971 // 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))972 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
973 {
974 DIR *dp;
975 struct dirent *entry;
976
977 if (!(dp = opendir("/proc"))) perror_exit("opendir");
978
979 while ((entry = readdir(dp))) {
980 unsigned u;
981 char *cmd, **curname;
982
983 if (!(u = atoi(entry->d_name))) continue;
984 sprintf(libbuf, "/proc/%u/cmdline", u);
985 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
986
987 for (curname = names; *curname; curname++)
988 if (**curname == '/' ? !strcmp(cmd, *curname)
989 : !strcmp(getbasename(cmd), getbasename(*curname)))
990 if (callback(u, *curname)) break;
991 if (*curname) break;
992 }
993 closedir(dp);
994 }
995
996 // display first few digits of number with power of two units
human_readable(char * buf,unsigned long long num,int style)997 int human_readable(char *buf, unsigned long long num, int style)
998 {
999 unsigned long long snap = 0;
1000 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
1001
1002 // Divide rounding up until we have 3 or fewer digits. Since the part we
1003 // print is decimal, the test is 999 even when we divide by 1024.
1004 // We can't run out of units because 2<<64 is 18 exabytes.
1005 // test 5675 is 5.5k not 5.6k.
1006 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
1007 len = sprintf(buf, "%llu", num);
1008 if (unit && len == 1) {
1009 // Redo rounding for 1.2M case, this works with and without HR_1000.
1010 num = snap/divisor;
1011 snap -= num*divisor;
1012 snap = ((snap*100)+50)/divisor;
1013 snap /= 10;
1014 len = sprintf(buf, "%llu.%llu", num, snap);
1015 }
1016 if (style & HR_SPACE) buf[len++] = ' ';
1017 if (unit) {
1018 unit = " kMGTPE"[unit];
1019
1020 if (!(style&HR_1000)) unit = toupper(unit);
1021 buf[len++] = unit;
1022 } else if (style & HR_B) buf[len++] = 'B';
1023 buf[len] = 0;
1024
1025 return len;
1026 }
1027
1028 // The qsort man page says you can use alphasort, the posix committee
1029 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1030 // So just do our own. (The const is entirely to humor the stupid compiler.)
qstrcmp(const void * a,const void * b)1031 int qstrcmp(const void *a, const void *b)
1032 {
1033 return strcmp(*(char **)a, *(char **)b);
1034 }
1035
1036 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
1037 // we should generate a uuid structure by reading a clock with 100 nanosecond
1038 // precision, normalizing it to the start of the gregorian calendar in 1582,
1039 // and looking up our eth0 mac address.
1040 //
1041 // On the other hand, we have 128 bits to come up with a unique identifier, of
1042 // which 6 have a defined value. /dev/urandom it is.
1043
create_uuid(char * uuid)1044 void create_uuid(char *uuid)
1045 {
1046 // Read 128 random bits
1047 int fd = xopenro("/dev/urandom");
1048 xreadall(fd, uuid, 16);
1049 close(fd);
1050
1051 // Claim to be a DCE format UUID.
1052 uuid[6] = (uuid[6] & 0x0F) | 0x40;
1053 uuid[8] = (uuid[8] & 0x3F) | 0x80;
1054
1055 // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1056 // set bit 1 of the node ID, which is the mac multicast bit. This means we
1057 // should never collide with anybody actually using a macaddr.
1058 uuid[11] |= 128;
1059 }
1060
show_uuid(char * uuid)1061 char *show_uuid(char *uuid)
1062 {
1063 char *out = libbuf;
1064 int i;
1065
1066 for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1067 *out = 0;
1068
1069 return libbuf;
1070 }
1071
1072 // Returns pointer to letter at end, 0 if none. *start = initial %
next_printf(char * s,char ** start)1073 char *next_printf(char *s, char **start)
1074 {
1075 for (; *s; s++) {
1076 if (*s != '%') continue;
1077 if (*++s == '%') continue;
1078 if (start) *start = s-1;
1079 while (0 <= stridx("0'#-+ ", *s)) s++;
1080 while (isdigit(*s)) s++;
1081 if (*s == '.') s++;
1082 while (isdigit(*s)) s++;
1083
1084 return s;
1085 }
1086
1087 return 0;
1088 }
1089
1090 // Posix inexplicably hasn't got this, so find str in line.
strnstr(char * line,char * str)1091 char *strnstr(char *line, char *str)
1092 {
1093 long len = strlen(str);
1094 char *s;
1095
1096 for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break;
1097
1098 return *s ? s : 0;
1099 }
1100
dev_minor(int dev)1101 int dev_minor(int dev)
1102 {
1103 return ((dev&0xfff00000)>>12)|(dev&0xff);
1104 }
1105
dev_major(int dev)1106 int dev_major(int dev)
1107 {
1108 return (dev&0xfff00)>>8;
1109 }
1110
dev_makedev(int major,int minor)1111 int dev_makedev(int major, int minor)
1112 {
1113 return (minor&0xff)|((major&0xfff)<<8)|((minor&0xfff00)<<12);
1114 }
1115
1116 // Return cached passwd entries.
bufgetpwuid(uid_t uid)1117 struct passwd *bufgetpwuid(uid_t uid)
1118 {
1119 struct pwuidbuf_list {
1120 struct pwuidbuf_list *next;
1121 struct passwd pw;
1122 } *list;
1123 struct passwd *temp;
1124 static struct pwuidbuf_list *pwuidbuf;
1125
1126 for (list = pwuidbuf; list; list = list->next)
1127 if (list->pw.pw_uid == uid) return &(list->pw);
1128
1129 list = xmalloc(512);
1130 list->next = pwuidbuf;
1131
1132 errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1133 512-sizeof(*list), &temp);
1134 if (!temp) {
1135 free(list);
1136
1137 return 0;
1138 }
1139 pwuidbuf = list;
1140
1141 return &list->pw;
1142 }
1143
1144 // Return cached passwd entries.
bufgetgrgid(gid_t gid)1145 struct group *bufgetgrgid(gid_t gid)
1146 {
1147 struct grgidbuf_list {
1148 struct grgidbuf_list *next;
1149 struct group gr;
1150 } *list;
1151 struct group *temp;
1152 static struct grgidbuf_list *grgidbuf;
1153
1154 for (list = grgidbuf; list; list = list->next)
1155 if (list->gr.gr_gid == gid) return &(list->gr);
1156
1157 list = xmalloc(512);
1158 list->next = grgidbuf;
1159
1160 errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1161 512-sizeof(*list), &temp);
1162 if (!temp) {
1163 free(list);
1164
1165 return 0;
1166 }
1167 grgidbuf = list;
1168
1169 return &list->gr;
1170 }
1171
1172 // Always null terminates, returns 0 for failure, len for success
readlinkat0(int dirfd,char * path,char * buf,int len)1173 int readlinkat0(int dirfd, char *path, char *buf, int len)
1174 {
1175 if (!len) return 0;
1176
1177 len = readlinkat(dirfd, path, buf, len-1);
1178 if (len<1) return 0;
1179 buf[len] = 0;
1180
1181 return len;
1182 }
1183
readlink0(char * path,char * buf,int len)1184 int readlink0(char *path, char *buf, int len)
1185 {
1186 return readlinkat0(AT_FDCWD, path, buf, len);
1187 }
1188
1189 // Do regex matching handling embedded NUL bytes in string (hence extra len
1190 // argument). Note that neither the pattern nor the match can currently include
1191 // NUL bytes (even with wildcards) and string must be null terminated at
1192 // string[len]. But this can find a match after the first NUL.
regexec0(regex_t * preg,char * string,long len,int nmatch,regmatch_t pmatch[],int eflags)1193 int regexec0(regex_t *preg, char *string, long len, int nmatch,
1194 regmatch_t pmatch[], int eflags)
1195 {
1196 char *s = string;
1197
1198 for (;;) {
1199 long ll = 0;
1200 int rc;
1201
1202 while (len && !*s) {
1203 s++;
1204 len--;
1205 }
1206 while (s[ll] && ll<len) ll++;
1207
1208 rc = regexec(preg, s, nmatch, pmatch, eflags);
1209 if (!rc) {
1210 for (rc = 0; rc<nmatch && pmatch[rc].rm_so!=-1; rc++) {
1211 pmatch[rc].rm_so += s-string;
1212 pmatch[rc].rm_eo += s-string;
1213 }
1214
1215 return 0;
1216 }
1217 if (ll==len) return rc;
1218
1219 s += ll;
1220 len -= ll;
1221 }
1222 }
1223
1224 // Return user name or string representation of number, returned buffer
1225 // lasts until next call.
getusername(uid_t uid)1226 char *getusername(uid_t uid)
1227 {
1228 struct passwd *pw = bufgetpwuid(uid);
1229 static char unum[12];
1230
1231 sprintf(unum, "%u", (unsigned)uid);
1232 return pw ? pw->pw_name : unum;
1233 }
1234
1235 // Return group name or string representation of number, returned buffer
1236 // lasts until next call.
getgroupname(gid_t gid)1237 char *getgroupname(gid_t gid)
1238 {
1239 struct group *gr = bufgetgrgid(gid);
1240 static char gnum[12];
1241
1242 sprintf(gnum, "%u", (unsigned)gid);
1243 return gr ? gr->gr_name : gnum;
1244 }
1245
1246 // Iterate over lines in file, calling function. Function can write 0 to
1247 // the line pointer if they want to keep it, or 1 to terminate processing,
1248 // otherwise line is freed. Passed file descriptor is closed at the end.
do_lines(int fd,void (* call)(char ** pline,long len))1249 void do_lines(int fd, void (*call)(char **pline, long len))
1250 {
1251 FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1252
1253 for (;;) {
1254 char *line = 0;
1255 ssize_t len;
1256
1257 len = getline(&line, (void *)&len, fp);
1258 if (len > 0) {
1259 call(&line, len);
1260 if (line == (void *)1) break;
1261 free(line);
1262 } else break;
1263 }
1264
1265 if (fd) fclose(fp);
1266 }
1267