4 gettext.install('torbrowser-launcher', '/usr/share/torbrowser-launcher/locale')
6 from twisted.internet import gtk2reactor
8 from twisted.internet import reactor
14 import os, sys, subprocess, locale, urllib2, gobject, time, pickle, json, tarfile
16 from twisted.web.client import Agent, ResponseDone
17 from twisted.web.http_headers import Headers
18 from twisted.internet.protocol import Protocol
19 from twisted.internet.ssl import ClientContextFactory
21 from OpenSSL.SSL import Context, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT
22 from OpenSSL.crypto import load_certificate, FILETYPE_PEM
24 class VerifyTorProjectCert(ClientContextFactory):
26 def __init__(self, torproject_pem):
27 self.torproject_ca = load_certificate(FILETYPE_PEM, open(torproject_pem, 'r').read())
29 def getContext(self, host, port):
30 ctx = ClientContextFactory.getContext(self)
31 ctx.set_verify_depth(0)
32 ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
35 def verifyHostname(self, connection, cert, errno, depth, preverifyOK):
36 return cert.digest('sha256') == self.torproject_ca.digest('sha256')
39 class TorBrowserLauncher:
42 self.set_gui(None, '', [])
43 self.discover_arch_lang()
45 self.mkdir(self.paths['dir']['download'])
46 self.mkdir(self.paths['dir']['tbb'])
49 # allow buttons to have icons
51 settings = gtk.settings_get_default()
52 settings.props.gtk_button_images = True
56 self.launch_gui = True
58 # if we haven't already hit an error
59 if self.gui != 'error':
61 if self.load_settings():
62 self.build_paths(self.settings['latest_version'])
64 # how long was it since the last update check?
65 # 86400 seconds = 24 hours
66 current_timestamp = int(time.time())
67 if current_timestamp - self.settings['last_update_check_timestamp'] >= 86400:
69 print 'Checking for update'
70 self.set_gui('task', _("Checking for Tor Browser update."),
71 ['download_update_check',
75 # no need to check for update
76 print _('Checked for update within 24 hours, skipping')
80 self.set_gui('error', _("Error loading settings. Delete ~/.torbrowser and try again."), [])
84 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
85 self.window.set_title(_("Tor Browser"))
86 self.window.set_icon_from_file(self.paths['file']['icon'])
87 self.window.set_position(gtk.WIN_POS_CENTER)
88 self.window.set_border_width(10)
89 self.window.connect("delete_event", self.delete_event)
90 self.window.connect("destroy", self.destroy)
92 # build the rest of the UI
96 def start_launcher(self):
97 # is TBB already installed?
98 if os.path.isfile(self.paths['file']['start']) and os.access(self.paths['file']['start'], os.X_OK):
99 if self.settings['installed_version'] == self.settings['latest_version']:
100 # current version of tbb is installed, launch it
102 self.launch_gui = False
103 elif self.settings['installed_version'] < self.settings['latest_version']:
104 # there is a tbb upgrade available
105 self.set_gui('task', _("Your Tor Browser is out of date."),
107 'download_tarball_sig',
112 # for some reason the installed tbb is newer than the current version?
113 self.set_gui('error', _("Something is wrong. The version of Tor Browser Bundle you have installed is newer than the current version?"), [])
117 # are the tarball and sig already downloaded?
118 if os.path.isfile(self.paths['file']['tarball']) and os.path.isfile(self.paths['file']['tarball_sig']):
119 # start the gui with verify
120 self.set_gui('task', _("Installing Tor Browser."),
127 self.set_gui('task', _("Downloading and installing Tor Browser."),
129 'download_tarball_sig',
134 # discover the architecture and language
135 def discover_arch_lang(self):
136 # figure out the architecture
137 (sysname, nodename, release, version, machine) = os.uname()
138 self.architecture = machine
140 # figure out the language
141 available_languages = ['en-US', 'ar', 'de', 'es-ES', 'fa', 'fr', 'it', 'ko', 'nl', 'pl', 'pt-PT', 'ru', 'vi', 'zh-CN']
142 default_locale = locale.getdefaultlocale()[0]
143 if default_locale == None:
144 self.language = 'en-US'
146 self.language = default_locale.replace('_', '-')
147 if self.language not in available_languages:
148 self.language = self.language.split('-')[0]
149 if self.language not in available_languages:
150 for l in available_languages:
151 if l[0:2] == self.language:
153 # if language isn't available, default to english
154 if self.language not in available_languages:
155 self.language = 'en-US'
157 # build all relevant paths
158 def build_paths(self, tbb_version = None):
159 homedir = os.getenv('HOME')
161 homedir = '/tmp/.torbrowser-'+os.getenv('USER')
162 if os.path.exists(homedir) == False:
164 os.mkdir(homedir, 0700)
166 self.set_gui('error', _("Error creating {0}").format(homedir), [], False)
167 if not os.access(homedir, os.W_OK):
168 self.set_gui('error', _("{0} is not writable").format(homedir), [], False)
170 tbb_data = '%s/.torbrowser' % homedir
173 tarball_filename = 'tor-browser-gnu-linux-'+self.architecture+'-'+tbb_version+'-dev-'+self.language+'.tar.gz'
174 self.paths['file']['tarball'] = tbb_data+'/download/'+tarball_filename
175 self.paths['file']['tarball_sig'] = tbb_data+'/download/'+tarball_filename+'.asc'
176 self.paths['url']['tarball'] = 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename
177 self.paths['url']['tarball_sig'] = 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename+'.asc'
178 self.paths['filename']['tarball'] = tarball_filename
179 self.paths['filename']['tarball_sig'] = tarball_filename+'.asc'
185 'download': tbb_data+'/download',
186 'tbb': tbb_data+'/tbb/'+self.architecture,
187 'gnupg_homedir': tbb_data+'/gnupg_homedir'
190 'settings': tbb_data+'/settings',
191 'version': tbb_data+'/version',
192 'start': tbb_data+'/tbb/'+self.architecture+'/tor-browser_'+self.language+'/start-tor-browser',
193 'update_check': tbb_data+'/download/RecommendedTBBVersions',
194 'icon': '/usr/share/pixmaps/torbrowser80.xpm',
195 'torproject_pem': '/usr/share/torbrowser-launcher/torproject.pem',
196 'erinn_key': '/usr/share/torbrowser-launcher/erinn.asc',
197 'sebastian_key': '/usr/share/torbrowser-launcher/sebastian.asc'
200 'update_check': 'https://check.torproject.org/RecommendedTBBVersions'
206 def mkdir(self, path):
208 if os.path.exists(path) == False:
209 os.makedirs(path, 0700)
212 self.set_gui('error', _("Cannot create directory {0}").format(path), [], False)
214 if not os.access(path, os.W_OK):
215 self.set_gui('error', _("{0} is not writable").format(path), [], False)
219 # if gnupg_homedir isn't set up, set it up
220 def init_gnupg(self):
221 if not os.path.exists(self.paths['dir']['gnupg_homedir']):
222 print _('Creating GnuPG homedir'), self.paths['dir']['gnupg_homedir']
223 if self.mkdir(self.paths['dir']['gnupg_homedir']):
225 print _('Importing keys')
226 p1 = subprocess.Popen(['/usr/bin/gpg', '--homedir', self.paths['dir']['gnupg_homedir'], '--import', self.paths['file']['erinn_key']])
227 p2 = subprocess.Popen(['/usr/bin/gpg', '--homedir', self.paths['dir']['gnupg_homedir'], '--import', self.paths['file']['sebastian_key']])
228 # wait for keys to import before moving on
232 # there are different GUIs that might appear, this sets which one we want
233 def set_gui(self, gui, message, tasks, autostart=True):
235 self.gui_message = message
236 self.gui_tasks = tasks
238 self.gui_autostart = autostart
240 # set all gtk variables to False
242 if hasattr(self, 'box'):
247 self.progressbar = False
248 self.button_box = False
249 self.start_button = False
250 self.exit_button = False
252 # build the application's UI
254 self.box = gtk.VBox(False, 20)
255 self.window.add(self.box)
257 if self.gui == 'error':
259 self.label = gtk.Label( self.gui_message )
260 self.label.set_line_wrap(True)
261 self.box.pack_start(self.label, True, True, 0)
264 #self.label2 = gtk.Label("You can fix the problem by deleting:\n"+self.paths['dir']['data']+"\n\nHowever, you will lose all your bookmarks and other Tor Browser preferences.")
265 #self.label2.set_line_wrap(True)
266 #self.box.pack_start(self.label2, True, True, 0)
270 exit_image = gtk.Image()
271 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
272 self.exit_button = gtk.Button("Exit")
273 self.exit_button.set_image(exit_image)
274 self.exit_button.connect("clicked", self.destroy, None)
275 self.box.add(self.exit_button)
276 self.exit_button.show()
278 elif self.gui == 'task':
280 self.label = gtk.Label( self.gui_message )
281 self.label.set_line_wrap(True)
282 self.box.pack_start(self.label, True, True, 0)
286 self.progressbar = gtk.ProgressBar(adjustment=None)
287 self.progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
288 self.progressbar.set_pulse_step(0.01)
289 self.box.pack_start(self.progressbar, True, True, 0)
292 self.button_box = gtk.HButtonBox()
293 self.button_box.set_layout(gtk.BUTTONBOX_SPREAD)
294 self.box.pack_start(self.button_box, True, True, 0)
295 self.button_box.show()
298 start_image = gtk.Image()
299 start_image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
300 self.start_button = gtk.Button("Start")
301 self.start_button.set_image(start_image)
302 self.start_button.connect("clicked", self.start, None)
303 self.button_box.add(self.start_button)
304 if not self.gui_autostart:
305 self.start_button.show()
308 exit_image = gtk.Image()
309 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
310 self.exit_button = gtk.Button("Exit")
311 self.exit_button.set_image(exit_image)
312 self.exit_button.connect("clicked", self.destroy, None)
313 self.button_box.add(self.exit_button)
314 self.exit_button.show()
319 if self.gui_autostart:
322 # start button clicked, begin tasks
323 def start(self, widget, data=None):
324 # disable the start button
325 if self.start_button:
326 self.start_button.set_sensitive(False)
328 # start running tasks
331 # run the next task in the task list
335 if self.gui_task_i >= len(self.gui_tasks):
339 task = self.gui_tasks[self.gui_task_i]
341 # get ready for the next task
344 if task == 'download_update_check':
345 print _('Downloading'), self.paths['url']['update_check']
346 self.download('update check', self.paths['url']['update_check'], self.paths['file']['update_check'])
348 if task == 'attempt_update':
349 print _('Checking to see if update it needed')
350 self.attempt_update()
352 elif task == 'download_tarball':
353 print _('Downloading'), self.paths['url']['tarball']
354 self.download('tarball', self.paths['url']['tarball'], self.paths['file']['tarball'])
356 elif task == 'download_tarball_sig':
357 print _('Downloading'), self.paths['url']['tarball_sig']
358 self.download('signature', self.paths['url']['tarball_sig'], self.paths['file']['tarball_sig'])
360 elif task == 'verify':
361 print _('Verifying signature')
364 elif task == 'extract':
365 print _('Extracting'), self.paths['filename']['tarball']
369 print _('Running'), self.paths['file']['start']
372 elif task == 'start_over':
373 print _('Starting download over again')
376 def response_received(self, response):
377 class FileDownloader(Protocol):
378 def __init__(self, file, total, progress, done_cb):
382 self.progress = progress
383 self.all_done = done_cb
385 def dataReceived(self, bytes):
386 self.file.write(bytes)
387 self.so_far += len(bytes)
388 percent = float(self.so_far) / float(self.total)
389 self.progress.set_fraction(percent)
390 amount = float(self.so_far)
392 for (size, unit) in [(1024 * 1024, "MiB"), (1024, "KiB")]:
395 amount = amount / float(size)
398 self.progress.set_text(_('Downloaded')+(' %2.1f%% (%2.1f %s)' % ((percent * 100.0), amount, units)))
400 def connectionLost(self, reason):
401 print _('Finished receiving body:'), reason.getErrorMessage()
402 self.all_done(reason)
404 dl = FileDownloader(self.file_download, response.length, self.progressbar, self.response_finished)
405 response.deliverBody(dl)
407 def response_finished(self, msg):
408 if msg.check(ResponseDone):
409 self.file_download.close()
414 print "FINISHED", msg
415 ## FIXME handle errors
417 def download_error(self, f):
418 print _("Download error"), f
419 self.set_gui('error', _("Error starting download:\n\n{0}\n\nAre you connected to the internet?").format(f.value), [], False)
423 def download(self, name, url, path):
424 # initialize the progress bar
425 self.progressbar.set_fraction(0)
426 self.progressbar.set_text(_('Downloading {0}').format(name))
427 self.progressbar.show()
430 agent = Agent(reactor, VerifyTorProjectCert(self.paths['file']['torproject_pem']))
431 d = agent.request('GET', url,
432 Headers({'User-Agent': ['torbrowser-launcher']}),
435 self.file_download = open(path, 'w')
436 d.addCallback(self.response_received).addErrback(self.download_error)
438 if not reactor.running:
441 def attempt_update(self):
442 # load the update check file
444 versions = json.load(open(self.paths['file']['update_check']))
445 latest_version = None
448 for version in versions:
449 if str(version).find(end) != -1:
450 latest_version = str(version)
453 self.settings['latest_version'] = latest_version[:-len(end)]
454 self.settings['last_update_check_timestamp'] = int(time.time())
456 self.build_paths(self.settings['latest_version'])
457 self.start_launcher()
460 # failed to find the latest version
461 self.set_gui('error', _("Error checking for updates."), [], False)
464 # not a valid JSON object
465 self.set_gui('error', _("Error checking for updates."), [], False)
472 # initialize the progress bar
473 self.progressbar.set_fraction(0)
474 self.progressbar.set_text(_('Verifying Signature'))
475 self.progressbar.show()
477 p = subprocess.Popen(['/usr/bin/gpg', '--homedir', self.paths['dir']['gnupg_homedir'], '--verify', self.paths['file']['tarball_sig']])
478 self.pulse_until_process_exits(p)
480 if p.returncode == 0:
483 self.set_gui('task', _("SIGNATURE VERIFICATION FAILED!\n\nYou might be under attack, or there might just be a networking problem. Click Start try the download again."), ['start_over'], False)
487 if not reactor.running:
491 # initialize the progress bar
492 self.progressbar.set_fraction(0)
493 self.progressbar.set_text(_('Installing'))
494 self.progressbar.show()
497 # make sure this file is a tarfile
498 if tarfile.is_tarfile(self.paths['file']['tarball']):
499 tf = tarfile.open(self.paths['file']['tarball'])
500 tf.extractall(self.paths['dir']['tbb'])
502 self.set_gui('task', _("Tor Browser Launcher doesn't understand the file format of {0}"), ['start_over'], False)
506 # installation is finished, so save installed_version
507 self.settings['installed_version'] = self.settings['latest_version']
512 def run(self, run_next_task = True):
513 subprocess.Popen([self.paths['file']['start']])
517 # make the progress bar pulse until process p (a Popen object) finishes
518 def pulse_until_process_exits(self, p):
519 while p.poll() == None:
521 self.progressbar.pulse()
524 # start over and download TBB again
525 def start_over(self):
526 self.label.set_text(_("Downloading Tor Browser Bundle over again."))
527 self.gui_tasks = ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run']
532 def load_settings(self):
533 if os.path.isfile(self.paths['file']['settings']):
534 self.settings = pickle.load(open(self.paths['file']['settings']))
536 if not 'installed_version' in self.settings:
538 if not 'latest_version' in self.settings:
540 if not 'last_update_check_timestamp' in self.settings:
544 'installed_version': False,
545 'latest_version': '0',
546 'last_update_check_timestamp': 0
552 def save_settings(self):
553 pickle.dump(self.settings, open(self.paths['file']['settings'], 'w'))
557 def refresh_gtk(self):
558 while gtk.events_pending():
559 gtk.main_iteration(False)
562 def delete_event(self, widget, event, data=None):
564 def destroy(self, widget, data=None):
565 if hasattr(self, 'file_download'):
566 self.file_download.close()
570 if __name__ == "__main__":
571 tor_browser_launcher_version = '0.1'
573 print _('Tor Browser Launcher')
574 print _('version {0}').format(tor_browser_launcher_version)
575 print 'https://github.com/micahflee/torbrowser-launcher'
577 app = TorBrowserLauncher()