summaryrefslogtreecommitdiffstats
path: root/dom/system/gonk/DataCallManager.js
blob: 5411987cdc2c0cc82c5feaf1609373ff402dad0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/systemlibs.js");

XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
                                   "@mozilla.org/settingsService;1",
                                   "nsISettingsService");

XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
                                   "@mozilla.org/network/manager;1",
                                   "nsINetworkManager");

XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
                                   "@mozilla.org/mobileconnection/mobileconnectionservice;1",
                                   "nsIMobileConnectionService");

XPCOMUtils.defineLazyServiceGetter(this, "gIccService",
                                   "@mozilla.org/icc/iccservice;1",
                                   "nsIIccService");

XPCOMUtils.defineLazyServiceGetter(this, "gDataCallInterfaceService",
                                   "@mozilla.org/datacall/interfaceservice;1",
                                   "nsIDataCallInterfaceService");

XPCOMUtils.defineLazyGetter(this, "RIL", function() {
  let obj = {};
  Cu.import("resource://gre/modules/ril_consts.js", obj);
  return obj;
});

// Ril quirk to attach data registration on demand.
var RILQUIRKS_DATA_REGISTRATION_ON_DEMAND =
  libcutils.property_get("ro.moz.ril.data_reg_on_demand", "false") == "true";

// Ril quirk to control the uicc/data subscription.
var RILQUIRKS_SUBSCRIPTION_CONTROL =
  libcutils.property_get("ro.moz.ril.subscription_control", "false") == "true";

// Ril quirk to enable IPv6 protocol/roaming protocol in APN settings.
var RILQUIRKS_HAVE_IPV6 =
  libcutils.property_get("ro.moz.ril.ipv6", "false") == "true";

const DATACALLMANAGER_CID =
  Components.ID("{35b9efa2-e42c-45ce-8210-0a13e6f4aadc}");
const DATACALLHANDLER_CID =
  Components.ID("{132b650f-c4d8-4731-96c5-83785cb31dee}");
const RILNETWORKINTERFACE_CID =
  Components.ID("{9574ee84-5d0d-4814-b9e6-8b279e03dcf4}");
const RILNETWORKINFO_CID =
  Components.ID("{dd6cf2f0-f0e3-449f-a69e-7c34fdcb8d4b}");

const TOPIC_XPCOM_SHUTDOWN      = "xpcom-shutdown";
const TOPIC_MOZSETTINGS_CHANGED = "mozsettings-changed";
const TOPIC_PREF_CHANGED        = "nsPref:changed";
const TOPIC_DATA_CALL_ERROR     = "data-call-error";
const PREF_RIL_DEBUG_ENABLED    = "ril.debugging.enabled";

const NETWORK_TYPE_UNKNOWN     = Ci.nsINetworkInfo.NETWORK_TYPE_UNKNOWN;
const NETWORK_TYPE_WIFI        = Ci.nsINetworkInfo.NETWORK_TYPE_WIFI;
const NETWORK_TYPE_MOBILE      = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE;
const NETWORK_TYPE_MOBILE_MMS  = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS;
const NETWORK_TYPE_MOBILE_SUPL = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_SUPL;
const NETWORK_TYPE_MOBILE_IMS  = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_IMS;
const NETWORK_TYPE_MOBILE_DUN  = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN;
const NETWORK_TYPE_MOBILE_FOTA = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_FOTA;

const NETWORK_STATE_UNKNOWN       = Ci.nsINetworkInfo.NETWORK_STATE_UNKNOWN;
const NETWORK_STATE_CONNECTING    = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTING;
const NETWORK_STATE_CONNECTED     = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
const NETWORK_STATE_DISCONNECTING = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTING;
const NETWORK_STATE_DISCONNECTED  = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;

const INT32_MAX = 2147483647;

// set to true in ril_consts.js to see debug messages
var DEBUG = RIL.DEBUG_RIL;

function updateDebugFlag() {
  // Read debug setting from pref
  let debugPref;
  try {
    debugPref = Services.prefs.getBoolPref(PREF_RIL_DEBUG_ENABLED);
  } catch (e) {
    debugPref = false;
  }
  DEBUG = debugPref || RIL.DEBUG_RIL;
}
updateDebugFlag();

function DataCallManager() {
  this._connectionHandlers = [];

  let numRadioInterfaces = gMobileConnectionService.numItems;
  for (let clientId = 0; clientId < numRadioInterfaces; clientId++) {
    this._connectionHandlers.push(new DataCallHandler(clientId));
  }

  let lock = gSettingsService.createLock();
  // Read the APN data from the settings DB.
  lock.get("ril.data.apnSettings", this);
  // Read the data enabled setting from DB.
  lock.get("ril.data.enabled", this);
  lock.get("ril.data.roaming_enabled", this);
  // Read the default client id for data call.
  lock.get("ril.data.defaultServiceId", this);

  Services.obs.addObserver(this, TOPIC_XPCOM_SHUTDOWN, false);
  Services.obs.addObserver(this, TOPIC_MOZSETTINGS_CHANGED, false);
  Services.prefs.addObserver(PREF_RIL_DEBUG_ENABLED, this, false);
}
DataCallManager.prototype = {
  classID:   DATACALLMANAGER_CID,
  classInfo: XPCOMUtils.generateCI({classID: DATACALLMANAGER_CID,
                                    classDescription: "Data Call Manager",
                                    interfaces: [Ci.nsIDataCallManager]}),

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallManager,
                                         Ci.nsIObserver,
                                         Ci.nsISettingsServiceCallback]),

  _connectionHandlers: null,

  // Flag to determine the data state to start with when we boot up. It
  // corresponds to the 'ril.data.enabled' setting from the UI.
  _dataEnabled: false,

  // Flag to record the default client id for data call. It corresponds to
  // the 'ril.data.defaultServiceId' setting from the UI.
  _dataDefaultClientId: -1,

  // Flag to record the current default client id for data call.
  // It differs from _dataDefaultClientId in that it is set only when
  // the switch of client id process is done.
  _currentDataClientId: -1,

  // Pending function to execute when we are notified that another data call has
  // been disconnected.
  _pendingDataCallRequest: null,

  debug: function(aMsg) {
    dump("-*- DataCallManager: " + aMsg + "\n");
  },

  get dataDefaultServiceId() {
    return this._dataDefaultClientId;
  },

  getDataCallHandler: function(aClientId) {
    let handler = this._connectionHandlers[aClientId]
    if (!handler) {
      throw Cr.NS_ERROR_UNEXPECTED;
    }

    return handler;
  },

  _setDataRegistration: function(aDataCallInterface, aAttach) {
    return new Promise(function(aResolve, aReject) {
      let callback = {
        QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallCallback]),
        notifySuccess: function() {
          aResolve();
        },
        notifyError: function(aErrorMsg) {
          aReject(aErrorMsg);
        }
      };

      aDataCallInterface.setDataRegistration(aAttach, callback);
    });
  },

  _handleDataClientIdChange: function(aNewClientId) {
    if (this._dataDefaultClientId === aNewClientId) {
       return;
    }
    this._dataDefaultClientId = aNewClientId;

    // This is to handle boot up stage.
    if (this._currentDataClientId == -1) {
      this._currentDataClientId = this._dataDefaultClientId;
      let connHandler = this._connectionHandlers[this._currentDataClientId];
      let dcInterface = connHandler.dataCallInterface;
      if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND ||
          RILQUIRKS_SUBSCRIPTION_CONTROL) {
        this._setDataRegistration(dcInterface, true);
      }
      if (this._dataEnabled) {
        let settings = connHandler.dataCallSettings;
        settings.oldEnabled = settings.enabled;
        settings.enabled = true;
        connHandler.updateRILNetworkInterface();
      }
      return;
    }

    let oldConnHandler = this._connectionHandlers[this._currentDataClientId];
    let oldIface = oldConnHandler.dataCallInterface;
    let oldSettings = oldConnHandler.dataCallSettings;
    let newConnHandler = this._connectionHandlers[this._dataDefaultClientId];
    let newIface = newConnHandler.dataCallInterface;
    let newSettings = newConnHandler.dataCallSettings;

    let applyPendingDataSettings = () => {
      if (DEBUG) {
        this.debug("Apply pending data registration and settings.");
      }

      if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND ||
          RILQUIRKS_SUBSCRIPTION_CONTROL) {
        this._setDataRegistration(oldIface, false).then(() => {
          if (this._dataEnabled) {
            newSettings.oldEnabled = newSettings.enabled;
            newSettings.enabled = true;
          }
          this._currentDataClientId = this._dataDefaultClientId;

          this._setDataRegistration(newIface, true).then(() => {
            newConnHandler.updateRILNetworkInterface();
          });
        });
        return;
      }

      if (this._dataEnabled) {
        newSettings.oldEnabled = newSettings.enabled;
        newSettings.enabled = true;
      }

      this._currentDataClientId = this._dataDefaultClientId;
      newConnHandler.updateRILNetworkInterface();
    };

    if (this._dataEnabled) {
      oldSettings.oldEnabled = oldSettings.enabled;
      oldSettings.enabled = false;
    }

    oldConnHandler.deactivateDataCallsAndWait().then(() => {
      applyPendingDataSettings();
    });
  },

  _shutdown: function() {
    for (let handler of this._connectionHandlers) {
      handler.shutdown();
    }
    this._connectionHandlers = null;
    Services.prefs.removeObserver(PREF_RIL_DEBUG_ENABLED, this);
    Services.obs.removeObserver(this, TOPIC_XPCOM_SHUTDOWN);
    Services.obs.removeObserver(this, TOPIC_MOZSETTINGS_CHANGED);
  },

  /**
   * nsISettingsServiceCallback
   */
  handle: function(aName, aResult) {
    switch (aName) {
      case "ril.data.apnSettings":
        if (DEBUG) {
          this.debug("'ril.data.apnSettings' is now " +
                     JSON.stringify(aResult));
        }
        if (!aResult) {
          break;
        }
        for (let clientId in this._connectionHandlers) {
          let handler = this._connectionHandlers[clientId];
          let apnSetting = aResult[clientId];
          if (handler && apnSetting) {
            handler.updateApnSettings(apnSetting);
          }
        }
        break;
      case "ril.data.enabled":
        if (DEBUG) {
          this.debug("'ril.data.enabled' is now " + aResult);
        }
        if (this._dataEnabled === aResult) {
          break;
        }
        this._dataEnabled = aResult;

        if (DEBUG) {
          this.debug("Default id for data call: " + this._dataDefaultClientId);
        }
        if (this._dataDefaultClientId === -1) {
          // We haven't got the default id for data from db.
          break;
        }

        let connHandler = this._connectionHandlers[this._dataDefaultClientId];
        let settings = connHandler.dataCallSettings;
        settings.oldEnabled = settings.enabled;
        settings.enabled = aResult;
        connHandler.updateRILNetworkInterface();
        break;
      case "ril.data.roaming_enabled":
        if (DEBUG) {
          this.debug("'ril.data.roaming_enabled' is now " + aResult);
          this.debug("Default id for data call: " + this._dataDefaultClientId);
        }
        for (let clientId = 0; clientId < this._connectionHandlers.length; clientId++) {
          let connHandler = this._connectionHandlers[clientId];
          let settings = connHandler.dataCallSettings;
          settings.roamingEnabled = Array.isArray(aResult) ? aResult[clientId]
                                                           : aResult;
        }
        if (this._dataDefaultClientId === -1) {
          // We haven't got the default id for data from db.
          break;
        }
        this._connectionHandlers[this._dataDefaultClientId].updateRILNetworkInterface();
        break;
      case "ril.data.defaultServiceId":
        aResult = aResult || 0;
        if (DEBUG) {
          this.debug("'ril.data.defaultServiceId' is now " + aResult);
        }
        this._handleDataClientIdChange(aResult);
        break;
    }
  },

  handleError: function(aErrorMessage) {
    if (DEBUG) {
      this.debug("There was an error while reading RIL settings.");
    }
  },

  /**
   * nsIObserver interface methods.
   */
  observe: function(aSubject, aTopic, aData) {
    switch (aTopic) {
      case TOPIC_MOZSETTINGS_CHANGED:
        if ("wrappedJSObject" in aSubject) {
          aSubject = aSubject.wrappedJSObject;
        }
        this.handle(aSubject.key, aSubject.value);
        break;
      case TOPIC_PREF_CHANGED:
        if (aData === PREF_RIL_DEBUG_ENABLED) {
          updateDebugFlag();
        }
        break;
      case TOPIC_XPCOM_SHUTDOWN:
        this._shutdown();
        break;
    }
  },
};

function DataCallHandler(aClientId) {
  // Initial owning attributes.
  this.clientId = aClientId;
  this.dataCallSettings = {
    oldEnabled: false,
    enabled: false,
    roamingEnabled: false
  };
  this._dataCalls = [];
  this._listeners = [];

  // This map is used to collect all the apn types and its corresponding
  // RILNetworkInterface.
  this.dataNetworkInterfaces = new Map();

  this.dataCallInterface = gDataCallInterfaceService.getDataCallInterface(aClientId);
  this.dataCallInterface.registerListener(this);

  let mobileConnection = gMobileConnectionService.getItemByServiceId(aClientId);
  mobileConnection.registerListener(this);

  this._dataInfo = {
    state: mobileConnection.data.state,
    type: mobileConnection.data.type,
    roaming: mobileConnection.data.roaming
  }
}
DataCallHandler.prototype = {
  classID:   DATACALLHANDLER_CID,
  classInfo: XPCOMUtils.generateCI({classID: DATACALLHANDLER_CID,
                                    classDescription: "Data Call Handler",
                                    interfaces: [Ci.nsIDataCallHandler]}),

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallHandler,
                                         Ci.nsIDataCallInterfaceListener,
                                         Ci.nsIMobileConnectionListener]),

  clientId: 0,
  dataCallInterface: null,
  dataCallSettings: null,
  dataNetworkInterfaces: null,
  _dataCalls: null,
  _dataInfo: null,

  // Apn settings to be setup after data call are cleared.
  _pendingApnSettings: null,

  debug: function(aMsg) {
    dump("-*- DataCallHandler[" + this.clientId + "]: " + aMsg + "\n");
  },

  shutdown: function() {
    // Shutdown all RIL network interfaces
    this.dataNetworkInterfaces.forEach(function(networkInterface) {
      gNetworkManager.unregisterNetworkInterface(networkInterface);
      networkInterface.shutdown();
      networkInterface = null;
    });
    this.dataNetworkInterfaces.clear();
    this._dataCalls = [];
    this.clientId = null;

    this.dataCallInterface.unregisterListener(this);
    this.dataCallInterface = null;

    let mobileConnection =
      gMobileConnectionService.getItemByServiceId(this.clientId);
    mobileConnection.unregisterListener(this);
  },

  /**
   * Check if we get all necessary APN data.
   */
  _validateApnSetting: function(aApnSetting) {
    return (aApnSetting &&
            aApnSetting.apn &&
            aApnSetting.types &&
            aApnSetting.types.length);
  },

  _convertApnType: function(aApnType) {
    switch (aApnType) {
      case "default":
        return NETWORK_TYPE_MOBILE;
      case "mms":
        return NETWORK_TYPE_MOBILE_MMS;
      case "supl":
        return NETWORK_TYPE_MOBILE_SUPL;
      case "ims":
        return NETWORK_TYPE_MOBILE_IMS;
      case "dun":
        return NETWORK_TYPE_MOBILE_DUN;
      case "fota":
        return NETWORK_TYPE_MOBILE_FOTA;
      default:
        return NETWORK_TYPE_UNKNOWN;
     }
  },

  _compareDataCallOptions: function(aDataCall, aNewDataCall) {
    return aDataCall.apnProfile.apn == aNewDataCall.apnProfile.apn &&
           aDataCall.apnProfile.user == aNewDataCall.apnProfile.user &&
           aDataCall.apnProfile.password == aNewDataCall.apnProfile.passwd &&
           aDataCall.apnProfile.authType == aNewDataCall.apnProfile.authType &&
           aDataCall.apnProfile.protocol == aNewDataCall.apnProfile.protocol &&
           aDataCall.apnProfile.roaming_protocol == aNewDataCall.apnProfile.roaming_protocol;
  },

  /**
   * This function will do the following steps:
   *   1. Clear the cached APN settings in the RIL.
   *   2. Combine APN, user name, and password as the key of |byApn| object to
   *      refer to the corresponding APN setting.
   *   3. Use APN type as the index of |byType| object to refer to the
   *      corresponding APN setting.
   *   4. Create RilNetworkInterface for each APN setting created at step 2.
   */
  _setupApnSettings: function(aNewApnSettings) {
    if (!aNewApnSettings) {
      return;
    }
    if (DEBUG) this.debug("setupApnSettings: " + JSON.stringify(aNewApnSettings));

    // Shutdown all network interfaces and clear data calls.
    this.dataNetworkInterfaces.forEach(function(networkInterface) {
      gNetworkManager.unregisterNetworkInterface(networkInterface);
      networkInterface.shutdown();
      networkInterface = null;
    });
    this.dataNetworkInterfaces.clear();
    this._dataCalls = [];

    // Cache the APN settings by APNs and by types in the RIL.
    for (let inputApnSetting of aNewApnSettings) {
      if (!this._validateApnSetting(inputApnSetting)) {
        continue;
      }

      // Use APN type as the key of dataNetworkInterfaces to refer to the
      // corresponding RILNetworkInterface.
      for (let i = 0; i < inputApnSetting.types.length; i++) {
        let apnType = inputApnSetting.types[i];
        let networkType = this._convertApnType(apnType);
        if (networkType === NETWORK_TYPE_UNKNOWN) {
          if (DEBUG) this.debug("Invalid apn type: " + apnType);
          continue;
        }

        if (DEBUG) this.debug("Preparing RILNetworkInterface for type: " + apnType);
        // Create DataCall for RILNetworkInterface or reuse one that is shareable.
        let dataCall;
        for (let i = 0; i < this._dataCalls.length; i++) {
          if (this._dataCalls[i].canHandleApn(inputApnSetting)) {
            if (DEBUG) this.debug("Found shareable DataCall, reusing it.");
            dataCall = this._dataCalls[i];
            break;
          }
        }

        if (!dataCall) {
          if (DEBUG) this.debug("No shareable DataCall found, creating one.");
          dataCall = new DataCall(this.clientId, inputApnSetting, this);
          this._dataCalls.push(dataCall);
        }

        try {
          let networkInterface = new RILNetworkInterface(this, networkType,
                                                         inputApnSetting,
                                                         dataCall);
          gNetworkManager.registerNetworkInterface(networkInterface);
          this.dataNetworkInterfaces.set(networkType, networkInterface);
        } catch (e) {
          if (DEBUG) {
            this.debug("Error setting up RILNetworkInterface for type " +
                        apnType + ": " + e);
          }
        }
      }
    }
  },

  /**
   * Check if all data is disconnected.
   */
  allDataDisconnected: function() {
    for (let i = 0; i < this._dataCalls.length; i++) {
      let dataCall = this._dataCalls[i];
      if (dataCall.state != NETWORK_STATE_UNKNOWN &&
          dataCall.state != NETWORK_STATE_DISCONNECTED) {
        return false;
      }
    }
    return true;
  },

  deactivateDataCallsAndWait: function() {
    return new Promise((aResolve, aReject) => {
      this.deactivateDataCalls({
        notifyDataCallsDisconnected: function() {
          aResolve();
        }
      });
    });
  },

  updateApnSettings: function(aNewApnSettings) {
    if (!aNewApnSettings) {
      return;
    }
    if (this._pendingApnSettings) {
      // Change of apn settings in process, just update to the newest.
      this._pengingApnSettings = aNewApnSettings;
      return;
    }

    this._pendingApnSettings = aNewApnSettings;
    this.deactivateDataCallsAndWait().then(() => {
      this._setupApnSettings(this._pendingApnSettings);
      this._pendingApnSettings = null;
      this.updateRILNetworkInterface();
    });
  },

  updateRILNetworkInterface: function() {
    let networkInterface = this.dataNetworkInterfaces.get(NETWORK_TYPE_MOBILE);
    if (!networkInterface) {
      if (DEBUG) {
        this.debug("No network interface for default data.");
      }
      return;
    }

    let connection =
      gMobileConnectionService.getItemByServiceId(this.clientId);

    // This check avoids data call connection if the radio is not ready
    // yet after toggling off airplane mode.
    let radioState = connection && connection.radioState;
    if (radioState != Ci.nsIMobileConnection.MOBILE_RADIO_STATE_ENABLED) {
      if (DEBUG) {
        this.debug("RIL is not ready for data connection: radio's not ready");
      }
      return;
    }

    // We only watch at "ril.data.enabled" flag changes for connecting or
    // disconnecting the data call. If the value of "ril.data.enabled" is
    // true and any of the remaining flags change the setting application
    // should turn this flag to false and then to true in order to reload
    // the new values and reconnect the data call.
    if (this.dataCallSettings.oldEnabled === this.dataCallSettings.enabled) {
      if (DEBUG) {
        this.debug("No changes for ril.data.enabled flag. Nothing to do.");
      }
      return;
    }

    let dataInfo = connection && connection.data;
    let isRegistered =
      dataInfo &&
      dataInfo.state == RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED;
    let haveDataConnection =
      dataInfo &&
      dataInfo.type != RIL.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN;
    if (!isRegistered || !haveDataConnection) {
      if (DEBUG) {
        this.debug("RIL is not ready for data connection: Phone's not " +
                   "registered or doesn't have data connection.");
      }
      return;
    }
    let wifi_active = false;
    if (gNetworkManager.activeNetworkInfo &&
        gNetworkManager.activeNetworkInfo.type == NETWORK_TYPE_WIFI) {
      wifi_active = true;
    }

    let defaultDataCallConnected = networkInterface.connected;

    // We have moved part of the decision making into DataCall, the rest will be
    // moved after Bug 904514 - [meta] NetworkManager enhancement.
    if (networkInterface.enabled &&
        (!this.dataCallSettings.enabled ||
         (dataInfo.roaming && !this.dataCallSettings.roamingEnabled))) {
      if (DEBUG) {
        this.debug("Data call settings: disconnect data call.");
      }
      networkInterface.disconnect();
      return;
    }

    if (networkInterface.enabled && wifi_active) {
      if (DEBUG) {
        this.debug("Disconnect data call when Wifi is connected.");
      }
      networkInterface.disconnect();
      return;
    }

    if (!this.dataCallSettings.enabled || defaultDataCallConnected) {
      if (DEBUG) {
        this.debug("Data call settings: nothing to do.");
      }
      return;
    }
    if (dataInfo.roaming && !this.dataCallSettings.roamingEnabled) {
      if (DEBUG) {
        this.debug("We're roaming, but data roaming is disabled.");
      }
      return;
    }
    if (wifi_active) {
      if (DEBUG) {
        this.debug("Don't connect data call when Wifi is connected.");
      }
      return;
    }
    if (this._pendingApnSettings) {
      if (DEBUG) this.debug("We're changing apn settings, ignore any changes.");
      return;
    }

    if (this._deactivatingDataCalls) {
      if (DEBUG) this.debug("We're deactivating all data calls, ignore any changes.");
      return;
    }

    if (DEBUG) {
      this.debug("Data call settings: connect data call.");
    }
    networkInterface.connect();
  },

  _isMobileNetworkType: function(aNetworkType) {
    if (aNetworkType === NETWORK_TYPE_MOBILE ||
        aNetworkType === NETWORK_TYPE_MOBILE_MMS ||
        aNetworkType === NETWORK_TYPE_MOBILE_SUPL ||
        aNetworkType === NETWORK_TYPE_MOBILE_IMS ||
        aNetworkType === NETWORK_TYPE_MOBILE_DUN ||
        aNetworkType === NETWORK_TYPE_MOBILE_FOTA) {
      return true;
    }

    return false;
  },

  getDataCallStateByType: function(aNetworkType) {
    if (!this._isMobileNetworkType(aNetworkType)) {
      if (DEBUG) this.debug(aNetworkType + " is not a mobile network type!");
      throw Cr.NS_ERROR_INVALID_ARG;
    }

    let networkInterface = this.dataNetworkInterfaces.get(aNetworkType);
    if (!networkInterface) {
      return NETWORK_STATE_UNKNOWN;
    }
    return networkInterface.info.state;
  },

  setupDataCallByType: function(aNetworkType) {
    if (DEBUG) {
      this.debug("setupDataCallByType: " + aNetworkType);
    }

    if (!this._isMobileNetworkType(aNetworkType)) {
      if (DEBUG) this.debug(aNetworkType + " is not a mobile network type!");
      throw Cr.NS_ERROR_INVALID_ARG;
    }

    let networkInterface = this.dataNetworkInterfaces.get(aNetworkType);
    if (!networkInterface) {
      if (DEBUG) {
        this.debug("No network interface for type: " + aNetworkType);
      }
      return;
    }

    networkInterface.connect();
  },

  deactivateDataCallByType: function(aNetworkType) {
    if (DEBUG) {
      this.debug("deactivateDataCallByType: " + aNetworkType);
    }

    if (!this._isMobileNetworkType(aNetworkType)) {
      if (DEBUG) this.debug(aNetworkType + " is not a mobile network type!");
      throw Cr.NS_ERROR_INVALID_ARG;
    }

    let networkInterface = this.dataNetworkInterfaces.get(aNetworkType);
    if (!networkInterface) {
      if (DEBUG) {
        this.debug("No network interface for type: " + aNetworkType);
      }
      return;
    }

    networkInterface.disconnect();
  },

  _deactivatingDataCalls: false,

  deactivateDataCalls: function(aCallback) {
    let dataDisconnecting = false;
    this.dataNetworkInterfaces.forEach(function(networkInterface) {
      if (networkInterface.enabled) {
        if (networkInterface.info.state != NETWORK_STATE_UNKNOWN &&
            networkInterface.info.state != NETWORK_STATE_DISCONNECTED) {
          dataDisconnecting = true;
        }
        networkInterface.disconnect();
      }
    });

    this._deactivatingDataCalls = dataDisconnecting;
    if (!dataDisconnecting) {
      aCallback.notifyDataCallsDisconnected();
      return;
    }

    let callback = {
      notifyAllDataDisconnected: () => {
        this._unregisterListener(callback);
        aCallback.notifyDataCallsDisconnected();
      }
    };
    this._registerListener(callback);
  },

  _listeners: null,

  _notifyListeners: function(aMethodName, aArgs) {
    let listeners = this._listeners.slice();
    for (let listener of listeners) {
      if (this._listeners.indexOf(listener) == -1) {
        // Listener has been unregistered in previous run.
        continue;
      }

      let handler = listener[aMethodName];
      try {
        handler.apply(listener, aArgs);
      } catch (e) {
        this.debug("listener for " + aMethodName + " threw an exception: " + e);
      }
    }
  },

  _registerListener: function(aListener) {
    if (this._listeners.indexOf(aListener) >= 0) {
      return;
    }

    this._listeners.push(aListener);
  },

  _unregisterListener: function(aListener) {
    let index = this._listeners.indexOf(aListener);
    if (index >= 0) {
      this._listeners.splice(index, 1);
    }
  },

  _findDataCallByCid: function(aCid) {
    if (aCid === undefined || aCid < 0) {
      return -1;
    }

    for (let i = 0; i < this._dataCalls.length; i++) {
      let datacall = this._dataCalls[i];
      if (datacall.linkInfo.cid != null &&
          datacall.linkInfo.cid == aCid) {
        return i;
      }
    }

    return -1;
  },

  /**
   * Notify about data call setup error, called from DataCall.
   */
  notifyDataCallError: function(aDataCall, aErrorMsg) {
    // Notify data call error only for data APN
    let networkInterface = this.dataNetworkInterfaces.get(NETWORK_TYPE_MOBILE);
    if (networkInterface && networkInterface.enabled) {
      let dataCall = networkInterface.dataCall;
      if (this._compareDataCallOptions(dataCall, aDataCall)) {
        Services.obs.notifyObservers(networkInterface.info,
                                     TOPIC_DATA_CALL_ERROR, aErrorMsg);
      }
    }
  },

  /**
   * Notify about data call changed, called from DataCall.
   */
  notifyDataCallChanged: function(aUpdatedDataCall) {
    // Process pending radio power off request after all data calls
    // are disconnected.
    if (aUpdatedDataCall.state == NETWORK_STATE_DISCONNECTED ||
        aUpdatedDataCall.state == NETWORK_STATE_UNKNOWN &&
        this.allDataDisconnected() && this._deactivatingDataCalls) {
      this._deactivatingDataCalls = false;
      this._notifyListeners("notifyAllDataDisconnected", {
        clientId: this.clientId
      });
    }
  },

  // nsIDataCallInterfaceListener

  notifyDataCallListChanged: function(aCount, aDataCallList) {
    let currentDataCalls = this._dataCalls.slice();
    for (let i = 0; i < aDataCallList.length; i++) {
      let dataCall = aDataCallList[i];
      let index = this._findDataCallByCid(dataCall.cid);
      if (index == -1) {
        if (DEBUG) {
          this.debug("Unexpected new data call: " + JSON.stringify(dataCall));
        }
        continue;
      }
      currentDataCalls[index].onDataCallChanged(dataCall);
      currentDataCalls[index] = null;
    }

    // If there is any CONNECTED DataCall left in currentDataCalls, means that
    // it is missing in dataCallList, we should send a DISCONNECTED event to
    // notify about this.
    for (let i = 0; i < currentDataCalls.length; i++) {
      let currentDataCall = currentDataCalls[i];
      if (currentDataCall && currentDataCall.linkInfo.cid != null &&
          currentDataCall.state == NETWORK_STATE_CONNECTED) {
        if (DEBUG) {
          this.debug("Expected data call missing: " + JSON.stringify(
            currentDataCall.apnProfile) + ", must have been DISCONNECTED.");
        }
        currentDataCall.onDataCallChanged({
          state: NETWORK_STATE_DISCONNECTED
        });
      }
    }
  },

  // nsIMobileConnectionListener

  notifyVoiceChanged: function() {},

  notifyDataChanged: function () {
    let connection = gMobileConnectionService.getItemByServiceId(this.clientId);
    let newDataInfo = connection.data;

    if (this._dataInfo.state == newDataInfo.state &&
        this._dataInfo.type == newDataInfo.type &&
        this._dataInfo.roaming == newDataInfo.roaming) {
      return;
    }

    this._dataInfo.state = newDataInfo.state;
    this._dataInfo.type = newDataInfo.type;
    this._dataInfo.roaming = newDataInfo.roaming;
    this.updateRILNetworkInterface();
  },

  notifyDataError: function (aMessage) {},

  notifyCFStateChanged: function(aAction, aReason, aNumber, aTimeSeconds, aServiceClass) {},

  notifyEmergencyCbModeChanged: function(aActive, aTimeoutMs) {},

  notifyOtaStatusChanged: function(aStatus) {},

  notifyRadioStateChanged: function() {},

  notifyClirModeChanged: function(aMode) {},

  notifyLastKnownNetworkChanged: function() {},

  notifyLastKnownHomeNetworkChanged: function() {},

  notifyNetworkSelectionModeChanged: function() {},

  notifyDeviceIdentitiesChanged: function() {}
};

function DataCall(aClientId, aApnSetting, aDataCallHandler) {
  this.clientId = aClientId;
  this.dataCallHandler = aDataCallHandler;
  this.apnProfile = {
    apn: aApnSetting.apn,
    user: aApnSetting.user,
    password: aApnSetting.password,
    authType: aApnSetting.authtype,
    protocol: aApnSetting.protocol,
    roaming_protocol: aApnSetting.roaming_protocol
  };
  this.linkInfo = {
    cid: null,
    ifname: null,
    addresses: [],
    dnses: [],
    gateways: [],
    pcscf: [],
    mtu: null
  };
  this.state = NETWORK_STATE_UNKNOWN;
  this.requestedNetworkIfaces = [];
}
DataCall.prototype = {
  /**
   * Standard values for the APN connection retry process
   * Retry funcion: time(secs) = A * numer_of_retries^2 + B
   */
  NETWORK_APNRETRY_FACTOR: 8,
  NETWORK_APNRETRY_ORIGIN: 3,
  NETWORK_APNRETRY_MAXRETRIES: 10,

  dataCallHandler: null,

  // Event timer for connection retries
  timer: null,

  // APN failed connections. Retry counter
  apnRetryCounter: 0,

  // Array to hold RILNetworkInterfaces that requested this DataCall.
  requestedNetworkIfaces: null,

  /**
   * @return "deactivate" if <ifname> changes or one of the aCurrentDataCall
   *         addresses is missing in updatedDataCall, or "identical" if no
   *         changes found, or "changed" otherwise.
   */
  _compareDataCallLink: function(aUpdatedDataCall, aCurrentDataCall) {
    // If network interface is changed, report as "deactivate".
    if (aUpdatedDataCall.ifname != aCurrentDataCall.ifname) {
      return "deactivate";
    }

    // If any existing address is missing, report as "deactivate".
    for (let i = 0; i < aCurrentDataCall.addresses.length; i++) {
      let address = aCurrentDataCall.addresses[i];
      if (aUpdatedDataCall.addresses.indexOf(address) < 0) {
        return "deactivate";
      }
    }

    if (aCurrentDataCall.addresses.length != aUpdatedDataCall.addresses.length) {
      // Since now all |aCurrentDataCall.addresses| are found in
      // |aUpdatedDataCall.addresses|, this means one or more new addresses are
      // reported.
      return "changed";
    }

    let fields = ["gateways", "dnses"];
    for (let i = 0; i < fields.length; i++) {
      // Compare <datacall>.<field>.
      let field = fields[i];
      let lhs = aUpdatedDataCall[field], rhs = aCurrentDataCall[field];
      if (lhs.length != rhs.length) {
        return "changed";
      }
      for (let i = 0; i < lhs.length; i++) {
        if (lhs[i] != rhs[i]) {
          return "changed";
        }
      }
    }

    if (aCurrentDataCall.mtu != aUpdatedDataCall.mtu) {
      return "changed";
    }

    return "identical";
  },

  _getGeckoDataCallState:function (aDataCall) {
    if (aDataCall.active == Ci.nsIDataCallInterface.DATACALL_STATE_ACTIVE_UP ||
        aDataCall.active == Ci.nsIDataCallInterface.DATACALL_STATE_ACTIVE_DOWN) {
      return NETWORK_STATE_CONNECTED;
    }

    return NETWORK_STATE_DISCONNECTED;
  },

  onSetupDataCallResult: function(aDataCall) {
    this.debug("onSetupDataCallResult: " + JSON.stringify(aDataCall));
    let errorMsg = aDataCall.errorMsg;
    if (aDataCall.failCause &&
        aDataCall.failCause != Ci.nsIDataCallInterface.DATACALL_FAIL_NONE) {
      errorMsg =
        RIL.RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[aDataCall.failCause];
    }

    if (errorMsg) {
      if (DEBUG) {
        this.debug("SetupDataCall error for apn " + this.apnProfile.apn + ": " +
                   errorMsg + " (" + aDataCall.failCause + "), retry time: " +
                   aDataCall.suggestedRetryTime);
      }

      this.state = NETWORK_STATE_DISCONNECTED;

      if (this.requestedNetworkIfaces.length === 0) {
        if (DEBUG) this.debug("This DataCall is not requested anymore.");
        return;
      }

      // Let DataCallHandler notify MobileConnectionService
      this.dataCallHandler.notifyDataCallError(this, errorMsg);

      // For suggestedRetryTime, the value of INT32_MAX(0x7fffffff) means no retry.
      if (aDataCall.suggestedRetryTime === INT32_MAX ||
          this.isPermanentFail(aDataCall.failCause, errorMsg)) {
        if (DEBUG) this.debug("Data call error: no retry needed.");
        return;
      }

      this.retry(aDataCall.suggestedRetryTime);
      return;
    }

    this.apnRetryCounter = 0;
    this.linkInfo.cid = aDataCall.cid;

    if (this.requestedNetworkIfaces.length === 0) {
      if (DEBUG) {
        this.debug("State is connected, but no network interface requested" +
                   " this DataCall");
      }
      this.deactivate();
      return;
    }

    this.linkInfo.ifname = aDataCall.ifname;
    this.linkInfo.addresses = aDataCall.addresses ? aDataCall.addresses.split(" ") : [];
    this.linkInfo.gateways = aDataCall.gateways ? aDataCall.gateways.split(" ") : [];
    this.linkInfo.dnses = aDataCall.dnses ? aDataCall.dnses.split(" ") : [];
    this.linkInfo.pcscf = aDataCall.pcscf ? aDataCall.pcscf.split(" ") : [];
    this.linkInfo.mtu = aDataCall.mtu > 0 ? aDataCall.mtu : 0;
    this.state = this._getGeckoDataCallState(aDataCall);

    // Notify DataCallHandler about data call connected.
    this.dataCallHandler.notifyDataCallChanged(this);

    for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
      this.requestedNetworkIfaces[i].notifyRILNetworkInterface();
    }
  },

  onDeactivateDataCallResult: function() {
    if (DEBUG) this.debug("onDeactivateDataCallResult");

    this.reset();

    if (this.requestedNetworkIfaces.length > 0) {
      if (DEBUG) {
        this.debug("State is disconnected/unknown, but this DataCall is" +
                   " requested.");
      }
      this.setup();
      return;
    }

    // Notify DataCallHandler about data call disconnected.
    this.dataCallHandler.notifyDataCallChanged(this);
  },

  onDataCallChanged: function(aUpdatedDataCall) {
    if (DEBUG) {
      this.debug("onDataCallChanged: " + JSON.stringify(aUpdatedDataCall));
    }

    if (this.state == NETWORK_STATE_CONNECTING ||
        this.state == NETWORK_STATE_DISCONNECTING) {
      if (DEBUG) {
        this.debug("We are in connecting/disconnecting state, ignore any " +
                   "unsolicited event for now.");
      }
      return;
    }

    let dataCallState = this._getGeckoDataCallState(aUpdatedDataCall);
    if (this.state == dataCallState &&
        dataCallState != NETWORK_STATE_CONNECTED) {
      return;
    }

    let newLinkInfo = {
      ifname: aUpdatedDataCall.ifname,
      addresses: aUpdatedDataCall.addresses ? aUpdatedDataCall.addresses.split(" ") : [],
      dnses: aUpdatedDataCall.dnses ? aUpdatedDataCall.dnses.split(" ") : [],
      gateways: aUpdatedDataCall.gateways ? aUpdatedDataCall.gateways.split(" ") : [],
      pcscf: aUpdatedDataCall.pcscf ? aUpdatedDataCall.pcscf.split(" ") : [],
      mtu: aUpdatedDataCall.mtu > 0 ? aUpdatedDataCall.mtu : 0
    };

    switch (dataCallState) {
      case NETWORK_STATE_CONNECTED:
        if (this.state == NETWORK_STATE_CONNECTED) {
          let result =
            this._compareDataCallLink(newLinkInfo, this.linkInfo);

          if (result == "identical") {
            if (DEBUG) this.debug("No changes in data call.");
            return;
          }
          if (result == "deactivate") {
            if (DEBUG) this.debug("Data link changed, cleanup.");
            this.deactivate();
            return;
          }
          // Minor change, just update and notify.
          if (DEBUG) {
            this.debug("Data link minor change, just update and notify.");
          }

          this.linkInfo.addresses = newLinkInfo.addresses.slice();
          this.linkInfo.gateways = newLinkInfo.gateways.slice();
          this.linkInfo.dnses = newLinkInfo.dnses.slice();
          this.linkInfo.pcscf = newLinkInfo.pcscf.slice();
          this.linkInfo.mtu = newLinkInfo.mtu;
        }
        break;
      case NETWORK_STATE_DISCONNECTED:
      case NETWORK_STATE_UNKNOWN:
        if (this.state == NETWORK_STATE_CONNECTED) {
          // Notify first on unexpected data call disconnection.
          this.state = dataCallState;
          for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
            this.requestedNetworkIfaces[i].notifyRILNetworkInterface();
          }
        }
        this.reset();

        if (this.requestedNetworkIfaces.length > 0) {
          if (DEBUG) {
            this.debug("State is disconnected/unknown, but this DataCall is" +
                       " requested.");
          }
          this.setup();
          return;
        }
        break;
    }

    this.state = dataCallState;

    // Notify DataCallHandler about data call changed.
    this.dataCallHandler.notifyDataCallChanged(this);

    for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
      this.requestedNetworkIfaces[i].notifyRILNetworkInterface();
    }
  },

  // Helpers

  debug: function(aMsg) {
    dump("-*- DataCall[" + this.clientId + ":" + this.apnProfile.apn + "]: " +
      aMsg + "\n");
  },

  get connected() {
    return this.state == NETWORK_STATE_CONNECTED;
  },

  isPermanentFail: function(aDataFailCause, aErrorMsg) {
    // Check ril.h for 'no retry' data call fail causes.
    if (aErrorMsg === RIL.GECKO_ERROR_RADIO_NOT_AVAILABLE ||
        aErrorMsg === RIL.GECKO_ERROR_INVALID_PARAMETER ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_OPERATOR_BARRED ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_MISSING_UKNOWN_APN ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_UNKNOWN_PDP_ADDRESS_TYPE ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_USER_AUTHENTICATION ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_ACTIVATION_REJECT_GGSN ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_SERVICE_OPTION_NOT_SUPPORTED ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_SERVICE_OPTION_NOT_SUBSCRIBED ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_NSAPI_IN_USE ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_ONLY_IPV4_ALLOWED ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_ONLY_IPV6_ALLOWED ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_PROTOCOL_ERRORS ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_RADIO_POWER_OFF ||
        aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_TETHERED_CALL_ACTIVE) {
      return true;
    }

    return false;
  },

  inRequestedTypes: function(aType) {
    for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
      if (this.requestedNetworkIfaces[i].info.type == aType) {
        return true;
      }
    }
    return false;
  },

  canHandleApn: function(aApnSetting) {
    let isIdentical = this.apnProfile.apn == aApnSetting.apn &&
                      (this.apnProfile.user || '') == (aApnSetting.user || '') &&
                      (this.apnProfile.password || '') == (aApnSetting.password || '') &&
                      (this.apnProfile.authType || '') == (aApnSetting.authtype || '');

    if (RILQUIRKS_HAVE_IPV6) {
      isIdentical = isIdentical &&
                    (this.apnProfile.protocol || '') == (aApnSetting.protocol || '') &&
                    (this.apnProfile.roaming_protocol || '') == (aApnSetting.roaming_protocol || '');
    }

    return isIdentical;
  },

  resetLinkInfo: function() {
    this.linkInfo.cid = null;
    this.linkInfo.ifname = null;
    this.linkInfo.addresses = [];
    this.linkInfo.dnses = [];
    this.linkInfo.gateways = [];
    this.linkInfo.pcscf = [];
    this.linkInfo.mtu = null;
  },

  reset: function() {
    this.resetLinkInfo();

    this.state = NETWORK_STATE_UNKNOWN;
  },

  connect: function(aNetworkInterface) {
    if (DEBUG) this.debug("connect: " + aNetworkInterface.info.type);

    if (this.requestedNetworkIfaces.indexOf(aNetworkInterface) == -1) {
      this.requestedNetworkIfaces.push(aNetworkInterface);
    }

    if (this.state == NETWORK_STATE_CONNECTING ||
        this.state == NETWORK_STATE_DISCONNECTING) {
      return;
    }
    if (this.state == NETWORK_STATE_CONNECTED) {
      // This needs to run asynchronously, to behave the same way as the case of
      // non-shared apn, see bug 1059110.
      Services.tm.currentThread.dispatch(() => {
        // Do not notify if state changed while this event was being dispatched,
        // the state probably was notified already or need not to be notified.
        if (aNetworkInterface.info.state == RIL.GECKO_NETWORK_STATE_CONNECTED) {
          aNetworkInterface.notifyRILNetworkInterface();
        }
      }, Ci.nsIEventTarget.DISPATCH_NORMAL);
      return;
    }

    // If retry mechanism is running on background, stop it since we are going
    // to setup data call now.
    if (this.timer) {
      this.timer.cancel();
    }

    this.setup();
  },

  setup: function() {
    if (DEBUG) {
      this.debug("Going to set up data connection with APN " +
                 this.apnProfile.apn);
    }

    let connection =
      gMobileConnectionService.getItemByServiceId(this.clientId);
    let dataInfo = connection && connection.data;
    if (dataInfo == null ||
        dataInfo.state != RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED ||
        dataInfo.type == RIL.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN) {
      return;
    }

    let radioTechType = dataInfo.type;
    let radioTechnology = RIL.GECKO_RADIO_TECH.indexOf(radioTechType);
    let authType = RIL.RIL_DATACALL_AUTH_TO_GECKO.indexOf(this.apnProfile.authType);
    // Use the default authType if the value in database is invalid.
    // For the case that user might not select the authentication type.
    if (authType == -1) {
      if (DEBUG) {
        this.debug("Invalid authType '" + this.apnProfile.authtype +
                   "', using '" + RIL.GECKO_DATACALL_AUTH_DEFAULT + "'");
      }
      authType = RIL.RIL_DATACALL_AUTH_TO_GECKO.indexOf(RIL.GECKO_DATACALL_AUTH_DEFAULT);
    }

    let pdpType = Ci.nsIDataCallInterface.DATACALL_PDP_TYPE_IPV4;
    if (RILQUIRKS_HAVE_IPV6) {
      pdpType = !dataInfo.roaming
              ? RIL.RIL_DATACALL_PDP_TYPES.indexOf(this.apnProfile.protocol)
              : RIL.RIL_DATACALL_PDP_TYPES.indexOf(this.apnProfile.roaming_protocol);
      if (pdpType == -1) {
        if (DEBUG) {
          this.debug("Invalid pdpType '" + (!dataInfo.roaming
                     ? this.apnProfile.protocol
                     : this.apnProfile.roaming_protocol) +
                     "', using '" + RIL.GECKO_DATACALL_PDP_TYPE_DEFAULT + "'");
        }
        pdpType = RIL.RIL_DATACALL_PDP_TYPES.indexOf(RIL.GECKO_DATACALL_PDP_TYPE_DEFAULT);
      }
    }

    let dcInterface = this.dataCallHandler.dataCallInterface;
    dcInterface.setupDataCall(
      this.apnProfile.apn, this.apnProfile.user, this.apnProfile.password,
      authType, pdpType, {
        QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallCallback]),
        notifySetupDataCallSuccess: (aDataCall) => {
          this.onSetupDataCallResult(aDataCall);
        },
        notifyError: (aErrorMsg) => {
          this.onSetupDataCallResult({errorMsg: aErrorMsg});
        }
      });
    this.state = NETWORK_STATE_CONNECTING;
  },

  retry: function(aSuggestedRetryTime) {
    let apnRetryTimer;

    // We will retry the connection in increasing times
    // based on the function: time = A * numer_of_retries^2 + B
    if (this.apnRetryCounter >= this.NETWORK_APNRETRY_MAXRETRIES) {
      this.apnRetryCounter = 0;
      this.timer = null;
      if (DEBUG) this.debug("Too many APN Connection retries - STOP retrying");
      return;
    }

    // If there is a valid aSuggestedRetryTime, override the retry timer.
    if (aSuggestedRetryTime !== undefined && aSuggestedRetryTime >= 0) {
      apnRetryTimer = aSuggestedRetryTime / 1000;
    } else {
      apnRetryTimer = this.NETWORK_APNRETRY_FACTOR *
                      (this.apnRetryCounter * this.apnRetryCounter) +
                      this.NETWORK_APNRETRY_ORIGIN;
    }
    this.apnRetryCounter++;
    if (DEBUG) {
      this.debug("Data call - APN Connection Retry Timer (secs-counter): " +
                 apnRetryTimer + "-" + this.apnRetryCounter);
    }

    if (this.timer == null) {
      // Event timer for connection retries
      this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    }
    this.timer.initWithCallback(this, apnRetryTimer * 1000,
                                Ci.nsITimer.TYPE_ONE_SHOT);
  },

  disconnect: function(aNetworkInterface) {
    if (DEBUG) this.debug("disconnect: " + aNetworkInterface.info.type);

    let index = this.requestedNetworkIfaces.indexOf(aNetworkInterface);
    if (index != -1) {
      this.requestedNetworkIfaces.splice(index, 1);

      if (this.state == NETWORK_STATE_DISCONNECTED ||
          this.state == NETWORK_STATE_UNKNOWN) {
        if (this.timer) {
          this.timer.cancel();
        }
        this.reset();
        return;
      }

      // Notify the DISCONNECTED event immediately after network interface is
      // removed from requestedNetworkIfaces, to make the DataCall, shared or
      // not, to have the same behavior.
      Services.tm.currentThread.dispatch(() => {
        // Do not notify if state changed while this event was being dispatched,
        // the state probably was notified already or need not to be notified.
        if (aNetworkInterface.info.state == RIL.GECKO_NETWORK_STATE_DISCONNECTED) {
          aNetworkInterface.notifyRILNetworkInterface();

          // Clear link info after notifying NetworkManager.
          if (this.requestedNetworkIfaces.length === 0) {
            this.resetLinkInfo();
          }
        }
      }, Ci.nsIEventTarget.DISPATCH_NORMAL);
    }

    // Only deactivate data call if no more network interface needs this
    // DataCall and if state is CONNECTED, for other states, we simply remove
    // the network interface from requestedNetworkIfaces.
    if (this.requestedNetworkIfaces.length > 0 ||
        this.state != NETWORK_STATE_CONNECTED) {
      return;
    }

    this.deactivate();
  },

  deactivate: function() {
    let reason = Ci.nsIDataCallInterface.DATACALL_DEACTIVATE_NO_REASON;
    if (DEBUG) {
      this.debug("Going to disconnect data connection cid " + this.linkInfo.cid);
    }

    let dcInterface = this.dataCallHandler.dataCallInterface;
    dcInterface.deactivateDataCall(this.linkInfo.cid, reason, {
      QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallCallback]),
      notifySuccess: () => {
        this.onDeactivateDataCallResult();
      },
      notifyError: (aErrorMsg) => {
        this.onDeactivateDataCallResult();
      }
    });

    this.state = NETWORK_STATE_DISCONNECTING;
  },

  // Entry method for timer events. Used to reconnect to a failed APN
  notify: function(aTimer) {
    this.setup();
  },

  shutdown: function() {
    if (this.timer) {
      this.timer.cancel();
      this.timer = null;
    }
  }
};

function RILNetworkInfo(aClientId, aType, aNetworkInterface)
{
  this.serviceId = aClientId;
  this.type = aType;

  this.networkInterface = aNetworkInterface;
}
RILNetworkInfo.prototype = {
  classID:   RILNETWORKINFO_CID,
  classInfo: XPCOMUtils.generateCI({classID: RILNETWORKINFO_CID,
                                    classDescription: "RILNetworkInfo",
                                    interfaces: [Ci.nsINetworkInfo,
                                                 Ci.nsIRilNetworkInfo]}),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInfo,
                                         Ci.nsIRilNetworkInfo]),

  networkInterface: null,

  getDataCall: function() {
    return this.networkInterface.dataCall;
  },

  getApnSetting: function() {
    return this.networkInterface.apnSetting;
  },

  debug: function(aMsg) {
    dump("-*- RILNetworkInfo[" + this.serviceId + ":" + this.type + "]: " +
         aMsg + "\n");
  },

  /**
   * nsINetworkInfo Implementation
   */
  get state() {
    let dataCall = this.getDataCall();
    if (!dataCall.inRequestedTypes(this.type)) {
      return NETWORK_STATE_DISCONNECTED;
    }
    return dataCall.state;
  },

  type: null,

  get name() {
    return this.getDataCall().linkInfo.ifname;
  },

  getAddresses: function(aIps, aPrefixLengths) {
    let addresses = this.getDataCall().linkInfo.addresses;

    let ips = [];
    let prefixLengths = [];
    for (let i = 0; i < addresses.length; i++) {
      let [ip, prefixLength] = addresses[i].split("/");
      ips.push(ip);
      prefixLengths.push(prefixLength);
    }

    aIps.value = ips.slice();
    aPrefixLengths.value = prefixLengths.slice();

    return ips.length;
  },

  getGateways: function(aCount) {
    let linkInfo = this.getDataCall().linkInfo;

    if (aCount) {
      aCount.value = linkInfo.gateways.length;
    }

    return linkInfo.gateways.slice();
  },

  getDnses: function(aCount) {
    let linkInfo = this.getDataCall().linkInfo;

    if (aCount) {
      aCount.value = linkInfo.dnses.length;
    }

    return linkInfo.dnses.slice();
  },

  /**
   * nsIRilNetworkInfo Implementation
   */

  serviceId: 0,

  get iccId() {
    let icc = gIccService.getIccByServiceId(this.serviceId);
    let iccInfo = icc && icc.iccInfo;

    return iccInfo && iccInfo.iccid;
  },

  get mmsc() {
    if (this.type != NETWORK_TYPE_MOBILE_MMS) {
      if (DEBUG) this.debug("Error! Only MMS network can get MMSC.");
      throw Cr.NS_ERROR_UNEXPECTED;
    }

    return this.getApnSetting().mmsc || "";
  },

  get mmsProxy() {
    if (this.type != NETWORK_TYPE_MOBILE_MMS) {
      if (DEBUG) this.debug("Error! Only MMS network can get MMS proxy.");
      throw Cr.NS_ERROR_UNEXPECTED;
    }

    return this.getApnSetting().mmsproxy || "";
  },

  get mmsPort() {
    if (this.type != NETWORK_TYPE_MOBILE_MMS) {
      if (DEBUG) this.debug("Error! Only MMS network can get MMS port.");
      throw Cr.NS_ERROR_UNEXPECTED;
    }

    // Note: Port 0 is reserved, so we treat it as invalid as well.
    // See http://www.iana.org/assignments/port-numbers
    return this.getApnSetting().mmsport || -1;
  },

  getPcscf: function(aCount) {
    if (this.type != NETWORK_TYPE_MOBILE_IMS) {
      if (DEBUG) this.debug("Error! Only IMS network can get pcscf.");
      throw Cr.NS_ERROR_UNEXPECTED;
    }

    let linkInfo = this.getDataCall().linkInfo;

    if (aCount) {
      aCount.value = linkInfo.pcscf.length;
    }
    return linkInfo.pcscf.slice();
  },
};

function RILNetworkInterface(aDataCallHandler, aType, aApnSetting, aDataCall) {
  if (!aDataCall) {
    throw new Error("No dataCall for RILNetworkInterface: " + type);
  }

  this.dataCallHandler = aDataCallHandler;
  this.enabled = false;
  this.dataCall = aDataCall;
  this.apnSetting = aApnSetting;

  this.info = new RILNetworkInfo(aDataCallHandler.clientId, aType, this);
}

RILNetworkInterface.prototype = {
  classID:   RILNETWORKINTERFACE_CID,
  classInfo: XPCOMUtils.generateCI({classID: RILNETWORKINTERFACE_CID,
                                    classDescription: "RILNetworkInterface",
                                    interfaces: [Ci.nsINetworkInterface]}),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface]),

  // If this RILNetworkInterface type is enabled or not.
  enabled: null,

  apnSetting: null,

  dataCall: null,

  /**
   * nsINetworkInterface Implementation
   */

  info: null,

  get httpProxyHost() {
    return this.apnSetting.proxy || "";
  },

  get httpProxyPort() {
    return this.apnSetting.port || "";
  },

  get mtu() {
    // Value provided by network has higher priority than apn settings.
    return this.dataCall.linkInfo.mtu || this.apnSetting.mtu || -1;
  },

  // Helpers

  debug: function(aMsg) {
    dump("-*- RILNetworkInterface[" + this.dataCallHandler.clientId + ":" +
         this.info.type + "]: " + aMsg + "\n");
  },

  get connected() {
    return this.info.state == NETWORK_STATE_CONNECTED;
  },

  notifyRILNetworkInterface: function() {
    if (DEBUG) {
      this.debug("notifyRILNetworkInterface type: " + this.info.type +
                 ", state: " + this.info.state);
    }

    gNetworkManager.updateNetworkInterface(this);
  },

  connect: function() {
    this.enabled = true;

    this.dataCall.connect(this);
  },

  disconnect: function() {
    if (!this.enabled) {
      return;
    }
    this.enabled = false;

    this.dataCall.disconnect(this);
  },

  shutdown: function() {
    this.dataCall.shutdown();
    this.dataCall = null;
  }
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DataCallManager]);