xref: /freebsd/contrib/ldns/util.c (revision 9ed998a81bab54203604d08293089db875758686)
1 /*
2  * util.c
3  *
4  * some general memory functions
5  *
6  * a Net::DNS like library for C
7  *
8  * (c) NLnet Labs, 2004-2006
9  *
10  * See the file LICENSE for the license
11  */
12 
13 #include <ldns/config.h>
14 
15 #include <ldns/rdata.h>
16 #include <ldns/rr.h>
17 #include <ldns/util.h>
18 #include <strings.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <sys/time.h>
22 #include <time.h>
23 #include <ctype.h>
24 
25 #ifdef HAVE_SSL
26 #include <openssl/rand.h>
27 #endif
28 
29 ldns_lookup_table *
ldns_lookup_by_name(ldns_lookup_table * table,const char * name)30 ldns_lookup_by_name(ldns_lookup_table *table, const char *name)
31 {
32 	while (table->name != NULL) {
33 		if (strcasecmp(name, table->name) == 0)
34 			return table;
35 		table++;
36 	}
37 	return NULL;
38 }
39 
40 ldns_lookup_table *
ldns_lookup_by_id(ldns_lookup_table * table,int id)41 ldns_lookup_by_id(ldns_lookup_table *table, int id)
42 {
43 	while (table->name != NULL) {
44 		if (table->id == id)
45 			return table;
46 		table++;
47 	}
48 	return NULL;
49 }
50 
51 int
ldns_get_bit(uint8_t bits[],size_t index)52 ldns_get_bit(uint8_t bits[], size_t index)
53 {
54 	/*
55 	 * The bits are counted from left to right, so bit #0 is the
56 	 * left most bit.
57 	 */
58 	return (int) (bits[index / 8] & (1 << (7 - index % 8)));
59 }
60 
61 int
ldns_get_bit_r(uint8_t bits[],size_t index)62 ldns_get_bit_r(uint8_t bits[], size_t index)
63 {
64 	/*
65 	 * The bits are counted from right to left, so bit #0 is the
66 	 * right most bit.
67 	 */
68 	return (int) bits[index / 8] & (1 << (index % 8));
69 }
70 
71 void
ldns_set_bit(uint8_t * byte,int bit_nr,bool value)72 ldns_set_bit(uint8_t *byte, int bit_nr, bool value)
73 {
74 	/*
75 	 * The bits are counted from right to left, so bit #0 is the
76 	 * right most bit.
77 	 */
78 	if (bit_nr >= 0 && bit_nr < 8) {
79 		if (value) {
80 			*byte = *byte | (0x01 << bit_nr);
81 		} else {
82 			*byte = *byte & ~(0x01 << bit_nr);
83 		}
84 	}
85 }
86 
87 int
ldns_hexdigit_to_int(char ch)88 ldns_hexdigit_to_int(char ch)
89 {
90 	switch (ch) {
91 	case '0': return 0;
92 	case '1': return 1;
93 	case '2': return 2;
94 	case '3': return 3;
95 	case '4': return 4;
96 	case '5': return 5;
97 	case '6': return 6;
98 	case '7': return 7;
99 	case '8': return 8;
100 	case '9': return 9;
101 	case 'a': case 'A': return 10;
102 	case 'b': case 'B': return 11;
103 	case 'c': case 'C': return 12;
104 	case 'd': case 'D': return 13;
105 	case 'e': case 'E': return 14;
106 	case 'f': case 'F': return 15;
107 	default:
108 		return -1;
109 	}
110 }
111 
112 char
ldns_int_to_hexdigit(int i)113 ldns_int_to_hexdigit(int i)
114 {
115 	switch (i) {
116 	case 0: return '0';
117 	case 1: return '1';
118 	case 2: return '2';
119 	case 3: return '3';
120 	case 4: return '4';
121 	case 5: return '5';
122 	case 6: return '6';
123 	case 7: return '7';
124 	case 8: return '8';
125 	case 9: return '9';
126 	case 10: return 'a';
127 	case 11: return 'b';
128 	case 12: return 'c';
129 	case 13: return 'd';
130 	case 14: return 'e';
131 	case 15: return 'f';
132 	default:
133 		abort();
134 	}
135 }
136 
137 int
ldns_hexstring_to_data(uint8_t * data,const char * str)138 ldns_hexstring_to_data(uint8_t *data, const char *str)
139 {
140 	size_t i;
141 
142 	if (!str || !data) {
143 		return -1;
144 	}
145 
146 	if (strlen(str) % 2 != 0) {
147 		return -2;
148 	}
149 
150 	for (i = 0; i < strlen(str) / 2; i++) {
151 		data[i] =
152 			16 * (uint8_t) ldns_hexdigit_to_int(str[i*2]) +
153 			(uint8_t) ldns_hexdigit_to_int(str[i*2 + 1]);
154 	}
155 
156 	return (int) i;
157 }
158 
159 const char *
ldns_version(void)160 ldns_version(void)
161 {
162 	return (char*)LDNS_VERSION;
163 }
164 
165 /* Number of days per month (except for February in leap years). */
166 static const int mdays[] = {
167 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
168 };
169 
170 #define LDNS_MOD(x,y) (((x) % (y) < 0) ? ((x) % (y) + (y)) : ((x) % (y)))
171 #define LDNS_DIV(x,y) (((x) % (y) < 0) ? ((x) / (y) -  1 ) : ((x) / (y)))
172 
173 static int
is_leap_year(int year)174 is_leap_year(int year)
175 {
176 	return LDNS_MOD(year,   4) == 0 && (LDNS_MOD(year, 100) != 0
177 	    || LDNS_MOD(year, 400) == 0);
178 }
179 
180 static int
leap_days(int y1,int y2)181 leap_days(int y1, int y2)
182 {
183 	--y1;
184 	--y2;
185 	return (LDNS_DIV(y2,   4) - LDNS_DIV(y1,   4)) -
186 	       (LDNS_DIV(y2, 100) - LDNS_DIV(y1, 100)) +
187 	       (LDNS_DIV(y2, 400) - LDNS_DIV(y1, 400));
188 }
189 
190 /*
191  * Code adapted from Python 2.4.1 sources (Lib/calendar.py).
192  */
193 time_t
ldns_mktime_from_utc(const struct tm * tm)194 ldns_mktime_from_utc(const struct tm *tm)
195 {
196 	int year = 1900 + tm->tm_year;
197 	time_t days = 365 * ((time_t) year - 1970) + leap_days(1970, year);
198 	time_t hours;
199 	time_t minutes;
200 	time_t seconds;
201 	int i;
202 
203 	for (i = 0; i < tm->tm_mon; ++i) {
204 		days += mdays[i];
205 	}
206 	if (tm->tm_mon > 1 && is_leap_year(year)) {
207 		++days;
208 	}
209 	days += tm->tm_mday - 1;
210 
211 	hours = days * 24 + tm->tm_hour;
212 	minutes = hours * 60 + tm->tm_min;
213 	seconds = minutes * 60 + tm->tm_sec;
214 
215 	return seconds;
216 }
217 
218 time_t
mktime_from_utc(const struct tm * tm)219 mktime_from_utc(const struct tm *tm)
220 {
221 	return ldns_mktime_from_utc(tm);
222 }
223 
224 #if SIZEOF_TIME_T <= 4
225 
226 static void
ldns_year_and_yday_from_days_since_epoch(int64_t days,struct tm * result)227 ldns_year_and_yday_from_days_since_epoch(int64_t days, struct tm *result)
228 {
229 	int year = 1970;
230 	int new_year;
231 
232 	while (days < 0 || days >= (int64_t) (is_leap_year(year) ? 366 : 365)) {
233 		new_year = year + (int) LDNS_DIV(days, 365);
234 		days -= (new_year - year) * 365;
235 		days -= leap_days(year, new_year);
236 		year  = new_year;
237 	}
238 	result->tm_year = year;
239 	result->tm_yday = (int) days;
240 }
241 
242 /* Number of days per month in a leap year. */
243 static const int leap_year_mdays[] = {
244 	31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
245 };
246 
247 static void
ldns_mon_and_mday_from_year_and_yday(struct tm * result)248 ldns_mon_and_mday_from_year_and_yday(struct tm *result)
249 {
250 	int idays = result->tm_yday;
251 	const int *mon_lengths = is_leap_year(result->tm_year) ?
252 					leap_year_mdays : mdays;
253 
254 	result->tm_mon = 0;
255 	while  (idays >= mon_lengths[result->tm_mon]) {
256 		idays -= mon_lengths[result->tm_mon++];
257 	}
258 	result->tm_mday = idays + 1;
259 }
260 
261 static void
ldns_wday_from_year_and_yday(struct tm * result)262 ldns_wday_from_year_and_yday(struct tm *result)
263 {
264 	result->tm_wday = 4 /* 1-1-1970 was a thursday */
265 			+ LDNS_MOD((result->tm_year - 1970), 7) * LDNS_MOD(365, 7)
266 			+ leap_days(1970, result->tm_year)
267 			+ result->tm_yday;
268 	result->tm_wday = LDNS_MOD(result->tm_wday, 7);
269 	if (result->tm_wday < 0) {
270 		result->tm_wday += 7;
271 	}
272 }
273 
274 static struct tm *
ldns_gmtime64_r(int64_t clock,struct tm * result)275 ldns_gmtime64_r(int64_t clock, struct tm *result)
276 {
277 	result->tm_isdst = 0;
278 	result->tm_sec   = (int) LDNS_MOD(clock, 60);
279 	clock            =       LDNS_DIV(clock, 60);
280 	result->tm_min   = (int) LDNS_MOD(clock, 60);
281 	clock            =       LDNS_DIV(clock, 60);
282 	result->tm_hour  = (int) LDNS_MOD(clock, 24);
283 	clock            =       LDNS_DIV(clock, 24);
284 
285 	ldns_year_and_yday_from_days_since_epoch(clock, result);
286 	ldns_mon_and_mday_from_year_and_yday(result);
287 	ldns_wday_from_year_and_yday(result);
288 	result->tm_year -= 1900;
289 
290 	return result;
291 }
292 
293 #endif /* SIZEOF_TIME_T <= 4 */
294 
295 static int64_t
ldns_serial_arithmetics_time(int32_t time,time_t now)296 ldns_serial_arithmetics_time(int32_t time, time_t now)
297 {
298 	/* Casting due to https://github.com/NLnetLabs/ldns/issues/71 */
299 	int32_t offset = (int32_t) ((uint32_t) time - (uint32_t) now);
300 	return (int64_t) now + offset;
301 }
302 
303 struct tm *
ldns_serial_arithmetics_gmtime_r(int32_t time,time_t now,struct tm * result)304 ldns_serial_arithmetics_gmtime_r(int32_t time, time_t now, struct tm *result)
305 {
306 #if SIZEOF_TIME_T <= 4
307 	int64_t secs_since_epoch = ldns_serial_arithmetics_time(time, now);
308 	return  ldns_gmtime64_r(secs_since_epoch, result);
309 #else
310 	time_t  secs_since_epoch = ldns_serial_arithmetics_time(time, now);
311 	return  gmtime_r(&secs_since_epoch, result);
312 #endif
313 }
314 
315 #ifdef ldns_serial_arithmitics_gmtime_r
316 #undef ldns_serial_arithmitics_gmtime_r
317 #endif
318 /* alias function because of previously used wrong spelling */
319 struct tm *ldns_serial_arithmitics_gmtime_r(int32_t, time_t, struct tm *);
320 struct tm *
321 ldns_serial_arithmitics_gmtime_r(int32_t time, time_t now, struct tm *result);
322 struct tm *
ldns_serial_arithmitics_gmtime_r(int32_t time,time_t now,struct tm * result)323 ldns_serial_arithmitics_gmtime_r(int32_t time, time_t now, struct tm *result)
324 {
325 	return ldns_serial_arithmetics_gmtime_r(time, now, result);
326 }
327 
328 /**
329  * Init the random source
330  * applications should call this if they need entropy data within ldns
331  * If openSSL is available, it is automatically seeded from /dev/urandom
332  * or /dev/random
333  *
334  * If you need more entropy, or have no openssl available, this function
335  * MUST be called at the start of the program
336  *
337  * If openssl *is* available, this function just adds more entropy
338  **/
339 int
ldns_init_random(FILE * fd,unsigned int size)340 ldns_init_random(FILE *fd, unsigned int size)
341 {
342 	/* if fp is given, seed srandom with data from file
343 	   otherwise use /dev/urandom */
344 	FILE *rand_f;
345 	uint8_t *seed;
346 	size_t read = 0;
347 	unsigned int seed_i;
348 	struct timeval tv;
349 
350 #ifdef HAVE_SSL
351 	if(RAND_status() == 1)
352 		/* already seeded */
353 		return 0;
354 #endif
355 	/* we'll need at least sizeof(unsigned int) bytes for the
356 	   standard prng seed */
357 	if (size < (unsigned int) sizeof(seed_i)){
358 		size = (unsigned int) sizeof(seed_i);
359 	}
360 
361 	seed = LDNS_XMALLOC(uint8_t, size);
362         if(!seed) {
363 		return 1;
364         }
365 
366 	if (!fd) {
367 		if ((rand_f = fopen("/dev/urandom", "r")) == NULL) {
368 			/* no readable /dev/urandom, try /dev/random */
369 			if ((rand_f = fopen("/dev/random", "r")) == NULL) {
370 				/* no readable /dev/random either, and no entropy
371 				   source given. we'll have to improvise */
372 				for (read = 0; read < size; read++) {
373 					gettimeofday(&tv, NULL);
374 					seed[read] = (uint8_t) (tv.tv_usec % 256);
375 				}
376 			} else {
377 				read = fread(seed, 1, size, rand_f);
378 			}
379 		} else {
380 			read = fread(seed, 1, size, rand_f);
381 		}
382 	} else {
383 		rand_f = fd;
384 		read = fread(seed, 1, size, rand_f);
385 	}
386 
387 	if (read < size) {
388 		LDNS_FREE(seed);
389 		if (!fd) fclose(rand_f);
390 		return 1;
391 	} else {
392 #ifdef HAVE_SSL
393 		/* Seed the OpenSSL prng (most systems have it seeded
394 		   automatically, in that case this call just adds entropy */
395 		RAND_seed(seed, (int) size);
396 #else
397 		/* Seed the standard prng, only uses the first
398 		 * unsigned sizeof(unsigned int) bytes found in the entropy pool
399 		 */
400 		memcpy(&seed_i, seed, sizeof(seed_i));
401 		srandom(seed_i);
402 #endif
403 		LDNS_FREE(seed);
404 	}
405 
406 	if (!fd) {
407                 if (rand_f) fclose(rand_f);
408 	}
409 
410 	return 0;
411 }
412 
413 /**
414  * Get random number.
415  *
416  */
417 uint16_t
ldns_get_random(void)418 ldns_get_random(void)
419 {
420         uint16_t rid = 0;
421 #ifdef HAVE_SSL
422         if (RAND_bytes((unsigned char*)&rid, 2) != 1) {
423                 rid = (uint16_t) random();
424         }
425 #else
426         rid = (uint16_t) random();
427 #endif
428 	return rid;
429 }
430 
431 /*
432  * BubbleBabble code taken from OpenSSH
433  * Copyright (c) 2001 Carsten Raskgaard.  All rights reserved.
434  */
435 char *
ldns_bubblebabble(uint8_t * data,size_t len)436 ldns_bubblebabble(uint8_t *data, size_t len)
437 {
438 	char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'y' };
439 	char consonants[] = { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm',
440 	    'n', 'p', 'r', 's', 't', 'v', 'z', 'x' };
441 	size_t i, j = 0, rounds, seed = 1;
442 	char *retval;
443 
444 	rounds = (len / 2) + 1;
445 	retval = LDNS_XMALLOC(char, rounds * 6);
446 	if(!retval) return NULL;
447 	retval[j++] = 'x';
448 	for (i = 0; i < rounds; i++) {
449 		size_t idx0, idx1, idx2, idx3, idx4;
450 		if ((i + 1 < rounds) || (len % 2 != 0)) {
451 			idx0 = (((((size_t)(data[2 * i])) >> 6) & 3) +
452 			    seed) % 6;
453 			idx1 = (((size_t)(data[2 * i])) >> 2) & 15;
454 			idx2 = ((((size_t)(data[2 * i])) & 3) +
455 			    (seed / 6)) % 6;
456 			retval[j++] = vowels[idx0];
457 			retval[j++] = consonants[idx1];
458 			retval[j++] = vowels[idx2];
459 			if ((i + 1) < rounds) {
460 				idx3 = (((size_t)(data[(2 * i) + 1])) >> 4) & 15;
461 				idx4 = (((size_t)(data[(2 * i) + 1]))) & 15;
462 				retval[j++] = consonants[idx3];
463 				retval[j++] = '-';
464 				retval[j++] = consonants[idx4];
465 				seed = ((seed * 5) +
466 				    ((((size_t)(data[2 * i])) * 7) +
467 				    ((size_t)(data[(2 * i) + 1])))) % 36;
468 			}
469 		} else {
470 			idx0 = seed % 6;
471 			idx1 = 16;
472 			idx2 = seed / 6;
473 			retval[j++] = vowels[idx0];
474 			retval[j++] = consonants[idx1];
475 			retval[j++] = vowels[idx2];
476 		}
477 	}
478 	retval[j++] = 'x';
479 	retval[j++] = '\0';
480 	return retval;
481 }
482 
483 /*
484  * For backwards compatibility, because we have always exported this symbol.
485  */
486 #ifdef HAVE_B64_NTOP
487 int ldns_b64_ntop(const uint8_t* src, size_t srclength,
488 		char *target, size_t targsize);
489 {
490 	return b64_ntop(src, srclength, target, targsize);
491 }
492 #endif
493 
494 /*
495  * For backwards compatibility, because we have always exported this symbol.
496  */
497 #ifdef HAVE_B64_PTON
ldns_b64_pton(const char * src,uint8_t * target,size_t targsize)498 int ldns_b64_pton(const char* src, uint8_t *target, size_t targsize)
499 {
500 	return b64_pton(src, target, targsize);
501 }
502 #endif
503 
504 
505 static int
ldns_b32_ntop_base(const uint8_t * src,size_t src_sz,char * dst,size_t dst_sz,bool extended_hex,bool add_padding)506 ldns_b32_ntop_base(const uint8_t* src, size_t src_sz,
507 		char* dst, size_t dst_sz,
508 		bool extended_hex, bool add_padding)
509 {
510 	size_t ret_sz;
511 	const char* b32 = extended_hex ? "0123456789abcdefghijklmnopqrstuv"
512 	                               : "abcdefghijklmnopqrstuvwxyz234567";
513 
514 	size_t c = 0; /* c is used to carry partial base32 character over
515 	               * byte boundaries for sizes with a remainder.
516 		       * (i.e. src_sz % 5 != 0)
517 		       */
518 
519 	ret_sz = add_padding ? ldns_b32_ntop_calculate_size(src_sz)
520 	                     : ldns_b32_ntop_calculate_size_no_padding(src_sz);
521 
522 	/* Do we have enough space? */
523 	if (dst_sz < ret_sz + 1)
524 		return -1;
525 
526 	/* We know the size; terminate the string */
527 	dst[ret_sz] = '\0';
528 
529 	/* First process all chunks of five */
530 	while (src_sz >= 5) {
531 		/* 00000... ........ ........ ........ ........ */
532 		dst[0] = b32[(src[0]       ) >> 3];
533 
534 		/* .....111 11...... ........ ........ ........ */
535 		dst[1] = b32[(src[0] & 0x07) << 2 | src[1] >> 6];
536 
537 		/* ........ ..22222. ........ ........ ........ */
538 		dst[2] = b32[(src[1] & 0x3e) >> 1];
539 
540 		/* ........ .......3 3333.... ........ ........ */
541 		dst[3] = b32[(src[1] & 0x01) << 4 | src[2] >> 4];
542 
543 		/* ........ ........ ....4444 4....... ........ */
544 		dst[4] = b32[(src[2] & 0x0f) << 1 | src[3] >> 7];
545 
546 		/* ........ ........ ........ .55555.. ........ */
547 		dst[5] = b32[(src[3] & 0x7c) >> 2];
548 
549 		/* ........ ........ ........ ......66 666..... */
550 		dst[6] = b32[(src[3] & 0x03) << 3 | src[4] >> 5];
551 
552 		/* ........ ........ ........ ........ ...77777 */
553 		dst[7] = b32[(src[4] & 0x1f)     ];
554 
555 		src_sz -= 5;
556 		src    += 5;
557 		dst    += 8;
558 	}
559 	/* Process what remains */
560 	switch (src_sz) {
561 	case 4: /* ........ ........ ........ ......66 666..... */
562 		dst[6] = b32[(src[3] & 0x03) << 3];
563 
564 		/* ........ ........ ........ .55555.. ........ */
565 		dst[5] = b32[(src[3] & 0x7c) >> 2];
566 
567 		/* ........ ........ ....4444 4....... ........ */
568 		         c =  src[3]         >> 7 ;
569 		/* fallthrough */
570 	case 3: dst[4] = b32[(src[2] & 0x0f) << 1 | c];
571 
572 		/* ........ .......3 3333.... ........ ........ */
573 			 c =  src[2]         >> 4 ;
574 		/* fallthrough */
575 	case 2:	dst[3] = b32[(src[1] & 0x01) << 4 | c];
576 
577 		/* ........ ..22222. ........ ........ ........ */
578 		dst[2] = b32[(src[1] & 0x3e) >> 1];
579 
580 		/* .....111 11...... ........ ........ ........ */
581 	                 c =  src[1]         >> 6 ;
582 		/* fallthrough */
583 	case 1:	dst[1] = b32[(src[0] & 0x07) << 2 | c];
584 
585 		/* 00000... ........ ........ ........ ........ */
586 		dst[0] = b32[ src[0]         >> 3];
587 	}
588 	/* Add padding */
589 	if (add_padding) {
590 		switch (src_sz) {
591 			case 1: dst[2] = '=';
592 				dst[3] = '=';
593 				/* fallthrough */
594 			case 2: dst[4] = '=';
595 				/* fallthrough */
596 			case 3: dst[5] = '=';
597 				dst[6] = '=';
598 				/* fallthrough */
599 			case 4: dst[7] = '=';
600 		}
601 	}
602 	return (int)ret_sz;
603 }
604 
605 int
ldns_b32_ntop(const uint8_t * src,size_t src_sz,char * dst,size_t dst_sz)606 ldns_b32_ntop(const uint8_t* src, size_t src_sz, char* dst, size_t dst_sz)
607 {
608 	return ldns_b32_ntop_base(src, src_sz, dst, dst_sz, false, true);
609 }
610 
611 int
ldns_b32_ntop_extended_hex(const uint8_t * src,size_t src_sz,char * dst,size_t dst_sz)612 ldns_b32_ntop_extended_hex(const uint8_t* src, size_t src_sz,
613 		char* dst, size_t dst_sz)
614 {
615 	return ldns_b32_ntop_base(src, src_sz, dst, dst_sz, true, true);
616 }
617 
618 #ifndef HAVE_B32_NTOP
619 
620 int
b32_ntop(const uint8_t * src,size_t src_sz,char * dst,size_t dst_sz)621 b32_ntop(const uint8_t* src, size_t src_sz, char* dst, size_t dst_sz)
622 {
623 	return ldns_b32_ntop_base(src, src_sz, dst, dst_sz, false, true);
624 }
625 
626 int
b32_ntop_extended_hex(const uint8_t * src,size_t src_sz,char * dst,size_t dst_sz)627 b32_ntop_extended_hex(const uint8_t* src, size_t src_sz,
628 		char* dst, size_t dst_sz)
629 {
630 	return ldns_b32_ntop_base(src, src_sz, dst, dst_sz, true, true);
631 }
632 
633 #endif /* ! HAVE_B32_NTOP */
634 
635 static int
ldns_b32_pton_base(const char * src,size_t src_sz,uint8_t * dst,size_t dst_sz,bool extended_hex,bool check_padding)636 ldns_b32_pton_base(const char* src, size_t src_sz,
637 		uint8_t* dst, size_t dst_sz,
638 		bool extended_hex, bool check_padding)
639 {
640 	size_t i = 0;
641 	char ch = '\0';
642 	uint8_t buf[8];
643 	uint8_t* start = dst;
644 
645 	while (src_sz) {
646 		/* Collect 8 characters in buf (if possible) */
647 		for (i = 0; i < 8; i++) {
648 
649 			do {
650 				ch = *src++;
651 				--src_sz;
652 
653 			} while (isspace((unsigned char)ch) && src_sz > 0);
654 
655 			if (ch == '=' || ch == '\0')
656 				break;
657 
658 			else if (extended_hex)
659 
660 				if (ch >= '0' && ch <= '9')
661 					buf[i] = (uint8_t)ch - '0';
662 				else if (ch >= 'a' && ch <= 'v')
663 					buf[i] = (uint8_t)ch - 'a' + 10;
664 				else if (ch >= 'A' && ch <= 'V')
665 					buf[i] = (uint8_t)ch - 'A' + 10;
666 				else
667 					return -1;
668 
669 			else if (ch >= 'a' && ch <= 'z')
670 				buf[i] = (uint8_t)ch - 'a';
671 			else if (ch >= 'A' && ch <= 'Z')
672 				buf[i] = (uint8_t)ch - 'A';
673 			else if (ch >= '2' && ch <= '7')
674 				buf[i] = (uint8_t)ch - '2' + 26;
675 			else
676 				return -1;
677 		}
678 		/* Less that 8 characters. We're done. */
679 		if (i < 8)
680 			break;
681 
682 		/* Enough space available at the destination? */
683 		if (dst_sz < 5)
684 			return -1;
685 
686 		/* 00000... ........ ........ ........ ........ */
687 		/* .....111 11...... ........ ........ ........ */
688 		dst[0] = buf[0] << 3 | buf[1] >> 2;
689 
690 		/* .....111 11...... ........ ........ ........ */
691 		/* ........ ..22222. ........ ........ ........ */
692 		/* ........ .......3 3333.... ........ ........ */
693 		dst[1] = buf[1] << 6 | buf[2] << 1 | buf[3] >> 4;
694 
695 		/* ........ .......3 3333.... ........ ........ */
696 		/* ........ ........ ....4444 4....... ........ */
697 		dst[2] = buf[3] << 4 | buf[4] >> 1;
698 
699 		/* ........ ........ ....4444 4....... ........ */
700 		/* ........ ........ ........ .55555.. ........ */
701 		/* ........ ........ ........ ......66 666..... */
702 		dst[3] = buf[4] << 7 | buf[5] << 2 | buf[6] >> 3;
703 
704 		/* ........ ........ ........ ......66 666..... */
705 		/* ........ ........ ........ ........ ...77777 */
706 		dst[4] = buf[6] << 5 | buf[7];
707 
708 		dst += 5;
709 		dst_sz -= 5;
710 	}
711 	/* Not ending on a eight byte boundary? */
712 	if (i > 0 && i < 8) {
713 
714 		/* Enough space available at the destination? */
715 		if (dst_sz < (i + 1) / 2)
716 			return -1;
717 
718 		switch (i) {
719 		case 7: /* ........ ........ ........ ......66 666..... */
720 			/* ........ ........ ........ .55555.. ........ */
721 			/* ........ ........ ....4444 4....... ........ */
722 			dst[3] = buf[4] << 7 | buf[5] << 2 | buf[6] >> 3;
723 			/* fallthrough */
724 
725 		case 5: /* ........ ........ ....4444 4....... ........ */
726 			/* ........ .......3 3333.... ........ ........ */
727 			dst[2] = buf[3] << 4 | buf[4] >> 1;
728 			/* fallthrough */
729 
730 		case 4: /* ........ .......3 3333.... ........ ........ */
731 			/* ........ ..22222. ........ ........ ........ */
732 			/* .....111 11...... ........ ........ ........ */
733 			dst[1] = buf[1] << 6 | buf[2] << 1 | buf[3] >> 4;
734 			/* fallthrough */
735 
736 		case 2: /* .....111 11...... ........ ........ ........ */
737 			/* 00000... ........ ........ ........ ........ */
738 			dst[0] = buf[0] << 3 | buf[1] >> 2;
739 
740 			break;
741 
742 		default:
743 			return -1;
744 		}
745 		dst += (i + 1) / 2;
746 
747 		if (check_padding) {
748 			/* Check remaining padding characters */
749 			if (ch != '=')
750 				return -1;
751 
752 			/* One down, 8 - i - 1 more to come... */
753 			for (i = 8 - i - 1; i > 0; i--) {
754 
755 				do {
756 					if (src_sz == 0)
757 						return -1;
758 					ch = *src++;
759 					src_sz--;
760 
761 				} while (isspace((unsigned char)ch));
762 
763 				if (ch != '=')
764 					return -1;
765 			}
766 		}
767 	}
768 	return dst - start;
769 }
770 
771 int
ldns_b32_pton(const char * src,size_t src_sz,uint8_t * dst,size_t dst_sz)772 ldns_b32_pton(const char* src, size_t src_sz, uint8_t* dst, size_t dst_sz)
773 {
774 	return ldns_b32_pton_base(src, src_sz, dst, dst_sz, false, true);
775 }
776 
777 int
ldns_b32_pton_extended_hex(const char * src,size_t src_sz,uint8_t * dst,size_t dst_sz)778 ldns_b32_pton_extended_hex(const char* src, size_t src_sz,
779 		uint8_t* dst, size_t dst_sz)
780 {
781 	return ldns_b32_pton_base(src, src_sz, dst, dst_sz, true, true);
782 }
783 
784 #ifndef HAVE_B32_PTON
785 
786 int
b32_pton(const char * src,size_t src_sz,uint8_t * dst,size_t dst_sz)787 b32_pton(const char* src, size_t src_sz, uint8_t* dst, size_t dst_sz)
788 {
789 	return ldns_b32_pton_base(src, src_sz, dst, dst_sz, false, true);
790 }
791 
792 int
b32_pton_extended_hex(const char * src,size_t src_sz,uint8_t * dst,size_t dst_sz)793 b32_pton_extended_hex(const char* src, size_t src_sz,
794 		uint8_t* dst, size_t dst_sz)
795 {
796 	return ldns_b32_pton_base(src, src_sz, dst, dst_sz, true, true);
797 }
798 
799 #endif /* ! HAVE_B32_PTON */
800 
801