]>
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")
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
):
625 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
626 "P2P-GO-NEG-FAILURE"], timeout
)
630 raise Exception("Group formation timed out")
631 if "P2P-GO-NEG-SUCCESS" in ev
:
635 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
639 raise Exception("Group formation timed out")
641 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
642 raise Exception("P2P_CONNECT failed")
644 def wait_event(self
, events
, timeout
=10):
645 start
= os
.times()[4]
647 while self
.mon
.pending():
649 logger
.debug(self
.ifname
+ ": " + ev
)
654 remaining
= start
+ timeout
- now
657 if not self
.mon
.pending(timeout
=remaining
):
661 def wait_global_event(self
, events
, timeout
):
662 if self
.global_iface
is None:
663 self
.wait_event(events
, timeout
)
665 start
= os
.times()[4]
667 while self
.global_mon
.pending():
668 ev
= self
.global_mon
.recv()
669 logger
.debug(self
.ifname
+ "(global): " + ev
)
674 remaining
= start
+ timeout
- now
677 if not self
.global_mon
.pending(timeout
=remaining
):
681 def wait_group_event(self
, events
, timeout
=10):
682 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
683 if self
.gctrl_mon
is None:
685 start
= os
.times()[4]
687 while self
.gctrl_mon
.pending():
688 ev
= self
.gctrl_mon
.recv()
689 logger
.debug(self
.group_ifname
+ ": " + ev
)
694 remaining
= start
+ timeout
- now
697 if not self
.gctrl_mon
.pending(timeout
=remaining
):
701 return self
.wait_event(events
, timeout
)
703 def wait_go_ending_session(self
):
706 self
.gctrl_mon
.detach()
709 self
.gctrl_mon
= None
710 ev
= self
.wait_global_event(["P2P-GROUP-REMOVED"], timeout
=3)
712 raise Exception("Group removal event timed out")
713 if "reason=GO_ENDING_SESSION" not in ev
:
714 raise Exception("Unexpected group removal reason")
716 def dump_monitor(self
):
719 while self
.mon
.pending():
721 logger
.debug(self
.ifname
+ ": " + ev
)
723 while self
.global_mon
and self
.global_mon
.pending():
724 ev
= self
.global_mon
.recv()
725 logger
.debug(self
.ifname
+ "(global): " + ev
)
727 return (count_iface
, count_global
)
729 def remove_group(self
, ifname
=None):
732 self
.gctrl_mon
.detach()
735 self
.gctrl_mon
= None
737 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
738 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
739 raise Exception("Group could not be removed")
740 self
.group_ifname
= None
742 def p2p_start_go(self
, persistent
=None, freq
=None, no_event_clear
=False):
744 cmd
= "P2P_GROUP_ADD"
745 if persistent
is None:
747 elif persistent
is True:
748 cmd
= cmd
+ " persistent"
750 cmd
= cmd
+ " persistent=" + str(persistent
)
752 cmd
= cmd
+ " freq=" + str(freq
)
753 if "OK" in self
.global_request(cmd
):
754 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
756 raise Exception("GO start up timed out")
757 if not no_event_clear
:
759 return self
.group_form_result(ev
)
760 raise Exception("P2P_GROUP_ADD failed")
762 def p2p_go_authorize_client(self
, pin
):
763 cmd
= "WPS_PIN any " + pin
764 if "FAIL" in self
.group_request(cmd
):
765 raise Exception("Failed to authorize client connection on GO")
768 def p2p_go_authorize_client_pbc(self
):
770 if "FAIL" in self
.group_request(cmd
):
771 raise Exception("Failed to authorize client connection on GO")
774 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False,
777 if not self
.discover_peer(go_addr
, social
=social
, freq
=freq
):
778 if social
or not self
.discover_peer(go_addr
, social
=social
):
779 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"], timeout
)
790 raise Exception("Joining the group timed out")
792 return self
.group_form_result(ev
)
793 raise Exception("P2P_CONNECT(join) failed")
795 def tdls_setup(self
, peer
):
796 cmd
= "TDLS_SETUP " + peer
797 if "FAIL" in self
.group_request(cmd
):
798 raise Exception("Failed to request TDLS setup")
801 def tdls_teardown(self
, peer
):
802 cmd
= "TDLS_TEARDOWN " + peer
803 if "FAIL" in self
.group_request(cmd
):
804 raise Exception("Failed to request TDLS teardown")
807 def tdls_link_status(self
, peer
):
808 cmd
= "TDLS_LINK_STATUS " + peer
809 ret
= self
.group_request(cmd
)
811 raise Exception("Failed to request TDLS link status")
815 """Return (tsid, up) tuples representing current tspecs"""
816 res
= self
.request("WMM_AC_STATUS")
817 tspecs
= re
.findall(r
"TSID=(\d+) UP=(\d+)", res
)
818 tspecs
= [tuple(map(int, tspec
)) for tspec
in tspecs
]
820 logger
.debug("tspecs: " + str(tspecs
))
823 def add_ts(self
, tsid
, up
, direction
="downlink", expect_failure
=False,
827 "nominal_msdu_size": 1500,
828 "min_phy_rate": 6000000,
829 "mean_data_rate": 1500,
831 cmd
= "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction
, tsid
, up
)
832 for (key
, value
) in params
.iteritems():
833 cmd
+= " %s=%d" % (key
, value
)
837 if self
.request(cmd
).strip() != "OK":
838 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid
, up
))
841 ev
= self
.wait_event(["TSPEC-REQ-FAILED"], timeout
=2)
843 raise Exception("ADDTS failed (time out while waiting failure)")
844 if "tsid=%d" % (tsid
) not in ev
:
845 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
848 ev
= self
.wait_event(["TSPEC-ADDED"], timeout
=1)
850 raise Exception("ADDTS failed (time out)")
851 if "tsid=%d" % (tsid
) not in ev
:
852 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
854 if not (tsid
, up
) in self
.tspecs():
855 raise Exception("ADDTS failed (tsid not in tspec list)")
857 def del_ts(self
, tsid
):
858 if self
.request("WMM_AC_DELTS %d" % (tsid
)).strip() != "OK":
859 raise Exception("DELTS failed")
861 ev
= self
.wait_event(["TSPEC-REMOVED"], timeout
=1)
863 raise Exception("DELTS failed (time out)")
864 if "tsid=%d" % (tsid
) not in ev
:
865 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
867 tspecs
= [(t
, u
) for (t
, u
) in self
.tspecs() if t
== tsid
]
869 raise Exception("DELTS failed (still in tspec list)")
871 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
872 logger
.info("Connect STA " + self
.ifname
+ " to AP")
873 id = self
.add_network()
875 self
.set_network_quoted(id, "ssid", ssid
)
877 self
.set_network(id, "ssid", ssid2
)
879 quoted
= [ "psk", "identity", "anonymous_identity", "password",
880 "ca_cert", "client_cert", "private_key",
881 "private_key_passwd", "ca_cert2", "client_cert2",
882 "private_key2", "phase1", "phase2", "domain_suffix_match",
883 "altsubject_match", "subject_match", "pac_file", "dh_file",
884 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
887 if field
in kwargs
and kwargs
[field
]:
888 self
.set_network_quoted(id, field
, kwargs
[field
])
890 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
891 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
892 "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
893 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
894 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
895 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
896 "disable_ht40", "disable_sgi", "disable_ldpc",
897 "ht40_intolerant", "update_identifier", "mac_addr",
898 "erp", "bg_scan_period", "bssid_blacklist",
899 "bssid_whitelist", "mem_only_psk", "eap_workaround" ]
900 for field
in not_quoted
:
901 if field
in kwargs
and kwargs
[field
]:
902 self
.set_network(id, field
, kwargs
[field
])
904 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
905 self
.set_network(id, "psk", kwargs
['raw_psk'])
906 if "password_hex" in kwargs
and kwargs
['password_hex']:
907 self
.set_network(id, "password", kwargs
['password_hex'])
908 if "peerkey" in kwargs
and kwargs
['peerkey']:
909 self
.set_network(id, "peerkey", "1")
910 if "okc" in kwargs
and kwargs
['okc']:
911 self
.set_network(id, "proactive_key_caching", "1")
912 if "ocsp" in kwargs
and kwargs
['ocsp']:
913 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
914 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
916 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
918 self
.connect_network(id, timeout
=20)
920 self
.connect_network(id)
923 self
.select_network(id)
926 def scan(self
, type=None, freq
=None, no_wait
=False, only_new
=False):
928 cmd
= "SCAN TYPE=" + type
932 cmd
= cmd
+ " freq=" + str(freq
)
937 if not "OK" in self
.request(cmd
):
938 raise Exception("Failed to trigger scan")
941 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
943 raise Exception("Scan timed out")
945 def scan_for_bss(self
, bssid
, freq
=None, force_scan
=False, only_new
=False):
946 if not force_scan
and self
.get_bss(bssid
) is not None:
948 for i
in range(0, 10):
949 self
.scan(freq
=freq
, type="ONLY", only_new
=only_new
)
950 if self
.get_bss(bssid
) is not None:
952 raise Exception("Could not find BSS " + bssid
+ " in scan")
954 def flush_scan_cache(self
, freq
=2417):
955 self
.request("BSS_FLUSH 0")
956 self
.scan(freq
=freq
, only_new
=True)
957 res
= self
.request("SCAN_RESULTS")
958 if len(res
.splitlines()) > 1:
959 self
.request("BSS_FLUSH 0")
960 self
.scan(freq
=2422, only_new
=True)
961 res
= self
.request("SCAN_RESULTS")
962 if len(res
.splitlines()) > 1:
963 logger
.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res
)
965 def roam(self
, bssid
, fail_test
=False):
967 if "OK" not in self
.request("ROAM " + bssid
):
968 raise Exception("ROAM failed")
970 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
972 raise Exception("Unexpected connection")
975 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
978 def roam_over_ds(self
, bssid
, fail_test
=False):
980 if "OK" not in self
.request("FT_DS " + bssid
):
981 raise Exception("FT_DS failed")
983 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
985 raise Exception("Unexpected connection")
988 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
991 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
992 new_passphrase
=None, no_wait
=False):
995 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
996 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
997 cipher
+ " " + new_passphrase
.encode("hex"))
1000 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
1002 self
.request("WPS_REG " + bssid
+ " " + pin
)
1005 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
1007 raise Exception("WPS cred timed out")
1008 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
1010 raise Exception("WPS timed out")
1011 self
.wait_connected(timeout
=15)
1014 self
.global_request("RELOG")
1016 def wait_completed(self
, timeout
=10):
1017 for i
in range(0, timeout
* 2):
1018 if self
.get_status_field("wpa_state") == "COMPLETED":
1021 raise Exception("Timeout while waiting for COMPLETED state")
1023 def get_capability(self
, field
):
1024 res
= self
.request("GET_CAPABILITY " + field
)
1027 return res
.split(' ')
1029 def get_bss(self
, bssid
, ifname
=None):
1030 if not ifname
or ifname
== self
.ifname
:
1031 res
= self
.request("BSS " + bssid
)
1032 elif ifname
== self
.group_ifname
:
1033 res
= self
.group_request("BSS " + bssid
)
1039 lines
= res
.splitlines()
1042 [name
,value
] = l
.split('=', 1)
1048 def get_pmksa(self
, bssid
):
1049 res
= self
.request("PMKSA")
1050 lines
= res
.splitlines()
1055 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
1056 vals
['index'] = index
1057 vals
['pmkid'] = pmkid
1058 vals
['expiration'] = expiration
1059 vals
['opportunistic'] = opportunistic
1063 def get_sta(self
, addr
, info
=None, next
=False):
1064 cmd
= "STA-NEXT " if next
else "STA "
1066 res
= self
.request("STA-FIRST")
1068 res
= self
.request(cmd
+ addr
+ " " + info
)
1070 res
= self
.request(cmd
+ addr
)
1071 lines
= res
.splitlines()
1079 [name
,value
] = l
.split('=', 1)
1083 def mgmt_rx(self
, timeout
=5):
1084 ev
= self
.wait_event(["MGMT-RX"], timeout
=timeout
)
1088 items
= ev
.split(' ')
1089 field
,val
= items
[1].split('=')
1091 raise Exception("Unexpected MGMT-RX event format: " + ev
)
1093 frame
= binascii
.unhexlify(items
[4])
1094 msg
['frame'] = frame
1096 hdr
= struct
.unpack('<HH6B6B6BH', frame
[0:24])
1098 msg
['subtype'] = (hdr
[0] >> 4) & 0xf
1100 msg
['duration'] = hdr
[0]
1102 msg
['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1104 msg
['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1106 msg
['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1108 msg
['seq_ctrl'] = hdr
[0]
1109 msg
['payload'] = frame
[24:]
1113 def wait_connected(self
, timeout
=10, error
="Connection timed out"):
1114 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
1116 raise Exception(error
)
1119 def wait_disconnected(self
, timeout
=10, error
="Disconnection timed out"):
1120 ev
= self
.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout
=timeout
)
1122 raise Exception(error
)
1125 def get_group_ifname(self
):
1126 return self
.group_ifname
if self
.group_ifname
else self
.ifname
1128 def get_config(self
):
1129 res
= self
.request("DUMP")
1130 if res
.startswith("FAIL"):
1131 raise Exception("DUMP failed")
1132 lines
= res
.splitlines()
1135 [name
,value
] = l
.split('=', 1)
1139 def asp_provision(self
, peer
, adv_id
, adv_mac
, session_id
, session_mac
,
1140 method
="1000", info
="", status
=None, cpt
=None, role
=None):
1142 cmd
= "P2P_ASP_PROVISION"
1143 params
= "info='%s' method=%s" % (info
, method
)
1145 cmd
= "P2P_ASP_PROVISION_RESP"
1146 params
= "status=%d" % status
1148 if role
is not None:
1149 params
+= " role=" + role
1151 params
+= " cpt=" + cpt
1153 if "OK" not in self
.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
1154 (cmd
, peer
, adv_id
, adv_mac
, session_id
, session_mac
, params
)):
1155 raise Exception("%s request failed" % cmd
)