crypt-portable

Portable version of the classic crypt(1) utility
git clone git://git.sgregoratto.me/crypt-portable
Log | Files | Refs

compats.c (43550B)


      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 /* 
    873  * Original: readpassphrase.c in OpenSSH portable
    874  */
    875 /*
    876  * Copyright (c) 2000-2002, 2007, 2010
    877  *	Todd C. Miller <millert@openbsd.org>
    878  *
    879  * Permission to use, copy, modify, and distribute this software for any
    880  * purpose with or without fee is hereby granted, provided that the above
    881  * copyright notice and this permission notice appear in all copies.
    882  *
    883  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    884  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    885  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    886  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    887  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    888  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    889  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    890  *
    891  * Sponsored in part by the Defense Advanced Research Projects
    892  * Agency (DARPA) and Air Force Research Laboratory, Air Force
    893  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
    894  */
    895 
    896 #include <ctype.h>
    897 #include <errno.h>
    898 #include <fcntl.h>
    899 #include <paths.h>
    900 #include <pwd.h>
    901 #include <signal.h>
    902 #include <string.h>
    903 #include <termios.h>
    904 #include <unistd.h>
    905 
    906 static volatile sig_atomic_t readpassphrase_signo[_NSIG];
    907 
    908 static void
    909 readpassphrase_handler(int s)
    910 {
    911 
    912 	readpassphrase_signo[s] = 1;
    913 }
    914 
    915 char *
    916 readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags)
    917 {
    918 	ssize_t nr;
    919 	int input, output, save_errno, i, need_restart;
    920 	char ch, *p, *end;
    921 	struct termios term, oterm;
    922 	struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm;
    923 	struct sigaction savetstp, savettin, savettou, savepipe;
    924 /* If we don't have TCSASOFT define it so that ORing it it below is a no-op. */
    925 #ifndef TCSASOFT
    926 	const int tcasoft = 0;
    927 #else
    928 	const int tcasoft = TCASOFT;
    929 #endif
    930 
    931 	/* I suppose we could alloc on demand in this case (XXX). */
    932 	if (bufsiz == 0) {
    933 		errno = EINVAL;
    934 		return(NULL);
    935 	}
    936 
    937 restart:
    938 	for (i = 0; i < _NSIG; i++)
    939 		readpassphrase_signo[i] = 0;
    940 	nr = -1;
    941 	save_errno = 0;
    942 	need_restart = 0;
    943 	/*
    944 	 * Read and write to /dev/tty if available.  If not, read from
    945 	 * stdin and write to stderr unless a tty is required.
    946 	 */
    947 	if ((flags & RPP_STDIN) ||
    948 	    (input = output = open(_PATH_TTY, O_RDWR)) == -1) {
    949 		if (flags & RPP_REQUIRE_TTY) {
    950 			errno = ENOTTY;
    951 			return(NULL);
    952 		}
    953 		input = STDIN_FILENO;
    954 		output = STDERR_FILENO;
    955 	}
    956 
    957 	/*
    958 	 * Turn off echo if possible.
    959 	 * If we are using a tty but are not the foreground pgrp this will
    960 	 * generate SIGTTOU, so do it *before* installing the signal handlers.
    961 	 */
    962 	if (input != STDIN_FILENO && tcgetattr(input, &oterm) == 0) {
    963 		memcpy(&term, &oterm, sizeof(term));
    964 		if (!(flags & RPP_ECHO_ON))
    965 			term.c_lflag &= ~(ECHO | ECHONL);
    966 #ifdef VSTATUS
    967 		if (term.c_cc[VSTATUS] != _POSIX_VDISABLE)
    968 			term.c_cc[VSTATUS] = _POSIX_VDISABLE;
    969 #endif
    970 		(void)tcsetattr(input, TCSAFLUSH|tcasoft, &term);
    971 	} else {
    972 		memset(&term, 0, sizeof(term));
    973 		term.c_lflag |= ECHO;
    974 		memset(&oterm, 0, sizeof(oterm));
    975 		oterm.c_lflag |= ECHO;
    976 	}
    977 
    978 	/*
    979 	 * Catch signals that would otherwise cause the user to end
    980 	 * up with echo turned off in the shell.  Don't worry about
    981 	 * things like SIGXCPU and SIGVTALRM for now.
    982 	 */
    983 	sigemptyset(&sa.sa_mask);
    984 	sa.sa_flags = 0;		/* don't restart system calls */
    985 	sa.sa_handler = readpassphrase_handler;
    986 	(void)sigaction(SIGALRM, &sa, &savealrm);
    987 	(void)sigaction(SIGHUP, &sa, &savehup);
    988 	(void)sigaction(SIGINT, &sa, &saveint);
    989 	(void)sigaction(SIGPIPE, &sa, &savepipe);
    990 	(void)sigaction(SIGQUIT, &sa, &savequit);
    991 	(void)sigaction(SIGTERM, &sa, &saveterm);
    992 	(void)sigaction(SIGTSTP, &sa, &savetstp);
    993 	(void)sigaction(SIGTTIN, &sa, &savettin);
    994 	(void)sigaction(SIGTTOU, &sa, &savettou);
    995 
    996 	if (!(flags & RPP_STDIN))
    997 		(void)write(output, prompt, strlen(prompt));
    998 	end = buf + bufsiz - 1;
    999 	p = buf;
   1000 	while ((nr = read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r') {
   1001 		if (p < end) {
   1002 			if ((flags & RPP_SEVENBIT))
   1003 				ch &= 0x7f;
   1004 			if (isalpha((unsigned char)ch)) {
   1005 				if ((flags & RPP_FORCELOWER))
   1006 					ch = (char)tolower((unsigned char)ch);
   1007 				if ((flags & RPP_FORCEUPPER))
   1008 					ch = (char)toupper((unsigned char)ch);
   1009 			}
   1010 			*p++ = ch;
   1011 		}
   1012 	}
   1013 	*p = '\0';
   1014 	save_errno = errno;
   1015 	if (!(term.c_lflag & ECHO))
   1016 		(void)write(output, "\n", 1);
   1017 
   1018 	/* Restore old terminal settings and signals. */
   1019 	if (memcmp(&term, &oterm, sizeof(term)) != 0) {
   1020 		const int sigttou = readpassphrase_signo[SIGTTOU];
   1021 
   1022 		/* Ignore SIGTTOU generated when we are not the fg pgrp. */
   1023 		while (tcsetattr(input, TCSAFLUSH|tcasoft, &oterm) == -1 &&
   1024 		    errno == EINTR && !readpassphrase_signo[SIGTTOU])
   1025 			continue;
   1026 		readpassphrase_signo[SIGTTOU] = sigttou;
   1027 	}
   1028 	(void)sigaction(SIGALRM, &savealrm, NULL);
   1029 	(void)sigaction(SIGHUP, &savehup, NULL);
   1030 	(void)sigaction(SIGINT, &saveint, NULL);
   1031 	(void)sigaction(SIGQUIT, &savequit, NULL);
   1032 	(void)sigaction(SIGPIPE, &savepipe, NULL);
   1033 	(void)sigaction(SIGTERM, &saveterm, NULL);
   1034 	(void)sigaction(SIGTSTP, &savetstp, NULL);
   1035 	(void)sigaction(SIGTTIN, &savettin, NULL);
   1036 	(void)sigaction(SIGTTOU, &savettou, NULL);
   1037 	if (input != STDIN_FILENO)
   1038 		(void)close(input);
   1039 
   1040 	/*
   1041 	 * If we were interrupted by a signal, resend it to ourselves
   1042 	 * now that we have restored the signal handlers.
   1043 	 */
   1044 	for (i = 0; i < _NSIG; i++) {
   1045 		if (readpassphrase_signo[i]) {
   1046 			kill(getpid(), i);
   1047 			switch (i) {
   1048 			case SIGTSTP:
   1049 			case SIGTTIN:
   1050 			case SIGTTOU:
   1051 				need_restart = 1;
   1052 			}
   1053 		}
   1054 	}
   1055 	if (need_restart)
   1056 		goto restart;
   1057 
   1058 	if (save_errno)
   1059 		errno = save_errno;
   1060 	return(nr == -1 ? NULL : buf);
   1061 }
   1062 #endif /* !HAVE_READPASSPHRASE */
   1063 #if !HAVE_REALLOCARRAY
   1064 /*
   1065  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
   1066  *
   1067  * Permission to use, copy, modify, and distribute this software for any
   1068  * purpose with or without fee is hereby granted, provided that the above
   1069  * copyright notice and this permission notice appear in all copies.
   1070  *
   1071  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1072  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1073  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1074  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1075  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1076  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1077  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1078  */
   1079 
   1080 #include <sys/types.h>
   1081 #include <errno.h>
   1082 #include <stdint.h>
   1083 #include <stdlib.h>
   1084 
   1085 /*
   1086  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
   1087  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
   1088  */
   1089 #define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
   1090 
   1091 void *
   1092 reallocarray(void *optr, size_t nmemb, size_t size)
   1093 {
   1094 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
   1095 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
   1096 		errno = ENOMEM;
   1097 		return NULL;
   1098 	}
   1099 	return realloc(optr, size * nmemb);
   1100 }
   1101 #endif /* !HAVE_REALLOCARRAY */
   1102 #if !HAVE_RECALLOCARRAY
   1103 /*
   1104  * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
   1105  *
   1106  * Permission to use, copy, modify, and distribute this software for any
   1107  * purpose with or without fee is hereby granted, provided that the above
   1108  * copyright notice and this permission notice appear in all copies.
   1109  *
   1110  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1111  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1112  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1113  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1114  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1115  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1116  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1117  */
   1118 
   1119 /* OPENBSD ORIGINAL: lib/libc/stdlib/recallocarray.c */
   1120 
   1121 #include <errno.h>
   1122 #include <stdlib.h>
   1123 #include <stdint.h>
   1124 #include <string.h>
   1125 #include <unistd.h>
   1126 
   1127 /*
   1128  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
   1129  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
   1130  */
   1131 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
   1132 
   1133 void *
   1134 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
   1135 {
   1136 	size_t oldsize, newsize;
   1137 	void *newptr;
   1138 
   1139 	if (ptr == NULL)
   1140 		return calloc(newnmemb, size);
   1141 
   1142 	if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
   1143 	    newnmemb > 0 && SIZE_MAX / newnmemb < size) {
   1144 		errno = ENOMEM;
   1145 		return NULL;
   1146 	}
   1147 	newsize = newnmemb * size;
   1148 
   1149 	if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
   1150 	    oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
   1151 		errno = EINVAL;
   1152 		return NULL;
   1153 	}
   1154 	oldsize = oldnmemb * size;
   1155 	
   1156 	/*
   1157 	 * Don't bother too much if we're shrinking just a bit,
   1158 	 * we do not shrink for series of small steps, oh well.
   1159 	 */
   1160 	if (newsize <= oldsize) {
   1161 		size_t d = oldsize - newsize;
   1162 
   1163 		if (d < oldsize / 2 && d < (size_t)getpagesize()) {
   1164 			memset((char *)ptr + newsize, 0, d);
   1165 			return ptr;
   1166 		}
   1167 	}
   1168 
   1169 	newptr = malloc(newsize);
   1170 	if (newptr == NULL)
   1171 		return NULL;
   1172 
   1173 	if (newsize > oldsize) {
   1174 		memcpy(newptr, ptr, oldsize);
   1175 		memset((char *)newptr + oldsize, 0, newsize - oldsize);
   1176 	} else
   1177 		memcpy(newptr, ptr, newsize);
   1178 
   1179 	explicit_bzero(ptr, oldsize);
   1180 	free(ptr);
   1181 
   1182 	return newptr;
   1183 }
   1184 #endif /* !HAVE_RECALLOCARRAY */
   1185 #if !HAVE_STRLCAT
   1186 /*
   1187  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
   1188  *
   1189  * Permission to use, copy, modify, and distribute this software for any
   1190  * purpose with or without fee is hereby granted, provided that the above
   1191  * copyright notice and this permission notice appear in all copies.
   1192  *
   1193  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1194  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1195  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1196  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1197  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1198  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1199  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1200  */
   1201 
   1202 #include <sys/types.h>
   1203 #include <string.h>
   1204 
   1205 /*
   1206  * Appends src to string dst of size siz (unlike strncat, siz is the
   1207  * full size of dst, not space left).  At most siz-1 characters
   1208  * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
   1209  * Returns strlen(src) + MIN(siz, strlen(initial dst)).
   1210  * If retval >= siz, truncation occurred.
   1211  */
   1212 size_t
   1213 strlcat(char *dst, const char *src, size_t siz)
   1214 {
   1215 	char *d = dst;
   1216 	const char *s = src;
   1217 	size_t n = siz;
   1218 	size_t dlen;
   1219 
   1220 	/* Find the end of dst and adjust bytes left but don't go past end */
   1221 	while (n-- != 0 && *d != '\0')
   1222 		d++;
   1223 	dlen = d - dst;
   1224 	n = siz - dlen;
   1225 
   1226 	if (n == 0)
   1227 		return(dlen + strlen(s));
   1228 	while (*s != '\0') {
   1229 		if (n != 1) {
   1230 			*d++ = *s;
   1231 			n--;
   1232 		}
   1233 		s++;
   1234 	}
   1235 	*d = '\0';
   1236 
   1237 	return(dlen + (s - src));	/* count does not include NUL */
   1238 }
   1239 #endif /* !HAVE_STRLCAT */
   1240 #if !HAVE_STRLCPY
   1241 /*
   1242  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
   1243  *
   1244  * Permission to use, copy, modify, and distribute this software for any
   1245  * purpose with or without fee is hereby granted, provided that the above
   1246  * copyright notice and this permission notice appear in all copies.
   1247  *
   1248  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1249  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1250  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1251  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1252  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1253  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1254  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1255  */
   1256 
   1257 #include <sys/types.h>
   1258 #include <string.h>
   1259 
   1260 /*
   1261  * Copy src to string dst of size siz.  At most siz-1 characters
   1262  * will be copied.  Always NUL terminates (unless siz == 0).
   1263  * Returns strlen(src); if retval >= siz, truncation occurred.
   1264  */
   1265 size_t
   1266 strlcpy(char *dst, const char *src, size_t siz)
   1267 {
   1268 	char *d = dst;
   1269 	const char *s = src;
   1270 	size_t n = siz;
   1271 
   1272 	/* Copy as many bytes as will fit */
   1273 	if (n != 0) {
   1274 		while (--n != 0) {
   1275 			if ((*d++ = *s++) == '\0')
   1276 				break;
   1277 		}
   1278 	}
   1279 
   1280 	/* Not enough room in dst, add NUL and traverse rest of src */
   1281 	if (n == 0) {
   1282 		if (siz != 0)
   1283 			*d = '\0';		/* NUL-terminate dst */
   1284 		while (*s++)
   1285 			;
   1286 	}
   1287 
   1288 	return(s - src - 1);	/* count does not include NUL */
   1289 }
   1290 #endif /* !HAVE_STRLCPY */
   1291 #if !HAVE_STRNDUP
   1292 /*	$OpenBSD$	*/
   1293 /*
   1294  * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com>
   1295  *
   1296  * Permission to use, copy, modify, and distribute this software for any
   1297  * purpose with or without fee is hereby granted, provided that the above
   1298  * copyright notice and this permission notice appear in all copies.
   1299  *
   1300  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1301  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1302  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1303  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1304  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1305  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1306  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1307  */
   1308 
   1309 #include <sys/types.h>
   1310 
   1311 #include <stddef.h>
   1312 #include <stdlib.h>
   1313 #include <string.h>
   1314 
   1315 char *
   1316 strndup(const char *str, size_t maxlen)
   1317 {
   1318 	char *copy;
   1319 	size_t len;
   1320 
   1321 	len = strnlen(str, maxlen);
   1322 	copy = malloc(len + 1);
   1323 	if (copy != NULL) {
   1324 		(void)memcpy(copy, str, len);
   1325 		copy[len] = '\0';
   1326 	}
   1327 
   1328 	return copy;
   1329 }
   1330 #endif /* !HAVE_STRNDUP */
   1331 #if !HAVE_STRNLEN
   1332 /*	$OpenBSD$	*/
   1333 
   1334 /*
   1335  * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com>
   1336  *
   1337  * Permission to use, copy, modify, and distribute this software for any
   1338  * purpose with or without fee is hereby granted, provided that the above
   1339  * copyright notice and this permission notice appear in all copies.
   1340  *
   1341  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1342  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1343  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1344  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1345  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1346  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1347  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1348  */
   1349 
   1350 #include <sys/types.h>
   1351 #include <string.h>
   1352 
   1353 size_t
   1354 strnlen(const char *str, size_t maxlen)
   1355 {
   1356 	const char *cp;
   1357 
   1358 	for (cp = str; maxlen != 0 && *cp != '\0'; cp++, maxlen--)
   1359 		;
   1360 
   1361 	return (size_t)(cp - str);
   1362 }
   1363 #endif /* !HAVE_STRNLEN */
   1364 #if !HAVE_STRTONUM
   1365 /*
   1366  * Copyright (c) 2004 Ted Unangst and Todd Miller
   1367  * All rights reserved.
   1368  *
   1369  * Permission to use, copy, modify, and distribute this software for any
   1370  * purpose with or without fee is hereby granted, provided that the above
   1371  * copyright notice and this permission notice appear in all copies.
   1372  *
   1373  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   1374  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   1375  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   1376  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   1377  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   1378  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   1379  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
   1380  */
   1381 
   1382 #include <errno.h>
   1383 #include <limits.h>
   1384 #include <stdlib.h>
   1385 
   1386 #define	INVALID		1
   1387 #define	TOOSMALL	2
   1388 #define	TOOLARGE	3
   1389 
   1390 long long
   1391 strtonum(const char *numstr, long long minval, long long maxval,
   1392     const char **errstrp)
   1393 {
   1394 	long long ll = 0;
   1395 	int error = 0;
   1396 	char *ep;
   1397 	struct errval {
   1398 		const char *errstr;
   1399 		int err;
   1400 	} ev[4] = {
   1401 		{ NULL,		0 },
   1402 		{ "invalid",	EINVAL },
   1403 		{ "too small",	ERANGE },
   1404 		{ "too large",	ERANGE },
   1405 	};
   1406 
   1407 	ev[0].err = errno;
   1408 	errno = 0;
   1409 	if (minval > maxval) {
   1410 		error = INVALID;
   1411 	} else {
   1412 		ll = strtoll(numstr, &ep, 10);
   1413 		if (numstr == ep || *ep != '\0')
   1414 			error = INVALID;
   1415 		else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
   1416 			error = TOOSMALL;
   1417 		else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
   1418 			error = TOOLARGE;
   1419 	}
   1420 	if (errstrp != NULL)
   1421 		*errstrp = ev[error].errstr;
   1422 	errno = ev[error].err;
   1423 	if (error)
   1424 		ll = 0;
   1425 
   1426 	return (ll);
   1427 }
   1428 #endif /* !HAVE_STRTONUM */