xfuncs.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 "busybox.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. // Die if we can't allocate size bytes of memory.
  21. void *xmalloc(size_t size)
  22. {
  23. void *ptr = malloc(size);
  24. if (ptr == NULL && size != 0)
  25. bb_error_msg_and_die(bb_msg_memory_exhausted);
  26. return ptr;
  27. }
  28. // Die if we can't resize previously allocated memory. (This returns a pointer
  29. // to the new memory, which may or may not be the same as the old memory.
  30. // It'll copy the contents to a new chunk and free the old one if necessary.)
  31. void *xrealloc(void *ptr, size_t size)
  32. {
  33. ptr = realloc(ptr, size);
  34. if (ptr == NULL && size != 0)
  35. bb_error_msg_and_die(bb_msg_memory_exhausted);
  36. return ptr;
  37. }
  38. #endif /* DMALLOC */
  39. // Die if we can't allocate and zero size bytes of memory.
  40. void *xzalloc(size_t size)
  41. {
  42. void *ptr = xmalloc(size);
  43. memset(ptr, 0, size);
  44. return ptr;
  45. }
  46. // Die if we can't copy a string to freshly allocated memory.
  47. char * xstrdup(const char *s)
  48. {
  49. char *t;
  50. if (s == NULL)
  51. return NULL;
  52. t = strdup(s);
  53. if (t == NULL)
  54. bb_error_msg_and_die(bb_msg_memory_exhausted);
  55. return t;
  56. }
  57. // Die if we can't allocate n+1 bytes (space for the null terminator) and copy
  58. // the (possibly truncated to length n) string into it.
  59. char * xstrndup(const char *s, int n)
  60. {
  61. int m;
  62. char *t;
  63. if (ENABLE_DEBUG && s == NULL)
  64. bb_error_msg_and_die("xstrndup bug");
  65. /* We can just xmalloc(n+1) and strncpy into it, */
  66. /* but think about xstrndup("abc", 10000) wastage! */
  67. m = n;
  68. t = (char*) s;
  69. while (m) {
  70. if (!*t) break;
  71. m--; t++;
  72. }
  73. n = n - m;
  74. t = xmalloc(n + 1);
  75. t[n] = '\0';
  76. return memcpy(t,s,n);
  77. }
  78. // Die if we can't open a file and return a FILE * to it.
  79. // Notice we haven't got xfread(), This is for use with fscanf() and friends.
  80. FILE *xfopen(const char *path, const char *mode)
  81. {
  82. FILE *fp = fopen(path, mode);
  83. if (fp == NULL)
  84. bb_perror_msg_and_die("%s", path);
  85. return fp;
  86. }
  87. // Die if we can't open an existing file and return an fd.
  88. int xopen(const char *pathname, int flags)
  89. {
  90. //if (ENABLE_DEBUG && (flags & O_CREAT))
  91. // bb_error_msg_and_die("xopen() with O_CREAT");
  92. return xopen3(pathname, flags, 0666);
  93. }
  94. // Die if we can't open a new file and return an fd.
  95. int xopen3(const char *pathname, int flags, int mode)
  96. {
  97. int ret;
  98. ret = open(pathname, flags, mode);
  99. if (ret < 0) {
  100. bb_perror_msg_and_die("%s", pathname);
  101. }
  102. return ret;
  103. }
  104. /*
  105. int ndelay_off(int fd)
  106. {
  107. return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) & ~O_NONBLOCK);
  108. }
  109. */
  110. // Turn on nonblocking I/O on a fd
  111. int ndelay_on(int fd)
  112. {
  113. return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) | O_NONBLOCK);
  114. }
  115. // Die with an error message if we can't write the entire buffer.
  116. void xwrite(int fd, const void *buf, size_t count)
  117. {
  118. if (count) {
  119. ssize_t size = full_write(fd, buf, count);
  120. if (size != count)
  121. bb_error_msg_and_die("short write");
  122. }
  123. }
  124. // Die with an error message if we can't lseek to the right spot.
  125. off_t xlseek(int fd, off_t offset, int whence)
  126. {
  127. off_t off = lseek(fd, offset, whence);
  128. if (off == (off_t)-1) {
  129. if (whence == SEEK_SET)
  130. bb_perror_msg_and_die("lseek(%"OFF_FMT"u)", offset);
  131. bb_perror_msg_and_die("lseek");
  132. }
  133. return off;
  134. }
  135. // Die with supplied filename if this FILE * has ferror set.
  136. void die_if_ferror(FILE *fp, const char *fn)
  137. {
  138. if (ferror(fp)) {
  139. bb_error_msg_and_die("%s: I/O error", fn);
  140. }
  141. }
  142. // Die with an error message if stdout has ferror set.
  143. void die_if_ferror_stdout(void)
  144. {
  145. die_if_ferror(stdout, bb_msg_standard_output);
  146. }
  147. // Die with an error message if we have trouble flushing stdout.
  148. void xfflush_stdout(void)
  149. {
  150. if (fflush(stdout)) {
  151. bb_perror_msg_and_die(bb_msg_standard_output);
  152. }
  153. }
  154. // This does a fork/exec in one call, using vfork(). Return PID of new child,
  155. // -1 for failure. Runs argv[0], searching path if that has no / in it.
  156. pid_t spawn(char **argv)
  157. {
  158. static int failed;
  159. pid_t pid;
  160. void *app = ENABLE_FEATURE_SH_STANDALONE_SHELL ? find_applet_by_name(argv[0]) : 0;
  161. // Be nice to nommu machines.
  162. failed = 0;
  163. pid = vfork();
  164. if (pid < 0) return pid;
  165. if (!pid) {
  166. execvp(app ? CONFIG_BUSYBOX_EXEC_PATH : *argv, argv);
  167. // We're sharing a stack with blocked parent, let parent know we failed
  168. // and then exit to unblock parent (but don't run atexit() stuff, which
  169. // would screw up parent.)
  170. failed = -1;
  171. _exit(0);
  172. }
  173. return failed ? failed : pid;
  174. }
  175. // Die with an error message if we can't spawn a child process.
  176. pid_t xspawn(char **argv)
  177. {
  178. pid_t pid = spawn(argv);
  179. if (pid < 0) bb_perror_msg_and_die("%s", *argv);
  180. return pid;
  181. }
  182. // Wait for the specified child PID to exit, returning child's error return.
  183. int wait4pid(int pid)
  184. {
  185. int status;
  186. if (pid == -1 || waitpid(pid, &status, 0) == -1) return -1;
  187. if (WIFEXITED(status)) return WEXITSTATUS(status);
  188. if (WIFSIGNALED(status)) return WTERMSIG(status);
  189. return 0;
  190. }
  191. void xsetenv(const char *key, const char *value)
  192. {
  193. if (setenv(key, value, 1))
  194. bb_error_msg_and_die(bb_msg_memory_exhausted);
  195. }
  196. // Converts unsigned long long value into compact 4-char
  197. // representation. Examples: "1234", "1.2k", " 27M", "123T"
  198. // Fifth char is always '\0'
  199. void smart_ulltoa5(unsigned long long ul, char buf[5])
  200. {
  201. char *fmt;
  202. char c;
  203. unsigned v,idx = 0;
  204. ul *= 10;
  205. if (ul > 9999*10) { // do not scale if 9999 or less
  206. while (ul >= 10000) {
  207. ul /= 1024;
  208. idx++;
  209. }
  210. }
  211. v = ul; // ullong divisions are expensive, avoid them
  212. fmt = " 123456789";
  213. if (!idx) { // 9999 or less: use 1234 format
  214. c = buf[0] = " 123456789"[v/10000];
  215. if (c!=' ') fmt = "0123456789";
  216. c = buf[1] = fmt[v/1000%10];
  217. if (c!=' ') fmt = "0123456789";
  218. buf[2] = fmt[v/100%10];
  219. buf[3] = "0123456789"[v/10%10];
  220. } else {
  221. if (v>=10*10) { // scaled value is >=10: use 123M format
  222. c = buf[0] = " 123456789"[v/1000];
  223. if (c!=' ') fmt = "0123456789";
  224. buf[1] = fmt[v/100%10];
  225. buf[2] = "0123456789"[v/10%10];
  226. } else { // scaled value is <10: use 1.2M format
  227. buf[0] = "0123456789"[v/10];
  228. buf[1] = '.';
  229. buf[2] = "0123456789"[v%10];
  230. }
  231. // see http://en.wikipedia.org/wiki/Tera
  232. buf[3] = " kMGTPEZY"[idx];
  233. }
  234. buf[4] = '\0';
  235. }
  236. // Convert unsigned integer to ascii, writing into supplied buffer. A
  237. // truncated result is always null terminated (unless buflen is 0), and
  238. // contains the first few digits of the result ala strncpy.
  239. void BUG_sizeof_unsigned_not_4(void);
  240. void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
  241. {
  242. unsigned i, out, res;
  243. if (sizeof(unsigned) != 4)
  244. BUG_sizeof_unsigned_not_4();
  245. if (buflen) {
  246. out = 0;
  247. for (i = 1000000000; i; i /= 10) {
  248. res = n / i;
  249. if (res || out || i == 1) {
  250. if (!--buflen) break;
  251. out++;
  252. n -= res*i;
  253. *buf++ = '0' + res;
  254. }
  255. }
  256. *buf = '\0';
  257. }
  258. }
  259. // Convert signed integer to ascii, like utoa_to_buf()
  260. void itoa_to_buf(int n, char *buf, unsigned buflen)
  261. {
  262. if (buflen && n<0) {
  263. n = -n;
  264. *buf++ = '-';
  265. buflen--;
  266. }
  267. utoa_to_buf((unsigned)n, buf, buflen);
  268. }
  269. // The following two functions use a static buffer, so calling either one a
  270. // second time will overwrite previous results.
  271. //
  272. // The largest 32 bit integer is -2 billion plus null terminator, or 12 bytes.
  273. // Int should always be 32 bits on any remotely Unix-like system, see
  274. // http://www.unix.org/whitepapers/64bit.html for the reasons why.
  275. static char local_buf[12];
  276. // Convert unsigned integer to ascii using a static buffer (returned).
  277. char *utoa(unsigned n)
  278. {
  279. utoa_to_buf(n, local_buf, sizeof(local_buf));
  280. return local_buf;
  281. }
  282. // Convert signed integer to ascii using a static buffer (returned).
  283. char *itoa(int n)
  284. {
  285. itoa_to_buf(n, local_buf, sizeof(local_buf));
  286. return local_buf;
  287. }
  288. // Die with an error message if we can't set gid. (Because resource limits may
  289. // limit this user to a given number of processes, and if that fills up the
  290. // setgid() will fail and we'll _still_be_root_, which is bad.)
  291. void xsetgid(gid_t gid)
  292. {
  293. if (setgid(gid)) bb_error_msg_and_die("setgid");
  294. }
  295. // Die with an error message if we can't set uid. (See xsetgid() for why.)
  296. void xsetuid(uid_t uid)
  297. {
  298. if (setuid(uid)) bb_error_msg_and_die("setuid");
  299. }
  300. // Return how long the file at fd is, if there's any way to determine it.
  301. off_t fdlength(int fd)
  302. {
  303. off_t bottom = 0, top = 0, pos;
  304. long size;
  305. // If the ioctl works for this, return it.
  306. if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
  307. // FIXME: explain why lseek(SEEK_END) is not used here!
  308. // If not, do a binary search for the last location we can read. (Some
  309. // block devices don't do BLKGETSIZE right.)
  310. do {
  311. char temp;
  312. pos = bottom + (top - bottom) / 2;
  313. // If we can read from the current location, it's bigger.
  314. if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
  315. if (bottom == top) bottom = top = (top+1) * 2;
  316. else bottom = pos;
  317. // If we can't, it's smaller.
  318. } else {
  319. if (bottom == top) {
  320. if (!top) return 0;
  321. bottom = top/2;
  322. }
  323. else top = pos;
  324. }
  325. } while (bottom + 1 != top);
  326. return pos + 1;
  327. }
  328. // Die with an error message if we can't malloc() enough space and do an
  329. // sprintf() into that space.
  330. char *xasprintf(const char *format, ...)
  331. {
  332. va_list p;
  333. int r;
  334. char *string_ptr;
  335. #if 1
  336. // GNU extension
  337. va_start(p, format);
  338. r = vasprintf(&string_ptr, format, p);
  339. va_end(p);
  340. #else
  341. // Bloat for systems that haven't got the GNU extension.
  342. va_start(p, format);
  343. r = vsnprintf(NULL, 0, format, p);
  344. va_end(p);
  345. string_ptr = xmalloc(r+1);
  346. va_start(p, format);
  347. r = vsnprintf(string_ptr, r+1, format, p);
  348. va_end(p);
  349. #endif
  350. if (r < 0) bb_error_msg_and_die(bb_msg_memory_exhausted);
  351. return string_ptr;
  352. }
  353. // Die with an error message if we can't copy an entire FILE * to stdout, then
  354. // close that file.
  355. void xprint_and_close_file(FILE *file)
  356. {
  357. fflush(stdout);
  358. // copyfd outputs error messages for us.
  359. if (bb_copyfd_eof(fileno(file), 1) == -1)
  360. exit(xfunc_error_retval);
  361. fclose(file);
  362. }
  363. // Die if we can't chdir to a new path.
  364. void xchdir(const char *path)
  365. {
  366. if (chdir(path))
  367. bb_perror_msg_and_die("chdir(%s)", path);
  368. }
  369. // Print a warning message if opendir() fails, but don't die.
  370. DIR *warn_opendir(const char *path)
  371. {
  372. DIR *dp;
  373. if ((dp = opendir(path)) == NULL) {
  374. bb_perror_msg("cannot open '%s'", path);
  375. return NULL;
  376. }
  377. return dp;
  378. }
  379. // Die with an error message if opendir() fails.
  380. DIR *xopendir(const char *path)
  381. {
  382. DIR *dp;
  383. if ((dp = opendir(path)) == NULL)
  384. bb_perror_msg_and_die("cannot open '%s'", path);
  385. return dp;
  386. }
  387. #ifndef BB_NOMMU
  388. // Die with an error message if we can't daemonize.
  389. void xdaemon(int nochdir, int noclose)
  390. {
  391. if (daemon(nochdir, noclose))
  392. bb_perror_msg_and_die("daemon");
  393. }
  394. #endif
  395. // Die with an error message if we can't open a new socket.
  396. int xsocket(int domain, int type, int protocol)
  397. {
  398. int r = socket(domain, type, protocol);
  399. if (r < 0) bb_perror_msg_and_die("socket");
  400. return r;
  401. }
  402. // Die with an error message if we can't bind a socket to an address.
  403. void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen)
  404. {
  405. if (bind(sockfd, my_addr, addrlen)) bb_perror_msg_and_die("bind");
  406. }
  407. // Die with an error message if we can't listen for connections on a socket.
  408. void xlisten(int s, int backlog)
  409. {
  410. if (listen(s, backlog)) bb_perror_msg_and_die("listen");
  411. }
  412. // xstat() - a stat() which dies on failure with meaningful error message
  413. void xstat(char *name, struct stat *stat_buf)
  414. {
  415. if (stat(name, stat_buf))
  416. bb_perror_msg_and_die("can't stat '%s'", name);
  417. }
  418. /* It is perfectly ok to pass in a NULL for either width or for
  419. * height, in which case that value will not be set. */
  420. int get_terminal_width_height(int fd, int *width, int *height)
  421. {
  422. struct winsize win = { 0, 0, 0, 0 };
  423. int ret = ioctl(fd, TIOCGWINSZ, &win);
  424. if (height) {
  425. if (!win.ws_row) {
  426. char *s = getenv("LINES");
  427. if (s) win.ws_row = atoi(s);
  428. }
  429. if (win.ws_row <= 1 || win.ws_row >= 30000)
  430. win.ws_row = 24;
  431. *height = (int) win.ws_row;
  432. }
  433. if (width) {
  434. if (!win.ws_col) {
  435. char *s = getenv("COLUMNS");
  436. if (s) win.ws_col = atoi(s);
  437. }
  438. if (win.ws_col <= 1 || win.ws_col >= 30000)
  439. win.ws_col = 80;
  440. *width = (int) win.ws_col;
  441. }
  442. return ret;
  443. }