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_add_cli_chan 0")
126 self.global_request("SET p2p_no_go_freq ")
127 self.global_request("SET p2p_pref_chan ")
128 self.global_request("SET p2p_no_group_iface 1")
129 self.global_request("SET p2p_go_intent 7")
130 self.global_request("P2P_FLUSH")
131 self.request("SET ignore_old_scan_res 0")
134 self.gctrl_mon.detach()
137 self.gctrl_mon = None
138 self.group_ifname = None
143 state1 = self.get_driver_status_field("scan_state")
144 p2pdev = "p2p-dev-" + self.ifname
145 state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
146 states = str(state1) + " " + str(state2)
147 if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
148 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
154 logger.error(self.ifname + ": Driver scan state did not clear")
155 print "Trying to clear cfg80211/mac80211 scan state"
157 cmd = ["ifconfig", self.ifname, "down"]
159 except subprocess.CalledProcessError, e:
160 logger.info("ifconfig failed: " + str(e.returncode))
161 logger.info(e.output)
163 cmd = ["ifconfig", self.ifname, "up"]
165 except subprocess.CalledProcessError, e:
166 logger.info("ifconfig failed: " + str(e.returncode))
167 logger.info(e.output)
169 # The ongoing scan could have discovered BSSes or P2P peers
170 logger.info("Run FLUSH again since scan was in progress")
171 self.request("FLUSH")
175 logger.info("No PING response from " + self.ifname + " after reset")
177 def add_network(self):
178 id = self.request("ADD_NETWORK")
180 raise Exception("ADD_NETWORK failed")
183 def remove_network(self, id):
184 id = self.request("REMOVE_NETWORK " + str(id))
186 raise Exception("REMOVE_NETWORK failed")
189 def get_network(self, id, field):
190 res = self.request("GET_NETWORK " + str(id) + " " + field)
195 def set_network(self, id, field, value):
196 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
198 raise Exception("SET_NETWORK failed")
201 def set_network_quoted(self, id, field, value):
202 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
204 raise Exception("SET_NETWORK failed")
207 def list_networks(self, p2p=False):
209 res = self.global_request("LIST_NETWORKS")
211 res = self.request("LIST_NETWORKS")
212 lines = res.splitlines()
215 if "network id" in l:
217 [id,ssid,bssid,flags] = l.split('\t')
220 network['ssid'] = ssid
221 network['bssid'] = bssid
222 network['flags'] = flags
223 networks.append(network)
226 def hs20_enable(self, auto_interworking=False):
227 self.request("SET interworking 1")
228 self.request("SET hs20 1")
229 if auto_interworking:
230 self.request("SET auto_interworking 1")
232 self.request("SET auto_interworking 0")
234 def interworking_add_network(self, bssid):
235 id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
236 if "FAIL" in id or "OK" in id:
237 raise Exception("INTERWORKING_ADD_NETWORK failed")
241 id = self.request("ADD_CRED")
243 raise Exception("ADD_CRED failed")
246 def remove_cred(self, id):
247 id = self.request("REMOVE_CRED " + str(id))
249 raise Exception("REMOVE_CRED failed")
252 def set_cred(self, id, field, value):
253 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
255 raise Exception("SET_CRED failed")
258 def set_cred_quoted(self, id, field, value):
259 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
261 raise Exception("SET_CRED failed")
264 def get_cred(self, id, field):
265 return self.request("GET_CRED " + str(id) + " " + field)
267 def add_cred_values(self, params):
270 quoted = [ "realm", "username", "password", "domain", "imsi",
271 "excluded_ssid", "milenage", "ca_cert", "client_cert",
272 "private_key", "domain_suffix_match", "provisioning_sp",
273 "roaming_partner", "phase1", "phase2" ]
276 self.set_cred_quoted(id, field, params[field])
278 not_quoted = [ "eap", "roaming_consortium", "priority",
279 "required_roaming_consortium", "sp_priority",
280 "max_bss_load", "update_identifier", "req_conn_capab",
281 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
282 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
283 for field in not_quoted:
285 self.set_cred(id, field, params[field])
289 def select_network(self, id, freq=None):
291 extra = " freq=" + str(freq)
294 id = self.request("SELECT_NETWORK " + str(id) + extra)
296 raise Exception("SELECT_NETWORK failed")
299 def mesh_group_add(self, id):
300 id = self.request("MESH_GROUP_ADD " + str(id))
302 raise Exception("MESH_GROUP_ADD failed")
305 def mesh_group_remove(self):
306 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
308 raise Exception("MESH_GROUP_REMOVE failed")
311 def connect_network(self, id, timeout=10):
313 self.select_network(id)
314 self.wait_connected(timeout=timeout)
317 def get_status(self, extra=None):
322 res = self.request("STATUS" + extra)
323 lines = res.splitlines()
327 [name,value] = l.split('=', 1)
329 except ValueError, e:
330 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
333 def get_status_field(self, field, extra=None):
334 vals = self.get_status(extra)
339 def get_group_status(self, extra=None):
344 res = self.group_request("STATUS" + extra)
345 lines = res.splitlines()
349 [name,value] = l.split('=', 1)
351 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
356 def get_group_status_field(self, field, extra=None):
357 vals = self.get_group_status(extra)
362 def get_driver_status(self, ifname=None):
364 res = self.request("STATUS-DRIVER")
366 res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
367 if res.startswith("FAIL"):
369 lines = res.splitlines()
373 [name,value] = l.split('=', 1)
375 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
380 def get_driver_status_field(self, field, ifname=None):
381 vals = self.get_driver_status(ifname)
387 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
388 return 1 if mcc < 2 else mcc
391 res = self.request("MIB")
392 lines = res.splitlines()
396 [name,value] = l.split('=', 1)
398 except ValueError, e:
399 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
402 def p2p_dev_addr(self):
403 return self.get_status_field("p2p_device_address")
405 def p2p_interface_addr(self):
406 return self.get_group_status_field("address")
410 res = self.p2p_interface_addr()
412 res = self.p2p_dev_addr()
415 def p2p_listen(self):
416 return self.global_request("P2P_LISTEN")
418 def p2p_ext_listen(self, period, interval):
419 return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
421 def p2p_cancel_ext_listen(self):
422 return self.global_request("P2P_EXT_LISTEN")
424 def p2p_find(self, social=False, progressive=False, dev_id=None,
425 dev_type=None, delay=None, freq=None):
428 cmd = cmd + " type=social"
430 cmd = cmd + " type=progressive"
432 cmd = cmd + " dev_id=" + dev_id
434 cmd = cmd + " dev_type=" + dev_type
436 cmd = cmd + " delay=" + str(delay)
438 cmd = cmd + " freq=" + str(freq)
439 return self.global_request(cmd)
441 def p2p_stop_find(self):
442 return self.global_request("P2P_STOP_FIND")
444 def wps_read_pin(self):
445 self.pin = self.request("WPS_PIN get").rstrip("\n")
446 if "FAIL" in self.pin:
447 raise Exception("Could not generate PIN")
450 def peer_known(self, peer, full=True):
451 res = self.global_request("P2P_PEER " + peer)
452 if peer.lower() not in res.lower():
456 return "[PROBE_REQ_ONLY]" not in res
458 def discover_peer(self, peer, full=True, timeout=15, social=True,
459 force_find=False, freq=None):
460 logger.info(self.ifname + ": Trying to discover peer " + peer)
461 if not force_find and self.peer_known(peer, full):
463 self.p2p_find(social, freq=freq)
465 while count < timeout * 4:
468 if self.peer_known(peer, full):
472 def get_peer(self, peer):
473 res = self.global_request("P2P_PEER " + peer)
474 if peer.lower() not in res.lower():
475 raise Exception("Peer information not available")
476 lines = res.splitlines()
480 [name,value] = l.split('=', 1)
484 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
486 if "P2P-GROUP-STARTED" in ev:
487 raise Exception("Group formation succeeded when expecting failure")
488 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
489 s = re.split(exp, ev)
493 res['result'] = 'go-neg-failed'
494 res['status'] = int(s[2])
497 if "P2P-GROUP-STARTED" not in ev:
498 raise Exception("No P2P-GROUP-STARTED event seen")
500 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.]*)'
501 s = re.split(exp, ev)
503 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
504 s = re.split(exp, ev)
506 raise Exception("Could not parse P2P-GROUP-STARTED")
508 res['result'] = 'success'
510 self.group_ifname = s[2]
512 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
513 self.gctrl_mon.attach()
515 logger.debug("Could not open monitor socket for group interface")
516 self.gctrl_mon = None
520 if "[PERSISTENT]" in ev:
521 res['persistent'] = True
523 res['persistent'] = False
524 p = re.match(r'psk=([0-9a-f]*)', s[6])
526 res['psk'] = p.group(1)
527 p = re.match(r'passphrase="(.*)"', s[6])
529 res['passphrase'] = p.group(1)
530 res['go_dev_addr'] = s[7]
532 if len(s) > 8 and len(s[8]) > 0:
533 res['ip_addr'] = s[8]
535 res['ip_mask'] = s[9]
537 res['go_ip_addr'] = s[10]
540 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
541 s = re.split(exp, go_neg_res)
543 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
544 res['go_neg_role'] = s[2]
545 res['go_neg_freq'] = s[3]
549 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
550 persistent=False, freq=None, freq2=None,
551 max_oper_chwidth=None, ht40=False, vht=False):
552 if not self.discover_peer(peer):
553 raise Exception("Peer " + peer + " not found")
556 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
558 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
560 cmd = cmd + ' go_intent=' + str(go_intent)
562 cmd = cmd + ' freq=' + str(freq)
564 cmd = cmd + ' freq2=' + str(freq2)
566 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
572 cmd = cmd + " persistent"
573 if "OK" in self.global_request(cmd):
575 raise Exception("P2P_CONNECT (auth) failed")
577 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
579 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
580 "P2P-GO-NEG-FAILURE"], timeout);
584 raise Exception("Group formation timed out")
585 if "P2P-GO-NEG-SUCCESS" in ev:
587 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
591 raise Exception("Group formation timed out")
593 return self.group_form_result(ev, expect_failure, go_neg_res)
595 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
596 expect_failure=False, persistent=False,
597 persistent_id=None, freq=None, provdisc=False,
598 wait_group=True, freq2=None, max_oper_chwidth=None,
599 ht40=False, vht=False):
600 if not self.discover_peer(peer):
601 raise Exception("Peer " + peer + " not found")
604 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
606 cmd = "P2P_CONNECT " + peer + " " + method
608 cmd = cmd + ' go_intent=' + str(go_intent)
610 cmd = cmd + ' freq=' + str(freq)
612 cmd = cmd + ' freq2=' + str(freq2)
614 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
620 cmd = cmd + " persistent"
622 cmd = cmd + " persistent=" + persistent_id
624 cmd = cmd + " provdisc"
625 if "OK" in self.global_request(cmd):
630 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
631 "P2P-GO-NEG-FAILURE"], timeout)
635 raise Exception("Group formation timed out")
636 if "P2P-GO-NEG-SUCCESS" in ev:
640 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
644 raise Exception("Group formation timed out")
646 return self.group_form_result(ev, expect_failure, go_neg_res)
647 raise Exception("P2P_CONNECT failed")
649 def wait_event(self, events, timeout=10):
650 start = os.times()[4]
652 while self.mon.pending():
654 logger.debug(self.ifname + ": " + ev)
659 remaining = start + timeout - now
662 if not self.mon.pending(timeout=remaining):
666 def wait_global_event(self, events, timeout):
667 if self.global_iface is None:
668 self.wait_event(events, timeout)
670 start = os.times()[4]
672 while self.global_mon.pending():
673 ev = self.global_mon.recv()
674 logger.debug(self.ifname + "(global): " + ev)
679 remaining = start + timeout - now
682 if not self.global_mon.pending(timeout=remaining):
686 def wait_group_event(self, events, timeout=10):
687 if self.group_ifname and self.group_ifname != self.ifname:
688 if self.gctrl_mon is None:
690 start = os.times()[4]
692 while self.gctrl_mon.pending():
693 ev = self.gctrl_mon.recv()
694 logger.debug(self.group_ifname + ": " + ev)
699 remaining = start + timeout - now
702 if not self.gctrl_mon.pending(timeout=remaining):
706 return self.wait_event(events, timeout)
708 def wait_go_ending_session(self):
711 self.gctrl_mon.detach()
714 self.gctrl_mon = None
715 ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
717 raise Exception("Group removal event timed out")
718 if "reason=GO_ENDING_SESSION" not in ev:
719 raise Exception("Unexpected group removal reason")
721 def dump_monitor(self):
724 while self.mon.pending():
726 logger.debug(self.ifname + ": " + ev)
728 while self.global_mon and self.global_mon.pending():
729 ev = self.global_mon.recv()
730 logger.debug(self.ifname + "(global): " + ev)
732 return (count_iface, count_global)
734 def remove_group(self, ifname=None):
737 self.gctrl_mon.detach()
740 self.gctrl_mon = None
742 ifname = self.group_ifname if self.group_ifname else self.ifname
743 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
744 raise Exception("Group could not be removed")
745 self.group_ifname = None
747 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
749 cmd = "P2P_GROUP_ADD"
750 if persistent is None:
752 elif persistent is True:
753 cmd = cmd + " persistent"
755 cmd = cmd + " persistent=" + str(persistent)
757 cmd = cmd + " freq=" + str(freq)
758 if "OK" in self.global_request(cmd):
759 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
761 raise Exception("GO start up timed out")
762 if not no_event_clear:
764 return self.group_form_result(ev)
765 raise Exception("P2P_GROUP_ADD failed")
767 def p2p_go_authorize_client(self, pin):
768 cmd = "WPS_PIN any " + pin
769 if "FAIL" in self.group_request(cmd):
770 raise Exception("Failed to authorize client connection on GO")
773 def p2p_go_authorize_client_pbc(self):
775 if "FAIL" in self.group_request(cmd):
776 raise Exception("Failed to authorize client connection on GO")
779 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
782 if not self.discover_peer(go_addr, social=social, freq=freq):
783 if social or not self.discover_peer(go_addr, social=social):
784 raise Exception("GO " + go_addr + " not found")
786 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
788 cmd += " freq=" + str(freq)
789 if "OK" in self.global_request(cmd):
793 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
795 raise Exception("Joining the group timed out")
797 return self.group_form_result(ev)
798 raise Exception("P2P_CONNECT(join) failed")
800 def tdls_setup(self, peer):
801 cmd = "TDLS_SETUP " + peer
802 if "FAIL" in self.group_request(cmd):
803 raise Exception("Failed to request TDLS setup")
806 def tdls_teardown(self, peer):
807 cmd = "TDLS_TEARDOWN " + peer
808 if "FAIL" in self.group_request(cmd):
809 raise Exception("Failed to request TDLS teardown")
812 def tdls_link_status(self, peer):
813 cmd = "TDLS_LINK_STATUS " + peer
814 ret = self.group_request(cmd)
816 raise Exception("Failed to request TDLS link status")
820 """Return (tsid, up) tuples representing current tspecs"""
821 res = self.request("WMM_AC_STATUS")
822 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
823 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
825 logger.debug("tspecs: " + str(tspecs))
828 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
832 "nominal_msdu_size": 1500,
833 "min_phy_rate": 6000000,
834 "mean_data_rate": 1500,
836 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
837 for (key, value) in params.iteritems():
838 cmd += " %s=%d" % (key, value)
842 if self.request(cmd).strip() != "OK":
843 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
846 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
848 raise Exception("ADDTS failed (time out while waiting failure)")
849 if "tsid=%d" % (tsid) not in ev:
850 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
853 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
855 raise Exception("ADDTS failed (time out)")
856 if "tsid=%d" % (tsid) not in ev:
857 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
859 if not (tsid, up) in self.tspecs():
860 raise Exception("ADDTS failed (tsid not in tspec list)")
862 def del_ts(self, tsid):
863 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
864 raise Exception("DELTS failed")
866 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
868 raise Exception("DELTS failed (time out)")
869 if "tsid=%d" % (tsid) not in ev:
870 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
872 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
874 raise Exception("DELTS failed (still in tspec list)")
876 def connect(self, ssid=None, ssid2=None, **kwargs):
877 logger.info("Connect STA " + self.ifname + " to AP")
878 id = self.add_network()
880 self.set_network_quoted(id, "ssid", ssid)
882 self.set_network(id, "ssid", ssid2)
884 quoted = [ "psk", "identity", "anonymous_identity", "password",
885 "ca_cert", "client_cert", "private_key",
886 "private_key_passwd", "ca_cert2", "client_cert2",
887 "private_key2", "phase1", "phase2", "domain_suffix_match",
888 "altsubject_match", "subject_match", "pac_file", "dh_file",
889 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
892 if field in kwargs and kwargs[field]:
893 self.set_network_quoted(id, field, kwargs[field])
895 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
896 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
897 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
898 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
899 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
900 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
901 "disable_ht40", "disable_sgi", "disable_ldpc",
902 "ht40_intolerant", "update_identifier", "mac_addr",
903 "erp", "bg_scan_period", "bssid_blacklist",
904 "bssid_whitelist", "mem_only_psk", "eap_workaround" ]
905 for field in not_quoted:
906 if field in kwargs and kwargs[field]:
907 self.set_network(id, field, kwargs[field])
909 if "raw_psk" in kwargs and kwargs['raw_psk']:
910 self.set_network(id, "psk", kwargs['raw_psk'])
911 if "password_hex" in kwargs and kwargs['password_hex']:
912 self.set_network(id, "password", kwargs['password_hex'])
913 if "peerkey" in kwargs and kwargs['peerkey']:
914 self.set_network(id, "peerkey", "1")
915 if "okc" in kwargs and kwargs['okc']:
916 self.set_network(id, "proactive_key_caching", "1")
917 if "ocsp" in kwargs and kwargs['ocsp']:
918 self.set_network(id, "ocsp", str(kwargs['ocsp']))
919 if "only_add_network" in kwargs and kwargs['only_add_network']:
921 if "wait_connect" not in kwargs or kwargs['wait_connect']:
923 self.connect_network(id, timeout=20)
925 self.connect_network(id)
928 self.select_network(id)
931 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
933 cmd = "SCAN TYPE=" + type
937 cmd = cmd + " freq=" + str(freq)
942 if not "OK" in self.request(cmd):
943 raise Exception("Failed to trigger scan")
946 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
948 raise Exception("Scan timed out")
950 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
951 if not force_scan and self.get_bss(bssid) is not None:
953 for i in range(0, 10):
954 self.scan(freq=freq, type="ONLY", only_new=only_new)
955 if self.get_bss(bssid) is not None:
957 raise Exception("Could not find BSS " + bssid + " in scan")
959 def flush_scan_cache(self, freq=2417):
960 self.request("BSS_FLUSH 0")
961 self.scan(freq=freq, only_new=True)
962 res = self.request("SCAN_RESULTS")
963 if len(res.splitlines()) > 1:
964 self.request("BSS_FLUSH 0")
965 self.scan(freq=2422, only_new=True)
966 res = self.request("SCAN_RESULTS")
967 if len(res.splitlines()) > 1:
968 logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
970 def roam(self, bssid, fail_test=False):
972 if "OK" not in self.request("ROAM " + bssid):
973 raise Exception("ROAM failed")
975 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
977 raise Exception("Unexpected connection")
980 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
983 def roam_over_ds(self, bssid, fail_test=False):
985 if "OK" not in self.request("FT_DS " + bssid):
986 raise Exception("FT_DS failed")
988 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
990 raise Exception("Unexpected connection")
993 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
996 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
997 new_passphrase=None, no_wait=False):
1000 self.request("WPS_REG " + bssid + " " + pin + " " +
1001 new_ssid.encode("hex") + " " + key_mgmt + " " +
1002 cipher + " " + new_passphrase.encode("hex"))
1005 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
1007 self.request("WPS_REG " + bssid + " " + pin)
1010 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
1012 raise Exception("WPS cred timed out")
1013 ev = self.wait_event(["WPS-FAIL"], timeout=15)
1015 raise Exception("WPS timed out")
1016 self.wait_connected(timeout=15)
1019 self.global_request("RELOG")
1021 def wait_completed(self, timeout=10):
1022 for i in range(0, timeout * 2):
1023 if self.get_status_field("wpa_state") == "COMPLETED":
1026 raise Exception("Timeout while waiting for COMPLETED state")
1028 def get_capability(self, field):
1029 res = self.request("GET_CAPABILITY " + field)
1032 return res.split(' ')
1034 def get_bss(self, bssid, ifname=None):
1035 if not ifname or ifname == self.ifname:
1036 res = self.request("BSS " + bssid)
1037 elif ifname == self.group_ifname:
1038 res = self.group_request("BSS " + bssid)
1044 lines = res.splitlines()
1047 [name,value] = l.split('=', 1)
1053 def get_pmksa(self, bssid):
1054 res = self.request("PMKSA")
1055 lines = res.splitlines()
1060 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
1061 vals['index'] = index
1062 vals['pmkid'] = pmkid
1063 vals['expiration'] = expiration
1064 vals['opportunistic'] = opportunistic
1068 def get_sta(self, addr, info=None, next=False):
1069 cmd = "STA-NEXT " if next else "STA "
1071 res = self.request("STA-FIRST")
1073 res = self.request(cmd + addr + " " + info)
1075 res = self.request(cmd + addr)
1076 lines = res.splitlines()
1084 [name,value] = l.split('=', 1)
1088 def mgmt_rx(self, timeout=5):
1089 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
1093 items = ev.split(' ')
1094 field,val = items[1].split('=')
1096 raise Exception("Unexpected MGMT-RX event format: " + ev)
1098 frame = binascii.unhexlify(items[4])
1099 msg['frame'] = frame
1101 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1103 msg['subtype'] = (hdr[0] >> 4) & 0xf
1105 msg['duration'] = hdr[0]
1107 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1109 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1111 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1113 msg['seq_ctrl'] = hdr[0]
1114 msg['payload'] = frame[24:]
1118 def wait_connected(self, timeout=10, error="Connection timed out"):
1119 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1121 raise Exception(error)
1124 def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
1125 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1127 raise Exception(error)
1130 def get_group_ifname(self):
1131 return self.group_ifname if self.group_ifname else self.ifname
1133 def get_config(self):
1134 res = self.request("DUMP")
1135 if res.startswith("FAIL"):
1136 raise Exception("DUMP failed")
1137 lines = res.splitlines()
1140 [name,value] = l.split('=', 1)
1144 def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
1145 method="1000", info="", status=None, cpt=None, role=None):
1147 cmd = "P2P_ASP_PROVISION"
1148 params = "info='%s' method=%s" % (info, method)
1150 cmd = "P2P_ASP_PROVISION_RESP"
1151 params = "status=%d" % status
1153 if role is not None:
1154 params += " role=" + role
1156 params += " cpt=" + cpt
1158 if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1159 (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
1160 raise Exception("%s request failed" % cmd)