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
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
|
/* Copyright 2012 Mozilla Foundation and Mozilla contributors
*
* 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.
*/
#include "NetworkUtils.h"
#include "mozilla/Sprintf.h"
#include "SystemProperty.h"
#include <android/log.h>
#include <limits>
#include "mozilla/dom/network/NetUtils.h"
#include "mozilla/fallible.h"
#include "base/task.h"
#include <errno.h>
#include <string.h>
#include <sys/types.h> // struct addrinfo
#include <sys/socket.h> // getaddrinfo(), freeaddrinfo()
#include <netdb.h>
#include <arpa/inet.h> // inet_ntop()
#define _DEBUG 0
#define WARN(args...) __android_log_print(ANDROID_LOG_WARN, "NetworkUtils", ## args)
#define ERROR(args...) __android_log_print(ANDROID_LOG_ERROR, "NetworkUtils", ## args)
#if _DEBUG
#define NU_DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, "NetworkUtils" , ## args)
#else
#define NU_DBG(args...)
#endif
using namespace mozilla::dom;
using namespace mozilla::ipc;
using mozilla::system::Property;
static const char* PERSIST_SYS_USB_CONFIG_PROPERTY = "persist.sys.usb.config";
static const char* SYS_USB_CONFIG_PROPERTY = "sys.usb.config";
static const char* SYS_USB_STATE_PROPERTY = "sys.usb.state";
static const char* USB_FUNCTION_RNDIS = "rndis";
static const char* USB_FUNCTION_ADB = "adb";
// Use this command to continue the function chain.
static const char* DUMMY_COMMAND = "tether status";
// IPV6 Tethering is not supported in AOSP, use the property to
// identify vendor specific support in IPV6. We can remove this flag
// once upstream Android support IPV6 in tethering.
static const char* IPV6_TETHERING = "ro.tethering.ipv6";
// Retry 20 times (2 seconds) for usb state transition.
static const uint32_t USB_FUNCTION_RETRY_TIMES = 20;
// Check "sys.usb.state" every 100ms.
static const uint32_t USB_FUNCTION_RETRY_INTERVAL = 100;
// 1xx - Requested action is proceeding
static const uint32_t NETD_COMMAND_PROCEEDING = 100;
// 2xx - Requested action has been successfully completed
static const uint32_t NETD_COMMAND_OKAY = 200;
// 4xx - The command is accepted but the requested action didn't
// take place.
static const uint32_t NETD_COMMAND_FAIL = 400;
// 5xx - The command syntax or parameters error
static const uint32_t NETD_COMMAND_ERROR = 500;
// 6xx - Unsolicited broadcasts
static const uint32_t NETD_COMMAND_UNSOLICITED = 600;
// Broadcast messages
static const uint32_t NETD_COMMAND_INTERFACE_CHANGE = 600;
static const uint32_t NETD_COMMAND_BANDWIDTH_CONTROLLER = 601;
static const char* INTERFACE_DELIMIT = ",";
static const char* USB_CONFIG_DELIMIT = ",";
static const char* NETD_MESSAGE_DELIMIT = " ";
static const uint32_t BUF_SIZE = 1024;
static const int32_t SUCCESS = 0;
static uint32_t SDK_VERSION;
static uint32_t SUPPORT_IPV6_TETHERING;
struct IFProperties {
char gateway[Property::VALUE_MAX_LENGTH];
char dns1[Property::VALUE_MAX_LENGTH];
char dns2[Property::VALUE_MAX_LENGTH];
};
struct CurrentCommand {
CommandChain* chain;
CommandCallback callback;
char command[MAX_COMMAND_SIZE];
};
typedef Tuple3<NetdCommand*, CommandChain*, CommandCallback> QueueData;
#define GET_CURRENT_NETD_COMMAND (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].a)
#define GET_CURRENT_CHAIN (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].b)
#define GET_CURRENT_CALLBACK (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].c)
#define GET_CURRENT_COMMAND (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].a->mData)
// A macro for native function call return value check.
// For native function call, non-zero return value means failure.
#define RETURN_IF_FAILED(rv) do { \
if (SUCCESS != rv) { \
return rv; \
} \
} while (0);
#define WARN_IF_FAILED(rv) do { \
if (SUCCESS != rv) { \
WARN("Error (%d) occurred in %s (%s:%d)", rv, __PRETTY_FUNCTION__, __FILE__, __LINE__); \
} \
} while (0);
static NetworkUtils* gNetworkUtils;
static nsTArray<QueueData> gCommandQueue;
static CurrentCommand gCurrentCommand;
static bool gPending = false;
static nsTArray<nsCString> gReason;
static NetworkParams *gWifiTetheringParms = 0;
static nsTArray<CommandChain*> gCommandChainQueue;
const CommandFunc NetworkUtils::sWifiEnableChain[] = {
NetworkUtils::clearWifiTetherParms,
NetworkUtils::wifiFirmwareReload,
NetworkUtils::startAccessPointDriver,
NetworkUtils::setAccessPoint,
NetworkUtils::startSoftAP,
NetworkUtils::setConfig,
NetworkUtils::tetherInterface,
NetworkUtils::addInterfaceToLocalNetwork,
NetworkUtils::addRouteToLocalNetwork,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::tetheringStatus,
NetworkUtils::startTethering,
NetworkUtils::setDnsForwarders,
NetworkUtils::enableNat,
NetworkUtils::wifiTetheringSuccess
};
const CommandFunc NetworkUtils::sWifiDisableChain[] = {
NetworkUtils::clearWifiTetherParms,
NetworkUtils::stopSoftAP,
NetworkUtils::stopAccessPointDriver,
NetworkUtils::wifiFirmwareReload,
NetworkUtils::untetherInterface,
NetworkUtils::removeInterfaceFromLocalNetwork,
NetworkUtils::preTetherInterfaceList,
NetworkUtils::postTetherInterfaceList,
NetworkUtils::disableNat,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::stopTethering,
NetworkUtils::wifiTetheringSuccess
};
const CommandFunc NetworkUtils::sWifiFailChain[] = {
NetworkUtils::clearWifiTetherParms,
NetworkUtils::stopSoftAP,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::stopTethering
};
const CommandFunc NetworkUtils::sWifiRetryChain[] = {
NetworkUtils::clearWifiTetherParms,
NetworkUtils::stopSoftAP,
NetworkUtils::stopTethering,
// sWifiEnableChain:
NetworkUtils::wifiFirmwareReload,
NetworkUtils::startAccessPointDriver,
NetworkUtils::setAccessPoint,
NetworkUtils::startSoftAP,
NetworkUtils::setConfig,
NetworkUtils::tetherInterface,
NetworkUtils::addInterfaceToLocalNetwork,
NetworkUtils::addRouteToLocalNetwork,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::tetheringStatus,
NetworkUtils::startTethering,
NetworkUtils::setDnsForwarders,
NetworkUtils::enableNat,
NetworkUtils::wifiTetheringSuccess
};
const CommandFunc NetworkUtils::sWifiOperationModeChain[] = {
NetworkUtils::wifiFirmwareReload,
NetworkUtils::wifiOperationModeSuccess
};
const CommandFunc NetworkUtils::sUSBEnableChain[] = {
NetworkUtils::setConfig,
NetworkUtils::enableNat,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::tetherInterface,
NetworkUtils::addInterfaceToLocalNetwork,
NetworkUtils::addRouteToLocalNetwork,
NetworkUtils::tetheringStatus,
NetworkUtils::startTethering,
NetworkUtils::setDnsForwarders,
NetworkUtils::addUpstreamInterface,
NetworkUtils::usbTetheringSuccess
};
const CommandFunc NetworkUtils::sUSBDisableChain[] = {
NetworkUtils::untetherInterface,
NetworkUtils::removeInterfaceFromLocalNetwork,
NetworkUtils::preTetherInterfaceList,
NetworkUtils::postTetherInterfaceList,
NetworkUtils::removeUpstreamInterface,
NetworkUtils::disableNat,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::stopTethering,
NetworkUtils::usbTetheringSuccess
};
const CommandFunc NetworkUtils::sUSBFailChain[] = {
NetworkUtils::stopSoftAP,
NetworkUtils::setIpForwardingEnabled,
NetworkUtils::stopTethering
};
const CommandFunc NetworkUtils::sUpdateUpStreamChain[] = {
NetworkUtils::cleanUpStream,
NetworkUtils::removeUpstreamInterface,
NetworkUtils::createUpStream,
NetworkUtils::addUpstreamInterface,
NetworkUtils::updateUpStreamSuccess
};
const CommandFunc NetworkUtils::sStartDhcpServerChain[] = {
NetworkUtils::setConfig,
NetworkUtils::startTethering,
NetworkUtils::setDhcpServerSuccess
};
const CommandFunc NetworkUtils::sStopDhcpServerChain[] = {
NetworkUtils::stopTethering,
NetworkUtils::setDhcpServerSuccess
};
const CommandFunc NetworkUtils::sNetworkInterfaceEnableAlarmChain[] = {
NetworkUtils::enableAlarm,
NetworkUtils::setQuota,
NetworkUtils::setAlarm,
NetworkUtils::networkInterfaceAlarmSuccess
};
const CommandFunc NetworkUtils::sNetworkInterfaceDisableAlarmChain[] = {
NetworkUtils::removeQuota,
NetworkUtils::disableAlarm,
NetworkUtils::networkInterfaceAlarmSuccess
};
const CommandFunc NetworkUtils::sNetworkInterfaceSetAlarmChain[] = {
NetworkUtils::setAlarm,
NetworkUtils::networkInterfaceAlarmSuccess
};
const CommandFunc NetworkUtils::sGetInterfacesChain[] = {
NetworkUtils::getInterfaceList,
NetworkUtils::getInterfacesSuccess
};
const CommandFunc NetworkUtils::sGetInterfaceConfigChain[] = {
NetworkUtils::getConfig,
NetworkUtils::getInterfaceConfigSuccess
};
const CommandFunc NetworkUtils::sSetInterfaceConfigChain[] = {
NetworkUtils::setConfig,
NetworkUtils::setInterfaceConfigSuccess
};
const CommandFunc NetworkUtils::sTetheringInterfaceSetAlarmChain[] = {
NetworkUtils::setGlobalAlarm,
NetworkUtils::removeAlarm,
NetworkUtils::networkInterfaceAlarmSuccess
};
const CommandFunc NetworkUtils::sTetheringInterfaceRemoveAlarmChain[] = {
NetworkUtils::removeGlobalAlarm,
NetworkUtils::setAlarm,
NetworkUtils::networkInterfaceAlarmSuccess
};
const CommandFunc NetworkUtils::sTetheringGetStatusChain[] = {
NetworkUtils::tetheringStatus,
NetworkUtils::defaultAsyncSuccessHandler
};
/**
* Helper function to get the mask from given prefix length.
*/
static uint32_t makeMask(const uint32_t prefixLength)
{
uint32_t mask = 0;
for (uint32_t i = 0; i < prefixLength; ++i) {
mask |= (0x80000000 >> i);
}
return ntohl(mask);
}
/**
* Helper function to get the network part of an ip from prefix.
* param ip must be in network byte order.
*/
static char* getNetworkAddr(const uint32_t ip, const uint32_t prefix)
{
uint32_t mask = 0, subnet = 0;
mask = ~mask << (32 - prefix);
mask = htonl(mask);
subnet = ip & mask;
struct in_addr addr;
addr.s_addr = subnet;
return inet_ntoa(addr);
}
/**
* Helper function to split string by seperator, store split result as an nsTArray.
*/
static void split(char* str, const char* sep, nsTArray<nsCString>& result)
{
char *s = strtok(str, sep);
while (s != nullptr) {
result.AppendElement(s);
s = strtok(nullptr, sep);
}
}
static void split(char* str, const char* sep, nsTArray<nsString>& result)
{
char *s = strtok(str, sep);
while (s != nullptr) {
result.AppendElement(NS_ConvertUTF8toUTF16(s));
s = strtok(nullptr, sep);
}
}
/**
* Helper function that implement join function.
*/
static void join(nsTArray<nsCString>& array,
const char* sep,
const uint32_t maxlen,
char* result)
{
#define CHECK_LENGTH(len, add, max) len += add; \
if (len > max - 1) \
return; \
uint32_t len = 0;
uint32_t seplen = strlen(sep);
if (array.Length() > 0) {
CHECK_LENGTH(len, strlen(array[0].get()), maxlen)
strcpy(result, array[0].get());
for (uint32_t i = 1; i < array.Length(); i++) {
CHECK_LENGTH(len, seplen, maxlen)
strcat(result, sep);
CHECK_LENGTH(len, strlen(array[i].get()), maxlen)
strcat(result, array[i].get());
}
}
#undef CHECK_LEN
}
static void convertUTF8toUTF16(nsTArray<nsCString>& narrow,
nsTArray<nsString>& wide,
uint32_t length)
{
for (uint32_t i = 0; i < length; i++) {
wide.AppendElement(NS_ConvertUTF8toUTF16(narrow[i].get()));
}
}
/**
* Helper function to get network interface properties from the system property table.
*/
static void getIFProperties(const char* ifname, IFProperties& prop)
{
char key[Property::KEY_MAX_LENGTH];
snprintf(key, Property::KEY_MAX_LENGTH - 1, "net.%s.gw", ifname);
Property::Get(key, prop.gateway, "");
snprintf(key, Property::KEY_MAX_LENGTH - 1, "net.%s.dns1", ifname);
Property::Get(key, prop.dns1, "");
snprintf(key, Property::KEY_MAX_LENGTH - 1, "net.%s.dns2", ifname);
Property::Get(key, prop.dns2, "");
}
static int getIpType(const char *aIp) {
struct addrinfo hint, *ip_info = NULL;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
hint.ai_flags = AI_NUMERICHOST;
if (getaddrinfo(aIp, NULL, &hint, &ip_info)) {
return AF_UNSPEC;
}
int type = ip_info->ai_family;
freeaddrinfo(ip_info);
return type;
}
static void postMessage(NetworkResultOptions& aResult)
{
MOZ_ASSERT(gNetworkUtils);
MOZ_ASSERT(gNetworkUtils->getMessageCallback());
if (*(gNetworkUtils->getMessageCallback()))
(*(gNetworkUtils->getMessageCallback()))(aResult);
}
static void postMessage(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
MOZ_ASSERT(gNetworkUtils);
MOZ_ASSERT(gNetworkUtils->getMessageCallback());
aResult.mId = aOptions.mId;
if (*(gNetworkUtils->getMessageCallback()))
(*(gNetworkUtils->getMessageCallback()))(aResult);
}
void NetworkUtils::runNextQueuedCommandChain()
{
if (gCommandChainQueue.IsEmpty()) {
NU_DBG("No command chain left in the queue. Done!");
return;
}
NU_DBG("Process the queued command chain.");
CommandChain* nextChain = gCommandChainQueue[0];
NetworkResultOptions newResult;
next(nextChain, false, newResult);
}
void NetworkUtils::next(CommandChain* aChain, bool aError, NetworkResultOptions& aResult)
{
if (aError) {
ErrorCallback onError = aChain->getErrorCallback();
if(onError) {
aResult.mError = true;
(*onError)(aChain->getParams(), aResult);
}
delete aChain;
gCommandChainQueue.RemoveElementAt(0);
runNextQueuedCommandChain();
return;
}
CommandFunc f = aChain->getNextCommand();
if (!f) {
delete aChain;
gCommandChainQueue.RemoveElementAt(0);
runNextQueuedCommandChain();
return;
}
(*f)(aChain, next, aResult);
}
CommandResult::CommandResult(int32_t aResultCode)
: mIsPending(false)
{
// This is usually not a netd command. We treat the return code
// typical linux convention, which uses 0 to indicate success.
mResult.mError = (aResultCode == SUCCESS ? false : true);
mResult.mResultCode = aResultCode;
if (aResultCode != SUCCESS) {
// The returned value is sometimes negative, make sure we pass a positive
// error number to strerror.
enum { STRERROR_R_BUF_SIZE = 1024, };
char strerrorBuf[STRERROR_R_BUF_SIZE];
strerror_r(abs(aResultCode), strerrorBuf, STRERROR_R_BUF_SIZE);
mResult.mReason = NS_ConvertUTF8toUTF16(strerrorBuf);
}
}
CommandResult::CommandResult(const mozilla::dom::NetworkResultOptions& aResult)
: mResult(aResult)
, mIsPending(false)
{
}
CommandResult::CommandResult(const Pending&)
: mIsPending(true)
{
}
bool CommandResult::isPending() const
{
return mIsPending;
}
/**
* Send command to netd.
*/
void NetworkUtils::nextNetdCommand()
{
if (gCommandQueue.IsEmpty() || gPending) {
return;
}
gCurrentCommand.chain = GET_CURRENT_CHAIN;
gCurrentCommand.callback = GET_CURRENT_CALLBACK;
snprintf(gCurrentCommand.command, MAX_COMMAND_SIZE - 1, "%s", GET_CURRENT_COMMAND);
NU_DBG("Sending \'%s\' command to netd.", gCurrentCommand.command);
SendNetdCommand(GET_CURRENT_NETD_COMMAND);
gCommandQueue.RemoveElementAt(0);
gPending = true;
}
/**
* Composite NetdCommand sent to netd
*
* @param aCommand Command sent to netd to execute.
* @param aChain Store command chain data, ex. command parameter.
* @param aCallback Callback function to be executed when the result of
* this command is returned from netd.
*/
void NetworkUtils::doCommand(const char* aCommand, CommandChain* aChain, CommandCallback aCallback)
{
NU_DBG("Preparing to send \'%s\' command...", aCommand);
NetdCommand* netdCommand = new NetdCommand();
// Android JB version adds sequence number to netd command.
if (SDK_VERSION >= 16) {
snprintf((char*)netdCommand->mData, MAX_COMMAND_SIZE - 1, "0 %s", aCommand);
} else {
snprintf((char*)netdCommand->mData, MAX_COMMAND_SIZE - 1, "%s", aCommand);
}
netdCommand->mSize = strlen((char*)netdCommand->mData) + 1;
gCommandQueue.AppendElement(QueueData(netdCommand, aChain, aCallback));
nextNetdCommand();
}
/*
* Netd command function
*/
#define GET_CHAR(prop) NS_ConvertUTF16toUTF8(aChain->getParams().prop).get()
#define GET_FIELD(prop) aChain->getParams().prop
void NetworkUtils::wifiFirmwareReload(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "softap fwreload %s %s", GET_CHAR(mIfname), GET_CHAR(mMode));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::startAccessPointDriver(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// Skip the command for sdk version >= 16.
if (SDK_VERSION >= 16) {
aResult.mResultCode = 0;
aResult.mResultReason = NS_ConvertUTF8toUTF16("");
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "softap start %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::stopAccessPointDriver(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// Skip the command for sdk version >= 16.
if (SDK_VERSION >= 16) {
aResult.mResultCode = 0;
aResult.mResultReason = NS_ConvertUTF8toUTF16("");
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "softap stop %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
/**
* Command format for sdk version < 16
* Arguments:
* argv[2] - wlan interface
* argv[3] - SSID
* argv[4] - Security
* argv[5] - Key
* argv[6] - Channel
* argv[7] - Preamble
* argv[8] - Max SCB
*
* Command format for sdk version >= 16
* Arguments:
* argv[2] - wlan interface
* argv[3] - SSID
* argv[4] - Security
* argv[5] - Key
*
* Command format for sdk version >= 18
* Arguments:
* argv[2] - wlan interface
* argv[3] - SSID
* argv[4] - Broadcast/Hidden
* argv[5] - Channel
* argv[6] - Security
* argv[7] - Key
*/
void NetworkUtils::setAccessPoint(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
nsCString ssid(GET_CHAR(mSsid));
nsCString key(GET_CHAR(mKey));
escapeQuote(ssid);
escapeQuote(key);
if (SDK_VERSION >= 19) {
snprintf(command, MAX_COMMAND_SIZE - 1, "softap set %s \"%s\" broadcast 6 %s \"%s\"",
GET_CHAR(mIfname),
ssid.get(),
GET_CHAR(mSecurity),
key.get());
} else if (SDK_VERSION >= 16) {
snprintf(command, MAX_COMMAND_SIZE - 1, "softap set %s \"%s\" %s \"%s\"",
GET_CHAR(mIfname),
ssid.get(),
GET_CHAR(mSecurity),
key.get());
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "softap set %s %s \"%s\" %s \"%s\" 6 0 8",
GET_CHAR(mIfname),
GET_CHAR(mWifictrlinterfacename),
ssid.get(),
GET_CHAR(mSecurity),
key.get());
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::cleanUpStream(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "nat disable %s %s 0", GET_CHAR(mPreInternalIfname), GET_CHAR(mPreExternalIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::createUpStream(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "nat enable %s %s 0", GET_CHAR(mCurInternalIfname), GET_CHAR(mCurExternalIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::startSoftAP(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
const char* command= "softap startap";
doCommand(command, aChain, aCallback);
}
void NetworkUtils::stopSoftAP(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
const char* command= "softap stopap";
doCommand(command, aChain, aCallback);
}
void NetworkUtils::clearWifiTetherParms(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
delete gWifiTetheringParms;
gWifiTetheringParms = 0;
next(aChain, false, aResult);
}
void NetworkUtils::enableAlarm(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
const char* command= "bandwidth enable";
doCommand(command, aChain, aCallback);
}
void NetworkUtils::disableAlarm(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
const char* command= "bandwidth disable";
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setQuota(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth setiquota %s % " PRId64, GET_CHAR(mIfname), INT64_MAX);
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeQuota(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth removeiquota %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setAlarm(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth setinterfacealert %s %lld",
GET_CHAR(mIfname), GET_FIELD(mThreshold));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeAlarm(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth removeinterfacealert %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setGlobalAlarm(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth setglobalalert %lld", GET_FIELD(mThreshold));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeGlobalAlarm(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth removeglobalalert");
doCommand(command, aChain, aCallback);
}
void NetworkUtils::tetherInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface add %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::addInterfaceToLocalNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// Skip the command for sdk version < 20.
if (SDK_VERSION < 20) {
aResult.mResultCode = 0;
aResult.mResultReason = NS_ConvertUTF8toUTF16("");
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "network interface add local %s",
GET_CHAR(mInternalIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::addRouteToLocalNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// Skip the command for sdk version < 20.
if (SDK_VERSION < 20) {
aResult.mResultCode = 0;
aResult.mResultReason = NS_ConvertUTF8toUTF16("");
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
uint32_t prefix = atoi(GET_CHAR(mPrefix));
uint32_t ip = inet_addr(GET_CHAR(mIp));
char* networkAddr = getNetworkAddr(ip, prefix);
snprintf(command, MAX_COMMAND_SIZE - 1, "network route add local %s %s/%s",
GET_CHAR(mInternalIfname), networkAddr, GET_CHAR(mPrefix));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::preTetherInterfaceList(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
if (SDK_VERSION >= 16) {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface list");
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface list 0");
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::postTetherInterfaceList(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// Send the dummy command to continue the function chain.
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
char buf[BUF_SIZE];
NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
size_t length = reason.Length() + 1 < BUF_SIZE ? reason.Length() + 1 : BUF_SIZE;
memcpy(buf, reason.get(), length);
split(buf, INTERFACE_DELIMIT, GET_FIELD(mInterfaceList));
doCommand(command, aChain, aCallback);
}
bool isCommandChainIPv6(CommandChain* aChain, const char *externalInterface) {
// Check by gateway address
if (getIpType(GET_CHAR(mGateway)) == AF_INET6) {
return true;
}
uint32_t length = GET_FIELD(mGateways).Length();
for (uint32_t i = 0; i < length; i++) {
NS_ConvertUTF16toUTF8 autoGateway(GET_FIELD(mGateways)[i]);
if(getIpType(autoGateway.get()) == AF_INET6) {
return true;
}
}
// Check by external inteface address
FILE *file = fopen("/proc/net/if_inet6", "r");
if (!file) {
return false;
}
bool isIPv6 = false;
char interface[32];
while(fscanf(file, "%*s %*s %*s %*s %*s %32s", interface)) {
if (strcmp(interface, externalInterface) == 0) {
isIPv6 = true;
break;
}
}
fclose(file);
return isIPv6;
}
void NetworkUtils::addUpstreamInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
nsCString interface(GET_CHAR(mExternalIfname));
if (!interface.get()[0]) {
interface = GET_CHAR(mCurExternalIfname);
}
if (SUPPORT_IPV6_TETHERING == 0 || !isCommandChainIPv6(aChain, interface.get())) {
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface add_upstream %s",
interface.get());
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeUpstreamInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
nsCString interface(GET_CHAR(mExternalIfname));
if (!interface.get()[0]) {
interface = GET_CHAR(mPreExternalIfname);
}
if (SUPPORT_IPV6_TETHERING == 0 || !isCommandChainIPv6(aChain, interface.get())) {
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface remove_upstream %s",
interface.get());
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setIpForwardingEnabled(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
if (GET_FIELD(mEnable)) {
snprintf(command, MAX_COMMAND_SIZE - 1, "ipfwd enable");
} else {
// Don't disable ip forwarding because others interface still need it.
// Send the dummy command to continue the function chain.
if (GET_FIELD(mInterfaceList).Length() > 1) {
snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "ipfwd disable");
}
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::tetheringStatus(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
const char* command= "tether status";
doCommand(command, aChain, aCallback);
}
void NetworkUtils::stopTethering(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
// Don't stop tethering because others interface still need it.
// Send the dummy to continue the function chain.
if (GET_FIELD(mInterfaceList).Length() > 1) {
snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether stop");
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::startTethering(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
// We don't need to start tethering again.
// Send the dummy command to continue the function chain.
if (aResult.mResultReason.Find("started") != kNotFound) {
snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
} else {
// If usbStartIp/usbEndIp is not valid, don't append them since
// the trailing white spaces will be parsed to extra empty args
// See: http://androidxref.com/4.3_r2.1/xref/system/core/libsysutils/src/FrameworkListener.cpp#78
if (!GET_FIELD(mUsbStartIp).IsEmpty() && !GET_FIELD(mUsbEndIp).IsEmpty()) {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether start %s %s %s %s",
GET_CHAR(mWifiStartIp), GET_CHAR(mWifiEndIp),
GET_CHAR(mUsbStartIp), GET_CHAR(mUsbEndIp));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether start %s %s",
GET_CHAR(mWifiStartIp), GET_CHAR(mWifiEndIp));
}
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::untetherInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface remove %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeInterfaceFromLocalNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// Skip the command for sdk version < 20.
if (SDK_VERSION < 20) {
aResult.mResultCode = 0;
aResult.mResultReason = NS_ConvertUTF8toUTF16("");
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "network interface remove local %s",
GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setDnsForwarders(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
if (SDK_VERSION >= 20) {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether dns set %d %s %s",
GET_FIELD(mNetId), GET_CHAR(mDns1), GET_CHAR(mDns2));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "tether dns set %s %s",
GET_CHAR(mDns1), GET_CHAR(mDns2));
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::enableNat(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
if (!GET_FIELD(mIp).IsEmpty() && !GET_FIELD(mPrefix).IsEmpty()) {
uint32_t prefix = atoi(GET_CHAR(mPrefix));
uint32_t ip = inet_addr(GET_CHAR(mIp));
char* networkAddr = getNetworkAddr(ip, prefix);
// address/prefix will only take effect when secondary routing table exists.
snprintf(command, MAX_COMMAND_SIZE - 1, "nat enable %s %s 1 %s/%s",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname), networkAddr,
GET_CHAR(mPrefix));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "nat enable %s %s 0",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::disableNat(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
if (!GET_FIELD(mIp).IsEmpty() && !GET_FIELD(mPrefix).IsEmpty()) {
uint32_t prefix = atoi(GET_CHAR(mPrefix));
uint32_t ip = inet_addr(GET_CHAR(mIp));
char* networkAddr = getNetworkAddr(ip, prefix);
snprintf(command, MAX_COMMAND_SIZE - 1, "nat disable %s %s 1 %s/%s",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname), networkAddr,
GET_CHAR(mPrefix));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "nat disable %s %s 0",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setDefaultInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "resolver setdefaultif %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeDefaultRoute(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
if (GET_FIELD(mLoopIndex) >= GET_FIELD(mGateways).Length()) {
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
nsTArray<nsString>& gateways = GET_FIELD(mGateways);
NS_ConvertUTF16toUTF8 autoGateway(gateways[GET_FIELD(mLoopIndex)]);
int type = getIpType(autoGateway.get());
snprintf(command, MAX_COMMAND_SIZE - 1, "network route remove %d %s %s/0 %s",
GET_FIELD(mNetId), GET_CHAR(mIfname),
type == AF_INET6 ? "::" : "0.0.0.0", autoGateway.get());
struct MyCallback {
static void callback(CommandCallback::CallbackType aOriginalCallback,
CommandChain* aChain,
bool aError,
mozilla::dom::NetworkResultOptions& aResult)
{
NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
NU_DBG("removeDefaultRoute's reason: %s", reason.get());
if (aError && !reason.EqualsASCII("removeRoute() failed (No such process)")) {
return aOriginalCallback(aChain, aError, aResult);
}
GET_FIELD(mLoopIndex)++;
return removeDefaultRoute(aChain, aOriginalCallback, aResult);
}
};
CommandCallback wrappedCallback(MyCallback::callback, aCallback);
doCommand(command, aChain, wrappedCallback);
}
void NetworkUtils::setInterfaceDns(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
int written;
if (SDK_VERSION >= 20) {
written = SprintfLiteral(command, "resolver setnetdns %d %s",
GET_FIELD(mNetId), GET_CHAR(mDomain));
} else {
written = SprintfLiteral(command, "resolver setifdns %s %s",
GET_CHAR(mIfname), GET_CHAR(mDomain));
}
nsTArray<nsString>& dnses = GET_FIELD(mDnses);
uint32_t length = dnses.Length();
for (uint32_t i = 0; i < length; i++) {
NS_ConvertUTF16toUTF8 autoDns(dnses[i]);
int ret = snprintf(command + written, sizeof(command) - written, " %s", autoDns.get());
if (ret <= 1) {
command[written] = '\0';
continue;
}
if (((size_t)ret + written) >= sizeof(command)) {
command[written] = '\0';
break;
}
written += ret;
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::getInterfaceList(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "interface list");
doCommand(command, aChain, aCallback);
}
void NetworkUtils::getConfig(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "interface getcfg %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setConfig(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
if (SDK_VERSION >= 16) {
snprintf(command, MAX_COMMAND_SIZE - 1, "interface setcfg %s %s %s %s",
GET_CHAR(mIfname),
GET_CHAR(mIp),
GET_CHAR(mPrefix),
GET_CHAR(mLink));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1, "interface setcfg %s %s %s [%s]",
GET_CHAR(mIfname),
GET_CHAR(mIp),
GET_CHAR(mPrefix),
GET_CHAR(mLink));
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::clearAddrForInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "interface clearaddrs %s", GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::createNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "network create %d", GET_FIELD(mNetId));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::destroyNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "network destroy %d", GET_FIELD(mNetId));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::addInterfaceToNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "network interface add %d %s",
GET_FIELD(mNetId), GET_CHAR(mIfname));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::addRouteToInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
struct MyCallback {
static void callback(CommandCallback::CallbackType aOriginalCallback,
CommandChain* aChain,
bool aError,
mozilla::dom::NetworkResultOptions& aResult)
{
NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
NU_DBG("addRouteToInterface's reason: %s", reason.get());
if (aError && reason.EqualsASCII("addRoute() failed (File exists)")) {
NU_DBG("Ignore \"File exists\" error when adding host route.");
return aOriginalCallback(aChain, false, aResult);
}
aOriginalCallback(aChain, aError, aResult);
}
};
CommandCallback wrappedCallback(MyCallback::callback, aCallback);
modifyRouteOnInterface(aChain, wrappedCallback, aResult, true);
}
void NetworkUtils::removeRouteFromInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
modifyRouteOnInterface(aChain, aCallback, aResult, false);
}
void NetworkUtils::modifyRouteOnInterface(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult,
bool aDoAdd)
{
char command[MAX_COMMAND_SIZE];
// AOSP adds host route to its interface table but it doesn't work for
// B2G because we cannot set fwmark per application. So, we add
// all host routes to legacy_system table except scope link route.
nsCString ipOrSubnetIp = NS_ConvertUTF16toUTF8(GET_FIELD(mIp));
nsCString gatewayOrEmpty;
const char* legacyOrEmpty = "legacy 0 "; // Add to legacy by default.
if (GET_FIELD(mGateway).IsEmpty()) {
ipOrSubnetIp = getSubnetIp(ipOrSubnetIp, GET_FIELD(mPrefixLength));
legacyOrEmpty = ""; // Add to interface table for scope link route.
} else {
gatewayOrEmpty = nsCString(" ") + NS_ConvertUTF16toUTF8(GET_FIELD(mGateway));
}
const char* action = aDoAdd ? "add" : "remove";
snprintf(command, MAX_COMMAND_SIZE - 1, "network route %s%s %d %s %s/%d%s",
legacyOrEmpty, action,
GET_FIELD(mNetId), GET_CHAR(mIfname), ipOrSubnetIp.get(),
GET_FIELD(mPrefixLength), gatewayOrEmpty.get());
doCommand(command, aChain, aCallback);
}
void NetworkUtils::addDefaultRouteToNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
if (GET_FIELD(mLoopIndex) >= GET_FIELD(mGateways).Length()) {
aCallback(aChain, false, aResult);
return;
}
char command[MAX_COMMAND_SIZE];
nsTArray<nsString>& gateways = GET_FIELD(mGateways);
NS_ConvertUTF16toUTF8 autoGateway(gateways[GET_FIELD(mLoopIndex)]);
int type = getIpType(autoGateway.get());
snprintf(command, MAX_COMMAND_SIZE - 1, "network route add %d %s %s/0 %s",
GET_FIELD(mNetId), GET_CHAR(mIfname),
type == AF_INET6 ? "::" : "0.0.0.0", autoGateway.get());
struct MyCallback {
static void callback(CommandCallback::CallbackType aOriginalCallback,
CommandChain* aChain,
bool aError,
mozilla::dom::NetworkResultOptions& aResult)
{
NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
NU_DBG("addDefaultRouteToNetwork's reason: %s", reason.get());
if (aError && !reason.EqualsASCII("addRoute() failed (File exists)")) {
return aOriginalCallback(aChain, aError, aResult);
}
GET_FIELD(mLoopIndex)++;
return addDefaultRouteToNetwork(aChain, aOriginalCallback, aResult);
}
};
CommandCallback wrappedCallback(MyCallback::callback, aCallback);
doCommand(command, aChain, wrappedCallback);
}
void NetworkUtils::setDefaultNetwork(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "network default set %d", GET_FIELD(mNetId));
doCommand(command, aChain, aCallback);
}
void NetworkUtils::addRouteToSecondaryTable(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult) {
char command[MAX_COMMAND_SIZE];
if (SDK_VERSION >= 20) {
snprintf(command, MAX_COMMAND_SIZE - 1,
"network route add %d %s %s/%s %s",
GET_FIELD(mNetId),
GET_CHAR(mIfname),
GET_CHAR(mIp),
GET_CHAR(mPrefix),
GET_CHAR(mGateway));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1,
"interface route add %s secondary %s %s %s",
GET_CHAR(mIfname),
GET_CHAR(mIp),
GET_CHAR(mPrefix),
GET_CHAR(mGateway));
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::removeRouteFromSecondaryTable(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult) {
char command[MAX_COMMAND_SIZE];
if (SDK_VERSION >= 20) {
snprintf(command, MAX_COMMAND_SIZE - 1,
"network route remove %d %s %s/%s %s",
GET_FIELD(mNetId),
GET_CHAR(mIfname),
GET_CHAR(mIp),
GET_CHAR(mPrefix),
GET_CHAR(mGateway));
} else {
snprintf(command, MAX_COMMAND_SIZE - 1,
"interface route remove %s secondary %s %s %s",
GET_CHAR(mIfname),
GET_CHAR(mIp),
GET_CHAR(mPrefix),
GET_CHAR(mGateway));
}
doCommand(command, aChain, aCallback);
}
void NetworkUtils::setIpv6Enabled(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult,
bool aEnabled)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "interface ipv6 %s %s",
GET_CHAR(mIfname), aEnabled ? "enable" : "disable");
struct MyCallback {
static void callback(CommandCallback::CallbackType aOriginalCallback,
CommandChain* aChain,
bool aError,
mozilla::dom::NetworkResultOptions& aResult)
{
aOriginalCallback(aChain, false, aResult);
}
};
CommandCallback wrappedCallback(MyCallback::callback, aCallback);
doCommand(command, aChain, wrappedCallback);
}
void NetworkUtils::enableIpv6(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
setIpv6Enabled(aChain, aCallback, aResult, true);
}
void NetworkUtils::disableIpv6(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
setIpv6Enabled(aChain, aCallback, aResult, false);
}
void NetworkUtils::setMtu(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char command[MAX_COMMAND_SIZE];
snprintf(command, MAX_COMMAND_SIZE - 1, "interface setmtu %s %ld",
GET_CHAR(mIfname), GET_FIELD(mMtu));
doCommand(command, aChain, aCallback);
}
#undef GET_CHAR
#undef GET_FIELD
/*
* Netd command success/fail function
*/
#define ASSIGN_FIELD(prop) aResult.prop = aChain->getParams().prop;
#define ASSIGN_FIELD_VALUE(prop, value) aResult.prop = value;
template<size_t N>
void NetworkUtils::runChain(const NetworkParams& aParams,
const CommandFunc (&aCmds)[N],
ErrorCallback aError)
{
CommandChain* chain = new CommandChain(aParams, aCmds, N, aError);
gCommandChainQueue.AppendElement(chain);
if (gCommandChainQueue.Length() > 1) {
NU_DBG("%d command chains are queued. Wait!", gCommandChainQueue.Length());
return;
}
NetworkResultOptions result;
NetworkUtils::next(gCommandChainQueue[0], false, result);
}
// Called to clean up the command chain and process the queued command chain if any.
void NetworkUtils::finalizeSuccess(CommandChain* aChain,
NetworkResultOptions& aResult)
{
next(aChain, false, aResult);
}
void NetworkUtils::wifiTetheringFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
// Notify the main thread.
postMessage(aOptions, aResult);
// If one of the stages fails, we try roll back to ensure
// we don't leave the network systems in limbo.
ASSIGN_FIELD_VALUE(mEnable, false)
runChain(aOptions, sWifiFailChain, nullptr);
}
void NetworkUtils::wifiTetheringSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
ASSIGN_FIELD(mEnable)
if (aChain->getParams().mEnable) {
MOZ_ASSERT(!gWifiTetheringParms);
gWifiTetheringParms = new NetworkParams(aChain->getParams());
}
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::usbTetheringFail(NetworkParams& aOptions,
NetworkResultOptions& aResult)
{
// Notify the main thread.
postMessage(aOptions, aResult);
// Try to roll back to ensure
// we don't leave the network systems in limbo.
// This parameter is used to disable ipforwarding.
{
aOptions.mEnable = false;
runChain(aOptions, sUSBFailChain, nullptr);
}
// Disable usb rndis function.
{
NetworkParams options;
options.mEnable = false;
options.mReport = false;
gNetworkUtils->enableUsbRndis(options);
}
}
void NetworkUtils::usbTetheringSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
ASSIGN_FIELD(mEnable)
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::networkInterfaceAlarmFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::networkInterfaceAlarmSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
// TODO : error is not used , and it is conflict with boolean type error.
// params.error = parseFloat(params.resultReason);
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::updateUpStreamFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::updateUpStreamSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
ASSIGN_FIELD(mCurExternalIfname)
ASSIGN_FIELD(mCurInternalIfname)
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::setDhcpServerFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
aResult.mSuccess = false;
postMessage(aOptions, aResult);
}
void NetworkUtils::setDhcpServerSuccess(CommandChain* aChain, CommandCallback aCallback, NetworkResultOptions& aResult)
{
aResult.mSuccess = true;
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::wifiOperationModeFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::wifiOperationModeSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::setDnsFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::defaultAsyncSuccessHandler(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
NU_DBG("defaultAsyncSuccessHandler");
aResult.mRet = true;
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::defaultAsyncFailureHandler(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
aResult.mRet = false;
postMessage(aOptions, aResult);
}
void NetworkUtils::getInterfacesFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::getInterfacesSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char buf[BUF_SIZE];
NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
memcpy(buf, reason.get(), strlen(reason.get()));
nsTArray<nsCString> result;
split(buf, INTERFACE_DELIMIT, result);
nsTArray<nsString> interfaceList;
uint32_t length = result.Length();
convertUTF8toUTF16(result, interfaceList, length);
aResult.mInterfaceList.Construct();
for (uint32_t i = 0; i < length; i++) {
aResult.mInterfaceList.Value().AppendElement(interfaceList[i], fallible_t());
}
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::getInterfaceConfigFail(NetworkParams& aOptions,
NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::getInterfaceConfigSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
char buf[BUF_SIZE];
NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
memcpy(buf, reason.get(), strlen(reason.get()));
nsTArray<nsCString> result;
split(buf, NETD_MESSAGE_DELIMIT, result);
ASSIGN_FIELD_VALUE(mMacAddr, NS_ConvertUTF8toUTF16(result[0]))
ASSIGN_FIELD_VALUE(mIpAddr, NS_ConvertUTF8toUTF16(result[1]))
ASSIGN_FIELD_VALUE(mPrefixLength, atol(result[2].get()))
if (result[3].Find("up")) {
ASSIGN_FIELD_VALUE(mFlag, NS_ConvertUTF8toUTF16("up"))
} else {
ASSIGN_FIELD_VALUE(mFlag, NS_ConvertUTF8toUTF16("down"))
}
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
void NetworkUtils::setInterfaceConfigFail(NetworkParams& aOptions,
NetworkResultOptions& aResult)
{
postMessage(aOptions, aResult);
}
void NetworkUtils::setInterfaceConfigSuccess(CommandChain* aChain,
CommandCallback aCallback,
NetworkResultOptions& aResult)
{
postMessage(aChain->getParams(), aResult);
finalizeSuccess(aChain, aResult);
}
#undef ASSIGN_FIELD
#undef ASSIGN_FIELD_VALUE
NetworkUtils::NetworkUtils(MessageCallback aCallback)
: mMessageCallback(aCallback)
{
mNetUtils = new NetUtils();
char value[Property::VALUE_MAX_LENGTH];
Property::Get("ro.build.version.sdk", value, nullptr);
SDK_VERSION = atoi(value);
Property::Get(IPV6_TETHERING, value, "0");
SUPPORT_IPV6_TETHERING = atoi(value);
gNetworkUtils = this;
}
NetworkUtils::~NetworkUtils()
{
}
#define GET_CHAR(prop) NS_ConvertUTF16toUTF8(aOptions.prop).get()
#define GET_FIELD(prop) aOptions.prop
// Hoist this type definition to global to avoid template
// instantiation error on gcc 4.4 used by ICS emulator.
typedef CommandResult (NetworkUtils::*CommandHandler)(NetworkParams&);
struct CommandHandlerEntry
{
const char* mCommandName;
CommandHandler mCommandHandler;
};
void NetworkUtils::ExecuteCommand(NetworkParams aOptions)
{
const static CommandHandlerEntry
COMMAND_HANDLER_TABLE[] = {
// For command 'testCommand', BUILD_ENTRY(testCommand) will generate
// {"testCommand", NetworkUtils::testCommand}
#define BUILD_ENTRY(c) {#c, &NetworkUtils::c}
BUILD_ENTRY(removeNetworkRoute),
BUILD_ENTRY(setDNS),
BUILD_ENTRY(setDefaultRoute),
BUILD_ENTRY(removeDefaultRoute),
BUILD_ENTRY(addHostRoute),
BUILD_ENTRY(removeHostRoute),
BUILD_ENTRY(addSecondaryRoute),
BUILD_ENTRY(removeSecondaryRoute),
BUILD_ENTRY(setNetworkInterfaceAlarm),
BUILD_ENTRY(enableNetworkInterfaceAlarm),
BUILD_ENTRY(disableNetworkInterfaceAlarm),
BUILD_ENTRY(setTetheringAlarm),
BUILD_ENTRY(removeTetheringAlarm),
BUILD_ENTRY(getTetheringStatus),
BUILD_ENTRY(setWifiOperationMode),
BUILD_ENTRY(setDhcpServer),
BUILD_ENTRY(setWifiTethering),
BUILD_ENTRY(setUSBTethering),
BUILD_ENTRY(enableUsbRndis),
BUILD_ENTRY(updateUpStream),
BUILD_ENTRY(configureInterface),
BUILD_ENTRY(dhcpRequest),
BUILD_ENTRY(stopDhcp),
BUILD_ENTRY(enableInterface),
BUILD_ENTRY(disableInterface),
BUILD_ENTRY(resetConnections),
BUILD_ENTRY(createNetwork),
BUILD_ENTRY(destroyNetwork),
BUILD_ENTRY(getNetId),
BUILD_ENTRY(getInterfaces),
BUILD_ENTRY(getInterfaceConfig),
BUILD_ENTRY(setInterfaceConfig),
BUILD_ENTRY(setMtu),
#undef BUILD_ENTRY
};
// Loop until we find the command name which matches aOptions.mCmd.
CommandHandler handler = nullptr;
for (size_t i = 0; i < mozilla::ArrayLength(COMMAND_HANDLER_TABLE); i++) {
if (aOptions.mCmd.EqualsASCII(COMMAND_HANDLER_TABLE[i].mCommandName)) {
handler = COMMAND_HANDLER_TABLE[i].mCommandHandler;
break;
}
}
if (!handler) {
// Command not found in COMMAND_HANDLER_TABLE.
WARN("unknown message: %s", NS_ConvertUTF16toUTF8(aOptions.mCmd).get());
return;
}
// The handler would return one of the following 3 values
// to be wrapped to CommandResult:
//
// 1) |int32_t| for mostly synchronous native function calls.
// 2) |NetworkResultOptions| to populate additional results. (e.g. dhcpRequest)
// 3) |CommandResult::Pending| to indicate the result is not
// obtained yet.
//
// If the handler returns "Pending", the handler should take the
// responsibility for posting result to main thread.
CommandResult commandResult = (this->*handler)(aOptions);
if (!commandResult.isPending()) {
postMessage(aOptions, commandResult.mResult);
}
}
/**
* Handle received data from netd.
*/
void NetworkUtils::onNetdMessage(NetdCommand* aCommand)
{
char* data = (char*)aCommand->mData;
// get code & reason.
char* result = strtok(data, NETD_MESSAGE_DELIMIT);
if (!result) {
nextNetdCommand();
return;
}
uint32_t code = atoi(result);
if (!isBroadcastMessage(code) && SDK_VERSION >= 16) {
strtok(nullptr, NETD_MESSAGE_DELIMIT);
}
char* reason = strtok(nullptr, "\0");
if (isBroadcastMessage(code)) {
NU_DBG("Receiving broadcast message from netd.");
NU_DBG(" ==> Code: %d Reason: %s", code, reason);
sendBroadcastMessage(code, reason);
if (code == NETD_COMMAND_INTERFACE_CHANGE) {
if (gWifiTetheringParms) {
char linkdownReason[MAX_COMMAND_SIZE];
snprintf(linkdownReason, MAX_COMMAND_SIZE - 1,
"Iface linkstate %s down",
NS_ConvertUTF16toUTF8(gWifiTetheringParms->mIfname).get());
if (!strcmp(reason, linkdownReason)) {
NU_DBG("Wifi link down, restarting tethering.");
runChain(*gWifiTetheringParms, sWifiRetryChain, wifiTetheringFail);
}
}
}
nextNetdCommand();
return;
}
// Set pending to false before we handle next command.
NU_DBG("Receiving \"%s\" command response from netd.", gCurrentCommand.command);
NU_DBG(" ==> Code: %d Reason: %s", code, reason);
gReason.AppendElement(nsCString(reason));
// 1xx response code regards as command is proceeding, we need to wait for
// final response code such as 2xx, 4xx and 5xx before sending next command.
if (isProceeding(code)) {
return;
}
if (isComplete(code)) {
gPending = false;
}
{
char buf[BUF_SIZE];
join(gReason, INTERFACE_DELIMIT, BUF_SIZE, buf);
NetworkResultOptions result;
result.mResultCode = code;
result.mResultReason = NS_ConvertUTF8toUTF16(buf);
(gCurrentCommand.callback)(gCurrentCommand.chain, isError(code), result);
gReason.Clear();
}
// Handling pending commands if any.
if (isComplete(code)) {
nextNetdCommand();
}
}
/**
* Start/Stop DHCP server.
*/
CommandResult NetworkUtils::setDhcpServer(NetworkParams& aOptions)
{
if (aOptions.mEnabled) {
aOptions.mWifiStartIp = aOptions.mStartIp;
aOptions.mWifiEndIp = aOptions.mEndIp;
aOptions.mIp = aOptions.mServerIp;
aOptions.mPrefix = aOptions.mMaskLength;
aOptions.mLink = NS_ConvertUTF8toUTF16("up");
runChain(aOptions, sStartDhcpServerChain, setDhcpServerFail);
} else {
runChain(aOptions, sStopDhcpServerChain, setDhcpServerFail);
}
return CommandResult::Pending();
}
/**
* Set DNS servers for given network interface.
*/
CommandResult NetworkUtils::setDNS(NetworkParams& aOptions)
{
uint32_t length = aOptions.mDnses.Length();
if (length > 0) {
for (uint32_t i = 0; i < length; i++) {
NS_ConvertUTF16toUTF8 autoDns(aOptions.mDnses[i]);
char dns_prop_key[Property::VALUE_MAX_LENGTH];
SprintfLiteral(dns_prop_key, "net.dns%d", i+1);
Property::Set(dns_prop_key, autoDns.get());
}
} else {
// Set dnses from system properties.
IFProperties interfaceProperties;
getIFProperties(GET_CHAR(mIfname), interfaceProperties);
Property::Set("net.dns1", interfaceProperties.dns1);
Property::Set("net.dns2", interfaceProperties.dns2);
}
// Bump the DNS change property.
char dnschange[Property::VALUE_MAX_LENGTH];
Property::Get("net.dnschange", dnschange, "0");
char num[Property::VALUE_MAX_LENGTH];
snprintf(num, Property::VALUE_MAX_LENGTH - 1, "%d", atoi(dnschange) + 1);
Property::Set("net.dnschange", num);
// DNS needs to be set through netd since JellyBean (4.3).
if (SDK_VERSION >= 20) {
// Lollipop.
static CommandFunc COMMAND_CHAIN[] = {
setInterfaceDns,
addDefaultRouteToNetwork,
defaultAsyncSuccessHandler
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(aOptions.mIfname, &netIdInfo)) {
return -1;
}
aOptions.mNetId = netIdInfo.mNetId;
runChain(aOptions, COMMAND_CHAIN, setDnsFail);
return CommandResult::Pending();
}
if (SDK_VERSION >= 18) {
// JB, KK.
static CommandFunc COMMAND_CHAIN[] = {
#if ANDROID_VERSION == 18
// Since we don't use per-interface DNS lookup feature on JB,
// we need to set the default DNS interface whenever setting the
// DNS name server.
setDefaultInterface,
#endif
setInterfaceDns,
defaultAsyncSuccessHandler
};
runChain(aOptions, COMMAND_CHAIN, setDnsFail);
return CommandResult::Pending();
}
return SUCCESS;
}
CommandResult NetworkUtils::configureInterface(NetworkParams& aOptions)
{
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
return mNetUtils->do_ifc_configure(
autoIfname.get(),
aOptions.mIpaddr,
aOptions.mMask,
aOptions.mGateway_long,
aOptions.mDns1_long,
aOptions.mDns2_long
);
}
CommandResult NetworkUtils::stopDhcp(NetworkParams& aOptions)
{
return mNetUtils->do_dhcp_stop(GET_CHAR(mIfname));
}
CommandResult NetworkUtils::dhcpRequest(NetworkParams& aOptions) {
mozilla::dom::NetworkResultOptions result;
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
char ipaddr[Property::VALUE_MAX_LENGTH];
char gateway[Property::VALUE_MAX_LENGTH];
uint32_t prefixLength;
char dns1[Property::VALUE_MAX_LENGTH];
char dns2[Property::VALUE_MAX_LENGTH];
char server[Property::VALUE_MAX_LENGTH];
uint32_t lease;
char vendorinfo[Property::VALUE_MAX_LENGTH];
int32_t ret = mNetUtils->do_dhcp_do_request(autoIfname.get(),
ipaddr,
gateway,
&prefixLength,
dns1,
dns2,
server,
&lease,
vendorinfo);
RETURN_IF_FAILED(ret);
result.mIpaddr_str = NS_ConvertUTF8toUTF16(ipaddr);
result.mGateway_str = NS_ConvertUTF8toUTF16(gateway);
result.mDns1_str = NS_ConvertUTF8toUTF16(dns1);
result.mDns2_str = NS_ConvertUTF8toUTF16(dns2);
result.mServer_str = NS_ConvertUTF8toUTF16(server);
result.mVendor_str = NS_ConvertUTF8toUTF16(vendorinfo);
result.mLease = lease;
result.mPrefixLength = prefixLength;
result.mMask = makeMask(prefixLength);
uint32_t inet4; // only support IPv4 for now.
#define INET_PTON(var, field) \
PR_BEGIN_MACRO \
inet_pton(AF_INET, var, &inet4); \
result.field = inet4; \
PR_END_MACRO
INET_PTON(ipaddr, mIpaddr);
INET_PTON(gateway, mGateway);
if (dns1[0] != '\0') {
INET_PTON(dns1, mDns1);
}
if (dns2[0] != '\0') {
INET_PTON(dns2, mDns2);
}
INET_PTON(server, mServer);
char inet_str[64];
if (inet_ntop(AF_INET, &result.mMask, inet_str, sizeof(inet_str))) {
result.mMask_str = NS_ConvertUTF8toUTF16(inet_str);
}
return result;
}
CommandResult NetworkUtils::enableInterface(NetworkParams& aOptions) {
return mNetUtils->do_ifc_enable(
NS_ConvertUTF16toUTF8(aOptions.mIfname).get());
}
CommandResult NetworkUtils::disableInterface(NetworkParams& aOptions) {
return mNetUtils->do_ifc_disable(
NS_ConvertUTF16toUTF8(aOptions.mIfname).get());
}
CommandResult NetworkUtils::resetConnections(NetworkParams& aOptions) {
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
return mNetUtils->do_ifc_reset_connections(
NS_ConvertUTF16toUTF8(aOptions.mIfname).get(),
RESET_ALL_ADDRESSES);
}
/**
* Set default route and DNS servers for given network interface.
*/
CommandResult NetworkUtils::setDefaultRoute(NetworkParams& aOptions)
{
if (SDK_VERSION < 20) {
return setDefaultRouteLegacy(aOptions);
}
static CommandFunc COMMAND_CHAIN[] = {
addDefaultRouteToNetwork,
setDefaultNetwork,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
ERROR("No such interface");
return -1;
}
aOptions.mNetId = netIdInfo.mNetId;
aOptions.mLoopIndex = 0;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
/**
* Set default route and DNS servers for given network interface by obsoleted libnetutils.
*/
CommandResult NetworkUtils::setDefaultRouteLegacy(NetworkParams& aOptions)
{
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
uint32_t length = aOptions.mGateways.Length();
if (length > 0) {
for (uint32_t i = 0; i < length; i++) {
NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateways[i]);
int type = getIpType(autoGateway.get());
if (type != AF_INET && type != AF_INET6) {
continue;
}
if (type == AF_INET6) {
RETURN_IF_FAILED(mNetUtils->do_ifc_add_route(autoIfname.get(), "::", 0, autoGateway.get()));
} else { /* type == AF_INET */
RETURN_IF_FAILED(mNetUtils->do_ifc_set_default_route(autoIfname.get(), inet_addr(autoGateway.get())));
}
}
} else {
// Set default froute from system properties.
char key[Property::KEY_MAX_LENGTH];
char gateway[Property::KEY_MAX_LENGTH];
snprintf(key, sizeof key - 1, "net.%s.gw", autoIfname.get());
Property::Get(key, gateway, "");
int type = getIpType(gateway);
if (type != AF_INET && type != AF_INET6) {
return EAFNOSUPPORT;
}
if (type == AF_INET6) {
RETURN_IF_FAILED(mNetUtils->do_ifc_add_route(autoIfname.get(), "::", 0, gateway));
} else { /* type == AF_INET */
RETURN_IF_FAILED(mNetUtils->do_ifc_set_default_route(autoIfname.get(), inet_addr(gateway)));
}
}
// Set the default DNS interface.
if (SDK_VERSION >= 18) {
// For JB, KK only.
static CommandFunc COMMAND_CHAIN[] = {
setDefaultInterface,
defaultAsyncSuccessHandler
};
runChain(aOptions, COMMAND_CHAIN, setDnsFail);
return CommandResult::Pending();
}
return SUCCESS;
}
/**
* Remove default route for given network interface.
*/
CommandResult NetworkUtils::removeDefaultRoute(NetworkParams& aOptions)
{
NU_DBG("Calling NetworkUtils::removeDefaultRoute");
if (SDK_VERSION < 20) {
return removeDefaultRouteLegacy(aOptions);
}
static CommandFunc COMMAND_CHAIN[] = {
removeDefaultRoute,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
ERROR("No such interface: %s", GET_CHAR(mIfname));
return -1;
}
NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
aOptions.mNetId = netIdInfo.mNetId;
aOptions.mLoopIndex = 0;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
/**
* Remove default route for given network interface by obsoleted libnetutils.
*/
CommandResult NetworkUtils::removeDefaultRouteLegacy(NetworkParams& aOptions)
{
// Legacy libnetutils calls before Lollipop.
uint32_t length = aOptions.mGateways.Length();
for (uint32_t i = 0; i < length; i++) {
NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateways[i]);
int type = getIpType(autoGateway.get());
if (type != AF_INET && type != AF_INET6) {
return EAFNOSUPPORT;
}
WARN_IF_FAILED(mNetUtils->do_ifc_remove_route(GET_CHAR(mIfname),
type == AF_INET ? "0.0.0.0" : "::",
0, autoGateway.get()));
}
return SUCCESS;
}
/**
* Add host route for given network interface.
*/
CommandResult NetworkUtils::addHostRoute(NetworkParams& aOptions)
{
if (SDK_VERSION < 20) {
return addHostRouteLegacy(aOptions);
}
static CommandFunc COMMAND_CHAIN[] = {
addRouteToInterface,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
ERROR("No such interface: %s", GET_CHAR(mIfname));
return -1;
}
NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
aOptions.mNetId = netIdInfo.mNetId;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
/**
* Add host route for given network interface.
*/
CommandResult NetworkUtils::addHostRouteLegacy(NetworkParams& aOptions)
{
if (aOptions.mGateway.IsEmpty()) {
ERROR("addHostRouteLegacy does not support empty gateway.");
return EINVAL;
}
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
NS_ConvertUTF16toUTF8 autoHostname(aOptions.mIp);
NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateway);
int type, prefix;
type = getIpType(autoHostname.get());
if (type != AF_INET && type != AF_INET6) {
return EAFNOSUPPORT;
}
if (type != getIpType(autoGateway.get())) {
return EINVAL;
}
prefix = type == AF_INET ? 32 : 128;
return mNetUtils->do_ifc_add_route(autoIfname.get(), autoHostname.get(),
prefix, autoGateway.get());
}
/**
* Remove host route for given network interface.
*/
CommandResult NetworkUtils::removeHostRoute(NetworkParams& aOptions)
{
if (SDK_VERSION < 20) {
return removeHostRouteLegacy(aOptions);
}
static CommandFunc COMMAND_CHAIN[] = {
removeRouteFromInterface,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
ERROR("No such interface: %s", GET_CHAR(mIfname));
return -1;
}
NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
aOptions.mNetId = netIdInfo.mNetId;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
/**
* Remove host route for given network interface.
*/
CommandResult NetworkUtils::removeHostRouteLegacy(NetworkParams& aOptions)
{
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
NS_ConvertUTF16toUTF8 autoHostname(aOptions.mIp);
NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateway);
int type, prefix;
type = getIpType(autoHostname.get());
if (type != AF_INET && type != AF_INET6) {
return EAFNOSUPPORT;
}
if (type != getIpType(autoGateway.get())) {
return EINVAL;
}
prefix = type == AF_INET ? 32 : 128;
return mNetUtils->do_ifc_remove_route(autoIfname.get(), autoHostname.get(),
prefix, autoGateway.get());
}
CommandResult NetworkUtils::removeNetworkRoute(NetworkParams& aOptions)
{
if (SDK_VERSION < 20) {
return removeNetworkRouteLegacy(aOptions);
}
static CommandFunc COMMAND_CHAIN[] = {
clearAddrForInterface,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
ERROR("interface %s is not present in any network", GET_CHAR(mIfname));
return -1;
}
NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
aOptions.mNetId = netIdInfo.mNetId;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
nsCString NetworkUtils::getSubnetIp(const nsCString& aIp, int aPrefixLength)
{
int type = getIpType(aIp.get());
if (AF_INET6 == type) {
struct in6_addr in6;
if (inet_pton(AF_INET6, aIp.get(), &in6) != 1) {
return nsCString();
}
uint32_t p, i, p1, mask;
p = aPrefixLength;
i = 0;
while (i < 4) {
p1 = p > 32 ? 32 : p;
p -= p1;
mask = p1 ? ~0x0 << (32 - p1) : 0;
in6.s6_addr32[i++] &= htonl(mask);
}
char subnetStr[INET6_ADDRSTRLEN];
if (!inet_ntop(AF_INET6, &in6, subnetStr, sizeof subnetStr)) {
return nsCString();
}
return nsCString(subnetStr);
}
if (AF_INET == type) {
uint32_t ip = inet_addr(aIp.get());
uint32_t netmask = makeMask(aPrefixLength);
uint32_t subnet = ip & netmask;
struct in_addr addr;
addr.s_addr = subnet;
return nsCString(inet_ntoa(addr));
}
return nsCString();
}
CommandResult NetworkUtils::removeNetworkRouteLegacy(NetworkParams& aOptions)
{
NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
NS_ConvertUTF16toUTF8 autoIp(aOptions.mIp);
int type = getIpType(autoIp.get());
if (type != AF_INET && type != AF_INET6) {
return EAFNOSUPPORT;
}
uint32_t prefixLength = GET_FIELD(mPrefixLength);
if (type == AF_INET6) {
// Calculate subnet.
struct in6_addr in6;
if (inet_pton(AF_INET6, autoIp.get(), &in6) != 1) {
return EINVAL;
}
uint32_t p, i, p1, mask;
p = prefixLength;
i = 0;
while (i < 4) {
p1 = p > 32 ? 32 : p;
p -= p1;
mask = p1 ? ~0x0 << (32 - p1) : 0;
in6.s6_addr32[i++] &= htonl(mask);
}
char subnetStr[INET6_ADDRSTRLEN];
if (!inet_ntop(AF_INET6, &in6, subnetStr, sizeof subnetStr)) {
return EINVAL;
}
// Remove default route.
WARN_IF_FAILED(mNetUtils->do_ifc_remove_route(autoIfname.get(), "::", 0, NULL));
// Remove subnet route.
RETURN_IF_FAILED(mNetUtils->do_ifc_remove_route(autoIfname.get(), subnetStr, prefixLength, NULL));
return SUCCESS;
}
/* type == AF_INET */
uint32_t ip = inet_addr(autoIp.get());
uint32_t netmask = makeMask(prefixLength);
uint32_t subnet = ip & netmask;
const char* gateway = "0.0.0.0";
struct in_addr addr;
addr.s_addr = subnet;
const char* dst = inet_ntoa(addr);
RETURN_IF_FAILED(mNetUtils->do_ifc_remove_default_route(autoIfname.get()));
RETURN_IF_FAILED(mNetUtils->do_ifc_remove_route(autoIfname.get(), dst, prefixLength, gateway));
return SUCCESS;
}
CommandResult NetworkUtils::addSecondaryRoute(NetworkParams& aOptions)
{
static CommandFunc COMMAND_CHAIN[] = {
addRouteToSecondaryTable,
defaultAsyncSuccessHandler
};
if (SDK_VERSION >= 20) {
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(aOptions.mIfname, &netIdInfo)) {
return -1;
}
aOptions.mNetId = netIdInfo.mNetId;
}
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
CommandResult NetworkUtils::removeSecondaryRoute(NetworkParams& aOptions)
{
static CommandFunc COMMAND_CHAIN[] = {
removeRouteFromSecondaryTable,
defaultAsyncSuccessHandler
};
if (SDK_VERSION >= 20) {
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(aOptions.mIfname, &netIdInfo)) {
return -1;
}
aOptions.mNetId = netIdInfo.mNetId;
}
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
CommandResult NetworkUtils::setNetworkInterfaceAlarm(NetworkParams& aOptions)
{
NU_DBG("setNetworkInterfaceAlarms: %s", GET_CHAR(mIfname));
runChain(aOptions, sNetworkInterfaceSetAlarmChain, networkInterfaceAlarmFail);
return CommandResult::Pending();
}
CommandResult NetworkUtils::enableNetworkInterfaceAlarm(NetworkParams& aOptions)
{
NU_DBG("enableNetworkInterfaceAlarm: %s", GET_CHAR(mIfname));
runChain(aOptions, sNetworkInterfaceEnableAlarmChain, networkInterfaceAlarmFail);
return CommandResult::Pending();
}
CommandResult NetworkUtils::disableNetworkInterfaceAlarm(NetworkParams& aOptions)
{
NU_DBG("disableNetworkInterfaceAlarms: %s", GET_CHAR(mIfname));
runChain(aOptions, sNetworkInterfaceDisableAlarmChain, networkInterfaceAlarmFail);
return CommandResult::Pending();
}
CommandResult NetworkUtils::setTetheringAlarm(NetworkParams& aOptions)
{
NU_DBG("setTetheringAlarm");
runChain(aOptions, sTetheringInterfaceSetAlarmChain, networkInterfaceAlarmFail);
return CommandResult::Pending();
}
CommandResult NetworkUtils::removeTetheringAlarm(NetworkParams& aOptions)
{
NU_DBG("removeTetheringAlarm");
runChain(aOptions, sTetheringInterfaceRemoveAlarmChain, networkInterfaceAlarmFail);
return CommandResult::Pending();
}
CommandResult NetworkUtils::getTetheringStatus(NetworkParams& aOptions)
{
NU_DBG("getTetheringStatus");
runChain(aOptions, sTetheringGetStatusChain, networkInterfaceAlarmFail);
return CommandResult::Pending();
}
/**
* handling main thread's reload Wifi firmware request
*/
CommandResult NetworkUtils::setWifiOperationMode(NetworkParams& aOptions)
{
NU_DBG("setWifiOperationMode: %s %s", GET_CHAR(mIfname), GET_CHAR(mMode));
runChain(aOptions, sWifiOperationModeChain, wifiOperationModeFail);
return CommandResult::Pending();
}
/**
* handling main thread's enable/disable WiFi Tethering request
*/
CommandResult NetworkUtils::setWifiTethering(NetworkParams& aOptions)
{
bool enable = aOptions.mEnable;
IFProperties interfaceProperties;
getIFProperties(GET_CHAR(mExternalIfname), interfaceProperties);
if (strcmp(interfaceProperties.dns1, "")) {
int type = getIpType(interfaceProperties.dns1);
if (type != AF_INET6) {
aOptions.mDns1 = NS_ConvertUTF8toUTF16(interfaceProperties.dns1);
}
}
if (strcmp(interfaceProperties.dns2, "")) {
int type = getIpType(interfaceProperties.dns2);
if (type != AF_INET6) {
aOptions.mDns2 = NS_ConvertUTF8toUTF16(interfaceProperties.dns2);
}
}
dumpParams(aOptions, "WIFI");
if (SDK_VERSION >= 20) {
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(aOptions.mExternalIfname, &netIdInfo)) {
ERROR("No such interface: %s", GET_CHAR(mExternalIfname));
return -1;
}
aOptions.mNetId = netIdInfo.mNetId;
}
if (enable) {
NU_DBG("Starting Wifi Tethering on %s <-> %s",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
runChain(aOptions, sWifiEnableChain, wifiTetheringFail);
} else {
NU_DBG("Stopping Wifi Tethering on %s <-> %s",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
runChain(aOptions, sWifiDisableChain, wifiTetheringFail);
}
return CommandResult::Pending();
}
CommandResult NetworkUtils::setUSBTethering(NetworkParams& aOptions)
{
bool enable = aOptions.mEnable;
IFProperties interfaceProperties;
getIFProperties(GET_CHAR(mExternalIfname), interfaceProperties);
if (strcmp(interfaceProperties.dns1, "")) {
int type = getIpType(interfaceProperties.dns1);
if (type != AF_INET6) {
aOptions.mDns1 = NS_ConvertUTF8toUTF16(interfaceProperties.dns1);
}
}
if (strcmp(interfaceProperties.dns2, "")) {
int type = getIpType(interfaceProperties.dns2);
if (type != AF_INET6) {
aOptions.mDns2 = NS_ConvertUTF8toUTF16(interfaceProperties.dns2);
}
}
dumpParams(aOptions, "USB");
if (SDK_VERSION >= 20) {
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.lookup(aOptions.mExternalIfname, &netIdInfo)) {
ERROR("No such interface: %s", GET_CHAR(mExternalIfname));
return -1;
}
aOptions.mNetId = netIdInfo.mNetId;
}
if (enable) {
NU_DBG("Starting USB Tethering on %s <-> %s",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
runChain(aOptions, sUSBEnableChain, usbTetheringFail);
} else {
NU_DBG("Stopping USB Tethering on %s <-> %s",
GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
runChain(aOptions, sUSBDisableChain, usbTetheringFail);
}
return CommandResult::Pending();
}
void NetworkUtils::escapeQuote(nsCString& aString)
{
aString.ReplaceSubstring("\\", "\\\\");
aString.ReplaceSubstring("\"", "\\\"");
}
CommandResult NetworkUtils::checkUsbRndisState(NetworkParams& aOptions)
{
static uint32_t retry = 0;
char currentState[Property::VALUE_MAX_LENGTH];
Property::Get(SYS_USB_STATE_PROPERTY, currentState, nullptr);
nsTArray<nsCString> stateFuncs;
split(currentState, USB_CONFIG_DELIMIT, stateFuncs);
bool rndisPresent = stateFuncs.Contains(nsCString(USB_FUNCTION_RNDIS));
if (aOptions.mEnable == rndisPresent) {
NetworkResultOptions result;
result.mEnable = aOptions.mEnable;
result.mResult = true;
retry = 0;
return result;
}
if (retry < USB_FUNCTION_RETRY_TIMES) {
retry++;
usleep(USB_FUNCTION_RETRY_INTERVAL * 1000);
return checkUsbRndisState(aOptions);
}
NetworkResultOptions result;
result.mResult = false;
retry = 0;
return result;
}
/**
* Modify usb function's property to turn on USB RNDIS function
*/
CommandResult NetworkUtils::enableUsbRndis(NetworkParams& aOptions)
{
bool report = aOptions.mReport;
// For some reason, rndis doesn't play well with diag,modem,nmea.
// So when turning rndis on, we set sys.usb.config to either "rndis"
// or "rndis,adb". When turning rndis off, we go back to
// persist.sys.usb.config.
//
// On the otoro/unagi, persist.sys.usb.config should be one of:
//
// diag,modem,nmea,mass_storage
// diag,modem,nmea,mass_storage,adb
//
// When rndis is enabled, sys.usb.config should be one of:
//
// rdnis
// rndis,adb
//
// and when rndis is disabled, it should revert to persist.sys.usb.config
char currentConfig[Property::VALUE_MAX_LENGTH];
Property::Get(SYS_USB_CONFIG_PROPERTY, currentConfig, nullptr);
nsTArray<nsCString> configFuncs;
split(currentConfig, USB_CONFIG_DELIMIT, configFuncs);
char persistConfig[Property::VALUE_MAX_LENGTH];
Property::Get(PERSIST_SYS_USB_CONFIG_PROPERTY, persistConfig, nullptr);
nsTArray<nsCString> persistFuncs;
split(persistConfig, USB_CONFIG_DELIMIT, persistFuncs);
if (aOptions.mEnable) {
configFuncs.Clear();
configFuncs.AppendElement(nsCString(USB_FUNCTION_RNDIS));
if (persistFuncs.Contains(nsCString(USB_FUNCTION_ADB))) {
configFuncs.AppendElement(nsCString(USB_FUNCTION_ADB));
}
} else {
// We're turning rndis off, revert back to the persist setting.
// adb will already be correct there, so we don't need to do any
// further adjustments.
configFuncs = persistFuncs;
}
char newConfig[Property::VALUE_MAX_LENGTH] = "";
Property::Get(SYS_USB_CONFIG_PROPERTY, currentConfig, nullptr);
join(configFuncs, USB_CONFIG_DELIMIT, Property::VALUE_MAX_LENGTH, newConfig);
if (strcmp(currentConfig, newConfig)) {
Property::Set(SYS_USB_CONFIG_PROPERTY, newConfig);
}
// Trigger the timer to check usb state and report the result to NetworkManager.
if (report) {
usleep(USB_FUNCTION_RETRY_INTERVAL * 1000);
return checkUsbRndisState(aOptions);
}
return SUCCESS;
}
/**
* handling upstream interface change event.
*/
CommandResult NetworkUtils::updateUpStream(NetworkParams& aOptions)
{
runChain(aOptions, sUpdateUpStreamChain, updateUpStreamFail);
return CommandResult::Pending();
}
/**
* handling upstream interface change event.
*/
CommandResult NetworkUtils::createNetwork(NetworkParams& aOptions)
{
if (SDK_VERSION < 20) {
return SUCCESS;
}
static CommandFunc COMMAND_CHAIN[] = {
createNetwork,
enableIpv6,
addInterfaceToNetwork,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
mNetIdManager.acquire(GET_FIELD(mIfname), &netIdInfo);
if (netIdInfo.mRefCnt > 1) {
// Already created. Just return.
NU_DBG("Interface %s (%d) has been created.", GET_CHAR(mIfname),
netIdInfo.mNetId);
return SUCCESS;
}
NU_DBG("Request netd to create a network with netid %d", netIdInfo.mNetId);
// Newly created netid. Ask netd to create network.
aOptions.mNetId = netIdInfo.mNetId;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
/**
* handling upstream interface change event.
*/
CommandResult NetworkUtils::destroyNetwork(NetworkParams& aOptions)
{
if (SDK_VERSION < 20) {
return SUCCESS;
}
static CommandFunc COMMAND_CHAIN[] = {
disableIpv6,
destroyNetwork,
defaultAsyncSuccessHandler,
};
NetIdManager::NetIdInfo netIdInfo;
if (!mNetIdManager.release(GET_FIELD(mIfname), &netIdInfo)) {
ERROR("No existing netid for %s", GET_CHAR(mIfname));
return -1;
}
if (netIdInfo.mRefCnt > 0) {
// Still be referenced. Just return.
NU_DBG("Someone is still using this interface.");
return SUCCESS;
}
NU_DBG("Interface %s (%d) is no longer used. Tell netd to destroy.",
GET_CHAR(mIfname), netIdInfo.mNetId);
aOptions.mNetId = netIdInfo.mNetId;
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
/**
* Query the netId associated with the given network interface name.
*/
CommandResult NetworkUtils::getNetId(NetworkParams& aOptions)
{
NetworkResultOptions result;
if (SDK_VERSION < 20) {
// For pre-Lollipop, use the interface name as the fallback.
result.mNetId = GET_FIELD(mIfname);
return result;
}
NetIdManager::NetIdInfo netIdInfo;
if (-1 == mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
return ESRCH;
}
result.mNetId.AppendInt(netIdInfo.mNetId, 10);
return result;
}
/**
* Get existing network interfaces.
*/
CommandResult NetworkUtils::getInterfaces(NetworkParams& aOptions)
{
runChain(aOptions, sGetInterfacesChain, getInterfacesFail);
return CommandResult::Pending();
}
/**
* Get network config of a specified interface.
*/
CommandResult NetworkUtils::getInterfaceConfig(NetworkParams& aOptions)
{
runChain(aOptions, sGetInterfaceConfigChain, getInterfaceConfigFail);
return CommandResult::Pending();
}
/**
* Set network config for a specified interface.
*/
CommandResult NetworkUtils::setInterfaceConfig(NetworkParams& aOptions)
{
runChain(aOptions, sSetInterfaceConfigChain, setInterfaceConfigFail);
return CommandResult::Pending();
}
CommandResult NetworkUtils::setMtu(NetworkParams& aOptions)
{
// Setting/getting mtu is supported since Kitkat.
if (SDK_VERSION < 19) {
ERROR("setMtu is not supported in current SDK_VERSION.");
return -1;
}
static CommandFunc COMMAND_CHAIN[] = {
setMtu,
defaultAsyncSuccessHandler,
};
runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
return CommandResult::Pending();
}
void NetworkUtils::sendBroadcastMessage(uint32_t code, char* reason)
{
NetworkResultOptions result;
switch(code) {
case NETD_COMMAND_INTERFACE_CHANGE:
result.mTopic = NS_ConvertUTF8toUTF16("netd-interface-change");
break;
case NETD_COMMAND_BANDWIDTH_CONTROLLER:
result.mTopic = NS_ConvertUTF8toUTF16("netd-bandwidth-control");
break;
default:
return;
}
result.mBroadcast = true;
result.mReason = NS_ConvertUTF8toUTF16(reason);
postMessage(result);
}
inline uint32_t NetworkUtils::netdResponseType(uint32_t code)
{
return (code / 100) * 100;
}
inline bool NetworkUtils::isBroadcastMessage(uint32_t code)
{
uint32_t type = netdResponseType(code);
return type == NETD_COMMAND_UNSOLICITED;
}
inline bool NetworkUtils::isError(uint32_t code)
{
uint32_t type = netdResponseType(code);
return type != NETD_COMMAND_PROCEEDING && type != NETD_COMMAND_OKAY;
}
inline bool NetworkUtils::isComplete(uint32_t code)
{
uint32_t type = netdResponseType(code);
return type != NETD_COMMAND_PROCEEDING;
}
inline bool NetworkUtils::isProceeding(uint32_t code)
{
uint32_t type = netdResponseType(code);
return type == NETD_COMMAND_PROCEEDING;
}
void NetworkUtils::dumpParams(NetworkParams& aOptions, const char* aType)
{
#ifdef _DEBUG
NU_DBG("Dump params:");
NU_DBG(" ifname: %s", GET_CHAR(mIfname));
NU_DBG(" ip: %s", GET_CHAR(mIp));
NU_DBG(" link: %s", GET_CHAR(mLink));
NU_DBG(" prefix: %s", GET_CHAR(mPrefix));
NU_DBG(" wifiStartIp: %s", GET_CHAR(mWifiStartIp));
NU_DBG(" wifiEndIp: %s", GET_CHAR(mWifiEndIp));
NU_DBG(" usbStartIp: %s", GET_CHAR(mUsbStartIp));
NU_DBG(" usbEndIp: %s", GET_CHAR(mUsbEndIp));
NU_DBG(" dnsserver1: %s", GET_CHAR(mDns1));
NU_DBG(" dnsserver2: %s", GET_CHAR(mDns2));
NU_DBG(" internalIfname: %s", GET_CHAR(mInternalIfname));
NU_DBG(" externalIfname: %s", GET_CHAR(mExternalIfname));
if (!strcmp(aType, "WIFI")) {
NU_DBG(" wifictrlinterfacename: %s", GET_CHAR(mWifictrlinterfacename));
NU_DBG(" ssid: %s", GET_CHAR(mSsid));
NU_DBG(" security: %s", GET_CHAR(mSecurity));
NU_DBG(" key: %s", GET_CHAR(mKey));
}
#endif
}
#undef GET_CHAR
#undef GET_FIELD
|