util: Don't read over 'size - 1' bytes of source string in ovs_strlcpy().
[sliver-openvswitch.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 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 <errno.h>
20 #include <stdarg.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "vlog.h"
27
28 VLOG_DEFINE_THIS_MODULE(util);
29
30 COVERAGE_DEFINE(util_xalloc);
31
32 const char *program_name;
33
34 void
35 out_of_memory(void)
36 {
37     ovs_fatal(0, "virtual memory exhausted");
38 }
39
40 void *
41 xcalloc(size_t count, size_t size)
42 {
43     void *p = count && size ? calloc(count, size) : malloc(1);
44     COVERAGE_INC(util_xalloc);
45     if (p == NULL) {
46         out_of_memory();
47     }
48     return p;
49 }
50
51 void *
52 xzalloc(size_t size)
53 {
54     return xcalloc(1, size);
55 }
56
57 void *
58 xmalloc(size_t size)
59 {
60     void *p = malloc(size ? size : 1);
61     COVERAGE_INC(util_xalloc);
62     if (p == NULL) {
63         out_of_memory();
64     }
65     return p;
66 }
67
68 void *
69 xrealloc(void *p, size_t size)
70 {
71     p = realloc(p, size ? size : 1);
72     COVERAGE_INC(util_xalloc);
73     if (p == NULL) {
74         out_of_memory();
75     }
76     return p;
77 }
78
79 void *
80 xmemdup(const void *p_, size_t size)
81 {
82     void *p = xmalloc(size);
83     memcpy(p, p_, size);
84     return p;
85 }
86
87 char *
88 xmemdup0(const char *p_, size_t length)
89 {
90     char *p = xmalloc(length + 1);
91     memcpy(p, p_, length);
92     p[length] = '\0';
93     return p;
94 }
95
96 char *
97 xstrdup(const char *s)
98 {
99     return xmemdup0(s, strlen(s));
100 }
101
102 char *
103 xvasprintf(const char *format, va_list args)
104 {
105     va_list args2;
106     size_t needed;
107     char *s;
108
109     va_copy(args2, args);
110     needed = vsnprintf(NULL, 0, format, args);
111
112     s = xmalloc(needed + 1);
113
114     vsnprintf(s, needed + 1, format, args2);
115     va_end(args2);
116
117     return s;
118 }
119
120 void *
121 x2nrealloc(void *p, size_t *n, size_t s)
122 {
123     *n = *n == 0 ? 1 : 2 * *n;
124     return xrealloc(p, *n * s);
125 }
126
127 char *
128 xasprintf(const char *format, ...)
129 {
130     va_list args;
131     char *s;
132
133     va_start(args, format);
134     s = xvasprintf(format, args);
135     va_end(args);
136
137     return s;
138 }
139
140 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
141  * bytes from 'src' and doesn't return anything. */
142 void
143 ovs_strlcpy(char *dst, const char *src, size_t size)
144 {
145     if (size > 0) {
146         size_t len = strnlen(src, size - 1);
147         memcpy(dst, src, len);
148         dst[len] = '\0';
149     }
150 }
151
152 void
153 ovs_fatal(int err_no, const char *format, ...)
154 {
155     va_list args;
156
157     fprintf(stderr, "%s: ", program_name);
158     va_start(args, format);
159     vfprintf(stderr, format, args);
160     va_end(args);
161     if (err_no != 0)
162         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
163     putc('\n', stderr);
164
165     exit(EXIT_FAILURE);
166 }
167
168 void
169 ovs_error(int err_no, const char *format, ...)
170 {
171     int save_errno = errno;
172     va_list args;
173
174     fprintf(stderr, "%s: ", program_name);
175     va_start(args, format);
176     vfprintf(stderr, format, args);
177     va_end(args);
178     if (err_no != 0) {
179         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
180     }
181     putc('\n', stderr);
182
183     errno = save_errno;
184 }
185
186 /* Many OVS functions return an int which is one of:
187  * - 0: no error yet
188  * - >0: errno value
189  * - EOF: end of file (not necessarily an error; depends on the function called)
190  *
191  * Returns the appropriate human-readable string. The caller must copy the
192  * string if it wants to hold onto it, as the storage may be overwritten on
193  * subsequent function calls.
194  */
195 const char *
196 ovs_retval_to_string(int retval)
197 {
198     static char unknown[48];
199
200     if (!retval) {
201         return "";
202     }
203     if (retval > 0) {
204         return strerror(retval);
205     }
206     if (retval == EOF) {
207         return "End of file";
208     }
209     snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
210     return unknown;
211 }
212
213 /* Sets program_name based on 'argv0'.  Should be called at the beginning of
214  * main(), as "set_program_name(argv[0]);".  */
215 void set_program_name(const char *argv0)
216 {
217     const char *slash = strrchr(argv0, '/');
218     program_name = slash ? slash + 1 : argv0;
219 }
220
221 /* Print the version information for the program.  */
222 void
223 ovs_print_version(char *date, char *time,
224                   uint8_t min_ofp, uint8_t max_ofp)
225 {
226     printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
227     printf("Compiled %s %s\n", date, time);
228     if (min_ofp || max_ofp) {
229         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
230     }
231 }
232
233 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
234  * line.  Numeric offsets are also included, starting at 'ofs' for the first
235  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
236  * are also rendered alongside. */
237 void
238 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
239              uintptr_t ofs, bool ascii)
240 {
241   const uint8_t *buf = buf_;
242   const size_t per_line = 16; /* Maximum bytes per line. */
243
244   while (size > 0)
245     {
246       size_t start, end, n;
247       size_t i;
248
249       /* Number of bytes on this line. */
250       start = ofs % per_line;
251       end = per_line;
252       if (end - start > size)
253         end = start + size;
254       n = end - start;
255
256       /* Print line. */
257       fprintf(stream, "%08jx  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
258       for (i = 0; i < start; i++)
259         fprintf(stream, "   ");
260       for (; i < end; i++)
261         fprintf(stream, "%02hhx%c",
262                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
263       if (ascii)
264         {
265           for (; i < per_line; i++)
266             fprintf(stream, "   ");
267           fprintf(stream, "|");
268           for (i = 0; i < start; i++)
269             fprintf(stream, " ");
270           for (; i < end; i++) {
271               int c = buf[i - start];
272               putc(c >= 32 && c < 127 ? c : '.', stream);
273           }
274           for (; i < per_line; i++)
275             fprintf(stream, " ");
276           fprintf(stream, "|");
277         }
278       fprintf(stream, "\n");
279
280       ofs += n;
281       buf += n;
282       size -= n;
283     }
284 }
285
286 bool
287 str_to_int(const char *s, int base, int *i)
288 {
289     long long ll;
290     bool ok = str_to_llong(s, base, &ll);
291     *i = ll;
292     return ok;
293 }
294
295 bool
296 str_to_long(const char *s, int base, long *li)
297 {
298     long long ll;
299     bool ok = str_to_llong(s, base, &ll);
300     *li = ll;
301     return ok;
302 }
303
304 bool
305 str_to_llong(const char *s, int base, long long *x)
306 {
307     int save_errno = errno;
308     char *tail;
309     errno = 0;
310     *x = strtoll(s, &tail, base);
311     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
312         errno = save_errno;
313         *x = 0;
314         return false;
315     } else {
316         errno = save_errno;
317         return true;
318     }
319 }
320
321 bool
322 str_to_uint(const char *s, int base, unsigned int *u)
323 {
324     return str_to_int(s, base, (int *) u);
325 }
326
327 bool
328 str_to_ulong(const char *s, int base, unsigned long *ul)
329 {
330     return str_to_long(s, base, (long *) ul);
331 }
332
333 bool
334 str_to_ullong(const char *s, int base, unsigned long long *ull)
335 {
336     return str_to_llong(s, base, (long long *) ull);
337 }
338
339 /* Converts floating-point string 's' into a double.  If successful, stores
340  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
341  * returns false.
342  *
343  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
344  * (e.g. "1e9999)" is. */
345 bool
346 str_to_double(const char *s, double *d)
347 {
348     int save_errno = errno;
349     char *tail;
350     errno = 0;
351     *d = strtod(s, &tail);
352     if (errno == EINVAL || (errno == ERANGE && *d != 0)
353         || tail == s || *tail != '\0') {
354         errno = save_errno;
355         *d = 0;
356         return false;
357     } else {
358         errno = save_errno;
359         return true;
360     }
361 }
362
363 /* Returns the value of 'c' as a hexadecimal digit. */
364 int
365 hexit_value(int c)
366 {
367     switch (c) {
368     case '0': case '1': case '2': case '3': case '4':
369     case '5': case '6': case '7': case '8': case '9':
370         return c - '0';
371
372     case 'a': case 'A':
373         return 0xa;
374
375     case 'b': case 'B':
376         return 0xb;
377
378     case 'c': case 'C':
379         return 0xc;
380
381     case 'd': case 'D':
382         return 0xd;
383
384     case 'e': case 'E':
385         return 0xe;
386
387     case 'f': case 'F':
388         return 0xf;
389
390     default:
391         return -1;
392     }
393 }
394
395 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
396  * UINT_MAX if one of those "digits" is not really a hex digit.  If 'ok' is
397  * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
398  * non-hex digit is detected. */
399 unsigned int
400 hexits_value(const char *s, size_t n, bool *ok)
401 {
402     unsigned int value;
403     size_t i;
404
405     value = 0;
406     for (i = 0; i < n; i++) {
407         int hexit = hexit_value(s[i]);
408         if (hexit < 0) {
409             if (ok) {
410                 *ok = false;
411             }
412             return UINT_MAX;
413         }
414         value = (value << 4) + hexit;
415     }
416     if (ok) {
417         *ok = true;
418     }
419     return value;
420 }
421
422 /* Returns the current working directory as a malloc()'d string, or a null
423  * pointer if the current working directory cannot be determined. */
424 char *
425 get_cwd(void)
426 {
427     long int path_max;
428     size_t size;
429
430     /* Get maximum path length or at least a reasonable estimate. */
431     path_max = pathconf(".", _PC_PATH_MAX);
432     size = (path_max < 0 ? 1024
433             : path_max > 10240 ? 10240
434             : path_max);
435
436     /* Get current working directory. */
437     for (;;) {
438         char *buf = xmalloc(size);
439         if (getcwd(buf, size)) {
440             return xrealloc(buf, strlen(buf) + 1);
441         } else {
442             int error = errno;
443             free(buf);
444             if (error != ERANGE) {
445                 VLOG_WARN("getcwd failed (%s)", strerror(error));
446                 return NULL;
447             }
448             size *= 2;
449         }
450     }
451 }
452
453 static char *
454 all_slashes_name(const char *s)
455 {
456     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
457                    : s[0] == '/' ? "/"
458                    : ".");
459 }
460
461 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
462  * similar to the POSIX dirname() function but thread-safe. */
463 char *
464 dir_name(const char *file_name)
465 {
466     size_t len = strlen(file_name);
467     while (len > 0 && file_name[len - 1] == '/') {
468         len--;
469     }
470     while (len > 0 && file_name[len - 1] != '/') {
471         len--;
472     }
473     while (len > 0 && file_name[len - 1] == '/') {
474         len--;
475     }
476     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
477 }
478
479 /* Returns the file name portion of 'file_name' as a malloc()'d string,
480  * similar to the POSIX basename() function but thread-safe. */
481 char *
482 base_name(const char *file_name)
483 {
484     size_t end, start;
485
486     end = strlen(file_name);
487     while (end > 0 && file_name[end - 1] == '/') {
488         end--;
489     }
490
491     if (!end) {
492         return all_slashes_name(file_name);
493     }
494
495     start = end;
496     while (start > 0 && file_name[start - 1] != '/') {
497         start--;
498     }
499
500     return xmemdup0(file_name + start, end - start);
501 }
502
503 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
504  * returns an absolute path to 'file_name' considering it relative to 'dir',
505  * which itself must be absolute.  'dir' may be null or the empty string, in
506  * which case the current working directory is used.
507  *
508  * Returns a null pointer if 'dir' is null and getcwd() fails. */
509 char *
510 abs_file_name(const char *dir, const char *file_name)
511 {
512     if (file_name[0] == '/') {
513         return xstrdup(file_name);
514     } else if (dir && dir[0]) {
515         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
516         return xasprintf("%s%s%s", dir, separator, file_name);
517     } else {
518         char *cwd = get_cwd();
519         if (cwd) {
520             char *abs_name = xasprintf("%s/%s", cwd, file_name);
521             free(cwd);
522             return abs_name;
523         } else {
524             return NULL;
525         }
526     }
527 }
528
529
530 /* Pass a value to this function if it is marked with
531  * __attribute__((warn_unused_result)) and you genuinely want to ignore
532  * its return value.  (Note that every scalar type can be implicitly
533  * converted to bool.) */
534 void ignore(bool x OVS_UNUSED) { }