#!/bin/bash
# apt method "https" on top of curl (/usr/bin/curl 8.x, TLS 1.2/1.3). Replaces the old method of apt-transport-https
# (libcurl with OpenSSL 0.9.8, TLS 1.0 only), which GitHub and most other servers refuse.
# Protocol: apt starts the method, reads "100 Capabilities", then sends "601 Configuration" and "600 URI Acquire" messages
# (header lines, an empty line ends a message) on stdin and gets "200 URI Start", "201 URI Done" or "400 URI Failure" on stdout.
# Honoured settings: Acquire::https::CaInfo (CA bundle), Acquire::https::Proxy, Acquire::https::Timeout,
# Acquire::https::Curl-Insecure "true" (no certificate check). NOT honoured: Acquire::https::Verify-Peer, because the
# phone ships Verify-Peer "false" in apt.conf.d, which would silently turn the verification off.
CURL=${CURL:-/usr/bin/curl}
CAINFO=; PROXY=; INSECURE=; TIMEOUT=60

# APT_CURL_DEBUG=/path/file writes the whole conversation with apt to that file. The Application Manager starts the methods
# without our environment: creating the file /etc/apt/apt-transport-curl.debug turns the log on (to /tmp/apt-transport-curl.log).
[ -n "${APT_CURL_DEBUG:-}" ] || ! [ -f /etc/apt/apt-transport-curl.debug ] || APT_CURL_DEBUG=/tmp/apt-transport-curl.log
# What goes wrong is always written to stderr (apt prints it) and to /tmp/apt-transport-curl.errors, and the method says why it ends:
# "Method https has died unexpectedly" tells nothing. /usr/share/doc/apt-transport-curl/check.sh prints the whole state of the installation.
ERRLOG=/tmp/apt-transport-curl.errors
problem() { printf '%s apt-transport-curl: %s\n' "$(date '+%F %T' 2>/dev/null)" "$*" >> "$ERRLOG" 2>/dev/null; printf 'apt-transport-curl: %s\n' "$*" >&2; }
trap '' PIPE       # a closed output is not a crash: the writes fail, the method goes on and ends with 0 at the end of its input
trap 'rc=$?; [ "$rc" -eq 0 ] || problem "the method ended with the exit code $rc (see check.sh)"' EXIT
dbg() { [ -z "${APT_CURL_DEBUG:-}" ] || printf '%s\n' "$*" >> "$APT_CURL_DEBUG"; }
# one write() per message: the old apt does not cope with a message that arrives in pieces
# The whole message (its lines and the empty line that ends it) goes out in ONE write(): the printf builtin of bash writes the pieces of a format like
# '%s\n' one by one, which put the empty line into a second write(); the apt-worker of the Application Manager read the first piece (it was woken by it)
# and never recognised the message ("Preparing installation" for ever). Only a format with a single %s makes one write().
send() { local m; dbg ">> $*"; m=$(printf '%s\n' "$@"; printf '\nx'); printf '%s' "${m%x}" 2>/dev/null; }

# The apt 0.7 of the phone misses the first message when the method answers at once (the compiled methods are slower to start
# because of dynamic linking): a short pause is needed, found by experiment (an immediate printf hangs apt for ever).
sleep 0.2 2>/dev/null || /bin/true
send "100 Capabilities" "Version: 1.2" "Pipeline: true"

# curl is checked once at the start: without it every request fails with a clear message instead of an exit code
CURL_PROBLEM=
if [ ! -x "$CURL" ]; then
    CURL_PROBLEM="$CURL is missing or not executable: install the package curl"
    problem "$CURL_PROBLEM"
fi

failure() { # uri message
    send "400 URI Failure" "URI: $1" "Message: $2"
}

acquire() { # uri filename
    local uri=$1 file=$2 hdr err rc code opts=() lm size
    [ -z "$CURL_PROBLEM" ] || { failure "$uri" "$CURL_PROBLEM"; return; }
    hdr=$(mktemp) && err=$(mktemp) || { failure "$uri" "mktemp failed"; return; }
    send "200 URI Start" "URI: $uri"
    opts=(-sS -L --proto =https,http --proto-redir =https,http --connect-timeout "$TIMEOUT" --speed-time "$TIMEOUT" --speed-limit 1
          -D "$hdr" -o "$file" -w '%{http_code}')
    [ -z "$CAINFO" ] || opts+=(--cacert "$CAINFO")
    [ -z "$PROXY" ] || opts+=(--proxy "$PROXY")
    [ -z "$INSECURE" ] || opts+=(-k)
    code=$("$CURL" "${opts[@]}" "$uri" 2> "$err")
    rc=$?
    if [ $rc -ne 0 ]; then
        problem "curl $rc for $uri: $(tr '\r\n' '  ' < "$err" | cut -c1-200)"
        failure "$uri" "$(tr '\r\n' '  ' < "$err" | cut -c1-200) (curl $rc)"
    elif [ "$code" != 200 ]; then
        rm -f "$file"
        failure "$uri" "HTTP $code"
    else
        # the headers of the last response (after redirects) hold the Last-Modified
        lm=$(grep -i '^last-modified:' "$hdr" | tail -n 1 | tr -d '\r' | sed 's/^[^:]*: *//')
        size=$(wc -c < "$file" | tr -d ' ')
        send "201 URI Done" "URI: $uri" "Filename: $file" "Size: $size" ${lm:+"Last-Modified: $lm"} \
             "MD5-Hash: $(md5sum < "$file" | cut -d' ' -f1)" "SHA1-Hash: $(sha1sum < "$file" | cut -d' ' -f1)" \
             "SHA256-Hash: $(sha256sum < "$file" | cut -d' ' -f1)"
    fi
    rm -f "$hdr" "$err"
}

config() { # Acquire::https::CaInfo=/path ...
    local k=${1%%=*} v=${1#*=}
    v=${v#\"}; v=${v%\"}
    case $k in
        Acquire::https::CaInfo)       CAINFO=$v ;;
        Acquire::https::Proxy)        [ "$v" = DIRECT ] && PROXY= || PROXY=$v ;;
        Acquire::https::Timeout)      TIMEOUT=$v ;;
        Acquire::https::Curl-Insecure) case $v in true|1|yes) INSECURE=1 ;; *) INSECURE= ;; esac ;;
    esac
}

# Send-Config is NOT requested: the apt-worker of the Application Manager reads our "100 Capabilities" and then never sends the
# "601 Configuration" (verified on the phone: nothing in the pipe, both sides waiting for ever). The few settings we use are read
# with apt-config at the first request instead.
loadconfig() {
    local k v
    [ -z "${CONFIG_LOADED:-}" ] || return 0
    CONFIG_LOADED=1
    while IFS= read -r line; do
        k=${line%% *}; v=${line#* }
        config "${k}=${v%;}"
    done < <(apt-config dump 2>/dev/null | grep '^Acquire::https::\(CaInfo\|Proxy\|Timeout\|Curl-Insecure\) ')
}

first=; uri=; file=
while IFS= read -r line; do
    line=${line%$'\r'}
    dbg "<< $line"
    if [ -n "$line" ]; then
        if [ -z "$first" ]; then first=$line; continue; fi
        case $line in
            URI:*)         uri=${line#URI: } ;;
            Filename:*)    file=${line#Filename: } ;;
            Config-Item:*) config "${line#Config-Item: }" ;;
        esac
        continue
    fi
    case $first in
        600*) loadconfig; acquire "$uri" "$file" ;;
    esac
    first=; uri=; file=
done
dbg "== end of input"
exit 0          # the end of the input is how apt ends the method; a closed output (a pipe to head, a test) is not an error
