3 from twisted.internet import gtk2reactor
5 from twisted.internet import reactor
11 import os, sys, subprocess, locale, urllib2, gobject, time
13 from twisted.web.client import Agent, ResponseDone
14 from twisted.web.http_headers import Headers
15 from twisted.internet.protocol import Protocol
16 from twisted.internet.ssl import ClientContextFactory
18 from OpenSSL.SSL import Context, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT
19 from OpenSSL.crypto import load_certificate, FILETYPE_PEM
21 class VerifyTorProjectCert(ClientContextFactory):
23 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:
36 def __init__(self, current_tbb_version):
38 self.current_tbb_version = current_tbb_version
39 self.discover_arch_lang()
45 # is TBB already installed?
46 if os.path.isfile(self.paths['file']['start']) and os.access(self.paths['file']['start'], os.X_OK):
47 # does the version file exist?
48 if os.path.isfile(self.paths['file']['version']):
49 installed_tbb_version = open(self.paths['file']['version']).read().strip()
51 if installed_tbb_version == current_tbb_version:
52 # current version is tbb is installed, launch it
55 elif installed_tbb_version < self.current_tbb_version:
56 # there is a tbb upgrade available
57 self.set_gui('task', "Your Tor Browser is out of date.",
59 'download_tarball_sig',
64 # for some reason the installed tbb is newer than the current version?
65 self.set_gui('error', "Something is wrong. The version of Tor Browser Bundle you have installed is newer than the current version?", [])
68 # if tbb is installed but the version file doesn't exist, something is wrong
69 self.set_gui('error', "Something is wrong. You have the Tor Browser Bundle installed, but the version file is missing.", [])
73 # save the current version to the file
74 open(self.paths['file']['version'], 'w').write(self.current_tbb_version)
76 # are the tarball and sig already downloaded?
77 if os.path.isfile(self.paths['file']['tarball']) and os.path.isfile(self.paths['file']['tarball_sig']):
78 # start the gui with verify
79 self.set_gui('task', "Installing Tor Browser.",
86 self.set_gui('task', "Downloading and installing Tor Browser.",
88 'download_tarball_sig',
97 # discover the architecture and language
98 def discover_arch_lang(self):
99 # figure out the architecture
100 (sysname, nodename, release, version, machine) = os.uname()
101 self.architecture = machine
103 # figure out the language
104 available_languages = ['en-US', 'ar', 'de', 'es-ES', 'fa', 'fr', 'it', 'ko', 'nl', 'pl', 'pt-PT', 'ru', 'vi', 'zh-CN']
105 default_locale = locale.getdefaultlocale()[0]
106 if default_locale == None:
107 self.language = 'en-US'
109 self.language = default_locale.replace('_', '-')
110 if self.language not in available_languages:
111 self.language = self.language.split('-')[0]
112 if self.language not in available_languages:
113 for l in available_languages:
114 if l[0:2] == self.language:
116 # if language isn't available, default to english
117 if self.language not in available_languages:
118 self.language = 'en-US'
120 # build all relevant paths
121 def build_paths(self):
122 tbb_data = os.getenv('HOME')+'/.torbrowser'
123 tarball_filename = 'tor-browser-gnu-linux-'+self.architecture+'-'+self.current_tbb_version+'-dev-'+self.language+'.tar.gz'
128 'download': tbb_data+'/download',
129 'tbb': tbb_data+'/tbb/'+self.architecture,
130 'gpg': tbb_data+'/gpgtmp'
133 'version': tbb_data+'/version',
134 'start': tbb_data+'/tbb/'+self.architecture+'/tor-browser_'+self.language+'/start-tor-browser',
135 'tarball': tbb_data+'/download/'+tarball_filename,
136 'tarball_sig': tbb_data+'/download/'+tarball_filename+'.asc',
137 'verify': '/usr/share/torbrowser-launcher/verify.sh'
140 'tarball': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename,
141 'tarball_sig': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename+'.asc'
144 'tarball': tarball_filename,
145 'tarball_sig': tarball_filename+'.asc'
149 # create directories that don't exist
151 if os.path.exists(self.paths['dir']['download']) == False:
152 os.makedirs(self.paths['dir']['download'])
153 if os.path.exists(self.paths['dir']['tbb']) == False:
154 os.makedirs(self.paths['dir']['tbb'])
156 # there are different GUIs that might appear, this sets which one we want
157 def set_gui(self, gui, message, tasks, autostart=True):
159 self.gui_message = message
160 self.gui_tasks = tasks
161 self.gui_autostart = autostart
163 # build the application's UI
167 # allow buttons to have icons
169 settings = gtk.settings_get_default()
170 settings.props.gtk_button_images = True
175 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
176 self.window.set_title("Tor Browser")
177 self.window.set_position(gtk.WIN_POS_CENTER)
178 self.window.set_border_width(10)
179 self.window.connect("delete_event", self.delete_event)
180 self.window.connect("destroy", self.destroy)
182 self.box = gtk.VBox(False, 20)
183 self.window.add(self.box)
185 if self.gui == 'error':
187 self.label1 = gtk.Label( self.gui_message )
188 self.label1.set_line_wrap(True)
189 self.box.pack_start(self.label1, True, True, 0)
192 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.")
193 self.label2.set_line_wrap(True)
194 self.box.pack_start(self.label2, True, True, 0)
198 exit_image = gtk.Image()
199 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
200 self.exit_button = gtk.Button("Exit")
201 self.exit_button.set_image(exit_image)
202 self.exit_button.connect("clicked", self.destroy, None)
203 self.box.add(self.exit_button)
204 self.exit_button.show()
206 elif self.gui == 'task':
208 self.label = gtk.Label( self.gui_message )
209 self.label.set_line_wrap(True)
210 self.box.pack_start(self.label, True, True, 0)
214 self.progressbar = gtk.ProgressBar(adjustment=None)
215 self.progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
216 self.progressbar.set_pulse_step(0.01)
217 self.box.pack_start(self.progressbar, True, True, 0)
220 self.button_box = gtk.HButtonBox()
221 self.button_box.set_layout(gtk.BUTTONBOX_SPREAD)
222 self.box.pack_start(self.button_box, True, True, 0)
223 self.button_box.show()
226 start_image = gtk.Image()
227 start_image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
228 self.start_button = gtk.Button("Start")
229 self.start_button.set_image(start_image)
230 self.start_button.connect("clicked", self.start, None)
231 self.button_box.add(self.start_button)
232 if not self.gui_autostart:
233 self.start_button.show()
236 exit_image = gtk.Image()
237 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
238 self.exit_button = gtk.Button("Exit")
239 self.exit_button.set_image(exit_image)
240 self.exit_button.connect("clicked", self.destroy, None)
241 self.button_box.add(self.exit_button)
242 self.exit_button.show()
247 if self.gui_autostart:
250 # start button clicked, begin tasks
251 def start(self, widget, data=None):
252 # disable the start button
253 self.start_button.set_sensitive(False)
255 # start running tasks
259 # run the next task in the task list
263 if self.gui_task_i >= len(self.gui_tasks):
267 task = self.gui_tasks[self.gui_task_i]
269 # get ready for the next task
272 if task == 'download_tarball':
273 print 'Downloading '+self.paths['url']['tarball']
274 self.download('tarball', self.paths['url']['tarball'], self.paths['file']['tarball'])
276 elif task == 'download_tarball_sig':
277 print 'Downloading '+self.paths['url']['tarball_sig']
278 self.download('signature', self.paths['url']['tarball_sig'], self.paths['file']['tarball_sig'])
280 elif task == 'verify':
281 print 'Verifying signature'
284 elif task == 'extract':
285 print 'Extracting '+self.paths['filename']['tarball']
289 print 'Running '+self.paths['file']['start']
292 elif task == 'start_over':
293 print 'Starting download over again'
296 def response_received(self, response):
297 class FileDownloader(Protocol):
298 def __init__(self, file, total, progress, done_cb):
302 self.progress = progress
303 self.all_done = done_cb
305 def dataReceived(self, bytes):
306 self.file.write(bytes)
307 self.so_far += len(bytes)
308 percent = float(self.so_far) / float(self.total)
309 self.progress.set_fraction(percent)
310 amount = float(self.so_far)
312 for (size, unit) in [(1024 * 1024, "MiB"), (1024, "KiB")]:
315 amount = amount / float(size)
318 self.progress.set_text('Downloaded %2.1f%% (%2.1f %s)' % ((percent * 100.0), amount, units))
320 def connectionLost(self, reason):
321 print 'Finished receiving body:', reason.getErrorMessage()
322 self.all_done(reason)
324 dl = FileDownloader(self.file_download, response.length, self.progressbar, self.response_finished)
325 response.deliverBody(dl)
328 def response_finished(self, msg):
329 if msg.check(ResponseDone):
330 self.file_download.close()
335 print "FINISHED", msg
336 ## FIXME handle errors
343 def download(self, name, url, path):
344 # initialize the progress bar
345 self.progressbar.set_fraction(0)
346 self.progressbar.set_text('Downloading '+name)
347 self.progressbar.show()
350 agent = Agent(reactor, VerifyTorProjectCert())
351 d = agent.request('GET', url,
352 Headers({'User-Agent': ['torbrowser-launcher']}),
355 self.file_download = open(path, 'w')
356 d.addCallback(self.response_received).addErrback(self.error)
358 def download_chunk(self, name):
359 # download 10kb a time
360 chunk = self.dl_response.read(10240)
361 self.dl_bytes_so_far += len(chunk)
362 self.file_download.write(chunk)
365 self.file_download.close()
370 percent = float(self.dl_bytes_so_far) / self.dl_total_size
371 self.progressbar.set_fraction(percent)
372 percent = round(percent*100, 2)
373 self.progressbar.set_text("Downloaded %d%% of %s" % (percent, name))
376 sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % (self.dl_bytes_so_far, self.dl_total_size, percent))
378 if self.dl_bytes_so_far >= self.dl_total_size:
379 sys.stdout.write('\n')
384 # initialize the progress bar
385 self.progressbar.set_fraction(0)
386 self.progressbar.set_text('Verifying Signature')
387 self.progressbar.show()
389 p = subprocess.Popen([self.paths['file']['verify'], self.paths['dir']['gpg'], self.paths['file']['tarball_sig']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
390 self.pulse_until_process_exits(p)
392 output = p.stdout.read()
394 if 'Good signature' in output:
397 self.progressbar.hide()
398 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.")
399 self.gui_tasks = ['start_over']
401 self.start_button.show()
402 self.start_button.set_sensitive(True)
405 # initialize the progress bar
406 self.progressbar.set_fraction(0)
407 self.progressbar.set_text('Installing')
408 self.progressbar.show()
410 p = subprocess.Popen(['tar', '-xf', self.paths['file']['tarball'], '-C', self.paths['dir']['tbb']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
411 self.pulse_until_process_exits(p)
415 def run(self, run_next_task = True):
416 subprocess.Popen([self.paths['file']['start']])
420 # make the progress bar pulse until process p (a Popen object) finishes
421 def pulse_until_process_exits(self, p):
422 while p.poll() == None:
424 self.progressbar.pulse()
427 # start over and download TBB again
428 def start_over(self):
429 self.label.set_text("Downloading Tor Browser Bundle over again.")
430 self.gui_tasks = ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run']
435 def refresh_gtk(self):
436 while gtk.events_pending():
437 gtk.main_iteration(False)
440 def delete_event(self, widget, event, data=None):
442 def destroy(self, widget, data=None):
444 gobject.source_remove(self.timer)
447 self.file_download.close()
450 if __name__ == "__main__":
451 current_tbl_version = '0.1'
452 current_tbb_version = '2.3.25-2'
454 print 'Tor Browser Launcher'
455 print 'version %s' % (current_tbl_version)
456 print 'https://github.com/micahflee/torbrowser-launcher'
458 app = TorBrowserLauncher(current_tbb_version)