]>
git.ipfire.org Git - location/libloc.git/blob - src/python/location-downloader.in
2 ###############################################################################
4 # libloc - A library to determine the location of someone on the Internet #
6 # Copyright (C) 2019 IPFire Development Team <info@ipfire.org> #
8 # This library is free software; you can redistribute it and/or #
9 # modify it under the terms of the GNU Lesser General Public #
10 # License as published by the Free Software Foundation; either #
11 # version 2.1 of the License, or (at your option) any later version. #
13 # This library is distributed in the hope that it will be useful, #
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
16 # Lesser General Public License for more details. #
18 ###############################################################################
34 # Load our location module
36 from location
.i18n
import _
38 DATABASE_FILENAME
= "test.db.xz"
40 "https://location.ipfire.org/databases/",
41 "https://people.ipfire.org/~ms/location/",
45 log
= logging
.getLogger("location.downloader")
48 class Downloader(object):
49 def __init__(self
, mirrors
):
50 self
.mirrors
= list(mirrors
)
53 random
.shuffle(self
.mirrors
)
55 # Get proxies from environment
56 self
.proxies
= self
._get
_proxies
()
58 def _get_proxies(self
):
61 for protocol
in ("https", "http"):
62 proxy
= os
.environ
.get("%s_proxy" % protocol
, None)
65 proxies
[protocol
] = proxy
69 def _make_request(self
, url
, baseurl
=None, headers
={}):
71 url
= urllib
.parse
.urljoin(baseurl
, url
)
73 req
= urllib
.request
.Request(url
, method
="GET")
77 "User-Agent" : "location-downloader/@VERSION@",
81 for header
in headers
:
82 req
.add_header(header
, headers
[header
])
85 for protocol
in self
.proxies
:
86 req
.set_proxy(self
.proxies
[protocol
], protocol
)
90 def _send_request(self
, req
, **kwargs
):
92 log
.debug("HTTP %s Request to %s" % (req
.method
, req
.host
))
93 log
.debug(" URL: %s" % req
.full_url
)
94 log
.debug(" Headers:")
95 for k
, v
in req
.header_items():
96 log
.debug(" %s: %s" % (k
, v
))
99 res
= urllib
.request
.urlopen(req
, **kwargs
)
101 except urllib
.error
.HTTPError
as e
:
102 # Log response headers
103 log
.debug("HTTP Response: %s" % e
.code
)
104 log
.debug(" Headers:")
105 for header
in e
.headers
:
106 log
.debug(" %s: %s" % (header
, e
.headers
[header
]))
108 # Raise all other errors
111 # Log response headers
112 log
.debug("HTTP Response: %s" % res
.code
)
113 log
.debug(" Headers:")
114 for k
, v
in res
.getheaders():
115 log
.debug(" %s: %s" % (k
, v
))
119 def download(self
, url
, public_key
, timestamp
=None, **kwargs
):
123 headers
["If-Modified-Since"] = timestamp
.strftime(
124 "%a, %d %b %Y %H:%M:%S GMT",
127 t
= tempfile
.NamedTemporaryFile(delete
=False)
130 for mirror
in self
.mirrors
:
131 # Prepare HTTP request
132 req
= self
._make
_request
(url
, baseurl
=mirror
, headers
=headers
)
135 with self
._send
_request
(req
) as res
:
136 decompressor
= lzma
.LZMADecompressor()
145 buf
= decompressor
.decompress(buf
)
149 # Write all data to disk
152 # Catch decompression errors
153 except lzma
.LZMAError
as e
:
154 log
.warning("Could not decompress downloaded file: %s" % e
)
157 except urllib
.error
.HTTPError
as e
:
158 # The file on the server was too old
160 log
.warning("%s is serving an outdated database. Trying next mirror..." % mirror
)
162 # Log any other HTTP errors
164 log
.warning("%s reported: %s" % (mirror
, e
))
166 # Throw away any downloaded content and try again
170 # Check if the downloaded database is recent
171 if not self
._check
_database
(t
, public_key
, timestamp
):
172 log
.warning("Downloaded database is outdated. Trying next mirror...")
174 # Throw away the data and try again
178 # Return temporary file
181 raise FileNotFoundError(url
)
183 def _check_database(self
, f
, public_key
, timestamp
=None):
185 Checks the downloaded database if it can be opened,
186 verified and if it is recent enough
188 log
.debug("Opening downloaded database at %s" % f
.name
)
190 db
= location
.Database(f
.name
)
192 # Database is not recent
193 if timestamp
and db
.created_at
< timestamp
.timestamp():
196 log
.info("Downloaded new database from %s" % (time
.strftime(
197 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
200 # Verify the database
201 with
open(public_key
, "r") as f
:
203 log
.error("Could not verify database")
211 self
.downloader
= Downloader(mirrors
=MIRRORS
)
214 parser
= argparse
.ArgumentParser(
215 description
=_("Location Downloader Command Line Interface"),
217 subparsers
= parser
.add_subparsers()
219 # Global configuration flags
220 parser
.add_argument("--debug", action
="store_true",
221 help=_("Enable debug output"))
222 parser
.add_argument("--quiet", action
="store_true",
223 help=_("Enable quiet mode"))
226 parser
.add_argument("--version", action
="version",
227 version
="%(prog)s @VERSION@")
230 parser
.add_argument("--database", "-d",
231 default
="@databasedir@/database.db", help=_("Path to database"),
235 parser
.add_argument("--public-key", "-k",
236 default
="@databasedir@/signing-key.pem", help=_("Public Signing Key"),
240 update
= subparsers
.add_parser("update", help=_("Update database"))
241 update
.set_defaults(func
=self
.handle_update
)
244 verify
= subparsers
.add_parser("verify",
245 help=_("Verify the downloaded database"))
246 verify
.set_defaults(func
=self
.handle_verify
)
248 args
= parser
.parse_args()
252 location
.logger
.set_level(logging
.DEBUG
)
254 location
.logger
.set_level(logging
.WARNING
)
256 # Print usage if no action was given
257 if not "func" in args
:
264 # Parse command line arguments
265 args
= self
.parse_cli()
268 ret
= args
.func(args
)
270 # Return with exit code
274 # Otherwise just exit
277 def handle_update(self
, ns
):
278 # Fetch the version we need from DNS
279 t
= location
.discover_latest_version()
281 # Parse timestamp into datetime format
283 timestamp
= datetime
.datetime
.fromtimestamp(t
)
289 db
= location
.Database(ns
.database
)
291 # Check if we are already on the latest version
292 if db
.created_at
>= timestamp
.timestamp():
293 log
.info("Already on the latest version")
296 except FileNotFoundError
as e
:
299 # Try downloading a new database
301 t
= self
.downloader
.download(DATABASE_FILENAME
,
302 public_key
=ns
.public_key
, timestamp
=timestamp
)
304 # If no file could be downloaded, log a message
305 except FileNotFoundError
as e
:
306 log
.error("Could not download a new database")
309 # If we have not received a new file, there is nothing to do
313 # Write temporary file to destination
314 shutil
.copyfile(t
.name
, ns
.database
)
316 # Remove temporary file
321 def handle_verify(self
, ns
):
323 db
= location
.Database(ns
.database
)
324 except FileNotFoundError
as e
:
325 log
.error("%s: %s" % (ns
.database
, e
))
328 # Verify the database
329 with
open(ns
.public_key
, "r") as f
:
331 log
.error("Could not verify database")
335 log
.debug("Database successfully verified")
340 # Run the command line interface