home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / firefox / components / nsUrlClassifierTable.js < prev    next >
Encoding:
JavaScript  |  2006-08-18  |  42.6 KB  |  1,354 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is Url Classifier code
  15.  *
  16.  * The Initial Developer of the Original Code is
  17.  * Google Inc.
  18.  * Portions created by the Initial Developer are Copyright (C) 2006
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *   Tony Chang <tony@ponderer.org>
  23.  *
  24.  * Alternatively, the contents of this file may be used under the terms of
  25.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  26.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27.  * in which case the provisions of the GPL or the LGPL are applicable instead
  28.  * of those above. If you wish to allow use of your version of this file only
  29.  * under the terms of either the GPL or the LGPL, and not to allow others to
  30.  * use your version of this file under the terms of the MPL, indicate your
  31.  * decision by deleting the provisions above and replace them with the notice
  32.  * and other provisions required by the GPL or the LGPL. If you do not delete
  33.  * the provisions above, a recipient may use your version of this file under
  34.  * the terms of any one of the MPL, the GPL or the LGPL.
  35.  *
  36.  * ***** END LICENSE BLOCK ***** */
  37.  
  38. const Cc = Components.classes;
  39. const Ci = Components.interfaces;
  40.  
  41. // js/lang.js is needed for Function.prototype.inherts
  42. /* ***** BEGIN LICENSE BLOCK *****
  43.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  44.  *
  45.  * The contents of this file are subject to the Mozilla Public License Version
  46.  * 1.1 (the "License"); you may not use this file except in compliance with
  47.  * the License. You may obtain a copy of the License at
  48.  * http://www.mozilla.org/MPL/
  49.  *
  50.  * Software distributed under the License is distributed on an "AS IS" basis,
  51.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  52.  * for the specific language governing rights and limitations under the
  53.  * License.
  54.  *
  55.  * The Original Code is Google Safe Browsing.
  56.  *
  57.  * The Initial Developer of the Original Code is Google Inc.
  58.  * Portions created by the Initial Developer are Copyright (C) 2006
  59.  * the Initial Developer. All Rights Reserved.
  60.  *
  61.  * Contributor(s):
  62.  *   Aaron Boodman <aa@google.com> (original author)
  63.  *
  64.  * Alternatively, the contents of this file may be used under the terms of
  65.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  66.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  67.  * in which case the provisions of the GPL or the LGPL are applicable instead
  68.  * of those above. If you wish to allow use of your version of this file only
  69.  * under the terms of either the GPL or the LGPL, and not to allow others to
  70.  * use your version of this file under the terms of the MPL, indicate your
  71.  * decision by deleting the provisions above and replace them with the notice
  72.  * and other provisions required by the GPL or the LGPL. If you do not delete
  73.  * the provisions above, a recipient may use your version of this file under
  74.  * the terms of any one of the MPL, the GPL or the LGPL.
  75.  *
  76.  * ***** END LICENSE BLOCK ***** */
  77.  
  78. // This file has pure js helper functions. Hence you'll find metion
  79. // of browser-specific features in here.
  80.  
  81.  
  82. /**
  83.  * lang.js - The missing JavaScript language features
  84.  *
  85.  * WARNING: This class adds members to the prototypes of String, Array, and
  86.  * Function for convenience.
  87.  *
  88.  * The tradeoff is that the for/in statement will not work properly for those
  89.  * objects when this library is used.
  90.  *
  91.  * To work around this for Arrays, you may want to use the forEach() method,
  92.  * which is more fun and easier to read.
  93.  */
  94.  
  95. /**
  96.  * Returns true if the specified value is |null|
  97.  */
  98. function isNull(val) {
  99.   return val === null;
  100. }
  101.  
  102. /**
  103.  * Returns true if the specified value is an array
  104.  */
  105. function isArray(val) {
  106.   return isObject(val) && val.constructor == Array;
  107. }
  108.  
  109. /**
  110.  * Returns true if the specified value is a string
  111.  */
  112. function isString(val) {
  113.   return typeof val == "string";
  114. }
  115.  
  116. /**
  117.  * Returns true if the specified value is a boolean
  118.  */
  119. function isBoolean(val) {
  120.   return typeof val == "boolean";
  121. }
  122.  
  123. /**
  124.  * Returns true if the specified value is a number
  125.  */
  126. function isNumber(val) {
  127.   return typeof val == "number";
  128. }
  129.  
  130. /**
  131.  * Returns true if the specified value is a function
  132.  */
  133. function isFunction(val) {
  134.   return typeof val == "function";
  135. }
  136.  
  137. /**
  138.  * Returns true if the specified value is an object
  139.  */
  140. function isObject(val) {
  141.   return val && typeof val == "object";
  142. }
  143.  
  144. /**
  145.  * Returns an array of all the properties defined on an object
  146.  */
  147. function getObjectProps(obj) {
  148.   var ret = [];
  149.  
  150.   for (var p in obj) {
  151.     ret.push(p);
  152.   }
  153.  
  154.   return ret;
  155. }
  156.  
  157. /**
  158.  * Returns true if the specified value is an object which has no properties
  159.  * defined.
  160.  */
  161. function isEmptyObject(val) {
  162.   if (!isObject(val)) {
  163.     return false;
  164.   }
  165.  
  166.   for (var p in val) {
  167.     return false;
  168.   }
  169.  
  170.   return true;
  171. }
  172.  
  173. var getHashCode;
  174. var removeHashCode;
  175.  
  176. (function () {
  177.   var hashCodeProperty = "lang_hashCode_";
  178.  
  179.   /**
  180.    * Adds a lang_hashCode_ field to an object. The hash code is unique for the
  181.    * given object.
  182.    * @param obj {Object} The object to get the hash code for
  183.    * @returns {Number} The hash code for the object
  184.    */
  185.   getHashCode = function(obj) {
  186.     // In IE, DOM nodes do not extend Object so they do not have this method.
  187.     // we need to check hasOwnProperty because the proto might have this set.
  188.     if (obj.hasOwnProperty && obj.hasOwnProperty(hashCodeProperty)) {
  189.       return obj[hashCodeProperty];
  190.     }
  191.     if (!obj[hashCodeProperty]) {
  192.       obj[hashCodeProperty] = ++getHashCode.hashCodeCounter_;
  193.     }
  194.     return obj[hashCodeProperty];
  195.   };
  196.  
  197.   /**
  198.    * Removes the lang_hashCode_ field from an object.
  199.    * @param obj {Object} The object to remove the field from. 
  200.    */
  201.   removeHashCode = function(obj) {
  202.     obj.removeAttribute(hashCodeProperty);
  203.   };
  204.  
  205.   getHashCode.hashCodeCounter_ = 0;
  206. })();
  207.  
  208. /**
  209.  * Fast prefix-checker.
  210.  */
  211. String.prototype.startsWith = function(prefix) {
  212.   if (this.length < prefix.length) {
  213.     return false;
  214.   }
  215.  
  216.   if (this.substring(0, prefix.length) == prefix) {
  217.     return true;
  218.   }
  219.  
  220.   return false;
  221. }
  222.  
  223. /**
  224.  * Removes whitespace from the beginning and end of the string
  225.  */
  226. String.prototype.trim = function() {
  227.   return this.replace(/^\s+|\s+$/g, "");
  228. }
  229.  
  230. /**
  231.  * Does simple python-style string substitution.
  232.  * "foo%s hot%s".subs("bar", "dog") becomes "foobar hotdot".
  233.  * For more fully-featured templating, see template.js.
  234.  */
  235. String.prototype.subs = function() {
  236.   var ret = this;
  237.  
  238.   // this appears to be slow, but testing shows it compares more or less equiv.
  239.   // to the regex.exec method.
  240.   for (var i = 0; i < arguments.length; i++) {
  241.     ret = ret.replace(/\%s/, String(arguments[i]));
  242.   }
  243.  
  244.   return ret;
  245. }
  246.  
  247. /**
  248.  * Returns the last element on an array without removing it.
  249.  */
  250. Array.prototype.peek = function() {
  251.   return this[this.length - 1];
  252. }
  253.  
  254. // TODO(anyone): add splice the first time someone needs it and then implement
  255. // push, pop, shift, unshift in terms of it where possible.
  256.  
  257. // TODO(anyone): add the other neat-o functional methods like map(), etc.
  258.  
  259. /**
  260.  * Partially applies this function to a particular "this object" and zero or
  261.  * more arguments. The result is a new function with some arguments of the first
  262.  * function pre-filled and the value of |this| "pre-specified".
  263.  *
  264.  * Remaining arguments specified at call-time are appended to the pre-
  265.  * specified ones.
  266.  *
  267.  * Also see: partial().
  268.  *
  269.  * Note that bind and partial are optimized such that repeated calls to it do 
  270.  * not create more than one function object, so there is no additional cost for
  271.  * something like:
  272.  *
  273.  * var g = bind(f, obj);
  274.  * var h = partial(g, 1, 2, 3);
  275.  * var k = partial(h, a, b, c);
  276.  *
  277.  * Usage:
  278.  * var barMethBound = bind(myFunction, myObj, "arg1", "arg2");
  279.  * barMethBound("arg3", "arg4");
  280.  *
  281.  * @param thisObj {object} Specifies the object which |this| should point to
  282.  * when the function is run. If the value is null or undefined, it will default
  283.  * to the global object.
  284.  *
  285.  * @returns {function} A partially-applied form of the function bind() was
  286.  * invoked as a method of.
  287.  */
  288. function bind(fn, self, opt_args) {
  289.   var boundargs = (typeof fn.boundArgs_ != "undefined") ? fn.boundArgs_ : [];
  290.   boundargs = boundargs.concat(Array.prototype.slice.call(arguments, 2));
  291.  
  292.   if (typeof fn.boundSelf_ != "undefined") {
  293.     self = fn.boundSelf_;
  294.   }
  295.  
  296.   if (typeof fn.boundFn_ != "undefined") {
  297.     fn = fn.boundFn_;
  298.   }
  299.  
  300.   var newfn = function() {
  301.     // Combine the static args and the new args into one big array
  302.     var args = boundargs.concat(Array.prototype.slice.call(arguments));
  303.     return fn.apply(self, args);
  304.   }
  305.  
  306.   newfn.boundArgs_ = boundargs;
  307.   newfn.boundSelf_ = self;
  308.   newfn.boundFn_ = fn;
  309.  
  310.   return newfn;
  311. }
  312.  
  313. /**
  314.  * An alias to the bind() global function.
  315.  *
  316.  * Usage:
  317.  * var g = f.bind(obj, arg1, arg2);
  318.  * g(arg3, arg4);
  319.  */
  320. Function.prototype.bind = function(self, opt_args) {
  321.   return bind.apply(
  322.     null, [this, self].concat(Array.prototype.slice.call(arguments, 1)));
  323. }
  324.  
  325. /**
  326.  * Like bind(), except that a "this object" is not required. Useful when the
  327.  * target function is already bound.
  328.  * 
  329.  * Usage:
  330.  * var g = partial(f, arg1, arg2);
  331.  * g(arg3, arg4);
  332.  */
  333. function partial(fn, opt_args) {
  334.   return bind.apply(
  335.     null, [fn, null].concat(Array.prototype.slice.call(arguments, 1)));
  336. }
  337.  
  338. /**
  339.  * An alias to the partial() global function.
  340.  *
  341.  * Usage:
  342.  * var g = f.partial(arg1, arg2);
  343.  * g(arg3, arg4);
  344.  */
  345. Function.prototype.partial = function(opt_args) {
  346.   return bind.apply(
  347.     null, [this, null].concat(Array.prototype.slice.call(arguments)));
  348. }
  349.  
  350. /**
  351.  * Convenience. Binds all the methods of obj to itself. Calling this in the
  352.  * constructor before referencing any methods makes things a little more like
  353.  * Java or Python where methods are intrinsically bound to their instance.
  354.  */
  355. function bindMethods(obj) {
  356.   for (var p in obj) {
  357.     if (isFunction(obj[p])) {
  358.       obj[p] = obj[p].bind(obj);
  359.     }
  360.   }
  361. }
  362.  
  363. /**
  364.  * Inherit the prototype methods from one constructor into another.
  365.  *
  366.  * Usage:
  367.  * <pre>
  368.  * function ParentClass(a, b) { }
  369.  * ParentClass.prototype.foo = function(a) { }
  370.  *
  371.  * function ChildClass(a, b, c) {
  372.  *   ParentClass.call(this, a, b);
  373.  * }
  374.  *
  375.  * ChildClass.inherits(ParentClass);
  376.  *
  377.  * var child = new ChildClass("a", "b", "see");
  378.  * child.foo(); // works
  379.  * </pre>
  380.  *
  381.  * In addition, a superclass' implementation of a method can be invoked
  382.  * as follows:
  383.  *
  384.  * <pre>
  385.  * ChildClass.prototype.foo = function(a) {
  386.  *   ChildClass.superClass_.foo.call(this, a);
  387.  *   // other code
  388.  * };
  389.  * </pre>
  390.  */
  391. Function.prototype.inherits = function(parentCtor) {
  392.   var tempCtor = function(){};
  393.   tempCtor.prototype = parentCtor.prototype;
  394.   this.superClass_ = parentCtor.prototype;
  395.   this.prototype = new tempCtor();
  396. }
  397. /* ***** BEGIN LICENSE BLOCK *****
  398.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  399.  *
  400.  * The contents of this file are subject to the Mozilla Public License Version
  401.  * 1.1 (the "License"); you may not use this file except in compliance with
  402.  * the License. You may obtain a copy of the License at
  403.  * http://www.mozilla.org/MPL/
  404.  *
  405.  * Software distributed under the License is distributed on an "AS IS" basis,
  406.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  407.  * for the specific language governing rights and limitations under the
  408.  * License.
  409.  *
  410.  * The Original Code is Google Safe Browsing.
  411.  *
  412.  * The Initial Developer of the Original Code is Google Inc.
  413.  * Portions created by the Initial Developer are Copyright (C) 2006
  414.  * the Initial Developer. All Rights Reserved.
  415.  *
  416.  * Contributor(s):
  417.  *   Fritz Schneider <fritz@google.com> (original author)
  418.  *
  419.  * Alternatively, the contents of this file may be used under the terms of
  420.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  421.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  422.  * in which case the provisions of the GPL or the LGPL are applicable instead
  423.  * of those above. If you wish to allow use of your version of this file only
  424.  * under the terms of either the GPL or the LGPL, and not to allow others to
  425.  * use your version of this file under the terms of the MPL, indicate your
  426.  * decision by deleting the provisions above and replace them with the notice
  427.  * and other provisions required by the GPL or the LGPL. If you do not delete
  428.  * the provisions above, a recipient may use your version of this file under
  429.  * the terms of any one of the MPL, the GPL or the LGPL.
  430.  *
  431.  * ***** END LICENSE BLOCK ***** */
  432.  
  433.  
  434. // This is the code used to interact with data encoded in the
  435. // goog-black-enchash format. The format is basically a map from
  436. // hashed hostnames to encrypted sequences of regular expressions
  437. // where the encryption key is derived from the hashed
  438. // hostname. Encoding lists like this raises the bar slightly on
  439. // deriving complete table data from the db. This data format is NOT
  440. // our idea; we would've raise the bar higher :)
  441. //
  442. // Anyway, this code is a port of the original C++ implementation by
  443. // Garret. To ease verification, I mirrored that code as closely as
  444. // possible.  As a result, you'll see some C++-style variable naming
  445. // and roundabout (C++) ways of doing things. Additionally, I've
  446. // omitted the comments.
  447. //
  448. // This code should not change, except to fix bugs.
  449. //
  450. // TODO: verify that using encodeURI() in getCanonicalHost is OK
  451. // TODO: accommodate other kinds of perl-but-not-javascript qualifiers
  452.  
  453.  
  454. /**
  455.  * This thing knows how to generate lookup keys and decrypt values found in
  456.  * a table of type enchash.
  457.  */
  458. function PROT_EnchashDecrypter() {
  459.   this.debugZone = "enchashdecrypter";
  460.   this.REs_ = PROT_EnchashDecrypter.REs;
  461.   this.hasher_ = new G_CryptoHasher();
  462.   this.base64_ = new G_Base64();
  463.   this.rc4_ = new ARC4();
  464. }
  465.  
  466. PROT_EnchashDecrypter.DATABASE_SALT = "oU3q.72p";
  467. PROT_EnchashDecrypter.SALT_LENGTH = PROT_EnchashDecrypter.DATABASE_SALT.length;
  468.  
  469. PROT_EnchashDecrypter.MAX_DOTS = 5;
  470.  
  471. PROT_EnchashDecrypter.REs = {};
  472. PROT_EnchashDecrypter.REs.FIND_DODGY_CHARS = 
  473.   new RegExp("[\x01-\x1f\x7f-\xff]+");
  474. PROT_EnchashDecrypter.REs.FIND_DODGY_CHARS_GLOBAL = 
  475.   new RegExp("[\x01-\x1f\x7f-\xff]+", "g");
  476. PROT_EnchashDecrypter.REs.FIND_END_DOTS = new RegExp("^\\.+|\\.+$");
  477. PROT_EnchashDecrypter.REs.FIND_END_DOTS_GLOBAL = 
  478.   new RegExp("^\\.+|\\.+$", "g");
  479. PROT_EnchashDecrypter.REs.FIND_MULTIPLE_DOTS = new RegExp("\\.{2,}");
  480. PROT_EnchashDecrypter.REs.FIND_MULTIPLE_DOTS_GLOBAL = 
  481.   new RegExp("\\.{2,}", "g");
  482. PROT_EnchashDecrypter.REs.FIND_TRAILING_DOTS = new RegExp("\\.+$");
  483. PROT_EnchashDecrypter.REs.POSSIBLE_IP = 
  484.   new RegExp("^((?:0x[0-9a-f]+|[0-9\\.])+)$", "i");
  485. PROT_EnchashDecrypter.REs.FIND_BAD_OCTAL = new RegExp("(^|\\.)0\\d*[89]");
  486. PROT_EnchashDecrypter.REs.IS_OCTAL = new RegExp("^0[0-7]*$");
  487. PROT_EnchashDecrypter.REs.IS_DECIMAL = new RegExp("^[0-9]+$");
  488. PROT_EnchashDecrypter.REs.IS_HEX = new RegExp("^0[xX]([0-9a-fA-F]+)$");
  489.  
  490. // Regexps are given in perl regexp format. Unfortunately, JavaScript's
  491. // library isn't completely compatible. For example, you can't specify
  492. // case-insensitive matching by using (?i) in the expression text :(
  493. // So we manually set this bit with the help of this regular expression.
  494. PROT_EnchashDecrypter.REs.CASE_INSENSITIVE = /\(\?i\)/g;
  495.  
  496. /**
  497.  * Helper function 
  498.  *
  499.  * @param str String to get chars from
  500.  * 
  501.  * @param n Number of characters to get
  502.  *
  503.  * @returns String made up of the last n characters of str
  504.  */ 
  505. PROT_EnchashDecrypter.prototype.lastNChars_ = function(str, n) {
  506.   n = -n;
  507.   return str.substr(n);
  508. }
  509.  
  510. /**
  511.  * We have to have our own hex-decoder because decodeURIComponent
  512.  * expects UTF-8 (so it will barf on invalid UTF-8 sequences).
  513.  *
  514.  * @param str String to decode
  515.  * 
  516.  * @returns The decoded string
  517.  */
  518. PROT_EnchashDecrypter.prototype.hexDecode_ = function(str) {
  519.   var output = [];
  520.  
  521.   var i = 0;
  522.   while (i < str.length) {
  523.     var c = str.charAt(i);
  524.   
  525.     if (c == "%" && i + 2 < str.length) {
  526.  
  527.       var asciiVal = Number("0x" + str.charAt(i + 1) + str.charAt(i + 2));
  528.       
  529.       if (!isNaN(asciiVal)) {
  530.         i += 2;
  531.         c = String.fromCharCode(asciiVal);
  532.       }
  533.     }
  534.     
  535.     output[output.length] = c;
  536.     ++i;
  537.   }
  538.   
  539.   return output.join("");
  540. }
  541.  
  542. /**
  543.  * Translate a plaintext enchash value into regular expressions
  544.  *
  545.  * @param data String containing a decrypted enchash db entry
  546.  *
  547.  * @returns An array of RegExps
  548.  */
  549. PROT_EnchashDecrypter.prototype.parseRegExps = function(data) {
  550.   var res = data.split("\t");
  551.   
  552.   G_Debug(this, "Got " + res.length + " regular rexpressions");
  553.   
  554.   for (var i = 0; i < res.length; i++) {
  555.     // Could have leading (?i); if so, set the flag and strip it
  556.     var flags = (this.REs_.CASE_INSENSITIVE.test(res[i])) ? "i" : "";
  557.     res[i] = res[i].replace(this.REs_.CASE_INSENSITIVE, "");
  558.     res[i] = new RegExp(res[i], flags);
  559.   }
  560.  
  561.   return res;
  562. }
  563.  
  564. PROT_EnchashDecrypter.prototype.getCanonicalHost = function(str) {
  565.   var urlObj = Cc["@mozilla.org/network/standard-url;1"]
  566.                .createInstance(Ci.nsIURL);
  567.   urlObj.spec = str;
  568.   var asciiHost = urlObj.asciiHost;
  569.  
  570.   var unescaped = this.hexDecode_(asciiHost);
  571.  
  572.   unescaped = unescaped.replace(this.REs_.FIND_DODGY_CHARS_GLOBAL, "")
  573.               .replace(this.REs_.FIND_END_DOTS_GLOBAL, "")
  574.               .replace(this.REs_.FIND_MULTIPLE_DOTS_GLOBAL, ".");
  575.  
  576.   var temp = this.parseIPAddress_(unescaped);
  577.   if (temp)
  578.     unescaped = temp;
  579.  
  580.   // TODO: what, exactly is it supposed to escape? This doesn't esecape 
  581.   // ":", "/", ";", and "?"
  582.   var escaped = encodeURI(unescaped);
  583.  
  584.   var k;
  585.   var index = escaped.length;
  586.   for (k = 0; k < PROT_EnchashDecrypter.MAX_DOTS + 1; k++) {
  587.     temp = escaped.lastIndexOf(".", index - 1);
  588.     if (temp == -1) {
  589.       break;
  590.     } else {
  591.       index = temp;
  592.     }
  593.   }
  594.   
  595.   if (k == PROT_EnchashDecrypter.MAX_DOTS + 1 && index != -1) {
  596.     escaped = escaped.substring(index + 1);
  597.   }
  598.  
  599.   escaped = escaped.toLowerCase();
  600.   return escaped;
  601. }
  602.  
  603. PROT_EnchashDecrypter.prototype.parseIPAddress_ = function(host) {
  604.  
  605.   host = host.replace(this.REs_.FIND_TRAILING_DOTS_GLOBAL, "");
  606.  
  607.   if (!this.REs_.POSSIBLE_IP.test(host))
  608.     return "";
  609.  
  610.   var parts = host.split(".");
  611.   if (parts.length > 4)
  612.     return "";
  613.  
  614.   var allowOctal = !this.REs_.FIND_BAD_OCTAL.test(host);
  615.  
  616.   for (var k = 0; k < parts.length; k++) {
  617.     var canon;
  618.     if (k == parts.length - 1) {
  619.       canon = this.canonicalNum_(parts[k], 5 - parts.length, allowOctal);
  620.     } else {
  621.       canon = this.canonicalNum_(parts[k], 1, allowOctal);
  622.     }
  623.     if (canon != "") 
  624.       parts[k] = canon;
  625.   }
  626.  
  627.   return parts.join(".");
  628. }
  629.  
  630. PROT_EnchashDecrypter.prototype.canonicalNum_ = function(num, bytes, octal) {
  631.   
  632.   if (bytes < 0) 
  633.     return "";
  634.   var temp_num;
  635.  
  636.   if (octal && this.REs_.IS_OCTAL.test(num)) {
  637.  
  638.     num = this.lastNChars_(num, 11);
  639.  
  640.     temp_num = parseInt(num, 8);
  641.     if (isNaN(temp_num))
  642.       temp_num = -1;
  643.  
  644.   } else if (this.REs_.IS_DECIMAL.test(num)) {
  645.  
  646.     num = this.lastNChars_(num, 32);
  647.  
  648.     temp_num = parseInt(num, 10);
  649.     if (isNaN(temp_num))
  650.       temp_num = -1;
  651.  
  652.   } else if (this.REs_.IS_HEX.test(num)) {
  653.  
  654.     num = this.lastNChars_(num, 8);
  655.  
  656.     temp_num = parseInt(num, 16);
  657.     if (isNaN(temp_num))
  658.       temp_num = -1;
  659.  
  660.   } else {
  661.     return "";
  662.   }
  663.  
  664.   if (temp_num == -1) 
  665.     return "";
  666.  
  667.   var parts = [];
  668.   while (bytes--) {
  669.     parts.push("" + (temp_num % 256));
  670.     temp_num -= temp_num % 256;
  671.     temp_num /= 256;
  672.   }
  673.  
  674.   return parts.join(".");
  675. }
  676.  
  677. PROT_EnchashDecrypter.prototype.getLookupKey = function(host) {
  678.   var dataKey = PROT_EnchashDecrypter.DATABASE_SALT + host;
  679.   dataKey = this.base64_.arrayifyString(dataKey);
  680.  
  681.   this.hasher_.init(G_CryptoHasher.algorithms.MD5);
  682.   var lookupDigest = this.hasher_.updateFromArray(dataKey);
  683.   var lookupKey = this.hasher_.digestHex();
  684.  
  685.   return lookupKey.toUpperCase();
  686. }
  687.  
  688. PROT_EnchashDecrypter.prototype.decryptData = function(data, host) {
  689.  
  690.   var ascii = this.base64_.decodeString(data);
  691.   var random_salt = ascii.slice(0, PROT_EnchashDecrypter.SALT_LENGTH);
  692.   var encrypted_data = ascii.slice(PROT_EnchashDecrypter.SALT_LENGTH);
  693.   var temp_decryption_key = 
  694.     this.base64_.arrayifyString(PROT_EnchashDecrypter.DATABASE_SALT);
  695.   temp_decryption_key = temp_decryption_key.concat(random_salt);
  696.   temp_decryption_key = 
  697.     temp_decryption_key.concat(this.base64_.arrayifyString(host));
  698.                                
  699.   this.hasher_.init(G_CryptoHasher.algorithms.MD5);
  700.   this.hasher_.updateFromArray(temp_decryption_key);
  701.   var decryption_key = this.base64_.arrayifyString(this.hasher_.digestRaw());
  702.  
  703.   this.rc4_.setKey(decryption_key, decryption_key.length);
  704.   this.rc4_.crypt(encrypted_data, encrypted_data.length);   // Works in-place
  705.   
  706.   return this.base64_.stringifyArray(encrypted_data);
  707. }
  708.  
  709. /* ***** BEGIN LICENSE BLOCK *****
  710.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  711.  *
  712.  * The contents of this file are subject to the Mozilla Public License Version
  713.  * 1.1 (the "License"); you may not use this file except in compliance with
  714.  * the License. You may obtain a copy of the License at
  715.  * http://www.mozilla.org/MPL/
  716.  *
  717.  * Software distributed under the License is distributed on an "AS IS" basis,
  718.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  719.  * for the specific language governing rights and limitations under the
  720.  * License.
  721.  *
  722.  * The Original Code is Google Safe Browsing.
  723.  *
  724.  * The Initial Developer of the Original Code is Google Inc.
  725.  * Portions created by the Initial Developer are Copyright (C) 2006
  726.  * the Initial Developer. All Rights Reserved.
  727.  *
  728.  * Contributor(s):
  729.  *   Tony Chang <tony@google.com> (original author)
  730.  *
  731.  * Alternatively, the contents of this file may be used under the terms of
  732.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  733.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  734.  * in which case the provisions of the GPL or the LGPL are applicable instead
  735.  * of those above. If you wish to allow use of your version of this file only
  736.  * under the terms of either the GPL or the LGPL, and not to allow others to
  737.  * use your version of this file under the terms of the MPL, indicate your
  738.  * decision by deleting the provisions above and replace them with the notice
  739.  * and other provisions required by the GPL or the LGPL. If you do not delete
  740.  * the provisions above, a recipient may use your version of this file under
  741.  * the terms of any one of the MPL, the GPL or the LGPL.
  742.  *
  743.  * ***** END LICENSE BLOCK ***** */
  744.  
  745. /**
  746.  * This class helps us batch a series of async calls to the db.
  747.  * If any of the tokens is in the database, we fire callback with
  748.  * true as a param.  If all the tokens are not in the  database,
  749.  * we fire callback with false as a param.
  750.  * This is an "Abstract" base class.  Subclasses need to supply
  751.  * the condition_ method.
  752.  *
  753.  * @param tokens Array of strings to lookup in the db
  754.  * @param tableName String name of the table
  755.  * @param callback Function callback function that takes true if the condition
  756.  *        passes.
  757.  */
  758. function MultiQuerier(tokens, tableName, callback) {
  759.   this.tokens_ = tokens;
  760.   this.tableName_ = tableName;
  761.   this.callback_ = callback;
  762.   this.dbservice_ = Cc["@mozilla.org/url-classifier/dbservice;1"]
  763.                     .getService(Ci.nsIUrlClassifierDBService);
  764.   // We put the current token in this variable.
  765.   this.key_ = null;
  766. }
  767.  
  768. /**
  769.  * Run the remaining tokens against the db.
  770.  */
  771. MultiQuerier.prototype.run = function() {
  772.   if (this.tokens_.length == 0) {
  773.     this.callback_.handleEvent(false);
  774.     this.dbservice_ = null;
  775.     this.callback_ = null;
  776.     return;
  777.   }
  778.   
  779.   this.key_ = this.tokens_.pop();
  780.   G_Debug(this, "Looking up " + this.key_ + " in " + this.tableName_);
  781.   this.dbservice_.exists(this.tableName_, this.key_,
  782.                          BindToObject(this.result_, this));
  783. }
  784.  
  785. /**
  786.  * Callback from the db.  If the returned value passes the this.condition_
  787.  * test, go ahead and call the main callback.
  788.  */
  789. MultiQuerier.prototype.result_ = function(value) {
  790.   if (this.condition_(value)) {
  791.     this.callback_.handleEvent(true)
  792.     this.dbservice_ = null;
  793.     this.callback_ = null;
  794.   } else {
  795.     this.run();
  796.   }
  797. }
  798.  
  799. // Subclasses must override this.
  800. MultiQuerier.prototype.condition_ = function(value) {
  801.   throw "MultiQuerier is an abstract base class";
  802. }
  803.  
  804.  
  805. /**
  806.  * Concrete MultiQuerier that stops if the key exists in the db.
  807.  */
  808. function ExistsMultiQuerier(tokens, tableName, callback) {
  809.   MultiQuerier.call(this, tokens, tableName, callback);
  810.   this.debugZone = "existsMultiQuerier";
  811. }
  812. ExistsMultiQuerier.inherits(MultiQuerier);
  813.  
  814. ExistsMultiQuerier.prototype.condition_ = function(value) {
  815.   return value.length > 0;
  816. }
  817.  
  818.  
  819. /**
  820.  * Concrete MultiQuerier that looks up a key, decrypts it, then
  821.  * checks the the resulting regular expressions for a match.
  822.  * @param tokens Array of hosts
  823.  */
  824. function EnchashMultiQuerier(tokens, tableName, callback, url) {
  825.   MultiQuerier.call(this, tokens, tableName, callback);
  826.   this.url_ = url;
  827.   this.enchashDecrypter_ = new PROT_EnchashDecrypter();
  828.   this.debugZone = "enchashMultiQuerier";
  829. }
  830. EnchashMultiQuerier.inherits(MultiQuerier);
  831.  
  832. EnchashMultiQuerier.prototype.run = function() {
  833.   if (this.tokens_.length == 0) {
  834.     this.callback_.handleEvent(false);
  835.     this.dbservice_ = null;
  836.     this.callback_ = null;
  837.     return;
  838.   }
  839.   var host = this.tokens_.pop();
  840.   this.key_ = host;
  841.   var lookupKey = this.enchashDecrypter_.getLookupKey(host);
  842.   this.dbservice_.exists(this.tableName_, lookupKey,
  843.                          BindToObject(this.result_, this));
  844. }
  845.  
  846. EnchashMultiQuerier.prototype.condition_ = function(encryptedValue) {
  847.   if (encryptedValue.length > 0) {
  848.     // We have encrypted regular expressions for this host. Let's 
  849.     // decrypt them and see if we have a match.
  850.     var decrypted = this.enchashDecrypter_.decryptData(encryptedValue,
  851.                                                        this.key_);
  852.     var res = this.enchashDecrypter_.parseRegExps(decrypted);
  853.     for (var j = 0; j < res.length; j++) {
  854.       if (res[j].test(this.url_)) {
  855.         return true;
  856.       }
  857.     }
  858.   }
  859.   return false;
  860. }
  861. /* ***** BEGIN LICENSE BLOCK *****
  862.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  863.  *
  864.  * The contents of this file are subject to the Mozilla Public License Version
  865.  * 1.1 (the "License"); you may not use this file except in compliance with
  866.  * the License. You may obtain a copy of the License at
  867.  * http://www.mozilla.org/MPL/
  868.  *
  869.  * Software distributed under the License is distributed on an "AS IS" basis,
  870.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  871.  * for the specific language governing rights and limitations under the
  872.  * License.
  873.  *
  874.  * The Original Code is Google Safe Browsing.
  875.  *
  876.  * The Initial Developer of the Original Code is Google Inc.
  877.  * Portions created by the Initial Developer are Copyright (C) 2006
  878.  * the Initial Developer. All Rights Reserved.
  879.  *
  880.  * Contributor(s):
  881.  *   Fritz Schneider <fritz@google.com> (original author)
  882.  *
  883.  * Alternatively, the contents of this file may be used under the terms of
  884.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  885.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  886.  * in which case the provisions of the GPL or the LGPL are applicable instead
  887.  * of those above. If you wish to allow use of your version of this file only
  888.  * under the terms of either the GPL or the LGPL, and not to allow others to
  889.  * use your version of this file under the terms of the MPL, indicate your
  890.  * decision by deleting the provisions above and replace them with the notice
  891.  * and other provisions required by the GPL or the LGPL. If you do not delete
  892.  * the provisions above, a recipient may use your version of this file under
  893.  * the terms of any one of the MPL, the GPL or the LGPL.
  894.  *
  895.  * ***** END LICENSE BLOCK ***** */
  896.  
  897.  
  898. // This is the class we use to canonicalize URLs for TRTables of type
  899. // url.  We maximally URL-decode the URL, treating +'s as if they're
  900. // not special.  We then specially URL-encode it (we encode ASCII
  901. // values [0, 32] (whitespace or unprintable), 37 (%), [127, 255]
  902. // (unprintable)).  
  903. //
  904. // This mapping is not a function. That is, multiple URLs can map to
  905. // the same canonical representation. However this is OK because
  906. // collisions happen only when there are weird characters (e.g.,
  907. // nonprintables), and the canonical representation makes us robust
  908. // to some weird kinds of encoding we could see. 
  909. //
  910. // All members are static at this point -- this is basically a namespace.
  911.  
  912.  
  913. /**
  914.  * Create a new URLCanonicalizer. Useless because members are static.
  915.  *
  916.  * @constructor
  917.  */
  918. function PROT_URLCanonicalizer() { 
  919.   throw new Error("No need to instantiate a canonicalizer at this point.");
  920. }
  921.  
  922. PROT_URLCanonicalizer.debugZone = "urlcanonicalizer";
  923.  
  924. PROT_URLCanonicalizer.hexChars_ = "0123456789ABCDEF";
  925.  
  926. /**
  927.  * Helper funciton to (maybe) convert a two-character hex string into its 
  928.  * decimal numerical equivalent
  929.  *
  930.  * @param hh String of length two that might be a valid hex sequence
  931.  *
  932.  * @returns Number: NaN if hh wasn't valid hex, else the appropriate decimal
  933.  *          value
  934.  */
  935. PROT_URLCanonicalizer.hexPairToInt_ = function(hh) {
  936.   return Number("0x" + hh);
  937. }
  938.  
  939. /**
  940.  * Helper function to hex-encode a number
  941.  *
  942.  * @param val Number in range [0, 255]
  943.  *
  944.  * @returns String containing the hex representation of that number (sans 0x)
  945.  */
  946. PROT_URLCanonicalizer.toHex_ = function(val) {
  947.   var retVal = PROT_URLCanonicalizer.hexChars_.charAt((val >> 4) & 15) + 
  948.                PROT_URLCanonicalizer.hexChars_.charAt(val & 15);
  949.   return retVal;
  950. }
  951.  
  952. /**
  953.  * Get the canonical version of the given URL for lookup in a table of 
  954.  * type -url.
  955.  *
  956.  * @param url String to canonicalize
  957.  *
  958.  * @returns String containing the canonicalized url (maximally url-decoded,
  959.  *          then specially url-encoded)
  960.  */
  961. PROT_URLCanonicalizer.canonicalizeURL_ = function(url) {
  962.   var arrayOfASCIIVals = PROT_URLCanonicalizer.fullyDecodeURL_(url);
  963.   return PROT_URLCanonicalizer.specialEncodeURL_(arrayOfASCIIVals);
  964. }
  965.  
  966. /**
  967.  * Maximally URL-decode a URL. This breaks the semantics of the URL, but
  968.  * we don't care because we're using it for lookup, not for navigation.
  969.  * We break multi-byte UTF-8 escape sequences as well, but we don't care
  970.  * so long as they canonicalize the same way consistently (they do).
  971.  *
  972.  * @param url String containing the URL to maximally decode. Should ONLY
  973.  *            contain characters with UCS codepoints U+0001 to U+00FF
  974.  *            (the ASCII set minus null).
  975.  *
  976.  * @returns Array of ASCII values corresponding to the decoded sequence of
  977.  *          characters in the url
  978.  */
  979. PROT_URLCanonicalizer.fullyDecodeURL_ = function(url) {
  980.  
  981.   // The goals here are: simplicity, correctness, and most of all
  982.   // portability; we want the same implementation of canonicalization
  983.   // wherever we use it so as to to minimize the chances of
  984.   // inconsistency. For example, we have to do this canonicalization
  985.   // on URLs we get from third parties, and at the lookup server when 
  986.   // we get a request.
  987.   //
  988.   // The following implementation should translate easily to any
  989.   // language that supports arrays and pointers or references. Note
  990.   // that arrays are pointer types in JavaScript, so foo = [some,
  991.   // array] points foo at the array; it doesn't copy it. The
  992.   // implementation is efficient (linear) so long as most %'s in the
  993.   // url belong to valid escape sequences and there aren't too many
  994.   // doubly-escaped values.
  995.  
  996.   // The basic idea is to copy current input to output, decoding escape 
  997.   // sequences as we see them, until we decode a %. At that point we start
  998.   // copying into the "next iteration buffer" instead of the output buffer; 
  999.   // we do this so we can accomodate multiply-escaped strings. When we hit 
  1000.   // the end of the input, we take the "next iteration buffer" as our input,
  1001.   // and start over.
  1002.  
  1003.   var nextIteration = url.split("");
  1004.   var output = [];
  1005.  
  1006.   while (nextIteration.length) {
  1007.  
  1008.     var decodedAPercent = false;
  1009.     var thisIteration = nextIteration;
  1010.     var nextIteration = [];
  1011.     
  1012.     var i = 0;
  1013.     while (i < thisIteration.length) {
  1014.  
  1015.       var c = thisIteration[i];
  1016.       if (c == "%" && i + 2 < thisIteration.length) {
  1017.  
  1018.         // Peek ahead to see if we have a valid HH sequence
  1019.         var asciiVal = 
  1020.           PROT_URLCanonicalizer.hexPairToInt_(thisIteration[i + 1] + 
  1021.                                               thisIteration[i + 2]);
  1022.         if (!isNaN(asciiVal)) {
  1023.           i += 2;                   // Valid HH sequence; consume it
  1024.           
  1025.           if (asciiVal == 0)        // We special case nulls
  1026.             asciiVal = 1;
  1027.           
  1028.           c = String.fromCharCode(asciiVal);
  1029.           if (c == "%")
  1030.             decodedAPercent = true;
  1031.         }
  1032.       }
  1033.  
  1034.       if (decodedAPercent)
  1035.         nextIteration[nextIteration.length] = c;
  1036.       else
  1037.         output[output.length] = c.charCodeAt(0);
  1038.       
  1039.       ++i;
  1040.     }
  1041.   }
  1042.  
  1043.   return output;
  1044. }
  1045.  
  1046. /**
  1047.  * Maximally URL-decode a URL (same as fullyDecodeURL_ except that it 
  1048.  * returns a string). Useful for making unittests more readable.
  1049.  *
  1050.  * @param url String containing the URL to maximally decode. Should ONLY
  1051.  *            contain characters with UCS codepoints U+0001 to U+00FF
  1052.  *            (the ASCII set minus null).
  1053.  *
  1054.  * @returns String containing the decoded URL
  1055.  */
  1056. PROT_URLCanonicalizer.fullyDecodeURLAsString_ = function(url) {
  1057.   var arrayOfASCIIVals = PROT_URLCanonicalizer.fullyDecodeURL_(url);
  1058.   var s = "";
  1059.   for (var i = 0; i < arrayOfASCIIVals.length; i++)
  1060.     s += String.fromCharCode(arrayOfASCIIVals[i]);
  1061.   return s;
  1062. }
  1063.  
  1064. /**
  1065.  * Specially URL-encode the given array of ASCII values. We want to encode 
  1066.  * the charcters: [0, 32], 37, [127, 255].
  1067.  *
  1068.  * @param arrayOfASCIIValues Array of ascii values (numbers) to encode
  1069.  *
  1070.  * @returns String corresonding to the escaped URL
  1071.  */
  1072. PROT_URLCanonicalizer.specialEncodeURL_ = function(arrayOfASCIIValues) {
  1073.  
  1074.   var output = [];
  1075.   for (var i = 0; i < arrayOfASCIIValues.length; i++) {
  1076.     var n = arrayOfASCIIValues[i];
  1077.  
  1078.     if (n <= 32 || n == 37 || n >= 127)
  1079.       output.push("%" + ((!n) ? "01" : PROT_URLCanonicalizer.toHex_(n)));
  1080.     else
  1081.       output.push(String.fromCharCode(n));
  1082.   }
  1083.  
  1084.   return output.join("");
  1085. }
  1086.  
  1087.  
  1088. /* ***** BEGIN LICENSE BLOCK *****
  1089.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  1090.  *
  1091.  * The contents of this file are subject to the Mozilla Public License Version
  1092.  * 1.1 (the "License"); you may not use this file except in compliance with
  1093.  * the License. You may obtain a copy of the License at
  1094.  * http://www.mozilla.org/MPL/
  1095.  *
  1096.  * Software distributed under the License is distributed on an "AS IS" basis,
  1097.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  1098.  * for the specific language governing rights and limitations under the
  1099.  * License.
  1100.  *
  1101.  * The Original Code is Url Classifier code
  1102.  *
  1103.  * The Initial Developer of the Original Code is
  1104.  * Google Inc.
  1105.  * Portions created by the Initial Developer are Copyright (C) 2006
  1106.  * the Initial Developer. All Rights Reserved.
  1107.  *
  1108.  * Contributor(s):
  1109.  *   Tony Chang <tony@ponderer.org>
  1110.  *
  1111.  * Alternatively, the contents of this file may be used under the terms of
  1112.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  1113.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  1114.  * in which case the provisions of the GPL or the LGPL are applicable instead
  1115.  * of those above. If you wish to allow use of your version of this file only
  1116.  * under the terms of either the GPL or the LGPL, and not to allow others to
  1117.  * use your version of this file under the terms of the MPL, indicate your
  1118.  * decision by deleting the provisions above and replace them with the notice
  1119.  * and other provisions required by the GPL or the LGPL. If you do not delete
  1120.  * the provisions above, a recipient may use your version of this file under
  1121.  * the terms of any one of the MPL, the GPL or the LGPL.
  1122.  *
  1123.  * ***** END LICENSE BLOCK ***** */
  1124.  
  1125. // XXX: This should all be moved into the dbservice class so it happens
  1126. // in the background thread.
  1127.  
  1128. /**
  1129.  * Abstract base class for a lookup table.
  1130.  * @construction
  1131.  */
  1132. function UrlClassifierTable() {
  1133.   this.debugZone = "urlclassifier-table";
  1134.   this.name = '';
  1135.   this.needsUpdate = false;
  1136. }
  1137.  
  1138. UrlClassifierTable.prototype.QueryInterface = function(iid) {
  1139.   if (iid.equals(Components.interfaces.nsISupports) ||
  1140.       iid.equals(Components.interfaces.nsIUrlClassifierTable))
  1141.     return this;                                              
  1142.   Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  1143.   return null;
  1144. }
  1145.  
  1146. /**
  1147.  * Subclasses need to implment this method.
  1148.  */
  1149. UrlClassifierTable.prototype.exists = function(url, callback) {
  1150.   throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  1151. }
  1152.  
  1153. /////////////////////////////////////////////////////////////////////
  1154. // Url table implementation
  1155. function UrlClassifierTableUrl() {
  1156.   UrlClassifierTable.call(this);
  1157. }
  1158. UrlClassifierTableUrl.inherits(UrlClassifierTable);
  1159.  
  1160. /**
  1161.  * Look up a URL in a URL table
  1162.  */
  1163. UrlClassifierTableUrl.prototype.exists = function(url, callback) {
  1164.   var canonicalized = PROT_URLCanonicalizer.canonicalizeURL_(url);
  1165.   G_Debug(this, "Looking up: " + url + " (" + canonicalized + ")");
  1166.  
  1167.   var dbservice_ = Cc["@mozilla.org/url-classifier/dbservice;1"]
  1168.                    .getService(Ci.nsIUrlClassifierDBService);
  1169.   var callbackHelper = new UrlLookupCallback(callback);
  1170.   dbservice_.exists(this.name,
  1171.                     canonicalized,
  1172.                     BindToObject(callbackHelper.dbCallback,
  1173.                                  callbackHelper));
  1174. }
  1175.  
  1176. /**
  1177.  * A helper class for handling url lookups in the database.  This allows us to
  1178.  * break our reference to callback to avoid memory leaks.
  1179.  * @param callback nsIUrlListManagerCallback
  1180.  */
  1181. function UrlLookupCallback(callback) {
  1182.   this.callback_ = callback;
  1183. }
  1184.  
  1185. /**
  1186.  * Callback function from nsIUrlClassifierDBService.exists.  For url lookup,
  1187.  * any non-empty string value is a database hit.
  1188.  * @param value String
  1189.  */
  1190. UrlLookupCallback.prototype.dbCallback = function(value) {
  1191.   this.callback_.handleEvent(value.length > 0);
  1192.   this.callback_ = null;
  1193. }
  1194.  
  1195. /////////////////////////////////////////////////////////////////////
  1196. // Domain table implementation
  1197.  
  1198. function UrlClassifierTableDomain() {
  1199.   UrlClassifierTable.call(this);
  1200.   this.debugZone = "urlclassifier-table-domain";
  1201.   this.ioService_ = Cc["@mozilla.org/network/io-service;1"]
  1202.                     .getService(Ci.nsIIOService);
  1203. }
  1204. UrlClassifierTableDomain.inherits(UrlClassifierTable);
  1205.  
  1206. /**
  1207.  * Look up a URL in a domain table
  1208.  *
  1209.  * @returns Boolean true if the url domain is in the table
  1210.  */
  1211. UrlClassifierTableDomain.prototype.exists = function(url, callback) {
  1212.   var urlObj = this.ioService_.newURI(url, null, null);
  1213.   var host = '';
  1214.   try {
  1215.     host = urlObj.host;
  1216.   } catch (e) { }
  1217.   var components = host.split(".");
  1218.  
  1219.   // We don't have a good way map from hosts to domains, so we instead try
  1220.   // each possibility. Could probably optimize to start at the second dot?
  1221.   var possible = [];
  1222.   for (var i = 0; i < components.length - 1; i++) {
  1223.     host = components.slice(i).join(".");
  1224.     possible.push(host);
  1225.   }
  1226.  
  1227.   // Run the possible domains against the db.
  1228.   (new ExistsMultiQuerier(possible, this.name, callback)).run();
  1229. }
  1230.  
  1231. /////////////////////////////////////////////////////////////////////
  1232. // Enchash table implementation
  1233.  
  1234. function UrlClassifierTableEnchash() {
  1235.   UrlClassifierTable.call(this);
  1236.   this.debugZone = "urlclassifier-table-enchash";
  1237.   this.enchashDecrypter_ = new PROT_EnchashDecrypter();
  1238. }
  1239. UrlClassifierTableEnchash.inherits(UrlClassifierTable);
  1240.  
  1241. /**
  1242.  * Look up a URL in an enchashDB.  We try all sub domains (up to MAX_DOTS).
  1243.  */
  1244. UrlClassifierTableEnchash.prototype.exists = function(url, callback) {
  1245.   var host = this.enchashDecrypter_.getCanonicalHost(url);
  1246.  
  1247.   var possible = [];
  1248.   for (var i = 0; i < PROT_EnchashDecrypter.MAX_DOTS + 1; i++) {
  1249.     possible.push(host);
  1250.  
  1251.     var index = host.indexOf(".");
  1252.     if (index == -1)
  1253.       break;
  1254.     host = host.substring(index + 1);
  1255.   }
  1256.   // Run the possible domains against the db.
  1257.   (new EnchashMultiQuerier(possible, this.name, callback, url)).run();
  1258. }
  1259. //@line 47 "/build/buildd/firefox-1.99+2.0b1+dfsg/toolkit/components/url-classifier/src/nsUrlClassifierTable.js"
  1260.  
  1261. var modScope = this;
  1262. function Init() {
  1263.   // Pull the library in.
  1264.   var jslib = Cc["@mozilla.org/url-classifier/jslib;1"]
  1265.               .getService().wrappedJSObject;
  1266.   modScope.G_Preferences = jslib.G_Preferences;
  1267.   modScope.G_PreferenceObserver = jslib.G_PreferenceObserver;
  1268.   modScope.G_Debug = jslib.G_Debug;
  1269.   modScope.G_CryptoHasher = jslib.G_CryptoHasher;
  1270.   modScope.G_Base64 = jslib.G_Base64;
  1271.   modScope.ARC4 = jslib.ARC4;
  1272.   modScope.BindToObject = jslib.BindToObject;
  1273.  
  1274.   // We only need to call Init once.
  1275.   modScope.Init = function() {};
  1276. }
  1277.  
  1278.  
  1279. function UrlClassifierTableMod() {
  1280.   this.components = {};
  1281.   this.addComponent({
  1282.       cid: "{43399ee0-da0b-46a8-9541-08721265981c}",
  1283.       name: "UrlClassifier Table Url Module",
  1284.       progid: "@mozilla.org/url-classifier/table;1?type=url",
  1285.       factory: new UrlClassifierTableFactory(UrlClassifierTableUrl)
  1286.     });
  1287.   this.addComponent({
  1288.       cid: "{3b5004c6-3fcd-4b12-b311-a4dfbeaf27aa}",
  1289.       name: "UrlClassifier Table Domain Module",
  1290.       progid: "@mozilla.org/url-classifier/table;1?type=domain",
  1291.       factory: new UrlClassifierTableFactory(UrlClassifierTableDomain)
  1292.     });
  1293.   this.addComponent({
  1294.       cid: "{04f15d1d-2db8-4b8e-91d7-82f30308b434}",
  1295.       name: "UrlClassifier Table Enchash Module",
  1296.       progid: "@mozilla.org/url-classifier/table;1?type=enchash",
  1297.       factory: new UrlClassifierTableFactory(UrlClassifierTableEnchash)
  1298.     });
  1299. }
  1300.  
  1301. UrlClassifierTableMod.prototype.addComponent = function(comp) {
  1302.   this.components[comp.cid] = comp;
  1303. };
  1304.  
  1305. UrlClassifierTableMod.prototype.registerSelf = function(compMgr, fileSpec, loc, type) {
  1306.   compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
  1307.   // Register all the components
  1308.   for (var cid in this.components) {
  1309.     var comp = this.components[cid];
  1310.     compMgr.registerFactoryLocation(Components.ID(comp.cid),
  1311.                                     comp.name,
  1312.                                     comp.progid,
  1313.                                     fileSpec,
  1314.                                     loc,
  1315.                                     type);
  1316.   }
  1317. };
  1318.  
  1319. UrlClassifierTableMod.prototype.getClassObject = function(compMgr, cid, iid) {
  1320.   var comp = this.components[cid.toString()];
  1321.  
  1322.   if (!comp)
  1323.     throw Components.results.NS_ERROR_NO_INTERFACE;
  1324.   if (!iid.equals(Ci.nsIFactory))
  1325.     throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  1326.  
  1327.   return comp.factory;
  1328. };
  1329.  
  1330. UrlClassifierTableMod.prototype.canUnload = function(compMgr) {
  1331.   return true;
  1332. };
  1333.  
  1334. /**
  1335.  * Create a factory.
  1336.  * @param ctor Function constructor for the object we're creating.
  1337.  */
  1338. function UrlClassifierTableFactory(ctor) {
  1339.   this.ctor = ctor;
  1340. }
  1341.  
  1342. UrlClassifierTableFactory.prototype.createInstance = function(outer, iid) {
  1343.   if (outer != null)
  1344.     throw Components.results.NS_ERROR_NO_AGGREGATION;
  1345.   Init();
  1346.   return (new this.ctor()).QueryInterface(iid);
  1347. };
  1348.  
  1349. var modInst = new UrlClassifierTableMod();
  1350.  
  1351. function NSGetModule(compMgr, fileSpec) {
  1352.   return modInst;
  1353. }
  1354.