wpasupplicant.py 47 KB

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