]>
git.ipfire.org Git - people/ms/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
= "location.db.xz"
40 "https://location.ipfire.org/databases/",
44 log
= logging
.getLogger("location.downloader")
47 class Downloader(object):
48 def __init__(self
, mirrors
):
49 self
.mirrors
= list(mirrors
)
52 random
.shuffle(self
.mirrors
)
54 # Get proxies from environment
55 self
.proxies
= self
._get
_proxies
()
57 def _get_proxies(self
):
60 for protocol
in ("https", "http"):
61 proxy
= os
.environ
.get("%s_proxy" % protocol
, None)
64 proxies
[protocol
] = proxy
68 def _make_request(self
, url
, baseurl
=None, headers
={}):
70 url
= urllib
.parse
.urljoin(baseurl
, url
)
72 req
= urllib
.request
.Request(url
, method
="GET")
76 "User-Agent" : "location-downloader/@VERSION@",
80 for header
in headers
:
81 req
.add_header(header
, headers
[header
])
84 for protocol
in self
.proxies
:
85 req
.set_proxy(self
.proxies
[protocol
], protocol
)
89 def _send_request(self
, req
, **kwargs
):
91 log
.debug("HTTP %s Request to %s" % (req
.method
, req
.host
))
92 log
.debug(" URL: %s" % req
.full_url
)
93 log
.debug(" Headers:")
94 for k
, v
in req
.header_items():
95 log
.debug(" %s: %s" % (k
, v
))
98 res
= urllib
.request
.urlopen(req
, **kwargs
)
100 except urllib
.error
.HTTPError
as e
:
101 # Log response headers
102 log
.debug("HTTP Response: %s" % e
.code
)
103 log
.debug(" Headers:")
104 for header
in e
.headers
:
105 log
.debug(" %s: %s" % (header
, e
.headers
[header
]))
107 # Raise all other errors
110 # Log response headers
111 log
.debug("HTTP Response: %s" % res
.code
)
112 log
.debug(" Headers:")
113 for k
, v
in res
.getheaders():
114 log
.debug(" %s: %s" % (k
, v
))
118 def download(self
, url
, public_key
, timestamp
=None, **kwargs
):
122 headers
["If-Modified-Since"] = timestamp
.strftime(
123 "%a, %d %b %Y %H:%M:%S GMT",
126 t
= tempfile
.NamedTemporaryFile(delete
=False)
129 for mirror
in self
.mirrors
:
130 # Prepare HTTP request
131 req
= self
._make
_request
(url
, baseurl
=mirror
, headers
=headers
)
134 with self
._send
_request
(req
) as res
:
135 decompressor
= lzma
.LZMADecompressor()
144 buf
= decompressor
.decompress(buf
)
148 # Write all data to disk
151 # Catch decompression errors
152 except lzma
.LZMAError
as e
:
153 log
.warning("Could not decompress downloaded file: %s" % e
)
156 except urllib
.error
.HTTPError
as e
:
157 # The file on the server was too old
159 log
.warning("%s is serving an outdated database. Trying next mirror..." % mirror
)
161 # Log any other HTTP errors
163 log
.warning("%s reported: %s" % (mirror
, e
))
165 # Throw away any downloaded content and try again
169 # Check if the downloaded database is recent
170 if not self
._check
_database
(t
, public_key
, timestamp
):
171 log
.warning("Downloaded database is outdated. Trying next mirror...")
173 # Throw away the data and try again
177 # Return temporary file
180 raise FileNotFoundError(url
)
182 def _check_database(self
, f
, public_key
, timestamp
=None):
184 Checks the downloaded database if it can be opened,
185 verified and if it is recent enough
187 log
.debug("Opening downloaded database at %s" % f
.name
)
189 db
= location
.Database(f
.name
)
191 # Database is not recent
192 if timestamp
and db
.created_at
< timestamp
.timestamp():
195 log
.info("Downloaded new database from %s" % (time
.strftime(
196 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
199 # Verify the database
200 with
open(public_key
, "r") as f
:
202 log
.error("Could not verify database")
210 self
.downloader
= Downloader(mirrors
=MIRRORS
)
213 parser
= argparse
.ArgumentParser(
214 description
=_("Location Downloader Command Line Interface"),
216 subparsers
= parser
.add_subparsers()
218 # Global configuration flags
219 parser
.add_argument("--debug", action
="store_true",
220 help=_("Enable debug output"))
221 parser
.add_argument("--quiet", action
="store_true",
222 help=_("Enable quiet mode"))
225 parser
.add_argument("--version", action
="version",
226 version
="%(prog)s @VERSION@")
229 parser
.add_argument("--database", "-d",
230 default
="@databasedir@/database.db", help=_("Path to database"),
234 parser
.add_argument("--public-key", "-k",
235 default
="@databasedir@/signing-key.pem", help=_("Public Signing Key"),
239 update
= subparsers
.add_parser("update", help=_("Update database"))
240 update
.set_defaults(func
=self
.handle_update
)
243 verify
= subparsers
.add_parser("verify",
244 help=_("Verify the downloaded database"))
245 verify
.set_defaults(func
=self
.handle_verify
)
247 args
= parser
.parse_args()
251 location
.logger
.set_level(logging
.DEBUG
)
253 location
.logger
.set_level(logging
.WARNING
)
255 # Print usage if no action was given
256 if not "func" in args
:
263 # Parse command line arguments
264 args
= self
.parse_cli()
267 ret
= args
.func(args
)
269 # Return with exit code
273 # Otherwise just exit
276 def handle_update(self
, ns
):
277 # Fetch the version we need from DNS
278 t
= location
.discover_latest_version()
280 # Parse timestamp into datetime format
282 timestamp
= datetime
.datetime
.fromtimestamp(t
)
288 db
= location
.Database(ns
.database
)
290 # Check if we are already on the latest version
291 if db
.created_at
>= timestamp
.timestamp():
292 log
.info("Already on the latest version")
295 except FileNotFoundError
as e
:
298 # Try downloading a new database
300 t
= self
.downloader
.download(DATABASE_FILENAME
,
301 public_key
=ns
.public_key
, timestamp
=timestamp
)
303 # If no file could be downloaded, log a message
304 except FileNotFoundError
as e
:
305 log
.error("Could not download a new database")
308 # If we have not received a new file, there is nothing to do
312 # Write temporary file to destination
313 shutil
.copyfile(t
.name
, ns
.database
)
315 # Remove temporary file
320 def handle_verify(self
, ns
):
322 db
= location
.Database(ns
.database
)
323 except FileNotFoundError
as e
:
324 log
.error("%s: %s" % (ns
.database
, e
))
327 # Verify the database
328 with
open(ns
.public_key
, "r") as f
:
330 log
.error("Could not verify database")
334 log
.debug("Database successfully verified")
339 # Run the command line interface