]>
git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/wpasupplicant.py
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")
127 self
.request("SET ignore_old_scan_res 0")
130 self
.gctrl_mon
.detach()
133 self
.gctrl_mon
= None
134 self
.group_ifname
= None
139 state1
= self
.get_driver_status_field("scan_state")
140 p2pdev
= "p2p-dev-" + self
.ifname
141 state2
= self
.get_driver_status_field("scan_state", ifname
=p2pdev
)
142 states
= str(state1
) + " " + str(state2
)
143 if "SCAN_STARTED" in states
or "SCAN_REQUESTED" in states
:
144 logger
.info(self
.ifname
+ ": Waiting for scan operation to complete before continuing")
150 logger
.error(self
.ifname
+ ": Driver scan state did not clear")
151 print "Trying to clear cfg80211/mac80211 scan state"
153 cmd
= ["ifconfig", self
.ifname
, "down"]
155 except subprocess
.CalledProcessError
, e
:
156 logger
.info("ifconfig failed: " + str(e
.returncode
))
157 logger
.info(e
.output
)
159 cmd
= ["ifconfig", self
.ifname
, "up"]
161 except subprocess
.CalledProcessError
, e
:
162 logger
.info("ifconfig failed: " + str(e
.returncode
))
163 logger
.info(e
.output
)
165 # The ongoing scan could have discovered BSSes or P2P peers
166 logger
.info("Run FLUSH again since scan was in progress")
167 self
.request("FLUSH")
171 logger
.info("No PING response from " + self
.ifname
+ " after reset")
173 def add_network(self
):
174 id = self
.request("ADD_NETWORK")
176 raise Exception("ADD_NETWORK failed")
179 def remove_network(self
, id):
180 id = self
.request("REMOVE_NETWORK " + str(id))
182 raise Exception("REMOVE_NETWORK failed")
185 def get_network(self
, id, field
):
186 res
= self
.request("GET_NETWORK " + str(id) + " " + field
)
191 def set_network(self
, id, field
, value
):
192 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ " " + value
)
194 raise Exception("SET_NETWORK failed")
197 def set_network_quoted(self
, id, field
, value
):
198 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ ' "' + value
+ '"')
200 raise Exception("SET_NETWORK failed")
203 def list_networks(self
, p2p
=False):
205 res
= self
.global_request("LIST_NETWORKS")
207 res
= self
.request("LIST_NETWORKS")
208 lines
= res
.splitlines()
211 if "network id" in l
:
213 [id,ssid
,bssid
,flags
] = l
.split('\t')
216 network
['ssid'] = ssid
217 network
['bssid'] = bssid
218 network
['flags'] = flags
219 networks
.append(network
)
222 def hs20_enable(self
, auto_interworking
=False):
223 self
.request("SET interworking 1")
224 self
.request("SET hs20 1")
225 if auto_interworking
:
226 self
.request("SET auto_interworking 1")
228 self
.request("SET auto_interworking 0")
230 def interworking_add_network(self
, bssid
):
231 id = self
.request("INTERWORKING_ADD_NETWORK " + bssid
)
232 if "FAIL" in id or "OK" in id:
233 raise Exception("INTERWORKING_ADD_NETWORK failed")
237 id = self
.request("ADD_CRED")
239 raise Exception("ADD_CRED failed")
242 def remove_cred(self
, id):
243 id = self
.request("REMOVE_CRED " + str(id))
245 raise Exception("REMOVE_CRED failed")
248 def set_cred(self
, id, field
, value
):
249 res
= self
.request("SET_CRED " + str(id) + " " + field
+ " " + value
)
251 raise Exception("SET_CRED failed")
254 def set_cred_quoted(self
, id, field
, value
):
255 res
= self
.request("SET_CRED " + str(id) + " " + field
+ ' "' + value
+ '"')
257 raise Exception("SET_CRED failed")
260 def get_cred(self
, id, field
):
261 return self
.request("GET_CRED " + str(id) + " " + field
)
263 def add_cred_values(self
, params
):
266 quoted
= [ "realm", "username", "password", "domain", "imsi",
267 "excluded_ssid", "milenage", "ca_cert", "client_cert",
268 "private_key", "domain_suffix_match", "provisioning_sp",
269 "roaming_partner", "phase1", "phase2" ]
272 self
.set_cred_quoted(id, field
, params
[field
])
274 not_quoted
= [ "eap", "roaming_consortium", "priority",
275 "required_roaming_consortium", "sp_priority",
276 "max_bss_load", "update_identifier", "req_conn_capab",
277 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
278 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
279 for field
in not_quoted
:
281 self
.set_cred(id, field
, params
[field
])
285 def select_network(self
, id, freq
=None):
287 extra
= " freq=" + str(freq
)
290 id = self
.request("SELECT_NETWORK " + str(id) + extra
)
292 raise Exception("SELECT_NETWORK failed")
295 def mesh_group_add(self
, id):
296 id = self
.request("MESH_GROUP_ADD " + str(id))
298 raise Exception("MESH_GROUP_ADD failed")
301 def mesh_group_remove(self
):
302 id = self
.request("MESH_GROUP_REMOVE " + str(self
.ifname
))
304 raise Exception("MESH_GROUP_REMOVE failed")
307 def connect_network(self
, id, timeout
=10):
309 self
.select_network(id)
310 self
.wait_connected(timeout
=timeout
)
313 def get_status(self
, extra
=None):
318 res
= self
.request("STATUS" + extra
)
319 lines
= res
.splitlines()
323 [name
,value
] = l
.split('=', 1)
325 except ValueError, e
:
326 logger
.info(self
.ifname
+ ": Ignore unexpected STATUS line: " + l
)
329 def get_status_field(self
, field
, extra
=None):
330 vals
= self
.get_status(extra
)
335 def get_group_status(self
, extra
=None):
340 res
= self
.group_request("STATUS" + extra
)
341 lines
= res
.splitlines()
345 [name
,value
] = l
.split('=', 1)
347 logger
.info(self
.ifname
+ ": Ignore unexpected status line: " + l
)
352 def get_group_status_field(self
, field
, extra
=None):
353 vals
= self
.get_group_status(extra
)
358 def get_driver_status(self
, ifname
=None):
360 res
= self
.request("STATUS-DRIVER")
362 res
= self
.global_request("IFNAME=%s STATUS-DRIVER" % ifname
)
363 if res
.startswith("FAIL"):
365 lines
= res
.splitlines()
369 [name
,value
] = l
.split('=', 1)
371 logger
.info(self
.ifname
+ ": Ignore unexpected status-driver line: " + l
)
376 def get_driver_status_field(self
, field
, ifname
=None):
377 vals
= self
.get_driver_status(ifname
)
383 mcc
= int(self
.get_driver_status_field('capa.num_multichan_concurrent'))
384 return 1 if mcc
< 2 else mcc
387 res
= self
.request("MIB")
388 lines
= res
.splitlines()
392 [name
,value
] = l
.split('=', 1)
394 except ValueError, e
:
395 logger
.info(self
.ifname
+ ": Ignore unexpected MIB line: " + l
)
398 def p2p_dev_addr(self
):
399 return self
.get_status_field("p2p_device_address")
401 def p2p_interface_addr(self
):
402 return self
.get_group_status_field("address")
406 res
= self
.p2p_interface_addr()
408 res
= self
.p2p_dev_addr()
411 def p2p_listen(self
):
412 return self
.global_request("P2P_LISTEN")
414 def p2p_ext_listen(self
, period
, interval
):
415 return self
.global_request("P2P_EXT_LISTEN %d %d" % (period
, interval
))
417 def p2p_cancel_ext_listen(self
):
418 return self
.global_request("P2P_EXT_LISTEN")
420 def p2p_find(self
, social
=False, progressive
=False, dev_id
=None,
421 dev_type
=None, delay
=None, freq
=None):
424 cmd
= cmd
+ " type=social"
426 cmd
= cmd
+ " type=progressive"
428 cmd
= cmd
+ " dev_id=" + dev_id
430 cmd
= cmd
+ " dev_type=" + dev_type
432 cmd
= cmd
+ " delay=" + str(delay
)
434 cmd
= cmd
+ " freq=" + str(freq
)
435 return self
.global_request(cmd
)
437 def p2p_stop_find(self
):
438 return self
.global_request("P2P_STOP_FIND")
440 def wps_read_pin(self
):
441 self
.pin
= self
.request("WPS_PIN get").rstrip("\n")
442 if "FAIL" in self
.pin
:
443 raise Exception("Could not generate PIN")
446 def peer_known(self
, peer
, full
=True):
447 res
= self
.global_request("P2P_PEER " + peer
)
448 if peer
.lower() not in res
.lower():
452 return "[PROBE_REQ_ONLY]" not in res
454 def discover_peer(self
, peer
, full
=True, timeout
=15, social
=True,
455 force_find
=False, freq
=None):
456 logger
.info(self
.ifname
+ ": Trying to discover peer " + peer
)
457 if not force_find
and self
.peer_known(peer
, full
):
459 self
.p2p_find(social
, freq
=freq
)
461 while count
< timeout
* 4:
464 if self
.peer_known(peer
, full
):
468 def get_peer(self
, peer
):
469 res
= self
.global_request("P2P_PEER " + peer
)
470 if peer
.lower() not in res
.lower():
471 raise Exception("Peer information not available")
472 lines
= res
.splitlines()
476 [name
,value
] = l
.split('=', 1)
480 def group_form_result(self
, ev
, expect_failure
=False, go_neg_res
=None):
482 if "P2P-GROUP-STARTED" in ev
:
483 raise Exception("Group formation succeeded when expecting failure")
484 exp
= r
'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
485 s
= re
.split(exp
, ev
)
489 res
['result'] = 'go-neg-failed'
490 res
['status'] = int(s
[2])
493 if "P2P-GROUP-STARTED" not in ev
:
494 raise Exception("No P2P-GROUP-STARTED event seen")
496 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.]*)'
497 s
= re
.split(exp
, ev
)
499 exp
= r
'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
500 s
= re
.split(exp
, ev
)
502 raise Exception("Could not parse P2P-GROUP-STARTED")
504 res
['result'] = 'success'
506 self
.group_ifname
= s
[2]
508 self
.gctrl_mon
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
509 self
.gctrl_mon
.attach()
511 logger
.debug("Could not open monitor socket for group interface")
512 self
.gctrl_mon
= None
516 if "[PERSISTENT]" in ev
:
517 res
['persistent'] = True
519 res
['persistent'] = False
520 p
= re
.match(r
'psk=([0-9a-f]*)', s
[6])
522 res
['psk'] = p
.group(1)
523 p
= re
.match(r
'passphrase="(.*)"', s
[6])
525 res
['passphrase'] = p
.group(1)
526 res
['go_dev_addr'] = s
[7]
528 if len(s
) > 8 and len(s
[8]) > 0:
529 res
['ip_addr'] = s
[8]
531 res
['ip_mask'] = s
[9]
533 res
['go_ip_addr'] = s
[10]
536 exp
= r
'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
537 s
= re
.split(exp
, go_neg_res
)
539 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
540 res
['go_neg_role'] = s
[2]
541 res
['go_neg_freq'] = s
[3]
545 def p2p_go_neg_auth(self
, peer
, pin
, method
, go_intent
=None,
546 persistent
=False, freq
=None, freq2
=None,
547 max_oper_chwidth
=None, ht40
=False, vht
=False):
548 if not self
.discover_peer(peer
):
549 raise Exception("Peer " + peer
+ " not found")
552 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
+ " auth"
554 cmd
= "P2P_CONNECT " + peer
+ " " + method
+ " auth"
556 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
558 cmd
= cmd
+ ' freq=' + str(freq
)
560 cmd
= cmd
+ ' freq2=' + str(freq2
)
562 cmd
= cmd
+ ' max_oper_chwidth=' + str(max_oper_chwidth
)
568 cmd
= cmd
+ " persistent"
569 if "OK" in self
.global_request(cmd
):
571 raise Exception("P2P_CONNECT (auth) failed")
573 def p2p_go_neg_auth_result(self
, timeout
=1, expect_failure
=False):
575 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
576 "P2P-GO-NEG-FAILURE"], timeout
);
580 raise Exception("Group formation timed out")
581 if "P2P-GO-NEG-SUCCESS" in ev
:
583 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
);
587 raise Exception("Group formation timed out")
589 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
591 def p2p_go_neg_init(self
, peer
, pin
, method
, timeout
=0, go_intent
=None,
592 expect_failure
=False, persistent
=False,
593 persistent_id
=None, freq
=None, provdisc
=False,
594 wait_group
=True, freq2
=None, max_oper_chwidth
=None,
595 ht40
=False, vht
=False):
596 if not self
.discover_peer(peer
):
597 raise Exception("Peer " + peer
+ " not found")
600 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
602 cmd
= "P2P_CONNECT " + peer
+ " " + method
604 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
606 cmd
= cmd
+ ' freq=' + str(freq
)
608 cmd
= cmd
+ ' freq2=' + str(freq2
)
610 cmd
= cmd
+ ' max_oper_chwidth=' + str(max_oper_chwidth
)
616 cmd
= cmd
+ " persistent"
618 cmd
= cmd
+ " persistent=" + persistent_id
620 cmd
= cmd
+ " provdisc"
621 if "OK" in self
.global_request(cmd
):
626 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
627 "P2P-GO-NEG-FAILURE"], timeout
)
631 raise Exception("Group formation timed out")
632 if "P2P-GO-NEG-SUCCESS" in ev
:
636 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
640 raise Exception("Group formation timed out")
642 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
643 raise Exception("P2P_CONNECT failed")
645 def wait_event(self
, events
, timeout
=10):
646 start
= os
.times()[4]
648 while self
.mon
.pending():
650 logger
.debug(self
.ifname
+ ": " + ev
)
655 remaining
= start
+ timeout
- now
658 if not self
.mon
.pending(timeout
=remaining
):
662 def wait_global_event(self
, events
, timeout
):
663 if self
.global_iface
is None:
664 self
.wait_event(events
, timeout
)
666 start
= os
.times()[4]
668 while self
.global_mon
.pending():
669 ev
= self
.global_mon
.recv()
670 logger
.debug(self
.ifname
+ "(global): " + ev
)
675 remaining
= start
+ timeout
- now
678 if not self
.global_mon
.pending(timeout
=remaining
):
682 def wait_group_event(self
, events
, timeout
=10):
683 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
684 if self
.gctrl_mon
is None:
686 start
= os
.times()[4]
688 while self
.gctrl_mon
.pending():
689 ev
= self
.gctrl_mon
.recv()
690 logger
.debug(self
.group_ifname
+ ": " + ev
)
695 remaining
= start
+ timeout
- now
698 if not self
.gctrl_mon
.pending(timeout
=remaining
):
702 return self
.wait_event(events
, timeout
)
704 def wait_go_ending_session(self
):
707 self
.gctrl_mon
.detach()
710 self
.gctrl_mon
= None
711 ev
= self
.wait_global_event(["P2P-GROUP-REMOVED"], timeout
=3)
713 raise Exception("Group removal event timed out")
714 if "reason=GO_ENDING_SESSION" not in ev
:
715 raise Exception("Unexpected group removal reason")
717 def dump_monitor(self
):
720 while self
.mon
.pending():
722 logger
.debug(self
.ifname
+ ": " + ev
)
724 while self
.global_mon
and self
.global_mon
.pending():
725 ev
= self
.global_mon
.recv()
726 logger
.debug(self
.ifname
+ "(global): " + ev
)
728 return (count_iface
, count_global
)
730 def remove_group(self
, ifname
=None):
733 self
.gctrl_mon
.detach()
736 self
.gctrl_mon
= None
738 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
739 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
740 raise Exception("Group could not be removed")
741 self
.group_ifname
= None
743 def p2p_start_go(self
, persistent
=None, freq
=None, no_event_clear
=False):
745 cmd
= "P2P_GROUP_ADD"
746 if persistent
is None:
748 elif persistent
is True:
749 cmd
= cmd
+ " persistent"
751 cmd
= cmd
+ " persistent=" + str(persistent
)
753 cmd
= cmd
+ " freq=" + str(freq
)
754 if "OK" in self
.global_request(cmd
):
755 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
757 raise Exception("GO start up timed out")
758 if not no_event_clear
:
760 return self
.group_form_result(ev
)
761 raise Exception("P2P_GROUP_ADD failed")
763 def p2p_go_authorize_client(self
, pin
):
764 cmd
= "WPS_PIN any " + pin
765 if "FAIL" in self
.group_request(cmd
):
766 raise Exception("Failed to authorize client connection on GO")
769 def p2p_go_authorize_client_pbc(self
):
771 if "FAIL" in self
.group_request(cmd
):
772 raise Exception("Failed to authorize client connection on GO")
775 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False,
778 if not self
.discover_peer(go_addr
, social
=social
, freq
=freq
):
779 if social
or not self
.discover_peer(go_addr
, social
=social
):
780 raise Exception("GO " + go_addr
+ " not found")
782 cmd
= "P2P_CONNECT " + go_addr
+ " " + pin
+ " join"
784 cmd
+= " freq=" + str(freq
)
785 if "OK" in self
.global_request(cmd
):
789 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
791 raise Exception("Joining the group timed out")
793 return self
.group_form_result(ev
)
794 raise Exception("P2P_CONNECT(join) failed")
796 def tdls_setup(self
, peer
):
797 cmd
= "TDLS_SETUP " + peer
798 if "FAIL" in self
.group_request(cmd
):
799 raise Exception("Failed to request TDLS setup")
802 def tdls_teardown(self
, peer
):
803 cmd
= "TDLS_TEARDOWN " + peer
804 if "FAIL" in self
.group_request(cmd
):
805 raise Exception("Failed to request TDLS teardown")
808 def tdls_link_status(self
, peer
):
809 cmd
= "TDLS_LINK_STATUS " + peer
810 ret
= self
.group_request(cmd
)
812 raise Exception("Failed to request TDLS link status")
816 """Return (tsid, up) tuples representing current tspecs"""
817 res
= self
.request("WMM_AC_STATUS")
818 tspecs
= re
.findall(r
"TSID=(\d+) UP=(\d+)", res
)
819 tspecs
= [tuple(map(int, tspec
)) for tspec
in tspecs
]
821 logger
.debug("tspecs: " + str(tspecs
))
824 def add_ts(self
, tsid
, up
, direction
="downlink", expect_failure
=False,
828 "nominal_msdu_size": 1500,
829 "min_phy_rate": 6000000,
830 "mean_data_rate": 1500,
832 cmd
= "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction
, tsid
, up
)
833 for (key
, value
) in params
.iteritems():
834 cmd
+= " %s=%d" % (key
, value
)
838 if self
.request(cmd
).strip() != "OK":
839 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid
, up
))
842 ev
= self
.wait_event(["TSPEC-REQ-FAILED"], timeout
=2)
844 raise Exception("ADDTS failed (time out while waiting failure)")
845 if "tsid=%d" % (tsid
) not in ev
:
846 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
849 ev
= self
.wait_event(["TSPEC-ADDED"], timeout
=1)
851 raise Exception("ADDTS failed (time out)")
852 if "tsid=%d" % (tsid
) not in ev
:
853 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
855 if not (tsid
, up
) in self
.tspecs():
856 raise Exception("ADDTS failed (tsid not in tspec list)")
858 def del_ts(self
, tsid
):
859 if self
.request("WMM_AC_DELTS %d" % (tsid
)).strip() != "OK":
860 raise Exception("DELTS failed")
862 ev
= self
.wait_event(["TSPEC-REMOVED"], timeout
=1)
864 raise Exception("DELTS failed (time out)")
865 if "tsid=%d" % (tsid
) not in ev
:
866 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
868 tspecs
= [(t
, u
) for (t
, u
) in self
.tspecs() if t
== tsid
]
870 raise Exception("DELTS failed (still in tspec list)")
872 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
873 logger
.info("Connect STA " + self
.ifname
+ " to AP")
874 id = self
.add_network()
876 self
.set_network_quoted(id, "ssid", ssid
)
878 self
.set_network(id, "ssid", ssid2
)
880 quoted
= [ "psk", "identity", "anonymous_identity", "password",
881 "ca_cert", "client_cert", "private_key",
882 "private_key_passwd", "ca_cert2", "client_cert2",
883 "private_key2", "phase1", "phase2", "domain_suffix_match",
884 "altsubject_match", "subject_match", "pac_file", "dh_file",
885 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
888 if field
in kwargs
and kwargs
[field
]:
889 self
.set_network_quoted(id, field
, kwargs
[field
])
891 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
892 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
893 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
894 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
895 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
896 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
897 "disable_ht40", "disable_sgi", "disable_ldpc",
898 "ht40_intolerant", "update_identifier", "mac_addr",
899 "erp", "bg_scan_period", "bssid_blacklist",
900 "bssid_whitelist", "mem_only_psk", "eap_workaround" ]
901 for field
in not_quoted
:
902 if field
in kwargs
and kwargs
[field
]:
903 self
.set_network(id, field
, kwargs
[field
])
905 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
906 self
.set_network(id, "psk", kwargs
['raw_psk'])
907 if "password_hex" in kwargs
and kwargs
['password_hex']:
908 self
.set_network(id, "password", kwargs
['password_hex'])
909 if "peerkey" in kwargs
and kwargs
['peerkey']:
910 self
.set_network(id, "peerkey", "1")
911 if "okc" in kwargs
and kwargs
['okc']:
912 self
.set_network(id, "proactive_key_caching", "1")
913 if "ocsp" in kwargs
and kwargs
['ocsp']:
914 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
915 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
917 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
919 self
.connect_network(id, timeout
=20)
921 self
.connect_network(id)
924 self
.select_network(id)
927 def scan(self
, type=None, freq
=None, no_wait
=False, only_new
=False):
929 cmd
= "SCAN TYPE=" + type
933 cmd
= cmd
+ " freq=" + str(freq
)
938 if not "OK" in self
.request(cmd
):
939 raise Exception("Failed to trigger scan")
942 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
944 raise Exception("Scan timed out")
946 def scan_for_bss(self
, bssid
, freq
=None, force_scan
=False, only_new
=False):
947 if not force_scan
and self
.get_bss(bssid
) is not None:
949 for i
in range(0, 10):
950 self
.scan(freq
=freq
, type="ONLY", only_new
=only_new
)
951 if self
.get_bss(bssid
) is not None:
953 raise Exception("Could not find BSS " + bssid
+ " in scan")
955 def flush_scan_cache(self
, freq
=2417):
956 self
.request("BSS_FLUSH 0")
957 self
.scan(freq
=freq
, only_new
=True)
958 res
= self
.request("SCAN_RESULTS")
959 if len(res
.splitlines()) > 1:
960 self
.request("BSS_FLUSH 0")
961 self
.scan(freq
=2422, only_new
=True)
962 res
= self
.request("SCAN_RESULTS")
963 if len(res
.splitlines()) > 1:
964 logger
.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res
)
966 def roam(self
, bssid
, fail_test
=False):
968 if "OK" not in self
.request("ROAM " + bssid
):
969 raise Exception("ROAM failed")
971 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
973 raise Exception("Unexpected connection")
976 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
979 def roam_over_ds(self
, bssid
, fail_test
=False):
981 if "OK" not in self
.request("FT_DS " + bssid
):
982 raise Exception("FT_DS failed")
984 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
986 raise Exception("Unexpected connection")
989 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
992 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
993 new_passphrase
=None, no_wait
=False):
996 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
997 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
998 cipher
+ " " + new_passphrase
.encode("hex"))
1001 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
1003 self
.request("WPS_REG " + bssid
+ " " + pin
)
1006 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
1008 raise Exception("WPS cred timed out")
1009 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
1011 raise Exception("WPS timed out")
1012 self
.wait_connected(timeout
=15)
1015 self
.global_request("RELOG")
1017 def wait_completed(self
, timeout
=10):
1018 for i
in range(0, timeout
* 2):
1019 if self
.get_status_field("wpa_state") == "COMPLETED":
1022 raise Exception("Timeout while waiting for COMPLETED state")
1024 def get_capability(self
, field
):
1025 res
= self
.request("GET_CAPABILITY " + field
)
1028 return res
.split(' ')
1030 def get_bss(self
, bssid
, ifname
=None):
1031 if not ifname
or ifname
== self
.ifname
:
1032 res
= self
.request("BSS " + bssid
)
1033 elif ifname
== self
.group_ifname
:
1034 res
= self
.group_request("BSS " + bssid
)
1040 lines
= res
.splitlines()
1043 [name
,value
] = l
.split('=', 1)
1049 def get_pmksa(self
, bssid
):
1050 res
= self
.request("PMKSA")
1051 lines
= res
.splitlines()
1056 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
1057 vals
['index'] = index
1058 vals
['pmkid'] = pmkid
1059 vals
['expiration'] = expiration
1060 vals
['opportunistic'] = opportunistic
1064 def get_sta(self
, addr
, info
=None, next
=False):
1065 cmd
= "STA-NEXT " if next
else "STA "
1067 res
= self
.request("STA-FIRST")
1069 res
= self
.request(cmd
+ addr
+ " " + info
)
1071 res
= self
.request(cmd
+ addr
)
1072 lines
= res
.splitlines()
1080 [name
,value
] = l
.split('=', 1)
1084 def mgmt_rx(self
, timeout
=5):
1085 ev
= self
.wait_event(["MGMT-RX"], timeout
=timeout
)
1089 items
= ev
.split(' ')
1090 field
,val
= items
[1].split('=')
1092 raise Exception("Unexpected MGMT-RX event format: " + ev
)
1094 frame
= binascii
.unhexlify(items
[4])
1095 msg
['frame'] = frame
1097 hdr
= struct
.unpack('<HH6B6B6BH', frame
[0:24])
1099 msg
['subtype'] = (hdr
[0] >> 4) & 0xf
1101 msg
['duration'] = hdr
[0]
1103 msg
['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1105 msg
['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1107 msg
['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1109 msg
['seq_ctrl'] = hdr
[0]
1110 msg
['payload'] = frame
[24:]
1114 def wait_connected(self
, timeout
=10, error
="Connection timed out"):
1115 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
1117 raise Exception(error
)
1120 def wait_disconnected(self
, timeout
=10, error
="Disconnection timed out"):
1121 ev
= self
.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout
=timeout
)
1123 raise Exception(error
)
1126 def get_group_ifname(self
):
1127 return self
.group_ifname
if self
.group_ifname
else self
.ifname
1129 def get_config(self
):
1130 res
= self
.request("DUMP")
1131 if res
.startswith("FAIL"):
1132 raise Exception("DUMP failed")
1133 lines
= res
.splitlines()
1136 [name
,value
] = l
.split('=', 1)
1140 def asp_provision(self
, peer
, adv_id
, adv_mac
, session_id
, session_mac
,
1141 method
="1000", info
="", status
=None, cpt
=None, role
=None):
1143 cmd
= "P2P_ASP_PROVISION"
1144 params
= "info='%s' method=%s" % (info
, method
)
1146 cmd
= "P2P_ASP_PROVISION_RESP"
1147 params
= "status=%d" % status
1149 if role
is not None:
1150 params
+= " role=" + role
1152 params
+= " cpt=" + cpt
1154 if "OK" not in self
.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1155 (cmd
, peer
, adv_id
, adv_mac
, session_id
, session_mac
, params
)):
1156 raise Exception("%s request failed" % cmd
)