wpasupplicant.py 36 KB

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