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