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