1 /*
2  * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 2001-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /* $Id: parseint.c,v 1.8 2007/06/19 23:47:17 tbox Exp $ */
19 
20 /*! \file */
21 
22 #include <config.h>
23 
24 #include <ctype.h>
25 #include <errno.h>
26 #include <limits.h>
27 
28 #include <isc/parseint.h>
29 #include <isc/result.h>
30 #include <isc/stdlib.h>
31 
32 isc_result_t
isc_parse_uint32(isc_uint32_t * uip,const char * string,int base)33 isc_parse_uint32(isc_uint32_t *uip, const char *string, int base) {
34 	unsigned long n;
35 	isc_uint32_t r;
36 	char *e;
37 	if (! isalnum((unsigned char)(string[0])))
38 		return (ISC_R_BADNUMBER);
39 	errno = 0;
40 	n = strtoul(string, &e, base);
41 	if (*e != '\0')
42 		return (ISC_R_BADNUMBER);
43 	/*
44 	 * Where long is 64 bits we need to convert to 32 bits then test for
45 	 * equality.  This is a no-op on 32 bit machines and a good compiler
46 	 * will optimise it away.
47 	 */
48 	r = (isc_uint32_t)n;
49 	if ((n == ULONG_MAX && errno == ERANGE) || (n != (unsigned long)r))
50 		return (ISC_R_RANGE);
51 	*uip = r;
52 	return (ISC_R_SUCCESS);
53 }
54 
55 isc_result_t
isc_parse_uint16(isc_uint16_t * uip,const char * string,int base)56 isc_parse_uint16(isc_uint16_t *uip, const char *string, int base) {
57 	isc_uint32_t val;
58 	isc_result_t result;
59 	result = isc_parse_uint32(&val, string, base);
60 	if (result != ISC_R_SUCCESS)
61 		return (result);
62 	if (val > 0xFFFF)
63 		return (ISC_R_RANGE);
64 	*uip = (isc_uint16_t) val;
65 	return (ISC_R_SUCCESS);
66 }
67 
68 isc_result_t
isc_parse_uint8(isc_uint8_t * uip,const char * string,int base)69 isc_parse_uint8(isc_uint8_t *uip, const char *string, int base) {
70 	isc_uint32_t val;
71 	isc_result_t result;
72 	result = isc_parse_uint32(&val, string, base);
73 	if (result != ISC_R_SUCCESS)
74 		return (result);
75 	if (val > 0xFF)
76 		return (ISC_R_RANGE);
77 	*uip = (isc_uint8_t) val;
78 	return (ISC_R_SUCCESS);
79 }
80