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

import binascii
import re
import logging
logger = logging.getLogger()
import struct
import subprocess
import time

import hostapd
from wpasupplicant import WpaSupplicant
from utils import HwsimSkip, alloc_fail, fail_test, wait_fail_trigger
from test_ap_ht import clear_scan_cache
from remotehost import remote_compatible
from test_ap_vht import vht_supported

def check_rrm_support(dev):
    rrm = int(dev.get_driver_status_field("capa.rrm_flags"), 16)
    if rrm & 0x5 != 0x5 and rrm & 0x10 != 0x10:
        raise HwsimSkip("Required RRM capabilities are not supported")

def check_tx_power_support(dev):
    rrm = int(dev.get_driver_status_field("capa.rrm_flags"), 16)
    if rrm & 0x8 != 0x8:
        raise HwsimSkip("Required RRM capabilities are not supported")

nr="00112233445500000000510107"
lci="01000800101298c0b512926666f6c2f1001c00004104050000c00012"
civic="01000b0011223344556677889900998877665544332211aabbccddeeff"

def check_nr_results(dev, bssids=None, lci=False, civic=False):
    if bssids is None:
        ev = dev.wait_event(["RRM-NEIGHBOR-REP-REQUEST-FAILED" ], timeout=10)
        if ev is None:
            raise Exception("RRM neighbor report failure not received")
        return

    received = []
    for bssid in bssids:
        ev = dev.wait_event(["RRM-NEIGHBOR-REP-RECEIVED"], timeout=10)
        if ev is None:
            raise Exception("RRM report result not indicated")
        received.append(ev)

    for bssid in bssids:
        found = False
        for r in received:
            if "RRM-NEIGHBOR-REP-RECEIVED bssid=" + bssid in r:
                if lci and "lci=" not in r:
                    raise Exception("LCI data not reported for %s" % bssid)
                if civic and "civic=" not in r:
                    raise Exception("civic data not reported for %s" % bssid)
                received.remove(r)
                found = True
                break
        if not found:
            raise Exception("RRM report result for %s not indicated" % bssid)

def test_rrm_neighbor_db(dev, apdev):
    """hostapd ctrl_iface SET_NEIGHBOR"""
    params = { "ssid": "test", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    # Bad BSSID
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:gg ssid=\"test1\" nr=" + nr):
        raise Exception("Set neighbor succeeded unexpectedly")

    # Bad SSID
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=test1 nr=" + nr):
        raise Exception("Set neighbor succeeded unexpectedly")

    # No SSID
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 nr=" + nr):
        raise Exception("Set neighbor succeeded unexpectedly")

    # No NR
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\""):
        raise Exception("Set neighbor succeeded unexpectedly")

    # Odd length of NR
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr[:-1]):
        raise Exception("Set neighbor succeeded unexpectedly")

    # Invalid lci
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr + " lci=1"):
        raise Exception("Set neighbor succeeded unexpectedly")

    # Invalid civic
    if "FAIL" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr + " civic=1"):
        raise Exception("Set neighbor succeeded unexpectedly")

    # No entry yet in database
    if "FAIL" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\""):
        raise Exception("Remove neighbor succeeded unexpectedly")

    # Add a neighbor entry
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr + " lci=" + lci + " civic=" + civic):
        raise Exception("Set neighbor failed")

    # Another BSSID with the same SSID
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:56 ssid=\"test1\" nr=" + nr + " lci=" + lci + " civic=" + civic):
        raise Exception("Set neighbor failed")

    # Fewer parameters
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr):
        raise Exception("Set neighbor failed")

    # SSID in hex format
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=7465737431 nr=" + nr):
        raise Exception("Set neighbor failed")

    # With more parameters
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr + " civic=" + civic):
        raise Exception("Set neighbor failed")

    # With all parameters
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\" nr=" + nr + " lci=" + lci + " civic=" + civic):
        raise Exception("Set neighbor failed")

    # Another SSID on the same BSSID
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test2\" nr=" + nr + " lci=" + lci):
        raise Exception("Set neighbor failed")

    if "OK" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\""):
        raise Exception("Remove neighbor failed")

    if "OK" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:56 ssid=\"test1\""):
        raise Exception("Remove neighbor failed")

    if "OK" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55 ssid=\"test2\""):
        raise Exception("Remove neighbor failed")

    # Double remove
    if "FAIL" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1\""):
        raise Exception("Remove neighbor succeeded unexpectedly")

    # Stationary AP
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test3\" nr=" + nr + " lci=" + lci + " civic=" + civic + " stat"):
        raise Exception("Set neighbor failed")

    if "OK" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55 ssid=\"test3\""):
        raise Exception("Remove neighbor failed")

    # Invalid remove - bad BSSID
    if "FAIL" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:5 ssid=\"test1\""):
        raise Exception("Remove neighbor succeeded unexpectedly")

    # Invalid remove - bad SSID
    if "FAIL" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55 ssid=\"test1"):
        raise Exception("Remove neighbor succeeded unexpectedly")

    # Invalid remove - missing SSID
    if "FAIL" not in hapd.request("REMOVE_NEIGHBOR 00:11:22:33:44:55"):
        raise Exception("Remove neighbor succeeded unexpectedly")

def test_rrm_neighbor_rep_req(dev, apdev):
    """wpa_supplicant ctrl_iface NEIGHBOR_REP_REQUEST"""
    check_rrm_support(dev[0])

    nr1="00112233445500000000510107"
    nr2="00112233445600000000510107"
    nr3="dd112233445500000000510107"

    params = { "ssid": "test" }
    hostapd.add_ap(apdev[0]['ifname'], params)
    params = { "ssid": "test2", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[1]['ifname'], params)

    bssid1 = apdev[1]['bssid']

    dev[0].connect("test", key_mgmt="NONE", scan_freq="2412")
    if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request succeeded unexpectedly (AP without RRM)")
    if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"abcdef\""):
        raise Exception("Request succeeded unexpectedly (AP without RRM 2)")
    dev[0].request("DISCONNECT")

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request failed")
    check_nr_results(dev[0], [bssid1])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST lci"):
        raise Exception("Request failed")
    check_nr_results(dev[0], [bssid1])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST lci civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], [bssid1])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test3\""):
        raise Exception("Request failed")
    check_nr_results(dev[0])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test3\" lci civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0])

    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"test3\" nr=" + nr1 + " lci=" + lci + " civic=" + civic):
        raise Exception("Set neighbor failed")
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:56 ssid=\"test3\" nr=" + nr2 + " lci=" + lci + " civic=" + civic):
        raise Exception("Set neighbor failed")
    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:56 ssid=\"test4\" nr=" + nr2 + " lci=" + lci + " civic=" + civic):
        raise Exception("Set neighbor failed")
    if "OK" not in hapd.request("SET_NEIGHBOR dd:11:22:33:44:55 ssid=\"test5\" nr=" + nr3 + " lci=" + lci):
        raise Exception("Set neighbor failed")

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test3\""):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:55", "00:11:22:33:44:56"])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test3\" lci"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:55", "00:11:22:33:44:56"],
                     lci=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test3\" civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:55", "00:11:22:33:44:56"],
                     civic=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test3\" lci civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:55", "00:11:22:33:44:56"],
                     lci=True, civic=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test4\""):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:56"])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test4\" lci"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:56"], lci=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test4\" civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:56"], civic=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test4\" lci civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["00:11:22:33:44:56"], lci=True, civic=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test5\""):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["dd:11:22:33:44:55"])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test5\" lci"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["dd:11:22:33:44:55"], lci=True)

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test5\" civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["dd:11:22:33:44:55"])

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST ssid=\"test5\" lci civic"):
        raise Exception("Request failed")
    check_nr_results(dev[0], ["dd:11:22:33:44:55"], lci=True)

def test_rrm_neighbor_rep_oom(dev, apdev):
    """hostapd neighbor report OOM"""
    check_rrm_support(dev[0])

    nr1="00112233445500000000510107"
    nr2="00112233445600000000510107"
    nr3="dd112233445500000000510107"

    params = { "ssid": "test", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].connect("test", key_mgmt="NONE", scan_freq="2412")

    with alloc_fail(hapd, 1, "hostapd_send_nei_report_resp"):
        if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
            raise Exception("Request failed")
        ev = dev[0].wait_event(["RRM-NEIGHBOR-REP-REQUEST-FAILED"], timeout=5)
        if ev is None:
            raise Exception("Neighbor report failure not reported")

def test_rrm_lci_req(dev, apdev):
    """hostapd lci request"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    # station not specified
    if "FAIL" not in hapd.request("REQ_LCI "):
        raise Exception("REQ_LCI with no station succeeded unexpectedly")

    # station that is not connected specified
    if "FAIL" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
        raise Exception("REQ_LCI succeeded unexpectedly (station not connected)")

    dev[0].request("SET LCI ")
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    # station connected without LCI
    if "FAIL" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
        raise Exception("REQ_LCI succeeded unexpectedly (station without lci)")

    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected(timeout=2)

    dev[0].request("SET LCI " + lci)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    # station connected with LCI
    if "OK" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
        raise Exception("REQ_LCI failed unexpectedly")

def test_rrm_lci_req_timeout(dev, apdev):
    """hostapd lci request timeout"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].request("SET LCI " + lci)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hapd.set("ext_mgmt_frame_handling", "1")
    if "OK" not in hapd.request("REQ_LCI " + addr):
        raise Exception("REQ_LCI failed unexpectedly")
    ev = hapd.wait_event(["MGMT-RX"], timeout=5)
    if ev is None:
        raise Exception("No response seen at the AP")
    # Ignore response and wait for HOSTAPD_RRM_REQUEST_TIMEOUT
    time.sleep(5.1)
    # Process response after timeout
    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % ev.split(' ')[1]):
        raise Exception("MGMT_RX_PROCESS failed")
    for i in range(257):
        if "OK" not in hapd.request("REQ_LCI " + addr):
            raise Exception("REQ_LCI failed unexpectedly")
        dev[0].dump_monitor()
        hapd.dump_monitor()
    hapd.set("ext_mgmt_frame_handling", "0")
    dev[0].request("DISCONNECT")
    dev[0].wait_disconnected()

def test_rrm_lci_req_oom(dev, apdev):
    """LCI report generation OOM"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].request("SET LCI " + lci)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    with alloc_fail(dev[0], 1, "wpabuf_resize;wpas_rrm_build_lci_report"):
        if "OK" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
            raise Exception("REQ_LCI failed unexpectedly")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")

    dev[0].request("SET LCI ")
    # This in in wpas_rrm_build_lci_report(), but backtrace may not always work
    # for the "reject" label there.
    with alloc_fail(dev[0], 1, "wpabuf_resize;wpas_rrm_handle_msr_req_element"):
        if "OK" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
            raise Exception("REQ_LCI failed unexpectedly")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")

def test_rrm_lci_req_ap_oom(dev, apdev):
    """LCI report generation AP OOM and failure"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].request("SET LCI " + lci)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    with alloc_fail(hapd, 1, "wpabuf_alloc;hostapd_send_lci_req"):
        if "FAIL" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
            raise Exception("REQ_LCI succeeded during OOM")

    with fail_test(hapd, 1, "nl80211_send_frame_cmd;hostapd_send_lci_req"):
        if "FAIL" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
            raise Exception("REQ_LCI succeeded during failure testing")

def test_rrm_lci_req_get_reltime_failure(dev, apdev):
    """LCI report generation and os_get_reltime() failure"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].request("SET LCI " + lci)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    with fail_test(dev[0], 1, "os_get_reltime;wpas_rrm_build_lci_report"):
        if "OK" not in hapd.request("REQ_LCI " + dev[0].own_addr()):
            raise Exception("REQ_LCI failed unexpectedly")
        wait_fail_trigger(dev[0], "GET_FAIL")

def test_rrm_neighbor_rep_req_from_conf(dev, apdev):
    """wpa_supplicant ctrl_iface NEIGHBOR_REP_REQUEST and hostapd config"""
    check_rrm_support(dev[0])

    params = { "ssid": "test2", "rrm_neighbor_report": "1",
               "stationary_ap": "1", "lci": lci, "civic": civic }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    bssid = apdev[0]['bssid']

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request failed")
    check_nr_results(dev[0], [bssid])

def test_rrm_neighbor_rep_req_timeout(dev, apdev):
    """wpa_supplicant behavior on NEIGHBOR_REP_REQUEST response timeout"""
    check_rrm_support(dev[0])

    params = { "ssid": "test2", "rrm_neighbor_report": "1",
               "stationary_ap": "1", "lci": lci, "civic": civic }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    hapd.set("ext_mgmt_frame_handling", "1")

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request failed")
    msg = hapd.mgmt_rx()
    if msg is None:
        raise Exception("Neighbor report request not seen")
    check_nr_results(dev[0])

def test_rrm_neighbor_rep_req_oom(dev, apdev):
    """wpa_supplicant ctrl_iface NEIGHBOR_REP_REQUEST OOM"""
    check_rrm_support(dev[0])

    params = { "ssid": "test2", "rrm_neighbor_report": "1",
               "stationary_ap": "1", "lci": lci, "civic": civic }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    with alloc_fail(dev[0], 1, "wpabuf_alloc;wpas_rrm_process_neighbor_rep"):
        if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
            raise Exception("Request failed")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")

    with fail_test(dev[0], 1,
                    "wpa_driver_nl80211_send_action;wpas_rrm_send_neighbor_rep_request"):
        if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
            raise Exception("Request succeeded unexpectedly")

    with alloc_fail(dev[0], 1,
                    "wpabuf_alloc;wpas_rrm_send_neighbor_rep_request"):
        if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
            raise Exception("Request succeeded unexpectedly")

def test_rrm_neighbor_rep_req_disconnect(dev, apdev):
    """wpa_supplicant behavior on disconnection during NEIGHBOR_REP_REQUEST"""
    check_rrm_support(dev[0])

    params = { "ssid": "test2", "rrm_neighbor_report": "1",
               "stationary_ap": "1", "lci": lci, "civic": civic }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request accepted while disconnected")

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    hapd.set("ext_mgmt_frame_handling", "1")

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request failed")
    msg = hapd.mgmt_rx()
    if msg is None:
        raise Exception("Neighbor report request not seen")
    dev[0].request("DISCONNECT")
    check_nr_results(dev[0])

def test_rrm_neighbor_rep_req_not_supported(dev, apdev):
    """NEIGHBOR_REP_REQUEST for AP not supporting neighbor report"""
    check_rrm_support(dev[0])

    params = { "ssid": "test2", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request accepted unexpectedly")

def test_rrm_neighbor_rep_req_busy(dev, apdev):
    """wpa_supplicant and concurrent NEIGHBOR_REP_REQUEST commands"""
    check_rrm_support(dev[0])

    params = { "ssid": "test2", "rrm_neighbor_report": "1",
               "stationary_ap": "1", "lci": lci, "civic": civic }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    dev[0].connect("test2", key_mgmt="NONE", scan_freq="2412")

    hapd.set("ext_mgmt_frame_handling", "1")

    if "OK" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request failed")
    msg = hapd.mgmt_rx()
    if msg is None:
        raise Exception("Neighbor report request not seen")

    if "FAIL" not in dev[0].request("NEIGHBOR_REP_REQUEST"):
        raise Exception("Request accepted while disconnected")

def test_rrm_ftm_range_req(dev, apdev):
    """hostapd FTM range request command"""
    check_rrm_support(dev[0])
    try:
        run_rrm_ftm_range_req(dev, apdev)
    finally:
        dev[1].request("VENDOR_ELEM_REMOVE 13 *")

def run_rrm_ftm_range_req(dev, apdev):
    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    # station not specified
    if "FAIL" not in hapd.request("REQ_RANGE "):
        raise Exception("REQ_RANGE with no station succeeded unexpectedly")

    # station that is not connected specified
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr()):
        raise Exception("REQ_RANGE succeeded unexpectedly (station not connected)")

    # No responders specified
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 10"):
        raise Exception("REQ_RANGE succeeded unexpectedly (no responder)")

    # Bad responder address
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 10 00:11:22:33:44:"):
        raise Exception("REQ_RANGE succeeded unexpectedly (bad responder address)")

    # Bad responder address
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 10 00:11:22:33:44:55 00:11:22:33:44"):
        raise Exception("REQ_RANGE succeeded unexpectedly (bad responder address 2)")

    # Bad min_ap value
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 300 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (invalid min_ap value)")

    # Bad rand value
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " -1 10 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (invalid rand value)")
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 65536 10 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (invalid rand value)")

    # Missing min_ap value
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10"):
        raise Exception("REQ_RANGE succeeded unexpectedly (missing min_ap value)")

    # Too many responders
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 10" + 20*" 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (too many responders)")
    # Wrong min AP count
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 10 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (responder not in database)")

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    # Override RM capabilities to include FTM range report
    dev[1].request("VENDOR_ELEM_ADD 13 46057100000004")
    dev[1].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    # Request range: Destination address is not connected
    if "FAIL" not in hapd.request("REQ_RANGE 11:22:33:44:55:66 10 1 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (responder not in database)")

    # Responder not in database
    # Note: this check would pass since the station does not support FTM range
    # request and not because the responder is not in the database.
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[0].own_addr() + " 10 1 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (responder not in database)")

    # Missing neighbor report for 00:11:22:33:44:55
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[1].own_addr() + " 10 1 00:11:22:33:44:55"):
        raise Exception("REQ_RANGE succeeded unexpectedly (responder not in database)")

    # Send request
    if "OK" not in hapd.request("REQ_RANGE " + dev[1].own_addr() + " 10 1 " + bssid):
        raise Exception("REQ_RANGE failed unexpectedly")

    # Too long range request
    if "FAIL" not in hapd.request("REQ_RANGE " + dev[1].own_addr() + " 10 1" + 16*(" " + bssid)):
        raise Exception("REQ_RANGE accepted for too long range request")

    time.sleep(0.1)
    dev[0].request("DISCONNECT")
    dev[1].request("DISCONNECT")
    dev[1].wait_disconnected()

def test_rrm_ftm_range_req_timeout(dev, apdev):
    """hostapd FTM range request timeout"""
    check_rrm_support(dev[0])
    try:
        run_rrm_ftm_range_req_timeout(dev, apdev)
    finally:
        dev[1].request("VENDOR_ELEM_REMOVE 13 *")

def run_rrm_ftm_range_req_timeout(dev, apdev):
    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    # Override RM capabilities to include FTM range report
    dev[1].request("VENDOR_ELEM_ADD 13 46057100000004")
    dev[1].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[1].own_addr()

    hapd.set("ext_mgmt_frame_handling", "1")
    if "OK" not in hapd.request("REQ_RANGE " + addr + " 10 1 " + bssid):
        raise Exception("REQ_RANGE failed")
    ev = hapd.wait_event(["MGMT-RX"], timeout=5)
    if ev is None:
        raise Exception("No response seen at the AP")
    # Ignore response and wait for HOSTAPD_RRM_REQUEST_TIMEOUT
    time.sleep(5.1)
    # Process response after timeout
    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=%s" % ev.split(' ')[1]):
        raise Exception("MGMT_RX_PROCESS failed")

    for i in range(257):
        if "OK" not in hapd.request("REQ_RANGE " + addr + " 10 1 " + bssid):
            raise Exception("REQ_RANGE failed")
        dev[1].dump_monitor()
        hapd.dump_monitor()

    hapd.set("ext_mgmt_frame_handling", "0")
    dev[1].request("DISCONNECT")
    dev[1].wait_disconnected()

def test_rrm_ftm_range_req_failure(dev, apdev):
    """hostapd FTM range request failure"""
    check_rrm_support(dev[0])
    try:
        run_rrm_ftm_range_req_failure(dev, apdev)
    finally:
        dev[1].request("VENDOR_ELEM_REMOVE 13 *")

def run_rrm_ftm_range_req_failure(dev, apdev):
    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    # Override RM capabilities to include FTM range report
    dev[1].request("VENDOR_ELEM_ADD 13 46057100000004")
    dev[1].connect("rrm", key_mgmt="NONE", scan_freq="2412")

    with alloc_fail(hapd, 1, "wpabuf_alloc;hostapd_send_range_req"):
        if "FAIL" not in hapd.request("REQ_RANGE " + dev[1].own_addr() + " 10 1 " + bssid):
            raise Exception("REQ_RANGE succeeded during OOM")

    with fail_test(hapd, 1, "nl80211_send_frame_cmd;hostapd_send_range_req"):
        if "FAIL" not in hapd.request("REQ_RANGE " + dev[1].own_addr() + " 10 1 " + bssid):
            raise Exception("REQ_RANGE succeeded during failure testing")

    dev[1].request("DISCONNECT")
    dev[1].wait_disconnected()

def test_rrm_ftm_capa_indication(dev, apdev):
    """FTM capability indication"""
    try:
        _test_rrm_ftm_capa_indication(dev, apdev)
    finally:
        dev[0].request("SET ftm_initiator 0")
        dev[0].request("SET ftm_responder 0")

def _test_rrm_ftm_capa_indication(dev, apdev):
    params = { "ssid": "ftm",
               "ftm_responder": "1",
               "ftm_initiator": "1", }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)

    if "OK" not in dev[0].request("SET ftm_initiator 1"):
        raise Exception("could not set ftm_initiator")
    if "OK" not in dev[0].request("SET ftm_responder 1"):
        raise Exception("could not set ftm_responder")
    dev[0].scan_for_bss(apdev[0]['bssid'], freq=2412, force_scan=True)

class BeaconReport:
    def __init__(self, report):
        self.opclass, self.channel, self.start, self.duration, self.frame_info, self.rcpi, self.rsni = struct.unpack("<BBQHBBB", report[0:15])
        report = report[15:]
        self.bssid = report[0:6]
        self.bssid_str = "%02x:%02x:%02x:%02x:%02x:%02x" % (struct.unpack('6B', self.bssid))
        report = report[6:]
        self.antenna_id, self.parent_tsf = struct.unpack("<BI", report[0:5])
        report = report[5:]
        self.subelems = report
        self.frame_body = None
        self.frame_body_fragment_id = None
        self.last_indication = None
        while len(report) >= 2:
            eid,elen = struct.unpack('BB', report[0:2])
            report = report[2:]
            if len(report) < elen:
                raise Exception("Invalid subelement in beacon report")
            if eid == 1:
                # Reported Frame Body
                # Contents depends on the reporting detail request:
                # 0 = no Reported Frame Body subelement
                # 1 = all fixed fields and any elements identified in Request
                #     element
                # 2 = all fixed fields and all elements
                # Fixed fields: Timestamp[8] BeaconInt[2] CapabInfo[2]
                self.frame_body = report[0:elen]
	    if eid == 2:
	        self.frame_body_fragment_id = report[0:elen]
            if eid == 164:
                self.last_indication = report[0:elen]
            report = report[elen:]
    def __str__(self):
        txt = "opclass={} channel={} start={} duration={} frame_info={} rcpi={} rsni={} bssid={} antenna_id={} parent_tsf={}".format(self.opclass, self.channel, self.start, self.duration, self.frame_info, self.rcpi, self.rsni, self.bssid_str, self.antenna_id, self.parent_tsf)
        if self.frame_body:
            txt += " frame_body=" + binascii.hexlify(self.frame_body)
        if self.frame_body_fragment_id:
            txt += " fragment_id=" + binascii.hexlify(self.frame_body_fragment_id)
        if self.last_indication:
            txt += " last_indication=" + binascii.hexlify(self.last_indication)

        return txt

def run_req_beacon(hapd, addr, request):
    token = hapd.request("REQ_BEACON " + addr + " " + request)
    if "FAIL" in token:
        raise Exception("REQ_BEACON failed")

    ev = hapd.wait_event(["BEACON-REQ-TX-STATUS"], timeout=5)
    if ev is None:
        raise Exception("No TX status event for beacon request received")
    fields = ev.split(' ')
    if fields[1] != addr:
        raise Exception("Unexpected STA address in TX status: " + fields[1])
    if fields[2] != token:
        raise Exception("Unexpected dialog token in TX status: " + fields[2] + " (expected " + token + ")")
    if fields[3] != "ack=1":
        raise Exception("Unexected ACK status in TX status: " + fields[3])
    return token

@remote_compatible
def test_rrm_beacon_req_table(dev, apdev):
    """Beacon request - beacon table mode"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another" })

    tests = [ "REQ_BEACON ",
              "REQ_BEACON q",
              "REQ_BEACON 11:22:33:44:55:66 1",
              "REQ_BEACON 11:22:33:44:55:66 1q",
              "REQ_BEACON 11:22:33:44:55:66 11223344556677889900aabbccddeeff" ]
    for t in tests:
        if "FAIL" not in hapd.request(t):
            raise Exception("Invalid command accepted: " + t)

    dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        if fields[1] != addr:
            raise Exception("Unexpected STA address in beacon report response: " + fields[1])
        if fields[2] != token:
            raise Exception("Unexpected dialog token in beacon report response: " + fields[2] + " (expected " + token + ")")
        if fields[3] != "00":
            raise Exception("Unexpected measurement report mode")

        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))

        # Default reporting detail is 2, i.e., all fixed fields and elements.
        if not report.frame_body:
            raise Exception("Reported Frame Body subelement missing")
        if len(report.frame_body) <= 12:
            raise Exception("Too short Reported Frame Body subelement")

def test_rrm_beacon_req_frame_body_fragmentation(dev, apdev):
    """Beacon request - beacon table mode - frame body fragmentation"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }

    hapd = hostapd.add_ap(apdev[0], params)
    hapd.set('vendor_elements', ("dd051122330203dd0400137400dd04001374ffdd0511"
              "22330203dd0400137400dd04001374ffdd051122330203dd0400137400dd04001"
              "374ffdd051122330203dd0400137400dd04001374ffdd051122330203dd040013"
              "7400dd04001374ffdd051122330203dd0400137400dd04001374ffdd051122330"
              "203dd0400137400dd04001374ffdd051122330203dd0400137400dd04001374ff"
              "dd051122330203dd0400137400dd04001374ff"))

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff")

    # 2 beacon reports elements are expected because of fragmentation
    for i in range(0, 2):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        if fields[1] != addr:
            raise Exception("Unexpected STA address in beacon report response: " + fields[1])
        if fields[2] != token:
            raise Exception("Unexpected dialog token in beacon report response: " + fields[2] + " (expected " + token + ")")
        if fields[3] != "00":
            raise Exception("Unexpected measurement report mode")

        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))

        # Default reporting detail is 2, i.e., all fixed fields and elements.
        if not report.frame_body_fragment_id:
            raise Exception("Reported Frame Body Fragment ID subelement missing")
        fragment_id = binascii.hexlify(report.frame_body_fragment_id)
        frag_number = int(fragment_id[2:], 16) & int(0x7f)
        if frag_number != i:
            raise Exception("Incorrect fragment number: %d" % frag_number)
        more_frags = int(fragment_id[2:], 16) >> 7
        if i == 0 and more_frags != 1:
            raise Exception("more fragments bit is not set on first fragment")
        if i == 1 and more_frags != 0:
            raise Exception("more fragments bit is set on last fragment")

def test_rrm_beacon_req_last_frame_indication(dev, apdev):
    """Beacon request - beacon table mode - last frame indication"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }

    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    # The request contains the last beacon report indication subelement
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffffa40101")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        if fields[1] != addr:
            raise Exception("Unexpected STA address in beacon report response: " + fields[1])
        if fields[2] != token:
            raise Exception("Unexpected dialog token in beacon report response: " + fields[2] + " (expected " + token + ")")
        if fields[3] != "00":
            raise Exception("Unexpected measurement report mode")

        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))

        if not report.last_indication:
            raise Exception("Last Beacon Report Indication subelement missing")

        last = binascii.hexlify(report.last_indication)
        if last != '01':
            raise Exception("last beacon report indication is not set on last frame")

    # The request does not contain the last beacon report indication subelement
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        if fields[1] != addr:
            raise Exception("Unexpected STA address in beacon report response: " + fields[1])
        if fields[2] != token:
            raise Exception("Unexpected dialog token in beacon report response: " + fields[2] + " (expected " + token + ")")
        if fields[3] != "00":
            raise Exception("Unexpected measurement report mode")

        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))

        if report.last_indication:
            raise Exception("Last Beacon Report Indication subelement present but not requested")

@remote_compatible
def test_rrm_beacon_req_table_detail(dev, apdev):
    """Beacon request - beacon table mode - reporting detail"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    logger.info("Reporting Detail 0")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020100")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if report.frame_body:
        raise Exception("Reported Frame Body subelement included with Reporting Detail 0")
    hapd.dump_monitor()

    logger.info("Reporting Detail 1")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if not report.frame_body:
        raise Exception("Reported Frame Body subelement missing")
    if len(report.frame_body) != 12:
        raise Exception("Unexpected Reported Frame Body subelement length with Reporting Detail 1")
    hapd.dump_monitor()

    logger.info("Reporting Detail 2")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020102")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if not report.frame_body:
        raise Exception("Reported Frame Body subelement missing")
    if len(report.frame_body) <= 12:
        raise Exception("Unexpected Reported Frame Body subelement length with Reporting Detail 2")
    hapd.dump_monitor()

    logger.info("Reporting Detail 3 (invalid)")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020103")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response to invalid reporting detail 3")
    hapd.dump_monitor()

    logger.info("Reporting Detail (too short)")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "0200")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response to invalid reporting detail")
    hapd.dump_monitor()

@remote_compatible
def test_rrm_beacon_req_table_request(dev, apdev):
    """Beacon request - beacon table mode - request element"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a03000106")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if not report.frame_body:
        raise Exception("Reported Frame Body subelement missing")
    if len(report.frame_body) != 12 + 5 + 10:
        raise Exception("Unexpected Reported Frame Body subelement length with Reporting Detail 1 and requested elements SSID + SuppRates")
    hapd.dump_monitor()

    logger.info("Incorrect reporting detail with request subelement")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020102" + "0a03000106")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response (invalid reporting detail)")
    hapd.dump_monitor()

    logger.info("Invalid request subelement length")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a00")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response (invalid request subelement length)")
    hapd.dump_monitor()

    logger.info("Multiple request subelements")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a0100" + "0a0101")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response (multiple request subelements)")
    hapd.dump_monitor()

@remote_compatible
def test_rrm_beacon_req_table_request_oom(dev, apdev):
    """Beacon request - beacon table mode - request element OOM"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    with alloc_fail(dev[0], 1,
                    "bitfield_alloc;wpas_rm_handle_beacon_req_subelem"):
        token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a03000106")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.1)
        if ev is not None:
            raise Exception("Unexpected beacon report response received (OOM)")

    with alloc_fail(dev[0], 1,
                    "wpabuf_alloc;wpas_rrm_send_msr_report_mpdu"):
        token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a03000106")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.1)
        if ev is not None:
            raise Exception("Unexpected beacon report response received (OOM)")

    with fail_test(dev[0], 1,
                    "wpa_driver_nl80211_send_action;wpas_rrm_send_msr_report_mpdu"):
        token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a03000106")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.1)
        if ev is not None:
            raise Exception("Unexpected beacon report response received (OOM)")

    with alloc_fail(dev[0], 1,
                    "wpabuf_resize;wpas_add_beacon_rep"):
        token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a03000106")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report response not received (OOM -> empty report)")
        fields = ev.split(' ')
        if len(fields[4]) > 0:
            raise Exception("Unexpected beacon report received")

@remote_compatible
def test_rrm_beacon_req_table_bssid(dev, apdev):
    """Beacon request - beacon table mode - specific BSSID"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    bssid2 = hapd2.own_addr()
    token = run_req_beacon(hapd, addr, "51000000000002" + bssid2.replace(':', ''))
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if "bssid=" + bssid2 not in str(report):
        raise Exception("Report for unexpect BSS")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.1)
    if ev is not None:
        raise Exception("Unexpected beacon report response")

@remote_compatible
def test_rrm_beacon_req_table_ssid(dev, apdev):
    """Beacon request - beacon table mode - specific SSID"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    bssid2 = hapd2.own_addr()
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "0007" + "another".encode('hex'))
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if "bssid=" + bssid2 not in str(report):
        raise Exception("Report for unexpect BSS")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.1)
    if ev is not None:
        raise Exception("Unexpected beacon report response")
    hapd.dump_monitor()

    logger.info("Wildcard SSID")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "0000")
    for i in range(2):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report response not received")
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
    hapd.dump_monitor()

    logger.info("Too long SSID")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "0021" + 33*"00")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response (invalid SSID subelement in request)")
    hapd.dump_monitor()

@remote_compatible
def test_rrm_beacon_req_table_info(dev, apdev):
    """Beacon request - beacon table mode - Reporting Information subelement"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    logger.info("Unsupported reporting information 1")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "01020100")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response (incapable) is not received")

    fields = ev.split(' ')
    if fields[3] != "02":
        raise Exception("Beacon report response - unexpected mode (" + fields[3] + ")")
    hapd.dump_monitor()

    logger.info("Invalid reporting information length")
    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "010100")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response (invalid reporting information length)")
    hapd.dump_monitor()

@remote_compatible
def test_rrm_beacon_req_table_unknown_subelem(dev, apdev):
    """Beacon request - beacon table mode - unknown subelement"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "330101" + "fe00")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))

@remote_compatible
def test_rrm_beacon_req_table_truncated_subelem(dev, apdev):
    """Beacon request - beacon table mode - Truncated subelement"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "0001")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response (truncated subelement)")
    hapd.dump_monitor()

@remote_compatible
def test_rrm_beacon_req_table_rsne(dev, apdev):
    """Beacon request - beacon table mode - RSNE reporting"""
    params = hostapd.wpa2_params(ssid="rrm-rsn", passphrase="12345678")
    params["rrm_beacon_report"] = "1"
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm-rsn", psk="12345678", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000002ffffffffffff" + "020101" + "0a0130")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if not report.frame_body:
        raise Exception("Reported Frame Body subelement missing")
    if len(report.frame_body) != 12 + 22:
        raise Exception("Unexpected Reported Frame Body subelement length with Reporting Detail 1 and requested element RSNE")
    if binascii.unhexlify("30140100000fac040100000fac040100000fac020c00") not in report.frame_body:
        raise Exception("Full RSNE not found")

def test_rrm_beacon_req_table_vht(dev, apdev):
    """Beacon request - beacon table mode - VHT"""
    clear_scan_cache(apdev[0])
    try:
        hapd = None
        params = { "ssid": "rrm-vht",
                   "country_code": "FI",
                   "hw_mode": "a",
                   "channel": "36",
                   "ht_capab": "[HT40+]",
                   "ieee80211n": "1",
                   "ieee80211ac": "1",
                   "vht_oper_chwidth": "1",
                   "vht_oper_centr_freq_seg0_idx": "42",
                   "rrm_beacon_report": "1" }
        hapd = hostapd.add_ap(apdev[0], params)

        params = { "ssid": "test-vht40",
                   "country_code": "FI",
                   "hw_mode": "a",
                   "channel": "48",
                   "ieee80211n": "1",
                   "ieee80211ac": "1",
                   "ht_capab": "[HT40-]",
                   "vht_capab": "",
                   "vht_oper_chwidth": "0",
                   "vht_oper_centr_freq_seg0_idx": "0",
                 }
        hapd2 = hostapd.add_ap(apdev[1], params)

        dev[0].scan_for_bss(apdev[1]['bssid'], freq=5240)
        dev[0].connect("rrm-vht", key_mgmt="NONE", scan_freq="5180")

        addr = dev[0].own_addr()

        token = run_req_beacon(hapd, addr, "f0000000000002ffffffffffff")
        for i in range(2):
            ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
            if ev is None:
                raise Exception("Beacon report %d response not received" % i)
            fields = ev.split(' ')
            report = BeaconReport(binascii.unhexlify(fields[4]))
            logger.info("Received beacon report: " + str(report))
            if report.bssid_str == apdev[0]['bssid']:
                if report.opclass != 128 or report.channel != 36:
                    raise Exception("Incorrect opclass/channel for AP0")
            elif report.bssid_str == apdev[1]['bssid']:
                if report.opclass != 117 or report.channel != 48:
                    raise Exception("Incorrect opclass/channel for AP1")
    except Exception, e:
        if isinstance(e, Exception) and str(e) == "AP startup failed":
            if not vht_supported():
                raise HwsimSkip("80 MHz channel not supported in regulatory information")
        raise
    finally:
        dev[0].request("DISCONNECT")
        if hapd:
            hapd.request("DISABLE")
        subprocess.call(['iw', 'reg', 'set', '00'])
        dev[0].flush_scan_cache()

@remote_compatible
def test_rrm_beacon_req_active(dev, apdev):
    """Beacon request - active scan mode"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000640001ffffffffffff")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.bssid_str == apdev[0]['bssid']:
            if report.opclass != 81 or report.channel != 1:
                raise Exception("Incorrect opclass/channel for AP0")
        elif report.bssid_str == apdev[1]['bssid']:
            if report.opclass != 81 or report.channel != 11:
                raise Exception("Incorrect opclass/channel for AP1")

@remote_compatible
def test_rrm_beacon_req_active_ignore_old_result(dev, apdev):
    """Beacon request - active scan mode and old scan result"""
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another" })
    dev[0].scan_for_bss(apdev[1]['bssid'], freq=2412)
    hapd2.disable()

    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51010000640001ffffffffffff")

    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))
    if report.bssid_str == apdev[1]['bssid']:
        raise Exception("Old BSS reported")

    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response")

def start_ap(dev):
    id = dev.add_network()
    dev.set_network(id, "mode", "2")
    dev.set_network_quoted(id, "ssid", 32*'A')
    dev.set_network_quoted(id, "psk", "1234567890")
    dev.set_network(id, "frequency", "2412")
    dev.set_network(id, "scan_freq", "2412")
    dev.select_network(id)
    dev.wait_connected()

def test_rrm_beacon_req_active_many(dev, apdev):
    """Beacon request - active scan mode and many BSSs"""
    for i in range(1, 7):
        ifname = apdev[0]['ifname'] if i == 1 else apdev[0]['ifname'] + "-%d" % i
        hapd1 = hostapd.add_bss(apdev[0], ifname, 'bss-%i.conf' % i)
        hapd1.set('vendor_elements', "dd50" + 80*'bb')
        hapd1.request("UPDATE_BEACON")

    wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
    wpas.interface_add("wlan5")
    wpas.request("SET device_name " + 20*'a')
    start_ap(wpas)
    start_ap(dev[1])
    start_ap(dev[2])

    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    params['vendor_elements'] = "dd50" + 80*'aa'
    hapd = hostapd.add_ap(apdev[1]['ifname'], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    ok = False
    for j in range(3):
        token = run_req_beacon(hapd, addr, "51010000640001ffffffffffff")

        for i in range(10):
            ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
            if ev is None:
                raise Exception("Beacon report %d response not received" % i)
            fields = ev.split(' ')
            if len(fields[4]) == 0:
                break
            report = BeaconReport(binascii.unhexlify(fields[4]))
            logger.info("Received beacon report: " + str(report))
            if i == 9:
                ok = True
        if ok:
            break

@remote_compatible
def test_rrm_beacon_req_active_ap_channels(dev, apdev):
    """Beacon request - active scan mode with AP Channel Report subelement"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51ff0000640001ffffffffffff" + "dd0111" + "330351010b" + "dd0111")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.bssid_str == apdev[0]['bssid']:
            if report.opclass != 81 or report.channel != 1:
                raise Exception("Incorrect opclass/channel for AP0")
        elif report.bssid_str == apdev[1]['bssid']:
            if report.opclass != 81 or report.channel != 11:
                raise Exception("Incorrect opclass/channel for AP1")

@remote_compatible
def test_rrm_beacon_req_passive_ap_channels(dev, apdev):
    """Beacon request - passive scan mode with AP Channel Report subelement"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51ff0000640000ffffffffffff" + "330351010b" + "3300" + "dd00")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.bssid_str == apdev[0]['bssid']:
            if report.opclass != 81 or report.channel != 1:
                raise Exception("Incorrect opclass/channel for AP0")
        elif report.bssid_str == apdev[1]['bssid']:
            if report.opclass != 81 or report.channel != 11:
                raise Exception("Incorrect opclass/channel for AP1")

@remote_compatible
def test_rrm_beacon_req_active_single_channel(dev, apdev):
    """Beacon request - active scan mode with single channel"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "510b0000640001ffffffffffff")

    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received")
    fields = ev.split(' ')
    report = BeaconReport(binascii.unhexlify(fields[4]))
    logger.info("Received beacon report: " + str(report))

@remote_compatible
def test_rrm_beacon_req_active_ap_channels_unknown_opclass(dev, apdev):
    """Beacon request - active scan mode with AP Channel Report subelement and unknown opclass"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51ff0000640001ffffffffffff" + "3303ff010b")

    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response (refused) not received")

    fields = ev.split(' ')
    if fields[3] != "04":
        raise Exception("Unexpected beacon report mode: " + fields[3])

@remote_compatible
def test_rrm_beacon_req_active_ap_channel_oom(dev, apdev):
    """Beacon request - AP Channel Report subelement and OOM"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    with alloc_fail(dev[0], 1, "wpas_add_channels"):
        token = run_req_beacon(hapd, addr, "51ff0000640001ffffffffffff" + "330351010b")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        # allow either not to respond or send refused response
        if ev is not None:
            fields = ev.split(' ')
            if fields[3] != "04":
                raise Exception("Unexpected Beacon report during OOM with mode: " + fields[3])

@remote_compatible
def test_rrm_beacon_req_active_scan_fail(dev, apdev):
    """Beacon request - Active scan failure"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    with alloc_fail(dev[0], 1, "wpa_supplicant_trigger_scan"):
        token = run_req_beacon(hapd, addr, "51ff0000640001ffffffffffff" + "330351010b")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("No Beacon report")
        fields = ev.split(' ')
        if fields[3] != "04":
            raise Exception("Unexpected Beacon report contents: " + ev)

@remote_compatible
def test_rrm_beacon_req_active_zero_duration(dev, apdev):
    """Beacon request - Action scan and zero duration"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000000001ffffffffffff")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected Beacon report")

@remote_compatible
def test_rrm_beacon_req_active_fail_random(dev, apdev):
    """Beacon request - active scan mode os_get_random failure"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    with fail_test(dev[0], 1, "os_get_random;wpas_rm_handle_beacon_req"):
        token = run_req_beacon(hapd, addr, "51000000640001ffffffffffff")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report response not received")
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))

@remote_compatible
def test_rrm_beacon_req_passive(dev, apdev):
    """Beacon request - passive scan mode"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    hapd2 = hostapd.add_ap(apdev[1], { "ssid": "another", "channel": "11" })

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51000000640000ffffffffffff")

    for i in range(1, 3):
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report %d response not received" % i)
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.bssid_str == apdev[0]['bssid']:
            if report.opclass != 81 or report.channel != 1:
                raise Exception("Incorrect opclass/channel for AP0")
        elif report.bssid_str == apdev[1]['bssid']:
            if report.opclass != 81 or report.channel != 11:
                raise Exception("Incorrect opclass/channel for AP1")

@remote_compatible
def test_rrm_beacon_req_passive_no_match(dev, apdev):
    """Beacon request - passive scan mode and no matching BSS"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "51010000640000021122334455")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report %d response not received" % i)
    fields = ev.split(' ')
    if len(fields[4]) > 0:
        raise Exception("Unexpected beacon report BSS")

@remote_compatible
def test_rrm_beacon_req_passive_no_match_oom(dev, apdev):
    """Beacon request - passive scan mode and no matching BSS (OOM)"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    with alloc_fail(dev[0], 1, "wpabuf_resize;wpas_beacon_rep_scan_process"):
        token = run_req_beacon(hapd, addr, "51010000640000021122334455")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=0.2)
        if ev is not None:
            raise Exception("Unexpected Beacon report response during OOM")

    # verify reporting is still functional
    token = run_req_beacon(hapd, addr, "51010000640000021122334455")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report %d response not received" % i)
    fields = ev.split(' ')
    if len(fields[4]) > 0:
        raise Exception("Unexpected beacon report BSS")

@remote_compatible
def test_rrm_beacon_req_active_duration_mandatory(dev, apdev):
    """Beacon request - Action scan and duration mandatory"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    token = run_req_beacon(hapd, addr, "req_mode=10 51000000640001ffffffffffff")
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("No Beacon report response")
    fields = ev.split(' ')
    rrm = int(dev[0].get_driver_status_field("capa.rrm_flags"), 16)
    if rrm & 0x20 == 0x20:
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
    else:
        # Driver does not support scan dwell time setting, so wpa_supplicant
        # rejects the measurement request due to the mandatory duration using
        # Measurement Report Mode field Incapable=1.
        if fields[3] != '02':
            raise Exception("Unexpected Measurement Report Mode: " + fields[3])
        if len(fields[4]) > 0:
            raise Exception("Unexpected beacon report received")

def test_rrm_beacon_req_passive_scan_vht(dev, apdev):
    """Beacon request - passive scan mode - VHT"""
    clear_scan_cache(apdev[0])
    try:
        hapd = None
        params = { "ssid": "rrm-vht",
                   "country_code": "FI",
                   'ieee80211d': '1',
                   "hw_mode": "a",
                   "channel": "36",
                   "ht_capab": "[HT40+]",
                   "ieee80211n": "1",
                   "ieee80211ac": "1",
                   "vht_oper_chwidth": "1",
                   "vht_oper_centr_freq_seg0_idx": "42",
                   "rrm_beacon_report": "1" }
        hapd = hostapd.add_ap(apdev[0], params)

        dev[0].scan_for_bss(apdev[0]['bssid'], freq=5180)
        dev[0].connect("rrm-vht", key_mgmt="NONE", scan_freq="5180")

        addr = dev[0].own_addr()

        token = run_req_beacon(hapd, addr, "80000000640000ffffffffffff")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report response not received")
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.opclass != 128 or report.channel != 36:
            raise Exception("Incorrect opclass/channel for AP")

        token = run_req_beacon(hapd, addr, "82000000640000ffffffffffff")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report response not received")
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.opclass != 128 or report.channel != 36:
            raise Exception("Incorrect opclass/channel for AP")
    except Exception, e:
        if isinstance(e, Exception) and str(e) == "AP startup failed":
            if not vht_supported():
                raise HwsimSkip("80 MHz channel not supported in regulatory information")
        raise
    finally:
        if hapd:
            hapd.request("DISABLE")
        dev[0].request("DISCONNECT")
        dev[0].request("ABORT_SCAN")
        dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.5)
        subprocess.call(['iw', 'reg', 'set', '00'])
        dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=0.5)
        dev[0].flush_scan_cache()

def test_rrm_beacon_req_passive_scan_vht160(dev, apdev):
    """Beacon request - passive scan mode - VHT160"""
    clear_scan_cache(apdev[0])
    try:
        hapd = None
        params = { "ssid": "rrm-vht",
                   "country_code": "ZA",
                   'ieee80211d': '1',
                   "hw_mode": "a",
                   "channel": "104",
                   "ht_capab": "[HT40-]",
                   "ieee80211n": "1",
                   "ieee80211ac": "1",
                   "vht_oper_chwidth": "2",
                   "vht_oper_centr_freq_seg0_idx": "114",
                   "rrm_beacon_report": "1" }
        hapd = hostapd.add_ap(apdev[0], params)

        dev[0].scan_for_bss(apdev[0]['bssid'], freq=5520)
        dev[0].connect("rrm-vht", key_mgmt="NONE", scan_freq="5520")
        sig = dev[0].request("SIGNAL_POLL").splitlines()
        if "WIDTH=160 MHz" not in sig:
            raise Exception("Unexpected SIGNAL_POLL value: " + str(sig))

        addr = dev[0].own_addr()

        token = run_req_beacon(hapd, addr, "81000000640000ffffffffffff")
        ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
        if ev is None:
            raise Exception("Beacon report response not received")
        fields = ev.split(' ')
        report = BeaconReport(binascii.unhexlify(fields[4]))
        logger.info("Received beacon report: " + str(report))
        if report.opclass != 129 or report.channel != 104:
            raise Exception("Incorrect opclass/channel for AP")
    except Exception, e:
        if isinstance(e, Exception) and str(e) == "AP startup failed":
            raise HwsimSkip("ZA regulatory rule likely did not have DFS requirement removed")
        raise
    finally:
        if hapd:
            hapd.request("DISABLE")
        dev[0].request("DISCONNECT")
        dev[0].request("ABORT_SCAN")
        dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=0.5)
        subprocess.call(['iw', 'reg', 'set', '00'])
        dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=0.5)
        dev[0].flush_scan_cache()

def test_rrm_beacon_req_ap_errors(dev, apdev):
    """Beacon request - AP error cases"""
    try:
        run_rrm_beacon_req_ap_errors(dev, apdev)
    finally:
        dev[1].request("VENDOR_ELEM_REMOVE 13 *")

def run_rrm_beacon_req_ap_errors(dev, apdev):
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()
    dev[0].scan_for_bss(bssid, freq=2412)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()
    # Override RM capabilities (remove all)
    dev[1].request("VENDOR_ELEM_ADD 13 46050000000000")
    dev[1].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr1 = dev[1].own_addr()

    # Beacon request: Too short request data
    if "FAIL" not in hapd.request("REQ_BEACON " + addr + " 11"):
        raise Exception("Invalid REQ_BEACON accepted")

    # Beacon request: 02:00:00:00:01:00 does not support table beacon report
    if "FAIL" not in hapd.request("REQ_BEACON " + addr1 + " 51000000000002ffffffffffff"):
        raise Exception("Invalid REQ_BEACON accepted")

    # Beacon request: 02:00:00:00:01:00 does not support active beacon report
    if "FAIL" not in hapd.request("REQ_BEACON " + addr1 + " 51000000640001ffffffffffff"):
        raise Exception("Invalid REQ_BEACON accepted")

    # Beacon request: 02:00:00:00:01:00 does not support passive beacon report
    if "FAIL" not in hapd.request("REQ_BEACON " + addr1 + " 510b0000640000ffffffffffff"):
        raise Exception("Invalid REQ_BEACON accepted")

    # Beacon request: Unknown measurement mode 3
    if "FAIL" not in hapd.request("REQ_BEACON " + addr1 + " 510b0000640003ffffffffffff"):
        raise Exception("Invalid REQ_BEACON accepted")

    for i in range(257):
        if "FAIL" in hapd.request("REQ_BEACON " + addr + " 510b0000640000ffffffffffff"):
            raise Exception("REQ_BEACON failed")
        dev[0].dump_monitor()
        hapd.dump_monitor()

    with alloc_fail(hapd, 1, "wpabuf_alloc;hostapd_send_beacon_req"):
        if "FAIL" not in hapd.request("REQ_BEACON " + addr + " 510b0000640000ffffffffffff"):
            raise Exception("REQ_BEACON accepted during OOM")

    with fail_test(hapd, 1, "nl80211_send_frame_cmd;hostapd_send_beacon_req"):
        if "FAIL" not in hapd.request("REQ_BEACON " + addr + " 510b0000640000ffffffffffff"):
            raise Exception("REQ_BEACON accepted during failure testing")

def test_rrm_req_reject_oom(dev, apdev):
    """Radio measurement request - OOM while rejecting a request"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + addr.replace(':', '') + 2*bssid.replace(':', '') + "1000"

    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("SET ext_mgmt_frame_handling 1")

    with alloc_fail(dev[0], 1, "wpabuf_resize;wpas_rrm_handle_msr_req_element"):
        # "RRM: Parallel measurements are not supported, reject"
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "05000100002603010105"):
            raise Exception("MGMT_RX_PROCESS failed")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")
        ev = hapd.wait_event(["MGMT-RX"], timeout=0.2)
        if ev is not None:
            raise Exception("Unexpected beacon report response during OOM")

def test_rrm_req_when_rrm_not_used(dev, apdev):
    """Radio/link measurement request for non-RRM association"""
    params = { "ssid": "rrm" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + addr.replace(':', '') + 2*bssid.replace(':', '') + "1000"

    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("SET ext_mgmt_frame_handling 1")

    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "050001000026030100fe"):
        raise Exception("MGMT_RX_PROCESS failed")
    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "0502000000"):
        raise Exception("MGMT_RX_PROCESS failed")
    ev = hapd.wait_event(["MGMT-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected beacon report response when RRM is disabled")

    dev[0].request("REMOVE_NETWORK all")
    dev[0].wait_disconnected()
    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "050001000026030100fe"):
        raise Exception("MGMT_RX_PROCESS failed")
    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "0502000000"):
        raise Exception("MGMT_RX_PROCESS failed")

@remote_compatible
def test_rrm_req_proto(dev, apdev):
    """Radio measurement request - protocol testing"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0], params)
    bssid = hapd.own_addr()

    dev[0].request("SET LCI ")
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + addr.replace(':', '') + 2*bssid.replace(':', '') + "1000"

    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("SET ext_mgmt_frame_handling 1")

    tests = []
    # "RRM: Ignoring too short radio measurement request"
    tests += [ "0500", "050001", "05000100" ]
    # No measurement request element at all
    tests += [ "0500010000" ]
    # "RRM: Truncated element"
    tests += [ "050001000026" ]
    # "RRM: Element length too short"
    tests += [ "05000100002600", "0500010000260111", "050001000026021122" ]
    # "RRM: Element length too long"
    tests += [ "05000100002603", "0500010000260311", "050001000026031122" ]
    # "RRM: Enable bit not supported, ignore"
    tests += [ "05000100002603010200" ]
    # "RRM: Measurement report failed. TX power insertion not supported"
    #    OR
    # "RRM: Link measurement report failed. Request too short"
    tests += [ "0502" ]
    # Too short LCI request
    tests += [ "05000100002603010008" ]
    # Too short neighbor report response
    tests += [ "0505" ]
    # Unexpected neighbor report response
    tests += [ "050500", "050501", "050502", "050503", "050504", "050505" ]
    # Too short beacon request
    tests += [ "05000100002603010005",
               "0500010000260f010005112233445566778899aabbcc" ]
    # Unknown beacon report mode
    tests += [ "05000100002610010005112233445566778899aabbccdd" ]
    # "RRM: Expected Measurement Request element, but EID is 0"
    tests += [ "05000100000000" ]
    for t in tests:
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed")
    ev = hapd.wait_event(["MGMT-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected response seen at the AP: " + ev)

    tests = []
    # "RRM: Parallel measurements are not supported, reject"
    tests += [ "05000100002603010105" ]
    # "RRM: Unsupported radio measurement type 254"
    tests += [ "050001000026030100fe" ]
    # Reject LCI request
    tests += [ "0500010000260701000811223344" ]
    # Beacon report info subelement; no valid channels
    tests += [ "05000100002614010005112233445566008899aabbccdd01020000" ]
    for t in tests:
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed")
        ev = hapd.wait_event(["MGMT-RX"], timeout=5)
        if ev is None:
            raise Exception("No response seen at the AP")
        hapd.dump_monitor()

    dev[0].request("SET LCI " + lci)
    tests = []
    # "Not building LCI report - bad location subject"
    tests += [ "0500010000260701000811223344" ]
    for t in tests:
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed")
    ev = hapd.wait_event(["MGMT-RX"], timeout=0.2)
    if ev is not None:
        raise Exception("Unexpected response seen at the AP: " + ev)

    tests = []
    # LCI report or reject
    tests += [ "0500010000260701000801223344",
               "05000100002607010008010402ff",
               "05000100002608010008010402ffff" ]
    for t in tests:
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed")
        ev = hapd.wait_event(["MGMT-RX"], timeout=5)
        if ev is None:
            raise Exception("No response seen at the AP")
        hapd.dump_monitor()

    # Verify rejection of a group-addressed request frame
    hdr = "d0003a01" + "ffffffffffff" + 2*bssid.replace(':', '') + "1000"
    # "RRM: Parallel measurements are not supported, reject"
    t = "05000100002603010105"
    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
        raise Exception("MGMT_RX_PROCESS failed")
    ev = hapd.wait_event(["MGMT-RX"], timeout=0.1)
    if ev is not None:
        raise Exception("Unexpected response seen at the AP (broadcast request rejected)")
    hapd.dump_monitor()

    hapd.set("ext_mgmt_frame_handling", "0")
    dev[0].request("SET ext_mgmt_frame_handling 0")
    dev[0].request("SET LCI ")

def test_rrm_link_measurement(dev, apdev):
    """Radio measurement request - link measurement"""
    check_tx_power_support(dev[0])
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + addr.replace(':', '') + 2*bssid.replace(':', '') + "1000"

    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("SET ext_mgmt_frame_handling 1")

    if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "0502000000"):
        raise Exception("MGMT_RX_PROCESS failed")
    ev = hapd.wait_event(["MGMT-RX"], timeout=5)
    if ev is None:
        raise Exception("No link measurement report seen")

def test_rrm_link_measurement_oom(dev, apdev):
    """Radio measurement request - link measurement OOM"""
    check_tx_power_support(dev[0])
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + addr.replace(':', '') + 2*bssid.replace(':', '') + "1000"

    hapd.set("ext_mgmt_frame_handling", "1")
    dev[0].request("SET ext_mgmt_frame_handling 1")

    with alloc_fail(dev[0], 1, "wpabuf_alloc;wpas_rrm_handle_link_measurement_request"):
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "0502000000"):
            raise Exception("MGMT_RX_PROCESS failed")
        wait_fail_trigger(dev[0], "GET_ALLOC_FAIL")

    with fail_test(dev[0], 1, "wpas_rrm_handle_link_measurement_request"):
        if "OK" not in dev[0].request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "0502000000"):
            raise Exception("MGMT_RX_PROCESS failed")
        wait_fail_trigger(dev[0], "GET_FAIL")

    ev = hapd.wait_event(["MGMT-RX"], timeout=0.1)
    if ev is not None:
        raise Exception("Unexpected beacon report response during OOM")

def test_rrm_rep_parse_proto(dev, apdev):
    """hostapd rrm report parsing protocol testing"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    dev[0].request("SET LCI " + lci)
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + bssid.replace(':', '') + addr.replace(':', '') + bssid.replace(':', '') + "1000"
    hapd.set("ext_mgmt_frame_handling", "1")

    tests = [ "0501",
              "05ff01",
              "0501012703fffffe2700",
              "0501012703ffff05",
              "05010127ffffff05" + 252*"00",
              "0504012603ffffff2600",
              "0504012603ffff08",
              "0504012608ffff08ffffffffff",
              "0504012608ffff08ff04021234",
              "0504012608ffff08ff04020100",
              "0504012608ffff08ff0402ffff" ]
    for t in tests:
        if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed for " + t)

    if "OK" not in hapd.request("SET_NEIGHBOR 00:11:22:33:44:55 ssid=\"rrm\" nr=" + nr + " lci=" + lci):
        raise Exception("Set neighbor failed")
    if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + "0504012608ffff08ff04021000"):
        raise Exception("MGMT_RX_PROCESS failed")

def test_rrm_unexpected(dev, apdev):
    """hostapd unexpected rrm"""
    check_rrm_support(dev[0])

    params = { "ssid": "rrm", "rrm_neighbor_report": "0" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    addr = dev[0].own_addr()

    hdr = "d0003a01" + bssid.replace(':', '') + addr.replace(':', '') + bssid.replace(':', '') + "1000"
    hapd.set("ext_mgmt_frame_handling", "1")

    tests = [ "050401" ]
    for t in tests:
        if "OK" not in hapd.request("MGMT_RX_PROCESS freq=2412 datarate=0 ssi_signal=-30 frame=" + hdr + t):
            raise Exception("MGMT_RX_PROCESS failed for " + t)

def check_beacon_req(hapd, addr, idx):
    request = "51000000000002ffffffffffff" + "020100"
    token = hapd.request("REQ_BEACON " + addr + " " + request)
    if "FAIL" in token:
        raise Exception("REQ_BEACON failed (%d)" % idx)
    ev = hapd.wait_event(["BEACON-RESP-RX"], timeout=10)
    if ev is None:
        raise Exception("Beacon report response not received (%d)" % idx)

def test_rrm_reassociation(dev, apdev):
    """Radio measurement request - reassociation"""
    params = { "ssid": "rrm", "rrm_beacon_report": "1" }
    hapd = hostapd.add_ap(apdev[0]['ifname'], params)
    bssid = hapd.own_addr()

    addr = dev[0].own_addr()
    dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
    check_beacon_req(hapd, addr, 1)

    dev[0].request("REASSOCIATE")
    dev[0].wait_connected()
    check_beacon_req(hapd, addr, 1)

    hapd2 = hostapd.add_ap(apdev[1]['ifname'], params)
    bssid2 = hapd2.own_addr()
    dev[0].scan_for_bss(bssid2, freq=2412)
    dev[0].roam(bssid2)
    check_beacon_req(hapd2, addr, 2)

    dev[0].scan_for_bss(bssid, freq=2412)
    dev[0].roam(bssid)
    check_beacon_req(hapd, addr, 3)