File: auto-apt-proxy

package info (click to toggle)
auto-apt-proxy 11
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 136 kB
  • sloc: sh: 108; makefile: 13
file content (80 lines) | stat: -rwxr-xr-x 1,697 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/sh

set -e

tmpfile=$(mktemp)
cleanup() {
  rm -f "$tmpfile"
}
trap cleanup INT EXIT TERM

hit() {
  /usr/lib/apt/apt-helper \
    -o Acquire::http::Proxy=DIRECT \
    download-file "$@" "$tmpfile" 2>&1
}

detect_apt_cacher() {
  local ip="$1"
  local proxy=http://$ip:3142
  hit -o "Acquire::http::Proxy::${ip}=DIRECT" "$proxy" >/dev/null 2>&1 || true;
  if [ -s "$tmpfile" ] && grep -q -i '<title>Apt-cacher' "$tmpfile"; then
    echo "$proxy"
    return 0
  fi
  return 1
}

detect_apt_cacher_ng() {
  local ip="$1"
  local proxy=http://$ip:3142
  if hit -o "Acquire::http::Proxy::${ip}=DIRECT" "$proxy" | grep -q -i '406.*usage.information'; then
    echo "$proxy"
    return 0
  fi
  return 1
}

detect_approx() {
  local ip="$1"
  local proxy=http://$ip:9999
  hit -o "Acquire::http::Proxy::${ip}=DIRECT" "$proxy" >/dev/null 2>&1 || true;
  if [ -s "$tmpfile" ] && grep -q -i '<title>approx\s*server</title>' "$tmpfile"; then
    echo "$proxy"
    return 0
  fi
  return 1
}

detect() {
  if command -v ip >/dev/null; then
    gateway=$(ip route | awk '/default/ { print($3) }')
  else
    gateway=''
  fi
  for ip in 127.0.0.1 $gateway; do
    detect_apt_cacher_ng "$ip" && return 0
    detect_approx "$ip"        && return 0
    detect_apt_cacher "$ip"    && return 0
  done
  return 0
}

if [ $# -eq 0 ]; then
  detect
else
  case "$1" in
    ftp://*|http://*|https://*|file://*)
      # APT mode: first argument is an URI
      detect
      ;;
    *)
      # wrapper mode: execute command using the detected proxy
      proxy=$(detect || true)
      if [ -n "$proxy" ]; then
        export http_proxy="$proxy"
        export HTTP_PROXY="$proxy"
      fi
      exec "$@"
  esac
fi