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