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.
17 logger = logging.getLogger()
18 wpas_ctrl = '/var/run/wpa_supplicant'
21 def __init__(self, ifname=None, global_iface=None, hostname=None,
22 port=9877, global_port=9878):
23 self.hostname = hostname
24 self.group_ifname = None
26 self.host = remotehost.Host(hostname, ifname)
27 self._group_dbg = None
29 self.set_ifname(ifname, hostname, port)
30 res = self.get_driver_status()
31 if 'capa.flags' in res and int(res['capa.flags'], 0) & 0x20000000:
32 self.p2p_dev_ifname = 'p2p-dev-' + self.ifname
34 self.p2p_dev_ifname = ifname
38 self.global_iface = global_iface
41 self.global_ctrl = wpaspy.Ctrl(hostname, global_port)
42 self.global_mon = wpaspy.Ctrl(hostname, global_port)
43 self.global_dbg = hostname + "/" + str(global_port) + "/"
45 self.global_ctrl = wpaspy.Ctrl(global_iface)
46 self.global_mon = wpaspy.Ctrl(global_iface)
48 self.global_mon.attach()
50 self.global_mon = None
52 def cmd_execute(self, cmd_array, shell=False):
53 if self.hostname is None:
55 cmd = ' '.join(cmd_array)
58 proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT,
59 stdout=subprocess.PIPE, shell=shell)
60 out = proc.communicate()[0]
64 return self.host.execute(cmd_array)
68 self.global_mon.detach()
69 self.global_mon = None
70 self.global_ctrl.terminate()
71 self.global_ctrl = None
75 self.global_mon.detach()
76 self.global_mon = None
77 self.global_ctrl = None
80 def set_ifname(self, ifname, hostname=None, port=9877):
83 self.ctrl = wpaspy.Ctrl(hostname, port)
84 self.mon = wpaspy.Ctrl(hostname, port)
85 self.host = remotehost.Host(hostname, ifname)
86 self.dbg = hostname + "/" + ifname
88 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
89 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
93 def remove_ifname(self):
100 def get_ctrl_iface_port(self, ifname):
101 if self.hostname is None:
104 res = self.global_request("INTERFACES ctrl")
105 lines = res.splitlines()
109 if words[0] == ifname:
113 raise Exception("Could not find UDP port for " + ifname)
114 res = line.find("ctrl_iface=udp:")
116 raise Exception("Wrong ctrl_interface format")
117 words = line.split(":")
120 def interface_add(self, ifname, config="", driver="nl80211",
121 drv_params=None, br_ifname=None, create=False,
122 set_ifname=True, all_params=False, if_type=None):
123 status, groups = self.host.execute(["id"])
126 group = "admin" if "(admin)" in groups else "adm"
127 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
129 cmd = cmd + '\t' + drv_params
133 cmd += '\t' + br_ifname
141 cmd += '\t' + if_type
142 if all_params and not create:
148 if "FAIL" in self.global_request(cmd):
149 raise Exception("Failed to add a dynamic wpa_supplicant interface")
150 if not create and set_ifname:
151 port = self.get_ctrl_iface_port(ifname)
152 self.set_ifname(ifname, self.hostname, port)
153 res = self.get_driver_status()
154 if 'capa.flags' in res and int(res['capa.flags'], 0) & 0x20000000:
155 self.p2p_dev_ifname = 'p2p-dev-' + self.ifname
157 self.p2p_dev_ifname = ifname
159 def interface_remove(self, ifname):
161 self.global_request("INTERFACE_REMOVE " + ifname)
163 def request(self, cmd, timeout=10):
164 logger.debug(self.dbg + ": CTRL: " + cmd)
165 return self.ctrl.request(cmd, timeout=timeout)
167 def global_request(self, cmd):
168 if self.global_iface is None:
169 return self.request(cmd)
171 ifname = self.ifname or self.global_iface
172 logger.debug(self.global_dbg + ifname + ": CTRL(global): " + cmd)
173 return self.global_ctrl.request(cmd)
177 if self._group_dbg is not None:
178 return self._group_dbg
179 if self.group_ifname is None:
180 raise Exception("Cannot have group_dbg without group_ifname")
181 if self.hostname is None:
182 self._group_dbg = self.group_ifname
184 self._group_dbg = self.hostname + "/" + self.group_ifname
185 return self._group_dbg
187 def group_request(self, cmd):
188 if self.group_ifname and self.group_ifname != self.ifname:
189 if self.hostname is None:
190 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
192 port = self.get_ctrl_iface_port(self.group_ifname)
193 gctrl = wpaspy.Ctrl(self.hostname, port)
194 logger.debug(self.group_dbg + ": CTRL(group): " + cmd)
195 return gctrl.request(cmd)
196 return self.request(cmd)
199 return "PONG" in self.request("PING")
201 def global_ping(self):
202 return "PONG" in self.global_request("PING")
206 res = self.request("FLUSH")
208 logger.info("FLUSH to " + self.ifname + " failed: " + res)
209 self.global_request("REMOVE_NETWORK all")
210 self.global_request("SET p2p_no_group_iface 1")
211 self.global_request("P2P_FLUSH")
214 self.gctrl_mon.detach()
217 self.gctrl_mon = None
218 self.group_ifname = None
223 state1 = self.get_driver_status_field("scan_state")
224 p2pdev = "p2p-dev-" + self.ifname
225 state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
226 states = str(state1) + " " + str(state2)
227 if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
228 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
234 logger.error(self.ifname + ": Driver scan state did not clear")
235 print "Trying to clear cfg80211/mac80211 scan state"
236 status, buf = self.host.execute(["ifconfig", self.ifname, "down"])
238 logger.info("ifconfig failed: " + buf)
240 status, buf = self.host.execute(["ifconfig", self.ifname, "up"])
242 logger.info("ifconfig failed: " + buf)
245 # The ongoing scan could have discovered BSSes or P2P peers
246 logger.info("Run FLUSH again since scan was in progress")
247 self.request("FLUSH")
251 logger.info("No PING response from " + self.ifname + " after reset")
253 def add_network(self):
254 id = self.request("ADD_NETWORK")
256 raise Exception("ADD_NETWORK failed")
259 def remove_network(self, id):
260 id = self.request("REMOVE_NETWORK " + str(id))
262 raise Exception("REMOVE_NETWORK failed")
265 def get_network(self, id, field):
266 res = self.request("GET_NETWORK " + str(id) + " " + field)
271 def set_network(self, id, field, value):
272 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
274 raise Exception("SET_NETWORK failed")
277 def set_network_quoted(self, id, field, value):
278 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
280 raise Exception("SET_NETWORK failed")
283 def p2pdev_request(self, cmd):
284 return self.global_request("IFNAME=" + self.p2p_dev_ifname + " " + cmd)
286 def p2pdev_add_network(self):
287 id = self.p2pdev_request("ADD_NETWORK")
289 raise Exception("p2pdev ADD_NETWORK failed")
292 def p2pdev_set_network(self, id, field, value):
293 res = self.p2pdev_request("SET_NETWORK " + str(id) + " " + field + " " + value)
295 raise Exception("p2pdev SET_NETWORK failed")
298 def p2pdev_set_network_quoted(self, id, field, value):
299 res = self.p2pdev_request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
301 raise Exception("p2pdev SET_NETWORK failed")
304 def list_networks(self, p2p=False):
306 res = self.global_request("LIST_NETWORKS")
308 res = self.request("LIST_NETWORKS")
309 lines = res.splitlines()
312 if "network id" in l:
314 [id,ssid,bssid,flags] = l.split('\t')
317 network['ssid'] = ssid
318 network['bssid'] = bssid
319 network['flags'] = flags
320 networks.append(network)
323 def hs20_enable(self, auto_interworking=False):
324 self.request("SET interworking 1")
325 self.request("SET hs20 1")
326 if auto_interworking:
327 self.request("SET auto_interworking 1")
329 self.request("SET auto_interworking 0")
331 def interworking_add_network(self, bssid):
332 id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
333 if "FAIL" in id or "OK" in id:
334 raise Exception("INTERWORKING_ADD_NETWORK failed")
338 id = self.request("ADD_CRED")
340 raise Exception("ADD_CRED failed")
343 def remove_cred(self, id):
344 id = self.request("REMOVE_CRED " + str(id))
346 raise Exception("REMOVE_CRED failed")
349 def set_cred(self, id, field, value):
350 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
352 raise Exception("SET_CRED failed")
355 def set_cred_quoted(self, id, field, value):
356 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
358 raise Exception("SET_CRED failed")
361 def get_cred(self, id, field):
362 return self.request("GET_CRED " + str(id) + " " + field)
364 def add_cred_values(self, params):
367 quoted = [ "realm", "username", "password", "domain", "imsi",
368 "excluded_ssid", "milenage", "ca_cert", "client_cert",
369 "private_key", "domain_suffix_match", "provisioning_sp",
370 "roaming_partner", "phase1", "phase2", "private_key_passwd" ]
373 self.set_cred_quoted(id, field, params[field])
375 not_quoted = [ "eap", "roaming_consortium", "priority",
376 "required_roaming_consortium", "sp_priority",
377 "max_bss_load", "update_identifier", "req_conn_capab",
378 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
379 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
380 for field in not_quoted:
382 self.set_cred(id, field, params[field])
386 def select_network(self, id, freq=None):
388 extra = " freq=" + str(freq)
391 id = self.request("SELECT_NETWORK " + str(id) + extra)
393 raise Exception("SELECT_NETWORK failed")
396 def mesh_group_add(self, id):
397 id = self.request("MESH_GROUP_ADD " + str(id))
399 raise Exception("MESH_GROUP_ADD failed")
402 def mesh_group_remove(self):
403 id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
405 raise Exception("MESH_GROUP_REMOVE failed")
408 def connect_network(self, id, timeout=None):
410 timeout = 10 if self.hostname is None else 60
412 self.select_network(id)
413 self.wait_connected(timeout=timeout)
416 def get_status(self, extra=None):
421 res = self.request("STATUS" + extra)
422 lines = res.splitlines()
426 [name,value] = l.split('=', 1)
428 except ValueError, e:
429 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
432 def get_status_field(self, field, extra=None):
433 vals = self.get_status(extra)
438 def get_group_status(self, extra=None):
443 res = self.group_request("STATUS" + extra)
444 lines = res.splitlines()
448 [name,value] = l.split('=', 1)
450 logger.info(self.ifname + ": Ignore unexpected status line: " + l)
455 def get_group_status_field(self, field, extra=None):
456 vals = self.get_group_status(extra)
461 def get_driver_status(self, ifname=None):
463 res = self.request("STATUS-DRIVER")
465 res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
466 if res.startswith("FAIL"):
468 lines = res.splitlines()
472 [name,value] = l.split('=', 1)
474 logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
479 def get_driver_status_field(self, field, ifname=None):
480 vals = self.get_driver_status(ifname)
486 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
487 return 1 if mcc < 2 else mcc
490 res = self.request("MIB")
491 lines = res.splitlines()
495 [name,value] = l.split('=', 1)
497 except ValueError, e:
498 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
501 def p2p_dev_addr(self):
502 return self.get_status_field("p2p_device_address")
504 def p2p_interface_addr(self):
505 return self.get_group_status_field("address")
509 res = self.p2p_interface_addr()
511 res = self.p2p_dev_addr()
514 def p2p_listen(self):
515 return self.global_request("P2P_LISTEN")
517 def p2p_ext_listen(self, period, interval):
518 return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
520 def p2p_cancel_ext_listen(self):
521 return self.global_request("P2P_EXT_LISTEN")
523 def p2p_find(self, social=False, progressive=False, dev_id=None,
524 dev_type=None, delay=None, freq=None):
527 cmd = cmd + " type=social"
529 cmd = cmd + " type=progressive"
531 cmd = cmd + " dev_id=" + dev_id
533 cmd = cmd + " dev_type=" + dev_type
535 cmd = cmd + " delay=" + str(delay)
537 cmd = cmd + " freq=" + str(freq)
538 return self.global_request(cmd)
540 def p2p_stop_find(self):
541 return self.global_request("P2P_STOP_FIND")
543 def wps_read_pin(self):
544 self.pin = self.request("WPS_PIN get").rstrip("\n")
545 if "FAIL" in self.pin:
546 raise Exception("Could not generate PIN")
549 def peer_known(self, peer, full=True):
550 res = self.global_request("P2P_PEER " + peer)
551 if peer.lower() not in res.lower():
555 return "[PROBE_REQ_ONLY]" not in res
557 def discover_peer(self, peer, full=True, timeout=15, social=True,
558 force_find=False, freq=None):
559 logger.info(self.ifname + ": Trying to discover peer " + peer)
560 if not force_find and self.peer_known(peer, full):
562 self.p2p_find(social, freq=freq)
564 while count < timeout * 4:
567 if self.peer_known(peer, full):
571 def get_peer(self, peer):
572 res = self.global_request("P2P_PEER " + peer)
573 if peer.lower() not in res.lower():
574 raise Exception("Peer information not available")
575 lines = res.splitlines()
579 [name,value] = l.split('=', 1)
583 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
585 if "P2P-GROUP-STARTED" in ev:
586 raise Exception("Group formation succeeded when expecting failure")
587 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
588 s = re.split(exp, ev)
592 res['result'] = 'go-neg-failed'
593 res['status'] = int(s[2])
596 if "P2P-GROUP-STARTED" not in ev:
597 raise Exception("No P2P-GROUP-STARTED event seen")
599 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.]*)'
600 s = re.split(exp, ev)
602 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
603 s = re.split(exp, ev)
605 raise Exception("Could not parse P2P-GROUP-STARTED")
607 res['result'] = 'success'
609 self.group_ifname = s[2]
611 if self.hostname is None:
612 self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl,
615 port = self.get_ctrl_iface_port(self.group_ifname)
616 self.gctrl_mon = wpaspy.Ctrl(self.hostname, port)
617 self.gctrl_mon.attach()
619 logger.debug("Could not open monitor socket for group interface")
620 self.gctrl_mon = None
624 if "[PERSISTENT]" in ev:
625 res['persistent'] = True
627 res['persistent'] = False
628 p = re.match(r'psk=([0-9a-f]*)', s[6])
630 res['psk'] = p.group(1)
631 p = re.match(r'passphrase="(.*)"', s[6])
633 res['passphrase'] = p.group(1)
634 res['go_dev_addr'] = s[7]
636 if len(s) > 8 and len(s[8]) > 0:
637 res['ip_addr'] = s[8]
639 res['ip_mask'] = s[9]
641 res['go_ip_addr'] = s[10]
644 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
645 s = re.split(exp, go_neg_res)
647 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
648 res['go_neg_role'] = s[2]
649 res['go_neg_freq'] = s[3]
653 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
654 persistent=False, freq=None, freq2=None,
655 max_oper_chwidth=None, ht40=False, vht=False):
656 if not self.discover_peer(peer):
657 raise Exception("Peer " + peer + " not found")
660 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
662 cmd = "P2P_CONNECT " + peer + " " + method + " auth"
664 cmd = cmd + ' go_intent=' + str(go_intent)
666 cmd = cmd + ' freq=' + str(freq)
668 cmd = cmd + ' freq2=' + str(freq2)
670 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
676 cmd = cmd + " persistent"
677 if "OK" in self.global_request(cmd):
679 raise Exception("P2P_CONNECT (auth) failed")
681 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
683 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
684 "P2P-GO-NEG-FAILURE"], timeout)
688 raise Exception("Group formation timed out")
689 if "P2P-GO-NEG-SUCCESS" in ev:
691 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
695 raise Exception("Group formation timed out")
697 return self.group_form_result(ev, expect_failure, go_neg_res)
699 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
700 expect_failure=False, persistent=False,
701 persistent_id=None, freq=None, provdisc=False,
702 wait_group=True, freq2=None, max_oper_chwidth=None,
703 ht40=False, vht=False):
704 if not self.discover_peer(peer):
705 raise Exception("Peer " + peer + " not found")
708 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
710 cmd = "P2P_CONNECT " + peer + " " + method
711 if go_intent is not None:
712 cmd = cmd + ' go_intent=' + str(go_intent)
714 cmd = cmd + ' freq=' + str(freq)
716 cmd = cmd + ' freq2=' + str(freq2)
718 cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
724 cmd = cmd + " persistent"
726 cmd = cmd + " persistent=" + persistent_id
728 cmd = cmd + " provdisc"
729 if "OK" in self.global_request(cmd):
733 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
734 "P2P-GO-NEG-FAILURE"], timeout)
738 raise Exception("Group formation timed out")
739 if "P2P-GO-NEG-SUCCESS" in ev:
743 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
747 raise Exception("Group formation timed out")
749 return self.group_form_result(ev, expect_failure, go_neg_res)
750 raise Exception("P2P_CONNECT failed")
752 def wait_event(self, events, timeout=10):
753 start = os.times()[4]
755 while self.mon.pending():
757 logger.debug(self.dbg + ": " + ev)
762 remaining = start + timeout - now
765 if not self.mon.pending(timeout=remaining):
769 def wait_global_event(self, events, timeout):
770 if self.global_iface is None:
771 self.wait_event(events, timeout)
773 start = os.times()[4]
775 while self.global_mon.pending():
776 ev = self.global_mon.recv()
777 logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
782 remaining = start + timeout - now
785 if not self.global_mon.pending(timeout=remaining):
789 def wait_group_event(self, events, timeout=10):
790 if self.group_ifname and self.group_ifname != self.ifname:
791 if self.gctrl_mon is None:
793 start = os.times()[4]
795 while self.gctrl_mon.pending():
796 ev = self.gctrl_mon.recv()
797 logger.debug(self.group_dbg + "(group): " + ev)
802 remaining = start + timeout - now
805 if not self.gctrl_mon.pending(timeout=remaining):
809 return self.wait_event(events, timeout)
811 def wait_go_ending_session(self):
814 self.gctrl_mon.detach()
817 self.gctrl_mon = None
818 timeout = 3 if self.hostname is None else 10
819 ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=timeout)
821 raise Exception("Group removal event timed out")
822 if "reason=GO_ENDING_SESSION" not in ev:
823 raise Exception("Unexpected group removal reason")
825 def dump_monitor(self):
828 while self.mon.pending():
830 logger.debug(self.dbg + ": " + ev)
832 while self.global_mon and self.global_mon.pending():
833 ev = self.global_mon.recv()
834 logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
836 return (count_iface, count_global)
838 def remove_group(self, ifname=None):
841 self.gctrl_mon.detach()
844 self.gctrl_mon = None
846 ifname = self.group_ifname if self.group_ifname else self.ifname
847 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
848 raise Exception("Group could not be removed")
849 self.group_ifname = None
851 def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
853 cmd = "P2P_GROUP_ADD"
854 if persistent is None:
856 elif persistent is True:
857 cmd = cmd + " persistent"
859 cmd = cmd + " persistent=" + str(persistent)
861 cmd = cmd + " freq=" + str(freq)
862 if "OK" in self.global_request(cmd):
863 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
865 raise Exception("GO start up timed out")
866 if not no_event_clear:
868 return self.group_form_result(ev)
869 raise Exception("P2P_GROUP_ADD failed")
871 def p2p_go_authorize_client(self, pin):
872 cmd = "WPS_PIN any " + pin
873 if "FAIL" in self.group_request(cmd):
874 raise Exception("Failed to authorize client connection on GO")
877 def p2p_go_authorize_client_pbc(self):
879 if "FAIL" in self.group_request(cmd):
880 raise Exception("Failed to authorize client connection on GO")
883 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
886 if not self.discover_peer(go_addr, social=social, freq=freq):
887 if social or not self.discover_peer(go_addr, social=social):
888 raise Exception("GO " + go_addr + " not found")
891 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
893 cmd += " freq=" + str(freq)
894 if "OK" in self.global_request(cmd):
898 ev = self.wait_global_event(["P2P-GROUP-STARTED",
899 "P2P-GROUP-FORMATION-FAILURE"],
902 raise Exception("Joining the group timed out")
903 if "P2P-GROUP-STARTED" not in ev:
904 raise Exception("Failed to join the group")
906 return self.group_form_result(ev)
907 raise Exception("P2P_CONNECT(join) failed")
909 def tdls_setup(self, peer):
910 cmd = "TDLS_SETUP " + peer
911 if "FAIL" in self.group_request(cmd):
912 raise Exception("Failed to request TDLS setup")
915 def tdls_teardown(self, peer):
916 cmd = "TDLS_TEARDOWN " + peer
917 if "FAIL" in self.group_request(cmd):
918 raise Exception("Failed to request TDLS teardown")
921 def tdls_link_status(self, peer):
922 cmd = "TDLS_LINK_STATUS " + peer
923 ret = self.group_request(cmd)
925 raise Exception("Failed to request TDLS link status")
929 """Return (tsid, up) tuples representing current tspecs"""
930 res = self.request("WMM_AC_STATUS")
931 tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
932 tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
934 logger.debug("tspecs: " + str(tspecs))
937 def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
941 "nominal_msdu_size": 1500,
942 "min_phy_rate": 6000000,
943 "mean_data_rate": 1500,
945 cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
946 for (key, value) in params.iteritems():
947 cmd += " %s=%d" % (key, value)
951 if self.request(cmd).strip() != "OK":
952 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
955 ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
957 raise Exception("ADDTS failed (time out while waiting failure)")
958 if "tsid=%d" % (tsid) not in ev:
959 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
962 ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
964 raise Exception("ADDTS failed (time out)")
965 if "tsid=%d" % (tsid) not in ev:
966 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
968 if not (tsid, up) in self.tspecs():
969 raise Exception("ADDTS failed (tsid not in tspec list)")
971 def del_ts(self, tsid):
972 if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
973 raise Exception("DELTS failed")
975 ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
977 raise Exception("DELTS failed (time out)")
978 if "tsid=%d" % (tsid) not in ev:
979 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
981 tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
983 raise Exception("DELTS failed (still in tspec list)")
985 def connect(self, ssid=None, ssid2=None, **kwargs):
986 logger.info("Connect STA " + self.ifname + " to AP")
987 id = self.add_network()
989 self.set_network_quoted(id, "ssid", ssid)
991 self.set_network(id, "ssid", ssid2)
993 quoted = [ "psk", "identity", "anonymous_identity", "password",
994 "ca_cert", "client_cert", "private_key",
995 "private_key_passwd", "ca_cert2", "client_cert2",
996 "private_key2", "phase1", "phase2", "domain_suffix_match",
997 "altsubject_match", "subject_match", "pac_file", "dh_file",
998 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
1000 for field in quoted:
1001 if field in kwargs and kwargs[field]:
1002 self.set_network_quoted(id, field, kwargs[field])
1004 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
1005 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
1006 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
1007 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
1008 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
1009 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
1010 "disable_ht40", "disable_sgi", "disable_ldpc",
1011 "ht40_intolerant", "update_identifier", "mac_addr",
1012 "erp", "bg_scan_period", "bssid_blacklist",
1013 "bssid_whitelist", "mem_only_psk", "eap_workaround",
1015 for field in not_quoted:
1016 if field in kwargs and kwargs[field]:
1017 self.set_network(id, field, kwargs[field])
1019 if "raw_psk" in kwargs and kwargs['raw_psk']:
1020 self.set_network(id, "psk", kwargs['raw_psk'])
1021 if "password_hex" in kwargs and kwargs['password_hex']:
1022 self.set_network(id, "password", kwargs['password_hex'])
1023 if "peerkey" in kwargs and kwargs['peerkey']:
1024 self.set_network(id, "peerkey", "1")
1025 if "okc" in kwargs and kwargs['okc']:
1026 self.set_network(id, "proactive_key_caching", "1")
1027 if "ocsp" in kwargs and kwargs['ocsp']:
1028 self.set_network(id, "ocsp", str(kwargs['ocsp']))
1029 if "only_add_network" in kwargs and kwargs['only_add_network']:
1031 if "wait_connect" not in kwargs or kwargs['wait_connect']:
1033 self.connect_network(id, timeout=20)
1035 self.connect_network(id)
1038 self.select_network(id)
1041 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
1043 cmd = "SCAN TYPE=" + type
1047 cmd = cmd + " freq=" + str(freq)
1049 cmd += " only_new=1"
1052 if not "OK" in self.request(cmd):
1053 raise Exception("Failed to trigger scan")
1056 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
1058 raise Exception("Scan timed out")
1060 def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
1061 if not force_scan and self.get_bss(bssid) is not None:
1063 for i in range(0, 10):
1064 self.scan(freq=freq, type="ONLY", only_new=only_new)
1065 if self.get_bss(bssid) is not None:
1067 raise Exception("Could not find BSS " + bssid + " in scan")
1069 def flush_scan_cache(self, freq=2417):
1070 self.request("BSS_FLUSH 0")
1071 self.scan(freq=freq, only_new=True)
1072 res = self.request("SCAN_RESULTS")
1073 if len(res.splitlines()) > 1:
1074 self.request("BSS_FLUSH 0")
1075 self.scan(freq=2422, only_new=True)
1076 res = self.request("SCAN_RESULTS")
1077 if len(res.splitlines()) > 1:
1078 logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
1080 def roam(self, bssid, fail_test=False):
1082 if "OK" not in self.request("ROAM " + bssid):
1083 raise Exception("ROAM failed")
1085 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1087 raise Exception("Unexpected connection")
1090 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
1093 def roam_over_ds(self, bssid, fail_test=False):
1095 if "OK" not in self.request("FT_DS " + bssid):
1096 raise Exception("FT_DS failed")
1098 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
1100 raise Exception("Unexpected connection")
1103 self.wait_connected(timeout=10, error="Roaming with the AP timed out")
1106 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
1107 new_passphrase=None, no_wait=False):
1110 self.request("WPS_REG " + bssid + " " + pin + " " +
1111 new_ssid.encode("hex") + " " + key_mgmt + " " +
1112 cipher + " " + new_passphrase.encode("hex"))
1115 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
1117 self.request("WPS_REG " + bssid + " " + pin)
1120 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
1122 raise Exception("WPS cred timed out")
1123 ev = self.wait_event(["WPS-FAIL"], timeout=15)
1125 raise Exception("WPS timed out")
1126 self.wait_connected(timeout=15)
1129 self.global_request("RELOG")
1131 def wait_completed(self, timeout=10):
1132 for i in range(0, timeout * 2):
1133 if self.get_status_field("wpa_state") == "COMPLETED":
1136 raise Exception("Timeout while waiting for COMPLETED state")
1138 def get_capability(self, field):
1139 res = self.request("GET_CAPABILITY " + field)
1142 return res.split(' ')
1144 def get_bss(self, bssid, ifname=None):
1145 if not ifname or ifname == self.ifname:
1146 res = self.request("BSS " + bssid)
1147 elif ifname == self.group_ifname:
1148 res = self.group_request("BSS " + bssid)
1154 lines = res.splitlines()
1157 [name,value] = l.split('=', 1)
1163 def get_pmksa(self, bssid):
1164 res = self.request("PMKSA")
1165 lines = res.splitlines()
1170 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
1171 vals['index'] = index
1172 vals['pmkid'] = pmkid
1173 vals['expiration'] = expiration
1174 vals['opportunistic'] = opportunistic
1178 def get_sta(self, addr, info=None, next=False):
1179 cmd = "STA-NEXT " if next else "STA "
1181 res = self.request("STA-FIRST")
1183 res = self.request(cmd + addr + " " + info)
1185 res = self.request(cmd + addr)
1186 lines = res.splitlines()
1194 [name,value] = l.split('=', 1)
1198 def mgmt_rx(self, timeout=5):
1199 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
1203 items = ev.split(' ')
1204 field,val = items[1].split('=')
1206 raise Exception("Unexpected MGMT-RX event format: " + ev)
1209 field,val = items[2].split('=')
1210 if field != "datarate":
1211 raise Exception("Unexpected MGMT-RX event format: " + ev)
1212 msg['datarate'] = val
1214 field,val = items[3].split('=')
1215 if field != "ssi_signal":
1216 raise Exception("Unexpected MGMT-RX event format: " + ev)
1217 msg['ssi_signal'] = val
1219 frame = binascii.unhexlify(items[4])
1220 msg['frame'] = frame
1222 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
1224 msg['subtype'] = (hdr[0] >> 4) & 0xf
1226 msg['duration'] = hdr[0]
1228 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1230 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1232 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
1234 msg['seq_ctrl'] = hdr[0]
1235 msg['payload'] = frame[24:]
1239 def wait_connected(self, timeout=10, error="Connection timed out"):
1240 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
1242 raise Exception(error)
1245 def wait_disconnected(self, timeout=None, error="Disconnection timed out"):
1247 timeout = 10 if self.hostname is None else 30
1248 ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
1250 raise Exception(error)
1253 def get_group_ifname(self):
1254 return self.group_ifname if self.group_ifname else self.ifname
1256 def get_config(self):
1257 res = self.request("DUMP")
1258 if res.startswith("FAIL"):
1259 raise Exception("DUMP failed")
1260 lines = res.splitlines()
1263 [name,value] = l.split('=', 1)
1267 def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
1268 method="1000", info="", status=None, cpt=None, role=None):
1270 cmd = "P2P_ASP_PROVISION"
1271 params = "info='%s' method=%s" % (info, method)
1273 cmd = "P2P_ASP_PROVISION_RESP"
1274 params = "status=%d" % status
1276 if role is not None:
1277 params += " role=" + role
1279 params += " cpt=" + cpt
1281 if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1282 (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
1283 raise Exception("%s request failed" % cmd)