wpasupplicant.py 39 KB

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