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
42 with open(summary_file, 'a') as f:
45 def success_report(txt):
48 with open(success_file, 'a') as f:
53 if os.path.isdir(wpas_ctrl):
55 ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
56 except OSError, error:
57 print "Could not find wpa_supplicant: ", error
61 print "No wpa_supplicant control interface found"
66 if ifname not in ctrl:
69 print "Trying to use control interface " + ctrl
70 wpas = wpaspy.Ctrl(ctrl)
77 def wpas_tag_read(message):
81 cmd = "WPS_NFC_TAG_READ " + str(message).encode("hex")
84 cmd = cmd + " freq=" + force_freq
85 if "FAIL" in wpas.request(cmd):
90 def wpas_get_handover_req():
94 res = wpas.request("NFC_GET_HANDOVER_REQ NDEF P2P-CR").rstrip()
97 return res.decode("hex")
99 def wpas_get_handover_req_wps():
100 wpas = wpas_connect()
103 res = wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip()
106 return res.decode("hex")
109 def wpas_get_handover_sel(tag=False):
110 wpas = wpas_connect()
114 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR-TAG").rstrip()
116 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR").rstrip()
119 return res.decode("hex")
122 def wpas_get_handover_sel_wps():
123 wpas = wpas_connect()
126 res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR");
129 return res.rstrip().decode("hex")
132 def wpas_report_handover(req, sel, type):
133 wpas = wpas_connect()
136 cmd = "NFC_REPORT_HANDOVER " + type + " P2P " + str(req).encode("hex") + " " + str(sel).encode("hex")
139 cmd = cmd + " freq=" + force_freq
140 return wpas.request(cmd)
143 def wpas_report_handover_wsc(req, sel, type):
144 wpas = wpas_connect()
147 cmd = "NFC_REPORT_HANDOVER " + type + " WPS " + str(req).encode("hex") + " " + str(sel).encode("hex")
149 cmd = cmd + " freq=" + force_freq
150 return wpas.request(cmd)
153 def p2p_handover_client(llc):
154 message = nfc.ndef.HandoverRequestMessage(version="1.2")
155 message.nonce = random.randint(0, 0xffff)
157 global include_p2p_req
159 data = wpas_get_handover_req()
161 summary("Could not get handover request carrier record from wpa_supplicant")
163 print "Handover request carrier record from wpa_supplicant: " + data.encode("hex")
164 datamsg = nfc.ndef.Message(data)
165 message.add_carrier(datamsg[0], "active", datamsg[1:])
167 global include_wps_req
169 print "Handover request (pre-WPS):"
171 print message.pretty()
175 data = wpas_get_handover_req_wps()
177 print "Add WPS request in addition to P2P"
178 datamsg = nfc.ndef.Message(data)
179 message.add_carrier(datamsg[0], "active", datamsg[1:])
181 print "Handover request:"
183 print message.pretty()
186 print str(message).encode("hex")
188 client = nfc.handover.HandoverClient(llc)
190 summary("Trying to initiate NFC connection handover")
192 summary("Connected for handover")
193 except nfc.llcp.ConnectRefused:
194 summary("Handover connection refused")
198 summary("Other exception: " + str(e))
202 summary("Sending handover request")
204 if not client.send(message):
205 summary("Failed to send handover request")
209 summary("Receiving handover response")
210 message = client._recv()
212 summary("No response received")
215 if message.type != "urn:nfc:wkt:Hs":
216 summary("Response was not Hs - received: " + message.type)
220 print "Received message"
222 print message.pretty()
225 print str(message).encode("hex")
226 message = nfc.ndef.HandoverSelectMessage(message)
227 summary("Handover select received")
229 print message.pretty()
233 for carrier in message.carriers:
234 print "Remote carrier type: " + carrier.type
235 if carrier.type == "application/vnd.wfa.p2p":
236 print "P2P carrier type match - send to wpa_supplicant"
237 if "OK" in wpas_report_handover(data, carrier.record, "INIT"):
238 success_report("P2P handover reported successfully (initiator)")
240 summary("P2P handover report rejected")
245 print "Done with handover"
248 print "only_one -> stop loop"
250 continue_loop = False
254 print "Trying to exit.."
259 class HandoverServer(nfc.handover.HandoverServer):
260 def __init__(self, llc):
261 super(HandoverServer, self).__init__(llc)
262 self.sent_carrier = None
263 self.ho_server_processing = False
266 def process_request(self, request):
267 self.ho_server_processing = True
269 print "HandoverServer - request received"
271 print "Parsed handover request: " + request.pretty()
275 sel = nfc.ndef.HandoverSelectMessage(version="1.2")
279 for carrier in request.carriers:
280 print "Remote carrier type: " + carrier.type
281 if carrier.type == "application/vnd.wfa.p2p":
282 print "P2P carrier type match - add P2P carrier record"
284 self.received_carrier = carrier.record
285 print "Carrier record:"
287 print carrier.record.pretty()
290 data = wpas_get_handover_sel()
292 print "Could not get handover select carrier record from wpa_supplicant"
294 print "Handover select carrier record from wpa_supplicant:"
295 print data.encode("hex")
296 self.sent_carrier = data
297 if "OK" in wpas_report_handover(self.received_carrier, self.sent_carrier, "RESP"):
298 success_report("P2P handover reported successfully (responder)")
300 summary("P2P handover report rejected")
303 message = nfc.ndef.Message(data);
304 sel.add_carrier(message[0], "active", message[1:])
307 for carrier in request.carriers:
310 print "Remote carrier type: " + carrier.type
311 if carrier.type == "application/vnd.wfa.wsc":
312 print "WSC carrier type match - add WSC carrier record"
314 self.received_carrier = carrier.record
315 print "Carrier record:"
317 print carrier.record.pretty()
320 data = wpas_get_handover_sel_wps()
322 print "Could not get handover select carrier record from wpa_supplicant"
324 print "Handover select carrier record from wpa_supplicant:"
325 print data.encode("hex")
326 self.sent_carrier = data
327 if "OK" in wpas_report_handover_wsc(self.received_carrier, self.sent_carrier, "RESP"):
328 success_report("WSC handover reported successfully")
330 summary("WSC handover report rejected")
333 message = nfc.ndef.Message(data);
334 sel.add_carrier(message[0], "active", message[1:])
338 print "Handover select:"
343 print str(sel).encode("hex")
345 summary("Sending handover select")
350 def clear_raw_mode():
351 import sys, tty, termios
352 global prev_tcgetattr, in_raw_mode
355 fd = sys.stdin.fileno()
356 termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr)
361 import sys, tty, termios, select
362 global prev_tcgetattr, in_raw_mode
363 fd = sys.stdin.fileno()
364 prev_tcgetattr = termios.tcgetattr(fd)
369 [i, o, e] = select.select([fd], [], [], 0.05)
371 ch = sys.stdin.read(1)
373 termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr)
378 def p2p_tag_read(tag):
380 if len(tag.ndef.message):
381 for record in tag.ndef.message:
382 print "record type " + record.type
383 if record.type == "application/vnd.wfa.wsc":
384 summary("WPS tag - send to wpa_supplicant")
385 success = wpas_tag_read(tag.ndef.message)
387 if record.type == "application/vnd.wfa.p2p":
388 summary("P2P tag - send to wpa_supplicant")
389 success = wpas_tag_read(tag.ndef.message)
395 success_report("Tag read succeeded")
400 def rdwr_connected_p2p_write(tag):
401 summary("Tag found - writing - " + str(tag))
403 tag.ndef.message = str(p2p_sel_data)
404 success_report("Tag write succeeded")
405 print "Done - remove tag"
409 continue_loop = False
410 global p2p_sel_wait_remove
411 return p2p_sel_wait_remove
413 def wps_write_p2p_handover_sel(clf, wait_remove=True):
414 print "Write P2P handover select"
415 data = wpas_get_handover_sel(tag=True)
417 summary("Could not get P2P handover select from wpa_supplicant")
420 global p2p_sel_wait_remove
421 p2p_sel_wait_remove = wait_remove
423 p2p_sel_data = nfc.ndef.HandoverSelectMessage(version="1.2")
424 message = nfc.ndef.Message(data);
425 p2p_sel_data.add_carrier(message[0], "active", message[1:])
426 print "Handover select:"
428 print p2p_sel_data.pretty()
431 print str(p2p_sel_data).encode("hex")
433 print "Touch an NFC tag"
434 clf.connect(rdwr={'on-connect': rdwr_connected_p2p_write})
437 def rdwr_connected(tag):
438 global only_one, no_wait
439 summary("Tag connected: " + str(tag))
442 print "NDEF tag: " + tag.type
444 print tag.ndef.message.pretty()
447 success = p2p_tag_read(tag)
448 if only_one and success:
450 continue_loop = False
452 summary("Not an NDEF tag - remove tag")
458 def llcp_worker(llc):
461 print "Starting handover client"
462 p2p_handover_client(llc)
467 print "Wait for handover to complete"
469 print "Wait for handover to complete - press 'i' to initiate ('w' for WPS only, 'p' for P2P only)"
471 global wait_connection
472 while not wait_connection and srv.sent_carrier is None:
473 if srv.ho_server_processing:
478 global include_wps_req, include_p2p_req
481 include_wps_req = True
482 include_p2p_req = True
484 include_wps_req = False
485 include_p2p_req = True
487 include_wps_req = True
488 include_p2p_req = False
492 print "Starting handover client"
493 p2p_handover_client(llc)
497 print "Exiting llcp_worker thread"
499 def llcp_startup(clf, llc):
500 print "Start LLCP server"
502 srv = HandoverServer(llc)
505 def llcp_connected(llc):
506 print "P2P LLCP connected"
507 global wait_connection
508 wait_connection = False
510 if not init_on_touch:
513 if init_on_touch or not no_input:
514 threading.Thread(target=llcp_worker, args=(llc,)).start()
517 def terminate_loop():
522 clf = nfc.ContactlessFrontend()
524 parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for P2P and WPS NFC operations')
525 parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO,
526 action='store_const', dest='loglevel',
527 help='verbose debug output')
528 parser.add_argument('-q', const=logging.WARNING, action='store_const',
529 dest='loglevel', help='be quiet')
530 parser.add_argument('--only-one', '-1', action='store_true',
531 help='run only one operation and exit')
532 parser.add_argument('--init-on-touch', '-I', action='store_true',
533 help='initiate handover on touch')
534 parser.add_argument('--no-wait', action='store_true',
535 help='do not wait for tag to be removed before exiting')
536 parser.add_argument('--ifname', '-i',
537 help='network interface name')
538 parser.add_argument('--no-wps-req', '-N', action='store_true',
539 help='do not include WPS carrier record in request')
540 parser.add_argument('--no-input', '-a', action='store_true',
541 help='do not use stdout input to initiate handover')
542 parser.add_argument('--tag-read-only', '-t', action='store_true',
543 help='tag read only (do not allow connection handover)')
544 parser.add_argument('--handover-only', action='store_true',
545 help='connection handover only (do not allow tag read)')
546 parser.add_argument('--freq', '-f',
547 help='forced frequency of operating channel in MHz')
548 parser.add_argument('--summary',
549 help='summary file for writing status updates')
550 parser.add_argument('--success',
551 help='success file for writing success update')
552 parser.add_argument('command', choices=['write-p2p-sel'],
554 args = parser.parse_args()
557 only_one = args.only_one
560 no_wait = args.no_wait
563 force_freq = args.freq
565 logging.basicConfig(level=args.loglevel)
568 init_on_touch = args.init_on_touch
573 print "Selected ifname " + ifname
576 global include_wps_req
577 include_wps_req = False
581 summary_file = args.summary
585 success_file = args.success
591 clf = nfc.ContactlessFrontend()
592 global wait_connection
595 if not clf.open("usb"):
596 print "Could not open connection with an NFC device"
599 if args.command == "write-p2p-sel":
600 wps_write_p2p_handover_sel(clf, wait_remove=not args.no_wait)
605 print "Waiting for a tag or peer to be touched"
606 wait_connection = True
608 if args.tag_read_only:
609 if not clf.connect(rdwr={'on-connect': rdwr_connected}):
611 elif args.handover_only:
612 if not clf.connect(llcp={'on-startup': llcp_startup,
613 'on-connect': llcp_connected},
614 terminate=terminate_loop):
617 if not clf.connect(rdwr={'on-connect': rdwr_connected},
618 llcp={'on-startup': llcp_startup,
619 'on-connect': llcp_connected},
620 terminate=terminate_loop):
623 print "clf.connect failed"
626 if only_one and srv and srv.success:
629 except KeyboardInterrupt:
636 if __name__ == '__main__':