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")
505 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
507 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
509 cmd = cmd + ' go_intent=' + str(go_intent)
511 cmd = cmd + ' freq=' + str(freq)
513 cmd = cmd + " persistent"
514 if "OK" in self.global_request(cmd):
516 raise Exception("P2P_CONNECT (auth) failed")
518 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
520 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
521 "P2P-GO-NEG-FAILURE"], timeout);
525 raise Exception("Group formation timed out")
526 if "P2P-GO-NEG-SUCCESS" in ev:
528 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
532 raise Exception("Group formation timed out")
534 return self.group_form_result(ev, expect_failure, go_neg_res)
536 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):
537 if not self.discover_peer(peer):
538 raise Exception("Peer " + peer + " not found")
541 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
543 cmd = "P2P_CONNECT " + peer + " " + method
545 cmd = cmd + ' go_intent=' + str(go_intent)
547 cmd = cmd + ' freq=' + str(freq)
549 cmd = cmd + " persistent"
551 cmd = cmd + " persistent=" + persistent_id
553 cmd = cmd + " provdisc"
554 if "OK" in self.global_request(cmd):
559 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
560 "P2P-GO-NEG-FAILURE"], timeout)
564 raise Exception("Group formation timed out")
565 if "P2P-GO-NEG-SUCCESS" in ev:
569 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
573 raise Exception("Group formation timed out")
575 return self.group_form_result(ev, expect_failure, go_neg_res)
576 raise Exception("P2P_CONNECT failed")
578 def wait_event(self, events, timeout=10):
579 start = os.times()[4]
581 while self.mon.pending():
583 logger.debug(self.ifname + ": " + ev)
588 remaining = start + timeout - now
591 if not self.mon.pending(timeout=remaining):
595 def wait_global_event(self, events, timeout):
596 if self.global_iface is None:
597 self.wait_event(events, timeout)
599 start = os.times()[4]
601 while self.global_mon.pending():
602 ev = self.global_mon.recv()
603 logger.debug(self.ifname + "(global): " + ev)
608 remaining = start + timeout - now
611 if not self.global_mon.pending(timeout=remaining):
615 def wait_group_event(self, events, timeout=10):
616 if self.group_ifname and self.group_ifname != self.ifname:
617 if self.gctrl_mon is None:
619 start = os.times()[4]
621 while self.gctrl_mon.pending():
622 ev = self.gctrl_mon.recv()
623 logger.debug(self.group_ifname + ": " + ev)
628 remaining = start + timeout - now
631 if not self.gctrl_mon.pending(timeout=remaining):
635 return self.wait_event(events, timeout)
637 def wait_go_ending_session(self):
640 self.gctrl_mon.detach()
643 self.gctrl_mon = None
644 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
646 raise Exception("Group removal event timed out")
647 if "reason=GO_ENDING_SESSION" not in ev:
648 raise Exception("Unexpected group removal reason")
650 def dump_monitor(self):
651 while self.mon.pending():
653 logger.debug(self.ifname + ": " + ev)
654 while self.global_mon and self.global_mon.pending():
655 ev = self.global_mon.recv()
656 logger.debug(self.ifname + "(global): " + ev)
658 def remove_group(self, ifname=None):
661 self.gctrl_mon.detach()
664 self.gctrl_mon = None
666 ifname = self.group_ifname if self.group_ifname else self.ifname
667 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
668 raise Exception("Group could not be removed")
669 self.group_ifname = None
671 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
673 cmd = "P2P_GROUP_ADD"
674 if persistent is None:
676 elif persistent is True:
677 cmd = cmd + " persistent"
679 cmd = cmd + " persistent=" + str(persistent)
681 cmd = cmd + " freq=" + str(freq)
682 if "OK" in self.global_request(cmd):
683 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
685 raise Exception("GO start up timed out")
686 if not no_event_clear:
688 return self.group_form_result(ev)
689 raise Exception("P2P_GROUP_ADD failed")
691 def p2p_go_authorize_client(self, pin):
692 cmd = "WPS_PIN any " + pin
693 if "FAIL" in self.group_request(cmd):
694 raise Exception("Failed to authorize client connection on GO")
697 def p2p_go_authorize_client_pbc(self):
699 if "FAIL" in self.group_request(cmd):
700 raise Exception("Failed to authorize client connection on GO")
703 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
706 if not self.discover_peer(go_addr, social=social):
707 if social or not self.discover_peer(go_addr, social=social):
708 raise Exception("GO " + go_addr + " not found")
710 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
712 cmd += " freq=" + str(freq)
713 if "OK" in self.global_request(cmd):
717 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
719 raise Exception("Joining the group timed out")
721 return self.group_form_result(ev)
722 raise Exception("P2P_CONNECT(join) failed")
724 def tdls_setup(self, peer):
725 cmd = "TDLS_SETUP " + peer
726 if "FAIL" in self.group_request(cmd):
727 raise Exception("Failed to request TDLS setup")
730 def tdls_teardown(self, peer):
731 cmd = "TDLS_TEARDOWN " + peer
732 if "FAIL" in self.group_request(cmd):
733 raise Exception("Failed to request TDLS teardown")
737 """Return (tsid, up) tuples representing current tspecs"""
738 res = self.request("WMM_AC_STATUS")
739 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
740 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
742 logger.debug("tspecs: " + str(tspecs))
745 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
749 "nominal_msdu_size": 1500,
750 "min_phy_rate": 6000000,
751 "mean_data_rate": 1500,
753 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
754 for (key, value) in params.iteritems():
755 cmd += " %s=%d" % (key, value)
759 if self.request(cmd).strip() != "OK":
760 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
763 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
765 raise Exception("ADDTS failed (time out while waiting failure)")
766 if "tsid=%d" % (tsid) not in ev:
767 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
770 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
772 raise Exception("ADDTS failed (time out)")
773 if "tsid=%d" % (tsid) not in ev:
774 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
776 if not (tsid, up) in self.tspecs():
777 raise Exception("ADDTS failed (tsid not in tspec list)")
779 def del_ts(self, tsid):
780 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
781 raise Exception("DELTS failed")
783 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
785 raise Exception("DELTS failed (time out)")
786 if "tsid=%d" % (tsid) not in ev:
787 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
789 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
791 raise Exception("DELTS failed (still in tspec list)")
793 def connect(self, ssid=None, ssid2=None, **kwargs):
794 logger.info("Connect STA " + self.ifname + " to AP")
795 id = self.add_network()
797 self.set_network_quoted(id, "ssid", ssid)
799 self.set_network(id, "ssid", ssid2)
801 quoted = [ "psk", "identity", "anonymous_identity", "password",
802 "ca_cert", "client_cert", "private_key",
803 "private_key_passwd", "ca_cert2", "client_cert2",
804 "private_key2", "phase1", "phase2", "domain_suffix_match",
805 "altsubject_match", "subject_match", "pac_file", "dh_file",
806 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
809 if field in kwargs and kwargs[field]:
810 self.set_network_quoted(id, field, kwargs[field])
812 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
813 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
814 "wep_tx_keyidx", "scan_freq", "eap",
815 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
816 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
817 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
818 "disable_ht40", "disable_sgi", "disable_ldpc",
819 "ht40_intolerant", "update_identifier", "mac_addr",
820 "erp", "bg_scan_period", "bssid_blacklist",
822 for field in not_quoted:
823 if field in kwargs and kwargs[field]:
824 self.set_network(id, field, kwargs[field])
826 if "raw_psk" in kwargs and kwargs['raw_psk']:
827 self.set_network(id, "psk", kwargs['raw_psk'])
828 if "password_hex" in kwargs and kwargs['password_hex']:
829 self.set_network(id, "password", kwargs['password_hex'])
830 if "peerkey" in kwargs and kwargs['peerkey']:
831 self.set_network(id, "peerkey", "1")
832 if "okc" in kwargs and kwargs['okc']:
833 self.set_network(id, "proactive_key_caching", "1")
834 if "ocsp" in kwargs and kwargs['ocsp']:
835 self.set_network(id, "ocsp", str(kwargs['ocsp']))
836 if "only_add_network" in kwargs and kwargs['only_add_network']:
838 if "wait_connect" not in kwargs or kwargs['wait_connect']:
840 self.connect_network(id, timeout=20)
842 self.connect_network(id)
845 self.select_network(id)
848 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
850 cmd = "SCAN TYPE=" + type
854 cmd = cmd + " freq=" + str(freq)
859 if not "OK" in self.request(cmd):
860 raise Exception("Failed to trigger scan")
863 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
865 raise Exception("Scan timed out")
867 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
868 if not force_scan and self.get_bss(bssid) is not None:
870 for i in range(0, 10):
871 self.scan(freq=freq, type="ONLY", only_new=only_new)
872 if self.get_bss(bssid) is not None:
874 raise Exception("Could not find BSS " + bssid + " in scan")
876 def flush_scan_cache(self, freq=2417):
877 self.request("BSS_FLUSH 0")
878 self.scan(freq=freq, only_new=True)
880 def roam(self, bssid, fail_test=False):
882 if "OK" not in self.request("ROAM " + bssid):
883 raise Exception("ROAM failed")
885 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
887 raise Exception("Unexpected connection")
890 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
893 def roam_over_ds(self, bssid, fail_test=False):
895 if "OK" not in self.request("FT_DS " + bssid):
896 raise Exception("FT_DS failed")
898 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
900 raise Exception("Unexpected connection")
903 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
906 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
907 new_passphrase=None, no_wait=False):
910 self.request("WPS_REG " + bssid + " " + pin + " " +
911 new_ssid.encode("hex") + " " + key_mgmt + " " +
912 cipher + " " + new_passphrase.encode("hex"))
915 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
917 self.request("WPS_REG " + bssid + " " + pin)
920 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
922 raise Exception("WPS cred timed out")
923 ev = self.wait_event(["WPS-FAIL"], timeout=15)
925 raise Exception("WPS timed out")
926 self.wait_connected(timeout=15)
929 self.global_request("RELOG")
931 def wait_completed(self, timeout=10):
932 for i in range(0, timeout * 2):
933 if self.get_status_field("wpa_state") == "COMPLETED":
936 raise Exception("Timeout while waiting for COMPLETED state")
938 def get_capability(self, field):
939 res = self.request("GET_CAPABILITY " + field)
942 return res.split(' ')
944 def get_bss(self, bssid):
945 res = self.request("BSS " + bssid)
948 lines = res.splitlines()
951 [name,value] = l.split('=', 1)
957 def get_pmksa(self, bssid):
958 res = self.request("PMKSA")
959 lines = res.splitlines()
964 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
965 vals['index'] = index
966 vals['pmkid'] = pmkid
967 vals['expiration'] = expiration
968 vals['opportunistic'] = opportunistic
972 def get_sta(self, addr, info=None, next=False):
973 cmd = "STA-NEXT " if next else "STA "
975 res = self.request("STA-FIRST")
977 res = self.request(cmd + addr + " " + info)
979 res = self.request(cmd + addr)
980 lines = res.splitlines()
988 [name,value] = l.split('=', 1)
992 def mgmt_rx(self, timeout=5):
993 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
997 items = ev.split(' ')
998 field,val = items[1].split('=')
1000 raise Exception("Unexpected MGMT-RX event format: " + ev)
1002 frame = binascii.unhexlify(items[4])
1003 msg['frame'] = frame
1005 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1007 msg['subtype'] = (hdr[0] >> 4) & 0xf
1009 msg['duration'] = hdr[0]
1011 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1013 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1015 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1017 msg['seq_ctrl'] = hdr[0]
1018 msg['payload'] = frame[24:]
1022 def wait_connected(self, timeout=10, error="Connection timed out"):
1023 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1025 raise Exception(error)
1028 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1029 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1031 raise Exception(error)