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
36 def set_ifname(self, ifname):
38 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
39 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
42 def remove_ifname(self):
49 def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
51 groups = subprocess.check_output(["id"])
52 group = "admin" if "(admin)" in groups else "adm"
55 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
57 cmd = cmd + '\t' + drv_params
58 if "FAIL" in self.global_request(cmd):
59 raise Exception("Failed to add a dynamic wpa_supplicant interface")
60 self.set_ifname(ifname)
62 def interface_remove(self, ifname):
64 self.global_request("INTERFACE_REMOVE " + ifname)
66 def request(self, cmd):
67 logger.debug(self.ifname + ": CTRL: " + cmd)
68 return self.ctrl.request(cmd)
70 def global_request(self, cmd):
71 if self.global_iface is None:
74 ifname = self.ifname or self.global_iface
75 logger.debug(ifname + ": CTRL(global): " + cmd)
76 return self.global_ctrl.request(cmd)
78 def group_request(self, cmd):
79 if self.group_ifname and self.group_ifname != self.ifname:
80 logger.debug(self.group_ifname + ": CTRL: " + cmd)
81 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
82 return gctrl.request(cmd)
83 return self.request(cmd)
86 return "PONG" in self.request("PING")
88 def global_ping(self):
89 return "PONG" in self.global_request("PING")
93 res = self.request("FLUSH")
95 logger.info("FLUSH to " + self.ifname + " failed: " + res)
96 self.request("SET p2p_add_cli_chan 0")
97 self.request("SET p2p_no_go_freq ")
98 self.request("SET p2p_pref_chan ")
99 self.request("SET p2p_no_group_iface 1")
100 self.request("SET p2p_go_intent 7")
101 self.request("SET ignore_old_scan_res 0")
104 self.gctrl_mon.detach()
107 self.gctrl_mon = None
108 self.group_ifname = None
113 state = self.get_driver_status_field("scan_state")
114 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
115 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
121 logger.error(self.ifname + ": Driver scan state did not clear")
122 print "Trying to clear cfg80211/mac80211 scan state"
124 cmd = ["sudo", "ifconfig", self.ifname, "down"]
126 except subprocess.CalledProcessError, e:
127 logger.info("ifconfig failed: " + str(e.returncode))
128 logger.info(e.output)
130 cmd = ["sudo", "ifconfig", self.ifname, "up"]
132 except subprocess.CalledProcessError, e:
133 logger.info("ifconfig failed: " + str(e.returncode))
134 logger.info(e.output)
136 # The ongoing scan could have discovered BSSes or P2P peers
137 logger.info("Run FLUSH again since scan was in progress")
138 self.request("FLUSH")
142 logger.info("No PING response from " + self.ifname + " after reset")
144 def add_network(self):
145 id = self.request("ADD_NETWORK")
147 raise Exception("ADD_NETWORK failed")
150 def remove_network(self, id):
151 id = self.request("REMOVE_NETWORK " + str(id))
153 raise Exception("REMOVE_NETWORK failed")
156 def get_network(self, id, field):
157 res = self.request("GET_NETWORK " + str(id) + " " + field)
162 def set_network(self, id, field, value):
163 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
165 raise Exception("SET_NETWORK failed")
168 def set_network_quoted(self, id, field, value):
169 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
171 raise Exception("SET_NETWORK failed")
174 def list_networks(self):
175 res = self.request("LIST_NETWORKS")
176 lines = res.splitlines()
179 if "network id" in l:
181 [id,ssid,bssid,flags] = l.split('\t')
184 network['ssid'] = ssid
185 network['bssid'] = bssid
186 network['flags'] = flags
187 networks.append(network)
190 def hs20_enable(self, auto_interworking=False):
191 self.request("SET interworking 1")
192 self.request("SET hs20 1")
193 if auto_interworking:
194 self.request("SET auto_interworking 1")
196 self.request("SET auto_interworking 0")
199 id = self.request("ADD_CRED")
201 raise Exception("ADD_CRED failed")
204 def remove_cred(self, id):
205 id = self.request("REMOVE_CRED " + str(id))
207 raise Exception("REMOVE_CRED failed")
210 def set_cred(self, id, field, value):
211 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
213 raise Exception("SET_CRED failed")
216 def set_cred_quoted(self, id, field, value):
217 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
219 raise Exception("SET_CRED failed")
222 def get_cred(self, id, field):
223 return self.request("GET_CRED " + str(id) + " " + field)
225 def add_cred_values(self, params):
228 quoted = [ "realm", "username", "password", "domain", "imsi",
229 "excluded_ssid", "milenage", "ca_cert", "client_cert",
230 "private_key", "domain_suffix_match", "provisioning_sp",
231 "roaming_partner", "phase1", "phase2" ]
234 self.set_cred_quoted(id, field, params[field])
236 not_quoted = [ "eap", "roaming_consortium", "priority",
237 "required_roaming_consortium", "sp_priority",
238 "max_bss_load", "update_identifier", "req_conn_capab",
239 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
240 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
241 for field in not_quoted:
243 self.set_cred(id, field, params[field])
247 def select_network(self, id, freq=None):
249 extra = " freq=" + freq
252 id = self.request("SELECT_NETWORK " + str(id) + extra)
254 raise Exception("SELECT_NETWORK failed")
257 def mesh_group_add(self, id):
258 id = self.request("MESH_GROUP_ADD " + str(id))
260 raise Exception("MESH_GROUP_ADD failed")
263 def mesh_group_remove(self):
264 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
266 raise Exception("MESH_GROUP_REMOVE failed")
269 def connect_network(self, id, timeout=10):
271 self.select_network(id)
272 self.wait_connected(timeout=timeout)
275 def get_status(self, extra=None):
280 res = self.request("STATUS" + extra)
281 lines = res.splitlines()
285 [name,value] = l.split('=', 1)
287 except ValueError, e:
288 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
291 def get_status_field(self, field, extra=None):
292 vals = self.get_status(extra)
297 def get_group_status(self, extra=None):
302 res = self.group_request("STATUS" + extra)
303 lines = res.splitlines()
307 [name,value] = l.split('=', 1)
309 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
314 def get_group_status_field(self, field, extra=None):
315 vals = self.get_group_status(extra)
320 def get_driver_status(self):
321 res = self.request("STATUS-DRIVER")
322 lines = res.splitlines()
326 [name,value] = l.split('=', 1)
328 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
333 def get_driver_status_field(self, field):
334 vals = self.get_driver_status()
340 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
341 return 1 if mcc < 2 else mcc
344 res = self.request("MIB")
345 lines = res.splitlines()
349 [name,value] = l.split('=', 1)
351 except ValueError, e:
352 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
355 def p2p_dev_addr(self):
356 return self.get_status_field("p2p_device_address")
358 def p2p_interface_addr(self):
359 return self.get_group_status_field("address")
363 res = self.p2p_interface_addr()
365 res = self.p2p_dev_addr()
368 def p2p_listen(self):
369 return self.global_request("P2P_LISTEN")
371 def p2p_find(self, social=False, progressive=False, dev_id=None,
372 dev_type=None, delay=None):
375 cmd = cmd + " type=social"
377 cmd = cmd + " type=progressive"
379 cmd = cmd + " dev_id=" + dev_id
381 cmd = cmd + " dev_type=" + dev_type
383 cmd = cmd + " delay=" + str(delay)
384 return self.global_request(cmd)
386 def p2p_stop_find(self):
387 return self.global_request("P2P_STOP_FIND")
389 def wps_read_pin(self):
390 self.pin = self.request("WPS_PIN get").rstrip("\n")
391 if "FAIL" in self.pin:
392 raise Exception("Could not generate PIN")
395 def peer_known(self, peer, full=True):
396 res = self.global_request("P2P_PEER " + peer)
397 if peer.lower() not in res.lower():
401 return "[PROBE_REQ_ONLY]" not in res
403 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
404 logger.info(self.ifname + ": Trying to discover peer " + peer)
405 if not force_find and self.peer_known(peer, full):
407 self.p2p_find(social)
409 while count < timeout * 4:
412 if self.peer_known(peer, full):
416 def get_peer(self, peer):
417 res = self.global_request("P2P_PEER " + peer)
418 if peer.lower() not in res.lower():
419 raise Exception("Peer information not available")
420 lines = res.splitlines()
424 [name,value] = l.split('=', 1)
428 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
430 if "P2P-GROUP-STARTED" in ev:
431 raise Exception("Group formation succeeded when expecting failure")
432 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
433 s = re.split(exp, ev)
437 res['result'] = 'go-neg-failed'
438 res['status'] = int(s[2])
441 if "P2P-GROUP-STARTED" not in ev:
442 raise Exception("No P2P-GROUP-STARTED event seen")
444 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.]*)'
445 s = re.split(exp, ev)
447 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
448 s = re.split(exp, ev)
450 raise Exception("Could not parse P2P-GROUP-STARTED")
452 res['result'] = 'success'
454 self.group_ifname = s[2]
456 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
457 self.gctrl_mon.attach()
459 logger.debug("Could not open monitor socket for group interface")
460 self.gctrl_mon = None
464 if "[PERSISTENT]" in ev:
465 res['persistent'] = True
467 res['persistent'] = False
468 p = re.match(r'psk=([0-9a-f]*)', s[6])
470 res['psk'] = p.group(1)
471 p = re.match(r'passphrase="(.*)"', s[6])
473 res['passphrase'] = p.group(1)
474 res['go_dev_addr'] = s[7]
476 if len(s) > 8 and len(s[8]) > 0:
477 res['ip_addr'] = s[8]
479 res['ip_mask'] = s[9]
481 res['go_ip_addr'] = s[10]
484 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
485 s = re.split(exp, go_neg_res)
487 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
488 res['go_neg_role'] = s[2]
489 res['go_neg_freq'] = s[3]
493 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
494 if not self.discover_peer(peer):
495 raise Exception("Peer " + peer + " not found")
497 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
499 cmd = cmd + ' go_intent=' + str(go_intent)
501 cmd = cmd + ' freq=' + str(freq)
503 cmd = cmd + " persistent"
504 if "OK" in self.global_request(cmd):
506 raise Exception("P2P_CONNECT (auth) failed")
508 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
510 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
511 "P2P-GO-NEG-FAILURE"], timeout);
515 raise Exception("Group formation timed out")
516 if "P2P-GO-NEG-SUCCESS" in ev:
518 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
522 raise Exception("Group formation timed out")
524 return self.group_form_result(ev, expect_failure, go_neg_res)
526 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):
527 if not self.discover_peer(peer):
528 raise Exception("Peer " + peer + " not found")
531 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
533 cmd = "P2P_CONNECT " + peer + " " + method
535 cmd = cmd + ' go_intent=' + str(go_intent)
537 cmd = cmd + ' freq=' + str(freq)
539 cmd = cmd + " persistent"
541 cmd = cmd + " persistent=" + persistent_id
543 cmd = cmd + " provdisc"
544 if "OK" in self.global_request(cmd):
549 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
550 "P2P-GO-NEG-FAILURE"], timeout)
554 raise Exception("Group formation timed out")
555 if "P2P-GO-NEG-SUCCESS" in ev:
559 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
563 raise Exception("Group formation timed out")
565 return self.group_form_result(ev, expect_failure, go_neg_res)
566 raise Exception("P2P_CONNECT failed")
568 def wait_event(self, events, timeout=10):
569 start = os.times()[4]
571 while self.mon.pending():
573 logger.debug(self.ifname + ": " + ev)
578 remaining = start + timeout - now
581 if not self.mon.pending(timeout=remaining):
585 def wait_global_event(self, events, timeout):
586 if self.global_iface is None:
587 self.wait_event(events, timeout)
589 start = os.times()[4]
591 while self.global_mon.pending():
592 ev = self.global_mon.recv()
593 logger.debug(self.ifname + "(global): " + ev)
598 remaining = start + timeout - now
601 if not self.global_mon.pending(timeout=remaining):
605 def wait_group_event(self, events, timeout=10):
606 if self.group_ifname and self.group_ifname != self.ifname:
607 if self.gctrl_mon is None:
609 start = os.times()[4]
611 while self.gctrl_mon.pending():
612 ev = self.gctrl_mon.recv()
613 logger.debug(self.group_ifname + ": " + ev)
618 remaining = start + timeout - now
621 if not self.gctrl_mon.pending(timeout=remaining):
625 return self.wait_event(events, timeout)
627 def wait_go_ending_session(self):
630 self.gctrl_mon.detach()
633 self.gctrl_mon = None
634 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
636 raise Exception("Group removal event timed out")
637 if "reason=GO_ENDING_SESSION" not in ev:
638 raise Exception("Unexpected group removal reason")
640 def dump_monitor(self):
641 while self.mon.pending():
643 logger.debug(self.ifname + ": " + ev)
644 while self.global_mon and self.global_mon.pending():
645 ev = self.global_mon.recv()
646 logger.debug(self.ifname + "(global): " + ev)
648 def remove_group(self, ifname=None):
651 self.gctrl_mon.detach()
654 self.gctrl_mon = None
656 ifname = self.group_ifname if self.group_ifname else self.ifname
657 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
658 raise Exception("Group could not be removed")
659 self.group_ifname = None
661 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
663 cmd = "P2P_GROUP_ADD"
664 if persistent is None:
666 elif persistent is True:
667 cmd = cmd + " persistent"
669 cmd = cmd + " persistent=" + str(persistent)
671 cmd = cmd + " freq=" + str(freq)
672 if "OK" in self.global_request(cmd):
673 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
675 raise Exception("GO start up timed out")
676 if not no_event_clear:
678 return self.group_form_result(ev)
679 raise Exception("P2P_GROUP_ADD failed")
681 def p2p_go_authorize_client(self, pin):
682 cmd = "WPS_PIN any " + pin
683 if "FAIL" in self.group_request(cmd):
684 raise Exception("Failed to authorize client connection on GO")
687 def p2p_go_authorize_client_pbc(self):
689 if "FAIL" in self.group_request(cmd):
690 raise Exception("Failed to authorize client connection on GO")
693 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
696 if not self.discover_peer(go_addr, social=social):
697 if social or not self.discover_peer(go_addr, social=social):
698 raise Exception("GO " + go_addr + " not found")
700 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
702 cmd += " freq=" + str(freq)
703 if "OK" in self.global_request(cmd):
707 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
709 raise Exception("Joining the group timed out")
711 return self.group_form_result(ev)
712 raise Exception("P2P_CONNECT(join) failed")
714 def tdls_setup(self, peer):
715 cmd = "TDLS_SETUP " + peer
716 if "FAIL" in self.group_request(cmd):
717 raise Exception("Failed to request TDLS setup")
720 def tdls_teardown(self, peer):
721 cmd = "TDLS_TEARDOWN " + peer
722 if "FAIL" in self.group_request(cmd):
723 raise Exception("Failed to request TDLS teardown")
727 """Return (tsid, up) tuples representing current tspecs"""
728 res = self.request("WMM_AC_STATUS")
729 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
730 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
732 logger.debug("tspecs: " + str(tspecs))
735 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
739 "nominal_msdu_size": 1500,
740 "min_phy_rate": 6000000,
741 "mean_data_rate": 1500,
743 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
744 for (key, value) in params.iteritems():
745 cmd += " %s=%d" % (key, value)
749 if self.request(cmd).strip() != "OK":
750 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
753 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
755 raise Exception("ADDTS failed (time out while waiting failure)")
756 if "tsid=%d" % (tsid) not in ev:
757 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
760 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
762 raise Exception("ADDTS failed (time out)")
763 if "tsid=%d" % (tsid) not in ev:
764 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
766 if not (tsid, up) in self.tspecs():
767 raise Exception("ADDTS failed (tsid not in tspec list)")
769 def del_ts(self, tsid):
770 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
771 raise Exception("DELTS failed")
773 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
775 raise Exception("DELTS failed (time out)")
776 if "tsid=%d" % (tsid) not in ev:
777 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
779 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
781 raise Exception("DELTS failed (still in tspec list)")
783 def connect(self, ssid=None, ssid2=None, **kwargs):
784 logger.info("Connect STA " + self.ifname + " to AP")
785 id = self.add_network()
787 self.set_network_quoted(id, "ssid", ssid)
789 self.set_network(id, "ssid", ssid2)
791 quoted = [ "psk", "identity", "anonymous_identity", "password",
792 "ca_cert", "client_cert", "private_key",
793 "private_key_passwd", "ca_cert2", "client_cert2",
794 "private_key2", "phase1", "phase2", "domain_suffix_match",
795 "altsubject_match", "subject_match", "pac_file", "dh_file",
796 "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
798 if field in kwargs and kwargs[field]:
799 self.set_network_quoted(id, field, kwargs[field])
801 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
802 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
803 "wep_tx_keyidx", "scan_freq", "eap",
804 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
805 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
806 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
807 "disable_ht40", "disable_sgi", "disable_ldpc",
808 "ht40_intolerant", "update_identifier", "mac_addr",
809 "erp", "bg_scan_period" ]
810 for field in not_quoted:
811 if field in kwargs and kwargs[field]:
812 self.set_network(id, field, kwargs[field])
814 if "raw_psk" in kwargs and kwargs['raw_psk']:
815 self.set_network(id, "psk", kwargs['raw_psk'])
816 if "password_hex" in kwargs and kwargs['password_hex']:
817 self.set_network(id, "password", kwargs['password_hex'])
818 if "peerkey" in kwargs and kwargs['peerkey']:
819 self.set_network(id, "peerkey", "1")
820 if "okc" in kwargs and kwargs['okc']:
821 self.set_network(id, "proactive_key_caching", "1")
822 if "ocsp" in kwargs and kwargs['ocsp']:
823 self.set_network(id, "ocsp", str(kwargs['ocsp']))
824 if "only_add_network" in kwargs and kwargs['only_add_network']:
826 if "wait_connect" not in kwargs or kwargs['wait_connect']:
828 self.connect_network(id, timeout=20)
830 self.connect_network(id)
833 self.select_network(id)
836 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
838 cmd = "SCAN TYPE=" + type
842 cmd = cmd + " freq=" + str(freq)
847 if not "OK" in self.request(cmd):
848 raise Exception("Failed to trigger scan")
851 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
853 raise Exception("Scan timed out")
855 def scan_for_bss(self, bssid, freq=None, force_scan=False):
856 if not force_scan and self.get_bss(bssid) is not None:
858 for i in range(0, 10):
859 self.scan(freq=freq, type="ONLY")
860 if self.get_bss(bssid) is not None:
862 raise Exception("Could not find BSS " + bssid + " in scan")
864 def flush_scan_cache(self, freq=2417):
865 self.request("BSS_FLUSH 0")
866 self.scan(freq=freq, only_new=True)
868 def roam(self, bssid, fail_test=False):
870 if "OK" not in self.request("ROAM " + bssid):
871 raise Exception("ROAM failed")
873 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
875 raise Exception("Unexpected connection")
878 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
881 def roam_over_ds(self, bssid, fail_test=False):
883 if "OK" not in self.request("FT_DS " + bssid):
884 raise Exception("FT_DS failed")
886 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
888 raise Exception("Unexpected connection")
891 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
894 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
895 new_passphrase=None, no_wait=False):
898 self.request("WPS_REG " + bssid + " " + pin + " " +
899 new_ssid.encode("hex") + " " + key_mgmt + " " +
900 cipher + " " + new_passphrase.encode("hex"))
903 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
905 self.request("WPS_REG " + bssid + " " + pin)
908 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
910 raise Exception("WPS cred timed out")
911 ev = self.wait_event(["WPS-FAIL"], timeout=15)
913 raise Exception("WPS timed out")
914 self.wait_connected(timeout=15)
917 self.global_request("RELOG")
919 def wait_completed(self, timeout=10):
920 for i in range(0, timeout * 2):
921 if self.get_status_field("wpa_state") == "COMPLETED":
924 raise Exception("Timeout while waiting for COMPLETED state")
926 def get_capability(self, field):
927 res = self.request("GET_CAPABILITY " + field)
930 return res.split(' ')
932 def get_bss(self, bssid):
933 res = self.request("BSS " + bssid)
936 lines = res.splitlines()
939 [name,value] = l.split('=', 1)
945 def get_pmksa(self, bssid):
946 res = self.request("PMKSA")
947 lines = res.splitlines()
952 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
953 vals['index'] = index
954 vals['pmkid'] = pmkid
955 vals['expiration'] = expiration
956 vals['opportunistic'] = opportunistic
960 def get_sta(self, addr, info=None, next=False):
961 cmd = "STA-NEXT " if next else "STA "
963 res = self.request("STA-FIRST")
965 res = self.request(cmd + addr + " " + info)
967 res = self.request(cmd + addr)
968 lines = res.splitlines()
976 [name,value] = l.split('=', 1)
980 def mgmt_rx(self, timeout=5):
981 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
985 items = ev.split(' ')
986 field,val = items[1].split('=')
988 raise Exception("Unexpected MGMT-RX event format: " + ev)
990 frame = binascii.unhexlify(items[4])
993 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
995 msg['subtype'] = (hdr[0] >> 4) & 0xf
997 msg['duration'] = hdr[0]
999 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1001 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1003 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1005 msg['seq_ctrl'] = hdr[0]
1006 msg['payload'] = frame[24:]
1010 def wait_connected(self, timeout=10, error="Connection timed out"):
1011 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1013 raise Exception(error)
1016 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1017 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1019 raise Exception(error)