xref: /openbsd/usr.bin/file/magic-common.c (revision 09467b48)
1 /* $OpenBSD: magic-common.c,v 1.3 2015/08/11 22:29:25 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2015 Nicholas Marriott <nicm@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include <ctype.h>
22 #include <errno.h>
23 #include <limits.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 
29 #include "magic.h"
30 
31 char *
32 magic_strtoull(const char *s, uint64_t *u)
33 {
34 	char	*endptr;
35 
36 	if (*s == '-' || *s == '\0')
37 		return (NULL);
38 
39 	errno = 0;
40 	*u = strtoull(s, &endptr, 0);
41 	if (endptr == s)
42 		*u = strtoull(s, &endptr, 16);
43 	if (errno == ERANGE && *u == ULLONG_MAX)
44 		return (NULL);
45 	if (*endptr == 'L')
46 		endptr++;
47 	return (endptr);
48 }
49 
50 char *
51 magic_strtoll(const char *s, int64_t *i)
52 {
53 	char	*endptr;
54 
55 	if (*s == '\0')
56 		return (NULL);
57 
58 	errno = 0;
59 	*i = strtoll(s, &endptr, 0);
60 	if (endptr == s)
61 		*i = strtoll(s, &endptr, 16);
62 	if (errno == ERANGE && *i == LLONG_MAX)
63 		return (NULL);
64 	if (*endptr == 'L')
65 		endptr++;
66 	return (endptr);
67 }
68 
69 void
70 magic_vwarnm(struct magic *m, u_int line, const char *fmt, va_list ap)
71 {
72 	char	*msg;
73 
74 	if (!m->warnings)
75 		return;
76 
77 	if (vasprintf(&msg, fmt, ap) == -1)
78 		return;
79 	fprintf(stderr, "%s:%u: %s\n", m->path, line, msg);
80 	free(msg);
81 }
82 
83 void
84 magic_warnm(struct magic *m, u_int line, const char *fmt, ...)
85 {
86 	va_list	 ap;
87 
88 	va_start(ap, fmt);
89 	magic_vwarnm (m, line, fmt, ap);
90 	va_end(ap);
91 }
92 
93 void
94 magic_warn(struct magic_line *ml, const char *fmt, ...)
95 {
96 	va_list	 ap;
97 
98 	va_start(ap, fmt);
99 	magic_vwarnm (ml->root, ml->line, fmt, ap);
100 	va_end(ap);
101 }
102