Logoj0ke.net Open Build Service > Projects > internetx:projects:webservices > haproxy > haproxy-geoip
Sign Up | Log In

File haproxy-geoip of Package haproxy

 
1
#!/bin/bash
2
3
set -e -o pipefail 
4
5
DEFAULT_INFILE="http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip"
6
DEFAULT_CACHEFILE="/etc/haproxy/GeoIPCountryCSV.zip"
7
8
function usage()
9
{
10
    cat >&2 << EOF
11
12
Usage: $0 [-l] [-i <input file>] [<country code>...]
13
14
Options :
15
  -h              display this help and exit
16
  -l              applies a lowercase filter to the output
17
  -c <cachefile>  when using an HTTP URL, defines where the file will be cached
18
                    on disk. This prevents downloading a file that was not
19
                    modified
20
                    Default: $DEFAULT_CACHEFILE
21
  -i <infile>     the input file containing the GeOIP database.
22
                    it can be a local file or an HTTP URL. If the file name
23
                    ends with ".zip", it will be automatically unzipped
24
                    Default: $DEFAULT_INFILE
25
26
  <country code>  if specified, only those countries will be sent to the
27
                    output. If not specified, all of them will
28
29
30
Example :
31
$ $0 -l -i $DEFAULT_INFILE FR UK IT US
32
EOF
33
    exit 1
34
}
35
# Initialize the parameters from the command line
36
filters=""
37
infile=$DEFAULT_INFILE
38
cachefile=$DEFAULT_CACHEFILE
39
lowercase_opts=0
40
while getopts "c:i:hl" opt;
41
do
42
    case $opt in
43
        c) cachefile=$OPTARG;;
44
        i) infile=$OPTARG;;
45
        l) lowercase_opts=1;;
46
        h | \?) usage;;
47
    esac
48
done
49
shift $(($OPTIND - 1)) 
50
51
52
# Fetch the file if it's a HTTP URL, then use the cache file as input
53
if [[ "$infile" =~ ^http://.* ]];
54
then
55
    curl -fs -z $cachefile -o $cachefile $infile || { echo "Unable to fetch the GeoIP data file"; exit 1; }
56
    infile=$cachefile
57
fi
58
59
if [ ! -e $infile ];
60
then
61
    echo "Le fichier source de géolocalisation $infile n'existe pas". >&2
62
    exit 1
63
fi
64
65
# Should we decompress it on the fly ?
66
if [[ "$infile" =~ ^.*\.zip ]];
67
then
68
    reader="funzip"
69
else
70
    reader="cat"
71
fi
72
73
# Initialize the country filter
74
countries=""
75
for country in $*;
76
do
77
    if [ "$countries" = "" ];
78
    then
79
        countries="$country"
80
    else
81
        countries="$countries|$country"
82
    fi
83
done
84
85
if [ "$countries" != "" ];
86
then
87
    filters="$filters|grep -Ei '($countries)'"
88
fi
89
90
# Initialize the lowercase filter
91
if [ $lowercase_opts -eq 1 ];
92
then
93
    filters="$filters|tr A-Z a-z"
94
fi
95
96
# Now we can launch the conversion process
97
eval "$reader $infile | cut -d, -f1,2,5 | iprange | sed 's/\"//g' $filters" || { echo "GeoIP data conversion failure"; exit 1; }
98