dpp-nfc: Add a class for maintaining connection handover state

This cleans up the shared state between the handover server and client.

Signed-off-by: Jouni Malinen <jouni@codeaurora.org>
This commit is contained in:
Jouni Malinen 2020-07-30 20:58:08 +03:00 committed by Jouni Malinen
parent 66d74626ba
commit aaa8638ed2

View file

@ -29,23 +29,14 @@ init_on_touch = False
in_raw_mode = False in_raw_mode = False
prev_tcgetattr = 0 prev_tcgetattr = 0
no_input = False no_input = False
srv = None
hs_client = None
need_client = False
continue_loop = True continue_loop = True
terminate_now = False terminate_now = False
summary_file = None summary_file = None
success_file = None success_file = None
my_crn_ready = False
my_crn = None
peer_crn = None
hs_sent = False
netrole = None netrole = None
operation_success = False operation_success = False
mutex = threading.Lock() mutex = threading.Lock()
client_mutex = threading.Lock() client_mutex = threading.Lock()
no_alt_proposal = False
i_m_selector = False
C_NORMAL = '\033[0m' C_NORMAL = '\033[0m'
C_RED = '\033[91m' C_RED = '\033[91m'
@ -251,26 +242,22 @@ def wpas_report_handover_sel(uri):
cmd = "DPP_NFC_HANDOVER_SEL own=%d uri=%s" % (own_id, uri) cmd = "DPP_NFC_HANDOVER_SEL own=%d uri=%s" % (own_id, uri)
return wpas.request(cmd) return wpas.request(cmd)
def dpp_handover_client(llc, alt=False): def dpp_handover_client(handover, alt=False):
summary("About to start run_dpp_handover_client (alt=%s)" % str(alt)) summary("About to start run_dpp_handover_client (alt=%s)" % str(alt))
if alt: if alt:
global need_client handover.need_client = True
need_client = True
with client_mutex: with client_mutex:
summary("Start run_dpp_handover_client (client_mutex held; alt=%s))" % str(alt)) summary("Start run_dpp_handover_client (client_mutex held; alt=%s))" % str(alt))
if alt: if alt:
global i_m_selector handover.i_m_selector = False
i_m_selector = False run_dpp_handover_client(handover, alt)
run_dpp_handover_client(llc, alt)
summary("Done run_dpp_handover_client (alt=%s)" % str(alt)) summary("Done run_dpp_handover_client (alt=%s)" % str(alt))
def run_dpp_handover_client(llc, alt=False): def run_dpp_handover_client(handover, alt=False):
chan_override = None chan_override = None
global alt_proposal_used
if alt: if alt:
global altchanlist chan_override = handover.altchanlist
chan_override = altchanlist handover.alt_proposal_used = True
alt_proposal_used = True
global test_uri, test_alt_uri global test_uri, test_alt_uri
if test_uri: if test_uri:
summary("TEST MODE: Using specified URI (alt=%s)" % str(alt)) summary("TEST MODE: Using specified URI (alt=%s)" % str(alt))
@ -297,17 +284,15 @@ def run_dpp_handover_client(llc, alt=False):
message = [hr, carrier] message = [hr, carrier]
summary("NFC Handover Request message for DPP: " + str(message)) summary("NFC Handover Request message for DPP: " + str(message))
global peer_crn if handover.peer_crn is not None and not alt:
if peer_crn is not None and not alt:
summary("NFC handover request from peer was already received - do not send own") summary("NFC handover request from peer was already received - do not send own")
return return
global hs_client if handover.client:
if hs_client:
summary("Use already started handover client") summary("Use already started handover client")
client = hs_client client = handover.client
else: else:
summary("Start handover client") summary("Start handover client")
client = nfc.handover.HandoverClient(llc) client = nfc.handover.HandoverClient(handover.llc)
try: try:
summary("Trying to initiate NFC connection handover") summary("Trying to initiate NFC connection handover")
client.connect() client.connect()
@ -320,66 +305,58 @@ def run_dpp_handover_client(llc, alt=False):
summary("Other exception: " + str(e)) summary("Other exception: " + str(e))
client.close() client.close()
return return
hs_client = client; handover.client = client
if peer_crn is not None and not alt: if handover.peer_crn is not None and not alt:
summary("NFC handover request from peer was already received - do not send own") summary("NFC handover request from peer was already received - do not send own")
return return
summary("Sending handover request") summary("Sending handover request")
global my_crn, my_crn_ready, hs_sent, need_client handover.my_crn_ready = True
my_crn_ready = True
if not client.send_records(message): if not client.send_records(message):
my_crn_ready = False handover.my_crn_ready = False
summary("Failed to send handover request", color=C_RED) summary("Failed to send handover request", color=C_RED)
hs_client = None
client.close()
return return
my_crn, = struct.unpack('>H', crn) handover.my_crn, = struct.unpack('>H', crn)
summary("Receiving handover response") summary("Receiving handover response")
try: try:
message = client.recv_records(timeout=3.0) message = client.recv_records(timeout=3.0)
except Exception as e: except Exception as e:
# This is fine if we are the handover selector # This is fine if we are the handover selector
if hs_sent: if handover.hs_sent:
summary("Client receive failed as expected since I'm the handover server: %s" % str(e)) summary("Client receive failed as expected since I'm the handover server: %s" % str(e))
elif alt_proposal_used and not alt: elif handover.alt_proposal_used and not alt:
summary("Client received failed for initial proposal as expected since alternative proposal was also used: %s" % str(e)) summary("Client received failed for initial proposal as expected since alternative proposal was also used: %s" % str(e))
else: else:
summary("Client receive failed: %s" % str(e), color=C_RED) summary("Client receive failed: %s" % str(e), color=C_RED)
message = None message = None
if message is None: if message is None:
if hs_sent: if handover.hs_sent:
summary("No response received as expected since I'm the handover server") summary("No response received as expected since I'm the handover server")
elif alt_proposal_used and not alt: elif handover.alt_proposal_used and not alt:
summary("No response received for initial proposal as expected since alternative proposal was also used") summary("No response received for initial proposal as expected since alternative proposal was also used")
elif need_client: elif handover.need_client:
summary("No response received, but handover client is still needed") summary("No response received, but handover client is still needed")
else: else:
summary("No response received", color=C_RED) summary("No response received", color=C_RED)
hs_client = None
client.close()
return return
summary("Received message: " + str(message)) summary("Received message: " + str(message))
if len(message) < 1 or \ if len(message) < 1 or \
not isinstance(message[0], ndef.HandoverSelectRecord): not isinstance(message[0], ndef.HandoverSelectRecord):
summary("Response was not Hs - received: " + message.type) summary("Response was not Hs - received: " + message.type)
hs_client = None
client.close()
return return
summary("Received handover select message") summary("Received handover select message")
summary("alternative carriers: " + str(message[0].alternative_carriers)) summary("alternative carriers: " + str(message[0].alternative_carriers))
global i_m_selector if handover.i_m_selector:
if i_m_selector:
summary("Ignore the received select since I'm the handover selector") summary("Ignore the received select since I'm the handover selector")
return return
if alt_proposal_used and not alt: if handover.alt_proposal_used and not alt:
summary("Ignore received handover select for the initial proposal since alternative proposal was sent") summary("Ignore received handover select for the initial proposal since alternative proposal was sent")
client.close() client.close()
return return
@ -435,23 +412,19 @@ def run_dpp_handover_client(llc, alt=False):
summary("Failed to initiate DPP authentication", color=C_RED) summary("Failed to initiate DPP authentication", color=C_RED)
break break
global no_alt_proposal if not dpp_found and handover.no_alt_proposal:
if not dpp_found and no_alt_proposal:
summary("DPP carrier not seen in response - do not allow alternative proposal anymore") summary("DPP carrier not seen in response - do not allow alternative proposal anymore")
elif not dpp_found: elif not dpp_found:
summary("DPP carrier not seen in response - allow peer to initiate a new handover with different parameters") summary("DPP carrier not seen in response - allow peer to initiate a new handover with different parameters")
my_crn_ready = False handover.my_crn_ready = False
my_crn = None handover.my_crn = None
peer_crn = None handover.peer_crn = None
hs_sent = False handover.hs_sent = False
hs_client = None
client.close()
summary("Returning from dpp_handover_client") summary("Returning from dpp_handover_client")
return return
summary("Remove peer") summary("Remove peer")
hs_client = None handover.close()
client.close()
summary("Done with handover") summary("Done with handover")
global only_one global only_one
if only_one: if only_one:
@ -468,15 +441,17 @@ def run_dpp_handover_client(llc, alt=False):
summary("Returning from dpp_handover_client") summary("Returning from dpp_handover_client")
class HandoverServer(nfc.handover.HandoverServer): class HandoverServer(nfc.handover.HandoverServer):
def __init__(self, llc): def __init__(self, handover, llc):
super(HandoverServer, self).__init__(llc) super(HandoverServer, self).__init__(llc)
self.sent_carrier = None self.sent_carrier = None
self.ho_server_processing = False self.ho_server_processing = False
self.success = False self.success = False
self.try_own = False self.try_own = False
self.llc = llc self.llc = llc
self.handover = handover
def process_handover_request_message(self, records): def process_handover_request_message(self, records):
handover = self.handover
self.ho_server_processing = True self.ho_server_processing = True
global in_raw_mode global in_raw_mode
was_in_raw_mode = in_raw_mode was_in_raw_mode = in_raw_mode
@ -485,34 +460,33 @@ class HandoverServer(nfc.handover.HandoverServer):
print("\n") print("\n")
summary("HandoverServer - request received: " + str(records)) summary("HandoverServer - request received: " + str(records))
global my_crn, peer_crn, my_crn_ready
for carrier in records: for carrier in records:
if not isinstance(carrier, ndef.HandoverRequestRecord): if not isinstance(carrier, ndef.HandoverRequestRecord):
continue continue
if carrier.collision_resolution_number: if carrier.collision_resolution_number:
peer_crn = carrier.collision_resolution_number handover.peer_crn = carrier.collision_resolution_number
summary("peer_crn: %d" % peer_crn) summary("peer_crn: %d" % handover.peer_crn)
if my_crn is None and my_crn_ready: if handover.my_crn is None and handover.my_crn_ready:
summary("Still trying to send own handover request - wait a moment to see if that succeeds before checking crn values") summary("Still trying to send own handover request - wait a moment to see if that succeeds before checking crn values")
for i in range(10): for i in range(10):
if my_crn is not None: if handover.my_crn is not None:
break break
time.sleep(0.01) time.sleep(0.01)
if my_crn is not None: if handover.my_crn is not None:
summary("my_crn: %d" % my_crn) summary("my_crn: %d" % handover.my_crn)
if my_crn is not None and peer_crn is not None: if handover.my_crn is not None and handover.peer_crn is not None:
if my_crn == peer_crn: if handover.my_crn == handover.peer_crn:
summary("Same crn used - automatic collision resolution failed") summary("Same crn used - automatic collision resolution failed")
# TODO: Should generate a new Handover Request message # TODO: Should generate a new Handover Request message
return '' return ''
if ((my_crn & 1) == (peer_crn & 1) and my_crn > peer_crn) or \ if ((handover.my_crn & 1) == (handover.peer_crn & 1) and \
((my_crn & 1) != (peer_crn & 1) and my_crn < peer_crn): handover.my_crn > handover.peer_crn) or \
((handover.my_crn & 1) != (handover.peer_crn & 1) and \
handover.my_crn < handover.peer_crn):
summary("I'm the Handover Selector Device") summary("I'm the Handover Selector Device")
global i_m_selector handover.i_m_selector = True
i_m_selector = True
else: else:
summary("Peer is the Handover Selector device") summary("Peer is the Handover Selector device")
summary("Ignore the received request.") summary("Ignore the received request.")
@ -553,10 +527,9 @@ class HandoverServer(nfc.handover.HandoverServer):
if res is None or "FAIL" in res: if res is None or "FAIL" in res:
summary("DPP handover request processing failed", summary("DPP handover request processing failed",
color=C_RED) color=C_RED)
global altchanlist if handover.altchanlist:
if altchanlist:
data = wpas_get_nfc_uri(start_listen=False, data = wpas_get_nfc_uri(start_listen=False,
chan_override=altchanlist) chan_override=handover.altchanlist)
summary("Own URI (try another channel list): %s" % data) summary("Own URI (try another channel list): %s" % data)
continue continue
@ -615,21 +588,20 @@ class HandoverServer(nfc.handover.HandoverServer):
sel = [hs, carrier] sel = [hs, carrier]
break break
global hs_sent, no_alt_proposal
summary("Sending handover select: " + str(sel)) summary("Sending handover select: " + str(sel))
if found: if found:
summary("Handover completed successfully") summary("Handover completed successfully")
self.success = True self.success = True
hs_sent = True handover.hs_sent = True
elif no_alt_proposal: elif handover.no_alt_proposal:
summary("Do not try alternative proposal anymore - handover failed", summary("Do not try alternative proposal anymore - handover failed",
color=C_RED) color=C_RED)
hs_sent = True handover.hs_sent = True
else: else:
summary("Try to initiate with alternative parameters") summary("Try to initiate with alternative parameters")
self.try_own = True self.try_own = True
hs_sent = False handover.hs_sent = False
no_alt_proposal = True handover.no_alt_proposal = True
threading.Thread(target=llcp_worker, args=(self.llc, True)).start() threading.Thread(target=llcp_worker, args=(self.llc, True)).start()
return sel return sel
@ -772,16 +744,17 @@ def rdwr_connected(tag):
return not no_wait return not no_wait
def llcp_worker(llc, try_alt): def llcp_worker(llc, try_alt):
global handover
print("Start of llcp_worker()") print("Start of llcp_worker()")
if try_alt: if try_alt:
summary("Starting handover client (try_alt)") summary("Starting handover client (try_alt)")
dpp_handover_client(llc, alt=True) dpp_handover_client(handover, alt=True)
summary("Exiting llcp_worker thread (try_alt)") summary("Exiting llcp_worker thread (try_alt)")
return return
global init_on_touch global init_on_touch
if init_on_touch: if init_on_touch:
summary("Starting handover client (init_on_touch)") summary("Starting handover client (init_on_touch)")
dpp_handover_client(llc) dpp_handover_client(handover)
summary("Exiting llcp_worker thread (init_on_touch)") summary("Exiting llcp_worker thread (init_on_touch)")
return return
@ -790,21 +763,18 @@ def llcp_worker(llc, try_alt):
summary("Wait for handover to complete") summary("Wait for handover to complete")
else: else:
print("Wait for handover to complete - press 'i' to initiate") print("Wait for handover to complete - press 'i' to initiate")
global srv while not handover.wait_connection and handover.srv.sent_carrier is None:
global wait_connection if handover.srv.try_own:
while not wait_connection and srv.sent_carrier is None: handover.srv.try_own = False
if srv.try_own:
srv.try_own = False
summary("Try to initiate another handover with own parameters") summary("Try to initiate another handover with own parameters")
global peer_crn, my_crn, my_crn_ready, hs_sent handover.my_crn_ready = False
my_crn_ready = False handover.my_crn = None
my_crn = None handover.peer_crn = None
peer_crn = None handover.hs_sent = False
hs_sent = False dpp_handover_client(handover, alt=True)
dpp_handover_client(llc, alt=True)
summary("Exiting llcp_worker thread (retry with own parameters)") summary("Exiting llcp_worker thread (retry with own parameters)")
return return
if srv.ho_server_processing: if handover.srv.ho_server_processing:
time.sleep(0.025) time.sleep(0.025)
elif no_input: elif no_input:
time.sleep(0.5) time.sleep(0.5)
@ -814,7 +784,7 @@ def llcp_worker(llc, try_alt):
continue continue
clear_raw_mode() clear_raw_mode()
summary("Starting handover client") summary("Starting handover client")
dpp_handover_client(llc) dpp_handover_client(handover)
summary("Exiting llcp_worker thread (manual init)") summary("Exiting llcp_worker thread (manual init)")
return return
@ -825,37 +795,49 @@ def llcp_worker(llc, try_alt):
print("\r") print("\r")
summary("Exiting llcp_worker thread") summary("Exiting llcp_worker thread")
class ConnectionHandover():
def __init__(self):
self.client = None
self.reset()
def reset(self):
self.wait_connection = False
self.my_crn_ready = False
self.my_crn = None
self.peer_crn = None
self.hs_sent = False
self.no_alt_proposal = False
self.alt_proposal_used = False
self.need_client = False
self.i_m_selector = False
def start_handover_server(self, llc):
summary("Start handover server")
self.llc = llc
self.srv = HandoverServer(self, llc)
def close(self):
if self.client:
self.client.close()
self.client = None
def llcp_startup(llc): def llcp_startup(llc):
summary("Start LLCP server") global handover
global srv handover.start_handover_server(llc)
srv = HandoverServer(llc)
return llc return llc
def llcp_connected(llc): def llcp_connected(llc):
summary("P2P LLCP connected") summary("P2P LLCP connected")
global wait_connection, my_crn, peer_crn, my_crn_ready, hs_sent global handover
global no_alt_proposal, alt_proposal_used, need_client, i_m_selector handover.srv.start()
wait_connection = False
my_crn_ready = False
my_crn = None
peer_crn = None
hs_sent = False
no_alt_proposal = False
alt_proposal_used = False
need_client = False
i_m_selector = False
global srv
srv.start()
if init_on_touch or not no_input: if init_on_touch or not no_input:
threading.Thread(target=llcp_worker, args=(llc, False)).start() threading.Thread(target=llcp_worker, args=(llc, False)).start()
return True return True
def llcp_release(llc): def llcp_release(llc):
summary("LLCP release") summary("LLCP release")
global hs_client global handover
if hs_client: handover.close()
hs_client.close()
hs_client = None
return True return True
def terminate_loop(): def terminate_loop():
@ -915,16 +897,19 @@ def main():
args = parser.parse_args() args = parser.parse_args()
summary(args) summary(args)
global handover
handover = ConnectionHandover()
global only_one global only_one
only_one = args.only_one only_one = args.only_one
global no_wait global no_wait
no_wait = args.no_wait no_wait = args.no_wait
global chanlist, altchanlist, netrole, test_uri, test_alt_uri, test_sel_uri global chanlist, netrole, test_uri, test_alt_uri, test_sel_uri
global test_crn global test_crn
chanlist = args.chan chanlist = args.chan
altchanlist = args.altchan handover.altchanlist = args.altchan
netrole = args.netrole netrole = args.netrole
test_uri = args.test_uri test_uri = args.test_uri
test_alt_uri = args.test_alt_uri test_alt_uri = args.test_alt_uri
@ -978,7 +963,6 @@ def main():
no_input = True no_input = True
clf = nfc.ContactlessFrontend() clf = nfc.ContactlessFrontend()
global wait_connection
try: try:
if not clf.open(args.device): if not clf.open(args.device):
@ -1011,7 +995,7 @@ def main():
else: else:
summary("Waiting for a tag or peer to be touched", summary("Waiting for a tag or peer to be touched",
color=C_GREEN) color=C_GREEN)
wait_connection = True handover.wait_connection = True
try: try:
if args.tag_read_only: if args.tag_read_only:
if not clf.connect(rdwr={'on-connect': rdwr_connected}): if not clf.connect(rdwr={'on-connect': rdwr_connected}):
@ -1033,8 +1017,7 @@ def main():
summary("clf.connect failed: " + str(e)) summary("clf.connect failed: " + str(e))
break break
global srv if only_one and handover.srv and handover.srv.success:
if only_one and srv and srv.success:
raise SystemExit raise SystemExit
except KeyboardInterrupt: except KeyboardInterrupt: