~ubuntu-branches/ubuntu/maverick/ubufox/maverick-proposed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Plugin Finder Service.
 *
 * The Initial Developer of the Original Code is
 * IBM Corporation.
 * Portions created by the IBM Corporation are Copyright (C) 2004
 * IBM Corporation. All Rights Reserved.
 *
 * Contributor(s):
 *   Doron Rosenberg <doronr@us.ibm.com>
 *   Alexander Sack <asac@jwsdot.com> - Canonical Ltd.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

Components.utils.import("resource://gre/modules/AddonManager.jsm");

const DOWNLOAD_STARTED = 0;
const DOWNLOAD_FINISHED = 1;
const INSTALL_STARTED = 2;
const INSTALL_FINISHED = 3;
const INSTALLS_COMPLETE = 4;

function getLocalizedError(key)
{
  return document.getElementById("xpinstallStrings").getString(key);
}

function binaryToHex(input)
{
  return [('0' + input.charCodeAt(i).toString(16)).slice(-2)
          for (i in input)].join('');
}

function verifyHash(aFile, aHash)
{
  try {
    var [, method, hash] = /^([A-Za-z0-9]+):(.*)$/.exec(aHash);

    var fis = Components.classes['@mozilla.org/network/file-input-stream;1'].
      createInstance(Components.interfaces.nsIFileInputStream);
    fis.init(aFile, -1, -1, 0);

    var hasher = Components.classes['@mozilla.org/security/hash;1'].
      createInstance(Components.interfaces.nsICryptoHash);
    hasher.initWithString(method);
    hasher.updateFromStream(fis, -1);
    dlhash = binaryToHex(hasher.finish(false));
    return dlhash == hash;
  }
  catch (e) {
    Components.utils.reportError(e);
    return false;
  }
}

function InstallerObserver(aPlugin)
{
  this._plugin = aPlugin;
  this._init();
}

InstallerObserver.prototype = {
  _init: function()
  {
    try {
      var ios = Components.classes["@mozilla.org/network/io-service;1"].
        getService(Components.interfaces.nsIIOService);
      var uri = ios.newURI(this._plugin.InstallerLocation, null, null);
      uri.QueryInterface(Components.interfaces.nsIURL);

      // Use a local filename appropriate for the OS
      var leafName = uri.fileName;
      var os = Components.classes["@mozilla.org/xre/app-info;1"]
                         .getService(Components.interfaces.nsIXULRuntime)
                         .OS;
      if (os == "WINNT" && leafName.indexOf(".") < 0)
        leafName += ".exe";

      var dirs = Components.classes["@mozilla.org/file/directory_service;1"].
        getService(Components.interfaces.nsIProperties);

      var resultFile = dirs.get("TmpD", Components.interfaces.nsIFile);
      resultFile.append(leafName);
      resultFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE,
                              0770);

      var channel = ios.newChannelFromURI(uri);
      this._downloader =
        Components.classes["@mozilla.org/network/downloader;1"].
          createInstance(Components.interfaces.nsIDownloader);
      this._downloader.init(this, resultFile);
      channel.notificationCallbacks = this;

      this._fireNotification(DOWNLOAD_STARTED, null);

      channel.asyncOpen(this._downloader, null);
    }
    catch (e) {
      Components.utils.reportError(e);
      this._fireNotification(INSTALL_FINISHED, getLocalizedError("error-228"));
      if (resultFile && resultFile.exists())
        resultfile.remove(false);
    }
  },

  /**
   * Inform the gPluginInstaller about what's going on.
   */
  _fireNotification: function(aStatus, aErrorMsg)
  {
    gPluginInstaller.pluginXPIInstallationProgress(this._plugin.pid,
                                                   aStatus, aErrorMsg);

    if (aStatus == INSTALL_FINISHED) {
      --PluginInstallService._installersPending;
      PluginInstallService._fireFinishedNotification();
    }
  },

  QueryInterface: function(iid)
  {
    if (iid.equals(Components.interfaces.nsISupports) ||
        iid.equals(Components.interfaces.nsIInterfaceRequestor) ||
        iid.equals(Components.interfaces.nsIDownloadObserver) ||
        iid.equals(Components.interfaces.nsIProgressEventSink))
      return this;

    throw Components.results.NS_ERROR_NO_INTERFACE;
  },

  getInterface: function(iid)
  {
    if (iid.equals(Components.interfaces.nsIProgressEventSink))
      return this;

    return null;
  },

  onDownloadComplete: function(downloader, request, ctxt, status, result)
  {
    if (!Components.isSuccessCode(status)) {
      // xpinstall error 228 is "Download Error"
      this._fireNotification(INSTALL_FINISHED, getLocalizedError("error-228"));
      result.remove(false);
      return;
    }

    this._fireNotification(DOWNLOAD_FINISHED);

    if (this._plugin.InstallerHash &&
        !verifyHash(result, this._plugin.InstallerHash)) {
      // xpinstall error 261 is "Invalid file hash..."
      this._fireNotification(INSTALL_FINISHED, getLocalizedError("error-261"));
      result.remove(false);
      return;
    }

    this._fireNotification(INSTALL_STARTED);

    result.QueryInterface(Components.interfaces.nsILocalFile);
    try {
      // Make sure the file is executable
      result.permissions = 0770;
      var process = Components.classes["@mozilla.org/process/util;1"]
                              .createInstance(Components.interfaces.nsIProcess);
      process.init(result);
      var self = this;
      process.runAsync([], 0, {
        observe: function(subject, topic, data) {
          if (topic != "process-finished") {
            Components.utils.reportError("Failed to launch installer");
            self._fireNotification(INSTALL_FINISHED,
                                   getLocalizedError("error-207"));
          }
          else if (process.exitValue != 0) {
            Components.utils.reportError("Installer returned exit code " + process.exitValue);
            self._fireNotification(INSTALL_FINISHED,
                                   getLocalizedError("error-203"));
          }
          else {
            self._fireNotification(INSTALL_FINISHED, null);
          }
          result.remove(false);
        }
      });
    }
    catch (e) {
      Components.utils.reportError(e);
      this._fireNotification(INSTALL_FINISHED, getLocalizedError("error-207"));
      result.remove(false);
    }
  },

  onProgress: function(aRequest, aContext, aProgress, aProgressMax)
  {
    gPluginInstaller.pluginInstallationProgressMeter(this._plugin.pid,
                                                     aProgress,
                                                     aProgressMax);
  },

  onStatus: function(aRequest, aContext, aStatus, aStatusArg)
  {
    /* pass */
  }
};

var PluginInstallService = {

  /**
   * Start installation of installers and XPI plugins.
   * @param aInstallerPlugins An array of objects which should have the
   *                          properties "pid", "InstallerLocation",
   *                          and "InstallerHash"
   * @param aXPIPlugins       An array of objects which should have the
   *                          properties "pid", "XPILocation",
   *                          and "XPIHash"
   */
  startPluginInstallation: function (aInstallerPlugins,
                                     aXPIPlugins)
  {
    this._xpiPlugins = aXPIPlugins;
    this._xpisPending = aXPIPlugins.length;

    aXPIPlugins.forEach(function(plugin) {
      AddonManager.getInstallForURL(plugin.XPILocation, function(install) {
        install.addListener(PluginInstallService);
        install.install();
      }, "application/x-xpinstall", plugin.XPIHash);
    });

    // InstallerObserver may finish immediately so we must initialise the
    // installers after setting the number of installers and xpis pending
    this._installersPending = aInstallerPlugins.length;
    this._installerPlugins = [new InstallerObserver(plugin)
                              for each (plugin in aInstallerPlugins)];
  },

  _fireFinishedNotification: function()
  {
    if (this._installersPending == 0 && this._xpisPending == 0)
      gPluginInstaller.pluginXPIInstallationProgress(null, INSTALLS_COMPLETE, null);
  },

  getPidForInstall: function(install) {
    for (let i = 0; i < this._xpiPlugins.length; i++) {
      if (install.sourceURI.spec == this._xpiPlugins[i].XPILocation)
        return this._xpiPlugins[i].pid;
    }
    return -1;
  },

  // InstallListener interface
  onDownloadStarted: function(install) {
    var pid = this.getPidForInstall(install);
    gPluginInstaller.pluginXPIInstallationProgress(pid, DOWNLOAD_STARTED, null);
  },

  onDownloadProgress: function(install) {
    var pid = this.getPidForInstall(install);
    gPluginInstaller.pluginXPIInstallationProgressMeter(pid, install.progress,
                                                     install.maxProgress);
  },

  onDownloadEnded: function(install) {
    var pid = this.getPidForInstall(install);
    gPluginInstaller.pluginXPIInstallationProgress(pid, DOWNLOAD_FINISHED, null);
  },

  onDownloadFailed: function(install) {
    var pid = this.getPidForInstall(install);
    switch (install.error) {
    case AddonManager.ERROR_NETWORK_FAILURE:
      var errorMsg = getLocalizedError("error-228");
      break;
    case AddonManager.ERROR_INCORRECT_HASH:
      var errorMsg = getLocalizedError("error-261");
      break;
    case AddonManager.ERROR_CORRUPT_FILE:
      var errorMsg = getLocalizedError("error-207");
      break;
    }
    gPluginInstaller.pluginXPIInstallationProgress(pid, INSTALL_FINISHED, errorMsg);

    this._xpisPending--;
    this._fireFinishedNotification();
  },

  onInstallStarted: function(install) {
    var pid = this.getPidForInstall(install);
    gPluginInstaller.pluginXPIInstallationProgress(pid, INSTALL_STARTED, null);
  },

  onInstallEnded: function(install, addon) {
    var pid = this.getPidForInstall(install);
    gPluginInstaller.pluginXPIInstallationProgress(pid, INSTALL_FINISHED, null);

    this._xpisPending--;
    this._fireFinishedNotification();
  },

  onInstallFailed: function(install) {
    var pid = this.getPidForInstall(install);
    gPluginInstaller.pluginXPIInstallationProgress(pid, INSTALL_FINISHED,
                                                   getLocalizedError("error-203"));

    this._xpisPending--;
    this._fireFinishedNotification();
  }
}


var AptInstaller = {

  mAptInstallerService: null,
  mAptUrlArray: null,
  mAptPidArray: null,
  mRunning: false,

  install: function(aAptPlugins,
		    aAptInstallerService) {

    this.mAptInstallerService = aAptInstallerService;
    this.mAptPlugins = aAptPlugins;
    this.mRunning = true;

    //    var thread = Components.classes["@mozilla.org/thread;1"]
    //      .createInstance(Components.interfaces.nsIThread);
    //    thread.init(this, 0, nsIThread.PRIORITY_NORMAL, nsIThread.SCOPE_LOCAL, nsIThread.STATE_UNJOINABLE);
    this.run();
  },

  run: function()
  {
    for (var i = 0; i < this.mAptPlugins.length; i++) {
      var aptUrl = this.mAptPlugins[i].XPILocation;
      var aptPid = this.mAptPlugins[i].pid;
      this.mAptInstallerService.onNotifyStart(aptUrl, aptPid);

      var executable =
        Components.classes['@mozilla.org/file/local;1']
       .createInstance(Components.interfaces.nsILocalFile);

      executable.initWithPath("/usr/bin/apturl");

      if(!executable.exists() || !executable.isExecutable()) {
        window.alert('Unexpected error!');
        this.mAptInstallerService.onNotifyResult(aptUrl, aptPid, -1);
        continue;
      }

      var procUtil =
        Components.classes['@mozilla.org/process/util;1']
        .createInstance(Components.interfaces.nsIProcess);

      var nsFile = executable.QueryInterface(Components.interfaces.nsIFile);

      procUtil.init(executable);

      var prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
                                .getService(Components.interfaces.nsIPrefBranch);

      var proxyType = prefBranch.getIntPref("network.proxy.type");
      var proxyHost = prefBranch.getCharPref("network.proxy.http");
      var proxyPort = prefBranch.getIntPref("network.proxy.http_port");

      var httpProxy = "";
      if(proxyType > 0 && proxyHost != null && proxyHost.length > 0)
      {
        httpProxy = proxyHost;
        if(proxyPort > 0)
        {
          httpProxy = httpProxy + ":" + proxyPort;
        }
      }

      var args = new Array();
      if(httpProxy.length > 0)
      {
        args = new Array("--http-proxy", httpProxy, aptUrl);
      } else {
        args = new Array(aptUrl);
      }
      procUtil.run(true, args, args.length);
      res = procUtil.exitValue;

      this.mAptInstallerService.onNotifyResult(aptUrl, aptPid, res);
    }

    this.mAptInstallerService.onNotifyResult(null, null, -1 );
    mRunning = false;
    return true;
  }
}

var PluginAPTInstallService = {
  
  init: function () 
  {
  },

  pluginPidArray: null,

  startPluginInstallation: function (aAptPlugins) {
    AptInstaller.install(aAptPlugins, this);
  },

  onNotifyStart: function (aptUrl, aptPid) {
    gPluginInstaller.pluginXPIInstallationProgress(aptPid, 6, null);
  },

  onNotifyResult: function (aptUrl, aptPid, result) {
    if(result > 0) {
      gPluginInstaller.pluginXPIInstallationProgress(aptPid, 7, "Apt Install Failed or Cancelled");
    } else if (result == 0) {
      gPluginInstaller.pluginXPIInstallationProgress(aptPid, 7, null);
    } else {
      gPluginInstaller.pluginXPIInstallationProgress(null, 8, null);
    }
  }
}