wpasupplicant.py 45 KB

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