diff options
Diffstat (limited to 'wpa_supplicant/examples')
28 files changed, 0 insertions, 5141 deletions
diff --git a/wpa_supplicant/examples/60_wpa_supplicant b/wpa_supplicant/examples/60_wpa_supplicant deleted file mode 100755 index 39bd8e09b589..000000000000 --- a/wpa_supplicant/examples/60_wpa_supplicant +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -# /etc/pm/sleep.d/60_wpa_supplicant -# Action script to notify wpa_supplicant of pm-action events. - -PATH=/sbin:/usr/sbin:/bin:/usr/bin - -WPACLI=wpa_cli - -case "$1" in - suspend|hibernate) - $WPACLI suspend - ;; - resume|thaw) - $WPACLI resume - ;; -esac - -exit 0 diff --git a/wpa_supplicant/examples/dbus-listen-preq.py b/wpa_supplicant/examples/dbus-listen-preq.py deleted file mode 100755 index 337519f4e927..000000000000 --- a/wpa_supplicant/examples/dbus-listen-preq.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python - -from __future__ import print_function -import dbus -import sys -import time -import gobject -from dbus.mainloop.glib import DBusGMainLoop - -WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1" -WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface" - -def usage(): - print("Usage: %s <ifname>" % sys.argv[0]) - print("Press Ctrl-C to stop") - -def ProbeRequest(args): - if 'addr' in args: - print('%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['addr']), - end=' ') - if 'dst' in args: - print('-> %.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['dst']), - end=' ') - if 'bssid' in args: - print('(bssid %.2x:%.2x:%.2x:%.2x:%.2x:%.2x)' % tuple(args['dst']), - end=' ') - if 'signal' in args: - print('signal:%d' % args['signal'], end=' ') - if 'ies' in args: - print('have IEs (%d bytes)' % len(args['ies']), end=' ') - print('') - -if __name__ == "__main__": - global bus - global wpas_obj - global if_obj - global p2p_iface - - dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) - - bus = dbus.SystemBus() - wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH) - - # Print list of i/f if no one is specified - if (len(sys.argv) < 2) : - usage() - sys.exit(0) - - wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE) - - ifname = sys.argv[1] - - path = wpas.GetInterface(ifname) - - if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) - iface = dbus.Interface(if_obj, WPAS_DBUS_INTERFACES_INTERFACE) - - bus.add_signal_receiver(ProbeRequest, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="ProbeRequest") - - iface.SubscribeProbeReq() - - gobject.MainLoop().run() diff --git a/wpa_supplicant/examples/dpp-nfc.py b/wpa_supplicant/examples/dpp-nfc.py deleted file mode 100755 index 8e865f3fcd33..000000000000 --- a/wpa_supplicant/examples/dpp-nfc.py +++ /dev/null @@ -1,1186 +0,0 @@ -#!/usr/bin/python3 -# -# Example nfcpy to wpa_supplicant wrapper for DPP NFC operations -# Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi> -# Copyright (c) 2019-2020, The Linux Foundation -# -# This software may be distributed under the terms of the BSD license. -# See README for more details. - -import binascii -import errno -import os -import struct -import sys -import time -import threading -import argparse - -import nfc -import ndef - -import logging - -scriptsdir = os.path.dirname(os.path.realpath(sys.modules[__name__].__file__)) -sys.path.append(os.path.join(scriptsdir, '..', '..', 'wpaspy')) -import wpaspy - -wpas_ctrl = '/var/run/wpa_supplicant' -ifname = None -init_on_touch = False -in_raw_mode = False -prev_tcgetattr = 0 -no_input = False -continue_loop = True -terminate_now = False -summary_file = None -success_file = None -netrole = None -operation_success = False -mutex = threading.Lock() - -C_NORMAL = '\033[0m' -C_RED = '\033[91m' -C_GREEN = '\033[92m' -C_YELLOW = '\033[93m' -C_BLUE = '\033[94m' -C_MAGENTA = '\033[95m' -C_CYAN = '\033[96m' - -def summary(txt, color=None): - with mutex: - if color: - print(color + txt + C_NORMAL) - else: - print(txt) - if summary_file: - with open(summary_file, 'a') as f: - f.write(txt + "\n") - -def success_report(txt): - summary(txt) - if success_file: - with open(success_file, 'a') as f: - f.write(txt + "\n") - -def wpas_connect(): - ifaces = [] - if os.path.isdir(wpas_ctrl): - try: - ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] - except OSError as error: - summary("Could not find wpa_supplicant: %s", str(error)) - return None - - if len(ifaces) < 1: - summary("No wpa_supplicant control interface found") - return None - - for ctrl in ifaces: - if ifname and ifname not in ctrl: - continue - if os.path.basename(ctrl).startswith("p2p-dev-"): - # skip P2P management interface - continue - try: - summary("Trying to use control interface " + ctrl) - wpas = wpaspy.Ctrl(ctrl) - return wpas - except Exception as e: - pass - summary("Could not connect to wpa_supplicant") - return None - -def dpp_nfc_uri_process(uri): - wpas = wpas_connect() - if wpas is None: - return False - peer_id = wpas.request("DPP_NFC_URI " + uri) - if "FAIL" in peer_id: - summary("Could not parse DPP URI from NFC URI record", color=C_RED) - return False - peer_id = int(peer_id) - summary("peer_id=%d for URI from NFC Tag: %s" % (peer_id, uri)) - cmd = "DPP_AUTH_INIT peer=%d" % peer_id - global enrollee_only, configurator_only, config_params - if enrollee_only: - cmd += " role=enrollee" - elif configurator_only: - cmd += " role=configurator" - if config_params: - cmd += " " + config_params - summary("Initiate DPP authentication: " + cmd) - res = wpas.request(cmd) - if "OK" not in res: - summary("Failed to initiate DPP Authentication", color=C_RED) - return False - summary("DPP Authentication initiated") - return True - -def dpp_hs_tag_read(record): - wpas = wpas_connect() - if wpas is None: - return False - summary(record) - if len(record.data) < 5: - summary("Too short DPP HS", color=C_RED) - return False - if record.data[0] != 0: - summary("Unexpected URI Identifier Code", color=C_RED) - return False - uribuf = record.data[1:] - try: - uri = uribuf.decode() - except: - summary("Invalid URI payload", color=C_RED) - return False - summary("URI: " + uri) - if not uri.startswith("DPP:"): - summary("Not a DPP URI", color=C_RED) - return False - return dpp_nfc_uri_process(uri) - -def get_status(wpas, extra=None): - if extra: - extra = "-" + extra - else: - extra = "" - res = wpas.request("STATUS" + extra) - lines = res.splitlines() - vals = dict() - for l in lines: - try: - [name, value] = l.split('=', 1) - except ValueError: - summary("Ignore unexpected status line: %s" % l) - continue - vals[name] = value - return vals - -def get_status_field(wpas, field, extra=None): - vals = get_status(wpas, extra) - if field in vals: - return vals[field] - return None - -def own_addr(wpas): - addr = get_status_field(wpas, "address") - if addr is None: - addr = get_status_field(wpas, "bssid[0]") - return addr - -def dpp_bootstrap_gen(wpas, type="qrcode", chan=None, mac=None, info=None, - curve=None, key=None): - cmd = "DPP_BOOTSTRAP_GEN type=" + type - if chan: - cmd += " chan=" + chan - if mac: - if mac is True: - mac = own_addr(wpas) - if mac is None: - summary("Could not determine local MAC address for bootstrap info") - else: - cmd += " mac=" + mac.replace(':', '') - if info: - cmd += " info=" + info - if curve: - cmd += " curve=" + curve - if key: - cmd += " key=" + key - res = wpas.request(cmd) - if "FAIL" in res: - raise Exception("Failed to generate bootstrapping info") - return int(res) - -def dpp_start_listen(wpas, freq): - if get_status_field(wpas, "bssid[0]"): - summary("Own AP freq: %s MHz" % str(get_status_field(wpas, "freq"))) - if get_status_field(wpas, "beacon_set", extra="DRIVER") is None: - summary("Enable beaconing to have radio ready for RX") - wpas.request("DISABLE") - wpas.request("SET start_disabled 0") - wpas.request("ENABLE") - cmd = "DPP_LISTEN %d" % freq - global enrollee_only - global configurator_only - if enrollee_only: - cmd += " role=enrollee" - elif configurator_only: - cmd += " role=configurator" - global netrole - if netrole: - cmd += " netrole=" + netrole - summary(cmd) - res = wpas.request(cmd) - if "OK" not in res: - summary("Failed to start DPP listen", color=C_RED) - return False - return True - -def wpas_get_nfc_uri(start_listen=True, pick_channel=False, chan_override=None): - listen_freq = 2412 - wpas = wpas_connect() - if wpas is None: - return None - global own_id, chanlist - if chan_override: - chan = chan_override - else: - chan = chanlist - if chan and chan.startswith("81/"): - listen_freq = int(chan[3:].split(',')[0]) * 5 + 2407 - if chan is None and get_status_field(wpas, "bssid[0]"): - freq = get_status_field(wpas, "freq") - if freq: - freq = int(freq) - if freq >= 2412 and freq <= 2462: - chan = "81/%d" % ((freq - 2407) / 5) - summary("Use current AP operating channel (%d MHz) as the URI channel list (%s)" % (freq, chan)) - listen_freq = freq - if chan is None and pick_channel: - chan = "81/6" - summary("Use channel 2437 MHz since no other preference provided") - listen_freq = 2437 - own_id = dpp_bootstrap_gen(wpas, type="nfc-uri", chan=chan, mac=True) - res = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % own_id).rstrip() - if "FAIL" in res: - return None - if start_listen: - if not dpp_start_listen(wpas, listen_freq): - raise Exception("Failed to start listen operation on %d MHz" % listen_freq) - return res - -def wpas_report_handover_req(uri): - wpas = wpas_connect() - if wpas is None: - return None - global own_id - cmd = "DPP_NFC_HANDOVER_REQ own=%d uri=%s" % (own_id, uri) - return wpas.request(cmd) - -def wpas_report_handover_sel(uri): - wpas = wpas_connect() - if wpas is None: - return None - global own_id - cmd = "DPP_NFC_HANDOVER_SEL own=%d uri=%s" % (own_id, uri) - return wpas.request(cmd) - -def dpp_handover_client(handover, alt=False): - summary("About to start run_dpp_handover_client (alt=%s)" % str(alt)) - if alt: - handover.i_m_selector = False - run_dpp_handover_client(handover, alt) - summary("Done run_dpp_handover_client (alt=%s)" % str(alt)) - -def run_client_alt(handover, alt): - if handover.start_client_alt and not alt: - handover.start_client_alt = False - summary("Try to send alternative handover request") - dpp_handover_client(handover, alt=True) - -class HandoverClient(nfc.handover.HandoverClient): - def __init__(self, handover, llc): - super(HandoverClient, self).__init__(llc) - self.handover = handover - - def recv_records(self, timeout=None): - msg = self.recv_octets(timeout) - if msg is None: - return None - records = list(ndef.message_decoder(msg, 'relax')) - if records and records[0].type == 'urn:nfc:wkt:Hs': - summary("Handover client received message '{0}'".format(records[0].type)) - return list(ndef.message_decoder(msg, 'relax')) - summary("Handover client received invalid message: %s" + binascii.hexlify(msg)) - return None - - def recv_octets(self, timeout=None): - start = time.time() - msg = bytearray() - while True: - poll_timeout = 0.1 if timeout is None or timeout > 0.1 else timeout - if not self.socket.poll('recv', poll_timeout): - if timeout: - timeout -= time.time() - start - if timeout <= 0: - return None - start = time.time() - continue - try: - r = self.socket.recv() - if r is None: - return None - msg += r - except TypeError: - return b'' - try: - list(ndef.message_decoder(msg, 'strict', {})) - return bytes(msg) - except ndef.DecodeError: - if timeout: - timeout -= time.time() - start - if timeout <= 0: - return None - start = time.time() - continue - return None - -def run_dpp_handover_client(handover, alt=False): - chan_override = None - if alt: - chan_override = handover.altchanlist - handover.alt_proposal_used = True - global test_uri, test_alt_uri - if test_uri: - summary("TEST MODE: Using specified URI (alt=%s)" % str(alt)) - uri = test_alt_uri if alt else test_uri - else: - uri = wpas_get_nfc_uri(start_listen=False, chan_override=chan_override) - if uri is None: - summary("Cannot start handover client - no bootstrap URI available", - color=C_RED) - return - handover.my_uri = uri - uri = ndef.UriRecord(uri) - summary("NFC URI record for DPP: " + str(uri)) - carrier = ndef.Record('application/vnd.wfa.dpp', 'A', uri.data) - global test_crn - if test_crn: - prev, = struct.unpack('>H', test_crn) - summary("TEST MODE: Use specified crn %d" % prev) - crn = test_crn - test_crn = struct.pack('>H', prev + 0x10) - else: - crn = os.urandom(2) - hr = ndef.HandoverRequestRecord(version="1.4", crn=crn) - hr.add_alternative_carrier('active', carrier.name) - message = [hr, carrier] - summary("NFC Handover Request message for DPP: " + str(message)) - - if handover.peer_crn is not None and not alt: - summary("NFC handover request from peer was already received - do not send own") - return - if handover.client: - summary("Use already started handover client") - client = handover.client - else: - summary("Start handover client") - client = HandoverClient(handover, handover.llc) - try: - summary("Trying to initiate NFC connection handover") - client.connect() - summary("Connected for handover") - except nfc.llcp.ConnectRefused: - summary("Handover connection refused") - client.close() - return - except Exception as e: - summary("Other exception: " + str(e)) - client.close() - return - handover.client = client - - if handover.peer_crn is not None and not alt: - summary("NFC handover request from peer was already received - do not send own") - return - - summary("Sending handover request") - - handover.my_crn_ready = True - - if not client.send_records(message): - handover.my_crn_ready = False - summary("Failed to send handover request", color=C_RED) - run_client_alt(handover, alt) - return - - handover.my_crn, = struct.unpack('>H', crn) - - summary("Receiving handover response") - try: - start = time.time() - message = client.recv_records(timeout=3.0) - end = time.time() - summary("Received {} record(s) in {} seconds".format(len(message) if message is not None else -1, end - start)) - except Exception as e: - # This is fine if we are the handover selector - if handover.hs_sent: - summary("Client receive failed as expected since I'm the handover server: %s" % str(e)) - 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)) - else: - summary("Client receive failed: %s" % str(e), color=C_RED) - message = None - if message is None: - if handover.hs_sent: - summary("No response received as expected since I'm the handover server") - elif handover.alt_proposal_used and not alt: - summary("No response received for initial proposal as expected since alternative proposal was also used") - elif handover.try_own and not alt: - summary("No response received for initial proposal as expected since alternative proposal will also be sent") - else: - summary("No response received", color=C_RED) - run_client_alt(handover, alt) - return - summary("Received message: " + str(message)) - if len(message) < 1 or \ - not isinstance(message[0], ndef.HandoverSelectRecord): - summary("Response was not Hs - received: " + message.type) - return - - summary("Received handover select message") - summary("alternative carriers: " + str(message[0].alternative_carriers)) - if handover.i_m_selector: - summary("Ignore the received select since I'm the handover selector") - run_client_alt(handover, alt) - return - - if handover.alt_proposal_used and not alt: - summary("Ignore received handover select for the initial proposal since alternative proposal was sent") - client.close() - return - - dpp_found = False - for carrier in message: - if isinstance(carrier, ndef.HandoverSelectRecord): - continue - summary("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.dpp": - if len(carrier.data) == 0 or carrier.data[0] != 0: - summary("URI Identifier Code 'None' not seen", color=C_RED) - continue - summary("DPP carrier type match - send to wpa_supplicant") - dpp_found = True - uri = carrier.data[1:].decode("utf-8") - summary("DPP URI: " + uri) - handover.peer_uri = uri - if test_uri: - summary("TEST MODE: Fake processing") - break - res = wpas_report_handover_sel(uri) - if res is None or "FAIL" in res: - summary("DPP handover report rejected", color=C_RED) - break - - success_report("DPP handover reported successfully (initiator)") - summary("peer_id=" + res) - peer_id = int(res) - wpas = wpas_connect() - if wpas is None: - break - - global enrollee_only - global config_params - if enrollee_only: - extra = " role=enrollee" - elif config_params: - extra = " role=configurator " + config_params - else: - # TODO: Single Configurator instance - res = wpas.request("DPP_CONFIGURATOR_ADD") - if "FAIL" in res: - summary("Failed to initiate Configurator", color=C_RED) - break - conf_id = int(res) - extra = " conf=sta-dpp configurator=%d" % conf_id - global own_id - summary("Initiate DPP authentication") - cmd = "DPP_AUTH_INIT peer=%d own=%d" % (peer_id, own_id) - cmd += extra - res = wpas.request(cmd) - if "FAIL" in res: - summary("Failed to initiate DPP authentication", color=C_RED) - break - - if not dpp_found and handover.no_alt_proposal: - summary("DPP carrier not seen in response - do not allow alternative proposal anymore") - elif not dpp_found: - summary("DPP carrier not seen in response - allow peer to initiate a new handover with different parameters") - handover.alt_proposal = True - handover.my_crn_ready = False - handover.my_crn = None - handover.peer_crn = None - handover.hs_sent = False - summary("Returning from dpp_handover_client") - return - - summary("Remove peer") - handover.close() - summary("Done with handover") - global only_one - if only_one: - print("only_one -> stop loop") - global continue_loop - continue_loop = False - - global no_wait - if no_wait or only_one: - summary("Trying to exit..") - global terminate_now - terminate_now = True - - summary("Returning from dpp_handover_client") - -class HandoverServer(nfc.handover.HandoverServer): - def __init__(self, handover, llc): - super(HandoverServer, self).__init__(llc) - self.sent_carrier = None - self.ho_server_processing = False - self.success = False - self.llc = llc - self.handover = handover - - def serve(self, socket): - peer_sap = socket.getpeername() - summary("Serving handover client on remote sap {0}".format(peer_sap)) - send_miu = socket.getsockopt(nfc.llcp.SO_SNDMIU) - try: - while socket.poll("recv"): - req = bytearray() - while socket.poll("recv"): - r = socket.recv() - if r is None: - return None - summary("Received %d octets" % len(r)) - req += r - if len(req) == 0: - continue - try: - list(ndef.message_decoder(req, 'strict', {})) - except ndef.DecodeError: - continue - summary("Full message received") - resp = self._process_request_data(req) - if resp is None or len(resp) == 0: - summary("No handover select to send out - wait for a possible alternative handover request") - handover.alt_proposal = True - req = bytearray() - continue - - for offset in range(0, len(resp), send_miu): - if not socket.send(resp[offset:offset + send_miu]): - summary("Failed to send handover select - connection closed") - return - summary("Sent out full handover select") - if handover.terminate_on_hs_send_completion: - handover.delayed_exit() - - except nfc.llcp.Error as e: - global terminate_now - summary("HandoverServer exception: %s" % e, - color=None if e.errno == errno.EPIPE or terminate_now else C_RED) - finally: - socket.close() - summary("Handover serve thread exiting") - - def process_handover_request_message(self, records): - handover = self.handover - self.ho_server_processing = True - global in_raw_mode - was_in_raw_mode = in_raw_mode - clear_raw_mode() - if was_in_raw_mode: - print("\n") - summary("HandoverServer - request received: " + str(records)) - - for carrier in records: - if not isinstance(carrier, ndef.HandoverRequestRecord): - continue - if carrier.collision_resolution_number: - handover.peer_crn = carrier.collision_resolution_number - summary("peer_crn: %d" % handover.peer_crn) - - 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") - for i in range(10): - if handover.my_crn is not None: - break - time.sleep(0.01) - if handover.my_crn is not None: - summary("my_crn: %d" % handover.my_crn) - - if handover.my_crn is not None and handover.peer_crn is not None: - if handover.my_crn == handover.peer_crn: - summary("Same crn used - automatic collision resolution failed") - # TODO: Should generate a new Handover Request message - return '' - if ((handover.my_crn & 1) == (handover.peer_crn & 1) and \ - 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") - handover.i_m_selector = True - else: - summary("Peer is the Handover Selector device") - summary("Ignore the received request.") - return '' - - hs = ndef.HandoverSelectRecord('1.4') - sel = [hs] - - found = False - - for carrier in records: - if isinstance(carrier, ndef.HandoverRequestRecord): - continue - summary("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.dpp": - summary("DPP carrier type match - add DPP carrier record") - if len(carrier.data) == 0 or carrier.data[0] != 0: - summary("URI Identifier Code 'None' not seen", color=C_RED) - continue - uri = carrier.data[1:].decode("utf-8") - summary("Received DPP URI: " + uri) - - global test_uri, test_alt_uri - if test_uri: - summary("TEST MODE: Using specified URI") - data = test_sel_uri if test_sel_uri else test_uri - elif handover.alt_proposal and handover.altchanlist: - summary("Use alternative channel list while processing alternative proposal from peer") - data = wpas_get_nfc_uri(start_listen=False, - chan_override=handover.altchanlist, - pick_channel=True) - else: - data = wpas_get_nfc_uri(start_listen=False, - pick_channel=True) - summary("Own URI (pre-processing): %s" % data) - - if test_uri: - summary("TEST MODE: Fake processing") - res = "OK" - data += " [%s]" % uri - else: - res = wpas_report_handover_req(uri) - if res is None or "FAIL" in res: - summary("DPP handover request processing failed", - color=C_RED) - if handover.altchanlist: - data = wpas_get_nfc_uri(start_listen=False, - chan_override=handover.altchanlist) - summary("Own URI (try another channel list): %s" % data) - continue - - if test_alt_uri: - summary("TEST MODE: Reject initial proposal") - continue - - found = True - - if not test_uri: - wpas = wpas_connect() - if wpas is None: - continue - global own_id - data = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % own_id).rstrip() - if "FAIL" in data: - continue - summary("Own URI (post-processing): %s" % data) - handover.my_uri = data - handover.peer_uri = uri - uri = ndef.UriRecord(data) - summary("Own bootstrapping NFC URI record: " + str(uri)) - - if not test_uri: - info = wpas.request("DPP_BOOTSTRAP_INFO %d" % own_id) - freq = None - for line in info.splitlines(): - if line.startswith("use_freq="): - freq = int(line.split('=')[1]) - if freq is None or freq == 0: - summary("No channel negotiated over NFC - use channel 6") - freq = 2437 - else: - summary("Negotiated channel: %d MHz" % freq) - if not dpp_start_listen(wpas, freq): - break - - carrier = ndef.Record('application/vnd.wfa.dpp', 'A', uri.data) - summary("Own DPP carrier record: " + str(carrier)) - hs.add_alternative_carrier('active', carrier.name) - sel = [hs, carrier] - break - - summary("Sending handover select: " + str(sel)) - if found: - summary("Handover completed successfully") - handover.terminate_on_hs_send_completion = True - self.success = True - handover.hs_sent = True - handover.i_m_selector = True - elif handover.no_alt_proposal: - summary("Do not try alternative proposal anymore - handover failed", - color=C_RED) - handover.hs_sent = True - else: - summary("Try to initiate with alternative parameters") - handover.try_own = True - handover.hs_sent = False - handover.no_alt_proposal = True - if handover.client_thread: - handover.start_client_alt = True - else: - handover.client_thread = threading.Thread(target=llcp_worker, - args=(self.llc, True)) - handover.client_thread.start() - return sel - -def clear_raw_mode(): - import sys, tty, termios - global prev_tcgetattr, in_raw_mode - if not in_raw_mode: - return - fd = sys.stdin.fileno() - termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr) - in_raw_mode = False - -def getch(): - import sys, tty, termios, select - global prev_tcgetattr, in_raw_mode - fd = sys.stdin.fileno() - prev_tcgetattr = termios.tcgetattr(fd) - ch = None - try: - tty.setraw(fd) - in_raw_mode = True - [i, o, e] = select.select([fd], [], [], 0.05) - if i: - ch = sys.stdin.read(1) - finally: - termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr) - in_raw_mode = False - return ch - -def dpp_tag_read(tag): - success = False - for record in tag.ndef.records: - summary(record) - summary("record type " + record.type) - if record.type == "application/vnd.wfa.dpp": - summary("DPP HS tag - send to wpa_supplicant") - success = dpp_hs_tag_read(record) - break - if isinstance(record, ndef.UriRecord): - summary("URI record: uri=" + record.uri) - summary("URI record: iri=" + record.iri) - if record.iri.startswith("DPP:"): - summary("DPP URI") - if not dpp_nfc_uri_process(record.iri): - break - success = True - else: - summary("Ignore unknown URI") - break - - if success: - success_report("Tag read succeeded") - - return success - -def rdwr_connected_write_tag(tag): - summary("Tag found - writing - " + str(tag)) - if not tag.ndef: - summary("Not a formatted NDEF tag", color=C_RED) - return - if not tag.ndef.is_writeable: - summary("Not a writable tag", color=C_RED) - return - global dpp_tag_data - if tag.ndef.capacity < len(dpp_tag_data): - summary("Not enough room for the message") - return - try: - tag.ndef.records = dpp_tag_data - except ValueError as e: - summary("Writing the tag failed: %s" % str(e), color=C_RED) - return - success_report("Tag write succeeded") - summary("Tag writing completed - remove tag", color=C_GREEN) - global only_one, operation_success - operation_success = True - if only_one: - global continue_loop - continue_loop = False - global dpp_sel_wait_remove - return dpp_sel_wait_remove - -def write_nfc_uri(clf, wait_remove=True): - summary("Write NFC URI record") - data = wpas_get_nfc_uri() - if data is None: - summary("Could not get NFC URI from wpa_supplicant", color=C_RED) - return - - global dpp_sel_wait_remove - dpp_sel_wait_remove = wait_remove - summary("URI: %s" % data) - uri = ndef.UriRecord(data) - summary(uri) - - summary("Touch an NFC tag to write URI record", color=C_CYAN) - global dpp_tag_data - dpp_tag_data = [uri] - clf.connect(rdwr={'on-connect': rdwr_connected_write_tag}) - -def write_nfc_hs(clf, wait_remove=True): - summary("Write NFC Handover Select record on a tag") - data = wpas_get_nfc_uri() - if data is None: - summary("Could not get NFC URI from wpa_supplicant", color=C_RED) - return - - global dpp_sel_wait_remove - dpp_sel_wait_remove = wait_remove - summary("URI: %s" % data) - uri = ndef.UriRecord(data) - summary(uri) - carrier = ndef.Record('application/vnd.wfa.dpp', 'A', uri.data) - hs = ndef.HandoverSelectRecord('1.4') - hs.add_alternative_carrier('active', carrier.name) - summary(hs) - summary(carrier) - - summary("Touch an NFC tag to write HS record", color=C_CYAN) - global dpp_tag_data - dpp_tag_data = [hs, carrier] - summary(dpp_tag_data) - clf.connect(rdwr={'on-connect': rdwr_connected_write_tag}) - -def rdwr_connected(tag): - global only_one, no_wait - summary("Tag connected: " + str(tag)) - - if tag.ndef: - summary("NDEF tag: " + tag.type) - summary(tag.ndef.records) - success = dpp_tag_read(tag) - if only_one and success: - global continue_loop - continue_loop = False - else: - summary("Not an NDEF tag - remove tag", color=C_RED) - return True - - return not no_wait - -def llcp_worker(llc, try_alt): - global handover - print("Start of llcp_worker()") - if try_alt: - summary("Starting handover client (try_alt)") - dpp_handover_client(handover, alt=True) - summary("Exiting llcp_worker thread (try_alt)") - return - global init_on_touch - if init_on_touch: - summary("Starting handover client (init_on_touch)") - dpp_handover_client(handover) - summary("Exiting llcp_worker thread (init_on_touch)") - return - - global no_input - if no_input: - summary("Wait for handover to complete") - else: - print("Wait for handover to complete - press 'i' to initiate") - while not handover.wait_connection and handover.srv.sent_carrier is None: - if handover.try_own: - handover.try_own = False - summary("Try to initiate another handover with own parameters") - handover.my_crn_ready = False - handover.my_crn = None - handover.peer_crn = None - handover.hs_sent = False - dpp_handover_client(handover, alt=True) - summary("Exiting llcp_worker thread (retry with own parameters)") - return - if handover.srv.ho_server_processing: - time.sleep(0.025) - elif no_input: - time.sleep(0.5) - else: - res = getch() - if res != 'i': - continue - clear_raw_mode() - summary("Starting handover client") - dpp_handover_client(handover) - summary("Exiting llcp_worker thread (manual init)") - return - - global in_raw_mode - was_in_raw_mode = in_raw_mode - clear_raw_mode() - if was_in_raw_mode: - print("\r") - summary("Exiting llcp_worker thread") - -class ConnectionHandover(): - def __init__(self): - self.client = None - self.client_thread = None - self.reset() - self.exit_thread = None - - 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.i_m_selector = False - self.start_client_alt = False - self.terminate_on_hs_send_completion = False - self.try_own = False - self.my_uri = None - self.peer_uri = None - self.connected = False - self.alt_proposal = 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 run_delayed_exit(self): - summary("Trying to exit (delayed)..") - time.sleep(0.25) - summary("Trying to exit (after wait)..") - global terminate_now - terminate_now = True - - def delayed_exit(self): - global only_one - if only_one: - self.exit_thread = threading.Thread(target=self.run_delayed_exit) - self.exit_thread.start() - -def llcp_startup(llc): - global handover - handover.start_handover_server(llc) - return llc - -def llcp_connected(llc): - summary("P2P LLCP connected") - global handover - handover.connected = True - handover.srv.start() - if init_on_touch or not no_input: - handover.client_thread = threading.Thread(target=llcp_worker, - args=(llc, False)) - handover.client_thread.start() - return True - -def llcp_release(llc): - summary("LLCP release") - global handover - handover.close() - return True - -def terminate_loop(): - global terminate_now - return terminate_now - -def main(): - clf = nfc.ContactlessFrontend() - - parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for DPP NFC operations') - parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO, - action='store_const', dest='loglevel', - help='verbose debug output') - parser.add_argument('-q', const=logging.WARNING, action='store_const', - dest='loglevel', help='be quiet') - parser.add_argument('--only-one', '-1', action='store_true', - help='run only one operation and exit') - parser.add_argument('--init-on-touch', '-I', action='store_true', - help='initiate handover on touch') - parser.add_argument('--no-wait', action='store_true', - help='do not wait for tag to be removed before exiting') - parser.add_argument('--ifname', '-i', - help='network interface name') - parser.add_argument('--no-input', '-a', action='store_true', - help='do not use stdout input to initiate handover') - parser.add_argument('--tag-read-only', '-t', action='store_true', - help='tag read only (do not allow connection handover)') - parser.add_argument('--handover-only', action='store_true', - help='connection handover only (do not allow tag read)') - parser.add_argument('--enrollee', action='store_true', - help='run as Enrollee-only') - parser.add_argument('--configurator', action='store_true', - help='run as Configurator-only') - parser.add_argument('--config-params', default='', - help='configurator parameters') - parser.add_argument('--ctrl', default='/var/run/wpa_supplicant', - help='wpa_supplicant/hostapd control interface') - parser.add_argument('--summary', - help='summary file for writing status updates') - parser.add_argument('--success', - help='success file for writing success update') - parser.add_argument('--device', default='usb', help='NFC device to open') - parser.add_argument('--chan', default=None, help='channel list') - parser.add_argument('--altchan', default=None, help='alternative channel list') - parser.add_argument('--netrole', default=None, help='netrole for Enrollee') - parser.add_argument('--test-uri', default=None, - help='test mode: initial URI') - parser.add_argument('--test-alt-uri', default=None, - help='test mode: alternative URI') - parser.add_argument('--test-sel-uri', default=None, - help='test mode: handover select URI') - parser.add_argument('--test-crn', default=None, - help='test mode: hardcoded crn') - parser.add_argument('command', choices=['write-nfc-uri', - 'write-nfc-hs'], - nargs='?') - args = parser.parse_args() - summary(args) - - global handover - handover = ConnectionHandover() - - global only_one - only_one = args.only_one - - global no_wait - no_wait = args.no_wait - - global chanlist, netrole, test_uri, test_alt_uri, test_sel_uri - global test_crn - chanlist = args.chan - handover.altchanlist = args.altchan - netrole = args.netrole - test_uri = args.test_uri - test_alt_uri = args.test_alt_uri - test_sel_uri = args.test_sel_uri - if args.test_crn: - test_crn = struct.pack('>H', int(args.test_crn)) - else: - test_crn = None - - logging.basicConfig(level=args.loglevel) - for l in ['nfc.clf.rcs380', - 'nfc.clf.transport', - 'nfc.clf.device', - 'nfc.clf.__init__', - 'nfc.llcp', - 'nfc.handover']: - log = logging.getLogger(l) - log.setLevel(args.loglevel) - - global init_on_touch - init_on_touch = args.init_on_touch - - global enrollee_only - enrollee_only = args.enrollee - - global configurator_only - configurator_only = args.configurator - - global config_params - config_params = args.config_params - - if args.ifname: - global ifname - ifname = args.ifname - summary("Selected ifname " + ifname) - - if args.ctrl: - global wpas_ctrl - wpas_ctrl = args.ctrl - - if args.summary: - global summary_file - summary_file = args.summary - - if args.success: - global success_file - success_file = args.success - - if args.no_input: - global no_input - no_input = True - - clf = nfc.ContactlessFrontend() - - try: - if not clf.open(args.device): - summary("Could not open connection with an NFC device", color=C_RED) - raise SystemExit(1) - - if args.command == "write-nfc-uri": - write_nfc_uri(clf, wait_remove=not args.no_wait) - if not operation_success: - raise SystemExit(1) - raise SystemExit - - if args.command == "write-nfc-hs": - write_nfc_hs(clf, wait_remove=not args.no_wait) - if not operation_success: - raise SystemExit(1) - raise SystemExit - - global continue_loop - while continue_loop: - global in_raw_mode - was_in_raw_mode = in_raw_mode - clear_raw_mode() - if was_in_raw_mode: - print("\r") - if args.handover_only: - summary("Waiting a peer to be touched", color=C_MAGENTA) - elif args.tag_read_only: - summary("Waiting for a tag to be touched", color=C_BLUE) - else: - summary("Waiting for a tag or peer to be touched", - color=C_GREEN) - handover.wait_connection = True - try: - if args.tag_read_only: - if not clf.connect(rdwr={'on-connect': rdwr_connected}): - break - elif args.handover_only: - if not clf.connect(llcp={'on-startup': llcp_startup, - 'on-connect': llcp_connected, - 'on-release': llcp_release}, - terminate=terminate_loop): - break - else: - if not clf.connect(rdwr={'on-connect': rdwr_connected}, - llcp={'on-startup': llcp_startup, - 'on-connect': llcp_connected, - 'on-release': llcp_release}, - terminate=terminate_loop): - break - except Exception as e: - summary("clf.connect failed: " + str(e)) - break - - if only_one and handover.connected: - role = "selector" if handover.i_m_selector else "requestor" - summary("Connection handover result: I'm the %s" % role, - color=C_YELLOW) - if handover.peer_uri: - summary("Peer URI: " + handover.peer_uri, color=C_YELLOW) - if handover.my_uri: - summary("My URI: " + handover.my_uri, color=C_YELLOW) - if not (handover.peer_uri and handover.my_uri): - summary("Negotiated connection handover failed", - color=C_YELLOW) - break - - except KeyboardInterrupt: - raise SystemExit - finally: - clf.close() - - raise SystemExit - -if __name__ == '__main__': - main() diff --git a/wpa_supplicant/examples/dpp-qrcode.py b/wpa_supplicant/examples/dpp-qrcode.py deleted file mode 100755 index b468d15cf9cd..000000000000 --- a/wpa_supplicant/examples/dpp-qrcode.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/python -# -# Example Android logcat to wpa_supplicant wrapper for QR Code scans -# Copyright (c) 2017, Qualcomm Atheros, Inc. -# -# This software may be distributed under the terms of the BSD license. -# See README for more details. - -import os -import sys -import argparse -import logging -import qrcode - -scriptsdir = os.path.dirname(os.path.realpath(sys.modules[__name__].__file__)) -sys.path.append(os.path.join(scriptsdir, '..', '..', 'wpaspy')) - -import wpaspy - -wpas_ctrl = '/var/run/wpa_supplicant' - -def wpas_connect(): - ifaces = [] - if os.path.isdir(wpas_ctrl): - try: - ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] - except OSError as error: - print("Could not find wpa_supplicant: ", error) - return None - - if len(ifaces) < 1: - print("No wpa_supplicant control interface found") - return None - - for ctrl in ifaces: - try: - wpas = wpaspy.Ctrl(ctrl) - return wpas - except Exception as e: - pass - return None - -def dpp_logcat(): - for line in iter(sys.stdin.readline, ''): - if "ResultHandler: Launching intent: Intent" not in line: - continue - if "act=android.intent.action.VIEW" not in line: - continue - uri = None - for val in line.split(' '): - if val.startswith('dat='): - uri = val.split('=', 1)[1] - break - if not uri: - continue - if not uri.startswith('DPP:'): - continue - print("Found DPP bootstrap info URI:") - print(uri) - wpas = wpas_connect() - if not wpas: - print("Could not connect to wpa_supplicant") - print('') - continue - res = wpas.request("DPP_QR_CODE " + uri); - try: - id = int(res) - except ValueError: - print("QR Code URI rejected") - continue - print("QR Code URI accepted - ID=%d" % id) - print(wpas.request("DPP_BOOTSTRAP_INFO %d" % id)) - del wpas - -def dpp_display(curve): - wpas = wpas_connect() - if not wpas: - print("Could not connect to wpa_supplicant") - return - res = wpas.request("STATUS") - addr = None - for line in res.splitlines(): - if line.startswith("address="): - addr = line.split('=')[1] - break - cmd = "DPP_BOOTSTRAP_GEN type=qrcode" - cmd += " chan=81/1" - if addr: - cmd += " mac=" + addr.replace(':','') - if curve: - cmd += " curve=" + curve - res = wpas.request(cmd) - try: - id = int(res) - except ValueError: - print("Failed to generate bootstrap info URI") - return - print("Bootstrap information - ID=%d" % id) - print(wpas.request("DPP_BOOTSTRAP_INFO %d" % id)) - uri = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % id) - print(uri) - print("ID=%d" % id) - qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, - border=3) - qr.add_data(uri, optimize=5) - qr.print_ascii(tty=True) - print("ID=%d" % id) - del wpas - -def main(): - parser = argparse.ArgumentParser(description='Android logcat to wpa_supplicant integration for DPP QR Code operations') - parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO, - action='store_const', dest='loglevel', - help='verbose debug output') - parser.add_argument('--curve', '-c', - help='set a specific curve (P-256, P-384, P-521, BP-256R1, BP-384R1, BP-512R1) for key generation') - parser.add_argument('command', choices=['logcat', - 'display'], - nargs='?') - args = parser.parse_args() - - logging.basicConfig(level=args.loglevel) - - if args.command == "logcat": - dpp_logcat() - elif args.command == "display": - dpp_display(args.curve) - -if __name__ == '__main__': - main() diff --git a/wpa_supplicant/examples/ieee8021x.conf b/wpa_supplicant/examples/ieee8021x.conf deleted file mode 100644 index e8a5503d8359..000000000000 --- a/wpa_supplicant/examples/ieee8021x.conf +++ /dev/null @@ -1,13 +0,0 @@ -# IEEE 802.1X with dynamic WEP keys using EAP-PEAP/MSCHAPv2 - -ctrl_interface=/var/run/wpa_supplicant - -network={ - ssid="example 802.1x network" - key_mgmt=IEEE8021X - eap=PEAP - phase2="auth=MSCHAPV2" - identity="user name" - password="password" - ca_cert="/etc/cert/ca.pem" -} diff --git a/wpa_supplicant/examples/openCryptoki.conf b/wpa_supplicant/examples/openCryptoki.conf deleted file mode 100644 index e2301a61cabf..000000000000 --- a/wpa_supplicant/examples/openCryptoki.conf +++ /dev/null @@ -1,41 +0,0 @@ -# EAP-TLS using private key and certificates via OpenSSL PKCS#11 engine and -# openCryptoki (e.g., with TPM token) - -# This example uses following PKCS#11 objects: -# $ pkcs11-tool --module /usr/lib/opencryptoki/libopencryptoki.so -O -l -# Please enter User PIN: -# Private Key Object; RSA -# label: rsakey -# ID: 04 -# Usage: decrypt, sign, unwrap -# Certificate Object, type = X.509 cert -# label: ca -# ID: 01 -# Certificate Object, type = X.509 cert -# label: cert -# ID: 04 - -# Configure OpenSSL to load the PKCS#11 engine and openCryptoki module -pkcs11_engine_path=/usr/lib/engines/engine_pkcs11.so -pkcs11_module_path=/usr/lib/opencryptoki/libopencryptoki.so - -network={ - ssid="test network" - key_mgmt=WPA-EAP - eap=TLS - identity="User" - - # use OpenSSL PKCS#11 engine for this network - engine=1 - engine_id="pkcs11" - - # select the private key and certificates based on ID (see pkcs11-tool - # output above) - key_id="4" - cert_id="4" - ca_cert_id="1" - - # set the PIN code; leave this out to configure the PIN to be requested - # interactively when needed (e.g., via wpa_gui or wpa_cli) - pin="123456" -} diff --git a/wpa_supplicant/examples/p2p-action-udhcp.sh b/wpa_supplicant/examples/p2p-action-udhcp.sh deleted file mode 100755 index 53d8b777cd51..000000000000 --- a/wpa_supplicant/examples/p2p-action-udhcp.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/sh - -IFNAME=$1 -CMD=$2 - -kill_daemon() { - NAME=$1 - PF=$2 - - if [ ! -r $PF ]; then - return - fi - - PID=`cat $PF` - if [ $PID -gt 0 ]; then - if ps $PID | grep -q $NAME; then - kill $PID - fi - fi - rm $PF -} - -if [ "$CMD" = "P2P-GROUP-STARTED" ]; then - GIFNAME=$3 - if [ "$4" = "GO" ]; then - kill_daemon udhcpc /var/run/udhcpc-$GIFNAME.pid - ifconfig $GIFNAME 192.168.42.1 up - udhcpd /etc/udhcpd-p2p.conf - fi - if [ "$4" = "client" ]; then - kill_daemon udhcpc /var/run/udhcpc-$GIFNAME.pid - kill_daemon udhcpd /var/run/udhcpd-$GIFNAME.pid - udhcpc -i $GIFNAME -p /var/run/udhcpc-$GIFNAME.pid \ - -s /etc/udhcpc.script - fi -fi - -if [ "$CMD" = "P2P-GROUP-REMOVED" ]; then - GIFNAME=$3 - if [ "$4" = "GO" ]; then - kill_daemon udhcpd /var/run/udhcpd-$GIFNAME.pid - ifconfig $GIFNAME 0.0.0.0 - fi - if [ "$4" = "client" ]; then - kill_daemon udhcpc /var/run/udhcpc-$GIFNAME.pid - ifconfig $GIFNAME 0.0.0.0 - fi -fi - -if [ "$CMD" = "P2P-CROSS-CONNECT-ENABLE" ]; then - GIFNAME=$3 - UPLINK=$4 - # enable NAT/masquerade $GIFNAME -> $UPLINK - iptables -P FORWARD DROP - iptables -t nat -A POSTROUTING -o $UPLINK -j MASQUERADE - iptables -A FORWARD -i $UPLINK -o $GIFNAME -m state --state RELATED,ESTABLISHED -j ACCEPT - iptables -A FORWARD -i $GIFNAME -o $UPLINK -j ACCEPT - sysctl net.ipv4.ip_forward=1 -fi - -if [ "$CMD" = "P2P-CROSS-CONNECT-DISABLE" ]; then - GIFNAME=$3 - UPLINK=$4 - # disable NAT/masquerade $GIFNAME -> $UPLINK - sysctl net.ipv4.ip_forward=0 - iptables -t nat -D POSTROUTING -o $UPLINK -j MASQUERADE - iptables -D FORWARD -i $UPLINK -o $GIFNAME -m state --state RELATED,ESTABLISHED -j ACCEPT - iptables -D FORWARD -i $GIFNAME -o $UPLINK -j ACCEPT -fi diff --git a/wpa_supplicant/examples/p2p-action.sh b/wpa_supplicant/examples/p2p-action.sh deleted file mode 100755 index 6c27b27b787e..000000000000 --- a/wpa_supplicant/examples/p2p-action.sh +++ /dev/null @@ -1,96 +0,0 @@ -#!/bin/sh - -IFNAME=$1 -CMD=$2 - -kill_daemon() { - NAME=$1 - PF=$2 - - if [ ! -r $PF ]; then - return - fi - - PID=`cat $PF` - if [ $PID -gt 0 ]; then - if ps $PID | grep -q $NAME; then - kill $PID - fi - fi - rm $PF -} - -if [ "$CMD" = "P2P-GROUP-STARTED" ]; then - GIFNAME=$3 - if [ "$4" = "GO" ]; then - kill_daemon dhclient /var/run/dhclient-$GIFNAME.pid - rm /var/run/dhclient.leases-$GIFNAME - kill_daemon dnsmasq /var/run/dnsmasq.pid-$GIFNAME - ifconfig $GIFNAME 192.168.42.1 up - if ! dnsmasq -x /var/run/dnsmasq.pid-$GIFNAME \ - -i $GIFNAME \ - -F192.168.42.11,192.168.42.99; then - # another dnsmasq instance may be running and blocking us; try to - # start with -z to avoid that - dnsmasq -x /var/run/dnsmasq.pid-$GIFNAME \ - -i $GIFNAME \ - -F192.168.42.11,192.168.42.99 --listen-address 192.168.42.1 -z -p 0 - fi - fi - if [ "$4" = "client" ]; then - kill_daemon dhclient /var/run/dhclient-$GIFNAME.pid - rm /var/run/dhclient.leases-$GIFNAME - kill_daemon dnsmasq /var/run/dnsmasq.pid-$GIFNAME - ipaddr=`echo "$*" | sed 's/.* ip_addr=\([^ ]*\).*/\1/'` - ipmask=`echo "$*" | sed 's/.* ip_mask=\([^ ]*\).*/\1/'` - goipaddr=`echo "$*" | sed 's/.* go_ip_addr=\([^ ]*\).*/\1/'` - if echo "$ipaddr$ipmask$goipaddr" | grep -q ' '; then - ipaddr="" - ipmask="" - goipaddr="" - fi - if [ -n "$ipaddr" ]; then - sudo ifconfig $GIFNAME "$ipaddr" netmask "$ipmask" - sudo ip ro re default via "$goipaddr" - exit 0 - fi - dhclient -pf /var/run/dhclient-$GIFNAME.pid \ - -lf /var/run/dhclient.leases-$GIFNAME \ - -nw \ - $GIFNAME - fi -fi - -if [ "$CMD" = "P2P-GROUP-REMOVED" ]; then - GIFNAME=$3 - if [ "$4" = "GO" ]; then - kill_daemon dnsmasq /var/run/dnsmasq.pid-$GIFNAME - ifconfig $GIFNAME 0.0.0.0 - fi - if [ "$4" = "client" ]; then - kill_daemon dhclient /var/run/dhclient-$GIFNAME.pid - rm /var/run/dhclient.leases-$GIFNAME - ifconfig $GIFNAME 0.0.0.0 - fi -fi - -if [ "$CMD" = "P2P-CROSS-CONNECT-ENABLE" ]; then - GIFNAME=$3 - UPLINK=$4 - # enable NAT/masquerade $GIFNAME -> $UPLINK - iptables -P FORWARD DROP - iptables -t nat -A POSTROUTING -o $UPLINK -j MASQUERADE - iptables -A FORWARD -i $UPLINK -o $GIFNAME -m state --state RELATED,ESTABLISHED -j ACCEPT - iptables -A FORWARD -i $GIFNAME -o $UPLINK -j ACCEPT - sysctl net.ipv4.ip_forward=1 -fi - -if [ "$CMD" = "P2P-CROSS-CONNECT-DISABLE" ]; then - GIFNAME=$3 - UPLINK=$4 - # disable NAT/masquerade $GIFNAME -> $UPLINK - sysctl net.ipv4.ip_forward=0 - iptables -t nat -D POSTROUTING -o $UPLINK -j MASQUERADE - iptables -D FORWARD -i $UPLINK -o $GIFNAME -m state --state RELATED,ESTABLISHED -j ACCEPT - iptables -D FORWARD -i $GIFNAME -o $UPLINK -j ACCEPT -fi diff --git a/wpa_supplicant/examples/p2p-nfc.py b/wpa_supplicant/examples/p2p-nfc.py deleted file mode 100755 index 889ac8bff155..000000000000 --- a/wpa_supplicant/examples/p2p-nfc.py +++ /dev/null @@ -1,654 +0,0 @@ -#!/usr/bin/python -# -# Example nfcpy to wpa_supplicant wrapper for P2P NFC operations -# Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi> -# -# This software may be distributed under the terms of the BSD license. -# See README for more details. - -import os -import sys -import time -import random -import threading -import argparse - -import nfc -import nfc.ndef -import nfc.llcp -import nfc.handover - -import logging - -import wpaspy - -wpas_ctrl = '/var/run/wpa_supplicant' -ifname = None -init_on_touch = False -in_raw_mode = False -prev_tcgetattr = 0 -include_wps_req = True -include_p2p_req = True -no_input = False -srv = None -continue_loop = True -terminate_now = False -summary_file = None -success_file = None - -def summary(txt): - print(txt) - if summary_file: - with open(summary_file, 'a') as f: - f.write(txt + "\n") - -def success_report(txt): - summary(txt) - if success_file: - with open(success_file, 'a') as f: - f.write(txt + "\n") - -def wpas_connect(): - ifaces = [] - if os.path.isdir(wpas_ctrl): - try: - ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] - except OSError as error: - print("Could not find wpa_supplicant: ", error) - return None - - if len(ifaces) < 1: - print("No wpa_supplicant control interface found") - return None - - for ctrl in ifaces: - if ifname: - if ifname not in ctrl: - continue - try: - print("Trying to use control interface " + ctrl) - wpas = wpaspy.Ctrl(ctrl) - return wpas - except Exception as e: - pass - return None - - -def wpas_tag_read(message): - wpas = wpas_connect() - if (wpas == None): - return False - cmd = "WPS_NFC_TAG_READ " + str(message).encode("hex") - global force_freq - if force_freq: - cmd = cmd + " freq=" + force_freq - if "FAIL" in wpas.request(cmd): - return False - return True - - -def wpas_get_handover_req(): - wpas = wpas_connect() - if (wpas == None): - return None - res = wpas.request("NFC_GET_HANDOVER_REQ NDEF P2P-CR").rstrip() - if "FAIL" in res: - return None - return res.decode("hex") - -def wpas_get_handover_req_wps(): - wpas = wpas_connect() - if (wpas == None): - return None - res = wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR").rstrip() - if "FAIL" in res: - return None - return res.decode("hex") - - -def wpas_get_handover_sel(tag=False): - wpas = wpas_connect() - if (wpas == None): - return None - if tag: - res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR-TAG").rstrip() - else: - res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR").rstrip() - if "FAIL" in res: - return None - return res.decode("hex") - - -def wpas_get_handover_sel_wps(): - wpas = wpas_connect() - if (wpas == None): - return None - res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR"); - if "FAIL" in res: - return None - return res.rstrip().decode("hex") - - -def wpas_report_handover(req, sel, type): - wpas = wpas_connect() - if (wpas == None): - return None - cmd = "NFC_REPORT_HANDOVER " + type + " P2P " + str(req).encode("hex") + " " + str(sel).encode("hex") - global force_freq - if force_freq: - cmd = cmd + " freq=" + force_freq - return wpas.request(cmd) - - -def wpas_report_handover_wsc(req, sel, type): - wpas = wpas_connect() - if (wpas == None): - return None - cmd = "NFC_REPORT_HANDOVER " + type + " WPS " + str(req).encode("hex") + " " + str(sel).encode("hex") - if force_freq: - cmd = cmd + " freq=" + force_freq - return wpas.request(cmd) - - -def p2p_handover_client(llc): - message = nfc.ndef.HandoverRequestMessage(version="1.2") - message.nonce = random.randint(0, 0xffff) - - global include_p2p_req - if include_p2p_req: - data = wpas_get_handover_req() - if (data == None): - summary("Could not get handover request carrier record from wpa_supplicant") - return - print("Handover request carrier record from wpa_supplicant: " + data.encode("hex")) - datamsg = nfc.ndef.Message(data) - message.add_carrier(datamsg[0], "active", datamsg[1:]) - - global include_wps_req - if include_wps_req: - print("Handover request (pre-WPS):") - try: - print(message.pretty()) - except Exception as e: - print(e) - - data = wpas_get_handover_req_wps() - if data: - print("Add WPS request in addition to P2P") - datamsg = nfc.ndef.Message(data) - message.add_carrier(datamsg[0], "active", datamsg[1:]) - - print("Handover request:") - try: - print(message.pretty()) - except Exception as e: - print(e) - print(str(message).encode("hex")) - - client = nfc.handover.HandoverClient(llc) - try: - summary("Trying to initiate NFC connection handover") - client.connect() - summary("Connected for handover") - except nfc.llcp.ConnectRefused: - summary("Handover connection refused") - client.close() - return - except Exception as e: - summary("Other exception: " + str(e)) - client.close() - return - - summary("Sending handover request") - - if not client.send(message): - summary("Failed to send handover request") - client.close() - return - - summary("Receiving handover response") - message = client._recv() - if message is None: - summary("No response received") - client.close() - return - if message.type != "urn:nfc:wkt:Hs": - summary("Response was not Hs - received: " + message.type) - client.close() - return - - print("Received message") - try: - print(message.pretty()) - except Exception as e: - print(e) - print(str(message).encode("hex")) - message = nfc.ndef.HandoverSelectMessage(message) - summary("Handover select received") - try: - print(message.pretty()) - except Exception as e: - print(e) - - for carrier in message.carriers: - print("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.p2p": - print("P2P carrier type match - send to wpa_supplicant") - if "OK" in wpas_report_handover(data, carrier.record, "INIT"): - success_report("P2P handover reported successfully (initiator)") - else: - summary("P2P handover report rejected") - break - - print("Remove peer") - client.close() - print("Done with handover") - global only_one - if only_one: - print("only_one -> stop loop") - global continue_loop - continue_loop = False - - global no_wait - if no_wait: - print("Trying to exit..") - global terminate_now - terminate_now = True - - -class HandoverServer(nfc.handover.HandoverServer): - def __init__(self, llc): - super(HandoverServer, self).__init__(llc) - self.sent_carrier = None - self.ho_server_processing = False - self.success = False - - # override to avoid parser error in request/response.pretty() in nfcpy - # due to new WSC handover format - def _process_request(self, request): - summary("received handover request {}".format(request.type)) - response = nfc.ndef.Message("\xd1\x02\x01Hs\x12") - if not request.type == 'urn:nfc:wkt:Hr': - summary("not a handover request") - else: - try: - request = nfc.ndef.HandoverRequestMessage(request) - except nfc.ndef.DecodeError as e: - summary("error decoding 'Hr' message: {}".format(e)) - else: - response = self.process_request(request) - summary("send handover response {}".format(response.type)) - return response - - def process_request(self, request): - self.ho_server_processing = True - clear_raw_mode() - print("HandoverServer - request received") - try: - print("Parsed handover request: " + request.pretty()) - except Exception as e: - print(e) - - sel = nfc.ndef.HandoverSelectMessage(version="1.2") - - found = False - - for carrier in request.carriers: - print("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.p2p": - print("P2P carrier type match - add P2P carrier record") - found = True - self.received_carrier = carrier.record - print("Carrier record:") - try: - print(carrier.record.pretty()) - except Exception as e: - print(e) - data = wpas_get_handover_sel() - if data is None: - print("Could not get handover select carrier record from wpa_supplicant") - continue - print("Handover select carrier record from wpa_supplicant:") - print(data.encode("hex")) - self.sent_carrier = data - if "OK" in wpas_report_handover(self.received_carrier, self.sent_carrier, "RESP"): - success_report("P2P handover reported successfully (responder)") - else: - summary("P2P handover report rejected") - break - - message = nfc.ndef.Message(data); - sel.add_carrier(message[0], "active", message[1:]) - break - - for carrier in request.carriers: - if found: - break - print("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.wsc": - print("WSC carrier type match - add WSC carrier record") - found = True - self.received_carrier = carrier.record - print("Carrier record:") - try: - print(carrier.record.pretty()) - except Exception as e: - print(e) - data = wpas_get_handover_sel_wps() - if data is None: - print("Could not get handover select carrier record from wpa_supplicant") - continue - print("Handover select carrier record from wpa_supplicant:") - print(data.encode("hex")) - self.sent_carrier = data - if "OK" in wpas_report_handover_wsc(self.received_carrier, self.sent_carrier, "RESP"): - success_report("WSC handover reported successfully") - else: - summary("WSC handover report rejected") - break - - message = nfc.ndef.Message(data); - sel.add_carrier(message[0], "active", message[1:]) - found = True - break - - print("Handover select:") - try: - print(sel.pretty()) - except Exception as e: - print(e) - print(str(sel).encode("hex")) - - summary("Sending handover select") - self.success = True - return sel - - -def clear_raw_mode(): - import sys, tty, termios - global prev_tcgetattr, in_raw_mode - if not in_raw_mode: - return - fd = sys.stdin.fileno() - termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr) - in_raw_mode = False - - -def getch(): - import sys, tty, termios, select - global prev_tcgetattr, in_raw_mode - fd = sys.stdin.fileno() - prev_tcgetattr = termios.tcgetattr(fd) - ch = None - try: - tty.setraw(fd) - in_raw_mode = True - [i, o, e] = select.select([fd], [], [], 0.05) - if i: - ch = sys.stdin.read(1) - finally: - termios.tcsetattr(fd, termios.TCSADRAIN, prev_tcgetattr) - in_raw_mode = False - return ch - - -def p2p_tag_read(tag): - success = False - if len(tag.ndef.message): - for record in tag.ndef.message: - print("record type " + record.type) - if record.type == "application/vnd.wfa.wsc": - summary("WPS tag - send to wpa_supplicant") - success = wpas_tag_read(tag.ndef.message) - break - if record.type == "application/vnd.wfa.p2p": - summary("P2P tag - send to wpa_supplicant") - success = wpas_tag_read(tag.ndef.message) - break - else: - summary("Empty tag") - - if success: - success_report("Tag read succeeded") - - return success - - -def rdwr_connected_p2p_write(tag): - summary("Tag found - writing - " + str(tag)) - global p2p_sel_data - tag.ndef.message = str(p2p_sel_data) - success_report("Tag write succeeded") - print("Done - remove tag") - global only_one - if only_one: - global continue_loop - continue_loop = False - global p2p_sel_wait_remove - return p2p_sel_wait_remove - -def wps_write_p2p_handover_sel(clf, wait_remove=True): - print("Write P2P handover select") - data = wpas_get_handover_sel(tag=True) - if (data == None): - summary("Could not get P2P handover select from wpa_supplicant") - return - - global p2p_sel_wait_remove - p2p_sel_wait_remove = wait_remove - global p2p_sel_data - p2p_sel_data = nfc.ndef.HandoverSelectMessage(version="1.2") - message = nfc.ndef.Message(data); - p2p_sel_data.add_carrier(message[0], "active", message[1:]) - print("Handover select:") - try: - print(p2p_sel_data.pretty()) - except Exception as e: - print(e) - print(str(p2p_sel_data).encode("hex")) - - print("Touch an NFC tag") - clf.connect(rdwr={'on-connect': rdwr_connected_p2p_write}) - - -def rdwr_connected(tag): - global only_one, no_wait - summary("Tag connected: " + str(tag)) - - if tag.ndef: - print("NDEF tag: " + tag.type) - try: - print(tag.ndef.message.pretty()) - except Exception as e: - print(e) - success = p2p_tag_read(tag) - if only_one and success: - global continue_loop - continue_loop = False - else: - summary("Not an NDEF tag - remove tag") - return True - - return not no_wait - - -def llcp_worker(llc): - global init_on_touch - if init_on_touch: - print("Starting handover client") - p2p_handover_client(llc) - return - - global no_input - if no_input: - print("Wait for handover to complete") - else: - print("Wait for handover to complete - press 'i' to initiate ('w' for WPS only, 'p' for P2P only)") - global srv - global wait_connection - while not wait_connection and srv.sent_carrier is None: - if srv.ho_server_processing: - time.sleep(0.025) - elif no_input: - time.sleep(0.5) - else: - global include_wps_req, include_p2p_req - res = getch() - if res == 'i': - include_wps_req = True - include_p2p_req = True - elif res == 'p': - include_wps_req = False - include_p2p_req = True - elif res == 'w': - include_wps_req = True - include_p2p_req = False - else: - continue - clear_raw_mode() - print("Starting handover client") - p2p_handover_client(llc) - return - - clear_raw_mode() - print("Exiting llcp_worker thread") - -def llcp_startup(clf, llc): - print("Start LLCP server") - global srv - srv = HandoverServer(llc) - return llc - -def llcp_connected(llc): - print("P2P LLCP connected") - global wait_connection - wait_connection = False - global init_on_touch - if not init_on_touch: - global srv - srv.start() - if init_on_touch or not no_input: - threading.Thread(target=llcp_worker, args=(llc,)).start() - return True - -def terminate_loop(): - global terminate_now - return terminate_now - -def main(): - clf = nfc.ContactlessFrontend() - - parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for P2P and WPS NFC operations') - parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO, - action='store_const', dest='loglevel', - help='verbose debug output') - parser.add_argument('-q', const=logging.WARNING, action='store_const', - dest='loglevel', help='be quiet') - parser.add_argument('--only-one', '-1', action='store_true', - help='run only one operation and exit') - parser.add_argument('--init-on-touch', '-I', action='store_true', - help='initiate handover on touch') - parser.add_argument('--no-wait', action='store_true', - help='do not wait for tag to be removed before exiting') - parser.add_argument('--ifname', '-i', - help='network interface name') - parser.add_argument('--no-wps-req', '-N', action='store_true', - help='do not include WPS carrier record in request') - parser.add_argument('--no-input', '-a', action='store_true', - help='do not use stdout input to initiate handover') - parser.add_argument('--tag-read-only', '-t', action='store_true', - help='tag read only (do not allow connection handover)') - parser.add_argument('--handover-only', action='store_true', - help='connection handover only (do not allow tag read)') - parser.add_argument('--freq', '-f', - help='forced frequency of operating channel in MHz') - parser.add_argument('--summary', - help='summary file for writing status updates') - parser.add_argument('--success', - help='success file for writing success update') - parser.add_argument('command', choices=['write-p2p-sel'], - nargs='?') - args = parser.parse_args() - - global only_one - only_one = args.only_one - - global no_wait - no_wait = args.no_wait - - global force_freq - force_freq = args.freq - - logging.basicConfig(level=args.loglevel) - - global init_on_touch - init_on_touch = args.init_on_touch - - if args.ifname: - global ifname - ifname = args.ifname - print("Selected ifname " + ifname) - - if args.no_wps_req: - global include_wps_req - include_wps_req = False - - if args.summary: - global summary_file - summary_file = args.summary - - if args.success: - global success_file - success_file = args.success - - if args.no_input: - global no_input - no_input = True - - clf = nfc.ContactlessFrontend() - global wait_connection - - try: - if not clf.open("usb"): - print("Could not open connection with an NFC device") - raise SystemExit - - if args.command == "write-p2p-sel": - wps_write_p2p_handover_sel(clf, wait_remove=not args.no_wait) - raise SystemExit - - global continue_loop - while continue_loop: - print("Waiting for a tag or peer to be touched") - wait_connection = True - try: - if args.tag_read_only: - if not clf.connect(rdwr={'on-connect': rdwr_connected}): - break - elif args.handover_only: - if not clf.connect(llcp={'on-startup': llcp_startup, - 'on-connect': llcp_connected}, - terminate=terminate_loop): - break - else: - if not clf.connect(rdwr={'on-connect': rdwr_connected}, - llcp={'on-startup': llcp_startup, - 'on-connect': llcp_connected}, - terminate=terminate_loop): - break - except Exception as e: - print("clf.connect failed") - - global srv - if only_one and srv and srv.success: - raise SystemExit - - except KeyboardInterrupt: - raise SystemExit - finally: - clf.close() - - raise SystemExit - -if __name__ == '__main__': - main() diff --git a/wpa_supplicant/examples/p2p/p2p_connect.py b/wpa_supplicant/examples/p2p/p2p_connect.py deleted file mode 100644 index bfb553341ad6..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_connect.py +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/python -# Tests p2p_connect -# Will try to connect to another peer -# and form a group -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import getopt -from dbus.mainloop.glib import DBusGMainLoop - - -def usage(): - print("Usage:") - print(" %s -i <interface_name> -m <wps_method> \ " \ - % sys.argv[0]) - print(" -a <addr> [-p <pin>] [-g <go_intent>] \ ") - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -m = wps method") - print(" -a = peer address") - print(" -p = pin number (8 digits)") - print(" -g = group owner intent") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i wlan0 -a 0015008352c0 -m display -p 12345670" % sys.argv[0]) - - -# Required Signals -def GONegotiationSuccess(status): - print("Go Negotiation Success") - -def GONegotiationFailure(status): - print('Go Negotiation Failed. Status:') - print(format(status)) - os._exit(0) - -def GroupStarted(properties): - if properties.has_key("group_object"): - print('Group Formation Complete %s' \ - % properties["group_object"]) - os._exit(0) - -def WpsFailure(status, etc): - print("WPS Authentication Failure".format(status)) - print(etc) - os._exit(0) - -class P2P_Connect(): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global ifname - global wpas - global wpas_dbus_interface - global timeout - global path - global wps_method - global go_intent - global addr - global pin - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Dictionary of Arguments - global p2p_connect_arguements - - # Constructor - def __init__(self,ifname,wpas_dbus_interface,addr, - pin,wps_method,go_intent): - # Initializes variables and threads - self.ifname = ifname - self.wpas_dbus_interface = wpas_dbus_interface - self.wps_method = wps_method - self.go_intent = go_intent - self.addr = addr - self.pin = pin - - # Generating interface/object paths - self.wpas_dbus_opath = \ - "/" + self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = \ - self.wpas_dbus_opath + "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface( - self.wpas_object, self.wpas_dbus_interface) - - # See if wpa_supplicant already knows about this interface - self.path = None - try: - self.path = self.wpas.GetInterface(ifname) - except dbus.DBusException as exc: - if not str(exc).startswith( - self.wpas_dbus_interface + \ - ".InterfaceUnknown:"): - raise exc - try: - path = self.wpas.CreateInterface( - {'Ifname': ifname, 'Driver': 'test'}) - time.sleep(1) - - except dbus.DBusException as exc: - if not str(exc).startswith( - self.wpas_dbus_interface + \ - ".InterfaceExists:"): - raise exc - - # Get Interface and objects - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface,self.path) - self.p2p_interface = dbus.Interface( - self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - # Add signals - self.bus.add_signal_receiver(GONegotiationSuccess, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="GONegotiationSuccess") - self.bus.add_signal_receiver(GONegotiationFailure, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="GONegotiationFailure") - self.bus.add_signal_receiver(GroupStarted, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="GroupStarted") - self.bus.add_signal_receiver(WpsFailure, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="WpsFailed") - - - #Constructing all the arguments needed to connect - def constructArguements(self): - # Adding required arguments - self.p2p_connect_arguements = {'wps_method':self.wps_method, - 'peer':dbus.ObjectPath(self.path+'/Peers/'+self.addr)} - - # Display requires a pin, and a go intent of 15 - if (self.wps_method == 'display'): - if (self.pin != None): - self.p2p_connect_arguements.update({'pin':self.pin}) - else: - print("Error:\n Pin required for wps_method=display") - usage() - quit() - - if (self.go_intent != None and int(self.go_intent) != 15): - print("go_intent overwritten to 15") - - self.go_intent = '15' - - # Keypad requires a pin, and a go intent of less than 15 - elif (self.wps_method == 'keypad'): - if (self.pin != None): - self.p2p_connect_arguements.update({'pin':self.pin}) - else: - print("Error:\n Pin required for wps_method=keypad") - usage() - quit() - - if (self.go_intent != None and int(self.go_intent) == 15): - error = "Error :\n Group Owner intent cannot be" + \ - " 15 for wps_method=keypad" - print(error) - usage() - quit() - - # Doesn't require pin - # for ./wpa_cli, p2p_connect [mac] [pin#], wps_method=keypad - elif (self.wps_method == 'pin'): - if (self.pin != None): - print("pin ignored") - - # No pin is required for pbc so it is ignored - elif (self.wps_method == 'pbc'): - if (self.pin != None): - print("pin ignored") - - else: - print("Error:\n wps_method not supported or does not exist") - usage() - quit() - - # Go_intent is optional for all arguments - if (self.go_intent != None): - self.p2p_connect_arguements.update( - {'go_intent':dbus.Int32(self.go_intent)}) - - # Running p2p_connect - def run(self): - try: - result_pin = self.p2p_interface.Connect( - self.p2p_connect_arguements) - - except dbus.DBusException as exc: - raise exc - - if (self.wps_method == 'pin' and \ - not self.p2p_connect_arguements.has_key('pin') ): - print("Connect return with pin value of %d " % int(result_pin)) - gobject.MainLoop().run() - -if __name__ == "__main__": - - # Required - interface_name = None - wps_method = None - addr = None - - # Conditionally optional - pin = None - - # Optional - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - go_intent = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:m:a:p:g:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # WPS Method - elif (key == "-m"): - wps_method = value - # Address - elif (key == "-a"): - addr = value - # Pin - elif (key == "-p"): - pin = value - # Group Owner Intent - elif (key == "-g"): - go_intent = value - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Required Arguments check - if (interface_name == None or wps_method == None or addr == None): - print("Error:\n Required arguments not specified") - usage() - quit() - - # Group Owner Intent Check - if (go_intent != None and (int(go_intent) > 15 or int(go_intent) < 0) ): - print("Error:\n Group Owner Intent must be between 0 and 15 inclusive") - usage() - quit() - - # Pin Check - if (pin != None and len(pin) != 8): - print("Error:\n Pin is not 8 digits") - usage() - quit() - - try: - p2p_connect_test = P2P_Connect(interface_name,wpas_dbus_interface, - addr,pin,wps_method,go_intent) - - except: - print("Error:\n Invalid Arguments") - usage() - quit() - - p2p_connect_test.constructArguements() - p2p_connect_test.run() - - os._exit(0) diff --git a/wpa_supplicant/examples/p2p/p2p_disconnect.py b/wpa_supplicant/examples/p2p/p2p_disconnect.py deleted file mode 100644 index f04b98e667ce..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_disconnect.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/python -# Tests P2P_Disconnect -# Will perform disconnect on interface_name -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import threading -import getopt -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> \ " \ - % sys.argv[0]) - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i p2p-wlan0-0" % sys.argv[0]) - -# Required Signals -def GroupFinished(status, etc): - print("Disconnected") - os._exit(0) - -class P2P_Disconnect (threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global path - global timeout - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,timeout): - # Initializes variables and threads - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - self.timeout = timeout - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - # Signals - self.bus.add_signal_receiver(GroupFinished, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="GroupFinished") - - # Runs p2p_disconnect - def run(self): - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - self.p2p_interface.Disconnect() - gobject.MainLoop().run() - - -if __name__ == "__main__": - - timeout = 5 - # Defaults for optional inputs - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - # Constructor - try: - p2p_disconnect_test = P2P_Disconnect(interface_name, - wpas_dbus_interface,timeout) - - except: - print("Error:\n Invalid wpas_dbus_interface") - usage() - quit() - - # Start P2P_Disconnect - p2p_disconnect_test.start() - - try: - time.sleep(int(p2p_disconnect_test.timeout)) - - except: - pass - - print("Disconnect timed out") - quit() diff --git a/wpa_supplicant/examples/p2p/p2p_find.py b/wpa_supplicant/examples/p2p/p2p_find.py deleted file mode 100644 index 412d8120031a..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_find.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/python -# Tests p2p_find -# Will list all devices found/lost within a time frame (timeout) -# Then Program will exit -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import threading -import getopt -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> [-t <timeout>] \ " \ - % sys.argv[0]) - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -t = timeout = 0s (infinite)") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i wlan0 -t 10" % sys.argv[0]) - -# Required Signals -def deviceFound(devicepath): - print("Device found: %s" % (devicepath)) - -def deviceLost(devicepath): - print("Device lost: %s" % (devicepath)) - -class P2P_Find (threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global timeout - global path - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,timeout): - # Initializes variables and threads - self.timeout = int(timeout) - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - #Adds listeners for find and lost - self.bus.add_signal_receiver(deviceFound, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="DeviceFound") - self.bus.add_signal_receiver(deviceLost, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="DeviceLost") - - - # Sets up p2p_find - P2PFindDict = dbus.Dictionary( - {'Timeout':int(self.timeout)}) - self.p2p_interface.Find(P2PFindDict) - - # Run p2p_find - def run(self): - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - gobject.MainLoop().run() - -if __name__ == "__main__": - - # Defaults for optional inputs - timeout = 0 - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:t:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # Timeout - elif (key == "-t"): - if ( int(value) >= 0): - timeout = value - else: - print("Error:\n Timeout cannot be negative") - usage() - quit() - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - # Constructor - try: - p2p_find_test = P2P_Find(interface_name, wpas_dbus_interface, timeout) - - except: - print("Error:\n Invalid wpas_dbus_interface") - usage() - quit() - - # Start P2P_Find - p2p_find_test.start() - - try: - # If timeout is 0, then run forever - if (timeout == 0): - while(True): - pass - # Else sleep for (timeout) - else: - time.sleep(p2p_find_test.timeout) - - except: - pass - - quit() diff --git a/wpa_supplicant/examples/p2p/p2p_flush.py b/wpa_supplicant/examples/p2p/p2p_flush.py deleted file mode 100644 index 5cc3a0e18b23..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_flush.py +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/python -# Tests P2P_Flush -# Will flush the p2p interface -# Then Program will exit -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import threading -import getopt -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> \ " \ - % sys.argv[0]) - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i wlan0" % sys.argv[0]) - -# Required Signals\ -def deviceLost(devicepath): - print("Device lost: %s" % (devicepath)) - -class P2P_Flush (threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global path - global timeout - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,timeout): - # Initializes variables and threads - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - self.timeout = timeout - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - # Signals - self.bus.add_signal_receiver(deviceLost, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="DeviceLost") - - # Runs p2p_flush - def run(self): - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - self.p2p_interface.Flush() - gobject.MainLoop().run() - - -if __name__ == "__main__": - # Needed to show which devices were lost - timeout = 5 - # Defaults for optional inputs - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - # Constructor - try: - p2p_flush_test = P2P_Flush(interface_name, wpas_dbus_interface,timeout) - - except: - print("Error:\n Invalid wpas_dbus_interface") - usage() - quit() - - # Start P2P_Find - p2p_flush_test.start() - - try: - time.sleep(int(p2p_flush_test.timeout)) - - except: - pass - - print("p2p_flush complete") - quit() diff --git a/wpa_supplicant/examples/p2p/p2p_group_add.py b/wpa_supplicant/examples/p2p/p2p_group_add.py deleted file mode 100644 index db6d60d80c1b..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_group_add.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/python -# Tests p2p_group_add -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import getopt -import threading -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> [-p <persistent>] \ " \ - % sys.argv[0]) - print(" [-f <frequency>] [-o <group_object_path>] \ ") - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -p = persistent group = 0 (0=false, 1=true)") - print(" -f = frequency") - print(" -o = persistent group object path") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i wlan0" % sys.argv[0]) - -# Required Signals -def GroupStarted(properties): - if properties.has_key("group_object"): - print('Group Formation Complete %s' \ - % properties["group_object"]) - os._exit(0) - -def WpsFailure(status, etc): - print("WPS Authentication Failure".format(status)) - print(etc) - os._exit(0) - -class P2P_Group_Add (threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global path - global persistent - global frequency - global persistent_group_object - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Arguments - global P2PDictionary - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,persistent,frequency, - persistent_group_object): - # Initializes variables and threads - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - self.persistent = persistent - self.frequency = frequency - self.persistent_group_object = persistent_group_object - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - #Adds listeners - self.bus.add_signal_receiver(GroupStarted, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="GroupStarted") - self.bus.add_signal_receiver(WpsFailure, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="WpsFailed") - - # Sets up p2p_group_add dictionary - def constructArguments(self): - self.P2PDictionary = {'persistent':self.persistent} - - if (self.frequency != None): - if (int(self.frequency) > 0): - self.P2PDictionary.update({'frequency':int(self.frequency)}) - else: - print("Error:\n Frequency must be greater than 0") - usage() - os._exit(0) - - if (self.persistent_group_object != None): - self.P2PDictionary.update({'persistent_group_object': - self.persistent_group_object}) - - # Run p2p_group_remove - def run(self): - try: - self.p2p_interface.GroupAdd(self.P2PDictionary) - - except: - print("Error:\n Could not perform group add") - usage() - os._exit(0) - - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - gobject.MainLoop().run() - - -if __name__ == "__main__": - - # Defaults for optional inputs - # 0 = false, 1 = true - persistent = False - frequency = None - persistent_group_object = None - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:p:f:o:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # Timeout - elif (key == "-p"): - if (value == '0'): - persistent = False - elif (value == '1'): - persistent = True - else: - print("Error:\n Persistent can only be 1 or 0") - usage() - os._exit(0) - # Frequency - elif (key == "-f"): - frequency = value - # Persistent group object path - elif (key == "-o"): - persistent_group_object = value - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - try: - p2p_group_add_test = P2P_Group_Add(interface_name,wpas_dbus_interface, - persistent,frequency,persistent_group_object) - except: - print("Error:\n Invalid Arguments") - - p2p_group_add_test.constructArguments() - p2p_group_add_test.start() - time.sleep(5) - print("Error:\n Group formation timed out") - os._exit(0) diff --git a/wpa_supplicant/examples/p2p/p2p_invite.py b/wpa_supplicant/examples/p2p/p2p_invite.py deleted file mode 100644 index 8944e11ed47c..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_invite.py +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/python -# Tests p2p_invite -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import getopt -import threading -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> -a <addr> \ " \ - % sys.argv[0]) - print(" [-o <persistent_group_object>] [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -a = address of peer") - print(" -o = persistent group object path") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i p2p-wlan0-0 -a 00150083523c" % sys.argv[0]) - -# Required Signals -def InvitationResult(invite_result): - print("Invitation Result signal :") - status = invite_result['status'] - print("status = ", status) - if invite_result.has_key('BSSID'): - bssid = invite_result['BSSID'] - print("BSSID = ", hex(bssid[0]) , ":" , \ - hex(bssid[1]) , ":" , hex(bssid[2]) , ":", \ - hex(bssid[3]) , ":" , hex(bssid[4]) , ":" , \ - hex(bssid[5])) - os._exit(0) - -class P2P_Invite (threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global path - global addr - global persistent_group_object - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Arguments - global P2PDictionary - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,addr, - persistent_group_object): - # Initializes variables and threads - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - self.addr = addr - self.persistent_group_object = persistent_group_object - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - #Adds listeners - self.bus.add_signal_receiver(InvitationResult, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="InvitationResult") - - # Sets up p2p_invite dictionary - def constructArguements(self): - self.P2PDictionary = \ - {'peer':dbus.ObjectPath(self.path+'/Peers/'+self.addr)} - if (self.persistent_group_object != None): - self.P2PDictionary.update({"persistent_group_object": - self.persistent_group_object}) - - # Run p2p_invite - def run(self): - try: - self.p2p_interface.Invite(self.P2PDictionary) - - except: - print("Error:\n Invalid Arguments") - usage() - os._exit(0) - - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - gobject.MainLoop().run() - -if __name__ == "__main__": - # Defaults for optional inputs - addr = None - persistent_group_object = None - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:o:w:a:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - elif (key == "-a"): - addr = value - # Persistent group object path - elif (key == "-o"): - persistent_group_object = value - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - if (addr == None): - print("Error:\n peer address is required") - usage() - quit() - - try: - p2p_invite_test = \ - P2P_Invite(interface_name,wpas_dbus_interface, - addr,persistent_group_object) - except: - print("Error:\n Invalid Arguments") - usage() - os._exit(1) - - p2p_invite_test.constructArguements() - p2p_invite_test.start() - time.sleep(10) - print("Error:\n p2p_invite timed out") - os._exit(0) diff --git a/wpa_supplicant/examples/p2p/p2p_listen.py b/wpa_supplicant/examples/p2p/p2p_listen.py deleted file mode 100644 index cbeda9ff43ca..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_listen.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/python -# Tests P2P_Find -# Will listen -# Then Program will exit -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import threading -import getopt -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> [-t <timeout>] \ " \ - % sys.argv[0]) - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -t = timeout = 0s (infinite)") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i wlan0 -t 5" % sys.argv[0]) - -# Required Signals -def p2pStateChange(status): - print(status) - -class P2P_Listen(threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global path - global timeout - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,timeout): - # Initializes variables and threads - self.timeout = int(timeout) - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - self.bus.add_signal_receiver(p2pStateChange, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="P2PStateChanged") - - # Run p2p_find - def run(self): - # Sets up p2p_listen - self.p2p_interface.Listen(int(self.timeout)) - - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - gobject.MainLoop().run() - -if __name__ == "__main__": - - # Defaults for optional inputs - timeout = 0 - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"hi:t:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # Timeout - elif (key == "-t"): - if ( int(value) >= 0): - timeout = value - else: - print("Error:\n Timeout cannot be negative") - usage() - quit() - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - # Constructor - try: - p2p_listen_test = P2P_Listen(interface_name, wpas_dbus_interface, timeout) - - except: - print("Error:\n Invalid wpas_dbus_interface") - usage() - quit() - - # Start P2P_Find - p2p_listen_test.start() - - try: - # If timeout is 0, then run forever - if (int(p2p_listen_test.timeout) == 0): - while(True): - pass - # Else sleep for (timeout) - else: - time.sleep(int(p2p_listen_test.timeout)) - - except: - pass - - quit() diff --git a/wpa_supplicant/examples/p2p/p2p_stop_find.py b/wpa_supplicant/examples/p2p/p2p_stop_find.py deleted file mode 100644 index f367196454d9..000000000000 --- a/wpa_supplicant/examples/p2p/p2p_stop_find.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/python -# Tests p2p_stop_find -######### MAY NEED TO RUN AS SUDO ############# - -import dbus -import sys, os -import time -import gobject -import threading -import getopt -from dbus.mainloop.glib import DBusGMainLoop - -def usage(): - print("Usage:") - print(" %s -i <interface_name> \ " \ - % sys.argv[0]) - print(" [-w <wpas_dbus_interface>]") - print("Options:") - print(" -i = interface name") - print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1") - print("Example:") - print(" %s -i wlan0" % sys.argv[0]) - -# Required Signals -def deviceLost(devicepath): - print("Device lost: %s" % (devicepath)) - -def p2pStateChange(status): - print(status) - os._exit(0) - -class P2P_Stop_Find (threading.Thread): - # Needed Variables - global bus - global wpas_object - global interface_object - global p2p_interface - global interface_name - global wpas - global wpas_dbus_interface - global path - global timeout - - # Dbus Paths - global wpas_dbus_opath - global wpas_dbus_interfaces_opath - global wpas_dbus_interfaces_interface - global wpas_dbus_interfaces_p2pdevice - - # Constructor - def __init__(self,interface_name,wpas_dbus_interface,timeout): - # Initializes variables and threads - self.interface_name = interface_name - self.wpas_dbus_interface = wpas_dbus_interface - self.timeout = timeout - - # Initializes thread and daemon allows for ctrl-c kill - threading.Thread.__init__(self) - self.daemon = True - - # Generating interface/object paths - self.wpas_dbus_opath = "/" + \ - self.wpas_dbus_interface.replace(".","/") - self.wpas_wpas_dbus_interfaces_opath = self.wpas_dbus_opath + \ - "/Interfaces" - self.wpas_dbus_interfaces_interface = \ - self.wpas_dbus_interface + ".Interface" - self.wpas_dbus_interfaces_p2pdevice = \ - self.wpas_dbus_interfaces_interface \ - + ".P2PDevice" - - # Getting interfaces and objects - DBusGMainLoop(set_as_default=True) - self.bus = dbus.SystemBus() - self.wpas_object = self.bus.get_object( - self.wpas_dbus_interface, - self.wpas_dbus_opath) - self.wpas = dbus.Interface(self.wpas_object, - self.wpas_dbus_interface) - - # Try to see if supplicant knows about interface - # If not, throw an exception - try: - self.path = self.wpas.GetInterface( - self.interface_name) - except dbus.DBusException as exc: - error = 'Error:\n Interface ' + self.interface_name \ - + ' was not found' - print(error) - usage() - os._exit(0) - - self.interface_object = self.bus.get_object( - self.wpas_dbus_interface, self.path) - self.p2p_interface = dbus.Interface(self.interface_object, - self.wpas_dbus_interfaces_p2pdevice) - - # Signals - self.bus.add_signal_receiver(deviceLost, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="DeviceLost") - self.bus.add_signal_receiver(p2pStateChange, - dbus_interface=self.wpas_dbus_interfaces_p2pdevice, - signal_name="P2PStateChanged") - - # Runs p2p_stop_find - def run(self): - # Allows other threads to keep working while MainLoop runs - # Required for timeout implementation - gobject.MainLoop().get_context().iteration(True) - gobject.threads_init() - self.p2p_interface.StopFind() - gobject.MainLoop().run() - - -if __name__ == "__main__": - # Needed because P2PStateChanged signal is not caught - timeout = 5 - # Defaults for optional inputs - wpas_dbus_interface = 'fi.w1.wpa_supplicant1' - - # interface_name is required - interface_name = None - - # Using getopts to handle options - try: - options, args = getopt.getopt(sys.argv[1:],"ht:i:w:") - - except getopt.GetoptError: - usage() - quit() - - # If there's a switch, override default option - for key, value in options: - # Help - if (key == "-h"): - usage() - quit() - # Interface Name - elif (key == "-i"): - interface_name = value - # Dbus interface - elif (key == "-w"): - wpas_dbus_interface = value - else: - assert False, "unhandled option" - - # Interface name is required and was not given - if (interface_name == None): - print("Error:\n interface_name is required") - usage() - quit() - - # Constructor - try: - p2p_stop_find_test = P2P_Stop_Find(interface_name, - wpas_dbus_interface,timeout) - - except: - print("Error:\n Invalid wpas_dbus_interface") - usage() - quit() - - # Start P2P_Find - p2p_stop_find_test.start() - - try: - time.sleep(int(p2p_stop_find_test.timeout)) - - except: - pass - - print("p2p find stopped") - quit() diff --git a/wpa_supplicant/examples/plaintext.conf b/wpa_supplicant/examples/plaintext.conf deleted file mode 100644 index 542ac1dd3b96..000000000000 --- a/wpa_supplicant/examples/plaintext.conf +++ /dev/null @@ -1,8 +0,0 @@ -# Plaintext (no encryption) network - -ctrl_interface=/var/run/wpa_supplicant - -network={ - ssid="example open network" - key_mgmt=NONE -} diff --git a/wpa_supplicant/examples/udhcpd-p2p.conf b/wpa_supplicant/examples/udhcpd-p2p.conf deleted file mode 100644 index f92cc619e962..000000000000 --- a/wpa_supplicant/examples/udhcpd-p2p.conf +++ /dev/null @@ -1,118 +0,0 @@ -# Sample udhcpd configuration file (/etc/udhcpd.conf) - -# The start and end of the IP lease block - -start 192.168.42.20 #default: 192.168.0.20 -end 192.168.42.254 #default: 192.168.0.254 - - -# The interface that udhcpd will use - -interface wlan2 #default: eth0 - - -# The maximum number of leases (includes addresses reserved -# by OFFER's, DECLINE's, and ARP conflicts) - -#max_leases 254 #default: 254 - - -# If remaining is true (default), udhcpd will store the time -# remaining for each lease in the udhcpd leases file. This is -# for embedded systems that cannot keep time between reboots. -# If you set remaining to no, the absolute time that the lease -# expires at will be stored in the dhcpd.leases file. - -#remaining yes #default: yes - - -# The time period at which udhcpd will write out a dhcpd.leases -# file. If this is 0, udhcpd will never automatically write a -# lease file. (specified in seconds) - -#auto_time 7200 #default: 7200 (2 hours) - - -# The amount of time that an IP will be reserved (leased) for if a -# DHCP decline message is received (seconds). - -#decline_time 3600 #default: 3600 (1 hour) - - -# The amount of time that an IP will be reserved (leased) for if an -# ARP conflct occurs. (seconds - -#conflict_time 3600 #default: 3600 (1 hour) - - -# How long an offered address is reserved (leased) in seconds - -#offer_time 60 #default: 60 (1 minute) - -# If a lease to be given is below this value, the full lease time is -# instead used (seconds). - -#min_lease 60 #default: 60 - - -# The location of the leases file - -#lease_file /var/lib/misc/udhcpd.leases #default: /var/lib/misc/udhcpd.leases - -# The location of the pid file -pidfile /var/run/udhcpd-wlan2.pid #default: /var/run/udhcpd.pid - -# Every time udhcpd writes a leases file, the below script will be called. -# Useful for writing the lease file to flash every few hours. - -#notify_file #default: (no script) - -#notify_file dumpleases # <--- useful for debugging - -# The following are bootp specific options, setable by udhcpd. - -#siaddr 192.168.0.22 #default: 0.0.0.0 - -#sname zorak #default: (none) - -#boot_file /var/nfs_root #default: (none) - -# The remainder of options are DHCP options and can be specified with the -# keyword 'opt' or 'option'. If an option can take multiple items, such -# as the dns option, they can be listed on the same line, or multiple -# lines. The only option with a default is 'lease'. - -#Examles -opt dns 192.168.2.1 -option subnet 255.255.255.0 -option domain atherosowl.com -option lease 864000 # 10 days of seconds - - -# Currently supported options, for more info, see options.c -#opt subnet -#opt timezone -#opt router -#opt timesvr -#opt namesvr -#opt dns -#opt logsvr -#opt cookiesvr -#opt lprsvr -#opt bootsize -#opt domain -#opt swapsvr -#opt rootpath -#opt ipttl -#opt mtu -#opt broadcast -#opt wins -#opt lease -#opt ntpsrv -#opt tftp -#opt bootfile - - -# Static leases map -#static_lease 00:60:08:11:CE:4E 192.168.0.54 -#static_lease 00:60:08:11:CE:3E 192.168.0.44 diff --git a/wpa_supplicant/examples/wep.conf b/wpa_supplicant/examples/wep.conf deleted file mode 100644 index 9c7b55f2722a..000000000000 --- a/wpa_supplicant/examples/wep.conf +++ /dev/null @@ -1,11 +0,0 @@ -# Static WEP keys - -ctrl_interface=/var/run/wpa_supplicant - -network={ - ssid="example wep network" - key_mgmt=NONE - wep_key0="abcde" - wep_key1=0102030405 - wep_tx_keyidx=0 -} diff --git a/wpa_supplicant/examples/wpa-psk-tkip.conf b/wpa_supplicant/examples/wpa-psk-tkip.conf deleted file mode 100644 index 93d7fc2444ea..000000000000 --- a/wpa_supplicant/examples/wpa-psk-tkip.conf +++ /dev/null @@ -1,12 +0,0 @@ -# WPA-PSK/TKIP - -ctrl_interface=/var/run/wpa_supplicant - -network={ - ssid="example wpa-psk network" - key_mgmt=WPA-PSK - proto=WPA - pairwise=TKIP - group=TKIP - psk="secret passphrase" -} diff --git a/wpa_supplicant/examples/wpa2-eap-ccmp.conf b/wpa_supplicant/examples/wpa2-eap-ccmp.conf deleted file mode 100644 index d7a64d87b254..000000000000 --- a/wpa_supplicant/examples/wpa2-eap-ccmp.conf +++ /dev/null @@ -1,15 +0,0 @@ -# WPA2-EAP/CCMP using EAP-TLS - -ctrl_interface=/var/run/wpa_supplicant - -network={ - ssid="example wpa2-eap network" - key_mgmt=WPA-EAP - proto=WPA2 - pairwise=CCMP - group=CCMP - eap=TLS - ca_cert="/etc/cert/ca.pem" - private_key="/etc/cert/user.p12" - private_key_passwd="PKCS#12 passhrase" -} diff --git a/wpa_supplicant/examples/wpas-dbus-new-getall.py b/wpa_supplicant/examples/wpas-dbus-new-getall.py deleted file mode 100755 index 732f54d20f8b..000000000000 --- a/wpa_supplicant/examples/wpas-dbus-new-getall.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python - -import dbus -import sys, os -import time -import gobject - -def main(): - bus = dbus.SystemBus() - wpas_obj = bus.get_object("fi.w1.wpa_supplicant1", - "/fi/w1/wpa_supplicant1") - props = wpas_obj.GetAll("fi.w1.wpa_supplicant1", - dbus_interface=dbus.PROPERTIES_IFACE) - print("GetAll(fi.w1.wpa_supplicant1, /fi/w1/wpa_supplicant1):") - print(props) - - if len(sys.argv) != 2: - os._exit(1) - - ifname = sys.argv[1] - - wpas = dbus.Interface(wpas_obj, "fi.w1.wpa_supplicant1") - path = wpas.GetInterface(ifname) - if_obj = bus.get_object("fi.w1.wpa_supplicant1", path) - props = if_obj.GetAll("fi.w1.wpa_supplicant1.Interface", - dbus_interface=dbus.PROPERTIES_IFACE) - print('') - print("GetAll(fi.w1.wpa_supplicant1.Interface, %s):" % (path)) - print(props) - - props = if_obj.GetAll("fi.w1.wpa_supplicant1.Interface.WPS", - dbus_interface=dbus.PROPERTIES_IFACE) - print('') - print("GetAll(fi.w1.wpa_supplicant1.Interface.WPS, %s):" % (path)) - print(props) - - res = if_obj.Get("fi.w1.wpa_supplicant1.Interface", 'BSSs', - dbus_interface=dbus.PROPERTIES_IFACE) - if len(res) > 0: - bss_obj = bus.get_object("fi.w1.wpa_supplicant1", res[0]) - props = bss_obj.GetAll("fi.w1.wpa_supplicant1.BSS", - dbus_interface=dbus.PROPERTIES_IFACE) - print('') - print("GetAll(fi.w1.wpa_supplicant1.BSS, %s):" % (res[0])) - print(props) - - res = if_obj.Get("fi.w1.wpa_supplicant1.Interface", 'Networks', - dbus_interface=dbus.PROPERTIES_IFACE) - if len(res) > 0: - net_obj = bus.get_object("fi.w1.wpa_supplicant1", res[0]) - props = net_obj.GetAll("fi.w1.wpa_supplicant1.Network", - dbus_interface=dbus.PROPERTIES_IFACE) - print('') - print("GetAll(fi.w1.wpa_supplicant1.Network, %s):" % (res[0])) - print(props) - -if __name__ == "__main__": - main() diff --git a/wpa_supplicant/examples/wpas-dbus-new-signals.py b/wpa_supplicant/examples/wpas-dbus-new-signals.py deleted file mode 100755 index 366a65546af6..000000000000 --- a/wpa_supplicant/examples/wpas-dbus-new-signals.py +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/python - -import dbus -import sys, os -import time -import gobject -from dbus.mainloop.glib import DBusGMainLoop - -WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1" - -WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface" -WPAS_DBUS_INTERFACES_OPATH = "/fi/w1/wpa_supplicant1/Interfaces" -WPAS_DBUS_BSS_INTERFACE = "fi.w1.wpa_supplicant1.BSS" -WPAS_DBUS_NETWORK_INTERFACE = "fi.w1.wpa_supplicant1.Network" - -def byte_array_to_string(s): - import urllib - r = "" - for c in s: - if c >= 32 and c < 127: - r += "%c" % c - else: - r += urllib.quote(chr(c)) - return r - -def list_interfaces(wpas_obj): - ifaces = wpas_obj.Get(WPAS_DBUS_INTERFACE, 'Interfaces', - dbus_interface=dbus.PROPERTIES_IFACE) - for path in ifaces: - if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) - ifname = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'Ifname', - dbus_interface=dbus.PROPERTIES_IFACE) - print(ifname) - -def interfaceAdded(interface, properties): - print("InterfaceAdded(%s): Ifname=%s" % (interface, properties['Ifname'])) - -def interfaceRemoved(interface): - print("InterfaceRemoved(%s)" % (interface)) - -def propertiesChanged(properties): - for i in properties: - print("PropertiesChanged: %s=%s" % (i, properties[i])) - -def showBss(bss): - net_obj = bus.get_object(WPAS_DBUS_SERVICE, bss) - net = dbus.Interface(net_obj, WPAS_DBUS_BSS_INTERFACE) - - # Convert the byte-array for SSID and BSSID to printable strings - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'BSSID', - dbus_interface=dbus.PROPERTIES_IFACE) - bssid = "" - for item in val: - bssid = bssid + ":%02x" % item - bssid = bssid[1:] - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'SSID', - dbus_interface=dbus.PROPERTIES_IFACE) - ssid = byte_array_to_string(val) - - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'WPA', - dbus_interface=dbus.PROPERTIES_IFACE) - wpa = "no" - if val != None: - wpa = "yes" - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'RSN', - dbus_interface=dbus.PROPERTIES_IFACE) - wpa2 = "no" - if val != None: - wpa2 = "yes" - freq = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'Frequency', - dbus_interface=dbus.PROPERTIES_IFACE) - signal = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'Signal', - dbus_interface=dbus.PROPERTIES_IFACE) - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'Rates', - dbus_interface=dbus.PROPERTIES_IFACE) - if len(val) > 0: - maxrate = val[0] / 1000000 - else: - maxrate = 0 - - print(" %s :: ssid='%s' wpa=%s wpa2=%s signal=%d rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, signal, maxrate, freq)) - -def scanDone(success): - gobject.MainLoop().quit() - print("Scan done: success=%s" % success) - -def scanDone2(success, path=None): - print("Scan done: success=%s [path=%s]" % (success, path)) - -def bssAdded(bss, properties): - print("BSS added: %s" % (bss)) - showBss(bss) - -def bssRemoved(bss): - print("BSS removed: %s" % (bss)) - -def blobAdded(blob): - print("BlobAdded(%s)" % (blob)) - -def blobRemoved(blob): - print("BlobRemoved(%s)" % (blob)) - -def networkAdded(network, properties): - print("NetworkAdded(%s)" % (network)) - -def networkRemoved(network): - print("NetworkRemoved(%s)" % (network)) - -def networkSelected(network): - print("NetworkSelected(%s)" % (network)) - -def propertiesChangedInterface(properties): - for i in properties: - print("PropertiesChanged(interface): %s=%s" % (i, properties[i])) - -def propertiesChangedBss(properties): - for i in properties: - print("PropertiesChanged(BSS): %s=%s" % (i, properties[i])) - -def propertiesChangedNetwork(properties): - for i in properties: - print("PropertiesChanged(Network): %s=%s" % (i, properties[i])) - -def main(): - dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) - global bus - bus = dbus.SystemBus() - wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH) - - if len(sys.argv) != 2: - list_interfaces(wpas_obj) - os._exit(1) - - wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE) - bus.add_signal_receiver(interfaceAdded, - dbus_interface=WPAS_DBUS_INTERFACE, - signal_name="InterfaceAdded") - bus.add_signal_receiver(interfaceRemoved, - dbus_interface=WPAS_DBUS_INTERFACE, - signal_name="InterfaceRemoved") - bus.add_signal_receiver(propertiesChanged, - dbus_interface=WPAS_DBUS_INTERFACE, - signal_name="PropertiesChanged") - - ifname = sys.argv[1] - path = wpas.GetInterface(ifname) - if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) - iface = dbus.Interface(if_obj, WPAS_DBUS_INTERFACES_INTERFACE) - iface.connect_to_signal("ScanDone", scanDone2, - path_keyword='path') - - bus.add_signal_receiver(scanDone, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="ScanDone", - path=path) - bus.add_signal_receiver(bssAdded, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BSSAdded", - path=path) - bus.add_signal_receiver(bssRemoved, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BSSRemoved", - path=path) - bus.add_signal_receiver(blobAdded, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BlobAdded", - path=path) - bus.add_signal_receiver(blobRemoved, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BlobRemoved", - path=path) - bus.add_signal_receiver(networkAdded, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="NetworkAdded", - path=path) - bus.add_signal_receiver(networkRemoved, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="NetworkRemoved", - path=path) - bus.add_signal_receiver(networkSelected, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="NetworkSelected", - path=path) - bus.add_signal_receiver(propertiesChangedInterface, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="PropertiesChanged", - path=path) - - bus.add_signal_receiver(propertiesChangedBss, - dbus_interface=WPAS_DBUS_BSS_INTERFACE, - signal_name="PropertiesChanged") - - bus.add_signal_receiver(propertiesChangedNetwork, - dbus_interface=WPAS_DBUS_NETWORK_INTERFACE, - signal_name="PropertiesChanged") - - gobject.MainLoop().run() - -if __name__ == "__main__": - main() - diff --git a/wpa_supplicant/examples/wpas-dbus-new-wps.py b/wpa_supplicant/examples/wpas-dbus-new-wps.py deleted file mode 100755 index 7d87b1efd5dc..000000000000 --- a/wpa_supplicant/examples/wpas-dbus-new-wps.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python - -import dbus -import sys, os -import time -import gobject -from dbus.mainloop.glib import DBusGMainLoop - -WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1" - -WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface" -WPAS_DBUS_WPS_INTERFACE = "fi.w1.wpa_supplicant1.Interface.WPS" - -def propertiesChanged(properties): - if properties.has_key("State"): - print("PropertiesChanged: State: %s" % (properties["State"])) - -def scanDone(success): - print("Scan done: success=%s" % success) - -def bssAdded(bss, properties): - print("BSS added: %s" % (bss)) - -def bssRemoved(bss): - print("BSS removed: %s" % (bss)) - -def wpsEvent(name, args): - print("WPS event: %s" % (name)) - print(args) - -def credentials(cred): - print("WPS credentials: %s" % (cred)) - -def main(): - dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) - global bus - bus = dbus.SystemBus() - wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH) - - if len(sys.argv) != 2: - print("Missing ifname argument") - os._exit(1) - - wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE) - bus.add_signal_receiver(scanDone, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="ScanDone") - bus.add_signal_receiver(bssAdded, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BSSAdded") - bus.add_signal_receiver(bssRemoved, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BSSRemoved") - bus.add_signal_receiver(propertiesChanged, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="PropertiesChanged") - bus.add_signal_receiver(wpsEvent, - dbus_interface=WPAS_DBUS_WPS_INTERFACE, - signal_name="Event") - bus.add_signal_receiver(credentials, - dbus_interface=WPAS_DBUS_WPS_INTERFACE, - signal_name="Credentials") - - ifname = sys.argv[1] - - path = wpas.GetInterface(ifname) - if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) - if_obj.Set(WPAS_DBUS_WPS_INTERFACE, 'ProcessCredentials', - dbus.Boolean(1), - dbus_interface=dbus.PROPERTIES_IFACE) - wps = dbus.Interface(if_obj, WPAS_DBUS_WPS_INTERFACE) - wps.Start({'Role': 'enrollee', 'Type': 'pbc'}) - - gobject.MainLoop().run() - -if __name__ == "__main__": - main() - diff --git a/wpa_supplicant/examples/wpas-dbus-new.py b/wpa_supplicant/examples/wpas-dbus-new.py deleted file mode 100755 index 6bf74ae44122..000000000000 --- a/wpa_supplicant/examples/wpas-dbus-new.py +++ /dev/null @@ -1,149 +0,0 @@ -#!/usr/bin/python - -import dbus -import sys, os -import time -import gobject -from dbus.mainloop.glib import DBusGMainLoop - -WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1" -WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1" - -WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface" -WPAS_DBUS_INTERFACES_OPATH = "/fi/w1/wpa_supplicant1/Interfaces" -WPAS_DBUS_BSS_INTERFACE = "fi.w1.wpa_supplicant1.BSS" - -def byte_array_to_string(s): - import urllib - r = "" - for c in s: - if c >= 32 and c < 127: - r += "%c" % c - else: - r += urllib.quote(chr(c)) - return r - -def list_interfaces(wpas_obj): - ifaces = wpas_obj.Get(WPAS_DBUS_INTERFACE, 'Interfaces', - dbus_interface=dbus.PROPERTIES_IFACE) - for path in ifaces: - if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) - ifname = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'Ifname', - dbus_interface=dbus.PROPERTIES_IFACE) - print(ifname) - -def propertiesChanged(properties): - if properties.has_key("State"): - print("PropertiesChanged: State: %s" % (properties["State"])) - -def showBss(bss): - net_obj = bus.get_object(WPAS_DBUS_SERVICE, bss) - net = dbus.Interface(net_obj, WPAS_DBUS_BSS_INTERFACE) - - # Convert the byte-array for SSID and BSSID to printable strings - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'BSSID', - dbus_interface=dbus.PROPERTIES_IFACE) - bssid = "" - for item in val: - bssid = bssid + ":%02x" % item - bssid = bssid[1:] - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'SSID', - dbus_interface=dbus.PROPERTIES_IFACE) - ssid = byte_array_to_string(val) - - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'WPA', - dbus_interface=dbus.PROPERTIES_IFACE) - wpa = "no" - if len(val["KeyMgmt"]) > 0: - wpa = "yes" - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'RSN', - dbus_interface=dbus.PROPERTIES_IFACE) - wpa2 = "no" - if len(val["KeyMgmt"]) > 0: - wpa2 = "yes" - freq = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'Frequency', - dbus_interface=dbus.PROPERTIES_IFACE) - signal = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'Signal', - dbus_interface=dbus.PROPERTIES_IFACE) - val = net_obj.Get(WPAS_DBUS_BSS_INTERFACE, 'Rates', - dbus_interface=dbus.PROPERTIES_IFACE) - if len(val) > 0: - maxrate = val[0] / 1000000 - else: - maxrate = 0 - - print(" %s :: ssid='%s' wpa=%s wpa2=%s signal=%d rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, signal, maxrate, freq)) - -def scanDone(success): - print("Scan done: success=%s" % success) - - res = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'BSSs', - dbus_interface=dbus.PROPERTIES_IFACE) - - print("Scanned wireless networks:") - for opath in res: - print(opath) - showBss(opath) - -def bssAdded(bss, properties): - print("BSS added: %s" % (bss)) - showBss(bss) - -def bssRemoved(bss): - print("BSS removed: %s" % (bss)) - -def main(): - dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) - global bus - bus = dbus.SystemBus() - wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH) - - if len(sys.argv) != 2: - list_interfaces(wpas_obj) - os._exit(1) - - wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE) - bus.add_signal_receiver(scanDone, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="ScanDone") - bus.add_signal_receiver(bssAdded, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BSSAdded") - bus.add_signal_receiver(bssRemoved, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="BSSRemoved") - bus.add_signal_receiver(propertiesChanged, - dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, - signal_name="PropertiesChanged") - - ifname = sys.argv[1] - - # See if wpa_supplicant already knows about this interface - path = None - try: - path = wpas.GetInterface(ifname) - except dbus.DBusException as exc: - if not str(exc).startswith("fi.w1.wpa_supplicant1.InterfaceUnknown:"): - raise exc - try: - path = wpas.CreateInterface({'Ifname': ifname, 'Driver': 'test'}) - time.sleep(1) - - except dbus.DBusException as exc: - if not str(exc).startswith("fi.w1.wpa_supplicant1.InterfaceExists:"): - raise exc - - global if_obj - if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) - global iface - iface = dbus.Interface(if_obj, WPAS_DBUS_INTERFACES_INTERFACE) - iface.Scan({'Type': 'active'}) - - gobject.MainLoop().run() - - wpas.RemoveInterface(dbus.ObjectPath(path)) - -if __name__ == "__main__": - main() - diff --git a/wpa_supplicant/examples/wps-ap-cli b/wpa_supplicant/examples/wps-ap-cli deleted file mode 100755 index 15d913ef1fae..000000000000 --- a/wpa_supplicant/examples/wps-ap-cli +++ /dev/null @@ -1,81 +0,0 @@ -#!/bin/sh - -CLI=wpa_cli - -pbc() -{ - echo "Starting PBC mode" - echo "Push button on the station within two minutes" - if ! $CLI wps_pbc | grep -q OK; then - echo "Failed to enable PBC mode" - fi -} - -enter_pin() -{ - echo "Enter a PIN from a station to be enrolled to the network." - printf "Enrollee PIN: " - read pin - cpin=`$CLI wps_check_pin "$pin" | tail -1` - if [ "$cpin" = "FAIL-CHECKSUM" ]; then - echo "Checksum digit is not valid" - printf "Do you want to use this PIN (y/n)? " - read resp - case "$resp" in - y*) - cpin=`echo "$pin" | sed "s/[^1234567890]//g"` - ;; - *) - return 1 - ;; - esac - fi - if [ "$cpin" = "FAIL" ]; then - echo "Invalid PIN: $pin" - return 1 - fi - echo "Enabling Enrollee PIN: $cpin" - $CLI wps_pin any "$cpin" -} - -show_config() -{ - $CLI status wps -} - -main_menu() -{ - echo "WPS AP" - echo "------" - echo "1: Push button (activate PBC)" - echo "2: Enter Enrollee PIN" - echo "3: Show current configuration" - echo "0: Exit wps-ap-cli" - - printf "Command: " - read cmd - - case "$cmd" in - 1) - pbc - ;; - 2) - enter_pin - ;; - 3) - show_config - ;; - 0) - exit 0 - ;; - *) - echo "Unknown command: $cmd" - ;; - esac - - echo - main_menu -} - - -main_menu diff --git a/wpa_supplicant/examples/wps-nfc.py b/wpa_supplicant/examples/wps-nfc.py deleted file mode 100755 index bb458fb37a84..000000000000 --- a/wpa_supplicant/examples/wps-nfc.py +++ /dev/null @@ -1,525 +0,0 @@ -#!/usr/bin/python -# -# Example nfcpy to wpa_supplicant wrapper for WPS NFC operations -# Copyright (c) 2012-2013, Jouni Malinen <j@w1.fi> -# -# This software may be distributed under the terms of the BSD license. -# See README for more details. - -import os -import sys -import time -import random -import threading -import argparse - -import nfc -import nfc.ndef -import nfc.llcp -import nfc.handover - -import logging - -import wpaspy - -wpas_ctrl = '/var/run/wpa_supplicant' -srv = None -continue_loop = True -terminate_now = False -summary_file = None -success_file = None - -def summary(txt): - print(txt) - if summary_file: - with open(summary_file, 'a') as f: - f.write(txt + "\n") - -def success_report(txt): - summary(txt) - if success_file: - with open(success_file, 'a') as f: - f.write(txt + "\n") - -def wpas_connect(): - ifaces = [] - if os.path.isdir(wpas_ctrl): - try: - ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] - except OSError as error: - print("Could not find wpa_supplicant: ", error) - return None - - if len(ifaces) < 1: - print("No wpa_supplicant control interface found") - return None - - for ctrl in ifaces: - try: - wpas = wpaspy.Ctrl(ctrl) - return wpas - except Exception as e: - pass - return None - - -def wpas_tag_read(message): - wpas = wpas_connect() - if (wpas == None): - return False - if "FAIL" in wpas.request("WPS_NFC_TAG_READ " + str(message).encode("hex")): - return False - return True - -def wpas_get_config_token(id=None): - wpas = wpas_connect() - if (wpas == None): - return None - if id: - ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF " + id) - else: - ret = wpas.request("WPS_NFC_CONFIG_TOKEN NDEF") - if "FAIL" in ret: - return None - return ret.rstrip().decode("hex") - - -def wpas_get_er_config_token(uuid): - wpas = wpas_connect() - if (wpas == None): - return None - ret = wpas.request("WPS_ER_NFC_CONFIG_TOKEN NDEF " + uuid) - if "FAIL" in ret: - return None - return ret.rstrip().decode("hex") - - -def wpas_get_password_token(): - wpas = wpas_connect() - if (wpas == None): - return None - ret = wpas.request("WPS_NFC_TOKEN NDEF") - if "FAIL" in ret: - return None - return ret.rstrip().decode("hex") - -def wpas_get_handover_req(): - wpas = wpas_connect() - if (wpas == None): - return None - ret = wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS-CR") - if "FAIL" in ret: - return None - return ret.rstrip().decode("hex") - - -def wpas_get_handover_sel(uuid): - wpas = wpas_connect() - if (wpas == None): - return None - if uuid is None: - res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR").rstrip() - else: - res = wpas.request("NFC_GET_HANDOVER_SEL NDEF WPS-CR " + uuid).rstrip() - if "FAIL" in res: - return None - return res.decode("hex") - - -def wpas_report_handover(req, sel, type): - wpas = wpas_connect() - if (wpas == None): - return None - return wpas.request("NFC_REPORT_HANDOVER " + type + " WPS " + - str(req).encode("hex") + " " + - str(sel).encode("hex")) - - -class HandoverServer(nfc.handover.HandoverServer): - def __init__(self, llc): - super(HandoverServer, self).__init__(llc) - self.sent_carrier = None - self.ho_server_processing = False - self.success = False - - # override to avoid parser error in request/response.pretty() in nfcpy - # due to new WSC handover format - def _process_request(self, request): - summary("received handover request {}".format(request.type)) - response = nfc.ndef.Message("\xd1\x02\x01Hs\x12") - if not request.type == 'urn:nfc:wkt:Hr': - summary("not a handover request") - else: - try: - request = nfc.ndef.HandoverRequestMessage(request) - except nfc.ndef.DecodeError as e: - summary("error decoding 'Hr' message: {}".format(e)) - else: - response = self.process_request(request) - summary("send handover response {}".format(response.type)) - return response - - def process_request(self, request): - self.ho_server_processing = True - summary("HandoverServer - request received") - try: - print("Parsed handover request: " + request.pretty()) - except Exception as e: - print(e) - - sel = nfc.ndef.HandoverSelectMessage(version="1.2") - - for carrier in request.carriers: - print("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.wsc": - summary("WPS carrier type match - add WPS carrier record") - data = wpas_get_handover_sel(self.uuid) - if data is None: - summary("Could not get handover select carrier record from wpa_supplicant") - continue - print("Handover select carrier record from wpa_supplicant:") - print(data.encode("hex")) - self.sent_carrier = data - if "OK" in wpas_report_handover(carrier.record, self.sent_carrier, "RESP"): - success_report("Handover reported successfully (responder)") - else: - summary("Handover report rejected (responder)") - - message = nfc.ndef.Message(data); - sel.add_carrier(message[0], "active", message[1:]) - - print("Handover select:") - try: - print(sel.pretty()) - except Exception as e: - print(e) - print(str(sel).encode("hex")) - - summary("Sending handover select") - self.success = True - return sel - - -def wps_handover_init(llc): - summary("Trying to initiate WPS handover") - - data = wpas_get_handover_req() - if (data == None): - summary("Could not get handover request carrier record from wpa_supplicant") - return - print("Handover request carrier record from wpa_supplicant: " + data.encode("hex")) - - message = nfc.ndef.HandoverRequestMessage(version="1.2") - message.nonce = random.randint(0, 0xffff) - datamsg = nfc.ndef.Message(data) - message.add_carrier(datamsg[0], "active", datamsg[1:]) - - print("Handover request:") - try: - print(message.pretty()) - except Exception as e: - print(e) - print(str(message).encode("hex")) - - client = nfc.handover.HandoverClient(llc) - try: - summary("Trying to initiate NFC connection handover") - client.connect() - summary("Connected for handover") - except nfc.llcp.ConnectRefused: - summary("Handover connection refused") - client.close() - return - except Exception as e: - summary("Other exception: " + str(e)) - client.close() - return - - summary("Sending handover request") - - if not client.send(message): - summary("Failed to send handover request") - client.close() - return - - summary("Receiving handover response") - message = client._recv() - if message is None: - summary("No response received") - client.close() - return - if message.type != "urn:nfc:wkt:Hs": - summary("Response was not Hs - received: " + message.type) - client.close() - return - - print("Received message") - try: - print(message.pretty()) - except Exception as e: - print(e) - print(str(message).encode("hex")) - message = nfc.ndef.HandoverSelectMessage(message) - summary("Handover select received") - try: - print(message.pretty()) - except Exception as e: - print(e) - - for carrier in message.carriers: - print("Remote carrier type: " + carrier.type) - if carrier.type == "application/vnd.wfa.wsc": - print("WPS carrier type match - send to wpa_supplicant") - if "OK" in wpas_report_handover(data, carrier.record, "INIT"): - success_report("Handover reported successfully (initiator)") - else: - summary("Handover report rejected (initiator)") - # nfcpy does not support the new format.. - #wifi = nfc.ndef.WifiConfigRecord(carrier.record) - #print wifi.pretty() - - print("Remove peer") - client.close() - print("Done with handover") - global only_one - if only_one: - global continue_loop - continue_loop = False - - global no_wait - if no_wait: - print("Trying to exit..") - global terminate_now - terminate_now = True - -def wps_tag_read(tag, wait_remove=True): - success = False - if len(tag.ndef.message): - for record in tag.ndef.message: - print("record type " + record.type) - if record.type == "application/vnd.wfa.wsc": - summary("WPS tag - send to wpa_supplicant") - success = wpas_tag_read(tag.ndef.message) - break - else: - summary("Empty tag") - - if success: - success_report("Tag read succeeded") - - if wait_remove: - print("Remove tag") - while tag.is_present: - time.sleep(0.1) - - return success - - -def rdwr_connected_write(tag): - summary("Tag found - writing - " + str(tag)) - global write_data - tag.ndef.message = str(write_data) - success_report("Tag write succeeded") - print("Done - remove tag") - global only_one - if only_one: - global continue_loop - continue_loop = False - global write_wait_remove - while write_wait_remove and tag.is_present: - time.sleep(0.1) - -def wps_write_config_tag(clf, id=None, wait_remove=True): - print("Write WPS config token") - global write_data, write_wait_remove - write_wait_remove = wait_remove - write_data = wpas_get_config_token(id) - if write_data == None: - print("Could not get WPS config token from wpa_supplicant") - sys.exit(1) - return - print("Touch an NFC tag") - clf.connect(rdwr={'on-connect': rdwr_connected_write}) - - -def wps_write_er_config_tag(clf, uuid, wait_remove=True): - print("Write WPS ER config token") - global write_data, write_wait_remove - write_wait_remove = wait_remove - write_data = wpas_get_er_config_token(uuid) - if write_data == None: - print("Could not get WPS config token from wpa_supplicant") - return - - print("Touch an NFC tag") - clf.connect(rdwr={'on-connect': rdwr_connected_write}) - - -def wps_write_password_tag(clf, wait_remove=True): - print("Write WPS password token") - global write_data, write_wait_remove - write_wait_remove = wait_remove - write_data = wpas_get_password_token() - if write_data == None: - print("Could not get WPS password token from wpa_supplicant") - return - - print("Touch an NFC tag") - clf.connect(rdwr={'on-connect': rdwr_connected_write}) - - -def rdwr_connected(tag): - global only_one, no_wait - summary("Tag connected: " + str(tag)) - - if tag.ndef: - print("NDEF tag: " + tag.type) - try: - print(tag.ndef.message.pretty()) - except Exception as e: - print(e) - success = wps_tag_read(tag, not only_one) - if only_one and success: - global continue_loop - continue_loop = False - else: - summary("Not an NDEF tag - remove tag") - return True - - return not no_wait - - -def llcp_worker(llc): - global arg_uuid - if arg_uuid is None: - wps_handover_init(llc) - print("Exiting llcp_worker thread") - return - - global srv - global wait_connection - while not wait_connection and srv.sent_carrier is None: - if srv.ho_server_processing: - time.sleep(0.025) - -def llcp_startup(clf, llc): - global arg_uuid - if arg_uuid: - print("Start LLCP server") - global srv - srv = HandoverServer(llc) - if arg_uuid is "ap": - print("Trying to handle WPS handover") - srv.uuid = None - else: - print("Trying to handle WPS handover with AP " + arg_uuid) - srv.uuid = arg_uuid - return llc - -def llcp_connected(llc): - print("P2P LLCP connected") - global wait_connection - wait_connection = False - global arg_uuid - if arg_uuid: - global srv - srv.start() - else: - threading.Thread(target=llcp_worker, args=(llc,)).start() - print("llcp_connected returning") - return True - - -def terminate_loop(): - global terminate_now - return terminate_now - -def main(): - clf = nfc.ContactlessFrontend() - - parser = argparse.ArgumentParser(description='nfcpy to wpa_supplicant integration for WPS NFC operations') - parser.add_argument('-d', const=logging.DEBUG, default=logging.INFO, - action='store_const', dest='loglevel', - help='verbose debug output') - parser.add_argument('-q', const=logging.WARNING, action='store_const', - dest='loglevel', help='be quiet') - parser.add_argument('--only-one', '-1', action='store_true', - help='run only one operation and exit') - parser.add_argument('--no-wait', action='store_true', - help='do not wait for tag to be removed before exiting') - parser.add_argument('--uuid', - help='UUID of an AP (used for WPS ER operations)') - parser.add_argument('--id', - help='network id (used for WPS ER operations)') - parser.add_argument('--summary', - help='summary file for writing status updates') - parser.add_argument('--success', - help='success file for writing success update') - parser.add_argument('command', choices=['write-config', - 'write-er-config', - 'write-password'], - nargs='?') - args = parser.parse_args() - - global arg_uuid - arg_uuid = args.uuid - - global only_one - only_one = args.only_one - - global no_wait - no_wait = args.no_wait - - if args.summary: - global summary_file - summary_file = args.summary - - if args.success: - global success_file - success_file = args.success - - logging.basicConfig(level=args.loglevel) - - try: - if not clf.open("usb"): - print("Could not open connection with an NFC device") - raise SystemExit - - if args.command == "write-config": - wps_write_config_tag(clf, id=args.id, wait_remove=not args.no_wait) - raise SystemExit - - if args.command == "write-er-config": - wps_write_er_config_tag(clf, args.uuid, wait_remove=not args.no_wait) - raise SystemExit - - if args.command == "write-password": - wps_write_password_tag(clf, wait_remove=not args.no_wait) - raise SystemExit - - global continue_loop - while continue_loop: - print("Waiting for a tag or peer to be touched") - wait_connection = True - try: - if not clf.connect(rdwr={'on-connect': rdwr_connected}, - llcp={'on-startup': llcp_startup, - 'on-connect': llcp_connected}, - terminate=terminate_loop): - break - except Exception as e: - print("clf.connect failed") - - global srv - if only_one and srv and srv.success: - raise SystemExit - - except KeyboardInterrupt: - raise SystemExit - finally: - clf.close() - - raise SystemExit - -if __name__ == '__main__': - main() |