wpasupplicant.py 44 KB

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