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