wpasupplicant.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. if res.startswith("FAIL"):
  323. return dict()
  324. lines = res.splitlines()
  325. vals = dict()
  326. for l in lines:
  327. try:
  328. [name,value] = l.split('=', 1)
  329. except ValueError:
  330. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  331. continue
  332. vals[name] = value
  333. return vals
  334. def get_driver_status_field(self, field, ifname=None):
  335. vals = self.get_driver_status(ifname)
  336. if field in vals:
  337. return vals[field]
  338. return None
  339. def get_mcc(self):
  340. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  341. return 1 if mcc < 2 else mcc
  342. def get_mib(self):
  343. res = self.request("MIB")
  344. lines = res.splitlines()
  345. vals = dict()
  346. for l in lines:
  347. try:
  348. [name,value] = l.split('=', 1)
  349. vals[name] = value
  350. except ValueError, e:
  351. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  352. return vals
  353. def p2p_dev_addr(self):
  354. return self.get_status_field("p2p_device_address")
  355. def p2p_interface_addr(self):
  356. return self.get_group_status_field("address")
  357. def own_addr(self):
  358. try:
  359. res = self.p2p_interface_addr()
  360. except:
  361. res = self.p2p_dev_addr()
  362. return res
  363. def p2p_listen(self):
  364. return self.global_request("P2P_LISTEN")
  365. def p2p_find(self, social=False, progressive=False, dev_id=None,
  366. dev_type=None, delay=None, freq=None):
  367. cmd = "P2P_FIND"
  368. if social:
  369. cmd = cmd + " type=social"
  370. elif progressive:
  371. cmd = cmd + " type=progressive"
  372. if dev_id:
  373. cmd = cmd + " dev_id=" + dev_id
  374. if dev_type:
  375. cmd = cmd + " dev_type=" + dev_type
  376. if delay:
  377. cmd = cmd + " delay=" + str(delay)
  378. if freq:
  379. cmd = cmd + " freq=" + str(freq)
  380. return self.global_request(cmd)
  381. def p2p_stop_find(self):
  382. return self.global_request("P2P_STOP_FIND")
  383. def wps_read_pin(self):
  384. self.pin = self.request("WPS_PIN get").rstrip("\n")
  385. if "FAIL" in self.pin:
  386. raise Exception("Could not generate PIN")
  387. return self.pin
  388. def peer_known(self, peer, full=True):
  389. res = self.global_request("P2P_PEER " + peer)
  390. if peer.lower() not in res.lower():
  391. return False
  392. if not full:
  393. return True
  394. return "[PROBE_REQ_ONLY]" not in res
  395. def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
  396. logger.info(self.ifname + ": Trying to discover peer " + peer)
  397. if not force_find and self.peer_known(peer, full):
  398. return True
  399. self.p2p_find(social)
  400. count = 0
  401. while count < timeout * 4:
  402. time.sleep(0.25)
  403. count = count + 1
  404. if self.peer_known(peer, full):
  405. return True
  406. return False
  407. def get_peer(self, peer):
  408. res = self.global_request("P2P_PEER " + peer)
  409. if peer.lower() not in res.lower():
  410. raise Exception("Peer information not available")
  411. lines = res.splitlines()
  412. vals = dict()
  413. for l in lines:
  414. if '=' in l:
  415. [name,value] = l.split('=', 1)
  416. vals[name] = value
  417. return vals
  418. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  419. if expect_failure:
  420. if "P2P-GROUP-STARTED" in ev:
  421. raise Exception("Group formation succeeded when expecting failure")
  422. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  423. s = re.split(exp, ev)
  424. if len(s) < 3:
  425. return None
  426. res = {}
  427. res['result'] = 'go-neg-failed'
  428. res['status'] = int(s[2])
  429. return res
  430. if "P2P-GROUP-STARTED" not in ev:
  431. raise Exception("No P2P-GROUP-STARTED event seen")
  432. 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.]*)'
  433. s = re.split(exp, ev)
  434. if len(s) < 11:
  435. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  436. s = re.split(exp, ev)
  437. if len(s) < 8:
  438. raise Exception("Could not parse P2P-GROUP-STARTED")
  439. res = {}
  440. res['result'] = 'success'
  441. res['ifname'] = s[2]
  442. self.group_ifname = s[2]
  443. try:
  444. self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  445. self.gctrl_mon.attach()
  446. except:
  447. logger.debug("Could not open monitor socket for group interface")
  448. self.gctrl_mon = None
  449. res['role'] = s[3]
  450. res['ssid'] = s[4]
  451. res['freq'] = s[5]
  452. if "[PERSISTENT]" in ev:
  453. res['persistent'] = True
  454. else:
  455. res['persistent'] = False
  456. p = re.match(r'psk=([0-9a-f]*)', s[6])
  457. if p:
  458. res['psk'] = p.group(1)
  459. p = re.match(r'passphrase="(.*)"', s[6])
  460. if p:
  461. res['passphrase'] = p.group(1)
  462. res['go_dev_addr'] = s[7]
  463. if len(s) > 8 and len(s[8]) > 0:
  464. res['ip_addr'] = s[8]
  465. if len(s) > 9:
  466. res['ip_mask'] = s[9]
  467. if len(s) > 10:
  468. res['go_ip_addr'] = s[10]
  469. if go_neg_res:
  470. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  471. s = re.split(exp, go_neg_res)
  472. if len(s) < 4:
  473. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  474. res['go_neg_role'] = s[2]
  475. res['go_neg_freq'] = s[3]
  476. return res
  477. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
  478. if not self.discover_peer(peer):
  479. raise Exception("Peer " + peer + " not found")
  480. self.dump_monitor()
  481. if pin:
  482. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  483. else:
  484. cmd = "P2P_CONNECT " + peer + " " + method + " auth"
  485. if go_intent:
  486. cmd = cmd + ' go_intent=' + str(go_intent)
  487. if freq:
  488. cmd = cmd + ' freq=' + str(freq)
  489. if persistent:
  490. cmd = cmd + " persistent"
  491. if "OK" in self.global_request(cmd):
  492. return None
  493. raise Exception("P2P_CONNECT (auth) failed")
  494. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  495. go_neg_res = None
  496. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  497. "P2P-GO-NEG-FAILURE"], timeout);
  498. if ev is None:
  499. if expect_failure:
  500. return None
  501. raise Exception("Group formation timed out")
  502. if "P2P-GO-NEG-SUCCESS" in ev:
  503. go_neg_res = ev
  504. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  505. if ev is None:
  506. if expect_failure:
  507. return None
  508. raise Exception("Group formation timed out")
  509. self.dump_monitor()
  510. return self.group_form_result(ev, expect_failure, go_neg_res)
  511. 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):
  512. if not self.discover_peer(peer):
  513. raise Exception("Peer " + peer + " not found")
  514. self.dump_monitor()
  515. if pin:
  516. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  517. else:
  518. cmd = "P2P_CONNECT " + peer + " " + method
  519. if go_intent:
  520. cmd = cmd + ' go_intent=' + str(go_intent)
  521. if freq:
  522. cmd = cmd + ' freq=' + str(freq)
  523. if persistent:
  524. cmd = cmd + " persistent"
  525. elif persistent_id:
  526. cmd = cmd + " persistent=" + persistent_id
  527. if provdisc:
  528. cmd = cmd + " provdisc"
  529. if "OK" in self.global_request(cmd):
  530. if timeout == 0:
  531. self.dump_monitor()
  532. return None
  533. go_neg_res = None
  534. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  535. "P2P-GO-NEG-FAILURE"], timeout)
  536. if ev is None:
  537. if expect_failure:
  538. return None
  539. raise Exception("Group formation timed out")
  540. if "P2P-GO-NEG-SUCCESS" in ev:
  541. if not wait_group:
  542. return ev
  543. go_neg_res = ev
  544. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  545. if ev is None:
  546. if expect_failure:
  547. return None
  548. raise Exception("Group formation timed out")
  549. self.dump_monitor()
  550. return self.group_form_result(ev, expect_failure, go_neg_res)
  551. raise Exception("P2P_CONNECT failed")
  552. def wait_event(self, events, timeout=10):
  553. start = os.times()[4]
  554. while True:
  555. while self.mon.pending():
  556. ev = self.mon.recv()
  557. logger.debug(self.ifname + ": " + ev)
  558. for event in events:
  559. if event in ev:
  560. return ev
  561. now = os.times()[4]
  562. remaining = start + timeout - now
  563. if remaining <= 0:
  564. break
  565. if not self.mon.pending(timeout=remaining):
  566. break
  567. return None
  568. def wait_global_event(self, events, timeout):
  569. if self.global_iface is None:
  570. self.wait_event(events, timeout)
  571. else:
  572. start = os.times()[4]
  573. while True:
  574. while self.global_mon.pending():
  575. ev = self.global_mon.recv()
  576. logger.debug(self.ifname + "(global): " + ev)
  577. for event in events:
  578. if event in ev:
  579. return ev
  580. now = os.times()[4]
  581. remaining = start + timeout - now
  582. if remaining <= 0:
  583. break
  584. if not self.global_mon.pending(timeout=remaining):
  585. break
  586. return None
  587. def wait_group_event(self, events, timeout=10):
  588. if self.group_ifname and self.group_ifname != self.ifname:
  589. if self.gctrl_mon is None:
  590. return None
  591. start = os.times()[4]
  592. while True:
  593. while self.gctrl_mon.pending():
  594. ev = self.gctrl_mon.recv()
  595. logger.debug(self.group_ifname + ": " + ev)
  596. for event in events:
  597. if event in ev:
  598. return ev
  599. now = os.times()[4]
  600. remaining = start + timeout - now
  601. if remaining <= 0:
  602. break
  603. if not self.gctrl_mon.pending(timeout=remaining):
  604. break
  605. return None
  606. return self.wait_event(events, timeout)
  607. def wait_go_ending_session(self):
  608. if self.gctrl_mon:
  609. try:
  610. self.gctrl_mon.detach()
  611. except:
  612. pass
  613. self.gctrl_mon = None
  614. ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
  615. if ev is None:
  616. raise Exception("Group removal event timed out")
  617. if "reason=GO_ENDING_SESSION" not in ev:
  618. raise Exception("Unexpected group removal reason")
  619. def dump_monitor(self):
  620. while self.mon.pending():
  621. ev = self.mon.recv()
  622. logger.debug(self.ifname + ": " + ev)
  623. while self.global_mon and self.global_mon.pending():
  624. ev = self.global_mon.recv()
  625. logger.debug(self.ifname + "(global): " + ev)
  626. def remove_group(self, ifname=None):
  627. if self.gctrl_mon:
  628. try:
  629. self.gctrl_mon.detach()
  630. except:
  631. pass
  632. self.gctrl_mon = None
  633. if ifname is None:
  634. ifname = self.group_ifname if self.group_ifname else self.ifname
  635. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  636. raise Exception("Group could not be removed")
  637. self.group_ifname = None
  638. def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
  639. self.dump_monitor()
  640. cmd = "P2P_GROUP_ADD"
  641. if persistent is None:
  642. pass
  643. elif persistent is True:
  644. cmd = cmd + " persistent"
  645. else:
  646. cmd = cmd + " persistent=" + str(persistent)
  647. if freq:
  648. cmd = cmd + " freq=" + str(freq)
  649. if "OK" in self.global_request(cmd):
  650. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  651. if ev is None:
  652. raise Exception("GO start up timed out")
  653. if not no_event_clear:
  654. self.dump_monitor()
  655. return self.group_form_result(ev)
  656. raise Exception("P2P_GROUP_ADD failed")
  657. def p2p_go_authorize_client(self, pin):
  658. cmd = "WPS_PIN any " + pin
  659. if "FAIL" in self.group_request(cmd):
  660. raise Exception("Failed to authorize client connection on GO")
  661. return None
  662. def p2p_go_authorize_client_pbc(self):
  663. cmd = "WPS_PBC"
  664. if "FAIL" in self.group_request(cmd):
  665. raise Exception("Failed to authorize client connection on GO")
  666. return None
  667. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  668. freq=None):
  669. self.dump_monitor()
  670. if not self.discover_peer(go_addr, social=social):
  671. if social or not self.discover_peer(go_addr, social=social):
  672. raise Exception("GO " + go_addr + " not found")
  673. self.dump_monitor()
  674. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  675. if freq:
  676. cmd += " freq=" + str(freq)
  677. if "OK" in self.global_request(cmd):
  678. if timeout == 0:
  679. self.dump_monitor()
  680. return None
  681. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  682. if ev is None:
  683. raise Exception("Joining the group timed out")
  684. self.dump_monitor()
  685. return self.group_form_result(ev)
  686. raise Exception("P2P_CONNECT(join) failed")
  687. def tdls_setup(self, peer):
  688. cmd = "TDLS_SETUP " + peer
  689. if "FAIL" in self.group_request(cmd):
  690. raise Exception("Failed to request TDLS setup")
  691. return None
  692. def tdls_teardown(self, peer):
  693. cmd = "TDLS_TEARDOWN " + peer
  694. if "FAIL" in self.group_request(cmd):
  695. raise Exception("Failed to request TDLS teardown")
  696. return None
  697. def tdls_link_status(self, peer):
  698. cmd = "TDLS_LINK_STATUS " + peer
  699. ret = self.group_request(cmd)
  700. if "FAIL" in ret:
  701. raise Exception("Failed to request TDLS link status")
  702. return ret
  703. def tspecs(self):
  704. """Return (tsid, up) tuples representing current tspecs"""
  705. res = self.request("WMM_AC_STATUS")
  706. tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
  707. tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
  708. logger.debug("tspecs: " + str(tspecs))
  709. return tspecs
  710. def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
  711. extra=None):
  712. params = {
  713. "sba": 9000,
  714. "nominal_msdu_size": 1500,
  715. "min_phy_rate": 6000000,
  716. "mean_data_rate": 1500,
  717. }
  718. cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
  719. for (key, value) in params.iteritems():
  720. cmd += " %s=%d" % (key, value)
  721. if extra:
  722. cmd += " " + extra
  723. if self.request(cmd).strip() != "OK":
  724. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  725. if expect_failure:
  726. ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
  727. if ev is None:
  728. raise Exception("ADDTS failed (time out while waiting failure)")
  729. if "tsid=%d" % (tsid) not in ev:
  730. raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
  731. return
  732. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  733. if ev is None:
  734. raise Exception("ADDTS failed (time out)")
  735. if "tsid=%d" % (tsid) not in ev:
  736. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  737. if not (tsid, up) in self.tspecs():
  738. raise Exception("ADDTS failed (tsid not in tspec list)")
  739. def del_ts(self, tsid):
  740. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  741. raise Exception("DELTS failed")
  742. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  743. if ev is None:
  744. raise Exception("DELTS failed (time out)")
  745. if "tsid=%d" % (tsid) not in ev:
  746. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  747. tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
  748. if tspecs:
  749. raise Exception("DELTS failed (still in tspec list)")
  750. def connect(self, ssid=None, ssid2=None, **kwargs):
  751. logger.info("Connect STA " + self.ifname + " to AP")
  752. id = self.add_network()
  753. if ssid:
  754. self.set_network_quoted(id, "ssid", ssid)
  755. elif ssid2:
  756. self.set_network(id, "ssid", ssid2)
  757. quoted = [ "psk", "identity", "anonymous_identity", "password",
  758. "ca_cert", "client_cert", "private_key",
  759. "private_key_passwd", "ca_cert2", "client_cert2",
  760. "private_key2", "phase1", "phase2", "domain_suffix_match",
  761. "altsubject_match", "subject_match", "pac_file", "dh_file",
  762. "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
  763. "domain_match" ]
  764. for field in quoted:
  765. if field in kwargs and kwargs[field]:
  766. self.set_network_quoted(id, field, kwargs[field])
  767. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  768. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  769. "wep_tx_keyidx", "scan_freq", "eap",
  770. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  771. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  772. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  773. "disable_ht40", "disable_sgi", "disable_ldpc",
  774. "ht40_intolerant", "update_identifier", "mac_addr",
  775. "erp", "bg_scan_period", "bssid_blacklist",
  776. "bssid_whitelist", "mem_only_psk", "eap_workaround" ]
  777. for field in not_quoted:
  778. if field in kwargs and kwargs[field]:
  779. self.set_network(id, field, kwargs[field])
  780. if "raw_psk" in kwargs and kwargs['raw_psk']:
  781. self.set_network(id, "psk", kwargs['raw_psk'])
  782. if "password_hex" in kwargs and kwargs['password_hex']:
  783. self.set_network(id, "password", kwargs['password_hex'])
  784. if "peerkey" in kwargs and kwargs['peerkey']:
  785. self.set_network(id, "peerkey", "1")
  786. if "okc" in kwargs and kwargs['okc']:
  787. self.set_network(id, "proactive_key_caching", "1")
  788. if "ocsp" in kwargs and kwargs['ocsp']:
  789. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  790. if "only_add_network" in kwargs and kwargs['only_add_network']:
  791. return id
  792. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  793. if "eap" in kwargs:
  794. self.connect_network(id, timeout=20)
  795. else:
  796. self.connect_network(id)
  797. else:
  798. self.dump_monitor()
  799. self.select_network(id)
  800. return id
  801. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  802. if type:
  803. cmd = "SCAN TYPE=" + type
  804. else:
  805. cmd = "SCAN"
  806. if freq:
  807. cmd = cmd + " freq=" + str(freq)
  808. if only_new:
  809. cmd += " only_new=1"
  810. if not no_wait:
  811. self.dump_monitor()
  812. if not "OK" in self.request(cmd):
  813. raise Exception("Failed to trigger scan")
  814. if no_wait:
  815. return
  816. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  817. if ev is None:
  818. raise Exception("Scan timed out")
  819. def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
  820. if not force_scan and self.get_bss(bssid) is not None:
  821. return
  822. for i in range(0, 10):
  823. self.scan(freq=freq, type="ONLY", only_new=only_new)
  824. if self.get_bss(bssid) is not None:
  825. return
  826. raise Exception("Could not find BSS " + bssid + " in scan")
  827. def flush_scan_cache(self, freq=2417):
  828. self.request("BSS_FLUSH 0")
  829. self.scan(freq=freq, only_new=True)
  830. res = self.request("SCAN_RESULTS")
  831. if len(res.splitlines()) > 1:
  832. self.request("BSS_FLUSH 0")
  833. self.scan(freq=2422, only_new=True)
  834. res = self.request("SCAN_RESULTS")
  835. if len(res.splitlines()) > 1:
  836. logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
  837. def roam(self, bssid, fail_test=False):
  838. self.dump_monitor()
  839. if "OK" not in self.request("ROAM " + bssid):
  840. raise Exception("ROAM failed")
  841. if fail_test:
  842. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  843. if ev is not None:
  844. raise Exception("Unexpected connection")
  845. self.dump_monitor()
  846. return
  847. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  848. self.dump_monitor()
  849. def roam_over_ds(self, bssid, fail_test=False):
  850. self.dump_monitor()
  851. if "OK" not in self.request("FT_DS " + bssid):
  852. raise Exception("FT_DS failed")
  853. if fail_test:
  854. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  855. if ev is not None:
  856. raise Exception("Unexpected connection")
  857. self.dump_monitor()
  858. return
  859. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  860. self.dump_monitor()
  861. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  862. new_passphrase=None, no_wait=False):
  863. self.dump_monitor()
  864. if new_ssid:
  865. self.request("WPS_REG " + bssid + " " + pin + " " +
  866. new_ssid.encode("hex") + " " + key_mgmt + " " +
  867. cipher + " " + new_passphrase.encode("hex"))
  868. if no_wait:
  869. return
  870. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  871. else:
  872. self.request("WPS_REG " + bssid + " " + pin)
  873. if no_wait:
  874. return
  875. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  876. if ev is None:
  877. raise Exception("WPS cred timed out")
  878. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  879. if ev is None:
  880. raise Exception("WPS timed out")
  881. self.wait_connected(timeout=15)
  882. def relog(self):
  883. self.global_request("RELOG")
  884. def wait_completed(self, timeout=10):
  885. for i in range(0, timeout * 2):
  886. if self.get_status_field("wpa_state") == "COMPLETED":
  887. return
  888. time.sleep(0.5)
  889. raise Exception("Timeout while waiting for COMPLETED state")
  890. def get_capability(self, field):
  891. res = self.request("GET_CAPABILITY " + field)
  892. if "FAIL" in res:
  893. return None
  894. return res.split(' ')
  895. def get_bss(self, bssid, ifname=None):
  896. if not ifname or ifname == self.ifname:
  897. res = self.request("BSS " + bssid)
  898. elif ifname == self.group_ifname:
  899. res = self.group_request("BSS " + bssid)
  900. else:
  901. return None
  902. if "FAIL" in res:
  903. return None
  904. lines = res.splitlines()
  905. vals = dict()
  906. for l in lines:
  907. [name,value] = l.split('=', 1)
  908. vals[name] = value
  909. if len(vals) == 0:
  910. return None
  911. return vals
  912. def get_pmksa(self, bssid):
  913. res = self.request("PMKSA")
  914. lines = res.splitlines()
  915. for l in lines:
  916. if bssid not in l:
  917. continue
  918. vals = dict()
  919. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  920. vals['index'] = index
  921. vals['pmkid'] = pmkid
  922. vals['expiration'] = expiration
  923. vals['opportunistic'] = opportunistic
  924. return vals
  925. return None
  926. def get_sta(self, addr, info=None, next=False):
  927. cmd = "STA-NEXT " if next else "STA "
  928. if addr is None:
  929. res = self.request("STA-FIRST")
  930. elif info:
  931. res = self.request(cmd + addr + " " + info)
  932. else:
  933. res = self.request(cmd + addr)
  934. lines = res.splitlines()
  935. vals = dict()
  936. first = True
  937. for l in lines:
  938. if first:
  939. vals['addr'] = l
  940. first = False
  941. else:
  942. [name,value] = l.split('=', 1)
  943. vals[name] = value
  944. return vals
  945. def mgmt_rx(self, timeout=5):
  946. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  947. if ev is None:
  948. return None
  949. msg = {}
  950. items = ev.split(' ')
  951. field,val = items[1].split('=')
  952. if field != "freq":
  953. raise Exception("Unexpected MGMT-RX event format: " + ev)
  954. msg['freq'] = val
  955. frame = binascii.unhexlify(items[4])
  956. msg['frame'] = frame
  957. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  958. msg['fc'] = hdr[0]
  959. msg['subtype'] = (hdr[0] >> 4) & 0xf
  960. hdr = hdr[1:]
  961. msg['duration'] = hdr[0]
  962. hdr = hdr[1:]
  963. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  964. hdr = hdr[6:]
  965. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  966. hdr = hdr[6:]
  967. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  968. hdr = hdr[6:]
  969. msg['seq_ctrl'] = hdr[0]
  970. msg['payload'] = frame[24:]
  971. return msg
  972. def wait_connected(self, timeout=10, error="Connection timed out"):
  973. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  974. if ev is None:
  975. raise Exception(error)
  976. return ev
  977. def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
  978. ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
  979. if ev is None:
  980. raise Exception(error)
  981. return ev
  982. def get_group_ifname(self):
  983. return self.group_ifname if self.group_ifname else self.ifname
  984. def get_config(self):
  985. res = self.request("DUMP")
  986. if res.startswith("FAIL"):
  987. raise Exception("DUMP failed")
  988. lines = res.splitlines()
  989. vals = dict()
  990. for l in lines:
  991. [name,value] = l.split('=', 1)
  992. vals[name] = value
  993. return vals
  994. def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
  995. method="1000", info="", status=None):
  996. if status is None:
  997. cmd = "P2P_ASP_PROVISION"
  998. params = "info='%s' method=%s" % (info, method)
  999. else:
  1000. cmd = "P2P_ASP_PROVISION_RESP"
  1001. params = "status=%d" % status
  1002. if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
  1003. (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
  1004. raise Exception("%s request failed" % cmd)