dom/system/gonk/RadioInterfaceLayer.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/dom/system/gonk/RadioInterfaceLayer.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,4774 @@
     1.4 +/* Copyright 2012 Mozilla Foundation and Mozilla contributors
     1.5 + *
     1.6 + * Licensed under the Apache License, Version 2.0 (the "License");
     1.7 + * you may not use this file except in compliance with the License.
     1.8 + * You may obtain a copy of the License at
     1.9 + *
    1.10 + *     http://www.apache.org/licenses/LICENSE-2.0
    1.11 + *
    1.12 + * Unless required by applicable law or agreed to in writing, software
    1.13 + * distributed under the License is distributed on an "AS IS" BASIS,
    1.14 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    1.15 + * See the License for the specific language governing permissions and
    1.16 + * limitations under the License.
    1.17 + */
    1.18 +
    1.19 +"use strict";
    1.20 +
    1.21 +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
    1.22 +
    1.23 +Cu.import("resource://gre/modules/XPCOMUtils.jsm");
    1.24 +Cu.import("resource://gre/modules/Services.jsm");
    1.25 +Cu.import("resource://gre/modules/Sntp.jsm");
    1.26 +Cu.import("resource://gre/modules/systemlibs.js");
    1.27 +Cu.import("resource://gre/modules/Promise.jsm");
    1.28 +Cu.import("resource://gre/modules/FileUtils.jsm");
    1.29 +
    1.30 +var RIL = {};
    1.31 +Cu.import("resource://gre/modules/ril_consts.js", RIL);
    1.32 +
    1.33 +// set to true in ril_consts.js to see debug messages
    1.34 +var DEBUG = RIL.DEBUG_RIL;
    1.35 +
    1.36 +// Read debug setting from pref
    1.37 +let debugPref = false;
    1.38 +try {
    1.39 +  debugPref = Services.prefs.getBoolPref("ril.debugging.enabled");
    1.40 +} catch(e) {
    1.41 +  debugPref = false;
    1.42 +}
    1.43 +DEBUG = RIL.DEBUG_RIL || debugPref;
    1.44 +
    1.45 +function debug(s) {
    1.46 +  dump("-*- RadioInterfaceLayer: " + s + "\n");
    1.47 +}
    1.48 +
    1.49 +// Ril quirk to attach data registration on demand.
    1.50 +let RILQUIRKS_DATA_REGISTRATION_ON_DEMAND =
    1.51 +  libcutils.property_get("ro.moz.ril.data_reg_on_demand", "false") == "true";
    1.52 +
    1.53 +// Ril quirk to always turn the radio off for the client without SIM card
    1.54 +// except hw default client.
    1.55 +let RILQUIRKS_RADIO_OFF_WO_CARD =
    1.56 +  libcutils.property_get("ro.moz.ril.radio_off_wo_card", "false") == "true";
    1.57 +
    1.58 +// Ril quirk to enable IPv6 protocol/roaming protocol in APN settings.
    1.59 +let RILQUIRKS_HAVE_IPV6 =
    1.60 +  libcutils.property_get("ro.moz.ril.ipv6", "false") == "true";
    1.61 +
    1.62 +const RADIOINTERFACELAYER_CID =
    1.63 +  Components.ID("{2d831c8d-6017-435b-a80c-e5d422810cea}");
    1.64 +const RADIOINTERFACE_CID =
    1.65 +  Components.ID("{6a7c91f0-a2b3-4193-8562-8969296c0b54}");
    1.66 +const RILNETWORKINTERFACE_CID =
    1.67 +  Components.ID("{3bdd52a9-3965-4130-b569-0ac5afed045e}");
    1.68 +const GSMICCINFO_CID =
    1.69 +  Components.ID("{d90c4261-a99d-47bc-8b05-b057bb7e8f8a}");
    1.70 +const CDMAICCINFO_CID =
    1.71 +  Components.ID("{39ba3c08-aacc-46d0-8c04-9b619c387061}");
    1.72 +
    1.73 +const NS_XPCOM_SHUTDOWN_OBSERVER_ID      = "xpcom-shutdown";
    1.74 +const kNetworkInterfaceStateChangedTopic = "network-interface-state-changed";
    1.75 +const kNetworkConnStateChangedTopic      = "network-connection-state-changed";
    1.76 +const kNetworkActiveChangedTopic         = "network-active-changed";
    1.77 +const kSmsReceivedObserverTopic          = "sms-received";
    1.78 +const kSilentSmsReceivedObserverTopic    = "silent-sms-received";
    1.79 +const kSmsSendingObserverTopic           = "sms-sending";
    1.80 +const kSmsSentObserverTopic              = "sms-sent";
    1.81 +const kSmsFailedObserverTopic            = "sms-failed";
    1.82 +const kSmsDeliverySuccessObserverTopic   = "sms-delivery-success";
    1.83 +const kSmsDeliveryErrorObserverTopic     = "sms-delivery-error";
    1.84 +const kMozSettingsChangedObserverTopic   = "mozsettings-changed";
    1.85 +const kSysMsgListenerReadyObserverTopic  = "system-message-listener-ready";
    1.86 +const kSysClockChangeObserverTopic       = "system-clock-change";
    1.87 +const kScreenStateChangedTopic           = "screen-state-changed";
    1.88 +
    1.89 +const kSettingsCellBroadcastSearchList = "ril.cellbroadcast.searchlist";
    1.90 +const kSettingsClockAutoUpdateEnabled = "time.clock.automatic-update.enabled";
    1.91 +const kSettingsClockAutoUpdateAvailable = "time.clock.automatic-update.available";
    1.92 +const kSettingsTimezoneAutoUpdateEnabled = "time.timezone.automatic-update.enabled";
    1.93 +const kSettingsTimezoneAutoUpdateAvailable = "time.timezone.automatic-update.available";
    1.94 +
    1.95 +const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
    1.96 +
    1.97 +const kPrefCellBroadcastDisabled = "ril.cellbroadcast.disabled";
    1.98 +const kPrefClirModePreference = "ril.clirMode";
    1.99 +const kPrefRilNumRadioInterfaces = "ril.numRadioInterfaces";
   1.100 +
   1.101 +const DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED = "received";
   1.102 +const DOM_MOBILE_MESSAGE_DELIVERY_SENDING  = "sending";
   1.103 +const DOM_MOBILE_MESSAGE_DELIVERY_SENT     = "sent";
   1.104 +const DOM_MOBILE_MESSAGE_DELIVERY_ERROR    = "error";
   1.105 +
   1.106 +const RADIO_POWER_OFF_TIMEOUT = 30000;
   1.107 +const SMS_HANDLED_WAKELOCK_TIMEOUT = 5000;
   1.108 +const HW_DEFAULT_CLIENT_ID = 0;
   1.109 +
   1.110 +const RIL_IPC_MOBILECONNECTION_MSG_NAMES = [
   1.111 +  "RIL:GetRilContext",
   1.112 +  "RIL:GetAvailableNetworks",
   1.113 +  "RIL:SelectNetwork",
   1.114 +  "RIL:SelectNetworkAuto",
   1.115 +  "RIL:SetPreferredNetworkType",
   1.116 +  "RIL:GetPreferredNetworkType",
   1.117 +  "RIL:SendMMI",
   1.118 +  "RIL:CancelMMI",
   1.119 +  "RIL:RegisterMobileConnectionMsg",
   1.120 +  "RIL:SetCallForwardingOptions",
   1.121 +  "RIL:GetCallForwardingOptions",
   1.122 +  "RIL:SetCallBarringOptions",
   1.123 +  "RIL:GetCallBarringOptions",
   1.124 +  "RIL:ChangeCallBarringPassword",
   1.125 +  "RIL:SetCallWaitingOptions",
   1.126 +  "RIL:GetCallWaitingOptions",
   1.127 +  "RIL:SetCallingLineIdRestriction",
   1.128 +  "RIL:GetCallingLineIdRestriction",
   1.129 +  "RIL:SetRoamingPreference",
   1.130 +  "RIL:GetRoamingPreference",
   1.131 +  "RIL:ExitEmergencyCbMode",
   1.132 +  "RIL:SetRadioEnabled",
   1.133 +  "RIL:SetVoicePrivacyMode",
   1.134 +  "RIL:GetVoicePrivacyMode",
   1.135 +  "RIL:GetSupportedNetworkTypes"
   1.136 +];
   1.137 +
   1.138 +const RIL_IPC_MOBILENETWORK_MSG_NAMES = [
   1.139 +  "RIL:GetLastKnownNetwork",
   1.140 +  "RIL:GetLastKnownHomeNetwork"
   1.141 +];
   1.142 +
   1.143 +const RIL_IPC_ICCMANAGER_MSG_NAMES = [
   1.144 +  "RIL:SendStkResponse",
   1.145 +  "RIL:SendStkMenuSelection",
   1.146 +  "RIL:SendStkTimerExpiration",
   1.147 +  "RIL:SendStkEventDownload",
   1.148 +  "RIL:GetCardLockState",
   1.149 +  "RIL:UnlockCardLock",
   1.150 +  "RIL:SetCardLock",
   1.151 +  "RIL:GetCardLockRetryCount",
   1.152 +  "RIL:IccOpenChannel",
   1.153 +  "RIL:IccExchangeAPDU",
   1.154 +  "RIL:IccCloseChannel",
   1.155 +  "RIL:ReadIccContacts",
   1.156 +  "RIL:UpdateIccContact",
   1.157 +  "RIL:RegisterIccMsg",
   1.158 +  "RIL:MatchMvno"
   1.159 +];
   1.160 +
   1.161 +const RIL_IPC_VOICEMAIL_MSG_NAMES = [
   1.162 +  "RIL:RegisterVoicemailMsg",
   1.163 +  "RIL:GetVoicemailInfo"
   1.164 +];
   1.165 +
   1.166 +const RIL_IPC_CELLBROADCAST_MSG_NAMES = [
   1.167 +  "RIL:RegisterCellBroadcastMsg"
   1.168 +];
   1.169 +
   1.170 +XPCOMUtils.defineLazyServiceGetter(this, "gPowerManagerService",
   1.171 +                                   "@mozilla.org/power/powermanagerservice;1",
   1.172 +                                   "nsIPowerManagerService");
   1.173 +
   1.174 +XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
   1.175 +                                   "@mozilla.org/mobilemessage/mobilemessageservice;1",
   1.176 +                                   "nsIMobileMessageService");
   1.177 +
   1.178 +XPCOMUtils.defineLazyServiceGetter(this, "gSmsService",
   1.179 +                                   "@mozilla.org/sms/smsservice;1",
   1.180 +                                   "nsISmsService");
   1.181 +
   1.182 +XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageDatabaseService",
   1.183 +                                   "@mozilla.org/mobilemessage/rilmobilemessagedatabaseservice;1",
   1.184 +                                   "nsIRilMobileMessageDatabaseService");
   1.185 +
   1.186 +XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
   1.187 +                                   "@mozilla.org/parentprocessmessagemanager;1",
   1.188 +                                   "nsIMessageBroadcaster");
   1.189 +
   1.190 +XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
   1.191 +                                   "@mozilla.org/settingsService;1",
   1.192 +                                   "nsISettingsService");
   1.193 +
   1.194 +XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
   1.195 +                                   "@mozilla.org/system-message-internal;1",
   1.196 +                                   "nsISystemMessagesInternal");
   1.197 +
   1.198 +XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
   1.199 +                                   "@mozilla.org/network/manager;1",
   1.200 +                                   "nsINetworkManager");
   1.201 +
   1.202 +XPCOMUtils.defineLazyServiceGetter(this, "gTimeService",
   1.203 +                                   "@mozilla.org/time/timeservice;1",
   1.204 +                                   "nsITimeService");
   1.205 +
   1.206 +XPCOMUtils.defineLazyServiceGetter(this, "gSystemWorkerManager",
   1.207 +                                   "@mozilla.org/telephony/system-worker-manager;1",
   1.208 +                                   "nsISystemWorkerManager");
   1.209 +
   1.210 +XPCOMUtils.defineLazyServiceGetter(this, "gTelephonyProvider",
   1.211 +                                   "@mozilla.org/telephony/telephonyprovider;1",
   1.212 +                                   "nsIGonkTelephonyProvider");
   1.213 +
   1.214 +XPCOMUtils.defineLazyGetter(this, "WAP", function() {
   1.215 +  let wap = {};
   1.216 +  Cu.import("resource://gre/modules/WapPushManager.js", wap);
   1.217 +  return wap;
   1.218 +});
   1.219 +
   1.220 +XPCOMUtils.defineLazyGetter(this, "PhoneNumberUtils", function() {
   1.221 +  let ns = {};
   1.222 +  Cu.import("resource://gre/modules/PhoneNumberUtils.jsm", ns);
   1.223 +  return ns.PhoneNumberUtils;
   1.224 +});
   1.225 +
   1.226 +XPCOMUtils.defineLazyGetter(this, "gMessageManager", function() {
   1.227 +  return {
   1.228 +    QueryInterface: XPCOMUtils.generateQI([Ci.nsIMessageListener,
   1.229 +                                           Ci.nsIObserver]),
   1.230 +
   1.231 +    ril: null,
   1.232 +
   1.233 +    // Manage message targets in terms of topic. Only the authorized and
   1.234 +    // registered contents can receive related messages.
   1.235 +    targetsByTopic: {},
   1.236 +    topics: [],
   1.237 +
   1.238 +    targetMessageQueue: [],
   1.239 +    ready: false,
   1.240 +
   1.241 +    init: function(ril) {
   1.242 +      this.ril = ril;
   1.243 +
   1.244 +      Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
   1.245 +      Services.obs.addObserver(this, kSysMsgListenerReadyObserverTopic, false);
   1.246 +      this._registerMessageListeners();
   1.247 +    },
   1.248 +
   1.249 +    _shutdown: function() {
   1.250 +      this.ril = null;
   1.251 +
   1.252 +      Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
   1.253 +      this._unregisterMessageListeners();
   1.254 +    },
   1.255 +
   1.256 +    _registerMessageListeners: function() {
   1.257 +      ppmm.addMessageListener("child-process-shutdown", this);
   1.258 +      for (let msgname of RIL_IPC_MOBILECONNECTION_MSG_NAMES) {
   1.259 +        ppmm.addMessageListener(msgname, this);
   1.260 +      }
   1.261 +      for (let msgname of RIL_IPC_MOBILENETWORK_MSG_NAMES) {
   1.262 +        ppmm.addMessageListener(msgname, this);
   1.263 +      }
   1.264 +      for (let msgName of RIL_IPC_ICCMANAGER_MSG_NAMES) {
   1.265 +        ppmm.addMessageListener(msgName, this);
   1.266 +      }
   1.267 +      for (let msgname of RIL_IPC_VOICEMAIL_MSG_NAMES) {
   1.268 +        ppmm.addMessageListener(msgname, this);
   1.269 +      }
   1.270 +      for (let msgname of RIL_IPC_CELLBROADCAST_MSG_NAMES) {
   1.271 +        ppmm.addMessageListener(msgname, this);
   1.272 +      }
   1.273 +    },
   1.274 +
   1.275 +    _unregisterMessageListeners: function() {
   1.276 +      ppmm.removeMessageListener("child-process-shutdown", this);
   1.277 +      for (let msgname of RIL_IPC_MOBILECONNECTION_MSG_NAMES) {
   1.278 +        ppmm.removeMessageListener(msgname, this);
   1.279 +      }
   1.280 +      for (let msgname of RIL_IPC_MOBILENETWORK_MSG_NAMES) {
   1.281 +        ppmm.removeMessageListener(msgname, this);
   1.282 +      }
   1.283 +      for (let msgName of RIL_IPC_ICCMANAGER_MSG_NAMES) {
   1.284 +        ppmm.removeMessageListener(msgName, this);
   1.285 +      }
   1.286 +      for (let msgname of RIL_IPC_VOICEMAIL_MSG_NAMES) {
   1.287 +        ppmm.removeMessageListener(msgname, this);
   1.288 +      }
   1.289 +      for (let msgname of RIL_IPC_CELLBROADCAST_MSG_NAMES) {
   1.290 +        ppmm.removeMessageListener(msgname, this);
   1.291 +      }
   1.292 +      ppmm = null;
   1.293 +    },
   1.294 +
   1.295 +    _registerMessageTarget: function(topic, target) {
   1.296 +      let targets = this.targetsByTopic[topic];
   1.297 +      if (!targets) {
   1.298 +        targets = this.targetsByTopic[topic] = [];
   1.299 +        let list = this.topics;
   1.300 +        if (list.indexOf(topic) == -1) {
   1.301 +          list.push(topic);
   1.302 +        }
   1.303 +      }
   1.304 +
   1.305 +      if (targets.indexOf(target) != -1) {
   1.306 +        if (DEBUG) debug("Already registered this target!");
   1.307 +        return;
   1.308 +      }
   1.309 +
   1.310 +      targets.push(target);
   1.311 +      if (DEBUG) debug("Registered " + topic + " target: " + target);
   1.312 +    },
   1.313 +
   1.314 +    _unregisterMessageTarget: function(topic, target) {
   1.315 +      if (topic == null) {
   1.316 +        // Unregister the target for every topic when no topic is specified.
   1.317 +        for (let type of this.topics) {
   1.318 +          this._unregisterMessageTarget(type, target);
   1.319 +        }
   1.320 +        return;
   1.321 +      }
   1.322 +
   1.323 +      // Unregister the target for a specified topic.
   1.324 +      let targets = this.targetsByTopic[topic];
   1.325 +      if (!targets) {
   1.326 +        return;
   1.327 +      }
   1.328 +
   1.329 +      let index = targets.indexOf(target);
   1.330 +      if (index != -1) {
   1.331 +        targets.splice(index, 1);
   1.332 +        if (DEBUG) debug("Unregistered " + topic + " target: " + target);
   1.333 +      }
   1.334 +    },
   1.335 +
   1.336 +    _enqueueTargetMessage: function(topic, message, options) {
   1.337 +      let msg = { topic : topic,
   1.338 +                  message : message,
   1.339 +                  options : options };
   1.340 +      // Remove previous queued message with the same message type and client Id
   1.341 +      // , only one message per (message type + client Id) is allowed in queue.
   1.342 +      let messageQueue = this.targetMessageQueue;
   1.343 +      for(let i = 0; i < messageQueue.length; i++) {
   1.344 +        if (messageQueue[i].message === message &&
   1.345 +            messageQueue[i].options.clientId === options.clientId) {
   1.346 +          messageQueue.splice(i, 1);
   1.347 +          break;
   1.348 +        }
   1.349 +      }
   1.350 +
   1.351 +      messageQueue.push(msg);
   1.352 +    },
   1.353 +
   1.354 +    _sendTargetMessage: function(topic, message, options) {
   1.355 +      if (!this.ready) {
   1.356 +        this._enqueueTargetMessage(topic, message, options);
   1.357 +        return;
   1.358 +      }
   1.359 +
   1.360 +      let targets = this.targetsByTopic[topic];
   1.361 +      if (!targets) {
   1.362 +        return;
   1.363 +      }
   1.364 +
   1.365 +      for (let target of targets) {
   1.366 +        target.sendAsyncMessage(message, options);
   1.367 +      }
   1.368 +    },
   1.369 +
   1.370 +    _resendQueuedTargetMessage: function() {
   1.371 +      this.ready = true;
   1.372 +
   1.373 +      // Here uses this._sendTargetMessage() to resend message, which will
   1.374 +      // enqueue message if listener is not ready.
   1.375 +      // So only resend after listener is ready, or it will cause infinate loop and
   1.376 +      // hang the system.
   1.377 +
   1.378 +      // Dequeue and resend messages.
   1.379 +      for each (let msg in this.targetMessageQueue) {
   1.380 +        this._sendTargetMessage(msg.topic, msg.message, msg.options);
   1.381 +      }
   1.382 +      this.targetMessageQueue = null;
   1.383 +    },
   1.384 +
   1.385 +    /**
   1.386 +     * nsIMessageListener interface methods.
   1.387 +     */
   1.388 +
   1.389 +    receiveMessage: function(msg) {
   1.390 +      if (DEBUG) debug("Received '" + msg.name + "' message from content process");
   1.391 +      if (msg.name == "child-process-shutdown") {
   1.392 +        // By the time we receive child-process-shutdown, the child process has
   1.393 +        // already forgotten its permissions so we need to unregister the target
   1.394 +        // for every permission.
   1.395 +        this._unregisterMessageTarget(null, msg.target);
   1.396 +        return null;
   1.397 +      }
   1.398 +
   1.399 +      if (RIL_IPC_MOBILECONNECTION_MSG_NAMES.indexOf(msg.name) != -1) {
   1.400 +        if (!msg.target.assertPermission("mobileconnection")) {
   1.401 +          if (DEBUG) {
   1.402 +            debug("MobileConnection message " + msg.name +
   1.403 +                  " from a content process with no 'mobileconnection' privileges.");
   1.404 +          }
   1.405 +          return null;
   1.406 +        }
   1.407 +      } else if (RIL_IPC_MOBILENETWORK_MSG_NAMES.indexOf(msg.name) != -1) {
   1.408 +        if (!msg.target.assertPermission("mobilenetwork")) {
   1.409 +          if (DEBUG) {
   1.410 +            debug("MobileNetwork message " + msg.name +
   1.411 +                  " from a content process with no 'mobilenetwork' privileges.");
   1.412 +          }
   1.413 +          return null;
   1.414 +        }
   1.415 +      } else if (RIL_IPC_ICCMANAGER_MSG_NAMES.indexOf(msg.name) != -1) {
   1.416 +        if (!msg.target.assertPermission("mobileconnection")) {
   1.417 +          if (DEBUG) {
   1.418 +            debug("IccManager message " + msg.name +
   1.419 +                  " from a content process with no 'mobileconnection' privileges.");
   1.420 +          }
   1.421 +          return null;
   1.422 +        }
   1.423 +      } else if (RIL_IPC_VOICEMAIL_MSG_NAMES.indexOf(msg.name) != -1) {
   1.424 +        if (!msg.target.assertPermission("voicemail")) {
   1.425 +          if (DEBUG) {
   1.426 +            debug("Voicemail message " + msg.name +
   1.427 +                  " from a content process with no 'voicemail' privileges.");
   1.428 +          }
   1.429 +          return null;
   1.430 +        }
   1.431 +      } else if (RIL_IPC_CELLBROADCAST_MSG_NAMES.indexOf(msg.name) != -1) {
   1.432 +        if (!msg.target.assertPermission("cellbroadcast")) {
   1.433 +          if (DEBUG) {
   1.434 +            debug("Cell Broadcast message " + msg.name +
   1.435 +                  " from a content process with no 'cellbroadcast' privileges.");
   1.436 +          }
   1.437 +          return null;
   1.438 +        }
   1.439 +      } else {
   1.440 +        if (DEBUG) debug("Ignoring unknown message type: " + msg.name);
   1.441 +        return null;
   1.442 +      }
   1.443 +
   1.444 +      switch (msg.name) {
   1.445 +        case "RIL:RegisterMobileConnectionMsg":
   1.446 +          this._registerMessageTarget("mobileconnection", msg.target);
   1.447 +          return null;
   1.448 +        case "RIL:RegisterIccMsg":
   1.449 +          this._registerMessageTarget("icc", msg.target);
   1.450 +          return null;
   1.451 +        case "RIL:RegisterVoicemailMsg":
   1.452 +          this._registerMessageTarget("voicemail", msg.target);
   1.453 +          return null;
   1.454 +        case "RIL:RegisterCellBroadcastMsg":
   1.455 +          this._registerMessageTarget("cellbroadcast", msg.target);
   1.456 +          return null;
   1.457 +      }
   1.458 +
   1.459 +      let clientId = msg.json.clientId || 0;
   1.460 +      let radioInterface = this.ril.getRadioInterface(clientId);
   1.461 +      if (!radioInterface) {
   1.462 +        if (DEBUG) debug("No such radio interface: " + clientId);
   1.463 +        return null;
   1.464 +      }
   1.465 +
   1.466 +      if (msg.name === "RIL:SetRadioEnabled") {
   1.467 +        // Special handler for SetRadioEnabled.
   1.468 +        return gRadioEnabledController.receiveMessage(msg);
   1.469 +      }
   1.470 +
   1.471 +      return radioInterface.receiveMessage(msg);
   1.472 +    },
   1.473 +
   1.474 +    /**
   1.475 +     * nsIObserver interface methods.
   1.476 +     */
   1.477 +
   1.478 +    observe: function(subject, topic, data) {
   1.479 +      switch (topic) {
   1.480 +        case kSysMsgListenerReadyObserverTopic:
   1.481 +          Services.obs.removeObserver(this, kSysMsgListenerReadyObserverTopic);
   1.482 +          this._resendQueuedTargetMessage();
   1.483 +          break;
   1.484 +        case NS_XPCOM_SHUTDOWN_OBSERVER_ID:
   1.485 +          this._shutdown();
   1.486 +          break;
   1.487 +      }
   1.488 +    },
   1.489 +
   1.490 +    sendMobileConnectionMessage: function(message, clientId, data) {
   1.491 +      this._sendTargetMessage("mobileconnection", message, {
   1.492 +        clientId: clientId,
   1.493 +        data: data
   1.494 +      });
   1.495 +    },
   1.496 +
   1.497 +    sendVoicemailMessage: function(message, clientId, data) {
   1.498 +      this._sendTargetMessage("voicemail", message, {
   1.499 +        clientId: clientId,
   1.500 +        data: data
   1.501 +      });
   1.502 +    },
   1.503 +
   1.504 +    sendCellBroadcastMessage: function(message, clientId, data) {
   1.505 +      this._sendTargetMessage("cellbroadcast", message, {
   1.506 +        clientId: clientId,
   1.507 +        data: data
   1.508 +      });
   1.509 +    },
   1.510 +
   1.511 +    sendIccMessage: function(message, clientId, data) {
   1.512 +      this._sendTargetMessage("icc", message, {
   1.513 +        clientId: clientId,
   1.514 +        data: data
   1.515 +      });
   1.516 +    }
   1.517 +  };
   1.518 +});
   1.519 +
   1.520 +XPCOMUtils.defineLazyGetter(this, "gRadioEnabledController", function() {
   1.521 +  let _ril = null;
   1.522 +  let _pendingMessages = [];  // For queueing "RIL =SetRadioEnabled" messages.
   1.523 +  let _isProcessingPending = false;
   1.524 +  let _timer = null;
   1.525 +  let _request = null;
   1.526 +  let _deactivatingDeferred = {};
   1.527 +  let _initializedCardState = {};
   1.528 +  let _allCardStateInitialized = !RILQUIRKS_RADIO_OFF_WO_CARD;
   1.529 +
   1.530 +  return {
   1.531 +    init: function(ril) {
   1.532 +      _ril = ril;
   1.533 +    },
   1.534 +
   1.535 +    receiveCardState: function(clientId) {
   1.536 +      if (_allCardStateInitialized) {
   1.537 +        return;
   1.538 +      }
   1.539 +
   1.540 +      if (DEBUG) debug("RadioControl: receive cardState from " + clientId);
   1.541 +      _initializedCardState[clientId] = true;
   1.542 +      if (Object.keys(_initializedCardState).length == _ril.numRadioInterfaces) {
   1.543 +        _allCardStateInitialized = true;
   1.544 +        this._startProcessingPending();
   1.545 +      }
   1.546 +    },
   1.547 +
   1.548 +    receiveMessage: function(msg) {
   1.549 +      if (DEBUG) debug("RadioControl: receiveMessage: " + JSON.stringify(msg));
   1.550 +      _pendingMessages.push(msg);
   1.551 +      this._startProcessingPending();
   1.552 +    },
   1.553 +
   1.554 +    isDeactivatingDataCalls: function() {
   1.555 +      return _request !== null;
   1.556 +    },
   1.557 +
   1.558 +    finishDeactivatingDataCalls: function(clientId) {
   1.559 +      if (DEBUG) debug("RadioControl: finishDeactivatingDataCalls: " + clientId);
   1.560 +      let deferred = _deactivatingDeferred[clientId];
   1.561 +      if (deferred) {
   1.562 +        deferred.resolve();
   1.563 +      }
   1.564 +    },
   1.565 +
   1.566 +    _startProcessingPending: function() {
   1.567 +      if (!_isProcessingPending) {
   1.568 +        if (DEBUG) debug("RadioControl: start dequeue");
   1.569 +        _isProcessingPending = true;
   1.570 +        this._processNextMessage();
   1.571 +      }
   1.572 +    },
   1.573 +
   1.574 +    _processNextMessage: function() {
   1.575 +      if (_pendingMessages.length === 0 || !_allCardStateInitialized) {
   1.576 +        if (DEBUG) debug("RadioControl: stop dequeue");
   1.577 +        _isProcessingPending = false;
   1.578 +        return;
   1.579 +      }
   1.580 +
   1.581 +      let msg = _pendingMessages.shift();
   1.582 +      this._handleMessage(msg);
   1.583 +    },
   1.584 +
   1.585 +    _getNumCards: function() {
   1.586 +      let numCards = 0;
   1.587 +      for (let i = 0, N = _ril.numRadioInterfaces; i < N; ++i) {
   1.588 +        if (this._isCardPresentAtClient(i)) {
   1.589 +          numCards++;
   1.590 +        }
   1.591 +      }
   1.592 +      return numCards;
   1.593 +    },
   1.594 +
   1.595 +    _isCardPresentAtClient: function(clientId) {
   1.596 +      let cardState = _ril.getRadioInterface(clientId).rilContext.cardState;
   1.597 +      return cardState !== RIL.GECKO_CARDSTATE_UNDETECTED &&
   1.598 +        cardState !== RIL.GECKO_CARDSTATE_UNKNOWN;
   1.599 +    },
   1.600 +
   1.601 +    _isRadioAbleToEnableAtClient: function(clientId, numCards) {
   1.602 +      if (!RILQUIRKS_RADIO_OFF_WO_CARD) {
   1.603 +        return true;
   1.604 +      }
   1.605 +
   1.606 +      // We could only turn on the radio for clientId if
   1.607 +      // 1. a SIM card is presented or
   1.608 +      // 2. it is the default clientId and there is no any SIM card at any client.
   1.609 +
   1.610 +      if (this._isCardPresentAtClient(clientId)) {
   1.611 +        return true;
   1.612 +      }
   1.613 +
   1.614 +      numCards = numCards == null ? this._getNumCards() : numCards;
   1.615 +      if (clientId === HW_DEFAULT_CLIENT_ID && numCards === 0) {
   1.616 +        return true;
   1.617 +      }
   1.618 +
   1.619 +      return false;
   1.620 +    },
   1.621 +
   1.622 +    _handleMessage: function(msg) {
   1.623 +      if (DEBUG) debug("RadioControl: handleMessage: " + JSON.stringify(msg));
   1.624 +      let clientId = msg.json.clientId || 0;
   1.625 +      let radioInterface = _ril.getRadioInterface(clientId);
   1.626 +
   1.627 +      if (!radioInterface.isValidStateForSetRadioEnabled()) {
   1.628 +        radioInterface.setRadioEnabledResponse(msg.target, msg.json.data,
   1.629 +                                               "InvalidStateError");
   1.630 +        this._processNextMessage();
   1.631 +        return;
   1.632 +      }
   1.633 +
   1.634 +      if (radioInterface.isDummyForSetRadioEnabled(msg.json.data)) {
   1.635 +        radioInterface.setRadioEnabledResponse(msg.target, msg.json.data);
   1.636 +        this._processNextMessage();
   1.637 +        return;
   1.638 +      }
   1.639 +
   1.640 +      if (msg.json.data.enabled) {
   1.641 +        if (this._isRadioAbleToEnableAtClient(clientId)) {
   1.642 +          radioInterface.receiveMessage(msg);
   1.643 +        } else {
   1.644 +          // Not really do it but respond success.
   1.645 +          radioInterface.setRadioEnabledResponse(msg.target, msg.json.data);
   1.646 +        }
   1.647 +
   1.648 +        this._processNextMessage();
   1.649 +      } else {
   1.650 +        _request = function() {
   1.651 +          radioInterface.receiveMessage(msg);
   1.652 +        };
   1.653 +
   1.654 +        // In 2G network, modem takes 35+ seconds to process deactivate data
   1.655 +        // call request if device has active voice call (please see bug 964974
   1.656 +        // for more details). Therefore we should hangup all active voice calls
   1.657 +        // first. And considering some DSDS architecture, toggling one radio may
   1.658 +        // toggle both, so we send hangUpAll to all clients.
   1.659 +        for (let i = 0, N = _ril.numRadioInterfaces; i < N; ++i) {
   1.660 +          let iface = _ril.getRadioInterface(i);
   1.661 +          iface.workerMessenger.send("hangUpAll");
   1.662 +        }
   1.663 +
   1.664 +        // In some DSDS architecture with only one modem, toggling one radio may
   1.665 +        // toggle both. Therefore, for safely turning off, we should first
   1.666 +        // explicitly deactivate all data calls from all clients.
   1.667 +        this._deactivateDataCalls().then(() => {
   1.668 +          if (DEBUG) debug("RadioControl: deactivation done");
   1.669 +          this._executeRequest();
   1.670 +        });
   1.671 +
   1.672 +        this._createTimer();
   1.673 +      }
   1.674 +    },
   1.675 +
   1.676 +    _deactivateDataCalls: function() {
   1.677 +      if (DEBUG) debug("RadioControl: deactivating data calls...");
   1.678 +      _deactivatingDeferred = {};
   1.679 +
   1.680 +      let promise = Promise.resolve();
   1.681 +      for (let i = 0, N = _ril.numRadioInterfaces; i < N; ++i) {
   1.682 +        promise = promise.then(this._deactivateDataCallsForClient(i));
   1.683 +      }
   1.684 +
   1.685 +      return promise;
   1.686 +    },
   1.687 +
   1.688 +    _deactivateDataCallsForClient: function(clientId) {
   1.689 +      return function() {
   1.690 +        let deferred = _deactivatingDeferred[clientId] = Promise.defer();
   1.691 +        let dataConnectionHandler = gDataConnectionManager.getConnectionHandler(clientId);
   1.692 +        dataConnectionHandler.deactivateDataCalls();
   1.693 +        return deferred.promise;
   1.694 +      };
   1.695 +    },
   1.696 +
   1.697 +    _createTimer: function() {
   1.698 +      if (!_timer) {
   1.699 +        _timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
   1.700 +      }
   1.701 +      _timer.initWithCallback(this._executeRequest.bind(this),
   1.702 +                              RADIO_POWER_OFF_TIMEOUT,
   1.703 +                              Ci.nsITimer.TYPE_ONE_SHOT);
   1.704 +    },
   1.705 +
   1.706 +    _cancelTimer: function() {
   1.707 +      if (_timer) {
   1.708 +        _timer.cancel();
   1.709 +      }
   1.710 +    },
   1.711 +
   1.712 +    _executeRequest: function() {
   1.713 +      if (typeof _request === "function") {
   1.714 +        if (DEBUG) debug("RadioControl: executeRequest");
   1.715 +        this._cancelTimer();
   1.716 +        _request();
   1.717 +        _request = null;
   1.718 +      }
   1.719 +      this._processNextMessage();
   1.720 +    },
   1.721 +  };
   1.722 +});
   1.723 +
   1.724 +XPCOMUtils.defineLazyGetter(this, "gDataConnectionManager", function () {
   1.725 +  return {
   1.726 +    QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
   1.727 +                                           Ci.nsISettingsServiceCallback]),
   1.728 +
   1.729 +    _connectionHandlers: null,
   1.730 +
   1.731 +    // Flag to determine the data state to start with when we boot up. It
   1.732 +    // corresponds to the 'ril.data.enabled' setting from the UI.
   1.733 +    _dataEnabled: false,
   1.734 +
   1.735 +    // Flag to record the default client id for data call. It corresponds to
   1.736 +    // the 'ril.data.defaultServiceId' setting from the UI.
   1.737 +    _dataDefaultClientId: -1,
   1.738 +
   1.739 +    // Flag to record the current default client id for data call.
   1.740 +    // It differs from _dataDefaultClientId in that it is set only when
   1.741 +    // the switch of client id process is done.
   1.742 +    _currentDataClientId: -1,
   1.743 +
   1.744 +    // Pending function to execute when we are notified that another data call has
   1.745 +    // been disconnected.
   1.746 +    _pendingDataCallRequest: null,
   1.747 +
   1.748 +    debug: function(s) {
   1.749 +      dump("-*- DataConnectionManager: " + s + "\n");
   1.750 +    },
   1.751 +
   1.752 +    init: function(ril) {
   1.753 +      if (!ril) {
   1.754 +        return;
   1.755 +      }
   1.756 +
   1.757 +      this._connectionHandlers = [];
   1.758 +      for (let clientId = 0; clientId < ril.numRadioInterfaces; clientId++) {
   1.759 +        let radioInterface = ril.getRadioInterface(clientId);
   1.760 +        this._connectionHandlers.push(
   1.761 +          new DataConnectionHandler(clientId, radioInterface));
   1.762 +      }
   1.763 +
   1.764 +      let lock = gSettingsService.createLock();
   1.765 +      // Read the APN data from the settings DB.
   1.766 +      lock.get("ril.data.apnSettings", this);
   1.767 +      // Read the data enabled setting from DB.
   1.768 +      lock.get("ril.data.enabled", this);
   1.769 +      lock.get("ril.data.roaming_enabled", this);
   1.770 +      // Read the default client id for data call.
   1.771 +      lock.get("ril.data.defaultServiceId", this);
   1.772 +
   1.773 +      Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
   1.774 +      Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false);
   1.775 +      Services.obs.addObserver(this, kNetworkInterfaceStateChangedTopic, false);
   1.776 +    },
   1.777 +
   1.778 +    getConnectionHandler: function(clientId) {
   1.779 +      return this._connectionHandlers[clientId];
   1.780 +    },
   1.781 +
   1.782 +    _handleDataClientIdChange: function(newDefault) {
   1.783 +      if (this._dataDefaultClientId === newDefault) {
   1.784 +         return;
   1.785 +      }
   1.786 +      this._dataDefaultClientId = newDefault;
   1.787 +
   1.788 +      if (this._currentDataClientId == -1) {
   1.789 +        // This is to handle boot up stage.
   1.790 +        this._currentDataClientId = this._dataDefaultClientId;
   1.791 +        let connHandler = this._connectionHandlers[this._currentDataClientId];
   1.792 +        let radioInterface = connHandler.radioInterface;
   1.793 +        if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND) {
   1.794 +          radioInterface.setDataRegistration(true);
   1.795 +        }
   1.796 +        if (this._dataEnabled) {
   1.797 +          let settings = connHandler.dataCallSettings;
   1.798 +          settings.oldEnabled = settings.enabled;
   1.799 +          settings.enabled = true;
   1.800 +          connHandler.updateRILNetworkInterface();
   1.801 +        }
   1.802 +        return;
   1.803 +      }
   1.804 +
   1.805 +      let oldConnHandler = this._connectionHandlers[this._currentDataClientId];
   1.806 +      let oldIface = oldConnHandler.radioInterface;
   1.807 +      let oldSettings = oldConnHandler.dataCallSettings;
   1.808 +      let newConnHandler = this._connectionHandlers[this._dataDefaultClientId];
   1.809 +      let newIface = newConnHandler.radioInterface;
   1.810 +      let newSettings = newConnHandler.dataCallSettings;
   1.811 +
   1.812 +      if (!this._dataEnabled) {
   1.813 +        if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND) {
   1.814 +          oldIface.setDataRegistration(false);
   1.815 +          newIface.setDataRegistration(true);
   1.816 +        }
   1.817 +        this._currentDataClientId = this._dataDefaultClientId;
   1.818 +        return;
   1.819 +      }
   1.820 +
   1.821 +      oldSettings.oldEnabled = oldSettings.enabled;
   1.822 +      oldSettings.enabled = false;
   1.823 +
   1.824 +      if (oldConnHandler.anyDataConnected()) {
   1.825 +        this._pendingDataCallRequest = function () {
   1.826 +          if (DEBUG) {
   1.827 +            this.debug("Executing pending data call request.");
   1.828 +          }
   1.829 +          if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND) {
   1.830 +            newIface.setDataRegistration(true);
   1.831 +          }
   1.832 +          newSettings.oldEnabled = newSettings.enabled;
   1.833 +          newSettings.enabled = this._dataEnabled;
   1.834 +
   1.835 +          this._currentDataClientId = this._dataDefaultClientId;
   1.836 +          newConnHandler.updateRILNetworkInterface();
   1.837 +        };
   1.838 +
   1.839 +        if (DEBUG) {
   1.840 +          this.debug("_handleDataClientIdChange: existing data call(s) active" +
   1.841 +                     ", wait for them to get disconnected.");
   1.842 +        }
   1.843 +        oldConnHandler.deactivateDataCalls();
   1.844 +        return;
   1.845 +      }
   1.846 +
   1.847 +      newSettings.oldEnabled = newSettings.enabled;
   1.848 +      newSettings.enabled = true;
   1.849 +
   1.850 +      this._currentDataClientId = this._dataDefaultClientId;
   1.851 +      if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND) {
   1.852 +        oldIface.setDataRegistration(false);
   1.853 +        newIface.setDataRegistration(true);
   1.854 +      }
   1.855 +      newConnHandler.updateRILNetworkInterface();
   1.856 +    },
   1.857 +
   1.858 +    _shutdown: function() {
   1.859 +      for (let handler of this._connectionHandlers) {
   1.860 +        handler.shutdown();
   1.861 +      }
   1.862 +      this._connectionHandlers = null;
   1.863 +      Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
   1.864 +      Services.obs.removeObserver(this, kMozSettingsChangedObserverTopic);
   1.865 +      Services.obs.removeObserver(this, kNetworkInterfaceStateChangedTopic);
   1.866 +    },
   1.867 +
   1.868 +    /**
   1.869 +     * nsISettingsServiceCallback
   1.870 +     */
   1.871 +    handle: function(name, result) {
   1.872 +      switch(name) {
   1.873 +        case "ril.data.apnSettings":
   1.874 +          if (DEBUG) {
   1.875 +            this.debug("'ril.data.apnSettings' is now " +
   1.876 +                       JSON.stringify(result));
   1.877 +          }
   1.878 +          if (!result) {
   1.879 +            break;
   1.880 +          }
   1.881 +          for (let clientId in this._connectionHandlers) {
   1.882 +            let handler = this._connectionHandlers[clientId];
   1.883 +            let apnSetting = result[clientId];
   1.884 +            if (handler && apnSetting) {
   1.885 +              handler.updateApnSettings(apnSetting);
   1.886 +              handler.updateRILNetworkInterface();
   1.887 +            }
   1.888 +          }
   1.889 +          break;
   1.890 +        case "ril.data.enabled":
   1.891 +          if (DEBUG) {
   1.892 +            this.debug("'ril.data.enabled' is now " + result);
   1.893 +          }
   1.894 +          if (this._dataEnabled === result) {
   1.895 +            break;
   1.896 +          }
   1.897 +          this._dataEnabled = result;
   1.898 +
   1.899 +          if (DEBUG) {
   1.900 +            this.debug("Default id for data call: " + this._dataDefaultClientId);
   1.901 +          }
   1.902 +          if (this._dataDefaultClientId === -1) {
   1.903 +            // We haven't got the default id for data from db.
   1.904 +            break;
   1.905 +          }
   1.906 +
   1.907 +          let connHandler = this._connectionHandlers[this._dataDefaultClientId];
   1.908 +          let settings = connHandler.dataCallSettings;
   1.909 +          settings.oldEnabled = settings.enabled;
   1.910 +          settings.enabled = result;
   1.911 +          connHandler.updateRILNetworkInterface();
   1.912 +          break;
   1.913 +        case "ril.data.roaming_enabled":
   1.914 +          if (DEBUG) {
   1.915 +            this.debug("'ril.data.roaming_enabled' is now " + result);
   1.916 +            this.debug("Default id for data call: " + this._dataDefaultClientId);
   1.917 +          }
   1.918 +          for (let clientId = 0; clientId < this._connectionHandlers.length; clientId++) {
   1.919 +            let connHandler = this._connectionHandlers[clientId];
   1.920 +            let settings = connHandler.dataCallSettings;
   1.921 +            settings.roamingEnabled = Array.isArray(result) ? result[clientId] : result;
   1.922 +          }
   1.923 +          if (this._dataDefaultClientId === -1) {
   1.924 +            // We haven't got the default id for data from db.
   1.925 +            break;
   1.926 +          }
   1.927 +          this._connectionHandlers[this._dataDefaultClientId].updateRILNetworkInterface();
   1.928 +          break;
   1.929 +        case "ril.data.defaultServiceId":
   1.930 +          result = result || 0;
   1.931 +          if (DEBUG) {
   1.932 +            this.debug("'ril.data.defaultServiceId' is now " + result);
   1.933 +          }
   1.934 +          this._handleDataClientIdChange(result);
   1.935 +          break;
   1.936 +      }
   1.937 +    },
   1.938 +
   1.939 +    handleError: function(errorMessage) {
   1.940 +      if (DEBUG) {
   1.941 +        this.debug("There was an error while reading RIL settings.");
   1.942 +      }
   1.943 +    },
   1.944 +
   1.945 +    /**
   1.946 +     * nsIObserver interface methods.
   1.947 +     */
   1.948 +    observe: function(subject, topic, data) {
   1.949 +      switch (topic) {
   1.950 +        case kMozSettingsChangedObserverTopic:
   1.951 +          let setting = JSON.parse(data);
   1.952 +          this.handle(setting.key, setting.value);
   1.953 +          break;
   1.954 +        case kNetworkInterfaceStateChangedTopic:
   1.955 +          let network = subject.QueryInterface(Ci.nsINetworkInterface);
   1.956 +          // DSDS: setup pending data connection when switching the default id
   1.957 +          // for data call. We can not use network.type to tell if it's
   1.958 +          // NETWORK_TYPE_MOBILE, since the type is removed from
   1.959 +          // RILNetworkInterface.connectedTypes on disconnect().
   1.960 +          if (network.state == Ci.nsINetworkInterface.NETWORK_STATE_UNKNOWN) {
   1.961 +            let connHandler = this._connectionHandlers[this._currentDataClientId];
   1.962 +            let radioInterface = connHandler.radioInterface;
   1.963 +            if (connHandler.allDataDisconnected() &&
   1.964 +                typeof this._pendingDataCallRequest === "function") {
   1.965 +              if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND) {
   1.966 +                radioInterface.setDataRegistration(false);
   1.967 +              }
   1.968 +              if (DEBUG) {
   1.969 +                this.debug("All data calls disconnected, setup pending data call.");
   1.970 +              }
   1.971 +              this._pendingDataCallRequest();
   1.972 +              this._pendingDataCallRequest = null;
   1.973 +            }
   1.974 +          }
   1.975 +          break;
   1.976 +        case NS_XPCOM_SHUTDOWN_OBSERVER_ID:
   1.977 +          this._shutdown();
   1.978 +          break;
   1.979 +      }
   1.980 +    },
   1.981 +  };
   1.982 +});
   1.983 +
   1.984 +// Initialize shared preference "ril.numRadioInterfaces" according to system
   1.985 +// property.
   1.986 +try {
   1.987 +  Services.prefs.setIntPref(kPrefRilNumRadioInterfaces, (function() {
   1.988 +    // When Gonk property "ro.moz.ril.numclients" is not set, return 1; if
   1.989 +    // explicitly set to any number larger-equal than 0, return num; else, return
   1.990 +    // 1 for compatibility.
   1.991 +    try {
   1.992 +      let numString = libcutils.property_get("ro.moz.ril.numclients", "1");
   1.993 +      let num = parseInt(numString, 10);
   1.994 +      if (num >= 0) {
   1.995 +        return num;
   1.996 +      }
   1.997 +    } catch (e) {}
   1.998 +
   1.999 +    return 1;
  1.1000 +  })());
  1.1001 +} catch (e) {}
  1.1002 +
  1.1003 +function IccInfo() {}
  1.1004 +IccInfo.prototype = {
  1.1005 +  iccType: null,
  1.1006 +  iccid: null,
  1.1007 +  mcc: null,
  1.1008 +  mnc: null,
  1.1009 +  spn: null,
  1.1010 +  isDisplayNetworkNameRequired: null,
  1.1011 +  isDisplaySpnRequired: null
  1.1012 +};
  1.1013 +
  1.1014 +function GsmIccInfo() {}
  1.1015 +GsmIccInfo.prototype = {
  1.1016 +  __proto__: IccInfo.prototype,
  1.1017 +  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMMozGsmIccInfo]),
  1.1018 +  classID: GSMICCINFO_CID,
  1.1019 +  classInfo: XPCOMUtils.generateCI({
  1.1020 +    classID:          GSMICCINFO_CID,
  1.1021 +    classDescription: "MozGsmIccInfo",
  1.1022 +    flags:            Ci.nsIClassInfo.DOM_OBJECT,
  1.1023 +    interfaces:       [Ci.nsIDOMMozGsmIccInfo]
  1.1024 +  }),
  1.1025 +
  1.1026 +  // nsIDOMMozGsmIccInfo
  1.1027 +
  1.1028 +  msisdn: null
  1.1029 +};
  1.1030 +
  1.1031 +function CdmaIccInfo() {}
  1.1032 +CdmaIccInfo.prototype = {
  1.1033 +  __proto__: IccInfo.prototype,
  1.1034 +  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMMozCdmaIccInfo]),
  1.1035 +  classID: CDMAICCINFO_CID,
  1.1036 +  classInfo: XPCOMUtils.generateCI({
  1.1037 +    classID:          CDMAICCINFO_CID,
  1.1038 +    classDescription: "MozCdmaIccInfo",
  1.1039 +    flags:            Ci.nsIClassInfo.DOM_OBJECT,
  1.1040 +    interfaces:       [Ci.nsIDOMMozCdmaIccInfo]
  1.1041 +  }),
  1.1042 +
  1.1043 +  // nsIDOMMozCdmaIccInfo
  1.1044 +
  1.1045 +  mdn: null,
  1.1046 +  prlVersion: 0
  1.1047 +};
  1.1048 +
  1.1049 +function DataConnectionHandler(clientId, radioInterface) {
  1.1050 +  // Initial owning attributes.
  1.1051 +  this.clientId = clientId;
  1.1052 +  this.radioInterface = radioInterface;
  1.1053 +  this.dataCallSettings = {
  1.1054 +    oldEnabled: false,
  1.1055 +    enabled: false,
  1.1056 +    roamingEnabled: false
  1.1057 +  };
  1.1058 +  this._dataCallbacks = [];
  1.1059 +
  1.1060 +  // This matrix is used to keep all the APN settings.
  1.1061 +  //   - |byApn| object makes it easier to get the corresponding APN setting
  1.1062 +  //     via a given set of APN, user name and password.
  1.1063 +  //   - |byType| object makes it easier to get the corresponding APN setting
  1.1064 +  //     via a given APN type.
  1.1065 +  this.apnSettings = {
  1.1066 +    byType: {},
  1.1067 +    byApn: {}
  1.1068 +  };
  1.1069 +}
  1.1070 +DataConnectionHandler.prototype = {
  1.1071 +  clientId: 0,
  1.1072 +  radioInterface: null,
  1.1073 +  // Data calls setting.
  1.1074 +  dataCallSettings: null,
  1.1075 +  apnSettings: null,
  1.1076 +
  1.1077 +  // Apn settings to be setup after data call are cleared.
  1.1078 +  _pendingApnSettings: null,
  1.1079 +
  1.1080 +  debug: function(s) {
  1.1081 +    dump("-*- DataConnectionHandler[" + this.clientId + "]: " + s + "\n");
  1.1082 +  },
  1.1083 +
  1.1084 +  shutdown: function() {
  1.1085 +    // Shutdown all RIL network interfaces
  1.1086 +    for (let [, apnSetting] of Iterator(this.apnSettings.byApn)) {
  1.1087 +      if (apnSetting.iface) {
  1.1088 +        apnSetting.iface.shutdown();
  1.1089 +      }
  1.1090 +    }
  1.1091 +    this.clientId = null;
  1.1092 +    this.radioInterface = null;
  1.1093 +  },
  1.1094 +
  1.1095 +  /**
  1.1096 +   * Check if we get all necessary APN data.
  1.1097 +   */
  1.1098 +  _validateApnSetting: function(apnSetting) {
  1.1099 +    return (apnSetting &&
  1.1100 +            apnSetting.apn &&
  1.1101 +            apnSetting.types &&
  1.1102 +            apnSetting.types.length);
  1.1103 +  },
  1.1104 +
  1.1105 +  _deliverDataCallCallback: function(name, args) {
  1.1106 +    // We need to worry about callback registration state mutations during the
  1.1107 +    // callback firing. The behaviour we want is to *not* call any callbacks
  1.1108 +    // that are added during the firing and to *not* call any callbacks that are
  1.1109 +    // removed during the firing. To address this, we make a copy of the
  1.1110 +    // callback list before dispatching and then double-check that each callback
  1.1111 +    // is still registered before calling it.
  1.1112 +    let callbacks = this._dataCallbacks.slice();
  1.1113 +    for (let callback of callbacks) {
  1.1114 +      if (this._dataCallbacks.indexOf(callback) == -1) {
  1.1115 +        continue;
  1.1116 +      }
  1.1117 +      try {
  1.1118 +        let handler = callback[name];
  1.1119 +        if (typeof handler !== "function") {
  1.1120 +          throw new Error("No handler for " + name);
  1.1121 +        }
  1.1122 +        handler.apply(callback, args);
  1.1123 +      } catch (e) {
  1.1124 +        if (DEBUG) {
  1.1125 +          this.debug("callback handler for " + name + " threw an exception: " + e);
  1.1126 +        }
  1.1127 +      }
  1.1128 +    }
  1.1129 +  },
  1.1130 +
  1.1131 +  /**
  1.1132 +   * This function will do the following steps:
  1.1133 +   *   1. Clear the cached APN settings in the RIL.
  1.1134 +   *   2. Combine APN, user name, and password as the key of |byApn| object to
  1.1135 +   *      refer to the corresponding APN setting.
  1.1136 +   *   3. Use APN type as the index of |byType| object to refer to the
  1.1137 +   *      corresponding APN setting.
  1.1138 +   *   4. Create RilNetworkInterface for each APN setting created at step 2.
  1.1139 +   */
  1.1140 +  _setupApnSettings: function(newApnSettings) {
  1.1141 +    if (!newApnSettings) {
  1.1142 +      return;
  1.1143 +    }
  1.1144 +    if (DEBUG) this.debug("setupApnSettings: " + JSON.stringify(newApnSettings));
  1.1145 +
  1.1146 +    // Unregister anything from iface and delete it.
  1.1147 +    for (let [, apnSetting] in Iterator(this.apnSettings.byApn)) {
  1.1148 +      if (apnSetting.iface.name in gNetworkManager.networkInterfaces) {
  1.1149 +        gNetworkManager.unregisterNetworkInterface(apnSetting.iface);
  1.1150 +      }
  1.1151 +      this.unregisterDataCallCallback(apnSetting.iface);
  1.1152 +      delete apnSetting.iface;
  1.1153 +    }
  1.1154 +    this.apnSettings.byApn = {};
  1.1155 +    this.apnSettings.byType = {};
  1.1156 +
  1.1157 +    // Cache the APN settings by APNs and by types in the RIL.
  1.1158 +    for (let inputApnSetting of newApnSettings) {
  1.1159 +      if (!this._validateApnSetting(inputApnSetting)) {
  1.1160 +        continue;
  1.1161 +      }
  1.1162 +
  1.1163 +      // Combine APN, user name, and password as the key of |byApn| object to
  1.1164 +      // refer to the corresponding APN setting.
  1.1165 +      let apnKey = inputApnSetting.apn +
  1.1166 +                   (inputApnSetting.user || "") +
  1.1167 +                   (inputApnSetting.password || "");
  1.1168 +
  1.1169 +      if (!this.apnSettings.byApn[apnKey]) {
  1.1170 +        this.apnSettings.byApn[apnKey] = inputApnSetting;
  1.1171 +      } else {
  1.1172 +        this.apnSettings.byApn[apnKey].types =
  1.1173 +          this.apnSettings.byApn[apnKey].types.concat(inputApnSetting.types);
  1.1174 +      }
  1.1175 +
  1.1176 +      // Use APN type as the index of |byType| object to refer to the
  1.1177 +      // corresponding APN setting.
  1.1178 +      for (let type of inputApnSetting.types) {
  1.1179 +        this.apnSettings.byType[type] = this.apnSettings.byApn[apnKey];
  1.1180 +      }
  1.1181 +    }
  1.1182 +
  1.1183 +    // Create RilNetworkInterface for each APN setting that just cached.
  1.1184 +    for (let [, apnSetting] in Iterator(this.apnSettings.byApn)) {
  1.1185 +      apnSetting.iface = new RILNetworkInterface(this, apnSetting);
  1.1186 +    }
  1.1187 +  },
  1.1188 +
  1.1189 +  /**
  1.1190 +   * Check if all data is disconnected.
  1.1191 +   */
  1.1192 +  allDataDisconnected: function() {
  1.1193 +    for (let [, apnSetting] of Iterator(this.apnSettings.byApn)) {
  1.1194 +      let iface = apnSetting.iface;
  1.1195 +      if (iface && iface.state != RIL.GECKO_NETWORK_STATE_UNKNOWN &&
  1.1196 +          iface.state != RIL.GECKO_NETWORK_STATE_DISCONNECTED) {
  1.1197 +        return false;
  1.1198 +      }
  1.1199 +    }
  1.1200 +    return true;
  1.1201 +  },
  1.1202 +
  1.1203 +  /**
  1.1204 +   * Check if there is any activated data connection.
  1.1205 +   */
  1.1206 +  anyDataConnected: function() {
  1.1207 +    for (let [, apnSetting] of Iterator(this.apnSettings.byApn)) {
  1.1208 +      let iface = apnSetting.iface;
  1.1209 +      if (iface && iface.state == RIL.GECKO_NETWORK_STATE_CONNECTED) {
  1.1210 +        return true;
  1.1211 +      }
  1.1212 +    }
  1.1213 +    return false;
  1.1214 +  },
  1.1215 +
  1.1216 +  updateApnSettings: function(newApnSettings) {
  1.1217 +    if (!newApnSettings) {
  1.1218 +      return;
  1.1219 +    }
  1.1220 +    if (this._pendingApnSettings) {
  1.1221 +      // Change of apn settings in process, just update to the newest.
  1.1222 +      this._pengingApnSettings = newApnSettings;
  1.1223 +      return;
  1.1224 +    }
  1.1225 +
  1.1226 +    let isDeactivatingDataCalls = false;
  1.1227 +    // Clear the cached APN settings in the RIL.
  1.1228 +    for (let [, apnSetting] of Iterator(this.apnSettings.byApn)) {
  1.1229 +      // Clear all existing connections based on APN types.
  1.1230 +      for (let type of apnSetting.types) {
  1.1231 +        if (this.getDataCallStateByType(type) ==
  1.1232 +            RIL.GECKO_NETWORK_STATE_CONNECTED) {
  1.1233 +          this.deactivateDataCallByType(type);
  1.1234 +          isDeactivatingDataCalls = true;
  1.1235 +        }
  1.1236 +      }
  1.1237 +    }
  1.1238 +    if (isDeactivatingDataCalls) {
  1.1239 +      // Defer apn settings setup until all data calls are cleared.
  1.1240 +      this._pendingApnSettings = newApnSettings;
  1.1241 +      return;
  1.1242 +    }
  1.1243 +    this._setupApnSettings(newApnSettings);
  1.1244 +  },
  1.1245 +
  1.1246 +  updateRILNetworkInterface: function() {
  1.1247 +    let apnSetting = this.apnSettings.byType.default;
  1.1248 +    if (!this._validateApnSetting(apnSetting)) {
  1.1249 +      if (DEBUG) {
  1.1250 +        this.debug("We haven't gotten completely the APN data.");
  1.1251 +      }
  1.1252 +      return;
  1.1253 +    }
  1.1254 +
  1.1255 +    // This check avoids data call connection if the radio is not ready
  1.1256 +    // yet after toggling off airplane mode.
  1.1257 +    let rilContext = this.radioInterface.rilContext;
  1.1258 +    if (rilContext.radioState != RIL.GECKO_RADIOSTATE_READY) {
  1.1259 +      if (DEBUG) {
  1.1260 +        this.debug("RIL is not ready for data connection: radio's not ready");
  1.1261 +      }
  1.1262 +      return;
  1.1263 +    }
  1.1264 +
  1.1265 +    // We only watch at "ril.data.enabled" flag changes for connecting or
  1.1266 +    // disconnecting the data call. If the value of "ril.data.enabled" is
  1.1267 +    // true and any of the remaining flags change the setting application
  1.1268 +    // should turn this flag to false and then to true in order to reload
  1.1269 +    // the new values and reconnect the data call.
  1.1270 +    if (this.dataCallSettings.oldEnabled === this.dataCallSettings.enabled) {
  1.1271 +      if (DEBUG) {
  1.1272 +        this.debug("No changes for ril.data.enabled flag. Nothing to do.");
  1.1273 +      }
  1.1274 +      return;
  1.1275 +    }
  1.1276 +
  1.1277 +    let defaultDataCallState = this.getDataCallStateByType("default");
  1.1278 +    if (defaultDataCallState == RIL.GECKO_NETWORK_STATE_CONNECTING ||
  1.1279 +        defaultDataCallState == RIL.GECKO_NETWORK_STATE_DISCONNECTING) {
  1.1280 +      if (DEBUG) {
  1.1281 +        this.debug("Nothing to do during connecting/disconnecting in progress.");
  1.1282 +      }
  1.1283 +      return;
  1.1284 +    }
  1.1285 +
  1.1286 +    let dataInfo = rilContext.data;
  1.1287 +    let isRegistered =
  1.1288 +      dataInfo.state == RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED;
  1.1289 +    let haveDataConnection =
  1.1290 +      dataInfo.type != RIL.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN;
  1.1291 +    if (!isRegistered || !haveDataConnection) {
  1.1292 +      if (DEBUG) {
  1.1293 +        this.debug("RIL is not ready for data connection: Phone's not " +
  1.1294 +                   "registered or doesn't have data connection.");
  1.1295 +      }
  1.1296 +      return;
  1.1297 +    }
  1.1298 +    let wifi_active = false;
  1.1299 +    if (gNetworkManager.active &&
  1.1300 +        gNetworkManager.active.type == Ci.nsINetworkInterface.NETWORK_TYPE_WIFI) {
  1.1301 +      wifi_active = true;
  1.1302 +    }
  1.1303 +
  1.1304 +    let defaultDataCallConnected = defaultDataCallState ==
  1.1305 +                                   RIL.GECKO_NETWORK_STATE_CONNECTED;
  1.1306 +    if (defaultDataCallConnected &&
  1.1307 +        (!this.dataCallSettings.enabled ||
  1.1308 +         (dataInfo.roaming && !this.dataCallSettings.roamingEnabled))) {
  1.1309 +      if (DEBUG) {
  1.1310 +        this.debug("Data call settings: disconnect data call.");
  1.1311 +      }
  1.1312 +      this.deactivateDataCallByType("default");
  1.1313 +      return;
  1.1314 +    }
  1.1315 +
  1.1316 +    if (defaultDataCallConnected && wifi_active) {
  1.1317 +      if (DEBUG) {
  1.1318 +        this.debug("Disconnect data call when Wifi is connected.");
  1.1319 +      }
  1.1320 +      this.deactivateDataCallByType("default");
  1.1321 +      return;
  1.1322 +    }
  1.1323 +
  1.1324 +    if (!this.dataCallSettings.enabled || defaultDataCallConnected) {
  1.1325 +      if (DEBUG) {
  1.1326 +        this.debug("Data call settings: nothing to do.");
  1.1327 +      }
  1.1328 +      return;
  1.1329 +    }
  1.1330 +    if (dataInfo.roaming && !this.dataCallSettings.roamingEnabled) {
  1.1331 +      if (DEBUG) {
  1.1332 +        this.debug("We're roaming, but data roaming is disabled.");
  1.1333 +      }
  1.1334 +      return;
  1.1335 +    }
  1.1336 +    if (wifi_active) {
  1.1337 +      if (DEBUG) {
  1.1338 +        this.debug("Don't connect data call when Wifi is connected.");
  1.1339 +      }
  1.1340 +      return;
  1.1341 +    }
  1.1342 +    if (this._pendingApnSettings) {
  1.1343 +      if (DEBUG) this.debug("We're changing apn settings, ignore any changes.");
  1.1344 +      return;
  1.1345 +    }
  1.1346 +
  1.1347 +    let detailedRadioState = rilContext.detailedRadioState;
  1.1348 +    if (gRadioEnabledController.isDeactivatingDataCalls() ||
  1.1349 +        detailedRadioState == RIL.GECKO_DETAILED_RADIOSTATE_ENABLING ||
  1.1350 +        detailedRadioState == RIL.GECKO_DETAILED_RADIOSTATE_DISABLING) {
  1.1351 +      // We're changing the radio power currently, ignore any changes.
  1.1352 +      return;
  1.1353 +    }
  1.1354 +
  1.1355 +    if (DEBUG) {
  1.1356 +      this.debug("Data call settings: connect data call.");
  1.1357 +    }
  1.1358 +    this.setupDataCallByType("default");
  1.1359 +  },
  1.1360 +
  1.1361 +  getDataCallStateByType: function(apnType) {
  1.1362 +    let apnSetting = this.apnSettings.byType[apnType];
  1.1363 +    if (!apnSetting) {
  1.1364 +       return RIL.GECKO_NETWORK_STATE_UNKNOWN;
  1.1365 +    }
  1.1366 +    if (!apnSetting.iface.inConnectedTypes(apnType)) {
  1.1367 +      return RIL.GECKO_NETWORK_STATE_DISCONNECTED;
  1.1368 +    }
  1.1369 +    return apnSetting.iface.state;
  1.1370 +  },
  1.1371 +
  1.1372 +  setupDataCallByType: function(apnType) {
  1.1373 +    if (DEBUG) {
  1.1374 +      this.debug("setupDataCallByType: " + apnType);
  1.1375 +    }
  1.1376 +    let apnSetting = this.apnSettings.byType[apnType];
  1.1377 +    if (!apnSetting) {
  1.1378 +      if (DEBUG) {
  1.1379 +        this.debug("No apn setting for type: " + apnType);
  1.1380 +      }
  1.1381 +      return;
  1.1382 +    }
  1.1383 +
  1.1384 +    let dataInfo = this.radioInterface.rilContext.data;
  1.1385 +    if (dataInfo.state != RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED ||
  1.1386 +        dataInfo.type == RIL.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN) {
  1.1387 +      return;
  1.1388 +    }
  1.1389 +
  1.1390 +    apnSetting.iface.connect(apnType);
  1.1391 +    // We just call connect() function, so this interface should be in
  1.1392 +    // connecting state. If this interface is already in connected state, we
  1.1393 +    // are sure that this interface have successfully established connection
  1.1394 +    // for other data call types before we call connect() function for current
  1.1395 +    // data call type. In this circumstance, we have to directly update the
  1.1396 +    // necessary data call and interface information to RILContentHelper
  1.1397 +    // and network manager for current data call type.
  1.1398 +    if (apnSetting.iface.connected) {
  1.1399 +      // Update the interface status via-registration if the interface has
  1.1400 +      // already been registered in the network manager.
  1.1401 +      if (apnSetting.iface.name in gNetworkManager.networkInterfaces) {
  1.1402 +        gNetworkManager.unregisterNetworkInterface(apnSetting.iface);
  1.1403 +      }
  1.1404 +      gNetworkManager.registerNetworkInterface(apnSetting.iface);
  1.1405 +
  1.1406 +      Services.obs.notifyObservers(apnSetting.iface,
  1.1407 +                                   kNetworkInterfaceStateChangedTopic,
  1.1408 +                                   null);
  1.1409 +    }
  1.1410 +  },
  1.1411 +
  1.1412 +  deactivateDataCallByType: function(apnType) {
  1.1413 +    if (DEBUG) {
  1.1414 +      this.debug("deactivateDataCallByType: " + apnType);
  1.1415 +    }
  1.1416 +    let apnSetting = this.apnSettings.byType[apnType];
  1.1417 +    if (!apnSetting) {
  1.1418 +      if (DEBUG) {
  1.1419 +        this.debug("No apn setting for type: " + apnType);
  1.1420 +      }
  1.1421 +      return;
  1.1422 +    }
  1.1423 +
  1.1424 +    apnSetting.iface.disconnect(apnType);
  1.1425 +    // We just call disconnect() function, so this interface should be in
  1.1426 +    // disconnecting state. If this interface is still in connected state, we
  1.1427 +    // are sure that other data call types still need this connection of this
  1.1428 +    // interface. In this circumstance, we have to directly update the
  1.1429 +    // necessary data call and interface information to RILContentHelper
  1.1430 +    // and network manager for current data call type.
  1.1431 +    if (apnSetting.iface.connectedTypes.length && apnSetting.iface.connected) {
  1.1432 +      // Update the interface status via-registration if the interface has
  1.1433 +      // already been registered in the network manager.
  1.1434 +      if (apnSetting.iface.name in gNetworkManager.networkInterfaces) {
  1.1435 +        gNetworkManager.unregisterNetworkInterface(apnSetting.iface);
  1.1436 +      }
  1.1437 +      gNetworkManager.registerNetworkInterface(apnSetting.iface);
  1.1438 +
  1.1439 +      Services.obs.notifyObservers(apnSetting.iface,
  1.1440 +                                   kNetworkInterfaceStateChangedTopic,
  1.1441 +                                   null);
  1.1442 +    }
  1.1443 +  },
  1.1444 +
  1.1445 +  deactivateDataCalls: function() {
  1.1446 +    let dataDisconnecting = false;
  1.1447 +    for (let [, apnSetting] of Iterator(this.apnSettings.byApn)) {
  1.1448 +      for (let type of apnSetting.types) {
  1.1449 +        if (this.getDataCallStateByType(type) ==
  1.1450 +            RIL.GECKO_NETWORK_STATE_CONNECTED) {
  1.1451 +          this.deactivateDataCallByType(type);
  1.1452 +          dataDisconnecting = true;
  1.1453 +        }
  1.1454 +      }
  1.1455 +    }
  1.1456 +
  1.1457 +    // No data calls exist. It's safe to proceed the pending radio power off
  1.1458 +    // request.
  1.1459 +    if (gRadioEnabledController.isDeactivatingDataCalls() && !dataDisconnecting) {
  1.1460 +      gRadioEnabledController.finishDeactivatingDataCalls(this.clientId);
  1.1461 +    }
  1.1462 +  },
  1.1463 +
  1.1464 +  registerDataCallCallback: function(callback) {
  1.1465 +    if (this._dataCallbacks.indexOf(callback) != -1) {
  1.1466 +      throw new Error("Already registered this callback: " + callback);
  1.1467 +    }
  1.1468 +    this._dataCallbacks.push(callback);
  1.1469 +    if (DEBUG) {
  1.1470 +      this.debug("Registering callback: " + callback);
  1.1471 +    }
  1.1472 +  },
  1.1473 +
  1.1474 +  unregisterDataCallCallback: function(callback) {
  1.1475 +    let index = this._dataCallbacks.indexOf(callback);
  1.1476 +    if (index != -1) {
  1.1477 +      this._dataCallbacks.splice(index, 1);
  1.1478 +      if (DEBUG) {
  1.1479 +        this.debug("Unregistering callback: " + callback);
  1.1480 +      }
  1.1481 +    }
  1.1482 +  },
  1.1483 +
  1.1484 +  /**
  1.1485 +   * Handle data errors.
  1.1486 +   */
  1.1487 +  handleDataCallError: function(message) {
  1.1488 +    // Notify data call error only for data APN
  1.1489 +    let apnSetting = this.apnSettings && this.apnSettings.byType.default;
  1.1490 +    if (apnSetting) {
  1.1491 +      if (message.apn == apnSetting.apn &&
  1.1492 +          apnSetting.iface.inConnectedTypes("default")) {
  1.1493 +        gMessageManager.sendMobileConnectionMessage("RIL:DataError",
  1.1494 +                                                    this.clientId, message);
  1.1495 +      }
  1.1496 +    }
  1.1497 +
  1.1498 +    this._deliverDataCallCallback("dataCallError", [message]);
  1.1499 +  },
  1.1500 +
  1.1501 +  /**
  1.1502 +   * Handle data call state changes.
  1.1503 +   */
  1.1504 +  handleDataCallState: function(datacall) {
  1.1505 +    this._deliverDataCallCallback("dataCallStateChanged", [datacall]);
  1.1506 +
  1.1507 +    // Process pending radio power off request after all data calls
  1.1508 +    // are disconnected.
  1.1509 +    if (datacall.state == RIL.GECKO_NETWORK_STATE_UNKNOWN &&
  1.1510 +        this.allDataDisconnected()) {
  1.1511 +      if (gRadioEnabledController.isDeactivatingDataCalls()) {
  1.1512 +        if (DEBUG) {
  1.1513 +          this.debug("All data connections are disconnected.");
  1.1514 +        }
  1.1515 +        gRadioEnabledController.finishDeactivatingDataCalls(this.clientId);
  1.1516 +      }
  1.1517 +
  1.1518 +      if (this._pendingApnSettings) {
  1.1519 +        if (DEBUG) {
  1.1520 +          this.debug("Setup pending apn settings.");
  1.1521 +        }
  1.1522 +        this._setupApnSettings(this._pendingApnSettings);
  1.1523 +        this._pendingApnSettings = null;
  1.1524 +        this.updateRILNetworkInterface();
  1.1525 +      }
  1.1526 +    }
  1.1527 +  },
  1.1528 +};
  1.1529 +
  1.1530 +function RadioInterfaceLayer() {
  1.1531 +  let workerMessenger = new WorkerMessenger();
  1.1532 +  workerMessenger.init();
  1.1533 +
  1.1534 +  let numIfaces = this.numRadioInterfaces;
  1.1535 +  if (DEBUG) debug(numIfaces + " interfaces");
  1.1536 +  this.radioInterfaces = [];
  1.1537 +  for (let clientId = 0; clientId < numIfaces; clientId++) {
  1.1538 +    this.radioInterfaces.push(new RadioInterface(clientId, workerMessenger));
  1.1539 +  }
  1.1540 +
  1.1541 +  Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
  1.1542 +
  1.1543 +  gMessageManager.init(this);
  1.1544 +  gRadioEnabledController.init(this);
  1.1545 +  gDataConnectionManager.init(this);
  1.1546 +}
  1.1547 +RadioInterfaceLayer.prototype = {
  1.1548 +
  1.1549 +  classID:   RADIOINTERFACELAYER_CID,
  1.1550 +  classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACELAYER_CID,
  1.1551 +                                    classDescription: "RadioInterfaceLayer",
  1.1552 +                                    interfaces: [Ci.nsIRadioInterfaceLayer]}),
  1.1553 +
  1.1554 +  QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioInterfaceLayer,
  1.1555 +                                         Ci.nsIObserver]),
  1.1556 +
  1.1557 +  /**
  1.1558 +   * nsIObserver interface methods.
  1.1559 +   */
  1.1560 +
  1.1561 +  observe: function(subject, topic, data) {
  1.1562 +    switch (topic) {
  1.1563 +      case NS_XPCOM_SHUTDOWN_OBSERVER_ID:
  1.1564 +        for (let radioInterface of this.radioInterfaces) {
  1.1565 +          radioInterface.shutdown();
  1.1566 +        }
  1.1567 +        this.radioInterfaces = null;
  1.1568 +        Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
  1.1569 +        break;
  1.1570 +     }
  1.1571 +  },
  1.1572 +
  1.1573 +  /**
  1.1574 +   * nsIRadioInterfaceLayer interface methods.
  1.1575 +   */
  1.1576 +
  1.1577 +  getRadioInterface: function(clientId) {
  1.1578 +    return this.radioInterfaces[clientId];
  1.1579 +  },
  1.1580 +
  1.1581 +  setMicrophoneMuted: function(muted) {
  1.1582 +    for (let clientId = 0; clientId < this.numRadioInterfaces; clientId++) {
  1.1583 +      let radioInterface = this.radioInterfaces[clientId];
  1.1584 +      radioInterface.workerMessenger.send("setMute", { muted: muted });
  1.1585 +    }
  1.1586 +  }
  1.1587 +};
  1.1588 +
  1.1589 +XPCOMUtils.defineLazyGetter(RadioInterfaceLayer.prototype,
  1.1590 +                            "numRadioInterfaces", function() {
  1.1591 +  try {
  1.1592 +    return Services.prefs.getIntPref(kPrefRilNumRadioInterfaces);
  1.1593 +  } catch(e) {}
  1.1594 +
  1.1595 +  return 1;
  1.1596 +});
  1.1597 +
  1.1598 +function WorkerMessenger() {
  1.1599 +  // Initial owning attributes.
  1.1600 +  this.radioInterfaces = [];
  1.1601 +  this.tokenCallbackMap = {};
  1.1602 +
  1.1603 +  this.worker = new ChromeWorker("resource://gre/modules/ril_worker.js");
  1.1604 +  this.worker.onerror = this.onerror.bind(this);
  1.1605 +  this.worker.onmessage = this.onmessage.bind(this);
  1.1606 +}
  1.1607 +WorkerMessenger.prototype = {
  1.1608 +  radioInterfaces: null,
  1.1609 +  worker: null,
  1.1610 +
  1.1611 +  // This gets incremented each time we send out a message.
  1.1612 +  token: 1,
  1.1613 +
  1.1614 +  // Maps tokens we send out with messages to the message callback.
  1.1615 +  tokenCallbackMap: null,
  1.1616 +
  1.1617 +  init: function() {
  1.1618 +    let options = {
  1.1619 +      debug: DEBUG,
  1.1620 +      cellBroadcastDisabled: false,
  1.1621 +      clirMode: RIL.CLIR_DEFAULT,
  1.1622 +      quirks: {
  1.1623 +        callstateExtraUint32:
  1.1624 +          libcutils.property_get("ro.moz.ril.callstate_extra_int", "false") === "true",
  1.1625 +        v5Legacy:
  1.1626 +          libcutils.property_get("ro.moz.ril.v5_legacy", "true") === "true",
  1.1627 +        requestUseDialEmergencyCall:
  1.1628 +          libcutils.property_get("ro.moz.ril.dial_emergency_call", "false") === "true",
  1.1629 +        simAppStateExtraFields:
  1.1630 +          libcutils.property_get("ro.moz.ril.simstate_extra_field", "false") === "true",
  1.1631 +        extraUint2ndCall:
  1.1632 +          libcutils.property_get("ro.moz.ril.extra_int_2nd_call", "false") == "true",
  1.1633 +        haveQueryIccLockRetryCount:
  1.1634 +          libcutils.property_get("ro.moz.ril.query_icc_count", "false") == "true",
  1.1635 +        sendStkProfileDownload:
  1.1636 +          libcutils.property_get("ro.moz.ril.send_stk_profile_dl", "false") == "true",
  1.1637 +        dataRegistrationOnDemand:
  1.1638 +          libcutils.property_get("ro.moz.ril.data_reg_on_demand", "false") == "true"
  1.1639 +      },
  1.1640 +      rilEmergencyNumbers: libcutils.property_get("ril.ecclist") ||
  1.1641 +                           libcutils.property_get("ro.ril.ecclist")
  1.1642 +    };
  1.1643 +
  1.1644 +    try {
  1.1645 +      options.cellBroadcastDisabled =
  1.1646 +        Services.prefs.getBoolPref(kPrefCellBroadcastDisabled);
  1.1647 +    } catch(e) {}
  1.1648 +
  1.1649 +    try {
  1.1650 +      options.clirMode = Services.prefs.getIntPref(kPrefClirModePreference);
  1.1651 +    } catch(e) {}
  1.1652 +
  1.1653 +    this.send(null, "setInitialOptions", options);
  1.1654 +  },
  1.1655 +
  1.1656 +  debug: function(aClientId, aMessage) {
  1.1657 +    // We use the same debug subject with RadioInterface's here.
  1.1658 +    dump("-*- RadioInterface[" + aClientId + "]: " + aMessage + "\n");
  1.1659 +  },
  1.1660 +
  1.1661 +  onerror: function(event) {
  1.1662 +    if (DEBUG) {
  1.1663 +      this.debug("X", "Got an error: " + event.filename + ":" +
  1.1664 +                 event.lineno + ": " + event.message + "\n");
  1.1665 +    }
  1.1666 +    event.preventDefault();
  1.1667 +  },
  1.1668 +
  1.1669 +  /**
  1.1670 +   * Process the incoming message from the RIL worker.
  1.1671 +   */
  1.1672 +  onmessage: function(event) {
  1.1673 +    let message = event.data;
  1.1674 +    let clientId = message.rilMessageClientId;
  1.1675 +    if (clientId === null) {
  1.1676 +      return;
  1.1677 +    }
  1.1678 +
  1.1679 +    if (DEBUG) {
  1.1680 +      this.debug(clientId, "Received message from worker: " + JSON.stringify(message));
  1.1681 +    }
  1.1682 +
  1.1683 +    let token = message.rilMessageToken;
  1.1684 +    if (token == null) {
  1.1685 +      // That's an unsolicited message.  Pass to RadioInterface directly.
  1.1686 +      let radioInterface = this.radioInterfaces[clientId];
  1.1687 +      radioInterface.handleUnsolicitedWorkerMessage(message);
  1.1688 +      return;
  1.1689 +    }
  1.1690 +
  1.1691 +    let callback = this.tokenCallbackMap[message.rilMessageToken];
  1.1692 +    if (!callback) {
  1.1693 +      if (DEBUG) this.debug(clientId, "Ignore orphan token: " + message.rilMessageToken);
  1.1694 +      return;
  1.1695 +    }
  1.1696 +
  1.1697 +    let keep = false;
  1.1698 +    try {
  1.1699 +      keep = callback(message);
  1.1700 +    } catch(e) {
  1.1701 +      if (DEBUG) this.debug(clientId, "callback throws an exception: " + e);
  1.1702 +    }
  1.1703 +
  1.1704 +    if (!keep) {
  1.1705 +      delete this.tokenCallbackMap[message.rilMessageToken];
  1.1706 +    }
  1.1707 +  },
  1.1708 +
  1.1709 +  registerClient: function(aClientId, aRadioInterface) {
  1.1710 +    if (DEBUG) this.debug(aClientId, "Starting RIL Worker");
  1.1711 +
  1.1712 +    // Keep a reference so that we can dispatch unsolicited messages to it.
  1.1713 +    this.radioInterfaces[aClientId] = aRadioInterface;
  1.1714 +
  1.1715 +    this.send(null, "registerClient", { clientId: aClientId });
  1.1716 +    gSystemWorkerManager.registerRilWorker(aClientId, this.worker);
  1.1717 +  },
  1.1718 +
  1.1719 +  /**
  1.1720 +   * Send arbitrary message to worker.
  1.1721 +   *
  1.1722 +   * @param rilMessageType
  1.1723 +   *        A text message type.
  1.1724 +   * @param message [optional]
  1.1725 +   *        An optional message object to send.
  1.1726 +   * @param callback [optional]
  1.1727 +   *        An optional callback function which is called when worker replies
  1.1728 +   *        with an message containing a "rilMessageToken" attribute of the
  1.1729 +   *        same value we passed.  This callback function accepts only one
  1.1730 +   *        parameter -- the reply from worker.  It also returns a boolean
  1.1731 +   *        value true to keep current token-callback mapping and wait for
  1.1732 +   *        another worker reply, or false to remove the mapping.
  1.1733 +   */
  1.1734 +  send: function(clientId, rilMessageType, message, callback) {
  1.1735 +    message = message || {};
  1.1736 +
  1.1737 +    message.rilMessageClientId = clientId;
  1.1738 +    message.rilMessageToken = this.token;
  1.1739 +    this.token++;
  1.1740 +
  1.1741 +    if (callback) {
  1.1742 +      // Only create the map if callback is provided.  For sending a request
  1.1743 +      // and intentionally leaving the callback undefined, that reply will
  1.1744 +      // be dropped in |this.onmessage| because of that orphan token.
  1.1745 +      //
  1.1746 +      // For sending a request that never replied at all, we're fine with this
  1.1747 +      // because no callback shall be passed and we leave nothing to be cleaned
  1.1748 +      // up later.
  1.1749 +      this.tokenCallbackMap[message.rilMessageToken] = callback;
  1.1750 +    }
  1.1751 +
  1.1752 +    message.rilMessageType = rilMessageType;
  1.1753 +    this.worker.postMessage(message);
  1.1754 +  },
  1.1755 +
  1.1756 +  /**
  1.1757 +   * Send message to worker and return worker reply to RILContentHelper.
  1.1758 +   *
  1.1759 +   * @param msg
  1.1760 +   *        A message object from ppmm.
  1.1761 +   * @param rilMessageType
  1.1762 +   *        A text string for worker message type.
  1.1763 +   * @param ipcType [optinal]
  1.1764 +   *        A text string for ipc message type. "msg.name" if omitted.
  1.1765 +   *
  1.1766 +   * @TODO: Bug 815526 - deprecate RILContentHelper.
  1.1767 +   */
  1.1768 +  sendWithIPCMessage: function(clientId, msg, rilMessageType, ipcType) {
  1.1769 +    this.send(clientId, rilMessageType, msg.json.data, (function(reply) {
  1.1770 +      ipcType = ipcType || msg.name;
  1.1771 +      msg.target.sendAsyncMessage(ipcType, {
  1.1772 +        clientId: clientId,
  1.1773 +        data: reply
  1.1774 +      });
  1.1775 +      return false;
  1.1776 +    }).bind(this));
  1.1777 +  }
  1.1778 +};
  1.1779 +
  1.1780 +function RadioInterface(aClientId, aWorkerMessenger) {
  1.1781 +  this.clientId = aClientId;
  1.1782 +  this.workerMessenger = {
  1.1783 +    send: aWorkerMessenger.send.bind(aWorkerMessenger, aClientId),
  1.1784 +    sendWithIPCMessage:
  1.1785 +      aWorkerMessenger.sendWithIPCMessage.bind(aWorkerMessenger, aClientId),
  1.1786 +  };
  1.1787 +  aWorkerMessenger.registerClient(aClientId, this);
  1.1788 +
  1.1789 +  this.supportedNetworkTypes = this.getSupportedNetworkTypes();
  1.1790 +
  1.1791 +  this.rilContext = {
  1.1792 +    radioState:     RIL.GECKO_RADIOSTATE_UNAVAILABLE,
  1.1793 +    detailedRadioState: null,
  1.1794 +    cardState:      RIL.GECKO_CARDSTATE_UNKNOWN,
  1.1795 +    networkSelectionMode: RIL.GECKO_NETWORK_SELECTION_UNKNOWN,
  1.1796 +    iccInfo:        null,
  1.1797 +    imsi:           null,
  1.1798 +
  1.1799 +    // These objects implement the nsIDOMMozMobileConnectionInfo interface,
  1.1800 +    // although the actual implementation lives in the content process. So are
  1.1801 +    // the child attributes `network` and `cell`, which implement
  1.1802 +    // nsIDOMMozMobileNetworkInfo and nsIDOMMozMobileCellInfo respectively.
  1.1803 +    voice:          {connected: false,
  1.1804 +                     emergencyCallsOnly: false,
  1.1805 +                     roaming: false,
  1.1806 +                     network: null,
  1.1807 +                     cell: null,
  1.1808 +                     type: null,
  1.1809 +                     signalStrength: null,
  1.1810 +                     relSignalStrength: null},
  1.1811 +    data:           {connected: false,
  1.1812 +                     emergencyCallsOnly: false,
  1.1813 +                     roaming: false,
  1.1814 +                     network: null,
  1.1815 +                     cell: null,
  1.1816 +                     type: null,
  1.1817 +                     signalStrength: null,
  1.1818 +                     relSignalStrength: null},
  1.1819 +  };
  1.1820 +
  1.1821 +  this.voicemailInfo = {
  1.1822 +    number: null,
  1.1823 +    displayName: null
  1.1824 +  };
  1.1825 +
  1.1826 +  this.operatorInfo = {};
  1.1827 +
  1.1828 +  let lock = gSettingsService.createLock();
  1.1829 +
  1.1830 +  // Read the "time.clock.automatic-update.enabled" setting to see if
  1.1831 +  // we need to adjust the system clock time by NITZ or SNTP.
  1.1832 +  lock.get(kSettingsClockAutoUpdateEnabled, this);
  1.1833 +
  1.1834 +  // Read the "time.timezone.automatic-update.enabled" setting to see if
  1.1835 +  // we need to adjust the system timezone by NITZ.
  1.1836 +  lock.get(kSettingsTimezoneAutoUpdateEnabled, this);
  1.1837 +
  1.1838 +  // Set "time.clock.automatic-update.available" to false when starting up.
  1.1839 +  this.setClockAutoUpdateAvailable(false);
  1.1840 +
  1.1841 +  // Set "time.timezone.automatic-update.available" to false when starting up.
  1.1842 +  this.setTimezoneAutoUpdateAvailable(false);
  1.1843 +
  1.1844 +  // Read the Cell Broadcast Search List setting, string of integers or integer
  1.1845 +  // ranges separated by comma, to set listening channels.
  1.1846 +  lock.get(kSettingsCellBroadcastSearchList, this);
  1.1847 +
  1.1848 +  Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false);
  1.1849 +  Services.obs.addObserver(this, kSysClockChangeObserverTopic, false);
  1.1850 +  Services.obs.addObserver(this, kScreenStateChangedTopic, false);
  1.1851 +
  1.1852 +  Services.obs.addObserver(this, kNetworkConnStateChangedTopic, false);
  1.1853 +  Services.obs.addObserver(this, kNetworkActiveChangedTopic, false);
  1.1854 +  Services.prefs.addObserver(kPrefCellBroadcastDisabled, this, false);
  1.1855 +
  1.1856 +  this.portAddressedSmsApps = {};
  1.1857 +  this.portAddressedSmsApps[WAP.WDP_PORT_PUSH] = this.handleSmsWdpPortPush.bind(this);
  1.1858 +
  1.1859 +  this._receivedSmsSegmentsMap = {};
  1.1860 +
  1.1861 +  this._sntp = new Sntp(this.setClockBySntp.bind(this),
  1.1862 +                        Services.prefs.getIntPref("network.sntp.maxRetryCount"),
  1.1863 +                        Services.prefs.getIntPref("network.sntp.refreshPeriod"),
  1.1864 +                        Services.prefs.getIntPref("network.sntp.timeout"),
  1.1865 +                        Services.prefs.getCharPref("network.sntp.pools").split(";"),
  1.1866 +                        Services.prefs.getIntPref("network.sntp.port"));
  1.1867 +}
  1.1868 +
  1.1869 +RadioInterface.prototype = {
  1.1870 +
  1.1871 +  classID:   RADIOINTERFACE_CID,
  1.1872 +  classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACE_CID,
  1.1873 +                                    classDescription: "RadioInterface",
  1.1874 +                                    interfaces: [Ci.nsIRadioInterface]}),
  1.1875 +
  1.1876 +  QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioInterface,
  1.1877 +                                         Ci.nsIObserver,
  1.1878 +                                         Ci.nsISettingsServiceCallback]),
  1.1879 +
  1.1880 +  // A private wrapped WorkerMessenger instance.
  1.1881 +  workerMessenger: null,
  1.1882 +
  1.1883 +  debug: function(s) {
  1.1884 +    dump("-*- RadioInterface[" + this.clientId + "]: " + s + "\n");
  1.1885 +  },
  1.1886 +
  1.1887 +  shutdown: function() {
  1.1888 +    // Release the CPU wake lock for handling the received SMS.
  1.1889 +    this._releaseSmsHandledWakeLock();
  1.1890 +
  1.1891 +    Services.obs.removeObserver(this, kMozSettingsChangedObserverTopic);
  1.1892 +    Services.obs.removeObserver(this, kSysClockChangeObserverTopic);
  1.1893 +    Services.obs.removeObserver(this, kScreenStateChangedTopic);
  1.1894 +    Services.obs.removeObserver(this, kNetworkConnStateChangedTopic);
  1.1895 +    Services.obs.removeObserver(this, kNetworkActiveChangedTopic);
  1.1896 +  },
  1.1897 +
  1.1898 +  /**
  1.1899 +   * A utility function to copy objects. The srcInfo may contain
  1.1900 +   * "rilMessageType", should ignore it.
  1.1901 +   */
  1.1902 +  updateInfo: function(srcInfo, destInfo) {
  1.1903 +    for (let key in srcInfo) {
  1.1904 +      if (key === "rilMessageType") {
  1.1905 +        continue;
  1.1906 +      }
  1.1907 +      destInfo[key] = srcInfo[key];
  1.1908 +    }
  1.1909 +  },
  1.1910 +
  1.1911 +  /**
  1.1912 +   * A utility function to compare objects. The srcInfo may contain
  1.1913 +   * "rilMessageType", should ignore it.
  1.1914 +   */
  1.1915 +  isInfoChanged: function(srcInfo, destInfo) {
  1.1916 +    if (!destInfo) {
  1.1917 +      return true;
  1.1918 +    }
  1.1919 +
  1.1920 +    for (let key in srcInfo) {
  1.1921 +      if (key === "rilMessageType") {
  1.1922 +        continue;
  1.1923 +      }
  1.1924 +      if (srcInfo[key] !== destInfo[key]) {
  1.1925 +        return true;
  1.1926 +      }
  1.1927 +    }
  1.1928 +
  1.1929 +    return false;
  1.1930 +  },
  1.1931 +
  1.1932 +  /**
  1.1933 +   * A utility function to get supportedNetworkTypes from system property
  1.1934 +   */
  1.1935 +  getSupportedNetworkTypes: function() {
  1.1936 +    let key = "ro.moz.ril." + this.clientId + ".network_types";
  1.1937 +    let supportedNetworkTypes = libcutils.property_get(key, "").split(",");
  1.1938 +    for (let type of supportedNetworkTypes) {
  1.1939 +      // If the value in system property is not valid, use the default one which
  1.1940 +      // is defined in ril_consts.js.
  1.1941 +      if (RIL.GECKO_SUPPORTED_NETWORK_TYPES.indexOf(type) < 0) {
  1.1942 +        if (DEBUG) this.debug("Unknown network type: " + type);
  1.1943 +        supportedNetworkTypes =
  1.1944 +          RIL.GECKO_SUPPORTED_NETWORK_TYPES_DEFAULT.split(",");
  1.1945 +        break;
  1.1946 +      }
  1.1947 +    }
  1.1948 +    if (DEBUG) this.debug("Supported Network Types: " + supportedNetworkTypes);
  1.1949 +    return supportedNetworkTypes;
  1.1950 +  },
  1.1951 +
  1.1952 +  /**
  1.1953 +   * Process a message from the content process.
  1.1954 +   */
  1.1955 +  receiveMessage: function(msg) {
  1.1956 +    switch (msg.name) {
  1.1957 +      case "RIL:GetRilContext":
  1.1958 +        // This message is sync.
  1.1959 +        return this.rilContext;
  1.1960 +      case "RIL:GetLastKnownNetwork":
  1.1961 +        // This message is sync.
  1.1962 +        return this._lastKnownNetwork;
  1.1963 +      case "RIL:GetLastKnownHomeNetwork":
  1.1964 +        // This message is sync.
  1.1965 +        return this._lastKnownHomeNetwork;
  1.1966 +      case "RIL:GetAvailableNetworks":
  1.1967 +        this.workerMessenger.sendWithIPCMessage(msg, "getAvailableNetworks");
  1.1968 +        break;
  1.1969 +      case "RIL:SelectNetwork":
  1.1970 +        this.workerMessenger.sendWithIPCMessage(msg, "selectNetwork");
  1.1971 +        break;
  1.1972 +      case "RIL:SelectNetworkAuto":
  1.1973 +        this.workerMessenger.sendWithIPCMessage(msg, "selectNetworkAuto");
  1.1974 +        break;
  1.1975 +      case "RIL:SetPreferredNetworkType":
  1.1976 +        this.setPreferredNetworkType(msg.target, msg.json.data);
  1.1977 +        break;
  1.1978 +      case "RIL:GetPreferredNetworkType":
  1.1979 +        this.getPreferredNetworkType(msg.target, msg.json.data);
  1.1980 +        break;
  1.1981 +      case "RIL:GetCardLockState":
  1.1982 +        this.workerMessenger.sendWithIPCMessage(msg, "iccGetCardLockState",
  1.1983 +                                                "RIL:CardLockResult");
  1.1984 +        break;
  1.1985 +      case "RIL:UnlockCardLock":
  1.1986 +        this.workerMessenger.sendWithIPCMessage(msg, "iccUnlockCardLock",
  1.1987 +                                                "RIL:CardLockResult");
  1.1988 +        break;
  1.1989 +      case "RIL:SetCardLock":
  1.1990 +        this.workerMessenger.sendWithIPCMessage(msg, "iccSetCardLock",
  1.1991 +                                                "RIL:CardLockResult");
  1.1992 +        break;
  1.1993 +      case "RIL:GetCardLockRetryCount":
  1.1994 +        this.workerMessenger.sendWithIPCMessage(msg, "iccGetCardLockRetryCount",
  1.1995 +                                                "RIL:CardLockRetryCount");
  1.1996 +        break;
  1.1997 +      case "RIL:SendMMI":
  1.1998 +        this.sendMMI(msg.target, msg.json.data);
  1.1999 +        break;
  1.2000 +      case "RIL:CancelMMI":
  1.2001 +        this.workerMessenger.sendWithIPCMessage(msg, "cancelUSSD");
  1.2002 +        break;
  1.2003 +      case "RIL:SendStkResponse":
  1.2004 +        this.workerMessenger.send("sendStkTerminalResponse", msg.json.data);
  1.2005 +        break;
  1.2006 +      case "RIL:SendStkMenuSelection":
  1.2007 +        this.workerMessenger.send("sendStkMenuSelection", msg.json.data);
  1.2008 +        break;
  1.2009 +      case "RIL:SendStkTimerExpiration":
  1.2010 +        this.workerMessenger.send("sendStkTimerExpiration", msg.json.data);
  1.2011 +        break;
  1.2012 +      case "RIL:SendStkEventDownload":
  1.2013 +        this.workerMessenger.send("sendStkEventDownload", msg.json.data);
  1.2014 +        break;
  1.2015 +      case "RIL:IccOpenChannel":
  1.2016 +        this.workerMessenger.sendWithIPCMessage(msg, "iccOpenChannel");
  1.2017 +        break;
  1.2018 +      case "RIL:IccCloseChannel":
  1.2019 +        this.workerMessenger.sendWithIPCMessage(msg, "iccCloseChannel");
  1.2020 +        break;
  1.2021 +      case "RIL:IccExchangeAPDU":
  1.2022 +        this.workerMessenger.sendWithIPCMessage(msg, "iccExchangeAPDU");
  1.2023 +        break;
  1.2024 +      case "RIL:ReadIccContacts":
  1.2025 +        this.workerMessenger.sendWithIPCMessage(msg, "readICCContacts");
  1.2026 +        break;
  1.2027 +      case "RIL:UpdateIccContact":
  1.2028 +        this.workerMessenger.sendWithIPCMessage(msg, "updateICCContact");
  1.2029 +        break;
  1.2030 +      case "RIL:MatchMvno":
  1.2031 +        this.matchMvno(msg.target, msg.json.data);
  1.2032 +        break;
  1.2033 +      case "RIL:SetCallForwardingOptions":
  1.2034 +        this.setCallForwardingOptions(msg.target, msg.json.data);
  1.2035 +        break;
  1.2036 +      case "RIL:GetCallForwardingOptions":
  1.2037 +        this.workerMessenger.sendWithIPCMessage(msg, "queryCallForwardStatus");
  1.2038 +        break;
  1.2039 +      case "RIL:SetCallBarringOptions":
  1.2040 +        this.workerMessenger.sendWithIPCMessage(msg, "setCallBarring");
  1.2041 +        break;
  1.2042 +      case "RIL:GetCallBarringOptions":
  1.2043 +        this.workerMessenger.sendWithIPCMessage(msg, "queryCallBarringStatus");
  1.2044 +        break;
  1.2045 +      case "RIL:ChangeCallBarringPassword":
  1.2046 +        this.workerMessenger.sendWithIPCMessage(msg, "changeCallBarringPassword");
  1.2047 +        break;
  1.2048 +      case "RIL:SetCallWaitingOptions":
  1.2049 +        this.workerMessenger.sendWithIPCMessage(msg, "setCallWaiting");
  1.2050 +        break;
  1.2051 +      case "RIL:GetCallWaitingOptions":
  1.2052 +        this.workerMessenger.sendWithIPCMessage(msg, "queryCallWaiting");
  1.2053 +        break;
  1.2054 +      case "RIL:SetCallingLineIdRestriction":
  1.2055 +        this.setCallingLineIdRestriction(msg.target, msg.json.data);
  1.2056 +        break;
  1.2057 +      case "RIL:GetCallingLineIdRestriction":
  1.2058 +        this.workerMessenger.sendWithIPCMessage(msg, "getCLIR");
  1.2059 +        break;
  1.2060 +      case "RIL:ExitEmergencyCbMode":
  1.2061 +        this.workerMessenger.sendWithIPCMessage(msg, "exitEmergencyCbMode");
  1.2062 +        break;
  1.2063 +      case "RIL:SetRadioEnabled":
  1.2064 +        this.setRadioEnabled(msg.target, msg.json.data);
  1.2065 +        break;
  1.2066 +      case "RIL:GetVoicemailInfo":
  1.2067 +        // This message is sync.
  1.2068 +        return this.voicemailInfo;
  1.2069 +      case "RIL:SetRoamingPreference":
  1.2070 +        this.workerMessenger.sendWithIPCMessage(msg, "setRoamingPreference");
  1.2071 +        break;
  1.2072 +      case "RIL:GetRoamingPreference":
  1.2073 +        this.workerMessenger.sendWithIPCMessage(msg, "queryRoamingPreference");
  1.2074 +        break;
  1.2075 +      case "RIL:SetVoicePrivacyMode":
  1.2076 +        this.workerMessenger.sendWithIPCMessage(msg, "setVoicePrivacyMode");
  1.2077 +        break;
  1.2078 +      case "RIL:GetVoicePrivacyMode":
  1.2079 +        this.workerMessenger.sendWithIPCMessage(msg, "queryVoicePrivacyMode");
  1.2080 +        break;
  1.2081 +      case "RIL:GetSupportedNetworkTypes":
  1.2082 +        // This message is sync.
  1.2083 +        return this.supportedNetworkTypes;
  1.2084 +    }
  1.2085 +    return null;
  1.2086 +  },
  1.2087 +
  1.2088 +  handleUnsolicitedWorkerMessage: function(message) {
  1.2089 +    let connHandler = gDataConnectionManager.getConnectionHandler(this.clientId);
  1.2090 +    switch (message.rilMessageType) {
  1.2091 +      case "callRing":
  1.2092 +        gTelephonyProvider.notifyCallRing();
  1.2093 +        break;
  1.2094 +      case "callStateChange":
  1.2095 +        gTelephonyProvider.notifyCallStateChanged(this.clientId, message.call);
  1.2096 +        break;
  1.2097 +      case "callDisconnected":
  1.2098 +        gTelephonyProvider.notifyCallDisconnected(this.clientId, message.call);
  1.2099 +        break;
  1.2100 +      case "conferenceCallStateChanged":
  1.2101 +        gTelephonyProvider.notifyConferenceCallStateChanged(message.state);
  1.2102 +        break;
  1.2103 +      case "cdmaCallWaiting":
  1.2104 +        gTelephonyProvider.notifyCdmaCallWaiting(this.clientId, message.number);
  1.2105 +        break;
  1.2106 +      case "suppSvcNotification":
  1.2107 +        gTelephonyProvider.notifySupplementaryService(this.clientId,
  1.2108 +                                                      message.callIndex,
  1.2109 +                                                      message.notification);
  1.2110 +        break;
  1.2111 +      case "datacallerror":
  1.2112 +        connHandler.handleDataCallError(message);
  1.2113 +        break;
  1.2114 +      case "datacallstatechange":
  1.2115 +        let addresses = [];
  1.2116 +        for (let i = 0; i < message.addresses.length; i++) {
  1.2117 +          let [address, prefixLength] = message.addresses[i].split("/");
  1.2118 +          // From AOSP hardware/ril/include/telephony/ril.h, that address prefix
  1.2119 +          // is said to be OPTIONAL, but we never met such case before.
  1.2120 +          addresses.push({
  1.2121 +            address: address,
  1.2122 +            prefixLength: prefixLength ? parseInt(prefixLength, 10) : 0
  1.2123 +          });
  1.2124 +        }
  1.2125 +        message.addresses = addresses;
  1.2126 +        connHandler.handleDataCallState(message);
  1.2127 +        break;
  1.2128 +      case "emergencyCbModeChange":
  1.2129 +        this.handleEmergencyCbModeChange(message);
  1.2130 +        break;
  1.2131 +      case "networkinfochanged":
  1.2132 +        this.updateNetworkInfo(message);
  1.2133 +        break;
  1.2134 +      case "networkselectionmodechange":
  1.2135 +        this.updateNetworkSelectionMode(message);
  1.2136 +        break;
  1.2137 +      case "voiceregistrationstatechange":
  1.2138 +        this.updateVoiceConnection(message);
  1.2139 +        break;
  1.2140 +      case "dataregistrationstatechange":
  1.2141 +        this.updateDataConnection(message);
  1.2142 +        break;
  1.2143 +      case "signalstrengthchange":
  1.2144 +        this.handleSignalStrengthChange(message);
  1.2145 +        break;
  1.2146 +      case "operatorchange":
  1.2147 +        this.handleOperatorChange(message);
  1.2148 +        break;
  1.2149 +      case "otastatuschange":
  1.2150 +        this.handleOtaStatus(message);
  1.2151 +        break;
  1.2152 +      case "radiostatechange":
  1.2153 +        this.handleRadioStateChange(message);
  1.2154 +        break;
  1.2155 +      case "cardstatechange":
  1.2156 +        this.rilContext.cardState = message.cardState;
  1.2157 +        gRadioEnabledController.receiveCardState(this.clientId);
  1.2158 +        gMessageManager.sendIccMessage("RIL:CardStateChanged",
  1.2159 +                                       this.clientId, message);
  1.2160 +        break;
  1.2161 +      case "sms-received":
  1.2162 +        this.handleSmsMultipart(message);
  1.2163 +        break;
  1.2164 +      case "cellbroadcast-received":
  1.2165 +        message.timestamp = Date.now();
  1.2166 +        gMessageManager.sendCellBroadcastMessage("RIL:CellBroadcastReceived",
  1.2167 +                                                 this.clientId, message);
  1.2168 +        break;
  1.2169 +      case "nitzTime":
  1.2170 +        this.handleNitzTime(message);
  1.2171 +        break;
  1.2172 +      case "iccinfochange":
  1.2173 +        this.handleIccInfoChange(message);
  1.2174 +        break;
  1.2175 +      case "iccimsi":
  1.2176 +        this.rilContext.imsi = message.imsi;
  1.2177 +        break;
  1.2178 +      case "iccmbdn":
  1.2179 +        this.handleIccMbdn(message);
  1.2180 +        break;
  1.2181 +      case "iccmwis":
  1.2182 +        gMessageManager.sendVoicemailMessage("RIL:VoicemailNotification",
  1.2183 +                                             this.clientId, message.mwi);
  1.2184 +        break;
  1.2185 +      case "USSDReceived":
  1.2186 +        if (DEBUG) this.debug("USSDReceived " + JSON.stringify(message));
  1.2187 +        this.handleUSSDReceived(message);
  1.2188 +        break;
  1.2189 +      case "stkcommand":
  1.2190 +        this.handleStkProactiveCommand(message);
  1.2191 +        break;
  1.2192 +      case "stksessionend":
  1.2193 +        gMessageManager.sendIccMessage("RIL:StkSessionEnd", this.clientId, null);
  1.2194 +        break;
  1.2195 +      case "exitEmergencyCbMode":
  1.2196 +        this.handleExitEmergencyCbMode(message);
  1.2197 +        break;
  1.2198 +      case "cdma-info-rec-received":
  1.2199 +        if (DEBUG) this.debug("cdma-info-rec-received: " + JSON.stringify(message));
  1.2200 +        gSystemMessenger.broadcastMessage("cdma-info-rec-received", message);
  1.2201 +        break;
  1.2202 +      default:
  1.2203 +        throw new Error("Don't know about this message type: " +
  1.2204 +                        message.rilMessageType);
  1.2205 +    }
  1.2206 +  },
  1.2207 +
  1.2208 +  /**
  1.2209 +   * Get phone number from iccInfo.
  1.2210 +   *
  1.2211 +   * If the icc card is gsm card, the phone number is in msisdn.
  1.2212 +   * @see nsIDOMMozGsmIccInfo
  1.2213 +   *
  1.2214 +   * Otherwise, the phone number is in mdn.
  1.2215 +   * @see nsIDOMMozCdmaIccInfo
  1.2216 +   */
  1.2217 +  getPhoneNumber: function() {
  1.2218 +    let iccInfo = this.rilContext.iccInfo;
  1.2219 +
  1.2220 +    if (!iccInfo) {
  1.2221 +      return null;
  1.2222 +    }
  1.2223 +
  1.2224 +    // After moving SMS code out of RadioInterfaceLayer, we could use
  1.2225 +    // |iccInfo instanceof Ci.nsIDOMMozGsmIccInfo| here.
  1.2226 +    // TODO: Bug 873351 - B2G SMS: move SMS code out of RadioInterfaceLayer to
  1.2227 +    //                    SmsService
  1.2228 +    let number = (iccInfo instanceof GsmIccInfo) ? iccInfo.msisdn : iccInfo.mdn;
  1.2229 +
  1.2230 +    // Workaround an xpconnect issue with undefined string objects.
  1.2231 +    // See bug 808220
  1.2232 +    if (number === undefined || number === "undefined") {
  1.2233 +      return null;
  1.2234 +    }
  1.2235 +
  1.2236 +    return number;
  1.2237 +  },
  1.2238 +
  1.2239 +  /**
  1.2240 +   * A utility function to get the ICC ID of the SIM card (if installed).
  1.2241 +   */
  1.2242 +  getIccId: function() {
  1.2243 +    let iccInfo = this.rilContext.iccInfo;
  1.2244 +
  1.2245 +    if (!iccInfo) {
  1.2246 +      return null;
  1.2247 +    }
  1.2248 +
  1.2249 +    let iccId = iccInfo.iccid;
  1.2250 +
  1.2251 +    // Workaround an xpconnect issue with undefined string objects.
  1.2252 +    // See bug 808220
  1.2253 +    if (iccId === undefined || iccId === "undefined") {
  1.2254 +      return null;
  1.2255 +    }
  1.2256 +
  1.2257 +    return iccId;
  1.2258 +  },
  1.2259 +
  1.2260 +  // Matches the mvnoData pattern with imsi. Characters 'x' and 'X' are skipped
  1.2261 +  // and not compared. E.g., if the mvnoData passed is '310260x10xxxxxx',
  1.2262 +  // then the function returns true only if imsi has the same first 6 digits,
  1.2263 +  // 8th and 9th digit.
  1.2264 +  isImsiMatches: function(mvnoData) {
  1.2265 +    let imsi = this.rilContext.imsi;
  1.2266 +
  1.2267 +    // This should not be an error, but a mismatch.
  1.2268 +    if (mvnoData.length > imsi.length) {
  1.2269 +      return false;
  1.2270 +    }
  1.2271 +
  1.2272 +    for (let i = 0; i < mvnoData.length; i++) {
  1.2273 +      let c = mvnoData[i];
  1.2274 +      if ((c !== 'x') && (c !== 'X') && (c !== imsi[i])) {
  1.2275 +        return false;
  1.2276 +      }
  1.2277 +    }
  1.2278 +    return true;
  1.2279 +  },
  1.2280 +
  1.2281 +  matchMvno: function(target, message) {
  1.2282 +    if (DEBUG) this.debug("matchMvno: " + JSON.stringify(message));
  1.2283 +
  1.2284 +    if (!message || !message.mvnoType || !message.mvnoData) {
  1.2285 +      message.errorMsg = RIL.GECKO_ERROR_INVALID_PARAMETER;
  1.2286 +    }
  1.2287 +    // Currently we only support imsi matching.
  1.2288 +    if (message.mvnoType != "imsi") {
  1.2289 +      message.errorMsg = RIL.GECKO_ERROR_MODE_NOT_SUPPORTED;
  1.2290 +    }
  1.2291 +    // Fire error if mvnoType is imsi but imsi is not available.
  1.2292 +    if (!this.rilContext.imsi) {
  1.2293 +      message.errorMsg = RIL.GECKO_ERROR_GENERIC_FAILURE;
  1.2294 +    }
  1.2295 +
  1.2296 +    if (!message.errorMsg) {
  1.2297 +      message.result = this.isImsiMatches(message.mvnoData);
  1.2298 +    }
  1.2299 +
  1.2300 +    target.sendAsyncMessage("RIL:MatchMvno", {
  1.2301 +      clientId: this.clientId,
  1.2302 +      data: message
  1.2303 +    });
  1.2304 +  },
  1.2305 +
  1.2306 +  updateNetworkInfo: function(message) {
  1.2307 +    let voiceMessage = message[RIL.NETWORK_INFO_VOICE_REGISTRATION_STATE];
  1.2308 +    let dataMessage = message[RIL.NETWORK_INFO_DATA_REGISTRATION_STATE];
  1.2309 +    let operatorMessage = message[RIL.NETWORK_INFO_OPERATOR];
  1.2310 +    let selectionMessage = message[RIL.NETWORK_INFO_NETWORK_SELECTION_MODE];
  1.2311 +    let signalMessage = message[RIL.NETWORK_INFO_SIGNAL];
  1.2312 +
  1.2313 +    // Batch the *InfoChanged messages together
  1.2314 +    if (voiceMessage) {
  1.2315 +      this.updateVoiceConnection(voiceMessage, true);
  1.2316 +    }
  1.2317 +
  1.2318 +    if (dataMessage) {
  1.2319 +      this.updateDataConnection(dataMessage, true);
  1.2320 +    }
  1.2321 +
  1.2322 +    if (operatorMessage) {
  1.2323 +      this.handleOperatorChange(operatorMessage, true);
  1.2324 +    }
  1.2325 +
  1.2326 +    if (signalMessage) {
  1.2327 +      this.handleSignalStrengthChange(signalMessage, true);
  1.2328 +    }
  1.2329 +
  1.2330 +    let voice = this.rilContext.voice;
  1.2331 +    let data = this.rilContext.data;
  1.2332 +
  1.2333 +    this.checkRoamingBetweenOperators(voice);
  1.2334 +    this.checkRoamingBetweenOperators(data);
  1.2335 +
  1.2336 +    if (voiceMessage || operatorMessage || signalMessage) {
  1.2337 +      gMessageManager.sendMobileConnectionMessage("RIL:VoiceInfoChanged",
  1.2338 +                                                  this.clientId, voice);
  1.2339 +    }
  1.2340 +    if (dataMessage || operatorMessage || signalMessage) {
  1.2341 +      gMessageManager.sendMobileConnectionMessage("RIL:DataInfoChanged",
  1.2342 +                                                  this.clientId, data);
  1.2343 +    }
  1.2344 +
  1.2345 +    if (selectionMessage) {
  1.2346 +      this.updateNetworkSelectionMode(selectionMessage);
  1.2347 +    }
  1.2348 +  },
  1.2349 +
  1.2350 +  /**
  1.2351 +    * Fix the roaming. RIL can report roaming in some case it is not
  1.2352 +    * really the case. See bug 787967
  1.2353 +    *
  1.2354 +    * @param registration  The voiceMessage or dataMessage from which the
  1.2355 +    *                      roaming state will be changed (maybe, if needed).
  1.2356 +    */
  1.2357 +  checkRoamingBetweenOperators: function(registration) {
  1.2358 +    let iccInfo = this.rilContext.iccInfo;
  1.2359 +    let operator = registration.network;
  1.2360 +    let state = registration.state;
  1.2361 +
  1.2362 +    if (!iccInfo || !operator ||
  1.2363 +        state != RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED) {
  1.2364 +      return;
  1.2365 +    }
  1.2366 +
  1.2367 +    let spn = iccInfo.spn && iccInfo.spn.toLowerCase();
  1.2368 +    let longName = operator.longName && operator.longName.toLowerCase();
  1.2369 +    let shortName = operator.shortName && operator.shortName.toLowerCase();
  1.2370 +
  1.2371 +    let equalsLongName = longName && (spn == longName);
  1.2372 +    let equalsShortName = shortName && (spn == shortName);
  1.2373 +    let equalsMcc = iccInfo.mcc == operator.mcc;
  1.2374 +
  1.2375 +    registration.roaming = registration.roaming &&
  1.2376 +                           !(equalsMcc && (equalsLongName || equalsShortName));
  1.2377 +  },
  1.2378 +
  1.2379 +  /**
  1.2380 +   * Handle data connection changes.
  1.2381 +   *
  1.2382 +   * @param newInfo The new voice connection information.
  1.2383 +   * @param batch   When batch is true, the RIL:VoiceInfoChanged message will
  1.2384 +   *                not be sent.
  1.2385 +   */
  1.2386 +  updateVoiceConnection: function(newInfo, batch) {
  1.2387 +    let voiceInfo = this.rilContext.voice;
  1.2388 +    voiceInfo.state = newInfo.state;
  1.2389 +    voiceInfo.connected = newInfo.connected;
  1.2390 +    voiceInfo.roaming = newInfo.roaming;
  1.2391 +    voiceInfo.emergencyCallsOnly = newInfo.emergencyCallsOnly;
  1.2392 +    voiceInfo.type = newInfo.type;
  1.2393 +
  1.2394 +    // Make sure we also reset the operator and signal strength information
  1.2395 +    // if we drop off the network.
  1.2396 +    if (newInfo.state !== RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED) {
  1.2397 +      voiceInfo.cell = null;
  1.2398 +      voiceInfo.network = null;
  1.2399 +      voiceInfo.signalStrength = null;
  1.2400 +      voiceInfo.relSignalStrength = null;
  1.2401 +    } else {
  1.2402 +      voiceInfo.cell = newInfo.cell;
  1.2403 +      voiceInfo.network = this.operatorInfo;
  1.2404 +    }
  1.2405 +
  1.2406 +    if (!batch) {
  1.2407 +      gMessageManager.sendMobileConnectionMessage("RIL:VoiceInfoChanged",
  1.2408 +                                                  this.clientId, voiceInfo);
  1.2409 +    }
  1.2410 +  },
  1.2411 +
  1.2412 +  /**
  1.2413 +   * Handle the data connection's state has changed.
  1.2414 +   *
  1.2415 +   * @param newInfo The new data connection information.
  1.2416 +   * @param batch   When batch is true, the RIL:DataInfoChanged message will
  1.2417 +   *                not be sent.
  1.2418 +   */
  1.2419 +  updateDataConnection: function(newInfo, batch) {
  1.2420 +    let dataInfo = this.rilContext.data;
  1.2421 +    dataInfo.state = newInfo.state;
  1.2422 +    dataInfo.roaming = newInfo.roaming;
  1.2423 +    dataInfo.emergencyCallsOnly = newInfo.emergencyCallsOnly;
  1.2424 +    dataInfo.type = newInfo.type;
  1.2425 +    // For the data connection, the `connected` flag indicates whether
  1.2426 +    // there's an active data call.
  1.2427 +    dataInfo.connected = false;
  1.2428 +    if (gNetworkManager.active &&
  1.2429 +        gNetworkManager.active.type ===
  1.2430 +          Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE &&
  1.2431 +        gNetworkManager.active.serviceId === this.clientId) {
  1.2432 +      dataInfo.connected = true;
  1.2433 +    }
  1.2434 +
  1.2435 +    // Make sure we also reset the operator and signal strength information
  1.2436 +    // if we drop off the network.
  1.2437 +    if (newInfo.state !== RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED) {
  1.2438 +      dataInfo.cell = null;
  1.2439 +      dataInfo.network = null;
  1.2440 +      dataInfo.signalStrength = null;
  1.2441 +      dataInfo.relSignalStrength = null;
  1.2442 +    } else {
  1.2443 +      dataInfo.cell = newInfo.cell;
  1.2444 +      dataInfo.network = this.operatorInfo;
  1.2445 +    }
  1.2446 +
  1.2447 +    if (!batch) {
  1.2448 +      gMessageManager.sendMobileConnectionMessage("RIL:DataInfoChanged",
  1.2449 +                                                  this.clientId, dataInfo);
  1.2450 +    }
  1.2451 +
  1.2452 +    let connHandler = gDataConnectionManager.getConnectionHandler(this.clientId);
  1.2453 +    connHandler.updateRILNetworkInterface();
  1.2454 +  },
  1.2455 +
  1.2456 +  getPreferredNetworkType: function(target, message) {
  1.2457 +    this.workerMessenger.send("getPreferredNetworkType", message, (function(response) {
  1.2458 +      if (response.success) {
  1.2459 +        response.type = RIL.RIL_PREFERRED_NETWORK_TYPE_TO_GECKO[response.networkType];
  1.2460 +      }
  1.2461 +
  1.2462 +      target.sendAsyncMessage("RIL:GetPreferredNetworkType", {
  1.2463 +        clientId: this.clientId,
  1.2464 +        data: response
  1.2465 +      });
  1.2466 +      return false;
  1.2467 +    }).bind(this));
  1.2468 +  },
  1.2469 +
  1.2470 +  setPreferredNetworkType: function(target, message) {
  1.2471 +    let networkType = RIL.RIL_PREFERRED_NETWORK_TYPE_TO_GECKO.indexOf(message.type);
  1.2472 +    if (networkType < 0) {
  1.2473 +      message.errorMsg = RIL.GECKO_ERROR_INVALID_PARAMETER;
  1.2474 +      target.sendAsyncMessage("RIL:SetPreferredNetworkType", {
  1.2475 +        clientId: this.clientId,
  1.2476 +        data: message
  1.2477 +      });
  1.2478 +      return false;
  1.2479 +    }
  1.2480 +    message.networkType = networkType;
  1.2481 +
  1.2482 +    this.workerMessenger.send("setPreferredNetworkType", message, (function(response) {
  1.2483 +      target.sendAsyncMessage("RIL:SetPreferredNetworkType", {
  1.2484 +        clientId: this.clientId,
  1.2485 +        data: response
  1.2486 +      });
  1.2487 +      return false;
  1.2488 +    }).bind(this));
  1.2489 +  },
  1.2490 +
  1.2491 +  setCellBroadcastSearchList: function(newSearchList) {
  1.2492 +    if ((newSearchList == this._cellBroadcastSearchList) ||
  1.2493 +          (newSearchList && this._cellBroadcastSearchList &&
  1.2494 +            newSearchList.gsm == this._cellBroadcastSearchList.gsm &&
  1.2495 +            newSearchList.cdma == this._cellBroadcastSearchList.cdma)) {
  1.2496 +      return;
  1.2497 +    }
  1.2498 +
  1.2499 +    this.workerMessenger.send("setCellBroadcastSearchList",
  1.2500 +                              { searchList: newSearchList },
  1.2501 +                              (function callback(response) {
  1.2502 +      if (!response.success) {
  1.2503 +        let lock = gSettingsService.createLock();
  1.2504 +        lock.set(kSettingsCellBroadcastSearchList,
  1.2505 +                 this._cellBroadcastSearchList, null);
  1.2506 +      } else {
  1.2507 +        this._cellBroadcastSearchList = response.searchList;
  1.2508 +      }
  1.2509 +
  1.2510 +      return false;
  1.2511 +    }).bind(this));
  1.2512 +  },
  1.2513 +
  1.2514 +  /**
  1.2515 +   * Handle signal strength changes.
  1.2516 +   *
  1.2517 +   * @param message The new signal strength.
  1.2518 +   * @param batch   When batch is true, the RIL:VoiceInfoChanged and
  1.2519 +   *                RIL:DataInfoChanged message will not be sent.
  1.2520 +   */
  1.2521 +  handleSignalStrengthChange: function(message, batch) {
  1.2522 +    let voiceInfo = this.rilContext.voice;
  1.2523 +    // If the voice is not registered, need not to update signal information.
  1.2524 +    if (voiceInfo.state === RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED &&
  1.2525 +        this.isInfoChanged(message.voice, voiceInfo)) {
  1.2526 +      this.updateInfo(message.voice, voiceInfo);
  1.2527 +      if (!batch) {
  1.2528 +        gMessageManager.sendMobileConnectionMessage("RIL:VoiceInfoChanged",
  1.2529 +                                                    this.clientId, voiceInfo);
  1.2530 +      }
  1.2531 +    }
  1.2532 +
  1.2533 +    let dataInfo = this.rilContext.data;
  1.2534 +    // If the data is not registered, need not to update signal information.
  1.2535 +    if (dataInfo.state === RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED &&
  1.2536 +        this.isInfoChanged(message.data, dataInfo)) {
  1.2537 +      this.updateInfo(message.data, dataInfo);
  1.2538 +      if (!batch) {
  1.2539 +        gMessageManager.sendMobileConnectionMessage("RIL:DataInfoChanged",
  1.2540 +                                                    this.clientId, dataInfo);
  1.2541 +      }
  1.2542 +    }
  1.2543 +  },
  1.2544 +
  1.2545 +  /**
  1.2546 +   * Handle operator information changes.
  1.2547 +   *
  1.2548 +   * @param message The new operator information.
  1.2549 +   * @param batch   When batch is true, the RIL:VoiceInfoChanged and
  1.2550 +   *                RIL:DataInfoChanged message will not be sent.
  1.2551 +   */
  1.2552 +  handleOperatorChange: function(message, batch) {
  1.2553 +    let operatorInfo = this.operatorInfo;
  1.2554 +    let voice = this.rilContext.voice;
  1.2555 +    let data = this.rilContext.data;
  1.2556 +
  1.2557 +    if (this.isInfoChanged(message, operatorInfo)) {
  1.2558 +      this.updateInfo(message, operatorInfo);
  1.2559 +
  1.2560 +      // Update lastKnownNetwork
  1.2561 +      if (message.mcc && message.mnc) {
  1.2562 +        this._lastKnownNetwork = message.mcc + "-" + message.mnc;
  1.2563 +      }
  1.2564 +
  1.2565 +      // If the voice is unregistered, no need to send RIL:VoiceInfoChanged.
  1.2566 +      if (voice.network && !batch) {
  1.2567 +        gMessageManager.sendMobileConnectionMessage("RIL:VoiceInfoChanged",
  1.2568 +                                                    this.clientId, voice);
  1.2569 +      }
  1.2570 +
  1.2571 +      // If the data is unregistered, no need to send RIL:DataInfoChanged.
  1.2572 +      if (data.network && !batch) {
  1.2573 +        gMessageManager.sendMobileConnectionMessage("RIL:DataInfoChanged",
  1.2574 +                                                    this.clientId, data);
  1.2575 +      }
  1.2576 +    }
  1.2577 +  },
  1.2578 +
  1.2579 +  handleOtaStatus: function(message) {
  1.2580 +    if (message.status < 0 ||
  1.2581 +        RIL.CDMA_OTA_PROVISION_STATUS_TO_GECKO.length <= message.status) {
  1.2582 +      return;
  1.2583 +    }
  1.2584 +
  1.2585 +    let status = RIL.CDMA_OTA_PROVISION_STATUS_TO_GECKO[message.status];
  1.2586 +
  1.2587 +    gMessageManager.sendMobileConnectionMessage("RIL:OtaStatusChanged",
  1.2588 +                                                this.clientId, status);
  1.2589 +  },
  1.2590 +
  1.2591 +  _convertRadioState: function(state) {
  1.2592 +    switch (state) {
  1.2593 +      case RIL.GECKO_RADIOSTATE_OFF:
  1.2594 +        return RIL.GECKO_DETAILED_RADIOSTATE_DISABLED;
  1.2595 +      case RIL.GECKO_RADIOSTATE_READY:
  1.2596 +        return RIL.GECKO_DETAILED_RADIOSTATE_ENABLED;
  1.2597 +      default:
  1.2598 +        return RIL.GECKO_DETAILED_RADIOSTATE_UNKNOWN;
  1.2599 +    }
  1.2600 +  },
  1.2601 +
  1.2602 +  handleRadioStateChange: function(message) {
  1.2603 +    let newState = message.radioState;
  1.2604 +    if (this.rilContext.radioState == newState) {
  1.2605 +      return;
  1.2606 +    }
  1.2607 +    this.rilContext.radioState = newState;
  1.2608 +    this.handleDetailedRadioStateChanged(this._convertRadioState(newState));
  1.2609 +
  1.2610 +    //TODO Should we notify this change as a card state change?
  1.2611 +  },
  1.2612 +
  1.2613 +  handleDetailedRadioStateChanged: function(state) {
  1.2614 +    if (this.rilContext.detailedRadioState == state) {
  1.2615 +      return;
  1.2616 +    }
  1.2617 +    this.rilContext.detailedRadioState = state;
  1.2618 +    gMessageManager.sendMobileConnectionMessage("RIL:RadioStateChanged",
  1.2619 +                                                this.clientId, state);
  1.2620 +  },
  1.2621 +
  1.2622 +  setDataRegistration: function(attach) {
  1.2623 +    this.workerMessenger.send("setDataRegistration", {attach: attach});
  1.2624 +  },
  1.2625 +
  1.2626 +  /**
  1.2627 +   * TODO: Bug 911713 - B2G NetworkManager: Move policy control logic to
  1.2628 +   *                    NetworkManager
  1.2629 +   */
  1.2630 +  updateRILNetworkInterface: function() {
  1.2631 +    let connHandler = gDataConnectionManager.getConnectionHandler(this.clientId);
  1.2632 +    connHandler.updateRILNetworkInterface();
  1.2633 +  },
  1.2634 +
  1.2635 +  /**
  1.2636 +   * Update network selection mode
  1.2637 +   */
  1.2638 +  updateNetworkSelectionMode: function(message) {
  1.2639 +    if (DEBUG) this.debug("updateNetworkSelectionMode: " + JSON.stringify(message));
  1.2640 +    this.rilContext.networkSelectionMode = message.mode;
  1.2641 +    gMessageManager.sendMobileConnectionMessage("RIL:NetworkSelectionModeChanged",
  1.2642 +                                                this.clientId, message);
  1.2643 +  },
  1.2644 +
  1.2645 +  /**
  1.2646 +   * Handle emergency callback mode change.
  1.2647 +   */
  1.2648 +  handleEmergencyCbModeChange: function(message) {
  1.2649 +    if (DEBUG) this.debug("handleEmergencyCbModeChange: " + JSON.stringify(message));
  1.2650 +    gMessageManager.sendMobileConnectionMessage("RIL:EmergencyCbModeChanged",
  1.2651 +                                                this.clientId, message);
  1.2652 +  },
  1.2653 +
  1.2654 +  /**
  1.2655 +   * Handle WDP port push PDU. Constructor WDP bearer information and deliver
  1.2656 +   * to WapPushManager.
  1.2657 +   *
  1.2658 +   * @param message
  1.2659 +   *        A SMS message.
  1.2660 +   */
  1.2661 +  handleSmsWdpPortPush: function(message) {
  1.2662 +    if (message.encoding != RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
  1.2663 +      if (DEBUG) {
  1.2664 +        this.debug("Got port addressed SMS but not encoded in 8-bit alphabet." +
  1.2665 +                   " Drop!");
  1.2666 +      }
  1.2667 +      return;
  1.2668 +    }
  1.2669 +
  1.2670 +    let options = {
  1.2671 +      bearer: WAP.WDP_BEARER_GSM_SMS_GSM_MSISDN,
  1.2672 +      sourceAddress: message.sender,
  1.2673 +      sourcePort: message.originatorPort,
  1.2674 +      destinationAddress: this.rilContext.iccInfo.msisdn,
  1.2675 +      destinationPort: message.destinationPort,
  1.2676 +      serviceId: this.clientId
  1.2677 +    };
  1.2678 +    WAP.WapPushManager.receiveWdpPDU(message.fullData, message.fullData.length,
  1.2679 +                                     0, options);
  1.2680 +  },
  1.2681 +
  1.2682 +  /**
  1.2683 +   * A helper to broadcast the system message to launch registered apps
  1.2684 +   * like Costcontrol, Notification and Message app... etc.
  1.2685 +   *
  1.2686 +   * @param aName
  1.2687 +   *        The system message name.
  1.2688 +   * @param aDomMessage
  1.2689 +   *        The nsIDOMMozSmsMessage object.
  1.2690 +   */
  1.2691 +  broadcastSmsSystemMessage: function(aName, aDomMessage) {
  1.2692 +    if (DEBUG) this.debug("Broadcasting the SMS system message: " + aName);
  1.2693 +
  1.2694 +    // Sadly we cannot directly broadcast the aDomMessage object
  1.2695 +    // because the system message mechamism will rewrap the object
  1.2696 +    // based on the content window, which needs to know the properties.
  1.2697 +    gSystemMessenger.broadcastMessage(aName, {
  1.2698 +      iccId:             aDomMessage.iccId,
  1.2699 +      type:              aDomMessage.type,
  1.2700 +      id:                aDomMessage.id,
  1.2701 +      threadId:          aDomMessage.threadId,
  1.2702 +      delivery:          aDomMessage.delivery,
  1.2703 +      deliveryStatus:    aDomMessage.deliveryStatus,
  1.2704 +      sender:            aDomMessage.sender,
  1.2705 +      receiver:          aDomMessage.receiver,
  1.2706 +      body:              aDomMessage.body,
  1.2707 +      messageClass:      aDomMessage.messageClass,
  1.2708 +      timestamp:         aDomMessage.timestamp,
  1.2709 +      sentTimestamp:     aDomMessage.sentTimestamp,
  1.2710 +      deliveryTimestamp: aDomMessage.deliveryTimestamp,
  1.2711 +      read:              aDomMessage.read
  1.2712 +    });
  1.2713 +  },
  1.2714 +
  1.2715 +  // The following attributes/functions are used for acquiring/releasing the
  1.2716 +  // CPU wake lock when the RIL handles the received SMS. Note that we need
  1.2717 +  // a timer to bound the lock's life cycle to avoid exhausting the battery.
  1.2718 +  _smsHandledWakeLock: null,
  1.2719 +  _smsHandledWakeLockTimer: null,
  1.2720 +
  1.2721 +  _acquireSmsHandledWakeLock: function() {
  1.2722 +    if (!this._smsHandledWakeLock) {
  1.2723 +      if (DEBUG) this.debug("Acquiring a CPU wake lock for handling SMS.");
  1.2724 +      this._smsHandledWakeLock = gPowerManagerService.newWakeLock("cpu");
  1.2725 +    }
  1.2726 +    if (!this._smsHandledWakeLockTimer) {
  1.2727 +      if (DEBUG) this.debug("Creating a timer for releasing the CPU wake lock.");
  1.2728 +      this._smsHandledWakeLockTimer =
  1.2729 +        Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  1.2730 +    }
  1.2731 +    if (DEBUG) this.debug("Setting the timer for releasing the CPU wake lock.");
  1.2732 +    this._smsHandledWakeLockTimer
  1.2733 +        .initWithCallback(this._releaseSmsHandledWakeLock.bind(this),
  1.2734 +                          SMS_HANDLED_WAKELOCK_TIMEOUT,
  1.2735 +                          Ci.nsITimer.TYPE_ONE_SHOT);
  1.2736 +  },
  1.2737 +
  1.2738 +  _releaseSmsHandledWakeLock: function() {
  1.2739 +    if (DEBUG) this.debug("Releasing the CPU wake lock for handling SMS.");
  1.2740 +    if (this._smsHandledWakeLockTimer) {
  1.2741 +      this._smsHandledWakeLockTimer.cancel();
  1.2742 +    }
  1.2743 +    if (this._smsHandledWakeLock) {
  1.2744 +      this._smsHandledWakeLock.unlock();
  1.2745 +      this._smsHandledWakeLock = null;
  1.2746 +    }
  1.2747 +  },
  1.2748 +
  1.2749 +  /**
  1.2750 +   * Hash map for received multipart sms fragments. Messages are hashed with
  1.2751 +   * its sender address and concatenation reference number. Three additional
  1.2752 +   * attributes `segmentMaxSeq`, `receivedSegments`, `segments` are inserted.
  1.2753 +   */
  1.2754 +  _receivedSmsSegmentsMap: null,
  1.2755 +
  1.2756 +  /**
  1.2757 +   * Helper for processing received multipart SMS.
  1.2758 +   *
  1.2759 +   * @return null for handled segments, and an object containing full message
  1.2760 +   *         body/data once all segments are received.
  1.2761 +   */
  1.2762 +  _processReceivedSmsSegment: function(aSegment) {
  1.2763 +
  1.2764 +    // Directly replace full message body for single SMS.
  1.2765 +    if (!(aSegment.segmentMaxSeq && (aSegment.segmentMaxSeq > 1))) {
  1.2766 +      if (aSegment.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
  1.2767 +        aSegment.fullData = aSegment.data;
  1.2768 +      } else {
  1.2769 +        aSegment.fullBody = aSegment.body;
  1.2770 +      }
  1.2771 +      return aSegment;
  1.2772 +    }
  1.2773 +
  1.2774 +    // Handle Concatenation for Class 0 SMS
  1.2775 +    let hash = aSegment.sender + ":" +
  1.2776 +               aSegment.segmentRef + ":" +
  1.2777 +               aSegment.segmentMaxSeq;
  1.2778 +    let seq = aSegment.segmentSeq;
  1.2779 +
  1.2780 +    let options = this._receivedSmsSegmentsMap[hash];
  1.2781 +    if (!options) {
  1.2782 +      options = aSegment;
  1.2783 +      this._receivedSmsSegmentsMap[hash] = options;
  1.2784 +
  1.2785 +      options.receivedSegments = 0;
  1.2786 +      options.segments = [];
  1.2787 +    } else if (options.segments[seq]) {
  1.2788 +      // Duplicated segment?
  1.2789 +      if (DEBUG) {
  1.2790 +        this.debug("Got duplicated segment no." + seq +
  1.2791 +                           " of a multipart SMS: " + JSON.stringify(aSegment));
  1.2792 +      }
  1.2793 +      return null;
  1.2794 +    }
  1.2795 +
  1.2796 +    if (options.receivedSegments > 0) {
  1.2797 +      // Update received timestamp.
  1.2798 +      options.timestamp = aSegment.timestamp;
  1.2799 +    }
  1.2800 +
  1.2801 +    if (options.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
  1.2802 +      options.segments[seq] = aSegment.data;
  1.2803 +    } else {
  1.2804 +      options.segments[seq] = aSegment.body;
  1.2805 +    }
  1.2806 +    options.receivedSegments++;
  1.2807 +
  1.2808 +    // The port information is only available in 1st segment for CDMA WAP Push.
  1.2809 +    // If the segments of a WAP Push are not received in sequence
  1.2810 +    // (e.g., SMS with seq == 1 is not the 1st segment received by the device),
  1.2811 +    // we have to retrieve the port information from 1st segment and
  1.2812 +    // save it into the cached options.
  1.2813 +    if (aSegment.teleservice === RIL.PDU_CDMA_MSG_TELESERIVCIE_ID_WAP
  1.2814 +        && seq === 1) {
  1.2815 +      if (!options.originatorPort && aSegment.originatorPort) {
  1.2816 +        options.originatorPort = aSegment.originatorPort;
  1.2817 +      }
  1.2818 +
  1.2819 +      if (!options.destinationPort && aSegment.destinationPort) {
  1.2820 +        options.destinationPort = aSegment.destinationPort;
  1.2821 +      }
  1.2822 +    }
  1.2823 +
  1.2824 +    if (options.receivedSegments < options.segmentMaxSeq) {
  1.2825 +      if (DEBUG) {
  1.2826 +        this.debug("Got segment no." + seq + " of a multipart SMS: " +
  1.2827 +                           JSON.stringify(options));
  1.2828 +      }
  1.2829 +      return null;
  1.2830 +    }
  1.2831 +
  1.2832 +    // Remove from map
  1.2833 +    delete this._receivedSmsSegmentsMap[hash];
  1.2834 +
  1.2835 +    // Rebuild full body
  1.2836 +    if (options.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
  1.2837 +      // Uint8Array doesn't have `concat`, so we have to merge all segements
  1.2838 +      // by hand.
  1.2839 +      let fullDataLen = 0;
  1.2840 +      for (let i = 1; i <= options.segmentMaxSeq; i++) {
  1.2841 +        fullDataLen += options.segments[i].length;
  1.2842 +      }
  1.2843 +
  1.2844 +      options.fullData = new Uint8Array(fullDataLen);
  1.2845 +      for (let d= 0, i = 1; i <= options.segmentMaxSeq; i++) {
  1.2846 +        let data = options.segments[i];
  1.2847 +        for (let j = 0; j < data.length; j++) {
  1.2848 +          options.fullData[d++] = data[j];
  1.2849 +        }
  1.2850 +      }
  1.2851 +    } else {
  1.2852 +      options.fullBody = options.segments.join("");
  1.2853 +    }
  1.2854 +
  1.2855 +    // Remove handy fields after completing the concatenation.
  1.2856 +    delete options.receivedSegments;
  1.2857 +    delete options.segments;
  1.2858 +
  1.2859 +    if (DEBUG) {
  1.2860 +      this.debug("Got full multipart SMS: " + JSON.stringify(options));
  1.2861 +    }
  1.2862 +
  1.2863 +    return options;
  1.2864 +  },
  1.2865 +
  1.2866 +  /**
  1.2867 +   * Helper to create Savable SmsSegment.
  1.2868 +   */
  1.2869 +  _createSavableSmsSegment: function(aMessage) {
  1.2870 +    // We precisely define what data fields to be stored into
  1.2871 +    // DB here for better data migration.
  1.2872 +    let segment = {};
  1.2873 +    segment.messageType = aMessage.messageType;
  1.2874 +    segment.teleservice = aMessage.teleservice;
  1.2875 +    segment.SMSC = aMessage.SMSC;
  1.2876 +    segment.sentTimestamp = aMessage.sentTimestamp;
  1.2877 +    segment.timestamp = Date.now();
  1.2878 +    segment.sender = aMessage.sender;
  1.2879 +    segment.pid = aMessage.pid;
  1.2880 +    segment.encoding = aMessage.encoding;
  1.2881 +    segment.messageClass = aMessage.messageClass;
  1.2882 +    segment.iccId = this.getIccId();
  1.2883 +    if (aMessage.header) {
  1.2884 +      segment.segmentRef = aMessage.header.segmentRef;
  1.2885 +      segment.segmentSeq = aMessage.header.segmentSeq;
  1.2886 +      segment.segmentMaxSeq = aMessage.header.segmentMaxSeq;
  1.2887 +      segment.originatorPort = aMessage.header.originatorPort;
  1.2888 +      segment.destinationPort = aMessage.header.destinationPort;
  1.2889 +    }
  1.2890 +    segment.mwiPresent = (aMessage.mwi)? true: false;
  1.2891 +    segment.mwiDiscard = (segment.mwiPresent)? aMessage.mwi.discard: false;
  1.2892 +    segment.mwiMsgCount = (segment.mwiPresent)? aMessage.mwi.msgCount: 0;
  1.2893 +    segment.mwiActive = (segment.mwiPresent)? aMessage.mwi.active: false;
  1.2894 +    segment.serviceCategory = aMessage.serviceCategory;
  1.2895 +    segment.language = aMessage.language;
  1.2896 +    segment.data = aMessage.data;
  1.2897 +    segment.body = aMessage.body;
  1.2898 +
  1.2899 +    return segment;
  1.2900 +  },
  1.2901 +
  1.2902 +  /**
  1.2903 +   * Helper to purge complete message.
  1.2904 +   *
  1.2905 +   * We remove unnessary fields defined in _createSavableSmsSegment() after
  1.2906 +   * completing the concatenation.
  1.2907 +   */
  1.2908 +  _purgeCompleteSmsMessage: function(aMessage) {
  1.2909 +    // Purge concatenation info
  1.2910 +    delete aMessage.segmentRef;
  1.2911 +    delete aMessage.segmentSeq;
  1.2912 +    delete aMessage.segmentMaxSeq;
  1.2913 +
  1.2914 +    // Purge partial message body
  1.2915 +    delete aMessage.data;
  1.2916 +    delete aMessage.body;
  1.2917 +  },
  1.2918 +
  1.2919 +  /**
  1.2920 +   * handle concatenation of received SMS.
  1.2921 +   */
  1.2922 +  handleSmsMultipart: function(aMessage) {
  1.2923 +    if (DEBUG) this.debug("handleSmsMultipart: " + JSON.stringify(aMessage));
  1.2924 +
  1.2925 +    this._acquireSmsHandledWakeLock();
  1.2926 +
  1.2927 +    let segment = this._createSavableSmsSegment(aMessage);
  1.2928 +
  1.2929 +    let isMultipart = (segment.segmentMaxSeq && (segment.segmentMaxSeq > 1));
  1.2930 +    let messageClass = segment.messageClass;
  1.2931 +
  1.2932 +    let handleReceivedAndAck = function(aRvOfIncompleteMsg, aCompleteMessage) {
  1.2933 +      if (aCompleteMessage) {
  1.2934 +        this._purgeCompleteSmsMessage(aCompleteMessage);
  1.2935 +        if (this.handleSmsReceived(aCompleteMessage)) {
  1.2936 +          this.sendAckSms(Cr.NS_OK, aCompleteMessage);
  1.2937 +        }
  1.2938 +        // else Ack will be sent after further process in handleSmsReceived.
  1.2939 +      } else {
  1.2940 +        this.sendAckSms(aRvOfIncompleteMsg, segment);
  1.2941 +      }
  1.2942 +    }.bind(this);
  1.2943 +
  1.2944 +    // No need to access SmsSegmentStore for Class 0 SMS and Single SMS.
  1.2945 +    if (!isMultipart ||
  1.2946 +        (messageClass == RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0])) {
  1.2947 +      // `When a mobile terminated message is class 0 and the MS has the
  1.2948 +      // capability of displaying short messages, the MS shall display the
  1.2949 +      // message immediately and send an acknowledgement to the SC when the
  1.2950 +      // message has successfully reached the MS irrespective of whether
  1.2951 +      // there is memory available in the (U)SIM or ME. The message shall
  1.2952 +      // not be automatically stored in the (U)SIM or ME.`
  1.2953 +      // ~ 3GPP 23.038 clause 4
  1.2954 +
  1.2955 +      handleReceivedAndAck(Cr.NS_OK,  // ACK OK For Incomplete Class 0
  1.2956 +                           this._processReceivedSmsSegment(segment));
  1.2957 +    } else {
  1.2958 +      gMobileMessageDatabaseService
  1.2959 +        .saveSmsSegment(segment, function notifyResult(aRv, aCompleteMessage) {
  1.2960 +        handleReceivedAndAck(aRv,  // Ack according to the result after saving
  1.2961 +                             aCompleteMessage);
  1.2962 +      });
  1.2963 +    }
  1.2964 +  },
  1.2965 +
  1.2966 +  portAddressedSmsApps: null,
  1.2967 +  handleSmsReceived: function(message) {
  1.2968 +    if (DEBUG) this.debug("handleSmsReceived: " + JSON.stringify(message));
  1.2969 +
  1.2970 +    if (message.messageType == RIL.PDU_CDMA_MSG_TYPE_BROADCAST) {
  1.2971 +      gMessageManager.sendCellBroadcastMessage("RIL:CellBroadcastReceived",
  1.2972 +                                               this.clientId, message);
  1.2973 +      return true;
  1.2974 +    }
  1.2975 +
  1.2976 +    // Dispatch to registered handler if application port addressing is
  1.2977 +    // available. Note that the destination port can possibly be zero when
  1.2978 +    // representing a UDP/TCP port.
  1.2979 +    if (message.destinationPort != null) {
  1.2980 +      let handler = this.portAddressedSmsApps[message.destinationPort];
  1.2981 +      if (handler) {
  1.2982 +        handler(message);
  1.2983 +      }
  1.2984 +      return true;
  1.2985 +    }
  1.2986 +
  1.2987 +    if (message.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
  1.2988 +      // Don't know how to handle binary data yet.
  1.2989 +      return true;
  1.2990 +    }
  1.2991 +
  1.2992 +    message.type = "sms";
  1.2993 +    message.sender = message.sender || null;
  1.2994 +    message.receiver = this.getPhoneNumber();
  1.2995 +    message.body = message.fullBody = message.fullBody || null;
  1.2996 +
  1.2997 +    if (gSmsService.isSilentNumber(message.sender)) {
  1.2998 +      message.id = -1;
  1.2999 +      message.threadId = 0;
  1.3000 +      message.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
  1.3001 +      message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
  1.3002 +      message.read = false;
  1.3003 +
  1.3004 +      let domMessage =
  1.3005 +        gMobileMessageService.createSmsMessage(message.id,
  1.3006 +                                               message.threadId,
  1.3007 +                                               message.iccId,
  1.3008 +                                               message.delivery,
  1.3009 +                                               message.deliveryStatus,
  1.3010 +                                               message.sender,
  1.3011 +                                               message.receiver,
  1.3012 +                                               message.body,
  1.3013 +                                               message.messageClass,
  1.3014 +                                               message.timestamp,
  1.3015 +                                               message.sentTimestamp,
  1.3016 +                                               0,
  1.3017 +                                               message.read);
  1.3018 +
  1.3019 +      Services.obs.notifyObservers(domMessage,
  1.3020 +                                   kSilentSmsReceivedObserverTopic,
  1.3021 +                                   null);
  1.3022 +      return true;
  1.3023 +    }
  1.3024 +
  1.3025 +    if (message.mwiPresent) {
  1.3026 +      let mwi = {
  1.3027 +        discard: message.mwiDiscard,
  1.3028 +        msgCount: message.mwiMsgCount,
  1.3029 +        active: message.mwiActive
  1.3030 +      };
  1.3031 +      this.workerMessenger.send("updateMwis", { mwi: mwi });
  1.3032 +
  1.3033 +      mwi.returnNumber = message.sender;
  1.3034 +      mwi.returnMessage = message.fullBody;
  1.3035 +      gMessageManager.sendVoicemailMessage("RIL:VoicemailNotification",
  1.3036 +                                           this.clientId, mwi);
  1.3037 +
  1.3038 +      // Dicarded MWI comes without text body.
  1.3039 +      // Hence, we discard it here after notifying the MWI status.
  1.3040 +      if (message.mwiDiscard) {
  1.3041 +        return true;
  1.3042 +      }
  1.3043 +    }
  1.3044 +
  1.3045 +    let notifyReceived = function notifyReceived(rv, domMessage) {
  1.3046 +      let success = Components.isSuccessCode(rv);
  1.3047 +
  1.3048 +      this.sendAckSms(rv, message);
  1.3049 +
  1.3050 +      if (!success) {
  1.3051 +        // At this point we could send a message to content to notify the user
  1.3052 +        // that storing an incoming SMS failed, most likely due to a full disk.
  1.3053 +        if (DEBUG) {
  1.3054 +          this.debug("Could not store SMS, error code " + rv);
  1.3055 +        }
  1.3056 +        return;
  1.3057 +      }
  1.3058 +
  1.3059 +      this.broadcastSmsSystemMessage(kSmsReceivedObserverTopic, domMessage);
  1.3060 +      Services.obs.notifyObservers(domMessage, kSmsReceivedObserverTopic, null);
  1.3061 +    }.bind(this);
  1.3062 +
  1.3063 +    if (message.messageClass != RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0]) {
  1.3064 +      gMobileMessageDatabaseService.saveReceivedMessage(message,
  1.3065 +                                                        notifyReceived);
  1.3066 +    } else {
  1.3067 +      message.id = -1;
  1.3068 +      message.threadId = 0;
  1.3069 +      message.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
  1.3070 +      message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
  1.3071 +      message.read = false;
  1.3072 +
  1.3073 +      let domMessage =
  1.3074 +        gMobileMessageService.createSmsMessage(message.id,
  1.3075 +                                               message.threadId,
  1.3076 +                                               message.iccId,
  1.3077 +                                               message.delivery,
  1.3078 +                                               message.deliveryStatus,
  1.3079 +                                               message.sender,
  1.3080 +                                               message.receiver,
  1.3081 +                                               message.body,
  1.3082 +                                               message.messageClass,
  1.3083 +                                               message.timestamp,
  1.3084 +                                               message.sentTimestamp,
  1.3085 +                                               0,
  1.3086 +                                               message.read);
  1.3087 +
  1.3088 +      notifyReceived(Cr.NS_OK, domMessage);
  1.3089 +    }
  1.3090 +
  1.3091 +    // SMS ACK will be sent in notifyReceived. Return false here.
  1.3092 +    return false;
  1.3093 +  },
  1.3094 +
  1.3095 +  /**
  1.3096 +   * Handle ACK response of received SMS.
  1.3097 +   */
  1.3098 +  sendAckSms: function(aRv, aMessage) {
  1.3099 +    if (aMessage.messageClass === RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_2]) {
  1.3100 +      return;
  1.3101 +    }
  1.3102 +
  1.3103 +    let result = RIL.PDU_FCS_OK;
  1.3104 +    if (!Components.isSuccessCode(aRv)) {
  1.3105 +      if (DEBUG) this.debug("Failed to handle received sms: " + aRv);
  1.3106 +      result = (aRv === Cr.NS_ERROR_FILE_NO_DEVICE_SPACE)
  1.3107 +                ? RIL.PDU_FCS_MEMORY_CAPACITY_EXCEEDED
  1.3108 +                : RIL.PDU_FCS_UNSPECIFIED;
  1.3109 +    }
  1.3110 +
  1.3111 +    this.workerMessenger.send("ackSMS", { result: result });
  1.3112 +
  1.3113 +  },
  1.3114 +
  1.3115 +  /**
  1.3116 +   * Set the setting value of "time.clock.automatic-update.available".
  1.3117 +   */
  1.3118 +  setClockAutoUpdateAvailable: function(value) {
  1.3119 +    gSettingsService.createLock().set(kSettingsClockAutoUpdateAvailable, value, null,
  1.3120 +                                      "fromInternalSetting");
  1.3121 +  },
  1.3122 +
  1.3123 +  /**
  1.3124 +   * Set the setting value of "time.timezone.automatic-update.available".
  1.3125 +   */
  1.3126 +  setTimezoneAutoUpdateAvailable: function(value) {
  1.3127 +    gSettingsService.createLock().set(kSettingsTimezoneAutoUpdateAvailable, value, null,
  1.3128 +                                      "fromInternalSetting");
  1.3129 +  },
  1.3130 +
  1.3131 +  /**
  1.3132 +   * Set the system clock by NITZ.
  1.3133 +   */
  1.3134 +  setClockByNitz: function(message) {
  1.3135 +    // To set the system clock time. Note that there could be a time diff
  1.3136 +    // between when the NITZ was received and when the time is actually set.
  1.3137 +    gTimeService.set(
  1.3138 +      message.networkTimeInMS + (Date.now() - message.receiveTimeInMS));
  1.3139 +  },
  1.3140 +
  1.3141 +  /**
  1.3142 +   * Set the system time zone by NITZ.
  1.3143 +   */
  1.3144 +  setTimezoneByNitz: function(message) {
  1.3145 +    // To set the sytem timezone. Note that we need to convert the time zone
  1.3146 +    // value to a UTC repesentation string in the format of "UTC(+/-)hh:mm".
  1.3147 +    // Ex, time zone -480 is "UTC+08:00"; time zone 630 is "UTC-10:30".
  1.3148 +    //
  1.3149 +    // We can unapply the DST correction if we want the raw time zone offset:
  1.3150 +    // message.networkTimeZoneInMinutes -= message.networkDSTInMinutes;
  1.3151 +    if (message.networkTimeZoneInMinutes != (new Date()).getTimezoneOffset()) {
  1.3152 +      let absTimeZoneInMinutes = Math.abs(message.networkTimeZoneInMinutes);
  1.3153 +      let timeZoneStr = "UTC";
  1.3154 +      timeZoneStr += (message.networkTimeZoneInMinutes > 0 ? "-" : "+");
  1.3155 +      timeZoneStr += ("0" + Math.floor(absTimeZoneInMinutes / 60)).slice(-2);
  1.3156 +      timeZoneStr += ":";
  1.3157 +      timeZoneStr += ("0" + absTimeZoneInMinutes % 60).slice(-2);
  1.3158 +      gSettingsService.createLock().set("time.timezone", timeZoneStr, null);
  1.3159 +    }
  1.3160 +  },
  1.3161 +
  1.3162 +  /**
  1.3163 +   * Handle the NITZ message.
  1.3164 +   */
  1.3165 +  handleNitzTime: function(message) {
  1.3166 +    // Got the NITZ info received from the ril_worker.
  1.3167 +    this.setClockAutoUpdateAvailable(true);
  1.3168 +    this.setTimezoneAutoUpdateAvailable(true);
  1.3169 +
  1.3170 +    // Cache the latest NITZ message whenever receiving it.
  1.3171 +    this._lastNitzMessage = message;
  1.3172 +
  1.3173 +    // Set the received NITZ clock if the setting is enabled.
  1.3174 +    if (this._clockAutoUpdateEnabled) {
  1.3175 +      this.setClockByNitz(message);
  1.3176 +    }
  1.3177 +    // Set the received NITZ timezone if the setting is enabled.
  1.3178 +    if (this._timezoneAutoUpdateEnabled) {
  1.3179 +      this.setTimezoneByNitz(message);
  1.3180 +    }
  1.3181 +  },
  1.3182 +
  1.3183 +  /**
  1.3184 +   * Set the system clock by SNTP.
  1.3185 +   */
  1.3186 +  setClockBySntp: function(offset) {
  1.3187 +    // Got the SNTP info.
  1.3188 +    this.setClockAutoUpdateAvailable(true);
  1.3189 +    if (!this._clockAutoUpdateEnabled) {
  1.3190 +      return;
  1.3191 +    }
  1.3192 +    if (this._lastNitzMessage) {
  1.3193 +      if (DEBUG) debug("SNTP: NITZ available, discard SNTP");
  1.3194 +      return;
  1.3195 +    }
  1.3196 +    gTimeService.set(Date.now() + offset);
  1.3197 +  },
  1.3198 +
  1.3199 +  handleIccMbdn: function(message) {
  1.3200 +    let voicemailInfo = this.voicemailInfo;
  1.3201 +
  1.3202 +    voicemailInfo.number = message.number;
  1.3203 +    voicemailInfo.displayName = message.alphaId;
  1.3204 +
  1.3205 +    gMessageManager.sendVoicemailMessage("RIL:VoicemailInfoChanged",
  1.3206 +                                         this.clientId, voicemailInfo);
  1.3207 +  },
  1.3208 +
  1.3209 +  handleIccInfoChange: function(message) {
  1.3210 +    let oldSpn = this.rilContext.iccInfo ? this.rilContext.iccInfo.spn : null;
  1.3211 +
  1.3212 +    if (!message || !message.iccType) {
  1.3213 +      // Card is not detected, clear iccInfo to null.
  1.3214 +      this.rilContext.iccInfo = null;
  1.3215 +    } else {
  1.3216 +      if (!this.rilContext.iccInfo) {
  1.3217 +        if (message.iccType === "ruim" || message.iccType === "csim") {
  1.3218 +          this.rilContext.iccInfo = new CdmaIccInfo();
  1.3219 +        } else {
  1.3220 +          this.rilContext.iccInfo = new GsmIccInfo();
  1.3221 +        }
  1.3222 +      }
  1.3223 +
  1.3224 +      if (!this.isInfoChanged(message, this.rilContext.iccInfo)) {
  1.3225 +        return;
  1.3226 +      }
  1.3227 +
  1.3228 +      this.updateInfo(message, this.rilContext.iccInfo);
  1.3229 +    }
  1.3230 +
  1.3231 +    // RIL:IccInfoChanged corresponds to a DOM event that gets fired only
  1.3232 +    // when iccInfo has changed.
  1.3233 +    gMessageManager.sendIccMessage("RIL:IccInfoChanged",
  1.3234 +                                   this.clientId,
  1.3235 +                                   message.iccType ? message : null);
  1.3236 +
  1.3237 +    // Update lastKnownSimMcc.
  1.3238 +    if (message.mcc) {
  1.3239 +      try {
  1.3240 +        Services.prefs.setCharPref("ril.lastKnownSimMcc",
  1.3241 +                                   message.mcc.toString());
  1.3242 +      } catch (e) {}
  1.3243 +    }
  1.3244 +
  1.3245 +    // Update lastKnownHomeNetwork.
  1.3246 +    if (message.mcc && message.mnc) {
  1.3247 +      this._lastKnownHomeNetwork = message.mcc + "-" + message.mnc;
  1.3248 +    }
  1.3249 +
  1.3250 +    // If spn becomes available, we should check roaming again.
  1.3251 +    if (!oldSpn && message.spn) {
  1.3252 +      let voice = this.rilContext.voice;
  1.3253 +      let data = this.rilContext.data;
  1.3254 +      let voiceRoaming = voice.roaming;
  1.3255 +      let dataRoaming = data.roaming;
  1.3256 +      this.checkRoamingBetweenOperators(voice);
  1.3257 +      this.checkRoamingBetweenOperators(data);
  1.3258 +      if (voiceRoaming != voice.roaming) {
  1.3259 +        gMessageManager.sendMobileConnectionMessage("RIL:VoiceInfoChanged",
  1.3260 +                                                    this.clientId, voice);
  1.3261 +      }
  1.3262 +      if (dataRoaming != data.roaming) {
  1.3263 +        gMessageManager.sendMobileConnectionMessage("RIL:DataInfoChanged",
  1.3264 +                                                    this.clientId, data);
  1.3265 +      }
  1.3266 +    }
  1.3267 +  },
  1.3268 +
  1.3269 +  handleUSSDReceived: function(ussd) {
  1.3270 +    if (DEBUG) this.debug("handleUSSDReceived " + JSON.stringify(ussd));
  1.3271 +    gSystemMessenger.broadcastMessage("ussd-received", ussd);
  1.3272 +    gMessageManager.sendMobileConnectionMessage("RIL:USSDReceived",
  1.3273 +                                                this.clientId, ussd);
  1.3274 +  },
  1.3275 +
  1.3276 +  handleStkProactiveCommand: function(message) {
  1.3277 +    if (DEBUG) this.debug("handleStkProactiveCommand " + JSON.stringify(message));
  1.3278 +    let iccId = this.rilContext.iccInfo && this.rilContext.iccInfo.iccid;
  1.3279 +    if (iccId) {
  1.3280 +      gSystemMessenger.broadcastMessage("icc-stkcommand",
  1.3281 +                                        {iccId: iccId,
  1.3282 +                                         command: message});
  1.3283 +    }
  1.3284 +    gMessageManager.sendIccMessage("RIL:StkCommand", this.clientId, message);
  1.3285 +  },
  1.3286 +
  1.3287 +  handleExitEmergencyCbMode: function(message) {
  1.3288 +    if (DEBUG) this.debug("handleExitEmergencyCbMode: " + JSON.stringify(message));
  1.3289 +    gMessageManager.sendRequestResults("RIL:ExitEmergencyCbMode", message);
  1.3290 +  },
  1.3291 +
  1.3292 +  // nsIObserver
  1.3293 +
  1.3294 +  observe: function(subject, topic, data) {
  1.3295 +    switch (topic) {
  1.3296 +      case kMozSettingsChangedObserverTopic:
  1.3297 +        let setting = JSON.parse(data);
  1.3298 +        this.handleSettingsChange(setting.key, setting.value, setting.message);
  1.3299 +        break;
  1.3300 +      case NS_PREFBRANCH_PREFCHANGE_TOPIC_ID:
  1.3301 +        if (data === kPrefCellBroadcastDisabled) {
  1.3302 +          let value = false;
  1.3303 +          try {
  1.3304 +            value = Services.prefs.getBoolPref(kPrefCellBroadcastDisabled);
  1.3305 +          } catch(e) {}
  1.3306 +          this.workerMessenger.send("setCellBroadcastDisabled",
  1.3307 +                                    { disabled: value });
  1.3308 +        }
  1.3309 +        break;
  1.3310 +      case kSysClockChangeObserverTopic:
  1.3311 +        let offset = parseInt(data, 10);
  1.3312 +        if (this._lastNitzMessage) {
  1.3313 +          this._lastNitzMessage.receiveTimeInMS += offset;
  1.3314 +        }
  1.3315 +        this._sntp.updateOffset(offset);
  1.3316 +        break;
  1.3317 +      case kNetworkConnStateChangedTopic:
  1.3318 +        let network = subject.QueryInterface(Ci.nsINetworkInterface);
  1.3319 +        if (network.state != Ci.nsINetworkInterface.NETWORK_STATE_CONNECTED) {
  1.3320 +          return;
  1.3321 +        }
  1.3322 +
  1.3323 +        // SNTP can only update when we have mobile or Wifi connections.
  1.3324 +        if (network.type != Ci.nsINetworkInterface.NETWORK_TYPE_WIFI &&
  1.3325 +            network.type != Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE) {
  1.3326 +          return;
  1.3327 +        }
  1.3328 +
  1.3329 +        // If the network comes from RIL, make sure the RIL service is matched.
  1.3330 +        if (subject instanceof Ci.nsIRilNetworkInterface) {
  1.3331 +          network = subject.QueryInterface(Ci.nsIRilNetworkInterface);
  1.3332 +          if (network.serviceId != this.clientId) {
  1.3333 +            return;
  1.3334 +          }
  1.3335 +        }
  1.3336 +
  1.3337 +        // SNTP won't update unless the SNTP is already expired.
  1.3338 +        if (this._sntp.isExpired()) {
  1.3339 +          this._sntp.request();
  1.3340 +        }
  1.3341 +        break;
  1.3342 +      case kNetworkActiveChangedTopic:
  1.3343 +        let dataInfo = this.rilContext.data;
  1.3344 +        let connected = false;
  1.3345 +        if (gNetworkManager.active &&
  1.3346 +            gNetworkManager.active.type ===
  1.3347 +              Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE &&
  1.3348 +            gNetworkManager.active.serviceId === this.clientId) {
  1.3349 +          connected = true;
  1.3350 +        }
  1.3351 +        if (dataInfo.connected !== connected) {
  1.3352 +          dataInfo.connected = connected;
  1.3353 +          gMessageManager.sendMobileConnectionMessage("RIL:DataInfoChanged",
  1.3354 +                                                      this.clientId, dataInfo);
  1.3355 +        }
  1.3356 +        break;
  1.3357 +      case kScreenStateChangedTopic:
  1.3358 +        this.workerMessenger.send("setScreenState", { on: (data === "on") });
  1.3359 +        break;
  1.3360 +    }
  1.3361 +  },
  1.3362 +
  1.3363 +  supportedNetworkTypes: null,
  1.3364 +
  1.3365 +  // Flag to determine whether to update system clock automatically. It
  1.3366 +  // corresponds to the "time.clock.automatic-update.enabled" setting.
  1.3367 +  _clockAutoUpdateEnabled: null,
  1.3368 +
  1.3369 +  // Flag to determine whether to update system timezone automatically. It
  1.3370 +  // corresponds to the "time.clock.automatic-update.enabled" setting.
  1.3371 +  _timezoneAutoUpdateEnabled: null,
  1.3372 +
  1.3373 +  // Remember the last NITZ message so that we can set the time based on
  1.3374 +  // the network immediately when users enable network-based time.
  1.3375 +  _lastNitzMessage: null,
  1.3376 +
  1.3377 +  // Object that handles SNTP.
  1.3378 +  _sntp: null,
  1.3379 +
  1.3380 +  // Cell Broadcast settings values.
  1.3381 +  _cellBroadcastSearchList: null,
  1.3382 +
  1.3383 +  // Operator's mcc-mnc.
  1.3384 +  _lastKnownNetwork: null,
  1.3385 +
  1.3386 +  // ICC's mcc-mnc.
  1.3387 +  _lastKnownHomeNetwork: null,
  1.3388 +
  1.3389 +  handleSettingsChange: function(aName, aResult, aMessage) {
  1.3390 +    // Don't allow any content processes to modify the setting
  1.3391 +    // "time.clock.automatic-update.available" except for the chrome process.
  1.3392 +    if (aName === kSettingsClockAutoUpdateAvailable &&
  1.3393 +        aMessage !== "fromInternalSetting") {
  1.3394 +      let isClockAutoUpdateAvailable = this._lastNitzMessage !== null ||
  1.3395 +                                       this._sntp.isAvailable();
  1.3396 +      if (aResult !== isClockAutoUpdateAvailable) {
  1.3397 +        if (DEBUG) {
  1.3398 +          debug("Content processes cannot modify 'time.clock.automatic-update.available'. Restore!");
  1.3399 +        }
  1.3400 +        // Restore the setting to the current value.
  1.3401 +        this.setClockAutoUpdateAvailable(isClockAutoUpdateAvailable);
  1.3402 +      }
  1.3403 +    }
  1.3404 +
  1.3405 +    // Don't allow any content processes to modify the setting
  1.3406 +    // "time.timezone.automatic-update.available" except for the chrome
  1.3407 +    // process.
  1.3408 +    if (aName === kSettingsTimezoneAutoUpdateAvailable &&
  1.3409 +        aMessage !== "fromInternalSetting") {
  1.3410 +      let isTimezoneAutoUpdateAvailable = this._lastNitzMessage !== null;
  1.3411 +      if (aResult !== isTimezoneAutoUpdateAvailable) {
  1.3412 +        if (DEBUG) {
  1.3413 +          this.debug("Content processes cannot modify 'time.timezone.automatic-update.available'. Restore!");
  1.3414 +        }
  1.3415 +        // Restore the setting to the current value.
  1.3416 +        this.setTimezoneAutoUpdateAvailable(isTimezoneAutoUpdateAvailable);
  1.3417 +      }
  1.3418 +    }
  1.3419 +
  1.3420 +    this.handle(aName, aResult);
  1.3421 +  },
  1.3422 +
  1.3423 +  // nsISettingsServiceCallback
  1.3424 +  handle: function(aName, aResult) {
  1.3425 +    switch(aName) {
  1.3426 +      case kSettingsClockAutoUpdateEnabled:
  1.3427 +        this._clockAutoUpdateEnabled = aResult;
  1.3428 +        if (!this._clockAutoUpdateEnabled) {
  1.3429 +          break;
  1.3430 +        }
  1.3431 +
  1.3432 +        // Set the latest cached NITZ time if it's available.
  1.3433 +        if (this._lastNitzMessage) {
  1.3434 +          this.setClockByNitz(this._lastNitzMessage);
  1.3435 +        } else if (gNetworkManager.active && gNetworkManager.active.state ==
  1.3436 +                 Ci.nsINetworkInterface.NETWORK_STATE_CONNECTED) {
  1.3437 +          // Set the latest cached SNTP time if it's available.
  1.3438 +          if (!this._sntp.isExpired()) {
  1.3439 +            this.setClockBySntp(this._sntp.getOffset());
  1.3440 +          } else {
  1.3441 +            // Or refresh the SNTP.
  1.3442 +            this._sntp.request();
  1.3443 +          }
  1.3444 +        } else {
  1.3445 +          // Set a sane minimum time.
  1.3446 +          let buildTime = libcutils.property_get("ro.build.date.utc", "0") * 1000;
  1.3447 +          let file = FileUtils.File("/system/b2g/b2g");
  1.3448 +          if (file.lastModifiedTime > buildTime) {
  1.3449 +            buildTime = file.lastModifiedTime;
  1.3450 +          }
  1.3451 +          if (buildTime > Date.now()) {
  1.3452 +            gTimeService.set(buildTime);
  1.3453 +          }
  1.3454 +        }
  1.3455 +        break;
  1.3456 +      case kSettingsTimezoneAutoUpdateEnabled:
  1.3457 +        this._timezoneAutoUpdateEnabled = aResult;
  1.3458 +
  1.3459 +        if (this._timezoneAutoUpdateEnabled) {
  1.3460 +          // Apply the latest cached NITZ for timezone if it's available.
  1.3461 +          if (this._timezoneAutoUpdateEnabled && this._lastNitzMessage) {
  1.3462 +            this.setTimezoneByNitz(this._lastNitzMessage);
  1.3463 +          }
  1.3464 +        }
  1.3465 +        break;
  1.3466 +      case kSettingsCellBroadcastSearchList:
  1.3467 +        if (DEBUG) {
  1.3468 +          this.debug("'" + kSettingsCellBroadcastSearchList +
  1.3469 +            "' is now " + JSON.stringify(aResult));
  1.3470 +        }
  1.3471 +        // TODO: Set searchlist for Multi-SIM. See Bug 921326.
  1.3472 +        let result = Array.isArray(aResult) ? aResult[0] : aResult;
  1.3473 +        this.setCellBroadcastSearchList(result);
  1.3474 +        break;
  1.3475 +    }
  1.3476 +  },
  1.3477 +
  1.3478 +  handleError: function(aErrorMessage) {
  1.3479 +    if (DEBUG) {
  1.3480 +      this.debug("There was an error while reading RIL settings.");
  1.3481 +    }
  1.3482 +  },
  1.3483 +
  1.3484 +  // nsIRadioInterface
  1.3485 +
  1.3486 +  rilContext: null,
  1.3487 +
  1.3488 +  // Handle phone functions of nsIRILContentHelper
  1.3489 +
  1.3490 +  _sendCfStateChanged: function(message) {
  1.3491 +    gMessageManager.sendMobileConnectionMessage("RIL:CfStateChanged",
  1.3492 +                                                this.clientId, message);
  1.3493 +  },
  1.3494 +
  1.3495 +  _updateCallingLineIdRestrictionPref: function(mode) {
  1.3496 +    try {
  1.3497 +      Services.prefs.setIntPref(kPrefClirModePreference, mode);
  1.3498 +      Services.prefs.savePrefFile(null);
  1.3499 +      if (DEBUG) {
  1.3500 +        this.debug(kPrefClirModePreference + " pref is now " + mode);
  1.3501 +      }
  1.3502 +    } catch (e) {}
  1.3503 +  },
  1.3504 +
  1.3505 +  sendMMI: function(target, message) {
  1.3506 +    if (DEBUG) this.debug("SendMMI " + JSON.stringify(message));
  1.3507 +    this.workerMessenger.send("sendMMI", message, (function(response) {
  1.3508 +      if (response.isSetCallForward) {
  1.3509 +        this._sendCfStateChanged(response);
  1.3510 +      } else if (response.isSetCLIR && response.success) {
  1.3511 +        this._updateCallingLineIdRestrictionPref(response.clirMode);
  1.3512 +      }
  1.3513 +
  1.3514 +      target.sendAsyncMessage("RIL:SendMMI", {
  1.3515 +        clientId: this.clientId,
  1.3516 +        data: response
  1.3517 +      });
  1.3518 +      return false;
  1.3519 +    }).bind(this));
  1.3520 +  },
  1.3521 +
  1.3522 +  setCallForwardingOptions: function(target, message) {
  1.3523 +    if (DEBUG) this.debug("setCallForwardingOptions: " + JSON.stringify(message));
  1.3524 +    message.serviceClass = RIL.ICC_SERVICE_CLASS_VOICE;
  1.3525 +    this.workerMessenger.send("setCallForward", message, (function(response) {
  1.3526 +      this._sendCfStateChanged(response);
  1.3527 +      target.sendAsyncMessage("RIL:SetCallForwardingOptions", {
  1.3528 +        clientId: this.clientId,
  1.3529 +        data: response
  1.3530 +      });
  1.3531 +      return false;
  1.3532 +    }).bind(this));
  1.3533 +  },
  1.3534 +
  1.3535 +  setCallingLineIdRestriction: function(target, message) {
  1.3536 +    if (DEBUG) {
  1.3537 +      this.debug("setCallingLineIdRestriction: " + JSON.stringify(message));
  1.3538 +    }
  1.3539 +    this.workerMessenger.send("setCLIR", message, (function(response) {
  1.3540 +      if (response.success) {
  1.3541 +        this._updateCallingLineIdRestrictionPref(response.clirMode);
  1.3542 +      }
  1.3543 +      target.sendAsyncMessage("RIL:SetCallingLineIdRestriction", {
  1.3544 +        clientId: this.clientId,
  1.3545 +        data: response
  1.3546 +      });
  1.3547 +      return false;
  1.3548 +    }).bind(this));
  1.3549 +  },
  1.3550 +
  1.3551 +  isValidStateForSetRadioEnabled: function() {
  1.3552 +    let state = this.rilContext.detailedRadioState;
  1.3553 +    return state == RIL.GECKO_DETAILED_RADIOSTATE_ENABLED ||
  1.3554 +      state == RIL.GECKO_DETAILED_RADIOSTATE_DISABLED;
  1.3555 +  },
  1.3556 +
  1.3557 +  isDummyForSetRadioEnabled: function(message) {
  1.3558 +    let state = this.rilContext.detailedRadioState;
  1.3559 +    return (state == RIL.GECKO_DETAILED_RADIOSTATE_ENABLED && message.enabled) ||
  1.3560 +      (state == RIL.GECKO_DETAILED_RADIOSTATE_DISABLED && !message.enabled);
  1.3561 +  },
  1.3562 +
  1.3563 +  setRadioEnabledResponse: function(target, message, errorMsg) {
  1.3564 +    if (errorMsg) {
  1.3565 +      message.errorMsg = errorMsg;
  1.3566 +    }
  1.3567 +
  1.3568 +    target.sendAsyncMessage("RIL:SetRadioEnabled", {
  1.3569 +      clientId: this.clientId,
  1.3570 +      data: message
  1.3571 +    });
  1.3572 +  },
  1.3573 +
  1.3574 +  setRadioEnabled: function(target, message) {
  1.3575 +    if (DEBUG) {
  1.3576 +      this.debug("setRadioEnabled: " + JSON.stringify(message));
  1.3577 +    }
  1.3578 +
  1.3579 +    if (!this.isValidStateForSetRadioEnabled()) {
  1.3580 +      this.setRadioEnabledResponse(target, message, "InvalidStateError");
  1.3581 +      return;
  1.3582 +    }
  1.3583 +
  1.3584 +    if (this.isDummyForSetRadioEnabled(message)) {
  1.3585 +      this.setRadioEnabledResponse(target, message);
  1.3586 +      return;
  1.3587 +    }
  1.3588 +
  1.3589 +    let callback = (function(response) {
  1.3590 +      if (response.errorMsg) {
  1.3591 +        // Request fails. Rollback to the original radiostate.
  1.3592 +        let state = message.enabled ? RIL.GECKO_DETAILED_RADIOSTATE_DISABLED
  1.3593 +                                    : RIL.GECKO_DETAILED_RADIOSTATE_ENABLED;
  1.3594 +        this.handleDetailedRadioStateChanged(state);
  1.3595 +      }
  1.3596 +      this.setRadioEnabledResponse(target, response);
  1.3597 +      return false;
  1.3598 +    }).bind(this);
  1.3599 +
  1.3600 +    this.setRadioEnabledInternal(message, callback);
  1.3601 +  },
  1.3602 +
  1.3603 +  setRadioEnabledInternal: function(message, callback) {
  1.3604 +    let state = message.enabled ? RIL.GECKO_DETAILED_RADIOSTATE_ENABLING
  1.3605 +                                : RIL.GECKO_DETAILED_RADIOSTATE_DISABLING;
  1.3606 +    this.handleDetailedRadioStateChanged(state);
  1.3607 +    this.workerMessenger.send("setRadioEnabled", message, callback);
  1.3608 +  },
  1.3609 +
  1.3610 +  /**
  1.3611 +   * List of tuples of national language identifier pairs.
  1.3612 +   *
  1.3613 +   * TODO: Support static/runtime settings, see bug 733331.
  1.3614 +   */
  1.3615 +  enabledGsmTableTuples: [
  1.3616 +    [RIL.PDU_NL_IDENTIFIER_DEFAULT, RIL.PDU_NL_IDENTIFIER_DEFAULT],
  1.3617 +  ],
  1.3618 +
  1.3619 +  /**
  1.3620 +   * Use 16-bit reference number for concatenated outgoint messages.
  1.3621 +   *
  1.3622 +   * TODO: Support static/runtime settings, see bug 733331.
  1.3623 +   */
  1.3624 +  segmentRef16Bit: false,
  1.3625 +
  1.3626 +  /**
  1.3627 +   * Get valid SMS concatenation reference number.
  1.3628 +   */
  1.3629 +  _segmentRef: 0,
  1.3630 +  get nextSegmentRef() {
  1.3631 +    let ref = this._segmentRef++;
  1.3632 +
  1.3633 +    this._segmentRef %= (this.segmentRef16Bit ? 65535 : 255);
  1.3634 +
  1.3635 +    // 0 is not a valid SMS concatenation reference number.
  1.3636 +    return ref + 1;
  1.3637 +  },
  1.3638 +
  1.3639 +  /**
  1.3640 +   * Calculate encoded length using specified locking/single shift table
  1.3641 +   *
  1.3642 +   * @param message
  1.3643 +   *        message string to be encoded.
  1.3644 +   * @param langTable
  1.3645 +   *        locking shift table string.
  1.3646 +   * @param langShiftTable
  1.3647 +   *        single shift table string.
  1.3648 +   * @param strict7BitEncoding
  1.3649 +   *        Optional. Enable Latin characters replacement with corresponding
  1.3650 +   *        ones in GSM SMS 7-bit default alphabet.
  1.3651 +   *
  1.3652 +   * @return encoded length in septets.
  1.3653 +   *
  1.3654 +   * @note that the algorithm used in this function must match exactly with
  1.3655 +   * GsmPDUHelper#writeStringAsSeptets.
  1.3656 +   */
  1.3657 +  _countGsm7BitSeptets: function(message, langTable, langShiftTable, strict7BitEncoding) {
  1.3658 +    let length = 0;
  1.3659 +    for (let msgIndex = 0; msgIndex < message.length; msgIndex++) {
  1.3660 +      let c = message.charAt(msgIndex);
  1.3661 +      if (strict7BitEncoding) {
  1.3662 +        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
  1.3663 +      }
  1.3664 +
  1.3665 +      let septet = langTable.indexOf(c);
  1.3666 +
  1.3667 +      // According to 3GPP TS 23.038, section 6.1.1 General notes, "The
  1.3668 +      // characters marked '1)' are not used but are displayed as a space."
  1.3669 +      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
  1.3670 +        continue;
  1.3671 +      }
  1.3672 +
  1.3673 +      if (septet >= 0) {
  1.3674 +        length++;
  1.3675 +        continue;
  1.3676 +      }
  1.3677 +
  1.3678 +      septet = langShiftTable.indexOf(c);
  1.3679 +      if (septet < 0) {
  1.3680 +        if (!strict7BitEncoding) {
  1.3681 +          return -1;
  1.3682 +        }
  1.3683 +
  1.3684 +        // Bug 816082, when strict7BitEncoding is enabled, we should replace
  1.3685 +        // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
  1.3686 +        c = "*";
  1.3687 +        if (langTable.indexOf(c) >= 0) {
  1.3688 +          length++;
  1.3689 +        } else if (langShiftTable.indexOf(c) >= 0) {
  1.3690 +          length += 2;
  1.3691 +        } else {
  1.3692 +          // We can't even encode a '*' character with current configuration.
  1.3693 +          return -1;
  1.3694 +        }
  1.3695 +
  1.3696 +        continue;
  1.3697 +      }
  1.3698 +
  1.3699 +      // According to 3GPP TS 23.038 B.2, "This code represents a control
  1.3700 +      // character and therefore must not be used for language specific
  1.3701 +      // characters."
  1.3702 +      if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
  1.3703 +        continue;
  1.3704 +      }
  1.3705 +
  1.3706 +      // The character is not found in locking shfit table, but could be
  1.3707 +      // encoded as <escape><char> with single shift table. Note that it's
  1.3708 +      // still possible for septet to has the value of PDU_NL_EXTENDED_ESCAPE,
  1.3709 +      // but we can display it as a space in this case as said in previous
  1.3710 +      // comment.
  1.3711 +      length += 2;
  1.3712 +    }
  1.3713 +
  1.3714 +    return length;
  1.3715 +  },
  1.3716 +
  1.3717 +  /**
  1.3718 +   * Calculate user data length of specified message string encoded in GSM 7Bit
  1.3719 +   * alphabets.
  1.3720 +   *
  1.3721 +   * @param message
  1.3722 +   *        a message string to be encoded.
  1.3723 +   * @param strict7BitEncoding
  1.3724 +   *        Optional. Enable Latin characters replacement with corresponding
  1.3725 +   *        ones in GSM SMS 7-bit default alphabet.
  1.3726 +   *
  1.3727 +   * @return null or an options object with attributes `dcs`,
  1.3728 +   *         `userDataHeaderLength`, `encodedFullBodyLength`, `langIndex`,
  1.3729 +   *         `langShiftIndex`, `segmentMaxSeq` set.
  1.3730 +   *
  1.3731 +   * @see #_calculateUserDataLength().
  1.3732 +   */
  1.3733 +  _calculateUserDataLength7Bit: function(message, strict7BitEncoding) {
  1.3734 +    let options = null;
  1.3735 +    let minUserDataSeptets = Number.MAX_VALUE;
  1.3736 +    for (let i = 0; i < this.enabledGsmTableTuples.length; i++) {
  1.3737 +      let [langIndex, langShiftIndex] = this.enabledGsmTableTuples[i];
  1.3738 +
  1.3739 +      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[langIndex];
  1.3740 +      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[langShiftIndex];
  1.3741 +
  1.3742 +      let bodySeptets = this._countGsm7BitSeptets(message,
  1.3743 +                                                  langTable,
  1.3744 +                                                  langShiftTable,
  1.3745 +                                                  strict7BitEncoding);
  1.3746 +      if (bodySeptets < 0) {
  1.3747 +        continue;
  1.3748 +      }
  1.3749 +
  1.3750 +      let headerLen = 0;
  1.3751 +      if (langIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
  1.3752 +        headerLen += 3; // IEI + len + langIndex
  1.3753 +      }
  1.3754 +      if (langShiftIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
  1.3755 +        headerLen += 3; // IEI + len + langShiftIndex
  1.3756 +      }
  1.3757 +
  1.3758 +      // Calculate full user data length, note the extra byte is for header len
  1.3759 +      let headerSeptets = Math.ceil((headerLen ? headerLen + 1 : 0) * 8 / 7);
  1.3760 +      let segmentSeptets = RIL.PDU_MAX_USER_DATA_7BIT;
  1.3761 +      if ((bodySeptets + headerSeptets) > segmentSeptets) {
  1.3762 +        headerLen += this.segmentRef16Bit ? 6 : 5;
  1.3763 +        headerSeptets = Math.ceil((headerLen + 1) * 8 / 7);
  1.3764 +        segmentSeptets -= headerSeptets;
  1.3765 +      }
  1.3766 +
  1.3767 +      let segments = Math.ceil(bodySeptets / segmentSeptets);
  1.3768 +      let userDataSeptets = bodySeptets + headerSeptets * segments;
  1.3769 +      if (userDataSeptets >= minUserDataSeptets) {
  1.3770 +        continue;
  1.3771 +      }
  1.3772 +
  1.3773 +      minUserDataSeptets = userDataSeptets;
  1.3774 +
  1.3775 +      options = {
  1.3776 +        dcs: RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET,
  1.3777 +        encodedFullBodyLength: bodySeptets,
  1.3778 +        userDataHeaderLength: headerLen,
  1.3779 +        langIndex: langIndex,
  1.3780 +        langShiftIndex: langShiftIndex,
  1.3781 +        segmentMaxSeq: segments,
  1.3782 +        segmentChars: segmentSeptets,
  1.3783 +      };
  1.3784 +    }
  1.3785 +
  1.3786 +    return options;
  1.3787 +  },
  1.3788 +
  1.3789 +  /**
  1.3790 +   * Calculate user data length of specified message string encoded in UCS2.
  1.3791 +   *
  1.3792 +   * @param message
  1.3793 +   *        a message string to be encoded.
  1.3794 +   *
  1.3795 +   * @return an options object with attributes `dcs`, `userDataHeaderLength`,
  1.3796 +   *         `encodedFullBodyLength`, `segmentMaxSeq` set.
  1.3797 +   *
  1.3798 +   * @see #_calculateUserDataLength().
  1.3799 +   */
  1.3800 +  _calculateUserDataLengthUCS2: function(message) {
  1.3801 +    let bodyChars = message.length;
  1.3802 +    let headerLen = 0;
  1.3803 +    let headerChars = Math.ceil((headerLen ? headerLen + 1 : 0) / 2);
  1.3804 +    let segmentChars = RIL.PDU_MAX_USER_DATA_UCS2;
  1.3805 +    if ((bodyChars + headerChars) > segmentChars) {
  1.3806 +      headerLen += this.segmentRef16Bit ? 6 : 5;
  1.3807 +      headerChars = Math.ceil((headerLen + 1) / 2);
  1.3808 +      segmentChars -= headerChars;
  1.3809 +    }
  1.3810 +
  1.3811 +    let segments = Math.ceil(bodyChars / segmentChars);
  1.3812 +
  1.3813 +    return {
  1.3814 +      dcs: RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET,
  1.3815 +      encodedFullBodyLength: bodyChars * 2,
  1.3816 +      userDataHeaderLength: headerLen,
  1.3817 +      segmentMaxSeq: segments,
  1.3818 +      segmentChars: segmentChars,
  1.3819 +    };
  1.3820 +  },
  1.3821 +
  1.3822 +  /**
  1.3823 +   * Calculate user data length and its encoding.
  1.3824 +   *
  1.3825 +   * @param message
  1.3826 +   *        a message string to be encoded.
  1.3827 +   * @param strict7BitEncoding
  1.3828 +   *        Optional. Enable Latin characters replacement with corresponding
  1.3829 +   *        ones in GSM SMS 7-bit default alphabet.
  1.3830 +   *
  1.3831 +   * @return an options object with some or all of following attributes set:
  1.3832 +   *
  1.3833 +   * @param dcs
  1.3834 +   *        Data coding scheme. One of the PDU_DCS_MSG_CODING_*BITS_ALPHABET
  1.3835 +   *        constants.
  1.3836 +   * @param userDataHeaderLength
  1.3837 +   *        Length of embedded user data header, in bytes. The whole header
  1.3838 +   *        size will be userDataHeaderLength + 1; 0 for no header.
  1.3839 +   * @param encodedFullBodyLength
  1.3840 +   *        Length of the message body when encoded with the given DCS. For
  1.3841 +   *        UCS2, in bytes; for 7-bit, in septets.
  1.3842 +   * @param langIndex
  1.3843 +   *        Table index used for normal 7-bit encoded character lookup.
  1.3844 +   * @param langShiftIndex
  1.3845 +   *        Table index used for escaped 7-bit encoded character lookup.
  1.3846 +   * @param segmentMaxSeq
  1.3847 +   *        Max sequence number of a multi-part messages, or 1 for single one.
  1.3848 +   *        This number might not be accurate for a multi-part message until
  1.3849 +   *        it's processed by #_fragmentText() again.
  1.3850 +   */
  1.3851 +  _calculateUserDataLength: function(message, strict7BitEncoding) {
  1.3852 +    let options = this._calculateUserDataLength7Bit(message, strict7BitEncoding);
  1.3853 +    if (!options) {
  1.3854 +      options = this._calculateUserDataLengthUCS2(message);
  1.3855 +    }
  1.3856 +
  1.3857 +    if (DEBUG) this.debug("_calculateUserDataLength: " + JSON.stringify(options));
  1.3858 +    return options;
  1.3859 +  },
  1.3860 +
  1.3861 +  /**
  1.3862 +   * Fragment GSM 7-Bit encodable string for transmission.
  1.3863 +   *
  1.3864 +   * @param text
  1.3865 +   *        text string to be fragmented.
  1.3866 +   * @param langTable
  1.3867 +   *        locking shift table string.
  1.3868 +   * @param langShiftTable
  1.3869 +   *        single shift table string.
  1.3870 +   * @param segmentSeptets
  1.3871 +   *        Number of available spetets per segment.
  1.3872 +   * @param strict7BitEncoding
  1.3873 +   *        Optional. Enable Latin characters replacement with corresponding
  1.3874 +   *        ones in GSM SMS 7-bit default alphabet.
  1.3875 +   *
  1.3876 +   * @return an array of objects. See #_fragmentText() for detailed definition.
  1.3877 +   */
  1.3878 +  _fragmentText7Bit: function(text, langTable, langShiftTable, segmentSeptets, strict7BitEncoding) {
  1.3879 +    let ret = [];
  1.3880 +    let body = "", len = 0;
  1.3881 +    // If the message is empty, we only push the empty message to ret.
  1.3882 +    if (text.length === 0) {
  1.3883 +      ret.push({
  1.3884 +        body: text,
  1.3885 +        encodedBodyLength: text.length,
  1.3886 +      });
  1.3887 +      return ret;
  1.3888 +    }
  1.3889 +
  1.3890 +    for (let i = 0, inc = 0; i < text.length; i++) {
  1.3891 +      let c = text.charAt(i);
  1.3892 +      if (strict7BitEncoding) {
  1.3893 +        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
  1.3894 +      }
  1.3895 +
  1.3896 +      let septet = langTable.indexOf(c);
  1.3897 +      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
  1.3898 +        continue;
  1.3899 +      }
  1.3900 +
  1.3901 +      if (septet >= 0) {
  1.3902 +        inc = 1;
  1.3903 +      } else {
  1.3904 +        septet = langShiftTable.indexOf(c);
  1.3905 +        if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
  1.3906 +          continue;
  1.3907 +        }
  1.3908 +
  1.3909 +        inc = 2;
  1.3910 +        if (septet < 0) {
  1.3911 +          if (!strict7BitEncoding) {
  1.3912 +            throw new Error("Given text cannot be encoded with GSM 7-bit Alphabet!");
  1.3913 +          }
  1.3914 +
  1.3915 +          // Bug 816082, when strict7BitEncoding is enabled, we should replace
  1.3916 +          // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
  1.3917 +          c = "*";
  1.3918 +          if (langTable.indexOf(c) >= 0) {
  1.3919 +            inc = 1;
  1.3920 +          }
  1.3921 +        }
  1.3922 +      }
  1.3923 +
  1.3924 +      if ((len + inc) > segmentSeptets) {
  1.3925 +        ret.push({
  1.3926 +          body: body,
  1.3927 +          encodedBodyLength: len,
  1.3928 +        });
  1.3929 +        body = c;
  1.3930 +        len = inc;
  1.3931 +      } else {
  1.3932 +        body += c;
  1.3933 +        len += inc;
  1.3934 +      }
  1.3935 +    }
  1.3936 +
  1.3937 +    if (len) {
  1.3938 +      ret.push({
  1.3939 +        body: body,
  1.3940 +        encodedBodyLength: len,
  1.3941 +      });
  1.3942 +    }
  1.3943 +
  1.3944 +    return ret;
  1.3945 +  },
  1.3946 +
  1.3947 +  /**
  1.3948 +   * Fragment UCS2 encodable string for transmission.
  1.3949 +   *
  1.3950 +   * @param text
  1.3951 +   *        text string to be fragmented.
  1.3952 +   * @param segmentChars
  1.3953 +   *        Number of available characters per segment.
  1.3954 +   *
  1.3955 +   * @return an array of objects. See #_fragmentText() for detailed definition.
  1.3956 +   */
  1.3957 +  _fragmentTextUCS2: function(text, segmentChars) {
  1.3958 +    let ret = [];
  1.3959 +    // If the message is empty, we only push the empty message to ret.
  1.3960 +    if (text.length === 0) {
  1.3961 +      ret.push({
  1.3962 +        body: text,
  1.3963 +        encodedBodyLength: text.length,
  1.3964 +      });
  1.3965 +      return ret;
  1.3966 +    }
  1.3967 +
  1.3968 +    for (let offset = 0; offset < text.length; offset += segmentChars) {
  1.3969 +      let str = text.substr(offset, segmentChars);
  1.3970 +      ret.push({
  1.3971 +        body: str,
  1.3972 +        encodedBodyLength: str.length * 2,
  1.3973 +      });
  1.3974 +    }
  1.3975 +
  1.3976 +    return ret;
  1.3977 +  },
  1.3978 +
  1.3979 +  /**
  1.3980 +   * Fragment string for transmission.
  1.3981 +   *
  1.3982 +   * Fragment input text string into an array of objects that contains
  1.3983 +   * attributes `body`, substring for this segment, `encodedBodyLength`,
  1.3984 +   * length of the encoded segment body in septets.
  1.3985 +   *
  1.3986 +   * @param text
  1.3987 +   *        Text string to be fragmented.
  1.3988 +   * @param options
  1.3989 +   *        Optional pre-calculated option object. The output array will be
  1.3990 +   *        stored at options.segments if there are multiple segments.
  1.3991 +   * @param strict7BitEncoding
  1.3992 +   *        Optional. Enable Latin characters replacement with corresponding
  1.3993 +   *        ones in GSM SMS 7-bit default alphabet.
  1.3994 +   *
  1.3995 +   * @return Populated options object.
  1.3996 +   */
  1.3997 +  _fragmentText: function(text, options, strict7BitEncoding) {
  1.3998 +    if (!options) {
  1.3999 +      options = this._calculateUserDataLength(text, strict7BitEncoding);
  1.4000 +    }
  1.4001 +
  1.4002 +    if (options.dcs == RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
  1.4003 +      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[options.langIndex];
  1.4004 +      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[options.langShiftIndex];
  1.4005 +      options.segments = this._fragmentText7Bit(text,
  1.4006 +                                                langTable, langShiftTable,
  1.4007 +                                                options.segmentChars,
  1.4008 +                                                strict7BitEncoding);
  1.4009 +    } else {
  1.4010 +      options.segments = this._fragmentTextUCS2(text,
  1.4011 +                                                options.segmentChars);
  1.4012 +    }
  1.4013 +
  1.4014 +    // Re-sync options.segmentMaxSeq with actual length of returning array.
  1.4015 +    options.segmentMaxSeq = options.segments.length;
  1.4016 +
  1.4017 +    return options;
  1.4018 +  },
  1.4019 +
  1.4020 +  getSegmentInfoForText: function(text, request) {
  1.4021 +    let strict7BitEncoding;
  1.4022 +    try {
  1.4023 +      strict7BitEncoding = Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
  1.4024 +    } catch (e) {
  1.4025 +      strict7BitEncoding = false;
  1.4026 +    }
  1.4027 +
  1.4028 +    let options = this._fragmentText(text, null, strict7BitEncoding);
  1.4029 +    let charsInLastSegment;
  1.4030 +    if (options.segmentMaxSeq) {
  1.4031 +      let lastSegment = options.segments[options.segmentMaxSeq - 1];
  1.4032 +      charsInLastSegment = lastSegment.encodedBodyLength;
  1.4033 +      if (options.dcs == RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET) {
  1.4034 +        // In UCS2 encoding, encodedBodyLength is in octets.
  1.4035 +        charsInLastSegment /= 2;
  1.4036 +      }
  1.4037 +    } else {
  1.4038 +      charsInLastSegment = 0;
  1.4039 +    }
  1.4040 +
  1.4041 +    let result = gMobileMessageService
  1.4042 +                 .createSmsSegmentInfo(options.segmentMaxSeq,
  1.4043 +                                       options.segmentChars,
  1.4044 +                                       options.segmentChars - charsInLastSegment);
  1.4045 +    request.notifySegmentInfoForTextGot(result);
  1.4046 +  },
  1.4047 +
  1.4048 +  getSmscAddress: function(request) {
  1.4049 +    this.workerMessenger.send("getSmscAddress",
  1.4050 +                              null,
  1.4051 +                              (function(response) {
  1.4052 +      if (!response.errorMsg) {
  1.4053 +        request.notifyGetSmscAddress(response.smscAddress);
  1.4054 +      } else {
  1.4055 +        request.notifyGetSmscAddressFailed(response.errorMsg);
  1.4056 +      }
  1.4057 +    }).bind(this));
  1.4058 +  },
  1.4059 +
  1.4060 +  sendSMS: function(number, message, silent, request) {
  1.4061 +    let strict7BitEncoding;
  1.4062 +    try {
  1.4063 +      strict7BitEncoding = Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
  1.4064 +    } catch (e) {
  1.4065 +      strict7BitEncoding = false;
  1.4066 +    }
  1.4067 +
  1.4068 +    let options = this._fragmentText(message, null, strict7BitEncoding);
  1.4069 +    options.number = PhoneNumberUtils.normalize(number);
  1.4070 +    let requestStatusReport;
  1.4071 +    try {
  1.4072 +      requestStatusReport =
  1.4073 +        Services.prefs.getBoolPref("dom.sms.requestStatusReport");
  1.4074 +    } catch (e) {
  1.4075 +      requestStatusReport = true;
  1.4076 +    }
  1.4077 +    options.requestStatusReport = requestStatusReport && !silent;
  1.4078 +    if (options.segmentMaxSeq > 1) {
  1.4079 +      options.segmentRef16Bit = this.segmentRef16Bit;
  1.4080 +      options.segmentRef = this.nextSegmentRef;
  1.4081 +    }
  1.4082 +
  1.4083 +    let notifyResult = (function notifyResult(rv, domMessage) {
  1.4084 +      if (!Components.isSuccessCode(rv)) {
  1.4085 +        if (DEBUG) this.debug("Error! Fail to save sending message! rv = " + rv);
  1.4086 +        request.notifySendMessageFailed(
  1.4087 +          gMobileMessageDatabaseService.translateCrErrorToMessageCallbackError(rv));
  1.4088 +        Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
  1.4089 +        return;
  1.4090 +      }
  1.4091 +
  1.4092 +      if (!silent) {
  1.4093 +        Services.obs.notifyObservers(domMessage, kSmsSendingObserverTopic, null);
  1.4094 +      }
  1.4095 +
  1.4096 +      // If the radio is disabled or the SIM card is not ready, just directly
  1.4097 +      // return with the corresponding error code.
  1.4098 +      let errorCode;
  1.4099 +      if (!PhoneNumberUtils.isPlainPhoneNumber(options.number)) {
  1.4100 +        if (DEBUG) this.debug("Error! Address is invalid when sending SMS: " +
  1.4101 +                              options.number);
  1.4102 +        errorCode = Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR;
  1.4103 +      } else if (this.rilContext.detailedRadioState ==
  1.4104 +                 RIL.GECKO_DETAILED_RADIOSTATE_DISABLED) {
  1.4105 +        if (DEBUG) this.debug("Error! Radio is disabled when sending SMS.");
  1.4106 +        errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
  1.4107 +      } else if (this.rilContext.cardState != "ready") {
  1.4108 +        if (DEBUG) this.debug("Error! SIM card is not ready when sending SMS.");
  1.4109 +        errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
  1.4110 +      }
  1.4111 +      if (errorCode) {
  1.4112 +        if (silent) {
  1.4113 +          request.notifySendMessageFailed(errorCode);
  1.4114 +          return;
  1.4115 +        }
  1.4116 +
  1.4117 +        gMobileMessageDatabaseService
  1.4118 +          .setMessageDeliveryByMessageId(domMessage.id,
  1.4119 +                                         null,
  1.4120 +                                         DOM_MOBILE_MESSAGE_DELIVERY_ERROR,
  1.4121 +                                         RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
  1.4122 +                                         null,
  1.4123 +                                         function notifyResult(rv, domMessage) {
  1.4124 +          // TODO bug 832140 handle !Components.isSuccessCode(rv)
  1.4125 +          request.notifySendMessageFailed(errorCode);
  1.4126 +          Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
  1.4127 +        });
  1.4128 +        return;
  1.4129 +      }
  1.4130 +
  1.4131 +      // Keep current SMS message info for sent/delivered notifications
  1.4132 +      let context = {
  1.4133 +        request: request,
  1.4134 +        sms: domMessage,
  1.4135 +        requestStatusReport: options.requestStatusReport,
  1.4136 +        silent: silent
  1.4137 +      };
  1.4138 +
  1.4139 +      // This is the entry point starting to send SMS.
  1.4140 +      this.workerMessenger.send("sendSMS", options,
  1.4141 +                                (function(context, response) {
  1.4142 +        if (response.errorMsg) {
  1.4143 +          // Failed to send SMS out.
  1.4144 +          let error = Ci.nsIMobileMessageCallback.UNKNOWN_ERROR;
  1.4145 +          switch (response.errorMsg) {
  1.4146 +            case RIL.ERROR_RADIO_NOT_AVAILABLE:
  1.4147 +              error = Ci.nsIMobileMessageCallback.NO_SIGNAL_ERROR;
  1.4148 +              break;
  1.4149 +            case RIL.ERROR_FDN_CHECK_FAILURE:
  1.4150 +              error = Ci.nsIMobileMessageCallback.FDN_CHECK_ERROR;
  1.4151 +              break;
  1.4152 +          }
  1.4153 +
  1.4154 +          if (context.silent) {
  1.4155 +            context.request.notifySendMessageFailed(error);
  1.4156 +            return false;
  1.4157 +          }
  1.4158 +
  1.4159 +          gMobileMessageDatabaseService
  1.4160 +            .setMessageDeliveryByMessageId(context.sms.id,
  1.4161 +                                           null,
  1.4162 +                                           DOM_MOBILE_MESSAGE_DELIVERY_ERROR,
  1.4163 +                                           RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
  1.4164 +                                           null,
  1.4165 +                                           function notifyResult(rv, domMessage) {
  1.4166 +            // TODO bug 832140 handle !Components.isSuccessCode(rv)
  1.4167 +            context.request.notifySendMessageFailed(error);
  1.4168 +            Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
  1.4169 +          });
  1.4170 +          return false;
  1.4171 +        } // End of send failure.
  1.4172 +
  1.4173 +        if (response.deliveryStatus) {
  1.4174 +          // Message delivery.
  1.4175 +          gMobileMessageDatabaseService
  1.4176 +            .setMessageDeliveryByMessageId(context.sms.id,
  1.4177 +                                           null,
  1.4178 +                                           context.sms.delivery,
  1.4179 +                                           response.deliveryStatus,
  1.4180 +                                           null,
  1.4181 +                                           (function notifyResult(rv, domMessage) {
  1.4182 +            // TODO bug 832140 handle !Components.isSuccessCode(rv)
  1.4183 +
  1.4184 +            let topic = (response.deliveryStatus ==
  1.4185 +                         RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS)
  1.4186 +                        ? kSmsDeliverySuccessObserverTopic
  1.4187 +                        : kSmsDeliveryErrorObserverTopic;
  1.4188 +
  1.4189 +            // Broadcasting a "sms-delivery-success" system message to open apps.
  1.4190 +            if (topic == kSmsDeliverySuccessObserverTopic) {
  1.4191 +              this.broadcastSmsSystemMessage(topic, domMessage);
  1.4192 +            }
  1.4193 +
  1.4194 +            // Notifying observers the delivery status is updated.
  1.4195 +            Services.obs.notifyObservers(domMessage, topic, null);
  1.4196 +          }).bind(this));
  1.4197 +
  1.4198 +          // Send transaction has ended completely.
  1.4199 +          return false;
  1.4200 +        } // End of message delivery.
  1.4201 +
  1.4202 +        // Message sent.
  1.4203 +        if (context.silent) {
  1.4204 +          // There is no way to modify nsIDOMMozSmsMessage attributes as they
  1.4205 +          // are read only so we just create a new sms instance to send along
  1.4206 +          // with the notification.
  1.4207 +          let sms = context.sms;
  1.4208 +          context.request.notifyMessageSent(
  1.4209 +            gMobileMessageService.createSmsMessage(sms.id,
  1.4210 +                                                   sms.threadId,
  1.4211 +                                                   sms.iccId,
  1.4212 +                                                   DOM_MOBILE_MESSAGE_DELIVERY_SENT,
  1.4213 +                                                   sms.deliveryStatus,
  1.4214 +                                                   sms.sender,
  1.4215 +                                                   sms.receiver,
  1.4216 +                                                   sms.body,
  1.4217 +                                                   sms.messageClass,
  1.4218 +                                                   sms.timestamp,
  1.4219 +                                                   Date.now(),
  1.4220 +                                                   0,
  1.4221 +                                                   sms.read));
  1.4222 +          // We don't wait for SMS-DELIVER-REPORT for silent one.
  1.4223 +          return false;
  1.4224 +        }
  1.4225 +
  1.4226 +        gMobileMessageDatabaseService
  1.4227 +          .setMessageDeliveryByMessageId(context.sms.id,
  1.4228 +                                         null,
  1.4229 +                                         DOM_MOBILE_MESSAGE_DELIVERY_SENT,
  1.4230 +                                         context.sms.deliveryStatus,
  1.4231 +                                         null,
  1.4232 +                                         (function notifyResult(rv, domMessage) {
  1.4233 +          // TODO bug 832140 handle !Components.isSuccessCode(rv)
  1.4234 +
  1.4235 +          if (context.requestStatusReport) {
  1.4236 +            context.sms = domMessage;
  1.4237 +          }
  1.4238 +
  1.4239 +          this.broadcastSmsSystemMessage(kSmsSentObserverTopic, domMessage);
  1.4240 +          context.request.notifyMessageSent(domMessage);
  1.4241 +          Services.obs.notifyObservers(domMessage, kSmsSentObserverTopic, null);
  1.4242 +        }).bind(this));
  1.4243 +
  1.4244 +        // Only keep current context if we have requested for delivery report.
  1.4245 +        return context.requestStatusReport;
  1.4246 +      }).bind(this, context)); // End of |workerMessenger.send| callback.
  1.4247 +    }).bind(this); // End of DB saveSendingMessage callback.
  1.4248 +
  1.4249 +    let sendingMessage = {
  1.4250 +      type: "sms",
  1.4251 +      sender: this.getPhoneNumber(),
  1.4252 +      receiver: number,
  1.4253 +      body: message,
  1.4254 +      deliveryStatusRequested: options.requestStatusReport,
  1.4255 +      timestamp: Date.now(),
  1.4256 +      iccId: this.getIccId()
  1.4257 +    };
  1.4258 +
  1.4259 +    if (silent) {
  1.4260 +      let delivery = DOM_MOBILE_MESSAGE_DELIVERY_SENDING;
  1.4261 +      let deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_PENDING;
  1.4262 +      let domMessage =
  1.4263 +        gMobileMessageService.createSmsMessage(-1, // id
  1.4264 +                                               0,  // threadId
  1.4265 +                                               sendingMessage.iccId,
  1.4266 +                                               delivery,
  1.4267 +                                               deliveryStatus,
  1.4268 +                                               sendingMessage.sender,
  1.4269 +                                               sendingMessage.receiver,
  1.4270 +                                               sendingMessage.body,
  1.4271 +                                               "normal", // message class
  1.4272 +                                               sendingMessage.timestamp,
  1.4273 +                                               0,
  1.4274 +                                               0,
  1.4275 +                                               false);
  1.4276 +      notifyResult(Cr.NS_OK, domMessage);
  1.4277 +      return;
  1.4278 +    }
  1.4279 +
  1.4280 +    let id = gMobileMessageDatabaseService.saveSendingMessage(
  1.4281 +      sendingMessage, notifyResult);
  1.4282 +  },
  1.4283 +
  1.4284 +  // TODO: Bug 928861 - B2G NetworkManager: Provide a more generic function
  1.4285 +  //                    for connecting
  1.4286 +  setupDataCallByType: function(apntype) {
  1.4287 +    let connHandler = gDataConnectionManager.getConnectionHandler(this.clientId);
  1.4288 +    connHandler.setupDataCallByType(apntype);
  1.4289 +  },
  1.4290 +
  1.4291 +  // TODO: Bug 928861 - B2G NetworkManager: Provide a more generic function
  1.4292 +  //                    for connecting
  1.4293 +  deactivateDataCallByType: function(apntype) {
  1.4294 +    let connHandler = gDataConnectionManager.getConnectionHandler(this.clientId);
  1.4295 +    connHandler.deactivateDataCallByType(apntype);
  1.4296 +  },
  1.4297 +
  1.4298 +  // TODO: Bug 904514 - [meta] NetworkManager enhancement
  1.4299 +  getDataCallStateByType: function(apntype) {
  1.4300 +    let connHandler = gDataConnectionManager.getConnectionHandler(this.clientId);
  1.4301 +    return connHandler.getDataCallStateByType(apntype);
  1.4302 +  },
  1.4303 +
  1.4304 +  setupDataCall: function(radioTech, apn, user, passwd, chappap, pdptype) {
  1.4305 +    this.workerMessenger.send("setupDataCall", { radioTech: radioTech,
  1.4306 +                                                 apn: apn,
  1.4307 +                                                 user: user,
  1.4308 +                                                 passwd: passwd,
  1.4309 +                                                 chappap: chappap,
  1.4310 +                                                 pdptype: pdptype });
  1.4311 +  },
  1.4312 +
  1.4313 +  deactivateDataCall: function(cid, reason) {
  1.4314 +    this.workerMessenger.send("deactivateDataCall", { cid: cid,
  1.4315 +                                                      reason: reason });
  1.4316 +  },
  1.4317 +
  1.4318 +  sendWorkerMessage: function(rilMessageType, message, callback) {
  1.4319 +    if (callback) {
  1.4320 +      this.workerMessenger.send(rilMessageType, message, function(response) {
  1.4321 +        return callback.handleResponse(response);
  1.4322 +      });
  1.4323 +    } else {
  1.4324 +      this.workerMessenger.send(rilMessageType, message);
  1.4325 +    }
  1.4326 +  }
  1.4327 +};
  1.4328 +
  1.4329 +function RILNetworkInterface(dataConnectionHandler, apnSetting) {
  1.4330 +  this.dataConnectionHandler = dataConnectionHandler;
  1.4331 +  this.apnSetting = apnSetting;
  1.4332 +  this.connectedTypes = [];
  1.4333 +
  1.4334 +  this.ips = [];
  1.4335 +  this.prefixLengths = [];
  1.4336 +  this.dnses = [];
  1.4337 +  this.gateways = [];
  1.4338 +}
  1.4339 +
  1.4340 +RILNetworkInterface.prototype = {
  1.4341 +  classID:   RILNETWORKINTERFACE_CID,
  1.4342 +  classInfo: XPCOMUtils.generateCI({classID: RILNETWORKINTERFACE_CID,
  1.4343 +                                    classDescription: "RILNetworkInterface",
  1.4344 +                                    interfaces: [Ci.nsINetworkInterface,
  1.4345 +                                                 Ci.nsIRilNetworkInterface]}),
  1.4346 +  QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface,
  1.4347 +                                         Ci.nsIRilNetworkInterface]),
  1.4348 +
  1.4349 +  // nsINetworkInterface
  1.4350 +
  1.4351 +  NETWORK_STATE_UNKNOWN:       Ci.nsINetworkInterface.NETWORK_STATE_UNKNOWN,
  1.4352 +  NETWORK_STATE_CONNECTING:    Ci.nsINetworkInterface.CONNECTING,
  1.4353 +  NETWORK_STATE_CONNECTED:     Ci.nsINetworkInterface.CONNECTED,
  1.4354 +  NETWORK_STATE_DISCONNECTING: Ci.nsINetworkInterface.DISCONNECTING,
  1.4355 +  NETWORK_STATE_DISCONNECTED:  Ci.nsINetworkInterface.DISCONNECTED,
  1.4356 +
  1.4357 +  NETWORK_TYPE_WIFI:        Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
  1.4358 +  NETWORK_TYPE_MOBILE:      Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE,
  1.4359 +  NETWORK_TYPE_MOBILE_MMS:  Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE_MMS,
  1.4360 +  NETWORK_TYPE_MOBILE_SUPL: Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE_SUPL,
  1.4361 +  NETWORK_TYPE_MOBILE_IMS:  Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE_IMS,
  1.4362 +  NETWORK_TYPE_MOBILE_DUN:  Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE_DUN,
  1.4363 +  // The network manager should only need to add the host route for "other"
  1.4364 +  // types, which is the same handling method as the supl type. So let the
  1.4365 +  // definition of other types to be the same as the one of supl type.
  1.4366 +  NETWORK_TYPE_MOBILE_OTHERS: Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE_SUPL,
  1.4367 +
  1.4368 +  /**
  1.4369 +   * Standard values for the APN connection retry process
  1.4370 +   * Retry funcion: time(secs) = A * numer_of_retries^2 + B
  1.4371 +   */
  1.4372 +  NETWORK_APNRETRY_FACTOR: 8,
  1.4373 +  NETWORK_APNRETRY_ORIGIN: 3,
  1.4374 +  NETWORK_APNRETRY_MAXRETRIES: 10,
  1.4375 +
  1.4376 +  // Event timer for connection retries
  1.4377 +  timer: null,
  1.4378 +
  1.4379 +  /**
  1.4380 +   * nsINetworkInterface Implementation
  1.4381 +   */
  1.4382 +
  1.4383 +  state: Ci.nsINetworkInterface.NETWORK_STATE_UNKNOWN,
  1.4384 +
  1.4385 +  get type() {
  1.4386 +    if (this.connectedTypes.indexOf("default") != -1) {
  1.4387 +      return this.NETWORK_TYPE_MOBILE;
  1.4388 +    }
  1.4389 +    if (this.connectedTypes.indexOf("mms") != -1) {
  1.4390 +      return this.NETWORK_TYPE_MOBILE_MMS;
  1.4391 +    }
  1.4392 +    if (this.connectedTypes.indexOf("supl") != -1) {
  1.4393 +      return this.NETWORK_TYPE_MOBILE_SUPL;
  1.4394 +    }
  1.4395 +    if (this.connectedTypes.indexOf("ims") != -1) {
  1.4396 +      return this.NETWORK_TYPE_MOBILE_IMS;
  1.4397 +    }
  1.4398 +    if (this.connectedTypes.indexOf("dun") != -1) {
  1.4399 +      return this.NETWORK_TYPE_MOBILE_DUN;
  1.4400 +    }
  1.4401 +
  1.4402 +    return this.NETWORK_TYPE_MOBILE_OTHERS;
  1.4403 +  },
  1.4404 +
  1.4405 +  name: null,
  1.4406 +
  1.4407 +  ips: null,
  1.4408 +
  1.4409 +  prefixLengths: null,
  1.4410 +
  1.4411 +  gateways: null,
  1.4412 +
  1.4413 +  dnses: null,
  1.4414 +
  1.4415 +  get httpProxyHost() {
  1.4416 +    return this.apnSetting.proxy || "";
  1.4417 +  },
  1.4418 +
  1.4419 +  get httpProxyPort() {
  1.4420 +    return this.apnSetting.port || "";
  1.4421 +  },
  1.4422 +
  1.4423 +  /**
  1.4424 +   * nsIRilNetworkInterface Implementation
  1.4425 +   */
  1.4426 +
  1.4427 +  get serviceId() {
  1.4428 +    return this.dataConnectionHandler.clientId;
  1.4429 +  },
  1.4430 +
  1.4431 +  get iccId() {
  1.4432 +    let iccInfo = this.dataConnectionHandler.radioInterface.rilContext.iccInfo;
  1.4433 +    return iccInfo && iccInfo.iccid;
  1.4434 +  },
  1.4435 +
  1.4436 +  get mmsc() {
  1.4437 +    if (!this.inConnectedTypes("mms")) {
  1.4438 +      if (DEBUG) this.debug("Error! Only MMS network can get MMSC.");
  1.4439 +      throw Cr.NS_ERROR_UNEXPECTED;
  1.4440 +    }
  1.4441 +
  1.4442 +    let mmsc = this.apnSetting.mmsc;
  1.4443 +    if (!mmsc) {
  1.4444 +      try {
  1.4445 +        mmsc = Services.prefs.getCharPref("ril.mms.mmsc");
  1.4446 +      } catch (e) {
  1.4447 +        mmsc = "";
  1.4448 +      }
  1.4449 +    }
  1.4450 +
  1.4451 +    return mmsc;
  1.4452 +  },
  1.4453 +
  1.4454 +  get mmsProxy() {
  1.4455 +    if (!this.inConnectedTypes("mms")) {
  1.4456 +      if (DEBUG) this.debug("Error! Only MMS network can get MMS proxy.");
  1.4457 +      throw Cr.NS_ERROR_UNEXPECTED;
  1.4458 +    }
  1.4459 +
  1.4460 +    let proxy = this.apnSetting.mmsproxy;
  1.4461 +    if (!proxy) {
  1.4462 +      try {
  1.4463 +        proxy = Services.prefs.getCharPref("ril.mms.mmsproxy");
  1.4464 +      } catch (e) {
  1.4465 +        proxy = "";
  1.4466 +      }
  1.4467 +    }
  1.4468 +
  1.4469 +    return proxy;
  1.4470 +  },
  1.4471 +
  1.4472 +  get mmsPort() {
  1.4473 +    if (!this.inConnectedTypes("mms")) {
  1.4474 +      if (DEBUG) this.debug("Error! Only MMS network can get MMS port.");
  1.4475 +      throw Cr.NS_ERROR_UNEXPECTED;
  1.4476 +    }
  1.4477 +
  1.4478 +    let port = this.apnSetting.mmsport;
  1.4479 +    if (!port) {
  1.4480 +      try {
  1.4481 +        port = Services.prefs.getIntPref("ril.mms.mmsport");
  1.4482 +      } catch (e) {
  1.4483 +        port = -1;
  1.4484 +      }
  1.4485 +    }
  1.4486 +
  1.4487 +    return port;
  1.4488 +  },
  1.4489 +
  1.4490 +  getAddresses: function (ips, prefixLengths) {
  1.4491 +    ips.value = this.ips.slice();
  1.4492 +    prefixLengths.value = this.prefixLengths.slice();
  1.4493 +
  1.4494 +    return this.ips.length;
  1.4495 +  },
  1.4496 +
  1.4497 +  getGateways: function (count) {
  1.4498 +    if (count) {
  1.4499 +      count.value = this.gateways.length;
  1.4500 +    }
  1.4501 +    return this.gateways.slice();
  1.4502 +  },
  1.4503 +
  1.4504 +  getDnses: function (count) {
  1.4505 +    if (count) {
  1.4506 +      count.value = this.dnses.length;
  1.4507 +    }
  1.4508 +    return this.dnses.slice();
  1.4509 +  },
  1.4510 +
  1.4511 +  debug: function(s) {
  1.4512 +    dump("-*- RILNetworkInterface[" + this.dataConnectionHandler.clientId + ":" +
  1.4513 +         this.type + "]: " + s + "\n");
  1.4514 +  },
  1.4515 +
  1.4516 +  dataCallError: function(message) {
  1.4517 +    if (message.apn != this.apnSetting.apn) {
  1.4518 +      return;
  1.4519 +    }
  1.4520 +    if (DEBUG) this.debug("Data call error on APN: " + message.apn);
  1.4521 +    this.reset();
  1.4522 +  },
  1.4523 +
  1.4524 +  dataCallStateChanged: function(datacall) {
  1.4525 +    if (this.cid && this.cid != datacall.cid) {
  1.4526 +    // If data call for this connection existed but cid mismatched,
  1.4527 +    // it means this datacall state change is not for us.
  1.4528 +      return;
  1.4529 +    }
  1.4530 +    // If data call for this connection does not exist, it could be state
  1.4531 +    // change for new data call.  We only update data call state change
  1.4532 +    // if APN name matched.
  1.4533 +    if (!this.cid && datacall.apn != this.apnSetting.apn) {
  1.4534 +      return;
  1.4535 +    }
  1.4536 +    if (DEBUG) {
  1.4537 +      this.debug("Data call ID: " + datacall.cid + ", interface name: " +
  1.4538 +                 datacall.ifname + ", APN name: " + datacall.apn);
  1.4539 +    }
  1.4540 +    if (this.connecting &&
  1.4541 +        (datacall.state == RIL.GECKO_NETWORK_STATE_CONNECTING ||
  1.4542 +         datacall.state == RIL.GECKO_NETWORK_STATE_CONNECTED)) {
  1.4543 +      this.connecting = false;
  1.4544 +      this.cid = datacall.cid;
  1.4545 +      this.name = datacall.ifname;
  1.4546 +      for (let entry of datacall.addresses) {
  1.4547 +        this.ips.push(entry.address);
  1.4548 +        this.prefixLengths.push(entry.prefixLength);
  1.4549 +      }
  1.4550 +      this.gateways = datacall.gateways.slice();
  1.4551 +      this.dnses = datacall.dnses.slice();
  1.4552 +      if (!this.registeredAsNetworkInterface) {
  1.4553 +        gNetworkManager.registerNetworkInterface(this);
  1.4554 +        this.registeredAsNetworkInterface = true;
  1.4555 +      }
  1.4556 +    }
  1.4557 +    // In current design, we don't update status of secondary APN if it shares
  1.4558 +    // same APN name with the default APN.  In this condition, this.cid will
  1.4559 +    // not be set and we don't want to update its status.
  1.4560 +    if (this.cid == null) {
  1.4561 +      return;
  1.4562 +    }
  1.4563 +
  1.4564 +    if (this.state == datacall.state) {
  1.4565 +      if (datacall.state != RIL.GECKO_NETWORK_STATE_CONNECTED) {
  1.4566 +        return;
  1.4567 +      }
  1.4568 +      // State remains connected, check for minor changes.
  1.4569 +      let changed = false;
  1.4570 +      if (this.ips.length != datacall.addresses.length) {
  1.4571 +        changed = true;
  1.4572 +        this.ips = [];
  1.4573 +        this.prefixLengths = [];
  1.4574 +        for (let entry of datacall.addresses) {
  1.4575 +          this.ips.push(entry.address);
  1.4576 +          this.prefixLengths.push(entry.prefixLength);
  1.4577 +        }
  1.4578 +      }
  1.4579 +
  1.4580 +      let reduceFunc = function(aRhs, aChanged, aElement, aIndex) {
  1.4581 +        return aChanged || (aElement != aRhs[aIndex]);
  1.4582 +      };
  1.4583 +      for (let field of ["gateways", "dnses"]) {
  1.4584 +        let lhs = this[field], rhs = datacall[field];
  1.4585 +        if (lhs.length != rhs.length ||
  1.4586 +            lhs.reduce(reduceFunc.bind(null, rhs), false)) {
  1.4587 +          changed = true;
  1.4588 +          this[field] = rhs.slice();
  1.4589 +        }
  1.4590 +      }
  1.4591 +
  1.4592 +      if (changed) {
  1.4593 +        if (DEBUG) this.debug("Notify for data call minor changes.");
  1.4594 +        Services.obs.notifyObservers(this,
  1.4595 +                                     kNetworkInterfaceStateChangedTopic,
  1.4596 +                                     null);
  1.4597 +      }
  1.4598 +      return;
  1.4599 +    }
  1.4600 +
  1.4601 +    this.state = datacall.state;
  1.4602 +
  1.4603 +    Services.obs.notifyObservers(this,
  1.4604 +                                 kNetworkInterfaceStateChangedTopic,
  1.4605 +                                 null);
  1.4606 +
  1.4607 +    if ((this.state == RIL.GECKO_NETWORK_STATE_UNKNOWN ||
  1.4608 +         this.state == RIL.GECKO_NETWORK_STATE_DISCONNECTED) &&
  1.4609 +        this.registeredAsNetworkInterface) {
  1.4610 +      gNetworkManager.unregisterNetworkInterface(this);
  1.4611 +      this.registeredAsNetworkInterface = false;
  1.4612 +      this.cid = null;
  1.4613 +      this.connectedTypes = [];
  1.4614 +
  1.4615 +      this.ips = [];
  1.4616 +      this.prefixLengths = [];
  1.4617 +      this.dnses = [];
  1.4618 +      this.gateways = [];
  1.4619 +    }
  1.4620 +
  1.4621 +    // In case the data setting changed while the datacall was being started or
  1.4622 +    // ended, let's re-check the setting and potentially adjust the datacall
  1.4623 +    // state again.
  1.4624 +    let apnSettings = this.dataConnectionHandler.apnSettings;
  1.4625 +    if (apnSettings.byType.default &&
  1.4626 +        (apnSettings.byType.default.apn == this.apnSetting.apn)) {
  1.4627 +      this.dataConnectionHandler.updateRILNetworkInterface();
  1.4628 +    }
  1.4629 +  },
  1.4630 +
  1.4631 +  // Helpers
  1.4632 +
  1.4633 +  cid: null,
  1.4634 +  registeredAsDataCallCallback: false,
  1.4635 +  registeredAsNetworkInterface: false,
  1.4636 +  connecting: false,
  1.4637 +  apnSetting: null,
  1.4638 +
  1.4639 +  // APN failed connections. Retry counter
  1.4640 +  apnRetryCounter: 0,
  1.4641 +
  1.4642 +  connectedTypes: null,
  1.4643 +
  1.4644 +  inConnectedTypes: function(type) {
  1.4645 +    return this.connectedTypes.indexOf(type) != -1;
  1.4646 +  },
  1.4647 +
  1.4648 +  get connected() {
  1.4649 +    return this.state == RIL.GECKO_NETWORK_STATE_CONNECTED;
  1.4650 +  },
  1.4651 +
  1.4652 +  connect: function(apntype) {
  1.4653 +    if (apntype && !this.inConnectedTypes(apntype)) {
  1.4654 +      this.connectedTypes.push(apntype);
  1.4655 +    }
  1.4656 +
  1.4657 +    if (this.connecting || this.connected) {
  1.4658 +      return;
  1.4659 +    }
  1.4660 +
  1.4661 +    // When the retry mechanism is running in background and someone calls
  1.4662 +    // disconnect(), this.connectedTypes.length has chances to become 0.
  1.4663 +    if (!this.connectedTypes.length) {
  1.4664 +      return;
  1.4665 +    }
  1.4666 +
  1.4667 +    if (!this.registeredAsDataCallCallback) {
  1.4668 +      this.dataConnectionHandler.registerDataCallCallback(this);
  1.4669 +      this.registeredAsDataCallCallback = true;
  1.4670 +    }
  1.4671 +
  1.4672 +    if (!this.apnSetting.apn) {
  1.4673 +      if (DEBUG) this.debug("APN name is empty, nothing to do.");
  1.4674 +      return;
  1.4675 +    }
  1.4676 +
  1.4677 +    if (DEBUG) {
  1.4678 +      this.debug("Going to set up data connection with APN " +
  1.4679 +                 this.apnSetting.apn);
  1.4680 +    }
  1.4681 +    let radioInterface = this.dataConnectionHandler.radioInterface;
  1.4682 +    let radioTechType = radioInterface.rilContext.data.type;
  1.4683 +    let radioTechnology = RIL.GECKO_RADIO_TECH.indexOf(radioTechType);
  1.4684 +    let authType = RIL.RIL_DATACALL_AUTH_TO_GECKO.indexOf(this.apnSetting.authtype);
  1.4685 +    // Use the default authType if the value in database is invalid.
  1.4686 +    // For the case that user might not select the authentication type.
  1.4687 +    if (authType == -1) {
  1.4688 +      if (DEBUG) {
  1.4689 +        this.debug("Invalid authType " + this.apnSetting.authtype);
  1.4690 +      }
  1.4691 +      authType = RIL.RIL_DATACALL_AUTH_TO_GECKO.indexOf(RIL.GECKO_DATACALL_AUTH_DEFAULT);
  1.4692 +    }
  1.4693 +    let pdpType = RIL.GECKO_DATACALL_PDP_TYPE_IP;
  1.4694 +    if (RILQUIRKS_HAVE_IPV6) {
  1.4695 +      pdpType = !radioInterface.rilContext.data.roaming
  1.4696 +              ? this.apnSetting.protocol
  1.4697 +              : this.apnSetting.roaming_protocol;
  1.4698 +      if (RIL.RIL_DATACALL_PDP_TYPES.indexOf(pdpType) < 0) {
  1.4699 +        if (DEBUG) {
  1.4700 +          this.debug("Invalid pdpType '" + pdpType + "', using '" +
  1.4701 +                     RIL.GECKO_DATACALL_PDP_TYPE_DEFAULT + "'");
  1.4702 +        }
  1.4703 +        pdpType = RIL.GECKO_DATACALL_PDP_TYPE_DEFAULT;
  1.4704 +      }
  1.4705 +    }
  1.4706 +    radioInterface.setupDataCall(radioTechnology,
  1.4707 +                                 this.apnSetting.apn,
  1.4708 +                                 this.apnSetting.user,
  1.4709 +                                 this.apnSetting.password,
  1.4710 +                                 authType,
  1.4711 +                                 pdpType);
  1.4712 +    this.connecting = true;
  1.4713 +  },
  1.4714 +
  1.4715 +  reset: function() {
  1.4716 +    let apnRetryTimer;
  1.4717 +    this.connecting = false;
  1.4718 +    // We will retry the connection in increasing times
  1.4719 +    // based on the function: time = A * numer_of_retries^2 + B
  1.4720 +    if (this.apnRetryCounter >= this.NETWORK_APNRETRY_MAXRETRIES) {
  1.4721 +      this.apnRetryCounter = 0;
  1.4722 +      this.timer = null;
  1.4723 +      this.connectedTypes = [];
  1.4724 +      if (DEBUG) this.debug("Too many APN Connection retries - STOP retrying");
  1.4725 +      return;
  1.4726 +    }
  1.4727 +
  1.4728 +    apnRetryTimer = this.NETWORK_APNRETRY_FACTOR *
  1.4729 +                    (this.apnRetryCounter * this.apnRetryCounter) +
  1.4730 +                    this.NETWORK_APNRETRY_ORIGIN;
  1.4731 +    this.apnRetryCounter++;
  1.4732 +    if (DEBUG) {
  1.4733 +      this.debug("Data call - APN Connection Retry Timer (secs-counter): " +
  1.4734 +                 apnRetryTimer + "-" + this.apnRetryCounter);
  1.4735 +    }
  1.4736 +
  1.4737 +    if (this.timer == null) {
  1.4738 +      // Event timer for connection retries
  1.4739 +      this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  1.4740 +    }
  1.4741 +    this.timer.initWithCallback(this, apnRetryTimer * 1000,
  1.4742 +                                Ci.nsITimer.TYPE_ONE_SHOT);
  1.4743 +  },
  1.4744 +
  1.4745 +  disconnect: function(apntype) {
  1.4746 +    let index = this.connectedTypes.indexOf(apntype);
  1.4747 +    if (index != -1) {
  1.4748 +      this.connectedTypes.splice(index, 1);
  1.4749 +    }
  1.4750 +
  1.4751 +    if (this.connectedTypes.length) {
  1.4752 +      return;
  1.4753 +    }
  1.4754 +
  1.4755 +    if (this.state == RIL.GECKO_NETWORK_STATE_DISCONNECTING ||
  1.4756 +        this.state == RIL.GECKO_NETWORK_STATE_DISCONNECTED ||
  1.4757 +        this.state == RIL.GECKO_NETWORK_STATE_UNKNOWN) {
  1.4758 +      return;
  1.4759 +    }
  1.4760 +    let reason = RIL.DATACALL_DEACTIVATE_NO_REASON;
  1.4761 +    if (DEBUG) this.debug("Going to disconnet data connection " + this.cid);
  1.4762 +    this.dataConnectionHandler.radioInterface.deactivateDataCall(this.cid,
  1.4763 +                                                                 reason);
  1.4764 +  },
  1.4765 +
  1.4766 +  // Entry method for timer events. Used to reconnect to a failed APN
  1.4767 +  notify: function(timer) {
  1.4768 +    this.connect();
  1.4769 +  },
  1.4770 +
  1.4771 +  shutdown: function() {
  1.4772 +    this.timer = null;
  1.4773 +  }
  1.4774 +
  1.4775 +};
  1.4776 +
  1.4777 +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([RadioInterfaceLayer]);

mercurial