socket-util: error number to string for sockets.
[sliver-openvswitch.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <ctype.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <pthread.h>
23 #include <stdarg.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include "bitmap.h"
31 #include "byte-order.h"
32 #include "coverage.h"
33 #include "ovs-thread.h"
34 #include "vlog.h"
35 #ifdef HAVE_PTHREAD_SET_NAME_NP
36 #include <pthread_np.h>
37 #endif
38
39 VLOG_DEFINE_THIS_MODULE(util);
40
41 COVERAGE_DEFINE(util_xalloc);
42
43 /* argv[0] without directory names. */
44 const char *program_name;
45
46 /* Name for the currently running thread or process, for log messages, process
47  * listings, and debuggers. */
48 DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name);
49
50 /* --version option output. */
51 static char *program_version;
52
53 /* Buffer used by ovs_strerror(). */
54 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
55                               strerror_buffer,
56                               { "" });
57
58 void
59 ovs_assert_failure(const char *where, const char *function,
60                    const char *condition)
61 {
62     /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
63      * to trigger an assertion failure of its own. */
64     static int reentry = 0;
65
66     switch (reentry++) {
67     case 0:
68         VLOG_ABORT("%s: assertion %s failed in %s()",
69                    where, condition, function);
70         OVS_NOT_REACHED();
71
72     case 1:
73         fprintf(stderr, "%s: assertion %s failed in %s()",
74                 where, condition, function);
75         abort();
76
77     default:
78         abort();
79     }
80 }
81
82 void
83 out_of_memory(void)
84 {
85     ovs_abort(0, "virtual memory exhausted");
86 }
87
88 void *
89 xcalloc(size_t count, size_t size)
90 {
91     void *p = count && size ? calloc(count, size) : malloc(1);
92     COVERAGE_INC(util_xalloc);
93     if (p == NULL) {
94         out_of_memory();
95     }
96     return p;
97 }
98
99 void *
100 xzalloc(size_t size)
101 {
102     return xcalloc(1, size);
103 }
104
105 void *
106 xmalloc(size_t size)
107 {
108     void *p = malloc(size ? size : 1);
109     COVERAGE_INC(util_xalloc);
110     if (p == NULL) {
111         out_of_memory();
112     }
113     return p;
114 }
115
116 void *
117 xrealloc(void *p, size_t size)
118 {
119     p = realloc(p, size ? size : 1);
120     COVERAGE_INC(util_xalloc);
121     if (p == NULL) {
122         out_of_memory();
123     }
124     return p;
125 }
126
127 void *
128 xmemdup(const void *p_, size_t size)
129 {
130     void *p = xmalloc(size);
131     memcpy(p, p_, size);
132     return p;
133 }
134
135 char *
136 xmemdup0(const char *p_, size_t length)
137 {
138     char *p = xmalloc(length + 1);
139     memcpy(p, p_, length);
140     p[length] = '\0';
141     return p;
142 }
143
144 char *
145 xstrdup(const char *s)
146 {
147     return xmemdup0(s, strlen(s));
148 }
149
150 char *
151 xvasprintf(const char *format, va_list args)
152 {
153     va_list args2;
154     size_t needed;
155     char *s;
156
157     va_copy(args2, args);
158     needed = vsnprintf(NULL, 0, format, args);
159
160     s = xmalloc(needed + 1);
161
162     vsnprintf(s, needed + 1, format, args2);
163     va_end(args2);
164
165     return s;
166 }
167
168 void *
169 x2nrealloc(void *p, size_t *n, size_t s)
170 {
171     *n = *n == 0 ? 1 : 2 * *n;
172     return xrealloc(p, *n * s);
173 }
174
175 char *
176 xasprintf(const char *format, ...)
177 {
178     va_list args;
179     char *s;
180
181     va_start(args, format);
182     s = xvasprintf(format, args);
183     va_end(args);
184
185     return s;
186 }
187
188 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
189  * bytes from 'src' and doesn't return anything. */
190 void
191 ovs_strlcpy(char *dst, const char *src, size_t size)
192 {
193     if (size > 0) {
194         size_t len = strnlen(src, size - 1);
195         memcpy(dst, src, len);
196         dst[len] = '\0';
197     }
198 }
199
200 /* Copies 'src' to 'dst'.  Reads no more than 'size - 1' bytes from 'src'.
201  * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
202  * to every otherwise unused byte in 'dst'.
203  *
204  * Except for performance, the following call:
205  *     ovs_strzcpy(dst, src, size);
206  * is equivalent to these two calls:
207  *     memset(dst, '\0', size);
208  *     ovs_strlcpy(dst, src, size);
209  *
210  * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
211  */
212 void
213 ovs_strzcpy(char *dst, const char *src, size_t size)
214 {
215     if (size > 0) {
216         size_t len = strnlen(src, size - 1);
217         memcpy(dst, src, len);
218         memset(dst + len, '\0', size - len);
219     }
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.  Then, terminates with abort().
225  *
226  * This function is preferred to ovs_fatal() in a situation where it would make
227  * sense for a monitoring process to restart the daemon.
228  *
229  * 'format' should not end with a new-line, because this function will add one
230  * itself. */
231 void
232 ovs_abort(int err_no, const char *format, ...)
233 {
234     va_list args;
235
236     va_start(args, format);
237     ovs_abort_valist(err_no, format, args);
238 }
239
240 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
241 void
242 ovs_abort_valist(int err_no, const char *format, va_list args)
243 {
244     ovs_error_valist(err_no, format, args);
245     abort();
246 }
247
248 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
249  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
250  * the message inside parentheses.  Then, terminates with EXIT_FAILURE.
251  *
252  * 'format' should not end with a new-line, because this function will add one
253  * itself. */
254 void
255 ovs_fatal(int err_no, const char *format, ...)
256 {
257     va_list args;
258
259     va_start(args, format);
260     ovs_fatal_valist(err_no, format, args);
261 }
262
263 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
264 void
265 ovs_fatal_valist(int err_no, const char *format, va_list args)
266 {
267     ovs_error_valist(err_no, format, args);
268     exit(EXIT_FAILURE);
269 }
270
271 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
272  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
273  * the message inside parentheses.
274  *
275  * 'format' should not end with a new-line, because this function will add one
276  * itself. */
277 void
278 ovs_error(int err_no, const char *format, ...)
279 {
280     va_list args;
281
282     va_start(args, format);
283     ovs_error_valist(err_no, format, args);
284     va_end(args);
285 }
286
287 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
288 void
289 ovs_error_valist(int err_no, const char *format, va_list args)
290 {
291     const char *subprogram_name = get_subprogram_name();
292     int save_errno = errno;
293
294     if (subprogram_name[0]) {
295         fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
296     } else {
297         fprintf(stderr, "%s: ", program_name);
298     }
299
300     vfprintf(stderr, format, args);
301     if (err_no != 0) {
302         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
303     }
304     putc('\n', stderr);
305
306     errno = save_errno;
307 }
308
309 /* Many OVS functions return an int which is one of:
310  * - 0: no error yet
311  * - >0: errno value
312  * - EOF: end of file (not necessarily an error; depends on the function called)
313  *
314  * Returns the appropriate human-readable string. The caller must copy the
315  * string if it wants to hold onto it, as the storage may be overwritten on
316  * subsequent function calls.
317  */
318 const char *
319 ovs_retval_to_string(int retval)
320 {
321     return (!retval ? ""
322             : retval == EOF ? "End of file"
323             : ovs_strerror(retval));
324 }
325
326 /* This function returns the string describing the error number in 'error'
327  * for POSIX platforms.  For Windows, this function can be used for C library
328  * calls.  For socket calls that are also used in Windows, use sock_strerror()
329  * instead.  For WINAPI calls, look at ovs_lasterror_to_string(). */
330 const char *
331 ovs_strerror(int error)
332 {
333     enum { BUFSIZE = sizeof strerror_buffer_get()->s };
334     int save_errno;
335     char *buffer;
336     char *s;
337
338     save_errno = errno;
339     buffer = strerror_buffer_get()->s;
340
341 #if STRERROR_R_CHAR_P
342     /* GNU style strerror_r() might return an immutable static string, or it
343      * might write and return 'buffer', but in either case we can pass the
344      * returned string directly to the caller. */
345     s = strerror_r(error, buffer, BUFSIZE);
346 #else  /* strerror_r() returns an int. */
347     s = buffer;
348     if (strerror_r(error, buffer, BUFSIZE)) {
349         /* strerror_r() is only allowed to fail on ERANGE (because the buffer
350          * is too short).  We don't check the actual failure reason because
351          * POSIX requires strerror_r() to return the error but old glibc
352          * (before 2.13) returns -1 and sets errno. */
353         snprintf(buffer, BUFSIZE, "Unknown error %d", error);
354     }
355 #endif
356
357     errno = save_errno;
358
359     return s;
360 }
361
362 /* Sets global "program_name" and "program_version" variables.  Should
363  * be called at the beginning of main() with "argv[0]" as the argument
364  * to 'argv0'.
365  *
366  * 'version' should contain the version of the caller's program.  If 'version'
367  * is the same as the VERSION #define, the caller is assumed to be part of Open
368  * vSwitch.  Otherwise, it is assumed to be an external program linking against
369  * the Open vSwitch libraries.
370  *
371  * The 'date' and 'time' arguments should likely be called with
372  * "__DATE__" and "__TIME__" to use the time the binary was built.
373  * Alternatively, the "set_program_name" macro may be called to do this
374  * automatically.
375  */
376 void
377 set_program_name__(const char *argv0, const char *version, const char *date,
378                    const char *time)
379 {
380 #ifdef _WIN32
381     char *basename;
382     size_t max_len = strlen(argv0) + 1;
383
384     if (program_name) {
385         return;
386     }
387     basename = xmalloc(max_len);
388     _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
389     assert_single_threaded();
390     program_name = basename;
391 #else
392     const char *slash = strrchr(argv0, '/');
393     assert_single_threaded();
394     program_name = slash ? slash + 1 : argv0;
395 #endif
396
397     free(program_version);
398
399     if (!strcmp(version, VERSION)) {
400         program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
401                                     "Compiled %s %s\n",
402                                     program_name, date, time);
403     } else {
404         program_version = xasprintf("%s %s\n"
405                                     "Open vSwitch Library "VERSION"\n"
406                                     "Compiled %s %s\n",
407                                     program_name, version, date, time);
408     }
409 }
410
411 /* Returns the name of the currently running thread or process. */
412 const char *
413 get_subprogram_name(void)
414 {
415     const char *name = subprogram_name_get();
416     return name ? name : "";
417 }
418
419 /* Sets the formatted value of 'format' as the name of the currently running
420  * thread or process.  (This appears in log messages and may also be visible in
421  * system process listings and debuggers.) */
422 void
423 set_subprogram_name(const char *format, ...)
424 {
425     char *pname;
426
427     if (format) {
428         va_list args;
429
430         va_start(args, format);
431         pname = xvasprintf(format, args);
432         va_end(args);
433     } else {
434         pname = xstrdup(program_name);
435     }
436
437     free(subprogram_name_set(pname));
438
439 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
440     pthread_setname_np(pthread_self(), pname);
441 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
442     pthread_setname_np(pthread_self(), "%s", pname);
443 #elif HAVE_PTHREAD_SET_NAME_NP
444     pthread_set_name_np(pthread_self(), pname);
445 #endif
446 }
447
448 /* Returns a pointer to a string describing the program version.  The
449  * caller must not modify or free the returned string.
450  */
451 const char *
452 get_program_version(void)
453 {
454     return program_version;
455 }
456
457 /* Print the version information for the program.  */
458 void
459 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
460 {
461     printf("%s", program_version);
462     if (min_ofp || max_ofp) {
463         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
464     }
465 }
466
467 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
468  * line.  Numeric offsets are also included, starting at 'ofs' for the first
469  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
470  * are also rendered alongside. */
471 void
472 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
473              uintptr_t ofs, bool ascii)
474 {
475   const uint8_t *buf = buf_;
476   const size_t per_line = 16; /* Maximum bytes per line. */
477
478   while (size > 0)
479     {
480       size_t start, end, n;
481       size_t i;
482
483       /* Number of bytes on this line. */
484       start = ofs % per_line;
485       end = per_line;
486       if (end - start > size)
487         end = start + size;
488       n = end - start;
489
490       /* Print line. */
491       fprintf(stream, "%08"PRIxMAX"  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
492       for (i = 0; i < start; i++)
493         fprintf(stream, "   ");
494       for (; i < end; i++)
495         fprintf(stream, "%02x%c",
496                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
497       if (ascii)
498         {
499           for (; i < per_line; i++)
500             fprintf(stream, "   ");
501           fprintf(stream, "|");
502           for (i = 0; i < start; i++)
503             fprintf(stream, " ");
504           for (; i < end; i++) {
505               int c = buf[i - start];
506               putc(c >= 32 && c < 127 ? c : '.', stream);
507           }
508           for (; i < per_line; i++)
509             fprintf(stream, " ");
510           fprintf(stream, "|");
511         }
512       fprintf(stream, "\n");
513
514       ofs += n;
515       buf += n;
516       size -= n;
517     }
518 }
519
520 bool
521 str_to_int(const char *s, int base, int *i)
522 {
523     long long ll;
524     bool ok = str_to_llong(s, base, &ll);
525     *i = ll;
526     return ok;
527 }
528
529 bool
530 str_to_long(const char *s, int base, long *li)
531 {
532     long long ll;
533     bool ok = str_to_llong(s, base, &ll);
534     *li = ll;
535     return ok;
536 }
537
538 bool
539 str_to_llong(const char *s, int base, long long *x)
540 {
541     int save_errno = errno;
542     char *tail;
543     errno = 0;
544     *x = strtoll(s, &tail, base);
545     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
546         errno = save_errno;
547         *x = 0;
548         return false;
549     } else {
550         errno = save_errno;
551         return true;
552     }
553 }
554
555 /* Converts floating-point string 's' into a double.  If successful, stores
556  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
557  * returns false.
558  *
559  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
560  * (e.g. "1e9999)" is. */
561 bool
562 str_to_double(const char *s, double *d)
563 {
564     int save_errno = errno;
565     char *tail;
566     errno = 0;
567     *d = strtod(s, &tail);
568     if (errno == EINVAL || (errno == ERANGE && *d != 0)
569         || tail == s || *tail != '\0') {
570         errno = save_errno;
571         *d = 0;
572         return false;
573     } else {
574         errno = save_errno;
575         return true;
576     }
577 }
578
579 /* Returns the value of 'c' as a hexadecimal digit. */
580 int
581 hexit_value(int c)
582 {
583     switch (c) {
584     case '0': case '1': case '2': case '3': case '4':
585     case '5': case '6': case '7': case '8': case '9':
586         return c - '0';
587
588     case 'a': case 'A':
589         return 0xa;
590
591     case 'b': case 'B':
592         return 0xb;
593
594     case 'c': case 'C':
595         return 0xc;
596
597     case 'd': case 'D':
598         return 0xd;
599
600     case 'e': case 'E':
601         return 0xe;
602
603     case 'f': case 'F':
604         return 0xf;
605
606     default:
607         return -1;
608     }
609 }
610
611 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
612  * UINT_MAX if one of those "digits" is not really a hex digit.  If 'ok' is
613  * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
614  * non-hex digit is detected. */
615 unsigned int
616 hexits_value(const char *s, size_t n, bool *ok)
617 {
618     unsigned int value;
619     size_t i;
620
621     value = 0;
622     for (i = 0; i < n; i++) {
623         int hexit = hexit_value(s[i]);
624         if (hexit < 0) {
625             if (ok) {
626                 *ok = false;
627             }
628             return UINT_MAX;
629         }
630         value = (value << 4) + hexit;
631     }
632     if (ok) {
633         *ok = true;
634     }
635     return value;
636 }
637
638 /* Returns the current working directory as a malloc()'d string, or a null
639  * pointer if the current working directory cannot be determined. */
640 char *
641 get_cwd(void)
642 {
643     long int path_max;
644     size_t size;
645
646     /* Get maximum path length or at least a reasonable estimate. */
647     path_max = pathconf(".", _PC_PATH_MAX);
648     size = (path_max < 0 ? 1024
649             : path_max > 10240 ? 10240
650             : path_max);
651
652     /* Get current working directory. */
653     for (;;) {
654         char *buf = xmalloc(size);
655         if (getcwd(buf, size)) {
656             return xrealloc(buf, strlen(buf) + 1);
657         } else {
658             int error = errno;
659             free(buf);
660             if (error != ERANGE) {
661                 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
662                 return NULL;
663             }
664             size *= 2;
665         }
666     }
667 }
668
669 static char *
670 all_slashes_name(const char *s)
671 {
672     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
673                    : s[0] == '/' ? "/"
674                    : ".");
675 }
676
677 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
678  * similar to the POSIX dirname() function but thread-safe. */
679 char *
680 dir_name(const char *file_name)
681 {
682     size_t len = strlen(file_name);
683     while (len > 0 && file_name[len - 1] == '/') {
684         len--;
685     }
686     while (len > 0 && file_name[len - 1] != '/') {
687         len--;
688     }
689     while (len > 0 && file_name[len - 1] == '/') {
690         len--;
691     }
692     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
693 }
694
695 /* Returns the file name portion of 'file_name' as a malloc()'d string,
696  * similar to the POSIX basename() function but thread-safe. */
697 char *
698 base_name(const char *file_name)
699 {
700     size_t end, start;
701
702     end = strlen(file_name);
703     while (end > 0 && file_name[end - 1] == '/') {
704         end--;
705     }
706
707     if (!end) {
708         return all_slashes_name(file_name);
709     }
710
711     start = end;
712     while (start > 0 && file_name[start - 1] != '/') {
713         start--;
714     }
715
716     return xmemdup0(file_name + start, end - start);
717 }
718
719 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
720  * returns an absolute path to 'file_name' considering it relative to 'dir',
721  * which itself must be absolute.  'dir' may be null or the empty string, in
722  * which case the current working directory is used.
723  *
724  * Returns a null pointer if 'dir' is null and getcwd() fails. */
725 char *
726 abs_file_name(const char *dir, const char *file_name)
727 {
728     if (file_name[0] == '/') {
729         return xstrdup(file_name);
730     } else if (dir && dir[0]) {
731         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
732         return xasprintf("%s%s%s", dir, separator, file_name);
733     } else {
734         char *cwd = get_cwd();
735         if (cwd) {
736             char *abs_name = xasprintf("%s/%s", cwd, file_name);
737             free(cwd);
738             return abs_name;
739         } else {
740             return NULL;
741         }
742     }
743 }
744
745 /* Like readlink(), but returns the link name as a null-terminated string in
746  * allocated memory that the caller must eventually free (with free()).
747  * Returns NULL on error, in which case errno is set appropriately. */
748 char *
749 xreadlink(const char *filename)
750 {
751     size_t size;
752
753     for (size = 64; ; size *= 2) {
754         char *buf = xmalloc(size);
755         ssize_t retval = readlink(filename, buf, size);
756         int error = errno;
757
758         if (retval >= 0 && retval < size) {
759             buf[retval] = '\0';
760             return buf;
761         }
762
763         free(buf);
764         if (retval < 0) {
765             errno = error;
766             return NULL;
767         }
768     }
769 }
770
771 /* Returns a version of 'filename' with symlinks in the final component
772  * dereferenced.  This differs from realpath() in that:
773  *
774  *     - 'filename' need not exist.
775  *
776  *     - If 'filename' does exist as a symlink, its referent need not exist.
777  *
778  *     - Only symlinks in the final component of 'filename' are dereferenced.
779  *
780  * The caller must eventually free the returned string (with free()). */
781 char *
782 follow_symlinks(const char *filename)
783 {
784     struct stat s;
785     char *fn;
786     int i;
787
788     fn = xstrdup(filename);
789     for (i = 0; i < 10; i++) {
790         char *linkname;
791         char *next_fn;
792
793         if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
794             return fn;
795         }
796
797         linkname = xreadlink(fn);
798         if (!linkname) {
799             VLOG_WARN("%s: readlink failed (%s)",
800                       filename, ovs_strerror(errno));
801             return fn;
802         }
803
804         if (linkname[0] == '/') {
805             /* Target of symlink is absolute so use it raw. */
806             next_fn = linkname;
807         } else {
808             /* Target of symlink is relative so add to 'fn''s directory. */
809             char *dir = dir_name(fn);
810
811             if (!strcmp(dir, ".")) {
812                 next_fn = linkname;
813             } else {
814                 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
815                 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
816                 free(linkname);
817             }
818
819             free(dir);
820         }
821
822         free(fn);
823         fn = next_fn;
824     }
825
826     VLOG_WARN("%s: too many levels of symlinks", filename);
827     free(fn);
828     return xstrdup(filename);
829 }
830
831 /* Pass a value to this function if it is marked with
832  * __attribute__((warn_unused_result)) and you genuinely want to ignore
833  * its return value.  (Note that every scalar type can be implicitly
834  * converted to bool.) */
835 void ignore(bool x OVS_UNUSED) { }
836
837 /* Returns an appropriate delimiter for inserting just before the 0-based item
838  * 'index' in a list that has 'total' items in it. */
839 const char *
840 english_list_delimiter(size_t index, size_t total)
841 {
842     return (index == 0 ? ""
843             : index < total - 1 ? ", "
844             : total > 2 ? ", and "
845             : " and ");
846 }
847
848 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
849 #if __GNUC__ >= 4
850 /* Defined inline in util.h. */
851 #else
852 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
853 int
854 raw_ctz(uint64_t n)
855 {
856     uint64_t k;
857     int count = 63;
858
859 #define CTZ_STEP(X)                             \
860     k = n << (X);                               \
861     if (k) {                                    \
862         count -= X;                             \
863         n = k;                                  \
864     }
865     CTZ_STEP(32);
866     CTZ_STEP(16);
867     CTZ_STEP(8);
868     CTZ_STEP(4);
869     CTZ_STEP(2);
870     CTZ_STEP(1);
871 #undef CTZ_STEP
872
873     return count;
874 }
875
876 /* Returns the number of leading 0-bits in 'n'.  Undefined if 'n' == 0. */
877 int
878 raw_clz64(uint64_t n)
879 {
880     uint64_t k;
881     int count = 63;
882
883 #define CLZ_STEP(X)                             \
884     k = n >> (X);                               \
885     if (k) {                                    \
886         count -= X;                             \
887         n = k;                                  \
888     }
889     CLZ_STEP(32);
890     CLZ_STEP(16);
891     CLZ_STEP(8);
892     CLZ_STEP(4);
893     CLZ_STEP(2);
894     CLZ_STEP(1);
895 #undef CLZ_STEP
896
897     return count;
898 }
899 #endif
900
901 #if NEED_COUNT_1BITS_8
902 #define INIT1(X)                                \
903     ((((X) & (1 << 0)) != 0) +                  \
904      (((X) & (1 << 1)) != 0) +                  \
905      (((X) & (1 << 2)) != 0) +                  \
906      (((X) & (1 << 3)) != 0) +                  \
907      (((X) & (1 << 4)) != 0) +                  \
908      (((X) & (1 << 5)) != 0) +                  \
909      (((X) & (1 << 6)) != 0) +                  \
910      (((X) & (1 << 7)) != 0))
911 #define INIT2(X)   INIT1(X),  INIT1((X) +  1)
912 #define INIT4(X)   INIT2(X),  INIT2((X) +  2)
913 #define INIT8(X)   INIT4(X),  INIT4((X) +  4)
914 #define INIT16(X)  INIT8(X),  INIT8((X) +  8)
915 #define INIT32(X) INIT16(X), INIT16((X) + 16)
916 #define INIT64(X) INIT32(X), INIT32((X) + 32)
917
918 const uint8_t count_1bits_8[256] = {
919     INIT64(0), INIT64(64), INIT64(128), INIT64(192)
920 };
921 #endif
922
923 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
924 bool
925 is_all_zeros(const uint8_t *p, size_t n)
926 {
927     size_t i;
928
929     for (i = 0; i < n; i++) {
930         if (p[i] != 0x00) {
931             return false;
932         }
933     }
934     return true;
935 }
936
937 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
938 bool
939 is_all_ones(const uint8_t *p, size_t n)
940 {
941     size_t i;
942
943     for (i = 0; i < n; i++) {
944         if (p[i] != 0xff) {
945             return false;
946         }
947     }
948     return true;
949 }
950
951 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
952  * starting from bit 'dst_ofs' in 'dst'.  'src' is 'src_len' bytes long and
953  * 'dst' is 'dst_len' bytes long.
954  *
955  * If you consider all of 'src' to be a single unsigned integer in network byte
956  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
957  * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
958  * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
959  * 2], and so on.  Similarly for 'dst'.
960  *
961  * Required invariants:
962  *   src_ofs + n_bits <= src_len * 8
963  *   dst_ofs + n_bits <= dst_len * 8
964  *   'src' and 'dst' must not overlap.
965  */
966 void
967 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
968              void *dst_, unsigned int dst_len, unsigned int dst_ofs,
969              unsigned int n_bits)
970 {
971     const uint8_t *src = src_;
972     uint8_t *dst = dst_;
973
974     src += src_len - (src_ofs / 8 + 1);
975     src_ofs %= 8;
976
977     dst += dst_len - (dst_ofs / 8 + 1);
978     dst_ofs %= 8;
979
980     if (src_ofs == 0 && dst_ofs == 0) {
981         unsigned int n_bytes = n_bits / 8;
982         if (n_bytes) {
983             dst -= n_bytes - 1;
984             src -= n_bytes - 1;
985             memcpy(dst, src, n_bytes);
986
987             n_bits %= 8;
988             src--;
989             dst--;
990         }
991         if (n_bits) {
992             uint8_t mask = (1 << n_bits) - 1;
993             *dst = (*dst & ~mask) | (*src & mask);
994         }
995     } else {
996         while (n_bits > 0) {
997             unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
998             unsigned int chunk = MIN(n_bits, max_copy);
999             uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1000
1001             *dst &= ~mask;
1002             *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1003
1004             src_ofs += chunk;
1005             if (src_ofs == 8) {
1006                 src--;
1007                 src_ofs = 0;
1008             }
1009             dst_ofs += chunk;
1010             if (dst_ofs == 8) {
1011                 dst--;
1012                 dst_ofs = 0;
1013             }
1014             n_bits -= chunk;
1015         }
1016     }
1017 }
1018
1019 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.  'dst' is
1020  * 'dst_len' bytes long.
1021  *
1022  * If you consider all of 'dst' to be a single unsigned integer in network byte
1023  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1024  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1025  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1026  * 2], and so on.
1027  *
1028  * Required invariant:
1029  *   dst_ofs + n_bits <= dst_len * 8
1030  */
1031 void
1032 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1033              unsigned int n_bits)
1034 {
1035     uint8_t *dst = dst_;
1036
1037     if (!n_bits) {
1038         return;
1039     }
1040
1041     dst += dst_len - (dst_ofs / 8 + 1);
1042     dst_ofs %= 8;
1043
1044     if (dst_ofs) {
1045         unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1046
1047         *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1048
1049         n_bits -= chunk;
1050         if (!n_bits) {
1051             return;
1052         }
1053
1054         dst--;
1055     }
1056
1057     while (n_bits >= 8) {
1058         *dst-- = 0;
1059         n_bits -= 8;
1060     }
1061
1062     if (n_bits) {
1063         *dst &= ~((1 << n_bits) - 1);
1064     }
1065 }
1066
1067 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1068  * 'dst' is 'dst_len' bytes long.
1069  *
1070  * If you consider all of 'dst' to be a single unsigned integer in network byte
1071  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1072  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1073  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1074  * 2], and so on.
1075  *
1076  * Required invariant:
1077  *   dst_ofs + n_bits <= dst_len * 8
1078  */
1079 void
1080 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1081             unsigned int n_bits)
1082 {
1083     uint8_t *dst = dst_;
1084
1085     if (!n_bits) {
1086         return;
1087     }
1088
1089     dst += dst_len - (dst_ofs / 8 + 1);
1090     dst_ofs %= 8;
1091
1092     if (dst_ofs) {
1093         unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1094
1095         *dst |= ((1 << chunk) - 1) << dst_ofs;
1096
1097         n_bits -= chunk;
1098         if (!n_bits) {
1099             return;
1100         }
1101
1102         dst--;
1103     }
1104
1105     while (n_bits >= 8) {
1106         *dst-- = 0xff;
1107         n_bits -= 8;
1108     }
1109
1110     if (n_bits) {
1111         *dst |= (1 << n_bits) - 1;
1112     }
1113 }
1114
1115 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1116  * Returns false if any 1-bits are found, otherwise true.  'dst' is 'dst_len'
1117  * bytes long.
1118  *
1119  * If you consider all of 'dst' to be a single unsigned integer in network byte
1120  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1121  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1122  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1123  * 2], and so on.
1124  *
1125  * Required invariant:
1126  *   dst_ofs + n_bits <= dst_len * 8
1127  */
1128 bool
1129 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1130                      unsigned int n_bits)
1131 {
1132     const uint8_t *p = p_;
1133
1134     if (!n_bits) {
1135         return true;
1136     }
1137
1138     p += len - (ofs / 8 + 1);
1139     ofs %= 8;
1140
1141     if (ofs) {
1142         unsigned int chunk = MIN(n_bits, 8 - ofs);
1143
1144         if (*p & (((1 << chunk) - 1) << ofs)) {
1145             return false;
1146         }
1147
1148         n_bits -= chunk;
1149         if (!n_bits) {
1150             return true;
1151         }
1152
1153         p--;
1154     }
1155
1156     while (n_bits >= 8) {
1157         if (*p) {
1158             return false;
1159         }
1160         n_bits -= 8;
1161         p--;
1162     }
1163
1164     if (n_bits && *p & ((1 << n_bits) - 1)) {
1165         return false;
1166     }
1167
1168     return true;
1169 }
1170
1171 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1172  * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1173  *
1174  * If you consider all of 'dst' to be a single unsigned integer in network byte
1175  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1176  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1177  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1178  * 2], and so on.
1179  *
1180  * Required invariants:
1181  *   dst_ofs + n_bits <= dst_len * 8
1182  *   n_bits <= 64
1183  */
1184 void
1185 bitwise_put(uint64_t value,
1186             void *dst, unsigned int dst_len, unsigned int dst_ofs,
1187             unsigned int n_bits)
1188 {
1189     ovs_be64 n_value = htonll(value);
1190     bitwise_copy(&n_value, sizeof n_value, 0,
1191                  dst, dst_len, dst_ofs,
1192                  n_bits);
1193 }
1194
1195 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1196  * which is 'src_len' bytes long.
1197  *
1198  * If you consider all of 'src' to be a single unsigned integer in network byte
1199  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1200  * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1201  * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1202  * 2], and so on.
1203  *
1204  * Required invariants:
1205  *   src_ofs + n_bits <= src_len * 8
1206  *   n_bits <= 64
1207  */
1208 uint64_t
1209 bitwise_get(const void *src, unsigned int src_len,
1210             unsigned int src_ofs, unsigned int n_bits)
1211 {
1212     ovs_be64 value = htonll(0);
1213
1214     bitwise_copy(src, src_len, src_ofs,
1215                  &value, sizeof value, 0,
1216                  n_bits);
1217     return ntohll(value);
1218 }
1219 \f
1220 /* ovs_scan */
1221
1222 struct scan_spec {
1223     unsigned int width;
1224     enum {
1225         SCAN_DISCARD,
1226         SCAN_CHAR,
1227         SCAN_SHORT,
1228         SCAN_INT,
1229         SCAN_LONG,
1230         SCAN_LLONG,
1231         SCAN_INTMAX_T,
1232         SCAN_PTRDIFF_T,
1233         SCAN_SIZE_T
1234     } type;
1235 };
1236
1237 static const char *
1238 skip_spaces(const char *s)
1239 {
1240     while (isspace((unsigned char) *s)) {
1241         s++;
1242     }
1243     return s;
1244 }
1245
1246 static const char *
1247 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1248 {
1249     const char *start = s;
1250     uintmax_t value;
1251     bool negative;
1252     int n_digits;
1253
1254     negative = *s == '-';
1255     s += *s == '-' || *s == '+';
1256
1257     if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1258         base = 16;
1259         s += 2;
1260     } else if (!base) {
1261         base = *s == '0' ? 8 : 10;
1262     }
1263
1264     if (s - start >= spec->width) {
1265         return NULL;
1266     }
1267
1268     value = 0;
1269     n_digits = 0;
1270     while (s - start < spec->width) {
1271         int digit = hexit_value(*s);
1272
1273         if (digit < 0 || digit >= base) {
1274             break;
1275         }
1276         value = value * base + digit;
1277         n_digits++;
1278         s++;
1279     }
1280     if (!n_digits) {
1281         return NULL;
1282     }
1283
1284     if (negative) {
1285         value = -value;
1286     }
1287
1288     switch (spec->type) {
1289     case SCAN_DISCARD:
1290         break;
1291     case SCAN_CHAR:
1292         *va_arg(*args, char *) = value;
1293         break;
1294     case SCAN_SHORT:
1295         *va_arg(*args, short int *) = value;
1296         break;
1297     case SCAN_INT:
1298         *va_arg(*args, int *) = value;
1299         break;
1300     case SCAN_LONG:
1301         *va_arg(*args, long int *) = value;
1302         break;
1303     case SCAN_LLONG:
1304         *va_arg(*args, long long int *) = value;
1305         break;
1306     case SCAN_INTMAX_T:
1307         *va_arg(*args, intmax_t *) = value;
1308         break;
1309     case SCAN_PTRDIFF_T:
1310         *va_arg(*args, ptrdiff_t *) = value;
1311         break;
1312     case SCAN_SIZE_T:
1313         *va_arg(*args, size_t *) = value;
1314         break;
1315     }
1316     return s;
1317 }
1318
1319 static const char *
1320 skip_digits(const char *s)
1321 {
1322     while (*s >= '0' && *s <= '9') {
1323         s++;
1324     }
1325     return s;
1326 }
1327
1328 static const char *
1329 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1330 {
1331     const char *start = s;
1332     long double value;
1333     char *tail;
1334     char *copy;
1335     bool ok;
1336
1337     s += *s == '+' || *s == '-';
1338     s = skip_digits(s);
1339     if (*s == '.') {
1340         s = skip_digits(s + 1);
1341     }
1342     if (*s == 'e' || *s == 'E') {
1343         s++;
1344         s += *s == '+' || *s == '-';
1345         s = skip_digits(s);
1346     }
1347
1348     if (s - start > spec->width) {
1349         s = start + spec->width;
1350     }
1351
1352     copy = xmemdup0(start, s - start);
1353     value = strtold(copy, &tail);
1354     ok = *tail == '\0';
1355     free(copy);
1356     if (!ok) {
1357         return NULL;
1358     }
1359
1360     switch (spec->type) {
1361     case SCAN_DISCARD:
1362         break;
1363     case SCAN_INT:
1364         *va_arg(*args, float *) = value;
1365         break;
1366     case SCAN_LONG:
1367         *va_arg(*args, double *) = value;
1368         break;
1369     case SCAN_LLONG:
1370         *va_arg(*args, long double *) = value;
1371         break;
1372
1373     case SCAN_CHAR:
1374     case SCAN_SHORT:
1375     case SCAN_INTMAX_T:
1376     case SCAN_PTRDIFF_T:
1377     case SCAN_SIZE_T:
1378         OVS_NOT_REACHED();
1379     }
1380     return s;
1381 }
1382
1383 static void
1384 scan_output_string(const struct scan_spec *spec,
1385                    const char *s, size_t n,
1386                    va_list *args)
1387 {
1388     if (spec->type != SCAN_DISCARD) {
1389         char *out = va_arg(*args, char *);
1390         memcpy(out, s, n);
1391         out[n] = '\0';
1392     }
1393 }
1394
1395 static const char *
1396 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1397 {
1398     size_t n;
1399
1400     for (n = 0; n < spec->width; n++) {
1401         if (!s[n] || isspace((unsigned char) s[n])) {
1402             break;
1403         }
1404     }
1405     if (!n) {
1406         return NULL;
1407     }
1408
1409     scan_output_string(spec, s, n, args);
1410     return s + n;
1411 }
1412
1413 static const char *
1414 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1415 {
1416     const uint8_t *p = (const uint8_t *) p_;
1417
1418     *complemented = *p == '^';
1419     p += *complemented;
1420
1421     if (*p == ']') {
1422         bitmap_set1(set, ']');
1423         p++;
1424     }
1425
1426     while (*p && *p != ']') {
1427         if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1428             bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1429             p += 3;
1430         } else {
1431             bitmap_set1(set, *p++);
1432         }
1433     }
1434     if (*p == ']') {
1435         p++;
1436     }
1437     return (const char *) p;
1438 }
1439
1440 static const char *
1441 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1442          va_list *args)
1443 {
1444     unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1445     bool complemented;
1446     unsigned int n;
1447
1448     /* Parse the scan set. */
1449     memset(set, 0, sizeof set);
1450     *pp = parse_scanset(*pp, set, &complemented);
1451
1452     /* Parse the data. */
1453     n = 0;
1454     while (s[n]
1455            && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1456            && n < spec->width) {
1457         n++;
1458     }
1459     if (!n) {
1460         return NULL;
1461     }
1462     scan_output_string(spec, s, n, args);
1463     return s + n;
1464 }
1465
1466 static const char *
1467 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1468 {
1469     unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1470
1471     if (strlen(s) < n) {
1472         return NULL;
1473     }
1474     if (spec->type != SCAN_DISCARD) {
1475         memcpy(va_arg(*args, char *), s, n);
1476     }
1477     return s + n;
1478 }
1479
1480 /* This is an implementation of the standard sscanf() function, with the
1481  * following exceptions:
1482  *
1483  *   - It returns true if the entire format was successfully scanned and
1484  *     converted, false if any conversion failed.
1485  *
1486  *   - The standard doesn't define sscanf() behavior when an out-of-range value
1487  *     is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff".  Some
1488  *     implementations consider this an error and stop scanning.  This
1489  *     implementation never considers an out-of-range value an error; instead,
1490  *     it stores the least-significant bits of the converted value in the
1491  *     destination, e.g. the value 255 for both examples earlier.
1492  *
1493  *   - Only single-byte characters are supported, that is, the 'l' modifier
1494  *     on %s, %[, and %c is not supported.  The GNU extension 'a' modifier is
1495  *     also not supported.
1496  *
1497  *   - %p is not supported.
1498  */
1499 bool
1500 ovs_scan(const char *s, const char *format, ...)
1501 {
1502     const char *const start = s;
1503     bool ok = false;
1504     const char *p;
1505     va_list args;
1506
1507     va_start(args, format);
1508     p = format;
1509     while (*p != '\0') {
1510         struct scan_spec spec;
1511         unsigned char c = *p++;
1512         bool discard;
1513
1514         if (isspace(c)) {
1515             s = skip_spaces(s);
1516             continue;
1517         } else if (c != '%') {
1518             if (*s != c) {
1519                 goto exit;
1520             }
1521             s++;
1522             continue;
1523         } else if (*p == '%') {
1524             if (*s++ != '%') {
1525                 goto exit;
1526             }
1527             p++;
1528             continue;
1529         }
1530
1531         /* Parse '*' flag. */
1532         discard = *p == '*';
1533         p += discard;
1534
1535         /* Parse field width. */
1536         spec.width = 0;
1537         while (*p >= '0' && *p <= '9') {
1538             spec.width = spec.width * 10 + (*p++ - '0');
1539         }
1540         if (spec.width == 0) {
1541             spec.width = UINT_MAX;
1542         }
1543
1544         /* Parse type modifier. */
1545         switch (*p) {
1546         case 'h':
1547             if (p[1] == 'h') {
1548                 spec.type = SCAN_CHAR;
1549                 p += 2;
1550             } else {
1551                 spec.type = SCAN_SHORT;
1552                 p++;
1553             }
1554             break;
1555
1556         case 'j':
1557             spec.type = SCAN_INTMAX_T;
1558             p++;
1559             break;
1560
1561         case 'l':
1562             if (p[1] == 'l') {
1563                 spec.type = SCAN_LLONG;
1564                 p += 2;
1565             } else {
1566                 spec.type = SCAN_LONG;
1567                 p++;
1568             }
1569             break;
1570
1571         case 'L':
1572         case 'q':
1573             spec.type = SCAN_LLONG;
1574             p++;
1575             break;
1576
1577         case 't':
1578             spec.type = SCAN_PTRDIFF_T;
1579             p++;
1580             break;
1581
1582         case 'z':
1583             spec.type = SCAN_SIZE_T;
1584             p++;
1585             break;
1586
1587         default:
1588             spec.type = SCAN_INT;
1589             break;
1590         }
1591
1592         if (discard) {
1593             spec.type = SCAN_DISCARD;
1594         }
1595
1596         c = *p++;
1597         if (c != 'c' && c != 'n' && c != '[') {
1598             s = skip_spaces(s);
1599         }
1600         switch (c) {
1601         case 'd':
1602             s = scan_int(s, &spec, 10, &args);
1603             break;
1604
1605         case 'i':
1606             s = scan_int(s, &spec, 0, &args);
1607             break;
1608
1609         case 'o':
1610             s = scan_int(s, &spec, 8, &args);
1611             break;
1612
1613         case 'u':
1614             s = scan_int(s, &spec, 10, &args);
1615             break;
1616
1617         case 'x':
1618         case 'X':
1619             s = scan_int(s, &spec, 16, &args);
1620             break;
1621
1622         case 'e':
1623         case 'f':
1624         case 'g':
1625         case 'E':
1626         case 'G':
1627             s = scan_float(s, &spec, &args);
1628             break;
1629
1630         case 's':
1631             s = scan_string(s, &spec, &args);
1632             break;
1633
1634         case '[':
1635             s = scan_set(s, &spec, &p, &args);
1636             break;
1637
1638         case 'c':
1639             s = scan_chars(s, &spec, &args);
1640             break;
1641
1642         case 'n':
1643             if (spec.type != SCAN_DISCARD) {
1644                 *va_arg(args, int *) = s - start;
1645             }
1646             break;
1647         }
1648
1649         if (!s) {
1650             goto exit;
1651         }
1652     }
1653     ok = true;
1654
1655 exit:
1656     va_end(args);
1657     return ok;
1658 }
1659
1660 #ifdef _WIN32
1661 \f
1662 /* Calls FormatMessage() with GetLastError() as an argument. Returns
1663  * pointer to a buffer that receives the null-terminated string that specifies
1664  * the formatted message and that has to be freed by the caller with
1665  * LocalFree(). */
1666 char *
1667 ovs_lasterror_to_string(void)
1668 {
1669     char *buffer;
1670     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1671                   | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), 0,
1672                   (char *)&buffer, 0, NULL);
1673     return buffer;
1674 }
1675 #endif