wpasupplicant.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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=1, expect_failure=False):
  610. go_neg_res = None
  611. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  612. "P2P-GO-NEG-FAILURE"], timeout)
  613. if ev is None:
  614. if expect_failure:
  615. return None
  616. raise Exception("Group formation timed out")
  617. if "P2P-GO-NEG-SUCCESS" in ev:
  618. go_neg_res = ev
  619. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  620. if ev is None:
  621. if expect_failure:
  622. return None
  623. raise Exception("Group formation timed out")
  624. self.dump_monitor()
  625. return self.group_form_result(ev, expect_failure, go_neg_res)
  626. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
  627. expect_failure=False, persistent=False,
  628. persistent_id=None, freq=None, provdisc=False,
  629. wait_group=True, freq2=None, max_oper_chwidth=None,
  630. ht40=False, vht=False):
  631. if not self.discover_peer(peer):
  632. raise Exception("Peer " + peer + " not found")
  633. self.dump_monitor()
  634. if pin:
  635. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  636. else:
  637. cmd = "P2P_CONNECT " + peer + " " + method
  638. if go_intent is not None:
  639. cmd = cmd + ' go_intent=' + str(go_intent)
  640. if freq:
  641. cmd = cmd + ' freq=' + str(freq)
  642. if freq2:
  643. cmd = cmd + ' freq2=' + str(freq2)
  644. if max_oper_chwidth:
  645. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  646. if ht40:
  647. cmd = cmd + ' ht40'
  648. if vht:
  649. cmd = cmd + ' vht'
  650. if persistent:
  651. cmd = cmd + " persistent"
  652. elif persistent_id:
  653. cmd = cmd + " persistent=" + persistent_id
  654. if provdisc:
  655. cmd = cmd + " provdisc"
  656. if "OK" in self.global_request(cmd):
  657. if timeout == 0:
  658. return None
  659. go_neg_res = None
  660. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  661. "P2P-GO-NEG-FAILURE"], timeout)
  662. if ev is None:
  663. if expect_failure:
  664. return None
  665. raise Exception("Group formation timed out")
  666. if "P2P-GO-NEG-SUCCESS" in ev:
  667. if not wait_group:
  668. return ev
  669. go_neg_res = ev
  670. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  671. if ev is None:
  672. if expect_failure:
  673. return None
  674. raise Exception("Group formation timed out")
  675. self.dump_monitor()
  676. return self.group_form_result(ev, expect_failure, go_neg_res)
  677. raise Exception("P2P_CONNECT failed")
  678. def wait_event(self, events, timeout=10):
  679. start = os.times()[4]
  680. while True:
  681. while self.mon.pending():
  682. ev = self.mon.recv()
  683. logger.debug(self.dbg + ": " + ev)
  684. for event in events:
  685. if event in ev:
  686. return ev
  687. now = os.times()[4]
  688. remaining = start + timeout - now
  689. if remaining <= 0:
  690. break
  691. if not self.mon.pending(timeout=remaining):
  692. break
  693. return None
  694. def wait_global_event(self, events, timeout):
  695. if self.global_iface is None:
  696. self.wait_event(events, timeout)
  697. else:
  698. start = os.times()[4]
  699. while True:
  700. while self.global_mon.pending():
  701. ev = self.global_mon.recv()
  702. logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
  703. for event in events:
  704. if event in ev:
  705. return ev
  706. now = os.times()[4]
  707. remaining = start + timeout - now
  708. if remaining <= 0:
  709. break
  710. if not self.global_mon.pending(timeout=remaining):
  711. break
  712. return None
  713. def wait_group_event(self, events, timeout=10):
  714. if self.group_ifname and self.group_ifname != self.ifname:
  715. if self.gctrl_mon is None:
  716. return None
  717. start = os.times()[4]
  718. while True:
  719. while self.gctrl_mon.pending():
  720. ev = self.gctrl_mon.recv()
  721. logger.debug(self.group_dbg + "(group): " + ev)
  722. for event in events:
  723. if event in ev:
  724. return ev
  725. now = os.times()[4]
  726. remaining = start + timeout - now
  727. if remaining <= 0:
  728. break
  729. if not self.gctrl_mon.pending(timeout=remaining):
  730. break
  731. return None
  732. return self.wait_event(events, timeout)
  733. def wait_go_ending_session(self):
  734. if self.gctrl_mon:
  735. try:
  736. self.gctrl_mon.detach()
  737. except:
  738. pass
  739. self.gctrl_mon = None
  740. timeout = 3 if self.hostname is None else 10
  741. ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=timeout)
  742. if ev is None:
  743. raise Exception("Group removal event timed out")
  744. if "reason=GO_ENDING_SESSION" not in ev:
  745. raise Exception("Unexpected group removal reason")
  746. def dump_monitor(self):
  747. count_iface = 0
  748. count_global = 0
  749. while self.mon.pending():
  750. ev = self.mon.recv()
  751. logger.debug(self.dbg + ": " + ev)
  752. count_iface += 1
  753. while self.global_mon and self.global_mon.pending():
  754. ev = self.global_mon.recv()
  755. logger.debug(self.global_dbg + self.ifname + "(global): " + ev)
  756. count_global += 1
  757. return (count_iface, count_global)
  758. def remove_group(self, ifname=None):
  759. if self.gctrl_mon:
  760. try:
  761. self.gctrl_mon.detach()
  762. except:
  763. pass
  764. self.gctrl_mon = None
  765. if ifname is None:
  766. ifname = self.group_ifname if self.group_ifname else self.ifname
  767. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  768. raise Exception("Group could not be removed")
  769. self.group_ifname = None
  770. def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
  771. self.dump_monitor()
  772. cmd = "P2P_GROUP_ADD"
  773. if persistent is None:
  774. pass
  775. elif persistent is True:
  776. cmd = cmd + " persistent"
  777. else:
  778. cmd = cmd + " persistent=" + str(persistent)
  779. if freq:
  780. cmd = cmd + " freq=" + str(freq)
  781. if "OK" in self.global_request(cmd):
  782. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  783. if ev is None:
  784. raise Exception("GO start up timed out")
  785. if not no_event_clear:
  786. self.dump_monitor()
  787. return self.group_form_result(ev)
  788. raise Exception("P2P_GROUP_ADD failed")
  789. def p2p_go_authorize_client(self, pin):
  790. cmd = "WPS_PIN any " + pin
  791. if "FAIL" in self.group_request(cmd):
  792. raise Exception("Failed to authorize client connection on GO")
  793. return None
  794. def p2p_go_authorize_client_pbc(self):
  795. cmd = "WPS_PBC"
  796. if "FAIL" in self.group_request(cmd):
  797. raise Exception("Failed to authorize client connection on GO")
  798. return None
  799. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  800. freq=None):
  801. self.dump_monitor()
  802. if not self.discover_peer(go_addr, social=social, freq=freq):
  803. if social or not self.discover_peer(go_addr, social=social):
  804. raise Exception("GO " + go_addr + " not found")
  805. self.p2p_stop_find()
  806. self.dump_monitor()
  807. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  808. if freq:
  809. cmd += " freq=" + str(freq)
  810. if "OK" in self.global_request(cmd):
  811. if timeout == 0:
  812. self.dump_monitor()
  813. return None
  814. ev = self.wait_global_event(["P2P-GROUP-STARTED",
  815. "P2P-GROUP-FORMATION-FAILURE"],
  816. timeout)
  817. if ev is None:
  818. raise Exception("Joining the group timed out")
  819. if "P2P-GROUP-STARTED" not in ev:
  820. raise Exception("Failed to join the group")
  821. self.dump_monitor()
  822. return self.group_form_result(ev)
  823. raise Exception("P2P_CONNECT(join) failed")
  824. def tdls_setup(self, peer):
  825. cmd = "TDLS_SETUP " + peer
  826. if "FAIL" in self.group_request(cmd):
  827. raise Exception("Failed to request TDLS setup")
  828. return None
  829. def tdls_teardown(self, peer):
  830. cmd = "TDLS_TEARDOWN " + peer
  831. if "FAIL" in self.group_request(cmd):
  832. raise Exception("Failed to request TDLS teardown")
  833. return None
  834. def tdls_link_status(self, peer):
  835. cmd = "TDLS_LINK_STATUS " + peer
  836. ret = self.group_request(cmd)
  837. if "FAIL" in ret:
  838. raise Exception("Failed to request TDLS link status")
  839. return ret
  840. def tspecs(self):
  841. """Return (tsid, up) tuples representing current tspecs"""
  842. res = self.request("WMM_AC_STATUS")
  843. tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
  844. tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
  845. logger.debug("tspecs: " + str(tspecs))
  846. return tspecs
  847. def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
  848. extra=None):
  849. params = {
  850. "sba": 9000,
  851. "nominal_msdu_size": 1500,
  852. "min_phy_rate": 6000000,
  853. "mean_data_rate": 1500,
  854. }
  855. cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
  856. for (key, value) in params.iteritems():
  857. cmd += " %s=%d" % (key, value)
  858. if extra:
  859. cmd += " " + extra
  860. if self.request(cmd).strip() != "OK":
  861. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  862. if expect_failure:
  863. ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
  864. if ev is None:
  865. raise Exception("ADDTS failed (time out while waiting failure)")
  866. if "tsid=%d" % (tsid) not in ev:
  867. raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
  868. return
  869. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  870. if ev is None:
  871. raise Exception("ADDTS failed (time out)")
  872. if "tsid=%d" % (tsid) not in ev:
  873. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  874. if not (tsid, up) in self.tspecs():
  875. raise Exception("ADDTS failed (tsid not in tspec list)")
  876. def del_ts(self, tsid):
  877. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  878. raise Exception("DELTS failed")
  879. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  880. if ev is None:
  881. raise Exception("DELTS failed (time out)")
  882. if "tsid=%d" % (tsid) not in ev:
  883. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  884. tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
  885. if tspecs:
  886. raise Exception("DELTS failed (still in tspec list)")
  887. def connect(self, ssid=None, ssid2=None, **kwargs):
  888. logger.info("Connect STA " + self.ifname + " to AP")
  889. id = self.add_network()
  890. if ssid:
  891. self.set_network_quoted(id, "ssid", ssid)
  892. elif ssid2:
  893. self.set_network(id, "ssid", ssid2)
  894. quoted = [ "psk", "identity", "anonymous_identity", "password",
  895. "ca_cert", "client_cert", "private_key",
  896. "private_key_passwd", "ca_cert2", "client_cert2",
  897. "private_key2", "phase1", "phase2", "domain_suffix_match",
  898. "altsubject_match", "subject_match", "pac_file", "dh_file",
  899. "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
  900. "domain_match" ]
  901. for field in quoted:
  902. if field in kwargs and kwargs[field]:
  903. self.set_network_quoted(id, field, kwargs[field])
  904. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  905. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  906. "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
  907. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  908. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  909. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  910. "disable_ht40", "disable_sgi", "disable_ldpc",
  911. "ht40_intolerant", "update_identifier", "mac_addr",
  912. "erp", "bg_scan_period", "bssid_blacklist",
  913. "bssid_whitelist", "mem_only_psk", "eap_workaround",
  914. "engine" ]
  915. for field in not_quoted:
  916. if field in kwargs and kwargs[field]:
  917. self.set_network(id, field, kwargs[field])
  918. if "raw_psk" in kwargs and kwargs['raw_psk']:
  919. self.set_network(id, "psk", kwargs['raw_psk'])
  920. if "password_hex" in kwargs and kwargs['password_hex']:
  921. self.set_network(id, "password", kwargs['password_hex'])
  922. if "peerkey" in kwargs and kwargs['peerkey']:
  923. self.set_network(id, "peerkey", "1")
  924. if "okc" in kwargs and kwargs['okc']:
  925. self.set_network(id, "proactive_key_caching", "1")
  926. if "ocsp" in kwargs and kwargs['ocsp']:
  927. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  928. if "only_add_network" in kwargs and kwargs['only_add_network']:
  929. return id
  930. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  931. if "eap" in kwargs:
  932. self.connect_network(id, timeout=20)
  933. else:
  934. self.connect_network(id)
  935. else:
  936. self.dump_monitor()
  937. self.select_network(id)
  938. return id
  939. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  940. if type:
  941. cmd = "SCAN TYPE=" + type
  942. else:
  943. cmd = "SCAN"
  944. if freq:
  945. cmd = cmd + " freq=" + str(freq)
  946. if only_new:
  947. cmd += " only_new=1"
  948. if not no_wait:
  949. self.dump_monitor()
  950. if not "OK" in self.request(cmd):
  951. raise Exception("Failed to trigger scan")
  952. if no_wait:
  953. return
  954. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS",
  955. "CTRL-EVENT-SCAN-FAILED"], 15)
  956. if ev is None:
  957. raise Exception("Scan timed out")
  958. if "CTRL-EVENT-SCAN-FAILED" in ev:
  959. raise Exception("Scan failed: " + ev)
  960. def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
  961. if not force_scan and self.get_bss(bssid) is not None:
  962. return
  963. for i in range(0, 10):
  964. self.scan(freq=freq, type="ONLY", only_new=only_new)
  965. if self.get_bss(bssid) is not None:
  966. return
  967. raise Exception("Could not find BSS " + bssid + " in scan")
  968. def flush_scan_cache(self, freq=2417):
  969. self.request("BSS_FLUSH 0")
  970. self.scan(freq=freq, only_new=True)
  971. res = self.request("SCAN_RESULTS")
  972. if len(res.splitlines()) > 1:
  973. self.request("BSS_FLUSH 0")
  974. self.scan(freq=2422, only_new=True)
  975. res = self.request("SCAN_RESULTS")
  976. if len(res.splitlines()) > 1:
  977. logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
  978. def roam(self, bssid, fail_test=False):
  979. self.dump_monitor()
  980. if "OK" not in self.request("ROAM " + bssid):
  981. raise Exception("ROAM 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 roam_over_ds(self, bssid, fail_test=False):
  991. self.dump_monitor()
  992. if "OK" not in self.request("FT_DS " + bssid):
  993. raise Exception("FT_DS failed")
  994. if fail_test:
  995. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  996. if ev is not None:
  997. raise Exception("Unexpected connection")
  998. self.dump_monitor()
  999. return
  1000. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  1001. self.dump_monitor()
  1002. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  1003. new_passphrase=None, no_wait=False):
  1004. self.dump_monitor()
  1005. if new_ssid:
  1006. self.request("WPS_REG " + bssid + " " + pin + " " +
  1007. new_ssid.encode("hex") + " " + key_mgmt + " " +
  1008. cipher + " " + new_passphrase.encode("hex"))
  1009. if no_wait:
  1010. return
  1011. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  1012. else:
  1013. self.request("WPS_REG " + bssid + " " + pin)
  1014. if no_wait:
  1015. return
  1016. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  1017. if ev is None:
  1018. raise Exception("WPS cred timed out")
  1019. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  1020. if ev is None:
  1021. raise Exception("WPS timed out")
  1022. self.wait_connected(timeout=15)
  1023. def relog(self):
  1024. self.global_request("RELOG")
  1025. def wait_completed(self, timeout=10):
  1026. for i in range(0, timeout * 2):
  1027. if self.get_status_field("wpa_state") == "COMPLETED":
  1028. return
  1029. time.sleep(0.5)
  1030. raise Exception("Timeout while waiting for COMPLETED state")
  1031. def get_capability(self, field):
  1032. res = self.request("GET_CAPABILITY " + field)
  1033. if "FAIL" in res:
  1034. return None
  1035. return res.split(' ')
  1036. def get_bss(self, bssid, ifname=None):
  1037. if not ifname or ifname == self.ifname:
  1038. res = self.request("BSS " + bssid)
  1039. elif ifname == self.group_ifname:
  1040. res = self.group_request("BSS " + bssid)
  1041. else:
  1042. return None
  1043. if "FAIL" in res:
  1044. return None
  1045. lines = res.splitlines()
  1046. vals = dict()
  1047. for l in lines:
  1048. [name,value] = l.split('=', 1)
  1049. vals[name] = value
  1050. if len(vals) == 0:
  1051. return None
  1052. return vals
  1053. def get_pmksa(self, bssid):
  1054. res = self.request("PMKSA")
  1055. lines = res.splitlines()
  1056. for l in lines:
  1057. if bssid not in l:
  1058. continue
  1059. vals = dict()
  1060. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  1061. vals['index'] = index
  1062. vals['pmkid'] = pmkid
  1063. vals['expiration'] = expiration
  1064. vals['opportunistic'] = opportunistic
  1065. return vals
  1066. return None
  1067. def get_sta(self, addr, info=None, next=False):
  1068. cmd = "STA-NEXT " if next else "STA "
  1069. if addr is None:
  1070. res = self.request("STA-FIRST")
  1071. elif info:
  1072. res = self.request(cmd + addr + " " + info)
  1073. else:
  1074. res = self.request(cmd + addr)
  1075. lines = res.splitlines()
  1076. vals = dict()
  1077. first = True
  1078. for l in lines:
  1079. if first:
  1080. vals['addr'] = l
  1081. first = False
  1082. else:
  1083. [name,value] = l.split('=', 1)
  1084. vals[name] = value
  1085. return vals
  1086. def mgmt_rx(self, timeout=5):
  1087. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  1088. if ev is None:
  1089. return None
  1090. msg = {}
  1091. items = ev.split(' ')
  1092. field,val = items[1].split('=')
  1093. if field != "freq":
  1094. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1095. msg['freq'] = val
  1096. field,val = items[2].split('=')
  1097. if field != "datarate":
  1098. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1099. msg['datarate'] = val
  1100. field,val = items[3].split('=')
  1101. if field != "ssi_signal":
  1102. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1103. msg['ssi_signal'] = val
  1104. frame = binascii.unhexlify(items[4])
  1105. msg['frame'] = frame
  1106. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  1107. msg['fc'] = hdr[0]
  1108. msg['subtype'] = (hdr[0] >> 4) & 0xf
  1109. hdr = hdr[1:]
  1110. msg['duration'] = hdr[0]
  1111. hdr = hdr[1:]
  1112. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1113. hdr = hdr[6:]
  1114. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1115. hdr = hdr[6:]
  1116. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1117. hdr = hdr[6:]
  1118. msg['seq_ctrl'] = hdr[0]
  1119. msg['payload'] = frame[24:]
  1120. return msg
  1121. def wait_connected(self, timeout=10, error="Connection timed out"):
  1122. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  1123. if ev is None:
  1124. raise Exception(error)
  1125. return ev
  1126. def wait_disconnected(self, timeout=None, error="Disconnection timed out"):
  1127. if timeout is None:
  1128. timeout = 10 if self.hostname is None else 30
  1129. ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
  1130. if ev is None:
  1131. raise Exception(error)
  1132. return ev
  1133. def get_group_ifname(self):
  1134. return self.group_ifname if self.group_ifname else self.ifname
  1135. def get_config(self):
  1136. res = self.request("DUMP")
  1137. if res.startswith("FAIL"):
  1138. raise Exception("DUMP failed")
  1139. lines = res.splitlines()
  1140. vals = dict()
  1141. for l in lines:
  1142. [name,value] = l.split('=', 1)
  1143. vals[name] = value
  1144. return vals
  1145. def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
  1146. method="1000", info="", status=None, cpt=None, role=None):
  1147. if status is None:
  1148. cmd = "P2P_ASP_PROVISION"
  1149. params = "info='%s' method=%s" % (info, method)
  1150. else:
  1151. cmd = "P2P_ASP_PROVISION_RESP"
  1152. params = "status=%d" % status
  1153. if role is not None:
  1154. params += " role=" + role
  1155. if cpt is not None:
  1156. params += " cpt=" + cpt
  1157. if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
  1158. (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
  1159. raise Exception("%s request failed" % cmd)