fst_module_aux.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. # FST tests related classes
  2. # Copyright (c) 2015, Qualcomm Atheros, Inc.
  3. #
  4. # This software may be distributed under the terms of the BSD license.
  5. # See README for more details.
  6. import logging
  7. import subprocess
  8. import os
  9. import signal
  10. import time
  11. import re
  12. import hostapd
  13. import wpaspy
  14. import utils
  15. from wpasupplicant import WpaSupplicant
  16. import fst_test_common
  17. logger = logging.getLogger()
  18. def parse_fst_iface_event(ev):
  19. """Parses FST iface event that comes as a string, e.g.
  20. "<3>FST-EVENT-IFACE attached ifname=wlan9 group=fstg0"
  21. Returns a dictionary with parsed "event_type", "ifname", and "group"; or
  22. None if not an FST event or can't be parsed."""
  23. event = {}
  24. if ev.find("FST-EVENT-IFACE") == -1:
  25. return None
  26. if ev.find("attached") != -1:
  27. event['event_type'] = 'attached'
  28. elif ev.find("detached") != -1:
  29. event['event_type'] = 'detached'
  30. else:
  31. return None
  32. f = re.search("ifname=(\S+)", ev)
  33. if f is not None:
  34. event['ifname'] = f.group(1)
  35. f = re.search("group=(\S+)", ev)
  36. if f is not None:
  37. event['group'] = f.group(1)
  38. return event
  39. def parse_fst_session_event(ev):
  40. """Parses FST session event that comes as a string, e.g.
  41. "<3>FST-EVENT-SESSION event_type=EVENT_FST_SESSION_STATE session_id=0 reason=REASON_STT"
  42. Returns a dictionary with parsed "type", "id", and "reason"; or None if not
  43. a FST event or can't be parsed"""
  44. event = {}
  45. if ev.find("FST-EVENT-SESSION") == -1:
  46. return None
  47. event['new_state'] = '' # The field always exists in the dictionary
  48. f = re.search("event_type=(\S+)", ev)
  49. if f is None:
  50. return None
  51. event['type'] = f.group(1)
  52. f = re.search("session_id=(\d+)", ev)
  53. if f is not None:
  54. event['id'] = f.group(1)
  55. f = re.search("old_state=(\S+)", ev)
  56. if f is not None:
  57. event['old_state'] = f.group(1)
  58. f = re.search("new_state=(\S+)", ev)
  59. if f is not None:
  60. event['new_state'] = f.group(1)
  61. f = re.search("reason=(\S+)", ev)
  62. if f is not None:
  63. event['reason'] = f.group(1)
  64. return event
  65. def start_two_ap_sta_pairs(apdev, rsn=False):
  66. """auxiliary function that creates two pairs of APs and STAs"""
  67. ap1 = FstAP(apdev[0]['ifname'], 'fst_11a', 'a',
  68. fst_test_common.fst_test_def_chan_a,
  69. fst_test_common.fst_test_def_group,
  70. fst_test_common.fst_test_def_prio_low,
  71. fst_test_common.fst_test_def_llt, rsn=rsn)
  72. ap1.start()
  73. ap2 = FstAP(apdev[1]['ifname'], 'fst_11g', 'g',
  74. fst_test_common.fst_test_def_chan_g,
  75. fst_test_common.fst_test_def_group,
  76. fst_test_common.fst_test_def_prio_high,
  77. fst_test_common.fst_test_def_llt, rsn=rsn)
  78. ap2.start()
  79. sta1 = FstSTA('wlan5',
  80. fst_test_common.fst_test_def_group,
  81. fst_test_common.fst_test_def_prio_low,
  82. fst_test_common.fst_test_def_llt, rsn=rsn)
  83. sta1.start()
  84. sta2 = FstSTA('wlan6',
  85. fst_test_common.fst_test_def_group,
  86. fst_test_common.fst_test_def_prio_high,
  87. fst_test_common.fst_test_def_llt, rsn=rsn)
  88. sta2.start()
  89. return ap1, ap2, sta1, sta2
  90. def stop_two_ap_sta_pairs(ap1, ap2, sta1, sta2):
  91. sta1.stop()
  92. sta2.stop()
  93. ap1.stop()
  94. ap2.stop()
  95. def connect_two_ap_sta_pairs(ap1, ap2, dev1, dev2, rsn=False):
  96. """Connects a pair of stations, each one to a separate AP"""
  97. dev1.scan(freq=fst_test_common.fst_test_def_freq_a)
  98. dev2.scan(freq=fst_test_common.fst_test_def_freq_g)
  99. if rsn:
  100. dev1.connect(ap1, psk="12345678",
  101. scan_freq=fst_test_common.fst_test_def_freq_a)
  102. dev2.connect(ap2, psk="12345678",
  103. scan_freq=fst_test_common.fst_test_def_freq_g)
  104. else:
  105. dev1.connect(ap1, key_mgmt="NONE",
  106. scan_freq=fst_test_common.fst_test_def_freq_a)
  107. dev2.connect(ap2, key_mgmt="NONE",
  108. scan_freq=fst_test_common.fst_test_def_freq_g)
  109. def disconnect_two_ap_sta_pairs(ap1, ap2, dev1, dev2):
  110. dev1.disconnect()
  111. dev2.disconnect()
  112. def external_sta_connect(sta, ap, **kwargs):
  113. """Connects the external station to the given AP"""
  114. if not isinstance(sta, WpaSupplicant):
  115. raise Exception("Bad STA object")
  116. if not isinstance(ap, FstAP):
  117. raise Exception("Bad AP object to connect to")
  118. hap = ap.get_instance()
  119. sta.connect(ap.get_ssid(), **kwargs)
  120. def disconnect_external_sta(sta, ap, check_disconnect=True):
  121. """Disconnects the external station from the AP"""
  122. if not isinstance(sta, WpaSupplicant):
  123. raise Exception("Bad STA object")
  124. if not isinstance(ap, FstAP):
  125. raise Exception("Bad AP object to connect to")
  126. sta.request("DISCONNECT")
  127. if check_disconnect:
  128. hap = ap.get_instance()
  129. ev = hap.wait_event([ "AP-STA-DISCONNECTED" ], timeout=10)
  130. if ev is None:
  131. raise Exception("No disconnection event received from %s" % ap.get_ssid())
  132. #
  133. # FstDevice class
  134. # This is the parent class for the AP (FstAP) and STA (FstSTA) that implements
  135. # FST functionality.
  136. #
  137. class FstDevice:
  138. def __init__(self, iface, fst_group, fst_pri, fst_llt=None, rsn=False):
  139. self.iface = iface
  140. self.fst_group = fst_group
  141. self.fst_pri = fst_pri
  142. self.fst_llt = fst_llt # None llt means no llt parameter will be set
  143. self.instance = None # Hostapd/WpaSupplicant instance
  144. self.peer_obj = None # Peer object, must be a FstDevice child object
  145. self.new_peer_addr = None # Peer MAC address for new session iface
  146. self.old_peer_addr = None # Peer MAC address for old session iface
  147. self.role = 'initiator' # Role: initiator/responder
  148. s = self.grequest("FST-MANAGER TEST_REQUEST IS_SUPPORTED")
  149. if not s.startswith('OK'):
  150. raise utils.HwsimSkip("FST not supported")
  151. self.rsn = rsn
  152. def ifname(self):
  153. return self.iface
  154. def get_instance(self):
  155. """Gets the Hostapd/WpaSupplicant instance"""
  156. raise Exception("Virtual get_instance() called!")
  157. def get_own_mac_address(self):
  158. """Gets the device's own MAC address"""
  159. raise Exception("Virtual get_own_mac_address() called!")
  160. def get_new_peer_addr(self):
  161. return self.new_peer_addr
  162. def get_old_peer_addr(self):
  163. return self.old_peer_addr
  164. def get_actual_peer_addr(self):
  165. """Gets the peer address. A connected AP/station address is returned."""
  166. raise Exception("Virtual get_actual_peer_addr() called!")
  167. def grequest(self, req):
  168. """Send request on the global control interface"""
  169. raise Exception, "Virtual grequest() called!"
  170. def wait_gevent(self, events, timeout=None):
  171. """Wait for a list of events on the global interface"""
  172. raise Exception("Virtual wait_gevent() called!")
  173. def request(self, req):
  174. """Issue a request to the control interface"""
  175. h = self.get_instance()
  176. return h.request(req)
  177. def wait_event(self, events, timeout=None):
  178. """Wait for an event from the control interface"""
  179. h = self.get_instance()
  180. if timeout is not None:
  181. return h.wait_event(events, timeout=timeout)
  182. else:
  183. return h.wait_event(events)
  184. def set_old_peer_addr(self, peer_addr=None):
  185. """Sets the peer address"""
  186. if peer_addr is not None:
  187. self.old_peer_addr = peer_addr
  188. else:
  189. self.old_peer_addr = self.get_actual_peer_addr()
  190. def set_new_peer_addr(self, peer_addr=None):
  191. """Sets the peer address"""
  192. if peer_addr is not None:
  193. self.new_peer_addr = peer_addr
  194. else:
  195. self.new_peer_addr = self.get_actual_peer_addr()
  196. def add_peer(self, obj, old_peer_addr=None, new_peer_addr=None):
  197. """Add peer for FST session(s). 'obj' is a FstDevice subclass object.
  198. The method must be called before add_session().
  199. If peer_addr is not specified, the address of the currently connected
  200. station is used."""
  201. if not isinstance(obj, FstDevice):
  202. raise Exception("Peer must be a FstDevice object")
  203. self.peer_obj = obj
  204. self.set_old_peer_addr(old_peer_addr)
  205. self.set_new_peer_addr(new_peer_addr)
  206. def get_peer(self):
  207. """Returns peer object"""
  208. return self.peer_obj
  209. def set_fst_parameters(self, group_id=None, pri=None, llt=None):
  210. """Change/set new FST parameters. Can be used to start FST sessions with
  211. different FST parameters than defined in the configuration file."""
  212. if group_id is not None:
  213. self.fst_group = group_id
  214. if pri is not None:
  215. self.fst_pri = pri
  216. if llt is not None:
  217. self.fst_llt = llt
  218. def get_local_mbies(self, ifname=None):
  219. if_name = ifname if ifname is not None else self.iface
  220. return self.grequest("FST-MANAGER TEST_REQUEST GET_LOCAL_MBIES " + if_name)
  221. def add_session(self):
  222. """Adds an FST session. add_peer() must be called calling this
  223. function"""
  224. if self.peer_obj is None:
  225. raise Exception("Peer wasn't added before starting session")
  226. self.dump_monitor()
  227. grp = ' ' + self.fst_group if self.fst_group != '' else ''
  228. sid = self.grequest("FST-MANAGER SESSION_ADD" + grp)
  229. sid = sid.strip()
  230. if sid.startswith("FAIL"):
  231. raise Exception("Cannot add FST session with groupid ==" + grp)
  232. self.dump_monitor()
  233. return sid
  234. def set_session_param(self, params):
  235. request = "FST-MANAGER SESSION_SET"
  236. if params is not None and params != '':
  237. request = request + ' ' + params
  238. return self.grequest(request)
  239. def get_session_params(self, sid):
  240. request = "FST-MANAGER SESSION_GET " + sid
  241. res = self.grequest(request)
  242. if res.startswith("FAIL"):
  243. return None
  244. params = {}
  245. for i in res.splitlines():
  246. p = i.split('=')
  247. params[p[0]] = p[1]
  248. return params
  249. def iface_peers(self, ifname):
  250. grp = self.fst_group if self.fst_group != '' else ''
  251. res = self.grequest("FST-MANAGER IFACE_PEERS " + grp + ' ' + ifname)
  252. if res.startswith("FAIL"):
  253. return None
  254. return res.splitlines()
  255. def get_peer_mbies(self, ifname, peer_addr):
  256. return self.grequest("FST-MANAGER GET_PEER_MBIES %s %s" % (ifname, peer_addr))
  257. def list_ifaces(self):
  258. grp = self.fst_group if self.fst_group != '' else ''
  259. res = self.grequest("FST-MANAGER LIST_IFACES " + grp)
  260. if res.startswith("FAIL"):
  261. return None
  262. ifaces = []
  263. for i in res.splitlines():
  264. p = i.split(':')
  265. iface = {}
  266. iface['name'] = p[0]
  267. iface['priority'] = p[1]
  268. iface['llt'] = p[2]
  269. ifaces.append(iface)
  270. return ifaces
  271. def list_groups(self):
  272. res = self.grequest("FST-MANAGER LIST_GROUPS")
  273. if res.startswith("FAIL"):
  274. return None
  275. return res.splitlines()
  276. def configure_session(self, sid, new_iface, old_iface = None):
  277. """Calls session_set for a number of parameters some of which are stored
  278. in "self" while others are passed to this function explicitly. If
  279. old_iface is None, current iface is used; if old_iface is an empty
  280. string."""
  281. self.dump_monitor()
  282. oldiface = old_iface if old_iface is not None else self.iface
  283. s = self.set_session_param(sid + ' old_ifname=' + oldiface)
  284. if not s.startswith("OK"):
  285. raise Exception("Cannot set FST session old_ifname: " + s)
  286. if new_iface is not None:
  287. s = self.set_session_param(sid + " new_ifname=" + new_iface)
  288. if not s.startswith("OK"):
  289. raise Exception("Cannot set FST session new_ifname:" + s)
  290. if self.new_peer_addr is not None and self.new_peer_addr != '':
  291. s = self.set_session_param(sid + " new_peer_addr=" + self.new_peer_addr)
  292. if not s.startswith("OK"):
  293. raise Exception("Cannot set FST session peer address:" + s + " (new)")
  294. if self.old_peer_addr is not None and self.old_peer_addr != '':
  295. s = self.set_session_param(sid + " old_peer_addr=" + self.old_peer_addr)
  296. if not s.startswith("OK"):
  297. raise Exception("Cannot set FST session peer address:" + s + " (old)")
  298. if self.fst_llt is not None and self.fst_llt != '':
  299. s = self.set_session_param(sid + " llt=" + self.fst_llt)
  300. if not s.startswith("OK"):
  301. raise Exception("Cannot set FST session llt:" + s)
  302. self.dump_monitor()
  303. def send_iface_attach_request(self, ifname, group, llt, priority):
  304. request = "FST-ATTACH " + ifname + ' ' + group
  305. if llt is not None:
  306. request += " llt=" + llt
  307. if priority is not None:
  308. request += " priority=" + priority
  309. res = self.grequest(request)
  310. if not res.startswith("OK"):
  311. raise Exception("Cannot attach FST iface: " + res)
  312. def send_iface_detach_request(self, ifname):
  313. res = self.grequest("FST-DETACH " + ifname)
  314. if not res.startswith("OK"):
  315. raise Exception("Cannot detach FST iface: " + res)
  316. def send_session_setup_request(self, sid):
  317. s = self.grequest("FST-MANAGER SESSION_INITIATE " + sid)
  318. if not s.startswith('OK'):
  319. raise Exception("Cannot send setup request: %s" % s)
  320. return s
  321. def send_session_setup_response(self, sid, response):
  322. request = "FST-MANAGER SESSION_RESPOND " + sid + " " + response
  323. s = self.grequest(request)
  324. if not s.startswith('OK'):
  325. raise Exception("Cannot send setup response: %s" % s)
  326. return s
  327. def send_test_session_setup_request(self, fsts_id,
  328. additional_parameter = None):
  329. request = "FST-MANAGER TEST_REQUEST SEND_SETUP_REQUEST " + fsts_id
  330. if additional_parameter is not None:
  331. request += " " + additional_parameter
  332. s = self.grequest(request)
  333. if not s.startswith('OK'):
  334. raise Exception("Cannot send FST setup request: %s" % s)
  335. return s
  336. def send_test_session_setup_response(self, fsts_id,
  337. response, additional_parameter = None):
  338. request = "FST-MANAGER TEST_REQUEST SEND_SETUP_RESPONSE " + fsts_id + " " + response
  339. if additional_parameter is not None:
  340. request += " " + additional_parameter
  341. s = self.grequest(request)
  342. if not s.startswith('OK'):
  343. raise Exception("Cannot send FST setup response: %s" % s)
  344. return s
  345. def send_test_ack_request(self, fsts_id):
  346. s = self.grequest("FST-MANAGER TEST_REQUEST SEND_ACK_REQUEST " + fsts_id)
  347. if not s.startswith('OK'):
  348. raise Exception("Cannot send FST ack request: %s" % s)
  349. return s
  350. def send_test_ack_response(self, fsts_id):
  351. s = self.grequest("FST-MANAGER TEST_REQUEST SEND_ACK_RESPONSE " + fsts_id)
  352. if not s.startswith('OK'):
  353. raise Exception("Cannot send FST ack response: %s" % s)
  354. return s
  355. def send_test_tear_down(self, fsts_id):
  356. s = self.grequest("FST-MANAGER TEST_REQUEST SEND_TEAR_DOWN " + fsts_id)
  357. if not s.startswith('OK'):
  358. raise Exception("Cannot send FST tear down: %s" % s)
  359. return s
  360. def get_fsts_id_by_sid(self, sid):
  361. s = self.grequest("FST-MANAGER TEST_REQUEST GET_FSTS_ID " + sid)
  362. if s == ' ' or s.startswith('FAIL'):
  363. raise Exception("Cannot get fsts_id for sid == %s" % sid)
  364. return int(s)
  365. def wait_for_iface_event(self, timeout):
  366. while True:
  367. ev = self.wait_gevent(["FST-EVENT-IFACE"], timeout)
  368. if ev is None:
  369. raise Exception("No FST-EVENT-IFACE received")
  370. event = parse_fst_iface_event(ev)
  371. if event is None:
  372. # We can't parse so it's not our event, wait for next one
  373. continue
  374. return event
  375. def wait_for_session_event(self, timeout, events_to_ignore=[],
  376. events_to_count=[]):
  377. while True:
  378. ev = self.wait_gevent(["FST-EVENT-SESSION"], timeout)
  379. if ev is None:
  380. raise Exception("No FST-EVENT-SESSION received")
  381. event = parse_fst_session_event(ev)
  382. if event is None:
  383. # We can't parse so it's not our event, wait for next one
  384. continue
  385. if len(events_to_ignore) > 0:
  386. if event['type'] in events_to_ignore:
  387. continue
  388. elif len(events_to_count) > 0:
  389. if not event['type'] in events_to_count:
  390. continue
  391. return event
  392. def initiate_session(self, sid, response="accept"):
  393. """Initiates FST session with given session id 'sid'.
  394. 'response' is the session respond answer: "accept", "reject", or a
  395. special "timeout" value to skip the response in order to test session
  396. timeouts.
  397. Returns: "OK" - session has been initiated, otherwise the reason for the
  398. reset: REASON_REJECT, REASON_STT."""
  399. strsid = ' ' + sid if sid != '' else ''
  400. s = self.grequest("FST-MANAGER SESSION_INITIATE"+ strsid)
  401. if not s.startswith('OK'):
  402. raise Exception("Cannot initiate fst session: %s" % s)
  403. ev = self.peer_obj.wait_gevent([ "FST-EVENT-SESSION" ], timeout=5)
  404. if ev is None:
  405. raise Exception("No FST-EVENT-SESSION received")
  406. # We got FST event
  407. event = parse_fst_session_event(ev)
  408. if event == None:
  409. raise Exception("Unrecognized FST event: " % ev)
  410. if event['type'] != 'EVENT_FST_SETUP':
  411. raise Exception("Expected FST_SETUP event, got: " + event['type'])
  412. ev = self.peer_obj.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
  413. if ev is None:
  414. raise Exception("No FST-EVENT-SESSION received")
  415. event = parse_fst_session_event(ev)
  416. if event == None:
  417. raise Exception("Unrecognized FST event: " % ev)
  418. if event['type'] != 'EVENT_FST_SESSION_STATE':
  419. raise Exception("Expected EVENT_FST_SESSION_STATE event, got: " + event['type'])
  420. if event['new_state'] != "SETUP_COMPLETION":
  421. raise Exception("Expected new state SETUP_COMPLETION, got: " + event['new_state'])
  422. if response == '':
  423. return 'OK'
  424. if response != "timeout":
  425. s = self.peer_obj.grequest("FST-MANAGER SESSION_RESPOND "+ event['id'] + " " + response) # Or reject
  426. if not s.startswith('OK'):
  427. raise Exception("Error session_respond: %s" % s)
  428. # Wait for EVENT_FST_SESSION_STATE events. We should get at least 2
  429. # events. The 1st event will be EVENT_FST_SESSION_STATE
  430. # old_state=INITIAL new_state=SETUP_COMPLETED. The 2nd event will be
  431. # either EVENT_FST_ESTABLISHED with the session id or
  432. # EVENT_FST_SESSION_STATE with new_state=INITIAL if the session was
  433. # reset, the reason field will tell why.
  434. result = ''
  435. while result == '':
  436. ev = self.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
  437. if ev is None:
  438. break # No session event received
  439. event = parse_fst_session_event(ev)
  440. if event == None:
  441. # We can't parse so it's not our event, wait for next one
  442. continue
  443. if event['type'] == 'EVENT_FST_ESTABLISHED':
  444. result = "OK"
  445. break
  446. elif event['type'] == "EVENT_FST_SESSION_STATE":
  447. if event['new_state'] == "INITIAL":
  448. # Session was reset, the only reason to get back to initial
  449. # state.
  450. result = event['reason']
  451. break
  452. if result == '':
  453. raise Exception("No event for session respond")
  454. return result
  455. def transfer_session(self, sid):
  456. """Transfers the session. 'sid' is the session id. 'hsta' is the
  457. station-responder object.
  458. Returns: REASON_SWITCH - the session has been transferred successfully
  459. or a REASON_... reported by the reset event."""
  460. request = "FST-MANAGER SESSION_TRANSFER"
  461. self.dump_monitor()
  462. if sid != '':
  463. request += ' ' + sid
  464. s = self.grequest(request)
  465. if not s.startswith('OK'):
  466. raise Exception("Cannot transfer fst session: %s" % s)
  467. result = ''
  468. while result == '':
  469. ev = self.peer_obj.wait_gevent([ "FST-EVENT-SESSION" ], timeout=5)
  470. if ev is None:
  471. raise Exception("Missing session transfer event")
  472. # We got FST event. We expect TRANSITION_CONFIRMED state and then
  473. # INITIAL (reset) with the reason (e.g. "REASON_SWITCH").
  474. # Right now we'll be waiting for the reset event and record the
  475. # reason.
  476. event = parse_fst_session_event(ev)
  477. if event == None:
  478. raise Exception("Unrecognized FST event: " % ev)
  479. if event['new_state'] == 'INITIAL':
  480. result = event['reason']
  481. self.dump_monitor()
  482. return result
  483. def wait_for_tear_down(self):
  484. ev = self.wait_gevent([ "FST-EVENT-SESSION" ], timeout=5)
  485. if ev is None:
  486. raise Exception("No FST-EVENT-SESSION received")
  487. # We got FST event
  488. event = parse_fst_session_event(ev)
  489. if event == None:
  490. raise Exception("Unrecognized FST event: " % ev)
  491. if event['type'] != 'EVENT_FST_SESSION_STATE':
  492. raise Exception("Expected EVENT_FST_SESSION_STATE event, got: " + event['type'])
  493. if event['new_state'] != "INITIAL":
  494. raise Exception("Expected new state INITIAL, got: " + event['new_state'])
  495. if event['reason'] != 'REASON_TEARDOWN':
  496. raise Exception("Expected reason REASON_TEARDOWN, got: " + event['reason'])
  497. def teardown_session(self, sid):
  498. """Tears down FST session with a given session id ('sid')"""
  499. strsid = ' ' + sid if sid != '' else ''
  500. s = self.grequest("FST-MANAGER SESSION_TEARDOWN" + strsid)
  501. if not s.startswith('OK'):
  502. raise Exception("Cannot tear down fst session: %s" % s)
  503. self.peer_obj.wait_for_tear_down()
  504. def remove_session(self, sid, wait_for_tear_down=True):
  505. """Removes FST session with a given session id ('sid')"""
  506. strsid = ' ' + sid if sid != '' else ''
  507. s = self.grequest("FST-MANAGER SESSION_REMOVE" + strsid)
  508. if not s.startswith('OK'):
  509. raise Exception("Cannot remove fst session: %s" % s)
  510. if wait_for_tear_down == True:
  511. self.peer_obj.wait_for_tear_down()
  512. def remove_all_sessions(self):
  513. """Removes FST session with a given session id ('sid')"""
  514. grp = ' ' + self.fst_group if self.fst_group != '' else ''
  515. s = self.grequest("FST-MANAGER LIST_SESSIONS" + grp)
  516. if not s.startswith('FAIL'):
  517. for sid in s.splitlines():
  518. sid = sid.strip()
  519. if len(sid) != 0:
  520. self.remove_session(sid, wait_for_tear_down=False)
  521. #
  522. # FstAP class
  523. #
  524. class FstAP (FstDevice):
  525. def __init__(self, iface, ssid, mode, chan, fst_group, fst_pri,
  526. fst_llt=None, rsn=False):
  527. """If fst_group is empty, then FST parameters will not be set
  528. If fst_llt is empty, the parameter will not be set and the default value
  529. is expected to be configured."""
  530. self.ssid = ssid
  531. self.mode = mode
  532. self.chan = chan
  533. self.reg_ctrl = fst_test_common.HapdRegCtrl()
  534. self.reg_ctrl.add_ap(iface, self.chan)
  535. self.global_instance = hostapd.HostapdGlobal()
  536. FstDevice.__init__(self, iface, fst_group, fst_pri, fst_llt, rsn)
  537. def start(self, return_early=False):
  538. """Starts AP the "standard" way as it was intended by hostapd tests.
  539. This will work only when FST supports fully dynamically loading
  540. parameters in hostapd."""
  541. params = {}
  542. params['ssid'] = self.ssid
  543. params['hw_mode'] = self.mode
  544. params['channel'] = self.chan
  545. params['country_code'] = 'US'
  546. if self.rsn:
  547. params['wpa'] = '2'
  548. params['wpa_key_mgmt'] = 'WPA-PSK'
  549. params['rsn_pairwise'] = 'CCMP'
  550. params['wpa_passphrase'] = '12345678'
  551. self.hapd=hostapd.add_ap(self.iface, params)
  552. if not self.hapd.ping():
  553. raise Exception("Could not ping FST hostapd")
  554. self.reg_ctrl.start()
  555. self.get_global_instance()
  556. if return_early:
  557. return self.hapd
  558. if len(self.fst_group) != 0:
  559. self.send_iface_attach_request(self.iface, self.fst_group,
  560. self.fst_llt, self.fst_pri)
  561. return self.hapd
  562. def stop(self):
  563. """Removes the AP, To be used when dynamic fst APs are implemented in
  564. hostapd."""
  565. if len(self.fst_group) != 0:
  566. self.remove_all_sessions()
  567. try:
  568. self.send_iface_detach_request(self.iface)
  569. except Exception, e:
  570. logger.info(str(e))
  571. self.reg_ctrl.stop()
  572. del self.global_instance
  573. self.global_instance = None
  574. def get_instance(self):
  575. """Return the Hostapd/WpaSupplicant instance"""
  576. if self.instance is None:
  577. self.instance = hostapd.Hostapd(self.iface)
  578. return self.instance
  579. def get_global_instance(self):
  580. return self.global_instance
  581. def get_own_mac_address(self):
  582. """Gets the device's own MAC address"""
  583. h = self.get_instance()
  584. status = h.get_status()
  585. return status['bssid[0]']
  586. def get_actual_peer_addr(self):
  587. """Gets the peer address. A connected station address is returned."""
  588. # Use the device instance, the global control interface doesn't have
  589. # station address
  590. h = self.get_instance()
  591. sta = h.get_sta(None)
  592. if sta is None or 'addr' not in sta:
  593. # Maybe station is not connected?
  594. addr = None
  595. else:
  596. addr=sta['addr']
  597. return addr
  598. def grequest(self, req):
  599. """Send request on the global control interface"""
  600. logger.debug("FstAP::grequest: " + req)
  601. h = self.get_global_instance()
  602. return h.request(req)
  603. def wait_gevent(self, events, timeout=None):
  604. """Wait for a list of events on the global interface"""
  605. h = self.get_global_instance()
  606. if timeout is not None:
  607. return h.wait_event(events, timeout=timeout)
  608. else:
  609. return h.wait_event(events)
  610. def get_ssid(self):
  611. return self.ssid
  612. def dump_monitor(self):
  613. """Dump control interface monitor events"""
  614. if self.instance:
  615. self.instance.dump_monitor()
  616. #
  617. # FstSTA class
  618. #
  619. class FstSTA (FstDevice):
  620. def __init__(self, iface, fst_group, fst_pri, fst_llt=None, rsn=False):
  621. """If fst_group is empty, then FST parameters will not be set
  622. If fst_llt is empty, the parameter will not be set and the default value
  623. is expected to be configured."""
  624. FstDevice.__init__(self, iface, fst_group, fst_pri, fst_llt, rsn)
  625. self.connected = None # FstAP object the station is connected to
  626. def start(self):
  627. """Current implementation involves running another instance of
  628. wpa_supplicant with fixed FST STAs configurations. When any type of
  629. dynamic STA loading is implemented, rewrite the function similarly to
  630. FstAP."""
  631. h = self.get_instance()
  632. h.interface_add(self.iface, drv_params="force_connect_cmd=1")
  633. if not h.global_ping():
  634. raise Exception("Could not ping FST wpa_supplicant")
  635. if len(self.fst_group) != 0:
  636. self.send_iface_attach_request(self.iface, self.fst_group,
  637. self.fst_llt, self.fst_pri)
  638. return None
  639. def stop(self):
  640. """Removes the STA. In a static (temporary) implementation does nothing,
  641. the STA will be removed when the fst wpa_supplicant process is killed by
  642. fstap.cleanup()."""
  643. h = self.get_instance()
  644. h.dump_monitor()
  645. if len(self.fst_group) != 0:
  646. self.remove_all_sessions()
  647. self.send_iface_detach_request(self.iface)
  648. h.dump_monitor()
  649. h.interface_remove(self.iface)
  650. h.close_ctrl()
  651. del h
  652. self.instance = None
  653. def get_instance(self):
  654. """Return the Hostapd/WpaSupplicant instance"""
  655. if self.instance is None:
  656. self.instance = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
  657. return self.instance
  658. def get_own_mac_address(self):
  659. """Gets the device's own MAC address"""
  660. h = self.get_instance()
  661. status = h.get_status()
  662. return status['address']
  663. def get_actual_peer_addr(self):
  664. """Gets the peer address. A connected station address is returned"""
  665. h = self.get_instance()
  666. status = h.get_status()
  667. return status['bssid']
  668. def grequest(self, req):
  669. """Send request on the global control interface"""
  670. logger.debug("FstSTA::grequest: " + req)
  671. h = self.get_instance()
  672. return h.global_request(req)
  673. def wait_gevent(self, events, timeout=None):
  674. """Wait for a list of events on the global interface"""
  675. h = self.get_instance()
  676. if timeout is not None:
  677. return h.wait_global_event(events, timeout=timeout)
  678. else:
  679. return h.wait_global_event(events)
  680. def scan(self, freq=None, no_wait=False, only_new=False):
  681. """Issue Scan with given parameters. Returns the BSS dictionary for the
  682. AP found (the 1st BSS found. TODO: What if the AP required is not the
  683. 1st in list?) or None if no BSS found. None call be also a result of
  684. no_wait=True. Note, request("SCAN_RESULTS") can be used to get all the
  685. results at once."""
  686. h = self.get_instance()
  687. h.dump_monitor()
  688. h.scan(None, freq, no_wait, only_new)
  689. r = h.get_bss('0')
  690. h.dump_monitor()
  691. return r
  692. def connect(self, ap, **kwargs):
  693. """Connects to the given AP"""
  694. if not isinstance(ap, FstAP):
  695. raise Exception("Bad AP object to connect to")
  696. h = self.get_instance()
  697. hap = ap.get_instance()
  698. h.dump_monitor()
  699. h.connect(ap.get_ssid(), **kwargs)
  700. h.dump_monitor()
  701. self.connected = ap
  702. def connect_to_external_ap(self, ap, ssid, check_connection=True, **kwargs):
  703. """Connects to the given external AP"""
  704. if not isinstance(ap, hostapd.Hostapd):
  705. raise Exception("Bad AP object to connect to")
  706. h = self.get_instance()
  707. h.dump_monitor()
  708. h.connect(ssid, **kwargs)
  709. self.connected = ap
  710. if check_connection:
  711. ev = ap.wait_event([ "AP-STA-CONNECTED" ], timeout=10)
  712. if ev is None:
  713. self.connected = None
  714. raise Exception("No connection event received from %s" % ssid)
  715. h.dump_monitor()
  716. def disconnect(self, check_disconnect=True):
  717. """Disconnects from the AP the station is currently connected to"""
  718. if self.connected is not None:
  719. h = self.get_instance()
  720. h.dump_monitor()
  721. h.request("DISCONNECT")
  722. if check_disconnect:
  723. hap = self.connected.get_instance()
  724. ev = hap.wait_event([ "AP-STA-DISCONNECTED" ], timeout=10)
  725. if ev is None:
  726. raise Exception("No disconnection event received from %s" % self.connected.get_ssid())
  727. h.dump_monitor()
  728. self.connected = None
  729. def disconnect_from_external_ap(self, check_disconnect=True):
  730. """Disconnects from the external AP the station is currently connected
  731. to"""
  732. if self.connected is not None:
  733. h = self.get_instance()
  734. h.dump_monitor()
  735. h.request("DISCONNECT")
  736. if check_disconnect:
  737. hap = self.connected
  738. ev = hap.wait_event([ "AP-STA-DISCONNECTED" ], timeout=10)
  739. if ev is None:
  740. raise Exception("No disconnection event received from AP")
  741. h.dump_monitor()
  742. self.connected = None
  743. def dump_monitor(self):
  744. """Dump control interface monitor events"""
  745. if self.instance:
  746. self.instance.dump_monitor()