/
torbutton.js
2254 lines (1928 loc) · 85.2 KB
/
torbutton.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Bug 1506 P1-P5: This is the main Torbutton overlay file. Much needs to be
// preserved here, but in an ideal world, most of this code should perhaps be
// moved into an XPCOM service, and much can also be tossed. See also
// individual 1506 comments for details.
// TODO: check for leaks: http://www.mozilla.org/scriptable/avoiding-leaks.html
// TODO: Double-check there are no strange exploits to defeat:
// http://kb.mozillazine.org/Links_to_local_pages_don%27t_work
let { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
let { showDialog, show_torbrowser_manual } = Cu.import("resource://torbutton/modules/utils.js", {});
let { unescapeTorString } = Cu.import("resource://torbutton/modules/utils.js", {});
let SecurityPrefs = Cu.import("resource://torbutton/modules/security-prefs.js", {});
let { bindPrefAndInit, observe } = Cu.import("resource://torbutton/modules/utils.js", {});
Cu.importGlobalProperties(["XMLHttpRequest"]);
const k_tb_last_browser_version_pref = "extensions.torbutton.lastBrowserVersion";
const k_tb_browser_update_needed_pref = "extensions.torbutton.updateNeeded";
const k_tb_last_update_check_pref = "extensions.torbutton.lastUpdateCheck";
const k_tb_tor_check_failed_topic = "Torbutton:TorCheckFailed";
const k_tb_donation_banner_countdown = "extensions.torbutton.donation_banner_countdown";
var m_tb_prefs = Services.prefs;
// status
var m_tb_wasinited = false;
var m_tb_plugin_string = false;
var m_tb_is_main_window = false;
var m_tb_hidden_browser = false;
var m_tb_confirming_plugins = false;
var m_tb_window_height = window.outerHeight;
var m_tb_window_width = window.outerWidth;
var m_tb_tbb = false;
var m_tb_control_ipc_file = null; // Set if using IPC (UNIX domain socket).
var m_tb_control_port = null; // Set if using TCP.
var m_tb_control_host = null; // Set if using TCP.
var m_tb_control_pass = null;
var m_tb_control_desc = null; // For logging.
var m_tb_domWindowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIDOMWindowUtils);
// Bug 1506 P1: This object is only for updating the UI for toggling and style
var torbutton_window_pref_observer =
{
register: function()
{
m_tb_prefs.addObserver("extensions.torbutton", this, false);
},
unregister: function()
{
m_tb_prefs.removeObserver("extensions.torbutton", this);
},
// topic: what event occurred
// subject: what nsIPrefBranch we're observing
// data: which pref has been changed (relative to subject)
observe: function(subject, topic, data)
{
if (topic != "nsPref:changed") return;
switch (data) {
case k_tb_browser_update_needed_pref:
torbutton_notify_if_update_needed();
break;
}
}
}
// Bug 1506 P2: This object keeps Firefox prefs in sync with Torbutton prefs.
// It probably could stand some simplification (See #3100). It also belongs
// in a component, not the XUL overlay.
var torbutton_unique_pref_observer =
{
register: function()
{
this.forced_ua = false;
m_tb_prefs.addObserver("extensions.torbutton", this, false);
m_tb_prefs.addObserver("network.cookie", this, false);
m_tb_prefs.addObserver("browser.privatebrowsing.autostart", this, false);
m_tb_prefs.addObserver("javascript", this, false);
m_tb_prefs.addObserver("noscript", this, false);
m_tb_prefs.addObserver("plugin.disable", this, false);
m_tb_prefs.addObserver("privacy.firstparty.isolate", this, false);
m_tb_prefs.addObserver("privacy.resistFingerprinting", this, false);
// We observe xpcom-category-entry-added for plugins w/ Gecko-Content-Viewers
var observerService = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
observerService.addObserver(this, "xpcom-category-entry-added", false);
},
unregister: function()
{
m_tb_prefs.removeObserver("extensions.torbutton", this);
m_tb_prefs.removeObserver("network.cookie", this);
m_tb_prefs.removeObserver("browser.privatebrowsing.autostart", this);
m_tb_prefs.removeObserver("javascript", this);
m_tb_prefs.removeObserver("noscript", this);
m_tb_prefs.removeObserver("plugin.disable", this);
m_tb_prefs.removeObserver("privacy.firstparty.isolate", this);
m_tb_prefs.removeObserver("privacy.resistFingerprinting", this);
var observerService = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
observerService.removeObserver(this, "xpcom-category-entry-added");
},
// topic: what event occurred
// subject: what nsIPrefBranch we're observing
// data: which pref has been changed (relative to subject)
observe: function(subject, topic, data)
{
if (topic == "xpcom-category-entry-added") {
// Hrmm. should we inspect subject too? it's just mime type..
subject.QueryInterface(Ci.nsISupportsCString);
if (data == "Gecko-Content-Viewers" &&
!m_tb_prefs.getBoolPref("extensions.torbutton.startup") &&
m_tb_prefs.getBoolPref("extensions.torbutton.confirm_plugins")) {
torbutton_log(3, "Got plugin enabled notification: "+subject);
/* We need to protect this call with a flag becuase we can
* get multiple observer events for each mime type a plugin
* registers. Thankfully, these notifications arrive only on
* the main thread, *however*, our confirmation dialog suspends
* execution and allows more events to arrive until it is answered
*/
if (!m_tb_confirming_plugins) {
m_tb_confirming_plugins = true;
torbutton_confirm_plugins();
m_tb_confirming_plugins = false;
} else {
torbutton_log(3, "Skipping notification for mime type: "+subject);
}
}
return;
}
if (topic != "nsPref:changed") return;
// Make sure the NoScript button shows the current NoScript state. We
// don't want to run the update function, though, if just a timer gets
// updated. Fixes bug 21324.
if (data.startsWith("noscript.") &&
data !== "noscript.subscription.lastCheck") {
torbutton_update_noscript_button();
}
switch (data) {
case "network.cookie.cookieBehavior":
let val = m_tb_prefs.getIntPref("network.cookie.cookieBehavior");
let firstparty_isolate = m_tb_prefs.getBoolPref("privacy.firstparty.isolate");
if (val == 0 && firstparty_isolate) // Allow all cookies
m_tb_prefs.setBoolPref("privacy.firstparty.isolate", false);
else if (val == 1 && !firstparty_isolate) // Block third party cookies
m_tb_prefs.setBoolPref("privacy.firstparty.isolate", true);
break;
case "plugin.disable":
torbutton_toggle_plugins(
m_tb_prefs.getBoolPref("plugin.disable"));
break;
case "browser.privatebrowsing.autostart":
torbutton_update_disk_prefs();
break;
case "extensions.torbutton.use_nontor_proxy":
torbutton_use_nontor_proxy();
break;
case "privacy.resistFingerprinting":
torbutton_update_fingerprinting_prefs();
break;
case "privacy.firstparty.isolate":
torbutton_update_isolation_prefs();
break;
}
}
}
var torbutton_tor_check_observer = {
register: function()
{
this._obsSvc = Cc["@mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
this._obsSvc.addObserver(this, k_tb_tor_check_failed_topic, false);
},
unregister: function()
{
if (this._obsSvc)
this._obsSvc.removeObserver(this, k_tb_tor_check_failed_topic);
},
observe: function(subject, topic, data)
{
if (topic == k_tb_tor_check_failed_topic) {
// Update toolbar icon and tooltip.
torbutton_update_toolbutton();
// Update all open about:tor pages.
torbutton_abouttor_message_handler.updateAllOpenPages();
// If the user does not have an about:tor tab open in the front most
// window, open one.
var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
if (win == window) {
let foundTab = false;
let tabBrowser = top.getBrowser();
for (let i = 0; !foundTab && (i < tabBrowser.browsers.length); ++i) {
let b = tabBrowser.getBrowserAtIndex(i);
foundTab = (b.currentURI.spec.toLowerCase() == "about:tor");
}
if (!foundTab)
gBrowser.selectedTab = gBrowser.addTab("about:tor");
}
}
}
};
function torbutton_init_toolbutton()
{
try {
torbutton_log(3, "Initializing the Torbutton button.");
torbutton_update_toolbutton();
} catch(e) {
torbutton_log(4, "Error Initializing Torbutton button: "+e);
}
}
// Show the Sign Up for Tor News banner a finite number of times.
function torbutton_donation_banner_countdown() {
let count = m_tb_prefs.getIntPref(k_tb_donation_banner_countdown, 0);
if (count > 0) {
m_tb_prefs.setIntPref(k_tb_donation_banner_countdown, count - 1);
}
}
// Bug 1506 P2-P4: This code sets some version variables that are irrelevant.
// It does read out some important environment variables, though. It is
// called once per browser window.. This might belong in a component.
function torbutton_init() {
torbutton_log(3, 'called init()');
SecurityPrefs.initialize();
if (m_tb_wasinited) {
return;
}
m_tb_wasinited = true;
// Determine if we are running inside Tor Browser.
var cur_version;
try {
cur_version = m_tb_prefs.getCharPref("torbrowser.version");
m_tb_tbb = true;
torbutton_log(3, "This is a Tor Browser");
} catch(e) {
torbutton_log(3, "This is not a Tor Browser: "+e);
}
// If the Tor Browser version has changed since the last time Torbutton
// was loaded, reset the version check preferences in order to avoid
// incorrectly reporting that the browser needs to be updated.
var last_version;
try {
last_version = m_tb_prefs.getCharPref(k_tb_last_browser_version_pref);
} catch (e) {}
if (cur_version != last_version) {
m_tb_prefs.setBoolPref(k_tb_browser_update_needed_pref, false);
if (m_tb_prefs.prefHasUserValue(k_tb_last_update_check_pref)) {
m_tb_prefs.clearUserPref(k_tb_last_update_check_pref);
}
if (cur_version)
m_tb_prefs.setCharPref(k_tb_last_browser_version_pref, cur_version);
}
let tlps;
try {
tlps = Cc["@torproject.org/torlauncher-protocol-service;1"]
.getService(Ci.nsISupports).wrappedJSObject;
} catch(e) {}
// Bug 1506 P4: These vars are very important for New Identity
var environ = Components.classes["@mozilla.org/process/environment;1"]
.getService(Components.interfaces.nsIEnvironment);
if (environ.exists("TOR_CONTROL_PASSWD")) {
m_tb_control_pass = environ.get("TOR_CONTROL_PASSWD");
} else if (environ.exists("TOR_CONTROL_COOKIE_AUTH_FILE")) {
var cookie_path = environ.get("TOR_CONTROL_COOKIE_AUTH_FILE");
try {
if ("" != cookie_path) {
m_tb_control_pass = torbutton_read_authentication_cookie(cookie_path);
}
} catch(e) {
torbutton_log(4, 'unable to read authentication cookie');
}
} else try {
// Try to get password from Tor Launcher.
m_tb_control_pass = tlps.TorGetPassword(false);
} catch(e) {}
// Try to get the control port IPC file (an nsIFile) from Tor Launcher,
// since Tor Launcher knows how to handle its own preferences and how to
// resolve relative paths.
try {
m_tb_control_ipc_file = tlps.TorGetControlIPCFile();
} catch(e) {}
if (m_tb_control_ipc_file) {
m_tb_control_desc = m_tb_control_ipc_file.path;
} else {
if (environ.exists("TOR_CONTROL_PORT")) {
m_tb_control_port = environ.get("TOR_CONTROL_PORT");
} else {
try {
const kTLControlPortPref = "extensions.torlauncher.control_port";
m_tb_control_port = m_tb_prefs.getIntPref(kTLControlPortPref);
} catch(e) {
// Since we want to disable some features when Tor Launcher is
// not installed (e.g., New Identity), we do not set a default
// port value here.
}
}
if (m_tb_control_port) {
m_tb_control_desc = "" + m_tb_control_port;
}
if (environ.exists("TOR_CONTROL_HOST")) {
m_tb_control_host = environ.get("TOR_CONTROL_HOST");
} else {
try {
const kTLControlHostPref = "extensions.torlauncher.control_host";
m_tb_control_host = m_tb_prefs.getCharPref(kTLControlHostPref);
} catch(e) {
m_tb_control_host = "127.0.0.1";
}
}
}
// Add about:tor IPC message listener.
window.messageManager.addMessageListener("AboutTor:Loaded",
torbutton_abouttor_message_handler);
window.messageManager.addMessageListener("AboutTor:HideDonationBanner",
torbutton_abouttor_message_handler);
torbutton_donation_banner_countdown();
setupPreferencesForMobile();
// XXX: Get rid of the cached asmjs (or IndexedDB) files on disk in case we
// don't allow things saved to disk. This is an ad-hoc fix to work around
// #19417. Once this is properly solved we should remove this code again.
if (m_tb_prefs.getBoolPref("browser.privatebrowsing.autostart")) {
let orig_quota_test = m_tb_prefs.getBoolPref("dom.quotaManager.testing");
try {
// This works only by setting the pref to `true` otherwise we get an
// exception and nothing is happening.
m_tb_prefs.setBoolPref("dom.quotaManager.testing", true);
Cc["@mozilla.org/dom/quota-manager-service;1"]
.getService(Ci.nsIQuotaManagerService).clear();
} catch(e) {
} finally {
m_tb_prefs.setBoolPref("dom.quotaManager.testing", orig_quota_test);
}
}
// listen for our toolbar button being added so we can initialize it
torbutton_init_toolbutton();
torbutton_log(1, 'registering pref observer');
torbutton_window_pref_observer.register();
torbutton_log(1, "registering Tor check observer");
torbutton_tor_check_observer.register();
//setting up context menu
//var contextMenu = document.getElementById("contentAreaContextMenu");
//if (contextMenu)
// contextMenu.addEventListener("popupshowing", torbutton_check_contextmenu, false);
// Add toolbutton to the bar.
// This should maybe be in the startup function, but we want to add
// the button to the panel before it's state (color) is set..
if (!m_tb_prefs.getBoolPref("extensions.torbutton.inserted_button")) {
torbutton_log(3, 'Adding button');
try {
// ESR31-style toolbar is handled by the existing compiled-in pref.
// We also need to prevent first-run toolbar reorg (#13378), so we
// reset this toolbar state on first-run.
try {
m_tb_prefs.clearUserPref("browser.uiCustomization.state");
} catch(e) {}
CustomizableUI.reset();
CustomizableUI.undoReset();
torbutton_log(3, 'Button added');
m_tb_prefs.setBoolPref("extensions.torbutton.inserted_button", true);
} catch(e) {
torbutton_log(4, 'Failed to add Torbutton to toolbar: '+e);
}
}
torbutton_update_toolbutton();
torbutton_notify_if_update_needed();
createTorCircuitDisplay(m_tb_control_ipc_file, m_tb_control_host,
m_tb_control_port, m_tb_control_pass,
"extensions.torbutton.display_circuit");
torbutton_init_user_manual_links();
// Arrange for our about:tor content script to be loaded in each frame.
window.messageManager.loadFrameScript(
"chrome://torbutton/content/aboutTor/aboutTor-content.js", true);
torbutton_log(3, 'init completed');
}
var torbutton_abouttor_message_handler = {
// Receive IPC messages from the about:tor content script.
receiveMessage: function(aMessage) {
switch(aMessage.name) {
case "AboutTor:Loaded":
aMessage.target.messageManager.sendAsyncMessage("AboutTor:ChromeData",
this.chromeData);
break;
case "AboutTor:HideDonationBanner":
torbutton_log(5, "message AboutTor:HideDonationBanner received");
m_tb_prefs.setIntPref(k_tb_donation_banner_countdown, 0);
break;
}
},
// Send privileged data to all of the about:tor content scripts.
updateAllOpenPages: function() {
window.messageManager.broadcastAsyncMessage("AboutTor:ChromeData",
this.chromeData);
},
// The chrome data contains all of the data needed by the about:tor
// content process that is only available here (in the chrome process).
// It is sent to the content process when an about:tor window is opened
// and in response to events such as the browser noticing that Tor is
// not working.
get chromeData() {
return {
torOn: torbutton_tor_check_ok()
};
}
};
function torbutton_confirm_plugins() {
var any_plugins_enabled = false;
var PH=Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
var P=PH.getPluginTags({});
for(var i=0; i<P.length; i++) {
if (!P[i].disabled)
any_plugins_enabled = true;
}
if (!any_plugins_enabled) {
torbutton_log(3, "False positive on plugin notification. Ignoring");
return;
}
torbutton_log(3, "Confirming plugin usage.");
var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
// Display two buttons, both with string titles.
var flags = prompts.STD_YES_NO_BUTTONS + prompts.BUTTON_DELAY_ENABLE;
var message = torbutton_get_property_string("torbutton.popup.confirm_plugins");
var askAgainText = torbutton_get_property_string("torbutton.popup.never_ask_again");
var askAgain = {value: false};
var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var no_plugins = (prompts.confirmEx(win, "", message, flags, null, null, null,
askAgainText, askAgain) == 1);
m_tb_prefs.setBoolPref("extensions.torbutton.confirm_plugins", !askAgain.value);
// The pref observer for "plugin.disable" will set the appropriate plugin state.
// So, we only touch the pref if it has changed.
if (no_plugins !=
m_tb_prefs.getBoolPref("plugin.disable"))
m_tb_prefs.setBoolPref("plugin.disable", no_plugins);
else
torbutton_toggle_plugins(no_plugins);
// Now, if any tabs were open to about:addons, reload them. Our popup
// messed up that page.
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var browserEnumerator = wm.getEnumerator("navigator:browser");
// Check each browser instance for our URL
while (browserEnumerator.hasMoreElements()) {
var browserWin = browserEnumerator.getNext();
var tabbrowser = browserWin.gBrowser;
// Check each tab of this browser instance
var numTabs = tabbrowser.browsers.length;
for (var index = 0; index < numTabs; index++) {
var currentBrowser = tabbrowser.getBrowserAtIndex(index);
if ("about:addons" == currentBrowser.currentURI.spec) {
torbutton_log(3, "Got browser: "+currentBrowser.currentURI.spec);
currentBrowser.reload();
}
}
}
}
function torbutton_inform_about_tbb() {
var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
var message = torbutton_get_property_string("torbutton.popup.prompt_torbrowser");
var title = torbutton_get_property_string("torbutton.title.prompt_torbrowser");
var checkbox = {value: false};
var sb = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService);
var browserstrings = sb.createBundle("chrome://browser/locale/browser.properties");
var askagain = browserstrings.GetStringFromName("privateBrowsingNeverAsk");
var response = prompts.alertCheck(null, title, message, askagain, checkbox);
// Update preferences to reflect their response and to prevent the prompt from
// being displayed again.
m_tb_prefs.setBoolPref("extensions.torbutton.prompt_torbrowser", !checkbox.value);
}
// Bug 1506 P2: It might be nice to let people move the button around, I guess?
function torbutton_get_toolbutton() {
var o_toolbutton = false;
torbutton_log(1, 'get_toolbutton(): looking for button element');
if (document.getElementById("torbutton-button")) {
o_toolbutton = document.getElementById("torbutton-button");
} else if (document.getElementById("torbutton-button-tb")) {
o_toolbutton = document.getElementById("torbutton-button-tb");
} else if (document.getElementById("torbutton-button-tb-msg")) {
o_toolbutton = document.getElementById("torbutton-button-tb-msg");
} else {
torbutton_log(3, 'get_toolbutton(): did not find torbutton-button');
}
return o_toolbutton;
}
function torbutton_update_is_needed() {
var updateNeeded = false;
try {
updateNeeded = m_tb_prefs.getBoolPref(k_tb_browser_update_needed_pref);
} catch (e) {}
return updateNeeded;
}
function torbutton_notify_if_update_needed() {
function setOrClearAttribute(aElement, aAttrName, aValue)
{
if (!aElement || !aAttrName)
return;
if (aValue)
aElement.setAttribute(aAttrName, aValue);
else
aElement.removeAttribute(aAttrName);
}
let updateNeeded = torbutton_update_is_needed();
// Change look of toolbar item (enable/disable animated update icon).
var btn = torbutton_get_toolbutton();
setOrClearAttribute(btn, "tbUpdateNeeded", updateNeeded);
// Make the "check for update" menu item bold if an update is needed.
var item = document.getElementById("torbutton-checkForUpdate");
setOrClearAttribute(item, "tbUpdateNeeded", updateNeeded);
}
function torbutton_check_for_update() {
// Open the update prompt in the correct mode. The update state
// checks used here were adapted from isPending() and isApplied() in
// Mozilla's browser/base/content/aboutDialog.js code.
let updateMgr = Cc["@mozilla.org/updates/update-manager;1"]
.getService(Ci.nsIUpdateManager);
let update = updateMgr.activeUpdate;
let updateState = (update) ? update.state : undefined;
let pendingStates = [ "pending", "pending-service",
"applied", "applied-service" ];
let isPending = (updateState && (pendingStates.indexOf(updateState) >= 0));
let prompter = Cc["@mozilla.org/updates/update-prompt;1"]
.createInstance(Ci.nsIUpdatePrompt);
if (isPending)
prompter.showUpdateDownloaded(update, false);
else
prompter.checkForUpdates();
}
// Bug 1506 P4: Checking for Tor Browser updates is pretty important,
// probably even as a fallback if we ever do get a working updater.
function torbutton_do_async_versioncheck() {
if (!m_tb_tbb || !m_tb_prefs.getBoolPref("extensions.torbutton.versioncheck_enabled")) {
return;
}
// Suppress update check if done recently.
const kMinSecsBetweenChecks = 120 * 60; // 2.0 hours
var now = Date.now() / 1000;
var lastCheckTime;
try {
lastCheckTime = parseFloat(m_tb_prefs.getCharPref(k_tb_last_update_check_pref));
if (isNaN(lastCheckTime))
lastCheckTime = undefined;
} catch (e) {}
if (lastCheckTime && ((now - lastCheckTime) < kMinSecsBetweenChecks))
return;
m_tb_prefs.setCharPref(k_tb_last_update_check_pref, now);
torbutton_log(3, "Checking version with socks port: "
+m_tb_prefs.getIntPref("network.proxy.socks_port"));
try {
var req = new XMLHttpRequest();
var url = m_tb_prefs.getCharPref("extensions.torbutton.versioncheck_url");
req.open('GET', url, true);
req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
req.overrideMimeType("text/json");
req.onreadystatechange = function (oEvent) {
if (req.readyState === 4) {
if(req.status == 200) {
if(!req.responseText) {
torbutton_log(5, "Version check failed! No JSON present!");
return -1;
}
try {
var version_list = JSON.parse(req.responseText);
var my_version = m_tb_prefs.getCharPref("torbrowser.version");
var platformSuffix;
var platform = Services.appinfo.OS;
switch (platform) {
case "WINNT":
platformSuffix = "Windows";
break;
case "Darwin":
platformSuffix = "MacOS";
break;
case "Linux":
case "Android":
platformSuffix = platform;
break;
}
if (platformSuffix)
my_version += "-" + platformSuffix;
if (version_list.indexOf(my_version) >= 0) {
torbutton_log(3, "Version check passed.");
m_tb_prefs.setBoolPref(k_tb_browser_update_needed_pref, false);
return;
}
torbutton_log(5, "Your Tor Browser is out of date.");
m_tb_prefs.setBoolPref(k_tb_browser_update_needed_pref, true);
return;
} catch(e) {
torbutton_log(5, "Version check failed! JSON parsing error: "+e);
return;
}
} else if (req.status == 404) {
// We're going to assume 404 means the service is not implemented yet.
torbutton_log(3, "Version check failed. Versions file is 404.");
return -1;
}
torbutton_log(5, "Version check failed! Web server error: "+req.status);
return -1;
}
};
req.send(null);
} catch(e) {
if(e.result == 0x80004005) { // NS_ERROR_FAILURE
torbutton_log(5, "Version check failed! Is tor running?");
return -1;
}
torbutton_log(5, "Version check failed! Tor internal error: "+e);
return -1;
}
}
function torbutton_update_toolbutton()
{
let o_toolbutton = torbutton_get_toolbutton();
if (!o_toolbutton) return;
let isOK = torbutton_tor_check_ok();
let tbstatus = isOK ? "on" : "off";
o_toolbutton.setAttribute("tbstatus", tbstatus);
let tooltipKey = isOK ? "torbutton.panel.label.enabled"
: "torbutton.panel.label.disabled";
o_toolbutton.setAttribute("tooltiptext",
torbutton_get_property_string(tooltipKey));
}
// Bug 1506 P4: Control port interaction. Needed for New Identity.
function torbutton_socket_readline(input) {
var str = "";
var bytes;
while((bytes = input.readBytes(1)) != "\n") {
if (bytes != '\r')
str += bytes;
}
return str;
}
// Bug 1506 P4: Control port interaction. Needed for New Identity.
function torbutton_read_authentication_cookie(path) {
var file = Components.classes['@mozilla.org/file/local;1']
.createInstance(Components.interfaces.nsIFile);
file.initWithPath(path);
var fileStream = Components.classes['@mozilla.org/network/file-input-stream;1']
.createInstance(Components.interfaces.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
var binaryStream = Components.classes['@mozilla.org/binaryinputstream;1']
.createInstance(Components.interfaces.nsIBinaryInputStream);
binaryStream.setInputStream(fileStream);
var array = binaryStream.readByteArray(fileStream.available());
binaryStream.close();
fileStream.close();
return torbutton_array_to_hexdigits(array);
}
// Bug 1506 P4: Control port interaction. Needed for New Identity.
function torbutton_array_to_hexdigits(array) {
return array.map(function(c) {
return String("0" + c.toString(16)).slice(-2)
}).join('');
};
// Bug 1506 P4: Control port interaction. Needed for New Identity.
//
// Executes a command on the control port.
// Return a string response upon success and null upon error.
function torbutton_send_ctrl_cmd(command) {
// We spin the event queue until it is empty and we can be sure that sending
// NEWNYM is not leading to a deadlock (see bug 9531 comment 23 for an
// invstigation on why and when this may happen). This is surrounded by
// suppressing/unsuppressing user initiated events in a window's document to
// be sure that these events are not interfering with processing events being
// in the event queue.
var thread = Cc["@mozilla.org/thread-manager;1"].
getService(Ci.nsIThreadManager).currentThread;
m_tb_domWindowUtils.suppressEventHandling(true);
while (thread.processNextEvent(false)) {}
m_tb_domWindowUtils.suppressEventHandling(false);
try {
let sts = Cc["@mozilla.org/network/socket-transport-service;1"]
.getService(Ci.nsISocketTransportService);
let socket;
if (m_tb_control_ipc_file) {
socket = sts.createUnixDomainTransport(m_tb_control_ipc_file);
} else {
socket = sts.createTransport(null, 0, m_tb_control_host,
m_tb_control_port, null);
}
// If we don't get a response from the control port in 2 seconds, someting is wrong..
socket.setTimeout(Ci.nsISocketTransport.TIMEOUT_READ_WRITE, 2);
var input = socket.openInputStream(3, 1, 1); // 3 == OPEN_BLOCKING|OPEN_UNBUFFERED
var output = socket.openOutputStream(3, 1, 1); // 3 == OPEN_BLOCKING|OPEN_UNBUFFERED
var inputStream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
var outputStream = Cc["@mozilla.org/binaryoutputstream;1"].createInstance(Ci.nsIBinaryOutputStream);
inputStream.setInputStream(input);
outputStream.setOutputStream(output);
var auth_cmd = "AUTHENTICATE "+m_tb_control_pass+"\r\n";
outputStream.writeBytes(auth_cmd, auth_cmd.length);
var bytes = torbutton_socket_readline(inputStream);
if (bytes.indexOf("250") != 0) {
torbutton_safelog(4, "Unexpected auth response on control port "+m_tb_control_desc+":", bytes);
return null;
}
outputStream.writeBytes(command, command.length);
bytes = torbutton_socket_readline(inputStream);
if(bytes.indexOf("250") != 0) {
torbutton_safelog(4, "Unexpected command response on control port "+m_tb_control_desc+":", bytes);
return null;
}
// Closing these streams prevents a shutdown hang on Mac OS. See bug 10201.
inputStream.close();
outputStream.close();
socket.close(Cr.NS_OK);
return bytes.substr(4);
} catch(e) {
torbutton_log(4, "Exception on control port "+e);
return null;
}
}
// Bug 1506 P4: Needed for New IP Address
function torbutton_new_circuit() {
let firstPartyDomain = gBrowser.contentPrincipal.originAttributes
.firstPartyDomain;
let domainIsolator = Cc["@torproject.org/domain-isolator;1"]
.getService(Ci.nsISupports).wrappedJSObject;
domainIsolator.newCircuitForDomain(firstPartyDomain);
gBrowser.reloadWithFlags(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
}
// Bug 1506 P4: Needed for New Identity.
function torbutton_new_identity() {
try {
// Make sure that we can only click once on New Identiy to avoid race
// conditions leading to failures (see bug 11783 for an example).
// TODO: Remove the Torbutton menu entry again once we have done our
// security control redesign.
document.getElementById("torbutton-new-identity").disabled = true;
document.getElementById("menu_newIdentity").disabled = true;
document.getElementById("appMenuNewIdentity").disabled = true;
let shouldConfirm = m_tb_prefs.getBoolPref("extensions.torbutton.confirm_newnym");
if (shouldConfirm) {
let prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService);
// Display two buttons, both with string titles.
let flags = prompts.STD_YES_NO_BUTTONS;
let message = torbutton_get_property_string("torbutton.popup.confirm_newnym");
let askAgainText = torbutton_get_property_string("torbutton.popup.never_ask_again");
let askAgain = {value: false};
let confirmed = (prompts.confirmEx(null, "", message, flags, null, null, null,
askAgainText, askAgain) == 0);
m_tb_prefs.setBoolPref("extensions.torbutton.confirm_newnym", !askAgain.value);
if (confirmed) {
torbutton_do_new_identity();
} else {
// TODO: Remove the Torbutton menu entry again once we have done our
// security control redesign.
document.getElementById("torbutton-new-identity").disabled = false;
document.getElementById("menu_newIdentity").disabled = false;
document.getElementById("appMenuNewIdentity").disabled = false;
}
} else {
torbutton_do_new_identity();
}
} catch(e) {
// If something went wrong make sure we have the New Identity button
// enabled (again).
// TODO: Remove the Torbutton menu entry again once we have done our
// security control redesign.
document.getElementById("torbutton-new-identity").disabled = false;
document.getElementById("menu_newIdentity").disabled = false;
document.getElementById("appMenuNewIdentity").disabled = false;
torbutton_log(5, "Unexpected error on new identity: "+e);
window.alert("Torbutton: Unexpected error on new identity: "+e);
}
}
/* The "New Identity" implementation does the following:
* 1. Disables Javascript and plugins on all tabs
* 2. Clears state:
* a. OCSP
* b. Cache + image cache
* c. Site-specific zoom
* d. Cookies+DOM Storage+safe browsing key
* e. google wifi geolocation token
* f. http auth
* g. SSL Session IDs
* h. last open location url
* i. clear content prefs
* j. permissions
* k. site security settings (e.g. HSTS)
* l. IndexedDB and asmjscache storage
* 3. Sends tor the NEWNYM signal to get a new circuit
* 4. Opens a new window with the default homepage
* 5. Closes this window
*
* XXX: intermediate SSL certificates are not cleared.
*/
// Bug 1506 P4: Needed for New Identity.
function torbutton_do_new_identity() {
var obsSvc = Components.classes["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
torbutton_log(3, "New Identity: Disabling JS");
torbutton_disable_all_js();
m_tb_prefs.setBoolPref("browser.zoom.siteSpecific",
!m_tb_prefs.getBoolPref("browser.zoom.siteSpecific"));
m_tb_prefs.setBoolPref("browser.zoom.siteSpecific",
!m_tb_prefs.getBoolPref("browser.zoom.siteSpecific"));
try {
if(m_tb_prefs.prefHasUserValue("geo.wifi.access_token")) {
m_tb_prefs.clearUserPref("geo.wifi.access_token");
}
} catch(e) {
torbutton_log(3, "Exception on wifi token clear: "+e);
}
try {
if(m_tb_prefs.prefHasUserValue("general.open_location.last_url")) {
m_tb_prefs.clearUserPref("general.open_location.last_url");
}
} catch(e) {
torbutton_log(3, "Exception on clearing last opened location: "+e);
}
torbutton_log(3, "New Identity: Closing tabs and clearing searchbox");
torbutton_close_tabs_on_new_identity();
// Bug #10800: Trying to clear search/find can cause exceptions
// in unknown cases. Just log for now.
try {
var searchBar = window.document.getElementById("searchbar");
if (searchBar)
searchBar.textbox.reset();
} catch(e) {
torbutton_log(5, "New Identity: Exception on clearing search box: "+e);
}
try {
if (gFindBarInitialized) {
var findbox = gFindBar.getElement("findbar-textbox");
findbox.reset();
gFindBar.close();
}
} catch(e) {
torbutton_log(5, "New Identity: Exception on clearing find bar: "+e);
}
torbutton_log(3, "New Identity: Emitting Private Browsing Session clear event");
obsSvc.notifyObservers(null, "browser:purge-session-history", "");
torbutton_log(3, "New Identity: Clearing NoScript Temporary Permissions");
try {
if ("@maone.net/noscript-service;1" in Components.classes) {
var nsSvc = Components.classes["@maone.net/noscript-service;1"].getService().wrappedJSObject
nsSvc.eraseTemp();
}
} catch(e) {
torbutton_log(5, "New Identity: Error clearing NoScript Temporary Permissions: "+e);
window.alert("Torbutton: Error clearing NoScript Temporary Permissions: "+e);
}
torbutton_log(3, "New Identity: Clearing HTTP Auth");
if(m_tb_prefs.getBoolPref('extensions.torbutton.clear_http_auth')) {
var auth = Components.classes["@mozilla.org/network/http-auth-manager;1"].
getService(Components.interfaces.nsIHttpAuthManager);
auth.clearAll();
}
torbutton_log(3, "New Identity: Clearing Crypto Tokens");
// Clear all crypto auth tokens. This includes calls to PK11_LogoutAll(),
// nsNSSComponent::LogoutAuthenticatedPK11() and clearing the SSL session
// cache.
let sdr = Components.classes["@mozilla.org/security/sdr;1"].
getService(Components.interfaces.nsISecretDecoderRing);
sdr.logoutAndTeardown();
// This clears the OCSP cache.
//
// nsNSSComponent::Observe() watches security.OCSP.enabled, which calls
// setValidationOptions(), which in turn calls setNonPkixOcspEnabled() which,
// if security.OCSP.enabled is set to 0, calls CERT_DisableOCSPChecking(),
// which calls CERT_ClearOCSPCache().