OSDN Git Service

Redo namestopid to handle more cases.
[android-x86/external-toybox.git] / lib / lib.c
1 /* lib.c - various reusable stuff.
2  *
3  * Copyright 2006 Rob Landley <rob@landley.net>
4  */
5
6 #include "toys.h"
7
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>0) fprintf(stderr, s, strerror(err));
16   if (err<0 && CFG_TOYBOX_HELP)
17     fprintf(stderr, " (see \"%s --help\")", toys.which->name);
18   if (msg || err) putc('\n', stderr);
19   if (!toys.exitval) toys.exitval++;
20 }
21
22 // These functions don't collapse together because of the va_stuff.
23
24 void error_msg(char *msg, ...)
25 {
26   va_list va;
27
28   va_start(va, msg);
29   verror_msg(msg, 0, va);
30   va_end(va);
31 }
32
33 void perror_msg(char *msg, ...)
34 {
35   va_list va;
36
37   va_start(va, msg);
38   verror_msg(msg, errno, va);
39   va_end(va);
40 }
41
42 // Die with an error message.
43 void error_exit(char *msg, ...)
44 {
45   va_list va;
46
47   va_start(va, msg);
48   verror_msg(msg, 0, va);
49   va_end(va);
50
51   xexit();
52 }
53
54 // Die with an error message and strerror(errno)
55 void perror_exit(char *msg, ...)
56 {
57   va_list va;
58
59   va_start(va, msg);
60   verror_msg(msg, errno, va);
61   va_end(va);
62
63   xexit();
64 }
65
66 // Exit with an error message after showing help text.
67 void help_exit(char *msg, ...)
68 {
69   va_list va;
70
71   if (!msg) show_help(stdout);
72   else {
73     va_start(va, msg);
74     verror_msg(msg, -1, 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).
85 void error_msg_raw(char *msg)
86 {
87   error_msg("%s", msg);
88 }
89
90 void perror_msg_raw(char *msg)
91 {
92   perror_msg("%s", msg);
93 }
94
95 void error_exit_raw(char *msg)
96 {
97   error_exit("%s", msg);
98 }
99
100 void perror_exit_raw(char *msg)
101 {
102   perror_exit("%s", msg);
103 }
104
105 // Keep reading until full or EOF
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
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.
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
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.
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
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
277 long long estrtol(char *str, char **end, int base)
278 {
279   errno = 0;
280
281   return strtoll(str, end, base);
282 }
283
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.)
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
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
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
338 // Convert utf8 sequence to a unicode wide character
339 int utf8towc(wchar_t *wc, char *str, unsigned len)
340 {
341   unsigned result, mask, first;
342   char *s, c;
343
344   // fast path ASCII
345   if (len && *str<128) return !!(*wc = *str);
346
347   result = first = *(s = str++);
348   if (result<0xc2 || result>0xf4) return -1;
349   for (mask = 6; (first&0xc0)==0xc0; mask += 5, first <<= 1) {
350     if (!--len) return -2;
351     if (((c = *(str++))&0xc0) != 0x80) return -1;
352     result = (result<<6)|(c&0x3f);
353   }
354   result &= (1<<mask)-1;
355   c = str-s;
356
357   // Avoid overlong encodings
358   if (result<(unsigned []){0x80,0x800,0x10000}[c-2]) return -1;
359
360   // Limit unicode so it can't encode anything UTF-16 can't.
361   if (result>0x10ffff || (result>=0xd800 && result<=0xdfff)) return -1;
362   *wc = result;
363
364   return str-s;
365 }
366
367 char *strlower(char *s)
368 {
369   char *try, *new;
370
371   if (!CFG_TOYBOX_I18N) {
372     try = new = xstrdup(s);
373     for (; *s; s++) *(new++) = tolower(*s);
374   } else {
375     // I can't guarantee the string _won't_ expand during reencoding, so...?
376     try = new = xmalloc(strlen(s)*2+1);
377
378     while (*s) {
379       wchar_t c;
380       int len = utf8towc(&c, s, MB_CUR_MAX);
381
382       if (len < 1) *(new++) = *(s++);
383       else {
384         s += len;
385         // squash title case too
386         c = towlower(c);
387
388         // if we had a valid utf8 sequence, convert it to lower case, and can't
389         // encode back to utf8, something is wrong with your libc. But just
390         // in case somebody finds an exploit...
391         len = wcrtomb(new, c, 0);
392         if (len < 1) error_exit("bad utf8 %x", (int)c);
393         new += len;
394       }
395     }
396     *new = 0;
397   }
398
399   return try;
400 }
401
402 // strstr but returns pointer after match
403 char *strafter(char *haystack, char *needle)
404 {
405   char *s = strstr(haystack, needle);
406
407   return s ? s+strlen(needle) : s;
408 }
409
410 // Remove trailing \n
411 char *chomp(char *s)
412 {
413   char *p = strrchr(s, '\n');
414
415   if (p && !p[1]) *p = 0;
416   return s;
417 }
418
419 int unescape(char c)
420 {
421   char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
422   int idx = stridx(from, c);
423
424   return (idx == -1) ? 0 : to[idx];
425 }
426
427 // If string ends with suffix return pointer to start of suffix in string,
428 // else NULL
429 char *strend(char *str, char *suffix)
430 {
431   long a = strlen(str), b = strlen(suffix);
432
433   if (a>b && !strcmp(str += a-b, suffix)) return str;
434
435   return 0;
436 }
437
438 // If *a starts with b, advance *a past it and return 1, else return 0;
439 int strstart(char **a, char *b)
440 {
441   int len = strlen(b), i = !strncmp(*a, b, len);
442
443   if (i) *a += len;
444
445   return i;
446 }
447
448 // Return how long the file at fd is, if there's any way to determine it.
449 off_t fdlength(int fd)
450 {
451   struct stat st;
452   off_t base = 0, range = 1, expand = 1, old;
453
454   if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
455
456   // If the ioctl works for this, return it.
457   // TODO: is blocksize still always 512, or do we stat for it?
458   // unsigned int size;
459   // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
460
461   // If not, do a binary search for the last location we can read.  (Some
462   // block devices don't do BLKGETSIZE right.)  This should probably have
463   // a CONFIG option...
464
465   // If not, do a binary search for the last location we can read.
466
467   old = lseek(fd, 0, SEEK_CUR);
468   do {
469     char temp;
470     off_t pos = base + range / 2;
471
472     if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
473       off_t delta = (pos + 1) - base;
474
475       base += delta;
476       if (expand) range = (expand <<= 1) - base;
477       else range -= delta;
478     } else {
479       expand = 0;
480       range = pos - base;
481     }
482   } while (range > 0);
483
484   lseek(fd, old, SEEK_SET);
485
486   return base;
487 }
488
489 // Read contents of file as a single nul-terminated string.
490 // measure file size if !len, allocate buffer if !buf
491 // Existing buffers need len in *plen
492 // Returns amount of data read in *plen
493 char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
494 {
495   off_t len, rlen;
496   int fd;
497   char *buf, *rbuf;
498
499   // Unsafe to probe for size with a supplied buffer, don't ever do that.
500   if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
501
502   if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
503
504   // If we dunno the length, probe it. If we can't probe, start with 1 page.
505   if (!*plen) {
506     if ((len = fdlength(fd))>0) *plen = len;
507     else len = 4096;
508   } else len = *plen-1;
509
510   if (!ibuf) buf = xmalloc(len+1);
511   else buf = ibuf;
512
513   for (rbuf = buf;;) {
514     rlen = readall(fd, rbuf, len);
515     if (*plen || rlen<len) break;
516
517     // If reading unknown size, expand buffer by 1.5 each time we fill it up.
518     rlen += rbuf-buf;
519     buf = xrealloc(buf, len = (rlen*3)/2);
520     rbuf = buf+rlen;
521     len -= rlen;
522   }
523   *plen = len = rlen+(rbuf-buf);
524   close(fd);
525
526   if (rlen<0) {
527     if (ibuf != buf) free(buf);
528     buf = 0;
529   } else buf[len] = 0;
530
531   return buf;
532 }
533
534 char *readfile(char *name, char *ibuf, off_t len)
535 {
536   return readfileat(AT_FDCWD, name, ibuf, &len);
537 }
538
539 // Sleep for this many thousandths of a second
540 void msleep(long miliseconds)
541 {
542   struct timespec ts;
543
544   ts.tv_sec = miliseconds/1000;
545   ts.tv_nsec = (miliseconds%1000)*1000000;
546   nanosleep(&ts, &ts);
547 }
548
549 // return 1<<x of highest bit set
550 int highest_bit(unsigned long l)
551 {
552   int i;
553
554   for (i = 0; l; i++) l >>= 1;
555
556   return i-1;
557 }
558
559 // Inefficient, but deals with unaligned access
560 int64_t peek_le(void *ptr, unsigned size)
561 {
562   int64_t ret = 0;
563   char *c = ptr;
564   int i;
565
566   for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
567   return ret;
568 }
569
570 int64_t peek_be(void *ptr, unsigned size)
571 {
572   int64_t ret = 0;
573   char *c = ptr;
574   int i;
575
576   for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
577   return ret;
578 }
579
580 int64_t peek(void *ptr, unsigned size)
581 {
582   return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
583 }
584
585 void poke(void *ptr, uint64_t val, int size)
586 {
587   if (size & 8) {
588     volatile uint64_t *p = (uint64_t *)ptr;
589     *p = val;
590   } else if (size & 4) {
591     volatile int *p = (int *)ptr;
592     *p = val;
593   } else if (size & 2) {
594     volatile short *p = (short *)ptr;
595     *p = val;
596   } else {
597     volatile char *p = (char *)ptr;
598     *p = val;
599   }
600 }
601
602 // Iterate through an array of files, opening each one and calling a function
603 // on that filehandle and name. The special filename "-" means stdin if
604 // flags is O_RDONLY, stdout otherwise. An empty argument list calls
605 // function() on just stdin/stdout.
606 //
607 // Note: pass O_CLOEXEC to automatically close filehandles when function()
608 // returns, otherwise filehandles must be closed by function().
609 // pass WARN_ONLY to produce warning messages about files it couldn't
610 // open/create, and skip them. Otherwise function is called with fd -1.
611 void loopfiles_rw(char **argv, int flags, int permissions,
612   void (*function)(int fd, char *name))
613 {
614   int fd, failok = !(flags&WARN_ONLY);
615
616   flags &= ~WARN_ONLY;
617
618   // If no arguments, read from stdin.
619   if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
620   else do {
621     // Filename "-" means read from stdin.
622     // Inability to open a file prints a warning, but doesn't exit.
623
624     if (!strcmp(*argv, "-")) fd = 0;
625     else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
626       perror_msg_raw(*argv);
627       continue;
628     }
629     function(fd, *argv);
630     if ((flags & O_CLOEXEC) && fd) close(fd);
631   } while (*++argv);
632 }
633
634 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
635 void loopfiles(char **argv, void (*function)(int fd, char *name))
636 {
637   loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
638 }
639
640 // call loopfiles with do_lines()
641 static void (*do_lines_bridge)(char **pline, long len);
642 static void loopfile_lines_bridge(int fd, char *name)
643 {
644   do_lines(fd, do_lines_bridge);
645 }
646
647 void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
648 {
649   do_lines_bridge = function;
650   loopfiles(argv, loopfile_lines_bridge);
651 }
652
653 // Slow, but small.
654
655 char *get_rawline(int fd, long *plen, char end)
656 {
657   char c, *buf = NULL;
658   long len = 0;
659
660   for (;;) {
661     if (1>read(fd, &c, 1)) break;
662     if (!(len & 63)) buf=xrealloc(buf, len+65);
663     if ((buf[len++]=c) == end) break;
664   }
665   if (buf) buf[len]=0;
666   if (plen) *plen = len;
667
668   return buf;
669 }
670
671 char *get_line(int fd)
672 {
673   long len;
674   char *buf = get_rawline(fd, &len, '\n');
675
676   if (buf && buf[--len]=='\n') buf[len]=0;
677
678   return buf;
679 }
680
681 int wfchmodat(int fd, char *name, mode_t mode)
682 {
683   int rc = fchmodat(fd, name, mode, 0);
684
685   if (rc) {
686     perror_msg("chmod '%s' to %04o", name, mode);
687     toys.exitval=1;
688   }
689   return rc;
690 }
691
692 static char *tempfile2zap;
693 static void tempfile_handler(void)
694 {
695   if (1 < (long)tempfile2zap) unlink(tempfile2zap);
696 }
697
698 // Open a temporary file to copy an existing file into.
699 int copy_tempfile(int fdin, char *name, char **tempname)
700 {
701   struct stat statbuf;
702   int fd;
703   int ignored __attribute__((__unused__));
704
705   *tempname = xmprintf("%s%s", name, "XXXXXX");
706   if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
707   if (!tempfile2zap) sigatexit(tempfile_handler);
708   tempfile2zap = *tempname;
709
710   // Set permissions of output file (ignoring errors, usually due to nonroot)
711
712   fstat(fdin, &statbuf);
713   fchmod(fd, statbuf.st_mode);
714
715   // We chmod before chown, which strips the suid bit. Caller has to explicitly
716   // switch it back on if they want to keep suid.
717
718   // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
719   // this but it's _supposed_ to fail when we're not root.
720   ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
721
722   return fd;
723 }
724
725 // Abort the copy and delete the temporary file.
726 void delete_tempfile(int fdin, int fdout, char **tempname)
727 {
728   close(fdin);
729   close(fdout);
730   if (*tempname) unlink(*tempname);
731   tempfile2zap = (char *)1;
732   free(*tempname);
733   *tempname = NULL;
734 }
735
736 // Copy the rest of the data and replace the original with the copy.
737 void replace_tempfile(int fdin, int fdout, char **tempname)
738 {
739   char *temp = xstrdup(*tempname);
740
741   temp[strlen(temp)-6]=0;
742   if (fdin != -1) {
743     xsendfile(fdin, fdout);
744     xclose(fdin);
745   }
746   xclose(fdout);
747   rename(*tempname, temp);
748   tempfile2zap = (char *)1;
749   free(*tempname);
750   free(temp);
751   *tempname = NULL;
752 }
753
754 // Create a 256 entry CRC32 lookup table.
755
756 void crc_init(unsigned int *crc_table, int little_endian)
757 {
758   unsigned int i;
759
760   // Init the CRC32 table (big endian)
761   for (i=0; i<256; i++) {
762     unsigned int j, c = little_endian ? i : i<<24;
763     for (j=8; j; j--)
764       if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
765       else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
766     crc_table[i] = c;
767   }
768 }
769
770 // Init base64 table
771
772 void base64_init(char *p)
773 {
774   int i;
775
776   for (i = 'A'; i != ':'; i++) {
777     if (i == 'Z'+1) i = 'a';
778     if (i == 'z'+1) i = '0';
779     *(p++) = i;
780   }
781   *(p++) = '+';
782   *(p++) = '/';
783 }
784
785 int yesno(int def)
786 {
787   char buf;
788
789   fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
790   fflush(stderr);
791   while (fread(&buf, 1, 1, stdin)) {
792     int new;
793
794     // The letter changes the value, the newline (or space) returns it.
795     if (isspace(buf)) break;
796     if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
797   }
798
799   return def;
800 }
801
802 struct signame {
803   int num;
804   char *name;
805 };
806
807 // Signals required by POSIX 2008:
808 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
809
810 #define SIGNIFY(x) {SIG##x, #x}
811
812 static struct signame signames[] = {
813   SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
814   SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
815   SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
816   SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
817   SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
818
819   // Start of non-terminal signals
820
821   SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
822   SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
823 };
824
825 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
826 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
827
828 // Handler that sets toys.signal, and writes to toys.signalfd if set
829 void generic_signal(int sig)
830 {
831   if (toys.signalfd) {
832     char c = sig;
833
834     writeall(toys.signalfd, &c, 1);
835   }
836   toys.signal = sig;
837 }
838
839 void exit_signal(int sig)
840 {
841   if (sig) toys.exitval = sig|128;
842   xexit();
843 }
844
845 // Install the same handler on every signal that defaults to killing the
846 // process, calling the handler on the way out. Calling multiple times
847 // adds the handlers to a list, to be called in order.
848 void sigatexit(void *handler)
849 {
850   struct arg_list *al = xmalloc(sizeof(struct arg_list));
851   int i;
852
853   for (i=0; signames[i].num != SIGCHLD; i++)
854     signal(signames[i].num, exit_signal);
855   al->next = toys.xexit;
856   al->arg = handler;
857   toys.xexit = al;
858 }
859
860 // Convert name to signal number.  If name == NULL print names.
861 int sig_to_num(char *pidstr)
862 {
863   int i;
864
865   if (pidstr) {
866     char *s;
867
868     i = estrtol(pidstr, &s, 10);
869     if (!errno && !*s) return i;
870
871     if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
872   }
873   for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
874     if (!pidstr) xputs(signames[i].name);
875     else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
876
877   return -1;
878 }
879
880 char *num_to_sig(int sig)
881 {
882   int i;
883
884   for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
885     if (signames[i].num == sig) return signames[i].name;
886   return NULL;
887 }
888
889 // premute mode bits based on posix mode strings.
890 mode_t string_to_mode(char *modestr, mode_t mode)
891 {
892   char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
893        *s, *str = modestr;
894   mode_t extrabits = mode & ~(07777);
895
896   // Handle octal mode
897   if (isdigit(*str)) {
898     mode = estrtol(str, &s, 8);
899     if (errno || *s || (mode & ~(07777))) goto barf;
900
901     return mode | extrabits;
902   }
903
904   // Gaze into the bin of permission...
905   for (;;) {
906     int i, j, dowho, dohow, dowhat, amask;
907
908     dowho = dohow = dowhat = amask = 0;
909
910     // Find the who, how, and what stanzas, in that order
911     while (*str && (s = strchr(whos, *str))) {
912       dowho |= 1<<(s-whos);
913       str++;
914     }
915     // If who isn't specified, like "a" but honoring umask.
916     if (!dowho) {
917       dowho = 8;
918       umask(amask=umask(0));
919     }
920     if (!*str || !(s = strchr(hows, *str))) goto barf;
921     dohow = *(str++);
922
923     if (!dohow) goto barf;
924     while (*str && (s = strchr(whats, *str))) {
925       dowhat |= 1<<(s-whats);
926       str++;
927     }
928
929     // Convert X to x for directory or if already executable somewhere
930     if ((dowhat&32) &&  (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
931
932     // Copy mode from another category?
933     if (!dowhat && *str && (s = strchr(whys, *str))) {
934       dowhat = (mode>>(3*(s-whys)))&7;
935       str++;
936     }
937
938     // Are we ready to do a thing yet?
939     if (*str && *(str++) != ',') goto barf;
940
941     // Ok, apply the bits to the mode.
942     for (i=0; i<4; i++) {
943       for (j=0; j<3; j++) {
944         mode_t bit = 0;
945         int where = 1<<((3*i)+j);
946
947         if (amask & where) continue;
948
949         // Figure out new value at this location
950         if (i == 3) {
951           // suid/sticky bit.
952           if (j) {
953             if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
954           } else if (dowhat & 16) bit++;
955         } else {
956           if (!(dowho&(8|(1<<i)))) continue;
957           if (dowhat&(1<<j)) bit++;
958         }
959
960         // When selection active, modify bit
961
962         if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
963         if (bit && dohow != '-') mode |= where;
964       }
965     }
966
967     if (!*str) break;
968   }
969
970   return mode|extrabits;
971 barf:
972   error_exit("bad mode '%s'", modestr);
973 }
974
975 // Format access mode into a drwxrwxrwx string
976 void mode_to_string(mode_t mode, char *buf)
977 {
978   char c, d;
979   int i, bit;
980
981   buf[10]=0;
982   for (i=0; i<9; i++) {
983     bit = mode & (1<<i);
984     c = i%3;
985     if (!c && (mode & (1<<((d=i/3)+9)))) {
986       c = "tss"[d];
987       if (!bit) c &= ~0x20;
988     } else c = bit ? "xwr"[c] : '-';
989     buf[9-i] = c;
990   }
991
992   if (S_ISDIR(mode)) c = 'd';
993   else if (S_ISBLK(mode)) c = 'b';
994   else if (S_ISCHR(mode)) c = 'c';
995   else if (S_ISLNK(mode)) c = 'l';
996   else if (S_ISFIFO(mode)) c = 'p';
997   else if (S_ISSOCK(mode)) c = 's';
998   else c = '-';
999   *buf = c;
1000 }
1001
1002 // basename() can modify its argument or return a pointer to a constant string
1003 // This just gives after the last '/' or the whole stirng if no /
1004 char *getbasename(char *name)
1005 {
1006   char *s = strrchr(name, '/');
1007
1008   if (s) return s+1;
1009
1010   return name;
1011 }
1012
1013 // Execute a callback for each PID that matches a process name from a list.
1014 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
1015 {
1016   DIR *dp;
1017   struct dirent *entry;
1018
1019   if (!(dp = opendir("/proc"))) perror_exit("no /proc");
1020
1021   while ((entry = readdir(dp))) {
1022     unsigned u = atoi(entry->d_name);
1023     char *cmd = 0, *comm, **cur;
1024     off_t len;
1025
1026     if (!u) continue;
1027
1028     // Comm is original name of executable (argv[0] could be #! interpreter)
1029     // but it's limited to 15 characters
1030     sprintf(libbuf, "/proc/%u/comm", u);
1031     len = sizeof(libbuf);
1032     if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
1033       continue;
1034     if (libbuf[len-1] == '\n') libbuf[--len] = 0;
1035
1036     for (cur = names; *cur; cur++) {
1037       struct stat st1, st2;
1038       char *bb = basename(*cur);
1039       off_t len;
1040
1041       // fast path: only matching a filename (no path) that fits in comm
1042       if (strncmp(comm, bb, 15)) continue;
1043       len = strlen(bb);
1044       if (bb==*cur && len<16) goto match;
1045
1046       // If we have a path to existing file only match if same inode
1047       if (bb!=*cur && !stat(*cur, &st1)) {
1048         char buf[32];
1049
1050         sprintf(buf, "/proc/%u/exe", u);
1051         if (stat(buf, &st1)) continue;
1052         if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) continue;
1053         goto match;
1054       }
1055
1056       // Nope, gotta read command line to confirm
1057       if (!cmd) {
1058         sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1059         len = sizeof(libbuf)-17;
1060         if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1061         // readfile only guarnatees one null terminator and we need two
1062         // (yes the kernel should do this for us, don't care)
1063         cmd[len] = 0;
1064       }
1065       if (!strcmp(bb, basename(cmd))) goto match;
1066       if (bb!=*cur && !strcmp(bb, basename(cmd+strlen(cmd)+1))) goto match;
1067       continue;
1068 match:
1069       if (callback(u, *cur)) break;
1070     }
1071   }
1072   closedir(dp);
1073 }
1074
1075 // display first few digits of number with power of two units
1076 int human_readable(char *buf, unsigned long long num, int style)
1077 {
1078   unsigned long long snap = 0;
1079   int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
1080
1081   // Divide rounding up until we have 3 or fewer digits. Since the part we
1082   // print is decimal, the test is 999 even when we divide by 1024.
1083   // We can't run out of units because 2<<64 is 18 exabytes.
1084   // test 5675 is 5.5k not 5.6k.
1085   for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
1086   len = sprintf(buf, "%llu", num);
1087   if (unit && len == 1) {
1088     // Redo rounding for 1.2M case, this works with and without HR_1000.
1089     num = snap/divisor;
1090     snap -= num*divisor;
1091     snap = ((snap*100)+50)/divisor;
1092     snap /= 10;
1093     len = sprintf(buf, "%llu.%llu", num, snap);
1094   }
1095   if (style & HR_SPACE) buf[len++] = ' ';
1096   if (unit) {
1097     unit = " kMGTPE"[unit];
1098
1099     if (!(style&HR_1000)) unit = toupper(unit);
1100     buf[len++] = unit;
1101   } else if (style & HR_B) buf[len++] = 'B';
1102   buf[len] = 0;
1103
1104   return len;
1105 }
1106
1107 // The qsort man page says you can use alphasort, the posix committee
1108 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1109 // So just do our own. (The const is entirely to humor the stupid compiler.)
1110 int qstrcmp(const void *a, const void *b)
1111 {
1112   return strcmp(*(char **)a, *(char **)b);
1113 }
1114
1115 // According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
1116 // we should generate a uuid structure by reading a clock with 100 nanosecond
1117 // precision, normalizing it to the start of the gregorian calendar in 1582,
1118 // and looking up our eth0 mac address.
1119 //
1120 // On the other hand, we have 128 bits to come up with a unique identifier, of
1121 // which 6 have a defined value.  /dev/urandom it is.
1122
1123 void create_uuid(char *uuid)
1124 {
1125   // Read 128 random bits
1126   int fd = xopenro("/dev/urandom");
1127   xreadall(fd, uuid, 16);
1128   close(fd);
1129
1130   // Claim to be a DCE format UUID.
1131   uuid[6] = (uuid[6] & 0x0F) | 0x40;
1132   uuid[8] = (uuid[8] & 0x3F) | 0x80;
1133
1134   // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1135   // set bit 1 of the node ID, which is the mac multicast bit.  This means we
1136   // should never collide with anybody actually using a macaddr.
1137   uuid[11] |= 128;
1138 }
1139
1140 char *show_uuid(char *uuid)
1141 {
1142   char *out = libbuf;
1143   int i;
1144
1145   for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1146   *out = 0;
1147
1148   return libbuf;
1149 }
1150
1151 // Returns pointer to letter at end, 0 if none. *start = initial %
1152 char *next_printf(char *s, char **start)
1153 {
1154   for (; *s; s++) {
1155     if (*s != '%') continue;
1156     if (*++s == '%') continue;
1157     if (start) *start = s-1;
1158     while (0 <= stridx("0'#-+ ", *s)) s++;
1159     while (isdigit(*s)) s++;
1160     if (*s == '.') s++;
1161     while (isdigit(*s)) s++;
1162
1163     return s;
1164   }
1165
1166   return 0;
1167 }
1168
1169 // Posix inexplicably hasn't got this, so find str in line.
1170 char *strnstr(char *line, char *str)
1171 {
1172   long len = strlen(str);
1173   char *s;
1174
1175   for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break;
1176
1177   return *s ? s : 0;
1178 }
1179
1180 int dev_minor(int dev)
1181 {
1182   return ((dev&0xfff00000)>>12)|(dev&0xff);
1183 }
1184
1185 int dev_major(int dev)
1186 {
1187   return (dev&0xfff00)>>8;
1188 }
1189
1190 int dev_makedev(int major, int minor)
1191 {
1192   return (minor&0xff)|((major&0xfff)<<8)|((minor&0xfff00)<<12);
1193 }
1194
1195 // Return cached passwd entries.
1196 struct passwd *bufgetpwuid(uid_t uid)
1197 {
1198   struct pwuidbuf_list {
1199     struct pwuidbuf_list *next;
1200     struct passwd pw;
1201   } *list;
1202   struct passwd *temp;
1203   static struct pwuidbuf_list *pwuidbuf;
1204
1205   for (list = pwuidbuf; list; list = list->next)
1206     if (list->pw.pw_uid == uid) return &(list->pw);
1207
1208   list = xmalloc(512);
1209   list->next = pwuidbuf;
1210
1211   errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1212     512-sizeof(*list), &temp);
1213   if (!temp) {
1214     free(list);
1215
1216     return 0;
1217   }
1218   pwuidbuf = list;
1219
1220   return &list->pw;
1221 }
1222
1223 // Return cached passwd entries.
1224 struct group *bufgetgrgid(gid_t gid)
1225 {
1226   struct grgidbuf_list {
1227     struct grgidbuf_list *next;
1228     struct group gr;
1229   } *list;
1230   struct group *temp;
1231   static struct grgidbuf_list *grgidbuf;
1232
1233   for (list = grgidbuf; list; list = list->next)
1234     if (list->gr.gr_gid == gid) return &(list->gr);
1235
1236   list = xmalloc(512);
1237   list->next = grgidbuf;
1238
1239   errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1240     512-sizeof(*list), &temp);
1241   if (!temp) {
1242     free(list);
1243
1244     return 0;
1245   }
1246   grgidbuf = list;
1247
1248   return &list->gr;
1249 }
1250
1251 // Always null terminates, returns 0 for failure, len for success
1252 int readlinkat0(int dirfd, char *path, char *buf, int len)
1253 {
1254   if (!len) return 0;
1255
1256   len = readlinkat(dirfd, path, buf, len-1);
1257   if (len<1) return 0;
1258   buf[len] = 0;
1259
1260   return len;
1261 }
1262
1263 int readlink0(char *path, char *buf, int len)
1264 {
1265   return readlinkat0(AT_FDCWD, path, buf, len);
1266 }
1267
1268 // Do regex matching handling embedded NUL bytes in string (hence extra len
1269 // argument). Note that neither the pattern nor the match can currently include
1270 // NUL bytes (even with wildcards) and string must be null terminated at
1271 // string[len]. But this can find a match after the first NUL.
1272 int regexec0(regex_t *preg, char *string, long len, int nmatch,
1273   regmatch_t pmatch[], int eflags)
1274 {
1275   char *s = string;
1276
1277   for (;;) {
1278     long ll = 0;
1279     int rc;
1280
1281     while (len && !*s) {
1282       s++;
1283       len--;
1284     }
1285     while (s[ll] && ll<len) ll++;
1286
1287     rc = regexec(preg, s, nmatch, pmatch, eflags);
1288     if (!rc) {
1289       for (rc = 0; rc<nmatch && pmatch[rc].rm_so!=-1; rc++) {
1290         pmatch[rc].rm_so += s-string;
1291         pmatch[rc].rm_eo += s-string;
1292       }
1293
1294       return 0;
1295     }
1296     if (ll==len) return rc;
1297
1298     s += ll;
1299     len -= ll;
1300   }
1301 }
1302
1303 // Return user name or string representation of number, returned buffer
1304 // lasts until next call.
1305 char *getusername(uid_t uid)
1306 {
1307   struct passwd *pw = bufgetpwuid(uid);
1308   static char unum[12];
1309
1310   sprintf(unum, "%u", (unsigned)uid);
1311   return pw ? pw->pw_name : unum;
1312 }
1313
1314 // Return group name or string representation of number, returned buffer
1315 // lasts until next call.
1316 char *getgroupname(gid_t gid)
1317 {
1318   struct group *gr = bufgetgrgid(gid);
1319   static char gnum[12];
1320
1321   sprintf(gnum, "%u", (unsigned)gid);
1322   return gr ? gr->gr_name : gnum;
1323 }
1324
1325 // Iterate over lines in file, calling function. Function can write 0 to
1326 // the line pointer if they want to keep it, or 1 to terminate processing,
1327 // otherwise line is freed. Passed file descriptor is closed at the end.
1328 void do_lines(int fd, void (*call)(char **pline, long len))
1329 {
1330   FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1331
1332   for (;;) {
1333     char *line = 0;
1334     ssize_t len;
1335
1336     len = getline(&line, (void *)&len, fp);
1337     if (len > 0) {
1338       call(&line, len);
1339       if (line == (void *)1) break;
1340       free(line);
1341     } else break;
1342   }
1343
1344   if (fd) fclose(fp);
1345 }
1346
1347 // Returns the number of bytes taken by the environment variables. For use
1348 // when calculating the maximum bytes of environment+argument data that can
1349 // be passed to exec for find(1) and xargs(1).
1350 long environ_bytes()
1351 {
1352   long bytes = sizeof(char *);
1353   char **ev;
1354
1355   for (ev = environ; *ev; ev++)
1356     bytes += sizeof(char *) + strlen(*ev) + 1;
1357   return bytes;
1358 }