wpasupplicant.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 wps_read_pin(self):
  87. #TODO: make this random
  88. self.pin = "12345670"
  89. return self.pin
  90. def peer_known(self, peer, full=True):
  91. res = self.request("P2P_PEER " + peer)
  92. if peer.lower() not in res.lower():
  93. return False
  94. if not full:
  95. return True
  96. return "[PROBE_REQ_ONLY]" not in res
  97. def discover_peer(self, peer, full=True, timeout=15):
  98. logger.info(self.ifname + ": Trying to discover peer " + peer)
  99. if self.peer_known(peer, full):
  100. return True
  101. self.p2p_find()
  102. count = 0
  103. while count < timeout:
  104. time.sleep(1)
  105. count = count + 1
  106. if self.peer_known(peer, full):
  107. return True
  108. return False
  109. def group_form_result(self, ev, expect_failure=False):
  110. if expect_failure:
  111. if "P2P-GROUP-STARTED" in ev:
  112. raise Exception("Group formation succeeded when expecting failure")
  113. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  114. s = re.split(exp, ev)
  115. if len(s) < 3:
  116. return None
  117. res = {}
  118. res['result'] = 'go-neg-failed'
  119. res['status'] = int(s[2])
  120. return res
  121. if "P2P-GROUP-STARTED" not in ev:
  122. raise Exception("No P2P-GROUP-STARTED event seen")
  123. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  124. s = re.split(exp, ev)
  125. if len(s) < 8:
  126. raise Exception("Could not parse P2P-GROUP-STARTED")
  127. res = {}
  128. res['result'] = 'success'
  129. res['ifname'] = s[2]
  130. self.group_ifname = s[2]
  131. res['role'] = s[3]
  132. res['ssid'] = s[4]
  133. res['freq'] = s[5]
  134. p = re.match(r'psk=([0-9a-f]*)', s[6])
  135. if p:
  136. res['psk'] = p.group(1)
  137. p = re.match(r'passphrase="(.*)"', s[6])
  138. if p:
  139. res['passphrase'] = p.group(1)
  140. res['go_dev_addr'] = s[7]
  141. return res
  142. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  143. if not self.discover_peer(peer):
  144. raise Exception("Peer " + peer + " not found")
  145. self.dump_monitor()
  146. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  147. if go_intent:
  148. cmd = cmd + ' go_intent=' + str(go_intent)
  149. if "OK" in self.request(cmd):
  150. return None
  151. raise Exception("P2P_CONNECT (auth) failed")
  152. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  153. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  154. if ev is None:
  155. if expect_failure:
  156. return None
  157. raise Exception("Group formation timed out")
  158. self.dump_monitor()
  159. return self.group_form_result(ev, expect_failure)
  160. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  161. if not self.discover_peer(peer):
  162. raise Exception("Peer " + peer + " not found")
  163. self.dump_monitor()
  164. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  165. if go_intent:
  166. cmd = cmd + ' go_intent=' + str(go_intent)
  167. if "OK" in self.request(cmd):
  168. if timeout == 0:
  169. self.dump_monitor()
  170. return None
  171. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  172. if ev is None:
  173. if expect_failure:
  174. return None
  175. raise Exception("Group formation timed out")
  176. self.dump_monitor()
  177. return self.group_form_result(ev, expect_failure)
  178. raise Exception("P2P_CONNECT failed")
  179. def wait_event(self, events, timeout):
  180. count = 0
  181. while count < timeout * 2:
  182. count = count + 1
  183. time.sleep(0.1)
  184. while self.mon.pending():
  185. ev = self.mon.recv()
  186. logger.debug(self.ifname + ": " + ev)
  187. for event in events:
  188. if event in ev:
  189. return ev
  190. return None
  191. def dump_monitor(self):
  192. while self.mon.pending():
  193. ev = self.mon.recv()
  194. logger.debug(self.ifname + ": " + ev)
  195. def remove_group(self, ifname=None):
  196. if ifname is None:
  197. ifname = self.group_ifname if self.group_ifname else self.iname
  198. if "OK" not in self.request("P2P_GROUP_REMOVE " + ifname):
  199. raise Exception("Group could not be removed")
  200. self.group_ifname = None
  201. def p2p_start_go(self, persistent=None):
  202. self.dump_monitor()
  203. cmd = "P2P_GROUP_ADD"
  204. if persistent is None:
  205. pass
  206. elif persistent is True:
  207. cmd = cmd + " persistent"
  208. else:
  209. cmd = cmd + " persistent=" + str(persistent)
  210. if "OK" in self.request(cmd):
  211. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout=5)
  212. if ev is None:
  213. raise Exception("GO start up timed out")
  214. self.dump_monitor()
  215. return self.group_form_result(ev)
  216. raise Exception("P2P_GROUP_ADD failed")
  217. def p2p_go_authorize_client(self, pin):
  218. cmd = "WPS_PIN any " + pin
  219. if "FAIL" in self.group_request(cmd):
  220. raise Exception("Failed to authorize client connection on GO")
  221. return None
  222. def p2p_connect_group(self, go_addr, pin, timeout=0):
  223. self.dump_monitor()
  224. if not self.discover_peer(go_addr):
  225. raise Exception("GO " + go_addr + " not found")
  226. self.dump_monitor()
  227. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  228. if "OK" in self.request(cmd):
  229. if timeout == 0:
  230. self.dump_monitor()
  231. return None
  232. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout)
  233. if ev is None:
  234. raise Exception("Joining the group timed out")
  235. self.dump_monitor()
  236. return self.group_form_result(ev)
  237. raise Exception("P2P_CONNECT(join) failed")
  238. def tdls_setup(self, peer):
  239. cmd = "TDLS_SETUP " + peer
  240. if "FAIL" in self.group_request(cmd):
  241. raise Exception("Failed to request TDLS setup")
  242. return None
  243. def tdls_teardown(self, peer):
  244. cmd = "TDLS_TEARDOWN " + peer
  245. if "FAIL" in self.group_request(cmd):
  246. raise Exception("Failed to request TDLS teardown")
  247. return None