packets: Add more utility functions for IPv4 and IPv6 addresses.
[sliver-openvswitch.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "util.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdarg.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "vlog.h"
30
31 VLOG_DEFINE_THIS_MODULE(util);
32
33 COVERAGE_DEFINE(util_xalloc);
34
35 const char *program_name;
36 static char *program_version;
37
38 void
39 out_of_memory(void)
40 {
41     ovs_abort(0, "virtual memory exhausted");
42 }
43
44 void *
45 xcalloc(size_t count, size_t size)
46 {
47     void *p = count && size ? calloc(count, size) : malloc(1);
48     COVERAGE_INC(util_xalloc);
49     if (p == NULL) {
50         out_of_memory();
51     }
52     return p;
53 }
54
55 void *
56 xzalloc(size_t size)
57 {
58     return xcalloc(1, size);
59 }
60
61 void *
62 xmalloc(size_t size)
63 {
64     void *p = malloc(size ? size : 1);
65     COVERAGE_INC(util_xalloc);
66     if (p == NULL) {
67         out_of_memory();
68     }
69     return p;
70 }
71
72 void *
73 xrealloc(void *p, size_t size)
74 {
75     p = realloc(p, size ? size : 1);
76     COVERAGE_INC(util_xalloc);
77     if (p == NULL) {
78         out_of_memory();
79     }
80     return p;
81 }
82
83 void *
84 xmemdup(const void *p_, size_t size)
85 {
86     void *p = xmalloc(size);
87     memcpy(p, p_, size);
88     return p;
89 }
90
91 char *
92 xmemdup0(const char *p_, size_t length)
93 {
94     char *p = xmalloc(length + 1);
95     memcpy(p, p_, length);
96     p[length] = '\0';
97     return p;
98 }
99
100 char *
101 xstrdup(const char *s)
102 {
103     return xmemdup0(s, strlen(s));
104 }
105
106 char *
107 xvasprintf(const char *format, va_list args)
108 {
109     va_list args2;
110     size_t needed;
111     char *s;
112
113     va_copy(args2, args);
114     needed = vsnprintf(NULL, 0, format, args);
115
116     s = xmalloc(needed + 1);
117
118     vsnprintf(s, needed + 1, format, args2);
119     va_end(args2);
120
121     return s;
122 }
123
124 void *
125 x2nrealloc(void *p, size_t *n, size_t s)
126 {
127     *n = *n == 0 ? 1 : 2 * *n;
128     return xrealloc(p, *n * s);
129 }
130
131 char *
132 xasprintf(const char *format, ...)
133 {
134     va_list args;
135     char *s;
136
137     va_start(args, format);
138     s = xvasprintf(format, args);
139     va_end(args);
140
141     return s;
142 }
143
144 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
145  * bytes from 'src' and doesn't return anything. */
146 void
147 ovs_strlcpy(char *dst, const char *src, size_t size)
148 {
149     if (size > 0) {
150         size_t len = strnlen(src, size - 1);
151         memcpy(dst, src, len);
152         dst[len] = '\0';
153     }
154 }
155
156 /* Copies 'src' to 'dst'.  Reads no more than 'size - 1' bytes from 'src'.
157  * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
158  * to every otherwise unused byte in 'dst'.
159  *
160  * Except for performance, the following call:
161  *     ovs_strzcpy(dst, src, size);
162  * is equivalent to these two calls:
163  *     memset(dst, '\0', size);
164  *     ovs_strlcpy(dst, src, size);
165  *
166  * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
167  */
168 void
169 ovs_strzcpy(char *dst, const char *src, size_t size)
170 {
171     if (size > 0) {
172         size_t len = strnlen(src, size - 1);
173         memcpy(dst, src, len);
174         memset(dst + len, '\0', size - len);
175     }
176 }
177
178 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
179  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
180  * the message inside parentheses.  Then, terminates with abort().
181  *
182  * This function is preferred to ovs_fatal() in a situation where it would make
183  * sense for a monitoring process to restart the daemon.
184  *
185  * 'format' should not end with a new-line, because this function will add one
186  * itself. */
187 void
188 ovs_abort(int err_no, const char *format, ...)
189 {
190     va_list args;
191
192     va_start(args, format);
193     ovs_error_valist(err_no, format, args);
194     va_end(args);
195
196     abort();
197 }
198
199 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
200  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
201  * the message inside parentheses.  Then, terminates with EXIT_FAILURE.
202  *
203  * 'format' should not end with a new-line, because this function will add one
204  * itself. */
205 void
206 ovs_fatal(int err_no, const char *format, ...)
207 {
208     va_list args;
209
210     va_start(args, format);
211     ovs_fatal_valist(err_no, format, args);
212 }
213
214 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
215 void
216 ovs_fatal_valist(int err_no, const char *format, va_list args)
217 {
218     ovs_error_valist(err_no, format, args);
219     exit(EXIT_FAILURE);
220 }
221
222 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
223  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
224  * the message inside parentheses.
225  *
226  * 'format' should not end with a new-line, because this function will add one
227  * itself. */
228 void
229 ovs_error(int err_no, const char *format, ...)
230 {
231     va_list args;
232
233     va_start(args, format);
234     ovs_error_valist(err_no, format, args);
235     va_end(args);
236 }
237
238 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
239 void
240 ovs_error_valist(int err_no, const char *format, va_list args)
241 {
242     int save_errno = errno;
243
244     fprintf(stderr, "%s: ", program_name);
245     vfprintf(stderr, format, args);
246     if (err_no != 0) {
247         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
248     }
249     putc('\n', stderr);
250
251     errno = save_errno;
252 }
253
254 /* Many OVS functions return an int which is one of:
255  * - 0: no error yet
256  * - >0: errno value
257  * - EOF: end of file (not necessarily an error; depends on the function called)
258  *
259  * Returns the appropriate human-readable string. The caller must copy the
260  * string if it wants to hold onto it, as the storage may be overwritten on
261  * subsequent function calls.
262  */
263 const char *
264 ovs_retval_to_string(int retval)
265 {
266     static char unknown[48];
267
268     if (!retval) {
269         return "";
270     }
271     if (retval > 0) {
272         return strerror(retval);
273     }
274     if (retval == EOF) {
275         return "End of file";
276     }
277     snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
278     return unknown;
279 }
280
281 /* Sets global "program_name" and "program_version" variables.  Should
282  * be called at the beginning of main() with "argv[0]" as the argument
283  * to 'argv0'.
284  *
285  * The 'date' and 'time' arguments should likely be called with
286  * "__DATE__" and "__TIME__" to use the time the binary was built.
287  * Alternatively, the "set_program_name" macro may be called to do this
288  * automatically.
289  */
290 void
291 set_program_name__(const char *argv0, const char *date, const char *time)
292 {
293     const char *slash = strrchr(argv0, '/');
294     program_name = slash ? slash + 1 : argv0;
295
296     free(program_version);
297     program_version = xasprintf("%s (Open vSwitch) "VERSION BUILDNR"\n"
298                                 "Compiled %s %s\n",
299                                 program_name, date, time);
300 }
301
302 /* Returns a pointer to a string describing the program version.  The
303  * caller must not modify or free the returned string.
304  */
305 const char *
306 get_program_version(void)
307 {
308     return program_version;
309 }
310
311 /* Print the version information for the program.  */
312 void
313 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
314 {
315     printf("%s", program_version);
316     if (min_ofp || max_ofp) {
317         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
318     }
319 }
320
321 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
322  * line.  Numeric offsets are also included, starting at 'ofs' for the first
323  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
324  * are also rendered alongside. */
325 void
326 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
327              uintptr_t ofs, bool ascii)
328 {
329   const uint8_t *buf = buf_;
330   const size_t per_line = 16; /* Maximum bytes per line. */
331
332   while (size > 0)
333     {
334       size_t start, end, n;
335       size_t i;
336
337       /* Number of bytes on this line. */
338       start = ofs % per_line;
339       end = per_line;
340       if (end - start > size)
341         end = start + size;
342       n = end - start;
343
344       /* Print line. */
345       fprintf(stream, "%08jx  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
346       for (i = 0; i < start; i++)
347         fprintf(stream, "   ");
348       for (; i < end; i++)
349         fprintf(stream, "%02hhx%c",
350                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
351       if (ascii)
352         {
353           for (; i < per_line; i++)
354             fprintf(stream, "   ");
355           fprintf(stream, "|");
356           for (i = 0; i < start; i++)
357             fprintf(stream, " ");
358           for (; i < end; i++) {
359               int c = buf[i - start];
360               putc(c >= 32 && c < 127 ? c : '.', stream);
361           }
362           for (; i < per_line; i++)
363             fprintf(stream, " ");
364           fprintf(stream, "|");
365         }
366       fprintf(stream, "\n");
367
368       ofs += n;
369       buf += n;
370       size -= n;
371     }
372 }
373
374 bool
375 str_to_int(const char *s, int base, int *i)
376 {
377     long long ll;
378     bool ok = str_to_llong(s, base, &ll);
379     *i = ll;
380     return ok;
381 }
382
383 bool
384 str_to_long(const char *s, int base, long *li)
385 {
386     long long ll;
387     bool ok = str_to_llong(s, base, &ll);
388     *li = ll;
389     return ok;
390 }
391
392 bool
393 str_to_llong(const char *s, int base, long long *x)
394 {
395     int save_errno = errno;
396     char *tail;
397     errno = 0;
398     *x = strtoll(s, &tail, base);
399     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
400         errno = save_errno;
401         *x = 0;
402         return false;
403     } else {
404         errno = save_errno;
405         return true;
406     }
407 }
408
409 bool
410 str_to_uint(const char *s, int base, unsigned int *u)
411 {
412     return str_to_int(s, base, (int *) u);
413 }
414
415 bool
416 str_to_ulong(const char *s, int base, unsigned long *ul)
417 {
418     return str_to_long(s, base, (long *) ul);
419 }
420
421 bool
422 str_to_ullong(const char *s, int base, unsigned long long *ull)
423 {
424     return str_to_llong(s, base, (long long *) ull);
425 }
426
427 /* Converts floating-point string 's' into a double.  If successful, stores
428  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
429  * returns false.
430  *
431  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
432  * (e.g. "1e9999)" is. */
433 bool
434 str_to_double(const char *s, double *d)
435 {
436     int save_errno = errno;
437     char *tail;
438     errno = 0;
439     *d = strtod(s, &tail);
440     if (errno == EINVAL || (errno == ERANGE && *d != 0)
441         || tail == s || *tail != '\0') {
442         errno = save_errno;
443         *d = 0;
444         return false;
445     } else {
446         errno = save_errno;
447         return true;
448     }
449 }
450
451 /* Returns the value of 'c' as a hexadecimal digit. */
452 int
453 hexit_value(int c)
454 {
455     switch (c) {
456     case '0': case '1': case '2': case '3': case '4':
457     case '5': case '6': case '7': case '8': case '9':
458         return c - '0';
459
460     case 'a': case 'A':
461         return 0xa;
462
463     case 'b': case 'B':
464         return 0xb;
465
466     case 'c': case 'C':
467         return 0xc;
468
469     case 'd': case 'D':
470         return 0xd;
471
472     case 'e': case 'E':
473         return 0xe;
474
475     case 'f': case 'F':
476         return 0xf;
477
478     default:
479         return -1;
480     }
481 }
482
483 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
484  * UINT_MAX if one of those "digits" is not really a hex digit.  If 'ok' is
485  * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
486  * non-hex digit is detected. */
487 unsigned int
488 hexits_value(const char *s, size_t n, bool *ok)
489 {
490     unsigned int value;
491     size_t i;
492
493     value = 0;
494     for (i = 0; i < n; i++) {
495         int hexit = hexit_value(s[i]);
496         if (hexit < 0) {
497             if (ok) {
498                 *ok = false;
499             }
500             return UINT_MAX;
501         }
502         value = (value << 4) + hexit;
503     }
504     if (ok) {
505         *ok = true;
506     }
507     return value;
508 }
509
510 /* Returns the current working directory as a malloc()'d string, or a null
511  * pointer if the current working directory cannot be determined. */
512 char *
513 get_cwd(void)
514 {
515     long int path_max;
516     size_t size;
517
518     /* Get maximum path length or at least a reasonable estimate. */
519     path_max = pathconf(".", _PC_PATH_MAX);
520     size = (path_max < 0 ? 1024
521             : path_max > 10240 ? 10240
522             : path_max);
523
524     /* Get current working directory. */
525     for (;;) {
526         char *buf = xmalloc(size);
527         if (getcwd(buf, size)) {
528             return xrealloc(buf, strlen(buf) + 1);
529         } else {
530             int error = errno;
531             free(buf);
532             if (error != ERANGE) {
533                 VLOG_WARN("getcwd failed (%s)", strerror(error));
534                 return NULL;
535             }
536             size *= 2;
537         }
538     }
539 }
540
541 static char *
542 all_slashes_name(const char *s)
543 {
544     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
545                    : s[0] == '/' ? "/"
546                    : ".");
547 }
548
549 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
550  * similar to the POSIX dirname() function but thread-safe. */
551 char *
552 dir_name(const char *file_name)
553 {
554     size_t len = strlen(file_name);
555     while (len > 0 && file_name[len - 1] == '/') {
556         len--;
557     }
558     while (len > 0 && file_name[len - 1] != '/') {
559         len--;
560     }
561     while (len > 0 && file_name[len - 1] == '/') {
562         len--;
563     }
564     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
565 }
566
567 /* Returns the file name portion of 'file_name' as a malloc()'d string,
568  * similar to the POSIX basename() function but thread-safe. */
569 char *
570 base_name(const char *file_name)
571 {
572     size_t end, start;
573
574     end = strlen(file_name);
575     while (end > 0 && file_name[end - 1] == '/') {
576         end--;
577     }
578
579     if (!end) {
580         return all_slashes_name(file_name);
581     }
582
583     start = end;
584     while (start > 0 && file_name[start - 1] != '/') {
585         start--;
586     }
587
588     return xmemdup0(file_name + start, end - start);
589 }
590
591 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
592  * returns an absolute path to 'file_name' considering it relative to 'dir',
593  * which itself must be absolute.  'dir' may be null or the empty string, in
594  * which case the current working directory is used.
595  *
596  * Returns a null pointer if 'dir' is null and getcwd() fails. */
597 char *
598 abs_file_name(const char *dir, const char *file_name)
599 {
600     if (file_name[0] == '/') {
601         return xstrdup(file_name);
602     } else if (dir && dir[0]) {
603         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
604         return xasprintf("%s%s%s", dir, separator, file_name);
605     } else {
606         char *cwd = get_cwd();
607         if (cwd) {
608             char *abs_name = xasprintf("%s/%s", cwd, file_name);
609             free(cwd);
610             return abs_name;
611         } else {
612             return NULL;
613         }
614     }
615 }
616
617
618 /* Pass a value to this function if it is marked with
619  * __attribute__((warn_unused_result)) and you genuinely want to ignore
620  * its return value.  (Note that every scalar type can be implicitly
621  * converted to bool.) */
622 void ignore(bool x OVS_UNUSED) { }
623
624 /* Returns an appropriate delimiter for inserting just before the 0-based item
625  * 'index' in a list that has 'total' items in it. */
626 const char *
627 english_list_delimiter(size_t index, size_t total)
628 {
629     return (index == 0 ? ""
630             : index < total - 1 ? ", "
631             : total > 2 ? ", and "
632             : " and ");
633 }
634
635 /* Given a 32 bit word 'n', calculates floor(log_2('n')).  This is equivalent
636  * to finding the bit position of the most significant one bit in 'n'.  It is
637  * an error to call this function with 'n' == 0. */
638 int
639 log_2_floor(uint32_t n)
640 {
641     assert(n);
642
643 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
644 #error "Someone screwed up the #includes."
645 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
646     return 31 - __builtin_clz(n);
647 #else
648     {
649         int log = 0;
650
651 #define BIN_SEARCH_STEP(BITS)                   \
652         if (n >= (1 << BITS)) {                 \
653             log += BITS;                        \
654             n >>= BITS;                         \
655         }
656         BIN_SEARCH_STEP(16);
657         BIN_SEARCH_STEP(8);
658         BIN_SEARCH_STEP(4);
659         BIN_SEARCH_STEP(2);
660         BIN_SEARCH_STEP(1);
661 #undef BIN_SEARCH_STEP
662         return log;
663     }
664 #endif
665 }
666
667 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
668 int
669 ctz(uint32_t n)
670 {
671     if (!n) {
672         return 32;
673     } else {
674 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
675 #error "Someone screwed up the #includes."
676 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
677         return __builtin_ctz(n);
678 #else
679         unsigned int k;
680         int count = 31;
681
682 #define CTZ_STEP(X)                             \
683         k = n << (X);                           \
684         if (k) {                                \
685             count -= X;                         \
686             n = k;                              \
687         }
688         CTZ_STEP(16);
689         CTZ_STEP(8);
690         CTZ_STEP(4);
691         CTZ_STEP(2);
692         CTZ_STEP(1);
693 #undef CTZ_STEP
694
695         return count;
696 #endif
697     }
698 }