1 | #!/bin/sh
|
---|
2 | #
|
---|
3 | # Pen proxy wrapper, periodic check for best connections available.
|
---|
4 | #
|
---|
5 | # Stichting Wireless Leiden
|
---|
6 | #
|
---|
7 | # Rick van der Zwet <rick@wirelessleiden.nl>
|
---|
8 | #
|
---|
9 |
|
---|
10 | BIND_ADDR=${1:-172.31.255.1}
|
---|
11 | BIND_PORT=${2:-3128}
|
---|
12 |
|
---|
13 |
|
---|
14 | # Internal parameters, don't touch unless you know what you are doing.
|
---|
15 | TEST_URL="http://tinyproxy.stats/"
|
---|
16 | TEST_INTERVAL=`expr 15 \* 60`
|
---|
17 | PIDFILE='/var/run/pen.pid'
|
---|
18 | PEN='/usr/local/bin/pen'
|
---|
19 | PEN_FLAGS="-S 20 -b 30 -p ${PIDFILE} ${BIND_ADDR}:${BIND_PORT}"
|
---|
20 |
|
---|
21 | TAG=`basename $0`
|
---|
22 | logit() {
|
---|
23 | logger -t "$TAG" $*
|
---|
24 | }
|
---|
25 |
|
---|
26 | get_proxy_list() {
|
---|
27 | # Get (updated) proxy listing from configuration files.
|
---|
28 | . /etc/rc.subr
|
---|
29 | load_rc_config "pen_wrapper"
|
---|
30 | make_list "$list_normal_proxies" " "
|
---|
31 | }
|
---|
32 |
|
---|
33 |
|
---|
34 | # Return speed value, higher is better
|
---|
35 | test_proxy() {
|
---|
36 | PROXY=$1
|
---|
37 | retstr=`HTTP_PROXY=http://$PROXY fetch -T 3 -o /dev/null ${TEST_URL} 2>&1`
|
---|
38 | bps=`echo "${retstr}" | awk '/Bps/ {printf $4}'`
|
---|
39 | echo ${bps:-"0"}
|
---|
40 | }
|
---|
41 |
|
---|
42 | # Sort proxy list on highest bandwidth
|
---|
43 | test_proxies() {
|
---|
44 | result=''
|
---|
45 | for host in $*; do
|
---|
46 | bps=`test_proxy $host:3128`
|
---|
47 | if [ "$bps" != "0" ]; then
|
---|
48 | result="$result $bps:$host:3128"
|
---|
49 | fi
|
---|
50 | done
|
---|
51 |
|
---|
52 | echo $result | xargs -n1 | sort -t':' -k1 -n -r | cut -d: -f 2,3 | xargs
|
---|
53 | }
|
---|
54 |
|
---|
55 |
|
---|
56 | ##
|
---|
57 | # Main loop
|
---|
58 | LIVE_PROXY_LIST=''
|
---|
59 | while true; do
|
---|
60 | PROXY_LIST=`get_proxy_list`
|
---|
61 | if [ -z "$PROXY_LIST" ]; then
|
---|
62 | logit "Not starting: list_normal_proxies variable not configured"
|
---|
63 | else
|
---|
64 | NEW_PROXY_LIST=`test_proxies $PROXY_LIST`
|
---|
65 | if [ "${LIVE_PROXY_LIST}" != "${NEW_PROXY_LIST}" ]; then
|
---|
66 | logit "INFO: New listing to be configured '${NEW_PROXY_LIST}'"
|
---|
67 |
|
---|
68 | # Pen should only be started if alias exists
|
---|
69 | ifconfig | grep -q ${BIND_ADDR} || {
|
---|
70 | logit "Not starting: alias $BIND_ADDR not configured!"
|
---|
71 | } && {
|
---|
72 | [ -r ${PIDFILE} ] && kill `cat ${PIDFILE}`
|
---|
73 | ${PEN} ${PEN_FLAGS} ${NEW_PROXY_LIST}
|
---|
74 | LIVE_PROXY_LIST="${NEW_PROXY_LIST}"
|
---|
75 | }
|
---|
76 | fi
|
---|
77 | fi
|
---|
78 |
|
---|
79 | sleep ${TEST_INTERVAL}
|
---|
80 | done
|
---|