Mark trust messages as translatable
[zeroinstall.git] / zeroinstall / injector / handler.py
blob770b26c21dc15abd0b38d6c981f8cf1c1c1600dc
1 """
2 Integrates download callbacks with an external mainloop.
3 While things are being downloaded, Zero Install returns control to your program.
4 Your mainloop is responsible for monitoring the state of the downloads and notifying
5 Zero Install when they are complete.
7 To do this, you supply a L{Handler} to the L{policy}.
8 """
10 # Copyright (C) 2009, Thomas Leonard
11 # See the README file for details, or visit http://0install.net.
13 from zeroinstall import _
14 import sys
15 from logging import debug, warn
17 from zeroinstall import NeedDownload, SafeException
18 from zeroinstall.support import tasks
19 from zeroinstall.injector import download
21 class NoTrustedKeys(SafeException):
22 """Thrown by L{Handler.confirm_trust_keys} on failure."""
23 pass
25 class Handler(object):
26 """
27 This implementation uses the GLib mainloop. Note that QT4 can use the GLib mainloop too.
29 @ivar monitored_downloads: dict of downloads in progress
30 @type monitored_downloads: {URL: L{download.Download}}
31 @ivar n_completed_downloads: number of downloads which have finished for GUIs, etc (can be reset as desired).
32 @type n_completed_downloads: int
33 @ivar total_bytes_downloaded: informational counter for GUIs, etc (can be reset as desired). Updated when download finishes.
34 @type total_bytes_downloaded: int
35 """
37 __slots__ = ['monitored_downloads', '_loop', 'dry_run', 'total_bytes_downloaded', 'n_completed_downloads', '_current_confirm']
39 def __init__(self, mainloop = None, dry_run = False):
40 self.monitored_downloads = {}
41 self._loop = None
42 self.dry_run = dry_run
43 self.n_completed_downloads = 0
44 self.total_bytes_downloaded = 0
45 self._current_confirm = None
47 def monitor_download(self, dl):
48 """Called when a new L{download} is started.
49 This is mainly used by the GUI to display the progress bar."""
50 dl.start()
51 self.monitored_downloads[dl.url] = dl
52 self.downloads_changed()
54 @tasks.async
55 def download_done_stats():
56 yield dl.downloaded
57 # NB: we don't check for exceptions here; someone else should be doing that
58 try:
59 self.n_completed_downloads += 1
60 self.total_bytes_downloaded += dl.get_bytes_downloaded_so_far()
61 del self.monitored_downloads[dl.url]
62 self.downloads_changed()
63 except Exception, ex:
64 self.report_error(ex)
65 download_done_stats()
67 def impl_added_to_store(self, impl):
68 """Called by the L{fetch.Fetcher} when adding an implementation.
69 The GUI uses this to update its display.
70 @param impl: the implementation which has been added
71 @type impl: L{model.Implementation}
72 """
73 pass
75 def downloads_changed(self):
76 """This is just for the GUI to override to update its display."""
77 pass
79 def wait_for_blocker(self, blocker):
80 """Run a recursive mainloop until blocker is triggered.
81 @param blocker: event to wait on
82 @type blocker: L{tasks.Blocker}"""
83 if not blocker.happened:
84 import gobject
86 def quitter():
87 yield blocker
88 self._loop.quit()
89 quit = tasks.Task(quitter(), "quitter")
91 assert self._loop is None # Avoid recursion
92 self._loop = gobject.MainLoop(gobject.main_context_default())
93 try:
94 debug(_("Entering mainloop, waiting for %s"), blocker)
95 self._loop.run()
96 finally:
97 self._loop = None
99 assert blocker.happened, "Someone quit the main loop!"
101 tasks.check(blocker)
103 def get_download(self, url, force = False, hint = None):
104 """Return the Download object currently downloading 'url'.
105 If no download for this URL has been started, start one now (and
106 start monitoring it).
107 If the download failed and force is False, return it anyway.
108 If force is True, abort any current or failed download and start
109 a new one.
110 @rtype: L{download.Download}
112 if self.dry_run:
113 raise NeedDownload(url)
115 try:
116 dl = self.monitored_downloads[url]
117 if dl and force:
118 dl.abort()
119 raise KeyError
120 except KeyError:
121 dl = download.Download(url, hint)
122 self.monitor_download(dl)
123 return dl
125 def confirm_keys(self, pending, fetch_key_info):
126 """We don't trust any of the signatures yet. Ask the user.
127 When done update the L{trust} database, and then call L{trust.TrustDB.notify}.
128 This method just calls L{confirm_import_feed} if the handler (self) is
129 new-style, or L{confirm_trust_keys} for older classes. A class
130 is considered old-style if it overrides confirm_trust_keys and
131 not confirm_import_feed.
132 @since: 0.42
133 @arg pending: an object holding details of the updated feed
134 @type pending: L{PendingFeed}
135 @arg fetch_key_info: a function which can be used to fetch information about a key fingerprint
136 @type fetch_key_info: str -> L{Blocker}
137 @return: A blocker that triggers when the user has chosen, or None if already done.
138 @rtype: None | L{Blocker}"""
140 assert pending.sigs
142 if hasattr(self.confirm_trust_keys, 'original') or not hasattr(self.confirm_import_feed, 'original'):
143 # new-style class
144 from zeroinstall.injector import gpg
145 valid_sigs = [s for s in pending.sigs if isinstance(s, gpg.ValidSig)]
146 if not valid_sigs:
147 raise SafeException(_('No valid signatures found on "%s". Signatures:%s') %
148 (pending.url, ''.join(['\n- ' + str(s) for s in pending.sigs])))
150 # Start downloading information about the keys...
151 kfs = {}
152 for sig in valid_sigs:
153 kfs[sig] = fetch_key_info(sig.fingerprint)
155 return self._queue_confirm_import_feed(pending, kfs)
156 else:
157 # old-style class
158 from zeroinstall.injector import iface_cache
159 import warnings
160 warnings.warn(_("Should override confirm_import_feed(); using old confirm_trust_keys() for now"), DeprecationWarning, stacklevel = 2)
162 iface = iface_cache.iface_cache.get_interface(pending.url)
163 return self.confirm_trust_keys(iface, pending.sigs, pending.new_xml)
165 @tasks.async
166 def _queue_confirm_import_feed(self, pending, valid_sigs):
167 # If we're already confirming something else, wait for that to finish...
168 while self._current_confirm is not None:
169 yield self._current_confirm
171 self._current_confirm = lock = tasks.Blocker('confirm key lock')
172 try:
173 done = self.confirm_import_feed(pending, valid_sigs)
174 yield done
175 tasks.check(done)
176 finally:
177 self._current_confirm = None
178 lock.trigger()
180 @tasks.async
181 def confirm_import_feed(self, pending, valid_sigs):
182 """Sub-classes should override this method to interact with the user about new feeds.
183 If multiple feeds need confirmation, L{confirm_keys} will only invoke one instance of this
184 method at a time.
185 @param pending: the new feed to be imported
186 @type pending: L{PendingFeed}
187 @param valid_sigs: maps signatures to a list of fetchers collecting information about the key
188 @type valid_sigs: {L{gpg.ValidSig} : L{fetch.KeyInfoFetcher}}
189 @since: 0.42
190 @see: L{confirm_keys}"""
191 from zeroinstall.injector import trust
193 assert valid_sigs
195 domain = trust.domain_from_url(pending.url)
197 # Ask on stderr, because we may be writing XML to stdout
198 print >>sys.stderr, _("Feed: %s"), pending.url
199 print >>sys.stderr, _("The feed is correctly signed with the following keys:")
200 for x in valid_sigs:
201 print >>sys.stderr, "-", x
203 def text(parent):
204 text = ""
205 for node in parent.childNodes:
206 if node.nodeType == node.TEXT_NODE:
207 text = text + node.data
208 return text
210 shown = set()
211 key_info_fetchers = valid_sigs.values()
212 while key_info_fetchers:
213 old_kfs = key_info_fetchers
214 key_info_fetchers = []
215 for kf in old_kfs:
216 infos = set(kf.info) - shown
217 if infos:
218 if len(valid_sigs) > 1:
219 print "%s: " % kf.fingerprint
220 for info in infos:
221 print >>sys.stderr, "-", text(info)
222 shown.add(info)
223 if kf.blocker:
224 key_info_fetchers.append(kf)
225 if key_info_fetchers:
226 for kf in key_info_fetchers: print >>sys.stderr, kf.status
227 stdin = tasks.InputBlocker(0, 'console')
228 blockers = [kf.blocker for kf in key_info_fetchers] + [stdin]
229 yield blockers
230 for b in blockers:
231 try:
232 tasks.check(b)
233 except Exception, ex:
234 warn(_("Failed to get key info: %s"), ex)
235 if stdin.happened:
236 print >>sys.stderr, _("Skipping remaining key lookups due to input from user")
237 break
239 if len(valid_sigs) == 1:
240 print >>sys.stderr, _("Do you want to trust this key to sign feeds from '%s'?") % domain
241 else:
242 print >>sys.stderr, _("Do you want to trust all of these keys to sign feeds from '%s'?") % domain
243 while True:
244 print >>sys.stderr, _("Trust [Y/N] "),
245 i = raw_input()
246 if not i: continue
247 if i in 'Nn':
248 raise NoTrustedKeys(_('Not signed with a trusted key'))
249 if i in 'Yy':
250 break
251 for key in valid_sigs:
252 print >>sys.stderr, _("Trusting %s for %s") % (key.fingerprint, domain)
253 trust.trust_db.trust_key(key.fingerprint, domain)
255 confirm_import_feed.original = True
257 def confirm_trust_keys(self, interface, sigs, iface_xml):
258 """We don't trust any of the signatures yet. Ask the user.
259 When done update the L{trust} database, and then call L{trust.TrustDB.notify}.
260 @deprecated: see L{confirm_keys}
261 @arg interface: the interface being updated
262 @arg sigs: a list of signatures (from L{gpg.check_stream})
263 @arg iface_xml: the downloaded data (not yet trusted)
264 @return: a blocker, if confirmation will happen asynchronously, or None
265 @rtype: L{tasks.Blocker}"""
266 import warnings
267 warnings.warn(_("Use confirm_keys, not confirm_trust_keys"), DeprecationWarning, stacklevel = 2)
268 from zeroinstall.injector import trust, gpg
269 assert sigs
270 valid_sigs = [s for s in sigs if isinstance(s, gpg.ValidSig)]
271 if not valid_sigs:
272 raise SafeException('No valid signatures found on "%s". Signatures:%s' %
273 (interface.uri, ''.join(['\n- ' + str(s) for s in sigs])))
275 domain = trust.domain_from_url(interface.uri)
277 # Ask on stderr, because we may be writing XML to stdout
278 print >>sys.stderr, "\nInterface:", interface.uri
279 print >>sys.stderr, "The interface is correctly signed with the following keys:"
280 for x in valid_sigs:
281 print >>sys.stderr, "-", x
283 if len(valid_sigs) == 1:
284 print >>sys.stderr, "Do you want to trust this key to sign feeds from '%s'?" % domain
285 else:
286 print >>sys.stderr, "Do you want to trust all of these keys to sign feeds from '%s'?" % domain
287 while True:
288 print >>sys.stderr, "Trust [Y/N] ",
289 i = raw_input()
290 if not i: continue
291 if i in 'Nn':
292 raise NoTrustedKeys(_('Not signed with a trusted key'))
293 if i in 'Yy':
294 break
295 for key in valid_sigs:
296 print >>sys.stderr, "Trusting", key.fingerprint, "for", domain
297 trust.trust_db.trust_key(key.fingerprint, domain)
299 trust.trust_db.notify()
301 confirm_trust_keys.original = True # Detect if someone overrides it
303 def report_error(self, exception, tb = None):
304 """Report an exception to the user.
305 @param exception: the exception to report
306 @type exception: L{SafeException}
307 @param tb: optional traceback
308 @since: 0.25"""
309 warn("%s", str(exception) or type(exception))
310 #import traceback
311 #traceback.print_exception(exception, None, tb)