dom/network/src/NetworkStatsManager.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/dom/network/src/NetworkStatsManager.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,476 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this file,
     1.6 + * You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +"use strict";
     1.9 +
    1.10 +const DEBUG = false;
    1.11 +function debug(s) { dump("-*- NetworkStatsManager: " + s + "\n"); }
    1.12 +
    1.13 +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
    1.14 +
    1.15 +Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    1.16 +Cu.import("resource://gre/modules/Services.jsm");
    1.17 +Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
    1.18 +
    1.19 +// Ensure NetworkStatsService and NetworkStatsDB are loaded in the parent process
    1.20 +// to receive messages from the child processes.
    1.21 +let appInfo = Cc["@mozilla.org/xre/app-info;1"];
    1.22 +let isParentProcess = !appInfo || appInfo.getService(Ci.nsIXULRuntime)
    1.23 +                        .processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
    1.24 +if (isParentProcess) {
    1.25 +  Cu.import("resource://gre/modules/NetworkStatsService.jsm");
    1.26 +}
    1.27 +
    1.28 +XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
    1.29 +                                   "@mozilla.org/childprocessmessagemanager;1",
    1.30 +                                   "nsISyncMessageSender");
    1.31 +
    1.32 +// NetworkStatsData
    1.33 +const nsIClassInfo              = Ci.nsIClassInfo;
    1.34 +const NETWORKSTATSDATA_CID      = Components.ID("{3b16fe17-5583-483a-b486-b64a3243221c}");
    1.35 +const nsIDOMMozNetworkStatsData = Ci.nsIDOMMozNetworkStatsData;
    1.36 +
    1.37 +function NetworkStatsData(aWindow, aData) {
    1.38 +  this.rxBytes = aData.rxBytes;
    1.39 +  this.txBytes = aData.txBytes;
    1.40 +  this.date = new aWindow.Date(aData.date.getTime());
    1.41 +}
    1.42 +
    1.43 +NetworkStatsData.prototype = {
    1.44 +  __exposedProps__: {
    1.45 +    rxBytes: 'r',
    1.46 +    txBytes: 'r',
    1.47 +    date:  'r',
    1.48 +  },
    1.49 +
    1.50 +  classID : NETWORKSTATSDATA_CID,
    1.51 +  classInfo : XPCOMUtils.generateCI({classID: NETWORKSTATSDATA_CID,
    1.52 +                                     contractID:"@mozilla.org/networkstatsdata;1",
    1.53 +                                     classDescription: "NetworkStatsData",
    1.54 +                                     interfaces: [nsIDOMMozNetworkStatsData],
    1.55 +                                     flags: nsIClassInfo.DOM_OBJECT}),
    1.56 +
    1.57 +  QueryInterface : XPCOMUtils.generateQI([nsIDOMMozNetworkStatsData])
    1.58 +};
    1.59 +
    1.60 +// NetworkStatsInterface
    1.61 +const NETWORKSTATSINTERFACE_CONTRACTID = "@mozilla.org/networkstatsinterface;1";
    1.62 +const NETWORKSTATSINTERFACE_CID        = Components.ID("{f540615b-d803-43ff-8200-2a9d145a5645}");
    1.63 +const nsIDOMMozNetworkStatsInterface   = Ci.nsIDOMMozNetworkStatsInterface;
    1.64 +
    1.65 +function NetworkStatsInterface(aNetwork) {
    1.66 +  if (DEBUG) {
    1.67 +    debug("NetworkStatsInterface Constructor");
    1.68 +  }
    1.69 +  this.type = aNetwork.type;
    1.70 +  this.id = aNetwork.id;
    1.71 +}
    1.72 +
    1.73 +NetworkStatsInterface.prototype = {
    1.74 +  __exposedProps__: {
    1.75 +    id: 'r',
    1.76 +    type: 'r',
    1.77 +  },
    1.78 +
    1.79 +  classID : NETWORKSTATSINTERFACE_CID,
    1.80 +  classInfo : XPCOMUtils.generateCI({classID: NETWORKSTATSINTERFACE_CID,
    1.81 +                                     contractID: NETWORKSTATSINTERFACE_CONTRACTID,
    1.82 +                                     classDescription: "NetworkStatsInterface",
    1.83 +                                     interfaces: [nsIDOMMozNetworkStatsInterface],
    1.84 +                                     flags: nsIClassInfo.DOM_OBJECT}),
    1.85 +
    1.86 +  QueryInterface : XPCOMUtils.generateQI([nsIDOMMozNetworkStatsInterface])
    1.87 +}
    1.88 +
    1.89 +// NetworkStats
    1.90 +const NETWORKSTATS_CONTRACTID = "@mozilla.org/networkstats;1";
    1.91 +const NETWORKSTATS_CID        = Components.ID("{f1996e44-1057-4d4b-8ff8-919e76c4cfa9}");
    1.92 +const nsIDOMMozNetworkStats   = Ci.nsIDOMMozNetworkStats;
    1.93 +
    1.94 +function NetworkStats(aWindow, aStats) {
    1.95 +  if (DEBUG) {
    1.96 +    debug("NetworkStats Constructor");
    1.97 +  }
    1.98 +  this.appManifestURL = aStats.appManifestURL || null;
    1.99 +  this.serviceType = aStats.serviceType || null;
   1.100 +  this.network = new NetworkStatsInterface(aStats.network);
   1.101 +  this.start = aStats.start ? new aWindow.Date(aStats.start.getTime()) : null;
   1.102 +  this.end = aStats.end ? new aWindow.Date(aStats.end.getTime()) : null;
   1.103 +
   1.104 +  let samples = this.data = new aWindow.Array();
   1.105 +  for (let i = 0; i < aStats.data.length; i++) {
   1.106 +    samples.push(new NetworkStatsData(aWindow, aStats.data[i]));
   1.107 +  }
   1.108 +}
   1.109 +
   1.110 +NetworkStats.prototype = {
   1.111 +  __exposedProps__: {
   1.112 +    appManifestURL: 'r',
   1.113 +    serviceType: 'r',
   1.114 +    network: 'r',
   1.115 +    start: 'r',
   1.116 +    end:  'r',
   1.117 +    data:  'r',
   1.118 +  },
   1.119 +
   1.120 +  classID : NETWORKSTATS_CID,
   1.121 +  classInfo : XPCOMUtils.generateCI({classID: NETWORKSTATS_CID,
   1.122 +                                     contractID: NETWORKSTATS_CONTRACTID,
   1.123 +                                     classDescription: "NetworkStats",
   1.124 +                                     interfaces: [nsIDOMMozNetworkStats],
   1.125 +                                     flags: nsIClassInfo.DOM_OBJECT}),
   1.126 +
   1.127 +  QueryInterface : XPCOMUtils.generateQI([nsIDOMMozNetworkStats,
   1.128 +                                          nsIDOMMozNetworkStatsData,
   1.129 +                                          nsIDOMMozNetworkStatsInterface])
   1.130 +}
   1.131 +
   1.132 +// NetworkStatsAlarm
   1.133 +const NETWORKSTATSALARM_CID      = Components.ID("{063ebeb2-5c6e-47ae-bdcd-5e6ebdc7a68c}");
   1.134 +const nsIDOMMozNetworkStatsAlarm = Ci.nsIDOMMozNetworkStatsAlarm;
   1.135 +
   1.136 +function NetworkStatsAlarm(aAlarm) {
   1.137 +  this.alarmId = aAlarm.id;
   1.138 +  this.network = new NetworkStatsInterface(aAlarm.network);
   1.139 +  this.threshold = aAlarm.threshold;
   1.140 +  this.data = aAlarm.data;
   1.141 +}
   1.142 +
   1.143 +NetworkStatsAlarm.prototype = {
   1.144 +  __exposedProps__: {
   1.145 +    alarmId: 'r',
   1.146 +    network: 'r',
   1.147 +    threshold: 'r',
   1.148 +    data: 'r',
   1.149 +  },
   1.150 +
   1.151 +  classID : NETWORKSTATSALARM_CID,
   1.152 +  classInfo : XPCOMUtils.generateCI({classID: NETWORKSTATSALARM_CID,
   1.153 +                                     contractID:"@mozilla.org/networkstatsalarm;1",
   1.154 +                                     classDescription: "NetworkStatsAlarm",
   1.155 +                                     interfaces: [nsIDOMMozNetworkStatsAlarm],
   1.156 +                                     flags: nsIClassInfo.DOM_OBJECT}),
   1.157 +
   1.158 +  QueryInterface : XPCOMUtils.generateQI([nsIDOMMozNetworkStatsAlarm])
   1.159 +};
   1.160 +
   1.161 +// NetworkStatsManager
   1.162 +
   1.163 +const NETWORKSTATSMANAGER_CONTRACTID = "@mozilla.org/networkStatsManager;1";
   1.164 +const NETWORKSTATSMANAGER_CID        = Components.ID("{8a66f4c1-0c25-4a66-9fc5-0106947b91f9}");
   1.165 +const nsIDOMMozNetworkStatsManager   = Ci.nsIDOMMozNetworkStatsManager;
   1.166 +
   1.167 +function NetworkStatsManager() {
   1.168 +  if (DEBUG) {
   1.169 +    debug("Constructor");
   1.170 +  }
   1.171 +}
   1.172 +
   1.173 +NetworkStatsManager.prototype = {
   1.174 +  __proto__: DOMRequestIpcHelper.prototype,
   1.175 +
   1.176 +  checkPrivileges: function checkPrivileges() {
   1.177 +    if (!this.hasPrivileges) {
   1.178 +      throw Components.Exception("Permission denied", Cr.NS_ERROR_FAILURE);
   1.179 +    }
   1.180 +  },
   1.181 +
   1.182 +  getSamples: function getSamples(aNetwork, aStart, aEnd, aOptions) {
   1.183 +    this.checkPrivileges();
   1.184 +
   1.185 +    if (aStart.constructor.name !== "Date" ||
   1.186 +        aEnd.constructor.name !== "Date" ||
   1.187 +        aStart > aEnd) {
   1.188 +      throw Components.results.NS_ERROR_INVALID_ARG;
   1.189 +    }
   1.190 +
   1.191 +    let appManifestURL = null;
   1.192 +    let serviceType = null;
   1.193 +    if (aOptions) {
   1.194 +      if (aOptions.appManifestURL && aOptions.serviceType) {
   1.195 +        throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
   1.196 +      }
   1.197 +      appManifestURL = aOptions.appManifestURL;
   1.198 +      serviceType = aOptions.serviceType;
   1.199 +    }
   1.200 +
   1.201 +    // TODO Bug 929410 Date object cannot correctly pass through cpmm/ppmm IPC
   1.202 +    // This is just a work-around by passing timestamp numbers.
   1.203 +    aStart = aStart.getTime();
   1.204 +    aEnd = aEnd.getTime();
   1.205 +
   1.206 +    let request = this.createRequest();
   1.207 +    cpmm.sendAsyncMessage("NetworkStats:Get",
   1.208 +                          { network: aNetwork,
   1.209 +                            start: aStart,
   1.210 +                            end: aEnd,
   1.211 +                            appManifestURL: appManifestURL,
   1.212 +                            serviceType: serviceType,
   1.213 +                            id: this.getRequestId(request) });
   1.214 +    return request;
   1.215 +  },
   1.216 +
   1.217 +  clearStats: function clearStats(aNetwork) {
   1.218 +    this.checkPrivileges();
   1.219 +
   1.220 +    let request = this.createRequest();
   1.221 +    cpmm.sendAsyncMessage("NetworkStats:Clear",
   1.222 +                          { network: aNetwork,
   1.223 +                            id: this.getRequestId(request) });
   1.224 +    return request;
   1.225 +  },
   1.226 +
   1.227 +  clearAllStats: function clearAllStats() {
   1.228 +    this.checkPrivileges();
   1.229 +
   1.230 +    let request = this.createRequest();
   1.231 +    cpmm.sendAsyncMessage("NetworkStats:ClearAll",
   1.232 +                          {id: this.getRequestId(request)});
   1.233 +    return request;
   1.234 +  },
   1.235 +
   1.236 +  addAlarm: function addAlarm(aNetwork, aThreshold, aOptions) {
   1.237 +    this.checkPrivileges();
   1.238 +
   1.239 +    if (!aOptions) {
   1.240 +      aOptions = Object.create(null);
   1.241 +    }
   1.242 +
   1.243 +    if (aOptions.startTime && aOptions.startTime.constructor.name !== "Date") {
   1.244 +      throw Components.results.NS_ERROR_INVALID_ARG;
   1.245 +    }
   1.246 +
   1.247 +    let request = this.createRequest();
   1.248 +    cpmm.sendAsyncMessage("NetworkStats:SetAlarm",
   1.249 +                          {id: this.getRequestId(request),
   1.250 +                           data: {network: aNetwork,
   1.251 +                                  threshold: aThreshold,
   1.252 +                                  startTime: aOptions.startTime,
   1.253 +                                  data: aOptions.data,
   1.254 +                                  manifestURL: this.manifestURL,
   1.255 +                                  pageURL: this.pageURL}});
   1.256 +    return request;
   1.257 +  },
   1.258 +
   1.259 +  getAllAlarms: function getAllAlarms(aNetwork) {
   1.260 +    this.checkPrivileges();
   1.261 +
   1.262 +    let request = this.createRequest();
   1.263 +    cpmm.sendAsyncMessage("NetworkStats:GetAlarms",
   1.264 +                          {id: this.getRequestId(request),
   1.265 +                           data: {network: aNetwork,
   1.266 +                                  manifestURL: this.manifestURL}});
   1.267 +    return request;
   1.268 +  },
   1.269 +
   1.270 +  removeAlarms: function removeAlarms(aAlarmId) {
   1.271 +    this.checkPrivileges();
   1.272 +
   1.273 +    if (aAlarmId == 0) {
   1.274 +      aAlarmId = -1;
   1.275 +    }
   1.276 +
   1.277 +    let request = this.createRequest();
   1.278 +    cpmm.sendAsyncMessage("NetworkStats:RemoveAlarms",
   1.279 +                          {id: this.getRequestId(request),
   1.280 +                           data: {alarmId: aAlarmId,
   1.281 +                                  manifestURL: this.manifestURL}});
   1.282 +
   1.283 +    return request;
   1.284 +  },
   1.285 +
   1.286 +  getAvailableNetworks: function getAvailableNetworks() {
   1.287 +    this.checkPrivileges();
   1.288 +
   1.289 +    let request = this.createRequest();
   1.290 +    cpmm.sendAsyncMessage("NetworkStats:GetAvailableNetworks",
   1.291 +                          { id: this.getRequestId(request) });
   1.292 +    return request;
   1.293 +  },
   1.294 +
   1.295 +  getAvailableServiceTypes: function getAvailableServiceTypes() {
   1.296 +    this.checkPrivileges();
   1.297 +
   1.298 +    let request = this.createRequest();
   1.299 +    cpmm.sendAsyncMessage("NetworkStats:GetAvailableServiceTypes",
   1.300 +                          { id: this.getRequestId(request) });
   1.301 +    return request;
   1.302 +  },
   1.303 +
   1.304 +  get sampleRate() {
   1.305 +    this.checkPrivileges();
   1.306 +    return cpmm.sendSyncMessage("NetworkStats:SampleRate")[0];
   1.307 +  },
   1.308 +
   1.309 +  get maxStorageAge() {
   1.310 +    this.checkPrivileges();
   1.311 +    return cpmm.sendSyncMessage("NetworkStats:MaxStorageAge")[0];
   1.312 +  },
   1.313 +
   1.314 +  receiveMessage: function(aMessage) {
   1.315 +    if (DEBUG) {
   1.316 +      debug("NetworkStatsmanager::receiveMessage: " + aMessage.name);
   1.317 +    }
   1.318 +
   1.319 +    let msg = aMessage.json;
   1.320 +    let req = this.takeRequest(msg.id);
   1.321 +    if (!req) {
   1.322 +      if (DEBUG) {
   1.323 +        debug("No request stored with id " + msg.id);
   1.324 +      }
   1.325 +      return;
   1.326 +    }
   1.327 +
   1.328 +    switch (aMessage.name) {
   1.329 +      case "NetworkStats:Get:Return":
   1.330 +        if (msg.error) {
   1.331 +          Services.DOMRequest.fireError(req, msg.error);
   1.332 +          return;
   1.333 +        }
   1.334 +
   1.335 +        let result = new NetworkStats(this._window, msg.result);
   1.336 +        if (DEBUG) {
   1.337 +          debug("result: " + JSON.stringify(result));
   1.338 +        }
   1.339 +        Services.DOMRequest.fireSuccess(req, result);
   1.340 +        break;
   1.341 +
   1.342 +      case "NetworkStats:GetAvailableNetworks:Return":
   1.343 +        if (msg.error) {
   1.344 +          Services.DOMRequest.fireError(req, msg.error);
   1.345 +          return;
   1.346 +        }
   1.347 +
   1.348 +        let networks = new this._window.Array();
   1.349 +        for (let i = 0; i < msg.result.length; i++) {
   1.350 +          networks.push(new NetworkStatsInterface(msg.result[i]));
   1.351 +        }
   1.352 +
   1.353 +        Services.DOMRequest.fireSuccess(req, networks);
   1.354 +        break;
   1.355 +
   1.356 +      case "NetworkStats:GetAvailableServiceTypes:Return":
   1.357 +        if (msg.error) {
   1.358 +          Services.DOMRequest.fireError(req, msg.error);
   1.359 +          return;
   1.360 +        }
   1.361 +
   1.362 +        let serviceTypes = new this._window.Array();
   1.363 +        for (let i = 0; i < msg.result.length; i++) {
   1.364 +          serviceTypes.push(msg.result[i]);
   1.365 +        }
   1.366 +
   1.367 +        Services.DOMRequest.fireSuccess(req, serviceTypes);
   1.368 +        break;
   1.369 +
   1.370 +      case "NetworkStats:Clear:Return":
   1.371 +      case "NetworkStats:ClearAll:Return":
   1.372 +        if (msg.error) {
   1.373 +          Services.DOMRequest.fireError(req, msg.error);
   1.374 +          return;
   1.375 +        }
   1.376 +
   1.377 +        Services.DOMRequest.fireSuccess(req, true);
   1.378 +        break;
   1.379 +
   1.380 +      case "NetworkStats:SetAlarm:Return":
   1.381 +      case "NetworkStats:RemoveAlarms:Return":
   1.382 +        if (msg.error) {
   1.383 +          Services.DOMRequest.fireError(req, msg.error);
   1.384 +          return;
   1.385 +        }
   1.386 +
   1.387 +        Services.DOMRequest.fireSuccess(req, msg.result);
   1.388 +        break;
   1.389 +
   1.390 +      case "NetworkStats:GetAlarms:Return":
   1.391 +        if (msg.error) {
   1.392 +          Services.DOMRequest.fireError(req, msg.error);
   1.393 +          return;
   1.394 +        }
   1.395 +
   1.396 +        let alarms = new this._window.Array();
   1.397 +        for (let i = 0; i < msg.result.length; i++) {
   1.398 +          alarms.push(new NetworkStatsAlarm(msg.result[i]));
   1.399 +        }
   1.400 +
   1.401 +        Services.DOMRequest.fireSuccess(req, alarms);
   1.402 +        break;
   1.403 +
   1.404 +      default:
   1.405 +        if (DEBUG) {
   1.406 +          debug("Wrong message: " + aMessage.name);
   1.407 +        }
   1.408 +    }
   1.409 +  },
   1.410 +
   1.411 +  init: function(aWindow) {
   1.412 +    // Set navigator.mozNetworkStats to null.
   1.413 +    if (!Services.prefs.getBoolPref("dom.mozNetworkStats.enabled")) {
   1.414 +      return null;
   1.415 +    }
   1.416 +
   1.417 +    let principal = aWindow.document.nodePrincipal;
   1.418 +    let secMan = Services.scriptSecurityManager;
   1.419 +    let perm = principal == secMan.getSystemPrincipal() ?
   1.420 +                 Ci.nsIPermissionManager.ALLOW_ACTION :
   1.421 +                 Services.perms.testExactPermissionFromPrincipal(principal,
   1.422 +                                                                 "networkstats-manage");
   1.423 +
   1.424 +    // Only pages with perm set can use the netstats.
   1.425 +    this.hasPrivileges = perm == Ci.nsIPermissionManager.ALLOW_ACTION;
   1.426 +    if (DEBUG) {
   1.427 +      debug("has privileges: " + this.hasPrivileges);
   1.428 +    }
   1.429 +
   1.430 +    if (!this.hasPrivileges) {
   1.431 +      return null;
   1.432 +    }
   1.433 +
   1.434 +    this.initDOMRequestHelper(aWindow, ["NetworkStats:Get:Return",
   1.435 +                                        "NetworkStats:GetAvailableNetworks:Return",
   1.436 +                                        "NetworkStats:GetAvailableServiceTypes:Return",
   1.437 +                                        "NetworkStats:Clear:Return",
   1.438 +                                        "NetworkStats:ClearAll:Return",
   1.439 +                                        "NetworkStats:SetAlarm:Return",
   1.440 +                                        "NetworkStats:GetAlarms:Return",
   1.441 +                                        "NetworkStats:RemoveAlarms:Return"]);
   1.442 +
   1.443 +    // Init app properties.
   1.444 +    let appsService = Cc["@mozilla.org/AppsService;1"]
   1.445 +                        .getService(Ci.nsIAppsService);
   1.446 +
   1.447 +    this.manifestURL = appsService.getManifestURLByLocalId(principal.appId);
   1.448 +
   1.449 +    let isApp = !!this.manifestURL.length;
   1.450 +    if (isApp) {
   1.451 +      this.pageURL = principal.URI.spec;
   1.452 +    }
   1.453 +  },
   1.454 +
   1.455 +  // Called from DOMRequestIpcHelper
   1.456 +  uninit: function uninit() {
   1.457 +    if (DEBUG) {
   1.458 +      debug("uninit call");
   1.459 +    }
   1.460 +  },
   1.461 +
   1.462 +  classID : NETWORKSTATSMANAGER_CID,
   1.463 +  QueryInterface : XPCOMUtils.generateQI([nsIDOMMozNetworkStatsManager,
   1.464 +                                         Ci.nsIDOMGlobalPropertyInitializer,
   1.465 +                                         Ci.nsISupportsWeakReference,
   1.466 +                                         Ci.nsIObserver]),
   1.467 +
   1.468 +  classInfo : XPCOMUtils.generateCI({classID: NETWORKSTATSMANAGER_CID,
   1.469 +                                     contractID: NETWORKSTATSMANAGER_CONTRACTID,
   1.470 +                                     classDescription: "NetworkStatsManager",
   1.471 +                                     interfaces: [nsIDOMMozNetworkStatsManager],
   1.472 +                                     flags: nsIClassInfo.DOM_OBJECT})
   1.473 +}
   1.474 +
   1.475 +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkStatsAlarm,
   1.476 +                                                     NetworkStatsData,
   1.477 +                                                     NetworkStatsInterface,
   1.478 +                                                     NetworkStats,
   1.479 +                                                     NetworkStatsManager]);

mercurial