wpasupplicant.py 46 KB

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