wpasupplicant.py 7.2 KB

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