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
18 class TorBrowserLauncher:
19 def __init__(self, current_tbb_version):
21 self.current_tbb_version = current_tbb_version
22 self.discover_arch_lang()
28 # is TBB already installed?
29 if os.path.isfile(self.paths['file']['start']) and os.access(self.paths['file']['start'], os.X_OK):
30 # does the version file exist?
31 if os.path.isfile(self.paths['file']['version']):
32 installed_tbb_version = open(self.paths['file']['version']).read().strip()
34 if installed_tbb_version == current_tbb_version:
35 # current version is tbb is installed, launch it
38 elif installed_tbb_version < self.current_tbb_version:
39 # there is a tbb upgrade available
40 self.set_gui('task', "Your Tor Browser is out of date.",
42 'download_tarball_sig',
47 # for some reason the installed tbb is newer than the current version?
48 self.set_gui('error', "Something is wrong. The version of Tor Browser Bundle you have installed is newer than the current version?", [])
51 # if tbb is installed but the version file doesn't exist, something is wrong
52 self.set_gui('error', "Something is wrong. You have the Tor Browser Bundle installed, but the version file is missing.", [])
56 # save the current version to the file
57 open(self.paths['file']['version'], 'w').write(self.current_tbb_version)
59 # are the tarball and sig already downloaded?
60 if os.path.isfile(self.paths['file']['tarball']) and os.path.isfile(self.paths['file']['tarball_sig']):
61 # start the gui with verify
62 self.set_gui('task', "Installing Tor Browser.",
69 self.set_gui('task', "Downloading and installing Tor Browser.",
71 'download_tarball_sig',
81 # discover the architecture and language
82 def discover_arch_lang(self):
83 # figure out the architecture
84 (sysname, nodename, release, version, machine) = os.uname()
85 self.architecture = machine
87 # figure out the language
88 available_languages = ['en-US', 'ar', 'de', 'es-ES', 'fa', 'fr', 'it', 'ko', 'nl', 'pl', 'pt-PT', 'ru', 'vi', 'zh-CN']
89 default_locale = locale.getdefaultlocale()[0]
90 if default_locale == None:
91 self.language = 'en-US'
93 self.language = default_locale.replace('_', '-')
94 if self.language not in available_languages:
95 self.language = self.language.split('-')[0]
96 if self.language not in available_languages:
97 for l in available_languages:
98 if l[0:2] == self.language:
100 # if language isn't available, default to english
101 if self.language not in available_languages:
102 self.language = 'en-US'
104 # build all relevant paths
105 def build_paths(self):
106 tbb_data = os.getenv('HOME')+'/.torbrowser'
107 tarball_filename = 'tor-browser-gnu-linux-'+self.architecture+'-'+self.current_tbb_version+'-dev-'+self.language+'.tar.gz'
112 'download': tbb_data+'/download',
113 'tbb': tbb_data+'/tbb/'+self.architecture,
114 'gpg': tbb_data+'/gpgtmp'
117 'version': tbb_data+'/version',
118 'start': tbb_data+'/tbb/'+self.architecture+'/tor-browser_'+self.language+'/start-tor-browser',
119 'tarball': tbb_data+'/download/'+tarball_filename,
120 'tarball_sig': tbb_data+'/download/'+tarball_filename+'.asc',
121 'verify': '/usr/share/torbrowser-launcher/verify.sh'
124 'tarball': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename,
125 'tarball_sig': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename+'.asc'
128 'tarball': tarball_filename,
129 'tarball_sig': tarball_filename+'.asc'
133 # create directories that don't exist
135 if os.path.exists(self.paths['dir']['download']) == False:
136 os.makedirs(self.paths['dir']['download'])
137 if os.path.exists(self.paths['dir']['tbb']) == False:
138 os.makedirs(self.paths['dir']['tbb'])
140 # there are different GUIs that might appear, this sets which one we want
141 def set_gui(self, gui, message, tasks, autostart=True):
143 self.gui_message = message
144 self.gui_tasks = tasks
145 self.gui_autostart = autostart
147 # build the application's UI
151 # allow buttons to have icons
153 settings = gtk.settings_get_default()
154 settings.props.gtk_button_images = True
159 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
160 self.window.set_title("Tor Browser")
161 self.window.set_position(gtk.WIN_POS_CENTER)
162 self.window.set_border_width(10)
163 self.window.connect("delete_event", self.delete_event)
164 self.window.connect("destroy", self.destroy)
166 self.box = gtk.VBox(False, 20)
167 self.window.add(self.box)
169 if self.gui == 'error':
171 self.label1 = gtk.Label( self.gui_message )
172 self.label1.set_line_wrap(True)
173 self.box.pack_start(self.label1, True, True, 0)
176 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.")
177 self.label2.set_line_wrap(True)
178 self.box.pack_start(self.label2, True, True, 0)
182 exit_image = gtk.Image()
183 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
184 self.exit_button = gtk.Button("Exit")
185 self.exit_button.set_image(exit_image)
186 self.exit_button.connect("clicked", self.destroy, None)
187 self.box.add(self.exit_button)
188 self.exit_button.show()
190 elif self.gui == 'task':
192 self.label = gtk.Label( self.gui_message )
193 self.label.set_line_wrap(True)
194 self.box.pack_start(self.label, True, True, 0)
198 self.progressbar = gtk.ProgressBar(adjustment=None)
199 self.progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
200 self.progressbar.set_pulse_step(0.01)
201 self.box.pack_start(self.progressbar, True, True, 0)
204 self.button_box = gtk.HButtonBox()
205 self.button_box.set_layout(gtk.BUTTONBOX_SPREAD)
206 self.box.pack_start(self.button_box, True, True, 0)
207 self.button_box.show()
210 start_image = gtk.Image()
211 start_image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
212 self.start_button = gtk.Button("Start")
213 self.start_button.set_image(start_image)
214 self.start_button.connect("clicked", self.start, None)
215 self.button_box.add(self.start_button)
216 if not self.gui_autostart:
217 self.start_button.show()
220 exit_image = gtk.Image()
221 exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
222 self.exit_button = gtk.Button("Exit")
223 self.exit_button.set_image(exit_image)
224 self.exit_button.connect("clicked", self.destroy, None)
225 self.button_box.add(self.exit_button)
226 self.exit_button.show()
231 if self.gui_autostart:
234 # start button clicked, begin tasks
235 def start(self, widget, data=None):
236 # disable the start button
237 self.start_button.set_sensitive(False)
239 # start running tasks
243 # run the next task in the task list
247 if self.gui_task_i >= len(self.gui_tasks):
251 task = self.gui_tasks[self.gui_task_i]
253 # get ready for the next task
256 if task == 'download_tarball':
257 print 'Downloading '+self.paths['url']['tarball']
258 self.download('tarball', self.paths['url']['tarball'], self.paths['file']['tarball'])
260 elif task == 'download_tarball_sig':
261 print 'Downloading '+self.paths['url']['tarball_sig']
262 self.download('signature', self.paths['url']['tarball_sig'], self.paths['file']['tarball_sig'])
264 elif task == 'verify':
265 print 'Verifying signature'
268 elif task == 'extract':
269 print 'Extracting '+self.paths['filename']['tarball']
273 print 'Running '+self.paths['file']['start']
276 elif task == 'start_over':
277 print 'Starting download over again'
280 def response_received(self, response):
281 class FileDownloader(Protocol):
282 def __init__(self, file, total, progress, done_cb):
286 self.progress = progress
287 self.all_done = done_cb
289 def dataReceived(self, bytes):
290 self.file.write(bytes)
291 self.so_far += len(bytes)
292 percent = float(self.so_far) / float(self.total)
293 self.progress.set_fraction(percent)
294 amount = float(self.so_far)
296 for (size, unit) in [(1000000, "MB"), (1000, "KB")]:
299 amount = amount / float(size)
302 self.progress.set_text('Downloaded %2.1f%% (%2.1f %s)' % ((percent * 100.0), amount, units))
304 def connectionLost(self, reason):
305 print 'Finished receiving body:', reason.getErrorMessage()
306 self.all_done(reason)
308 dl = FileDownloader(self.file_download, response.length, self.progressbar, self.response_finished)
309 response.deliverBody(dl)
312 def response_finished(self, msg):
314 if msg.check(ResponseDone):
315 self.file_download.close()
320 print "FINISHED", msg
321 ## FIXME handle errors
324 def download(self, name, url, path):
325 # initialize the progress bar
326 self.progressbar.set_fraction(0)
327 self.progressbar.set_text('Downloading '+name)
328 self.progressbar.show()
331 agent = Agent(reactor)
332 d = agent.request('GET', url,
333 Headers({'User-Agent': ['torbrowser-launcher']}),
336 self.file_download = open(path, 'w')
337 d.addCallback(self.response_received)
339 def download_chunk(self, name):
340 # download 10kb a time
341 chunk = self.dl_response.read(10240)
342 self.dl_bytes_so_far += len(chunk)
343 self.file_download.write(chunk)
346 self.file_download.close()
351 percent = float(self.dl_bytes_so_far) / self.dl_total_size
352 self.progressbar.set_fraction(percent)
353 percent = round(percent*100, 2)
354 self.progressbar.set_text("Downloaded %d%% of %s" % (percent, name))
357 sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % (self.dl_bytes_so_far, self.dl_total_size, percent))
359 if self.dl_bytes_so_far >= self.dl_total_size:
360 sys.stdout.write('\n')
365 # initialize the progress bar
366 self.progressbar.set_fraction(0)
367 self.progressbar.set_text('Verifying Signature')
368 self.progressbar.show()
370 p = subprocess.Popen([self.paths['file']['verify'], self.paths['dir']['gpg'], self.paths['file']['tarball_sig']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
371 self.pulse_until_process_exits(p)
373 output = p.stdout.read()
375 if 'Good signature' in output:
378 self.progressbar.hide()
379 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.")
380 self.gui_tasks = ['start_over']
382 self.start_button.show()
383 self.start_button.set_sensitive(True)
386 # initialize the progress bar
387 self.progressbar.set_fraction(0)
388 self.progressbar.set_text('Installing')
389 self.progressbar.show()
391 p = subprocess.Popen(['tar', '-xf', self.paths['file']['tarball'], '-C', self.paths['dir']['tbb']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
392 self.pulse_until_process_exits(p)
396 def run(self, run_next_task = True):
397 subprocess.Popen([self.paths['file']['start']])
401 # make the progress bar pulse until process p (a Popen object) finishes
402 def pulse_until_process_exits(self, p):
403 while p.poll() == None:
405 self.progressbar.pulse()
408 # start over and download TBB again
409 def start_over(self):
410 self.label.set_text("Downloading Tor Browser Bundle over again.")
411 self.gui_tasks = ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run']
416 def refresh_gtk(self):
417 while gtk.events_pending():
418 gtk.main_iteration(False)
421 def delete_event(self, widget, event, data=None):
423 def destroy(self, widget, data=None):
425 gobject.source_remove(self.timer)
428 self.file_download.close()
431 if __name__ == "__main__":
432 current_tbl_version = '0.1'
433 current_tbb_version = '2.3.25-2'
435 print 'Tor Browser Launcher'
436 print 'version %s' % (current_tbl_version)
437 print 'https://github.com/micahflee/torbrowser-launcher'
439 app = TorBrowserLauncher(current_tbb_version)