1/*	$NetBSD$	*/
2
3/*
4 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (c) 2001 by Internet Software Consortium.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
17 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20#include <port_before.h>
21#include <ctype.h>
22#include <stdio.h>
23#include <string.h>
24#include <isc/misc.h>
25#include <port_after.h>
26
27static const char hex[17] = "0123456789abcdef";
28
29int
30isc_gethexstring(unsigned char *buf, size_t len, int count, FILE *fp,
31		 int *multiline)
32{
33	int c, n;
34	unsigned char x;
35	char *s;
36	int result = count;
37
38	x = 0; /*%< silence compiler */
39	n = 0;
40	while (count > 0) {
41		c = fgetc(fp);
42
43		if ((c == EOF) ||
44		    (c == '\n' && !*multiline) ||
45		    (c == '(' && *multiline) ||
46		    (c == ')' && !*multiline))
47			goto formerr;
48		/* comment */
49		if (c == ';') {
50			do {
51				c = fgetc(fp);
52			} while (c != EOF && c != '\n');
53			if (c == '\n' && *multiline)
54				continue;
55			goto formerr;
56		}
57		/* white space */
58		if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
59			continue;
60		/* multiline */
61		if ('(' == c || c == ')') {
62			*multiline = (c == '(' /*)*/);
63			continue;
64		}
65		if ((s = strchr(hex, tolower(c))) == NULL)
66			goto formerr;
67		x = (x<<4) | (s - hex);
68		if (++n == 2) {
69			if (len > 0U) {
70				*buf++ = x;
71				len--;
72			} else
73				result = -1;
74			count--;
75			n = 0;
76		}
77	}
78	return (result);
79
80 formerr:
81	if (c == '\n')
82		ungetc(c, fp);
83	return (-1);
84}
85
86void
87isc_puthexstring(FILE *fp, const unsigned char *buf, size_t buflen,
88		 size_t len1, size_t len2, const char *sep)
89{
90	size_t i = 0;
91
92	if (len1 < 4U)
93		len1 = 4;
94	if (len2 < 4U)
95		len2 = 4;
96	while (buflen > 0U) {
97		fputc(hex[(buf[0]>>4)&0xf], fp);
98		fputc(hex[buf[0]&0xf], fp);
99		i += 2;
100		buflen--;
101		buf++;
102		if (i >= len1 && sep != NULL) {
103			fputs(sep, fp);
104			i = 0;
105			len1 = len2;
106		}
107	}
108}
109
110void
111isc_tohex(const unsigned char *buf, size_t buflen, char *t) {
112	while (buflen > 0U) {
113		*t++ = hex[(buf[0]>>4)&0xf];
114		*t++ = hex[buf[0]&0xf];
115		buf++;
116		buflen--;
117	}
118	*t = '\0';
119}
120
121/*! \file */
122