Don't abort on https or other unknown download URL schemes
[zeroinstall.git] / zeroinstall / injector / fetch.py
blob0c203368e8e735b62d61c254906e08c9a27a44d8
1 """
2 Downloads feeds, keys, packages and icons.
3 """
5 # Copyright (C) 2008, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 import os, sys
9 from logging import info, debug, warn
11 from zeroinstall.support import tasks, basedir
12 from zeroinstall.injector.namespaces import XMLNS_IFACE, config_site
13 from zeroinstall.injector.model import DownloadSource, Recipe, SafeException, network_offline, escape
14 from zeroinstall.injector.iface_cache import PendingFeed, ReplayAttack
15 from zeroinstall.injector.handler import NoTrustedKeys
17 def _escape_slashes(path):
18 return path.replace('/', '%23')
20 def _get_feed_dir(feed):
21 """The algorithm from 0mirror."""
22 if '#' in feed:
23 raise SafeException("Invalid URL '%s'" % feed)
24 scheme, rest = feed.split('://', 1)
25 domain, rest = rest.split('/', 1)
26 for x in [scheme, domain, rest]:
27 if not x or x.startswith(','):
28 raise SafeException("Invalid URL '%s'" % feed)
29 return os.path.join('feeds', scheme, domain, _escape_slashes(rest))
31 class Fetcher(object):
32 """Downloads and stores various things.
33 @ivar handler: handler to use for user-interaction
34 @type handler: L{handler.Handler}
35 @ivar feed_mirror: the base URL of a mirror site for keys and feeds
36 @type feed_mirror: str
37 """
38 __slots__ = ['handler', 'feed_mirror']
40 def __init__(self, handler):
41 self.handler = handler
42 self.feed_mirror = "http://roscidus.com/0mirror"
44 @tasks.async
45 def cook(self, required_digest, recipe, stores, force = False, impl_hint = None):
46 """Follow a Recipe.
47 @param impl_hint: the Implementation this is for (if any) as a hint for the GUI
48 @see: L{download_impl} uses this method when appropriate"""
49 # Maybe we're taking this metaphor too far?
51 # Start downloading all the ingredients.
52 downloads = {} # Downloads that are not yet successful
53 streams = {} # Streams collected from successful downloads
55 # Start a download for each ingredient
56 blockers = []
57 for step in recipe.steps:
58 blocker, stream = self.download_archive(step, force = force, impl_hint = impl_hint)
59 assert stream
60 blockers.append(blocker)
61 streams[step] = stream
63 while blockers:
64 yield blockers
65 tasks.check(blockers)
66 blockers = [b for b in blockers if not b.happened]
68 from zeroinstall.zerostore import unpack
70 # Create an empty directory for the new implementation
71 store = stores.stores[0]
72 tmpdir = store.get_tmp_dir_for(required_digest)
73 try:
74 # Unpack each of the downloaded archives into it in turn
75 for step in recipe.steps:
76 stream = streams[step]
77 stream.seek(0)
78 unpack.unpack_archive_over(step.url, stream, tmpdir, step.extract)
79 # Check that the result is correct and store it in the cache
80 store.check_manifest_and_rename(required_digest, tmpdir)
81 tmpdir = None
82 finally:
83 # If unpacking fails, remove the temporary directory
84 if tmpdir is not None:
85 from zeroinstall import support
86 support.ro_rmtree(tmpdir)
88 def get_feed_mirror(self, url):
89 """Return the URL of a mirror for this feed."""
90 return '%s/%s/latest.xml' % (self.feed_mirror, _get_feed_dir(url))
92 def download_and_import_feed(self, feed_url, iface_cache, force = False):
93 """Download the feed, download any required keys, confirm trust if needed and import.
94 @param feed_url: the feed to be downloaded
95 @type feed_url: str
96 @param iface_cache: cache in which to store the feed
97 @type iface_cache: L{iface_cache.IfaceCache}
98 @param force: whether to abort and restart an existing download"""
100 debug("download_and_import_feed %s (force = %d)", feed_url, force)
101 assert not feed_url.startswith('/')
103 primary = self._download_and_import_feed(feed_url, iface_cache, force, use_mirror = False)
105 @tasks.named_async("monitor feed downloads for " + feed_url)
106 def wait_for_downloads(primary):
107 # Download just the upstream feed, unless it takes too long...
108 timeout = tasks.TimeoutBlocker(5, 'Mirror timeout') # 5 seconds
110 yield primary, timeout
111 tasks.check(timeout)
113 try:
114 tasks.check(primary)
115 if primary.happened:
116 return # OK, primary succeeded!
117 # OK, maybe it's just being slow...
118 info("Feed download from %s is taking a long time. Trying mirror too...", feed_url)
119 primary_ex = None
120 except NoTrustedKeys, ex:
121 raise # Don't bother trying the mirror if we have a trust problem
122 except ReplayAttack, ex:
123 raise # Don't bother trying the mirror if we have a replay attack
124 except SafeException, ex:
125 # Primary failed
126 primary = None
127 primary_ex = ex
128 warn("Trying mirror, as feed download from %s failed: %s", feed_url, ex)
130 # Start downloading from mirror...
131 mirror = self._download_and_import_feed(feed_url, iface_cache, force, use_mirror = True)
133 # Wait until both mirror and primary tasks are complete...
134 while True:
135 blockers = filter(None, [primary, mirror])
136 if not blockers:
137 break
138 yield blockers
140 if primary:
141 try:
142 tasks.check(primary)
143 if primary.happened:
144 primary = None
145 # No point carrying on with the mirror once the primary has succeeded
146 if mirror:
147 info("Primary feed download succeeded; aborting mirror download for " + feed_url)
148 mirror.dl.abort()
149 except SafeException, ex:
150 primary = None
151 primary_ex = ex
152 info("Feed download from %s failed; still trying mirror: %s", feed_url, ex)
154 if mirror:
155 try:
156 tasks.check(mirror)
157 if mirror.happened:
158 mirror = None
159 if primary_ex:
160 # We already warned; no need to raise an exception too,
161 # as the mirror download succeeded.
162 primary_ex = None
163 except ReplayAttack, ex:
164 info("Version from mirror is older than cached version; ignoring it: %s", ex)
165 mirror = None
166 primary_ex = None
167 except SafeException, ex:
168 info("Mirror download failed: %s", ex)
169 mirror = None
171 if primary_ex:
172 raise primary_ex
174 return wait_for_downloads(primary)
176 def _download_and_import_feed(self, feed_url, iface_cache, force, use_mirror):
177 """Download and import a feed.
178 @param use_mirror: False to use primary location; True to use mirror."""
179 if use_mirror:
180 url = self.get_feed_mirror(feed_url)
181 else:
182 url = feed_url
184 dl = self.handler.get_download(url, force = force, hint = feed_url)
185 stream = dl.tempfile
187 @tasks.named_async("fetch_feed " + url)
188 def fetch_feed():
189 yield dl.downloaded
190 tasks.check(dl.downloaded)
192 pending = PendingFeed(feed_url, stream)
194 if use_mirror:
195 # If we got the feed from a mirror, get the key from there too
196 key_mirror = self.feed_mirror + '/keys/'
197 else:
198 key_mirror = None
200 keys_downloaded = tasks.Task(pending.download_keys(self.handler, feed_hint = feed_url, key_mirror = key_mirror), "download keys for " + feed_url)
201 yield keys_downloaded.finished
202 tasks.check(keys_downloaded.finished)
204 iface = iface_cache.get_interface(pending.url)
205 if not iface_cache.update_interface_if_trusted(iface, pending.sigs, pending.new_xml):
206 blocker = self.handler.confirm_trust_keys(iface, pending.sigs, pending.new_xml)
207 if blocker:
208 yield blocker
209 tasks.check(blocker)
210 if not iface_cache.update_interface_if_trusted(iface, pending.sigs, pending.new_xml):
211 raise NoTrustedKeys("No signing keys trusted; not importing")
213 task = fetch_feed()
214 task.dl = dl
215 return task
217 def download_impl(self, impl, retrieval_method, stores, force = False):
218 """Download an implementation.
219 @param impl: the selected implementation
220 @type impl: L{model.ZeroInstallImplementation}
221 @param retrieval_method: a way of getting the implementation (e.g. an Archive or a Recipe)
222 @type retrieval_method: L{model.RetrievalMethod}
223 @param stores: where to store the downloaded implementation
224 @type stores: L{zerostore.Stores}
225 @param force: whether to abort and restart an existing download
226 @rtype: L{tasks.Blocker}"""
227 assert impl
228 assert retrieval_method
230 from zeroinstall.zerostore import manifest
231 alg = impl.id.split('=', 1)[0]
232 if alg not in manifest.algorithms:
233 raise SafeException("Unknown digest algorithm '%s' for '%s' version %s" %
234 (alg, impl.feed.get_name(), impl.get_version()))
236 @tasks.async
237 def download_impl():
238 if isinstance(retrieval_method, DownloadSource):
239 blocker, stream = self.download_archive(retrieval_method, force = force, impl_hint = impl)
240 yield blocker
241 tasks.check(blocker)
243 stream.seek(0)
244 self._add_to_cache(stores, retrieval_method, stream)
245 elif isinstance(retrieval_method, Recipe):
246 blocker = self.cook(impl.id, retrieval_method, stores, force, impl_hint = impl)
247 yield blocker
248 tasks.check(blocker)
249 else:
250 raise Exception("Unknown download type for '%s'" % retrieval_method)
252 self.handler.impl_added_to_store(impl)
253 return download_impl()
255 def _add_to_cache(self, stores, retrieval_method, stream):
256 assert isinstance(retrieval_method, DownloadSource)
257 required_digest = retrieval_method.implementation.id
258 url = retrieval_method.url
259 stores.add_archive_to_cache(required_digest, stream, retrieval_method.url, retrieval_method.extract,
260 type = retrieval_method.type, start_offset = retrieval_method.start_offset or 0)
262 def download_archive(self, download_source, force = False, impl_hint = None):
263 """Fetch an archive. You should normally call L{download_impl}
264 instead, since it handles other kinds of retrieval method too."""
265 from zeroinstall.zerostore import unpack
267 url = download_source.url
268 if not (url.startswith('http:') or url.startswith('https:') or url.startswith('ftp:')):
269 raise SafeException("Unknown scheme in download URL '%s'" % url)
271 mime_type = download_source.type
272 if not mime_type:
273 mime_type = unpack.type_from_url(download_source.url)
274 if not mime_type:
275 raise SafeException("No 'type' attribute on archive, and I can't guess from the name (%s)" % download_source.url)
276 unpack.check_type_ok(mime_type)
277 dl = self.handler.get_download(download_source.url, force = force, hint = impl_hint)
278 dl.expected_size = download_source.size + (download_source.start_offset or 0)
279 return (dl.downloaded, dl.tempfile)
281 def download_icon(self, interface, force = False):
282 """Download an icon for this interface and add it to the
283 icon cache. If the interface has no icon or we are offline, do nothing.
284 @return: the task doing the import, or None
285 @rtype: L{tasks.Task}"""
286 debug("download_icon %s (force = %d)", interface, force)
288 # Find a suitable icon to download
289 for icon in interface.get_metadata(XMLNS_IFACE, 'icon'):
290 type = icon.getAttribute('type')
291 if type != 'image/png':
292 debug('Skipping non-PNG icon')
293 continue
294 source = icon.getAttribute('href')
295 if source:
296 break
297 warn('Missing "href" attribute on <icon> in %s', interface)
298 else:
299 info('No PNG icons found in %s', interface)
300 return
302 dl = self.handler.get_download(source, force = force, hint = interface)
304 @tasks.async
305 def download_and_add_icon():
306 stream = dl.tempfile
307 yield dl.downloaded
308 try:
309 tasks.check(dl.downloaded)
310 stream.seek(0)
312 import shutil
313 icons_cache = basedir.save_cache_path(config_site, 'interface_icons')
314 icon_file = file(os.path.join(icons_cache, escape(interface.uri)), 'w')
315 shutil.copyfileobj(stream, icon_file)
316 except Exception, ex:
317 self.handler.report_error(ex)
319 return download_and_add_icon()
321 def download_impls(self, implementations, stores):
322 """Download the given implementations, choosing a suitable retrieval method for each."""
323 blockers = []
325 to_download = []
326 for impl in implementations:
327 debug("start_downloading_impls: for %s get %s", impl.feed, impl)
328 source = self.get_best_source(impl)
329 if not source:
330 raise SafeException("Implementation " + impl.id + " of "
331 "interface " + impl.feed.get_name() + " cannot be "
332 "downloaded (no download locations given in "
333 "interface!)")
334 to_download.append((impl, source))
336 for impl, source in to_download:
337 blockers.append(self.download_impl(impl, source, stores))
339 if not blockers:
340 return None
342 @tasks.async
343 def download_impls(blockers):
344 # Record the first error log the rest
345 error = []
346 def dl_error(ex, tb = None):
347 if error:
348 self.handler.report_error(ex)
349 else:
350 error.append(ex)
351 while blockers:
352 yield blockers
353 tasks.check(blockers, dl_error)
355 blockers = [b for b in blockers if not b.happened]
356 if error:
357 raise error[0]
359 return download_impls(blockers)
361 def get_best_source(self, impl):
362 """Return the best download source for this implementation.
363 @rtype: L{model.RetrievalMethod}"""
364 if impl.download_sources:
365 return impl.download_sources[0]
366 return None