ptime

Reformat timestamps
git clone git://git.sgregoratto.me/ptime
Log | Files | Refs

compats.c (43526B)


      1 #include "config.h"
      2 #if !HAVE_ERR
      3 /*
      4  * Copyright (c) 1993
      5  *      The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <errno.h>
     33 #include <stdarg.h>
     34 #include <stdio.h>
     35 #include <stdlib.h>
     36 #include <string.h>
     37 
     38 void
     39 vwarnx(const char *fmt, va_list ap)
     40 {
     41 	fprintf(stderr, "%s: ", getprogname());
     42 	if (fmt != NULL)
     43 		vfprintf(stderr, fmt, ap);
     44 }
     45 
     46 void
     47 vwarn(const char *fmt, va_list ap)
     48 {
     49 	int sverrno;
     50 
     51 	sverrno = errno;
     52 	vwarnx(fmt, ap);
     53 	if (fmt != NULL)
     54 		fputs(": ", stderr);
     55 	fprintf(stderr, "%s\n", strerror(sverrno));
     56 }
     57 
     58 void
     59 err(int eval, const char *fmt, ...)
     60 {
     61 	va_list ap;
     62 
     63 	va_start(ap, fmt);
     64 	vwarn(fmt, ap);
     65 	va_end(ap);
     66 	exit(eval);
     67 }
     68 
     69 void
     70 errx(int eval, const char *fmt, ...)
     71 {
     72 	va_list ap;
     73 
     74 	va_start(ap, fmt);
     75 	vwarnx(fmt, ap);
     76 	va_end(ap);
     77 	fputc('\n', stderr);
     78 	exit(eval);
     79 }
     80 
     81 void
     82 warn(const char *fmt, ...)
     83 {
     84 	va_list ap;
     85 
     86 	va_start(ap, fmt);
     87 	vwarn(fmt, ap);
     88 	va_end(ap);
     89 }
     90 
     91 void
     92 warnx(const char *fmt, ...)
     93 {
     94 	va_list ap;
     95 
     96 	va_start(ap, fmt);
     97 	vwarnx(fmt, ap);
     98 	va_end(ap);
     99 	fputc('\n', stderr);
    100 }
    101 #endif /* !HAVE_ERR */
    102 #if !HAVE_B64_NTOP
    103 /*	$OpenBSD$	*/
    104 
    105 /*
    106  * Copyright (c) 1996 by Internet Software Consortium.
    107  *
    108  * Permission to use, copy, modify, and distribute this software for any
    109  * purpose with or without fee is hereby granted, provided that the above
    110  * copyright notice and this permission notice appear in all copies.
    111  *
    112  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
    113  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
    114  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
    115  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
    116  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
    117  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
    118  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
    119  * SOFTWARE.
    120  */
    121 
    122 /*
    123  * Portions Copyright (c) 1995 by International Business Machines, Inc.
    124  *
    125  * International Business Machines, Inc. (hereinafter called IBM) grants
    126  * permission under its copyrights to use, copy, modify, and distribute this
    127  * Software with or without fee, provided that the above copyright notice and
    128  * all paragraphs of this notice appear in all copies, and that the name of IBM
    129  * not be used in connection with the marketing of any product incorporating
    130  * the Software or modifications thereof, without specific, written prior
    131  * permission.
    132  *
    133  * To the extent it has a right to do so, IBM grants an immunity from suit
    134  * under its patents, if any, for the use, sale or manufacture of products to
    135  * the extent that such products are used for performing Domain Name System
    136  * dynamic updates in TCP/IP networks by means of the Software.  No immunity is
    137  * granted for any product per se or for any other function of any product.
    138  *
    139  * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
    140  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    141  * PARTICULAR PURPOSE.  IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
    142  * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
    143  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
    144  * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
    145  */
    146 
    147 #include <sys/types.h>
    148 #include <sys/socket.h>
    149 #include <netinet/in.h>
    150 #include <arpa/inet.h>
    151 #include <arpa/nameser.h>
    152 
    153 #include <ctype.h>
    154 #include <resolv.h>
    155 #include <stdio.h>
    156 
    157 #include <stdlib.h>
    158 #include <string.h>
    159 
    160 static const char b64_Base64[] =
    161 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    162 static const char b64_Pad64 = '=';
    163 
    164 /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
    165    The following encoding technique is taken from RFC 1521 by Borenstein
    166    and Freed.  It is reproduced here in a slightly edited form for
    167    convenience.
    168 
    169    A 65-character subset of US-ASCII is used, enabling 6 bits to be
    170    represented per printable character. (The extra 65th character, "=",
    171    is used to signify a special processing function.)
    172 
    173    The encoding process represents 24-bit groups of input bits as output
    174    strings of 4 encoded characters. Proceeding from left to right, a
    175    24-bit input group is formed by concatenating 3 8-bit input groups.
    176    These 24 bits are then treated as 4 concatenated 6-bit groups, each
    177    of which is translated into a single digit in the base64 alphabet.
    178 
    179    Each 6-bit group is used as an index into an array of 64 printable
    180    characters. The character referenced by the index is placed in the
    181    output string.
    182 
    183                          Table 1: The Base64 Alphabet
    184 
    185       Value Encoding  Value Encoding  Value Encoding  Value Encoding
    186           0 A            17 R            34 i            51 z
    187           1 B            18 S            35 j            52 0
    188           2 C            19 T            36 k            53 1
    189           3 D            20 U            37 l            54 2
    190           4 E            21 V            38 m            55 3
    191           5 F            22 W            39 n            56 4
    192           6 G            23 X            40 o            57 5
    193           7 H            24 Y            41 p            58 6
    194           8 I            25 Z            42 q            59 7
    195           9 J            26 a            43 r            60 8
    196          10 K            27 b            44 s            61 9
    197          11 L            28 c            45 t            62 +
    198          12 M            29 d            46 u            63 /
    199          13 N            30 e            47 v
    200          14 O            31 f            48 w         (pad) =
    201          15 P            32 g            49 x
    202          16 Q            33 h            50 y
    203 
    204    Special processing is performed if fewer than 24 bits are available
    205    at the end of the data being encoded.  A full encoding quantum is
    206    always completed at the end of a quantity.  When fewer than 24 input
    207    bits are available in an input group, zero bits are added (on the
    208    right) to form an integral number of 6-bit groups.  Padding at the
    209    end of the data is performed using the '=' character.
    210 
    211    Since all base64 input is an integral number of octets, only the
    212          -------------------------------------------------                       
    213    following cases can arise:
    214    
    215        (1) the final quantum of encoding input is an integral
    216            multiple of 24 bits; here, the final unit of encoded
    217 	   output will be an integral multiple of 4 characters
    218 	   with no "=" padding,
    219        (2) the final quantum of encoding input is exactly 8 bits;
    220            here, the final unit of encoded output will be two
    221 	   characters followed by two "=" padding characters, or
    222        (3) the final quantum of encoding input is exactly 16 bits;
    223            here, the final unit of encoded output will be three
    224 	   characters followed by one "=" padding character.
    225    */
    226 
    227 int
    228 b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize)
    229 {
    230 	size_t datalength = 0;
    231 	u_char input[3];
    232 	u_char output[4];
    233 	size_t i;
    234 
    235 	while (2 < srclength) {
    236 		input[0] = *src++;
    237 		input[1] = *src++;
    238 		input[2] = *src++;
    239 		srclength -= 3;
    240 
    241 		output[0] = input[0] >> 2;
    242 		output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
    243 		output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
    244 		output[3] = input[2] & 0x3f;
    245 
    246 		if (datalength + 4 > targsize)
    247 			return (-1);
    248 		target[datalength++] = b64_Base64[output[0]];
    249 		target[datalength++] = b64_Base64[output[1]];
    250 		target[datalength++] = b64_Base64[output[2]];
    251 		target[datalength++] = b64_Base64[output[3]];
    252 	}
    253     
    254 	/* Now we worry about padding. */
    255 	if (0 != srclength) {
    256 		/* Get what's left. */
    257 		input[0] = input[1] = input[2] = '\0';
    258 		for (i = 0; i < srclength; i++)
    259 			input[i] = *src++;
    260 	
    261 		output[0] = input[0] >> 2;
    262 		output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
    263 		output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
    264 
    265 		if (datalength + 4 > targsize)
    266 			return (-1);
    267 		target[datalength++] = b64_Base64[output[0]];
    268 		target[datalength++] = b64_Base64[output[1]];
    269 		if (srclength == 1)
    270 			target[datalength++] = b64_Pad64;
    271 		else
    272 			target[datalength++] = b64_Base64[output[2]];
    273 		target[datalength++] = b64_Pad64;
    274 	}
    275 	if (datalength >= targsize)
    276 		return (-1);
    277 	target[datalength] = '\0';	/* Returned value doesn't count \0. */
    278 	return (datalength);
    279 }
    280 
    281 /* skips all whitespace anywhere.
    282    converts characters, four at a time, starting at (or after)
    283    src from base - 64 numbers into three 8 bit bytes in the target area.
    284    it returns the number of data bytes stored at the target, or -1 on error.
    285  */
    286 
    287 int
    288 b64_pton(char const *src, u_char *target, size_t targsize)
    289 {
    290 	int state, ch;
    291 	size_t tarindex;
    292 	u_char nextbyte;
    293 	char *pos;
    294 
    295 	state = 0;
    296 	tarindex = 0;
    297 
    298 	while ((ch = (unsigned char)*src++) != '\0') {
    299 		if (isspace(ch))	/* Skip whitespace anywhere. */
    300 			continue;
    301 
    302 		if (ch == b64_Pad64)
    303 			break;
    304 
    305 		pos = strchr(b64_Base64, ch);
    306 		if (pos == 0) 		/* A non-base64 character. */
    307 			return (-1);
    308 
    309 		switch (state) {
    310 		case 0:
    311 			if (target) {
    312 				if (tarindex >= targsize)
    313 					return (-1);
    314 				target[tarindex] = (pos - b64_Base64) << 2;
    315 			}
    316 			state = 1;
    317 			break;
    318 		case 1:
    319 			if (target) {
    320 				if (tarindex >= targsize)
    321 					return (-1);
    322 				target[tarindex]   |=  (pos - b64_Base64) >> 4;
    323 				nextbyte = ((pos - b64_Base64) & 0x0f) << 4;
    324 				if (tarindex + 1 < targsize)
    325 					target[tarindex+1] = nextbyte;
    326 				else if (nextbyte)
    327 					return (-1);
    328 			}
    329 			tarindex++;
    330 			state = 2;
    331 			break;
    332 		case 2:
    333 			if (target) {
    334 				if (tarindex >= targsize)
    335 					return (-1);
    336 				target[tarindex]   |=  (pos - b64_Base64) >> 2;
    337 				nextbyte = ((pos - b64_Base64) & 0x03) << 6;
    338 				if (tarindex + 1 < targsize)
    339 					target[tarindex+1] = nextbyte;
    340 				else if (nextbyte)
    341 					return (-1);
    342 			}
    343 			tarindex++;
    344 			state = 3;
    345 			break;
    346 		case 3:
    347 			if (target) {
    348 				if (tarindex >= targsize)
    349 					return (-1);
    350 				target[tarindex] |= (pos - b64_Base64);
    351 			}
    352 			tarindex++;
    353 			state = 0;
    354 			break;
    355 		}
    356 	}
    357 
    358 	/*
    359 	 * We are done decoding Base-64 chars.  Let's see if we ended
    360 	 * on a byte boundary, and/or with erroneous trailing characters.
    361 	 */
    362 
    363 	if (ch == b64_Pad64) {			/* We got a pad char. */
    364 		ch = (unsigned char)*src++;	/* Skip it, get next. */
    365 		switch (state) {
    366 		case 0:		/* Invalid = in first position */
    367 		case 1:		/* Invalid = in second position */
    368 			return (-1);
    369 
    370 		case 2:		/* Valid, means one byte of info */
    371 			/* Skip any number of spaces. */
    372 			for (; ch != '\0'; ch = (unsigned char)*src++)
    373 				if (!isspace(ch))
    374 					break;
    375 			/* Make sure there is another trailing = sign. */
    376 			if (ch != b64_Pad64)
    377 				return (-1);
    378 			ch = (unsigned char)*src++;		/* Skip the = */
    379 			/* Fall through to "single trailing =" case. */
    380 			/* FALLTHROUGH */
    381 
    382 		case 3:		/* Valid, means two bytes of info */
    383 			/*
    384 			 * We know this char is an =.  Is there anything but
    385 			 * whitespace after it?
    386 			 */
    387 			for (; ch != '\0'; ch = (unsigned char)*src++)
    388 				if (!isspace(ch))
    389 					return (-1);
    390 
    391 			/*
    392 			 * Now make sure for cases 2 and 3 that the "extra"
    393 			 * bits that slopped past the last full byte were
    394 			 * zeros.  If we don't check them, they become a
    395 			 * subliminal channel.
    396 			 */
    397 			if (target && tarindex < targsize &&
    398 			    target[tarindex] != 0)
    399 				return (-1);
    400 		}
    401 	} else {
    402 		/*
    403 		 * We ended by seeing the end of the string.  Make sure we
    404 		 * have no partial bytes lying around.
    405 		 */
    406 		if (state != 0)
    407 			return (-1);
    408 	}
    409 
    410 	return (tarindex);
    411 }
    412 #endif /* !HAVE_B64_NTOP */
    413 #if !HAVE_EXPLICIT_BZERO
    414 /* OPENBSD ORIGINAL: lib/libc/string/explicit_bzero.c */
    415 /*
    416  * Public domain.
    417  * Written by Ted Unangst
    418  */
    419 
    420 #include <string.h>
    421 
    422 /*
    423  * explicit_bzero - don't let the compiler optimize away bzero
    424  */
    425 
    426 #if HAVE_MEMSET_S
    427 
    428 void
    429 explicit_bzero(void *p, size_t n)
    430 {
    431 	if (n == 0)
    432 		return;
    433 	(void)memset_s(p, n, 0, n);
    434 }
    435 
    436 #else /* HAVE_MEMSET_S */
    437 
    438 /*
    439  * Indirect bzero through a volatile pointer to hopefully avoid
    440  * dead-store optimisation eliminating the call.
    441  */
    442 static void (* volatile ssh_bzero)(void *, size_t) = bzero;
    443 
    444 void
    445 explicit_bzero(void *p, size_t n)
    446 {
    447 	if (n == 0)
    448 		return;
    449 	/*
    450 	 * clang -fsanitize=memory needs to intercept memset-like functions
    451 	 * to correctly detect memory initialisation. Make sure one is called
    452 	 * directly since our indirection trick above sucessfully confuses it.
    453 	 */
    454 #if defined(__has_feature)
    455 # if __has_feature(memory_sanitizer)
    456 	memset(p, 0, n);
    457 # endif
    458 #endif
    459 
    460 	ssh_bzero(p, n);
    461 }
    462 
    463 #endif /* HAVE_MEMSET_S */
    464 #endif /* !HAVE_EXPLICIT_BZERO */
    465 #if !HAVE_GETPROGNAME
    466 /*
    467  * Copyright (c) 2016 Nicholas Marriott <nicholas.marriott@gmail.com>
    468  * Copyright (c) 2017 Kristaps Dzonsons <kristaps@bsd.lv>
    469  *
    470  * Permission to use, copy, modify, and distribute this software for any
    471  * purpose with or without fee is hereby granted, provided that the above
    472  * copyright notice and this permission notice appear in all copies.
    473  *
    474  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    475  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    476  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    477  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    478  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
    479  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
    480  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    481  */
    482 
    483 #include <sys/types.h>
    484 
    485 #include <errno.h>
    486 
    487 #if HAVE_PROGRAM_INVOCATION_SHORT_NAME
    488 const char *
    489 getprogname(void)
    490 {
    491 	return (program_invocation_short_name);
    492 }
    493 #elif HAVE___PROGNAME
    494 const char *
    495 getprogname(void)
    496 {
    497 	extern char	*__progname;
    498 
    499 	return (__progname);
    500 }
    501 #else
    502 #error No getprogname available.
    503 #endif
    504 #endif /* !HAVE_GETPROGNAME */
    505 #if !HAVE_MD5
    506 /*
    507  * This code implements the MD5 message-digest algorithm.
    508  * The algorithm is due to Ron Rivest.	This code was
    509  * written by Colin Plumb in 1993, no copyright is claimed.
    510  * This code is in the public domain; do with it what you wish.
    511  *
    512  * Equivalent code is available from RSA Data Security, Inc.
    513  * This code has been tested against that, and is equivalent,
    514  * except that you don't need to include two pages of legalese
    515  * with every copy.
    516  *
    517  * To compute the message digest of a chunk of bytes, declare an
    518  * MD5Context structure, pass it to MD5Init, call MD5Update as
    519  * needed on buffers full of bytes, and then call MD5Final, which
    520  * will fill a supplied 16-byte array with the digest.
    521  */
    522 
    523 #include <sys/types.h>
    524 #include <stdlib.h>
    525 #include <string.h>
    526 
    527 #define PUT_64BIT_LE(cp, value) do {					\
    528 	(cp)[7] = (value) >> 56;					\
    529 	(cp)[6] = (value) >> 48;					\
    530 	(cp)[5] = (value) >> 40;					\
    531 	(cp)[4] = (value) >> 32;					\
    532 	(cp)[3] = (value) >> 24;					\
    533 	(cp)[2] = (value) >> 16;					\
    534 	(cp)[1] = (value) >> 8;						\
    535 	(cp)[0] = (value); } while (0)
    536 
    537 #define PUT_32BIT_LE(cp, value) do {					\
    538 	(cp)[3] = (value) >> 24;					\
    539 	(cp)[2] = (value) >> 16;					\
    540 	(cp)[1] = (value) >> 8;						\
    541 	(cp)[0] = (value); } while (0)
    542 
    543 static u_int8_t PADDING[MD5_BLOCK_LENGTH] = {
    544 	0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    545 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    546 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    547 };
    548 
    549 /*
    550  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
    551  * initialization constants.
    552  */
    553 void
    554 MD5Init(MD5_CTX *ctx)
    555 {
    556 	ctx->count = 0;
    557 	ctx->state[0] = 0x67452301;
    558 	ctx->state[1] = 0xefcdab89;
    559 	ctx->state[2] = 0x98badcfe;
    560 	ctx->state[3] = 0x10325476;
    561 }
    562 
    563 /*
    564  * Update context to reflect the concatenation of another buffer full
    565  * of bytes.
    566  */
    567 void
    568 MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len)
    569 {
    570 	size_t have, need;
    571 
    572 	/* Check how many bytes we already have and how many more we need. */
    573 	have = (size_t)((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1));
    574 	need = MD5_BLOCK_LENGTH - have;
    575 
    576 	/* Update bitcount */
    577 	ctx->count += (u_int64_t)len << 3;
    578 
    579 	if (len >= need) {
    580 		if (have != 0) {
    581 			memcpy(ctx->buffer + have, input, need);
    582 			MD5Transform(ctx->state, ctx->buffer);
    583 			input += need;
    584 			len -= need;
    585 			have = 0;
    586 		}
    587 
    588 		/* Process data in MD5_BLOCK_LENGTH-byte chunks. */
    589 		while (len >= MD5_BLOCK_LENGTH) {
    590 			MD5Transform(ctx->state, input);
    591 			input += MD5_BLOCK_LENGTH;
    592 			len -= MD5_BLOCK_LENGTH;
    593 		}
    594 	}
    595 
    596 	/* Handle any remaining bytes of data. */
    597 	if (len != 0)
    598 		memcpy(ctx->buffer + have, input, len);
    599 }
    600 
    601 /*
    602  * Pad pad to 64-byte boundary with the bit pattern
    603  * 1 0* (64-bit count of bits processed, MSB-first)
    604  */
    605 void
    606 MD5Pad(MD5_CTX *ctx)
    607 {
    608 	u_int8_t count[8];
    609 	size_t padlen;
    610 
    611 	/* Convert count to 8 bytes in little endian order. */
    612 	PUT_64BIT_LE(count, ctx->count);
    613 
    614 	/* Pad out to 56 mod 64. */
    615 	padlen = MD5_BLOCK_LENGTH -
    616 	    ((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1));
    617 	if (padlen < 1 + 8)
    618 		padlen += MD5_BLOCK_LENGTH;
    619 	MD5Update(ctx, PADDING, padlen - 8);		/* padlen - 8 <= 64 */
    620 	MD5Update(ctx, count, 8);
    621 }
    622 
    623 /*
    624  * Final wrapup--call MD5Pad, fill in digest and zero out ctx.
    625  */
    626 void
    627 MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx)
    628 {
    629 	int i;
    630 
    631 	MD5Pad(ctx);
    632 	for (i = 0; i < 4; i++)
    633 		PUT_32BIT_LE(digest + i * 4, ctx->state[i]);
    634 	memset(ctx, 0, sizeof(*ctx));
    635 }
    636 
    637 
    638 /* The four core functions - F1 is optimized somewhat */
    639 
    640 /* #define F1(x, y, z) (x & y | ~x & z) */
    641 #define F1(x, y, z) (z ^ (x & (y ^ z)))
    642 #define F2(x, y, z) F1(z, x, y)
    643 #define F3(x, y, z) (x ^ y ^ z)
    644 #define F4(x, y, z) (y ^ (x | ~z))
    645 
    646 /* This is the central step in the MD5 algorithm. */
    647 #define MD5STEP(f, w, x, y, z, data, s) \
    648 	( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
    649 
    650 /*
    651  * The core of the MD5 algorithm, this alters an existing MD5 hash to
    652  * reflect the addition of 16 longwords of new data.  MD5Update blocks
    653  * the data and converts bytes into longwords for this routine.
    654  */
    655 void
    656 MD5Transform(u_int32_t state[4], const u_int8_t block[MD5_BLOCK_LENGTH])
    657 {
    658 	u_int32_t a, b, c, d, in[MD5_BLOCK_LENGTH / 4];
    659 
    660 #if BYTE_ORDER == LITTLE_ENDIAN
    661 	memcpy(in, block, sizeof(in));
    662 #else
    663 	for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) {
    664 		in[a] = (u_int32_t)(
    665 		    (u_int32_t)(block[a * 4 + 0]) |
    666 		    (u_int32_t)(block[a * 4 + 1]) <<  8 |
    667 		    (u_int32_t)(block[a * 4 + 2]) << 16 |
    668 		    (u_int32_t)(block[a * 4 + 3]) << 24);
    669 	}
    670 #endif
    671 
    672 	a = state[0];
    673 	b = state[1];
    674 	c = state[2];
    675 	d = state[3];
    676 
    677 	MD5STEP(F1, a, b, c, d, in[ 0] + 0xd76aa478,  7);
    678 	MD5STEP(F1, d, a, b, c, in[ 1] + 0xe8c7b756, 12);
    679 	MD5STEP(F1, c, d, a, b, in[ 2] + 0x242070db, 17);
    680 	MD5STEP(F1, b, c, d, a, in[ 3] + 0xc1bdceee, 22);
    681 	MD5STEP(F1, a, b, c, d, in[ 4] + 0xf57c0faf,  7);
    682 	MD5STEP(F1, d, a, b, c, in[ 5] + 0x4787c62a, 12);
    683 	MD5STEP(F1, c, d, a, b, in[ 6] + 0xa8304613, 17);
    684 	MD5STEP(F1, b, c, d, a, in[ 7] + 0xfd469501, 22);
    685 	MD5STEP(F1, a, b, c, d, in[ 8] + 0x698098d8,  7);
    686 	MD5STEP(F1, d, a, b, c, in[ 9] + 0x8b44f7af, 12);
    687 	MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
    688 	MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
    689 	MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122,  7);
    690 	MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
    691 	MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
    692 	MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
    693 
    694 	MD5STEP(F2, a, b, c, d, in[ 1] + 0xf61e2562,  5);
    695 	MD5STEP(F2, d, a, b, c, in[ 6] + 0xc040b340,  9);
    696 	MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
    697 	MD5STEP(F2, b, c, d, a, in[ 0] + 0xe9b6c7aa, 20);
    698 	MD5STEP(F2, a, b, c, d, in[ 5] + 0xd62f105d,  5);
    699 	MD5STEP(F2, d, a, b, c, in[10] + 0x02441453,  9);
    700 	MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
    701 	MD5STEP(F2, b, c, d, a, in[ 4] + 0xe7d3fbc8, 20);
    702 	MD5STEP(F2, a, b, c, d, in[ 9] + 0x21e1cde6,  5);
    703 	MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6,  9);
    704 	MD5STEP(F2, c, d, a, b, in[ 3] + 0xf4d50d87, 14);
    705 	MD5STEP(F2, b, c, d, a, in[ 8] + 0x455a14ed, 20);
    706 	MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905,  5);
    707 	MD5STEP(F2, d, a, b, c, in[ 2] + 0xfcefa3f8,  9);
    708 	MD5STEP(F2, c, d, a, b, in[ 7] + 0x676f02d9, 14);
    709 	MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
    710 
    711 	MD5STEP(F3, a, b, c, d, in[ 5] + 0xfffa3942,  4);
    712 	MD5STEP(F3, d, a, b, c, in[ 8] + 0x8771f681, 11);
    713 	MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
    714 	MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
    715 	MD5STEP(F3, a, b, c, d, in[ 1] + 0xa4beea44,  4);
    716 	MD5STEP(F3, d, a, b, c, in[ 4] + 0x4bdecfa9, 11);
    717 	MD5STEP(F3, c, d, a, b, in[ 7] + 0xf6bb4b60, 16);
    718 	MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
    719 	MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6,  4);
    720 	MD5STEP(F3, d, a, b, c, in[ 0] + 0xeaa127fa, 11);
    721 	MD5STEP(F3, c, d, a, b, in[ 3] + 0xd4ef3085, 16);
    722 	MD5STEP(F3, b, c, d, a, in[ 6] + 0x04881d05, 23);
    723 	MD5STEP(F3, a, b, c, d, in[ 9] + 0xd9d4d039,  4);
    724 	MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
    725 	MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
    726 	MD5STEP(F3, b, c, d, a, in[2 ] + 0xc4ac5665, 23);
    727 
    728 	MD5STEP(F4, a, b, c, d, in[ 0] + 0xf4292244,  6);
    729 	MD5STEP(F4, d, a, b, c, in[7 ] + 0x432aff97, 10);
    730 	MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
    731 	MD5STEP(F4, b, c, d, a, in[5 ] + 0xfc93a039, 21);
    732 	MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3,  6);
    733 	MD5STEP(F4, d, a, b, c, in[3 ] + 0x8f0ccc92, 10);
    734 	MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
    735 	MD5STEP(F4, b, c, d, a, in[1 ] + 0x85845dd1, 21);
    736 	MD5STEP(F4, a, b, c, d, in[8 ] + 0x6fa87e4f,  6);
    737 	MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
    738 	MD5STEP(F4, c, d, a, b, in[6 ] + 0xa3014314, 15);
    739 	MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
    740 	MD5STEP(F4, a, b, c, d, in[4 ] + 0xf7537e82,  6);
    741 	MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
    742 	MD5STEP(F4, c, d, a, b, in[2 ] + 0x2ad7d2bb, 15);
    743 	MD5STEP(F4, b, c, d, a, in[9 ] + 0xeb86d391, 21);
    744 
    745 	state[0] += a;
    746 	state[1] += b;
    747 	state[2] += c;
    748 	state[3] += d;
    749 }
    750 
    751 char *
    752 MD5End(MD5_CTX *ctx, char *buf)
    753 {
    754 	int i;
    755 	unsigned char digest[MD5_DIGEST_LENGTH];
    756 	static const char hex[]="0123456789abcdef";
    757 
    758 	if (!buf)
    759 		buf = malloc(2*MD5_DIGEST_LENGTH + 1);
    760 	if (!buf)
    761 		return 0;
    762 	MD5Final(digest, ctx);
    763 	for (i = 0; i < MD5_DIGEST_LENGTH; i++) {
    764 		buf[i+i] = hex[digest[i] >> 4];
    765 		buf[i+i+1] = hex[digest[i] & 0x0f];
    766 	}
    767 	buf[i+i] = '\0';
    768 	return buf;
    769 }
    770 #endif /* !HAVE_MD5 */
    771 #if !HAVE_MEMMEM
    772 /*-
    773  * Copyright (c) 2005 Pascal Gloor <pascal.gloor@spale.com>
    774  *
    775  * Redistribution and use in source and binary forms, with or without
    776  * modification, are permitted provided that the following conditions
    777  * are met:
    778  * 1. Redistributions of source code must retain the above copyright
    779  *    notice, this list of conditions and the following disclaimer.
    780  * 2. Redistributions in binary form must reproduce the above copyright
    781  *    notice, this list of conditions and the following disclaimer in
    782  *    the documentation and/or other materials provided with the
    783  *    distribution.
    784  * 3. The name of the author may not be used to endorse or promote
    785  *    products derived from this software without specific prior written
    786  *    permission.
    787  *
    788  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
    789  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    790  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
    791  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR
    792  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    793  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    794  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    795  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
    796  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    797  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    798  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    799  */
    800 /*
    801  * Find the first occurrence of the byte string s in byte string l.
    802  */
    803 void *
    804 memmem(const void *l, size_t l_len, const void *s, size_t s_len)
    805 {
    806 	const char *cur, *last;
    807 	const char *cl = l;
    808 	const char *cs = s;
    809 
    810 	/* a zero length needle should just return the haystack */
    811 	if (l_len == 0)
    812 		return (void *)cl;
    813 
    814 	/* "s" must be smaller or equal to "l" */
    815 	if (l_len < s_len)
    816 		return NULL;
    817 
    818 	/* special case where s_len == 1 */
    819 	if (s_len == 1)
    820 		return memchr(l, *cs, l_len);
    821 
    822 	/* the last position where its possible to find "s" in "l" */
    823 	last = cl + l_len - s_len;
    824 
    825 	for (cur = cl; cur <= last; cur++)
    826 		if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
    827 			return (void *)cur;
    828 
    829 	return NULL;
    830 }
    831 #endif /* !HAVE_MEMMEM */
    832 #if !HAVE_MEMRCHR
    833 /*
    834  * Copyright (c) 2007 Todd C. Miller <Todd.Miller@courtesan.com>
    835  *
    836  * Permission to use, copy, modify, and distribute this software for any
    837  * purpose with or without fee is hereby granted, provided that the above
    838  * copyright notice and this permission notice appear in all copies.
    839  *
    840  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    841  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    842  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    843  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    844  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    845  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    846  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    847  *
    848  */
    849 
    850 #include <string.h>
    851 
    852 /*
    853  * Reverse memchr()
    854  * Find the last occurrence of 'c' in the buffer 's' of size 'n'.
    855  */
    856 void *
    857 memrchr(const void *s, int c, size_t n)
    858 {
    859     const unsigned char *cp;
    860 
    861     if (n != 0) {
    862         cp = (unsigned char *)s + n;
    863         do {
    864             if (*(--cp) == (unsigned char)c)
    865                 return((void *)cp);
    866         } while (--n != 0);
    867     }
    868     return(NULL);
    869 }
    870 #endif /* !HAVE_MEMRCHR */
    871 #if !HAVE_READPASSPHRASE
    872 /*	$OpenBSD$	*/
    873 
    874 /*
    875  * Copyright (c) 2000-2002, 2007, 2010
    876  *	Todd C. Miller <millert@openbsd.org>
    877  *
    878  * Permission to use, copy, modify, and distribute this software for any
    879  * purpose with or without fee is hereby granted, provided that the above
    880  * copyright notice and this permission notice appear in all copies.
    881  *
    882  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    883  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    884  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    885  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    886  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    887  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    888  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    889  *
    890  * Sponsored in part by the Defense Advanced Research Projects
    891  * Agency (DARPA) and Air Force Research Laboratory, Air Force
    892  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
    893  */
    894 
    895 #include <ctype.h>
    896 #include <errno.h>
    897 #include <fcntl.h>
    898 #include <paths.h>
    899 #include <pwd.h>
    900 #include <signal.h>
    901 #include <string.h>
    902 #include <termios.h>
    903 #include <unistd.h>
    904 
    905 #ifndef TCSASOFT
    906 /* If we don't have TCSASOFT define it so that ORing it it below is a no-op. */
    907 # define TCSASOFT 0
    908 #endif
    909 
    910 /* SunOS 4.x which lacks _POSIX_VDISABLE, but has VDISABLE */
    911 #if !defined(_POSIX_VDISABLE) && defined(VDISABLE)
    912 #  define _POSIX_VDISABLE       VDISABLE
    913 #endif
    914 
    915 static volatile sig_atomic_t signo[_NSIG];
    916 
    917 static void handler(int);
    918 
    919 char *
    920 readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags)
    921 {
    922 	ssize_t nr;
    923 	int input, output, save_errno, i, need_restart;
    924 	char ch, *p, *end;
    925 	struct termios term, oterm;
    926 	struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm;
    927 	struct sigaction savetstp, savettin, savettou, savepipe;
    928 
    929 	/* I suppose we could alloc on demand in this case (XXX). */
    930 	if (bufsiz == 0) {
    931 		errno = EINVAL;
    932 		return(NULL);
    933 	}
    934 
    935 restart:
    936 	for (i = 0; i < _NSIG; i++)
    937 		signo[i] = 0;
    938 	nr = -1;
    939 	save_errno = 0;
    940 	need_restart = 0;
    941 	/*
    942 	 * Read and write to /dev/tty if available.  If not, read from
    943 	 * stdin and write to stderr unless a tty is required.
    944 	 */
    945 	if ((flags & RPP_STDIN) ||
    946 	    (input = output = open(_PATH_TTY, O_RDWR)) == -1) {
    947 		if (flags & RPP_REQUIRE_TTY) {
    948 			errno = ENOTTY;
    949 			return(NULL);
    950 		}
    951 		input = STDIN_FILENO;
    952 		output = STDERR_FILENO;
    953 	}
    954 
    955 	/*
    956 	 * Turn off echo if possible.
    957 	 * If we are using a tty but are not the foreground pgrp this will
    958 	 * generate SIGTTOU, so do it *before* installing the signal handlers.
    959 	 */
    960 	if (input != STDIN_FILENO && tcgetattr(input, &oterm) == 0) {
    961 		memcpy(&term, &oterm, sizeof(term));
    962 		if (!(flags & RPP_ECHO_ON))
    963 			term.c_lflag &= ~(ECHO | ECHONL);
    964 #ifdef VSTATUS
    965 		if (term.c_cc[VSTATUS] != _POSIX_VDISABLE)
    966 			term.c_cc[VSTATUS] = _POSIX_VDISABLE;
    967 #endif
    968 		(void)tcsetattr(input, TCSAFLUSH|TCSASOFT, &term);
    969 	} else {
    970 		memset(&term, 0, sizeof(term));
    971 		term.c_lflag |= ECHO;
    972 		memset(&oterm, 0, sizeof(oterm));
    973 		oterm.c_lflag |= ECHO;
    974 	}
    975 
    976 	/*
    977 	 * Catch signals that would otherwise cause the user to end
    978 	 * up with echo turned off in the shell.  Don't worry about
    979 	 * things like SIGXCPU and SIGVTALRM for now.
    980 	 */
    981 	sigemptyset(&sa.sa_mask);
    982 	sa.sa_flags = 0;		/* don't restart system calls */
    983 	sa.sa_handler = handler;
    984 	(void)sigaction(SIGALRM, &sa, &savealrm);
    985 	(void)sigaction(SIGHUP, &sa, &savehup);
    986 	(void)sigaction(SIGINT, &sa, &saveint);
    987 	(void)sigaction(SIGPIPE, &sa, &savepipe);
    988 	(void)sigaction(SIGQUIT, &sa, &savequit);
    989 	(void)sigaction(SIGTERM, &sa, &saveterm);
    990 	(void)sigaction(SIGTSTP, &sa, &savetstp);
    991 	(void)sigaction(SIGTTIN, &sa, &savettin);
    992 	(void)sigaction(SIGTTOU, &sa, &savettou);
    993 
    994 	if (!(flags & RPP_STDIN))
    995 		(void)write(output, prompt, strlen(prompt));
    996 	end = buf + bufsiz - 1;
    997 	p = buf;
    998 	while ((nr = read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r') {
    999 		if (p < end) {
   1000 			if ((flags & RPP_SEVENBIT))
   1001 				ch &= 0x7f;
   1002 			if (isalpha((unsigned char)ch)) {
   1003 				if ((flags & RPP_FORCELOWER))
   1004 					ch = (char)tolower((unsigned char)ch);
   1005 				if ((flags & RPP_FORCEUPPER))
   1006 					ch = (char)toupper((unsigned char)ch);
   1007 			}
   1008 			*p++ = ch;
   1009 		}
   1010 	}
   1011 	*p = '\0';
   1012 	save_errno = errno;
   1013 	if (!(term.c_lflag & ECHO))
   1014 		(void)write(output, "\n", 1);
   1015 
   1016 	/* Restore old terminal settings and signals. */
   1017 	if (memcmp(&term, &oterm, sizeof(term)) != 0) {
   1018 		const int sigttou = signo[SIGTTOU];
   1019 
   1020 		/* Ignore SIGTTOU generated when we are not the fg pgrp. */
   1021 		while (tcsetattr(input, TCSAFLUSH|TCSASOFT, &oterm) == -1 &&
   1022 		    errno == EINTR && !signo[SIGTTOU])
   1023 			continue;
   1024 		signo[SIGTTOU] = sigttou;
   1025 	}
   1026 	(void)sigaction(SIGALRM, &savealrm, NULL);
   1027 	(void)sigaction(SIGHUP, &savehup, NULL);
   1028 	(void)sigaction(SIGINT, &saveint, NULL);
   1029 	(void)sigaction(SIGQUIT, &savequit, NULL);
   1030 	(void)sigaction(SIGPIPE, &savepipe, NULL);
   1031 	(void)sigaction(SIGTERM, &saveterm, NULL);
   1032 	(void)sigaction(SIGTSTP, &savetstp, NULL);
   1033 	(void)sigaction(SIGTTIN, &savettin, NULL);
   1034 	(void)sigaction(SIGTTOU, &savettou, NULL);
   1035 	if (input != STDIN_FILENO)
   1036 		(void)close(input);
   1037 
   1038 	/*
   1039 	 * If we were interrupted by a signal, resend it to ourselves
   1040 	 * now that we have restored the signal handlers.
   1041 	 */
   1042 	for (i = 0; i < _NSIG; i++) {
   1043 		if (signo[i]) {
   1044 			kill(getpid(), i);
   1045 			switch (i) {
   1046 			case SIGTSTP:
   1047 			case SIGTTIN:
   1048 			case SIGTTOU:
   1049 				need_restart = 1;
   1050 			}
   1051 		}
   1052 	}
   1053 	if (need_restart)
   1054 		goto restart;
   1055 
   1056 	if (save_errno)
   1057 		errno = save_errno;
   1058 	return(nr == -1 ? NULL : buf);
   1059 }
   1060 
   1061 static void
   1062 handler(int s)
   1063 {
   1064 
   1065 	signo[s] = 1;
   1066 }
   1067 #endif /* !HAVE_READPASSPHRASE */
   1068 #if !HAVE_REALLOCARRAY
   1069 /*
   1070  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
   1071  *
   1072  * Permission to use, copy, modify, and distribute this software for any
   1073  * purpose with or without fee is hereby granted, provided that the above
   1074  * copyright notice and this permission notice appear in all copies.
   1075  *
   1076  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1077  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1078  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1079  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1080  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1081  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1082  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1083  */
   1084 
   1085 #include <sys/types.h>
   1086 #include <errno.h>
   1087 #include <stdint.h>
   1088 #include <stdlib.h>
   1089 
   1090 /*
   1091  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
   1092  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
   1093  */
   1094 #define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
   1095 
   1096 void *
   1097 reallocarray(void *optr, size_t nmemb, size_t size)
   1098 {
   1099 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
   1100 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
   1101 		errno = ENOMEM;
   1102 		return NULL;
   1103 	}
   1104 	return realloc(optr, size * nmemb);
   1105 }
   1106 #endif /* !HAVE_REALLOCARRAY */
   1107 #if !HAVE_RECALLOCARRAY
   1108 /*
   1109  * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
   1110  *
   1111  * Permission to use, copy, modify, and distribute this software for any
   1112  * purpose with or without fee is hereby granted, provided that the above
   1113  * copyright notice and this permission notice appear in all copies.
   1114  *
   1115  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1116  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1117  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1118  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1119  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1120  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1121  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1122  */
   1123 
   1124 /* OPENBSD ORIGINAL: lib/libc/stdlib/recallocarray.c */
   1125 
   1126 #include <errno.h>
   1127 #include <stdlib.h>
   1128 #include <stdint.h>
   1129 #include <string.h>
   1130 #include <unistd.h>
   1131 
   1132 /*
   1133  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
   1134  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
   1135  */
   1136 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
   1137 
   1138 void *
   1139 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
   1140 {
   1141 	size_t oldsize, newsize;
   1142 	void *newptr;
   1143 
   1144 	if (ptr == NULL)
   1145 		return calloc(newnmemb, size);
   1146 
   1147 	if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
   1148 	    newnmemb > 0 && SIZE_MAX / newnmemb < size) {
   1149 		errno = ENOMEM;
   1150 		return NULL;
   1151 	}
   1152 	newsize = newnmemb * size;
   1153 
   1154 	if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
   1155 	    oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
   1156 		errno = EINVAL;
   1157 		return NULL;
   1158 	}
   1159 	oldsize = oldnmemb * size;
   1160 	
   1161 	/*
   1162 	 * Don't bother too much if we're shrinking just a bit,
   1163 	 * we do not shrink for series of small steps, oh well.
   1164 	 */
   1165 	if (newsize <= oldsize) {
   1166 		size_t d = oldsize - newsize;
   1167 
   1168 		if (d < oldsize / 2 && d < (size_t)getpagesize()) {
   1169 			memset((char *)ptr + newsize, 0, d);
   1170 			return ptr;
   1171 		}
   1172 	}
   1173 
   1174 	newptr = malloc(newsize);
   1175 	if (newptr == NULL)
   1176 		return NULL;
   1177 
   1178 	if (newsize > oldsize) {
   1179 		memcpy(newptr, ptr, oldsize);
   1180 		memset((char *)newptr + oldsize, 0, newsize - oldsize);
   1181 	} else
   1182 		memcpy(newptr, ptr, newsize);
   1183 
   1184 	explicit_bzero(ptr, oldsize);
   1185 	free(ptr);
   1186 
   1187 	return newptr;
   1188 }
   1189 #endif /* !HAVE_RECALLOCARRAY */
   1190 #if !HAVE_STRLCAT
   1191 /*
   1192  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
   1193  *
   1194  * Permission to use, copy, modify, and distribute this software for any
   1195  * purpose with or without fee is hereby granted, provided that the above
   1196  * copyright notice and this permission notice appear in all copies.
   1197  *
   1198  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1199  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1200  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1201  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1202  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1203  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1204  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1205  */
   1206 
   1207 #include <sys/types.h>
   1208 #include <string.h>
   1209 
   1210 /*
   1211  * Appends src to string dst of size siz (unlike strncat, siz is the
   1212  * full size of dst, not space left).  At most siz-1 characters
   1213  * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
   1214  * Returns strlen(src) + MIN(siz, strlen(initial dst)).
   1215  * If retval >= siz, truncation occurred.
   1216  */
   1217 size_t
   1218 strlcat(char *dst, const char *src, size_t siz)
   1219 {
   1220 	char *d = dst;
   1221 	const char *s = src;
   1222 	size_t n = siz;
   1223 	size_t dlen;
   1224 
   1225 	/* Find the end of dst and adjust bytes left but don't go past end */
   1226 	while (n-- != 0 && *d != '\0')
   1227 		d++;
   1228 	dlen = d - dst;
   1229 	n = siz - dlen;
   1230 
   1231 	if (n == 0)
   1232 		return(dlen + strlen(s));
   1233 	while (*s != '\0') {
   1234 		if (n != 1) {
   1235 			*d++ = *s;
   1236 			n--;
   1237 		}
   1238 		s++;
   1239 	}
   1240 	*d = '\0';
   1241 
   1242 	return(dlen + (s - src));	/* count does not include NUL */
   1243 }
   1244 #endif /* !HAVE_STRLCAT */
   1245 #if !HAVE_STRLCPY
   1246 /*
   1247  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
   1248  *
   1249  * Permission to use, copy, modify, and distribute this software for any
   1250  * purpose with or without fee is hereby granted, provided that the above
   1251  * copyright notice and this permission notice appear in all copies.
   1252  *
   1253  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1254  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1255  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1256  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1257  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1258  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1259  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1260  */
   1261 
   1262 #include <sys/types.h>
   1263 #include <string.h>
   1264 
   1265 /*
   1266  * Copy src to string dst of size siz.  At most siz-1 characters
   1267  * will be copied.  Always NUL terminates (unless siz == 0).
   1268  * Returns strlen(src); if retval >= siz, truncation occurred.
   1269  */
   1270 size_t
   1271 strlcpy(char *dst, const char *src, size_t siz)
   1272 {
   1273 	char *d = dst;
   1274 	const char *s = src;
   1275 	size_t n = siz;
   1276 
   1277 	/* Copy as many bytes as will fit */
   1278 	if (n != 0) {
   1279 		while (--n != 0) {
   1280 			if ((*d++ = *s++) == '\0')
   1281 				break;
   1282 		}
   1283 	}
   1284 
   1285 	/* Not enough room in dst, add NUL and traverse rest of src */
   1286 	if (n == 0) {
   1287 		if (siz != 0)
   1288 			*d = '\0';		/* NUL-terminate dst */
   1289 		while (*s++)
   1290 			;
   1291 	}
   1292 
   1293 	return(s - src - 1);	/* count does not include NUL */
   1294 }
   1295 #endif /* !HAVE_STRLCPY */
   1296 #if !HAVE_STRNDUP
   1297 /*	$OpenBSD$	*/
   1298 /*
   1299  * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com>
   1300  *
   1301  * Permission to use, copy, modify, and distribute this software for any
   1302  * purpose with or without fee is hereby granted, provided that the above
   1303  * copyright notice and this permission notice appear in all copies.
   1304  *
   1305  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1306  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1307  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1308  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1309  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1310  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1311  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1312  */
   1313 
   1314 #include <sys/types.h>
   1315 
   1316 #include <stddef.h>
   1317 #include <stdlib.h>
   1318 #include <string.h>
   1319 
   1320 char *
   1321 strndup(const char *str, size_t maxlen)
   1322 {
   1323 	char *copy;
   1324 	size_t len;
   1325 
   1326 	len = strnlen(str, maxlen);
   1327 	copy = malloc(len + 1);
   1328 	if (copy != NULL) {
   1329 		(void)memcpy(copy, str, len);
   1330 		copy[len] = '\0';
   1331 	}
   1332 
   1333 	return copy;
   1334 }
   1335 #endif /* !HAVE_STRNDUP */
   1336 #if !HAVE_STRNLEN
   1337 /*	$OpenBSD$	*/
   1338 
   1339 /*
   1340  * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com>
   1341  *
   1342  * Permission to use, copy, modify, and distribute this software for any
   1343  * purpose with or without fee is hereby granted, provided that the above
   1344  * copyright notice and this permission notice appear in all copies.
   1345  *
   1346  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1347  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1348  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1349  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1350  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1351  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1352  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1353  */
   1354 
   1355 #include <sys/types.h>
   1356 #include <string.h>
   1357 
   1358 size_t
   1359 strnlen(const char *str, size_t maxlen)
   1360 {
   1361 	const char *cp;
   1362 
   1363 	for (cp = str; maxlen != 0 && *cp != '\0'; cp++, maxlen--)
   1364 		;
   1365 
   1366 	return (size_t)(cp - str);
   1367 }
   1368 #endif /* !HAVE_STRNLEN */
   1369 #if !HAVE_STRTONUM
   1370 /*
   1371  * Copyright (c) 2004 Ted Unangst and Todd Miller
   1372  * All rights reserved.
   1373  *
   1374  * Permission to use, copy, modify, and distribute this software for any
   1375  * purpose with or without fee is hereby granted, provided that the above
   1376  * copyright notice and this permission notice appear in all copies.
   1377  *
   1378  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1379  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1380  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1381  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1382  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1383  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1384  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1385  */
   1386 
   1387 #include <errno.h>
   1388 #include <limits.h>
   1389 #include <stdlib.h>
   1390 
   1391 #define	INVALID		1
   1392 #define	TOOSMALL	2
   1393 #define	TOOLARGE	3
   1394 
   1395 long long
   1396 strtonum(const char *numstr, long long minval, long long maxval,
   1397     const char **errstrp)
   1398 {
   1399 	long long ll = 0;
   1400 	int error = 0;
   1401 	char *ep;
   1402 	struct errval {
   1403 		const char *errstr;
   1404 		int err;
   1405 	} ev[4] = {
   1406 		{ NULL,		0 },
   1407 		{ "invalid",	EINVAL },
   1408 		{ "too small",	ERANGE },
   1409 		{ "too large",	ERANGE },
   1410 	};
   1411 
   1412 	ev[0].err = errno;
   1413 	errno = 0;
   1414 	if (minval > maxval) {
   1415 		error = INVALID;
   1416 	} else {
   1417 		ll = strtoll(numstr, &ep, 10);
   1418 		if (numstr == ep || *ep != '\0')
   1419 			error = INVALID;
   1420 		else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
   1421 			error = TOOSMALL;
   1422 		else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
   1423 			error = TOOLARGE;
   1424 	}
   1425 	if (errstrp != NULL)
   1426 		*errstrp = ev[error].errstr;
   1427 	errno = ev[error].err;
   1428 	if (error)
   1429 		ll = 0;
   1430 
   1431 	return (ll);
   1432 }
   1433 #endif /* !HAVE_STRTONUM */