wpasupplicant.py 47 KB

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