xfuncs: Handle missing non-POSIX termios constants
[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 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  * TODO: move xmalloc() and xatonum() here.
22  */
23 #include "libbb.h"
24
25 /* Turn on nonblocking I/O on a fd */
26 int FAST_FUNC ndelay_on(int fd)
27 {
28         int flags = fcntl(fd, F_GETFL);
29         if (flags & O_NONBLOCK)
30                 return flags;
31         fcntl(fd, F_SETFL, flags | O_NONBLOCK);
32         return flags;
33 }
34
35 int FAST_FUNC ndelay_off(int fd)
36 {
37         int flags = fcntl(fd, F_GETFL);
38         if (!(flags & O_NONBLOCK))
39                 return flags;
40         fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
41         return flags;
42 }
43
44 void FAST_FUNC close_on_exec_on(int fd)
45 {
46         fcntl(fd, F_SETFD, FD_CLOEXEC);
47 }
48
49 char* FAST_FUNC strncpy_IFNAMSIZ(char *dst, const char *src)
50 {
51 #ifndef IFNAMSIZ
52         enum { IFNAMSIZ = 16 };
53 #endif
54         return strncpy(dst, src, IFNAMSIZ);
55 }
56
57
58 /* Convert unsigned integer to ascii, writing into supplied buffer.
59  * A truncated result contains the first few digits of the result ala strncpy.
60  * Returns a pointer past last generated digit, does _not_ store NUL.
61  */
62 void BUG_sizeof(void);
63 char* FAST_FUNC utoa_to_buf(unsigned n, char *buf, unsigned buflen)
64 {
65         unsigned i, out, res;
66
67         if (buflen) {
68                 out = 0;
69                 if (sizeof(n) == 4)
70                 // 2^32-1 = 4294967295
71                         i = 1000000000;
72 #if UINT_MAX > 4294967295 /* prevents warning about "const too large" */
73                 else
74                 if (sizeof(n) == 8)
75                 // 2^64-1 = 18446744073709551615
76                         i = 10000000000000000000;
77 #endif
78                 else
79                         BUG_sizeof();
80                 for (; i; i /= 10) {
81                         res = n / i;
82                         n = n % i;
83                         if (res || out || i == 1) {
84                                 if (--buflen == 0)
85                                         break;
86                                 out++;
87                                 *buf++ = '0' + res;
88                         }
89                 }
90         }
91         return buf;
92 }
93
94 /* Convert signed integer to ascii, like utoa_to_buf() */
95 char* FAST_FUNC itoa_to_buf(int n, char *buf, unsigned buflen)
96 {
97         if (!buflen)
98                 return buf;
99         if (n < 0) {
100                 n = -n;
101                 *buf++ = '-';
102                 buflen--;
103         }
104         return utoa_to_buf((unsigned)n, buf, buflen);
105 }
106
107 // The following two functions use a static buffer, so calling either one a
108 // second time will overwrite previous results.
109 //
110 // The largest 32 bit integer is -2 billion plus NUL, or 1+10+1=12 bytes.
111 // It so happens that sizeof(int) * 3 is enough for 32+ bit ints.
112 // (sizeof(int) * 3 + 2 is correct for any width, even 8-bit)
113
114 static char local_buf[sizeof(int) * 3];
115
116 /* Convert unsigned integer to ascii using a static buffer (returned). */
117 char* FAST_FUNC utoa(unsigned n)
118 {
119         *(utoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
120
121         return local_buf;
122 }
123
124 /* Convert signed integer to ascii using a static buffer (returned). */
125 char* FAST_FUNC itoa(int n)
126 {
127         *(itoa_to_buf(n, local_buf, sizeof(local_buf) - 1)) = '\0';
128
129         return local_buf;
130 }
131
132 /* Emit a string of hex representation of bytes */
133 char* FAST_FUNC bin2hex(char *p, const char *cp, int count)
134 {
135         while (count) {
136                 unsigned char c = *cp++;
137                 /* put lowercase hex digits */
138                 *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
139                 *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
140                 count--;
141         }
142         return p;
143 }
144
145 /* Convert "[x]x[:][x]x[:][x]x[:][x]x" hex string to binary, no more than COUNT bytes */
146 char* FAST_FUNC hex2bin(char *dst, const char *str, int count)
147 {
148         errno = EINVAL;
149         while (*str && count) {
150                 uint8_t val;
151                 uint8_t c = *str++;
152                 if (isdigit(c))
153                         val = c - '0';
154                 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
155                         val = (c|0x20) - ('a' - 10);
156                 else
157                         return NULL;
158                 val <<= 4;
159                 c = *str;
160                 if (isdigit(c))
161                         val |= c - '0';
162                 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
163                         val |= (c|0x20) - ('a' - 10);
164                 else if (c == ':' || c == '\0')
165                         val >>= 4;
166                 else
167                         return NULL;
168
169                 *dst++ = val;
170                 if (c != '\0')
171                         str++;
172                 if (*str == ':')
173                         str++;
174                 count--;
175         }
176         errno = (*str ? ERANGE : 0);
177         return dst;
178 }
179
180 /* Return how long the file at fd is, if there's any way to determine it. */
181 #ifdef UNUSED
182 off_t FAST_FUNC fdlength(int fd)
183 {
184         off_t bottom = 0, top = 0, pos;
185         long size;
186
187         // If the ioctl works for this, return it.
188
189         if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
190
191         // FIXME: explain why lseek(SEEK_END) is not used here!
192
193         // If not, do a binary search for the last location we can read.  (Some
194         // block devices don't do BLKGETSIZE right.)
195
196         do {
197                 char temp;
198
199                 pos = bottom + (top - bottom) / 2;
200
201                 // If we can read from the current location, it's bigger.
202
203                 if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
204                         if (bottom == top) bottom = top = (top+1) * 2;
205                         else bottom = pos;
206
207                 // If we can't, it's smaller.
208                 } else {
209                         if (bottom == top) {
210                                 if (!top) return 0;
211                                 bottom = top/2;
212                         }
213                         else top = pos;
214                 }
215         } while (bottom + 1 != top);
216
217         return pos + 1;
218 }
219 #endif
220
221 int FAST_FUNC bb_putchar_stderr(char ch)
222 {
223         return write(STDERR_FILENO, &ch, 1);
224 }
225
226 ssize_t FAST_FUNC full_write1_str(const char *str)
227 {
228         return full_write(STDOUT_FILENO, str, strlen(str));
229 }
230
231 ssize_t FAST_FUNC full_write2_str(const char *str)
232 {
233         return full_write(STDERR_FILENO, str, strlen(str));
234 }
235
236 static int wh_helper(int value, int def_val, const char *env_name, int *err)
237 {
238         /* Envvars override even if "value" from ioctl is valid (>0).
239          * Rationale: it's impossible to guess what user wants.
240          * For example: "man CMD | ...": should "man" format output
241          * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
242          * We _cant_ know it. If "..." saves text for e.g. email,
243          * then it's probably 80 chars.
244          * If "..." is, say, "grep -v DISCARD | $PAGER", then user
245          * would prefer his tty's width to be used!
246          *
247          * Since we don't know, at least allow user to do this:
248          * "COLUMNS=80 man CMD | ..."
249          */
250         char *s = getenv(env_name);
251         if (s) {
252                 value = atoi(s);
253                 /* If LINES/COLUMNS are set, pretend that there is
254                  * no error getting w/h, this prevents some ugly
255                  * cursor tricks by our callers */
256                 *err = 0;
257         }
258
259         if (value <= 1 || value >= 30000)
260                 value = def_val;
261         return value;
262 }
263
264 /* It is perfectly ok to pass in a NULL for either width or for
265  * height, in which case that value will not be set.  */
266 int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
267 {
268         struct winsize win;
269         int err;
270         int close_me = -1;
271
272         if (fd == -1) {
273                 if (isatty(STDOUT_FILENO))
274                         fd = STDOUT_FILENO;
275                 else
276                 if (isatty(STDERR_FILENO))
277                         fd = STDERR_FILENO;
278                 else
279                 if (isatty(STDIN_FILENO))
280                         fd = STDIN_FILENO;
281                 else
282                         close_me = fd = open("/dev/tty", O_RDONLY);
283         }
284
285         win.ws_row = 0;
286         win.ws_col = 0;
287         /* I've seen ioctl returning 0, but row/col is (still?) 0.
288          * We treat that as an error too.  */
289         err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
290         if (height)
291                 *height = wh_helper(win.ws_row, 24, "LINES", &err);
292         if (width)
293                 *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
294
295         if (close_me >= 0)
296                 close(close_me);
297
298         return err;
299 }
300 int FAST_FUNC get_terminal_width(int fd)
301 {
302         unsigned width;
303         get_terminal_width_height(fd, &width, NULL);
304         return width;
305 }
306
307 int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
308 {
309         return tcsetattr(STDIN_FILENO, TCSANOW, tp);
310 }
311
312 int FAST_FUNC get_termios_and_make_raw(int fd, struct termios *newterm, struct termios *oldterm, int flags)
313 {
314 //TODO: slattach, shell read might be adapted to use this too: grep for "tcsetattr", "[VTIME] = 0"
315         int r;
316
317         memset(oldterm, 0, sizeof(*oldterm)); /* paranoia */
318         r = tcgetattr(fd, oldterm);
319         *newterm = *oldterm;
320
321         /* Turn off buffered input (ICANON)
322          * Turn off echoing (ECHO)
323          * and separate echoing of newline (ECHONL, normally off anyway)
324          */
325         newterm->c_lflag &= ~(ICANON | ECHO | ECHONL);
326         if (flags & TERMIOS_CLEAR_ISIG) {
327                 /* dont recognize INT/QUIT/SUSP chars */
328                 newterm->c_lflag &= ~ISIG;
329         }
330         /* reads will block only if < 1 char is available */
331         newterm->c_cc[VMIN] = 1;
332         /* no timeout (reads block forever) */
333         newterm->c_cc[VTIME] = 0;
334         if (flags & TERMIOS_RAW_CRNL) {
335 /* IXON, IXOFF, and IXANY:
336  * IXOFF=1: sw flow control is enabled on input queue:
337  * tty transmits a STOP char when input queue is close to full
338  * and transmits a START char when input queue is nearly empty.
339  * IXON=1: sw flow control is enabled on output queue:
340  * tty will stop sending if STOP char is received,
341  * and resume sending if START is received, or if any char
342  * is received and IXANY=1.
343  */
344                 /* IXON=0: XON/XOFF chars are treated as normal chars (why we do this?) */
345                 /* dont convert CR to NL on input */
346                 newterm->c_iflag &= ~(IXON | ICRNL);
347                 /* dont convert NL to CR+NL on output */
348                 newterm->c_oflag &= ~(ONLCR);
349                 /* Maybe clear more c_oflag bits? Usually, only OPOST and ONLCR are set.
350                  * OPOST  Enable output processing (reqd for OLCUC and *NL* bits to work)
351                  * OLCUC  Map lowercase characters to uppercase on output.
352                  * OCRNL  Map CR to NL on output.
353                  * ONOCR  Don't output CR at column 0.
354                  * ONLRET Don't output CR.
355                  */
356         }
357         if (flags & TERMIOS_RAW_INPUT) {
358 #ifndef IMAXBEL
359 # define IMAXBEL 0
360 #endif
361 #ifndef IUCLC
362 # define IUCLC 0
363 #endif
364 #ifndef IXANY
365 # define IXANY 0
366 #endif
367                 /* IXOFF=0: disable sending XON/XOFF if input buf is full */
368                 /* IXON=0: input XON/XOFF chars are not special */
369                 /* dont convert anything on input */
370                 newterm->c_iflag &= ~(IXOFF|IXON|IXANY|BRKINT|INLCR|ICRNL|IUCLC|IMAXBEL);
371         }
372         return r;
373 }
374
375 int FAST_FUNC set_termios_to_raw(int fd, struct termios *oldterm, int flags)
376 {
377         struct termios newterm;
378
379         get_termios_and_make_raw(fd, &newterm, oldterm, flags);
380         return tcsetattr(fd, TCSANOW, &newterm);
381 }
382
383 pid_t FAST_FUNC safe_waitpid(pid_t pid, int *wstat, int options)
384 {
385         pid_t r;
386
387         do
388                 r = waitpid(pid, wstat, options);
389         while ((r == -1) && (errno == EINTR));
390         return r;
391 }
392
393 pid_t FAST_FUNC wait_any_nohang(int *wstat)
394 {
395         return safe_waitpid(-1, wstat, WNOHANG);
396 }
397
398 // Wait for the specified child PID to exit, returning child's error return.
399 int FAST_FUNC wait4pid(pid_t pid)
400 {
401         int status;
402
403         if (pid <= 0) {
404                 /*errno = ECHILD; -- wrong. */
405                 /* we expect errno to be already set from failed [v]fork/exec */
406                 return -1;
407         }
408         if (safe_waitpid(pid, &status, 0) == -1)
409                 return -1;
410         if (WIFEXITED(status))
411                 return WEXITSTATUS(status);
412         if (WIFSIGNALED(status))
413                 return WTERMSIG(status) + 0x180;
414         return 0;
415 }
416
417 // Useful when we do know that pid is valid, and we just want to wait
418 // for it to exit. Not existing pid is fatal. waitpid() status is not returned.
419 int FAST_FUNC wait_for_exitstatus(pid_t pid)
420 {
421         int exit_status, n;
422
423         n = safe_waitpid(pid, &exit_status, 0);
424         if (n < 0)
425                 bb_perror_msg_and_die("waitpid");
426         return exit_status;
427 }