1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.nfc.cardemulation; 17 18 import android.util.Log; 19 import android.util.SparseArray; 20 21 import com.android.nfc.NfcService; 22 23 import java.io.FileDescriptor; 24 import java.io.PrintWriter; 25 import java.util.Arrays; 26 import java.util.ArrayList; 27 import java.util.HashMap; 28 import java.util.HashSet; 29 import java.util.Map; 30 import java.util.Set; 31 32 import android.util.StatsLog; 33 34 public class AidRoutingManager { 35 36 static final String TAG = "AidRoutingManager"; 37 38 static final boolean DBG = false; 39 40 static final int ROUTE_HOST = 0x00; 41 42 // Every routing table entry is matched exact 43 static final int AID_MATCHING_EXACT_ONLY = 0x00; 44 // Every routing table entry can be matched either exact or prefix 45 static final int AID_MATCHING_EXACT_OR_PREFIX = 0x01; 46 // Every routing table entry is matched as a prefix 47 static final int AID_MATCHING_PREFIX_ONLY = 0x02; 48 // Every routing table entry can be matched either exact or prefix or subset only 49 static final int AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX = 0x03; 50 51 int mDefaultIsoDepRoute; 52 //Let mDefaultRoute as default aid route 53 int mDefaultRoute; 54 55 int mMaxAidRoutingTableSize; 56 57 final byte[] mOffHostRouteUicc; 58 final byte[] mOffHostRouteEse; 59 // Used for backward compatibility in case application doesn't specify the 60 // SE 61 final int mDefaultOffHostRoute; 62 63 // How the NFC controller can match AIDs in the routing table; 64 // see AID_MATCHING constants 65 final int mAidMatchingSupport; 66 67 final Object mLock = new Object(); 68 69 // mAidRoutingTable contains the current routing table. The index is the route ID. 70 // The route can include routes to a eSE/UICC. 71 SparseArray<Set<String>> mAidRoutingTable = 72 new SparseArray<Set<String>>(); 73 74 // Easy look-up what the route is for a certain AID 75 HashMap<String, Integer> mRouteForAid = new HashMap<String, Integer>(); 76 doGetDefaultRouteDestination()77 private native int doGetDefaultRouteDestination(); doGetDefaultOffHostRouteDestination()78 private native int doGetDefaultOffHostRouteDestination(); doGetOffHostUiccDestination()79 private native byte[] doGetOffHostUiccDestination(); doGetOffHostEseDestination()80 private native byte[] doGetOffHostEseDestination(); doGetAidMatchingMode()81 private native int doGetAidMatchingMode(); doGetDefaultIsoDepRouteDestination()82 private native int doGetDefaultIsoDepRouteDestination(); 83 84 final class AidEntry { 85 boolean isOnHost; 86 String offHostSE; 87 int route; 88 int aidInfo; 89 } 90 AidRoutingManager()91 public AidRoutingManager() { 92 mDefaultRoute = doGetDefaultRouteDestination(); 93 if (DBG) 94 Log.d(TAG, "mDefaultRoute=0x" + Integer.toHexString(mDefaultRoute)); 95 mDefaultOffHostRoute = doGetDefaultOffHostRouteDestination(); 96 if (DBG) 97 Log.d(TAG, "mDefaultOffHostRoute=0x" + Integer.toHexString(mDefaultOffHostRoute)); 98 mOffHostRouteUicc = doGetOffHostUiccDestination(); 99 if (DBG) 100 Log.d(TAG, "mOffHostRouteUicc=" + Arrays.toString(mOffHostRouteUicc)); 101 mOffHostRouteEse = doGetOffHostEseDestination(); 102 if (DBG) 103 Log.d(TAG, "mOffHostRouteEse=" + Arrays.toString(mOffHostRouteEse)); 104 mAidMatchingSupport = doGetAidMatchingMode(); 105 if (DBG) Log.d(TAG, "mAidMatchingSupport=0x" + Integer.toHexString(mAidMatchingSupport)); 106 107 mDefaultIsoDepRoute = doGetDefaultIsoDepRouteDestination(); 108 if (DBG) Log.d(TAG, "mDefaultIsoDepRoute=0x" + Integer.toHexString(mDefaultIsoDepRoute)); 109 } 110 supportsAidPrefixRouting()111 public boolean supportsAidPrefixRouting() { 112 return mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX || 113 mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY || 114 mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX; 115 } 116 supportsAidSubsetRouting()117 public boolean supportsAidSubsetRouting() { 118 return mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX; 119 } 120 calculateAidRouteSize(HashMap<String, AidEntry> routeCache)121 public int calculateAidRouteSize(HashMap<String, AidEntry> routeCache) { 122 // TAG + ROUTE + LENGTH_BYTE + POWER 123 int AID_HDR_LENGTH = 0x04; 124 int routeTableSize = 0x00; 125 for(Map.Entry<String, AidEntry> aidEntry : routeCache.entrySet()) { 126 String aid = aidEntry.getKey(); 127 // removing prefix length 128 if(aid.endsWith("*")) { 129 routeTableSize += ((aid.length() - 0x01) / 0x02) + AID_HDR_LENGTH; 130 } else { 131 routeTableSize += (aid.length() / 0x02)+ AID_HDR_LENGTH; 132 } 133 } 134 if (DBG) Log.d(TAG, "calculateAidRouteSize: " + routeTableSize); 135 return routeTableSize; 136 } 137 clearNfcRoutingTableLocked()138 private void clearNfcRoutingTableLocked() { 139 for (Map.Entry<String, Integer> aidEntry : mRouteForAid.entrySet()) { 140 String aid = aidEntry.getKey(); 141 if (aid.endsWith("*")) { 142 if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) { 143 Log.e(TAG, "Device does not support prefix AIDs but AID [" + aid 144 + "] is registered"); 145 } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY) { 146 if (DBG) Log.d(TAG, "Unrouting prefix AID " + aid); 147 // Cut off '*' since controller anyway treats all AIDs as a prefix 148 aid = aid.substring(0, aid.length() - 1); 149 } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX || 150 mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) { 151 aid = aid.substring(0, aid.length() - 1); 152 if (DBG) Log.d(TAG, "Unrouting prefix AID " + aid); 153 } 154 } else if (aid.endsWith("#")) { 155 if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) { 156 Log.e(TAG, "Device does not support subset AIDs but AID [" + aid 157 + "] is registered"); 158 } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY || 159 mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX) { 160 Log.e(TAG, "Device does not support subset AIDs but AID [" + aid 161 + "] is registered"); 162 } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) { 163 if (DBG) Log.d(TAG, "Unrouting subset AID " + aid); 164 aid = aid.substring(0, aid.length() - 1); 165 } 166 } else { 167 if (DBG) Log.d(TAG, "Unrouting exact AID " + aid); 168 } 169 170 NfcService.getInstance().unrouteAids(aid); 171 } 172 if(NfcService.getInstance().getNciVersion() != NfcService.getInstance().NCI_VERSION_1_0) { 173 // unRoute EmptyAid 174 NfcService.getInstance().unrouteAids(""); 175 } 176 } 177 getRouteForSecureElement(String se)178 private int getRouteForSecureElement(String se) { 179 if (se == null || se.length() <= 3) { 180 return 0; 181 } 182 try { 183 if (se.startsWith("eSE") && mOffHostRouteEse != null) { 184 int index = Integer.parseInt(se.substring(3)); 185 if (mOffHostRouteEse.length >= index && index > 0) { 186 return mOffHostRouteEse[index - 1] & 0xFF; 187 } 188 } else if (se.startsWith("SIM") && mOffHostRouteUicc != null) { 189 int index = Integer.parseInt(se.substring(3)); 190 if (mOffHostRouteUicc.length >= index && index > 0) { 191 return mOffHostRouteUicc[index - 1] & 0xFF; 192 } 193 } 194 if (mOffHostRouteEse == null && mOffHostRouteUicc == null) 195 return mDefaultOffHostRoute; 196 } catch (NumberFormatException e) { } 197 return 0; 198 } 199 configureRouting(HashMap<String, AidEntry> aidMap, boolean force)200 public boolean configureRouting(HashMap<String, AidEntry> aidMap, boolean force) { 201 boolean aidRouteResolved = false; 202 HashMap<String, AidEntry> aidRoutingTableCache = new HashMap<String, AidEntry>(aidMap.size()); 203 ArrayList<Integer> seList = new ArrayList<Integer>(); 204 seList.add(ROUTE_HOST); 205 206 SparseArray<Set<String>> aidRoutingTable = new SparseArray<Set<String>>(aidMap.size()); 207 HashMap<String, Integer> routeForAid = new HashMap<String, Integer>(aidMap.size()); 208 HashMap<String, Integer> infoForAid = new HashMap<String, Integer>(aidMap.size()); 209 // Then, populate internal data structures first 210 for (Map.Entry<String, AidEntry> aidEntry : aidMap.entrySet()) { 211 int route = ROUTE_HOST; 212 if (!aidEntry.getValue().isOnHost) { 213 String offHostSE = aidEntry.getValue().offHostSE; 214 if (offHostSE == null) { 215 route = mDefaultOffHostRoute; 216 } else { 217 route = getRouteForSecureElement(offHostSE); 218 if (route == 0) { 219 Log.e(TAG, "Invalid Off host Aid Entry " + offHostSE); 220 continue; 221 } 222 } 223 } 224 if (!seList.contains(route)) 225 seList.add(route); 226 aidEntry.getValue().route = route; 227 int aidType = aidEntry.getValue().aidInfo; 228 String aid = aidEntry.getKey(); 229 Set<String> entries = 230 aidRoutingTable.get(route, new HashSet<String>()); 231 entries.add(aid); 232 aidRoutingTable.put(route, entries); 233 routeForAid.put(aid, route); 234 infoForAid.put(aid, aidType); 235 } 236 237 synchronized (mLock) { 238 if (routeForAid.equals(mRouteForAid) && !force) { 239 if (DBG) Log.d(TAG, "Routing table unchanged, not updating"); 240 return false; 241 } 242 243 // Otherwise, update internal structures and commit new routing 244 clearNfcRoutingTableLocked(); 245 mRouteForAid = routeForAid; 246 mAidRoutingTable = aidRoutingTable; 247 248 mMaxAidRoutingTableSize = NfcService.getInstance().getAidRoutingTableSize(); 249 if (DBG) Log.d(TAG, "mMaxAidRoutingTableSize: " + mMaxAidRoutingTableSize); 250 251 //calculate AidRoutingTableSize for existing route destination 252 for(int index = 0; index < seList.size(); index ++) { 253 mDefaultRoute = seList.get(index); 254 if(index != 0) 255 if (DBG) Log.d(TAG, "AidRoutingTable is full, try to switch mDefaultRoute to 0x" + Integer.toHexString(mDefaultRoute)); 256 257 aidRoutingTableCache.clear(); 258 259 if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY) { 260 /* If a non-default route registers an exact AID which is shorter 261 * than this exact AID, this will create a problem with controllers 262 * that treat every AID in the routing table as a prefix. 263 * For example, if App A registers F0000000041010 as an exact AID, 264 * and App B registers F000000004 as an exact AID, and App B is not 265 * the default route, the following would be added to the routing table: 266 * F000000004 -> non-default destination 267 * However, because in this mode, the controller treats every routing table 268 * entry as a prefix, it means F0000000041010 would suddenly go to the non-default 269 * destination too, whereas it should have gone to the default. 270 * 271 * The only way to prevent this is to add the longer AIDs of the 272 * default route at the top of the table, so they will be matched first. 273 */ 274 Set<String> defaultRouteAids = mAidRoutingTable.get(mDefaultRoute); 275 if (defaultRouteAids != null) { 276 for (String defaultRouteAid : defaultRouteAids) { 277 // Check whether there are any shorted AIDs routed to non-default 278 // TODO this is O(N^2) run-time complexity... 279 for (Map.Entry<String, Integer> aidEntry : mRouteForAid.entrySet()) { 280 String aid = aidEntry.getKey(); 281 int route = aidEntry.getValue(); 282 if (defaultRouteAid.startsWith(aid) && route != mDefaultRoute) { 283 if (DBG) Log.d(TAG, "Adding AID " + defaultRouteAid + " for default " + 284 "route, because a conflicting shorter AID will be " + 285 "added to the routing table"); 286 aidRoutingTableCache.put(defaultRouteAid, aidMap.get(defaultRouteAid)); 287 } 288 } 289 } 290 } 291 } 292 293 // Add AID entries for all non-default routes 294 for (int i = 0; i < mAidRoutingTable.size(); i++) { 295 int route = mAidRoutingTable.keyAt(i); 296 if (route != mDefaultRoute) { 297 Set<String> aidsForRoute = mAidRoutingTable.get(route); 298 for (String aid : aidsForRoute) { 299 if (aid.endsWith("*")) { 300 if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) { 301 Log.e(TAG, "This device does not support prefix AIDs."); 302 } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY) { 303 if (DBG) Log.d(TAG, "Routing prefix AID " + aid + " to route " 304 + Integer.toString(route)); 305 // Cut off '*' since controller anyway treats all AIDs as a prefix 306 aidRoutingTableCache.put(aid.substring(0,aid.length() - 1), aidMap.get(aid)); 307 } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX || 308 mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) { 309 if (DBG) Log.d(TAG, "Routing prefix AID " + aid + " to route " 310 + Integer.toString(route)); 311 aidRoutingTableCache.put(aid.substring(0,aid.length() - 1), aidMap.get(aid)); 312 } 313 } else if (aid.endsWith("#")) { 314 if (mAidMatchingSupport == AID_MATCHING_EXACT_ONLY) { 315 Log.e(TAG, "Device does not support subset AIDs but AID [" + aid 316 + "] is registered"); 317 } else if (mAidMatchingSupport == AID_MATCHING_PREFIX_ONLY || 318 mAidMatchingSupport == AID_MATCHING_EXACT_OR_PREFIX) { 319 Log.e(TAG, "Device does not support subset AIDs but AID [" + aid 320 + "] is registered"); 321 } else if (mAidMatchingSupport == AID_MATCHING_EXACT_OR_SUBSET_OR_PREFIX) { 322 if (DBG) Log.d(TAG, "Routing subset AID " + aid + " to route " 323 + Integer.toString(route)); 324 aidRoutingTableCache.put(aid.substring(0,aid.length() - 1), aidMap.get(aid)); 325 } 326 } else { 327 if (DBG) Log.d(TAG, "Routing exact AID " + aid + " to route " 328 + Integer.toString(route)); 329 aidRoutingTableCache.put(aid, aidMap.get(aid)); 330 } 331 } 332 } 333 } 334 335 if(mDefaultRoute != mDefaultIsoDepRoute) { 336 if(NfcService.getInstance().getNciVersion() != NfcService.getInstance().NCI_VERSION_1_0) { 337 String emptyAid = ""; 338 AidEntry entry = new AidEntry(); 339 entry.route = mDefaultRoute; 340 if(mDefaultRoute==ROUTE_HOST) { 341 entry.isOnHost = true; 342 } else{ 343 entry.isOnHost = false; 344 } 345 entry.aidInfo = RegisteredAidCache.AID_ROUTE_QUAL_PREFIX; 346 aidRoutingTableCache.put(emptyAid, entry); 347 if (DBG) Log.d(TAG, "Add emptyAid into AidRoutingTable"); 348 } 349 } 350 351 if( calculateAidRouteSize(aidRoutingTableCache) <= mMaxAidRoutingTableSize) { 352 aidRouteResolved = true; 353 break; 354 } 355 } 356 357 if(aidRouteResolved == true) { 358 commit(aidRoutingTableCache); 359 } else { 360 StatsLog.write(StatsLog.NFC_ERROR_OCCURRED, StatsLog.NFC_ERROR_OCCURRED__TYPE__AID_OVERFLOW, 0, 0); 361 Log.e(TAG, "RoutingTable unchanged because it's full, not updating"); 362 } 363 } 364 return true; 365 } 366 commit(HashMap<String, AidEntry> routeCache )367 private void commit(HashMap<String, AidEntry> routeCache ) { 368 369 if(routeCache != null) { 370 371 for (Map.Entry<String, AidEntry> aidEntry : routeCache.entrySet()) { 372 int route = aidEntry.getValue().route; 373 int aidType = aidEntry.getValue().aidInfo; 374 String aid = aidEntry.getKey(); 375 if (DBG) Log.d (TAG, "commit aid:"+aid+"route:"+route+"aidtype:"+aidType); 376 377 NfcService.getInstance().routeAids(aid, route, aidType); 378 } 379 } 380 381 // And finally commit the routing 382 NfcService.getInstance().commitRouting(); 383 } 384 385 /** 386 * This notifies that the AID routing table in the controller 387 * has been cleared (usually due to NFC being turned off). 388 */ onNfccRoutingTableCleared()389 public void onNfccRoutingTableCleared() { 390 // The routing table in the controller was cleared 391 // To stay in sync, clear our own tables. 392 synchronized (mLock) { 393 mAidRoutingTable.clear(); 394 mRouteForAid.clear(); 395 } 396 } 397 dump(FileDescriptor fd, PrintWriter pw, String[] args)398 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 399 pw.println("Routing table:"); 400 pw.println(" Default route: " + ((mDefaultRoute == 0x00) ? "host" : "secure element")); 401 synchronized (mLock) { 402 for (int i = 0; i < mAidRoutingTable.size(); i++) { 403 Set<String> aids = mAidRoutingTable.valueAt(i); 404 pw.println(" Routed to 0x" + Integer.toHexString(mAidRoutingTable.keyAt(i)) + ":"); 405 for (String aid : aids) { 406 pw.println(" \"" + aid + "\""); 407 } 408 } 409 } 410 } 411 } 412