home *** CD-ROM | disk | FTP | other *** search
/ Chip 2008 June / CHIP-2008-06.iso / bonus / +10SecurityTips / files / xB-Browser_2.0.0.12b.exe / App / Browser / firefox / components / nsSafebrowsingApplication.js < prev    next >
Encoding:
Text File  |  2008-02-02  |  142.4 KB  |  3,986 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 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/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 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/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.   return gDataProvider.getReportPhishURL();
  950. }
  951. /* ***** BEGIN LICENSE BLOCK *****
  952.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  953.  *
  954.  * The contents of this file are subject to the Mozilla Public License Version
  955.  * 1.1 (the "License"); you may not use this file except in compliance with
  956.  * the License. You may obtain a copy of the License at
  957.  * http://www.mozilla.org/MPL/
  958.  *
  959.  * Software distributed under the License is distributed on an "AS IS" basis,
  960.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  961.  * for the specific language governing rights and limitations under the
  962.  * License.
  963.  *
  964.  * The Original Code is Google Safe Browsing.
  965.  *
  966.  * The Initial Developer of the Original Code is Google Inc.
  967.  * Portions created by the Initial Developer are Copyright (C) 2006
  968.  * the Initial Developer. All Rights Reserved.
  969.  *
  970.  * Contributor(s):
  971.  *   Fritz Schneider <fritz@google.com> (original author)
  972.  *
  973.  * Alternatively, the contents of this file may be used under the terms of
  974.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  975.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  976.  * in which case the provisions of the GPL or the LGPL are applicable instead
  977.  * of those above. If you wish to allow use of your version of this file only
  978.  * under the terms of either the GPL or the LGPL, and not to allow others to
  979.  * use your version of this file under the terms of the MPL, indicate your
  980.  * decision by deleting the provisions above and replace them with the notice
  981.  * and other provisions required by the GPL or the LGPL. If you do not delete
  982.  * the provisions above, a recipient may use your version of this file under
  983.  * the terms of any one of the MPL, the GPL or the LGPL.
  984.  *
  985.  * ***** END LICENSE BLOCK ***** */
  986.  
  987. // There is one BrowserView per browser window, and each BrowserView
  988. // is responsible for keeping track of problems (phishy documents)
  989. // within that window. The BrowserView is also responsible for
  990. // figuring out what to do about such problems, for example, whether
  991. // the tab with a phishy page is currently showing and therefore if we
  992. // should be showing a warning.
  993. // 
  994. // The BrowserView receives information from three places:
  995. //
  996. // - from the phishing warden. When the phishing warden notices a
  997. //   problem, it queries all browser views to see which one (if any)
  998. //   has the Document that is problematic. It then hands the problem
  999. //   off to the appropriate BrowserView.
  1000. // 
  1001. // - from the controller. The controller responds to explicit user 
  1002. //   actions (tab switches, requests to hide the warning message, 
  1003. //   etc.) and let's the BrowserView know about any user action 
  1004. //   having to do with the problems it is tracking.
  1005. //
  1006. // - from the TabbedBrowserWatcher. When the BrowserView is keeping
  1007. //   track of a problematic document it listens for interesting
  1008. //   events affecting it, for example pagehide (at which point
  1009. //   we presumably hide the warning if we're showing it).
  1010. //
  1011. // The BrowserView associates at most one "problem" with each Document
  1012. // in the browser window. It keeps state about which Documents are 
  1013. // problematic by storing a "problem queue" on each browser (tab).
  1014. // At most one problematic document per browser (tab) is active
  1015. // at any time. That is, we show the warning for at most one phishy
  1016. // document at any one time. If another phishy doc loads in that tab,
  1017. // it goes onto the end of the queue to be activated only when the
  1018. // currently active document goes away.
  1019. //
  1020. // If we had multiple types of warnings (one for after the page had
  1021. // loaded, one for when the user clicked a link, etc) here's where
  1022. // we'd select the appropate one to use. As it stands, we only have
  1023. // one displayer (an "afterload" displayer). A displayer knows _how_
  1024. // to display a warning, whereas as the BrowserView knows _what_ and
  1025. // _when_.
  1026. //
  1027. // To keep things (relatively) easy to reason about and efficient (the
  1028. // phishwarden could be querying us inside a progresslistener
  1029. // notification, or the controller inside an event handler), we have
  1030. // the following rules:
  1031. //
  1032. // - at most one of a displayer's start() or stop() methods is called
  1033. //   in any iteration (if calling two is required, the second is run in 
  1034. //   the next event loop)
  1035. // - displayers should run their operations synchronously so we don't have
  1036. //   to look two places (here and in the displayer) to see what is happening 
  1037. //   when
  1038. // - displayer actions are run after cleaning up the browser view state
  1039. //   in case they have consequences
  1040. //
  1041. // TODO: this could use some redesign, but I don't have time.
  1042. // TODO: the queue needs to be abstracted, but we want another release fast,
  1043. //       so I'm not going to touch it for the time being
  1044. // TODO: IDN issues and canonical URLs?
  1045. // TODO: Perhaps we should blur the page before showing a warning in order
  1046. //       to prevent stray keystrokes?
  1047.  
  1048. /**
  1049.  * The BrowerView is responsible for keeping track of and figuring out
  1050.  * what to do with problems within a single browser window.
  1051.  * 
  1052.  * TODO 
  1053.  * Unify all browser-related state here. Currently it's split
  1054.  * between two objects, this object and the controller. We could have
  1055.  * this object be solely responsible for UI hide/show decisions, which
  1056.  * would probably make it easier to reason about what's going on.
  1057.  * 
  1058.  * TODO 
  1059.  * Investigate an alternative model. For example, we could factor out
  1060.  * the problem signaling stuff from the tab/UI logic into a
  1061.  * ProblemRegistry. Attach listeners to new docs/requests as they go
  1062.  * by and have these listeners periodically check in with a
  1063.  * ProblemRegistry to see if they're watching a problematic
  1064.  * doc/request. If so, then have them flag the browser view to be
  1065.  * aware of the problem.
  1066.  *
  1067.  * @constructor
  1068.  * @param tabWatcher Reference to the TabbedBrowserWatcher we'll use to query 
  1069.  *                   for information about active tabs/browsers.
  1070.  * @param doc Reference to the XUL Document (browser window) in which the 
  1071.  *            tabwatcher is watching
  1072.  */ 
  1073. function PROT_BrowserView(tabWatcher, doc) {
  1074.   this.debugZone = "browserview";
  1075.   this.tabWatcher_ = tabWatcher;
  1076.   this.doc_ = doc;
  1077. }
  1078.  
  1079. /**
  1080.  * See if we have any Documents with a given (problematic) URL that
  1081.  * haven't yet been marked as problems. Called as a subroutine by
  1082.  * tryToHandleProblemRequest().
  1083.  *
  1084.  * @param url String containing the URL to look for
  1085.  *
  1086.  * @returns Reference to an unhandled Document with the problem URL or null
  1087.  */
  1088. PROT_BrowserView.prototype.getFirstUnhandledDocWithURL_ = function(url) {
  1089.   var docs = this.tabWatcher_.getDocumentsFromURL(url);
  1090.   if (!docs.length)
  1091.     return null;
  1092.  
  1093.   for (var i = 0; i < docs.length; i++) {
  1094.     // We only care about top level documents (i.e., we don't care about
  1095.     // frames).
  1096.     if (docs[i].defaultView.top != docs[i].defaultView)
  1097.       continue;
  1098.  
  1099.     var browser = this.tabWatcher_.getBrowserFromDocument(docs[i]);
  1100.     G_Assert(this, !!browser, "Found doc but can't find browser???");
  1101.     var alreadyHandled = this.getProblem_(docs[i], browser);
  1102.  
  1103.     if (!alreadyHandled)
  1104.       return docs[i];
  1105.   }
  1106.   return null;
  1107. }
  1108.  
  1109. /**
  1110.  * Invoked by the warden to give us the opportunity to handle a
  1111.  * problem.  A problem is signaled once per request for a problem
  1112.  * Document and is handled at most once, so there's no issue with us
  1113.  * "losing" a problem due to multiple concurrently loading Documents
  1114.  * with the same URL.
  1115.  *
  1116.  * @param warden Reference to the warden signalling the problem. We'll
  1117.  *               need him to instantiate one of his warning displayers
  1118.  * 
  1119.  * @param request The nsIRequest that is problematic
  1120.  *
  1121.  * @returns Boolean indicating whether we handled problem
  1122.  */
  1123. PROT_BrowserView.prototype.tryToHandleProblemRequest = function(warden,
  1124.                                                                 request) {
  1125.  
  1126.   var doc = this.getFirstUnhandledDocWithURL_(request.name);
  1127.   if (doc) {
  1128.     var browser = this.tabWatcher_.getBrowserFromDocument(doc);
  1129.     G_Assert(this, !!browser, "Couldn't get browser from problem doc???");
  1130.     G_Assert(this, !this.getProblem_(doc, browser),
  1131.              "Doc is supposedly unhandled, but has state?");
  1132.     
  1133.     this.isProblemDocument_(browser, doc, warden);
  1134.     return true;
  1135.   }
  1136.   return false;
  1137. }
  1138.  
  1139. /**
  1140.  * We're sure a particular Document is problematic, so let's instantiate
  1141.  * a dispalyer for it and add it to the problem queue for the browser.
  1142.  *
  1143.  * @param browser Reference to the browser in which the problem doc resides
  1144.  *
  1145.  * @param doc Reference to the problematic document
  1146.  * 
  1147.  * @param warden Reference to the warden signalling the problem.
  1148.  */
  1149. PROT_BrowserView.prototype.isProblemDocument_ = function(browser, 
  1150.                                                          doc, 
  1151.                                                          warden) {
  1152.  
  1153.   G_Debug(this, "Document is problem: " + doc.location.href);
  1154.  
  1155.   var url = doc.location.href;
  1156.  
  1157.   // We only have one type of displayer right now
  1158.   var displayer = new warden.displayers_["afterload"]("Phishing afterload",
  1159.                                                       browser,
  1160.                                                       this.doc_,
  1161.                                                       url);
  1162.  
  1163.   // We listen for the problematic document being navigated away from
  1164.   // so we can remove it from the problem queue
  1165.  
  1166.   var hideHandler = BindToObject(this.onNavAwayFromProblem_, 
  1167.                                  this, 
  1168.                                  doc, 
  1169.                                  browser);
  1170.   doc.defaultView.addEventListener("pagehide", hideHandler, true);
  1171.  
  1172.   // More info than we technically need, but it comes in handy for debugging
  1173.   var problem = {
  1174.     "browser_": browser,
  1175.     "doc_": doc,
  1176.     "displayer_": displayer,
  1177.     "url_": url,
  1178.     "hideHandler_": hideHandler,
  1179.   };
  1180.   var numInQueue = this.queueProblem_(browser, problem);
  1181.  
  1182.   // If the queue was empty, schedule us to take something out
  1183.   if (numInQueue == 1)
  1184.     new G_Alarm(BindToObject(this.unqueueNextProblem_, this, browser), 0);
  1185. }
  1186.  
  1187. /**
  1188.  * Invoked when a problematic document is navigated away from. 
  1189.  *
  1190.  * @param doc Reference to the problematic Document navigated away from
  1191.  
  1192.  * @param browser Reference to the browser in which the problem document
  1193.  *                unloaded
  1194.  */
  1195. PROT_BrowserView.prototype.onNavAwayFromProblem_ = function(doc, browser) {
  1196.  
  1197.   G_Debug(this, "User nav'd away from problem.");
  1198.   var problem = this.getProblem_(doc, browser);
  1199.   (new PROT_Reporter).report("phishnavaway", problem.url_);
  1200.  
  1201.   G_Assert(this, doc === problem.doc_, "State doc not equal to nav away doc?");
  1202.   G_Assert(this, browser === problem.browser_, 
  1203.            "State browser not equal to nav away browser?");
  1204.   
  1205.   this.problemResolved(browser, doc);
  1206. }
  1207.  
  1208. /**
  1209.  * @param browser Reference to a browser we'd like to know about
  1210.  * 
  1211.  * @returns Boolean indicating if the browser in question has 
  1212.  *          problematic content
  1213.  */
  1214. PROT_BrowserView.prototype.hasProblem = function(browser) {
  1215.   return this.hasNonemptyProblemQueue_(browser);
  1216. }
  1217.  
  1218. /**
  1219.  * @param browser Reference to a browser we'd like to know about
  1220.  *
  1221.  * @returns Boolean indicating if the browser in question has a
  1222.  *          problem (i.e., it has a non-empty problem queue)
  1223.  */
  1224. PROT_BrowserView.prototype.hasNonemptyProblemQueue_ = function(browser) {
  1225.   try {
  1226.     return !!browser.PROT_problemState__ && 
  1227.       !!browser.PROT_problemState__.length;
  1228.   } catch(e) {
  1229.     // We could be checking a browser that has just been closed, in
  1230.     // which case its properties will not be valid, causing the above
  1231.     // statement to throw an error. Since this case handled elsewhere,
  1232.     // just return false.
  1233.     return false;
  1234.   }
  1235. }
  1236.  
  1237. /**
  1238.  * Invoked to indicate that the problem for a particular problematic
  1239.  * document in a browser has been resolved (e.g., by being navigated
  1240.  * away from).
  1241.  *
  1242.  * @param browser Reference to the browser in which resolution is happening
  1243.  *
  1244.  * @param opt_doc Reference to the problematic doc whose problem was resolved
  1245.  *                (if absent, assumes the doc assocaited with the currently
  1246.  *                active displayer)
  1247.  */
  1248. PROT_BrowserView.prototype.problemResolved = function(browser, opt_doc) {
  1249.   var problem;
  1250.   var doc;
  1251.   if (!!opt_doc) {
  1252.     doc = opt_doc;
  1253.     problem = this.getProblem_(doc, browser);
  1254.   } else {
  1255.     problem = this.getCurrentProblem_(browser);
  1256.     doc = problem.doc_;
  1257.   }
  1258.  
  1259.   problem.displayer_.done();
  1260.   var wasHead = this.deleteProblemFromQueue_(doc, browser);
  1261.  
  1262.   // Peek at the next problem (if any) in the queue for this browser
  1263.   var queueNotEmpty = this.getCurrentProblem_(browser);
  1264.  
  1265.   if (wasHead && queueNotEmpty) {
  1266.     G_Debug(this, "More problems pending. Scheduling unqueue.");
  1267.     new G_Alarm(BindToObject(this.unqueueNextProblem_, this, browser), 0);
  1268.   }
  1269. }
  1270.  
  1271. /**
  1272.  * Peek at the top of the problem queue and if there's something there,
  1273.  * make it active. 
  1274.  *
  1275.  * @param browser Reference to the browser we should activate a problem
  1276.  *                displayer in if one is available
  1277.  */
  1278. PROT_BrowserView.prototype.unqueueNextProblem_ = function(browser) {
  1279.   var problem = this.getCurrentProblem_(browser);
  1280.   if (!problem) {
  1281.     G_Debug(this, "No problem in queue; doc nav'd away from? (shrug)");
  1282.     return;
  1283.   }
  1284.  
  1285.   // Two problem docs that load in rapid succession could both schedule 
  1286.   // themselves to be unqueued before this method is called. So ensure 
  1287.   // that the problem at the head of the queue is not, in fact, active.
  1288.   if (!problem.displayer_.isActive()) {
  1289.     problem.displayer_.start();
  1290.  
  1291.     // Due to a bfcache bug, if we show the warning during paint
  1292.     // suppression, the collapsing of the content pane affects the doc we're
  1293.     // naving from :( The symptom is a page with grey screen on navigation
  1294.     // to or from a phishing page (the contentDocument will have width
  1295.     // zero).
  1296.     //
  1297.     // Paint supression lasts at most 250ms from when the parser sees
  1298.     // the body, and the parser sees the body well before it has a
  1299.     // height. We err on the side of caution.
  1300.     //
  1301.     // Thanks to bryner for helping to track the bfcache bug down.
  1302.     // https://bugzilla.mozilla.org/show_bug.cgi?id=319646
  1303.     
  1304.     if (this.tabWatcher_.getCurrentBrowser() === browser)
  1305.       new G_Alarm(BindToObject(this.problemBrowserMaybeSelected, 
  1306.                                this, 
  1307.                                browser),
  1308.                   350 /*ms*/);
  1309.   }
  1310. }
  1311.  
  1312. /**
  1313.  * Helper function that adds a new problem to the queue of problems pending
  1314.  * on this browser.
  1315.  *
  1316.  * @param browser Browser to which we should add state
  1317.  *
  1318.  * @param problem Object (structure, really) encapsulating the problem
  1319.  *
  1320.  * @returns Number indicating the number of items in the queue (and from
  1321.  *          which you can infer whether the recently added item was
  1322.  *          placed at the head, and hence should be active.
  1323.  */
  1324. PROT_BrowserView.prototype.queueProblem_ = function(browser, problem) {
  1325.   G_Debug(this, "Adding problem state for " + problem.url_);
  1326.  
  1327.   if (this.hasNonemptyProblemQueue_(browser))
  1328.     G_Debug(this, "Already has problem state. Queueing this problem...");
  1329.  
  1330.   // First problem ever signaled on this browser? Make a new queue!
  1331.   if (browser.PROT_problemState__ == undefined)
  1332.     browser.PROT_problemState__ = [];
  1333.  
  1334.   browser.PROT_problemState__.push(problem);
  1335.   return browser.PROT_problemState__.length;
  1336. }
  1337.  
  1338. /**
  1339.  * Helper function that removes a problem from the queue and deactivates
  1340.  * it.
  1341.  *
  1342.  * @param doc Reference to the doc for which we should remove state
  1343.  *
  1344.  * @param browser Reference to the browser from which we should remove
  1345.  *                state
  1346.  *
  1347.  * @returns Boolean indicating if the remove problem was currently active
  1348.  *          (that is, if it was at the head of the queue)
  1349.  */
  1350. PROT_BrowserView.prototype.deleteProblemFromQueue_ = function(doc, browser) {
  1351.   G_Debug(this, "Deleting problem state for " + browser);
  1352.   G_Assert(this, !!this.hasNonemptyProblemQueue_(browser),
  1353.            "Browser has no problem state");
  1354.  
  1355.   var problem = this.getProblem_(doc, browser);
  1356.   G_Assert(this, !!problem, "Couldnt find state in removeproblemstate???");
  1357.  
  1358.   var wasHead = browser.PROT_problemState__[0] === problem;
  1359.   this.removeProblemFromQueue_(doc, browser);
  1360.  
  1361.   var hideHandler = problem.hideHandler_;
  1362.   G_Assert(this, !!hideHandler, "No hidehandler in state?");
  1363.   problem.doc_.defaultView.removeEventListener("pagehide",
  1364.                                                hideHandler,
  1365.                                                true);
  1366.   return wasHead;
  1367. }
  1368.  
  1369. /**
  1370.  * Helper function that removes a problem from the queue but does 
  1371.  * NOT deactivate it.
  1372.  *
  1373.  * @param doc Reference to the doc for which we should remove state
  1374.  *
  1375.  * @param browser Reference to the browser from which we should remove
  1376.  *                state
  1377.  *
  1378.  * @returns Boolean indicating if the remove problem was currently active
  1379.  *          (that is, if it was at the head of the queue)
  1380.  */
  1381. PROT_BrowserView.prototype.removeProblemFromQueue_ = function(doc, browser) {
  1382.   G_Debug(this, "Removing problem state for " + browser);
  1383.   G_Assert(this, !!this.hasNonemptyProblemQueue_(browser),
  1384.            "Browser has no problem state");
  1385.  
  1386.   var problem = null;
  1387.   // TODO Blech. Let's please have an abstraction here instead.
  1388.   for (var i = 0; i < browser.PROT_problemState__.length; i++)
  1389.     if (browser.PROT_problemState__[i].doc_ === doc) {
  1390.       problem = browser.PROT_problemState__.splice(i, 1)[0];
  1391.       break;
  1392.     }
  1393.   return problem;
  1394. }
  1395.  
  1396. /**
  1397.  * Retrieve (but do not remove) the problem state for a particular
  1398.  * problematic Document in this browser
  1399.  *
  1400.  * @param doc Reference to the problematic doc to get state for
  1401.  *
  1402.  * @param browser Reference to the browser from which to get state
  1403.  *
  1404.  * @returns Object encapsulating the state we stored, or null if none
  1405.  */
  1406. PROT_BrowserView.prototype.getProblem_ = function(doc, browser) {
  1407.   if (!this.hasNonemptyProblemQueue_(browser))
  1408.     return null;
  1409.  
  1410.   // TODO Blech. Let's please have an abstraction here instead.
  1411.   for (var i = 0; i < browser.PROT_problemState__.length; i++)
  1412.     if (browser.PROT_problemState__[i].doc_ === doc)
  1413.       return browser.PROT_problemState__[i];
  1414.   return null;
  1415. }
  1416.  
  1417. /**
  1418.  * Retrieve the problem state for the currently active problem Document 
  1419.  * in this browser
  1420.  *
  1421.  * @param browser Reference to the browser from which to get state
  1422.  *
  1423.  * @returns Object encapsulating the state we stored, or null if none
  1424.  */
  1425. PROT_BrowserView.prototype.getCurrentProblem_ = function(browser) {
  1426.   return browser.PROT_problemState__[0];
  1427. }
  1428.  
  1429. /**
  1430.  * Invoked by the controller when the user switches tabs away from a problem 
  1431.  * tab. 
  1432.  *
  1433.  * @param browser Reference to the tab that was switched from
  1434.  */
  1435. PROT_BrowserView.prototype.problemBrowserUnselected = function(browser) {
  1436.   var problem = this.getCurrentProblem_(browser);
  1437.   G_Assert(this, !!problem, "Couldn't get state from browser");
  1438.   problem.displayer_.browserUnselected();
  1439. }
  1440.  
  1441. /**
  1442.  * Checks to see if the problem browser is selected, and if so, 
  1443.  * tell it it to show its warning.
  1444.  *
  1445.  * @param browser Reference to the browser we wish to check
  1446.  */
  1447. PROT_BrowserView.prototype.problemBrowserMaybeSelected = function(browser) {
  1448.   var problem = this.getCurrentProblem_(browser);
  1449.  
  1450.   if (this.tabWatcher_.getCurrentBrowser() === browser &&
  1451.       problem &&
  1452.       problem.displayer_.isActive()) 
  1453.     this.problemBrowserSelected(browser);
  1454. }
  1455.  
  1456. /**
  1457.  * Invoked by the controller when the user switches tabs to a problem tab
  1458.  *
  1459.  * @param browser Reference to the tab that was switched to
  1460.  */
  1461. PROT_BrowserView.prototype.problemBrowserSelected = function(browser) {
  1462.   G_Debug(this, "Problem browser selected");
  1463.   var problem = this.getCurrentProblem_(browser);
  1464.   G_Assert(this, !!problem, "No state? But we're selected!");
  1465.   problem.displayer_.browserSelected();
  1466. }
  1467.  
  1468. /**
  1469.  * Invoked by the controller when the user accepts our warning. Passes
  1470.  * the accept through to the message displayer, which knows what to do
  1471.  * (it will be displayer-specific).
  1472.  *
  1473.  * @param browser Reference to the browser for which the user accepted
  1474.  *                our warning
  1475.  */
  1476. PROT_BrowserView.prototype.acceptAction = function(browser) {
  1477.   var problem = this.getCurrentProblem_(browser);
  1478.  
  1479.   // We run the action only after we're completely through processing
  1480.   // this event. We do this because the action could cause state to be
  1481.   // cleared (e.g., by navigating the problem document) that we need
  1482.   // to finish processing the event.
  1483.  
  1484.   new G_Alarm(BindToObject(problem.displayer_.acceptAction, 
  1485.                            problem.displayer_), 
  1486.               0);
  1487. }
  1488.  
  1489. /**
  1490.  * Invoked by the controller when the user declines our
  1491.  * warning. Passes the decline through to the message displayer, which
  1492.  * knows what to do (it will be displayer-specific).
  1493.  *
  1494.  * @param browser Reference to the browser for which the user declined
  1495.  *                our warning
  1496.  */
  1497. PROT_BrowserView.prototype.declineAction = function(browser) {
  1498.   var problem = this.getCurrentProblem_(browser);
  1499.   G_Assert(this, !!problem, "User declined but no state???");
  1500.  
  1501.   // We run the action only after we're completely through processing
  1502.   // this event. We do this because the action could cause state to be
  1503.   // cleared (e.g., by navigating the problem document) that we need
  1504.   // to finish processing the event.
  1505.  
  1506.   new G_Alarm(BindToObject(problem.displayer_.declineAction, 
  1507.                            problem.displayer_), 
  1508.               0);
  1509. }
  1510.  
  1511. /**
  1512.  * The user wants to see the warning message. So let em! At some point when
  1513.  * we have multiple types of warnings, we'll have to mediate them here.
  1514.  *
  1515.  * @param browser Reference to the browser that has the warning the user 
  1516.  *                wants to see. 
  1517.  */
  1518. PROT_BrowserView.prototype.explicitShow = function(browser) {
  1519.   var problem = this.getCurrentProblem_(browser);
  1520.   G_Assert(this, !!problem, "Explicit show on browser w/o problem state???");
  1521.   problem.displayer_.explicitShow();
  1522. }
  1523. /* ***** BEGIN LICENSE BLOCK *****
  1524.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1525.  *
  1526.  * The contents of this file are subject to the Mozilla Public License Version
  1527.  * 1.1 (the "License"); you may not use this file except in compliance with
  1528.  * the License. You may obtain a copy of the License at
  1529.  * http://www.mozilla.org/MPL/
  1530.  *
  1531.  * Software distributed under the License is distributed on an "AS IS" basis,
  1532.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1533.  * for the specific language governing rights and limitations under the
  1534.  * License.
  1535.  *
  1536.  * The Original Code is Google Safe Browsing.
  1537.  *
  1538.  * The Initial Developer of the Original Code is Google Inc.
  1539.  * Portions created by the Initial Developer are Copyright (C) 2006
  1540.  * the Initial Developer. All Rights Reserved.
  1541.  *
  1542.  * Contributor(s):
  1543.  *   Fritz Schneider <fritz@google.com> (original author)
  1544.  *
  1545.  * Alternatively, the contents of this file may be used under the terms of
  1546.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1547.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1548.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1549.  * of those above. If you wish to allow use of your version of this file only
  1550.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1551.  * use your version of this file under the terms of the MPL, indicate your
  1552.  * decision by deleting the provisions above and replace them with the notice
  1553.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1554.  * the provisions above, a recipient may use your version of this file under
  1555.  * the terms of any one of the MPL, the GPL or the LGPL.
  1556.  *
  1557.  * ***** END LICENSE BLOCK ***** */
  1558.  
  1559.  
  1560. // This is our controller -- the thingy that listens to what the user
  1561. // is doing. There is one controller per browser window, and each has
  1562. // a BrowserView that manages information about problems within the
  1563. // window. The controller figures out when the browser might want to
  1564. // know about something, but the browser view figures out what exactly
  1565. // to do (and the BrowserView's displayer figures out how to do it).
  1566. //
  1567. // For example, the controller might notice that the user has switched
  1568. // to a tab that has something problematic in it. It would tell its 
  1569. // BrowserView this, and the BrowserView would figure out whether it 
  1570. // is appropriate to show a warning (e.g., perhaps the user previously
  1571. // dismissed the warning for that problem). If so, the BrowserView tells
  1572. // the displayer to show the warning. Anyhoo...
  1573. //
  1574. // TODO Could move all browser-related hide/show logic into the browser
  1575. //      view. Need to think about this more.
  1576.  
  1577. /**
  1578.  * Handles user actions, translating them into messages to the view
  1579.  *
  1580.  * @constructor
  1581.  * @param win Reference to the Window (browser window context) we should
  1582.  *            attach to
  1583.  * @param tabWatcher  Reference to the TabbedBrowserWatcher object 
  1584.  *                    the controller should use to receive events about tabs.
  1585.  * @param phishingWarden Reference to the PhishingWarden we should register
  1586.  *                       our browserview with
  1587.  */
  1588. function PROT_Controller(win, tabWatcher, phishingWarden) {
  1589.   this.debugZone = "controller";
  1590.  
  1591.   this.win_ = win;
  1592.   this.phishingWarden_ = phishingWarden;
  1593.  
  1594.   // Use this to query preferences
  1595.   this.prefs_ = new G_Preferences();
  1596.  
  1597.   // Set us up to receive the events we want.
  1598.   this.tabWatcher_ = tabWatcher;
  1599.   this.onTabSwitchCallback_ = BindToObject(this.onTabSwitch, this);
  1600.   this.tabWatcher_.registerListener("tabswitch",
  1601.                                     this.onTabSwitchCallback_);
  1602.  
  1603.  
  1604.   // Install our command controllers. These commands are issued from
  1605.   // various places in our UI, including our preferences dialog, the
  1606.   // warning dialog, etc.
  1607.   var commandHandlers = { 
  1608.     "safebrowsing-show-warning" :
  1609.       BindToObject(this.onUserShowWarning, this),
  1610.     "safebrowsing-accept-warning" :
  1611.       BindToObject(this.onUserAcceptWarning, this),
  1612.     "safebrowsing-decline-warning" :
  1613.       BindToObject(this.onUserDeclineWarning, this),
  1614.   };
  1615.  
  1616.   this.commandController_ = new PROT_CommandController(commandHandlers);
  1617.   this.win_.controllers.appendController(this.commandController_);
  1618.  
  1619.   // This guy embodies the logic of when to display warnings
  1620.   // (displayers embody the how).
  1621.   this.browserView_ = new PROT_BrowserView(this.tabWatcher_, 
  1622.                                            this.win_.document);
  1623.  
  1624.   // We need to let the phishing warden know about this browser view so it 
  1625.   // can be given the opportunity to handle problem documents. We also need
  1626.   // to let the warden know when this window and hence this browser view
  1627.   // is going away.
  1628.   this.phishingWarden_.addBrowserView(this.browserView_);
  1629.  
  1630.   this.windowWatcher_ = 
  1631.     Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  1632.     .getService(Components.interfaces.nsIWindowWatcher);
  1633.  
  1634.   G_Debug(this, "Controller initialized.");
  1635. }
  1636.  
  1637. /**
  1638.  * Invoked when the browser window is closing. Do some cleanup.
  1639.  */
  1640. PROT_Controller.prototype.shutdown = function(e) {
  1641.   G_Debug(this, "Browser window closing. Shutting controller down.");
  1642.   if (this.browserView_) {
  1643.     this.phishingWarden_.removeBrowserView(this.browserView_);
  1644.   }
  1645.  
  1646.   if (this.commandController_) {
  1647.     this.win_.controllers.removeController(this.commandController_);
  1648.     this.commandController_ = null;
  1649.   }
  1650.  
  1651.  
  1652.   // No need to drain the browser view's problem queue explicitly; it will
  1653.   // receive pagehides for all the browsers in its queues as they're torn
  1654.   // down, and it will remove them.
  1655.   this.browserView_ = null;
  1656.  
  1657.   if (this.tabWatcher_) {
  1658.     this.tabWatcher_.removeListener("tabswitch", 
  1659.                                     this.onTabSwitchCallback_);
  1660.     this.tabWatcher_.shutdown();
  1661.   }
  1662.  
  1663.   this.win_.removeEventListener("unload", this.onShutdown_, false);
  1664.   this.prefs_ = null;
  1665.  
  1666.   this.windowWatcher_ = null;
  1667.  
  1668.   G_Debug(this, "Controller shut down.");
  1669. }
  1670.  
  1671. /**
  1672.  * The user clicked the urlbar icon; they want to see the warning message
  1673.  * again.
  1674.  */
  1675. PROT_Controller.prototype.onUserShowWarning = function() {
  1676.   var browser = this.tabWatcher_.getCurrentBrowser();
  1677.   this.browserView_.explicitShow(browser);
  1678. }
  1679.  
  1680. /**
  1681.  * Deal with a user accepting our warning. 
  1682.  *
  1683.  * TODO the warning hide/display instructions here can probably be moved
  1684.  * into the browserview in the future, given its knowledge of when the
  1685.  * problem doc hides/shows.
  1686.  */
  1687. PROT_Controller.prototype.onUserAcceptWarning = function() {
  1688.   G_Debug(this, "User accepted warning.");
  1689.   var browser = this.tabWatcher_.getCurrentBrowser();
  1690.   G_Assert(this, !!browser, "Couldn't get current browser?!?");
  1691.   G_Assert(this, this.browserView_.hasProblem(browser),
  1692.            "User accept fired, but browser doesn't have warning showing?!?");
  1693.  
  1694.   this.browserView_.acceptAction(browser);
  1695.   this.browserView_.problemResolved(browser);
  1696. }
  1697.  
  1698. /**
  1699.  * Deal with a user declining our warning. 
  1700.  *
  1701.  * TODO the warning hide/display instructions here can probably be moved
  1702.  * into the browserview in the future, given its knowledge of when the
  1703.  * problem doc hides/shows.
  1704.  */
  1705. PROT_Controller.prototype.onUserDeclineWarning = function() {
  1706.   G_Debug(this, "User declined warning.");
  1707.   var browser = this.tabWatcher_.getCurrentBrowser();
  1708.   G_Assert(this, this.browserView_.hasProblem(browser),
  1709.            "User decline fired, but browser doesn't have warning showing?!?");
  1710.   this.browserView_.declineAction(browser);
  1711.   // We don't call problemResolved() here because all declining does it
  1712.   // hide the message; we still have the urlbar icon showing, giving
  1713.   // the user the ability to bring the warning message back up if they
  1714.   // so desire.
  1715. }
  1716.  
  1717. /**
  1718.  * Notice tab switches, and display or hide warnings as appropriate.
  1719.  *
  1720.  * TODO this logic can probably move into the browser view at some
  1721.  * point. But one thing at a time.
  1722.  */
  1723. PROT_Controller.prototype.onTabSwitch = function(e) {
  1724.   if (this.browserView_.hasProblem(e.fromBrowser)) 
  1725.     this.browserView_.problemBrowserUnselected(e.fromBrowser);
  1726.  
  1727.   if (this.browserView_.hasProblem(e.toBrowser))
  1728.     this.browserView_.problemBrowserSelected(e.toBrowser);
  1729. }
  1730. /* ***** BEGIN LICENSE BLOCK *****
  1731.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1732.  *
  1733.  * The contents of this file are subject to the Mozilla Public License Version
  1734.  * 1.1 (the "License"); you may not use this file except in compliance with
  1735.  * the License. You may obtain a copy of the License at
  1736.  * http://www.mozilla.org/MPL/
  1737.  *
  1738.  * Software distributed under the License is distributed on an "AS IS" basis,
  1739.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1740.  * for the specific language governing rights and limitations under the
  1741.  * License.
  1742.  *
  1743.  * The Original Code is Google Safe Browsing.
  1744.  *
  1745.  * The Initial Developer of the Original Code is Google Inc.
  1746.  * Portions created by the Initial Developer are Copyright (C) 2006
  1747.  * the Initial Developer. All Rights Reserved.
  1748.  *
  1749.  * Contributor(s):
  1750.  *   Fritz Schneider <fritz@google.com> (original author)
  1751.  *
  1752.  * Alternatively, the contents of this file may be used under the terms of
  1753.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1754.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1755.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1756.  * of those above. If you wish to allow use of your version of this file only
  1757.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1758.  * use your version of this file under the terms of the MPL, indicate your
  1759.  * decision by deleting the provisions above and replace them with the notice
  1760.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1761.  * the provisions above, a recipient may use your version of this file under
  1762.  * the terms of any one of the MPL, the GPL or the LGPL.
  1763.  *
  1764.  * ***** END LICENSE BLOCK ***** */
  1765.  
  1766.  
  1767. // Some misc command-related plumbing used by the controller.
  1768.  
  1769.  
  1770. /**
  1771.  * A tiny wrapper class for super-simple command handlers.
  1772.  *
  1773.  * @param commandHandlerMap An object containing name/value pairs where
  1774.  *                          the name is command name (string) and value
  1775.  *                          is the function to execute for that command
  1776.  */
  1777. function PROT_CommandController(commandHandlerMap) {
  1778.   this.debugZone = "commandhandler";
  1779.   this.cmds_ = commandHandlerMap;
  1780. }
  1781.  
  1782. /**
  1783.  * @param cmd Command to query support for
  1784.  * @returns Boolean indicating if this controller supports cmd
  1785.  */
  1786. PROT_CommandController.prototype.supportsCommand = function(cmd) { 
  1787.   return (cmd in this.cmds_); 
  1788. }
  1789.  
  1790. /**
  1791.  * Trivial implementation
  1792.  *
  1793.  * @param cmd Command to query status of
  1794.  */
  1795. PROT_CommandController.prototype.isCommandEnabled = function(cmd) { 
  1796.   return true; 
  1797. }
  1798.   
  1799. /**
  1800.  * Execute a command
  1801.  *
  1802.  * @param cmd Command to execute
  1803.  */
  1804. PROT_CommandController.prototype.doCommand = function(cmd) {
  1805.   return this.cmds_[cmd](); 
  1806. }
  1807.  
  1808. /**
  1809.  * Trivial implementation
  1810.  */
  1811. PROT_CommandController.prototype.onEvent = function(cmd) { }
  1812.  
  1813. /* ***** BEGIN LICENSE BLOCK *****
  1814.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1815.  *
  1816.  * The contents of this file are subject to the Mozilla Public License Version
  1817.  * 1.1 (the "License"); you may not use this file except in compliance with
  1818.  * the License. You may obtain a copy of the License at
  1819.  * http://www.mozilla.org/MPL/
  1820.  *
  1821.  * Software distributed under the License is distributed on an "AS IS" basis,
  1822.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1823.  * for the specific language governing rights and limitations under the
  1824.  * License.
  1825.  *
  1826.  * The Original Code is Google Safe Browsing.
  1827.  *
  1828.  * The Initial Developer of the Original Code is Google Inc.
  1829.  * Portions created by the Initial Developer are Copyright (C) 2006
  1830.  * the Initial Developer. All Rights Reserved.
  1831.  *
  1832.  * Contributor(s):
  1833.  *   Fritz Schneider <fritz@google.com> (original author)
  1834.  *   J. Paul Reed <preed@mozilla.com>
  1835.  *
  1836.  * Alternatively, the contents of this file may be used under the terms of
  1837.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1838.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1839.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1840.  * of those above. If you wish to allow use of your version of this file only
  1841.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1842.  * use your version of this file under the terms of the MPL, indicate your
  1843.  * decision by deleting the provisions above and replace them with the notice
  1844.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1845.  * the provisions above, a recipient may use your version of this file under
  1846.  * the terms of any one of the MPL, the GPL or the LGPL.
  1847.  *
  1848.  * ***** END LICENSE BLOCK ***** */
  1849.  
  1850.  
  1851. // A class that encapsulates data provider specific values.  The
  1852. // root of the provider pref tree is browser.safebrowsing.provider.
  1853. // followed by a number, followed by specific properties.  The properties
  1854. // that a data provider can supply are:
  1855. //
  1856. // name: The name of the provider
  1857. // lookupURL: The URL to send requests to in enhanced mode
  1858. // keyURL: Before we send URLs in enhanced mode, we need to encrypt them
  1859. // reportURL: When shown a warning bubble, we send back the user decision
  1860. //            (get me out of here/ignore warning) to this URL (strip cookies
  1861. //            first).  This is optional.
  1862. // reportGenericURL: HTML page for general user feedback
  1863. // reportPhishURL: HTML page for notifying the provider of a new phishing page
  1864. // reportErrorURL: HTML page for notifying the provider of a false positive
  1865.  
  1866. const kDataProviderIdPref = 'browser.safebrowsing.dataProvider';
  1867. const kProviderBasePref = 'browser.safebrowsing.provider.';
  1868.  
  1869. //@line 58 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/browser/components/safebrowsing/src/../content/globalstore.js"
  1870. const MOZ_OFFICIAL_BUILD = true;
  1871. //@line 62 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/browser/components/safebrowsing/src/../content/globalstore.js"
  1872.  
  1873. const MOZ_PARAM_LOCALE = /\{moz:locale\}/g;
  1874. const MOZ_PARAM_CLIENT = /\{moz:client\}/g;
  1875. const MOZ_PARAM_BUILDID = /\{moz:buildid\}/g;
  1876. const MOZ_PARAM_VERSION = /\{moz:version\}/g;
  1877.  
  1878. /**
  1879.  * Information regarding the data provider.
  1880.  */
  1881. function PROT_DataProvider() {
  1882.   this.prefs_ = new G_Preferences();
  1883.  
  1884.   this.loadDataProviderPrefs_();
  1885.   
  1886.   // Watch for changes in the data provider and update accordingly.
  1887.   this.prefs_.addObserver(kDataProviderIdPref,
  1888.                           BindToObject(this.loadDataProviderPrefs_, this));
  1889.  
  1890.   // Watch for when anti-phishing is toggled on or off.
  1891.   this.prefs_.addObserver(kPhishWardenEnabledPref,
  1892.                           BindToObject(this.loadDataProviderPrefs_, this));
  1893.  
  1894.   // Watch for when remote lookups are toggled on or off.
  1895.   this.prefs_.addObserver(kPhishWardenRemoteLookups,
  1896.                           BindToObject(this.loadDataProviderPrefs_, this));
  1897. }
  1898.  
  1899. /**
  1900.  * Populate all the provider variables.  We also call this when whenever
  1901.  * the provider id changes.
  1902.  */
  1903. PROT_DataProvider.prototype.loadDataProviderPrefs_ = function() {
  1904.   // Currently, there's no UI for changing local list provider so we
  1905.   // hard code the value for provider 0.
  1906.   this.updateURL_ = this.getUrlPref_(
  1907.         'browser.safebrowsing.provider.0.updateURL');
  1908.  
  1909.   var id = this.prefs_.getPref(kDataProviderIdPref, null);
  1910.  
  1911.   // default to 0
  1912.   if (null == id)
  1913.     id = 0;
  1914.   
  1915.   var basePref = kProviderBasePref + id + '.';
  1916.  
  1917.   this.name_ = this.prefs_.getPref(basePref + "name", "");
  1918.  
  1919.   // Urls used to get data from a provider
  1920.   this.lookupURL_ = this.getUrlPref_(basePref + "lookupURL");
  1921.   this.keyURL_ = this.getUrlPref_(basePref + "keyURL");
  1922.   this.reportURL_ = this.getUrlPref_(basePref + "reportURL");
  1923.  
  1924.   // Urls to HTML report pages
  1925.   this.reportGenericURL_ = this.getUrlPref_(basePref + "reportGenericURL");
  1926.   this.reportErrorURL_ = this.getUrlPref_(basePref + "reportErrorURL");
  1927.   this.reportPhishURL_ = this.getUrlPref_(basePref + "reportPhishURL");
  1928.  
  1929.   // Propogate the changes to the list-manager.
  1930.   this.updateListManager_();
  1931. }
  1932.  
  1933. /**
  1934.  * The list manager needs urls to operate.  It needs a url to know where the
  1935.  * table updates are, and it needs a url for decrypting enchash style tables.
  1936.  */
  1937. PROT_DataProvider.prototype.updateListManager_ = function() {
  1938.   var listManager = Cc["@mozilla.org/url-classifier/listmanager;1"]
  1939.                       .getService(Ci.nsIUrlListManager);
  1940.  
  1941.   // If we add support for changing local data providers, we need to add a
  1942.   // pref observer that sets the update url accordingly.
  1943.   listManager.setUpdateUrl(this.getUpdateURL());
  1944.  
  1945.   // setKeyUrl has the side effect of fetching a key from the server.
  1946.   // This shouldn't happen if anti-phishing is disabled or we're in local
  1947.   // list mode, so we need to check for that.
  1948.   var isEnabled = this.prefs_.getPref(kPhishWardenEnabledPref, false);
  1949.   var remoteLookups = this.prefs_.getPref(kPhishWardenRemoteLookups, false);
  1950.   if (isEnabled && remoteLookups) {
  1951.     listManager.setKeyUrl(this.getKeyURL());
  1952.   } else {
  1953.     // Clear the key to stop updates.
  1954.     listManager.setKeyUrl("");
  1955.   }
  1956. }
  1957.  
  1958. /**
  1959.  * Lookup the value of a URL from prefs file and do parameter substitution.
  1960.  */
  1961. PROT_DataProvider.prototype.getUrlPref_ = function(prefName) {
  1962.   var url = this.prefs_.getPref(prefName);
  1963.  
  1964.   var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
  1965.                           .getService(Components.interfaces.nsIXULAppInfo);
  1966.  
  1967.   var mozClientStr = MOZ_OFFICIAL_BUILD ? 'navclient-auto-ffox' : appInfo.name;
  1968.  
  1969.   // Parameter substitution
  1970.   url = url.replace(MOZ_PARAM_LOCALE, this.getLocale_());
  1971.   url = url.replace(MOZ_PARAM_CLIENT, mozClientStr);
  1972.   url = url.replace(MOZ_PARAM_BUILDID, appInfo.appBuildID);
  1973.   url = url.replace(MOZ_PARAM_VERSION, appInfo.version);
  1974.   return url;
  1975. }
  1976.  
  1977. /**
  1978.  * @return String the browser locale (similar code is in nsSearchService.js)
  1979.  */
  1980. PROT_DataProvider.prototype.getLocale_ = function() {
  1981.   const localePref = "general.useragent.locale";
  1982.   var locale = this.getLocalizedPref_(localePref);
  1983.   if (locale)
  1984.     return locale;
  1985.  
  1986.   // Not localized
  1987.   var prefs = new G_Preferences();
  1988.   return prefs.getPref(localePref, "");
  1989. }
  1990.  
  1991. /**
  1992.  * @return String name of the localized pref, null if none exists.
  1993.  */
  1994. PROT_DataProvider.prototype.getLocalizedPref_ = function(aPrefName) {
  1995.   // G_Preferences doesn't know about complex values, so we use the
  1996.   // xpcom object directly.
  1997.   var prefs = Cc["@mozilla.org/preferences-service;1"]
  1998.               .getService(Ci.nsIPrefBranch);
  1999.   try {
  2000.     return prefs.getComplexValue(aPrefName, Ci.nsIPrefLocalizedString).data;
  2001.   } catch (ex) {
  2002.   }
  2003.   return "";
  2004. }
  2005.  
  2006. //////////////////////////////////////////////////////////////////////////////
  2007. // Getters for the remote provider pref values mentioned above.
  2008. PROT_DataProvider.prototype.getName = function() {
  2009.   return this.name_;
  2010. }
  2011.  
  2012. PROT_DataProvider.prototype.getUpdateURL = function() {
  2013.   return this.updateURL_;
  2014. }
  2015.  
  2016. PROT_DataProvider.prototype.getLookupURL = function() {
  2017.   return this.lookupURL_;
  2018. }
  2019. PROT_DataProvider.prototype.getKeyURL = function() {
  2020.   return this.keyURL_;
  2021. }
  2022. PROT_DataProvider.prototype.getReportURL = function() {
  2023.   return this.reportURL_;
  2024. }
  2025.  
  2026. PROT_DataProvider.prototype.getReportGenericURL = function() {
  2027.   return this.reportGenericURL_;
  2028. }
  2029. PROT_DataProvider.prototype.getReportErrorURL = function() {
  2030.   return this.reportErrorURL_;
  2031. }
  2032. PROT_DataProvider.prototype.getReportPhishURL = function() {
  2033.   return this.reportPhishURL_;
  2034. }
  2035. /* ***** BEGIN LICENSE BLOCK *****
  2036.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  2037.  *
  2038.  * The contents of this file are subject to the Mozilla Public License Version
  2039.  * 1.1 (the "License"); you may not use this file except in compliance with
  2040.  * the License. You may obtain a copy of the License at
  2041.  * http://www.mozilla.org/MPL/
  2042.  *
  2043.  * Software distributed under the License is distributed on an "AS IS" basis,
  2044.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  2045.  * for the specific language governing rights and limitations under the
  2046.  * License.
  2047.  *
  2048.  * The Original Code is Google Safe Browsing.
  2049.  *
  2050.  * The Initial Developer of the Original Code is Google Inc.
  2051.  * Portions created by the Initial Developer are Copyright (C) 2006
  2052.  * the Initial Developer. All Rights Reserved.
  2053.  *
  2054.  * Contributor(s):
  2055.  *   Niels Provos <niels@google.com> (original author)d
  2056.  
  2057.  *   Fritz Schneider <fritz@google.com>
  2058.  *
  2059.  * Alternatively, the contents of this file may be used under the terms of
  2060.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  2061.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  2062.  * in which case the provisions of the GPL or the LGPL are applicable instead
  2063.  * of those above. If you wish to allow use of your version of this file only
  2064.  * under the terms of either the GPL or the LGPL, and not to allow others to
  2065.  * use your version of this file under the terms of the MPL, indicate your
  2066.  * decision by deleting the provisions above and replace them with the notice
  2067.  * and other provisions required by the GPL or the LGPL. If you do not delete
  2068.  * the provisions above, a recipient may use your version of this file under
  2069.  * the terms of any one of the MPL, the GPL or the LGPL.
  2070.  *
  2071.  * ***** END LICENSE BLOCK ***** */
  2072.  
  2073. // A warden that knows how to register lists with a listmanager and keep them
  2074. // updated if necessary.  The ListWarden also provides a simple interface to
  2075. // check if a URL is evil or not.  Specialized wardens like the PhishingWarden
  2076. // inherit from it.
  2077. //
  2078. // Classes that inherit from ListWarden are responsible for calling
  2079. // enableTableUpdates or disableTableUpdates.  This usually entails
  2080. // registering prefObservers and calling enable or disable in the base
  2081. // class as appropriate.
  2082. //
  2083.  
  2084. /**
  2085.  * Abtracts the checking of user/browser actions for signs of
  2086.  * phishing. 
  2087.  *
  2088.  * @constructor
  2089.  */
  2090. function PROT_ListWarden() {
  2091.   this.debugZone = "listwarden";
  2092.   var listManager = Cc["@mozilla.org/url-classifier/listmanager;1"]
  2093.                       .getService(Ci.nsIUrlListManager);
  2094.   this.listManager_ = listManager;
  2095.  
  2096.   // Once we register tables, their respective names will be listed here.
  2097.   this.blackTables_ = [];
  2098.   this.whiteTables_ = [];
  2099. }
  2100.  
  2101. PROT_ListWarden.IN_BLACKLIST = 0
  2102. PROT_ListWarden.IN_WHITELIST = 1
  2103. PROT_ListWarden.NOT_FOUND = 2
  2104.  
  2105. /**
  2106.  * Tell the ListManger to keep all of our tables updated
  2107.  */
  2108.  
  2109. PROT_ListWarden.prototype.enableBlacklistTableUpdates = function() {
  2110.   for (var i = 0; i < this.blackTables_.length; ++i) {
  2111.     this.listManager_.enableUpdate(this.blackTables_[i]);
  2112.   }
  2113. }
  2114.  
  2115. /**
  2116.  * Tell the ListManager to stop updating our tables
  2117.  */
  2118.  
  2119. PROT_ListWarden.prototype.disableBlacklistTableUpdates = function() {
  2120.   for (var i = 0; i < this.blackTables_.length; ++i) {
  2121.     this.listManager_.disableUpdate(this.blackTables_[i]);
  2122.   }
  2123. }
  2124.  
  2125. /**
  2126.  * Tell the ListManager to update whitelist tables.  They may be enabled even
  2127.  * when other updates aren't, for performance reasons.
  2128.  */
  2129. PROT_ListWarden.prototype.enableWhitelistTableUpdates = function() {
  2130.   for (var i = 0; i < this.whiteTables_.length; ++i) {
  2131.     this.listManager_.enableUpdate(this.whiteTables_[i]);
  2132.   }
  2133. }
  2134.  
  2135. /**
  2136.  * Tell the ListManager to stop updating whitelist tables.
  2137.  */
  2138. PROT_ListWarden.prototype.disableWhitelistTableUpdates = function() {
  2139.   for (var i = 0; i < this.whiteTables_.length; ++i) {
  2140.     this.listManager_.disableUpdate(this.whiteTables_[i]);
  2141.   }
  2142. }
  2143.  
  2144. /**
  2145.  * Register a new black list table with the list manager
  2146.  * @param tableName - name of the table to register
  2147.  * @returns true if the table could be registered, false otherwise
  2148.  */
  2149.  
  2150. PROT_ListWarden.prototype.registerBlackTable = function(tableName) {
  2151.   var result = this.listManager_.registerTable(tableName, false);
  2152.   if (result) {
  2153.     this.blackTables_.push(tableName);
  2154.   }
  2155.   return result;
  2156. }
  2157.  
  2158. /**
  2159.  * Register a new white list table with the list manager
  2160.  * @param tableName - name of the table to register
  2161.  * @returns true if the table could be registered, false otherwise
  2162.  */
  2163.  
  2164. PROT_ListWarden.prototype.registerWhiteTable = function(tableName) {
  2165.   var result = this.listManager_.registerTable(tableName, false);
  2166.   if (result) {
  2167.     this.whiteTables_.push(tableName);
  2168.   }
  2169.   return result;
  2170. }
  2171.  
  2172. /**
  2173.  * Method that looks up a url on the whitelist.
  2174.  *
  2175.  * @param url The URL to check
  2176.  * @param callback Function with a single param:
  2177.  *       PROT_ListWarden.IN_BLACKLIST, PROT_ListWarden.IN_WHITELIST,
  2178.  *       or PROT_ListWarden.NOT_FOUND
  2179.  */
  2180. PROT_ListWarden.prototype.isWhiteURL = function(url, callback) {
  2181.   (new MultiTableQuerier(url,
  2182.                          this.whiteTables_,
  2183.                          [] /* no blacklists */,
  2184.                          callback)).run();
  2185. }
  2186.  
  2187. /**
  2188.  * Method that looks up a url in both the white and black lists.
  2189.  *
  2190.  * If there is conflict, the white list has precedence over the black list.
  2191.  *
  2192.  * This is tricky because all database queries are asynchronous.  So we need
  2193.  * to chain together our checks against white and black tables.  We use
  2194.  * MultiTableQuerier (see below) to manage this.
  2195.  *
  2196.  * @param url URL to look up
  2197.  * @param callback Function with a single param:
  2198.  *       PROT_ListWarden.IN_BLACKLIST, PROT_ListWarden.IN_WHITELIST,
  2199.  *       or PROT_ListWarden.NOT_FOUND
  2200.  */
  2201. PROT_ListWarden.prototype.isEvilURL = function(url, callback) {
  2202.   (new MultiTableQuerier(url,
  2203.                          this.whiteTables_,
  2204.                          this.blackTables_,
  2205.                          callback)).run();
  2206. }
  2207.  
  2208. /**
  2209.  * This class helps us query multiple tables even though each table check
  2210.  * is asynchronous.  It provides callbacks for each listManager lookup
  2211.  * and decides whether we need to continue querying or not.  After
  2212.  * instantiating the method, use run() to invoke.
  2213.  *
  2214.  * @param url String The url to check
  2215.  * @param whiteTables Array of strings with each white table name
  2216.  * @param blackTables Array of strings with each black table name
  2217.  * @param callback Function to call with result 
  2218.  *       PROT_ListWarden.IN_BLACKLIST, PROT_ListWarden.IN_WHITELIST,
  2219.  *       or PROT_ListWarden.NOT_FOUND
  2220.  */
  2221. function MultiTableQuerier(url, whiteTables, blackTables, callback) {
  2222.   this.debugZone = "multitablequerier";
  2223.   this.url_ = url;
  2224.  
  2225.   this.whiteTables_ = whiteTables;
  2226.   this.blackTables_ = blackTables;
  2227.   this.whiteIdx_ = 0;
  2228.   this.blackIdx_ = 0;
  2229.  
  2230.   this.callback_ = callback;
  2231.   this.listManager_ = Cc["@mozilla.org/url-classifier/listmanager;1"]
  2232.                       .getService(Ci.nsIUrlListManager);
  2233. }
  2234.  
  2235. /**
  2236.  * We first query the white tables in succession.  If any contain
  2237.  * the url, we stop.  If none contain the url, we query the black tables
  2238.  * in succession.  If any contain the url, we call callback and
  2239.  * stop.  If none of the black tables contain the url, then we just stop
  2240.  * (i.e., it's not black url).
  2241.  */
  2242. MultiTableQuerier.prototype.run = function() {
  2243.   var whiteTable = this.whiteTables_[this.whiteIdx_];
  2244.   var blackTable = this.blackTables_[this.blackIdx_];
  2245.   if (whiteTable) {
  2246.     //G_Debug(this, "Looking in whitetable: " + whiteTable);
  2247.     ++this.whiteIdx_;
  2248.     this.listManager_.safeExists(whiteTable, this.url_,
  2249.                                  BindToObject(this.whiteTableCallback_,
  2250.                                               this));
  2251.   } else if (blackTable) {
  2252.     //G_Debug(this, "Looking in blacktable: " + blackTable);
  2253.     ++this.blackIdx_;
  2254.     this.listManager_.safeExists(blackTable, this.url_,
  2255.                                  BindToObject(this.blackTableCallback_,
  2256.                                               this));
  2257.   } else {
  2258.     // No tables left to check, so we quit.
  2259.     G_Debug(this, "Not found in any tables: " + this.url_);
  2260.     this.callback_(PROT_ListWarden.NOT_FOUND);
  2261.  
  2262.     // Break circular ref to callback.
  2263.     this.callback_ = null;
  2264.     this.listManager_ = null;
  2265.   }
  2266. }
  2267.  
  2268. /**
  2269.  * After checking a white table, we return here.  If the url is found,
  2270.  * we can stop.  Otherwise, we call run again.
  2271.  */
  2272. MultiTableQuerier.prototype.whiteTableCallback_ = function(isFound) {
  2273.   //G_Debug(this, "whiteTableCallback_: " + isFound);
  2274.   if (!isFound)
  2275.     this.run();
  2276.   else {
  2277.     G_Debug(this, "Found in whitelist: " + this.url_)
  2278.     this.callback_(PROT_ListWarden.IN_WHITELIST);
  2279.  
  2280.     // Break circular ref to callback.
  2281.     this.callback_ = null;
  2282.     this.listManager_ = null;
  2283.   }
  2284. }
  2285.  
  2286. /**
  2287.  * After checking a black table, we return here.  If the url is found,
  2288.  * we can call the callback and stop.  Otherwise, we call run again.
  2289.  */
  2290. MultiTableQuerier.prototype.blackTableCallback_ = function(isFound) {
  2291.   //G_Debug(this, "blackTableCallback_: " + isFound);
  2292.   if (!isFound) {
  2293.     this.run();
  2294.   } else {
  2295.     // In the blacklist, must be an evil url.
  2296.     G_Debug(this, "Found in blacklist: " + this.url_)
  2297.     this.callback_(PROT_ListWarden.IN_BLACKLIST);
  2298.  
  2299.     // Break circular ref to callback.
  2300.     this.callback_ = null;
  2301.     this.listManager_ = null;
  2302.   }
  2303. }
  2304. /* ***** BEGIN LICENSE BLOCK *****
  2305.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  2306.  *
  2307.  * The contents of this file are subject to the Mozilla Public License Version
  2308.  * 1.1 (the "License"); you may not use this file except in compliance with
  2309.  * the License. You may obtain a copy of the License at
  2310.  * http://www.mozilla.org/MPL/
  2311.  *
  2312.  * Software distributed under the License is distributed on an "AS IS" basis,
  2313.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  2314.  * for the specific language governing rights and limitations under the
  2315.  * License.
  2316.  *
  2317.  * The Original Code is Google Safe Browsing.
  2318.  *
  2319.  * The Initial Developer of the Original Code is Google Inc.
  2320.  * Portions created by the Initial Developer are Copyright (C) 2006
  2321.  * the Initial Developer. All Rights Reserved.
  2322.  *
  2323.  * Contributor(s):
  2324.  *   Fritz Schneider <fritz@google.com> (original author)
  2325.  *
  2326.  * Alternatively, the contents of this file may be used under the terms of
  2327.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  2328.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  2329.  * in which case the provisions of the GPL or the LGPL are applicable instead
  2330.  * of those above. If you wish to allow use of your version of this file only
  2331.  * under the terms of either the GPL or the LGPL, and not to allow others to
  2332.  * use your version of this file under the terms of the MPL, indicate your
  2333.  * decision by deleting the provisions above and replace them with the notice
  2334.  * and other provisions required by the GPL or the LGPL. If you do not delete
  2335.  * the provisions above, a recipient may use your version of this file under
  2336.  * the terms of any one of the MPL, the GPL or the LGPL.
  2337.  *
  2338.  * ***** END LICENSE BLOCK ***** */
  2339.  
  2340.  
  2341. // Implementation of the warning message we show users when we
  2342. // notice navigation to a phishing page after it has loaded. The
  2343. // browser view encapsulates all the hide/show logic, so the displayer
  2344. // doesn't need to know when to display itself, only how.
  2345. //
  2346. // Displayers implement the following interface:
  2347. //
  2348. // start() -- fired to initialize the displayer (to make it active). When
  2349. //            called, this displayer starts listening for and responding to
  2350. //            events. At most one displayer per tab should be active at a 
  2351. //            time, and start() should be called at most once.
  2352. // declineAction() -- fired when the user declines the warning.
  2353. // acceptAction() -- fired when the user declines the warning
  2354. // explicitShow() -- fired when the user wants to see the warning again
  2355. // browserSelected() -- the browser is the top tab
  2356. // browserUnselected() -- the browser is no long the top tab
  2357. // done() -- clean up. May be called once (even if the displayer wasn't
  2358. //           activated).
  2359. //
  2360. // At the moment, all displayers share access to the same xul in 
  2361. // safebrowsing-overlay.xul. Hence the need for at most one displayer
  2362. // to be active per tab at a time.
  2363.  
  2364. /**
  2365.  * Factory that knows how to create a displayer appropriate to the
  2366.  * user's platform. We use a clunky canvas-based displayer for all
  2367.  * platforms until such time as we can overlay semi-transparent
  2368.  * areas over browser content.
  2369.  *
  2370.  * See the base object for a description of the constructor args
  2371.  *
  2372.  * @constructor
  2373.  */
  2374. function PROT_PhishMsgDisplayer(msgDesc, browser, doc, url) {
  2375.  
  2376.   // TODO: Change this to return a PhishMsgDisplayerTransp on windows
  2377.   // (and maybe other platforms) when Firefox 2.0 hits.
  2378.  
  2379.   return new PROT_PhishMsgDisplayerCanvas(msgDesc, browser, doc, url);
  2380. }
  2381.  
  2382.  
  2383. /**
  2384.  * Base class that implements most of the plumbing required to hide
  2385.  * and show a phishing warning. Subclasses implement the actual
  2386.  * showMessage and hideMessage methods. 
  2387.  *
  2388.  * This class is not meant to be instantiated directly.
  2389.  *
  2390.  * @param msgDesc String describing the kind of warning this is
  2391.  * @param browser Reference to the browser over which we display the msg
  2392.  * @param doc Reference to the document in which browser is found
  2393.  * @param url String containing url of the problem document
  2394.  * @constructor
  2395.  */
  2396. function PROT_PhishMsgDisplayerBase(msgDesc, browser, doc, url) {
  2397.   this.debugZone = "phishdisplayer";
  2398.   this.msgDesc_ = msgDesc;                                // currently unused
  2399.   this.browser_ = browser;
  2400.   this.doc_ = doc;
  2401.   this.url_ = url;
  2402.  
  2403.   // We'll need to manipulate the XUL in safebrowsing-overlay.xul
  2404.   this.messageId_ = "safebrowsing-palm-message";
  2405.   this.messageTailId_ = "safebrowsing-palm-message-tail-container";
  2406.   this.messageContentId_ = "safebrowsing-palm-message-content";
  2407.   this.extendedMessageId_ = "safebrowsing-palm-extended-message";
  2408.   this.showmoreLinkId_ = "safebrowsing-palm-showmore-link";
  2409.   this.faqLinkId_ = "safebrowsing-palm-faq-link";
  2410.   this.urlbarIconId_ = "safebrowsing-urlbar-icon";
  2411.   this.refElementId_ = this.urlbarIconId_;
  2412.  
  2413.   // We use this to report user actions to the server
  2414.   this.reporter_ = new PROT_Reporter();
  2415.  
  2416.   // The active UI elements in our warning send these commands; bind them
  2417.   // to their handlers but don't register the commands until we start
  2418.   // (because another displayer might be active)
  2419.   this.commandHandlers_ = {
  2420.     "safebrowsing-palm-showmore":
  2421.       BindToObject(this.showMore_, this),
  2422.   };
  2423.  
  2424.   this.windowWatcher_ = 
  2425.     Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2426.     .getService(Components.interfaces.nsIWindowWatcher);
  2427. }
  2428.  
  2429. /**
  2430.  * @returns The default background color of the browser
  2431.  */
  2432. PROT_PhishMsgDisplayerBase.prototype.getBackgroundColor_ = function() {
  2433.   var pref = Components.classes["@mozilla.org/preferences-service;1"].
  2434.              getService(Components.interfaces.nsIPrefBranch);
  2435.   return pref.getCharPref("browser.display.background_color");
  2436. }
  2437.  
  2438. /**
  2439.  * Fired when the user declines our warning. Report it!
  2440.  */
  2441. PROT_PhishMsgDisplayerBase.prototype.declineAction = function() {
  2442.   G_Debug(this, "User declined warning.");
  2443.   G_Assert(this, this.started_, "Decline on a non-active displayer?");
  2444.   this.reporter_.report("phishdecline", this.url_);
  2445.  
  2446.   this.messageShouldShow_ = false;
  2447.   if (this.messageShowing_)
  2448.     this.hideMessage_();
  2449. }
  2450.  
  2451. /**
  2452.  * Fired when the user accepts our warning
  2453.  */
  2454. PROT_PhishMsgDisplayerBase.prototype.acceptAction = function() {
  2455.   G_Assert(this, this.started_, "Accept on an unstarted displayer?");
  2456.   G_Assert(this, this.done_, "Accept on a finished displayer?");
  2457.   G_Debug(this, "User accepted warning.");
  2458.   this.reporter_.report("phishaccept", this.url_);
  2459.  
  2460.   var url = this.getMeOutOfHereUrl_();
  2461.   this.browser_.loadURI(url);
  2462. }
  2463.  
  2464. /**
  2465.  * Get the url for "Get me out of here."  This is the browser's default home
  2466.  * page, or, about:blank.
  2467.  * @return String url
  2468.  */
  2469. PROT_PhishMsgDisplayerBase.prototype.getMeOutOfHereUrl_ = function() {
  2470.   // Try to get their homepage from prefs.
  2471.   var prefs = Cc["@mozilla.org/preferences-service;1"]
  2472.               .getService(Ci.nsIPrefService).getDefaultBranch(null);
  2473.  
  2474.   var url = "about:blank";
  2475.   try {
  2476.     url = prefs.getComplexValue("browser.startup.homepage",
  2477.                                 Ci.nsIPrefLocalizedString).data;
  2478.     // If url is a pipe-delimited set of pages, just take the first one.
  2479.     // This will need to change once bug 221445 is fixed.
  2480.     if (url.indexOf("|") != -1)
  2481.       url = url.split("|")[0];
  2482.   } catch(e) {
  2483.     G_Debug(this, "Couldn't get homepage pref: " + e);
  2484.   }
  2485.   
  2486.   return url;
  2487. }
  2488.  
  2489. /**
  2490.  * Invoked when the browser is resized
  2491.  */
  2492. PROT_PhishMsgDisplayerBase.prototype.onBrowserResized_ = function(event) {
  2493.   G_Debug(this, "Got resize for " + event.target);
  2494.  
  2495.   if (this.messageShowing_) {
  2496.     this.hideMessage_(); 
  2497.     this.showMessage_();
  2498.   }
  2499. }
  2500.  
  2501. /**
  2502.  * Invoked by the browser view when our browser is switched to
  2503.  */
  2504. PROT_PhishMsgDisplayerBase.prototype.browserSelected = function() {
  2505.   G_Assert(this, this.started_, "Displayer selected before being started???");
  2506.  
  2507.   // If messageshowing hasn't been set, then this is the first time this
  2508.   // problematic browser tab has been on top, so do our setup and show
  2509.   // the warning.
  2510.   if (this.messageShowing_ === undefined) {
  2511.     this.messageShouldShow_ = true;
  2512.   }
  2513.  
  2514.   this.hideLockIcon_();        // Comes back when we are unselected or unloaded
  2515.   this.addWarningInUrlbar_();  // Goes away when we are unselected or unloaded
  2516.  
  2517.   // messageShouldShow might be false if the user dismissed the warning, 
  2518.   // switched tabs, and then switched back. We're still active, but don't
  2519.   // want to show the warning again. The user can cause it to show by
  2520.   // clicking our icon in the urlbar.
  2521.   if (this.messageShouldShow_)
  2522.     this.showMessage_();
  2523. }
  2524.  
  2525. /**
  2526.  * Invoked to display the warning message explicitly, for example if the user
  2527.  * clicked the url warning icon.
  2528.  */
  2529. PROT_PhishMsgDisplayerBase.prototype.explicitShow = function() {
  2530.   this.messageShouldShow_ = true;
  2531.   if (!this.messageShowing_)
  2532.     this.showMessage_();
  2533. }
  2534.  
  2535. /** 
  2536.  * Invoked by the browser view when our browser is switched away from
  2537.  */
  2538. PROT_PhishMsgDisplayerBase.prototype.browserUnselected = function() {
  2539.   this.removeWarningInUrlbar_();
  2540.   this.unhideLockIcon_();
  2541.   if (this.messageShowing_)
  2542.     this.hideMessage_();
  2543. }
  2544.  
  2545. /**
  2546.  * Invoked to make this displayer active. The displayer will now start
  2547.  * responding to notifications such as commands and resize events. We
  2548.  * can't do this in the constructor because there might be many 
  2549.  * displayers instantiated waiting in the problem queue for a particular
  2550.  * browser (e.g., a page has multiple framed problem pages), and we
  2551.  * don't want them all responding to commands!
  2552.  *
  2553.  * Invoked zero (the page we're a warning for was nav'd away from
  2554.  * before it reaches the head of the problem queue) or one (we're
  2555.  * displaying this warning) times by the browser view.
  2556.  */
  2557. PROT_PhishMsgDisplayerBase.prototype.start = function() {
  2558.   G_Assert(this, this.started_ == undefined, "Displayer started twice?");
  2559.   this.started_ = true;
  2560.  
  2561.   this.commandController_ = new PROT_CommandController(this.commandHandlers_);
  2562.   this.doc_.defaultView.controllers.appendController(this.commandController_);
  2563.  
  2564.   // Add an event listener for when the browser resizes (e.g., user
  2565.   // shows/hides the sidebar).
  2566.   this.resizeHandler_ = BindToObject(this.onBrowserResized_, this);
  2567.   this.browser_.addEventListener("resize",
  2568.                                  this.resizeHandler_, 
  2569.                                  false);
  2570. }
  2571.  
  2572. /**
  2573.  * @returns Boolean indicating whether this displayer is currently
  2574.  *          active
  2575.  */
  2576. PROT_PhishMsgDisplayerBase.prototype.isActive = function() {
  2577.   return !!this.started_;
  2578. }
  2579.  
  2580. /**
  2581.  * Invoked by the browser view to clean up after the user is done 
  2582.  * interacting with the message. Should be called once by the browser
  2583.  * view. 
  2584.  */
  2585. PROT_PhishMsgDisplayerBase.prototype.done = function() {
  2586.   G_Assert(this, !this.done_, "Called done more than once?");
  2587.   this.done_ = true;
  2588.  
  2589.   // If the Document we're showing the warning for was nav'd away from
  2590.   // before we had a chance to get started, we have nothing to do.
  2591.   if (this.started_) {
  2592.  
  2593.     // If we were started, we must be the current problem, so these things
  2594.     // must be showing
  2595.     this.removeWarningInUrlbar_();
  2596.     this.unhideLockIcon_();
  2597.  
  2598.     // Could be though that they've closed the warning dialog
  2599.     if (this.messageShowing_)
  2600.       this.hideMessage_();
  2601.  
  2602.     if (this.resizeHandler_) {
  2603.       this.browser_.removeEventListener("resize", 
  2604.                                         this.resizeHandler_, 
  2605.                                         false);
  2606.       this.resizeHandler_ = null;
  2607.     }
  2608.     
  2609.     var win = this.doc_.defaultView;
  2610.     win.controllers.removeController(this.commandController_);
  2611.     this.commandController_ = null;
  2612.   }
  2613. }
  2614.  
  2615. /**
  2616.  * Helper function to remove a substring from inside a string.
  2617.  *
  2618.  * @param orig String to remove substring from
  2619.  * 
  2620.  * @param toRemove String to remove (if it is present)
  2621.  *
  2622.  * @returns String with the substring removed
  2623.  */
  2624. PROT_PhishMsgDisplayerBase.prototype.removeIfExists_ = function(orig,
  2625.                                                                 toRemove) {
  2626.   var pos = orig.indexOf(toRemove);
  2627.   if (pos != -1)
  2628.     orig = orig.substring(0, pos) + orig.substring(pos + toRemove.length);
  2629.  
  2630.   return orig;
  2631. }
  2632.  
  2633. /**
  2634.  * We don't want to confuse users if they land on a phishy page that uses
  2635.  * SSL, so ensure that the lock icon never shows when we're showing our 
  2636.  * warning.
  2637.  */
  2638. PROT_PhishMsgDisplayerBase.prototype.hideLockIcon_ = function() {
  2639.   var lockIcon = this.doc_.getElementById("lock-icon");
  2640.   if (!lockIcon)
  2641.     return;
  2642.   lockIcon.hidden = true;
  2643. }
  2644.  
  2645. /**
  2646.  * Ensure they can see it after our warning is finished.
  2647.  */
  2648. PROT_PhishMsgDisplayerBase.prototype.unhideLockIcon_ = function() {
  2649.   var lockIcon = this.doc_.getElementById("lock-icon");
  2650.   if (!lockIcon)
  2651.     return;
  2652.   lockIcon.hidden = false;
  2653. }
  2654.  
  2655. /**
  2656.  * This method makes our warning icon visible in the location bar. It will
  2657.  * be removed only when the problematic document is navigated awy from 
  2658.  * (i.e., when done() is called), and not when the warning is dismissed.
  2659.  */
  2660. PROT_PhishMsgDisplayerBase.prototype.addWarningInUrlbar_ = function() {
  2661.   var urlbarIcon = this.doc_.getElementById(this.urlbarIconId_);
  2662.   if (!urlbarIcon)
  2663.     return;
  2664.   urlbarIcon.setAttribute('level', 'warn');
  2665. }
  2666.  
  2667. /**
  2668.  * Hides our urlbar icon
  2669.  */
  2670. PROT_PhishMsgDisplayerBase.prototype.removeWarningInUrlbar_ = function() {
  2671.   var urlbarIcon = this.doc_.getElementById(this.urlbarIconId_);
  2672.   if (!urlbarIcon)
  2673.     return;
  2674.   urlbarIcon.setAttribute('level', 'safe');
  2675. }
  2676.  
  2677. /**
  2678.  * VIRTUAL -- Displays the warning message
  2679.  */
  2680. PROT_PhishMsgDisplayerBase.prototype.showMessage_ = function() { };
  2681.  
  2682. /**
  2683.  * VIRTUAL -- Hide the warning message from the user.
  2684.  */
  2685. PROT_PhishMsgDisplayerBase.prototype.hideMessage_ = function() { };
  2686.  
  2687. /**
  2688.  * Reposition the message relative to refElement in the parent window
  2689.  *
  2690.  * @param message Reference to the element to position
  2691.  * @param tail Reference to the message tail
  2692.  * @param refElement Reference to element relative to which we position
  2693.  *                   ourselves
  2694.  */
  2695. PROT_PhishMsgDisplayerBase.prototype.adjustLocation_ = function(message,
  2696.                                                                 tail,
  2697.                                                                 refElement) {
  2698.   var refX = refElement.boxObject.x;
  2699.   var refY = refElement.boxObject.y;
  2700.   var refHeight = refElement.boxObject.height;
  2701.   var refWidth = refElement.boxObject.width;
  2702.   G_Debug(this, "Ref element is at [window-relative] (" + refX + ", " + 
  2703.           refY + ")");
  2704.  
  2705.   var pixelsIntoRefY = -2;
  2706.   var tailY = refY + refHeight - pixelsIntoRefY;
  2707.   var tailPixelsLeftOfRefX = tail.boxObject.width;
  2708.   var tailPixelsIntoRefX = Math.round(refWidth / 2);
  2709.   var tailX = refX - tailPixelsLeftOfRefX + tailPixelsIntoRefX;
  2710.  
  2711.   // Move message up a couple pixels so the tail overlaps it.
  2712.   var messageY = tailY + tail.boxObject.height - 2;
  2713.   var messagePixelsLeftOfRefX = 375;
  2714.   var messageX = refX - messagePixelsLeftOfRefX;
  2715.   G_Debug(this, "Message is at [window-relative] (" + messageX + ", " + 
  2716.           messageY + ")");
  2717.   G_Debug(this, "Tail is at [window-relative] (" + tailX + ", " + 
  2718.           tailY + ")");
  2719.  
  2720.   if (messageX < 0) {
  2721.     // We're hanging off the left edge, switch to floating mode
  2722.     tail.style.display = "none";
  2723.     this.adjustLocationFloating_(message);
  2724.     return;
  2725.   }
  2726.  
  2727.   tail.style.top = tailY + "px";
  2728.   tail.style.left = tailX + "px";
  2729.   message.style.top = messageY + "px";
  2730.   message.style.left = messageX + "px";
  2731.   
  2732.   this.maybeAddScrollbars_();
  2733. }
  2734.  
  2735. /**
  2736.  * Position the warning bubble with no reference element.  In this case we
  2737.  * just center the warning bubble at the top of the users window.
  2738.  * @param message XULElement message bubble XUL container.
  2739.  */
  2740. PROT_PhishMsgDisplayerBase.prototype.adjustLocationFloating_ = function(message) {
  2741.   // Compute X offset
  2742.   var browserX = this.browser_.boxObject.x;
  2743.   var browserXCenter = browserX + this.browser_.boxObject.width / 2;
  2744.   var messageX = browserXCenter - (message.boxObject.width / 2);
  2745.  
  2746.   // Compute Y offset (top of the browser window)
  2747.   var messageY = this.browser_.boxObject.y;
  2748.  
  2749.   // Position message
  2750.   message.style.top = messageY + "px";
  2751.   message.style.left = messageX + "px";
  2752.  
  2753.   this.maybeAddScrollbars_();
  2754. }
  2755.  
  2756. /**
  2757.  * Add a vertical scrollbar if we're falling out of the browser window.
  2758.  */
  2759. PROT_PhishMsgDisplayerBase.prototype.maybeAddScrollbars_ = function() {
  2760.   var message = this.doc_.getElementById(this.messageId_);
  2761.   
  2762.   var content = this.doc_.getElementById(this.messageContentId_);
  2763.   var bottom = content.boxObject.y + content.boxObject.height;
  2764.   var maxY = this.doc_.defaultView.innerHeight;
  2765.   G_Debug(this, "bottom: " + bottom + ", maxY: " + maxY
  2766.                 + ", new height: " + (maxY - content.boxObject.y));
  2767.   if (bottom > maxY) {
  2768.     var newHeight = maxY - content.boxObject.y;
  2769.     if (newHeight < 1)
  2770.       newHeight = 1;
  2771.  
  2772.     content.style.height = newHeight + "px";
  2773.     content.style.overflow = "auto";
  2774.   }
  2775. }
  2776.  
  2777. /**
  2778.  * Show the extended warning message
  2779.  */
  2780. PROT_PhishMsgDisplayerBase.prototype.showMore_ = function() {
  2781.   this.doc_.getElementById(this.extendedMessageId_).hidden = false;
  2782.   this.doc_.getElementById(this.showmoreLinkId_).style.display = "none";
  2783.  
  2784.   // set FAQ URL
  2785.   var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  2786.                             .getService(Components.interfaces.nsIURLFormatter);
  2787.   var faqURL = formatter.formatURLPref("browser.safebrowsing.warning.infoURL");
  2788.   var labelEl = this.doc_.getElementById(this.faqLinkId_);
  2789.   labelEl.setAttribute("href", faqURL);
  2790.   
  2791.   this.maybeAddScrollbars_();
  2792. }
  2793.  
  2794. /**
  2795.  * The user clicked on one of the links in the buble.  Display the
  2796.  * corresponding page in a new window with all the chrome enabled.
  2797.  *
  2798.  * @param url The URL to display in a new window
  2799.  */
  2800. PROT_PhishMsgDisplayerBase.prototype.showURL_ = function(url) {
  2801.   this.windowWatcher_.openWindow(this.windowWatcher_.activeWindow,
  2802.                                  url,
  2803.                                  "_blank",
  2804.                                  null,
  2805.                                  null);
  2806. }
  2807.  
  2808. /**
  2809.  * If the warning bubble came up in error, this url goes to a form
  2810.  * to notify the data provider.
  2811.  * @return url String
  2812.  */
  2813. PROT_PhishMsgDisplayerBase.prototype.getReportErrorURL_ = function() {
  2814.   var badUrl = this.url_;
  2815.  
  2816.   var url = gDataProvider.getReportErrorURL();
  2817.   url += "&url=" + encodeURIComponent(badUrl);
  2818.   return url;
  2819. }
  2820.  
  2821. /**
  2822.  * URL for the user to report back to us.  This is to provide the user
  2823.  * with an action after being warned.
  2824.  */
  2825. PROT_PhishMsgDisplayerBase.prototype.getReportGenericURL_ = function() {
  2826.   var badUrl = this.url_;
  2827.  
  2828.   var url = gDataProvider.getReportGenericURL();
  2829.   url += "&url=" + encodeURIComponent(badUrl);
  2830.   return url;
  2831. }
  2832.  
  2833.  
  2834. /**
  2835.  * A specific implementation of the dislpayer using a canvas. This
  2836.  * class is meant for use on platforms that don't support transparent
  2837.  * elements over browser content (currently: all platforms). 
  2838.  *
  2839.  * The main ugliness is the fact that we're hiding the content area and
  2840.  * painting the page to canvas. As a result, we must periodically
  2841.  * re-paint the canvas to reflect updates to the page. Otherwise if
  2842.  * the page was half-loaded when we showed our warning, it would
  2843.  * stay that way even though the page actually finished loading. 
  2844.  *
  2845.  * See base constructor for full details of constructor args.
  2846.  *
  2847.  * @constructor
  2848.  */
  2849. function PROT_PhishMsgDisplayerCanvas(msgDesc, browser, doc, url) {
  2850.   PROT_PhishMsgDisplayerBase.call(this, msgDesc, browser, doc, url);
  2851.  
  2852.   this.dimAreaId_ = "safebrowsing-dim-area-canvas";
  2853.   this.pageCanvasId_ = "safebrowsing-page-canvas";
  2854.   this.xhtmlNS_ = "http://www.w3.org/1999/xhtml";     // we create html:canvas
  2855. }
  2856.  
  2857. PROT_PhishMsgDisplayerCanvas.inherits(PROT_PhishMsgDisplayerBase);
  2858.  
  2859. /**
  2860.  * Displays the warning message.  First we make sure the overlay is loaded
  2861.  * then call showMessageAfterOverlay_.
  2862.  */
  2863. PROT_PhishMsgDisplayerCanvas.prototype.showMessage_ = function() {
  2864.   G_Debug(this, "Showing message.");
  2865.  
  2866.   // Load the overlay if we haven't already.
  2867.   var dimmer = this.doc_.getElementById('safebrowsing-dim-area-canvas');
  2868.   if (!dimmer) {
  2869.     var onOverlayMerged = BindToObject(this.showMessageAfterOverlay_,
  2870.                                        this);
  2871.     var observer = new G_ObserverWrapper("xul-overlay-merged",
  2872.                                          onOverlayMerged);
  2873.  
  2874.     this.doc_.loadOverlay(
  2875.         "chrome://browser/content/safebrowsing/warning-overlay.xul",
  2876.         observer);
  2877.   } else {
  2878.     // The overlay is already loaded so we go ahead and call
  2879.     // showMessageAfterOverlay_.
  2880.     this.showMessageAfterOverlay_();
  2881.   }
  2882. }
  2883.  
  2884. /**
  2885.  * This does the actual work of showing the warning message.
  2886.  */
  2887. PROT_PhishMsgDisplayerCanvas.prototype.showMessageAfterOverlay_ = function() {
  2888.   this.messageShowing_ = true;
  2889.  
  2890.   // Position the canvas overlay. Order here is significant, but don't ask me
  2891.   // why for some of these. You need to:
  2892.   // 1. get browser dimensions
  2893.   // 2. add canvas to the document
  2894.   // 3. unhide the dimmer (gray out overlay)
  2895.   // 4. display to the canvas
  2896.   // 5. unhide the warning message
  2897.   // 6. update link targets in warning message
  2898.   // 7. focus the warning message
  2899.  
  2900.   // (1)
  2901.   var w = this.browser_.boxObject.width;
  2902.   G_Debug(this, "browser w=" + w);
  2903.   var h = this.browser_.boxObject.height;
  2904.   G_Debug(this, "browser h=" + h);
  2905.   var x = this.browser_.boxObject.x;
  2906.   G_Debug(this, "browser x=" + w);
  2907.   var y = this.browser_.boxObject.y;
  2908.   G_Debug(this, "browser y=" + h);
  2909.  
  2910.   var win = this.browser_.contentWindow;
  2911.   var scrollX = win.scrollX;
  2912.   G_Debug(this, "win scrollx=" + scrollX);
  2913.   var scrollY = win.scrollY;
  2914.   G_Debug(this, "win scrolly=" + scrollY);
  2915.  
  2916.   // (2)
  2917.   // We add the canvas dynamically and remove it when we're done because
  2918.   // leaving it hanging around consumes a lot of memory.
  2919.   var pageCanvas = this.doc_.createElementNS(this.xhtmlNS_, "html:canvas");
  2920.   pageCanvas.id = this.pageCanvasId_;
  2921.   pageCanvas.style.left = x + 'px';
  2922.   pageCanvas.style.top = y + 'px';
  2923.  
  2924.   var dimarea = this.doc_.getElementById(this.dimAreaId_);
  2925.   this.doc_.getElementById('main-window').insertBefore(pageCanvas,
  2926.                                                        dimarea);
  2927.  
  2928.   // (3)
  2929.   dimarea.style.left = x + 'px';
  2930.   dimarea.style.top = y + 'px';
  2931.   dimarea.style.width = w + 'px';
  2932.   dimarea.style.height = h + 'px';
  2933.   dimarea.hidden = false;
  2934.   
  2935.   // (4)
  2936.   pageCanvas.setAttribute("width", w);
  2937.   pageCanvas.setAttribute("height", h);
  2938.  
  2939.   var bgcolor = this.getBackgroundColor_();
  2940.  
  2941.   var cx = pageCanvas.getContext("2d");
  2942.   cx.drawWindow(win, scrollX, scrollY, w, h, bgcolor);
  2943.  
  2944.   // Now repaint the window every so often in case the content hasn't fully
  2945.   // loaded at this point.
  2946.   var debZone = this.debugZone;
  2947.   function repaint() {
  2948.     G_Debug(debZone, "Repainting canvas...");
  2949.     cx.drawWindow(win, scrollX, scrollY, w, h, bgcolor);
  2950.   };
  2951.   this.repainter_ = new PROT_PhishMsgCanvasRepainter(repaint);
  2952.  
  2953.   // (5)
  2954.   this.showAndPositionWarning_();
  2955.  
  2956.   // (6)
  2957.   var link = this.doc_.getElementById('safebrowsing-palm-falsepositive-link');
  2958.   link.href = this.getReportErrorURL_();
  2959.  
  2960.   // (7)
  2961.   this.doc_.getElementById(this.messageContentId_).focus();
  2962. }
  2963.  
  2964. /**
  2965.  * Show and position the warning message.  We position the waring message
  2966.  * relative to the icon in the url bar, but if the element doesn't exist,
  2967.  * (e.g., the user remove the url bar from her/his chrome), we anchor at the
  2968.  * top of the window.
  2969.  */
  2970. PROT_PhishMsgDisplayerCanvas.prototype.showAndPositionWarning_ = function() {
  2971.   var refElement = this.doc_.getElementById(this.refElementId_);
  2972.   var message = this.doc_.getElementById(this.messageId_);
  2973.   var tail = this.doc_.getElementById(this.messageTailId_);
  2974.  
  2975.   message.hidden = false;
  2976.   message.style.display = "block";
  2977.  
  2978.   // Determine if the refElement is visible.
  2979.   if (this.isVisibleElement_(refElement)) {
  2980.     // Show tail and position warning relative to refElement.
  2981.     tail.hidden = false;
  2982.     tail.style.display = "block";
  2983.     this.adjustLocation_(message, tail, refElement);
  2984.   } else {
  2985.     // No ref element, position in the top center of window.
  2986.     tail.hidden = true;
  2987.     tail.style.display = "none";
  2988.     this.adjustLocationFloating_(message);
  2989.   }
  2990. }
  2991.  
  2992. /**
  2993.  * @return Boolean true if elt is a visible XUL element.
  2994.  */
  2995. PROT_PhishMsgDisplayerCanvas.prototype.isVisibleElement_ = function(elt) {
  2996.   if (!elt)
  2997.     return false;
  2998.   
  2999.   // If it's on a collapsed/hidden toolbar, the x position is set to 0.
  3000.   if (elt.boxObject.x == 0)
  3001.     return false;
  3002.  
  3003.   return true;
  3004. }
  3005.  
  3006. /**
  3007.  * Hide the warning message from the user.
  3008.  */
  3009. PROT_PhishMsgDisplayerCanvas.prototype.hideMessage_ = function() {
  3010.   G_Debug(this, "Hiding phishing warning.");
  3011.   G_Assert(this, this.messageShowing_, "Hide message called but not showing?");
  3012.  
  3013.   this.messageShowing_ = false;
  3014.   this.repainter_.cancel();
  3015.   this.repainter_ = null;
  3016.  
  3017.   // Hide the warning popup.
  3018.   var message = this.doc_.getElementById(this.messageId_);
  3019.   message.hidden = true;
  3020.   message.style.display = "none";
  3021.   var content = this.doc_.getElementById(this.messageContentId_);
  3022.   content.style.height = "";
  3023.   content.style.overflow = "";
  3024.  
  3025.   var tail = this.doc_.getElementById(this.messageTailId_);
  3026.   tail.hidden = true;
  3027.   tail.style.display = "none";
  3028.  
  3029.   // Remove the canvas element from the chrome document.
  3030.   var pageCanvas = this.doc_.getElementById(this.pageCanvasId_);
  3031.   pageCanvas.parentNode.removeChild(pageCanvas);
  3032.  
  3033.   // Hide the dimmer.
  3034.   var dimarea = this.doc_.getElementById(this.dimAreaId_);
  3035.   dimarea.hidden = true;
  3036. }
  3037.  
  3038.  
  3039. /**
  3040.  * Helper class that periodically repaints the canvas. We repaint
  3041.  * frequently at first, and then back off to a less frequent schedule
  3042.  * at "steady state," and finally just stop altogether. We have to do
  3043.  * this because we're not sure if the page has finished loading when
  3044.  * we first paint the canvas, and because we want to reflect any
  3045.  * dynamically written content into the canvas as it appears in the
  3046.  * page after load.
  3047.  *
  3048.  * @param repaintFunc Function to call to repaint browser.
  3049.  *
  3050.  * @constructor
  3051.  */
  3052. function PROT_PhishMsgCanvasRepainter(repaintFunc) {
  3053.   this.count_ = 0;
  3054.   this.repaintFunc_ = repaintFunc;
  3055.   this.initPeriodMS_ = 500;             // Initially repaint every 500ms
  3056.   this.steadyStateAtMS_ = 10 * 1000;    // Go slowly after 10 seconds,
  3057.   this.steadyStatePeriodMS_ = 3 * 1000; // repainting every 3 seconds, and
  3058.   this.quitAtMS_ = 20 * 1000;           // stop after 20 seconds
  3059.   this.startMS_ = (new Date).getTime();
  3060.   this.alarm_ = new G_Alarm(BindToObject(this.repaint, this), 
  3061.                             this.initPeriodMS_);
  3062. }
  3063.  
  3064. /**
  3065.  * Called periodically to repaint the canvas
  3066.  */
  3067. PROT_PhishMsgCanvasRepainter.prototype.repaint = function() {
  3068.   this.repaintFunc_();
  3069.  
  3070.   var nextRepaint;
  3071.   // If we're in "steady state", use the slow repaint rate, else fast
  3072.   if ((new Date).getTime() - this.startMS_ > this.steadyStateAtMS_)
  3073.     nextRepaint = this.steadyStatePeriodMS_;
  3074.   else 
  3075.     nextRepaint = this.initPeriodMS_;
  3076.  
  3077.   if (!((new Date).getTime() - this.startMS_ > this.quitAtMS_))
  3078.     this.alarm_ = new G_Alarm(BindToObject(this.repaint, this), nextRepaint);
  3079. }
  3080.  
  3081. /**
  3082.  * Called to stop repainting the canvas
  3083.  */
  3084. PROT_PhishMsgCanvasRepainter.prototype.cancel = function() {
  3085.   if (this.alarm_) {
  3086.     this.alarm_.cancel();
  3087.     this.alarm_ = null;
  3088.   }
  3089.   this.repaintFunc_ = null;
  3090. }
  3091. /* ***** BEGIN LICENSE BLOCK *****
  3092.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3093.  *
  3094.  * The contents of this file are subject to the Mozilla Public License Version
  3095.  * 1.1 (the "License"); you may not use this file except in compliance with
  3096.  * the License. You may obtain a copy of the License at
  3097.  * http://www.mozilla.org/MPL/
  3098.  *
  3099.  * Software distributed under the License is distributed on an "AS IS" basis,
  3100.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  3101.  * for the specific language governing rights and limitations under the
  3102.  * License.
  3103.  *
  3104.  * The Original Code is Google Safe Browsing.
  3105.  *
  3106.  * The Initial Developer of the Original Code is Google Inc.
  3107.  * Portions created by the Initial Developer are Copyright (C) 2006
  3108.  * the Initial Developer. All Rights Reserved.
  3109.  *
  3110.  * Contributor(s):
  3111.  *   Fritz Schneider <fritz@google.com> (original author)
  3112.  *
  3113.  * Alternatively, the contents of this file may be used under the terms of
  3114.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  3115.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  3116.  * in which case the provisions of the GPL or the LGPL are applicable instead
  3117.  * of those above. If you wish to allow use of your version of this file only
  3118.  * under the terms of either the GPL or the LGPL, and not to allow others to
  3119.  * use your version of this file under the terms of the MPL, indicate your
  3120.  * decision by deleting the provisions above and replace them with the notice
  3121.  * and other provisions required by the GPL or the LGPL. If you do not delete
  3122.  * the provisions above, a recipient may use your version of this file under
  3123.  * the terms of any one of the MPL, the GPL or the LGPL.
  3124.  *
  3125.  * ***** END LICENSE BLOCK ***** */
  3126.  
  3127.  
  3128. // The warden checks request to see if they are for phishy pages. It
  3129. // does so by either querying a remote server with the URL (advanced
  3130. // protectoin mode) or querying our locally stored blacklists (privacy
  3131. // mode).
  3132. // 
  3133. // When the warden notices a problem, it queries all browser views
  3134. // (each of which corresopnds to an open browser window) to see
  3135. // whether one of them can handle it. A browser view can handle a
  3136. // problem if its browser window has an HTMLDocument loaded with the
  3137. // given URL and that Document hasn't already been flagged as a
  3138. // problem. For every problematic URL we notice loading, at most one
  3139. // Document is flagged as problematic. Otherwise you can get into
  3140. // trouble if multiple concurrent phishy pages load with the same URL.
  3141. //
  3142. // Since we check URLs very early in the request cycle (in a progress
  3143. // listener), the URL might not yet be associated with a Document when
  3144. // we determine that it is phishy. So the the warden retries finding
  3145. // a browser view to handle the problem until one can, or until it
  3146. // determines it should give up (see complicated logic below).
  3147. //
  3148. // The warden has displayers that the browser view uses to render
  3149. // different kinds of warnings (e.g., one that's shown before a page
  3150. // loads as opposed to one that's shown after the page has already
  3151. // loaded).
  3152. //
  3153. // Note: There is a single warden for the whole application.
  3154. //
  3155. // TODO better way to expose displayers/views to browser view
  3156.  
  3157. const kPhishWardenEnabledPref = "browser.safebrowsing.enabled";
  3158. const kPhishWardenRemoteLookups = "browser.safebrowsing.remoteLookups";
  3159.  
  3160. // We have hardcoded URLs that we let people navigate to in order to 
  3161. // check out the warning.
  3162. const kTestUrls = {
  3163.   "http://www.google.com/tools/firefox/safebrowsing/phish-o-rama.html": true,
  3164.   "http://www.mozilla.org/projects/bonecho/anti-phishing/its-a-trap.html": true,
  3165.   "http://www.mozilla.com/firefox/its-a-trap.html": true,
  3166. }
  3167.  
  3168. /**
  3169.  * Abtracts the checking of user/browser actions for signs of
  3170.  * phishing. 
  3171.  *
  3172.  * @param progressListener nsIDocNavStartProgressListener
  3173.  * @constructor
  3174.  */
  3175. function PROT_PhishingWarden(progressListener) {
  3176.   PROT_ListWarden.call(this);
  3177.  
  3178.   this.debugZone = "phishwarden";
  3179.   this.testing_ = false;
  3180.   this.browserViews_ = [];
  3181.  
  3182.   // Use this to query preferences
  3183.   this.prefs_ = new G_Preferences();
  3184.  
  3185.   // Only one displayer so far; perhaps we'll have others in the future
  3186.   this.displayers_ = {
  3187.     "afterload": PROT_PhishMsgDisplayer,
  3188.   };
  3189.  
  3190.   // We use this dude to do lookups on our remote server
  3191.   this.fetcher_ = new PROT_TRFetcher();
  3192.  
  3193.   // We need to know whether we're enabled and whether we're in advanced
  3194.   // mode, so reflect the appropriate preferences into our state.
  3195.  
  3196.   // Read state: should we be checking remote preferences?
  3197.   this.checkRemote_ = this.prefs_.getPref(kPhishWardenRemoteLookups, null);
  3198.   
  3199.   // true if we should use whitelists to suppress remote lookups
  3200.   this.checkWhitelists_ = false;
  3201.  
  3202.   // Get notifications when the remote check preference changes
  3203.   var checkRemotePrefObserver = BindToObject(this.onCheckRemotePrefChanged,
  3204.                                              this);
  3205.   this.prefs_.addObserver(kPhishWardenRemoteLookups, checkRemotePrefObserver);
  3206.  
  3207.   // Global preference to enable the phishing warden
  3208.   this.phishWardenEnabled_ = this.prefs_.getPref(kPhishWardenEnabledPref, null);
  3209.  
  3210.   // Get notifications when the phishing warden enabled pref changes
  3211.   var phishWardenPrefObserver = 
  3212.     BindToObject(this.onPhishWardenEnabledPrefChanged, this);
  3213.   this.prefs_.addObserver(kPhishWardenEnabledPref, phishWardenPrefObserver);
  3214.   
  3215.   // Get notifications when the data provider pref changes
  3216.   var dataProviderPrefObserver =
  3217.     BindToObject(this.onDataProviderPrefChanged, this);
  3218.   this.prefs_.addObserver(kDataProviderIdPref, dataProviderPrefObserver);
  3219.  
  3220.   // hook up our browser listener
  3221.   this.progressListener_ = progressListener;
  3222.   this.progressListener_.callback = this;
  3223.   this.progressListener_.enabled = this.phishWardenEnabled_;
  3224.   // ms to wait after a request has started before firing JS callback
  3225.   this.progressListener_.delay = 1500;
  3226.  
  3227.   // object to keep track of request errors if we're in remote check mode
  3228.   this.requestBackoff_ = new RequestBackoff(3 /* num errors */,
  3229.                                    10*60*1000 /* error time, 10min */,
  3230.                                    10*60*1000 /* backoff interval, 10min */,
  3231.                                    6*60*60*1000 /* max backoff, 6hr */);
  3232.  
  3233.   G_Debug(this, "phishWarden initialized");
  3234. }
  3235.  
  3236. PROT_PhishingWarden.inherits(PROT_ListWarden);
  3237.  
  3238. /**
  3239.  * We implement nsIWebProgressListener
  3240.  */
  3241. PROT_PhishingWarden.prototype.QueryInterface = function(iid) {
  3242.   if (iid.equals(Ci.nsISupports) || 
  3243.       iid.equals(Ci.nsIWebProgressListener) ||
  3244.       iid.equals(Ci.nsISupportsWeakReference))
  3245.     return this;
  3246.   throw Components.results.NS_ERROR_NO_INTERFACE;
  3247. }
  3248.  
  3249. /**
  3250.  * Cleanup on shutdown.
  3251.  */
  3252. PROT_PhishingWarden.prototype.shutdown = function() {
  3253.   this.progressListener_.callback = null;
  3254.   this.progressListener_ = null;
  3255.   this.listManager_ = null;
  3256. }
  3257.  
  3258. /**
  3259.  * When a preference (either advanced features or the phishwarden
  3260.  * enabled) changes, we might have to start or stop asking for updates. 
  3261.  * 
  3262.  * This is a little tricky; we start or stop management only when we
  3263.  * have complete information we can use to determine whether we
  3264.  * should.  It could be the case that one pref or the other isn't set
  3265.  * yet (e.g., they haven't opted in/out of advanced features). So do
  3266.  * nothing unless we have both pref values -- we get notifications for
  3267.  * both, so eventually we will start correctly.
  3268.  */ 
  3269. PROT_PhishingWarden.prototype.maybeToggleUpdateChecking = function() {
  3270.   if (this.testing_)
  3271.     return;
  3272.  
  3273.   var phishWardenEnabled = this.prefs_.getPref(kPhishWardenEnabledPref, null);
  3274.  
  3275.   this.checkRemote_ = this.prefs_.getPref(kPhishWardenRemoteLookups, null);
  3276.  
  3277.   G_Debug(this, "Maybe toggling update checking. " +
  3278.           "Warden enabled? " + phishWardenEnabled + " || " +
  3279.           "Check remote? " + this.checkRemote_);
  3280.  
  3281.   // Do nothing unless both prefs are set.  They can be null (unset), true, or
  3282.   // false.
  3283.   if (phishWardenEnabled === null || this.checkRemote_ === null)
  3284.     return;
  3285.  
  3286.   // We update and save to disk all tables if we don't have remote checking
  3287.   // enabled.
  3288.   if (phishWardenEnabled === true) {
  3289.     // If anti-phishing is enabled, we always download the local files to
  3290.     // use in case remote lookups fail.
  3291.     this.enableBlacklistTableUpdates();
  3292.     this.enableWhitelistTableUpdates();
  3293.  
  3294.     if (this.checkRemote_ === true) {
  3295.       // Remote lookup mode
  3296.       // We check to see if the local list update host is the same as the
  3297.       // remote lookup host.  If they are the same, then we don't bother
  3298.       // to do a remote url check if the url is in the whitelist.
  3299.       var ioService = Cc["@mozilla.org/network/io-service;1"]
  3300.                      .getService(Ci.nsIIOService);
  3301.       var updateHost = '';
  3302.       var lookupHost = '';
  3303.       try {
  3304.         var url = ioService.newURI(gDataProvider.getUpdateURL(),
  3305.                                          null, null);
  3306.         updateHost = url.asciiHost;
  3307.       } catch (e) { }
  3308.       try {
  3309.         var url = ioService.newURI(gDataProvider.getLookupURL(),
  3310.                                          null, null);
  3311.         lookupHost = url.asciiHost;
  3312.       } catch (e) { }
  3313.  
  3314.       if (updateHost && lookupHost && updateHost == lookupHost) {
  3315.         // The data provider for local lists and remote lookups is the
  3316.         // same, enable whitelist lookup suppression.
  3317.         this.checkWhitelists_ = true;
  3318.       } else {
  3319.         // hosts don't match, don't use whitelist suppression
  3320.         this.checkWhitelists_ = false;
  3321.       }
  3322.     }
  3323.   } else {
  3324.     // Anti-phishing is off, disable table updates
  3325.     this.disableBlacklistTableUpdates();
  3326.     this.disableWhitelistTableUpdates();
  3327.   }
  3328. }
  3329.  
  3330. /**
  3331.  * Controllers register their browser views with us
  3332.  *
  3333.  * @param view Reference to a browser view 
  3334.  */
  3335. PROT_PhishingWarden.prototype.addBrowserView = function(view) {
  3336.   G_Debug(this, "New browser view registered.");
  3337.   this.browserViews_.push(view);
  3338. }
  3339.  
  3340. /**
  3341.  * Controllers unregister their views when their window closes
  3342.  *
  3343.  * @param view Reference to a browser view 
  3344.  */
  3345. PROT_PhishingWarden.prototype.removeBrowserView = function(view) {
  3346.   for (var i = 0; i < this.browserViews_.length; i++)
  3347.     if (this.browserViews_[i] === view) {
  3348.       G_Debug(this, "Browser view unregistered.");
  3349.       this.browserViews_.splice(i, 1);
  3350.       return;
  3351.     }
  3352.   G_Assert(this, false, "Tried to unregister non-existent browser view!");
  3353. }
  3354.  
  3355. /**
  3356.  * Deal with a user changing the pref that says whether we should check
  3357.  * the remote server (i.e., whether we're in advanced mode)
  3358.  *
  3359.  * @param prefName Name of the pref holding the value indicating whether
  3360.  *                 we should check remote server
  3361.  */
  3362. PROT_PhishingWarden.prototype.onCheckRemotePrefChanged = function(prefName) {
  3363.   this.checkRemote_ = this.prefs_.getBoolPrefOrDefault(prefName,
  3364.                                                        this.checkRemote_);
  3365.   this.requestBackoff_.reset();
  3366.   this.maybeToggleUpdateChecking();
  3367. }
  3368.  
  3369. /**
  3370.  * Deal with a user changing the pref that says whether we should 
  3371.  * enable the phishing warden (i.e., that SafeBrowsing is active)
  3372.  *
  3373.  * @param prefName Name of the pref holding the value indicating whether
  3374.  *                 we should enable the phishing warden
  3375.  */
  3376. PROT_PhishingWarden.prototype.onPhishWardenEnabledPrefChanged = function(
  3377.                                                                     prefName) {
  3378.   this.phishWardenEnabled_ = 
  3379.     this.prefs_.getBoolPrefOrDefault(prefName, this.phishWardenEnabled_);
  3380.   this.requestBackoff_.reset();
  3381.   this.maybeToggleUpdateChecking();
  3382.   this.progressListener_.enabled = this.phishWardenEnabled_;
  3383. }
  3384.  
  3385. /**
  3386.  * Event fired when the user changes data providers.
  3387.  */
  3388. PROT_PhishingWarden.prototype.onDataProviderPrefChanged = function(prefName) {
  3389.   // We want to reset request backoff state since it's a different provider.
  3390.   this.requestBackoff_.reset();
  3391.  
  3392.   // If we have a new data provider and we're doing remote lookups, then
  3393.   // we may want to use whitelist lookup suppression or change which
  3394.   // tables are being downloaded.
  3395.   if (this.checkRemote_) {
  3396.     this.maybeToggleUpdateChecking();
  3397.   }
  3398. }
  3399.  
  3400. /**
  3401.  * A request for a Document has been initiated somewhere. Check it!
  3402.  *
  3403.  * @param request
  3404.  * @param url
  3405.  */ 
  3406. PROT_PhishingWarden.prototype.onDocNavStart = function(request, url) {
  3407.   G_Debug(this, "checkRemote: " +
  3408.           (this.checkRemote_ ? "yes" : "no"));
  3409.  
  3410.   // If we're on a test page, trigger the warning.
  3411.   // XXX Do we still need a test url or should each provider just put
  3412.   // it in their local list?
  3413.   if (this.isBlacklistTestURL(url)) {
  3414.     this.houstonWeHaveAProblem_(request);
  3415.     return;
  3416.   }
  3417.  
  3418.   // Make a remote lookup check if the pref is selected and if we haven't
  3419.   // triggered server backoff.  Otherwise, make a local check.
  3420.   if (this.checkRemote_ && this.requestBackoff_.canMakeRequest()) {
  3421.     // If we can use whitelists to suppress remote lookups, do so.
  3422.     if (this.checkWhitelists_) {
  3423.       var maybeRemoteCheck = BindToObject(this.maybeMakeRemoteCheck_,
  3424.                                           this,
  3425.                                           url,
  3426.                                           request);
  3427.       this.isWhiteURL(url, maybeRemoteCheck);
  3428.     } else {
  3429.       // Do a remote lookup (don't check whitelists)
  3430.       this.fetcher_.get(url,
  3431.                         BindToObject(this.onTRFetchComplete,
  3432.                                      this,
  3433.                                      url,
  3434.                                      request));
  3435.     }
  3436.   } else {
  3437.     // Check the local lists for a match.
  3438.     var evilCallback = BindToObject(this.localListMatch_,
  3439.                                     this,
  3440.                                     url,
  3441.                                     request);
  3442.     this.isEvilURL(url, evilCallback);
  3443.   }
  3444. }
  3445.  
  3446. /** 
  3447.  * Callback from whitelist check when remote lookups is on.
  3448.  * @param url String url to lookup
  3449.  * @param request nsIRequest object
  3450.  * @param status int enum from callback (PROT_ListWarden.IN_BLACKLIST,
  3451.  *    PROT_ListWarden.IN_WHITELIST, PROT_ListWarden.NOT_FOUND)
  3452.  */
  3453. PROT_PhishingWarden.prototype.maybeMakeRemoteCheck_ = function(url, request, status) {
  3454.   if (PROT_ListWarden.IN_WHITELIST == status)
  3455.     return;
  3456.  
  3457.   G_Debug(this, "Local whitelist lookup failed");
  3458.   this.fetcher_.get(url,
  3459.                     BindToObject(this.onTRFetchComplete,
  3460.                                  this,
  3461.                                  url,
  3462.                                  request));
  3463. }
  3464.  
  3465. /**
  3466.  * Invoked with the result of a lookupserver request.
  3467.  *
  3468.  * @param url String the URL we looked up
  3469.  * @param request The nsIRequest in which we're interested
  3470.  * @param trValues Object holding name/value pairs parsed from the
  3471.  *                 lookupserver's response
  3472.  * @param status Number HTTP status code or NS_ERROR_NOT_AVAILABLE if there's
  3473.  *               an HTTP error
  3474.  */
  3475. PROT_PhishingWarden.prototype.onTRFetchComplete = function(url,
  3476.                                                            request,
  3477.                                                            trValues,
  3478.                                                            status) {
  3479.   // Did the remote http request succeed?  If not, we fall back on
  3480.   // local lists.
  3481.   if (status == Components.results.NS_ERROR_NOT_AVAILABLE ||
  3482.       this.requestBackoff_.isErrorStatus_(status)) {
  3483.     this.requestBackoff_.noteServerResponse(status);
  3484.  
  3485.     G_Debug(this, "remote check failed, using local lists instead");
  3486.     var evilCallback = BindToObject(this.localListMatch_,
  3487.                                     this,
  3488.                                     url,
  3489.                                     request);
  3490.     this.isEvilURL(url, evilCallback);
  3491.   } else {
  3492.     var callback = BindToObject(this.houstonWeHaveAProblem_, this, request);
  3493.     this.checkRemoteData(callback, trValues);
  3494.   }
  3495. }
  3496.  
  3497. /**
  3498.  * One of our Check* methods found a problem with a request. Why do we
  3499.  * need to keep the nsIRequest (instead of just passing in the URL)? 
  3500.  * Because we need to know when to stop looking for the URL its
  3501.  * fetching, and to know this we need the nsIRequest.isPending flag.
  3502.  *
  3503.  * @param request nsIRequest that is problematic
  3504.  */
  3505. PROT_PhishingWarden.prototype.houstonWeHaveAProblem_ = function(request) {
  3506.  
  3507.   // We have a problem request that might or might not be associated
  3508.   // with a Document that's currently in a browser. If it is, we 
  3509.   // want that Document. If it's not, we want to give it a chance to 
  3510.   // be loaded. See below for complete details.
  3511.  
  3512.   if (this.maybeLocateProblem_(request))       // Cases 1 and 2 (see below)
  3513.     return;
  3514.  
  3515.   // OK, so the request isn't associated with any currently accessible
  3516.   // Document, and we want to give it the chance to be. We don't want
  3517.   // to retry forever (e.g., what if the Document was already displayed
  3518.   // and navigated away from?), so we'll use nsIRequest.isPending to help
  3519.   // us decide what to do.
  3520.   //
  3521.   // Aácomplication arises because there is a lag between when a
  3522.   // request transitions from pending to not-pending and when it's
  3523.   // associated with a Document in a browser. The transition from
  3524.   // pending to not occurs just before the notification corresponding
  3525.   // to NavWatcher.DOCNAVSTART (see NavWatcher), but the association
  3526.   // occurs afterwards. Unfortunately, we're probably in DOCNAVSTART.
  3527.   // 
  3528.   // Diagnosis by Darin:
  3529.   // ---------------------------------------------------------------------------
  3530.   // Here's a summary of what happens:
  3531.   //
  3532.   //   RestorePresentation() {
  3533.   //     Dispatch_OnStateChange(dummy_request, STATE_START)
  3534.   //     PostCompletionEvent()
  3535.   //   }
  3536.   //
  3537.   //   CompletionEvent() {
  3538.   //     ReallyRestorePresentation()
  3539.   //     Dispatch_OnStateChange(dummy_request, STATE_STOP)
  3540.   //   }
  3541.   //
  3542.   // So, now your code receives that initial OnStateChange event and sees
  3543.   // that the dummy_request is not pending and not loaded in any window.
  3544.   // So, you put a timeout(0) event in the queue.  Then, the CompletionEvent
  3545.   // is added to the queue.  The stack unwinds....
  3546.   //
  3547.   // Your timeout runs, and you find that the dummy_request is still not
  3548.   // pending and not loaded in any window.  Then the CompletionEvent
  3549.   // runs, and it hooks up the cached presentation.
  3550.   // 
  3551.   // https://bugzilla.mozilla.org/show_bug.cgi?id=319527
  3552.   // ---------------------------------------------------------------------------
  3553.   //
  3554.   // So the logic is:
  3555.   //
  3556.   //         request     found an unhandled          
  3557.   //  case   pending?    doc with the url?         action
  3558.   //  ----------------------------------------------------------------
  3559.   //   1      yes             yes           Use that doc (handled above)
  3560.   //   2      no              yes           Use that doc (handled above)
  3561.   //   3      yes             no            Retry
  3562.   //   4      no              no            Retry twice (case described above)
  3563.   //
  3564.   // We don't get into trouble with Docs with the same URL "stealing" the 
  3565.   // warning because there is exactly one warning signaled per nav to 
  3566.   // a problem URL, and each Doc can be marked as problematic at most once.
  3567.  
  3568.   if (request.isPending()) {        // Case 3
  3569.  
  3570.     G_Debug(this, "Can't find problem Doc; Req pending. Retrying.");
  3571.     new G_Alarm(BindToObject(this.houstonWeHaveAProblem_, 
  3572.                              this, 
  3573.                              request), 
  3574.                 200 /*ms*/);
  3575.  
  3576.   } else {                          // Case 4
  3577.  
  3578.     G_Debug(this, 
  3579.             "Can't find problem Doc; Req completed. Retrying at most twice.");
  3580.     new G_ConditionalAlarm(BindToObject(this.maybeLocateProblem_, 
  3581.                                         this, 
  3582.                                         request),
  3583.                            0 /* next event loop */, 
  3584.                            true /* repeat */, 
  3585.                            2 /* at most twice */);
  3586.   }
  3587. }
  3588.  
  3589. /**
  3590.  * Query all browser views we know about and offer them the chance to
  3591.  * handle the problematic request.
  3592.  *
  3593.  * @param request nsIRequest that is problematic
  3594.  * 
  3595.  * @returns Boolean indicating if someone decided to handle it
  3596.  */
  3597. PROT_PhishingWarden.prototype.maybeLocateProblem_ = function(request) {
  3598.   G_Debug(this, "Trying to find the problem.");
  3599.  
  3600.   G_Debug(this, this.browserViews_.length + " browser views to check.");
  3601.   for (var i = 0; i < this.browserViews_.length; i++) {
  3602.     if (this.browserViews_[i].tryToHandleProblemRequest(this, request)) {
  3603.       G_Debug(this, "Found browser view willing to handle problem!");
  3604.       return true;
  3605.     }
  3606.     G_Debug(this, "wrong browser view");
  3607.   }
  3608.   return false;
  3609. }
  3610.  
  3611. /**
  3612.  * Indicates if this URL is one of the possible blacklist test URLs.
  3613.  * These test URLs should always be considered as phishy.
  3614.  *
  3615.  * @param url URL to check 
  3616.  * @return A boolean indicating whether this is one of our blacklist
  3617.  *         test URLs
  3618.  */
  3619. PROT_PhishingWarden.prototype.isBlacklistTestURL = function(url) {
  3620.   // Explicitly check for URL so we don't get JS warnings in strict mode.
  3621.   if (kTestUrls[url])
  3622.     return true;
  3623.   return false;
  3624. }
  3625.  
  3626. /**
  3627.  * Callback for found local blacklist match.  First we report that we have
  3628.  * a blacklist hit, then we bring up the warning dialog.
  3629.  * @param status Number enum from callback (PROT_ListWarden.IN_BLACKLIST,
  3630.  *    PROT_ListWarden.IN_WHITELIST, PROT_ListWarden.NOT_FOUND)
  3631.  */
  3632. PROT_PhishingWarden.prototype.localListMatch_ = function(url, request, status) {
  3633.   if (PROT_ListWarden.IN_BLACKLIST != status)
  3634.     return;
  3635.  
  3636.   // Maybe send a report
  3637.   (new PROT_Reporter).report("phishblhit", url);
  3638.   this.houstonWeHaveAProblem_(request);
  3639. }
  3640.  
  3641. /**
  3642.  * Examine data fetched from a lookup server for evidence of a
  3643.  * phishing problem. 
  3644.  *
  3645.  * @param callback Function to invoke if there is a problem. 
  3646.  * @param trValues Object containing name/value pairs the server returned
  3647.  */
  3648. PROT_PhishingWarden.prototype.checkRemoteData = function(callback, 
  3649.                                                          trValues) {
  3650.  
  3651.   if (!trValues) {
  3652.     G_Debug(this, "Didn't get TR values from the server.");
  3653.     return;
  3654.   }
  3655.   
  3656.   G_Debug(this, "Page has phishiness " + trValues["phishy"]);
  3657.  
  3658.   if (trValues["phishy"] == 1) {     // It's on our blacklist 
  3659.     G_Debug(this, "Remote blacklist hit");
  3660.     callback(this);
  3661.   } else {
  3662.     G_Debug(this, "Remote blacklist miss");
  3663.   }
  3664. }
  3665.  
  3666. /* ***** BEGIN LICENSE BLOCK *****
  3667.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3668.  *
  3669.  * The contents of this file are subject to the Mozilla Public License Version
  3670.  * 1.1 (the "License"); you may not use this file except in compliance with
  3671.  * the License. You may obtain a copy of the License at
  3672.  * http://www.mozilla.org/MPL/
  3673.  *
  3674.  * Software distributed under the License is distributed on an "AS IS" basis,
  3675.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  3676.  * for the specific language governing rights and limitations under the
  3677.  * License.
  3678.  *
  3679.  * The Original Code is Google Safe Browsing.
  3680.  *
  3681.  * The Initial Developer of the Original Code is Google Inc.
  3682.  * Portions created by the Initial Developer are Copyright (C) 2006
  3683.  * the Initial Developer. All Rights Reserved.
  3684.  *
  3685.  * Contributor(s):
  3686.  *   Fritz Schneider <fritz@google.com> (original author)
  3687.  *
  3688.  * Alternatively, the contents of this file may be used under the terms of
  3689.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  3690.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  3691.  * in which case the provisions of the GPL or the LGPL are applicable instead
  3692.  * of those above. If you wish to allow use of your version of this file only
  3693.  * under the terms of either the GPL or the LGPL, and not to allow others to
  3694.  * use your version of this file under the terms of the MPL, indicate your
  3695.  * decision by deleting the provisions above and replace them with the notice
  3696.  * and other provisions required by the GPL or the LGPL. If you do not delete
  3697.  * the provisions above, a recipient may use your version of this file under
  3698.  * the terms of any one of the MPL, the GPL or the LGPL.
  3699.  *
  3700.  * ***** END LICENSE BLOCK ***** */
  3701.  
  3702.  
  3703. // A tiny class to do reporting for us. We report interesting user actions
  3704. // such as the user hitting a blacklisted page, and the user accepting
  3705. // or declining the warning.
  3706. //
  3707. // Each report has a subject and data. Current reports are:
  3708. //
  3709. // subject         data     meaning
  3710. // --------------------------------
  3711. // phishnavaway    url      the user navigated away from a phishy page
  3712. // phishdecline    url      the user declined our warning
  3713. // phishaccept     url      the user accepted our warning
  3714. // phishblhit      url      the user loaded a phishing page
  3715. //
  3716. // We only send reports in advanced protection mode, and even then we
  3717. // strip cookies from the request before sending it.
  3718.  
  3719. /**
  3720.  * A very complicated class to send pings to the provider. The class does
  3721.  * nothing if we're not in advanced protection mode.
  3722.  *
  3723.  * @constructor
  3724.  */
  3725. function PROT_Reporter() {
  3726.   this.debugZone = "reporter";
  3727.   this.prefs_ = new G_Preferences();
  3728. }
  3729.  
  3730. /**
  3731.  * Send a report!
  3732.  *
  3733.  * @param subject String indicating what this report is about (will be 
  3734.  *                urlencoded)
  3735.  * @param data String giving extra information about this report (will be 
  3736.  *                urlencoded)
  3737.  */
  3738. PROT_Reporter.prototype.report = function(subject, data) {
  3739.   // Send a report iff we're in advanced protection mode
  3740.   if (!this.prefs_.getPref(kPhishWardenRemoteLookups, false))
  3741.     return;
  3742.   // Make sure a report url is defined
  3743.   var url = gDataProvider.getReportURL();
  3744.  
  3745.   // Report url is optional, so we just ignore the request if a report
  3746.   // url isn't provided.
  3747.   if (!url)
  3748.     return;
  3749.  
  3750.   url += "evts=" + encodeURIComponent(subject)
  3751.          + "&evtd=" + encodeURIComponent(data);
  3752.   G_Debug(this, "Sending report: " + url);
  3753.   (new PROT_XMLFetcher(true /* strip cookies */)).get(url, null /* no cb */);
  3754. }
  3755. /* ***** BEGIN LICENSE BLOCK *****
  3756.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3757.  *
  3758.  * The contents of this file are subject to the Mozilla Public License Version
  3759.  * 1.1 (the "License"); you may not use this file except in compliance with
  3760.  * the License. You may obtain a copy of the License at
  3761.  * http://www.mozilla.org/MPL/
  3762.  *
  3763.  * Software distributed under the License is distributed on an "AS IS" basis,
  3764.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  3765.  * for the specific language governing rights and limitations under the
  3766.  * License.
  3767.  *
  3768.  * The Original Code is Google Safe Browsing.
  3769.  *
  3770.  * The Initial Developer of the Original Code is Google Inc.
  3771.  * Portions created by the Initial Developer are Copyright (C) 2006
  3772.  * the Initial Developer. All Rights Reserved.
  3773.  *
  3774.  * Contributor(s):
  3775.  *   Fritz Schneider <fritz@google.com> (original author)
  3776.  *
  3777.  * Alternatively, the contents of this file may be used under the terms of
  3778.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  3779.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  3780.  * in which case the provisions of the GPL or the LGPL are applicable instead
  3781.  * of those above. If you wish to allow use of your version of this file only
  3782.  * under the terms of either the GPL or the LGPL, and not to allow others to
  3783.  * use your version of this file under the terms of the MPL, indicate your
  3784.  * decision by deleting the provisions above and replace them with the notice
  3785.  * and other provisions required by the GPL or the LGPL. If you do not delete
  3786.  * the provisions above, a recipient may use your version of this file under
  3787.  * the terms of any one of the MPL, the GPL or the LGPL.
  3788.  *
  3789.  * ***** END LICENSE BLOCK ***** */
  3790.  
  3791.  
  3792. // A helper class that does "trustrank" lookups on a remote
  3793. // server. Right now this lookup just indicates if a page is
  3794. // phishing. The response format is protocol4 name/value pairs.
  3795. // 
  3796. // Since we're sending full URLs to the server, we try to encrypt
  3797. // them before transmission. Else HTTPS query params could leak.
  3798.  
  3799. /**
  3800.  * A helper class that fetches trustrank values, parses them, and
  3801.  * passes them via an object to a callback.
  3802.   * 
  3803.  * @constructor
  3804.  */
  3805. function PROT_TRFetcher(opt_noCrypto) {
  3806.   this.debugZone = "trfetcher";
  3807.   this.useCrypto_ = !opt_noCrypto;
  3808.   this.protocol4Parser_ = new G_Protocol4Parser();
  3809.  
  3810.   // We lazily instantiate the UrlCrypto object due to:
  3811.   // https://bugzilla.mozilla.org/show_bug.cgi?id=321024
  3812.   //
  3813.   // Otherwise here we would use:
  3814.   // this.urlCrypto_ = new PROT_UrlCrypto();
  3815. }
  3816.  
  3817. PROT_TRFetcher.TRY_REKEYING_RESPONSE = "pleaserekey";
  3818.  
  3819. /**
  3820.  * Get the URL of the request that will fetch us TR for the argument URL
  3821.  *
  3822.  * @param url String containing the URL we'd like to fetch info about
  3823.  *
  3824.  * @returns String containing the url we should use to fetch tr info
  3825.  */
  3826. PROT_TRFetcher.prototype.getRequestURL_ = function(url) {
  3827.  
  3828.   if (!this.urlCrypto_)
  3829.     this.urlCrypto_ = new PROT_UrlCrypto();
  3830.  
  3831.   G_Debug(this, "Fetching for " + url);
  3832.     
  3833.   var requestURL = gDataProvider.getLookupURL();
  3834.   if (!requestURL)
  3835.     return null;
  3836.  
  3837.   if (this.useCrypto_) {
  3838.     var maybeCryptedParams = this.urlCrypto_.maybeCryptParams({ "q": url});
  3839.     
  3840.     for (var param in maybeCryptedParams) 
  3841.       requestURL += param + "=" + 
  3842.                     encodeURIComponent(maybeCryptedParams[param]) + "&";
  3843.   } else {
  3844.     requestURL += "q=" + encodeURIComponent(url);
  3845.   }
  3846.  
  3847.   G_Debug(this, "Request URL: " + requestURL);
  3848.  
  3849.   return requestURL;
  3850. };
  3851.  
  3852. /**
  3853.  * Fetches information about a page.
  3854.  * 
  3855.  * @param forPage URL for which to fetch info
  3856.  *
  3857.  * @param callback Function to call back when complete.
  3858.  */
  3859. PROT_TRFetcher.prototype.get = function(forPage, callback) {
  3860.   
  3861.   var url = this.getRequestURL_(forPage);
  3862.   if (!url) {
  3863.     G_Debug(this, "No remote lookup url.");
  3864.     return;
  3865.   }
  3866.   var closure = BindToObject(this.onFetchComplete_, this, callback);
  3867.   (new PROT_XMLFetcher()).get(url, closure);
  3868. };
  3869.  
  3870. /**
  3871.  * Invoked when a fetch has completed.
  3872.  *
  3873.  * @param callback Function to invoke with parsed response object
  3874.  * @param responseText Text of the protocol4 message
  3875.  * @param httpStatus Number HTTP status code or NS_ERROR_NOT_AVAILABLE if the
  3876.  *     request failed
  3877.  */
  3878. PROT_TRFetcher.prototype.onFetchComplete_ = function(callback, responseText,
  3879.                                                      httpStatus) {
  3880.   
  3881.   var responseObj = this.extractResponse_(responseText);
  3882.  
  3883.   // The server might tell us to rekey, for example if it sees that
  3884.   // our request was unencrypted (meaning that we might not yet have
  3885.   // a key). If so, pass this hint along to the crypto key manager.
  3886.  
  3887.   if (responseObj[PROT_TRFetcher.TRY_REKEYING_RESPONSE] == "1" &&
  3888.       this.urlCrypto_) {
  3889.     G_Debug(this, "We're supposed to re-key. Trying.");
  3890.     var manager = this.urlCrypto_.getManager();
  3891.     if (manager)
  3892.       manager.maybeReKey();
  3893.   }
  3894.  
  3895.   G_Debug(this, "TR Response:");
  3896.   for (var field in responseObj)
  3897.     G_Debug(this, field + "=" + responseObj[field]);
  3898.  
  3899.   callback(responseObj, httpStatus);
  3900. };
  3901.  
  3902. /**
  3903.  * Parse a protocol4 message (lookup server response)
  3904.  * 
  3905.  * @param responseText String containing the server's response
  3906.  *
  3907.  * @returns Object containing the returned values or null if no
  3908.  *          response was received
  3909.  */
  3910. PROT_TRFetcher.prototype.extractResponse_ = function(responseText) {
  3911.   return this.protocol4Parser_.parse(responseText);
  3912. };
  3913.  
  3914. //@line 27 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/browser/components/safebrowsing/src/nsSafebrowsingApplication.js"
  3915.  
  3916. var modScope = this;
  3917. function Init() {
  3918.   var jslib = Cc["@mozilla.org/url-classifier/jslib;1"]
  3919.               .getService().wrappedJSObject;
  3920.   modScope.String.prototype.startsWith = jslib.String.prototype.startsWith;
  3921.   modScope.G_Debug = jslib.G_Debug;
  3922.   modScope.G_Assert = jslib.G_Assert;
  3923.   modScope.G_Alarm = jslib.G_Alarm;
  3924.   modScope.G_ConditionalAlarm = jslib.G_ConditionalAlarm;
  3925.   modScope.G_ObserverWrapper = jslib.G_ObserverWrapper;
  3926.   modScope.G_Preferences = jslib.G_Preferences;
  3927.   modScope.PROT_XMLFetcher = jslib.PROT_XMLFetcher;
  3928.   modScope.BindToObject = jslib.BindToObject;
  3929.   modScope.G_Protocol4Parser = jslib.G_Protocol4Parser;
  3930.   modScope.G_ObjectSafeMap = jslib.G_ObjectSafeMap;
  3931.   modScope.PROT_UrlCrypto = jslib.PROT_UrlCrypto;
  3932.   modScope.RequestBackoff = jslib.RequestBackoff;
  3933.   
  3934.   // We only need to call Init once
  3935.   modScope.Init = function() {};
  3936. }
  3937.  
  3938. // Module object
  3939. function SafebrowsingApplicationMod() {
  3940.   this.firstTime = true;
  3941.   this.cid = Components.ID("{c64d0bcb-8270-4ca7-a0b3-3380c8ffecb5}");
  3942.   this.progid = "@mozilla.org/safebrowsing/application;1";
  3943. }
  3944.  
  3945. SafebrowsingApplicationMod.prototype.registerSelf = function(compMgr, fileSpec, loc, type) {
  3946.   if (this.firstTime) {
  3947.     this.firstTime = false;
  3948.     throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  3949.   }
  3950.   compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
  3951.   compMgr.registerFactoryLocation(this.cid,
  3952.                                   "Safebrowsing Application Module",
  3953.                                   this.progid,
  3954.                                   fileSpec,
  3955.                                   loc,
  3956.                                   type);
  3957. };
  3958.  
  3959. SafebrowsingApplicationMod.prototype.getClassObject = function(compMgr, cid, iid) {  
  3960.   if (!cid.equals(this.cid))
  3961.     throw Components.results.NS_ERROR_NO_INTERFACE;
  3962.   if (!iid.equals(Ci.nsIFactory))
  3963.     throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  3964.  
  3965.   return this.factory;
  3966. }
  3967.  
  3968. SafebrowsingApplicationMod.prototype.canUnload = function(compMgr) {
  3969.   return true;
  3970. }
  3971.  
  3972. SafebrowsingApplicationMod.prototype.factory = {
  3973.   createInstance: function(outer, iid) {
  3974.     if (outer != null)
  3975.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  3976.     Init();
  3977.     return new PROT_Application();
  3978.   }
  3979. };
  3980.  
  3981. var ApplicationModInst = new SafebrowsingApplicationMod();
  3982.  
  3983. function NSGetModule(compMgr, fileSpec) {
  3984.   return ApplicationModInst;
  3985. }
  3986.