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()
83 return res.decode("hex")
85 def wpas_get_handover_req_wps():
89 res = wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip()
92 return res.decode("hex")
95 def wpas_get_handover_sel(tag=False):
100 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR-TAG").rstrip()
102 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR").rstrip()
105 return res.decode("hex")
108 def wpas_get_handover_sel_wps():
109 wpas = wpas_connect()
112 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR");
115 return res.rstrip().decode("hex")
118 def wpas_report_handover(req, sel, type):
119 wpas = wpas_connect()
122 cmd = "NFC_REPORT_HANDOVER " + type + " P2P " + str(req).encode("hex") + " " + str(sel).encode("hex")
125 cmd = cmd + " freq=" + force_freq
126 return wpas.request(cmd)
129 def wpas_report_handover_wsc(req, sel, type):
130 wpas = wpas_connect()
133 cmd = "NFC_REPORT_HANDOVER " + type + " WPS " + str(req).encode("hex") + " " + str(sel).encode("hex")
135 cmd = cmd + " freq=" + force_freq
136 return wpas.request(cmd)
139 def p2p_handover_client(llc):
140 message = nfc.ndef.HandoverRequestMessage(version="1.2")
141 message.nonce = random.randint(0, 0xffff)
143 global include_p2p_req
145 data = wpas_get_handover_req()
147 print "Could not get handover request carrier record from wpa_supplicant"
149 print "Handover request carrier record from wpa_supplicant: " + data.encode("hex")
150 datamsg = nfc.ndef.Message(data)
151 message.add_carrier(datamsg[0], "active", datamsg[1:])
153 global include_wps_req
155 print "Handover request (pre-WPS):"
157 print message.pretty()
161 data = wpas_get_handover_req_wps()
163 print "Add WPS request in addition to P2P"
164 datamsg = nfc.ndef.Message(data)
165 message.add_carrier(datamsg[0], "active", datamsg[1:])
167 print "Handover request:"
169 print message.pretty()
172 print str(message).encode("hex")
174 client = nfc.handover.HandoverClient(llc)
176 print "Trying handover";
178 print "Connected for handover"
179 except nfc.llcp.ConnectRefused:
180 print "Handover connection refused"
184 print "Other exception: " + str(e)
188 print "Sending handover request"
190 if not client.send(message):
191 print "Failed to send handover request"
193 print "Receiving handover response"
194 message = client._recv()
196 print "No response received"
199 if message.type != "urn:nfc:wkt:Hs":
200 print "Response was not Hs - received: " + message.type
204 print "Received message"
206 print message.pretty()
209 print str(message).encode("hex")
210 message = nfc.ndef.HandoverSelectMessage(message)
211 print "Handover select received"
213 print message.pretty()
217 for carrier in message.carriers:
218 print "Remote carrier type: " + carrier.type
219 if carrier.type == "application/vnd.wfa.p2p":
220 print "P2P carrier type match - send to wpa_supplicant"
221 wpas_report_handover(data, carrier.record, "INIT")
226 print "Done with handover"
229 print "only_one -> stop loop"
231 continue_loop = False
235 print "Trying to exit.."
240 class HandoverServer(nfc.handover.HandoverServer):
241 def __init__(self, llc):
242 super(HandoverServer, self).__init__(llc)
243 self.sent_carrier = None
244 self.ho_server_processing = False
247 def process_request(self, request):
248 self.ho_server_processing = True
250 print "HandoverServer - request received"
252 print "Parsed handover request: " + request.pretty()
256 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
260 for carrier in request.carriers:
261 print "Remote carrier type: " + carrier.type
262 if carrier.type == "application/vnd.wfa.p2p":
263 print "P2P carrier type match - add P2P carrier record"
265 self.received_carrier = carrier.record
266 print "Carrier record:"
268 print carrier.record.pretty()
271 data = wpas_get_handover_sel()
273 print "Could not get handover select carrier record from wpa_supplicant"
275 print "Handover select carrier record from wpa_supplicant:"
276 print data.encode("hex")
277 self.sent_carrier = data
278 wpas_report_handover(self.received_carrier, self.sent_carrier,
281 message = nfc.ndef.Message(data);
282 sel.add_carrier(message[0], "active", message[1:])
285 for carrier in request.carriers:
288 print "Remote carrier type: " + carrier.type
289 if carrier.type == "application/vnd.wfa.wsc":
290 print "WSC carrier type match - add WSC carrier record"
292 self.received_carrier = carrier.record
293 print "Carrier record:"
295 print carrier.record.pretty()
298 data = wpas_get_handover_sel_wps()
300 print "Could not get handover select carrier record from wpa_supplicant"
302 print "Handover select carrier record from wpa_supplicant:"
303 print data.encode("hex")
304 self.sent_carrier = data
305 wpas_report_handover_wsc(self.received_carrier,
306 self.sent_carrier, "RESP")
308 message = nfc.ndef.Message(data);
309 sel.add_carrier(message[0], "active", message[1:])
313 print "Handover select:"
318 print str(sel).encode("hex")
320 print "Sending handover select"
325 def clear_raw_mode():
326 import sys, tty, termios
327 global prev_tcgetattr, in_raw_mode
330 fd = sys.stdin.fileno()
331 termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr)
336 import sys, tty, termios, select
337 global prev_tcgetattr, in_raw_mode
338 fd = sys.stdin.fileno()
339 prev_tcgetattr = termios.tcgetattr(fd)
344 [i, o, e] = select.select([fd], [], [], 0.05)
346 ch = sys.stdin.read(1)
348 termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr)
353 def p2p_tag_read(tag):
355 if len(tag.ndef.message):
356 for record in tag.ndef.message:
357 print "record type " + record.type
358 if record.type == "application/vnd.wfa.wsc":
359 print "WPS tag - send to wpa_supplicant"
360 success = wpas_tag_read(tag.ndef.message)
362 if record.type == "application/vnd.wfa.p2p":
363 print "P2P tag - send to wpa_supplicant"
364 success = wpas_tag_read(tag.ndef.message)
372 def rdwr_connected_p2p_write(tag):
373 print "Tag found - writing"
375 tag.ndef.message = str(p2p_sel_data)
376 print "Done - remove tag"
380 continue_loop = False
381 global p2p_sel_wait_remove
382 return p2p_sel_wait_remove
384 def wps_write_p2p_handover_sel(clf, wait_remove=True):
385 print "Write P2P handover select"
386 data = wpas_get_handover_sel(tag=True)
388 print "Could not get P2P handover select from wpa_supplicant"
391 global p2p_sel_wait_remove
392 p2p_sel_wait_remove = wait_remove
394 p2p_sel_data = nfc.ndef.HandoverSelectMessage(version="1.2")
395 message = nfc.ndef.Message(data);
396 p2p_sel_data.add_carrier(message[0], "active", message[1:])
397 print "Handover select:"
399 print p2p_sel_data.pretty()
402 print str(p2p_sel_data).encode("hex")
404 print "Touch an NFC tag"
405 clf.connect(rdwr={'on-connect': rdwr_connected_p2p_write})
408 def rdwr_connected(tag):
409 global only_one, no_wait
410 print "Tag connected: " + str(tag)
413 print "NDEF tag: " + tag.type
415 print tag.ndef.message.pretty()
418 success = p2p_tag_read(tag)
419 if only_one and success:
421 continue_loop = False
423 print "Not an NDEF tag - remove tag"
428 def llcp_worker(llc):
431 print "Starting handover client"
432 p2p_handover_client(llc)
437 print "Wait for handover to complete"
439 print "Wait for handover to complete - press 'i' to initiate ('w' for WPS only, 'p' for P2P only)"
441 global wait_connection
442 while not wait_connection and srv.sent_carrier is None:
443 if srv.ho_server_processing:
448 global include_wps_req, include_p2p_req
451 include_wps_req = True
452 include_p2p_req = True
454 include_wps_req = False
455 include_p2p_req = True
457 include_wps_req = True
458 include_p2p_req = False
462 print "Starting handover client"
463 p2p_handover_client(llc)
467 print "Exiting llcp_worker thread"
469 def llcp_startup(clf, llc):
470 print "Start LLCP server"
472 srv = HandoverServer(llc)
475 def llcp_connected(llc):
476 print "P2P LLCP connected"
477 global wait_connection
478 wait_connection = False
480 if not init_on_touch:
483 if init_on_touch or not no_input:
484 threading.Thread(target=llcp_worker, args=(llc,)).start()
487 def terminate_loop():
492 clf = nfc.ContactlessFrontend()
494 parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for P2P and WPS NFC operations')
495 parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,
496 action='store_const', dest='loglevel',
497 help='verbose debug output')
498 parser.add_argument('-q', const=logging.WARNING, action='store_const',
499 dest='loglevel', help='be quiet')
500 parser.add_argument('--only-one', '-1', action='store_true',
501 help='run only one operation and exit')
502 parser.add_argument('--init-on-touch', '-I', action='store_true',
503 help='initiate handover on touch')
504 parser.add_argument('--no-wait', action='store_true',
505 help='do not wait for tag to be removed before exiting')
506 parser.add_argument('--ifname', '-i',
507 help='network interface name')
508 parser.add_argument('--no-wps-req', '-N', action='store_true',
509 help='do not include WPS carrier record in request')
510 parser.add_argument('--no-input', '-a', action='store_true',
511 help='do not use stdout input to initiate handover')
512 parser.add_argument('--tag-read-only', '-t', action='store_true',
513 help='tag read only (do not allow connection handover)')
514 parser.add_argument('--handover-only', action='store_true',
515 help='connection handover only (do not allow tag read)')
516 parser.add_argument('--freq', '-f',
517 help='forced frequency of operating channel in MHz')
518 parser.add_argument('command', choices=['write-p2p-sel'],
520 args = parser.parse_args()
523 only_one = args.only_one
526 no_wait = args.no_wait
529 force_freq = args.freq
531 logging.basicConfig(level=args.loglevel)
534 init_on_touch = args.init_on_touch
539 print "Selected ifname " + ifname
542 global include_wps_req
543 include_wps_req = False
549 clf = nfc.ContactlessFrontend()
550 global wait_connection
553 if not clf.open("usb"):
554 print "Could not open connection with an NFC device"
557 if args.command == "write-p2p-sel":
558 wps_write_p2p_handover_sel(clf, wait_remove=not args.no_wait)
563 print "Waiting for a tag or peer to be touched"
564 wait_connection = True
566 if args.tag_read_only:
567 if not clf.connect(rdwr={'on-connect': rdwr_connected}):
569 elif args.handover_only:
570 if not clf.connect(llcp={'on-startup': llcp_startup,
571 'on-connect': llcp_connected},
572 terminate=terminate_loop):
575 if not clf.connect(rdwr={'on-connect': rdwr_connected},
576 llcp={'on-startup': llcp_startup,
577 'on-connect': llcp_connected},
578 terminate=terminate_loop):
581 print "clf.connect failed"
584 if only_one and srv and srv.success:
587 except KeyboardInterrupt:
594 if __name__ == '__main__':