2 from twisted.internet import gtk2reactor
4 from twisted.internet import reactor
10 import os, sys, subprocess, locale, urllib2, gobject, time, pickle, json
12 from twisted.web.client import Agent, ResponseDone
13 from twisted.web.http_headers import Headers
14 from twisted.internet.protocol import Protocol
15 from twisted.internet.ssl import ClientContextFactory
17 from OpenSSL.SSL import Context, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT
18 from OpenSSL.crypto import load_certificate, FILETYPE_PEM
20 class VerifyTorProjectCert(ClientContextFactory):
22 def __init__(self, torproject_pem):
23 self.torproject_ca = load_certificate(FILETYPE_PEM, open(torproject_pem, 'r').read())
25 def getContext(self, host, port):
26 ctx = ClientContextFactory.getContext(self)
27 ctx.set_verify_depth(0)
28 ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
31 def verifyHostname(self, connection, cert, errno, depth, preverifyOK):
32 return cert.digest('sha256') == self.torproject_ca.digest('sha256')
35 class TorBrowserLauncher:
38 self.set_gui(None, '', [])
39 self.discover_arch_lang()
41 self.mkdir(self.paths['dir']['download'])
42 self.mkdir(self.paths['dir']['tbb'])
44 # allow buttons to have icons
46 settings = gtk.settings_get_default()
47 settings.props.gtk_button_images = True
51 self.launch_gui = True
53 # if we haven't already hit an error
54 if self.gui != 'error':
56 if self.load_settings():
57 self.build_paths(self.settings['latest_version'])
59 # how long was it since the last update check?
60 # 86400 seconds = 24 hours
61 current_timestamp = int(time.time())
62 if current_timestamp - self.settings['last_update_check_timestamp'] >= 86400:
64 print 'Checking for update'
65 self.set_gui('task', "Checking for Tor Browser update.",
66 ['download_update_check',
70 # no need to check for update
71 print 'Checked for update within 24 hours, skipping'
75 self.set_gui('error', "Error loading settings. Delete ~/.torbrowser and try again.", [])
79 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
80 self.window.set_title("Tor Browser")
81 self.window.set_position(gtk.WIN_POS_CENTER)
82 self.window.set_border_width(10)
83 self.window.connect("delete_event", self.delete_event)
84 self.window.connect("destroy", self.destroy)
86 # build the rest of the UI
91 def start_launcher(self):
92 # is TBB already installed?
93 if os.path.isfile(self.paths['file']['start']) and os.access(self.paths['file']['start'], os.X_OK):
94 if self.settings['installed_version'] == self.settings['latest_version']:
95 # current version of tbb is installed, launch it
97 self.launch_gui = False
98 elif self.settings['installed_version'] < self.settings['latest_version']:
99 # there is a tbb upgrade available
100 self.set_gui('task', "Your Tor Browser is out of date.",
102 'download_tarball_sig',
107 # for some reason the installed tbb is newer than the current version?
108 self.set_gui('error', "Something is wrong. The version of Tor Browser Bundle you have installed is newer than the current version?", [])
112 # are the tarball and sig already downloaded?
113 if os.path.isfile(self.paths['file']['tarball']) and os.path.isfile(self.paths['file']['tarball_sig']):
114 # start the gui with verify
115 self.set_gui('task', "Installing Tor Browser.",
122 self.set_gui('task', "Downloading and installing Tor Browser.",
124 'download_tarball_sig',
129 # discover the architecture and language
130 def discover_arch_lang(self):
131 # figure out the architecture
132 (sysname, nodename, release, version, machine) = os.uname()
133 self.architecture = machine
135 # figure out the language
136 available_languages = ['en-US', 'ar', 'de', 'es-ES', 'fa', 'fr', 'it', 'ko', 'nl', 'pl', 'pt-PT', 'ru', 'vi', 'zh-CN']
137 default_locale = locale.getdefaultlocale()[0]
138 if default_locale == None:
139 self.language = 'en-US'
141 self.language = default_locale.replace('_', '-')
142 if self.language not in available_languages:
143 self.language = self.language.split('-')[0]
144 if self.language not in available_languages:
145 for l in available_languages:
146 if l[0:2] == self.language:
148 # if language isn't available, default to english
149 if self.language not in available_languages:
150 self.language = 'en-US'
152 # build all relevant paths
153 def build_paths(self, tbb_version = None):
154 homedir = os.getenv('HOME')
156 homedir = '/tmp/.torbrowser-'+os.getenv('USER')
157 if os.path.exists(homedir) == False:
159 os.mkdir(homedir, 0700)
161 self.set_gui('error', "Error creating %s" % homedir, [], False)
162 if not os.access(homedir, os.W_OK):
163 self.set_gui('error', "%s is not writable" % homedir, [], False)
165 tbb_data = '%s/.torbrowser' % homedir
168 tarball_filename = 'tor-browser-gnu-linux-'+self.architecture+'-'+tbb_version+'-dev-'+self.language+'.tar.gz'
169 self.paths['file']['tarball'] = tbb_data+'/download/'+tarball_filename
170 self.paths['file']['tarball_sig'] = tbb_data+'/download/'+tarball_filename+'.asc'
171 self.paths['url']['tarball'] = 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename
172 self.paths['url']['tarball_sig'] = 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename+'.asc'
173 self.paths['filename']['tarball'] = tarball_filename
174 self.paths['filename']['tarball_sig'] = tarball_filename+'.asc'
180 'download': tbb_data+'/download',
181 'tbb': tbb_data+'/tbb/'+self.architecture,
182 'gpg': tbb_data+'/gpgtmp'
185 'settings': tbb_data+'/settings',
186 'version': tbb_data+'/version',
187 'start': tbb_data+'/tbb/'+self.architecture+'/tor-browser_'+self.language+'/start-tor-browser',
188 'update_check': tbb_data+'/download/RecommendedTBBVersions',
189 'verify': '/usr/share/torbrowser-launcher/verify.sh',
190 'torproject_pem': '/usr/share/torbrowser-launcher/torproject.pem'
193 'update_check': 'https://check.torproject.org/RecommendedTBBVersions'
199 def mkdir(self, path):
201 if os.path.exists(path) == False:
202 os.makedirs(path, 0700)
204 self.set_gui('error', "Cannot create directory %s" % path, [], False)
205 if not os.access(path, os.W_OK):
206 self.set_gui('error', "%s is not writable" % path, [], False)
208 # there are different GUIs that might appear, this sets which one we want
209 def set_gui(self, gui, message, tasks, autostart=True):
211 self.gui_message = message
212 self.gui_tasks = tasks
214 self.gui_autostart = autostart
216 # set all gtk variables to False
218 if hasattr(self, 'box'):
223 self.progressbar = False
224 self.button_box = False
225 self.start_button = False
226 self.exit_button = False
228 # build the application's UI
230 self.box = gtk.VBox(False, 20)
231 self.window.add(self.box)
233 if self.gui == 'error':
235 self.label = gtk.Label( self.gui_message )
236 self.label.set_line_wrap(True)
237 self.box.pack_start(self.label, True, True, 0)
240 #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.")
241 #self.label2.set_line_wrap(True)
242 #self.box.pack_start(self.label2, True, True, 0)
246 exit_image = gtk.Image()
247 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
248 self.exit_button = gtk.Button("Exit")
249 self.exit_button.set_image(exit_image)
250 self.exit_button.connect("clicked", self.destroy, None)
251 self.box.add(self.exit_button)
252 self.exit_button.show()
254 elif self.gui == 'task':
256 self.label = gtk.Label( self.gui_message )
257 self.label.set_line_wrap(True)
258 self.box.pack_start(self.label, True, True, 0)
262 self.progressbar = gtk.ProgressBar(adjustment=None)
263 self.progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
264 self.progressbar.set_pulse_step(0.01)
265 self.box.pack_start(self.progressbar, True, True, 0)
268 self.button_box = gtk.HButtonBox()
269 self.button_box.set_layout(gtk.BUTTONBOX_SPREAD)
270 self.box.pack_start(self.button_box, True, True, 0)
271 self.button_box.show()
274 start_image = gtk.Image()
275 start_image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
276 self.start_button = gtk.Button("Start")
277 self.start_button.set_image(start_image)
278 self.start_button.connect("clicked", self.start, None)
279 self.button_box.add(self.start_button)
280 if not self.gui_autostart:
281 self.start_button.show()
284 exit_image = gtk.Image()
285 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
286 self.exit_button = gtk.Button("Exit")
287 self.exit_button.set_image(exit_image)
288 self.exit_button.connect("clicked", self.destroy, None)
289 self.button_box.add(self.exit_button)
290 self.exit_button.show()
295 if self.gui_autostart:
298 # start button clicked, begin tasks
299 def start(self, widget, data=None):
300 # disable the start button
301 if self.start_button:
302 self.start_button.set_sensitive(False)
304 # start running tasks
307 # run the next task in the task list
311 if self.gui_task_i >= len(self.gui_tasks):
315 task = self.gui_tasks[self.gui_task_i]
317 # get ready for the next task
320 if task == 'download_update_check':
321 print 'Downloading '+self.paths['url']['update_check']
322 self.download('update check', self.paths['url']['update_check'], self.paths['file']['update_check'])
324 if task == 'attempt_update':
325 print 'Checking to see if update it needed'
326 self.attempt_update()
328 elif task == 'download_tarball':
329 print 'Downloading '+self.paths['url']['tarball']
330 self.download('tarball', self.paths['url']['tarball'], self.paths['file']['tarball'])
332 elif task == 'download_tarball_sig':
333 print 'Downloading '+self.paths['url']['tarball_sig']
334 self.download('signature', self.paths['url']['tarball_sig'], self.paths['file']['tarball_sig'])
336 elif task == 'verify':
337 print 'Verifying signature'
340 elif task == 'extract':
341 print 'Extracting '+self.paths['filename']['tarball']
345 print 'Running '+self.paths['file']['start']
348 elif task == 'start_over':
349 print 'Starting download over again'
352 def response_received(self, response):
353 class FileDownloader(Protocol):
354 def __init__(self, file, total, progress, done_cb):
358 self.progress = progress
359 self.all_done = done_cb
361 def dataReceived(self, bytes):
362 self.file.write(bytes)
363 self.so_far += len(bytes)
364 percent = float(self.so_far) / float(self.total)
365 self.progress.set_fraction(percent)
366 amount = float(self.so_far)
368 for (size, unit) in [(1024 * 1024, "MiB"), (1024, "KiB")]:
371 amount = amount / float(size)
374 self.progress.set_text('Downloaded %2.1f%% (%2.1f %s)' % ((percent * 100.0), amount, units))
376 def connectionLost(self, reason):
377 print 'Finished receiving body:', reason.getErrorMessage()
378 self.all_done(reason)
380 dl = FileDownloader(self.file_download, response.length, self.progressbar, self.response_finished)
381 response.deliverBody(dl)
383 def response_finished(self, msg):
384 if msg.check(ResponseDone):
385 self.file_download.close()
390 print "FINISHED", msg
391 ## FIXME handle errors
393 def download_error(self, f):
394 print "Download error", f
395 self.set_gui('error', "Error starting download:\n\n%s\n\nAre you connected to the internet?" % f.value, [], False)
399 def download(self, name, url, path):
400 # initialize the progress bar
401 self.progressbar.set_fraction(0)
402 self.progressbar.set_text('Downloading '+name)
403 self.progressbar.show()
406 agent = Agent(reactor, VerifyTorProjectCert(self.paths['file']['torproject_pem']))
407 d = agent.request('GET', url,
408 Headers({'User-Agent': ['torbrowser-launcher']}),
411 self.file_download = open(path, 'w')
412 d.addCallback(self.response_received).addErrback(self.download_error)
414 def attempt_update(self):
415 # load the update check file
417 versions = json.load(open(self.paths['file']['update_check']))
418 latest_version = None
421 for version in versions:
422 if str(version).find(end) != -1:
423 latest_version = str(version)
426 self.settings['latest_version'] = latest_version[:-len(end)]
427 self.settings['last_update_check_timestamp'] = int(time.time())
429 self.build_paths(self.settings['latest_version'])
430 self.start_launcher()
433 # failed to find the latest version
434 self.set_gui('error', "Error checking for updates.", [], False)
437 # not a valid JSON object
438 self.set_gui('error', "Error checking for updates.", [], False)
445 # initialize the progress bar
446 self.progressbar.set_fraction(0)
447 self.progressbar.set_text('Verifying Signature')
448 self.progressbar.show()
450 p = subprocess.Popen([self.paths['file']['verify'], self.paths['dir']['gpg'], self.paths['file']['tarball_sig']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
451 self.pulse_until_process_exits(p)
453 output = p.stdout.read()
455 if 'Good signature' in output:
458 self.progressbar.hide()
459 self.label.set_text("SIGNATURE VERIFICATION FAILED!\n\nYou might be under attack, or there might just be a networking problem. Click Start try the download again.")
460 self.gui_tasks = ['start_over']
462 self.start_button.show()
463 self.start_button.set_sensitive(True)
466 # initialize the progress bar
467 self.progressbar.set_fraction(0)
468 self.progressbar.set_text('Installing')
469 self.progressbar.show()
471 p = subprocess.Popen(['tar', '-xf', self.paths['file']['tarball'], '-C', self.paths['dir']['tbb']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
472 self.pulse_until_process_exits(p)
474 # installation is finished, so save installed_version
475 self.settings['installed_version'] = self.settings['latest_version']
480 def run(self, run_next_task = True):
481 subprocess.Popen([self.paths['file']['start']])
485 # make the progress bar pulse until process p (a Popen object) finishes
486 def pulse_until_process_exits(self, p):
487 while p.poll() == None:
489 self.progressbar.pulse()
492 # start over and download TBB again
493 def start_over(self):
494 self.label.set_text("Downloading Tor Browser Bundle over again.")
495 self.gui_tasks = ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run']
500 def load_settings(self):
501 if os.path.isfile(self.paths['file']['settings']):
502 self.settings = pickle.load(open(self.paths['file']['settings']))
504 if not 'installed_version' in self.settings:
506 if not 'latest_version' in self.settings:
508 if not 'last_update_check_timestamp' in self.settings:
512 'installed_version': False,
513 'latest_version': '0',
514 'last_update_check_timestamp': 0
520 def save_settings(self):
521 pickle.dump(self.settings, open(self.paths['file']['settings'], 'w'))
525 def refresh_gtk(self):
526 while gtk.events_pending():
527 gtk.main_iteration(False)
530 def delete_event(self, widget, event, data=None):
532 def destroy(self, widget, data=None):
533 if hasattr(self, 'file_download'):
534 self.file_download.close()
537 if __name__ == "__main__":
538 tor_browser_launcher_version = '0.1'
540 print 'Tor Browser Launcher'
541 print 'version %s' % (tor_browser_launcher_version)
542 print 'https://github.com/micahflee/torbrowser-launcher'
544 app = TorBrowserLauncher()