]>
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
, timeout
=10):
79 logger
.debug(self
.ifname
+ ": CTRL: " + cmd
)
80 return self
.ctrl
.request(cmd
, timeout
=timeout
)
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")
210 def interworking_add_network(self
, bssid
):
211 id = self
.request("INTERWORKING_ADD_NETWORK " + bssid
)
212 if "FAIL" in id or "OK" in id:
213 raise Exception("INTERWORKING_ADD_NETWORK failed")
217 id = self
.request("ADD_CRED")
219 raise Exception("ADD_CRED failed")
222 def remove_cred(self
, id):
223 id = self
.request("REMOVE_CRED " + str(id))
225 raise Exception("REMOVE_CRED failed")
228 def set_cred(self
, id, field
, value
):
229 res
= self
.request("SET_CRED " + str(id) + " " + field
+ " " + value
)
231 raise Exception("SET_CRED failed")
234 def set_cred_quoted(self
, id, field
, value
):
235 res
= self
.request("SET_CRED " + str(id) + " " + field
+ ' "' + value
+ '"')
237 raise Exception("SET_CRED failed")
240 def get_cred(self
, id, field
):
241 return self
.request("GET_CRED " + str(id) + " " + field
)
243 def add_cred_values(self
, params
):
246 quoted
= [ "realm", "username", "password", "domain", "imsi",
247 "excluded_ssid", "milenage", "ca_cert", "client_cert",
248 "private_key", "domain_suffix_match", "provisioning_sp",
249 "roaming_partner", "phase1", "phase2" ]
252 self
.set_cred_quoted(id, field
, params
[field
])
254 not_quoted
= [ "eap", "roaming_consortium", "priority",
255 "required_roaming_consortium", "sp_priority",
256 "max_bss_load", "update_identifier", "req_conn_capab",
257 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
258 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
259 for field
in not_quoted
:
261 self
.set_cred(id, field
, params
[field
])
265 def select_network(self
, id, freq
=None):
267 extra
= " freq=" + str(freq
)
270 id = self
.request("SELECT_NETWORK " + str(id) + extra
)
272 raise Exception("SELECT_NETWORK failed")
275 def mesh_group_add(self
, id):
276 id = self
.request("MESH_GROUP_ADD " + str(id))
278 raise Exception("MESH_GROUP_ADD failed")
281 def mesh_group_remove(self
):
282 id = self
.request("MESH_GROUP_REMOVE " + str(self
.ifname
))
284 raise Exception("MESH_GROUP_REMOVE failed")
287 def connect_network(self
, id, timeout
=10):
289 self
.select_network(id)
290 self
.wait_connected(timeout
=timeout
)
293 def get_status(self
, extra
=None):
298 res
= self
.request("STATUS" + extra
)
299 lines
= res
.splitlines()
303 [name
,value
] = l
.split('=', 1)
305 except ValueError, e
:
306 logger
.info(self
.ifname
+ ": Ignore unexpected STATUS line: " + l
)
309 def get_status_field(self
, field
, extra
=None):
310 vals
= self
.get_status(extra
)
315 def get_group_status(self
, extra
=None):
320 res
= self
.group_request("STATUS" + extra
)
321 lines
= res
.splitlines()
325 [name
,value
] = l
.split('=', 1)
327 logger
.info(self
.ifname
+ ": Ignore unexpected status line: " + l
)
332 def get_group_status_field(self
, field
, extra
=None):
333 vals
= self
.get_group_status(extra
)
338 def get_driver_status(self
):
339 res
= self
.request("STATUS-DRIVER")
340 lines
= res
.splitlines()
344 [name
,value
] = l
.split('=', 1)
346 logger
.info(self
.ifname
+ ": Ignore unexpected status-driver line: " + l
)
351 def get_driver_status_field(self
, field
):
352 vals
= self
.get_driver_status()
358 mcc
= int(self
.get_driver_status_field('capa.num_multichan_concurrent'))
359 return 1 if mcc
< 2 else mcc
362 res
= self
.request("MIB")
363 lines
= res
.splitlines()
367 [name
,value
] = l
.split('=', 1)
369 except ValueError, e
:
370 logger
.info(self
.ifname
+ ": Ignore unexpected MIB line: " + l
)
373 def p2p_dev_addr(self
):
374 return self
.get_status_field("p2p_device_address")
376 def p2p_interface_addr(self
):
377 return self
.get_group_status_field("address")
381 res
= self
.p2p_interface_addr()
383 res
= self
.p2p_dev_addr()
386 def p2p_listen(self
):
387 return self
.global_request("P2P_LISTEN")
389 def p2p_find(self
, social
=False, progressive
=False, dev_id
=None,
390 dev_type
=None, delay
=None):
393 cmd
= cmd
+ " type=social"
395 cmd
= cmd
+ " type=progressive"
397 cmd
= cmd
+ " dev_id=" + dev_id
399 cmd
= cmd
+ " dev_type=" + dev_type
401 cmd
= cmd
+ " delay=" + str(delay
)
402 return self
.global_request(cmd
)
404 def p2p_stop_find(self
):
405 return self
.global_request("P2P_STOP_FIND")
407 def wps_read_pin(self
):
408 self
.pin
= self
.request("WPS_PIN get").rstrip("\n")
409 if "FAIL" in self
.pin
:
410 raise Exception("Could not generate PIN")
413 def peer_known(self
, peer
, full
=True):
414 res
= self
.global_request("P2P_PEER " + peer
)
415 if peer
.lower() not in res
.lower():
419 return "[PROBE_REQ_ONLY]" not in res
421 def discover_peer(self
, peer
, full
=True, timeout
=15, social
=True, force_find
=False):
422 logger
.info(self
.ifname
+ ": Trying to discover peer " + peer
)
423 if not force_find
and self
.peer_known(peer
, full
):
425 self
.p2p_find(social
)
427 while count
< timeout
* 4:
430 if self
.peer_known(peer
, full
):
434 def get_peer(self
, peer
):
435 res
= self
.global_request("P2P_PEER " + peer
)
436 if peer
.lower() not in res
.lower():
437 raise Exception("Peer information not available")
438 lines
= res
.splitlines()
442 [name
,value
] = l
.split('=', 1)
446 def group_form_result(self
, ev
, expect_failure
=False, go_neg_res
=None):
448 if "P2P-GROUP-STARTED" in ev
:
449 raise Exception("Group formation succeeded when expecting failure")
450 exp
= r
'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
451 s
= re
.split(exp
, ev
)
455 res
['result'] = 'go-neg-failed'
456 res
['status'] = int(s
[2])
459 if "P2P-GROUP-STARTED" not in ev
:
460 raise Exception("No P2P-GROUP-STARTED event seen")
462 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.]*)'
463 s
= re
.split(exp
, ev
)
465 exp
= r
'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
466 s
= re
.split(exp
, ev
)
468 raise Exception("Could not parse P2P-GROUP-STARTED")
470 res
['result'] = 'success'
472 self
.group_ifname
= s
[2]
474 self
.gctrl_mon
= wpaspy
.Ctrl(os
.path
.join(wpas_ctrl
, self
.group_ifname
))
475 self
.gctrl_mon
.attach()
477 logger
.debug("Could not open monitor socket for group interface")
478 self
.gctrl_mon
= None
482 if "[PERSISTENT]" in ev
:
483 res
['persistent'] = True
485 res
['persistent'] = False
486 p
= re
.match(r
'psk=([0-9a-f]*)', s
[6])
488 res
['psk'] = p
.group(1)
489 p
= re
.match(r
'passphrase="(.*)"', s
[6])
491 res
['passphrase'] = p
.group(1)
492 res
['go_dev_addr'] = s
[7]
494 if len(s
) > 8 and len(s
[8]) > 0:
495 res
['ip_addr'] = s
[8]
497 res
['ip_mask'] = s
[9]
499 res
['go_ip_addr'] = s
[10]
502 exp
= r
'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
503 s
= re
.split(exp
, go_neg_res
)
505 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
506 res
['go_neg_role'] = s
[2]
507 res
['go_neg_freq'] = s
[3]
511 def p2p_go_neg_auth(self
, peer
, pin
, method
, go_intent
=None, persistent
=False, freq
=None):
512 if not self
.discover_peer(peer
):
513 raise Exception("Peer " + peer
+ " not found")
516 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
+ " auth"
518 cmd
= "P2P_CONNECT " + peer
+ " " + method
+ " auth"
520 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
522 cmd
= cmd
+ ' freq=' + str(freq
)
524 cmd
= cmd
+ " persistent"
525 if "OK" in self
.global_request(cmd
):
527 raise Exception("P2P_CONNECT (auth) failed")
529 def p2p_go_neg_auth_result(self
, timeout
=1, expect_failure
=False):
531 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
532 "P2P-GO-NEG-FAILURE"], timeout
);
536 raise Exception("Group formation timed out")
537 if "P2P-GO-NEG-SUCCESS" in ev
:
539 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
);
543 raise Exception("Group formation timed out")
545 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
547 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):
548 if not self
.discover_peer(peer
):
549 raise Exception("Peer " + peer
+ " not found")
552 cmd
= "P2P_CONNECT " + peer
+ " " + pin
+ " " + method
554 cmd
= "P2P_CONNECT " + peer
+ " " + method
556 cmd
= cmd
+ ' go_intent=' + str(go_intent
)
558 cmd
= cmd
+ ' freq=' + str(freq
)
560 cmd
= cmd
+ " persistent"
562 cmd
= cmd
+ " persistent=" + persistent_id
564 cmd
= cmd
+ " provdisc"
565 if "OK" in self
.global_request(cmd
):
570 ev
= self
.wait_global_event(["P2P-GO-NEG-SUCCESS",
571 "P2P-GO-NEG-FAILURE"], timeout
)
575 raise Exception("Group formation timed out")
576 if "P2P-GO-NEG-SUCCESS" in ev
:
580 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
584 raise Exception("Group formation timed out")
586 return self
.group_form_result(ev
, expect_failure
, go_neg_res
)
587 raise Exception("P2P_CONNECT failed")
589 def wait_event(self
, events
, timeout
=10):
590 start
= os
.times()[4]
592 while self
.mon
.pending():
594 logger
.debug(self
.ifname
+ ": " + ev
)
599 remaining
= start
+ timeout
- now
602 if not self
.mon
.pending(timeout
=remaining
):
606 def wait_global_event(self
, events
, timeout
):
607 if self
.global_iface
is None:
608 self
.wait_event(events
, timeout
)
610 start
= os
.times()[4]
612 while self
.global_mon
.pending():
613 ev
= self
.global_mon
.recv()
614 logger
.debug(self
.ifname
+ "(global): " + ev
)
619 remaining
= start
+ timeout
- now
622 if not self
.global_mon
.pending(timeout
=remaining
):
626 def wait_group_event(self
, events
, timeout
=10):
627 if self
.group_ifname
and self
.group_ifname
!= self
.ifname
:
628 if self
.gctrl_mon
is None:
630 start
= os
.times()[4]
632 while self
.gctrl_mon
.pending():
633 ev
= self
.gctrl_mon
.recv()
634 logger
.debug(self
.group_ifname
+ ": " + ev
)
639 remaining
= start
+ timeout
- now
642 if not self
.gctrl_mon
.pending(timeout
=remaining
):
646 return self
.wait_event(events
, timeout
)
648 def wait_go_ending_session(self
):
651 self
.gctrl_mon
.detach()
654 self
.gctrl_mon
= None
655 ev
= self
.wait_global_event(["P2P-GROUP-REMOVED"], timeout
=3)
657 raise Exception("Group removal event timed out")
658 if "reason=GO_ENDING_SESSION" not in ev
:
659 raise Exception("Unexpected group removal reason")
661 def dump_monitor(self
):
662 while self
.mon
.pending():
664 logger
.debug(self
.ifname
+ ": " + ev
)
665 while self
.global_mon
and self
.global_mon
.pending():
666 ev
= self
.global_mon
.recv()
667 logger
.debug(self
.ifname
+ "(global): " + ev
)
669 def remove_group(self
, ifname
=None):
672 self
.gctrl_mon
.detach()
675 self
.gctrl_mon
= None
677 ifname
= self
.group_ifname
if self
.group_ifname
else self
.ifname
678 if "OK" not in self
.global_request("P2P_GROUP_REMOVE " + ifname
):
679 raise Exception("Group could not be removed")
680 self
.group_ifname
= None
682 def p2p_start_go(self
, persistent
=None, freq
=None, no_event_clear
=False):
684 cmd
= "P2P_GROUP_ADD"
685 if persistent
is None:
687 elif persistent
is True:
688 cmd
= cmd
+ " persistent"
690 cmd
= cmd
+ " persistent=" + str(persistent
)
692 cmd
= cmd
+ " freq=" + str(freq
)
693 if "OK" in self
.global_request(cmd
):
694 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
=5)
696 raise Exception("GO start up timed out")
697 if not no_event_clear
:
699 return self
.group_form_result(ev
)
700 raise Exception("P2P_GROUP_ADD failed")
702 def p2p_go_authorize_client(self
, pin
):
703 cmd
= "WPS_PIN any " + pin
704 if "FAIL" in self
.group_request(cmd
):
705 raise Exception("Failed to authorize client connection on GO")
708 def p2p_go_authorize_client_pbc(self
):
710 if "FAIL" in self
.group_request(cmd
):
711 raise Exception("Failed to authorize client connection on GO")
714 def p2p_connect_group(self
, go_addr
, pin
, timeout
=0, social
=False,
717 if not self
.discover_peer(go_addr
, social
=social
):
718 if social
or not self
.discover_peer(go_addr
, social
=social
):
719 raise Exception("GO " + go_addr
+ " not found")
721 cmd
= "P2P_CONNECT " + go_addr
+ " " + pin
+ " join"
723 cmd
+= " freq=" + str(freq
)
724 if "OK" in self
.global_request(cmd
):
728 ev
= self
.wait_global_event(["P2P-GROUP-STARTED"], timeout
)
730 raise Exception("Joining the group timed out")
732 return self
.group_form_result(ev
)
733 raise Exception("P2P_CONNECT(join) failed")
735 def tdls_setup(self
, peer
):
736 cmd
= "TDLS_SETUP " + peer
737 if "FAIL" in self
.group_request(cmd
):
738 raise Exception("Failed to request TDLS setup")
741 def tdls_teardown(self
, peer
):
742 cmd
= "TDLS_TEARDOWN " + peer
743 if "FAIL" in self
.group_request(cmd
):
744 raise Exception("Failed to request TDLS teardown")
748 """Return (tsid, up) tuples representing current tspecs"""
749 res
= self
.request("WMM_AC_STATUS")
750 tspecs
= re
.findall(r
"TSID=(\d+) UP=(\d+)", res
)
751 tspecs
= [tuple(map(int, tspec
)) for tspec
in tspecs
]
753 logger
.debug("tspecs: " + str(tspecs
))
756 def add_ts(self
, tsid
, up
, direction
="downlink", expect_failure
=False,
760 "nominal_msdu_size": 1500,
761 "min_phy_rate": 6000000,
762 "mean_data_rate": 1500,
764 cmd
= "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction
, tsid
, up
)
765 for (key
, value
) in params
.iteritems():
766 cmd
+= " %s=%d" % (key
, value
)
770 if self
.request(cmd
).strip() != "OK":
771 raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid
, up
))
774 ev
= self
.wait_event(["TSPEC-REQ-FAILED"], timeout
=2)
776 raise Exception("ADDTS failed (time out while waiting failure)")
777 if "tsid=%d" % (tsid
) not in ev
:
778 raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
781 ev
= self
.wait_event(["TSPEC-ADDED"], timeout
=1)
783 raise Exception("ADDTS failed (time out)")
784 if "tsid=%d" % (tsid
) not in ev
:
785 raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
787 if not (tsid
, up
) in self
.tspecs():
788 raise Exception("ADDTS failed (tsid not in tspec list)")
790 def del_ts(self
, tsid
):
791 if self
.request("WMM_AC_DELTS %d" % (tsid
)).strip() != "OK":
792 raise Exception("DELTS failed")
794 ev
= self
.wait_event(["TSPEC-REMOVED"], timeout
=1)
796 raise Exception("DELTS failed (time out)")
797 if "tsid=%d" % (tsid
) not in ev
:
798 raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
800 tspecs
= [(t
, u
) for (t
, u
) in self
.tspecs() if t
== tsid
]
802 raise Exception("DELTS failed (still in tspec list)")
804 def connect(self
, ssid
=None, ssid2
=None, **kwargs
):
805 logger
.info("Connect STA " + self
.ifname
+ " to AP")
806 id = self
.add_network()
808 self
.set_network_quoted(id, "ssid", ssid
)
810 self
.set_network(id, "ssid", ssid2
)
812 quoted
= [ "psk", "identity", "anonymous_identity", "password",
813 "ca_cert", "client_cert", "private_key",
814 "private_key_passwd", "ca_cert2", "client_cert2",
815 "private_key2", "phase1", "phase2", "domain_suffix_match",
816 "altsubject_match", "subject_match", "pac_file", "dh_file",
817 "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
820 if field
in kwargs
and kwargs
[field
]:
821 self
.set_network_quoted(id, field
, kwargs
[field
])
823 not_quoted
= [ "proto", "key_mgmt", "ieee80211w", "pairwise",
824 "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
825 "wep_tx_keyidx", "scan_freq", "eap",
826 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
827 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
828 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
829 "disable_ht40", "disable_sgi", "disable_ldpc",
830 "ht40_intolerant", "update_identifier", "mac_addr",
831 "erp", "bg_scan_period", "bssid_blacklist",
833 for field
in not_quoted
:
834 if field
in kwargs
and kwargs
[field
]:
835 self
.set_network(id, field
, kwargs
[field
])
837 if "raw_psk" in kwargs
and kwargs
['raw_psk']:
838 self
.set_network(id, "psk", kwargs
['raw_psk'])
839 if "password_hex" in kwargs
and kwargs
['password_hex']:
840 self
.set_network(id, "password", kwargs
['password_hex'])
841 if "peerkey" in kwargs
and kwargs
['peerkey']:
842 self
.set_network(id, "peerkey", "1")
843 if "okc" in kwargs
and kwargs
['okc']:
844 self
.set_network(id, "proactive_key_caching", "1")
845 if "ocsp" in kwargs
and kwargs
['ocsp']:
846 self
.set_network(id, "ocsp", str(kwargs
['ocsp']))
847 if "only_add_network" in kwargs
and kwargs
['only_add_network']:
849 if "wait_connect" not in kwargs
or kwargs
['wait_connect']:
851 self
.connect_network(id, timeout
=20)
853 self
.connect_network(id)
856 self
.select_network(id)
859 def scan(self
, type=None, freq
=None, no_wait
=False, only_new
=False):
861 cmd
= "SCAN TYPE=" + type
865 cmd
= cmd
+ " freq=" + str(freq
)
870 if not "OK" in self
.request(cmd
):
871 raise Exception("Failed to trigger scan")
874 ev
= self
.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
876 raise Exception("Scan timed out")
878 def scan_for_bss(self
, bssid
, freq
=None, force_scan
=False, only_new
=False):
879 if not force_scan
and self
.get_bss(bssid
) is not None:
881 for i
in range(0, 10):
882 self
.scan(freq
=freq
, type="ONLY", only_new
=only_new
)
883 if self
.get_bss(bssid
) is not None:
885 raise Exception("Could not find BSS " + bssid
+ " in scan")
887 def flush_scan_cache(self
, freq
=2417):
888 self
.request("BSS_FLUSH 0")
889 self
.scan(freq
=freq
, only_new
=True)
891 def roam(self
, bssid
, fail_test
=False):
893 if "OK" not in self
.request("ROAM " + bssid
):
894 raise Exception("ROAM failed")
896 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
898 raise Exception("Unexpected connection")
901 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
904 def roam_over_ds(self
, bssid
, fail_test
=False):
906 if "OK" not in self
.request("FT_DS " + bssid
):
907 raise Exception("FT_DS failed")
909 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=1)
911 raise Exception("Unexpected connection")
914 self
.wait_connected(timeout
=10, error
="Roaming with the AP timed out")
917 def wps_reg(self
, bssid
, pin
, new_ssid
=None, key_mgmt
=None, cipher
=None,
918 new_passphrase
=None, no_wait
=False):
921 self
.request("WPS_REG " + bssid
+ " " + pin
+ " " +
922 new_ssid
.encode("hex") + " " + key_mgmt
+ " " +
923 cipher
+ " " + new_passphrase
.encode("hex"))
926 ev
= self
.wait_event(["WPS-SUCCESS"], timeout
=15)
928 self
.request("WPS_REG " + bssid
+ " " + pin
)
931 ev
= self
.wait_event(["WPS-CRED-RECEIVED"], timeout
=15)
933 raise Exception("WPS cred timed out")
934 ev
= self
.wait_event(["WPS-FAIL"], timeout
=15)
936 raise Exception("WPS timed out")
937 self
.wait_connected(timeout
=15)
940 self
.global_request("RELOG")
942 def wait_completed(self
, timeout
=10):
943 for i
in range(0, timeout
* 2):
944 if self
.get_status_field("wpa_state") == "COMPLETED":
947 raise Exception("Timeout while waiting for COMPLETED state")
949 def get_capability(self
, field
):
950 res
= self
.request("GET_CAPABILITY " + field
)
953 return res
.split(' ')
955 def get_bss(self
, bssid
, ifname
=None):
956 if not ifname
or ifname
== self
.ifname
:
957 res
= self
.request("BSS " + bssid
)
958 elif ifname
== self
.group_ifname
:
959 res
= self
.group_request("BSS " + bssid
)
965 lines
= res
.splitlines()
968 [name
,value
] = l
.split('=', 1)
974 def get_pmksa(self
, bssid
):
975 res
= self
.request("PMKSA")
976 lines
= res
.splitlines()
981 [index
,aa
,pmkid
,expiration
,opportunistic
] = l
.split(' ')
982 vals
['index'] = index
983 vals
['pmkid'] = pmkid
984 vals
['expiration'] = expiration
985 vals
['opportunistic'] = opportunistic
989 def get_sta(self
, addr
, info
=None, next
=False):
990 cmd
= "STA-NEXT " if next
else "STA "
992 res
= self
.request("STA-FIRST")
994 res
= self
.request(cmd
+ addr
+ " " + info
)
996 res
= self
.request(cmd
+ addr
)
997 lines
= res
.splitlines()
1005 [name
,value
] = l
.split('=', 1)
1009 def mgmt_rx(self
, timeout
=5):
1010 ev
= self
.wait_event(["MGMT-RX"], timeout
=timeout
)
1014 items
= ev
.split(' ')
1015 field
,val
= items
[1].split('=')
1017 raise Exception("Unexpected MGMT-RX event format: " + ev
)
1019 frame
= binascii
.unhexlify(items
[4])
1020 msg
['frame'] = frame
1022 hdr
= struct
.unpack('<HH6B6B6BH', frame
[0:24])
1024 msg
['subtype'] = (hdr
[0] >> 4) & 0xf
1026 msg
['duration'] = hdr
[0]
1028 msg
['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1030 msg
['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1032 msg
['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr
[0:6]
1034 msg
['seq_ctrl'] = hdr
[0]
1035 msg
['payload'] = frame
[24:]
1039 def wait_connected(self
, timeout
=10, error
="Connection timed out"):
1040 ev
= self
.wait_event(["CTRL-EVENT-CONNECTED"], timeout
=timeout
)
1042 raise Exception(error
)
1045 def wait_disconnected(self
, timeout
=10, error
="Disconnection timed out"):
1046 ev
= self
.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout
=timeout
)
1048 raise Exception(error
)
1051 def get_group_ifname(self
):
1052 return self
.group_ifname
if self
.group_ifname
else self
.ifname