Home | History | Annotate | Download | only in wifi
      1 //
      2 // Copyright (C) 2012 The Android Open Source Project
      3 //
      4 // Licensed under the Apache License, Version 2.0 (the "License");
      5 // you may not use this file except in compliance with the License.
      6 // You may obtain a copy of the License at
      7 //
      8 //      http://www.apache.org/licenses/LICENSE-2.0
      9 //
     10 // Unless required by applicable law or agreed to in writing, software
     11 // distributed under the License is distributed on an "AS IS" BASIS,
     12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13 // See the License for the specific language governing permissions and
     14 // limitations under the License.
     15 //
     16 
     17 #include "shill/wifi/wifi.h"
     18 
     19 #include <linux/if.h>
     20 #include <linux/netlink.h>  // Needs typedefs from sys/socket.h.
     21 #include <netinet/ether.h>
     22 #include <sys/socket.h>
     23 
     24 #include <map>
     25 #include <string>
     26 #include <vector>
     27 
     28 #include <base/files/file_util.h>
     29 #include <base/memory/ref_counted.h>
     30 #include <base/strings/string_number_conversions.h>
     31 #include <base/strings/string_split.h>
     32 #include <base/strings/string_util.h>
     33 #include <base/strings/stringprintf.h>
     34 #if defined(__ANDROID__)
     35 #include <dbus/service_constants.h>
     36 #else
     37 #include <chromeos/dbus/service_constants.h>
     38 #endif  // __ANDROID__
     39 
     40 #include "shill/dhcp/mock_dhcp_config.h"
     41 #include "shill/dhcp/mock_dhcp_provider.h"
     42 #include "shill/error.h"
     43 #include "shill/event_dispatcher.h"
     44 #include "shill/geolocation_info.h"
     45 #include "shill/ip_address_store.h"
     46 #include "shill/key_value_store.h"
     47 #include "shill/logging.h"
     48 #include "shill/manager.h"
     49 #include "shill/mock_adaptors.h"
     50 #include "shill/mock_device.h"
     51 #include "shill/mock_device_info.h"
     52 #include "shill/mock_eap_credentials.h"
     53 #include "shill/mock_event_dispatcher.h"
     54 #include "shill/mock_ipconfig.h"
     55 #include "shill/mock_link_monitor.h"
     56 #include "shill/mock_log.h"
     57 #include "shill/mock_manager.h"
     58 #include "shill/mock_metrics.h"
     59 #include "shill/mock_profile.h"
     60 #include "shill/mock_store.h"
     61 #include "shill/net/ieee80211.h"
     62 #include "shill/net/ip_address.h"
     63 #include "shill/net/mock_netlink_manager.h"
     64 #include "shill/net/mock_rtnl_handler.h"
     65 #include "shill/net/mock_time.h"
     66 #include "shill/net/netlink_message_matchers.h"
     67 #include "shill/net/netlink_packet.h"
     68 #include "shill/net/nl80211_attribute.h"
     69 #include "shill/net/nl80211_message.h"
     70 #include "shill/nice_mock_control.h"
     71 #include "shill/property_store_unittest.h"
     72 #include "shill/supplicant/mock_supplicant_bss_proxy.h"
     73 #include "shill/supplicant/mock_supplicant_eap_state_handler.h"
     74 #include "shill/supplicant/mock_supplicant_interface_proxy.h"
     75 #include "shill/supplicant/mock_supplicant_network_proxy.h"
     76 #include "shill/supplicant/mock_supplicant_process_proxy.h"
     77 #include "shill/supplicant/wpa_supplicant.h"
     78 #include "shill/technology.h"
     79 #include "shill/test_event_dispatcher.h"
     80 #include "shill/testing.h"
     81 #include "shill/wifi/mock_mac80211_monitor.h"
     82 #include "shill/wifi/mock_scan_session.h"
     83 #include "shill/wifi/mock_tdls_manager.h"
     84 #include "shill/wifi/mock_wake_on_wifi.h"
     85 #include "shill/wifi/mock_wifi_provider.h"
     86 #include "shill/wifi/mock_wifi_service.h"
     87 #include "shill/wifi/scan_session.h"
     88 #include "shill/wifi/wake_on_wifi.h"
     89 #include "shill/wifi/wifi_endpoint.h"
     90 #include "shill/wifi/wifi_service.h"
     91 
     92 using base::FilePath;
     93 using base::StringPrintf;
     94 using std::map;
     95 using std::set;
     96 using std::string;
     97 using std::unique_ptr;
     98 using std::vector;
     99 using ::testing::_;
    100 using ::testing::AnyNumber;
    101 using ::testing::AtLeast;
    102 using ::testing::ContainsRegex;
    103 using ::testing::DefaultValue;
    104 using ::testing::DoAll;
    105 using ::testing::EndsWith;
    106 using ::testing::HasSubstr;
    107 using ::testing::InSequence;
    108 using ::testing::Invoke;
    109 using ::testing::InvokeWithoutArgs;
    110 using ::testing::MakeMatcher;
    111 using ::testing::Matcher;
    112 using ::testing::MatcherInterface;
    113 using ::testing::MatchResultListener;
    114 using ::testing::Mock;
    115 using ::testing::NiceMock;
    116 using ::testing::NotNull;
    117 using ::testing::Ref;
    118 using ::testing::Return;
    119 using ::testing::ReturnNew;
    120 using ::testing::ReturnRef;
    121 using ::testing::SaveArg;
    122 using ::testing::SetArgumentPointee;
    123 using ::testing::StrEq;
    124 using ::testing::StrictMock;
    125 using ::testing::Test;
    126 using ::testing::Values;
    127 
    128 namespace shill {
    129 
    130 namespace {
    131 
    132 const uint16_t kNl80211FamilyId = 0x13;
    133 const uint16_t kRandomScanFrequency1 = 5600;
    134 const uint16_t kRandomScanFrequency2 = 5560;
    135 const uint16_t kRandomScanFrequency3 = 2422;
    136 const int kInterfaceIndex = 1234;
    137 
    138 // Bytes representing a NL80211_CMD_NEW_WIPHY message reporting the WiFi
    139 // capabilities of a NIC with wiphy index |kNewWiphyNlMsg_WiphyIndex| which
    140 // supports operating bands with the frequencies specified in
    141 // |kNewWiphyNlMsg_UniqueFrequencies|.
    142 const uint8_t kNewWiphyNlMsg[] = {
    143     0x68, 0x0c, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
    144     0xf6, 0x31, 0x00, 0x00, 0x03, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
    145     0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x02, 0x00, 0x70, 0x68, 0x79, 0x30,
    146     0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x2e, 0x00, 0x01, 0x00, 0x00, 0x00,
    147     0x05, 0x00, 0x3d, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x3e, 0x00,
    148     0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x3f, 0x00, 0xff, 0xff, 0xff, 0xff,
    149     0x08, 0x00, 0x40, 0x00, 0xff, 0xff, 0xff, 0xff, 0x05, 0x00, 0x59, 0x00,
    150     0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x00, 0x00,
    151     0x05, 0x00, 0x7b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x38, 0x00,
    152     0xd1, 0x08, 0x00, 0x00, 0x06, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00,
    153     0x05, 0x00, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x68, 0x00,
    154     0x04, 0x00, 0x8b, 0x00, 0x04, 0x00, 0x8c, 0x00, 0x18, 0x00, 0x39, 0x00,
    155     0x01, 0xac, 0x0f, 0x00, 0x05, 0xac, 0x0f, 0x00, 0x02, 0xac, 0x0f, 0x00,
    156     0x04, 0xac, 0x0f, 0x00, 0x06, 0xac, 0x0f, 0x00, 0x05, 0x00, 0x56, 0x00,
    157     0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x66, 0x00, 0x08, 0x00, 0x71, 0x00,
    158     0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x72, 0x00, 0x03, 0x00, 0x00, 0x00,
    159     0x08, 0x00, 0x69, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x6a, 0x00,
    160     0x03, 0x00, 0x00, 0x00, 0x24, 0x00, 0x20, 0x00, 0x04, 0x00, 0x01, 0x00,
    161     0x04, 0x00, 0x02, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    162     0x04, 0x00, 0x05, 0x00, 0x04, 0x00, 0x06, 0x00, 0x04, 0x00, 0x08, 0x00,
    163     0x04, 0x00, 0x09, 0x00, 0x50, 0x05, 0x16, 0x00, 0xf8, 0x01, 0x00, 0x00,
    164     0x14, 0x00, 0x03, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    165     0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00,
    166     0xef, 0x11, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x03, 0x00, 0x00, 0x00,
    167     0x05, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0x00, 0x28, 0x01, 0x01, 0x00,
    168     0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x6c, 0x09, 0x00, 0x00,
    169     0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00,
    170     0x08, 0x00, 0x01, 0x00, 0x71, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00,
    171     0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01, 0x00,
    172     0x76, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00,
    173     0x14, 0x00, 0x03, 0x00, 0x08, 0x00, 0x01, 0x00, 0x7b, 0x09, 0x00, 0x00,
    174     0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x04, 0x00,
    175     0x08, 0x00, 0x01, 0x00, 0x80, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00,
    176     0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x05, 0x00, 0x08, 0x00, 0x01, 0x00,
    177     0x85, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00,
    178     0x14, 0x00, 0x06, 0x00, 0x08, 0x00, 0x01, 0x00, 0x8a, 0x09, 0x00, 0x00,
    179     0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x07, 0x00,
    180     0x08, 0x00, 0x01, 0x00, 0x8f, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00,
    181     0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x08, 0x00, 0x08, 0x00, 0x01, 0x00,
    182     0x94, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00,
    183     0x14, 0x00, 0x09, 0x00, 0x08, 0x00, 0x01, 0x00, 0x99, 0x09, 0x00, 0x00,
    184     0x08, 0x00, 0x06, 0x00, 0x6c, 0x07, 0x00, 0x00, 0x14, 0x00, 0x0a, 0x00,
    185     0x08, 0x00, 0x01, 0x00, 0x9e, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00,
    186     0x6c, 0x07, 0x00, 0x00, 0x18, 0x00, 0x0b, 0x00, 0x08, 0x00, 0x01, 0x00,
    187     0xa3, 0x09, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x08, 0x00, 0x06, 0x00,
    188     0x6c, 0x07, 0x00, 0x00, 0x18, 0x00, 0x0c, 0x00, 0x08, 0x00, 0x01, 0x00,
    189     0xa8, 0x09, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x08, 0x00, 0x06, 0x00,
    190     0x6c, 0x07, 0x00, 0x00, 0x18, 0x00, 0x0d, 0x00, 0x08, 0x00, 0x01, 0x00,
    191     0xb4, 0x09, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x08, 0x00, 0x06, 0x00,
    192     0xd0, 0x07, 0x00, 0x00, 0xa0, 0x00, 0x02, 0x00, 0x0c, 0x00, 0x00, 0x00,
    193     0x08, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00,
    194     0x08, 0x00, 0x01, 0x00, 0x14, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00,
    195     0x10, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01, 0x00, 0x37, 0x00, 0x00, 0x00,
    196     0x04, 0x00, 0x02, 0x00, 0x10, 0x00, 0x03, 0x00, 0x08, 0x00, 0x01, 0x00,
    197     0x6e, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x0c, 0x00, 0x04, 0x00,
    198     0x08, 0x00, 0x01, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x05, 0x00,
    199     0x08, 0x00, 0x01, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00,
    200     0x08, 0x00, 0x01, 0x00, 0x78, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x07, 0x00,
    201     0x08, 0x00, 0x01, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x08, 0x00,
    202     0x08, 0x00, 0x01, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x09, 0x00,
    203     0x08, 0x00, 0x01, 0x00, 0x68, 0x01, 0x00, 0x00, 0x0c, 0x00, 0x0a, 0x00,
    204     0x08, 0x00, 0x01, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x0c, 0x00, 0x0b, 0x00,
    205     0x08, 0x00, 0x01, 0x00, 0x1c, 0x02, 0x00, 0x00, 0x54, 0x03, 0x01, 0x00,
    206     0x14, 0x00, 0x03, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    207     0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00,
    208     0xef, 0x11, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x03, 0x00, 0x00, 0x00,
    209     0x05, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0x00, 0xc0, 0x02, 0x01, 0x00,
    210     0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x3c, 0x14, 0x00, 0x00,
    211     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x1c, 0x00, 0x01, 0x00,
    212     0x08, 0x00, 0x01, 0x00, 0x50, 0x14, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    213     0x04, 0x00, 0x04, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    214     0x14, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01, 0x00, 0x64, 0x14, 0x00, 0x00,
    215     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x14, 0x00, 0x03, 0x00,
    216     0x08, 0x00, 0x01, 0x00, 0x78, 0x14, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00,
    217     0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x01, 0x00,
    218     0x8c, 0x14, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    219     0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    220     0x20, 0x00, 0x05, 0x00, 0x08, 0x00, 0x01, 0x00, 0xa0, 0x14, 0x00, 0x00,
    221     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00,
    222     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x06, 0x00,
    223     0x08, 0x00, 0x01, 0x00, 0xb4, 0x14, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    224     0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00,
    225     0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x07, 0x00, 0x08, 0x00, 0x01, 0x00,
    226     0xc8, 0x14, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    227     0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    228     0x20, 0x00, 0x08, 0x00, 0x08, 0x00, 0x01, 0x00, 0x7c, 0x15, 0x00, 0x00,
    229     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00,
    230     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x09, 0x00,
    231     0x08, 0x00, 0x01, 0x00, 0x90, 0x15, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    232     0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00,
    233     0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x01, 0x00,
    234     0xa4, 0x15, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    235     0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    236     0x20, 0x00, 0x0b, 0x00, 0x08, 0x00, 0x01, 0x00, 0xb8, 0x15, 0x00, 0x00,
    237     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00,
    238     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x0c, 0x00,
    239     0x08, 0x00, 0x01, 0x00, 0xcc, 0x15, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    240     0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00,
    241     0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x0d, 0x00, 0x08, 0x00, 0x01, 0x00,
    242     0xe0, 0x15, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    243     0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    244     0x20, 0x00, 0x0e, 0x00, 0x08, 0x00, 0x01, 0x00, 0xf4, 0x15, 0x00, 0x00,
    245     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00,
    246     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x0f, 0x00,
    247     0x08, 0x00, 0x01, 0x00, 0x08, 0x16, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    248     0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00,
    249     0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x10, 0x00, 0x08, 0x00, 0x01, 0x00,
    250     0x1c, 0x16, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    251     0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    252     0x20, 0x00, 0x11, 0x00, 0x08, 0x00, 0x01, 0x00, 0x30, 0x16, 0x00, 0x00,
    253     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00,
    254     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x20, 0x00, 0x12, 0x00,
    255     0x08, 0x00, 0x01, 0x00, 0x44, 0x16, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    256     0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x05, 0x00, 0x08, 0x00, 0x06, 0x00,
    257     0xd0, 0x07, 0x00, 0x00, 0x14, 0x00, 0x13, 0x00, 0x08, 0x00, 0x01, 0x00,
    258     0x71, 0x16, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    259     0x1c, 0x00, 0x14, 0x00, 0x08, 0x00, 0x01, 0x00, 0x85, 0x16, 0x00, 0x00,
    260     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x08, 0x00, 0x06, 0x00,
    261     0xd0, 0x07, 0x00, 0x00, 0x1c, 0x00, 0x15, 0x00, 0x08, 0x00, 0x01, 0x00,
    262     0x99, 0x16, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00,
    263     0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00, 0x1c, 0x00, 0x16, 0x00,
    264     0x08, 0x00, 0x01, 0x00, 0xad, 0x16, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00,
    265     0x04, 0x00, 0x04, 0x00, 0x08, 0x00, 0x06, 0x00, 0xd0, 0x07, 0x00, 0x00,
    266     0x1c, 0x00, 0x17, 0x00, 0x08, 0x00, 0x01, 0x00, 0xc1, 0x16, 0x00, 0x00,
    267     0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x04, 0x00, 0x08, 0x00, 0x06, 0x00,
    268     0xd0, 0x07, 0x00, 0x00, 0x64, 0x00, 0x02, 0x00, 0x0c, 0x00, 0x00, 0x00,
    269     0x08, 0x00, 0x01, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00,
    270     0x08, 0x00, 0x01, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x02, 0x00,
    271     0x08, 0x00, 0x01, 0x00, 0x78, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x03, 0x00,
    272     0x08, 0x00, 0x01, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x04, 0x00,
    273     0x08, 0x00, 0x01, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x05, 0x00,
    274     0x08, 0x00, 0x01, 0x00, 0x68, 0x01, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00,
    275     0x08, 0x00, 0x01, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x0c, 0x00, 0x07, 0x00,
    276     0x08, 0x00, 0x01, 0x00, 0x1c, 0x02, 0x00, 0x00, 0xd4, 0x00, 0x32, 0x00,
    277     0x08, 0x00, 0x01, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00,
    278     0x06, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00, 0x0b, 0x00, 0x00, 0x00,
    279     0x08, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x08, 0x00, 0x05, 0x00,
    280     0x13, 0x00, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00, 0x19, 0x00, 0x00, 0x00,
    281     0x08, 0x00, 0x07, 0x00, 0x25, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00,
    282     0x26, 0x00, 0x00, 0x00, 0x08, 0x00, 0x09, 0x00, 0x27, 0x00, 0x00, 0x00,
    283     0x08, 0x00, 0x0a, 0x00, 0x28, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0b, 0x00,
    284     0x2b, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x37, 0x00, 0x00, 0x00,
    285     0x08, 0x00, 0x0d, 0x00, 0x39, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0e, 0x00,
    286     0x3b, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0f, 0x00, 0x43, 0x00, 0x00, 0x00,
    287     0x08, 0x00, 0x10, 0x00, 0x31, 0x00, 0x00, 0x00, 0x08, 0x00, 0x11, 0x00,
    288     0x41, 0x00, 0x00, 0x00, 0x08, 0x00, 0x12, 0x00, 0x42, 0x00, 0x00, 0x00,
    289     0x08, 0x00, 0x13, 0x00, 0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x14, 0x00,
    290     0x51, 0x00, 0x00, 0x00, 0x08, 0x00, 0x15, 0x00, 0x54, 0x00, 0x00, 0x00,
    291     0x08, 0x00, 0x16, 0x00, 0x57, 0x00, 0x00, 0x00, 0x08, 0x00, 0x17, 0x00,
    292     0x55, 0x00, 0x00, 0x00, 0x08, 0x00, 0x18, 0x00, 0x2d, 0x00, 0x00, 0x00,
    293     0x08, 0x00, 0x19, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x08, 0x00, 0x1a, 0x00,
    294     0x30, 0x00, 0x00, 0x00, 0x08, 0x00, 0x6f, 0x00, 0x88, 0x13, 0x00, 0x00,
    295     0x04, 0x00, 0x6c, 0x00, 0xac, 0x03, 0x63, 0x00, 0x04, 0x00, 0x00, 0x00,
    296     0x84, 0x00, 0x01, 0x00, 0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
    297     0x06, 0x00, 0x65, 0x00, 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    298     0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00,
    299     0x06, 0x00, 0x65, 0x00, 0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    300     0x50, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00,
    301     0x06, 0x00, 0x65, 0x00, 0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    302     0x80, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00,
    303     0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    304     0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00,
    305     0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    306     0xe0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00,
    307     0x84, 0x00, 0x02, 0x00, 0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
    308     0x06, 0x00, 0x65, 0x00, 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    309     0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00,
    310     0x06, 0x00, 0x65, 0x00, 0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    311     0x50, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00,
    312     0x06, 0x00, 0x65, 0x00, 0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    313     0x80, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00,
    314     0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    315     0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00,
    316     0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    317     0xe0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00,
    318     0x84, 0x00, 0x03, 0x00, 0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
    319     0x06, 0x00, 0x65, 0x00, 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    320     0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00,
    321     0x06, 0x00, 0x65, 0x00, 0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    322     0x50, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00,
    323     0x06, 0x00, 0x65, 0x00, 0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    324     0x80, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00,
    325     0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    326     0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00,
    327     0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    328     0xe0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00,
    329     0x84, 0x00, 0x04, 0x00, 0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
    330     0x06, 0x00, 0x65, 0x00, 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    331     0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00,
    332     0x06, 0x00, 0x65, 0x00, 0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    333     0x50, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00,
    334     0x06, 0x00, 0x65, 0x00, 0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    335     0x80, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00,
    336     0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    337     0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00,
    338     0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    339     0xe0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00,
    340     0x04, 0x00, 0x05, 0x00, 0x04, 0x00, 0x06, 0x00, 0x84, 0x00, 0x07, 0x00,
    341     0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    342     0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x20, 0x00, 0x00, 0x00,
    343     0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    344     0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x50, 0x00, 0x00, 0x00,
    345     0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    346     0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x80, 0x00, 0x00, 0x00,
    347     0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    348     0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xb0, 0x00, 0x00, 0x00,
    349     0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    350     0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xe0, 0x00, 0x00, 0x00,
    351     0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x84, 0x00, 0x08, 0x00,
    352     0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    353     0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x20, 0x00, 0x00, 0x00,
    354     0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    355     0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x50, 0x00, 0x00, 0x00,
    356     0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    357     0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x80, 0x00, 0x00, 0x00,
    358     0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    359     0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xb0, 0x00, 0x00, 0x00,
    360     0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    361     0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xe0, 0x00, 0x00, 0x00,
    362     0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x84, 0x00, 0x09, 0x00,
    363     0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    364     0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x20, 0x00, 0x00, 0x00,
    365     0x06, 0x00, 0x65, 0x00, 0x30, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    366     0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x50, 0x00, 0x00, 0x00,
    367     0x06, 0x00, 0x65, 0x00, 0x60, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    368     0x70, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x80, 0x00, 0x00, 0x00,
    369     0x06, 0x00, 0x65, 0x00, 0x90, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    370     0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xb0, 0x00, 0x00, 0x00,
    371     0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    372     0xd0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xe0, 0x00, 0x00, 0x00,
    373     0x06, 0x00, 0x65, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x14, 0x01, 0x64, 0x00,
    374     0x04, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x06, 0x00, 0x65, 0x00,
    375     0xd0, 0x00, 0x00, 0x00, 0x14, 0x00, 0x02, 0x00, 0x06, 0x00, 0x65, 0x00,
    376     0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00,
    377     0x3c, 0x00, 0x03, 0x00, 0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
    378     0x06, 0x00, 0x65, 0x00, 0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    379     0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00,
    380     0x06, 0x00, 0x65, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    381     0xc0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00,
    382     0x3c, 0x00, 0x04, 0x00, 0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00,
    383     0x06, 0x00, 0x65, 0x00, 0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    384     0x40, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00,
    385     0x06, 0x00, 0x65, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    386     0xc0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00,
    387     0x04, 0x00, 0x05, 0x00, 0x04, 0x00, 0x06, 0x00, 0x1c, 0x00, 0x07, 0x00,
    388     0x06, 0x00, 0x65, 0x00, 0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    389     0xc0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00,
    390     0x14, 0x00, 0x08, 0x00, 0x06, 0x00, 0x65, 0x00, 0x40, 0x00, 0x00, 0x00,
    391     0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x09, 0x00,
    392     0x06, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    393     0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0x40, 0x00, 0x00, 0x00,
    394     0x06, 0x00, 0x65, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00,
    395     0xb0, 0x00, 0x00, 0x00, 0x06, 0x00, 0x65, 0x00, 0xc0, 0x00, 0x00, 0x00,
    396     0x06, 0x00, 0x65, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x79, 0x00,
    397     0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x06, 0x00, 0x50, 0x00, 0x78, 0x00,
    398     0x4c, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, 0x1c, 0x00, 0x01, 0x00,
    399     0x08, 0x00, 0x01, 0x00, 0x00, 0x08, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00,
    400     0x04, 0x00, 0x02, 0x00, 0x04, 0x00, 0x05, 0x00, 0x04, 0x00, 0x08, 0x00,
    401     0x18, 0x00, 0x02, 0x00, 0x08, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00,
    402     0x0c, 0x00, 0x02, 0x00, 0x04, 0x00, 0x03, 0x00, 0x04, 0x00, 0x09, 0x00,
    403     0x08, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00,
    404     0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x8f, 0x00, 0x03, 0x00, 0x00, 0x00,
    405     0x1e, 0x00, 0x94, 0x00, 0x42, 0x08, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff,
    406     0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    407     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    408 const uint32_t kNewWiphyNlMsg_WiphyIndex = 2;
    409 const int kNewWiphyNlMsg_Nl80211AttrWiphyOffset = 4;
    410 const uint16_t kNewWiphyNlMsg_UniqueFrequencies[] = {
    411     2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457,
    412     2462, 2467, 2472, 2484, 5180, 5200, 5220, 5240, 5260, 5280,
    413     5300, 5320, 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640,
    414     5660, 5680, 5700, 5745, 5765, 5785, 5805, 5825};
    415 
    416 const uint32_t kScanTriggerMsgWiphyIndex = 0;
    417 const uint8_t kActiveScanTriggerNlMsg[] = {
    418     0x44, 0x01, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    419     0x00, 0x00, 0x00, 0x00, 0x21, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
    420     0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00,
    421     0x0c, 0x00, 0x99, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    422     0x08, 0x00, 0x2d, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0c, 0x01, 0x2c, 0x00,
    423     0x08, 0x00, 0x00, 0x00, 0x6c, 0x09, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
    424     0x71, 0x09, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x76, 0x09, 0x00, 0x00,
    425     0x08, 0x00, 0x03, 0x00, 0x7b, 0x09, 0x00, 0x00, 0x08, 0x00, 0x04, 0x00,
    426     0x80, 0x09, 0x00, 0x00, 0x08, 0x00, 0x05, 0x00, 0x85, 0x09, 0x00, 0x00,
    427     0x08, 0x00, 0x06, 0x00, 0x8a, 0x09, 0x00, 0x00, 0x08, 0x00, 0x07, 0x00,
    428     0x8f, 0x09, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x94, 0x09, 0x00, 0x00,
    429     0x08, 0x00, 0x09, 0x00, 0x99, 0x09, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00,
    430     0x9e, 0x09, 0x00, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x3c, 0x14, 0x00, 0x00,
    431     0x08, 0x00, 0x0c, 0x00, 0x50, 0x14, 0x00, 0x00, 0x08, 0x00, 0x0d, 0x00,
    432     0x64, 0x14, 0x00, 0x00, 0x08, 0x00, 0x0e, 0x00, 0x78, 0x14, 0x00, 0x00,
    433     0x08, 0x00, 0x0f, 0x00, 0x8c, 0x14, 0x00, 0x00, 0x08, 0x00, 0x10, 0x00,
    434     0xa0, 0x14, 0x00, 0x00, 0x08, 0x00, 0x11, 0x00, 0xb4, 0x14, 0x00, 0x00,
    435     0x08, 0x00, 0x12, 0x00, 0xc8, 0x14, 0x00, 0x00, 0x08, 0x00, 0x13, 0x00,
    436     0x7c, 0x15, 0x00, 0x00, 0x08, 0x00, 0x14, 0x00, 0x90, 0x15, 0x00, 0x00,
    437     0x08, 0x00, 0x15, 0x00, 0xa4, 0x15, 0x00, 0x00, 0x08, 0x00, 0x16, 0x00,
    438     0xb8, 0x15, 0x00, 0x00, 0x08, 0x00, 0x17, 0x00, 0xcc, 0x15, 0x00, 0x00,
    439     0x08, 0x00, 0x18, 0x00, 0x1c, 0x16, 0x00, 0x00, 0x08, 0x00, 0x19, 0x00,
    440     0x30, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1a, 0x00, 0x44, 0x16, 0x00, 0x00,
    441     0x08, 0x00, 0x1b, 0x00, 0x58, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1c, 0x00,
    442     0x71, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x85, 0x16, 0x00, 0x00,
    443     0x08, 0x00, 0x1e, 0x00, 0x99, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1f, 0x00,
    444     0xad, 0x16, 0x00, 0x00, 0x08, 0x00, 0x20, 0x00, 0xc1, 0x16, 0x00, 0x00};
    445 
    446 const uint8_t kPassiveScanTriggerNlMsg[] = {
    447     0x40, 0x01, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    448     0x00, 0x00, 0x00, 0x00, 0x21, 0x01, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00,
    449     0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00,
    450     0x0c, 0x00, 0x99, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    451     0x04, 0x00, 0x2d, 0x00, 0x0c, 0x01, 0x2c, 0x00, 0x08, 0x00, 0x00, 0x00,
    452     0x6c, 0x09, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x71, 0x09, 0x00, 0x00,
    453     0x08, 0x00, 0x02, 0x00, 0x76, 0x09, 0x00, 0x00, 0x08, 0x00, 0x03, 0x00,
    454     0x7b, 0x09, 0x00, 0x00, 0x08, 0x00, 0x04, 0x00, 0x80, 0x09, 0x00, 0x00,
    455     0x08, 0x00, 0x05, 0x00, 0x85, 0x09, 0x00, 0x00, 0x08, 0x00, 0x06, 0x00,
    456     0x8a, 0x09, 0x00, 0x00, 0x08, 0x00, 0x07, 0x00, 0x8f, 0x09, 0x00, 0x00,
    457     0x08, 0x00, 0x08, 0x00, 0x94, 0x09, 0x00, 0x00, 0x08, 0x00, 0x09, 0x00,
    458     0x99, 0x09, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x9e, 0x09, 0x00, 0x00,
    459     0x08, 0x00, 0x0b, 0x00, 0x3c, 0x14, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00,
    460     0x50, 0x14, 0x00, 0x00, 0x08, 0x00, 0x0d, 0x00, 0x64, 0x14, 0x00, 0x00,
    461     0x08, 0x00, 0x0e, 0x00, 0x78, 0x14, 0x00, 0x00, 0x08, 0x00, 0x0f, 0x00,
    462     0x8c, 0x14, 0x00, 0x00, 0x08, 0x00, 0x10, 0x00, 0xa0, 0x14, 0x00, 0x00,
    463     0x08, 0x00, 0x11, 0x00, 0xb4, 0x14, 0x00, 0x00, 0x08, 0x00, 0x12, 0x00,
    464     0xc8, 0x14, 0x00, 0x00, 0x08, 0x00, 0x13, 0x00, 0x7c, 0x15, 0x00, 0x00,
    465     0x08, 0x00, 0x14, 0x00, 0x90, 0x15, 0x00, 0x00, 0x08, 0x00, 0x15, 0x00,
    466     0xa4, 0x15, 0x00, 0x00, 0x08, 0x00, 0x16, 0x00, 0xb8, 0x15, 0x00, 0x00,
    467     0x08, 0x00, 0x17, 0x00, 0xcc, 0x15, 0x00, 0x00, 0x08, 0x00, 0x18, 0x00,
    468     0x1c, 0x16, 0x00, 0x00, 0x08, 0x00, 0x19, 0x00, 0x30, 0x16, 0x00, 0x00,
    469     0x08, 0x00, 0x1a, 0x00, 0x44, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1b, 0x00,
    470     0x58, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1c, 0x00, 0x71, 0x16, 0x00, 0x00,
    471     0x08, 0x00, 0x1d, 0x00, 0x85, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1e, 0x00,
    472     0x99, 0x16, 0x00, 0x00, 0x08, 0x00, 0x1f, 0x00, 0xad, 0x16, 0x00, 0x00,
    473     0x08, 0x00, 0x20, 0x00, 0xc1, 0x16, 0x00, 0x00};
    474 
    475 }  // namespace
    476 
    477 class WiFiPropertyTest : public PropertyStoreTest {
    478  public:
    479   WiFiPropertyTest()
    480       : metrics_(nullptr),
    481         device_(
    482             new WiFi(control_interface(), dispatcher(), &metrics_,
    483                      manager(), "wifi", "", kInterfaceIndex)) {
    484   }
    485   virtual ~WiFiPropertyTest() {}
    486 
    487  protected:
    488   MockMetrics metrics_;
    489   WiFiRefPtr device_;
    490 };
    491 
    492 TEST_F(WiFiPropertyTest, Contains) {
    493   EXPECT_TRUE(device_->store().Contains(kNameProperty));
    494   EXPECT_FALSE(device_->store().Contains(""));
    495 }
    496 
    497 TEST_F(WiFiPropertyTest, SetProperty) {
    498   {
    499     Error error;
    500     EXPECT_TRUE(device_->mutable_store()->SetAnyProperty(
    501         kBgscanSignalThresholdProperty, PropertyStoreTest::kInt32V, &error));
    502   }
    503   {
    504     Error error;
    505     EXPECT_TRUE(device_->mutable_store()->SetAnyProperty(
    506         kScanIntervalProperty, PropertyStoreTest::kUint16V, &error));
    507   }
    508   // Ensure that an attempt to write a R/O property returns InvalidArgs error.
    509   {
    510     Error error;
    511     EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
    512         kScanningProperty, PropertyStoreTest::kBoolV, &error));
    513     ASSERT_TRUE(error.IsFailure());
    514     EXPECT_EQ(Error::kInvalidArguments, error.type());
    515   }
    516 
    517   {
    518     Error error;
    519     EXPECT_TRUE(device_->mutable_store()->SetAnyProperty(
    520         kBgscanMethodProperty,
    521         brillo::Any(string(WPASupplicant::kNetworkBgscanMethodSimple)),
    522         &error));
    523   }
    524 
    525   {
    526     Error error;
    527     EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
    528         kBgscanMethodProperty,
    529         brillo::Any(string("not a real scan method")),
    530         &error));
    531   }
    532 }
    533 
    534 TEST_F(WiFiPropertyTest, BgscanMethodProperty) {
    535   EXPECT_NE(WPASupplicant::kNetworkBgscanMethodLearn,
    536             WiFi::kDefaultBgscanMethod);
    537   EXPECT_TRUE(device_->bgscan_method_.empty());
    538 
    539   string method;
    540   Error unused_error;
    541   EXPECT_TRUE(device_->store().GetStringProperty(
    542       kBgscanMethodProperty, &method, &unused_error));
    543   EXPECT_EQ(WiFi::kDefaultBgscanMethod, method);
    544   EXPECT_EQ(WPASupplicant::kNetworkBgscanMethodSimple, method);
    545 
    546   Error error;
    547   EXPECT_TRUE(device_->mutable_store()->SetAnyProperty(
    548       kBgscanMethodProperty,
    549       brillo::Any(string(WPASupplicant::kNetworkBgscanMethodLearn)),
    550       &error));
    551   EXPECT_EQ(WPASupplicant::kNetworkBgscanMethodLearn, device_->bgscan_method_);
    552   EXPECT_TRUE(device_->store().GetStringProperty(
    553       kBgscanMethodProperty, &method, &unused_error));
    554   EXPECT_EQ(WPASupplicant::kNetworkBgscanMethodLearn, method);
    555 
    556   EXPECT_TRUE(device_->mutable_store()->ClearProperty(
    557       kBgscanMethodProperty, &error));
    558   EXPECT_TRUE(device_->store().GetStringProperty(
    559       kBgscanMethodProperty, &method, &unused_error));
    560   EXPECT_EQ(WiFi::kDefaultBgscanMethod, method);
    561   EXPECT_TRUE(device_->bgscan_method_.empty());
    562 }
    563 
    564 MATCHER_P(EndpointMatch, endpoint, "") {
    565   return
    566       arg->ssid() == endpoint->ssid() &&
    567       arg->network_mode() == endpoint->network_mode() &&
    568       arg->security_mode() == endpoint->security_mode();
    569 }
    570 
    571 
    572 class WiFiObjectTest : public ::testing::TestWithParam<string> {
    573  public:
    574   // Note: When this constructor is called (via the initialization lists in the
    575   // constructors of WiFiMainTest and WiFiTimerTest), |dispatcher| will point to
    576   // an uninitialized EventDispatcher. Any functions (including constructors in
    577   // the initialization list) that use the message loop should not be called in
    578   // this constructor, since the delayed initialization of the message loop can
    579   // cause concurrency-related bugs. (See crbug.com/509138 for an example.)
    580   explicit WiFiObjectTest(EventDispatcher* dispatcher)
    581       : event_dispatcher_(dispatcher),
    582         metrics_(nullptr),
    583         manager_(&control_interface_, nullptr, &metrics_),
    584         device_info_(&control_interface_, dispatcher, &metrics_, &manager_),
    585         wifi_(new WiFi(&control_interface_, dispatcher, &metrics_, &manager_,
    586                        kDeviceName, kDeviceAddress, kInterfaceIndex)),
    587         bss_counter_(0),
    588         mac80211_monitor_(new StrictMock<MockMac80211Monitor>(
    589             dispatcher, kDeviceName, WiFi::kStuckQueueLengthThreshold,
    590             base::Closure(), &metrics_)),
    591         supplicant_process_proxy_(new NiceMock<MockSupplicantProcessProxy>()),
    592         supplicant_bss_proxy_(new NiceMock<MockSupplicantBSSProxy>()),
    593         dhcp_config_(new MockDHCPConfig(&control_interface_, kDeviceName)),
    594         adaptor_(new DeviceMockAdaptor()),
    595         eap_state_handler_(new NiceMock<MockSupplicantEAPStateHandler>()),
    596         supplicant_interface_proxy_(
    597             new NiceMock<MockSupplicantInterfaceProxy>()),
    598         supplicant_network_proxy_(new NiceMock<MockSupplicantNetworkProxy>()) {
    599     wifi_->mac80211_monitor_.reset(mac80211_monitor_);
    600     wifi_->supplicant_process_proxy_.reset(supplicant_process_proxy_);
    601     InstallMockScanSession();
    602     ON_CALL(*supplicant_process_proxy_, CreateInterface(_, _))
    603         .WillByDefault(DoAll(SetArgumentPointee<1>(string("/default/path")),
    604                              Return(true)));
    605     ON_CALL(*supplicant_process_proxy_, GetInterface(_, _))
    606         .WillByDefault(DoAll(SetArgumentPointee<1>(string("/default/path")),
    607                              Return(true)));
    608     ON_CALL(*supplicant_interface_proxy_.get(), AddNetwork(_, _))
    609         .WillByDefault(DoAll(SetArgumentPointee<1>(string("/default/path")),
    610                              Return(true)));
    611     ON_CALL(*supplicant_interface_proxy_.get(), Disconnect())
    612         .WillByDefault(Return(true));
    613     ON_CALL(*supplicant_interface_proxy_.get(), RemoveNetwork(_))
    614         .WillByDefault(Return(true));
    615     ON_CALL(*supplicant_interface_proxy_.get(), Scan(_))
    616         .WillByDefault(Return(true));
    617     ON_CALL(*supplicant_network_proxy_.get(), SetEnabled(_))
    618         .WillByDefault(Return(true));
    619 
    620     EXPECT_CALL(*mac80211_monitor_, UpdateConnectedState(_))
    621         .Times(AnyNumber());
    622 
    623     ON_CALL(dhcp_provider_, CreateIPv4Config(_, _, _, _))
    624         .WillByDefault(Return(dhcp_config_));
    625     ON_CALL(*dhcp_config_.get(), RequestIP()).WillByDefault(Return(true));
    626     ON_CALL(*manager(), IsSuspending()).WillByDefault(Return(false));
    627 
    628     ON_CALL(control_interface_, CreateSupplicantInterfaceProxy(_, _))
    629         .WillByDefault(ReturnAndReleasePointee(&supplicant_interface_proxy_));
    630     ON_CALL(control_interface_, CreateSupplicantBSSProxy(_, _))
    631         .WillByDefault(ReturnAndReleasePointee(&supplicant_bss_proxy_));
    632     ON_CALL(control_interface_, CreateSupplicantNetworkProxy(_))
    633         .WillByDefault(ReturnAndReleasePointee(&supplicant_network_proxy_));
    634     Nl80211Message::SetMessageType(kNl80211FamilyId);
    635 
    636     // Transfers ownership.
    637     wifi_->eap_state_handler_.reset(eap_state_handler_);
    638 
    639     wifi_->provider_ = &wifi_provider_;
    640     wifi_->time_ = &time_;
    641     wifi_->netlink_manager_ = &netlink_manager_;
    642     wifi_->progressive_scan_enabled_ = true;
    643     wifi_->adaptor_.reset(adaptor_);  // Transfers ownership.
    644 
    645     // The following is only useful when a real |ScanSession| is used; it is
    646     // ignored by |MockScanSession|.
    647     wifi_->all_scan_frequencies_.insert(kRandomScanFrequency1);
    648     wifi_->all_scan_frequencies_.insert(kRandomScanFrequency2);
    649     wifi_->all_scan_frequencies_.insert(kRandomScanFrequency3);
    650   }
    651 
    652   virtual void SetUp() {
    653     // EnableScopes... so that we can EXPECT_CALL for scoped log messages.
    654     ScopeLogger::GetInstance()->EnableScopesByName("wifi");
    655     ScopeLogger::GetInstance()->set_verbose_level(3);
    656     static_cast<Device*>(wifi_.get())->rtnl_handler_ = &rtnl_handler_;
    657     wifi_->set_dhcp_provider(&dhcp_provider_);
    658     ON_CALL(manager_, device_info()).WillByDefault(Return(&device_info_));
    659     EXPECT_CALL(manager_, UpdateEnabledTechnologies()).Times(AnyNumber());
    660     EXPECT_CALL(*supplicant_bss_proxy_, Die()).Times(AnyNumber());
    661     // Must be called here instead of in the constructor so that the destructor
    662     // of SimpleAlarmTimer will not be invoked before the EventDispatcher is
    663     // properly constructed (crbug.com/509138).
    664     InstallMockWakeOnWiFi();
    665   }
    666 
    667   virtual void TearDown() {
    668     EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(_))
    669         .WillRepeatedly(Return(nullptr));
    670     wifi_->SelectService(nullptr);
    671     if (supplicant_bss_proxy_.get()) {
    672       EXPECT_CALL(*supplicant_bss_proxy_, Die());
    673     }
    674     EXPECT_CALL(*mac80211_monitor_, Stop());
    675     // must Stop WiFi instance, to clear its list of services.
    676     // otherwise, the WiFi instance will not be deleted. (because
    677     // services reference a WiFi instance, creating a cycle.)
    678     wifi_->Stop(nullptr, ResultCallback());
    679     wifi_->set_dhcp_provider(nullptr);
    680     // Reset scope logging, to avoid interfering with other tests.
    681     ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
    682     ScopeLogger::GetInstance()->set_verbose_level(0);
    683   }
    684 
    685   // Needs to be public since it is called via Invoke().
    686   void StopWiFi() {
    687     EXPECT_CALL(*mac80211_monitor_, Stop());
    688     wifi_->SetEnabled(false);  // Stop(nullptr, ResultCallback());
    689   }
    690 
    691   void ResetPendingService() {
    692     SetPendingService(nullptr);
    693   }
    694 
    695   size_t GetScanFrequencyCount() const {
    696     return wifi_->all_scan_frequencies_.size();
    697   }
    698 
    699   void SetScanSize(int min, int max) {
    700     wifi_->min_frequencies_to_scan_ = min;
    701     wifi_->max_frequencies_to_scan_ = max;
    702   }
    703 
    704   // This clears WiFi::scan_session_, thereby allowing WiFi::Scan to create a
    705   // real scan session.
    706   void ClearScanSession() {
    707     wifi_->scan_session_.reset();
    708   }
    709 
    710   bool IsScanSessionNull() {
    711     return !wifi_->scan_session_;
    712   }
    713 
    714   void InstallMockScanSession() {
    715     WiFiProvider::FrequencyCountList previous_frequencies;
    716     set<uint16_t> available_frequencies;
    717     ScanSession::FractionList fractions;
    718     ScanSession::OnScanFailed null_callback;
    719     scan_session_ = new MockScanSession(&netlink_manager_,
    720                                         event_dispatcher_,
    721                                         previous_frequencies,
    722                                         available_frequencies,
    723                                         0,
    724                                         fractions,
    725                                         0,
    726                                         0,
    727                                         null_callback,
    728                                         nullptr);
    729     wifi_->scan_session_.reset(scan_session_);
    730   }
    731 
    732   void InstallMockWakeOnWiFi() {
    733     wake_on_wifi_ = new MockWakeOnWiFi(&netlink_manager_, event_dispatcher_,
    734                                        &metrics_);
    735     wifi_->wake_on_wifi_.reset(wake_on_wifi_);
    736   }
    737 
    738   // Or DisableProgressiveScan()...
    739   void EnableFullScan() {
    740     wifi_->progressive_scan_enabled_ = false;
    741   }
    742 
    743   void OnTriggerScanResponse(const Nl80211Message& message) {
    744     wifi_->scan_session_->OnTriggerScanResponse(message);
    745   }
    746 
    747   void SetScanState(WiFi::ScanState new_state,
    748                     WiFi::ScanMethod new_method,
    749                     const char* reason) {
    750     wifi_->SetScanState(new_state, new_method, reason);
    751   }
    752 
    753   void VerifyScanState(WiFi::ScanState state, WiFi::ScanMethod method) const {
    754     EXPECT_EQ(state, wifi_->scan_state_);
    755     EXPECT_EQ(method, wifi_->scan_method_);
    756   }
    757 
    758   void SetRoamThresholdMember(uint16_t threshold) {
    759     wifi_->roam_threshold_db_ = threshold;
    760   }
    761 
    762   bool SetRoamThreshold(uint16_t threshold) {
    763     return wifi_->SetRoamThreshold(threshold, nullptr);
    764   }
    765 
    766   uint16_t GetRoamThreshold() const {
    767     return wifi_->GetRoamThreshold(nullptr);
    768   }
    769 
    770  protected:
    771   typedef scoped_refptr<MockWiFiService> MockWiFiServiceRefPtr;
    772 
    773   // Simulate the course of events when the last endpoint of a service is
    774   // removed.
    775   class EndpointRemovalHandler {
    776    public:
    777     EndpointRemovalHandler(WiFiRefPtr wifi, const WiFiServiceRefPtr& service)
    778         : wifi_(wifi), service_(service) {}
    779     virtual ~EndpointRemovalHandler() {}
    780 
    781     WiFiServiceRefPtr OnEndpointRemoved(
    782         const WiFiEndpointConstRefPtr& endpoint) {
    783       wifi_->DisassociateFromService(service_);
    784       return service_;
    785     }
    786 
    787    private:
    788     WiFiRefPtr wifi_;
    789     WiFiServiceRefPtr service_;
    790   };
    791 
    792   EndpointRemovalHandler* MakeEndpointRemovalHandler(
    793       const WiFiServiceRefPtr& service) {
    794     return new EndpointRemovalHandler(wifi_, service);
    795   }
    796   void CancelScanTimer() {
    797     wifi_->scan_timer_callback_.Cancel();
    798   }
    799   // This function creates a new endpoint with a mode set to |mode|.  We
    800   // synthesize new |path| and |bssid| values, since we don't really care
    801   // what they are for unit tests.  If "use_ssid" is true, we used the
    802   // passed-in ssid, otherwise we create a synthesized value for it as well.
    803   WiFiEndpointRefPtr MakeNewEndpoint(const char* mode,
    804                                      bool use_ssid,
    805                                      string* ssid,
    806                                      string* path,
    807                                      string* bssid) {
    808     bss_counter_++;
    809     if (!use_ssid) {
    810       *ssid = StringPrintf("ssid%d", bss_counter_);
    811     }
    812     *path = StringPrintf("/interface/bss%d", bss_counter_);
    813     *bssid = StringPrintf("00:00:00:00:00:%02x", bss_counter_);
    814     WiFiEndpointRefPtr endpoint = MakeEndpointWithMode(*ssid, *bssid, mode);
    815     EXPECT_CALL(wifi_provider_,
    816                 OnEndpointAdded(EndpointMatch(endpoint))).Times(1);
    817     return endpoint;
    818   }
    819   WiFiEndpointRefPtr MakeEndpoint(const string& ssid, const string& bssid) {
    820     return MakeEndpointWithMode(ssid, bssid, kNetworkModeInfrastructure);
    821   }
    822   WiFiEndpointRefPtr MakeEndpointWithMode(
    823       const string& ssid, const string& bssid, const string& mode) {
    824     return WiFiEndpoint::MakeOpenEndpoint(
    825         &control_interface_, nullptr, ssid, bssid, mode, 0, 0);
    826   }
    827   MockWiFiServiceRefPtr MakeMockServiceWithSSID(
    828       vector<uint8_t> ssid, const std::string& security) {
    829     return new NiceMock<MockWiFiService>(
    830         &control_interface_,
    831         event_dispatcher_,
    832         &metrics_,
    833         &manager_,
    834         &wifi_provider_,
    835         ssid,
    836         kModeManaged,
    837         security,
    838         false);
    839   }
    840   MockWiFiServiceRefPtr MakeMockService(const std::string& security) {
    841     return MakeMockServiceWithSSID(vector<uint8_t>(1, 'a'), security);
    842   }
    843   string MakeNewEndpointAndService(int16_t signal_strength,
    844                                    uint16_t frequency,
    845                                    const char* mode,
    846                                    WiFiEndpointRefPtr* endpoint_ptr,
    847                                    MockWiFiServiceRefPtr* service_ptr) {
    848     string ssid;
    849     string path;
    850     string bssid;
    851     WiFiEndpointRefPtr endpoint =
    852         MakeNewEndpoint(mode, false, &ssid, &path, &bssid);
    853     MockWiFiServiceRefPtr service =
    854         MakeMockServiceWithSSID(endpoint->ssid(), endpoint->security_mode());
    855     EXPECT_CALL(wifi_provider_, FindServiceForEndpoint(EndpointMatch(endpoint)))
    856         .WillRepeatedly(Return(service));
    857     ON_CALL(*service, GetEndpointCount()).WillByDefault(Return(1));
    858     ReportBSS(path, ssid, bssid, signal_strength, frequency, mode);
    859     if (service_ptr) {
    860       *service_ptr = service;
    861     }
    862     if (endpoint_ptr) {
    863       *endpoint_ptr = endpoint;
    864     }
    865     return path;
    866   }
    867   string AddEndpointToService(
    868       WiFiServiceRefPtr service,
    869       int16_t signal_strength,
    870       uint16_t frequency,
    871       const char* mode,
    872       WiFiEndpointRefPtr* endpoint_ptr) {
    873     string ssid(service->ssid().begin(), service->ssid().end());
    874     string path;
    875     string bssid;
    876     WiFiEndpointRefPtr endpoint =
    877         MakeNewEndpoint(mode, true, &ssid, &path, &bssid);
    878     EXPECT_CALL(wifi_provider_, FindServiceForEndpoint(EndpointMatch(endpoint)))
    879         .WillRepeatedly(Return(service));
    880     ReportBSS(path, ssid, bssid, signal_strength, frequency, mode);
    881     if (endpoint_ptr) {
    882       *endpoint_ptr = endpoint;
    883     }
    884     return path;
    885   }
    886   void InitiateConnect(WiFiServiceRefPtr service) {
    887     wifi_->ConnectTo(service.get());
    888   }
    889   void InitiateDisconnect(WiFiServiceRefPtr service) {
    890     wifi_->DisconnectFrom(service.get());
    891   }
    892   void InitiateDisconnectIfActive(WiFiServiceRefPtr service) {
    893     wifi_->DisconnectFromIfActive(service.get());
    894   }
    895   MockWiFiServiceRefPtr SetupConnectingService(
    896       const string& network_path,
    897       WiFiEndpointRefPtr* endpoint_ptr,
    898       string* bss_path_ptr) {
    899     MockWiFiServiceRefPtr service;
    900     WiFiEndpointRefPtr endpoint;
    901     string bss_path(MakeNewEndpointAndService(
    902         0, 0, kNetworkModeAdHoc, &endpoint, &service));
    903     if (!network_path.empty()) {
    904       EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
    905       EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(_, _))
    906           .WillOnce(DoAll(SetArgumentPointee<1>(network_path), Return(true)));
    907       EXPECT_CALL(*GetSupplicantInterfaceProxy(),
    908                   SetHT40Enable(network_path, true));
    909       EXPECT_CALL(*GetSupplicantInterfaceProxy(), SelectNetwork(network_path));
    910     }
    911     EXPECT_CALL(*service, SetState(Service::kStateAssociating));
    912     InitiateConnect(service);
    913     Mock::VerifyAndClearExpectations(service.get());
    914     EXPECT_FALSE(GetPendingTimeout().IsCancelled());
    915     if (endpoint_ptr) {
    916       *endpoint_ptr = endpoint;
    917     }
    918     if (bss_path_ptr) {
    919       *bss_path_ptr = bss_path;
    920     }
    921     return service;
    922   }
    923 
    924   MockWiFiServiceRefPtr SetupConnectedService(
    925       const string& network_path,
    926       WiFiEndpointRefPtr* endpoint_ptr,
    927       string* bss_path_ptr) {
    928     WiFiEndpointRefPtr endpoint;
    929     string bss_path;
    930     MockWiFiServiceRefPtr service =
    931         SetupConnectingService(network_path, &endpoint, &bss_path);
    932     if (endpoint_ptr) {
    933       *endpoint_ptr = endpoint;
    934     }
    935     if (bss_path_ptr) {
    936       *bss_path_ptr = bss_path;
    937     }
    938     EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
    939     ReportCurrentBSSChanged(bss_path);
    940     EXPECT_TRUE(GetPendingTimeout().IsCancelled());
    941     Mock::VerifyAndClearExpectations(service.get());
    942 
    943     EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
    944     EXPECT_CALL(*service, ResetSuspectedCredentialFailures());
    945     EXPECT_CALL(*dhcp_provider(), CreateIPv4Config(_, _, _, _))
    946         .Times(AnyNumber());
    947     EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(AnyNumber());
    948     EXPECT_CALL(wifi_provider_, IncrementConnectCount(_));
    949     ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
    950     Mock::VerifyAndClearExpectations(service.get());
    951 
    952     EXPECT_EQ(service, GetCurrentService());
    953     return service;
    954   }
    955 
    956   void FireScanTimer() {
    957     wifi_->ScanTimerHandler();
    958   }
    959   void TriggerScan(WiFi::ScanMethod method) {
    960     if (method == WiFi::kScanMethodFull) {
    961       wifi_->Scan(Device::kFullScan, nullptr, __func__);
    962     } else {
    963       wifi_->Scan(Device::kProgressiveScan, nullptr, __func__);
    964     }
    965   }
    966   const WiFiServiceRefPtr& GetCurrentService() {
    967     return wifi_->current_service_;
    968   }
    969   void SetCurrentService(const WiFiServiceRefPtr& service) {
    970     wifi_->current_service_ = service;
    971   }
    972   const WiFi::EndpointMap& GetEndpointMap() {
    973     return wifi_->endpoint_by_rpcid_;
    974   }
    975   const WiFiServiceRefPtr& GetPendingService() {
    976     return wifi_->pending_service_;
    977   }
    978   const base::CancelableClosure& GetPendingTimeout() {
    979     return wifi_->pending_timeout_callback_;
    980   }
    981   const base::CancelableClosure& GetReconnectTimeoutCallback() {
    982     return wifi_->reconnect_timeout_callback_;
    983   }
    984   const ServiceRefPtr& GetSelectedService() {
    985     return wifi_->selected_service();
    986   }
    987   const string& GetSupplicantBSS() {
    988     return wifi_->supplicant_bss_;
    989   }
    990   void SetSupplicantBSS(const string& bss) {
    991     wifi_->supplicant_bss_ = bss;
    992   }
    993   int GetReconnectTimeoutSeconds() {
    994     return WiFi::kReconnectTimeoutSeconds;
    995   }
    996   const base::CancelableClosure& GetScanTimer() {
    997     return wifi_->scan_timer_callback_;
    998   }
    999   // note: the tests need the proxies referenced by WiFi (not the
   1000   // proxies instantiated by WiFiObjectTest), to ensure that WiFi
   1001   // sets up its proxies correctly.
   1002   SupplicantProcessProxyInterface* GetSupplicantProcessProxy() {
   1003     return wifi_->supplicant_process_proxy_.get();
   1004   }
   1005   MockSupplicantInterfaceProxy* GetSupplicantInterfaceProxyFromWiFi() {
   1006     return static_cast<MockSupplicantInterfaceProxy*>(
   1007         wifi_->supplicant_interface_proxy_.get());
   1008   }
   1009   // This function returns the supplicant interface proxy whether
   1010   // or not we have passed the instantiated object to the WiFi instance
   1011   // from WiFiObjectTest, so tests don't need to worry about when they
   1012   // set expectations relative to StartWiFi().
   1013   MockSupplicantInterfaceProxy* GetSupplicantInterfaceProxy() {
   1014     MockSupplicantInterfaceProxy* proxy = GetSupplicantInterfaceProxyFromWiFi();
   1015     return proxy ? proxy : supplicant_interface_proxy_.get();
   1016   }
   1017   const string& GetSupplicantState() {
   1018     return wifi_->supplicant_state_;
   1019   }
   1020   int GetSupplicantDisconnectReason() {
   1021     return wifi_->supplicant_disconnect_reason_;
   1022   }
   1023   void ClearCachedCredentials(const WiFiService* service) {
   1024     return wifi_->ClearCachedCredentials(service);
   1025   }
   1026   void NotifyEndpointChanged(const WiFiEndpointConstRefPtr& endpoint) {
   1027     wifi_->NotifyEndpointChanged(endpoint);
   1028   }
   1029   bool RemoveNetwork(const string& network) {
   1030     return wifi_->RemoveNetwork(network);
   1031   }
   1032   KeyValueStore CreateBSSProperties(const string& ssid,
   1033                                     const string& bssid,
   1034                                     int16_t signal_strength,
   1035                                     uint16_t frequency,
   1036                                     const char* mode);
   1037   void RemoveBSS(const string& bss_path);
   1038   void ReportBSS(const string& bss_path,
   1039                  const string& ssid,
   1040                  const string& bssid,
   1041                  int16_t signal_strength,
   1042                  uint16_t frequency,
   1043                  const char* mode);
   1044   void ReportIPConfigComplete() {
   1045     wifi_->OnIPConfigUpdated(dhcp_config_, true);
   1046   }
   1047   void ReportIPConfigCompleteGatewayArpReceived() {
   1048     wifi_->OnIPConfigUpdated(dhcp_config_, false);
   1049   }
   1050 
   1051   // Calls the delayed version of the BSS methods.
   1052   void BSSAdded(const string& bss_path,
   1053                 const KeyValueStore& properties) {
   1054     wifi_->BSSAdded(bss_path, properties);
   1055   }
   1056   void BSSRemoved(const string& bss_path) {
   1057     wifi_->BSSRemoved(bss_path);
   1058   }
   1059 
   1060   void ReportIPv6ConfigComplete() {
   1061     wifi_->OnIPv6ConfigUpdated();
   1062   }
   1063   void ReportIPConfigFailure() {
   1064     wifi_->OnIPConfigFailure();
   1065   }
   1066   void ReportConnected() {
   1067     wifi_->OnConnected();
   1068   }
   1069   void ReportLinkUp() {
   1070     wifi_->LinkEvent(IFF_LOWER_UP, IFF_LOWER_UP);
   1071   }
   1072   void ScanDone(const bool& success) {
   1073     wifi_->ScanDone(success);
   1074   }
   1075   void ReportScanFailed() {
   1076     wifi_->ScanFailedTask();
   1077   }
   1078   void ReportScanDone() {
   1079     // Eliminate |scan_session| so |ScanDoneTask| doesn't launch another scan.
   1080     wifi_->scan_session_.reset();
   1081     wifi_->ScanDoneTask();
   1082     // Make a new |scan_session| so that future scanning is done with the mock.
   1083     InstallMockScanSession();
   1084   }
   1085   void ReportScanDoneKeepScanSession() {
   1086     wifi_->ScanDoneTask();
   1087   }
   1088   void ReportCurrentBSSChanged(const string& new_bss) {
   1089     wifi_->CurrentBSSChanged(new_bss);
   1090   }
   1091   void ReportStateChanged(const string& new_state) {
   1092     wifi_->StateChanged(new_state);
   1093   }
   1094   void ReportDisconnectReasonChanged(int reason) {
   1095     wifi_->DisconnectReasonChanged(reason);
   1096   }
   1097   void ReportWiFiDebugScopeChanged(bool enabled) {
   1098     wifi_->OnWiFiDebugScopeChanged(enabled);
   1099   }
   1100   void RequestStationInfo() {
   1101     wifi_->RequestStationInfo();
   1102   }
   1103   void ReportReceivedStationInfo(const Nl80211Message& nl80211_message) {
   1104     wifi_->OnReceivedStationInfo(nl80211_message);
   1105   }
   1106   KeyValueStore GetLinkStatistics() {
   1107     return wifi_->GetLinkStatistics(nullptr);
   1108   }
   1109   void SetPendingService(const WiFiServiceRefPtr& service) {
   1110     wifi_->SetPendingService(service);
   1111   }
   1112   void SetServiceNetworkRpcId(
   1113       const WiFiServiceRefPtr& service, const string& rpcid) {
   1114     wifi_->rpcid_by_service_[service.get()] = rpcid;
   1115   }
   1116   bool RpcIdByServiceIsEmpty() {
   1117     return wifi_->rpcid_by_service_.empty();
   1118   }
   1119   bool SetScanInterval(uint16_t interval_seconds, Error* error) {
   1120     return wifi_->SetScanInterval(interval_seconds, error);
   1121   }
   1122   uint16_t GetScanInterval() {
   1123     return wifi_->GetScanInterval(nullptr);
   1124   }
   1125   void StartWiFi(bool supplicant_present) {
   1126     EXPECT_CALL(netlink_manager_, SubscribeToEvents(
   1127         Nl80211Message::kMessageTypeString,
   1128         NetlinkManager::kEventTypeConfig));
   1129     EXPECT_CALL(netlink_manager_, SubscribeToEvents(
   1130         Nl80211Message::kMessageTypeString,
   1131         NetlinkManager::kEventTypeScan));
   1132     EXPECT_CALL(netlink_manager_, SubscribeToEvents(
   1133         Nl80211Message::kMessageTypeString,
   1134         NetlinkManager::kEventTypeRegulatory));
   1135     EXPECT_CALL(netlink_manager_, SubscribeToEvents(
   1136         Nl80211Message::kMessageTypeString,
   1137         NetlinkManager::kEventTypeMlme));
   1138     EXPECT_CALL(netlink_manager_, SendNl80211Message(
   1139         IsNl80211Command(kNl80211FamilyId, NL80211_CMD_GET_WIPHY), _, _, _));
   1140 
   1141     wifi_->supplicant_present_ = supplicant_present;
   1142     wifi_->SetEnabled(true);  // Start(nullptr, ResultCallback());
   1143     if (supplicant_present)
   1144       // Mimic the callback from |supplicant_process_proxy_|.
   1145       wifi_->OnSupplicantAppear();
   1146   }
   1147   void StartWiFi() {
   1148     StartWiFi(true);
   1149   }
   1150   void OnAfterResume() {
   1151     EXPECT_CALL(*wake_on_wifi_, OnAfterResume());
   1152     wifi_->OnAfterResume();
   1153   }
   1154   void OnBeforeSuspend() {
   1155     ResultCallback callback(
   1156         base::Bind(&WiFiObjectTest::SuspendCallback, base::Unretained(this)));
   1157     wifi_->OnBeforeSuspend(callback);
   1158   }
   1159   void OnDarkResume() {
   1160     ResultCallback callback(
   1161         base::Bind(&WiFiObjectTest::SuspendCallback, base::Unretained(this)));
   1162     wifi_->OnDarkResume(callback);
   1163   }
   1164   void RemoveSupplicantNetworks() {
   1165     wifi_->RemoveSupplicantNetworks();
   1166   }
   1167   void InitiateScan(Device::ScanType scan_type) {
   1168     wifi_->InitiateScan(scan_type);
   1169   }
   1170   void InitiateScanInDarkResume(const WiFi::FreqSet& freqs) {
   1171     wifi_->InitiateScanInDarkResume(freqs);
   1172   }
   1173   void TriggerPassiveScan(const WiFi::FreqSet& freqs) {
   1174     wifi_->TriggerPassiveScan(freqs);
   1175   }
   1176   void OnSupplicantAppear() {
   1177     wifi_->OnSupplicantAppear();
   1178     EXPECT_TRUE(wifi_->supplicant_present_);
   1179   }
   1180   void OnSupplicantVanish() {
   1181     wifi_->OnSupplicantVanish();
   1182     EXPECT_FALSE(wifi_->supplicant_present_);
   1183   }
   1184   bool GetSupplicantPresent() {
   1185     return wifi_->supplicant_present_;
   1186   }
   1187   bool GetIsRoamingInProgress() {
   1188     return wifi_->is_roaming_in_progress_;
   1189   }
   1190   void SetIPConfig(const IPConfigRefPtr& ipconfig) {
   1191     return wifi_->set_ipconfig(ipconfig);
   1192   }
   1193   bool SetBgscanMethod(const string& method) {
   1194     Error error;
   1195     return wifi_->mutable_store()->SetAnyProperty(kBgscanMethodProperty,
   1196                                                   brillo::Any(method),
   1197                                                   &error);
   1198   }
   1199 
   1200   void AppendBgscan(WiFiService* service,
   1201                     KeyValueStore* service_params) {
   1202     wifi_->AppendBgscan(service, service_params);
   1203   }
   1204 
   1205   void ReportCertification(const KeyValueStore& properties) {
   1206     wifi_->CertificationTask(properties);
   1207   }
   1208 
   1209   void ReportEAPEvent(const string& status, const string& parameter) {
   1210     wifi_->EAPEventTask(status, parameter);
   1211   }
   1212 
   1213   void RestartFastScanAttempts() {
   1214     wifi_->RestartFastScanAttempts();
   1215   }
   1216 
   1217   void SetFastScansRemaining(int num) {
   1218     wifi_->fast_scans_remaining_ = num;
   1219   }
   1220 
   1221   void StartReconnectTimer() {
   1222     wifi_->StartReconnectTimer();
   1223   }
   1224 
   1225   void StopReconnectTimer() {
   1226     wifi_->StopReconnectTimer();
   1227   }
   1228 
   1229   void SetLinkMonitor(LinkMonitor* link_monitor) {
   1230     wifi_->set_link_monitor(link_monitor);
   1231   }
   1232 
   1233   bool SuspectCredentials(const WiFiServiceRefPtr& service,
   1234                           Service::ConnectFailure* failure) {
   1235     return wifi_->SuspectCredentials(service, failure);
   1236   }
   1237 
   1238   void OnLinkMonitorFailure() {
   1239     wifi_->OnLinkMonitorFailure();
   1240   }
   1241 
   1242   void OnUnreliableLink() {
   1243     wifi_->OnUnreliableLink();
   1244   }
   1245 
   1246   bool SetBgscanShortInterval(const uint16_t& interval, Error* error) {
   1247     return wifi_->SetBgscanShortInterval(interval, error);
   1248   }
   1249 
   1250   bool SetBgscanSignalThreshold(const int32_t& threshold, Error* error) {
   1251     return wifi_->SetBgscanSignalThreshold(threshold, error);
   1252   }
   1253 
   1254   void SetTDLSManager(TDLSManager* tdls_manager) {
   1255     wifi_->tdls_manager_.reset(tdls_manager);
   1256   }
   1257 
   1258   void TDLSDiscoverResponse(const string& peer_address) {
   1259     wifi_->TDLSDiscoverResponse(peer_address);
   1260   }
   1261 
   1262   string PerformTDLSOperation(
   1263       const string& operation, const string& peer, Error* error) {
   1264     return wifi_->PerformTDLSOperation(operation, peer, error);
   1265   }
   1266 
   1267   void TimeoutPendingConnection() {
   1268     wifi_->PendingTimeoutHandler();
   1269   }
   1270 
   1271   void OnNewWiphy(const Nl80211Message& new_wiphy_message) {
   1272     wifi_->OnNewWiphy(new_wiphy_message);
   1273   }
   1274 
   1275   bool IsConnectedToCurrentService() {
   1276     return wifi_->IsConnectedToCurrentService();
   1277   }
   1278 
   1279   NiceMockControl* control_interface() {
   1280     return &control_interface_;
   1281   }
   1282 
   1283   MockMetrics* metrics() {
   1284     return &metrics_;
   1285   }
   1286 
   1287   MockManager* manager() {
   1288     return &manager_;
   1289   }
   1290 
   1291   MockDeviceInfo* device_info() {
   1292     return &device_info_;
   1293   }
   1294 
   1295   MockDHCPProvider* dhcp_provider() {
   1296     return &dhcp_provider_;
   1297   }
   1298 
   1299   const WiFiConstRefPtr wifi() const {
   1300     return wifi_;
   1301   }
   1302 
   1303   MockWiFiProvider* wifi_provider() {
   1304     return &wifi_provider_;
   1305   }
   1306 
   1307   MockMac80211Monitor* mac80211_monitor() {
   1308     return mac80211_monitor_;
   1309   }
   1310 
   1311   void ReportConnectedToServiceAfterWake() {
   1312     wifi_->ReportConnectedToServiceAfterWake();
   1313   }
   1314 
   1315   void StartScanTimer() {
   1316     wifi_->StartScanTimer();
   1317   }
   1318 
   1319   bool ParseWiphyIndex(const Nl80211Message& nl80211_message) {
   1320     return wifi_->ParseWiphyIndex(nl80211_message);
   1321   }
   1322 
   1323   uint32_t GetWiphyIndex() { return wifi_->wiphy_index_; }
   1324 
   1325   void SetWiphyIndex(uint32_t index) { wifi_->wiphy_index_ = index; }
   1326 
   1327   std::set<uint16_t>* GetAllScanFrequencies() {
   1328     return &wifi_->all_scan_frequencies_;
   1329   }
   1330 
   1331   void OnScanStarted(const NetlinkMessage& netlink_message) {
   1332     wifi_->OnScanStarted(netlink_message);
   1333   }
   1334 
   1335   bool ScanFailedCallbackIsCancelled() {
   1336     return wifi_->scan_failed_callback_.IsCancelled();
   1337   }
   1338 
   1339   void SetWiFiEnabled(bool enabled) {
   1340     wifi_->enabled_ = enabled;
   1341   }
   1342 
   1343   MOCK_METHOD1(SuspendCallback, void(const Error& error));
   1344 
   1345   EventDispatcher* event_dispatcher_;
   1346   MockScanSession* scan_session_;  // Owned by |wifi_|.
   1347   MockWakeOnWiFi* wake_on_wifi_;  // Owned by |wifi_|.
   1348   NiceMock<MockRTNLHandler> rtnl_handler_;
   1349   MockTime time_;
   1350 
   1351  private:
   1352   NiceMockControl control_interface_;
   1353   MockMetrics metrics_;
   1354   MockManager manager_;
   1355   MockDeviceInfo device_info_;
   1356   WiFiRefPtr wifi_;
   1357   NiceMock<MockWiFiProvider> wifi_provider_;
   1358   int bss_counter_;
   1359   MockMac80211Monitor* mac80211_monitor_;  // Owned by |wifi_|.
   1360 
   1361   // protected fields interspersed between private fields, due to
   1362   // initialization order
   1363  protected:
   1364   static const char kDeviceName[];
   1365   static const char kDeviceAddress[];
   1366   static const char kNetworkModeAdHoc[];
   1367   static const char kNetworkModeInfrastructure[];
   1368   static const char kBSSName[];
   1369   static const char kSSIDName[];
   1370   static const uint16_t kRoamThreshold;
   1371 
   1372   MockSupplicantProcessProxy* supplicant_process_proxy_;
   1373   unique_ptr<MockSupplicantBSSProxy> supplicant_bss_proxy_;
   1374   MockDHCPProvider dhcp_provider_;
   1375   scoped_refptr<MockDHCPConfig> dhcp_config_;
   1376 
   1377   // These pointers track mock objects owned by the WiFi device instance
   1378   // and manager so we can perform expectations against them.
   1379   DeviceMockAdaptor* adaptor_;
   1380   MockSupplicantEAPStateHandler* eap_state_handler_;
   1381   MockNetlinkManager netlink_manager_;
   1382 
   1383  private:
   1384   unique_ptr<MockSupplicantInterfaceProxy> supplicant_interface_proxy_;
   1385   unique_ptr<MockSupplicantNetworkProxy> supplicant_network_proxy_;
   1386 };
   1387 
   1388 const char WiFiObjectTest::kDeviceName[] = "wlan0";
   1389 const char WiFiObjectTest::kDeviceAddress[] = "000102030405";
   1390 const char WiFiObjectTest::kNetworkModeAdHoc[] = "ad-hoc";
   1391 const char WiFiObjectTest::kNetworkModeInfrastructure[] = "infrastructure";
   1392 const char WiFiObjectTest::kBSSName[] = "bss0";
   1393 const char WiFiObjectTest::kSSIDName[] = "ssid0";
   1394 const uint16_t WiFiObjectTest::kRoamThreshold = 32;  // Arbitrary value.
   1395 
   1396 void WiFiObjectTest::RemoveBSS(const string& bss_path) {
   1397   wifi_->BSSRemovedTask(bss_path);
   1398 }
   1399 
   1400 KeyValueStore WiFiObjectTest::CreateBSSProperties(
   1401     const string& ssid,
   1402     const string& bssid,
   1403     int16_t signal_strength,
   1404     uint16_t frequency,
   1405     const char* mode) {
   1406   KeyValueStore bss_properties;
   1407   bss_properties.SetUint8s("SSID", vector<uint8_t>(ssid.begin(), ssid.end()));
   1408   {
   1409     string bssid_nosep;
   1410     vector<uint8_t> bssid_bytes;
   1411     base::RemoveChars(bssid, ":", &bssid_nosep);
   1412     base::HexStringToBytes(bssid_nosep, &bssid_bytes);
   1413     bss_properties.SetUint8s("BSSID", bssid_bytes);
   1414   }
   1415   bss_properties.SetInt16(WPASupplicant::kBSSPropertySignal, signal_strength);
   1416   bss_properties.SetUint16(WPASupplicant::kBSSPropertyFrequency, frequency);
   1417   bss_properties.SetString(WPASupplicant::kBSSPropertyMode, mode);
   1418 
   1419   return bss_properties;
   1420 }
   1421 
   1422 void WiFiObjectTest::ReportBSS(const string& bss_path,
   1423                                const string& ssid,
   1424                                const string& bssid,
   1425                                int16_t signal_strength,
   1426                                uint16_t frequency,
   1427                                const char* mode) {
   1428   wifi_->BSSAddedTask(
   1429       bss_path,
   1430       CreateBSSProperties(ssid, bssid, signal_strength, frequency, mode));
   1431 }
   1432 
   1433 // Most of our tests involve using a real EventDispatcher object.
   1434 class WiFiMainTest : public WiFiObjectTest {
   1435  public:
   1436   WiFiMainTest() : WiFiObjectTest(&dispatcher_) {}
   1437 
   1438  protected:
   1439   // A progressive scan requests one or more scans, each of which asks about a
   1440   // different batch of frequencies/channels.
   1441   enum WhichBatchOfProgressiveScan {
   1442     kFirstProgressiveScanBatch,
   1443     kOnlyFullScanBatch,
   1444     kNotFirstProgressiveScanBatch
   1445   };
   1446   void StartScan(WiFi::ScanMethod method) {
   1447     if (method == WiFi::kScanMethodFull) {
   1448       EnableFullScan();
   1449     }
   1450     VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   1451     EXPECT_CALL(*adaptor_, EmitBoolChanged(kPoweredProperty, _)).
   1452         Times(AnyNumber());
   1453     // Using kFirstProgressiveScanBatch regardless of the method since
   1454     // kFOnlyFullScanBatch does exactly the same thing.
   1455     ExpectScanStart(method, false);
   1456     StartWiFi();
   1457     dispatcher_.DispatchPendingEvents();
   1458     VerifyScanState(WiFi::kScanScanning, method);
   1459   }
   1460 
   1461   MockWiFiServiceRefPtr AttemptConnection(WiFi::ScanMethod method,
   1462                                           WiFiEndpointRefPtr* endpoint,
   1463                                           string* bss_path) {
   1464     WiFiEndpointRefPtr dummy_endpoint;
   1465     if (!endpoint) {
   1466       endpoint = &dummy_endpoint;  // If caller doesn't care about endpoint.
   1467     }
   1468 
   1469     string dummy_bss_path;
   1470     if (!bss_path) {
   1471       bss_path = &dummy_bss_path;  // If caller doesn't care about bss_path.
   1472     }
   1473 
   1474     ExpectScanStop();
   1475     ExpectConnecting();
   1476     MockWiFiServiceRefPtr service =
   1477         SetupConnectingService("", endpoint, bss_path);
   1478     ReportScanDoneKeepScanSession();
   1479     dispatcher_.DispatchPendingEvents();
   1480     VerifyScanState(WiFi::kScanConnecting, method);
   1481 
   1482     return service;
   1483   }
   1484 
   1485   void ExpectScanStart(WiFi::ScanMethod method, bool is_continued) {
   1486     if (method == WiFi::kScanMethodProgressive) {
   1487       ASSERT_FALSE(IsScanSessionNull());
   1488       EXPECT_CALL(*scan_session_, HasMoreFrequencies());
   1489       EXPECT_CALL(*scan_session_, InitiateScan());
   1490     } else {
   1491       EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1492     }
   1493     if (!is_continued) {
   1494       EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty,
   1495                                              true));
   1496       EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_));
   1497     }
   1498   }
   1499 
   1500   // Scanning can stop for any reason (including transitioning to connecting).
   1501   void ExpectScanStop() {
   1502     EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty, false));
   1503   }
   1504 
   1505   void ExpectConnecting() {
   1506     EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
   1507     EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _));
   1508   }
   1509 
   1510   void ExpectConnected() {
   1511     EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_));
   1512     ExpectScanIdle();
   1513   }
   1514 
   1515   void ExpectFoundNothing() {
   1516     EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
   1517     EXPECT_CALL(*metrics(), ResetConnectTimer(_));
   1518     ExpectScanIdle();
   1519   }
   1520 
   1521   void ExpectScanIdle() {
   1522     EXPECT_CALL(*metrics(), ResetScanTimer(_));
   1523     EXPECT_CALL(*metrics(), ResetConnectTimer(_)).RetiresOnSaturation();
   1524   }
   1525 
   1526   EventDispatcherForTest dispatcher_;
   1527 };
   1528 
   1529 TEST_F(WiFiMainTest, ProxiesSetUpDuringStart) {
   1530   EXPECT_EQ(nullptr, GetSupplicantInterfaceProxyFromWiFi());;
   1531 
   1532   StartWiFi();
   1533   EXPECT_NE(nullptr, GetSupplicantInterfaceProxyFromWiFi());
   1534 }
   1535 
   1536 TEST_F(WiFiMainTest, SupplicantPresent) {
   1537   EXPECT_FALSE(GetSupplicantPresent());
   1538 }
   1539 
   1540 TEST_F(WiFiMainTest, RoamThresholdProperty) {
   1541   static const uint16_t kRoamThreshold16 = 16;
   1542   static const uint16_t kRoamThreshold32 = 32;
   1543 
   1544   StartWiFi(false);  // No supplicant present.
   1545   OnSupplicantAppear();
   1546 
   1547   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   1548               SetRoamThreshold(kRoamThreshold16));
   1549   EXPECT_TRUE(SetRoamThreshold(kRoamThreshold16));
   1550   EXPECT_EQ(GetRoamThreshold(), kRoamThreshold16);
   1551 
   1552   // Try a different number
   1553   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   1554               SetRoamThreshold(kRoamThreshold32));
   1555   EXPECT_TRUE(SetRoamThreshold(kRoamThreshold32));
   1556   EXPECT_EQ(GetRoamThreshold(), kRoamThreshold32);
   1557 
   1558   // Do not set supplicant's roam threshold property immediately if the
   1559   // current WiFi service has its own roam threshold property set.
   1560   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   1561   service->roam_threshold_db_set_ = true;
   1562   SetCurrentService(service);
   1563   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetRoamThreshold(_)).Times(0);
   1564   EXPECT_TRUE(SetRoamThreshold(kRoamThreshold16));
   1565   EXPECT_EQ(kRoamThreshold16, GetRoamThreshold());
   1566 }
   1567 
   1568 TEST_F(WiFiMainTest, OnSupplicantAppearStarted) {
   1569   EXPECT_EQ(nullptr, GetSupplicantInterfaceProxyFromWiFi());;
   1570 
   1571   StartWiFi(false);  // No supplicant present.
   1572   EXPECT_EQ(nullptr, GetSupplicantInterfaceProxyFromWiFi());;
   1573 
   1574   SetRoamThresholdMember(kRoamThreshold);
   1575   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveAllNetworks());
   1576   EXPECT_CALL(*GetSupplicantInterfaceProxy(), FlushBSS(0));
   1577   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetFastReauth(false));
   1578   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetRoamThreshold(kRoamThreshold));
   1579   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetScanInterval(_));
   1580   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetDisableHighBitrates(true));
   1581 
   1582   OnSupplicantAppear();
   1583   EXPECT_NE(nullptr, GetSupplicantInterfaceProxyFromWiFi());
   1584 
   1585   // If supplicant reappears while the device is started, the device should be
   1586   // restarted.
   1587   EXPECT_CALL(*manager(), DeregisterDevice(_));
   1588   EXPECT_CALL(*manager(), RegisterDevice(_));
   1589   OnSupplicantAppear();
   1590 }
   1591 
   1592 TEST_F(WiFiMainTest, OnSupplicantAppearStopped) {
   1593   EXPECT_EQ(nullptr, GetSupplicantInterfaceProxyFromWiFi());
   1594 
   1595   OnSupplicantAppear();
   1596   EXPECT_EQ(nullptr, GetSupplicantInterfaceProxyFromWiFi());
   1597 
   1598   // If supplicant reappears while the device is stopped, the device should not
   1599   // be restarted.
   1600   EXPECT_CALL(*manager(), DeregisterDevice(_)).Times(0);
   1601   OnSupplicantAppear();
   1602 }
   1603 
   1604 TEST_F(WiFiMainTest, OnSupplicantVanishStarted) {
   1605   EXPECT_EQ(nullptr, GetSupplicantInterfaceProxyFromWiFi());;
   1606 
   1607   StartWiFi();
   1608   EXPECT_NE(nullptr, GetSupplicantInterfaceProxyFromWiFi());
   1609   EXPECT_TRUE(GetSupplicantPresent());
   1610 
   1611   EXPECT_CALL(*manager(), DeregisterDevice(_));
   1612   EXPECT_CALL(*manager(), RegisterDevice(_));
   1613   OnSupplicantVanish();
   1614 }
   1615 
   1616 TEST_F(WiFiMainTest, OnSupplicantVanishStopped) {
   1617   OnSupplicantAppear();
   1618   EXPECT_TRUE(GetSupplicantPresent());
   1619   EXPECT_CALL(*manager(), DeregisterDevice(_)).Times(0);
   1620   OnSupplicantVanish();
   1621 }
   1622 
   1623 TEST_F(WiFiMainTest, OnSupplicantVanishedWhileConnected) {
   1624   StartWiFi();
   1625   WiFiEndpointRefPtr endpoint;
   1626   WiFiServiceRefPtr service(
   1627       SetupConnectedService("", &endpoint, nullptr));
   1628   ScopedMockLog log;
   1629   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   1630   EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
   1631                        EndsWith("silently resetting current_service_.")));
   1632   EXPECT_CALL(*manager(), DeregisterDevice(_))
   1633       .WillOnce(InvokeWithoutArgs(this, &WiFiObjectTest::StopWiFi));
   1634   unique_ptr<EndpointRemovalHandler> handler(
   1635       MakeEndpointRemovalHandler(service));
   1636   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
   1637       .WillOnce(Invoke(handler.get(),
   1638                 &EndpointRemovalHandler::OnEndpointRemoved));
   1639   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
   1640   EXPECT_CALL(*manager(), RegisterDevice(_));
   1641   OnSupplicantVanish();
   1642   EXPECT_EQ(nullptr, GetCurrentService());;
   1643 }
   1644 
   1645 TEST_F(WiFiMainTest, CleanStart_FullScan) {
   1646   EnableFullScan();
   1647   EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_, _));
   1648   EXPECT_CALL(*supplicant_process_proxy_, GetInterface(_, _))
   1649       .Times(AnyNumber())
   1650       .WillRepeatedly(Return(false));
   1651   EXPECT_TRUE(GetScanTimer().IsCancelled());
   1652   StartWiFi();
   1653   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1654   dispatcher_.DispatchPendingEvents();
   1655   EXPECT_FALSE(GetScanTimer().IsCancelled());
   1656 }
   1657 
   1658 TEST_F(WiFiMainTest, CleanStart) {
   1659   EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_, _));
   1660   EXPECT_CALL(*supplicant_process_proxy_, GetInterface(_, _))
   1661       .Times(AnyNumber())
   1662       .WillRepeatedly(Return(false));
   1663   EXPECT_TRUE(GetScanTimer().IsCancelled());
   1664   StartWiFi();
   1665   EXPECT_CALL(*scan_session_, InitiateScan());
   1666   dispatcher_.DispatchPendingEvents();
   1667   EXPECT_FALSE(GetScanTimer().IsCancelled());
   1668 }
   1669 
   1670 TEST_F(WiFiMainTest, ClearCachedCredentials) {
   1671   StartWiFi();
   1672   string network = "/test/path";
   1673   WiFiServiceRefPtr service(SetupConnectedService(network, nullptr, nullptr));
   1674   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network));
   1675   ClearCachedCredentials(service.get());
   1676 }
   1677 
   1678 TEST_F(WiFiMainTest, NotifyEndpointChanged) {
   1679   WiFiEndpointRefPtr endpoint =
   1680       MakeEndpointWithMode("ssid", "00:00:00:00:00:00", kNetworkModeAdHoc);
   1681   EXPECT_CALL(*wifi_provider(), OnEndpointUpdated(EndpointMatch(endpoint)));
   1682   NotifyEndpointChanged(endpoint);
   1683 }
   1684 
   1685 TEST_F(WiFiMainTest, RemoveNetwork) {
   1686   string network = "/test/path";
   1687   StartWiFi();
   1688   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network))
   1689       .WillOnce(Return(true));
   1690   EXPECT_TRUE(RemoveNetwork(network));
   1691 }
   1692 
   1693 TEST_F(WiFiMainTest, UseArpGateway) {
   1694   StartWiFi();
   1695 
   1696   // With no selected service.
   1697   EXPECT_TRUE(wifi()->ShouldUseArpGateway());
   1698   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kDeviceName, _, true, _))
   1699       .WillOnce(Return(dhcp_config_));
   1700   const_cast<WiFi*>(wifi().get())->AcquireIPConfig();
   1701 
   1702   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   1703   InitiateConnect(service);
   1704 
   1705   // Selected service that does not have a static IP address.
   1706   EXPECT_CALL(*service, HasStaticIPAddress()).WillRepeatedly(Return(false));
   1707   EXPECT_TRUE(wifi()->ShouldUseArpGateway());
   1708   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kDeviceName, _, true, _))
   1709       .WillOnce(Return(dhcp_config_));
   1710   const_cast<WiFi*>(wifi().get())->AcquireIPConfig();
   1711   Mock::VerifyAndClearExpectations(service.get());
   1712 
   1713   // Selected service that has a static IP address.
   1714   EXPECT_CALL(*service, HasStaticIPAddress()).WillRepeatedly(Return(true));
   1715   EXPECT_FALSE(wifi()->ShouldUseArpGateway());
   1716   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kDeviceName, _, false, _))
   1717       .WillOnce(Return(dhcp_config_));
   1718   const_cast<WiFi*>(wifi().get())->AcquireIPConfig();
   1719 }
   1720 
   1721 TEST_F(WiFiMainTest, RemoveNetworkFailed) {
   1722   string network = "/test/path";
   1723   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network))
   1724       .WillRepeatedly(Return(false));
   1725   StartWiFi();
   1726   EXPECT_FALSE(RemoveNetwork(network));
   1727 }
   1728 
   1729 TEST_F(WiFiMainTest, Restart_FullScan) {
   1730   EnableFullScan();
   1731   EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_, _))
   1732       .Times(AnyNumber())
   1733       .WillRepeatedly(Return(false));
   1734   EXPECT_CALL(*supplicant_process_proxy_, GetInterface(_, _));
   1735   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1736   StartWiFi();
   1737   dispatcher_.DispatchPendingEvents();
   1738 }
   1739 
   1740 TEST_F(WiFiMainTest, Restart) {
   1741   EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_, _))
   1742       .Times(AnyNumber())
   1743       .WillRepeatedly(Return(false));
   1744   EXPECT_CALL(*scan_session_, InitiateScan());
   1745   StartWiFi();
   1746   dispatcher_.DispatchPendingEvents();
   1747 }
   1748 
   1749 TEST_F(WiFiMainTest, StartClearsState) {
   1750   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveAllNetworks());
   1751   EXPECT_CALL(*GetSupplicantInterfaceProxy(), FlushBSS(_));
   1752   StartWiFi();
   1753 }
   1754 
   1755 TEST_F(WiFiMainTest, NoScansWhileConnecting_FullScan) {
   1756   // Setup 'connecting' state.
   1757   StartScan(WiFi::kScanMethodFull);
   1758   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1759 
   1760   ExpectScanStop();
   1761   ExpectConnecting();
   1762   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   1763   InitiateConnect(service);
   1764   VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodFull);
   1765 
   1766   // If we're connecting, we ignore scan requests and stay on channel.
   1767   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   1768   TriggerScan(WiFi::kScanMethodFull);
   1769   dispatcher_.DispatchPendingEvents();
   1770   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1771   Mock::VerifyAndClearExpectations(service.get());
   1772 
   1773   // Terminate the scan.
   1774   ExpectFoundNothing();
   1775   TimeoutPendingConnection();
   1776   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   1777 
   1778   // Start a fresh scan.
   1779   ExpectScanStart(WiFi::kScanMethodFull, false);
   1780   TriggerScan(WiFi::kScanMethodFull);
   1781   dispatcher_.DispatchPendingEvents();
   1782   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1783   Mock::VerifyAndClearExpectations(service.get());
   1784 
   1785   // Similarly, ignore scans when our connected service is reconnecting.
   1786   ExpectScanStop();
   1787   ExpectScanIdle();
   1788   SetPendingService(nullptr);
   1789   SetCurrentService(service);
   1790   EXPECT_CALL(*service, IsConnecting()).WillOnce(Return(true));
   1791   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   1792   TriggerScan(WiFi::kScanMethodFull);
   1793   dispatcher_.DispatchPendingEvents();
   1794   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1795   Mock::VerifyAndClearExpectations(service.get());
   1796 
   1797   // But otherwise we'll honor the request.
   1798   EXPECT_CALL(*service, IsConnecting()).Times(AtLeast(2)).
   1799       WillRepeatedly(Return(false));
   1800   ExpectScanStart(WiFi::kScanMethodFull, false);
   1801   TriggerScan(WiFi::kScanMethodFull);
   1802   dispatcher_.DispatchPendingEvents();
   1803   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1804   Mock::VerifyAndClearExpectations(service.get());
   1805 
   1806   // Silence messages from the destructor.
   1807   ExpectScanStop();
   1808   ExpectScanIdle();
   1809 }
   1810 
   1811 TEST_F(WiFiMainTest, NoScansWhileConnecting) {
   1812   // Setup 'connecting' state.
   1813   StartScan(WiFi::kScanMethodProgressive);
   1814   ExpectScanStop();
   1815   ExpectConnecting();
   1816   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   1817   InitiateConnect(service);
   1818   VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
   1819 
   1820   // If we're connecting, we ignore scan requests and stay on channel.
   1821   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   1822   TriggerScan(WiFi::kScanMethodProgressive);
   1823   dispatcher_.DispatchPendingEvents();
   1824   Mock::VerifyAndClearExpectations(service.get());
   1825   Mock::VerifyAndClearExpectations(scan_session_);
   1826 
   1827   // Terminate the scan.
   1828   ExpectFoundNothing();
   1829   TimeoutPendingConnection();
   1830   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   1831 
   1832   // Start a fresh scan.
   1833   InstallMockScanSession();
   1834   ExpectScanStart(WiFi::kScanMethodProgressive, false);
   1835   TriggerScan(WiFi::kScanMethodProgressive);
   1836   dispatcher_.DispatchPendingEvents();
   1837   Mock::VerifyAndClearExpectations(service.get());
   1838   Mock::VerifyAndClearExpectations(scan_session_);
   1839 
   1840   // Similarly, ignore scans when our connected service is reconnecting.
   1841   ExpectScanStop();
   1842   ExpectScanIdle();
   1843   SetPendingService(nullptr);
   1844   SetCurrentService(service);
   1845   EXPECT_CALL(*service, IsConnecting()).WillOnce(Return(true));
   1846   InstallMockScanSession();
   1847   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   1848   TriggerScan(WiFi::kScanMethodProgressive);
   1849   dispatcher_.DispatchPendingEvents();
   1850   Mock::VerifyAndClearExpectations(service.get());
   1851   Mock::VerifyAndClearExpectations(scan_session_);
   1852 
   1853   // Unlike Full scan, Progressive scan will reject attempts to scan while
   1854   // we're connected.
   1855   EXPECT_CALL(*service, IsConnecting()).WillOnce(Return(false));
   1856   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   1857   TriggerScan(WiFi::kScanMethodProgressive);
   1858   dispatcher_.DispatchPendingEvents();
   1859   Mock::VerifyAndClearExpectations(service.get());
   1860   Mock::VerifyAndClearExpectations(scan_session_);
   1861 }
   1862 
   1863 TEST_F(WiFiMainTest, ResetScanStateWhenScanFailed) {
   1864   StartScan(WiFi::kScanMethodFull);
   1865   ExpectScanStop();
   1866   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodFull);
   1867   ReportScanFailed();
   1868   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   1869 }
   1870 
   1871 TEST_F(WiFiMainTest, ResumeStartsScanWhenIdle_FullScan) {
   1872   EnableFullScan();
   1873   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1874   StartWiFi();
   1875   dispatcher_.DispatchPendingEvents();
   1876   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1877   ReportScanDone();
   1878   ASSERT_TRUE(wifi()->IsIdle());
   1879   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1880   OnAfterResume();
   1881   dispatcher_.DispatchPendingEvents();
   1882 }
   1883 
   1884 TEST_F(WiFiMainTest, ResumeStartsScanWhenIdle) {
   1885   EXPECT_CALL(*scan_session_, InitiateScan());
   1886   StartWiFi();
   1887   dispatcher_.DispatchPendingEvents();
   1888   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1889   ReportScanDone();
   1890   ASSERT_TRUE(wifi()->IsIdle());
   1891   dispatcher_.DispatchPendingEvents();
   1892   OnAfterResume();
   1893   EXPECT_NE(nullptr, scan_session_);;
   1894   InstallMockScanSession();
   1895   EXPECT_CALL(*scan_session_, InitiateScan());
   1896   dispatcher_.DispatchPendingEvents();
   1897 }
   1898 
   1899 TEST_F(WiFiMainTest, ResumeDoesNotScanIfConnected) {
   1900   StartWiFi();
   1901   dispatcher_.DispatchPendingEvents();
   1902   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1903   ReportScanDone();
   1904   CancelScanTimer();
   1905   EXPECT_TRUE(GetScanTimer().IsCancelled());
   1906   ASSERT_TRUE(wifi()->IsIdle());
   1907   dispatcher_.DispatchPendingEvents();
   1908   OnAfterResume();
   1909   EXPECT_FALSE(GetScanTimer().IsCancelled());
   1910   InstallMockScanSession();
   1911   SetCurrentService(MakeMockService(kSecurityNone));
   1912   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   1913   dispatcher_.DispatchPendingEvents();
   1914 }
   1915 
   1916 TEST_F(WiFiMainTest, SuspendDoesNotStartScan_FullScan) {
   1917   EnableFullScan();
   1918   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1919   StartWiFi();
   1920   dispatcher_.DispatchPendingEvents();
   1921   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1922   ASSERT_TRUE(wifi()->IsIdle());
   1923   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   1924   OnBeforeSuspend();
   1925   dispatcher_.DispatchPendingEvents();
   1926 }
   1927 
   1928 TEST_F(WiFiMainTest, SuspendDoesNotStartScan) {
   1929   EXPECT_CALL(*scan_session_, InitiateScan());
   1930   StartWiFi();
   1931   dispatcher_.DispatchPendingEvents();
   1932   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1933   ASSERT_TRUE(wifi()->IsIdle());
   1934   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   1935   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   1936   OnBeforeSuspend();
   1937   dispatcher_.DispatchPendingEvents();
   1938 }
   1939 
   1940 TEST_F(WiFiMainTest, ResumeDoesNotStartScanWhenNotIdle_FullScan) {
   1941   EnableFullScan();
   1942   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   1943   StartWiFi();
   1944   dispatcher_.DispatchPendingEvents();
   1945   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1946   WiFiServiceRefPtr service(
   1947       SetupConnectedService("", nullptr, nullptr));
   1948   EXPECT_FALSE(wifi()->IsIdle());
   1949   ScopedMockLog log;
   1950   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   1951   EXPECT_CALL(log, Log(_, _, EndsWith("already connecting or connected.")));
   1952   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   1953   OnAfterResume();
   1954   dispatcher_.DispatchPendingEvents();
   1955 }
   1956 
   1957 TEST_F(WiFiMainTest, ResumeDoesNotStartScanWhenNotIdle) {
   1958   EXPECT_CALL(*scan_session_, InitiateScan());
   1959   StartWiFi();
   1960   dispatcher_.DispatchPendingEvents();
   1961   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1962   WiFiServiceRefPtr service(
   1963       SetupConnectedService("", nullptr, nullptr));
   1964   EXPECT_FALSE(wifi()->IsIdle());
   1965   ScopedMockLog log;
   1966   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   1967   EXPECT_CALL(log, Log(_, _, EndsWith("already connecting or connected.")));
   1968   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   1969   EXPECT_TRUE(IsScanSessionNull());
   1970   OnAfterResume();
   1971   dispatcher_.DispatchPendingEvents();
   1972 }
   1973 
   1974 TEST_F(WiFiMainTest, ResumeWithCurrentService) {
   1975   StartWiFi();
   1976   SetupConnectedService("", nullptr, nullptr);
   1977 
   1978   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetHT40Enable(_, true)).Times(1);
   1979   OnAfterResume();
   1980   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   1981 }
   1982 
   1983 TEST_F(WiFiMainTest, ScanResults) {
   1984   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(_)).Times(5);
   1985   StartWiFi();
   1986   ReportBSS("bss0", "ssid0", "00:00:00:00:00:00", 0, 0, kNetworkModeAdHoc);
   1987   ReportBSS(
   1988       "bss1", "ssid1", "00:00:00:00:00:01", 1, 0, kNetworkModeInfrastructure);
   1989   ReportBSS(
   1990       "bss2", "ssid2", "00:00:00:00:00:02", 2, 0, kNetworkModeInfrastructure);
   1991   ReportBSS(
   1992       "bss3", "ssid3", "00:00:00:00:00:03", 3, 0, kNetworkModeInfrastructure);
   1993   const uint16_t frequency = 2412;
   1994   ReportBSS("bss4", "ssid4", "00:00:00:00:00:04", 4, frequency,
   1995             kNetworkModeAdHoc);
   1996 
   1997   const WiFi::EndpointMap& endpoints_by_rpcid = GetEndpointMap();
   1998   EXPECT_EQ(5, endpoints_by_rpcid.size());
   1999 
   2000   WiFi::EndpointMap::const_iterator i;
   2001   WiFiEndpointRefPtr endpoint;
   2002   for (i = endpoints_by_rpcid.begin();
   2003        i != endpoints_by_rpcid.end();
   2004        ++i) {
   2005     if (i->second->bssid_string() == "00:00:00:00:00:04")
   2006       break;
   2007   }
   2008   ASSERT_TRUE(i != endpoints_by_rpcid.end());
   2009   EXPECT_EQ(4, i->second->signal_strength());
   2010   EXPECT_EQ(frequency, i->second->frequency());
   2011   EXPECT_EQ("adhoc", i->second->network_mode());
   2012 }
   2013 
   2014 TEST_F(WiFiMainTest, ScanCompleted) {
   2015   StartWiFi();
   2016   WiFiEndpointRefPtr ap0 = MakeEndpointWithMode("ssid0", "00:00:00:00:00:00",
   2017                                                 kNetworkModeAdHoc);
   2018   WiFiEndpointRefPtr ap1 = MakeEndpoint("ssid1", "00:00:00:00:00:01");
   2019   WiFiEndpointRefPtr ap2 = MakeEndpoint("ssid2", "00:00:00:00:00:02");
   2020   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap0))).Times(1);
   2021   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap1))).Times(1);
   2022   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap2))).Times(1);
   2023   ReportBSS("bss0", ap0->ssid_string(), ap0->bssid_string(), 0, 0,
   2024             kNetworkModeAdHoc);
   2025   ReportBSS("bss1", ap1->ssid_string(), ap1->bssid_string(), 0, 0,
   2026             kNetworkModeInfrastructure);
   2027   ReportBSS("bss2", ap2->ssid_string(), ap2->bssid_string(), 0, 0,
   2028             kNetworkModeInfrastructure);
   2029   manager()->set_suppress_autoconnect(true);
   2030   ReportScanDone();
   2031   EXPECT_FALSE(manager()->suppress_autoconnect());
   2032   Mock::VerifyAndClearExpectations(wifi_provider());
   2033 
   2034   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(_)).Times(0);
   2035 
   2036   // BSSes with SSIDs that start with nullptr should be filtered.
   2037   ReportBSS("bss3", string(1, 0), "00:00:00:00:00:03", 3, 0, kNetworkModeAdHoc);
   2038 
   2039   // BSSes with empty SSIDs should be filtered.
   2040   ReportBSS("bss3", string(), "00:00:00:00:00:03", 3, 0, kNetworkModeAdHoc);
   2041 }
   2042 
   2043 TEST_F(WiFiMainTest, LoneBSSRemovedWhileConnected) {
   2044   StartWiFi();
   2045   WiFiEndpointRefPtr endpoint;
   2046   string bss_path;
   2047   WiFiServiceRefPtr service(
   2048       SetupConnectedService("", &endpoint, &bss_path));
   2049   unique_ptr<EndpointRemovalHandler> handler(
   2050       MakeEndpointRemovalHandler(service));
   2051   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
   2052       .WillOnce(Invoke(handler.get(),
   2053                 &EndpointRemovalHandler::OnEndpointRemoved));
   2054   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2055   RemoveBSS(bss_path);
   2056 }
   2057 
   2058 TEST_F(WiFiMainTest, NonSolitaryBSSRemoved) {
   2059   StartWiFi();
   2060   WiFiEndpointRefPtr endpoint;
   2061   string bss_path;
   2062   WiFiServiceRefPtr service(
   2063       SetupConnectedService("", &endpoint, &bss_path));
   2064   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
   2065       .WillOnce(Return(nullptr));
   2066   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
   2067   RemoveBSS(bss_path);
   2068 }
   2069 
   2070 TEST_F(WiFiMainTest, ReconnectPreservesDBusPath) {
   2071   StartWiFi();
   2072   string kPath = "/test/path";
   2073   MockWiFiServiceRefPtr service(SetupConnectedService(kPath, nullptr, nullptr));
   2074 
   2075   // Return the service to a connectable state.
   2076   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2077   InitiateDisconnect(service);
   2078   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2079 
   2080   // Complete the disconnection by reporting a BSS change.
   2081   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   2082 
   2083   // A second connection attempt should remember the DBus path associated
   2084   // with this service, and should not request new configuration parameters.
   2085   EXPECT_CALL(*service, GetSupplicantConfigurationParameters()).Times(0);
   2086   EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(_, _)).Times(0);
   2087   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SelectNetwork(kPath));
   2088   InitiateConnect(service);
   2089 }
   2090 
   2091 TEST_F(WiFiMainTest, DisconnectPendingService) {
   2092   StartWiFi();
   2093   MockWiFiServiceRefPtr service(
   2094       SetupConnectingService("", nullptr, nullptr));
   2095   EXPECT_TRUE(GetPendingService() == service.get());
   2096   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2097   EXPECT_CALL(*service, SetFailure(_)).Times(0);
   2098   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2099   service->set_expecting_disconnect(true);
   2100   InitiateDisconnect(service);
   2101   Mock::VerifyAndClearExpectations(service.get());
   2102   EXPECT_EQ(nullptr, GetPendingService());;
   2103 }
   2104 
   2105 TEST_F(WiFiMainTest, DisconnectPendingServiceWithFailure) {
   2106   StartWiFi();
   2107   MockWiFiServiceRefPtr service(
   2108       SetupConnectingService("", nullptr, nullptr));
   2109   EXPECT_TRUE(GetPendingService() == service.get());
   2110   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2111   EXPECT_CALL(*service, SetFailure(Service::kFailureOutOfRange));
   2112   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2113   InitiateDisconnect(service);
   2114   Mock::VerifyAndClearExpectations(service.get());
   2115   EXPECT_EQ(nullptr, GetPendingService());;
   2116 }
   2117 
   2118 TEST_F(WiFiMainTest, DisconnectPendingServiceWithCurrent) {
   2119   StartWiFi();
   2120   MockWiFiServiceRefPtr service0(
   2121       SetupConnectedService("", nullptr, nullptr));
   2122   EXPECT_EQ(service0, GetCurrentService());
   2123   EXPECT_EQ(nullptr, GetPendingService().get());
   2124 
   2125   // We don't explicitly call Disconnect() while transitioning to a new
   2126   // service.  Instead, we use the side-effect of SelectNetwork (verified in
   2127   // SetupConnectingService).
   2128   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
   2129   MockWiFiServiceRefPtr service1(
   2130       SetupConnectingService("/new/path", nullptr, nullptr));
   2131   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2132 
   2133   EXPECT_EQ(service0, GetCurrentService());
   2134   EXPECT_EQ(service1, GetPendingService());
   2135   EXPECT_CALL(*service1, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2136   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2137   InitiateDisconnect(service1);
   2138   Mock::VerifyAndClearExpectations(service1.get());
   2139 
   2140   // |current_service_| will be unchanged until supplicant signals
   2141   // that CurrentBSS has changed.
   2142   EXPECT_EQ(service0, GetCurrentService());
   2143   // |pending_service_| is updated immediately.
   2144   EXPECT_EQ(nullptr, GetPendingService().get());
   2145   EXPECT_TRUE(GetPendingTimeout().IsCancelled());
   2146 }
   2147 
   2148 TEST_F(WiFiMainTest, DisconnectCurrentService) {
   2149   StartWiFi();
   2150   string kPath("/fake/path");
   2151   MockWiFiServiceRefPtr service(SetupConnectedService(kPath, nullptr, nullptr));
   2152   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2153   service->set_expecting_disconnect(true);
   2154   InitiateDisconnect(service);
   2155 
   2156   // |current_service_| should not change until supplicant reports
   2157   // a BSS change.
   2158   EXPECT_EQ(service, GetCurrentService());
   2159 
   2160   // Expect that the entry associated with this network will be disabled.
   2161   unique_ptr<MockSupplicantNetworkProxy> network_proxy(
   2162       new MockSupplicantNetworkProxy());
   2163   EXPECT_CALL(*control_interface(),
   2164               CreateSupplicantNetworkProxy(kPath))
   2165       .WillOnce(ReturnAndReleasePointee(&network_proxy));
   2166   EXPECT_CALL(*network_proxy, SetEnabled(false)).WillOnce(Return(true));
   2167   EXPECT_CALL(*eap_state_handler_, Reset());
   2168   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(0);
   2169   EXPECT_CALL(*service, SetFailure(_)).Times(0);
   2170   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2171   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   2172   EXPECT_EQ(nullptr, GetCurrentService().get());
   2173   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2174 }
   2175 
   2176 TEST_F(WiFiMainTest, DisconnectCurrentServiceWithFailure) {
   2177   StartWiFi();
   2178   string kPath("/fake/path");
   2179   MockWiFiServiceRefPtr service(SetupConnectedService(kPath, nullptr, nullptr));
   2180   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2181   InitiateDisconnect(service);
   2182 
   2183   // |current_service_| should not change until supplicant reports
   2184   // a BSS change.
   2185   EXPECT_EQ(service, GetCurrentService());
   2186 
   2187   // Expect that the entry associated with this network will be disabled.
   2188   unique_ptr<MockSupplicantNetworkProxy> network_proxy(
   2189       new MockSupplicantNetworkProxy());
   2190   EXPECT_CALL(*control_interface(),
   2191               CreateSupplicantNetworkProxy(kPath))
   2192       .WillOnce(ReturnAndReleasePointee(&network_proxy));
   2193   EXPECT_CALL(*network_proxy, SetEnabled(false)).WillOnce(Return(true));
   2194   EXPECT_CALL(*eap_state_handler_, Reset());
   2195   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(0);
   2196   EXPECT_CALL(*service, SetFailure(Service::kFailureOutOfRange));
   2197   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2198   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   2199   EXPECT_EQ(nullptr, GetCurrentService().get());
   2200   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2201 }
   2202 
   2203 TEST_F(WiFiMainTest, DisconnectCurrentServiceWithErrors) {
   2204   StartWiFi();
   2205   string kPath("/fake/path");
   2206   WiFiServiceRefPtr service(SetupConnectedService(kPath, nullptr, nullptr));
   2207   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect())
   2208       .WillOnce(Return(false));
   2209   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(1);
   2210   InitiateDisconnect(service);
   2211 
   2212   // We may sometimes fail to disconnect via supplicant, and we patch up some
   2213   // state when this happens.
   2214   EXPECT_EQ(nullptr, GetCurrentService().get());
   2215   EXPECT_EQ(nullptr, GetSelectedService().get());
   2216 }
   2217 
   2218 TEST_F(WiFiMainTest, DisconnectCurrentServiceWithPending) {
   2219   StartWiFi();
   2220   MockWiFiServiceRefPtr service0(SetupConnectedService("",
   2221                                                        nullptr, nullptr));
   2222   MockWiFiServiceRefPtr service1(SetupConnectingService("",
   2223                                                         nullptr, nullptr));
   2224   EXPECT_EQ(service0, GetCurrentService());
   2225   EXPECT_EQ(service1, GetPendingService());
   2226   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
   2227   InitiateDisconnect(service0);
   2228 
   2229   EXPECT_EQ(service0, GetCurrentService());
   2230   EXPECT_EQ(service1, GetPendingService());
   2231   EXPECT_FALSE(GetPendingTimeout().IsCancelled());
   2232 
   2233   EXPECT_CALL(*service0, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2234   EXPECT_CALL(*service0, SetFailure(_)).Times(0);
   2235   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   2236 }
   2237 
   2238 TEST_F(WiFiMainTest, DisconnectCurrentServiceWhileRoaming) {
   2239   StartWiFi();
   2240   string kPath("/fake/path");
   2241   WiFiServiceRefPtr service(SetupConnectedService(kPath, nullptr, nullptr));
   2242 
   2243   // As it roams to another AP, supplicant signals that it is in
   2244   // the authenticating state.
   2245   ReportStateChanged(WPASupplicant::kInterfaceStateAuthenticating);
   2246 
   2247   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2248   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath));
   2249   InitiateDisconnect(service);
   2250 
   2251   // Because the interface was not connected, we should have immediately
   2252   // forced ourselves into a disconnected state.
   2253   EXPECT_EQ(nullptr, GetCurrentService().get());
   2254   EXPECT_EQ(nullptr, GetSelectedService().get());
   2255 
   2256   // Check calls before TearDown/dtor.
   2257   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2258 }
   2259 
   2260 TEST_F(WiFiMainTest, DisconnectWithWiFiServiceConnected) {
   2261   StartWiFi();
   2262   MockWiFiServiceRefPtr service0(SetupConnectedService("",
   2263                                                        nullptr, nullptr));
   2264   NiceScopedMockLog log;
   2265   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   2266   ScopeLogger::GetInstance()->set_verbose_level(2);
   2267   EXPECT_CALL(log, Log(_, _, ContainsRegex("DisconnectFromIfActive.*service")))
   2268       .Times(1);
   2269   EXPECT_CALL(log,
   2270               Log(_, _, ContainsRegex("DisconnectFrom[^a-zA-Z].*service")))
   2271       .Times(1);
   2272   EXPECT_CALL(*service0, IsActive(_)).Times(0);
   2273   InitiateDisconnectIfActive(service0);
   2274 
   2275   Mock::VerifyAndClearExpectations(&log);
   2276   Mock::VerifyAndClearExpectations(service0.get());
   2277   ScopeLogger::GetInstance()->set_verbose_level(0);
   2278   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   2279 }
   2280 
   2281 TEST_F(WiFiMainTest, DisconnectWithWiFiServiceIdle) {
   2282   StartWiFi();
   2283   MockWiFiServiceRefPtr service0(SetupConnectedService("",
   2284                                                        nullptr, nullptr));
   2285   InitiateDisconnectIfActive(service0);
   2286   MockWiFiServiceRefPtr service1(SetupConnectedService("",
   2287                                                        nullptr, nullptr));
   2288   NiceScopedMockLog log;
   2289   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   2290   ScopeLogger::GetInstance()->set_verbose_level(2);
   2291   EXPECT_CALL(log, Log(_, _, ContainsRegex("DisconnectFromIfActive.*service")))
   2292       .Times(1);
   2293   EXPECT_CALL(*service0, IsActive(_)).WillOnce(Return(false));
   2294   EXPECT_CALL(log, Log(_, _, HasSubstr("is not active, no need"))).Times(1);
   2295   EXPECT_CALL(log, Log(logging::LOG_WARNING, _,
   2296                        ContainsRegex("In .*DisconnectFrom\\(.*\\):")))
   2297       .Times(0);
   2298   InitiateDisconnectIfActive(service0);
   2299 
   2300   Mock::VerifyAndClearExpectations(&log);
   2301   Mock::VerifyAndClearExpectations(service0.get());
   2302   ScopeLogger::GetInstance()->set_verbose_level(0);
   2303   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   2304 }
   2305 
   2306 TEST_F(WiFiMainTest, DisconnectWithWiFiServiceConnectedInError) {
   2307   StartWiFi();
   2308   MockWiFiServiceRefPtr service0(SetupConnectedService("",
   2309                                                        nullptr, nullptr));
   2310   SetCurrentService(nullptr);
   2311   ResetPendingService();
   2312   NiceScopedMockLog log;
   2313   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   2314   ScopeLogger::GetInstance()->set_verbose_level(2);
   2315   EXPECT_CALL(log, Log(_, _, ContainsRegex("DisconnectFromIfActive.*service")))
   2316       .Times(1);
   2317   EXPECT_CALL(*service0, IsActive(_)).WillOnce(Return(true));
   2318   EXPECT_CALL(log,
   2319               Log(_, _, ContainsRegex("DisconnectFrom[^a-zA-Z].*service")))
   2320       .Times(1);
   2321   EXPECT_CALL(log, Log(logging::LOG_WARNING, _,
   2322                        ContainsRegex("In .*DisconnectFrom\\(.*\\):"))).Times(1);
   2323   InitiateDisconnectIfActive(service0);
   2324 
   2325   Mock::VerifyAndClearExpectations(&log);
   2326   Mock::VerifyAndClearExpectations(service0.get());
   2327   ScopeLogger::GetInstance()->set_verbose_level(0);
   2328   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   2329 }
   2330 
   2331 TEST_F(WiFiMainTest, TimeoutPendingServiceWithEndpoints) {
   2332   StartScan(WiFi::kScanMethodProgressive);
   2333   const base::CancelableClosure& pending_timeout = GetPendingTimeout();
   2334   EXPECT_TRUE(pending_timeout.IsCancelled());
   2335   MockWiFiServiceRefPtr service = AttemptConnection(
   2336       WiFi::kScanMethodProgressive, nullptr, nullptr);
   2337 
   2338   // Timeout the connection attempt.
   2339   EXPECT_FALSE(pending_timeout.IsCancelled());
   2340   EXPECT_EQ(service, GetPendingService());
   2341   // Simulate a service with a wifi_ reference calling DisconnectFrom().
   2342   EXPECT_CALL(*service,
   2343               DisconnectWithFailure(Service::kFailureOutOfRange, _,
   2344                                     HasSubstr("PendingTimeoutHandler")))
   2345       .WillOnce(InvokeWithoutArgs(this, &WiFiObjectTest::ResetPendingService));
   2346   EXPECT_CALL(*service, HasEndpoints()).Times(0);
   2347   // DisconnectFrom() should not be called directly from WiFi.
   2348   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(1);
   2349   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
   2350 
   2351   // Innocuous redundant call to NotifyDeviceScanFinished.
   2352   ExpectFoundNothing();
   2353   EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_)).Times(0);
   2354   NiceScopedMockLog log;
   2355   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   2356   ScopeLogger::GetInstance()->set_verbose_level(10);
   2357   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   2358   EXPECT_CALL(log, Log(_, _,
   2359                        HasSubstr("-> PROGRESSIVE_FINISHED_NOCONNECTION")));
   2360   pending_timeout.callback().Run();
   2361   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2362   // Service state should be idle, so it is connectable again.
   2363   EXPECT_EQ(Service::kStateIdle, service->state());
   2364   Mock::VerifyAndClearExpectations(service.get());
   2365 
   2366   ScopeLogger::GetInstance()->set_verbose_level(0);
   2367   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   2368 }
   2369 
   2370 TEST_F(WiFiMainTest, TimeoutPendingServiceWithoutEndpoints) {
   2371   StartWiFi();
   2372   const base::CancelableClosure& pending_timeout = GetPendingTimeout();
   2373   EXPECT_TRUE(pending_timeout.IsCancelled());
   2374   MockWiFiServiceRefPtr service(
   2375       SetupConnectingService("", nullptr, nullptr));
   2376   EXPECT_FALSE(pending_timeout.IsCancelled());
   2377   EXPECT_EQ(service, GetPendingService());
   2378   // We expect the service to get a disconnect call, but in this scenario
   2379   // the service does nothing.
   2380   EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureOutOfRange,
   2381                                               _,
   2382                                               HasSubstr("PendingTimeoutHandler")));
   2383   EXPECT_CALL(*service, HasEndpoints()).WillOnce(Return(false));
   2384   // DisconnectFrom() should be called directly from WiFi.
   2385   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2386   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2387   pending_timeout.callback().Run();
   2388   EXPECT_EQ(nullptr, GetPendingService().get());
   2389 }
   2390 
   2391 TEST_F(WiFiMainTest, DisconnectInvalidService) {
   2392   StartWiFi();
   2393   MockWiFiServiceRefPtr service;
   2394   MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, nullptr, &service);
   2395   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
   2396   InitiateDisconnect(service);
   2397 }
   2398 
   2399 TEST_F(WiFiMainTest, DisconnectCurrentServiceFailure) {
   2400   StartWiFi();
   2401   string kPath("/fake/path");
   2402   WiFiServiceRefPtr service(SetupConnectedService(kPath, nullptr, nullptr));
   2403   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect())
   2404       .WillRepeatedly(Return(false));
   2405   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath));
   2406   InitiateDisconnect(service);
   2407   EXPECT_EQ(nullptr, GetCurrentService().get());
   2408 }
   2409 
   2410 TEST_F(WiFiMainTest, Stop) {
   2411   StartWiFi();
   2412   WiFiEndpointRefPtr endpoint0;
   2413   string kPath("/fake/path");
   2414   WiFiServiceRefPtr service0(SetupConnectedService(kPath, &endpoint0, nullptr));
   2415   WiFiEndpointRefPtr endpoint1;
   2416   MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, &endpoint1, nullptr);
   2417 
   2418   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint0)))
   2419       .WillOnce(Return(nullptr));
   2420   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint1)))
   2421       .WillOnce(Return(nullptr));
   2422   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(1);
   2423   StopWiFi();
   2424   EXPECT_TRUE(GetScanTimer().IsCancelled());
   2425   EXPECT_FALSE(wifi()->weak_ptr_factory_.HasWeakPtrs());
   2426 }
   2427 
   2428 TEST_F(WiFiMainTest, StopWhileConnected) {
   2429   StartWiFi();
   2430   WiFiEndpointRefPtr endpoint;
   2431   WiFiServiceRefPtr service(
   2432       SetupConnectedService("", &endpoint, nullptr));
   2433   unique_ptr<EndpointRemovalHandler> handler(
   2434       MakeEndpointRemovalHandler(service));
   2435   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
   2436       .WillOnce(Invoke(handler.get(),
   2437                 &EndpointRemovalHandler::OnEndpointRemoved));
   2438   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2439   StopWiFi();
   2440   EXPECT_EQ(nullptr, GetCurrentService());;
   2441 }
   2442 
   2443 TEST_F(WiFiMainTest, ReconnectTimer) {
   2444   StartWiFi();
   2445   MockWiFiServiceRefPtr service(
   2446       SetupConnectedService("", nullptr, nullptr));
   2447   EXPECT_CALL(*service, IsConnected()).WillRepeatedly(Return(true));
   2448   EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
   2449   ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
   2450   EXPECT_FALSE(GetReconnectTimeoutCallback().IsCancelled());
   2451   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   2452   EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
   2453   ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
   2454   EXPECT_FALSE(GetReconnectTimeoutCallback().IsCancelled());
   2455   ReportCurrentBSSChanged(kBSSName);
   2456   EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
   2457   ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
   2458   EXPECT_FALSE(GetReconnectTimeoutCallback().IsCancelled());
   2459   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2460   GetReconnectTimeoutCallback().callback().Run();
   2461   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2462   EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
   2463 }
   2464 
   2465 
   2466 MATCHER_P(HasHiddenSSID_FullScan, ssid, "") {
   2467   if (!arg.ContainsByteArrays(WPASupplicant::kPropertyScanSSIDs)) {
   2468     return false;
   2469   }
   2470 
   2471   ByteArrays ssids = arg.GetByteArrays(WPASupplicant::kPropertyScanSSIDs);
   2472   // A valid Scan containing a single hidden SSID should contain
   2473   // two SSID entries: one containing the SSID we are looking for,
   2474   // and an empty entry, signifying that we also want to do a
   2475   // broadcast probe request for all non-hidden APs as well.
   2476   return ssids.size() == 2 && ssids[0] == ssid && ssids[1].empty();
   2477 }
   2478 
   2479 MATCHER(HasNoHiddenSSID_FullScan, "") {
   2480   return !arg.ContainsByteArrays(WPASupplicant::kPropertyScanSSIDs);
   2481 }
   2482 
   2483 TEST_F(WiFiMainTest, ScanHidden_FullScan) {
   2484   EnableFullScan();
   2485   vector<uint8_t>kSSID(1, 'a');
   2486   ByteArrays ssids;
   2487   ssids.push_back(kSSID);
   2488 
   2489   StartWiFi();
   2490   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList()).WillOnce(Return(ssids));
   2491   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   2492               Scan(HasHiddenSSID_FullScan(kSSID)));
   2493   dispatcher_.DispatchPendingEvents();
   2494 }
   2495 
   2496 // This test is slightly different from the test in scan_session_unittest.cc
   2497 // because this tests the piece of WiFi that builds the SSID list.
   2498 TEST_F(WiFiMainTest, ScanHidden) {
   2499   // Clear the Mock ScanSession because hidden SSIDs are added when wifi
   2500   // instantiates a new ScanSession (and it won't instantiate a new ScanSession
   2501   // if there's already one there).
   2502   ClearScanSession();
   2503   vector<uint8_t>kSSID(1, 'a');
   2504   ByteArrays ssids;
   2505   ssids.push_back(kSSID);
   2506 
   2507   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList()).WillOnce(Return(ssids));
   2508   StartWiFi();
   2509   EXPECT_CALL(netlink_manager_,
   2510               SendNl80211Message(HasHiddenSSID(kNl80211FamilyId), _, _, _));
   2511   dispatcher_.DispatchPendingEvents();
   2512 }
   2513 
   2514 TEST_F(WiFiMainTest, ScanNoHidden_FullScan) {
   2515   EnableFullScan();
   2516   StartWiFi();
   2517   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
   2518       .WillOnce(Return(ByteArrays()));
   2519   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(HasNoHiddenSSID_FullScan()));
   2520   dispatcher_.DispatchPendingEvents();
   2521 }
   2522 
   2523 // This test is slightly different from the test in scan_session_unittest.cc
   2524 // because this tests the piece of WiFi that builds the SSID list.
   2525 TEST_F(WiFiMainTest, ScanNoHidden) {
   2526   // Clear the Mock ScanSession because hidden SSIDs are added when wifi
   2527   // instantiates a new ScanSession (and it won't instantiate a new ScanSession
   2528   // if there's already one there).
   2529   ClearScanSession();
   2530   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
   2531       .WillOnce(Return(ByteArrays()));
   2532   StartWiFi();
   2533   EXPECT_CALL(netlink_manager_,
   2534               SendNl80211Message(HasNoHiddenSSID(kNl80211FamilyId), _, _, _));
   2535   dispatcher_.DispatchPendingEvents();
   2536 }
   2537 
   2538 TEST_F(WiFiMainTest, ScanWiFiDisabledAfterResume) {
   2539   ScopedMockLog log;
   2540   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   2541   EXPECT_CALL(log, Log(_, _, EndsWith(
   2542       "Ignoring scan request while device is not enabled."))).Times(1);
   2543   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   2544   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   2545   StartWiFi();
   2546   StopWiFi();
   2547   // A scan is queued when WiFi resumes.
   2548   OnAfterResume();
   2549   dispatcher_.DispatchPendingEvents();
   2550 }
   2551 
   2552 TEST_F(WiFiMainTest, ScanRejected) {
   2553   StartWiFi();
   2554   ReportScanDone();
   2555   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2556 
   2557   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_))
   2558       .WillOnce(Return(false));
   2559   TriggerScan(WiFi::kScanMethodFull);
   2560   dispatcher_.DispatchPendingEvents();
   2561   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2562 }
   2563 
   2564 TEST_F(WiFiMainTest, ProgressiveScanFound) {
   2565   // Set min & max scan frequency count to 1 so each scan will be of a single
   2566   // frequency.
   2567   SetScanSize(1, 1);
   2568 
   2569   // Do the first scan (finds nothing).
   2570   StartScan(WiFi::kScanMethodProgressive);
   2571   EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_)).Times(0);
   2572   ReportScanDoneKeepScanSession();
   2573 
   2574   // Do the second scan (connects afterwards).
   2575   ExpectScanStart(WiFi::kScanMethodProgressive, true);
   2576   dispatcher_.DispatchPendingEvents();
   2577   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
   2578   ReportScanDoneKeepScanSession();
   2579 
   2580   // Connect after second scan.
   2581   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   2582   EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
   2583   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   2584   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   2585   EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty, false));
   2586   SetPendingService(service);
   2587 
   2588   // Verify that the third scan aborts and there is no further scan.
   2589   ScopedMockLog log;
   2590   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   2591   EXPECT_CALL(log, Log(_, _, EndsWith(
   2592       "Ignoring scan request while connecting to an AP."))).Times(1);
   2593   dispatcher_.DispatchPendingEvents();
   2594   VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
   2595 }
   2596 
   2597 TEST_F(WiFiMainTest, ProgressiveScanNotFound) {
   2598   // Set min & max scan frequency count to 1 so each scan will be of a single
   2599   // frequency.
   2600   SetScanSize(1, 1);
   2601 
   2602   // This test never connects
   2603   EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _)).Times(0);
   2604   EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_)).Times(0);
   2605 
   2606   // Do the first scan (finds nothing).
   2607   StartScan(WiFi::kScanMethodProgressive);
   2608   ReportScanDoneKeepScanSession();
   2609 
   2610   // Do the second scan (finds nothing).
   2611   ExpectScanStart(WiFi::kScanMethodProgressive, true);
   2612   EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_)).Times(0);
   2613   dispatcher_.DispatchPendingEvents();
   2614   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
   2615   ReportScanDoneKeepScanSession();
   2616 
   2617   // Do the third scan. After (simulated) exhausting of search frequencies,
   2618   // verify that this scan uses supplicant rather than internal (progressive)
   2619   // scan.
   2620   EXPECT_CALL(*scan_session_, HasMoreFrequencies()).WillOnce(Return(false));
   2621   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   2622   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   2623   dispatcher_.DispatchPendingEvents();
   2624   VerifyScanState(WiFi::kScanScanning,
   2625                   WiFi::kScanMethodProgressiveFinishedToFull);
   2626 
   2627   // And verify that ScanDone reports a complete scan (i.e., the
   2628   // wifi_::scan_session_ has truly been cleared).
   2629   ExpectScanStop();
   2630   ExpectFoundNothing();
   2631   ReportScanDoneKeepScanSession();
   2632   dispatcher_.DispatchPendingEvents();  // Launch UpdateScanStateAfterScanDone
   2633   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2634 }
   2635 
   2636 TEST_F(WiFiMainTest, ProgressiveScanError) {
   2637   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2638   ClearScanSession();  // Clear Mock ScanSession to get an actual ScanSession.
   2639   StartWiFi();  // Posts |ProgressiveScanTask|.
   2640 
   2641   EXPECT_CALL(netlink_manager_, SendNl80211Message(
   2642       IsNl80211Command(kNl80211FamilyId, NL80211_CMD_TRIGGER_SCAN), _, _, _));
   2643   dispatcher_.DispatchPendingEvents();  // Executes |ProgressiveScanTask|.
   2644 
   2645   // Calls |WiFi::OnFailedProgressiveScan| which calls |ScanTask|
   2646   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(1);
   2647   NewScanResultsMessage not_supposed_to_get_this_message;
   2648   OnTriggerScanResponse(not_supposed_to_get_this_message);
   2649   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressiveErrorToFull);
   2650 
   2651   EXPECT_TRUE(IsScanSessionNull());
   2652 
   2653   // Post and execute |UpdateScanStateAfterScanDone|.
   2654   ReportScanDoneKeepScanSession();
   2655   dispatcher_.DispatchPendingEvents();
   2656   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2657 }
   2658 
   2659 TEST_F(WiFiMainTest, InitialSupplicantState) {
   2660   EXPECT_EQ(WiFi::kInterfaceStateUnknown, GetSupplicantState());
   2661 }
   2662 
   2663 TEST_F(WiFiMainTest, StateChangeNoService) {
   2664   // State change should succeed even if there is no pending Service.
   2665   ReportStateChanged(WPASupplicant::kInterfaceStateScanning);
   2666   EXPECT_EQ(WPASupplicant::kInterfaceStateScanning, GetSupplicantState());
   2667 }
   2668 
   2669 TEST_F(WiFiMainTest, StateChangeWithService) {
   2670   // Forward transition should trigger a Service state change.
   2671   StartWiFi();
   2672   dispatcher_.DispatchPendingEvents();
   2673   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   2674   InitiateConnect(service);
   2675   EXPECT_CALL(*service.get(), SetState(Service::kStateAssociating));
   2676   ReportStateChanged(WPASupplicant::kInterfaceStateAssociated);
   2677   // Verify expectations now, because WiFi may report other state changes
   2678   // when WiFi is Stop()-ed (during TearDown()).
   2679   Mock::VerifyAndClearExpectations(service.get());
   2680   EXPECT_CALL(*service.get(), SetState(_)).Times(AnyNumber());
   2681 }
   2682 
   2683 TEST_F(WiFiMainTest, StateChangeBackwardsWithService) {
   2684   // Some backwards transitions should not trigger a Service state change.
   2685   // Supplicant state should still be updated, however.
   2686   EXPECT_CALL(*dhcp_provider(), CreateIPv4Config(_, _, _, _))
   2687       .Times(AnyNumber());
   2688   EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(AnyNumber());
   2689   StartWiFi();
   2690   dispatcher_.DispatchPendingEvents();
   2691   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   2692   EXPECT_CALL(*service, SetState(Service::kStateAssociating));
   2693   EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
   2694   EXPECT_CALL(*service, ResetSuspectedCredentialFailures());
   2695   InitiateConnect(service);
   2696   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   2697   ReportStateChanged(WPASupplicant::kInterfaceStateAuthenticating);
   2698   EXPECT_EQ(WPASupplicant::kInterfaceStateAuthenticating,
   2699             GetSupplicantState());
   2700   // Verify expectations now, because WiFi may report other state changes
   2701   // when WiFi is Stop()-ed (during TearDown()).
   2702   Mock::VerifyAndClearExpectations(service.get());
   2703   EXPECT_CALL(*service, SetState(_)).Times(AnyNumber());
   2704 }
   2705 
   2706 TEST_F(WiFiMainTest, ConnectToServiceWithoutRecentIssues) {
   2707   MockSupplicantProcessProxy* process_proxy = supplicant_process_proxy_;
   2708   StartWiFi();
   2709   dispatcher_.DispatchPendingEvents();
   2710   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   2711   EXPECT_CALL(*process_proxy, GetDebugLevel(_)).Times(0);
   2712   EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
   2713   EXPECT_CALL(*service.get(), HasRecentConnectionIssues())
   2714       .WillOnce(Return(false));
   2715   InitiateConnect(service);
   2716 }
   2717 
   2718 TEST_F(WiFiMainTest, ConnectToServiceWithRecentIssues) {
   2719   // Turn of WiFi debugging, so the only reason we will turn on supplicant
   2720   // debugging will be to debug a problematic connection.
   2721   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   2722 
   2723   MockSupplicantProcessProxy* process_proxy = supplicant_process_proxy_;
   2724   StartWiFi();
   2725   dispatcher_.DispatchPendingEvents();
   2726   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   2727   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   2728       .WillOnce(
   2729           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelInfo)),
   2730                 Return(true)));
   2731   EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelDebug))
   2732       .Times(1);
   2733   EXPECT_CALL(*service.get(), HasRecentConnectionIssues())
   2734       .WillOnce(Return(true));
   2735   InitiateConnect(service);
   2736   Mock::VerifyAndClearExpectations(process_proxy);
   2737 
   2738   SetPendingService(nullptr);
   2739   SetCurrentService(service);
   2740 
   2741   // When we disconnect from the troubled service, we should reduce the
   2742   // level of supplicant debugging.
   2743   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   2744       .WillOnce(
   2745           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelDebug)),
   2746                 Return(true)));
   2747   EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelInfo))
   2748       .Times(1);
   2749   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   2750 }
   2751 
   2752 TEST_F(WiFiMainTest, CurrentBSSChangeConnectedToDisconnected) {
   2753   StartWiFi();
   2754   WiFiEndpointRefPtr endpoint;
   2755   MockWiFiServiceRefPtr service =
   2756       SetupConnectedService("", &endpoint, nullptr);
   2757 
   2758   EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2759   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   2760   EXPECT_EQ(nullptr, GetCurrentService().get());
   2761   EXPECT_EQ(nullptr, GetPendingService().get());
   2762   EXPECT_FALSE(GetIsRoamingInProgress());
   2763 }
   2764 
   2765 TEST_F(WiFiMainTest, CurrentBSSChangeConnectedToConnectedNewService) {
   2766   StartWiFi();
   2767   MockWiFiServiceRefPtr service0 =
   2768       SetupConnectedService("", nullptr, nullptr);
   2769   MockWiFiServiceRefPtr service1;
   2770   string bss_path1(MakeNewEndpointAndService(
   2771       0, 0, kNetworkModeAdHoc, nullptr, &service1));
   2772   EXPECT_EQ(service0.get(), GetCurrentService().get());
   2773 
   2774   // Note that we deliberately omit intermediate supplicant states
   2775   // (e.g. kInterfaceStateAssociating), on the theory that they are
   2776   // unreliable. Specifically, they may be quashed if the association
   2777   // completes before supplicant flushes its changed properties.
   2778   EXPECT_CALL(*service0, SetState(Service::kStateIdle)).Times(AtLeast(1));
   2779   ReportCurrentBSSChanged(bss_path1);
   2780   EXPECT_CALL(*service1, SetState(Service::kStateConfiguring));
   2781   EXPECT_CALL(*service1, ResetSuspectedCredentialFailures());
   2782   EXPECT_CALL(*wifi_provider(), IncrementConnectCount(_));
   2783   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   2784   EXPECT_EQ(service1.get(), GetCurrentService().get());
   2785   EXPECT_FALSE(GetIsRoamingInProgress());
   2786   Mock::VerifyAndClearExpectations(service0.get());
   2787   Mock::VerifyAndClearExpectations(service1.get());
   2788 }
   2789 
   2790 TEST_F(WiFiMainTest, CurrentBSSChangedUpdateServiceEndpoint) {
   2791   StartWiFi();
   2792   dispatcher_.DispatchPendingEvents();
   2793   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
   2794 
   2795   MockWiFiServiceRefPtr service =
   2796       SetupConnectedService("", nullptr, nullptr);
   2797   WiFiEndpointRefPtr endpoint;
   2798   string bss_path =
   2799       AddEndpointToService(service, 0, 0, kNetworkModeAdHoc, &endpoint);
   2800   EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
   2801   ReportCurrentBSSChanged(bss_path);
   2802   EXPECT_TRUE(GetIsRoamingInProgress());
   2803   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   2804 
   2805   // If we report a "completed" state change on a connected service after
   2806   // wpa_supplicant has roamed, we should renew our IPConfig.
   2807   scoped_refptr<MockIPConfig> ipconfig(
   2808       new MockIPConfig(control_interface(), kDeviceName));
   2809   SetIPConfig(ipconfig);
   2810   EXPECT_CALL(*service, IsConnected()).WillOnce(Return(true));
   2811   EXPECT_CALL(*ipconfig, RenewIP());
   2812   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   2813   Mock::VerifyAndClearExpectations(ipconfig.get());
   2814   EXPECT_FALSE(GetIsRoamingInProgress());
   2815 }
   2816 
   2817 TEST_F(WiFiMainTest, DisconnectReasonUpdated) {
   2818   ScopedMockLog log;
   2819   int test_reason = 4;
   2820   int test_reason_second = 0;
   2821   EXPECT_CALL(*adaptor_, EmitBoolChanged(kPoweredProperty, _))
   2822       .Times(AnyNumber());
   2823   EXPECT_EQ(GetSupplicantDisconnectReason(), WiFi::kDefaultDisconnectReason);
   2824   EXPECT_CALL(log,
   2825               Log(logging::LOG_INFO, _, EndsWith(" DisconnectReason to 4")));
   2826   ReportDisconnectReasonChanged(test_reason);
   2827   EXPECT_EQ(GetSupplicantDisconnectReason(), test_reason);
   2828   EXPECT_CALL(log,
   2829               Log(logging::LOG_INFO, _, EndsWith("Reason to 0 (was 4)")));
   2830   ReportDisconnectReasonChanged(test_reason_second);
   2831   EXPECT_EQ(GetSupplicantDisconnectReason(), test_reason_second);
   2832 }
   2833 
   2834 TEST_F(WiFiMainTest, DisconnectReasonCleared) {
   2835   int test_reason = 4;
   2836   // Clearing the value for supplicant_disconnect_reason_ is done prior to any
   2837   // early exits in the WiFi::StateChanged method.  This allows the value to be
   2838   // checked without a mock pending or current service.
   2839   ReportDisconnectReasonChanged(test_reason);
   2840   EXPECT_EQ(wifi().get()->supplicant_disconnect_reason_, test_reason);
   2841   ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
   2842   ReportStateChanged(WPASupplicant::kInterfaceStateAssociated);
   2843   EXPECT_EQ(wifi().get()->supplicant_disconnect_reason_,
   2844             WiFi::kDefaultDisconnectReason);
   2845 }
   2846 
   2847 TEST_F(WiFiMainTest, NewConnectPreemptsPending) {
   2848   StartWiFi();
   2849   MockWiFiServiceRefPtr service0(
   2850       SetupConnectingService("", nullptr, nullptr));
   2851   EXPECT_EQ(service0.get(), GetPendingService().get());
   2852   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   2853   MockWiFiServiceRefPtr service1(
   2854       SetupConnectingService("", nullptr, nullptr));
   2855   EXPECT_EQ(service1.get(), GetPendingService().get());
   2856   EXPECT_EQ(nullptr, GetCurrentService().get());
   2857 }
   2858 
   2859 TEST_F(WiFiMainTest, ConnectedToUnintendedPreemptsPending) {
   2860   StartWiFi();
   2861   string bss_path;
   2862   // Connecting two different services back-to-back.
   2863   MockWiFiServiceRefPtr unintended_service(
   2864       SetupConnectingService("", nullptr, &bss_path));
   2865   MockWiFiServiceRefPtr intended_service(
   2866       SetupConnectingService("", nullptr, nullptr));
   2867 
   2868   // Verify the pending service.
   2869   EXPECT_EQ(intended_service.get(), GetPendingService().get());
   2870 
   2871   // Connected to the unintended service (service0).
   2872   ReportCurrentBSSChanged(bss_path);
   2873 
   2874   // Verify the pending service is disconnected, and the service state is back
   2875   // to idle, so it is connectable again.
   2876   EXPECT_EQ(nullptr, GetPendingService().get());
   2877   EXPECT_EQ(nullptr, GetCurrentService().get());
   2878   EXPECT_EQ(Service::kStateIdle, intended_service->state());
   2879 }
   2880 
   2881 TEST_F(WiFiMainTest, IsIdle) {
   2882   StartWiFi();
   2883   EXPECT_TRUE(wifi()->IsIdle());
   2884   MockWiFiServiceRefPtr service(
   2885       SetupConnectingService("", nullptr, nullptr));
   2886   EXPECT_FALSE(wifi()->IsIdle());
   2887 }
   2888 
   2889 MATCHER_P(WiFiAddedArgs, bgscan, "") {
   2890   return arg.ContainsUint(WPASupplicant::kNetworkPropertyScanSSID) &&
   2891       arg.ContainsUint(WPASupplicant::kNetworkPropertyDisableVHT) &&
   2892       arg.ContainsString(WPASupplicant::kNetworkPropertyBgscan) == bgscan;
   2893 }
   2894 
   2895 TEST_F(WiFiMainTest, AddNetworkArgs) {
   2896   StartWiFi();
   2897   MockWiFiServiceRefPtr service;
   2898   MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, nullptr, &service);
   2899   EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
   2900   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   2901               AddNetwork(WiFiAddedArgs(true), _));
   2902   EXPECT_TRUE(SetBgscanMethod(WPASupplicant::kNetworkBgscanMethodSimple));
   2903   InitiateConnect(service);
   2904 }
   2905 
   2906 TEST_F(WiFiMainTest, AddNetworkArgsNoBgscan) {
   2907   StartWiFi();
   2908   MockWiFiServiceRefPtr service;
   2909   MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, nullptr, &service);
   2910   EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
   2911   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   2912               AddNetwork(WiFiAddedArgs(false), _));
   2913   InitiateConnect(service);
   2914 }
   2915 
   2916 TEST_F(WiFiMainTest, AppendBgscan) {
   2917   StartWiFi();
   2918   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   2919   {
   2920     // 1 endpoint, default bgscan method -- background scan disabled.
   2921     KeyValueStore params;
   2922     EXPECT_CALL(*service, GetEndpointCount()).WillOnce(Return(1));
   2923     AppendBgscan(service.get(), &params);
   2924     Mock::VerifyAndClearExpectations(service.get());
   2925     EXPECT_FALSE(params.ContainsString(WPASupplicant::kNetworkPropertyBgscan));
   2926   }
   2927   {
   2928     // 2 endpoints, default bgscan method -- background scan frequency reduced.
   2929     KeyValueStore params;
   2930     EXPECT_CALL(*service, GetEndpointCount()).WillOnce(Return(2));
   2931     AppendBgscan(service.get(), &params);
   2932     Mock::VerifyAndClearExpectations(service.get());
   2933     string config_string;
   2934     EXPECT_TRUE(params.ContainsString(WPASupplicant::kNetworkPropertyBgscan));
   2935     config_string = params.GetString(WPASupplicant::kNetworkPropertyBgscan);
   2936     vector<string> elements = base::SplitString(
   2937         config_string, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
   2938     ASSERT_EQ(4, elements.size());
   2939     EXPECT_EQ(WiFi::kDefaultBgscanMethod, elements[0]);
   2940     EXPECT_EQ(StringPrintf("%d", WiFi::kBackgroundScanIntervalSeconds),
   2941               elements[3]);
   2942   }
   2943   {
   2944     // Explicit bgscan method -- regular background scan frequency.
   2945     EXPECT_TRUE(SetBgscanMethod(WPASupplicant::kNetworkBgscanMethodSimple));
   2946     KeyValueStore params;
   2947     EXPECT_CALL(*service, GetEndpointCount()).Times(0);
   2948     AppendBgscan(service.get(), &params);
   2949     Mock::VerifyAndClearExpectations(service.get());
   2950     EXPECT_TRUE(params.ContainsString(WPASupplicant::kNetworkPropertyBgscan));
   2951     string config_string =
   2952         params.GetString(WPASupplicant::kNetworkPropertyBgscan);
   2953     vector<string> elements = base::SplitString(
   2954         config_string, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
   2955     ASSERT_EQ(4, elements.size());
   2956     EXPECT_EQ(StringPrintf("%d", WiFi::kDefaultScanIntervalSeconds),
   2957               elements[3]);
   2958   }
   2959   {
   2960     // No scan method, simply returns without appending properties
   2961     EXPECT_TRUE(SetBgscanMethod(WPASupplicant::kNetworkBgscanMethodNone));
   2962     KeyValueStore params;
   2963     EXPECT_CALL(*service, GetEndpointCount()).Times(0);
   2964     AppendBgscan(service.get(), &params);
   2965     Mock::VerifyAndClearExpectations(service.get());
   2966     string config_string;
   2967     EXPECT_FALSE(params.ContainsString(WPASupplicant::kNetworkPropertyBgscan));
   2968   }
   2969 }
   2970 
   2971 TEST_F(WiFiMainTest, StateAndIPIgnoreLinkEvent) {
   2972   StartWiFi();
   2973   MockWiFiServiceRefPtr service(
   2974       SetupConnectingService("", nullptr, nullptr));
   2975   EXPECT_CALL(*service.get(), SetState(_)).Times(0);
   2976   EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(0);
   2977   ReportLinkUp();
   2978 
   2979   // Verify expectations now, because WiFi may cause |service| state
   2980   // changes during TearDown().
   2981   Mock::VerifyAndClearExpectations(service.get());
   2982 }
   2983 
   2984 TEST_F(WiFiMainTest, SupplicantCompletedAlreadyConnected) {
   2985   StartWiFi();
   2986   MockWiFiServiceRefPtr service(
   2987       SetupConnectedService("", nullptr, nullptr));
   2988   Mock::VerifyAndClearExpectations(dhcp_config_.get());
   2989   EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(0);
   2990   // Simulate a rekeying event from the AP.  These show as transitions from
   2991   // completed->completed from wpa_supplicant.
   2992   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   2993   // When we get an IP, WiFi should enable high bitrates on the interface again.
   2994   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   2995   EXPECT_CALL(*GetSupplicantInterfaceProxy(), EnableHighBitrates()).Times(1);
   2996   EXPECT_CALL(*manager(), device_info()).WillOnce(Return(device_info()));
   2997   ReportIPConfigComplete();
   2998   // Similarly, rekeying events after we have an IP don't trigger L3
   2999   // configuration.  However, we treat all transitions to completed as potential
   3000   // reassociations, so we will reenable high rates again here.
   3001   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   3002   EXPECT_CALL(*service, IsConnected()).WillOnce(Return(true));
   3003   EXPECT_CALL(*GetSupplicantInterfaceProxy(), EnableHighBitrates()).Times(1);
   3004   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   3005 }
   3006 
   3007 TEST_F(WiFiMainTest, BSSAddedCreatesBSSProxy) {
   3008   // TODO(quiche): Consider using a factory for WiFiEndpoints, so that
   3009   // we can test the interaction between WiFi and WiFiEndpoint. (Right
   3010   // now, we're testing across multiple layers.)
   3011   EXPECT_CALL(*supplicant_bss_proxy_, Die()).Times(AnyNumber());
   3012   EXPECT_CALL(*control_interface(), CreateSupplicantBSSProxy(_, _));
   3013   StartWiFi();
   3014   ReportBSS("bss0", "ssid0", "00:00:00:00:00:00", 0, 0, kNetworkModeAdHoc);
   3015 }
   3016 
   3017 TEST_F(WiFiMainTest, BSSRemovedDestroysBSSProxy) {
   3018   // TODO(quiche): As for BSSAddedCreatesBSSProxy, consider using a
   3019   // factory for WiFiEndpoints.
   3020   // Get the pointer before we transfer ownership.
   3021   MockSupplicantBSSProxy* proxy = supplicant_bss_proxy_.get();
   3022   EXPECT_CALL(*proxy, Die());
   3023   StartWiFi();
   3024   string bss_path(
   3025       MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, nullptr, nullptr));
   3026   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(_)).WillOnce(Return(nullptr));
   3027   RemoveBSS(bss_path);
   3028   // Check this now, to make sure RemoveBSS killed the proxy (rather
   3029   // than TearDown).
   3030   Mock::VerifyAndClearExpectations(proxy);
   3031 }
   3032 
   3033 TEST_F(WiFiMainTest, FlushBSSOnResume) {
   3034   const struct timeval resume_time = {1, 0};
   3035   const struct timeval scan_done_time = {6, 0};
   3036 
   3037   StartWiFi();
   3038 
   3039   EXPECT_CALL(time_, GetTimeMonotonic(_))
   3040       .WillOnce(DoAll(SetArgumentPointee<0>(resume_time), Return(0)))
   3041       .WillOnce(DoAll(SetArgumentPointee<0>(scan_done_time), Return(0)));
   3042   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   3043               FlushBSS(WiFi::kMaxBSSResumeAgeSeconds + 5));
   3044   OnAfterResume();
   3045   ReportScanDone();
   3046 }
   3047 
   3048 TEST_F(WiFiMainTest, CallWakeOnWiFi_OnScanDone) {
   3049   StartWiFi();
   3050 
   3051   // Call WakeOnWiFi::OnNoAutoConnetableServicesAfterScan if we find 0 auto-
   3052   // connectable services.
   3053   EXPECT_CALL(*wifi_provider(), NumAutoConnectableServices())
   3054       .WillOnce(Return(0));
   3055   EXPECT_TRUE(wifi()->IsIdle());
   3056   EXPECT_CALL(*wake_on_wifi_, OnNoAutoConnectableServicesAfterScan(_, _, _));
   3057   ReportScanDone();
   3058 
   3059   // If we have 1 or more auto-connectable services, do not call
   3060   // WakeOnWiFi::OnNoAutoConnetableServicesAfterScan.
   3061   EXPECT_CALL(*wifi_provider(), NumAutoConnectableServices())
   3062       .WillOnce(Return(1));
   3063   EXPECT_TRUE(wifi()->IsIdle());
   3064   EXPECT_CALL(*wake_on_wifi_, OnNoAutoConnectableServicesAfterScan(_, _, _))
   3065       .Times(0);
   3066   ReportScanDone();
   3067 
   3068   // If the WiFi device is not Idle, do not call
   3069   // WakeOnWiFi::OnNoAutoConnetableServicesAfterScan.
   3070   SetCurrentService(MakeMockService(kSecurityWep));
   3071   EXPECT_FALSE(wifi()->IsIdle());
   3072   EXPECT_CALL(*wifi_provider(), NumAutoConnectableServices())
   3073       .WillOnce(Return(0));
   3074   EXPECT_CALL(*wake_on_wifi_, OnNoAutoConnectableServicesAfterScan(_, _, _))
   3075       .Times(0);
   3076   ReportScanDone();
   3077 }
   3078 
   3079 TEST_F(WiFiMainTest, ScanTimerIdle_FullScan) {
   3080   EnableFullScan();
   3081   StartWiFi();
   3082   dispatcher_.DispatchPendingEvents();
   3083   ReportScanDone();
   3084   CancelScanTimer();
   3085   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3086 
   3087   EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
   3088   dispatcher_.DispatchPendingEvents();
   3089   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
   3090   FireScanTimer();
   3091   dispatcher_.DispatchPendingEvents();
   3092   EXPECT_FALSE(GetScanTimer().IsCancelled());  // Automatically re-armed.
   3093 }
   3094 
   3095 TEST_F(WiFiMainTest, ScanTimerIdle) {
   3096   StartWiFi();
   3097   dispatcher_.DispatchPendingEvents();
   3098   ReportScanDone();
   3099   CancelScanTimer();
   3100   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3101   dispatcher_.DispatchPendingEvents();
   3102   InstallMockScanSession();
   3103   EXPECT_CALL(*scan_session_, InitiateScan());
   3104   FireScanTimer();
   3105   dispatcher_.DispatchPendingEvents();
   3106   EXPECT_FALSE(GetScanTimer().IsCancelled());  // Automatically re-armed.
   3107 }
   3108 
   3109 TEST_F(WiFiMainTest, ScanTimerScanning) {
   3110   StartWiFi();
   3111   dispatcher_.DispatchPendingEvents();
   3112   CancelScanTimer();
   3113   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3114 
   3115   // Should not call Scan, since we're already scanning.
   3116   // (Scanning is triggered by StartWiFi.)
   3117   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   3118   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   3119   FireScanTimer();
   3120   dispatcher_.DispatchPendingEvents();
   3121   EXPECT_FALSE(GetScanTimer().IsCancelled());  // Automatically re-armed.
   3122 }
   3123 
   3124 TEST_F(WiFiMainTest, ScanTimerConnecting) {
   3125   StartWiFi();
   3126   dispatcher_.DispatchPendingEvents();
   3127   MockWiFiServiceRefPtr service =
   3128       SetupConnectingService("", nullptr, nullptr);
   3129   CancelScanTimer();
   3130   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3131 
   3132   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   3133   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   3134   FireScanTimer();
   3135   dispatcher_.DispatchPendingEvents();
   3136   EXPECT_FALSE(GetScanTimer().IsCancelled());  // Automatically re-armed.
   3137 }
   3138 
   3139 TEST_F(WiFiMainTest, ScanTimerSuspending) {
   3140   EnableFullScan();
   3141   StartWiFi();
   3142   dispatcher_.DispatchPendingEvents();
   3143   ReportScanDone();
   3144   CancelScanTimer();
   3145   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3146 
   3147   EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
   3148   dispatcher_.DispatchPendingEvents();
   3149   EXPECT_CALL(*manager(), IsSuspending()).WillOnce(Return(true));
   3150   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   3151   FireScanTimer();
   3152   dispatcher_.DispatchPendingEvents();
   3153   EXPECT_TRUE(GetScanTimer().IsCancelled());  // Do not re-arm.
   3154 }
   3155 
   3156 TEST_F(WiFiMainTest, ScanTimerReconfigured) {
   3157   StartWiFi();
   3158   CancelScanTimer();
   3159   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3160 
   3161   SetScanInterval(1, nullptr);
   3162   EXPECT_FALSE(GetScanTimer().IsCancelled());
   3163 }
   3164 
   3165 TEST_F(WiFiMainTest, ScanTimerResetOnScanDone) {
   3166   StartWiFi();
   3167   CancelScanTimer();
   3168   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3169 
   3170   ReportScanDone();
   3171   EXPECT_FALSE(GetScanTimer().IsCancelled());
   3172 }
   3173 
   3174 TEST_F(WiFiMainTest, ScanTimerStopOnZeroInterval) {
   3175   StartWiFi();
   3176   EXPECT_FALSE(GetScanTimer().IsCancelled());
   3177 
   3178   SetScanInterval(0, nullptr);
   3179   EXPECT_TRUE(GetScanTimer().IsCancelled());
   3180 }
   3181 
   3182 TEST_F(WiFiMainTest, ScanOnDisconnectWithHidden_FullScan) {
   3183   EnableFullScan();
   3184   StartWiFi();
   3185   dispatcher_.DispatchPendingEvents();
   3186   SetupConnectedService("", nullptr, nullptr);
   3187   vector<uint8_t>kSSID(1, 'a');
   3188   ByteArrays ssids;
   3189   ssids.push_back(kSSID);
   3190   ExpectScanIdle();
   3191   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
   3192       .WillRepeatedly(Return(ssids));
   3193   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   3194               Scan(HasHiddenSSID_FullScan(kSSID)));
   3195   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   3196   dispatcher_.DispatchPendingEvents();
   3197 }
   3198 
   3199 TEST_F(WiFiMainTest, ScanOnDisconnectWithHidden) {
   3200   StartWiFi();
   3201   dispatcher_.DispatchPendingEvents();
   3202   ReportScanDone();
   3203   SetupConnectedService("", nullptr, nullptr);
   3204   InstallMockScanSession();
   3205   vector<uint8_t>kSSID(1, 'a');
   3206   ByteArrays ssids;
   3207   ssids.push_back(kSSID);
   3208   ExpectScanIdle();
   3209   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
   3210       .WillRepeatedly(Return(ssids));
   3211   EXPECT_CALL(*scan_session_, InitiateScan());
   3212   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   3213   dispatcher_.DispatchPendingEvents();
   3214 }
   3215 
   3216 TEST_F(WiFiMainTest, NoScanOnDisconnectWithoutHidden) {
   3217   StartWiFi();
   3218   dispatcher_.DispatchPendingEvents();
   3219   SetupConnectedService("", nullptr, nullptr);
   3220   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   3221   EXPECT_TRUE(IsScanSessionNull());
   3222   EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
   3223       .WillRepeatedly(Return(ByteArrays()));
   3224   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   3225   dispatcher_.DispatchPendingEvents();
   3226 }
   3227 
   3228 TEST_F(WiFiMainTest, LinkMonitorFailure) {
   3229   ScopedMockLog log;
   3230   auto link_monitor = new StrictMock<MockLinkMonitor>();
   3231   StartWiFi();
   3232   SetLinkMonitor(link_monitor);
   3233   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   3234   EXPECT_CALL(*link_monitor, IsGatewayFound())
   3235       .WillOnce(Return(false))
   3236       .WillRepeatedly(Return(true));
   3237 
   3238   // We never had an ARP reply during this connection, so we assume
   3239   // the problem is gateway, rather than link.
   3240   EXPECT_CALL(log, Log(logging::LOG_INFO, _,
   3241                        EndsWith("gateway was never found."))).Times(1);
   3242   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach()).Times(0);
   3243   OnLinkMonitorFailure();
   3244   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   3245 
   3246   // No supplicant, so we can't Reattach.
   3247   OnSupplicantVanish();
   3248   EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
   3249                        EndsWith("Cannot reassociate."))).Times(1);
   3250   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach()).Times(0);
   3251   OnLinkMonitorFailure();
   3252   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   3253 
   3254   // Normal case: call Reattach.
   3255   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   3256   SetCurrentService(service);
   3257   OnSupplicantAppear();
   3258   EXPECT_CALL(log, Log(logging::LOG_INFO, _,
   3259                        EndsWith("Called Reattach()."))).Times(1);
   3260   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach())
   3261       .WillOnce(Return(true));
   3262   OnLinkMonitorFailure();
   3263   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   3264 
   3265   // Service is unreliable, skip reassociate attempt.
   3266   service->set_unreliable(true);
   3267   EXPECT_CALL(log, Log(logging::LOG_INFO, _,
   3268                        EndsWith("skipping reassociate attempt."))).Times(1);
   3269   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach()).Times(0);
   3270   OnLinkMonitorFailure();
   3271   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   3272 }
   3273 
   3274 TEST_F(WiFiMainTest, UnreliableLink) {
   3275   StartWiFi();
   3276   SetupConnectedService("", nullptr, nullptr);
   3277 
   3278   EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetHT40Enable(_, false)).Times(1);
   3279   OnUnreliableLink();
   3280   Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
   3281 }
   3282 
   3283 TEST_F(WiFiMainTest, SuspectCredentialsOpen) {
   3284   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   3285   EXPECT_CALL(*service, AddSuspectedCredentialFailure()).Times(0);
   3286   EXPECT_FALSE(SuspectCredentials(service, nullptr));
   3287 }
   3288 
   3289 TEST_F(WiFiMainTest, SuspectCredentialsWPA) {
   3290   MockWiFiServiceRefPtr service = MakeMockService(kSecurityWpa);
   3291   ReportStateChanged(WPASupplicant::kInterfaceState4WayHandshake);
   3292   EXPECT_CALL(*service, AddSuspectedCredentialFailure())
   3293       .WillOnce(Return(false))
   3294       .WillOnce(Return(true));
   3295   EXPECT_FALSE(SuspectCredentials(service, nullptr));
   3296   Service::ConnectFailure failure;
   3297   EXPECT_TRUE(SuspectCredentials(service, &failure));
   3298   EXPECT_EQ(Service::kFailureBadPassphrase, failure);
   3299 }
   3300 
   3301 TEST_F(WiFiMainTest, SuspectCredentialsWEP) {
   3302   StartWiFi();
   3303   dispatcher_.DispatchPendingEvents();
   3304   MockWiFiServiceRefPtr service = MakeMockService(kSecurityWep);
   3305   ExpectConnecting();
   3306   InitiateConnect(service);
   3307   SetCurrentService(service);
   3308 
   3309   // These expectations are very much like SetupConnectedService except
   3310   // that we verify that ResetSupsectCredentialFailures() is not called
   3311   // on the service just because supplicant entered the Completed state.
   3312   EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
   3313   EXPECT_CALL(*service, ResetSuspectedCredentialFailures()).Times(0);
   3314   EXPECT_CALL(*dhcp_provider(), CreateIPv4Config(_, _, _, _))
   3315       .Times(AnyNumber());
   3316   EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(AnyNumber());
   3317   EXPECT_CALL(*manager(), device_info()).WillRepeatedly(Return(device_info()));
   3318   EXPECT_CALL(*device_info(), GetByteCounts(_, _, _))
   3319       .WillOnce(DoAll(SetArgumentPointee<2>(0LL), Return(true)));
   3320   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   3321 
   3322   Mock::VerifyAndClearExpectations(device_info());
   3323   Mock::VerifyAndClearExpectations(service.get());
   3324 
   3325   // Successful connect.
   3326   EXPECT_CALL(*GetSupplicantInterfaceProxy(), EnableHighBitrates()).Times(1);
   3327   EXPECT_CALL(*service, ResetSuspectedCredentialFailures());
   3328   ReportConnected();
   3329 
   3330   EXPECT_CALL(*device_info(), GetByteCounts(_, _, _))
   3331       .WillOnce(DoAll(SetArgumentPointee<2>(1LL), Return(true)))
   3332       .WillOnce(DoAll(SetArgumentPointee<2>(0LL), Return(true)))
   3333       .WillOnce(DoAll(SetArgumentPointee<2>(0LL), Return(true)));
   3334 
   3335   // If there was an increased byte-count while we were timing out DHCP,
   3336   // this should be considered a DHCP failure and not a credential failure.
   3337   EXPECT_CALL(*service, ResetSuspectedCredentialFailures()).Times(0);
   3338   EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureDHCP,
   3339                                               _,
   3340                                               HasSubstr("OnIPConfigFailure")));
   3341   ReportIPConfigFailure();
   3342   Mock::VerifyAndClearExpectations(service.get());
   3343 
   3344   // Connection failed during DHCP but service does not (yet) believe this is
   3345   // due to a passphrase issue.
   3346   EXPECT_CALL(*service, AddSuspectedCredentialFailure())
   3347       .WillOnce(Return(false));
   3348   EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureDHCP,
   3349                                               _,
   3350                                               HasSubstr("OnIPConfigFailure")));
   3351   ReportIPConfigFailure();
   3352   Mock::VerifyAndClearExpectations(service.get());
   3353 
   3354   // Connection failed during DHCP and service believes this is due to a
   3355   // passphrase issue.
   3356   EXPECT_CALL(*service, AddSuspectedCredentialFailure())
   3357       .WillOnce(Return(true));
   3358   EXPECT_CALL(*service,
   3359               DisconnectWithFailure(Service::kFailureBadPassphrase,
   3360                                     _,
   3361                                     HasSubstr("OnIPConfigFailure")));
   3362   ReportIPConfigFailure();
   3363 }
   3364 
   3365 TEST_F(WiFiMainTest, SuspectCredentialsEAPInProgress) {
   3366   MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
   3367   EXPECT_CALL(*eap_state_handler_, is_eap_in_progress())
   3368       .WillOnce(Return(false))
   3369       .WillOnce(Return(true))
   3370       .WillOnce(Return(false))
   3371       .WillOnce(Return(true));
   3372   EXPECT_CALL(*service, AddSuspectedCredentialFailure()).Times(0);
   3373   EXPECT_FALSE(SuspectCredentials(service, nullptr));
   3374   Mock::VerifyAndClearExpectations(service.get());
   3375 
   3376   EXPECT_CALL(*service, AddSuspectedCredentialFailure()).WillOnce(Return(true));
   3377   Service::ConnectFailure failure;
   3378   EXPECT_TRUE(SuspectCredentials(service, &failure));
   3379   EXPECT_EQ(Service::kFailureEAPAuthentication, failure);
   3380   Mock::VerifyAndClearExpectations(service.get());
   3381 
   3382   EXPECT_CALL(*service, AddSuspectedCredentialFailure()).Times(0);
   3383   EXPECT_FALSE(SuspectCredentials(service, nullptr));
   3384   Mock::VerifyAndClearExpectations(service.get());
   3385 
   3386   EXPECT_CALL(*service, AddSuspectedCredentialFailure())
   3387       .WillOnce(Return(false));
   3388   EXPECT_FALSE(SuspectCredentials(service, nullptr));
   3389 }
   3390 
   3391 TEST_F(WiFiMainTest, SuspectCredentialsYieldFailureWPA) {
   3392   MockWiFiServiceRefPtr service = MakeMockService(kSecurityWpa);
   3393   SetPendingService(service);
   3394   ReportStateChanged(WPASupplicant::kInterfaceState4WayHandshake);
   3395 
   3396   ExpectScanIdle();
   3397   EXPECT_CALL(*service, AddSuspectedCredentialFailure()).WillOnce(Return(true));
   3398   EXPECT_CALL(*service, SetFailure(Service::kFailureBadPassphrase));
   3399   EXPECT_CALL(*service, SetState(Service::kStateIdle));
   3400   ScopedMockLog log;
   3401   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   3402   EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith(kErrorBadPassphrase)));
   3403   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   3404 }
   3405 
   3406 TEST_F(WiFiMainTest, SuspectCredentialsYieldFailureEAP) {
   3407   MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
   3408   SetCurrentService(service);
   3409 
   3410   ScopedMockLog log;
   3411   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   3412   EXPECT_CALL(*service, SetState(Service::kStateIdle));
   3413   // Ensure that we retrieve is_eap_in_progress() before resetting the
   3414   // EAP handler's state.
   3415   InSequence seq;
   3416   EXPECT_CALL(*eap_state_handler_, is_eap_in_progress())
   3417       .WillOnce(Return(true));
   3418   EXPECT_CALL(*service, AddSuspectedCredentialFailure()).WillOnce(Return(true));
   3419   EXPECT_CALL(*service, SetFailure(Service::kFailureEAPAuthentication));
   3420   EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
   3421                        EndsWith(kErrorEapAuthenticationFailed)));
   3422   EXPECT_CALL(*eap_state_handler_, Reset());
   3423   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   3424 }
   3425 
   3426 TEST_F(WiFiMainTest, ReportConnectedToServiceAfterWake_CallsWakeOnWiFi) {
   3427   EXPECT_CALL(*wake_on_wifi_,
   3428               ReportConnectedToServiceAfterWake(IsConnectedToCurrentService()));
   3429   ReportConnectedToServiceAfterWake();
   3430 }
   3431 
   3432 // Scanning tests will use a mock of the event dispatcher instead of a real
   3433 // one.
   3434 class WiFiTimerTest : public WiFiObjectTest {
   3435  public:
   3436   WiFiTimerTest() : WiFiObjectTest(&mock_dispatcher_) {}
   3437 
   3438  protected:
   3439   void ExpectInitialScanSequence();
   3440 
   3441   StrictMock<MockEventDispatcher> mock_dispatcher_;
   3442 };
   3443 
   3444 void WiFiTimerTest::ExpectInitialScanSequence() {
   3445   // Choose a number of iterations some multiple higher than the fast scan
   3446   // count.
   3447   const int kScanTimes = WiFi::kNumFastScanAttempts * 4;
   3448 
   3449   // Each time we call FireScanTimer() below, WiFi will post a task to actually
   3450   // run Scan() on the wpa_supplicant proxy.
   3451   EXPECT_CALL(mock_dispatcher_, PostTask(_))
   3452       .Times(kScanTimes);
   3453   {
   3454     InSequence seq;
   3455     // The scans immediately after the initial scan should happen at the short
   3456     // interval.  If we add the initial scan (not invoked in this function) to
   3457     // the ones in the expectation below, we get WiFi::kNumFastScanAttempts at
   3458     // the fast scan interval.
   3459     EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3460         _, WiFi::kFastScanIntervalSeconds * 1000))
   3461         .Times(WiFi::kNumFastScanAttempts - 1);
   3462 
   3463     // After this, the WiFi device should use the normal scan interval.
   3464     EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3465         _, GetScanInterval() * 1000))
   3466         .Times(kScanTimes - WiFi::kNumFastScanAttempts + 1);
   3467 
   3468     for (int i = 0; i < kScanTimes; i++) {
   3469       FireScanTimer();
   3470     }
   3471   }
   3472 }
   3473 
   3474 TEST_F(WiFiTimerTest, FastRescan) {
   3475   // This is to cover calls to PostDelayedTask by WakeOnWiFi::StartMetricsTimer.
   3476   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(AnyNumber());
   3477   // This PostTask is a result of the call to Scan(nullptr), and is meant to
   3478   // post a task to call Scan() on the wpa_supplicant proxy immediately.
   3479   EXPECT_CALL(mock_dispatcher_, PostTask(_));
   3480   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3481       _, WiFi::kFastScanIntervalSeconds * 1000));
   3482   StartWiFi();
   3483 
   3484   ExpectInitialScanSequence();
   3485 
   3486   // If we end up disconnecting, the sequence should repeat.
   3487   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3488       _, WiFi::kFastScanIntervalSeconds * 1000));
   3489   RestartFastScanAttempts();
   3490 
   3491   ExpectInitialScanSequence();
   3492 }
   3493 
   3494 TEST_F(WiFiTimerTest, ReconnectTimer) {
   3495   EXPECT_CALL(mock_dispatcher_, PostTask(_)).Times(AnyNumber());
   3496   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(AnyNumber());
   3497   StartWiFi();
   3498   SetupConnectedService("", nullptr, nullptr);
   3499   Mock::VerifyAndClearExpectations(&mock_dispatcher_);
   3500 
   3501   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3502       _, GetReconnectTimeoutSeconds() * 1000)).Times(1);
   3503   StartReconnectTimer();
   3504   Mock::VerifyAndClearExpectations(&mock_dispatcher_);
   3505   StopReconnectTimer();
   3506 
   3507   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3508       _, GetReconnectTimeoutSeconds() * 1000)).Times(1);
   3509   StartReconnectTimer();
   3510   Mock::VerifyAndClearExpectations(&mock_dispatcher_);
   3511   GetReconnectTimeoutCallback().callback().Run();
   3512 
   3513   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3514       _, GetReconnectTimeoutSeconds() * 1000)).Times(1);
   3515   StartReconnectTimer();
   3516   Mock::VerifyAndClearExpectations(&mock_dispatcher_);
   3517 
   3518   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3519       _, GetReconnectTimeoutSeconds() * 1000)).Times(0);
   3520   StartReconnectTimer();
   3521 }
   3522 
   3523 TEST_F(WiFiTimerTest, RequestStationInfo) {
   3524   EXPECT_CALL(mock_dispatcher_, PostTask(_)).Times(AnyNumber());
   3525   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(AnyNumber());
   3526 
   3527   // Setup a connected service here while we have the expectations above set.
   3528   StartWiFi();
   3529   MockWiFiServiceRefPtr service =
   3530       SetupConnectedService("", nullptr, nullptr);
   3531   string connected_bss = GetSupplicantBSS();
   3532   Mock::VerifyAndClearExpectations(&mock_dispatcher_);
   3533 
   3534   EXPECT_CALL(netlink_manager_, SendNl80211Message(_, _, _, _)).Times(0);
   3535   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(0);
   3536   NiceScopedMockLog log;
   3537 
   3538   // There is no current_service_.
   3539   EXPECT_CALL(log, Log(_, _, HasSubstr("we are not connected")));
   3540   SetCurrentService(nullptr);
   3541   RequestStationInfo();
   3542 
   3543   // current_service_ is not connected.
   3544   EXPECT_CALL(*service, IsConnected()).WillOnce(Return(false));
   3545   SetCurrentService(service);
   3546   EXPECT_CALL(log, Log(_, _, HasSubstr("we are not connected")));
   3547   RequestStationInfo();
   3548 
   3549   // Endpoint does not exist in endpoint_by_rpcid_.
   3550   EXPECT_CALL(*service, IsConnected()).WillRepeatedly(Return(true));
   3551   SetSupplicantBSS("/some/path/that/does/not/exist/in/endpoint_by_rpcid");
   3552   EXPECT_CALL(log, Log(_, _, HasSubstr(
   3553       "Can't get endpoint for current supplicant BSS")));
   3554   RequestStationInfo();
   3555   Mock::VerifyAndClearExpectations(&netlink_manager_);
   3556   Mock::VerifyAndClearExpectations(&mock_dispatcher_);
   3557 
   3558   // We successfully trigger a request to get the station and start a timer
   3559   // for the next call.
   3560   EXPECT_CALL(netlink_manager_, SendNl80211Message(
   3561       IsNl80211Command(kNl80211FamilyId, NL80211_CMD_GET_STATION), _, _, _));
   3562   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
   3563       _, WiFi::kRequestStationInfoPeriodSeconds * 1000));
   3564   SetSupplicantBSS(connected_bss);
   3565   RequestStationInfo();
   3566 
   3567   // Now test that a properly formatted New Station message updates strength.
   3568   NewStationMessage new_station;
   3569   new_station.attributes()->CreateRawAttribute(NL80211_ATTR_MAC, "BSSID");
   3570 
   3571   // Confirm that up until now no link statistics exist.
   3572   KeyValueStore link_statistics = GetLinkStatistics();
   3573   EXPECT_TRUE(link_statistics.IsEmpty());
   3574 
   3575   // Use a reference to the endpoint instance in the WiFi device instead of
   3576   // the copy returned by SetupConnectedService().
   3577   WiFiEndpointRefPtr endpoint = GetEndpointMap().begin()->second;
   3578   new_station.attributes()->SetRawAttributeValue(
   3579       NL80211_ATTR_MAC, ByteString::CreateFromHexString(endpoint->bssid_hex()));
   3580   new_station.attributes()->CreateNestedAttribute(
   3581       NL80211_ATTR_STA_INFO, "Station Info");
   3582   AttributeListRefPtr station_info;
   3583   new_station.attributes()->GetNestedAttributeList(
   3584       NL80211_ATTR_STA_INFO, &station_info);
   3585   station_info->CreateU8Attribute(NL80211_STA_INFO_SIGNAL, "Signal");
   3586   const int kSignalValue = -20;
   3587   station_info->SetU8AttributeValue(NL80211_STA_INFO_SIGNAL, kSignalValue);
   3588   station_info->CreateU8Attribute(NL80211_STA_INFO_SIGNAL_AVG, "SignalAverage");
   3589   const int kSignalAvgValue = -40;
   3590   station_info->SetU8AttributeValue(NL80211_STA_INFO_SIGNAL_AVG,
   3591                                     kSignalAvgValue);
   3592   station_info->CreateU32Attribute(NL80211_STA_INFO_INACTIVE_TIME,
   3593                                    "InactiveTime");
   3594   const int32_t kInactiveTime = 100;
   3595   station_info->SetU32AttributeValue(NL80211_STA_INFO_INACTIVE_TIME,
   3596                                      kInactiveTime);
   3597   station_info->CreateU32Attribute(NL80211_STA_INFO_RX_PACKETS,
   3598                                    "ReceivedSuccesses");
   3599   const int32_t kReceiveSuccesses = 200;
   3600   station_info->SetU32AttributeValue(NL80211_STA_INFO_RX_PACKETS,
   3601                                      kReceiveSuccesses);
   3602   station_info->CreateU32Attribute(NL80211_STA_INFO_TX_FAILED,
   3603                                    "TransmitFailed");
   3604   const int32_t kTransmitFailed = 300;
   3605   station_info->SetU32AttributeValue(NL80211_STA_INFO_TX_FAILED,
   3606                                      kTransmitFailed);
   3607   station_info->CreateU32Attribute(NL80211_STA_INFO_TX_PACKETS,
   3608                                    "TransmitSuccesses");
   3609   const int32_t kTransmitSuccesses = 400;
   3610   station_info->SetU32AttributeValue(NL80211_STA_INFO_TX_PACKETS,
   3611                                      kTransmitSuccesses);
   3612   station_info->CreateU32Attribute(NL80211_STA_INFO_TX_RETRIES,
   3613                                    "TransmitRetries");
   3614   const int32_t kTransmitRetries = 500;
   3615   station_info->SetU32AttributeValue(NL80211_STA_INFO_TX_RETRIES,
   3616                                      kTransmitRetries);
   3617   station_info->CreateNestedAttribute(NL80211_STA_INFO_TX_BITRATE,
   3618                                       "Bitrate Info");
   3619 
   3620   // Embed transmit bitrate info within the station info element.
   3621   AttributeListRefPtr bitrate_info;
   3622   station_info->GetNestedAttributeList(
   3623       NL80211_STA_INFO_TX_BITRATE, &bitrate_info);
   3624   bitrate_info->CreateU16Attribute(NL80211_RATE_INFO_BITRATE, "Bitrate");
   3625   const int16_t kBitrate = 6005;
   3626   bitrate_info->SetU16AttributeValue(NL80211_RATE_INFO_BITRATE, kBitrate);
   3627   bitrate_info->CreateU8Attribute(NL80211_RATE_INFO_MCS, "MCS");
   3628   const int16_t kMCS = 7;
   3629   bitrate_info->SetU8AttributeValue(NL80211_RATE_INFO_MCS, kMCS);
   3630   bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_40_MHZ_WIDTH, "HT40");
   3631   bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_40_MHZ_WIDTH, true);
   3632   bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_SHORT_GI, "SGI");
   3633   bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_SHORT_GI, false);
   3634   station_info->SetNestedAttributeHasAValue(NL80211_STA_INFO_TX_BITRATE);
   3635 
   3636   new_station.attributes()->SetNestedAttributeHasAValue(NL80211_ATTR_STA_INFO);
   3637 
   3638   EXPECT_NE(kSignalValue, endpoint->signal_strength());
   3639   EXPECT_CALL(*wifi_provider(), OnEndpointUpdated(EndpointMatch(endpoint)));
   3640   EXPECT_CALL(*metrics(), NotifyWifiTxBitrate(kBitrate/10));
   3641   AttributeListConstRefPtr station_info_prime;
   3642   ReportReceivedStationInfo(new_station);
   3643   EXPECT_EQ(kSignalValue, endpoint->signal_strength());
   3644 
   3645   link_statistics = GetLinkStatistics();
   3646   ASSERT_FALSE(link_statistics.IsEmpty());
   3647   ASSERT_TRUE(link_statistics.ContainsInt(kLastReceiveSignalDbmProperty));
   3648   EXPECT_EQ(kSignalValue,
   3649             link_statistics.GetInt(kLastReceiveSignalDbmProperty));
   3650   ASSERT_TRUE(link_statistics.ContainsInt(kAverageReceiveSignalDbmProperty));
   3651   EXPECT_EQ(kSignalAvgValue,
   3652             link_statistics.GetInt(kAverageReceiveSignalDbmProperty));
   3653   ASSERT_TRUE(link_statistics.ContainsUint(kInactiveTimeMillisecondsProperty));
   3654   EXPECT_EQ(kInactiveTime,
   3655             link_statistics.GetUint(kInactiveTimeMillisecondsProperty));
   3656   ASSERT_TRUE(link_statistics.ContainsUint(kPacketReceiveSuccessesProperty));
   3657   EXPECT_EQ(kReceiveSuccesses,
   3658             link_statistics.GetUint(kPacketReceiveSuccessesProperty));
   3659   ASSERT_TRUE(link_statistics.ContainsUint(kPacketTransmitFailuresProperty));
   3660   EXPECT_EQ(kTransmitFailed,
   3661             link_statistics.GetUint(kPacketTransmitFailuresProperty));
   3662   ASSERT_TRUE(link_statistics.ContainsUint(kPacketTransmitSuccessesProperty));
   3663   EXPECT_EQ(kTransmitSuccesses,
   3664             link_statistics.GetUint(kPacketTransmitSuccessesProperty));
   3665   ASSERT_TRUE(link_statistics.ContainsUint(kTransmitRetriesProperty));
   3666   EXPECT_EQ(kTransmitRetries,
   3667             link_statistics.GetUint(kTransmitRetriesProperty));
   3668   EXPECT_EQ(StringPrintf("%d.%d MBit/s MCS %d 40MHz",
   3669                          kBitrate / 10, kBitrate % 10, kMCS),
   3670             link_statistics.LookupString(kTransmitBitrateProperty, ""));
   3671 
   3672   // New station info with VHT rate parameters.
   3673   NewStationMessage new_vht_station;
   3674   new_vht_station.attributes()->CreateRawAttribute(NL80211_ATTR_MAC, "BSSID");
   3675 
   3676   new_vht_station.attributes()->SetRawAttributeValue(
   3677       NL80211_ATTR_MAC, ByteString::CreateFromHexString(endpoint->bssid_hex()));
   3678   new_vht_station.attributes()->CreateNestedAttribute(
   3679       NL80211_ATTR_STA_INFO, "Station Info");
   3680   new_vht_station.attributes()->GetNestedAttributeList(
   3681       NL80211_ATTR_STA_INFO, &station_info);
   3682   station_info->CreateU8Attribute(NL80211_STA_INFO_SIGNAL, "Signal");
   3683   station_info->SetU8AttributeValue(NL80211_STA_INFO_SIGNAL, kSignalValue);
   3684   station_info->CreateNestedAttribute(NL80211_STA_INFO_TX_BITRATE,
   3685                                       "Bitrate Info");
   3686 
   3687   // Embed transmit VHT bitrate info within the station info element.
   3688   station_info->GetNestedAttributeList(
   3689       NL80211_STA_INFO_TX_BITRATE, &bitrate_info);
   3690   bitrate_info->CreateU32Attribute(NL80211_RATE_INFO_BITRATE32, "Bitrate32");
   3691   const int32_t kVhtBitrate = 70000;
   3692   bitrate_info->SetU32AttributeValue(NL80211_RATE_INFO_BITRATE32, kVhtBitrate);
   3693   bitrate_info->CreateU8Attribute(NL80211_RATE_INFO_VHT_MCS, "VHT-MCS");
   3694   const int8_t kVhtMCS = 7;
   3695   bitrate_info->SetU8AttributeValue(NL80211_RATE_INFO_VHT_MCS, kVhtMCS);
   3696   bitrate_info->CreateU8Attribute(NL80211_RATE_INFO_VHT_NSS, "VHT-NSS");
   3697   const int8_t kVhtNSS = 1;
   3698   bitrate_info->SetU8AttributeValue(NL80211_RATE_INFO_VHT_NSS, kVhtNSS);
   3699   bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_80_MHZ_WIDTH, "VHT80");
   3700   bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_80_MHZ_WIDTH, true);
   3701   bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_SHORT_GI, "SGI");
   3702   bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_SHORT_GI, false);
   3703   station_info->SetNestedAttributeHasAValue(NL80211_STA_INFO_TX_BITRATE);
   3704 
   3705   new_vht_station.attributes()->SetNestedAttributeHasAValue(
   3706       NL80211_ATTR_STA_INFO);
   3707 
   3708   EXPECT_CALL(*metrics(), NotifyWifiTxBitrate(kVhtBitrate/10));
   3709 
   3710   ReportReceivedStationInfo(new_vht_station);
   3711 
   3712   link_statistics = GetLinkStatistics();
   3713   EXPECT_EQ(StringPrintf("%d.%d MBit/s VHT-MCS %d 80MHz VHT-NSS %d",
   3714                          kVhtBitrate / 10, kVhtBitrate % 10, kVhtMCS, kVhtNSS),
   3715             link_statistics.LookupString(kTransmitBitrateProperty, ""));
   3716 }
   3717 
   3718 TEST_F(WiFiTimerTest, ResumeDispatchesConnectivityReportTask) {
   3719   EXPECT_CALL(mock_dispatcher_, PostTask(_)).Times(AnyNumber());
   3720   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(AnyNumber());
   3721   StartWiFi();
   3722   SetupConnectedService("", nullptr, nullptr);
   3723   EXPECT_CALL(
   3724       mock_dispatcher_,
   3725       PostDelayedTask(_, WiFi::kPostWakeConnectivityReportDelayMilliseconds));
   3726   OnAfterResume();
   3727 }
   3728 
   3729 TEST_F(WiFiTimerTest, StartScanTimer_ReturnsImmediately) {
   3730   Error e;
   3731   // Return immediately if scan interval is 0.
   3732   SetScanInterval(0, &e);
   3733   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(0);
   3734   StartScanTimer();
   3735 }
   3736 
   3737 TEST_F(WiFiTimerTest, StartScanTimer_HaveFastScansRemaining) {
   3738   Error e;
   3739   const int scan_interval = 10;
   3740   SetScanInterval(scan_interval, &e);
   3741   SetFastScansRemaining(1);
   3742   EXPECT_CALL(mock_dispatcher_,
   3743               PostDelayedTask(_, WiFi::kFastScanIntervalSeconds * 1000));
   3744   StartScanTimer();
   3745 }
   3746 
   3747 TEST_F(WiFiTimerTest, StartScanTimer_NoFastScansRemaining) {
   3748   Error e;
   3749   const int scan_interval = 10;
   3750   SetScanInterval(scan_interval, &e);
   3751   SetFastScansRemaining(0);
   3752   EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, scan_interval * 1000));
   3753   StartScanTimer();
   3754 }
   3755 
   3756 TEST_F(WiFiMainTest, EAPCertification) {
   3757   MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
   3758   EXPECT_CALL(*service, AddEAPCertification(_, _)).Times(0);
   3759 
   3760   ScopedMockLog log;
   3761   EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith("no current service.")));
   3762   KeyValueStore args;
   3763   ReportCertification(args);
   3764   Mock::VerifyAndClearExpectations(&log);
   3765 
   3766   SetCurrentService(service);
   3767   EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith("no depth parameter.")));
   3768   ReportCertification(args);
   3769   Mock::VerifyAndClearExpectations(&log);
   3770 
   3771   const uint32_t kDepth = 123;
   3772   args.SetUint(WPASupplicant::kInterfacePropertyDepth, kDepth);
   3773 
   3774   EXPECT_CALL(log,
   3775               Log(logging::LOG_ERROR, _, EndsWith("no subject parameter.")));
   3776   ReportCertification(args);
   3777   Mock::VerifyAndClearExpectations(&log);
   3778 
   3779   const string kSubject("subject");
   3780   args.SetString(WPASupplicant::kInterfacePropertySubject, kSubject);
   3781   EXPECT_CALL(*service, AddEAPCertification(kSubject, kDepth)).Times(1);
   3782   ReportCertification(args);
   3783 }
   3784 
   3785 TEST_F(WiFiTimerTest, ScanDoneDispatchesTasks) {
   3786   // Dispatch WiFi::ScanFailedTask if scan failed.
   3787   EXPECT_TRUE(ScanFailedCallbackIsCancelled());
   3788   EXPECT_CALL(mock_dispatcher_,
   3789               PostDelayedTask(_, WiFi::kPostScanFailedDelayMilliseconds));
   3790   ScanDone(false);
   3791   EXPECT_FALSE(ScanFailedCallbackIsCancelled());
   3792 
   3793   // Dispatch WiFi::ScanDoneTask if scan succeeded, and cancel the scan failed
   3794   // callback if has been dispatched.
   3795   EXPECT_CALL(mock_dispatcher_, PostTask(_));
   3796   ScanDone(true);
   3797   EXPECT_TRUE(ScanFailedCallbackIsCancelled());
   3798 }
   3799 
   3800 TEST_F(WiFiMainTest, EAPEvent) {
   3801   StartWiFi();
   3802   ScopedMockLog log;
   3803   EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith("no current service.")));
   3804   EXPECT_CALL(*eap_state_handler_, ParseStatus(_, _, _)).Times(0);
   3805   const string kEAPStatus("eap-status");
   3806   const string kEAPParameter("eap-parameter");
   3807   ReportEAPEvent(kEAPStatus, kEAPParameter);
   3808   Mock::VerifyAndClearExpectations(&log);
   3809   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   3810 
   3811   MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
   3812   EXPECT_CALL(*service, SetFailure(_)).Times(0);
   3813   EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _));
   3814   SetCurrentService(service);
   3815   ReportEAPEvent(kEAPStatus, kEAPParameter);
   3816   Mock::VerifyAndClearExpectations(service.get());
   3817   Mock::VerifyAndClearExpectations(eap_state_handler_);
   3818 
   3819   EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _))
   3820       .WillOnce(DoAll(SetArgumentPointee<2>(Service::kFailureOutOfRange),
   3821                 Return(false)));
   3822   EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureOutOfRange,
   3823                                               _,
   3824                                               HasSubstr("EAPEventTask")));
   3825   ReportEAPEvent(kEAPStatus, kEAPParameter);
   3826 
   3827   MockEapCredentials* eap = new MockEapCredentials();
   3828   service->eap_.reset(eap);  // Passes ownership.
   3829   const char kNetworkRpcId[] = "/service/network/rpcid";
   3830   SetServiceNetworkRpcId(service, kNetworkRpcId);
   3831   EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _))
   3832       .WillOnce(DoAll(SetArgumentPointee<2>(Service::kFailurePinMissing),
   3833                 Return(false)));
   3834   // We need a real string object since it will be returned by reference below.
   3835   const string kEmptyPin;
   3836   EXPECT_CALL(*eap, pin()).WillOnce(ReturnRef(kEmptyPin));
   3837   EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailurePinMissing,
   3838                                               _,
   3839                                               HasSubstr("EAPEventTask")));
   3840   ReportEAPEvent(kEAPStatus, kEAPParameter);
   3841 
   3842   EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _))
   3843       .WillOnce(DoAll(SetArgumentPointee<2>(Service::kFailurePinMissing),
   3844                 Return(false)));
   3845   // We need a real string object since it will be returned by reference below.
   3846   const string kPin("000000");
   3847   EXPECT_CALL(*eap, pin()).WillOnce(ReturnRef(kPin));
   3848   EXPECT_CALL(*service, DisconnectWithFailure(_, _, _)).Times(0);
   3849   EXPECT_CALL(*GetSupplicantInterfaceProxy(),
   3850               NetworkReply(StrEq(kNetworkRpcId),
   3851                            StrEq(WPASupplicant::kEAPRequestedParameterPIN),
   3852                            Ref(kPin)));
   3853   ReportEAPEvent(kEAPStatus, kEAPParameter);
   3854 }
   3855 
   3856 TEST_F(WiFiMainTest, PendingScanDoesNotCrashAfterStop) {
   3857   // Scan is one task that should be skipped after Stop. Others are
   3858   // skipped by the same mechanism (invalidating weak pointers), so we
   3859   // don't test them individually.
   3860   //
   3861   // Note that we can't test behavior by setting expectations on the
   3862   // supplicant_interface_proxy_, since that is destroyed when we StopWiFi().
   3863   StartWiFi();
   3864   StopWiFi();
   3865   dispatcher_.DispatchPendingEvents();
   3866 }
   3867 
   3868 struct BSS {
   3869   string bsspath;
   3870   string ssid;
   3871   string bssid;
   3872   int16_t signal_strength;
   3873   uint16_t frequency;
   3874   const char* mode;
   3875 };
   3876 
   3877 TEST_F(WiFiMainTest, GetGeolocationObjects) {
   3878   BSS bsses[] = {
   3879     {"bssid1", "ssid1", "00:00:00:00:00:00", 5, Metrics::kWiFiFrequency2412,
   3880      kNetworkModeInfrastructure},
   3881     {"bssid2", "ssid2", "01:00:00:00:00:00", 30, Metrics::kWiFiFrequency5170,
   3882      kNetworkModeInfrastructure},
   3883     // Same SSID but different BSSID is an additional geolocation object.
   3884     {"bssid3", "ssid1", "02:00:00:00:00:00", 100, 0,
   3885      kNetworkModeInfrastructure}
   3886   };
   3887   StartWiFi();
   3888   vector<GeolocationInfo> objects;
   3889   EXPECT_EQ(objects.size(), 0);
   3890 
   3891   for (size_t i = 0; i < arraysize(bsses); ++i) {
   3892     ReportBSS(bsses[i].bsspath, bsses[i].ssid, bsses[i].bssid,
   3893               bsses[i].signal_strength, bsses[i].frequency, bsses[i].mode);
   3894     objects = wifi()->GetGeolocationObjects();
   3895     EXPECT_EQ(objects.size(), i + 1);
   3896 
   3897     GeolocationInfo expected_info;
   3898     expected_info.AddField(kGeoMacAddressProperty, bsses[i].bssid);
   3899     expected_info.AddField(kGeoSignalStrengthProperty,
   3900                            StringPrintf("%d", bsses[i].signal_strength));
   3901     expected_info.AddField(kGeoChannelProperty, StringPrintf(
   3902         "%d", Metrics::WiFiFrequencyToChannel(bsses[i].frequency)));
   3903     EXPECT_TRUE(objects[i].Equals(expected_info));
   3904   }
   3905 }
   3906 
   3907 TEST_F(WiFiMainTest, SetSupplicantDebugLevel) {
   3908   MockSupplicantProcessProxy* process_proxy = supplicant_process_proxy_;
   3909 
   3910   // With WiFi not yet started, nothing interesting (including a crash) should
   3911   // happen.
   3912   EXPECT_CALL(*process_proxy, GetDebugLevel(_)).Times(0);
   3913   EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
   3914   ReportWiFiDebugScopeChanged(true);
   3915 
   3916   // This unit test turns on WiFi debugging, so when we start WiFi, we should
   3917   // check but not set the debug level if we return the "debug" level.
   3918   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   3919       .WillOnce(
   3920           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelDebug)),
   3921                 Return(true)));
   3922   EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
   3923   StartWiFi();
   3924   Mock::VerifyAndClearExpectations(process_proxy);
   3925 
   3926   // If WiFi debugging is toggled and wpa_supplicant reports debugging
   3927   // is set to some unmanaged level, WiFi should leave it alone.
   3928   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   3929       .WillOnce(
   3930           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelError)),
   3931                 Return(true)))
   3932       .WillOnce(
   3933           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelError)),
   3934                 Return(true)))
   3935       .WillOnce(
   3936           DoAll(SetArgumentPointee<0>(
   3937                     string(WPASupplicant::kDebugLevelExcessive)),
   3938                 Return(true)))
   3939       .WillOnce(
   3940           DoAll(SetArgumentPointee<0>(
   3941                     string(WPASupplicant::kDebugLevelExcessive)),
   3942                 Return(true)))
   3943       .WillOnce(
   3944           DoAll(SetArgumentPointee<0>(
   3945                     string(WPASupplicant::kDebugLevelMsgDump)),
   3946                 Return(true)))
   3947       .WillOnce(
   3948           DoAll(SetArgumentPointee<0>(
   3949                     string(WPASupplicant::kDebugLevelMsgDump)),
   3950                 Return(true)))
   3951       .WillOnce(
   3952           DoAll(SetArgumentPointee<0>(
   3953                     string(WPASupplicant::kDebugLevelWarning)),
   3954                 Return(true)))
   3955       .WillOnce(
   3956           DoAll(SetArgumentPointee<0>(
   3957                     string(WPASupplicant::kDebugLevelWarning)),
   3958                 Return(true)));
   3959   EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
   3960   ReportWiFiDebugScopeChanged(true);
   3961   ReportWiFiDebugScopeChanged(false);
   3962   ReportWiFiDebugScopeChanged(true);
   3963   ReportWiFiDebugScopeChanged(false);
   3964   ReportWiFiDebugScopeChanged(true);
   3965   ReportWiFiDebugScopeChanged(false);
   3966   ReportWiFiDebugScopeChanged(true);
   3967   ReportWiFiDebugScopeChanged(false);
   3968   Mock::VerifyAndClearExpectations(process_proxy);
   3969 
   3970   // If WiFi debugging is turned off and wpa_supplicant reports debugging
   3971   // is turned on, WiFi should turn supplicant debugging off.
   3972   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   3973       .WillOnce(
   3974           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelDebug)),
   3975                 Return(true)));
   3976   EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelInfo))
   3977       .Times(1);
   3978   ReportWiFiDebugScopeChanged(false);
   3979   Mock::VerifyAndClearExpectations(process_proxy);
   3980 
   3981   // If WiFi debugging is turned on and wpa_supplicant reports debugging
   3982   // is turned off, WiFi should turn supplicant debugging on.
   3983   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   3984       .WillOnce(
   3985           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelInfo)),
   3986                 Return(true)));
   3987   EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelDebug))
   3988       .Times(1);
   3989   ReportWiFiDebugScopeChanged(true);
   3990   Mock::VerifyAndClearExpectations(process_proxy);
   3991 
   3992   // If WiFi debugging is already in the correct state, it should not be
   3993   // changed.
   3994   EXPECT_CALL(*process_proxy, GetDebugLevel(_))
   3995       .WillOnce(
   3996           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelDebug)),
   3997                 Return(true)))
   3998       .WillOnce(
   3999           DoAll(SetArgumentPointee<0>(string(WPASupplicant::kDebugLevelInfo)),
   4000                 Return(true)));
   4001   EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
   4002   ReportWiFiDebugScopeChanged(true);
   4003   ReportWiFiDebugScopeChanged(false);
   4004 
   4005   // After WiFi is stopped, we shouldn't be calling the proxy.
   4006   EXPECT_CALL(*process_proxy, GetDebugLevel(_)).Times(0);
   4007   EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
   4008   StopWiFi();
   4009   ReportWiFiDebugScopeChanged(true);
   4010   ReportWiFiDebugScopeChanged(false);
   4011 }
   4012 
   4013 TEST_F(WiFiMainTest, LogSSID) {
   4014   EXPECT_EQ("[SSID=]", WiFi::LogSSID(""));
   4015   EXPECT_EQ("[SSID=foo\\x5b\\x09\\x5dbar]", WiFi::LogSSID("foo[\t]bar"));
   4016 }
   4017 
   4018 // Custom property setters should return false, and make no changes, if
   4019 // the new value is the same as the old value.
   4020 TEST_F(WiFiMainTest, CustomSetterNoopChange) {
   4021   // SetBgscanShortInterval
   4022   {
   4023     Error error;
   4024     static const uint16_t kKnownScanInterval = 4;
   4025     // Set to known value.
   4026     EXPECT_TRUE(SetBgscanShortInterval(kKnownScanInterval, &error));
   4027     EXPECT_TRUE(error.IsSuccess());
   4028     // Set to same value.
   4029     EXPECT_FALSE(SetBgscanShortInterval(kKnownScanInterval, &error));
   4030     EXPECT_TRUE(error.IsSuccess());
   4031   }
   4032 
   4033   // SetBgscanSignalThreshold
   4034   {
   4035     Error error;
   4036     static const int32_t kKnownSignalThreshold = 4;
   4037     // Set to known value.
   4038     EXPECT_TRUE(SetBgscanSignalThreshold(kKnownSignalThreshold, &error));
   4039     EXPECT_TRUE(error.IsSuccess());
   4040     // Set to same value.
   4041     EXPECT_FALSE(SetBgscanSignalThreshold(kKnownSignalThreshold, &error));
   4042     EXPECT_TRUE(error.IsSuccess());
   4043   }
   4044 
   4045   // SetScanInterval
   4046   {
   4047     Error error;
   4048     EXPECT_FALSE(SetScanInterval(GetScanInterval(), &error));
   4049     EXPECT_TRUE(error.IsSuccess());
   4050   }
   4051 }
   4052 
   4053 // The following tests check the scan_state_ / scan_method_ state machine.
   4054 
   4055 TEST_F(WiFiMainTest, FullScanFindsNothing) {
   4056   StartScan(WiFi::kScanMethodFull);
   4057   ReportScanDone();
   4058   ExpectScanStop();
   4059   ExpectFoundNothing();
   4060   NiceScopedMockLog log;
   4061   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4062   ScopeLogger::GetInstance()->set_verbose_level(10);
   4063   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4064   EXPECT_CALL(log, Log(_, _, HasSubstr("FULL_NOCONNECTION ->")));
   4065   EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
   4066   dispatcher_.DispatchPendingEvents();  // Launch UpdateScanStateAfterScanDone
   4067   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4068 
   4069   ScopeLogger::GetInstance()->set_verbose_level(0);
   4070   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4071 }
   4072 
   4073 TEST_F(WiFiMainTest, FullScanConnectingToConnected) {
   4074   StartScan(WiFi::kScanMethodFull);
   4075   WiFiEndpointRefPtr endpoint;
   4076   string bss_path;
   4077   MockWiFiServiceRefPtr service = AttemptConnection(WiFi::kScanMethodFull,
   4078                                                     &endpoint,
   4079                                                     &bss_path);
   4080 
   4081   // Complete the connection.
   4082   ExpectConnected();
   4083   EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
   4084   NiceScopedMockLog log;
   4085   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4086   ScopeLogger::GetInstance()->set_verbose_level(10);
   4087   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4088   EXPECT_CALL(log, Log(_, _, HasSubstr("-> FULL_CONNECTED")));
   4089   ReportCurrentBSSChanged(bss_path);
   4090   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4091 
   4092   ScopeLogger::GetInstance()->set_verbose_level(0);
   4093   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4094 }
   4095 
   4096 TEST_F(WiFiMainTest, ProgressiveScanConnectingToConnected) {
   4097   StartScan(WiFi::kScanMethodProgressive);
   4098   WiFiEndpointRefPtr endpoint;
   4099   string bss_path;
   4100   MockWiFiServiceRefPtr service = AttemptConnection(
   4101       WiFi::kScanMethodProgressive, &endpoint, &bss_path);
   4102 
   4103   // Complete the connection.
   4104   ExpectConnected();
   4105   EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
   4106   NiceScopedMockLog log;
   4107   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4108   ScopeLogger::GetInstance()->set_verbose_level(10);
   4109   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4110   EXPECT_CALL(log, Log(_, _, HasSubstr("-> PROGRESSIVE_CONNECTED")));
   4111   ReportCurrentBSSChanged(bss_path);
   4112   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4113 
   4114   ScopeLogger::GetInstance()->set_verbose_level(0);
   4115   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4116 }
   4117 
   4118 TEST_F(WiFiMainTest, ProgressiveScanConnectingToNotFound) {
   4119   StartScan(WiFi::kScanMethodProgressive);
   4120   WiFiEndpointRefPtr endpoint;
   4121   MockWiFiServiceRefPtr service = AttemptConnection(
   4122       WiFi::kScanMethodProgressive, &endpoint, nullptr);
   4123 
   4124   // Simulate connection timeout.
   4125   ExpectFoundNothing();
   4126   EXPECT_CALL(*service,
   4127               NotifyCurrentEndpoint(EndpointMatch(endpoint))).Times(0);
   4128   NiceScopedMockLog log;
   4129   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4130   ScopeLogger::GetInstance()->set_verbose_level(10);
   4131   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4132   EXPECT_CALL(log,
   4133               Log(_, _, HasSubstr("-> PROGRESSIVE_FINISHED_NOCONNECTION")));
   4134   EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_)).Times(0);
   4135   TimeoutPendingConnection();
   4136   ScopeLogger::GetInstance()->set_verbose_level(0);
   4137   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4138   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4139 }
   4140 
   4141 TEST_F(WiFiMainTest, ScanStateUma) {
   4142   EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
   4143       Times(0);
   4144   EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_));
   4145   SetScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive, __func__);
   4146 
   4147   EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
   4148   EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _));
   4149   SetScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive, __func__);
   4150 
   4151   ExpectScanIdle();  // After connected.
   4152   EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_));
   4153   EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _));
   4154   SetScanState(WiFi::kScanConnected, WiFi::kScanMethodProgressive, __func__);
   4155 }
   4156 
   4157 TEST_F(WiFiMainTest, ScanStateNotScanningNoUma) {
   4158   EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_)).Times(0);
   4159   EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _));
   4160   SetScanState(WiFi::kScanConnecting, WiFi::kScanMethodNone, __func__);
   4161 
   4162   ExpectScanIdle();  // After connected.
   4163   EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_));
   4164   EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
   4165       Times(0);
   4166   SetScanState(WiFi::kScanConnected, WiFi::kScanMethodNone, __func__);
   4167 }
   4168 
   4169 TEST_F(WiFiMainTest, ConnectToServiceNotPending) {
   4170   // Test for SetPendingService(nullptr), condition a)
   4171   // |ConnectTo|->|DisconnectFrom|.
   4172   StartScan(WiFi::kScanMethodProgressive);
   4173 
   4174   // Setup pending service.
   4175   ExpectScanStop();
   4176   ExpectConnecting();
   4177   MockWiFiServiceRefPtr service_pending(
   4178       SetupConnectingService("", nullptr, nullptr));
   4179   EXPECT_EQ(service_pending.get(), GetPendingService().get());
   4180 
   4181   // ConnectTo a different service than the pending one.
   4182   ExpectConnecting();
   4183   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
   4184   NiceScopedMockLog log;
   4185   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4186   ScopeLogger::GetInstance()->set_verbose_level(10);
   4187   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4188   EXPECT_CALL(log, Log(_, _, HasSubstr("-> TRANSITION_TO_CONNECTING")));
   4189   EXPECT_CALL(log, Log(_, _, HasSubstr("-> PROGRESSIVE_CONNECTING")));
   4190   MockWiFiServiceRefPtr service_connecting(
   4191       SetupConnectingService("", nullptr, nullptr));
   4192   ScopeLogger::GetInstance()->set_verbose_level(0);
   4193   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4194   EXPECT_EQ(service_connecting.get(), GetPendingService().get());
   4195   EXPECT_EQ(nullptr, GetCurrentService().get());
   4196   VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
   4197 
   4198   ExpectScanIdle();  // To silence messages from the destructor.
   4199 }
   4200 
   4201 TEST_F(WiFiMainTest, ConnectToWithError) {
   4202   StartScan(WiFi::kScanMethodProgressive);
   4203 
   4204   ExpectScanIdle();
   4205   EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(_, _)).
   4206       WillOnce(Return(false));
   4207   EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_)).Times(0);
   4208   EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
   4209       Times(0);
   4210   EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty, false));
   4211   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   4212   EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
   4213   InitiateConnect(service);
   4214   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4215   EXPECT_TRUE(IsScanSessionNull());
   4216 }
   4217 
   4218 TEST_F(WiFiMainTest, ScanStateHandleDisconnect) {
   4219   // Test for SetPendingService(nullptr), condition d) Disconnect while
   4220   // scanning.
   4221 
   4222   // Start scanning.
   4223   StartScan(WiFi::kScanMethodProgressive);
   4224 
   4225   // Set the pending service.
   4226   ReportScanDoneKeepScanSession();
   4227   ExpectScanStop();
   4228   ExpectConnecting();
   4229   MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
   4230   SetPendingService(service);
   4231   VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
   4232 
   4233   // Disconnect from the pending service.
   4234   ExpectScanIdle();
   4235   EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_)).Times(0);
   4236   EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
   4237       Times(0);
   4238   ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
   4239   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4240 }
   4241 
   4242 TEST_F(WiFiMainTest, ConnectWhileNotScanning) {
   4243   // Setup WiFi but terminate scan.
   4244   EXPECT_CALL(*adaptor_, EmitBoolChanged(kPoweredProperty, _)).
   4245       Times(AnyNumber());
   4246 
   4247   ExpectScanStart(WiFi::kScanMethodProgressive, false);
   4248   StartWiFi();
   4249   dispatcher_.DispatchPendingEvents();
   4250 
   4251   ExpectScanStop();
   4252   ExpectFoundNothing();
   4253   ReportScanDone();
   4254   dispatcher_.DispatchPendingEvents();
   4255   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4256 
   4257   // Connecting.
   4258   ExpectConnecting();
   4259   EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_)).Times(0);
   4260   WiFiEndpointRefPtr endpoint;
   4261   string bss_path;
   4262   NiceScopedMockLog log;
   4263   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4264   ScopeLogger::GetInstance()->set_verbose_level(10);
   4265   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4266   EXPECT_CALL(log, Log(_, _, HasSubstr("-> TRANSITION_TO_CONNECTING"))).
   4267       Times(0);
   4268   EXPECT_CALL(log, Log(_, _, HasSubstr("-> CONNECTING (not scan related)")));
   4269   MockWiFiServiceRefPtr service =
   4270       SetupConnectingService("", &endpoint, &bss_path);
   4271 
   4272   // Connected.
   4273   ExpectConnected();
   4274   EXPECT_CALL(log, Log(_, _, HasSubstr("-> CONNECTED (not scan related")));
   4275   ReportCurrentBSSChanged(bss_path);
   4276   ScopeLogger::GetInstance()->set_verbose_level(0);
   4277   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4278   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4279 }
   4280 
   4281 TEST_F(WiFiMainTest, BackgroundScan) {
   4282   StartWiFi();
   4283   SetupConnectedService("", nullptr, nullptr);
   4284   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4285 
   4286   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(1);
   4287   TriggerScan(WiFi::kScanMethodFull);
   4288   dispatcher_.DispatchPendingEvents();
   4289   VerifyScanState(WiFi::kScanBackgroundScanning, WiFi::kScanMethodFull);
   4290 
   4291   ReportScanDone();
   4292   EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
   4293   dispatcher_.DispatchPendingEvents();  // Launch UpdateScanStateAfterScanDone
   4294   VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
   4295 }
   4296 
   4297 TEST_F(WiFiMainTest, ProgressiveScanDuringFull) {
   4298   StartScan(WiFi::kScanMethodFull);
   4299 
   4300   // Now, try to slam-in a progressive scan.
   4301   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   4302   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   4303   TriggerScan(WiFi::kScanMethodProgressive);
   4304   dispatcher_.DispatchPendingEvents();
   4305   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodFull);
   4306 
   4307   // And, for the destructor.
   4308   ExpectScanStop();
   4309   ExpectScanIdle();
   4310 }
   4311 
   4312 TEST_F(WiFiMainTest, FullScanDuringProgressive) {
   4313   StartScan(WiFi::kScanMethodProgressive);
   4314 
   4315   // Now, try to slam-in a full scan.
   4316   EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
   4317   EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
   4318   TriggerScan(WiFi::kScanMethodFull);
   4319   dispatcher_.DispatchPendingEvents();
   4320   VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
   4321 
   4322   // And, for the destructor.
   4323   ExpectScanStop();
   4324   ExpectScanIdle();
   4325 }
   4326 
   4327 TEST_F(WiFiMainTest, TDLSDiscoverResponse) {
   4328   const char kPeer[] = "peer";
   4329   MockTDLSManager* tdls_manager = new StrictMock<MockTDLSManager>();
   4330   SetTDLSManager(tdls_manager);
   4331 
   4332   EXPECT_CALL(*tdls_manager, OnDiscoverResponseReceived(kPeer));
   4333   TDLSDiscoverResponse(kPeer);
   4334   Mock::VerifyAndClearExpectations(tdls_manager);
   4335 }
   4336 
   4337 TEST_F(WiFiMainTest, PerformTDLSOperation) {
   4338   const char kPeerMac[] = "00:11:22:33:44:55";
   4339   MockTDLSManager* tdls_manager = new StrictMock<MockTDLSManager>();
   4340   SetTDLSManager(tdls_manager);
   4341 
   4342   Error error;
   4343   // No address resolution is performed since MAC address is provided.
   4344   EXPECT_CALL(*tdls_manager,
   4345               PerformOperation(kPeerMac, kTDLSStatusOperation, &error))
   4346       .WillOnce(Return(kTDLSConnectedState));
   4347   EXPECT_EQ(kTDLSConnectedState,
   4348             PerformTDLSOperation(kTDLSStatusOperation, kPeerMac, &error));
   4349   EXPECT_TRUE(error.IsSuccess());
   4350 }
   4351 
   4352 TEST_F(WiFiMainTest, OnNewWiphy) {
   4353   NewWiphyMessage new_wiphy_message;
   4354   NetlinkPacket packet(kNewWiphyNlMsg, sizeof(kNewWiphyNlMsg));
   4355   new_wiphy_message.InitFromPacket(&packet, NetlinkMessage::MessageContext());
   4356   EXPECT_CALL(*mac80211_monitor(), Start(_));
   4357   EXPECT_CALL(*wake_on_wifi_, ParseWakeOnWiFiCapabilities(_));
   4358   EXPECT_CALL(*wake_on_wifi_, OnWiphyIndexReceived(kNewWiphyNlMsg_WiphyIndex));
   4359   GetAllScanFrequencies()->clear();
   4360   OnNewWiphy(new_wiphy_message);
   4361   EXPECT_EQ(arraysize(kNewWiphyNlMsg_UniqueFrequencies),
   4362             GetAllScanFrequencies()->size());
   4363   for (uint16_t freq : kNewWiphyNlMsg_UniqueFrequencies) {
   4364     EXPECT_TRUE(GetAllScanFrequencies()->find(freq) !=
   4365                 GetAllScanFrequencies()->end());
   4366   }
   4367 }
   4368 
   4369 TEST_F(WiFiMainTest, StateChangedUpdatesMac80211Monitor) {
   4370   EXPECT_CALL(*mac80211_monitor(), UpdateConnectedState(true)).Times(2);
   4371   ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
   4372   ReportStateChanged(WPASupplicant::kInterfaceState4WayHandshake);
   4373 
   4374   EXPECT_CALL(*mac80211_monitor(), UpdateConnectedState(false));
   4375   ReportStateChanged(WPASupplicant::kInterfaceStateAssociating);
   4376 }
   4377 
   4378 TEST_F(WiFiMainTest, OnIPConfigUpdated_InvokesOnConnectedAndReachable) {
   4379   ScopedMockLog log;
   4380   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4381   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4382   ScopeLogger::GetInstance()->set_verbose_level(3);
   4383   EXPECT_CALL(log, Log(_, _, HasSubstr("IPv4 DHCP lease obtained")));
   4384   EXPECT_CALL(*wake_on_wifi_, OnConnectedAndReachable(_, _));
   4385   EXPECT_CALL(*manager(), device_info()).WillOnce(Return(device_info()));
   4386   ReportIPConfigComplete();
   4387 
   4388   // We should not call WakeOnWiFi::OnConnectedAndReachable if we are not
   4389   // actually connected to a service.
   4390   SetCurrentService(nullptr);
   4391   EXPECT_CALL(*wake_on_wifi_, OnConnectedAndReachable(_, _)).Times(0);
   4392   ReportIPv6ConfigComplete();
   4393 
   4394   // If we are actually connected to a service when our IPv6 configuration is
   4395   // updated, we should call WakeOnWiFi::OnConnectedAndReachable.
   4396   MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
   4397   EXPECT_CALL(*service, IsConnected()).WillOnce(Return(true));
   4398   SetCurrentService(service);
   4399   EXPECT_CALL(log, Log(_, _, HasSubstr("IPv6 configuration obtained")));
   4400   EXPECT_CALL(*wake_on_wifi_, OnConnectedAndReachable(_, _));
   4401   ReportIPv6ConfigComplete();
   4402 
   4403   // Do not call WakeOnWiFi::OnConnectedAndReachable if the IP config update was
   4404   // triggered by a gateway ARP.
   4405   EXPECT_CALL(log, Log(_, _, HasSubstr("Gateway ARP received")));
   4406   EXPECT_CALL(*wake_on_wifi_, OnConnectedAndReachable(_, _)).Times(0);
   4407   ReportIPConfigCompleteGatewayArpReceived();
   4408 
   4409   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4410   ScopeLogger::GetInstance()->set_verbose_level(0);
   4411 }
   4412 
   4413 TEST_F(WiFiMainTest, OnBeforeSuspend_CallsWakeOnWiFi) {
   4414   SetWiFiEnabled(true);
   4415   EXPECT_CALL(
   4416       *wake_on_wifi_,
   4417       OnBeforeSuspend(IsConnectedToCurrentService(), _, _, _, _, _, _));
   4418   EXPECT_CALL(*this, SuspendCallback(_)).Times(0);
   4419   OnBeforeSuspend();
   4420 
   4421   SetWiFiEnabled(false);
   4422   EXPECT_CALL(*wake_on_wifi_,
   4423               OnBeforeSuspend(IsConnectedToCurrentService(), _, _, _, _, _, _))
   4424       .Times(0);
   4425   EXPECT_CALL(*this, SuspendCallback(ErrorTypeIs(Error::kSuccess)));
   4426   OnBeforeSuspend();
   4427 }
   4428 
   4429 TEST_F(WiFiMainTest, OnDarkResume_CallsWakeOnWiFi) {
   4430   SetWiFiEnabled(true);
   4431   EXPECT_CALL(*wake_on_wifi_,
   4432               OnDarkResume(IsConnectedToCurrentService(), _, _, _, _, _));
   4433   EXPECT_CALL(*this, SuspendCallback(_)).Times(0);
   4434   OnDarkResume();
   4435 
   4436   SetWiFiEnabled(false);
   4437   EXPECT_CALL(*wake_on_wifi_,
   4438               OnDarkResume(IsConnectedToCurrentService(), _, _, _, _, _))
   4439       .Times(0);
   4440   EXPECT_CALL(*this, SuspendCallback(ErrorTypeIs(Error::kSuccess)));
   4441   OnDarkResume();
   4442 }
   4443 
   4444 TEST_F(WiFiMainTest, RemoveSupplicantNetworks) {
   4445   StartWiFi();
   4446   MockWiFiServiceRefPtr service1 = MakeMockService(kSecurity8021x);
   4447   MockWiFiServiceRefPtr service2 = MakeMockService(kSecurity8021x);
   4448   const char kNetworkRpcId1[] = "/service/network/rpcid1";
   4449   const char kNetworkRpcId2[] = "/service/network/rpcid2";
   4450   string path1(kNetworkRpcId1);
   4451   string path2(kNetworkRpcId2);
   4452   SetServiceNetworkRpcId(service1, kNetworkRpcId1);
   4453   SetServiceNetworkRpcId(service2, kNetworkRpcId2);
   4454   ASSERT_FALSE(RpcIdByServiceIsEmpty());
   4455   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(path1));
   4456   EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(path2));
   4457   RemoveSupplicantNetworks();
   4458   ASSERT_TRUE(RpcIdByServiceIsEmpty());
   4459 }
   4460 
   4461 TEST_F(WiFiMainTest, InitiateScan_Idle) {
   4462   ScopedMockLog log;
   4463   Device::ScanType scan_type = Device::kFullScan;
   4464   ASSERT_TRUE(wifi()->IsIdle());
   4465   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4466   EXPECT_CALL(log, Log(_, _, ContainsRegex("Scan.* \\[full\\]")));
   4467   InitiateScan(scan_type);
   4468 
   4469   scan_type = Device::kProgressiveScan;
   4470   ASSERT_TRUE(wifi()->IsIdle());
   4471   EXPECT_CALL(log, Log(_, _, ContainsRegex("Scan.* \\[progressive\\]")));
   4472   InitiateScan(scan_type);
   4473 }
   4474 
   4475 TEST_F(WiFiMainTest, InitiateScan_NotIdle) {
   4476   const Device::ScanType scan_type = Device::kFullScan;
   4477   ScopedMockLog log;
   4478   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4479   ScopeLogger::GetInstance()->set_verbose_level(1);
   4480   MockWiFiServiceRefPtr service = MakeMockService(kSecurityWpa);
   4481   SetPendingService(service);
   4482   EXPECT_FALSE(wifi()->IsIdle());
   4483   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4484   EXPECT_CALL(
   4485       log,
   4486       Log(_, _, HasSubstr("skipping scan, already connecting or connected.")));
   4487   InitiateScan(scan_type);
   4488   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4489   ScopeLogger::GetInstance()->set_verbose_level(0);
   4490 }
   4491 
   4492 TEST_F(WiFiMainTest, InitiateScanInDarkResume_Idle) {
   4493   const WiFi::FreqSet freqs;
   4494   StartWiFi();
   4495   manager()->set_suppress_autoconnect(false);
   4496   ASSERT_TRUE(wifi()->IsIdle());
   4497   EXPECT_CALL(netlink_manager_,
   4498               SendNl80211Message(IsNl80211Command(kNl80211FamilyId,
   4499                                                   TriggerScanMessage::kCommand),
   4500                                  _, _, _));
   4501   EXPECT_CALL(*GetSupplicantInterfaceProxy(), FlushBSS(0));
   4502   InitiateScanInDarkResume(freqs);
   4503   EXPECT_TRUE(manager()->suppress_autoconnect());
   4504 }
   4505 
   4506 TEST_F(WiFiMainTest, InitiateScanInDarkResume_NotIdle) {
   4507   const WiFi::FreqSet freqs;
   4508   ScopedMockLog log;
   4509   MockWiFiServiceRefPtr service = MakeMockService(kSecurityWpa);
   4510   SetPendingService(service);
   4511   manager()->set_suppress_autoconnect(false);
   4512   EXPECT_FALSE(wifi()->IsIdle());
   4513   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4514   EXPECT_CALL(
   4515       log,
   4516       Log(_, _, HasSubstr("skipping scan, already connecting or connected.")));
   4517   EXPECT_CALL(netlink_manager_,
   4518               SendNl80211Message(IsNl80211Command(kNl80211FamilyId,
   4519                                                   TriggerScanMessage::kCommand),
   4520                                  _, _, _)).Times(0);
   4521   EXPECT_CALL(*GetSupplicantInterfaceProxy(), FlushBSS(_)).Times(0);
   4522   InitiateScanInDarkResume(freqs);
   4523   EXPECT_FALSE(manager()->suppress_autoconnect());
   4524 }
   4525 
   4526 TEST_F(WiFiMainTest, TriggerPassiveScan_NoResults) {
   4527   ScopedMockLog log;
   4528   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4529   ScopeLogger::GetInstance()->set_verbose_level(3);
   4530   const WiFi::FreqSet freqs;
   4531   EXPECT_CALL(netlink_manager_,
   4532               SendNl80211Message(IsNl80211Command(kNl80211FamilyId,
   4533                                                   TriggerScanMessage::kCommand),
   4534                                  _, _, _));
   4535   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4536   EXPECT_CALL(log, Log(_, _, HasSubstr("Scanning on specific channels")))
   4537       .Times(0);
   4538   TriggerPassiveScan(freqs);
   4539   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4540   ScopeLogger::GetInstance()->set_verbose_level(0);
   4541 }
   4542 
   4543 TEST_F(WiFiMainTest, TriggerPassiveScan_HasResults) {
   4544   ScopedMockLog log;
   4545   ScopeLogger::GetInstance()->EnableScopesByName("wifi");
   4546   ScopeLogger::GetInstance()->set_verbose_level(3);
   4547   const WiFi::FreqSet freqs = {1};
   4548   EXPECT_CALL(netlink_manager_,
   4549               SendNl80211Message(IsNl80211Command(kNl80211FamilyId,
   4550                                                   TriggerScanMessage::kCommand),
   4551                                  _, _, _));
   4552   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4553   EXPECT_CALL(log, Log(_, _, HasSubstr("Scanning on specific channels")))
   4554       .Times(1);
   4555   TriggerPassiveScan(freqs);
   4556   ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
   4557   ScopeLogger::GetInstance()->set_verbose_level(0);
   4558 }
   4559 
   4560 TEST_F(WiFiMainTest, PendingScanEvents) {
   4561   // This test essentially performs ReportBSS(), but ensures that the
   4562   // WiFi object successfully dispatches events in order.
   4563   StartWiFi();
   4564   BSSAdded(
   4565       "bss0",
   4566       CreateBSSProperties("ssid0", "00:00:00:00:00:00", 0, 0,
   4567                           kNetworkModeInfrastructure));
   4568   BSSAdded(
   4569       "bss1",
   4570       CreateBSSProperties("ssid1", "00:00:00:00:00:01", 0, 0,
   4571                           kNetworkModeInfrastructure));
   4572   BSSRemoved("bss0");
   4573   BSSAdded(
   4574       "bss2",
   4575       CreateBSSProperties("ssid2", "00:00:00:00:00:02", 0, 0,
   4576                           kNetworkModeInfrastructure));
   4577 
   4578   WiFiEndpointRefPtr ap0 = MakeEndpoint("ssid0", "00:00:00:00:00:00");
   4579   WiFiEndpointRefPtr ap1 = MakeEndpoint("ssid1", "00:00:00:00:00:01");
   4580   WiFiEndpointRefPtr ap2 = MakeEndpoint("ssid2", "00:00:00:00:00:02");
   4581 
   4582   InSequence seq;
   4583   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap0)));
   4584   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap1)));
   4585   WiFiServiceRefPtr null_service;
   4586   EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(ap0)))
   4587       .WillOnce(Return(null_service));
   4588   EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap2)));
   4589   dispatcher_.DispatchPendingEvents();
   4590   Mock::VerifyAndClearExpectations(wifi_provider());
   4591 
   4592   const WiFi::EndpointMap& endpoints_by_rpcid = GetEndpointMap();
   4593   EXPECT_EQ(2, endpoints_by_rpcid.size());
   4594 }
   4595 
   4596 TEST_F(WiFiMainTest, ParseWiphyIndex_Success) {
   4597   // Verify that the wiphy index in kNewWiphyNlMsg is parsed, and that the flag
   4598   // for having the wiphy index is set by ParseWiphyIndex.
   4599   EXPECT_EQ(GetWiphyIndex(), WiFi::kDefaultWiphyIndex);
   4600   NewWiphyMessage msg;
   4601   NetlinkPacket packet(kNewWiphyNlMsg, sizeof(kNewWiphyNlMsg));
   4602   msg.InitFromPacket(&packet, NetlinkMessage::MessageContext());
   4603   EXPECT_TRUE(ParseWiphyIndex(msg));
   4604   EXPECT_EQ(GetWiphyIndex(), kNewWiphyNlMsg_WiphyIndex);
   4605 }
   4606 
   4607 TEST_F(WiFiMainTest, ParseWiphyIndex_Failure) {
   4608   ScopedMockLog log;
   4609   // Change the NL80211_ATTR_WIPHY U32 attribute to the NL80211_ATTR_WIPHY_FREQ
   4610   // U32 attribute, so that this message no longer contains a wiphy_index to be
   4611   // parsed.
   4612   NewWiphyMessage msg;
   4613   MutableNetlinkPacket packet(kNewWiphyNlMsg, sizeof(kNewWiphyNlMsg));
   4614   struct nlattr* nl80211_attr_wiphy = reinterpret_cast<struct nlattr*>(
   4615       &packet.GetMutablePayload()->GetData()[
   4616           kNewWiphyNlMsg_Nl80211AttrWiphyOffset]);
   4617   nl80211_attr_wiphy->nla_type = NL80211_ATTR_WIPHY_FREQ;
   4618   msg.InitFromPacket(&packet, NetlinkMessage::MessageContext());
   4619   EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
   4620   EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
   4621                        "NL80211_CMD_NEW_WIPHY had no NL80211_ATTR_WIPHY"));
   4622   EXPECT_FALSE(ParseWiphyIndex(msg));
   4623   EXPECT_CALL(*wake_on_wifi_, OnWiphyIndexReceived(_)).Times(0);
   4624 }
   4625 
   4626 TEST_F(WiFiMainTest, OnScanStarted_ActiveScan) {
   4627   SetWiphyIndex(kScanTriggerMsgWiphyIndex);
   4628   TriggerScanMessage msg;
   4629   NetlinkPacket packet(
   4630       kActiveScanTriggerNlMsg, sizeof(kActiveScanTriggerNlMsg));
   4631   msg.InitFromPacket(&packet, NetlinkMessage::MessageContext());
   4632   EXPECT_CALL(*wake_on_wifi_, OnScanStarted(true));
   4633   OnScanStarted(msg);
   4634 }
   4635 
   4636 TEST_F(WiFiMainTest, OnScanStarted_PassiveScan) {
   4637   SetWiphyIndex(kScanTriggerMsgWiphyIndex);
   4638   TriggerScanMessage msg;
   4639   NetlinkPacket packet(
   4640       kPassiveScanTriggerNlMsg, sizeof(kPassiveScanTriggerNlMsg));
   4641   msg.InitFromPacket(&packet, NetlinkMessage::MessageContext());
   4642   EXPECT_CALL(*wake_on_wifi_, OnScanStarted(false));
   4643   OnScanStarted(msg);
   4644 }
   4645 
   4646 }  // namespace shill
   4647