blob: 98d3531d6221064d35f1f0daa5b56a4117a00176 [file] [log] [blame]
Eric Andersenaad1a882001-03-16 22:47:14 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Utility routines.
4 *
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Rob Landleyd921b2e2006-08-03 15:41:12 +00006 * Copyright (C) 2006 Rob Landley
Denis Vlasenkod18f52b2008-03-02 12:53:15 +00007 * Copyright (C) 2006 Denys Vlasenko
Eric Andersenaad1a882001-03-16 22:47:14 +00008 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02009 * Licensed under GPLv2, see file LICENSE in this source tree.
Eric Andersenaad1a882001-03-16 22:47:14 +000010 */
11
Denis Vlasenkob12b1c82008-04-09 00:33:23 +000012/* 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 * TODO: move xmalloc() and xatonum() here.
23 */
24
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000025#include "libbb.h"
Eric Andersenaad1a882001-03-16 22:47:14 +000026
Denis Vlasenkob12b1c82008-04-09 00:33:23 +000027/* Turn on nonblocking I/O on a fd */
Denys Vlasenkod6e76722014-09-22 21:14:02 +020028int FAST_FUNC ndelay_on(int fd)
Denis Vlasenko75f8d082006-11-22 15:54:52 +000029{
Denys Vlasenkoe9a40e32011-01-24 00:29:55 +010030 int flags = fcntl(fd, F_GETFL);
31 if (flags & O_NONBLOCK)
Denys Vlasenkod6e76722014-09-22 21:14:02 +020032 return flags;
Denys Vlasenkoe9a40e32011-01-24 00:29:55 +010033 fcntl(fd, F_SETFL, flags | O_NONBLOCK);
Denys Vlasenkod6e76722014-09-22 21:14:02 +020034 return flags;
Denis Vlasenko75f8d082006-11-22 15:54:52 +000035}
36
Denys Vlasenkod6e76722014-09-22 21:14:02 +020037int FAST_FUNC ndelay_off(int fd)
Denis Vlasenkoa5b3e762006-12-24 07:15:50 +000038{
Denys Vlasenkoe9a40e32011-01-24 00:29:55 +010039 int flags = fcntl(fd, F_GETFL);
40 if (!(flags & O_NONBLOCK))
Denys Vlasenkod6e76722014-09-22 21:14:02 +020041 return flags;
Denys Vlasenkoe9a40e32011-01-24 00:29:55 +010042 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
Denys Vlasenkod6e76722014-09-22 21:14:02 +020043 return flags;
Denis Vlasenkoa5b3e762006-12-24 07:15:50 +000044}
45
Denys Vlasenkoe9a40e32011-01-24 00:29:55 +010046void FAST_FUNC close_on_exec_on(int fd)
Denis Vlasenkoa27a11b2007-08-18 14:16:39 +000047{
Denys Vlasenkoe9a40e32011-01-24 00:29:55 +010048 fcntl(fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkoa27a11b2007-08-18 14:16:39 +000049}
50
Denis Vlasenko360d9662008-12-02 18:18:50 +000051char* FAST_FUNC strncpy_IFNAMSIZ(char *dst, const char *src)
52{
53#ifndef IFNAMSIZ
54 enum { IFNAMSIZ = 16 };
55#endif
56 return strncpy(dst, src, IFNAMSIZ);
57}
58
Denis Vlasenko56ea65c2008-01-06 03:26:53 +000059
Denys Vlasenkoab60cd12010-06-10 10:54:44 +020060/* Convert unsigned integer to ascii, writing into supplied buffer.
61 * A truncated result contains the first few digits of the result ala strncpy.
62 * Returns a pointer past last generated digit, does _not_ store NUL.
63 */
64void BUG_sizeof(void);
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +000065char* FAST_FUNC utoa_to_buf(unsigned n, char *buf, unsigned buflen)
Rob Landley5b88a382006-07-10 07:41:34 +000066{
Denis Vlasenkoaae03112006-11-05 00:44:39 +000067 unsigned i, out, res;
Denys Vlasenkoab60cd12010-06-10 10:54:44 +020068
Rob Landley22d39582006-07-11 00:44:36 +000069 if (buflen) {
Denis Vlasenkoaae03112006-11-05 00:44:39 +000070 out = 0;
Denys Vlasenkoab60cd12010-06-10 10:54:44 +020071 if (sizeof(n) == 4)
72 // 2^32-1 = 4294967295
73 i = 1000000000;
74#if UINT_MAX > 4294967295 /* prevents warning about "const too large" */
75 else
76 if (sizeof(n) == 8)
77 // 2^64-1 = 18446744073709551615
78 i = 10000000000000000000;
79#endif
80 else
81 BUG_sizeof();
82 for (; i; i /= 10) {
Denis Vlasenkoaae03112006-11-05 00:44:39 +000083 res = n / i;
Denys Vlasenkoab60cd12010-06-10 10:54:44 +020084 n = n % i;
Denis Vlasenkoaae03112006-11-05 00:44:39 +000085 if (res || out || i == 1) {
Denys Vlasenkoab60cd12010-06-10 10:54:44 +020086 if (--buflen == 0)
87 break;
Rob Landley22d39582006-07-11 00:44:36 +000088 out++;
Rob Landley22d39582006-07-11 00:44:36 +000089 *buf++ = '0' + res;
90 }
Rob Landley5b88a382006-07-10 07:41:34 +000091 }
92 }
Denis Vlasenko10457b92007-03-27 22:01:31 +000093 return buf;
Rob Landley5b88a382006-07-10 07:41:34 +000094}
95
Denis Vlasenkob12b1c82008-04-09 00:33:23 +000096/* Convert signed integer to ascii, like utoa_to_buf() */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +000097char* FAST_FUNC itoa_to_buf(int n, char *buf, unsigned buflen)
Rob Landley5b88a382006-07-10 07:41:34 +000098{
Denys Vlasenkoab60cd12010-06-10 10:54:44 +020099 if (!buflen)
100 return buf;
101 if (n < 0) {
Rob Landley5b88a382006-07-10 07:41:34 +0000102 n = -n;
103 *buf++ = '-';
Rob Landley22d39582006-07-11 00:44:36 +0000104 buflen--;
Rob Landley5b88a382006-07-10 07:41:34 +0000105 }
Denis Vlasenko10457b92007-03-27 22:01:31 +0000106 return utoa_to_buf((unsigned)n, buf, buflen);
Rob Landley5b88a382006-07-10 07:41:34 +0000107}
108
Rob Landleyda9d1d02006-09-14 19:52:07 +0000109// The following two functions use a static buffer, so calling either one a
110// second time will overwrite previous results.
111//
Denys Vlasenkoab60cd12010-06-10 10:54:44 +0200112// The largest 32 bit integer is -2 billion plus NUL, or 1+10+1=12 bytes.
113// It so happens that sizeof(int) * 3 is enough for 32+ bit ints.
Denis Vlasenkob12b1c82008-04-09 00:33:23 +0000114// (sizeof(int) * 3 + 2 is correct for any width, even 8-bit)
Rob Landleyda9d1d02006-09-14 19:52:07 +0000115
Denis Vlasenkob12b1c82008-04-09 00:33:23 +0000116static char local_buf[sizeof(int) * 3];
Rob Landley23b61be2006-08-04 20:20:03 +0000117
Denys Vlasenkoab60cd12010-06-10 10:54:44 +0200118/* Convert unsigned integer to ascii using a static buffer (returned). */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000119char* FAST_FUNC utoa(unsigned n)
Rob Landley23b61be2006-08-04 20:20:03 +0000120{
Denys Vlasenkoab60cd12010-06-10 10:54:44 +0200121 *(utoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
Rob Landley23b61be2006-08-04 20:20:03 +0000122
123 return local_buf;
124}
125
Denis Vlasenkob12b1c82008-04-09 00:33:23 +0000126/* Convert signed integer to ascii using a static buffer (returned). */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000127char* FAST_FUNC itoa(int n)
Rob Landley5b88a382006-07-10 07:41:34 +0000128{
Denys Vlasenkoab60cd12010-06-10 10:54:44 +0200129 *(itoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
Rob Landley5b88a382006-07-10 07:41:34 +0000130
131 return local_buf;
132}
Rob Landleydf822f22006-07-15 23:00:46 +0000133
Denis Vlasenkob12b1c82008-04-09 00:33:23 +0000134/* Emit a string of hex representation of bytes */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000135char* FAST_FUNC bin2hex(char *p, const char *cp, int count)
Denis Vlasenko3a34d0c2007-01-12 22:10:34 +0000136{
137 while (count) {
138 unsigned char c = *cp++;
139 /* put lowercase hex digits */
Denis Vlasenko98c0bba2007-01-26 23:31:05 +0000140 *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
141 *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
Denis Vlasenko3a34d0c2007-01-12 22:10:34 +0000142 count--;
143 }
144 return p;
145}
146
Denys Vlasenko48363312010-04-04 15:29:32 +0200147/* Convert "[x]x[:][x]x[:][x]x[:][x]x" hex string to binary, no more than COUNT bytes */
148char* FAST_FUNC hex2bin(char *dst, const char *str, int count)
149{
150 errno = EINVAL;
151 while (*str && count) {
152 uint8_t val;
153 uint8_t c = *str++;
154 if (isdigit(c))
155 val = c - '0';
156 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
157 val = (c|0x20) - ('a' - 10);
158 else
159 return NULL;
160 val <<= 4;
161 c = *str;
162 if (isdigit(c))
163 val |= c - '0';
164 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
165 val |= (c|0x20) - ('a' - 10);
166 else if (c == ':' || c == '\0')
167 val >>= 4;
168 else
169 return NULL;
170
171 *dst++ = val;
172 if (c != '\0')
173 str++;
174 if (*str == ':')
175 str++;
176 count--;
177 }
178 errno = (*str ? ERANGE : 0);
179 return dst;
180}
181
Denis Vlasenkob12b1c82008-04-09 00:33:23 +0000182/* Return how long the file at fd is, if there's any way to determine it. */
Denis Vlasenkob5c60fc2008-01-27 23:41:34 +0000183#ifdef UNUSED
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000184off_t FAST_FUNC fdlength(int fd)
Rob Landley53437472006-07-16 08:14:35 +0000185{
186 off_t bottom = 0, top = 0, pos;
187 long size;
188
Rob Landleyda9d1d02006-09-14 19:52:07 +0000189 // If the ioctl works for this, return it.
Rob Landley53437472006-07-16 08:14:35 +0000190
191 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
192
Denis Vlasenko621204b2006-10-27 09:03:24 +0000193 // FIXME: explain why lseek(SEEK_END) is not used here!
194
Rob Landleyda9d1d02006-09-14 19:52:07 +0000195 // If not, do a binary search for the last location we can read. (Some
196 // block devices don't do BLKGETSIZE right.)
Rob Landley53437472006-07-16 08:14:35 +0000197
198 do {
199 char temp;
200
Denis Vlasenkod25a2642006-09-05 09:36:19 +0000201 pos = bottom + (top - bottom) / 2;
Rob Landley53437472006-07-16 08:14:35 +0000202
Rob Landleyda9d1d02006-09-14 19:52:07 +0000203 // If we can read from the current location, it's bigger.
Rob Landley53437472006-07-16 08:14:35 +0000204
Denis Vlasenkoea620772006-10-14 02:23:43 +0000205 if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
Rob Landley53437472006-07-16 08:14:35 +0000206 if (bottom == top) bottom = top = (top+1) * 2;
207 else bottom = pos;
208
Rob Landleyda9d1d02006-09-14 19:52:07 +0000209 // If we can't, it's smaller.
Rob Landley53437472006-07-16 08:14:35 +0000210 } else {
211 if (bottom == top) {
212 if (!top) return 0;
213 bottom = top/2;
214 }
215 else top = pos;
216 }
217 } while (bottom + 1 != top);
218
219 return pos + 1;
220}
Denis Vlasenkob5c60fc2008-01-27 23:41:34 +0000221#endif
Rob Landleyd921b2e2006-08-03 15:41:12 +0000222
Denys Vlasenko19ced5c2010-06-06 21:53:09 +0200223int FAST_FUNC bb_putchar_stderr(char ch)
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +0000224{
Denys Vlasenko19ced5c2010-06-06 21:53:09 +0200225 return write(STDERR_FILENO, &ch, 1);
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +0000226}
227
Denys Vlasenko729ecb82010-06-07 14:14:26 +0200228ssize_t FAST_FUNC full_write1_str(const char *str)
229{
230 return full_write(STDOUT_FILENO, str, strlen(str));
231}
232
233ssize_t FAST_FUNC full_write2_str(const char *str)
234{
235 return full_write(STDERR_FILENO, str, strlen(str));
236}
237
Denys Vlasenkoc175c462010-04-18 22:09:30 -0700238static int wh_helper(int value, int def_val, const char *env_name, int *err)
239{
Denys Vlasenko7c3c92c2016-10-31 01:52:18 +0100240 /* Envvars override even if "value" from ioctl is valid (>0).
241 * Rationale: it's impossible to guess what user wants.
242 * For example: "man CMD | ...": should "man" format output
243 * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
244 * We _cant_ know it. If "..." saves text for e.g. email,
245 * then it's probably 80 chars.
246 * If "..." is, say, "grep -v DISCARD | $PAGER", then user
247 * would prefer his tty's width to be used!
248 *
249 * Since we don't know, at least allow user to do this:
250 * "COLUMNS=80 man CMD | ..."
251 */
252 char *s = getenv(env_name);
253 if (s) {
254 value = atoi(s);
255 /* If LINES/COLUMNS are set, pretend that there is
256 * no error getting w/h, this prevents some ugly
257 * cursor tricks by our callers */
258 *err = 0;
Denys Vlasenkoc175c462010-04-18 22:09:30 -0700259 }
Denys Vlasenko7c3c92c2016-10-31 01:52:18 +0100260
Denys Vlasenkoc175c462010-04-18 22:09:30 -0700261 if (value <= 1 || value >= 30000)
262 value = def_val;
263 return value;
264}
265
Rob Landleyfbdf1212006-09-20 22:06:01 +0000266/* It is perfectly ok to pass in a NULL for either width or for
Denis Vlasenko621204b2006-10-27 09:03:24 +0000267 * height, in which case that value will not be set. */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000268int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
Rob Landleyfbdf1212006-09-20 22:06:01 +0000269{
Denys Vlasenkoc175c462010-04-18 22:09:30 -0700270 struct winsize win;
271 int err;
Denys Vlasenko7c3c92c2016-10-31 01:52:18 +0100272 int close_me = -1;
273
274 if (fd == -1) {
275 if (isatty(STDOUT_FILENO))
276 fd = STDOUT_FILENO;
277 else
278 if (isatty(STDERR_FILENO))
279 fd = STDERR_FILENO;
280 else
281 if (isatty(STDIN_FILENO))
282 fd = STDIN_FILENO;
283 else
284 close_me = fd = open("/dev/tty", O_RDONLY);
285 }
Denis Vlasenko621204b2006-10-27 09:03:24 +0000286
Denys Vlasenkoc175c462010-04-18 22:09:30 -0700287 win.ws_row = 0;
288 win.ws_col = 0;
289 /* I've seen ioctl returning 0, but row/col is (still?) 0.
290 * We treat that as an error too. */
291 err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
292 if (height)
293 *height = wh_helper(win.ws_row, 24, "LINES", &err);
294 if (width)
295 *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
Denys Vlasenko7c3c92c2016-10-31 01:52:18 +0100296
297 if (close_me >= 0)
298 close(close_me);
299
Denys Vlasenkoc175c462010-04-18 22:09:30 -0700300 return err;
Rob Landleyfbdf1212006-09-20 22:06:01 +0000301}
Denys Vlasenko641caae2015-10-23 01:44:22 +0200302int FAST_FUNC get_terminal_width(int fd)
303{
304 unsigned width;
305 get_terminal_width_height(fd, &width, NULL);
306 return width;
307}
Denis Vlasenko202ac502008-11-05 13:20:58 +0000308
309int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
310{
311 return tcsetattr(STDIN_FILENO, TCSANOW, tp);
312}
Pascal Bellard21e8e8d2010-07-04 00:57:03 +0200313
Denys Vlasenko01ccdd12017-01-11 16:17:59 +0100314int FAST_FUNC set_termios_to_raw(int fd, struct termios *oldterm, int flags)
315{
316//TODO: lineedit, microcom and less might be adapted to use this too:
317// grep for "tcsetattr"
318
319 struct termios newterm;
320
321 tcgetattr(fd, oldterm);
322 newterm = *oldterm;
323
324 /* Turn off buffered input (ICANON)
325 * Turn off echoing (ECHO)
326 * and separate echoing of newline (ECHONL, normally off anyway)
327 */
328 newterm.c_lflag &= ~(ICANON | ECHO | ECHONL);
329 if (flags & TERMIOS_CLEAR_ISIG) {
330 /* dont recognize INT/QUIT/SUSP chars */
331 newterm.c_lflag &= ~ISIG;
332 }
333 /* reads will block only if < 1 char is available */
334 newterm.c_cc[VMIN] = 1;
335 /* no timeout (reads block forever) */
336 newterm.c_cc[VTIME] = 0;
337 if (flags & TERMIOS_RAW_CRNL) {
338 /* dont convert CR to NL on input */
339 newterm.c_iflag &= ~(IXON | ICRNL);
340 /* dont convert NL to CR on output */
341 newterm.c_oflag &= ~(ONLCR);
342 }
343 if (flags & TERMIOS_RAW_INPUT) {
344 /* dont convert anything on input */
345 newterm.c_iflag &= ~(BRKINT|INLCR|ICRNL|IXON|IXOFF|IUCLC|IXANY|IMAXBEL);
346 }
347
348 return tcsetattr(fd, TCSANOW, &newterm);
349}
350
Pascal Bellard21e8e8d2010-07-04 00:57:03 +0200351pid_t FAST_FUNC safe_waitpid(pid_t pid, int *wstat, int options)
352{
353 pid_t r;
354
355 do
356 r = waitpid(pid, wstat, options);
357 while ((r == -1) && (errno == EINTR));
358 return r;
359}
360
361pid_t FAST_FUNC wait_any_nohang(int *wstat)
362{
363 return safe_waitpid(-1, wstat, WNOHANG);
364}
365
366// Wait for the specified child PID to exit, returning child's error return.
367int FAST_FUNC wait4pid(pid_t pid)
368{
369 int status;
370
371 if (pid <= 0) {
372 /*errno = ECHILD; -- wrong. */
373 /* we expect errno to be already set from failed [v]fork/exec */
374 return -1;
375 }
376 if (safe_waitpid(pid, &status, 0) == -1)
377 return -1;
378 if (WIFEXITED(status))
379 return WEXITSTATUS(status);
380 if (WIFSIGNALED(status))
381 return WTERMSIG(status) + 0x180;
382 return 0;
383}
Denys Vlasenkoc4199f22016-04-01 22:12:44 +0200384
385// Useful when we do know that pid is valid, and we just want to wait
386// for it to exit. Not existing pid is fatal. waitpid() status is not returned.
387int FAST_FUNC wait_for_exitstatus(pid_t pid)
388{
389 int exit_status, n;
390
391 n = safe_waitpid(pid, &exit_status, 0);
392 if (n < 0)
393 bb_perror_msg_and_die("waitpid");
394 return exit_status;
395}