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',
98 # discover the architecture and language
99 def discover_arch_lang(self):
100 # figure out the architecture
101 (sysname, nodename, release, version, machine) = os.uname()
102 self.architecture = machine
104 # figure out the language
105 available_languages = ['en-US', 'ar', 'de', 'es-ES', 'fa', 'fr', 'it', 'ko', 'nl', 'pl', 'pt-PT', 'ru', 'vi', 'zh-CN']
106 default_locale = locale.getdefaultlocale()[0]
107 if default_locale == None:
108 self.language = 'en-US'
110 self.language = default_locale.replace('_', '-')
111 if self.language not in available_languages:
112 self.language = self.language.split('-')[0]
113 if self.language not in available_languages:
114 for l in available_languages:
115 if l[0:2] == self.language:
117 # if language isn't available, default to english
118 if self.language not in available_languages:
119 self.language = 'en-US'
121 # build all relevant paths
122 def build_paths(self):
123 tbb_data = os.getenv('HOME')+'/.torbrowser'
124 tarball_filename = 'tor-browser-gnu-linux-'+self.architecture+'-'+self.current_tbb_version+'-dev-'+self.language+'.tar.gz'
129 'download': tbb_data+'/download',
130 'tbb': tbb_data+'/tbb/'+self.architecture,
131 'gpg': tbb_data+'/gpgtmp'
134 'version': tbb_data+'/version',
135 'start': tbb_data+'/tbb/'+self.architecture+'/tor-browser_'+self.language+'/start-tor-browser',
136 'tarball': tbb_data+'/download/'+tarball_filename,
137 'tarball_sig': tbb_data+'/download/'+tarball_filename+'.asc',
138 'verify': '/usr/share/torbrowser-launcher/verify.sh'
141 'tarball': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename,
142 'tarball_sig': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename+'.asc'
145 'tarball': tarball_filename,
146 'tarball_sig': tarball_filename+'.asc'
150 # create directories that don't exist
152 if os.path.exists(self.paths['dir']['download']) == False:
153 os.makedirs(self.paths['dir']['download'])
154 if os.path.exists(self.paths['dir']['tbb']) == False:
155 os.makedirs(self.paths['dir']['tbb'])
157 # there are different GUIs that might appear, this sets which one we want
158 def set_gui(self, gui, message, tasks, autostart=True):
160 self.gui_message = message
161 self.gui_tasks = tasks
162 self.gui_autostart = autostart
164 # build the application's UI
168 # allow buttons to have icons
170 settings = gtk.settings_get_default()
171 settings.props.gtk_button_images = True
176 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
177 self.window.set_title("Tor Browser")
178 self.window.set_position(gtk.WIN_POS_CENTER)
179 self.window.set_border_width(10)
180 self.window.connect("delete_event", self.delete_event)
181 self.window.connect("destroy", self.destroy)
183 self.box = gtk.VBox(False, 20)
184 self.window.add(self.box)
186 if self.gui == 'error':
188 self.label1 = gtk.Label( self.gui_message )
189 self.label1.set_line_wrap(True)
190 self.box.pack_start(self.label1, True, True, 0)
193 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.")
194 self.label2.set_line_wrap(True)
195 self.box.pack_start(self.label2, True, True, 0)
199 exit_image = gtk.Image()
200 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
201 self.exit_button = gtk.Button("Exit")
202 self.exit_button.set_image(exit_image)
203 self.exit_button.connect("clicked", self.destroy, None)
204 self.box.add(self.exit_button)
205 self.exit_button.show()
207 elif self.gui == 'task':
209 self.label = gtk.Label( self.gui_message )
210 self.label.set_line_wrap(True)
211 self.box.pack_start(self.label, True, True, 0)
215 self.progressbar = gtk.ProgressBar(adjustment=None)
216 self.progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
217 self.progressbar.set_pulse_step(0.01)
218 self.box.pack_start(self.progressbar, True, True, 0)
221 self.button_box = gtk.HButtonBox()
222 self.button_box.set_layout(gtk.BUTTONBOX_SPREAD)
223 self.box.pack_start(self.button_box, True, True, 0)
224 self.button_box.show()
227 start_image = gtk.Image()
228 start_image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
229 self.start_button = gtk.Button("Start")
230 self.start_button.set_image(start_image)
231 self.start_button.connect("clicked", self.start, None)
232 self.button_box.add(self.start_button)
233 if not self.gui_autostart:
234 self.start_button.show()
237 exit_image = gtk.Image()
238 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
239 self.exit_button = gtk.Button("Exit")
240 self.exit_button.set_image(exit_image)
241 self.exit_button.connect("clicked", self.destroy, None)
242 self.button_box.add(self.exit_button)
243 self.exit_button.show()
248 if self.gui_autostart:
251 # start button clicked, begin tasks
252 def start(self, widget, data=None):
253 # disable the start button
254 self.start_button.set_sensitive(False)
256 # start running tasks
260 # run the next task in the task list
264 if self.gui_task_i >= len(self.gui_tasks):
268 task = self.gui_tasks[self.gui_task_i]
270 # get ready for the next task
273 if task == 'download_tarball':
274 print 'Downloading '+self.paths['url']['tarball']
275 self.download('tarball', self.paths['url']['tarball'], self.paths['file']['tarball'])
277 elif task == 'download_tarball_sig':
278 print 'Downloading '+self.paths['url']['tarball_sig']
279 self.download('signature', self.paths['url']['tarball_sig'], self.paths['file']['tarball_sig'])
281 elif task == 'verify':
282 print 'Verifying signature'
285 elif task == 'extract':
286 print 'Extracting '+self.paths['filename']['tarball']
290 print 'Running '+self.paths['file']['start']
293 elif task == 'start_over':
294 print 'Starting download over again'
297 def response_received(self, response):
298 class FileDownloader(Protocol):
299 def __init__(self, file, total, progress, done_cb):
303 self.progress = progress
304 self.all_done = done_cb
306 def dataReceived(self, bytes):
307 self.file.write(bytes)
308 self.so_far += len(bytes)
309 percent = float(self.so_far) / float(self.total)
310 self.progress.set_fraction(percent)
311 amount = float(self.so_far)
313 for (size, unit) in [(1024 * 1024, "MiB"), (1024, "KiB")]:
316 amount = amount / float(size)
319 self.progress.set_text('Downloaded %2.1f%% (%2.1f %s)' % ((percent * 100.0), amount, units))
321 def connectionLost(self, reason):
322 print 'Finished receiving body:', reason.getErrorMessage()
323 self.all_done(reason)
325 dl = FileDownloader(self.file_download, response.length, self.progressbar, self.response_finished)
326 response.deliverBody(dl)
329 def response_finished(self, msg):
331 if msg.check(ResponseDone):
332 self.file_download.close()
337 print "FINISHED", msg
338 ## FIXME handle errors
345 def download(self, name, url, path):
346 # initialize the progress bar
347 self.progressbar.set_fraction(0)
348 self.progressbar.set_text('Downloading '+name)
349 self.progressbar.show()
352 agent = Agent(reactor, VerifyTorProjectCert())
353 d = agent.request('GET', url,
354 Headers({'User-Agent': ['torbrowser-launcher']}),
357 self.file_download = open(path, 'w')
358 d.addCallback(self.response_received).addErrback(self.error)
360 def download_chunk(self, name):
361 # download 10kb a time
362 chunk = self.dl_response.read(10240)
363 self.dl_bytes_so_far += len(chunk)
364 self.file_download.write(chunk)
367 self.file_download.close()
372 percent = float(self.dl_bytes_so_far) / self.dl_total_size
373 self.progressbar.set_fraction(percent)
374 percent = round(percent*100, 2)
375 self.progressbar.set_text("Downloaded %d%% of %s" % (percent, name))
378 sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % (self.dl_bytes_so_far, self.dl_total_size, percent))
380 if self.dl_bytes_so_far >= self.dl_total_size:
381 sys.stdout.write('\n')
386 # initialize the progress bar
387 self.progressbar.set_fraction(0)
388 self.progressbar.set_text('Verifying Signature')
389 self.progressbar.show()
391 p = subprocess.Popen([self.paths['file']['verify'], self.paths['dir']['gpg'], self.paths['file']['tarball_sig']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
392 self.pulse_until_process_exits(p)
394 output = p.stdout.read()
396 if 'Good signature' in output:
399 self.progressbar.hide()
400 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.")
401 self.gui_tasks = ['start_over']
403 self.start_button.show()
404 self.start_button.set_sensitive(True)
407 # initialize the progress bar
408 self.progressbar.set_fraction(0)
409 self.progressbar.set_text('Installing')
410 self.progressbar.show()
412 p = subprocess.Popen(['tar', '-xf', self.paths['file']['tarball'], '-C', self.paths['dir']['tbb']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
413 self.pulse_until_process_exits(p)
417 def run(self, run_next_task = True):
418 subprocess.Popen([self.paths['file']['start']])
422 # make the progress bar pulse until process p (a Popen object) finishes
423 def pulse_until_process_exits(self, p):
424 while p.poll() == None:
426 self.progressbar.pulse()
429 # start over and download TBB again
430 def start_over(self):
431 self.label.set_text("Downloading Tor Browser Bundle over again.")
432 self.gui_tasks = ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run']
437 def refresh_gtk(self):
438 while gtk.events_pending():
439 gtk.main_iteration(False)
442 def delete_event(self, widget, event, data=None):
444 def destroy(self, widget, data=None):
446 gobject.source_remove(self.timer)
449 self.file_download.close()
452 if __name__ == "__main__":
453 current_tbl_version = '0.1'
454 current_tbb_version = '2.3.25-2'
456 print 'Tor Browser Launcher'
457 print 'version %s' % (current_tbl_version)
458 print 'https://github.com/micahflee/torbrowser-launcher'
460 app = TorBrowserLauncher(current_tbb_version)