wpasupplicant.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 get_status(self, field):
  41. res = self.request("STATUS")
  42. lines = res.splitlines()
  43. for l in lines:
  44. [name,value] = l.split('=', 1)
  45. if name == field:
  46. return value
  47. return None
  48. def p2p_dev_addr(self):
  49. return self.get_status("p2p_device_address")
  50. def p2p_listen(self):
  51. return self.request("P2P_LISTEN")
  52. def p2p_find(self, social=False):
  53. if social:
  54. return self.request("P2P_FIND type=social")
  55. return self.request("P2P_FIND")
  56. def wps_read_pin(self):
  57. #TODO: make this random
  58. self.pin = "12345670"
  59. return self.pin
  60. def peer_known(self, peer, full=True):
  61. res = self.request("P2P_PEER " + peer)
  62. if peer.lower() not in res.lower():
  63. return False
  64. if not full:
  65. return True
  66. return "[PROBE_REQ_ONLY]" not in res
  67. def discover_peer(self, peer, full=True, timeout=15):
  68. logger.info(self.ifname + ": Trying to discover peer " + peer)
  69. if self.peer_known(peer, full):
  70. return True
  71. self.p2p_find()
  72. count = 0
  73. while count < timeout:
  74. time.sleep(1)
  75. count = count + 1
  76. if self.peer_known(peer, full):
  77. return True
  78. return False
  79. def group_form_result(self, ev, expect_failure=False):
  80. if expect_failure:
  81. if "P2P-GROUP-STARTED" in ev:
  82. raise Exception("Group formation succeeded when expecting failure")
  83. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  84. s = re.split(exp, ev)
  85. if len(s) < 3:
  86. return None
  87. res = {}
  88. res['result'] = 'go-neg-failed'
  89. res['status'] = int(s[2])
  90. return res
  91. if "P2P-GROUP-STARTED" not in ev:
  92. raise Exception("No P2P-GROUP-STARTED event seen")
  93. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  94. s = re.split(exp, ev)
  95. if len(s) < 8:
  96. raise Exception("Could not parse P2P-GROUP-STARTED")
  97. res = {}
  98. res['result'] = 'success'
  99. res['ifname'] = s[2]
  100. self.group_ifname = s[2]
  101. res['role'] = s[3]
  102. res['ssid'] = s[4]
  103. res['freq'] = s[5]
  104. p = re.match(r'psk=([0-9a-f]*)', s[6])
  105. if p:
  106. res['psk'] = p.group(1)
  107. p = re.match(r'passphrase="(.*)"', s[6])
  108. if p:
  109. res['passphrase'] = p.group(1)
  110. res['go_dev_addr'] = s[7]
  111. return res
  112. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  113. if not self.discover_peer(peer):
  114. raise Exception("Peer " + peer + " not found")
  115. self.dump_monitor()
  116. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  117. if go_intent:
  118. cmd = cmd + ' go_intent=' + str(go_intent)
  119. if "OK" in self.request(cmd):
  120. return None
  121. raise Exception("P2P_CONNECT (auth) failed")
  122. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  123. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  124. if ev is None:
  125. if expect_failure:
  126. return None
  127. raise Exception("Group formation timed out")
  128. self.dump_monitor()
  129. return self.group_form_result(ev, expect_failure)
  130. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  131. if not self.discover_peer(peer):
  132. raise Exception("Peer " + peer + " not found")
  133. self.dump_monitor()
  134. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  135. if go_intent:
  136. cmd = cmd + ' go_intent=' + str(go_intent)
  137. if "OK" in self.request(cmd):
  138. if timeout == 0:
  139. self.dump_monitor()
  140. return None
  141. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  142. if ev is None:
  143. if expect_failure:
  144. return None
  145. raise Exception("Group formation timed out")
  146. self.dump_monitor()
  147. return self.group_form_result(ev, expect_failure)
  148. raise Exception("P2P_CONNECT failed")
  149. def wait_event(self, events, timeout):
  150. count = 0
  151. while count < timeout * 2:
  152. count = count + 1
  153. time.sleep(0.1)
  154. while self.mon.pending():
  155. ev = self.mon.recv()
  156. logger.debug(self.ifname + ": " + ev)
  157. for event in events:
  158. if event in ev:
  159. return ev
  160. return None
  161. def dump_monitor(self):
  162. while self.mon.pending():
  163. ev = self.mon.recv()
  164. logger.debug(self.ifname + ": " + ev)
  165. def remove_group(self, ifname=None):
  166. if ifname is None:
  167. ifname = self.group_ifname if self.group_ifname else self.iname
  168. if "OK" not in self.request("P2P_GROUP_REMOVE " + ifname):
  169. raise Exception("Group could not be removed")
  170. self.group_ifname = None
  171. def p2p_start_go(self):
  172. self.dump_monitor()
  173. cmd = "P2P_GROUP_ADD"
  174. if "OK" in self.request(cmd):
  175. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout=5)
  176. if ev is None:
  177. raise Exception("GO start up timed out")
  178. self.dump_monitor()
  179. return self.group_form_result(ev)
  180. raise Exception("P2P_GROUP_ADD failed")
  181. def p2p_go_authorize_client(self, pin):
  182. cmd = "WPS_PIN any " + pin
  183. if "FAIL" in self.group_request(cmd):
  184. raise Exception("Failed to authorize client connection on GO")
  185. return None
  186. def p2p_connect_group(self, go_addr, pin, timeout=0):
  187. self.dump_monitor()
  188. if not self.discover_peer(go_addr):
  189. raise Exception("GO " + go_addr + " not found")
  190. self.dump_monitor()
  191. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  192. if "OK" in self.request(cmd):
  193. if timeout == 0:
  194. self.dump_monitor()
  195. return None
  196. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout)
  197. if ev is None:
  198. raise Exception("Joining the group timed out")
  199. self.dump_monitor()
  200. return self.group_form_result(ev)
  201. raise Exception("P2P_CONNECT(join) failed")