fst_module_aux.py 32 KB

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