blob: 49c6b5f2747ea60e8fde115b8757129980d00bac [file] [log] [blame]
Sam Leffler6969d1d2010-03-15 16:07:11 -07001# Copyright (c) 2010 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
Christopher Wiley14796b32013-04-03 14:53:33 -07005import logging
Christopher Wiley3166e432013-08-06 09:53:12 -07006import random
Christopher Wiley14796b32013-04-03 14:53:33 -07007import re
Christopher Wiley3166e432013-08-06 09:53:12 -07008import string
Christopher Wiley14796b32013-04-03 14:53:33 -07009
Paul Stewartc9628b32010-08-11 13:03:51 -070010from autotest_lib.client.common_lib import error
Paul Stewart2ee7fdf2011-05-19 16:29:23 -070011from autotest_lib.server import site_linux_system
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070012from autotest_lib.server.cros import wifi_test_utils
Christopher Wiley99d42c92013-07-09 16:40:16 -070013from autotest_lib.server.cros.network import hostap_config
Sam Leffler19bb0a72010-04-12 08:51:08 -070014
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070015def isLinuxRouter(host):
16 """Check if host is a linux router.
17
18 @param host Host object representing the remote machine.
19 @return True iff remote system is a Linux system.
20
21 """
22 router_uname = host.run('uname').stdout
Sam Leffler19bb0a72010-04-12 08:51:08 -070023 return re.search('Linux', router_uname)
24
Christopher Wiley1febd6a2013-06-03 13:59:48 -070025
Paul Stewart2ee7fdf2011-05-19 16:29:23 -070026class LinuxRouter(site_linux_system.LinuxSystem):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070027 """Linux/mac80211-style WiFi Router support for WiFiTest class.
Sam Leffler6969d1d2010-03-15 16:07:11 -070028
29 This class implements test methods/steps that communicate with a
30 router implemented with Linux/mac80211. The router must
31 be pre-configured to enable ssh access and have a mac80211-based
32 wireless device. We also assume hostapd 0.7.x and iw are present
33 and any necessary modules are pre-loaded.
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070034
Sam Leffler6969d1d2010-03-15 16:07:11 -070035 """
36
Christopher Wiley3166e432013-08-06 09:53:12 -070037 KNOWN_TEST_PREFIX = 'network_WiFi'
38 SUFFIX_LETTERS = string.ascii_lowercase + string.digits
Sam Leffler6969d1d2010-03-15 16:07:11 -070039
Paul Stewart51b0f382013-06-12 09:03:02 -070040 def get_capabilities(self):
41 """@return iterable object of AP capabilities for this system."""
42 caps = set()
43 try:
44 self.cmd_send_management_frame = wifi_test_utils.must_be_installed(
45 self.router, '/usr/bin/send_management_frame')
46 caps.add(self.CAPABILITY_SEND_MANAGEMENT_FRAME)
47 except error.TestFail:
48 pass
49 return super(LinuxRouter, self).get_capabilities().union(caps)
50
51
Christopher Wiley3166e432013-08-06 09:53:12 -070052 def __init__(self, host, params, test_name):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070053 """Build a LinuxRouter.
54
55 @param host Host object representing the remote machine.
56 @param params dict of settings from site_wifitest based tests.
Christopher Wiley3166e432013-08-06 09:53:12 -070057 @param test_name string name of this test. Used in SSID creation.
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070058
59 """
60 site_linux_system.LinuxSystem.__init__(self, host, params, 'router')
mukesh agrawalfe0e85b2011-08-09 14:24:15 -070061 self._remove_interfaces()
Paul Stewart2ee7fdf2011-05-19 16:29:23 -070062
Wade Guthrie24d1e312012-04-24 16:53:40 -070063 # Router host.
64 self.router = host
65
Christopher Wileyf99e6cc2013-04-19 10:12:43 -070066 self.cmd_hostapd = wifi_test_utils.must_be_installed(
67 host, params.get('cmd_hostapd', '/usr/sbin/hostapd'))
68 self.cmd_hostapd_cli = params.get('cmd_hostapd_cli',
69 '/usr/sbin/hostapd_cli')
70 self.dhcpd_conf = '/tmp/dhcpd.%s.conf'
71 self.dhcpd_leases = '/tmp/dhcpd.leases'
Nebojsa Sabovic138ff912010-04-06 15:47:42 -070072
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -070073 # hostapd configuration persists throughout the test, subsequent
74 # 'config' commands only modify it.
Christopher Wiley3166e432013-08-06 09:53:12 -070075 self.ssid_prefix = test_name
76 if self.ssid_prefix.startswith(self.KNOWN_TEST_PREFIX):
77 # Many of our tests start with an uninteresting prefix.
78 # Remove it so we can have more unique bytes.
79 self.ssid_prefix = self.ssid_prefix[len(self.KNOWN_TEST_PREFIX):]
80 self.ssid_prefix = self.ssid_prefix.lstrip('_')
81 self.ssid_prefix += '_'
82
Paul Stewartd5aafa92013-03-24 19:06:14 -070083 self.default_config = {
Paul Stewartd5aafa92013-03-24 19:06:14 -070084 'hw_mode': 'g',
85 'ctrl_interface': '/tmp/hostapd-test.control',
86 'logger_syslog': '-1',
87 'logger_syslog_level': '0'
88 }
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -070089 self.hostapd = {
90 'configured': False,
Paul Stewart326badb2012-12-18 14:18:54 -080091 'config_file': "/tmp/hostapd-test-%s.conf",
92 'log_file': "/tmp/hostapd-test-%s.log",
Paul Stewartf854d2e2011-05-04 13:19:18 -070093 'log_count': 0,
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -070094 'driver': "nl80211",
Paul Stewartd5aafa92013-03-24 19:06:14 -070095 'conf': self.default_config.copy()
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -070096 }
Paul Stewartc2b3de82011-03-03 14:45:31 -080097 self.station = {
98 'configured': False,
Christopher Wiley3166e432013-08-06 09:53:12 -070099 'conf': {},
Paul Stewartc2b3de82011-03-03 14:45:31 -0800100 }
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700101 self.local_servers = []
Paul Stewart548cf452012-11-27 17:46:23 -0800102 self.hostapd_instances = []
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700103 self.force_local_server = "force_local_server" in params
104 self.dhcp_low = 1
105 self.dhcp_high = 128
Paul Stewartf05d7fd2011-04-06 16:19:37 -0700106
Paul Stewart548cf452012-11-27 17:46:23 -0800107 # Kill hostapd and dhcp server if already running.
Thieu Le7b23a542012-01-27 15:54:48 -0800108 self.kill_hostapd()
Paul Stewart548cf452012-11-27 17:46:23 -0800109 self.stop_dhcp_servers()
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700110
Nebojsa Sabovicbc245c62010-04-28 16:58:50 -0700111 # Place us in the US by default
112 self.router.run("%s reg set US" % self.cmd_iw)
Sam Leffler6969d1d2010-03-15 16:07:11 -0700113
Paul Stewartf05d7fd2011-04-06 16:19:37 -0700114
Christopher Wileyf4bc88b2013-08-29 16:45:15 -0700115 def close(self):
116 """Close global resources held by this system."""
117 self.destroy()
118 super(LinuxRouter, self).close()
119
120
Sam Leffler6969d1d2010-03-15 16:07:11 -0700121 def create(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700122 """Create a wifi device of the specified type.
Christopher Wiley14796b32013-04-03 14:53:33 -0700123
124 @param params dict containing the device type under key 'type'.
125
126 """
127 self.create_wifi_device(params['type'])
128
129
130 def create_wifi_device(self, device_type='hostap'):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700131 """Create a wifi device of the specified type.
Christopher Wiley14796b32013-04-03 14:53:33 -0700132
133 Defaults to creating a hostap managed device.
134
135 @param device_type string device type.
136
137 """
Sam Leffler6969d1d2010-03-15 16:07:11 -0700138 #
139 # AP mode is handled entirely by hostapd so we only
140 # have to setup others (mapping the bsd type to what
141 # iw wants)
142 #
143 # map from bsd types to iw types
Christopher Wiley14796b32013-04-03 14:53:33 -0700144 self.apmode = device_type in ('ap', 'hostap')
Paul Stewartc2b3de82011-03-03 14:45:31 -0800145 if not self.apmode:
Christopher Wiley14796b32013-04-03 14:53:33 -0700146 self.station['type'] = device_type
Paul Stewart2ee7fdf2011-05-19 16:29:23 -0700147 self.phytype = {
Christopher Wiley14796b32013-04-03 14:53:33 -0700148 'sta' : 'managed',
149 'monitor' : 'monitor',
150 'adhoc' : 'adhoc',
151 'ibss' : 'ibss',
152 'ap' : 'managed', # NB: handled by hostapd
153 'hostap' : 'managed', # NB: handled by hostapd
154 'mesh' : 'mesh',
155 'wds' : 'wds',
156 }[device_type]
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700157
Sam Leffler6969d1d2010-03-15 16:07:11 -0700158
Christopher Wileyd89b5282013-04-10 15:21:26 -0700159 def destroy(self, params={}):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700160 """Destroy a previously created device.
161
162 @param params dict of site_wifitest parameters.
163
164 """
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700165 self.deconfig(params)
Paul Stewartd5aafa92013-03-24 19:06:14 -0700166 self.hostapd['conf'] = self.default_config.copy()
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700167
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700168
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700169 def has_local_server(self):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700170 """@return True iff this router has local servers configured."""
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700171 return bool(self.local_servers)
Sam Leffler6969d1d2010-03-15 16:07:11 -0700172
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700173
Paul Stewart9e3ff0b2011-08-17 20:35:19 -0700174 def cleanup(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700175 """Clean up any resources in use.
176
177 @param params dict of site_wifitest parameters.
178
179 """
Paul Stewart9e3ff0b2011-08-17 20:35:19 -0700180 # For linux, this is a no-op
181 pass
182
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700183
Paul Stewart548cf452012-11-27 17:46:23 -0800184 def start_hostapd(self, conf, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700185 """Start a hostapd instance described by conf.
186
187 @param conf dict of hostapd configuration parameters.
188 @param params dict of site_wifitest parameters.
189
190 """
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700191 logging.info('Starting hostapd with parameters: %r', conf)
Paul Stewart548cf452012-11-27 17:46:23 -0800192 # Figure out the correct interface.
Paul Stewart326badb2012-12-18 14:18:54 -0800193 interface = self._get_wlanif(self.hostapd['frequency'],
194 self.phytype,
195 mode=conf.get('hw_mode', 'b'))
196
197 conf_file = self.hostapd['config_file'] % interface
198 log_file = self.hostapd['log_file'] % interface
199 conf['interface'] = interface
Paul Stewart548cf452012-11-27 17:46:23 -0800200
201 # Generate hostapd.conf.
202 self._pre_config_hook(conf)
203 self.router.run("cat <<EOF >%s\n%s\nEOF\n" %
204 (conf_file, '\n'.join(
205 "%s=%s" % kv for kv in conf.iteritems())))
206
207 # Run hostapd.
208 logging.info("Starting hostapd...")
209 self._pre_start_hook(params)
210 self.router.run("%s -dd %s &> %s &" %
211 (self.cmd_hostapd, conf_file, log_file))
212
213 self.hostapd_instances.append({
214 'conf_file': conf_file,
215 'log_file': log_file,
Paul Stewart326badb2012-12-18 14:18:54 -0800216 'interface': interface
Paul Stewart548cf452012-11-27 17:46:23 -0800217 })
218
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700219
Paul Stewart326badb2012-12-18 14:18:54 -0800220 def _kill_process_instance(self, process, instance=None, wait=0):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700221 """Kill a process on the router.
222
Paul Stewart326badb2012-12-18 14:18:54 -0800223 Kills program named |process|, optionally only a specific
224 |instance|. If |wait| is specified, we makes sure |process| exits
225 before returning.
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700226
227 @param process string name of process to kill.
228 @param instance string instance of process to kill.
229 @param wait int timeout in seconds to wait for.
230
Thieu Le7b23a542012-01-27 15:54:48 -0800231 """
Paul Stewart21737812012-12-06 11:03:32 -0800232 if instance:
Paul Stewart326badb2012-12-18 14:18:54 -0800233 search_arg = '-f "%s.*%s"' % (process, instance)
Paul Stewart21737812012-12-06 11:03:32 -0800234 else:
Paul Stewart326badb2012-12-18 14:18:54 -0800235 search_arg = process
Paul Stewart21737812012-12-06 11:03:32 -0800236
Paul Stewart326badb2012-12-18 14:18:54 -0800237 cmd = "pkill %s >/dev/null 2>&1" % search_arg
238
239 if wait:
240 cmd += (" && while pgrep %s &> /dev/null; do sleep 1; done" %
241 search_arg)
242 self.router.run(cmd, timeout=wait, ignore_status=True)
243 else:
244 self.router.run(cmd, ignore_status=True)
245
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700246
Paul Stewart326badb2012-12-18 14:18:54 -0800247 def kill_hostapd_instance(self, instance):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700248 """Kills a hostapd instance.
249
250 @param instance string instance to kill.
251
252 """
Paul Stewart326badb2012-12-18 14:18:54 -0800253 self._kill_process_instance('hostapd', instance, 30)
Thieu Le7b23a542012-01-27 15:54:48 -0800254
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700255
Paul Stewart21737812012-12-06 11:03:32 -0800256 def kill_hostapd(self):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700257 """Kill all hostapd instances."""
Paul Stewart21737812012-12-06 11:03:32 -0800258 self.kill_hostapd_instance(None)
259
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700260
261 def __get_default_hostap_config(self):
262 """@return dict of default options for hostapd."""
263 conf = self.hostapd['conf']
264 # default RTS and frag threshold to ``off''
265 conf['rts_threshold'] = '2347'
266 conf['fragm_threshold'] = '2346'
267 conf['driver'] = self.hostapd['driver']
Christopher Wiley0ff28ab2013-08-12 13:23:04 -0700268 conf['ssid'] = self._build_ssid('')
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700269 return conf
270
271
Christopher Wiley0ff28ab2013-08-12 13:23:04 -0700272 def _build_ssid(self, suffix):
Christopher Wiley3166e432013-08-06 09:53:12 -0700273 unique_salt = ''.join([random.choice(self.SUFFIX_LETTERS)
274 for x in range(5)])
275 return (self.ssid_prefix + unique_salt + suffix)[-32:]
276
277
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700278 def hostap_configure(self, configuration, multi_interface=None):
279 """Build up a hostapd configuration file and start hostapd.
280
281 Also setup a local server if this router supports them.
282
283 @param configuration HosetapConfig object.
284 @param multi_interface bool True iff multiple interfaces allowed.
285
286 """
287 if multi_interface is None and (self.hostapd['configured'] or
288 self.station['configured']):
289 self.deconfig()
290 # Start with the default hostapd config parameters.
291 conf = self.__get_default_hostap_config()
Christopher Wiley3166e432013-08-06 09:53:12 -0700292 conf['ssid'] = (configuration.ssid or
Christopher Wiley0ff28ab2013-08-12 13:23:04 -0700293 self._build_ssid(configuration.ssid_suffix))
Christopher Wiley9b406202013-05-06 14:07:49 -0700294 if configuration.bssid:
295 conf['bssid'] = configuration.bssid
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700296 conf['channel'] = configuration.channel
297 self.hostapd['frequency'] = configuration.frequency
298 conf['hw_mode'] = configuration.hw_mode
299 if configuration.hide_ssid:
300 conf['ignore_broadcast_ssid'] = 1
301 if configuration.is_11n:
302 conf['ieee80211n'] = 1
303 conf['ht_capab'] = ''.join(configuration.n_capabilities)
304 if configuration.wmm_enabled:
305 conf['wmm_enabled'] = 1
306 if configuration.require_ht:
307 conf['require_ht'] = 1
Christopher Wiley9fa7c632013-05-01 11:58:06 -0700308 if configuration.beacon_interval:
309 conf['beacon_int'] = configuration.beacon_interval
Christopher Wileya51258e2013-05-03 13:05:06 -0700310 if configuration.dtim_period:
311 conf['dtim_period'] = configuration.dtim_period
Christopher Wileye1235b62013-05-03 15:09:34 -0700312 if configuration.frag_threshold:
313 conf['fragm_threshold'] = configuration.frag_threshold
Christopher Wileyebdc27d2013-06-28 14:35:41 -0700314 if configuration.pmf_support:
315 conf['ieee80211w'] = configuration.pmf_support
Christopher Wileyb8921c72013-06-13 09:51:47 -0700316 conf.update(configuration.get_security_hostapd_conf())
Christopher Wileya89706d2013-06-12 13:20:58 -0700317
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700318 self.start_hostapd(conf, {})
319 # Configure transmit power
320 tx_power_params = {'interface': conf['interface']}
321 # TODO(wiley) support for setting transmit power
322 self.set_txpower(tx_power_params)
323 if self.force_local_server:
324 self.start_local_server(conf['interface'])
325 self._post_start_hook({})
326 logging.info('AP configured.')
327 self.hostapd['configured'] = True
328
329
Paul Stewartc2b3de82011-03-03 14:45:31 -0800330 def hostap_config(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700331 """Configure the AP per test requirements.
Sam Leffler6969d1d2010-03-15 16:07:11 -0700332
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700333 @param params dict of site_wifitest parameters.
334
335 """
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700336 # keep parameter modifications local-only
337 orig_params = params
338 params = params.copy()
339
Paul Stewart45338d22010-10-21 10:57:02 -0700340 multi_interface = 'multi_interface' in params
341 if multi_interface:
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700342 # remove non-hostapd config item from params
Paul Stewart45338d22010-10-21 10:57:02 -0700343 params.pop('multi_interface')
Paul Stewartc2b3de82011-03-03 14:45:31 -0800344 elif self.hostapd['configured'] or self.station['configured']:
Christopher Wileyd89b5282013-04-10 15:21:26 -0700345 self.deconfig()
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700346
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700347 local_server = params.pop('local_server', False)
348
Christopher Wiley7d414cc2013-04-17 17:26:32 -0700349 conf = self.__get_default_hostap_config()
Paul Stewartc2b3de82011-03-03 14:45:31 -0800350 tx_power_params = {}
351 htcaps = set()
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700352
Paul Stewartc2b3de82011-03-03 14:45:31 -0800353 for k, v in params.iteritems():
354 if k == 'ssid':
355 conf['ssid'] = v
356 elif k == 'ssid_suffix':
Christopher Wiley0ff28ab2013-08-12 13:23:04 -0700357 conf['ssid'] = self._build_ssid(v)
Paul Stewartc2b3de82011-03-03 14:45:31 -0800358 elif k == 'channel':
359 freq = int(v)
Paul Stewart2ee7fdf2011-05-19 16:29:23 -0700360 self.hostapd['frequency'] = freq
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700361
Paul Stewartc2b3de82011-03-03 14:45:31 -0800362 # 2.4GHz
363 if freq <= 2484:
364 # Make sure hw_mode is set
365 if conf.get('hw_mode') == 'a':
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700366 conf['hw_mode'] = 'g'
Paul Stewartc2b3de82011-03-03 14:45:31 -0800367
368 # Freq = 5 * chan + 2407, except channel 14
369 if freq == 2484:
370 conf['channel'] = 14
371 else:
372 conf['channel'] = (freq - 2407) / 5
373 # 5GHz
Sam Leffler6969d1d2010-03-15 16:07:11 -0700374 else:
Paul Stewartc2b3de82011-03-03 14:45:31 -0800375 # Make sure hw_mode is set
376 conf['hw_mode'] = 'a'
377 # Freq = 5 * chan + 4000
378 if freq < 5000:
379 conf['channel'] = (freq - 4000) / 5
380 # Freq = 5 * chan + 5000
381 else:
382 conf['channel'] = (freq - 5000) / 5
Sam Leffler6969d1d2010-03-15 16:07:11 -0700383
Paul Stewartc2b3de82011-03-03 14:45:31 -0800384 elif k == 'country':
385 conf['country_code'] = v
386 elif k == 'dotd':
387 conf['ieee80211d'] = 1
388 elif k == '-dotd':
389 conf['ieee80211d'] = 0
390 elif k == 'mode':
391 if v == '11a':
392 conf['hw_mode'] = 'a'
393 elif v == '11g':
394 conf['hw_mode'] = 'g'
395 elif v == '11b':
396 conf['hw_mode'] = 'b'
397 elif v == '11n':
398 conf['ieee80211n'] = 1
399 elif k == 'bintval':
400 conf['beacon_int'] = v
401 elif k == 'dtimperiod':
402 conf['dtim_period'] = v
403 elif k == 'rtsthreshold':
404 conf['rts_threshold'] = v
405 elif k == 'fragthreshold':
406 conf['fragm_threshold'] = v
407 elif k == 'shortpreamble':
408 conf['preamble'] = 1
409 elif k == 'authmode':
410 if v == "open":
411 conf['auth_algs'] = 1
412 elif v == "shared":
413 conf['auth_algs'] = 2
414 elif k == 'hidessid':
415 conf['ignore_broadcast_ssid'] = 1
416 elif k == 'wme':
417 conf['wmm_enabled'] = 1
418 elif k == '-wme':
419 conf['wmm_enabled'] = 0
420 elif k == 'deftxkey':
421 conf['wep_default_key'] = v
422 elif k == 'ht20':
423 htcaps.add('') # NB: ensure 802.11n setup below
424 conf['wmm_enabled'] = 1
425 elif k == 'ht40':
426 htcaps.add('[HT40-]')
427 htcaps.add('[HT40+]')
428 conf['wmm_enabled'] = 1
Paul Stewartc1df8d62011-04-07 14:28:15 -0700429 elif k in ('ht40+', 'ht40-'):
430 htcaps.add('[%s]' % k.upper())
431 conf['wmm_enabled'] = 1
Paul Stewartc2b3de82011-03-03 14:45:31 -0800432 elif k == 'shortgi':
433 htcaps.add('[SHORT-GI-20]')
434 htcaps.add('[SHORT-GI-40]')
435 elif k == 'pureg':
436 pass # TODO(sleffler) need hostapd support
437 elif k == 'puren':
438 pass # TODO(sleffler) need hostapd support
439 elif k == 'protmode':
440 pass # TODO(sleffler) need hostapd support
441 elif k == 'ht':
442 htcaps.add('') # NB: ensure 802.11n setup below
443 elif k == 'htprotmode':
444 pass # TODO(sleffler) need hostapd support
445 elif k == 'rifs':
446 pass # TODO(sleffler) need hostapd support
447 elif k == 'wepmode':
448 pass # NB: meaningless for hostapd; ignore
449 elif k == '-ampdu':
450 pass # TODO(sleffler) need hostapd support
451 elif k == 'txpower':
452 tx_power_params['power'] = v
Nebojsa Sabovic60ae1462010-05-07 16:14:45 -0700453 else:
Paul Stewartc2b3de82011-03-03 14:45:31 -0800454 conf[k] = v
Nebojsa Sabovic60ae1462010-05-07 16:14:45 -0700455
Paul Stewartc2b3de82011-03-03 14:45:31 -0800456 # Aggregate ht_capab.
457 if htcaps:
458 conf['ieee80211n'] = 1
459 conf['ht_capab'] = ''.join(htcaps)
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700460
Paul Stewart548cf452012-11-27 17:46:23 -0800461 self.start_hostapd(conf, orig_params)
Paul Stewart1ae854b2011-02-08 15:10:14 -0800462
Paul Stewartc2b3de82011-03-03 14:45:31 -0800463 # Configure transmit power
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700464 tx_power_params['interface'] = conf['interface']
Paul Stewartc2b3de82011-03-03 14:45:31 -0800465 self.set_txpower(tx_power_params)
Nebojsa Sabovic138ff912010-04-06 15:47:42 -0700466
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700467 if self.force_local_server or local_server is not False:
468 self.start_local_server(conf['interface'])
Sam Leffler6969d1d2010-03-15 16:07:11 -0700469
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700470 self._post_start_hook(orig_params)
471
472 logging.info("AP configured.")
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700473 self.hostapd['configured'] = True
Sam Leffler6969d1d2010-03-15 16:07:11 -0700474
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700475
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700476 @staticmethod
477 def ip_addr(netblock, idx):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700478 """Simple IPv4 calculator.
479
480 Takes host address in "IP/bits" notation and returns netmask, broadcast
481 address as well as integer offsets into the address range.
482
483 @param netblock string host address in "IP/bits" notation.
484 @param idx string describing what to return.
485 @return string containing something you hopefully requested.
486
Paul Stewartf05d7fd2011-04-06 16:19:37 -0700487 """
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700488 addr_str,bits = netblock.split('/')
Paul Stewartf05d7fd2011-04-06 16:19:37 -0700489 addr = map(int, addr_str.split('.'))
490 mask_bits = (-1 << (32-int(bits))) & 0xffffffff
491 mask = [(mask_bits >> s) & 0xff for s in range(24, -1, -8)]
Paul Stewart5977da92011-06-01 19:14:08 -0700492 if idx == 'local':
493 return addr_str
494 elif idx == 'netmask':
Paul Stewartf05d7fd2011-04-06 16:19:37 -0700495 return '.'.join(map(str, mask))
496 elif idx == 'broadcast':
497 offset = [m ^ 0xff for m in mask]
498 else:
499 offset = [(idx >> s) & 0xff for s in range(24, -1, -8)]
500 return '.'.join(map(str, [(a & m) + o
501 for a, m, o in zip(addr, mask, offset)]))
502
503
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700504 def ibss_configure(self, config):
505 """Configure a station based AP in IBSS mode.
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700506
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700507 Extract relevant configuration objects from |config| despite not
508 actually being a hostap managed endpoint.
509
510 @param config HostapConfig object.
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700511
512 """
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700513 if self.station['configured'] or self.hostapd['configured']:
Christopher Wileyd89b5282013-04-10 15:21:26 -0700514 self.deconfig()
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700515 interface = self._get_wlanif(config.frequency, self.phytype,
516 config.hw_mode)
Christopher Wiley3166e432013-08-06 09:53:12 -0700517 self.station['conf']['ssid'] = (config.ssid or
Christopher Wiley0ff28ab2013-08-12 13:23:04 -0700518 self._build_ssid(config.ssid_suffix))
Paul Stewartc2b3de82011-03-03 14:45:31 -0800519 # Connect the station
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700520 self.router.run('%s link set %s up' % (self.cmd_ip, interface))
Christopher Wiley3166e432013-08-06 09:53:12 -0700521 self.router.run('%s dev %s ibss join %s %d' % (
522 self.cmd_iw, interface, self.station['conf']['ssid'],
523 config.frequency))
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700524 # Always start a local server.
525 self.start_local_server(interface)
526 # Remember that this interface is up.
Paul Stewartc2b3de82011-03-03 14:45:31 -0800527 self.station['configured'] = True
528 self.station['interface'] = interface
529
530
Paul Stewart2bd823b2012-11-21 15:03:37 -0800531 def local_server_address(self, index):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700532 """Get the local server address for an interface.
533
534 When we multiple local servers, we give them static IP addresses
535 like 192.158.*.254.
536
537 @param index int describing which local server this is for.
538
539 """
Paul Stewart2bd823b2012-11-21 15:03:37 -0800540 return '%d.%d.%d.%d' % (192, 168, index, 254)
541
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700542
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700543 def start_local_server(self, interface):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700544 """Start a local server on an interface.
545
546 @param interface string (e.g. wlan0)
547
548 """
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700549 logging.info("Starting up local server...")
550
551 if len(self.local_servers) >= 256:
552 raise error.TestFail('Exhausted available local servers')
553
Paul Stewart2bd823b2012-11-21 15:03:37 -0800554 netblock = '%s/24' % self.local_server_address(len(self.local_servers))
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700555
556 params = {}
557 params['netblock'] = netblock
558 params['subnet'] = self.ip_addr(netblock, 0)
559 params['netmask'] = self.ip_addr(netblock, 'netmask')
560 params['dhcp_range'] = ' '.join(
561 (self.ip_addr(netblock, self.dhcp_low),
562 self.ip_addr(netblock, self.dhcp_high)))
mukesh agrawal05c455a2011-10-12 13:40:27 -0700563 params['interface'] = interface
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700564
565 params['ip_params'] = ("%s broadcast %s dev %s" %
566 (netblock,
567 self.ip_addr(netblock, 'broadcast'),
568 interface))
569 self.local_servers.append(params)
570
571 self.router.run("%s addr flush %s" %
572 (self.cmd_ip, interface))
573 self.router.run("%s addr add %s" %
574 (self.cmd_ip, params['ip_params']))
575 self.router.run("%s link set %s up" %
576 (self.cmd_ip, interface))
Paul Stewart548cf452012-11-27 17:46:23 -0800577 self.start_dhcp_server(interface)
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700578
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700579
Paul Stewart548cf452012-11-27 17:46:23 -0800580 def start_dhcp_server(self, interface):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700581 """Start a dhcp server on an interface.
582
583 @param interface string (e.g. wlan0)
584
585 """
Paul Stewart326badb2012-12-18 14:18:54 -0800586 conf_file = self.dhcpd_conf % interface
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700587 dhcp_conf = '\n'.join(map(
588 lambda server_conf: \
589 "subnet %(subnet)s netmask %(netmask)s {\n" \
590 " range %(dhcp_range)s;\n" \
591 "}" % server_conf,
592 self.local_servers))
593 self.router.run("cat <<EOF >%s\n%s\nEOF\n" %
Paul Stewart326badb2012-12-18 14:18:54 -0800594 (conf_file,
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700595 '\n'.join(('ddns-update-style none;', dhcp_conf))))
596 self.router.run("touch %s" % self.dhcpd_leases)
597
598 self.router.run("pkill dhcpd >/dev/null 2>&1", ignore_status=True)
599 self.router.run("%s -q -cf %s -lf %s" %
Paul Stewart326badb2012-12-18 14:18:54 -0800600 (self.cmd_dhcpd, conf_file, self.dhcpd_leases))
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700601
602
Paul Stewart326badb2012-12-18 14:18:54 -0800603 def stop_dhcp_server(self, instance=None):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700604 """Stop a dhcp server on the router.
605
606 @param instance string instance to kill.
607
608 """
Paul Stewart326badb2012-12-18 14:18:54 -0800609 self._kill_process_instance('dhcpd', instance, 0)
610
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700611
Paul Stewart548cf452012-11-27 17:46:23 -0800612 def stop_dhcp_servers(self):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700613 """Stop all dhcp servers on the router."""
Paul Stewart326badb2012-12-18 14:18:54 -0800614 self.stop_dhcp_server(None)
Paul Stewart548cf452012-11-27 17:46:23 -0800615
616
Paul Stewartc2b3de82011-03-03 14:45:31 -0800617 def config(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700618 """Configure an AP based on site_wifitest parameters.
619
620 @param params dict of site_wifitest parameters.
621
622 """
Paul Stewartc2b3de82011-03-03 14:45:31 -0800623 if self.apmode:
624 self.hostap_config(params)
625 else:
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700626 config = hostap_config.HostapConfig(
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700627 frequency=int(params.get('channel', None)))
628 self.ibss_configure(config)
Paul Stewartc2b3de82011-03-03 14:45:31 -0800629
630
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700631 def get_wifi_ip(self, ap_num):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700632 """Return IP address on the WiFi subnet of a local server on the router.
633
634 If no local servers are configured (e.g. for an RSPro), a TestFail will
635 be raised.
636
637 @param ap_num int which local server to get an address from.
638
639 """
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700640 if self.local_servers:
641 return self.ip_addr(self.local_servers[ap_num]['netblock'],
642 'local')
643 else:
644 raise error.TestFail("No IP address assigned")
Paul Stewart5977da92011-06-01 19:14:08 -0700645
646
Paul Stewart17350be2012-12-14 13:34:54 -0800647 def get_hostapd_mac(self, ap_num):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700648 """Return the MAC address of an AP in the test.
649
650 @param ap_num int index of local server to read the MAC address from.
651 @return string MAC address like 00:11:22:33:44:55.
652
653 """
Paul Stewart17350be2012-12-14 13:34:54 -0800654 instance = self.hostapd_instances[ap_num]
655 interface = instance['interface']
656 result = self.router.run('%s addr show %s' % (self.cmd_ip, interface))
657 # Example response:
658 # 1: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 UP qlen 1000
659 # link/ether 99:88:77:66:55:44 brd ff:ff:ff:ff:ff:ff
660 # inet 10.0.0.1/8 brd 10.255.255.255 scope global eth0
661 # inet6 fe80::6a7f:74ff:fe66:5544/64 scope link
662 # we want the MAC address after the "link/ether" above.
663 parts = result.stdout.split(' ')
664 return parts[parts.index('link/ether') + 1]
665
666
Christopher Wileyd89b5282013-04-10 15:21:26 -0700667 def deconfig(self, params={}):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700668 """De-configure the AP (will also bring wlan down).
Sam Leffler6969d1d2010-03-15 16:07:11 -0700669
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700670 @param params dict of parameters from site_wifitest.
671
672 """
Paul Stewartc2b3de82011-03-03 14:45:31 -0800673 if not self.hostapd['configured'] and not self.station['configured']:
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700674 return
Sam Leffler6969d1d2010-03-15 16:07:11 -0700675
Paul Stewartc2b3de82011-03-03 14:45:31 -0800676 if self.hostapd['configured']:
Paul Stewart326badb2012-12-18 14:18:54 -0800677 local_servers = []
Paul Stewart21737812012-12-06 11:03:32 -0800678 if 'instance' in params:
679 instances = [ self.hostapd_instances.pop(params['instance']) ]
Paul Stewart326badb2012-12-18 14:18:54 -0800680 for server in self.local_servers:
681 if server['interface'] == instances[0]['interface']:
682 local_servers = [server]
683 self.local_servers.remove(server)
684 break
Paul Stewart21737812012-12-06 11:03:32 -0800685 else:
686 instances = self.hostapd_instances
687 self.hostapd_instances = []
Paul Stewart326badb2012-12-18 14:18:54 -0800688 local_servers = self.local_servers
689 self.local_servers = []
Paul Stewart64cc4292011-06-01 10:59:36 -0700690
Paul Stewart21737812012-12-06 11:03:32 -0800691 for instance in instances:
692 if 'silent' in params:
693 # Deconfigure without notifying DUT. Remove the interface
694 # hostapd uses to send beacon and DEAUTH packets.
695 self._remove_interface(instance['interface'], True)
696
Paul Stewart326badb2012-12-18 14:18:54 -0800697 self.kill_hostapd_instance(instance['conf_file'])
Paul Stewart548cf452012-11-27 17:46:23 -0800698 self.router.get_file(instance['log_file'],
699 'debug/hostapd_router_%d_%s.log' %
700 (self.hostapd['log_count'],
701 instance['interface']))
702 self._release_wlanif(instance['interface'])
703# self.router.run("rm -f %(log_file)s %(conf_file)s" % instance)
Paul Stewartf854d2e2011-05-04 13:19:18 -0700704 self.hostapd['log_count'] += 1
Paul Stewartc2b3de82011-03-03 14:45:31 -0800705 if self.station['configured']:
Christopher Wiley05262d62013-04-17 17:53:59 -0700706 local_servers = self.local_servers
707 self.local_servers = []
Paul Stewartc2b3de82011-03-03 14:45:31 -0800708 if self.station['type'] == 'ibss':
709 self.router.run("%s dev %s ibss leave" %
710 (self.cmd_iw, self.station['interface']))
711 else:
712 self.router.run("%s dev %s disconnect" %
713 (self.cmd_iw, self.station['interface']))
714 self.router.run("%s link set %s down" % (self.cmd_ip,
715 self.station['interface']))
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700716
Paul Stewart326badb2012-12-18 14:18:54 -0800717 for server in local_servers:
718 self.stop_dhcp_server(server['interface'])
719 self.router.run("%s addr del %s" %
720 (self.cmd_ip, server['ip_params']),
721 ignore_status=True)
Nebojsa Sabovic4cc2ce92010-04-21 15:08:01 -0700722
723 self.hostapd['configured'] = False
Paul Stewartc2b3de82011-03-03 14:45:31 -0800724 self.station['configured'] = False
Paul Stewart7cb1f062010-06-10 15:46:20 -0700725
726
Paul Stewart17350be2012-12-14 13:34:54 -0800727 def verify_pmksa_auth(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700728 """Verify that the PMKSA auth was cached on a hostapd instance.
729
730 @param params dict with optional key 'instance' (defaults to 0).
731
732 """
Paul Stewart17350be2012-12-14 13:34:54 -0800733 instance_num = params.get('instance', 0)
734 instance = self.hostapd_instances[instance_num]
735 pmksa_match = 'PMK from PMKSA cache - skip IEEE 802.1X.EAP'
736 self.router.run('grep -q "%s" %s' % (pmksa_match, instance['log_file']))
737
738
Paul Stewart7cb1f062010-06-10 15:46:20 -0700739 def get_ssid(self):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700740 """@return string ssid for the network stemming from this router."""
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700741 if self.hostapd['configured']:
742 return self.hostapd['conf']['ssid']
743
Christopher Wiley3166e432013-08-06 09:53:12 -0700744 if not 'ssid' in self.station['conf']:
745 raise error.TestFail('Requested ssid of an unconfigured AP.')
746
Christopher Wiley1febd6a2013-06-03 13:59:48 -0700747 return self.station['conf']['ssid']
Paul Stewart98022e22010-10-22 10:33:14 -0700748
749
750 def set_txpower(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700751 """Set the transmission power for an interface.
752
753 Assumes that we want to refer to the first hostapd instance unless
754 'interface' is defined in params. Sets the transmission power to
755 'auto' if 'power' is not defined in params.
756
757 @param params dict of parameters as described above.
758
759 """
Paul Stewart548cf452012-11-27 17:46:23 -0800760 interface = params.get('interface',
761 self.hostapd_instances[0]['interface'])
762 power = params.get('power', 'auto')
Paul Stewart98022e22010-10-22 10:33:14 -0700763 self.router.run("%s dev %s set txpower %s" %
Paul Stewart548cf452012-11-27 17:46:23 -0800764 (self.cmd_iw, interface, power))
Paul Stewartaa52e8c2011-05-24 08:46:23 -0700765
766
767 def deauth(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700768 """Deauthenticates a client described in params.
769
770 @param params dict containing a key 'client'.
771
772 """
Paul Stewartaa52e8c2011-05-24 08:46:23 -0700773 self.router.run('%s -p%s deauthenticate %s' %
774 (self.cmd_hostapd_cli,
775 self.hostapd['conf']['ctrl_interface'],
776 params['client']))
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700777
778
Paul Stewart51b0f382013-06-12 09:03:02 -0700779 def send_management_frame(self, frame_type, instance=0):
780 """Injects a management frame into an active hostapd session.
781
782 @param frame_type string the type of frame to send.
783 @param instance int indicating which hostapd instance to inject into.
784
785 """
786 hostap_interface = self.hostapd_instances[instance]['interface']
787 interface = self._get_wlanif(0, 'monitor', same_phy_as=hostap_interface)
788 self.router.run("%s link set %s up" % (self.cmd_ip, interface))
789 self.router.run('%s %s %s' %
790 (self.cmd_send_management_frame, interface, frame_type))
791 self._release_wlanif(interface)
792
793
Paul Stewart25536942013-08-15 17:33:42 -0700794 def detect_client_deauth(self, client_mac, instance=0):
795 """Detects whether hostapd has logged a deauthentication from
796 |client_mac|.
797
798 @param client_mac string the MAC address of the client to detect.
799 @param instance int indicating which hostapd instance to query.
800
801 """
802 interface = self.hostapd_instances[instance]['interface']
803 deauth_msg = "%s: deauthentication: STA=%s" % (interface, client_mac)
804 log_file = self.hostapd_instances[instance]['log_file']
805 result = self.router.run("grep -qi '%s' %s" % (deauth_msg, log_file),
806 ignore_status=True)
807 return result.exit_status == 0
808
809
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700810 def _pre_config_hook(self, config):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700811 """Hook for subclasses.
812
813 Run after gathering configuration parameters,
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700814 but before writing parameters to config file.
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700815
816 @param config dict containing hostapd config parameters.
817
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700818 """
819 pass
820
821
822 def _pre_start_hook(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700823 """Hook for subclasses.
824
825 Run after generating hostapd config file, but before starting hostapd.
826
827 @param params dict parameters from site_wifitest.
828
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700829 """
830 pass
831
832
833 def _post_start_hook(self, params):
Christopher Wileyf99e6cc2013-04-19 10:12:43 -0700834 """Hook for subclasses run after starting hostapd.
835
836 @param params dict parameters from site_wifitest.
837
838 """
mukesh agrawalfe0e85b2011-08-09 14:24:15 -0700839 pass