lib.c 37 KB

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