wpasupplicant.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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", "private_key_passwd" ]
  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=None):
  362. if timeout is None:
  363. timeout = 10 if self.hostname is None else 60
  364. self.dump_monitor()
  365. self.select_network(id)
  366. self.wait_connected(timeout=timeout)
  367. self.dump_monitor()
  368. def get_status(self, extra=None):
  369. if extra:
  370. extra = "-" + extra
  371. else:
  372. extra = ""
  373. res = self.request("STATUS" + extra)
  374. lines = res.splitlines()
  375. vals = dict()
  376. for l in lines:
  377. try:
  378. [name,value] = l.split('=', 1)
  379. vals[name] = value
  380. except ValueError, e:
  381. logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
  382. return vals
  383. def get_status_field(self, field, extra=None):
  384. vals = self.get_status(extra)
  385. if field in vals:
  386. return vals[field]
  387. return None
  388. def get_group_status(self, extra=None):
  389. if extra:
  390. extra = "-" + extra
  391. else:
  392. extra = ""
  393. res = self.group_request("STATUS" + extra)
  394. lines = res.splitlines()
  395. vals = dict()
  396. for l in lines:
  397. try:
  398. [name,value] = l.split('=', 1)
  399. except ValueError:
  400. logger.info(self.ifname + ": Ignore unexpected status line: " + l)
  401. continue
  402. vals[name] = value
  403. return vals
  404. def get_group_status_field(self, field, extra=None):
  405. vals = self.get_group_status(extra)
  406. if field in vals:
  407. return vals[field]
  408. return None
  409. def get_driver_status(self, ifname=None):
  410. if ifname is None:
  411. res = self.request("STATUS-DRIVER")
  412. else:
  413. res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
  414. if res.startswith("FAIL"):
  415. return dict()
  416. lines = res.splitlines()
  417. vals = dict()
  418. for l in lines:
  419. try:
  420. [name,value] = l.split('=', 1)
  421. except ValueError:
  422. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  423. continue
  424. vals[name] = value
  425. return vals
  426. def get_driver_status_field(self, field, ifname=None):
  427. vals = self.get_driver_status(ifname)
  428. if field in vals:
  429. return vals[field]
  430. return None
  431. def get_mcc(self):
  432. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  433. return 1 if mcc < 2 else mcc
  434. def get_mib(self):
  435. res = self.request("MIB")
  436. lines = res.splitlines()
  437. vals = dict()
  438. for l in lines:
  439. try:
  440. [name,value] = l.split('=', 1)
  441. vals[name] = value
  442. except ValueError, e:
  443. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  444. return vals
  445. def p2p_dev_addr(self):
  446. return self.get_status_field("p2p_device_address")
  447. def p2p_interface_addr(self):
  448. return self.get_group_status_field("address")
  449. def own_addr(self):
  450. try:
  451. res = self.p2p_interface_addr()
  452. except:
  453. res = self.p2p_dev_addr()
  454. return res
  455. def p2p_listen(self):
  456. return self.global_request("P2P_LISTEN")
  457. def p2p_ext_listen(self, period, interval):
  458. return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
  459. def p2p_cancel_ext_listen(self):
  460. return self.global_request("P2P_EXT_LISTEN")
  461. def p2p_find(self, social=False, progressive=False, dev_id=None,
  462. dev_type=None, delay=None, freq=None):
  463. cmd = "P2P_FIND"
  464. if social:
  465. cmd = cmd + " type=social"
  466. elif progressive:
  467. cmd = cmd + " type=progressive"
  468. if dev_id:
  469. cmd = cmd + " dev_id=" + dev_id
  470. if dev_type:
  471. cmd = cmd + " dev_type=" + dev_type
  472. if delay:
  473. cmd = cmd + " delay=" + str(delay)
  474. if freq:
  475. cmd = cmd + " freq=" + str(freq)
  476. return self.global_request(cmd)
  477. def p2p_stop_find(self):
  478. return self.global_request("P2P_STOP_FIND")
  479. def wps_read_pin(self):
  480. self.pin = self.request("WPS_PIN get").rstrip("\n")
  481. if "FAIL" in self.pin:
  482. raise Exception("Could not generate PIN")
  483. return self.pin
  484. def peer_known(self, peer, full=True):
  485. res = self.global_request("P2P_PEER " + peer)
  486. if peer.lower() not in res.lower():
  487. return False
  488. if not full:
  489. return True
  490. return "[PROBE_REQ_ONLY]" not in res
  491. def discover_peer(self, peer, full=True, timeout=15, social=True,
  492. force_find=False, freq=None):
  493. logger.info(self.ifname + ": Trying to discover peer " + peer)
  494. if not force_find and self.peer_known(peer, full):
  495. return True
  496. self.p2p_find(social, freq=freq)
  497. count = 0
  498. while count < timeout * 4:
  499. time.sleep(0.25)
  500. count = count + 1
  501. if self.peer_known(peer, full):
  502. return True
  503. return False
  504. def get_peer(self, peer):
  505. res = self.global_request("P2P_PEER " + peer)
  506. if peer.lower() not in res.lower():
  507. raise Exception("Peer information not available")
  508. lines = res.splitlines()
  509. vals = dict()
  510. for l in lines:
  511. if '=' in l:
  512. [name,value] = l.split('=', 1)
  513. vals[name] = value
  514. return vals
  515. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  516. if expect_failure:
  517. if "P2P-GROUP-STARTED" in ev:
  518. raise Exception("Group formation succeeded when expecting failure")
  519. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  520. s = re.split(exp, ev)
  521. if len(s) < 3:
  522. return None
  523. res = {}
  524. res['result'] = 'go-neg-failed'
  525. res['status'] = int(s[2])
  526. return res
  527. if "P2P-GROUP-STARTED" not in ev:
  528. raise Exception("No P2P-GROUP-STARTED event seen")
  529. 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.]*)'
  530. s = re.split(exp, ev)
  531. if len(s) < 11:
  532. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  533. s = re.split(exp, ev)
  534. if len(s) < 8:
  535. raise Exception("Could not parse P2P-GROUP-STARTED")
  536. res = {}
  537. res['result'] = 'success'
  538. res['ifname'] = s[2]
  539. self.group_ifname = s[2]
  540. try:
  541. if self.hostname is None:
  542. self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl,
  543. self.group_ifname))
  544. else:
  545. port = self.get_ctrl_iface_port(self.group_ifname)
  546. self.gctrl_mon = wpaspy.Ctrl(self.hostname, port)
  547. self.gctrl_mon.attach()
  548. except:
  549. logger.debug("Could not open monitor socket for group interface")
  550. self.gctrl_mon = None
  551. res['role'] = s[3]
  552. res['ssid'] = s[4]
  553. res['freq'] = s[5]
  554. if "[PERSISTENT]" in ev:
  555. res['persistent'] = True
  556. else:
  557. res['persistent'] = False
  558. p = re.match(r'psk=([0-9a-f]*)', s[6])
  559. if p:
  560. res['psk'] = p.group(1)
  561. p = re.match(r'passphrase="(.*)"', s[6])
  562. if p:
  563. res['passphrase'] = p.group(1)
  564. res['go_dev_addr'] = s[7]
  565. if len(s) > 8 and len(s[8]) > 0:
  566. res['ip_addr'] = s[8]
  567. if len(s) > 9:
  568. res['ip_mask'] = s[9]
  569. if len(s) > 10:
  570. res['go_ip_addr'] = s[10]
  571. if go_neg_res:
  572. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  573. s = re.split(exp, go_neg_res)
  574. if len(s) < 4:
  575. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  576. res['go_neg_role'] = s[2]
  577. res['go_neg_freq'] = s[3]
  578. return res
  579. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
  580. persistent=False, freq=None, freq2=None,
  581. max_oper_chwidth=None, ht40=False, vht=False):
  582. if not self.discover_peer(peer):
  583. raise Exception("Peer " + peer + " not found")
  584. self.dump_monitor()
  585. if pin:
  586. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  587. else:
  588. cmd = "P2P_CONNECT " + peer + " " + method + " auth"
  589. if go_intent:
  590. cmd = cmd + ' go_intent=' + str(go_intent)
  591. if freq:
  592. cmd = cmd + ' freq=' + str(freq)
  593. if freq2:
  594. cmd = cmd + ' freq2=' + str(freq2)
  595. if max_oper_chwidth:
  596. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  597. if ht40:
  598. cmd = cmd + ' ht40'
  599. if vht:
  600. cmd = cmd + ' vht'
  601. if persistent:
  602. cmd = cmd + " persistent"
  603. if "OK" in self.global_request(cmd):
  604. return None
  605. raise Exception("P2P_CONNECT (auth) failed")
  606. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  607. go_neg_res = None
  608. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  609. "P2P-GO-NEG-FAILURE"], timeout)
  610. if ev is None:
  611. if expect_failure:
  612. return None
  613. raise Exception("Group formation timed out")
  614. if "P2P-GO-NEG-SUCCESS" in ev:
  615. go_neg_res = ev
  616. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  617. if ev is None:
  618. if expect_failure:
  619. return None
  620. raise Exception("Group formation timed out")
  621. self.dump_monitor()
  622. return self.group_form_result(ev, expect_failure, go_neg_res)
  623. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
  624. expect_failure=False, persistent=False,
  625. persistent_id=None, freq=None, provdisc=False,
  626. wait_group=True, freq2=None, max_oper_chwidth=None,
  627. ht40=False, vht=False):
  628. if not self.discover_peer(peer):
  629. raise Exception("Peer " + peer + " not found")
  630. self.dump_monitor()
  631. if pin:
  632. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  633. else:
  634. cmd = "P2P_CONNECT " + peer + " " + method
  635. if go_intent is not None:
  636. cmd = cmd + ' go_intent=' + str(go_intent)
  637. if freq:
  638. cmd = cmd + ' freq=' + str(freq)
  639. if freq2:
  640. cmd = cmd + ' freq2=' + str(freq2)
  641. if max_oper_chwidth:
  642. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  643. if ht40:
  644. cmd = cmd + ' ht40'
  645. if vht:
  646. cmd = cmd + ' vht'
  647. if persistent:
  648. cmd = cmd + " persistent"
  649. elif persistent_id:
  650. cmd = cmd + " persistent=" + persistent_id
  651. if provdisc:
  652. cmd = cmd + " provdisc"
  653. if "OK" in self.global_request(cmd):
  654. if timeout == 0:
  655. return None
  656. go_neg_res = None
  657. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  658. "P2P-GO-NEG-FAILURE"], timeout)
  659. if ev is None:
  660. if expect_failure:
  661. return None
  662. raise Exception("Group formation timed out")
  663. if "P2P-GO-NEG-SUCCESS" in ev:
  664. if not wait_group:
  665. return ev
  666. go_neg_res = ev
  667. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  668. if ev is None:
  669. if expect_failure:
  670. return None
  671. raise Exception("Group formation timed out")
  672. self.dump_monitor()
  673. return self.group_form_result(ev, expect_failure, go_neg_res)
  674. raise Exception("P2P_CONNECT failed")
  675. def wait_event(self, events, timeout=10):
  676. start = os.times()[4]
  677. while True:
  678. while self.mon.pending():
  679. ev = self.mon.recv()
  680. logger.debug(self.dbg + ": " + ev)
  681. for event in events:
  682. if event in ev:
  683. return ev
  684. now = os.times()[4]
  685. remaining = start + timeout - now
  686. if remaining <= 0:
  687. break
  688. if not self.mon.pending(timeout=remaining):
  689. break
  690. return None
  691. def wait_global_event(self, events, timeout):
  692. if self.global_iface is None:
  693. self.wait_event(events, timeout)
  694. else:
  695. start = os.times()[4]
  696. while True:
  697. while self.global_mon.pending():
  698. ev = self.global_mon.recv()
  699. logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
  700. for event in events:
  701. if event in ev:
  702. return ev
  703. now = os.times()[4]
  704. remaining = start + timeout - now
  705. if remaining <= 0:
  706. break
  707. if not self.global_mon.pending(timeout=remaining):
  708. break
  709. return None
  710. def wait_group_event(self, events, timeout=10):
  711. if self.group_ifname and self.group_ifname != self.ifname:
  712. if self.gctrl_mon is None:
  713. return None
  714. start = os.times()[4]
  715. while True:
  716. while self.gctrl_mon.pending():
  717. ev = self.gctrl_mon.recv()
  718. logger.debug(self.group_dbg + "(group): " + ev)
  719. for event in events:
  720. if event in ev:
  721. return ev
  722. now = os.times()[4]
  723. remaining = start + timeout - now
  724. if remaining <= 0:
  725. break
  726. if not self.gctrl_mon.pending(timeout=remaining):
  727. break
  728. return None
  729. return self.wait_event(events, timeout)
  730. def wait_go_ending_session(self):
  731. if self.gctrl_mon:
  732. try:
  733. self.gctrl_mon.detach()
  734. except:
  735. pass
  736. self.gctrl_mon = None
  737. timeout = 3 if self.hostname is None else 10
  738. ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=timeout)
  739. if ev is None:
  740. raise Exception("Group removal event timed out")
  741. if "reason=GO_ENDING_SESSION" not in ev:
  742. raise Exception("Unexpected group removal reason")
  743. def dump_monitor(self):
  744. count_iface = 0
  745. count_global = 0
  746. while self.mon.pending():
  747. ev = self.mon.recv()
  748. logger.debug(self.dbg + ": " + ev)
  749. count_iface += 1
  750. while self.global_mon and self.global_mon.pending():
  751. ev = self.global_mon.recv()
  752. logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
  753. count_global += 1
  754. return (count_iface, count_global)
  755. def remove_group(self, ifname=None):
  756. if self.gctrl_mon:
  757. try:
  758. self.gctrl_mon.detach()
  759. except:
  760. pass
  761. self.gctrl_mon = None
  762. if ifname is None:
  763. ifname = self.group_ifname if self.group_ifname else self.ifname
  764. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  765. raise Exception("Group could not be removed")
  766. self.group_ifname = None
  767. def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
  768. self.dump_monitor()
  769. cmd = "P2P_GROUP_ADD"
  770. if persistent is None:
  771. pass
  772. elif persistent is True:
  773. cmd = cmd + " persistent"
  774. else:
  775. cmd = cmd + " persistent=" + str(persistent)
  776. if freq:
  777. cmd = cmd + " freq=" + str(freq)
  778. if "OK" in self.global_request(cmd):
  779. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  780. if ev is None:
  781. raise Exception("GO start up timed out")
  782. if not no_event_clear:
  783. self.dump_monitor()
  784. return self.group_form_result(ev)
  785. raise Exception("P2P_GROUP_ADD failed")
  786. def p2p_go_authorize_client(self, pin):
  787. cmd = "WPS_PIN any " + pin
  788. if "FAIL" in self.group_request(cmd):
  789. raise Exception("Failed to authorize client connection on GO")
  790. return None
  791. def p2p_go_authorize_client_pbc(self):
  792. cmd = "WPS_PBC"
  793. if "FAIL" in self.group_request(cmd):
  794. raise Exception("Failed to authorize client connection on GO")
  795. return None
  796. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  797. freq=None):
  798. self.dump_monitor()
  799. if not self.discover_peer(go_addr, social=social, freq=freq):
  800. if social or not self.discover_peer(go_addr, social=social):
  801. raise Exception("GO " + go_addr + " not found")
  802. self.p2p_stop_find()
  803. self.dump_monitor()
  804. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  805. if freq:
  806. cmd += " freq=" + str(freq)
  807. if "OK" in self.global_request(cmd):
  808. if timeout == 0:
  809. self.dump_monitor()
  810. return None
  811. ev = self.wait_global_event(["P2P-GROUP-STARTED",
  812. "P2P-GROUP-FORMATION-FAILURE"],
  813. timeout)
  814. if ev is None:
  815. raise Exception("Joining the group timed out")
  816. if "P2P-GROUP-STARTED" not in ev:
  817. raise Exception("Failed to join the group")
  818. self.dump_monitor()
  819. return self.group_form_result(ev)
  820. raise Exception("P2P_CONNECT(join) failed")
  821. def tdls_setup(self, peer):
  822. cmd = "TDLS_SETUP " + peer
  823. if "FAIL" in self.group_request(cmd):
  824. raise Exception("Failed to request TDLS setup")
  825. return None
  826. def tdls_teardown(self, peer):
  827. cmd = "TDLS_TEARDOWN " + peer
  828. if "FAIL" in self.group_request(cmd):
  829. raise Exception("Failed to request TDLS teardown")
  830. return None
  831. def tdls_link_status(self, peer):
  832. cmd = "TDLS_LINK_STATUS " + peer
  833. ret = self.group_request(cmd)
  834. if "FAIL" in ret:
  835. raise Exception("Failed to request TDLS link status")
  836. return ret
  837. def tspecs(self):
  838. """Return (tsid, up) tuples representing current tspecs"""
  839. res = self.request("WMM_AC_STATUS")
  840. tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
  841. tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
  842. logger.debug("tspecs: " + str(tspecs))
  843. return tspecs
  844. def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
  845. extra=None):
  846. params = {
  847. "sba": 9000,
  848. "nominal_msdu_size": 1500,
  849. "min_phy_rate": 6000000,
  850. "mean_data_rate": 1500,
  851. }
  852. cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
  853. for (key, value) in params.iteritems():
  854. cmd += " %s=%d" % (key, value)
  855. if extra:
  856. cmd += " " + extra
  857. if self.request(cmd).strip() != "OK":
  858. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  859. if expect_failure:
  860. ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
  861. if ev is None:
  862. raise Exception("ADDTS failed (time out while waiting failure)")
  863. if "tsid=%d" % (tsid) not in ev:
  864. raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
  865. return
  866. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  867. if ev is None:
  868. raise Exception("ADDTS failed (time out)")
  869. if "tsid=%d" % (tsid) not in ev:
  870. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  871. if not (tsid, up) in self.tspecs():
  872. raise Exception("ADDTS failed (tsid not in tspec list)")
  873. def del_ts(self, tsid):
  874. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  875. raise Exception("DELTS failed")
  876. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  877. if ev is None:
  878. raise Exception("DELTS failed (time out)")
  879. if "tsid=%d" % (tsid) not in ev:
  880. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  881. tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
  882. if tspecs:
  883. raise Exception("DELTS failed (still in tspec list)")
  884. def connect(self, ssid=None, ssid2=None, **kwargs):
  885. logger.info("Connect STA " + self.ifname + " to AP")
  886. id = self.add_network()
  887. if ssid:
  888. self.set_network_quoted(id, "ssid", ssid)
  889. elif ssid2:
  890. self.set_network(id, "ssid", ssid2)
  891. quoted = [ "psk", "identity", "anonymous_identity", "password",
  892. "ca_cert", "client_cert", "private_key",
  893. "private_key_passwd", "ca_cert2", "client_cert2",
  894. "private_key2", "phase1", "phase2", "domain_suffix_match",
  895. "altsubject_match", "subject_match", "pac_file", "dh_file",
  896. "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
  897. "domain_match" ]
  898. for field in quoted:
  899. if field in kwargs and kwargs[field]:
  900. self.set_network_quoted(id, field, kwargs[field])
  901. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  902. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  903. "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
  904. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  905. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  906. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  907. "disable_ht40", "disable_sgi", "disable_ldpc",
  908. "ht40_intolerant", "update_identifier", "mac_addr",
  909. "erp", "bg_scan_period", "bssid_blacklist",
  910. "bssid_whitelist", "mem_only_psk", "eap_workaround",
  911. "engine" ]
  912. for field in not_quoted:
  913. if field in kwargs and kwargs[field]:
  914. self.set_network(id, field, kwargs[field])
  915. if "raw_psk" in kwargs and kwargs['raw_psk']:
  916. self.set_network(id, "psk", kwargs['raw_psk'])
  917. if "password_hex" in kwargs and kwargs['password_hex']:
  918. self.set_network(id, "password", kwargs['password_hex'])
  919. if "peerkey" in kwargs and kwargs['peerkey']:
  920. self.set_network(id, "peerkey", "1")
  921. if "okc" in kwargs and kwargs['okc']:
  922. self.set_network(id, "proactive_key_caching", "1")
  923. if "ocsp" in kwargs and kwargs['ocsp']:
  924. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  925. if "only_add_network" in kwargs and kwargs['only_add_network']:
  926. return id
  927. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  928. if "eap" in kwargs:
  929. self.connect_network(id, timeout=20)
  930. else:
  931. self.connect_network(id)
  932. else:
  933. self.dump_monitor()
  934. self.select_network(id)
  935. return id
  936. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  937. if type:
  938. cmd = "SCAN TYPE=" + type
  939. else:
  940. cmd = "SCAN"
  941. if freq:
  942. cmd = cmd + " freq=" + str(freq)
  943. if only_new:
  944. cmd += " only_new=1"
  945. if not no_wait:
  946. self.dump_monitor()
  947. if not "OK" in self.request(cmd):
  948. raise Exception("Failed to trigger scan")
  949. if no_wait:
  950. return
  951. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  952. if ev is None:
  953. raise Exception("Scan timed out")
  954. def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
  955. if not force_scan and self.get_bss(bssid) is not None:
  956. return
  957. for i in range(0, 10):
  958. self.scan(freq=freq, type="ONLY", only_new=only_new)
  959. if self.get_bss(bssid) is not None:
  960. return
  961. raise Exception("Could not find BSS " + bssid + " in scan")
  962. def flush_scan_cache(self, freq=2417):
  963. self.request("BSS_FLUSH 0")
  964. self.scan(freq=freq, only_new=True)
  965. res = self.request("SCAN_RESULTS")
  966. if len(res.splitlines()) > 1:
  967. self.request("BSS_FLUSH 0")
  968. self.scan(freq=2422, only_new=True)
  969. res = self.request("SCAN_RESULTS")
  970. if len(res.splitlines()) > 1:
  971. logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
  972. def roam(self, bssid, fail_test=False):
  973. self.dump_monitor()
  974. if "OK" not in self.request("ROAM " + bssid):
  975. raise Exception("ROAM failed")
  976. if fail_test:
  977. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  978. if ev is not None:
  979. raise Exception("Unexpected connection")
  980. self.dump_monitor()
  981. return
  982. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  983. self.dump_monitor()
  984. def roam_over_ds(self, bssid, fail_test=False):
  985. self.dump_monitor()
  986. if "OK" not in self.request("FT_DS " + bssid):
  987. raise Exception("FT_DS failed")
  988. if fail_test:
  989. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  990. if ev is not None:
  991. raise Exception("Unexpected connection")
  992. self.dump_monitor()
  993. return
  994. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  995. self.dump_monitor()
  996. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  997. new_passphrase=None, no_wait=False):
  998. self.dump_monitor()
  999. if new_ssid:
  1000. self.request("WPS_REG " + bssid + " " + pin + " " +
  1001. new_ssid.encode("hex") + " " + key_mgmt + " " +
  1002. cipher + " " + new_passphrase.encode("hex"))
  1003. if no_wait:
  1004. return
  1005. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  1006. else:
  1007. self.request("WPS_REG " + bssid + " " + pin)
  1008. if no_wait:
  1009. return
  1010. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  1011. if ev is None:
  1012. raise Exception("WPS cred timed out")
  1013. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  1014. if ev is None:
  1015. raise Exception("WPS timed out")
  1016. self.wait_connected(timeout=15)
  1017. def relog(self):
  1018. self.global_request("RELOG")
  1019. def wait_completed(self, timeout=10):
  1020. for i in range(0, timeout * 2):
  1021. if self.get_status_field("wpa_state") == "COMPLETED":
  1022. return
  1023. time.sleep(0.5)
  1024. raise Exception("Timeout while waiting for COMPLETED state")
  1025. def get_capability(self, field):
  1026. res = self.request("GET_CAPABILITY " + field)
  1027. if "FAIL" in res:
  1028. return None
  1029. return res.split(' ')
  1030. def get_bss(self, bssid, ifname=None):
  1031. if not ifname or ifname == self.ifname:
  1032. res = self.request("BSS " + bssid)
  1033. elif ifname == self.group_ifname:
  1034. res = self.group_request("BSS " + bssid)
  1035. else:
  1036. return None
  1037. if "FAIL" in res:
  1038. return None
  1039. lines = res.splitlines()
  1040. vals = dict()
  1041. for l in lines:
  1042. [name,value] = l.split('=', 1)
  1043. vals[name] = value
  1044. if len(vals) == 0:
  1045. return None
  1046. return vals
  1047. def get_pmksa(self, bssid):
  1048. res = self.request("PMKSA")
  1049. lines = res.splitlines()
  1050. for l in lines:
  1051. if bssid not in l:
  1052. continue
  1053. vals = dict()
  1054. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  1055. vals['index'] = index
  1056. vals['pmkid'] = pmkid
  1057. vals['expiration'] = expiration
  1058. vals['opportunistic'] = opportunistic
  1059. return vals
  1060. return None
  1061. def get_sta(self, addr, info=None, next=False):
  1062. cmd = "STA-NEXT " if next else "STA "
  1063. if addr is None:
  1064. res = self.request("STA-FIRST")
  1065. elif info:
  1066. res = self.request(cmd + addr + " " + info)
  1067. else:
  1068. res = self.request(cmd + addr)
  1069. lines = res.splitlines()
  1070. vals = dict()
  1071. first = True
  1072. for l in lines:
  1073. if first:
  1074. vals['addr'] = l
  1075. first = False
  1076. else:
  1077. [name,value] = l.split('=', 1)
  1078. vals[name] = value
  1079. return vals
  1080. def mgmt_rx(self, timeout=5):
  1081. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  1082. if ev is None:
  1083. return None
  1084. msg = {}
  1085. items = ev.split(' ')
  1086. field,val = items[1].split('=')
  1087. if field != "freq":
  1088. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1089. msg['freq'] = val
  1090. field,val = items[2].split('=')
  1091. if field != "datarate":
  1092. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1093. msg['datarate'] = val
  1094. field,val = items[3].split('=')
  1095. if field != "ssi_signal":
  1096. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1097. msg['ssi_signal'] = val
  1098. frame = binascii.unhexlify(items[4])
  1099. msg['frame'] = frame
  1100. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  1101. msg['fc'] = hdr[0]
  1102. msg['subtype'] = (hdr[0] >> 4) & 0xf
  1103. hdr = hdr[1:]
  1104. msg['duration'] = hdr[0]
  1105. hdr = hdr[1:]
  1106. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1107. hdr = hdr[6:]
  1108. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1109. hdr = hdr[6:]
  1110. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1111. hdr = hdr[6:]
  1112. msg['seq_ctrl'] = hdr[0]
  1113. msg['payload'] = frame[24:]
  1114. return msg
  1115. def wait_connected(self, timeout=10, error="Connection timed out"):
  1116. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  1117. if ev is None:
  1118. raise Exception(error)
  1119. return ev
  1120. def wait_disconnected(self, timeout=None, error="Disconnection timed out"):
  1121. if timeout is None:
  1122. timeout = 10 if self.hostname is None else 30
  1123. ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
  1124. if ev is None:
  1125. raise Exception(error)
  1126. return ev
  1127. def get_group_ifname(self):
  1128. return self.group_ifname if self.group_ifname else self.ifname
  1129. def get_config(self):
  1130. res = self.request("DUMP")
  1131. if res.startswith("FAIL"):
  1132. raise Exception("DUMP failed")
  1133. lines = res.splitlines()
  1134. vals = dict()
  1135. for l in lines:
  1136. [name,value] = l.split('=', 1)
  1137. vals[name] = value
  1138. return vals
  1139. def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
  1140. method="1000", info="", status=None, cpt=None, role=None):
  1141. if status is None:
  1142. cmd = "P2P_ASP_PROVISION"
  1143. params = "info='%s' method=%s" % (info, method)
  1144. else:
  1145. cmd = "P2P_ASP_PROVISION_RESP"
  1146. params = "status=%d" % status
  1147. if role is not None:
  1148. params += " role=" + role
  1149. if cpt is not None:
  1150. params += " cpt=" + cpt
  1151. if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
  1152. (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
  1153. raise Exception("%s request failed" % cmd)