lib.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  1. /* lib.c - various reusable stuff.
  2. *
  3. * Copyright 2006 Rob Landley <rob@landley.net>
  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++;
  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 = s+strlen(s);
  363. while (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. // Return how long the file at fd is, if there's any way to determine it.
  414. off_t fdlength(int fd)
  415. {
  416. struct stat st;
  417. off_t base = 0, range = 1, expand = 1, old;
  418. unsigned long long size;
  419. if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
  420. // If the ioctl works for this, return it.
  421. if (get_block_device_size(fd, &size)) return size;
  422. // If not, do a binary search for the last location we can read. (Some
  423. // block devices don't do BLKGETSIZE right.) This should probably have
  424. // a CONFIG option...
  425. old = lseek(fd, 0, SEEK_CUR);
  426. do {
  427. char temp;
  428. off_t pos = base + range / 2;
  429. if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
  430. off_t delta = (pos + 1) - base;
  431. base += delta;
  432. if (expand) range = (expand <<= 1) - base;
  433. else range -= delta;
  434. } else {
  435. expand = 0;
  436. range = pos - base;
  437. }
  438. } while (range > 0);
  439. lseek(fd, old, SEEK_SET);
  440. return base;
  441. }
  442. char *readfd(int fd, char *ibuf, off_t *plen)
  443. {
  444. off_t len, rlen;
  445. char *buf, *rbuf;
  446. // Unsafe to probe for size with a supplied buffer, don't ever do that.
  447. if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
  448. // If we dunno the length, probe it. If we can't probe, start with 1 page.
  449. if (!*plen) {
  450. if ((len = fdlength(fd))>0) *plen = len;
  451. else len = 4096;
  452. } else len = *plen-1;
  453. if (!ibuf) buf = xmalloc(len+1);
  454. else buf = ibuf;
  455. for (rbuf = buf;;) {
  456. rlen = readall(fd, rbuf, len);
  457. if (*plen || rlen<len) break;
  458. // If reading unknown size, expand buffer by 1.5 each time we fill it up.
  459. rlen += rbuf-buf;
  460. buf = xrealloc(buf, len = (rlen*3)/2);
  461. rbuf = buf+rlen;
  462. len -= rlen;
  463. }
  464. *plen = len = rlen+(rbuf-buf);
  465. if (rlen<0) {
  466. if (ibuf != buf) free(buf);
  467. buf = 0;
  468. } else buf[len] = 0;
  469. return buf;
  470. }
  471. // Read contents of file as a single nul-terminated string.
  472. // measure file size if !len, allocate buffer if !buf
  473. // Existing buffers need len in *plen
  474. // Returns amount of data read in *plen
  475. char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
  476. {
  477. if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0;
  478. ibuf = readfd(dirfd, ibuf, plen);
  479. close(dirfd);
  480. return ibuf;
  481. }
  482. char *readfile(char *name, char *ibuf, off_t len)
  483. {
  484. return readfileat(AT_FDCWD, name, ibuf, &len);
  485. }
  486. // Sleep for this many thousandths of a second
  487. void msleep(long milliseconds)
  488. {
  489. struct timespec ts;
  490. ts.tv_sec = milliseconds/1000;
  491. ts.tv_nsec = (milliseconds%1000)*1000000;
  492. nanosleep(&ts, &ts);
  493. }
  494. // Adjust timespec by nanosecond offset
  495. void nanomove(struct timespec *ts, long long offset)
  496. {
  497. long long nano = ts->tv_nsec + offset, secs = nano/1000000000;
  498. ts->tv_sec += secs;
  499. nano %= 1000000000;
  500. if (nano<0) {
  501. ts->tv_sec--;
  502. nano += 1000000000;
  503. }
  504. ts->tv_nsec = nano;
  505. }
  506. // return difference between two timespecs in nanosecs
  507. long long nanodiff(struct timespec *old, struct timespec *new)
  508. {
  509. return (new->tv_sec - old->tv_sec)*1000000000LL+(new->tv_nsec - old->tv_nsec);
  510. }
  511. // return 1<<x of highest bit set
  512. int highest_bit(unsigned long l)
  513. {
  514. int i;
  515. for (i = 0; l; i++) l >>= 1;
  516. return i-1;
  517. }
  518. // Inefficient, but deals with unaligned access
  519. int64_t peek_le(void *ptr, unsigned size)
  520. {
  521. int64_t ret = 0;
  522. char *c = ptr;
  523. int i;
  524. for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
  525. return ret;
  526. }
  527. int64_t peek_be(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 = (ret<<8)|(c[i]&0xff);
  533. return ret;
  534. }
  535. int64_t peek(void *ptr, unsigned size)
  536. {
  537. return (IS_BIG_ENDIAN ? peek_be : peek_le)(ptr, size);
  538. }
  539. void poke_le(void *ptr, long long val, unsigned size)
  540. {
  541. char *c = ptr;
  542. while (size--) {
  543. *c++ = val&255;
  544. val >>= 8;
  545. }
  546. }
  547. void poke_be(void *ptr, long long val, unsigned size)
  548. {
  549. char *c = ptr + size;
  550. while (size--) {
  551. *--c = val&255;
  552. val >>=8;
  553. }
  554. }
  555. void poke(void *ptr, long long val, unsigned size)
  556. {
  557. (IS_BIG_ENDIAN ? poke_be : poke_le)(ptr, val, size);
  558. }
  559. // Iterate through an array of files, opening each one and calling a function
  560. // on that filehandle and name. The special filename "-" means stdin if
  561. // flags is O_RDONLY, stdout otherwise. An empty argument list calls
  562. // function() on just stdin/stdout.
  563. //
  564. // Note: pass O_CLOEXEC to automatically close filehandles when function()
  565. // returns, otherwise filehandles must be closed by function().
  566. // pass WARN_ONLY to produce warning messages about files it couldn't
  567. // open/create, and skip them. Otherwise function is called with fd -1.
  568. void loopfiles_rw(char **argv, int flags, int permissions,
  569. void (*function)(int fd, char *name))
  570. {
  571. int fd, failok = !(flags&WARN_ONLY), anyway = flags & LOOPFILES_ANYWAY;
  572. flags &= ~(WARN_ONLY|LOOPFILES_ANYWAY);
  573. // If no arguments, read from stdin.
  574. if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
  575. else do {
  576. // Filename "-" means read from stdin.
  577. // Inability to open a file prints a warning, but doesn't exit.
  578. if (!strcmp(*argv, "-")) fd = 0;
  579. else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
  580. perror_msg_raw(*argv);
  581. if (!anyway) continue;
  582. }
  583. function(fd, *argv);
  584. if ((flags & O_CLOEXEC) && fd>0) close(fd);
  585. } while (*++argv);
  586. }
  587. // Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
  588. void loopfiles(char **argv, void (*function)(int fd, char *name))
  589. {
  590. loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
  591. }
  592. // glue to call do_lines() from loopfiles
  593. static void (*do_lines_bridge)(char **pline, long len);
  594. static void loopfile_lines_bridge(int fd, char *name)
  595. {
  596. do_lines(fd, '\n', do_lines_bridge);
  597. }
  598. void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
  599. {
  600. do_lines_bridge = function;
  601. // No O_CLOEXEC because we need to call fclose.
  602. loopfiles_rw(argv, O_RDONLY|WARN_ONLY, 0, loopfile_lines_bridge);
  603. }
  604. int wfchmodat(int fd, char *name, mode_t mode)
  605. {
  606. int rc = fchmodat(fd, name, mode, 0);
  607. if (rc) {
  608. perror_msg("chmod '%s' to %04o", name, mode);
  609. toys.exitval=1;
  610. }
  611. return rc;
  612. }
  613. static char *tempfile2zap;
  614. static void tempfile_handler(void)
  615. {
  616. if (1 < (long)tempfile2zap) unlink(tempfile2zap);
  617. }
  618. // Open a temporary file to copy an existing file into.
  619. int copy_tempfile(int fdin, char *name, char **tempname)
  620. {
  621. struct stat statbuf;
  622. int fd = xtempfile(name, tempname), ignored __attribute__((__unused__));
  623. // Record tempfile for exit cleanup if interrupted
  624. if (!tempfile2zap) sigatexit(tempfile_handler);
  625. tempfile2zap = *tempname;
  626. // Set permissions of output file.
  627. if (!fstat(fdin, &statbuf)) fchmod(fd, statbuf.st_mode);
  628. // We chmod before chown, which strips the suid bit. Caller has to explicitly
  629. // switch it back on if they want to keep suid.
  630. // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
  631. // this but it's _supposed_ to fail when we're not root.
  632. ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
  633. return fd;
  634. }
  635. // Abort the copy and delete the temporary file.
  636. void delete_tempfile(int fdin, int fdout, char **tempname)
  637. {
  638. close(fdin);
  639. close(fdout);
  640. if (*tempname) unlink(*tempname);
  641. tempfile2zap = (char *)1;
  642. free(*tempname);
  643. *tempname = NULL;
  644. }
  645. // Copy the rest of the data and replace the original with the copy.
  646. void replace_tempfile(int fdin, int fdout, char **tempname)
  647. {
  648. char *temp = xstrdup(*tempname);
  649. temp[strlen(temp)-6]=0;
  650. if (fdin != -1) {
  651. xsendfile(fdin, fdout);
  652. xclose(fdin);
  653. }
  654. xclose(fdout);
  655. xrename(*tempname, temp);
  656. tempfile2zap = (char *)1;
  657. free(*tempname);
  658. free(temp);
  659. *tempname = NULL;
  660. }
  661. // Create a 256 entry CRC32 lookup table.
  662. void crc_init(unsigned *crc_table, int little_endian)
  663. {
  664. unsigned int i;
  665. // Init the CRC32 table (big endian)
  666. for (i=0; i<256; i++) {
  667. unsigned int j, c = little_endian ? i : i<<24;
  668. for (j=8; j; j--)
  669. if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
  670. else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
  671. crc_table[i] = c;
  672. }
  673. }
  674. // Init base64 table
  675. void base64_init(char *p)
  676. {
  677. int i;
  678. for (i = 'A'; i != ':'; i++) {
  679. if (i == 'Z'+1) i = 'a';
  680. if (i == 'z'+1) i = '0';
  681. *(p++) = i;
  682. }
  683. *(p++) = '+';
  684. *(p++) = '/';
  685. }
  686. int yesno(int def)
  687. {
  688. return fyesno(stdin, def);
  689. }
  690. int fyesno(FILE *in, int def)
  691. {
  692. char buf;
  693. fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
  694. fflush(stderr);
  695. while (fread(&buf, 1, 1, in)) {
  696. int new;
  697. // The letter changes the value, the newline (or space) returns it.
  698. if (isspace(buf)) break;
  699. if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
  700. }
  701. return def;
  702. }
  703. // Handler that sets toys.signal, and writes to toys.signalfd if set
  704. void generic_signal(int sig)
  705. {
  706. if (toys.signalfd) {
  707. char c = sig;
  708. writeall(toys.signalfd, &c, 1);
  709. }
  710. toys.signal = sig;
  711. }
  712. void exit_signal(int sig)
  713. {
  714. if (sig) toys.exitval = sig|128;
  715. xexit();
  716. }
  717. // Install an atexit handler. Also install the same handler on every signal
  718. // that defaults to killing the process, calling the handler on the way out.
  719. // Calling multiple times adds the handlers to a list, to be called in LIFO
  720. // order.
  721. void sigatexit(void *handler)
  722. {
  723. struct arg_list *al = 0;
  724. xsignal_all_killers(handler ? exit_signal : SIG_DFL);
  725. if (handler) {
  726. al = xmalloc(sizeof(struct arg_list));
  727. al->next = toys.xexit;
  728. al->arg = handler;
  729. } else llist_traverse(toys.xexit, free);
  730. toys.xexit = al;
  731. }
  732. // Output a nicely formatted table of all the signals.
  733. void list_signals(void)
  734. {
  735. int i = 1, count = 0;
  736. unsigned cols = 80;
  737. char *name;
  738. terminal_size(&cols, 0);
  739. cols /= 16;
  740. for (; i<=NSIG; i++) {
  741. if ((name = num_to_sig(i))) {
  742. printf("%2d) SIG%-9s", i, name);
  743. if (++count % cols == 0) putchar('\n');
  744. }
  745. }
  746. putchar('\n');
  747. }
  748. // premute mode bits based on posix mode strings.
  749. mode_t string_to_mode(char *modestr, mode_t mode)
  750. {
  751. char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
  752. *s, *str = modestr;
  753. mode_t extrabits = mode & ~(07777);
  754. // Handle octal mode
  755. if (isdigit(*str)) {
  756. mode = estrtol(str, &s, 8);
  757. if (errno || *s || (mode & ~(07777))) goto barf;
  758. return mode | extrabits;
  759. }
  760. // Gaze into the bin of permission...
  761. for (;;) {
  762. int i, j, dowho, dohow, dowhat, amask;
  763. dowho = dohow = dowhat = amask = 0;
  764. // Find the who, how, and what stanzas, in that order
  765. while (*str && (s = strchr(whos, *str))) {
  766. dowho |= 1<<(s-whos);
  767. str++;
  768. }
  769. // If who isn't specified, like "a" but honoring umask.
  770. if (!dowho) {
  771. dowho = 8;
  772. umask(amask = umask(0));
  773. }
  774. // Repeated "hows" are allowed; something like "a=r+w+s" is valid.
  775. for (;;) {
  776. if (-1 == stridx(hows, dohow = *str)) goto barf;
  777. while (*++str && (s = strchr(whats, *str))) dowhat |= 1<<(s-whats);
  778. // Convert X to x for directory or if already executable somewhere
  779. if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
  780. // Copy mode from another category?
  781. if (!dowhat && -1 != (i = stridx(whys, *str))) {
  782. dowhat = (mode>>(3*i))&7;
  783. str++;
  784. }
  785. // Loop through what=xwrs and who=ogu to apply bits to the mode.
  786. for (i=0; i<4; i++) {
  787. for (j=0; j<3; j++) {
  788. mode_t bit = 0;
  789. int where = 1<<((3*i)+j);
  790. if (amask & where) continue;
  791. // Figure out new value at this location
  792. if (i == 3) {
  793. // suid and sticky
  794. if (!j) bit = dowhat&16; // o+s = t but a+s doesn't set t, hence t
  795. else if ((dowhat&8) && (dowho&(8|(1<<j)))) bit++;
  796. } else {
  797. if (!(dowho&(8|(1<<i)))) continue;
  798. else if (dowhat&(1<<j)) bit++;
  799. }
  800. // When selection active, modify bit
  801. if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
  802. if (bit && dohow != '-') mode |= where;
  803. }
  804. }
  805. if (!*str) return mode|extrabits;
  806. if (*str == ',') {
  807. str++;
  808. break;
  809. }
  810. }
  811. }
  812. barf:
  813. error_exit("bad mode '%s'", modestr);
  814. }
  815. // Format access mode into a drwxrwxrwx string
  816. void mode_to_string(mode_t mode, char *buf)
  817. {
  818. char c, d;
  819. int i, bit;
  820. buf[10]=0;
  821. for (i=0; i<9; i++) {
  822. bit = mode & (1<<i);
  823. c = i%3;
  824. if (!c && (mode & (1<<((d=i/3)+9)))) {
  825. c = "tss"[d];
  826. if (!bit) c &= ~0x20;
  827. } else c = bit ? "xwr"[c] : '-';
  828. buf[9-i] = c;
  829. }
  830. if (S_ISDIR(mode)) c = 'd';
  831. else if (S_ISBLK(mode)) c = 'b';
  832. else if (S_ISCHR(mode)) c = 'c';
  833. else if (S_ISLNK(mode)) c = 'l';
  834. else if (S_ISFIFO(mode)) c = 'p';
  835. else if (S_ISSOCK(mode)) c = 's';
  836. else c = '-';
  837. *buf = c;
  838. }
  839. // basename() can modify its argument or return a pointer to a constant string
  840. // This just gives after the last '/' or the whole stirng if no /
  841. char *getbasename(char *name)
  842. {
  843. char *s = strrchr(name, '/');
  844. if (s) return s+1;
  845. return name;
  846. }
  847. // Return pointer to xabspath(file) if file is under dir, else 0
  848. char *fileunderdir(char *file, char *dir)
  849. {
  850. char *s1 = xabspath(dir, ABS_FILE), *s2 = xabspath(file, 0), *ss = s2;
  851. int rc = s1 && s2 && strstart(&ss, s1) && (!s1[1] || s2[strlen(s1)] == '/');
  852. free(s1);
  853. if (!rc) free(s2);
  854. return rc ? s2 : 0;
  855. }
  856. // return (malloced) relative path to get from "from" to "to"
  857. char *relative_path(char *from, char *to)
  858. {
  859. char *s, *ret = 0;
  860. int i, j, k;
  861. if (!(from = xabspath(from, 0))) return 0;
  862. if (!(to = xabspath(to, 0))) goto error;
  863. // skip common directories from root
  864. for (i = j = 0; from[i] && from[i] == to[i]; i++) if (to[i] == '/') j = i+1;
  865. // count remaining destination directories
  866. for (i = j, k = 0; from[i]; i++) if (from[i] == '/') k++;
  867. if (!k) ret = xstrdup(to+j);
  868. else {
  869. s = ret = xmprintf("%*c%s", 3*k, ' ', to+j);
  870. while (k--) memcpy(s+3*k, "../", 3);
  871. }
  872. error:
  873. free(from);
  874. free(to);
  875. return ret;
  876. }
  877. // Execute a callback for each PID that matches a process name from a list.
  878. void names_to_pid(char **names, int (*callback)(pid_t pid, char *name),
  879. int scripts)
  880. {
  881. DIR *dp;
  882. struct dirent *entry;
  883. if (!(dp = opendir("/proc"))) perror_exit("no /proc");
  884. while ((entry = readdir(dp))) {
  885. unsigned u = atoi(entry->d_name);
  886. char *cmd = 0, *comm = 0, **cur;
  887. off_t len;
  888. if (!u) continue;
  889. // Comm is original name of executable (argv[0] could be #! interpreter)
  890. // but it's limited to 15 characters
  891. if (scripts) {
  892. sprintf(libbuf, "/proc/%u/comm", u);
  893. len = sizeof(libbuf);
  894. if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
  895. continue;
  896. if (libbuf[len-1] == '\n') libbuf[--len] = 0;
  897. }
  898. for (cur = names; *cur; cur++) {
  899. struct stat st1, st2;
  900. char *bb = getbasename(*cur);
  901. off_t len = strlen(bb);
  902. // Fast path: only matching a filename (no path) that fits in comm.
  903. // `len` must be 14 or less because with a full 15 bytes we don't
  904. // know whether the name fit or was truncated.
  905. if (scripts && len<=14 && bb==*cur && !strcmp(comm, bb)) goto match;
  906. // If we have a path to existing file only match if same inode
  907. if (bb!=*cur && !stat(*cur, &st1)) {
  908. char buf[32];
  909. sprintf(buf, "/proc/%u/exe", u);
  910. if (stat(buf, &st2)) continue;
  911. if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) continue;
  912. goto match;
  913. }
  914. // Nope, gotta read command line to confirm
  915. if (!cmd) {
  916. sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
  917. len = sizeof(libbuf)-17;
  918. if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
  919. // readfile only guarantees one null terminator and we need two
  920. // (yes the kernel should do this for us, don't care)
  921. cmd[len] = 0;
  922. }
  923. if (!strcmp(bb, getbasename(cmd))) goto match;
  924. if (scripts && !strcmp(bb, getbasename(cmd+strlen(cmd)+1))) goto match;
  925. continue;
  926. match:
  927. if (callback(u, *cur)) goto done;
  928. }
  929. }
  930. done:
  931. closedir(dp);
  932. }
  933. // display first "dgt" many digits of number plus unit (kilo-exabytes)
  934. int human_readable_long(char *buf, unsigned long long num, int dgt, int unit,
  935. int style)
  936. {
  937. unsigned long long snap = 0;
  938. int len, divisor = (style&HR_1000) ? 1000 : 1024;
  939. // Divide rounding up until we have 3 or fewer digits. Since the part we
  940. // print is decimal, the test is 999 even when we divide by 1024.
  941. // The largest unit we can detect is 1<<64 = 18 Exabytes, but we added
  942. // Zettabyte and Yottabyte in case "unit" starts above zero.
  943. for (;;unit++) {
  944. if ((len = snprintf(0, 0, "%llu", num))<=dgt) break;
  945. num = ((snap = num)+(divisor/2))/divisor;
  946. }
  947. if (CFG_TOYBOX_DEBUG && unit>8) return sprintf(buf, "%.*s", dgt, "TILT");
  948. len = sprintf(buf, "%llu", num);
  949. if (!(style & HR_NODOT) && unit && len == 1) {
  950. // Redo rounding for 1.2M case, this works with and without HR_1000.
  951. num = snap/divisor;
  952. snap -= num*divisor;
  953. snap = ((snap*100)+50)/divisor;
  954. snap /= 10;
  955. len = sprintf(buf, "%llu.%llu", num, snap);
  956. }
  957. if (style & HR_SPACE) buf[len++] = ' ';
  958. if (unit) {
  959. unit = " kMGTPEZY"[unit];
  960. if (!(style&HR_1000)) unit = toupper(unit);
  961. buf[len++] = unit;
  962. } else if (style & HR_B) buf[len++] = 'B';
  963. buf[len] = 0;
  964. return len;
  965. }
  966. // Give 3 digit estimate + units ala 999M or 1.7T
  967. int human_readable(char *buf, unsigned long long num, int style)
  968. {
  969. return human_readable_long(buf, num, 3, 0, style);
  970. }
  971. // The qsort man page says you can use alphasort, the posix committee
  972. // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
  973. // So just do our own. (The const is entirely to humor the stupid compiler.)
  974. int qstrcmp(const void *a, const void *b)
  975. {
  976. return strcmp(*(char **)a, *(char **)b);
  977. }
  978. // See https://tools.ietf.org/html/rfc4122, specifically section 4.4
  979. // "Algorithms for Creating a UUID from Truly Random or Pseudo-Random
  980. // Numbers".
  981. void create_uuid(char *uuid)
  982. {
  983. // "Set all the ... bits to randomly (or pseudo-randomly) chosen values".
  984. xgetrandom(uuid, 16, 0);
  985. // "Set the four most significant bits ... of the time_hi_and_version
  986. // field to the 4-bit version number [4]".
  987. uuid[6] = (uuid[6] & 0x0F) | 0x40;
  988. // "Set the two most significant bits (bits 6 and 7) of
  989. // clock_seq_hi_and_reserved to zero and one, respectively".
  990. uuid[8] = (uuid[8] & 0x3F) | 0x80;
  991. }
  992. char *show_uuid(char *uuid)
  993. {
  994. char *out = libbuf;
  995. int i;
  996. for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
  997. *out = 0;
  998. return libbuf;
  999. }
  1000. // Returns pointer to letter at end, 0 if none. *start = initial %
  1001. char *next_printf(char *s, char **start)
  1002. {
  1003. for (; *s; s++) {
  1004. if (*s != '%') continue;
  1005. if (*++s == '%') continue;
  1006. if (start) *start = s-1;
  1007. while (0 <= stridx("0'#-+ ", *s)) s++;
  1008. while (isdigit(*s)) s++;
  1009. if (*s == '.') s++;
  1010. while (isdigit(*s)) s++;
  1011. return s;
  1012. }
  1013. return 0;
  1014. }
  1015. // Return cached passwd entries.
  1016. struct passwd *bufgetpwnamuid(char *name, uid_t uid)
  1017. {
  1018. struct pwuidbuf_list {
  1019. struct pwuidbuf_list *next;
  1020. struct passwd pw;
  1021. } *list = 0;
  1022. struct passwd *temp;
  1023. static struct pwuidbuf_list *pwuidbuf;
  1024. unsigned size = 256;
  1025. // If we already have this one, return it.
  1026. for (list = pwuidbuf; list; list = list->next)
  1027. if (name ? !strcmp(name, list->pw.pw_name) : list->pw.pw_uid==uid)
  1028. return &(list->pw);
  1029. for (;;) {
  1030. list = xrealloc(list, size *= 2);
  1031. if (name) errno = getpwnam_r(name, &list->pw, sizeof(*list)+(char *)list,
  1032. size-sizeof(*list), &temp);
  1033. else errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
  1034. size-sizeof(*list), &temp);
  1035. if (errno != ERANGE) break;
  1036. }
  1037. if (!temp) {
  1038. free(list);
  1039. return 0;
  1040. }
  1041. list->next = pwuidbuf;
  1042. pwuidbuf = list;
  1043. return &list->pw;
  1044. }
  1045. struct passwd *bufgetpwuid(uid_t uid)
  1046. {
  1047. return bufgetpwnamuid(0, uid);
  1048. }
  1049. // Return cached group entries.
  1050. struct group *bufgetgrnamgid(char *name, gid_t gid)
  1051. {
  1052. struct grgidbuf_list {
  1053. struct grgidbuf_list *next;
  1054. struct group gr;
  1055. } *list = 0;
  1056. struct group *temp;
  1057. static struct grgidbuf_list *grgidbuf;
  1058. unsigned size = 256;
  1059. for (list = grgidbuf; list; list = list->next)
  1060. if (name ? !strcmp(name, list->gr.gr_name) : list->gr.gr_gid==gid)
  1061. return &(list->gr);
  1062. for (;;) {
  1063. list = xrealloc(list, size *= 2);
  1064. if (name) errno = getgrnam_r(name, &list->gr, sizeof(*list)+(char *)list,
  1065. size-sizeof(*list), &temp);
  1066. else errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
  1067. size-sizeof(*list), &temp);
  1068. if (errno != ERANGE) break;
  1069. }
  1070. if (!temp) {
  1071. free(list);
  1072. return 0;
  1073. }
  1074. list->next = grgidbuf;
  1075. grgidbuf = list;
  1076. return &list->gr;
  1077. }
  1078. struct group *bufgetgrgid(gid_t gid)
  1079. {
  1080. return bufgetgrnamgid(0, gid);
  1081. }
  1082. // Always null terminates, returns 0 for failure, len for success
  1083. int readlinkat0(int dirfd, char *path, char *buf, int len)
  1084. {
  1085. if (!len) return 0;
  1086. len = readlinkat(dirfd, path, buf, len-1);
  1087. if (len<0) len = 0;
  1088. buf[len] = 0;
  1089. return len;
  1090. }
  1091. int readlink0(char *path, char *buf, int len)
  1092. {
  1093. return readlinkat0(AT_FDCWD, path, buf, len);
  1094. }
  1095. // Do regex matching with len argument to handle embedded NUL bytes in string
  1096. int regexec0(regex_t *preg, char *string, long len, int nmatch,
  1097. regmatch_t *pmatch, int eflags)
  1098. {
  1099. regmatch_t backup;
  1100. if (!nmatch) pmatch = &backup;
  1101. pmatch->rm_so = 0;
  1102. pmatch->rm_eo = len;
  1103. return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
  1104. }
  1105. // Return user name or string representation of number, returned buffer
  1106. // lasts until next call.
  1107. char *getusername(uid_t uid)
  1108. {
  1109. struct passwd *pw = bufgetpwuid(uid);
  1110. static char unum[12];
  1111. sprintf(unum, "%u", (unsigned)uid);
  1112. return pw ? pw->pw_name : unum;
  1113. }
  1114. // Return group name or string representation of number, returned buffer
  1115. // lasts until next call.
  1116. char *getgroupname(gid_t gid)
  1117. {
  1118. struct group *gr = bufgetgrgid(gid);
  1119. static char gnum[12];
  1120. sprintf(gnum, "%u", (unsigned)gid);
  1121. return gr ? gr->gr_name : gnum;
  1122. }
  1123. // Iterate over lines in file, calling function. Function can write 0 to
  1124. // the line pointer if they want to keep it, or 1 to terminate processing,
  1125. // otherwise line is freed. Passed file descriptor is closed at the end.
  1126. // At EOF calls function(0, 0)
  1127. void do_lines(int fd, char delim, void (*call)(char **pline, long len))
  1128. {
  1129. FILE *fp = fd ? xfdopen(fd, "r") : stdin;
  1130. for (;;) {
  1131. char *line = 0;
  1132. ssize_t len;
  1133. len = getdelim(&line, (void *)&len, delim, fp);
  1134. if (len > 0) {
  1135. call(&line, len);
  1136. if (line == (void *)1) break;
  1137. free(line);
  1138. } else break;
  1139. }
  1140. call(0, 0);
  1141. if (fd) fclose(fp);
  1142. }
  1143. // Return unix time in milliseconds
  1144. long long millitime(void)
  1145. {
  1146. struct timespec ts;
  1147. clock_gettime(CLOCK_MONOTONIC, &ts);
  1148. return ts.tv_sec*1000+ts.tv_nsec/1000000;
  1149. }
  1150. // Formats `ts` in ISO format ("2018-06-28 15:08:58.846386216 -0700").
  1151. char *format_iso_time(char *buf, size_t len, struct timespec *ts)
  1152. {
  1153. char *s = buf;
  1154. s += strftime(s, len, "%F %T", localtime(&(ts->tv_sec)));
  1155. s += sprintf(s, ".%09ld ", ts->tv_nsec);
  1156. s += strftime(s, len-strlen(buf), "%z", localtime(&(ts->tv_sec)));
  1157. return buf;
  1158. }
  1159. // Syslog with the openlog/closelog, autodetecting daemon status via no tty
  1160. void loggit(int priority, char *format, ...)
  1161. {
  1162. int i, facility = LOG_DAEMON;
  1163. va_list va;
  1164. for (i = 0; i<3; i++) if (isatty(i)) facility = LOG_AUTH;
  1165. openlog(toys.which->name, LOG_PID, facility);
  1166. va_start(va, format);
  1167. vsyslog(priority, format, va);
  1168. va_end(va);
  1169. closelog();
  1170. }
  1171. // Calculate tar packet checksum, with cksum field treated as 8 spaces
  1172. unsigned tar_cksum(void *data)
  1173. {
  1174. unsigned i, cksum = 8*' ';
  1175. for (i = 0; i<500; i += (i==147) ? 9 : 1) cksum += ((char *)data)[i];
  1176. return cksum;
  1177. }
  1178. // is this a valid tar header?
  1179. int is_tar_header(void *pkt)
  1180. {
  1181. char *p = pkt;
  1182. int i = 0;
  1183. if (p[257] && memcmp("ustar", p+257, 5)) return 0;
  1184. if (p[148] != '0' && p[148] != ' ') return 0;
  1185. sscanf(p+148, "%8o", &i);
  1186. return i && tar_cksum(pkt) == i;
  1187. }
  1188. char *elf_arch_name(int type)
  1189. {
  1190. int i;
  1191. // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
  1192. // Names are linux/arch/ directory (sometimes before 32/64 bit merges)
  1193. struct {int val; char *name;} types[] = {{0x9026, "alpha"}, {93, "arc"},
  1194. {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
  1195. {247, "bpf"}, {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
  1196. {252, "csky"}, {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"},
  1197. {50, "ia64"}, {88, "m32r"}, {0x9041, "m32r"}, {4, "m68k"}, {174, "metag"},
  1198. {189, "microblaze"}, {0xbaab, "microblaze-old"}, {8, "mips"},
  1199. {10, "mips-old"}, {89, "mn10300"}, {0xbeef, "mn10300-old"}, {113, "nios2"},
  1200. {92, "openrisc"}, {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"},
  1201. {21, "ppc64"}, {243, "riscv"}, {22, "s390"}, {0xa390, "s390-old"},
  1202. {135, "score"}, {42, "sh"}, {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"},
  1203. {188, "tile"}, {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"},
  1204. {94, "xtensa"}, {0xabc7, "xtensa-old"}
  1205. };
  1206. for (i = 0; i<ARRAY_LEN(types); i++) {
  1207. if (type==types[i].val) return types[i].name;
  1208. }
  1209. sprintf(libbuf, "unknown arch %d", type);
  1210. return libbuf;
  1211. }