wpasupplicant.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/python
  2. #
  3. # Python class for controlling wpa_supplicant
  4. # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import os
  9. import time
  10. import logging
  11. import re
  12. import wpaspy
  13. logger = logging.getLogger(__name__)
  14. wpas_ctrl = '/var/run/wpa_supplicant'
  15. class WpaSupplicant:
  16. def __init__(self, ifname):
  17. self.ifname = ifname
  18. self.group_ifname = None
  19. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  20. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  21. self.mon.attach()
  22. def request(self, cmd):
  23. logger.debug(self.ifname + ": CTRL: " + cmd)
  24. return self.ctrl.request(cmd)
  25. def group_request(self, cmd):
  26. if self.group_ifname and self.group_ifname != self.ifname:
  27. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  28. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  29. return gctrl.request(cmd)
  30. return self.request(cmd)
  31. def ping(self):
  32. return "PONG" in self.request("PING")
  33. def reset(self):
  34. self.request("P2P_STOP_FIND")
  35. self.request("P2P_FLUSH")
  36. self.request("P2P_GROUP_REMOVE *")
  37. self.request("REMOVE_NETWORK *")
  38. self.request("REMOVE_CRED *")
  39. self.group_ifname = None
  40. def add_network(self):
  41. id = self.request("ADD_NETWORK")
  42. if "FAIL" in id:
  43. raise Exception("ADD_NETWORK failed")
  44. return int(id)
  45. def remove_network(self, id):
  46. id = self.request("REMOVE_NETWORK " + str(id))
  47. if "FAIL" in id:
  48. raise Exception("REMOVE_NETWORK failed")
  49. return None
  50. def set_network(self, id, field, value):
  51. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  52. if "FAIL" in res:
  53. raise Exception("SET_NETWORK failed")
  54. return None
  55. def set_network_quoted(self, id, field, value):
  56. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  57. if "FAIL" in res:
  58. raise Exception("SET_NETWORK failed")
  59. return None
  60. def get_status(self, field):
  61. res = self.request("STATUS")
  62. lines = res.splitlines()
  63. for l in lines:
  64. [name,value] = l.split('=', 1)
  65. if name == field:
  66. return value
  67. return None
  68. def get_group_status(self, field):
  69. res = self.group_request("STATUS")
  70. lines = res.splitlines()
  71. for l in lines:
  72. [name,value] = l.split('=', 1)
  73. if name == field:
  74. return value
  75. return None
  76. def p2p_dev_addr(self):
  77. return self.get_status("p2p_device_address")
  78. def p2p_interface_addr(self):
  79. return self.get_group_status("address")
  80. def p2p_listen(self):
  81. return self.request("P2P_LISTEN")
  82. def p2p_find(self, social=False):
  83. if social:
  84. return self.request("P2P_FIND type=social")
  85. return self.request("P2P_FIND")
  86. def p2p_stop_find(self):
  87. return self.request("P2P_STOP_FIND")
  88. def wps_read_pin(self):
  89. #TODO: make this random
  90. self.pin = "12345670"
  91. return self.pin
  92. def peer_known(self, peer, full=True):
  93. res = self.request("P2P_PEER " + peer)
  94. if peer.lower() not in res.lower():
  95. return False
  96. if not full:
  97. return True
  98. return "[PROBE_REQ_ONLY]" not in res
  99. def discover_peer(self, peer, full=True, timeout=15, social=True):
  100. logger.info(self.ifname + ": Trying to discover peer " + peer)
  101. if self.peer_known(peer, full):
  102. return True
  103. self.p2p_find(social)
  104. count = 0
  105. while count < timeout:
  106. time.sleep(1)
  107. count = count + 1
  108. if self.peer_known(peer, full):
  109. return True
  110. return False
  111. def group_form_result(self, ev, expect_failure=False):
  112. if expect_failure:
  113. if "P2P-GROUP-STARTED" in ev:
  114. raise Exception("Group formation succeeded when expecting failure")
  115. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  116. s = re.split(exp, ev)
  117. if len(s) < 3:
  118. return None
  119. res = {}
  120. res['result'] = 'go-neg-failed'
  121. res['status'] = int(s[2])
  122. return res
  123. if "P2P-GROUP-STARTED" not in ev:
  124. raise Exception("No P2P-GROUP-STARTED event seen")
  125. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  126. s = re.split(exp, ev)
  127. if len(s) < 8:
  128. raise Exception("Could not parse P2P-GROUP-STARTED")
  129. res = {}
  130. res['result'] = 'success'
  131. res['ifname'] = s[2]
  132. self.group_ifname = s[2]
  133. res['role'] = s[3]
  134. res['ssid'] = s[4]
  135. res['freq'] = s[5]
  136. p = re.match(r'psk=([0-9a-f]*)', s[6])
  137. if p:
  138. res['psk'] = p.group(1)
  139. p = re.match(r'passphrase="(.*)"', s[6])
  140. if p:
  141. res['passphrase'] = p.group(1)
  142. res['go_dev_addr'] = s[7]
  143. return res
  144. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  145. if not self.discover_peer(peer):
  146. raise Exception("Peer " + peer + " not found")
  147. self.dump_monitor()
  148. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  149. if go_intent:
  150. cmd = cmd + ' go_intent=' + str(go_intent)
  151. if "OK" in self.request(cmd):
  152. return None
  153. raise Exception("P2P_CONNECT (auth) failed")
  154. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  155. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  156. if ev is None:
  157. if expect_failure:
  158. return None
  159. raise Exception("Group formation timed out")
  160. self.dump_monitor()
  161. return self.group_form_result(ev, expect_failure)
  162. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  163. if not self.discover_peer(peer):
  164. raise Exception("Peer " + peer + " not found")
  165. self.dump_monitor()
  166. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  167. if go_intent:
  168. cmd = cmd + ' go_intent=' + str(go_intent)
  169. if "OK" in self.request(cmd):
  170. if timeout == 0:
  171. self.dump_monitor()
  172. return None
  173. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  174. if ev is None:
  175. if expect_failure:
  176. return None
  177. raise Exception("Group formation timed out")
  178. self.dump_monitor()
  179. return self.group_form_result(ev, expect_failure)
  180. raise Exception("P2P_CONNECT failed")
  181. def wait_event(self, events, timeout):
  182. count = 0
  183. while count < timeout * 10:
  184. count = count + 1
  185. time.sleep(0.1)
  186. while self.mon.pending():
  187. ev = self.mon.recv()
  188. logger.debug(self.ifname + ": " + ev)
  189. for event in events:
  190. if event in ev:
  191. return ev
  192. return None
  193. def dump_monitor(self):
  194. while self.mon.pending():
  195. ev = self.mon.recv()
  196. logger.debug(self.ifname + ": " + ev)
  197. def remove_group(self, ifname=None):
  198. if ifname is None:
  199. ifname = self.group_ifname if self.group_ifname else self.iname
  200. if "OK" not in self.request("P2P_GROUP_REMOVE " + ifname):
  201. raise Exception("Group could not be removed")
  202. self.group_ifname = None
  203. def p2p_start_go(self, persistent=None):
  204. self.dump_monitor()
  205. cmd = "P2P_GROUP_ADD"
  206. if persistent is None:
  207. pass
  208. elif persistent is True:
  209. cmd = cmd + " persistent"
  210. else:
  211. cmd = cmd + " persistent=" + str(persistent)
  212. if "OK" in self.request(cmd):
  213. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout=5)
  214. if ev is None:
  215. raise Exception("GO start up timed out")
  216. self.dump_monitor()
  217. return self.group_form_result(ev)
  218. raise Exception("P2P_GROUP_ADD failed")
  219. def p2p_go_authorize_client(self, pin):
  220. cmd = "WPS_PIN any " + pin
  221. if "FAIL" in self.group_request(cmd):
  222. raise Exception("Failed to authorize client connection on GO")
  223. return None
  224. def p2p_connect_group(self, go_addr, pin, timeout=0):
  225. self.dump_monitor()
  226. if not self.discover_peer(go_addr, social=False):
  227. raise Exception("GO " + go_addr + " not found")
  228. self.dump_monitor()
  229. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  230. if "OK" in self.request(cmd):
  231. if timeout == 0:
  232. self.dump_monitor()
  233. return None
  234. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout)
  235. if ev is None:
  236. raise Exception("Joining the group timed out")
  237. self.dump_monitor()
  238. return self.group_form_result(ev)
  239. raise Exception("P2P_CONNECT(join) failed")
  240. def tdls_setup(self, peer):
  241. cmd = "TDLS_SETUP " + peer
  242. if "FAIL" in self.group_request(cmd):
  243. raise Exception("Failed to request TDLS setup")
  244. return None
  245. def tdls_teardown(self, peer):
  246. cmd = "TDLS_TEARDOWN " + peer
  247. if "FAIL" in self.group_request(cmd):
  248. raise Exception("Failed to request TDLS teardown")
  249. return None