#!/bin/sh -e
#
# update-ca-certificates
#
# Copyright (c) 2003 Fumitoshi UKAI <ukai@debian.or.jp>
# Copyright (c) 2009 Philipp Kern <pkern@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301,
# USA.
#

verbose=0
fresh=0
default=0
DESTDIR=
CERTSCONF=/etc/ca-certificates.conf
CERTSCONFD=/etc/ca-certificates.d
CERTSDIR=/usr/share/ca-certificates
LOCALCERTSDIR=/etc/certs
CERTBUNDLE=/etc/certs/ca-certificates.crt
ETCCERTSDIR=/etc/openssl/certs
HOOKSDIR=/etc/ca-certificates/update.d

while [ $# -gt 0 ];
do
  case $1 in
    --verbose|-v)
      verbose=1;;
    --fresh|-f)
      fresh=1;;
    --default|-d)
      default=1
      fresh=1;;
    --destdir)
      DESTDIR=$2; shift;;
    --certsconf)
      shift
      CERTSCONF="$1";;
    --certsdir)
      shift
      CERTSDIR="$1";;
    --localcertsdir)
      shift
      LOCALCERTSDIR="$1";;
    --certbundle)
      shift
      CERTBUNDLE="$1";;
    --etccertsdir)
      shift
      ETCCERTSDIR="$1";;
    --hooksdir)
      shift
      HOOKSDIR="$1";;
    --sysroot)
      shift
      SYSROOT="$1"
      CERTSCONF="$1/${CERTSCONF}"
      CERTSDIR="$1/${CERTSDIR}"
      LOCALCERTSDIR="$1/${LOCALCERTSDIR}"
      ETCCERTSDIR="$1/${ETCCERTSDIR}"
      HOOKSDIR="$1/${HOOKSDIR}";;
    --help|-h|*)
      echo "$0: [--verbose] [--fresh]"
      exit;;
  esac
  shift
done

CERTSCONF=${DESTDIR}${CERTSCONF}
CERTSCONFD=${DESTDIR}${CERTSCONFD}
CERTSDIR=${DESTDIR}${CERTSDIR}
LOCALCERTSDIR=${DESTDIR}${LOCALCERTSDIR}
CERTBUNDLE=${DESTDIR}${CERTBUNDLE}
ETCCERTSDIR=${DESTDIR}${ETCCERTSDIR}
HOOKSDIR=${DESTDIR}${HOOKSDIR}

if [ ! -s "$CERTSCONF" ]
then
  fresh=1
fi

cleanup() {
  rm -f "$TEMPBUNDLE"
  rm -f "$ADDED"
  rm -f "$REMOVED"
  [ -z "$STAGING" ] || chmod u+w "$STAGING" 2>/dev/null || :
  rm -rf "$STAGING" "$OURS" "$NEW" "$LIVE"
}
trap cleanup 0

# Helper files.  (Some of them are not simple arrays because we spawn
# subshells later on.)
TEMPBUNDLE="${CERTBUNDLE}.new"
ADDED="$(mktemp -p "${TMPDIR:-/tmp}" "ca-certificates.tmp.XXXXXX")"
REMOVED="$(mktemp -p "${TMPDIR:-/tmp}" "ca-certificates.tmp.XXXXXX")"

# Adds a certificate to the bundle being built.  The OpenSSL hashed
# CApath is regenerated afterwards from the finished bundle by p11-kit.
add() {
  CERT="$1"
  echo "+$CERT" >> "$ADDED"
  # Add trailing newline to certificate, if it is missing (#635570)
  sed -e '$a\' "$CERT" >> "$TEMPBUNDLE"
}

remove() {
  CERT="$1"
  echo "-$CERT" >> "$REMOVED"
}

echo "Updating certificates in $ETCCERTSDIR..."

# Add default certificate authorities if requested
if [ "$default" = 1 ]; then
  find -L "$CERTSDIR" -type f -name '*.crt' | sort | while read -r crt
  do
    add "$crt"
  done
fi

for conf in $CERTSCONF $CERTSCONFD/*.conf; do
  # skip inexistent files (matched by glob)
  [ -f $conf ] || continue

  # Handle certificates that should be removed.  This is an explicit act
  # by prefixing lines in the configuration files with exclamation marks (!).
  sed -n -e '/^$/d' -e 's/^!//p' $conf | while read -r crt
  do
    remove "$CERTSDIR/$crt"
  done

  sed -e '/^$/d' -e '/^#/d' -e '/^!/d' $conf | while read -r crt
  do
    if test -f "$CERTSDIR/$crt"
    then
      add "$CERTSDIR/$crt"
    elif test -f "$LOCALCERTSDIR/$crt"
    then
      add "$LOCALCERTSDIR/$crt"
    else
      echo "W: $CERTSDIR/$crt or $LOCALCERTSDIR/$crt not found, but listed in $conf." >&2
      continue
    fi
  done
done

ADDED_CNT=$(wc -l < "$ADDED")
REMOVED_CNT=$(wc -l < "$REMOVED")

# chmod and mv only if TEMPBUNDLE exists or install may fail, #996005
if [ -f "$TEMPBUNDLE" ]
then
  chmod 0644 "$TEMPBUNDLE"
  mv -f "$TEMPBUNDLE" "$CERTBUNDLE"
  # Restore proper SELinux label after moving the file
  [ -x /sbin/restorecon ] && /sbin/restorecon "$CERTBUNDLE" >/dev/null 2>&1
fi

# Regenerate the OpenSSL hashed CApath from the freshly built bundle.
# p11-kit computes the hashes itself, so ca-certificates stays off the
# openssl -> ca-certificates dependency cycle.  Skipped under --destdir
# because trust reads the live system trust module, not the buildroot.
# The extraction goes to a staging directory (trust extract --overwrite
# unlinks everything in its target it did not write itself) and is synced
# to ETCCERTSDIR against a manifest of what we installed before, so files
# the local admin drops here are never deleted.
if [ -z "$DESTDIR" ]
then
  MANIFEST="$ETCCERTSDIR/.manifest"
  STAGING="$(mktemp -d -p "${TMPDIR:-/tmp}" "ca-certificates.stage.XXXXXX")"
  OURS="$(mktemp -p "${TMPDIR:-/tmp}" "ca-certificates.tmp.XXXXXX")"
  NEW="$(mktemp -p "${TMPDIR:-/tmp}" "ca-certificates.tmp.XXXXXX")"
  LIVE="$(mktemp -p "${TMPDIR:-/tmp}" "ca-certificates.tmp.XXXXXX")"

  trust extract --format=openssl-directory --filter=ca-anchors --overwrite "$STAGING"

  mkdir -p "$ETCCERTSDIR"
  chmod 755 "$ETCCERTSDIR"

  find "$STAGING" -maxdepth 1 \( -type f -o -type l \) -printf '%f\n' | sort > "$NEW"

  if [ -f "$MANIFEST" ]
  then
    sort "$MANIFEST" > "$OURS"
  else
    # No manifest yet: claim what earlier layouts generated -- hash links,
    # symlinks into the cert stores or dangling ones (openssl-rehash
    # layout) and TRUSTED CERTIFICATE files (direct p11-kit extraction).
    # Anything else was placed by the local admin and is left alone.
    {
      find "$ETCCERTSDIR" -maxdepth 1 -type l \
        \( -name '[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].*' \
        -o -lname "$CERTSDIR/*" -o -lname "$LOCALCERTSDIR/*" -o -xtype l \) \
        -printf '%f\n'
      grep -sl -- '-----BEGIN TRUSTED CERTIFICATE-----' "$ETCCERTSDIR"/*.pem | sed 's,.*/,,'
      echo README
    } | sort -u > "$OURS"
  fi

  # entries we installed on a previous run and which are gone from the new set;
  # never step outside the directory, whatever a damaged manifest claims
  comm -23 "$OURS" "$NEW" | while IFS= read -r f
  do
    case "$f" in ''|*/*) continue ;; esac
    rm -f "$ETCCERTSDIR/$f"
  done

  same_entry() {
    if [ -L "$1" ] || [ -L "$2" ]
    then
      [ -L "$1" ] && [ -L "$2" ] && [ "$(readlink "$1")" = "$(readlink "$2")" ]
    else
      [ "$(md5sum < "$1")" = "$(md5sum < "$2")" ]
    fi
  }

  # install the new set; identical entries are left as they are, a name
  # collision with a differing foreign file is resolved in our favour and
  # the foreign file is kept next to it as <name>.local
  while IFS= read -r f
  do
    if [ -e "$ETCCERTSDIR/$f" ] || [ -L "$ETCCERTSDIR/$f" ]
    then
      if same_entry "$STAGING/$f" "$ETCCERTSDIR/$f"
      then
        continue
      fi
      if ! grep -qxF -- "$f" "$OURS"
      then
        echo "W: $ETCCERTSDIR/$f is in the generated namespace, keeping it as $f.local" >&2
        mv -f "$ETCCERTSDIR/$f" "$ETCCERTSDIR/$f.local"
      fi
    fi
    cp -a --remove-destination "$STAGING/$f" "$ETCCERTSDIR/$f"
  done < "$NEW"

  cat > "$ETCCERTSDIR/README" <<'EOF'
This directory is generated by update-ca-certificates(8) from the
/etc/certs/ca-certificates.crt bundle.  Entries listed in .manifest are
rewritten on every run; other files are left alone, but OpenSSL ignores
them -- a certificate is only consulted here through its hash link, and
those all come from the trust store.

To trust a local CA system wide, put its certificate in /etc/certs, list
the file name in a /etc/ca-certificates.d/*.conf file and run
update-ca-certificates.  It then shows up here with its hash link.

To give a certificate to a single application only, keep it outside this
directory and point that application at it directly.
EOF

  { cat "$NEW"; echo README; } > "$MANIFEST"

  # files this script does not manage look trusted but are dead weight
  find "$ETCCERTSDIR" -maxdepth 1 \( -type f -o -type l \) -printf '%f\n' | sort > "$LIVE"
  { cat "$MANIFEST"; echo .manifest; } | sort | comm -13 - "$LIVE" | while IFS= read -r f
  do
    echo "W: $ETCCERTSDIR/$f is not part of the trust store and is ignored by OpenSSL, see $ETCCERTSDIR/README" >&2
  done

fi

echo "$ADDED_CNT added, $REMOVED_CNT removed; done."

# vim:set et sw=2:
