home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / firefox / components / nsSafebrowsingApplication.js < prev    next >
Encoding:
Text File  |  2006-08-18  |  135.1 KB  |  3,775 lines

  1. const Cc = Components.classes;
  2. const Ci = Components.interfaces;
  3.  
  4. // This is copied from toolkit/components/content/js/lang.js.
  5. // It seems cleaner to copy this rather than #include from so far away.
  6. Function.prototype.inherits = function(parentCtor) {
  7.   var tempCtor = function(){};
  8.   tempCtor.prototype = parentCtor.prototype;
  9.   this.superClass_ = parentCtor.prototype;
  10.   this.prototype = new tempCtor();
  11. }  
  12.  
  13. /* ***** BEGIN LICENSE BLOCK *****
  14.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  15.  *
  16.  * The contents of this file are subject to the Mozilla Public License Version
  17.  * 1.1 (the "License"); you may not use this file except in compliance with
  18.  * the License. You may obtain a copy of the License at
  19.  * http://www.mozilla.org/MPL/
  20.  *
  21.  * Software distributed under the License is distributed on an "AS IS" basis,
  22.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  23.  * for the specific language governing rights and limitations under the
  24.  * License.
  25.  *
  26.  * The Original Code is Google Safe Browsing.
  27.  *
  28.  * The Initial Developer of the Original Code is Google Inc.
  29.  * Portions created by the Initial Developer are Copyright (C) 2006
  30.  * the Initial Developer. All Rights Reserved.
  31.  *
  32.  * Contributor(s):
  33.  *   Fritz Schneider <fritz@google.com> (original author)
  34.  *
  35.  * Alternatively, the contents of this file may be used under the terms of
  36.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  37.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  38.  * in which case the provisions of the GPL or the LGPL are applicable instead
  39.  * of those above. If you wish to allow use of your version of this file only
  40.  * under the terms of either the GPL or the LGPL, and not to allow others to
  41.  * use your version of this file under the terms of the MPL, indicate your
  42.  * decision by deleting the provisions above and replace them with the notice
  43.  * and other provisions required by the GPL or the LGPL. If you do not delete
  44.  * the provisions above, a recipient may use your version of this file under
  45.  * the terms of any one of the MPL, the GPL or the LGPL.
  46.  *
  47.  * ***** END LICENSE BLOCK ***** */
  48.  
  49.  
  50. // This file implements an event registrar, an object with which you
  51. // can register handlers for arbitrary programmer-defined
  52. // events. Events are arbitrary strings and listeners are functions
  53. // taking an object (stuffed with arguments) as a parameter. When you
  54. // fire an event through the registrar, all listeners are invoked in
  55. // an unspecified order. The firing function takes an object to be
  56. // passed into each handler (it is _not_ copied, so be careful). We
  57. // chose this calling convention so we don't have to change handler
  58. // signatures when adding new information.
  59. //
  60. // Why not just use notifier/observers? Because passing data around
  61. // with them requires either serialization or a new xpcom interface,
  62. // both of which are a pain in the ass.
  63. //
  64. // Example:
  65. //
  66. // // Set up a listener
  67. // this.handleTabload = function(e) {
  68. //   foo(e.url);
  69. //   bar(e.browser);
  70. // };
  71. //
  72. // // Set up the registrar
  73. // var eventTypes = ["tabload", "tabunload", "tabswitch"];
  74. // var registrar = new EventRegistrar(eventTypes);
  75. // var handler = BindToObject(this.handleTabload, this);
  76. //
  77. // // Register a listener
  78. // registrar.registerListener("tabload", handler);
  79. //
  80. // // Fire an event and remove the listener
  81. // var event = { "url": "http://www", "browser": browser };
  82. // registrar.fire("tabload", event);
  83. // registrar.removeListener("tabload", handler);
  84. //
  85. // TODO: could add ability to cancel further handlers by having listeners
  86. //       return a boolean
  87.  
  88. /**
  89.  * EventRegistrars are used to manage user-defined events. 
  90.  *
  91.  * @constructor
  92.  * @param eventTypes {Array or Object} Array holding names of events or
  93.  *                   Object holding properties the values of which are 
  94.  *                   names (strings) for which listeners can register
  95.  */
  96. function EventRegistrar(eventTypes) {
  97.   this.eventTypes = [];
  98.   this.listeners_ = {};          // Listener sets, index by event type
  99.  
  100.   if (eventTypes instanceof Array) {
  101.     var events = eventTypes;
  102.   } else if (typeof eventTypes == "object") {
  103.     var events = [];
  104.     for (var e in eventTypes)
  105.       events.push(eventTypes[e]);
  106.   } else {
  107.     throw new Error("Unrecognized init parameter to EventRegistrar");
  108.   }
  109.  
  110.   for (var i = 0; i < events.length; i++) {
  111.     this.eventTypes.push(events[i]);          // Copy in case caller mutates
  112.     this.listeners_[events[i]] = 
  113.       new ListDictionary(events[i] + "Listeners");
  114.   }
  115. }
  116.  
  117. /**
  118.  * Indicates whether the given event is one the registrar can handle.
  119.  * 
  120.  * @param eventType {String} The name of the event to look up
  121.  * @returns {Boolean} false if the event type is not known or the 
  122.  *          event type string itself if it is
  123.  */
  124. EventRegistrar.prototype.isKnownEventType = function(eventType) {
  125.   for (var i=0; i < this.eventTypes.length; i++)
  126.     if (eventType == this.eventTypes[i])
  127.       return eventType;
  128.   return false;
  129. }
  130.  
  131. /**
  132.  * Add an event type to listen for.
  133.  * @param eventType {String} The name of the event to add
  134.  */
  135. EventRegistrar.prototype.addEventType = function(eventType) {
  136.   if (this.isKnownEventType(eventType))
  137.     throw new Error("Event type already known: " + eventType);
  138.  
  139.   this.eventTypes.push(eventType);
  140.   this.listeners_[eventType] = new ListDictionary(eventType + "Listeners");
  141. }
  142.  
  143. /**
  144.  * Register to receive events of the type passed in. 
  145.  * 
  146.  * @param eventType {String} indicating the event type (one of this.eventTypes)
  147.  * @param listener {Function} to invoke when the event occurs.
  148.  */
  149. EventRegistrar.prototype.registerListener = function(eventType, listener) {
  150.   if (this.isKnownEventType(eventType) === false)
  151.     throw new Error("Unknown event type: " + eventType);
  152.  
  153.   this.listeners_[eventType].addMember(listener);
  154. }
  155.  
  156. /**
  157.  * Unregister a listener.
  158.  * 
  159.  * @param eventType {String} One of EventRegistrar.eventTypes' members
  160.  * @param listener {Function} Function to remove as listener
  161.  */
  162. EventRegistrar.prototype.removeListener = function(eventType, listener) {
  163.   if (this.isKnownEventType(eventType) === false)
  164.     throw new Error("Unknown event type: " + eventType);
  165.  
  166.   this.listeners_[eventType].removeMember(listener);
  167. }
  168.  
  169. /**
  170.  * Invoke the handlers for the given eventType. 
  171.  *
  172.  * @param eventType {String} The event to fire
  173.  * @param e {Object} Object containing the parameters of the event
  174.  */
  175. EventRegistrar.prototype.fire = function(eventType, e) {
  176.   if (this.isKnownEventType(eventType) === false)
  177.     throw new Error("Unknown event type: " + eventType);
  178.  
  179.   var invoke = function(listener) {
  180.     listener(e);
  181.   };
  182.  
  183.   this.listeners_[eventType].forEach(invoke);
  184. }
  185. /* ***** BEGIN LICENSE BLOCK *****
  186.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  187.  *
  188.  * The contents of this file are subject to the Mozilla Public License Version
  189.  * 1.1 (the "License"); you may not use this file except in compliance with
  190.  * the License. You may obtain a copy of the License at
  191.  * http://www.mozilla.org/MPL/
  192.  *
  193.  * Software distributed under the License is distributed on an "AS IS" basis,
  194.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  195.  * for the specific language governing rights and limitations under the
  196.  * License.
  197.  *
  198.  * The Original Code is Google Safe Browsing.
  199.  *
  200.  * The Initial Developer of the Original Code is Google Inc.
  201.  * Portions created by the Initial Developer are Copyright (C) 2006
  202.  * the Initial Developer. All Rights Reserved.
  203.  *
  204.  * Contributor(s):
  205.  *   Fritz Schneider <fritz@google.com> (original author)
  206.  *
  207.  * Alternatively, the contents of this file may be used under the terms of
  208.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  209.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  210.  * in which case the provisions of the GPL or the LGPL are applicable instead
  211.  * of those above. If you wish to allow use of your version of this file only
  212.  * under the terms of either the GPL or the LGPL, and not to allow others to
  213.  * use your version of this file under the terms of the MPL, indicate your
  214.  * decision by deleting the provisions above and replace them with the notice
  215.  * and other provisions required by the GPL or the LGPL. If you do not delete
  216.  * the provisions above, a recipient may use your version of this file under
  217.  * the terms of any one of the MPL, the GPL or the LGPL.
  218.  *
  219.  * ***** END LICENSE BLOCK ***** */
  220.  
  221.  
  222. // This file implements a Dictionary data structure using a list
  223. // (array). We could instead use an object, but using a list enables
  224. // us to have ordering guarantees for iterators. The interface it exposes 
  225. // is:
  226. // 
  227. // addMember(item)
  228. // removeMember(item)
  229. // isMember(item)
  230. // forEach(func)
  231. //
  232. // TODO: this class isn't really a Dictionary, it's more like a 
  233. //       membership set (i.e., a set without union and whatnot). We
  234. //       should probably change the name to avoid confusion.
  235.  
  236. /**
  237.  * Create a new Dictionary data structure.
  238.  *
  239.  * @constructor
  240.  * @param name A string used to name the dictionary
  241.  */
  242. function ListDictionary(name) {
  243.   this.name_ = name;
  244.   this.members_ = [];
  245. }
  246.  
  247. /**
  248.  * Look an item up.
  249.  *
  250.  * @param item An item to look up in the dictionary
  251.  * @returns Boolean indicating if the parameter is a member of the dictionary
  252.  */
  253. ListDictionary.prototype.isMember = function(item) {
  254.   for (var i=0; i < this.members_.length; i++)
  255.     if (this.members_[i] == item)
  256.       return true;
  257.   return false;
  258. }
  259.  
  260. /**
  261.  * Add an item
  262.  *
  263.  * @param item An item to add (does not check for dups)
  264.  */
  265. ListDictionary.prototype.addMember = function(item) {
  266.   this.members_.push(item);
  267. }
  268.  
  269. /**
  270.  * Remove an item
  271.  *
  272.  * @param item The item to remove (doesn't check for dups)
  273.  * @returns Boolean indicating if the item was removed
  274.  */
  275. ListDictionary.prototype.removeMember = function(item) {
  276.   for (var i=0; i < this.members_.length; i++) {
  277.     if (this.members_[i] == item) {
  278.       for (var j=i; j < this.members_.length; j++)
  279.         this.members_[j] = this.members_[j+1];
  280.  
  281.       this.members_.length--;
  282.       return true;
  283.     }
  284.   }
  285.   return false;
  286. }
  287.  
  288. /**
  289.  * Apply a function to each of the members. Does NOT replace the members
  290.  * in the dictionary with results -- it just calls the function on each one.
  291.  *
  292.  * @param func Function to apply to the dictionary's members
  293.  */
  294. ListDictionary.prototype.forEach = function(func) {
  295.   if (typeof func != "function")
  296.     throw new Error("argument to forEach is not a function, it's a(n) " + 
  297.                     typeof func);
  298.  
  299.   for (var i=0; i < this.members_.length; i++)
  300.     func(this.members_[i]);
  301. }
  302. /* ***** BEGIN LICENSE BLOCK *****
  303.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  304.  *
  305.  * The contents of this file are subject to the Mozilla Public License Version
  306.  * 1.1 (the "License"); you may not use this file except in compliance with
  307.  * the License. You may obtain a copy of the License at
  308.  * http://www.mozilla.org/MPL/
  309.  *
  310.  * Software distributed under the License is distributed on an "AS IS" basis,
  311.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  312.  * for the specific language governing rights and limitations under the
  313.  * License.
  314.  *
  315.  * The Original Code is Google Safe Browsing.
  316.  *
  317.  * The Initial Developer of the Original Code is Google Inc.
  318.  * Portions created by the Initial Developer are Copyright (C) 2006
  319.  * the Initial Developer. All Rights Reserved.
  320.  *
  321.  * Contributor(s):
  322.  *   Fritz Schneider <fritz@google.com> (original author)
  323.  *
  324.  * Alternatively, the contents of this file may be used under the terms of
  325.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  326.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  327.  * in which case the provisions of the GPL or the LGPL are applicable instead
  328.  * of those above. If you wish to allow use of your version of this file only
  329.  * under the terms of either the GPL or the LGPL, and not to allow others to
  330.  * use your version of this file under the terms of the MPL, indicate your
  331.  * decision by deleting the provisions above and replace them with the notice
  332.  * and other provisions required by the GPL or the LGPL. If you do not delete
  333.  * the provisions above, a recipient may use your version of this file under
  334.  * the terms of any one of the MPL, the GPL or the LGPL.
  335.  *
  336.  * ***** END LICENSE BLOCK ***** */
  337.  
  338.  
  339. // This file implements a G_TabbedBrowserWatcher, an object
  340. // encapsulating and abstracting the mechanics of working with tabs
  341. // and the documents within them. The watcher provides notification of
  342. // various DOM-related events (a document loaded, a document unloaded,
  343. // tab was created/destroyed, user switched tabs, etc.) as well as
  344. // commonly required methods (get me the current tab, find the tab to
  345. // which this document belongs, etc.).
  346. //
  347. // This class does not do progresslistener-based notifications; for that,
  348. // use the NavWatcher.
  349. //
  350. // Note: I use "browser" and "tab" interchangeably.
  351. //
  352. // This class adds a level of indirection to event registration. You
  353. // initialize it with a tabbedbrowser, and then register to hear
  354. // events from it instead of from the tabbedbrowser or browser itself.
  355. // Your handlers are invoked with a custom object as an argument (see
  356. // below). This object contains useful information such as a reference
  357. // to the browser in which the event is happening and whether the
  358. // event is occurring on the top-level document in that browser.
  359. //
  360. // The events you can register to hear are:
  361. //
  362. // EVENT             DESCRIPTION
  363. // -----             -----------
  364. // load              Fires when a page is shown in the browser window and
  365. //                   this page wasn't in the bfcache
  366. //
  367. // unload            Fires when a page is nav'd away from in the browser window
  368. //                   and the page isn't going into the bfcache
  369. //
  370. // pageshow          Fires when a page is shown in the browser window, whether
  371. //                   it came from bfcache or not. (There is a "persisted"
  372. //                   property we can get from the event object if we'd like.
  373. //                   It indicates whether the page was loaded from bfcache.
  374. //                   If false then we known load recently fired).
  375. //
  376. // pagehide          Fires when a page is nav'd away from in the browser,
  377. //                   whether its going into the bfcache or not. (There is
  378. //                   a persisted property here as well that we're not
  379. //                   propagating -- when its true the page is going into
  380. //                   the bfcache, else it's not, and unload will shortly
  381. //                   fire).
  382. //
  383. // domcontentloaded  BROKEN BROKEN BROKEN BROKEN BROKEN BROKEN BROKEN BROKEN
  384. //                   Fires when a doc's DOM is ready, but its externally linked
  385. //                   content hasn't necessarily loaded. This event is
  386. //                   currently broken: it doesn't fire when using the
  387. //                   forward/back buttons in conjunction with the bfcache.
  388. //                   Bryner is working on a fix.
  389. //
  390. // tabload           Fires when a new tab has been created (but doesn't
  391. //                   necessarily have content loaded in it)
  392. //
  393. // tabunload         Fires when a tab is being destroyed (and might have had
  394. //                   the content it contains destroyed)
  395. //
  396. // tabswitch         Fires when the user switches tabs
  397. //
  398. // tabmove           Fires when a user drags a tab to a different position
  399. //
  400. //
  401. // For pageshow, pagehide, load, unload, and domcontentloaded, the event
  402. // object you'll receive has the following properties:
  403. //
  404. //      doc -- reference to Document on which the event fired
  405. //      browser -- the browser in which the document resides
  406. //      isTop -- boolean indicating if it is the top-level document
  407. //      inSelected -- boolean indicating if it is in the currently selected tab
  408. //
  409. // For tabload and unload it has:
  410. //
  411. //      browser -- reference to the browser that is loading or closing
  412. //
  413. // For tabswitch it has:
  414. //
  415. //      fromBrowser -- reference to the browser user is switching from
  416. //      toBrowser -- reference to the browser user is switching to
  417. //
  418. // For tabmove it has:
  419. //
  420. //      tab -- the tab that was moved (Note that this is the actual
  421. //             tab widget that holds the document title, not the
  422. //             browser object.  We use this because it's the target
  423. //             of the DOMNodeInserted event.)
  424. //      fromIndex -- the tab index before the move
  425. //      toIndex -- the tab index after the move
  426. //
  427. //
  428. // The order of events is:                   tabload
  429. //                                           domcontentloaded
  430. //                                           load
  431. //                                           pageshow
  432. //                                           --  --
  433. //                                           pagehide
  434. //                                           unload
  435. //                                           tabunload
  436. //
  437. // Example:
  438. //
  439. // function handler(e /*event object*/) {
  440. //   foo(e.browser);
  441. // };
  442. // var watcher = new G_TabbedBrowserWatcher(document.getElementById(gBrowser));
  443. // watcher.registerListener("load", handler);      // register for events
  444. // watcher.removeListener("load", handler);        // unregister
  445. //
  446. //
  447. // TODO, BUGS, ISSUES, COMPLICATIONS:
  448. //
  449. // The only major problem is in closing tabs:
  450. //
  451. //     + When you close a tab, the reference to the Document you get in the
  452. //       unload event is undefined. We pass this along. This could easily
  453. //       be fixed by not listening for unload at all, but instead inferring
  454. //       it from the information in pagehide, and then firing our own "fake"
  455. //       unload after firing pagehide.
  456. //
  457. //     + There's no docshell during the pagehide event, so we can't determine
  458. //       if the document is top-level. We pass undefined in this case.
  459. //
  460. //     + Though the browser reference during tabunload will be valid, its
  461. //       members most likely have already been torn down. Use it in an
  462. //       objectsafemap to keep state if you need its members.
  463. //
  464. //     + The event listener DOMNodeInserted has the potential to cause
  465. //       performance problems if there are too many events fired.  It
  466. //       should be ok, since we inserted it as far as possible into
  467. //       the xul tree.
  468. //
  469. //
  470. // TODO: need better enforcement of unique names. Two tabbedbrowserwatchers
  471. //       with the same name will clobber each other because they use that
  472. //       name to mark browsers they've seen.
  473. // 
  474. // TODO: the functions that iterate of windows and documents badly need
  475. //       to be made cleaner. Right now we have multiple implementations
  476. //       that essentially do the same thing :(
  477. //
  478. // But good enough for government work.
  479.  
  480. /**
  481.  * Encapsulates tab-related information. You can use the
  482.  * G_TabbedBrowserWatcher to watch for events on tabs as well as to
  483.  * retrieve tab-related data (such as what tab is currently showing).
  484.  * It receives many event notifications from G_BrowserWatchers it
  485.  * attaches to newly opening tabs.
  486.  *
  487.  * @param tabBrowser A reference to the tabbed browser you wish to watch.
  488.  *
  489.  * @param name String containing a probabilistically unique name. Used to
  490.  *             ensure that each tabbedbrowserwatcher can uniquely mark
  491.  *             browser it has "seen."
  492.  *
  493.  * @param opt_filterAboutBlank Boolean indicating whether to filter events
  494.  *                             for about:blank. These events are often
  495.  *                             spurious since about:blank is the default
  496.  *                             page for an empty browser.
  497.  *
  498.  * @constructor
  499.  */
  500.  
  501. function G_TabbedBrowserWatcher(tabBrowser, name, opt_filterAboutBlank) {
  502.   this.debugZone = "tabbedbrowserwatcher";
  503.   this.registrar_ = new EventRegistrar(G_TabbedBrowserWatcher.events);
  504.   this.tabBrowser_ = tabBrowser;
  505.   this.filterAboutBlank_ = !!opt_filterAboutBlank;
  506.   this.events = G_TabbedBrowserWatcher.events;      // Convenience pointer
  507.  
  508.   // We need some way to tell if we've seen a browser before, so we
  509.   // set a property on it with a probabilistically unique string. The
  510.   // string is a combination of a static string and one passed in by
  511.   // the caller.
  512.   G_Assert(this, typeof name == "string" && !!name,
  513.            "Need a probabilistically unique name");
  514.   this.name_ = name;
  515.   this.mark_ = G_TabbedBrowserWatcher.mark_ + "-" + this.name_;
  516.  
  517.   this.tabbox_ = this.getTabBrowser().mTabBox;
  518.  
  519.   // There's no tabswitch event in Firefox, so we fake it by watching
  520.   // for selects on the tabbox.
  521.   this.onTabSwitchClosure_ = BindToObject(this.onTabSwitch, this);
  522.   this.tabbox_.addEventListener("select",
  523.                                 this.onTabSwitchClosure_, true);
  524.  
  525.   // Used to determine when the user has switched tabs
  526.   this.lastTab_ = this.getCurrentBrowser();
  527. }
  528.  
  529. // Events for which listeners can register
  530. G_TabbedBrowserWatcher.events = {
  531.    TABSWITCH: "tabswitch",
  532.    };
  533.  
  534. // We mark new tabs as we see them
  535. G_TabbedBrowserWatcher.mark_ = "watcher-marked";
  536.  
  537. /**
  538.  * Remove all the event handlers and clean up circular refs.
  539.  */
  540. G_TabbedBrowserWatcher.prototype.shutdown = function() {
  541.   G_Debug(this, "Removing event listeners");
  542.   if (this.tabbox_) {
  543.     this.tabbox_.removeEventListener("select",
  544.                                      this.onTabSwitchClosure_, true);
  545.     // Break circular ref so we can be gc'ed.
  546.     this.tabbox_ = null;
  547.   }
  548.   // Break circular ref so we can be gc'ed.
  549.   if (this.lastTab_) {
  550.     this.lastTab_ = null;
  551.   }
  552.  
  553.   if (this.tabBrowser_) {
  554.     this.tabBrowser_ = null;
  555.   }
  556. }
  557.  
  558. /**
  559.  * Check to see if we've seen a browser before
  560.  *
  561.  * @param browser Browser to check
  562.  * @returns Boolean indicating if we've attached a BrowserWatcher to this
  563.  *          browser
  564.  */
  565. G_TabbedBrowserWatcher.prototype.isInstrumented_ = function(browser) {
  566.   return !!browser[this.mark_];
  567. }
  568.  
  569. /**
  570.  * Attaches a BrowserWatcher to a browser and marks it as seen
  571.  *
  572.  * @param browser Browser to which to attach a G_BrowserWatcher
  573.  */
  574. G_TabbedBrowserWatcher.prototype.instrumentBrowser_ = function(browser) {
  575.   G_Assert(this, !this.isInstrumented_(browser),
  576.            "Browser already instrumented!");
  577.  
  578.   // The browserwatcher will hook itself into the browser and its parent (us)
  579.   new G_BrowserWatcher(this, browser);
  580.   browser[this.mark_] = true;
  581. }
  582.  
  583. /**
  584.  * Register to receive events of a particular type
  585.  *
  586.  * @param eventType String indicating the event (see
  587.  *                  G_TabbedBrowserWatcher.events)
  588.  * @param listener Function to invoke when the event occurs. See top-
  589.  *                 level comments for parameters.
  590.  */
  591. G_TabbedBrowserWatcher.prototype.registerListener = function(eventType,
  592.                                                              listener) {
  593.   this.registrar_.registerListener(eventType, listener);
  594. }
  595.  
  596. /**
  597.  * Unregister a listener.
  598.  *
  599.  * @param eventType String one of G_TabbedBrowserWatcher.events' members
  600.  * @param listener Function to remove as listener
  601.  */
  602. G_TabbedBrowserWatcher.prototype.removeListener = function(eventType,
  603.                                                            listener) {
  604.   this.registrar_.removeListener(eventType, listener);
  605. }
  606.  
  607. /**
  608.  * Send an event to all listeners for that type.
  609.  *
  610.  * @param eventType String indicating the event to trigger
  611.  * @param e Object to pass to each listener (NOT copied -- be careful)
  612.  */
  613. G_TabbedBrowserWatcher.prototype.fire = function(eventType, e) {
  614.   this.registrar_.fire(eventType, e);
  615. }
  616.  
  617. /**
  618.  * Convenience function to send a document-related event. We use this
  619.  * convenience function because the event constructing logic and
  620.  * parameters are the same for all these events. (Document-related
  621.  * events are load, unload, pagehide, pageshow, and domcontentloaded).
  622.  *
  623.  * @param eventType String indicating the type of event to fire (one of
  624.  *                  the document-related events)
  625.  *
  626.  * @param doc Reference to the HTMLDocument the event is occuring to
  627.  *
  628.  * @param browser Reference to the browser in which the document is contained
  629.  */
  630. G_TabbedBrowserWatcher.prototype.fireDocEvent_ = function(eventType,
  631.                                                           doc,
  632.                                                           browser) {
  633.   // If we've already shutdown, don't bother firing any events.
  634.   if (!this.tabBrowser_) {
  635.     G_Debug(this, "Firing event after shutdown: " + eventType);
  636.     return;
  637.   }
  638.  
  639.   try {
  640.     // Could be that the browser's contentDocument has already been torn
  641.     // down. If so, this throws, and we can't tell without keeping more
  642.     // state whether doc was the top frame.
  643.     var isTop = (doc == browser.contentDocument);
  644.   } catch(e) {
  645.     var isTop = undefined;
  646.   }
  647.  
  648.   var inSelected = (browser == this.getCurrentBrowser());
  649.  
  650.   var location = doc ? doc.location.href : undefined;
  651.  
  652.   // Only send notifications for about:config's if we're supposed to
  653.   if (!this.filterAboutBlank_ || location != "about:blank") {
  654.  
  655.     G_Debug(this, "firing " + eventType + " for " + location +
  656.             (isTop ? " (isTop)" : "") + (inSelected ? " (inSelected)" : ""));
  657.     this.fire(eventType, { "doc": doc,
  658.                            "isTop": isTop,
  659.                            "inSelected": inSelected,
  660.                            "browser": browser});
  661.   }
  662. }
  663.  
  664. /**
  665.  * Invoked when the user might have switched tabs
  666.  *
  667.  * @param e Event object
  668.  */
  669. G_TabbedBrowserWatcher.prototype.onTabSwitch = function(e) {
  670.   // Filter spurious events
  671.   // The event target is usually tabs but can be tabpanels when tabs were opened
  672.   // programatically via tabbrowser.addTab().
  673.   if (e.target == null || 
  674.       (e.target.localName != "tabs" && e.target.localName != "tabpanels"))
  675.     return;
  676.  
  677.   var fromBrowser = this.lastTab_;
  678.   var toBrowser = this.getCurrentBrowser();
  679.  
  680.   if (fromBrowser != toBrowser) {
  681.     this.lastTab_ = toBrowser;
  682.     G_Debug(this, "firing tabswitch");
  683.     this.fire(this.events.TABSWITCH, { "fromBrowser": fromBrowser,
  684.                                        "toBrowser": toBrowser });
  685.   }
  686. }
  687.  
  688. // Utility functions
  689.  
  690. /**
  691.  * Returns a reference to the tabbed browser this G_TabbedBrowserWatcher
  692.  * was initialized with.
  693.  */
  694. G_TabbedBrowserWatcher.prototype.getTabBrowser = function() {
  695.   return this.tabBrowser_;
  696. }
  697.  
  698. /**
  699.  * Returns a reference to the currently selected tab.
  700.  */
  701. G_TabbedBrowserWatcher.prototype.getCurrentBrowser = function() {
  702.   return this.getTabBrowser().selectedBrowser;
  703. }
  704.  
  705. /**
  706.  * Returns a reference to the top window in the currently selected tab.
  707.  */
  708. G_TabbedBrowserWatcher.prototype.getCurrentWindow = function() {
  709.   return this.getCurrentBrowser().contentWindow;
  710. }
  711.  
  712. /**
  713.  * Find the browser corresponding to a Document
  714.  *
  715.  * @param doc Document we want the browser for
  716.  * @returns Reference to the browser in which the given document is found
  717.  *          or null if not found
  718.  */
  719. G_TabbedBrowserWatcher.prototype.getBrowserFromDocument = function(doc) {
  720.   // Could instead get the top window of the browser in which the doc
  721.   // is found via doc.defaultView.top, but sometimes the document
  722.   // isn't in a browser at all (it's being unloaded, for example), so
  723.   // defaultView won't be valid.
  724.  
  725.   // Helper: return true if doc is a sub-document of win
  726.   function docInWindow(doc, win) {
  727.     if (win.document == doc)
  728.       return true;
  729.  
  730.     if (win.frames)
  731.       for (var i = 0; i < win.frames.length; i++)
  732.         if (docInWindow(doc, win.frames[i]))
  733.           return true;
  734.  
  735.     return false;
  736.   }
  737.  
  738.   var browsers = this.getTabBrowser().browsers;
  739.   for (var i = 0; i < browsers.length; i++)
  740.     if (docInWindow(doc, browsers[i].contentWindow))
  741.       return browsers[i];
  742.  
  743.   return null;
  744. }
  745.  
  746. /**
  747.  * Find the Document that has the given URL loaded. Returns on the
  748.  * _first_ such document found, so be careful.
  749.  *
  750.  * TODO make doc/window searches more elegant, and don't use inner functions
  751.  *
  752.  * @param url String indicating the URL we're searching for
  753.  * @param opt_browser Optional reference to a browser. If given, the
  754.  *                    search will be confined to only this browser.
  755.  * @returns Reference to the Document with that URL or null if not found
  756.  */
  757. G_TabbedBrowserWatcher.prototype.getDocumentFromURL = function(url,
  758.                                                                opt_browser) {
  759.  
  760.   // Helper function: return the Document in win that has location of url
  761.   function docWithURL(win, url) {
  762.     if (win.document.location.href == url)
  763.       return win.document;
  764.  
  765.     if (win.frames)
  766.       for (var i = 0; i < win.frames.length; i++) {
  767.         var rv = docWithURL(win.frames[i], url);
  768.       if (rv)
  769.           return rv;
  770.       }
  771.  
  772.     return null;
  773.   }
  774.  
  775.   if (opt_browser)
  776.     return docWithURL(opt_browser.contentWindow, url);
  777.  
  778.   var browsers = this.getTabBrowser().browsers;
  779.   for (var i=0; i < browsers.length; i++) {
  780.     var rv = docWithURL(browsers[i].contentWindow, url);
  781.     if (rv)
  782.       return rv;
  783.   }
  784.  
  785.   return null;
  786. }
  787.  
  788. /**
  789.  * Find the all Documents that have the given URL loaded.
  790.  *
  791.  * TODO make doc/window searches more elegant, and don't use inner functions
  792.  *
  793.  * @param url String indicating the URL we're searching for
  794.  *
  795.  * @param opt_browser Optional reference to a browser. If given, the
  796.  *                    search will be confined to only this browser.
  797.  *
  798.  * @returns Array of Documents with the given URL (zero length if none found)
  799.  */
  800. G_TabbedBrowserWatcher.prototype.getDocumentsFromURL = function(url,
  801.                                                                 opt_browser) {
  802.  
  803.   var docs = [];
  804.  
  805.   // Helper function: add Docs in win with the location of url
  806.   function getDocsWithURL(win, url) {
  807.     if (win.document.location.href == url)
  808.       docs.push(win.document);
  809.  
  810.     if (win.frames)
  811.       for (var i = 0; i < win.frames.length; i++)
  812.         getDocsWithURL(win.frames[i], url);
  813.   }
  814.  
  815.   if (opt_browser)
  816.     return getDocsWithURL(opt_browser.contentWindow, url);
  817.  
  818.   var browsers = this.getTabBrowser().browsers;
  819.   for (var i=0; i < browsers.length; i++)
  820.     getDocsWithURL(browsers[i].contentWindow, url);
  821.  
  822.   return docs;
  823. }
  824.  
  825.  
  826. /**
  827.  * Finds the browser in which a Window resides.
  828.  *
  829.  * @param sub Window to find
  830.  * @returns Reference to the browser in which sub resides, else null
  831.  *          if not found
  832.  */
  833. G_TabbedBrowserWatcher.prototype.getBrowserFromWindow = function(sub) {
  834.  
  835.   // Helpfer function: return true if sub is a sub-window of win
  836.   function containsSubWindow(sub, win) {
  837.     if (win == sub)
  838.       return true;
  839.  
  840.     if (win.frames)
  841.       for (var i=0; i < win.frames.length; i++)
  842.         if (containsSubWindow(sub, win.frames[i]))
  843.           return true;
  844.  
  845.     return false;
  846.   }
  847.  
  848.   var browsers = this.getTabBrowser().browsers;
  849.   for (var i=0; i < browsers.length; i++)
  850.     if (containsSubWindow(sub, browsers[i].contentWindow))
  851.       return browsers[i];
  852.  
  853.   return null;
  854. }
  855.  
  856. /**
  857.  * Finds the XUL <tab> tag corresponding to a given browser.
  858.  *
  859.  * @param tabBrowser Reference to the tabbed browser in which browser lives
  860.  * @param browser Reference to the browser we wish to find the tab of
  861.  * @returns Reference to the browser's tab element, or null
  862.  * @static
  863.  */
  864. G_TabbedBrowserWatcher.getTabElementFromBrowser = function(tabBrowser,
  865.                                                            browser) {
  866.  
  867.   for (var i=0; i < tabBrowser.browsers.length; i++)
  868.     if (tabBrowser.browsers[i] == browser)
  869.       return tabBrowser.mTabContainer.childNodes[i];
  870.  
  871.   return null;
  872. }
  873. //@line 16 "/build/buildd/firefox-1.99+2.0b1+dfsg/browser/components/safebrowsing/src/nsSafebrowsingApplication.js"
  874.  
  875. /* ***** BEGIN LICENSE BLOCK *****
  876.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  877.  *
  878.  * The contents of this file are subject to the Mozilla Public License Version
  879.  * 1.1 (the "License"); you may not use this file except in compliance with
  880.  * the License. You may obtain a copy of the License at
  881.  * http://www.mozilla.org/MPL/
  882.  *
  883.  * Software distributed under the License is distributed on an "AS IS" basis,
  884.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  885.  * for the specific language governing rights and limitations under the
  886.  * License.
  887.  *
  888.  * The Original Code is Google Safe Browsing.
  889.  *
  890.  * The Initial Developer of the Original Code is Google Inc.
  891.  * Portions created by the Initial Developer are Copyright (C) 2006
  892.  * the Initial Developer. All Rights Reserved.
  893.  *
  894.  * Contributor(s):
  895.  *   Fritz Schneider <fritz@google.com> (original author)
  896.  *
  897.  * Alternatively, the contents of this file may be used under the terms of
  898.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  899.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  900.  * in which case the provisions of the GPL or the LGPL are applicable instead
  901.  * of those above. If you wish to allow use of your version of this file only
  902.  * under the terms of either the GPL or the LGPL, and not to allow others to
  903.  * use your version of this file under the terms of the MPL, indicate your
  904.  * decision by deleting the provisions above and replace them with the notice
  905.  * and other provisions required by the GPL or the LGPL. If you do not delete
  906.  * the provisions above, a recipient may use your version of this file under
  907.  * the terms of any one of the MPL, the GPL or the LGPL.
  908.  *
  909.  * ***** END LICENSE BLOCK ***** */
  910.  
  911. // We instantiate this variable when we create the application.
  912. var gDataProvider = null;
  913.  
  914. // An instance of our application is a PROT_Application object. It
  915. // basically just populates a few globals and instantiates wardens and
  916. // the listmanager.
  917.  
  918. /**
  919.  * An instance of our application. There should be exactly one of these.
  920.  * 
  921.  * Note: This object should instantiated only at profile-after-change
  922.  * or later because the listmanager and the cryptokeymanager need to
  923.  * read and write data files. Additionally, NSS isn't loaded until
  924.  * some time around then (Moz bug #321024).
  925.  *
  926.  * @constructor
  927.  */
  928. function PROT_Application() {
  929.   this.debugZone= "application";
  930.  
  931. //@line 88 "/build/buildd/firefox-1.99+2.0b1+dfsg/browser/components/safebrowsing/src/../content/application.js"
  932.   
  933.   // expose some classes
  934.   this.G_TabbedBrowserWatcher = G_TabbedBrowserWatcher;
  935.   this.PROT_Controller = PROT_Controller;
  936.   this.PROT_PhishingWarden = PROT_PhishingWarden;
  937.  
  938.   // Load data provider pref values
  939.   gDataProvider = new PROT_DataProvider();
  940.  
  941.   // expose the object
  942.   this.wrappedJSObject = this;
  943. }
  944.  
  945. /**
  946.  * @return String the report phishing URL (localized).
  947.  */
  948. PROT_Application.prototype.getReportPhishingURL = function() {
  949.   var prefs = new G_Preferences();
  950.   var reportUrl = gDataProvider.getReportPhishURL();
  951.  
  952.   // Append locale data.
  953.   reportUrl += "&hl=" + prefs.getPref("general.useragent.locale");
  954.  
  955.   return reportUrl;
  956. }
  957. /* ***** BEGIN LICENSE BLOCK *****
  958.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  959.  *
  960.  * The contents of this file are subject to the Mozilla Public License Version
  961.  * 1.1 (the "License"); you may not use this file except in compliance with
  962.  * the License. You may obtain a copy of the License at
  963.  * http://www.mozilla.org/MPL/
  964.  *
  965.  * Software distributed under the License is distributed on an "AS IS" basis,
  966.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  967.  * for the specific language governing rights and limitations under the
  968.  * License.
  969.  *
  970.  * The Original Code is Google Safe Browsing.
  971.  *
  972.  * The Initial Developer of the Original Code is Google Inc.
  973.  * Portions created by the Initial Developer are Copyright (C) 2006
  974.  * the Initial Developer. All Rights Reserved.
  975.  *
  976.  * Contributor(s):
  977.  *   Fritz Schneider <fritz@google.com> (original author)
  978.  *
  979.  * Alternatively, the contents of this file may be used under the terms of
  980.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  981.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  982.  * in which case the provisions of the GPL or the LGPL are applicable instead
  983.  * of those above. If you wish to allow use of your version of this file only
  984.  * under the terms of either the GPL or the LGPL, and not to allow others to
  985.  * use your version of this file under the terms of the MPL, indicate your
  986.  * decision by deleting the provisions above and replace them with the notice
  987.  * and other provisions required by the GPL or the LGPL. If you do not delete
  988.  * the provisions above, a recipient may use your version of this file under
  989.  * the terms of any one of the MPL, the GPL or the LGPL.
  990.  *
  991.  * ***** END LICENSE BLOCK ***** */
  992.  
  993. // There is one BrowserView per browser window, and each BrowserView
  994. // is responsible for keeping track of problems (phishy documents)
  995. // within that window. The BrowserView is also responsible for
  996. // figuring out what to do about such problems, for example, whether
  997. // the tab with a phishy page is currently showing and therefore if we
  998. // should be showing a warning.
  999. // 
  1000. // The BrowserView receives information from three places:
  1001. //
  1002. // - from the phishing warden. When the phishing warden notices a
  1003. //   problem, it queries all browser views to see which one (if any)
  1004. //   has the Document that is problematic. It then hands the problem
  1005. //   off to the appropriate BrowserView.
  1006. // 
  1007. // - from the controller. The controller responds to explicit user 
  1008. //   actions (tab switches, requests to hide the warning message, 
  1009. //   etc.) and let's the BrowserView know about any user action 
  1010. //   having to do with the problems it is tracking.
  1011. //
  1012. // - from the TabbedBrowserWatcher. When the BrowserView is keeping
  1013. //   track of a problematic document it listens for interesting
  1014. //   events affecting it, for example pagehide (at which point
  1015. //   we presumably hide the warning if we're showing it).
  1016. //
  1017. // The BrowserView associates at most one "problem" with each Document
  1018. // in the browser window. It keeps state about which Documents are 
  1019. // problematic by storing a "problem queue" on each browser (tab).
  1020. // At most one problematic document per browser (tab) is active
  1021. // at any time. That is, we show the warning for at most one phishy
  1022. // document at any one time. If another phishy doc loads in that tab,
  1023. // it goes onto the end of the queue to be activated only when the
  1024. // currently active document goes away.
  1025. //
  1026. // If we had multiple types of warnings (one for after the page had
  1027. // loaded, one for when the user clicked a link, etc) here's where
  1028. // we'd select the appropate one to use. As it stands, we only have
  1029. // one displayer (an "afterload" displayer). A displayer knows _how_
  1030. // to display a warning, whereas as the BrowserView knows _what_ and
  1031. // _when_.
  1032. //
  1033. // To keep things (relatively) easy to reason about and efficient (the
  1034. // phishwarden could be querying us inside a progresslistener
  1035. // notification, or the controller inside an event handler), we have
  1036. // the following rules:
  1037. //
  1038. // - at most one of a displayer's start() or stop() methods is called
  1039. //   in any iteration (if calling two is required, the second is run in 
  1040. //   the next event loop)
  1041. // - displayers should run their operations synchronously so we don't have
  1042. //   to look two places (here and in the displayer) to see what is happening 
  1043. //   when
  1044. // - displayer actions are run after cleaning up the browser view state
  1045. //   in case they have consequences
  1046. //
  1047. // TODO: this could use some redesign, but I don't have time.
  1048. // TODO: the queue needs to be abstracted, but we want another release fast,
  1049. //       so I'm not going to touch it for the time being
  1050. // TODO: IDN issues and canonical URLs?
  1051. // TODO: Perhaps we should blur the page before showing a warning in order
  1052. //       to prevent stray keystrokes?
  1053.  
  1054. /**
  1055.  * The BrowerView is responsible for keeping track of and figuring out
  1056.  * what to do with problems within a single browser window.
  1057.  * 
  1058.  * TODO 
  1059.  * Unify all browser-related state here. Currently it's split
  1060.  * between two objects, this object and the controller. We could have
  1061.  * this object be solely responsible for UI hide/show decisions, which
  1062.  * would probably make it easier to reason about what's going on.
  1063.  * 
  1064.  * TODO 
  1065.  * Investigate an alternative model. For example, we could factor out
  1066.  * the problem signaling stuff from the tab/UI logic into a
  1067.  * ProblemRegistry. Attach listeners to new docs/requests as they go
  1068.  * by and have these listeners periodically check in with a
  1069.  * ProblemRegistry to see if they're watching a problematic
  1070.  * doc/request. If so, then have them flag the browser view to be
  1071.  * aware of the problem.
  1072.  *
  1073.  * @constructor
  1074.  * @param tabWatcher Reference to the TabbedBrowserWatcher we'll use to query 
  1075.  *                   for information about active tabs/browsers.
  1076.  * @param doc Reference to the XUL Document (browser window) in which the 
  1077.  *            tabwatcher is watching
  1078.  */ 
  1079. function PROT_BrowserView(tabWatcher, doc) {
  1080.   this.debugZone = "browserview";
  1081.   this.tabWatcher_ = tabWatcher;
  1082.   this.doc_ = doc;
  1083. }
  1084.  
  1085. /**
  1086.  * See if we have any Documents with a given (problematic) URL that
  1087.  * haven't yet been marked as problems. Called as a subroutine by
  1088.  * tryToHandleProblemRequest().
  1089.  *
  1090.  * @param url String containing the URL to look for
  1091.  *
  1092.  * @returns Reference to an unhandled Document with the problem URL or null
  1093.  */
  1094. PROT_BrowserView.prototype.getFirstUnhandledDocWithURL_ = function(url) {
  1095.   var docs = this.tabWatcher_.getDocumentsFromURL(url);
  1096.   if (!docs.length)
  1097.     return null;
  1098.  
  1099.   for (var i = 0; i < docs.length; i++) {
  1100.     var browser = this.tabWatcher_.getBrowserFromDocument(docs[i]);
  1101.     G_Assert(this, !!browser, "Found doc but can't find browser???");
  1102.     var alreadyHandled = this.getProblem_(docs[i], browser);
  1103.  
  1104.     if (!alreadyHandled)
  1105.       return docs[i];
  1106.   }
  1107.   return null;
  1108. }
  1109.  
  1110. /**
  1111.  * Invoked by the warden to give us the opportunity to handle a
  1112.  * problem.  A problem is signaled once per request for a problem
  1113.  * Document and is handled at most once, so there's no issue with us
  1114.  * "losing" a problem due to multiple concurrently loading Documents
  1115.  * with the same URL.
  1116.  *
  1117.  * @param warden Reference to the warden signalling the problem. We'll
  1118.  *               need him to instantiate one of his warning displayers
  1119.  * 
  1120.  * @param request The nsIRequest that is problematic
  1121.  *
  1122.  * @returns Boolean indicating whether we handled problem
  1123.  */
  1124. PROT_BrowserView.prototype.tryToHandleProblemRequest = function(warden,
  1125.                                                                 request) {
  1126.  
  1127.   var doc = this.getFirstUnhandledDocWithURL_(request.name);
  1128.   if (doc) {
  1129.     var browser = this.tabWatcher_.getBrowserFromDocument(doc);
  1130.     G_Assert(this, !!browser, "Couldn't get browser from problem doc???");
  1131.     G_Assert(this, !this.getProblem_(doc, browser),
  1132.              "Doc is supposedly unhandled, but has state?");
  1133.     
  1134.     this.isProblemDocument_(browser, doc, warden);
  1135.     return true;
  1136.   }
  1137.   return false;
  1138. }
  1139.  
  1140. /**
  1141.  * We're sure a particular Document is problematic, so let's instantiate
  1142.  * a dispalyer for it and add it to the problem queue for the browser.
  1143.  *
  1144.  * @param browser Reference to the browser in which the problem doc resides
  1145.  *
  1146.  * @param doc Reference to the problematic document
  1147.  * 
  1148.  * @param warden Reference to the warden signalling the problem.
  1149.  */
  1150. PROT_BrowserView.prototype.isProblemDocument_ = function(browser, 
  1151.                                                          doc, 
  1152.                                                          warden) {
  1153.  
  1154.   G_Debug(this, "Document is problem: " + doc.location.href);
  1155.  
  1156.   var url = doc.location.href;
  1157.  
  1158.   // We only have one type of displayer right now
  1159.   var displayer = new warden.displayers_["afterload"]("Phishing afterload",
  1160.                                                       browser,
  1161.                                                       this.doc_,
  1162.                                                       url);
  1163.  
  1164.   // We listen for the problematic document being navigated away from
  1165.   // so we can remove it from the problem queue
  1166.  
  1167.   var hideHandler = BindToObject(this.onNavAwayFromProblem_, 
  1168.                                  this, 
  1169.                                  doc, 
  1170.                                  browser);
  1171.   doc.defaultView.addEventListener("pagehide", hideHandler, true);
  1172.  
  1173.   // More info than we technically need, but it comes in handy for debugging
  1174.   var problem = {
  1175.     "browser_": browser,
  1176.     "doc_": doc,
  1177.     "displayer_": displayer,
  1178.     "url_": url,
  1179.     "hideHandler_": hideHandler,
  1180.   };
  1181.   var numInQueue = this.queueProblem_(browser, problem);
  1182.  
  1183.   // If the queue was empty, schedule us to take something out
  1184.   if (numInQueue == 1)
  1185.     new G_Alarm(BindToObject(this.unqueueNextProblem_, this, browser), 0);
  1186. }
  1187.  
  1188. /**
  1189.  * Invoked when a problematic document is navigated away from. 
  1190.  *
  1191.  * @param doc Reference to the problematic Document navigated away from
  1192.  
  1193.  * @param browser Reference to the browser in which the problem document
  1194.  *                unloaded
  1195.  */
  1196. PROT_BrowserView.prototype.onNavAwayFromProblem_ = function(doc, browser) {
  1197.  
  1198.   G_Debug(this, "User nav'd away from problem.");
  1199.   var problem = this.getProblem_(doc, browser);
  1200.   (new PROT_Reporter).report("phishnavaway", problem.url_);
  1201.  
  1202.   G_Assert(this, doc === problem.doc_, "State doc not equal to nav away doc?");
  1203.   G_Assert(this, browser === problem.browser_, 
  1204.            "State browser not equal to nav away browser?");
  1205.   
  1206.   this.problemResolved(browser, doc);
  1207. }
  1208.  
  1209. /**
  1210.  * @param browser Reference to a browser we'd like to know about
  1211.  * 
  1212.  * @returns Boolean indicating if the browser in question has 
  1213.  *          problematic content
  1214.  */
  1215. PROT_BrowserView.prototype.hasProblem = function(browser) {
  1216.   return this.hasNonemptyProblemQueue_(browser);
  1217. }
  1218.  
  1219. /**
  1220.  * @param browser Reference to a browser we'd like to know about
  1221.  *
  1222.  * @returns Boolean indicating if the browser in question has a
  1223.  *          problem (i.e., it has a non-empty problem queue)
  1224.  */
  1225. PROT_BrowserView.prototype.hasNonemptyProblemQueue_ = function(browser) {
  1226.   try {
  1227.     return !!browser.PROT_problemState__ && 
  1228.       !!browser.PROT_problemState__.length;
  1229.   } catch(e) {
  1230.     // We could be checking a browser that has just been closed, in
  1231.     // which case its properties will not be valid, causing the above
  1232.     // statement to throw an error. Since this case handled elsewhere,
  1233.     // just return false.
  1234.     return false;
  1235.   }
  1236. }
  1237.  
  1238. /**
  1239.  * Invoked to indicate that the problem for a particular problematic
  1240.  * document in a browser has been resolved (e.g., by being navigated
  1241.  * away from).
  1242.  *
  1243.  * @param browser Reference to the browser in which resolution is happening
  1244.  *
  1245.  * @param opt_doc Reference to the problematic doc whose problem was resolved
  1246.  *                (if absent, assumes the doc assocaited with the currently
  1247.  *                active displayer)
  1248.  */
  1249. PROT_BrowserView.prototype.problemResolved = function(browser, opt_doc) {
  1250.   var problem;
  1251.   var doc;
  1252.   if (!!opt_doc) {
  1253.     doc = opt_doc;
  1254.     problem = this.getProblem_(doc, browser);
  1255.   } else {
  1256.     problem = this.getCurrentProblem_(browser);
  1257.     doc = problem.doc_;
  1258.   }
  1259.  
  1260.   problem.displayer_.done();
  1261.   var wasHead = this.deleteProblemFromQueue_(doc, browser);
  1262.  
  1263.   // Peek at the next problem (if any) in the queue for this browser
  1264.   var queueNotEmpty = this.getCurrentProblem_(browser);
  1265.  
  1266.   if (wasHead && queueNotEmpty) {
  1267.     G_Debug(this, "More problems pending. Scheduling unqueue.");
  1268.     new G_Alarm(BindToObject(this.unqueueNextProblem_, this, browser), 0);
  1269.   }
  1270. }
  1271.  
  1272. /**
  1273.  * Peek at the top of the problem queue and if there's something there,
  1274.  * make it active. 
  1275.  *
  1276.  * @param browser Reference to the browser we should activate a problem
  1277.  *                displayer in if one is available
  1278.  */
  1279. PROT_BrowserView.prototype.unqueueNextProblem_ = function(browser) {
  1280.   var problem = this.getCurrentProblem_(browser);
  1281.   if (!problem) {
  1282.     G_Debug(this, "No problem in queue; doc nav'd away from? (shrug)");
  1283.     return;
  1284.   }
  1285.  
  1286.   // Two problem docs that load in rapid succession could both schedule 
  1287.   // themselves to be unqueued before this method is called. So ensure 
  1288.   // that the problem at the head of the queue is not, in fact, active.
  1289.   if (!problem.displayer_.isActive()) {
  1290.  
  1291.     // It could be the case that the server is really slow to respond,
  1292.     // so there might not yet be anything in the problem Document. If
  1293.     // we show the warning when that's the case, the user will see a
  1294.     // blank document greyed out, and if they cancel the dialog
  1295.     // they'll see the page they're navigating away from because it
  1296.     // hasn't been painted over yet (b/c there's no content for the
  1297.     // problem page). So here we ensure that we have content for the
  1298.     // problem page before showing the dialog.
  1299.     var haveContent = false;
  1300.     try {
  1301.       // This will throw if there's no content yet
  1302.       var h = problem.doc_.defaultView.getComputedStyle(problem.doc_.body, "")
  1303.               .getPropertyValue("height");
  1304.       G_Debug(this, "body height: " + h);
  1305.  
  1306.       if (Number(h.substring(0, h.length - 2)))
  1307.         haveContent = true;
  1308.  
  1309.     } catch (e) {
  1310.       G_Debug(this, "Masked in unqueuenextproblem: " + e);
  1311.     }
  1312.     
  1313.     if (!haveContent) {
  1314.  
  1315.       G_Debug(this, "Didn't get computed style. Re-queueing.");
  1316.  
  1317.       // One stuck problem document in a page shouldn't prevent us
  1318.       // warning on other problem frames that might be loading or
  1319.       // loaded. So stick the Document that doesn't have content
  1320.       // back at the end of the queue.
  1321.       var p = this.removeProblemFromQueue_(problem.doc_, browser);
  1322.       G_Assert(this, p === problem, "Unqueued wrong problem?");
  1323.       this.queueProblem_(browser, problem);
  1324.  
  1325.       // Try again in a bit. This opens us up to a potential
  1326.       // vulnerability (put tons of hanging frames in a page
  1327.       // ahead of your real phishy frame), but the risk at the
  1328.       // moment is really low (plus it is outside our threat
  1329.       // model).
  1330.       new G_Alarm(BindToObject(this.unqueueNextProblem_, 
  1331.                                this, 
  1332.                                browser),
  1333.                   200 /*ms*/);
  1334.       return;
  1335.     }
  1336.  
  1337.     problem.displayer_.start();
  1338.  
  1339.     // OK, we have content, but there there is an additional
  1340.     // issue. Due to a bfcache bug, if we show the warning during
  1341.     // paint suppression, the collapsing of the content pane affects
  1342.     // the doc we're naving from :( The symptom is a page with grey
  1343.     // screen on navigation to or from a phishing page (the
  1344.     // contentDocument will have width zero).
  1345.     //
  1346.     // Paint supression lasts at most 250ms from when the parser sees
  1347.     // the body, and the parser sees the body well before it has a
  1348.     // height. We err on the side of caution.
  1349.     //
  1350.     // Thanks to bryner for helping to track the bfcache bug down.
  1351.     // https://bugzilla.mozilla.org/show_bug.cgi?id=319646
  1352.     
  1353.     if (this.tabWatcher_.getCurrentBrowser() === browser)
  1354.       new G_Alarm(BindToObject(this.problemBrowserMaybeSelected, 
  1355.                                this, 
  1356.                                browser),
  1357.                   350 /*ms*/);
  1358.   }
  1359. }
  1360.  
  1361. /**
  1362.  * Helper function that adds a new problem to the queue of problems pending
  1363.  * on this browser.
  1364.  *
  1365.  * @param browser Browser to which we should add state
  1366.  *
  1367.  * @param problem Object (structure, really) encapsulating the problem
  1368.  *
  1369.  * @returns Number indicating the number of items in the queue (and from
  1370.  *          which you can infer whether the recently added item was
  1371.  *          placed at the head, and hence should be active.
  1372.  */
  1373. PROT_BrowserView.prototype.queueProblem_ = function(browser, problem) {
  1374.   G_Debug(this, "Adding problem state for " + problem.url_);
  1375.  
  1376.   if (this.hasNonemptyProblemQueue_(browser))
  1377.     G_Debug(this, "Already has problem state. Queueing this problem...");
  1378.  
  1379.   // First problem ever signaled on this browser? Make a new queue!
  1380.   if (browser.PROT_problemState__ == undefined)
  1381.     browser.PROT_problemState__ = [];
  1382.  
  1383.   browser.PROT_problemState__.push(problem);
  1384.   return browser.PROT_problemState__.length;
  1385. }
  1386.  
  1387. /**
  1388.  * Helper function that removes a problem from the queue and deactivates
  1389.  * it.
  1390.  *
  1391.  * @param doc Reference to the doc for which we should remove state
  1392.  *
  1393.  * @param browser Reference to the browser from which we should remove
  1394.  *                state
  1395.  *
  1396.  * @returns Boolean indicating if the remove problem was currently active
  1397.  *          (that is, if it was at the head of the queue)
  1398.  */
  1399. PROT_BrowserView.prototype.deleteProblemFromQueue_ = function(doc, browser) {
  1400.   G_Debug(this, "Deleting problem state for " + browser);
  1401.   G_Assert(this, !!this.hasNonemptyProblemQueue_(browser),
  1402.            "Browser has no problem state");
  1403.  
  1404.   var problem = this.getProblem_(doc, browser);
  1405.   G_Assert(this, !!problem, "Couldnt find state in removeproblemstate???");
  1406.  
  1407.   var wasHead = browser.PROT_problemState__[0] === problem;
  1408.   this.removeProblemFromQueue_(doc, browser);
  1409.  
  1410.   var hideHandler = problem.hideHandler_;
  1411.   G_Assert(this, !!hideHandler, "No hidehandler in state?");
  1412.   problem.doc_.defaultView.removeEventListener("pagehide",
  1413.                                                hideHandler,
  1414.                                                true);
  1415.   return wasHead;
  1416. }
  1417.  
  1418. /**
  1419.  * Helper function that removes a problem from the queue but does 
  1420.  * NOT deactivate it.
  1421.  *
  1422.  * @param doc Reference to the doc for which we should remove state
  1423.  *
  1424.  * @param browser Reference to the browser from which we should remove
  1425.  *                state
  1426.  *
  1427.  * @returns Boolean indicating if the remove problem was currently active
  1428.  *          (that is, if it was at the head of the queue)
  1429.  */
  1430. PROT_BrowserView.prototype.removeProblemFromQueue_ = function(doc, browser) {
  1431.   G_Debug(this, "Removing problem state for " + browser);
  1432.   G_Assert(this, !!this.hasNonemptyProblemQueue_(browser),
  1433.            "Browser has no problem state");
  1434.  
  1435.   var problem = null;
  1436.   // TODO Blech. Let's please have an abstraction here instead.
  1437.   for (var i = 0; i < browser.PROT_problemState__.length; i++)
  1438.     if (browser.PROT_problemState__[i].doc_ === doc) {
  1439.       problem = browser.PROT_problemState__.splice(i, 1)[0];
  1440.       break;
  1441.     }
  1442.   return problem;
  1443. }
  1444.  
  1445. /**
  1446.  * Retrieve (but do not remove) the problem state for a particular
  1447.  * problematic Document in this browser
  1448.  *
  1449.  * @param doc Reference to the problematic doc to get state for
  1450.  *
  1451.  * @param browser Reference to the browser from which to get state
  1452.  *
  1453.  * @returns Object encapsulating the state we stored, or null if none
  1454.  */
  1455. PROT_BrowserView.prototype.getProblem_ = function(doc, browser) {
  1456.   if (!this.hasNonemptyProblemQueue_(browser))
  1457.     return null;
  1458.  
  1459.   // TODO Blech. Let's please have an abstraction here instead.
  1460.   for (var i = 0; i < browser.PROT_problemState__.length; i++)
  1461.     if (browser.PROT_problemState__[i].doc_ === doc)
  1462.       return browser.PROT_problemState__[i];
  1463.   return null;
  1464. }
  1465.  
  1466. /**
  1467.  * Retrieve the problem state for the currently active problem Document 
  1468.  * in this browser
  1469.  *
  1470.  * @param browser Reference to the browser from which to get state
  1471.  *
  1472.  * @returns Object encapsulating the state we stored, or null if none
  1473.  */
  1474. PROT_BrowserView.prototype.getCurrentProblem_ = function(browser) {
  1475.   return browser.PROT_problemState__[0];
  1476. }
  1477.  
  1478. /**
  1479.  * Invoked by the controller when the user switches tabs away from a problem 
  1480.  * tab. 
  1481.  *
  1482.  * @param browser Reference to the tab that was switched from
  1483.  */
  1484. PROT_BrowserView.prototype.problemBrowserUnselected = function(browser) {
  1485.   var problem = this.getCurrentProblem_(browser);
  1486.   G_Assert(this, !!problem, "Couldn't get state from browser");
  1487.   problem.displayer_.browserUnselected();
  1488. }
  1489.  
  1490. /**
  1491.  * Checks to see if the problem browser is selected, and if so, 
  1492.  * tell it it to show its warning.
  1493.  *
  1494.  * @param browser Reference to the browser we wish to check
  1495.  */
  1496. PROT_BrowserView.prototype.problemBrowserMaybeSelected = function(browser) {
  1497.   var problem = this.getCurrentProblem_(browser);
  1498.  
  1499.   if (this.tabWatcher_.getCurrentBrowser() === browser &&
  1500.       problem &&
  1501.       problem.displayer_.isActive()) 
  1502.     this.problemBrowserSelected(browser);
  1503. }
  1504.  
  1505. /**
  1506.  * Invoked by the controller when the user switches tabs to a problem tab
  1507.  *
  1508.  * @param browser Reference to the tab that was switched to
  1509.  */
  1510. PROT_BrowserView.prototype.problemBrowserSelected = function(browser) {
  1511.   G_Debug(this, "Problem browser selected");
  1512.   var problem = this.getCurrentProblem_(browser);
  1513.   G_Assert(this, !!problem, "No state? But we're selected!");
  1514.   problem.displayer_.browserSelected();
  1515. }
  1516.  
  1517. /**
  1518.  * Invoked by the controller when the user accepts our warning. Passes
  1519.  * the accept through to the message displayer, which knows what to do
  1520.  * (it will be displayer-specific).
  1521.  *
  1522.  * @param browser Reference to the browser for which the user accepted
  1523.  *                our warning
  1524.  */
  1525. PROT_BrowserView.prototype.acceptAction = function(browser) {
  1526.   var problem = this.getCurrentProblem_(browser);
  1527.  
  1528.   // We run the action only after we're completely through processing
  1529.   // this event. We do this because the action could cause state to be
  1530.   // cleared (e.g., by navigating the problem document) that we need
  1531.   // to finish processing the event.
  1532.  
  1533.   new G_Alarm(BindToObject(problem.displayer_.acceptAction, 
  1534.                            problem.displayer_), 
  1535.               0);
  1536. }
  1537.  
  1538. /**
  1539.  * Invoked by the controller when the user declines our
  1540.  * warning. Passes the decline through to the message displayer, which
  1541.  * knows what to do (it will be displayer-specific).
  1542.  *
  1543.  * @param browser Reference to the browser for which the user declined
  1544.  *                our warning
  1545.  */
  1546. PROT_BrowserView.prototype.declineAction = function(browser) {
  1547.   var problem = this.getCurrentProblem_(browser);
  1548.   G_Assert(this, !!problem, "User declined but no state???");
  1549.  
  1550.   // We run the action only after we're completely through processing
  1551.   // this event. We do this because the action could cause state to be
  1552.   // cleared (e.g., by navigating the problem document) that we need
  1553.   // to finish processing the event.
  1554.  
  1555.   new G_Alarm(BindToObject(problem.displayer_.declineAction, 
  1556.                            problem.displayer_), 
  1557.               0);
  1558. }
  1559.  
  1560. /**
  1561.  * The user wants to see the warning message. So let em! At some point when
  1562.  * we have multiple types of warnings, we'll have to mediate them here.
  1563.  *
  1564.  * @param browser Reference to the browser that has the warning the user 
  1565.  *                wants to see. 
  1566.  */
  1567. PROT_BrowserView.prototype.explicitShow = function(browser) {
  1568.   var problem = this.getCurrentProblem_(browser);
  1569.   G_Assert(this, !!problem, "Explicit show on browser w/o problem state???");
  1570.   problem.displayer_.explicitShow();
  1571. }
  1572. /* ***** BEGIN LICENSE BLOCK *****
  1573.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1574.  *
  1575.  * The contents of this file are subject to the Mozilla Public License Version
  1576.  * 1.1 (the "License"); you may not use this file except in compliance with
  1577.  * the License. You may obtain a copy of the License at
  1578.  * http://www.mozilla.org/MPL/
  1579.  *
  1580.  * Software distributed under the License is distributed on an "AS IS" basis,
  1581.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1582.  * for the specific language governing rights and limitations under the
  1583.  * License.
  1584.  *
  1585.  * The Original Code is Google Safe Browsing.
  1586.  *
  1587.  * The Initial Developer of the Original Code is Google Inc.
  1588.  * Portions created by the Initial Developer are Copyright (C) 2006
  1589.  * the Initial Developer. All Rights Reserved.
  1590.  *
  1591.  * Contributor(s):
  1592.  *   Fritz Schneider <fritz@google.com> (original author)
  1593.  *
  1594.  * Alternatively, the contents of this file may be used under the terms of
  1595.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1596.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1597.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1598.  * of those above. If you wish to allow use of your version of this file only
  1599.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1600.  * use your version of this file under the terms of the MPL, indicate your
  1601.  * decision by deleting the provisions above and replace them with the notice
  1602.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1603.  * the provisions above, a recipient may use your version of this file under
  1604.  * the terms of any one of the MPL, the GPL or the LGPL.
  1605.  *
  1606.  * ***** END LICENSE BLOCK ***** */
  1607.  
  1608.  
  1609. // This is our controller -- the thingy that listens to what the user
  1610. // is doing. There is one controller per browser window, and each has
  1611. // a BrowserView that manages information about problems within the
  1612. // window. The controller figures out when the browser might want to
  1613. // know about something, but the browser view figures out what exactly
  1614. // to do (and the BrowserView's displayer figures out how to do it).
  1615. //
  1616. // For example, the controller might notice that the user has switched
  1617. // to a tab that has something problematic in it. It would tell its 
  1618. // BrowserView this, and the BrowserView would figure out whether it 
  1619. // is appropriate to show a warning (e.g., perhaps the user previously
  1620. // dismissed the warning for that problem). If so, the BrowserView tells
  1621. // the displayer to show the warning. Anyhoo...
  1622. //
  1623. // TODO Could move all browser-related hide/show logic into the browser
  1624. //      view. Need to think about this more.
  1625.  
  1626. /**
  1627.  * Handles user actions, translating them into messages to the view
  1628.  *
  1629.  * @constructor
  1630.  * @param win Reference to the Window (browser window context) we should
  1631.  *            attach to
  1632.  * @param tabWatcher  Reference to the TabbedBrowserWatcher object 
  1633.  *                    the controller should use to receive events about tabs.
  1634.  * @param phishingWarden Reference to the PhishingWarden we should register
  1635.  *                       our browserview with
  1636.  */
  1637. function PROT_Controller(win, tabWatcher, phishingWarden) {
  1638.   this.debugZone = "controller";
  1639.  
  1640.   this.win_ = win;
  1641.   this.phishingWarden_ = phishingWarden;
  1642.  
  1643.   // Use this to query preferences
  1644.   this.prefs_ = new G_Preferences();
  1645.  
  1646.   // Set us up to receive the events we want.
  1647.   this.tabWatcher_ = tabWatcher;
  1648.   this.onTabSwitchCallback_ = BindToObject(this.onTabSwitch, this);
  1649.   this.tabWatcher_.registerListener("tabswitch",
  1650.                                     this.onTabSwitchCallback_);
  1651.  
  1652.  
  1653.   // Install our command controllers. These commands are issued from
  1654.   // various places in our UI, including our preferences dialog, the
  1655.   // warning dialog, etc.
  1656.   var commandHandlers = { 
  1657.     "safebrowsing-show-warning" :
  1658.       BindToObject(this.onUserShowWarning, this),
  1659.     "safebrowsing-accept-warning" :
  1660.       BindToObject(this.onUserAcceptWarning, this),
  1661.     "safebrowsing-decline-warning" :
  1662.       BindToObject(this.onUserDeclineWarning, this),
  1663.   };
  1664.  
  1665.   this.commandController_ = new PROT_CommandController(commandHandlers);
  1666.   this.win_.controllers.appendController(this.commandController_);
  1667.  
  1668.   // This guy embodies the logic of when to display warnings
  1669.   // (displayers embody the how).
  1670.   this.browserView_ = new PROT_BrowserView(this.tabWatcher_, 
  1671.                                            this.win_.document);
  1672.  
  1673.   // We need to let the phishing warden know about this browser view so it 
  1674.   // can be given the opportunity to handle problem documents. We also need
  1675.   // to let the warden know when this window and hence this browser view
  1676.   // is going away.
  1677.   this.phishingWarden_.addBrowserView(this.browserView_);
  1678.  
  1679.   this.windowWatcher_ = 
  1680.     Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  1681.     .getService(Components.interfaces.nsIWindowWatcher);
  1682.  
  1683.   G_Debug(this, "Controller initialized.");
  1684. }
  1685.  
  1686. /**
  1687.  * Invoked when the browser window is closing. Do some cleanup.
  1688.  */
  1689. PROT_Controller.prototype.shutdown = function(e) {
  1690.   G_Debug(this, "Browser window closing. Shutting controller down.");
  1691.   if (this.browserView_) {
  1692.     this.phishingWarden_.removeBrowserView(this.browserView_);
  1693.   }
  1694.  
  1695.   if (this.commandController_) {
  1696.     this.win_.controllers.removeController(this.commandController_);
  1697.     this.commandController_ = null;
  1698.   }
  1699.  
  1700.  
  1701.   // No need to drain the browser view's problem queue explicitly; it will
  1702.   // receive pagehides for all the browsers in its queues as they're torn
  1703.   // down, and it will remove them.
  1704.   this.browserView_ = null;
  1705.  
  1706.   if (this.tabWatcher_) {
  1707.     this.tabWatcher_.removeListener("tabswitch", 
  1708.                                     this.onTabSwitchCallback_);
  1709.     this.tabWatcher_.shutdown();
  1710.   }
  1711.  
  1712.   this.win_.removeEventListener("unload", this.onShutdown_, false);
  1713.   this.prefs_ = null;
  1714.  
  1715.   this.windowWatcher_ = null;
  1716.  
  1717.   G_Debug(this, "Controller shut down.");
  1718. }
  1719.  
  1720. /**
  1721.  * The user clicked the urlbar icon; they want to see the warning message
  1722.  * again.
  1723.  */
  1724. PROT_Controller.prototype.onUserShowWarning = function() {
  1725.   var browser = this.tabWatcher_.getCurrentBrowser();
  1726.   this.browserView_.explicitShow(browser);
  1727. }
  1728.  
  1729. /**
  1730.  * Deal with a user accepting our warning. 
  1731.  *
  1732.  * TODO the warning hide/display instructions here can probably be moved
  1733.  * into the browserview in the future, given its knowledge of when the
  1734.  * problem doc hides/shows.
  1735.  */
  1736. PROT_Controller.prototype.onUserAcceptWarning = function() {
  1737.   G_Debug(this, "User accepted warning.");
  1738.   var browser = this.tabWatcher_.getCurrentBrowser();
  1739.   G_Assert(this, !!browser, "Couldn't get current browser?!?");
  1740.   G_Assert(this, this.browserView_.hasProblem(browser),
  1741.            "User accept fired, but browser doesn't have warning showing?!?");
  1742.  
  1743.   this.browserView_.acceptAction(browser);
  1744.   this.browserView_.problemResolved(browser);
  1745. }
  1746.  
  1747. /**
  1748.  * Deal with a user declining our warning. 
  1749.  *
  1750.  * TODO the warning hide/display instructions here can probably be moved
  1751.  * into the browserview in the future, given its knowledge of when the
  1752.  * problem doc hides/shows.
  1753.  */
  1754. PROT_Controller.prototype.onUserDeclineWarning = function() {
  1755.   G_Debug(this, "User declined warning.");
  1756.   var browser = this.tabWatcher_.getCurrentBrowser();
  1757.   G_Assert(this, this.browserView_.hasProblem(browser),
  1758.            "User decline fired, but browser doesn't have warning showing?!?");
  1759.   this.browserView_.declineAction(browser);
  1760.   // We don't call problemResolved() here because all declining does it
  1761.   // hide the message; we still have the urlbar icon showing, giving
  1762.   // the user the ability to bring the warning message back up if they
  1763.   // so desire.
  1764. }
  1765.  
  1766. /**
  1767.  * Notice tab switches, and display or hide warnings as appropriate.
  1768.  *
  1769.  * TODO this logic can probably move into the browser view at some
  1770.  * point. But one thing at a time.
  1771.  */
  1772. PROT_Controller.prototype.onTabSwitch = function(e) {
  1773.   if (this.browserView_.hasProblem(e.fromBrowser)) 
  1774.     this.browserView_.problemBrowserUnselected(e.fromBrowser);
  1775.  
  1776.   if (this.browserView_.hasProblem(e.toBrowser))
  1777.     this.browserView_.problemBrowserSelected(e.toBrowser);
  1778. }
  1779. /* ***** BEGIN LICENSE BLOCK *****
  1780.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1781.  *
  1782.  * The contents of this file are subject to the Mozilla Public License Version
  1783.  * 1.1 (the "License"); you may not use this file except in compliance with
  1784.  * the License. You may obtain a copy of the License at
  1785.  * http://www.mozilla.org/MPL/
  1786.  *
  1787.  * Software distributed under the License is distributed on an "AS IS" basis,
  1788.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1789.  * for the specific language governing rights and limitations under the
  1790.  * License.
  1791.  *
  1792.  * The Original Code is Google Safe Browsing.
  1793.  *
  1794.  * The Initial Developer of the Original Code is Google Inc.
  1795.  * Portions created by the Initial Developer are Copyright (C) 2006
  1796.  * the Initial Developer. All Rights Reserved.
  1797.  *
  1798.  * Contributor(s):
  1799.  *   Fritz Schneider <fritz@google.com> (original author)
  1800.  *
  1801.  * Alternatively, the contents of this file may be used under the terms of
  1802.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1803.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1804.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1805.  * of those above. If you wish to allow use of your version of this file only
  1806.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1807.  * use your version of this file under the terms of the MPL, indicate your
  1808.  * decision by deleting the provisions above and replace them with the notice
  1809.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1810.  * the provisions above, a recipient may use your version of this file under
  1811.  * the terms of any one of the MPL, the GPL or the LGPL.
  1812.  *
  1813.  * ***** END LICENSE BLOCK ***** */
  1814.  
  1815.  
  1816. // Some misc command-related plumbing used by the controller.
  1817.  
  1818.  
  1819. /**
  1820.  * A tiny wrapper class for super-simple command handlers.
  1821.  *
  1822.  * @param commandHandlerMap An object containing name/value pairs where
  1823.  *                          the name is command name (string) and value
  1824.  *                          is the function to execute for that command
  1825.  */
  1826. function PROT_CommandController(commandHandlerMap) {
  1827.   this.debugZone = "commandhandler";
  1828.   this.cmds_ = commandHandlerMap;
  1829. }
  1830.  
  1831. /**
  1832.  * @param cmd Command to query support for
  1833.  * @returns Boolean indicating if this controller supports cmd
  1834.  */
  1835. PROT_CommandController.prototype.supportsCommand = function(cmd) { 
  1836.   return (cmd in this.cmds_); 
  1837. }
  1838.  
  1839. /**
  1840.  * Trivial implementation
  1841.  *
  1842.  * @param cmd Command to query status of
  1843.  */
  1844. PROT_CommandController.prototype.isCommandEnabled = function(cmd) { 
  1845.   return true; 
  1846. }
  1847.   
  1848. /**
  1849.  * Execute a command
  1850.  *
  1851.  * @param cmd Command to execute
  1852.  */
  1853. PROT_CommandController.prototype.doCommand = function(cmd) {
  1854.   return this.cmds_[cmd](); 
  1855. }
  1856.  
  1857. /**
  1858.  * Trivial implementation
  1859.  */
  1860. PROT_CommandController.prototype.onEvent = function(cmd) { }
  1861.  
  1862. /* ***** BEGIN LICENSE BLOCK *****
  1863.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1864.  *
  1865.  * The contents of this file are subject to the Mozilla Public License Version
  1866.  * 1.1 (the "License"); you may not use this file except in compliance with
  1867.  * the License. You may obtain a copy of the License at
  1868.  * http://www.mozilla.org/MPL/
  1869.  *
  1870.  * Software distributed under the License is distributed on an "AS IS" basis,
  1871.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1872.  * for the specific language governing rights and limitations under the
  1873.  * License.
  1874.  *
  1875.  * The Original Code is Google Safe Browsing.
  1876.  *
  1877.  * The Initial Developer of the Original Code is Google Inc.
  1878.  * Portions created by the Initial Developer are Copyright (C) 2006
  1879.  * the Initial Developer. All Rights Reserved.
  1880.  *
  1881.  * Contributor(s):
  1882.  *   Fritz Schneider <fritz@google.com> (original author)
  1883.  *
  1884.  * Alternatively, the contents of this file may be used under the terms of
  1885.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1886.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1887.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1888.  * of those above. If you wish to allow use of your version of this file only
  1889.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1890.  * use your version of this file under the terms of the MPL, indicate your
  1891.  * decision by deleting the provisions above and replace them with the notice
  1892.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1893.  * the provisions above, a recipient may use your version of this file under
  1894.  * the terms of any one of the MPL, the GPL or the LGPL.
  1895.  *
  1896.  * ***** END LICENSE BLOCK ***** */
  1897.  
  1898.  
  1899. // A class that encapsulates data provider specific values.  The
  1900. // root of the provider pref tree is browser.safebrowsing.provider.
  1901. // followed by a number, followed by specific properties.  The properties
  1902. // that a data provider can supply are:
  1903. //
  1904. // name: The name of the provider
  1905. // lookupURL: The URL to send requests to in enhanced mode
  1906. // keyURL: Before we send URLs in enhanced mode, we need to encrypt them
  1907. // reportURL: When shown a warning bubble, we send back the user decision
  1908. //            (get me out of here/ignore warning) to this URL (strip cookies
  1909. //            first).  This is optional.
  1910. // reportGenericURL: HTML page for general user feedback
  1911. // reportPhishURL: HTML page for notifying the provider of a new phishing page
  1912. // reportErrorURL: HTML page for notifying the provider of a false positive
  1913.  
  1914. const kDataProviderIdPref = 'browser.safebrowsing.dataProvider';
  1915. const kProviderBasePref = 'browser.safebrowsing.provider.';
  1916.  
  1917. /**
  1918.  * Information regarding the data provider.
  1919.  */
  1920. function PROT_DataProvider() {
  1921.   this.prefs_ = new G_Preferences();
  1922.  
  1923.   this.loadDataProviderPrefs_();
  1924.   
  1925.   // Watch for changes in the data provider and update accordingly.
  1926.   this.prefs_.addObserver(kDataProviderIdPref,
  1927.                           BindToObject(this.loadDataProviderPrefs_, this));
  1928. }
  1929.  
  1930. /**
  1931.  * Populate all the provider variables.  We also call this when whenever
  1932.  * the provider id changes.
  1933.  */
  1934. PROT_DataProvider.prototype.loadDataProviderPrefs_ = function() {
  1935.   // Currently, there's no UI for changing local list provider so we
  1936.   // hard code the value for provider 0.
  1937.   this.updateURL_ = this.prefs_.getPref(
  1938.         'browser.safebrowsing.provider.0.updateURL', "");
  1939.  
  1940.   var id = this.prefs_.getPref(kDataProviderIdPref, null);
  1941.  
  1942.   // default to 0
  1943.   if (null == id)
  1944.     id = 0;
  1945.   
  1946.   var basePref = kProviderBasePref + id + '.';
  1947.  
  1948.   this.name_ = this.prefs_.getPref(basePref + "name", "");
  1949.  
  1950.   // Urls used to get data from a provider
  1951.   this.lookupURL_ = this.prefs_.getPref(basePref + "lookupURL", "");
  1952.   this.keyURL_ = this.prefs_.getPref(basePref + "keyURL", "");
  1953.   this.reportURL_ = this.prefs_.getPref(basePref + "reportURL", "");
  1954.  
  1955.   // Urls to HTML report pages
  1956.   this.reportGenericURL_ = this.prefs_.getPref(basePref + "reportGenericURL", "");
  1957.   this.reportErrorURL_ = this.prefs_.getPref(basePref + "reportErrorURL", "");
  1958.   this.reportPhishURL_ = this.prefs_.getPref(basePref + "reportPhishURL", "");
  1959. }
  1960.  
  1961. //////////////////////////////////////////////////////////////////////////////
  1962. // Getters for the remote provider pref values mentioned above.
  1963. PROT_DataProvider.prototype.getName = function() {
  1964.   return this.name_;
  1965. }
  1966.  
  1967. PROT_DataProvider.prototype.getUpdateURL = function() {
  1968.   return this.updateURL_;
  1969. }
  1970.  
  1971. PROT_DataProvider.prototype.getLookupURL = function() {
  1972.   return this.lookupURL_;
  1973. }
  1974. PROT_DataProvider.prototype.getKeyURL = function() {
  1975.   return this.keyURL_;
  1976. }
  1977. PROT_DataProvider.prototype.getReportURL = function() {
  1978.   return this.reportURL_;
  1979. }
  1980.  
  1981. PROT_DataProvider.prototype.getReportGenericURL = function() {
  1982.   return this.reportGenericURL_;
  1983. }
  1984. PROT_DataProvider.prototype.getReportErrorURL = function() {
  1985.   return this.reportErrorURL_;
  1986. }
  1987. PROT_DataProvider.prototype.getReportPhishURL = function() {
  1988.   return this.reportPhishURL_;
  1989. }
  1990. /* ***** BEGIN LICENSE BLOCK *****
  1991.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1992.  *
  1993.  * The contents of this file are subject to the Mozilla Public License Version
  1994.  * 1.1 (the "License"); you may not use this file except in compliance with
  1995.  * the License. You may obtain a copy of the License at
  1996.  * http://www.mozilla.org/MPL/
  1997.  *
  1998.  * Software distributed under the License is distributed on an "AS IS" basis,
  1999.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  2000.  * for the specific language governing rights and limitations under the
  2001.  * License.
  2002.  *
  2003.  * The Original Code is Google Safe Browsing.
  2004.  *
  2005.  * The Initial Developer of the Original Code is Google Inc.
  2006.  * Portions created by the Initial Developer are Copyright (C) 2006
  2007.  * the Initial Developer. All Rights Reserved.
  2008.  *
  2009.  * Contributor(s):
  2010.  *   Niels Provos <niels@google.com> (original author)d
  2011.  
  2012.  *   Fritz Schneider <fritz@google.com>
  2013.  *
  2014.  * Alternatively, the contents of this file may be used under the terms of
  2015.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  2016.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  2017.  * in which case the provisions of the GPL or the LGPL are applicable instead
  2018.  * of those above. If you wish to allow use of your version of this file only
  2019.  * under the terms of either the GPL or the LGPL, and not to allow others to
  2020.  * use your version of this file under the terms of the MPL, indicate your
  2021.  * decision by deleting the provisions above and replace them with the notice
  2022.  * and other provisions required by the GPL or the LGPL. If you do not delete
  2023.  * the provisions above, a recipient may use your version of this file under
  2024.  * the terms of any one of the MPL, the GPL or the LGPL.
  2025.  *
  2026.  * ***** END LICENSE BLOCK ***** */
  2027.  
  2028. // A warden that knows how to register lists with a listmanager and keep them
  2029. // updated if necessary.  The ListWarden also provides a simple interface to
  2030. // check if a URL is evil or not.  Specialized wardens like the PhishingWarden
  2031. // inherit from it.
  2032. //
  2033. // Classes that inherit from ListWarden are responsible for calling
  2034. // enableTableUpdates or disableTableUpdates.  This usually entails
  2035. // registering prefObservers and calling enable or disable in the base
  2036. // class as appropriate.
  2037. //
  2038.  
  2039. /**
  2040.  * Abtracts the checking of user/browser actions for signs of
  2041.  * phishing. 
  2042.  *
  2043.  * @constructor
  2044.  */
  2045. function PROT_ListWarden() {
  2046.   this.debugZone = "listwarden";
  2047.   var listManager = Cc["@mozilla.org/url-classifier/listmanager;1"]
  2048.                       .getService(Ci.nsIUrlListManager);
  2049.   this.listManager_ = listManager;
  2050.  
  2051.   // If we add support for changing local data providers, we need to add a
  2052.   // pref observer that sets the update url accordingly.
  2053.   this.listManager_.setUpdateUrl(gDataProvider.getUpdateURL());
  2054.  
  2055.   // Once we register tables, their respective names will be listed here.
  2056.   this.blackTables_ = [];
  2057.   this.whiteTables_ = [];
  2058. }
  2059.  
  2060. /**
  2061.  * Tell the ListManger to keep all of our tables updated
  2062.  */
  2063.  
  2064. PROT_ListWarden.prototype.enableBlacklistTableUpdates = function() {
  2065.   for (var i = 0; i < this.blackTables_.length; ++i) {
  2066.     this.listManager_.enableUpdate(this.blackTables_[i]);
  2067.   }
  2068. }
  2069.  
  2070. /**
  2071.  * Tell the ListManager to stop updating our tables
  2072.  */
  2073.  
  2074. PROT_ListWarden.prototype.disableBlacklistTableUpdates = function() {
  2075.   for (var i = 0; i < this.blackTables_.length; ++i) {
  2076.     this.listManager_.disableUpdate(this.blackTables_[i]);
  2077.   }
  2078. }
  2079.  
  2080. /**
  2081.  * Tell the ListManager to update whitelist tables.  They may be enabled even
  2082.  * when other updates aren't, for performance reasons.
  2083.  */
  2084. PROT_ListWarden.prototype.enableWhitelistTableUpdates = function() {
  2085.   for (var i = 0; i < this.whiteTables_.length; ++i) {
  2086.     this.listManager_.enableUpdate(this.whiteTables_[i]);
  2087.   }
  2088. }
  2089.  
  2090. /**
  2091.  * Tell the ListManager to stop updating whitelist tables.
  2092.  */
  2093. PROT_ListWarden.prototype.disableWhitelistTableUpdates = function() {
  2094.   for (var i = 0; i < this.whiteTables_.length; ++i) {
  2095.     this.listManager_.disableUpdate(this.whiteTables_[i]);
  2096.   }
  2097. }
  2098.  
  2099. /**
  2100.  * Register a new black list table with the list manager
  2101.  * @param tableName - name of the table to register
  2102.  * @returns true if the table could be registered, false otherwise
  2103.  */
  2104.  
  2105. PROT_ListWarden.prototype.registerBlackTable = function(tableName) {
  2106.   var result = this.listManager_.registerTable(tableName, false);
  2107.   if (result) {
  2108.     this.blackTables_.push(tableName);
  2109.   }
  2110.   return result;
  2111. }
  2112.  
  2113. /**
  2114.  * Register a new white list table with the list manager
  2115.  * @param tableName - name of the table to register
  2116.  * @returns true if the table could be registered, false otherwise
  2117.  */
  2118.  
  2119. PROT_ListWarden.prototype.registerWhiteTable = function(tableName) {
  2120.   var result = this.listManager_.registerTable(tableName, false);
  2121.   if (result) {
  2122.     this.whiteTables_.push(tableName);
  2123.   }
  2124.   return result;
  2125. }
  2126.  
  2127. /**
  2128.  * Internal method that looks up a url in both the white and black lists.
  2129.  *
  2130.  * If there is conflict, the white list has precedence over the black list.
  2131.  *
  2132.  * This is tricky because all database queries are asynchronous.  So we need
  2133.  * to chain together our checks against white and black tables.  We use
  2134.  * MultiTableQuerier (see below) to manage this.
  2135.  *
  2136.  * @param url URL to look up
  2137.  * @param evilCallback Function if the url is evil, we call this function.
  2138.  */
  2139. PROT_ListWarden.prototype.isEvilURL_ = function(url, evilCallback) {
  2140.   (new MultiTableQuerier(url,
  2141.                          this.whiteTables_, 
  2142.                          this.blackTables_,
  2143.                          evilCallback)).run();
  2144. }
  2145.  
  2146. /**
  2147.  * This class helps us query multiple tables even though each table check
  2148.  * is asynchronous.  It provides callbacks for each listManager lookup
  2149.  * and decides whether we need to continue querying or not.  After
  2150.  * instantiating the method, use run() to invoke.
  2151.  *
  2152.  * @param url String The url to check
  2153.  * @param whiteTables Array of strings with each white table name
  2154.  * @param blackTables Array of strings with each black table name
  2155.  * @param evilCallback Function to call if it is an evil url
  2156.  */
  2157. function MultiTableQuerier(url, whiteTables, blackTables, evilCallback) {
  2158.   this.debugZone = "multitablequerier";
  2159.   this.url_ = url;
  2160.  
  2161.   this.whiteTables_ = whiteTables;
  2162.   this.blackTables_ = blackTables;
  2163.   this.whiteIdx_ = 0;
  2164.   this.blackIdx_ = 0;
  2165.  
  2166.   this.evilCallback_ = evilCallback;
  2167.   this.listManager_ = Cc["@mozilla.org/url-classifier/listmanager;1"]
  2168.                       .getService(Ci.nsIUrlListManager);
  2169. }
  2170.  
  2171. /**
  2172.  * We first query the white tables in succession.  If any contain
  2173.  * the url, we stop.  If none contain the url, we query the black tables
  2174.  * in succession.  If any contain the url, we call evilCallback and
  2175.  * stop.  If none of the black tables contain the url, then we just stop
  2176.  * (i.e., it's not black url).
  2177.  */
  2178. MultiTableQuerier.prototype.run = function() {
  2179.   var whiteTable = this.whiteTables_[this.whiteIdx_];
  2180.   var blackTable = this.blackTables_[this.blackIdx_];
  2181.   if (whiteTable) {
  2182.     //G_Debug(this, "Looking in whitetable: " + whiteTable);
  2183.     ++this.whiteIdx_;
  2184.     this.listManager_.safeExists(whiteTable, this.url_,
  2185.                                  BindToObject(this.whiteTableCallback_,
  2186.                                               this));
  2187.   } else if (blackTable) {
  2188.     //G_Debug(this, "Looking in blacktable: " + blackTable);
  2189.     ++this.blackIdx_;
  2190.     this.listManager_.safeExists(blackTable, this.url_,
  2191.                                  BindToObject(this.blackTableCallback_,
  2192.                                               this));
  2193.   } else {
  2194.     // No tables left to check, so we quit.
  2195.     G_Debug(this, "Not found in any tables: " + this.url_);
  2196.  
  2197.     // Break circular ref to callback.
  2198.     this.evilCallback_ = null;
  2199.     this.listManager_ = null;
  2200.   }
  2201. }
  2202.  
  2203. /**
  2204.  * After checking a white table, we return here.  If the url is found,
  2205.  * we can stop.  Otherwise, we call run again.
  2206.  */
  2207. MultiTableQuerier.prototype.whiteTableCallback_ = function(isFound) {
  2208.   //G_Debug(this, "whiteTableCallback_: " + isFound);
  2209.   if (!isFound)
  2210.     this.run();
  2211.   else {
  2212.     G_Debug(this, "Found in whitelist: " + this.url_)
  2213.  
  2214.     // Break circular ref to callback.
  2215.     this.evilCallback_ = null;
  2216.     this.listManager_ = null;
  2217.   }
  2218. }
  2219.  
  2220. /**
  2221.  * After checking a black table, we return here.  If the url is found,
  2222.  * we can call the evilCallback and stop.  Otherwise, we call run again.
  2223.  */
  2224. MultiTableQuerier.prototype.blackTableCallback_ = function(isFound) {
  2225.   //G_Debug(this, "blackTableCallback_: " + isFound);
  2226.   if (!isFound) {
  2227.     this.run();
  2228.   } else {
  2229.     // In the blacklist, must be an evil url.
  2230.     G_Debug(this, "Found in blacklist: " + this.url_)
  2231.     this.evilCallback_();
  2232.  
  2233.     // Break circular ref to callback.
  2234.     this.evilCallback_ = null;
  2235.     this.listManager_ = null;
  2236.   }
  2237. }
  2238. /* ***** BEGIN LICENSE BLOCK *****
  2239.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  2240.  *
  2241.  * The contents of this file are subject to the Mozilla Public License Version
  2242.  * 1.1 (the "License"); you may not use this file except in compliance with
  2243.  * the License. You may obtain a copy of the License at
  2244.  * http://www.mozilla.org/MPL/
  2245.  *
  2246.  * Software distributed under the License is distributed on an "AS IS" basis,
  2247.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  2248.  * for the specific language governing rights and limitations under the
  2249.  * License.
  2250.  *
  2251.  * The Original Code is Google Safe Browsing.
  2252.  *
  2253.  * The Initial Developer of the Original Code is Google Inc.
  2254.  * Portions created by the Initial Developer are Copyright (C) 2006
  2255.  * the Initial Developer. All Rights Reserved.
  2256.  *
  2257.  * Contributor(s):
  2258.  *   Fritz Schneider <fritz@google.com> (original author)
  2259.  *
  2260.  * Alternatively, the contents of this file may be used under the terms of
  2261.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  2262.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  2263.  * in which case the provisions of the GPL or the LGPL are applicable instead
  2264.  * of those above. If you wish to allow use of your version of this file only
  2265.  * under the terms of either the GPL or the LGPL, and not to allow others to
  2266.  * use your version of this file under the terms of the MPL, indicate your
  2267.  * decision by deleting the provisions above and replace them with the notice
  2268.  * and other provisions required by the GPL or the LGPL. If you do not delete
  2269.  * the provisions above, a recipient may use your version of this file under
  2270.  * the terms of any one of the MPL, the GPL or the LGPL.
  2271.  *
  2272.  * ***** END LICENSE BLOCK ***** */
  2273.  
  2274.  
  2275. // Implementation of the warning message we show users when we
  2276. // notice navigation to a phishing page after it has loaded. The
  2277. // browser view encapsulates all the hide/show logic, so the displayer
  2278. // doesn't need to know when to display itself, only how.
  2279. //
  2280. // Displayers implement the following interface:
  2281. //
  2282. // start() -- fired to initialize the displayer (to make it active). When
  2283. //            called, this displayer starts listening for and responding to
  2284. //            events. At most one displayer per tab should be active at a 
  2285. //            time, and start() should be called at most once.
  2286. // declineAction() -- fired when the user declines the warning.
  2287. // acceptAction() -- fired when the user declines the warning
  2288. // explicitShow() -- fired when the user wants to see the warning again
  2289. // browserSelected() -- the browser is the top tab
  2290. // browserUnselected() -- the browser is no long the top tab
  2291. // done() -- clean up. May be called once (even if the displayer wasn't
  2292. //           activated).
  2293. //
  2294. // At the moment, all displayers share access to the same xul in 
  2295. // safebrowsing-overlay.xul. Hence the need for at most one displayer
  2296. // to be active per tab at a time.
  2297.  
  2298. /**
  2299.  * Factory that knows how to create a displayer appropriate to the
  2300.  * user's platform. We use a clunky canvas-based displayer for all
  2301.  * platforms until such time as we can overlay semi-transparent
  2302.  * areas over browser content.
  2303.  *
  2304.  * See the base object for a description of the constructor args
  2305.  *
  2306.  * @constructor
  2307.  */
  2308. function PROT_PhishMsgDisplayer(msgDesc, browser, doc, url) {
  2309.  
  2310.   // TODO: Change this to return a PhishMsgDisplayerTransp on windows
  2311.   // (and maybe other platforms) when Firefox 2.0 hits.
  2312.  
  2313.   return new PROT_PhishMsgDisplayerCanvas(msgDesc, browser, doc, url);
  2314. }
  2315.  
  2316.  
  2317. /**
  2318.  * Base class that implements most of the plumbing required to hide
  2319.  * and show a phishing warning. Subclasses implement the actual
  2320.  * showMessage and hideMessage methods. 
  2321.  *
  2322.  * This class is not meant to be instantiated directly.
  2323.  *
  2324.  * @param msgDesc String describing the kind of warning this is
  2325.  * @param browser Reference to the browser over which we display the msg
  2326.  * @param doc Reference to the document in which browser is found
  2327.  * @param url String containing url of the problem document
  2328.  * @constructor
  2329.  */
  2330. function PROT_PhishMsgDisplayerBase(msgDesc, browser, doc, url) {
  2331.   this.debugZone = "phishdisplayer";
  2332.   this.msgDesc_ = msgDesc;                                // currently unused
  2333.   this.browser_ = browser;
  2334.   this.doc_ = doc;
  2335.   this.url_ = url;
  2336.  
  2337.   // We'll need to manipulate the XUL in safebrowsing-overlay.xul
  2338.   this.messageId_ = "safebrowsing-palm-message";
  2339.   this.messageTailId_ = "safebrowsing-palm-message-tail-container";
  2340.   this.messageContentId_ = "safebrowsing-palm-message-content";
  2341.   this.extendedMessageId_ = "safebrowsing-palm-extended-message";
  2342.   this.showmoreLinkId_ = "safebrowsing-palm-showmore-link";
  2343.   this.urlbarIconId_ = "safebrowsing-urlbar-icon";
  2344.   this.refElementId_ = this.urlbarIconId_;
  2345.  
  2346.   // We use this to report user actions to the server
  2347.   this.reporter_ = new PROT_Reporter();
  2348.  
  2349.   // The active UI elements in our warning send these commands; bind them
  2350.   // to their handlers but don't register the commands until we start
  2351.   // (because another displayer might be active)
  2352.   this.commandHandlers_ = {
  2353.     "safebrowsing-palm-showmore":
  2354.       BindToObject(this.showMore_, this),
  2355.   };
  2356.  
  2357.   this.windowWatcher_ = 
  2358.     Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2359.     .getService(Components.interfaces.nsIWindowWatcher);
  2360. }
  2361.  
  2362. /**
  2363.  * @returns The default background color of the browser
  2364.  */
  2365. PROT_PhishMsgDisplayerBase.prototype.getBackgroundColor_ = function() {
  2366.   var pref = Components.classes["@mozilla.org/preferences-service;1"].
  2367.              getService(Components.interfaces.nsIPrefBranch);
  2368.   return pref.getCharPref("browser.display.background_color");
  2369. }
  2370.  
  2371. /**
  2372.  * Fired when the user declines our warning. Report it!
  2373.  */
  2374. PROT_PhishMsgDisplayerBase.prototype.declineAction = function() {
  2375.   G_Debug(this, "User declined warning.");
  2376.   G_Assert(this, this.started_, "Decline on a non-active displayer?");
  2377.   this.reporter_.report("phishdecline", this.url_);
  2378.  
  2379.   this.messageShouldShow_ = false;
  2380.   if (this.messageShowing_)
  2381.     this.hideMessage_();
  2382. }
  2383.  
  2384. /**
  2385.  * Fired when the user accepts our warning
  2386.  */
  2387. PROT_PhishMsgDisplayerBase.prototype.acceptAction = function() {
  2388.   G_Assert(this, this.started_, "Accept on an unstarted displayer?");
  2389.   G_Assert(this, this.done_, "Accept on a finished displayer?");
  2390.   G_Debug(this, "User accepted warning.");
  2391.   this.reporter_.report("phishaccept", this.url_);
  2392.  
  2393.   var url = this.getMeOutOfHereUrl_();
  2394.   this.browser_.loadURI(url);
  2395. }
  2396.  
  2397. /**
  2398.  * Get the url for "Get me out of here."  This is the user's home page if
  2399.  * one is set, ow, about:blank.
  2400.  * @return String url
  2401.  */
  2402. PROT_PhishMsgDisplayerBase.prototype.getMeOutOfHereUrl_ = function() {
  2403.   // Try to get their homepage from prefs.
  2404.   var prefs = Cc["@mozilla.org/preferences-service;1"]
  2405.               .getService(Ci.nsIPrefService).getBranch(null);
  2406.  
  2407.   var url = "about:blank";
  2408.   try {
  2409.     url = prefs.getComplexValue("browser.startup.homepage",
  2410.                                 Ci.nsIPrefLocalizedString).data;
  2411.   } catch(e) {
  2412.     G_Debug(this, "Couldn't get homepage pref: " + e);
  2413.   }
  2414.   
  2415.   return url;
  2416. }
  2417.  
  2418. /**
  2419.  * Invoked when the browser is resized
  2420.  */
  2421. PROT_PhishMsgDisplayerBase.prototype.onBrowserResized_ = function(event) {
  2422.   G_Debug(this, "Got resize for " + event.target);
  2423.  
  2424.   if (this.messageShowing_) {
  2425.     this.hideMessage_(); 
  2426.     this.showMessage_();
  2427.   }
  2428. }
  2429.  
  2430. /**
  2431.  * Invoked by the browser view when our browser is switched to
  2432.  */
  2433. PROT_PhishMsgDisplayerBase.prototype.browserSelected = function() {
  2434.   G_Assert(this, this.started_, "Displayer selected before being started???");
  2435.  
  2436.   // If messageshowing hasn't been set, then this is the first time this
  2437.   // problematic browser tab has been on top, so do our setup and show
  2438.   // the warning.
  2439.   if (this.messageShowing_ === undefined) {
  2440.     this.messageShouldShow_ = true;
  2441.     this.ensureNavBarShowing_();
  2442.   }
  2443.  
  2444.   this.hideLockIcon_();        // Comes back when we are unselected or unloaded
  2445.   this.addWarningInUrlbar_();  // Goes away when we are unselected or unloaded
  2446.  
  2447.   // messageShouldShow might be false if the user dismissed the warning, 
  2448.   // switched tabs, and then switched back. We're still active, but don't
  2449.   // want to show the warning again. The user can cause it to show by
  2450.   // clicking our icon in the urlbar.
  2451.   if (this.messageShouldShow_)
  2452.     this.showMessage_();
  2453. }
  2454.  
  2455. /**
  2456.  * Invoked to display the warning message explicitly, for example if the user
  2457.  * clicked the url warning icon.
  2458.  */
  2459. PROT_PhishMsgDisplayerBase.prototype.explicitShow = function() {
  2460.   this.messageShouldShow_ = true;
  2461.   if (!this.messageShowing_)
  2462.     this.showMessage_();
  2463. }
  2464.  
  2465. /** 
  2466.  * Invoked by the browser view when our browser is switched away from
  2467.  */
  2468. PROT_PhishMsgDisplayerBase.prototype.browserUnselected = function() {
  2469.   this.removeWarningInUrlbar_();
  2470.   this.unhideLockIcon_();
  2471.   if (this.messageShowing_)
  2472.     this.hideMessage_();
  2473. }
  2474.  
  2475. /**
  2476.  * Invoked to make this displayer active. The displayer will now start
  2477.  * responding to notifications such as commands and resize events. We
  2478.  * can't do this in the constructor because there might be many 
  2479.  * displayers instantiated waiting in the problem queue for a particular
  2480.  * browser (e.g., a page has multiple framed problem pages), and we
  2481.  * don't want them all responding to commands!
  2482.  *
  2483.  * Invoked zero (the page we're a warning for was nav'd away from
  2484.  * before it reaches the head of the problem queue) or one (we're
  2485.  * displaying this warning) times by the browser view.
  2486.  */
  2487. PROT_PhishMsgDisplayerBase.prototype.start = function() {
  2488.   G_Assert(this, this.started_ == undefined, "Displayer started twice?");
  2489.   this.started_ = true;
  2490.  
  2491.   this.commandController_ = new PROT_CommandController(this.commandHandlers_);
  2492.   this.doc_.defaultView.controllers.appendController(this.commandController_);
  2493.  
  2494.   // Add an event listener for when the browser resizes (e.g., user
  2495.   // shows/hides the sidebar).
  2496.   this.resizeHandler_ = BindToObject(this.onBrowserResized_, this);
  2497.   this.browser_.addEventListener("resize",
  2498.                                  this.resizeHandler_, 
  2499.                                  false);
  2500. }
  2501.  
  2502. /**
  2503.  * @returns Boolean indicating whether this displayer is currently
  2504.  *          active
  2505.  */
  2506. PROT_PhishMsgDisplayerBase.prototype.isActive = function() {
  2507.   return !!this.started_;
  2508. }
  2509.  
  2510. /**
  2511.  * Invoked by the browser view to clean up after the user is done 
  2512.  * interacting with the message. Should be called once by the browser
  2513.  * view. 
  2514.  */
  2515. PROT_PhishMsgDisplayerBase.prototype.done = function() {
  2516.   G_Assert(this, !this.done_, "Called done more than once?");
  2517.   this.done_ = true;
  2518.  
  2519.   // If the Document we're showing the warning for was nav'd away from
  2520.   // before we had a chance to get started, we have nothing to do.
  2521.   if (this.started_) {
  2522.  
  2523.     // If we were started, we must be the current problem, so these things
  2524.     // must be showing
  2525.     this.removeWarningInUrlbar_();
  2526.     this.unhideLockIcon_();
  2527.  
  2528.     // Could be though that they've closed the warning dialog
  2529.     if (this.messageShowing_)
  2530.       this.hideMessage_();
  2531.  
  2532.     if (this.resizeHandler_) {
  2533.       this.browser_.removeEventListener("resize", 
  2534.                                         this.resizeHandler_, 
  2535.                                         false);
  2536.       this.resizeHandler_ = null;
  2537.     }
  2538.     
  2539.     var win = this.doc_.defaultView;
  2540.     win.controllers.removeController(this.commandController_);
  2541.     this.commandController_ = null;
  2542.   }
  2543. }
  2544.  
  2545. /**
  2546.  * Helper function to remove a substring from inside a string.
  2547.  *
  2548.  * @param orig String to remove substring from
  2549.  * 
  2550.  * @param toRemove String to remove (if it is present)
  2551.  *
  2552.  * @returns String with the substring removed
  2553.  */
  2554. PROT_PhishMsgDisplayerBase.prototype.removeIfExists_ = function(orig,
  2555.                                                                 toRemove) {
  2556.   var pos = orig.indexOf(toRemove);
  2557.   if (pos != -1)
  2558.     orig = orig.substring(0, pos) + orig.substring(pos + toRemove.length);
  2559.  
  2560.   return orig;
  2561. }
  2562.  
  2563. /**
  2564.  * Our message is displayed relative to an icon in the urlbar. However
  2565.  * it could be the case that the urlbar isn't showing, in which case
  2566.  * we would show the warning message some place crazy, such as
  2567.  * offscreen. So here we put it back if it's not there. This is a
  2568.  * good thing anyway: the user should be able to see the URL of the
  2569.  * site if we think it is suspicious.
  2570.  */
  2571. PROT_PhishMsgDisplayerBase.prototype.ensureNavBarShowing_ = function() {
  2572.   // Could be that the navbar was unselected in the Toolbars menu; fix it
  2573.   var navbar = this.doc_.getElementById("nav-bar");
  2574.   navbar.setAttribute("collapsed", false);
  2575.  
  2576.   // Now for the more complicated case: a popup window with toolbar=no. This
  2577.   // adds toolbar and location (among other things) to the chromhidden 
  2578.   // attribute on the window. We need to undo this, and manually fill in the
  2579.   // location.
  2580.   var win = this.doc_.getElementById("main-window");
  2581.   var hidden = win.getAttribute("chromehidden");
  2582.   G_Debug(this, "Old chromehidden string: " + hidden);
  2583.  
  2584.   var newHidden = this.removeIfExists_(hidden, "toolbar");
  2585.   newHidden = this.removeIfExists_(newHidden, "location");
  2586.  
  2587.   if (newHidden != hidden) {
  2588.     G_Debug(this, "New chromehidden string: " + newHidden);
  2589.     win.setAttribute("chromehidden", newHidden);
  2590.  
  2591.     // Now manually reflect the location
  2592.     var urlbar = this.doc_.getElementById("urlbar");
  2593.     urlbar.value = this.doc_.getElementById("content")
  2594.                    .contentDocument.location.href;
  2595.   }
  2596. }
  2597.  
  2598. /**
  2599.  * We don't want to confuse users if they land on a phishy page that uses
  2600.  * SSL, so ensure that the lock icon never shows when we're showing our 
  2601.  * warning.
  2602.  */
  2603. PROT_PhishMsgDisplayerBase.prototype.hideLockIcon_ = function() {
  2604.   var lockIcon = this.doc_.getElementById("lock-icon");
  2605.   lockIcon.hidden = true;
  2606. }
  2607.  
  2608. /**
  2609.  * Ensure they can see it after our warning is finished.
  2610.  */
  2611. PROT_PhishMsgDisplayerBase.prototype.unhideLockIcon_ = function() {
  2612.   var lockIcon = this.doc_.getElementById("lock-icon");
  2613.   lockIcon.hidden = false;
  2614. }
  2615.  
  2616. /**
  2617.  * This method makes our warning icon visible in the location bar. It will
  2618.  * be removed only when the problematic document is navigated awy from 
  2619.  * (i.e., when done() is called), and not when the warning is dismissed.
  2620.  */
  2621. PROT_PhishMsgDisplayerBase.prototype.addWarningInUrlbar_ = function() {
  2622.   var urlbarIcon = this.doc_.getElementById(this.urlbarIconId_);
  2623.   urlbarIcon.setAttribute('level', 'warn');
  2624. }
  2625.  
  2626. /**
  2627.  * Hides our urlbar icon
  2628.  */
  2629. PROT_PhishMsgDisplayerBase.prototype.removeWarningInUrlbar_ = function() {
  2630.   var urlbarIcon = this.doc_.getElementById(this.urlbarIconId_);
  2631.   urlbarIcon.setAttribute('level', 'safe');
  2632. }
  2633.  
  2634. /**
  2635.  * VIRTUAL -- Displays the warning message
  2636.  */
  2637. PROT_PhishMsgDisplayerBase.prototype.showMessage_ = function() { };
  2638.  
  2639. /**
  2640.  * VIRTUAL -- Hide the warning message from the user.
  2641.  */
  2642. PROT_PhishMsgDisplayerBase.prototype.hideMessage_ = function() { };
  2643.  
  2644. /**
  2645.  * Reposition the message relative to refElement in the parent window
  2646.  *
  2647.  * @param message Reference to the element to position
  2648.  * @param tail Reference to the message tail
  2649.  * @param refElement Reference to element relative to which we position
  2650.  *                   ourselves
  2651.  */
  2652. PROT_PhishMsgDisplayerBase.prototype.adjustLocation_ = function(message,
  2653.                                                                 tail,
  2654.                                                                 refElement) {
  2655.  
  2656.   var refX = refElement.boxObject.x;
  2657.   var refY = refElement.boxObject.y;
  2658.   var refHeight = refElement.boxObject.height;
  2659.   var refWidth = refElement.boxObject.width;
  2660.   G_Debug(this, "Ref element is at [window-relative] (" + refX + ", " + 
  2661.           refY + ")");
  2662.  
  2663.   var pixelsIntoRefY = -2;
  2664.   var tailY = refY + refHeight - pixelsIntoRefY;
  2665.   var tailPixelsLeftOfRefX = tail.boxObject.width;
  2666.   var tailPixelsIntoRefX = Math.round(refWidth / 2);
  2667.   var tailX = refX - tailPixelsLeftOfRefX + tailPixelsIntoRefX;
  2668.  
  2669.   var messageY = tailY + tail.boxObject.height + 3;
  2670.   var messagePixelsLeftOfRefX = 375;
  2671.   var messageX = refX - messagePixelsLeftOfRefX;
  2672.   G_Debug(this, "Message is at [window-relative] (" + messageX + ", " + 
  2673.           messageY + ")");
  2674.   G_Debug(this, "Tail is at [window-relative] (" + tailX + ", " + 
  2675.           tailY + ")");
  2676.  
  2677.   tail.style.top = tailY + "px";
  2678.   tail.style.left = tailX + "px";
  2679.   message.style.top = messageY + "px";
  2680.   message.style.left = messageX + "px";
  2681. }
  2682.  
  2683. /**
  2684.  * Show the extended warning message
  2685.  */
  2686. PROT_PhishMsgDisplayerBase.prototype.showMore_ = function() {
  2687.   this.doc_.getElementById(this.extendedMessageId_).hidden = false;
  2688.   this.doc_.getElementById(this.showmoreLinkId_).style.display = "none";
  2689. }
  2690.  
  2691. /**
  2692.  * The user clicked on one of the links in the buble.  Display the
  2693.  * corresponding page in a new window with all the chrome enabled.
  2694.  *
  2695.  * @param url The URL to display in a new window
  2696.  */
  2697. PROT_PhishMsgDisplayerBase.prototype.showURL_ = function(url) {
  2698.   this.windowWatcher_.openWindow(this.windowWatcher_.activeWindow,
  2699.                                  url,
  2700.                                  "_blank",
  2701.                                  null,
  2702.                                  null);
  2703. }
  2704.  
  2705. /**
  2706.  * If the warning bubble came up in error, this url goes to a form
  2707.  * to notify the data provider.
  2708.  * @return url String
  2709.  */
  2710. PROT_PhishMsgDisplayerBase.prototype.getReportErrorURL_ = function() {
  2711.   var badUrl = this.url_;
  2712.  
  2713.   var url = gDataProvider.getReportErrorURL();
  2714.   url += "&url=" + encodeURIComponent(badUrl);
  2715.   return url;
  2716. }
  2717.  
  2718. /**
  2719.  * URL for the user to report back to us.  This is to provide the user
  2720.  * with an action after being warned.
  2721.  */
  2722. PROT_PhishMsgDisplayerBase.prototype.getReportGenericURL_ = function() {
  2723.   var badUrl = this.url_;
  2724.  
  2725.   var url = gDataProvider.getReportGenericURL();
  2726.   url += "&url=" + encodeURIComponent(badUrl);
  2727.   return url;
  2728. }
  2729.  
  2730.  
  2731. /**
  2732.  * A specific implementation of the dislpayer using a canvas. This
  2733.  * class is meant for use on platforms that don't support transparent
  2734.  * elements over browser content (currently: all platforms). 
  2735.  *
  2736.  * The main ugliness is the fact that we're hiding the content area and
  2737.  * painting the page to canvas. As a result, we must periodically
  2738.  * re-paint the canvas to reflect updates to the page. Otherwise if
  2739.  * the page was half-loaded when we showed our warning, it would
  2740.  * stay that way even though the page actually finished loading. 
  2741.  *
  2742.  * See base constructor for full details of constructor args.
  2743.  *
  2744.  * @constructor
  2745.  */
  2746. function PROT_PhishMsgDisplayerCanvas(msgDesc, browser, doc, url) {
  2747.   PROT_PhishMsgDisplayerBase.call(this, msgDesc, browser, doc, url);
  2748.  
  2749.   this.dimAreaId_ = "safebrowsing-dim-area-canvas";
  2750.   this.pageCanvasId_ = "safebrowsing-page-canvas";
  2751.   this.xhtmlNS_ = "http://www.w3.org/1999/xhtml";     // we create html:canvas
  2752. }
  2753.  
  2754. PROT_PhishMsgDisplayerCanvas.inherits(PROT_PhishMsgDisplayerBase);
  2755.  
  2756. /**
  2757.  * Displays the warning message.  First we make sure the overlay is loaded
  2758.  * then call showMessageAfterOverlay_.
  2759.  */
  2760. PROT_PhishMsgDisplayerCanvas.prototype.showMessage_ = function() {
  2761.   G_Debug(this, "Showing message.");
  2762.  
  2763.   // Load the overlay if we haven't already.
  2764.   var dimmer = this.doc_.getElementById('safebrowsing-dim-area-canvas');
  2765.   if (!dimmer) {
  2766.     var onOverlayMerged = BindToObject(this.showMessageAfterOverlay_,
  2767.                                        this);
  2768.     var observer = new G_ObserverWrapper("xul-overlay-merged",
  2769.                                          onOverlayMerged);
  2770.  
  2771.     this.doc_.loadOverlay(
  2772.         "chrome://browser/content/safebrowsing/warning-overlay.xul",
  2773.         observer);
  2774.   } else {
  2775.     // The overlay is already loaded so we go ahead and call
  2776.     // showMessageAfterOverlay_.
  2777.     this.showMessageAfterOverlay_();
  2778.   }
  2779. }
  2780.  
  2781. /**
  2782.  * This does the actual work of showing the warning message.
  2783.  */
  2784. PROT_PhishMsgDisplayerCanvas.prototype.showMessageAfterOverlay_ = function() {
  2785.   this.messageShowing_ = true;
  2786.  
  2787.   // Position the canvas overlay. Order here is significant, but don't ask me
  2788.   // why for some of these. You need to:
  2789.   // 1. get browser dimensions
  2790.   // 2. add canvas to the document
  2791.   // 3. unhide the dimmer (gray out overlay)
  2792.   // 4. display to the canvas
  2793.   // 5. unhide the warning message
  2794.   // 6. update link targets in warning message
  2795.   // 7. focus the warning message
  2796.  
  2797.   // (1)
  2798.   var w = this.browser_.boxObject.width;
  2799.   G_Debug(this, "browser w=" + w);
  2800.   var h = this.browser_.boxObject.height;
  2801.   G_Debug(this, "browser h=" + h);
  2802.   var x = this.browser_.boxObject.x;
  2803.   G_Debug(this, "browser x=" + w);
  2804.   var y = this.browser_.boxObject.y;
  2805.   G_Debug(this, "browser y=" + h);
  2806.  
  2807.   var win = this.browser_.contentWindow;
  2808.   var scrollX = win.scrollX;
  2809.   G_Debug(this, "win scrollx=" + scrollX);
  2810.   var scrollY = win.scrollY;
  2811.   G_Debug(this, "win scrolly=" + scrollY);
  2812.  
  2813.   // (2)
  2814.   // We add the canvas dynamically and remove it when we're done because
  2815.   // leaving it hanging around consumes a lot of memory.
  2816.   var pageCanvas = this.doc_.createElementNS(this.xhtmlNS_, "html:canvas");
  2817.   pageCanvas.id = this.pageCanvasId_;
  2818.   pageCanvas.style.left = x + 'px';
  2819.   pageCanvas.style.top = y + 'px';
  2820.  
  2821.   var dimarea = this.doc_.getElementById(this.dimAreaId_);
  2822.   this.doc_.getElementById('main-window').insertBefore(pageCanvas,
  2823.                                                        dimarea);
  2824.  
  2825.   // (3)
  2826.   dimarea.style.left = x + 'px';
  2827.   dimarea.style.top = y + 'px';
  2828.   dimarea.style.width = w + 'px';
  2829.   dimarea.style.height = h + 'px';
  2830.   dimarea.hidden = false;
  2831.   
  2832.   // (4)
  2833.   pageCanvas.setAttribute("width", w);
  2834.   pageCanvas.setAttribute("height", h);
  2835.  
  2836.   var bgcolor = this.getBackgroundColor_();
  2837.  
  2838.   var cx = pageCanvas.getContext("2d");
  2839.   cx.drawWindow(win, scrollX, scrollY, w, h, bgcolor);
  2840.  
  2841.   // Now repaint the window every so often in case the content hasn't fully
  2842.   // loaded at this point.
  2843.   var debZone = this.debugZone;
  2844.   function repaint() {
  2845.     G_Debug(debZone, "Repainting canvas...");
  2846.     cx.drawWindow(win, scrollX, scrollY, w, h, bgcolor);
  2847.   };
  2848.   this.repainter_ = new PROT_PhishMsgCanvasRepainter(repaint);
  2849.  
  2850.   // (5)
  2851.   var refElement = this.doc_.getElementById(this.refElementId_);
  2852.   var message = this.doc_.getElementById(this.messageId_);
  2853.   var tail = this.doc_.getElementById(this.messageTailId_);
  2854.   message.hidden = false;
  2855.   message.style.display = "block";
  2856.   tail.hidden = false;
  2857.   tail.style.display = "block";
  2858.   this.adjustLocation_(message, tail, refElement);
  2859.  
  2860.   // (6)
  2861.   var link = this.doc_.getElementById('safebrowsing-palm-falsepositive-link');
  2862.   link.href = this.getReportErrorURL_();
  2863.   link = this.doc_.getElementById('safebrowsing-palm-report-link');
  2864.   link.href = this.getReportGenericURL_();
  2865.  
  2866.   // (7)
  2867.   this.doc_.getElementById(this.messageContentId_).focus();
  2868. }
  2869.  
  2870. /**
  2871.  * Hide the warning message from the user.
  2872.  */
  2873. PROT_PhishMsgDisplayerCanvas.prototype.hideMessage_ = function() {
  2874.   G_Debug(this, "Hiding phishing warning.");
  2875.   G_Assert(this, this.messageShowing_, "Hide message called but not showing?");
  2876.  
  2877.   this.messageShowing_ = false;
  2878.   this.repainter_.cancel();
  2879.   this.repainter_ = null;
  2880.  
  2881.   // Hide the warning popup.
  2882.   var message = this.doc_.getElementById(this.messageId_);
  2883.   message.hidden = true;
  2884.   message.style.display = "none";
  2885.  
  2886.   var tail = this.doc_.getElementById(this.messageTailId_);
  2887.   tail.hidden = true;
  2888.   tail.style.display = "none";
  2889.  
  2890.   // Remove the canvas element from the chrome document.
  2891.   var pageCanvas = this.doc_.getElementById(this.pageCanvasId_);
  2892.   pageCanvas.parentNode.removeChild(pageCanvas);
  2893.  
  2894.   // Hide the dimmer.
  2895.   var dimarea = this.doc_.getElementById(this.dimAreaId_);
  2896.   dimarea.hidden = true;
  2897. }
  2898.  
  2899.  
  2900. /**
  2901.  * Helper class that periodically repaints the canvas. We repaint
  2902.  * frequently at first, and then back off to a less frequent schedule
  2903.  * at "steady state," and finally just stop altogether. We have to do
  2904.  * this because we're not sure if the page has finished loading when
  2905.  * we first paint the canvas, and because we want to reflect any
  2906.  * dynamically written content into the canvas as it appears in the
  2907.  * page after load.
  2908.  *
  2909.  * @param repaintFunc Function to call to repaint browser.
  2910.  *
  2911.  * @constructor
  2912.  */
  2913. function PROT_PhishMsgCanvasRepainter(repaintFunc) {
  2914.   this.count_ = 0;
  2915.   this.repaintFunc_ = repaintFunc;
  2916.   this.initPeriodMS_ = 500;             // Initially repaint every 500ms
  2917.   this.steadyStateAtMS_ = 10 * 1000;    // Go slowly after 10 seconds,
  2918.   this.steadyStatePeriodMS_ = 3 * 1000; // repainting every 3 seconds, and
  2919.   this.quitAtMS_ = 20 * 1000;           // stop after 20 seconds
  2920.   this.startMS_ = (new Date).getTime();
  2921.   this.alarm_ = new G_Alarm(BindToObject(this.repaint, this), 
  2922.                             this.initPeriodMS_);
  2923. }
  2924.  
  2925. /**
  2926.  * Called periodically to repaint the canvas
  2927.  */
  2928. PROT_PhishMsgCanvasRepainter.prototype.repaint = function() {
  2929.   this.repaintFunc_();
  2930.  
  2931.   var nextRepaint;
  2932.   // If we're in "steady state", use the slow repaint rate, else fast
  2933.   if ((new Date).getTime() - this.startMS_ > this.steadyStateAtMS_)
  2934.     nextRepaint = this.steadyStatePeriodMS_;
  2935.   else 
  2936.     nextRepaint = this.initPeriodMS_;
  2937.  
  2938.   if (!((new Date).getTime() - this.startMS_ > this.quitAtMS_))
  2939.     this.alarm_ = new G_Alarm(BindToObject(this.repaint, this), nextRepaint);
  2940. }
  2941.  
  2942. /**
  2943.  * Called to stop repainting the canvas
  2944.  */
  2945. PROT_PhishMsgCanvasRepainter.prototype.cancel = function() {
  2946.   if (this.alarm_) {
  2947.     this.alarm_.cancel();
  2948.     this.alarm_ = null;
  2949.   }
  2950.   this.repaintFunc_ = null;
  2951. }
  2952. /* ***** BEGIN LICENSE BLOCK *****
  2953.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  2954.  *
  2955.  * The contents of this file are subject to the Mozilla Public License Version
  2956.  * 1.1 (the "License"); you may not use this file except in compliance with
  2957.  * the License. You may obtain a copy of the License at
  2958.  * http://www.mozilla.org/MPL/
  2959.  *
  2960.  * Software distributed under the License is distributed on an "AS IS" basis,
  2961.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  2962.  * for the specific language governing rights and limitations under the
  2963.  * License.
  2964.  *
  2965.  * The Original Code is Google Safe Browsing.
  2966.  *
  2967.  * The Initial Developer of the Original Code is Google Inc.
  2968.  * Portions created by the Initial Developer are Copyright (C) 2006
  2969.  * the Initial Developer. All Rights Reserved.
  2970.  *
  2971.  * Contributor(s):
  2972.  *   Fritz Schneider <fritz@google.com> (original author)
  2973.  *
  2974.  * Alternatively, the contents of this file may be used under the terms of
  2975.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  2976.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  2977.  * in which case the provisions of the GPL or the LGPL are applicable instead
  2978.  * of those above. If you wish to allow use of your version of this file only
  2979.  * under the terms of either the GPL or the LGPL, and not to allow others to
  2980.  * use your version of this file under the terms of the MPL, indicate your
  2981.  * decision by deleting the provisions above and replace them with the notice
  2982.  * and other provisions required by the GPL or the LGPL. If you do not delete
  2983.  * the provisions above, a recipient may use your version of this file under
  2984.  * the terms of any one of the MPL, the GPL or the LGPL.
  2985.  *
  2986.  * ***** END LICENSE BLOCK ***** */
  2987.  
  2988.  
  2989. // The warden checks request to see if they are for phishy pages. It
  2990. // does so by either querying a remote server with the URL (advanced
  2991. // protectoin mode) or querying our locally stored blacklists (privacy
  2992. // mode).
  2993. // 
  2994. // When the warden notices a problem, it queries all browser views
  2995. // (each of which corresopnds to an open browser window) to see
  2996. // whether one of them can handle it. A browser view can handle a
  2997. // problem if its browser window has an HTMLDocument loaded with the
  2998. // given URL and that Document hasn't already been flagged as a
  2999. // problem. For every problematic URL we notice loading, at most one
  3000. // Document is flagged as problematic. Otherwise you can get into
  3001. // trouble if multiple concurrent phishy pages load with the same URL.
  3002. //
  3003. // Since we check URLs very early in the request cycle (in a progress
  3004. // listener), the URL might not yet be associated with a Document when
  3005. // we determine that it is phishy. So the the warden retries finding
  3006. // a browser view to handle the problem until one can, or until it
  3007. // determines it should give up (see complicated logic below).
  3008. //
  3009. // The warden has displayers that the browser view uses to render
  3010. // different kinds of warnings (e.g., one that's shown before a page
  3011. // loads as opposed to one that's shown after the page has already
  3012. // loaded).
  3013. //
  3014. // Note: There is a single warden for the whole application.
  3015. //
  3016. // TODO better way to expose displayers/views to browser view
  3017.  
  3018. const kPhishWardenEnabledPref = "browser.safebrowsing.enabled";
  3019. const kPhishWardenRemoteLookups = "browser.safebrowsing.remoteLookups";
  3020.  
  3021. // We have hardcoded URLs that we let people navigate to in order to 
  3022. // check out the warning.
  3023. const kTestUrls = {
  3024.   "http://www.google.com/tools/firefox/safebrowsing/phish-o-rama.html": true,
  3025.   "http://www.mozilla.org/projects/bonecho/anti-phishing/its-a-trap.html": true,
  3026.   "http://www.mozilla.com/firefox/its-a-trap.html": true,
  3027. }
  3028.  
  3029. /**
  3030.  * Abtracts the checking of user/browser actions for signs of
  3031.  * phishing. 
  3032.  *
  3033.  * @param progressListener nsIDocNavStartProgressListener
  3034.  * @constructor
  3035.  */
  3036. function PROT_PhishingWarden(progressListener) {
  3037.   PROT_ListWarden.call(this);
  3038.  
  3039.   this.debugZone = "phishwarden";
  3040.   this.testing_ = false;
  3041.   this.browserViews_ = [];
  3042.  
  3043.   // Use this to query preferences
  3044.   this.prefs_ = new G_Preferences();
  3045.  
  3046.   // Only one displayer so far; perhaps we'll have others in the future
  3047.   this.displayers_ = {
  3048.     "afterload": PROT_PhishMsgDisplayer,
  3049.   };
  3050.  
  3051.   // We use this dude to do lookups on our remote server
  3052.   this.fetcher_ = new PROT_TRFetcher();
  3053.  
  3054.   // We need to know whether we're enabled and whether we're in advanced
  3055.   // mode, so reflect the appropriate preferences into our state.
  3056.  
  3057.   // Read state: should we be checking remote preferences?
  3058.   this.checkRemote_ = this.prefs_.getPref(kPhishWardenRemoteLookups, null);
  3059.  
  3060.   // Get notifications when the remote check preference changes
  3061.   var checkRemotePrefObserver = BindToObject(this.onCheckRemotePrefChanged,
  3062.                                              this);
  3063.   this.prefs_.addObserver(kPhishWardenRemoteLookups, checkRemotePrefObserver);
  3064.  
  3065.   // Global preference to enable the phishing warden
  3066.   this.phishWardenEnabled_ = this.prefs_.getPref(kPhishWardenEnabledPref, null);
  3067.  
  3068.   // Get notifications when the phishing warden enabled pref changes
  3069.   var phishWardenPrefObserver = 
  3070.     BindToObject(this.onPhishWardenEnabledPrefChanged, this);
  3071.   this.prefs_.addObserver(kPhishWardenEnabledPref, phishWardenPrefObserver);
  3072.  
  3073.   // hook up our browser listener
  3074.   this.progressListener_ = progressListener;
  3075.   this.progressListener_.callback = this;
  3076.   this.progressListener_.enabled = this.phishWardenEnabled_;
  3077.   // ms to wait after a request has started before firing JS callback
  3078.   this.progressListener_.delay = 1500;
  3079.  
  3080.   G_Debug(this, "phishWarden initialized");
  3081. }
  3082.  
  3083. PROT_PhishingWarden.inherits(PROT_ListWarden);
  3084.  
  3085. /**
  3086.  * We implement nsIWebProgressListener
  3087.  */
  3088. PROT_PhishingWarden.prototype.QueryInterface = function(iid) {
  3089.   if (iid.equals(Ci.nsISupports) || 
  3090.       iid.equals(Ci.nsIWebProgressListener) ||
  3091.       iid.equals(Ci.nsISupportsWeakReference))
  3092.     return this;
  3093.   throw Components.results.NS_ERROR_NO_INTERFACE;
  3094. }
  3095.  
  3096. /**
  3097.  * Cleanup on shutdown.
  3098.  */
  3099. PROT_PhishingWarden.prototype.shutdown = function() {
  3100.   this.progressListener_.callback = null;
  3101.   this.progressListener_ = null;
  3102.   this.listManager_ = null;
  3103. }
  3104.  
  3105. /**
  3106.  * When a preference (either advanced features or the phishwarden
  3107.  * enabled) changes, we might have to start or stop asking for updates. 
  3108.  * 
  3109.  * This is a little tricky; we start or stop management only when we
  3110.  * have complete information we can use to determine whether we
  3111.  * should.  It could be the case that one pref or the other isn't set
  3112.  * yet (e.g., they haven't opted in/out of advanced features). So do
  3113.  * nothing unless we have both pref values -- we get notifications for
  3114.  * both, so eventually we will start correctly.
  3115.  */ 
  3116. PROT_PhishingWarden.prototype.maybeToggleUpdateChecking = function() {
  3117.   if (this.testing_)
  3118.     return;
  3119.  
  3120.   var phishWardenEnabled = this.prefs_.getPref(kPhishWardenEnabledPref, null);
  3121.  
  3122.   this.checkRemote_ = this.prefs_.getPref(kPhishWardenRemoteLookups, null);
  3123.  
  3124.   G_Debug(this, "Maybe toggling update checking. " +
  3125.           "Warden enabled? " + phishWardenEnabled + " || " +
  3126.           "Check remote? " + this.checkRemote_);
  3127.  
  3128.   // Do nothing unless both prefs are set.  They can be null (unset), true, or
  3129.   // false.
  3130.   if (phishWardenEnabled === null || this.checkRemote_ === null)
  3131.     return;
  3132.  
  3133.   // We update and save to disk all tables if we don't have remote checking
  3134.   // enabled.  However, as long as the warden is enabled we always update the
  3135.   // whitelist, even if remote checking is disabled.  This gives a performance
  3136.   // benefit since we use the WL to suppress BL lookups.
  3137.   // 
  3138.   // phishEnabled remote WLupdates BLupdates
  3139.   // T            T      T         F
  3140.   // T            F      T         T
  3141.   // F            T      F         F
  3142.   // F            F      F         F
  3143.  
  3144.   if (phishWardenEnabled === true) {
  3145.     this.enableWhitelistTableUpdates();
  3146.     if (this.checkRemote_ === true) {
  3147.       this.disableBlacklistTableUpdates();
  3148.     } else if (this.checkRemote_ === false) {
  3149.       this.enableBlacklistTableUpdates();
  3150.     }
  3151.   } else if (phishWardenEnabled === false) {
  3152.     this.disableBlacklistTableUpdates();
  3153.     this.disableWhitelistTableUpdates();
  3154.   }
  3155. }
  3156.  
  3157. /**
  3158.  * Controllers register their browser views with us
  3159.  *
  3160.  * @param view Reference to a browser view 
  3161.  */
  3162. PROT_PhishingWarden.prototype.addBrowserView = function(view) {
  3163.   G_Debug(this, "New browser view registered.");
  3164.   this.browserViews_.push(view);
  3165. }
  3166.  
  3167. /**
  3168.  * Controllers unregister their views when their window closes
  3169.  *
  3170.  * @param view Reference to a browser view 
  3171.  */
  3172. PROT_PhishingWarden.prototype.removeBrowserView = function(view) {
  3173.   for (var i = 0; i < this.browserViews_.length; i++)
  3174.     if (this.browserViews_[i] === view) {
  3175.       G_Debug(this, "Browser view unregistered.");
  3176.       this.browserViews_.splice(i, 1);
  3177.       return;
  3178.     }
  3179.   G_Assert(this, false, "Tried to unregister non-existent browser view!");
  3180. }
  3181.  
  3182. /**
  3183.  * Deal with a user changing the pref that says whether we should check
  3184.  * the remote server (i.e., whether we're in advanced mode)
  3185.  *
  3186.  * @param prefName Name of the pref holding the value indicating whether
  3187.  *                 we should check remote server
  3188.  */
  3189. PROT_PhishingWarden.prototype.onCheckRemotePrefChanged = function(prefName) {
  3190.   this.checkRemote_ = this.prefs_.getBoolPrefOrDefault(prefName,
  3191.                                                        this.checkRemote_);
  3192.   this.maybeToggleUpdateChecking();
  3193. }
  3194.  
  3195. /**
  3196.  * Deal with a user changing the pref that says whether we should 
  3197.  * enable the phishing warden (i.e., that SafeBrowsing is active)
  3198.  *
  3199.  * @param prefName Name of the pref holding the value indicating whether
  3200.  *                 we should enable the phishing warden
  3201.  */
  3202. PROT_PhishingWarden.prototype.onPhishWardenEnabledPrefChanged = function(
  3203.                                                                     prefName) {
  3204.   this.phishWardenEnabled_ = 
  3205.     this.prefs_.getBoolPrefOrDefault(prefName, this.phishWardenEnabled_);
  3206.   this.maybeToggleUpdateChecking();
  3207.   this.progressListener_.enabled = this.phishWardenEnabled_;
  3208. }
  3209.  
  3210. /**
  3211.  * A request for a Document has been initiated somewhere. Check it!
  3212.  *
  3213.  * @param request
  3214.  * @param url
  3215.  */ 
  3216. PROT_PhishingWarden.prototype.onDocNavStart = function(request, url) {
  3217.   G_Debug(this, "checkRemote: " +
  3218.           (this.checkRemote_ ? "yes" : "no"));
  3219.  
  3220.   // This logic is a bit involved. In some instances of SafeBrowsing
  3221.   // (the stand-alone extension, for example), the user might yet have
  3222.   // opted into or out of advanced protection mode. In this case we
  3223.   // would like to show them a modal dialog requiring them
  3224.   // to. However, there are links from that dialog to the test page,
  3225.   // and the warden starts out as disabled. So we want to show the
  3226.   // warning on the test page so long as the extension hasn't been
  3227.   // explicitly disabled.
  3228.  
  3229.   // If we're on the test page and we're not explicitly disabled
  3230.   // XXX Do we still need a test url or should each provider just put
  3231.   // it in their local list?
  3232.   // Either send a request off or check locally
  3233.   if (this.checkRemote_) {
  3234.     // First check to see if it's a blacklist url.
  3235.     if (this.isBlacklistTestURL(url)) {
  3236.       this.houstonWeHaveAProblem_(request);
  3237.     } else {
  3238.       // TODO: Use local whitelists to suppress remote BL lookups. 
  3239.       this.fetcher_.get(url,
  3240.                         BindToObject(this.onTRFetchComplete,
  3241.                                      this,
  3242.                                      request));
  3243.     }
  3244.   } else {
  3245.     // Check the local lists for a match.
  3246.     var evilCallback = BindToObject(this.localListMatch_,
  3247.                                     this,
  3248.                                     url,
  3249.                                     request);
  3250.     this.checkUrl_(url, evilCallback);
  3251.   }
  3252. }
  3253.  
  3254. /**
  3255.  * Invoked with the result of a lookupserver request.
  3256.  *
  3257.  * @param request The nsIRequest in which we're interested
  3258.  *
  3259.  * @param trValues Object holding name/value pairs parsed from the
  3260.  *                 lookupserver's response
  3261.  */
  3262. PROT_PhishingWarden.prototype.onTRFetchComplete = function(request,
  3263.                                                            trValues) {
  3264.   var callback = BindToObject(this.houstonWeHaveAProblem_, this, request);
  3265.   this.checkRemoteData(callback, trValues);
  3266. }
  3267.  
  3268. /**
  3269.  * One of our Check* methods found a problem with a request. Why do we
  3270.  * need to keep the nsIRequest (instead of just passing in the URL)? 
  3271.  * Because we need to know when to stop looking for the URL its
  3272.  * fetching, and to know this we need the nsIRequest.isPending flag.
  3273.  *
  3274.  * @param request nsIRequest that is problematic
  3275.  */
  3276. PROT_PhishingWarden.prototype.houstonWeHaveAProblem_ = function(request) {
  3277.  
  3278.   // We have a problem request that might or might not be associated
  3279.   // with a Document that's currently in a browser. If it is, we 
  3280.   // want that Document. If it's not, we want to give it a chance to 
  3281.   // be loaded. See below for complete details.
  3282.  
  3283.   if (this.maybeLocateProblem_(request))       // Cases 1 and 2 (see below)
  3284.     return;
  3285.  
  3286.   // OK, so the request isn't associated with any currently accessible
  3287.   // Document, and we want to give it the chance to be. We don't want
  3288.   // to retry forever (e.g., what if the Document was already displayed
  3289.   // and navigated away from?), so we'll use nsIRequest.isPending to help
  3290.   // us decide what to do.
  3291.   //
  3292.   // Aácomplication arises because there is a lag between when a
  3293.   // request transitions from pending to not-pending and when it's
  3294.   // associated with a Document in a browser. The transition from
  3295.   // pending to not occurs just before the notification corresponding
  3296.   // to NavWatcher.DOCNAVSTART (see NavWatcher), but the association
  3297.   // occurs afterwards. Unfortunately, we're probably in DOCNAVSTART.
  3298.   // 
  3299.   // Diagnosis by Darin:
  3300.   // ---------------------------------------------------------------------------
  3301.   // Here's a summary of what happens:
  3302.   //
  3303.   //   RestorePresentation() {
  3304.   //     Dispatch_OnStateChange(dummy_request, STATE_START)
  3305.   //     PostCompletionEvent()
  3306.   //   }
  3307.   //
  3308.   //   CompletionEvent() {
  3309.   //     ReallyRestorePresentation()
  3310.   //     Dispatch_OnStateChange(dummy_request, STATE_STOP)
  3311.   //   }
  3312.   //
  3313.   // So, now your code receives that initial OnStateChange event and sees
  3314.   // that the dummy_request is not pending and not loaded in any window.
  3315.   // So, you put a timeout(0) event in the queue.  Then, the CompletionEvent
  3316.   // is added to the queue.  The stack unwinds....
  3317.   //
  3318.   // Your timeout runs, and you find that the dummy_request is still not
  3319.   // pending and not loaded in any window.  Then the CompletionEvent
  3320.   // runs, and it hooks up the cached presentation.
  3321.   // 
  3322.   // https://bugzilla.mozilla.org/show_bug.cgi?id=319527
  3323.   // ---------------------------------------------------------------------------
  3324.   //
  3325.   // So the logic is:
  3326.   //
  3327.   //         request     found an unhandled          
  3328.   //  case   pending?    doc with the url?         action
  3329.   //  ----------------------------------------------------------------
  3330.   //   1      yes             yes           Use that doc (handled above)
  3331.   //   2      no              yes           Use that doc (handled above)
  3332.   //   3      yes             no            Retry
  3333.   //   4      no              no            Retry twice (case described above)
  3334.   //
  3335.   // We don't get into trouble with Docs with the same URL "stealing" the 
  3336.   // warning because there is exactly one warning signaled per nav to 
  3337.   // a problem URL, and each Doc can be marked as problematic at most once.
  3338.  
  3339.   if (request.isPending()) {        // Case 3
  3340.  
  3341.     G_Debug(this, "Can't find problem Doc; Req pending. Retrying.");
  3342.     new G_Alarm(BindToObject(this.houstonWeHaveAProblem_, 
  3343.                              this, 
  3344.                              request), 
  3345.                 200 /*ms*/);
  3346.  
  3347.   } else {                          // Case 4
  3348.  
  3349.     G_Debug(this, 
  3350.             "Can't find problem Doc; Req completed. Retrying at most twice.");
  3351.     new G_ConditionalAlarm(BindToObject(this.maybeLocateProblem_, 
  3352.                                         this, 
  3353.                                         request),
  3354.                            0 /* next event loop */, 
  3355.                            true /* repeat */, 
  3356.                            2 /* at most twice */);
  3357.   }
  3358. }
  3359.  
  3360. /**
  3361.  * Query all browser views we know about and offer them the chance to
  3362.  * handle the problematic request.
  3363.  *
  3364.  * @param request nsIRequest that is problematic
  3365.  * 
  3366.  * @returns Boolean indicating if someone decided to handle it
  3367.  */
  3368. PROT_PhishingWarden.prototype.maybeLocateProblem_ = function(request) {
  3369.   G_Debug(this, "Trying to find the problem.");
  3370.  
  3371.   G_Debug(this, this.browserViews_.length + " browser views to check.");
  3372.   for (var i = 0; i < this.browserViews_.length; i++) {
  3373.     if (this.browserViews_[i].tryToHandleProblemRequest(this, request)) {
  3374.       G_Debug(this, "Found browser view willing to handle problem!");
  3375.       return true;
  3376.     }
  3377.     G_Debug(this, "wrong browser view");
  3378.   }
  3379.   return false;
  3380. }
  3381.  
  3382. /**
  3383.  * Indicates if this URL is one of the possible blacklist test URLs.
  3384.  * These test URLs should always be considered as phishy.
  3385.  *
  3386.  * @param url URL to check 
  3387.  * @return A boolean indicating whether this is one of our blacklist
  3388.  *         test URLs
  3389.  */
  3390. PROT_PhishingWarden.prototype.isBlacklistTestURL = function(url) {
  3391.   // Explicitly check for URL so we don't get JS warnings in strict mode.
  3392.   if (kTestUrls[url])
  3393.     return true;
  3394.   return false;
  3395. }
  3396.  
  3397. /**
  3398.  * Check to see if the url is in the blacklist.
  3399.  *
  3400.  * @param url String
  3401.  * @param callback Function
  3402.  */
  3403. PROT_PhishingWarden.prototype.checkUrl_ = function(url, callback) {
  3404.   // First check to see if it's a blacklist url.
  3405.   if (this.isBlacklistTestURL(url)) {
  3406.     callback();
  3407.     return;
  3408.   }
  3409.   this.isEvilURL_(url, callback);
  3410. }
  3411.  
  3412. /**
  3413.  * Callback for found local blacklist match.  First we report that we have
  3414.  * a blacklist hit, then we bring up the warning dialog.
  3415.  */
  3416. PROT_PhishingWarden.prototype.localListMatch_ = function(url, request) {
  3417.   // Maybe send a report
  3418.   (new PROT_Reporter).report("phishblhit", url);
  3419.   this.houstonWeHaveAProblem_(request);
  3420. }
  3421.  
  3422. /**
  3423.  * Examine data fetched from a lookup server for evidence of a
  3424.  * phishing problem. 
  3425.  *
  3426.  * @param callback Function to invoke if there is a problem. 
  3427.  * @param trValues Object containing name/value pairs the server returned
  3428.  */
  3429. PROT_PhishingWarden.prototype.checkRemoteData = function(callback, 
  3430.                                                          trValues) {
  3431.  
  3432.   if (!trValues) {
  3433.     G_Debug(this, "Didn't get TR values from the server.");
  3434.     return;
  3435.   }
  3436.   
  3437.   G_Debug(this, "Page has phishiness " + trValues["phishy"]);
  3438.  
  3439.   if (trValues["phishy"] == 1) {     // It's on our blacklist 
  3440.     G_Debug(this, "Remote blacklist hit");
  3441.     callback(this);
  3442.   } else {
  3443.     G_Debug(this, "Remote blacklist miss");
  3444.   }
  3445. }
  3446. /* ***** BEGIN LICENSE BLOCK *****
  3447.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3448.  *
  3449.  * The contents of this file are subject to the Mozilla Public License Version
  3450.  * 1.1 (the "License"); you may not use this file except in compliance with
  3451.  * the License. You may obtain a copy of the License at
  3452.  * http://www.mozilla.org/MPL/
  3453.  *
  3454.  * Software distributed under the License is distributed on an "AS IS" basis,
  3455.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  3456.  * for the specific language governing rights and limitations under the
  3457.  * License.
  3458.  *
  3459.  * The Original Code is Google Safe Browsing.
  3460.  *
  3461.  * The Initial Developer of the Original Code is Google Inc.
  3462.  * Portions created by the Initial Developer are Copyright (C) 2006
  3463.  * the Initial Developer. All Rights Reserved.
  3464.  *
  3465.  * Contributor(s):
  3466.  *   Fritz Schneider <fritz@google.com> (original author)
  3467.  *
  3468.  * Alternatively, the contents of this file may be used under the terms of
  3469.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  3470.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  3471.  * in which case the provisions of the GPL or the LGPL are applicable instead
  3472.  * of those above. If you wish to allow use of your version of this file only
  3473.  * under the terms of either the GPL or the LGPL, and not to allow others to
  3474.  * use your version of this file under the terms of the MPL, indicate your
  3475.  * decision by deleting the provisions above and replace them with the notice
  3476.  * and other provisions required by the GPL or the LGPL. If you do not delete
  3477.  * the provisions above, a recipient may use your version of this file under
  3478.  * the terms of any one of the MPL, the GPL or the LGPL.
  3479.  *
  3480.  * ***** END LICENSE BLOCK ***** */
  3481.  
  3482.  
  3483. // A tiny class to do reporting for us. We report interesting user actions
  3484. // such as the user hitting a blacklisted page, and the user accepting
  3485. // or declining the warning.
  3486. //
  3487. // Each report has a subject and data. Current reports are:
  3488. //
  3489. // subject         data     meaning
  3490. // --------------------------------
  3491. // phishnavaway    url      the user navigated away from a phishy page
  3492. // phishdecline    url      the user declined our warning
  3493. // phishaccept     url      the user accepted our warning
  3494. // phishblhit      url      the user loaded a phishing page
  3495. //
  3496. // We only send reports in advanced protection mode, and even then we
  3497. // strip cookies from the request before sending it.
  3498.  
  3499. /**
  3500.  * A very complicated class to send pings to the provider. The class does
  3501.  * nothing if we're not in advanced protection mode.
  3502.  *
  3503.  * @constructor
  3504.  */
  3505. function PROT_Reporter() {
  3506.   this.debugZone = "reporter";
  3507.   this.prefs_ = new G_Preferences();
  3508. }
  3509.  
  3510. /**
  3511.  * Send a report!
  3512.  *
  3513.  * @param subject String indicating what this report is about (will be 
  3514.  *                urlencoded)
  3515.  * @param data String giving extra information about this report (will be 
  3516.  *                urlencoded)
  3517.  */
  3518. PROT_Reporter.prototype.report = function(subject, data) {
  3519.   // Send a report iff we're in advanced protection mode
  3520.   if (!this.prefs_.getPref(kPhishWardenRemoteLookups, false))
  3521.     return;
  3522.   // Make sure a report url is defined
  3523.   var url = gDataProvider.getReportURL();
  3524.  
  3525.   // Report url is optional, so we just ignore the request if a report
  3526.   // url isn't provided.
  3527.   if (!url)
  3528.     return;
  3529.  
  3530.   url += "evts=" + encodeURIComponent(subject)
  3531.          + "&evtd=" + encodeURIComponent(data);
  3532.   G_Debug(this, "Sending report: " + url);
  3533.   (new PROT_XMLFetcher(true /* strip cookies */)).get(url, null /* no cb */);
  3534. }
  3535. /* ***** BEGIN LICENSE BLOCK *****
  3536.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3537.  *
  3538.  * The contents of this file are subject to the Mozilla Public License Version
  3539.  * 1.1 (the "License"); you may not use this file except in compliance with
  3540.  * the License. You may obtain a copy of the License at
  3541.  * http://www.mozilla.org/MPL/
  3542.  *
  3543.  * Software distributed under the License is distributed on an "AS IS" basis,
  3544.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  3545.  * for the specific language governing rights and limitations under the
  3546.  * License.
  3547.  *
  3548.  * The Original Code is Google Safe Browsing.
  3549.  *
  3550.  * The Initial Developer of the Original Code is Google Inc.
  3551.  * Portions created by the Initial Developer are Copyright (C) 2006
  3552.  * the Initial Developer. All Rights Reserved.
  3553.  *
  3554.  * Contributor(s):
  3555.  *   Fritz Schneider <fritz@google.com> (original author)
  3556.  *
  3557.  * Alternatively, the contents of this file may be used under the terms of
  3558.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  3559.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  3560.  * in which case the provisions of the GPL or the LGPL are applicable instead
  3561.  * of those above. If you wish to allow use of your version of this file only
  3562.  * under the terms of either the GPL or the LGPL, and not to allow others to
  3563.  * use your version of this file under the terms of the MPL, indicate your
  3564.  * decision by deleting the provisions above and replace them with the notice
  3565.  * and other provisions required by the GPL or the LGPL. If you do not delete
  3566.  * the provisions above, a recipient may use your version of this file under
  3567.  * the terms of any one of the MPL, the GPL or the LGPL.
  3568.  *
  3569.  * ***** END LICENSE BLOCK ***** */
  3570.  
  3571.  
  3572. // A helper class that does "trustrank" lookups on a remote
  3573. // server. Right now this lookup just indicates if a page is
  3574. // phishing. The response format is protocol4 name/value pairs.
  3575. // 
  3576. // Since we're sending full URLs to the server, we try to encrypt
  3577. // them before transmission. Else HTTPS query params could leak.
  3578.  
  3579. /**
  3580.  * A helper class that fetches trustrank values, parses them, and
  3581.  * passes them via an object to a callback.
  3582.   * 
  3583.  * @constructor
  3584.  */
  3585. function PROT_TRFetcher(opt_noCrypto) {
  3586.   this.debugZone = "trfetcher";
  3587.   this.useCrypto_ = !opt_noCrypto;
  3588.   this.protocol4Parser_ = new G_Protocol4Parser();
  3589.  
  3590.   // We lazily instantiate the UrlCrypto object due to:
  3591.   // https://bugzilla.mozilla.org/show_bug.cgi?id=321024
  3592.   //
  3593.   // Otherwise here we would use:
  3594.   // this.urlCrypto_ = new PROT_UrlCrypto();
  3595. }
  3596.  
  3597. PROT_TRFetcher.TRY_REKEYING_RESPONSE = "pleaserekey";
  3598.  
  3599. /**
  3600.  * Query params we'll send. Don't touch unless you know what you're
  3601.  * doing and are prepared to carefully test. 
  3602.  */
  3603. PROT_TRFetcher.prototype.extraQueryParams = {
  3604.   sourceid: "firefox-antiphish",
  3605.   features: "TrustRank",
  3606.   client: "navclient-auto-ffox2"
  3607. };
  3608.  
  3609. /**
  3610.  * Get the URL of the request that will fetch us TR for the argument URL
  3611.  *
  3612.  * @param url String containing the URL we'd like to fetch info about
  3613.  *
  3614.  * @returns String containing the url we should use to fetch tr info
  3615.  */
  3616. PROT_TRFetcher.prototype.getRequestURL_ = function(url) {
  3617.  
  3618.   if (!this.urlCrypto_)
  3619.     this.urlCrypto_ = new PROT_UrlCrypto();
  3620.  
  3621.   G_Debug(this, "Fetching for " + url);
  3622.     
  3623.   var requestURL = gDataProvider.getLookupURL();
  3624.   if (!requestURL)
  3625.     return null;
  3626.  
  3627.   for (var param in this.extraQueryParams) 
  3628.     requestURL += param + "=" + this.extraQueryParams[param] + "&";
  3629.  
  3630.   if (this.useCrypto_) {
  3631.     var maybeCryptedParams = this.urlCrypto_.maybeCryptParams({ "q": url});
  3632.     
  3633.     for (var param in maybeCryptedParams) 
  3634.       requestURL += param + "=" + 
  3635.                     encodeURIComponent(maybeCryptedParams[param]) + "&";
  3636.   } else {
  3637.     requestURL += "q=" + encodeURIComponent(url);
  3638.   }
  3639.  
  3640.   G_Debug(this, "Request URL: " + requestURL);
  3641.  
  3642.   return requestURL;
  3643. };
  3644.  
  3645. /**
  3646.  * Fetches information about a page.
  3647.  * 
  3648.  * @param forPage URL for which to fetch info
  3649.  *
  3650.  * @param callback Function to call back when complete.
  3651.  */
  3652. PROT_TRFetcher.prototype.get = function(forPage, callback) {
  3653.   
  3654.   var url = this.getRequestURL_(forPage);
  3655.   if (!url) {
  3656.     G_Debug(this, "No remote lookup url.");
  3657.     return;
  3658.   }
  3659.   var closure = BindToObject(this.onFetchComplete_, this, callback);
  3660.   (new PROT_XMLFetcher()).get(url, closure);
  3661. };
  3662.  
  3663. /**
  3664.  * Invoked when a fetch has completed.
  3665.  *
  3666.  * @param callback Function to invoke with parsed response object
  3667.  *
  3668.  * @param responseText Text of the protocol4 message
  3669.  */
  3670. PROT_TRFetcher.prototype.onFetchComplete_ = function(callback, responseText) {
  3671.   var responseObj = this.extractResponse_(responseText);
  3672.  
  3673.   // The server might tell us to rekey, for example if it sees that
  3674.   // our request was unencrypted (meaning that we might not yet have
  3675.   // a key). If so, pass this hint along to the crypto key manager.
  3676.  
  3677.   if (responseObj[PROT_TRFetcher.TRY_REKEYING_RESPONSE] == "1" &&
  3678.       this.urlCrypto_) {
  3679.     G_Debug(this, "We're supposed to re-key. Trying.");
  3680.     var manager = this.urlCrypto_.getManager();
  3681.     if (manager)
  3682.       manager.maybeReKey();
  3683.   }
  3684.  
  3685.   G_Debug(this, "TR Response:");
  3686.   for (var field in responseObj)
  3687.     G_Debug(this, field + "=" + responseObj[field]);
  3688.  
  3689.   callback(responseObj);
  3690. };
  3691.  
  3692. /**
  3693.  * Parse a protocol4 message (lookup server response)
  3694.  * 
  3695.  * @param responseText String containing the server's response
  3696.  *
  3697.  * @returns Object containing the returned values or null if no
  3698.  *          response was received
  3699.  */
  3700. PROT_TRFetcher.prototype.extractResponse_ = function(responseText) {
  3701.   return this.protocol4Parser_.parse(responseText);
  3702. };
  3703.  
  3704. //@line 27 "/build/buildd/firefox-1.99+2.0b1+dfsg/browser/components/safebrowsing/src/nsSafebrowsingApplication.js"
  3705.  
  3706. var modScope = this;
  3707. function Init() {
  3708.   var jslib = Cc["@mozilla.org/url-classifier/jslib;1"]
  3709.               .getService().wrappedJSObject;
  3710.   modScope.String.prototype.startsWith = jslib.String.prototype.startsWith;
  3711.   modScope.G_Debug = jslib.G_Debug;
  3712.   modScope.G_Assert = jslib.G_Assert;
  3713.   modScope.G_Alarm = jslib.G_Alarm;
  3714.   modScope.G_ConditionalAlarm = jslib.G_ConditionalAlarm;
  3715.   modScope.G_ObserverWrapper = jslib.G_ObserverWrapper;
  3716.   modScope.G_Preferences = jslib.G_Preferences;
  3717.   modScope.PROT_XMLFetcher = jslib.PROT_XMLFetcher;
  3718.   modScope.BindToObject = jslib.BindToObject;
  3719.   modScope.G_Protocol4Parser = jslib.G_Protocol4Parser;
  3720.   modScope.G_ObjectSafeMap = jslib.G_ObjectSafeMap;
  3721.   modScope.PROT_UrlCrypto = jslib.PROT_UrlCrypto;
  3722.   
  3723.   // We only need to call Init once
  3724.   modScope.Init = function() {};
  3725. }
  3726.  
  3727. // Module object
  3728. function SafebrowsingApplicationMod() {
  3729.   this.firstTime = true;
  3730.   this.cid = Components.ID("{c64d0bcb-8270-4ca7-a0b3-3380c8ffecb5}");
  3731.   this.progid = "@mozilla.org/safebrowsing/application;1";
  3732. }
  3733.  
  3734. SafebrowsingApplicationMod.prototype.registerSelf = function(compMgr, fileSpec, loc, type) {
  3735.   if (this.firstTime) {
  3736.     this.firstTime = false;
  3737.     throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  3738.   }
  3739.   compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
  3740.   compMgr.registerFactoryLocation(this.cid,
  3741.                                   "Safebrowsing Application Module",
  3742.                                   this.progid,
  3743.                                   fileSpec,
  3744.                                   loc,
  3745.                                   type);
  3746. };
  3747.  
  3748. SafebrowsingApplicationMod.prototype.getClassObject = function(compMgr, cid, iid) {  
  3749.   if (!cid.equals(this.cid))
  3750.     throw Components.results.NS_ERROR_NO_INTERFACE;
  3751.   if (!iid.equals(Ci.nsIFactory))
  3752.     throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  3753.  
  3754.   return this.factory;
  3755. }
  3756.  
  3757. SafebrowsingApplicationMod.prototype.canUnload = function(compMgr) {
  3758.   return true;
  3759. }
  3760.  
  3761. SafebrowsingApplicationMod.prototype.factory = {
  3762.   createInstance: function(outer, iid) {
  3763.     if (outer != null)
  3764.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  3765.     Init();
  3766.     return new PROT_Application();
  3767.   }
  3768. };
  3769.  
  3770. var ApplicationModInst = new SafebrowsingApplicationMod();
  3771.  
  3772. function NSGetModule(compMgr, fileSpec) {
  3773.   return ApplicationModInst;
  3774. }
  3775.