wpasupplicant.py 36 KB

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