wpasupplicant.py 39 KB

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