]> git.lizzy.rs Git - torbrowser-launcher.git/blob - torbrowser-launcher
made language default to en-US if the we can't figure out the default locale (#12)
[torbrowser-launcher.git] / torbrowser-launcher
1 #!/usr/bin/env python
2
3 import os, sys, subprocess, locale, urllib2, gobject, time
4
5 import pygtk
6 pygtk.require('2.0')
7 import gtk
8
9 class TorBrowserLauncher:
10   def __init__(self, current_tbb_version):
11     # initialize the app
12     self.current_tbb_version = current_tbb_version
13     self.discover_arch_lang()
14     self.build_paths()
15     self.mkdirs()
16
17     launch_gui = True
18
19     # is TBB already installed?
20     if os.path.isfile(self.paths['file']['start']) and os.access(self.paths['file']['start'], os.X_OK):
21       # does the version file exist?
22       if os.path.isfile(self.paths['file']['version']):
23         installed_tbb_version = open(self.paths['file']['version']).read().strip()
24
25         if installed_tbb_version == current_tbb_version:
26           # current version is tbb is installed, launch it
27           self.run(False)
28           launch_gui = False
29         elif installed_tbb_version < self.current_tbb_version:
30           # there is a tbb upgrade available
31           self.set_gui('task', "Your Tor Browser is out of date. Click Start to download the latest version from https://www.torproject.org.", ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run'])
32         else:
33           # for some reason the installed tbb is newer than the current version?
34           self.set_gui('error', "Something is wrong. The version of Tor Browser Bundle you have installed is newer than the current version?", [])
35
36       else:
37         # if tbb is installed but the version file doesn't exist, something is wrong
38         self.set_gui('error', "Something is wrong. You have the Tor Browser Bundle installed, but the version file is missing.", [])
39
40     # not installed
41     else:
42       # save the current version to the file
43       open(self.paths['file']['version'], 'w').write(self.current_tbb_version)
44
45       # are the tarball and sig already downloaded?
46       if os.path.isfile(self.paths['file']['tarball']) and os.path.isfile(self.paths['file']['tarball_sig']):
47         # start the gui with verify
48         self.set_gui('task', "You already have Tor Browser Bundle downloaded, but it isn't installed yet.", ['verify', 'extract', 'run'])
49
50       # first run
51       else:
52         self.set_gui('task', "The first time you run the Tor Browser Launcher you need to download the Tor Browser Bundle. Click Start to download it now from https://www.torproject.org/.", ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run'])
53
54     if launch_gui:
55       self.build_ui()
56       gtk.main()
57   
58   # discover the architecture and language
59   def discover_arch_lang(self):
60     # figure out the architecture
61     self.architecture = subprocess.Popen(['uname', '-m'], stdout=subprocess.PIPE, stderr=None).stdout.read().strip('\n')
62
63     # figure out the language
64     available_languages = ['en-US', 'ar', 'de', 'es-ES', 'fa', 'fr', 'it', 'ko', 'nl', 'pl', 'pt-PT', 'ru', 'vi', 'zh-CN']
65     default_locale = locale.getdefaultlocale()[0]
66     if default_locale == None:
67       self.language = 'en-US'
68     else:
69       self.language = default_locale.replace('_', '-')
70       if self.language not in available_languages:
71         self.language = self.language.split('-')[0]
72         if self.language not in available_languages:
73           for l in available_languages:
74             if l[0:2] == self.language:
75               self.language = l
76       # if language isn't available, default to english
77       if self.language not in available_languages:
78         self.language = 'en-US'
79
80   # build all relevant paths
81   def build_paths(self):
82     tbb_data = os.getenv('HOME')+'/.torbrowser'
83     tarball_filename = 'tor-browser-gnu-linux-'+self.architecture+'-'+self.current_tbb_version+'-dev-'+self.language+'.tar.gz'
84
85     self.paths = {
86       'dir': {
87         'data': tbb_data,
88         'download': tbb_data+'/download',
89         'tbb': tbb_data+'/tbb/'+self.architecture,
90         'gpg': tbb_data+'/gpgtmp'
91       },
92       'file': {
93         'version': tbb_data+'/version',
94         'start': tbb_data+'/tbb/'+self.architecture+'/tor-browser_'+self.language+'/start-tor-browser',
95         'tarball': tbb_data+'/download/'+tarball_filename,
96         'tarball_sig': tbb_data+'/download/'+tarball_filename+'.asc',
97         'verify': '/usr/share/torbrowser-launcher/verify.sh'
98       },
99       'url': {
100         'tarball': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename,
101         'tarball_sig': 'https://www.torproject.org/dist/torbrowser/linux/'+tarball_filename+'.asc'
102       },
103       'filename': {
104         'tarball': tarball_filename,
105         'tarball_sig': tarball_filename+'.asc'
106       }
107     }
108
109   # create directories that don't exist
110   def mkdirs(self):
111     if os.path.exists(self.paths['dir']['download']) == False:
112       os.makedirs(self.paths['dir']['download'])
113     if os.path.exists(self.paths['dir']['tbb']) == False:
114       os.makedirs(self.paths['dir']['tbb'])
115
116   # there are different GUIs that might appear, this sets which one we want
117   def set_gui(self, gui, message, tasks):
118     self.gui = gui
119     self.gui_message = message
120     self.gui_tasks = tasks
121
122   # build the application's UI
123   def build_ui(self):
124     self.timer = False
125
126     # allow buttons to have icons
127     try:
128       settings = gtk.settings_get_default()
129       settings.props.gtk_button_images = True
130     except:
131       pass
132
133     # set up the window
134     self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
135     self.window.set_title("Tor Browser")
136     self.window.set_position(gtk.WIN_POS_CENTER)
137     self.window.set_border_width(10)
138     self.window.connect("delete_event", self.delete_event)
139     self.window.connect("destroy", self.destroy)
140
141     self.box = gtk.VBox(False, 20)
142     self.window.add(self.box)
143
144     if self.gui == 'error':
145       # labels
146       self.label1 = gtk.Label( self.gui_message ) 
147       self.label1.set_line_wrap(True)
148       self.box.pack_start(self.label1, True, True, 0)
149       self.label1.show()
150
151       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.") 
152       self.label2.set_line_wrap(True)
153       self.box.pack_start(self.label2, True, True, 0)
154       self.label2.show()
155
156       # exit button
157       exit_image = gtk.Image()
158       exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
159       self.exit_button = gtk.Button("Exit")
160       self.exit_button.set_image(exit_image)
161       self.exit_button.connect("clicked", self.destroy, None)
162       self.box.add(self.exit_button)
163       self.exit_button.show()
164
165     elif self.gui == 'task':
166       # label
167       self.label = gtk.Label( self.gui_message ) 
168       self.label.set_line_wrap(True)
169       self.box.pack_start(self.label, True, True, 0)
170       self.label.show()
171       
172       # progress bar
173       self.progressbar = gtk.ProgressBar(adjustment=None)
174       self.progressbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
175       self.progressbar.set_pulse_step(0.01)
176       self.box.pack_start(self.progressbar, True, True, 0)
177
178       # button box
179       self.button_box = gtk.HButtonBox()
180       self.button_box.set_layout(gtk.BUTTONBOX_SPREAD)
181       self.box.pack_start(self.button_box, True, True, 0)
182       self.button_box.show()
183
184       # start button
185       start_image = gtk.Image()
186       start_image.set_from_stock(gtk.STOCK_APPLY, gtk.ICON_SIZE_BUTTON)
187       self.start_button = gtk.Button("Start")
188       self.start_button.set_image(start_image)
189       self.start_button.connect("clicked", self.start, None)
190       self.button_box.add(self.start_button)
191       self.start_button.show()
192
193       # exit button
194       exit_image = gtk.Image()
195       exit_image.set_from_stock(gtk.STOCK_CANCEL, gtk.ICON_SIZE_BUTTON)
196       self.exit_button = gtk.Button("Exit")
197       self.exit_button.set_image(exit_image)
198       self.exit_button.connect("clicked", self.destroy, None)
199       self.button_box.add(self.exit_button)
200       self.exit_button.show()
201
202     self.box.show()
203     self.window.show()
204
205   # start button clicked, begin tasks
206   def start(self, widget, data=None):
207     # disable the start button
208     self.start_button.set_sensitive(False)
209
210     # start running tasks
211     self.gui_task_i = 0
212     self.run_task()
213     
214   # run the next task in the task list
215   def run_task(self):
216     if self.gui_task_i >= len(self.gui_tasks):
217       self.destroy(False)
218       return
219
220     task = self.gui_tasks[self.gui_task_i]
221     
222     # get ready for the next task
223     self.gui_task_i += 1
224
225     if task == 'download_tarball':
226       print 'Downloading '+self.paths['url']['tarball']
227       self.download('tarball', self.paths['url']['tarball'], self.paths['file']['tarball'])
228
229     elif task == 'download_tarball_sig':
230       print 'Downloading '+self.paths['url']['tarball_sig']
231       self.download('signature', self.paths['url']['tarball_sig'], self.paths['file']['tarball_sig'])
232
233     elif task == 'verify':
234       print 'Verifying signature'
235       self.verify()
236
237     elif task == 'extract':
238       print 'Extracting '+self.paths['filename']['tarball']
239       self.extract()
240
241     elif task == 'run':
242       print 'Running '+self.paths['file']['start']
243       self.run()
244     
245     elif task == 'start_over':
246       print 'Starting download over again'
247       self.start_over()
248
249
250   def download(self, name, url, path):
251     # initialize the progress bar
252     self.progressbar.set_fraction(0) 
253     self.progressbar.set_text('Downloading '+name)
254     self.progressbar.show()
255     self.refresh_gtk()
256
257     # start the download
258     self.dl_response = urllib2.urlopen(url)
259     self.dl_total_size = self.dl_response.info().getheader('Content-Length').strip()
260     self.dl_total_size = int(self.dl_total_size)
261     self.dl_bytes_so_far = 0
262
263     # set a timer to download more chunks
264     self.timer = gobject.timeout_add(1, self.download_chunk, name)
265
266     # open a file to write to
267     self.file_download = open(path, 'w')
268
269   def download_chunk(self, name):
270     # download 10kb a time
271     chunk = self.dl_response.read(10240)
272     self.dl_bytes_so_far += len(chunk)
273     self.file_download.write(chunk)
274
275     if not chunk:
276       self.file_download.close()
277       # next task!
278       self.run_task()
279       return False
280
281     percent = float(self.dl_bytes_so_far) / self.dl_total_size
282     self.progressbar.set_fraction(percent)
283     percent = round(percent*100, 2)
284     self.progressbar.set_text("Downloaded %d%% of %s" % (percent, name))
285     self.refresh_gtk()
286     
287     sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" % (self.dl_bytes_so_far, self.dl_total_size, percent))
288
289     if self.dl_bytes_so_far >= self.dl_total_size:
290       sys.stdout.write('\n')
291
292     return True
293
294   def verify(self):
295     # initialize the progress bar
296     self.progressbar.set_fraction(0) 
297     self.progressbar.set_text('Verifying Signature')
298     self.progressbar.show()
299
300     p = subprocess.Popen([self.paths['file']['verify'], self.paths['dir']['gpg'], self.paths['file']['tarball_sig']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
301     self.pulse_until_process_exits(p)
302
303     output = p.stdout.read()
304     
305     if 'Good signature' in output:
306       self.run_task()
307     else:
308       self.progressbar.hide()
309       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.")
310       self.gui_tasks = ['start_over']
311       self.gui_task_i = 0
312       self.start_button.set_sensitive(True)
313
314   def extract(self):
315     # initialize the progress bar
316     self.progressbar.set_fraction(0) 
317     self.progressbar.set_text('Installing')
318     self.progressbar.show()
319
320     p = subprocess.Popen(['tar', '-xf', self.paths['file']['tarball'], '-C', self.paths['dir']['tbb']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
321     self.pulse_until_process_exits(p)
322
323     self.run_task()
324
325   def run(self, run_next_task = True):
326     subprocess.Popen([self.paths['file']['start']])
327     if run_next_task:
328       self.run_task()
329
330   # make the progress bar pulse until process p (a Popen object) finishes
331   def pulse_until_process_exits(self, p):
332     while p.poll() == None:
333       time.sleep(0.01)
334       self.progressbar.pulse()
335       self.refresh_gtk()
336
337   # start over and download TBB again
338   def start_over(self):
339     self.label.set_text("Downloading Tor Browser Bundle over again.")
340     self.gui_tasks = ['download_tarball', 'download_tarball_sig', 'verify', 'extract', 'run']
341     self.gui_task_i = 0
342     self.start(None)
343   
344   # refresh gtk
345   def refresh_gtk(self):
346     while gtk.events_pending():
347        gtk.main_iteration(False)
348
349   # exit
350   def delete_event(self, widget, event, data=None):
351     return False
352   def destroy(self, widget, data=None):
353     if self.timer:
354       gobject.source_remove(self.timer)
355     self.timer = False
356
357     gtk.main_quit()
358
359 if __name__ == "__main__":
360   current_tbl_version = '0.1'
361   current_tbb_version = '2.3.25-2'
362
363   print 'Tor Browser Launcher'
364   print 'version %s' % (current_tbl_version)
365   print 'https://github.com/micahflee/torbrowser-launcher'
366
367   app = TorBrowserLauncher(current_tbb_version)
368