]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/wpasupplicant.py
tests: Clear ignore_old_scan_res explicitly in test cases where it is used
[thirdparty/hostap.git] / tests / hwsim / wpasupplicant.py
1 # Python class for controlling wpa_supplicant
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import os
8 import time
9 import logging
10 import binascii
11 import re
12 import struct
13 import subprocess
14 import wpaspy
15
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
18
19 class WpaSupplicant:
20 def __init__(self, ifname=None, global_iface=None):
21 self.group_ifname = None
22 self.gctrl_mon = None
23 if ifname:
24 self.set_ifname(ifname)
25 else:
26 self.ifname = None
27
28 self.global_iface = global_iface
29 if global_iface:
30 self.global_ctrl = wpaspy.Ctrl(global_iface)
31 self.global_mon = wpaspy.Ctrl(global_iface)
32 self.global_mon.attach()
33 else:
34 self.global_mon = None
35
36 def close_ctrl(self):
37 if self.global_mon:
38 self.global_mon.detach()
39 self.global_mon = None
40 self.global_ctrl = None
41 self.remove_ifname()
42
43 def set_ifname(self, ifname):
44 self.ifname = ifname
45 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
46 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
47 self.mon.attach()
48
49 def remove_ifname(self):
50 if self.ifname:
51 self.mon.detach()
52 self.mon = None
53 self.ctrl = None
54 self.ifname = None
55
56 def interface_add(self, ifname, config="", driver="nl80211",
57 drv_params=None, br_ifname=None, create=False,
58 set_ifname=True, all_params=False, if_type=None):
59 try:
60 groups = subprocess.check_output(["id"])
61 group = "admin" if "(admin)" in groups else "adm"
62 except Exception, e:
63 group = "admin"
64 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
65 if drv_params:
66 cmd = cmd + '\t' + drv_params
67 if br_ifname:
68 if not drv_params:
69 cmd += '\t'
70 cmd += '\t' + br_ifname
71 if create:
72 if not br_ifname:
73 cmd += '\t'
74 if not drv_params:
75 cmd += '\t'
76 cmd += '\tcreate'
77 if if_type:
78 cmd += '\t' + if_type
79 if all_params and not create:
80 if not br_ifname:
81 cmd += '\t'
82 if not drv_params:
83 cmd += '\t'
84 cmd += '\t'
85 if "FAIL" in self.global_request(cmd):
86 raise Exception("Failed to add a dynamic wpa_supplicant interface")
87 if not create and set_ifname:
88 self.set_ifname(ifname)
89
90 def interface_remove(self, ifname):
91 self.remove_ifname()
92 self.global_request("INTERFACE_REMOVE " + ifname)
93
94 def request(self, cmd, timeout=10):
95 logger.debug(self.ifname + ": CTRL: " + cmd)
96 return self.ctrl.request(cmd, timeout=timeout)
97
98 def global_request(self, cmd):
99 if self.global_iface is None:
100 self.request(cmd)
101 else:
102 ifname = self.ifname or self.global_iface
103 logger.debug(ifname + ": CTRL(global): " + cmd)
104 return self.global_ctrl.request(cmd)
105
106 def group_request(self, cmd):
107 if self.group_ifname and self.group_ifname != self.ifname:
108 logger.debug(self.group_ifname + ": CTRL: " + cmd)
109 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
110 return gctrl.request(cmd)
111 return self.request(cmd)
112
113 def ping(self):
114 return "PONG" in self.request("PING")
115
116 def global_ping(self):
117 return "PONG" in self.global_request("PING")
118
119 def reset(self):
120 self.dump_monitor()
121 res = self.request("FLUSH")
122 if not "OK" in res:
123 logger.info("FLUSH to " + self.ifname + " failed: " + res)
124 self.global_request("REMOVE_NETWORK all")
125 self.global_request("SET p2p_no_group_iface 1")
126 self.global_request("P2P_FLUSH")
127 if self.gctrl_mon:
128 try:
129 self.gctrl_mon.detach()
130 except:
131 pass
132 self.gctrl_mon = None
133 self.group_ifname = None
134 self.dump_monitor()
135
136 iter = 0
137 while iter < 60:
138 state1 = self.get_driver_status_field("scan_state")
139 p2pdev = "p2p-dev-" + self.ifname
140 state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
141 states = str(state1) + " " + str(state2)
142 if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
143 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
144 time.sleep(1)
145 else:
146 break
147 iter = iter + 1
148 if iter == 60:
149 logger.error(self.ifname + ": Driver scan state did not clear")
150 print "Trying to clear cfg80211/mac80211 scan state"
151 try:
152 cmd = ["ifconfig", self.ifname, "down"]
153 subprocess.call(cmd)
154 except subprocess.CalledProcessError, e:
155 logger.info("ifconfig failed: " + str(e.returncode))
156 logger.info(e.output)
157 try:
158 cmd = ["ifconfig", self.ifname, "up"]
159 subprocess.call(cmd)
160 except subprocess.CalledProcessError, e:
161 logger.info("ifconfig failed: " + str(e.returncode))
162 logger.info(e.output)
163 if iter > 0:
164 # The ongoing scan could have discovered BSSes or P2P peers
165 logger.info("Run FLUSH again since scan was in progress")
166 self.request("FLUSH")
167 self.dump_monitor()
168
169 if not self.ping():
170 logger.info("No PING response from " + self.ifname + " after reset")
171
172 def add_network(self):
173 id = self.request("ADD_NETWORK")
174 if "FAIL" in id:
175 raise Exception("ADD_NETWORK failed")
176 return int(id)
177
178 def remove_network(self, id):
179 id = self.request("REMOVE_NETWORK " + str(id))
180 if "FAIL" in id:
181 raise Exception("REMOVE_NETWORK failed")
182 return None
183
184 def get_network(self, id, field):
185 res = self.request("GET_NETWORK " + str(id) + " " + field)
186 if res == "FAIL\n":
187 return None
188 return res
189
190 def set_network(self, id, field, value):
191 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
192 if "FAIL" in res:
193 raise Exception("SET_NETWORK failed")
194 return None
195
196 def set_network_quoted(self, id, field, value):
197 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
198 if "FAIL" in res:
199 raise Exception("SET_NETWORK failed")
200 return None
201
202 def list_networks(self, p2p=False):
203 if p2p:
204 res = self.global_request("LIST_NETWORKS")
205 else:
206 res = self.request("LIST_NETWORKS")
207 lines = res.splitlines()
208 networks = []
209 for l in lines:
210 if "network id" in l:
211 continue
212 [id,ssid,bssid,flags] = l.split('\t')
213 network = {}
214 network['id'] = id
215 network['ssid'] = ssid
216 network['bssid'] = bssid
217 network['flags'] = flags
218 networks.append(network)
219 return networks
220
221 def hs20_enable(self, auto_interworking=False):
222 self.request("SET interworking 1")
223 self.request("SET hs20 1")
224 if auto_interworking:
225 self.request("SET auto_interworking 1")
226 else:
227 self.request("SET auto_interworking 0")
228
229 def interworking_add_network(self, bssid):
230 id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
231 if "FAIL" in id or "OK" in id:
232 raise Exception("INTERWORKING_ADD_NETWORK failed")
233 return int(id)
234
235 def add_cred(self):
236 id = self.request("ADD_CRED")
237 if "FAIL" in id:
238 raise Exception("ADD_CRED failed")
239 return int(id)
240
241 def remove_cred(self, id):
242 id = self.request("REMOVE_CRED " + str(id))
243 if "FAIL" in id:
244 raise Exception("REMOVE_CRED failed")
245 return None
246
247 def set_cred(self, id, field, value):
248 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
249 if "FAIL" in res:
250 raise Exception("SET_CRED failed")
251 return None
252
253 def set_cred_quoted(self, id, field, value):
254 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
255 if "FAIL" in res:
256 raise Exception("SET_CRED failed")
257 return None
258
259 def get_cred(self, id, field):
260 return self.request("GET_CRED " + str(id) + " " + field)
261
262 def add_cred_values(self, params):
263 id = self.add_cred()
264
265 quoted = [ "realm", "username", "password", "domain", "imsi",
266 "excluded_ssid", "milenage", "ca_cert", "client_cert",
267 "private_key", "domain_suffix_match", "provisioning_sp",
268 "roaming_partner", "phase1", "phase2" ]
269 for field in quoted:
270 if field in params:
271 self.set_cred_quoted(id, field, params[field])
272
273 not_quoted = [ "eap", "roaming_consortium", "priority",
274 "required_roaming_consortium", "sp_priority",
275 "max_bss_load", "update_identifier", "req_conn_capab",
276 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
277 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
278 for field in not_quoted:
279 if field in params:
280 self.set_cred(id, field, params[field])
281
282 return id;
283
284 def select_network(self, id, freq=None):
285 if freq:
286 extra = " freq=" + str(freq)
287 else:
288 extra = ""
289 id = self.request("SELECT_NETWORK " + str(id) + extra)
290 if "FAIL" in id:
291 raise Exception("SELECT_NETWORK failed")
292 return None
293
294 def mesh_group_add(self, id):
295 id = self.request("MESH_GROUP_ADD " + str(id))
296 if "FAIL" in id:
297 raise Exception("MESH_GROUP_ADD failed")
298 return None
299
300 def mesh_group_remove(self):
301 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
302 if "FAIL" in id:
303 raise Exception("MESH_GROUP_REMOVE failed")
304 return None
305
306 def connect_network(self, id, timeout=10):
307 self.dump_monitor()
308 self.select_network(id)
309 self.wait_connected(timeout=timeout)
310 self.dump_monitor()
311
312 def get_status(self, extra=None):
313 if extra:
314 extra = "-" + extra
315 else:
316 extra = ""
317 res = self.request("STATUS" + extra)
318 lines = res.splitlines()
319 vals = dict()
320 for l in lines:
321 try:
322 [name,value] = l.split('=', 1)
323 vals[name] = value
324 except ValueError, e:
325 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
326 return vals
327
328 def get_status_field(self, field, extra=None):
329 vals = self.get_status(extra)
330 if field in vals:
331 return vals[field]
332 return None
333
334 def get_group_status(self, extra=None):
335 if extra:
336 extra = "-" + extra
337 else:
338 extra = ""
339 res = self.group_request("STATUS" + extra)
340 lines = res.splitlines()
341 vals = dict()
342 for l in lines:
343 try:
344 [name,value] = l.split('=', 1)
345 except ValueError:
346 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
347 continue
348 vals[name] = value
349 return vals
350
351 def get_group_status_field(self, field, extra=None):
352 vals = self.get_group_status(extra)
353 if field in vals:
354 return vals[field]
355 return None
356
357 def get_driver_status(self, ifname=None):
358 if ifname is None:
359 res = self.request("STATUS-DRIVER")
360 else:
361 res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
362 if res.startswith("FAIL"):
363 return dict()
364 lines = res.splitlines()
365 vals = dict()
366 for l in lines:
367 try:
368 [name,value] = l.split('=', 1)
369 except ValueError:
370 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
371 continue
372 vals[name] = value
373 return vals
374
375 def get_driver_status_field(self, field, ifname=None):
376 vals = self.get_driver_status(ifname)
377 if field in vals:
378 return vals[field]
379 return None
380
381 def get_mcc(self):
382 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
383 return 1 if mcc < 2 else mcc
384
385 def get_mib(self):
386 res = self.request("MIB")
387 lines = res.splitlines()
388 vals = dict()
389 for l in lines:
390 try:
391 [name,value] = l.split('=', 1)
392 vals[name] = value
393 except ValueError, e:
394 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
395 return vals
396
397 def p2p_dev_addr(self):
398 return self.get_status_field("p2p_device_address")
399
400 def p2p_interface_addr(self):
401 return self.get_group_status_field("address")
402
403 def own_addr(self):
404 try:
405 res = self.p2p_interface_addr()
406 except:
407 res = self.p2p_dev_addr()
408 return res
409
410 def p2p_listen(self):
411 return self.global_request("P2P_LISTEN")
412
413 def p2p_ext_listen(self, period, interval):
414 return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
415
416 def p2p_cancel_ext_listen(self):
417 return self.global_request("P2P_EXT_LISTEN")
418
419 def p2p_find(self, social=False, progressive=False, dev_id=None,
420 dev_type=None, delay=None, freq=None):
421 cmd = "P2P_FIND"
422 if social:
423 cmd = cmd + " type=social"
424 elif progressive:
425 cmd = cmd + " type=progressive"
426 if dev_id:
427 cmd = cmd + " dev_id=" + dev_id
428 if dev_type:
429 cmd = cmd + " dev_type=" + dev_type
430 if delay:
431 cmd = cmd + " delay=" + str(delay)
432 if freq:
433 cmd = cmd + " freq=" + str(freq)
434 return self.global_request(cmd)
435
436 def p2p_stop_find(self):
437 return self.global_request("P2P_STOP_FIND")
438
439 def wps_read_pin(self):
440 self.pin = self.request("WPS_PIN get").rstrip("\n")
441 if "FAIL" in self.pin:
442 raise Exception("Could not generate PIN")
443 return self.pin
444
445 def peer_known(self, peer, full=True):
446 res = self.global_request("P2P_PEER " + peer)
447 if peer.lower() not in res.lower():
448 return False
449 if not full:
450 return True
451 return "[PROBE_REQ_ONLY]" not in res
452
453 def discover_peer(self, peer, full=True, timeout=15, social=True,
454 force_find=False, freq=None):
455 logger.info(self.ifname + ": Trying to discover peer " + peer)
456 if not force_find and self.peer_known(peer, full):
457 return True
458 self.p2p_find(social, freq=freq)
459 count = 0
460 while count < timeout * 4:
461 time.sleep(0.25)
462 count = count + 1
463 if self.peer_known(peer, full):
464 return True
465 return False
466
467 def get_peer(self, peer):
468 res = self.global_request("P2P_PEER " + peer)
469 if peer.lower() not in res.lower():
470 raise Exception("Peer information not available")
471 lines = res.splitlines()
472 vals = dict()
473 for l in lines:
474 if '=' in l:
475 [name,value] = l.split('=', 1)
476 vals[name] = value
477 return vals
478
479 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
480 if expect_failure:
481 if "P2P-GROUP-STARTED" in ev:
482 raise Exception("Group formation succeeded when expecting failure")
483 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
484 s = re.split(exp, ev)
485 if len(s) < 3:
486 return None
487 res = {}
488 res['result'] = 'go-neg-failed'
489 res['status'] = int(s[2])
490 return res
491
492 if "P2P-GROUP-STARTED" not in ev:
493 raise Exception("No P2P-GROUP-STARTED event seen")
494
495 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*) ip_addr=([0-9.]*) ip_mask=([0-9.]*) go_ip_addr=([0-9.]*)'
496 s = re.split(exp, ev)
497 if len(s) < 11:
498 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
499 s = re.split(exp, ev)
500 if len(s) < 8:
501 raise Exception("Could not parse P2P-GROUP-STARTED")
502 res = {}
503 res['result'] = 'success'
504 res['ifname'] = s[2]
505 self.group_ifname = s[2]
506 try:
507 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
508 self.gctrl_mon.attach()
509 except:
510 logger.debug("Could not open monitor socket for group interface")
511 self.gctrl_mon = None
512 res['role'] = s[3]
513 res['ssid'] = s[4]
514 res['freq'] = s[5]
515 if "[PERSISTENT]" in ev:
516 res['persistent'] = True
517 else:
518 res['persistent'] = False
519 p = re.match(r'psk=([0-9a-f]*)', s[6])
520 if p:
521 res['psk'] = p.group(1)
522 p = re.match(r'passphrase="(.*)"', s[6])
523 if p:
524 res['passphrase'] = p.group(1)
525 res['go_dev_addr'] = s[7]
526
527 if len(s) > 8 and len(s[8]) > 0:
528 res['ip_addr'] = s[8]
529 if len(s) > 9:
530 res['ip_mask'] = s[9]
531 if len(s) > 10:
532 res['go_ip_addr'] = s[10]
533
534 if go_neg_res:
535 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
536 s = re.split(exp, go_neg_res)
537 if len(s) < 4:
538 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
539 res['go_neg_role'] = s[2]
540 res['go_neg_freq'] = s[3]
541
542 return res
543
544 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
545 persistent=False, freq=None, freq2=None,
546 max_oper_chwidth=None, ht40=False, vht=False):
547 if not self.discover_peer(peer):
548 raise Exception("Peer " + peer + " not found")
549 self.dump_monitor()
550 if pin:
551 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
552 else:
553 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
554 if go_intent:
555 cmd = cmd + ' go_intent=' + str(go_intent)
556 if freq:
557 cmd = cmd + ' freq=' + str(freq)
558 if freq2:
559 cmd = cmd + ' freq2=' + str(freq2)
560 if max_oper_chwidth:
561 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
562 if ht40:
563 cmd = cmd + ' ht40'
564 if vht:
565 cmd = cmd + ' vht'
566 if persistent:
567 cmd = cmd + " persistent"
568 if "OK" in self.global_request(cmd):
569 return None
570 raise Exception("P2P_CONNECT (auth) failed")
571
572 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
573 go_neg_res = None
574 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
575 "P2P-GO-NEG-FAILURE"], timeout);
576 if ev is None:
577 if expect_failure:
578 return None
579 raise Exception("Group formation timed out")
580 if "P2P-GO-NEG-SUCCESS" in ev:
581 go_neg_res = ev
582 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
583 if ev is None:
584 if expect_failure:
585 return None
586 raise Exception("Group formation timed out")
587 self.dump_monitor()
588 return self.group_form_result(ev, expect_failure, go_neg_res)
589
590 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
591 expect_failure=False, persistent=False,
592 persistent_id=None, freq=None, provdisc=False,
593 wait_group=True, freq2=None, max_oper_chwidth=None,
594 ht40=False, vht=False):
595 if not self.discover_peer(peer):
596 raise Exception("Peer " + peer + " not found")
597 self.dump_monitor()
598 if pin:
599 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
600 else:
601 cmd = "P2P_CONNECT " + peer + " " + method
602 if go_intent:
603 cmd = cmd + ' go_intent=' + str(go_intent)
604 if freq:
605 cmd = cmd + ' freq=' + str(freq)
606 if freq2:
607 cmd = cmd + ' freq2=' + str(freq2)
608 if max_oper_chwidth:
609 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
610 if ht40:
611 cmd = cmd + ' ht40'
612 if vht:
613 cmd = cmd + ' vht'
614 if persistent:
615 cmd = cmd + " persistent"
616 elif persistent_id:
617 cmd = cmd + " persistent=" + persistent_id
618 if provdisc:
619 cmd = cmd + " provdisc"
620 if "OK" in self.global_request(cmd):
621 if timeout == 0:
622 self.dump_monitor()
623 return None
624 go_neg_res = None
625 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
626 "P2P-GO-NEG-FAILURE"], timeout)
627 if ev is None:
628 if expect_failure:
629 return None
630 raise Exception("Group formation timed out")
631 if "P2P-GO-NEG-SUCCESS" in ev:
632 if not wait_group:
633 return ev
634 go_neg_res = ev
635 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
636 if ev is None:
637 if expect_failure:
638 return None
639 raise Exception("Group formation timed out")
640 self.dump_monitor()
641 return self.group_form_result(ev, expect_failure, go_neg_res)
642 raise Exception("P2P_CONNECT failed")
643
644 def wait_event(self, events, timeout=10):
645 start = os.times()[4]
646 while True:
647 while self.mon.pending():
648 ev = self.mon.recv()
649 logger.debug(self.ifname + ": " + ev)
650 for event in events:
651 if event in ev:
652 return ev
653 now = os.times()[4]
654 remaining = start + timeout - now
655 if remaining <= 0:
656 break
657 if not self.mon.pending(timeout=remaining):
658 break
659 return None
660
661 def wait_global_event(self, events, timeout):
662 if self.global_iface is None:
663 self.wait_event(events, timeout)
664 else:
665 start = os.times()[4]
666 while True:
667 while self.global_mon.pending():
668 ev = self.global_mon.recv()
669 logger.debug(self.ifname + "(global): " + ev)
670 for event in events:
671 if event in ev:
672 return ev
673 now = os.times()[4]
674 remaining = start + timeout - now
675 if remaining <= 0:
676 break
677 if not self.global_mon.pending(timeout=remaining):
678 break
679 return None
680
681 def wait_group_event(self, events, timeout=10):
682 if self.group_ifname and self.group_ifname != self.ifname:
683 if self.gctrl_mon is None:
684 return None
685 start = os.times()[4]
686 while True:
687 while self.gctrl_mon.pending():
688 ev = self.gctrl_mon.recv()
689 logger.debug(self.group_ifname + ": " + ev)
690 for event in events:
691 if event in ev:
692 return ev
693 now = os.times()[4]
694 remaining = start + timeout - now
695 if remaining <= 0:
696 break
697 if not self.gctrl_mon.pending(timeout=remaining):
698 break
699 return None
700
701 return self.wait_event(events, timeout)
702
703 def wait_go_ending_session(self):
704 if self.gctrl_mon:
705 try:
706 self.gctrl_mon.detach()
707 except:
708 pass
709 self.gctrl_mon = None
710 ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
711 if ev is None:
712 raise Exception("Group removal event timed out")
713 if "reason=GO_ENDING_SESSION" not in ev:
714 raise Exception("Unexpected group removal reason")
715
716 def dump_monitor(self):
717 count_iface = 0
718 count_global = 0
719 while self.mon.pending():
720 ev = self.mon.recv()
721 logger.debug(self.ifname + ": " + ev)
722 count_iface += 1
723 while self.global_mon and self.global_mon.pending():
724 ev = self.global_mon.recv()
725 logger.debug(self.ifname + "(global): " + ev)
726 count_global += 1
727 return (count_iface, count_global)
728
729 def remove_group(self, ifname=None):
730 if self.gctrl_mon:
731 try:
732 self.gctrl_mon.detach()
733 except:
734 pass
735 self.gctrl_mon = None
736 if ifname is None:
737 ifname = self.group_ifname if self.group_ifname else self.ifname
738 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
739 raise Exception("Group could not be removed")
740 self.group_ifname = None
741
742 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
743 self.dump_monitor()
744 cmd = "P2P_GROUP_ADD"
745 if persistent is None:
746 pass
747 elif persistent is True:
748 cmd = cmd + " persistent"
749 else:
750 cmd = cmd + " persistent=" + str(persistent)
751 if freq:
752 cmd = cmd + " freq=" + str(freq)
753 if "OK" in self.global_request(cmd):
754 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
755 if ev is None:
756 raise Exception("GO start up timed out")
757 if not no_event_clear:
758 self.dump_monitor()
759 return self.group_form_result(ev)
760 raise Exception("P2P_GROUP_ADD failed")
761
762 def p2p_go_authorize_client(self, pin):
763 cmd = "WPS_PIN any " + pin
764 if "FAIL" in self.group_request(cmd):
765 raise Exception("Failed to authorize client connection on GO")
766 return None
767
768 def p2p_go_authorize_client_pbc(self):
769 cmd = "WPS_PBC"
770 if "FAIL" in self.group_request(cmd):
771 raise Exception("Failed to authorize client connection on GO")
772 return None
773
774 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
775 freq=None):
776 self.dump_monitor()
777 if not self.discover_peer(go_addr, social=social, freq=freq):
778 if social or not self.discover_peer(go_addr, social=social):
779 raise Exception("GO " + go_addr + " not found")
780 self.dump_monitor()
781 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
782 if freq:
783 cmd += " freq=" + str(freq)
784 if "OK" in self.global_request(cmd):
785 if timeout == 0:
786 self.dump_monitor()
787 return None
788 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
789 if ev is None:
790 raise Exception("Joining the group timed out")
791 self.dump_monitor()
792 return self.group_form_result(ev)
793 raise Exception("P2P_CONNECT(join) failed")
794
795 def tdls_setup(self, peer):
796 cmd = "TDLS_SETUP " + peer
797 if "FAIL" in self.group_request(cmd):
798 raise Exception("Failed to request TDLS setup")
799 return None
800
801 def tdls_teardown(self, peer):
802 cmd = "TDLS_TEARDOWN " + peer
803 if "FAIL" in self.group_request(cmd):
804 raise Exception("Failed to request TDLS teardown")
805 return None
806
807 def tdls_link_status(self, peer):
808 cmd = "TDLS_LINK_STATUS " + peer
809 ret = self.group_request(cmd)
810 if "FAIL" in ret:
811 raise Exception("Failed to request TDLS link status")
812 return ret
813
814 def tspecs(self):
815 """Return (tsid, up) tuples representing current tspecs"""
816 res = self.request("WMM_AC_STATUS")
817 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
818 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
819
820 logger.debug("tspecs: " + str(tspecs))
821 return tspecs
822
823 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
824 extra=None):
825 params = {
826 "sba": 9000,
827 "nominal_msdu_size": 1500,
828 "min_phy_rate": 6000000,
829 "mean_data_rate": 1500,
830 }
831 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
832 for (key, value) in params.iteritems():
833 cmd += " %s=%d" % (key, value)
834 if extra:
835 cmd += " " + extra
836
837 if self.request(cmd).strip() != "OK":
838 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
839
840 if expect_failure:
841 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
842 if ev is None:
843 raise Exception("ADDTS failed (time out while waiting failure)")
844 if "tsid=%d" % (tsid) not in ev:
845 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
846 return
847
848 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
849 if ev is None:
850 raise Exception("ADDTS failed (time out)")
851 if "tsid=%d" % (tsid) not in ev:
852 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
853
854 if not (tsid, up) in self.tspecs():
855 raise Exception("ADDTS failed (tsid not in tspec list)")
856
857 def del_ts(self, tsid):
858 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
859 raise Exception("DELTS failed")
860
861 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
862 if ev is None:
863 raise Exception("DELTS failed (time out)")
864 if "tsid=%d" % (tsid) not in ev:
865 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
866
867 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
868 if tspecs:
869 raise Exception("DELTS failed (still in tspec list)")
870
871 def connect(self, ssid=None, ssid2=None, **kwargs):
872 logger.info("Connect STA " + self.ifname + " to AP")
873 id = self.add_network()
874 if ssid:
875 self.set_network_quoted(id, "ssid", ssid)
876 elif ssid2:
877 self.set_network(id, "ssid", ssid2)
878
879 quoted = [ "psk", "identity", "anonymous_identity", "password",
880 "ca_cert", "client_cert", "private_key",
881 "private_key_passwd", "ca_cert2", "client_cert2",
882 "private_key2", "phase1", "phase2", "domain_suffix_match",
883 "altsubject_match", "subject_match", "pac_file", "dh_file",
884 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
885 "domain_match" ]
886 for field in quoted:
887 if field in kwargs and kwargs[field]:
888 self.set_network_quoted(id, field, kwargs[field])
889
890 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
891 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
892 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
893 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
894 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
895 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
896 "disable_ht40", "disable_sgi", "disable_ldpc",
897 "ht40_intolerant", "update_identifier", "mac_addr",
898 "erp", "bg_scan_period", "bssid_blacklist",
899 "bssid_whitelist", "mem_only_psk", "eap_workaround" ]
900 for field in not_quoted:
901 if field in kwargs and kwargs[field]:
902 self.set_network(id, field, kwargs[field])
903
904 if "raw_psk" in kwargs and kwargs['raw_psk']:
905 self.set_network(id, "psk", kwargs['raw_psk'])
906 if "password_hex" in kwargs and kwargs['password_hex']:
907 self.set_network(id, "password", kwargs['password_hex'])
908 if "peerkey" in kwargs and kwargs['peerkey']:
909 self.set_network(id, "peerkey", "1")
910 if "okc" in kwargs and kwargs['okc']:
911 self.set_network(id, "proactive_key_caching", "1")
912 if "ocsp" in kwargs and kwargs['ocsp']:
913 self.set_network(id, "ocsp", str(kwargs['ocsp']))
914 if "only_add_network" in kwargs and kwargs['only_add_network']:
915 return id
916 if "wait_connect" not in kwargs or kwargs['wait_connect']:
917 if "eap" in kwargs:
918 self.connect_network(id, timeout=20)
919 else:
920 self.connect_network(id)
921 else:
922 self.dump_monitor()
923 self.select_network(id)
924 return id
925
926 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
927 if type:
928 cmd = "SCAN TYPE=" + type
929 else:
930 cmd = "SCAN"
931 if freq:
932 cmd = cmd + " freq=" + str(freq)
933 if only_new:
934 cmd += " only_new=1"
935 if not no_wait:
936 self.dump_monitor()
937 if not "OK" in self.request(cmd):
938 raise Exception("Failed to trigger scan")
939 if no_wait:
940 return
941 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
942 if ev is None:
943 raise Exception("Scan timed out")
944
945 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
946 if not force_scan and self.get_bss(bssid) is not None:
947 return
948 for i in range(0, 10):
949 self.scan(freq=freq, type="ONLY", only_new=only_new)
950 if self.get_bss(bssid) is not None:
951 return
952 raise Exception("Could not find BSS " + bssid + " in scan")
953
954 def flush_scan_cache(self, freq=2417):
955 self.request("BSS_FLUSH 0")
956 self.scan(freq=freq, only_new=True)
957 res = self.request("SCAN_RESULTS")
958 if len(res.splitlines()) > 1:
959 self.request("BSS_FLUSH 0")
960 self.scan(freq=2422, only_new=True)
961 res = self.request("SCAN_RESULTS")
962 if len(res.splitlines()) > 1:
963 logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
964
965 def roam(self, bssid, fail_test=False):
966 self.dump_monitor()
967 if "OK" not in self.request("ROAM " + bssid):
968 raise Exception("ROAM failed")
969 if fail_test:
970 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
971 if ev is not None:
972 raise Exception("Unexpected connection")
973 self.dump_monitor()
974 return
975 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
976 self.dump_monitor()
977
978 def roam_over_ds(self, bssid, fail_test=False):
979 self.dump_monitor()
980 if "OK" not in self.request("FT_DS " + bssid):
981 raise Exception("FT_DS failed")
982 if fail_test:
983 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
984 if ev is not None:
985 raise Exception("Unexpected connection")
986 self.dump_monitor()
987 return
988 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
989 self.dump_monitor()
990
991 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
992 new_passphrase=None, no_wait=False):
993 self.dump_monitor()
994 if new_ssid:
995 self.request("WPS_REG " + bssid + " " + pin + " " +
996 new_ssid.encode("hex") + " " + key_mgmt + " " +
997 cipher + " " + new_passphrase.encode("hex"))
998 if no_wait:
999 return
1000 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
1001 else:
1002 self.request("WPS_REG " + bssid + " " + pin)
1003 if no_wait:
1004 return
1005 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
1006 if ev is None:
1007 raise Exception("WPS cred timed out")
1008 ev = self.wait_event(["WPS-FAIL"], timeout=15)
1009 if ev is None:
1010 raise Exception("WPS timed out")
1011 self.wait_connected(timeout=15)
1012
1013 def relog(self):
1014 self.global_request("RELOG")
1015
1016 def wait_completed(self, timeout=10):
1017 for i in range(0, timeout * 2):
1018 if self.get_status_field("wpa_state") == "COMPLETED":
1019 return
1020 time.sleep(0.5)
1021 raise Exception("Timeout while waiting for COMPLETED state")
1022
1023 def get_capability(self, field):
1024 res = self.request("GET_CAPABILITY " + field)
1025 if "FAIL" in res:
1026 return None
1027 return res.split(' ')
1028
1029 def get_bss(self, bssid, ifname=None):
1030 if not ifname or ifname == self.ifname:
1031 res = self.request("BSS " + bssid)
1032 elif ifname == self.group_ifname:
1033 res = self.group_request("BSS " + bssid)
1034 else:
1035 return None
1036
1037 if "FAIL" in res:
1038 return None
1039 lines = res.splitlines()
1040 vals = dict()
1041 for l in lines:
1042 [name,value] = l.split('=', 1)
1043 vals[name] = value
1044 if len(vals) == 0:
1045 return None
1046 return vals
1047
1048 def get_pmksa(self, bssid):
1049 res = self.request("PMKSA")
1050 lines = res.splitlines()
1051 for l in lines:
1052 if bssid not in l:
1053 continue
1054 vals = dict()
1055 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
1056 vals['index'] = index
1057 vals['pmkid'] = pmkid
1058 vals['expiration'] = expiration
1059 vals['opportunistic'] = opportunistic
1060 return vals
1061 return None
1062
1063 def get_sta(self, addr, info=None, next=False):
1064 cmd = "STA-NEXT " if next else "STA "
1065 if addr is None:
1066 res = self.request("STA-FIRST")
1067 elif info:
1068 res = self.request(cmd + addr + " " + info)
1069 else:
1070 res = self.request(cmd + addr)
1071 lines = res.splitlines()
1072 vals = dict()
1073 first = True
1074 for l in lines:
1075 if first:
1076 vals['addr'] = l
1077 first = False
1078 else:
1079 [name,value] = l.split('=', 1)
1080 vals[name] = value
1081 return vals
1082
1083 def mgmt_rx(self, timeout=5):
1084 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
1085 if ev is None:
1086 return None
1087 msg = {}
1088 items = ev.split(' ')
1089 field,val = items[1].split('=')
1090 if field != "freq":
1091 raise Exception("Unexpected MGMT-RX event format: " + ev)
1092 msg['freq'] = val
1093 frame = binascii.unhexlify(items[4])
1094 msg['frame'] = frame
1095
1096 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1097 msg['fc'] = hdr[0]
1098 msg['subtype'] = (hdr[0] >> 4) & 0xf
1099 hdr = hdr[1:]
1100 msg['duration'] = hdr[0]
1101 hdr = hdr[1:]
1102 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1103 hdr = hdr[6:]
1104 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1105 hdr = hdr[6:]
1106 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1107 hdr = hdr[6:]
1108 msg['seq_ctrl'] = hdr[0]
1109 msg['payload'] = frame[24:]
1110
1111 return msg
1112
1113 def wait_connected(self, timeout=10, error="Connection timed out"):
1114 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1115 if ev is None:
1116 raise Exception(error)
1117 return ev
1118
1119 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1120 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1121 if ev is None:
1122 raise Exception(error)
1123 return ev
1124
1125 def get_group_ifname(self):
1126 return self.group_ifname if self.group_ifname else self.ifname
1127
1128 def get_config(self):
1129 res = self.request("DUMP")
1130 if res.startswith("FAIL"):
1131 raise Exception("DUMP failed")
1132 lines = res.splitlines()
1133 vals = dict()
1134 for l in lines:
1135 [name,value] = l.split('=', 1)
1136 vals[name] = value
1137 return vals
1138
1139 def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
1140 method="1000", info="", status=None, cpt=None, role=None):
1141 if status is None:
1142 cmd = "P2P_ASP_PROVISION"
1143 params = "info='%s' method=%s" % (info, method)
1144 else:
1145 cmd = "P2P_ASP_PROVISION_RESP"
1146 params = "status=%d" % status
1147
1148 if role is not None:
1149 params += " role=" + role
1150 if cpt is not None:
1151 params += " cpt=" + cpt
1152
1153 if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1154 (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
1155 raise Exception("%s request failed" % cmd)