1 # Python class for controlling wpa_supplicant
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
20 def __init__(self, ifname=None, global_iface=None):
21 self.group_ifname = None
24 self.set_ifname(ifname)
28 self.global_iface = global_iface
30 self.global_ctrl = wpaspy.Ctrl(global_iface)
31 self.global_mon = wpaspy.Ctrl(global_iface)
32 self.global_mon.attach()
34 self.global_mon = None
38 self.global_mon.detach()
39 self.global_mon = None
40 self.global_ctrl = None
43 def set_ifname(self, ifname):
45 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
46 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
49 def remove_ifname(self):
56 def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
58 groups = subprocess.check_output(["id"])
59 group = "admin" if "(admin)" in groups else "adm"
62 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
64 cmd = cmd + '\t' + drv_params
65 if "FAIL" in self.global_request(cmd):
66 raise Exception("Failed to add a dynamic wpa_supplicant interface")
67 self.set_ifname(ifname)
69 def interface_remove(self, ifname):
71 self.global_request("INTERFACE_REMOVE " + ifname)
73 def request(self, cmd):
74 logger.debug(self.ifname + ": CTRL: " + cmd)
75 return self.ctrl.request(cmd)
77 def global_request(self, cmd):
78 if self.global_iface is None:
81 ifname = self.ifname or self.global_iface
82 logger.debug(ifname + ": CTRL(global): " + cmd)
83 return self.global_ctrl.request(cmd)
85 def group_request(self, cmd):
86 if self.group_ifname and self.group_ifname != self.ifname:
87 logger.debug(self.group_ifname + ": CTRL: " + cmd)
88 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
89 return gctrl.request(cmd)
90 return self.request(cmd)
93 return "PONG" in self.request("PING")
95 def global_ping(self):
96 return "PONG" in self.global_request("PING")
100 res = self.request("FLUSH")
102 logger.info("FLUSH to " + self.ifname + " failed: " + res)
103 self.request("SET p2p_add_cli_chan 0")
104 self.request("SET p2p_no_go_freq ")
105 self.request("SET p2p_pref_chan ")
106 self.request("SET p2p_no_group_iface 1")
107 self.request("SET p2p_go_intent 7")
108 self.request("SET ignore_old_scan_res 0")
111 self.gctrl_mon.detach()
114 self.gctrl_mon = None
115 self.group_ifname = None
120 state = self.get_driver_status_field("scan_state")
121 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
122 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
128 logger.error(self.ifname + ": Driver scan state did not clear")
129 print "Trying to clear cfg80211/mac80211 scan state"
131 cmd = ["sudo", "ifconfig", self.ifname, "down"]
133 except subprocess.CalledProcessError, e:
134 logger.info("ifconfig failed: " + str(e.returncode))
135 logger.info(e.output)
137 cmd = ["sudo", "ifconfig", self.ifname, "up"]
139 except subprocess.CalledProcessError, e:
140 logger.info("ifconfig failed: " + str(e.returncode))
141 logger.info(e.output)
143 # The ongoing scan could have discovered BSSes or P2P peers
144 logger.info("Run FLUSH again since scan was in progress")
145 self.request("FLUSH")
149 logger.info("No PING response from " + self.ifname + " after reset")
151 def add_network(self):
152 id = self.request("ADD_NETWORK")
154 raise Exception("ADD_NETWORK failed")
157 def remove_network(self, id):
158 id = self.request("REMOVE_NETWORK " + str(id))
160 raise Exception("REMOVE_NETWORK failed")
163 def get_network(self, id, field):
164 res = self.request("GET_NETWORK " + str(id) + " " + field)
169 def set_network(self, id, field, value):
170 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
172 raise Exception("SET_NETWORK failed")
175 def set_network_quoted(self, id, field, value):
176 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
178 raise Exception("SET_NETWORK failed")
181 def list_networks(self):
182 res = self.request("LIST_NETWORKS")
183 lines = res.splitlines()
186 if "network id" in l:
188 [id,ssid,bssid,flags] = l.split('\t')
191 network['ssid'] = ssid
192 network['bssid'] = bssid
193 network['flags'] = flags
194 networks.append(network)
197 def hs20_enable(self, auto_interworking=False):
198 self.request("SET interworking 1")
199 self.request("SET hs20 1")
200 if auto_interworking:
201 self.request("SET auto_interworking 1")
203 self.request("SET auto_interworking 0")
206 id = self.request("ADD_CRED")
208 raise Exception("ADD_CRED failed")
211 def remove_cred(self, id):
212 id = self.request("REMOVE_CRED " + str(id))
214 raise Exception("REMOVE_CRED failed")
217 def set_cred(self, id, field, value):
218 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
220 raise Exception("SET_CRED failed")
223 def set_cred_quoted(self, id, field, value):
224 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
226 raise Exception("SET_CRED failed")
229 def get_cred(self, id, field):
230 return self.request("GET_CRED " + str(id) + " " + field)
232 def add_cred_values(self, params):
235 quoted = [ "realm", "username", "password", "domain", "imsi",
236 "excluded_ssid", "milenage", "ca_cert", "client_cert",
237 "private_key", "domain_suffix_match", "provisioning_sp",
238 "roaming_partner", "phase1", "phase2" ]
241 self.set_cred_quoted(id, field, params[field])
243 not_quoted = [ "eap", "roaming_consortium", "priority",
244 "required_roaming_consortium", "sp_priority",
245 "max_bss_load", "update_identifier", "req_conn_capab",
246 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
247 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
248 for field in not_quoted:
250 self.set_cred(id, field, params[field])
254 def select_network(self, id, freq=None):
256 extra = " freq=" + freq
259 id = self.request("SELECT_NETWORK " + str(id) + extra)
261 raise Exception("SELECT_NETWORK failed")
264 def mesh_group_add(self, id):
265 id = self.request("MESH_GROUP_ADD " + str(id))
267 raise Exception("MESH_GROUP_ADD failed")
270 def mesh_group_remove(self):
271 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
273 raise Exception("MESH_GROUP_REMOVE failed")
276 def connect_network(self, id, timeout=10):
278 self.select_network(id)
279 self.wait_connected(timeout=timeout)
282 def get_status(self, extra=None):
287 res = self.request("STATUS" + extra)
288 lines = res.splitlines()
292 [name,value] = l.split('=', 1)
294 except ValueError, e:
295 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
298 def get_status_field(self, field, extra=None):
299 vals = self.get_status(extra)
304 def get_group_status(self, extra=None):
309 res = self.group_request("STATUS" + extra)
310 lines = res.splitlines()
314 [name,value] = l.split('=', 1)
316 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
321 def get_group_status_field(self, field, extra=None):
322 vals = self.get_group_status(extra)
327 def get_driver_status(self):
328 res = self.request("STATUS-DRIVER")
329 lines = res.splitlines()
333 [name,value] = l.split('=', 1)
335 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
340 def get_driver_status_field(self, field):
341 vals = self.get_driver_status()
347 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
348 return 1 if mcc < 2 else mcc
351 res = self.request("MIB")
352 lines = res.splitlines()
356 [name,value] = l.split('=', 1)
358 except ValueError, e:
359 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
362 def p2p_dev_addr(self):
363 return self.get_status_field("p2p_device_address")
365 def p2p_interface_addr(self):
366 return self.get_group_status_field("address")
370 res = self.p2p_interface_addr()
372 res = self.p2p_dev_addr()
375 def p2p_listen(self):
376 return self.global_request("P2P_LISTEN")
378 def p2p_find(self, social=False, progressive=False, dev_id=None,
379 dev_type=None, delay=None):
382 cmd = cmd + " type=social"
384 cmd = cmd + " type=progressive"
386 cmd = cmd + " dev_id=" + dev_id
388 cmd = cmd + " dev_type=" + dev_type
390 cmd = cmd + " delay=" + str(delay)
391 return self.global_request(cmd)
393 def p2p_stop_find(self):
394 return self.global_request("P2P_STOP_FIND")
396 def wps_read_pin(self):
397 self.pin = self.request("WPS_PIN get").rstrip("\n")
398 if "FAIL" in self.pin:
399 raise Exception("Could not generate PIN")
402 def peer_known(self, peer, full=True):
403 res = self.global_request("P2P_PEER " + peer)
404 if peer.lower() not in res.lower():
408 return "[PROBE_REQ_ONLY]" not in res
410 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
411 logger.info(self.ifname + ": Trying to discover peer " + peer)
412 if not force_find and self.peer_known(peer, full):
414 self.p2p_find(social)
416 while count < timeout * 4:
419 if self.peer_known(peer, full):
423 def get_peer(self, peer):
424 res = self.global_request("P2P_PEER " + peer)
425 if peer.lower() not in res.lower():
426 raise Exception("Peer information not available")
427 lines = res.splitlines()
431 [name,value] = l.split('=', 1)
435 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
437 if "P2P-GROUP-STARTED" in ev:
438 raise Exception("Group formation succeeded when expecting failure")
439 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
440 s = re.split(exp, ev)
444 res['result'] = 'go-neg-failed'
445 res['status'] = int(s[2])
448 if "P2P-GROUP-STARTED" not in ev:
449 raise Exception("No P2P-GROUP-STARTED event seen")
451 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.]*)'
452 s = re.split(exp, ev)
454 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
455 s = re.split(exp, ev)
457 raise Exception("Could not parse P2P-GROUP-STARTED")
459 res['result'] = 'success'
461 self.group_ifname = s[2]
463 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
464 self.gctrl_mon.attach()
466 logger.debug("Could not open monitor socket for group interface")
467 self.gctrl_mon = None
471 if "[PERSISTENT]" in ev:
472 res['persistent'] = True
474 res['persistent'] = False
475 p = re.match(r'psk=([0-9a-f]*)', s[6])
477 res['psk'] = p.group(1)
478 p = re.match(r'passphrase="(.*)"', s[6])
480 res['passphrase'] = p.group(1)
481 res['go_dev_addr'] = s[7]
483 if len(s) > 8 and len(s[8]) > 0:
484 res['ip_addr'] = s[8]
486 res['ip_mask'] = s[9]
488 res['go_ip_addr'] = s[10]
491 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
492 s = re.split(exp, go_neg_res)
494 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
495 res['go_neg_role'] = s[2]
496 res['go_neg_freq'] = s[3]
500 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
501 if not self.discover_peer(peer):
502 raise Exception("Peer " + peer + " not found")
504 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
506 cmd = cmd + ' go_intent=' + str(go_intent)
508 cmd = cmd + ' freq=' + str(freq)
510 cmd = cmd + " persistent"
511 if "OK" in self.global_request(cmd):
513 raise Exception("P2P_CONNECT (auth) failed")
515 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
517 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
518 "P2P-GO-NEG-FAILURE"], timeout);
522 raise Exception("Group formation timed out")
523 if "P2P-GO-NEG-SUCCESS" in ev:
525 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
529 raise Exception("Group formation timed out")
531 return self.group_form_result(ev, expect_failure, go_neg_res)
533 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, persistent_id=None, freq=None, provdisc=False, wait_group=True):
534 if not self.discover_peer(peer):
535 raise Exception("Peer " + peer + " not found")
538 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
540 cmd = "P2P_CONNECT " + peer + " " + method
542 cmd = cmd + ' go_intent=' + str(go_intent)
544 cmd = cmd + ' freq=' + str(freq)
546 cmd = cmd + " persistent"
548 cmd = cmd + " persistent=" + persistent_id
550 cmd = cmd + " provdisc"
551 if "OK" in self.global_request(cmd):
556 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
557 "P2P-GO-NEG-FAILURE"], timeout)
561 raise Exception("Group formation timed out")
562 if "P2P-GO-NEG-SUCCESS" in ev:
566 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
570 raise Exception("Group formation timed out")
572 return self.group_form_result(ev, expect_failure, go_neg_res)
573 raise Exception("P2P_CONNECT failed")
575 def wait_event(self, events, timeout=10):
576 start = os.times()[4]
578 while self.mon.pending():
580 logger.debug(self.ifname + ": " + ev)
585 remaining = start + timeout - now
588 if not self.mon.pending(timeout=remaining):
592 def wait_global_event(self, events, timeout):
593 if self.global_iface is None:
594 self.wait_event(events, timeout)
596 start = os.times()[4]
598 while self.global_mon.pending():
599 ev = self.global_mon.recv()
600 logger.debug(self.ifname + "(global): " + ev)
605 remaining = start + timeout - now
608 if not self.global_mon.pending(timeout=remaining):
612 def wait_group_event(self, events, timeout=10):
613 if self.group_ifname and self.group_ifname != self.ifname:
614 if self.gctrl_mon is None:
616 start = os.times()[4]
618 while self.gctrl_mon.pending():
619 ev = self.gctrl_mon.recv()
620 logger.debug(self.group_ifname + ": " + ev)
625 remaining = start + timeout - now
628 if not self.gctrl_mon.pending(timeout=remaining):
632 return self.wait_event(events, timeout)
634 def wait_go_ending_session(self):
637 self.gctrl_mon.detach()
640 self.gctrl_mon = None
641 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
643 raise Exception("Group removal event timed out")
644 if "reason=GO_ENDING_SESSION" not in ev:
645 raise Exception("Unexpected group removal reason")
647 def dump_monitor(self):
648 while self.mon.pending():
650 logger.debug(self.ifname + ": " + ev)
651 while self.global_mon and self.global_mon.pending():
652 ev = self.global_mon.recv()
653 logger.debug(self.ifname + "(global): " + ev)
655 def remove_group(self, ifname=None):
658 self.gctrl_mon.detach()
661 self.gctrl_mon = None
663 ifname = self.group_ifname if self.group_ifname else self.ifname
664 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
665 raise Exception("Group could not be removed")
666 self.group_ifname = None
668 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
670 cmd = "P2P_GROUP_ADD"
671 if persistent is None:
673 elif persistent is True:
674 cmd = cmd + " persistent"
676 cmd = cmd + " persistent=" + str(persistent)
678 cmd = cmd + " freq=" + str(freq)
679 if "OK" in self.global_request(cmd):
680 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
682 raise Exception("GO start up timed out")
683 if not no_event_clear:
685 return self.group_form_result(ev)
686 raise Exception("P2P_GROUP_ADD failed")
688 def p2p_go_authorize_client(self, pin):
689 cmd = "WPS_PIN any " + pin
690 if "FAIL" in self.group_request(cmd):
691 raise Exception("Failed to authorize client connection on GO")
694 def p2p_go_authorize_client_pbc(self):
696 if "FAIL" in self.group_request(cmd):
697 raise Exception("Failed to authorize client connection on GO")
700 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
703 if not self.discover_peer(go_addr, social=social):
704 if social or not self.discover_peer(go_addr, social=social):
705 raise Exception("GO " + go_addr + " not found")
707 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
709 cmd += " freq=" + str(freq)
710 if "OK" in self.global_request(cmd):
714 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
716 raise Exception("Joining the group timed out")
718 return self.group_form_result(ev)
719 raise Exception("P2P_CONNECT(join) failed")
721 def tdls_setup(self, peer):
722 cmd = "TDLS_SETUP " + peer
723 if "FAIL" in self.group_request(cmd):
724 raise Exception("Failed to request TDLS setup")
727 def tdls_teardown(self, peer):
728 cmd = "TDLS_TEARDOWN " + peer
729 if "FAIL" in self.group_request(cmd):
730 raise Exception("Failed to request TDLS teardown")
734 """Return (tsid, up) tuples representing current tspecs"""
735 res = self.request("WMM_AC_STATUS")
736 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
737 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
739 logger.debug("tspecs: " + str(tspecs))
742 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
746 "nominal_msdu_size": 1500,
747 "min_phy_rate": 6000000,
748 "mean_data_rate": 1500,
750 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
751 for (key, value) in params.iteritems():
752 cmd += " %s=%d" % (key, value)
756 if self.request(cmd).strip() != "OK":
757 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
760 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
762 raise Exception("ADDTS failed (time out while waiting failure)")
763 if "tsid=%d" % (tsid) not in ev:
764 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
767 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
769 raise Exception("ADDTS failed (time out)")
770 if "tsid=%d" % (tsid) not in ev:
771 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
773 if not (tsid, up) in self.tspecs():
774 raise Exception("ADDTS failed (tsid not in tspec list)")
776 def del_ts(self, tsid):
777 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
778 raise Exception("DELTS failed")
780 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
782 raise Exception("DELTS failed (time out)")
783 if "tsid=%d" % (tsid) not in ev:
784 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
786 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
788 raise Exception("DELTS failed (still in tspec list)")
790 def connect(self, ssid=None, ssid2=None, **kwargs):
791 logger.info("Connect STA " + self.ifname + " to AP")
792 id = self.add_network()
794 self.set_network_quoted(id, "ssid", ssid)
796 self.set_network(id, "ssid", ssid2)
798 quoted = [ "psk", "identity", "anonymous_identity", "password",
799 "ca_cert", "client_cert", "private_key",
800 "private_key_passwd", "ca_cert2", "client_cert2",
801 "private_key2", "phase1", "phase2", "domain_suffix_match",
802 "altsubject_match", "subject_match", "pac_file", "dh_file",
803 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
806 if field in kwargs and kwargs[field]:
807 self.set_network_quoted(id, field, kwargs[field])
809 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
810 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
811 "wep_tx_keyidx", "scan_freq", "eap",
812 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
813 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
814 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
815 "disable_ht40", "disable_sgi", "disable_ldpc",
816 "ht40_intolerant", "update_identifier", "mac_addr",
817 "erp", "bg_scan_period", "bssid_blacklist",
819 for field in not_quoted:
820 if field in kwargs and kwargs[field]:
821 self.set_network(id, field, kwargs[field])
823 if "raw_psk" in kwargs and kwargs['raw_psk']:
824 self.set_network(id, "psk", kwargs['raw_psk'])
825 if "password_hex" in kwargs and kwargs['password_hex']:
826 self.set_network(id, "password", kwargs['password_hex'])
827 if "peerkey" in kwargs and kwargs['peerkey']:
828 self.set_network(id, "peerkey", "1")
829 if "okc" in kwargs and kwargs['okc']:
830 self.set_network(id, "proactive_key_caching", "1")
831 if "ocsp" in kwargs and kwargs['ocsp']:
832 self.set_network(id, "ocsp", str(kwargs['ocsp']))
833 if "only_add_network" in kwargs and kwargs['only_add_network']:
835 if "wait_connect" not in kwargs or kwargs['wait_connect']:
837 self.connect_network(id, timeout=20)
839 self.connect_network(id)
842 self.select_network(id)
845 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
847 cmd = "SCAN TYPE=" + type
851 cmd = cmd + " freq=" + str(freq)
856 if not "OK" in self.request(cmd):
857 raise Exception("Failed to trigger scan")
860 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
862 raise Exception("Scan timed out")
864 def scan_for_bss(self, bssid, freq=None, force_scan=False):
865 if not force_scan and self.get_bss(bssid) is not None:
867 for i in range(0, 10):
868 self.scan(freq=freq, type="ONLY")
869 if self.get_bss(bssid) is not None:
871 raise Exception("Could not find BSS " + bssid + " in scan")
873 def flush_scan_cache(self, freq=2417):
874 self.request("BSS_FLUSH 0")
875 self.scan(freq=freq, only_new=True)
877 def roam(self, bssid, fail_test=False):
879 if "OK" not in self.request("ROAM " + bssid):
880 raise Exception("ROAM failed")
882 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
884 raise Exception("Unexpected connection")
887 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
890 def roam_over_ds(self, bssid, fail_test=False):
892 if "OK" not in self.request("FT_DS " + bssid):
893 raise Exception("FT_DS failed")
895 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
897 raise Exception("Unexpected connection")
900 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
903 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
904 new_passphrase=None, no_wait=False):
907 self.request("WPS_REG " + bssid + " " + pin + " " +
908 new_ssid.encode("hex") + " " + key_mgmt + " " +
909 cipher + " " + new_passphrase.encode("hex"))
912 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
914 self.request("WPS_REG " + bssid + " " + pin)
917 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
919 raise Exception("WPS cred timed out")
920 ev = self.wait_event(["WPS-FAIL"], timeout=15)
922 raise Exception("WPS timed out")
923 self.wait_connected(timeout=15)
926 self.global_request("RELOG")
928 def wait_completed(self, timeout=10):
929 for i in range(0, timeout * 2):
930 if self.get_status_field("wpa_state") == "COMPLETED":
933 raise Exception("Timeout while waiting for COMPLETED state")
935 def get_capability(self, field):
936 res = self.request("GET_CAPABILITY " + field)
939 return res.split(' ')
941 def get_bss(self, bssid):
942 res = self.request("BSS " + bssid)
945 lines = res.splitlines()
948 [name,value] = l.split('=', 1)
954 def get_pmksa(self, bssid):
955 res = self.request("PMKSA")
956 lines = res.splitlines()
961 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
962 vals['index'] = index
963 vals['pmkid'] = pmkid
964 vals['expiration'] = expiration
965 vals['opportunistic'] = opportunistic
969 def get_sta(self, addr, info=None, next=False):
970 cmd = "STA-NEXT " if next else "STA "
972 res = self.request("STA-FIRST")
974 res = self.request(cmd + addr + " " + info)
976 res = self.request(cmd + addr)
977 lines = res.splitlines()
985 [name,value] = l.split('=', 1)
989 def mgmt_rx(self, timeout=5):
990 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
994 items = ev.split(' ')
995 field,val = items[1].split('=')
997 raise Exception("Unexpected MGMT-RX event format: " + ev)
999 frame = binascii.unhexlify(items[4])
1000 msg['frame'] = frame
1002 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1004 msg['subtype'] = (hdr[0] >> 4) & 0xf
1006 msg['duration'] = hdr[0]
1008 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1010 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1012 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1014 msg['seq_ctrl'] = hdr[0]
1015 msg['payload'] = frame[24:]
1019 def wait_connected(self, timeout=10, error="Connection timed out"):
1020 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1022 raise Exception(error)
1025 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1026 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1028 raise Exception(error)