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",
57 drv_params=None, br_ifname=None, create=False,
58 set_ifname=True, all_params=False, if_type=None):
60 groups = subprocess.check_output(["id"])
61 group = "admin" if "(admin)" in groups else "adm"
64 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
66 cmd = cmd + '\t' + drv_params
70 cmd += '\t' + br_ifname
79 if all_params and not create:
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)
90 def interface_remove(self, ifname):
92 self.global_request("INTERFACE_REMOVE " + ifname)
94 def request(self, cmd, timeout=10):
95 logger.debug(self.ifname + ": CTRL: " + cmd)
96 return self.ctrl.request(cmd, timeout=timeout)
98 def global_request(self, cmd):
99 if self.global_iface is None:
102 ifname = self.ifname or self.global_iface
103 logger.debug(ifname + ": CTRL(global): " + cmd)
104 return self.global_ctrl.request(cmd)
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)
114 return "PONG" in self.request("PING")
116 def global_ping(self):
117 return "PONG" in self.global_request("PING")
121 res = self.request("FLUSH")
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")
129 self.gctrl_mon.detach()
132 self.gctrl_mon = None
133 self.group_ifname = None
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")
149 logger.error(self.ifname + ": Driver scan state did not clear")
150 print "Trying to clear cfg80211/mac80211 scan state"
152 cmd = ["ifconfig", self.ifname, "down"]
154 except subprocess.CalledProcessError, e:
155 logger.info("ifconfig failed: " + str(e.returncode))
156 logger.info(e.output)
158 cmd = ["ifconfig", self.ifname, "up"]
160 except subprocess.CalledProcessError, e:
161 logger.info("ifconfig failed: " + str(e.returncode))
162 logger.info(e.output)
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")
170 logger.info("No PING response from " + self.ifname + " after reset")
172 def add_network(self):
173 id = self.request("ADD_NETWORK")
175 raise Exception("ADD_NETWORK failed")
178 def remove_network(self, id):
179 id = self.request("REMOVE_NETWORK " + str(id))
181 raise Exception("REMOVE_NETWORK failed")
184 def get_network(self, id, field):
185 res = self.request("GET_NETWORK " + str(id) + " " + field)
190 def set_network(self, id, field, value):
191 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
193 raise Exception("SET_NETWORK failed")
196 def set_network_quoted(self, id, field, value):
197 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
199 raise Exception("SET_NETWORK failed")
202 def list_networks(self, p2p=False):
204 res = self.global_request("LIST_NETWORKS")
206 res = self.request("LIST_NETWORKS")
207 lines = res.splitlines()
210 if "network id" in l:
212 [id,ssid,bssid,flags] = l.split('\t')
215 network['ssid'] = ssid
216 network['bssid'] = bssid
217 network['flags'] = flags
218 networks.append(network)
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")
227 self.request("SET auto_interworking 0")
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")
236 id = self.request("ADD_CRED")
238 raise Exception("ADD_CRED failed")
241 def remove_cred(self, id):
242 id = self.request("REMOVE_CRED " + str(id))
244 raise Exception("REMOVE_CRED failed")
247 def set_cred(self, id, field, value):
248 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
250 raise Exception("SET_CRED failed")
253 def set_cred_quoted(self, id, field, value):
254 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
256 raise Exception("SET_CRED failed")
259 def get_cred(self, id, field):
260 return self.request("GET_CRED " + str(id) + " " + field)
262 def add_cred_values(self, params):
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" ]
271 self.set_cred_quoted(id, field, params[field])
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:
280 self.set_cred(id, field, params[field])
284 def select_network(self, id, freq=None):
286 extra = " freq=" + str(freq)
289 id = self.request("SELECT_NETWORK " + str(id) + extra)
291 raise Exception("SELECT_NETWORK failed")
294 def mesh_group_add(self, id):
295 id = self.request("MESH_GROUP_ADD " + str(id))
297 raise Exception("MESH_GROUP_ADD failed")
300 def mesh_group_remove(self):
301 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
303 raise Exception("MESH_GROUP_REMOVE failed")
306 def connect_network(self, id, timeout=10):
308 self.select_network(id)
309 self.wait_connected(timeout=timeout)
312 def get_status(self, extra=None):
317 res = self.request("STATUS" + extra)
318 lines = res.splitlines()
322 [name,value] = l.split('=', 1)
324 except ValueError, e:
325 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
328 def get_status_field(self, field, extra=None):
329 vals = self.get_status(extra)
334 def get_group_status(self, extra=None):
339 res = self.group_request("STATUS" + extra)
340 lines = res.splitlines()
344 [name,value] = l.split('=', 1)
346 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
351 def get_group_status_field(self, field, extra=None):
352 vals = self.get_group_status(extra)
357 def get_driver_status(self, ifname=None):
359 res = self.request("STATUS-DRIVER")
361 res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
362 if res.startswith("FAIL"):
364 lines = res.splitlines()
368 [name,value] = l.split('=', 1)
370 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
375 def get_driver_status_field(self, field, ifname=None):
376 vals = self.get_driver_status(ifname)
382 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
383 return 1 if mcc < 2 else mcc
386 res = self.request("MIB")
387 lines = res.splitlines()
391 [name,value] = l.split('=', 1)
393 except ValueError, e:
394 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
397 def p2p_dev_addr(self):
398 return self.get_status_field("p2p_device_address")
400 def p2p_interface_addr(self):
401 return self.get_group_status_field("address")
405 res = self.p2p_interface_addr()
407 res = self.p2p_dev_addr()
410 def p2p_listen(self):
411 return self.global_request("P2P_LISTEN")
413 def p2p_ext_listen(self, period, interval):
414 return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
416 def p2p_cancel_ext_listen(self):
417 return self.global_request("P2P_EXT_LISTEN")
419 def p2p_find(self, social=False, progressive=False, dev_id=None,
420 dev_type=None, delay=None, freq=None):
423 cmd = cmd + " type=social"
425 cmd = cmd + " type=progressive"
427 cmd = cmd + " dev_id=" + dev_id
429 cmd = cmd + " dev_type=" + dev_type
431 cmd = cmd + " delay=" + str(delay)
433 cmd = cmd + " freq=" + str(freq)
434 return self.global_request(cmd)
436 def p2p_stop_find(self):
437 return self.global_request("P2P_STOP_FIND")
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")
445 def peer_known(self, peer, full=True):
446 res = self.global_request("P2P_PEER " + peer)
447 if peer.lower() not in res.lower():
451 return "[PROBE_REQ_ONLY]" not in res
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):
458 self.p2p_find(social, freq=freq)
460 while count < timeout * 4:
463 if self.peer_known(peer, full):
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()
475 [name,value] = l.split('=', 1)
479 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
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)
488 res['result'] = 'go-neg-failed'
489 res['status'] = int(s[2])
492 if "P2P-GROUP-STARTED" not in ev:
493 raise Exception("No P2P-GROUP-STARTED event seen")
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)
498 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
499 s = re.split(exp, ev)
501 raise Exception("Could not parse P2P-GROUP-STARTED")
503 res['result'] = 'success'
505 self.group_ifname = s[2]
507 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
508 self.gctrl_mon.attach()
510 logger.debug("Could not open monitor socket for group interface")
511 self.gctrl_mon = None
515 if "[PERSISTENT]" in ev:
516 res['persistent'] = True
518 res['persistent'] = False
519 p = re.match(r'psk=([0-9a-f]*)', s[6])
521 res['psk'] = p.group(1)
522 p = re.match(r'passphrase="(.*)"', s[6])
524 res['passphrase'] = p.group(1)
525 res['go_dev_addr'] = s[7]
527 if len(s) > 8 and len(s[8]) > 0:
528 res['ip_addr'] = s[8]
530 res['ip_mask'] = s[9]
532 res['go_ip_addr'] = s[10]
535 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
536 s = re.split(exp, go_neg_res)
538 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
539 res['go_neg_role'] = s[2]
540 res['go_neg_freq'] = s[3]
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")
551 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
553 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
555 cmd = cmd + ' go_intent=' + str(go_intent)
557 cmd = cmd + ' freq=' + str(freq)
559 cmd = cmd + ' freq2=' + str(freq2)
561 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
567 cmd = cmd + " persistent"
568 if "OK" in self.global_request(cmd):
570 raise Exception("P2P_CONNECT (auth) failed")
572 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
574 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
575 "P2P-GO-NEG-FAILURE"], timeout);
579 raise Exception("Group formation timed out")
580 if "P2P-GO-NEG-SUCCESS" in ev:
582 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
586 raise Exception("Group formation timed out")
588 return self.group_form_result(ev, expect_failure, go_neg_res)
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")
599 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
601 cmd = "P2P_CONNECT " + peer + " " + method
603 cmd = cmd + ' go_intent=' + str(go_intent)
605 cmd = cmd + ' freq=' + str(freq)
607 cmd = cmd + ' freq2=' + str(freq2)
609 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
615 cmd = cmd + " persistent"
617 cmd = cmd + " persistent=" + persistent_id
619 cmd = cmd + " provdisc"
620 if "OK" in self.global_request(cmd):
624 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
625 "P2P-GO-NEG-FAILURE"], timeout)
629 raise Exception("Group formation timed out")
630 if "P2P-GO-NEG-SUCCESS" in ev:
634 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
638 raise Exception("Group formation timed out")
640 return self.group_form_result(ev, expect_failure, go_neg_res)
641 raise Exception("P2P_CONNECT failed")
643 def wait_event(self, events, timeout=10):
644 start = os.times()[4]
646 while self.mon.pending():
648 logger.debug(self.ifname + ": " + ev)
653 remaining = start + timeout - now
656 if not self.mon.pending(timeout=remaining):
660 def wait_global_event(self, events, timeout):
661 if self.global_iface is None:
662 self.wait_event(events, timeout)
664 start = os.times()[4]
666 while self.global_mon.pending():
667 ev = self.global_mon.recv()
668 logger.debug(self.ifname + "(global): " + ev)
673 remaining = start + timeout - now
676 if not self.global_mon.pending(timeout=remaining):
680 def wait_group_event(self, events, timeout=10):
681 if self.group_ifname and self.group_ifname != self.ifname:
682 if self.gctrl_mon is None:
684 start = os.times()[4]
686 while self.gctrl_mon.pending():
687 ev = self.gctrl_mon.recv()
688 logger.debug(self.group_ifname + ": " + ev)
693 remaining = start + timeout - now
696 if not self.gctrl_mon.pending(timeout=remaining):
700 return self.wait_event(events, timeout)
702 def wait_go_ending_session(self):
705 self.gctrl_mon.detach()
708 self.gctrl_mon = None
709 ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
711 raise Exception("Group removal event timed out")
712 if "reason=GO_ENDING_SESSION" not in ev:
713 raise Exception("Unexpected group removal reason")
715 def dump_monitor(self):
718 while self.mon.pending():
720 logger.debug(self.ifname + ": " + ev)
722 while self.global_mon and self.global_mon.pending():
723 ev = self.global_mon.recv()
724 logger.debug(self.ifname + "(global): " + ev)
726 return (count_iface, count_global)
728 def remove_group(self, ifname=None):
731 self.gctrl_mon.detach()
734 self.gctrl_mon = None
736 ifname = self.group_ifname if self.group_ifname else self.ifname
737 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
738 raise Exception("Group could not be removed")
739 self.group_ifname = None
741 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
743 cmd = "P2P_GROUP_ADD"
744 if persistent is None:
746 elif persistent is True:
747 cmd = cmd + " persistent"
749 cmd = cmd + " persistent=" + str(persistent)
751 cmd = cmd + " freq=" + str(freq)
752 if "OK" in self.global_request(cmd):
753 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
755 raise Exception("GO start up timed out")
756 if not no_event_clear:
758 return self.group_form_result(ev)
759 raise Exception("P2P_GROUP_ADD failed")
761 def p2p_go_authorize_client(self, pin):
762 cmd = "WPS_PIN any " + pin
763 if "FAIL" in self.group_request(cmd):
764 raise Exception("Failed to authorize client connection on GO")
767 def p2p_go_authorize_client_pbc(self):
769 if "FAIL" in self.group_request(cmd):
770 raise Exception("Failed to authorize client connection on GO")
773 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
776 if not self.discover_peer(go_addr, social=social, freq=freq):
777 if social or not self.discover_peer(go_addr, social=social):
778 raise Exception("GO " + go_addr + " not found")
781 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
783 cmd += " freq=" + str(freq)
784 if "OK" in self.global_request(cmd):
788 ev = self.wait_global_event(["P2P-GROUP-STARTED",
789 "P2P-GROUP-FORMATION-FAILURE"],
792 raise Exception("Joining the group timed out")
793 if "P2P-GROUP-STARTED" not in ev:
794 raise Exception("Failed to join the group")
796 return self.group_form_result(ev)
797 raise Exception("P2P_CONNECT(join) failed")
799 def tdls_setup(self, peer):
800 cmd = "TDLS_SETUP " + peer
801 if "FAIL" in self.group_request(cmd):
802 raise Exception("Failed to request TDLS setup")
805 def tdls_teardown(self, peer):
806 cmd = "TDLS_TEARDOWN " + peer
807 if "FAIL" in self.group_request(cmd):
808 raise Exception("Failed to request TDLS teardown")
811 def tdls_link_status(self, peer):
812 cmd = "TDLS_LINK_STATUS " + peer
813 ret = self.group_request(cmd)
815 raise Exception("Failed to request TDLS link status")
819 """Return (tsid, up) tuples representing current tspecs"""
820 res = self.request("WMM_AC_STATUS")
821 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
822 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
824 logger.debug("tspecs: " + str(tspecs))
827 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
831 "nominal_msdu_size": 1500,
832 "min_phy_rate": 6000000,
833 "mean_data_rate": 1500,
835 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
836 for (key, value) in params.iteritems():
837 cmd += " %s=%d" % (key, value)
841 if self.request(cmd).strip() != "OK":
842 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
845 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
847 raise Exception("ADDTS failed (time out while waiting failure)")
848 if "tsid=%d" % (tsid) not in ev:
849 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
852 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
854 raise Exception("ADDTS failed (time out)")
855 if "tsid=%d" % (tsid) not in ev:
856 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
858 if not (tsid, up) in self.tspecs():
859 raise Exception("ADDTS failed (tsid not in tspec list)")
861 def del_ts(self, tsid):
862 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
863 raise Exception("DELTS failed")
865 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
867 raise Exception("DELTS failed (time out)")
868 if "tsid=%d" % (tsid) not in ev:
869 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
871 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
873 raise Exception("DELTS failed (still in tspec list)")
875 def connect(self, ssid=None, ssid2=None, **kwargs):
876 logger.info("Connect STA " + self.ifname + " to AP")
877 id = self.add_network()
879 self.set_network_quoted(id, "ssid", ssid)
881 self.set_network(id, "ssid", ssid2)
883 quoted = [ "psk", "identity", "anonymous_identity", "password",
884 "ca_cert", "client_cert", "private_key",
885 "private_key_passwd", "ca_cert2", "client_cert2",
886 "private_key2", "phase1", "phase2", "domain_suffix_match",
887 "altsubject_match", "subject_match", "pac_file", "dh_file",
888 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
891 if field in kwargs and kwargs[field]:
892 self.set_network_quoted(id, field, kwargs[field])
894 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
895 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
896 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
897 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
898 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
899 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
900 "disable_ht40", "disable_sgi", "disable_ldpc",
901 "ht40_intolerant", "update_identifier", "mac_addr",
902 "erp", "bg_scan_period", "bssid_blacklist",
903 "bssid_whitelist", "mem_only_psk", "eap_workaround" ]
904 for field in not_quoted:
905 if field in kwargs and kwargs[field]:
906 self.set_network(id, field, kwargs[field])
908 if "raw_psk" in kwargs and kwargs['raw_psk']:
909 self.set_network(id, "psk", kwargs['raw_psk'])
910 if "password_hex" in kwargs and kwargs['password_hex']:
911 self.set_network(id, "password", kwargs['password_hex'])
912 if "peerkey" in kwargs and kwargs['peerkey']:
913 self.set_network(id, "peerkey", "1")
914 if "okc" in kwargs and kwargs['okc']:
915 self.set_network(id, "proactive_key_caching", "1")
916 if "ocsp" in kwargs and kwargs['ocsp']:
917 self.set_network(id, "ocsp", str(kwargs['ocsp']))
918 if "only_add_network" in kwargs and kwargs['only_add_network']:
920 if "wait_connect" not in kwargs or kwargs['wait_connect']:
922 self.connect_network(id, timeout=20)
924 self.connect_network(id)
927 self.select_network(id)
930 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
932 cmd = "SCAN TYPE=" + type
936 cmd = cmd + " freq=" + str(freq)
941 if not "OK" in self.request(cmd):
942 raise Exception("Failed to trigger scan")
945 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
947 raise Exception("Scan timed out")
949 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
950 if not force_scan and self.get_bss(bssid) is not None:
952 for i in range(0, 10):
953 self.scan(freq=freq, type="ONLY", only_new=only_new)
954 if self.get_bss(bssid) is not None:
956 raise Exception("Could not find BSS " + bssid + " in scan")
958 def flush_scan_cache(self, freq=2417):
959 self.request("BSS_FLUSH 0")
960 self.scan(freq=freq, only_new=True)
961 res = self.request("SCAN_RESULTS")
962 if len(res.splitlines()) > 1:
963 self.request("BSS_FLUSH 0")
964 self.scan(freq=2422, only_new=True)
965 res = self.request("SCAN_RESULTS")
966 if len(res.splitlines()) > 1:
967 logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
969 def roam(self, bssid, fail_test=False):
971 if "OK" not in self.request("ROAM " + bssid):
972 raise Exception("ROAM failed")
974 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
976 raise Exception("Unexpected connection")
979 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
982 def roam_over_ds(self, bssid, fail_test=False):
984 if "OK" not in self.request("FT_DS " + bssid):
985 raise Exception("FT_DS failed")
987 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
989 raise Exception("Unexpected connection")
992 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
995 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
996 new_passphrase=None, no_wait=False):
999 self.request("WPS_REG " + bssid + " " + pin + " " +
1000 new_ssid.encode("hex") + " " + key_mgmt + " " +
1001 cipher + " " + new_passphrase.encode("hex"))
1004 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
1006 self.request("WPS_REG " + bssid + " " + pin)
1009 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
1011 raise Exception("WPS cred timed out")
1012 ev = self.wait_event(["WPS-FAIL"], timeout=15)
1014 raise Exception("WPS timed out")
1015 self.wait_connected(timeout=15)
1018 self.global_request("RELOG")
1020 def wait_completed(self, timeout=10):
1021 for i in range(0, timeout * 2):
1022 if self.get_status_field("wpa_state") == "COMPLETED":
1025 raise Exception("Timeout while waiting for COMPLETED state")
1027 def get_capability(self, field):
1028 res = self.request("GET_CAPABILITY " + field)
1031 return res.split(' ')
1033 def get_bss(self, bssid, ifname=None):
1034 if not ifname or ifname == self.ifname:
1035 res = self.request("BSS " + bssid)
1036 elif ifname == self.group_ifname:
1037 res = self.group_request("BSS " + bssid)
1043 lines = res.splitlines()
1046 [name,value] = l.split('=', 1)
1052 def get_pmksa(self, bssid):
1053 res = self.request("PMKSA")
1054 lines = res.splitlines()
1059 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
1060 vals['index'] = index
1061 vals['pmkid'] = pmkid
1062 vals['expiration'] = expiration
1063 vals['opportunistic'] = opportunistic
1067 def get_sta(self, addr, info=None, next=False):
1068 cmd = "STA-NEXT " if next else "STA "
1070 res = self.request("STA-FIRST")
1072 res = self.request(cmd + addr + " " + info)
1074 res = self.request(cmd + addr)
1075 lines = res.splitlines()
1083 [name,value] = l.split('=', 1)
1087 def mgmt_rx(self, timeout=5):
1088 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
1092 items = ev.split(' ')
1093 field,val = items[1].split('=')
1095 raise Exception("Unexpected MGMT-RX event format: " + ev)
1097 frame = binascii.unhexlify(items[4])
1098 msg['frame'] = frame
1100 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1102 msg['subtype'] = (hdr[0] >> 4) & 0xf
1104 msg['duration'] = hdr[0]
1106 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1108 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1110 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1112 msg['seq_ctrl'] = hdr[0]
1113 msg['payload'] = frame[24:]
1117 def wait_connected(self, timeout=10, error="Connection timed out"):
1118 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1120 raise Exception(error)
1123 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1124 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1126 raise Exception(error)
1129 def get_group_ifname(self):
1130 return self.group_ifname if self.group_ifname else self.ifname
1132 def get_config(self):
1133 res = self.request("DUMP")
1134 if res.startswith("FAIL"):
1135 raise Exception("DUMP failed")
1136 lines = res.splitlines()
1139 [name,value] = l.split('=', 1)
1143 def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
1144 method="1000", info="", status=None, cpt=None, role=None):
1146 cmd = "P2P_ASP_PROVISION"
1147 params = "info='%s' method=%s" % (info, method)
1149 cmd = "P2P_ASP_PROVISION_RESP"
1150 params = "status=%d" % status
1152 if role is not None:
1153 params += " role=" + role
1155 params += " cpt=" + cpt
1157 if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1158 (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
1159 raise Exception("%s request failed" % cmd)