1161748Scperciva#!/bin/sh
2161748Scperciva
3161748Scperciva#-
4173441Scperciva# Copyright 2004-2007 Colin Percival
5161748Scperciva# All rights reserved
6161748Scperciva#
7161748Scperciva# Redistribution and use in source and binary forms, with or without
8161748Scperciva# modification, are permitted providing that the following conditions 
9161748Scperciva# are met:
10161748Scperciva# 1. Redistributions of source code must retain the above copyright
11161748Scperciva#    notice, this list of conditions and the following disclaimer.
12161748Scperciva# 2. Redistributions in binary form must reproduce the above copyright
13161748Scperciva#    notice, this list of conditions and the following disclaimer in the
14161748Scperciva#    documentation and/or other materials provided with the distribution.
15161748Scperciva#
16161748Scperciva# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17161748Scperciva# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18161748Scperciva# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19161748Scperciva# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
20161748Scperciva# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21161748Scperciva# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22161748Scperciva# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23161748Scperciva# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24161748Scperciva# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25161748Scperciva# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26161748Scperciva# POSSIBILITY OF SUCH DAMAGE.
27161748Scperciva
28161748Scperciva# $FreeBSD$
29161748Scperciva
30161748Scperciva#### Usage function -- called from command-line handling code.
31161748Scperciva
32161748Scperciva# Usage instructions.  Options not listed:
33161748Scperciva# --debug	-- don't filter output from utilities
34161748Scperciva# --no-stats	-- don't show progress statistics while fetching files
35161748Scpercivausage () {
36161748Scperciva	cat <<EOF
37161748Scpercivausage: `basename $0` [options] command ... [path]
38161748Scperciva
39161748ScpercivaOptions:
40161748Scperciva  -b basedir   -- Operate on a system mounted at basedir
41161748Scperciva                  (default: /)
42161748Scperciva  -d workdir   -- Store working files in workdir
43161748Scperciva                  (default: /var/db/freebsd-update/)
44161748Scperciva  -f conffile  -- Read configuration options from conffile
45161748Scperciva                  (default: /etc/freebsd-update.conf)
46282874Sdelphij  -F           -- Force a fetch operation to proceed
47161748Scperciva  -k KEY       -- Trust an RSA key with SHA256 hash of KEY
48173564Scperciva  -r release   -- Target for upgrade (e.g., 6.2-RELEASE)
49161748Scperciva  -s server    -- Server from which to fetch updates
50161748Scperciva                  (default: update.FreeBSD.org)
51161748Scperciva  -t address   -- Mail output of cron command, if any, to address
52161748Scperciva                  (default: root)
53282874Sdelphij  --not-running-from-cron
54282874Sdelphij               -- Run without a tty, for use by automated tools
55161748ScpercivaCommands:
56161748Scperciva  fetch        -- Fetch updates from server
57161748Scperciva  cron         -- Sleep rand(3600) seconds, fetch updates, and send an
58161748Scperciva                  email if updates were found
59173564Scperciva  upgrade      -- Fetch upgrades to FreeBSD version specified via -r option
60173564Scperciva  install      -- Install downloaded updates or upgrades
61161748Scperciva  rollback     -- Uninstall most recently installed updates
62181142Scperciva  IDS          -- Compare the system against an index of "known good" files.
63161748ScpercivaEOF
64161748Scperciva	exit 0
65161748Scperciva}
66161748Scperciva
67161748Scperciva#### Configuration processing functions
68161748Scperciva
69161748Scperciva#-
70161748Scperciva# Configuration options are set in the following order of priority:
71161748Scperciva# 1. Command line options
72161748Scperciva# 2. Configuration file options
73161748Scperciva# 3. Default options
74161748Scperciva# In addition, certain options (e.g., IgnorePaths) can be specified multiple
75161748Scperciva# times and (as long as these are all in the same place, e.g., inside the
76161748Scperciva# configuration file) they will accumulate.  Finally, because the path to the
77161748Scperciva# configuration file can be specified at the command line, the entire command
78161748Scperciva# line must be processed before we start reading the configuration file.
79161748Scperciva#
80161748Scperciva# Sound like a mess?  It is.  Here's how we handle this:
81161748Scperciva# 1. Initialize CONFFILE and all the options to "".
82161748Scperciva# 2. Process the command line.  Throw an error if a non-accumulating option
83161748Scperciva#    is specified twice.
84161748Scperciva# 3. If CONFFILE is "", set CONFFILE to /etc/freebsd-update.conf .
85161748Scperciva# 4. For all the configuration options X, set X_saved to X.
86161748Scperciva# 5. Initialize all the options to "".
87161748Scperciva# 6. Read CONFFILE line by line, parsing options.
88161748Scperciva# 7. For each configuration option X, set X to X_saved iff X_saved is not "".
89161748Scperciva# 8. Repeat steps 4-7, except setting options to their default values at (6).
90161748Scperciva
91161748ScpercivaCONFIGOPTIONS="KEYPRINT WORKDIR SERVERNAME MAILTO ALLOWADD ALLOWDELETE
92161748Scperciva    KEEPMODIFIEDMETADATA COMPONENTS IGNOREPATHS UPDATEIFUNMODIFIED
93181142Scperciva    BASEDIR VERBOSELEVEL TARGETRELEASE STRICTCOMPONENTS MERGECHANGES
94196392Ssimon    IDSIGNOREPATHS BACKUPKERNEL BACKUPKERNELDIR BACKUPKERNELSYMBOLFILES"
95161748Scperciva
96161748Scperciva# Set all the configuration options to "".
97161748Scpercivanullconfig () {
98161748Scperciva	for X in ${CONFIGOPTIONS}; do
99161748Scperciva		eval ${X}=""
100161748Scperciva	done
101161748Scperciva}
102161748Scperciva
103161748Scperciva# For each configuration option X, set X_saved to X.
104161748Scpercivasaveconfig () {
105161748Scperciva	for X in ${CONFIGOPTIONS}; do
106161748Scperciva		eval ${X}_saved=\$${X}
107161748Scperciva	done
108161748Scperciva}
109161748Scperciva
110161748Scperciva# For each configuration option X, set X to X_saved if X_saved is not "".
111161748Scpercivamergeconfig () {
112161748Scperciva	for X in ${CONFIGOPTIONS}; do
113161748Scperciva		eval _=\$${X}_saved
114161748Scperciva		if ! [ -z "${_}" ]; then
115161748Scperciva			eval ${X}=\$${X}_saved
116161748Scperciva		fi
117161748Scperciva	done
118161748Scperciva}
119161748Scperciva
120161748Scperciva# Set the trusted keyprint.
121161748Scpercivaconfig_KeyPrint () {
122161748Scperciva	if [ -z ${KEYPRINT} ]; then
123161748Scperciva		KEYPRINT=$1
124161748Scperciva	else
125161748Scperciva		return 1
126161748Scperciva	fi
127161748Scperciva}
128161748Scperciva
129161748Scperciva# Set the working directory.
130161748Scpercivaconfig_WorkDir () {
131161748Scperciva	if [ -z ${WORKDIR} ]; then
132161748Scperciva		WORKDIR=$1
133161748Scperciva	else
134161748Scperciva		return 1
135161748Scperciva	fi
136161748Scperciva}
137161748Scperciva
138161748Scperciva# Set the name of the server (pool) from which to fetch updates
139161748Scpercivaconfig_ServerName () {
140161748Scperciva	if [ -z ${SERVERNAME} ]; then
141161748Scperciva		SERVERNAME=$1
142161748Scperciva	else
143161748Scperciva		return 1
144161748Scperciva	fi
145161748Scperciva}
146161748Scperciva
147161748Scperciva# Set the address to which 'cron' output will be mailed.
148161748Scpercivaconfig_MailTo () {
149161748Scperciva	if [ -z ${MAILTO} ]; then
150161748Scperciva		MAILTO=$1
151161748Scperciva	else
152161748Scperciva		return 1
153161748Scperciva	fi
154161748Scperciva}
155161748Scperciva
156161748Scperciva# Set whether FreeBSD Update is allowed to add files (or directories, or
157161748Scperciva# symlinks) which did not previously exist.
158161748Scpercivaconfig_AllowAdd () {
159161748Scperciva	if [ -z ${ALLOWADD} ]; then
160161748Scperciva		case $1 in
161161748Scperciva		[Yy][Ee][Ss])
162161748Scperciva			ALLOWADD=yes
163161748Scperciva			;;
164161748Scperciva		[Nn][Oo])
165161748Scperciva			ALLOWADD=no
166161748Scperciva			;;
167161748Scperciva		*)
168161748Scperciva			return 1
169161748Scperciva			;;
170161748Scperciva		esac
171161748Scperciva	else
172161748Scperciva		return 1
173161748Scperciva	fi
174161748Scperciva}
175161748Scperciva
176161748Scperciva# Set whether FreeBSD Update is allowed to remove files/directories/symlinks.
177161748Scpercivaconfig_AllowDelete () {
178161748Scperciva	if [ -z ${ALLOWDELETE} ]; then
179161748Scperciva		case $1 in
180161748Scperciva		[Yy][Ee][Ss])
181161748Scperciva			ALLOWDELETE=yes
182161748Scperciva			;;
183161748Scperciva		[Nn][Oo])
184161748Scperciva			ALLOWDELETE=no
185161748Scperciva			;;
186161748Scperciva		*)
187161748Scperciva			return 1
188161748Scperciva			;;
189161748Scperciva		esac
190161748Scperciva	else
191161748Scperciva		return 1
192161748Scperciva	fi
193161748Scperciva}
194161748Scperciva
195161748Scperciva# Set whether FreeBSD Update should keep existing inode ownership,
196161748Scperciva# permissions, and flags, in the event that they have been modified locally
197161748Scperciva# after the release.
198161748Scpercivaconfig_KeepModifiedMetadata () {
199161748Scperciva	if [ -z ${KEEPMODIFIEDMETADATA} ]; then
200161748Scperciva		case $1 in
201161748Scperciva		[Yy][Ee][Ss])
202161748Scperciva			KEEPMODIFIEDMETADATA=yes
203161748Scperciva			;;
204161748Scperciva		[Nn][Oo])
205161748Scperciva			KEEPMODIFIEDMETADATA=no
206161748Scperciva			;;
207161748Scperciva		*)
208161748Scperciva			return 1
209161748Scperciva			;;
210161748Scperciva		esac
211161748Scperciva	else
212161748Scperciva		return 1
213161748Scperciva	fi
214161748Scperciva}
215161748Scperciva
216161748Scperciva# Add to the list of components which should be kept updated.
217161748Scpercivaconfig_Components () {
218161748Scperciva	for C in $@; do
219161748Scperciva		COMPONENTS="${COMPONENTS} ${C}"
220161748Scperciva	done
221161748Scperciva}
222161748Scperciva
223161748Scperciva# Add to the list of paths under which updates will be ignored.
224161748Scpercivaconfig_IgnorePaths () {
225161748Scperciva	for C in $@; do
226161748Scperciva		IGNOREPATHS="${IGNOREPATHS} ${C}"
227161748Scperciva	done
228161748Scperciva}
229161748Scperciva
230181142Scperciva# Add to the list of paths which IDS should ignore.
231181142Scpercivaconfig_IDSIgnorePaths () {
232181142Scperciva	for C in $@; do
233181142Scperciva		IDSIGNOREPATHS="${IDSIGNOREPATHS} ${C}"
234181142Scperciva	done
235181142Scperciva}
236181142Scperciva
237161748Scperciva# Add to the list of paths within which updates will be performed only if the
238161748Scperciva# file on disk has not been modified locally.
239161748Scpercivaconfig_UpdateIfUnmodified () {
240161748Scperciva	for C in $@; do
241161748Scperciva		UPDATEIFUNMODIFIED="${UPDATEIFUNMODIFIED} ${C}"
242161748Scperciva	done
243161748Scperciva}
244161748Scperciva
245173564Scperciva# Add to the list of paths within which updates to text files will be merged
246173564Scperciva# instead of overwritten.
247173564Scpercivaconfig_MergeChanges () {
248173564Scperciva	for C in $@; do
249173564Scperciva		MERGECHANGES="${MERGECHANGES} ${C}"
250173564Scperciva	done
251173564Scperciva}
252173564Scperciva
253161748Scperciva# Work on a FreeBSD installation mounted under $1
254161748Scpercivaconfig_BaseDir () {
255161748Scperciva	if [ -z ${BASEDIR} ]; then
256161748Scperciva		BASEDIR=$1
257161748Scperciva	else
258161748Scperciva		return 1
259161748Scperciva	fi
260161748Scperciva}
261161748Scperciva
262173564Scperciva# When fetching upgrades, should we assume the user wants exactly the
263173564Scperciva# components listed in COMPONENTS, rather than trying to guess based on
264173564Scperciva# what's currently installed?
265173564Scpercivaconfig_StrictComponents () {
266173564Scperciva	if [ -z ${STRICTCOMPONENTS} ]; then
267173564Scperciva		case $1 in
268173564Scperciva		[Yy][Ee][Ss])
269173564Scperciva			STRICTCOMPONENTS=yes
270173564Scperciva			;;
271173564Scperciva		[Nn][Oo])
272173564Scperciva			STRICTCOMPONENTS=no
273173564Scperciva			;;
274173564Scperciva		*)
275173564Scperciva			return 1
276173564Scperciva			;;
277173564Scperciva		esac
278173564Scperciva	else
279173564Scperciva		return 1
280173564Scperciva	fi
281173564Scperciva}
282173564Scperciva
283173564Scperciva# Upgrade to FreeBSD $1
284173564Scpercivaconfig_TargetRelease () {
285173564Scperciva	if [ -z ${TARGETRELEASE} ]; then
286173564Scperciva		TARGETRELEASE=$1
287173564Scperciva	else
288173564Scperciva		return 1
289173564Scperciva	fi
290197618Scperciva	if echo ${TARGETRELEASE} | grep -qE '^[0-9.]+$'; then
291197618Scperciva		TARGETRELEASE="${TARGETRELEASE}-RELEASE"
292197618Scperciva	fi
293173564Scperciva}
294173564Scperciva
295161748Scperciva# Define what happens to output of utilities
296161748Scpercivaconfig_VerboseLevel () {
297161748Scperciva	if [ -z ${VERBOSELEVEL} ]; then
298161748Scperciva		case $1 in
299161748Scperciva		[Dd][Ee][Bb][Uu][Gg])
300161748Scperciva			VERBOSELEVEL=debug
301161748Scperciva			;;
302161748Scperciva		[Nn][Oo][Ss][Tt][Aa][Tt][Ss])
303161748Scperciva			VERBOSELEVEL=nostats
304161748Scperciva			;;
305161748Scperciva		[Ss][Tt][Aa][Tt][Ss])
306161748Scperciva			VERBOSELEVEL=stats
307161748Scperciva			;;
308161748Scperciva		*)
309161748Scperciva			return 1
310161748Scperciva			;;
311161748Scperciva		esac
312161748Scperciva	else
313161748Scperciva		return 1
314161748Scperciva	fi
315161748Scperciva}
316161748Scperciva
317196392Ssimonconfig_BackupKernel () {
318196392Ssimon	if [ -z ${BACKUPKERNEL} ]; then
319196392Ssimon		case $1 in
320196392Ssimon		[Yy][Ee][Ss])
321196392Ssimon			BACKUPKERNEL=yes
322196392Ssimon			;;
323196392Ssimon		[Nn][Oo])
324196392Ssimon			BACKUPKERNEL=no
325196392Ssimon			;;
326196392Ssimon		*)
327196392Ssimon			return 1
328196392Ssimon			;;
329196392Ssimon		esac
330196392Ssimon	else
331196392Ssimon		return 1
332196392Ssimon	fi
333196392Ssimon}
334196392Ssimon
335196392Ssimonconfig_BackupKernelDir () {
336196392Ssimon	if [ -z ${BACKUPKERNELDIR} ]; then
337196392Ssimon		if [ -z "$1" ]; then
338196392Ssimon			echo "BackupKernelDir set to empty dir"
339196392Ssimon			return 1
340196392Ssimon		fi
341196392Ssimon
342196392Ssimon		# We check for some paths which would be extremely odd
343196392Ssimon		# to use, but which could cause a lot of problems if
344196392Ssimon		# used.
345196392Ssimon		case $1 in
346196392Ssimon		/|/bin|/boot|/etc|/lib|/libexec|/sbin|/usr|/var)
347196392Ssimon			echo "BackupKernelDir set to invalid path $1"
348196392Ssimon			return 1
349196392Ssimon			;;
350196392Ssimon		/*)
351196392Ssimon			BACKUPKERNELDIR=$1
352196392Ssimon			;;
353196392Ssimon		*)
354196392Ssimon			echo "BackupKernelDir ($1) is not an absolute path"
355196392Ssimon			return 1
356196392Ssimon			;;
357196392Ssimon		esac
358196392Ssimon	else
359196392Ssimon		return 1
360196392Ssimon	fi
361196392Ssimon}
362196392Ssimon
363196392Ssimonconfig_BackupKernelSymbolFiles () {
364196392Ssimon	if [ -z ${BACKUPKERNELSYMBOLFILES} ]; then
365196392Ssimon		case $1 in
366196392Ssimon		[Yy][Ee][Ss])
367196392Ssimon			BACKUPKERNELSYMBOLFILES=yes
368196392Ssimon			;;
369196392Ssimon		[Nn][Oo])
370196392Ssimon			BACKUPKERNELSYMBOLFILES=no
371196392Ssimon			;;
372196392Ssimon		*)
373196392Ssimon			return 1
374196392Ssimon			;;
375196392Ssimon		esac
376196392Ssimon	else
377196392Ssimon		return 1
378196392Ssimon	fi
379196392Ssimon}
380196392Ssimon
381161748Scperciva# Handle one line of configuration
382161748Scpercivaconfigline () {
383161748Scperciva	if [ $# -eq 0 ]; then
384161748Scperciva		return
385161748Scperciva	fi
386161748Scperciva
387161748Scperciva	OPT=$1
388161748Scperciva	shift
389161748Scperciva	config_${OPT} $@
390161748Scperciva}
391161748Scperciva
392161748Scperciva#### Parameter handling functions.
393161748Scperciva
394161748Scperciva# Initialize parameters to null, just in case they're
395161748Scperciva# set in the environment.
396161748Scpercivainit_params () {
397161748Scperciva	# Configration settings
398161748Scperciva	nullconfig
399161748Scperciva
400161748Scperciva	# No configuration file set yet
401161748Scperciva	CONFFILE=""
402161748Scperciva
403161748Scperciva	# No commands specified yet
404161748Scperciva	COMMANDS=""
405282874Sdelphij
406282874Sdelphij	# Force fetch to proceed
407282874Sdelphij	FORCEFETCH=0
408282874Sdelphij
409282874Sdelphij	# Run without a TTY
410282874Sdelphij	NOTTYOK=0
411161748Scperciva}
412161748Scperciva
413161748Scperciva# Parse the command line
414161748Scpercivaparse_cmdline () {
415161748Scperciva	while [ $# -gt 0 ]; do
416161748Scperciva		case "$1" in
417161748Scperciva		# Location of configuration file
418161748Scperciva		-f)
419161748Scperciva			if [ $# -eq 1 ]; then usage; fi
420161748Scperciva			if [ ! -z "${CONFFILE}" ]; then usage; fi
421161748Scperciva			shift; CONFFILE="$1"
422161748Scperciva			;;
423282874Sdelphij		-F)
424282874Sdelphij			FORCEFETCH=1
425282874Sdelphij			;;
426282874Sdelphij		--not-running-from-cron)
427282874Sdelphij			NOTTYOK=1
428282874Sdelphij			;;
429161748Scperciva
430161748Scperciva		# Configuration file equivalents
431161748Scperciva		-b)
432161748Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
433161748Scperciva			config_BaseDir $1 || usage
434161748Scperciva			;;
435161748Scperciva		-d)
436161748Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
437161748Scperciva			config_WorkDir $1 || usage
438161748Scperciva			;;
439161748Scperciva		-k)
440161748Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
441161748Scperciva			config_KeyPrint $1 || usage
442161748Scperciva			;;
443161748Scperciva		-s)
444161748Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
445161748Scperciva			config_ServerName $1 || usage
446161748Scperciva			;;
447173564Scperciva		-r)
448173564Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
449173564Scperciva			config_TargetRelease $1 || usage
450173564Scperciva			;;
451161748Scperciva		-t)
452161748Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
453161748Scperciva			config_MailTo $1 || usage
454161748Scperciva			;;
455161748Scperciva		-v)
456161748Scperciva			if [ $# -eq 1 ]; then usage; fi; shift
457161748Scperciva			config_VerboseLevel $1 || usage
458161748Scperciva			;;
459161748Scperciva
460161748Scperciva		# Aliases for "-v debug" and "-v nostats"
461161748Scperciva		--debug)
462161748Scperciva			config_VerboseLevel debug || usage
463161748Scperciva			;;
464161748Scperciva		--no-stats)
465161748Scperciva			config_VerboseLevel nostats || usage
466161748Scperciva			;;
467161748Scperciva
468161748Scperciva		# Commands
469181142Scperciva		cron | fetch | upgrade | install | rollback | IDS)
470161748Scperciva			COMMANDS="${COMMANDS} $1"
471161748Scperciva			;;
472161748Scperciva
473161748Scperciva		# Anything else is an error
474161748Scperciva		*)
475161748Scperciva			usage
476161748Scperciva			;;
477161748Scperciva		esac
478161748Scperciva		shift
479161748Scperciva	done
480161748Scperciva
481161748Scperciva	# Make sure we have at least one command
482161748Scperciva	if [ -z "${COMMANDS}" ]; then
483161748Scperciva		usage
484161748Scperciva	fi
485161748Scperciva}
486161748Scperciva
487161748Scperciva# Parse the configuration file
488161748Scpercivaparse_conffile () {
489161748Scperciva	# If a configuration file was specified on the command line, check
490161748Scperciva	# that it exists and is readable.
491161748Scperciva	if [ ! -z "${CONFFILE}" ] && [ ! -r "${CONFFILE}" ]; then
492161748Scperciva		echo -n "File does not exist "
493161748Scperciva		echo -n "or is not readable: "
494161748Scperciva		echo ${CONFFILE}
495161748Scperciva		exit 1
496161748Scperciva	fi
497161748Scperciva
498161748Scperciva	# If a configuration file was not specified on the command line,
499161748Scperciva	# use the default configuration file path.  If that default does
500161748Scperciva	# not exist, give up looking for any configuration.
501161748Scperciva	if [ -z "${CONFFILE}" ]; then
502161748Scperciva		CONFFILE="/etc/freebsd-update.conf"
503161748Scperciva		if [ ! -r "${CONFFILE}" ]; then
504161748Scperciva			return
505161748Scperciva		fi
506161748Scperciva	fi
507161748Scperciva
508161748Scperciva	# Save the configuration options specified on the command line, and
509161748Scperciva	# clear all the options in preparation for reading the config file.
510161748Scperciva	saveconfig
511161748Scperciva	nullconfig
512161748Scperciva
513161748Scperciva	# Read the configuration file.  Anything after the first '#' is
514161748Scperciva	# ignored, and any blank lines are ignored.
515161748Scperciva	L=0
516161748Scperciva	while read LINE; do
517161748Scperciva		L=$(($L + 1))
518161748Scperciva		LINEX=`echo "${LINE}" | cut -f 1 -d '#'`
519161748Scperciva		if ! configline ${LINEX}; then
520161748Scperciva			echo "Error processing configuration file, line $L:"
521161748Scperciva			echo "==> ${LINE}"
522161748Scperciva			exit 1
523161748Scperciva		fi
524161748Scperciva	done < ${CONFFILE}
525161748Scperciva
526161748Scperciva	# Merge the settings read from the configuration file with those
527161748Scperciva	# provided at the command line.
528161748Scperciva	mergeconfig
529161748Scperciva}
530161748Scperciva
531161748Scperciva# Provide some default parameters
532161748Scpercivadefault_params () {
533161748Scperciva	# Save any parameters already configured, and clear the slate
534161748Scperciva	saveconfig
535161748Scperciva	nullconfig
536161748Scperciva
537161748Scperciva	# Default configurations
538161748Scperciva	config_WorkDir /var/db/freebsd-update
539161748Scperciva	config_MailTo root
540161748Scperciva	config_AllowAdd yes
541161748Scperciva	config_AllowDelete yes
542161748Scperciva	config_KeepModifiedMetadata yes
543161748Scperciva	config_BaseDir /
544161748Scperciva	config_VerboseLevel stats
545173564Scperciva	config_StrictComponents no
546196392Ssimon	config_BackupKernel yes
547196392Ssimon	config_BackupKernelDir /boot/kernel.old
548196392Ssimon	config_BackupKernelSymbolFiles no
549161748Scperciva
550161748Scperciva	# Merge these defaults into the earlier-configured settings
551161748Scperciva	mergeconfig
552161748Scperciva}
553161748Scperciva
554161748Scperciva# Set utility output filtering options, based on ${VERBOSELEVEL}
555161748Scpercivafetch_setup_verboselevel () {
556161748Scperciva	case ${VERBOSELEVEL} in
557161748Scperciva	debug)
558161748Scperciva		QUIETREDIR="/dev/stderr"
559161748Scperciva		QUIETFLAG=" "
560161748Scperciva		STATSREDIR="/dev/stderr"
561161748Scperciva		DDSTATS=".."
562161748Scperciva		XARGST="-t"
563161748Scperciva		NDEBUG=" "
564161748Scperciva		;;
565161748Scperciva	nostats)
566161748Scperciva		QUIETREDIR=""
567161748Scperciva		QUIETFLAG=""
568161748Scperciva		STATSREDIR="/dev/null"
569161748Scperciva		DDSTATS=".."
570161748Scperciva		XARGST=""
571161748Scperciva		NDEBUG=""
572161748Scperciva		;;
573161748Scperciva	stats)
574161748Scperciva		QUIETREDIR="/dev/null"
575161748Scperciva		QUIETFLAG="-q"
576161748Scperciva		STATSREDIR="/dev/stdout"
577161748Scperciva		DDSTATS=""
578161748Scperciva		XARGST=""
579161748Scperciva		NDEBUG="-n"
580161748Scperciva		;;
581161748Scperciva	esac
582161748Scperciva}
583161748Scperciva
584161748Scperciva# Perform sanity checks and set some final parameters
585161748Scperciva# in preparation for fetching files.  Figure out which
586161748Scperciva# set of updates should be downloaded: If the user is
587161748Scperciva# running *-p[0-9]+, strip off the last part; if the
588161748Scperciva# user is running -SECURITY, call it -RELEASE.  Chdir
589161748Scperciva# into the working directory.
590212434Scpercivafetchupgrade_check_params () {
591161748Scperciva	export HTTP_USER_AGENT="freebsd-update (${COMMAND}, `uname -r`)"
592161748Scperciva
593161748Scperciva	_SERVERNAME_z=\
594161748Scperciva"SERVERNAME must be given via command line or configuration file."
595161748Scperciva	_KEYPRINT_z="Key must be given via -k option or configuration file."
596161748Scperciva	_KEYPRINT_bad="Invalid key fingerprint: "
597161748Scperciva	_WORKDIR_bad="Directory does not exist or is not writable: "
598161748Scperciva
599161748Scperciva	if [ -z "${SERVERNAME}" ]; then
600161748Scperciva		echo -n "`basename $0`: "
601161748Scperciva		echo "${_SERVERNAME_z}"
602161748Scperciva		exit 1
603161748Scperciva	fi
604161748Scperciva	if [ -z "${KEYPRINT}" ]; then
605161748Scperciva		echo -n "`basename $0`: "
606161748Scperciva		echo "${_KEYPRINT_z}"
607161748Scperciva		exit 1
608161748Scperciva	fi
609161748Scperciva	if ! echo "${KEYPRINT}" | grep -qE "^[0-9a-f]{64}$"; then
610161748Scperciva		echo -n "`basename $0`: "
611161748Scperciva		echo -n "${_KEYPRINT_bad}"
612161748Scperciva		echo ${KEYPRINT}
613161748Scperciva		exit 1
614161748Scperciva	fi
615161748Scperciva	if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then
616161748Scperciva		echo -n "`basename $0`: "
617161748Scperciva		echo -n "${_WORKDIR_bad}"
618161748Scperciva		echo ${WORKDIR}
619161748Scperciva		exit 1
620161748Scperciva	fi
621200054Scperciva	chmod 700 ${WORKDIR}
622161748Scperciva	cd ${WORKDIR} || exit 1
623161748Scperciva
624161748Scperciva	# Generate release number.  The s/SECURITY/RELEASE/ bit exists
625161748Scperciva	# to provide an upgrade path for FreeBSD Update 1.x users, since
626161748Scperciva	# the kernels provided by FreeBSD Update 1.x are always labelled
627161748Scperciva	# as X.Y-SECURITY.
628161748Scperciva	RELNUM=`uname -r |
629161748Scperciva	    sed -E 's,-p[0-9]+,,' |
630161748Scperciva	    sed -E 's,-SECURITY,-RELEASE,'`
631161748Scperciva	ARCH=`uname -m`
632161748Scperciva	FETCHDIR=${RELNUM}/${ARCH}
633173564Scperciva	PATCHDIR=${RELNUM}/${ARCH}/bp
634161748Scperciva
635161748Scperciva	# Figure out what directory contains the running kernel
636161748Scperciva	BOOTFILE=`sysctl -n kern.bootfile`
637161748Scperciva	KERNELDIR=${BOOTFILE%/kernel}
638161748Scperciva	if ! [ -d ${KERNELDIR} ]; then
639161748Scperciva		echo "Cannot identify running kernel"
640161748Scperciva		exit 1
641161748Scperciva	fi
642161748Scperciva
643167189Scperciva	# Figure out what kernel configuration is running.  We start with
644167189Scperciva	# the output of `uname -i`, and then make the following adjustments:
645167189Scperciva	# 1. Replace "SMP-GENERIC" with "SMP".  Why the SMP kernel config
646167189Scperciva	# file says "ident SMP-GENERIC", I don't know...
647167189Scperciva	# 2. If the kernel claims to be GENERIC _and_ ${ARCH} is "amd64"
648167189Scperciva	# _and_ `sysctl kern.version` contains a line which ends "/SMP", then
649167189Scperciva	# we're running an SMP kernel.  This mis-identification is a bug
650167189Scperciva	# which was fixed in 6.2-STABLE.
651167189Scperciva	KERNCONF=`uname -i`
652167189Scperciva	if [ ${KERNCONF} = "SMP-GENERIC" ]; then
653167189Scperciva		KERNCONF=SMP
654167189Scperciva	fi
655167189Scperciva	if [ ${KERNCONF} = "GENERIC" ] && [ ${ARCH} = "amd64" ]; then
656167189Scperciva		if sysctl kern.version | grep -qE '/SMP$'; then
657167189Scperciva			KERNCONF=SMP
658167189Scperciva		fi
659167189Scperciva	fi
660167189Scperciva
661161748Scperciva	# Define some paths
662161748Scperciva	BSPATCH=/usr/bin/bspatch
663161748Scperciva	SHA256=/sbin/sha256
664161748Scperciva	PHTTPGET=/usr/libexec/phttpget
665161748Scperciva
666161748Scperciva	# Set up variables relating to VERBOSELEVEL
667161748Scperciva	fetch_setup_verboselevel
668161748Scperciva
669161748Scperciva	# Construct a unique name from ${BASEDIR}
670161748Scperciva	BDHASH=`echo ${BASEDIR} | sha256 -q`
671161748Scperciva}
672161748Scperciva
673212434Scperciva# Perform sanity checks etc. before fetching updates.
674212434Scpercivafetch_check_params () {
675212434Scperciva	fetchupgrade_check_params
676212434Scperciva
677212434Scperciva	if ! [ -z "${TARGETRELEASE}" ]; then
678212434Scperciva		echo -n "`basename $0`: "
679212434Scperciva		echo -n "-r option is meaningless with 'fetch' command.  "
680212434Scperciva		echo "(Did you mean 'upgrade' instead?)"
681212434Scperciva		exit 1
682212434Scperciva	fi
683282874Sdelphij
684282874Sdelphij	# Check that we have updates ready to install
685282874Sdelphij	if [ -f ${BDHASH}-install/kerneldone -a $FORCEFETCH -eq 0 ]; then
686282874Sdelphij		echo "You have a partially completed upgrade pending"
687282874Sdelphij		echo "Run '$0 install' first."
688282874Sdelphij		echo "Run '$0 fetch -F' to proceed anyway."
689282874Sdelphij		exit 1
690282874Sdelphij	fi
691212434Scperciva}
692212434Scperciva
693173564Scperciva# Perform sanity checks etc. before fetching upgrades.
694173564Scpercivaupgrade_check_params () {
695212434Scperciva	fetchupgrade_check_params
696173564Scperciva
697173564Scperciva	# Unless set otherwise, we're upgrading to the same kernel config.
698173564Scperciva	NKERNCONF=${KERNCONF}
699173564Scperciva
700173564Scperciva	# We need TARGETRELEASE set
701173564Scperciva	_TARGETRELEASE_z="Release target must be specified via -r option."
702173564Scperciva	if [ -z "${TARGETRELEASE}" ]; then
703173564Scperciva		echo -n "`basename $0`: "
704173564Scperciva		echo "${_TARGETRELEASE_z}"
705173564Scperciva		exit 1
706173564Scperciva	fi
707173564Scperciva
708173564Scperciva	# The target release should be != the current release.
709173564Scperciva	if [ "${TARGETRELEASE}" = "${RELNUM}" ]; then
710173564Scperciva		echo -n "`basename $0`: "
711173564Scperciva		echo "Cannot upgrade from ${RELNUM} to itself"
712173564Scperciva		exit 1
713173564Scperciva	fi
714173564Scperciva
715173564Scperciva	# Turning off AllowAdd or AllowDelete is a bad idea for upgrades.
716173564Scperciva	if [ "${ALLOWADD}" = "no" ]; then
717173564Scperciva		echo -n "`basename $0`: "
718173564Scperciva		echo -n "WARNING: \"AllowAdd no\" is a bad idea "
719173564Scperciva		echo "when upgrading between releases."
720173564Scperciva		echo
721173564Scperciva	fi
722173564Scperciva	if [ "${ALLOWDELETE}" = "no" ]; then
723173564Scperciva		echo -n "`basename $0`: "
724173564Scperciva		echo -n "WARNING: \"AllowDelete no\" is a bad idea "
725173564Scperciva		echo "when upgrading between releases."
726173564Scperciva		echo
727173564Scperciva	fi
728173564Scperciva
729173564Scperciva	# Set EDITOR to /usr/bin/vi if it isn't already set
730173564Scperciva	: ${EDITOR:='/usr/bin/vi'}
731173564Scperciva}
732173564Scperciva
733161748Scperciva# Perform sanity checks and set some final parameters in
734161748Scperciva# preparation for installing updates.
735161748Scpercivainstall_check_params () {
736161748Scperciva	# Check that we are root.  All sorts of things won't work otherwise.
737161748Scperciva	if [ `id -u` != 0 ]; then
738161748Scperciva		echo "You must be root to run this."
739161748Scperciva		exit 1
740161748Scperciva	fi
741161748Scperciva
742173441Scperciva	# Check that securelevel <= 0.  Otherwise we can't update schg files.
743173441Scperciva	if [ `sysctl -n kern.securelevel` -gt 0 ]; then
744173441Scperciva		echo "Updates cannot be installed when the system securelevel"
745173441Scperciva		echo "is greater than zero."
746173441Scperciva		exit 1
747173441Scperciva	fi
748173441Scperciva
749161748Scperciva	# Check that we have a working directory
750161748Scperciva	_WORKDIR_bad="Directory does not exist or is not writable: "
751161748Scperciva	if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then
752161748Scperciva		echo -n "`basename $0`: "
753161748Scperciva		echo -n "${_WORKDIR_bad}"
754161748Scperciva		echo ${WORKDIR}
755161748Scperciva		exit 1
756161748Scperciva	fi
757161748Scperciva	cd ${WORKDIR} || exit 1
758161748Scperciva
759161748Scperciva	# Construct a unique name from ${BASEDIR}
760161748Scperciva	BDHASH=`echo ${BASEDIR} | sha256 -q`
761161748Scperciva
762161748Scperciva	# Check that we have updates ready to install
763161748Scperciva	if ! [ -L ${BDHASH}-install ]; then
764161748Scperciva		echo "No updates are available to install."
765161748Scperciva		echo "Run '$0 fetch' first."
766161748Scperciva		exit 1
767161748Scperciva	fi
768161748Scperciva	if ! [ -f ${BDHASH}-install/INDEX-OLD ] ||
769161748Scperciva	    ! [ -f ${BDHASH}-install/INDEX-NEW ]; then
770161748Scperciva		echo "Update manifest is corrupt -- this should never happen."
771161748Scperciva		echo "Re-run '$0 fetch'."
772161748Scperciva		exit 1
773161748Scperciva	fi
774196392Ssimon
775196392Ssimon	# Figure out what directory contains the running kernel
776196392Ssimon	BOOTFILE=`sysctl -n kern.bootfile`
777196392Ssimon	KERNELDIR=${BOOTFILE%/kernel}
778196392Ssimon	if ! [ -d ${KERNELDIR} ]; then
779196392Ssimon		echo "Cannot identify running kernel"
780196392Ssimon		exit 1
781196392Ssimon	fi
782161748Scperciva}
783161748Scperciva
784161748Scperciva# Perform sanity checks and set some final parameters in
785161748Scperciva# preparation for UNinstalling updates.
786161748Scpercivarollback_check_params () {
787161748Scperciva	# Check that we are root.  All sorts of things won't work otherwise.
788161748Scperciva	if [ `id -u` != 0 ]; then
789161748Scperciva		echo "You must be root to run this."
790161748Scperciva		exit 1
791161748Scperciva	fi
792161748Scperciva
793161748Scperciva	# Check that we have a working directory
794161748Scperciva	_WORKDIR_bad="Directory does not exist or is not writable: "
795161748Scperciva	if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then
796161748Scperciva		echo -n "`basename $0`: "
797161748Scperciva		echo -n "${_WORKDIR_bad}"
798161748Scperciva		echo ${WORKDIR}
799161748Scperciva		exit 1
800161748Scperciva	fi
801161748Scperciva	cd ${WORKDIR} || exit 1
802161748Scperciva
803161748Scperciva	# Construct a unique name from ${BASEDIR}
804161748Scperciva	BDHASH=`echo ${BASEDIR} | sha256 -q`
805161748Scperciva
806161748Scperciva	# Check that we have updates ready to rollback
807161748Scperciva	if ! [ -L ${BDHASH}-rollback ]; then
808161748Scperciva		echo "No rollback directory found."
809161748Scperciva		exit 1
810161748Scperciva	fi
811161748Scperciva	if ! [ -f ${BDHASH}-rollback/INDEX-OLD ] ||
812161748Scperciva	    ! [ -f ${BDHASH}-rollback/INDEX-NEW ]; then
813161748Scperciva		echo "Update manifest is corrupt -- this should never happen."
814161748Scperciva		exit 1
815161748Scperciva	fi
816161748Scperciva}
817161748Scperciva
818181142Scperciva# Perform sanity checks and set some final parameters
819181142Scperciva# in preparation for comparing the system against the
820181142Scperciva# published index.  Figure out which index we should
821181142Scperciva# compare against: If the user is running *-p[0-9]+,
822181142Scperciva# strip off the last part; if the user is running
823181142Scperciva# -SECURITY, call it -RELEASE.  Chdir into the working
824181142Scperciva# directory.
825181142ScpercivaIDS_check_params () {
826181142Scperciva	export HTTP_USER_AGENT="freebsd-update (${COMMAND}, `uname -r`)"
827181142Scperciva
828181142Scperciva	_SERVERNAME_z=\
829181142Scperciva"SERVERNAME must be given via command line or configuration file."
830181142Scperciva	_KEYPRINT_z="Key must be given via -k option or configuration file."
831181142Scperciva	_KEYPRINT_bad="Invalid key fingerprint: "
832181142Scperciva	_WORKDIR_bad="Directory does not exist or is not writable: "
833181142Scperciva
834181142Scperciva	if [ -z "${SERVERNAME}" ]; then
835181142Scperciva		echo -n "`basename $0`: "
836181142Scperciva		echo "${_SERVERNAME_z}"
837181142Scperciva		exit 1
838181142Scperciva	fi
839181142Scperciva	if [ -z "${KEYPRINT}" ]; then
840181142Scperciva		echo -n "`basename $0`: "
841181142Scperciva		echo "${_KEYPRINT_z}"
842181142Scperciva		exit 1
843181142Scperciva	fi
844181142Scperciva	if ! echo "${KEYPRINT}" | grep -qE "^[0-9a-f]{64}$"; then
845181142Scperciva		echo -n "`basename $0`: "
846181142Scperciva		echo -n "${_KEYPRINT_bad}"
847181142Scperciva		echo ${KEYPRINT}
848181142Scperciva		exit 1
849181142Scperciva	fi
850181142Scperciva	if ! [ -d "${WORKDIR}" -a -w "${WORKDIR}" ]; then
851181142Scperciva		echo -n "`basename $0`: "
852181142Scperciva		echo -n "${_WORKDIR_bad}"
853181142Scperciva		echo ${WORKDIR}
854181142Scperciva		exit 1
855181142Scperciva	fi
856181142Scperciva	cd ${WORKDIR} || exit 1
857181142Scperciva
858181142Scperciva	# Generate release number.  The s/SECURITY/RELEASE/ bit exists
859181142Scperciva	# to provide an upgrade path for FreeBSD Update 1.x users, since
860181142Scperciva	# the kernels provided by FreeBSD Update 1.x are always labelled
861181142Scperciva	# as X.Y-SECURITY.
862181142Scperciva	RELNUM=`uname -r |
863181142Scperciva	    sed -E 's,-p[0-9]+,,' |
864181142Scperciva	    sed -E 's,-SECURITY,-RELEASE,'`
865181142Scperciva	ARCH=`uname -m`
866181142Scperciva	FETCHDIR=${RELNUM}/${ARCH}
867181142Scperciva	PATCHDIR=${RELNUM}/${ARCH}/bp
868181142Scperciva
869181142Scperciva	# Figure out what directory contains the running kernel
870181142Scperciva	BOOTFILE=`sysctl -n kern.bootfile`
871181142Scperciva	KERNELDIR=${BOOTFILE%/kernel}
872181142Scperciva	if ! [ -d ${KERNELDIR} ]; then
873181142Scperciva		echo "Cannot identify running kernel"
874181142Scperciva		exit 1
875181142Scperciva	fi
876181142Scperciva
877181142Scperciva	# Figure out what kernel configuration is running.  We start with
878181142Scperciva	# the output of `uname -i`, and then make the following adjustments:
879181142Scperciva	# 1. Replace "SMP-GENERIC" with "SMP".  Why the SMP kernel config
880181142Scperciva	# file says "ident SMP-GENERIC", I don't know...
881181142Scperciva	# 2. If the kernel claims to be GENERIC _and_ ${ARCH} is "amd64"
882181142Scperciva	# _and_ `sysctl kern.version` contains a line which ends "/SMP", then
883181142Scperciva	# we're running an SMP kernel.  This mis-identification is a bug
884181142Scperciva	# which was fixed in 6.2-STABLE.
885181142Scperciva	KERNCONF=`uname -i`
886181142Scperciva	if [ ${KERNCONF} = "SMP-GENERIC" ]; then
887181142Scperciva		KERNCONF=SMP
888181142Scperciva	fi
889181142Scperciva	if [ ${KERNCONF} = "GENERIC" ] && [ ${ARCH} = "amd64" ]; then
890181142Scperciva		if sysctl kern.version | grep -qE '/SMP$'; then
891181142Scperciva			KERNCONF=SMP
892181142Scperciva		fi
893181142Scperciva	fi
894181142Scperciva
895181142Scperciva	# Define some paths
896181142Scperciva	SHA256=/sbin/sha256
897181142Scperciva	PHTTPGET=/usr/libexec/phttpget
898181142Scperciva
899181142Scperciva	# Set up variables relating to VERBOSELEVEL
900181142Scperciva	fetch_setup_verboselevel
901181142Scperciva}
902181142Scperciva
903161748Scperciva#### Core functionality -- the actual work gets done here
904161748Scperciva
905161748Scperciva# Use an SRV query to pick a server.  If the SRV query doesn't provide
906161748Scperciva# a useful answer, use the server name specified by the user.
907161748Scperciva# Put another way... look up _http._tcp.${SERVERNAME} and pick a server
908161748Scperciva# from that; or if no servers are returned, use ${SERVERNAME}.
909161748Scperciva# This allows a user to specify "portsnap.freebsd.org" (in which case
910161748Scperciva# portsnap will select one of the mirrors) or "portsnap5.tld.freebsd.org"
911161748Scperciva# (in which case portsnap will use that particular server, since there
912161748Scperciva# won't be an SRV entry for that name).
913161748Scperciva#
914161748Scperciva# We ignore the Port field, since we are always going to use port 80.
915161748Scperciva
916161748Scperciva# Fetch the mirror list, but do not pick a mirror yet.  Returns 1 if
917161748Scperciva# no mirrors are available for any reason.
918161748Scpercivafetch_pick_server_init () {
919161748Scperciva	: > serverlist_tried
920161748Scperciva
921161748Scperciva# Check that host(1) exists (i.e., that the system wasn't built with the
922161748Scperciva# WITHOUT_BIND set) and don't try to find a mirror if it doesn't exist.
923161748Scperciva	if ! which -s host; then
924161748Scperciva		: > serverlist_full
925161748Scperciva		return 1
926161748Scperciva	fi
927161748Scperciva
928161748Scperciva	echo -n "Looking up ${SERVERNAME} mirrors... "
929161748Scperciva
930161748Scperciva# Issue the SRV query and pull out the Priority, Weight, and Target fields.
931161748Scperciva# BIND 9 prints "$name has SRV record ..." while BIND 8 prints
932161748Scperciva# "$name server selection ..."; we allow either format.
933161748Scperciva	MLIST="_http._tcp.${SERVERNAME}"
934161748Scperciva	host -t srv "${MLIST}" |
935161748Scperciva	    sed -nE "s/${MLIST} (has SRV record|server selection) //p" |
936161748Scperciva	    cut -f 1,2,4 -d ' ' |
937161748Scperciva	    sed -e 's/\.$//' |
938161748Scperciva	    sort > serverlist_full
939161748Scperciva
940161748Scperciva# If no records, give up -- we'll just use the server name we were given.
941161748Scperciva	if [ `wc -l < serverlist_full` -eq 0 ]; then
942161748Scperciva		echo "none found."
943161748Scperciva		return 1
944161748Scperciva	fi
945161748Scperciva
946161748Scperciva# Report how many mirrors we found.
947161748Scperciva	echo `wc -l < serverlist_full` "mirrors found."
948161748Scperciva
949161748Scperciva# Generate a random seed for use in picking mirrors.  If HTTP_PROXY
950161748Scperciva# is set, this will be used to generate the seed; otherwise, the seed
951161748Scperciva# will be random.
952161748Scperciva	if [ -n "${HTTP_PROXY}${http_proxy}" ]; then
953161748Scperciva		RANDVALUE=`sha256 -qs "${HTTP_PROXY}${http_proxy}" |
954161748Scperciva		    tr -d 'a-f' |
955161748Scperciva		    cut -c 1-9`
956161748Scperciva	else
957161748Scperciva		RANDVALUE=`jot -r 1 0 999999999`
958161748Scperciva	fi
959161748Scperciva}
960161748Scperciva
961161748Scperciva# Pick a mirror.  Returns 1 if we have run out of mirrors to try.
962161748Scpercivafetch_pick_server () {
963161748Scperciva# Generate a list of not-yet-tried mirrors
964161748Scperciva	sort serverlist_tried |
965161748Scperciva	    comm -23 serverlist_full - > serverlist
966161748Scperciva
967161748Scperciva# Have we run out of mirrors?
968161748Scperciva	if [ `wc -l < serverlist` -eq 0 ]; then
969161748Scperciva		echo "No mirrors remaining, giving up."
970161748Scperciva		return 1
971161748Scperciva	fi
972161748Scperciva
973161748Scperciva# Find the highest priority level (lowest numeric value).
974161748Scperciva	SRV_PRIORITY=`cut -f 1 -d ' ' serverlist | sort -n | head -1`
975161748Scperciva
976161748Scperciva# Add up the weights of the response lines at that priority level.
977161748Scperciva	SRV_WSUM=0;
978161748Scperciva	while read X; do
979161748Scperciva		case "$X" in
980161748Scperciva		${SRV_PRIORITY}\ *)
981161748Scperciva			SRV_W=`echo $X | cut -f 2 -d ' '`
982161748Scperciva			SRV_WSUM=$(($SRV_WSUM + $SRV_W))
983161748Scperciva			;;
984161748Scperciva		esac
985161748Scperciva	done < serverlist
986161748Scperciva
987161748Scperciva# If all the weights are 0, pretend that they are all 1 instead.
988161748Scperciva	if [ ${SRV_WSUM} -eq 0 ]; then
989161748Scperciva		SRV_WSUM=`grep -E "^${SRV_PRIORITY} " serverlist | wc -l`
990161748Scperciva		SRV_W_ADD=1
991161748Scperciva	else
992161748Scperciva		SRV_W_ADD=0
993161748Scperciva	fi
994161748Scperciva
995161748Scperciva# Pick a value between 0 and the sum of the weights - 1
996161748Scperciva	SRV_RND=`expr ${RANDVALUE} % ${SRV_WSUM}`
997161748Scperciva
998161748Scperciva# Read through the list of mirrors and set SERVERNAME.  Write the line
999161748Scperciva# corresponding to the mirror we selected into serverlist_tried so that
1000161748Scperciva# we won't try it again.
1001161748Scperciva	while read X; do
1002161748Scperciva		case "$X" in
1003161748Scperciva		${SRV_PRIORITY}\ *)
1004161748Scperciva			SRV_W=`echo $X | cut -f 2 -d ' '`
1005161748Scperciva			SRV_W=$(($SRV_W + $SRV_W_ADD))
1006161748Scperciva			if [ $SRV_RND -lt $SRV_W ]; then
1007161748Scperciva				SERVERNAME=`echo $X | cut -f 3 -d ' '`
1008161748Scperciva				echo "$X" >> serverlist_tried
1009161748Scperciva				break
1010161748Scperciva			else
1011161748Scperciva				SRV_RND=$(($SRV_RND - $SRV_W))
1012161748Scperciva			fi
1013161748Scperciva			;;
1014161748Scperciva		esac
1015161748Scperciva	done < serverlist
1016161748Scperciva}
1017161748Scperciva
1018161748Scperciva# Take a list of ${oldhash}|${newhash} and output a list of needed patches,
1019161748Scperciva# i.e., those for which we have ${oldhash} and don't have ${newhash}.
1020161748Scpercivafetch_make_patchlist () {
1021161748Scperciva	grep -vE "^([0-9a-f]{64})\|\1$" |
1022161748Scperciva	    tr '|' ' ' |
1023161748Scperciva		while read X Y; do
1024161748Scperciva			if [ -f "files/${Y}.gz" ] ||
1025161748Scperciva			    [ ! -f "files/${X}.gz" ]; then
1026161748Scperciva				continue
1027161748Scperciva			fi
1028161748Scperciva			echo "${X}|${Y}"
1029161748Scperciva		done | uniq
1030161748Scperciva}
1031161748Scperciva
1032161748Scperciva# Print user-friendly progress statistics
1033161748Scpercivafetch_progress () {
1034161748Scperciva	LNC=0
1035161748Scperciva	while read x; do
1036161748Scperciva		LNC=$(($LNC + 1))
1037161748Scperciva		if [ $(($LNC % 10)) = 0 ]; then
1038161748Scperciva			echo -n $LNC
1039161748Scperciva		elif [ $(($LNC % 2)) = 0 ]; then
1040161748Scperciva			echo -n .
1041161748Scperciva		fi
1042161748Scperciva	done
1043161748Scperciva	echo -n " "
1044161748Scperciva}
1045161748Scperciva
1046173564Scperciva# Function for asking the user if everything is ok
1047173564Scpercivacontinuep () {
1048173564Scperciva	while read -p "Does this look reasonable (y/n)? " CONTINUE; do
1049173564Scperciva		case "${CONTINUE}" in
1050173564Scperciva		y*)
1051173564Scperciva			return 0
1052173564Scperciva			;;
1053173564Scperciva		n*)
1054173564Scperciva			return 1
1055173564Scperciva			;;
1056173564Scperciva		esac
1057173564Scperciva	done
1058173564Scperciva}
1059173564Scperciva
1060161748Scperciva# Initialize the working directory
1061161748Scpercivaworkdir_init () {
1062161748Scperciva	mkdir -p files
1063161748Scperciva	touch tINDEX.present
1064161748Scperciva}
1065161748Scperciva
1066161748Scperciva# Check that we have a public key with an appropriate hash, or
1067161748Scperciva# fetch the key if it doesn't exist.  Returns 1 if the key has
1068161748Scperciva# not yet been fetched.
1069161748Scpercivafetch_key () {
1070161748Scperciva	if [ -r pub.ssl ] && [ `${SHA256} -q pub.ssl` = ${KEYPRINT} ]; then
1071161748Scperciva		return 0
1072161748Scperciva	fi
1073161748Scperciva
1074161748Scperciva	echo -n "Fetching public key from ${SERVERNAME}... "
1075161748Scperciva	rm -f pub.ssl
1076161748Scperciva	fetch ${QUIETFLAG} http://${SERVERNAME}/${FETCHDIR}/pub.ssl \
1077161748Scperciva	    2>${QUIETREDIR} || true
1078161748Scperciva	if ! [ -r pub.ssl ]; then
1079161748Scperciva		echo "failed."
1080161748Scperciva		return 1
1081161748Scperciva	fi
1082161748Scperciva	if ! [ `${SHA256} -q pub.ssl` = ${KEYPRINT} ]; then
1083161748Scperciva		echo "key has incorrect hash."
1084161748Scperciva		rm -f pub.ssl
1085161748Scperciva		return 1
1086161748Scperciva	fi
1087161748Scperciva	echo "done."
1088161748Scperciva}
1089161748Scperciva
1090161748Scperciva# Fetch metadata signature, aka "tag".
1091161748Scpercivafetch_tag () {
1092173564Scperciva	echo -n "Fetching metadata signature "
1093173564Scperciva	echo ${NDEBUG} "for ${RELNUM} from ${SERVERNAME}... "
1094161748Scperciva	rm -f latest.ssl
1095161748Scperciva	fetch ${QUIETFLAG} http://${SERVERNAME}/${FETCHDIR}/latest.ssl	\
1096161748Scperciva	    2>${QUIETREDIR} || true
1097161748Scperciva	if ! [ -r latest.ssl ]; then
1098161748Scperciva		echo "failed."
1099161748Scperciva		return 1
1100161748Scperciva	fi
1101161748Scperciva
1102161748Scperciva	openssl rsautl -pubin -inkey pub.ssl -verify		\
1103161748Scperciva	    < latest.ssl > tag.new 2>${QUIETREDIR} || true
1104161748Scperciva	rm latest.ssl
1105161748Scperciva
1106161748Scperciva	if ! [ `wc -l < tag.new` = 1 ] ||
1107161748Scperciva	    ! grep -qE	\
1108161748Scperciva    "^freebsd-update\|${ARCH}\|${RELNUM}\|[0-9]+\|[0-9a-f]{64}\|[0-9]{10}" \
1109161748Scperciva		tag.new; then
1110161748Scperciva		echo "invalid signature."
1111161748Scperciva		return 1
1112161748Scperciva	fi
1113161748Scperciva
1114161748Scperciva	echo "done."
1115161748Scperciva
1116161748Scperciva	RELPATCHNUM=`cut -f 4 -d '|' < tag.new`
1117161748Scperciva	TINDEXHASH=`cut -f 5 -d '|' < tag.new`
1118161748Scperciva	EOLTIME=`cut -f 6 -d '|' < tag.new`
1119161748Scperciva}
1120161748Scperciva
1121161748Scperciva# Sanity-check the patch number in a tag, to make sure that we're not
1122161748Scperciva# going to "update" backwards and to prevent replay attacks.
1123161748Scpercivafetch_tagsanity () {
1124161748Scperciva	# Check that we're not going to move from -pX to -pY with Y < X.
1125161748Scperciva	RELPX=`uname -r | sed -E 's,.*-,,'`
1126161748Scperciva	if echo ${RELPX} | grep -qE '^p[0-9]+$'; then
1127161748Scperciva		RELPX=`echo ${RELPX} | cut -c 2-`
1128161748Scperciva	else
1129161748Scperciva		RELPX=0
1130161748Scperciva	fi
1131161748Scperciva	if [ "${RELPATCHNUM}" -lt "${RELPX}" ]; then
1132161748Scperciva		echo
1133161748Scperciva		echo -n "Files on mirror (${RELNUM}-p${RELPATCHNUM})"
1134161748Scperciva		echo " appear older than what"
1135161748Scperciva		echo "we are currently running (`uname -r`)!"
1136161748Scperciva		echo "Cowardly refusing to proceed any further."
1137161748Scperciva		return 1
1138161748Scperciva	fi
1139161748Scperciva
1140161748Scperciva	# If "tag" exists and corresponds to ${RELNUM}, make sure that
1141161748Scperciva	# it contains a patch number <= RELPATCHNUM, in order to protect
1142161748Scperciva	# against rollback (replay) attacks.
1143161748Scperciva	if [ -f tag ] &&
1144161748Scperciva	    grep -qE	\
1145161748Scperciva    "^freebsd-update\|${ARCH}\|${RELNUM}\|[0-9]+\|[0-9a-f]{64}\|[0-9]{10}" \
1146161748Scperciva		tag; then
1147161748Scperciva		LASTRELPATCHNUM=`cut -f 4 -d '|' < tag`
1148161748Scperciva
1149161748Scperciva		if [ "${RELPATCHNUM}" -lt "${LASTRELPATCHNUM}" ]; then
1150161748Scperciva			echo
1151161748Scperciva			echo -n "Files on mirror (${RELNUM}-p${RELPATCHNUM})"
1152161748Scperciva			echo " are older than the"
1153161748Scperciva			echo -n "most recently seen updates"
1154161748Scperciva			echo " (${RELNUM}-p${LASTRELPATCHNUM})."
1155161748Scperciva			echo "Cowardly refusing to proceed any further."
1156161748Scperciva			return 1
1157161748Scperciva		fi
1158161748Scperciva	fi
1159161748Scperciva}
1160161748Scperciva
1161161748Scperciva# Fetch metadata index file
1162161748Scpercivafetch_metadata_index () {
1163161748Scperciva	echo ${NDEBUG} "Fetching metadata index... "
1164161748Scperciva	rm -f ${TINDEXHASH}
1165161748Scperciva	fetch ${QUIETFLAG} http://${SERVERNAME}/${FETCHDIR}/t/${TINDEXHASH}
1166161748Scperciva	    2>${QUIETREDIR}
1167161748Scperciva	if ! [ -f ${TINDEXHASH} ]; then
1168161748Scperciva		echo "failed."
1169161748Scperciva		return 1
1170161748Scperciva	fi
1171161748Scperciva	if [ `${SHA256} -q ${TINDEXHASH}` != ${TINDEXHASH} ]; then
1172161748Scperciva		echo "update metadata index corrupt."
1173161748Scperciva		return 1
1174161748Scperciva	fi
1175161748Scperciva	echo "done."
1176161748Scperciva}
1177161748Scperciva
1178161748Scperciva# Print an error message about signed metadata being bogus.
1179161748Scpercivafetch_metadata_bogus () {
1180161748Scperciva	echo
1181161748Scperciva	echo "The update metadata$1 is correctly signed, but"
1182161748Scperciva	echo "failed an integrity check."
1183161748Scperciva	echo "Cowardly refusing to proceed any further."
1184161748Scperciva	return 1
1185161748Scperciva}
1186161748Scperciva
1187161748Scperciva# Construct tINDEX.new by merging the lines named in $1 from ${TINDEXHASH}
1188161748Scperciva# with the lines not named in $@ from tINDEX.present (if that file exists).
1189161748Scpercivafetch_metadata_index_merge () {
1190161748Scperciva	for METAFILE in $@; do
1191161748Scperciva		if [ `grep -E "^${METAFILE}\|" ${TINDEXHASH} | wc -l`	\
1192161748Scperciva		    -ne 1 ]; then
1193161748Scperciva			fetch_metadata_bogus " index"
1194161748Scperciva			return 1
1195161748Scperciva		fi
1196161748Scperciva
1197161748Scperciva		grep -E "${METAFILE}\|" ${TINDEXHASH}
1198161748Scperciva	done |
1199161748Scperciva	    sort > tINDEX.wanted
1200161748Scperciva
1201161748Scperciva	if [ -f tINDEX.present ]; then
1202161748Scperciva		join -t '|' -v 2 tINDEX.wanted tINDEX.present |
1203161748Scperciva		    sort -m - tINDEX.wanted > tINDEX.new
1204161748Scperciva		rm tINDEX.wanted
1205161748Scperciva	else
1206161748Scperciva		mv tINDEX.wanted tINDEX.new
1207161748Scperciva	fi
1208161748Scperciva}
1209161748Scperciva
1210161748Scperciva# Sanity check all the lines of tINDEX.new.  Even if more metadata lines
1211161748Scperciva# are added by future versions of the server, this won't cause problems,
1212161748Scperciva# since the only lines which appear in tINDEX.new are the ones which we
1213161748Scperciva# specifically grepped out of ${TINDEXHASH}.
1214161748Scpercivafetch_metadata_index_sanity () {
1215161748Scperciva	if grep -qvE '^[0-9A-Z.-]+\|[0-9a-f]{64}$' tINDEX.new; then
1216161748Scperciva		fetch_metadata_bogus " index"
1217161748Scperciva		return 1
1218161748Scperciva	fi
1219161748Scperciva}
1220161748Scperciva
1221161748Scperciva# Sanity check the metadata file $1.
1222161748Scpercivafetch_metadata_sanity () {
1223161748Scperciva	# Some aliases to save space later: ${P} is a character which can
1224161748Scperciva	# appear in a path; ${M} is the four numeric metadata fields; and
1225161748Scperciva	# ${H} is a sha256 hash.
1226257192Sdelphij	P="[-+./:=%@_[~[:alnum:]]"
1227161748Scperciva	M="[0-9]+\|[0-9]+\|[0-9]+\|[0-9]+"
1228161748Scperciva	H="[0-9a-f]{64}"
1229161748Scperciva
1230161748Scperciva	# Check that the first four fields make sense.
1231161748Scperciva	if gunzip -c < files/$1.gz |
1232303304Sdelphij	    grep -qvE "^[a-z]+\|[0-9a-z-]+\|${P}+\|[fdL-]\|"; then
1233161748Scperciva		fetch_metadata_bogus ""
1234161748Scperciva		return 1
1235161748Scperciva	fi
1236161748Scperciva
1237161748Scperciva	# Remove the first three fields.
1238161748Scperciva	gunzip -c < files/$1.gz |
1239161748Scperciva	    cut -f 4- -d '|' > sanitycheck.tmp
1240161748Scperciva
1241161748Scperciva	# Sanity check entries with type 'f'
1242161748Scperciva	if grep -E '^f' sanitycheck.tmp |
1243161748Scperciva	    grep -qvE "^f\|${M}\|${H}\|${P}*\$"; then
1244161748Scperciva		fetch_metadata_bogus ""
1245161748Scperciva		return 1
1246161748Scperciva	fi
1247161748Scperciva
1248161748Scperciva	# Sanity check entries with type 'd'
1249161748Scperciva	if grep -E '^d' sanitycheck.tmp |
1250161748Scperciva	    grep -qvE "^d\|${M}\|\|\$"; then
1251161748Scperciva		fetch_metadata_bogus ""
1252161748Scperciva		return 1
1253161748Scperciva	fi
1254161748Scperciva
1255161748Scperciva	# Sanity check entries with type 'L'
1256161748Scperciva	if grep -E '^L' sanitycheck.tmp |
1257161748Scperciva	    grep -qvE "^L\|${M}\|${P}*\|\$"; then
1258161748Scperciva		fetch_metadata_bogus ""
1259161748Scperciva		return 1
1260161748Scperciva	fi
1261161748Scperciva
1262161748Scperciva	# Sanity check entries with type '-'
1263161748Scperciva	if grep -E '^-' sanitycheck.tmp |
1264161748Scperciva	    grep -qvE "^-\|\|\|\|\|\|"; then
1265161748Scperciva		fetch_metadata_bogus ""
1266161748Scperciva		return 1
1267161748Scperciva	fi
1268161748Scperciva
1269161748Scperciva	# Clean up
1270161748Scperciva	rm sanitycheck.tmp
1271161748Scperciva}
1272161748Scperciva
1273161748Scperciva# Fetch the metadata index and metadata files listed in $@,
1274161748Scperciva# taking advantage of metadata patches where possible.
1275161748Scpercivafetch_metadata () {
1276161748Scperciva	fetch_metadata_index || return 1
1277161748Scperciva	fetch_metadata_index_merge $@ || return 1
1278161748Scperciva	fetch_metadata_index_sanity || return 1
1279161748Scperciva
1280161748Scperciva	# Generate a list of wanted metadata patches
1281161748Scperciva	join -t '|' -o 1.2,2.2 tINDEX.present tINDEX.new |
1282161748Scperciva	    fetch_make_patchlist > patchlist
1283161748Scperciva
1284161748Scperciva	if [ -s patchlist ]; then
1285161748Scperciva		# Attempt to fetch metadata patches
1286161748Scperciva		echo -n "Fetching `wc -l < patchlist | tr -d ' '` "
1287161748Scperciva		echo ${NDEBUG} "metadata patches.${DDSTATS}"
1288161748Scperciva		tr '|' '-' < patchlist |
1289161748Scperciva		    lam -s "${FETCHDIR}/tp/" - -s ".gz" |
1290161748Scperciva		    xargs ${XARGST} ${PHTTPGET} ${SERVERNAME}	\
1291161748Scperciva			2>${STATSREDIR} | fetch_progress
1292161748Scperciva		echo "done."
1293161748Scperciva
1294161748Scperciva		# Attempt to apply metadata patches
1295161748Scperciva		echo -n "Applying metadata patches... "
1296161748Scperciva		tr '|' ' ' < patchlist |
1297161748Scperciva		    while read X Y; do
1298161748Scperciva			if [ ! -f "${X}-${Y}.gz" ]; then continue; fi
1299161748Scperciva			gunzip -c < ${X}-${Y}.gz > diff
1300161748Scperciva			gunzip -c < files/${X}.gz > diff-OLD
1301161748Scperciva
1302161748Scperciva			# Figure out which lines are being added and removed
1303161748Scperciva			grep -E '^-' diff |
1304161748Scperciva			    cut -c 2- |
1305161748Scperciva			    while read PREFIX; do
1306161748Scperciva				look "${PREFIX}" diff-OLD
1307161748Scperciva			    done |
1308161748Scperciva			    sort > diff-rm
1309161748Scperciva			grep -E '^\+' diff |
1310161748Scperciva			    cut -c 2- > diff-add
1311161748Scperciva
1312161748Scperciva			# Generate the new file
1313161748Scperciva			comm -23 diff-OLD diff-rm |
1314161748Scperciva			    sort - diff-add > diff-NEW
1315161748Scperciva
1316161748Scperciva			if [ `${SHA256} -q diff-NEW` = ${Y} ]; then
1317161748Scperciva				mv diff-NEW files/${Y}
1318161748Scperciva				gzip -n files/${Y}
1319161748Scperciva			else
1320161748Scperciva				mv diff-NEW ${Y}.bad
1321161748Scperciva			fi
1322161748Scperciva			rm -f ${X}-${Y}.gz diff
1323161748Scperciva			rm -f diff-OLD diff-NEW diff-add diff-rm
1324161748Scperciva		done 2>${QUIETREDIR}
1325161748Scperciva		echo "done."
1326161748Scperciva	fi
1327161748Scperciva
1328161748Scperciva	# Update metadata without patches
1329161748Scperciva	cut -f 2 -d '|' < tINDEX.new |
1330161748Scperciva	    while read Y; do
1331161748Scperciva		if [ ! -f "files/${Y}.gz" ]; then
1332161748Scperciva			echo ${Y};
1333161748Scperciva		fi
1334164600Scperciva	    done |
1335164600Scperciva	    sort -u > filelist
1336161748Scperciva
1337161748Scperciva	if [ -s filelist ]; then
1338161748Scperciva		echo -n "Fetching `wc -l < filelist | tr -d ' '` "
1339161748Scperciva		echo ${NDEBUG} "metadata files... "
1340161748Scperciva		lam -s "${FETCHDIR}/m/" - -s ".gz" < filelist |
1341161748Scperciva		    xargs ${XARGST} ${PHTTPGET} ${SERVERNAME}	\
1342161748Scperciva		    2>${QUIETREDIR}
1343161748Scperciva
1344161748Scperciva		while read Y; do
1345161748Scperciva			if ! [ -f ${Y}.gz ]; then
1346161748Scperciva				echo "failed."
1347161748Scperciva				return 1
1348161748Scperciva			fi
1349161748Scperciva			if [ `gunzip -c < ${Y}.gz |
1350161748Scperciva			    ${SHA256} -q` = ${Y} ]; then
1351161748Scperciva				mv ${Y}.gz files/${Y}.gz
1352161748Scperciva			else
1353161748Scperciva				echo "metadata is corrupt."
1354161748Scperciva				return 1
1355161748Scperciva			fi
1356161748Scperciva		done < filelist
1357161748Scperciva		echo "done."
1358161748Scperciva	fi
1359161748Scperciva
1360161748Scperciva# Sanity-check the metadata files.
1361161748Scperciva	cut -f 2 -d '|' tINDEX.new > filelist
1362161748Scperciva	while read X; do
1363161748Scperciva		fetch_metadata_sanity ${X} || return 1
1364161748Scperciva	done < filelist
1365161748Scperciva
1366161748Scperciva# Remove files which are no longer needed
1367161748Scperciva	cut -f 2 -d '|' tINDEX.present |
1368161748Scperciva	    sort > oldfiles
1369161748Scperciva	cut -f 2 -d '|' tINDEX.new |
1370161748Scperciva	    sort |
1371161748Scperciva	    comm -13 - oldfiles |
1372161748Scperciva	    lam -s "files/" - -s ".gz" |
1373161748Scperciva	    xargs rm -f
1374161748Scperciva	rm patchlist filelist oldfiles
1375161748Scperciva	rm ${TINDEXHASH}
1376161748Scperciva
1377161748Scperciva# We're done!
1378161748Scperciva	mv tINDEX.new tINDEX.present
1379161748Scperciva	mv tag.new tag
1380161748Scperciva
1381161748Scperciva	return 0
1382161748Scperciva}
1383161748Scperciva
1384173564Scperciva# Extract a subset of a downloaded metadata file containing only the parts
1385173564Scperciva# which are listed in COMPONENTS.
1386173564Scpercivafetch_filter_metadata_components () {
1387173564Scperciva	METAHASH=`look "$1|" tINDEX.present | cut -f 2 -d '|'`
1388173564Scperciva	gunzip -c < files/${METAHASH}.gz > $1.all
1389173564Scperciva
1390173564Scperciva	# Fish out the lines belonging to components we care about.
1391173564Scperciva	for C in ${COMPONENTS}; do
1392173564Scperciva		look "`echo ${C} | tr '/' '|'`|" $1.all
1393173564Scperciva	done > $1
1394173564Scperciva
1395173564Scperciva	# Remove temporary file.
1396173564Scperciva	rm $1.all
1397173564Scperciva}
1398173564Scperciva
1399161869Scperciva# Generate a filtered version of the metadata file $1 from the downloaded
1400161748Scperciva# file, by fishing out the lines corresponding to components we're trying
1401161748Scperciva# to keep updated, and then removing lines corresponding to paths we want
1402161748Scperciva# to ignore.
1403161748Scpercivafetch_filter_metadata () {
1404173564Scperciva	# Fish out the lines belonging to components we care about.
1405173564Scperciva	fetch_filter_metadata_components $1
1406161748Scperciva
1407161748Scperciva	# Canonicalize directory names by removing any trailing / in
1408161748Scperciva	# order to avoid listing directories multiple times if they
1409161748Scperciva	# belong to multiple components.  Turning "/" into "" doesn't
1410161748Scperciva	# matter, since we add a leading "/" when we use paths later.
1411173564Scperciva	cut -f 3- -d '|' $1 |
1412161748Scperciva	    sed -e 's,/|d|,|d|,' |
1413276157Sdes	    sed -e 's,/|-|,|-|,' |
1414161748Scperciva	    sort -u > $1.tmp
1415161748Scperciva
1416161748Scperciva	# Figure out which lines to ignore and remove them.
1417161748Scperciva	for X in ${IGNOREPATHS}; do
1418161748Scperciva		grep -E "^${X}" $1.tmp
1419161748Scperciva	done |
1420161748Scperciva	    sort -u |
1421161748Scperciva	    comm -13 - $1.tmp > $1
1422161748Scperciva
1423161748Scperciva	# Remove temporary files.
1424173564Scperciva	rm $1.tmp
1425161748Scperciva}
1426161748Scperciva
1427173564Scperciva# Filter the metadata file $1 by adding lines with "/boot/$2"
1428164600Scperciva# replaced by ${KERNELDIR} (which is `sysctl -n kern.bootfile` minus the
1429173564Scperciva# trailing "/kernel"); and if "/boot/$2" does not exist, remove
1430164600Scperciva# the original lines which start with that.
1431164600Scperciva# Put another way: Deal with the fact that the FOO kernel is sometimes
1432164600Scperciva# installed in /boot/FOO/ and is sometimes installed elsewhere.
1433161748Scpercivafetch_filter_kernel_names () {
1434173564Scperciva	grep ^/boot/$2 $1 |
1435173564Scperciva	    sed -e "s,/boot/$2,${KERNELDIR},g" |
1436161748Scperciva	    sort - $1 > $1.tmp
1437161748Scperciva	mv $1.tmp $1
1438164600Scperciva
1439173564Scperciva	if ! [ -d /boot/$2 ]; then
1440173564Scperciva		grep -v ^/boot/$2 $1 > $1.tmp
1441164600Scperciva		mv $1.tmp $1
1442164600Scperciva	fi
1443161748Scperciva}
1444161748Scperciva
1445161748Scperciva# For all paths appearing in $1 or $3, inspect the system
1446161748Scperciva# and generate $2 describing what is currently installed.
1447161748Scpercivafetch_inspect_system () {
1448161748Scperciva	# No errors yet...
1449161748Scperciva	rm -f .err
1450161748Scperciva
1451161748Scperciva	# Tell the user why his disk is suddenly making lots of noise
1452161748Scperciva	echo -n "Inspecting system... "
1453161748Scperciva
1454161748Scperciva	# Generate list of files to inspect
1455161748Scperciva	cat $1 $3 |
1456161748Scperciva	    cut -f 1 -d '|' |
1457161748Scperciva	    sort -u > filelist
1458161748Scperciva
1459161748Scperciva	# Examine each file and output lines of the form
1460161748Scperciva	# /path/to/file|type|device-inum|user|group|perm|flags|value
1461161748Scperciva	# sorted by device and inode number.
1462161748Scperciva	while read F; do
1463161748Scperciva		# If the symlink/file/directory does not exist, record this.
1464161748Scperciva		if ! [ -e ${BASEDIR}/${F} ]; then
1465161748Scperciva			echo "${F}|-||||||"
1466161748Scperciva			continue
1467161748Scperciva		fi
1468161748Scperciva		if ! [ -r ${BASEDIR}/${F} ]; then
1469161748Scperciva			echo "Cannot read file: ${BASEDIR}/${F}"	\
1470161748Scperciva			    >/dev/stderr
1471161748Scperciva			touch .err
1472161748Scperciva			return 1
1473161748Scperciva		fi
1474161748Scperciva
1475161748Scperciva		# Otherwise, output an index line.
1476161748Scperciva		if [ -L ${BASEDIR}/${F} ]; then
1477161748Scperciva			echo -n "${F}|L|"
1478161748Scperciva			stat -n -f '%d-%i|%u|%g|%Mp%Lp|%Of|' ${BASEDIR}/${F};
1479161748Scperciva			readlink ${BASEDIR}/${F};
1480161748Scperciva		elif [ -f ${BASEDIR}/${F} ]; then
1481161748Scperciva			echo -n "${F}|f|"
1482161748Scperciva			stat -n -f '%d-%i|%u|%g|%Mp%Lp|%Of|' ${BASEDIR}/${F};
1483161748Scperciva			sha256 -q ${BASEDIR}/${F};
1484161748Scperciva		elif [ -d ${BASEDIR}/${F} ]; then
1485161748Scperciva			echo -n "${F}|d|"
1486161748Scperciva			stat -f '%d-%i|%u|%g|%Mp%Lp|%Of|' ${BASEDIR}/${F};
1487161748Scperciva		else
1488161748Scperciva			echo "Unknown file type: ${BASEDIR}/${F}"	\
1489161748Scperciva			    >/dev/stderr
1490161748Scperciva			touch .err
1491161748Scperciva			return 1
1492161748Scperciva		fi
1493161748Scperciva	done < filelist |
1494161748Scperciva	    sort -k 3,3 -t '|' > $2.tmp
1495161748Scperciva	rm filelist
1496161748Scperciva
1497215087Sbcr	# Check if an error occurred during system inspection
1498161748Scperciva	if [ -f .err ]; then
1499161748Scperciva		return 1
1500161748Scperciva	fi
1501161748Scperciva
1502161748Scperciva	# Convert to the form
1503161748Scperciva	# /path/to/file|type|user|group|perm|flags|value|hlink
1504161748Scperciva	# by resolving identical device and inode numbers into hard links.
1505161748Scperciva	cut -f 1,3 -d '|' $2.tmp |
1506161748Scperciva	    sort -k 1,1 -t '|' |
1507161748Scperciva	    sort -s -u -k 2,2 -t '|' |
1508161748Scperciva	    join -1 2 -2 3 -t '|' - $2.tmp |
1509161748Scperciva	    awk -F \| -v OFS=\|		\
1510161748Scperciva		'{
1511161748Scperciva		    if (($2 == $3) || ($4 == "-"))
1512161748Scperciva			print $3,$4,$5,$6,$7,$8,$9,""
1513161748Scperciva		    else
1514161748Scperciva			print $3,$4,$5,$6,$7,$8,$9,$2
1515161748Scperciva		}' |
1516161748Scperciva	    sort > $2
1517161748Scperciva	rm $2.tmp
1518161748Scperciva
1519161748Scperciva	# We're finished looking around
1520161748Scperciva	echo "done."
1521161748Scperciva}
1522161748Scperciva
1523173564Scperciva# For any paths matching ${MERGECHANGES}, compare $1 and $2 and find any
1524173564Scperciva# files which differ; generate $3 containing these paths and the old hashes.
1525173564Scpercivafetch_filter_mergechanges () {
1526173564Scperciva	# Pull out the paths and hashes of the files matching ${MERGECHANGES}.
1527173564Scperciva	for F in $1 $2; do
1528173564Scperciva		for X in ${MERGECHANGES}; do
1529173564Scperciva			grep -E "^${X}" ${F}
1530173564Scperciva		done |
1531173564Scperciva		    cut -f 1,2,7 -d '|' |
1532173564Scperciva		    sort > ${F}-values
1533173564Scperciva	done
1534173564Scperciva
1535173564Scperciva	# Any line in $2-values which doesn't appear in $1-values and is a
1536173564Scperciva	# file means that we should list the path in $3.
1537173564Scperciva	comm -13 $1-values $2-values |
1538173564Scperciva	    fgrep '|f|' |
1539173564Scperciva	    cut -f 1 -d '|' > $2-paths
1540173564Scperciva
1541173564Scperciva	# For each path, pull out one (and only one!) entry from $1-values.
1542173564Scperciva	# Note that we cannot distinguish which "old" version the user made
1543173564Scperciva	# changes to; but hopefully any changes which occur due to security
1544173564Scperciva	# updates will exist in both the "new" version and the version which
1545173564Scperciva	# the user has installed, so the merging will still work.
1546173564Scperciva	while read X; do
1547173564Scperciva		look "${X}|" $1-values |
1548173564Scperciva		    head -1
1549173564Scperciva	done < $2-paths > $3
1550173564Scperciva
1551173564Scperciva	# Clean up
1552173564Scperciva	rm $1-values $2-values $2-paths
1553173564Scperciva}
1554173564Scperciva
1555161748Scperciva# For any paths matching ${UPDATEIFUNMODIFIED}, remove lines from $[123]
1556173564Scperciva# which correspond to lines in $2 with hashes not matching $1 or $3, unless
1557173564Scperciva# the paths are listed in $4.  For entries in $2 marked "not present"
1558173564Scperciva# (aka. type -), remove lines from $[123] unless there is a corresponding
1559173564Scperciva# entry in $1.
1560161748Scpercivafetch_filter_unmodified_notpresent () {
1561161748Scperciva	# Figure out which lines of $1 and $3 correspond to bits which
1562161748Scperciva	# should only be updated if they haven't changed, and fish out
1563161748Scperciva	# the (path, type, value) tuples.
1564161748Scperciva	# NOTE: We don't consider a file to be "modified" if it matches
1565161748Scperciva	# the hash from $3.
1566161748Scperciva	for X in ${UPDATEIFUNMODIFIED}; do
1567161748Scperciva		grep -E "^${X}" $1
1568161748Scperciva		grep -E "^${X}" $3
1569161748Scperciva	done |
1570161748Scperciva	    cut -f 1,2,7 -d '|' |
1571161748Scperciva	    sort > $1-values
1572161748Scperciva
1573161748Scperciva	# Do the same for $2.
1574161748Scperciva	for X in ${UPDATEIFUNMODIFIED}; do
1575161748Scperciva		grep -E "^${X}" $2
1576161748Scperciva	done |
1577161748Scperciva	    cut -f 1,2,7 -d '|' |
1578161748Scperciva	    sort > $2-values
1579161748Scperciva
1580161748Scperciva	# Any entry in $2-values which is not in $1-values corresponds to
1581173564Scperciva	# a path which we need to remove from $1, $2, and $3, unless it
1582173564Scperciva	# that path appears in $4.
1583173564Scperciva	comm -13 $1-values $2-values |
1584173564Scperciva	    sort -t '|' -k 1,1 > mlines.tmp
1585173564Scperciva	cut -f 1 -d '|' $4 |
1586173564Scperciva	    sort |
1587173564Scperciva	    join -v 2 -t '|' - mlines.tmp |
1588173564Scperciva	    sort > mlines
1589173564Scperciva	rm $1-values $2-values mlines.tmp
1590161748Scperciva
1591161748Scperciva	# Any lines in $2 which are not in $1 AND are "not present" lines
1592161748Scperciva	# also belong in mlines.
1593161748Scperciva	comm -13 $1 $2 |
1594161748Scperciva	    cut -f 1,2,7 -d '|' |
1595161748Scperciva	    fgrep '|-|' >> mlines
1596161748Scperciva
1597161748Scperciva	# Remove lines from $1, $2, and $3
1598161748Scperciva	for X in $1 $2 $3; do
1599161748Scperciva		sort -t '|' -k 1,1 ${X} > ${X}.tmp
1600161748Scperciva		cut -f 1 -d '|' < mlines |
1601161748Scperciva		    sort |
1602161748Scperciva		    join -v 2 -t '|' - ${X}.tmp |
1603161748Scperciva		    sort > ${X}
1604161748Scperciva		rm ${X}.tmp
1605161748Scperciva	done
1606161748Scperciva
1607161748Scperciva	# Store a list of the modified files, for future reference
1608161748Scperciva	fgrep -v '|-|' mlines |
1609161748Scperciva	    cut -f 1 -d '|' > modifiedfiles
1610161748Scperciva	rm mlines
1611161748Scperciva}
1612161748Scperciva
1613161748Scperciva# For each entry in $1 of type -, remove any corresponding
1614161748Scperciva# entry from $2 if ${ALLOWADD} != "yes".  Remove all entries
1615161748Scperciva# of type - from $1.
1616161748Scpercivafetch_filter_allowadd () {
1617161748Scperciva	cut -f 1,2 -d '|' < $1 |
1618161748Scperciva	    fgrep '|-' |
1619161748Scperciva	    cut -f 1 -d '|' > filesnotpresent
1620161748Scperciva
1621161748Scperciva	if [ ${ALLOWADD} != "yes" ]; then
1622161748Scperciva		sort < $2 |
1623161748Scperciva		    join -v 1 -t '|' - filesnotpresent |
1624161748Scperciva		    sort > $2.tmp
1625161748Scperciva		mv $2.tmp $2
1626161748Scperciva	fi
1627161748Scperciva
1628161748Scperciva	sort < $1 |
1629161748Scperciva	    join -v 1 -t '|' - filesnotpresent |
1630161748Scperciva	    sort > $1.tmp
1631161748Scperciva	mv $1.tmp $1
1632161748Scperciva	rm filesnotpresent
1633161748Scperciva}
1634161748Scperciva
1635161748Scperciva# If ${ALLOWDELETE} != "yes", then remove any entries from $1
1636161748Scperciva# which don't correspond to entries in $2.
1637161748Scpercivafetch_filter_allowdelete () {
1638161748Scperciva	# Produce a lists ${PATH}|${TYPE}
1639161748Scperciva	for X in $1 $2; do
1640161748Scperciva		cut -f 1-2 -d '|' < ${X} |
1641161748Scperciva		    sort -u > ${X}.nodes
1642161748Scperciva	done
1643161748Scperciva
1644161748Scperciva	# Figure out which lines need to be removed from $1.
1645161748Scperciva	if [ ${ALLOWDELETE} != "yes" ]; then
1646161748Scperciva		comm -23 $1.nodes $2.nodes > $1.badnodes
1647161748Scperciva	else
1648161748Scperciva		: > $1.badnodes
1649161748Scperciva	fi
1650161748Scperciva
1651161748Scperciva	# Remove the relevant lines from $1
1652161748Scperciva	while read X; do
1653161748Scperciva		look "${X}|" $1
1654161748Scperciva	done < $1.badnodes |
1655161748Scperciva	    comm -13 - $1 > $1.tmp
1656161748Scperciva	mv $1.tmp $1
1657161748Scperciva
1658161748Scperciva	rm $1.badnodes $1.nodes $2.nodes
1659161748Scperciva}
1660161748Scperciva
1661161748Scperciva# If ${KEEPMODIFIEDMETADATA} == "yes", then for each entry in $2
1662161748Scperciva# with metadata not matching any entry in $1, replace the corresponding
1663161748Scperciva# line of $3 with one having the same metadata as the entry in $2.
1664161748Scpercivafetch_filter_modified_metadata () {
1665161748Scperciva	# Fish out the metadata from $1 and $2
1666161748Scperciva	for X in $1 $2; do
1667161748Scperciva		cut -f 1-6 -d '|' < ${X} > ${X}.metadata
1668161748Scperciva	done
1669161748Scperciva
1670161748Scperciva	# Find the metadata we need to keep
1671161748Scperciva	if [ ${KEEPMODIFIEDMETADATA} = "yes" ]; then
1672161748Scperciva		comm -13 $1.metadata $2.metadata > keepmeta
1673161748Scperciva	else
1674161748Scperciva		: > keepmeta
1675161748Scperciva	fi
1676161748Scperciva
1677161748Scperciva	# Extract the lines which we need to remove from $3, and
1678161748Scperciva	# construct the lines which we need to add to $3.
1679161748Scperciva	: > $3.remove
1680161748Scperciva	: > $3.add
1681161748Scperciva	while read LINE; do
1682161748Scperciva		NODE=`echo "${LINE}" | cut -f 1-2 -d '|'`
1683161748Scperciva		look "${NODE}|" $3 >> $3.remove
1684161748Scperciva		look "${NODE}|" $3 |
1685161748Scperciva		    cut -f 7- -d '|' |
1686161748Scperciva		    lam -s "${LINE}|" - >> $3.add
1687161748Scperciva	done < keepmeta
1688161748Scperciva
1689161748Scperciva	# Remove the specified lines and add the new lines.
1690161748Scperciva	sort $3.remove |
1691161748Scperciva	    comm -13 - $3 |
1692161748Scperciva	    sort -u - $3.add > $3.tmp
1693161748Scperciva	mv $3.tmp $3
1694161748Scperciva
1695161748Scperciva	rm keepmeta $1.metadata $2.metadata $3.add $3.remove
1696161748Scperciva}
1697161748Scperciva
1698161748Scperciva# Remove lines from $1 and $2 which are identical;
1699161748Scperciva# no need to update a file if it isn't changing.
1700161748Scpercivafetch_filter_uptodate () {
1701161748Scperciva	comm -23 $1 $2 > $1.tmp
1702161748Scperciva	comm -13 $1 $2 > $2.tmp
1703161748Scperciva
1704161748Scperciva	mv $1.tmp $1
1705161748Scperciva	mv $2.tmp $2
1706161748Scperciva}
1707161748Scperciva
1708173564Scperciva# Fetch any "clean" old versions of files we need for merging changes.
1709173564Scpercivafetch_files_premerge () {
1710173564Scperciva	# We only need to do anything if $1 is non-empty.
1711173564Scperciva	if [ -s $1 ]; then
1712173564Scperciva		# Tell the user what we're doing
1713173564Scperciva		echo -n "Fetching files from ${OLDRELNUM} for merging... "
1714173564Scperciva
1715173564Scperciva		# List of files wanted
1716173564Scperciva		fgrep '|f|' < $1 |
1717173564Scperciva		    cut -f 3 -d '|' |
1718173564Scperciva		    sort -u > files.wanted
1719173564Scperciva
1720173564Scperciva		# Only fetch the files we don't already have
1721173564Scperciva		while read Y; do
1722173564Scperciva			if [ ! -f "files/${Y}.gz" ]; then
1723173564Scperciva				echo ${Y};
1724173564Scperciva			fi
1725173564Scperciva		done < files.wanted > filelist
1726173564Scperciva
1727173564Scperciva		# Actually fetch them
1728173564Scperciva		lam -s "${OLDFETCHDIR}/f/" - -s ".gz" < filelist |
1729173564Scperciva		    xargs ${XARGST} ${PHTTPGET} ${SERVERNAME}	\
1730173564Scperciva		    2>${QUIETREDIR}
1731173564Scperciva
1732173564Scperciva		# Make sure we got them all, and move them into /files/
1733173564Scperciva		while read Y; do
1734173564Scperciva			if ! [ -f ${Y}.gz ]; then
1735173564Scperciva				echo "failed."
1736173564Scperciva				return 1
1737173564Scperciva			fi
1738173564Scperciva			if [ `gunzip -c < ${Y}.gz |
1739173564Scperciva			    ${SHA256} -q` = ${Y} ]; then
1740173564Scperciva				mv ${Y}.gz files/${Y}.gz
1741173564Scperciva			else
1742173564Scperciva				echo "${Y} has incorrect hash."
1743173564Scperciva				return 1
1744173564Scperciva			fi
1745173564Scperciva		done < filelist
1746173564Scperciva		echo "done."
1747173564Scperciva
1748173564Scperciva		# Clean up
1749173564Scperciva		rm filelist files.wanted
1750173564Scperciva	fi
1751173564Scperciva}
1752173564Scperciva
1753161748Scperciva# Prepare to fetch files: Generate a list of the files we need,
1754161748Scperciva# copy the unmodified files we have into /files/, and generate
1755161748Scperciva# a list of patches to download.
1756161748Scpercivafetch_files_prepare () {
1757161748Scperciva	# Tell the user why his disk is suddenly making lots of noise
1758161748Scperciva	echo -n "Preparing to download files... "
1759161748Scperciva
1760161748Scperciva	# Reduce indices to ${PATH}|${HASH} pairs
1761161748Scperciva	for X in $1 $2 $3; do
1762161748Scperciva		cut -f 1,2,7 -d '|' < ${X} |
1763161748Scperciva		    fgrep '|f|' |
1764161748Scperciva		    cut -f 1,3 -d '|' |
1765161748Scperciva		    sort > ${X}.hashes
1766161748Scperciva	done
1767161748Scperciva
1768161748Scperciva	# List of files wanted
1769161748Scperciva	cut -f 2 -d '|' < $3.hashes |
1770173441Scperciva	    sort -u |
1771173441Scperciva	    while read HASH; do
1772173441Scperciva		if ! [ -f files/${HASH}.gz ]; then
1773173441Scperciva			echo ${HASH}
1774173441Scperciva		fi
1775173441Scperciva	done > files.wanted
1776161748Scperciva
1777161748Scperciva	# Generate a list of unmodified files
1778161748Scperciva	comm -12 $1.hashes $2.hashes |
1779161748Scperciva	    sort -k 1,1 -t '|' > unmodified.files
1780161748Scperciva
1781161748Scperciva	# Copy all files into /files/.  We only need the unmodified files
1782161748Scperciva	# for use in patching; but we'll want all of them if the user asks
1783161748Scperciva	# to rollback the updates later.
1784171784Scperciva	while read LINE; do
1785171784Scperciva		F=`echo "${LINE}" | cut -f 1 -d '|'`
1786171784Scperciva		HASH=`echo "${LINE}" | cut -f 2 -d '|'`
1787171784Scperciva
1788171784Scperciva		# Skip files we already have.
1789171784Scperciva		if [ -f files/${HASH}.gz ]; then
1790171784Scperciva			continue
1791171784Scperciva		fi
1792171784Scperciva
1793171784Scperciva		# Make sure the file hasn't changed.
1794161748Scperciva		cp "${BASEDIR}/${F}" tmpfile
1795171784Scperciva		if [ `sha256 -q tmpfile` != ${HASH} ]; then
1796171784Scperciva			echo
1797171784Scperciva			echo "File changed while FreeBSD Update running: ${F}"
1798171784Scperciva			return 1
1799171784Scperciva		fi
1800171784Scperciva
1801171784Scperciva		# Place the file into storage.
1802171784Scperciva		gzip -c < tmpfile > files/${HASH}.gz
1803161748Scperciva		rm tmpfile
1804171784Scperciva	done < $2.hashes
1805161748Scperciva
1806161748Scperciva	# Produce a list of patches to download
1807161748Scperciva	sort -k 1,1 -t '|' $3.hashes |
1808161748Scperciva	    join -t '|' -o 2.2,1.2 - unmodified.files |
1809161748Scperciva	    fetch_make_patchlist > patchlist
1810161748Scperciva
1811161748Scperciva	# Garbage collect
1812161748Scperciva	rm unmodified.files $1.hashes $2.hashes $3.hashes
1813161748Scperciva
1814161748Scperciva	# We don't need the list of possible old files any more.
1815161748Scperciva	rm $1
1816161748Scperciva
1817161748Scperciva	# We're finished making noise
1818161748Scperciva	echo "done."
1819161748Scperciva}
1820161748Scperciva
1821161748Scperciva# Fetch files.
1822161748Scpercivafetch_files () {
1823161748Scperciva	# Attempt to fetch patches
1824161748Scperciva	if [ -s patchlist ]; then
1825161748Scperciva		echo -n "Fetching `wc -l < patchlist | tr -d ' '` "
1826161748Scperciva		echo ${NDEBUG} "patches.${DDSTATS}"
1827161748Scperciva		tr '|' '-' < patchlist |
1828173564Scperciva		    lam -s "${PATCHDIR}/" - |
1829161748Scperciva		    xargs ${XARGST} ${PHTTPGET} ${SERVERNAME}	\
1830161748Scperciva			2>${STATSREDIR} | fetch_progress
1831161748Scperciva		echo "done."
1832161748Scperciva
1833161748Scperciva		# Attempt to apply patches
1834161748Scperciva		echo -n "Applying patches... "
1835161748Scperciva		tr '|' ' ' < patchlist |
1836161748Scperciva		    while read X Y; do
1837161748Scperciva			if [ ! -f "${X}-${Y}" ]; then continue; fi
1838161748Scperciva			gunzip -c < files/${X}.gz > OLD
1839161748Scperciva
1840161748Scperciva			bspatch OLD NEW ${X}-${Y}
1841161748Scperciva
1842161748Scperciva			if [ `${SHA256} -q NEW` = ${Y} ]; then
1843161748Scperciva				mv NEW files/${Y}
1844161748Scperciva				gzip -n files/${Y}
1845161748Scperciva			fi
1846161748Scperciva			rm -f diff OLD NEW ${X}-${Y}
1847161748Scperciva		done 2>${QUIETREDIR}
1848161748Scperciva		echo "done."
1849161748Scperciva	fi
1850161748Scperciva
1851161748Scperciva	# Download files which couldn't be generate via patching
1852161748Scperciva	while read Y; do
1853161748Scperciva		if [ ! -f "files/${Y}.gz" ]; then
1854161748Scperciva			echo ${Y};
1855161748Scperciva		fi
1856161748Scperciva	done < files.wanted > filelist
1857161748Scperciva
1858161748Scperciva	if [ -s filelist ]; then
1859161748Scperciva		echo -n "Fetching `wc -l < filelist | tr -d ' '` "
1860161748Scperciva		echo ${NDEBUG} "files... "
1861161748Scperciva		lam -s "${FETCHDIR}/f/" - -s ".gz" < filelist |
1862161748Scperciva		    xargs ${XARGST} ${PHTTPGET} ${SERVERNAME}	\
1863161748Scperciva		    2>${QUIETREDIR}
1864161748Scperciva
1865161748Scperciva		while read Y; do
1866161748Scperciva			if ! [ -f ${Y}.gz ]; then
1867161748Scperciva				echo "failed."
1868161748Scperciva				return 1
1869161748Scperciva			fi
1870161748Scperciva			if [ `gunzip -c < ${Y}.gz |
1871161748Scperciva			    ${SHA256} -q` = ${Y} ]; then
1872161748Scperciva				mv ${Y}.gz files/${Y}.gz
1873161748Scperciva			else
1874161748Scperciva				echo "${Y} has incorrect hash."
1875161748Scperciva				return 1
1876161748Scperciva			fi
1877161748Scperciva		done < filelist
1878161748Scperciva		echo "done."
1879161748Scperciva	fi
1880161748Scperciva
1881161748Scperciva	# Clean up
1882161748Scperciva	rm files.wanted filelist patchlist
1883161748Scperciva}
1884161748Scperciva
1885161748Scperciva# Create and populate install manifest directory; and report what updates
1886161748Scperciva# are available.
1887161748Scpercivafetch_create_manifest () {
1888161748Scperciva	# If we have an existing install manifest, nuke it.
1889161748Scperciva	if [ -L "${BDHASH}-install" ]; then
1890161748Scperciva		rm -r ${BDHASH}-install/
1891161748Scperciva		rm ${BDHASH}-install
1892161748Scperciva	fi
1893161748Scperciva
1894161748Scperciva	# Report to the user if any updates were avoided due to local changes
1895161748Scperciva	if [ -s modifiedfiles ]; then
1896161748Scperciva		echo
1897161748Scperciva		echo -n "The following files are affected by updates, "
1898161748Scperciva		echo "but no changes have"
1899161748Scperciva		echo -n "been downloaded because the files have been "
1900161748Scperciva		echo "modified locally:"
1901161748Scperciva		cat modifiedfiles
1902217767Sgordon	fi | $PAGER
1903161748Scperciva	rm modifiedfiles
1904161748Scperciva
1905161748Scperciva	# If no files will be updated, tell the user and exit
1906161748Scperciva	if ! [ -s INDEX-PRESENT ] &&
1907161748Scperciva	    ! [ -s INDEX-NEW ]; then
1908161748Scperciva		rm INDEX-PRESENT INDEX-NEW
1909161748Scperciva		echo
1910161748Scperciva		echo -n "No updates needed to update system to "
1911161748Scperciva		echo "${RELNUM}-p${RELPATCHNUM}."
1912161748Scperciva		return
1913161748Scperciva	fi
1914161748Scperciva
1915161748Scperciva	# Divide files into (a) removed files, (b) added files, and
1916161748Scperciva	# (c) updated files.
1917161748Scperciva	cut -f 1 -d '|' < INDEX-PRESENT |
1918161748Scperciva	    sort > INDEX-PRESENT.flist
1919161748Scperciva	cut -f 1 -d '|' < INDEX-NEW |
1920161748Scperciva	    sort > INDEX-NEW.flist
1921161748Scperciva	comm -23 INDEX-PRESENT.flist INDEX-NEW.flist > files.removed
1922161748Scperciva	comm -13 INDEX-PRESENT.flist INDEX-NEW.flist > files.added
1923161748Scperciva	comm -12 INDEX-PRESENT.flist INDEX-NEW.flist > files.updated
1924161748Scperciva	rm INDEX-PRESENT.flist INDEX-NEW.flist
1925161748Scperciva
1926161748Scperciva	# Report removed files, if any
1927161748Scperciva	if [ -s files.removed ]; then
1928161748Scperciva		echo
1929161748Scperciva		echo -n "The following files will be removed "
1930161748Scperciva		echo "as part of updating to ${RELNUM}-p${RELPATCHNUM}:"
1931161748Scperciva		cat files.removed
1932217767Sgordon	fi | $PAGER
1933161748Scperciva	rm files.removed
1934161748Scperciva
1935161748Scperciva	# Report added files, if any
1936161748Scperciva	if [ -s files.added ]; then
1937161748Scperciva		echo
1938161748Scperciva		echo -n "The following files will be added "
1939161748Scperciva		echo "as part of updating to ${RELNUM}-p${RELPATCHNUM}:"
1940161748Scperciva		cat files.added
1941217767Sgordon	fi | $PAGER
1942161748Scperciva	rm files.added
1943161748Scperciva
1944161748Scperciva	# Report updated files, if any
1945161748Scperciva	if [ -s files.updated ]; then
1946161748Scperciva		echo
1947161748Scperciva		echo -n "The following files will be updated "
1948161748Scperciva		echo "as part of updating to ${RELNUM}-p${RELPATCHNUM}:"
1949161748Scperciva
1950161748Scperciva		cat files.updated
1951217767Sgordon	fi | $PAGER
1952161748Scperciva	rm files.updated
1953161748Scperciva
1954161748Scperciva	# Create a directory for the install manifest.
1955161748Scperciva	MDIR=`mktemp -d install.XXXXXX` || return 1
1956161748Scperciva
1957161748Scperciva	# Populate it
1958161748Scperciva	mv INDEX-PRESENT ${MDIR}/INDEX-OLD
1959161748Scperciva	mv INDEX-NEW ${MDIR}/INDEX-NEW
1960161748Scperciva
1961161748Scperciva	# Link it into place
1962161748Scperciva	ln -s ${MDIR} ${BDHASH}-install
1963161748Scperciva}
1964161748Scperciva
1965161748Scperciva# Warn about any upcoming EoL
1966161748Scpercivafetch_warn_eol () {
1967161748Scperciva	# What's the current time?
1968161748Scperciva	NOWTIME=`date "+%s"`
1969161748Scperciva
1970161748Scperciva	# When did we last warn about the EoL date?
1971161748Scperciva	if [ -f lasteolwarn ]; then
1972161748Scperciva		LASTWARN=`cat lasteolwarn`
1973161748Scperciva	else
1974161748Scperciva		LASTWARN=`expr ${NOWTIME} - 63072000`
1975161748Scperciva	fi
1976161748Scperciva
1977161748Scperciva	# If the EoL time is past, warn.
1978161748Scperciva	if [ ${EOLTIME} -lt ${NOWTIME} ]; then
1979161748Scperciva		echo
1980161748Scperciva		cat <<-EOF
1981161869Scperciva		WARNING: `uname -sr` HAS PASSED ITS END-OF-LIFE DATE.
1982161748Scperciva		Any security issues discovered after `date -r ${EOLTIME}`
1983161748Scperciva		will not have been corrected.
1984161748Scperciva		EOF
1985161748Scperciva		return 1
1986161748Scperciva	fi
1987161748Scperciva
1988161748Scperciva	# Figure out how long it has been since we last warned about the
1989161748Scperciva	# upcoming EoL, and how much longer we have left.
1990161748Scperciva	SINCEWARN=`expr ${NOWTIME} - ${LASTWARN}`
1991161748Scperciva	TIMELEFT=`expr ${EOLTIME} - ${NOWTIME}`
1992161748Scperciva
1993171838Scperciva	# Don't warn if the EoL is more than 3 months away
1994171838Scperciva	if [ ${TIMELEFT} -gt 7884000 ]; then
1995161748Scperciva		return 0
1996161748Scperciva	fi
1997161748Scperciva
1998161748Scperciva	# Don't warn if the time remaining is more than 3 times the time
1999161748Scperciva	# since the last warning.
2000161748Scperciva	if [ ${TIMELEFT} -gt `expr ${SINCEWARN} \* 3` ]; then
2001161748Scperciva		return 0
2002161748Scperciva	fi
2003161748Scperciva
2004161748Scperciva	# Figure out what time units to use.
2005161748Scperciva	if [ ${TIMELEFT} -lt 604800 ]; then
2006161748Scperciva		UNIT="day"
2007161748Scperciva		SIZE=86400
2008161748Scperciva	elif [ ${TIMELEFT} -lt 2678400 ]; then
2009161748Scperciva		UNIT="week"
2010161748Scperciva		SIZE=604800
2011161748Scperciva	else
2012161748Scperciva		UNIT="month"
2013161748Scperciva		SIZE=2678400
2014161748Scperciva	fi
2015161748Scperciva
2016161748Scperciva	# Compute the right number of units
2017161748Scperciva	NUM=`expr ${TIMELEFT} / ${SIZE}`
2018161748Scperciva	if [ ${NUM} != 1 ]; then
2019161748Scperciva		UNIT="${UNIT}s"
2020161748Scperciva	fi
2021161748Scperciva
2022161748Scperciva	# Print the warning
2023161748Scperciva	echo
2024161748Scperciva	cat <<-EOF
2025161748Scperciva		WARNING: `uname -sr` is approaching its End-of-Life date.
2026161748Scperciva		It is strongly recommended that you upgrade to a newer
2027161748Scperciva		release within the next ${NUM} ${UNIT}.
2028161748Scperciva	EOF
2029161748Scperciva
2030161748Scperciva	# Update the stored time of last warning
2031161748Scperciva	echo ${NOWTIME} > lasteolwarn
2032161748Scperciva}
2033161748Scperciva
2034161748Scperciva# Do the actual work involved in "fetch" / "cron".
2035161748Scpercivafetch_run () {
2036161748Scperciva	workdir_init || return 1
2037161748Scperciva
2038161748Scperciva	# Prepare the mirror list.
2039161748Scperciva	fetch_pick_server_init && fetch_pick_server
2040161748Scperciva
2041161748Scperciva	# Try to fetch the public key until we run out of servers.
2042161748Scperciva	while ! fetch_key; do
2043161748Scperciva		fetch_pick_server || return 1
2044161748Scperciva	done
2045161748Scperciva
2046161748Scperciva	# Try to fetch the metadata index signature ("tag") until we run
2047161748Scperciva	# out of available servers; and sanity check the downloaded tag.
2048161748Scperciva	while ! fetch_tag; do
2049161748Scperciva		fetch_pick_server || return 1
2050161748Scperciva	done
2051161748Scperciva	fetch_tagsanity || return 1
2052161748Scperciva
2053161748Scperciva	# Fetch the latest INDEX-NEW and INDEX-OLD files.
2054161748Scperciva	fetch_metadata INDEX-NEW INDEX-OLD || return 1
2055161748Scperciva
2056161748Scperciva	# Generate filtered INDEX-NEW and INDEX-OLD files containing only
2057161748Scperciva	# the lines which (a) belong to components we care about, and (b)
2058161748Scperciva	# don't correspond to paths we're explicitly ignoring.
2059161748Scperciva	fetch_filter_metadata INDEX-NEW || return 1
2060161748Scperciva	fetch_filter_metadata INDEX-OLD || return 1
2061161748Scperciva
2062173564Scperciva	# Translate /boot/${KERNCONF} into ${KERNELDIR}
2063173564Scperciva	fetch_filter_kernel_names INDEX-NEW ${KERNCONF}
2064173564Scperciva	fetch_filter_kernel_names INDEX-OLD ${KERNCONF}
2065161748Scperciva
2066161748Scperciva	# For all paths appearing in INDEX-OLD or INDEX-NEW, inspect the
2067161748Scperciva	# system and generate an INDEX-PRESENT file.
2068161748Scperciva	fetch_inspect_system INDEX-OLD INDEX-PRESENT INDEX-NEW || return 1
2069161748Scperciva
2070161748Scperciva	# Based on ${UPDATEIFUNMODIFIED}, remove lines from INDEX-* which
2071161748Scperciva	# correspond to lines in INDEX-PRESENT with hashes not appearing
2072161748Scperciva	# in INDEX-OLD or INDEX-NEW.  Also remove lines where the entry in
2073161748Scperciva	# INDEX-PRESENT has type - and there isn't a corresponding entry in
2074161748Scperciva	# INDEX-OLD with type -.
2075173564Scperciva	fetch_filter_unmodified_notpresent	\
2076173564Scperciva	    INDEX-OLD INDEX-PRESENT INDEX-NEW /dev/null
2077161748Scperciva
2078161748Scperciva	# For each entry in INDEX-PRESENT of type -, remove any corresponding
2079161748Scperciva	# entry from INDEX-NEW if ${ALLOWADD} != "yes".  Remove all entries
2080161748Scperciva	# of type - from INDEX-PRESENT.
2081161748Scperciva	fetch_filter_allowadd INDEX-PRESENT INDEX-NEW
2082161748Scperciva
2083161748Scperciva	# If ${ALLOWDELETE} != "yes", then remove any entries from
2084161748Scperciva	# INDEX-PRESENT which don't correspond to entries in INDEX-NEW.
2085161748Scperciva	fetch_filter_allowdelete INDEX-PRESENT INDEX-NEW
2086161748Scperciva
2087161748Scperciva	# If ${KEEPMODIFIEDMETADATA} == "yes", then for each entry in
2088161748Scperciva	# INDEX-PRESENT with metadata not matching any entry in INDEX-OLD,
2089161748Scperciva	# replace the corresponding line of INDEX-NEW with one having the
2090161748Scperciva	# same metadata as the entry in INDEX-PRESENT.
2091161748Scperciva	fetch_filter_modified_metadata INDEX-OLD INDEX-PRESENT INDEX-NEW
2092161748Scperciva
2093161748Scperciva	# Remove lines from INDEX-PRESENT and INDEX-NEW which are identical;
2094161748Scperciva	# no need to update a file if it isn't changing.
2095161748Scperciva	fetch_filter_uptodate INDEX-PRESENT INDEX-NEW
2096161748Scperciva
2097161748Scperciva	# Prepare to fetch files: Generate a list of the files we need,
2098161748Scperciva	# copy the unmodified files we have into /files/, and generate
2099161748Scperciva	# a list of patches to download.
2100171784Scperciva	fetch_files_prepare INDEX-OLD INDEX-PRESENT INDEX-NEW || return 1
2101161748Scperciva
2102161748Scperciva	# Fetch files.
2103161748Scperciva	fetch_files || return 1
2104161748Scperciva
2105161748Scperciva	# Create and populate install manifest directory; and report what
2106161748Scperciva	# updates are available.
2107161748Scperciva	fetch_create_manifest || return 1
2108161748Scperciva
2109161748Scperciva	# Warn about any upcoming EoL
2110161748Scperciva	fetch_warn_eol || return 1
2111161748Scperciva}
2112161748Scperciva
2113173564Scperciva# If StrictComponents is not "yes", generate a new components list
2114173564Scperciva# with only the components which appear to be installed.
2115173564Scpercivaupgrade_guess_components () {
2116173564Scperciva	if [ "${STRICTCOMPONENTS}" = "no" ]; then
2117173564Scperciva		# Generate filtered INDEX-ALL with only the components listed
2118173564Scperciva		# in COMPONENTS.
2119173564Scperciva		fetch_filter_metadata_components $1 || return 1
2120173564Scperciva
2121173564Scperciva		# Tell the user why his disk is suddenly making lots of noise
2122173564Scperciva		echo -n "Inspecting system... "
2123173564Scperciva
2124173564Scperciva		# Look at the files on disk, and assume that a component is
2125173564Scperciva		# supposed to be present if it is more than half-present.
2126173564Scperciva		cut -f 1-3 -d '|' < INDEX-ALL |
2127173564Scperciva		    tr '|' ' ' |
2128173564Scperciva		    while read C S F; do
2129173564Scperciva			if [ -e ${BASEDIR}/${F} ]; then
2130173564Scperciva				echo "+ ${C}|${S}"
2131173564Scperciva			fi
2132173564Scperciva			echo "= ${C}|${S}"
2133173564Scperciva		    done |
2134173564Scperciva		    sort |
2135173564Scperciva		    uniq -c |
2136173564Scperciva		    sed -E 's,^ +,,' > compfreq
2137173564Scperciva		grep ' = ' compfreq |
2138173564Scperciva		    cut -f 1,3 -d ' ' |
2139173564Scperciva		    sort -k 2,2 -t ' ' > compfreq.total
2140173564Scperciva		grep ' + ' compfreq |
2141173564Scperciva		    cut -f 1,3 -d ' ' |
2142173564Scperciva		    sort -k 2,2 -t ' ' > compfreq.present
2143173564Scperciva		join -t ' ' -1 2 -2 2 compfreq.present compfreq.total |
2144173564Scperciva		    while read S P T; do
2145173564Scperciva			if [ ${P} -gt `expr ${T} / 2` ]; then
2146173564Scperciva				echo ${S}
2147173564Scperciva			fi
2148173564Scperciva		    done > comp.present
2149173564Scperciva		cut -f 2 -d ' ' < compfreq.total > comp.total
2150173564Scperciva		rm INDEX-ALL compfreq compfreq.total compfreq.present
2151173564Scperciva
2152173564Scperciva		# We're done making noise.
2153173564Scperciva		echo "done."
2154173564Scperciva
2155173564Scperciva		# Sometimes the kernel isn't installed where INDEX-ALL
2156173564Scperciva		# thinks that it should be: In particular, it is often in
2157173564Scperciva		# /boot/kernel instead of /boot/GENERIC or /boot/SMP.  To
2158173564Scperciva		# deal with this, if "kernel|X" is listed in comp.total
2159173564Scperciva		# (i.e., is a component which would be upgraded if it is
2160173564Scperciva		# found to be present) we will add it to comp.present.
2161173564Scperciva		# If "kernel|<anything>" is in comp.total but "kernel|X" is
2162173564Scperciva		# not, we print a warning -- the user is running a kernel
2163173564Scperciva		# which isn't part of the release.
2164173564Scperciva		KCOMP=`echo ${KERNCONF} | tr 'A-Z' 'a-z'`
2165173564Scperciva		grep -E "^kernel\|${KCOMP}\$" comp.total >> comp.present
2166173564Scperciva
2167173564Scperciva		if grep -qE "^kernel\|" comp.total &&
2168173564Scperciva		    ! grep -qE "^kernel\|${KCOMP}\$" comp.total; then
2169173564Scperciva			cat <<-EOF
2170173564Scperciva
2171173564ScpercivaWARNING: This system is running a "${KCOMP}" kernel, which is not a
2172173564Scpercivakernel configuration distributed as part of FreeBSD ${RELNUM}.
2173173564ScpercivaThis kernel will not be updated: you MUST update the kernel manually
2174173564Scpercivabefore running "$0 install".
2175173564Scperciva			EOF
2176173564Scperciva		fi
2177173564Scperciva
2178173564Scperciva		# Re-sort the list of installed components and generate
2179173564Scperciva		# the list of non-installed components.
2180173564Scperciva		sort -u < comp.present > comp.present.tmp
2181173564Scperciva		mv comp.present.tmp comp.present
2182173564Scperciva		comm -13 comp.present comp.total > comp.absent
2183173564Scperciva
2184173564Scperciva		# Ask the user to confirm that what we have is correct.  To
2185173564Scperciva		# reduce user confusion, translate "X|Y" back to "X/Y" (as
2186173564Scperciva		# subcomponents must be listed in the configuration file).
2187173564Scperciva		echo
2188173564Scperciva		echo -n "The following components of FreeBSD "
2189173564Scperciva		echo "seem to be installed:"
2190173564Scperciva		tr '|' '/' < comp.present |
2191173564Scperciva		    fmt -72
2192173564Scperciva		echo
2193173564Scperciva		echo -n "The following components of FreeBSD "
2194173564Scperciva		echo "do not seem to be installed:"
2195173564Scperciva		tr '|' '/' < comp.absent |
2196173564Scperciva		    fmt -72
2197173564Scperciva		echo
2198173564Scperciva		continuep || return 1
2199173564Scperciva		echo
2200173564Scperciva
2201173564Scperciva		# Suck the generated list of components into ${COMPONENTS}.
2202173564Scperciva		# Note that comp.present.tmp is used due to issues with
2203173564Scperciva		# pipelines and setting variables.
2204173564Scperciva		COMPONENTS=""
2205173564Scperciva		tr '|' '/' < comp.present > comp.present.tmp
2206173564Scperciva		while read C; do
2207173564Scperciva			COMPONENTS="${COMPONENTS} ${C}"
2208173564Scperciva		done < comp.present.tmp
2209173564Scperciva
2210173564Scperciva		# Delete temporary files
2211173564Scperciva		rm comp.present comp.present.tmp comp.absent comp.total
2212173564Scperciva	fi
2213173564Scperciva}
2214173564Scperciva
2215173564Scperciva# If StrictComponents is not "yes", COMPONENTS contains an entry
2216173564Scperciva# corresponding to the currently running kernel, and said kernel
2217173564Scperciva# does not exist in the new release, add "kernel/generic" to the
2218173564Scperciva# list of components.
2219173564Scpercivaupgrade_guess_new_kernel () {
2220173564Scperciva	if [ "${STRICTCOMPONENTS}" = "no" ]; then
2221173564Scperciva		# Grab the unfiltered metadata file.
2222173564Scperciva		METAHASH=`look "$1|" tINDEX.present | cut -f 2 -d '|'`
2223173564Scperciva		gunzip -c < files/${METAHASH}.gz > $1.all
2224173564Scperciva
2225173564Scperciva		# If "kernel/${KCOMP}" is in ${COMPONENTS} and that component
2226173564Scperciva		# isn't in $1.all, we need to add kernel/generic.
2227173564Scperciva		for C in ${COMPONENTS}; do
2228173564Scperciva			if [ ${C} = "kernel/${KCOMP}" ] &&
2229173564Scperciva			    ! grep -qE "^kernel\|${KCOMP}\|" $1.all; then
2230173564Scperciva				COMPONENTS="${COMPONENTS} kernel/generic"
2231173564Scperciva				NKERNCONF="GENERIC"
2232173564Scperciva				cat <<-EOF
2233173564Scperciva
2234173564ScpercivaWARNING: This system is running a "${KCOMP}" kernel, which is not a
2235173564Scpercivakernel configuration distributed as part of FreeBSD ${RELNUM}.
2236173564ScpercivaAs part of upgrading to FreeBSD ${RELNUM}, this kernel will be
2237173564Scpercivareplaced with a "generic" kernel.
2238173564Scperciva				EOF
2239173564Scperciva				continuep || return 1
2240173564Scperciva			fi
2241173564Scperciva		done
2242173564Scperciva
2243173564Scperciva		# Don't need this any more...
2244173564Scperciva		rm $1.all
2245173564Scperciva	fi
2246173564Scperciva}
2247173564Scperciva
2248173564Scperciva# Convert INDEX-OLD (last release) and INDEX-ALL (new release) into
2249173564Scperciva# INDEX-OLD and INDEX-NEW files (in the sense of normal upgrades).
2250173564Scpercivaupgrade_oldall_to_oldnew () {
2251173564Scperciva	# For each ${F}|... which appears in INDEX-ALL but does not appear
2252173564Scperciva	# in INDEX-OLD, add ${F}|-|||||| to INDEX-OLD.
2253173564Scperciva	cut -f 1 -d '|' < $1 |
2254173564Scperciva	    sort -u > $1.paths
2255173564Scperciva	cut -f 1 -d '|' < $2 |
2256173564Scperciva	    sort -u |
2257173564Scperciva	    comm -13 $1.paths - |
2258173564Scperciva	    lam - -s "|-||||||" |
2259173564Scperciva	    sort - $1 > $1.tmp
2260173564Scperciva	mv $1.tmp $1
2261173564Scperciva
2262173564Scperciva	# Remove lines from INDEX-OLD which also appear in INDEX-ALL
2263173564Scperciva	comm -23 $1 $2 > $1.tmp
2264173564Scperciva	mv $1.tmp $1
2265173564Scperciva
2266173564Scperciva	# Remove lines from INDEX-ALL which have a file name not appearing
2267173564Scperciva	# anywhere in INDEX-OLD (since these must be files which haven't
2268173564Scperciva	# changed -- if they were new, there would be an entry of type "-").
2269173564Scperciva	cut -f 1 -d '|' < $1 |
2270173564Scperciva	    sort -u > $1.paths
2271173564Scperciva	sort -k 1,1 -t '|' < $2 |
2272173564Scperciva	    join -t '|' - $1.paths |
2273173564Scperciva	    sort > $2.tmp
2274173564Scperciva	rm $1.paths
2275173564Scperciva	mv $2.tmp $2
2276173564Scperciva
2277173564Scperciva	# Rename INDEX-ALL to INDEX-NEW.
2278173564Scperciva	mv $2 $3
2279173564Scperciva}
2280173564Scperciva
2281221780Scperciva# Helper for upgrade_merge: Return zero true iff the two files differ only
2282221780Scperciva# in the contents of their $FreeBSD$ tags.
2283221780Scpercivasamef () {
2284221780Scperciva	X=`sed -E 's/\\$FreeBSD.*\\$/\$FreeBSD\$/' < $1 | ${SHA256}`
2285221780Scperciva	Y=`sed -E 's/\\$FreeBSD.*\\$/\$FreeBSD\$/' < $2 | ${SHA256}`
2286221780Scperciva
2287221780Scperciva	if [ $X = $Y ]; then
2288221780Scperciva		return 0;
2289221780Scperciva	else
2290221780Scperciva		return 1;
2291221780Scperciva	fi
2292221780Scperciva}
2293221780Scperciva
2294173564Scperciva# From the list of "old" files in $1, merge changes in $2 with those in $3,
2295173564Scperciva# and update $3 to reflect the hashes of merged files.
2296173564Scpercivaupgrade_merge () {
2297173564Scperciva	# We only need to do anything if $1 is non-empty.
2298173564Scperciva	if [ -s $1 ]; then
2299173564Scperciva		cut -f 1 -d '|' $1 |
2300173564Scperciva		    sort > $1-paths
2301173564Scperciva
2302173564Scperciva		# Create staging area for merging files
2303173564Scperciva		rm -rf merge/
2304173564Scperciva		while read F; do
2305173564Scperciva			D=`dirname ${F}`
2306173564Scperciva			mkdir -p merge/old/${D}
2307173564Scperciva			mkdir -p merge/${OLDRELNUM}/${D}
2308173564Scperciva			mkdir -p merge/${RELNUM}/${D}
2309173564Scperciva			mkdir -p merge/new/${D}
2310173564Scperciva		done < $1-paths
2311173564Scperciva
2312173564Scperciva		# Copy in files
2313173564Scperciva		while read F; do
2314173564Scperciva			# Currently installed file
2315173564Scperciva			V=`look "${F}|" $2 | cut -f 7 -d '|'`
2316173564Scperciva			gunzip < files/${V}.gz > merge/old/${F}
2317173564Scperciva
2318173564Scperciva			# Old release
2319173564Scperciva			if look "${F}|" $1 | fgrep -q "|f|"; then
2320173564Scperciva				V=`look "${F}|" $1 | cut -f 3 -d '|'`
2321173564Scperciva				gunzip < files/${V}.gz		\
2322173564Scperciva				    > merge/${OLDRELNUM}/${F}
2323173564Scperciva			fi
2324173564Scperciva
2325173564Scperciva			# New release
2326173564Scperciva			if look "${F}|" $3 | cut -f 1,2,7 -d '|' |
2327173564Scperciva			    fgrep -q "|f|"; then
2328173564Scperciva				V=`look "${F}|" $3 | cut -f 7 -d '|'`
2329173564Scperciva				gunzip < files/${V}.gz		\
2330173564Scperciva				    > merge/${RELNUM}/${F}
2331173564Scperciva			fi
2332173564Scperciva		done < $1-paths
2333173564Scperciva
2334173564Scperciva		# Attempt to automatically merge changes
2335173564Scperciva		echo -n "Attempting to automatically merge "
2336173564Scperciva		echo -n "changes in files..."
2337173564Scperciva		: > failed.merges
2338173564Scperciva		while read F; do
2339173564Scperciva			# If the file doesn't exist in the new release,
2340173564Scperciva			# the result of "merging changes" is having the file
2341173564Scperciva			# not exist.
2342173564Scperciva			if ! [ -f merge/${RELNUM}/${F} ]; then
2343173564Scperciva				continue
2344173564Scperciva			fi
2345173564Scperciva
2346173564Scperciva			# If the file didn't exist in the old release, we're
2347173564Scperciva			# going to throw away the existing file and hope that
2348173564Scperciva			# the version from the new release is what we want.
2349173564Scperciva			if ! [ -f merge/${OLDRELNUM}/${F} ]; then
2350173564Scperciva				cp merge/${RELNUM}/${F} merge/new/${F}
2351173564Scperciva				continue
2352173564Scperciva			fi
2353173564Scperciva
2354173564Scperciva			# Some files need special treatment.
2355173564Scperciva			case ${F} in
2356173564Scperciva			/etc/spwd.db | /etc/pwd.db | /etc/login.conf.db)
2357173564Scperciva				# Don't merge these -- we're rebuild them
2358173564Scperciva				# after updates are installed.
2359173564Scperciva				cp merge/old/${F} merge/new/${F}
2360173564Scperciva				;;
2361173564Scperciva			*)
2362173564Scperciva				if ! merge -p -L "current version"	\
2363173564Scperciva				    -L "${OLDRELNUM}" -L "${RELNUM}"	\
2364173564Scperciva				    merge/old/${F}			\
2365173564Scperciva				    merge/${OLDRELNUM}/${F}		\
2366173564Scperciva				    merge/${RELNUM}/${F}		\
2367173564Scperciva				    > merge/new/${F} 2>/dev/null; then
2368173564Scperciva					echo ${F} >> failed.merges
2369173564Scperciva				fi
2370173564Scperciva				;;
2371173564Scperciva			esac
2372173564Scperciva		done < $1-paths
2373173564Scperciva		echo " done."
2374173564Scperciva
2375173564Scperciva		# Ask the user to handle any files which didn't merge.
2376173564Scperciva		while read F; do
2377221780Scperciva			# If the installed file differs from the version in
2378221780Scperciva			# the old release only due to $FreeBSD$ tag expansion
2379221780Scperciva			# then just use the version in the new release.
2380221780Scperciva			if samef merge/old/${F} merge/${OLDRELNUM}/${F}; then
2381221780Scperciva				cp merge/${RELNUM}/${F} merge/new/${F}
2382221780Scperciva				continue
2383221780Scperciva			fi
2384221780Scperciva
2385173564Scperciva			cat <<-EOF
2386173564Scperciva
2387173564ScpercivaThe following file could not be merged automatically: ${F}
2388173564ScpercivaPress Enter to edit this file in ${EDITOR} and resolve the conflicts
2389173564Scpercivamanually...
2390173564Scperciva			EOF
2391173564Scperciva			read dummy </dev/tty
2392173564Scperciva			${EDITOR} `pwd`/merge/new/${F} < /dev/tty
2393173564Scperciva		done < failed.merges
2394173564Scperciva		rm failed.merges
2395173564Scperciva
2396173564Scperciva		# Ask the user to confirm that he likes how the result
2397173564Scperciva		# of merging files.
2398173564Scperciva		while read F; do
2399221780Scperciva			# Skip files which haven't changed except possibly
2400221780Scperciva			# in their $FreeBSD$ tags.
2401221780Scperciva			if [ -f merge/old/${F} ] && [ -f merge/new/${F} ] &&
2402221780Scperciva			    samef merge/old/${F} merge/new/${F}; then
2403173564Scperciva				continue
2404173564Scperciva			fi
2405173564Scperciva
2406221780Scperciva			# Skip files where the installed file differs from
2407221780Scperciva			# the old file only due to $FreeBSD$ tags.
2408221780Scperciva			if [ -f merge/old/${F} ] &&
2409221780Scperciva			    [ -f merge/${OLDRELNUM}/${F} ] &&
2410221780Scperciva			    samef merge/old/${F} merge/${OLDRELNUM}/${F}; then
2411221780Scperciva				continue
2412221780Scperciva			fi
2413221780Scperciva
2414173564Scperciva			# Warn about files which are ceasing to exist.
2415173564Scperciva			if ! [ -f merge/new/${F} ]; then
2416173564Scperciva				cat <<-EOF
2417173564Scperciva
2418173564ScpercivaThe following file will be removed, as it no longer exists in
2419173564ScpercivaFreeBSD ${RELNUM}: ${F}
2420173564Scperciva				EOF
2421173564Scperciva				continuep < /dev/tty || return 1
2422173564Scperciva				continue
2423173564Scperciva			fi
2424173564Scperciva
2425173564Scperciva			# Print changes for the user's approval.
2426173564Scperciva			cat <<-EOF
2427173564Scperciva
2428173564ScpercivaThe following changes, which occurred between FreeBSD ${OLDRELNUM} and
2429173564ScpercivaFreeBSD ${RELNUM} have been merged into ${F}:
2430173564ScpercivaEOF
2431173564Scperciva			diff -U 5 -L "current version" -L "new version"	\
2432173564Scperciva			    merge/old/${F} merge/new/${F} || true
2433173564Scperciva			continuep < /dev/tty || return 1
2434173564Scperciva		done < $1-paths
2435173564Scperciva
2436173564Scperciva		# Store merged files.
2437173564Scperciva		while read F; do
2438177527Scperciva			if [ -f merge/new/${F} ]; then
2439177527Scperciva				V=`${SHA256} -q merge/new/${F}`
2440173564Scperciva
2441173564Scperciva				gzip -c < merge/new/${F} > files/${V}.gz
2442173564Scperciva				echo "${F}|${V}"
2443173564Scperciva			fi
2444173564Scperciva		done < $1-paths > newhashes
2445173564Scperciva
2446173564Scperciva		# Pull lines out from $3 which need to be updated to
2447173564Scperciva		# reflect merged files.
2448173564Scperciva		while read F; do
2449173564Scperciva			look "${F}|" $3
2450173564Scperciva		done < $1-paths > $3-oldlines
2451173564Scperciva
2452173564Scperciva		# Update lines to reflect merged files
2453173564Scperciva		join -t '|' -o 1.1,1.2,1.3,1.4,1.5,1.6,2.2,1.8		\
2454173564Scperciva		    $3-oldlines newhashes > $3-newlines
2455173564Scperciva
2456173564Scperciva		# Remove old lines from $3 and add new lines.
2457173564Scperciva		sort $3-oldlines |
2458173564Scperciva		    comm -13 - $3 |
2459173564Scperciva		    sort - $3-newlines > $3.tmp
2460173564Scperciva		mv $3.tmp $3
2461173564Scperciva
2462173564Scperciva		# Clean up
2463173564Scperciva		rm $1-paths newhashes $3-oldlines $3-newlines
2464173564Scperciva		rm -rf merge/
2465173564Scperciva	fi
2466173564Scperciva
2467173564Scperciva	# We're done with merging files.
2468173564Scperciva	rm $1
2469173564Scperciva}
2470173564Scperciva
2471173564Scperciva# Do the work involved in fetching upgrades to a new release
2472173564Scpercivaupgrade_run () {
2473173564Scperciva	workdir_init || return 1
2474173564Scperciva
2475173564Scperciva	# Prepare the mirror list.
2476173564Scperciva	fetch_pick_server_init && fetch_pick_server
2477173564Scperciva
2478173564Scperciva	# Try to fetch the public key until we run out of servers.
2479173564Scperciva	while ! fetch_key; do
2480173564Scperciva		fetch_pick_server || return 1
2481173564Scperciva	done
2482173564Scperciva 
2483173564Scperciva	# Try to fetch the metadata index signature ("tag") until we run
2484173564Scperciva	# out of available servers; and sanity check the downloaded tag.
2485173564Scperciva	while ! fetch_tag; do
2486173564Scperciva		fetch_pick_server || return 1
2487173564Scperciva	done
2488173564Scperciva	fetch_tagsanity || return 1
2489173564Scperciva
2490173564Scperciva	# Fetch the INDEX-OLD and INDEX-ALL.
2491173564Scperciva	fetch_metadata INDEX-OLD INDEX-ALL || return 1
2492173564Scperciva
2493173564Scperciva	# If StrictComponents is not "yes", generate a new components list
2494173564Scperciva	# with only the components which appear to be installed.
2495173564Scperciva	upgrade_guess_components INDEX-ALL || return 1
2496173564Scperciva
2497173564Scperciva	# Generate filtered INDEX-OLD and INDEX-ALL files containing only
2498173564Scperciva	# the components we want and without anything marked as "Ignore".
2499173564Scperciva	fetch_filter_metadata INDEX-OLD || return 1
2500173564Scperciva	fetch_filter_metadata INDEX-ALL || return 1
2501173564Scperciva
2502173564Scperciva	# Merge the INDEX-OLD and INDEX-ALL files into INDEX-OLD.
2503173564Scperciva	sort INDEX-OLD INDEX-ALL > INDEX-OLD.tmp
2504173564Scperciva	mv INDEX-OLD.tmp INDEX-OLD
2505173564Scperciva	rm INDEX-ALL
2506173564Scperciva
2507173564Scperciva	# Adjust variables for fetching files from the new release.
2508173564Scperciva	OLDRELNUM=${RELNUM}
2509173564Scperciva	RELNUM=${TARGETRELEASE}
2510173564Scperciva	OLDFETCHDIR=${FETCHDIR}
2511173564Scperciva	FETCHDIR=${RELNUM}/${ARCH}
2512173564Scperciva
2513173564Scperciva	# Try to fetch the NEW metadata index signature ("tag") until we run
2514173564Scperciva	# out of available servers; and sanity check the downloaded tag.
2515173564Scperciva	while ! fetch_tag; do
2516173564Scperciva		fetch_pick_server || return 1
2517173564Scperciva	done
2518173564Scperciva
2519173564Scperciva	# Fetch the new INDEX-ALL.
2520173564Scperciva	fetch_metadata INDEX-ALL || return 1
2521173564Scperciva
2522173564Scperciva	# If StrictComponents is not "yes", COMPONENTS contains an entry
2523173564Scperciva	# corresponding to the currently running kernel, and said kernel
2524173564Scperciva	# does not exist in the new release, add "kernel/generic" to the
2525173564Scperciva	# list of components.
2526173564Scperciva	upgrade_guess_new_kernel INDEX-ALL || return 1
2527173564Scperciva
2528173564Scperciva	# Filter INDEX-ALL to contain only the components we want and without
2529173564Scperciva	# anything marked as "Ignore".
2530173564Scperciva	fetch_filter_metadata INDEX-ALL || return 1
2531173564Scperciva
2532173564Scperciva	# Convert INDEX-OLD (last release) and INDEX-ALL (new release) into
2533173564Scperciva	# INDEX-OLD and INDEX-NEW files (in the sense of normal upgrades).
2534173564Scperciva	upgrade_oldall_to_oldnew INDEX-OLD INDEX-ALL INDEX-NEW
2535173564Scperciva
2536173564Scperciva	# Translate /boot/${KERNCONF} or /boot/${NKERNCONF} into ${KERNELDIR}
2537173564Scperciva	fetch_filter_kernel_names INDEX-NEW ${NKERNCONF}
2538173564Scperciva	fetch_filter_kernel_names INDEX-OLD ${KERNCONF}
2539173564Scperciva
2540173564Scperciva	# For all paths appearing in INDEX-OLD or INDEX-NEW, inspect the
2541173564Scperciva	# system and generate an INDEX-PRESENT file.
2542173564Scperciva	fetch_inspect_system INDEX-OLD INDEX-PRESENT INDEX-NEW || return 1
2543173564Scperciva
2544173564Scperciva	# Based on ${MERGECHANGES}, generate a file tomerge-old with the
2545173564Scperciva	# paths and hashes of old versions of files to merge.
2546173564Scperciva	fetch_filter_mergechanges INDEX-OLD INDEX-PRESENT tomerge-old
2547173564Scperciva
2548173564Scperciva	# Based on ${UPDATEIFUNMODIFIED}, remove lines from INDEX-* which
2549173564Scperciva	# correspond to lines in INDEX-PRESENT with hashes not appearing
2550173564Scperciva	# in INDEX-OLD or INDEX-NEW.  Also remove lines where the entry in
2551173564Scperciva	# INDEX-PRESENT has type - and there isn't a corresponding entry in
2552173564Scperciva	# INDEX-OLD with type -.
2553173564Scperciva	fetch_filter_unmodified_notpresent	\
2554173564Scperciva	    INDEX-OLD INDEX-PRESENT INDEX-NEW tomerge-old
2555173564Scperciva
2556173564Scperciva	# For each entry in INDEX-PRESENT of type -, remove any corresponding
2557173564Scperciva	# entry from INDEX-NEW if ${ALLOWADD} != "yes".  Remove all entries
2558173564Scperciva	# of type - from INDEX-PRESENT.
2559173564Scperciva	fetch_filter_allowadd INDEX-PRESENT INDEX-NEW
2560173564Scperciva
2561173564Scperciva	# If ${ALLOWDELETE} != "yes", then remove any entries from
2562173564Scperciva	# INDEX-PRESENT which don't correspond to entries in INDEX-NEW.
2563173564Scperciva	fetch_filter_allowdelete INDEX-PRESENT INDEX-NEW
2564173564Scperciva
2565173564Scperciva	# If ${KEEPMODIFIEDMETADATA} == "yes", then for each entry in
2566173564Scperciva	# INDEX-PRESENT with metadata not matching any entry in INDEX-OLD,
2567173564Scperciva	# replace the corresponding line of INDEX-NEW with one having the
2568173564Scperciva	# same metadata as the entry in INDEX-PRESENT.
2569173564Scperciva	fetch_filter_modified_metadata INDEX-OLD INDEX-PRESENT INDEX-NEW
2570173564Scperciva
2571173564Scperciva	# Remove lines from INDEX-PRESENT and INDEX-NEW which are identical;
2572173564Scperciva	# no need to update a file if it isn't changing.
2573173564Scperciva	fetch_filter_uptodate INDEX-PRESENT INDEX-NEW
2574173564Scperciva
2575173564Scperciva	# Fetch "clean" files from the old release for merging changes.
2576173564Scperciva	fetch_files_premerge tomerge-old
2577173564Scperciva
2578173564Scperciva	# Prepare to fetch files: Generate a list of the files we need,
2579173564Scperciva	# copy the unmodified files we have into /files/, and generate
2580173564Scperciva	# a list of patches to download.
2581173564Scperciva	fetch_files_prepare INDEX-OLD INDEX-PRESENT INDEX-NEW || return 1
2582173564Scperciva
2583173564Scperciva	# Fetch patches from to-${RELNUM}/${ARCH}/bp/
2584173564Scperciva	PATCHDIR=to-${RELNUM}/${ARCH}/bp
2585173564Scperciva	fetch_files || return 1
2586173564Scperciva
2587173564Scperciva	# Merge configuration file changes.
2588173564Scperciva	upgrade_merge tomerge-old INDEX-PRESENT INDEX-NEW || return 1
2589173564Scperciva
2590173564Scperciva	# Create and populate install manifest directory; and report what
2591173564Scperciva	# updates are available.
2592173564Scperciva	fetch_create_manifest || return 1
2593173564Scperciva
2594173564Scperciva	# Leave a note behind to tell the "install" command that the kernel
2595173564Scperciva	# needs to be installed before the world.
2596173564Scperciva	touch ${BDHASH}-install/kernelfirst
2597212431Scperciva
2598212431Scperciva	# Remind the user that they need to run "freebsd-update install"
2599212431Scperciva	# to install the downloaded bits, in case they didn't RTFM.
2600212431Scperciva	echo "To install the downloaded upgrades, run \"$0 install\"."
2601173564Scperciva}
2602173564Scperciva
2603161748Scperciva# Make sure that all the file hashes mentioned in $@ have corresponding
2604161748Scperciva# gzipped files stored in /files/.
2605161748Scpercivainstall_verify () {
2606161748Scperciva	# Generate a list of hashes
2607161748Scperciva	cat $@ |
2608161748Scperciva	    cut -f 2,7 -d '|' |
2609161748Scperciva	    grep -E '^f' |
2610161748Scperciva	    cut -f 2 -d '|' |
2611161748Scperciva	    sort -u > filelist
2612161748Scperciva
2613161748Scperciva	# Make sure all the hashes exist
2614161748Scperciva	while read HASH; do
2615161748Scperciva		if ! [ -f files/${HASH}.gz ]; then
2616161748Scperciva			echo -n "Update files missing -- "
2617161748Scperciva			echo "this should never happen."
2618161748Scperciva			echo "Re-run '$0 fetch'."
2619161748Scperciva			return 1
2620161748Scperciva		fi
2621161748Scperciva	done < filelist
2622161748Scperciva
2623161748Scperciva	# Clean up
2624161748Scperciva	rm filelist
2625161748Scperciva}
2626161748Scperciva
2627161748Scperciva# Remove the system immutable flag from files
2628161748Scpercivainstall_unschg () {
2629161748Scperciva	# Generate file list
2630161748Scperciva	cat $@ |
2631161748Scperciva	    cut -f 1 -d '|' > filelist
2632161748Scperciva
2633161748Scperciva	# Remove flags
2634161748Scperciva	while read F; do
2635169603Scperciva		if ! [ -e ${BASEDIR}/${F} ]; then
2636161748Scperciva			continue
2637161748Scperciva		fi
2638161748Scperciva
2639169603Scperciva		chflags noschg ${BASEDIR}/${F} || return 1
2640161748Scperciva	done < filelist
2641161748Scperciva
2642161748Scperciva	# Clean up
2643161748Scperciva	rm filelist
2644161748Scperciva}
2645161748Scperciva
2646196392Ssimon# Decide which directory name to use for kernel backups.
2647196392Ssimonbackup_kernel_finddir () {
2648196392Ssimon	CNT=0
2649196392Ssimon	while true ; do
2650196392Ssimon		# Pathname does not exist, so it is OK use that name
2651196392Ssimon		# for backup directory.
2652196392Ssimon		if [ ! -e $BACKUPKERNELDIR ]; then
2653196392Ssimon			return 0
2654196392Ssimon		fi
2655196392Ssimon
2656196392Ssimon		# If directory do exist, we only use if it has our
2657196392Ssimon		# marker file.
2658196392Ssimon		if [ -d $BACKUPKERNELDIR -a \
2659196392Ssimon			-e $BACKUPKERNELDIR/.freebsd-update ]; then
2660196392Ssimon			return 0
2661196392Ssimon		fi
2662196392Ssimon
2663196392Ssimon		# We could not use current directory name, so add counter to
2664196392Ssimon		# the end and try again.
2665196392Ssimon		CNT=$((CNT + 1))
2666196392Ssimon		if [ $CNT -gt 9 ]; then
2667196392Ssimon			echo "Could not find valid backup dir ($BACKUPKERNELDIR)"
2668196392Ssimon			exit 1
2669196392Ssimon		fi
2670196392Ssimon		BACKUPKERNELDIR="`echo $BACKUPKERNELDIR | sed -Ee 's/[0-9]\$//'`"
2671196392Ssimon		BACKUPKERNELDIR="${BACKUPKERNELDIR}${CNT}"
2672196392Ssimon	done
2673196392Ssimon}
2674196392Ssimon
2675196392Ssimon# Backup the current kernel using hardlinks, if not disabled by user.
2676196392Ssimon# Since we delete all files in the directory used for previous backups
2677196392Ssimon# we create a marker file called ".freebsd-update" in the directory so
2678196392Ssimon# we can determine on the next run that the directory was created by
2679196392Ssimon# freebsd-update and we then do not accidentally remove user files in
2680196392Ssimon# the unlikely case that the user has created a directory with a
2681196392Ssimon# conflicting name.
2682196392Ssimonbackup_kernel () {
2683196392Ssimon	# Only make kernel backup is so configured.
2684196392Ssimon	if [ $BACKUPKERNEL != yes ]; then
2685196392Ssimon		return 0
2686196392Ssimon	fi
2687196392Ssimon
2688196392Ssimon	# Decide which directory name to use for kernel backups.
2689196392Ssimon	backup_kernel_finddir
2690196392Ssimon
2691196392Ssimon	# Remove old kernel backup files.  If $BACKUPKERNELDIR was
2692196392Ssimon	# "not ours", backup_kernel_finddir would have exited, so
2693196392Ssimon	# deleting the directory content is as safe as we can make it.
2694196392Ssimon	if [ -d $BACKUPKERNELDIR ]; then
2695212505Sjh		rm -fr $BACKUPKERNELDIR
2696196392Ssimon	fi
2697196392Ssimon
2698212505Sjh	# Create directories for backup.
2699196392Ssimon	mkdir -p $BACKUPKERNELDIR
2700212505Sjh	mtree -cdn -p "${KERNELDIR}" | \
2701212505Sjh	    mtree -Ue -p "${BACKUPKERNELDIR}" > /dev/null
2702196392Ssimon
2703196392Ssimon	# Mark the directory as having been created by freebsd-update.
2704196392Ssimon	touch $BACKUPKERNELDIR/.freebsd-update
2705196392Ssimon	if [ $? -ne 0 ]; then
2706196392Ssimon		echo "Could not create kernel backup directory"
2707196392Ssimon		exit 1
2708196392Ssimon	fi
2709196392Ssimon
2710196392Ssimon	# Disable pathname expansion to be sure *.symbols is not
2711196392Ssimon	# expanded.
2712196392Ssimon	set -f
2713196392Ssimon
2714196392Ssimon	# Use find to ignore symbol files, unless disabled by user.
2715196392Ssimon	if [ $BACKUPKERNELSYMBOLFILES = yes ]; then
2716196392Ssimon		FINDFILTER=""
2717196392Ssimon	else
2718196392Ssimon		FINDFILTER=-"a ! -name *.symbols"
2719196392Ssimon	fi
2720196392Ssimon
2721196392Ssimon	# Backup all the kernel files using hardlinks.
2722212505Sjh	(cd $KERNELDIR && find . -type f $FINDFILTER -exec \
2723212505Sjh	    cp -pl '{}' ${BACKUPKERNELDIR}/'{}' \;)
2724196392Ssimon
2725196392Ssimon	# Re-enable patchname expansion.
2726196392Ssimon	set +f
2727196392Ssimon}
2728196392Ssimon
2729161748Scperciva# Install new files
2730161748Scpercivainstall_from_index () {
2731161748Scperciva	# First pass: Do everything apart from setting file flags.  We
2732161748Scperciva	# can't set flags yet, because schg inhibits hard linking.
2733161748Scperciva	sort -k 1,1 -t '|' $1 |
2734161748Scperciva	    tr '|' ' ' |
2735161748Scperciva	    while read FPATH TYPE OWNER GROUP PERM FLAGS HASH LINK; do
2736161748Scperciva		case ${TYPE} in
2737161748Scperciva		d)
2738161748Scperciva			# Create a directory
2739161748Scperciva			install -d -o ${OWNER} -g ${GROUP}		\
2740161748Scperciva			    -m ${PERM} ${BASEDIR}/${FPATH}
2741161748Scperciva			;;
2742161748Scperciva		f)
2743161748Scperciva			if [ -z "${LINK}" ]; then
2744161748Scperciva				# Create a file, without setting flags.
2745161748Scperciva				gunzip < files/${HASH}.gz > ${HASH}
2746161748Scperciva				install -S -o ${OWNER} -g ${GROUP}	\
2747161748Scperciva				    -m ${PERM} ${HASH} ${BASEDIR}/${FPATH}
2748161748Scperciva				rm ${HASH}
2749161748Scperciva			else
2750161748Scperciva				# Create a hard link.
2751169603Scperciva				ln -f ${BASEDIR}/${LINK} ${BASEDIR}/${FPATH}
2752161748Scperciva			fi
2753161748Scperciva			;;
2754161748Scperciva		L)
2755161748Scperciva			# Create a symlink
2756161748Scperciva			ln -sfh ${HASH} ${BASEDIR}/${FPATH}
2757161748Scperciva			;;
2758161748Scperciva		esac
2759161748Scperciva	    done
2760161748Scperciva
2761161748Scperciva	# Perform a second pass, adding file flags.
2762161748Scperciva	tr '|' ' ' < $1 |
2763161748Scperciva	    while read FPATH TYPE OWNER GROUP PERM FLAGS HASH LINK; do
2764161748Scperciva		if [ ${TYPE} = "f" ] &&
2765161748Scperciva		    ! [ ${FLAGS} = "0" ]; then
2766161748Scperciva			chflags ${FLAGS} ${BASEDIR}/${FPATH}
2767161748Scperciva		fi
2768161748Scperciva	    done
2769161748Scperciva}
2770161748Scperciva
2771161748Scperciva# Remove files which we want to delete
2772161748Scpercivainstall_delete () {
2773161748Scperciva	# Generate list of new files
2774161748Scperciva	cut -f 1 -d '|' < $2 |
2775161748Scperciva	    sort > newfiles
2776161748Scperciva
2777161748Scperciva	# Generate subindex of old files we want to nuke
2778161748Scperciva	sort -k 1,1 -t '|' $1 |
2779161748Scperciva	    join -t '|' -v 1 - newfiles |
2780164600Scperciva	    sort -r -k 1,1 -t '|' |
2781161748Scperciva	    cut -f 1,2 -d '|' |
2782161748Scperciva	    tr '|' ' ' > killfiles
2783161748Scperciva
2784161748Scperciva	# Remove the offending bits
2785161748Scperciva	while read FPATH TYPE; do
2786161748Scperciva		case ${TYPE} in
2787161748Scperciva		d)
2788161748Scperciva			rmdir ${BASEDIR}/${FPATH}
2789161748Scperciva			;;
2790161748Scperciva		f)
2791161748Scperciva			rm ${BASEDIR}/${FPATH}
2792161748Scperciva			;;
2793161748Scperciva		L)
2794161748Scperciva			rm ${BASEDIR}/${FPATH}
2795161748Scperciva			;;
2796161748Scperciva		esac
2797161748Scperciva	done < killfiles
2798161748Scperciva
2799161748Scperciva	# Clean up
2800161748Scperciva	rm newfiles killfiles
2801161748Scperciva}
2802161748Scperciva
2803173564Scperciva# Install new files, delete old files, and update linker.hints
2804173564Scpercivainstall_files () {
2805173564Scperciva	# If we haven't already dealt with the kernel, deal with it.
2806173564Scperciva	if ! [ -f $1/kerneldone ]; then
2807173564Scperciva		grep -E '^/boot/' $1/INDEX-OLD > INDEX-OLD
2808173564Scperciva		grep -E '^/boot/' $1/INDEX-NEW > INDEX-NEW
2809173564Scperciva
2810196392Ssimon		# Backup current kernel before installing a new one
2811196392Ssimon		backup_kernel || return 1
2812196392Ssimon
2813173564Scperciva		# Install new files
2814173564Scperciva		install_from_index INDEX-NEW || return 1
2815173564Scperciva
2816173564Scperciva		# Remove files which need to be deleted
2817173564Scperciva		install_delete INDEX-OLD INDEX-NEW || return 1
2818173564Scperciva
2819173564Scperciva		# Update linker.hints if necessary
2820173564Scperciva		if [ -s INDEX-OLD -o -s INDEX-NEW ]; then
2821173564Scperciva			kldxref -R /boot/ 2>/dev/null
2822173564Scperciva		fi
2823173564Scperciva
2824173564Scperciva		# We've finished updating the kernel.
2825173564Scperciva		touch $1/kerneldone
2826173564Scperciva
2827173564Scperciva		# Do we need to ask for a reboot now?
2828173564Scperciva		if [ -f $1/kernelfirst ] &&
2829173564Scperciva		    [ -s INDEX-OLD -o -s INDEX-NEW ]; then
2830173564Scperciva			cat <<-EOF
2831173564Scperciva
2832173564ScpercivaKernel updates have been installed.  Please reboot and run
2833173564Scperciva"$0 install" again to finish installing updates.
2834173564Scperciva			EOF
2835173564Scperciva			exit 0
2836173564Scperciva		fi
2837161748Scperciva	fi
2838173564Scperciva
2839173564Scperciva	# If we haven't already dealt with the world, deal with it.
2840173564Scperciva	if ! [ -f $1/worlddone ]; then
2841257192Sdelphij		# Create any necessary directories first
2842257192Sdelphij		grep -vE '^/boot/' $1/INDEX-NEW |
2843257192Sdelphij		    grep -E '^[^|]+\|d\|' > INDEX-NEW
2844257192Sdelphij		install_from_index INDEX-NEW || return 1
2845257192Sdelphij
2846279265Sdelphij		# Install new runtime linker
2847279265Sdelphij		grep -vE '^/boot/' $1/INDEX-NEW |
2848279265Sdelphij		    grep -vE '^[^|]+\|d\|' |
2849279265Sdelphij		    grep -E '^/libexec/ld-elf[^|]*\.so\.[0-9]+\|' > INDEX-NEW
2850279265Sdelphij		install_from_index INDEX-NEW || return 1
2851279265Sdelphij
2852173564Scperciva		# Install new shared libraries next
2853173564Scperciva		grep -vE '^/boot/' $1/INDEX-NEW |
2854257192Sdelphij		    grep -vE '^[^|]+\|d\|' |
2855279265Sdelphij		    grep -vE '^/libexec/ld-elf[^|]*\.so\.[0-9]+\|' |
2856257192Sdelphij		    grep -E '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' > INDEX-NEW
2857173564Scperciva		install_from_index INDEX-NEW || return 1
2858173564Scperciva
2859173564Scperciva		# Deal with everything else
2860173564Scperciva		grep -vE '^/boot/' $1/INDEX-OLD |
2861257192Sdelphij		    grep -vE '^[^|]+\|d\|' |
2862279265Sdelphij		    grep -vE '^/libexec/ld-elf[^|]*\.so\.[0-9]+\|' |
2863257192Sdelphij		    grep -vE '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' > INDEX-OLD
2864173564Scperciva		grep -vE '^/boot/' $1/INDEX-NEW |
2865257192Sdelphij		    grep -vE '^[^|]+\|d\|' |
2866279265Sdelphij		    grep -vE '^/libexec/ld-elf[^|]*\.so\.[0-9]+\|' |
2867257192Sdelphij		    grep -vE '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' > INDEX-NEW
2868173564Scperciva		install_from_index INDEX-NEW || return 1
2869173564Scperciva		install_delete INDEX-OLD INDEX-NEW || return 1
2870173564Scperciva
2871173564Scperciva		# Rebuild /etc/spwd.db and /etc/pwd.db if necessary.
2872173564Scperciva		if [ /etc/master.passwd -nt /etc/spwd.db ] ||
2873173564Scperciva		    [ /etc/master.passwd -nt /etc/pwd.db ]; then
2874173564Scperciva			pwd_mkdb /etc/master.passwd
2875173564Scperciva		fi
2876173564Scperciva
2877173564Scperciva		# Rebuild /etc/login.conf.db if necessary.
2878173564Scperciva		if [ /etc/login.conf -nt /etc/login.conf.db ]; then
2879173564Scperciva			cap_mkdb /etc/login.conf
2880173564Scperciva		fi
2881173564Scperciva
2882173564Scperciva		# We've finished installing the world and deleting old files
2883173564Scperciva		# which are not shared libraries.
2884173564Scperciva		touch $1/worlddone
2885173564Scperciva
2886173564Scperciva		# Do we need to ask the user to portupgrade now?
2887173564Scperciva		grep -vE '^/boot/' $1/INDEX-NEW |
2888257192Sdelphij		    grep -E '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' |
2889173564Scperciva		    cut -f 1 -d '|' |
2890173564Scperciva		    sort > newfiles
2891173564Scperciva		if grep -vE '^/boot/' $1/INDEX-OLD |
2892257192Sdelphij		    grep -E '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' |
2893173564Scperciva		    cut -f 1 -d '|' |
2894173564Scperciva		    sort |
2895173564Scperciva		    join -v 1 - newfiles |
2896173564Scperciva		    grep -q .; then
2897173564Scperciva			cat <<-EOF
2898173564Scperciva
2899173564ScpercivaCompleting this upgrade requires removing old shared object files.
2900173564ScpercivaPlease rebuild all installed 3rd party software (e.g., programs
2901173564Scpercivainstalled from the ports tree) and then run "$0 install"
2902173564Scpercivaagain to finish installing updates.
2903173564Scperciva			EOF
2904173564Scperciva			rm newfiles
2905173564Scperciva			exit 0
2906173564Scperciva		fi
2907173564Scperciva		rm newfiles
2908173564Scperciva	fi
2909173564Scperciva
2910173564Scperciva	# Remove old shared libraries
2911173564Scperciva	grep -vE '^/boot/' $1/INDEX-NEW |
2912257192Sdelphij	    grep -vE '^[^|]+\|d\|' |
2913257192Sdelphij	    grep -E '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' > INDEX-NEW
2914173564Scperciva	grep -vE '^/boot/' $1/INDEX-OLD |
2915257192Sdelphij	    grep -vE '^[^|]+\|d\|' |
2916257192Sdelphij	    grep -E '^[^|]*/lib/[^|]*\.so\.[0-9]+\|' > INDEX-OLD
2917173564Scperciva	install_delete INDEX-OLD INDEX-NEW || return 1
2918173564Scperciva
2919257192Sdelphij	# Remove old directories
2920258724Sdelphij	grep -vE '^/boot/' $1/INDEX-NEW |
2921258724Sdelphij	    grep -E '^[^|]+\|d\|' > INDEX-NEW
2922257192Sdelphij	grep -vE '^/boot/' $1/INDEX-OLD |
2923257192Sdelphij	    grep -E '^[^|]+\|d\|' > INDEX-OLD
2924257192Sdelphij	install_delete INDEX-OLD INDEX-NEW || return 1
2925257192Sdelphij
2926173564Scperciva	# Remove temporary files
2927173564Scperciva	rm INDEX-OLD INDEX-NEW
2928161748Scperciva}
2929161748Scperciva
2930161748Scperciva# Rearrange bits to allow the installed updates to be rolled back
2931161748Scpercivainstall_setup_rollback () {
2932173564Scperciva	# Remove the "reboot after installing kernel", "kernel updated", and
2933173564Scperciva	# "finished installing the world" flags if present -- they are
2934173564Scperciva	# irrelevant when rolling back updates.
2935173564Scperciva	if [ -f ${BDHASH}-install/kernelfirst ]; then
2936173564Scperciva		rm ${BDHASH}-install/kernelfirst
2937173564Scperciva		rm ${BDHASH}-install/kerneldone
2938173564Scperciva	fi
2939173564Scperciva	if [ -f ${BDHASH}-install/worlddone ]; then
2940173564Scperciva		rm ${BDHASH}-install/worlddone
2941173564Scperciva	fi
2942173564Scperciva
2943161748Scperciva	if [ -L ${BDHASH}-rollback ]; then
2944161748Scperciva		mv ${BDHASH}-rollback ${BDHASH}-install/rollback
2945161748Scperciva	fi
2946161748Scperciva
2947161748Scperciva	mv ${BDHASH}-install ${BDHASH}-rollback
2948161748Scperciva}
2949161748Scperciva
2950161748Scperciva# Actually install updates
2951161748Scpercivainstall_run () {
2952161748Scperciva	echo -n "Installing updates..."
2953161748Scperciva
2954161748Scperciva	# Make sure we have all the files we should have
2955161748Scperciva	install_verify ${BDHASH}-install/INDEX-OLD	\
2956161748Scperciva	    ${BDHASH}-install/INDEX-NEW || return 1
2957161748Scperciva
2958161748Scperciva	# Remove system immutable flag from files
2959161748Scperciva	install_unschg ${BDHASH}-install/INDEX-OLD	\
2960161748Scperciva	    ${BDHASH}-install/INDEX-NEW || return 1
2961161748Scperciva
2962173564Scperciva	# Install new files, delete old files, and update linker.hints
2963173564Scperciva	install_files ${BDHASH}-install || return 1
2964161748Scperciva
2965161748Scperciva	# Rearrange bits to allow the installed updates to be rolled back
2966161748Scperciva	install_setup_rollback
2967161748Scperciva
2968161748Scperciva	echo " done."
2969161748Scperciva}
2970161748Scperciva
2971161748Scperciva# Rearrange bits to allow the previous set of updates to be rolled back next.
2972161748Scpercivarollback_setup_rollback () {
2973161748Scperciva	if [ -L ${BDHASH}-rollback/rollback ]; then
2974161748Scperciva		mv ${BDHASH}-rollback/rollback rollback-tmp
2975161748Scperciva		rm -r ${BDHASH}-rollback/
2976161748Scperciva		rm ${BDHASH}-rollback
2977161748Scperciva		mv rollback-tmp ${BDHASH}-rollback
2978161748Scperciva	else
2979161748Scperciva		rm -r ${BDHASH}-rollback/
2980161748Scperciva		rm ${BDHASH}-rollback
2981161748Scperciva	fi
2982161748Scperciva}
2983161748Scperciva
2984173564Scperciva# Install old files, delete new files, and update linker.hints
2985173564Scpercivarollback_files () {
2986173671Scperciva	# Install old shared library files which don't have the same path as
2987173671Scperciva	# a new shared library file.
2988173671Scperciva	grep -vE '^/boot/' $1/INDEX-NEW |
2989177601Scperciva	    grep -E '/lib/.*\.so\.[0-9]+\|' |
2990173671Scperciva	    cut -f 1 -d '|' |
2991173671Scperciva	    sort > INDEX-NEW.libs.flist
2992173564Scperciva	grep -vE '^/boot/' $1/INDEX-OLD |
2993177601Scperciva	    grep -E '/lib/.*\.so\.[0-9]+\|' |
2994173671Scperciva	    sort -k 1,1 -t '|' - |
2995173671Scperciva	    join -t '|' -v 1 - INDEX-NEW.libs.flist > INDEX-OLD
2996173564Scperciva	install_from_index INDEX-OLD || return 1
2997173564Scperciva
2998173564Scperciva	# Deal with files which are neither kernel nor shared library
2999173564Scperciva	grep -vE '^/boot/' $1/INDEX-OLD |
3000177601Scperciva	    grep -vE '/lib/.*\.so\.[0-9]+\|' > INDEX-OLD
3001173564Scperciva	grep -vE '^/boot/' $1/INDEX-NEW |
3002177601Scperciva	    grep -vE '/lib/.*\.so\.[0-9]+\|' > INDEX-NEW
3003173564Scperciva	install_from_index INDEX-OLD || return 1
3004173564Scperciva	install_delete INDEX-NEW INDEX-OLD || return 1
3005173564Scperciva
3006173671Scperciva	# Install any old shared library files which we didn't install above.
3007173671Scperciva	grep -vE '^/boot/' $1/INDEX-OLD |
3008177601Scperciva	    grep -E '/lib/.*\.so\.[0-9]+\|' |
3009173671Scperciva	    sort -k 1,1 -t '|' - |
3010173671Scperciva	    join -t '|' - INDEX-NEW.libs.flist > INDEX-OLD
3011173671Scperciva	install_from_index INDEX-OLD || return 1
3012173671Scperciva
3013173564Scperciva	# Delete unneeded shared library files
3014173564Scperciva	grep -vE '^/boot/' $1/INDEX-OLD |
3015177601Scperciva	    grep -E '/lib/.*\.so\.[0-9]+\|' > INDEX-OLD
3016173564Scperciva	grep -vE '^/boot/' $1/INDEX-NEW |
3017177601Scperciva	    grep -E '/lib/.*\.so\.[0-9]+\|' > INDEX-NEW
3018173564Scperciva	install_delete INDEX-NEW INDEX-OLD || return 1
3019173564Scperciva
3020173564Scperciva	# Deal with kernel files
3021173564Scperciva	grep -E '^/boot/' $1/INDEX-OLD > INDEX-OLD
3022173564Scperciva	grep -E '^/boot/' $1/INDEX-NEW > INDEX-NEW
3023173564Scperciva	install_from_index INDEX-OLD || return 1
3024173564Scperciva	install_delete INDEX-NEW INDEX-OLD || return 1
3025173564Scperciva	if [ -s INDEX-OLD -o -s INDEX-NEW ]; then
3026173564Scperciva		kldxref -R /boot/ 2>/dev/null
3027173564Scperciva	fi
3028173564Scperciva
3029173564Scperciva	# Remove temporary files
3030173672Scperciva	rm INDEX-OLD INDEX-NEW INDEX-NEW.libs.flist
3031173564Scperciva}
3032173564Scperciva
3033161748Scperciva# Actually rollback updates
3034161748Scpercivarollback_run () {
3035161748Scperciva	echo -n "Uninstalling updates..."
3036161748Scperciva
3037161748Scperciva	# If there are updates waiting to be installed, remove them; we
3038161748Scperciva	# want the user to re-run 'fetch' after rolling back updates.
3039161748Scperciva	if [ -L ${BDHASH}-install ]; then
3040161748Scperciva		rm -r ${BDHASH}-install/
3041161748Scperciva		rm ${BDHASH}-install
3042161748Scperciva	fi
3043161748Scperciva
3044161748Scperciva	# Make sure we have all the files we should have
3045161748Scperciva	install_verify ${BDHASH}-rollback/INDEX-NEW	\
3046161748Scperciva	    ${BDHASH}-rollback/INDEX-OLD || return 1
3047161748Scperciva
3048161748Scperciva	# Remove system immutable flag from files
3049161748Scperciva	install_unschg ${BDHASH}-rollback/INDEX-NEW	\
3050161748Scperciva	    ${BDHASH}-rollback/INDEX-OLD || return 1
3051161748Scperciva
3052173564Scperciva	# Install old files, delete new files, and update linker.hints
3053173564Scperciva	rollback_files ${BDHASH}-rollback || return 1
3054161748Scperciva
3055161748Scperciva	# Remove the rollback directory and the symlink pointing to it; and
3056161748Scperciva	# rearrange bits to allow the previous set of updates to be rolled
3057161748Scperciva	# back next.
3058161748Scperciva	rollback_setup_rollback
3059161748Scperciva
3060161748Scperciva	echo " done."
3061161748Scperciva}
3062161748Scperciva
3063181142Scperciva# Compare INDEX-ALL and INDEX-PRESENT and print warnings about differences.
3064181142ScpercivaIDS_compare () {
3065181425Scperciva	# Get all the lines which mismatch in something other than file
3066181425Scperciva	# flags.  We ignore file flags because sysinstall doesn't seem to
3067181425Scperciva	# set them when it installs FreeBSD; warning about these adds a
3068181425Scperciva	# very large amount of noise.
3069181425Scperciva	cut -f 1-5,7-8 -d '|' $1 > $1.noflags
3070181425Scperciva	sort -k 1,1 -t '|' $1.noflags > $1.sorted
3071181425Scperciva	cut -f 1-5,7-8 -d '|' $2 |
3072181425Scperciva	    comm -13 $1.noflags - |
3073181425Scperciva	    fgrep -v '|-|||||' |
3074181142Scperciva	    sort -k 1,1 -t '|' |
3075181142Scperciva	    join -t '|' $1.sorted - > INDEX-NOTMATCHING
3076181142Scperciva
3077181142Scperciva	# Ignore files which match IDSIGNOREPATHS.
3078181142Scperciva	for X in ${IDSIGNOREPATHS}; do
3079181142Scperciva		grep -E "^${X}" INDEX-NOTMATCHING
3080181142Scperciva	done |
3081181142Scperciva	    sort -u |
3082181142Scperciva	    comm -13 - INDEX-NOTMATCHING > INDEX-NOTMATCHING.tmp
3083181142Scperciva	mv INDEX-NOTMATCHING.tmp INDEX-NOTMATCHING
3084181142Scperciva
3085181142Scperciva	# Go through the lines and print warnings.
3086181142Scperciva	while read LINE; do
3087181142Scperciva		FPATH=`echo "${LINE}" | cut -f 1 -d '|'`
3088181142Scperciva		TYPE=`echo "${LINE}" | cut -f 2 -d '|'`
3089181142Scperciva		OWNER=`echo "${LINE}" | cut -f 3 -d '|'`
3090181142Scperciva		GROUP=`echo "${LINE}" | cut -f 4 -d '|'`
3091181142Scperciva		PERM=`echo "${LINE}" | cut -f 5 -d '|'`
3092181425Scperciva		HASH=`echo "${LINE}" | cut -f 6 -d '|'`
3093181425Scperciva		LINK=`echo "${LINE}" | cut -f 7 -d '|'`
3094181425Scperciva		P_TYPE=`echo "${LINE}" | cut -f 8 -d '|'`
3095181425Scperciva		P_OWNER=`echo "${LINE}" | cut -f 9 -d '|'`
3096181425Scperciva		P_GROUP=`echo "${LINE}" | cut -f 10 -d '|'`
3097181425Scperciva		P_PERM=`echo "${LINE}" | cut -f 11 -d '|'`
3098181425Scperciva		P_HASH=`echo "${LINE}" | cut -f 12 -d '|'`
3099181425Scperciva		P_LINK=`echo "${LINE}" | cut -f 13 -d '|'`
3100181142Scperciva
3101181142Scperciva		# Warn about different object types.
3102181142Scperciva		if ! [ "${TYPE}" = "${P_TYPE}" ]; then
3103181142Scperciva			echo -n "${FPATH} is a "
3104181142Scperciva			case "${P_TYPE}" in
3105181142Scperciva			f)	echo -n "regular file, "
3106181142Scperciva				;;
3107181142Scperciva			d)	echo -n "directory, "
3108181142Scperciva				;;
3109181142Scperciva			L)	echo -n "symlink, "
3110181142Scperciva				;;
3111181142Scperciva			esac
3112181142Scperciva			echo -n "but should be a "
3113181142Scperciva			case "${TYPE}" in
3114181142Scperciva			f)	echo -n "regular file."
3115181142Scperciva				;;
3116181142Scperciva			d)	echo -n "directory."
3117181142Scperciva				;;
3118181142Scperciva			L)	echo -n "symlink."
3119181142Scperciva				;;
3120181142Scperciva			esac
3121181142Scperciva			echo
3122181142Scperciva
3123181142Scperciva			# Skip other tests, since they don't make sense if
3124181142Scperciva			# we're comparing different object types.
3125181142Scperciva			continue
3126181142Scperciva		fi
3127181142Scperciva
3128181142Scperciva		# Warn about different owners.
3129181142Scperciva		if ! [ "${OWNER}" = "${P_OWNER}" ]; then
3130181142Scperciva			echo -n "${FPATH} is owned by user id ${P_OWNER}, "
3131181142Scperciva			echo "but should be owned by user id ${OWNER}."
3132181142Scperciva		fi
3133181142Scperciva
3134181142Scperciva		# Warn about different groups.
3135181142Scperciva		if ! [ "${GROUP}" = "${P_GROUP}" ]; then
3136181142Scperciva			echo -n "${FPATH} is owned by group id ${P_GROUP}, "
3137181142Scperciva			echo "but should be owned by group id ${GROUP}."
3138181142Scperciva		fi
3139181142Scperciva
3140181142Scperciva		# Warn about different permissions.  We do not warn about
3141181142Scperciva		# different permissions on symlinks, since some archivers
3142181142Scperciva		# don't extract symlink permissions correctly and they are
3143181142Scperciva		# ignored anyway.
3144181142Scperciva		if ! [ "${PERM}" = "${P_PERM}" ] &&
3145181142Scperciva		    ! [ "${TYPE}" = "L" ]; then
3146181142Scperciva			echo -n "${FPATH} has ${P_PERM} permissions, "
3147181142Scperciva			echo "but should have ${PERM} permissions."
3148181142Scperciva		fi
3149181142Scperciva
3150181142Scperciva		# Warn about different file hashes / symlink destinations.
3151181142Scperciva		if ! [ "${HASH}" = "${P_HASH}" ]; then
3152181142Scperciva			if [ "${TYPE}" = "L" ]; then
3153181142Scperciva				echo -n "${FPATH} is a symlink to ${P_HASH}, "
3154181142Scperciva				echo "but should be a symlink to ${HASH}."
3155181142Scperciva			fi
3156181142Scperciva			if [ "${TYPE}" = "f" ]; then
3157181142Scperciva				echo -n "${FPATH} has SHA256 hash ${P_HASH}, "
3158181142Scperciva				echo "but should have SHA256 hash ${HASH}."
3159181142Scperciva			fi
3160181142Scperciva		fi
3161181142Scperciva
3162181142Scperciva		# We don't warn about different hard links, since some
3163181142Scperciva		# some archivers break hard links, and as long as the
3164181142Scperciva		# underlying data is correct they really don't matter.
3165181142Scperciva	done < INDEX-NOTMATCHING
3166181142Scperciva
3167181142Scperciva	# Clean up
3168181425Scperciva	rm $1 $1.noflags $1.sorted $2 INDEX-NOTMATCHING
3169181142Scperciva}
3170181142Scperciva
3171181142Scperciva# Do the work involved in comparing the system to a "known good" index
3172181142ScpercivaIDS_run () {
3173181142Scperciva	workdir_init || return 1
3174181142Scperciva
3175181142Scperciva	# Prepare the mirror list.
3176181142Scperciva	fetch_pick_server_init && fetch_pick_server
3177181142Scperciva
3178181142Scperciva	# Try to fetch the public key until we run out of servers.
3179181142Scperciva	while ! fetch_key; do
3180181142Scperciva		fetch_pick_server || return 1
3181181142Scperciva	done
3182181142Scperciva 
3183181142Scperciva	# Try to fetch the metadata index signature ("tag") until we run
3184181142Scperciva	# out of available servers; and sanity check the downloaded tag.
3185181142Scperciva	while ! fetch_tag; do
3186181142Scperciva		fetch_pick_server || return 1
3187181142Scperciva	done
3188181142Scperciva	fetch_tagsanity || return 1
3189181142Scperciva
3190181142Scperciva	# Fetch INDEX-OLD and INDEX-ALL.
3191181142Scperciva	fetch_metadata INDEX-OLD INDEX-ALL || return 1
3192181142Scperciva
3193181142Scperciva	# Generate filtered INDEX-OLD and INDEX-ALL files containing only
3194181142Scperciva	# the components we want and without anything marked as "Ignore".
3195181142Scperciva	fetch_filter_metadata INDEX-OLD || return 1
3196181142Scperciva	fetch_filter_metadata INDEX-ALL || return 1
3197181142Scperciva
3198181142Scperciva	# Merge the INDEX-OLD and INDEX-ALL files into INDEX-ALL.
3199181142Scperciva	sort INDEX-OLD INDEX-ALL > INDEX-ALL.tmp
3200181142Scperciva	mv INDEX-ALL.tmp INDEX-ALL
3201181142Scperciva	rm INDEX-OLD
3202181142Scperciva
3203181142Scperciva	# Translate /boot/${KERNCONF} to ${KERNELDIR}
3204181142Scperciva	fetch_filter_kernel_names INDEX-ALL ${KERNCONF}
3205181142Scperciva
3206181142Scperciva	# Inspect the system and generate an INDEX-PRESENT file.
3207181142Scperciva	fetch_inspect_system INDEX-ALL INDEX-PRESENT /dev/null || return 1
3208181142Scperciva
3209181142Scperciva	# Compare INDEX-ALL and INDEX-PRESENT and print warnings about any
3210181142Scperciva	# differences.
3211181142Scperciva	IDS_compare INDEX-ALL INDEX-PRESENT
3212181142Scperciva}
3213181142Scperciva
3214161748Scperciva#### Main functions -- call parameter-handling and core functions
3215161748Scperciva
3216161748Scperciva# Using the command line, configuration file, and defaults,
3217161748Scperciva# set all the parameters which are needed later.
3218161748Scpercivaget_params () {
3219161748Scperciva	init_params
3220161748Scperciva	parse_cmdline $@
3221161748Scperciva	parse_conffile
3222161748Scperciva	default_params
3223161748Scperciva}
3224161748Scperciva
3225161748Scperciva# Fetch command.  Make sure that we're being called
3226161748Scperciva# interactively, then run fetch_check_params and fetch_run
3227161748Scpercivacmd_fetch () {
3228282874Sdelphij	if [ ! -t 0 -a $NOTTYOK -eq 0 ]; then
3229161748Scperciva		echo -n "`basename $0` fetch should not "
3230161748Scperciva		echo "be run non-interactively."
3231161748Scperciva		echo "Run `basename $0` cron instead."
3232161748Scperciva		exit 1
3233161748Scperciva	fi
3234161748Scperciva	fetch_check_params
3235161748Scperciva	fetch_run || exit 1
3236161748Scperciva}
3237161748Scperciva
3238161748Scperciva# Cron command.  Make sure the parameters are sensible; wait
3239161748Scperciva# rand(3600) seconds; then fetch updates.  While fetching updates,
3240161748Scperciva# send output to a temporary file; only print that file if the
3241161748Scperciva# fetching failed.
3242161748Scpercivacmd_cron () {
3243161748Scperciva	fetch_check_params
3244161748Scperciva	sleep `jot -r 1 0 3600`
3245161748Scperciva
3246161748Scperciva	TMPFILE=`mktemp /tmp/freebsd-update.XXXXXX` || exit 1
3247161748Scperciva	if ! fetch_run >> ${TMPFILE} ||
3248161748Scperciva	    ! grep -q "No updates needed" ${TMPFILE} ||
3249161748Scperciva	    [ ${VERBOSELEVEL} = "debug" ]; then
3250161748Scperciva		mail -s "`hostname` security updates" ${MAILTO} < ${TMPFILE}
3251161748Scperciva	fi
3252161748Scperciva
3253161748Scperciva	rm ${TMPFILE}
3254161748Scperciva}
3255161748Scperciva
3256173564Scperciva# Fetch files for upgrading to a new release.
3257173564Scpercivacmd_upgrade () {
3258173564Scperciva	upgrade_check_params
3259173564Scperciva	upgrade_run || exit 1
3260173564Scperciva}
3261173564Scperciva
3262161748Scperciva# Install downloaded updates.
3263161748Scpercivacmd_install () {
3264161748Scperciva	install_check_params
3265161748Scperciva	install_run || exit 1
3266161748Scperciva}
3267161748Scperciva
3268161748Scperciva# Rollback most recently installed updates.
3269161748Scpercivacmd_rollback () {
3270161748Scperciva	rollback_check_params
3271161748Scperciva	rollback_run || exit 1
3272161748Scperciva}
3273161748Scperciva
3274181142Scperciva# Compare system against a "known good" index.
3275181142Scpercivacmd_IDS () {
3276181142Scperciva	IDS_check_params
3277181142Scperciva	IDS_run || exit 1
3278181142Scperciva}
3279181142Scperciva
3280161748Scperciva#### Entry point
3281161748Scperciva
3282161748Scperciva# Make sure we find utilities from the base system
3283161748Scpercivaexport PATH=/sbin:/bin:/usr/sbin:/usr/bin:${PATH}
3284161748Scperciva
3285217767Sgordon# Set a pager if the user doesn't
3286217767Sgordonif [ -z "$PAGER" ]; then
3287217767Sgordon	PAGER=/usr/bin/more
3288217767Sgordonfi
3289217767Sgordon
3290163564Scperciva# Set LC_ALL in order to avoid problems with character ranges like [A-Z].
3291163564Scpercivaexport LC_ALL=C
3292163564Scperciva
3293161748Scpercivaget_params $@
3294161748Scpercivafor COMMAND in ${COMMANDS}; do
3295161748Scperciva	cmd_${COMMAND}
3296161748Scpercivadone
3297