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
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
import static android.Manifest.permission.DUMP;
import static android.Manifest.permission.SHUTDOWN;
import static android.net.NetworkStats.SET_DEFAULT;
import static android.net.NetworkStats.TAG_ALL;
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static android.net.TrafficStats.UID_TETHERING;
import static android.net.RouteInfo.RTN_THROW;
import static android.net.RouteInfo.RTN_UNICAST;
import static android.net.RouteInfo.RTN_UNREACHABLE;
import static com.android.server.NetworkManagementService.NetdResponseCode.ClatdStatusResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsListResult;
import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.INetworkManagementEventObserver;
import android.net.InterfaceConfiguration;
import android.net.IpPrefix;
import android.net.LinkAddress;
import android.net.Network;
import android.net.NetworkStats;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.net.UidRange;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.os.BatteryStats;
import android.os.Binder;
import android.os.Handler;
import android.os.INetworkActivityListener;
import android.os.INetworkManagementService;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.telephony.DataConnectionRealTimeInfo;
import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Slog;
import android.util.SparseBooleanArray;
import com.android.internal.app.IBatteryStats;
import com.android.internal.net.NetworkStatsFactory;
import com.android.internal.util.Preconditions;
import com.android.server.NativeDaemonConnector.Command;
import com.android.server.NativeDaemonConnector.SensitiveArg;
import com.android.server.net.LockdownVpnTracker;
import com.google.android.collect.Maps;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.concurrent.CountDownLatch;
/**
* @hide
*/
public class NetworkManagementService extends INetworkManagementService.Stub
implements Watchdog.Monitor {
private static final String TAG = "NetworkManagementService";
private static final boolean DBG = false;
private static final String NETD_TAG = "NetdConnector";
private static final String NETD_SOCKET_NAME = "netd";
private static final int MAX_UID_RANGES_PER_COMMAND = 10;
/**
* Name representing {@link #setGlobalAlert(long)} limit when delivered to
* {@link INetworkManagementEventObserver#limitReached(String, String)}.
*/
public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
class NetdResponseCode {
/* Keep in sync with system/netd/server/ResponseCode.h */
public static final int InterfaceListResult = 110;
public static final int TetherInterfaceListResult = 111;
public static final int TetherDnsFwdTgtListResult = 112;
public static final int TtyListResult = 113;
public static final int TetheringStatsListResult = 114;
public static final int TetherStatusResult = 210;
public static final int IpFwdStatusResult = 211;
public static final int InterfaceGetCfgResult = 213;
public static final int SoftapStatusResult = 214;
public static final int InterfaceRxCounterResult = 216;
public static final int InterfaceTxCounterResult = 217;
public static final int QuotaCounterResult = 220;
public static final int TetheringStatsResult = 221;
public static final int DnsProxyQueryResult = 222;
public static final int ClatdStatusResult = 223;
public static final int InterfaceChange = 600;
public static final int BandwidthControl = 601;
public static final int InterfaceClassActivity = 613;
public static final int InterfaceAddressChange = 614;
public static final int InterfaceDnsServerInfo = 615;
public static final int RouteChange = 616;
}
static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
/**
* Binder context for this service
*/
private final Context mContext;
/**
* connector object for communicating with netd
*/
private final NativeDaemonConnector mConnector;
private final Handler mFgHandler;
private final Handler mDaemonHandler;
private final PhoneStateListener mPhoneStateListener;
private IBatteryStats mBatteryStats;
private final Thread mThread;
private CountDownLatch mConnectedSignal = new CountDownLatch(1);
private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
new RemoteCallbackList<INetworkManagementEventObserver>();
private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
private Object mQuotaLock = new Object();
/** Set of interfaces with active quotas. */
private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
/** Set of interfaces with active alerts. */
private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
/** Set of UIDs with active reject rules. */
private SparseBooleanArray mUidRejectOnQuota = new SparseBooleanArray();
private Object mIdleTimerLock = new Object();
/** Set of interfaces with active idle timers. */
private static class IdleTimerParams {
public final int timeout;
public final int type;
public int networkCount;
IdleTimerParams(int timeout, int type) {
this.timeout = timeout;
this.type = type;
this.networkCount = 1;
}
}
private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
private volatile boolean mBandwidthControlEnabled;
private volatile boolean mFirewallEnabled;
private boolean mMobileActivityFromRadio = false;
private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
new RemoteCallbackList<INetworkActivityListener>();
private boolean mNetworkActive;
/**
* Constructs a new NetworkManagementService instance
*
* @param context Binder context for this service
*/
private NetworkManagementService(Context context, String socket) {
mContext = context;
// make sure this is on the same looper as our NativeDaemonConnector for sync purposes
mFgHandler = new Handler(FgThread.get().getLooper());
if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
mConnector = null;
mThread = null;
mDaemonHandler = null;
mPhoneStateListener = null;
return;
}
// Don't need this wake lock, since we now have a time stamp for when
// the network actually went inactive. (It might be nice to still do this,
// but I don't want to do it through the power manager because that pollutes the
// battery stats history with pointless noise.)
//PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
mConnector = new NativeDaemonConnector(
new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
FgThread.get().getLooper());
mThread = new Thread(mConnector, NETD_TAG);
mDaemonHandler = new Handler(FgThread.get().getLooper());
mPhoneStateListener = new PhoneStateListener(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
mDaemonHandler.getLooper()) {
@Override
public void onDataConnectionRealTimeInfoChanged(
DataConnectionRealTimeInfo dcRtInfo) {
if (DBG) Slog.d(TAG, "onDataConnectionRealTimeInfoChanged: " + dcRtInfo);
notifyInterfaceClassActivity(ConnectivityManager.TYPE_MOBILE,
dcRtInfo.getDcPowerState(), dcRtInfo.getTime(), true);
}
};
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null) {
tm.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_DATA_CONNECTION_REAL_TIME_INFO);
}
// Add ourself to the Watchdog monitors.
Watchdog.getInstance().addMonitor(this);
}
static NetworkManagementService create(Context context,
String socket) throws InterruptedException {
final NetworkManagementService service = new NetworkManagementService(context, socket);
final CountDownLatch connectedSignal = service.mConnectedSignal;
if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
service.mThread.start();
if (DBG) Slog.d(TAG, "Awaiting socket connection");
connectedSignal.await();
if (DBG) Slog.d(TAG, "Connected");
return service;
}
public static NetworkManagementService create(Context context) throws InterruptedException {
return create(context, NETD_SOCKET_NAME);
}
public void systemReady() {
prepareNativeDaemon();
if (DBG) Slog.d(TAG, "Prepared");
}
private IBatteryStats getBatteryStats() {
synchronized (this) {
if (mBatteryStats != null) {
return mBatteryStats;
}
mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
BatteryStats.SERVICE_NAME));
return mBatteryStats;
}
}
@Override
public void registerObserver(INetworkManagementEventObserver observer) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
mObservers.register(observer);
}
@Override
public void unregisterObserver(INetworkManagementEventObserver observer) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
mObservers.unregister(observer);
}
/**
* Notify our observers of an interface status change
*/
private void notifyInterfaceStatusChanged(String iface, boolean up) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).interfaceStatusChanged(iface, up);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of an interface link state change
* (typically, an Ethernet cable has been plugged-in or unplugged).
*/
private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).interfaceLinkStateChanged(iface, up);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of an interface addition.
*/
private void notifyInterfaceAdded(String iface) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).interfaceAdded(iface);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of an interface removal.
*/
private void notifyInterfaceRemoved(String iface) {
// netd already clears out quota and alerts for removed ifaces; update
// our sanity-checking state.
mActiveAlerts.remove(iface);
mActiveQuotas.remove(iface);
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).interfaceRemoved(iface);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of a limit reached.
*/
private void notifyLimitReached(String limitName, String iface) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).limitReached(limitName, iface);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of a change in the data activity state of the interface
*/
private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
boolean fromRadio) {
final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
if (isMobile) {
if (!fromRadio) {
if (mMobileActivityFromRadio) {
// If this call is not coming from a report from the radio itself, but we
// have previously received reports from the radio, then we will take the
// power state to just be whatever the radio last reported.
powerState = mLastPowerStateFromRadio;
}
} else {
mMobileActivityFromRadio = true;
}
if (mLastPowerStateFromRadio != powerState) {
mLastPowerStateFromRadio = powerState;
try {
getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos);
} catch (RemoteException e) {
}
}
}
boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
|| powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
// Report the change in data activity. We don't do this if this is a change
// on the mobile network, that is not coming from the radio itself, and we
// have previously seen change reports from the radio. In that case only
// the radio is the authority for the current state.
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).interfaceClassDataActivityChanged(
Integer.toString(type), isActive, tsNanos);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
boolean report = false;
synchronized (mIdleTimerLock) {
if (mActiveIdleTimers.isEmpty()) {
// If there are no idle timers, we are not monitoring activity, so we
// are always considered active.
isActive = true;
}
if (mNetworkActive != isActive) {
mNetworkActive = isActive;
report = isActive;
}
}
if (report) {
reportNetworkActive();
}
}
/**
* Prepare native daemon once connected, enabling modules and pushing any
* existing in-memory rules.
*/
private void prepareNativeDaemon() {
mBandwidthControlEnabled = false;
// only enable bandwidth control when support exists
final boolean hasKernelSupport = new File("/proc/net/xt_qtaguid/ctrl").exists();
if (hasKernelSupport) {
Slog.d(TAG, "enabling bandwidth control");
try {
mConnector.execute("bandwidth", "enable");
mBandwidthControlEnabled = true;
} catch (NativeDaemonConnectorException e) {
Log.wtf(TAG, "problem enabling bandwidth controls", e);
}
} else {
Slog.d(TAG, "not enabling bandwidth control");
}
SystemProperties.set(PROP_QTAGUID_ENABLED, mBandwidthControlEnabled ? "1" : "0");
if (mBandwidthControlEnabled) {
try {
getBatteryStats().noteNetworkStatsEnabled();
} catch (RemoteException e) {
}
}
// push any existing quota or UID rules
synchronized (mQuotaLock) {
int size = mActiveQuotas.size();
if (size > 0) {
Slog.d(TAG, "pushing " + size + " active quota rules");
final HashMap<String, Long> activeQuotas = mActiveQuotas;
mActiveQuotas = Maps.newHashMap();
for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
setInterfaceQuota(entry.getKey(), entry.getValue());
}
}
size = mActiveAlerts.size();
if (size > 0) {
Slog.d(TAG, "pushing " + size + " active alert rules");
final HashMap<String, Long> activeAlerts = mActiveAlerts;
mActiveAlerts = Maps.newHashMap();
for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
setInterfaceAlert(entry.getKey(), entry.getValue());
}
}
size = mUidRejectOnQuota.size();
if (size > 0) {
Slog.d(TAG, "pushing " + size + " active uid rules");
final SparseBooleanArray uidRejectOnQuota = mUidRejectOnQuota;
mUidRejectOnQuota = new SparseBooleanArray();
for (int i = 0; i < uidRejectOnQuota.size(); i++) {
setUidNetworkRules(uidRejectOnQuota.keyAt(i), uidRejectOnQuota.valueAt(i));
}
}
}
// TODO: Push any existing firewall state
setFirewallEnabled(mFirewallEnabled || LockdownVpnTracker.isEnabled());
}
/**
* Notify our observers of a new or updated interface address.
*/
private void notifyAddressUpdated(String iface, LinkAddress address) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).addressUpdated(iface, address);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of a deleted interface address.
*/
private void notifyAddressRemoved(String iface, LinkAddress address) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).addressRemoved(iface, address);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of DNS server information received.
*/
private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mObservers.getBroadcastItem(i).interfaceDnsServerInfo(iface, lifetime,
addresses);
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
/**
* Notify our observers of a route change.
*/
private void notifyRouteChange(String action, RouteInfo route) {
final int length = mObservers.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
if (action.equals("updated")) {
mObservers.getBroadcastItem(i).routeUpdated(route);
} else {
mObservers.getBroadcastItem(i).routeRemoved(route);
}
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mObservers.finishBroadcast();
}
}
//
// Netd Callback handling
//
private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
@Override
public void onDaemonConnected() {
// event is dispatched from internal NDC thread, so we prepare the
// daemon back on main thread.
if (mConnectedSignal != null) {
mConnectedSignal.countDown();
mConnectedSignal = null;
} else {
mFgHandler.post(new Runnable() {
@Override
public void run() {
prepareNativeDaemon();
}
});
}
}
@Override
public boolean onCheckHoldWakeLock(int code) {
return code == NetdResponseCode.InterfaceClassActivity;
}
@Override
public boolean onEvent(int code, String raw, String[] cooked) {
String errorMessage = String.format("Invalid event from daemon (%s)", raw);
switch (code) {
case NetdResponseCode.InterfaceChange:
/*
* a network interface change occured
* Format: "NNN Iface added <name>"
* "NNN Iface removed <name>"
* "NNN Iface changed <name> <up/down>"
* "NNN Iface linkstatus <name> <up/down>"
*/
if (cooked.length < 4 || !cooked[1].equals("Iface")) {
throw new IllegalStateException(errorMessage);
}
if (cooked[2].equals("added")) {
notifyInterfaceAdded(cooked[3]);
return true;
} else if (cooked[2].equals("removed")) {
notifyInterfaceRemoved(cooked[3]);
return true;
} else if (cooked[2].equals("changed") && cooked.length == 5) {
notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
return true;
} else if (cooked[2].equals("linkstate") && cooked.length == 5) {
notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
return true;
}
throw new IllegalStateException(errorMessage);
// break;
case NetdResponseCode.BandwidthControl:
/*
* Bandwidth control needs some attention
* Format: "NNN limit alert <alertName> <ifaceName>"
*/
if (cooked.length < 5 || !cooked[1].equals("limit")) {
throw new IllegalStateException(errorMessage);
}
if (cooked[2].equals("alert")) {
notifyLimitReached(cooked[3], cooked[4]);
return true;
}
throw new IllegalStateException(errorMessage);
// break;
case NetdResponseCode.InterfaceClassActivity:
/*
* An network interface class state changed (active/idle)
* Format: "NNN IfaceClass <active/idle> <label>"
*/
if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
throw new IllegalStateException(errorMessage);
}
long timestampNanos = 0;
if (cooked.length == 5) {
try {
timestampNanos = Long.parseLong(cooked[4]);
} catch(NumberFormatException ne) {}
} else {
timestampNanos = SystemClock.elapsedRealtimeNanos();
}
boolean isActive = cooked[2].equals("active");
notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
: DataConnectionRealTimeInfo.DC_POWER_STATE_LOW, timestampNanos, false);
return true;
// break;
case NetdResponseCode.InterfaceAddressChange:
/*
* A network address change occurred
* Format: "NNN Address updated <addr> <iface> <flags> <scope>"
* "NNN Address removed <addr> <iface> <flags> <scope>"
*/
if (cooked.length < 7 || !cooked[1].equals("Address")) {
throw new IllegalStateException(errorMessage);
}
String iface = cooked[4];
LinkAddress address;
try {
int flags = Integer.parseInt(cooked[5]);
int scope = Integer.parseInt(cooked[6]);
address = new LinkAddress(cooked[3], flags, scope);
} catch(NumberFormatException e) { // Non-numeric lifetime or scope.
throw new IllegalStateException(errorMessage, e);
} catch(IllegalArgumentException e) { // Malformed/invalid IP address.
throw new IllegalStateException(errorMessage, e);
}
if (cooked[2].equals("updated")) {
notifyAddressUpdated(iface, address);
} else {
notifyAddressRemoved(iface, address);
}
return true;
// break;
case NetdResponseCode.InterfaceDnsServerInfo:
/*
* Information about available DNS servers has been received.
* Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
*/
long lifetime; // Actually a 32-bit unsigned integer.
if (cooked.length == 6 &&
cooked[1].equals("DnsInfo") &&
cooked[2].equals("servers")) {
try {
lifetime = Long.parseLong(cooked[4]);
} catch (NumberFormatException e) {
throw new IllegalStateException(errorMessage);
}
String[] servers = cooked[5].split(",");
notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
}
return true;
// break;
case NetdResponseCode.RouteChange:
/*
* A route has been updated or removed.
* Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
*/
if (!cooked[1].equals("Route") || cooked.length < 6) {
throw new IllegalStateException(errorMessage);
}
String via = null;
String dev = null;
boolean valid = true;
for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
if (cooked[i].equals("dev")) {
if (dev == null) {
dev = cooked[i+1];
} else {
valid = false; // Duplicate interface.
}
} else if (cooked[i].equals("via")) {
if (via == null) {
via = cooked[i+1];
} else {
valid = false; // Duplicate gateway.
}
} else {
valid = false; // Unknown syntax.
}
}
if (valid) {
try {
// InetAddress.parseNumericAddress(null) inexplicably returns ::1.
InetAddress gateway = null;
if (via != null) gateway = InetAddress.parseNumericAddress(via);
RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
notifyRouteChange(cooked[2], route);
return true;
} catch (IllegalArgumentException e) {}
}
throw new IllegalStateException(errorMessage);
// break;
default: break;
}
return false;
}
}
//
// INetworkManagementService members
//
@Override
public String[] listInterfaces() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return NativeDaemonEvent.filterMessageList(
mConnector.executeForList("interface", "list"), InterfaceListResult);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public InterfaceConfiguration getInterfaceConfig(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final NativeDaemonEvent event;
try {
event = mConnector.execute("interface", "getcfg", iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
event.checkCode(InterfaceGetCfgResult);
// Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3
final StringTokenizer st = new StringTokenizer(event.getMessage());
InterfaceConfiguration cfg;
try {
cfg = new InterfaceConfiguration();
cfg.setHardwareAddress(st.nextToken(" "));
InetAddress addr = null;
int prefixLength = 0;
try {
addr = NetworkUtils.numericToInetAddress(st.nextToken());
} catch (IllegalArgumentException iae) {
Slog.e(TAG, "Failed to parse ipaddr", iae);
}
try {
prefixLength = Integer.parseInt(st.nextToken());
} catch (NumberFormatException nfe) {
Slog.e(TAG, "Failed to parse prefixLength", nfe);
}
cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
while (st.hasMoreTokens()) {
cfg.setFlag(st.nextToken());
}
} catch (NoSuchElementException nsee) {
throw new IllegalStateException("Invalid response from daemon: " + event);
}
return cfg;
}
@Override
public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
LinkAddress linkAddr = cfg.getLinkAddress();
if (linkAddr == null || linkAddr.getAddress() == null) {
throw new IllegalStateException("Null LinkAddress given");
}
final Command cmd = new Command("interface", "setcfg", iface,
linkAddr.getAddress().getHostAddress(),
linkAddr.getPrefixLength());
for (String flag : cfg.getFlags()) {
cmd.appendArg(flag);
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setInterfaceDown(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
ifcg.setInterfaceDown();
setInterfaceConfig(iface, ifcg);
}
@Override
public void setInterfaceUp(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
ifcg.setInterfaceUp();
setInterfaceConfig(iface, ifcg);
}
@Override
public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute(
"interface", "ipv6privacyextensions", iface, enable ? "enable" : "disable");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
/* TODO: This is right now a IPv4 only function. Works for wifi which loses its
IPv6 addresses on interface down, but we need to do full clean up here */
@Override
public void clearInterfaceAddresses(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("interface", "clearaddrs", iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void enableIpv6(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("interface", "ipv6", iface, "enable");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void disableIpv6(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("interface", "ipv6", iface, "disable");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setInterfaceIpv6NdOffload(String iface, boolean enable) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute(
"interface", "ipv6ndoffload", iface, (enable ? "enable" : "disable"));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void addRoute(int netId, RouteInfo route) {
modifyRoute("add", "" + netId, route);
}
@Override
public void removeRoute(int netId, RouteInfo route) {
modifyRoute("remove", "" + netId, route);
}
private void modifyRoute(String action, String netId, RouteInfo route) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final Command cmd = new Command("network", "route", action, netId);
// create triplet: interface dest-ip-addr/prefixlength gateway-ip-addr
cmd.appendArg(route.getInterface());
cmd.appendArg(route.getDestination().toString());
switch (route.getType()) {
case RouteInfo.RTN_UNICAST:
if (route.hasGateway()) {
cmd.appendArg(route.getGateway().getHostAddress());
}
break;
case RouteInfo.RTN_UNREACHABLE:
cmd.appendArg("unreachable");
break;
case RouteInfo.RTN_THROW:
cmd.appendArg("throw");
break;
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
private ArrayList<String> readRouteList(String filename) {
FileInputStream fstream = null;
ArrayList<String> list = new ArrayList<String>();
try {
fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String s;
// throw away the title line
while (((s = br.readLine()) != null) && (s.length() != 0)) {
list.add(s);
}
} catch (IOException ex) {
// return current list, possibly empty
} finally {
if (fstream != null) {
try {
fstream.close();
} catch (IOException ex) {}
}
}
return list;
}
@Override
public RouteInfo[] getRoutes(String interfaceName) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
// v4 routes listed as:
// iface dest-addr gateway-addr flags refcnt use metric netmask mtu window IRTT
for (String s : readRouteList("/proc/net/route")) {
String[] fields = s.split("\t");
if (fields.length > 7) {
String iface = fields[0];
if (interfaceName.equals(iface)) {
String dest = fields[1];
String gate = fields[2];
String flags = fields[3]; // future use?
String mask = fields[7];
try {
// address stored as a hex string, ex: 0014A8C0
InetAddress destAddr =
NetworkUtils.intToInetAddress((int)Long.parseLong(dest, 16));
int prefixLength =
NetworkUtils.netmaskIntToPrefixLength(
(int)Long.parseLong(mask, 16));
LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
// address stored as a hex string, ex 0014A8C0
InetAddress gatewayAddr =
NetworkUtils.intToInetAddress((int)Long.parseLong(gate, 16));
RouteInfo route = new RouteInfo(linkAddress, gatewayAddr);
routes.add(route);
} catch (Exception e) {
Log.e(TAG, "Error parsing route " + s + " : " + e);
continue;
}
}
}
}
// v6 routes listed as:
// dest-addr prefixlength ?? ?? gateway-addr ?? ?? ?? ?? iface
for (String s : readRouteList("/proc/net/ipv6_route")) {
String[]fields = s.split("\\s+");
if (fields.length > 9) {
String iface = fields[9].trim();
if (interfaceName.equals(iface)) {
String dest = fields[0];
String prefix = fields[1];
String gate = fields[4];
try {
// prefix length stored as a hex string, ex 40
int prefixLength = Integer.parseInt(prefix, 16);
// address stored as a 32 char hex string
// ex fe800000000000000000000000000000
InetAddress destAddr = NetworkUtils.hexToInet6Address(dest);
LinkAddress linkAddress = new LinkAddress(destAddr, prefixLength);
InetAddress gateAddr = NetworkUtils.hexToInet6Address(gate);
RouteInfo route = new RouteInfo(linkAddress, gateAddr);
routes.add(route);
} catch (Exception e) {
Log.e(TAG, "Error parsing route " + s + " : " + e);
continue;
}
}
}
}
return routes.toArray(new RouteInfo[routes.size()]);
}
@Override
public void setMtu(String iface, int mtu) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final NativeDaemonEvent event;
try {
event = mConnector.execute("interface", "setmtu", iface, mtu);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void shutdown() {
// TODO: remove from aidl if nobody calls externally
mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
Slog.d(TAG, "Shutting down");
}
@Override
public boolean getIpForwardingEnabled() throws IllegalStateException{
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final NativeDaemonEvent event;
try {
event = mConnector.execute("ipfwd", "status");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
// 211 Forwarding enabled
event.checkCode(IpFwdStatusResult);
return event.getMessage().endsWith("enabled");
}
@Override
public void setIpForwardingEnabled(boolean enable) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("ipfwd", enable ? "enable" : "disable");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void startTethering(String[] dhcpRange) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// cmd is "tether start first_start first_stop second_start second_stop ..."
// an odd number of addrs will fail
final Command cmd = new Command("tether", "start");
for (String d : dhcpRange) {
cmd.appendArg(d);
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void stopTethering() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("tether", "stop");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public boolean isTetheringStarted() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final NativeDaemonEvent event;
try {
event = mConnector.execute("tether", "status");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
// 210 Tethering services started
event.checkCode(TetherStatusResult);
return event.getMessage().endsWith("started");
}
@Override
public void tetherInterface(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("tether", "interface", "add", iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
List<RouteInfo> routes = new ArrayList<RouteInfo>();
// The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
// suitable to use as a route destination.
routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
addInterfaceToLocalNetwork(iface, routes);
}
@Override
public void untetherInterface(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("tether", "interface", "remove", iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
removeInterfaceFromLocalNetwork(iface);
}
@Override
public String[] listTetheredInterfaces() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return NativeDaemonEvent.filterMessageList(
mConnector.executeForList("tether", "interface", "list"),
TetherInterfaceListResult);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setDnsForwarders(Network network, String[] dns) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
final Command cmd = new Command("tether", "dns", "set", netId);
for (String s : dns) {
cmd.appendArg(NetworkUtils.numericToInetAddress(s).getHostAddress());
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public String[] getDnsForwarders() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return NativeDaemonEvent.filterMessageList(
mConnector.executeForList("tether", "dns", "list"), TetherDnsFwdTgtListResult);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
ArrayList<InterfaceAddress> filtered = new ArrayList<InterfaceAddress>(addresses.size());
for (InterfaceAddress ia : addresses) {
if (!ia.getAddress().isLinkLocalAddress())
filtered.add(ia);
}
return filtered;
}
private void modifyNat(String action, String internalInterface, String externalInterface)
throws SocketException {
final Command cmd = new Command("nat", action, internalInterface, externalInterface);
final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(
internalInterface);
if (internalNetworkInterface == null) {
cmd.appendArg("0");
} else {
// Don't touch link-local routes, as link-local addresses aren't routable,
// kernel creates link-local routes on all interfaces automatically
List<InterfaceAddress> interfaceAddresses = excludeLinkLocal(
internalNetworkInterface.getInterfaceAddresses());
cmd.appendArg(interfaceAddresses.size());
for (InterfaceAddress ia : interfaceAddresses) {
InetAddress addr = NetworkUtils.getNetworkPart(
ia.getAddress(), ia.getNetworkPrefixLength());
cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
}
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void enableNat(String internalInterface, String externalInterface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
modifyNat("enable", internalInterface, externalInterface);
} catch (SocketException e) {
throw new IllegalStateException(e);
}
}
@Override
public void disableNat(String internalInterface, String externalInterface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
modifyNat("disable", internalInterface, externalInterface);
} catch (SocketException e) {
throw new IllegalStateException(e);
}
}
@Override
public String[] listTtys() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return NativeDaemonEvent.filterMessageList(
mConnector.executeForList("list_ttys"), TtyListResult);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void attachPppd(
String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("pppd", "attach", tty,
NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void detachPppd(String tty) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("pppd", "detach", tty);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void startAccessPoint(
WifiConfiguration wifiConfig, String wlanIface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
wifiFirmwareReload(wlanIface, "AP");
if (wifiConfig == null) {
mConnector.execute("softap", "set", wlanIface);
} else {
mConnector.execute("softap", "set", wlanIface, wifiConfig.SSID,
"broadcast", "6", getSecurityType(wifiConfig),
new SensitiveArg(wifiConfig.preSharedKey));
}
mConnector.execute("softap", "startap");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
private static String getSecurityType(WifiConfiguration wifiConfig) {
switch (wifiConfig.getAuthType()) {
case KeyMgmt.WPA_PSK:
return "wpa-psk";
case KeyMgmt.WPA2_PSK:
return "wpa2-psk";
default:
return "open";
}
}
/* @param mode can be "AP", "STA" or "P2P" */
@Override
public void wifiFirmwareReload(String wlanIface, String mode) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("softap", "fwreload", wlanIface, mode);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void stopAccessPoint(String wlanIface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("softap", "stopap");
wifiFirmwareReload(wlanIface, "STA");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setAccessPoint(WifiConfiguration wifiConfig, String wlanIface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
if (wifiConfig == null) {
mConnector.execute("softap", "set", wlanIface);
} else {
mConnector.execute("softap", "set", wlanIface, wifiConfig.SSID,
"broadcast", "6", getSecurityType(wifiConfig),
new SensitiveArg(wifiConfig.preSharedKey));
}
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void addIdleTimer(String iface, int timeout, final int type) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
if (DBG) Slog.d(TAG, "Adding idletimer");
synchronized (mIdleTimerLock) {
IdleTimerParams params = mActiveIdleTimers.get(iface);
if (params != null) {
// the interface already has idletimer, update network count
params.networkCount++;
return;
}
try {
mConnector.execute("idletimer", "add", iface, Integer.toString(timeout),
Integer.toString(type));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
// Networks start up.
if (ConnectivityManager.isNetworkTypeMobile(type)) {
mNetworkActive = false;
}
mDaemonHandler.post(new Runnable() {
@Override public void run() {
notifyInterfaceClassActivity(type,
DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
SystemClock.elapsedRealtimeNanos(), false);
}
});
}
}
@Override
public void removeIdleTimer(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
if (DBG) Slog.d(TAG, "Removing idletimer");
synchronized (mIdleTimerLock) {
final IdleTimerParams params = mActiveIdleTimers.get(iface);
if (params == null || --(params.networkCount) > 0) {
return;
}
try {
mConnector.execute("idletimer", "remove", iface,
Integer.toString(params.timeout), Integer.toString(params.type));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
mActiveIdleTimers.remove(iface);
mDaemonHandler.post(new Runnable() {
@Override public void run() {
notifyInterfaceClassActivity(params.type,
DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
SystemClock.elapsedRealtimeNanos(), false);
}
});
}
}
@Override
public NetworkStats getNetworkStatsSummaryDev() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return mStatsFactory.readNetworkStatsSummaryDev();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public NetworkStats getNetworkStatsSummaryXt() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return mStatsFactory.readNetworkStatsSummaryXt();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public NetworkStats getNetworkStatsDetail() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public void setInterfaceQuota(String iface, long quotaBytes) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// silently discard when control disabled
// TODO: eventually migrate to be always enabled
if (!mBandwidthControlEnabled) return;
synchronized (mQuotaLock) {
if (mActiveQuotas.containsKey(iface)) {
throw new IllegalStateException("iface " + iface + " already has quota");
}
try {
// TODO: support quota shared across interfaces
mConnector.execute("bandwidth", "setiquota", iface, quotaBytes);
mActiveQuotas.put(iface, quotaBytes);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
}
@Override
public void removeInterfaceQuota(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// silently discard when control disabled
// TODO: eventually migrate to be always enabled
if (!mBandwidthControlEnabled) return;
synchronized (mQuotaLock) {
if (!mActiveQuotas.containsKey(iface)) {
// TODO: eventually consider throwing
return;
}
mActiveQuotas.remove(iface);
mActiveAlerts.remove(iface);
try {
// TODO: support quota shared across interfaces
mConnector.execute("bandwidth", "removeiquota", iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
}
@Override
public void setInterfaceAlert(String iface, long alertBytes) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// silently discard when control disabled
// TODO: eventually migrate to be always enabled
if (!mBandwidthControlEnabled) return;
// quick sanity check
if (!mActiveQuotas.containsKey(iface)) {
throw new IllegalStateException("setting alert requires existing quota on iface");
}
synchronized (mQuotaLock) {
if (mActiveAlerts.containsKey(iface)) {
throw new IllegalStateException("iface " + iface + " already has alert");
}
try {
// TODO: support alert shared across interfaces
mConnector.execute("bandwidth", "setinterfacealert", iface, alertBytes);
mActiveAlerts.put(iface, alertBytes);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
}
@Override
public void removeInterfaceAlert(String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// silently discard when control disabled
// TODO: eventually migrate to be always enabled
if (!mBandwidthControlEnabled) return;
synchronized (mQuotaLock) {
if (!mActiveAlerts.containsKey(iface)) {
// TODO: eventually consider throwing
return;
}
try {
// TODO: support alert shared across interfaces
mConnector.execute("bandwidth", "removeinterfacealert", iface);
mActiveAlerts.remove(iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
}
@Override
public void setGlobalAlert(long alertBytes) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// silently discard when control disabled
// TODO: eventually migrate to be always enabled
if (!mBandwidthControlEnabled) return;
try {
mConnector.execute("bandwidth", "setglobalalert", alertBytes);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
// silently discard when control disabled
// TODO: eventually migrate to be always enabled
if (!mBandwidthControlEnabled) return;
synchronized (mQuotaLock) {
final boolean oldRejectOnQuota = mUidRejectOnQuota.get(uid, false);
if (oldRejectOnQuota == rejectOnQuotaInterfaces) {
// TODO: eventually consider throwing
return;
}
try {
mConnector.execute("bandwidth",
rejectOnQuotaInterfaces ? "addnaughtyapps" : "removenaughtyapps", uid);
if (rejectOnQuotaInterfaces) {
mUidRejectOnQuota.put(uid, true);
} else {
mUidRejectOnQuota.delete(uid);
}
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
}
@Override
public boolean isBandwidthControlEnabled() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
return mBandwidthControlEnabled;
}
@Override
public NetworkStats getNetworkStatsUidDetail(int uid) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
return mStatsFactory.readNetworkStatsDetail(uid, null, TAG_ALL, null);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public NetworkStats getNetworkStatsTethering() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
try {
final NativeDaemonEvent[] events = mConnector.executeForList(
"bandwidth", "gettetherstats");
for (NativeDaemonEvent event : events) {
if (event.getCode() != TetheringStatsListResult) continue;
// 114 ifaceIn ifaceOut rx_bytes rx_packets tx_bytes tx_packets
final StringTokenizer tok = new StringTokenizer(event.getMessage());
try {
final String ifaceIn = tok.nextToken();
final String ifaceOut = tok.nextToken();
final NetworkStats.Entry entry = new NetworkStats.Entry();
entry.iface = ifaceOut;
entry.uid = UID_TETHERING;
entry.set = SET_DEFAULT;
entry.tag = TAG_NONE;
entry.rxBytes = Long.parseLong(tok.nextToken());
entry.rxPackets = Long.parseLong(tok.nextToken());
entry.txBytes = Long.parseLong(tok.nextToken());
entry.txPackets = Long.parseLong(tok.nextToken());
stats.combineValues(entry);
} catch (NoSuchElementException e) {
throw new IllegalStateException("problem parsing tethering stats: " + event);
} catch (NumberFormatException e) {
throw new IllegalStateException("problem parsing tethering stats: " + event);
}
}
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
return stats;
}
@Override
public void setDnsServersForNetwork(int netId, String[] servers, String domains) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Command cmd;
if (servers.length > 0) {
cmd = new Command("resolver", "setnetdns", netId,
(domains == null ? "" : domains));
for (String s : servers) {
InetAddress a = NetworkUtils.numericToInetAddress(s);
if (a.isAnyLocalAddress() == false) {
cmd.appendArg(a.getHostAddress());
}
}
} else {
cmd = new Command("resolver", "clearnetdns", netId);
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void addVpnUidRanges(int netId, UidRange[] ranges) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Object[] argv = new Object[3 + MAX_UID_RANGES_PER_COMMAND];
argv[0] = "users";
argv[1] = "add";
argv[2] = netId;
int argc = 3;
// Avoid overly long commands by limiting number of UID ranges per command.
for (int i = 0; i < ranges.length; i++) {
argv[argc++] = ranges[i].toString();
if (i == (ranges.length - 1) || argc == argv.length) {
try {
mConnector.execute("network", Arrays.copyOf(argv, argc));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
argc = 3;
}
}
}
@Override
public void removeVpnUidRanges(int netId, UidRange[] ranges) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Object[] argv = new Object[3 + MAX_UID_RANGES_PER_COMMAND];
argv[0] = "users";
argv[1] = "remove";
argv[2] = netId;
int argc = 3;
// Avoid overly long commands by limiting number of UID ranges per command.
for (int i = 0; i < ranges.length; i++) {
argv[argc++] = ranges[i].toString();
if (i == (ranges.length - 1) || argc == argv.length) {
try {
mConnector.execute("network", Arrays.copyOf(argv, argc));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
argc = 3;
}
}
}
@Override
public void flushNetworkDnsCache(int netId) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("resolver", "flushnet", netId);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setFirewallEnabled(boolean enabled) {
enforceSystemUid();
try {
mConnector.execute("firewall", enabled ? "enable" : "disable");
mFirewallEnabled = enabled;
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public boolean isFirewallEnabled() {
enforceSystemUid();
return mFirewallEnabled;
}
@Override
public void setFirewallInterfaceRule(String iface, boolean allow) {
enforceSystemUid();
Preconditions.checkState(mFirewallEnabled);
final String rule = allow ? "allow" : "deny";
try {
mConnector.execute("firewall", "set_interface_rule", iface, rule);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setFirewallEgressSourceRule(String addr, boolean allow) {
enforceSystemUid();
Preconditions.checkState(mFirewallEnabled);
final String rule = allow ? "allow" : "deny";
try {
mConnector.execute("firewall", "set_egress_source_rule", addr, rule);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setFirewallEgressDestRule(String addr, int port, boolean allow) {
enforceSystemUid();
Preconditions.checkState(mFirewallEnabled);
final String rule = allow ? "allow" : "deny";
try {
mConnector.execute("firewall", "set_egress_dest_rule", addr, port, rule);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setFirewallUidRule(int uid, boolean allow) {
enforceSystemUid();
Preconditions.checkState(mFirewallEnabled);
final String rule = allow ? "allow" : "deny";
try {
mConnector.execute("firewall", "set_uid_rule", uid, rule);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
private static void enforceSystemUid() {
final int uid = Binder.getCallingUid();
if (uid != Process.SYSTEM_UID) {
throw new SecurityException("Only available to AID_SYSTEM");
}
}
@Override
public void startClatd(String interfaceName) throws IllegalStateException {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("clatd", "start", interfaceName);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void stopClatd(String interfaceName) throws IllegalStateException {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("clatd", "stop", interfaceName);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public boolean isClatdStarted(String interfaceName) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final NativeDaemonEvent event;
try {
event = mConnector.execute("clatd", "status", interfaceName);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
event.checkCode(ClatdStatusResult);
return event.getMessage().endsWith("started");
}
@Override
public void registerNetworkActivityListener(INetworkActivityListener listener) {
mNetworkActivityListeners.register(listener);
}
@Override
public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
mNetworkActivityListeners.unregister(listener);
}
@Override
public boolean isNetworkActive() {
synchronized (mNetworkActivityListeners) {
return mNetworkActive || mActiveIdleTimers.isEmpty();
}
}
private void reportNetworkActive() {
final int length = mNetworkActivityListeners.beginBroadcast();
try {
for (int i = 0; i < length; i++) {
try {
mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
} catch (RemoteException e) {
} catch (RuntimeException e) {
}
}
} finally {
mNetworkActivityListeners.finishBroadcast();
}
}
/** {@inheritDoc} */
@Override
public void monitor() {
if (mConnector != null) {
mConnector.monitor();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
mContext.enforceCallingOrSelfPermission(DUMP, TAG);
pw.println("NetworkManagementService NativeDaemonConnector Log:");
mConnector.dump(fd, pw, args);
pw.println();
pw.print("Bandwidth control enabled: "); pw.println(mBandwidthControlEnabled);
pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
pw.print("mNetworkActive="); pw.println(mNetworkActive);
synchronized (mQuotaLock) {
pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
}
synchronized (mUidRejectOnQuota) {
pw.print("UID reject on quota ifaces: [");
final int size = mUidRejectOnQuota.size();
for (int i = 0; i < size; i++) {
pw.print(mUidRejectOnQuota.keyAt(i));
if (i < size - 1) pw.print(",");
}
pw.println("]");
}
synchronized (mIdleTimerLock) {
pw.println("Idle timers:");
for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
pw.print(" "); pw.print(ent.getKey()); pw.println(":");
IdleTimerParams params = ent.getValue();
pw.print(" timeout="); pw.print(params.timeout);
pw.print(" type="); pw.print(params.type);
pw.print(" networkCount="); pw.println(params.networkCount);
}
}
pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
}
@Override
public void createPhysicalNetwork(int netId) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "create", netId);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "create", netId, "vpn", hasDNS ? "1" : "0",
secure ? "1" : "0");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void removeNetwork(int netId) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "destroy", netId);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void addInterfaceToNetwork(String iface, int netId) {
modifyInterfaceInNetwork("add", "" + netId, iface);
}
@Override
public void removeInterfaceFromNetwork(String iface, int netId) {
modifyInterfaceInNetwork("remove", "" + netId, iface);
}
private void modifyInterfaceInNetwork(String action, String netId, String iface) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "interface", action, netId, iface);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
final Command cmd = new Command("network", "route", "legacy", uid, "add", netId);
// create triplet: interface dest-ip-addr/prefixlength gateway-ip-addr
final LinkAddress la = routeInfo.getDestinationLinkAddress();
cmd.appendArg(routeInfo.getInterface());
cmd.appendArg(la.getAddress().getHostAddress() + "/" + la.getPrefixLength());
if (routeInfo.hasGateway()) {
cmd.appendArg(routeInfo.getGateway().getHostAddress());
}
try {
mConnector.execute(cmd);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setDefaultNetId(int netId) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "default", "set", netId);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void clearDefaultNetId() {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "default", "clear");
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void setPermission(String permission, int[] uids) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Object[] argv = new Object[4 + MAX_UID_RANGES_PER_COMMAND];
argv[0] = "permission";
argv[1] = "user";
argv[2] = "set";
argv[3] = permission;
int argc = 4;
// Avoid overly long commands by limiting number of UIDs per command.
for (int i = 0; i < uids.length; ++i) {
argv[argc++] = uids[i];
if (i == uids.length - 1 || argc == argv.length) {
try {
mConnector.execute("network", Arrays.copyOf(argv, argc));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
argc = 4;
}
}
}
@Override
public void clearPermission(int[] uids) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Object[] argv = new Object[3 + MAX_UID_RANGES_PER_COMMAND];
argv[0] = "permission";
argv[1] = "user";
argv[2] = "clear";
int argc = 3;
// Avoid overly long commands by limiting number of UIDs per command.
for (int i = 0; i < uids.length; ++i) {
argv[argc++] = uids[i];
if (i == uids.length - 1 || argc == argv.length) {
try {
mConnector.execute("network", Arrays.copyOf(argv, argc));
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
argc = 3;
}
}
}
@Override
public void allowProtect(int uid) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "protect", "allow", uid);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void denyProtect(int uid) {
mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
try {
mConnector.execute("network", "protect", "deny", uid);
} catch (NativeDaemonConnectorException e) {
throw e.rethrowAsParcelableException();
}
}
@Override
public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
modifyInterfaceInNetwork("add", "local", iface);
for (RouteInfo route : routes) {
if (!route.isDefaultRoute()) {
modifyRoute("add", "local", route);
}
}
}
@Override
public void removeInterfaceFromLocalNetwork(String iface) {
modifyInterfaceInNetwork("remove", "local", iface);
}
}
|