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