]>
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):
59 groups
= subprocess
.check_output(["id"])
60 group
= "admin" if "(admin)" in groups
else "adm"
63 cmd
= "INTERFACE_ADD " + ifname
+ "\t" + config
+ "\t" + driver
+ "\tDIR=/var/run/wpa_supplicant GROUP=" + group
65 cmd
= cmd
+ '\t' + drv_params
69 cmd
+= '\t' + br_ifname
70 if "FAIL" in self
.global_request(cmd
):
71 raise Exception("Failed to add a dynamic wpa_supplicant interface")
72 self
.set_ifname(ifname
)
74 def interface_remove(self
, ifname
):
76 self
.global_request("INTERFACE_REMOVE " + ifname
)
78 def request(self
, cmd
):
79 logger
.debug(self
.ifname
+ ": CTRL: " + cmd
)
80 return self
.ctrl
.request(cmd
)
82 def global_request(self
, cmd
):
83 if self
.global_iface
is None:
86 ifname
= self
.ifname
or self
.global_iface
87 logger
.debug(ifname
+ ": CTRL(global): " + cmd
)
88 return self
.global_ctrl
.request(cmd
)
90 def group_request(self
, cmd
):
91 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
92 logger
.debug(self
.group_ifname
+ ": CTRL: " + cmd
)
93 gctrl
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
94 return gctrl
.request(cmd
)
95 return self
.request(cmd
)
98 return "PONG" in self
.request("PING")
100 def global_ping(self
):
101 return "PONG" in self
.global_request("PING")
105 res
= self
.request("FLUSH")
107 logger
.info("FLUSH to " + self
.ifname
+ " failed: " + res
)
108 self
.request("SET p2p_add_cli_chan 0")
109 self
.request("SET p2p_no_go_freq ")
110 self
.request("SET p2p_pref_chan ")
111 self
.request("SET p2p_no_group_iface 1")
112 self
.request("SET p2p_go_intent 7")
113 self
.request("SET ignore_old_scan_res 0")
116 self
.gctrl_mon
.detach()
119 self
.gctrl_mon
= None
120 self
.group_ifname
= None
125 state
= self
.get_driver_status_field("scan_state")
126 if "SCAN_STARTED" in state
or "SCAN_REQUESTED" in state
:
127 logger
.info(self
.ifname
+ ": Waiting for scan operation to complete before continuing")
133 logger
.error(self
.ifname
+ ": Driver scan state did not clear")
134 print "Trying to clear cfg80211/mac80211 scan state"
136 cmd
= ["ifconfig", self
.ifname
, "down"]
138 except subprocess
.CalledProcessError
, e
:
139 logger
.info("ifconfig failed: " + str(e
.returncode
))
140 logger
.info(e
.output
)
142 cmd
= ["ifconfig", self
.ifname
, "up"]
144 except subprocess
.CalledProcessError
, e
:
145 logger
.info("ifconfig failed: " + str(e
.returncode
))
146 logger
.info(e
.output
)
148 # The ongoing scan could have discovered BSSes or P2P peers
149 logger
.info("Run FLUSH again since scan was in progress")
150 self
.request("FLUSH")
154 logger
.info("No PING response from " + self
.ifname
+ " after reset")
156 def add_network(self
):
157 id = self
.request("ADD_NETWORK")
159 raise Exception("ADD_NETWORK failed")
162 def remove_network(self
, id):
163 id = self
.request("REMOVE_NETWORK " + str(id))
165 raise Exception("REMOVE_NETWORK failed")
168 def get_network(self
, id, field
):
169 res
= self
.request("GET_NETWORK " + str(id) + " " + field
)
174 def set_network(self
, id, field
, value
):
175 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ " " + value
)
177 raise Exception("SET_NETWORK failed")
180 def set_network_quoted(self
, id, field
, value
):
181 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ ' "' + value
+ '"')
183 raise Exception("SET_NETWORK failed")
186 def list_networks(self
):
187 res
= self
.request("LIST_NETWORKS")
188 lines
= res
.splitlines()
191 if "network id" in l
:
193 [id,ssid
,bssid
,flags
] = l
.split('\t')
196 network
['ssid'] = ssid
197 network
['bssid'] = bssid
198 network
['flags'] = flags
199 networks
.append(network
)
202 def hs20_enable(self
, auto_interworking
=False):
203 self
.request("SET interworking 1")
204 self
.request("SET hs20 1")
205 if auto_interworking
:
206 self
.request("SET auto_interworking 1")
208 self
.request("SET auto_interworking 0")
211 id = self
.request("ADD_CRED")
213 raise Exception("ADD_CRED failed")
216 def remove_cred(self
, id):
217 id = self
.request("REMOVE_CRED " + str(id))
219 raise Exception("REMOVE_CRED failed")
222 def set_cred(self
, id, field
, value
):
223 res
= self
.request("SET_CRED " + str(id) + " " + field
+ " " + value
)
225 raise Exception("SET_CRED failed")
228 def set_cred_quoted(self
, id, field
, value
):
229 res
= self
.request("SET_CRED " + str(id) + " " + field
+ ' "' + value
+ '"')
231 raise Exception("SET_CRED failed")
234 def get_cred(self
, id, field
):
235 return self
.request("GET_CRED " + str(id) + " " + field
)
237 def add_cred_values(self
, params
):
240 quoted
= [ "realm", "username", "password", "domain", "imsi",
241 "excluded_ssid", "milenage", "ca_cert", "client_cert",
242 "private_key", "domain_suffix_match", "provisioning_sp",
243 "roaming_partner", "phase1", "phase2" ]
246 self
.set_cred_quoted(id, field
, params
[field
])
248 not_quoted
= [ "eap", "roaming_consortium", "priority",
249 "required_roaming_consortium", "sp_priority",
250 "max_bss_load", "update_identifier", "req_conn_capab",
251 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
252 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
253 for field
in not_quoted
:
255 self
.set_cred(id, field
, params
[field
])
259 def select_network(self
, id, freq
=None):
261 extra
= " freq=" + freq
264 id = self
.request("SELECT_NETWORK " + str(id) + extra
)
266 raise Exception("SELECT_NETWORK failed")
269 def mesh_group_add(self
, id):
270 id = self
.request("MESH_GROUP_ADD " + str(id))
272 raise Exception("MESH_GROUP_ADD failed")
275 def mesh_group_remove(self
):
276 id = self
.request("MESH_GROUP_REMOVE " + str(self
.ifname
))
278 raise Exception("MESH_GROUP_REMOVE failed")
281 def connect_network(self
, id, timeout
=10):
283 self
.select_network(id)
284 self
.wait_connected(timeout
=timeout
)
287 def get_status(self
, extra
=None):
292 res
= self
.request("STATUS" + extra
)
293 lines
= res
.splitlines()
297 [name
,value
] = l
.split('=', 1)
299 except ValueError, e
:
300 logger
.info(self
.ifname
+ ": Ignore unexpected STATUS line: " + l
)
303 def get_status_field(self
, field
, extra
=None):
304 vals
= self
.get_status(extra
)
309 def get_group_status(self
, extra
=None):
314 res
= self
.group_request("STATUS" + extra
)
315 lines
= res
.splitlines()
319 [name
,value
] = l
.split('=', 1)
321 logger
.info(self
.ifname
+ ": Ignore unexpected status line: " + l
)
326 def get_group_status_field(self
, field
, extra
=None):
327 vals
= self
.get_group_status(extra
)
332 def get_driver_status(self
):
333 res
= self
.request("STATUS-DRIVER")
334 lines
= res
.splitlines()
338 [name
,value
] = l
.split('=', 1)
340 logger
.info(self
.ifname
+ ": Ignore unexpected status-driver line: " + l
)
345 def get_driver_status_field(self
, field
):
346 vals
= self
.get_driver_status()
352 mcc
= int(self
.get_driver_status_field('capa.num_multichan_concurrent'))
353 return 1 if mcc
< 2 else mcc
356 res
= self
.request("MIB")
357 lines
= res
.splitlines()
361 [name
,value
] = l
.split('=', 1)
363 except ValueError, e
:
364 logger
.info(self
.ifname
+ ": Ignore unexpected MIB line: " + l
)
367 def p2p_dev_addr(self
):
368 return self
.get_status_field("p2p_device_address")
370 def p2p_interface_addr(self
):
371 return self
.get_group_status_field("address")
375 res
= self
.p2p_interface_addr()
377 res
= self
.p2p_dev_addr()
380 def p2p_listen(self
):
381 return self
.global_request("P2P_LISTEN")
383 def p2p_find(self
, social
=False, progressive
=False, dev_id
=None,
384 dev_type
=None, delay
=None):
387 cmd
= cmd
+ " type=social"
389 cmd
= cmd
+ " type=progressive"
391 cmd
= cmd
+ " dev_id=" + dev_id
393 cmd
= cmd
+ " dev_type=" + dev_type
395 cmd
= cmd
+ " delay=" + str(delay
)
396 return self
.global_request(cmd
)
398 def p2p_stop_find(self
):
399 return self
.global_request("P2P_STOP_FIND")
401 def wps_read_pin(self
):
402 self
.pin
= self
.request("WPS_PIN get").rstrip("\n")
403 if "FAIL" in self
.pin
:
404 raise Exception("Could not generate PIN")
407 def peer_known(self
, peer
, full
=True):
408 res
= self
.global_request("P2P_PEER " + peer
)
409 if peer
.lower() not in res
.lower():
413 return "[PROBE_REQ_ONLY]" not in res
415 def discover_peer(self
, peer
, full
=True, timeout
=15, social
=True, force_find
=False):
416 logger
.info(self
.ifname
+ ": Trying to discover peer " + peer
)
417 if not force_find
and self
.peer_known(peer
, full
):
419 self
.p2p_find(social
)
421 while count
< timeout
* 4:
424 if self
.peer_known(peer
, full
):
428 def get_peer(self
, peer
):
429 res
= self
.global_request("P2P_PEER " + peer
)
430 if peer
.lower() not in res
.lower():
431 raise Exception("Peer information not available")
432 lines
= res
.splitlines()
436 [name
,value
] = l
.split('=', 1)
440 def group_form_result(self
, ev
, expect_failure
=False, go_neg_res
=None):
442 if "P2P-GROUP-STARTED" in ev
:
443 raise Exception("Group formation succeeded when expecting failure")
444 exp
= r
'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
445 s
= re
.split(exp
, ev
)
449 res
['result'] = 'go-neg-failed'
450 res
['status'] = int(s
[2])
453 if "P2P-GROUP-STARTED" not in ev
:
454 raise Exception("No P2P-GROUP-STARTED event seen")
456 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.]*)'
457 s
= re
.split(exp
, ev
)
459 exp
= r
'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
460 s
= re
.split(exp
, ev
)
462 raise Exception("Could not parse P2P-GROUP-STARTED")
464 res
['result'] = 'success'
466 self
.group_ifname
= s
[2]
468 self
.gctrl_mon
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
469 self
.gctrl_mon
.attach()
471 logger
.debug("Could not open monitor socket for group interface")
472 self
.gctrl_mon
= None
476 if "[PERSISTENT]" in ev
:
477 res
['persistent'] = True
479 res
['persistent'] = False
480 p
= re
.match(r
'psk=([0-9a-f]*)', s
[6])
482 res
['psk'] = p
.group(1)
483 p
= re
.match(r
'passphrase="(.*)"', s
[6])
485 res
['passphrase'] = p
.group(1)
486 res
['go_dev_addr'] = s
[7]
488 if len(s
) > 8 and len(s
[8]) > 0:
489 res
['ip_addr'] = s
[8]
491 res
['ip_mask'] = s
[9]
493 res
['go_ip_addr'] = s
[10]
496 exp
= r
'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
497 s
= re
.split(exp
, go_neg_res
)
499 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
500 res
['go_neg_role'] = s
[2]
501 res
['go_neg_freq'] = s
[3]
505 def p2p_go_neg_auth(self
, peer
, pin
, method
, go_intent
=None, persistent
=False, freq
=None):
506 if not self
.discover_peer(peer
):
507 raise Exception("Peer " + peer
+ " not found")
510 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
+ " auth"
512 cmd
= "P2P_CONNECT " + peer
+ " " + method
+ " auth"
514 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
516 cmd
= cmd
+ ' freq=' + str(freq
)
518 cmd
= cmd
+ " persistent"
519 if "OK" in self
.global_request(cmd
):
521 raise Exception("P2P_CONNECT (auth) failed")
523 def p2p_go_neg_auth_result(self
, timeout
=1, expect_failure
=False):
525 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
526 "P2P-GO-NEG-FAILURE"], timeout
);
530 raise Exception("Group formation timed out")
531 if "P2P-GO-NEG-SUCCESS" in ev
:
533 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
);
537 raise Exception("Group formation timed out")
539 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
541 def p2p_go_neg_init(self
, peer
, pin
, method
, timeout
=0, go_intent
=None, expect_failure
=False, persistent
=False, persistent_id
=None, freq
=None, provdisc
=False, wait_group
=True):
542 if not self
.discover_peer(peer
):
543 raise Exception("Peer " + peer
+ " not found")
546 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
548 cmd
= "P2P_CONNECT " + peer
+ " " + method
550 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
552 cmd
= cmd
+ ' freq=' + str(freq
)
554 cmd
= cmd
+ " persistent"
556 cmd
= cmd
+ " persistent=" + persistent_id
558 cmd
= cmd
+ " provdisc"
559 if "OK" in self
.global_request(cmd
):
564 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
565 "P2P-GO-NEG-FAILURE"], timeout
)
569 raise Exception("Group formation timed out")
570 if "P2P-GO-NEG-SUCCESS" in ev
:
574 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
578 raise Exception("Group formation timed out")
580 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
581 raise Exception("P2P_CONNECT failed")
583 def wait_event(self
, events
, timeout
=10):
584 start
= os
.times()[4]
586 while self
.mon
.pending():
588 logger
.debug(self
.ifname
+ ": " + ev
)
593 remaining
= start
+ timeout
- now
596 if not self
.mon
.pending(timeout
=remaining
):
600 def wait_global_event(self
, events
, timeout
):
601 if self
.global_iface
is None:
602 self
.wait_event(events
, timeout
)
604 start
= os
.times()[4]
606 while self
.global_mon
.pending():
607 ev
= self
.global_mon
.recv()
608 logger
.debug(self
.ifname
+ "(global): " + ev
)
613 remaining
= start
+ timeout
- now
616 if not self
.global_mon
.pending(timeout
=remaining
):
620 def wait_group_event(self
, events
, timeout
=10):
621 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
622 if self
.gctrl_mon
is None:
624 start
= os
.times()[4]
626 while self
.gctrl_mon
.pending():
627 ev
= self
.gctrl_mon
.recv()
628 logger
.debug(self
.group_ifname
+ ": " + ev
)
633 remaining
= start
+ timeout
- now
636 if not self
.gctrl_mon
.pending(timeout
=remaining
):
640 return self
.wait_event(events
, timeout
)
642 def wait_go_ending_session(self
):
645 self
.gctrl_mon
.detach()
648 self
.gctrl_mon
= None
649 ev
= self
.wait_global_event(["P2P-GROUP-REMOVED"], timeout
=3)
651 raise Exception("Group removal event timed out")
652 if "reason=GO_ENDING_SESSION" not in ev
:
653 raise Exception("Unexpected group removal reason")
655 def dump_monitor(self
):
656 while self
.mon
.pending():
658 logger
.debug(self
.ifname
+ ": " + ev
)
659 while self
.global_mon
and self
.global_mon
.pending():
660 ev
= self
.global_mon
.recv()
661 logger
.debug(self
.ifname
+ "(global): " + ev
)
663 def remove_group(self
, ifname
=None):
666 self
.gctrl_mon
.detach()
669 self
.gctrl_mon
= None
671 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
672 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
673 raise Exception("Group could not be removed")
674 self
.group_ifname
= None
676 def p2p_start_go(self
, persistent
=None, freq
=None, no_event_clear
=False):
678 cmd
= "P2P_GROUP_ADD"
679 if persistent
is None:
681 elif persistent
is True:
682 cmd
= cmd
+ " persistent"
684 cmd
= cmd
+ " persistent=" + str(persistent
)
686 cmd
= cmd
+ " freq=" + str(freq
)
687 if "OK" in self
.global_request(cmd
):
688 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
690 raise Exception("GO start up timed out")
691 if not no_event_clear
:
693 return self
.group_form_result(ev
)
694 raise Exception("P2P_GROUP_ADD failed")
696 def p2p_go_authorize_client(self
, pin
):
697 cmd
= "WPS_PIN any " + pin
698 if "FAIL" in self
.group_request(cmd
):
699 raise Exception("Failed to authorize client connection on GO")
702 def p2p_go_authorize_client_pbc(self
):
704 if "FAIL" in self
.group_request(cmd
):
705 raise Exception("Failed to authorize client connection on GO")
708 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False,
711 if not self
.discover_peer(go_addr
, social
=social
):
712 if social
or not self
.discover_peer(go_addr
, social
=social
):
713 raise Exception("GO " + go_addr
+ " not found")
715 cmd
= "P2P_CONNECT " + go_addr
+ " " + pin
+ " join"
717 cmd
+= " freq=" + str(freq
)
718 if "OK" in self
.global_request(cmd
):
722 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
724 raise Exception("Joining the group timed out")
726 return self
.group_form_result(ev
)
727 raise Exception("P2P_CONNECT(join) failed")
729 def tdls_setup(self
, peer
):
730 cmd
= "TDLS_SETUP " + peer
731 if "FAIL" in self
.group_request(cmd
):
732 raise Exception("Failed to request TDLS setup")
735 def tdls_teardown(self
, peer
):
736 cmd
= "TDLS_TEARDOWN " + peer
737 if "FAIL" in self
.group_request(cmd
):
738 raise Exception("Failed to request TDLS teardown")
742 """Return (tsid, up) tuples representing current tspecs"""
743 res
= self
.request("WMM_AC_STATUS")
744 tspecs
= re
.findall(r
"TSID=(\d+) UP=(\d+)", res
)
745 tspecs
= [tuple(map(int, tspec
)) for tspec
in tspecs
]
747 logger
.debug("tspecs: " + str(tspecs
))
750 def add_ts(self
, tsid
, up
, direction
="downlink", expect_failure
=False,
754 "nominal_msdu_size": 1500,
755 "min_phy_rate": 6000000,
756 "mean_data_rate": 1500,
758 cmd
= "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction
, tsid
, up
)
759 for (key
, value
) in params
.iteritems():
760 cmd
+= " %s=%d" % (key
, value
)
764 if self
.request(cmd
).strip() != "OK":
765 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid
, up
))
768 ev
= self
.wait_event(["TSPEC-REQ-FAILED"], timeout
=2)
770 raise Exception("ADDTS failed (time out while waiting failure)")
771 if "tsid=%d" % (tsid
) not in ev
:
772 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
775 ev
= self
.wait_event(["TSPEC-ADDED"], timeout
=1)
777 raise Exception("ADDTS failed (time out)")
778 if "tsid=%d" % (tsid
) not in ev
:
779 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
781 if not (tsid
, up
) in self
.tspecs():
782 raise Exception("ADDTS failed (tsid not in tspec list)")
784 def del_ts(self
, tsid
):
785 if self
.request("WMM_AC_DELTS %d" % (tsid
)).strip() != "OK":
786 raise Exception("DELTS failed")
788 ev
= self
.wait_event(["TSPEC-REMOVED"], timeout
=1)
790 raise Exception("DELTS failed (time out)")
791 if "tsid=%d" % (tsid
) not in ev
:
792 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
794 tspecs
= [(t
, u
) for (t
, u
) in self
.tspecs() if t
== tsid
]
796 raise Exception("DELTS failed (still in tspec list)")
798 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
799 logger
.info("Connect STA " + self
.ifname
+ " to AP")
800 id = self
.add_network()
802 self
.set_network_quoted(id, "ssid", ssid
)
804 self
.set_network(id, "ssid", ssid2
)
806 quoted
= [ "psk", "identity", "anonymous_identity", "password",
807 "ca_cert", "client_cert", "private_key",
808 "private_key_passwd", "ca_cert2", "client_cert2",
809 "private_key2", "phase1", "phase2", "domain_suffix_match",
810 "altsubject_match", "subject_match", "pac_file", "dh_file",
811 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
814 if field
in kwargs
and kwargs
[field
]:
815 self
.set_network_quoted(id, field
, kwargs
[field
])
817 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
818 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
819 "wep_tx_keyidx", "scan_freq", "eap",
820 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
821 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
822 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
823 "disable_ht40", "disable_sgi", "disable_ldpc",
824 "ht40_intolerant", "update_identifier", "mac_addr",
825 "erp", "bg_scan_period", "bssid_blacklist",
827 for field
in not_quoted
:
828 if field
in kwargs
and kwargs
[field
]:
829 self
.set_network(id, field
, kwargs
[field
])
831 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
832 self
.set_network(id, "psk", kwargs
['raw_psk'])
833 if "password_hex" in kwargs
and kwargs
['password_hex']:
834 self
.set_network(id, "password", kwargs
['password_hex'])
835 if "peerkey" in kwargs
and kwargs
['peerkey']:
836 self
.set_network(id, "peerkey", "1")
837 if "okc" in kwargs
and kwargs
['okc']:
838 self
.set_network(id, "proactive_key_caching", "1")
839 if "ocsp" in kwargs
and kwargs
['ocsp']:
840 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
841 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
843 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
845 self
.connect_network(id, timeout
=20)
847 self
.connect_network(id)
850 self
.select_network(id)
853 def scan(self
, type=None, freq
=None, no_wait
=False, only_new
=False):
855 cmd
= "SCAN TYPE=" + type
859 cmd
= cmd
+ " freq=" + str(freq
)
864 if not "OK" in self
.request(cmd
):
865 raise Exception("Failed to trigger scan")
868 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
870 raise Exception("Scan timed out")
872 def scan_for_bss(self
, bssid
, freq
=None, force_scan
=False, only_new
=False):
873 if not force_scan
and self
.get_bss(bssid
) is not None:
875 for i
in range(0, 10):
876 self
.scan(freq
=freq
, type="ONLY", only_new
=only_new
)
877 if self
.get_bss(bssid
) is not None:
879 raise Exception("Could not find BSS " + bssid
+ " in scan")
881 def flush_scan_cache(self
, freq
=2417):
882 self
.request("BSS_FLUSH 0")
883 self
.scan(freq
=freq
, only_new
=True)
885 def roam(self
, bssid
, fail_test
=False):
887 if "OK" not in self
.request("ROAM " + bssid
):
888 raise Exception("ROAM failed")
890 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
892 raise Exception("Unexpected connection")
895 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
898 def roam_over_ds(self
, bssid
, fail_test
=False):
900 if "OK" not in self
.request("FT_DS " + bssid
):
901 raise Exception("FT_DS failed")
903 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
905 raise Exception("Unexpected connection")
908 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
911 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
912 new_passphrase
=None, no_wait
=False):
915 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
916 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
917 cipher
+ " " + new_passphrase
.encode("hex"))
920 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
922 self
.request("WPS_REG " + bssid
+ " " + pin
)
925 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
927 raise Exception("WPS cred timed out")
928 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
930 raise Exception("WPS timed out")
931 self
.wait_connected(timeout
=15)
934 self
.global_request("RELOG")
936 def wait_completed(self
, timeout
=10):
937 for i
in range(0, timeout
* 2):
938 if self
.get_status_field("wpa_state") == "COMPLETED":
941 raise Exception("Timeout while waiting for COMPLETED state")
943 def get_capability(self
, field
):
944 res
= self
.request("GET_CAPABILITY " + field
)
947 return res
.split(' ')
949 def get_bss(self
, bssid
, ifname
=None):
950 if not ifname
or ifname
== self
.ifname
:
951 res
= self
.request("BSS " + bssid
)
952 elif ifname
== self
.group_ifname
:
953 res
= self
.group_request("BSS " + bssid
)
959 lines
= res
.splitlines()
962 [name
,value
] = l
.split('=', 1)
968 def get_pmksa(self
, bssid
):
969 res
= self
.request("PMKSA")
970 lines
= res
.splitlines()
975 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
976 vals
['index'] = index
977 vals
['pmkid'] = pmkid
978 vals
['expiration'] = expiration
979 vals
['opportunistic'] = opportunistic
983 def get_sta(self
, addr
, info
=None, next
=False):
984 cmd
= "STA-NEXT " if next
else "STA "
986 res
= self
.request("STA-FIRST")
988 res
= self
.request(cmd
+ addr
+ " " + info
)
990 res
= self
.request(cmd
+ addr
)
991 lines
= res
.splitlines()
999 [name
,value
] = l
.split('=', 1)
1003 def mgmt_rx(self
, timeout
=5):
1004 ev
= self
.wait_event(["MGMT-RX"], timeout
=timeout
)
1008 items
= ev
.split(' ')
1009 field
,val
= items
[1].split('=')
1011 raise Exception("Unexpected MGMT-RX event format: " + ev
)
1013 frame
= binascii
.unhexlify(items
[4])
1014 msg
['frame'] = frame
1016 hdr
= struct
.unpack('<HH6B6B6BH', frame
[0:24])
1018 msg
['subtype'] = (hdr
[0] >> 4) & 0xf
1020 msg
['duration'] = hdr
[0]
1022 msg
['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1024 msg
['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1026 msg
['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1028 msg
['seq_ctrl'] = hdr
[0]
1029 msg
['payload'] = frame
[24:]
1033 def wait_connected(self
, timeout
=10, error
="Connection timed out"):
1034 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
1036 raise Exception(error
)
1039 def wait_disconnected(self
, timeout
=10, error
="Disconnection timed out"):
1040 ev
= self
.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout
=timeout
)
1042 raise Exception(error
)
1045 def get_group_ifname(self
):
1046 return self
.group_ifname
if self
.group_ifname
else self
.ifname