]>
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 def set_ifname(self
, ifname
):
36 self
.ctrl
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, ifname
))
37 self
.mon
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, ifname
))
40 def remove_ifname(self
):
47 def interface_add(self
, ifname
, config
="", driver
="nl80211", drv_params
=None):
49 groups
= subprocess
.check_output(["id"])
50 group
= "admin" if "(admin)" in groups
else "adm"
53 cmd
= "INTERFACE_ADD " + ifname
+ "\t" + config
+ "\t" + driver
+ "\tDIR=/var/run/wpa_supplicant GROUP=" + group
55 cmd
= cmd
+ '\t' + drv_params
56 if "FAIL" in self
.global_request(cmd
):
57 raise Exception("Failed to add a dynamic wpa_supplicant interface")
58 self
.set_ifname(ifname
)
60 def interface_remove(self
, ifname
):
62 self
.global_request("INTERFACE_REMOVE " + ifname
)
64 def request(self
, cmd
):
65 logger
.debug(self
.ifname
+ ": CTRL: " + cmd
)
66 return self
.ctrl
.request(cmd
)
68 def global_request(self
, cmd
):
69 if self
.global_iface
is None:
72 ifname
= self
.ifname
or self
.global_iface
73 logger
.debug(ifname
+ ": CTRL(global): " + cmd
)
74 return self
.global_ctrl
.request(cmd
)
76 def group_request(self
, cmd
):
77 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
78 logger
.debug(self
.group_ifname
+ ": CTRL: " + cmd
)
79 gctrl
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
80 return gctrl
.request(cmd
)
81 return self
.request(cmd
)
84 return "PONG" in self
.request("PING")
86 def global_ping(self
):
87 return "PONG" in self
.global_request("PING")
91 res
= self
.request("FLUSH")
93 logger
.info("FLUSH to " + self
.ifname
+ " failed: " + res
)
94 self
.request("WPS_ER_STOP")
95 self
.request("SET pmf 0")
96 self
.request("SET p2p_add_cli_chan 0")
97 self
.request("SET p2p_no_go_freq ")
98 self
.request("SET p2p_pref_chan ")
99 self
.request("SET p2p_no_group_iface 1")
100 self
.request("SET p2p_go_intent 7")
101 self
.request("SET ignore_old_scan_res 0")
104 self
.gctrl_mon
.detach()
107 self
.gctrl_mon
= None
108 self
.group_ifname
= None
113 state
= self
.get_driver_status_field("scan_state")
114 if "SCAN_STARTED" in state
or "SCAN_REQUESTED" in state
:
115 logger
.info(self
.ifname
+ ": Waiting for scan operation to complete before continuing")
121 logger
.error(self
.ifname
+ ": Driver scan state did not clear")
122 print "Trying to clear cfg80211/mac80211 scan state"
124 cmd
= ["sudo", "ifconfig", self
.ifname
, "down"]
126 except subprocess
.CalledProcessError
, e
:
127 logger
.info("ifconfig failed: " + str(e
.returncode
))
128 logger
.info(e
.output
)
130 cmd
= ["sudo", "ifconfig", self
.ifname
, "up"]
132 except subprocess
.CalledProcessError
, e
:
133 logger
.info("ifconfig failed: " + str(e
.returncode
))
134 logger
.info(e
.output
)
136 # The ongoing scan could have discovered BSSes or P2P peers
137 logger
.info("Run FLUSH again since scan was in progress")
138 self
.request("FLUSH")
142 logger
.info("No PING response from " + self
.ifname
+ " after reset")
144 def add_network(self
):
145 id = self
.request("ADD_NETWORK")
147 raise Exception("ADD_NETWORK failed")
150 def remove_network(self
, id):
151 id = self
.request("REMOVE_NETWORK " + str(id))
153 raise Exception("REMOVE_NETWORK failed")
156 def get_network(self
, id, field
):
157 res
= self
.request("GET_NETWORK " + str(id) + " " + field
)
162 def set_network(self
, id, field
, value
):
163 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ " " + value
)
165 raise Exception("SET_NETWORK failed")
168 def set_network_quoted(self
, id, field
, value
):
169 res
= self
.request("SET_NETWORK " + str(id) + " " + field
+ ' "' + value
+ '"')
171 raise Exception("SET_NETWORK failed")
174 def list_networks(self
):
175 res
= self
.request("LIST_NETWORKS")
176 lines
= res
.splitlines()
179 if "network id" in l
:
181 [id,ssid
,bssid
,flags
] = l
.split('\t')
184 network
['ssid'] = ssid
185 network
['bssid'] = bssid
186 network
['flags'] = flags
187 networks
.append(network
)
190 def hs20_enable(self
, auto_interworking
=False):
191 self
.request("SET interworking 1")
192 self
.request("SET hs20 1")
193 if auto_interworking
:
194 self
.request("SET auto_interworking 1")
196 self
.request("SET auto_interworking 0")
199 id = self
.request("ADD_CRED")
201 raise Exception("ADD_CRED failed")
204 def remove_cred(self
, id):
205 id = self
.request("REMOVE_CRED " + str(id))
207 raise Exception("REMOVE_CRED failed")
210 def set_cred(self
, id, field
, value
):
211 res
= self
.request("SET_CRED " + str(id) + " " + field
+ " " + value
)
213 raise Exception("SET_CRED failed")
216 def set_cred_quoted(self
, id, field
, value
):
217 res
= self
.request("SET_CRED " + str(id) + " " + field
+ ' "' + value
+ '"')
219 raise Exception("SET_CRED failed")
222 def get_cred(self
, id, field
):
223 return self
.request("GET_CRED " + str(id) + " " + field
)
225 def add_cred_values(self
, params
):
228 quoted
= [ "realm", "username", "password", "domain", "imsi",
229 "excluded_ssid", "milenage", "ca_cert", "client_cert",
230 "private_key", "domain_suffix_match", "provisioning_sp",
231 "roaming_partner", "phase1", "phase2" ]
234 self
.set_cred_quoted(id, field
, params
[field
])
236 not_quoted
= [ "eap", "roaming_consortium", "priority",
237 "required_roaming_consortium", "sp_priority",
238 "max_bss_load", "update_identifier", "req_conn_capab",
239 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
240 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
241 for field
in not_quoted
:
243 self
.set_cred(id, field
, params
[field
])
247 def select_network(self
, id, freq
=None):
249 extra
= " freq=" + freq
252 id = self
.request("SELECT_NETWORK " + str(id) + extra
)
254 raise Exception("SELECT_NETWORK failed")
257 def mesh_group_add(self
, id):
258 id = self
.request("MESH_GROUP_ADD " + str(id))
260 raise Exception("MESH_GROUP_ADD failed")
263 def mesh_group_remove(self
):
264 id = self
.request("MESH_GROUP_REMOVE " + str(self
.ifname
))
266 raise Exception("MESH_GROUP_REMOVE failed")
269 def connect_network(self
, id, timeout
=10):
271 self
.select_network(id)
272 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
274 raise Exception("Association with the AP timed out")
277 def get_status(self
, extra
=None):
282 res
= self
.request("STATUS" + extra
)
283 lines
= res
.splitlines()
287 [name
,value
] = l
.split('=', 1)
289 except ValueError, e
:
290 logger
.info(self
.ifname
+ ": Ignore unexpected STATUS line: " + l
)
293 def get_status_field(self
, field
, extra
=None):
294 vals
= self
.get_status(extra
)
299 def get_group_status(self
, extra
=None):
304 res
= self
.group_request("STATUS" + extra
)
305 lines
= res
.splitlines()
309 [name
,value
] = l
.split('=', 1)
311 logger
.info(self
.ifname
+ ": Ignore unexpected status line: " + l
)
316 def get_group_status_field(self
, field
, extra
=None):
317 vals
= self
.get_group_status(extra
)
322 def get_driver_status(self
):
323 res
= self
.request("STATUS-DRIVER")
324 lines
= res
.splitlines()
328 [name
,value
] = l
.split('=', 1)
330 logger
.info(self
.ifname
+ ": Ignore unexpected status-driver line: " + l
)
335 def get_driver_status_field(self
, field
):
336 vals
= self
.get_driver_status()
342 mcc
= int(self
.get_driver_status_field('capa.num_multichan_concurrent'))
343 return 1 if mcc
< 2 else mcc
346 res
= self
.request("MIB")
347 lines
= res
.splitlines()
351 [name
,value
] = l
.split('=', 1)
353 except ValueError, e
:
354 logger
.info(self
.ifname
+ ": Ignore unexpected MIB line: " + l
)
357 def p2p_dev_addr(self
):
358 return self
.get_status_field("p2p_device_address")
360 def p2p_interface_addr(self
):
361 return self
.get_group_status_field("address")
365 res
= self
.p2p_interface_addr()
367 res
= self
.p2p_dev_addr()
370 def p2p_listen(self
):
371 return self
.global_request("P2P_LISTEN")
373 def p2p_find(self
, social
=False, progressive
=False, dev_id
=None, dev_type
=None):
376 cmd
= cmd
+ " type=social"
378 cmd
= cmd
+ " type=progressive"
380 cmd
= cmd
+ " dev_id=" + dev_id
382 cmd
= cmd
+ " dev_type=" + dev_type
383 return self
.global_request(cmd
)
385 def p2p_stop_find(self
):
386 return self
.global_request("P2P_STOP_FIND")
388 def wps_read_pin(self
):
389 self
.pin
= self
.request("WPS_PIN get").rstrip("\n")
390 if "FAIL" in self
.pin
:
391 raise Exception("Could not generate PIN")
394 def peer_known(self
, peer
, full
=True):
395 res
= self
.global_request("P2P_PEER " + peer
)
396 if peer
.lower() not in res
.lower():
400 return "[PROBE_REQ_ONLY]" not in res
402 def discover_peer(self
, peer
, full
=True, timeout
=15, social
=True, force_find
=False):
403 logger
.info(self
.ifname
+ ": Trying to discover peer " + peer
)
404 if not force_find
and self
.peer_known(peer
, full
):
406 self
.p2p_find(social
)
408 while count
< timeout
* 4:
411 if self
.peer_known(peer
, full
):
415 def get_peer(self
, peer
):
416 res
= self
.global_request("P2P_PEER " + peer
)
417 if peer
.lower() not in res
.lower():
418 raise Exception("Peer information not available")
419 lines
= res
.splitlines()
423 [name
,value
] = l
.split('=', 1)
427 def group_form_result(self
, ev
, expect_failure
=False, go_neg_res
=None):
429 if "P2P-GROUP-STARTED" in ev
:
430 raise Exception("Group formation succeeded when expecting failure")
431 exp
= r
'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
432 s
= re
.split(exp
, ev
)
436 res
['result'] = 'go-neg-failed'
437 res
['status'] = int(s
[2])
440 if "P2P-GROUP-STARTED" not in ev
:
441 raise Exception("No P2P-GROUP-STARTED event seen")
443 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.]*)'
444 s
= re
.split(exp
, ev
)
446 exp
= r
'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
447 s
= re
.split(exp
, ev
)
449 raise Exception("Could not parse P2P-GROUP-STARTED")
451 res
['result'] = 'success'
453 self
.group_ifname
= s
[2]
455 self
.gctrl_mon
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
456 self
.gctrl_mon
.attach()
458 logger
.debug("Could not open monitor socket for group interface")
459 self
.gctrl_mon
= None
463 if "[PERSISTENT]" in ev
:
464 res
['persistent'] = True
466 res
['persistent'] = False
467 p
= re
.match(r
'psk=([0-9a-f]*)', s
[6])
469 res
['psk'] = p
.group(1)
470 p
= re
.match(r
'passphrase="(.*)"', s
[6])
472 res
['passphrase'] = p
.group(1)
473 res
['go_dev_addr'] = s
[7]
475 if len(s
) > 8 and len(s
[8]) > 0:
476 res
['ip_addr'] = s
[8]
478 res
['ip_mask'] = s
[9]
480 res
['go_ip_addr'] = s
[10]
483 exp
= r
'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
484 s
= re
.split(exp
, go_neg_res
)
486 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
487 res
['go_neg_role'] = s
[2]
488 res
['go_neg_freq'] = s
[3]
492 def p2p_go_neg_auth(self
, peer
, pin
, method
, go_intent
=None, persistent
=False, freq
=None):
493 if not self
.discover_peer(peer
):
494 raise Exception("Peer " + peer
+ " not found")
496 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
+ " auth"
498 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
500 cmd
= cmd
+ ' freq=' + str(freq
)
502 cmd
= cmd
+ " persistent"
503 if "OK" in self
.global_request(cmd
):
505 raise Exception("P2P_CONNECT (auth) failed")
507 def p2p_go_neg_auth_result(self
, timeout
=1, expect_failure
=False):
509 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
510 "P2P-GO-NEG-FAILURE"], timeout
);
514 raise Exception("Group formation timed out")
515 if "P2P-GO-NEG-SUCCESS" in ev
:
517 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
);
521 raise Exception("Group formation timed out")
523 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
525 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):
526 if not self
.discover_peer(peer
):
527 raise Exception("Peer " + peer
+ " not found")
530 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
532 cmd
= "P2P_CONNECT " + peer
+ " " + method
534 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
536 cmd
= cmd
+ ' freq=' + str(freq
)
538 cmd
= cmd
+ " persistent"
540 cmd
= cmd
+ " persistent=" + persistent_id
542 cmd
= cmd
+ " provdisc"
543 if "OK" in self
.global_request(cmd
):
548 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
549 "P2P-GO-NEG-FAILURE"], timeout
)
553 raise Exception("Group formation timed out")
554 if "P2P-GO-NEG-SUCCESS" in ev
:
558 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
562 raise Exception("Group formation timed out")
564 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
565 raise Exception("P2P_CONNECT failed")
567 def wait_event(self
, events
, timeout
=10):
568 start
= os
.times()[4]
570 while self
.mon
.pending():
572 logger
.debug(self
.ifname
+ ": " + ev
)
577 remaining
= start
+ timeout
- now
580 if not self
.mon
.pending(timeout
=remaining
):
584 def wait_global_event(self
, events
, timeout
):
585 if self
.global_iface
is None:
586 self
.wait_event(events
, timeout
)
588 start
= os
.times()[4]
590 while self
.global_mon
.pending():
591 ev
= self
.global_mon
.recv()
592 logger
.debug(self
.ifname
+ "(global): " + ev
)
597 remaining
= start
+ timeout
- now
600 if not self
.global_mon
.pending(timeout
=remaining
):
604 def wait_group_event(self
, events
, timeout
=10):
605 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
606 if self
.gctrl_mon
is None:
608 start
= os
.times()[4]
610 while self
.gctrl_mon
.pending():
611 ev
= self
.gctrl_mon
.recv()
612 logger
.debug(self
.group_ifname
+ ": " + ev
)
617 remaining
= start
+ timeout
- now
620 if not self
.gctrl_mon
.pending(timeout
=remaining
):
624 return self
.wait_event(events
, timeout
)
626 def wait_go_ending_session(self
):
629 self
.gctrl_mon
.detach()
632 self
.gctrl_mon
= None
633 ev
= self
.wait_event(["P2P-GROUP-REMOVED"], timeout
=3)
635 raise Exception("Group removal event timed out")
636 if "reason=GO_ENDING_SESSION" not in ev
:
637 raise Exception("Unexpected group removal reason")
639 def dump_monitor(self
):
640 while self
.mon
.pending():
642 logger
.debug(self
.ifname
+ ": " + ev
)
643 while self
.global_mon
.pending():
644 ev
= self
.global_mon
.recv()
645 logger
.debug(self
.ifname
+ "(global): " + ev
)
647 def remove_group(self
, ifname
=None):
650 self
.gctrl_mon
.detach()
653 self
.gctrl_mon
= None
655 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
656 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
657 raise Exception("Group could not be removed")
658 self
.group_ifname
= None
660 def p2p_start_go(self
, persistent
=None, freq
=None):
662 cmd
= "P2P_GROUP_ADD"
663 if persistent
is None:
665 elif persistent
is True:
666 cmd
= cmd
+ " persistent"
668 cmd
= cmd
+ " persistent=" + str(persistent
)
670 cmd
= cmd
+ " freq=" + str(freq
)
671 if "OK" in self
.global_request(cmd
):
672 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
674 raise Exception("GO start up timed out")
676 return self
.group_form_result(ev
)
677 raise Exception("P2P_GROUP_ADD failed")
679 def p2p_go_authorize_client(self
, pin
):
680 cmd
= "WPS_PIN any " + pin
681 if "FAIL" in self
.group_request(cmd
):
682 raise Exception("Failed to authorize client connection on GO")
685 def p2p_go_authorize_client_pbc(self
):
687 if "FAIL" in self
.group_request(cmd
):
688 raise Exception("Failed to authorize client connection on GO")
691 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False,
694 if not self
.discover_peer(go_addr
, social
=social
):
695 if social
or not self
.discover_peer(go_addr
, social
=social
):
696 raise Exception("GO " + go_addr
+ " not found")
698 cmd
= "P2P_CONNECT " + go_addr
+ " " + pin
+ " join"
700 cmd
+= " freq=" + str(freq
)
701 if "OK" in self
.global_request(cmd
):
705 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
707 raise Exception("Joining the group timed out")
709 return self
.group_form_result(ev
)
710 raise Exception("P2P_CONNECT(join) failed")
712 def tdls_setup(self
, peer
):
713 cmd
= "TDLS_SETUP " + peer
714 if "FAIL" in self
.group_request(cmd
):
715 raise Exception("Failed to request TDLS setup")
718 def tdls_teardown(self
, peer
):
719 cmd
= "TDLS_TEARDOWN " + peer
720 if "FAIL" in self
.group_request(cmd
):
721 raise Exception("Failed to request TDLS teardown")
724 def add_ts(self
, tsid
, up
, direction
="downlink", expect_failure
=False,
728 "nominal_msdu_size": 1500,
729 "min_phy_rate": 6000000,
730 "mean_data_rate": 1500,
732 cmd
= "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction
, tsid
, up
)
733 for (key
, value
) in params
.iteritems():
734 cmd
+= " %s=%d" % (key
, value
)
738 if self
.request(cmd
).strip() != "OK":
739 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid
, up
))
742 ev
= self
.wait_event(["TSPEC-REQ-FAILED"], timeout
=2)
744 raise Exception("ADDTS failed (time out while waiting failure)")
745 if "tsid=%d" % (tsid
) not in ev
:
746 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
749 ev
= self
.wait_event(["TSPEC-ADDED"], timeout
=1)
751 raise Exception("ADDTS failed (time out)")
752 if "tsid=%d" % (tsid
) not in ev
:
753 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
755 def del_ts(self
, tsid
):
756 if self
.request("WMM_AC_DELTS %d" % (tsid
)).strip() != "OK":
757 raise Exception("DELTS failed")
759 ev
= self
.wait_event(["TSPEC-REMOVED"], timeout
=1)
761 raise Exception("DELTS failed (time out)")
762 if "tsid=%d" % (tsid
) not in ev
:
763 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
765 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
766 logger
.info("Connect STA " + self
.ifname
+ " to AP")
767 id = self
.add_network()
769 self
.set_network_quoted(id, "ssid", ssid
)
771 self
.set_network(id, "ssid", ssid2
)
773 quoted
= [ "psk", "identity", "anonymous_identity", "password",
774 "ca_cert", "client_cert", "private_key",
775 "private_key_passwd", "ca_cert2", "client_cert2",
776 "private_key2", "phase1", "phase2", "domain_suffix_match",
777 "altsubject_match", "subject_match", "pac_file", "dh_file",
778 "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
780 if field
in kwargs
and kwargs
[field
]:
781 self
.set_network_quoted(id, field
, kwargs
[field
])
783 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
784 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
785 "wep_tx_keyidx", "scan_freq", "eap",
786 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
787 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
788 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
789 "disable_ht40", "disable_sgi", "disable_ldpc",
790 "ht40_intolerant", "update_identifier", "mac_addr",
792 for field
in not_quoted
:
793 if field
in kwargs
and kwargs
[field
]:
794 self
.set_network(id, field
, kwargs
[field
])
796 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
797 self
.set_network(id, "psk", kwargs
['raw_psk'])
798 if "password_hex" in kwargs
and kwargs
['password_hex']:
799 self
.set_network(id, "password", kwargs
['password_hex'])
800 if "peerkey" in kwargs
and kwargs
['peerkey']:
801 self
.set_network(id, "peerkey", "1")
802 if "okc" in kwargs
and kwargs
['okc']:
803 self
.set_network(id, "proactive_key_caching", "1")
804 if "ocsp" in kwargs
and kwargs
['ocsp']:
805 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
806 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
808 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
810 self
.connect_network(id, timeout
=20)
812 self
.connect_network(id)
815 self
.select_network(id)
818 def scan(self
, type=None, freq
=None, no_wait
=False, only_new
=False):
820 cmd
= "SCAN TYPE=" + type
824 cmd
= cmd
+ " freq=" + str(freq
)
829 if not "OK" in self
.request(cmd
):
830 raise Exception("Failed to trigger scan")
833 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
835 raise Exception("Scan timed out")
837 def scan_for_bss(self
, bssid
, freq
=None, force_scan
=False):
838 if not force_scan
and self
.get_bss(bssid
) is not None:
840 for i
in range(0, 10):
841 self
.scan(freq
=freq
, type="ONLY")
842 if self
.get_bss(bssid
) is not None:
844 raise Exception("Could not find BSS " + bssid
+ " in scan")
846 def flush_scan_cache(self
):
847 self
.request("BSS_FLUSH 0")
848 self
.scan(freq
=2412, only_new
=True)
850 def roam(self
, bssid
, fail_test
=False):
852 if "OK" not in self
.request("ROAM " + bssid
):
853 raise Exception("ROAM failed")
855 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
857 raise Exception("Unexpected connection")
860 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=10)
862 raise Exception("Roaming with the AP timed out")
865 def roam_over_ds(self
, bssid
, fail_test
=False):
867 if "OK" not in self
.request("FT_DS " + bssid
):
868 raise Exception("FT_DS failed")
870 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
872 raise Exception("Unexpected connection")
875 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=10)
877 raise Exception("Roaming with the AP timed out")
880 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
881 new_passphrase
=None, no_wait
=False):
884 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
885 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
886 cipher
+ " " + new_passphrase
.encode("hex"))
889 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
891 self
.request("WPS_REG " + bssid
+ " " + pin
)
894 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
896 raise Exception("WPS cred timed out")
897 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
899 raise Exception("WPS timed out")
900 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=15)
902 raise Exception("Association with the AP timed out")
905 self
.global_request("RELOG")
907 def wait_completed(self
, timeout
=10):
908 for i
in range(0, timeout
* 2):
909 if self
.get_status_field("wpa_state") == "COMPLETED":
912 raise Exception("Timeout while waiting for COMPLETED state")
914 def get_capability(self
, field
):
915 res
= self
.request("GET_CAPABILITY " + field
)
918 return res
.split(' ')
920 def get_bss(self
, bssid
):
921 res
= self
.request("BSS " + bssid
)
924 lines
= res
.splitlines()
927 [name
,value
] = l
.split('=', 1)
933 def get_pmksa(self
, bssid
):
934 res
= self
.request("PMKSA")
935 lines
= res
.splitlines()
940 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
941 vals
['index'] = index
942 vals
['pmkid'] = pmkid
943 vals
['expiration'] = expiration
944 vals
['opportunistic'] = opportunistic
948 def get_sta(self
, addr
, info
=None, next
=False):
949 cmd
= "STA-NEXT " if next
else "STA "
951 res
= self
.request("STA-FIRST")
953 res
= self
.request(cmd
+ addr
+ " " + info
)
955 res
= self
.request(cmd
+ addr
)
956 lines
= res
.splitlines()
964 [name
,value
] = l
.split('=', 1)
968 def mgmt_rx(self
, timeout
=5):
969 ev
= self
.wait_event(["MGMT-RX"], timeout
=timeout
)
973 items
= ev
.split(' ')
974 field
,val
= items
[1].split('=')
976 raise Exception("Unexpected MGMT-RX event format: " + ev
)
978 frame
= binascii
.unhexlify(items
[4])
981 hdr
= struct
.unpack('<HH6B6B6BH', frame
[0:24])
983 msg
['subtype'] = (hdr
[0] >> 4) & 0xf
985 msg
['duration'] = hdr
[0]
987 msg
['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
989 msg
['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
991 msg
['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
993 msg
['seq_ctrl'] = hdr
[0]
994 msg
['payload'] = frame
[24:]