home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2006 February / maximum-cd-2006-02.iso / Software / Apps / firefox_setup_1.5.exe / browser.xpi / bin / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2005-11-11  |  95.0 KB  |  2,835 lines

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Mozilla Public License Version
  6.  * 1.1 (the "License"); you may not use this file except in compliance with
  7.  * the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/MPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is the Update Service.
  16.  *
  17.  * The Initial Developer of the Original Code is Ben Goodger.
  18.  * Portions created by the Initial Developer are Copyright (C) 2004
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *  Ben Goodger <ben@mozilla.org> (Original Author)
  23.  *  Darin Fisher <darin@meer.net>
  24.  *  Ben Turner <bent.mozilla@gmail.com>
  25.  *
  26.  * Alternatively, the contents of this file may be used under the terms of
  27.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  28.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  29.  * in which case the provisions of the GPL or the LGPL are applicable instead
  30.  * of those above. If you wish to allow use of your version of this file only
  31.  * under the terms of either the GPL or the LGPL, and not to allow others to
  32.  * use your version of this file under the terms of the MPL, indicate your
  33.  * decision by deleting the provisions above and replace them with the notice
  34.  * and other provisions required by the GPL or the LGPL. If you do not delete
  35.  * the provisions above, a recipient may use your version of this file under
  36.  * the terms of any one of the MPL, the GPL or the LGPL.
  37.  *
  38.  * ***** END LICENSE BLOCK ***** */
  39.  
  40. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  41. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  42. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  43. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  44. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  45. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  46. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  47. const PREF_APP_UPDATE_URL                 = "app.update.url";
  48. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  49. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  50. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  51. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  52. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  53. const PREF_APP_EXTENSIONS_VERSION         = "app.extensions.version";
  54. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  55. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  56.  
  57. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  58. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  59. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  60. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  61. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  62.  
  63. const KEY_APPDIR          = "XCurProcD";
  64.  
  65. const DIR_UPDATES         = "updates";
  66. const FILE_UPDATE_STATUS  = "update.status";
  67. const FILE_UPDATE_ARCHIVE = "update.mar";
  68. const FILE_UPDATE_LOG     = "update.log"
  69. const FILE_UPDATES_DB     = "updates.xml";
  70. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  71. const FILE_PERMS_TEST     = "update.test";
  72. const FILE_LAST_LOG       = "last-update.log";
  73.  
  74. const MODE_RDONLY   = 0x01;
  75. const MODE_WRONLY   = 0x02;
  76. const MODE_CREATE   = 0x08;
  77. const MODE_APPEND   = 0x10;
  78. const MODE_TRUNCATE = 0x20;
  79.  
  80. const PERMS_FILE      = 0644;
  81. const PERMS_DIRECTORY = 0755;
  82.  
  83. const STATE_NONE            = null;
  84. const STATE_DOWNLOADING     = "downloading";
  85. const STATE_PENDING         = "pending";
  86. const STATE_APPLYING        = "applying";
  87. const STATE_SUCCEEDED       = "succeeded";
  88. const STATE_DOWNLOAD_FAILED = "download-failed";
  89. const STATE_FAILED          = "failed";
  90.  
  91. // From updater/errors.h:
  92. const WRITE_ERROR = 7;
  93.  
  94. const DOWNLOAD_CHUNK_SIZE           = 65536;
  95. const DOWNLOAD_BACKGROUND_INTERVAL  = 60;  // seconds
  96. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  97.  
  98. // Values for the PREF_APP_UPDATE_INCOMPATIBLE_MODE pref. See documentation in
  99. // code below. 
  100. const INCOMPATIBLE_MODE_NEWVERSIONS   = 0;
  101. const INCOMPATIBLE_MODE_NONEWVERSIONS = 1;
  102.  
  103. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  104.  
  105. const nsILocalFile            = Components.interfaces.nsILocalFile;
  106. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  107. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  108. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  109. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  110. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  111. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  112. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  113.  
  114. const Node = Components.interfaces.nsIDOMNode;
  115.  
  116. var gApp        = null;
  117. var gPref       = null;
  118. var gOS         = null;
  119. var gConsole    = null;
  120. var gLogEnabled = { };
  121.  
  122. /**
  123.  * Logs a string to the error console. 
  124.  * @param   string
  125.  *          The string to write to the error console..
  126.  */  
  127. function LOG(module, string) {
  128.   if (module in gLogEnabled) {
  129.     dump("*** " + module + ":" + string + "\n");
  130.     gConsole.logStringMessage(string);
  131.   }
  132. }
  133.  
  134. /**
  135.  * Convert a string containing binary values to hex.
  136.  */
  137. function binaryToHex(input) {
  138.   var result = "";
  139.   for (var i = 0; i < input.length; ++i) {
  140.     var hex = input.charCodeAt(i).toString(16);
  141.     if (hex.length == 1)
  142.       hex = "0" + hex;
  143.     result += hex;
  144.   }
  145.   return result;
  146. }
  147.  
  148. /**
  149.  * Gets a File URL spec for a nsIFile
  150.  * @param   file
  151.  *          The file to get a file URL spec to
  152.  * @returns The file URL spec to the file
  153.  */
  154. function getURLSpecFromFile(file) {
  155.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  156.                          .getService(Components.interfaces.nsIIOService);
  157.   var fph = ioServ.getProtocolHandler("file")
  158.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  159.   return fph.getURLSpecFromFile(file);
  160. }
  161.  
  162. /**
  163.  * Gets the specified directory at the specified hierarchy under a 
  164.  * Directory Service key. 
  165.  * @param   key
  166.  *          The Directory Service Key to start from
  167.  * @param   pathArray
  168.  *          An array of path components to locate beneath the directory 
  169.  *          specified by |key|
  170.  * @return  nsIFile object for the location specified. If the directory
  171.  *          requested does not exist, it is created, along with any
  172.  *          parent directories that need to be created.
  173.  */
  174. function getDir(key, pathArray) {
  175.   return getDirInternal(key, pathArray, true);
  176. }
  177.  
  178. /**
  179.  * Gets the specified directory at the speciifed hierarchy under a 
  180.  * Directory Service key. 
  181.  * @param   key
  182.  *          The Directory Service Key to start from
  183.  * @param   pathArray
  184.  *          An array of path components to locate beneath the directory 
  185.  *          specified by |key|
  186.  * @return  nsIFile object for the location specified. If the directory
  187.  *          requested does not exist, it is NOT created.
  188.  */
  189. function getDirNoCreate(key, pathArray) {
  190.   return getDirInternal(key, pathArray, false);
  191. }
  192.  
  193. /**
  194.  * Gets the specified directory at the speciifed hierarchy under a 
  195.  * Directory Service key. 
  196.  * @param   key
  197.  *          The Directory Service Key to start from
  198.  * @param   pathArray
  199.  *          An array of path components to locate beneath the directory 
  200.  *          specified by |key|
  201.  * @param   shouldCreate
  202.  *          true if the directory hierarchy specified in |pathArray|
  203.  *          should be created if it does not exist,
  204.  *          false otherwise.
  205.  * @return  nsIFile object for the location specified. 
  206.  */
  207. function getDirInternal(key, pathArray, shouldCreate) {
  208.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  209.                               .getService(Components.interfaces.nsIProperties);
  210.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  211.   for (var i = 0; i < pathArray.length; ++i) {
  212.     dir.append(pathArray[i]);
  213.     if (shouldCreate && !dir.exists())
  214.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  215.   }
  216.   return dir;
  217. }
  218.  
  219. /**
  220.  * Gets the file at the speciifed hierarchy under a Directory Service key.
  221.  * @param   key
  222.  *          The Directory Service Key to start from
  223.  * @param   pathArray
  224.  *          An array of path components to locate beneath the directory 
  225.  *          specified by |key|. The last item in this array must be the
  226.  *          leaf name of a file.
  227.  * @return  nsIFile object for the file specified. The file is NOT created
  228.  *          if it does not exist, however all required directories along 
  229.  *          the way are.
  230.  */
  231. function getFile(key, pathArray) {
  232.   var file = getDir(key, pathArray.slice(0, -1));
  233.   file.append(pathArray[pathArray.length - 1]);
  234.   return file;
  235. }
  236.  
  237. /**
  238.  * Closes a Safe Output Stream
  239.  * @param   fos
  240.  *          The Safe Output Stream to close
  241.  */
  242. function closeSafeOutputStream(fos) {
  243.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  244.     try {
  245.       fos.finish();
  246.     }
  247.     catch (e) {
  248.       fos.close();
  249.     }
  250.   }
  251.   else
  252.     fos.close();
  253. }
  254.  
  255. /**
  256.  * Returns human readable status text from the updates.properties bundle
  257.  * based on an error code
  258.  * @param   code
  259.  *          The error code to look up human readable status text for
  260.  * @param   defaultCode
  261.  *          The default code to look up should human readable status text
  262.  *          not exist for |code|
  263.  * @returns A human readable status text string
  264.  */
  265. function getStatusTextFromCode(code, defaultCode) {
  266.   var sbs = 
  267.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  268.       getService(Components.interfaces.nsIStringBundleService);
  269.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  270.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  271.   try {
  272.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  273.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  274.   }
  275.   catch (e) {
  276.     // Use the default reason
  277.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  278.   }
  279.   return reason;
  280. }
  281.  
  282. /**
  283.  * Get the Active Updates directory
  284.  * @returns The active updates directory, as a nsIFile object
  285.  */
  286. function getUpdatesDir() {
  287.   // Right now, we only support downloading one patch at a time, so we always
  288.   // use the same target directory.
  289.   var fileLocator =
  290.       Components.classes["@mozilla.org/file/directory_service;1"].
  291.       getService(Components.interfaces.nsIProperties);
  292.   var appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  293.   appDir.append(DIR_UPDATES);
  294.   appDir.append("0");
  295.   if (!appDir.exists())
  296.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  297.   return appDir;
  298. }
  299.  
  300. /**
  301.  * Reads the update state from the update.status file in the specified
  302.  * directory.
  303.  * @param   dir
  304.  *          The dir to look for an update.status file in
  305.  * @returns The status value of the update.
  306.  */
  307. function readStatusFile(dir) {
  308.   var statusFile = dir.clone();
  309.   statusFile.append(FILE_UPDATE_STATUS);
  310.   LOG("General", "Reading Status File: " + statusFile.path);
  311.   return readStringFromFile(statusFile) || STATE_NONE;
  312. }
  313.  
  314. /**
  315.  * Writes the current update operation/state to a file in the patch 
  316.  * directory, indicating to the patching system that operations need
  317.  * to be performed.
  318.  * @param   dir
  319.  *          The patch directory where the update.status file should be 
  320.  *          written.
  321.  * @param   state
  322.  *          The state value to write.
  323.  */
  324. function writeStatusFile(dir, state) {
  325.   var statusFile = dir.clone();
  326.   statusFile.append(FILE_UPDATE_STATUS);
  327.   writeStringToFile(statusFile, state);
  328. }
  329.  
  330. /**
  331.  * Removes the Updates Directory
  332.  */
  333. function cleanUpUpdatesDir() {
  334.   // Bail out if we don't have appropriate permissions
  335.   var updateDir;
  336.   try {
  337.     updateDir = getUpdatesDir();
  338.   }
  339.   catch (e) {
  340.     return;
  341.   }
  342.         
  343.   var e = updateDir.directoryEntries;
  344.   while (e.hasMoreElements()) {
  345.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  346.     // Preserve the last update log file for debugging purposes
  347.     if (f.leafName == FILE_UPDATE_LOG) {
  348.       try {
  349.         var dir = f.parent.parent;
  350.         var logFile = dir.clone();
  351.         logFile.append(FILE_LAST_LOG);
  352.         if (logFile.exists())
  353.           logFile.remove(false);
  354.         f.copyTo(dir, FILE_LAST_LOG);
  355.       }
  356.       catch (e) {
  357.         LOG("General", "Failed to copy file: " + f.path);
  358.       }
  359.     }
  360.     // Now, recursively remove this file.  The recusive removal is really
  361.     // only needed on Mac OSX because this directory will contain a copy of
  362.     // updater.app, which is itself a directory.
  363.     try {
  364.       f.remove(true);
  365.     }
  366.     catch (e) {
  367.       LOG("General", "Failed to remove file: " + f.path);
  368.     }
  369.   }
  370.   try {
  371.     updateDir.remove(false);
  372.   } catch (e) {
  373.     LOG("General", "Failed to remove update directory: " + updateDir.path + 
  374.         " - This is almost always bad. Exception = " + e);
  375.     throw e;
  376.   }
  377. }
  378.  
  379. /**
  380.  * Clean up updates list and the updates directory.
  381.  */
  382. function cleanupActiveUpdate() {
  383.   // Move the update from the Active Update list into the Past Updates list.
  384.   var um = 
  385.       Components.classes["@mozilla.org/updates/update-manager;1"].
  386.       getService(Components.interfaces.nsIUpdateManager);
  387.   um.activeUpdate = null;
  388.   um.saveUpdates();
  389.  
  390.   // Now trash the updates directory, since we're done with it
  391.   cleanUpUpdatesDir();
  392. }
  393.  
  394. /**
  395.  * Gets a preference value, handling the case where there is no default.
  396.  * @param   func
  397.  *          The name of the preference function to call, on nsIPrefBranch
  398.  * @param   preference
  399.  *          The name of the preference
  400.  * @param   defaultValue
  401.  *          The default value to return in the event the preference has 
  402.  *          no setting
  403.  * @returns The value of the preference, or undefined if there was no
  404.  *          user or default value.
  405.  */
  406. function getPref(func, preference, defaultValue) {
  407.   try {
  408.     return gPref[func](preference);
  409.   }
  410.   catch (e) {
  411.   }
  412.   return defaultValue;
  413. }
  414.  
  415. /**
  416.  * Gets the current value of the locale.  It's possible for this preference to
  417.  * be localized, so we have to do a little extra work here.  Similar code
  418.  * exists in nsHttpHandler.cpp when building the UA string.
  419.  */
  420. function getLocale() {
  421.   try {
  422.     return gPref.getComplexValue(PREF_GENERAL_USERAGENT_LOCALE,
  423.                                  nsIPrefLocalizedString).data;
  424.   } catch (e) {}
  425.  
  426.   return gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  427. }
  428.  
  429. /**
  430.  * An enumeration of items in a JS array.
  431.  * @constructor
  432.  */
  433. function ArrayEnumerator(aItems) {
  434.   this._index = 0;
  435.   if (aItems) {
  436.     for (var i = 0; i < aItems.length; ++i) {
  437.       if (!aItems[i])
  438.         aItems.splice(i, 1);      
  439.     }
  440.   }
  441.   this._contents = aItems;
  442. }
  443.  
  444. ArrayEnumerator.prototype = {
  445.   _index: 0,
  446.   _contents: [],
  447.   
  448.   hasMoreElements: function() {
  449.     return this._index < this._contents.length;
  450.   },
  451.   
  452.   getNext: function() {
  453.     return this._contents[this._index++];      
  454.   }
  455. };
  456.  
  457. /**
  458.  * Trims a prefix from a string.
  459.  * @param   string
  460.  *          The source string
  461.  * @param   prefix
  462.  *          The prefix to remove.
  463.  * @returns The suffix (string - prefix)
  464.  */
  465. function stripPrefix(string, prefix) {
  466.   return string.substr(prefix.length);
  467. }
  468.  
  469. /**
  470.  * Writes a string of text to a file.  A newline will be appended to the data
  471.  * written to the file.  This function only works with ASCII text.
  472.  */
  473. function writeStringToFile(file, text) {
  474.   var fos =
  475.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  476.       createInstance(nsIFileOutputStream);
  477.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  478.   if (!file.exists()) 
  479.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  480.   fos.init(file, modeFlags, PERMS_FILE, 0);
  481.   text += "\n";
  482.   fos.write(text, text.length);    
  483.   closeSafeOutputStream(fos);
  484. }
  485.  
  486. /**
  487.  * Reads a string of text from a file.  A trailing newline will be removed
  488.  * before the result is returned.  This function only works with ASCII text.
  489.  */
  490. function readStringFromFile(file) {
  491.   var fis =
  492.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  493.       createInstance(nsIFileInputStream);
  494.   var modeFlags = MODE_RDONLY;
  495.   if (!file.exists())
  496.     return null;
  497.   fis.init(file, modeFlags, PERMS_FILE, 0);
  498.   var sis =
  499.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  500.       createInstance(Components.interfaces.nsIScriptableInputStream);
  501.   sis.init(fis);
  502.   var text = sis.read(sis.available());
  503.   sis.close();
  504.   if (text[text.length - 1] == "\n")
  505.     text = text.slice(0, -1);
  506.   return text;
  507. }
  508.  
  509. /**
  510.  * Update Patch
  511.  * @param   patch
  512.  *          A <patch> element to initialize this object with
  513.  * @constructor
  514.  */
  515. function UpdatePatch(patch) {
  516.   this._properties = {};
  517.   for (var i = 0; i < patch.attributes.length; ++i) {
  518.     var attr = patch.attributes.item(i);
  519.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  520.     switch (attr.name) {
  521.     case "selected":
  522.       this.selected = attr.value == "true";
  523.       break;
  524.     default:
  525.       this[attr.name] = attr.value;
  526.       break;
  527.     };
  528.   }
  529. }
  530. UpdatePatch.prototype = {
  531.   /**
  532.    * See nsIUpdateService.idl
  533.    */
  534.   serialize: function(updates) {
  535.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  536.     patch.setAttribute("type", this.type);
  537.     patch.setAttribute("URL", this.URL);
  538.     patch.setAttribute("hashFunction", this.hashFunction);
  539.     patch.setAttribute("hashValue", this.hashValue);
  540.     patch.setAttribute("size", this.size);
  541.     patch.setAttribute("selected", this.selected);
  542.     patch.setAttribute("state", this.state);
  543.     
  544.     for (var p in this._properties) {
  545.       if (this._properties[p].present)
  546.         patch.setAttribute(p, this._properties[p].data);
  547.     }
  548.     
  549.     return patch; 
  550.   },
  551.   
  552.   /**
  553.    * A hash of custom properties
  554.    */
  555.   _properties: null,
  556.   
  557.   /**
  558.    * See nsIWritablePropertyBag.idl
  559.    */
  560.   setProperty: function(name, value) {
  561.     this._properties[name] = { data: value, present: true };
  562.   },
  563.   
  564.   /**
  565.    * See nsIWritablePropertyBag.idl
  566.    */
  567.   deleteProperty: function(name) {
  568.     if (name in this._properties)
  569.       this._properties[name].present = false;
  570.     else
  571.       throw Components.results.NS_ERROR_FAILURE;
  572.   },
  573.   
  574.   /**
  575.    * See nsIPropertyBag.idl
  576.    */
  577.   get enumerator() {
  578.     var properties = [];
  579.     for (var p in this._properties)
  580.       properties.push(this._properties[p].data);
  581.     return new ArrayEnumerator(properties);
  582.   },
  583.   
  584.   /**
  585.    * See nsIPropertyBag.idl
  586.    */
  587.   getProperty: function(name) {
  588.     if (name in this._properties &&
  589.         this._properties[name].present)
  590.       return this._properties[name].data;
  591.     throw Components.results.NS_ERROR_FAILURE;
  592.   },
  593.   
  594.   /**
  595.    * Returns whether or not the update.status file for this patch exists at the 
  596.    * appropriate location. 
  597.    */
  598.   get statusFileExists() {
  599.     var statusFile = getUpdatesDir();
  600.     statusFile.append(FILE_UPDATE_STATUS);
  601.     return statusFile.exists();
  602.   },
  603.   
  604.   /**
  605.    * See nsIUpdateService.idl
  606.    */
  607.   get state() {
  608.     if (!this.statusFileExists)
  609.       return STATE_NONE;
  610.     return this._properties.state;
  611.   },
  612.   set state(val) {
  613.     this._properties.state = val;
  614.   },
  615.   
  616.   /**
  617.    * See nsISupports.idl
  618.    */
  619.   QueryInterface: function(iid) {
  620.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  621.         !iid.equals(Components.interfaces.nsIPropertyBag) && 
  622.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) && 
  623.         !iid.equals(Components.interfaces.nsISupports))
  624.       throw Components.results.NS_ERROR_NO_INTERFACE;
  625.     return this;
  626.   }
  627. };
  628.  
  629. /**
  630.  * Update
  631.  * Implements nsIUpdate
  632.  * @param   update
  633.  *          An <update> element to initialize this object with
  634.  * @constructor
  635.  */
  636. function Update(update) {
  637.   this._properties = {};
  638.   this._patches = [];
  639.   this.installDate = 0;
  640.   this.isCompleteUpdate = false;
  641.  
  642.   // Null <update>, assume this is a message container and do no 
  643.   // further initialization
  644.   if (!update)
  645.     return;
  646.     
  647.   for (var i = 0; i < update.childNodes.length; ++i) {
  648.     var patchElement = update.childNodes.item(i);
  649.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  650.         patchElement.localName != "patch")
  651.       continue;
  652.  
  653.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  654.     this._patches.push(new UpdatePatch(patchElement));
  655.   }
  656.  
  657.   for (var i = 0; i < update.attributes.length; ++i) {
  658.     var attr = update.attributes.item(i);
  659.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  660.     if (attr.name == "installDate" && attr.value) 
  661.       this.installDate = parseInt(attr.value);
  662.     else if (attr.name == "isCompleteUpdate")
  663.       this.isCompleteUpdate = attr.value == "true";
  664.     else if (attr.name == "isSecurityUpdate")
  665.       this.isSecurityUpdate = attr.value == "true";
  666.     else if (attr.name == "detailsURL")
  667.       this._detailsURL = attr.value;
  668.     else
  669.       this[attr.name] = attr.value;
  670.   }
  671.   
  672.   // The Update Name is either the string provided by the <update> element, or
  673.   // the string: "<App Name> <Update App Version>"
  674.   var name = "";
  675.   if (update.hasAttribute("name"))
  676.     name = update.getAttribute("name");
  677.   else {
  678.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  679.                         .getService(Components.interfaces.nsIStringBundleService);
  680.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  681.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  682.     var appName = brandBundle.GetStringFromName("brandShortName");
  683.     name = updateBundle.formatStringFromName("updateName", 
  684.                                              [appName, this.version], 2);
  685.   }
  686.   this.name = name;
  687. }
  688. Update.prototype = {
  689.   /**
  690.    * See nsIUpdateService.idl
  691.    */
  692.   get patchCount() {
  693.     return this._patches.length;
  694.   },
  695.   
  696.   /**
  697.    * See nsIUpdateService.idl
  698.    */
  699.   getPatchAt: function(index) {
  700.     return this._patches[index];
  701.   },
  702.  
  703.   /**
  704.    * See nsIUpdateService.idl
  705.    * 
  706.    * We use a copy of the state cached on this object in |_state| only when 
  707.    * there is no selected patch, i.e. in the case when we could not load 
  708.    * |.activeUpdate| from the update manager for some reason but still have
  709.    * the update.status file to work with. 
  710.    */
  711.   _state: "",
  712.   set state(state) {
  713.     if (this.selectedPatch)
  714.       this.selectedPatch.state = state;
  715.     this._state = state;
  716.     return state;
  717.   },
  718.   get state() {
  719.     if (this.selectedPatch)
  720.       return this.selectedPatch.state;
  721.     return this._state;
  722.   },
  723.  
  724.   /**
  725.    * See nsIUpdateService.idl
  726.    */
  727.   errorCode: 0,
  728.     
  729.   /**
  730.    * See nsIUpdateService.idl
  731.    */
  732.   get selectedPatch() {
  733.     for (var i = 0; i < this.patchCount; ++i) {
  734.       if (this._patches[i].selected)
  735.         return this._patches[i];
  736.     }
  737.     return null;
  738.   },
  739.   
  740.   /**
  741.    * See nsIUpdateService.idl
  742.    */
  743.   get detailsURL() {
  744.     if (!this._detailsURL) {
  745.       try {
  746.         // Try using a default details URL supplied by the distribution
  747.         // if the update XML does not supply one.
  748.         return gPref.getComplexValue(PREF_APP_UPDATE_URL_DETAILS,
  749.                                      nsIPrefLocalizedString).data;
  750.       }
  751.       catch (e) {
  752.       }
  753.     }
  754.     return this._detailsURL || "";
  755.   },
  756.   
  757.   /**
  758.    * See nsIUpdateService.idl
  759.    */
  760.   serialize: function(updates) {
  761.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  762.     update.setAttribute("type", this.type);
  763.     update.setAttribute("name", this.name);
  764.     update.setAttribute("version", this.version);
  765.     update.setAttribute("extensionVersion", this.extensionVersion);
  766.     update.setAttribute("detailsURL", this.detailsURL);
  767.     update.setAttribute("licenseURL", this.licenseURL);
  768.     update.setAttribute("serviceURL", this.serviceURL);
  769.     update.setAttribute("installDate", this.installDate);
  770.     update.setAttribute("statusText", this.statusText);
  771.     update.setAttribute("buildID", this.buildID);
  772.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  773.     updates.documentElement.appendChild(update);
  774.     
  775.     for (var p in this._properties) {
  776.       if (this._properties[p].present)
  777.         update.setAttribute(p, this._properties[p].data);
  778.     }
  779.     
  780.     for (var i = 0; i < this.patchCount; ++i)
  781.       update.appendChild(this.getPatchAt(i).serialize(updates));
  782.     
  783.     return update;
  784.   },
  785.    
  786.   /**
  787.    * A hash of custom properties
  788.    */
  789.   _properties: null,
  790.   
  791.   /**
  792.    * See nsIWritablePropertyBag.idl
  793.    */
  794.   setProperty: function(name, value) {
  795.     this._properties[name] = { data: value, present: true };
  796.   },
  797.   
  798.   /**
  799.    * See nsIWritablePropertyBag.idl
  800.    */
  801.   deleteProperty: function(name) {
  802.     if (name in this._properties)
  803.       this._properties[name].present = false;
  804.     else
  805.       throw Components.results.NS_ERROR_FAILURE;
  806.   },
  807.   
  808.   /**
  809.    * See nsIPropertyBag.idl
  810.    */
  811.   get enumerator() {
  812.     var properties = [];
  813.     for (var p in this._properties)
  814.       properties.push(this._properties[p].data);
  815.     return new ArrayEnumerator(properties);
  816.   },
  817.   
  818.   /**
  819.    * See nsIPropertyBag.idl
  820.    */
  821.   getProperty: function(name) {
  822.     if (name in this._properties &&
  823.         this._properties[name].present)
  824.       return this._properties[name].data;
  825.     throw Components.results.NS_ERROR_FAILURE;
  826.   },
  827.   
  828.   /**
  829.    * See nsISupports.idl
  830.    */
  831.   QueryInterface: function(iid) {
  832.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  833.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  834.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  835.         !iid.equals(Components.interfaces.nsISupports))
  836.       throw Components.results.NS_ERROR_NO_INTERFACE;
  837.     return this;
  838.   }
  839. }; 
  840.  
  841. /**
  842.  * UpdateService
  843.  * A Service for managing the discovery and installation of software updates.
  844.  * @constructor
  845.  */
  846. function UpdateService() {
  847.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  848.                     .getService(Components.interfaces.nsIXULAppInfo)
  849.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  850.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  851.                     .getService(Components.interfaces.nsIPrefBranch2);
  852.   gOS   = Components.classes["@mozilla.org/observer-service;1"]
  853.                     .getService(Components.interfaces.nsIObserverService);
  854.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  855.                        .getService(Components.interfaces.nsIConsoleService);  
  856.  
  857.   // Start the update timer only after a profile has been selected so that the
  858.   // appropriate values for the update check are read from the user's profile.  
  859.   gOS.addObserver(this, "profile-after-change", false);
  860.  
  861.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid 
  862.   // shutdown leaks.
  863.   gOS.addObserver(this, "xpcom-shutdown", false);
  864. }
  865.  
  866. UpdateService.prototype = {
  867.   /**
  868.    * The downloader we are using to download updates. There is only ever one of
  869.    * these.
  870.    */
  871.   _downloader: null,
  872.  
  873.   /**
  874.    * Handle Observer Service notifications
  875.    * @param   subject
  876.    *          The subject of the notification
  877.    * @param   topic
  878.    *          The notification name
  879.    * @param   data
  880.    *          Additional data
  881.    */
  882.   observe: function(subject, topic, data) {
  883.     switch (topic) {
  884.     case "profile-after-change":
  885.       gOS.removeObserver(this, "profile-after-change");
  886.       this._start();
  887.       break;
  888.     case "xpcom-shutdown":
  889.       gOS.removeObserver(this, "xpcom-shutdown");
  890.       
  891.       // Release Services
  892.       gApp      = null;
  893.       gPref     = null;
  894.       gOS       = null;
  895.       gConsole  = null;
  896.       break;
  897.     }
  898.   },
  899.   
  900.   /**
  901.    * Start the Update Service
  902.    */
  903.   _start: function() {
  904.     // Start logging
  905.     this._initLoggingPrefs();
  906.     
  907.     // Clean up any extant updates
  908.     this._postUpdateProcessing();
  909.  
  910.     // Register a background update check timer
  911.     var tm = 
  912.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  913.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  914.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  915.     tm.registerTimer("background-update-timer", this, interval);
  916.  
  917.     // Resume fetching...
  918.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  919.                         .getService(Components.interfaces.nsIUpdateManager);
  920.     var activeUpdate = um.activeUpdate;
  921.     if (activeUpdate) {
  922.       var status = this.downloadUpdate(activeUpdate, true);
  923.       if (status == STATE_NONE)
  924.         cleanupActiveUpdate();
  925.     }
  926.   },
  927.   
  928.   /**
  929.    * Perform post-processing on updates lingering in the updates directory
  930.    * from a previous browser session - either report install failures (and
  931.    * optionally attempt to fetch a different version if appropriate) or 
  932.    * notify the user of install success.
  933.    */
  934.   _postUpdateProcessing: function() {
  935.     // Detect installation failures and notify
  936.     
  937.     // Bail out if we don't have appropriate permissions
  938.     if (!this.canUpdate)
  939.       return;
  940.       
  941.     var status = readStatusFile(getUpdatesDir()); 
  942.  
  943.     // Make sure to cleanup after an update that failed for an unknown reason
  944.     if (status == "null")
  945.       status = null;
  946.  
  947.     if (status == STATE_DOWNLOADING) {
  948.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  949.     }
  950.     else if (status != null) {
  951.       // null status means the update.status file is not present, because either:
  952.       // 1) no update was performed, and so there's no UI to show
  953.       // 2) an update was attempted but failed during checking, transfer or 
  954.       //    verification, and was cleaned up at that point, and UI notifying of
  955.       //    that error was shown at that stage. 
  956.       var um = 
  957.           Components.classes["@mozilla.org/updates/update-manager;1"].
  958.           getService(Components.interfaces.nsIUpdateManager);
  959.       var prompter = 
  960.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  961.           createInstance(Components.interfaces.nsIUpdatePrompt);
  962.  
  963.       var shouldCleanup = true;
  964.       var update = um.activeUpdate;
  965.       if (!update) {
  966.         if ((status == STATE_SUCCEEDED) && (um.updateCount >= 1))
  967.           update = um.getUpdateAt(0);
  968.         else
  969.           update = new Update(null);
  970.       }
  971.       update.state = status;
  972.       var sbs = 
  973.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  974.           getService(Components.interfaces.nsIStringBundleService);
  975.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  976.       if (status == STATE_SUCCEEDED) {
  977.         update.statusText = bundle.GetStringFromName("installSuccess");
  978.         
  979.         // Dig through the update history to find the patch that was just
  980.         // installed and update its metadata.
  981.         for (var i = 0; i < um.updateCount; ++i) {
  982.           var umUpdate = um.getUpdateAt(i);
  983.           if (umUpdate && umUpdate.version == update.version &&
  984.                           umUpdate.buildID == update.buildID) {
  985.             umUpdate.statusText = update.statusText;
  986.             break;
  987.           }
  988.         }
  989.  
  990.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  991.         prompter.showUpdateInstalled(update);
  992.  
  993.         // Perform platform-specific post-update processing.
  994.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  995.           Components.classes[POST_UPDATE_CONTRACTID].
  996.               createInstance(Components.interfaces.nsIRunnable).run();
  997.         }
  998.         
  999.         // Done with this update. Clean it up.
  1000.         cleanupActiveUpdate();
  1001.       }
  1002.       else {
  1003.         // If we hit an error, then the error code will be included in the
  1004.         // status string following a colon.  If we had an I/O error, then we
  1005.         // assume that the patch is not invalid, and we restage the patch so
  1006.         // that it can be attempted again the next time we restart.
  1007.         var ary = status.split(": ");
  1008.         update.state = ary[0];
  1009.         if (update.state == STATE_FAILED && ary[1]) {
  1010.           update.errorCode = ary[1];
  1011.           if (update.errorCode == WRITE_ERROR) {
  1012.             prompter.showUpdateError(update);
  1013.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1014.             return;
  1015.           }
  1016.         }
  1017.  
  1018.         // Something went wrong with the patch application process.
  1019.         cleanupActiveUpdate();
  1020.  
  1021.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1022.         var oldType = update.selectedPatch ? update.selectedPatch.type 
  1023.                                            : "complete";
  1024.         if (update.selectedPatch && oldType == "partial") {
  1025.           // Partial patch application failed, try downloading the complete
  1026.           // update in the background instead.
  1027.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " + 
  1028.               "failed, downloading Complete Patch and maybe showing UI");
  1029.           var status = this.downloadUpdate(update, true);
  1030.           if (status == STATE_NONE)
  1031.             cleanupActiveUpdate();
  1032.         }
  1033.         else {
  1034.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " + 
  1035.               "only patch failed. Showing error.");
  1036.         }
  1037.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1038.         update.setProperty("patchingFailed", oldType);
  1039.         prompter.showUpdateError(update);
  1040.       }
  1041.     }
  1042.     else {
  1043.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1044.     }
  1045.   },
  1046.  
  1047.   /**
  1048.    * Initialize Logging preferences, formatted like so:
  1049.    *  app.update.log.<moduleName> = <true|false>
  1050.    */
  1051.   _initLoggingPrefs: function() {
  1052.     try {
  1053.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1054.                         .getService(Components.interfaces.nsIPrefService);
  1055.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1056.       var modules = logBranch.getChildList("", { value: 0 });
  1057.  
  1058.       for (var i = 0; i < modules.length; ++i) {
  1059.         if (logBranch.prefHasUserValue(modules[i]))
  1060.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1061.       }
  1062.     }
  1063.     catch (e) {
  1064.     }
  1065.   },
  1066.   
  1067.   /**
  1068.    *
  1069.    */
  1070.   _needsToPromptForUpdate: function(updates) {
  1071.     // First, check for Extension incompatibilities. These trump any preference
  1072.     // settings.
  1073.     var em = Components.classes["@mozilla.org/extensions/manager;1"]
  1074.                        .getService(Components.interfaces.nsIExtensionManager);
  1075.     var incompatibleList = { };
  1076.     for (var i = 0; i < updates.length; ++i) {
  1077.       var count = {};
  1078.       em.getIncompatibleItemList(gApp.ID, updates[i].extensionVersion,
  1079.                                  nsIUpdateItem.TYPE_ADDON, false, count);
  1080.       if (count.value > 0)
  1081.         return true;
  1082.     }
  1083.  
  1084.     // Now, inspect user preferences.
  1085.     
  1086.     // No prompt necessary, silently update...
  1087.     return false;
  1088.   },
  1089.   
  1090.   /**
  1091.    * Notified when a timer fires
  1092.    * @param   timer
  1093.    *          The timer that fired
  1094.    */
  1095.   notify: function(timer) {
  1096.     // If a download is in progress, then do nothing.
  1097.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1098.       return;
  1099.  
  1100.     var self = this;
  1101.     var listener = {
  1102.       /**
  1103.        * See nsIUpdateService.idl
  1104.        */
  1105.       onProgress: function(request, position, totalSize) { 
  1106.       },
  1107.       
  1108.       /**
  1109.        * See nsIUpdateService.idl
  1110.        */
  1111.       onCheckComplete: function(request, updates, updateCount) {
  1112.         self._selectAndInstallUpdate(updates);
  1113.       },
  1114.  
  1115.       /**
  1116.        * See nsIUpdateService.idl
  1117.        */
  1118.       onError: function(request, update) { 
  1119.         LOG("Checker", "Error during background update: " + update.statusText);
  1120.       },
  1121.     }
  1122.     this.backgroundChecker.checkForUpdates(listener, false);
  1123.   },
  1124.   
  1125.   /**
  1126.    * Determine whether or not an update requires user confirmation before it
  1127.    * can be installed.
  1128.    * @param   update
  1129.    *          The update to be installed
  1130.    * @returns true if a prompt UI should be shown asking the user if they want
  1131.    *          to install the update, false if the update should just be 
  1132.    *          silently downloaded and installed.
  1133.    */
  1134.   _shouldPrompt: function(update) {
  1135.     // There are two possible outcomes here:
  1136.     // 1. download and install the update automatically
  1137.     // 2. alert the user about the presence of an update before doing anything
  1138.     //
  1139.     // The outcome we follow is determined as follows:
  1140.     // 
  1141.     // Update Type      Mode      Incompatible    Outcome
  1142.     // Major            0         Yes or No       Auto Install
  1143.     // Major            1         No              Auto Install
  1144.     // Major            1         Yes             Notify and Confirm
  1145.     // Major            2         Yes or No       Notify and Confirm
  1146.     // Minor            0         Yes or No       Auto Install
  1147.     // Minor            1         No              Auto Install
  1148.     // Minor            1         Yes             Notify and Confirm
  1149.     // Minor            2         No              Auto Install
  1150.     // Minor            2         Yes             Notify and Confirm
  1151.     //
  1152.     // In addition, if there is a license associated with an update, regardless
  1153.     // of type it must be agreed to. 
  1154.     //
  1155.     // If app.update.enabled is set to false, an update check is not performed
  1156.     // at all, and so none of the decision making above is entered into.
  1157.     //
  1158.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1159.     try {
  1160.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1161.     }
  1162.     catch (e) {
  1163.       licenseAccepted = false;
  1164.     }
  1165.     if (update.licenseURL && !licenseAccepted) {
  1166.       LOG("Checker", "_shouldPrompt: Prompting because of an un-accepted " + 
  1167.           "license");
  1168.       return true;
  1169.     }
  1170.     
  1171.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1172.     if (!updateEnabled) {
  1173.       LOG("Checker", "_shouldPrompt: Not prompting because update is " + 
  1174.           "disabled");
  1175.       return false;
  1176.     }
  1177.     
  1178.     // User has turned off automatic download and install
  1179.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1180.     if (!autoEnabled) {
  1181.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1182.       return true;
  1183.     }
  1184.     
  1185.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1186.     case 1:
  1187.       // Mode 1 is do not prompt only if there are no incompatibilities
  1188.       // releases
  1189.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1190.       return !isCompatible(update);
  1191.     case 2:
  1192.       // Mode 2 is do not prompt only if there are no incompatibilities for 
  1193.       // minor updates only
  1194.       LOG("Checker", "_shouldPrompt: Prompting if major or there are " + 
  1195.           "incompatibilities");
  1196.       return update.type == "minor" ? !isCompatible(update) : true;
  1197.     }
  1198.     // Mode 0 is do not prompt regardless of incompatibilities
  1199.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1200.         "ignore incompatibilities");
  1201.     return false;
  1202.   },
  1203.   
  1204.   /**
  1205.    * Determine which of the specified updates should be installed.
  1206.    * @param   updates
  1207.    *          An array of available updates
  1208.    */
  1209.   selectUpdate: function(updates) {
  1210.     if (updates.length == 0)
  1211.       return null;
  1212.     
  1213.     // Choose the newest of the available minor and major updates. 
  1214.     var majorUpdate = null, minorUpdate = null;
  1215.     var newestMinor = updates[0], newestMajor = updates[0];
  1216.  
  1217.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1218.                        .getService(Components.interfaces.nsIVersionComparator);
  1219.     for (var i = 0; i < updates.length; ++i) {
  1220.       if (updates[i].type == "major" && 
  1221.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1222.         majorUpdate = newestMajor = updates[i];
  1223.       if (updates[i].type == "minor" && 
  1224.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1225.         minorUpdate = newestMinor = updates[i];
  1226.     }
  1227.  
  1228.     // If there's a major update, always try and fetch that one first, 
  1229.     // otherwise fall back to the newest minor update.
  1230.     return majorUpdate || minorUpdate;
  1231.   },
  1232.   
  1233.   /**
  1234.    * Determine which of the specified updates should be installed and
  1235.    * begin the download/installation process, optionally prompting the
  1236.    * user for permission if required.
  1237.    * @param   updates
  1238.    *          An array of available updates
  1239.    */
  1240.   _selectAndInstallUpdate: function(updates) {
  1241.     // Don't prompt if there's an active update - the user is already 
  1242.     // aware and is downloading, or performed some user action to prevent
  1243.     // notification.
  1244.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1245.                        .getService(Components.interfaces.nsIUpdateManager);
  1246.     if (um.activeUpdate)
  1247.       return;
  1248.     
  1249.     var update = this.selectUpdate(updates, updates.length);
  1250.     if (!update)
  1251.       return;
  1252.     
  1253.     if (this._shouldPrompt(update))
  1254.       showPromptIfNoIncompatibilities(update);
  1255.     else {
  1256.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1257.       var status = this.downloadUpdate(update, true);
  1258.       if (status == STATE_NONE)
  1259.         cleanupActiveUpdate();
  1260.     }
  1261.   },
  1262.  
  1263.   /**
  1264.    * The Checker used for background update checks.
  1265.    */
  1266.   _backgroundChecker: null,
  1267.   
  1268.   /**
  1269.    * See nsIUpdateService.idl
  1270.    */
  1271.   get backgroundChecker() {
  1272.     if (!this._backgroundChecker) 
  1273.       this._backgroundChecker = new Checker();
  1274.     return this._backgroundChecker;
  1275.   },
  1276.   
  1277.   /**
  1278.    * See nsIUpdateService.idl
  1279.    */
  1280.   get canUpdate() {
  1281.     try {
  1282.       var appDirFile = getFile(KEY_APPDIR, [FILE_PERMS_TEST]);
  1283.       if (!appDirFile.exists()) {
  1284.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1285.         appDirFile.remove(false);
  1286.       }
  1287.       var updateDir = getUpdatesDir();
  1288.       var upDirFile = updateDir.clone();
  1289.       upDirFile.append(FILE_PERMS_TEST);
  1290.       if (!upDirFile.exists()) {
  1291.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1292.         upDirFile.remove(false);
  1293.       }
  1294.     }
  1295.     catch (e) {
  1296.       // No write privileges to install directory
  1297.       return false;
  1298.     }
  1299.     // If the administrator has locked the app update functionality 
  1300.     // OFF - this is not just a user setting, so disable the manual
  1301.     // UI too.
  1302.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1303.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED))
  1304.       return false;
  1305.     return true;
  1306.   },
  1307.   
  1308.   /**
  1309.    * See nsIUpdateService.idl
  1310.    */
  1311.   addDownloadListener: function(listener) {
  1312.     if (!this._downloader) {
  1313.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1314.       return;
  1315.     }
  1316.     this._downloader.addDownloadListener(listener);
  1317.   },
  1318.   
  1319.   /**
  1320.    * See nsIUpdateService.idl
  1321.    */
  1322.   removeDownloadListener: function(listener) {
  1323.     if (!this._downloader) {
  1324.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1325.       return;
  1326.     }
  1327.     this._downloader.removeDownloadListener(listener);
  1328.   },
  1329.   
  1330.   /**
  1331.    * See nsIUpdateService.idl
  1332.    */
  1333.   downloadUpdate: function(update, background) {
  1334.     if (!update)
  1335.       throw Components.results.NS_ERROR_NULL_POINTER;
  1336.     if (this.isDownloading) {
  1337.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1338.           background == this._downloader.background) {
  1339.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1340.         return readStatusFile(getUpdatesDir());
  1341.       }
  1342.       this._downloader.cancel();
  1343.     }
  1344.     this._downloader = new Downloader(background);
  1345.     return this._downloader.downloadUpdate(update);
  1346.   },
  1347.   
  1348.   /**
  1349.    * See nsIUpdateService.idl
  1350.    */
  1351.   pauseDownload: function() {
  1352.     if (this.isDownloading)
  1353.       this._downloader.cancel();
  1354.   },
  1355.   
  1356.   /**
  1357.    * See nsIUpdateService.idl
  1358.    */
  1359.   get isDownloading() {
  1360.     return this._downloader && this._downloader.isBusy;
  1361.   },
  1362.   
  1363.   /**
  1364.    * See nsISupports.idl
  1365.    */
  1366.   QueryInterface: function(iid) {
  1367.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1368.         !iid.equals(Components.interfaces.nsITimerCallback) && 
  1369.         !iid.equals(Components.interfaces.nsIObserver) && 
  1370.         !iid.equals(Components.interfaces.nsISupports))
  1371.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1372.     return this;
  1373.   }
  1374. };
  1375.  
  1376. /**
  1377.  * A service to manage active and past updates.
  1378.  * @constructor
  1379.  */
  1380. function UpdateManager() {
  1381.   // Ensure the Active Update file is loaded
  1382.   var updates = this._loadXMLFileIntoArray(getFile(KEY_APPDIR, 
  1383.     [FILE_UPDATE_ACTIVE]));
  1384.   if (updates.length > 0)
  1385.     this._activeUpdate = updates[0];
  1386. }
  1387. UpdateManager.prototype = {
  1388.   /**
  1389.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1390.    * objects.
  1391.    */
  1392.   _updates: null,
  1393.   
  1394.   /**
  1395.    * The current actively downloading/installing update, as a nsIUpdate object.
  1396.    */
  1397.   _activeUpdate: null,
  1398.   
  1399.   /**
  1400.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1401.    * @param   file
  1402.    *          A nsIFile for the updates.xml file
  1403.    * @returns The array of nsIUpdate items held in the file.
  1404.    */
  1405.   _loadXMLFileIntoArray: function(file) {
  1406.     if (!file.exists()) {
  1407.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1408.       return [];
  1409.     }
  1410.  
  1411.     var result = [];
  1412.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1413.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1414.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1415.     try {
  1416.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1417.                             .createInstance(Components.interfaces.nsIDOMParser);
  1418.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1419.       
  1420.       var updateCount = doc.documentElement.childNodes.length;
  1421.       for (var i = 0; i < updateCount; ++i) {
  1422.         var updateElement = doc.documentElement.childNodes.item(i);
  1423.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1424.             updateElement.localName != "update")
  1425.           continue;
  1426.  
  1427.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1428.         result.push(new Update(updateElement));
  1429.       }
  1430.     }
  1431.     catch (e) {
  1432.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " + 
  1433.           e);
  1434.     }
  1435.     fileStream.close();
  1436.     return result;
  1437.   },
  1438.   
  1439.   /**
  1440.    * Load the update manager, initializing state from state files.
  1441.    */
  1442.   _ensureUpdates: function() {
  1443.     if (!this._updates) {
  1444.       this._updates = this._loadXMLFileIntoArray(getFile(KEY_APPDIR, 
  1445.                         [FILE_UPDATES_DB]));
  1446.  
  1447.       // Make sure that any active update is part of our updates list
  1448.       var active = this.activeUpdate;
  1449.       if (active)
  1450.         this._addUpdate(active);
  1451.     }
  1452.   },
  1453.  
  1454.   /**
  1455.    * See nsIUpdateService.idl
  1456.    */
  1457.   getUpdateAt: function(index) {
  1458.     this._ensureUpdates();
  1459.     return this._updates[index];
  1460.   },
  1461.   
  1462.   /**
  1463.    * See nsIUpdateService.idl
  1464.    */
  1465.   get updateCount() {
  1466.     this._ensureUpdates();
  1467.     return this._updates.length;
  1468.   },
  1469.   
  1470.   /**
  1471.    * See nsIUpdateService.idl
  1472.    */
  1473.   get activeUpdate() {
  1474.     if (this._activeUpdate &&
  1475.         this._activeUpdate.serviceURL != Checker.prototype.updateURL) {
  1476.       // User switched channels, clear out any old active updates and remove
  1477.       // partial downloads
  1478.       this._activeUpdate = null;
  1479.       
  1480.       // Destroy the updates directory, since we're done with it.
  1481.       cleanUpUpdatesDir();
  1482.     }
  1483.     return this._activeUpdate;
  1484.   },
  1485.   set activeUpdate(activeUpdate) {
  1486.     this._addUpdate(activeUpdate);
  1487.     this._activeUpdate = activeUpdate;
  1488.     if (!activeUpdate) {
  1489.       // If |activeUpdate| is null, we have updated both lists - the active list
  1490.       // and the history list, so we want to write both files.
  1491.       this.saveUpdates();
  1492.     }
  1493.     else
  1494.       this._writeUpdatesToXMLFile([this._activeUpdate], 
  1495.                                   getFile(KEY_APPDIR, [FILE_UPDATE_ACTIVE]));
  1496.     return activeUpdate;
  1497.   },
  1498.   
  1499.   /**
  1500.    * Add an update to the Updates list. If the item already exists in the list,
  1501.    * replace the existing value with the new value.
  1502.    * @param   update
  1503.    *          The nsIUpdate object to add.
  1504.    */
  1505.   _addUpdate: function(update) {
  1506.     if (!update)
  1507.       return;
  1508.     if (this._updates) {
  1509.       for (var i = 0; i < this._updates.length; ++i) {
  1510.         if (this._updates[i].version == update.version &&
  1511.             this._updates[i].buildID == update.buildID) {
  1512.           // Replace the existing entry with the new value, updating
  1513.           // all metadata.
  1514.           this._updates[i] = update;
  1515.           return;
  1516.         }
  1517.       }
  1518.     }
  1519.     // Otherwise add it to the front of the list.
  1520.     if (update) 
  1521.       this._updates = [update].concat(this._updates);
  1522.   },
  1523.   
  1524.   /**
  1525.    * Serializes an array of updates to an XML file
  1526.    * @param   updates
  1527.    *          An array of nsIUpdate objects
  1528.    * @param   file
  1529.    *          The nsIFile object to serialize to
  1530.    */
  1531.   _writeUpdatesToXMLFile: function(updates, file) {
  1532.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1533.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1534.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1535.     if (!file.exists()) 
  1536.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1537.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1538.     
  1539.     try {
  1540.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1541.                             .createInstance(Components.interfaces.nsIDOMParser);
  1542.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1543.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1544.  
  1545.       for (var i = 0; i < updates.length; ++i) {
  1546.         if (updates[i])
  1547.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1548.       }
  1549.  
  1550.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1551.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1552.       serializer.serializeToStream(doc.documentElement, fos, null);
  1553.     }
  1554.     catch (e) {
  1555.     }
  1556.     
  1557.     closeSafeOutputStream(fos);
  1558.   },
  1559.  
  1560.   /**
  1561.    * See nsIUpdateService.idl
  1562.    */
  1563.   saveUpdates: function() {
  1564.     this._writeUpdatesToXMLFile([this._activeUpdate], 
  1565.                                 getFile(KEY_APPDIR, [FILE_UPDATE_ACTIVE]));
  1566.     if (this._updates) {
  1567.       this._writeUpdatesToXMLFile(this._updates, 
  1568.                                   getFile(KEY_APPDIR, [FILE_UPDATES_DB]));
  1569.     }
  1570.   },
  1571.   
  1572.   /**
  1573.    * See nsISupports.idl
  1574.    */
  1575.   QueryInterface: function(iid) {
  1576.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1577.         !iid.equals(Components.interfaces.nsISupports))
  1578.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1579.     return this;
  1580.   }
  1581. };
  1582.  
  1583. /**
  1584.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  1585.  * security dialogs from being shown to the user.  It is better to simply fail
  1586.  * if the certificate is bad.  See bug 304286.
  1587.  */
  1588. function BadCertHandler() {
  1589. }
  1590. BadCertHandler.prototype = {
  1591.   /**
  1592.    * See nsIBadCertListener
  1593.    */
  1594.   confirmUnknownIssuer: function(socketInfo, cert, certAddType) {
  1595.     return false;
  1596.   },
  1597.  
  1598.   confirmMismatchDomain: function(socketInfo, targetURL, cert) {
  1599.     return false;
  1600.   },
  1601.  
  1602.   confirmCertExpired: function(socketInfo, cert) {
  1603.     return false;
  1604.   },
  1605.  
  1606.   notifyCrlNextupdate: function(socketInfo, targetURL, cert) {
  1607.   },
  1608.  
  1609.   /**
  1610.    * See nsIInterfaceRequestor
  1611.    */
  1612.   getInterface: function(iid) {
  1613.     if (iid.equals(Components.interfaces.nsIBadCertListener))
  1614.       return this;
  1615.  
  1616.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  1617.     return null;
  1618.   },
  1619.  
  1620.   /**
  1621.    * See nsISupports
  1622.    */
  1623.   QueryInterface: function(iid) {
  1624.     if (!iid.equals(Components.interfaces.nsIBadCertListener) &&
  1625.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  1626.         !iid.equals(Components.interfaces.nsISupports))
  1627.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1628.     return this;
  1629.   }
  1630. };
  1631.  
  1632. /**
  1633.  * Checker
  1634.  * Checks for new Updates
  1635.  * @constructor
  1636.  */
  1637. function Checker() {
  1638. }
  1639. Checker.prototype = {
  1640.   /**
  1641.    * The XMLHttpRequest object that performs the connection.
  1642.    */
  1643.   _request  : null,
  1644.   
  1645.   /**
  1646.    * The nsIUpdateCheckListener callback
  1647.    */
  1648.   _callback : null,
  1649.   
  1650.   /**
  1651.    * The URL of the update service XML file to connect to that contains details
  1652.    * about available updates.
  1653.    */
  1654.   get updateURL() {
  1655.     var defaults =
  1656.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1657.         getDefaultBranch(null);
  1658.  
  1659.     // Use the override URL if specified.
  1660.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1661.  
  1662.     // Otherwise, construct the update URL from component parts.
  1663.     if (!url) {
  1664.       try {
  1665.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1666.       } catch (e) {
  1667.       }
  1668.     }
  1669.  
  1670.     if (!url || url == "") {
  1671.       LOG("Checker", "Update URL not defined");
  1672.       return null;
  1673.     }
  1674.  
  1675.     // Read the update channel from defaults only.  We do this to ensure that
  1676.     // the channel is tightly coupled with the application and does not apply
  1677.     // to other instances of the application that may use the same profile.
  1678.     function getUpdateChannel() {
  1679.       try {
  1680.         return defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  1681.       } catch (e) {
  1682.         return "default";  // failover when pref not found
  1683.       }
  1684.     }
  1685.  
  1686.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1687.     url = url.replace(/%VERSION%/g, gApp.version);
  1688.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1689.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gApp.XPCOMABI);
  1690.     url = url.replace(/%LOCALE%/g, getLocale());
  1691.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1692.     url = url.replace(/\+/g, "%2B");
  1693.  
  1694.     LOG("Checker", "update url: " + url);
  1695.     return url;
  1696.   },
  1697.   
  1698.   /**
  1699.    * See nsIUpdateService.idl
  1700.    */
  1701.   checkForUpdates: function(listener, force) {
  1702.     if (!listener)
  1703.       throw Components.results.NS_ERROR_NULL_POINTER;
  1704.       
  1705.     if (!this.updateURL || (!this.enabled && !force))
  1706.       return;
  1707.       
  1708.     this._request = 
  1709.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1710.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1711.     this._request.open("GET", this.updateURL, true);
  1712.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1713.     this._request.overrideMimeType("text/xml");
  1714.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1715.     
  1716.     var self = this;
  1717.     this._request.onerror     = function(event) { self.onError(event);    };
  1718.     this._request.onload      = function(event) { self.onLoad(event);     };
  1719.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1720.  
  1721.     LOG("Checker", "checkForUpdates: sending request to " + this.updateURL);
  1722.     this._request.send(null);
  1723.     
  1724.     this._callback = listener;
  1725.   },
  1726.   
  1727.   /**
  1728.    * When progress associated with the XMLHttpRequest is received.
  1729.    * @param   event
  1730.    *          The nsIDOMLSProgressEvent for the load.
  1731.    */
  1732.   onProgress: function(event) {
  1733.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1734.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1735.   },
  1736.   
  1737.   /**
  1738.    * Returns an array of nsIUpdate objects discovered by the update check.
  1739.    */
  1740.   get _updates() {
  1741.     var updatesElement = this._request.responseXML.documentElement;
  1742.     if (!updatesElement) {
  1743.       LOG("Checker", "get_updates: empty updates document?!");
  1744.       return [];
  1745.     }
  1746.  
  1747.     if (updatesElement.nodeName != "updates") {
  1748.       LOG("Checker", "get_updates: unexpected node name!");
  1749.       throw "";
  1750.     }
  1751.     
  1752.     var updates = [];
  1753.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  1754.       var updateElement = updatesElement.childNodes.item(i);
  1755.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1756.           updateElement.localName != "update")
  1757.         continue;
  1758.  
  1759.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1760.       var update = new Update(updateElement);
  1761.       update.serviceURL = this.updateURL;
  1762.       updates.push(update);
  1763.     }
  1764.  
  1765.     return updates;
  1766.   },
  1767.   
  1768.   /**
  1769.    * The XMLHttpRequest succeeded and the document was loaded.
  1770.    * @param   event
  1771.    *          The nsIDOMLSEvent for the load
  1772.    */
  1773.   onLoad: function(event) {
  1774.     LOG("Checker", "onLoad: request completed downloading document");
  1775.     
  1776.     // Analyze the resulting DOM and determine the set of updates to install
  1777.     try {
  1778.       var updates = this._updates;
  1779.       
  1780.       LOG("Checker", "Updates available: " + updates.length);
  1781.       
  1782.       // ... and tell the Update Service about what we discovered.
  1783.       this._callback.onCheckComplete(event.target, updates, updates.length);
  1784.     }
  1785.     catch (e) {
  1786.       LOG("Checker", "There was a problem with the update service URL specified, " + 
  1787.           "either the XML file was malformed or it does not exist at the location " + 
  1788.           "specified. Exception: " + e);
  1789.       var update = new Update(null);
  1790.       update.statusText = getStatusTextFromCode(404, 404);
  1791.       this._callback.onError(event.target, update);
  1792.     }
  1793.   },
  1794.   
  1795.   /**
  1796.    * There was an error of some kind during the XMLHttpRequest
  1797.    * @param   event
  1798.    *          The nsIDOMLSEvent for the load
  1799.    */
  1800.   onError: function(event) {
  1801.     LOG("Checker", "onError: error during load");
  1802.     
  1803.     var request = event.target;
  1804.     try {
  1805.       var status = request.status;
  1806.     }
  1807.     catch (e) {
  1808.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  1809.       status = req.status;
  1810.     }
  1811.     
  1812.     // If we can't find an error string specific to this status code, 
  1813.     // just use the 200 message from above, which means everything 
  1814.     // "looks" fine but there was probably an XML error or a bogus file.
  1815.     var update = new Update(null);
  1816.     update.statusText = getStatusTextFromCode(status, 200);
  1817.     this._callback.onError(request, update);
  1818.   },
  1819.   
  1820.   /**
  1821.    * Whether or not we are allowed to do update checking.
  1822.    */
  1823.   _enabled: true,
  1824.   
  1825.   /**
  1826.    * See nsIUpdateService.idl
  1827.    */
  1828.   get enabled() {
  1829.     var aus = 
  1830.         Components.classes["@mozilla.org/updates/update-service;1"].
  1831.         getService(Components.interfaces.nsIApplicationUpdateService);
  1832.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) && 
  1833.                   aus.canUpdate && this._enabled;
  1834.     return enabled;
  1835.   },
  1836.   
  1837.   /**
  1838.    * See nsIUpdateService.idl
  1839.    */
  1840.   stopChecking: function(duration) {
  1841.     // Always stop the current check
  1842.     if (this._request)
  1843.       this._request.abort();
  1844.     
  1845.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  1846.     switch (duration) {
  1847.     case nsIUpdateChecker.CURRENT_SESSION:
  1848.       this._enabled = false;
  1849.       break;
  1850.     case nsIUpdateChecker.ANY_CHECKS:
  1851.       this._enabled = false;
  1852.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  1853.       break;
  1854.     }
  1855.   },
  1856.   
  1857.   /**
  1858.    * See nsISupports.idl
  1859.    */
  1860.   QueryInterface: function(iid) {
  1861.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  1862.         !iid.equals(Components.interfaces.nsISupports))
  1863.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1864.     return this;
  1865.   }
  1866. };
  1867.  
  1868. /**
  1869.  * Manages the download of updates
  1870.  * @param   background
  1871.  *          Whether or not this downloader is operating in background
  1872.  *          update mode. 
  1873.  * @constructor
  1874.  */
  1875. function Downloader(background) {
  1876.   this.background = background;
  1877. }
  1878. Downloader.prototype = {
  1879.   /**
  1880.    * The nsIUpdatePatch that we are downloading
  1881.    */
  1882.   _patch: null,
  1883.   
  1884.   /**
  1885.    * The nsIUpdate that we are downloading
  1886.    */
  1887.   _update: null,
  1888.   
  1889.   /**
  1890.    * The nsIIncrementalDownload object handling the download
  1891.    */
  1892.   _request: null,
  1893.  
  1894.   /**
  1895.    * Whether or not the update being downloaded is a complete replacement of
  1896.    * the user's existing installation or a patch representing the difference
  1897.    * between the new version and the previous version.
  1898.    */
  1899.   isCompleteUpdate: null,
  1900.  
  1901.   /**
  1902.    * Cancels the active download.
  1903.    */  
  1904.   cancel: function() {
  1905.     if (this._request && 
  1906.         this._request instanceof Components.interfaces.nsIRequest) {
  1907.       const NS_BINDING_ABORTED = 0x804b0002;
  1908.       this._request.cancel(NS_BINDING_ABORTED);
  1909.     }
  1910.   },
  1911.  
  1912.   /**
  1913.    * Whether or not a patch has been downloaded and staged for installation.
  1914.    */
  1915.   get patchIsStaged() {
  1916.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  1917.   },
  1918.  
  1919.   /**
  1920.    * Verify the downloaded file.  We assume that the download is complete at
  1921.    * this point.
  1922.    */
  1923.   _verifyDownload: function() {
  1924.     if (!this._request)
  1925.       return false;
  1926.  
  1927.     var destination = this._request.destination;
  1928.  
  1929.     // Ensure that the file size matches the expected file size.
  1930.     if (destination.fileSize != this._patch.size)
  1931.       return false;
  1932.  
  1933.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  1934.         createInstance(nsIFileInputStream);
  1935.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  1936.  
  1937.     try {
  1938.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  1939.           createInstance(nsICryptoHash);
  1940.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  1941.       if (hashFunction == undefined)
  1942.         throw Components.results.NS_ERROR_UNEXPECTED;
  1943.       hash.init(hashFunction);
  1944.       hash.updateFromStream(fileStream, -1);
  1945.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  1946.       // encoded binary (such as what is typically output by programs like
  1947.       // sha1sum).  In the future, this may change to base64 depending on how
  1948.       // we choose to compute these hashes.
  1949.       digest = binaryToHex(hash.finish(false));
  1950.     } catch (e) {
  1951.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  1952.       digest = "";
  1953.     }
  1954.  
  1955.     fileStream.close();
  1956.  
  1957.     return digest == this._patch.hashValue.toLowerCase();
  1958.   },
  1959.  
  1960.   /**
  1961.    * Select the patch to use given the current state of updateDir and the given
  1962.    * set of update patches.
  1963.    * @param   update
  1964.    *          A nsIUpdate object to select a patch from
  1965.    * @param   updateDir
  1966.    *          A nsIFile representing the update directory
  1967.    * @returns A nsIUpdatePatch object to download
  1968.    */
  1969.   _selectPatch: function(update, updateDir) {
  1970.     // Given an update to download, we will always try to download the patch
  1971.     // for a partial update over the patch for a full update.
  1972.  
  1973.     /**
  1974.      * Return the first UpdatePatch with the given type.
  1975.      * @param   type
  1976.      *          The type of the patch ("complete" or "partial")
  1977.      * @returns A nsIUpdatePatch object matching the type specified
  1978.      */
  1979.     function getPatchOfType(type) {
  1980.       for (var i = 0; i < update.patchCount; ++i) {
  1981.         var patch = update.getPatchAt(i);
  1982.         if (patch && patch.type == type)
  1983.           return patch;
  1984.       }
  1985.       return null;
  1986.     }
  1987.  
  1988.     // Look to see if any of the patches in the Update object has been
  1989.     // pre-selected for download, otherwise we must figure out which one
  1990.     // to select ourselves. 
  1991.     var selectedPatch = update.selectedPatch;
  1992.     
  1993.     var state = readStatusFile(updateDir)
  1994.  
  1995.     // If this is a patch that we know about, then select it.  If it is a patch
  1996.     // that we do not know about, then remove it and use our default logic.
  1997.     var useComplete = false;
  1998.     if (selectedPatch) {
  1999.       LOG("Downloader", "found existing patch [state="+state+"]");
  2000.       switch (state) {
  2001.       case STATE_DOWNLOADING: 
  2002.         LOG("Downloader", "resuming download");
  2003.         return selectedPatch;
  2004.       case STATE_PENDING:
  2005.         LOG("Downloader", "already downloaded and staged");
  2006.         return null;
  2007.       default:
  2008.         // Something went wrong when we tried to apply the previous patch.
  2009.         // Try the complete patch next time.
  2010.         if (update && selectedPatch.type == "partial") {
  2011.           useComplete = true;
  2012.         } else {
  2013.           // This is a pretty fatal error.  Just bail.
  2014.           LOG("Downloader", "failed to apply complete patch!");
  2015.           writeStatusFile(updateDir, STATE_NONE);
  2016.           return null;
  2017.         }
  2018.       }
  2019.  
  2020.       selectedPatch = null;
  2021.     }
  2022.     
  2023.     // If we were not able to discover an update from a previous download, we 
  2024.     // select the best patch from the given set.
  2025.     var partialPatch = getPatchOfType("partial");
  2026.     if (!useComplete)
  2027.       selectedPatch = partialPatch;
  2028.     if (!selectedPatch) {
  2029.       if (partialPatch)
  2030.         partialPatch.selected = false;
  2031.       selectedPatch = getPatchOfType("complete");
  2032.     }
  2033.  
  2034.     // Restore the updateDir since we may have deleted it.
  2035.     updateDir = getUpdatesDir();
  2036.     
  2037.     selectedPatch.selected = true;
  2038.     update.isCompleteUpdate = useComplete;
  2039.     
  2040.     // Reset the Active Update object on the Update Manager and flush the
  2041.     // Active Update DB. 
  2042.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2043.                        .getService(Components.interfaces.nsIUpdateManager);
  2044.     um.activeUpdate = update;
  2045.  
  2046.     return selectedPatch;
  2047.   },
  2048.  
  2049.   /**
  2050.    * Whether or not we are currently downloading something.
  2051.    */
  2052.   get isBusy() {
  2053.     return this._request != null;
  2054.   },
  2055.   
  2056.   /**
  2057.    * Download and stage the given update.
  2058.    * @param   update
  2059.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2060.    */
  2061.   downloadUpdate: function(update) {
  2062.     if (!update)
  2063.       throw Components.results.NS_ERROR_NULL_POINTER;
  2064.     
  2065.     var updateDir = getUpdatesDir();
  2066.  
  2067.     this._update = update;
  2068.  
  2069.     // This function may return null, which indicates that there are no patches
  2070.     // to download.
  2071.     this._patch = this._selectPatch(update, updateDir);
  2072.     if (!this._patch) {
  2073.       LOG("Downloader", "no patch to download");
  2074.       return readStatusFile(updateDir);
  2075.     }
  2076.     this.isCompleteUpdate = this._patch.type == "complete";
  2077.  
  2078.     var patchFile = updateDir.clone();
  2079.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2080.  
  2081.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2082.         getService(Components.interfaces.nsIIOService);
  2083.     var uri = ios.newURI(this._patch.URL, null, null);
  2084.  
  2085.     this._request =
  2086.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2087.         createInstance(nsIIncrementalDownload);
  2088.  
  2089.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " + 
  2090.         patchFile.path);
  2091.  
  2092.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2093.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2094.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2095.     this._request.start(this, null);
  2096.  
  2097.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2098.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2099.     this._patch.state = STATE_DOWNLOADING;
  2100.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2101.                        .getService(Components.interfaces.nsIUpdateManager);
  2102.     um.saveUpdates();
  2103.     return STATE_DOWNLOADING;
  2104.   },
  2105.   
  2106.   /**
  2107.    * An array of download listeners to notify when we receive 
  2108.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2109.    */
  2110.   _listeners: [],
  2111.  
  2112.   /** 
  2113.    * Adds a listener to the download process
  2114.    * @param   listener
  2115.    *          A download listener, implementing nsIRequestObserver and
  2116.    *          nsIProgressEventSink
  2117.    */
  2118.   addDownloadListener: function(listener) {
  2119.     for (var i = 0; i < this._listeners.length; ++i) {
  2120.       if (this._listeners[i] == listener)
  2121.         return;
  2122.     }
  2123.     this._listeners.push(listener);
  2124.   },
  2125.   
  2126.   /** 
  2127.    * Removes a download listener
  2128.    * @param   listener
  2129.    *          The listener to remove.
  2130.    */
  2131.   removeDownloadListener: function(listener) {
  2132.     for (var i = 0; i < this._listeners.length; ++i) {
  2133.       if (this._listeners[i] == listener) {
  2134.         this._listeners.splice(i, 1);
  2135.         return;
  2136.       }
  2137.     }
  2138.   },
  2139.   
  2140.   /**
  2141.    * When the async request begins
  2142.    * @param   request
  2143.    *          The nsIRequest object for the transfer
  2144.    * @param   context
  2145.    *          Additional data
  2146.    */
  2147.   onStartRequest: function(request, context) {
  2148.     request.QueryInterface(nsIIncrementalDownload);
  2149.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2150.     
  2151.     var listenerCount = this._listeners.length;
  2152.     for (var i = 0; i < listenerCount; ++i)
  2153.       this._listeners[i].onStartRequest(request, context);
  2154.   },
  2155.   
  2156.   /** 
  2157.    * When new data has been downloaded
  2158.    * @param   request
  2159.    *          The nsIRequest object for the transfer
  2160.    * @param   context
  2161.    *          Additional data
  2162.    * @param   progress
  2163.    *          The current number of bytes transferred
  2164.    * @param   maxProgress
  2165.    *          The total number of bytes that must be transferred
  2166.    */
  2167.   onProgress: function(request, context, progress, maxProgress) {
  2168.     request.QueryInterface(nsIIncrementalDownload);
  2169.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2170.     
  2171.     var listenerCount = this._listeners.length;
  2172.     for (var i = 0; i < listenerCount; ++i) {
  2173.       var listener = this._listeners[i];
  2174.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2175.         listener.onProgress(request, context, progress, maxProgress);
  2176.     }
  2177.   },
  2178.   
  2179.   /** 
  2180.    * When we have new status text
  2181.    * @param   request
  2182.    *          The nsIRequest object for the transfer
  2183.    * @param   context
  2184.    *          Additional data
  2185.    * @param   status
  2186.    *          A status code
  2187.    * @param   statusText
  2188.    *          Human readable version of |status|
  2189.    */
  2190.   onStatus: function(request, context, status, statusText) {
  2191.     request.QueryInterface(nsIIncrementalDownload);
  2192.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2193.     var listenerCount = this._listeners.length;
  2194.     for (var i = 0; i < listenerCount; ++i) {
  2195.       var listener = this._listeners[i];
  2196.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2197.         listener.onStatus(request, context, status, statusText);
  2198.     }
  2199.   },
  2200.   
  2201.   /** 
  2202.    * When data transfer ceases
  2203.    * @param   request
  2204.    *          The nsIRequest object for the transfer
  2205.    * @param   context
  2206.    *          Additional data
  2207.    * @param   status
  2208.    *          Status code containing the reason for the cessation.
  2209.    */
  2210.   onStopRequest: function(request, context, status) {
  2211.     request.QueryInterface(nsIIncrementalDownload);
  2212.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2213.  
  2214.     var state = this._patch.state;
  2215.     var shouldShowPrompt = false;
  2216.     var deleteActiveUpdate = false;
  2217.     const NS_BINDING_ABORTED = 0x804b0002;
  2218.     const NS_ERROR_ABORT = 0x80004004;
  2219.     if (Components.isSuccessCode(status)) {
  2220.       if (this._verifyDownload()) {
  2221.         state = STATE_PENDING;
  2222.         
  2223.         // We only need to explicitly show the prompt if this is a backround
  2224.         // download, since otherwise some kind of UI is already visible and 
  2225.         // that UI will notify. 
  2226.         if (this.background)
  2227.           shouldShowPrompt = true;
  2228.         
  2229.         // Tell the updater.exe we're ready to apply.
  2230.         writeStatusFile(getUpdatesDir(), state);
  2231.         this._update.installDate = (new Date()).getTime();
  2232.         this._update.statusText = "Install Pending";
  2233.       } else {
  2234.         LOG("Downloader", "onStopRequest: download verification failed");
  2235.         state = STATE_DOWNLOAD_FAILED;
  2236.         
  2237.         var sbs = 
  2238.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2239.             getService(Components.interfaces.nsIStringBundleService);
  2240.         var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2241.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2242.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2243.         this._update.statusText = updateStrings.
  2244.           formatStringFromName("verificationError", [brandShortName], 1);
  2245.         
  2246.         // TODO: use more informative error code here
  2247.         status = Components.results.NS_ERROR_UNEXPECTED;
  2248.         
  2249.         var message = getStatusTextFromCode("verification_failed", 
  2250.           "verification_failed");
  2251.         this._update.statusText = message;
  2252.         
  2253.         if (this._update.isCompleteUpdate)
  2254.           deleteActiveUpdate = true;
  2255.  
  2256.         // Destroy the updates directory, since we're done with it.
  2257.         cleanUpUpdatesDir();
  2258.       }
  2259.     }
  2260.     else if (status != NS_BINDING_ABORTED &&
  2261.              status != NS_ERROR_ABORT) {
  2262.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2263.       // Some sort of other failure, log this in the |statusText| property
  2264.       state = STATE_DOWNLOAD_FAILED;
  2265.       
  2266.       // XXXben - if |request| (The Incremental Download) provided a means
  2267.       // for accessing the http channel we could do more here.
  2268.       
  2269.       const NS_BINDING_FAILED = 2152398849;
  2270.       this._update.statusText = getStatusTextFromCode(status, 
  2271.         NS_BINDING_FAILED);
  2272.       
  2273.       // Destroy the updates directory, since we're done with it.
  2274.       cleanUpUpdatesDir();
  2275.       
  2276.       deleteActiveUpdate = true;
  2277.     }
  2278.     LOG("Downloader", "Setting state to: " + state);
  2279.     this._patch.state = state;
  2280.     var um = 
  2281.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2282.         getService(Components.interfaces.nsIUpdateManager);
  2283.     if (deleteActiveUpdate) {
  2284.       this._update.installDate = (new Date()).getTime();
  2285.       um.activeUpdate = null;
  2286.     }
  2287.     um.saveUpdates();
  2288.     
  2289.     var listenerCount = this._listeners.length;
  2290.     for (var i = 0; i < listenerCount; ++i)
  2291.       this._listeners[i].onStopRequest(request, context, status);
  2292.  
  2293.     this._request = null;
  2294.     
  2295.     if (state == STATE_DOWNLOAD_FAILED) {
  2296.       if (!this._update.isCompleteUpdate) {
  2297.         // If we were downloading a patch and the patch verification phase 
  2298.         // failed, log this and then commence downloading the complete update.
  2299.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2300.         this._update.isCompleteUpdate = true;
  2301.         var status = this.downloadUpdate(this._update);
  2302.         if (status == STATE_NONE)
  2303.           cleanupActiveUpdate();
  2304.         // This will reset the |.state| property on this._update if a new 
  2305.         // download initiates.
  2306.       }
  2307.       else {
  2308.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2309.         // ...
  2310.         
  2311.         // If this was ever a foreground download, and now there is no UI active
  2312.         // (e.g. because the user closed the download window) and there was an
  2313.         // error, we must notify now. Otherwise we can keep the failure to 
  2314.         // ourselves since the user won't be expecting it. 
  2315.         var fgdl = false;
  2316.         try {
  2317.           fgdl = this._update.getProperty("foregroundDownload");
  2318.         }
  2319.         catch (e) {
  2320.         }
  2321.         if (fgdl == "true") {
  2322.           var prompter = 
  2323.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2324.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2325.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2326.           this._update.setProperty("downloadFailed", "true");
  2327.           prompter.showUpdateError(this._update);
  2328.         }
  2329.       }
  2330.     }
  2331.  
  2332.     // Do this after *everything* else, since it will likely cause the app 
  2333.     // to shut down. 
  2334.     if (shouldShowPrompt) {
  2335.       // Notify the user that an update has been downloaded and is ready for 
  2336.       // installation (i.e. that they should restart the application). We do
  2337.       // not notify on failed update attempts.
  2338.       var prompter = 
  2339.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2340.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2341.       prompter.showUpdateDownloaded(this._update);
  2342.     }
  2343.   },
  2344.  
  2345.   /**
  2346.    * See nsIInterfaceRequestor.idl
  2347.    */
  2348.   getInterface: function(iid) {
  2349.     // The network request may require proxy authentication, so provide the
  2350.     // default nsIAuthPrompt if requested.
  2351.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2352.       var prompt =
  2353.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2354.           createInstance();
  2355.       return prompt.QueryInterface(iid);
  2356.     }
  2357.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  2358.     return null;
  2359.   },
  2360.    
  2361.   /**
  2362.    * See nsISupports.idl
  2363.    */
  2364.   QueryInterface: function(iid) {
  2365.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2366.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2367.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2368.         !iid.equals(Components.interfaces.nsISupports))
  2369.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2370.     return this;
  2371.   }
  2372. };
  2373.  
  2374. /**
  2375.  * A manager for update check timers. Manages timers that fire over long 
  2376.  * periods of time (e.g. days, weeks).
  2377.  * @constructor
  2378.  */
  2379. function TimerManager() {
  2380.   gOS = Components.classes["@mozilla.org/observer-service;1"]
  2381.                   .getService(Components.interfaces.nsIObserverService);
  2382.   gOS.addObserver(this, "xpcom-shutdown", false);
  2383.  
  2384.   const nsITimer = Components.interfaces.nsITimer;
  2385.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2386.                           .createInstance(nsITimer);
  2387.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2388.   this._timer.initWithCallback(this, timerInterval, 
  2389.                                nsITimer.TYPE_REPEATING_SLACK);
  2390. }
  2391. TimerManager.prototype = {
  2392.   /**
  2393.    * See nsIObserver.idl
  2394.    */
  2395.   observe: function(subject, topic, data) {
  2396.     if (topic == "xpcom-shutdown") {
  2397.       gOS.removeObserver(this, "xpcom-shutdown");
  2398.  
  2399.       // Release everything we hold onto. 
  2400.       this._timer = null;
  2401.       this._timers = null;
  2402.     }
  2403.   },
  2404.  
  2405.   /**
  2406.    * The Checker Timer
  2407.    */
  2408.   _timer: null,
  2409.   
  2410.   /**
  2411.    * The set of registered timers.
  2412.    */
  2413.   _timers: { },
  2414.   
  2415.   /**
  2416.    * Called when the checking timer fires.
  2417.    * @param   timer
  2418.    *          The checking timer that fired. 
  2419.    */
  2420.   notify: function(timer) {
  2421.     for (var timerID in this._timers) {
  2422.       var timerData = this._timers[timerID];
  2423.       var lastUpdateTime = timerData.lastUpdateTime;
  2424.       var now = Math.round(Date.now() / 1000);
  2425.     
  2426.       // Fudge the lastUpdateTime by some random increment of the update 
  2427.       // check interval (e.g. some random slice of 10 minutes) so that when
  2428.       // the time comes to check, we offset each client request by a random
  2429.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2430.       // whereas app.update.lastUpdateTime is in seconds
  2431.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2432.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2433.  
  2434.       if ((now - lastUpdateTime) > timerData.interval &&
  2435.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2436.         timerData.callback.notify(timer);
  2437.         timerData.lastUpdateTime = now;
  2438.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2439.         gPref.setIntPref(preference, now);
  2440.       }
  2441.     }
  2442.   },
  2443.   
  2444.   /**
  2445.    * See nsIUpdateService.idl
  2446.    */
  2447.   registerTimer: function(id, callback, interval) {
  2448.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2449.     var now = Math.round(Date.now() / 1000);
  2450.     var lastUpdateTime = null;
  2451.     if (gPref.prefHasUserValue(preference)) {
  2452.       lastUpdateTime = gPref.getIntPref(preference);
  2453.     } else {
  2454.       gPref.setIntPref(preference, now);
  2455.       lastUpdateTime = now;
  2456.     }
  2457.     this._timers[id] = { callback       : callback, 
  2458.                          interval       : interval,
  2459.                          lastUpdateTime : lastUpdateTime }; 
  2460.   },
  2461.  
  2462.   /**
  2463.    * See nsISupports.idl
  2464.    */
  2465.   QueryInterface: function(iid) {
  2466.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2467.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2468.         !iid.equals(Components.interfaces.nsIObserver) &&
  2469.         !iid.equals(Components.interfaces.nsISupports))
  2470.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2471.     return this;
  2472.   }
  2473. };
  2474.  
  2475. //@line 2476 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2476. /**
  2477.  * UpdatePrompt
  2478.  * An object which can prompt the user with information about updates, request
  2479.  * action, etc. Embedding clients can override this component with one that 
  2480.  * invokes a native front end. 
  2481.  * @constructor
  2482.  */
  2483. function UpdatePrompt() {
  2484. }
  2485. UpdatePrompt.prototype = {
  2486.   /**
  2487.    * See nsIUpdateService.idl
  2488.    */
  2489.   checkForUpdates: function() {
  2490.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2491.                  null, null);
  2492.   },
  2493.     
  2494.   /**
  2495.    * See nsIUpdateService.idl
  2496.    */
  2497.   showUpdateAvailable: function(update) {
  2498.     if (this._enabled) {
  2499.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2500.                    "updatesavailable", update);
  2501.     }
  2502.   },
  2503.   
  2504.   /**
  2505.    * See nsIUpdateService.idl
  2506.    */
  2507.   showUpdateDownloaded: function(update) {
  2508.     if (this._enabled) {
  2509.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2510.                    "finishedBackground", update);
  2511.     }
  2512.   },
  2513.   
  2514.   /**
  2515.    * See nsIUpdateService.idl
  2516.    */
  2517.   showUpdateInstalled: function(update) {
  2518.     var showUpdateInstalledUI = getPref("getBoolPref", 
  2519.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2520.     if (this._enabled && showUpdateInstalledUI) {
  2521.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2522.                    "installed", update);
  2523.     }
  2524.   },
  2525.   
  2526.   /**
  2527.    * See nsIUpdateService.idl
  2528.    */
  2529.   showUpdateError: function(update) {
  2530.     if (this._enabled) {
  2531.       // In some cases, we want to just show a simple alert dialog:
  2532.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2533.         var sbs = 
  2534.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2535.             getService(Components.interfaces.nsIStringBundleService);
  2536.         var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2537.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2538.         var text = updateBundle.formatStringFromName("updaterIOErrorText",
  2539.                                                      [gApp.name], 1);
  2540.         var ww =
  2541.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2542.             getService(Components.interfaces.nsIWindowWatcher);
  2543.         ww.getNewPrompter(null).alert(title, text);
  2544.       } else {
  2545.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2546.                      "errors", update);
  2547.       }
  2548.     }
  2549.   },
  2550.   
  2551.   /**
  2552.    * See nsIUpdateService.idl
  2553.    */
  2554.   showUpdateHistory: function(parent) {
  2555.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History", 
  2556.                  null, null);
  2557.   },
  2558.   
  2559.   /**
  2560.    * Whether or not we are enabled (i.e. not in Silent mode)
  2561.    */
  2562.   get _enabled() {
  2563.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2564.   },
  2565.   
  2566.   /**
  2567.    * Show the Update Checking UI
  2568.    * @param   parent
  2569.    *          A parent window, can be null
  2570.    * @param   uri
  2571.    *          The URI string of the dialog to show
  2572.    * @param   name
  2573.    *          The Window Name of the dialog to show, in case it is already open
  2574.    *          and can merely be focused
  2575.    * @param   page
  2576.    *          The page of the wizard to be displayed, if one is already open.
  2577.    * @param   update
  2578.    *          An update to pass to the UI in the window arguments. 
  2579.    *          Can be null
  2580.    */
  2581.   _showUI: function(parent, uri, features, name, page, update) {
  2582.     var ary = null;
  2583.     if (update) {
  2584.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2585.                       .createInstance(Components.interfaces.nsISupportsArray);
  2586.       ary.AppendElement(update);
  2587.     }
  2588.       
  2589.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  2590.                        .getService(Components.interfaces.nsIWindowMediator);
  2591.     var win = wm.getMostRecentWindow(name);
  2592.     if (win) {
  2593.       if (page && "setCurrentPage" in win)
  2594.         win.setCurrentPage(page);
  2595.       win.focus();
  2596.     }
  2597.     else {
  2598.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2599.       if (features)
  2600.         openFeatures += "," + features;
  2601.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2602.                          .getService(Components.interfaces.nsIWindowWatcher);
  2603.       ww.openWindow(parent, uri, "", openFeatures, ary);
  2604.     }
  2605.   },
  2606.   
  2607.   /**
  2608.    * See nsISupports.idl
  2609.    */
  2610.   QueryInterface: function(iid) {
  2611.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  2612.         !iid.equals(Components.interfaces.nsISupports))
  2613.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2614.     return this;
  2615.   }
  2616. };
  2617. //@line 2618 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2618.  
  2619. var gModule = {
  2620.   registerSelf: function(componentManager, fileSpec, location, type) {
  2621.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  2622.     
  2623.     for (var key in this._objects) {
  2624.       var obj = this._objects[key];
  2625.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  2626.                                                fileSpec, location, type);
  2627.     }
  2628.  
  2629.     // Make the Update Service a startup observer
  2630.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  2631.                                     .getService(Components.interfaces.nsICategoryManager);
  2632.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  2633.                                      "service," + this._objects.service.contractID, 
  2634.                                      true, true, null);
  2635.   },
  2636.   
  2637.   getClassObject: function(componentManager, cid, iid) {
  2638.     if (!iid.equals(Components.interfaces.nsIFactory))
  2639.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  2640.  
  2641.     for (var key in this._objects) {
  2642.       if (cid.equals(this._objects[key].CID))
  2643.         return this._objects[key].factory;
  2644.     }
  2645.     
  2646.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2647.   },
  2648.   
  2649.   _makeFactory: #1= function(ctor) {
  2650.     function ci(outer, iid) {
  2651.       if (outer != null)
  2652.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  2653.       return (new ctor()).QueryInterface(iid);
  2654.     } 
  2655.     return { createInstance: ci };
  2656.   },
  2657.   
  2658.   _objects: {
  2659.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  2660.                contractID : "@mozilla.org/updates/update-service;1",
  2661.                className  : "Update Service",
  2662.                factory    : #1#(UpdateService)
  2663.              },
  2664.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  2665.                contractID : "@mozilla.org/updates/update-checker;1",
  2666.                className  : "Update Checker",
  2667.                factory    : #1#(Checker)
  2668.              },
  2669. //@line 2670 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2670.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  2671.                contractID : "@mozilla.org/updates/update-prompt;1",
  2672.                className  : "Update Prompt",
  2673.                factory    : #1#(UpdatePrompt)
  2674.              },
  2675. //@line 2676 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2676.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  2677.                contractID : "@mozilla.org/updates/timer-manager;1",
  2678.                className  : "Timer Manager",
  2679.                factory    : #1#(TimerManager)
  2680.              },
  2681.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  2682.                contractID : "@mozilla.org/updates/update-manager;1",
  2683.                className  : "Update Manager",
  2684.                factory    : #1#(UpdateManager)
  2685.              },
  2686.   },
  2687.   
  2688.   canUnload: function(componentManager) {
  2689.     return true;
  2690.   }
  2691. };
  2692.  
  2693. function NSGetModule(compMgr, fileSpec) {
  2694.   return gModule;
  2695. }
  2696.  
  2697. /**
  2698.  * Determines whether or there are installed addons which are incompatible 
  2699.  * with this update.
  2700.  * @param   update
  2701.  *          The update to check compatibility against
  2702.  * @returns true if there are no addons installed that are incompatible with
  2703.  *          the specified update, false otherwise.
  2704.  */
  2705. function isCompatible(update) {
  2706. //@line 2707 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2707.   var em = 
  2708.       Components.classes["@mozilla.org/extensions/manager;1"].
  2709.       getService(Components.interfaces.nsIExtensionManager);
  2710.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  2711.     nsIUpdateItem.TYPE_ADDON, false, { });
  2712.   return items.length == 0;
  2713. //@line 2716 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2714. }
  2715.  
  2716. /**
  2717.  * Shows a prompt for an update, provided there are no incompatible addons.
  2718.  * If there are, kick off an update check and see if updates are available
  2719.  * that will resolve the incompatibilities.
  2720.  * @param   update
  2721.  *          The available update to show
  2722.  */
  2723. function showPromptIfNoIncompatibilities(update) {
  2724.   function showPrompt(update) {
  2725.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  2726.     var prompter = 
  2727.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  2728.         createInstance(Components.interfaces.nsIUpdatePrompt);
  2729.     prompter.showUpdateAvailable(update);
  2730.   }
  2731.  
  2732. //@line 2735 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2733.   /**
  2734.    * Determines if an addon is compatible with a particular update.
  2735.    * @param   addon
  2736.    *          The addon to check
  2737.    * @param   version
  2738.    *          The extensionVersion of the update to check for compatibility 
  2739.    *          against.
  2740.    * @returns true if the addon is compatible, false otherwise
  2741.    */
  2742.   function addonIsCompatible(addon, version) {
  2743.     var vc = 
  2744.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  2745.         getService(Components.interfaces.nsIVersionComparator);
  2746.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  2747.           (vc.compare(version, addon.maxAppVersion) <= 0);
  2748.   }
  2749.  
  2750.   /**
  2751.    * An object implementing nsIAddonUpdateCheckListener that looks for 
  2752.    * available updates to addons and if updates are found that will make the 
  2753.    * user's installed addon set compatible with the update, suppresses the
  2754.    * prompt that would otherwise be shown.
  2755.    * @param   addons
  2756.    *          An array of incompatible addons that are installed.
  2757.    * @constructor
  2758.    */
  2759.   function Listener(addons) {
  2760.     this._addons = addons;
  2761.   }
  2762.   Listener.prototype = {
  2763.     _addons: null,
  2764.     
  2765.     /**
  2766.      * See nsIUpdateService.idl
  2767.      */
  2768.     onUpdateStarted: function() { 
  2769.     },
  2770.     onUpdateEnded: function() {
  2771.       // There are still incompatibilities, even after an extension update 
  2772.       // check to see if there were newer, compatible versions available, so
  2773.       // we have to prompt. 
  2774.       // 
  2775.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we 
  2776.       // handle incompatibilities:
  2777.       // 0    We count both VersionInfo updates _and_ NewerVersion updates
  2778.       //      against the list of incompatible addons installed - i.e. if
  2779.       //      Foo 1.2 is installed and it is incompatible with the update, and
  2780.       //      we find Foo 2.0 which is but which is not yet downloaded or 
  2781.       //      installed, then we do NOT prompt because the user can download
  2782.       //      Foo 2.0 when they restart after the update during the mismatch
  2783.       //      checking UI. This is the default, since it suppresses most 
  2784.       //      prompt dialogs. 
  2785.       // 1    We count only VersionInfo updates against the list of 
  2786.       //      incompatible addons installed - i.e. if the situation above
  2787.       //      with Foo 1.2 and available update to 2.0 applies, we DO show
  2788.       //      the prompt since a download operation will be required after
  2789.       //      the update. This is not the default and is supplied only as
  2790.       //      a hidden option for those that want it. 
  2791.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2792.                          INCOMPATIBLE_MODE_NEWVERSIONS);
  2793.       if ((mode == 0 && this._addons.length) || !isCompatible(update))
  2794.         showPrompt(update);
  2795.     },
  2796.     onAddonUpdateStarted: function(addon) {
  2797.     },
  2798.     onAddonUpdateEnded: function(addon, status) {
  2799.       if (status == Components.interfaces.nsIAddonUpdateCheckListener.STATUS_UPDATE &&
  2800.           addonIsCompatible(addon, update.extensionVersion)) {
  2801.         for (var i = 0; i < this._addons.length; ++i) {
  2802.           if (this._addons[i] == addon) {
  2803.             this._addons.splice(i, 1);
  2804.             break;
  2805.           }
  2806.         }
  2807.       }
  2808.     },
  2809.     /**
  2810.      * See nsISupports.idl
  2811.      */
  2812.     QueryInterface: function(iid) {
  2813.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  2814.           !iid.equals(Components.interfaces.nsISupports))
  2815.         throw Components.results.NS_ERROR_NO_INTERFACE;
  2816.       return this;
  2817.     }
  2818.   };
  2819.   
  2820.   if (!isCompatible(update)) {
  2821.     var em = 
  2822.         Components.classes["@mozilla.org/extensions/manager;1"].
  2823.         getService(Components.interfaces.nsIExtensionManager);
  2824.     var listener = new Listener(em.getIncompatibleItemList("", 
  2825.       update.extensionVersion, nsIUpdateItem.TYPE_ADDON, false, { }));
  2826.     // See documentation on |mode| above. 
  2827.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2828.                        INCOMPATIBLE_MODE_NEWVERSIONS);
  2829.     em.update([], 0, mode != 0, listener);
  2830.   }
  2831.   else
  2832. //@line 2835 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2833.     showPrompt(update);
  2834. }
  2835.