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

package com.android.server.wifi.aware;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.wifi.V1_0.NanDataPathChannelCfg;
import android.hardware.wifi.V1_0.NanStatusType;
import android.hardware.wifi.V1_2.NanDataPathChannelInfo;
import android.net.ConnectivityManager;
import android.net.IpPrefix;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.MacAddress;
import android.net.MatchAllNetworkSpecifier;
import android.net.NetworkAgent;
import android.net.NetworkCapabilities;
import android.net.NetworkFactory;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.RouteInfo;
import android.net.wifi.aware.TlvBufferUtils;
import android.net.wifi.aware.WifiAwareAgentNetworkSpecifier;
import android.net.wifi.aware.WifiAwareManager;
import android.net.wifi.aware.WifiAwareNetworkInfo;
import android.net.wifi.aware.WifiAwareNetworkSpecifier;
import android.net.wifi.aware.WifiAwareUtils;
import android.os.Build;
import android.os.IBinder;
import android.os.INetworkManagementService;
import android.os.Looper;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Pair;

import com.android.internal.annotations.VisibleForTesting;
import com.android.server.wifi.util.WifiPermissionsUtil;
import com.android.server.wifi.util.WifiPermissionsWrapper;

import libcore.util.HexEncoding;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Manages Aware data-path lifetime: interface creation/deletion, data-path setup and tear-down.
 * The Aware network configuration is:
 * - transport = TRANSPORT_WIFI_AWARE
 * - capabilities = NET_CAPABILITY_NOT_VPN
 * - network specifier generated by DiscoverySession.createNetworkSpecifier(...) or
 *   WifiAwareManager.createNetworkSpecifier(...).
 */
public class WifiAwareDataPathStateManager {
    private static final String TAG = "WifiAwareDataPathStMgr";
    private static final boolean VDBG = false; // STOPSHIP if true
    /* package */ boolean mDbg = false;

    private static final String AWARE_INTERFACE_PREFIX = "aware_data";
    private static final String NETWORK_TAG = "WIFI_AWARE_FACTORY";
    private static final String AGENT_TAG_PREFIX = "WIFI_AWARE_AGENT_";
    private static final int NETWORK_FACTORY_SCORE_AVAIL = 1;
    private static final int NETWORK_FACTORY_BANDWIDTH_AVAIL = 1;
    private static final int NETWORK_FACTORY_SIGNAL_STRENGTH_AVAIL = 1;

    private final WifiAwareStateManager mMgr;
    public NetworkInterfaceWrapper mNiWrapper = new NetworkInterfaceWrapper();
    private static final NetworkCapabilities sNetworkCapabilitiesFilter = new NetworkCapabilities();
    private final Set<String> mInterfaces = new HashSet<>();
    private final Map<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>
            mNetworkRequestsCache = new ArrayMap<>();
    private Context mContext;
    private WifiAwareMetrics mAwareMetrics;
    private WifiPermissionsUtil mWifiPermissionsUtil;
    private WifiPermissionsWrapper mPermissionsWrapper;
    private Looper mLooper;
    private WifiAwareNetworkFactory mNetworkFactory;
    public INetworkManagementService mNwService;

    // internal debug flag to override API check
    /* package */ boolean mAllowNdpResponderFromAnyOverride = false;

    public WifiAwareDataPathStateManager(WifiAwareStateManager mgr) {
        mMgr = mgr;
    }

    /**
     * Initialize the Aware data-path state manager. Specifically register the network factory with
     * connectivity service.
     */
    public void start(Context context, Looper looper, WifiAwareMetrics awareMetrics,
            WifiPermissionsUtil wifiPermissionsUtil, WifiPermissionsWrapper permissionsWrapper) {
        if (VDBG) Log.v(TAG, "start");

        mContext = context;
        mAwareMetrics = awareMetrics;
        mWifiPermissionsUtil = wifiPermissionsUtil;
        mPermissionsWrapper = permissionsWrapper;
        mLooper = looper;

        sNetworkCapabilitiesFilter.clearAll();
        sNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE);
        sNetworkCapabilitiesFilter
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
        sNetworkCapabilitiesFilter.setNetworkSpecifier(new MatchAllNetworkSpecifier());
        sNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(NETWORK_FACTORY_BANDWIDTH_AVAIL);
        sNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(NETWORK_FACTORY_BANDWIDTH_AVAIL);
        sNetworkCapabilitiesFilter.setSignalStrength(NETWORK_FACTORY_SIGNAL_STRENGTH_AVAIL);

        mNetworkFactory = new WifiAwareNetworkFactory(looper, context, sNetworkCapabilitiesFilter);
        mNetworkFactory.setScoreFilter(NETWORK_FACTORY_SCORE_AVAIL);
        mNetworkFactory.register();

        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
        mNwService = INetworkManagementService.Stub.asInterface(b);
    }

    private Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>
                getNetworkRequestByNdpId(int ndpId) {
        for (Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> entry :
                mNetworkRequestsCache.entrySet()) {
            if (entry.getValue().ndpId == ndpId) {
                return entry;
            }
        }

        return null;
    }

    private Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>
                getNetworkRequestByCanonicalDescriptor(CanonicalConnectionInfo cci) {
        if (VDBG) Log.v(TAG, "getNetworkRequestByCanonicalDescriptor: cci=" + cci);
        for (Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> entry :
                mNetworkRequestsCache.entrySet()) {
            if (VDBG) {
                Log.v(TAG, "getNetworkRequestByCanonicalDescriptor: entry=" + entry.getValue()
                        + " --> cci=" + entry.getValue().getCanonicalDescriptor());
            }
            if (entry.getValue().getCanonicalDescriptor().matches(cci)) {
                return entry;
            }
        }

        return null;
    }

    /**
     * Create all Aware data-path interfaces which are possible on the device - based on the
     * capabilities of the firmware.
     */
    public void createAllInterfaces() {
        if (VDBG) Log.v(TAG, "createAllInterfaces");

        if (mMgr.getCapabilities() == null) {
            Log.e(TAG, "createAllInterfaces: capabilities aren't initialized yet!");
            return;
        }

        for (int i = 0; i < mMgr.getCapabilities().maxNdiInterfaces; ++i) {
            String name = AWARE_INTERFACE_PREFIX + i;
            if (mInterfaces.contains(name)) {
                Log.e(TAG, "createAllInterfaces(): interface already up, " + name
                        + ", possibly failed to delete - deleting/creating again to be safe");
                mMgr.deleteDataPathInterface(name);

                // critical to remove so that don't get infinite loop if the delete fails again
                mInterfaces.remove(name);
            }

            mMgr.createDataPathInterface(name);
        }
    }

    /**
     * Delete all Aware data-path interfaces which are currently up.
     */
    public void deleteAllInterfaces() {
        if (VDBG) Log.v(TAG, "deleteAllInterfaces");
        onAwareDownCleanupDataPaths();

        if (mMgr.getCapabilities() == null) {
            Log.e(TAG, "deleteAllInterfaces: capabilities aren't initialized yet!");
            return;
        }

        for (int i = 0; i < mMgr.getCapabilities().maxNdiInterfaces; ++i) {
            String name = AWARE_INTERFACE_PREFIX + i;
            mMgr.deleteDataPathInterface(name);
        }
        mMgr.releaseAwareInterface();
    }

    /**
     * Called when firmware indicates the an interface was created.
     */
    public void onInterfaceCreated(String interfaceName) {
        if (VDBG) Log.v(TAG, "onInterfaceCreated: interfaceName=" + interfaceName);

        if (mInterfaces.contains(interfaceName)) {
            Log.w(TAG, "onInterfaceCreated: already contains interface -- " + interfaceName);
        }

        mInterfaces.add(interfaceName);
    }

    /**
     * Called when firmware indicates the an interface was deleted.
     */
    public void onInterfaceDeleted(String interfaceName) {
        if (VDBG) Log.v(TAG, "onInterfaceDeleted: interfaceName=" + interfaceName);

        if (!mInterfaces.contains(interfaceName)) {
            Log.w(TAG, "onInterfaceDeleted: interface not on list -- " + interfaceName);
        }

        mInterfaces.remove(interfaceName);
    }

    /**
     * Response to initiating data-path request. Indicates that request is successful (not
     * complete!) and is now in progress.
     *
     * @param networkSpecifier The network specifier provided as part of the initiate request.
     * @param ndpId            The ID assigned to the data-path.
     */
    public void onDataPathInitiateSuccess(WifiAwareNetworkSpecifier networkSpecifier, int ndpId) {
        if (VDBG) {
            Log.v(TAG,
                    "onDataPathInitiateSuccess: networkSpecifier=" + networkSpecifier + ", ndpId="
                            + ndpId);
        }

        AwareNetworkRequestInformation nnri = mNetworkRequestsCache.get(networkSpecifier);
        if (nnri == null) {
            Log.w(TAG, "onDataPathInitiateSuccess: network request not found for networkSpecifier="
                    + networkSpecifier);
            mMgr.endDataPath(ndpId);
            return;
        }

        if (nnri.state
                != AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE) {
            Log.w(TAG, "onDataPathInitiateSuccess: network request in incorrect state: state="
                    + nnri.state);
            mNetworkRequestsCache.remove(networkSpecifier);
            mMgr.endDataPath(ndpId);
            return;
        }

        nnri.state = AwareNetworkRequestInformation.STATE_WAIT_FOR_CONFIRM;
        nnri.ndpId = ndpId;
    }

    /**
     * Response to an attempt to set up a data-path (on the initiator side).
     *
     * @param networkSpecifier The network specifier provided as part of the initiate request.
     * @param reason           Failure reason.
     */
    public void onDataPathInitiateFail(WifiAwareNetworkSpecifier networkSpecifier, int reason) {
        if (VDBG) {
            Log.v(TAG,
                    "onDataPathInitiateFail: networkSpecifier=" + networkSpecifier + ", reason="
                            + reason);
        }

        AwareNetworkRequestInformation nnri = mNetworkRequestsCache.remove(networkSpecifier);
        if (nnri == null) {
            Log.w(TAG, "onDataPathInitiateFail: network request not found for networkSpecifier="
                    + networkSpecifier);
            return;
        }

        if (nnri.state
                != AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE) {
            Log.w(TAG, "onDataPathInitiateFail: network request in incorrect state: state="
                    + nnri.state);
        }

        mAwareMetrics.recordNdpStatus(reason, networkSpecifier.isOutOfBand(), nnri.startTimestamp);
    }


    /**
     * Notification (unsolicited/asynchronous) that a peer has requested to set up a data-path
     * connection with us.
     *
     * @param pubSubId      The ID of the discovery session context for the data-path - or 0 if not
     *                      related to a discovery session.
     * @param mac           The discovery MAC address of the peer.
     * @param ndpId         The locally assigned ID for the data-path.
     * @param message       The app_info HAL field (peer's info: binary blob)
     * @return The network specifier of the data-path (or null if none/error)
     */
    public WifiAwareNetworkSpecifier onDataPathRequest(int pubSubId, byte[] mac, int ndpId,
            byte[] message) {
        if (VDBG) {
            Log.v(TAG,
                    "onDataPathRequest: pubSubId=" + pubSubId + ", mac=" + String.valueOf(
                            HexEncoding.encode(mac)) + ", ndpId=" + ndpId);
        }

        WifiAwareNetworkSpecifier networkSpecifier = null;
        AwareNetworkRequestInformation nnri = null;
        for (Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> entry :
                mNetworkRequestsCache.entrySet()) {
            /*
             * Checking that the incoming request (from the Initiator) matches the request
             * we (the Responder) already have set up. The rules are:
             * - The discovery session (pub/sub ID) must match.
             * - The peer MAC address (if specified - i.e. non-null) must match. A null peer MAC ==
             *   accept (otherwise matching) requests from any peer MAC.
             * - The request must be pending (i.e. we could have completed requests for the same
             *   parameters)
             */
            if (entry.getValue().pubSubId != 0 && entry.getValue().pubSubId != pubSubId) {
                continue;
            }

            if (entry.getValue().peerDiscoveryMac != null && !Arrays.equals(
                    entry.getValue().peerDiscoveryMac, mac)) {
                continue;
            }

            if (entry.getValue().state
                    != AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_REQUEST) {
                continue;
            }

            networkSpecifier = entry.getKey();
            nnri = entry.getValue();
            break;
        }

        // it is also possible that this is an initiator-side data-path request indication (which
        // happens when the Responder responds). In such a case it will be matched by the NDP ID.
        Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> nnriE =
                getNetworkRequestByNdpId(ndpId);
        if (nnriE != null) {
            if (VDBG) {
                Log.v(TAG,
                        "onDataPathRequest: initiator-side indication for " + nnriE.getValue());
            }

            // potential transmission mechanism for port/transport-protocol information from
            // Responder (alternative to confirm message)
            NetworkInformationData.ParsedResults peerServerInfo = NetworkInformationData.parseTlv(
                    message);
            if (peerServerInfo != null) {
                nnriE.getValue().peerPort = peerServerInfo.port;
                nnriE.getValue().peerTransportProtocol = peerServerInfo.transportProtocol;
            }

            return null; // ignore this for NDP set up flow: it is used to obtain app_info from Resp
        }

        if (nnri == null) {
            Log.w(TAG, "onDataPathRequest: can't find a request with specified pubSubId=" + pubSubId
                    + ", mac=" + String.valueOf(HexEncoding.encode(mac)));
            if (VDBG) {
                Log.v(TAG, "onDataPathRequest: network request cache = " + mNetworkRequestsCache);
            }
            mMgr.respondToDataPathRequest(false, ndpId, "", null, null, null, false);
            return null;
        }

        if (nnri.peerDiscoveryMac == null) {
            // the "accept anyone" request is now specific
            nnri.peerDiscoveryMac = mac;
        }
        nnri.interfaceName = selectInterfaceForRequest(nnri);
        if (nnri.interfaceName == null) {
            Log.w(TAG,
                    "onDataPathRequest: request " + networkSpecifier + " no interface available");
            mMgr.respondToDataPathRequest(false, ndpId, "", null, null, null, false);
            mNetworkRequestsCache.remove(networkSpecifier);
            return null;
        }

        nnri.state = AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_RESPOND_RESPONSE;
        nnri.ndpId = ndpId;
        nnri.startTimestamp = SystemClock.elapsedRealtime();
        mMgr.respondToDataPathRequest(true, ndpId, nnri.interfaceName, nnri.networkSpecifier.pmk,
                nnri.networkSpecifier.passphrase,
                NetworkInformationData.buildTlv(nnri.networkSpecifier.port,
                        nnri.networkSpecifier.transportProtocol),
                nnri.networkSpecifier.isOutOfBand());

        return networkSpecifier;
    }

    /**
     * Called on the RESPONDER when the response to data-path request has been completed.
     *
     * @param ndpId The ID of the data-path (NDP)
     * @param success Whether or not the 'RespondToDataPathRequest' operation was a success.
     */
    public void onRespondToDataPathRequest(int ndpId, boolean success, int reasonOnFailure) {
        if (VDBG) {
            Log.v(TAG, "onRespondToDataPathRequest: ndpId=" + ndpId + ", success=" + success);
        }

        WifiAwareNetworkSpecifier networkSpecifier = null;
        AwareNetworkRequestInformation nnri = null;
        for (Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> entry :
                mNetworkRequestsCache.entrySet()) {
            if (entry.getValue().ndpId == ndpId) {
                networkSpecifier = entry.getKey();
                nnri = entry.getValue();
                break;
            }
        }

        if (nnri == null) {
            Log.w(TAG, "onRespondToDataPathRequest: can't find a request with specified ndpId="
                    + ndpId);
            if (VDBG) {
                Log.v(TAG, "onRespondToDataPathRequest: network request cache = "
                        + mNetworkRequestsCache);
            }
            return;
        }

        if (!success) {
            Log.w(TAG, "onRespondToDataPathRequest: request " + networkSpecifier
                    + " failed responding");
            mMgr.endDataPath(ndpId);
            mNetworkRequestsCache.remove(networkSpecifier);
            mAwareMetrics.recordNdpStatus(reasonOnFailure, networkSpecifier.isOutOfBand(),
                    nnri.startTimestamp);
            return;
        }

        if (nnri.state
                != AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_RESPOND_RESPONSE) {
            Log.w(TAG, "onRespondToDataPathRequest: request " + networkSpecifier
                    + " is incorrect state=" + nnri.state);
            mMgr.endDataPath(ndpId);
            mNetworkRequestsCache.remove(networkSpecifier);
            return;
        }

        nnri.state = AwareNetworkRequestInformation.STATE_WAIT_FOR_CONFIRM;
    }

    /**
     * Notification (unsolicited/asynchronous) that the data-path (which we've been setting up)
     * is possibly (if {@code accept} is {@code true}) ready for use from the firmware's
     * perspective - now can do L3 configuration.
     *
     * @param ndpId         Id of the data-path
     * @param mac           The MAC address of the peer's data-path (not discovery interface). Only
     *                      valid
     *                      if {@code accept} is {@code true}.
     * @param accept        Indicates whether the data-path setup has succeeded (been accepted) or
     *                      failed (been rejected).
     * @param reason        If {@code accept} is {@code false} provides a reason code for the
     *                      rejection/failure.
     * @param message       The message provided by the peer as part of the data-path setup
     *                      process.
     * @param channelInfo   Lists of channels used for this NDP.
     * @return The network specifier of the data-path or a null if none/error.
     */
    public WifiAwareNetworkSpecifier onDataPathConfirm(int ndpId, byte[] mac, boolean accept,
            int reason, byte[] message, List<NanDataPathChannelInfo> channelInfo) {
        if (VDBG) {
            Log.v(TAG, "onDataPathConfirm: ndpId=" + ndpId + ", mac=" + String.valueOf(
                    HexEncoding.encode(mac)) + ", accept=" + accept + ", reason=" + reason
                    + ", message.length=" + ((message == null) ? 0 : message.length)
                    + ", channelInfo=" + channelInfo);
        }

        Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> nnriE =
                getNetworkRequestByNdpId(ndpId);
        if (nnriE == null) {
            Log.w(TAG, "onDataPathConfirm: network request not found for ndpId=" + ndpId);
            if (accept) {
                mMgr.endDataPath(ndpId);
            }
            return null;
        }

        WifiAwareNetworkSpecifier networkSpecifier = nnriE.getKey();
        AwareNetworkRequestInformation nnri = nnriE.getValue();

        // validate state
        if (nnri.state != AwareNetworkRequestInformation.STATE_WAIT_FOR_CONFIRM) {
            Log.w(TAG, "onDataPathConfirm: invalid state=" + nnri.state);
            mNetworkRequestsCache.remove(networkSpecifier);
            if (accept) {
                mMgr.endDataPath(ndpId);
            }
            return networkSpecifier;
        }

        if (accept) {
            nnri.state = AwareNetworkRequestInformation.STATE_CONFIRMED;
            nnri.peerDataMac = mac;
            nnri.channelInfo = channelInfo;

            NetworkInfo networkInfo = new NetworkInfo(ConnectivityManager.TYPE_NONE, 0,
                    NETWORK_TAG, "");
            NetworkCapabilities networkCapabilities = new NetworkCapabilities(
                    sNetworkCapabilitiesFilter);
            LinkProperties linkProperties = new LinkProperties();

            boolean interfaceUsedByAnotherNdp = isInterfaceUpAndUsedByAnotherNdp(nnri);
            if (!interfaceUsedByAnotherNdp) {
                try {
                    mNwService.setInterfaceUp(nnri.interfaceName);
                    mNwService.enableIpv6(nnri.interfaceName);
                } catch (Exception e) { // NwService throws runtime exceptions for errors
                    Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri
                            + ": can't configure network - "
                            + e);
                    mMgr.endDataPath(ndpId);
                    nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                    return networkSpecifier;
                }
            } else {
                if (VDBG) {
                    Log.v(TAG, "onDataPathConfirm: interface already configured: "
                            + nnri.interfaceName);
                }
            }

            try {
                nnri.peerIpv6 = Inet6Address.getByAddress(null,
                        MacAddress.fromBytes(mac).getLinkLocalIpv6FromEui48Mac().getAddress(),
                        NetworkInterface.getByName(nnri.interfaceName));
            } catch (SocketException | UnknownHostException e) {
                Log.e(TAG, "onDataPathConfirm: error obtaining scoped IPv6 address -- " + e);
                nnri.peerIpv6 = null;
            }
            // only relevant for the initiator
            if (nnri.networkSpecifier.role
                    == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR) {
                NetworkInformationData.ParsedResults peerServerInfo =
                        NetworkInformationData.parseTlv(message);
                if (peerServerInfo != null) {
                    nnri.peerPort = peerServerInfo.port;
                    nnri.peerTransportProtocol = peerServerInfo.transportProtocol;
                }
            }

            if (nnri.peerIpv6 != null) {
                networkCapabilities.setTransportInfo(
                        new WifiAwareNetworkInfo(nnri.peerIpv6, nnri.peerPort,
                                nnri.peerTransportProtocol));
            }
            if (VDBG) {
                Log.v(TAG, "onDataPathConfirm: AwareNetworkInfo="
                        + networkCapabilities.getTransportInfo());
            }

            if (!mNiWrapper.configureAgentProperties(nnri, nnri.equivalentSpecifiers, ndpId,
                    networkInfo, networkCapabilities, linkProperties)) {
                return networkSpecifier;
            }

            nnri.networkAgent = new WifiAwareNetworkAgent(mLooper, mContext,
                    AGENT_TAG_PREFIX + nnri.ndpId,
                    new NetworkInfo(ConnectivityManager.TYPE_NONE, 0, NETWORK_TAG, ""),
                    networkCapabilities, linkProperties, NETWORK_FACTORY_SCORE_AVAIL,
                    nnri);
            nnri.networkAgent.sendNetworkInfo(networkInfo);

            mAwareMetrics.recordNdpStatus(NanStatusType.SUCCESS, networkSpecifier.isOutOfBand(),
                    nnri.startTimestamp);
            nnri.startTimestamp = SystemClock.elapsedRealtime(); // update time-stamp for duration
            mAwareMetrics.recordNdpCreation(nnri.uid, mNetworkRequestsCache);
        } else {
            if (VDBG) {
                Log.v(TAG, "onDataPathConfirm: data-path for networkSpecifier=" + networkSpecifier
                        + " rejected - reason=" + reason);
            }
            mNetworkRequestsCache.remove(networkSpecifier);
            mAwareMetrics.recordNdpStatus(reason, networkSpecifier.isOutOfBand(),
                    nnri.startTimestamp);
        }

        return networkSpecifier;
    }

    /**
     * Notification (unsolicited/asynchronous) from the firmware that the specified data-path has
     * been terminated.
     *
     * @param ndpId The ID of the terminated data-path.
     */
    public void onDataPathEnd(int ndpId) {
        if (VDBG) Log.v(TAG, "onDataPathEnd: ndpId=" + ndpId);

        Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> nnriE =
                getNetworkRequestByNdpId(ndpId);
        if (nnriE == null) {
            if (VDBG) {
                Log.v(TAG, "onDataPathEnd: network request not found for ndpId=" + ndpId);
            }
            return;
        }

        tearDownInterfaceIfPossible(nnriE.getValue());
        if (nnriE.getValue().state == AwareNetworkRequestInformation.STATE_CONFIRMED
                || nnriE.getValue().state == AwareNetworkRequestInformation.STATE_TERMINATING) {
            mAwareMetrics.recordNdpSessionDuration(nnriE.getValue().startTimestamp);
        }
        mNetworkRequestsCache.remove(nnriE.getKey());

        mNetworkFactory.tickleConnectivityIfWaiting();
    }

    /**
     * Notification (unsolicited/asynchronous) from the firmware that the channel for the specified
     * NDP ids has been updated.
     */
    public void onDataPathSchedUpdate(byte[] peerMac, List<Integer> ndpIds,
            List<NanDataPathChannelInfo> channelInfo) {
        if (VDBG) {
            Log.v(TAG, "onDataPathSchedUpdate: peerMac=" + MacAddress.fromBytes(peerMac).toString()
                    + ", ndpIds=" + ndpIds + ", channelInfo=" + channelInfo);
        }

        for (int ndpId : ndpIds) {
            Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> nnriE =
                    getNetworkRequestByNdpId(ndpId);
            if (nnriE == null) {
                Log.e(TAG, "onDataPathSchedUpdate: ndpId=" + ndpId + " - not found");
                continue;
            }
            if (!Arrays.equals(peerMac, nnriE.getValue().peerDiscoveryMac)) {
                Log.e(TAG, "onDataPathSchedUpdate: ndpId=" + ndpId + ", report NMI="
                        + MacAddress.fromBytes(peerMac).toString() + " doesn't match NDP NMI="
                        + MacAddress.fromBytes(nnriE.getValue().peerDiscoveryMac).toString());
                continue;
            }

            nnriE.getValue().channelInfo = channelInfo;
        }
    }

    /**
     * Called whenever Aware comes down. Clean up all pending and up network requests and agents.
     */
    public void onAwareDownCleanupDataPaths() {
        if (VDBG) Log.v(TAG, "onAwareDownCleanupDataPaths");

        Iterator<Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation>> it =
                mNetworkRequestsCache.entrySet().iterator();
        while (it.hasNext()) {
            tearDownInterfaceIfPossible(it.next().getValue());
            it.remove();
        }
    }

    /**
     * Called when timed-out waiting for confirmation of the data-path setup (i.e.
     * onDataPathConfirm). Started on the initiator when executing the request for the data-path
     * and on the responder when received a request for data-path (in both cases only on success
     * - i.e. when we're proceeding with data-path setup).
     */
    public void handleDataPathTimeout(NetworkSpecifier networkSpecifier) {
        if (mDbg) Log.v(TAG, "handleDataPathTimeout: networkSpecifier=" + networkSpecifier);

        AwareNetworkRequestInformation nnri = mNetworkRequestsCache.remove(networkSpecifier);
        if (nnri == null) {
            if (mDbg) {
                Log.v(TAG,
                        "handleDataPathTimeout: network request not found for networkSpecifier="
                                + networkSpecifier);
            }
            return;
        }
        mAwareMetrics.recordNdpStatus(NanStatusType.INTERNAL_FAILURE,
                nnri.networkSpecifier.isOutOfBand(), nnri.startTimestamp);

        mMgr.endDataPath(nnri.ndpId);
        nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
    }

    private class WifiAwareNetworkFactory extends NetworkFactory {
        // Request received while waiting for confirmation that a canonically identical data-path
        // (NDP) is in the process of being terminated
        private boolean mWaitingForTermination = false;

        WifiAwareNetworkFactory(Looper looper, Context context, NetworkCapabilities filter) {
            super(looper, context, NETWORK_TAG, filter);
        }

        public void tickleConnectivityIfWaiting() {
            if (mWaitingForTermination) {
                if (VDBG) Log.v(TAG, "tickleConnectivityIfWaiting: was waiting!");
                mWaitingForTermination = false;
                reevaluateAllRequests();
            }
        }

        @Override
        public boolean acceptRequest(NetworkRequest request, int score) {
            if (VDBG) {
                Log.v(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request + ", score="
                        + score);
            }

            if (!mMgr.isUsageEnabled()) {
                if (VDBG) {
                    Log.v(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
                            + " -- Aware disabled");
                }
                return false;
            }

            if (mInterfaces.isEmpty()) {
                Log.w(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
                        + " -- No Aware interfaces are up");
                return false;
            }

            NetworkSpecifier networkSpecifierBase =
                    request.networkCapabilities.getNetworkSpecifier();
            if (!(networkSpecifierBase instanceof WifiAwareNetworkSpecifier)) {
                Log.w(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
                        + " - not a WifiAwareNetworkSpecifier");
                return false;
            }

            WifiAwareNetworkSpecifier networkSpecifier =
                    (WifiAwareNetworkSpecifier) networkSpecifierBase;

            // look up specifier - are we being called again?
            AwareNetworkRequestInformation nnri = mNetworkRequestsCache.get(networkSpecifier);
            if (nnri != null) {
                if (VDBG) {
                    Log.v(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
                            + " - already in cache with state=" + nnri.state);
                }

                if (nnri.state == AwareNetworkRequestInformation.STATE_TERMINATING) {
                    mWaitingForTermination = true;
                    return false;
                }

                // seems to happen after a network agent is created - trying to rematch all
                // requests again!?
                return true;
            }

            nnri = AwareNetworkRequestInformation.processNetworkSpecifier(networkSpecifier, mMgr,
                    mWifiPermissionsUtil, mPermissionsWrapper, mAllowNdpResponderFromAnyOverride);
            if (nnri == null) {
                Log.e(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
                        + " - can't parse network specifier");
                return false;
            }

            // check to see if a canonical version exists
            Map.Entry<WifiAwareNetworkSpecifier, AwareNetworkRequestInformation> primaryRequest =
                    getNetworkRequestByCanonicalDescriptor(nnri.getCanonicalDescriptor());
            if (primaryRequest != null) {
                if (VDBG) {
                    Log.v(TAG, "WifiAwareNetworkFactory.acceptRequest: request=" + request
                            + ", already has a primary request=" + primaryRequest.getKey()
                            + " with state=" + primaryRequest.getValue().state);
                }

                if (primaryRequest.getValue().state
                        == AwareNetworkRequestInformation.STATE_TERMINATING) {
                    mWaitingForTermination = true;
                } else {
                    primaryRequest.getValue().updateToSupportNewRequest(networkSpecifier);
                }
                return false;
            }

            mNetworkRequestsCache.put(networkSpecifier, nnri);

            return true;
        }

        @Override
        protected void needNetworkFor(NetworkRequest networkRequest, int score) {
            if (VDBG) {
                Log.v(TAG, "WifiAwareNetworkFactory.needNetworkFor: networkRequest="
                        + networkRequest + ", score=" + score);
            }

            NetworkSpecifier networkSpecifierObj =
                    networkRequest.networkCapabilities.getNetworkSpecifier();
            WifiAwareNetworkSpecifier networkSpecifier = null;
            if (networkSpecifierObj instanceof WifiAwareNetworkSpecifier) {
                networkSpecifier = (WifiAwareNetworkSpecifier) networkSpecifierObj;
            }
            AwareNetworkRequestInformation nnri = mNetworkRequestsCache.get(networkSpecifier);
            if (nnri == null) {
                Log.e(TAG, "WifiAwareNetworkFactory.needNetworkFor: networkRequest="
                        + networkRequest + " not in cache!?");
                return;
            }

            if (nnri.state != AwareNetworkRequestInformation.STATE_IDLE) {
                if (VDBG) {
                    Log.v(TAG, "WifiAwareNetworkFactory.needNetworkFor: networkRequest="
                            + networkRequest + " - already in progress");
                    // TODO: understand how/when can be called again/while in progress (seems
                    // to be related to score re-calculation after a network agent is created)
                }
                return;
            }
            if (nnri.networkSpecifier.role
                    == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR) {
                nnri.interfaceName = selectInterfaceForRequest(nnri);
                if (nnri.interfaceName == null) {
                    Log.w(TAG, "needNetworkFor: request " + networkSpecifier
                            + " no interface available");
                    mNetworkRequestsCache.remove(networkSpecifier);
                    return;
                }

                mMgr.initiateDataPathSetup(networkSpecifier, nnri.peerInstanceId,
                        NanDataPathChannelCfg.CHANNEL_NOT_REQUESTED, selectChannelForRequest(nnri),
                        nnri.peerDiscoveryMac, nnri.interfaceName, nnri.networkSpecifier.pmk,
                        nnri.networkSpecifier.passphrase, nnri.networkSpecifier.isOutOfBand(),
                        null);
                nnri.state =
                        AwareNetworkRequestInformation.STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE;
                nnri.startTimestamp = SystemClock.elapsedRealtime();
            } else {
                nnri.state = AwareNetworkRequestInformation.STATE_RESPONDER_WAIT_FOR_REQUEST;
            }
        }

        @Override
        protected void releaseNetworkFor(NetworkRequest networkRequest) {
            if (VDBG) {
                Log.v(TAG, "WifiAwareNetworkFactory.releaseNetworkFor: networkRequest="
                        + networkRequest);
            }

            NetworkSpecifier networkSpecifierObj =
                    networkRequest.networkCapabilities.getNetworkSpecifier();
            WifiAwareNetworkSpecifier networkSpecifier = null;
            if (networkSpecifierObj instanceof WifiAwareNetworkSpecifier) {
                networkSpecifier = (WifiAwareNetworkSpecifier) networkSpecifierObj;
            }

            AwareNetworkRequestInformation nnri = mNetworkRequestsCache.get(networkSpecifier);
            if (nnri == null) {
                Log.e(TAG, "WifiAwareNetworkFactory.releaseNetworkFor: networkRequest="
                        + networkRequest + " not in cache!?");
                return;
            }

            if (nnri.networkAgent != null) {
                if (VDBG) {
                    Log.v(TAG, "WifiAwareNetworkFactory.releaseNetworkFor: networkRequest="
                            + networkRequest + ", nnri=" + nnri
                            + ": agent already created - deferring ending data-path to agent"
                            + ".unwanted()");
                }
                return;
            }

            /*
             * Since there's no agent it means we're in the process of setting up the NDP.
             * However, it is possible that there were other equivalent requests for this NDP. We
             * should keep going in that case.
             */
            nnri.removeSupportForRequest(networkSpecifier);
            if (nnri.equivalentSpecifiers.isEmpty()) {
                if (VDBG) {
                    Log.v(TAG, "releaseNetworkFor: there are no further requests, networkRequest="
                            + networkRequest);
                }
                if (nnri.ndpId != 0) { // 0 is never a valid ID!
                    if (VDBG) Log.v(TAG, "releaseNetworkFor: in progress NDP being terminated");
                    mMgr.endDataPath(nnri.ndpId);
                    nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                } else {
                    mNetworkRequestsCache.remove(networkSpecifier);
                }
            } else {
                if (VDBG) {
                    Log.v(TAG, "releaseNetworkFor: equivalent requests exist - not terminating "
                            + "networkRequest=" + networkRequest);
                }
            }
        }
    }

    private class WifiAwareNetworkAgent extends NetworkAgent {
        private NetworkInfo mNetworkInfo;
        private AwareNetworkRequestInformation mAwareNetworkRequestInfo;

        WifiAwareNetworkAgent(Looper looper, Context context, String logTag, NetworkInfo ni,
                NetworkCapabilities nc, LinkProperties lp, int score,
                AwareNetworkRequestInformation anri) {
            super(looper, context, logTag, ni, nc, lp, score);

            mNetworkInfo = ni;
            mAwareNetworkRequestInfo = anri;
        }

        @Override
        protected void unwanted() {
            if (VDBG) {
                Log.v(TAG, "WifiAwareNetworkAgent.unwanted: request=" + mAwareNetworkRequestInfo);
            }

            mMgr.endDataPath(mAwareNetworkRequestInfo.ndpId);
            mAwareNetworkRequestInfo.state = AwareNetworkRequestInformation.STATE_TERMINATING;

            // Will get a callback (on both initiator and responder) when data-path actually
            // terminated. At that point will inform the agent and will clear the cache.
        }

        void reconfigureAgentAsDisconnected() {
            if (VDBG) {
                Log.v(TAG, "WifiAwareNetworkAgent.reconfigureAgentAsDisconnected: request="
                        + mAwareNetworkRequestInfo);
            }

            mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, "");
            sendNetworkInfo(mNetworkInfo);
        }
    }

    private void tearDownInterfaceIfPossible(AwareNetworkRequestInformation nnri) {
        if (VDBG) Log.v(TAG, "tearDownInterfaceIfPossible: nnri=" + nnri);

        if (!TextUtils.isEmpty(nnri.interfaceName)) {
            boolean interfaceUsedByAnotherNdp = isInterfaceUpAndUsedByAnotherNdp(nnri);
            if (interfaceUsedByAnotherNdp) {
                if (VDBG) {
                    Log.v(TAG, "tearDownInterfaceIfPossible: interfaceName=" + nnri.interfaceName
                            + ", still in use - not turning down");
                }
            } else {
                try {
                    mNwService.setInterfaceDown(nnri.interfaceName);
                } catch (Exception e) { // NwService throws runtime exceptions for errors
                    Log.e(TAG, "tearDownInterfaceIfPossible: nnri=" + nnri
                            + ": can't bring interface down - " + e);
                }
            }
        }

        if (nnri.networkAgent != null) {
            nnri.networkAgent.reconfigureAgentAsDisconnected();
        }
    }

    private boolean isInterfaceUpAndUsedByAnotherNdp(AwareNetworkRequestInformation nri) {
        for (AwareNetworkRequestInformation lnri : mNetworkRequestsCache.values()) {
            if (lnri == nri) {
                continue;
            }

            if (nri.interfaceName.equals(lnri.interfaceName) && (
                    lnri.state == AwareNetworkRequestInformation.STATE_CONFIRMED
                            || lnri.state == AwareNetworkRequestInformation.STATE_TERMINATING)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Select one of the existing interfaces for the new network request. A request is canonical
     * (otherwise it wouldn't be executed).
     *
     * Construct a list of all interfaces currently used to communicate to the peer. The remaining
     * interfaces are available for use for this request - if none are left then the request should
     * fail (signaled to the caller by returning a null).
     */
    private String selectInterfaceForRequest(AwareNetworkRequestInformation req) {
        SortedSet<String> potential = new TreeSet<>(mInterfaces);
        Set<String> used = new HashSet<>();

        if (VDBG) {
            Log.v(TAG, "selectInterfaceForRequest: req=" + req + ", mNetworkRequestsCache="
                    + mNetworkRequestsCache);
        }

        for (AwareNetworkRequestInformation nnri : mNetworkRequestsCache.values()) {
            if (nnri == req) {
                continue;
            }

            if (Arrays.equals(req.peerDiscoveryMac, nnri.peerDiscoveryMac)) {
                used.add(nnri.interfaceName);
            }
        }

        if (VDBG) {
            Log.v(TAG, "selectInterfaceForRequest: potential=" + potential + ", used=" + used);
        }

        for (String ifName: potential) {
            if (!used.contains(ifName)) {
                return ifName;
            }
        }

        Log.e(TAG, "selectInterfaceForRequest: req=" + req + " - no interfaces available!");
        return null;
    }

    /**
     * Select a channel for the network request.
     *
     * TODO (b/38209409): The value from this function isn't currently used - the channel selection
     * is delegated to the HAL.
     */
    private int selectChannelForRequest(AwareNetworkRequestInformation req) {
        return 2437;
    }

    /**
     * Aware network request. State object: contains network request information/state through its
     * lifetime.
     */
    @VisibleForTesting
    public static class AwareNetworkRequestInformation {
        static final int STATE_IDLE = 100;
        static final int STATE_WAIT_FOR_CONFIRM = 101;
        static final int STATE_CONFIRMED = 102;
        static final int STATE_INITIATOR_WAIT_FOR_REQUEST_RESPONSE = 103;
        static final int STATE_RESPONDER_WAIT_FOR_REQUEST = 104;
        static final int STATE_RESPONDER_WAIT_FOR_RESPOND_RESPONSE = 105;
        static final int STATE_TERMINATING = 106;

        public int state;

        public int uid;
        public String interfaceName;
        public int pubSubId = 0;
        public int peerInstanceId = 0;
        public byte[] peerDiscoveryMac = null;
        public int ndpId = 0; // 0 is never a valid ID!
        public byte[] peerDataMac;
        public Inet6Address peerIpv6;
        public int peerPort = 0; // uninitialized (invalid) value
        public int peerTransportProtocol = -1; // uninitialized (invalid) value
        public WifiAwareNetworkSpecifier networkSpecifier;
        public List<NanDataPathChannelInfo> channelInfo;
        public long startTimestamp = 0; // request is made (initiator) / get request (responder)

        public WifiAwareNetworkAgent networkAgent;

        /* A collection of specifiers which are equivalent to the current request and are
         * supported by it's agent. This list DOES include the original (first) network specifier
         * (which is stored separately above).
         */
        public Set<WifiAwareNetworkSpecifier> equivalentSpecifiers = new HashSet<>();

        void updateToSupportNewRequest(WifiAwareNetworkSpecifier ns) {
            if (VDBG) Log.v(TAG, "updateToSupportNewRequest: ns=" + ns);
            if (equivalentSpecifiers.add(ns) && state == STATE_CONFIRMED) {
                if (networkAgent == null) {
                    Log.wtf(TAG, "updateToSupportNewRequest: null agent in CONFIRMED state!?");
                    return;
                }

                networkAgent.sendNetworkCapabilities(getNetworkCapabilities());
            }
        }

        void removeSupportForRequest(WifiAwareNetworkSpecifier ns) {
            if (VDBG) Log.v(TAG, "removeSupportForRequest: ns=" + ns);
            equivalentSpecifiers.remove(ns);

            // we will not update the agent:
            // 1. this will only get called before the agent is created
            // 2. connectivity service does not allow (WTF) updates with reduced capabilities
        }

        private NetworkCapabilities getNetworkCapabilities() {
            NetworkCapabilities nc = new NetworkCapabilities(sNetworkCapabilitiesFilter);
            nc.setNetworkSpecifier(new WifiAwareAgentNetworkSpecifier(equivalentSpecifiers.toArray(
                    new WifiAwareNetworkSpecifier[equivalentSpecifiers.size()])));
            if (peerIpv6 != null) {
                nc.setTransportInfo(
                        new WifiAwareNetworkInfo(peerIpv6, peerPort, peerTransportProtocol));
            }
            return nc;
        }

        /**
         * Returns a canonical descriptor for the network request.
         */
        CanonicalConnectionInfo getCanonicalDescriptor() {
            return new CanonicalConnectionInfo(peerDiscoveryMac, networkSpecifier.pmk,
                    networkSpecifier.sessionId, networkSpecifier.passphrase);
        }

        static AwareNetworkRequestInformation processNetworkSpecifier(WifiAwareNetworkSpecifier ns,
                WifiAwareStateManager mgr, WifiPermissionsUtil wifiPermissionsUtil,
                WifiPermissionsWrapper permissionWrapper,
                boolean allowNdpResponderFromAnyOverride) {
            int uid, pubSubId = 0;
            int peerInstanceId = 0;
            byte[] peerMac = ns.peerMac;

            if (VDBG) {
                Log.v(TAG, "processNetworkSpecifier: networkSpecifier=" + ns);
            }

            // type: always valid
            if (ns.type < 0
                    || ns.type > WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_MAX_VALID) {
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                        + ", invalid 'type' value");
                return null;
            }

            // role: always valid
            if (ns.role != WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
                    && ns.role != WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER) {
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                        + " -- invalid 'role' value");
                return null;
            }

            if (ns.role == WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
                    && ns.type != WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB
                    && ns.type != WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_OOB) {
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                        + " -- invalid 'type' value for INITIATOR (only IB and OOB are "
                        + "permitted)");
                return null;
            }

            // look up network specifier information in Aware state manager
            WifiAwareClientState client = mgr.getClient(ns.clientId);
            if (client == null) {
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                        + " -- not client with this id -- clientId=" + ns.clientId);
                return null;
            }
            uid = client.getUid();

            // API change post 27: no longer allow "ANY"-style responders (initiators were never
            // permitted).
            // Note: checks are done on the manager. This is a backup for apps which bypass the
            // check.
            if (!allowNdpResponderFromAnyOverride && !wifiPermissionsUtil.isTargetSdkLessThan(
                    client.getCallingPackage(), Build.VERSION_CODES.P)) {
                if (ns.type != WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB
                        && ns.type != WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_OOB) {
                    Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                            + " -- no ANY specifications allowed for this API level");
                    return null;
                }
            }

            // validate the port & transportProtocol
            if (ns.port < 0 || ns.transportProtocol < -1) {
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                        + " -- invalid port/transportProtocol");
                return null;
            }
            if (ns.port != 0 || ns.transportProtocol != -1) {
                if (ns.role != WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER) {
                    Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                            + " -- port/transportProtocol can only be specified on responder");
                    return null;
                }
                if (TextUtils.isEmpty(ns.passphrase) && ns.pmk == null) {
                    Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                            + " -- port/transportProtocol can only be specified on secure ndp");
                    return null;
                }
            }

            // validate the role (if session ID provided: i.e. session 1xx)
            if (ns.type == WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB
                    || ns.type == WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB_ANY_PEER) {
                WifiAwareDiscoverySessionState session = client.getSession(ns.sessionId);
                if (session == null) {
                    Log.e(TAG,
                            "processNetworkSpecifier: networkSpecifier=" + ns
                                    + " -- no session with this id -- sessionId=" + ns.sessionId);
                    return null;
                }

                if ((session.isPublishSession()
                        && ns.role != WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER) || (
                        !session.isPublishSession() && ns.role
                                != WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR)) {
                    Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                            + " -- invalid role for session type");
                    return null;
                }

                if (ns.type == WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB) {
                    pubSubId = session.getPubSubId();
                    WifiAwareDiscoverySessionState.PeerInfo peerInfo = session.getPeerInfo(
                            ns.peerId);
                    if (peerInfo == null) {
                        Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                                + " -- no peer info associated with this peer id -- peerId="
                                + ns.peerId);
                        return null;
                    }
                    peerInstanceId = peerInfo.mInstanceId;
                    try {
                        peerMac = peerInfo.mMac;
                        if (peerMac == null || peerMac.length != 6) {
                            Log.e(TAG, "processNetworkSpecifier: networkSpecifier="
                                    + ns + " -- invalid peer MAC address");
                            return null;
                        }
                    } catch (IllegalArgumentException e) {
                        Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns
                                + " -- invalid peer MAC address -- e=" + e);
                        return null;
                    }
                }
            }

            // validate UID
            if (ns.requestorUid != uid) {
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns.toString()
                        + " -- UID mismatch to clientId's uid=" + uid);
                return null;
            }

            // validate permission if PMK is used (SystemApi)
            if (ns.pmk != null && ns.pmk.length != 0) {
                if (permissionWrapper.getUidPermission(Manifest.permission.CONNECTIVITY_INTERNAL,
                        ns.requestorUid) != PackageManager.PERMISSION_GRANTED) {
                    Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns.toString()
                            + " -- UID doesn't have permission to use PMK API");
                    return null;
                }
            }

            // validate passphrase & PMK (if provided)
            if (!TextUtils.isEmpty(ns.passphrase)) { // non-null indicates usage
                if (!WifiAwareUtils.validatePassphrase(ns.passphrase)) {
                    Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns.toString()
                            + " -- invalid passphrase length: " + ns.passphrase.length());
                    return null;
                }
            }
            if (ns.pmk != null && !WifiAwareUtils.validatePmk(ns.pmk)) { // non-null indicates usage
                Log.e(TAG, "processNetworkSpecifier: networkSpecifier=" + ns.toString()
                        + " -- invalid pmk length: " + ns.pmk.length);
                return null;
            }

            // create container and populate
            AwareNetworkRequestInformation nnri = new AwareNetworkRequestInformation();
            nnri.state = AwareNetworkRequestInformation.STATE_IDLE;
            nnri.uid = uid;
            nnri.pubSubId = pubSubId;
            nnri.peerInstanceId = peerInstanceId;
            nnri.peerDiscoveryMac = peerMac;
            nnri.networkSpecifier = ns;
            nnri.equivalentSpecifiers.add(ns);

            return nnri;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder("AwareNetworkRequestInformation: ");
            sb.append("state=").append(state).append(", ns=").append(networkSpecifier).append(
                    ", uid=").append(uid).append(", interfaceName=").append(interfaceName).append(
                    ", pubSubId=").append(pubSubId).append(", peerInstanceId=").append(
                    peerInstanceId).append(", peerDiscoveryMac=").append(
                    peerDiscoveryMac == null ? ""
                            : String.valueOf(HexEncoding.encode(peerDiscoveryMac))).append(
                    ", ndpId=").append(ndpId).append(", peerDataMac=").append(
                    peerDataMac == null ? ""
                            : String.valueOf(HexEncoding.encode(peerDataMac)))
                    .append(", peerIpv6=").append(peerIpv6).append(", peerPort=").append(
                    peerPort).append(", peerTransportProtocol=").append(
                    peerTransportProtocol).append(", startTimestamp=").append(
                    startTimestamp).append(", channelInfo=").append(
                    channelInfo).append(", equivalentSpecifiers=[");
            for (WifiAwareNetworkSpecifier ns: equivalentSpecifiers) {
                sb.append(ns.toString()).append(", ");
            }
            return sb.append("]").toString();
        }
    }

    /**
     * A canonical (unique) descriptor of the peer connection.
     */
    static class CanonicalConnectionInfo {
        CanonicalConnectionInfo(byte[] peerDiscoveryMac, byte[] pmk, int sessionId,
                String passphrase) {
            this.peerDiscoveryMac = peerDiscoveryMac;
            this.pmk = pmk;
            this.sessionId = sessionId;
            this.passphrase = passphrase;
        }

        public final byte[] peerDiscoveryMac;

        /*
         * Security configuration matching:
         * - open: pmk/passphrase = null
         * - pmk: pmk != null, passphrase = null
         * - passphrase: passphrase != null, sessionId used (==0 for OOB), pmk=null
         */
        public final byte[] pmk;

        public final int sessionId;
        public final String passphrase;

        public boolean matches(CanonicalConnectionInfo other) {
            return (other.peerDiscoveryMac == null || Arrays
                    .equals(peerDiscoveryMac, other.peerDiscoveryMac))
                    && Arrays.equals(pmk, other.pmk)
                    && TextUtils.equals(passphrase, other.passphrase)
                    && (TextUtils.isEmpty(passphrase) || sessionId == other.sessionId);
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder("CanonicalConnectionInfo: [");
            sb.append("peerDiscoveryMac=").append(peerDiscoveryMac == null ? ""
                    : String.valueOf(HexEncoding.encode(peerDiscoveryMac))).append(", pmk=").append(
                    pmk == null ? "" : "*").append(", sessionId=").append(sessionId).append(
                    ", passphrase=").append(passphrase == null ? "" : "*").append("]");
            return sb.toString();
        }
    }

    /**
     * Enables mocking.
     */
    @VisibleForTesting
    public class NetworkInterfaceWrapper {
        /**
         * Configures network agent properties: link-local address, connected status, interface
         * name. Delegated to enable mocking.
         */
        public boolean configureAgentProperties(AwareNetworkRequestInformation nnri,
                Set<WifiAwareNetworkSpecifier> networkSpecifiers, int ndpId,
                NetworkInfo networkInfo, NetworkCapabilities networkCapabilities,
                LinkProperties linkProperties) {
            // find link-local address
            InetAddress linkLocal = null;
            NetworkInterface ni;
            try {
                ni = NetworkInterface.getByName(nnri.interfaceName);
            } catch (SocketException e) {
                Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri
                        + ": can't get network interface - " + e);
                mMgr.endDataPath(ndpId);
                nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                return false;
            }
            if (ni == null) {
                Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri
                        + ": can't get network interface (null)");
                mMgr.endDataPath(ndpId);
                nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                return false;
            }
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = addresses.nextElement();
                if (ip instanceof Inet6Address && ip.isLinkLocalAddress()) {
                    linkLocal = ip;
                    break;
                }
            }

            if (linkLocal == null) {
                Log.e(TAG, "onDataPathConfirm: ACCEPT nnri=" + nnri + ": no link local addresses");
                mMgr.endDataPath(ndpId);
                nnri.state = AwareNetworkRequestInformation.STATE_TERMINATING;
                return false;
            }

            // configure agent
            networkInfo.setIsAvailable(true);
            networkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);

            networkCapabilities.setNetworkSpecifier(new WifiAwareAgentNetworkSpecifier(
                    networkSpecifiers.toArray(new WifiAwareNetworkSpecifier[0])));

            linkProperties.setInterfaceName(nnri.interfaceName);
            linkProperties.addLinkAddress(new LinkAddress(linkLocal, 64));
            linkProperties.addRoute(
                    new RouteInfo(new IpPrefix("fe80::/64"), null, nnri.interfaceName));

            return true;
        }
    }

    /**
     * Utility (hence static) class encapsulating the data structure used to communicate Wi-Fi Aware
     * specific network capabilities. The TLV is defined as part of the NANv3 spec:
     *
     * - Generic Service Protocol
     *   - Port
     *   - Transport protocol
     */
    @VisibleForTesting
    public static class NetworkInformationData {
        // All package visible to allow usage in unit testing
        /* package */ static final int IPV6_LL_TYPE = 0x00; // Table 82
        /* package */ static final int SERVICE_INFO_TYPE = 0x01; // Table 83
        /* package */ static final byte[] WFA_OUI = {0x50, 0x6F, (byte) 0x9A}; // Table 83
        /* package */ static final int GENERIC_SERVICE_PROTOCOL_TYPE = 0x02; // Table 50
        /* package */ static final int SUB_TYPE_PORT = 0x00; // Table 127
        /* package */ static final int SUB_TYPE_TRANSPORT_PROTOCOL = 0x01; // Table 128

        /**
         * Construct the TLV.
         */
        public static byte[] buildTlv(int port, int transportProtocol) {
            if (port == 0 && transportProtocol == -1) {
                return null;
            }

            TlvBufferUtils.TlvConstructor tlvc = new TlvBufferUtils.TlvConstructor(1, 2);
            tlvc.setByteOrder(ByteOrder.LITTLE_ENDIAN);
            tlvc.allocate(20); // safe size for now

            tlvc.putRawByteArray(WFA_OUI);
            tlvc.putRawByte((byte) GENERIC_SERVICE_PROTOCOL_TYPE);

            if (port != 0) {
                tlvc.putShort(SUB_TYPE_PORT, (short) port);
            }
            if (transportProtocol != -1) {
                tlvc.putByte(SUB_TYPE_TRANSPORT_PROTOCOL, (byte) transportProtocol);
            }

            byte[] subTypes = tlvc.getArray();

            tlvc.allocate(20);
            tlvc.putByteArray(SERVICE_INFO_TYPE, subTypes);

            return tlvc.getArray();
        }

        static class ParsedResults {
            ParsedResults(int port, int transportProtocol) {
                this.port = port;
                this.transportProtocol = transportProtocol;
            }

            public int port = 0;
            public int transportProtocol = -1;
        }

        /**
         * Parse the TLV and return <port, transportProtocol>.
         */
        public static ParsedResults parseTlv(byte[] tlvs) {
            int port = 0;
            int transportProtocol = -1;

            try {
                TlvBufferUtils.TlvIterable tlvi = new TlvBufferUtils.TlvIterable(1, 2, tlvs);
                tlvi.setByteOrder(ByteOrder.LITTLE_ENDIAN);
                for (TlvBufferUtils.TlvElement tlve : tlvi) {
                    switch (tlve.type) {
                        case IPV6_LL_TYPE:
                            Log.w(TAG,
                                    "NetworkInformationData: non-default IPv6 not supporting - "
                                            + "ignoring");
                            break;
                        case SERVICE_INFO_TYPE:
                            Pair<Integer, Integer> serviceInfo = parseServiceInfoTlv(
                                    tlve.getRawData());
                            if (serviceInfo != null) {
                                port = serviceInfo.first;
                                transportProtocol = serviceInfo.second;
                            }
                            break;
                        default:
                            Log.w(TAG,
                                    "NetworkInformationData: ignoring unknown T -- " + tlve.type);
                            break;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "NetworkInformationData: error parsing TLV -- " + e);
                return null;
            }
            if (port == 0 && transportProtocol == -1) {
                return null;
            }
            return new ParsedResults(port, transportProtocol);
        }

        private static Pair<Integer, Integer> parseServiceInfoTlv(byte[] tlv) {
            int port = 0;
            int transportProtocol = -1;

            if (tlv.length < 4) {
                Log.e(TAG, "NetworkInformationData: invalid SERVICE_INFO_TYPE length");
                return null;
            }
            if (tlv[0] != WFA_OUI[0] || tlv[1] != WFA_OUI[1] || tlv[2] != WFA_OUI[2]) {
                Log.e(TAG, "NetworkInformationData: unexpected OUI");
                return null;
            }
            if (tlv[3] != GENERIC_SERVICE_PROTOCOL_TYPE) {
                Log.e(TAG, "NetworkInformationData: invalid type -- " + tlv[3]);
                return null;
            }
            TlvBufferUtils.TlvIterable subTlvi = new TlvBufferUtils.TlvIterable(1,
                    2, Arrays.copyOfRange(tlv, 4, tlv.length));
            subTlvi.setByteOrder(ByteOrder.LITTLE_ENDIAN);
            for (TlvBufferUtils.TlvElement subTlve : subTlvi) {
                switch (subTlve.type) {
                    case SUB_TYPE_PORT:
                        if (subTlve.length != 2) {
                            Log.e(TAG,
                                    "NetworkInformationData: invalid port TLV "
                                            + "length -- " + subTlve.length);
                            return null;
                        }
                        port = subTlve.getShort();
                        if (port < 0) {
                            port += -2 * (int) Short.MIN_VALUE;
                        }
                        if (port == 0) {
                            Log.e(TAG, "NetworkInformationData: invalid port "
                                    + port);
                            return null;
                        }
                        break;
                    case SUB_TYPE_TRANSPORT_PROTOCOL:
                        if (subTlve.length != 1) {
                            Log.e(TAG,  "NetworkInformationData: invalid transport "
                                    + "protocol TLV length -- " + subTlve.length);
                            return null;
                        }
                        transportProtocol = subTlve.getByte();
                        if (transportProtocol < 0) {
                            transportProtocol += -2 * (int) Byte.MIN_VALUE;
                        }
                        break;
                    default:
                        Log.w(TAG,  "NetworkInformationData: ignoring unknown "
                                + "SERVICE_INFO.T -- " + subTlve.type);
                        break;
                }
            }
            return Pair.create(port, transportProtocol);
        }
    }

    /**
     * Dump the internal state of the class.
     */
    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("WifiAwareDataPathStateManager:");
        pw.println("  mInterfaces: " + mInterfaces);
        pw.println("  sNetworkCapabilitiesFilter: " + sNetworkCapabilitiesFilter);
        pw.println("  mNetworkRequestsCache: " + mNetworkRequestsCache);
        pw.println("  mNetworkFactory:");
        mNetworkFactory.dump(fd, pw, args);
    }
}