xstrndup: Use strndup instead of implementing it.
[oweals/busybox.git] / libbb / xfuncs_printf.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 Denys Vlasenko
8  *
9  * Licensed under GPLv2, see file LICENSE in this source tree.
10  */
11 /* We need to have separate xfuncs.c and xfuncs_printf.c because
12  * with current linkers, even with section garbage collection,
13  * if *.o module references any of XXXprintf functions, you pull in
14  * entire printf machinery. Even if you do not use the function
15  * which uses XXXprintf.
16  *
17  * xfuncs.c contains functions (not necessarily xfuncs)
18  * which do not pull in printf, directly or indirectly.
19  * xfunc_printf.c contains those which do.
20  */
21 #include "libbb.h"
22
23
24 /* All the functions starting with "x" call bb_error_msg_and_die() if they
25  * fail, so callers never need to check for errors.  If it returned, it
26  * succeeded. */
27
28 void FAST_FUNC bb_die_memory_exhausted(void)
29 {
30         bb_simple_error_msg_and_die(bb_msg_memory_exhausted);
31 }
32
33 #ifndef DMALLOC
34 /* dmalloc provides variants of these that do abort() on failure.
35  * Since dmalloc's prototypes overwrite the impls here as they are
36  * included after these prototypes in libbb.h, all is well.
37  */
38 // Warn if we can't allocate size bytes of memory.
39 void* FAST_FUNC malloc_or_warn(size_t size)
40 {
41         void *ptr = malloc(size);
42         if (ptr == NULL && size != 0)
43                 bb_simple_error_msg(bb_msg_memory_exhausted);
44         return ptr;
45 }
46
47 // Die if we can't allocate size bytes of memory.
48 void* FAST_FUNC xmalloc(size_t size)
49 {
50         void *ptr = malloc(size);
51         if (ptr == NULL && size != 0)
52                 bb_die_memory_exhausted();
53         return ptr;
54 }
55
56 // Die if we can't resize previously allocated memory.  (This returns a pointer
57 // to the new memory, which may or may not be the same as the old memory.
58 // It'll copy the contents to a new chunk and free the old one if necessary.)
59 void* FAST_FUNC xrealloc(void *ptr, size_t size)
60 {
61         ptr = realloc(ptr, size);
62         if (ptr == NULL && size != 0)
63                 bb_die_memory_exhausted();
64         return ptr;
65 }
66 #endif /* DMALLOC */
67
68 // Die if we can't allocate and zero size bytes of memory.
69 void* FAST_FUNC xzalloc(size_t size)
70 {
71         void *ptr = xmalloc(size);
72         memset(ptr, 0, size);
73         return ptr;
74 }
75
76 // Die if we can't copy a string to freshly allocated memory.
77 char* FAST_FUNC xstrdup(const char *s)
78 {
79         char *t;
80
81         if (s == NULL)
82                 return NULL;
83
84         t = strdup(s);
85
86         if (t == NULL)
87                 bb_die_memory_exhausted();
88
89         return t;
90 }
91
92 // Die if we can't allocate n+1 bytes (space for the null terminator) and copy
93 // the (possibly truncated to length n) string into it.
94 char* FAST_FUNC xstrndup(const char *s, int n)
95 {
96         char *t;
97
98         if (ENABLE_DEBUG && s == NULL)
99                 bb_simple_error_msg_and_die("xstrndup bug");
100
101         t = strndup(s, n);
102
103         if (t == NULL)
104                 bb_die_memory_exhausted();
105
106         return t;
107 }
108
109 void* FAST_FUNC xmemdup(const void *s, int n)
110 {
111         return memcpy(xmalloc(n), s, n);
112 }
113
114 // Die if we can't open a file and return a FILE* to it.
115 // Notice we haven't got xfread(), This is for use with fscanf() and friends.
116 FILE* FAST_FUNC xfopen(const char *path, const char *mode)
117 {
118         FILE *fp = fopen(path, mode);
119         if (fp == NULL)
120                 bb_perror_msg_and_die("can't open '%s'", path);
121         return fp;
122 }
123
124 // Die if we can't open a file and return a fd.
125 int FAST_FUNC xopen3(const char *pathname, int flags, int mode)
126 {
127         int ret;
128
129         ret = open(pathname, flags, mode);
130         if (ret < 0) {
131                 bb_perror_msg_and_die("can't open '%s'", pathname);
132         }
133         return ret;
134 }
135
136 // Die if we can't open a file and return a fd.
137 int FAST_FUNC xopen(const char *pathname, int flags)
138 {
139         return xopen3(pathname, flags, 0666);
140 }
141
142 // Warn if we can't open a file and return a fd.
143 int FAST_FUNC open3_or_warn(const char *pathname, int flags, int mode)
144 {
145         int ret;
146
147         ret = open(pathname, flags, mode);
148         if (ret < 0) {
149                 bb_perror_msg("can't open '%s'", pathname);
150         }
151         return ret;
152 }
153
154 // Warn if we can't open a file and return a fd.
155 int FAST_FUNC open_or_warn(const char *pathname, int flags)
156 {
157         return open3_or_warn(pathname, flags, 0666);
158 }
159
160 /* Die if we can't open an existing file readonly with O_NONBLOCK
161  * and return the fd.
162  * Note that for ioctl O_RDONLY is sufficient.
163  */
164 int FAST_FUNC xopen_nonblocking(const char *pathname)
165 {
166         return xopen(pathname, O_RDONLY | O_NONBLOCK);
167 }
168
169 int FAST_FUNC xopen_as_uid_gid(const char *pathname, int flags, uid_t u, gid_t g)
170 {
171         int fd;
172         uid_t old_euid = geteuid();
173         gid_t old_egid = getegid();
174
175         xsetegid(g);
176         xseteuid(u);
177
178         fd = xopen(pathname, flags);
179
180         xseteuid(old_euid);
181         xsetegid(old_egid);
182
183         return fd;
184 }
185
186 void FAST_FUNC xunlink(const char *pathname)
187 {
188         if (unlink(pathname))
189                 bb_perror_msg_and_die("can't remove file '%s'", pathname);
190 }
191
192 void FAST_FUNC xrename(const char *oldpath, const char *newpath)
193 {
194         if (rename(oldpath, newpath))
195                 bb_perror_msg_and_die("can't move '%s' to '%s'", oldpath, newpath);
196 }
197
198 int FAST_FUNC rename_or_warn(const char *oldpath, const char *newpath)
199 {
200         int n = rename(oldpath, newpath);
201         if (n)
202                 bb_perror_msg("can't move '%s' to '%s'", oldpath, newpath);
203         return n;
204 }
205
206 void FAST_FUNC xpipe(int filedes[2])
207 {
208         if (pipe(filedes))
209                 bb_simple_perror_msg_and_die("can't create pipe");
210 }
211
212 void FAST_FUNC xdup2(int from, int to)
213 {
214         if (dup2(from, to) != to)
215                 bb_simple_perror_msg_and_die("can't duplicate file descriptor");
216                 //              " %d to %d", from, to);
217 }
218
219 // "Renumber" opened fd
220 void FAST_FUNC xmove_fd(int from, int to)
221 {
222         if (from == to)
223                 return;
224         xdup2(from, to);
225         close(from);
226 }
227
228 // Die with an error message if we can't write the entire buffer.
229 void FAST_FUNC xwrite(int fd, const void *buf, size_t count)
230 {
231         if (count) {
232                 ssize_t size = full_write(fd, buf, count);
233                 if ((size_t)size != count) {
234                         /*
235                          * Two cases: write error immediately;
236                          * or some writes succeeded, then we hit an error.
237                          * In either case, errno is set.
238                          */
239                         bb_simple_perror_msg_and_die(
240                                 size >= 0 ? "short write" : "write error"
241                         );
242                 }
243         }
244 }
245 void FAST_FUNC xwrite_str(int fd, const char *str)
246 {
247         xwrite(fd, str, strlen(str));
248 }
249
250 void FAST_FUNC xclose(int fd)
251 {
252         if (close(fd))
253                 bb_simple_perror_msg_and_die("close failed");
254 }
255
256 // Die with an error message if we can't lseek to the right spot.
257 off_t FAST_FUNC xlseek(int fd, off_t offset, int whence)
258 {
259         off_t off = lseek(fd, offset, whence);
260         if (off == (off_t)-1) {
261                 bb_perror_msg_and_die("lseek(%"OFF_FMT"u, %d)", offset, whence);
262         }
263         return off;
264 }
265
266 int FAST_FUNC xmkstemp(char *template)
267 {
268         int fd = mkstemp(template);
269         if (fd < 0)
270                 bb_perror_msg_and_die("can't create temp file '%s'", template);
271         return fd;
272 }
273
274 // Die with supplied filename if this FILE* has ferror set.
275 void FAST_FUNC die_if_ferror(FILE *fp, const char *fn)
276 {
277         if (ferror(fp)) {
278                 /* ferror doesn't set useful errno */
279                 bb_error_msg_and_die("%s: I/O error", fn);
280         }
281 }
282
283 // Die with an error message if stdout has ferror set.
284 void FAST_FUNC die_if_ferror_stdout(void)
285 {
286         die_if_ferror(stdout, bb_msg_standard_output);
287 }
288
289 int FAST_FUNC fflush_all(void)
290 {
291         return fflush(NULL);
292 }
293
294
295 int FAST_FUNC bb_putchar(int ch)
296 {
297         return putchar(ch);
298 }
299
300 /* Die with an error message if we can't copy an entire FILE* to stdout,
301  * then close that file. */
302 void FAST_FUNC xprint_and_close_file(FILE *file)
303 {
304         fflush_all();
305         // copyfd outputs error messages for us.
306         if (bb_copyfd_eof(fileno(file), STDOUT_FILENO) == -1)
307                 xfunc_die();
308
309         fclose(file);
310 }
311
312 // Die with an error message if we can't malloc() enough space and do an
313 // sprintf() into that space.
314 char* FAST_FUNC xasprintf(const char *format, ...)
315 {
316         va_list p;
317         int r;
318         char *string_ptr;
319
320         va_start(p, format);
321         r = vasprintf(&string_ptr, format, p);
322         va_end(p);
323
324         if (r < 0)
325                 bb_die_memory_exhausted();
326         return string_ptr;
327 }
328
329 void FAST_FUNC xsetenv(const char *key, const char *value)
330 {
331         if (setenv(key, value, 1))
332                 bb_die_memory_exhausted();
333 }
334
335 /* Handles "VAR=VAL" strings, even those which are part of environ
336  * _right now_
337  */
338 void FAST_FUNC bb_unsetenv(const char *var)
339 {
340         char onstack[128 - 16]; /* smaller stack setup code on x86 */
341         char *tp;
342
343         tp = strchr(var, '=');
344         if (tp) {
345                 /* In case var was putenv'ed, we can't replace '='
346                  * with NUL and unsetenv(var) - it won't work,
347                  * env is modified by the replacement, unsetenv
348                  * sees "VAR" instead of "VAR=VAL" and does not remove it!
349                  * Horror :(
350                  */
351                 unsigned sz = tp - var;
352                 if (sz < sizeof(onstack)) {
353                         ((char*)mempcpy(onstack, var, sz))[0] = '\0';
354                         tp = NULL;
355                         var = onstack;
356                 } else {
357                         /* unlikely: very long var name */
358                         var = tp = xstrndup(var, sz);
359                 }
360         }
361         unsetenv(var);
362         free(tp);
363 }
364
365 void FAST_FUNC bb_unsetenv_and_free(char *var)
366 {
367         bb_unsetenv(var);
368         free(var);
369 }
370
371 // Die with an error message if we can't set gid.  (Because resource limits may
372 // limit this user to a given number of processes, and if that fills up the
373 // setgid() will fail and we'll _still_be_root_, which is bad.)
374 void FAST_FUNC xsetgid(gid_t gid)
375 {
376         if (setgid(gid)) bb_simple_perror_msg_and_die("setgid");
377 }
378
379 // Die with an error message if we can't set uid.  (See xsetgid() for why.)
380 void FAST_FUNC xsetuid(uid_t uid)
381 {
382         if (setuid(uid)) bb_simple_perror_msg_and_die("setuid");
383 }
384
385 void FAST_FUNC xsetegid(gid_t egid)
386 {
387         if (setegid(egid)) bb_simple_perror_msg_and_die("setegid");
388 }
389
390 void FAST_FUNC xseteuid(uid_t euid)
391 {
392         if (seteuid(euid)) bb_simple_perror_msg_and_die("seteuid");
393 }
394
395 // Die if we can't chdir to a new path.
396 void FAST_FUNC xchdir(const char *path)
397 {
398         if (chdir(path))
399                 bb_perror_msg_and_die("can't change directory to '%s'", path);
400 }
401
402 void FAST_FUNC xfchdir(int fd)
403 {
404         if (fchdir(fd))
405                 bb_simple_perror_msg_and_die("fchdir");
406 }
407
408 void FAST_FUNC xchroot(const char *path)
409 {
410         if (chroot(path))
411                 bb_perror_msg_and_die("can't change root directory to '%s'", path);
412         xchdir("/");
413 }
414
415 // Print a warning message if opendir() fails, but don't die.
416 DIR* FAST_FUNC warn_opendir(const char *path)
417 {
418         DIR *dp;
419
420         dp = opendir(path);
421         if (!dp)
422                 bb_perror_msg("can't open '%s'", path);
423         return dp;
424 }
425
426 // Die with an error message if opendir() fails.
427 DIR* FAST_FUNC xopendir(const char *path)
428 {
429         DIR *dp;
430
431         dp = opendir(path);
432         if (!dp)
433                 bb_perror_msg_and_die("can't open '%s'", path);
434         return dp;
435 }
436
437 // Die with an error message if we can't open a new socket.
438 int FAST_FUNC xsocket(int domain, int type, int protocol)
439 {
440         int r = socket(domain, type, protocol);
441
442         if (r < 0) {
443                 /* Hijack vaguely related config option */
444 #if ENABLE_VERBOSE_RESOLUTION_ERRORS
445                 const char *s = "INET";
446 # ifdef AF_PACKET
447                 if (domain == AF_PACKET) s = "PACKET";
448 # endif
449 # ifdef AF_NETLINK
450                 if (domain == AF_NETLINK) s = "NETLINK";
451 # endif
452 IF_FEATURE_IPV6(if (domain == AF_INET6) s = "INET6";)
453                 bb_perror_msg_and_die("socket(AF_%s,%d,%d)", s, type, protocol);
454 #else
455                 bb_simple_perror_msg_and_die("socket");
456 #endif
457         }
458
459         return r;
460 }
461
462 // Die with an error message if we can't bind a socket to an address.
463 void FAST_FUNC xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen)
464 {
465         if (bind(sockfd, my_addr, addrlen)) bb_simple_perror_msg_and_die("bind");
466 }
467
468 // Die with an error message if we can't listen for connections on a socket.
469 void FAST_FUNC xlisten(int s, int backlog)
470 {
471         if (listen(s, backlog)) bb_simple_perror_msg_and_die("listen");
472 }
473
474 /* Die with an error message if sendto failed.
475  * Return bytes sent otherwise  */
476 ssize_t FAST_FUNC xsendto(int s, const void *buf, size_t len, const struct sockaddr *to,
477                                 socklen_t tolen)
478 {
479         ssize_t ret = sendto(s, buf, len, 0, to, tolen);
480         if (ret < 0) {
481                 if (ENABLE_FEATURE_CLEAN_UP)
482                         close(s);
483                 bb_simple_perror_msg_and_die("sendto");
484         }
485         return ret;
486 }
487
488 // xstat() - a stat() which dies on failure with meaningful error message
489 void FAST_FUNC xstat(const char *name, struct stat *stat_buf)
490 {
491         if (stat(name, stat_buf))
492                 bb_perror_msg_and_die("can't stat '%s'", name);
493 }
494
495 void FAST_FUNC xfstat(int fd, struct stat *stat_buf, const char *errmsg)
496 {
497         /* errmsg is usually a file name, but not always:
498          * xfstat may be called in a spot where file name is no longer
499          * available, and caller may give e.g. "can't stat input file" string.
500          */
501         if (fstat(fd, stat_buf))
502                 bb_simple_perror_msg_and_die(errmsg);
503 }
504
505 // selinux_or_die() - die if SELinux is disabled.
506 void FAST_FUNC selinux_or_die(void)
507 {
508 #if ENABLE_SELINUX
509         int rc = is_selinux_enabled();
510         if (rc == 0) {
511                 bb_simple_error_msg_and_die("SELinux is disabled");
512         } else if (rc < 0) {
513                 bb_simple_error_msg_and_die("is_selinux_enabled() failed");
514         }
515 #else
516         bb_simple_error_msg_and_die("SELinux support is disabled");
517 #endif
518 }
519
520 int FAST_FUNC ioctl_or_perror_and_die(int fd, unsigned request, void *argp, const char *fmt,...)
521 {
522         int ret;
523         va_list p;
524
525         ret = ioctl(fd, request, argp);
526         if (ret < 0) {
527                 va_start(p, fmt);
528                 bb_verror_msg(fmt, p, strerror(errno));
529                 /* xfunc_die can actually longjmp, so be nice */
530                 va_end(p);
531                 xfunc_die();
532         }
533         return ret;
534 }
535
536 int FAST_FUNC ioctl_or_perror(int fd, unsigned request, void *argp, const char *fmt,...)
537 {
538         va_list p;
539         int ret = ioctl(fd, request, argp);
540
541         if (ret < 0) {
542                 va_start(p, fmt);
543                 bb_verror_msg(fmt, p, strerror(errno));
544                 va_end(p);
545         }
546         return ret;
547 }
548
549 #if ENABLE_IOCTL_HEX2STR_ERROR
550 int FAST_FUNC bb_ioctl_or_warn(int fd, unsigned request, void *argp, const char *ioctl_name)
551 {
552         int ret;
553
554         ret = ioctl(fd, request, argp);
555         if (ret < 0)
556                 bb_simple_perror_msg(ioctl_name);
557         return ret;
558 }
559 int FAST_FUNC bb_xioctl(int fd, unsigned request, void *argp, const char *ioctl_name)
560 {
561         int ret;
562
563         ret = ioctl(fd, request, argp);
564         if (ret < 0)
565                 bb_simple_perror_msg_and_die(ioctl_name);
566         return ret;
567 }
568 #else
569 int FAST_FUNC bb_ioctl_or_warn(int fd, unsigned request, void *argp)
570 {
571         int ret;
572
573         ret = ioctl(fd, request, argp);
574         if (ret < 0)
575                 bb_perror_msg("ioctl %#x failed", request);
576         return ret;
577 }
578 int FAST_FUNC bb_xioctl(int fd, unsigned request, void *argp)
579 {
580         int ret;
581
582         ret = ioctl(fd, request, argp);
583         if (ret < 0)
584                 bb_perror_msg_and_die("ioctl %#x failed", request);
585         return ret;
586 }
587 #endif
588
589 char* FAST_FUNC xmalloc_ttyname(int fd)
590 {
591         char buf[128];
592         int r = ttyname_r(fd, buf, sizeof(buf) - 1);
593         if (r)
594                 return NULL;
595         return xstrdup(buf);
596 }
597
598 void FAST_FUNC generate_uuid(uint8_t *buf)
599 {
600         /* http://www.ietf.org/rfc/rfc4122.txt
601          *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
602          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
603          * |                          time_low                             |
604          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
605          * |       time_mid                |         time_hi_and_version   |
606          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
607          * |clk_seq_and_variant            |         node (0-1)            |
608          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
609          * |                         node (2-5)                            |
610          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
611          * IOW, uuid has this layout:
612          * uint32_t time_low (big endian)
613          * uint16_t time_mid (big endian)
614          * uint16_t time_hi_and_version (big endian)
615          *  version is a 4-bit field:
616          *   1 Time-based
617          *   2 DCE Security, with embedded POSIX UIDs
618          *   3 Name-based (MD5)
619          *   4 Randomly generated
620          *   5 Name-based (SHA-1)
621          * uint16_t clk_seq_and_variant (big endian)
622          *  variant is a 3-bit field:
623          *   0xx Reserved, NCS backward compatibility
624          *   10x The variant specified in rfc4122
625          *   110 Reserved, Microsoft backward compatibility
626          *   111 Reserved for future definition
627          * uint8_t node[6]
628          *
629          * For version 4, these bits are set/cleared:
630          * time_hi_and_version & 0x0fff | 0x4000
631          * clk_seq_and_variant & 0x3fff | 0x8000
632          */
633         pid_t pid;
634         int i;
635
636         i = open("/dev/urandom", O_RDONLY);
637         if (i >= 0) {
638                 read(i, buf, 16);
639                 close(i);
640         }
641         /* Paranoia. /dev/urandom may be missing.
642          * rand() is guaranteed to generate at least [0, 2^15) range,
643          * but lowest bits in some libc are not so "random".  */
644         srand(monotonic_us()); /* pulls in printf */
645         pid = getpid();
646         while (1) {
647                 for (i = 0; i < 16; i++)
648                         buf[i] ^= rand() >> 5;
649                 if (pid == 0)
650                         break;
651                 srand(pid);
652                 pid = 0;
653         }
654
655         /* version = 4 */
656         buf[4 + 2    ] = (buf[4 + 2    ] & 0x0f) | 0x40;
657         /* variant = 10x */
658         buf[4 + 2 + 2] = (buf[4 + 2 + 2] & 0x3f) | 0x80;
659 }
660
661 #if BB_MMU
662 pid_t FAST_FUNC xfork(void)
663 {
664         pid_t pid;
665         pid = fork();
666         if (pid < 0) /* wtf? */
667                 bb_simple_perror_msg_and_die("vfork"+1);
668         return pid;
669 }
670 #endif
671
672 void FAST_FUNC xvfork_parent_waits_and_exits(void)
673 {
674         pid_t pid;
675
676         fflush_all();
677         pid = xvfork();
678         if (pid > 0) {
679                 /* Parent */
680                 int exit_status = wait_for_exitstatus(pid);
681                 if (WIFSIGNALED(exit_status))
682                         kill_myself_with_sig(WTERMSIG(exit_status));
683                 _exit(WEXITSTATUS(exit_status));
684         }
685         /* Child continues */
686 }