3 # Example nfcpy to wpa_supplicant wrapper for P2P NFC operations
4 # Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi>
6 # This software may be distributed under the terms of the BSD license.
7 # See README for more details.
25 wpas_ctrl = '/var/run/wpa_supplicant'
30 include_wps_req = True
31 include_p2p_req = True
39 if os.path.isdir(wpas_ctrl):
41 ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
42 except OSError, error:
43 print "Could not find wpa_supplicant: ", error
47 print "No wpa_supplicant control interface found"
52 if ifname not in ctrl:
55 print "Trying to use control interface " + ctrl
56 wpas = wpaspy.Ctrl(ctrl)
63 def wpas_tag_read(message):
67 cmd = "WPS_NFC_TAG_READ " + str(message).encode("hex")
70 cmd = cmd + " freq=" + force_freq
71 if "FAIL" in wpas.request(cmd):
76 def wpas_get_handover_req():
80 res = wpas.request("NFC_GET_HANDOVER_REQ NDEF P2P-CR").rstrip().decode("hex")
85 def wpas_get_handover_req_wps():
89 return wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip().decode("hex")
92 def wpas_get_handover_sel(tag=False):
97 return wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR-TAG").rstrip().decode("hex")
98 return wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR").rstrip().decode("hex")
101 def wpas_get_handover_sel_wps():
102 wpas = wpas_connect()
105 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR");
108 return res.rstrip().decode("hex")
111 def wpas_report_handover(req, sel, type):
112 wpas = wpas_connect()
115 cmd = "NFC_REPORT_HANDOVER " + type + " P2P " + str(req).encode("hex") + " " + str(sel).encode("hex")
118 cmd = cmd + " freq=" + force_freq
119 return wpas.request(cmd)
122 def wpas_report_handover_wsc(req, sel, type):
123 wpas = wpas_connect()
126 cmd = "NFC_REPORT_HANDOVER " + type + " WPS " + str(req).encode("hex") + " " + str(sel).encode("hex")
128 cmd = cmd + " freq=" + force_freq
129 return wpas.request(cmd)
132 def p2p_handover_client(llc):
133 message = nfc.ndef.HandoverRequestMessage(version="1.2")
134 message.nonce = random.randint(0, 0xffff)
136 global include_p2p_req
138 data = wpas_get_handover_req()
140 print "Could not get handover request carrier record from wpa_supplicant"
142 print "Handover request carrier record from wpa_supplicant: " + data.encode("hex")
143 datamsg = nfc.ndef.Message(data)
144 message.add_carrier(datamsg[0], "active", datamsg[1:])
146 global include_wps_req
148 print "Handover request (pre-WPS):"
150 print message.pretty()
154 data = wpas_get_handover_req_wps()
156 print "Add WPS request in addition to P2P"
157 datamsg = nfc.ndef.Message(data)
158 message.add_carrier(datamsg[0], "active", datamsg[1:])
160 print "Handover request:"
162 print message.pretty()
165 print str(message).encode("hex")
167 client = nfc.handover.HandoverClient(llc)
169 print "Trying handover";
171 print "Connected for handover"
172 except nfc.llcp.ConnectRefused:
173 print "Handover connection refused"
177 print "Other exception: " + str(e)
181 print "Sending handover request"
183 if not client.send(message):
184 print "Failed to send handover request"
186 print "Receiving handover response"
187 message = client._recv()
189 print "No response received"
192 if message.type != "urn:nfc:wkt:Hs":
193 print "Response was not Hs - received: " + message.type
197 print "Received message"
199 print message.pretty()
202 print str(message).encode("hex")
203 message = nfc.ndef.HandoverSelectMessage(message)
204 print "Handover select received"
206 print message.pretty()
210 for carrier in message.carriers:
211 print "Remote carrier type: " + carrier.type
212 if carrier.type == "application/vnd.wfa.p2p":
213 print "P2P carrier type match - send to wpa_supplicant"
214 wpas_report_handover(data, carrier.record, "INIT")
219 print "Done with handover"
222 print "only_one -> stop loop"
224 continue_loop = False
228 print "Trying to exit.."
233 class HandoverServer(nfc.handover.HandoverServer):
234 def __init__(self, llc):
235 super(HandoverServer, self).__init__(llc)
236 self.sent_carrier = None
237 self.ho_server_processing = False
240 def process_request(self, request):
241 self.ho_server_processing = True
243 print "HandoverServer - request received"
245 print "Parsed handover request: " + request.pretty()
249 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
253 for carrier in request.carriers:
254 print "Remote carrier type: " + carrier.type
255 if carrier.type == "application/vnd.wfa.p2p":
256 print "P2P carrier type match - add P2P carrier record"
258 self.received_carrier = carrier.record
259 print "Carrier record:"
261 print carrier.record.pretty()
264 data = wpas_get_handover_sel()
266 print "Could not get handover select carrier record from wpa_supplicant"
268 print "Handover select carrier record from wpa_supplicant:"
269 print data.encode("hex")
270 self.sent_carrier = data
271 wpas_report_handover(self.received_carrier, self.sent_carrier,
274 message = nfc.ndef.Message(data);
275 sel.add_carrier(message[0], "active", message[1:])
278 for carrier in request.carriers:
281 print "Remote carrier type: " + carrier.type
282 if carrier.type == "application/vnd.wfa.wsc":
283 print "WSC carrier type match - add WSC carrier record"
285 self.received_carrier = carrier.record
286 print "Carrier record:"
288 print carrier.record.pretty()
291 data = wpas_get_handover_sel_wps()
293 print "Could not get handover select carrier record from wpa_supplicant"
295 print "Handover select carrier record from wpa_supplicant:"
296 print data.encode("hex")
297 self.sent_carrier = data
298 wpas_report_handover_wsc(self.received_carrier,
299 self.sent_carrier, "RESP")
301 message = nfc.ndef.Message(data);
302 sel.add_carrier(message[0], "active", message[1:])
306 print "Handover select:"
311 print str(sel).encode("hex")
313 print "Sending handover select"
318 def clear_raw_mode():
319 import sys, tty, termios
320 global prev_tcgetattr, in_raw_mode
323 fd = sys.stdin.fileno()
324 termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr)
329 import sys, tty, termios, select
330 global prev_tcgetattr, in_raw_mode
331 fd = sys.stdin.fileno()
332 prev_tcgetattr = termios.tcgetattr(fd)
337 [i, o, e] = select.select([fd], [], [], 0.05)
339 ch = sys.stdin.read(1)
341 termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr)
346 def p2p_tag_read(tag):
348 if len(tag.ndef.message):
349 for record in tag.ndef.message:
350 print "record type " + record.type
351 if record.type == "application/vnd.wfa.wsc":
352 print "WPS tag - send to wpa_supplicant"
353 success = wpas_tag_read(tag.ndef.message)
355 if record.type == "application/vnd.wfa.p2p":
356 print "P2P tag - send to wpa_supplicant"
357 success = wpas_tag_read(tag.ndef.message)
365 def rdwr_connected_p2p_write(tag):
366 print "Tag found - writing"
368 tag.ndef.message = str(p2p_sel_data)
369 print "Done - remove tag"
373 continue_loop = False
374 global p2p_sel_wait_remove
375 return p2p_sel_wait_remove
377 def wps_write_p2p_handover_sel(clf, wait_remove=True):
378 print "Write P2P handover select"
379 data = wpas_get_handover_sel(tag=True)
381 print "Could not get P2P handover select from wpa_supplicant"
384 global p2p_sel_wait_remove
385 p2p_sel_wait_remove = wait_remove
387 p2p_sel_data = nfc.ndef.HandoverSelectMessage(version="1.2")
388 message = nfc.ndef.Message(data);
389 p2p_sel_data.add_carrier(message[0], "active", message[1:])
390 print "Handover select:"
392 print p2p_sel_data.pretty()
395 print str(p2p_sel_data).encode("hex")
397 print "Touch an NFC tag"
398 clf.connect(rdwr={'on-connect': rdwr_connected_p2p_write})
401 def rdwr_connected(tag):
402 global only_one, no_wait
403 print "Tag connected: " + str(tag)
406 print "NDEF tag: " + tag.type
408 print tag.ndef.message.pretty()
411 success = p2p_tag_read(tag)
412 if only_one and success:
414 continue_loop = False
416 print "Not an NDEF tag - remove tag"
421 def llcp_worker(llc):
424 print "Starting handover client"
425 p2p_handover_client(llc)
430 print "Wait for handover to complete"
432 print "Wait for handover to complete - press 'i' to initiate ('w' for WPS only, 'p' for P2P only)"
434 global wait_connection
435 while not wait_connection and srv.sent_carrier is None:
436 if srv.ho_server_processing:
441 global include_wps_req, include_p2p_req
444 include_wps_req = True
445 include_p2p_req = True
447 include_wps_req = False
448 include_p2p_req = True
450 include_wps_req = True
451 include_p2p_req = False
455 print "Starting handover client"
456 p2p_handover_client(llc)
460 print "Exiting llcp_worker thread"
462 def llcp_startup(clf, llc):
463 print "Start LLCP server"
465 srv = HandoverServer(llc)
468 def llcp_connected(llc):
469 print "P2P LLCP connected"
470 global wait_connection
471 wait_connection = False
473 if not init_on_touch:
476 if init_on_touch or not no_input:
477 threading.Thread(target=llcp_worker, args=(llc,)).start()
480 def terminate_loop():
485 clf = nfc.ContactlessFrontend()
487 parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for P2P and WPS NFC operations')
488 parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,
489 action='store_const', dest='loglevel',
490 help='verbose debug output')
491 parser.add_argument('-q', const=logging.WARNING, action='store_const',
492 dest='loglevel', help='be quiet')
493 parser.add_argument('--only-one', '-1', action='store_true',
494 help='run only one operation and exit')
495 parser.add_argument('--init-on-touch', '-I', action='store_true',
496 help='initiate handover on touch')
497 parser.add_argument('--no-wait', action='store_true',
498 help='do not wait for tag to be removed before exiting')
499 parser.add_argument('--ifname', '-i',
500 help='network interface name')
501 parser.add_argument('--no-wps-req', '-N', action='store_true',
502 help='do not include WPS carrier record in request')
503 parser.add_argument('--no-input', '-a', action='store_true',
504 help='do not use stdout input to initiate handover')
505 parser.add_argument('--tag-read-only', '-t', action='store_true',
506 help='tag read only (do not allow connection handover)')
507 parser.add_argument('--freq', '-f',
508 help='forced frequency of operating channel in MHz')
509 parser.add_argument('command', choices=['write-p2p-sel'],
511 args = parser.parse_args()
514 only_one = args.only_one
517 no_wait = args.no_wait
520 force_freq = args.freq
522 logging.basicConfig(level=args.loglevel)
525 init_on_touch = args.init_on_touch
530 print "Selected ifname " + ifname
533 global include_wps_req
534 include_wps_req = False
540 clf = nfc.ContactlessFrontend()
541 global wait_connection
544 if not clf.open("usb"):
545 print "Could not open connection with an NFC device"
548 if args.command == "write-p2p-sel":
549 wps_write_p2p_handover_sel(clf, wait_remove=not args.no_wait)
554 print "Waiting for a tag or peer to be touched"
555 wait_connection = True
557 if args.tag_read_only:
558 if not clf.connect(rdwr={'on-connect': rdwr_connected}):
561 if not clf.connect(rdwr={'on-connect': rdwr_connected},
562 llcp={'on-startup': llcp_startup,
563 'on-connect': llcp_connected},
564 terminate=terminate_loop):
567 print "clf.connect failed"
570 if only_one and srv and srv.success:
573 except KeyboardInterrupt:
580 if __name__ == '__main__':