• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import collections
6import logging
7import re
8import time
9
10from autotest_lib.client.common_lib import error
11from autotest_lib.client.common_lib import utils
12from autotest_lib.client.common_lib.cros.network import xmlrpc_datatypes
13
14
15# Used to represent stations we parse out of scan results.
16Station = collections.namedtuple('Station',
17                                 ['bssid', 'frequency', 'signal', 'ssid'])
18
19class WpaCliProxy(object):
20    """Interacts with a DUT through wpa_cli rather than shill."""
21
22    SCANNING_INTERVAL_SECONDS = 5
23    POLLING_INTERVAL_SECONDS = 0.5
24    # From wpa_supplicant.c:wpa_supplicant_state_txt()
25    WPA_SUPPLICANT_ASSOCIATING_STATES = (
26            'AUTHENTICATING',
27            'ASSOCIATING',
28            'ASSOCIATED',
29            '4WAY_HANDSHAKE',
30            'GROUP_HANDSHAKE')
31    WPA_SUPPLICANT_ASSOCIATED_STATES = (
32            'COMPLETED',)
33    ANDROID_CMD_FORMAT = '/system/bin/wpa_cli IFNAME={0[ifname]} {0[cmd]}'
34    BRILLO_CMD_FORMAT = 'su system /system/bin/wpa_cli -i{0[ifname]} -p/data/misc/wifi/sockets {0[cmd]}'
35    CROS_CMD_FORMAT = 'su wpa -s /bin/bash -c "/usr/bin/wpa_cli {0[cmd]}"'
36    CAST_CMD_FORMAT = '/system/bin/wpa_cli -i {0[ifname]} {0[cmd]}'
37
38
39    def __init__(self, host, wifi_if):
40        self._host = host
41        self._wifi_if = wifi_if
42        self._created_networks = {}
43        # TODO(wiley) Hardcoding this IFNAME prefix makes some big assumptions.
44        #             we'll need to discover this parameter as it becomes more
45        #             generally useful.
46        if host.get_os_type() == 'android':
47            self._wpa_cli_cmd_format = self.ANDROID_CMD_FORMAT
48        elif host.get_os_type() == 'brillo':
49            self._wpa_cli_cmd_format = self.BRILLO_CMD_FORMAT
50        elif host.get_os_type() == 'cros':
51            self._wpa_cli_cmd_format = self.CROS_CMD_FORMAT
52        elif host.get_os_type() == 'cast_os':
53            self._wpa_cli_cmd_format = self.CAST_CMD_FORMAT
54
55
56    def _add_network(self, ssid):
57        """
58        Add a wpa_supplicant network for ssid.
59
60        @param ssid string: name of network to add.
61        @return int network id of added network.
62
63        """
64        add_result = self.run_wpa_cli_cmd('add_network', check_result=False)
65        network_id = int(add_result.stdout.splitlines()[-1])
66        self.run_wpa_cli_cmd('set_network %d ssid \\"%s\\"' %
67                             (network_id, ssid))
68        self._created_networks[ssid] = network_id
69        logging.debug('Added network %s=%d', ssid, network_id)
70        return network_id
71
72
73    def run_wpa_cli_cmd(self, command, check_result=True):
74        """
75        Run a wpa_cli command and optionally check the result.
76
77        @param command string: suffix of a command to be prefixed with
78                an appropriate wpa_cli for this host.
79        @param check_result bool: True iff we want to check that the
80                command comes back with an 'OK' response.
81        @return result object returned by host.run.
82
83        """
84        cmd = self._wpa_cli_cmd_format.format(
85                {'ifname' : self._wifi_if, 'cmd' : command})
86        result = self._host.run(cmd)
87        if check_result and not result.stdout.strip().endswith('OK'):
88            raise error.TestFail('wpa_cli command failed: %s' % command)
89
90        return result
91
92
93    def _get_status_dict(self):
94        """
95        Gets the status output for a WiFi interface.
96
97        Get the output of wpa_cli status.  This summarizes what wpa_supplicant
98        is doing with respect to the WiFi interface.
99
100        Example output:
101
102            Using interface 'wlan0'
103            wpa_state=INACTIVE
104            p2p_device_address=32:76:6f:f2:a6:c4
105            address=30:76:6f:f2:a6:c4
106
107        @return dict of key/value pairs parsed from output using = as divider.
108
109        """
110        status_result = self.run_wpa_cli_cmd('status', check_result=False)
111        return dict([line.strip().split('=', 1)
112                     for line in status_result.stdout.splitlines()
113                     if line.find('=') > 0])
114
115
116    def _is_associating_or_associated(self):
117        """@return True if the DUT is assocating or associated with a BSS."""
118        state = self._get_status_dict().get('wpa_state', None)
119        return state in (self.WPA_SUPPLICANT_ASSOCIATING_STATES +
120                         self.WPA_SUPPLICANT_ASSOCIATED_STATES)
121
122
123    def _is_associated(self, ssid):
124        """
125        Check if the DUT is associated to a given SSID.
126
127        @param ssid string: SSID of the network we're concerned about.
128        @return True if we're associated with the specified SSID.
129
130        """
131        status_dict = self._get_status_dict()
132        return (status_dict.get('ssid', None) == ssid and
133                status_dict.get('wpa_state', None) in
134                        self.WPA_SUPPLICANT_ASSOCIATED_STATES)
135
136
137    def _is_connected(self, ssid):
138        """
139        Check that we're connected to |ssid| and have an IP address.
140
141        @param ssid string: SSID of the network we're concerned about.
142        @return True if we have an IP and we're associated with |ssid|.
143
144        """
145        status_dict = self._get_status_dict()
146        return (status_dict.get('ssid', None) == ssid and
147                status_dict.get('ip_address', None))
148
149
150    def clean_profiles(self):
151        """Remove state associated with past networks we've connected to."""
152        # list_networks output looks like:
153        # Using interface 'wlan0'^M
154        # network id / ssid / bssid / flags^M
155        # 0    SimpleConnect_jstja_ch1 any     [DISABLED]^M
156        # 1    SimpleConnect_gjji2_ch6 any     [DISABLED]^M
157        # 2    SimpleConnect_xe9d1_ch11        any     [DISABLED]^M
158        list_networks_result = self.run_wpa_cli_cmd(
159                'list_networks', check_result=False)
160        start_parsing = False
161        for line in list_networks_result.stdout.splitlines():
162            if not start_parsing:
163                if line.startswith('network id'):
164                    start_parsing = True
165                continue
166
167            network_id = int(line.split()[0])
168            self.run_wpa_cli_cmd('remove_network %d' % network_id)
169        self._created_networks = {}
170
171
172    def create_profile(self, _):
173        """
174        This is a no op, since we don't have profiles.
175
176        @param _ ignored.
177
178        """
179        logging.info('Skipping create_profile on %s', self.__class__.__name__)
180
181
182    def pop_profile(self, _):
183        """
184        This is a no op, since we don't have profiles.
185
186        @param _ ignored.
187
188        """
189        logging.info('Skipping pop_profile on %s', self.__class__.__name__)
190
191
192    def push_profile(self, _):
193        """
194        This is a no op, since we don't have profiles.
195
196        @param _ ignored.
197
198        """
199        logging.info('Skipping push_profile on %s', self.__class__.__name__)
200
201
202    def remove_profile(self, _):
203        """
204        This is a no op, since we don't have profiles.
205
206        @param _ ignored.
207
208        """
209        logging.info('Skipping remove_profile on %s', self.__class__.__name__)
210
211
212    def init_test_network_state(self):
213        """Create a clean slate for tests with respect to remembered networks.
214
215        For wpa_cli hosts, this means removing all remembered networks.
216
217        @return True iff operation succeeded, False otherwise.
218
219        """
220        self.clean_profiles()
221        return True
222
223
224    def connect_wifi(self, assoc_params):
225        """
226        Connect to the WiFi network described by AssociationParameters.
227
228        @param assoc_params AssociationParameters object.
229        @return serialized AssociationResult object.
230
231        """
232        logging.debug('connect_wifi()')
233        # Ouptut should look like:
234        #   Using interface 'wlan0'
235        #   0
236        assoc_result = xmlrpc_datatypes.AssociationResult()
237        network_id = self._add_network(assoc_params.ssid)
238        if assoc_params.is_hidden:
239            self.run_wpa_cli_cmd('set_network %d %s %s' %
240                                 (network_id, 'scan_ssid', '1'))
241
242        sec_config = assoc_params.security_config
243        for field, value in sec_config.get_wpa_cli_properties().iteritems():
244            self.run_wpa_cli_cmd('set_network %d %s %s' %
245                                 (network_id, field, value))
246        self.run_wpa_cli_cmd('select_network %d' % network_id)
247
248        # Wait for an appropriate BSS to appear in scan results.
249        scan_results_pattern = '\t'.join(['([0-9a-f:]{17})', # BSSID
250                                          '([0-9]+)',  # Frequency
251                                          '(-[0-9]+)',  # Signal level
252                                          '(.*)',  # Encryption types
253                                          '(.*)'])  # SSID
254        last_scan_time = -1.0
255        start_time = time.time()
256        while time.time() - start_time < assoc_params.discovery_timeout:
257            assoc_result.discovery_time = time.time() - start_time
258            if self._is_associating_or_associated():
259                # Internally, wpa_supplicant writes its scan_results response
260                # to a 4kb buffer.  When there are many BSS's, the buffer fills
261                # up, and we'll never see the BSS we care about in some cases.
262                break
263
264            scan_result = self.run_wpa_cli_cmd('scan_results',
265                                               check_result=False)
266            found_stations = []
267            for line in scan_result.stdout.strip().splitlines():
268                match = re.match(scan_results_pattern, line)
269                if match is None:
270                    continue
271                found_stations.append(
272                        Station(bssid=match.group(1), frequency=match.group(2),
273                                signal=match.group(3), ssid=match.group(5)))
274            logging.debug('Found stations: %r',
275                          [station.ssid for station in found_stations])
276            if [station for station in found_stations
277                    if station.ssid == assoc_params.ssid]:
278                break
279
280            if time.time() - last_scan_time > self.SCANNING_INTERVAL_SECONDS:
281                # Sometimes this might fail with a FAIL-BUSY if the previous
282                # scan hasn't finished.
283                scan_result = self.run_wpa_cli_cmd('scan', check_result=False)
284                if scan_result.stdout.strip().endswith('OK'):
285                    last_scan_time = time.time()
286            time.sleep(self.POLLING_INTERVAL_SECONDS)
287        else:
288            assoc_result.failure_reason = 'Discovery timed out'
289            return assoc_result.serialize()
290
291        # Wait on association to finish.
292        start_time = time.time()
293        success = utils.poll_for_condition(
294                condition=lambda: self._is_associated(assoc_params.ssid),
295                timeout=assoc_params.association_timeout,
296                sleep_interval=self.POLLING_INTERVAL_SECONDS,
297                desc='Wait on association to finish')
298        assoc_result.association_time = time.time() - start_time
299        if not success:
300            assoc_result.failure_reason = 'Association timed out'
301            return assoc_result.serialize()
302
303        # Then wait for ip configuration to finish.
304        start_time = time.time()
305        success = utils.poll_for_condition(
306                condition=lambda: self._is_connected(assoc_params.ssid),
307                timeout=assoc_params.configuration_timeout,
308                sleep_interval=self.POLLING_INTERVAL_SECONDS,
309                desc='Wait for ip configuration to finish')
310        assoc_result.configuration_time = time.time() - start_time
311        if not success:
312            assoc_result.failure_reason = 'DHCP negotiation timed out'
313            return assoc_result.serialize()
314
315        assoc_result.success = True
316        logging.info('Connected to %s', assoc_params.ssid)
317        return assoc_result.serialize()
318
319
320    def disconnect(self, ssid):
321        """
322        Disconnect from a WiFi network named |ssid|.
323
324        @param ssid string: name of network to disable in wpa_supplicant.
325
326        """
327        logging.debug('disconnect()')
328        if ssid not in self._created_networks:
329            return False
330        self.run_wpa_cli_cmd('disable_network %d' %
331                             self._created_networks[ssid])
332        return True
333
334
335    def delete_entries_for_ssid(self, ssid):
336        """Delete a profile entry.
337
338        @param ssid string of WiFi service for which to delete entries.
339        @return True on success, False otherwise.
340        """
341        return self.disconnect(ssid)
342
343
344    def set_device_enabled(self, wifi_interface, enabled):
345        """Enable or disable the WiFi device.
346
347        @param wifi_interface: string name of interface being modified.
348        @param enabled: boolean; true if this device should be enabled,
349                false if this device should be disabled.
350        @return True if it worked; false, otherwise
351
352        """
353        return False
354
355
356    def sync_time_to(self, epoch_seconds):
357        """
358        Sync time on the DUT to |epoch_seconds| from the epoch.
359
360        @param epoch_seconds float: number of seconds since the epoch.
361
362        """
363        # This will claim to fail, but will work anyway.
364        self._host.run('date -u %f' % epoch_seconds, ignore_status=True)
365