1#!/bin/sh 2 3#- 4# Copyright 2004-2006 Colin Percival 5# All rights reserved 6# 7# Redistribution and use in source and binary forms, with or without 8# modification, are permitted providing 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# 16# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 20# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 22# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 23# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 24# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 25# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26# POSSIBILITY OF SUCH DAMAGE. 27 28# $FreeBSD$ 29 30#### Usage function -- called from command-line handling code. 31 32# Usage instructions. Options not listed: 33# --debug -- don't filter output from utilities 34# --no-stats -- don't show progress statistics while fetching files 35usage () { 36 cat <<EOF 37usage: `basename $0` [options] command ... [path] 38 39Options: 40 -b basedir -- Operate on a system mounted at basedir 41 (default: /) 42 -d workdir -- Store working files in workdir 43 (default: /var/db/freebsd-update/) 44 -f conffile -- Read configuration options from conffile 45 (default: /etc/freebsd-update.conf) 46 -k KEY -- Trust an RSA key with SHA256 hash of KEY 47 -s server -- Server from which to fetch updates 48 (default: update.FreeBSD.org) 49 -t address -- Mail output of cron command, if any, to address 50 (default: root) 51Commands: 52 fetch -- Fetch updates from server 53 cron -- Sleep rand(3600) seconds, fetch updates, and send an 54 email if updates were found 55 install -- Install downloaded updates 56 rollback -- Uninstall most recently installed updates 57EOF 58 exit 0 59} 60 61#### Configuration processing functions 62 63#- 64# Configuration options are set in the following order of priority: 65# 1. Command line options 66# 2. Configuration file options 67# 3. Default options 68# In addition, certain options (e.g., IgnorePaths) can be specified multiple 69# times and (as long as these are all in the same place, e.g., inside the 70# configuration file) they will accumulate. Finally, because the path to the 71# configuration file can be specified at the command line, the entire command 72# line must be processed before we start reading the configuration file. 73# 74# Sound like a mess? It is. Here's how we handle this: 75# 1. Initialize CONFFILE and all the options to "". 76# 2. Process the command line. Throw an error if a non-accumulating option 77# is specified twice. 78# 3. If CONFFILE is "", set CONFFILE to /etc/freebsd-update.conf . 79# 4. For all the configuration options X, set X_saved to X. 80# 5. Initialize all the options to "". 81# 6. Read CONFFILE line by line, parsing options. 82# 7. For each configuration option X, set X to X_saved iff X_saved is not "". 83# 8. Repeat steps 4-7, except setting options to their default values at (6). 84 85CONFIGOPTIONS="KEYPRINT WORKDIR SERVERNAME MAILTO ALLOWADD ALLOWDELETE 86 KEEPMODIFIEDMETADATA COMPONENTS IGNOREPATHS UPDATEIFUNMODIFIED 87 BASEDIR VERBOSELEVEL" 88 89# Set all the configuration options to "". 90nullconfig () { 91 for X in ${CONFIGOPTIONS}; do 92 eval ${X}="" 93 done 94} 95 96# For each configuration option X, set X_saved to X. 97saveconfig () { 98 for X in ${CONFIGOPTIONS}; do 99 eval ${X}_saved=\$${X} 100 done 101} 102 103# For each configuration option X, set X to X_saved if X_saved is not "". 104mergeconfig () { 105 for X in ${CONFIGOPTIONS}; do 106 eval _=\$${X}_saved 107 if ! [ -z "${_}" ]; then 108 eval ${X}=\$${X}_saved 109 fi 110 done 111} 112 113# Set the trusted keyprint. 114config_KeyPrint () { 115 if [ -z ${KEYPRINT} ]; then 116 KEYPRINT=$1 117 else 118 return 1 119 fi 120} 121 122# Set the working directory. 123config_WorkDir () { 124 if [ -z ${WORKDIR} ]; then 125 WORKDIR=$1 126 else 127 return 1 128 fi 129} 130 131# Set the name of the server (pool) from which to fetch updates 132config_ServerName () { 133 if [ -z ${SERVERNAME} ]; then 134 SERVERNAME=$1 135 else 136 return 1 137 fi 138} 139 140# Set the address to which 'cron' output will be mailed. 141config_MailTo () { 142 if [ -z ${MAILTO} ]; then 143 MAILTO=$1 144 else 145 return 1 146 fi 147} 148 149# Set whether FreeBSD Update is allowed to add files (or directories, or 150# symlinks) which did not previously exist. 151config_AllowAdd () { 152 if [ -z ${ALLOWADD} ]; then 153 case $1 in 154 [Yy][Ee][Ss]) 155 ALLOWADD=yes 156 ;; 157 [Nn][Oo]) 158 ALLOWADD=no 159 ;; 160 *) 161 return 1 162 ;; 163 esac 164 else 165 return 1 166 fi 167} 168 169# Set whether FreeBSD Update is allowed to remove files/directories/symlinks. 170config_AllowDelete () { 171 if [ -z ${ALLOWDELETE} ]; then 172 case $1 in 173 [Yy][Ee][Ss]) 174 ALLOWDELETE=yes 175 ;; 176 [Nn][Oo]) 177 ALLOWDELETE=no 178 ;; 179 *) 180 return 1 181 ;; 182 esac 183 else 184 return 1 185 fi 186} 187 188# Set whether FreeBSD Update should keep existing inode ownership, 189# permissions, and flags, in the event that they have been modified locally 190# after the release. 191config_KeepModifiedMetadata () { 192 if [ -z ${KEEPMODIFIEDMETADATA} ]; then 193 case $1 in 194 [Yy][Ee][Ss]) 195 KEEPMODIFIEDMETADATA=yes 196 ;; 197 [Nn][Oo]) 198 KEEPMODIFIEDMETADATA=no 199 ;; 200 *) 201 return 1 202 ;; 203 esac 204 else 205 return 1 206 fi 207} 208 209# Add to the list of components which should be kept updated. 210config_Components () { 211 for C in $@; do 212 COMPONENTS="${COMPONENTS} ${C}" 213 done 214} 215 216# Add to the list of paths under which updates will be ignored. 217config_IgnorePaths () { 218 for C in $@; do 219 IGNOREPATHS="${IGNOREPATHS} ${C}" 220 done 221} 222 223# Add to the list of paths within which updates will be performed only if the 224# file on disk has not been modified locally. 225config_UpdateIfUnmodified () { 226 for C in $@; do 227 UPDATEIFUNMODIFIED="${UPDATEIFUNMODIFIED} ${C}" 228 done 229} 230 231# Work on a FreeBSD installation mounted under $1 232config_BaseDir () { 233 if [ -z ${BASEDIR} ]; then 234 BASEDIR=$1 235 else 236 return 1 237 fi 238} 239 240# Define what happens to output of utilities 241config_VerboseLevel () { 242 if [ -z ${VERBOSELEVEL} ]; then 243 case $1 in 244 [Dd][Ee][Bb][Uu][Gg]) 245 VERBOSELEVEL=debug 246 ;; 247 [Nn][Oo][Ss][Tt][Aa][Tt][Ss]) 248 VERBOSELEVEL=nostats 249 ;; 250 [Ss][Tt][Aa][Tt][Ss]) 251 VERBOSELEVEL=stats 252 ;; 253 *) 254 return 1 255 ;; 256 esac 257 else 258 return 1 259 fi 260} 261 262# Handle one line of configuration 263configline () { 264 if [ $# -eq 0 ]; then 265 return 266 fi 267 268 OPT=$1 269 shift 270 config_${OPT} $@ 271} 272 273#### Parameter handling functions. 274 275# Initialize parameters to null, just in case they're 276# set in the environment. 277init_params () { 278 # Configration settings 279 nullconfig 280 281 # No configuration file set yet 282 CONFFILE="" 283 284 # No commands specified yet 285 COMMANDS="" 286} 287 288# Parse the command line 289parse_cmdline () { 290 while [ $# -gt 0 ]; do 291 case "$1" in 292 # Location of configuration file 293 -f) 294 if [ $# -eq 1 ]; then usage; fi 295 if [ ! -z "${CONFFILE}" ]; then usage; fi 296 shift; CONFFILE="$1" 297 ;; 298 299 # Configuration file equivalents 300 -b) 301 if [ $# -eq 1 ]; then usage; fi; shift 302 config_BaseDir $1 || usage 303 ;; 304 -d) 305 if [ $# -eq 1 ]; then usage; fi; shift 306 config_WorkDir $1 || usage 307 ;; 308 -k) 309 if [ $# -eq 1 ]; then usage; fi; shift 310 config_KeyPrint $1 || usage 311 ;; 312 -s) 313 if [ $# -eq 1 ]; then usage; fi; shift 314 config_ServerName $1 || usage 315 ;; 316 -t) 317 if [ $# -eq 1 ]; then usage; fi; shift 318 config_MailTo $1 || usage 319 ;; 320 -v) 321 if [ $# -eq 1 ]; then usage; fi; shift 322 config_VerboseLevel $1 || usage 323 ;; 324 325 # Aliases for "-v debug" and "-v nostats" 326 --debug) 327 config_VerboseLevel debug || usage 328 ;; 329 --no-stats) 330 config_VerboseLevel nostats || usage 331 ;; 332 333 # Commands 334 cron | fetch | install | rollback) 335 COMMANDS="${COMMANDS} $1" 336 ;; 337 338 # Anything else is an error 339 *) 340 usage 341 ;; 342 esac 343 shift 344 done 345 346 # Make sure we have at least one command 347 if [ -z "${COMMANDS}" ]; then 348 usage 349 fi 350} 351 352# Parse the configuration file 353parse_conffile () { 354 # If a configuration file was specified on the command line, check 355 # that it exists and is readable. 356 if [ ! -z "${CONFFILE}" ] && [ ! -r "${CONFFILE}" ]; then 357 echo -n "File does not exist " 358 echo -n "or is not readable: " 359 echo ${CONFFILE} 360 exit 1 361 fi 362 363 # If a configuration file was not specified on the command line, 364 # use the default configuration file path. If that default does 365 # not exist, give up looking for any configuration. 366 if [ -z "${CONFFILE}" ]; then 367 CONFFILE="/etc/freebsd-update.conf" 368 if [ ! -r "${CONFFILE}" ]; then 369 return 370 fi 371 fi 372 373 # Save the configuration options specified on the command line, and 374 # clear all the options in preparation for reading the config file. 375 saveconfig 376 nullconfig 377 378 # Read the configuration file. Anything after the first '#' is 379 # ignored, and any blank lines are ignored. 380 L=0 381 while read LINE; do 382 L=$(($L + 1)) 383 LINEX=`echo "${LINE}" | cut -f 1 -d '#'` 384 if ! configline ${LINEX}; then 385 echo "Error processing configuration file, line $L:" 386 echo "==> ${LINE}" 387 exit 1 388 fi 389 done < ${CONFFILE} 390 391 # Merge the settings read from the configuration file with those 392 # provided at the command line. 393 mergeconfig 394} 395 396# Provide some default parameters 397default_params () { 398 # Save any parameters already configured, and clear the slate 399 saveconfig 400 nullconfig 401 402 # Default configurations 403 config_WorkDir /var/db/freebsd-update 404 config_MailTo root 405 config_AllowAdd yes 406 config_AllowDelete yes 407 config_KeepModifiedMetadata yes 408 config_BaseDir / 409 config_VerboseLevel stats 410 411 # Merge these defaults into the earlier-configured settings 412 mergeconfig 413} 414 415# Set utility output filtering options, based on ${VERBOSELEVEL} 416fetch_setup_verboselevel () { 417 case ${VERBOSELEVEL} in 418 debug) 419 QUIETREDIR="/dev/stderr" 420 QUIETFLAG=" " 421 STATSREDIR="/dev/stderr" 422 DDSTATS=".." 423 XARGST="-t" 424 NDEBUG=" " 425 ;; 426 nostats) 427 QUIETREDIR="" 428 QUIETFLAG="" 429 STATSREDIR="/dev/null" 430 DDSTATS=".." 431 XARGST="" 432 NDEBUG="" 433 ;; 434 stats) 435 QUIETREDIR="/dev/null" 436 QUIETFLAG="-q" 437 STATSREDIR="/dev/stdout" 438 DDSTATS="" 439 XARGST="" 440 NDEBUG="-n" 441 ;; 442 esac 443} 444 445# Perform sanity checks and set some final parameters 446# in preparation for fetching files. Figure out which 447# set of updates should be downloaded: If the user is 448# running *-p[0-9]+, strip off the last part; if the 449# user is running -SECURITY, call it -RELEASE. Chdir 450# into the working directory. 451fetch_check_params () { 452 export HTTP_USER_AGENT="freebsd-update (${COMMAND}, `uname -r`)" 453 454 _SERVERNAME_z=\ 455"SERVERNAME must be given via command line or configuration file." 456 _KEYPRINT_z="Key must be given via -k option or configuration file." 457 _KEYPRINT_bad="Invalid key fingerprint: " 458 _WORKDIR_bad="Directory does not exist or is not writable: " 459 460 if [ -z "${SERVERNAME}" ]; then 461 echo -n "`basename $0`: " 462 echo "${_SERVERNAME_z}" 463 exit 1 464 fi 465 if [ -z "${KEYPRINT}" ]; then 466 echo -n "`basename $0`: " 467 echo "${_KEYPRINT_z}" 468 exit 1 469 fi 470 if ! echo "${KEYPRINT}" | grep -qE "^[0-9a-f]{64}$"; then 471 echo -n "`basename $0`: " 472 echo -n "${_KEYPRINT_bad}" 473 echo ${KEYPRINT} 474 exit 1 475 fi 476 if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then 477 echo -n "`basename $0`: " 478 echo -n "${_WORKDIR_bad}" 479 echo ${WORKDIR} 480 exit 1 481 fi 482 cd ${WORKDIR} || exit 1 483 484 # Generate release number. The s/SECURITY/RELEASE/ bit exists 485 # to provide an upgrade path for FreeBSD Update 1.x users, since 486 # the kernels provided by FreeBSD Update 1.x are always labelled 487 # as X.Y-SECURITY. 488 RELNUM=`uname -r | 489 sed -E 's,-p[0-9]+,,' | 490 sed -E 's,-SECURITY,-RELEASE,'` 491 ARCH=`uname -m` 492 FETCHDIR=${RELNUM}/${ARCH} 493 494 # Figure out what directory contains the running kernel 495 BOOTFILE=`sysctl -n kern.bootfile` 496 KERNELDIR=${BOOTFILE%/kernel} 497 if ! [ -d ${KERNELDIR} ]; then 498 echo "Cannot identify running kernel" 499 exit 1 500 fi 501 502 # Define some paths 503 BSPATCH=/usr/bin/bspatch 504 SHA256=/sbin/sha256 505 PHTTPGET=/usr/libexec/phttpget 506 507 # Set up variables relating to VERBOSELEVEL 508 fetch_setup_verboselevel 509 510 # Construct a unique name from ${BASEDIR} 511 BDHASH=`echo ${BASEDIR} | sha256 -q` 512} 513 514# Perform sanity checks and set some final parameters in 515# preparation for installing updates. 516install_check_params () { 517 # Check that we are root. All sorts of things won't work otherwise. 518 if [ `id -u` != 0 ]; then 519 echo "You must be root to run this." 520 exit 1 521 fi 522 523 # Check that we have a working directory 524 _WORKDIR_bad="Directory does not exist or is not writable: " 525 if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then 526 echo -n "`basename $0`: " 527 echo -n "${_WORKDIR_bad}" 528 echo ${WORKDIR} 529 exit 1 530 fi 531 cd ${WORKDIR} || exit 1 532 533 # Construct a unique name from ${BASEDIR} 534 BDHASH=`echo ${BASEDIR} | sha256 -q` 535 536 # Check that we have updates ready to install 537 if ! [ -L ${BDHASH}-install ]; then 538 echo "No updates are available to install." 539 echo "Run '$0 fetch' first." 540 exit 1 541 fi 542 if ! [ -f ${BDHASH}-install/INDEX-OLD ] || 543 ! [ -f ${BDHASH}-install/INDEX-NEW ]; then 544 echo "Update manifest is corrupt -- this should never happen." 545 echo "Re-run '$0 fetch'." 546 exit 1 547 fi 548} 549 550# Perform sanity checks and set some final parameters in 551# preparation for UNinstalling updates. 552rollback_check_params () { 553 # Check that we are root. All sorts of things won't work otherwise. 554 if [ `id -u` != 0 ]; then 555 echo "You must be root to run this." 556 exit 1 557 fi 558 559 # Check that we have a working directory 560 _WORKDIR_bad="Directory does not exist or is not writable: " 561 if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then 562 echo -n "`basename $0`: " 563 echo -n "${_WORKDIR_bad}" 564 echo ${WORKDIR} 565 exit 1 566 fi 567 cd ${WORKDIR} || exit 1 568 569 # Construct a unique name from ${BASEDIR} 570 BDHASH=`echo ${BASEDIR} | sha256 -q` 571 572 # Check that we have updates ready to rollback 573 if ! [ -L ${BDHASH}-rollback ]; then 574 echo "No rollback directory found." 575 exit 1 576 fi 577 if ! [ -f ${BDHASH}-rollback/INDEX-OLD ] || 578 ! [ -f ${BDHASH}-rollback/INDEX-NEW ]; then 579 echo "Update manifest is corrupt -- this should never happen." 580 exit 1 581 fi 582} 583 584#### Core functionality -- the actual work gets done here 585 586# Use an SRV query to pick a server. If the SRV query doesn't provide 587# a useful answer, use the server name specified by the user. 588# Put another way... look up _http._tcp.${SERVERNAME} and pick a server 589# from that; or if no servers are returned, use ${SERVERNAME}. 590# This allows a user to specify "portsnap.freebsd.org" (in which case 591# portsnap will select one of the mirrors) or "portsnap5.tld.freebsd.org" 592# (in which case portsnap will use that particular server, since there 593# won't be an SRV entry for that name). 594# 595# We ignore the Port field, since we are always going to use port 80. 596 597# Fetch the mirror list, but do not pick a mirror yet. Returns 1 if 598# no mirrors are available for any reason. 599fetch_pick_server_init () { 600 : > serverlist_tried 601 602# Check that host(1) exists (i.e., that the system wasn't built with the 603# WITHOUT_BIND set) and don't try to find a mirror if it doesn't exist. 604 if ! which -s host; then 605 : > serverlist_full 606 return 1 607 fi 608 609 echo -n "Looking up ${SERVERNAME} mirrors... " 610 611# Issue the SRV query and pull out the Priority, Weight, and Target fields. 612# BIND 9 prints "$name has SRV record ..." while BIND 8 prints 613# "$name server selection ..."; we allow either format. 614 MLIST="_http._tcp.${SERVERNAME}" 615 host -t srv "${MLIST}" | 616 sed -nE "s/${MLIST} (has SRV record|server selection) //p" | 617 cut -f 1,2,4 -d ' ' | 618 sed -e 's/\.$//' | 619 sort > serverlist_full 620 621# If no records, give up -- we'll just use the server name we were given. 622 if [ `wc -l < serverlist_full` -eq 0 ]; then 623 echo "none found." 624 return 1 625 fi 626 627# Report how many mirrors we found. 628 echo `wc -l < serverlist_full` "mirrors found." 629 630# Generate a random seed for use in picking mirrors. If HTTP_PROXY 631# is set, this will be used to generate the seed; otherwise, the seed 632# will be random. 633 if [ -n "${HTTP_PROXY}${http_proxy}" ]; then 634 RANDVALUE=`sha256 -qs "${HTTP_PROXY}${http_proxy}" | 635 tr -d 'a-f' | 636 cut -c 1-9` 637 else 638 RANDVALUE=`jot -r 1 0 999999999` 639 fi 640} 641 642# Pick a mirror. Returns 1 if we have run out of mirrors to try. 643fetch_pick_server () { 644# Generate a list of not-yet-tried mirrors 645 sort serverlist_tried | 646 comm -23 serverlist_full - > serverlist 647 648# Have we run out of mirrors? 649 if [ `wc -l < serverlist` -eq 0 ]; then 650 echo "No mirrors remaining, giving up." 651 return 1 652 fi 653 654# Find the highest priority level (lowest numeric value). 655 SRV_PRIORITY=`cut -f 1 -d ' ' serverlist | sort -n | head -1` 656 657# Add up the weights of the response lines at that priority level. 658 SRV_WSUM=0; 659 while read X; do 660 case "$X" in 661 ${SRV_PRIORITY}\ *) 662 SRV_W=`echo $X | cut -f 2 -d ' '` 663 SRV_WSUM=$(($SRV_WSUM + $SRV_W)) 664 ;; 665 esac 666 done < serverlist 667 668# If all the weights are 0, pretend that they are all 1 instead. 669 if [ ${SRV_WSUM} -eq 0 ]; then 670 SRV_WSUM=`grep -E "^${SRV_PRIORITY} " serverlist | wc -l` 671 SRV_W_ADD=1 672 else 673 SRV_W_ADD=0 674 fi 675 676# Pick a value between 0 and the sum of the weights - 1 677 SRV_RND=`expr ${RANDVALUE} % ${SRV_WSUM}` 678 679# Read through the list of mirrors and set SERVERNAME. Write the line 680# corresponding to the mirror we selected into serverlist_tried so that 681# we won't try it again. 682 while read X; do 683 case "$X" in 684 ${SRV_PRIORITY}\ *) 685 SRV_W=`echo $X | cut -f 2 -d ' '` 686 SRV_W=$(($SRV_W + $SRV_W_ADD)) 687 if [ $SRV_RND -lt $SRV_W ]; then 688 SERVERNAME=`echo $X | cut -f 3 -d ' '` 689 echo "$X" >> serverlist_tried 690 break 691 else 692 SRV_RND=$(($SRV_RND - $SRV_W)) 693 fi 694 ;; 695 esac 696 done < serverlist 697} 698 699# Take a list of ${oldhash}|${newhash} and output a list of needed patches, 700# i.e., those for which we have ${oldhash} and don't have ${newhash}. 701fetch_make_patchlist () { 702 grep -vE "^([0-9a-f]{64})\|\1$" | 703 tr '|' ' ' | 704 while read X Y; do 705 if [ -f "files/${Y}.gz" ] || 706 [ ! -f "files/${X}.gz" ]; then 707 continue 708 fi 709 echo "${X}|${Y}" 710 done | uniq 711} 712 713# Print user-friendly progress statistics 714fetch_progress () { 715 LNC=0 716 while read x; do 717 LNC=$(($LNC + 1)) 718 if [ $(($LNC % 10)) = 0 ]; then 719 echo -n $LNC 720 elif [ $(($LNC % 2)) = 0 ]; then 721 echo -n . 722 fi 723 done 724 echo -n " " 725} 726 727# Initialize the working directory 728workdir_init () { 729 mkdir -p files 730 touch tINDEX.present 731} 732 733# Check that we have a public key with an appropriate hash, or 734# fetch the key if it doesn't exist. Returns 1 if the key has 735# not yet been fetched. 736fetch_key () { 737 if [ -r pub.ssl ] && [ `${SHA256} -q pub.ssl` = ${KEYPRINT} ]; then 738 return 0 739 fi 740 741 echo -n "Fetching public key from ${SERVERNAME}... " 742 rm -f pub.ssl 743 fetch ${QUIETFLAG} http://${SERVERNAME}/${FETCHDIR}/pub.ssl \ 744 2>${QUIETREDIR} || true 745 if ! [ -r pub.ssl ]; then 746 echo "failed." 747 return 1 748 fi 749 if ! [ `${SHA256} -q pub.ssl` = ${KEYPRINT} ]; then 750 echo "key has incorrect hash." 751 rm -f pub.ssl 752 return 1 753 fi 754 echo "done." 755} 756 757# Fetch metadata signature, aka "tag". 758fetch_tag () { 759 echo ${NDEBUG} "Fetching metadata signature from ${SERVERNAME}... " 760 rm -f latest.ssl 761 fetch ${QUIETFLAG} http://${SERVERNAME}/${FETCHDIR}/latest.ssl \ 762 2>${QUIETREDIR} || true 763 if ! [ -r latest.ssl ]; then 764 echo "failed." 765 return 1 766 fi 767 768 openssl rsautl -pubin -inkey pub.ssl -verify \ 769 < latest.ssl > tag.new 2>${QUIETREDIR} || true 770 rm latest.ssl 771 772 if ! [ `wc -l < tag.new` = 1 ] || 773 ! grep -qE \ 774 "^freebsd-update\|${ARCH}\|${RELNUM}\|[0-9]+\|[0-9a-f]{64}\|[0-9]{10}" \ 775 tag.new; then 776 echo "invalid signature." 777 return 1 778 fi 779 780 echo "done." 781 782 RELPATCHNUM=`cut -f 4 -d '|' < tag.new` 783 TINDEXHASH=`cut -f 5 -d '|' < tag.new` 784 EOLTIME=`cut -f 6 -d '|' < tag.new` 785} 786 787# Sanity-check the patch number in a tag, to make sure that we're not 788# going to "update" backwards and to prevent replay attacks. 789fetch_tagsanity () { 790 # Check that we're not going to move from -pX to -pY with Y < X. 791 RELPX=`uname -r | sed -E 's,.*-,,'` 792 if echo ${RELPX} | grep -qE '^p[0-9]+$'; then 793 RELPX=`echo ${RELPX} | cut -c 2-` 794 else 795 RELPX=0 796 fi 797 if [ "${RELPATCHNUM}" -lt "${RELPX}" ]; then 798 echo 799 echo -n "Files on mirror (${RELNUM}-p${RELPATCHNUM})" 800 echo " appear older than what" 801 echo "we are currently running (`uname -r`)!" 802 echo "Cowardly refusing to proceed any further." 803 return 1 804 fi 805 806 # If "tag" exists and corresponds to ${RELNUM}, make sure that 807 # it contains a patch number <= RELPATCHNUM, in order to protect 808 # against rollback (replay) attacks. 809 if [ -f tag ] && 810 grep -qE \ 811 "^freebsd-update\|${ARCH}\|${RELNUM}\|[0-9]+\|[0-9a-f]{64}\|[0-9]{10}" \ 812 tag; then 813 LASTRELPATCHNUM=`cut -f 4 -d '|' < tag` 814 815 if [ "${RELPATCHNUM}" -lt "${LASTRELPATCHNUM}" ]; then 816 echo 817 echo -n "Files on mirror (${RELNUM}-p${RELPATCHNUM})" 818 echo " are older than the" 819 echo -n "most recently seen updates" 820 echo " (${RELNUM}-p${LASTRELPATCHNUM})." 821 echo "Cowardly refusing to proceed any further." 822 return 1 823 fi 824 fi 825} 826 827# Fetch metadata index file 828fetch_metadata_index () { 829 echo ${NDEBUG} "Fetching metadata index... " 830 rm -f ${TINDEXHASH} 831 fetch ${QUIETFLAG} http://${SERVERNAME}/${FETCHDIR}/t/${TINDEXHASH} 832 2>${QUIETREDIR} 833 if ! [ -f ${TINDEXHASH} ]; then 834 echo "failed." 835 return 1 836 fi 837 if [ `${SHA256} -q ${TINDEXHASH}` != ${TINDEXHASH} ]; then 838 echo "update metadata index corrupt." 839 return 1 840 fi 841 echo "done." 842} 843 844# Print an error message about signed metadata being bogus. 845fetch_metadata_bogus () { 846 echo 847 echo "The update metadata$1 is correctly signed, but" 848 echo "failed an integrity check." 849 echo "Cowardly refusing to proceed any further." 850 return 1 851} 852 853# Construct tINDEX.new by merging the lines named in $1 from ${TINDEXHASH} 854# with the lines not named in $@ from tINDEX.present (if that file exists). 855fetch_metadata_index_merge () { 856 for METAFILE in $@; do 857 if [ `grep -E "^${METAFILE}\|" ${TINDEXHASH} | wc -l` \ 858 -ne 1 ]; then 859 fetch_metadata_bogus " index" 860 return 1 861 fi 862 863 grep -E "${METAFILE}\|" ${TINDEXHASH} 864 done | 865 sort > tINDEX.wanted 866 867 if [ -f tINDEX.present ]; then 868 join -t '|' -v 2 tINDEX.wanted tINDEX.present | 869 sort -m - tINDEX.wanted > tINDEX.new 870 rm tINDEX.wanted 871 else 872 mv tINDEX.wanted tINDEX.new 873 fi 874} 875 876# Sanity check all the lines of tINDEX.new. Even if more metadata lines 877# are added by future versions of the server, this won't cause problems, 878# since the only lines which appear in tINDEX.new are the ones which we 879# specifically grepped out of ${TINDEXHASH}. 880fetch_metadata_index_sanity () { 881 if grep -qvE '^[0-9A-Z.-]+\|[0-9a-f]{64}$' tINDEX.new; then 882 fetch_metadata_bogus " index" 883 return 1 884 fi 885} 886 887# Sanity check the metadata file $1. 888fetch_metadata_sanity () { 889 # Some aliases to save space later: ${P} is a character which can 890 # appear in a path; ${M} is the four numeric metadata fields; and 891 # ${H} is a sha256 hash. 892 P="[-+./:=_[[:alnum:]]" 893 M="[0-9]+\|[0-9]+\|[0-9]+\|[0-9]+" 894 H="[0-9a-f]{64}" 895 896 # Check that the first four fields make sense. 897 if gunzip -c < files/$1.gz | 898 grep -qvE "^[a-z]+\|[0-9a-z]+\|${P}+\|[fdL-]\|"; then 899 fetch_metadata_bogus "" 900 return 1 901 fi 902 903 # Remove the first three fields. 904 gunzip -c < files/$1.gz | 905 cut -f 4- -d '|' > sanitycheck.tmp 906 907 # Sanity check entries with type 'f' 908 if grep -E '^f' sanitycheck.tmp | 909 grep -qvE "^f\|${M}\|${H}\|${P}*\$"; then 910 fetch_metadata_bogus "" 911 return 1 912 fi 913 914 # Sanity check entries with type 'd' 915 if grep -E '^d' sanitycheck.tmp | 916 grep -qvE "^d\|${M}\|\|\$"; then 917 fetch_metadata_bogus "" 918 return 1 919 fi 920 921 # Sanity check entries with type 'L' 922 if grep -E '^L' sanitycheck.tmp | 923 grep -qvE "^L\|${M}\|${P}*\|\$"; then 924 fetch_metadata_bogus "" 925 return 1 926 fi 927 928 # Sanity check entries with type '-' 929 if grep -E '^-' sanitycheck.tmp | 930 grep -qvE "^-\|\|\|\|\|\|"; then 931 fetch_metadata_bogus "" 932 return 1 933 fi 934 935 # Clean up 936 rm sanitycheck.tmp 937} 938 939# Fetch the metadata index and metadata files listed in $@, 940# taking advantage of metadata patches where possible. 941fetch_metadata () { 942 fetch_metadata_index || return 1 943 fetch_metadata_index_merge $@ || return 1 944 fetch_metadata_index_sanity || return 1 945 946 # Generate a list of wanted metadata patches 947 join -t '|' -o 1.2,2.2 tINDEX.present tINDEX.new | 948 fetch_make_patchlist > patchlist 949 950 if [ -s patchlist ]; then 951 # Attempt to fetch metadata patches 952 echo -n "Fetching `wc -l < patchlist | tr -d ' '` " 953 echo ${NDEBUG} "metadata patches.${DDSTATS}" 954 tr '|' '-' < patchlist | 955 lam -s "${FETCHDIR}/tp/" - -s ".gz" | 956 xargs ${XARGST} ${PHTTPGET} ${SERVERNAME} \ 957 2>${STATSREDIR} | fetch_progress 958 echo "done." 959 960 # Attempt to apply metadata patches 961 echo -n "Applying metadata patches... " 962 tr '|' ' ' < patchlist | 963 while read X Y; do 964 if [ ! -f "${X}-${Y}.gz" ]; then continue; fi 965 gunzip -c < ${X}-${Y}.gz > diff 966 gunzip -c < files/${X}.gz > diff-OLD 967 968 # Figure out which lines are being added and removed 969 grep -E '^-' diff | 970 cut -c 2- | 971 while read PREFIX; do 972 look "${PREFIX}" diff-OLD 973 done | 974 sort > diff-rm 975 grep -E '^\+' diff | 976 cut -c 2- > diff-add 977 978 # Generate the new file 979 comm -23 diff-OLD diff-rm | 980 sort - diff-add > diff-NEW 981 982 if [ `${SHA256} -q diff-NEW` = ${Y} ]; then 983 mv diff-NEW files/${Y} 984 gzip -n files/${Y} 985 else 986 mv diff-NEW ${Y}.bad 987 fi 988 rm -f ${X}-${Y}.gz diff 989 rm -f diff-OLD diff-NEW diff-add diff-rm 990 done 2>${QUIETREDIR} 991 echo "done." 992 fi 993 994 # Update metadata without patches 995 cut -f 2 -d '|' < tINDEX.new | 996 while read Y; do 997 if [ ! -f "files/${Y}.gz" ]; then 998 echo ${Y}; 999 fi 1000 done | 1001 sort -u > filelist 1002 1003 if [ -s filelist ]; then 1004 echo -n "Fetching `wc -l < filelist | tr -d ' '` " 1005 echo ${NDEBUG} "metadata files... " 1006 lam -s "${FETCHDIR}/m/" - -s ".gz" < filelist | 1007 xargs ${XARGST} ${PHTTPGET} ${SERVERNAME} \ 1008 2>${QUIETREDIR} 1009 1010 while read Y; do 1011 if ! [ -f ${Y}.gz ]; then 1012 echo "failed." 1013 return 1 1014 fi 1015 if [ `gunzip -c < ${Y}.gz | 1016 ${SHA256} -q` = ${Y} ]; then 1017 mv ${Y}.gz files/${Y}.gz 1018 else 1019 echo "metadata is corrupt." 1020 return 1 1021 fi 1022 done < filelist 1023 echo "done." 1024 fi 1025 1026# Sanity-check the metadata files. 1027 cut -f 2 -d '|' tINDEX.new > filelist 1028 while read X; do 1029 fetch_metadata_sanity ${X} || return 1 1030 done < filelist 1031 1032# Remove files which are no longer needed 1033 cut -f 2 -d '|' tINDEX.present | 1034 sort > oldfiles 1035 cut -f 2 -d '|' tINDEX.new | 1036 sort | 1037 comm -13 - oldfiles | 1038 lam -s "files/" - -s ".gz" | 1039 xargs rm -f 1040 rm patchlist filelist oldfiles 1041 rm ${TINDEXHASH} 1042 1043# We're done! 1044 mv tINDEX.new tINDEX.present 1045 mv tag.new tag 1046 1047 return 0 1048} 1049 1050# Generate a filtered version of the metadata file $1 from the downloaded 1051# file, by fishing out the lines corresponding to components we're trying 1052# to keep updated, and then removing lines corresponding to paths we want 1053# to ignore. 1054fetch_filter_metadata () { 1055 METAHASH=`look "$1|" tINDEX.present | cut -f 2 -d '|'` 1056 gunzip -c < files/${METAHASH}.gz > $1.all 1057 1058 # Fish out the lines belonging to components we care about. 1059 # Canonicalize directory names by removing any trailing / in 1060 # order to avoid listing directories multiple times if they 1061 # belong to multiple components. Turning "/" into "" doesn't 1062 # matter, since we add a leading "/" when we use paths later. 1063 for C in ${COMPONENTS}; do 1064 look "`echo ${C} | tr '/' '|'`|" $1.all 1065 done | 1066 cut -f 3- -d '|' | 1067 sed -e 's,/|d|,|d|,' | 1068 sort -u > $1.tmp 1069 1070 # Figure out which lines to ignore and remove them. 1071 for X in ${IGNOREPATHS}; do 1072 grep -E "^${X}" $1.tmp 1073 done | 1074 sort -u | 1075 comm -13 - $1.tmp > $1 1076 1077 # Remove temporary files. 1078 rm $1.all $1.tmp 1079} 1080 1081# Filter the metadata file $1 by adding lines with "/boot/`uname -i`" 1082# replaced by ${KERNELDIR} (which is `sysctl -n kern.bootfile` minus the 1083# trailing "/kernel"); and if "/boot/`uname -i`" does not exist, remove 1084# the original lines which start with that. 1085# Put another way: Deal with the fact that the FOO kernel is sometimes 1086# installed in /boot/FOO/ and is sometimes installed elsewhere. 1087fetch_filter_kernel_names () { 1088 KERNCONF=`uname -i` 1089 1090 grep ^/boot/${KERNCONF} $1 | 1091 sed -e "s,/boot/${KERNCONF},${KERNELDIR},g" | 1092 sort - $1 > $1.tmp 1093 mv $1.tmp $1 1094 1095 if ! [ -d /boot/${KERNCONF} ]; then 1096 grep -v ^/boot/${KERNCONF} $1 > $1.tmp 1097 mv $1.tmp $1 1098 fi 1099} 1100 1101# For all paths appearing in $1 or $3, inspect the system 1102# and generate $2 describing what is currently installed. 1103fetch_inspect_system () { 1104 # No errors yet... 1105 rm -f .err 1106 1107 # Tell the user why his disk is suddenly making lots of noise 1108 echo -n "Inspecting system... " 1109 1110 # Generate list of files to inspect 1111 cat $1 $3 | 1112 cut -f 1 -d '|' | 1113 sort -u > filelist 1114 1115 # Examine each file and output lines of the form 1116 # /path/to/file|type|device-inum|user|group|perm|flags|value 1117 # sorted by device and inode number. 1118 while read F; do 1119 # If the symlink/file/directory does not exist, record this. 1120 if ! [ -e ${BASEDIR}/${F} ]; then 1121 echo "${F}|-||||||" 1122 continue 1123 fi 1124 if ! [ -r ${BASEDIR}/${F} ]; then 1125 echo "Cannot read file: ${BASEDIR}/${F}" \ 1126 >/dev/stderr 1127 touch .err 1128 return 1 1129 fi 1130 1131 # Otherwise, output an index line. 1132 if [ -L ${BASEDIR}/${F} ]; then 1133 echo -n "${F}|L|" 1134 stat -n -f '%d-%i|%u|%g|%Mp%Lp|%Of|' ${BASEDIR}/${F}; 1135 readlink ${BASEDIR}/${F}; 1136 elif [ -f ${BASEDIR}/${F} ]; then 1137 echo -n "${F}|f|" 1138 stat -n -f '%d-%i|%u|%g|%Mp%Lp|%Of|' ${BASEDIR}/${F}; 1139 sha256 -q ${BASEDIR}/${F}; 1140 elif [ -d ${BASEDIR}/${F} ]; then 1141 echo -n "${F}|d|" 1142 stat -f '%d-%i|%u|%g|%Mp%Lp|%Of|' ${BASEDIR}/${F}; 1143 else 1144 echo "Unknown file type: ${BASEDIR}/${F}" \ 1145 >/dev/stderr 1146 touch .err 1147 return 1 1148 fi 1149 done < filelist | 1150 sort -k 3,3 -t '|' > $2.tmp 1151 rm filelist 1152 1153 # Check if an error occured during system inspection 1154 if [ -f .err ]; then 1155 return 1 1156 fi 1157 1158 # Convert to the form 1159 # /path/to/file|type|user|group|perm|flags|value|hlink 1160 # by resolving identical device and inode numbers into hard links. 1161 cut -f 1,3 -d '|' $2.tmp | 1162 sort -k 1,1 -t '|' | 1163 sort -s -u -k 2,2 -t '|' | 1164 join -1 2 -2 3 -t '|' - $2.tmp | 1165 awk -F \| -v OFS=\| \ 1166 '{ 1167 if (($2 == $3) || ($4 == "-")) 1168 print $3,$4,$5,$6,$7,$8,$9,"" 1169 else 1170 print $3,$4,$5,$6,$7,$8,$9,$2 1171 }' | 1172 sort > $2 1173 rm $2.tmp 1174 1175 # We're finished looking around 1176 echo "done." 1177} 1178 1179# For any paths matching ${UPDATEIFUNMODIFIED}, remove lines from $[123] 1180# which correspond to lines in $2 with hashes not matching $1 or $3. For 1181# entries in $2 marked "not present" (aka. type -), remove lines from $[123] 1182# unless there is a corresponding entry in $1. 1183fetch_filter_unmodified_notpresent () { 1184 # Figure out which lines of $1 and $3 correspond to bits which 1185 # should only be updated if they haven't changed, and fish out 1186 # the (path, type, value) tuples. 1187 # NOTE: We don't consider a file to be "modified" if it matches 1188 # the hash from $3. 1189 for X in ${UPDATEIFUNMODIFIED}; do 1190 grep -E "^${X}" $1 1191 grep -E "^${X}" $3 1192 done | 1193 cut -f 1,2,7 -d '|' | 1194 sort > $1-values 1195 1196 # Do the same for $2. 1197 for X in ${UPDATEIFUNMODIFIED}; do 1198 grep -E "^${X}" $2 1199 done | 1200 cut -f 1,2,7 -d '|' | 1201 sort > $2-values 1202 1203 # Any entry in $2-values which is not in $1-values corresponds to 1204 # a path which we need to remove from $1, $2, and $3. 1205 comm -13 $1-values $2-values > mlines 1206 rm $1-values $2-values 1207 1208 # Any lines in $2 which are not in $1 AND are "not present" lines 1209 # also belong in mlines. 1210 comm -13 $1 $2 | 1211 cut -f 1,2,7 -d '|' | 1212 fgrep '|-|' >> mlines 1213 1214 # Remove lines from $1, $2, and $3 1215 for X in $1 $2 $3; do 1216 sort -t '|' -k 1,1 ${X} > ${X}.tmp 1217 cut -f 1 -d '|' < mlines | 1218 sort | 1219 join -v 2 -t '|' - ${X}.tmp | 1220 sort > ${X} 1221 rm ${X}.tmp 1222 done 1223 1224 # Store a list of the modified files, for future reference 1225 fgrep -v '|-|' mlines | 1226 cut -f 1 -d '|' > modifiedfiles 1227 rm mlines 1228} 1229 1230# For each entry in $1 of type -, remove any corresponding 1231# entry from $2 if ${ALLOWADD} != "yes". Remove all entries 1232# of type - from $1. 1233fetch_filter_allowadd () { 1234 cut -f 1,2 -d '|' < $1 | 1235 fgrep '|-' | 1236 cut -f 1 -d '|' > filesnotpresent 1237 1238 if [ ${ALLOWADD} != "yes" ]; then 1239 sort < $2 | 1240 join -v 1 -t '|' - filesnotpresent | 1241 sort > $2.tmp 1242 mv $2.tmp $2 1243 fi 1244 1245 sort < $1 | 1246 join -v 1 -t '|' - filesnotpresent | 1247 sort > $1.tmp 1248 mv $1.tmp $1 1249 rm filesnotpresent 1250} 1251 1252# If ${ALLOWDELETE} != "yes", then remove any entries from $1 1253# which don't correspond to entries in $2. 1254fetch_filter_allowdelete () { 1255 # Produce a lists ${PATH}|${TYPE} 1256 for X in $1 $2; do 1257 cut -f 1-2 -d '|' < ${X} | 1258 sort -u > ${X}.nodes 1259 done 1260 1261 # Figure out which lines need to be removed from $1. 1262 if [ ${ALLOWDELETE} != "yes" ]; then 1263 comm -23 $1.nodes $2.nodes > $1.badnodes 1264 else 1265 : > $1.badnodes 1266 fi 1267 1268 # Remove the relevant lines from $1 1269 while read X; do 1270 look "${X}|" $1 1271 done < $1.badnodes | 1272 comm -13 - $1 > $1.tmp 1273 mv $1.tmp $1 1274 1275 rm $1.badnodes $1.nodes $2.nodes 1276} 1277 1278# If ${KEEPMODIFIEDMETADATA} == "yes", then for each entry in $2 1279# with metadata not matching any entry in $1, replace the corresponding 1280# line of $3 with one having the same metadata as the entry in $2. 1281fetch_filter_modified_metadata () { 1282 # Fish out the metadata from $1 and $2 1283 for X in $1 $2; do 1284 cut -f 1-6 -d '|' < ${X} > ${X}.metadata 1285 done 1286 1287 # Find the metadata we need to keep 1288 if [ ${KEEPMODIFIEDMETADATA} = "yes" ]; then 1289 comm -13 $1.metadata $2.metadata > keepmeta 1290 else 1291 : > keepmeta 1292 fi 1293 1294 # Extract the lines which we need to remove from $3, and 1295 # construct the lines which we need to add to $3. 1296 : > $3.remove 1297 : > $3.add 1298 while read LINE; do 1299 NODE=`echo "${LINE}" | cut -f 1-2 -d '|'` 1300 look "${NODE}|" $3 >> $3.remove 1301 look "${NODE}|" $3 | 1302 cut -f 7- -d '|' | 1303 lam -s "${LINE}|" - >> $3.add 1304 done < keepmeta 1305 1306 # Remove the specified lines and add the new lines. 1307 sort $3.remove | 1308 comm -13 - $3 | 1309 sort -u - $3.add > $3.tmp 1310 mv $3.tmp $3 1311 1312 rm keepmeta $1.metadata $2.metadata $3.add $3.remove 1313} 1314 1315# Remove lines from $1 and $2 which are identical; 1316# no need to update a file if it isn't changing. 1317fetch_filter_uptodate () { 1318 comm -23 $1 $2 > $1.tmp 1319 comm -13 $1 $2 > $2.tmp 1320 1321 mv $1.tmp $1 1322 mv $2.tmp $2 1323} 1324 1325# Prepare to fetch files: Generate a list of the files we need, 1326# copy the unmodified files we have into /files/, and generate 1327# a list of patches to download. 1328fetch_files_prepare () { 1329 # Tell the user why his disk is suddenly making lots of noise 1330 echo -n "Preparing to download files... " 1331 1332 # Reduce indices to ${PATH}|${HASH} pairs 1333 for X in $1 $2 $3; do 1334 cut -f 1,2,7 -d '|' < ${X} | 1335 fgrep '|f|' | 1336 cut -f 1,3 -d '|' | 1337 sort > ${X}.hashes 1338 done 1339 1340 # List of files wanted 1341 cut -f 2 -d '|' < $3.hashes | 1342 sort -u > files.wanted 1343 1344 # Generate a list of unmodified files 1345 comm -12 $1.hashes $2.hashes | 1346 sort -k 1,1 -t '|' > unmodified.files 1347 1348 # Copy all files into /files/. We only need the unmodified files 1349 # for use in patching; but we'll want all of them if the user asks 1350 # to rollback the updates later. 1351 cut -f 1 -d '|' < $2.hashes | 1352 while read F; do 1353 cp "${BASEDIR}/${F}" tmpfile 1354 gzip -c < tmpfile > files/`sha256 -q tmpfile`.gz 1355 rm tmpfile 1356 done 1357 1358 # Produce a list of patches to download 1359 sort -k 1,1 -t '|' $3.hashes | 1360 join -t '|' -o 2.2,1.2 - unmodified.files | 1361 fetch_make_patchlist > patchlist 1362 1363 # Garbage collect 1364 rm unmodified.files $1.hashes $2.hashes $3.hashes 1365 1366 # We don't need the list of possible old files any more. 1367 rm $1 1368 1369 # We're finished making noise 1370 echo "done." 1371} 1372 1373# Fetch files. 1374fetch_files () { 1375 # Attempt to fetch patches 1376 if [ -s patchlist ]; then 1377 echo -n "Fetching `wc -l < patchlist | tr -d ' '` " 1378 echo ${NDEBUG} "patches.${DDSTATS}" 1379 tr '|' '-' < patchlist | 1380 lam -s "${FETCHDIR}/bp/" - | 1381 xargs ${XARGST} ${PHTTPGET} ${SERVERNAME} \ 1382 2>${STATSREDIR} | fetch_progress 1383 echo "done." 1384 1385 # Attempt to apply patches 1386 echo -n "Applying patches... " 1387 tr '|' ' ' < patchlist | 1388 while read X Y; do 1389 if [ ! -f "${X}-${Y}" ]; then continue; fi 1390 gunzip -c < files/${X}.gz > OLD 1391 1392 bspatch OLD NEW ${X}-${Y} 1393 1394 if [ `${SHA256} -q NEW` = ${Y} ]; then 1395 mv NEW files/${Y} 1396 gzip -n files/${Y} 1397 fi 1398 rm -f diff OLD NEW ${X}-${Y} 1399 done 2>${QUIETREDIR} 1400 echo "done." 1401 fi 1402 1403 # Download files which couldn't be generate via patching 1404 while read Y; do 1405 if [ ! -f "files/${Y}.gz" ]; then 1406 echo ${Y}; 1407 fi 1408 done < files.wanted > filelist 1409 1410 if [ -s filelist ]; then 1411 echo -n "Fetching `wc -l < filelist | tr -d ' '` " 1412 echo ${NDEBUG} "files... " 1413 lam -s "${FETCHDIR}/f/" - -s ".gz" < filelist | 1414 xargs ${XARGST} ${PHTTPGET} ${SERVERNAME} \ 1415 2>${QUIETREDIR} 1416 1417 while read Y; do 1418 if ! [ -f ${Y}.gz ]; then 1419 echo "failed." 1420 return 1 1421 fi 1422 if [ `gunzip -c < ${Y}.gz | 1423 ${SHA256} -q` = ${Y} ]; then 1424 mv ${Y}.gz files/${Y}.gz 1425 else 1426 echo "${Y} has incorrect hash." 1427 return 1 1428 fi 1429 done < filelist 1430 echo "done." 1431 fi 1432 1433 # Clean up 1434 rm files.wanted filelist patchlist 1435} 1436 1437# Create and populate install manifest directory; and report what updates 1438# are available. 1439fetch_create_manifest () { 1440 # If we have an existing install manifest, nuke it. 1441 if [ -L "${BDHASH}-install" ]; then 1442 rm -r ${BDHASH}-install/ 1443 rm ${BDHASH}-install 1444 fi 1445 1446 # Report to the user if any updates were avoided due to local changes 1447 if [ -s modifiedfiles ]; then 1448 echo 1449 echo -n "The following files are affected by updates, " 1450 echo "but no changes have" 1451 echo -n "been downloaded because the files have been " 1452 echo "modified locally:" 1453 cat modifiedfiles 1454 fi 1455 rm modifiedfiles 1456 1457 # If no files will be updated, tell the user and exit 1458 if ! [ -s INDEX-PRESENT ] && 1459 ! [ -s INDEX-NEW ]; then 1460 rm INDEX-PRESENT INDEX-NEW 1461 echo 1462 echo -n "No updates needed to update system to " 1463 echo "${RELNUM}-p${RELPATCHNUM}." 1464 return 1465 fi 1466 1467 # Divide files into (a) removed files, (b) added files, and 1468 # (c) updated files. 1469 cut -f 1 -d '|' < INDEX-PRESENT | 1470 sort > INDEX-PRESENT.flist 1471 cut -f 1 -d '|' < INDEX-NEW | 1472 sort > INDEX-NEW.flist 1473 comm -23 INDEX-PRESENT.flist INDEX-NEW.flist > files.removed 1474 comm -13 INDEX-PRESENT.flist INDEX-NEW.flist > files.added 1475 comm -12 INDEX-PRESENT.flist INDEX-NEW.flist > files.updated 1476 rm INDEX-PRESENT.flist INDEX-NEW.flist 1477 1478 # Report removed files, if any 1479 if [ -s files.removed ]; then 1480 echo 1481 echo -n "The following files will be removed " 1482 echo "as part of updating to ${RELNUM}-p${RELPATCHNUM}:" 1483 cat files.removed 1484 fi 1485 rm files.removed 1486 1487 # Report added files, if any 1488 if [ -s files.added ]; then 1489 echo 1490 echo -n "The following files will be added " 1491 echo "as part of updating to ${RELNUM}-p${RELPATCHNUM}:" 1492 cat files.added 1493 fi 1494 rm files.added 1495 1496 # Report updated files, if any 1497 if [ -s files.updated ]; then 1498 echo 1499 echo -n "The following files will be updated " 1500 echo "as part of updating to ${RELNUM}-p${RELPATCHNUM}:" 1501 1502 cat files.updated 1503 fi 1504 rm files.updated 1505 1506 # Create a directory for the install manifest. 1507 MDIR=`mktemp -d install.XXXXXX` || return 1 1508 1509 # Populate it 1510 mv INDEX-PRESENT ${MDIR}/INDEX-OLD 1511 mv INDEX-NEW ${MDIR}/INDEX-NEW 1512 1513 # Link it into place 1514 ln -s ${MDIR} ${BDHASH}-install 1515} 1516 1517# Warn about any upcoming EoL 1518fetch_warn_eol () { 1519 # What's the current time? 1520 NOWTIME=`date "+%s"` 1521 1522 # When did we last warn about the EoL date? 1523 if [ -f lasteolwarn ]; then 1524 LASTWARN=`cat lasteolwarn` 1525 else 1526 LASTWARN=`expr ${NOWTIME} - 63072000` 1527 fi 1528 1529 # If the EoL time is past, warn. 1530 if [ ${EOLTIME} -lt ${NOWTIME} ]; then 1531 echo 1532 cat <<-EOF 1533 WARNING: `uname -sr` HAS PASSED ITS END-OF-LIFE DATE. 1534 Any security issues discovered after `date -r ${EOLTIME}` 1535 will not have been corrected. 1536 EOF 1537 return 1 1538 fi 1539 1540 # Figure out how long it has been since we last warned about the 1541 # upcoming EoL, and how much longer we have left. 1542 SINCEWARN=`expr ${NOWTIME} - ${LASTWARN}` 1543 TIMELEFT=`expr ${EOLTIME} - ${NOWTIME}` 1544 1545 # Don't warn if the EoL is more than 6 months away 1546 if [ ${TIMELEFT} -gt 15768000 ]; then 1547 return 0 1548 fi 1549 1550 # Don't warn if the time remaining is more than 3 times the time 1551 # since the last warning. 1552 if [ ${TIMELEFT} -gt `expr ${SINCEWARN} \* 3` ]; then 1553 return 0 1554 fi 1555 1556 # Figure out what time units to use. 1557 if [ ${TIMELEFT} -lt 604800 ]; then 1558 UNIT="day" 1559 SIZE=86400 1560 elif [ ${TIMELEFT} -lt 2678400 ]; then 1561 UNIT="week" 1562 SIZE=604800 1563 else 1564 UNIT="month" 1565 SIZE=2678400 1566 fi 1567 1568 # Compute the right number of units 1569 NUM=`expr ${TIMELEFT} / ${SIZE}` 1570 if [ ${NUM} != 1 ]; then 1571 UNIT="${UNIT}s" 1572 fi 1573 1574 # Print the warning 1575 echo 1576 cat <<-EOF 1577 WARNING: `uname -sr` is approaching its End-of-Life date. 1578 It is strongly recommended that you upgrade to a newer 1579 release within the next ${NUM} ${UNIT}. 1580 EOF 1581 1582 # Update the stored time of last warning 1583 echo ${NOWTIME} > lasteolwarn 1584} 1585 1586# Do the actual work involved in "fetch" / "cron". 1587fetch_run () { 1588 workdir_init || return 1 1589 1590 # Prepare the mirror list. 1591 fetch_pick_server_init && fetch_pick_server 1592 1593 # Try to fetch the public key until we run out of servers. 1594 while ! fetch_key; do 1595 fetch_pick_server || return 1 1596 done 1597 1598 # Try to fetch the metadata index signature ("tag") until we run 1599 # out of available servers; and sanity check the downloaded tag. 1600 while ! fetch_tag; do 1601 fetch_pick_server || return 1 1602 done 1603 fetch_tagsanity || return 1 1604 1605 # Fetch the latest INDEX-NEW and INDEX-OLD files. 1606 fetch_metadata INDEX-NEW INDEX-OLD || return 1 1607 1608 # Generate filtered INDEX-NEW and INDEX-OLD files containing only 1609 # the lines which (a) belong to components we care about, and (b) 1610 # don't correspond to paths we're explicitly ignoring. 1611 fetch_filter_metadata INDEX-NEW || return 1 1612 fetch_filter_metadata INDEX-OLD || return 1 1613 1614 # Translate /boot/`uname -i` into ${KERNELDIR} 1615 fetch_filter_kernel_names INDEX-NEW 1616 fetch_filter_kernel_names INDEX-OLD 1617 1618 # For all paths appearing in INDEX-OLD or INDEX-NEW, inspect the 1619 # system and generate an INDEX-PRESENT file. 1620 fetch_inspect_system INDEX-OLD INDEX-PRESENT INDEX-NEW || return 1 1621 1622 # Based on ${UPDATEIFUNMODIFIED}, remove lines from INDEX-* which 1623 # correspond to lines in INDEX-PRESENT with hashes not appearing 1624 # in INDEX-OLD or INDEX-NEW. Also remove lines where the entry in 1625 # INDEX-PRESENT has type - and there isn't a corresponding entry in 1626 # INDEX-OLD with type -. 1627 fetch_filter_unmodified_notpresent INDEX-OLD INDEX-PRESENT INDEX-NEW 1628 1629 # For each entry in INDEX-PRESENT of type -, remove any corresponding 1630 # entry from INDEX-NEW if ${ALLOWADD} != "yes". Remove all entries 1631 # of type - from INDEX-PRESENT. 1632 fetch_filter_allowadd INDEX-PRESENT INDEX-NEW 1633 1634 # If ${ALLOWDELETE} != "yes", then remove any entries from 1635 # INDEX-PRESENT which don't correspond to entries in INDEX-NEW. 1636 fetch_filter_allowdelete INDEX-PRESENT INDEX-NEW 1637 1638 # If ${KEEPMODIFIEDMETADATA} == "yes", then for each entry in 1639 # INDEX-PRESENT with metadata not matching any entry in INDEX-OLD, 1640 # replace the corresponding line of INDEX-NEW with one having the 1641 # same metadata as the entry in INDEX-PRESENT. 1642 fetch_filter_modified_metadata INDEX-OLD INDEX-PRESENT INDEX-NEW 1643 1644 # Remove lines from INDEX-PRESENT and INDEX-NEW which are identical; 1645 # no need to update a file if it isn't changing. 1646 fetch_filter_uptodate INDEX-PRESENT INDEX-NEW 1647 1648 # Prepare to fetch files: Generate a list of the files we need, 1649 # copy the unmodified files we have into /files/, and generate 1650 # a list of patches to download. 1651 fetch_files_prepare INDEX-OLD INDEX-PRESENT INDEX-NEW 1652 1653 # Fetch files. 1654 fetch_files || return 1 1655 1656 # Create and populate install manifest directory; and report what 1657 # updates are available. 1658 fetch_create_manifest || return 1 1659 1660 # Warn about any upcoming EoL 1661 fetch_warn_eol || return 1 1662} 1663 1664# Make sure that all the file hashes mentioned in $@ have corresponding 1665# gzipped files stored in /files/. 1666install_verify () { 1667 # Generate a list of hashes 1668 cat $@ | 1669 cut -f 2,7 -d '|' | 1670 grep -E '^f' | 1671 cut -f 2 -d '|' | 1672 sort -u > filelist 1673 1674 # Make sure all the hashes exist 1675 while read HASH; do 1676 if ! [ -f files/${HASH}.gz ]; then 1677 echo -n "Update files missing -- " 1678 echo "this should never happen." 1679 echo "Re-run '$0 fetch'." 1680 return 1 1681 fi 1682 done < filelist 1683 1684 # Clean up 1685 rm filelist 1686} 1687 1688# Remove the system immutable flag from files 1689install_unschg () { 1690 # Generate file list 1691 cat $@ | 1692 cut -f 1 -d '|' > filelist 1693 1694 # Remove flags 1695 while read F; do 1696 if ! [ -e ${F} ]; then 1697 continue 1698 fi 1699 1700 chflags noschg ${F} || return 1 1701 done < filelist 1702 1703 # Clean up 1704 rm filelist 1705} 1706 1707# Install new files 1708install_from_index () { 1709 # First pass: Do everything apart from setting file flags. We 1710 # can't set flags yet, because schg inhibits hard linking. 1711 sort -k 1,1 -t '|' $1 | 1712 tr '|' ' ' | 1713 while read FPATH TYPE OWNER GROUP PERM FLAGS HASH LINK; do 1714 case ${TYPE} in 1715 d) 1716 # Create a directory 1717 install -d -o ${OWNER} -g ${GROUP} \ 1718 -m ${PERM} ${BASEDIR}/${FPATH} 1719 ;; 1720 f) 1721 if [ -z "${LINK}" ]; then 1722 # Create a file, without setting flags. 1723 gunzip < files/${HASH}.gz > ${HASH} 1724 install -S -o ${OWNER} -g ${GROUP} \ 1725 -m ${PERM} ${HASH} ${BASEDIR}/${FPATH} 1726 rm ${HASH} 1727 else 1728 # Create a hard link. 1729 ln -f ${LINK} ${BASEDIR}/${FPATH} 1730 fi 1731 ;; 1732 L) 1733 # Create a symlink 1734 ln -sfh ${HASH} ${BASEDIR}/${FPATH} 1735 ;; 1736 esac 1737 done 1738 1739 # Perform a second pass, adding file flags. 1740 tr '|' ' ' < $1 | 1741 while read FPATH TYPE OWNER GROUP PERM FLAGS HASH LINK; do 1742 if [ ${TYPE} = "f" ] && 1743 ! [ ${FLAGS} = "0" ]; then 1744 chflags ${FLAGS} ${BASEDIR}/${FPATH} 1745 fi 1746 done 1747} 1748 1749# Remove files which we want to delete 1750install_delete () { 1751 # Generate list of new files 1752 cut -f 1 -d '|' < $2 | 1753 sort > newfiles 1754 1755 # Generate subindex of old files we want to nuke 1756 sort -k 1,1 -t '|' $1 | 1757 join -t '|' -v 1 - newfiles | 1758 sort -r -k 1,1 -t '|' | 1759 cut -f 1,2 -d '|' | 1760 tr '|' ' ' > killfiles 1761 1762 # Remove the offending bits 1763 while read FPATH TYPE; do 1764 case ${TYPE} in 1765 d) 1766 rmdir ${BASEDIR}/${FPATH} 1767 ;; 1768 f) 1769 rm ${BASEDIR}/${FPATH} 1770 ;; 1771 L) 1772 rm ${BASEDIR}/${FPATH} 1773 ;; 1774 esac 1775 done < killfiles 1776 1777 # Clean up 1778 rm newfiles killfiles 1779} 1780 1781# Update linker.hints if anything in /boot/ was touched 1782install_kldxref () { 1783 if cat $@ | 1784 grep -qE '^/boot/'; then 1785 kldxref -R /boot/ 1786 fi 1787} 1788 1789# Rearrange bits to allow the installed updates to be rolled back 1790install_setup_rollback () { 1791 if [ -L ${BDHASH}-rollback ]; then 1792 mv ${BDHASH}-rollback ${BDHASH}-install/rollback 1793 fi 1794 1795 mv ${BDHASH}-install ${BDHASH}-rollback 1796} 1797 1798# Actually install updates 1799install_run () { 1800 echo -n "Installing updates..." 1801 1802 # Make sure we have all the files we should have 1803 install_verify ${BDHASH}-install/INDEX-OLD \ 1804 ${BDHASH}-install/INDEX-NEW || return 1 1805 1806 # Remove system immutable flag from files 1807 install_unschg ${BDHASH}-install/INDEX-OLD \ 1808 ${BDHASH}-install/INDEX-NEW || return 1 1809 1810 # Install new files 1811 install_from_index \ 1812 ${BDHASH}-install/INDEX-NEW || return 1 1813 1814 # Remove files which we want to delete 1815 install_delete ${BDHASH}-install/INDEX-OLD \ 1816 ${BDHASH}-install/INDEX-NEW || return 1 1817 1818 # Update linker.hints if anything in /boot/ was touched 1819 install_kldxref ${BDHASH}-install/INDEX-OLD \ 1820 ${BDHASH}-install/INDEX-NEW 1821 1822 # Rearrange bits to allow the installed updates to be rolled back 1823 install_setup_rollback 1824 1825 echo " done." 1826} 1827 1828# Rearrange bits to allow the previous set of updates to be rolled back next. 1829rollback_setup_rollback () { 1830 if [ -L ${BDHASH}-rollback/rollback ]; then 1831 mv ${BDHASH}-rollback/rollback rollback-tmp 1832 rm -r ${BDHASH}-rollback/ 1833 rm ${BDHASH}-rollback 1834 mv rollback-tmp ${BDHASH}-rollback 1835 else 1836 rm -r ${BDHASH}-rollback/ 1837 rm ${BDHASH}-rollback 1838 fi 1839} 1840 1841# Actually rollback updates 1842rollback_run () { 1843 echo -n "Uninstalling updates..." 1844 1845 # If there are updates waiting to be installed, remove them; we 1846 # want the user to re-run 'fetch' after rolling back updates. 1847 if [ -L ${BDHASH}-install ]; then 1848 rm -r ${BDHASH}-install/ 1849 rm ${BDHASH}-install 1850 fi 1851 1852 # Make sure we have all the files we should have 1853 install_verify ${BDHASH}-rollback/INDEX-NEW \ 1854 ${BDHASH}-rollback/INDEX-OLD || return 1 1855 1856 # Remove system immutable flag from files 1857 install_unschg ${BDHASH}-rollback/INDEX-NEW \ 1858 ${BDHASH}-rollback/INDEX-OLD || return 1 1859 1860 # Install new files 1861 install_from_index \ 1862 ${BDHASH}-rollback/INDEX-OLD || return 1 1863 1864 # Remove files which we want to delete 1865 install_delete ${BDHASH}-rollback/INDEX-NEW \ 1866 ${BDHASH}-rollback/INDEX-OLD || return 1 1867 1868 # Update linker.hints if anything in /boot/ was touched 1869 install_kldxref ${BDHASH}-rollback/INDEX-NEW \ 1870 ${BDHASH}-rollback/INDEX-OLD 1871 1872 # Remove the rollback directory and the symlink pointing to it; and 1873 # rearrange bits to allow the previous set of updates to be rolled 1874 # back next. 1875 rollback_setup_rollback 1876 1877 echo " done." 1878} 1879 1880#### Main functions -- call parameter-handling and core functions 1881 1882# Using the command line, configuration file, and defaults, 1883# set all the parameters which are needed later. 1884get_params () { 1885 init_params 1886 parse_cmdline $@ 1887 parse_conffile 1888 default_params 1889} 1890 1891# Fetch command. Make sure that we're being called 1892# interactively, then run fetch_check_params and fetch_run 1893cmd_fetch () { 1894 if [ ! -t 0 ]; then 1895 echo -n "`basename $0` fetch should not " 1896 echo "be run non-interactively." 1897 echo "Run `basename $0` cron instead." 1898 exit 1 1899 fi 1900 fetch_check_params 1901 fetch_run || exit 1 1902} 1903 1904# Cron command. Make sure the parameters are sensible; wait 1905# rand(3600) seconds; then fetch updates. While fetching updates, 1906# send output to a temporary file; only print that file if the 1907# fetching failed. 1908cmd_cron () { 1909 fetch_check_params 1910 sleep `jot -r 1 0 3600` 1911 1912 TMPFILE=`mktemp /tmp/freebsd-update.XXXXXX` || exit 1 1913 if ! fetch_run >> ${TMPFILE} || 1914 ! grep -q "No updates needed" ${TMPFILE} || 1915 [ ${VERBOSELEVEL} = "debug" ]; then 1916 mail -s "`hostname` security updates" ${MAILTO} < ${TMPFILE} 1917 fi 1918 1919 rm ${TMPFILE} 1920} 1921 1922# Install downloaded updates. 1923cmd_install () { 1924 install_check_params 1925 install_run || exit 1 1926} 1927 1928# Rollback most recently installed updates. 1929cmd_rollback () { 1930 rollback_check_params 1931 rollback_run || exit 1 1932} 1933 1934#### Entry point 1935 1936# Make sure we find utilities from the base system 1937export PATH=/sbin:/bin:/usr/sbin:/usr/bin:${PATH} 1938 1939# Set LC_ALL in order to avoid problems with character ranges like [A-Z]. 1940export LC_ALL=C 1941 1942get_params $@ 1943for COMMAND in ${COMMANDS}; do 1944 cmd_${COMMAND} 1945done 1946