wpasupplicant.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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. import os
  7. import time
  8. import logging
  9. import binascii
  10. import re
  11. import struct
  12. import wpaspy
  13. import remotehost
  14. import subprocess
  15. logger = logging.getLogger()
  16. wpas_ctrl = '/var/run/wpa_supplicant'
  17. class WpaSupplicant:
  18. def __init__(self, ifname=None, global_iface=None, hostname=None,
  19. port=9877, global_port=9878):
  20. self.hostname = hostname
  21. self.group_ifname = None
  22. self.gctrl_mon = None
  23. self.host = remotehost.Host(hostname, ifname)
  24. self._group_dbg = None
  25. if ifname:
  26. self.set_ifname(ifname, hostname, port)
  27. res = self.get_driver_status()
  28. if 'capa.flags' in res and int(res['capa.flags'], 0) & 0x20000000:
  29. self.p2p_dev_ifname = 'p2p-dev-' + self.ifname
  30. else:
  31. self.p2p_dev_ifname = ifname
  32. else:
  33. self.ifname = None
  34. self.global_iface = global_iface
  35. if global_iface:
  36. if hostname != None:
  37. self.global_ctrl = wpaspy.Ctrl(hostname, global_port)
  38. self.global_mon = wpaspy.Ctrl(hostname, global_port)
  39. self.global_dbg = hostname + "/" + str(global_port) + "/"
  40. else:
  41. self.global_ctrl = wpaspy.Ctrl(global_iface)
  42. self.global_mon = wpaspy.Ctrl(global_iface)
  43. self.global_dbg = ""
  44. self.global_mon.attach()
  45. else:
  46. self.global_mon = None
  47. def cmd_execute(self, cmd_array, shell=False):
  48. if self.hostname is None:
  49. if shell:
  50. cmd = ' '.join(cmd_array)
  51. else:
  52. cmd = cmd_array
  53. proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT,
  54. stdout=subprocess.PIPE, shell=shell)
  55. out = proc.communicate()[0]
  56. ret = proc.returncode
  57. return ret, out
  58. else:
  59. return self.host.execute(cmd_array)
  60. def terminate(self):
  61. if self.global_mon:
  62. self.global_mon.detach()
  63. self.global_mon = None
  64. self.global_ctrl.terminate()
  65. self.global_ctrl = None
  66. def close_ctrl(self):
  67. if self.global_mon:
  68. self.global_mon.detach()
  69. self.global_mon = None
  70. self.global_ctrl = None
  71. self.remove_ifname()
  72. def set_ifname(self, ifname, hostname=None, port=9877):
  73. self.ifname = ifname
  74. if hostname != None:
  75. self.ctrl = wpaspy.Ctrl(hostname, port)
  76. self.mon = wpaspy.Ctrl(hostname, port)
  77. self.host = remotehost.Host(hostname, ifname)
  78. self.dbg = hostname + "/" + ifname
  79. else:
  80. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  81. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  82. self.dbg = ifname
  83. self.mon.attach()
  84. def remove_ifname(self):
  85. if self.ifname:
  86. self.mon.detach()
  87. self.mon = None
  88. self.ctrl = None
  89. self.ifname = None
  90. def get_ctrl_iface_port(self, ifname):
  91. if self.hostname is None:
  92. return None
  93. res = self.global_request("INTERFACES ctrl")
  94. lines = res.splitlines()
  95. found = False
  96. for line in lines:
  97. words = line.split()
  98. if words[0] == ifname:
  99. found = True
  100. break
  101. if not found:
  102. raise Exception("Could not find UDP port for " + ifname)
  103. res = line.find("ctrl_iface=udp:")
  104. if res == -1:
  105. raise Exception("Wrong ctrl_interface format")
  106. words = line.split(":")
  107. return int(words[1])
  108. def interface_add(self, ifname, config="", driver="nl80211",
  109. drv_params=None, br_ifname=None, create=False,
  110. set_ifname=True, all_params=False, if_type=None):
  111. status, groups = self.host.execute(["id"])
  112. if status != 0:
  113. group = "admin"
  114. group = "admin" if "(admin)" in groups else "adm"
  115. cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
  116. if drv_params:
  117. cmd = cmd + '\t' + drv_params
  118. if br_ifname:
  119. if not drv_params:
  120. cmd += '\t'
  121. cmd += '\t' + br_ifname
  122. if create:
  123. if not br_ifname:
  124. cmd += '\t'
  125. if not drv_params:
  126. cmd += '\t'
  127. cmd += '\tcreate'
  128. if if_type:
  129. cmd += '\t' + if_type
  130. if all_params and not create:
  131. if not br_ifname:
  132. cmd += '\t'
  133. if not drv_params:
  134. cmd += '\t'
  135. cmd += '\t'
  136. if "FAIL" in self.global_request(cmd):
  137. raise Exception("Failed to add a dynamic wpa_supplicant interface")
  138. if not create and set_ifname:
  139. port = self.get_ctrl_iface_port(ifname)
  140. self.set_ifname(ifname, self.hostname, port)
  141. res = self.get_driver_status()
  142. if 'capa.flags' in res and int(res['capa.flags'], 0) & 0x20000000:
  143. self.p2p_dev_ifname = 'p2p-dev-' + self.ifname
  144. else:
  145. self.p2p_dev_ifname = ifname
  146. def interface_remove(self, ifname):
  147. self.remove_ifname()
  148. self.global_request("INTERFACE_REMOVE " + ifname)
  149. def request(self, cmd, timeout=10):
  150. logger.debug(self.dbg + ": CTRL: " + cmd)
  151. return self.ctrl.request(cmd, timeout=timeout)
  152. def global_request(self, cmd):
  153. if self.global_iface is None:
  154. return self.request(cmd)
  155. else:
  156. ifname = self.ifname or self.global_iface
  157. logger.debug(self.global_dbg + ifname + ": CTRL(global): " + cmd)
  158. return self.global_ctrl.request(cmd)
  159. @property
  160. def group_dbg(self):
  161. if self._group_dbg is not None:
  162. return self._group_dbg
  163. if self.group_ifname is None:
  164. raise Exception("Cannot have group_dbg without group_ifname")
  165. if self.hostname is None:
  166. self._group_dbg = self.group_ifname
  167. else:
  168. self._group_dbg = self.hostname + "/" + self.group_ifname
  169. return self._group_dbg
  170. def group_request(self, cmd):
  171. if self.group_ifname and self.group_ifname != self.ifname:
  172. if self.hostname is None:
  173. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  174. else:
  175. port = self.get_ctrl_iface_port(self.group_ifname)
  176. gctrl = wpaspy.Ctrl(self.hostname, port)
  177. logger.debug(self.group_dbg + ": CTRL(group): " + cmd)
  178. return gctrl.request(cmd)
  179. return self.request(cmd)
  180. def ping(self):
  181. return "PONG" in self.request("PING")
  182. def global_ping(self):
  183. return "PONG" in self.global_request("PING")
  184. def reset(self):
  185. self.dump_monitor()
  186. res = self.request("FLUSH")
  187. if not "OK" in res:
  188. logger.info("FLUSH to " + self.ifname + " failed: " + res)
  189. self.global_request("REMOVE_NETWORK all")
  190. self.global_request("SET p2p_no_group_iface 1")
  191. self.global_request("P2P_FLUSH")
  192. if self.gctrl_mon:
  193. try:
  194. self.gctrl_mon.detach()
  195. except:
  196. pass
  197. self.gctrl_mon = None
  198. self.group_ifname = None
  199. self.dump_monitor()
  200. iter = 0
  201. while iter < 60:
  202. state1 = self.get_driver_status_field("scan_state")
  203. p2pdev = "p2p-dev-" + self.ifname
  204. state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
  205. states = str(state1) + " " + str(state2)
  206. if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
  207. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  208. time.sleep(1)
  209. else:
  210. break
  211. iter = iter + 1
  212. if iter == 60:
  213. logger.error(self.ifname + ": Driver scan state did not clear")
  214. print "Trying to clear cfg80211/mac80211 scan state"
  215. status, buf = self.host.execute(["ifconfig", self.ifname, "down"])
  216. if status != 0:
  217. logger.info("ifconfig failed: " + buf)
  218. logger.info(status)
  219. status, buf = self.host.execute(["ifconfig", self.ifname, "up"])
  220. if status != 0:
  221. logger.info("ifconfig failed: " + buf)
  222. logger.info(status)
  223. if iter > 0:
  224. # The ongoing scan could have discovered BSSes or P2P peers
  225. logger.info("Run FLUSH again since scan was in progress")
  226. self.request("FLUSH")
  227. self.dump_monitor()
  228. if not self.ping():
  229. logger.info("No PING response from " + self.ifname + " after reset")
  230. def add_network(self):
  231. id = self.request("ADD_NETWORK")
  232. if "FAIL" in id:
  233. raise Exception("ADD_NETWORK failed")
  234. return int(id)
  235. def remove_network(self, id):
  236. id = self.request("REMOVE_NETWORK " + str(id))
  237. if "FAIL" in id:
  238. raise Exception("REMOVE_NETWORK failed")
  239. return None
  240. def get_network(self, id, field):
  241. res = self.request("GET_NETWORK " + str(id) + " " + field)
  242. if res == "FAIL\n":
  243. return None
  244. return res
  245. def set_network(self, id, field, value):
  246. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  247. if "FAIL" in res:
  248. raise Exception("SET_NETWORK failed")
  249. return None
  250. def set_network_quoted(self, id, field, value):
  251. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  252. if "FAIL" in res:
  253. raise Exception("SET_NETWORK failed")
  254. return None
  255. def p2pdev_request(self, cmd):
  256. return self.global_request("IFNAME=" + self.p2p_dev_ifname + " " + cmd)
  257. def p2pdev_add_network(self):
  258. id = self.p2pdev_request("ADD_NETWORK")
  259. if "FAIL" in id:
  260. raise Exception("p2pdev ADD_NETWORK failed")
  261. return int(id)
  262. def p2pdev_set_network(self, id, field, value):
  263. res = self.p2pdev_request("SET_NETWORK " + str(id) + " " + field + " " + value)
  264. if "FAIL" in res:
  265. raise Exception("p2pdev SET_NETWORK failed")
  266. return None
  267. def p2pdev_set_network_quoted(self, id, field, value):
  268. res = self.p2pdev_request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  269. if "FAIL" in res:
  270. raise Exception("p2pdev SET_NETWORK failed")
  271. return None
  272. def list_networks(self, p2p=False):
  273. if p2p:
  274. res = self.global_request("LIST_NETWORKS")
  275. else:
  276. res = self.request("LIST_NETWORKS")
  277. lines = res.splitlines()
  278. networks = []
  279. for l in lines:
  280. if "network id" in l:
  281. continue
  282. [id,ssid,bssid,flags] = l.split('\t')
  283. network = {}
  284. network['id'] = id
  285. network['ssid'] = ssid
  286. network['bssid'] = bssid
  287. network['flags'] = flags
  288. networks.append(network)
  289. return networks
  290. def hs20_enable(self, auto_interworking=False):
  291. self.request("SET interworking 1")
  292. self.request("SET hs20 1")
  293. if auto_interworking:
  294. self.request("SET auto_interworking 1")
  295. else:
  296. self.request("SET auto_interworking 0")
  297. def interworking_add_network(self, bssid):
  298. id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
  299. if "FAIL" in id or "OK" in id:
  300. raise Exception("INTERWORKING_ADD_NETWORK failed")
  301. return int(id)
  302. def add_cred(self):
  303. id = self.request("ADD_CRED")
  304. if "FAIL" in id:
  305. raise Exception("ADD_CRED failed")
  306. return int(id)
  307. def remove_cred(self, id):
  308. id = self.request("REMOVE_CRED " + str(id))
  309. if "FAIL" in id:
  310. raise Exception("REMOVE_CRED failed")
  311. return None
  312. def set_cred(self, id, field, value):
  313. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  314. if "FAIL" in res:
  315. raise Exception("SET_CRED failed")
  316. return None
  317. def set_cred_quoted(self, id, field, value):
  318. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  319. if "FAIL" in res:
  320. raise Exception("SET_CRED failed")
  321. return None
  322. def get_cred(self, id, field):
  323. return self.request("GET_CRED " + str(id) + " " + field)
  324. def add_cred_values(self, params):
  325. id = self.add_cred()
  326. quoted = [ "realm", "username", "password", "domain", "imsi",
  327. "excluded_ssid", "milenage", "ca_cert", "client_cert",
  328. "private_key", "domain_suffix_match", "provisioning_sp",
  329. "roaming_partner", "phase1", "phase2" ]
  330. for field in quoted:
  331. if field in params:
  332. self.set_cred_quoted(id, field, params[field])
  333. not_quoted = [ "eap", "roaming_consortium", "priority",
  334. "required_roaming_consortium", "sp_priority",
  335. "max_bss_load", "update_identifier", "req_conn_capab",
  336. "min_dl_bandwidth_home", "min_ul_bandwidth_home",
  337. "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
  338. for field in not_quoted:
  339. if field in params:
  340. self.set_cred(id, field, params[field])
  341. return id;
  342. def select_network(self, id, freq=None):
  343. if freq:
  344. extra = " freq=" + str(freq)
  345. else:
  346. extra = ""
  347. id = self.request("SELECT_NETWORK " + str(id) + extra)
  348. if "FAIL" in id:
  349. raise Exception("SELECT_NETWORK failed")
  350. return None
  351. def mesh_group_add(self, id):
  352. id = self.request("MESH_GROUP_ADD " + str(id))
  353. if "FAIL" in id:
  354. raise Exception("MESH_GROUP_ADD failed")
  355. return None
  356. def mesh_group_remove(self):
  357. id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
  358. if "FAIL" in id:
  359. raise Exception("MESH_GROUP_REMOVE failed")
  360. return None
  361. def connect_network(self, id, timeout=10):
  362. self.dump_monitor()
  363. self.select_network(id)
  364. self.wait_connected(timeout=timeout)
  365. self.dump_monitor()
  366. def get_status(self, extra=None):
  367. if extra:
  368. extra = "-" + extra
  369. else:
  370. extra = ""
  371. res = self.request("STATUS" + extra)
  372. lines = res.splitlines()
  373. vals = dict()
  374. for l in lines:
  375. try:
  376. [name,value] = l.split('=', 1)
  377. vals[name] = value
  378. except ValueError, e:
  379. logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
  380. return vals
  381. def get_status_field(self, field, extra=None):
  382. vals = self.get_status(extra)
  383. if field in vals:
  384. return vals[field]
  385. return None
  386. def get_group_status(self, extra=None):
  387. if extra:
  388. extra = "-" + extra
  389. else:
  390. extra = ""
  391. res = self.group_request("STATUS" + extra)
  392. lines = res.splitlines()
  393. vals = dict()
  394. for l in lines:
  395. try:
  396. [name,value] = l.split('=', 1)
  397. except ValueError:
  398. logger.info(self.ifname + ": Ignore unexpected status line: " + l)
  399. continue
  400. vals[name] = value
  401. return vals
  402. def get_group_status_field(self, field, extra=None):
  403. vals = self.get_group_status(extra)
  404. if field in vals:
  405. return vals[field]
  406. return None
  407. def get_driver_status(self, ifname=None):
  408. if ifname is None:
  409. res = self.request("STATUS-DRIVER")
  410. else:
  411. res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
  412. if res.startswith("FAIL"):
  413. return dict()
  414. lines = res.splitlines()
  415. vals = dict()
  416. for l in lines:
  417. try:
  418. [name,value] = l.split('=', 1)
  419. except ValueError:
  420. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  421. continue
  422. vals[name] = value
  423. return vals
  424. def get_driver_status_field(self, field, ifname=None):
  425. vals = self.get_driver_status(ifname)
  426. if field in vals:
  427. return vals[field]
  428. return None
  429. def get_mcc(self):
  430. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  431. return 1 if mcc < 2 else mcc
  432. def get_mib(self):
  433. res = self.request("MIB")
  434. lines = res.splitlines()
  435. vals = dict()
  436. for l in lines:
  437. try:
  438. [name,value] = l.split('=', 1)
  439. vals[name] = value
  440. except ValueError, e:
  441. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  442. return vals
  443. def p2p_dev_addr(self):
  444. return self.get_status_field("p2p_device_address")
  445. def p2p_interface_addr(self):
  446. return self.get_group_status_field("address")
  447. def own_addr(self):
  448. try:
  449. res = self.p2p_interface_addr()
  450. except:
  451. res = self.p2p_dev_addr()
  452. return res
  453. def p2p_listen(self):
  454. return self.global_request("P2P_LISTEN")
  455. def p2p_ext_listen(self, period, interval):
  456. return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
  457. def p2p_cancel_ext_listen(self):
  458. return self.global_request("P2P_EXT_LISTEN")
  459. def p2p_find(self, social=False, progressive=False, dev_id=None,
  460. dev_type=None, delay=None, freq=None):
  461. cmd = "P2P_FIND"
  462. if social:
  463. cmd = cmd + " type=social"
  464. elif progressive:
  465. cmd = cmd + " type=progressive"
  466. if dev_id:
  467. cmd = cmd + " dev_id=" + dev_id
  468. if dev_type:
  469. cmd = cmd + " dev_type=" + dev_type
  470. if delay:
  471. cmd = cmd + " delay=" + str(delay)
  472. if freq:
  473. cmd = cmd + " freq=" + str(freq)
  474. return self.global_request(cmd)
  475. def p2p_stop_find(self):
  476. return self.global_request("P2P_STOP_FIND")
  477. def wps_read_pin(self):
  478. self.pin = self.request("WPS_PIN get").rstrip("\n")
  479. if "FAIL" in self.pin:
  480. raise Exception("Could not generate PIN")
  481. return self.pin
  482. def peer_known(self, peer, full=True):
  483. res = self.global_request("P2P_PEER " + peer)
  484. if peer.lower() not in res.lower():
  485. return False
  486. if not full:
  487. return True
  488. return "[PROBE_REQ_ONLY]" not in res
  489. def discover_peer(self, peer, full=True, timeout=15, social=True,
  490. force_find=False, freq=None):
  491. logger.info(self.ifname + ": Trying to discover peer " + peer)
  492. if not force_find and self.peer_known(peer, full):
  493. return True
  494. self.p2p_find(social, freq=freq)
  495. count = 0
  496. while count < timeout * 4:
  497. time.sleep(0.25)
  498. count = count + 1
  499. if self.peer_known(peer, full):
  500. return True
  501. return False
  502. def get_peer(self, peer):
  503. res = self.global_request("P2P_PEER " + peer)
  504. if peer.lower() not in res.lower():
  505. raise Exception("Peer information not available")
  506. lines = res.splitlines()
  507. vals = dict()
  508. for l in lines:
  509. if '=' in l:
  510. [name,value] = l.split('=', 1)
  511. vals[name] = value
  512. return vals
  513. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  514. if expect_failure:
  515. if "P2P-GROUP-STARTED" in ev:
  516. raise Exception("Group formation succeeded when expecting failure")
  517. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  518. s = re.split(exp, ev)
  519. if len(s) < 3:
  520. return None
  521. res = {}
  522. res['result'] = 'go-neg-failed'
  523. res['status'] = int(s[2])
  524. return res
  525. if "P2P-GROUP-STARTED" not in ev:
  526. raise Exception("No P2P-GROUP-STARTED event seen")
  527. 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.]*)'
  528. s = re.split(exp, ev)
  529. if len(s) < 11:
  530. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  531. s = re.split(exp, ev)
  532. if len(s) < 8:
  533. raise Exception("Could not parse P2P-GROUP-STARTED")
  534. res = {}
  535. res['result'] = 'success'
  536. res['ifname'] = s[2]
  537. self.group_ifname = s[2]
  538. try:
  539. if self.hostname is None:
  540. self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl,
  541. self.group_ifname))
  542. else:
  543. port = self.get_ctrl_iface_port(self.group_ifname)
  544. self.gctrl_mon = wpaspy.Ctrl(self.hostname, port)
  545. self.gctrl_mon.attach()
  546. except:
  547. logger.debug("Could not open monitor socket for group interface")
  548. self.gctrl_mon = None
  549. res['role'] = s[3]
  550. res['ssid'] = s[4]
  551. res['freq'] = s[5]
  552. if "[PERSISTENT]" in ev:
  553. res['persistent'] = True
  554. else:
  555. res['persistent'] = False
  556. p = re.match(r'psk=([0-9a-f]*)', s[6])
  557. if p:
  558. res['psk'] = p.group(1)
  559. p = re.match(r'passphrase="(.*)"', s[6])
  560. if p:
  561. res['passphrase'] = p.group(1)
  562. res['go_dev_addr'] = s[7]
  563. if len(s) > 8 and len(s[8]) > 0:
  564. res['ip_addr'] = s[8]
  565. if len(s) > 9:
  566. res['ip_mask'] = s[9]
  567. if len(s) > 10:
  568. res['go_ip_addr'] = s[10]
  569. if go_neg_res:
  570. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  571. s = re.split(exp, go_neg_res)
  572. if len(s) < 4:
  573. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  574. res['go_neg_role'] = s[2]
  575. res['go_neg_freq'] = s[3]
  576. return res
  577. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
  578. persistent=False, freq=None, freq2=None,
  579. max_oper_chwidth=None, ht40=False, vht=False):
  580. if not self.discover_peer(peer):
  581. raise Exception("Peer " + peer + " not found")
  582. self.dump_monitor()
  583. if pin:
  584. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  585. else:
  586. cmd = "P2P_CONNECT " + peer + " " + method + " auth"
  587. if go_intent:
  588. cmd = cmd + ' go_intent=' + str(go_intent)
  589. if freq:
  590. cmd = cmd + ' freq=' + str(freq)
  591. if freq2:
  592. cmd = cmd + ' freq2=' + str(freq2)
  593. if max_oper_chwidth:
  594. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  595. if ht40:
  596. cmd = cmd + ' ht40'
  597. if vht:
  598. cmd = cmd + ' vht'
  599. if persistent:
  600. cmd = cmd + " persistent"
  601. if "OK" in self.global_request(cmd):
  602. return None
  603. raise Exception("P2P_CONNECT (auth) failed")
  604. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  605. go_neg_res = None
  606. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  607. "P2P-GO-NEG-FAILURE"], timeout);
  608. if ev is None:
  609. if expect_failure:
  610. return None
  611. raise Exception("Group formation timed out")
  612. if "P2P-GO-NEG-SUCCESS" in ev:
  613. go_neg_res = ev
  614. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  615. if ev is None:
  616. if expect_failure:
  617. return None
  618. raise Exception("Group formation timed out")
  619. self.dump_monitor()
  620. return self.group_form_result(ev, expect_failure, go_neg_res)
  621. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
  622. expect_failure=False, persistent=False,
  623. persistent_id=None, freq=None, provdisc=False,
  624. wait_group=True, freq2=None, max_oper_chwidth=None,
  625. ht40=False, vht=False):
  626. if not self.discover_peer(peer):
  627. raise Exception("Peer " + peer + " not found")
  628. self.dump_monitor()
  629. if pin:
  630. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  631. else:
  632. cmd = "P2P_CONNECT " + peer + " " + method
  633. if go_intent is not None:
  634. cmd = cmd + ' go_intent=' + str(go_intent)
  635. if freq:
  636. cmd = cmd + ' freq=' + str(freq)
  637. if freq2:
  638. cmd = cmd + ' freq2=' + str(freq2)
  639. if max_oper_chwidth:
  640. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  641. if ht40:
  642. cmd = cmd + ' ht40'
  643. if vht:
  644. cmd = cmd + ' vht'
  645. if persistent:
  646. cmd = cmd + " persistent"
  647. elif persistent_id:
  648. cmd = cmd + " persistent=" + persistent_id
  649. if provdisc:
  650. cmd = cmd + " provdisc"
  651. if "OK" in self.global_request(cmd):
  652. if timeout == 0:
  653. return None
  654. go_neg_res = None
  655. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  656. "P2P-GO-NEG-FAILURE"], timeout)
  657. if ev is None:
  658. if expect_failure:
  659. return None
  660. raise Exception("Group formation timed out")
  661. if "P2P-GO-NEG-SUCCESS" in ev:
  662. if not wait_group:
  663. return ev
  664. go_neg_res = ev
  665. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  666. if ev is None:
  667. if expect_failure:
  668. return None
  669. raise Exception("Group formation timed out")
  670. self.dump_monitor()
  671. return self.group_form_result(ev, expect_failure, go_neg_res)
  672. raise Exception("P2P_CONNECT failed")
  673. def wait_event(self, events, timeout=10):
  674. start = os.times()[4]
  675. while True:
  676. while self.mon.pending():
  677. ev = self.mon.recv()
  678. logger.debug(self.dbg + ": " + ev)
  679. for event in events:
  680. if event in ev:
  681. return ev
  682. now = os.times()[4]
  683. remaining = start + timeout - now
  684. if remaining <= 0:
  685. break
  686. if not self.mon.pending(timeout=remaining):
  687. break
  688. return None
  689. def wait_global_event(self, events, timeout):
  690. if self.global_iface is None:
  691. self.wait_event(events, timeout)
  692. else:
  693. start = os.times()[4]
  694. while True:
  695. while self.global_mon.pending():
  696. ev = self.global_mon.recv()
  697. logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
  698. for event in events:
  699. if event in ev:
  700. return ev
  701. now = os.times()[4]
  702. remaining = start + timeout - now
  703. if remaining <= 0:
  704. break
  705. if not self.global_mon.pending(timeout=remaining):
  706. break
  707. return None
  708. def wait_group_event(self, events, timeout=10):
  709. if self.group_ifname and self.group_ifname != self.ifname:
  710. if self.gctrl_mon is None:
  711. return None
  712. start = os.times()[4]
  713. while True:
  714. while self.gctrl_mon.pending():
  715. ev = self.gctrl_mon.recv()
  716. logger.debug(self.group_dbg + "(group): " + ev)
  717. for event in events:
  718. if event in ev:
  719. return ev
  720. now = os.times()[4]
  721. remaining = start + timeout - now
  722. if remaining <= 0:
  723. break
  724. if not self.gctrl_mon.pending(timeout=remaining):
  725. break
  726. return None
  727. return self.wait_event(events, timeout)
  728. def wait_go_ending_session(self):
  729. if self.gctrl_mon:
  730. try:
  731. self.gctrl_mon.detach()
  732. except:
  733. pass
  734. self.gctrl_mon = None
  735. ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
  736. if ev is None:
  737. raise Exception("Group removal event timed out")
  738. if "reason=GO_ENDING_SESSION" not in ev:
  739. raise Exception("Unexpected group removal reason")
  740. def dump_monitor(self):
  741. count_iface = 0
  742. count_global = 0
  743. while self.mon.pending():
  744. ev = self.mon.recv()
  745. logger.debug(self.dbg + ": " + ev)
  746. count_iface += 1
  747. while self.global_mon and self.global_mon.pending():
  748. ev = self.global_mon.recv()
  749. logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
  750. count_global += 1
  751. return (count_iface, count_global)
  752. def remove_group(self, ifname=None):
  753. if self.gctrl_mon:
  754. try:
  755. self.gctrl_mon.detach()
  756. except:
  757. pass
  758. self.gctrl_mon = None
  759. if ifname is None:
  760. ifname = self.group_ifname if self.group_ifname else self.ifname
  761. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  762. raise Exception("Group could not be removed")
  763. self.group_ifname = None
  764. def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
  765. self.dump_monitor()
  766. cmd = "P2P_GROUP_ADD"
  767. if persistent is None:
  768. pass
  769. elif persistent is True:
  770. cmd = cmd + " persistent"
  771. else:
  772. cmd = cmd + " persistent=" + str(persistent)
  773. if freq:
  774. cmd = cmd + " freq=" + str(freq)
  775. if "OK" in self.global_request(cmd):
  776. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  777. if ev is None:
  778. raise Exception("GO start up timed out")
  779. if not no_event_clear:
  780. self.dump_monitor()
  781. return self.group_form_result(ev)
  782. raise Exception("P2P_GROUP_ADD failed")
  783. def p2p_go_authorize_client(self, pin):
  784. cmd = "WPS_PIN any " + pin
  785. if "FAIL" in self.group_request(cmd):
  786. raise Exception("Failed to authorize client connection on GO")
  787. return None
  788. def p2p_go_authorize_client_pbc(self):
  789. cmd = "WPS_PBC"
  790. if "FAIL" in self.group_request(cmd):
  791. raise Exception("Failed to authorize client connection on GO")
  792. return None
  793. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  794. freq=None):
  795. self.dump_monitor()
  796. if not self.discover_peer(go_addr, social=social, freq=freq):
  797. if social or not self.discover_peer(go_addr, social=social):
  798. raise Exception("GO " + go_addr + " not found")
  799. self.p2p_stop_find()
  800. self.dump_monitor()
  801. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  802. if freq:
  803. cmd += " freq=" + str(freq)
  804. if "OK" in self.global_request(cmd):
  805. if timeout == 0:
  806. self.dump_monitor()
  807. return None
  808. ev = self.wait_global_event(["P2P-GROUP-STARTED",
  809. "P2P-GROUP-FORMATION-FAILURE"],
  810. timeout)
  811. if ev is None:
  812. raise Exception("Joining the group timed out")
  813. if "P2P-GROUP-STARTED" not in ev:
  814. raise Exception("Failed to join the group")
  815. self.dump_monitor()
  816. return self.group_form_result(ev)
  817. raise Exception("P2P_CONNECT(join) failed")
  818. def tdls_setup(self, peer):
  819. cmd = "TDLS_SETUP " + peer
  820. if "FAIL" in self.group_request(cmd):
  821. raise Exception("Failed to request TDLS setup")
  822. return None
  823. def tdls_teardown(self, peer):
  824. cmd = "TDLS_TEARDOWN " + peer
  825. if "FAIL" in self.group_request(cmd):
  826. raise Exception("Failed to request TDLS teardown")
  827. return None
  828. def tdls_link_status(self, peer):
  829. cmd = "TDLS_LINK_STATUS " + peer
  830. ret = self.group_request(cmd)
  831. if "FAIL" in ret:
  832. raise Exception("Failed to request TDLS link status")
  833. return ret
  834. def tspecs(self):
  835. """Return (tsid, up) tuples representing current tspecs"""
  836. res = self.request("WMM_AC_STATUS")
  837. tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
  838. tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
  839. logger.debug("tspecs: " + str(tspecs))
  840. return tspecs
  841. def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
  842. extra=None):
  843. params = {
  844. "sba": 9000,
  845. "nominal_msdu_size": 1500,
  846. "min_phy_rate": 6000000,
  847. "mean_data_rate": 1500,
  848. }
  849. cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
  850. for (key, value) in params.iteritems():
  851. cmd += " %s=%d" % (key, value)
  852. if extra:
  853. cmd += " " + extra
  854. if self.request(cmd).strip() != "OK":
  855. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  856. if expect_failure:
  857. ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
  858. if ev is None:
  859. raise Exception("ADDTS failed (time out while waiting failure)")
  860. if "tsid=%d" % (tsid) not in ev:
  861. raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
  862. return
  863. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  864. if ev is None:
  865. raise Exception("ADDTS failed (time out)")
  866. if "tsid=%d" % (tsid) not in ev:
  867. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  868. if not (tsid, up) in self.tspecs():
  869. raise Exception("ADDTS failed (tsid not in tspec list)")
  870. def del_ts(self, tsid):
  871. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  872. raise Exception("DELTS failed")
  873. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  874. if ev is None:
  875. raise Exception("DELTS failed (time out)")
  876. if "tsid=%d" % (tsid) not in ev:
  877. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  878. tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
  879. if tspecs:
  880. raise Exception("DELTS failed (still in tspec list)")
  881. def connect(self, ssid=None, ssid2=None, **kwargs):
  882. logger.info("Connect STA " + self.ifname + " to AP")
  883. id = self.add_network()
  884. if ssid:
  885. self.set_network_quoted(id, "ssid", ssid)
  886. elif ssid2:
  887. self.set_network(id, "ssid", ssid2)
  888. quoted = [ "psk", "identity", "anonymous_identity", "password",
  889. "ca_cert", "client_cert", "private_key",
  890. "private_key_passwd", "ca_cert2", "client_cert2",
  891. "private_key2", "phase1", "phase2", "domain_suffix_match",
  892. "altsubject_match", "subject_match", "pac_file", "dh_file",
  893. "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
  894. "domain_match" ]
  895. for field in quoted:
  896. if field in kwargs and kwargs[field]:
  897. self.set_network_quoted(id, field, kwargs[field])
  898. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  899. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  900. "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
  901. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  902. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  903. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  904. "disable_ht40", "disable_sgi", "disable_ldpc",
  905. "ht40_intolerant", "update_identifier", "mac_addr",
  906. "erp", "bg_scan_period", "bssid_blacklist",
  907. "bssid_whitelist", "mem_only_psk", "eap_workaround",
  908. "engine" ]
  909. for field in not_quoted:
  910. if field in kwargs and kwargs[field]:
  911. self.set_network(id, field, kwargs[field])
  912. if "raw_psk" in kwargs and kwargs['raw_psk']:
  913. self.set_network(id, "psk", kwargs['raw_psk'])
  914. if "password_hex" in kwargs and kwargs['password_hex']:
  915. self.set_network(id, "password", kwargs['password_hex'])
  916. if "peerkey" in kwargs and kwargs['peerkey']:
  917. self.set_network(id, "peerkey", "1")
  918. if "okc" in kwargs and kwargs['okc']:
  919. self.set_network(id, "proactive_key_caching", "1")
  920. if "ocsp" in kwargs and kwargs['ocsp']:
  921. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  922. if "only_add_network" in kwargs and kwargs['only_add_network']:
  923. return id
  924. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  925. if "eap" in kwargs:
  926. self.connect_network(id, timeout=20)
  927. else:
  928. self.connect_network(id)
  929. else:
  930. self.dump_monitor()
  931. self.select_network(id)
  932. return id
  933. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  934. if type:
  935. cmd = "SCAN TYPE=" + type
  936. else:
  937. cmd = "SCAN"
  938. if freq:
  939. cmd = cmd + " freq=" + str(freq)
  940. if only_new:
  941. cmd += " only_new=1"
  942. if not no_wait:
  943. self.dump_monitor()
  944. if not "OK" in self.request(cmd):
  945. raise Exception("Failed to trigger scan")
  946. if no_wait:
  947. return
  948. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  949. if ev is None:
  950. raise Exception("Scan timed out")
  951. def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
  952. if not force_scan and self.get_bss(bssid) is not None:
  953. return
  954. for i in range(0, 10):
  955. self.scan(freq=freq, type="ONLY", only_new=only_new)
  956. if self.get_bss(bssid) is not None:
  957. return
  958. raise Exception("Could not find BSS " + bssid + " in scan")
  959. def flush_scan_cache(self, freq=2417):
  960. self.request("BSS_FLUSH 0")
  961. self.scan(freq=freq, only_new=True)
  962. res = self.request("SCAN_RESULTS")
  963. if len(res.splitlines()) > 1:
  964. self.request("BSS_FLUSH 0")
  965. self.scan(freq=2422, only_new=True)
  966. res = self.request("SCAN_RESULTS")
  967. if len(res.splitlines()) > 1:
  968. logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
  969. def roam(self, bssid, fail_test=False):
  970. self.dump_monitor()
  971. if "OK" not in self.request("ROAM " + bssid):
  972. raise Exception("ROAM failed")
  973. if fail_test:
  974. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  975. if ev is not None:
  976. raise Exception("Unexpected connection")
  977. self.dump_monitor()
  978. return
  979. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  980. self.dump_monitor()
  981. def roam_over_ds(self, bssid, fail_test=False):
  982. self.dump_monitor()
  983. if "OK" not in self.request("FT_DS " + bssid):
  984. raise Exception("FT_DS failed")
  985. if fail_test:
  986. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  987. if ev is not None:
  988. raise Exception("Unexpected connection")
  989. self.dump_monitor()
  990. return
  991. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  992. self.dump_monitor()
  993. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  994. new_passphrase=None, no_wait=False):
  995. self.dump_monitor()
  996. if new_ssid:
  997. self.request("WPS_REG " + bssid + " " + pin + " " +
  998. new_ssid.encode("hex") + " " + key_mgmt + " " +
  999. cipher + " " + new_passphrase.encode("hex"))
  1000. if no_wait:
  1001. return
  1002. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  1003. else:
  1004. self.request("WPS_REG " + bssid + " " + pin)
  1005. if no_wait:
  1006. return
  1007. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  1008. if ev is None:
  1009. raise Exception("WPS cred timed out")
  1010. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  1011. if ev is None:
  1012. raise Exception("WPS timed out")
  1013. self.wait_connected(timeout=15)
  1014. def relog(self):
  1015. self.global_request("RELOG")
  1016. def wait_completed(self, timeout=10):
  1017. for i in range(0, timeout * 2):
  1018. if self.get_status_field("wpa_state") == "COMPLETED":
  1019. return
  1020. time.sleep(0.5)
  1021. raise Exception("Timeout while waiting for COMPLETED state")
  1022. def get_capability(self, field):
  1023. res = self.request("GET_CAPABILITY " + field)
  1024. if "FAIL" in res:
  1025. return None
  1026. return res.split(' ')
  1027. def get_bss(self, bssid, ifname=None):
  1028. if not ifname or ifname == self.ifname:
  1029. res = self.request("BSS " + bssid)
  1030. elif ifname == self.group_ifname:
  1031. res = self.group_request("BSS " + bssid)
  1032. else:
  1033. return None
  1034. if "FAIL" in res:
  1035. return None
  1036. lines = res.splitlines()
  1037. vals = dict()
  1038. for l in lines:
  1039. [name,value] = l.split('=', 1)
  1040. vals[name] = value
  1041. if len(vals) == 0:
  1042. return None
  1043. return vals
  1044. def get_pmksa(self, bssid):
  1045. res = self.request("PMKSA")
  1046. lines = res.splitlines()
  1047. for l in lines:
  1048. if bssid not in l:
  1049. continue
  1050. vals = dict()
  1051. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  1052. vals['index'] = index
  1053. vals['pmkid'] = pmkid
  1054. vals['expiration'] = expiration
  1055. vals['opportunistic'] = opportunistic
  1056. return vals
  1057. return None
  1058. def get_sta(self, addr, info=None, next=False):
  1059. cmd = "STA-NEXT " if next else "STA "
  1060. if addr is None:
  1061. res = self.request("STA-FIRST")
  1062. elif info:
  1063. res = self.request(cmd + addr + " " + info)
  1064. else:
  1065. res = self.request(cmd + addr)
  1066. lines = res.splitlines()
  1067. vals = dict()
  1068. first = True
  1069. for l in lines:
  1070. if first:
  1071. vals['addr'] = l
  1072. first = False
  1073. else:
  1074. [name,value] = l.split('=', 1)
  1075. vals[name] = value
  1076. return vals
  1077. def mgmt_rx(self, timeout=5):
  1078. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  1079. if ev is None:
  1080. return None
  1081. msg = {}
  1082. items = ev.split(' ')
  1083. field,val = items[1].split('=')
  1084. if field != "freq":
  1085. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1086. msg['freq'] = val
  1087. field,val = items[2].split('=')
  1088. if field != "datarate":
  1089. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1090. msg['datarate'] = val
  1091. field,val = items[3].split('=')
  1092. if field != "ssi_signal":
  1093. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1094. msg['ssi_signal'] = val
  1095. frame = binascii.unhexlify(items[4])
  1096. msg['frame'] = frame
  1097. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  1098. msg['fc'] = hdr[0]
  1099. msg['subtype'] = (hdr[0] >> 4) & 0xf
  1100. hdr = hdr[1:]
  1101. msg['duration'] = hdr[0]
  1102. hdr = hdr[1:]
  1103. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1104. hdr = hdr[6:]
  1105. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1106. hdr = hdr[6:]
  1107. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1108. hdr = hdr[6:]
  1109. msg['seq_ctrl'] = hdr[0]
  1110. msg['payload'] = frame[24:]
  1111. return msg
  1112. def wait_connected(self, timeout=10, error="Connection timed out"):
  1113. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  1114. if ev is None:
  1115. raise Exception(error)
  1116. return ev
  1117. def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
  1118. ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
  1119. if ev is None:
  1120. raise Exception(error)
  1121. return ev
  1122. def get_group_ifname(self):
  1123. return self.group_ifname if self.group_ifname else self.ifname
  1124. def get_config(self):
  1125. res = self.request("DUMP")
  1126. if res.startswith("FAIL"):
  1127. raise Exception("DUMP failed")
  1128. lines = res.splitlines()
  1129. vals = dict()
  1130. for l in lines:
  1131. [name,value] = l.split('=', 1)
  1132. vals[name] = value
  1133. return vals
  1134. def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
  1135. method="1000", info="", status=None, cpt=None, role=None):
  1136. if status is None:
  1137. cmd = "P2P_ASP_PROVISION"
  1138. params = "info='%s' method=%s" % (info, method)
  1139. else:
  1140. cmd = "P2P_ASP_PROVISION_RESP"
  1141. params = "status=%d" % status
  1142. if role is not None:
  1143. params += " role=" + role
  1144. if cpt is not None:
  1145. params += " cpt=" + cpt
  1146. if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
  1147. (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
  1148. raise Exception("%s request failed" % cmd)