NfcService.java 65.5 KB
Newer Older
Nick Pelly's avatar
Nick Pelly committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package com.android.nfc;
Nick Pelly's avatar
Nick Pelly committed
18

19
import com.android.nfc.DeviceHost.DeviceHostListener;
20 21
import com.android.nfc.DeviceHost.LlcpServerSocket;
import com.android.nfc.DeviceHost.LlcpSocket;
22 23
import com.android.nfc.DeviceHost.NfcDepEndpoint;
import com.android.nfc.DeviceHost.TagEndpoint;
24 25
import com.android.nfc.nxp.NativeNfcManager;
import com.android.nfc.nxp.NativeNfcSecureElement;
26
import com.android.nfc3.R;
Jeff Hamilton's avatar
Jeff Hamilton committed
27

28
import android.app.Application;
29
import android.app.KeyguardManager;
30
import android.app.PendingIntent;
31
import android.content.BroadcastReceiver;
32
import android.content.ComponentName;
33
import android.content.ContentResolver;
34 35 36
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
Nick Pelly's avatar
Nick Pelly committed
37
import android.content.SharedPreferences;
38
import android.content.pm.PackageManager;
39 40
import android.media.AudioManager;
import android.media.SoundPool;
41
import android.net.Uri;
Nick Pelly's avatar
Nick Pelly committed
42 43
import android.nfc.ErrorCodes;
import android.nfc.FormatException;
44
import android.nfc.INdefPushCallback;
Nick Pelly's avatar
Nick Pelly committed
45
import android.nfc.INfcAdapter;
46
import android.nfc.INfcAdapterExtras;
Nick Pelly's avatar
Nick Pelly committed
47 48 49
import android.nfc.INfcTag;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
Nick Pelly's avatar
Nick Pelly committed
50
import android.nfc.Tag;
51
import android.nfc.TechListParcel;
52
import android.nfc.TransceiveResult;
53
import android.nfc.tech.Ndef;
54
import android.nfc.tech.TagTechnology;
55
import android.os.AsyncTask;
Kenny Root's avatar
Kenny Root committed
56
import android.os.Binder;
Jeff Hamilton's avatar
Jeff Hamilton committed
57
import android.os.Bundle;
58
import android.os.Handler;
59
import android.os.IBinder;
60
import android.os.Message;
61
import android.os.PowerManager;
62
import android.os.Process;
Nick Pelly's avatar
Nick Pelly committed
63
import android.os.RemoteException;
64
import android.os.ServiceManager;
65
import android.provider.Settings;
Nick Pelly's avatar
Nick Pelly committed
66 67
import android.util.Log;

68
import java.io.FileDescriptor;
69
import java.io.IOException;
70 71
import java.io.PrintWriter;
import java.util.Arrays;
72
import java.util.HashMap;
73
import java.util.HashSet;
74
import java.util.concurrent.ExecutionException;
75

76
public class NfcService extends Application implements DeviceHostListener {
Jason parks's avatar
Jason parks committed
77 78
    private static final String ACTION_MASTER_CLEAR_NOTIFICATION = "android.intent.action.MASTER_CLEAR_NOTIFICATION";

79
    static final boolean DBG = true;
80
    static final String TAG = "NfcService";
Jason parks's avatar
Jason parks committed
81

Jeff Hamilton's avatar
Jeff Hamilton committed
82
    public static final String SERVICE_NAME = "nfc";
Jason parks's avatar
Jason parks committed
83

Nick Pelly's avatar
Nick Pelly committed
84 85 86 87
    private static final String NFC_PERM = android.Manifest.permission.NFC;
    private static final String NFC_PERM_ERROR = "NFC permission required";
    private static final String ADMIN_PERM = android.Manifest.permission.WRITE_SECURE_SETTINGS;
    private static final String ADMIN_PERM_ERROR = "WRITE_SECURE_SETTINGS permission required";
Nick Pelly's avatar
Nick Pelly committed
88
    private static final String NFCEE_ADMIN_PERM = "com.android.nfc.permission.NFCEE_ADMIN";
89
    private static final String NFCEE_ADMIN_PERM_ERROR = "NFCEE_ADMIN permission required";
Nick Pelly's avatar
Nick Pelly committed
90

91
    public static final String PREF = "NfcServicePrefs";
Nick Pelly's avatar
Nick Pelly committed
92

93 94 95 96 97 98
    static final String PREF_NFC_ON = "nfc_on";
    static final boolean NFC_ON_DEFAULT = true;
    static final String PREF_NDEF_PUSH_ON = "ndef_push_on";
    static final boolean NDEF_PUSH_ON_DEFAULT = true;
    static final String PREF_FIRST_BEAM = "first_beam";
    static final String PREF_FIRST_BOOT = "first_boot";
Nick Pelly's avatar
Nick Pelly committed
99

100 101 102 103 104
    static final int MSG_NDEF_TAG = 0;
    static final int MSG_CARD_EMULATION = 1;
    static final int MSG_LLCP_LINK_ACTIVATION = 2;
    static final int MSG_LLCP_LINK_DEACTIVATED = 3;
    static final int MSG_TARGET_DESELECTED = 4;
Jeff Hamilton's avatar
Jeff Hamilton committed
105
    static final int MSG_MOCK_NDEF = 7;
106 107
    static final int MSG_SE_FIELD_ACTIVATED = 8;
    static final int MSG_SE_FIELD_DEACTIVATED = 9;
108 109 110
    static final int MSG_SE_APDU_RECEIVED = 10;
    static final int MSG_SE_EMV_CARD_REMOVAL = 11;
    static final int MSG_SE_MIFARE_ACCESS = 12;
111

112 113 114 115 116
    static final int TASK_ENABLE = 1;
    static final int TASK_DISABLE = 2;
    static final int TASK_BOOT = 3;
    static final int TASK_EE_WIPE = 4;

117 118 119 120
    // Copied from com.android.nfc_extras to avoid library dependency
    // Must keep in sync with com.android.nfc_extras
    static final int ROUTE_OFF = 1;
    static final int ROUTE_ON_WHEN_SCREEN_ON = 2;
Nick Pelly's avatar
Nick Pelly committed
121

122 123 124 125 126 127 128 129
    public static final String ACTION_RF_FIELD_ON_DETECTED =
        "com.android.nfc_extras.action.RF_FIELD_ON_DETECTED";
    public static final String ACTION_RF_FIELD_OFF_DETECTED =
        "com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED";
    public static final String ACTION_AID_SELECTED =
        "com.android.nfc_extras.action.AID_SELECTED";
    public static final String EXTRA_AID = "com.android.nfc_extras.extra.AID";

130 131 132 133 134 135 136 137 138 139 140 141 142
    public static final String ACTION_APDU_RECEIVED =
        "com.android.nfc_extras.action.APDU_RECEIVED";
    public static final String EXTRA_APDU_BYTES =
        "com.android.nfc_extras.extra.APDU_BYTES";

    public static final String ACTION_EMV_CARD_REMOVAL =
        "com.android.nfc_extras.action.EMV_CARD_REMOVAL";

    public static final String ACTION_MIFARE_ACCESS_DETECTED =
        "com.android.nfc_extras.action.MIFARE_ACCESS_DETECTED";
    public static final String EXTRA_MIFARE_BLOCK =
        "com.android.nfc_extras.extra.MIFARE_BLOCK";

143 144 145 146 147 148 149 150 151 152 153 154
    //TODO: dont hardcode this
    private static final byte[][] EE_WIPE_APDUS = {
        {(byte)0x00, (byte)0xa4, (byte)0x04, (byte)0x00, (byte)0x00},
        {(byte)0x00, (byte)0xa4, (byte)0x04, (byte)0x00, (byte)0x07, (byte)0xa0, (byte)0x00,
                (byte)0x00, (byte)0x04, (byte)0x76, (byte)0x20, (byte)0x10, (byte)0x00},
        {(byte)0x80, (byte)0xe2, (byte)0x01, (byte)0x03, (byte)0x00},
        {(byte)0x00, (byte)0xa4, (byte)0x04, (byte)0x00, (byte)0x00},
        {(byte)0x00, (byte)0xa4, (byte)0x04, (byte)0x00, (byte)0x07, (byte)0xa0, (byte)0x00,
                (byte)0x00, (byte)0x04, (byte)0x76, (byte)0x30, (byte)0x30, (byte)0x00},
        {(byte)0x80, (byte)0xb4, (byte)0x00, (byte)0x00, (byte)0x00},
        {(byte)0x00, (byte)0xa4, (byte)0x04, (byte)0x00, (byte)0x00},
    };
155 156 157

    // NFC Execution Environment
    // fields below are protected by this
158
    private NativeNfcSecureElement mSecureElement;
159 160
    private OpenSecureElement mOpenEe;  // null when EE closed
    private int mEeRoutingState;  // contactless interface routing
161

162 163 164
    // fields below must be used only on the UI thread and therefore aren't synchronized
    boolean mP2pStarted = false;

165 166
    // fields below are used in multiple threads and protected by synchronized(this)
    private final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();
167
    private HashSet<String> mSePackages = new HashSet<String>();
168
    private boolean mIsScreenUnlocked;
169
    private boolean mIsNdefPushEnabled;
170 171 172 173 174

    // mState is protected by this, however it is only modified in onCreate()
    // and the default AsyncTask thread so it is read unprotected from that
    // thread
    int mState;  // one of NfcAdapter.STATE_ON, STATE_TURNING_ON, etc
175 176

    // fields below are final after onCreate()
177
    Context mContext;
178
    private DeviceHost mDeviceHost;
Nick Pelly's avatar
Nick Pelly committed
179 180
    private SharedPreferences mPrefs;
    private SharedPreferences.Editor mPrefsEditor;
181
    private PowerManager.WakeLock mWakeLock;
182 183 184 185
    int mStartSound;
    int mEndSound;
    int mErrorSound;
    SoundPool mSoundPool; // playback synchronized on this
186
    P2pLinkManager mP2pLinkManager;
187 188 189
    TagService mNfcTagService;
    NfcAdapterService mNfcAdapter;
    NfcAdapterExtrasService mExtrasService;
190 191
    boolean mIsAirplaneSensitive;
    boolean mIsAirplaneToggleable;
Ben Dodson's avatar
Ben Dodson committed
192

193
    private NfcDispatcher mNfcDispatcher;
194
    private KeyguardManager mKeyguard;
Jeff Hamilton's avatar
Jeff Hamilton committed
195 196 197

    private static NfcService sService;

198 199 200 201 202 203 204 205 206 207 208 209 210
    public static void enforceAdminPerm(Context context) {
        int admin = context.checkCallingOrSelfPermission(ADMIN_PERM);
        int nfcee = context.checkCallingOrSelfPermission(NFCEE_ADMIN_PERM);
        if (admin != PackageManager.PERMISSION_GRANTED
                && nfcee != PackageManager.PERMISSION_GRANTED) {
            throw new SecurityException(ADMIN_PERM_ERROR);
        }
    }

    public static void enforceNfceeAdminPerm(Context context) {
        context.enforceCallingOrSelfPermission(NFCEE_ADMIN_PERM, NFCEE_ADMIN_PERM_ERROR);
    }

Jeff Hamilton's avatar
Jeff Hamilton committed
211 212 213
    public static NfcService getInstance() {
        return sService;
    }
Nick Pelly's avatar
Nick Pelly committed
214

215 216 217 218 219 220 221 222
    @Override
    public void onRemoteEndpointDiscovered(TagEndpoint tag) {
        sendMessage(NfcService.MSG_NDEF_TAG, tag);
    }

    /**
     * Notifies transaction
     */
223
    @Override
224 225 226 227 228 229 230
    public void onCardEmulationDeselected() {
        sendMessage(NfcService.MSG_TARGET_DESELECTED, null);
    }

    /**
     * Notifies transaction
     */
231
    @Override
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    public void onCardEmulationAidSelected(byte[] aid) {
        sendMessage(NfcService.MSG_CARD_EMULATION, aid);
    }

    /**
     * Notifies P2P Device detected, to activate LLCP link
     */
    @Override
    public void onLlcpLinkActivated(NfcDepEndpoint device) {
        sendMessage(NfcService.MSG_LLCP_LINK_ACTIVATION, device);
    }

    /**
     * Notifies P2P Device detected, to activate LLCP link
     */
247
    @Override
248 249 250 251
    public void onLlcpLinkDeactivated(NfcDepEndpoint device) {
        sendMessage(NfcService.MSG_LLCP_LINK_DEACTIVATED, device);
    }

252
    @Override
253 254 255 256
    public void onRemoteFieldActivated() {
        sendMessage(NfcService.MSG_SE_FIELD_ACTIVATED, null);
    }

257
    @Override
258 259 260 261
    public void onRemoteFieldDeactivated() {
        sendMessage(NfcService.MSG_SE_FIELD_DEACTIVATED, null);
    }

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    @Override
    public void onSeApduReceived(byte[] apdu) {
        sendMessage(NfcService.MSG_SE_APDU_RECEIVED, apdu);
    }

    @Override
    public void onSeEmvCardRemoval() {
        sendMessage(NfcService.MSG_SE_EMV_CARD_REMOVAL, null);
    }

    @Override
    public void onSeMifareAccess(byte[] block) {
        sendMessage(NfcService.MSG_SE_MIFARE_ACCESS, block);
    }

Nick Pelly's avatar
Nick Pelly committed
277 278
    @Override
    public void onCreate() {
279 280
        super.onCreate();

281 282
        mNfcTagService = new TagService();
        mNfcAdapter = new NfcAdapterService();
283
        mExtrasService = new NfcAdapterExtrasService();
284

285 286
        Log.i(TAG, "Starting NFC service");

Jeff Hamilton's avatar
Jeff Hamilton committed
287 288
        sService = this;

289 290 291 292 293
        mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
        mStartSound = mSoundPool.load(this, R.raw.start, 1);
        mEndSound = mSoundPool.load(this, R.raw.end, 1);
        mErrorSound = mSoundPool.load(this, R.raw.error, 1);

Nick Pelly's avatar
Nick Pelly committed
294
        mContext = this;
295
        mDeviceHost = new NativeNfcManager(this, this);
296

297 298
        mP2pLinkManager = new P2pLinkManager(mContext);
        mNfcDispatcher = new NfcDispatcher(this, mP2pLinkManager);
299

300
        mSecureElement = new NativeNfcSecureElement();
301
        mEeRoutingState = ROUTE_OFF;
302

303
        mPrefs = getSharedPreferences(PREF, Context.MODE_PRIVATE);
Nick Pelly's avatar
Nick Pelly committed
304
        mPrefsEditor = mPrefs.edit();
Nick Pelly's avatar
Nick Pelly committed
305

306
        mState = NfcAdapter.STATE_OFF;
307
        mIsNdefPushEnabled = mPrefs.getBoolean(PREF_NDEF_PUSH_ON, NDEF_PUSH_ON_DEFAULT);
Nick Pelly's avatar
Nick Pelly committed
308

309 310
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

311
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NfcService");
312
        mKeyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
313
        mIsScreenUnlocked = pm.isScreenOn() && !mKeyguard.isKeyguardLocked();
314

Jeff Hamilton's avatar
Jeff Hamilton committed
315
        ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
Nick Pelly's avatar
Nick Pelly committed
316

317
        IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
318 319
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
Jason parks's avatar
Jason parks committed
320
        filter.addAction(ACTION_MASTER_CLEAR_NOTIFICATION);
321
        filter.addAction(Intent.ACTION_USER_PRESENT);
322
        registerForAirplaneMode(filter);
323
        registerReceiver(mReceiver, filter);
Jason parks's avatar
Jason parks committed
324 325 326 327 328

        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");

329
        registerReceiver(mReceiver, filter);
Nick Pelly's avatar
Nick Pelly committed
330

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        new EnableDisableTask().execute(TASK_BOOT);  // do blocking boot tasks
    }

    void registerForAirplaneMode(IntentFilter filter) {
        final ContentResolver resolver = mContext.getContentResolver();
        final String airplaneModeRadios = Settings.System.getString(resolver,
                Settings.System.AIRPLANE_MODE_RADIOS);
        final String toggleableRadios = Settings.System.getString(resolver,
                Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);

        mIsAirplaneSensitive = airplaneModeRadios == null ? true :
                airplaneModeRadios.contains(Settings.System.RADIO_NFC);
        mIsAirplaneToggleable = toggleableRadios == null ? false :
            toggleableRadios.contains(Settings.System.RADIO_NFC);

        if (mIsAirplaneSensitive) {
            filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        }
    }

    /**
     * Manages tasks that involve turning on/off the NFC controller.
     *
     * <p>All work that might turn the NFC adapter on or off must be done
     * through this task, to keep the handling of mState simple.
     * In other words, mState is only modified in these tasks (and we
     * don't need a lock to read it in these tasks).
     *
     * <p>These tasks are all done on the same AsyncTask background
     * thread, so they are serialized. Each task may temporarily transition
     * mState to STATE_TURNING_OFF or STATE_TURNING_ON, but must exit in
     * either STATE_ON or STATE_OFF. This way each task can be guaranteed
     * of starting in either STATE_OFF or STATE_ON, without needing to hold
     * NfcService.this for the entire task.
     *
     * <p>AsyncTask's are also implicitly queued. This is useful for corner
     * cases like turning airplane mode on while TASK_ENABLE is in progress.
     * The TASK_DISABLE triggered by airplane mode will be correctly executed
     * immediately after TASK_ENABLE is complete. This seems like the most sane
     * way to deal with these situations.
     *
     * <p>{@link #TASK_ENABLE} enables the NFC adapter, without changing
     * preferences
     * <p>{@link #TASK_DISABLE} disables the NFC adapter, without changing
     * preferences
     * <p>{@link #TASK_BOOT} does first boot work and may enable NFC
     * <p>{@link #TASK_EE_WIPE} wipes the Execution Environment, and in the
     * process may temporarily enable the NFC adapter
     */
    class EnableDisableTask extends AsyncTask<Integer, Void, Void> {
        @Override
        protected Void doInBackground(Integer... params) {
            // Sanity check mState
            switch (mState) {
                case NfcAdapter.STATE_TURNING_OFF:
                case NfcAdapter.STATE_TURNING_ON:
                    Log.e(TAG, "Processing EnableDisable task " + params[0] + " from bad state " +
                            mState);
                    return null;
            }

392 393 394 395 396 397 398 399 400
            /* AsyncTask sets this thread to THREAD_PRIORITY_BACKGROUND,
             * override with the default. THREAD_PRIORITY_BACKGROUND causes
             * us to service software I2C too slow for firmware download
             * with the NXP PN544.
             * TODO: move this to the DAL I2C layer in libnfc-nxp, since this
             * problem only occurs on I2C platforms using PN544
             */
            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);

401 402 403 404 405 406 407 408
            switch (params[0].intValue()) {
                case TASK_ENABLE:
                    enableInternal();
                    break;
                case TASK_DISABLE:
                    disableInternal();
                    break;
                case TASK_BOOT:
409
                    Log.d(TAG,"checking on firmware download");
410 411
                    if (mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT) &&
                            !(mIsAirplaneSensitive && isAirplaneModeOn())) {
412
                        Log.d(TAG,"NFC is on. Doing normal stuff");
413
                        enableInternal();
414 415 416
                    } else {
                        Log.d(TAG,"NFC is off.  Checking firmware version");
                        mDeviceHost.checkFirmware();
417 418 419 420 421 422 423 424 425 426 427 428
                    }
                    if (mPrefs.getBoolean(PREF_FIRST_BOOT, true)) {
                        Log.i(TAG, "First Boot");
                        mPrefsEditor.putBoolean(PREF_FIRST_BOOT, false);
                        mPrefsEditor.apply();
                        executeEeWipe();
                    }
                    break;
                case TASK_EE_WIPE:
                    executeEeWipe();
                    break;
            }
429 430 431

            // Restore default AsyncTask priority
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
            return null;
        }

        /**
         * Enable NFC adapter functions.
         * Does not toggle preferences.
         */
        boolean enableInternal() {
            if (mState == NfcAdapter.STATE_ON) {
                return true;
            }
            Log.i(TAG, "Enabling NFC");
            updateState(NfcAdapter.STATE_TURNING_ON);

            if (!mDeviceHost.initialize()) {
                Log.w(TAG, "Error enabling NFC");
                updateState(NfcAdapter.STATE_OFF);
                return false;
            }

            synchronized(NfcService.this) {
                mObjectMap.clear();

455
                mP2pLinkManager.enableDisable(mIsNdefPushEnabled, true);
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
                updateState(NfcAdapter.STATE_ON);
            }

            /* Start polling loop */
            applyRouting();
            return true;
        }

        /**
         * Disable all NFC adapter functions.
         * Does not toggle preferences.
         */
        boolean disableInternal() {
            if (mState == NfcAdapter.STATE_OFF) {
                return true;
            }
            Log.i(TAG, "Disabling NFC");
            updateState(NfcAdapter.STATE_TURNING_OFF);

            /* Sometimes mDeviceHost.deinitialize() hangs, use a watch-dog.
             * Implemented with a new thread (instead of a Handler or AsyncTask),
             * because the UI Thread and AsyncTask thread-pools can also get hung
             * when the NFC controller stops responding */
            WatchDogThread watchDog = new WatchDogThread();
            watchDog.start();

482
            mP2pLinkManager.enableDisable(false, false);
483 484 485 486 487 488 489 490

            // Stop watchdog if tag present
            // A convenient way to stop the watchdog properly consists of
            // disconnecting the tag. The polling loop shall be stopped before
            // to avoid the tag being discovered again.
            applyRouting();
            maybeDisconnectTarget();

491
            mNfcDispatcher.setForegroundDispatch(null, null, null);
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

            boolean result = mDeviceHost.deinitialize();
            if (DBG) Log.d(TAG, "mDeviceHost.deinitialize() = " + result);

            watchDog.cancel();

            updateState(NfcAdapter.STATE_OFF);

            return result;
        }

        void executeEeWipe() {
            // TODO: read SE reset list from /system/etc
            byte[][]apdus = EE_WIPE_APDUS;

            boolean tempEnable = mState == NfcAdapter.STATE_OFF;
            if (tempEnable) {
                if (!enableInternal()) {
510
                    Log.w(TAG, "Could not enable NFC to wipe NFC-EE");
511
                    return;
Nick Pelly's avatar
Nick Pelly committed
512 513
                }
            }
514 515 516 517 518 519 520 521 522 523 524 525 526
            Log.i(TAG, "Executing SE wipe");
            int handle = mSecureElement.doOpenSecureElementConnection();
            if (handle == 0) {
                Log.w(TAG, "Could not open the secure element");
                if (tempEnable) {
                    disableInternal();
                }
                return;
            }

            mDeviceHost.setTimeout(TagTechnology.ISO_DEP, 10000);

            for (byte[] cmd : apdus) {
527 528 529 530 531
                byte[] resp = mSecureElement.doTransceive(handle, cmd);
                if (resp == null) {
                    Log.w(TAG, "Transceive failed, could not wipe NFC-EE");
                    break;
                }
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
            }

            mDeviceHost.resetTimeouts();
            mSecureElement.doDisconnect(handle);

            if (tempEnable) {
                disableInternal();
            }
        }

        void updateState(int newState) {
            synchronized (this) {
                if (newState == mState) {
                    return;
                }
                mState = newState;
                Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
                intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
                intent.putExtra(NfcAdapter.EXTRA_ADAPTER_STATE, mState);
                mContext.sendBroadcast(intent);
            }
        }
    }

    void saveNfcOnSetting(boolean on) {
        synchronized (NfcService.this) {
            mPrefsEditor.putBoolean(PREF_NFC_ON, on);
            mPrefsEditor.apply();
        }
Nick Pelly's avatar
Nick Pelly committed
561 562
    }

563
    void playSound(int sound) {
564 565 566 567 568
        synchronized (this) {
            mSoundPool.play(sound, 1.0f, 1.0f, 0, 0, 1.0f);
        }
    }

Nick Pelly's avatar
Nick Pelly committed
569
    @Override
570 571 572
    public void onTerminate() {
        super.onTerminate();
        // NFC application is persistent, it should not be destroyed by framework
Nick Pelly's avatar
Nick Pelly committed
573 574 575
        Log.wtf(TAG, "NFC service is under attack!");
    }

576
    final class NfcAdapterService extends INfcAdapter.Stub {
Jason parks's avatar
Jason parks committed
577
        @Override
Nick Pelly's avatar
Nick Pelly committed
578
        public boolean enable() throws RemoteException {
579
            NfcService.enforceAdminPerm(mContext);
Nick Pelly's avatar
Nick Pelly committed
580

581 582 583 584
            saveNfcOnSetting(true);
            if (mIsAirplaneSensitive && isAirplaneModeOn() && !mIsAirplaneToggleable) {
                Log.i(TAG, "denying enable() request (airplane mode)");
                return false;
Nick Pelly's avatar
Nick Pelly committed
585
            }
586 587 588
            new EnableDisableTask().execute(TASK_ENABLE);

            return true;
Nick Pelly's avatar
Nick Pelly committed
589 590
        }

Jason parks's avatar
Jason parks committed
591
        @Override
Nick Pelly's avatar
Nick Pelly committed
592
        public boolean disable() throws RemoteException {
593
            NfcService.enforceAdminPerm(mContext);
Nick Pelly's avatar
Nick Pelly committed
594

595 596 597 598
            saveNfcOnSetting(false);
            new EnableDisableTask().execute(TASK_DISABLE);

            return true;
Nick Pelly's avatar
Nick Pelly committed
599 600
        }

601
        @Override
602
        public boolean isNdefPushEnabled() throws RemoteException {
603
            synchronized (NfcService.this) {
604
                return mIsNdefPushEnabled;
605
            }
606 607 608
        }

        @Override
609
        public boolean enableNdefPush() throws RemoteException {
610 611
            NfcService.enforceAdminPerm(mContext);
            synchronized(NfcService.this) {
612
                if (mIsNdefPushEnabled) {
613 614
                    return true;
                }
615 616
                Log.i(TAG, "enabling NDEF Push");
                mPrefsEditor.putBoolean(PREF_NDEF_PUSH_ON, true);
617
                mPrefsEditor.apply();
618
                mIsNdefPushEnabled = true;
619
                if (isNfcEnabled()) {
620
                    mP2pLinkManager.enableDisable(true, true);
621 622 623 624 625 626
                }
            }
            return true;
        }

        @Override
627
        public boolean disableNdefPush() throws RemoteException {
628 629
            NfcService.enforceAdminPerm(mContext);
            synchronized(NfcService.this) {
630
                if (!mIsNdefPushEnabled) {
631 632
                    return true;
                }
633 634
                Log.i(TAG, "disabling NDEF Push");
                mPrefsEditor.putBoolean(PREF_NDEF_PUSH_ON, false);
635
                mPrefsEditor.apply();
636
                mIsNdefPushEnabled = false;
637
                if (isNfcEnabled()) {
638
                    mP2pLinkManager.enableDisable(false, true);
639 640 641 642 643
                }
            }
            return true;
        }

644
        @Override
645
        public void setForegroundDispatch(PendingIntent intent,
646
                IntentFilter[] filters, TechListParcel techListsParcel) {
647
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Jeff Hamilton's avatar
Jeff Hamilton committed
648

649 650 651 652
            // Short-cut the disable path
            if (intent == null && filters == null && techListsParcel == null) {
                mNfcDispatcher.setForegroundDispatch(null, null, null);
                return;
653
            }
Jeff Hamilton's avatar
Jeff Hamilton committed
654 655 656 657 658 659 660 661 662 663 664 665 666 667

            // Validate the IntentFilters
            if (filters != null) {
                if (filters.length == 0) {
                    filters = null;
                } else {
                    for (IntentFilter filter : filters) {
                        if (filter == null) {
                            throw new IllegalArgumentException("null IntentFilter");
                        }
                    }
                }
            }

668 669 670 671 672
            // Validate the tech lists
            String[][] techLists = null;
            if (techListsParcel != null) {
                techLists = techListsParcel.getTechLists();
            }
673

674
            mNfcDispatcher.setForegroundDispatch(intent, filters, techLists);
675 676
        }

677
        @Override
678
        public void setForegroundNdefPush(NdefMessage msg, INdefPushCallback callback) {
679
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
680
            mP2pLinkManager.setNdefToSend(msg, callback);
681 682
        }

Jason parks's avatar
Jason parks committed
683
        @Override
Nick Pelly's avatar
Nick Pelly committed
684
        public INfcTag getNfcTagInterface() throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
685
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
686 687 688
            return mNfcTagService;
        }

Jason parks's avatar
Jason parks committed
689
        @Override
690
        public INfcAdapterExtras getNfcAdapterExtrasInterface() {
691
            NfcService.enforceNfceeAdminPerm(mContext);
692
            return mExtrasService;
693 694
        }

Jason parks's avatar
Jason parks committed
695
        @Override
696 697 698 699 700 701 702 703 704
        public int getState() throws RemoteException {
            synchronized (NfcService.this) {
                return mState;
            }
        }

        @Override
        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
            NfcService.this.dump(fd, pw, args);
Nick Pelly's avatar
Nick Pelly committed
705 706 707
        }
    };

708
    final class TagService extends INfcTag.Stub {
Jason parks's avatar
Jason parks committed
709
        @Override
Nick Pelly's avatar
Nick Pelly committed
710
        public int close(int nativeHandle) throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
711
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
712

713
            TagEndpoint tag = null;
Nick Pelly's avatar
Nick Pelly committed
714

715
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
716 717 718 719
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
720
            tag = (TagEndpoint) findObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
721
            if (tag != null) {
722 723
                /* Remove the device from the hmap */
                unregisterObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
724
                tag.disconnect();
725
                return ErrorCodes.SUCCESS;
Nick Pelly's avatar
Nick Pelly committed
726 727
            }
            /* Restart polling loop for notification */
728
            applyRouting();
Nick Pelly's avatar
Nick Pelly committed
729 730 731
            return ErrorCodes.ERROR_DISCONNECT;
        }

Jason parks's avatar
Jason parks committed
732
        @Override
733
        public int connect(int nativeHandle, int technology) throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
734
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
735

736
            TagEndpoint tag = null;
Nick Pelly's avatar
Nick Pelly committed
737

738
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
739 740 741 742
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
743
            tag = (TagEndpoint) findObject(nativeHandle);
744 745
            if (tag == null) {
                return ErrorCodes.ERROR_DISCONNECT;
Nick Pelly's avatar
Nick Pelly committed
746
            }
747

748 749 750 751
            if (technology == TagTechnology.NFC_B) {
                return ErrorCodes.ERROR_NOT_SUPPORTED;
            }

752 753 754 755 756 757 758 759
            // Note that on most tags, all technologies are behind a single
            // handle. This means that the connect at the lower levels
            // will do nothing, as the tag is already connected to that handle.
            if (tag.connect(technology)) {
                return ErrorCodes.SUCCESS;
            } else {
                return ErrorCodes.ERROR_DISCONNECT;
            }
Nick Pelly's avatar
Nick Pelly committed
760 761
        }

762 763 764 765
        @Override
        public int reconnect(int nativeHandle) throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

766
            TagEndpoint tag = null;
767 768

            // Check if NFC is enabled
769
            if (!isNfcEnabled()) {
770 771 772 773
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
774
            tag = (TagEndpoint) findObject(nativeHandle);
775 776 777 778 779 780 781 782 783 784
            if (tag != null) {
                if (tag.reconnect()) {
                    return ErrorCodes.SUCCESS;
                } else {
                    return ErrorCodes.ERROR_DISCONNECT;
                }
            }
            return ErrorCodes.ERROR_DISCONNECT;
        }

Jason parks's avatar
Jason parks committed
785
        @Override
Jeff Hamilton's avatar
Jeff Hamilton committed
786
        public int[] getTechList(int nativeHandle) throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
787
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
788

Nick Pelly's avatar
Nick Pelly committed
789
            // Check if NFC is enabled
790
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
791 792 793 794
                return null;
            }

            /* find the tag in the hmap */
795
            TagEndpoint tag = (TagEndpoint) findObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
796
            if (tag != null) {
Jeff Hamilton's avatar
Jeff Hamilton committed
797
                return tag.getTechList();
Nick Pelly's avatar
Nick Pelly committed
798 799 800 801
            }
            return null;
        }

Jason parks's avatar
Jason parks committed
802
        @Override
Nick Pelly's avatar
Nick Pelly committed
803
        public byte[] getUid(int nativeHandle) throws RemoteException {
804
            TagEndpoint tag = null;
Nick Pelly's avatar
Nick Pelly committed
805 806 807
            byte[] uid;

            // Check if NFC is enabled
808
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
809 810 811 812
                return null;
            }

            /* find the tag in the hmap */
813
            tag = (TagEndpoint) findObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
814 815 816 817 818 819 820
            if (tag != null) {
                uid = tag.getUid();
                return uid;
            }
            return null;
        }

Jason parks's avatar
Jason parks committed
821
        @Override
822
        public boolean isPresent(int nativeHandle) throws RemoteException {
823
            TagEndpoint tag = null;
824 825

            // Check if NFC is enabled
826
            if (!isNfcEnabled()) {
827 828 829 830
                return false;
            }

            /* find the tag in the hmap */
831
            tag = (TagEndpoint) findObject(nativeHandle);
832 833 834 835
            if (tag == null) {
                return false;
            }

836
            return tag.isPresent();
837 838
        }

Jason parks's avatar
Jason parks committed
839
        @Override
Nick Pelly's avatar
Nick Pelly committed
840
        public boolean isNdef(int nativeHandle) throws RemoteException {
841
            TagEndpoint tag = null;
Nick Pelly's avatar
Nick Pelly committed
842 843

            // Check if NFC is enabled
844
            if (!isNfcEnabled()) {
845
                return false;
Nick Pelly's avatar
Nick Pelly committed
846 847 848
            }

            /* find the tag in the hmap */
849
            tag = (TagEndpoint) findObject(nativeHandle);
850
            int[] ndefInfo = new int[2];
851 852
            if (tag == null) {
                return false;
Nick Pelly's avatar
Nick Pelly committed
853
            }
854
            return tag.checkNdef(ndefInfo);
Nick Pelly's avatar
Nick Pelly committed
855 856
        }

Jason parks's avatar
Jason parks committed
857
        @Override
858
        public TransceiveResult transceive(int nativeHandle, byte[] data, boolean raw)
859
                throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
860
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
861

862
            TagEndpoint tag = null;
Nick Pelly's avatar
Nick Pelly committed
863 864 865
            byte[] response;

            // Check if NFC is enabled
866
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
867 868 869 870
                return null;
            }

            /* find the tag in the hmap */
871
            tag = (TagEndpoint) findObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
872
            if (tag != null) {
873 874 875 876
                // Check if length is within limits
                if (data.length > getMaxTransceiveLength(tag.getConnectedTechnology())) {
                    return new TransceiveResult(TransceiveResult.RESULT_EXCEEDED_LENGTH, null);
                }
877 878
                int[] targetLost = new int[1];
                response = tag.transceive(data, raw, targetLost);
879 880 881 882 883 884 885 886 887
                int result;
                if (response != null) {
                    result = TransceiveResult.RESULT_SUCCESS;
                } else if (targetLost[0] == 1) {
                    result = TransceiveResult.RESULT_TAGLOST;
                } else {
                    result = TransceiveResult.RESULT_FAILURE;
                }
                return new TransceiveResult(result, response);
Nick Pelly's avatar
Nick Pelly committed
888 889 890 891
            }
            return null;
        }

Jason parks's avatar
Jason parks committed
892
        @Override
893
        public NdefMessage ndefRead(int nativeHandle) throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
894
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
895

896
            TagEndpoint tag;
Nick Pelly's avatar
Nick Pelly committed
897 898

            // Check if NFC is enabled
899
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
900 901 902 903
                return null;
            }

            /* find the tag in the hmap */
904
            tag = (TagEndpoint) findObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
905
            if (tag != null) {
906 907
                byte[] buf = tag.readNdef();
                if (buf == null) {
Nick Pelly's avatar
Nick Pelly committed
908
                    return null;
909
                }
Nick Pelly's avatar
Nick Pelly committed
910 911 912 913 914 915 916 917 918 919 920

                /* Create an NdefMessage */
                try {
                    return new NdefMessage(buf);
                } catch (FormatException e) {
                    return null;
                }
            }
            return null;
        }

Jason parks's avatar
Jason parks committed
921
        @Override
922
        public int ndefWrite(int nativeHandle, NdefMessage msg) throws RemoteException {
Jeff Hamilton's avatar
Jeff Hamilton committed
923
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
Nick Pelly's avatar
Nick Pelly committed
924

925
            TagEndpoint tag;
Nick Pelly's avatar
Nick Pelly committed
926 927

            // Check if NFC is enabled
928
            if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
929 930 931 932
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
933
            tag = (TagEndpoint) findObject(nativeHandle);
Nick Pelly's avatar
Nick Pelly committed
934 935 936 937
            if (tag == null) {
                return ErrorCodes.ERROR_IO;
            }

938
            if (tag.writeNdef(msg.toByteArray())) {
Nick Pelly's avatar
Nick Pelly committed
939
                return ErrorCodes.SUCCESS;
940
            } else {
Nick Pelly's avatar
Nick Pelly committed
941 942 943 944 945
                return ErrorCodes.ERROR_IO;
            }

        }

Jason parks's avatar
Jason parks committed
946
        @Override
Nick Pelly's avatar
Nick Pelly committed
947
        public int getLastError(int nativeHandle) throws RemoteException {
948
            return(mDeviceHost.doGetLastError());
Nick Pelly's avatar
Nick Pelly committed
949 950
        }

Jason parks's avatar
Jason parks committed
951
        @Override
952 953
        public boolean ndefIsWritable(int nativeHandle) throws RemoteException {
            throw new UnsupportedOperationException();
Nick Pelly's avatar
Nick Pelly committed
954 955
        }

Jason parks's avatar
Jason parks committed
956
        @Override
957
        public int ndefMakeReadOnly(int nativeHandle) throws RemoteException {
958 959
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

960
            TagEndpoint tag;
961 962

            // Check if NFC is enabled
963
            if (!isNfcEnabled()) {
964 965 966 967
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
968
            tag = (TagEndpoint) findObject(nativeHandle);
969 970 971 972
            if (tag == null) {
                return ErrorCodes.ERROR_IO;
            }

973
            if (tag.makeReadOnly()) {
974
                return ErrorCodes.SUCCESS;
975
            } else {
976 977
                return ErrorCodes.ERROR_IO;
            }
Nick Pelly's avatar
Nick Pelly committed
978 979
        }

980 981 982 983
        @Override
        public int formatNdef(int nativeHandle, byte[] key) throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

984
            TagEndpoint tag;
985 986

            // Check if NFC is enabled
987
            if (!isNfcEnabled()) {
988 989 990 991
                return ErrorCodes.ERROR_NOT_INITIALIZED;
            }

            /* find the tag in the hmap */
992
            tag = (TagEndpoint) findObject(nativeHandle);
993 994 995 996 997 998
            if (tag == null) {
                return ErrorCodes.ERROR_IO;
            }

            if (tag.formatNdef(key)) {
                return ErrorCodes.SUCCESS;
999
            } else {
1000 1001 1002 1003
                return ErrorCodes.ERROR_IO;
            }
        }

1004 1005 1006 1007
        @Override
        public Tag rediscover(int nativeHandle) throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

1008
            TagEndpoint tag = null;
1009 1010

            // Check if NFC is enabled
1011
            if (!isNfcEnabled()) {
1012 1013 1014 1015
                return null;
            }

            /* find the tag in the hmap */
1016
            tag = (TagEndpoint) findObject(nativeHandle);
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
            if (tag != null) {
                // For now the prime usecase for rediscover() is to be able
                // to access the NDEF technology after formatting without
                // having to remove the tag from the field, or similar
                // to have access to NdefFormatable in case low-level commands
                // were used to remove NDEF. So instead of doing a full stack
                // rediscover (which is poorly supported at the moment anyway),
                // we simply remove these two technologies and detect them
                // again.
                tag.removeTechnology(TagTechnology.NDEF);
                tag.removeTechnology(TagTechnology.NDEF_FORMATABLE);
1028
                NdefMessage[] msgs = tag.findAndReadNdef();
1029 1030
                // Build a new Tag object to return
                Tag newTag = new Tag(tag.getUid(), tag.getTechList(),
1031
                        tag.getTechExtras(), tag.getHandle(), this);
1032 1033 1034 1035 1036
                return newTag;
            }
            return null;
        }

1037
        @Override
1038
        public int setTimeout(int tech, int timeout) throws RemoteException {
1039
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
1040
            boolean success = mDeviceHost.setTimeout(tech, timeout);
1041 1042 1043 1044 1045
            if (success) {
                return ErrorCodes.SUCCESS;
            } else {
                return ErrorCodes.ERROR_INVALID_PARAM;
            }
1046 1047
        }

1048 1049 1050 1051 1052 1053 1054
        @Override
        public int getTimeout(int tech) throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

            return mDeviceHost.getTimeout(tech);
        }

1055 1056 1057 1058
        @Override
        public void resetTimeouts() throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

1059
            mDeviceHost.resetTimeouts();
1060
        }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

        @Override
        public boolean canMakeReadOnly(int ndefType) throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

            return mDeviceHost.canMakeReadOnly(ndefType);
        }

        @Override
        public int getMaxTransceiveLength(int tech) throws RemoteException {
            mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);

            return mDeviceHost.getMaxTransceiveLength(tech);
        }
Nick Pelly's avatar
Nick Pelly committed
1075
    };
Nick Pelly's avatar
Nick Pelly committed
1076

1077 1078 1079 1080 1081 1082
    private void _nfcEeClose(boolean checkPid, int callingPid) throws IOException {
        // Blocks until a pending open() or transceive() times out.
        //TODO: This is incorrect behavior - the close should interrupt pending
        // operations. However this is not supported by current hardware.

        synchronized(NfcService.this) {
1083
            if (!isNfcEnabled()) {
1084 1085 1086 1087 1088 1089 1090 1091 1092
                throw new IOException("NFC adapter is disabled");
            }
            if (mOpenEe == null) {
                throw new IOException("NFC EE closed");
            }
            if (checkPid && mOpenEe.pid != -1 && callingPid != mOpenEe.pid) {
                throw new SecurityException("Wrong PID");
            }

1093
            mDeviceHost.resetTimeouts();
1094 1095 1096 1097 1098 1099 1100
            mSecureElement.doDisconnect(mOpenEe.handle);
            mOpenEe = null;

            applyRouting();
        }
    }

1101
    final class NfcAdapterExtrasService extends INfcAdapterExtras.Stub {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
        private Bundle writeNoException() {
            Bundle p = new Bundle();
            p.putInt("e", 0);
            return p;
        }
        private Bundle writeIoException(IOException e) {
            Bundle p = new Bundle();
            p.putInt("e", -1);
            p.putString("m", e.getMessage());
            return p;
        }
1113

Jason parks's avatar
Jason parks committed
1114
        @Override
1115
        public Bundle open(IBinder b) throws RemoteException {
1116
            NfcService.enforceNfceeAdminPerm(mContext);
Nick Pelly's avatar
Nick Pelly committed
1117

1118 1119 1120 1121 1122 1123
            Bundle result;
            try {
                _open(b);
                result = writeNoException();
            } catch (IOException e) {
                result = writeIoException(e);
1124
            }
1125 1126
            return result;
        }
1127

1128 1129
        private void _open(IBinder b) throws IOException, RemoteException {
            synchronized(NfcService.this) {
1130
                if (!isNfcEnabled()) {
1131 1132 1133 1134 1135
                    throw new IOException("NFC adapter is disabled");
                }
                if (mOpenEe != null) {
                    throw new IOException("NFC EE already open");
                }
1136

1137 1138 1139 1140
                int handle = mSecureElement.doOpenSecureElementConnection();
                if (handle == 0) {
                    throw new IOException("NFC EE failed to open");
                }
1141
                mDeviceHost.setTimeout(TagTechnology.ISO_DEP, 10000);
1142

1143 1144 1145 1146 1147 1148
                mOpenEe = new OpenSecureElement(getCallingPid(), handle);
                try {
                    b.linkToDeath(mOpenEe, 0);
                } catch (RemoteException e) {
                    mOpenEe.binderDied();
                }
1149 1150 1151 1152 1153 1154

                // Add the calling package to the list of packages that have accessed
                // the secure element.
                for (String packageName : getPackageManager().getPackagesForUid(getCallingUid())) {
                    mSePackages.add(packageName);
                }
1155
           }
1156 1157
        }

Jason parks's avatar
Jason parks committed
1158
        @Override
1159
        public Bundle close() throws RemoteException {
1160
            NfcService.enforceNfceeAdminPerm(mContext);
1161

1162 1163
            Bundle result;
            try {
1164
                _nfcEeClose(true, getCallingPid());
1165 1166 1167
                result = writeNoException();
            } catch (IOException e) {
                result = writeIoException(e);
1168
            }
1169 1170
            return result;
        }
1171

Jason parks's avatar
Jason parks committed
1172
        @Override
1173
        public Bundle transceive(byte[] in) throws RemoteException {
1174
            NfcService.enforceNfceeAdminPerm(mContext);
Nick Pelly's avatar
Nick Pelly committed
1175

1176 1177 1178 1179 1180 1181 1182 1183
            Bundle result;
            byte[] out;
            try {
                out = _transceive(in);
                result = writeNoException();
                result.putByteArray("out", out);
            } catch (IOException e) {
                result = writeIoException(e);
1184
            }
1185 1186
            return result;
        }
1187

1188 1189
        private byte[] _transceive(byte[] data) throws IOException, RemoteException {
            synchronized(NfcService.this) {
1190
                if (!isNfcEnabled()) {
1191 1192 1193 1194 1195 1196 1197 1198
                    throw new IOException("NFC is not enabled");
                }
                if (mOpenEe == null){
                    throw new IOException("NFC EE is not open");
                }
                if (getCallingPid() != mOpenEe.pid) {
                    throw new SecurityException("Wrong PID");
                }
1199 1200
            }

1201
            return mSecureElement.doTransceive(mOpenEe.handle, data);
1202 1203
        }

Jason parks's avatar
Jason parks committed
1204
        @Override
1205
        public int getCardEmulationRoute() throws RemoteException {
1206
            NfcService.enforceNfceeAdminPerm(mContext);
1207
            return mEeRoutingState;
1208 1209
        }

Jason parks's avatar
Jason parks committed
1210
        @Override
1211
        public void setCardEmulationRoute(int route) throws RemoteException {
1212
            NfcService.enforceNfceeAdminPerm(mContext);
1213 1214
            mEeRoutingState = route;
            applyRouting();
1215
        }
Jason parks's avatar
Jason parks committed
1216 1217

        @Override
1218
        public void authenticate(byte[] token) throws RemoteException {
Jason parks's avatar
Jason parks committed
1219 1220
            NfcService.enforceNfceeAdminPerm(mContext);
        }
1221 1222
    };

1223 1224 1225 1226 1227 1228 1229 1230
    /** resources kept while secure element is open */
    private class OpenSecureElement implements IBinder.DeathRecipient {
        public int pid;  // pid that opened SE
        public int handle; // low-level handle
        public OpenSecureElement(int pid, int handle) {
            this.pid = pid;
            this.handle = handle;
        }
Jason parks's avatar
Jason parks committed
1231
        @Override
1232 1233 1234 1235
        public void binderDied() {
            synchronized (NfcService.this) {
                if (DBG) Log.d(TAG, "Tracked app " + pid + " died");
                pid = -1;
1236
                try {
1237 1238
                    _nfcEeClose(false, -1);
                } catch (IOException e) { /* already closed */ }
1239 1240 1241 1242
            }
        }
    }

1243 1244 1245
    boolean isNfcEnabled() {
        synchronized (this) {
            return mState == NfcAdapter.STATE_ON;
1246
        }
1247 1248
    }

1249
    class WatchDogThread extends Thread {
Nick Pelly's avatar
Nick Pelly committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
        boolean mWatchDogCanceled = false;
        @Override
        public void run() {
            boolean slept = false;
            while (!slept) {
                try {
                    Thread.sleep(10000);
                    slept = true;
                } catch (InterruptedException e) { }
            }
            synchronized (this) {
                if (!mWatchDogCanceled) {
                    // Trigger watch-dog
                    Log.e(TAG, "Watch dog triggered");
1264
                    mDeviceHost.doAbort();
Nick Pelly's avatar
Nick Pelly committed
1265 1266 1267 1268 1269 1270 1271 1272
                }
            }
        }
        public synchronized void cancel() {
            mWatchDogCanceled = true;
        }
    }

1273
    /** apply NFC discovery and EE routing */
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
    void applyRouting() {
        synchronized (this) {
            if (!isNfcEnabled() || mOpenEe != null) {
                return;
            }
            if (mIsScreenUnlocked) {
                if (mEeRoutingState == ROUTE_ON_WHEN_SCREEN_ON) {
                    Log.d(TAG, "NFC-EE routing ON");
                    mDeviceHost.doSelectSecureElement();
                } else {
                    Log.d(TAG, "NFC-EE routing OFF");
                    mDeviceHost.doDeselectSecureElement();
                }
                Log.d(TAG, "NFC-C polling ON");
                mDeviceHost.enableDiscovery();
1289
            } else {
1290
                Log.d(TAG, "NFC-EE routing OFF");
1291
                mDeviceHost.doDeselectSecureElement();
1292 1293
                Log.d(TAG, "NFC-C polling OFF");
                mDeviceHost.disableDiscovery();
1294
            }
1295 1296 1297
        }
    }

Arnaud Ferir's avatar
Arnaud Ferir committed
1298
    /** Disconnect any target if present */
1299 1300
    void maybeDisconnectTarget() {
        if (!isNfcEnabled()) {
Nick Pelly's avatar
Nick Pelly committed
1301 1302
            return;
        }
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
        Object[] objectsToDisconnect;
        synchronized (this) {
            Object[] objectValues = mObjectMap.values().toArray();
            // Copy the array before we clear mObjectMap,
            // just in case the HashMap values are backed by the same array
            objectsToDisconnect = Arrays.copyOf(objectValues, objectValues.length);
            mObjectMap.clear();
        }
        for (Object o : objectsToDisconnect) {
            if (DBG) Log.d(TAG, "disconnecting " + o.getClass().getName());
            if (o instanceof TagEndpoint) {
                // Disconnect from tags
                TagEndpoint tag = (TagEndpoint) o;
                tag.disconnect();
            } else if (o instanceof NfcDepEndpoint) {
                // Disconnect from P2P devices
                NfcDepEndpoint device = (NfcDepEndpoint) o;
                if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
                    // Remote peer is target, request disconnection
                    device.disconnect();
                } else {
                    // Remote peer is initiator, we cannot disconnect
                    // Just wait for field removal
Jason parks's avatar
Jason parks committed
1326 1327 1328 1329 1330
                }
            }
        }
    }

1331 1332 1333 1334 1335
    Object findObject(int key) {
        synchronized (this) {
            Object device = mObjectMap.get(key);
            if (device == null) {
                Log.w(TAG, "Handle not found");
1336
            }
1337
            return device;
Nick Pelly's avatar
Nick Pelly committed
1338
        }
Nick Pelly's avatar
Nick Pelly committed
1339 1340
    }

1341 1342 1343
    void registerTagObject(TagEndpoint tag) {
        synchronized (this) {
            mObjectMap.put(tag.getHandle(), tag);
Nick Pelly's avatar
Nick Pelly committed
1344
        }
1345 1346
    }

1347 1348 1349 1350
    void unregisterObject(int handle) {
        synchronized (this) {
            mObjectMap.remove(handle);
        }
Nick Pelly's avatar
Nick Pelly committed
1351 1352
    }

Jeff Hamilton's avatar
Jeff Hamilton committed
1353
    /** For use by code in this process */
1354 1355 1356
    public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
            throws IOException, LlcpException {
        return mDeviceHost.createLlcpSocket(sap, miu, rw, linearBufferLength);
Jeff Hamilton's avatar
Jeff Hamilton committed
1357 1358 1359
    }

    /** For use by code in this process */
1360 1361 1362
    public LlcpServerSocket createLlcpServerSocket(int sap, String sn, int miu, int rw,
            int linearBufferLength) throws IOException, LlcpException {
        return mDeviceHost.createLlcpServerSocket(sap, sn, miu, rw, linearBufferLength);
Jeff Hamilton's avatar
Jeff Hamilton committed
1363 1364
    }

1365
    public void sendMockNdefTag(NdefMessage msg) {
Jeff Hamilton's avatar
Jeff Hamilton committed
1366
        sendMessage(MSG_MOCK_NDEF, msg);
1367 1368
    }

1369 1370 1371 1372 1373 1374 1375
    void sendMessage(int what, Object obj) {
        Message msg = mHandler.obtainMessage();
        msg.what = what;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

1376
    final class NfcServiceHandler extends Handler {
1377 1378
        @Override
        public void handleMessage(Message msg) {
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
            switch (msg.what) {
                case MSG_MOCK_NDEF: {
                    NdefMessage ndefMsg = (NdefMessage) msg.obj;
                    Bundle extras = new Bundle();
                    extras.putParcelable(Ndef.EXTRA_NDEF_MSG, ndefMsg);
                    extras.putInt(Ndef.EXTRA_NDEF_MAXLENGTH, 0);
                    extras.putInt(Ndef.EXTRA_NDEF_CARDSTATE, Ndef.NDEF_MODE_READ_ONLY);
                    extras.putInt(Ndef.EXTRA_NDEF_TYPE, Ndef.TYPE_OTHER);
                    Tag tag = Tag.createMockTag(new byte[] { 0x00 },
                            new int[] { TagTechnology.NDEF },
                            new Bundle[] { extras });
                    Log.d(TAG, "mock NDEF tag, starting corresponding activity");
                    Log.d(TAG, tag.toString());
                    boolean delivered = mNfcDispatcher.dispatchTag(tag,
                            new NdefMessage[] { ndefMsg });
                    if (delivered) {
1395 1396 1397
                        playSound(mEndSound);
                    } else {
                        playSound(mErrorSound);
1398 1399 1400
                    }
                    break;
                }
1401

1402 1403 1404 1405 1406
                case MSG_NDEF_TAG:
                    if (DBG) Log.d(TAG, "Tag detected, notifying applications");
                    TagEndpoint tag = (TagEndpoint) msg.obj;
                    playSound(mStartSound);
                    NdefMessage[] ndefMsgs = tag.findAndReadNdef();
1407

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
                    if (ndefMsgs != null) {
                        tag.startPresenceChecking();
                        dispatchTagEndpoint(tag, ndefMsgs);
                    } else {
                        if (tag.reconnect()) {
                            tag.startPresenceChecking();
                            dispatchTagEndpoint(tag, null);
                        } else {
                            tag.disconnect();
                            playSound(mErrorSound);
                        }
                    }
                    break;

                case MSG_CARD_EMULATION:
                    if (DBG) Log.d(TAG, "Card Emulation message");
                    byte[] aid = (byte[]) msg.obj;
                    /* Send broadcast */
                    Intent aidIntent = new Intent();
                    aidIntent.setAction(ACTION_AID_SELECTED);
                    aidIntent.putExtra(EXTRA_AID, aid);
                    if (DBG) Log.d(TAG, "Broadcasting " + ACTION_AID_SELECTED);
1430
                    sendSeBroadcast(aidIntent);
1431 1432 1433 1434 1435 1436 1437 1438
                    break;

                case MSG_SE_EMV_CARD_REMOVAL:
                    if (DBG) Log.d(TAG, "Card Removal message");
                    /* Send broadcast */
                    Intent cardRemovalIntent = new Intent();
                    cardRemovalIntent.setAction(ACTION_EMV_CARD_REMOVAL);
                    if (DBG) Log.d(TAG, "Broadcasting " + ACTION_EMV_CARD_REMOVAL);
1439
                    sendSeBroadcast(cardRemovalIntent);
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
                    break;

                case MSG_SE_APDU_RECEIVED:
                    if (DBG) Log.d(TAG, "APDU Received message");
                    byte[] apduBytes = (byte[]) msg.obj;
                    /* Send broadcast */
                    Intent apduReceivedIntent = new Intent();
                    apduReceivedIntent.setAction(ACTION_APDU_RECEIVED);
                    if (apduBytes != null && apduBytes.length > 0) {
                        apduReceivedIntent.putExtra(EXTRA_APDU_BYTES, apduBytes);
                    }
                    if (DBG) Log.d(TAG, "Broadcasting " + ACTION_APDU_RECEIVED);
1452
                    sendSeBroadcast(apduReceivedIntent);
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                    break;

                case MSG_SE_MIFARE_ACCESS:
                    if (DBG) Log.d(TAG, "MIFARE access message");
                    /* Send broadcast */
                    byte[] mifareCmd = (byte[]) msg.obj;
                    Intent mifareAccessIntent = new Intent();
                    mifareAccessIntent.setAction(ACTION_MIFARE_ACCESS_DETECTED);
                    if (mifareCmd != null && mifareCmd.length > 1) {
                        int mifareBlock = mifareCmd[1] & 0xff;
                        if (DBG) Log.d(TAG, "Mifare Block=" + mifareBlock);
                        mifareAccessIntent.putExtra(EXTRA_MIFARE_BLOCK, mifareBlock);
                    }
                    if (DBG) Log.d(TAG, "Broadcasting " + ACTION_MIFARE_ACCESS_DETECTED);
1467
                    sendSeBroadcast(mifareAccessIntent);
1468
                    break;
1469

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
                case MSG_LLCP_LINK_ACTIVATION:
                    llcpActivated((NfcDepEndpoint) msg.obj);
                    break;

                case MSG_LLCP_LINK_DEACTIVATED:
                    NfcDepEndpoint device = (NfcDepEndpoint) msg.obj;
                    boolean needsDisconnect = false;

                    Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
                    synchronized (NfcService.this) {
                        /* Check if the device has been already unregistered */
                        if (mObjectMap.remove(device.getHandle()) != null) {
                            /* Disconnect if we are initiator */
                            if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
                                if (DBG) Log.d(TAG, "disconnecting from target");
                                needsDisconnect = true;
                            } else {
                                if (DBG) Log.d(TAG, "not disconnecting from initiator");
                            }
                        }
                    }
                    if (needsDisconnect) {
                        device.disconnect();  // restarts polling loop
                    }

1495
                    mP2pLinkManager.onLlcpDeactivated();
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
                    break;

                case MSG_TARGET_DESELECTED:
                    /* Broadcast Intent Target Deselected */
                    if (DBG) Log.d(TAG, "Target Deselected");
                    Intent intent = new Intent();
                    intent.setAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
                    if (DBG) Log.d(TAG, "Broadcasting Intent");
                    mContext.sendOrderedBroadcast(intent, NFC_PERM);
                    break;

                case MSG_SE_FIELD_ACTIVATED: {
                    if (DBG) Log.d(TAG, "SE FIELD ACTIVATED");
                    Intent eventFieldOnIntent = new Intent();
                    eventFieldOnIntent.setAction(ACTION_RF_FIELD_ON_DETECTED);
1511
                    sendSeBroadcast(eventFieldOnIntent);
1512 1513 1514 1515 1516 1517 1518
                    break;
                }

                case MSG_SE_FIELD_DEACTIVATED: {
                    if (DBG) Log.d(TAG, "SE FIELD DEACTIVATED");
                    Intent eventFieldOffIntent = new Intent();
                    eventFieldOffIntent.setAction(ACTION_RF_FIELD_OFF_DETECTED);
1519
                    sendSeBroadcast(eventFieldOffIntent);
1520 1521 1522 1523 1524 1525 1526
                    break;
                }

                default:
                    Log.e(TAG, "Unknown message received");
                    break;
            }
1527
        }
Jeff Hamilton's avatar
Jeff Hamilton committed
1528

1529
        private void sendSeBroadcast(Intent intent) {
1530
            mNfcDispatcher.resumeAppSwitches();
1531 1532 1533 1534
            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            mContext.sendBroadcast(intent, NFCEE_ADMIN_PERM);
        }

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
        private boolean llcpActivated(NfcDepEndpoint device) {
            Log.d(TAG, "LLCP Activation message");

            if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
                if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
                if (device.connect()) {
                    /* Check LLCP compliancy */
                    if (mDeviceHost.doCheckLlcp()) {
                        /* Activate LLCP Link */
                        if (mDeviceHost.doActivateLlcp()) {
                            if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
1546 1547 1548 1549
                            boolean isZeroClickOn;
                            synchronized (NfcService.this) {
                                // Register P2P device
                                mObjectMap.put(device.getHandle(), device);
1550
                            }
1551
                            mP2pLinkManager.onLlcpActivated();
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
                            return true;
                        } else {
                            /* should not happen */
                            Log.w(TAG, "Initiator LLCP activation failed. Disconnect.");
                            device.disconnect();
                        }
                    } else {
                        if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
                        device.disconnect();
                    }
                } else {
                    if (DBG) Log.d(TAG, "Cannot connect remote Target. Polling loop restarted.");
                    /*
                     * The polling loop should have been restarted in failing
                     * doConnect
                     */
                }
            } else if (device.getMode() == NfcDepEndpoint.MODE_P2P_INITIATOR) {
                if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
                /* Check LLCP compliancy */
                if (mDeviceHost.doCheckLlcp()) {
                    /* Activate LLCP Link */
                    if (mDeviceHost.doActivateLlcp()) {
                        if (DBG) Log.d(TAG, "Target Activate LLCP OK");
1576 1577 1578 1579
                        boolean isZeroClickOn;
                        synchronized (NfcService.this) {
                            // Register P2P device
                            mObjectMap.put(device.getHandle(), device);
1580
                        }
1581
                        mP2pLinkManager.onLlcpActivated();
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
                        return true;
                    }
                } else {
                    Log.w(TAG, "checkLlcp failed");
                }
            }

            return false;
        }

1592 1593 1594 1595
        private void dispatchTagEndpoint(TagEndpoint tagEndpoint, NdefMessage[] msgs) {
            Tag tag = new Tag(tagEndpoint.getUid(), tagEndpoint.getTechList(),
                    tagEndpoint.getTechExtras(), tagEndpoint.getHandle(), mNfcTagService);
            registerTagObject(tagEndpoint);
1596
            if (!mNfcDispatcher.dispatchTag(tag, msgs)) {
1597
                unregisterObject(tagEndpoint.getHandle());
1598 1599 1600
                playSound(mErrorSound);
            } else {
                playSound(mEndSound);
1601 1602
            }
        }
Jeff Hamilton's avatar
Jeff Hamilton committed
1603
    }
1604

Jeff Hamilton's avatar
Jeff Hamilton committed
1605
    private NfcServiceHandler mHandler = new NfcServiceHandler();
1606

1607
    class EnableDisableDiscoveryTask extends AsyncTask<Boolean, Void, Void> {
Jason parks's avatar
Jason parks committed
1608
        @Override
1609 1610 1611 1612
        protected Void doInBackground(Boolean... params) {
            if (DBG) Log.d(TAG, "EnableDisableDiscoveryTask: enable = " + params[0]);

            if (params != null && params.length > 0 && params[0]) {
1613
                synchronized (NfcService.this) {
1614 1615
                    if (!mIsScreenUnlocked) {
                        mIsScreenUnlocked = true;
1616 1617 1618 1619
                        applyRouting();
                    } else {
                        if (DBG) Log.d(TAG, "Ignoring enable request");
                    }
1620
                }
1621
            } else {
1622
                mWakeLock.acquire();
1623
                synchronized (NfcService.this) {
1624 1625
                    if (mIsScreenUnlocked) {
                        mIsScreenUnlocked = false;
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
//                        applyRouting();
                        /*
                         * TODO undo this after the LLCP stack is fixed.
                         * This is done locally here since the LLCP stack is still using
                         * globals without holding any locks, and if we attempt to change
                         * the NFCEE routing while the target is still connected (and it's
                         * a P2P target) the async LLCP callbacks will crash since the routing
                         * manipulation code is overwriting globals it relies on. This hack should
                         * be removed when the LLCP stack is fixed.
                         */
1636 1637 1638 1639
                        if (isNfcEnabled() && mOpenEe == null) {
                            Log.d(TAG, "NFC-C polling OFF");
                            mDeviceHost.disableDiscovery();
                            maybeDisconnectTarget();
1640 1641 1642
                            Log.d(TAG, "NFC-EE routing OFF");
                            mDeviceHost.doDeselectSecureElement();
                        }
1643 1644 1645
                    } else {
                        if (DBG) Log.d(TAG, "Ignoring disable request");
                    }
1646
                }
1647
                mWakeLock.release();
1648 1649 1650 1651 1652
            }
            return null;
        }
    }

Nick Pelly's avatar
Nick Pelly committed
1653 1654 1655
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
1656 1657
            String action = intent.getAction();
            if (action.equals(
Nick Pelly's avatar
Nick Pelly committed
1658
                    NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
1659
                if (DBG) Log.d(TAG, "INERNAL_TARGET_DESELECTED_ACTION");
Nick Pelly's avatar
Nick Pelly committed
1660

Nick Pelly's avatar
Nick Pelly committed
1661
                /* Restart polling loop for notification */
1662
                applyRouting();
Nick Pelly's avatar
Nick Pelly committed
1663

1664
            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1665 1666 1667
                // Only enable if the screen is unlocked. If the screen is locked
                // Intent.ACTION_USER_PRESENT will be broadcast when the screen is
                // unlocked.
1668
                boolean enable = !mKeyguard.isKeyguardLocked();
1669

1670 1671 1672 1673
                // Perform discovery enable in thread to protect against ANR when the
                // NFC stack wedges. This is *not* the correct way to fix this issue -
                // configuration of the local NFC adapter should be very quick and should
                // be safe on the main thread, and the NFC stack should not wedge.
1674
                new EnableDisableDiscoveryTask().execute(enable);
1675
            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1676 1677 1678 1679
                // Perform discovery disable in thread to protect against ANR when the
                // NFC stack wedges. This is *not* the correct way to fix this issue -
                // configuration of the local NFC adapter should be very quick and should
                // be safe on the main thread, and the NFC stack should not wedge.
1680
                new EnableDisableDiscoveryTask().execute(Boolean.FALSE);
1681
            } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1682 1683
                // The user has unlocked the screen. Enabled!
                new EnableDisableDiscoveryTask().execute(Boolean.TRUE);
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
            } else if (action.equals(ACTION_MASTER_CLEAR_NOTIFICATION)) {
                EnableDisableTask eeWipeTask = new EnableDisableTask();
                eeWipeTask.execute(TASK_EE_WIPE);
                try {
                    eeWipeTask.get();  // blocks until EE wipe is complete
                } catch (ExecutionException e) {
                    Log.w(TAG, "failed to wipe NFC-EE");
                } catch (InterruptedException e) {
                    Log.w(TAG, "failed to wipe NFC-EE");
                }
            } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
1695 1696 1697 1698 1699 1700 1701
                boolean dataRemoved = intent.getBooleanExtra(Intent.EXTRA_DATA_REMOVED, false);
                if (dataRemoved) {
                    Uri data = intent.getData();
                    if (data == null) return;
                    String packageName = data.getSchemeSpecificPart();

                    synchronized (NfcService.this) {
1702
                        if (mSePackages.contains(packageName)) {
1703
                            new EnableDisableTask().execute(TASK_EE_WIPE);
1704
                            mSePackages.remove(packageName);
1705
                        }
Jason parks's avatar
Jason parks committed
1706 1707
                    }
                }
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
            } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
                boolean isAirplaneModeOn = intent.getBooleanExtra("state", false);
                // Query the airplane mode from Settings.System just to make sure that
                // some random app is not sending this intent
                if (isAirplaneModeOn != isAirplaneModeOn()) {
                    return;
                }
                if (!mIsAirplaneSensitive) {
                    return;
                }
                if (isAirplaneModeOn) {
                    new EnableDisableTask().execute(TASK_DISABLE);
                } else if (!isAirplaneModeOn && mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT)) {
                    new EnableDisableTask().execute(TASK_ENABLE);
                }
Nick Pelly's avatar
Nick Pelly committed
1723 1724 1725
            }
        }
    };
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749

    /** Returns true if airplane mode is currently on */
    boolean isAirplaneModeOn() {
        return Settings.System.getInt(mContext.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    }

    /** for debugging only - no il8n */
    static String stateToString(int state) {
        switch (state) {
            case NfcAdapter.STATE_OFF:
                return "off";
            case NfcAdapter.STATE_TURNING_ON:
                return "turning on";
            case NfcAdapter.STATE_ON:
                return "on";
            case NfcAdapter.STATE_TURNING_OFF:
                return "turning off";
            default:
                return "<error>";
        }
    }

    void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root's avatar
Kenny Root committed
1750 1751 1752 1753 1754 1755 1756 1757
        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
                != PackageManager.PERMISSION_GRANTED) {
            pw.println("Permission Denial: can't dump nfc from from pid="
                    + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
                    + " without permission " + android.Manifest.permission.DUMP);
            return;
        }

1758 1759
        synchronized (this) {
            pw.println("mState=" + stateToString(mState));
1760
            pw.println("mIsZeroClickRequested=" + mIsNdefPushEnabled);
1761 1762 1763
            pw.println("mIsScreenUnlocked=" + mIsScreenUnlocked);
            pw.println("mIsAirplaneSensitive=" + mIsAirplaneSensitive);
            pw.println("mIsAirplaneToggleable=" + mIsAirplaneToggleable);
1764
            mP2pLinkManager.dump(fd, pw, args);
1765
            pw.println(mDeviceHost.dump());
1766 1767
        }
    }
1768
}