xfuncs.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. * Copyright (C) 2006 Rob Landley
  7. * Copyright (C) 2006 Denis Vlasenko
  8. *
  9. * Licensed under GPL version 2, see file LICENSE in this tarball for details.
  10. */
  11. #include "libbb.h"
  12. /* All the functions starting with "x" call bb_error_msg_and_die() if they
  13. * fail, so callers never need to check for errors. If it returned, it
  14. * succeeded. */
  15. #ifndef DMALLOC
  16. /* dmalloc provides variants of these that do abort() on failure.
  17. * Since dmalloc's prototypes overwrite the impls here as they are
  18. * included after these prototypes in libbb.h, all is well.
  19. */
  20. // Warn if we can't allocate size bytes of memory.
  21. void *malloc_or_warn(size_t size)
  22. {
  23. void *ptr = malloc(size);
  24. if (ptr == NULL && size != 0)
  25. bb_error_msg(bb_msg_memory_exhausted);
  26. return ptr;
  27. }
  28. // Die if we can't allocate size bytes of memory.
  29. void *xmalloc(size_t size)
  30. {
  31. void *ptr = malloc(size);
  32. if (ptr == NULL && size != 0)
  33. bb_error_msg_and_die(bb_msg_memory_exhausted);
  34. return ptr;
  35. }
  36. // Die if we can't resize previously allocated memory. (This returns a pointer
  37. // to the new memory, which may or may not be the same as the old memory.
  38. // It'll copy the contents to a new chunk and free the old one if necessary.)
  39. void *xrealloc(void *ptr, size_t size)
  40. {
  41. ptr = realloc(ptr, size);
  42. if (ptr == NULL && size != 0)
  43. bb_error_msg_and_die(bb_msg_memory_exhausted);
  44. return ptr;
  45. }
  46. #endif /* DMALLOC */
  47. // Die if we can't allocate and zero size bytes of memory.
  48. void *xzalloc(size_t size)
  49. {
  50. void *ptr = xmalloc(size);
  51. memset(ptr, 0, size);
  52. return ptr;
  53. }
  54. // Die if we can't copy a string to freshly allocated memory.
  55. char * xstrdup(const char *s)
  56. {
  57. char *t;
  58. if (s == NULL)
  59. return NULL;
  60. t = strdup(s);
  61. if (t == NULL)
  62. bb_error_msg_and_die(bb_msg_memory_exhausted);
  63. return t;
  64. }
  65. // Die if we can't allocate n+1 bytes (space for the null terminator) and copy
  66. // the (possibly truncated to length n) string into it.
  67. char * xstrndup(const char *s, int n)
  68. {
  69. int m;
  70. char *t;
  71. if (ENABLE_DEBUG && s == NULL)
  72. bb_error_msg_and_die("xstrndup bug");
  73. /* We can just xmalloc(n+1) and strncpy into it, */
  74. /* but think about xstrndup("abc", 10000) wastage! */
  75. m = n;
  76. t = (char*) s;
  77. while (m) {
  78. if (!*t) break;
  79. m--;
  80. t++;
  81. }
  82. n -= m;
  83. t = xmalloc(n + 1);
  84. t[n] = '\0';
  85. return memcpy(t, s, n);
  86. }
  87. // Die if we can't open a file and return a FILE * to it.
  88. // Notice we haven't got xfread(), This is for use with fscanf() and friends.
  89. FILE *xfopen(const char *path, const char *mode)
  90. {
  91. FILE *fp = fopen(path, mode);
  92. if (fp == NULL)
  93. bb_perror_msg_and_die("can't open '%s'", path);
  94. return fp;
  95. }
  96. // Die if we can't open a file and return a fd.
  97. int xopen3(const char *pathname, int flags, int mode)
  98. {
  99. int ret;
  100. ret = open(pathname, flags, mode);
  101. if (ret < 0) {
  102. bb_perror_msg_and_die("can't open '%s'", pathname);
  103. }
  104. return ret;
  105. }
  106. // Die if we can't open an existing file and return a fd.
  107. int xopen(const char *pathname, int flags)
  108. {
  109. return xopen3(pathname, flags, 0666);
  110. }
  111. // Warn if we can't open a file and return a fd.
  112. int open3_or_warn(const char *pathname, int flags, int mode)
  113. {
  114. int ret;
  115. ret = open(pathname, flags, mode);
  116. if (ret < 0) {
  117. bb_perror_msg("can't open '%s'", pathname);
  118. }
  119. return ret;
  120. }
  121. // Warn if we can't open a file and return a fd.
  122. int open_or_warn(const char *pathname, int flags)
  123. {
  124. return open3_or_warn(pathname, flags, 0666);
  125. }
  126. void xpipe(int filedes[2])
  127. {
  128. if (pipe(filedes))
  129. bb_perror_msg_and_die("can't create pipe");
  130. }
  131. void xunlink(const char *pathname)
  132. {
  133. if (unlink(pathname))
  134. bb_perror_msg_and_die("can't remove file '%s'", pathname);
  135. }
  136. // Turn on nonblocking I/O on a fd
  137. int ndelay_on(int fd)
  138. {
  139. return fcntl(fd, F_SETFL, fcntl(fd,F_GETFL) | O_NONBLOCK);
  140. }
  141. int ndelay_off(int fd)
  142. {
  143. return fcntl(fd, F_SETFL, fcntl(fd,F_GETFL) & ~O_NONBLOCK);
  144. }
  145. void xdup2(int from, int to)
  146. {
  147. if (dup2(from, to) != to)
  148. bb_perror_msg_and_die("can't duplicate file descriptor");
  149. }
  150. // "Renumber" opened fd
  151. void xmove_fd(int from, int to)
  152. {
  153. if (from == to)
  154. return;
  155. xdup2(from, to);
  156. close(from);
  157. }
  158. // Die with an error message if we can't write the entire buffer.
  159. void xwrite(int fd, const void *buf, size_t count)
  160. {
  161. if (count) {
  162. ssize_t size = full_write(fd, buf, count);
  163. if (size != count)
  164. bb_error_msg_and_die("short write");
  165. }
  166. }
  167. // Die with an error message if we can't lseek to the right spot.
  168. off_t xlseek(int fd, off_t offset, int whence)
  169. {
  170. off_t off = lseek(fd, offset, whence);
  171. if (off == (off_t)-1) {
  172. if (whence == SEEK_SET)
  173. bb_perror_msg_and_die("lseek(%"OFF_FMT"u)", offset);
  174. bb_perror_msg_and_die("lseek");
  175. }
  176. return off;
  177. }
  178. // Die with supplied filename if this FILE * has ferror set.
  179. void die_if_ferror(FILE *fp, const char *fn)
  180. {
  181. if (ferror(fp)) {
  182. /* ferror doesn't set useful errno */
  183. bb_error_msg_and_die("%s: I/O error", fn);
  184. }
  185. }
  186. // Die with an error message if stdout has ferror set.
  187. void die_if_ferror_stdout(void)
  188. {
  189. die_if_ferror(stdout, bb_msg_standard_output);
  190. }
  191. // Die with an error message if we have trouble flushing stdout.
  192. void xfflush_stdout(void)
  193. {
  194. if (fflush(stdout)) {
  195. bb_perror_msg_and_die(bb_msg_standard_output);
  196. }
  197. }
  198. void sig_block(int sig)
  199. {
  200. sigset_t ss;
  201. sigemptyset(&ss);
  202. sigaddset(&ss, sig);
  203. sigprocmask(SIG_BLOCK, &ss, NULL);
  204. }
  205. void sig_unblock(int sig)
  206. {
  207. sigset_t ss;
  208. sigemptyset(&ss);
  209. sigaddset(&ss, sig);
  210. sigprocmask(SIG_UNBLOCK, &ss, NULL);
  211. }
  212. #if 0
  213. void sig_blocknone(void)
  214. {
  215. sigset_t ss;
  216. sigemptyset(&ss);
  217. sigprocmask(SIG_SETMASK, &ss, NULL);
  218. }
  219. #endif
  220. void sig_catch(int sig, void (*f)(int))
  221. {
  222. struct sigaction sa;
  223. sa.sa_handler = f;
  224. sa.sa_flags = 0;
  225. sigemptyset(&sa.sa_mask);
  226. sigaction(sig, &sa, NULL);
  227. }
  228. void sig_pause(void)
  229. {
  230. sigset_t ss;
  231. sigemptyset(&ss);
  232. sigsuspend(&ss);
  233. }
  234. void xsetenv(const char *key, const char *value)
  235. {
  236. if (setenv(key, value, 1))
  237. bb_error_msg_and_die(bb_msg_memory_exhausted);
  238. }
  239. // Converts unsigned long long value into compact 4-char
  240. // representation. Examples: "1234", "1.2k", " 27M", "123T"
  241. // Fifth char is always '\0'
  242. void smart_ulltoa5(unsigned long long ul, char buf[5])
  243. {
  244. const char *fmt;
  245. char c;
  246. unsigned v,idx = 0;
  247. ul *= 10;
  248. if (ul > 9999*10) { // do not scale if 9999 or less
  249. while (ul >= 10000) {
  250. ul /= 1024;
  251. idx++;
  252. }
  253. }
  254. v = ul; // ullong divisions are expensive, avoid them
  255. fmt = " 123456789";
  256. if (!idx) { // 9999 or less: use 1234 format
  257. c = buf[0] = " 123456789"[v/10000];
  258. if (c != ' ') fmt = "0123456789";
  259. c = buf[1] = fmt[v/1000%10];
  260. if (c != ' ') fmt = "0123456789";
  261. buf[2] = fmt[v/100%10];
  262. buf[3] = "0123456789"[v/10%10];
  263. } else {
  264. if (v >= 10*10) { // scaled value is >=10: use 123M format
  265. c = buf[0] = " 123456789"[v/1000];
  266. if (c != ' ') fmt = "0123456789";
  267. buf[1] = fmt[v/100%10];
  268. buf[2] = "0123456789"[v/10%10];
  269. } else { // scaled value is <10: use 1.2M format
  270. buf[0] = "0123456789"[v/10];
  271. buf[1] = '.';
  272. buf[2] = "0123456789"[v%10];
  273. }
  274. // see http://en.wikipedia.org/wiki/Tera
  275. buf[3] = " kMGTPEZY"[idx];
  276. }
  277. buf[4] = '\0';
  278. }
  279. // Convert unsigned integer to ascii, writing into supplied buffer.
  280. // A truncated result contains the first few digits of the result ala strncpy.
  281. // Returns a pointer past last generated digit, does _not_ store NUL.
  282. void BUG_sizeof_unsigned_not_4(void);
  283. char *utoa_to_buf(unsigned n, char *buf, unsigned buflen)
  284. {
  285. unsigned i, out, res;
  286. if (sizeof(unsigned) != 4)
  287. BUG_sizeof_unsigned_not_4();
  288. if (buflen) {
  289. out = 0;
  290. for (i = 1000000000; i; i /= 10) {
  291. res = n / i;
  292. if (res || out || i == 1) {
  293. if (!--buflen) break;
  294. out++;
  295. n -= res*i;
  296. *buf++ = '0' + res;
  297. }
  298. }
  299. }
  300. return buf;
  301. }
  302. // Convert signed integer to ascii, like utoa_to_buf()
  303. char *itoa_to_buf(int n, char *buf, unsigned buflen)
  304. {
  305. if (buflen && n<0) {
  306. n = -n;
  307. *buf++ = '-';
  308. buflen--;
  309. }
  310. return utoa_to_buf((unsigned)n, buf, buflen);
  311. }
  312. // The following two functions use a static buffer, so calling either one a
  313. // second time will overwrite previous results.
  314. //
  315. // The largest 32 bit integer is -2 billion plus null terminator, or 12 bytes.
  316. // Int should always be 32 bits on any remotely Unix-like system, see
  317. // http://www.unix.org/whitepapers/64bit.html for the reasons why.
  318. static char local_buf[12];
  319. // Convert unsigned integer to ascii using a static buffer (returned).
  320. char *utoa(unsigned n)
  321. {
  322. *(utoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
  323. return local_buf;
  324. }
  325. // Convert signed integer to ascii using a static buffer (returned).
  326. char *itoa(int n)
  327. {
  328. *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
  329. return local_buf;
  330. }
  331. // Emit a string of hex representation of bytes
  332. char *bin2hex(char *p, const char *cp, int count)
  333. {
  334. while (count) {
  335. unsigned char c = *cp++;
  336. /* put lowercase hex digits */
  337. *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
  338. *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
  339. count--;
  340. }
  341. return p;
  342. }
  343. // Die with an error message if we can't set gid. (Because resource limits may
  344. // limit this user to a given number of processes, and if that fills up the
  345. // setgid() will fail and we'll _still_be_root_, which is bad.)
  346. void xsetgid(gid_t gid)
  347. {
  348. if (setgid(gid)) bb_perror_msg_and_die("setgid");
  349. }
  350. // Die with an error message if we can't set uid. (See xsetgid() for why.)
  351. void xsetuid(uid_t uid)
  352. {
  353. if (setuid(uid)) bb_perror_msg_and_die("setuid");
  354. }
  355. // Return how long the file at fd is, if there's any way to determine it.
  356. off_t fdlength(int fd)
  357. {
  358. off_t bottom = 0, top = 0, pos;
  359. long size;
  360. // If the ioctl works for this, return it.
  361. if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
  362. // FIXME: explain why lseek(SEEK_END) is not used here!
  363. // If not, do a binary search for the last location we can read. (Some
  364. // block devices don't do BLKGETSIZE right.)
  365. do {
  366. char temp;
  367. pos = bottom + (top - bottom) / 2;
  368. // If we can read from the current location, it's bigger.
  369. if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
  370. if (bottom == top) bottom = top = (top+1) * 2;
  371. else bottom = pos;
  372. // If we can't, it's smaller.
  373. } else {
  374. if (bottom == top) {
  375. if (!top) return 0;
  376. bottom = top/2;
  377. }
  378. else top = pos;
  379. }
  380. } while (bottom + 1 != top);
  381. return pos + 1;
  382. }
  383. // Die with an error message if we can't malloc() enough space and do an
  384. // sprintf() into that space.
  385. char *xasprintf(const char *format, ...)
  386. {
  387. va_list p;
  388. int r;
  389. char *string_ptr;
  390. #if 1
  391. // GNU extension
  392. va_start(p, format);
  393. r = vasprintf(&string_ptr, format, p);
  394. va_end(p);
  395. #else
  396. // Bloat for systems that haven't got the GNU extension.
  397. va_start(p, format);
  398. r = vsnprintf(NULL, 0, format, p);
  399. va_end(p);
  400. string_ptr = xmalloc(r+1);
  401. va_start(p, format);
  402. r = vsnprintf(string_ptr, r+1, format, p);
  403. va_end(p);
  404. #endif
  405. if (r < 0) bb_error_msg_and_die(bb_msg_memory_exhausted);
  406. return string_ptr;
  407. }
  408. #if 0 /* If we will ever meet a libc which hasn't [f]dprintf... */
  409. int fdprintf(int fd, const char *format, ...)
  410. {
  411. va_list p;
  412. int r;
  413. char *string_ptr;
  414. #if 1
  415. // GNU extension
  416. va_start(p, format);
  417. r = vasprintf(&string_ptr, format, p);
  418. va_end(p);
  419. #else
  420. // Bloat for systems that haven't got the GNU extension.
  421. va_start(p, format);
  422. r = vsnprintf(NULL, 0, format, p) + 1;
  423. va_end(p);
  424. string_ptr = malloc(r);
  425. if (string_ptr) {
  426. va_start(p, format);
  427. r = vsnprintf(string_ptr, r, format, p);
  428. va_end(p);
  429. }
  430. #endif
  431. if (r >= 0) {
  432. full_write(fd, string_ptr, r);
  433. free(string_ptr);
  434. }
  435. return r;
  436. }
  437. #endif
  438. // Die with an error message if we can't copy an entire FILE * to stdout, then
  439. // close that file.
  440. void xprint_and_close_file(FILE *file)
  441. {
  442. fflush(stdout);
  443. // copyfd outputs error messages for us.
  444. if (bb_copyfd_eof(fileno(file), 1) == -1)
  445. xfunc_die();
  446. fclose(file);
  447. }
  448. // Die if we can't chdir to a new path.
  449. void xchdir(const char *path)
  450. {
  451. if (chdir(path))
  452. bb_perror_msg_and_die("chdir(%s)", path);
  453. }
  454. // Print a warning message if opendir() fails, but don't die.
  455. DIR *warn_opendir(const char *path)
  456. {
  457. DIR *dp;
  458. dp = opendir(path);
  459. if (!dp)
  460. bb_perror_msg("can't open '%s'", path);
  461. return dp;
  462. }
  463. // Die with an error message if opendir() fails.
  464. DIR *xopendir(const char *path)
  465. {
  466. DIR *dp;
  467. dp = opendir(path);
  468. if (!dp)
  469. bb_perror_msg_and_die("can't open '%s'", path);
  470. return dp;
  471. }
  472. // Die with an error message if we can't open a new socket.
  473. int xsocket(int domain, int type, int protocol)
  474. {
  475. int r = socket(domain, type, protocol);
  476. if (r < 0) {
  477. /* Hijack vaguely related config option */
  478. #if ENABLE_VERBOSE_RESOLUTION_ERRORS
  479. const char *s = "INET";
  480. if (domain == AF_PACKET) s = "PACKET";
  481. if (domain == AF_NETLINK) s = "NETLINK";
  482. USE_FEATURE_IPV6(if (domain == AF_INET6) s = "INET6";)
  483. bb_perror_msg_and_die("socket(AF_%s)", s);
  484. #else
  485. bb_perror_msg_and_die("socket");
  486. #endif
  487. }
  488. return r;
  489. }
  490. // Die with an error message if we can't bind a socket to an address.
  491. void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen)
  492. {
  493. if (bind(sockfd, my_addr, addrlen)) bb_perror_msg_and_die("bind");
  494. }
  495. // Die with an error message if we can't listen for connections on a socket.
  496. void xlisten(int s, int backlog)
  497. {
  498. if (listen(s, backlog)) bb_perror_msg_and_die("listen");
  499. }
  500. /* Die with an error message if sendto failed.
  501. * Return bytes sent otherwise */
  502. ssize_t xsendto(int s, const void *buf, size_t len, const struct sockaddr *to,
  503. socklen_t tolen)
  504. {
  505. ssize_t ret = sendto(s, buf, len, 0, to, tolen);
  506. if (ret < 0) {
  507. if (ENABLE_FEATURE_CLEAN_UP)
  508. close(s);
  509. bb_perror_msg_and_die("sendto");
  510. }
  511. return ret;
  512. }
  513. // xstat() - a stat() which dies on failure with meaningful error message
  514. void xstat(const char *name, struct stat *stat_buf)
  515. {
  516. if (stat(name, stat_buf))
  517. bb_perror_msg_and_die("can't stat '%s'", name);
  518. }
  519. // selinux_or_die() - die if SELinux is disabled.
  520. void selinux_or_die(void)
  521. {
  522. #if ENABLE_SELINUX
  523. int rc = is_selinux_enabled();
  524. if (rc == 0) {
  525. bb_error_msg_and_die("SELinux is disabled");
  526. } else if (rc < 0) {
  527. bb_error_msg_and_die("is_selinux_enabled() failed");
  528. }
  529. #else
  530. bb_error_msg_and_die("SELinux support is disabled");
  531. #endif
  532. }
  533. /* It is perfectly ok to pass in a NULL for either width or for
  534. * height, in which case that value will not be set. */
  535. int get_terminal_width_height(int fd, int *width, int *height)
  536. {
  537. struct winsize win = { 0, 0, 0, 0 };
  538. int ret = ioctl(fd, TIOCGWINSZ, &win);
  539. if (height) {
  540. if (!win.ws_row) {
  541. char *s = getenv("LINES");
  542. if (s) win.ws_row = atoi(s);
  543. }
  544. if (win.ws_row <= 1 || win.ws_row >= 30000)
  545. win.ws_row = 24;
  546. *height = (int) win.ws_row;
  547. }
  548. if (width) {
  549. if (!win.ws_col) {
  550. char *s = getenv("COLUMNS");
  551. if (s) win.ws_col = atoi(s);
  552. }
  553. if (win.ws_col <= 1 || win.ws_col >= 30000)
  554. win.ws_col = 80;
  555. *width = (int) win.ws_col;
  556. }
  557. return ret;
  558. }
  559. void ioctl_or_perror_and_die(int fd, int request, void *argp, const char *fmt,...)
  560. {
  561. va_list p;
  562. if (ioctl(fd, request, argp) < 0) {
  563. va_start(p, fmt);
  564. bb_verror_msg(fmt, p, strerror(errno));
  565. /* xfunc_die can actually longjmp, so be nice */
  566. va_end(p);
  567. xfunc_die();
  568. }
  569. }
  570. int ioctl_or_perror(int fd, int request, void *argp, const char *fmt,...)
  571. {
  572. va_list p;
  573. int ret = ioctl(fd, request, argp);
  574. if (ret < 0) {
  575. va_start(p, fmt);
  576. bb_verror_msg(fmt, p, strerror(errno));
  577. va_end(p);
  578. }
  579. return ret;
  580. }
  581. #if ENABLE_IOCTL_HEX2STR_ERROR
  582. int bb_ioctl_or_warn(int fd, int request, void *argp, const char *ioctl_name)
  583. {
  584. int ret;
  585. ret = ioctl(fd, request, argp);
  586. if (ret < 0)
  587. bb_perror_msg("%s", ioctl_name);
  588. return ret;
  589. }
  590. void bb_xioctl(int fd, int request, void *argp, const char *ioctl_name)
  591. {
  592. if (ioctl(fd, request, argp) < 0)
  593. bb_perror_msg_and_die("%s", ioctl_name);
  594. }
  595. #else
  596. int bb_ioctl_or_warn(int fd, int request, void *argp)
  597. {
  598. int ret;
  599. ret = ioctl(fd, request, argp);
  600. if (ret < 0)
  601. bb_perror_msg("ioctl %#x failed", request);
  602. return ret;
  603. }
  604. void bb_xioctl(int fd, int request, void *argp)
  605. {
  606. if (ioctl(fd, request, argp) < 0)
  607. bb_perror_msg_and_die("ioctl %#x failed", request);
  608. }
  609. #endif