aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/android/nfc/cardemulation/AidRoutingManager.java
blob: d27e254b8323def7236826abc3a0cd077058257c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
 * Copyright (C) 2013 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.
 */

/******************************************************************************
 *
 *  The original Work has been changed by NXP Semiconductors.
 *
 *  Copyright (C) 2015-2018 NXP Semiconductors
 *
 *  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.
 *
 ******************************************************************************/
package com.android.nfc.cardemulation;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ActivityThread;
import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

import com.android.nfc.NfcService;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
public class AidRoutingManager {
    static final String TAG = "AidRoutingManager";

    static final boolean DBG =
        ("1" == (System.getProperty("persist.nfc.ce_debug")) ? true : false);

    static final int ROUTE_HOST = 0x00;

    // Every routing table entry is matched exact
    static final int AID_MATCHING_EXACT_ONLY = 0x00;
    // Every routing table entry can be matched either exact or prefix
    static final int AID_MATCHING_EXACT_OR_PREFIX = 0x01;
    // Every routing table entry is matched as a prefix
    static final int AID_MATCHING_PREFIX_ONLY = 0x02;
    // Every routing table entry can be matched either exact or prefix or subset only
    static final int AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX = 0x03;
    //Behavior as per Android-L, supporting prefix match and full
    //match for both OnHost and OffHost apps.
    static final int AID_MATCHING_L = 0x01;
    //Behavior as per Android-KitKat by NXP, supporting prefix match for
    //OffHost and prefix and full both for OnHost apps.
    static final int AID_MATCHING_K = 0x02;
    // This is the default IsoDep protocol route; it means
    // that for any AID that needs to be routed to this
    // destination, we won't need to add a rule to the routing
    // table, because this destination is already the default route.
    //
    // For Nexus devices, the default route is always 0x00.
    int mDefaultRoute;
    boolean mRoutingTableChanged;
    // For Nexus devices, just a static route to the eSE
    // OEMs/Carriers could manually map off-host AIDs
    // to the correct eSE/UICC based on state they keep.
    int mDefaultOffHostRoute;

    // How the NFC controller can match AIDs in the routing table;
    // see AID_MATCHING constants
    int mAidMatchingSupport;
    int mAidMatchingPlatform;
    //Changed from final to private int to update RoutingtableSize later in configureRouting.
    private int mAidRoutingTableSize;
    // Maximum AID routing table size
    final Object mLock = new Object();
    //set the status of last AID routes commit to routing table
    //if true, last commit was successful,
    //if false, there was an overflow of routing table for commit using last set of AID's in (mRouteForAid)
    boolean mLastCommitStatus;

    // mAidRoutingTable contains the current routing table. The index is the route ID.
    // The route can include routes to a eSE/UICC.
    SparseArray<Set<String>> mAidRoutingTable =
            new SparseArray<Set<String>>();

    // Easy look-up what the route is for a certain AID
    HashMap<String, Integer> mRouteForAid = new HashMap<String, Integer>();

    // Easy look-up what the power state is for a certain AID
    HashMap<String, Integer> mPowerForAid = new HashMap<String, Integer>();


    private native int doGetDefaultRouteDestination();
    private native int doGetDefaultOffHostRouteDestination();
    private native int doGetAidMatchingMode();
    private native int doGetAidMatchingPlatform();

    final VzwRoutingCache mVzwRoutingCache;

    final ActivityManager mActivityManager;

    public AidRoutingManager() {
        mDefaultRoute = doGetDefaultRouteDestination();
        mRoutingTableChanged = false;
        if (DBG) Log.d(TAG, "mDefaultRoute=0x" + Integer.toHexString(mDefaultRoute));
        mDefaultOffHostRoute = doGetDefaultOffHostRouteDestination();
        if (DBG) Log.d(TAG, "mDefaultOffHostRoute=0x" + Integer.toHexString(mDefaultOffHostRoute));
        mAidMatchingSupport = doGetAidMatchingMode();
        if (DBG) Log.d(TAG, "mAidMatchingSupport=0x" + Integer.toHexString(mAidMatchingSupport));
        mAidMatchingPlatform = doGetAidMatchingPlatform();
        if (DBG) Log.d(TAG, "mAidMatchingPlatform=0x" + Integer.toHexString(mAidMatchingPlatform));
        mVzwRoutingCache = new VzwRoutingCache();
        mLastCommitStatus = true;

        Context context = (Context) ActivityThread.currentApplication();
        mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    }

    public boolean supportsAidPrefixRouting() {
        return mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX ||
                mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY ||
                 mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX;
    }

    public boolean supportsAidSubsetRouting() {
        return mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX;
    }

    public boolean isRoutingTableUpdated() {
        return mRoutingTableChanged;
    }
    void clearNfcRoutingTableLocked() {
        /*
        for (Map.Entry<String, Integer> aidEntry : mRouteForAid.entrySet())  {
            String aid = aidEntry.getKey();
            if (aid.endsWith("*")) {
                if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) {
                    Log.e(TAG, "Device does not support prefix AIDs but AID [" + aid
                            + "] is registered");
                } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY) {
                    if (DBG) Log.d(TAG, "Unrouting prefix AID " + aid);
                    // Cut off '*' since controller anyway treats all AIDs as a prefix
                    aid = aid.substring(0, aid.length() - 1);
                } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX ||
                    mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) {
                    aid = aid.substring(0, aid.length() - 1);
                    if (DBG) Log.d(TAG, "Unrouting prefix AID " + aid);
                }
            }  else if (aid.endsWith("#")) {
                if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) {
                    Log.e(TAG, "Device does not support subset AIDs but AID [" + aid
                            + "] is registered");
                } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY ||
                    mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX) {
                    Log.e(TAG, "Device does not support subset AIDs but AID [" + aid
                            + "] is registered");
                } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) {
                    if (DBG) Log.d(TAG, "Unrouting subset AID " + aid);
                    aid = aid.substring(0, aid.length() - 1);
                }
            } else {
                if (DBG) Log.d(TAG, "Unrouting exact AID " + aid);
            }
            NfcService.getInstance().unrouteAids(aid);
        }
        */
        NfcService.getInstance().clearRouting();
        mRouteForAid.clear();
        mPowerForAid.clear();
        mAidRoutingTable.clear();
    }

    public boolean configureApduPatternRouting(List<ApduPatternResolveInfo> apduPatternList) {
        if(apduPatternList.size() == 0x00 || apduPatternList == null)
            return false;
        NfcService.getInstance().unrouteApduPattern("FFFFFFFFFFFFFFEF");
        for(ApduPatternResolveInfo apduPatternInfo : apduPatternList) {
            NfcService.getInstance().routeApduPattern(apduPatternInfo.referenceData,apduPatternInfo.mask,
                    apduPatternInfo.route,apduPatternInfo.powerState);
        }
        return true;
    }

    public void refreshConfigParameters() {
      mDefaultRoute = doGetDefaultRouteDestination();
      if (DBG)
        Log.d(TAG, "mDefaultRoute=0x" + Integer.toHexString(mDefaultRoute));
      mDefaultOffHostRoute = doGetDefaultOffHostRouteDestination();
      if (DBG)
        Log.d(TAG, "mDefaultOffHostRoute=0x" + Integer.toHexString(mDefaultOffHostRoute));
      mAidMatchingSupport = doGetAidMatchingMode();
      if (DBG)
        Log.d(TAG, "mAidMatchingSupport=0x" + Integer.toHexString(mAidMatchingSupport));
      mAidMatchingPlatform = doGetAidMatchingPlatform();
    }

    public boolean configureRouting(HashMap<String, AidElement> aidMap) {
        mRoutingTableChanged = false;
        //To handle Dynamic change in config files.
        refreshConfigParameters();
        mDefaultRoute = NfcService.getInstance().GetDefaultRouteLoc();
        boolean aidRouteResolved = false;
        if (DBG) Log.d(TAG, "mAidMatchingPlatform=0x" + Integer.toHexString(mAidMatchingPlatform));
        mAidRoutingTableSize = NfcService.getInstance().getAidRoutingTableSize();
        if (DBG) Log.d(TAG, "mDefaultRoute=0x" + Integer.toHexString(mDefaultRoute));
        Hashtable<String, AidElement> routeCache = new Hashtable<String, AidElement>(50);
        SparseArray<Set<String>> aidRoutingTable = new SparseArray<Set<String>>(aidMap.size());
        HashMap<String, Integer> routeForAid = new HashMap<String, Integer>(aidMap.size());
        HashMap<String, Integer> powerForAid = new HashMap<String, Integer>(aidMap.size());
        HashMap<String, Integer> infoForAid = new HashMap<String, Integer>(aidMap.size());
        // Then, populate internal data structures first
        DefaultAidRouteResolveCache defaultRouteCache = new DefaultAidRouteResolveCache();

        for (Map.Entry<String, AidElement> aidEntry : aidMap.entrySet())  {
            AidElement elem = aidEntry.getValue();
            int route = elem.getRouteLocation();
            int power = elem.getPowerState();
            int aidType = elem.getAidInfo();
            if (route == -1 ) {
                route = mDefaultOffHostRoute;
                elem.setRouteLocation(route);
            }
            String aid = aidEntry.getKey();
            Set<String> entries = aidRoutingTable.get(route, new HashSet<String>());
            entries.add(aid);
            aidRoutingTable.put(route, entries);
            routeForAid.put(aid, route);
            powerForAid.put(aid, power);
            infoForAid.put(aid, aidType);
            if (DBG) Log.d(TAG, "#######Routing AID " + aid + " to route "
                        + Integer.toString(route) + " with power "+ power);
        }

        synchronized (mLock) {
            if (routeForAid.equals(mRouteForAid)) {
                if (DBG) Log.d(TAG, "Routing table unchanged");
                if(mLastCommitStatus == false){
                    NfcService.getInstance().updateStatusOfServices(false);
                    NfcService.getInstance().notifyRoutingTableFull();
                }
                else
                {/*If last commit status was success, And a new service is added whose AID's are
                already resolved by previously installed services, service state of newly installed app needs to be updated*/
                    NfcService.getInstance().updateStatusOfServices(true);
                }
                if (isProcessingTapAgain() || NfcService.getInstance().mIsRoutingTableDirty) {
                    if (DBG) Log.d(TAG, "Routing table unchanged, but commit the routing");
                    NfcService.getInstance().commitRouting();
                } else {
                    if (DBG) Log.d(TAG, "Routing table unchanged, not updating");
                }
                return false;
            }

            // Otherwise, update internal structures and commit new routing
            clearNfcRoutingTableLocked();
            mRouteForAid = routeForAid;
            mPowerForAid = powerForAid;
            mAidRoutingTable = aidRoutingTable;
            for(int routeIndex=0; routeIndex < 0x03; routeIndex++) {
                routeCache.clear();
                if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY ||
                    mAidMatchingPlatform == AID_MATCHING_K) {
                /* If a non-default route registers an exact AID which is shorter
                 * than this exact AID, this will create a problem with controllers
                 * that treat every AID in the routing table as a prefix.
                 * For example, if App A registers F0000000041010 as an exact AID,
                 * and App B registers F000000004 as an exact AID, and App B is not
                 * the default route, the following would be added to the routing table:
                 * F000000004 -> non-default destination
                 * However, because in this mode, the controller treats every routing table
                 * entry as a prefix, it means F0000000041010 would suddenly go to the non-default
                 * destination too, whereas it should have gone to the default.
                 *
                 * The only way to prevent this is to add the longer AIDs of the
                 * default route at the top of the table, so they will be matched first.
                 */
                Set<String> defaultRouteAids = mAidRoutingTable.get(mDefaultRoute);
                if (defaultRouteAids != null) {
                    for (String defaultRouteAid : defaultRouteAids) {
                        // Check whether there are any shorted AIDs routed to non-default
                        // TODO this is O(N^2) run-time complexity...
                        for (Map.Entry<String, Integer> aidEntry : mRouteForAid.entrySet()) {
                            String aid = aidEntry.getKey();
                            int route = aidEntry.getValue();
                            if (defaultRouteAid.startsWith(aid) && route != mDefaultRoute) {
                                if (DBG) Log.d(TAG, "Adding AID " + defaultRouteAid + " for default " +
                                        "route, because a conflicting shorter AID will be added" +
                                        "to the routing table");
                                AidElement elem = aidMap.get(defaultRouteAid);
                                elem.setRouteLocation(mDefaultRoute);
                                routeCache.put(defaultRouteAid, elem);
                                //NfcService.getInstance().routeAids(defaultRouteAid, mDefaultRoute, mPowerForAid.get(defaultRouteAid),infoForAid.get(defaultRouteAid));
                            }
                        }
                    }
                }
            }

            // Add AID entries for all non-default routes
            for (int i = 0; i < mAidRoutingTable.size(); i++) {
                int route = mAidRoutingTable.keyAt(i);
                if (route != mDefaultRoute) {
                    Set<String> aidsForRoute = mAidRoutingTable.get(route);
                    for (String aid : aidsForRoute) {
                        if (aid.endsWith("*")) {
                            if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) {
                                Log.e(TAG, "This device does not support prefix AIDs.");
                            } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY) {
                                if (DBG) Log.d(TAG, "Routing prefix AID " + aid + " to route "
                                        + Integer.toString(route));
                                // Cut off '*' since controller anyway treats all AIDs as a prefix
                                AidElement elem = aidMap.get(aid);
                                elem.setAid(aid.substring(0,aid.length() - 1));
                                routeCache.put(aid, elem);
                                //NfcService.getInstance().routeAids(aid.substring(0,
                                                //aid.length() - 1), route, mPowerForAid.get(aid),infoForAid.get(aid));
                            } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX
                              || mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) {
                                Log.d(TAG, "Routing AID in AID_MATCHING_EXACT_OR_PREFIX");
                                if (DBG) Log.d(TAG, "Routing prefix AID " + aid + " to route "
                                        + Integer.toString(route));
                                AidElement elem = aidMap.get(aid);
                                routeCache.put(aid, elem);
                                //NfcService.getInstance().routeAids(aid, route, (mPowerForAid.get(aid)),infoForAid.get(aid));
                            }
                        } else if (aid.endsWith("#")) {
                            if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) {
                                Log.e(TAG, "Device does not support subset AIDs but AID [" + aid
                                        + "] is registered");
                            } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY ||
                                mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX) {
                                Log.e(TAG, "Device does not support subset AIDs but AID [" + aid
                                        + "] is registered");
                            } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) {
                                if (DBG) Log.d(TAG, "Routing subset AID " + aid + " to route "
                                        + Integer.toString(route));
                                AidElement elem = aidMap.get(aid);
                                routeCache.put(aid, elem);
                                //NfcService.getInstance().routeAids(aid, route, (mPowerForAid.get(aid)),infoForAid.get(aid));
                            }
                        } else {
                            if (DBG) Log.d(TAG, "Routing exact AID " + aid + " to route "
                                    + Integer.toString(route));
                            AidElement elem = aidMap.get(aid);
                            routeCache.put(aid, elem);
                            //NfcService.getInstance().routeAids(aid, route, mPowerForAid.get(aid),infoForAid.get(aid));
                        }
                    }
                }
            }

            if((routeIndex == 0x00) && (defaultRouteCache.calculateAidRouteSize(routeCache) <= mAidRoutingTableSize)) {
                // maximum aid table size is less than  AID route table size
                aidRouteResolved = true;
                break;
            } else {
                defaultRouteCache.updateDefaultAidRouteCache(routeCache , mDefaultRoute);
                mDefaultRoute = defaultRouteCache.getNextRouteLoc();
                if(mDefaultRoute == 0xFF)
                {
                    break;
                }
            }

        }
        }
        if(aidRouteResolved == false) {
            if(mAidRoutingTable.size() == 0x00) {
                aidRouteResolved = true;
                //update the cache , no applications present.
            }
            else if(defaultRouteCache.resolveDefaultAidRoute() == true) {
                aidRouteResolved = true;
                routeCache = defaultRouteCache.getResolvedAidRouteCache();
                //update preferences if different
                NfcService.getInstance().setDefaultAidRouteLoc(defaultRouteCache.getResolvedAidRoute());
            } else {
                NfcService.getInstance().notifyRoutingTableFull();
            }
        }
        // And finally commit the routing and update the status of commit for each service
        if(aidRouteResolved == true) {
            mRoutingTableChanged = true;
            commit(routeCache);
            NfcService.getInstance().updateStatusOfServices(true);
            mLastCommitStatus = true;
        }
        else{
            NfcService.getInstance().updateStatusOfServices(false);
            mLastCommitStatus = false;
        }
//        NfcService.getInstance().commitRouting();

        return true;
    }

    private void commit(Hashtable<String, AidElement> routeCache ) {

        if(routeCache != null) {
            List<AidElement> list = Collections.list(routeCache.elements());
            Collections.sort(list);
            Iterator<AidElement> it = list.iterator();
            NfcService.getInstance().clearRouting();
            while(it.hasNext()){
                AidElement element =it.next();
                if (DBG) Log.d (TAG, element.toString());
                NfcService.getInstance().routeAids(
                    element.getAid(),
                    element.getRouteLocation(),
                    element.getPowerState(),
                    element.getAidInfo());
            }
        }
        // And finally commit the routing
        NfcService.getInstance().commitRouting();
    }

    /**
     * This notifies that the AID routing table in the controller
     * has been cleared (usually due to NFC being turned off).
     */
    public void onNfccRoutingTableCleared() {
        // The routing table in the controller was cleared
        // To stay in sync, clear our own tables.
        synchronized (mLock) {
            mAidRoutingTable.clear();
            mRouteForAid.clear();
        }
    }

    public boolean UpdateVzwCache(byte[] aid,int route,int power,boolean isAllowed){
       mVzwRoutingCache.addAid(aid,route,power,isAllowed);
       return true;
    }

    public VzwRoutingCache GetVzwCache(){
       return mVzwRoutingCache;
    }

    public void ClearVzwCache() {
        mVzwRoutingCache.clear();
    }

    public int getAidMatchMode() {
        return mAidMatchingSupport;
    }

    public boolean getLastCommitRoutingStatus() {
        return mLastCommitStatus;
    }

    public int getAidMatchingPlatform() {
        return mAidMatchingPlatform;
    }

    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("Routing table:");
        pw.println("    Default route: " +
                (NfcService.getInstance().GetDefaultRouteLoc() == 0x00 ? "host" : "secure element"));
        synchronized (mLock) {
            for (int i = 0; i < mAidRoutingTable.size(); i++) {
                Set<String> aids = mAidRoutingTable.valueAt(i);
                pw.println("    Routed to 0x" + Integer.toHexString(mAidRoutingTable.keyAt(i)) + ":");
                for (String aid : aids) {
                    pw.println("        \"" + aid + "\"");
                }
            }
        }
    }

    final class ApduPatternResolveInfo {
        public String  mask;
        public String  referenceData;
        public int route;
        public int powerState;
    }

    final class DefaultAidRouteResolveCache {
        static final int AID_HDR_LENGTH = 0x04; // TAG + ROUTE + LENGTH_BYTE + POWER
        static final int MAX_AID_ENTRIES = 50;
        //AidCacheTable contains the current aid routing table for particular route.
        //The index is the route ID.
        private SparseArray<Hashtable<String, AidElement>> aidCacheTable;
        private HashMap <Integer , Integer> aidCacheSize;
        //HashMap containing aid routing size .
        //The index is route ID.
        private Hashtable<String, AidElement> resolvedAidCache;//HashTable containing resolved default aid routeCache
        private int mCurrDefaultAidRoute; // current default route in preferences
        private int mResolvedAidRoute;    //resolved aid route location
        private boolean mAidRouteResolvedStatus; // boolean value
        private ArrayList<Integer> aidRoutes;//non-default route location

        DefaultAidRouteResolveCache () {
            aidCacheTable = new SparseArray<Hashtable<String, AidElement>>(0x03);
            resolvedAidCache = new Hashtable<String, AidElement>();
            aidCacheSize= new HashMap <Integer , Integer>(0x03);
            aidRoutes = new ArrayList<Integer>();
            mCurrDefaultAidRoute = NfcService.getInstance().GetDefaultRouteLoc();
            mAidRouteResolvedStatus = false;
        }

        private Hashtable<String, AidElement> extractResolvedCache()
        {
            if(mAidRouteResolvedStatus == false) {
                return null;
            }
            for(int i=0;i< aidCacheTable.size() ;i++) {
                int route = aidCacheTable.keyAt(i);
                if(route == mResolvedAidRoute) {
                    return aidCacheTable.get(route);
                }
            }
            return null;
        }


        public int calculateAidRouteSize(Hashtable<String, AidElement> routeCache) {
            int routeTableSize = 0x00;
            int routeAidCount = 0x00;
            for(Map.Entry<String, AidElement> aidEntry : routeCache.entrySet()) {
                String aid = aidEntry.getKey();
                if(aid.endsWith("*")) {
                    routeTableSize += ((aid.length() - 0x01) / 0x02) + AID_HDR_LENGTH; // removing prefix length
                } else {
                    routeTableSize += (aid.length() / 0x02)+ AID_HDR_LENGTH;
                }
                routeAidCount++;
            }
            Log.d(TAG, "calculateAidRouteSize final Routing table size" +routeTableSize);
            if(routeTableSize <= mAidRoutingTableSize && routeAidCount > MAX_AID_ENTRIES) {
                routeTableSize = mAidRoutingTableSize + 0x01;
            }
                return routeTableSize;
        }

       public int updateDefaultAidRouteCache(Hashtable<String, AidElement> routeCache , int route) {
           int routesize = 0x00;
           Hashtable<String, AidElement> tempRouteCache = new Hashtable<String, AidElement>(0x50);
           tempRouteCache.putAll(routeCache);
           routesize = calculateAidRouteSize(tempRouteCache);
           aidCacheTable.put(route, tempRouteCache);
           aidCacheSize.put(route, routesize);
           Log.d(TAG, "updateDefaultAidRouteCache Routing table size" +routesize);
           return routesize;
       }

       public boolean resolveDefaultAidRoute () {

           int minRoute = 0xFF;
           int minAidRouteSize = mAidRoutingTableSize;
           int tempRoute = 0x00;
           int tempCacheSize = 0x00;
           Hashtable<String, AidElement> aidRouteCache = new Hashtable<String, AidElement>();
           Set<Integer> keys = aidCacheSize.keySet();
           for (Integer key : keys) {
               tempRoute = key;
               tempCacheSize = aidCacheSize.get(key);
               if (tempCacheSize <= minAidRouteSize) {
                   minAidRouteSize = tempCacheSize;
                   minRoute = tempRoute;
               }
           }
           if(minRoute != 0xFF) {
               mAidRouteResolvedStatus = true;
               mResolvedAidRoute = minRoute;
               Log.d(TAG, "min route found "+mResolvedAidRoute);
           }

           return mAidRouteResolvedStatus;
       }

       public int getResolvedAidRoute () {
           return mResolvedAidRoute;
       }

       public Hashtable<String, AidElement>  getResolvedAidRouteCache() {

           return extractResolvedCache();
       }

       public int getNextRouteLoc() {

           for (int i = 0; i < 0x03; i++) {
               if((i != mCurrDefaultAidRoute) && (!aidRoutes.contains(i)))
               {
                   aidRoutes.add(i);
                   return i;
               }
           }
           return 0xFF;
       }

    }

    // Returns true if AppChooserActivity is foreground to restart RF discovery so that
    // TapAgainDialog is dismissed when an external reader detects the device.
    private boolean isProcessingTapAgain() {
        String appChooserActivityClassName = AppChooserActivity.class.getName();
        return appChooserActivityClassName.equals(getTopClass());
    }

    private String getTopClass() {
        String topClass = null;
        List<RunningTaskInfo> tasks = mActivityManager.getRunningTasks(1);
        if (tasks != null && tasks.size() > 0) {
            topClass = tasks.get(0).topActivity.getClassName();
        }
        return topClass;
    }
}