tests: Add WpaSupplicant.wait_group_event()
[mech_eap.git] / tests / hwsim / wpasupplicant.py
1 # Python class for controlling wpa_supplicant
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import os
8 import time
9 import logging
10 import binascii
11 import re
12 import struct
13 import subprocess
14 import wpaspy
15
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
18
19 class WpaSupplicant:
20     def __init__(self, ifname=None, global_iface=None):
21         self.group_ifname = None
22         self.gctrl_mon = None
23         if ifname:
24             self.set_ifname(ifname)
25         else:
26             self.ifname = None
27
28         self.global_iface = global_iface
29         if global_iface:
30             self.global_ctrl = wpaspy.Ctrl(global_iface)
31             self.global_mon = wpaspy.Ctrl(global_iface)
32             self.global_mon.attach()
33
34     def set_ifname(self, ifname):
35         self.ifname = ifname
36         self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
37         self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
38         self.mon.attach()
39
40     def remove_ifname(self):
41         if self.ifname:
42             self.mon.detach()
43             self.mon = None
44             self.ctrl = None
45             self.ifname = None
46
47     def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
48         try:
49             groups = subprocess.check_output(["id"])
50             group = "admin" if "(admin)" in groups else "adm"
51         except Exception, e:
52             group = "admin"
53         cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
54         if drv_params:
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)
59
60     def interface_remove(self, ifname):
61         self.remove_ifname()
62         self.global_request("INTERFACE_REMOVE " + ifname)
63
64     def request(self, cmd):
65         logger.debug(self.ifname + ": CTRL: " + cmd)
66         return self.ctrl.request(cmd)
67
68     def global_request(self, cmd):
69         if self.global_iface is None:
70             self.request(cmd)
71         else:
72             ifname = self.ifname or self.global_iface
73             logger.debug(ifname + ": CTRL(global): " + cmd)
74             return self.global_ctrl.request(cmd)
75
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)
82
83     def ping(self):
84         return "PONG" in self.request("PING")
85
86     def global_ping(self):
87         return "PONG" in self.global_request("PING")
88
89     def reset(self):
90         self.dump_monitor()
91         res = self.request("FLUSH")
92         if not "OK" in res:
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 external_sim 0")
97         self.request("SET hessid 00:00:00:00:00:00")
98         self.request("SET access_network_type 15")
99         self.request("SET p2p_add_cli_chan 0")
100         self.request("SET p2p_no_go_freq ")
101         self.request("SET p2p_pref_chan ")
102         self.request("SET p2p_no_group_iface 1")
103         self.request("SET p2p_go_intent 7")
104         if self.gctrl_mon:
105             try:
106                 self.gctrl_mon.detach()
107             except:
108                 pass
109             self.gctrl_mon = None
110         self.group_ifname = None
111         self.dump_monitor()
112
113         iter = 0
114         while iter < 60:
115             state = self.get_driver_status_field("scan_state")
116             if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
117                 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
118                 time.sleep(1)
119             else:
120                 break
121             iter = iter + 1
122         if iter == 60:
123             logger.error(self.ifname + ": Driver scan state did not clear")
124             print "Trying to clear cfg80211/mac80211 scan state"
125             try:
126                 cmd = ["sudo", "ifconfig", self.ifname, "down"]
127                 subprocess.call(cmd)
128             except subprocess.CalledProcessError, e:
129                 logger.info("ifconfig failed: " + str(e.returncode))
130                 logger.info(e.output)
131             try:
132                 cmd = ["sudo", "ifconfig", self.ifname, "up"]
133                 subprocess.call(cmd)
134             except subprocess.CalledProcessError, e:
135                 logger.info("ifconfig failed: " + str(e.returncode))
136                 logger.info(e.output)
137         if iter > 0:
138             # The ongoing scan could have discovered BSSes or P2P peers
139             logger.info("Run FLUSH again since scan was in progress")
140             self.request("FLUSH")
141             self.dump_monitor()
142
143         if not self.ping():
144             logger.info("No PING response from " + self.ifname + " after reset")
145
146     def add_network(self):
147         id = self.request("ADD_NETWORK")
148         if "FAIL" in id:
149             raise Exception("ADD_NETWORK failed")
150         return int(id)
151
152     def remove_network(self, id):
153         id = self.request("REMOVE_NETWORK " + str(id))
154         if "FAIL" in id:
155             raise Exception("REMOVE_NETWORK failed")
156         return None
157
158     def get_network(self, id, field):
159         res = self.request("GET_NETWORK " + str(id) + " " + field)
160         if res == "FAIL\n":
161             return None
162         return res
163
164     def set_network(self, id, field, value):
165         res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
166         if "FAIL" in res:
167             raise Exception("SET_NETWORK failed")
168         return None
169
170     def set_network_quoted(self, id, field, value):
171         res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
172         if "FAIL" in res:
173             raise Exception("SET_NETWORK failed")
174         return None
175
176     def list_networks(self):
177         res = self.request("LIST_NETWORKS")
178         lines = res.splitlines()
179         networks = []
180         for l in lines:
181             if "network id" in l:
182                 continue
183             [id,ssid,bssid,flags] = l.split('\t')
184             network = {}
185             network['id'] = id
186             network['ssid'] = ssid
187             network['bssid'] = bssid
188             network['flags'] = flags
189             networks.append(network)
190         return networks
191
192     def hs20_enable(self, auto_interworking=False):
193         self.request("SET interworking 1")
194         self.request("SET hs20 1")
195         if auto_interworking:
196             self.request("SET auto_interworking 1")
197         else:
198             self.request("SET auto_interworking 0")
199
200     def add_cred(self):
201         id = self.request("ADD_CRED")
202         if "FAIL" in id:
203             raise Exception("ADD_CRED failed")
204         return int(id)
205
206     def remove_cred(self, id):
207         id = self.request("REMOVE_CRED " + str(id))
208         if "FAIL" in id:
209             raise Exception("REMOVE_CRED failed")
210         return None
211
212     def set_cred(self, id, field, value):
213         res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
214         if "FAIL" in res:
215             raise Exception("SET_CRED failed")
216         return None
217
218     def set_cred_quoted(self, id, field, value):
219         res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
220         if "FAIL" in res:
221             raise Exception("SET_CRED failed")
222         return None
223
224     def get_cred(self, id, field):
225         return self.request("GET_CRED " + str(id) + " " + field)
226
227     def add_cred_values(self, params):
228         id = self.add_cred()
229
230         quoted = [ "realm", "username", "password", "domain", "imsi",
231                    "excluded_ssid", "milenage", "ca_cert", "client_cert",
232                    "private_key", "domain_suffix_match", "provisioning_sp",
233                    "roaming_partner", "phase1", "phase2" ]
234         for field in quoted:
235             if field in params:
236                 self.set_cred_quoted(id, field, params[field])
237
238         not_quoted = [ "eap", "roaming_consortium", "priority",
239                        "required_roaming_consortium", "sp_priority",
240                        "max_bss_load", "update_identifier", "req_conn_capab",
241                        "min_dl_bandwidth_home", "min_ul_bandwidth_home",
242                        "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
243         for field in not_quoted:
244             if field in params:
245                 self.set_cred(id, field, params[field])
246
247         return id;
248
249     def select_network(self, id, freq=None):
250         if freq:
251             extra = " freq=" + freq
252         else:
253             extra = ""
254         id = self.request("SELECT_NETWORK " + str(id) + extra)
255         if "FAIL" in id:
256             raise Exception("SELECT_NETWORK failed")
257         return None
258
259     def connect_network(self, id, timeout=10):
260         self.dump_monitor()
261         self.select_network(id)
262         ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
263         if ev is None:
264             raise Exception("Association with the AP timed out")
265         self.dump_monitor()
266
267     def get_status(self, extra=None):
268         if extra:
269             extra = "-" + extra
270         else:
271             extra = ""
272         res = self.request("STATUS" + extra)
273         lines = res.splitlines()
274         vals = dict()
275         for l in lines:
276             try:
277                 [name,value] = l.split('=', 1)
278                 vals[name] = value
279             except ValueError, e:
280                 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
281         return vals
282
283     def get_status_field(self, field, extra=None):
284         vals = self.get_status(extra)
285         if field in vals:
286             return vals[field]
287         return None
288
289     def get_group_status(self, extra=None):
290         if extra:
291             extra = "-" + extra
292         else:
293             extra = ""
294         res = self.group_request("STATUS" + extra)
295         lines = res.splitlines()
296         vals = dict()
297         for l in lines:
298             [name,value] = l.split('=', 1)
299             vals[name] = value
300         return vals
301
302     def get_group_status_field(self, field, extra=None):
303         vals = self.get_group_status(extra)
304         if field in vals:
305             return vals[field]
306         return None
307
308     def get_driver_status(self):
309         res = self.request("STATUS-DRIVER")
310         lines = res.splitlines()
311         vals = dict()
312         for l in lines:
313             [name,value] = l.split('=', 1)
314             vals[name] = value
315         return vals
316
317     def get_driver_status_field(self, field):
318         vals = self.get_driver_status()
319         if field in vals:
320             return vals[field]
321         return None
322
323     def get_mcc(self):
324         mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
325         return 1 if mcc < 2 else mcc
326
327     def get_mib(self):
328         res = self.request("MIB")
329         lines = res.splitlines()
330         vals = dict()
331         for l in lines:
332             try:
333                 [name,value] = l.split('=', 1)
334                 vals[name] = value
335             except ValueError, e:
336                 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
337         return vals
338
339     def p2p_dev_addr(self):
340         return self.get_status_field("p2p_device_address")
341
342     def p2p_interface_addr(self):
343         return self.get_group_status_field("address")
344
345     def own_addr(self):
346         try:
347             res = self.p2p_interface_addr()
348         except:
349             res = self.p2p_dev_addr()
350         return res
351
352     def p2p_listen(self):
353         return self.global_request("P2P_LISTEN")
354
355     def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
356         cmd = "P2P_FIND"
357         if social:
358             cmd = cmd + " type=social"
359         elif progressive:
360             cmd = cmd + " type=progressive"
361         if dev_id:
362             cmd = cmd + " dev_id=" + dev_id
363         if dev_type:
364             cmd = cmd + " dev_type=" + dev_type
365         return self.global_request(cmd)
366
367     def p2p_stop_find(self):
368         return self.global_request("P2P_STOP_FIND")
369
370     def wps_read_pin(self):
371         self.pin = self.request("WPS_PIN get").rstrip("\n")
372         if "FAIL" in self.pin:
373             raise Exception("Could not generate PIN")
374         return self.pin
375
376     def peer_known(self, peer, full=True):
377         res = self.global_request("P2P_PEER " + peer)
378         if peer.lower() not in res.lower():
379             return False
380         if not full:
381             return True
382         return "[PROBE_REQ_ONLY]" not in res
383
384     def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
385         logger.info(self.ifname + ": Trying to discover peer " + peer)
386         if not force_find and self.peer_known(peer, full):
387             return True
388         self.p2p_find(social)
389         count = 0
390         while count < timeout:
391             time.sleep(1)
392             count = count + 1
393             if self.peer_known(peer, full):
394                 return True
395         return False
396
397     def get_peer(self, peer):
398         res = self.global_request("P2P_PEER " + peer)
399         if peer.lower() not in res.lower():
400             raise Exception("Peer information not available")
401         lines = res.splitlines()
402         vals = dict()
403         for l in lines:
404             if '=' in l:
405                 [name,value] = l.split('=', 1)
406                 vals[name] = value
407         return vals
408
409     def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
410         if expect_failure:
411             if "P2P-GROUP-STARTED" in ev:
412                 raise Exception("Group formation succeeded when expecting failure")
413             exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
414             s = re.split(exp, ev)
415             if len(s) < 3:
416                 return None
417             res = {}
418             res['result'] = 'go-neg-failed'
419             res['status'] = int(s[2])
420             return res
421
422         if "P2P-GROUP-STARTED" not in ev:
423             raise Exception("No P2P-GROUP-STARTED event seen")
424
425         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.]*)'
426         s = re.split(exp, ev)
427         if len(s) < 11:
428             exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
429             s = re.split(exp, ev)
430             if len(s) < 8:
431                 raise Exception("Could not parse P2P-GROUP-STARTED")
432         res = {}
433         res['result'] = 'success'
434         res['ifname'] = s[2]
435         self.group_ifname = s[2]
436         try:
437             self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
438             self.gctrl_mon.attach()
439         except:
440             logger.debug("Could not open monitor socket for group interface")
441             self.gctrl_mon = None
442         res['role'] = s[3]
443         res['ssid'] = s[4]
444         res['freq'] = s[5]
445         if "[PERSISTENT]" in ev:
446             res['persistent'] = True
447         else:
448             res['persistent'] = False
449         p = re.match(r'psk=([0-9a-f]*)', s[6])
450         if p:
451             res['psk'] = p.group(1)
452         p = re.match(r'passphrase="(.*)"', s[6])
453         if p:
454             res['passphrase'] = p.group(1)
455         res['go_dev_addr'] = s[7]
456
457         if len(s) > 8 and len(s[8]) > 0:
458             res['ip_addr'] = s[8]
459         if len(s) > 9:
460             res['ip_mask'] = s[9]
461         if len(s) > 10:
462             res['go_ip_addr'] = s[10]
463
464         if go_neg_res:
465             exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
466             s = re.split(exp, go_neg_res)
467             if len(s) < 4:
468                 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
469             res['go_neg_role'] = s[2]
470             res['go_neg_freq'] = s[3]
471
472         return res
473
474     def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
475         if not self.discover_peer(peer):
476             raise Exception("Peer " + peer + " not found")
477         self.dump_monitor()
478         cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
479         if go_intent:
480             cmd = cmd + ' go_intent=' + str(go_intent)
481         if freq:
482             cmd = cmd + ' freq=' + str(freq)
483         if persistent:
484             cmd = cmd + " persistent"
485         if "OK" in self.global_request(cmd):
486             return None
487         raise Exception("P2P_CONNECT (auth) failed")
488
489     def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
490         go_neg_res = None
491         ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
492                                      "P2P-GO-NEG-FAILURE"], timeout);
493         if ev is None:
494             if expect_failure:
495                 return None
496             raise Exception("Group formation timed out")
497         if "P2P-GO-NEG-SUCCESS" in ev:
498             go_neg_res = ev
499             ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
500             if ev is None:
501                 if expect_failure:
502                     return None
503                 raise Exception("Group formation timed out")
504         self.dump_monitor()
505         return self.group_form_result(ev, expect_failure, go_neg_res)
506
507     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):
508         if not self.discover_peer(peer):
509             raise Exception("Peer " + peer + " not found")
510         self.dump_monitor()
511         if pin:
512             cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
513         else:
514             cmd = "P2P_CONNECT " + peer + " " + method
515         if go_intent:
516             cmd = cmd + ' go_intent=' + str(go_intent)
517         if freq:
518             cmd = cmd + ' freq=' + str(freq)
519         if persistent:
520             cmd = cmd + " persistent"
521         elif persistent_id:
522             cmd = cmd + " persistent=" + persistent_id
523         if provdisc:
524             cmd = cmd + " provdisc"
525         if "OK" in self.global_request(cmd):
526             if timeout == 0:
527                 self.dump_monitor()
528                 return None
529             go_neg_res = None
530             ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
531                                          "P2P-GO-NEG-FAILURE"], timeout)
532             if ev is None:
533                 if expect_failure:
534                     return None
535                 raise Exception("Group formation timed out")
536             if "P2P-GO-NEG-SUCCESS" in ev:
537                 if not wait_group:
538                     return ev
539                 go_neg_res = ev
540                 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
541                 if ev is None:
542                     if expect_failure:
543                         return None
544                     raise Exception("Group formation timed out")
545             self.dump_monitor()
546             return self.group_form_result(ev, expect_failure, go_neg_res)
547         raise Exception("P2P_CONNECT failed")
548
549     def wait_event(self, events, timeout=10):
550         start = os.times()[4]
551         while True:
552             while self.mon.pending():
553                 ev = self.mon.recv()
554                 logger.debug(self.ifname + ": " + ev)
555                 for event in events:
556                     if event in ev:
557                         return ev
558             now = os.times()[4]
559             remaining = start + timeout - now
560             if remaining <= 0:
561                 break
562             if not self.mon.pending(timeout=remaining):
563                 break
564         return None
565
566     def wait_global_event(self, events, timeout):
567         if self.global_iface is None:
568             self.wait_event(events, timeout)
569         else:
570             start = os.times()[4]
571             while True:
572                 while self.global_mon.pending():
573                     ev = self.global_mon.recv()
574                     logger.debug(self.ifname + "(global): " + ev)
575                     for event in events:
576                         if event in ev:
577                             return ev
578                 now = os.times()[4]
579                 remaining = start + timeout - now
580                 if remaining <= 0:
581                     break
582                 if not self.global_mon.pending(timeout=remaining):
583                     break
584         return None
585
586     def wait_group_event(self, events, timeout=10):
587         if self.group_ifname and self.group_ifname != self.ifname:
588             if self.gctrl_mon is None:
589                 return None
590             start = os.times()[4]
591             while True:
592                 while self.gctrl_mon.pending():
593                     ev = self.gctrl_mon.recv()
594                     logger.debug(self.group_ifname + ": " + ev)
595                     for event in events:
596                         if event in ev:
597                             return ev
598                 now = os.times()[4]
599                 remaining = start + timeout - now
600                 if remaining <= 0:
601                     break
602                 if not self.gctrl_mon.pending(timeout=remaining):
603                     break
604             return None
605
606         return self.wait_event(events, timeout)
607
608     def wait_go_ending_session(self):
609         if self.gctrl_mon:
610             try:
611                 self.gctrl_mon.detach()
612             except:
613                 pass
614             self.gctrl_mon = None
615         ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
616         if ev is None:
617             raise Exception("Group removal event timed out")
618         if "reason=GO_ENDING_SESSION" not in ev:
619             raise Exception("Unexpected group removal reason")
620
621     def dump_monitor(self):
622         while self.mon.pending():
623             ev = self.mon.recv()
624             logger.debug(self.ifname + ": " + ev)
625         while self.global_mon.pending():
626             ev = self.global_mon.recv()
627             logger.debug(self.ifname + "(global): " + ev)
628
629     def remove_group(self, ifname=None):
630         if self.gctrl_mon:
631             try:
632                 self.gctrl_mon.detach()
633             except:
634                 pass
635             self.gctrl_mon = None
636         if ifname is None:
637             ifname = self.group_ifname if self.group_ifname else self.ifname
638         if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
639             raise Exception("Group could not be removed")
640         self.group_ifname = None
641
642     def p2p_start_go(self, persistent=None, freq=None):
643         self.dump_monitor()
644         cmd = "P2P_GROUP_ADD"
645         if persistent is None:
646             pass
647         elif persistent is True:
648             cmd = cmd + " persistent"
649         else:
650             cmd = cmd + " persistent=" + str(persistent)
651         if freq:
652             cmd = cmd + " freq=" + str(freq)
653         if "OK" in self.global_request(cmd):
654             ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
655             if ev is None:
656                 raise Exception("GO start up timed out")
657             self.dump_monitor()
658             return self.group_form_result(ev)
659         raise Exception("P2P_GROUP_ADD failed")
660
661     def p2p_go_authorize_client(self, pin):
662         cmd = "WPS_PIN any " + pin
663         if "FAIL" in self.group_request(cmd):
664             raise Exception("Failed to authorize client connection on GO")
665         return None
666
667     def p2p_go_authorize_client_pbc(self):
668         cmd = "WPS_PBC"
669         if "FAIL" in self.group_request(cmd):
670             raise Exception("Failed to authorize client connection on GO")
671         return None
672
673     def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
674         self.dump_monitor()
675         if not self.discover_peer(go_addr, social=social):
676             if social or not self.discover_peer(go_addr, social=social):
677                 raise Exception("GO " + go_addr + " not found")
678         self.dump_monitor()
679         cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
680         if "OK" in self.global_request(cmd):
681             if timeout == 0:
682                 self.dump_monitor()
683                 return None
684             ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
685             if ev is None:
686                 raise Exception("Joining the group timed out")
687             self.dump_monitor()
688             return self.group_form_result(ev)
689         raise Exception("P2P_CONNECT(join) failed")
690
691     def tdls_setup(self, peer):
692         cmd = "TDLS_SETUP " + peer
693         if "FAIL" in self.group_request(cmd):
694             raise Exception("Failed to request TDLS setup")
695         return None
696
697     def tdls_teardown(self, peer):
698         cmd = "TDLS_TEARDOWN " + peer
699         if "FAIL" in self.group_request(cmd):
700             raise Exception("Failed to request TDLS teardown")
701         return None
702
703     def connect(self, ssid=None, ssid2=None, **kwargs):
704         logger.info("Connect STA " + self.ifname + " to AP")
705         id = self.add_network()
706         if ssid:
707             self.set_network_quoted(id, "ssid", ssid)
708         elif ssid2:
709             self.set_network(id, "ssid", ssid2)
710
711         quoted = [ "psk", "identity", "anonymous_identity", "password",
712                    "ca_cert", "client_cert", "private_key",
713                    "private_key_passwd", "ca_cert2", "client_cert2",
714                    "private_key2", "phase1", "phase2", "domain_suffix_match",
715                    "altsubject_match", "subject_match", "pac_file", "dh_file",
716                    "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
717         for field in quoted:
718             if field in kwargs and kwargs[field]:
719                 self.set_network_quoted(id, field, kwargs[field])
720
721         not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
722                        "group", "wep_key0", "scan_freq", "eap",
723                        "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
724                        "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
725                        "disable_max_amsdu", "ampdu_factor", "ampdu_density",
726                        "disable_ht40", "disable_sgi", "disable_ldpc",
727                        "ht40_intolerant", "update_identifier", "mac_addr" ]
728         for field in not_quoted:
729             if field in kwargs and kwargs[field]:
730                 self.set_network(id, field, kwargs[field])
731
732         if "raw_psk" in kwargs and kwargs['raw_psk']:
733             self.set_network(id, "psk", kwargs['raw_psk'])
734         if "password_hex" in kwargs and kwargs['password_hex']:
735             self.set_network(id, "password", kwargs['password_hex'])
736         if "peerkey" in kwargs and kwargs['peerkey']:
737             self.set_network(id, "peerkey", "1")
738         if "okc" in kwargs and kwargs['okc']:
739             self.set_network(id, "proactive_key_caching", "1")
740         if "ocsp" in kwargs and kwargs['ocsp']:
741             self.set_network(id, "ocsp", str(kwargs['ocsp']))
742         if "only_add_network" in kwargs and kwargs['only_add_network']:
743             return id
744         if "wait_connect" not in kwargs or kwargs['wait_connect']:
745             if "eap" in kwargs:
746                 self.connect_network(id, timeout=20)
747             else:
748                 self.connect_network(id)
749         else:
750             self.dump_monitor()
751             self.select_network(id)
752         return id
753
754     def scan(self, type=None, freq=None, no_wait=False, only_new=False):
755         if type:
756             cmd = "SCAN TYPE=" + type
757         else:
758             cmd = "SCAN"
759         if freq:
760             cmd = cmd + " freq=" + freq
761         if only_new:
762             cmd += " only_new=1"
763         if not no_wait:
764             self.dump_monitor()
765         if not "OK" in self.request(cmd):
766             raise Exception("Failed to trigger scan")
767         if no_wait:
768             return
769         ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
770         if ev is None:
771             raise Exception("Scan timed out")
772
773     def scan_for_bss(self, bssid, freq=None, force_scan=False):
774         if not force_scan and self.get_bss(bssid) is not None:
775             return
776         for i in range(0, 10):
777             self.scan(freq=freq, type="ONLY")
778             if self.get_bss(bssid) is not None:
779                 return
780         raise Exception("Could not find BSS " + bssid + " in scan")
781
782     def roam(self, bssid, fail_test=False):
783         self.dump_monitor()
784         if "OK" not in self.request("ROAM " + bssid):
785             raise Exception("ROAM failed")
786         if fail_test:
787             ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
788             if ev is not None:
789                 raise Exception("Unexpected connection")
790             self.dump_monitor()
791             return
792         ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
793         if ev is None:
794             raise Exception("Roaming with the AP timed out")
795         self.dump_monitor()
796
797     def roam_over_ds(self, bssid, fail_test=False):
798         self.dump_monitor()
799         if "OK" not in self.request("FT_DS " + bssid):
800             raise Exception("FT_DS failed")
801         if fail_test:
802             ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
803             if ev is not None:
804                 raise Exception("Unexpected connection")
805             self.dump_monitor()
806             return
807         ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
808         if ev is None:
809             raise Exception("Roaming with the AP timed out")
810         self.dump_monitor()
811
812     def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
813                 new_passphrase=None, no_wait=False):
814         self.dump_monitor()
815         if new_ssid:
816             self.request("WPS_REG " + bssid + " " + pin + " " +
817                          new_ssid.encode("hex") + " " + key_mgmt + " " +
818                          cipher + " " + new_passphrase.encode("hex"))
819             if no_wait:
820                 return
821             ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
822         else:
823             self.request("WPS_REG " + bssid + " " + pin)
824             if no_wait:
825                 return
826             ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
827             if ev is None:
828                 raise Exception("WPS cred timed out")
829             ev = self.wait_event(["WPS-FAIL"], timeout=15)
830         if ev is None:
831             raise Exception("WPS timed out")
832         ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
833         if ev is None:
834             raise Exception("Association with the AP timed out")
835
836     def relog(self):
837         self.request("RELOG")
838
839     def wait_completed(self, timeout=10):
840         for i in range(0, timeout * 2):
841             if self.get_status_field("wpa_state") == "COMPLETED":
842                 return
843             time.sleep(0.5)
844         raise Exception("Timeout while waiting for COMPLETED state")
845
846     def get_capability(self, field):
847         res = self.request("GET_CAPABILITY " + field)
848         if "FAIL" in res:
849             return None
850         return res.split(' ')
851
852     def get_bss(self, bssid):
853         res = self.request("BSS " + bssid)
854         if "FAIL" in res:
855             return None
856         lines = res.splitlines()
857         vals = dict()
858         for l in lines:
859             [name,value] = l.split('=', 1)
860             vals[name] = value
861         if len(vals) == 0:
862             return None
863         return vals
864
865     def get_pmksa(self, bssid):
866         res = self.request("PMKSA")
867         lines = res.splitlines()
868         for l in lines:
869             if bssid not in l:
870                 continue
871             vals = dict()
872             [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
873             vals['index'] = index
874             vals['pmkid'] = pmkid
875             vals['expiration'] = expiration
876             vals['opportunistic'] = opportunistic
877             return vals
878         return None
879
880     def get_sta(self, addr, info=None, next=False):
881         cmd = "STA-NEXT " if next else "STA "
882         if addr is None:
883             res = self.request("STA-FIRST")
884         elif info:
885             res = self.request(cmd + addr + " " + info)
886         else:
887             res = self.request(cmd + addr)
888         lines = res.splitlines()
889         vals = dict()
890         first = True
891         for l in lines:
892             if first:
893                 vals['addr'] = l
894                 first = False
895             else:
896                 [name,value] = l.split('=', 1)
897                 vals[name] = value
898         return vals
899
900     def mgmt_rx(self, timeout=5):
901         ev = self.wait_event(["MGMT-RX"], timeout=timeout)
902         if ev is None:
903             return None
904         msg = {}
905         items = ev.split(' ')
906         field,val = items[1].split('=')
907         if field != "freq":
908             raise Exception("Unexpected MGMT-RX event format: " + ev)
909         msg['freq'] = val
910         frame = binascii.unhexlify(items[4])
911         msg['frame'] = frame
912
913         hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
914         msg['fc'] = hdr[0]
915         msg['subtype'] = (hdr[0] >> 4) & 0xf
916         hdr = hdr[1:]
917         msg['duration'] = hdr[0]
918         hdr = hdr[1:]
919         msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
920         hdr = hdr[6:]
921         msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
922         hdr = hdr[6:]
923         msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
924         hdr = hdr[6:]
925         msg['seq_ctrl'] = hdr[0]
926         msg['payload'] = frame[24:]
927
928         return msg