compats.c (109158B)
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 fprintf(stderr, "\n"); 45 } 46 47 void 48 vwarnc(int code, const char *fmt, va_list ap) 49 { 50 fprintf(stderr, "%s: ", getprogname()); 51 if (fmt != NULL) { 52 vfprintf(stderr, fmt, ap); 53 fprintf(stderr, ": "); 54 } 55 fprintf(stderr, "%s\n", strerror(code)); 56 } 57 58 void 59 vwarn(const char *fmt, va_list ap) 60 { 61 int sverrno; 62 63 sverrno = errno; 64 fprintf(stderr, "%s: ", getprogname()); 65 if (fmt != NULL) { 66 vfprintf(stderr, fmt, ap); 67 fprintf(stderr, ": "); 68 } 69 fprintf(stderr, "%s\n", strerror(sverrno)); 70 } 71 72 void 73 verrc(int eval, int code, const char *fmt, va_list ap) 74 { 75 fprintf(stderr, "%s: ", getprogname()); 76 if (fmt != NULL) { 77 vfprintf(stderr, fmt, ap); 78 fprintf(stderr, ": "); 79 } 80 fprintf(stderr, "%s\n", strerror(code)); 81 exit(eval); 82 } 83 84 void 85 verrx(int eval, const char *fmt, va_list ap) 86 { 87 fprintf(stderr, "%s: ", getprogname()); 88 if (fmt != NULL) 89 vfprintf(stderr, fmt, ap); 90 fprintf(stderr, "\n"); 91 exit(eval); 92 } 93 94 void 95 verr(int eval, const char *fmt, va_list ap) 96 { 97 int sverrno; 98 99 sverrno = errno; 100 fprintf(stderr, "%s: ", getprogname()); 101 if (fmt != NULL) { 102 vfprintf(stderr, fmt, ap); 103 fprintf(stderr, ": "); 104 } 105 fprintf(stderr, "%s\n", strerror(sverrno)); 106 exit(eval); 107 } 108 109 void 110 err(int eval, const char *fmt, ...) 111 { 112 va_list ap; 113 114 va_start(ap, fmt); 115 verr(eval, fmt, ap); 116 va_end(ap); 117 } 118 119 void 120 errc(int eval, int code, const char *fmt, ...) 121 { 122 va_list ap; 123 124 va_start(ap, fmt); 125 verrc(eval, code, fmt, ap); 126 va_end(ap); 127 } 128 129 void 130 errx(int eval, const char *fmt, ...) 131 { 132 va_list ap; 133 134 va_start(ap, fmt); 135 verrx(eval, fmt, ap); 136 va_end(ap); 137 } 138 139 void 140 warn(const char *fmt, ...) 141 { 142 va_list ap; 143 144 va_start(ap, fmt); 145 vwarn(fmt, ap); 146 va_end(ap); 147 } 148 149 void 150 warnc(int code, const char *fmt, ...) 151 { 152 va_list ap; 153 154 va_start(ap, fmt); 155 vwarnc(code, fmt, ap); 156 va_end(ap); 157 } 158 159 void 160 warnx(const char *fmt, ...) 161 { 162 va_list ap; 163 164 va_start(ap, fmt); 165 vwarnx(fmt, ap); 166 va_end(ap); 167 } 168 #endif /* !HAVE_ERR */ 169 #if !HAVE_B64_NTOP 170 /* $OpenBSD$ */ 171 172 /* 173 * Copyright (c) 1996 by Internet Software Consortium. 174 * 175 * Permission to use, copy, modify, and distribute this software for any 176 * purpose with or without fee is hereby granted, provided that the above 177 * copyright notice and this permission notice appear in all copies. 178 * 179 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS 180 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES 181 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE 182 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL 183 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR 184 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS 185 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS 186 * SOFTWARE. 187 */ 188 189 /* 190 * Portions Copyright (c) 1995 by International Business Machines, Inc. 191 * 192 * International Business Machines, Inc. (hereinafter called IBM) grants 193 * permission under its copyrights to use, copy, modify, and distribute this 194 * Software with or without fee, provided that the above copyright notice and 195 * all paragraphs of this notice appear in all copies, and that the name of IBM 196 * not be used in connection with the marketing of any product incorporating 197 * the Software or modifications thereof, without specific, written prior 198 * permission. 199 * 200 * To the extent it has a right to do so, IBM grants an immunity from suit 201 * under its patents, if any, for the use, sale or manufacture of products to 202 * the extent that such products are used for performing Domain Name System 203 * dynamic updates in TCP/IP networks by means of the Software. No immunity is 204 * granted for any product per se or for any other function of any product. 205 * 206 * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, 207 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 208 * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, 209 * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING 210 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN 211 * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. 212 */ 213 214 #include <sys/types.h> 215 #include <sys/socket.h> 216 #include <netinet/in.h> 217 #include <arpa/inet.h> 218 #include <arpa/nameser.h> 219 220 #include <ctype.h> 221 #include <resolv.h> 222 #include <stdio.h> 223 224 #include <stdlib.h> 225 #include <string.h> 226 227 static const char b64_Base64[] = 228 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 229 static const char b64_Pad64 = '='; 230 231 /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) 232 The following encoding technique is taken from RFC 1521 by Borenstein 233 and Freed. It is reproduced here in a slightly edited form for 234 convenience. 235 236 A 65-character subset of US-ASCII is used, enabling 6 bits to be 237 represented per printable character. (The extra 65th character, "=", 238 is used to signify a special processing function.) 239 240 The encoding process represents 24-bit groups of input bits as output 241 strings of 4 encoded characters. Proceeding from left to right, a 242 24-bit input group is formed by concatenating 3 8-bit input groups. 243 These 24 bits are then treated as 4 concatenated 6-bit groups, each 244 of which is translated into a single digit in the base64 alphabet. 245 246 Each 6-bit group is used as an index into an array of 64 printable 247 characters. The character referenced by the index is placed in the 248 output string. 249 250 Table 1: The Base64 Alphabet 251 252 Value Encoding Value Encoding Value Encoding Value Encoding 253 0 A 17 R 34 i 51 z 254 1 B 18 S 35 j 52 0 255 2 C 19 T 36 k 53 1 256 3 D 20 U 37 l 54 2 257 4 E 21 V 38 m 55 3 258 5 F 22 W 39 n 56 4 259 6 G 23 X 40 o 57 5 260 7 H 24 Y 41 p 58 6 261 8 I 25 Z 42 q 59 7 262 9 J 26 a 43 r 60 8 263 10 K 27 b 44 s 61 9 264 11 L 28 c 45 t 62 + 265 12 M 29 d 46 u 63 / 266 13 N 30 e 47 v 267 14 O 31 f 48 w (pad) = 268 15 P 32 g 49 x 269 16 Q 33 h 50 y 270 271 Special processing is performed if fewer than 24 bits are available 272 at the end of the data being encoded. A full encoding quantum is 273 always completed at the end of a quantity. When fewer than 24 input 274 bits are available in an input group, zero bits are added (on the 275 right) to form an integral number of 6-bit groups. Padding at the 276 end of the data is performed using the '=' character. 277 278 Since all base64 input is an integral number of octets, only the 279 ------------------------------------------------- 280 following cases can arise: 281 282 (1) the final quantum of encoding input is an integral 283 multiple of 24 bits; here, the final unit of encoded 284 output will be an integral multiple of 4 characters 285 with no "=" padding, 286 (2) the final quantum of encoding input is exactly 8 bits; 287 here, the final unit of encoded output will be two 288 characters followed by two "=" padding characters, or 289 (3) the final quantum of encoding input is exactly 16 bits; 290 here, the final unit of encoded output will be three 291 characters followed by one "=" padding character. 292 */ 293 294 int 295 b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize) 296 { 297 size_t datalength = 0; 298 u_char input[3]; 299 u_char output[4]; 300 size_t i; 301 302 while (2 < srclength) { 303 input[0] = *src++; 304 input[1] = *src++; 305 input[2] = *src++; 306 srclength -= 3; 307 308 output[0] = input[0] >> 2; 309 output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); 310 output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); 311 output[3] = input[2] & 0x3f; 312 313 if (datalength + 4 > targsize) 314 return (-1); 315 target[datalength++] = b64_Base64[output[0]]; 316 target[datalength++] = b64_Base64[output[1]]; 317 target[datalength++] = b64_Base64[output[2]]; 318 target[datalength++] = b64_Base64[output[3]]; 319 } 320 321 /* Now we worry about padding. */ 322 if (0 != srclength) { 323 /* Get what's left. */ 324 input[0] = input[1] = input[2] = '\0'; 325 for (i = 0; i < srclength; i++) 326 input[i] = *src++; 327 328 output[0] = input[0] >> 2; 329 output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); 330 output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); 331 332 if (datalength + 4 > targsize) 333 return (-1); 334 target[datalength++] = b64_Base64[output[0]]; 335 target[datalength++] = b64_Base64[output[1]]; 336 if (srclength == 1) 337 target[datalength++] = b64_Pad64; 338 else 339 target[datalength++] = b64_Base64[output[2]]; 340 target[datalength++] = b64_Pad64; 341 } 342 if (datalength >= targsize) 343 return (-1); 344 target[datalength] = '\0'; /* Returned value doesn't count \0. */ 345 return (datalength); 346 } 347 348 /* skips all whitespace anywhere. 349 converts characters, four at a time, starting at (or after) 350 src from base - 64 numbers into three 8 bit bytes in the target area. 351 it returns the number of data bytes stored at the target, or -1 on error. 352 */ 353 354 int 355 b64_pton(char const *src, u_char *target, size_t targsize) 356 { 357 int state, ch; 358 size_t tarindex; 359 u_char nextbyte; 360 char *pos; 361 362 state = 0; 363 tarindex = 0; 364 365 while ((ch = (unsigned char)*src++) != '\0') { 366 if (isspace(ch)) /* Skip whitespace anywhere. */ 367 continue; 368 369 if (ch == b64_Pad64) 370 break; 371 372 pos = strchr(b64_Base64, ch); 373 if (pos == 0) /* A non-base64 character. */ 374 return (-1); 375 376 switch (state) { 377 case 0: 378 if (target) { 379 if (tarindex >= targsize) 380 return (-1); 381 target[tarindex] = (pos - b64_Base64) << 2; 382 } 383 state = 1; 384 break; 385 case 1: 386 if (target) { 387 if (tarindex >= targsize) 388 return (-1); 389 target[tarindex] |= (pos - b64_Base64) >> 4; 390 nextbyte = ((pos - b64_Base64) & 0x0f) << 4; 391 if (tarindex + 1 < targsize) 392 target[tarindex+1] = nextbyte; 393 else if (nextbyte) 394 return (-1); 395 } 396 tarindex++; 397 state = 2; 398 break; 399 case 2: 400 if (target) { 401 if (tarindex >= targsize) 402 return (-1); 403 target[tarindex] |= (pos - b64_Base64) >> 2; 404 nextbyte = ((pos - b64_Base64) & 0x03) << 6; 405 if (tarindex + 1 < targsize) 406 target[tarindex+1] = nextbyte; 407 else if (nextbyte) 408 return (-1); 409 } 410 tarindex++; 411 state = 3; 412 break; 413 case 3: 414 if (target) { 415 if (tarindex >= targsize) 416 return (-1); 417 target[tarindex] |= (pos - b64_Base64); 418 } 419 tarindex++; 420 state = 0; 421 break; 422 } 423 } 424 425 /* 426 * We are done decoding Base-64 chars. Let's see if we ended 427 * on a byte boundary, and/or with erroneous trailing characters. 428 */ 429 430 if (ch == b64_Pad64) { /* We got a pad char. */ 431 ch = (unsigned char)*src++; /* Skip it, get next. */ 432 switch (state) { 433 case 0: /* Invalid = in first position */ 434 case 1: /* Invalid = in second position */ 435 return (-1); 436 437 case 2: /* Valid, means one byte of info */ 438 /* Skip any number of spaces. */ 439 for (; ch != '\0'; ch = (unsigned char)*src++) 440 if (!isspace(ch)) 441 break; 442 /* Make sure there is another trailing = sign. */ 443 if (ch != b64_Pad64) 444 return (-1); 445 ch = (unsigned char)*src++; /* Skip the = */ 446 /* Fall through to "single trailing =" case. */ 447 /* FALLTHROUGH */ 448 449 case 3: /* Valid, means two bytes of info */ 450 /* 451 * We know this char is an =. Is there anything but 452 * whitespace after it? 453 */ 454 for (; ch != '\0'; ch = (unsigned char)*src++) 455 if (!isspace(ch)) 456 return (-1); 457 458 /* 459 * Now make sure for cases 2 and 3 that the "extra" 460 * bits that slopped past the last full byte were 461 * zeros. If we don't check them, they become a 462 * subliminal channel. 463 */ 464 if (target && tarindex < targsize && 465 target[tarindex] != 0) 466 return (-1); 467 } 468 } else { 469 /* 470 * We ended by seeing the end of the string. Make sure we 471 * have no partial bytes lying around. 472 */ 473 if (state != 0) 474 return (-1); 475 } 476 477 return (tarindex); 478 } 479 #endif /* !HAVE_B64_NTOP */ 480 #if !HAVE_EXPLICIT_BZERO 481 /* OPENBSD ORIGINAL: lib/libc/string/explicit_bzero.c */ 482 /* 483 * Public domain. 484 * Written by Ted Unangst 485 */ 486 487 #include <string.h> 488 489 /* 490 * explicit_bzero - don't let the compiler optimize away bzero 491 */ 492 493 #if HAVE_MEMSET_S 494 495 void 496 explicit_bzero(void *p, size_t n) 497 { 498 if (n == 0) 499 return; 500 (void)memset_s(p, n, 0, n); 501 } 502 503 #else /* HAVE_MEMSET_S */ 504 505 #include <strings.h> 506 507 /* 508 * Indirect bzero through a volatile pointer to hopefully avoid 509 * dead-store optimisation eliminating the call. 510 */ 511 static void (* volatile ssh_bzero)(void *, size_t) = bzero; 512 513 void 514 explicit_bzero(void *p, size_t n) 515 { 516 if (n == 0) 517 return; 518 /* 519 * clang -fsanitize=memory needs to intercept memset-like functions 520 * to correctly detect memory initialisation. Make sure one is called 521 * directly since our indirection trick above sucessfully confuses it. 522 */ 523 #if defined(__has_feature) 524 # if __has_feature(memory_sanitizer) 525 memset(p, 0, n); 526 # endif 527 #endif 528 529 ssh_bzero(p, n); 530 } 531 532 #endif /* HAVE_MEMSET_S */ 533 #endif /* !HAVE_EXPLICIT_BZERO */ 534 #if !HAVE_FTS 535 /* $OpenBSD$ */ 536 537 /*- 538 * Copyright (c) 1990, 1993, 1994 539 * The Regents of the University of California. All rights reserved. 540 * 541 * Redistribution and use in source and binary forms, with or without 542 * modification, are permitted provided that the following conditions 543 * are met: 544 * 1. Redistributions of source code must retain the above copyright 545 * notice, this list of conditions and the following disclaimer. 546 * 2. Redistributions in binary form must reproduce the above copyright 547 * notice, this list of conditions and the following disclaimer in the 548 * documentation and/or other materials provided with the distribution. 549 * 3. Neither the name of the University nor the names of its contributors 550 * may be used to endorse or promote products derived from this software 551 * without specific prior written permission. 552 * 553 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 554 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 555 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 556 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 557 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 558 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 559 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 560 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 561 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 562 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 563 * SUCH DAMAGE. 564 */ 565 566 #include <sys/stat.h> 567 #include <sys/types.h> 568 569 #include <dirent.h> 570 #include <errno.h> 571 #include <fcntl.h> 572 #include <limits.h> 573 #include <stdlib.h> 574 #include <string.h> 575 #include <unistd.h> 576 577 /* 578 * oconfigure: Adapted from sys/_types.h. 579 * oconfigure: Be conservative with ALIGNBYTES. 580 */ 581 #define FTS_ALIGNBYTES (sizeof(long) - 1) 582 #define FTS_ALIGN(p) (((unsigned long)(p) + FTS_ALIGNBYTES) &~ FTS_ALIGNBYTES) 583 584 static FTSENT *fts_alloc(FTS *, char *, size_t); 585 static FTSENT *fts_build(FTS *, int); 586 static void fts_lfree(FTSENT *); 587 static void fts_load(FTS *, FTSENT *); 588 static size_t fts_maxarglen(char * const *); 589 static void fts_padjust(FTS *, FTSENT *); 590 static int fts_palloc(FTS *, size_t); 591 static FTSENT *fts_sort(FTS *, FTSENT *, int); 592 static u_short fts_stat(FTS *, FTSENT *, int, int); 593 static int fts_safe_changedir(FTS *, FTSENT *, int, char *); 594 595 /* oconfigure: Prefix with FTS_. */ 596 597 #define FTS_MAX(a, b) (((a) > (b)) ? (a) : (b)) 598 #define FTS_ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2]))) 599 #define FTS_CLR(opt) (sp->fts_options &= ~(opt)) 600 #define FTS_ISSET(opt) (sp->fts_options & (opt)) 601 #define FTS_SET(opt) (sp->fts_options |= (opt)) 602 #define FTS_FCHDIR(sp, fd) (!FTS_ISSET(FTS_NOCHDIR) && fchdir(fd)) 603 /* fts_build flags */ 604 #define FTS_BCHILD 1 /* fts_children */ 605 #define FTS_BNAMES 2 /* fts_children, names only */ 606 #define FTS_BREAD 3 /* fts_read */ 607 608 FTS * 609 fts_open(char * const *argv, int options, 610 int (*compar)(const FTSENT **, const FTSENT **)) 611 { 612 FTS *sp; 613 FTSENT *p, *root; 614 int nitems; 615 FTSENT *parent, *prev; 616 char empty[1] = { '\0' }; 617 618 /* Options check. */ 619 if (options & ~FTS_OPTIONMASK) { 620 errno = EINVAL; 621 return (NULL); 622 } 623 624 /* At least one path must be specified. */ 625 if (*argv == NULL) { 626 errno = EINVAL; 627 return (NULL); 628 } 629 630 /* Allocate/initialize the stream */ 631 if ((sp = calloc(1, sizeof(FTS))) == NULL) 632 return (NULL); 633 sp->fts_compar = compar; 634 sp->fts_options = options; 635 636 /* Logical walks turn on NOCHDIR; symbolic links are too hard. */ 637 if (FTS_ISSET(FTS_LOGICAL)) 638 FTS_SET(FTS_NOCHDIR); 639 640 /* 641 * Start out with 1K of path space, and enough, in any case, 642 * to hold the user's paths. 643 */ 644 if (fts_palloc(sp, FTS_MAX(fts_maxarglen(argv), PATH_MAX))) 645 goto mem1; 646 647 /* Allocate/initialize root's parent. */ 648 if ((parent = fts_alloc(sp, empty, 0)) == NULL) 649 goto mem2; 650 parent->fts_level = FTS_ROOTPARENTLEVEL; 651 652 /* Allocate/initialize root(s). */ 653 for (root = prev = NULL, nitems = 0; *argv; ++argv, ++nitems) { 654 if ((p = fts_alloc(sp, *argv, strlen(*argv))) == NULL) 655 goto mem3; 656 p->fts_level = FTS_ROOTLEVEL; 657 p->fts_parent = parent; 658 p->fts_accpath = p->fts_name; 659 p->fts_info = fts_stat(sp, p, FTS_ISSET(FTS_COMFOLLOW), -1); 660 661 /* Command-line "." and ".." are real directories. */ 662 if (p->fts_info == FTS_DOT) 663 p->fts_info = FTS_D; 664 665 /* 666 * If comparison routine supplied, traverse in sorted 667 * order; otherwise traverse in the order specified. 668 */ 669 if (compar) { 670 p->fts_link = root; 671 root = p; 672 } else { 673 p->fts_link = NULL; 674 if (root == NULL) 675 root = p; 676 else 677 prev->fts_link = p; 678 prev = p; 679 } 680 } 681 if (compar && nitems > 1) 682 root = fts_sort(sp, root, nitems); 683 684 /* 685 * Allocate a dummy pointer and make fts_read think that we've just 686 * finished the node before the root(s); set p->fts_info to FTS_INIT 687 * so that everything about the "current" node is ignored. 688 */ 689 if ((sp->fts_cur = fts_alloc(sp, empty, 0)) == NULL) 690 goto mem3; 691 sp->fts_cur->fts_link = root; 692 sp->fts_cur->fts_info = FTS_INIT; 693 694 /* 695 * If using chdir(2), grab a file descriptor pointing to dot to ensure 696 * that we can get back here; this could be avoided for some paths, 697 * but almost certainly not worth the effort. Slashes, symbolic links, 698 * and ".." are all fairly nasty problems. Note, if we can't get the 699 * descriptor we run anyway, just more slowly. 700 */ 701 if (!FTS_ISSET(FTS_NOCHDIR) && 702 (sp->fts_rfd = open(".", O_RDONLY | O_CLOEXEC)) == -1) 703 FTS_SET(FTS_NOCHDIR); 704 705 if (nitems == 0) 706 free(parent); 707 708 return (sp); 709 710 mem3: fts_lfree(root); 711 free(parent); 712 mem2: free(sp->fts_path); 713 mem1: free(sp); 714 return (NULL); 715 } 716 717 static void 718 fts_load(FTS *sp, FTSENT *p) 719 { 720 size_t len; 721 char *cp; 722 723 /* 724 * Load the stream structure for the next traversal. Since we don't 725 * actually enter the directory until after the preorder visit, set 726 * the fts_accpath field specially so the chdir gets done to the right 727 * place and the user can access the first node. From fts_open it's 728 * known that the path will fit. 729 */ 730 len = p->fts_pathlen = p->fts_namelen; 731 memmove(sp->fts_path, p->fts_name, len + 1); 732 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) { 733 len = strlen(++cp); 734 memmove(p->fts_name, cp, len + 1); 735 p->fts_namelen = len; 736 } 737 p->fts_accpath = p->fts_path = sp->fts_path; 738 sp->fts_dev = p->fts_dev; 739 } 740 741 int 742 fts_close(FTS *sp) 743 { 744 FTSENT *freep, *p; 745 int rfd, error = 0; 746 747 /* 748 * This still works if we haven't read anything -- the dummy structure 749 * points to the root list, so we step through to the end of the root 750 * list which has a valid parent pointer. 751 */ 752 if (sp->fts_cur) { 753 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) { 754 freep = p; 755 p = p->fts_link ? p->fts_link : p->fts_parent; 756 free(freep); 757 } 758 free(p); 759 } 760 761 /* Stash the original directory fd if needed. */ 762 rfd = FTS_ISSET(FTS_NOCHDIR) ? -1 : sp->fts_rfd; 763 764 /* Free up child linked list, sort array, path buffer, stream ptr.*/ 765 if (sp->fts_child) 766 fts_lfree(sp->fts_child); 767 free(sp->fts_array); 768 free(sp->fts_path); 769 free(sp); 770 771 /* Return to original directory, checking for error. */ 772 if (rfd != -1) { 773 int saved_errno; 774 error = fchdir(rfd); 775 saved_errno = errno; 776 (void)close(rfd); 777 errno = saved_errno; 778 } 779 780 return (error); 781 } 782 783 /* 784 * Special case of "/" at the end of the path so that slashes aren't 785 * appended which would cause paths to be written as "....//foo". 786 */ 787 #define NAPPEND(p) \ 788 (p->fts_path[p->fts_pathlen - 1] == '/' \ 789 ? p->fts_pathlen - 1 : p->fts_pathlen) 790 791 FTSENT * 792 fts_read(FTS *sp) 793 { 794 FTSENT *p, *tmp; 795 int instr; 796 char *t; 797 char up[3] = { '.', '.', '\0' }; 798 int saved_errno; 799 800 /* If finished or unrecoverable error, return NULL. */ 801 if (sp->fts_cur == NULL || FTS_ISSET(FTS_STOP)) 802 return (NULL); 803 804 /* Set current node pointer. */ 805 p = sp->fts_cur; 806 807 /* Save and zero out user instructions. */ 808 instr = p->fts_instr; 809 p->fts_instr = FTS_NOINSTR; 810 811 /* Any type of file may be re-visited; re-stat and re-turn. */ 812 if (instr == FTS_AGAIN) { 813 p->fts_info = fts_stat(sp, p, 0, -1); 814 return (p); 815 } 816 817 /* 818 * Following a symlink -- SLNONE test allows application to see 819 * SLNONE and recover. If indirecting through a symlink, have 820 * keep a pointer to current location. If unable to get that 821 * pointer, follow fails. 822 */ 823 if (instr == FTS_FOLLOW && 824 (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) { 825 p->fts_info = fts_stat(sp, p, 1, -1); 826 if (p->fts_info == FTS_D && !FTS_ISSET(FTS_NOCHDIR)) { 827 if ((p->fts_symfd = 828 open(".", O_RDONLY | O_CLOEXEC)) == -1) { 829 p->fts_errno = errno; 830 p->fts_info = FTS_ERR; 831 } else 832 p->fts_flags |= FTS_SYMFOLLOW; 833 } 834 return (p); 835 } 836 837 /* Directory in pre-order. */ 838 if (p->fts_info == FTS_D) { 839 /* If skipped or crossed mount point, do post-order visit. */ 840 if (instr == FTS_SKIP || 841 (FTS_ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) { 842 if (p->fts_flags & FTS_SYMFOLLOW) 843 (void)close(p->fts_symfd); 844 if (sp->fts_child) { 845 fts_lfree(sp->fts_child); 846 sp->fts_child = NULL; 847 } 848 p->fts_info = FTS_DP; 849 return (p); 850 } 851 852 /* Rebuild if only read the names and now traversing. */ 853 if (sp->fts_child && FTS_ISSET(FTS_NAMEONLY)) { 854 FTS_CLR(FTS_NAMEONLY); 855 fts_lfree(sp->fts_child); 856 sp->fts_child = NULL; 857 } 858 859 /* 860 * Cd to the subdirectory. 861 * 862 * If have already read and now fail to chdir, whack the list 863 * to make the names come out right, and set the parent errno 864 * so the application will eventually get an error condition. 865 * Set the FTS_DONTCHDIR flag so that when we logically change 866 * directories back to the parent we don't do a chdir. 867 * 868 * If haven't read do so. If the read fails, fts_build sets 869 * FTS_STOP or the fts_info field of the node. 870 */ 871 if (sp->fts_child) { 872 if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) { 873 p->fts_errno = errno; 874 p->fts_flags |= FTS_DONTCHDIR; 875 for (p = sp->fts_child; p; p = p->fts_link) 876 p->fts_accpath = 877 p->fts_parent->fts_accpath; 878 } 879 } else if ((sp->fts_child = fts_build(sp, FTS_BREAD)) == NULL) { 880 if (FTS_ISSET(FTS_STOP)) 881 return (NULL); 882 return (p); 883 } 884 p = sp->fts_child; 885 sp->fts_child = NULL; 886 goto name; 887 } 888 889 /* Move to the next node on this level. */ 890 next: tmp = p; 891 if ((p = p->fts_link)) { 892 free(tmp); 893 894 /* 895 * If reached the top, return to the original directory (or 896 * the root of the tree), and load the paths for the next root. 897 */ 898 if (p->fts_level == FTS_ROOTLEVEL) { 899 if (FTS_FCHDIR(sp, sp->fts_rfd)) { 900 FTS_SET(FTS_STOP); 901 return (NULL); 902 } 903 fts_load(sp, p); 904 return (sp->fts_cur = p); 905 } 906 907 /* 908 * User may have called fts_set on the node. If skipped, 909 * ignore. If followed, get a file descriptor so we can 910 * get back if necessary. 911 */ 912 if (p->fts_instr == FTS_SKIP) 913 goto next; 914 if (p->fts_instr == FTS_FOLLOW) { 915 p->fts_info = fts_stat(sp, p, 1, -1); 916 if (p->fts_info == FTS_D && !FTS_ISSET(FTS_NOCHDIR)) { 917 if ((p->fts_symfd = 918 open(".", O_RDONLY | O_CLOEXEC)) == -1) { 919 p->fts_errno = errno; 920 p->fts_info = FTS_ERR; 921 } else 922 p->fts_flags |= FTS_SYMFOLLOW; 923 } 924 p->fts_instr = FTS_NOINSTR; 925 } 926 927 name: t = sp->fts_path + NAPPEND(p->fts_parent); 928 *t++ = '/'; 929 memmove(t, p->fts_name, p->fts_namelen + 1); 930 return (sp->fts_cur = p); 931 } 932 933 /* Move up to the parent node. */ 934 p = tmp->fts_parent; 935 free(tmp); 936 937 if (p->fts_level == FTS_ROOTPARENTLEVEL) { 938 /* 939 * Done; free everything up and set errno to 0 so the user 940 * can distinguish between error and EOF. 941 */ 942 free(p); 943 errno = 0; 944 return (sp->fts_cur = NULL); 945 } 946 947 /* NUL terminate the pathname. */ 948 sp->fts_path[p->fts_pathlen] = '\0'; 949 950 /* 951 * Return to the parent directory. If at a root node or came through 952 * a symlink, go back through the file descriptor. Otherwise, cd up 953 * one directory. 954 */ 955 if (p->fts_level == FTS_ROOTLEVEL) { 956 if (FTS_FCHDIR(sp, sp->fts_rfd)) { 957 FTS_SET(FTS_STOP); 958 sp->fts_cur = p; 959 return (NULL); 960 } 961 } else if (p->fts_flags & FTS_SYMFOLLOW) { 962 if (FTS_FCHDIR(sp, p->fts_symfd)) { 963 saved_errno = errno; 964 (void)close(p->fts_symfd); 965 errno = saved_errno; 966 FTS_SET(FTS_STOP); 967 sp->fts_cur = p; 968 return (NULL); 969 } 970 (void)close(p->fts_symfd); 971 } else if (!(p->fts_flags & FTS_DONTCHDIR) && 972 fts_safe_changedir(sp, p->fts_parent, -1, up)) { 973 FTS_SET(FTS_STOP); 974 sp->fts_cur = p; 975 return (NULL); 976 } 977 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP; 978 return (sp->fts_cur = p); 979 } 980 981 /* 982 * Fts_set takes the stream as an argument although it's not used in this 983 * implementation; it would be necessary if anyone wanted to add global 984 * semantics to fts using fts_set. An error return is allowed for similar 985 * reasons. 986 */ 987 int 988 fts_set(FTS *sp, FTSENT *p, int instr) 989 { 990 if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW && 991 instr != FTS_NOINSTR && instr != FTS_SKIP) { 992 errno = EINVAL; 993 return (1); 994 } 995 p->fts_instr = instr; 996 return (0); 997 } 998 999 FTSENT * 1000 fts_children(FTS *sp, int instr) 1001 { 1002 FTSENT *p; 1003 int fd; 1004 1005 if (instr && instr != FTS_NAMEONLY) { 1006 errno = EINVAL; 1007 return (NULL); 1008 } 1009 1010 /* Set current node pointer. */ 1011 p = sp->fts_cur; 1012 1013 /* 1014 * Errno set to 0 so user can distinguish empty directory from 1015 * an error. 1016 */ 1017 errno = 0; 1018 1019 /* Fatal errors stop here. */ 1020 if (FTS_ISSET(FTS_STOP)) 1021 return (NULL); 1022 1023 /* Return logical hierarchy of user's arguments. */ 1024 if (p->fts_info == FTS_INIT) 1025 return (p->fts_link); 1026 1027 /* 1028 * If not a directory being visited in pre-order, stop here. Could 1029 * allow FTS_DNR, assuming the user has fixed the problem, but the 1030 * same effect is available with FTS_AGAIN. 1031 */ 1032 if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */) 1033 return (NULL); 1034 1035 /* Free up any previous child list. */ 1036 if (sp->fts_child) 1037 fts_lfree(sp->fts_child); 1038 1039 if (instr == FTS_NAMEONLY) { 1040 FTS_SET(FTS_NAMEONLY); 1041 instr = FTS_BNAMES; 1042 } else 1043 instr = FTS_BCHILD; 1044 1045 /* 1046 * If using chdir on a relative path and called BEFORE fts_read does 1047 * its chdir to the root of a traversal, we can lose -- we need to 1048 * chdir into the subdirectory, and we don't know where the current 1049 * directory is, so we can't get back so that the upcoming chdir by 1050 * fts_read will work. 1051 */ 1052 if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' || 1053 FTS_ISSET(FTS_NOCHDIR)) 1054 return (sp->fts_child = fts_build(sp, instr)); 1055 1056 if ((fd = open(".", O_RDONLY | O_CLOEXEC)) == -1) 1057 return (NULL); 1058 sp->fts_child = fts_build(sp, instr); 1059 if (fchdir(fd)) { 1060 (void)close(fd); 1061 return (NULL); 1062 } 1063 (void)close(fd); 1064 return (sp->fts_child); 1065 } 1066 1067 /* 1068 * This is the tricky part -- do not casually change *anything* in here. The 1069 * idea is to build the linked list of entries that are used by fts_children 1070 * and fts_read. There are lots of special cases. 1071 * 1072 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is 1073 * set and it's a physical walk (so that symbolic links can't be directories), 1074 * we can do things quickly. First, if it's a 4.4BSD file system, the type 1075 * of the file is in the directory entry. Otherwise, we assume that the number 1076 * of subdirectories in a node is equal to the number of links to the parent. 1077 * The former skips all stat calls. The latter skips stat calls in any leaf 1078 * directories and for any files after the subdirectories in the directory have 1079 * been found, cutting the stat calls by about 2/3. 1080 */ 1081 static FTSENT * 1082 fts_build(FTS *sp, int type) 1083 { 1084 struct dirent *dp; 1085 FTSENT *p, *head; 1086 FTSENT *cur, *tail; 1087 DIR *dirp; 1088 void *oldaddr; 1089 size_t len, maxlen, namlen; 1090 int nitems, cderrno, descend, level, nlinks, nostat, doadjust; 1091 int saved_errno; 1092 char *cp; 1093 char up[3] = { '.', '.', '\0' }; 1094 1095 /* Set current node pointer. */ 1096 cur = sp->fts_cur; 1097 1098 /* 1099 * Open the directory for reading. If this fails, we're done. 1100 * If being called from fts_read, set the fts_info field. 1101 */ 1102 if ((dirp = opendir(cur->fts_accpath)) == NULL) { 1103 if (type == FTS_BREAD) { 1104 cur->fts_info = FTS_DNR; 1105 cur->fts_errno = errno; 1106 } 1107 return (NULL); 1108 } 1109 1110 /* 1111 * Nlinks is the number of possible entries of type directory in the 1112 * directory if we're cheating on stat calls, 0 if we're not doing 1113 * any stat calls at all, -1 if we're doing stats on everything. 1114 */ 1115 if (type == FTS_BNAMES) 1116 nlinks = 0; 1117 else if (FTS_ISSET(FTS_NOSTAT) && FTS_ISSET(FTS_PHYSICAL)) { 1118 nlinks = cur->fts_nlink - (FTS_ISSET(FTS_SEEDOT) ? 0 : 2); 1119 nostat = 1; 1120 } else { 1121 nlinks = -1; 1122 nostat = 0; 1123 } 1124 1125 #ifdef notdef 1126 (void)printf("nlinks == %d (cur: %u)\n", nlinks, cur->fts_nlink); 1127 (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n", 1128 FTS_ISSET(FTS_NOSTAT), FTS_ISSET(FTS_PHYSICAL), FTS_ISSET(FTS_SEEDOT)); 1129 #endif 1130 /* 1131 * If we're going to need to stat anything or we want to descend 1132 * and stay in the directory, chdir. If this fails we keep going, 1133 * but set a flag so we don't chdir after the post-order visit. 1134 * We won't be able to stat anything, but we can still return the 1135 * names themselves. Note, that since fts_read won't be able to 1136 * chdir into the directory, it will have to return different path 1137 * names than before, i.e. "a/b" instead of "b". Since the node 1138 * has already been visited in pre-order, have to wait until the 1139 * post-order visit to return the error. There is a special case 1140 * here, if there was nothing to stat then it's not an error to 1141 * not be able to stat. This is all fairly nasty. If a program 1142 * needed sorted entries or stat information, they had better be 1143 * checking FTS_NS on the returned nodes. 1144 */ 1145 cderrno = 0; 1146 if (nlinks || type == FTS_BREAD) { 1147 if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) { 1148 if (nlinks && type == FTS_BREAD) 1149 cur->fts_errno = errno; 1150 cur->fts_flags |= FTS_DONTCHDIR; 1151 descend = 0; 1152 cderrno = errno; 1153 (void)closedir(dirp); 1154 dirp = NULL; 1155 } else 1156 descend = 1; 1157 } else 1158 descend = 0; 1159 1160 /* 1161 * Figure out the max file name length that can be stored in the 1162 * current path -- the inner loop allocates more path as necessary. 1163 * We really wouldn't have to do the maxlen calculations here, we 1164 * could do them in fts_read before returning the path, but it's a 1165 * lot easier here since the length is part of the dirent structure. 1166 * 1167 * If not changing directories set a pointer so that can just append 1168 * each new name into the path. 1169 */ 1170 len = NAPPEND(cur); 1171 if (FTS_ISSET(FTS_NOCHDIR)) { 1172 cp = sp->fts_path + len; 1173 *cp++ = '/'; 1174 } 1175 len++; 1176 maxlen = sp->fts_pathlen - len; 1177 1178 /* 1179 * fts_level is signed so we must prevent it from wrapping 1180 * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL. 1181 */ 1182 level = cur->fts_level; 1183 if (level < FTS_MAXLEVEL) 1184 level++; 1185 1186 /* Read the directory, attaching each entry to the `link' pointer. */ 1187 doadjust = 0; 1188 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) { 1189 if (!FTS_ISSET(FTS_SEEDOT) && FTS_ISDOT(dp->d_name)) 1190 continue; 1191 1192 namlen = strlen(dp->d_name); 1193 1194 if (!(p = fts_alloc(sp, dp->d_name, namlen))) 1195 goto mem1; 1196 if (namlen >= maxlen) { /* include space for NUL */ 1197 oldaddr = sp->fts_path; 1198 if (fts_palloc(sp, namlen +len + 1)) { 1199 /* 1200 * No more memory for path or structures. Save 1201 * errno, free up the current structure and the 1202 * structures already allocated. 1203 */ 1204 mem1: saved_errno = errno; 1205 free(p); 1206 fts_lfree(head); 1207 (void)closedir(dirp); 1208 cur->fts_info = FTS_ERR; 1209 FTS_SET(FTS_STOP); 1210 errno = saved_errno; 1211 return (NULL); 1212 } 1213 /* Did realloc() change the pointer? */ 1214 if (oldaddr != sp->fts_path) { 1215 doadjust = 1; 1216 if (FTS_ISSET(FTS_NOCHDIR)) 1217 cp = sp->fts_path + len; 1218 } 1219 maxlen = sp->fts_pathlen - len; 1220 } 1221 1222 p->fts_level = level; 1223 p->fts_parent = sp->fts_cur; 1224 p->fts_pathlen = len + namlen; 1225 if (p->fts_pathlen < len) { 1226 /* 1227 * If we wrap, free up the current structure and 1228 * the structures already allocated, then error 1229 * out with ENAMETOOLONG. 1230 */ 1231 free(p); 1232 fts_lfree(head); 1233 (void)closedir(dirp); 1234 cur->fts_info = FTS_ERR; 1235 FTS_SET(FTS_STOP); 1236 errno = ENAMETOOLONG; 1237 return (NULL); 1238 } 1239 1240 if (cderrno) { 1241 if (nlinks) { 1242 p->fts_info = FTS_NS; 1243 p->fts_errno = cderrno; 1244 } else 1245 p->fts_info = FTS_NSOK; 1246 p->fts_accpath = cur->fts_accpath; 1247 } else if (nlinks == 0 1248 #ifdef DT_DIR 1249 || (nostat && 1250 dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN) 1251 #endif 1252 ) { 1253 p->fts_accpath = 1254 FTS_ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name; 1255 p->fts_info = FTS_NSOK; 1256 } else { 1257 /* Build a file name for fts_stat to stat. */ 1258 if (FTS_ISSET(FTS_NOCHDIR)) { 1259 p->fts_accpath = p->fts_path; 1260 memmove(cp, p->fts_name, p->fts_namelen + 1); 1261 p->fts_info = fts_stat(sp, p, 0, dirfd(dirp)); 1262 } else { 1263 p->fts_accpath = p->fts_name; 1264 p->fts_info = fts_stat(sp, p, 0, -1); 1265 } 1266 1267 /* Decrement link count if applicable. */ 1268 if (nlinks > 0 && (p->fts_info == FTS_D || 1269 p->fts_info == FTS_DC || p->fts_info == FTS_DOT)) 1270 --nlinks; 1271 } 1272 1273 /* We walk in directory order so "ls -f" doesn't get upset. */ 1274 p->fts_link = NULL; 1275 if (head == NULL) 1276 head = tail = p; 1277 else { 1278 tail->fts_link = p; 1279 tail = p; 1280 } 1281 ++nitems; 1282 } 1283 if (dirp) 1284 (void)closedir(dirp); 1285 1286 /* 1287 * If realloc() changed the address of the path, adjust the 1288 * addresses for the rest of the tree and the dir list. 1289 */ 1290 if (doadjust) 1291 fts_padjust(sp, head); 1292 1293 /* 1294 * If not changing directories, reset the path back to original 1295 * state. 1296 */ 1297 if (FTS_ISSET(FTS_NOCHDIR)) { 1298 if (len == sp->fts_pathlen || nitems == 0) 1299 --cp; 1300 *cp = '\0'; 1301 } 1302 1303 /* 1304 * If descended after called from fts_children or after called from 1305 * fts_read and nothing found, get back. At the root level we use 1306 * the saved fd; if one of fts_open()'s arguments is a relative path 1307 * to an empty directory, we wind up here with no other way back. If 1308 * can't get back, we're done. 1309 */ 1310 if (descend && (type == FTS_BCHILD || !nitems) && 1311 (cur->fts_level == FTS_ROOTLEVEL ? FTS_FCHDIR(sp, sp->fts_rfd) : 1312 fts_safe_changedir(sp, cur->fts_parent, -1, up))) { 1313 cur->fts_info = FTS_ERR; 1314 FTS_SET(FTS_STOP); 1315 return (NULL); 1316 } 1317 1318 /* If didn't find anything, return NULL. */ 1319 if (!nitems) { 1320 if (type == FTS_BREAD) 1321 cur->fts_info = FTS_DP; 1322 return (NULL); 1323 } 1324 1325 /* Sort the entries. */ 1326 if (sp->fts_compar && nitems > 1) 1327 head = fts_sort(sp, head, nitems); 1328 return (head); 1329 } 1330 1331 static u_short 1332 fts_stat(FTS *sp, FTSENT *p, int follow, int dfd) 1333 { 1334 FTSENT *t; 1335 dev_t dev; 1336 ino_t ino; 1337 struct stat *sbp, sb; 1338 int saved_errno; 1339 const char *path; 1340 1341 if (dfd == -1) { 1342 path = p->fts_accpath; 1343 dfd = AT_FDCWD; 1344 } else 1345 path = p->fts_name; 1346 1347 /* If user needs stat info, stat buffer already allocated. */ 1348 sbp = FTS_ISSET(FTS_NOSTAT) ? &sb : p->fts_statp; 1349 1350 /* 1351 * If doing a logical walk, or application requested FTS_FOLLOW, do 1352 * a stat(2). If that fails, check for a non-existent symlink. If 1353 * fail, set the errno from the stat call. 1354 */ 1355 if (FTS_ISSET(FTS_LOGICAL) || follow) { 1356 if (fstatat(dfd, path, sbp, 0)) { 1357 saved_errno = errno; 1358 if (!fstatat(dfd, path, sbp, AT_SYMLINK_NOFOLLOW)) { 1359 errno = 0; 1360 return (FTS_SLNONE); 1361 } 1362 p->fts_errno = saved_errno; 1363 goto err; 1364 } 1365 } else if (fstatat(dfd, path, sbp, AT_SYMLINK_NOFOLLOW)) { 1366 p->fts_errno = errno; 1367 err: memset(sbp, 0, sizeof(struct stat)); 1368 return (FTS_NS); 1369 } 1370 1371 if (S_ISDIR(sbp->st_mode)) { 1372 /* 1373 * Set the device/inode. Used to find cycles and check for 1374 * crossing mount points. Also remember the link count, used 1375 * in fts_build to limit the number of stat calls. It is 1376 * understood that these fields are only referenced if fts_info 1377 * is set to FTS_D. 1378 */ 1379 dev = p->fts_dev = sbp->st_dev; 1380 ino = p->fts_ino = sbp->st_ino; 1381 p->fts_nlink = sbp->st_nlink; 1382 1383 if (FTS_ISDOT(p->fts_name)) 1384 return (FTS_DOT); 1385 1386 /* 1387 * Cycle detection is done by brute force when the directory 1388 * is first encountered. If the tree gets deep enough or the 1389 * number of symbolic links to directories is high enough, 1390 * something faster might be worthwhile. 1391 */ 1392 for (t = p->fts_parent; 1393 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent) 1394 if (ino == t->fts_ino && dev == t->fts_dev) { 1395 p->fts_cycle = t; 1396 return (FTS_DC); 1397 } 1398 return (FTS_D); 1399 } 1400 if (S_ISLNK(sbp->st_mode)) 1401 return (FTS_SL); 1402 if (S_ISREG(sbp->st_mode)) 1403 return (FTS_F); 1404 return (FTS_DEFAULT); 1405 } 1406 1407 static FTSENT * 1408 fts_sort(FTS *sp, FTSENT *head, int nitems) 1409 { 1410 FTSENT **ap, *p; 1411 1412 /* 1413 * Construct an array of pointers to the structures and call qsort(3). 1414 * Reassemble the array in the order returned by qsort. If unable to 1415 * sort for memory reasons, return the directory entries in their 1416 * current order. Allocate enough space for the current needs plus 1417 * 40 so don't realloc one entry at a time. 1418 */ 1419 if (nitems > sp->fts_nitems) { 1420 struct _ftsent **a; 1421 1422 if ((a = reallocarray(sp->fts_array, 1423 nitems + 40, sizeof(FTSENT *))) == NULL) { 1424 free(sp->fts_array); 1425 sp->fts_array = NULL; 1426 sp->fts_nitems = 0; 1427 return (head); 1428 } 1429 sp->fts_nitems = nitems + 40; 1430 sp->fts_array = a; 1431 } 1432 for (ap = sp->fts_array, p = head; p; p = p->fts_link) 1433 *ap++ = p; 1434 qsort(sp->fts_array, nitems, sizeof(FTSENT *), 1435 (int(*)(const void *, const void *))sp->fts_compar); 1436 for (head = *(ap = sp->fts_array); --nitems; ++ap) 1437 ap[0]->fts_link = ap[1]; 1438 ap[0]->fts_link = NULL; 1439 return (head); 1440 } 1441 1442 static FTSENT * 1443 fts_alloc(FTS *sp, char *name, size_t namelen) 1444 { 1445 FTSENT *p; 1446 size_t len; 1447 1448 /* 1449 * The file name is a variable length array and no stat structure is 1450 * necessary if the user has set the nostat bit. Allocate the FTSENT 1451 * structure, the file name and the stat structure in one chunk, but 1452 * be careful that the stat structure is reasonably aligned. Since the 1453 * fts_name field is declared to be of size 1, the fts_name pointer is 1454 * namelen + 2 before the first possible address of the stat structure. 1455 */ 1456 len = sizeof(FTSENT) + namelen; 1457 if (!FTS_ISSET(FTS_NOSTAT)) 1458 len += sizeof(struct stat) + FTS_ALIGNBYTES; 1459 if ((p = calloc(1, len)) == NULL) 1460 return (NULL); 1461 1462 p->fts_path = sp->fts_path; 1463 p->fts_namelen = namelen; 1464 p->fts_instr = FTS_NOINSTR; 1465 if (!FTS_ISSET(FTS_NOSTAT)) 1466 p->fts_statp = (struct stat *)FTS_ALIGN(p->fts_name + namelen + 2); 1467 memcpy(p->fts_name, name, namelen); 1468 1469 return (p); 1470 } 1471 1472 static void 1473 fts_lfree(FTSENT *head) 1474 { 1475 FTSENT *p; 1476 1477 /* Free a linked list of structures. */ 1478 while ((p = head)) { 1479 head = head->fts_link; 1480 free(p); 1481 } 1482 } 1483 1484 /* 1485 * Allow essentially unlimited paths; find, rm, ls should all work on any tree. 1486 * Most systems will allow creation of paths much longer than PATH_MAX, even 1487 * though the kernel won't resolve them. Add the size (not just what's needed) 1488 * plus 256 bytes so don't realloc the path 2 bytes at a time. 1489 */ 1490 static int 1491 fts_palloc(FTS *sp, size_t more) 1492 { 1493 char *p; 1494 1495 /* 1496 * Check for possible wraparound. 1497 */ 1498 more += 256; 1499 if (sp->fts_pathlen + more < sp->fts_pathlen) { 1500 free(sp->fts_path); 1501 sp->fts_path = NULL; 1502 errno = ENAMETOOLONG; 1503 return (1); 1504 } 1505 p = recallocarray(sp->fts_path, sp->fts_pathlen, 1506 sp->fts_pathlen + more, 1); 1507 if (p == NULL) { 1508 free(sp->fts_path); 1509 sp->fts_path = NULL; 1510 return (1); 1511 } 1512 sp->fts_pathlen += more; 1513 sp->fts_path = p; 1514 return (0); 1515 } 1516 1517 /* 1518 * When the path is realloc'd, have to fix all of the pointers in structures 1519 * already returned. 1520 */ 1521 static void 1522 fts_padjust(FTS *sp, FTSENT *head) 1523 { 1524 FTSENT *p; 1525 char *addr = sp->fts_path; 1526 1527 #define ADJUST(p) { \ 1528 if ((p)->fts_accpath != (p)->fts_name) { \ 1529 (p)->fts_accpath = \ 1530 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \ 1531 } \ 1532 (p)->fts_path = addr; \ 1533 } 1534 /* Adjust the current set of children. */ 1535 for (p = sp->fts_child; p; p = p->fts_link) 1536 ADJUST(p); 1537 1538 /* Adjust the rest of the tree, including the current level. */ 1539 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) { 1540 ADJUST(p); 1541 p = p->fts_link ? p->fts_link : p->fts_parent; 1542 } 1543 } 1544 1545 static size_t 1546 fts_maxarglen(char * const *argv) 1547 { 1548 size_t len, max; 1549 1550 for (max = 0; *argv; ++argv) 1551 if ((len = strlen(*argv)) > max) 1552 max = len; 1553 return (max + 1); 1554 } 1555 1556 /* 1557 * Change to dir specified by fd or p->fts_accpath without getting 1558 * tricked by someone changing the world out from underneath us. 1559 * Assumes p->fts_dev and p->fts_ino are filled in. 1560 */ 1561 static int 1562 fts_safe_changedir(FTS *sp, FTSENT *p, int fd, char *path) 1563 { 1564 int ret, oerrno, newfd; 1565 struct stat sb; 1566 1567 newfd = fd; 1568 if (FTS_ISSET(FTS_NOCHDIR)) 1569 return (0); 1570 if (fd == -1 && (newfd = open(path, O_RDONLY|O_DIRECTORY|O_CLOEXEC)) == -1) 1571 return (-1); 1572 if (fstat(newfd, &sb) == -1) { 1573 ret = -1; 1574 goto bail; 1575 } 1576 if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) { 1577 errno = ENOENT; /* disinformation */ 1578 ret = -1; 1579 goto bail; 1580 } 1581 ret = fchdir(newfd); 1582 bail: 1583 oerrno = errno; 1584 if (fd == -1) 1585 (void)close(newfd); 1586 errno = oerrno; 1587 return (ret); 1588 } 1589 #endif /* !HAVE_FTS */ 1590 #if !HAVE_GETPROGNAME 1591 /* 1592 * Copyright (c) 2016 Nicholas Marriott <nicholas.marriott@gmail.com> 1593 * Copyright (c) 2017 Kristaps Dzonsons <kristaps@bsd.lv> 1594 * Copyright (c) 2020 Stephen Gregoratto <dev@sgregoratto.me> 1595 * 1596 * Permission to use, copy, modify, and distribute this software for any 1597 * purpose with or without fee is hereby granted, provided that the above 1598 * copyright notice and this permission notice appear in all copies. 1599 * 1600 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 1601 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 1602 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 1603 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 1604 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER 1605 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 1606 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 1607 */ 1608 1609 #include <sys/types.h> 1610 1611 #include <errno.h> 1612 1613 #if HAVE_GETEXECNAME 1614 #include <stdlib.h> 1615 const char * 1616 getprogname(void) 1617 { 1618 return getexecname(); 1619 } 1620 #elif HAVE_PROGRAM_INVOCATION_SHORT_NAME 1621 const char * 1622 getprogname(void) 1623 { 1624 return (program_invocation_short_name); 1625 } 1626 #elif HAVE___PROGNAME 1627 const char * 1628 getprogname(void) 1629 { 1630 extern char *__progname; 1631 1632 return (__progname); 1633 } 1634 #else 1635 #error No getprogname available. 1636 #endif 1637 #endif /* !HAVE_GETPROGNAME */ 1638 #if !HAVE_MD5 1639 /* 1640 * This code implements the MD5 message-digest algorithm. 1641 * The algorithm is due to Ron Rivest. This code was 1642 * written by Colin Plumb in 1993, no copyright is claimed. 1643 * This code is in the public domain; do with it what you wish. 1644 * 1645 * Equivalent code is available from RSA Data Security, Inc. 1646 * This code has been tested against that, and is equivalent, 1647 * except that you don't need to include two pages of legalese 1648 * with every copy. 1649 * 1650 * To compute the message digest of a chunk of bytes, declare an 1651 * MD5Context structure, pass it to MD5Init, call MD5Update as 1652 * needed on buffers full of bytes, and then call MD5Final, which 1653 * will fill a supplied 16-byte array with the digest. 1654 */ 1655 1656 #include <sys/types.h> 1657 #include <stdlib.h> 1658 #include <string.h> 1659 1660 #ifndef BYTE_ORDER 1661 # if defined(LITTLE_ENDIAN) || defined(BIG_ENDIAN) 1662 # error Confusion in endian macros. 1663 # endif 1664 # if !defined(__BYTE_ORDER__) 1665 # error Byte order macro not found. 1666 # endif 1667 # if !defined(__ORDER_LITTLE_ENDIAN__) || !defined(__ORDER_BIG_ENDIAN__) 1668 # error Little/big endian macros not found. 1669 # endif 1670 # define BYTE_ORDER __BYTE_ORDER__ 1671 # define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ 1672 # define BIG_ENDIAN __ORDER_BIG_ENDIAN__ 1673 #endif /*!BYTE_ORDER*/ 1674 1675 #define PUT_64BIT_LE(cp, value) do { \ 1676 (cp)[7] = (value) >> 56; \ 1677 (cp)[6] = (value) >> 48; \ 1678 (cp)[5] = (value) >> 40; \ 1679 (cp)[4] = (value) >> 32; \ 1680 (cp)[3] = (value) >> 24; \ 1681 (cp)[2] = (value) >> 16; \ 1682 (cp)[1] = (value) >> 8; \ 1683 (cp)[0] = (value); } while (0) 1684 1685 #define PUT_32BIT_LE(cp, value) do { \ 1686 (cp)[3] = (value) >> 24; \ 1687 (cp)[2] = (value) >> 16; \ 1688 (cp)[1] = (value) >> 8; \ 1689 (cp)[0] = (value); } while (0) 1690 1691 static uint8_t PADDING[MD5_BLOCK_LENGTH] = { 1692 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1693 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1694 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 1695 }; 1696 1697 /* 1698 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious 1699 * initialization constants. 1700 */ 1701 void 1702 MD5Init(MD5_CTX *ctx) 1703 { 1704 ctx->count = 0; 1705 ctx->state[0] = 0x67452301; 1706 ctx->state[1] = 0xefcdab89; 1707 ctx->state[2] = 0x98badcfe; 1708 ctx->state[3] = 0x10325476; 1709 } 1710 1711 /* 1712 * Update context to reflect the concatenation of another buffer full 1713 * of bytes. 1714 */ 1715 void 1716 MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) 1717 { 1718 size_t have, need; 1719 1720 /* Check how many bytes we already have and how many more we need. */ 1721 have = (size_t)((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); 1722 need = MD5_BLOCK_LENGTH - have; 1723 1724 /* Update bitcount */ 1725 ctx->count += (uint64_t)len << 3; 1726 1727 if (len >= need) { 1728 if (have != 0) { 1729 memcpy(ctx->buffer + have, input, need); 1730 MD5Transform(ctx->state, ctx->buffer); 1731 input += need; 1732 len -= need; 1733 have = 0; 1734 } 1735 1736 /* Process data in MD5_BLOCK_LENGTH-byte chunks. */ 1737 while (len >= MD5_BLOCK_LENGTH) { 1738 MD5Transform(ctx->state, input); 1739 input += MD5_BLOCK_LENGTH; 1740 len -= MD5_BLOCK_LENGTH; 1741 } 1742 } 1743 1744 /* Handle any remaining bytes of data. */ 1745 if (len != 0) 1746 memcpy(ctx->buffer + have, input, len); 1747 } 1748 1749 /* 1750 * Pad pad to 64-byte boundary with the bit pattern 1751 * 1 0* (64-bit count of bits processed, MSB-first) 1752 */ 1753 void 1754 MD5Pad(MD5_CTX *ctx) 1755 { 1756 uint8_t count[8]; 1757 size_t padlen; 1758 1759 /* Convert count to 8 bytes in little endian order. */ 1760 PUT_64BIT_LE(count, ctx->count); 1761 1762 /* Pad out to 56 mod 64. */ 1763 padlen = MD5_BLOCK_LENGTH - 1764 ((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); 1765 if (padlen < 1 + 8) 1766 padlen += MD5_BLOCK_LENGTH; 1767 MD5Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ 1768 MD5Update(ctx, count, 8); 1769 } 1770 1771 /* 1772 * Final wrapup--call MD5Pad, fill in digest and zero out ctx. 1773 */ 1774 void 1775 MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx) 1776 { 1777 int i; 1778 1779 MD5Pad(ctx); 1780 for (i = 0; i < 4; i++) 1781 PUT_32BIT_LE(digest + i * 4, ctx->state[i]); 1782 memset(ctx, 0, sizeof(*ctx)); 1783 } 1784 1785 1786 /* The four core functions - F1 is optimized somewhat */ 1787 1788 /* #define F1(x, y, z) (x & y | ~x & z) */ 1789 #define F1(x, y, z) (z ^ (x & (y ^ z))) 1790 #define F2(x, y, z) F1(z, x, y) 1791 #define F3(x, y, z) (x ^ y ^ z) 1792 #define F4(x, y, z) (y ^ (x | ~z)) 1793 1794 /* This is the central step in the MD5 algorithm. */ 1795 #define MD5STEP(f, w, x, y, z, data, s) \ 1796 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) 1797 1798 /* 1799 * The core of the MD5 algorithm, this alters an existing MD5 hash to 1800 * reflect the addition of 16 longwords of new data. MD5Update blocks 1801 * the data and converts bytes into longwords for this routine. 1802 */ 1803 void 1804 MD5Transform(uint32_t state[4], const uint8_t block[MD5_BLOCK_LENGTH]) 1805 { 1806 uint32_t a, b, c, d, in[MD5_BLOCK_LENGTH / 4]; 1807 1808 #if BYTE_ORDER == LITTLE_ENDIAN 1809 memcpy(in, block, sizeof(in)); 1810 #else 1811 for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) { 1812 in[a] = (uint32_t)( 1813 (uint32_t)(block[a * 4 + 0]) | 1814 (uint32_t)(block[a * 4 + 1]) << 8 | 1815 (uint32_t)(block[a * 4 + 2]) << 16 | 1816 (uint32_t)(block[a * 4 + 3]) << 24); 1817 } 1818 #endif 1819 1820 a = state[0]; 1821 b = state[1]; 1822 c = state[2]; 1823 d = state[3]; 1824 1825 MD5STEP(F1, a, b, c, d, in[ 0] + 0xd76aa478, 7); 1826 MD5STEP(F1, d, a, b, c, in[ 1] + 0xe8c7b756, 12); 1827 MD5STEP(F1, c, d, a, b, in[ 2] + 0x242070db, 17); 1828 MD5STEP(F1, b, c, d, a, in[ 3] + 0xc1bdceee, 22); 1829 MD5STEP(F1, a, b, c, d, in[ 4] + 0xf57c0faf, 7); 1830 MD5STEP(F1, d, a, b, c, in[ 5] + 0x4787c62a, 12); 1831 MD5STEP(F1, c, d, a, b, in[ 6] + 0xa8304613, 17); 1832 MD5STEP(F1, b, c, d, a, in[ 7] + 0xfd469501, 22); 1833 MD5STEP(F1, a, b, c, d, in[ 8] + 0x698098d8, 7); 1834 MD5STEP(F1, d, a, b, c, in[ 9] + 0x8b44f7af, 12); 1835 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); 1836 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); 1837 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); 1838 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); 1839 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); 1840 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); 1841 1842 MD5STEP(F2, a, b, c, d, in[ 1] + 0xf61e2562, 5); 1843 MD5STEP(F2, d, a, b, c, in[ 6] + 0xc040b340, 9); 1844 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); 1845 MD5STEP(F2, b, c, d, a, in[ 0] + 0xe9b6c7aa, 20); 1846 MD5STEP(F2, a, b, c, d, in[ 5] + 0xd62f105d, 5); 1847 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); 1848 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); 1849 MD5STEP(F2, b, c, d, a, in[ 4] + 0xe7d3fbc8, 20); 1850 MD5STEP(F2, a, b, c, d, in[ 9] + 0x21e1cde6, 5); 1851 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); 1852 MD5STEP(F2, c, d, a, b, in[ 3] + 0xf4d50d87, 14); 1853 MD5STEP(F2, b, c, d, a, in[ 8] + 0x455a14ed, 20); 1854 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); 1855 MD5STEP(F2, d, a, b, c, in[ 2] + 0xfcefa3f8, 9); 1856 MD5STEP(F2, c, d, a, b, in[ 7] + 0x676f02d9, 14); 1857 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); 1858 1859 MD5STEP(F3, a, b, c, d, in[ 5] + 0xfffa3942, 4); 1860 MD5STEP(F3, d, a, b, c, in[ 8] + 0x8771f681, 11); 1861 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); 1862 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); 1863 MD5STEP(F3, a, b, c, d, in[ 1] + 0xa4beea44, 4); 1864 MD5STEP(F3, d, a, b, c, in[ 4] + 0x4bdecfa9, 11); 1865 MD5STEP(F3, c, d, a, b, in[ 7] + 0xf6bb4b60, 16); 1866 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); 1867 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); 1868 MD5STEP(F3, d, a, b, c, in[ 0] + 0xeaa127fa, 11); 1869 MD5STEP(F3, c, d, a, b, in[ 3] + 0xd4ef3085, 16); 1870 MD5STEP(F3, b, c, d, a, in[ 6] + 0x04881d05, 23); 1871 MD5STEP(F3, a, b, c, d, in[ 9] + 0xd9d4d039, 4); 1872 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); 1873 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); 1874 MD5STEP(F3, b, c, d, a, in[2 ] + 0xc4ac5665, 23); 1875 1876 MD5STEP(F4, a, b, c, d, in[ 0] + 0xf4292244, 6); 1877 MD5STEP(F4, d, a, b, c, in[7 ] + 0x432aff97, 10); 1878 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); 1879 MD5STEP(F4, b, c, d, a, in[5 ] + 0xfc93a039, 21); 1880 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); 1881 MD5STEP(F4, d, a, b, c, in[3 ] + 0x8f0ccc92, 10); 1882 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); 1883 MD5STEP(F4, b, c, d, a, in[1 ] + 0x85845dd1, 21); 1884 MD5STEP(F4, a, b, c, d, in[8 ] + 0x6fa87e4f, 6); 1885 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); 1886 MD5STEP(F4, c, d, a, b, in[6 ] + 0xa3014314, 15); 1887 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); 1888 MD5STEP(F4, a, b, c, d, in[4 ] + 0xf7537e82, 6); 1889 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); 1890 MD5STEP(F4, c, d, a, b, in[2 ] + 0x2ad7d2bb, 15); 1891 MD5STEP(F4, b, c, d, a, in[9 ] + 0xeb86d391, 21); 1892 1893 state[0] += a; 1894 state[1] += b; 1895 state[2] += c; 1896 state[3] += d; 1897 } 1898 1899 char * 1900 MD5End(MD5_CTX *ctx, char *buf) 1901 { 1902 int i; 1903 unsigned char digest[MD5_DIGEST_LENGTH]; 1904 static const char hex[]="0123456789abcdef"; 1905 1906 if (!buf) 1907 buf = malloc(2*MD5_DIGEST_LENGTH + 1); 1908 if (!buf) 1909 return 0; 1910 MD5Final(digest, ctx); 1911 for (i = 0; i < MD5_DIGEST_LENGTH; i++) { 1912 buf[i+i] = hex[digest[i] >> 4]; 1913 buf[i+i+1] = hex[digest[i] & 0x0f]; 1914 } 1915 buf[i+i] = '\0'; 1916 return buf; 1917 } 1918 #endif /* !HAVE_MD5 */ 1919 #if !HAVE_MEMMEM 1920 /*- 1921 * Copyright (c) 2005 Pascal Gloor <pascal.gloor@spale.com> 1922 * 1923 * Redistribution and use in source and binary forms, with or without 1924 * modification, are permitted provided that the following conditions 1925 * are met: 1926 * 1. Redistributions of source code must retain the above copyright 1927 * notice, this list of conditions and the following disclaimer. 1928 * 2. Redistributions in binary form must reproduce the above copyright 1929 * notice, this list of conditions and the following disclaimer in 1930 * the documentation and/or other materials provided with the 1931 * distribution. 1932 * 3. The name of the author may not be used to endorse or promote 1933 * products derived from this software without specific prior written 1934 * permission. 1935 * 1936 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' 1937 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 1938 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 1939 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR 1940 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 1941 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 1942 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 1943 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 1944 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 1945 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 1946 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 1947 */ 1948 /* 1949 * Find the first occurrence of the byte string s in byte string l. 1950 */ 1951 void * 1952 memmem(const void *l, size_t l_len, const void *s, size_t s_len) 1953 { 1954 const char *cur, *last; 1955 const char *cl = l; 1956 const char *cs = s; 1957 1958 /* a zero length needle should just return the haystack */ 1959 if (l_len == 0) 1960 return (void *)cl; 1961 1962 /* "s" must be smaller or equal to "l" */ 1963 if (l_len < s_len) 1964 return NULL; 1965 1966 /* special case where s_len == 1 */ 1967 if (s_len == 1) 1968 return memchr(l, *cs, l_len); 1969 1970 /* the last position where its possible to find "s" in "l" */ 1971 last = cl + l_len - s_len; 1972 1973 for (cur = cl; cur <= last; cur++) 1974 if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) 1975 return (void *)cur; 1976 1977 return NULL; 1978 } 1979 #endif /* !HAVE_MEMMEM */ 1980 #if !HAVE_MEMRCHR 1981 /* 1982 * Copyright (c) 2007 Todd C. Miller <Todd.Miller@courtesan.com> 1983 * 1984 * Permission to use, copy, modify, and distribute this software for any 1985 * purpose with or without fee is hereby granted, provided that the above 1986 * copyright notice and this permission notice appear in all copies. 1987 * 1988 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 1989 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 1990 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 1991 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 1992 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 1993 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 1994 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 1995 * 1996 */ 1997 1998 #include <string.h> 1999 2000 /* 2001 * Reverse memchr() 2002 * Find the last occurrence of 'c' in the buffer 's' of size 'n'. 2003 */ 2004 void * 2005 memrchr(const void *s, int c, size_t n) 2006 { 2007 const unsigned char *cp; 2008 2009 if (n != 0) { 2010 cp = (unsigned char *)s + n; 2011 do { 2012 if (*(--cp) == (unsigned char)c) 2013 return((void *)cp); 2014 } while (--n != 0); 2015 } 2016 return(NULL); 2017 } 2018 #endif /* !HAVE_MEMRCHR */ 2019 #if !HAVE_MKFIFOAT 2020 #include <sys/stat.h> 2021 2022 #include <errno.h> 2023 #include <fcntl.h> 2024 #include <unistd.h> 2025 2026 int 2027 mkfifoat(int fd, const char *path, mode_t mode) 2028 { 2029 int er, curfd = -1, newfd = -1; 2030 2031 /* Get our current directory then switch to the given one. */ 2032 2033 if (fd != AT_FDCWD) { 2034 if ((curfd = open(".", O_RDONLY | O_DIRECTORY, 0)) == -1) 2035 return -1; 2036 if (fchdir(fd) == -1) 2037 goto out; 2038 } 2039 2040 if ((newfd = mkfifo(path, mode)) == -1) 2041 goto out; 2042 2043 /* This leaves the fifo if it fails. */ 2044 2045 if (curfd != -1 && fchdir(curfd) == -1) 2046 goto out; 2047 if (curfd != -1) 2048 close(curfd); 2049 2050 return newfd; 2051 out: 2052 /* Ignore errors in close(2). */ 2053 2054 er = errno; 2055 if (curfd != -1) 2056 fchdir(curfd); 2057 if (curfd != -1) 2058 close(curfd); 2059 if (newfd != -1) 2060 close(newfd); 2061 errno = er; 2062 return -1; 2063 } 2064 #endif /* !HAVE_MKFIFOAT */ 2065 #if !HAVE_MKNODAT 2066 #include <sys/stat.h> 2067 2068 #include <errno.h> 2069 #include <fcntl.h> 2070 #include <unistd.h> 2071 2072 int 2073 mknodat(int fd, const char *path, mode_t mode, dev_t dev) 2074 { 2075 int er, curfd = -1, newfd = -1; 2076 2077 /* Get our current directory then switch to the given one. */ 2078 2079 if (fd != AT_FDCWD) { 2080 if ((curfd = open(".", O_RDONLY | O_DIRECTORY, 0)) == -1) 2081 return -1; 2082 if (fchdir(fd) == -1) 2083 goto out; 2084 } 2085 2086 if ((newfd = mknod(path, mode, dev)) == -1) 2087 goto out; 2088 2089 /* This leaves the node if it fails. */ 2090 2091 if (curfd != -1 && fchdir(curfd) == -1) 2092 goto out; 2093 if (curfd != -1) 2094 close(curfd); 2095 2096 return newfd; 2097 out: 2098 2099 /* Ignore errors in close(2). */ 2100 2101 er = errno; 2102 if (curfd != -1) 2103 fchdir(curfd); 2104 if (curfd != -1) 2105 close(curfd); 2106 if (newfd != -1) 2107 close(newfd); 2108 errno = er; 2109 return -1; 2110 } 2111 #endif /* !HAVE_MKNODAT */ 2112 #if !HAVE_READPASSPHRASE 2113 /* 2114 * Original: readpassphrase.c in OpenSSH portable 2115 */ 2116 /* 2117 * Copyright (c) 2000-2002, 2007, 2010 2118 * Todd C. Miller <millert@openbsd.org> 2119 * 2120 * Permission to use, copy, modify, and distribute this software for any 2121 * purpose with or without fee is hereby granted, provided that the above 2122 * copyright notice and this permission notice appear in all copies. 2123 * 2124 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 2125 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 2126 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 2127 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 2128 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 2129 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 2130 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 2131 * 2132 * Sponsored in part by the Defense Advanced Research Projects 2133 * Agency (DARPA) and Air Force Research Laboratory, Air Force 2134 * Materiel Command, USAF, under agreement number F39502-99-1-0512. 2135 */ 2136 2137 #include <ctype.h> 2138 #include <errno.h> 2139 #include <fcntl.h> 2140 #include <paths.h> 2141 #include <pwd.h> 2142 #include <signal.h> 2143 #include <string.h> 2144 #include <termios.h> 2145 #include <unistd.h> 2146 2147 #if !defined(_NSIG) && defined(NSIG) 2148 # define _NSIG NSIG 2149 #endif 2150 2151 static volatile sig_atomic_t readpassphrase_signo[_NSIG]; 2152 2153 static void 2154 readpassphrase_handler(int s) 2155 { 2156 2157 readpassphrase_signo[s] = 1; 2158 } 2159 2160 char * 2161 readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags) 2162 { 2163 ssize_t nr; 2164 int input, output, save_errno, i, need_restart; 2165 char ch, *p, *end; 2166 struct termios term, oterm; 2167 struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm; 2168 struct sigaction savetstp, savettin, savettou, savepipe; 2169 /* If we don't have TCSASOFT define it so that ORing it it below is a no-op. */ 2170 #ifndef TCSASOFT 2171 const int tcasoft = 0; 2172 #else 2173 const int tcasoft = TCSASOFT; 2174 #endif 2175 2176 /* I suppose we could alloc on demand in this case (XXX). */ 2177 if (bufsiz == 0) { 2178 errno = EINVAL; 2179 return(NULL); 2180 } 2181 2182 restart: 2183 for (i = 0; i < _NSIG; i++) 2184 readpassphrase_signo[i] = 0; 2185 nr = -1; 2186 save_errno = 0; 2187 need_restart = 0; 2188 /* 2189 * Read and write to /dev/tty if available. If not, read from 2190 * stdin and write to stderr unless a tty is required. 2191 */ 2192 if ((flags & RPP_STDIN) || 2193 (input = output = open(_PATH_TTY, O_RDWR)) == -1) { 2194 if (flags & RPP_REQUIRE_TTY) { 2195 errno = ENOTTY; 2196 return(NULL); 2197 } 2198 input = STDIN_FILENO; 2199 output = STDERR_FILENO; 2200 } 2201 2202 /* 2203 * Turn off echo if possible. 2204 * If we are using a tty but are not the foreground pgrp this will 2205 * generate SIGTTOU, so do it *before* installing the signal handlers. 2206 */ 2207 if (input != STDIN_FILENO && tcgetattr(input, &oterm) == 0) { 2208 memcpy(&term, &oterm, sizeof(term)); 2209 if (!(flags & RPP_ECHO_ON)) 2210 term.c_lflag &= ~(ECHO | ECHONL); 2211 #ifdef VSTATUS 2212 if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) 2213 term.c_cc[VSTATUS] = _POSIX_VDISABLE; 2214 #endif 2215 (void)tcsetattr(input, TCSAFLUSH|tcasoft, &term); 2216 } else { 2217 memset(&term, 0, sizeof(term)); 2218 term.c_lflag |= ECHO; 2219 memset(&oterm, 0, sizeof(oterm)); 2220 oterm.c_lflag |= ECHO; 2221 } 2222 2223 /* 2224 * Catch signals that would otherwise cause the user to end 2225 * up with echo turned off in the shell. Don't worry about 2226 * things like SIGXCPU and SIGVTALRM for now. 2227 */ 2228 sigemptyset(&sa.sa_mask); 2229 sa.sa_flags = 0; /* don't restart system calls */ 2230 sa.sa_handler = readpassphrase_handler; 2231 (void)sigaction(SIGALRM, &sa, &savealrm); 2232 (void)sigaction(SIGHUP, &sa, &savehup); 2233 (void)sigaction(SIGINT, &sa, &saveint); 2234 (void)sigaction(SIGPIPE, &sa, &savepipe); 2235 (void)sigaction(SIGQUIT, &sa, &savequit); 2236 (void)sigaction(SIGTERM, &sa, &saveterm); 2237 (void)sigaction(SIGTSTP, &sa, &savetstp); 2238 (void)sigaction(SIGTTIN, &sa, &savettin); 2239 (void)sigaction(SIGTTOU, &sa, &savettou); 2240 2241 if (!(flags & RPP_STDIN)) 2242 (void)write(output, prompt, strlen(prompt)); 2243 end = buf + bufsiz - 1; 2244 p = buf; 2245 while ((nr = read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r') { 2246 if (p < end) { 2247 if ((flags & RPP_SEVENBIT)) 2248 ch &= 0x7f; 2249 if (isalpha((unsigned char)ch)) { 2250 if ((flags & RPP_FORCELOWER)) 2251 ch = (char)tolower((unsigned char)ch); 2252 if ((flags & RPP_FORCEUPPER)) 2253 ch = (char)toupper((unsigned char)ch); 2254 } 2255 *p++ = ch; 2256 } 2257 } 2258 *p = '\0'; 2259 save_errno = errno; 2260 if (!(term.c_lflag & ECHO)) 2261 (void)write(output, "\n", 1); 2262 2263 /* Restore old terminal settings and signals. */ 2264 if (memcmp(&term, &oterm, sizeof(term)) != 0) { 2265 const int sigttou = readpassphrase_signo[SIGTTOU]; 2266 2267 /* Ignore SIGTTOU generated when we are not the fg pgrp. */ 2268 while (tcsetattr(input, TCSAFLUSH|tcasoft, &oterm) == -1 && 2269 errno == EINTR && !readpassphrase_signo[SIGTTOU]) 2270 continue; 2271 readpassphrase_signo[SIGTTOU] = sigttou; 2272 } 2273 (void)sigaction(SIGALRM, &savealrm, NULL); 2274 (void)sigaction(SIGHUP, &savehup, NULL); 2275 (void)sigaction(SIGINT, &saveint, NULL); 2276 (void)sigaction(SIGQUIT, &savequit, NULL); 2277 (void)sigaction(SIGPIPE, &savepipe, NULL); 2278 (void)sigaction(SIGTERM, &saveterm, NULL); 2279 (void)sigaction(SIGTSTP, &savetstp, NULL); 2280 (void)sigaction(SIGTTIN, &savettin, NULL); 2281 (void)sigaction(SIGTTOU, &savettou, NULL); 2282 if (input != STDIN_FILENO) 2283 (void)close(input); 2284 2285 /* 2286 * If we were interrupted by a signal, resend it to ourselves 2287 * now that we have restored the signal handlers. 2288 */ 2289 for (i = 0; i < _NSIG; i++) { 2290 if (readpassphrase_signo[i]) { 2291 kill(getpid(), i); 2292 switch (i) { 2293 case SIGTSTP: 2294 case SIGTTIN: 2295 case SIGTTOU: 2296 need_restart = 1; 2297 } 2298 } 2299 } 2300 if (need_restart) 2301 goto restart; 2302 2303 if (save_errno) 2304 errno = save_errno; 2305 return(nr == -1 ? NULL : buf); 2306 } 2307 #endif /* !HAVE_READPASSPHRASE */ 2308 #if !HAVE_REALLOCARRAY 2309 /* 2310 * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> 2311 * 2312 * Permission to use, copy, modify, and distribute this software for any 2313 * purpose with or without fee is hereby granted, provided that the above 2314 * copyright notice and this permission notice appear in all copies. 2315 * 2316 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 2317 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 2318 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 2319 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 2320 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 2321 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 2322 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 2323 */ 2324 2325 #include <sys/types.h> 2326 #include <errno.h> 2327 #include <stdint.h> 2328 #include <stdlib.h> 2329 2330 /* 2331 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 2332 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 2333 */ 2334 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) 2335 2336 void * 2337 reallocarray(void *optr, size_t nmemb, size_t size) 2338 { 2339 if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 2340 nmemb > 0 && SIZE_MAX / nmemb < size) { 2341 errno = ENOMEM; 2342 return NULL; 2343 } 2344 return realloc(optr, size * nmemb); 2345 } 2346 #endif /* !HAVE_REALLOCARRAY */ 2347 #if !HAVE_RECALLOCARRAY 2348 /* 2349 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net> 2350 * 2351 * Permission to use, copy, modify, and distribute this software for any 2352 * purpose with or without fee is hereby granted, provided that the above 2353 * copyright notice and this permission notice appear in all copies. 2354 * 2355 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 2356 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 2357 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 2358 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 2359 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 2360 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 2361 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 2362 */ 2363 2364 /* OPENBSD ORIGINAL: lib/libc/stdlib/recallocarray.c */ 2365 2366 #include <errno.h> 2367 #include <stdlib.h> 2368 #include <stdint.h> 2369 #include <string.h> 2370 #include <unistd.h> 2371 2372 /* 2373 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 2374 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 2375 */ 2376 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) 2377 2378 void * 2379 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size) 2380 { 2381 size_t oldsize, newsize; 2382 void *newptr; 2383 2384 if (ptr == NULL) 2385 return calloc(newnmemb, size); 2386 2387 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 2388 newnmemb > 0 && SIZE_MAX / newnmemb < size) { 2389 errno = ENOMEM; 2390 return NULL; 2391 } 2392 newsize = newnmemb * size; 2393 2394 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 2395 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) { 2396 errno = EINVAL; 2397 return NULL; 2398 } 2399 oldsize = oldnmemb * size; 2400 2401 /* 2402 * Don't bother too much if we're shrinking just a bit, 2403 * we do not shrink for series of small steps, oh well. 2404 */ 2405 if (newsize <= oldsize) { 2406 size_t d = oldsize - newsize; 2407 2408 if (d < oldsize / 2 && d < (size_t)getpagesize()) { 2409 memset((char *)ptr + newsize, 0, d); 2410 return ptr; 2411 } 2412 } 2413 2414 newptr = malloc(newsize); 2415 if (newptr == NULL) 2416 return NULL; 2417 2418 if (newsize > oldsize) { 2419 memcpy(newptr, ptr, oldsize); 2420 memset((char *)newptr + oldsize, 0, newsize - oldsize); 2421 } else 2422 memcpy(newptr, ptr, newsize); 2423 2424 explicit_bzero(ptr, oldsize); 2425 free(ptr); 2426 2427 return newptr; 2428 } 2429 #endif /* !HAVE_RECALLOCARRAY */ 2430 #if !HAVE_SETRESGID 2431 /* 2432 * Copyright (c) 2004, 2005 Darren Tucker (dtucker at zip com au). 2433 * 2434 * Permission to use, copy, modify, and distribute this software for any 2435 * purpose with or without fee is hereby granted, provided that the above 2436 * copyright notice and this permission notice appear in all copies. 2437 * 2438 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 2439 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 2440 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 2441 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 2442 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 2443 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 2444 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 2445 */ 2446 2447 #include <sys/types.h> 2448 #include <unistd.h> 2449 2450 int 2451 setresgid(gid_t rgid, gid_t egid, gid_t sgid) 2452 { 2453 /* this is the only configuration tested */ 2454 2455 if (rgid != egid || egid != sgid) 2456 return -1; 2457 2458 if (setregid(rgid, egid) == -1) 2459 return -1; 2460 2461 return 0; 2462 } 2463 #endif /* !HAVE_SETRESGID */ 2464 #if !HAVE_SETRESUID 2465 /* 2466 * Copyright (c) 2004, 2005 Darren Tucker (dtucker at zip com au). 2467 * 2468 * Permission to use, copy, modify, and distribute this software for any 2469 * purpose with or without fee is hereby granted, provided that the above 2470 * copyright notice and this permission notice appear in all copies. 2471 * 2472 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 2473 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 2474 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 2475 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 2476 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 2477 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 2478 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 2479 */ 2480 2481 #include <sys/types.h> 2482 2483 #include <errno.h> 2484 #include <unistd.h> 2485 2486 int 2487 setresuid(uid_t ruid, uid_t euid, uid_t suid) 2488 { 2489 uid_t ouid; 2490 int ret = -1; 2491 2492 /* Allow only the tested configuration. */ 2493 2494 if (ruid != euid || euid != suid) { 2495 errno = ENOSYS; 2496 return -1; 2497 } 2498 ouid = getuid(); 2499 2500 if ((ret = setreuid(euid, euid)) == -1) 2501 return -1; 2502 2503 /* 2504 * When real, effective and saved uids are the same and we have 2505 * changed uids, sanity check that we cannot restore the old uid. 2506 */ 2507 2508 if (ruid == euid && euid == suid && ouid != ruid && 2509 setuid(ouid) != -1 && seteuid(ouid) != -1) { 2510 errno = EINVAL; 2511 return -1; 2512 } 2513 2514 /* 2515 * Finally, check that the real and effective uids are what we 2516 * expect. 2517 */ 2518 if (getuid() != ruid || geteuid() != euid) { 2519 errno = EACCES; 2520 return -1; 2521 } 2522 2523 return ret; 2524 } 2525 #endif /* !HAVE_SETRESUID */ 2526 #if !HAVE_SHA2_H 2527 /* $OpenBSD$ */ 2528 2529 /* 2530 * FILE: sha2.c 2531 * AUTHOR: Aaron D. Gifford <me@aarongifford.com> 2532 * 2533 * Copyright (c) 2000-2001, Aaron D. Gifford 2534 * All rights reserved. 2535 * 2536 * Redistribution and use in source and binary forms, with or without 2537 * modification, are permitted provided that the following conditions 2538 * are met: 2539 * 1. Redistributions of source code must retain the above copyright 2540 * notice, this list of conditions and the following disclaimer. 2541 * 2. Redistributions in binary form must reproduce the above copyright 2542 * notice, this list of conditions and the following disclaimer in the 2543 * documentation and/or other materials provided with the distribution. 2544 * 3. Neither the name of the copyright holder nor the names of contributors 2545 * may be used to endorse or promote products derived from this software 2546 * without specific prior written permission. 2547 * 2548 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND 2549 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 2550 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 2551 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE 2552 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 2553 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 2554 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 2555 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 2556 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 2557 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 2558 * SUCH DAMAGE. 2559 * 2560 * $From: sha2.c,v 1.1 2001/11/08 00:01:51 adg Exp adg $ 2561 */ 2562 2563 /* OPENBSD ORIGINAL: lib/libc/hash/sha2.c */ 2564 2565 /* no-op out, similar to DEF_WEAK but only needed here */ 2566 #define MAKE_CLONE(x, y) void __ssh_compat_make_clone_##x_##y(void) 2567 2568 #include <sys/types.h> 2569 #include <sys/stat.h> 2570 2571 #include <errno.h> 2572 #include <fcntl.h> 2573 #include <stdlib.h> 2574 #include <stdio.h> 2575 #include <string.h> 2576 #include <unistd.h> 2577 2578 #ifndef MINIMUM 2579 # define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) 2580 #endif 2581 2582 #ifndef BYTE_ORDER 2583 # if defined(LITTLE_ENDIAN) || defined(BIG_ENDIAN) 2584 # error Confusion in endian macros. 2585 # endif 2586 # if !defined(__BYTE_ORDER__) 2587 # error Byte order macro not found. 2588 # endif 2589 # if !defined(__ORDER_LITTLE_ENDIAN__) || !defined(__ORDER_BIG_ENDIAN__) 2590 # error Little/big endian macros not found. 2591 # endif 2592 # define BYTE_ORDER __BYTE_ORDER__ 2593 # define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ 2594 # define BIG_ENDIAN __ORDER_BIG_ENDIAN__ 2595 #endif /*!BYTE_ORDER*/ 2596 2597 /* 2598 * UNROLLED TRANSFORM LOOP NOTE: 2599 * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform 2600 * loop version for the hash transform rounds (defined using macros 2601 * later in this file). Either define on the command line, for example: 2602 * 2603 * cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c 2604 * 2605 * or define below: 2606 * 2607 * #define SHA2_UNROLL_TRANSFORM 2608 * 2609 */ 2610 #if defined(__amd64__) || defined(__i386__) 2611 #define SHA2_UNROLL_TRANSFORM 2612 #endif 2613 2614 /*** SHA-224/256/384/512 Machine Architecture Definitions *****************/ 2615 /* 2616 * BYTE_ORDER NOTE: 2617 * 2618 * Please make sure that your system defines BYTE_ORDER. If your 2619 * architecture is little-endian, make sure it also defines 2620 * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are 2621 * equivalent. 2622 * 2623 * If your system does not define the above, then you can do so by 2624 * hand like this: 2625 * 2626 * #define LITTLE_ENDIAN 1234 2627 * #define BIG_ENDIAN 4321 2628 * 2629 * And for little-endian machines, add: 2630 * 2631 * #define BYTE_ORDER LITTLE_ENDIAN 2632 * 2633 * Or for big-endian machines: 2634 * 2635 * #define BYTE_ORDER BIG_ENDIAN 2636 * 2637 * The FreeBSD machine this was written on defines BYTE_ORDER 2638 * appropriately by including <sys/types.h> (which in turn includes 2639 * <machine/endian.h> where the appropriate definitions are actually 2640 * made). 2641 */ 2642 #if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN) 2643 #error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN 2644 #endif 2645 2646 2647 /*** SHA-224/256/384/512 Various Length Definitions ***********************/ 2648 /* NOTE: Most of these are in sha2.h */ 2649 #define SHA224_SHORT_BLOCK_LENGTH (SHA224_BLOCK_LENGTH - 8) 2650 #define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) 2651 #define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16) 2652 #define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) 2653 2654 /*** ENDIAN SPECIFIC COPY MACROS **************************************/ 2655 #define BE_8_TO_32(dst, cp) do { \ 2656 (dst) = (uint32_t)(cp)[3] | ((uint32_t)(cp)[2] << 8) | \ 2657 ((uint32_t)(cp)[1] << 16) | ((uint32_t)(cp)[0] << 24); \ 2658 } while(0) 2659 2660 #define BE_8_TO_64(dst, cp) do { \ 2661 (dst) = (uint64_t)(cp)[7] | ((uint64_t)(cp)[6] << 8) | \ 2662 ((uint64_t)(cp)[5] << 16) | ((uint64_t)(cp)[4] << 24) | \ 2663 ((uint64_t)(cp)[3] << 32) | ((uint64_t)(cp)[2] << 40) | \ 2664 ((uint64_t)(cp)[1] << 48) | ((uint64_t)(cp)[0] << 56); \ 2665 } while (0) 2666 2667 #define BE_64_TO_8(cp, src) do { \ 2668 (cp)[0] = (src) >> 56; \ 2669 (cp)[1] = (src) >> 48; \ 2670 (cp)[2] = (src) >> 40; \ 2671 (cp)[3] = (src) >> 32; \ 2672 (cp)[4] = (src) >> 24; \ 2673 (cp)[5] = (src) >> 16; \ 2674 (cp)[6] = (src) >> 8; \ 2675 (cp)[7] = (src); \ 2676 } while (0) 2677 2678 #define BE_32_TO_8(cp, src) do { \ 2679 (cp)[0] = (src) >> 24; \ 2680 (cp)[1] = (src) >> 16; \ 2681 (cp)[2] = (src) >> 8; \ 2682 (cp)[3] = (src); \ 2683 } while (0) 2684 2685 /* 2686 * Macro for incrementally adding the unsigned 64-bit integer n to the 2687 * unsigned 128-bit integer (represented using a two-element array of 2688 * 64-bit words): 2689 */ 2690 #define ADDINC128(w,n) do { \ 2691 (w)[0] += (uint64_t)(n); \ 2692 if ((w)[0] < (n)) { \ 2693 (w)[1]++; \ 2694 } \ 2695 } while (0) 2696 2697 /*** THE SIX LOGICAL FUNCTIONS ****************************************/ 2698 /* 2699 * Bit shifting and rotation (used by the six SHA-XYZ logical functions: 2700 * 2701 * NOTE: The naming of R and S appears backwards here (R is a SHIFT and 2702 * S is a ROTATION) because the SHA-224/256/384/512 description document 2703 * (see http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf) uses this 2704 * same "backwards" definition. 2705 */ 2706 /* Shift-right (used in SHA-224, SHA-256, SHA-384, and SHA-512): */ 2707 #define R(b,x) ((x) >> (b)) 2708 /* 32-bit Rotate-right (used in SHA-224 and SHA-256): */ 2709 #define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) 2710 /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */ 2711 #define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b)))) 2712 2713 /* Two of six logical functions used in SHA-224, SHA-256, SHA-384, and SHA-512: */ 2714 #define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) 2715 #define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 2716 2717 /* Four of six logical functions used in SHA-224 and SHA-256: */ 2718 #define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) 2719 #define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) 2720 #define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) 2721 #define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) 2722 2723 /* Four of six logical functions used in SHA-384 and SHA-512: */ 2724 #define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) 2725 #define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) 2726 #define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x))) 2727 #define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x))) 2728 2729 2730 /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/ 2731 /* Hash constant words K for SHA-224 and SHA-256: */ 2732 static const uint32_t K256[64] = { 2733 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 2734 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 2735 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 2736 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 2737 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 2738 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 2739 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 2740 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 2741 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 2742 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, 2743 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 2744 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 2745 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 2746 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 2747 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 2748 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL 2749 }; 2750 2751 /* Initial hash value H for SHA-256: */ 2752 static const uint32_t sha256_initial_hash_value[8] = { 2753 0x6a09e667UL, 2754 0xbb67ae85UL, 2755 0x3c6ef372UL, 2756 0xa54ff53aUL, 2757 0x510e527fUL, 2758 0x9b05688cUL, 2759 0x1f83d9abUL, 2760 0x5be0cd19UL 2761 }; 2762 2763 /* Hash constant words K for SHA-384 and SHA-512: */ 2764 static const uint64_t K512[80] = { 2765 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 2766 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 2767 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 2768 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 2769 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 2770 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 2771 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 2772 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 2773 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 2774 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 2775 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 2776 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 2777 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 2778 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 2779 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 2780 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 2781 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 2782 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 2783 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 2784 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 2785 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 2786 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 2787 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 2788 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 2789 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 2790 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 2791 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 2792 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 2793 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 2794 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 2795 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 2796 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 2797 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 2798 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 2799 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 2800 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 2801 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 2802 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 2803 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 2804 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL 2805 }; 2806 2807 /* Initial hash value H for SHA-512 */ 2808 static const uint64_t sha512_initial_hash_value[8] = { 2809 0x6a09e667f3bcc908ULL, 2810 0xbb67ae8584caa73bULL, 2811 0x3c6ef372fe94f82bULL, 2812 0xa54ff53a5f1d36f1ULL, 2813 0x510e527fade682d1ULL, 2814 0x9b05688c2b3e6c1fULL, 2815 0x1f83d9abfb41bd6bULL, 2816 0x5be0cd19137e2179ULL 2817 }; 2818 2819 /* Initial hash value H for SHA-384 */ 2820 static const uint64_t sha384_initial_hash_value[8] = { 2821 0xcbbb9d5dc1059ed8ULL, 2822 0x629a292a367cd507ULL, 2823 0x9159015a3070dd17ULL, 2824 0x152fecd8f70e5939ULL, 2825 0x67332667ffc00b31ULL, 2826 0x8eb44a8768581511ULL, 2827 0xdb0c2e0d64f98fa7ULL, 2828 0x47b5481dbefa4fa4ULL 2829 }; 2830 2831 /*** SHA-256: *********************************************************/ 2832 void 2833 SHA256Init(SHA2_CTX *context) 2834 { 2835 memcpy(context->state.st32, sha256_initial_hash_value, 2836 sizeof(sha256_initial_hash_value)); 2837 memset(context->buffer, 0, sizeof(context->buffer)); 2838 context->bitcount[0] = 0; 2839 } 2840 2841 #ifdef SHA2_UNROLL_TRANSFORM 2842 2843 /* Unrolled SHA-256 round macros: */ 2844 2845 #define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) do { \ 2846 BE_8_TO_32(W256[j], data); \ 2847 data += 4; \ 2848 T1 = (h) + Sigma1_256((e)) + Ch((e), (f), (g)) + K256[j] + W256[j]; \ 2849 (d) += T1; \ 2850 (h) = T1 + Sigma0_256((a)) + Maj((a), (b), (c)); \ 2851 j++; \ 2852 } while(0) 2853 2854 #define ROUND256(a,b,c,d,e,f,g,h) do { \ 2855 s0 = W256[(j+1)&0x0f]; \ 2856 s0 = sigma0_256(s0); \ 2857 s1 = W256[(j+14)&0x0f]; \ 2858 s1 = sigma1_256(s1); \ 2859 T1 = (h) + Sigma1_256((e)) + Ch((e), (f), (g)) + K256[j] + \ 2860 (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ 2861 (d) += T1; \ 2862 (h) = T1 + Sigma0_256((a)) + Maj((a), (b), (c)); \ 2863 j++; \ 2864 } while(0) 2865 2866 void 2867 SHA256Transform(uint32_t state[8], const uint8_t data[SHA256_BLOCK_LENGTH]) 2868 { 2869 uint32_t a, b, c, d, e, f, g, h, s0, s1; 2870 uint32_t T1, W256[16]; 2871 int j; 2872 2873 /* Initialize registers with the prev. intermediate value */ 2874 a = state[0]; 2875 b = state[1]; 2876 c = state[2]; 2877 d = state[3]; 2878 e = state[4]; 2879 f = state[5]; 2880 g = state[6]; 2881 h = state[7]; 2882 2883 j = 0; 2884 do { 2885 /* Rounds 0 to 15 (unrolled): */ 2886 ROUND256_0_TO_15(a,b,c,d,e,f,g,h); 2887 ROUND256_0_TO_15(h,a,b,c,d,e,f,g); 2888 ROUND256_0_TO_15(g,h,a,b,c,d,e,f); 2889 ROUND256_0_TO_15(f,g,h,a,b,c,d,e); 2890 ROUND256_0_TO_15(e,f,g,h,a,b,c,d); 2891 ROUND256_0_TO_15(d,e,f,g,h,a,b,c); 2892 ROUND256_0_TO_15(c,d,e,f,g,h,a,b); 2893 ROUND256_0_TO_15(b,c,d,e,f,g,h,a); 2894 } while (j < 16); 2895 2896 /* Now for the remaining rounds up to 63: */ 2897 do { 2898 ROUND256(a,b,c,d,e,f,g,h); 2899 ROUND256(h,a,b,c,d,e,f,g); 2900 ROUND256(g,h,a,b,c,d,e,f); 2901 ROUND256(f,g,h,a,b,c,d,e); 2902 ROUND256(e,f,g,h,a,b,c,d); 2903 ROUND256(d,e,f,g,h,a,b,c); 2904 ROUND256(c,d,e,f,g,h,a,b); 2905 ROUND256(b,c,d,e,f,g,h,a); 2906 } while (j < 64); 2907 2908 /* Compute the current intermediate hash value */ 2909 state[0] += a; 2910 state[1] += b; 2911 state[2] += c; 2912 state[3] += d; 2913 state[4] += e; 2914 state[5] += f; 2915 state[6] += g; 2916 state[7] += h; 2917 2918 /* Clean up */ 2919 a = b = c = d = e = f = g = h = T1 = 0; 2920 } 2921 2922 #else /* SHA2_UNROLL_TRANSFORM */ 2923 2924 void 2925 SHA256Transform(uint32_t state[8], const uint8_t data[SHA256_BLOCK_LENGTH]) 2926 { 2927 uint32_t a, b, c, d, e, f, g, h, s0, s1; 2928 uint32_t T1, T2, W256[16]; 2929 int j; 2930 2931 /* Initialize registers with the prev. intermediate value */ 2932 a = state[0]; 2933 b = state[1]; 2934 c = state[2]; 2935 d = state[3]; 2936 e = state[4]; 2937 f = state[5]; 2938 g = state[6]; 2939 h = state[7]; 2940 2941 j = 0; 2942 do { 2943 BE_8_TO_32(W256[j], data); 2944 data += 4; 2945 /* Apply the SHA-256 compression function to update a..h */ 2946 T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; 2947 T2 = Sigma0_256(a) + Maj(a, b, c); 2948 h = g; 2949 g = f; 2950 f = e; 2951 e = d + T1; 2952 d = c; 2953 c = b; 2954 b = a; 2955 a = T1 + T2; 2956 2957 j++; 2958 } while (j < 16); 2959 2960 do { 2961 /* Part of the message block expansion: */ 2962 s0 = W256[(j+1)&0x0f]; 2963 s0 = sigma0_256(s0); 2964 s1 = W256[(j+14)&0x0f]; 2965 s1 = sigma1_256(s1); 2966 2967 /* Apply the SHA-256 compression function to update a..h */ 2968 T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + 2969 (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); 2970 T2 = Sigma0_256(a) + Maj(a, b, c); 2971 h = g; 2972 g = f; 2973 f = e; 2974 e = d + T1; 2975 d = c; 2976 c = b; 2977 b = a; 2978 a = T1 + T2; 2979 2980 j++; 2981 } while (j < 64); 2982 2983 /* Compute the current intermediate hash value */ 2984 state[0] += a; 2985 state[1] += b; 2986 state[2] += c; 2987 state[3] += d; 2988 state[4] += e; 2989 state[5] += f; 2990 state[6] += g; 2991 state[7] += h; 2992 2993 /* Clean up */ 2994 a = b = c = d = e = f = g = h = T1 = T2 = 0; 2995 } 2996 2997 #endif /* SHA2_UNROLL_TRANSFORM */ 2998 2999 void 3000 SHA256Update(SHA2_CTX *context, const uint8_t *data, size_t len) 3001 { 3002 uint64_t freespace, usedspace; 3003 3004 /* Calling with no data is valid (we do nothing) */ 3005 if (len == 0) 3006 return; 3007 3008 usedspace = (context->bitcount[0] >> 3) % SHA256_BLOCK_LENGTH; 3009 if (usedspace > 0) { 3010 /* Calculate how much free space is available in the buffer */ 3011 freespace = SHA256_BLOCK_LENGTH - usedspace; 3012 3013 if (len >= freespace) { 3014 /* Fill the buffer completely and process it */ 3015 memcpy(&context->buffer[usedspace], data, freespace); 3016 context->bitcount[0] += freespace << 3; 3017 len -= freespace; 3018 data += freespace; 3019 SHA256Transform(context->state.st32, context->buffer); 3020 } else { 3021 /* The buffer is not yet full */ 3022 memcpy(&context->buffer[usedspace], data, len); 3023 context->bitcount[0] += (uint64_t)len << 3; 3024 /* Clean up: */ 3025 usedspace = freespace = 0; 3026 return; 3027 } 3028 } 3029 while (len >= SHA256_BLOCK_LENGTH) { 3030 /* Process as many complete blocks as we can */ 3031 SHA256Transform(context->state.st32, data); 3032 context->bitcount[0] += SHA256_BLOCK_LENGTH << 3; 3033 len -= SHA256_BLOCK_LENGTH; 3034 data += SHA256_BLOCK_LENGTH; 3035 } 3036 if (len > 0) { 3037 /* There's left-overs, so save 'em */ 3038 memcpy(context->buffer, data, len); 3039 context->bitcount[0] += len << 3; 3040 } 3041 /* Clean up: */ 3042 usedspace = freespace = 0; 3043 } 3044 3045 void 3046 SHA256Pad(SHA2_CTX *context) 3047 { 3048 unsigned int usedspace; 3049 3050 usedspace = (context->bitcount[0] >> 3) % SHA256_BLOCK_LENGTH; 3051 if (usedspace > 0) { 3052 /* Begin padding with a 1 bit: */ 3053 context->buffer[usedspace++] = 0x80; 3054 3055 if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { 3056 /* Set-up for the last transform: */ 3057 memset(&context->buffer[usedspace], 0, 3058 SHA256_SHORT_BLOCK_LENGTH - usedspace); 3059 } else { 3060 if (usedspace < SHA256_BLOCK_LENGTH) { 3061 memset(&context->buffer[usedspace], 0, 3062 SHA256_BLOCK_LENGTH - usedspace); 3063 } 3064 /* Do second-to-last transform: */ 3065 SHA256Transform(context->state.st32, context->buffer); 3066 3067 /* Prepare for last transform: */ 3068 memset(context->buffer, 0, SHA256_SHORT_BLOCK_LENGTH); 3069 } 3070 } else { 3071 /* Set-up for the last transform: */ 3072 memset(context->buffer, 0, SHA256_SHORT_BLOCK_LENGTH); 3073 3074 /* Begin padding with a 1 bit: */ 3075 *context->buffer = 0x80; 3076 } 3077 /* Store the length of input data (in bits) in big endian format: */ 3078 BE_64_TO_8(&context->buffer[SHA256_SHORT_BLOCK_LENGTH], 3079 context->bitcount[0]); 3080 3081 /* Final transform: */ 3082 SHA256Transform(context->state.st32, context->buffer); 3083 3084 /* Clean up: */ 3085 usedspace = 0; 3086 } 3087 3088 void 3089 SHA256Final(uint8_t digest[SHA256_DIGEST_LENGTH], SHA2_CTX *context) 3090 { 3091 SHA256Pad(context); 3092 3093 #if BYTE_ORDER == LITTLE_ENDIAN 3094 int i; 3095 3096 /* Convert TO host byte order */ 3097 for (i = 0; i < 8; i++) 3098 BE_32_TO_8(digest + i * 4, context->state.st32[i]); 3099 #else 3100 memcpy(digest, context->state.st32, SHA256_DIGEST_LENGTH); 3101 #endif 3102 explicit_bzero(context, sizeof(*context)); 3103 } 3104 3105 3106 /*** SHA-512: *********************************************************/ 3107 void 3108 SHA512Init(SHA2_CTX *context) 3109 { 3110 memcpy(context->state.st64, sha512_initial_hash_value, 3111 sizeof(sha512_initial_hash_value)); 3112 memset(context->buffer, 0, sizeof(context->buffer)); 3113 context->bitcount[0] = context->bitcount[1] = 0; 3114 } 3115 3116 #ifdef SHA2_UNROLL_TRANSFORM 3117 3118 /* Unrolled SHA-512 round macros: */ 3119 3120 #define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) do { \ 3121 BE_8_TO_64(W512[j], data); \ 3122 data += 8; \ 3123 T1 = (h) + Sigma1_512((e)) + Ch((e), (f), (g)) + K512[j] + W512[j]; \ 3124 (d) += T1; \ 3125 (h) = T1 + Sigma0_512((a)) + Maj((a), (b), (c)); \ 3126 j++; \ 3127 } while(0) 3128 3129 3130 #define ROUND512(a,b,c,d,e,f,g,h) do { \ 3131 s0 = W512[(j+1)&0x0f]; \ 3132 s0 = sigma0_512(s0); \ 3133 s1 = W512[(j+14)&0x0f]; \ 3134 s1 = sigma1_512(s1); \ 3135 T1 = (h) + Sigma1_512((e)) + Ch((e), (f), (g)) + K512[j] + \ 3136 (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ 3137 (d) += T1; \ 3138 (h) = T1 + Sigma0_512((a)) + Maj((a), (b), (c)); \ 3139 j++; \ 3140 } while(0) 3141 3142 void 3143 SHA512Transform(uint64_t state[8], const uint8_t data[SHA512_BLOCK_LENGTH]) 3144 { 3145 uint64_t a, b, c, d, e, f, g, h, s0, s1; 3146 uint64_t T1, W512[16]; 3147 int j; 3148 3149 /* Initialize registers with the prev. intermediate value */ 3150 a = state[0]; 3151 b = state[1]; 3152 c = state[2]; 3153 d = state[3]; 3154 e = state[4]; 3155 f = state[5]; 3156 g = state[6]; 3157 h = state[7]; 3158 3159 j = 0; 3160 do { 3161 /* Rounds 0 to 15 (unrolled): */ 3162 ROUND512_0_TO_15(a,b,c,d,e,f,g,h); 3163 ROUND512_0_TO_15(h,a,b,c,d,e,f,g); 3164 ROUND512_0_TO_15(g,h,a,b,c,d,e,f); 3165 ROUND512_0_TO_15(f,g,h,a,b,c,d,e); 3166 ROUND512_0_TO_15(e,f,g,h,a,b,c,d); 3167 ROUND512_0_TO_15(d,e,f,g,h,a,b,c); 3168 ROUND512_0_TO_15(c,d,e,f,g,h,a,b); 3169 ROUND512_0_TO_15(b,c,d,e,f,g,h,a); 3170 } while (j < 16); 3171 3172 /* Now for the remaining rounds up to 79: */ 3173 do { 3174 ROUND512(a,b,c,d,e,f,g,h); 3175 ROUND512(h,a,b,c,d,e,f,g); 3176 ROUND512(g,h,a,b,c,d,e,f); 3177 ROUND512(f,g,h,a,b,c,d,e); 3178 ROUND512(e,f,g,h,a,b,c,d); 3179 ROUND512(d,e,f,g,h,a,b,c); 3180 ROUND512(c,d,e,f,g,h,a,b); 3181 ROUND512(b,c,d,e,f,g,h,a); 3182 } while (j < 80); 3183 3184 /* Compute the current intermediate hash value */ 3185 state[0] += a; 3186 state[1] += b; 3187 state[2] += c; 3188 state[3] += d; 3189 state[4] += e; 3190 state[5] += f; 3191 state[6] += g; 3192 state[7] += h; 3193 3194 /* Clean up */ 3195 a = b = c = d = e = f = g = h = T1 = 0; 3196 } 3197 3198 #else /* SHA2_UNROLL_TRANSFORM */ 3199 3200 void 3201 SHA512Transform(uint64_t state[8], const uint8_t data[SHA512_BLOCK_LENGTH]) 3202 { 3203 uint64_t a, b, c, d, e, f, g, h, s0, s1; 3204 uint64_t T1, T2, W512[16]; 3205 int j; 3206 3207 /* Initialize registers with the prev. intermediate value */ 3208 a = state[0]; 3209 b = state[1]; 3210 c = state[2]; 3211 d = state[3]; 3212 e = state[4]; 3213 f = state[5]; 3214 g = state[6]; 3215 h = state[7]; 3216 3217 j = 0; 3218 do { 3219 BE_8_TO_64(W512[j], data); 3220 data += 8; 3221 /* Apply the SHA-512 compression function to update a..h */ 3222 T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; 3223 T2 = Sigma0_512(a) + Maj(a, b, c); 3224 h = g; 3225 g = f; 3226 f = e; 3227 e = d + T1; 3228 d = c; 3229 c = b; 3230 b = a; 3231 a = T1 + T2; 3232 3233 j++; 3234 } while (j < 16); 3235 3236 do { 3237 /* Part of the message block expansion: */ 3238 s0 = W512[(j+1)&0x0f]; 3239 s0 = sigma0_512(s0); 3240 s1 = W512[(j+14)&0x0f]; 3241 s1 = sigma1_512(s1); 3242 3243 /* Apply the SHA-512 compression function to update a..h */ 3244 T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + 3245 (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); 3246 T2 = Sigma0_512(a) + Maj(a, b, c); 3247 h = g; 3248 g = f; 3249 f = e; 3250 e = d + T1; 3251 d = c; 3252 c = b; 3253 b = a; 3254 a = T1 + T2; 3255 3256 j++; 3257 } while (j < 80); 3258 3259 /* Compute the current intermediate hash value */ 3260 state[0] += a; 3261 state[1] += b; 3262 state[2] += c; 3263 state[3] += d; 3264 state[4] += e; 3265 state[5] += f; 3266 state[6] += g; 3267 state[7] += h; 3268 3269 /* Clean up */ 3270 a = b = c = d = e = f = g = h = T1 = T2 = 0; 3271 } 3272 3273 #endif /* SHA2_UNROLL_TRANSFORM */ 3274 3275 void 3276 SHA512Update(SHA2_CTX *context, const uint8_t *data, size_t len) 3277 { 3278 size_t freespace, usedspace; 3279 3280 /* Calling with no data is valid (we do nothing) */ 3281 if (len == 0) 3282 return; 3283 3284 usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; 3285 if (usedspace > 0) { 3286 /* Calculate how much free space is available in the buffer */ 3287 freespace = SHA512_BLOCK_LENGTH - usedspace; 3288 3289 if (len >= freespace) { 3290 /* Fill the buffer completely and process it */ 3291 memcpy(&context->buffer[usedspace], data, freespace); 3292 ADDINC128(context->bitcount, freespace << 3); 3293 len -= freespace; 3294 data += freespace; 3295 SHA512Transform(context->state.st64, context->buffer); 3296 } else { 3297 /* The buffer is not yet full */ 3298 memcpy(&context->buffer[usedspace], data, len); 3299 ADDINC128(context->bitcount, len << 3); 3300 /* Clean up: */ 3301 usedspace = freespace = 0; 3302 return; 3303 } 3304 } 3305 while (len >= SHA512_BLOCK_LENGTH) { 3306 /* Process as many complete blocks as we can */ 3307 SHA512Transform(context->state.st64, data); 3308 ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); 3309 len -= SHA512_BLOCK_LENGTH; 3310 data += SHA512_BLOCK_LENGTH; 3311 } 3312 if (len > 0) { 3313 /* There's left-overs, so save 'em */ 3314 memcpy(context->buffer, data, len); 3315 ADDINC128(context->bitcount, len << 3); 3316 } 3317 /* Clean up: */ 3318 usedspace = freespace = 0; 3319 } 3320 3321 void 3322 SHA512Pad(SHA2_CTX *context) 3323 { 3324 unsigned int usedspace; 3325 3326 usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; 3327 if (usedspace > 0) { 3328 /* Begin padding with a 1 bit: */ 3329 context->buffer[usedspace++] = 0x80; 3330 3331 if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { 3332 /* Set-up for the last transform: */ 3333 memset(&context->buffer[usedspace], 0, SHA512_SHORT_BLOCK_LENGTH - usedspace); 3334 } else { 3335 if (usedspace < SHA512_BLOCK_LENGTH) { 3336 memset(&context->buffer[usedspace], 0, SHA512_BLOCK_LENGTH - usedspace); 3337 } 3338 /* Do second-to-last transform: */ 3339 SHA512Transform(context->state.st64, context->buffer); 3340 3341 /* And set-up for the last transform: */ 3342 memset(context->buffer, 0, SHA512_BLOCK_LENGTH - 2); 3343 } 3344 } else { 3345 /* Prepare for final transform: */ 3346 memset(context->buffer, 0, SHA512_SHORT_BLOCK_LENGTH); 3347 3348 /* Begin padding with a 1 bit: */ 3349 *context->buffer = 0x80; 3350 } 3351 /* Store the length of input data (in bits) in big endian format: */ 3352 BE_64_TO_8(&context->buffer[SHA512_SHORT_BLOCK_LENGTH], 3353 context->bitcount[1]); 3354 BE_64_TO_8(&context->buffer[SHA512_SHORT_BLOCK_LENGTH + 8], 3355 context->bitcount[0]); 3356 3357 /* Final transform: */ 3358 SHA512Transform(context->state.st64, context->buffer); 3359 3360 /* Clean up: */ 3361 usedspace = 0; 3362 } 3363 3364 void 3365 SHA512Final(uint8_t digest[SHA512_DIGEST_LENGTH], SHA2_CTX *context) 3366 { 3367 SHA512Pad(context); 3368 3369 #if BYTE_ORDER == LITTLE_ENDIAN 3370 int i; 3371 3372 /* Convert TO host byte order */ 3373 for (i = 0; i < 8; i++) 3374 BE_64_TO_8(digest + i * 8, context->state.st64[i]); 3375 #else 3376 memcpy(digest, context->state.st64, SHA512_DIGEST_LENGTH); 3377 #endif 3378 explicit_bzero(context, sizeof(*context)); 3379 } 3380 3381 /*** SHA-384: *********************************************************/ 3382 void 3383 SHA384Init(SHA2_CTX *context) 3384 { 3385 memcpy(context->state.st64, sha384_initial_hash_value, 3386 sizeof(sha384_initial_hash_value)); 3387 memset(context->buffer, 0, sizeof(context->buffer)); 3388 context->bitcount[0] = context->bitcount[1] = 0; 3389 } 3390 3391 MAKE_CLONE(SHA384Transform, SHA512Transform); 3392 MAKE_CLONE(SHA384Update, SHA512Update); 3393 MAKE_CLONE(SHA384Pad, SHA512Pad); 3394 3395 /* Equivalent of MAKE_CLONE (which is a no-op) for SHA384 funcs */ 3396 void 3397 SHA384Transform(uint64_t state[8], const uint8_t data[SHA512_BLOCK_LENGTH]) 3398 { 3399 SHA512Transform(state, data); 3400 } 3401 3402 void 3403 SHA384Update(SHA2_CTX *context, const uint8_t *data, size_t len) 3404 { 3405 SHA512Update(context, data, len); 3406 } 3407 3408 void 3409 SHA384Pad(SHA2_CTX *context) 3410 { 3411 SHA512Pad(context); 3412 } 3413 3414 void 3415 SHA384Final(uint8_t digest[SHA384_DIGEST_LENGTH], SHA2_CTX *context) 3416 { 3417 SHA384Pad(context); 3418 3419 #if BYTE_ORDER == LITTLE_ENDIAN 3420 int i; 3421 3422 /* Convert TO host byte order */ 3423 for (i = 0; i < 6; i++) 3424 BE_64_TO_8(digest + i * 8, context->state.st64[i]); 3425 #else 3426 memcpy(digest, context->state.st64, SHA384_DIGEST_LENGTH); 3427 #endif 3428 /* Zero out state data */ 3429 explicit_bzero(context, sizeof(*context)); 3430 } 3431 3432 char * 3433 SHA256End(SHA2_CTX *ctx, char *buf) 3434 { 3435 int i; 3436 uint8_t digest[SHA256_DIGEST_LENGTH]; 3437 static const char hex[] = "0123456789abcdef"; 3438 3439 if (buf == NULL && (buf = malloc(SHA256_DIGEST_STRING_LENGTH)) == NULL) 3440 return (NULL); 3441 3442 SHA256Final(digest, ctx); 3443 for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { 3444 buf[i + i] = hex[digest[i] >> 4]; 3445 buf[i + i + 1] = hex[digest[i] & 0x0f]; 3446 } 3447 buf[i + i] = '\0'; 3448 explicit_bzero(digest, sizeof(digest)); 3449 return (buf); 3450 } 3451 3452 char * 3453 SHA384End(SHA2_CTX *ctx, char *buf) 3454 { 3455 int i; 3456 uint8_t digest[SHA384_DIGEST_LENGTH]; 3457 static const char hex[] = "0123456789abcdef"; 3458 3459 if (buf == NULL && (buf = malloc(SHA384_DIGEST_STRING_LENGTH)) == NULL) 3460 return (NULL); 3461 3462 SHA384Final(digest, ctx); 3463 for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { 3464 buf[i + i] = hex[digest[i] >> 4]; 3465 buf[i + i + 1] = hex[digest[i] & 0x0f]; 3466 } 3467 buf[i + i] = '\0'; 3468 explicit_bzero(digest, sizeof(digest)); 3469 return (buf); 3470 } 3471 3472 char * 3473 SHA512End(SHA2_CTX *ctx, char *buf) 3474 { 3475 int i; 3476 uint8_t digest[SHA512_DIGEST_LENGTH]; 3477 static const char hex[] = "0123456789abcdef"; 3478 3479 if (buf == NULL && (buf = malloc(SHA512_DIGEST_STRING_LENGTH)) == NULL) 3480 return (NULL); 3481 3482 SHA512Final(digest, ctx); 3483 for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { 3484 buf[i + i] = hex[digest[i] >> 4]; 3485 buf[i + i + 1] = hex[digest[i] & 0x0f]; 3486 } 3487 buf[i + i] = '\0'; 3488 explicit_bzero(digest, sizeof(digest)); 3489 return (buf); 3490 } 3491 3492 char * 3493 SHA256FileChunk(const char *filename, char *buf, off_t off, off_t len) 3494 { 3495 struct stat sb; 3496 u_char buffer[BUFSIZ]; 3497 SHA2_CTX ctx; 3498 int fd, save_errno; 3499 ssize_t nr; 3500 3501 SHA256Init(&ctx); 3502 3503 if ((fd = open(filename, O_RDONLY)) == -1) 3504 return (NULL); 3505 if (len == 0) { 3506 if (fstat(fd, &sb) == -1) { 3507 save_errno = errno; 3508 close(fd); 3509 errno = save_errno; 3510 return (NULL); 3511 } 3512 len = sb.st_size; 3513 } 3514 if (off > 0 && lseek(fd, off, SEEK_SET) == -1) { 3515 save_errno = errno; 3516 close(fd); 3517 errno = save_errno; 3518 return (NULL); 3519 } 3520 3521 while ((nr = read(fd, buffer, MINIMUM(sizeof(buffer), (size_t)len))) > 0) { 3522 SHA256Update(&ctx, buffer, nr); 3523 if (len > 0 && (len -= nr) == 0) 3524 break; 3525 } 3526 3527 save_errno = errno; 3528 close(fd); 3529 errno = save_errno; 3530 return (nr == -1 ? NULL : SHA256End(&ctx, buf)); 3531 } 3532 3533 char * 3534 SHA256File(const char *filename, char *buf) 3535 { 3536 return (SHA256FileChunk(filename, buf, 0, 0)); 3537 } 3538 3539 char * 3540 SHA384FileChunk(const char *filename, char *buf, off_t off, off_t len) 3541 { 3542 struct stat sb; 3543 u_char buffer[BUFSIZ]; 3544 SHA2_CTX ctx; 3545 int fd, save_errno; 3546 ssize_t nr; 3547 3548 SHA384Init(&ctx); 3549 3550 if ((fd = open(filename, O_RDONLY)) == -1) 3551 return (NULL); 3552 if (len == 0) { 3553 if (fstat(fd, &sb) == -1) { 3554 save_errno = errno; 3555 close(fd); 3556 errno = save_errno; 3557 return (NULL); 3558 } 3559 len = sb.st_size; 3560 } 3561 if (off > 0 && lseek(fd, off, SEEK_SET) == -1) { 3562 save_errno = errno; 3563 close(fd); 3564 errno = save_errno; 3565 return (NULL); 3566 } 3567 3568 while ((nr = read(fd, buffer, MINIMUM(sizeof(buffer), (size_t)len))) > 0) { 3569 SHA384Update(&ctx, buffer, nr); 3570 if (len > 0 && (len -= nr) == 0) 3571 break; 3572 } 3573 3574 save_errno = errno; 3575 close(fd); 3576 errno = save_errno; 3577 return (nr == -1 ? NULL : SHA384End(&ctx, buf)); 3578 } 3579 3580 char * 3581 SHA384File(const char *filename, char *buf) 3582 { 3583 return (SHA384FileChunk(filename, buf, 0, 0)); 3584 } 3585 3586 char * 3587 SHA512FileChunk(const char *filename, char *buf, off_t off, off_t len) 3588 { 3589 struct stat sb; 3590 u_char buffer[BUFSIZ]; 3591 SHA2_CTX ctx; 3592 int fd, save_errno; 3593 ssize_t nr; 3594 3595 SHA512Init(&ctx); 3596 3597 if ((fd = open(filename, O_RDONLY)) == -1) 3598 return (NULL); 3599 if (len == 0) { 3600 if (fstat(fd, &sb) == -1) { 3601 save_errno = errno; 3602 close(fd); 3603 errno = save_errno; 3604 return (NULL); 3605 } 3606 len = sb.st_size; 3607 } 3608 if (off > 0 && lseek(fd, off, SEEK_SET) == -1) { 3609 save_errno = errno; 3610 close(fd); 3611 errno = save_errno; 3612 return (NULL); 3613 } 3614 3615 while ((nr = read(fd, buffer, MINIMUM(sizeof(buffer), (size_t)len))) > 0) { 3616 SHA512Update(&ctx, buffer, nr); 3617 if (len > 0 && (len -= nr) == 0) 3618 break; 3619 } 3620 3621 save_errno = errno; 3622 close(fd); 3623 errno = save_errno; 3624 return (nr == -1 ? NULL : SHA512End(&ctx, buf)); 3625 } 3626 3627 char * 3628 SHA512File(const char *filename, char *buf) 3629 { 3630 return (SHA512FileChunk(filename, buf, 0, 0)); 3631 } 3632 3633 char * 3634 SHA256Data(const u_char *data, size_t len, char *buf) 3635 { 3636 SHA2_CTX ctx; 3637 3638 SHA256Init(&ctx); 3639 SHA256Update(&ctx, data, len); 3640 return (SHA256End(&ctx, buf)); 3641 } 3642 3643 char * 3644 SHA384Data(const u_char *data, size_t len, char *buf) 3645 { 3646 SHA2_CTX ctx; 3647 3648 SHA384Init(&ctx); 3649 SHA384Update(&ctx, data, len); 3650 return (SHA384End(&ctx, buf)); 3651 } 3652 3653 char * 3654 SHA512Data(const u_char *data, size_t len, char *buf) 3655 { 3656 SHA2_CTX ctx; 3657 3658 SHA512Init(&ctx); 3659 SHA512Update(&ctx, data, len); 3660 return (SHA512End(&ctx, buf)); 3661 } 3662 #endif /* !HAVE_SHA2_H */ 3663 #if !HAVE_STRLCAT 3664 /* 3665 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> 3666 * 3667 * Permission to use, copy, modify, and distribute this software for any 3668 * purpose with or without fee is hereby granted, provided that the above 3669 * copyright notice and this permission notice appear in all copies. 3670 * 3671 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 3672 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 3673 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 3674 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 3675 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 3676 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 3677 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 3678 */ 3679 3680 #include <sys/types.h> 3681 #include <string.h> 3682 3683 /* 3684 * Appends src to string dst of size siz (unlike strncat, siz is the 3685 * full size of dst, not space left). At most siz-1 characters 3686 * will be copied. Always NUL terminates (unless siz <= strlen(dst)). 3687 * Returns strlen(src) + MIN(siz, strlen(initial dst)). 3688 * If retval >= siz, truncation occurred. 3689 */ 3690 size_t 3691 strlcat(char *dst, const char *src, size_t siz) 3692 { 3693 char *d = dst; 3694 const char *s = src; 3695 size_t n = siz; 3696 size_t dlen; 3697 3698 /* Find the end of dst and adjust bytes left but don't go past end */ 3699 while (n-- != 0 && *d != '\0') 3700 d++; 3701 dlen = d - dst; 3702 n = siz - dlen; 3703 3704 if (n == 0) 3705 return(dlen + strlen(s)); 3706 while (*s != '\0') { 3707 if (n != 1) { 3708 *d++ = *s; 3709 n--; 3710 } 3711 s++; 3712 } 3713 *d = '\0'; 3714 3715 return(dlen + (s - src)); /* count does not include NUL */ 3716 } 3717 #endif /* !HAVE_STRLCAT */ 3718 #if !HAVE_STRLCPY 3719 /* 3720 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> 3721 * 3722 * Permission to use, copy, modify, and distribute this software for any 3723 * purpose with or without fee is hereby granted, provided that the above 3724 * copyright notice and this permission notice appear in all copies. 3725 * 3726 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 3727 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 3728 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 3729 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 3730 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 3731 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 3732 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 3733 */ 3734 3735 #include <sys/types.h> 3736 #include <string.h> 3737 3738 /* 3739 * Copy src to string dst of size siz. At most siz-1 characters 3740 * will be copied. Always NUL terminates (unless siz == 0). 3741 * Returns strlen(src); if retval >= siz, truncation occurred. 3742 */ 3743 size_t 3744 strlcpy(char *dst, const char *src, size_t siz) 3745 { 3746 char *d = dst; 3747 const char *s = src; 3748 size_t n = siz; 3749 3750 /* Copy as many bytes as will fit */ 3751 if (n != 0) { 3752 while (--n != 0) { 3753 if ((*d++ = *s++) == '\0') 3754 break; 3755 } 3756 } 3757 3758 /* Not enough room in dst, add NUL and traverse rest of src */ 3759 if (n == 0) { 3760 if (siz != 0) 3761 *d = '\0'; /* NUL-terminate dst */ 3762 while (*s++) 3763 ; 3764 } 3765 3766 return(s - src - 1); /* count does not include NUL */ 3767 } 3768 #endif /* !HAVE_STRLCPY */ 3769 #if !HAVE_STRNDUP 3770 /* $OpenBSD$ */ 3771 /* 3772 * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com> 3773 * 3774 * Permission to use, copy, modify, and distribute this software for any 3775 * purpose with or without fee is hereby granted, provided that the above 3776 * copyright notice and this permission notice appear in all copies. 3777 * 3778 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 3779 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 3780 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 3781 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 3782 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 3783 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 3784 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 3785 */ 3786 3787 #include <sys/types.h> 3788 3789 #include <stddef.h> 3790 #include <stdlib.h> 3791 #include <string.h> 3792 3793 char * 3794 strndup(const char *str, size_t maxlen) 3795 { 3796 char *copy; 3797 size_t len; 3798 3799 len = strnlen(str, maxlen); 3800 copy = malloc(len + 1); 3801 if (copy != NULL) { 3802 (void)memcpy(copy, str, len); 3803 copy[len] = '\0'; 3804 } 3805 3806 return copy; 3807 } 3808 #endif /* !HAVE_STRNDUP */ 3809 #if !HAVE_STRNLEN 3810 /* $OpenBSD$ */ 3811 3812 /* 3813 * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com> 3814 * 3815 * Permission to use, copy, modify, and distribute this software for any 3816 * purpose with or without fee is hereby granted, provided that the above 3817 * copyright notice and this permission notice appear in all copies. 3818 * 3819 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 3820 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 3821 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 3822 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 3823 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 3824 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 3825 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 3826 */ 3827 3828 #include <sys/types.h> 3829 #include <string.h> 3830 3831 size_t 3832 strnlen(const char *str, size_t maxlen) 3833 { 3834 const char *cp; 3835 3836 for (cp = str; maxlen != 0 && *cp != '\0'; cp++, maxlen--) 3837 ; 3838 3839 return (size_t)(cp - str); 3840 } 3841 #endif /* !HAVE_STRNLEN */ 3842 #if !HAVE_STRTONUM 3843 /* 3844 * Copyright (c) 2004 Ted Unangst and Todd Miller 3845 * All rights reserved. 3846 * 3847 * Permission to use, copy, modify, and distribute this software for any 3848 * purpose with or without fee is hereby granted, provided that the above 3849 * copyright notice and this permission notice appear in all copies. 3850 * 3851 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 3852 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 3853 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 3854 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 3855 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 3856 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 3857 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 3858 */ 3859 3860 #include <errno.h> 3861 #include <limits.h> 3862 #include <stdlib.h> 3863 3864 #define INVALID 1 3865 #define TOOSMALL 2 3866 #define TOOLARGE 3 3867 3868 long long 3869 strtonum(const char *numstr, long long minval, long long maxval, 3870 const char **errstrp) 3871 { 3872 long long ll = 0; 3873 int error = 0; 3874 char *ep; 3875 struct errval { 3876 const char *errstr; 3877 int err; 3878 } ev[4] = { 3879 { NULL, 0 }, 3880 { "invalid", EINVAL }, 3881 { "too small", ERANGE }, 3882 { "too large", ERANGE }, 3883 }; 3884 3885 ev[0].err = errno; 3886 errno = 0; 3887 if (minval > maxval) { 3888 error = INVALID; 3889 } else { 3890 ll = strtoll(numstr, &ep, 10); 3891 if (numstr == ep || *ep != '\0') 3892 error = INVALID; 3893 else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval) 3894 error = TOOSMALL; 3895 else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval) 3896 error = TOOLARGE; 3897 } 3898 if (errstrp != NULL) 3899 *errstrp = ev[error].errstr; 3900 errno = ev[error].err; 3901 if (error) 3902 ll = 0; 3903 3904 return (ll); 3905 } 3906 #endif /* !HAVE_STRTONUM */