aboutsummaryrefslogtreecommitdiff
path: root/bin/urlc
blob: e306d48f612851d013b9ed330f84cab0e5ba052b (plain) (blame)
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
#!/bin/sh
# Try to find erroneous or insecure URLs
self=urlc

# cURL request timeout
tm=${URLCHECK_TIMEOUT:-8}

# Create a temporary directory with name in $td, and handle POSIX-ish traps to
# remove it when the script exits.
td=
cleanup() {
    [ -n "$td" ] && rm -fr -- "$td"
    if [ "$1" != EXIT ] ; then
        trap - "$1"
        kill "-$1" "$$"
    fi
}
for sig in EXIT HUP INT TERM ; do
    # shellcheck disable=SC2064
    trap "cleanup $sig" "$sig"
done
td=$(mktd "$self") || exit

# Create buffer files for the headers and body content, to be cleaned up on
# exit
list=$td/list head=$td/head body=$td/body

# Iterate through input; ignore leading/trailing whitespace
# shellcheck disable=SC2002
cat -- "${@:--}" >"$list"
while read -r url ; do

    # Skip anything that doesn't start with HTTP
    case $url in
        http*) ;;
        *) continue ;;
    esac

    # Make initial request, log head and body to files, cry and skip on error
    if ! curl -A Mozilla -fHLsS -D "$head" -m "$tm" -o "$body" -- \
       "$url" ; then
        printf >&2 '%s: %s raises error\n' \
            "$self" "$url"
        ex=1
        continue
    fi

    # Iterate through header file, cry about the first redirect we find
    while IFS=': ' read -r header value ; do
        [ "$header" = 'Location' ] || continue
        printf >&2 '%s: %s redirects to %s\n' \
            "$self" "$url" "$value" >&2
        ex=1
        break
    done < "$head"

    # Skip anything that's already secure
    case $url in
        https*) continue ;;
        *) ;;
    esac

    # Form a naïve attempt at a possible secure URL and try to request it,
    # point it out if it actually works
    burl=${url#http://}
    surl=https://$burl
    if curl -A Mozilla -fLsS -D "$head" -m "$tm" -o "$body" -- \
       "$surl" 2>/dev/null ; then
        printf >&2 '%s: %s has a working secure version at %s\n' \
            "$self" "$url" "$surl"
        ex=1
    fi
done <"$list"

# Wait for the input process to finish
wait

# Exit if any errors
exit "${ex:-0}"