libbb: factor out hex2bin() for infiniband address parser
[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 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  * TODO: move xmalloc() and xatonum() here.
23  */
24
25 #include "libbb.h"
26
27 /* Turn on nonblocking I/O on a fd */
28 int FAST_FUNC ndelay_on(int fd)
29 {
30         return fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
31 }
32
33 int FAST_FUNC ndelay_off(int fd)
34 {
35         return fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
36 }
37
38 int FAST_FUNC close_on_exec_on(int fd)
39 {
40         return fcntl(fd, F_SETFD, FD_CLOEXEC);
41 }
42
43 char* FAST_FUNC strncpy_IFNAMSIZ(char *dst, const char *src)
44 {
45 #ifndef IFNAMSIZ
46         enum { IFNAMSIZ = 16 };
47 #endif
48         return strncpy(dst, src, IFNAMSIZ);
49 }
50
51
52 // Convert unsigned integer to ascii, writing into supplied buffer.
53 // A truncated result contains the first few digits of the result ala strncpy.
54 // Returns a pointer past last generated digit, does _not_ store NUL.
55 void BUG_sizeof_unsigned_not_4(void);
56 char* FAST_FUNC utoa_to_buf(unsigned n, char *buf, unsigned buflen)
57 {
58         unsigned i, out, res;
59         if (sizeof(unsigned) != 4)
60                 BUG_sizeof_unsigned_not_4();
61         if (buflen) {
62                 out = 0;
63                 for (i = 1000000000; i; i /= 10) {
64                         res = n / i;
65                         if (res || out || i == 1) {
66                                 if (!--buflen) break;
67                                 out++;
68                                 n -= res*i;
69                                 *buf++ = '0' + res;
70                         }
71                 }
72         }
73         return buf;
74 }
75
76 /* Convert signed integer to ascii, like utoa_to_buf() */
77 char* FAST_FUNC itoa_to_buf(int n, char *buf, unsigned buflen)
78 {
79         if (buflen && n < 0) {
80                 n = -n;
81                 *buf++ = '-';
82                 buflen--;
83         }
84         return utoa_to_buf((unsigned)n, buf, buflen);
85 }
86
87 // The following two functions use a static buffer, so calling either one a
88 // second time will overwrite previous results.
89 //
90 // The largest 32 bit integer is -2 billion plus null terminator, or 12 bytes.
91 // It so happens that sizeof(int) * 3 is enough for 32+ bits.
92 // (sizeof(int) * 3 + 2 is correct for any width, even 8-bit)
93
94 static char local_buf[sizeof(int) * 3];
95
96 // Convert unsigned integer to ascii using a static buffer (returned).
97 char* FAST_FUNC utoa(unsigned n)
98 {
99         *(utoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
100
101         return local_buf;
102 }
103
104 /* Convert signed integer to ascii using a static buffer (returned). */
105 char* FAST_FUNC itoa(int n)
106 {
107         *(itoa_to_buf(n, local_buf, sizeof(local_buf))) = '\0';
108
109         return local_buf;
110 }
111
112 /* Emit a string of hex representation of bytes */
113 char* FAST_FUNC bin2hex(char *p, const char *cp, int count)
114 {
115         while (count) {
116                 unsigned char c = *cp++;
117                 /* put lowercase hex digits */
118                 *p++ = 0x20 | bb_hexdigits_upcase[c >> 4];
119                 *p++ = 0x20 | bb_hexdigits_upcase[c & 0xf];
120                 count--;
121         }
122         return p;
123 }
124
125 /* Convert "[x]x[:][x]x[:][x]x[:][x]x" hex string to binary, no more than COUNT bytes */
126 char* FAST_FUNC hex2bin(char *dst, const char *str, int count)
127 {
128         errno = EINVAL;
129         while (*str && count) {
130                 uint8_t val;
131                 uint8_t c = *str++;
132                 if (isdigit(c))
133                         val = c - '0';
134                 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
135                         val = (c|0x20) - ('a' - 10);
136                 else
137                         return NULL;
138                 val <<= 4;
139                 c = *str;
140                 if (isdigit(c))
141                         val |= c - '0';
142                 else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
143                         val |= (c|0x20) - ('a' - 10);
144                 else if (c == ':' || c == '\0')
145                         val >>= 4;
146                 else
147                         return NULL;
148
149                 *dst++ = val;
150                 if (c != '\0')
151                         str++;
152                 if (*str == ':')
153                         str++;
154                 count--;
155         }
156         errno = (*str ? ERANGE : 0);
157         return dst;
158 }
159
160 /* Return how long the file at fd is, if there's any way to determine it. */
161 #ifdef UNUSED
162 off_t FAST_FUNC fdlength(int fd)
163 {
164         off_t bottom = 0, top = 0, pos;
165         long size;
166
167         // If the ioctl works for this, return it.
168
169         if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
170
171         // FIXME: explain why lseek(SEEK_END) is not used here!
172
173         // If not, do a binary search for the last location we can read.  (Some
174         // block devices don't do BLKGETSIZE right.)
175
176         do {
177                 char temp;
178
179                 pos = bottom + (top - bottom) / 2;
180
181                 // If we can read from the current location, it's bigger.
182
183                 if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
184                         if (bottom == top) bottom = top = (top+1) * 2;
185                         else bottom = pos;
186
187                 // If we can't, it's smaller.
188
189                 } else {
190                         if (bottom == top) {
191                                 if (!top) return 0;
192                                 bottom = top/2;
193                         }
194                         else top = pos;
195                 }
196         } while (bottom + 1 != top);
197
198         return pos + 1;
199 }
200 #endif
201
202 char* FAST_FUNC xmalloc_ttyname(int fd)
203 {
204         char *buf = xzalloc(128);
205         int r = ttyname_r(fd, buf, 127);
206         if (r) {
207                 free(buf);
208                 buf = NULL;
209         }
210         return buf;
211 }
212
213 /* It is perfectly ok to pass in a NULL for either width or for
214  * height, in which case that value will not be set.  */
215 int FAST_FUNC get_terminal_width_height(int fd, unsigned *width, unsigned *height)
216 {
217         struct winsize win = { 0, 0, 0, 0 };
218         int ret = ioctl(fd, TIOCGWINSZ, &win);
219
220         if (height) {
221                 if (!win.ws_row) {
222                         char *s = getenv("LINES");
223                         if (s) win.ws_row = atoi(s);
224                 }
225                 if (win.ws_row <= 1 || win.ws_row >= 30000)
226                         win.ws_row = 24;
227                 *height = (int) win.ws_row;
228         }
229
230         if (width) {
231                 if (!win.ws_col) {
232                         char *s = getenv("COLUMNS");
233                         if (s) win.ws_col = atoi(s);
234                 }
235                 if (win.ws_col <= 1 || win.ws_col >= 30000)
236                         win.ws_col = 80;
237                 *width = (int) win.ws_col;
238         }
239
240         return ret;
241 }
242
243 int FAST_FUNC tcsetattr_stdin_TCSANOW(const struct termios *tp)
244 {
245         return tcsetattr(STDIN_FILENO, TCSANOW, tp);
246 }
247
248 void FAST_FUNC generate_uuid(uint8_t *buf)
249 {
250         /* http://www.ietf.org/rfc/rfc4122.txt
251          *  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
252          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
253          * |                          time_low                             |
254          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
255          * |       time_mid                |         time_hi_and_version   |
256          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
257          * |clk_seq_and_variant            |         node (0-1)            |
258          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
259          * |                         node (2-5)                            |
260          * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
261          * IOW, uuid has this layout:
262          * uint32_t time_low (big endian)
263          * uint16_t time_mid (big endian)
264          * uint16_t time_hi_and_version (big endian)
265          *  version is a 4-bit field:
266          *   1 Time-based
267          *   2 DCE Security, with embedded POSIX UIDs
268          *   3 Name-based (MD5)
269          *   4 Randomly generated
270          *   5 Name-based (SHA-1)
271          * uint16_t clk_seq_and_variant (big endian)
272          *  variant is a 3-bit field:
273          *   0xx Reserved, NCS backward compatibility
274          *   10x The variant specified in rfc4122
275          *   110 Reserved, Microsoft backward compatibility
276          *   111 Reserved for future definition
277          * uint8_t node[6]
278          *
279          * For version 4, these bits are set/cleared:
280          * time_hi_and_version & 0x0fff | 0x4000
281          * clk_seq_and_variant & 0x3fff | 0x8000
282          */
283         pid_t pid;
284         int i;
285
286         i = open("/dev/urandom", O_RDONLY);
287         if (i >= 0) {
288                 read(i, buf, 16);
289                 close(i);
290         }
291         /* Paranoia. /dev/urandom may be missing.
292          * rand() is guaranteed to generate at least [0, 2^15) range,
293          * but lowest bits in some libc are not so "random".  */
294         srand(monotonic_us());
295         pid = getpid();
296         while (1) {
297                 for (i = 0; i < 16; i++)
298                         buf[i] ^= rand() >> 5;
299                 if (pid == 0)
300                         break;
301                 srand(pid);
302                 pid = 0;
303         }
304
305         /* version = 4 */
306         buf[4 + 2    ] = (buf[4 + 2    ] & 0x0f) | 0x40;
307         /* variant = 10x */
308         buf[4 + 2 + 2] = (buf[4 + 2 + 2] & 0x3f) | 0x80;
309 }