blob: 49beeeb3aadb12ebced3a1981fc1f0851afb8bea [file] [log] [blame]
nxpandroid64fd68c2015-09-23 16:45:15 +05301 /*
2 * Copyright (C) 2010 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/******************************************************************************
17 *
18 * The original Work has been changed by NXP Semiconductors.
19 *
20 * Copyright (C) 2015 NXP Semiconductors
21 *
22 * Licensed under the Apache License, Version 2.0 (the "License");
23 * you may not use this file except in compliance with the License.
24 * You may obtain a copy of the License at
25 *
26 * http://www.apache.org/licenses/LICENSE-2.0
27 *
28 * Unless required by applicable law or agreed to in writing, software
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
33 *
34 ******************************************************************************/
35package com.android.nfc;
36
37import android.app.ActivityManager;
38import android.app.Application;
nxpandroid6fd9cdb2017-07-12 18:25:41 +053039import android.app.backup.BackupManager;
nxpandroid64fd68c2015-09-23 16:45:15 +053040import android.app.KeyguardManager;
41import android.app.PendingIntent;
42import android.app.admin.DevicePolicyManager;
43import android.content.BroadcastReceiver;
44import android.content.ComponentName;
45import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
49import android.content.SharedPreferences;
nxpandroid3649b762017-02-24 15:44:54 +053050
nxpandroid64fd68c2015-09-23 16:45:15 +053051import android.content.pm.IPackageManager;
52import android.content.pm.PackageInfo;
nxpandroid64fd68c2015-09-23 16:45:15 +053053import android.content.pm.PackageManager;
54import android.content.pm.UserInfo;
55import android.content.res.Resources.NotFoundException;
56import android.media.AudioManager;
57import android.media.SoundPool;
58import android.net.Uri;
59import android.nfc.BeamShareData;
60import android.nfc.ErrorCodes;
61import android.nfc.FormatException;
62import android.nfc.IAppCallback;
63import android.nfc.INfcAdapter;
64import android.nfc.INfcAdapterExtras;
65import android.nfc.INfcCardEmulation;
nxpandroid34627bd2016-05-27 15:52:30 +053066import android.nfc.INfcFCardEmulation;
nxpandroid64fd68c2015-09-23 16:45:15 +053067import android.nfc.INfcTag;
68import android.nfc.INfcUnlockHandler;
nxpandroid281eb922016-08-25 20:27:46 +053069import android.nfc.ITagRemovedCallback;
nxpandroid64fd68c2015-09-23 16:45:15 +053070import android.nfc.NdefMessage;
71import android.nfc.NfcAdapter;
72import android.nfc.Tag;
73import android.nfc.TechListParcel;
74import android.nfc.TransceiveResult;
75import android.nfc.tech.Ndef;
76import android.nfc.tech.TagTechnology;
77import android.os.AsyncTask;
78import android.os.Binder;
79import android.os.Build;
80import android.os.Bundle;
81import android.os.Handler;
82import android.os.IBinder;
83import android.os.Message;
84import android.os.PowerManager;
85import android.os.Process;
86import android.os.RemoteException;
87import android.os.ServiceManager;
88import android.os.SystemClock;
89import android.os.UserHandle;
90import android.os.UserManager;
91import android.provider.Settings;
92import android.util.Log;
93
nxpandroid6fd9cdb2017-07-12 18:25:41 +053094import com.android.internal.logging.MetricsLogger;
nxpandroid64fd68c2015-09-23 16:45:15 +053095import com.android.nfc.DeviceHost.DeviceHostListener;
96import com.android.nfc.DeviceHost.LlcpConnectionlessSocket;
97import com.android.nfc.DeviceHost.LlcpServerSocket;
98import com.android.nfc.DeviceHost.LlcpSocket;
99import com.android.nfc.DeviceHost.NfcDepEndpoint;
100import com.android.nfc.DeviceHost.TagEndpoint;
101
102import com.android.nfc.dhimpl.NativeNfcSecureElement;
103import com.android.nfc.dhimpl.NativeNfcAla;
104import java.security.MessageDigest;
105
106import android.widget.Toast;
107
108import com.android.nfc.cardemulation.AidRoutingManager;
109import com.android.nfc.cardemulation.CardEmulationManager;
nxpandroidebf53fb2016-12-22 18:48:59 +0530110import com.android.nfc.cardemulation.RegisteredAidCache;
nxpandroid64fd68c2015-09-23 16:45:15 +0530111import com.android.nfc.dhimpl.NativeNfcManager;
112import com.android.nfc.handover.HandoverDataParser;
113
114import java.io.FileDescriptor;
115import java.io.PrintWriter;
nxpandroid34627bd2016-05-27 15:52:30 +0530116import java.nio.ByteBuffer;
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530117import java.util.concurrent.atomic.AtomicInteger;
nxpandroid64fd68c2015-09-23 16:45:15 +0530118import java.io.InputStream;
119import java.io.OutputStream;
120import java.io.FileInputStream;
121import java.io.FileOutputStream;
122import java.io.File;
nxpandroid281eb922016-08-25 20:27:46 +0530123import java.io.FileWriter;
nxpandroid64fd68c2015-09-23 16:45:15 +0530124import java.io.BufferedReader;
125import java.io.FileReader;
126import java.util.Arrays;
127import java.util.ArrayList;
128import java.util.HashMap;
129import java.util.List;
130import java.util.Map;
131import java.util.NoSuchElementException;
132import java.io.IOException;
133import java.io.FileNotFoundException;
nxpandroid3649b762017-02-24 15:44:54 +0530134
nxpandroid64fd68c2015-09-23 16:45:15 +0530135import android.util.Pair;
136import java.util.HashSet;
nxpandroid64fd68c2015-09-23 16:45:15 +0530137import java.util.concurrent.ExecutionException;
138
139import com.nxp.nfc.INxpNfcAdapter;
140import com.nxp.intf.ILoaderService;
141import com.nxp.intf.IJcopService;
142import com.nxp.intf.INxpExtrasService;
143import com.nxp.intf.IeSEClientServicesAdapter;
144import com.nxp.nfc.INfcDta;
145import com.nxp.nfc.INfcVzw;
146import com.nxp.nfc.INxpNfcAdapterExtras;
147import com.nxp.nfc.INxpNfcAccessExtras;
nxpandroid64fd68c2015-09-23 16:45:15 +0530148import com.nxp.nfc.NxpConstants;
149import com.vzw.nfc.RouteEntry;
150import com.gsma.nfc.internal.NxpNfcController;
151import com.nxp.nfc.gsma.internal.INxpNfcController;
152
153public class NfcService implements DeviceHostListener {
154 private static final String ACTION_MASTER_CLEAR_NOTIFICATION = "android.intent.action.MASTER_CLEAR_NOTIFICATION";
155
156 static final boolean DBG = true;
157 static final String TAG = "NfcService";
158
159 public static final String SERVICE_NAME = "nfc";
160
161 /** Regular NFC permission */
162 private static final String NFC_PERM = android.Manifest.permission.NFC;
163 private static final String NFC_PERM_ERROR = "NFC permission required";
164
165 public static final String PREF = "NfcServicePrefs";
nxpandroida9a68ba2016-01-14 21:12:17 +0530166 public static final String NXP_PREF = "NfcServiceNxpPrefs";
nxpandroid64fd68c2015-09-23 16:45:15 +0530167
168 static final String PREF_NFC_ON = "nfc_on";
169 static final boolean NFC_ON_DEFAULT = true;
170 static final String PREF_NDEF_PUSH_ON = "ndef_push_on";
171 static final boolean NDEF_PUSH_ON_DEFAULT = true;
172 static final String PREF_FIRST_BEAM = "first_beam";
173 static final String PREF_FIRST_BOOT = "first_boot";
nxpandroid64fd68c2015-09-23 16:45:15 +0530174 private static final String PREF_SECURE_ELEMENT_ON = "secure_element_on";
175 private boolean SECURE_ELEMENT_ON_DEFAULT = false;
176 private int SECURE_ELEMENT_ID_DEFAULT = 0;
nxpandroidebf53fb2016-12-22 18:48:59 +0530177 private int SECURE_ELEMENT_UICC_SLOT_DEFAULT = 1;
nxpandroid64fd68c2015-09-23 16:45:15 +0530178 private static final String PREF_DEFAULT_ROUTE_ID = "default_route_id";
179 private static final String PREF_MIFARE_DESFIRE_PROTO_ROUTE_ID = "mifare_desfire_proto_route";
180 private static final String PREF_SET_DEFAULT_ROUTE_ID ="set_default_route";
181 private static final String PREF_MIFARE_CLT_ROUTE_ID= "mifare_clt_route";
nxpandroidf1f54f52017-07-31 16:08:06 +0530182 private static final String LS_BACKUP_PATH = "/data/vendor/nfc/ls_backup.txt";
183 private static final String LS_UPDATE_BACKUP_PATH = "/data/vendor/nfc/loaderservice_updater.txt";
184 private static final String LS_UPDATE_BACKUP_OUT_PATH = "/data/vendor/nfc/loaderservice_updater_out.txt";
nxpandroid64fd68c2015-09-23 16:45:15 +0530185
nxpandroidf1f54f52017-07-31 16:08:06 +0530186 private static final String[] path = {"/data/vendor/nfc/JcopOs_Update1.apdu",
187 "/data/vendor/nfc/JcopOs_Update2.apdu",
188 "/data/vendor/nfc/JcopOs_Update3.apdu"};
nxpandroid64fd68c2015-09-23 16:45:15 +0530189
190 private static final String[] PREF_JCOP_MODTIME = {"jcop file1 modtime",
191 "jcop file2 modtime",
192 "jcop file3 modtime"};
193 private static final long[] JCOP_MODTIME_DEFAULT = {-1,-1,-1};
194 private static final long[] JCOP_MODTIME_TEMP = {-1,-1,-1};
195
196 private boolean ETSI_STOP_CONFIG = false;
nxpandroid7d44e572016-08-01 19:11:04 +0530197 private int ROUTE_ID_HOST = 0x00;
198 private int ROUTE_ID_SMX = 0x01;
199 private int ROUTE_ID_UICC = 0x02;
200 private int ROUTE_ID_UICC2 = 0x04;
nxpandroid64fd68c2015-09-23 16:45:15 +0530201
202 private int ROUTE_SWITCH_ON = 0x01;
203 private int ROUTE_SWITCH_OFF = 0x02;
204 private int ROUTE_BATT_OFF= 0x04;
205
206 private int TECH_TYPE_A= 0x01;
207 private int TECH_TYPE_B= 0x02;
208 private int TECH_TYPE_F= 0x04;
209
210 //TODO: Refer L_OSP_EXT [PN547C2]
211// private int DEFAULT_ROUTE_ID_DEFAULT = AidRoutingManager.DEFAULT_ROUTE;
212 private int DEFAULT_ROUTE_ID_DEFAULT = 0x00;
213 static final boolean SE_BROADCASTS_WITH_HCE = true;
214
215 private static final String PREF_SECURE_ELEMENT_ID = "secure_element_id";
nxpandroidebf53fb2016-12-22 18:48:59 +0530216 private static final String PREF_CUR_SELECTED_UICC_ID = "current_selected_uicc_id";
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530217 public static final int ROUTE_LOC_MASK=8;
218 public static final int TECH_TYPE_MASK=11;
219
220 static final String TRON_NFC_CE = "nfc_ce";
221 static final String TRON_NFC_P2P = "nfc_p2p";
222 static final String TRON_NFC_TAG = "nfc_tag";
nxpandroid64fd68c2015-09-23 16:45:15 +0530223
224 static final int MSG_NDEF_TAG = 0;
225 static final int MSG_CARD_EMULATION = 1;
226 static final int MSG_LLCP_LINK_ACTIVATION = 2;
227 static final int MSG_LLCP_LINK_DEACTIVATED = 3;
228 static final int MSG_TARGET_DESELECTED = 4;
229 static final int MSG_MOCK_NDEF = 7;
230 static final int MSG_SE_FIELD_ACTIVATED = 8;
231 static final int MSG_SE_FIELD_DEACTIVATED = 9;
232 static final int MSG_SE_APDU_RECEIVED = 10;
233 static final int MSG_SE_EMV_CARD_REMOVAL = 11;
234 static final int MSG_SE_MIFARE_ACCESS = 12;
235 static final int MSG_SE_LISTEN_ACTIVATED = 13;
236 static final int MSG_SE_LISTEN_DEACTIVATED = 14;
237 static final int MSG_LLCP_LINK_FIRST_PACKET = 15;
238 static final int MSG_ROUTE_AID = 16;
239 static final int MSG_UNROUTE_AID = 17;
240 static final int MSG_COMMIT_ROUTING = 18;
241 static final int MSG_INVOKE_BEAM = 19;
242
243 static final int MSG_SWP_READER_REQUESTED = 20;
244 static final int MSG_SWP_READER_ACTIVATED = 21;
245 static final int MSG_SWP_READER_DEACTIVATED = 22;
246 static final int MSG_CLEAR_ROUTING = 23;
247 static final int MSG_SET_SCREEN_STATE = 25;
248
249
250 static final int MSG_RF_FIELD_ACTIVATED = 26;
251 static final int MSG_RF_FIELD_DEACTIVATED = 27;
252 static final int MSG_RESUME_POLLING = 28;
253 static final int MSG_SWP_READER_REQUESTED_FAIL =29 ;
254 static final int MSG_SWP_READER_TAG_PRESENT = 30;
255 static final int MSG_SWP_READER_TAG_REMOVE = 31;
256 static final int MSG_CONNECTIVITY_EVENT = 40;
257 static final int MSG_VZW_ROUTE_AID = 41;
258 static final int MSG_VZW_COMMIT_ROUTING = 42;
259 static final int MSG_ROUTE_NFCID2 = 43;
260 static final int MSG_UNROUTE_NFCID2 = 44;
261 static final int MSG_COMMITINF_FELICA_ROUTING = 45;
262 static final int MSG_COMMITED_FELICA_ROUTING = 46;
263 static final int MSG_EMVCO_MULTI_CARD_DETECTED_EVENT = 47;
264 static final int MSG_ETSI_START_CONFIG = 48;
265 static final int MSG_ETSI_STOP_CONFIG = 49;
266 static final int MSG_ETSI_SWP_TIMEOUT = 50;
nxpandroide66eb092017-07-12 21:36:08 +0530267 static final int MSG_APPLY_SCREEN_STATE = 51;
nxpandroid34627bd2016-05-27 15:52:30 +0530268 static final int MSG_REGISTER_T3T_IDENTIFIER = 54;
269 static final int MSG_DEREGISTER_T3T_IDENTIFIER = 55;
nxpandroid281eb922016-08-25 20:27:46 +0530270 static final int MSG_TAG_DEBOUNCE = 56;
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530271 static final int MSG_UPDATE_STATS = 57;
nxpandroid5d64ce92016-11-18 19:48:53 +0530272 /*Restart Nfc disbale watchdog timer*/
273 static final int MSG_RESTART_WATCHDOG = 60;
nxpandroida5fd6622017-07-31 16:15:18 +0530274 static final int MSG_ROUTE_APDU = 61;
275 static final int MSG_UNROUTE_APDU = 62;
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530276 // Update stats every 4 hours
277 static final long STATS_UPDATE_INTERVAL_MS = 4 * 60 * 60 * 1000;
nxpandroid64fd68c2015-09-23 16:45:15 +0530278 static final long MAX_POLLING_PAUSE_TIMEOUT = 40000;
279 static final int TASK_ENABLE = 1;
280 static final int TASK_DISABLE = 2;
281 static final int TASK_BOOT = 3;
282 static final int TASK_EE_WIPE = 4;
nxpandroid1680a6d2017-01-13 19:13:14 +0530283 static final int TASK_RESTART = 0x1F;
nxpandroid64fd68c2015-09-23 16:45:15 +0530284 static final int MSG_CHANGE_DEFAULT_ROUTE = 52;
285 static final int MSG_SE_DELIVER_INTENT = 53;
286
287 // Copied from com.android.nfc_extras to avoid library dependency
288 // Must keep in sync with com.android.nfc_extras
289 static final int ROUTE_OFF = 1;
290 static final int ROUTE_ON_WHEN_SCREEN_ON = 2;
291
292 // Return values from NfcEe.open() - these are 1:1 mapped
293 // to the thrown EE_EXCEPTION_ exceptions in nfc-extras.
294 static final int EE_ERROR_IO = -1;
295 static final int EE_ERROR_ALREADY_OPEN = -2;
296 static final int EE_ERROR_INIT = -3;
297 static final int EE_ERROR_LISTEN_MODE = -4;
298 static final int EE_ERROR_EXT_FIELD = -5;
299 static final int EE_ERROR_NFC_DISABLED = -6;
300
301 // Polling technology masks
302 static final int NFC_POLL_A = 0x01;
303 static final int NFC_POLL_B = 0x02;
304 static final int NFC_POLL_F = 0x04;
305 static final int NFC_POLL_ISO15693 = 0x08;
306 static final int NFC_POLL_B_PRIME = 0x10;
307 static final int NFC_POLL_KOVIO = 0x20;
308
309 // minimum screen state that enables NFC polling
310 static final int NFC_POLLING_MODE = ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED;
311
312 // Time to wait for NFC controller to initialize before watchdog
313 // goes off. This time is chosen large, because firmware download
314 // may be a part of initialization.
315 static final int INIT_WATCHDOG_MS = 90000;
316 static final int INIT_WATCHDOG_LS_MS = 180000;
317 // Time to wait for routing to be applied before watchdog
318 // goes off
319 static final int ROUTING_WATCHDOG_MS = 10000;
320
321 // Amount of time to wait before closing the NFCEE connection
322 // in a disable/shutdown scenario.
323 static final int WAIT_FOR_NFCEE_OPERATIONS_MS = 5000;
324 // Polling interval for waiting on NFCEE operations
325 static final int WAIT_FOR_NFCEE_POLL_MS = 100;
326
327 // Default delay used for presence checks
328 static final int DEFAULT_PRESENCE_CHECK_DELAY = 125;
329
330 //Delay used for presence checks of NFC_F non-Ndef
331 //Make secure communication done or tranceive next request response command
332 //to pause timer before presence check command is sent
333 static final int NFC_F_TRANSCEIVE_PRESENCE_CHECK_DELAY = 500;
334
335 // The amount of time we wait before manually launching
336 // the Beam animation when called through the share menu.
337 static final int INVOKE_BEAM_DELAY_MS = 1000;
338 // for use with playSound()
339 public static final int SOUND_START = 0;
340 public static final int SOUND_END = 1;
341 public static final int SOUND_ERROR = 2;
342
nxpandroide66eb092017-07-12 21:36:08 +0530343 public static final int NCI_VERSION_2_0 = 0x20;
344
345 public static final int NCI_VERSION_1_0 = 0x10;
nxpandroid64fd68c2015-09-23 16:45:15 +0530346 //ETSI Reader Events
347 public static final int ETSI_READER_REQUESTED = 0;
348 public static final int ETSI_READER_START = 1;
349 public static final int ETSI_READER_STOP = 2;
350
351 //ETSI Reader Req States
352 public static final int STATE_SE_RDR_MODE_INVALID = 0x00;
353 public static final int STATE_SE_RDR_MODE_START_CONFIG = 0x01;
354 public static final int STATE_SE_RDR_MODE_START_IN_PROGRESS = 0x02;
355 public static final int STATE_SE_RDR_MODE_STARTED = 0x03;
356 public static final int STATE_SE_RDR_MODE_ACTIVATED = 0x04;
357 public static final int STATE_SE_RDR_MODE_STOP_CONFIG = 0x05;
358 public static final int STATE_SE_RDR_MODE_STOP_IN_PROGRESS = 0x06;
359 public static final int STATE_SE_RDR_MODE_STOPPED = 0x07;
360
nxpandroid281eb922016-08-25 20:27:46 +0530361 //Transit setconfig status
362 public static final int TRANSIT_SETCONFIG_STAT_SUCCESS = 0x00;
363 public static final int TRANSIT_SETCONFIG_STAT_FAILED = 0xFF;
364
nxpandroid64fd68c2015-09-23 16:45:15 +0530365 public static final String ACTION_RF_FIELD_ON_DETECTED =
366 "com.android.nfc_extras.action.RF_FIELD_ON_DETECTED";
367 public static final String ACTION_RF_FIELD_OFF_DETECTED =
368 "com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED";
369 public static final String ACTION_AID_SELECTED =
370 "com.android.nfc_extras.action.AID_SELECTED";
371 public static final String EXTRA_AID = "com.android.nfc_extras.extra.AID";
372
373 public static final String ACTION_LLCP_UP =
374 "com.android.nfc.action.LLCP_UP";
375
376 public static final String ACTION_LLCP_DOWN =
377 "com.android.nfc.action.LLCP_DOWN";
378
379 public static final String ACTION_APDU_RECEIVED =
380 "com.android.nfc_extras.action.APDU_RECEIVED";
381 public static final String EXTRA_APDU_BYTES =
382 "com.android.nfc_extras.extra.APDU_BYTES";
383
384 public static final String ACTION_EMV_CARD_REMOVAL =
385 "com.android.nfc_extras.action.EMV_CARD_REMOVAL";
386
387 public static final String ACTION_MIFARE_ACCESS_DETECTED =
388 "com.android.nfc_extras.action.MIFARE_ACCESS_DETECTED";
389 public static final String EXTRA_MIFARE_BLOCK =
390 "com.android.nfc_extras.extra.MIFARE_BLOCK";
391
392 public static final String ACTION_SE_LISTEN_ACTIVATED =
393 "com.android.nfc_extras.action.SE_LISTEN_ACTIVATED";
394 public static final String ACTION_SE_LISTEN_DEACTIVATED =
395 "com.android.nfc_extras.action.SE_LISTEN_DEACTIVATED";
396
397 public static final String ACTION_EMVCO_MULTIPLE_CARD_DETECTED =
398 "com.nxp.action.EMVCO_MULTIPLE_CARD_DETECTED";
399
nxpandroid34627bd2016-05-27 15:52:30 +0530400 public static final String ACTION_UICC_STATUS_RECEIVED =
401 "com.nxp.action.UICC_STATUS_RECEIVED";
402
nxpandroid1680a6d2017-01-13 19:13:14 +0530403 public static final String ACTION_FLASH_SUCCESS =
404 "com.android.nfc_extras.action.ACTION_FLASH_SUCCESS";
405
nxpandroid34627bd2016-05-27 15:52:30 +0530406 public static final String EXTRA_UICC_STATUS = "com.nxp.extra.UICC_STATUS";
407
nxpandroid64fd68c2015-09-23 16:45:15 +0530408 private static final String PACKAGE_SMART_CARD_SERVICE = "org.simalliance.openmobileapi.service";
409 /**
410 * SMART MX ID to be able to select it as the default Secure Element
411 */
412 public static final int SMART_MX_ID_TYPE = 1;
413
414 /**
415 * UICC ID to be able to select it as the default Secure Element
416 */
417 public static final int UICC_ID_TYPE = 2;
418
419 /**
nxpandroid7d44e572016-08-01 19:11:04 +0530420 * UICC2 ID to be able to select it as the default Secure Element
421 */
422 public static final int UICC2_ID_TYPE = 4;
423 /**
nxpandroid64fd68c2015-09-23 16:45:15 +0530424 * ID to be able to select all Secure Elements
425 */
nxpandroid0232af22017-07-12 21:40:33 +0530426 private static int ALL_SE_ID_TYPE = 7;
nxpandroid64fd68c2015-09-23 16:45:15 +0530427
428 public static final int PN547C2_ID = 1;
429 public static final int PN65T_ID = 2;
nxpandroidebf53fb2016-12-22 18:48:59 +0530430 public static final int PN548C2_ID = 3;
nxpandroid64fd68c2015-09-23 16:45:15 +0530431 public static final int PN66T_ID = 4;
nxpandroid34627bd2016-05-27 15:52:30 +0530432 public static final int PN551_ID = 5;
433 public static final int PN67T_ID = 6;
nxpandroid281eb922016-08-25 20:27:46 +0530434 public static final int PN553_ID = 7;
435 public static final int PN80T_ID = 8;
nxpandroid64fd68c2015-09-23 16:45:15 +0530436
437 public static final int LS_RETRY_CNT = 3;
nxpandroid5d3fdf82017-07-31 16:11:33 +0530438 public static final int LOADER_SERVICE_VERSION_LOW_LIMIT = 0x21;
439 public static final int LOADER_SERVICE_VERSION_HIGH_LIMIT = 0x24;
440
nxpandroid64fd68c2015-09-23 16:45:15 +0530441 private int mSelectedSeId = 0;
442 private boolean mNfcSecureElementState;
443 private boolean mIsSmartCardServiceSupported = false;
444 // Timeout to re-apply routing if a tag was present and we postponed it
445 private static final int APPLY_ROUTING_RETRY_TIMEOUT_MS = 5000;
446
447 private final UserManager mUserManager;
nxpandroide66eb092017-07-12 21:36:08 +0530448 private static int nci_version = NCI_VERSION_1_0;
nxpandroid64fd68c2015-09-23 16:45:15 +0530449 // NFC Execution Environment
450 // fields below are protected by this
451 private NativeNfcSecureElement mSecureElement;
452 private OpenSecureElement mOpenEe; // null when EE closed
453 private final ReaderModeDeathRecipient mReaderModeDeathRecipient =
454 new ReaderModeDeathRecipient();
455 private final NfcUnlockManager mNfcUnlockManager;
456
457 private int mEeRoutingState; // contactless interface routing
458 private int mLockscreenPollMask;
459 List<PackageInfo> mInstalledPackages; // cached version of installed packages
460 private NativeNfcAla mNfcAla;
461
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530462 private final BackupManager mBackupManager;
463
nxpandroid64fd68c2015-09-23 16:45:15 +0530464 NfcAccessExtrasService mNfcAccessExtrasService;
465
466 // fields below are used in multiple threads and protected by synchronized(this)
467 final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();
468 // mSePackages holds packages that accessed the SE, but only for the owner user,
469 // as SE access is not granted for non-owner users.
470 HashSet<String> mSePackages = new HashSet<String>();
471 int mScreenState;
nxpandroid5d64ce92016-11-18 19:48:53 +0530472 boolean mIsTaskBoot = false;
nxpandroid64fd68c2015-09-23 16:45:15 +0530473 boolean mInProvisionMode; // whether we're in setup wizard and enabled NFC provisioning
474 boolean mIsNdefPushEnabled;
475 boolean mNfcPollingEnabled; // current Device Host state of NFC-C polling
476 boolean mHostRouteEnabled; // current Device Host state of host-based routing
477 boolean mReaderModeEnabled; // current Device Host state of reader mode
478 boolean mNfceeRouteEnabled; // current Device Host state of NFC-EE routing
479 NfcDiscoveryParameters mCurrentDiscoveryParameters =
480 NfcDiscoveryParameters.getNfcOffParameters();
481 ReaderModeParams mReaderModeParams;
nxpandroid281eb922016-08-25 20:27:46 +0530482 private int mUserId;
483 boolean mPollingPaused;
484
nxpandroid623a3632017-04-10 18:27:16 +0530485 byte[] mDebounceTagUid;
nxpandroid281eb922016-08-25 20:27:46 +0530486 int mDebounceTagDebounceMs;
487 ITagRemovedCallback mDebounceTagRemovedCallback;
nxpandroid64fd68c2015-09-23 16:45:15 +0530488
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530489 // Only accessed on one thread so doesn't need locking
490 NdefMessage mLastReadNdefMessage;
491
492 // Metrics
493 AtomicInteger mNumTagsDetected;
494 AtomicInteger mNumP2pDetected;
495 AtomicInteger mNumHceDetected;
496
nxpandroid64fd68c2015-09-23 16:45:15 +0530497 // mState is protected by this, however it is only modified in onCreate()
498 // and the default AsyncTask thread so it is read unprotected from that
499 // thread
500 int mState; // one of NfcAdapter.STATE_ON, STATE_TURNING_ON, etc
501 boolean mPowerShutDown = false; // State for power shut down state
502
503 // fields below are final after onCreate()
504 Context mContext;
505 private DeviceHost mDeviceHost;
506 private SharedPreferences mPrefs;
nxpandroida9a68ba2016-01-14 21:12:17 +0530507 private SharedPreferences mNxpPrefs;
nxpandroid64fd68c2015-09-23 16:45:15 +0530508 private SharedPreferences.Editor mPrefsEditor;
nxpandroida9a68ba2016-01-14 21:12:17 +0530509 private SharedPreferences.Editor mNxpPrefsEditor;
nxpandroid64fd68c2015-09-23 16:45:15 +0530510 private PowerManager.WakeLock mRoutingWakeLock;
511 private PowerManager.WakeLock mEeWakeLock;
512
513 int mStartSound;
514 int mEndSound;
515 int mErrorSound;
516 SoundPool mSoundPool; // playback synchronized on this
517 P2pLinkManager mP2pLinkManager;
518 TagService mNfcTagService;
519 NfcAdapterService mNfcAdapter;
520 NfcAdapterExtrasService mExtrasService;
521// CardEmulationService mCardEmulationService;
522 NxpNfcAdapterService mNxpNfcAdapter;
523 NxpNfcAdapterExtrasService mNxpExtrasService;
524 NxpExtrasService mNxpExtras;
525 EseClientServicesAdapter mEseClientServicesAdapter;
nxpandroid64fd68c2015-09-23 16:45:15 +0530526 boolean mIsDebugBuild;
527 boolean mIsHceCapable;
nxpandroid34627bd2016-05-27 15:52:30 +0530528 boolean mIsHceFCapable;
nxpandroid64fd68c2015-09-23 16:45:15 +0530529 boolean mIsRoutingTableDirty;
530 boolean mIsFelicaOnHostConfigured;
531 boolean mIsFelicaOnHostConfiguring;
532
533 public boolean mIsRouteForced;
534 NfceeAccessControl mNfceeAccessControl;
535 NfcSccAccessControl mNfcSccAccessControl;
536 NfcSeAccessControl mNfcSeAccessControl;
537 NfcAlaService mAlaService;
538 NfcJcopService mJcopService;
539 NfcDtaService mDtaService;
540 NfcVzwService mVzwService;
541 private NfcDispatcher mNfcDispatcher;
542 private PowerManager mPowerManager;
543 private KeyguardManager mKeyguard;
544 ToastHandler mToastHandler;
545 private HandoverDataParser mHandoverDataParser;
546 private ContentResolver mContentResolver;
nxpandroidebf53fb2016-12-22 18:48:59 +0530547 private RegisteredAidCache mAidCache;
nxpandroid64fd68c2015-09-23 16:45:15 +0530548 private CardEmulationManager mCardEmulationManager;
549 private AidRoutingManager mAidRoutingManager;
nxpandroid64fd68c2015-09-23 16:45:15 +0530550 private ScreenStateHelper mScreenStateHelper;
551 private ForegroundUtils mForegroundUtils;
552 private boolean mClearNextTapDefault;
553 private NxpNfcController mNxpNfcController;
554
nxpandroid64fd68c2015-09-23 16:45:15 +0530555 private static NfcService sService;
nxpandroid281eb922016-08-25 20:27:46 +0530556 public static boolean sIsDtaMode = false;
557 public static boolean sIsShortRecordLayout = false;
558 public static boolean sAidTableFull = false;
nxpandroid5d64ce92016-11-18 19:48:53 +0530559 private WatchDogThread disableInternalwatchDog;
nxpandroid64fd68c2015-09-23 16:45:15 +0530560
561 //GSMA
562 private final Boolean defaultTransactionEventReceptionMode = Boolean.FALSE;
nxpandroid623a3632017-04-10 18:27:16 +0530563 private static final Boolean multiReceptionMode = Boolean.TRUE;
564 private static final Boolean unicastReceptionMode = Boolean.FALSE;
nxpandroid64fd68c2015-09-23 16:45:15 +0530565 boolean mIsSentUnicastReception = false;
566
567 public void enforceNfcSeAdminPerm(String pkg) {
568 if (pkg == null) {
569 throw new SecurityException("caller must pass a package name");
570 }
571 mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
572 if (!mNfcSeAccessControl.check(Binder.getCallingUid(), pkg)) {
573 throw new SecurityException(NfcSeAccessControl.NFCSE_ACCESS_PATH +
574 " denies NFCSe access to " + pkg);
575 }
576 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
577 throw new SecurityException("only the owner is allowed to act as SCC admin");
578 }
579 }
580 public void enforceNfceeAdminPerm(String pkg) {
581 if (pkg == null) {
582 throw new SecurityException("caller must pass a package name");
583 }
584 NfcPermissions.enforceUserPermissions(mContext);
585 if (!mNfceeAccessControl.check(Binder.getCallingUid(), pkg)) {
586 throw new SecurityException(NfceeAccessControl.NFCEE_ACCESS_PATH +
587 " denies NFCEE access to " + pkg);
588 }
589 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
590 throw new SecurityException("only the owner is allowed to call SE APIs");
591 }
592 }
593
594
595 /* SCC Access Control */
596 public void enforceNfcSccAdminPerm(String pkg) {
597 if (pkg == null) {
598 throw new SecurityException("caller must pass a package name");
599 }
600 mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
601 if (!mNfcSccAccessControl.check(Binder.getCallingUid(), pkg)) {
602 throw new SecurityException(NfcSccAccessControl.NFCSCC_ACCESS_PATH +
603 " denies NFCSCC access to " + pkg);
604 }
605 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
606 throw new SecurityException("only the owner is allowed to act as SCC admin");
607 }
608 }
609
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530610 boolean mIsLiveCaseEnabled; // whether live cases are enabled
611 int mLiveCaseTechnology; // Technology mask of accepted NFC tags
612
nxpandroid64fd68c2015-09-23 16:45:15 +0530613 public static NfcService getInstance() {
614 return sService;
615 }
616
617 @Override
618 public void onRemoteEndpointDiscovered(TagEndpoint tag) {
619 sendMessage(NfcService.MSG_NDEF_TAG, tag);
620 }
621
622 public int getRemainingAidTableSize() {
623 return mDeviceHost.getRemainingAidTableSize();
624 }
625
nxpandroidebf53fb2016-12-22 18:48:59 +0530626 public boolean getLastCommitRoutingStatus() {
627 return mAidRoutingManager.getLastCommitRoutingStatus();
628 }
629
nxpandroid64fd68c2015-09-23 16:45:15 +0530630 public int getChipVer() {
631 return mDeviceHost.getChipVer();
632 }
633 /**
634 * Notifies Card emulation deselect
635 */
636 @Override
637 public void onCardEmulationDeselected() {
638 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
639 sendMessage(NfcService.MSG_TARGET_DESELECTED, null);
640 }
641 }
642
643 /**
644 * Notifies transaction
645 */
646 @Override
647 public void onCardEmulationAidSelected(byte[] aid, byte[] data, int evtSrc) {
648 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
649 Pair<byte[], Integer> dataSrc = new Pair<byte[], Integer>(data, evtSrc);
650 Pair<byte[], Pair> transactionInfo = new Pair<byte[], Pair>(aid, dataSrc);
651 Log.d(TAG, "onCardEmulationAidSelected : Source" + evtSrc);
652
653 sendMessage(NfcService.MSG_CARD_EMULATION, transactionInfo);
654 }
655 }
656
657 /**
658 * Notifies connectivity
659 */
660 @Override
661 public void onConnectivityEvent(int evtSrc) {
662 Log.d(TAG, "onConnectivityEvent : Source" + evtSrc);
663 sendMessage(NfcService.MSG_CONNECTIVITY_EVENT, evtSrc);
664 }
665
666 @Override
667 public void onEmvcoMultiCardDetectedEvent() {
668 Log.d(TAG, "onEmvcoMultiCardDetectedEvent");
669 sendMessage(NfcService.MSG_EMVCO_MULTI_CARD_DETECTED_EVENT,null);
670 }
671
672 /**
673 * Notifies transaction
674 */
675 @Override
nxpandroid34627bd2016-05-27 15:52:30 +0530676 public void onHostCardEmulationActivated(int technology) {
nxpandroid64fd68c2015-09-23 16:45:15 +0530677 if (mCardEmulationManager != null) {
nxpandroid34627bd2016-05-27 15:52:30 +0530678 mCardEmulationManager.onHostCardEmulationActivated(technology);
nxpandroid64fd68c2015-09-23 16:45:15 +0530679 }
680 }
681
682 @Override
683 public void onAidRoutingTableFull() {
684 Log.d(TAG, "NxpNci: onAidRoutingTableFull: AID Routing Table is FULL!");
nxpandroid281eb922016-08-25 20:27:46 +0530685 /*if((ROUTE_ID_HOST != GetDefaultRouteLoc())&&(sAidTableFull == false))
nxpandroid64fd68c2015-09-23 16:45:15 +0530686 {
687 Log.d(TAG, "NxpNci: onAidRoutingTableFull: Making Default Route to HOST!");
nxpandroid281eb922016-08-25 20:27:46 +0530688 sAidTableFull = true;
nxpandroid64fd68c2015-09-23 16:45:15 +0530689 mHandler.sendEmptyMessage(NfcService.MSG_CHANGE_DEFAULT_ROUTE);
690 }*/
691 if (mIsHceCapable) {
692 mAidRoutingManager.onNfccRoutingTableCleared();
693 mCardEmulationManager.onRoutingTableChanged();
694 }
695 }
696
697 @Override
nxpandroid5d64ce92016-11-18 19:48:53 +0530698 public void onNotifyT3tConfigure() {
699 if (mCardEmulationManager != null) {
700 mCardEmulationManager.onT3tConfigure();
701 }
702 }
703
704 @Override
705 public void onNotifyReRoutingEntry() {
706 if (mCardEmulationManager != null) {
707 mCardEmulationManager.onReRoutingEntry();
708 }
709 }
710
711 @Override
nxpandroid34627bd2016-05-27 15:52:30 +0530712 public void onHostCardEmulationData(int technology, byte[] data) {
nxpandroid64fd68c2015-09-23 16:45:15 +0530713 if (mCardEmulationManager != null) {
nxpandroid34627bd2016-05-27 15:52:30 +0530714 mCardEmulationManager.onHostCardEmulationData(technology, data);
nxpandroid64fd68c2015-09-23 16:45:15 +0530715 }
716 }
717
718 @Override
nxpandroid34627bd2016-05-27 15:52:30 +0530719 public void onHostCardEmulationDeactivated(int technology) {
nxpandroid64fd68c2015-09-23 16:45:15 +0530720 if (mCardEmulationManager != null) {
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530721 // Do metrics here so we don't slow the CE path down
722 mNumHceDetected.incrementAndGet();
nxpandroid34627bd2016-05-27 15:52:30 +0530723 mCardEmulationManager.onHostCardEmulationDeactivated(technology);
nxpandroid64fd68c2015-09-23 16:45:15 +0530724 }
725 }
726
727 /**
728 * Notifies P2P Device detected, to activate LLCP link
729 */
730 @Override
731 public void onLlcpLinkActivated(NfcDepEndpoint device) {
732 sendMessage(NfcService.MSG_LLCP_LINK_ACTIVATION, device);
733 }
734
735 /**
736 * Notifies P2P Device detected, to activate LLCP link
737 */
738 @Override
739 public void onLlcpLinkDeactivated(NfcDepEndpoint device) {
740 sendMessage(NfcService.MSG_LLCP_LINK_DEACTIVATED, device);
741 }
742
743 /**
744 * Notifies P2P Device detected, first packet received over LLCP link
745 */
746 @Override
747 public void onLlcpFirstPacketReceived(NfcDepEndpoint device) {
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530748 mNumP2pDetected.incrementAndGet();
nxpandroid64fd68c2015-09-23 16:45:15 +0530749 sendMessage(NfcService.MSG_LLCP_LINK_FIRST_PACKET, device);
750 }
751
752 @Override
753 public void onRemoteFieldActivated() {
754 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
755 sendMessage(NfcService.MSG_SE_FIELD_ACTIVATED, null);
756 }
757 }
758
759 @Override
760 public void onRemoteFieldDeactivated() {
761 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
762 sendMessage(NfcService.MSG_SE_FIELD_DEACTIVATED, null);
763 }
764 }
765
766 @Override
767 public void onSeListenActivated() {
768 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
769 sendMessage(NfcService.MSG_SE_LISTEN_ACTIVATED, null);
770 }
771 if (mIsHceCapable) {
nxpandroid34627bd2016-05-27 15:52:30 +0530772 mCardEmulationManager.onHostCardEmulationActivated(TagTechnology.NFC_A);
nxpandroid64fd68c2015-09-23 16:45:15 +0530773 }
774 }
775
776 @Override
777 public void onSeListenDeactivated() {
778 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
779 sendMessage(NfcService.MSG_SE_LISTEN_DEACTIVATED, null);
780 }
781 if( mIsHceCapable) {
nxpandroid34627bd2016-05-27 15:52:30 +0530782 mCardEmulationManager.onHostCardEmulationDeactivated(TagTechnology.NFC_A);
nxpandroid64fd68c2015-09-23 16:45:15 +0530783 }
784 }
785
nxpandroid64fd68c2015-09-23 16:45:15 +0530786 @Override
787 public void onSeApduReceived(byte[] apdu) {
788 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
789 sendMessage(NfcService.MSG_SE_APDU_RECEIVED, apdu);
790 }
791 }
792
793 @Override
794 public void onSeEmvCardRemoval() {
795 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
796 sendMessage(NfcService.MSG_SE_EMV_CARD_REMOVAL, null);
797 }
798 }
799
800 @Override
801 public void onSeMifareAccess(byte[] block) {
802 if (!mIsHceCapable || SE_BROADCASTS_WITH_HCE) {
803 sendMessage(NfcService.MSG_SE_MIFARE_ACCESS, block);
804 }
805 }
806
807 @Override
808 public void onSWPReaderRequestedEvent(boolean istechA, boolean istechB)
809 {
810 int size=0;
811 ArrayList<Integer> techList = new ArrayList<Integer>();
812 if(istechA)
813 techList.add(TagTechnology.NFC_A);
814 if(istechB)
815 techList.add(TagTechnology.NFC_B);
816
817 sendMessage(NfcService.MSG_SWP_READER_REQUESTED , techList);
818 }
819
820 @Override
821 public void onSWPReaderRequestedFail(int FailCause)
822 {
823 sendMessage(NfcService.MSG_SWP_READER_REQUESTED_FAIL , FailCause);
824 }
825
826 @Override
827 public void onSWPReaderActivatedEvent()
828 {
829 sendMessage(NfcService.MSG_SWP_READER_ACTIVATED, null);
830 }
831
832 @Override
833 public void onETSIReaderModeStartConfig(int eeHandle)
834 {
835 ArrayList<Integer> configList = new ArrayList<Integer>();
836 configList.add(eeHandle);
837 sendMessage(NfcService.MSG_ETSI_START_CONFIG, configList);
838 }
839
840 @Override
841 public void onETSIReaderModeStopConfig(int disc_ntf_timeout)
842 {
843 sendMessage(NfcService.MSG_ETSI_STOP_CONFIG, disc_ntf_timeout);
844 }
845
846 @Override
847 public void onETSIReaderModeSwpTimeout(int disc_ntf_timeout)
848 {
849 sendMessage(NfcService.MSG_ETSI_SWP_TIMEOUT, disc_ntf_timeout);
850 }
851
nxpandroid34627bd2016-05-27 15:52:30 +0530852 @Override
853 public void onUiccStatusEvent(int uiccStat)
854 {
855 Log.i(TAG, "Broadcasting UICC Status : " + uiccStat);
856 Intent uiccStatusIntent = new Intent();
857 uiccStatusIntent.setAction(ACTION_UICC_STATUS_RECEIVED);
858 uiccStatusIntent.putExtra(EXTRA_UICC_STATUS, uiccStat);
859 mContext.sendBroadcast(uiccStatusIntent);
860 }
861
nxpandroid5d64ce92016-11-18 19:48:53 +0530862 @Override
863 public void onRestartWatchDog(int enable) {
864 Log.d(TAG, "Restart Watchdog: WatchDog Thread ID is "+ disableInternalwatchDog.getId());
865 sendMessage(NfcService.MSG_RESTART_WATCHDOG, enable);
866 }
nxpandroid1680a6d2017-01-13 19:13:14 +0530867 @Override
868 public void onFwDwnldReqRestartNfc() {
869 Log.d(TAG, "Restart NFC:When Fw dwnld request was stored during SPI onGoing");
870 new EnableDisableTask().execute(TASK_RESTART);
871 }
nxpandroid5d64ce92016-11-18 19:48:53 +0530872
nxpandroid64fd68c2015-09-23 16:45:15 +0530873 final class ReaderModeParams {
874 public int flags;
875 public IAppCallback callback;
876 public int presenceCheckDelay;
877 }
878
879 public NfcService(Application nfcApplication) {
880 mUserId = ActivityManager.getCurrentUser();
881 mContext = nfcApplication;
882
883 mNfcTagService = new TagService();
884 mNfcAdapter = new NfcAdapterService();
885 mNxpNfcAdapter = new NxpNfcAdapterService();
886 mExtrasService = new NfcAdapterExtrasService();
887 mNxpExtrasService = new NxpNfcAdapterExtrasService();
888 // mCardEmulationService = new CardEmulationService();
889
890 Log.i(TAG, "Starting NFC service");
891
892 sService = this;
893
894 mScreenStateHelper = new ScreenStateHelper(mContext);
895 mContentResolver = mContext.getContentResolver();
896 mDeviceHost = new NativeNfcManager(mContext, this);
897
898 mNfcUnlockManager = NfcUnlockManager.getInstance();
899
900 mHandoverDataParser = new HandoverDataParser();
901 boolean isNfcProvisioningEnabled = false;
902 try {
903 isNfcProvisioningEnabled = mContext.getResources().getBoolean(
904 R.bool.enable_nfc_provisioning);
905 } catch (NotFoundException e) {
906 }
907
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530908 try {
909 mIsLiveCaseEnabled = mContext.getResources().getBoolean(R.bool.enable_live_cases);
910 } catch (NotFoundException e) {
911 mIsLiveCaseEnabled = false;
912 }
913
914 mLiveCaseTechnology = 0;
915 String[] liveCaseTechList;
916 try {
917 liveCaseTechList = mContext.getResources().getStringArray(R.array.live_case_tag_types);
918 for (int i=0; i < liveCaseTechList.length; i++) {
919 if (liveCaseTechList[i].equals("TypeA")) {
920 mLiveCaseTechnology |= NFC_POLL_A;
921 } else if (liveCaseTechList[i].equals("TypeB")) {
922 mLiveCaseTechnology |= NFC_POLL_B;
923 } else if (liveCaseTechList[i].equals("TypeF")) {
924 mLiveCaseTechnology |= NFC_POLL_F;
925 } else if (liveCaseTechList[i].equals("TypeV")) {
926 mLiveCaseTechnology |= NFC_POLL_ISO15693;
927 }
928 }
929 } catch (NotFoundException e) {
930 mLiveCaseTechnology = 0;
931 }
932
nxpandroid64fd68c2015-09-23 16:45:15 +0530933 if (isNfcProvisioningEnabled) {
934 mInProvisionMode = Settings.Secure.getInt(mContentResolver,
935 Settings.Global.DEVICE_PROVISIONED, 0) == 0;
936 } else {
937 mInProvisionMode = false;
938 }
939
nxpandroid1153eb32015-11-06 18:46:58 +0530940 if(mInProvisionMode)
941 {
942 /* if device is in provision mode, set this mode at lower layers */
943 mDeviceHost.doSetProvisionMode(mInProvisionMode);
944 }
945
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530946 mNfcDispatcher = new NfcDispatcher(mContext, mHandoverDataParser, mInProvisionMode,
947 mIsLiveCaseEnabled);
nxpandroid64fd68c2015-09-23 16:45:15 +0530948 mP2pLinkManager = new P2pLinkManager(mContext, mHandoverDataParser,
949 mDeviceHost.getDefaultLlcpMiu(), mDeviceHost.getDefaultLlcpRwSize());
950
951 mSecureElement = new NativeNfcSecureElement(mContext);
952 mEeRoutingState = ROUTE_OFF;
953 mToastHandler = new ToastHandler(mContext);
954
955 mNfceeAccessControl = new NfceeAccessControl(mContext);
956 mNfcSccAccessControl = new NfcSccAccessControl(mContext);
957 mNfcSeAccessControl = new NfcSeAccessControl(mContext);
958 mNfcAla = new NativeNfcAla();
959
960 mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
961 mPrefsEditor = mPrefs.edit();
nxpandroida9a68ba2016-01-14 21:12:17 +0530962 mNxpPrefs = mContext.getSharedPreferences(NXP_PREF, Context.MODE_PRIVATE);
963 mNxpPrefsEditor = mNxpPrefs.edit();
nxpandroid64fd68c2015-09-23 16:45:15 +0530964
965 mState = NfcAdapter.STATE_OFF;
966 mIsNdefPushEnabled = mPrefs.getBoolean(PREF_NDEF_PUSH_ON, NDEF_PUSH_ON_DEFAULT);
967 setBeamShareActivityState(mIsNdefPushEnabled);
968
969 mIsDebugBuild = "userdebug".equals(Build.TYPE) || "eng".equals(Build.TYPE);
970
971 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
972
973 mRoutingWakeLock = mPowerManager.newWakeLock(
974 PowerManager.PARTIAL_WAKE_LOCK, "NfcService:mRoutingWakeLock");
975 mEeWakeLock = mPowerManager.newWakeLock(
976 PowerManager.PARTIAL_WAKE_LOCK, "NfcService:mEeWakeLock");
977
978 mKeyguard = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
979 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
980
981 mScreenState = mScreenStateHelper.checkScreenState();
982
nxpandroid6fd9cdb2017-07-12 18:25:41 +0530983 mNumTagsDetected = new AtomicInteger();
984 mNumP2pDetected = new AtomicInteger();
985 mNumHceDetected = new AtomicInteger();
986
987 mBackupManager = new BackupManager(mContext);
988
nxpandroid64fd68c2015-09-23 16:45:15 +0530989 // Intents for all users
990 IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
991 filter.addAction(Intent.ACTION_SCREEN_OFF);
992 filter.addAction(Intent.ACTION_SCREEN_ON);
993 filter.addAction(Intent.ACTION_USER_PRESENT);
994 filter.addAction(Intent.ACTION_USER_SWITCHED);
nxpandroid64fd68c2015-09-23 16:45:15 +0530995 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, null);
996
nxpandroid5d64ce92016-11-18 19:48:53 +0530997 filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
998 mContext.registerReceiver(mOwnerReceiver, filter);
999
nxpandroid64fd68c2015-09-23 16:45:15 +05301000 IntentFilter ownerFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1001 ownerFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1002 mContext.registerReceiver(mOwnerReceiver, ownerFilter);
1003
1004 ownerFilter = new IntentFilter();
1005 ownerFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1006 ownerFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1007 ownerFilter.addDataScheme("package");
1008 mContext.registerReceiver(mOwnerReceiver, ownerFilter);
1009
1010 IntentFilter x509CertificateFilter = new IntentFilter();
1011 x509CertificateFilter.addAction(NxpConstants.ACTION_CHECK_X509_RESULT);
nxpandroid5d64ce92016-11-18 19:48:53 +05301012 mContext.registerReceiverAsUser(x509CertificateReceiver, UserHandle.ALL,
1013 x509CertificateFilter, NfcPermissions.ADMIN_PERM, null);
nxpandroid64fd68c2015-09-23 16:45:15 +05301014
1015 IntentFilter enableNfc = new IntentFilter();
1016 enableNfc.addAction(NxpConstants.ACTION_GSMA_ENABLE_NFC);
nxpandroid5d64ce92016-11-18 19:48:53 +05301017 mContext.registerReceiverAsUser(mEnableNfc, UserHandle.ALL, enableNfc, null, null);
nxpandroid64fd68c2015-09-23 16:45:15 +05301018
1019 IntentFilter lsFilter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
1020 //mContext.registerReceiver(mAlaReceiver, lsFilter);
1021 mContext.registerReceiverAsUser(mAlaReceiver, UserHandle.ALL, lsFilter, null, null);
1022
1023 IntentFilter policyFilter = new IntentFilter(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1024 mContext.registerReceiverAsUser(mPolicyReceiver, UserHandle.ALL, policyFilter, null, null);
1025
1026 updatePackageCache();
1027
1028 PackageManager pm = mContext.getPackageManager();
nxpandroid34627bd2016-05-27 15:52:30 +05301029 mIsHceCapable =
1030 pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION) ||
1031 pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF);
1032 mIsHceFCapable =
1033 pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF);
1034
nxpandroid64fd68c2015-09-23 16:45:15 +05301035 if (mIsHceCapable) {
1036 mAidRoutingManager = new AidRoutingManager();
nxpandroid1680a6d2017-01-13 19:13:14 +05301037 mCardEmulationManager = new CardEmulationManager(mContext, mAidRoutingManager);
1038 mAidCache = mCardEmulationManager.getRegisteredAidCache();
nxpandroid64fd68c2015-09-23 16:45:15 +05301039 //mCardEmulationManager = new CardEmulationManager(mContext);
1040 Log.d("NfcService", "Before mIsHceCapable");
1041 mNxpNfcController = new NxpNfcController(mContext, mCardEmulationManager);
1042 }
1043
1044 mForegroundUtils = ForegroundUtils.getInstance();
nxpandroid281eb922016-08-25 20:27:46 +05301045
1046 // Make sure this is only called when object construction is complete.
1047 ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
1048
nxpandroid64fd68c2015-09-23 16:45:15 +05301049 new EnableDisableTask().execute(TASK_BOOT); // do blocking boot tasks
nxpandroid6fd9cdb2017-07-12 18:25:41 +05301050
1051 mHandler.sendEmptyMessageDelayed(MSG_UPDATE_STATS, STATS_UPDATE_INTERVAL_MS);
nxpandroid64fd68c2015-09-23 16:45:15 +05301052 }
1053
1054 void initSoundPool() {
1055 synchronized(this) {
1056 if (mSoundPool == null) {
1057 mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
1058 mStartSound = mSoundPool.load(mContext, R.raw.start, 1);
1059 mEndSound = mSoundPool.load(mContext, R.raw.end, 1);
1060 mErrorSound = mSoundPool.load(mContext, R.raw.error, 1);
1061 }
1062 }
1063 }
1064
1065 void releaseSoundPool() {
1066 synchronized (this) {
1067 if (mSoundPool != null) {
1068 mSoundPool.release();
1069 mSoundPool = null;
1070 }
1071 }
1072 }
1073
nxpandroid64fd68c2015-09-23 16:45:15 +05301074 void updatePackageCache() {
1075 PackageManager pm = mContext.getPackageManager();
nxpandroid281eb922016-08-25 20:27:46 +05301076 List<PackageInfo> packages = pm.getInstalledPackagesAsUser(0, UserHandle.USER_SYSTEM);
nxpandroid64fd68c2015-09-23 16:45:15 +05301077 synchronized (this) {
1078 mInstalledPackages = packages;
1079 }
1080 }
1081
nxpandroid7d44e572016-08-01 19:11:04 +05301082 int doOpenSecureElementConnection(int seId) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301083 mEeWakeLock.acquire();
1084 try {
nxpandroid7d44e572016-08-01 19:11:04 +05301085 return mSecureElement.doOpenSecureElementConnection(seId);
nxpandroid64fd68c2015-09-23 16:45:15 +05301086 } finally {
1087 mEeWakeLock.release();
1088 }
1089 }
1090
1091 byte[] doTransceive(int handle, byte[] cmd) {
1092 mEeWakeLock.acquire();
1093 try {
1094 return doTransceiveNoLock(handle, cmd);
1095 } finally {
1096 mEeWakeLock.release();
1097 }
1098 }
1099
1100 byte[] doTransceiveNoLock(int handle, byte[] cmd) {
1101 return mSecureElement.doTransceive(handle, cmd);
1102 }
1103
1104 void doDisconnect(int handle) {
1105 mEeWakeLock.acquire();
1106 try {
1107 mSecureElement.doDisconnect(handle);
1108 } finally {
1109 mEeWakeLock.release();
1110 }
1111 }
1112
1113 boolean doReset(int handle) {
1114 mEeWakeLock.acquire();
1115 try {
1116 return mSecureElement.doReset(handle);
1117 } finally {
1118 mEeWakeLock.release();
1119 }
1120 }
1121
1122 public static byte[] CreateSHA(String pkg, int alaVer){
nxpandroid281eb922016-08-25 20:27:46 +05301123 String localTAG = "Utils:CreateSHA";
nxpandroid64fd68c2015-09-23 16:45:15 +05301124 StringBuffer sb = new StringBuffer();
1125 try {
1126 MessageDigest md;
1127 if(alaVer == 1)
1128 md = MessageDigest.getInstance("SHA-256");
1129 else
1130 md = MessageDigest.getInstance("SHA-1");
1131
1132 md.update(pkg.getBytes());
1133
nxpandroid281eb922016-08-25 20:27:46 +05301134 byte[] byteData = md.digest();
1135 Log.i(localTAG, "byteData len : " + byteData.length);
nxpandroid64fd68c2015-09-23 16:45:15 +05301136 /*
1137 for (int i = 0; i < byteData.length; i++) {
1138 sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
1139 }
1140 // Log.i(TAG, "sb.toString()" + sb.toString());*/
1141 return byteData;
1142 } catch (Exception e) {
1143 e.printStackTrace();
1144 }
1145 return null;
1146 }
1147
1148 public static String getCallingAppPkg(Context context) {
nxpandroid281eb922016-08-25 20:27:46 +05301149 String localTAG = "getCallingAppPkg";
nxpandroid64fd68c2015-09-23 16:45:15 +05301150 ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
1151
1152 // get the info from the currently running task
1153 List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
1154
1155 Log.d("topActivity", "CURRENT Activity ::"
1156 + taskInfo.get(0).topActivity.getClassName());
1157 String s = taskInfo.get(0).topActivity.getClassName();
1158
1159 ComponentName componentInfo = taskInfo.get(0).topActivity;
1160 componentInfo.getPackageName();
nxpandroid281eb922016-08-25 20:27:46 +05301161 Log.i(localTAG,"componentInfo.getPackageName()" + componentInfo.getPackageName());
nxpandroid64fd68c2015-09-23 16:45:15 +05301162 return componentInfo.getPackageName();
1163 }
1164
1165 /**
1166 * Manages tasks that involve turning on/off the NFC controller.
1167 * <p/>
1168 * <p>All work that might turn the NFC adapter on or off must be done
1169 * through this task, to keep the handling of mState simple.
1170 * In other words, mState is only modified in these tasks (and we
1171 * don't need a lock to read it in these tasks).
1172 * <p/>
1173 * <p>These tasks are all done on the same AsyncTask background
1174 * thread, so they are serialized. Each task may temporarily transition
1175 * mState to STATE_TURNING_OFF or STATE_TURNING_ON, but must exit in
1176 * either STATE_ON or STATE_OFF. This way each task can be guaranteed
1177 * of starting in either STATE_OFF or STATE_ON, without needing to hold
1178 * NfcService.this for the entire task.
1179 * <p/>
1180 * <p>AsyncTask's are also implicitly queued. This is useful for corner
1181 * cases like turning airplane mode on while TASK_ENABLE is in progress.
1182 * The TASK_DISABLE triggered by airplane mode will be correctly executed
1183 * immediately after TASK_ENABLE is complete. This seems like the most sane
1184 * way to deal with these situations.
1185 * <p/>
1186 * <p>{@link #TASK_ENABLE} enables the NFC adapter, without changing
1187 * preferences
1188 * <p>{@link #TASK_DISABLE} disables the NFC adapter, without changing
1189 * preferences
1190 * <p>{@link #TASK_BOOT} does first boot work and may enable NFC
1191 */
1192 class EnableDisableTask extends AsyncTask<Integer, Void, Void> {
1193 @Override
1194 protected Void doInBackground(Integer... params) {
1195 // Sanity check mState
1196 switch (mState) {
1197 case NfcAdapter.STATE_TURNING_OFF:
1198 case NfcAdapter.STATE_TURNING_ON:
1199 Log.e(TAG, "Processing EnableDisable task " + params[0] + " from bad state " +
1200 mState);
1201 return null;
1202 }
1203
1204 /* AsyncTask sets this thread to THREAD_PRIORITY_BACKGROUND,
1205 * override with the default. THREAD_PRIORITY_BACKGROUND causes
1206 * us to service software I2C too slow for firmware download
1207 * with the NXP PN544.
1208 * TODO: move this to the DAL I2C layer in libnfc-nxp, since this
1209 * problem only occurs on I2C platforms using PN544
1210 */
1211 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1212
1213 switch (params[0].intValue()) {
1214 case TASK_ENABLE:
1215 enableInternal();
1216 break;
1217 case TASK_DISABLE:
1218 disableInternal();
1219 break;
1220 case TASK_BOOT:
1221 Log.d(TAG, "checking on firmware download");
nxpandroid7d44e572016-08-01 19:11:04 +05301222 if (mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT)) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301223 Log.d(TAG, "NFC is on. Doing normal stuff");
nxpandroid5d64ce92016-11-18 19:48:53 +05301224 mIsTaskBoot = true;
nxpandroid64fd68c2015-09-23 16:45:15 +05301225 enableInternal();
nxpandroid5d64ce92016-11-18 19:48:53 +05301226 mIsTaskBoot = false;
nxpandroid64fd68c2015-09-23 16:45:15 +05301227 } else {
1228 Log.d(TAG, "NFC is off. Checking firmware version");
1229 mDeviceHost.checkFirmware();
1230 }
1231 if (mPrefs.getBoolean(PREF_FIRST_BOOT, true)) {
1232 Log.i(TAG, "First Boot");
1233 mPrefsEditor.putBoolean(PREF_FIRST_BOOT, false);
1234 mPrefsEditor.apply();
1235 }
1236 break;
nxpandroid1680a6d2017-01-13 19:13:14 +05301237 case TASK_RESTART:
1238 restartInternal();
1239
nxpandroid64fd68c2015-09-23 16:45:15 +05301240 }
1241
1242 // Restore default AsyncTask priority
1243 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1244 return null;
1245 }
1246
1247 @Override
1248 protected void onPostExecute(Void result) {
1249
1250 if(mState == NfcAdapter.STATE_ON){
1251 IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
1252 filter.addAction(Intent.ACTION_SCREEN_OFF);
1253 filter.addAction(Intent.ACTION_SCREEN_ON);
1254 filter.addAction(Intent.ACTION_USER_PRESENT);
1255 filter.addAction(Intent.ACTION_USER_SWITCHED);
nxpandroid64fd68c2015-09-23 16:45:15 +05301256 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, null);
1257 }else if (mState == NfcAdapter.STATE_OFF){
1258 mContext.unregisterReceiver(mReceiver);
1259 IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
1260 filter.addAction(Intent.ACTION_USER_SWITCHED);
nxpandroid64fd68c2015-09-23 16:45:15 +05301261 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, null);
1262 }
1263
1264
1265 }
1266
1267 /**
1268 * Check the default Secure Element configuration.
1269 */
1270 void checkSecureElementConfuration() {
1271
1272 /* Get SE List */
nxpandroid281eb922016-08-25 20:27:46 +05301273 int[] seList = mDeviceHost.doGetSecureElementList();
nxpandroidebf53fb2016-12-22 18:48:59 +05301274 int uiccSlot = 0;
1275 uiccSlot = mPrefs.getInt(PREF_CUR_SELECTED_UICC_ID, SECURE_ELEMENT_UICC_SLOT_DEFAULT);
1276 int status = mDeviceHost.setPreferredSimSlot(uiccSlot);
nxpandroid64fd68c2015-09-23 16:45:15 +05301277 /* Check Secure Element setting */
nxpandroid281eb922016-08-25 20:27:46 +05301278 int seNum=mDeviceHost.GetDefaultSE();
1279 if(seNum != 0)
nxpandroid64fd68c2015-09-23 16:45:15 +05301280 {
1281 SECURE_ELEMENT_ON_DEFAULT=true;
nxpandroid281eb922016-08-25 20:27:46 +05301282 SECURE_ELEMENT_ID_DEFAULT=seNum;
nxpandroid64fd68c2015-09-23 16:45:15 +05301283 } else {
nxpandroid281eb922016-08-25 20:27:46 +05301284 if (seList != null) {
1285 for (int i = 0; i < seList.length; i++) {
1286 mDeviceHost.doDeselectSecureElement(seList[i]);
nxpandroid64fd68c2015-09-23 16:45:15 +05301287 }
1288 }
1289 }
1290
1291 mNfcSecureElementState =
nxpandroida9a68ba2016-01-14 21:12:17 +05301292 mNxpPrefs.getBoolean(PREF_SECURE_ELEMENT_ON, SECURE_ELEMENT_ON_DEFAULT);
nxpandroid64fd68c2015-09-23 16:45:15 +05301293
1294 if (mNfcSecureElementState) {
1295 int secureElementId =
nxpandroida9a68ba2016-01-14 21:12:17 +05301296 mNxpPrefs.getInt(PREF_SECURE_ELEMENT_ID, SECURE_ELEMENT_ID_DEFAULT);
nxpandroid64fd68c2015-09-23 16:45:15 +05301297
nxpandroid281eb922016-08-25 20:27:46 +05301298 if (seList != null) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301299
1300 if (secureElementId != ALL_SE_ID_TYPE/* SECURE_ELEMENT_ALL */) {
1301 mDeviceHost.doDeselectSecureElement(UICC_ID_TYPE);
nxpandroid7d44e572016-08-01 19:11:04 +05301302 mDeviceHost.doDeselectSecureElement(UICC2_ID_TYPE);
nxpandroid64fd68c2015-09-23 16:45:15 +05301303 mDeviceHost.doDeselectSecureElement(SMART_MX_ID_TYPE);
1304
nxpandroid281eb922016-08-25 20:27:46 +05301305 for (int i = 0; i < seList.length; i++) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301306
nxpandroid281eb922016-08-25 20:27:46 +05301307 if (seList[i] == secureElementId) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301308 if (secureElementId == SMART_MX_ID_TYPE) { // SECURE_ELEMENT_SMX_ID
nxpandroid281eb922016-08-25 20:27:46 +05301309 if (seList.length > 1) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301310 if (DBG) {
1311 Log.d(TAG, "Deselect UICC");
1312 }
1313 }
1314 Log.d(TAG, "Select SMX");
1315 mDeviceHost.doSelectSecureElement(secureElementId);
1316 mSelectedSeId = secureElementId;
1317 break;
1318 } else if (secureElementId == UICC_ID_TYPE/* SECURE_ELEMENT_UICC_ID */) {
nxpandroid281eb922016-08-25 20:27:46 +05301319 if (seList.length > 1) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301320 if (DBG) {
1321 Log.d(TAG, "Deselect SMX");
1322 }
1323 }
1324 Log.d(TAG, "Select UICC");
1325 mDeviceHost.doSelectSecureElement(secureElementId);
1326 mSelectedSeId = secureElementId;
1327 break;
nxpandroid7d44e572016-08-01 19:11:04 +05301328 }else if (secureElementId == UICC2_ID_TYPE/* SECURE_ELEMENT_UICC_ID */) {
nxpandroid281eb922016-08-25 20:27:46 +05301329 if (seList.length > 1) {
nxpandroid7d44e572016-08-01 19:11:04 +05301330 if (DBG) {
1331 Log.d(TAG, "Deselect SMX");
1332 }
1333 }
1334 Log.d(TAG, "Select UICC2");
1335 mDeviceHost.doSelectSecureElement(secureElementId);
1336 mSelectedSeId = secureElementId;
1337 break;
nxpandroid64fd68c2015-09-23 16:45:15 +05301338 } else if (secureElementId == SECURE_ELEMENT_ID_DEFAULT) {
nxpandroid281eb922016-08-25 20:27:46 +05301339 if (seList.length > 1) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301340 if (DBG) {
1341 Log.d(TAG, "UICC deselected by default");
1342 }
1343 }
1344 }
1345 }
1346 }
1347 } else {
1348 if (DBG) {
1349 Log.d(TAG, "Select ALL_SE");
1350 }
1351
nxpandroid281eb922016-08-25 20:27:46 +05301352 if (seList.length > 1) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301353
nxpandroid281eb922016-08-25 20:27:46 +05301354 for (int i = 0; i < seList.length; i++) {
1355 mDeviceHost.doSelectSecureElement(seList[i]);
nxpandroid64fd68c2015-09-23 16:45:15 +05301356 try{
1357 //Delay b/w two SE selection.
1358 Thread.sleep(200);
1359 } catch(Exception e) {
1360 e.printStackTrace();
1361 }
1362 }
1363 mSelectedSeId = secureElementId;
1364 }
1365 }
1366 }
1367 } else {
nxpandroid281eb922016-08-25 20:27:46 +05301368 if (seList != null && seList.length > 0) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301369 if (DBG) {
1370 Log.d(TAG, "UICC/eSE deselected by default");
1371 }
1372 mDeviceHost.doDeselectSecureElement(UICC_ID_TYPE);
nxpandroid7d44e572016-08-01 19:11:04 +05301373 mDeviceHost.doDeselectSecureElement(UICC2_ID_TYPE);
nxpandroid64fd68c2015-09-23 16:45:15 +05301374 mDeviceHost.doDeselectSecureElement(SMART_MX_ID_TYPE);
1375 }
1376 }
1377 }
1378
1379 boolean getJcopOsFileInfo() {
1380 File jcopOsFile;
1381 Log.i(TAG, "getJcopOsFileInfo");
1382
1383 for (int num = 0; num < 3; num++) {
1384 try{
1385 jcopOsFile = new File(path[num]);
1386 }catch(NullPointerException npe) {
1387 Log.e(TAG,"path to jcop os file was null");
1388 return false;
1389 }
1390 long modtime = jcopOsFile.lastModified();
1391 SharedPreferences prefs = mContext.getSharedPreferences(PREF,Context.MODE_PRIVATE);
1392 long prev_modtime = prefs.getLong(PREF_JCOP_MODTIME[num], JCOP_MODTIME_DEFAULT[num]);
1393 Log.d(TAG,"prev_modtime:" + prev_modtime);
1394 Log.d(TAG,"new_modtime:" + modtime);
1395 if(prev_modtime == modtime){
1396 return false;
1397 }
1398 JCOP_MODTIME_TEMP[num] = modtime;
1399 }
1400 return true;
1401 }
1402
1403 /* jcop os Download at boot time */
1404 void jcopOsDownload() {
1405 int status = ErrorCodes.SUCCESS;
1406 boolean jcopStatus;
1407 Log.i(TAG, "Jcop Download starts");
1408
1409 SharedPreferences prefs = mContext.getSharedPreferences(PREF,Context.MODE_PRIVATE);
1410 jcopStatus = getJcopOsFileInfo();
1411
1412 if( jcopStatus == true) {
1413 Log.i(TAG, "Starting getChipName");
1414 int Ver = mDeviceHost.getChipVer();
nxpandroid281eb922016-08-25 20:27:46 +05301415 if(Ver == PN80T_ID || Ver == PN67T_ID || Ver == PN66T_ID || Ver == PN65T_ID) {
nxpandroid64fd68c2015-09-23 16:45:15 +05301416 status = mDeviceHost.JCOSDownload();
1417 }
1418 if(status != ErrorCodes.SUCCESS) {
1419 Log.i(TAG, "Jcop Download failed");
1420 }
1421 else {
1422 Log.i(TAG, "Jcop Download success");
1423 prefs.edit().putLong(PREF_JCOP_MODTIME[0],JCOP_MODTIME_TEMP[0]).apply();
1424 prefs.edit().putLong(PREF_JCOP_MODTIME[1],JCOP_MODTIME_TEMP[1]).apply();
1425 prefs.edit().putLong(PREF_JCOP_MODTIME[2],JCOP_MODTIME_TEMP[2]).apply();
1426 }
1427 }
1428 }
1429 /**
1430 * Enable NFC adapter functions.
1431 * Does not toggle preferences.
1432 */
1433 boolean enableInternal() {
1434 if (mState == NfcAdapter.STATE_ON) {
1435 return true;
1436 }
1437 Log.i(TAG, "Enabling NFC");
1438 updateState(NfcAdapter.STATE_TURNING_ON);
1439 int timeout = mDeviceHost.getNfcInitTimeout();
1440 if (timeout < INIT_WATCHDOG_MS)
1441 {
1442 timeout = INIT_WATCHDOG_MS;
1443 }
1444 Log.i(TAG, "Enabling NFC timeout" +timeout);
1445 WatchDogThread watchDog = new WatchDogThread("enableInternal", timeout);
1446 watchDog.start();
1447 try {
1448 mRoutingWakeLock.acquire();
1449 try {
1450 if (!mDeviceHost.initialize()) {
1451 Log.w(TAG, "Error enabling NFC");
1452 updateState(NfcAdapter.STATE_OFF);
1453 return false;
1454 }
1455 } finally {
1456 mRoutingWakeLock.release();
1457 }
1458 } finally {
1459 watchDog.cancel();
1460 }
nxpandroid5d64ce92016-11-18 19:48:53 +05301461 int chipVer = mDeviceHost.getChipVer();
1462 if((chipVer == PN80T_ID) || (chipVer == PN553_ID)) {
1463 ALL_SE_ID_TYPE |= UICC2_ID_TYPE;
1464 }
nxpandroid64fd68c2015-09-23 16:45:15 +05301465 checkSecureElementConfuration();
1466
1467 mIsRouteForced = true;
1468 if (mIsHceCapable) {
1469 // Generate the initial card emulation routing table
nxpandroid281eb922016-08-25 20:27:46 +05301470 sAidTableFull = false;
nxpandroid64fd68c2015-09-23 16:45:15 +05301471 mCardEmulationManager.onNfcEnabled();
1472 }
1473 mIsRouteForced = false;
nxpandroide66eb092017-07-12 21:36:08 +05301474 nci_version = getNciVersion();
nxpandroid64fd68c2015-09-23 16:45:15 +05301475
1476 synchronized (NfcService.this) {
1477 mObjectMap.clear();
1478 mP2pLinkManager.enableDisable(mIsNdefPushEnabled, true);
1479 updateState(NfcAdapter.STATE_ON);
1480 }
1481
1482 synchronized (NfcService.this) {
1483 if(mDeviceHost.doCheckJcopDlAtBoot()) {
1484 /* start jcop download */
1485 Log.i(TAG, "Calling Jcop Download");
1486 jcopOsDownload();
1487 }
1488 }
1489
1490 initSoundPool();
1491 /* Start polling loop */
1492 Log.e(TAG, "applyRouting -3");
1493 mScreenState = mScreenStateHelper.checkScreenState();
nxpandroide66eb092017-07-12 21:36:08 +05301494 int screen_state_mask = (mNfcUnlockManager.isLockscreenPollingEnabled()) ?
1495 (ScreenStateHelper.SCREEN_POLLING_TAG_MASK | mScreenState) : mScreenState;
1496
1497 if(mNfcUnlockManager.isLockscreenPollingEnabled())
1498 applyRouting(false);
1499
1500 mDeviceHost.doSetScreenOrPowerState(screen_state_mask);
nxpandroid64fd68c2015-09-23 16:45:15 +05301501 mIsRoutingTableDirty = true;
nxpandroid5d64ce92016-11-18 19:48:53 +05301502 if((mScreenState < NFC_POLLING_MODE) && mIsTaskBoot)
1503 {
1504 /*During device boot if screen state is other ON_UNLOCKED,
1505 *first send discovery command with poll and linsten enabled
1506 *for DC/DC pass through mode activation.
1507 *Then send normal discovery according to screen state*/
1508 applyRouting(true);
1509 mIsTaskBoot = false;
1510 }
nxpandroid64fd68c2015-09-23 16:45:15 +05301511 applyRouting(true);
1512 return true;
1513 }
1514
1515 /**
1516 * Disable all NFC adapter functions.
1517 * Does not toggle preferences.
1518 */
1519 boolean disableInternal() {
1520 if (mState == NfcAdapter.STATE_OFF) {
1521 return true;
1522 }
1523 Log.i(TAG, "Disabling NFC");
1524 updateState(NfcAdapter.STATE_TURNING_OFF);
1525
1526 /* Sometimes mDeviceHost.deinitialize() hangs, use a watch-dog.
1527 * Implemented with a new thread (instead of a Handler or AsyncTask),
1528 * because the UI Thread and AsyncTask thread-pools can also get hung
1529 * when the NFC controller stops responding */
nxpandroid5d64ce92016-11-18 19:48:53 +05301530 disableInternalwatchDog = new WatchDogThread("disableInternal", ROUTING_WATCHDOG_MS);
1531 disableInternalwatchDog.start();
nxpandroid64fd68c2015-09-23 16:45:15 +05301532
1533 if (mIsHceCapable) {
1534 mCardEmulationManager.onNfcDisabled();
1535 }
1536
1537 mP2pLinkManager.enableDisable(false, false);
1538
1539 /* The NFC-EE may still be opened by another process,
1540 * and a transceive() could still be in progress on
1541 * another Binder thread.
1542 * Give it a while to finish existing operations
1543 * before we close it.
1544 */
1545 Long startTime = SystemClock.elapsedRealtime();
1546 do {
1547 synchronized (NfcService.this) {
1548 if (mOpenEe == null)
1549 break;
1550 }
1551 try {
1552 Thread.sleep(WAIT_FOR_NFCEE_POLL_MS);
1553 } catch (InterruptedException e) {
1554 // Ignore
1555 }
1556 } while (SystemClock.elapsedRealtime() - startTime < WAIT_FOR_NFCEE_OPERATIONS_MS);
1557
1558 synchronized (NfcService.this) {
1559 if (mOpenEe != null) {
1560 try {
1561 _nfcEeClose(-1, mOpenEe.binder);
1562 } catch (IOException e) { }
1563 }
1564 }
1565
1566 // Stop watchdog if tag present
1567 // A convenient way to stop the watchdog properly consists of
1568 // disconnecting the tag. The polling loop shall be stopped before
1569 // to avoid the tag being discovered again.
1570 maybeDisconnectTarget();
1571
1572 mNfcDispatcher.setForegroundDispatch(null, null, null);
1573
1574 boolean result = mDeviceHost.deinitialize();
1575 if (DBG) Log.d(TAG, "mDeviceHost.deinitialize() = " + result);
1576
nxpandroid5d64ce92016-11-18 19:48:53 +05301577 disableInternalwatchDog.cancel();
nxpandroid64fd68c2015-09-23 16:45:15 +05301578
1579 synchronized (NfcService.this) {
1580 mCurrentDiscoveryParameters = NfcDiscoveryParameters.getNfcOffParameters();
1581 updateState(NfcAdapter.STATE_OFF);
1582 }
1583
1584 releaseSoundPool();
1585
1586 return result;
1587 }
1588
nxpandroid1680a6d2017-01-13 19:13:14 +05301589 boolean restartInternal()
1590 {
1591 boolean result;
1592 result = disableInternal();
1593 if (DBG) Log.d(TAG, "disableInternal status = " + result);
1594 while(true)
1595 {
1596 if(mState == NfcAdapter.STATE_OFF)
1597 {
1598 if (DBG) Log.d(TAG, "disableInternal is success = " + result);
1599 break;
1600 }
1601 }
1602 result = enableInternal();
1603 if (DBG) Log.d(TAG, "enableInternal status = " + result);
1604 while(true)
1605 {
1606 if(mState == NfcAdapter.STATE_ON)
1607 {
1608 if (DBG) Log.d(TAG, "enableInternal is success = " + result);
1609 break;
1610 }
1611 }
1612 Intent flashIntent = new Intent();
1613 flashIntent.setAction(ACTION_FLASH_SUCCESS);
1614 if (DBG) Log.d(TAG, "Broadcasting " + ACTION_FLASH_SUCCESS);
1615 mContext.sendBroadcast(flashIntent);
1616 return result;
1617 }
1618
nxpandroid64fd68c2015-09-23 16:45:15 +05301619 void updateState(int newState) {
1620 synchronized (NfcService.this) {
1621 if (newState == mState) {
1622 return;
1623 }
nxpandroid34627bd2016-05-27 15:52:30 +05301624 int Ver = mDeviceHost.getChipVer();
nxpandroid281eb922016-08-25 20:27:46 +05301625 if(Ver == PN80T_ID || Ver == PN67T_ID || Ver == PN66T_ID || Ver == PN65T_ID) {
nxpandroid34627bd2016-05-27 15:52:30 +05301626 /*Added for Loader service recover during NFC Off/On*/
1627 if(newState == NfcAdapter.STATE_ON){
1628 NfcAlaService nas = new NfcAlaService();
1629 nas.LSReexecute();
1630 IntentFilter lsFilter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
1631 mContext.registerReceiverAsUser(mAlaReceiver, UserHandle.ALL, lsFilter, null, null);
1632 }
nxpandroid64fd68c2015-09-23 16:45:15 +05301633 }
1634 mState = newState;
1635 Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
1636 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1637 intent.putExtra(NfcAdapter.EXTRA_ADAPTER_STATE, mState);
1638 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
1639 }
1640 }
1641 }
1642
1643 void saveNfcOnSetting(boolean on) {
1644 synchronized (NfcService.this) {
1645 mPrefsEditor.putBoolean(PREF_NFC_ON, on);
1646 mPrefsEditor.apply();
nxpandroid6fd9cdb2017-07-12 18:25:41 +05301647 mBackupManager.dataChanged();
nxpandroid64fd68c2015-09-23 16:45:15 +05301648 }
1649 }
1650
1651 public void playSound(int sound) {
1652 synchronized (this) {
1653 if (mSoundPool == null) {
1654 Log.w(TAG, "Not playing sound when NFC is disabled");
1655 return;
1656 }
1657 switch (sound) {
1658 case SOUND_START:
1659 mSoundPool.play(mStartSound, 1.0f, 1.0f, 0, 0, 1.0f);
1660 break;
1661 case SOUND_END:
1662 mSoundPool.play(mEndSound, 1.0f, 1.0f, 0, 0, 1.0f);
1663 break;
1664 case SOUND_ERROR:
1665 mSoundPool.play(mErrorSound, 1.0f, 1.0f, 0, 0, 1.0f);
1666 break;
1667 }
1668 }
1669 }
1670
1671 synchronized int getUserId() {
1672 return mUserId;
1673 }
1674
1675 void setBeamShareActivityState(boolean enabled) {
1676 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1677 // Propagate the state change to all user profiles related to the current
1678 // user. Note that the list returned by getUserProfiles contains the
1679 // current user.
1680 List <UserHandle> luh = um.getUserProfiles();
1681 for (UserHandle uh : luh){
1682 enforceBeamShareActivityPolicy(mContext, uh, enabled);
1683 }
1684 }
1685
1686 void enforceBeamShareActivityPolicy(Context context, UserHandle uh,
1687 boolean isGlobalEnabled){
1688 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
1689 IPackageManager mIpm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
1690 boolean isActiveForUser =
1691 (!um.hasUserRestriction(UserManager.DISALLOW_OUTGOING_BEAM, uh)) &&
1692 isGlobalEnabled;
1693 if (DBG){
1694 Log.d(TAG, "Enforcing a policy change on user: " + uh +
1695 ", isActiveForUser = " + isActiveForUser);
1696 }
1697 try {
1698 mIpm.setComponentEnabledSetting(new ComponentName(
1699 BeamShareActivity.class.getPackageName$(),
1700 BeamShareActivity.class.getName()),
1701 isActiveForUser ?
1702 PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
1703 PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
1704 PackageManager.DONT_KILL_APP,
1705 uh.getIdentifier());
1706 } catch (RemoteException e) {
1707 Log.w(TAG, "Unable to change Beam status for user " + uh);
1708 }
1709 }
1710
1711 final class NfcAdapterService extends INfcAdapter.Stub {
1712 @Override
1713 public boolean enable() throws RemoteException {
1714 NfcPermissions.enforceAdminPermissions(mContext);
1715 int val = mDeviceHost.GetDefaultSE();
1716 Log.i(TAG, "getDefaultSE " + val);
1717
1718 saveNfcOnSetting(true);
1719
nxpandroid64fd68c2015-09-23 16:45:15 +05301720 new EnableDisableTask().execute(TASK_ENABLE);
1721
1722 return true;
1723 }
1724
nxpandroid64fd68c2015-09-23 16:45:15 +05301725 @Override
1726 public boolean disable(boolean saveState) throws RemoteException {
1727 NfcPermissions.enforceAdminPermissions(mContext);
1728 Log.d(TAG,"Disabling Nfc.");
1729
1730 //Check if this a device shutdown or Nfc only Nfc disable.
1731 if(!mPowerShutDown)
1732 {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05301733 int[] seList = mDeviceHost.doGetSecureElementList();
nxpandroid64fd68c2015-09-23 16:45:15 +05301734 Log.i(TAG, "Disabling NFC Disabling ESE/UICC");
nxpandroid64fd68c2015-09-23 16:45:15 +05301735 //Since only Nfc is getting disabled so disable CE from EE.
nxpandroida9a68ba2016-01-14 21:12:17 +05301736 mDeviceHost.doSetScreenOrPowerState(ScreenStateHelper.POWER_STATE_ON);
nxpandroid6fd9cdb2017-07-12 18:25:41 +05301737 if (seList != null) {
1738 for (int i = 0; i < seList.length; i++) {
1739 mDeviceHost.doDeselectSecureElement(seList[i]);
1740 }
1741 }
nxpandroid64fd68c2015-09-23 16:45:15 +05301742 } else {
1743 Log.i(TAG, "Power off : Disabling NFC Disabling ESE/UICC");
1744 mPowerShutDown = false;
nxpandroid64fd68c2015-09-23 16:45:15 +05301745 mCardEmulationManager.onPreferredForegroundServiceChanged(null);
1746 }
1747
1748 if (saveState) {
1749 saveNfcOnSetting(false);
1750 }
1751
1752 new EnableDisableTask().execute(TASK_DISABLE);
1753
1754 return true;
1755 }
1756
1757 @Override
1758 public void pausePolling(int timeoutInMs) {
1759 NfcPermissions.enforceAdminPermissions(mContext);
1760
1761 if (timeoutInMs <= 0 || timeoutInMs > MAX_POLLING_PAUSE_TIMEOUT) {
1762 Log.e(TAG, "Refusing to pause polling for " + timeoutInMs + "ms.");
1763 return;
1764 }
1765
1766 synchronized (NfcService.this) {
1767 mPollingPaused = true;
1768 mDeviceHost.disableDiscovery();
1769 mHandler.sendMessageDelayed(
1770 mHandler.obtainMessage(MSG_RESUME_POLLING), timeoutInMs);
1771 }
1772 }
1773
1774 @Override
1775 public void resumePolling() {
1776 NfcPermissions.enforceAdminPermissions(mContext);
1777
1778 synchronized (NfcService.this) {
1779 if (!mPollingPaused) {
1780 return;
1781 }
1782
1783 mHandler.removeMessages(MSG_RESUME_POLLING);
1784 mPollingPaused = false;
1785 new ApplyRoutingTask().execute();
1786 }
1787 }
1788
1789 @Override
1790 public boolean isNdefPushEnabled() throws RemoteException {
1791 synchronized (NfcService.this) {
1792 return mState == NfcAdapter.STATE_ON && mIsNdefPushEnabled;
1793 }
1794 }
1795
1796 @Override
1797 public boolean enableNdefPush() throws RemoteException {
1798 NfcPermissions.enforceAdminPermissions(mContext);
1799 synchronized (NfcService.this) {
1800 if (mIsNdefPushEnabled) {
1801 return true;
1802 }
1803 Log.i(TAG, "enabling NDEF Push");
1804 mPrefsEditor.putBoolean(PREF_NDEF_PUSH_ON, true);
1805 mPrefsEditor.apply();
1806 mIsNdefPushEnabled = true;
1807 setBeamShareActivityState(true);
1808 if (isNfcEnabled()) {
nxpandroid5d64ce92016-11-18 19:48:53 +05301809 mDeviceHost.doEnablep2p(mIsNdefPushEnabled);
nxpandroid64fd68c2015-09-23 16:45:15 +05301810 mP2pLinkManager.enableDisable(true, true);
1811 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05301812 mBackupManager.dataChanged();
nxpandroid64fd68c2015-09-23 16:45:15 +05301813 }
1814 return true;
1815 }
1816
1817 @Override
1818 public boolean disableNdefPush() throws RemoteException {
1819 NfcPermissions.enforceAdminPermissions(mContext);
1820 synchronized (NfcService.this) {
1821 if (!mIsNdefPushEnabled) {
1822 return true;
1823 }
1824 Log.i(TAG, "disabling NDEF Push");
1825 mPrefsEditor.putBoolean(PREF_NDEF_PUSH_ON, false);
1826 mPrefsEditor.apply();
1827 mIsNdefPushEnabled = false;
1828 setBeamShareActivityState(false);
1829 if (isNfcEnabled()) {
1830 mP2pLinkManager.enableDisable(false, true);
1831 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05301832 mBackupManager.dataChanged();
nxpandroid64fd68c2015-09-23 16:45:15 +05301833 }
1834 return true;
1835 }
1836
1837 @Override
1838 public void setForegroundDispatch(PendingIntent intent,
1839 IntentFilter[] filters, TechListParcel techListsParcel) {
1840 NfcPermissions.enforceUserPermissions(mContext);
nxpandroid281eb922016-08-25 20:27:46 +05301841 if (!mForegroundUtils.isInForeground(Binder.getCallingUid())) {
1842 Log.e(TAG, "setForegroundDispatch: Caller not in foreground.");
1843 return;
1844 }
nxpandroid64fd68c2015-09-23 16:45:15 +05301845 // Short-cut the disable path
1846 if (intent == null && filters == null && techListsParcel == null) {
1847 mNfcDispatcher.setForegroundDispatch(null, null, null);
1848 return;
1849 }
1850
1851 // Validate the IntentFilters
1852 if (filters != null) {
1853 if (filters.length == 0) {
1854 filters = null;
1855 } else {
1856 for (IntentFilter filter : filters) {
1857 if (filter == null) {
1858 throw new IllegalArgumentException("null IntentFilter");
1859 }
1860 }
1861 }
1862 }
1863
1864 // Validate the tech lists
1865 String[][] techLists = null;
1866 if (techListsParcel != null) {
1867 techLists = techListsParcel.getTechLists();
1868 }
1869
1870 mNfcDispatcher.setForegroundDispatch(intent, filters, techLists);
1871 }
1872
1873 @Override
1874 public void setAppCallback(IAppCallback callback) {
1875 NfcPermissions.enforceUserPermissions(mContext);
1876
1877 // don't allow Beam for managed profiles, or devices with a device owner or policy owner
1878 UserInfo userInfo = mUserManager.getUserInfo(UserHandle.getCallingUserId());
1879 if(!mUserManager.hasUserRestriction(
1880 UserManager.DISALLOW_OUTGOING_BEAM, userInfo.getUserHandle())) {
1881 mP2pLinkManager.setNdefCallback(callback, Binder.getCallingUid());
1882 } else if (DBG) {
1883 Log.d(TAG, "Disabling default Beam behavior");
1884 }
1885 }
1886
1887 @Override
1888 public INfcAdapterExtras getNfcAdapterExtrasInterface(String pkg) {
nxpandroida51b5bd2017-04-10 18:28:21 +05301889
1890 if (pkg.equals(PACKAGE_SMART_CARD_SERVICE)){
1891 Log.d(TAG, "wildcard for SmartcardService");
1892 return mExtrasService;
1893 }
1894
nxpandroid64fd68c2015-09-23 16:45:15 +05301895 NfcService.this.enforceNfceeAdminPerm(pkg);
1896 return mExtrasService;
1897 }
1898
nxpandroid281eb922016-08-25 20:27:46 +05301899 @Override
1900 public boolean ignore(int nativeHandle, int debounceMs, ITagRemovedCallback callback)
1901 throws RemoteException {
1902 NfcPermissions.enforceUserPermissions(mContext);
1903
1904 TagEndpoint tag = (TagEndpoint) findAndRemoveObject(nativeHandle);
1905 if (tag != null) {
1906 // Store UID and params
1907 int uidLength = tag.getUid().length;
1908 synchronized (NfcService.this) {
1909 mDebounceTagDebounceMs = debounceMs;
1910 mDebounceTagUid = new byte[uidLength];
1911 mDebounceTagRemovedCallback = callback;
1912 System.arraycopy(tag.getUid(), 0, mDebounceTagUid, 0, uidLength);
1913 }
1914
1915 // Disconnect from this tag; this should resume the normal
1916 // polling loop (and enter listen mode for a while), before
1917 // we pick up any tags again.
1918 tag.disconnect();
1919 mHandler.sendEmptyMessageDelayed(MSG_TAG_DEBOUNCE, debounceMs);
1920 return true;
1921 } else {
1922 return false;
1923 }
1924 }
1925
nxpandroid64fd68c2015-09-23 16:45:15 +05301926 @Override
1927 public void verifyNfcPermission() {
1928 NfcPermissions.enforceUserPermissions(mContext);
1929 }
1930
1931 @Override
1932 public void invokeBeam() {
1933 NfcPermissions.enforceUserPermissions(mContext);
1934
1935 if (mForegroundUtils.isInForeground(Binder.getCallingUid())) {
1936 mP2pLinkManager.onManualBeamInvoke(null);
1937 } else {
1938 Log.e(TAG, "Calling activity not in foreground.");
1939 }
1940 }
1941
1942 @Override
1943 public void invokeBeamInternal(BeamShareData shareData) {
1944 NfcPermissions.enforceAdminPermissions(mContext);
1945 Message msg = Message.obtain();
1946 msg.what = MSG_INVOKE_BEAM;
1947 msg.obj = shareData;
1948 // We have to send this message delayed for two reasons:
1949 // 1) This is an IPC call from BeamShareActivity, which is
1950 // running when the user has invoked Beam through the
1951 // share menu. As soon as BeamShareActivity closes, the UI
1952 // will need some time to rebuild the original Activity.
1953 // Waiting here for a while gives a better chance of the UI
1954 // having been rebuilt, which means the screenshot that the
1955 // Beam animation is using will be more accurate.
1956 // 2) Similarly, because the Activity that launched BeamShareActivity
1957 // with an ACTION_SEND intent is now in paused state, the NDEF
1958 // callbacks that it has registered may no longer be valid.
1959 // Allowing the original Activity to resume will make sure we
1960 // it has a chance to re-register the NDEF message / callback,
1961 // so we share the right data.
1962 //
1963 // Note that this is somewhat of a hack because the delay may not actually
1964 // be long enough for 2) on very slow devices, but there's no better
1965 // way to do this right now without additional framework changes.
1966 mHandler.sendMessageDelayed(msg, INVOKE_BEAM_DELAY_MS);
1967 }
1968
1969 @Override
1970 public INfcTag getNfcTagInterface() throws RemoteException {
1971 return mNfcTagService;
1972 }
1973
1974 @Override
1975 public INfcCardEmulation getNfcCardEmulationInterface() {
1976 if (mIsHceCapable) {
1977 return mCardEmulationManager.getNfcCardEmulationInterface();
1978 } else {
1979 return null;
1980 }
1981 }
1982
nxpandroid34627bd2016-05-27 15:52:30 +05301983 @Override
1984 public INfcFCardEmulation getNfcFCardEmulationInterface() {
1985 if (mIsHceFCapable) {
1986 return mCardEmulationManager.getNfcFCardEmulationInterface();
1987 } else {
1988 return null;
1989 }
1990 }
1991
nxpandroid64fd68c2015-09-23 16:45:15 +05301992
1993 @Override
1994 public int getState() throws RemoteException {
1995 synchronized (NfcService.this) {
1996 return mState;
1997 }
1998 }
1999
2000 @Override
2001 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2002 NfcService.this.dump(fd, pw, args);
2003 }
2004
2005 @Override
2006 public void dispatch(Tag tag) throws RemoteException {
2007 NfcPermissions.enforceAdminPermissions(mContext);
2008 mNfcDispatcher.dispatchTag(tag);
2009 }
2010
2011 @Override
2012 public void setP2pModes(int initiatorModes, int targetModes) throws RemoteException {
2013 NfcPermissions.enforceAdminPermissions(mContext);
2014 mDeviceHost.setP2pInitiatorModes(initiatorModes);
2015 mDeviceHost.setP2pTargetModes(targetModes);
2016 applyRouting(true);
2017 }
2018
2019 @Override
2020 public void setReaderMode(IBinder binder, IAppCallback callback, int flags, Bundle extras)
2021 throws RemoteException {
nxpandroid281eb922016-08-25 20:27:46 +05302022 int callingUid = Binder.getCallingUid();
2023 if (callingUid != Process.SYSTEM_UID && !mForegroundUtils.isInForeground(callingUid)) {
2024 Log.e(TAG, "setReaderMode: Caller is not in foreground and is not system process.");
2025 return;
2026 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302027 synchronized (NfcService.this) {
nxpandroid34627bd2016-05-27 15:52:30 +05302028 if (!isNfcEnabled()) {
2029 Log.e(TAG, "setReaderMode() called while NFC is not enabled.");
2030 return;
2031 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302032 if (flags != 0) {
2033 try {
2034 mReaderModeParams = new ReaderModeParams();
2035 mReaderModeParams.callback = callback;
2036 mReaderModeParams.flags = flags;
2037 mReaderModeParams.presenceCheckDelay = extras != null
2038 ? (extras.getInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY,
2039 DEFAULT_PRESENCE_CHECK_DELAY))
2040 : DEFAULT_PRESENCE_CHECK_DELAY;
2041 binder.linkToDeath(mReaderModeDeathRecipient, 0);
2042 } catch (RemoteException e) {
2043 Log.e(TAG, "Remote binder has already died.");
2044 return;
2045 }
2046 } else {
2047 try {
2048 mReaderModeParams = null;
2049 binder.unlinkToDeath(mReaderModeDeathRecipient, 0);
2050 } catch (NoSuchElementException e) {
2051 Log.e(TAG, "Reader mode Binder was never registered.");
2052 }
2053 }
2054 Log.e(TAG, "applyRouting -4");
2055 applyRouting(false);
2056 }
2057 }
2058
2059
2060 @Override
2061 public void addNfcUnlockHandler(INfcUnlockHandler unlockHandler, int[] techList) {
2062 NfcPermissions.enforceAdminPermissions(mContext);
2063
2064 int lockscreenPollMask = computeLockscreenPollMask(techList);
2065 synchronized (NfcService.this) {
2066 mNfcUnlockManager.addUnlockHandler(unlockHandler, lockscreenPollMask);
2067 }
2068
2069 applyRouting(false);
2070 }
2071
2072 @Override
2073 public void removeNfcUnlockHandler(INfcUnlockHandler token) throws RemoteException {
2074 synchronized (NfcService.this) {
2075 mNfcUnlockManager.removeUnlockHandler(token.asBinder());
2076 }
2077
2078 applyRouting(false);
2079 }
2080 private int computeLockscreenPollMask(int[] techList) {
2081
2082 Map<Integer, Integer> techCodeToMask = new HashMap<Integer, Integer>();
2083
2084 techCodeToMask.put(TagTechnology.NFC_A, NfcService.NFC_POLL_A);
2085 techCodeToMask.put(TagTechnology.NFC_B, NfcService.NFC_POLL_B);
2086 techCodeToMask.put(TagTechnology.NFC_V, NfcService.NFC_POLL_ISO15693);
2087 techCodeToMask.put(TagTechnology.NFC_F, NfcService.NFC_POLL_F);
2088 techCodeToMask.put(TagTechnology.NFC_BARCODE, NfcService.NFC_POLL_KOVIO);
2089 techCodeToMask.put(TagTechnology.MIFARE_CLASSIC, NfcService.NFC_POLL_A);
2090 techCodeToMask.put(TagTechnology.MIFARE_ULTRALIGHT, NfcService.NFC_POLL_A);
2091
2092 int mask = 0;
2093
2094 for (int i = 0; i < techList.length; i++) {
2095 if (techCodeToMask.containsKey(techList[i])) {
2096 mask |= techCodeToMask.get(techList[i]).intValue();
2097 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05302098 int screenState = mScreenStateHelper.checkScreenState();
2099 if (screenState != mScreenState) {
2100 new ApplyRoutingTask().execute(Integer.valueOf(screenState));
2101 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302102 }
2103
2104 return mask;
2105 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05302106
2107 /**
2108 * An interface for nxp extensions
2109 */
nxpandroid64fd68c2015-09-23 16:45:15 +05302110 @Override
nxpandroid6fd9cdb2017-07-12 18:25:41 +05302111 public IBinder getNfcAdapterVendorInterface(String vendor) {
2112 if(vendor.equalsIgnoreCase("nxp")) {
2113 return (IBinder) mNxpNfcAdapter;
2114 } else {
2115 return null;
2116 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302117 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05302118
nxpandroid64fd68c2015-09-23 16:45:15 +05302119 }
2120 final class NxpNfcAdapterService extends INxpNfcAdapter.Stub {
2121 @Override
2122 public INxpNfcAdapterExtras getNxpNfcAdapterExtrasInterface() throws RemoteException {
2123 return mNxpExtrasService;
2124 }
2125 @Override
2126 public IeSEClientServicesAdapter getNfcEseClientServicesAdapterInterface() {
2127 if(mEseClientServicesAdapter == null){
2128 mEseClientServicesAdapter = new EseClientServicesAdapter();
2129 }
2130 return mEseClientServicesAdapter;
2131 }
2132
2133 //GSMA Changes
2134 @Override
2135 public INxpNfcController getNxpNfcControllerInterface() {
2136 return mNxpNfcController.getNxpNfcControllerInterface();
2137 }
2138
2139 @Override
2140 public INfcDta getNfcDtaInterface() {
2141 NfcPermissions.enforceAdminPermissions(mContext);
2142 //begin
2143 if(mDtaService == null){
2144 mDtaService = new NfcDtaService();
2145 }
2146 //end
2147 return mDtaService;
2148 }
2149 @Override
2150 public INfcVzw getNfcVzwInterface() {
2151 NfcPermissions.enforceAdminPermissions(mContext);
2152 //begin
2153 if(mVzwService == null){
2154 mVzwService = new NfcVzwService();
2155 }
2156 //end
2157 return mVzwService;
2158 }
2159
2160 @Override
2161 public int setEmvCoPollProfile(boolean enable, int route) throws RemoteException {
2162 return mDeviceHost.setEmvCoPollProfile(enable, route);
2163 }
2164
2165 @Override
2166 public int[] getSecureElementList(String pkg) throws RemoteException {
2167 NfcService.this.enforceNfcSeAdminPerm(pkg);
2168
2169 int[] list = null;
2170 if (isNfcEnabled()) {
2171 list = mDeviceHost.doGetSecureElementList();
2172 }
2173 return list;
2174 }
2175
2176 @Override
2177 public int[] getActiveSecureElementList(String pkg) throws RemoteException {
nxpandroid64fd68c2015-09-23 16:45:15 +05302178
2179 int[] list = null;
2180 if (isNfcEnabled()) {
2181 list = mDeviceHost.doGetActiveSecureElementList();
2182 }
2183 for(int i=0; i< list.length; i++) {
2184 Log.d(TAG, "Active element = "+ list[i]);
2185 }
2186 return list;
2187 }
2188
2189 public INxpNfcAccessExtras getNxpNfcAccessExtrasInterface(String pkg) {
2190 NfcService.this.enforceNfcSccAdminPerm(pkg);
2191 Log.d(TAG, "getNxpNfcAccessExtrasInterface1");
2192 if(mNfcAccessExtrasService == null){
2193 mNfcAccessExtrasService = new NfcAccessExtrasService();
2194 }
2195 return mNfcAccessExtrasService;
2196 }
2197
2198 @Override
2199 public int getSelectedSecureElement(String pkg) throws RemoteException {
2200 NfcService.this.enforceNfcSeAdminPerm(pkg);
2201 return mSelectedSeId;
2202 }
2203 @Override
2204 public int deselectSecureElement(String pkg) throws RemoteException {
2205 NfcService.this.enforceNfcSeAdminPerm(pkg);
2206
2207 // Check if NFC is enabled
2208 if (!isNfcEnabled()) {
2209 return ErrorCodes.ERROR_NOT_INITIALIZED;
2210 }
2211
2212 if (mSelectedSeId == 0) {
2213 return ErrorCodes.ERROR_NO_SE_CONNECTED;
2214 }
2215
2216 if (mSelectedSeId != ALL_SE_ID_TYPE/* SECURE_ELEMENT_ALL */) {
2217 mDeviceHost.doDeselectSecureElement(mSelectedSeId);
2218 } else {
2219
2220 /* Get SE List */
nxpandroid281eb922016-08-25 20:27:46 +05302221 int[] seList = mDeviceHost.doGetSecureElementList();
nxpandroid64fd68c2015-09-23 16:45:15 +05302222
nxpandroid281eb922016-08-25 20:27:46 +05302223 for (int i = 0; i < seList.length; i++) {
2224 mDeviceHost.doDeselectSecureElement(seList[i]);
nxpandroid64fd68c2015-09-23 16:45:15 +05302225 }
2226
2227 // mDeviceHost.doSetMultiSEState(false);
2228 }
2229 mNfcSecureElementState = false;
2230 mSelectedSeId = 0;
2231
2232 /* store preference */
nxpandroida9a68ba2016-01-14 21:12:17 +05302233 mNxpPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, false);
2234 mNxpPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, 0);
2235 mNxpPrefsEditor.apply();
nxpandroid64fd68c2015-09-23 16:45:15 +05302236
2237 return ErrorCodes.SUCCESS;
2238 }
2239
2240
2241
2242
2243
2244 @Override
2245 public void storeSePreference(int seId) {
2246 NfcPermissions.enforceAdminPermissions(mContext);
2247 /* store */
2248 Log.d(TAG, "SE Preference stored");
nxpandroida9a68ba2016-01-14 21:12:17 +05302249 mNxpPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, true);
2250 mNxpPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, seId);
2251 mNxpPrefsEditor.apply();
nxpandroid64fd68c2015-09-23 16:45:15 +05302252 }
2253
2254 @Override
2255 public int selectSecureElement(String pkg,int seId) throws RemoteException {
2256 NfcService.this.enforceNfcSeAdminPerm(pkg);
2257
2258 // Check if NFC is enabled
2259 if (!isNfcEnabled()) {
2260 return ErrorCodes.ERROR_NOT_INITIALIZED;
2261 }
2262
2263 if (mSelectedSeId == seId) {
2264 return ErrorCodes.ERROR_SE_ALREADY_SELECTED;
2265 }
2266
2267 if (mSelectedSeId != 0) {
2268 return ErrorCodes.ERROR_SE_CONNECTED;
2269 }
2270 /* Get SE List */
nxpandroid281eb922016-08-25 20:27:46 +05302271 int[] seList = mDeviceHost.doGetSecureElementList();
nxpandroid64fd68c2015-09-23 16:45:15 +05302272
2273 mSelectedSeId = seId;
2274 if (seId != ALL_SE_ID_TYPE/* SECURE_ELEMENT_ALL */) {
2275 mDeviceHost.doSelectSecureElement(mSelectedSeId);
2276 } else {
nxpandroid281eb922016-08-25 20:27:46 +05302277 if (seList.length > 1) {
2278 for (int i = 0; i < seList.length; i++) {
2279 mDeviceHost.doSelectSecureElement(seList[i]);
nxpandroid64fd68c2015-09-23 16:45:15 +05302280 try{
2281 //Delay b/w two SE selection.
2282 Thread.sleep(200);
2283 } catch(Exception e) {
2284 e.printStackTrace();
2285 }
2286 }
2287 }
2288 }
2289 /* store */
nxpandroida9a68ba2016-01-14 21:12:17 +05302290 mNxpPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, true);
2291 mNxpPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, mSelectedSeId);
2292 mNxpPrefsEditor.apply();
nxpandroid64fd68c2015-09-23 16:45:15 +05302293
2294 mNfcSecureElementState = true;
2295
2296 return ErrorCodes.SUCCESS;
2297 }
2298
2299 public void MifareDesfireRouteSet(int routeLoc, boolean fullPower, boolean lowPower, boolean noPower)
2300 throws RemoteException
2301 {
2302 int protoRouteEntry = 0;
nxpandroid7d44e572016-08-01 19:11:04 +05302303 protoRouteEntry=((routeLoc & 0x03)== 0x01) ? (0x01 << ROUTE_LOC_MASK) : (((routeLoc & 0x03) == 0x02) ? (0x02 << ROUTE_LOC_MASK) : 0x00) ;
nxpandroid8aecbf82016-09-16 20:21:47 +05302304 protoRouteEntry |= ((fullPower ? (mDeviceHost.getDefaultDesfirePowerState() & 0x1F) | 0x01 : 0) | (lowPower ? 0x01 << 1 :0 ) | (noPower ? 0x01 << 2 :0));
2305
nxpandroid7d44e572016-08-01 19:11:04 +05302306 if(routeLoc == 0x00)
nxpandroid7d44e572016-08-01 19:11:04 +05302307 {
nxpandroid8aecbf82016-09-16 20:21:47 +05302308 /*
2309 bit pos 1 = Power Off
2310 bit pos 2 = Battery Off
2311 bit pos 4 = Screen Off
2312 Set these bits to 0 because in case routeLoc = HOST it can not work on POWER_OFF, BATTERY_OFF and SCREEN_OFF*/
2313 protoRouteEntry &= 0xE9;
nxpandroid7d44e572016-08-01 19:11:04 +05302314 }
nxpandroid8aecbf82016-09-16 20:21:47 +05302315
nxpandroid7d44e572016-08-01 19:11:04 +05302316 Log.i(TAG,"MifareDesfireRouteSet : " + protoRouteEntry);
nxpandroida9a68ba2016-01-14 21:12:17 +05302317 mNxpPrefsEditor = mNxpPrefs.edit();
2318 mNxpPrefsEditor.putInt("PREF_MIFARE_DESFIRE_PROTO_ROUTE_ID", protoRouteEntry);
2319 mNxpPrefsEditor.commit();
nxpandroid64fd68c2015-09-23 16:45:15 +05302320 Log.i(TAG,"MifareDesfireRouteSet function in");
2321 commitRouting();
2322 }
2323
2324 public void DefaultRouteSet(int routeLoc, boolean fullPower, boolean lowPower, boolean noPower)
2325 throws RemoteException
2326 {
2327 if (mIsHceCapable) {
2328 int protoRouteEntry = 0;
nxpandroid7d44e572016-08-01 19:11:04 +05302329 protoRouteEntry=((routeLoc & 0x03)== 0x01) ? (0x01 << ROUTE_LOC_MASK) : (((routeLoc & 0x03) == 0x02) ? (0x02 << ROUTE_LOC_MASK) : 0x00) ;
nxpandroid8aecbf82016-09-16 20:21:47 +05302330 protoRouteEntry |= ((fullPower ? (mDeviceHost.getDefaultAidPowerState() & 0x1F) | 0x01 : 0) | (lowPower ? 0x01 << 1 :0 ) | (noPower ? 0x01 << 2 :0));
2331
nxpandroid7d44e572016-08-01 19:11:04 +05302332 if(routeLoc == 0x00)
nxpandroid7d44e572016-08-01 19:11:04 +05302333 {
nxpandroid8aecbf82016-09-16 20:21:47 +05302334 /*
2335 bit pos 1 = Power Off
2336 bit pos 2 = Battery Off
2337 bit pos 4 = Screen Off
2338 Set these bits to 0 because in case routeLoc = HOST it can not work on POWER_OFF, BATTERY_OFF and SCREEN_OFF*/
2339 protoRouteEntry &= 0xE9;
nxpandroid7d44e572016-08-01 19:11:04 +05302340 }
2341 Log.i(TAG,"DefaultRouteSet : " + protoRouteEntry);
nxpandroid64fd68c2015-09-23 16:45:15 +05302342 if(GetDefaultRouteLoc() != routeLoc)
2343 {
nxpandroida9a68ba2016-01-14 21:12:17 +05302344 mNxpPrefsEditor = mNxpPrefs.edit();
2345 mNxpPrefsEditor.putInt("PREF_SET_DEFAULT_ROUTE_ID", protoRouteEntry );
2346 mNxpPrefsEditor.commit();
nxpandroid64fd68c2015-09-23 16:45:15 +05302347 mIsRouteForced = true;
2348 if (mIsHceCapable) {
2349 mAidRoutingManager.onNfccRoutingTableCleared();
2350 mCardEmulationManager.onRoutingTableChanged();
2351 }
2352 mIsRouteForced = false;
nxpandroid64fd68c2015-09-23 16:45:15 +05302353 }
2354 }
2355 else{
2356 Log.i(TAG,"DefaultRoute can not be set. mIsHceCapable = flase");
2357 }
2358 }
2359
2360 public void MifareCLTRouteSet(int routeLoc, boolean fullPower, boolean lowPower, boolean noPower)
2361 throws RemoteException
2362 {
2363 int techRouteEntry=0;
nxpandroid7d44e572016-08-01 19:11:04 +05302364 techRouteEntry=((routeLoc & 0x03) == 0x01) ? (0x01 << ROUTE_LOC_MASK) : (((routeLoc & 0x03) == 0x02) ? (0x02 << ROUTE_LOC_MASK) : 0x00);
2365 techRouteEntry |= ((fullPower ? (mDeviceHost.getDefaultMifareCLTPowerState() & 0x1F) | 0x01 : 0) | (lowPower ? 0x01 << 1 :0 ) | (noPower ? 0x01 << 2 :0));
2366 techRouteEntry |= (TECH_TYPE_A << TECH_TYPE_MASK);
2367
2368 Log.i(TAG,"MifareCLTRouteSet : " + techRouteEntry);
nxpandroida9a68ba2016-01-14 21:12:17 +05302369 mNxpPrefsEditor = mNxpPrefs.edit();
2370 mNxpPrefsEditor.putInt("PREF_MIFARE_CLT_ROUTE_ID", techRouteEntry);
2371 mNxpPrefsEditor.commit();
nxpandroid64fd68c2015-09-23 16:45:15 +05302372 commitRouting();
2373 }
2374 @Override
2375 public byte[] getFWVersion()
2376 {
nxpandroid5d64ce92016-11-18 19:48:53 +05302377 byte[] buf = new byte[3];
nxpandroid64fd68c2015-09-23 16:45:15 +05302378 Log.i(TAG, "Starting getFwVersion");
2379 int fwver = mDeviceHost.getFWVersion();
2380 buf[0] = (byte)((fwver&0xFF00)>>8);
2381 buf[1] = (byte)((fwver&0xFF));
nxpandroid5d64ce92016-11-18 19:48:53 +05302382 buf[2] = (byte)((fwver&0xFF0000)>>16);
nxpandroid64fd68c2015-09-23 16:45:15 +05302383 Log.i(TAG, "Firmware version is 0x"+ buf[0]+" 0x"+buf[1]);
2384 return buf;
2385 }
2386
2387 @Override
2388 public Map<String,Integer> getServicesAidCacheSize(int userId, String category){
2389 return mCardEmulationManager.getServicesAidCacheSize(userId, category);
2390 }
nxpandroida9a68ba2016-01-14 21:12:17 +05302391
2392 @Override
2393 public int updateServiceState(int userId , Map serviceState) {
2394 return mCardEmulationManager.updateServiceState(userId ,serviceState);
2395 }
2396
nxpandroid64fd68c2015-09-23 16:45:15 +05302397 @Override
2398 public int getSeInterface(int type) throws RemoteException {
2399 return mDeviceHost.doGetSeInterface(type);
2400 }
2401
nxpandroid34627bd2016-05-27 15:52:30 +05302402 @Override
2403 public int getMaxAidRoutingTableSize() throws RemoteException {
nxpandroid5d64ce92016-11-18 19:48:53 +05302404 NfcPermissions.enforceUserPermissions(mContext);
nxpandroid34627bd2016-05-27 15:52:30 +05302405 return getAidRoutingTableSize();
2406 }
2407
nxpandroid281eb922016-08-25 20:27:46 +05302408
nxpandroid34627bd2016-05-27 15:52:30 +05302409 @Override
2410 public int getCommittedAidRoutingTableSize() throws RemoteException {
nxpandroid5d64ce92016-11-18 19:48:53 +05302411 NfcPermissions.enforceUserPermissions(mContext);
nxpandroid34627bd2016-05-27 15:52:30 +05302412 return (getAidRoutingTableSize() - getRemainingAidTableSize());
2413 }
nxpandroid281eb922016-08-25 20:27:46 +05302414
2415 @Override
2416 public int setConfig(String configs , String pkg) {
2417 Log.e(TAG, "Setting configs for Transit" );
2418 /*Check permissions*/
2419 NfcPermissions.enforceAdminPermissions(mContext);
2420 /*Check if any NFC transactions are ongoing*/
2421 if(mDeviceHost.isNfccBusy())
2422 {
2423 Log.e(TAG, "NFCC is busy.." );
2424 return TRANSIT_SETCONFIG_STAT_FAILED;
2425 }
2426 /*check if format of configs is fine*/
2427 /*Save configurations to file*/
2428 try {
nxpandroidf1f54f52017-07-31 16:08:06 +05302429 File newTextFile = new File("/data/vendor/nfc/libnfc-nxpTransit.conf");
nxpandroid281eb922016-08-25 20:27:46 +05302430 if(configs == null)
2431 {
2432 if(newTextFile.delete()){
2433 Log.e(TAG, "Removing transit config file. Taking default Value" );
2434 }else{
2435 System.out.println("Error taking defualt value");
2436 }
2437 }
2438 else
2439 {
2440 FileWriter fw = new FileWriter(newTextFile);
2441 fw.write(configs);
2442 fw.close();
2443 Log.e(TAG, "File Written to libnfc-nxpTransit.conf successfully" );
2444 }
2445 } catch (Exception e) {
2446 e.printStackTrace();
2447 return TRANSIT_SETCONFIG_STAT_FAILED;
2448 }
2449
2450 /*restart NFC service*/
2451 try {
2452 mNfcAdapter.disable(true);
2453 mNfcAdapter.enable();
2454 } catch (Exception e) {
2455 Log.e(TAG, "Unable to restart NFC Service");
2456 e.printStackTrace();
2457 return TRANSIT_SETCONFIG_STAT_FAILED;
2458 }
2459 return TRANSIT_SETCONFIG_STAT_SUCCESS;
2460 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302461 }
2462
2463 final class ReaderModeDeathRecipient implements IBinder.DeathRecipient {
2464 @Override
2465 public void binderDied() {
2466 synchronized (NfcService.this) {
2467 if (mReaderModeParams != null) {
2468 mReaderModeParams = null;
2469 Log.e(TAG, "applyRouting -5");
2470 applyRouting(false);
2471 }
2472 }
2473 }
2474 }
2475
2476 final class TagService extends INfcTag.Stub {
2477 @Override
nxpandroid64fd68c2015-09-23 16:45:15 +05302478 public int connect(int nativeHandle, int technology) throws RemoteException {
2479 NfcPermissions.enforceUserPermissions(mContext);
2480
2481 TagEndpoint tag = null;
2482
2483 if (!isNfcEnabled()) {
2484 return ErrorCodes.ERROR_NOT_INITIALIZED;
2485 }
2486
2487 /* find the tag in the hmap */
2488 tag = (TagEndpoint) findObject(nativeHandle);
2489 if (tag == null) {
2490 return ErrorCodes.ERROR_DISCONNECT;
2491 }
2492
2493 if (!tag.isPresent()) {
2494 return ErrorCodes.ERROR_DISCONNECT;
2495 }
2496
2497 // Note that on most tags, all technologies are behind a single
2498 // handle. This means that the connect at the lower levels
2499 // will do nothing, as the tag is already connected to that handle.
2500 if (tag.connect(technology)) {
2501 return ErrorCodes.SUCCESS;
2502 } else {
2503 return ErrorCodes.ERROR_DISCONNECT;
2504 }
2505 }
2506
2507 @Override
2508 public int reconnect(int nativeHandle) throws RemoteException {
2509 NfcPermissions.enforceUserPermissions(mContext);
2510
2511 TagEndpoint tag = null;
2512
2513 // Check if NFC is enabled
2514 if (!isNfcEnabled()) {
2515 return ErrorCodes.ERROR_NOT_INITIALIZED;
2516 }
2517
2518 /* find the tag in the hmap */
2519 tag = (TagEndpoint) findObject(nativeHandle);
2520 if (tag != null) {
2521 if (tag.reconnect()) {
2522 return ErrorCodes.SUCCESS;
2523 } else {
2524 return ErrorCodes.ERROR_DISCONNECT;
2525 }
2526 }
2527 return ErrorCodes.ERROR_DISCONNECT;
2528 }
2529
2530 @Override
2531 public int[] getTechList(int nativeHandle) throws RemoteException {
2532 NfcPermissions.enforceUserPermissions(mContext);
2533
2534 // Check if NFC is enabled
2535 if (!isNfcEnabled()) {
2536 return null;
2537 }
2538
2539 /* find the tag in the hmap */
2540 TagEndpoint tag = (TagEndpoint) findObject(nativeHandle);
2541 if (tag != null) {
2542 return tag.getTechList();
2543 }
2544 return null;
2545 }
2546
2547 @Override
2548 public boolean isPresent(int nativeHandle) throws RemoteException {
2549 TagEndpoint tag = null;
2550
2551 // Check if NFC is enabled
2552 if (!isNfcEnabled()) {
2553 return false;
2554 }
2555
2556 /* find the tag in the hmap */
2557 tag = (TagEndpoint) findObject(nativeHandle);
2558 if (tag == null) {
2559 return false;
2560 }
2561
2562 return tag.isPresent();
2563 }
2564
2565 @Override
2566 public boolean isNdef(int nativeHandle) throws RemoteException {
2567 NfcPermissions.enforceUserPermissions(mContext);
2568
2569 TagEndpoint tag = null;
2570
2571 // Check if NFC is enabled
2572 if (!isNfcEnabled()) {
2573 return false;
2574 }
2575
2576 /* find the tag in the hmap */
2577 tag = (TagEndpoint) findObject(nativeHandle);
2578 int[] ndefInfo = new int[2];
2579 if (tag == null) {
2580 return false;
2581 }
2582 return tag.checkNdef(ndefInfo);
2583 }
2584
2585 @Override
2586 public TransceiveResult transceive(int nativeHandle, byte[] data, boolean raw)
2587 throws RemoteException {
2588 NfcPermissions.enforceUserPermissions(mContext);
2589
2590 TagEndpoint tag = null;
2591 byte[] response;
2592
2593 // Check if NFC is enabled
2594 if (!isNfcEnabled()) {
2595 return null;
2596 }
2597
2598 /* find the tag in the hmap */
2599 tag = (TagEndpoint) findObject(nativeHandle);
2600 if (tag != null) {
2601 // Check if length is within limits
2602 if (data.length > getMaxTransceiveLength(tag.getConnectedTechnology())) {
2603 return new TransceiveResult(TransceiveResult.RESULT_EXCEEDED_LENGTH, null);
2604 }
2605 int[] targetLost = new int[1];
2606 response = tag.transceive(data, raw, targetLost);
2607 int result;
2608 if (response != null) {
2609 result = TransceiveResult.RESULT_SUCCESS;
2610 } else if (targetLost[0] == 1) {
2611 result = TransceiveResult.RESULT_TAGLOST;
2612 } else {
2613 result = TransceiveResult.RESULT_FAILURE;
2614 }
2615 return new TransceiveResult(result, response);
2616 }
2617 return null;
2618 }
2619
2620 @Override
2621 public NdefMessage ndefRead(int nativeHandle) throws RemoteException {
2622 NfcPermissions.enforceUserPermissions(mContext);
2623
2624 TagEndpoint tag;
2625
2626 // Check if NFC is enabled
2627 if (!isNfcEnabled()) {
2628 return null;
2629 }
2630
2631 /* find the tag in the hmap */
2632 tag = (TagEndpoint) findObject(nativeHandle);
2633 if (tag != null) {
2634 byte[] buf = tag.readNdef();
2635 if (buf == null) {
2636 return null;
2637 }
2638
2639 /* Create an NdefMessage */
2640 try {
2641 return new NdefMessage(buf);
2642 } catch (FormatException e) {
2643 return null;
2644 }
2645 }
2646 return null;
2647 }
2648
2649 @Override
2650 public int ndefWrite(int nativeHandle, NdefMessage msg) throws RemoteException {
2651 NfcPermissions.enforceUserPermissions(mContext);
2652
2653 TagEndpoint tag;
2654
2655 // Check if NFC is enabled
2656 if (!isNfcEnabled()) {
2657 return ErrorCodes.ERROR_NOT_INITIALIZED;
2658 }
2659
2660 /* find the tag in the hmap */
2661 tag = (TagEndpoint) findObject(nativeHandle);
2662 if (tag == null) {
2663 return ErrorCodes.ERROR_IO;
2664 }
2665
2666 if (msg == null) return ErrorCodes.ERROR_INVALID_PARAM;
2667
2668 if (tag.writeNdef(msg.toByteArray())) {
2669 return ErrorCodes.SUCCESS;
2670 } else {
2671 return ErrorCodes.ERROR_IO;
2672 }
2673
2674 }
2675
2676 @Override
2677 public boolean ndefIsWritable(int nativeHandle) throws RemoteException {
2678 throw new UnsupportedOperationException();
2679 }
2680
2681 @Override
2682 public int ndefMakeReadOnly(int nativeHandle) throws RemoteException {
2683 NfcPermissions.enforceUserPermissions(mContext);
2684
2685 TagEndpoint tag;
2686
2687 // Check if NFC is enabled
2688 if (!isNfcEnabled()) {
2689 return ErrorCodes.ERROR_NOT_INITIALIZED;
2690 }
2691
2692 /* find the tag in the hmap */
2693 tag = (TagEndpoint) findObject(nativeHandle);
2694 if (tag == null) {
2695 return ErrorCodes.ERROR_IO;
2696 }
2697
2698 if (tag.makeReadOnly()) {
2699 return ErrorCodes.SUCCESS;
2700 } else {
2701 return ErrorCodes.ERROR_IO;
2702 }
2703 }
2704
2705 @Override
2706 public int formatNdef(int nativeHandle, byte[] key) throws RemoteException {
2707 NfcPermissions.enforceUserPermissions(mContext);
2708
2709 TagEndpoint tag;
2710
2711 // Check if NFC is enabled
2712 if (!isNfcEnabled()) {
2713 return ErrorCodes.ERROR_NOT_INITIALIZED;
2714 }
2715
2716 /* find the tag in the hmap */
2717 tag = (TagEndpoint) findObject(nativeHandle);
2718 if (tag == null) {
2719 return ErrorCodes.ERROR_IO;
2720 }
2721
2722 if (tag.formatNdef(key)) {
2723 return ErrorCodes.SUCCESS;
2724 } else {
2725 return ErrorCodes.ERROR_IO;
2726 }
2727 }
2728
2729 @Override
2730 public Tag rediscover(int nativeHandle) throws RemoteException {
2731 NfcPermissions.enforceUserPermissions(mContext);
2732
2733 TagEndpoint tag = null;
2734
2735 // Check if NFC is enabled
2736 if (!isNfcEnabled()) {
2737 return null;
2738 }
2739
2740 /* find the tag in the hmap */
2741 tag = (TagEndpoint) findObject(nativeHandle);
2742 if (tag != null) {
2743 // For now the prime usecase for rediscover() is to be able
2744 // to access the NDEF technology after formatting without
2745 // having to remove the tag from the field, or similar
2746 // to have access to NdefFormatable in case low-level commands
2747 // were used to remove NDEF. So instead of doing a full stack
2748 // rediscover (which is poorly supported at the moment anyway),
2749 // we simply remove these two technologies and detect them
2750 // again.
2751 tag.removeTechnology(TagTechnology.NDEF);
2752 tag.removeTechnology(TagTechnology.NDEF_FORMATABLE);
2753 tag.findAndReadNdef();
2754 // Build a new Tag object to return
2755 Tag newTag = new Tag(tag.getUid(), tag.getTechList(),
2756 tag.getTechExtras(), tag.getHandle(), this);
2757 return newTag;
2758 }
2759 return null;
2760 }
2761
2762 @Override
2763 public int setTimeout(int tech, int timeout) throws RemoteException {
2764 NfcPermissions.enforceUserPermissions(mContext);
2765 boolean success = mDeviceHost.setTimeout(tech, timeout);
2766 if (success) {
2767 return ErrorCodes.SUCCESS;
2768 } else {
2769 return ErrorCodes.ERROR_INVALID_PARAM;
2770 }
2771 }
2772
2773 @Override
2774 public int getTimeout(int tech) throws RemoteException {
2775 NfcPermissions.enforceUserPermissions(mContext);
2776
2777 return mDeviceHost.getTimeout(tech);
2778 }
2779
2780 @Override
2781 public void resetTimeouts() throws RemoteException {
2782 NfcPermissions.enforceUserPermissions(mContext);
2783
2784 mDeviceHost.resetTimeouts();
2785 }
2786
2787 @Override
2788 public boolean canMakeReadOnly(int ndefType) throws RemoteException {
2789 return mDeviceHost.canMakeReadOnly(ndefType);
2790 }
2791
2792 @Override
2793 public int getMaxTransceiveLength(int tech) throws RemoteException {
2794 return mDeviceHost.getMaxTransceiveLength(tech);
2795 }
2796
2797 @Override
2798 public boolean getExtendedLengthApdusSupported() throws RemoteException {
2799 return mDeviceHost.getExtendedLengthApdusSupported();
2800 }
2801 }
2802
2803 final class NfcJcopService extends IJcopService.Stub{
2804
2805 public int jcopOsDownload(String pkg) throws RemoteException
2806 {
2807 NfcService.this.enforceNfceeAdminPerm(pkg);
2808 int status = ErrorCodes.SUCCESS;
2809 boolean mode;
2810 mode = mDeviceHost.doCheckJcopDlAtBoot();
2811 if(mode == false) {
2812 Log.i(TAG, "Starting getChipName");
2813 int Ver = mDeviceHost.getChipVer();
nxpandroid281eb922016-08-25 20:27:46 +05302814 if(Ver == PN80T_ID || Ver == PN67T_ID || Ver == PN66T_ID || Ver == PN65T_ID) {
nxpandroid64fd68c2015-09-23 16:45:15 +05302815 status = mDeviceHost.JCOSDownload();
nxpandroid7d44e572016-08-01 19:11:04 +05302816 }
2817 else {
2818 status = ErrorCodes.ERROR_NOT_SUPPORTED;
nxpandroid64fd68c2015-09-23 16:45:15 +05302819 }
2820 }
2821 else {
2822 status = ErrorCodes.ERROR_NOT_SUPPORTED;
2823 }
2824 return status;
2825 }
2826 }
2827 final class EseClientServicesAdapter extends IeSEClientServicesAdapter.Stub{
2828 @Override
2829 public IJcopService getJcopService() {
2830 if(mJcopService == null){
2831 mJcopService = new NfcJcopService();
2832 }
2833 return mJcopService;
2834 }
2835 @Override
2836 public ILoaderService getLoaderService() {
2837 if(mAlaService == null){
2838 mAlaService = new NfcAlaService();
2839 }
2840 return mAlaService;
2841 }
2842 @Override
2843 public INxpExtrasService getNxpExtrasService() {
2844 if(mNxpExtras == null){
2845 mNxpExtras = new NxpExtrasService();
2846 }
2847 return mNxpExtras;
2848 }
2849 };
2850
2851 final class NfcAlaService extends ILoaderService.Stub{
2852 private boolean isRecovery = false;
2853 private String appName = null;
2854 private String srcIn = null;
2855 private String respOut = null;
2856 private String status = "false";
2857
2858 void NfcAlaService()
2859 {
2860 appName = null;
2861 srcIn = null;
2862 respOut = null;
2863 status = "false";
2864 isRecovery = false;
2865 }
2866 private synchronized void LSReexecute()
2867 {
2868 byte[] ret = {0x4E,0x02,(byte)0x69,(byte)0x87};
2869 byte retry = LS_RETRY_CNT;
2870 PrintWriter out= null;
2871 BufferedReader br = null;
2872 Log.i(TAG, "Enter: NfcAlaService constructor");
2873 try{
2874 File f = new File(LS_BACKUP_PATH);
2875
2876 Log.i(TAG, "Enter: NfcAlaService constructor file open");
2877 /*If the file does not exists*/
2878 if(!(f.isFile()))
2879 {
2880 Log.i(TAG, "FileNotFound ls backup");
nxpandroid34627bd2016-05-27 15:52:30 +05302881 this.status = null;
nxpandroid64fd68c2015-09-23 16:45:15 +05302882 }
2883 /*If the file exists*/
2884 else
2885 {
2886 Log.i(TAG, "File Found ls backup");
2887 br = new BufferedReader(new FileReader(LS_BACKUP_PATH));
2888 this.appName = br.readLine();
2889 this.srcIn = br.readLine();
2890 this.respOut = br.readLine();
2891 this.status = br.readLine();
2892 }
2893 }catch(FileNotFoundException f)
2894 {
2895 Log.i(TAG, "FileNotFoundException Raised during LS Initialization");
2896 return;
2897 }
2898 catch(IOException ie)
2899 {
2900 Log.i(TAG, "IOException Raised during LS Initialization ");
2901 return;
2902 }
2903 finally{
2904 try{
nxpandroid64fd68c2015-09-23 16:45:15 +05302905 if(br != null)
2906 br.close();
nxpandroid34627bd2016-05-27 15:52:30 +05302907 /*If the file does not exist or empty file */
2908 if(this.status == null)
2909 {
2910 out = new PrintWriter(LS_BACKUP_PATH);
2911 this.status = "true";
2912 out.println("null");
2913 out.println("null");
2914 out.println("null");
2915 out.println("true");
2916 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302917 }catch(IOException e)
2918 {
2919 Log.i(TAG, "IOException Raised during LS Initialization ");
2920 return;
2921 }
nxpandroid34627bd2016-05-27 15:52:30 +05302922 finally{
2923 if(this.status == null)
2924 this.status = "true";
2925 if(out != null)
2926 out.close();
2927 }
nxpandroid64fd68c2015-09-23 16:45:15 +05302928 }
2929 if(this.status.equals("true"))
2930 {
2931 Log.i(TAG, "LS Script execution completed");
2932 }
2933 else
2934 {
2935 Log.i(TAG, "LS Script execution aborted or tear down happened");
2936 Log.i(TAG, "Input script path"+ this.srcIn);
2937 Log.i(TAG, "Output response path"+ this.respOut);
2938 Log.i(TAG, "Application name which invoked LS"+ this.appName);
2939 try{
2940 File fSrc = new File(this.srcIn);
2941 File fRsp = new File(this.respOut);
2942 if((fSrc.isFile() && fRsp.isFile()))
2943 {
2944 byte[] lsAppletStatus = {0x6F,0x00};
2945 /*Perform lsExecuteScript on tear down*/
2946 WatchDogThread watchDog =
2947 new WatchDogThread("Loader service ", INIT_WATCHDOG_LS_MS);
2948 watchDog.start();
2949 try {
2950 mRoutingWakeLock.acquire();
2951 try {
2952 /*Reset retry counter*/
2953 while((retry-- > 0))
2954 {
2955 Thread.sleep(1000);
2956 lsAppletStatus = mNfcAla.doLsGetAppletStatus();
2957 if((lsAppletStatus[0]==0x63) && (lsAppletStatus[1]==0x40))
2958 {
2959 Log.i(TAG, "Started LS recovery since previous session failed");
2960 this.isRecovery = true;
2961 ret = this.lsExecuteScript(this.srcIn, this.respOut);
2962 }
2963 else
2964 {
2965 break;
2966 }
2967 }
2968 } finally {
2969 this.isRecovery = false;
2970 watchDog.cancel();
2971 mRoutingWakeLock.release();
2972 }
2973 }
2974 catch(RemoteException ie)
2975 {
2976 Log.i(TAG, "LS recovery Exception: ");
2977 }
2978 lsAppletStatus = mNfcAla.doLsGetAppletStatus();
2979 if((lsAppletStatus[0]==(byte)0x90)&&(lsAppletStatus[1]==(byte)0x00))
2980 {
2981 out = new PrintWriter(LS_BACKUP_PATH);
2982 out.println("null");
2983 out.println("null");
2984 out.println("null");
2985 out.println("true");
2986 out.close();
2987 Log.i(TAG, "Commiting Default Values of Loader Service AS RETRY ENDS: ");
2988 }
2989 }
2990 else
2991 {
2992 Log.i(TAG, "LS recovery not required");
2993 }
2994 }catch(InterruptedException re)
2995 {
2996 /*Retry failed todo*/
nxpandroid34627bd2016-05-27 15:52:30 +05302997 Log.i(TAG, "InterruptedException while LS recovery");
nxpandroid64fd68c2015-09-23 16:45:15 +05302998 }catch(FileNotFoundException re)
2999 {
3000 /*Retry failed todo*/
nxpandroid34627bd2016-05-27 15:52:30 +05303001 Log.i(TAG, "FileNotFoundException while LS recovery");
nxpandroid64fd68c2015-09-23 16:45:15 +05303002 }
3003 }
3004 }
3005 private void updateLoaderService() {
3006 byte[] ret = {0x4E,0x02,(byte)0x69,(byte)0x87};
3007 Log.i(TAG, "Enter: NfcAlaService constructor file open");
3008 File f = new File(LS_UPDATE_BACKUP_PATH);
nxpandroid34627bd2016-05-27 15:52:30 +05303009 /*If the file exists*/
nxpandroid64fd68c2015-09-23 16:45:15 +05303010 if((f.isFile()))
3011 {
3012 Log.i(TAG, "File Found LS update required");
3013 WatchDogThread watchDog =
3014 new WatchDogThread("LS Update Loader service ", (INIT_WATCHDOG_LS_MS+INIT_WATCHDOG_LS_MS));
3015 watchDog.start();
3016 try {
3017 try {
3018 /*Reset retry counter*/
3019 {
3020 Log.i(TAG, "Started LS update");
3021 ret = this.lsExecuteScript(LS_UPDATE_BACKUP_PATH, LS_UPDATE_BACKUP_OUT_PATH);
3022 if(ret[2] == (byte)(0x90) && ret[3] == (byte)(0x00))
3023 {
3024 Log.i(TAG, " LS update successfully completed");
3025 f.delete();
3026 } else {
3027 Log.i(TAG, " LS update failed");
3028 }
3029 }
3030 } finally {
3031 watchDog.cancel();
3032 }
3033 }
3034 catch(RemoteException ie)
3035 {
3036 Log.i(TAG, "LS update recovery Exception: ");
3037 }
3038 }
nxpandroid34627bd2016-05-27 15:52:30 +05303039 /*If the file does not exists*/
nxpandroid64fd68c2015-09-23 16:45:15 +05303040 else
3041 {
3042 Log.i(TAG, "No LS update");
3043 }
3044 }
3045
3046 public byte[] lsExecuteScript( String srcIn, String respOut) throws RemoteException {
3047 String pkg_name = getCallingAppPkg(mContext);
3048 byte[] sha_data = CreateSHA(pkg_name, 2);
3049 byte[] respSW = {0x4e,0x02,0x69,(byte)0x87};
3050 InputStream is = null;
3051 OutputStream os = null;
3052 PrintWriter out = null;
3053 FileReader fr = null;
3054 byte[] buffer = new byte[1024];
3055 int length = 0;
3056 String srcBackup = srcIn+"mw";
3057 String rspBackup = null;
3058 File rspFile = null;
3059 if(respOut != null)
3060 rspBackup = respOut+"mw";
3061 File srcFile = new File(srcBackup);
3062 if(respOut != null)
3063 rspFile = new File(rspBackup);
3064
3065
3066 /*If Previously Tear down happened before completion of LS execution*/
3067 if(this.isRecovery != false)
3068 {
3069 try{
3070 fr = new FileReader(LS_BACKUP_PATH);
3071 if(fr != null)
3072 {
3073 BufferedReader br = new BufferedReader(fr);
3074 if(br != null)
3075 {
3076 String appName = br.readLine();
3077 if(appName != null)
3078 {
3079 sha_data = CreateSHA(appName, 2);
3080 pkg_name = appName;
3081 }
3082 }
3083 }
3084 }catch(IOException ioe)
3085 {
3086 Log.i(TAG, "IOException thrown for opening ");
3087 }
3088 finally{
3089 try{
3090 if(fr != null)
3091 fr.close();
3092 }
3093 catch(IOException e)
3094 {
3095 Log.i(TAG, "IOException thrown for opening ");
3096 }
3097 }
3098 }
3099 /*Store it in File*/
3100 try{
3101 out = new PrintWriter(LS_BACKUP_PATH);
3102 out.println(pkg_name);
3103 out.println(srcIn);
3104 out.println(respOut);
3105 out.println(false);
3106 }catch(IOException fe)
3107 {
3108 Log.i(TAG, "IOException thrown during clearing ");
3109 }
3110 finally{
3111 if(out != null)
3112 out.close();
3113 }
3114 try{
3115 /*To avoid rewriting of backup file*/
3116 if(!(this.isRecovery)){
3117 is = new FileInputStream(srcIn);
3118 os = new FileOutputStream(srcBackup);
3119
3120 while((length = is.read(buffer))>0)
3121 {
3122 os.write(buffer,0,length);
3123 }
3124 if(is != null)is.close();
3125 if(os != null)os.close();}
3126 Log.i(TAG, "sha_data len : " + sha_data.length);
3127 Log.i(TAG, "Calling package APP Name is "+ pkg_name);
3128 if(sha_data != null)
3129 {
3130 respSW = mNfcAla.doLsExecuteScript(srcBackup, rspBackup, sha_data);
3131 }
3132 /*resp file is not null*/
3133 if(respOut != null){
3134 is = new FileInputStream(rspBackup);
3135 os = new FileOutputStream(respOut);
3136 length = 0;
3137 while((length = is.read(buffer))>0)
3138 {
3139 os.write(buffer,0,length);
3140 }
3141 }
3142 if(is != null)is.close();
3143 if(os != null)os.close();
3144 }catch(IOException ioe)
3145 {
3146 Log.i(TAG, "LS File not found");
3147 }catch(SecurityException se)
3148 {
3149 Log.i(TAG, "LS File access permission deneied");
3150 }
3151 finally{
3152 byte[] status = mNfcAla.doLsGetStatus();
3153 Log.i(TAG, "LS getStatus return SW1 : "+status[0]);
3154 Log.i(TAG, "LS getStatus return SW2: "+status[1]);
3155 if((status[0]== (byte)0x90) && (status[1] == 0x00))
3156 {
3157 try{
3158 out = new PrintWriter(LS_BACKUP_PATH);
3159 out.println("null");
3160 out.println("null");
3161 out.println("null");
3162 out.println("true");
3163 }catch(IOException fe)
3164 {
3165 Log.i(TAG, "FileNotFoundException thrown during clearing ");
3166 }
3167 finally
3168 {
3169 if(out != null)
3170 out.close();
3171 }
3172 Log.i(TAG, "COMMITTING THE DEFAULT VALUES OF LS : ");
3173 srcFile.delete();
3174 rspFile.delete();
3175 }
3176 else
3177 {
3178 Log.i(TAG, "NOT COMMITTING THE DEFAULT VALUES OF LS : ");
3179 }
3180 }
3181 return respSW;
3182 }
3183 public byte[] lsGetVersion()
3184 {
3185 byte[] respApdu = {0x4e,0x02,0x69,(byte)0x87};
3186
3187 respApdu = mNfcAla.doLsGetVersion();
3188 return respApdu;
3189 }
3190 public int appletLoadApplet(String pkg, String choice) throws RemoteException {
3191 String pkg_name = getCallingAppPkg(mContext);
3192 int state = 0;
3193 byte[] sha_data = CreateSHA(pkg_name, 1);
3194 Log.i(TAG, "sha_data len : " + sha_data.length);
3195
3196 if(sha_data != null)
3197 {
3198 state = mNfcAla.doAppletLoadApplet(choice, sha_data);
3199 return state;
3200 }
3201 else
3202 return 0xFF;
3203 }
3204 public int getListofApplets(String pkg, String[] name) throws RemoteException {
3205 int cnt = mNfcAla.GetAppletsList(name);
3206 Log.i(TAG, "GetListofApplets count : " + cnt);
3207 for(int i=0;i<cnt;i++) {
3208 Log.i(TAG, "GetListofApplets " + name[i]);
3209 }
3210
3211 return cnt;
3212 }
3213
nxpandroide68208c2017-02-24 16:08:04 +05303214 //Just Stub for compilation.
nxpandroid64fd68c2015-09-23 16:45:15 +05303215 public byte[] getKeyCertificate() throws RemoteException {
3216 return null;
3217 }
3218
3219 };
3220
nxpandroid64fd68c2015-09-23 16:45:15 +05303221 final class NxpExtrasService extends INxpExtrasService.Stub {
3222 private Bundle writeNoException() {
3223 Bundle p = new Bundle();
3224 p.putInt("e", 0);
3225 return p;
3226 }
3227
3228 private Bundle writeEeException(int exceptionType, String message) {
3229 Bundle p = new Bundle();
3230 p.putInt("e", exceptionType);
3231 p.putString("m", message);
3232 return p;
3233 }
3234
3235 @Override
nxpandroid5d64ce92016-11-18 19:48:53 +05303236 public Bundle getCallingAppPkg(String pkg, IBinder b) throws RemoteException {
3237 NfcService.this.enforceNfceeAdminPerm(pkg);
3238 Bundle result;
3239 String packageName;
3240 try{
3241 packageName = NfcService.this.getCallingAppPkg(mContext);
3242 result = writeNoException();
3243 result.putString("packageName", packageName);
3244 } catch(Exception e){
3245 result = writeEeException(EE_ERROR_IO, e.getMessage());
3246 }
3247 return result;
3248 }
3249
3250 @Override
nxpandroid64fd68c2015-09-23 16:45:15 +05303251 public boolean isEnabled()
3252 {
3253 try {
3254 return (mState == NfcAdapter.STATE_ON);
3255 } catch (Exception e) {
3256 Log.d(TAG, "Exception " + e.getMessage());
3257 return false;
3258 }
3259 }
3260
3261 @Override
3262 public byte[] getSecureElementUid(String pkg) throws RemoteException {
3263 NfcService.this.enforceNfceeAdminPerm(pkg);
3264 return mDeviceHost.getSecureElementUid();
3265 }
3266
3267 @Override
3268 public Bundle open(String pkg, IBinder b) throws RemoteException {
3269 NfcService.this.enforceNfceeAdminPerm(pkg);
3270
3271 Bundle result;
3272 int handle = _open(b);
3273 if (handle < 0) {
3274 result = writeEeException(handle, "NFCEE open exception.");
3275 } else {
3276 result = writeNoException();
3277 }
3278 return result;
3279 }
3280
3281 /**
3282 * Opens a connection to the secure element.
3283 *
3284 * @return A handle with a value >= 0 in case of success, or a
3285 * negative value in case of failure.
3286 */
3287 private int _open(IBinder b) {
3288 synchronized(NfcService.this) {
3289 if (!isNfcEnabled()) {
3290 return EE_ERROR_NFC_DISABLED;
3291 }
3292 if (mInProvisionMode) {
3293 // Deny access to the NFCEE as long as the device is being setup
3294 return EE_ERROR_IO;
3295 }
nxpandroide68208c2017-02-24 16:08:04 +05303296
nxpandroid64fd68c2015-09-23 16:45:15 +05303297 if (mOpenEe != null) {
3298 return EE_ERROR_ALREADY_OPEN;
3299 }
3300
3301 boolean restorePolling = false;
3302 if (mNfcPollingEnabled) {
3303 // Disable polling for tags/P2P when connecting to the SMX
3304 // on PN544-based devices. Whenever nfceeClose is called,
3305 // the polling configuration will be restored.
3306 mDeviceHost.disableDiscovery();
3307 mNfcPollingEnabled = false;
3308 restorePolling = true;
3309 }
nxpandroid7d44e572016-08-01 19:11:04 +05303310 int handle = doOpenSecureElementConnection(0xF3);
nxpandroid64fd68c2015-09-23 16:45:15 +05303311 if (handle < 0) {
3312
3313 if (restorePolling) {
3314 mDeviceHost.enableDiscovery(mCurrentDiscoveryParameters, true);
3315 mNfcPollingEnabled = true;
3316 }
3317 return handle;
3318 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303319
3320 mOpenEe = new OpenSecureElement(getCallingPid(), handle, b);
3321 try {
3322 b.linkToDeath(mOpenEe, 0);
3323 } catch (RemoteException e) {
3324 mOpenEe.binderDied();
3325 }
3326
3327 // Add the calling package to the list of packages that have accessed
3328 // the secure element.
3329 for (String packageName : mContext.getPackageManager().getPackagesForUid(getCallingUid())) {
3330 mSePackages.add(packageName);
3331 }
3332
3333 return handle;
3334 }
3335 }
3336
3337 @Override
3338 public Bundle close(String pkg, IBinder binder) throws RemoteException {
3339 NfcService.this.enforceNfceeAdminPerm(pkg);
3340
3341 Bundle result;
3342 try {
3343 _nfcEeClose(getCallingPid(), binder);
3344 result = writeNoException();
3345 } catch (IOException e) {
3346 result = writeEeException(EE_ERROR_IO, e.getMessage());
3347 }
3348 return result;
3349 }
3350 @Override
3351 public Bundle transceive(String pkg, byte[] in) throws RemoteException {
3352 NfcService.this.enforceNfceeAdminPerm(pkg);
3353
3354 Bundle result;
3355 byte[] out;
3356 try {
3357 out = _transceive(in);
3358 result = writeNoException();
3359 result.putByteArray("out", out);
3360 } catch (IOException e) {
3361 result = writeEeException(EE_ERROR_IO, e.getMessage());
3362 }
3363 return result;
3364 }
3365
3366 private byte[] _transceive(byte[] data) throws IOException {
3367 synchronized(NfcService.this) {
3368 if (!isNfcEnabled()) {
3369 throw new IOException("NFC is not enabled");
3370 }
3371 if (mOpenEe == null) {
3372 throw new IOException("NFC EE is not open");
3373 }
3374 if (getCallingPid() != mOpenEe.pid) {
3375 throw new SecurityException("Wrong PID");
3376 }
3377 }
3378
3379 return doTransceive(mOpenEe.handle, data);
3380 }
3381 };
3382 final class NfcDtaService extends INfcDta.Stub {
3383
3384 public boolean snepDtaCmd(String cmdType, String serviceName, int serviceSap, int miu, int rwSize, int testCaseId) throws RemoteException
3385 {
3386 NfcPermissions.enforceAdminPermissions(mContext);
3387 if(cmdType.equals(null))
3388 return false;
nxpandroid281eb922016-08-25 20:27:46 +05303389 if(cmdType.equals("enabledta") && (!sIsDtaMode)) {
nxpandroid64fd68c2015-09-23 16:45:15 +05303390 mDeviceHost.enableDtaMode();
nxpandroid281eb922016-08-25 20:27:46 +05303391 sIsDtaMode = true;
nxpandroid64fd68c2015-09-23 16:45:15 +05303392 Log.d(TAG, "DTA Mode is Enabled ");
nxpandroid281eb922016-08-25 20:27:46 +05303393 }else if(cmdType.equals("disableDta") && (sIsDtaMode)) {
nxpandroid64fd68c2015-09-23 16:45:15 +05303394 mDeviceHost.disableDtaMode();
nxpandroid281eb922016-08-25 20:27:46 +05303395 sIsDtaMode = false;
nxpandroid64fd68c2015-09-23 16:45:15 +05303396 } else if(cmdType.equals("enableserver")) {
3397 if(serviceName.equals(null))
3398 return false;
nxpandroida9a68ba2016-01-14 21:12:17 +05303399 mP2pLinkManager.enableExtDtaSnepServer(serviceName, serviceSap, miu, rwSize,testCaseId);
nxpandroid64fd68c2015-09-23 16:45:15 +05303400 } else if(cmdType.equals("disableserver")) {
3401 mP2pLinkManager.disableExtDtaSnepServer();
3402 } else if(cmdType.equals("enableclient")) {
3403 if(testCaseId == 0)
3404 return false;
3405 if(testCaseId>20){
nxpandroid281eb922016-08-25 20:27:46 +05303406 sIsShortRecordLayout=true;
nxpandroid64fd68c2015-09-23 16:45:15 +05303407 testCaseId=testCaseId-20;
3408 }else{
nxpandroid281eb922016-08-25 20:27:46 +05303409 sIsShortRecordLayout=false;
nxpandroid64fd68c2015-09-23 16:45:15 +05303410 }
3411 Log.d("testCaseId", ""+testCaseId);
3412 mP2pLinkManager.enableDtaSnepClient(serviceName, miu, rwSize, testCaseId);
3413 } else if(cmdType.equals("disableclient")) {
3414 mP2pLinkManager.disableDtaSnepClient();
3415 } else {
3416 Log.d(TAG, "Unkown DTA Command");
3417 return false;
3418 }
3419 return true;
3420 }
3421
3422 };
3423
3424 final class NfcVzwService extends INfcVzw.Stub {
3425 @Override
3426 public void setScreenOffCondition(boolean enable) throws RemoteException {
3427
3428 Message msg = mHandler.obtainMessage();
3429 msg.what=MSG_SET_SCREEN_STATE;
3430 msg.arg1= (enable)?1:0;
3431 mHandler.sendMessage(msg);
3432
3433 }
3434
3435 @Override
3436 public boolean setVzwAidList(RouteEntry[] entries)
3437 throws RemoteException {
nxpandroid64fd68c2015-09-23 16:45:15 +05303438 Log.i(TAG, "setVzwAidList enter");
3439 Log.i(TAG, "setVzwAidList entries length =" + entries.length);
3440 if (mIsHceCapable) {
3441 mAidRoutingManager.ClearVzwCache();
3442 for (int i = 0; i < entries.length; i++) {
3443 RouteEntry routeEntry = entries[i];
3444 mAidRoutingManager.UpdateVzwCache(routeEntry.getAid(),
3445 routeEntry.getLocation(), routeEntry.getPowerState(),
3446 routeEntry.isAllowed());
3447
3448 Log.i(TAG,
3449 "AID" + routeEntry.getAid() + "Location "
3450 + routeEntry.getLocation() + "powerstate "
3451 + routeEntry.getPowerState());
3452 }
3453 mAidRoutingManager.onNfccRoutingTableCleared();
3454 mCardEmulationManager.onRoutingTableChanged();
3455 return true;
3456 } else {
3457 return false;
3458 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303459 }
3460
3461 };
3462
3463 void _nfcEeClose(int callingPid, IBinder binder) throws IOException {
3464 // Blocks until a pending open() or transceive() times out.
3465 //TODO: This is incorrect behavior - the close should interrupt pending
3466 // operations. However this is not supported by current hardware.
3467
3468 synchronized (NfcService.this) {
3469 if (!isNfcEnabledOrShuttingDown()) {
3470 throw new IOException("NFC adapter is disabled");
3471 }
3472 if (mOpenEe == null) {
3473 throw new IOException("NFC EE closed");
3474 }
3475 if (callingPid != -1 && callingPid != mOpenEe.pid) {
3476 throw new SecurityException("Wrong PID");
3477 }
3478 if (mOpenEe.binder != binder) {
3479 throw new SecurityException("Wrong binder handle");
3480 }
3481
3482 binder.unlinkToDeath(mOpenEe, 0);
3483 mDeviceHost.resetTimeouts();
3484 doDisconnect(mOpenEe.handle);
3485 mOpenEe = null;
nxpandroid64fd68c2015-09-23 16:45:15 +05303486 }
3487 }
3488
3489 boolean _nfcEeReset() throws IOException {
3490 synchronized (NfcService.this) {
3491 if (!isNfcEnabledOrShuttingDown()) {
3492 throw new IOException("NFC adapter is disabled");
3493 }
3494 if (mOpenEe == null) {
3495 throw new IOException("NFC EE closed");
3496 }
3497 return mSecureElement.doReset(mOpenEe.handle);
3498 }
3499 }
3500
3501 final class NfcAccessExtrasService extends INxpNfcAccessExtras.Stub {
3502 public boolean checkChannelAdminAccess(String pkg) throws RemoteException {
3503 boolean result = true;
3504 try {
3505 NfcService.this.enforceNfcSccAdminPerm(pkg);
3506 } catch (Exception e) {
3507 e.printStackTrace();
3508 result = false;
3509 }
3510 return result;
3511 }
3512 };
3513
3514 final class NfcAdapterExtrasService extends INfcAdapterExtras.Stub {
3515 private Bundle writeNoException() {
3516 Bundle p = new Bundle();
3517 p.putInt("e", 0);
3518 return p;
3519 }
3520
3521 private Bundle writeEeException(int exceptionType, String message) {
3522 Bundle p = new Bundle();
3523 p.putInt("e", exceptionType);
3524 p.putString("m", message);
3525 return p;
3526 }
3527
3528 @Override
3529 public Bundle open(String pkg, IBinder b) throws RemoteException {
3530 NfcService.this.enforceNfceeAdminPerm(pkg);
3531
3532 Bundle result;
3533 int handle = _open(b);
3534 if (handle < 0) {
3535 result = writeEeException(handle, "NFCEE open exception.");
3536 } else {
3537 result = writeNoException();
3538 }
3539 return result;
3540 }
3541
3542 /**
3543 * Opens a connection to the secure element.
3544 *
3545 * @return A handle with a value >= 0 in case of success, or a
3546 * negative value in case of failure.
3547 */
3548 private int _open(IBinder b) {
3549 synchronized(NfcService.this) {
3550 if (!isNfcEnabled()) {
3551 return EE_ERROR_NFC_DISABLED;
3552 }
3553 if (mInProvisionMode) {
3554 // Deny access to the NFCEE as long as the device is being setup
3555 return EE_ERROR_IO;
3556 }
nxpandroid7d44e572016-08-01 19:11:04 +05303557 /*Concurrent access for DWP transactions to be allowed even when P2P is already ongoing */
3558 /*
nxpandroid64fd68c2015-09-23 16:45:15 +05303559 if (mP2pLinkManager.isLlcpActive()) {
3560 // Don't allow PN544-based devices to open the SE while the LLCP
3561 // link is still up or in a debounce state. This avoids race
3562 // conditions in the NXP stack around P2P/SMX switching.
3563 return EE_ERROR_EXT_FIELD;
nxpandroid7d44e572016-08-01 19:11:04 +05303564 }*/
nxpandroid64fd68c2015-09-23 16:45:15 +05303565 if (mOpenEe != null) {
3566 Log.i(TAG, "SE is Busy. returning..");
3567 return EE_ERROR_ALREADY_OPEN;
3568 }
3569 boolean restorePolling = false;
3570 if (mNfcPollingEnabled) {
3571 // Disable polling for tags/P2P when connecting to the SMX
3572 // on PN544-based devices. Whenever nfceeClose is called,
3573 // the polling configuration will be restored.
3574 mDeviceHost.disableDiscovery();
3575 mNfcPollingEnabled = false;
3576 restorePolling = true;
3577 }
3578
nxpandroid7d44e572016-08-01 19:11:04 +05303579 int handle = doOpenSecureElementConnection(0xF3);
nxpandroid64fd68c2015-09-23 16:45:15 +05303580 if (handle < 0) {
3581
3582 if (restorePolling) {
3583 mDeviceHost.enableDiscovery(mCurrentDiscoveryParameters, true);
3584 mNfcPollingEnabled = true;
3585 }
3586 return handle;
3587 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303588 mOpenEe = new OpenSecureElement(getCallingPid(), handle, b);
3589 try {
3590 b.linkToDeath(mOpenEe, 0);
3591 } catch (RemoteException e) {
3592 mOpenEe.binderDied();
3593 }
3594
3595 // Add the calling package to the list of packages that have accessed
3596 // the secure element.
3597 for (String packageName : mContext.getPackageManager().getPackagesForUid(getCallingUid())) {
3598 mSePackages.add(packageName);
3599 }
3600
3601 return handle;
3602 }
3603 }
3604
3605 @Override
3606 public Bundle close(String pkg, IBinder binder) throws RemoteException {
3607 NfcService.this.enforceNfceeAdminPerm(pkg);
3608
3609 Bundle result;
3610 try {
3611 _nfcEeClose(getCallingPid(), binder);
3612 result = writeNoException();
3613 } catch (IOException e) {
3614 result = writeEeException(EE_ERROR_IO, e.getMessage());
3615 }
3616 return result;
3617 }
3618
nxpandroid64fd68c2015-09-23 16:45:15 +05303619 @Override
3620 public Bundle transceive(String pkg, byte[] in) throws RemoteException {
3621 NfcService.this.enforceNfceeAdminPerm(pkg);
3622
3623 Bundle result;
3624 byte[] out;
3625 try {
3626 out = _transceive(in);
3627 result = writeNoException();
3628 result.putByteArray("out", out);
3629 } catch (IOException e) {
3630 result = writeEeException(EE_ERROR_IO, e.getMessage());
3631 }
3632 return result;
3633 }
3634
3635 private byte[] _transceive(byte[] data) throws IOException {
3636 synchronized(NfcService.this) {
3637 if (!isNfcEnabled()) {
3638 throw new IOException("NFC is not enabled");
3639 }
3640 if (mOpenEe == null) {
3641 throw new IOException("NFC EE is not open");
3642 }
3643 if (getCallingPid() != mOpenEe.pid) {
3644 throw new SecurityException("Wrong PID");
3645 }
3646 }
3647
3648 return doTransceive(mOpenEe.handle, data);
3649 }
3650
nxpandroid64fd68c2015-09-23 16:45:15 +05303651 @Override
3652 public int getCardEmulationRoute(String pkg) throws RemoteException {
3653 NfcService.this.enforceNfceeAdminPerm(pkg);
3654 return mEeRoutingState;
3655 }
3656
3657 @Override
3658 public void setCardEmulationRoute(String pkg, int route) throws RemoteException {
3659 NfcService.this.enforceNfceeAdminPerm(pkg);
3660 mEeRoutingState = route;
3661 ApplyRoutingTask applyRoutingTask = new ApplyRoutingTask();
3662 applyRoutingTask.execute();
3663 try {
3664 // Block until route is set
3665 applyRoutingTask.get();
3666 } catch (ExecutionException e) {
3667 Log.e(TAG, "failed to set card emulation mode");
3668 } catch (InterruptedException e) {
3669 Log.e(TAG, "failed to set card emulation mode");
3670 }
3671 }
3672
3673 @Override
3674 public void authenticate(String pkg, byte[] token) throws RemoteException {
3675 NfcService.this.enforceNfceeAdminPerm(pkg);
3676 }
3677
3678 @Override
3679 public String getDriverName(String pkg) throws RemoteException {
3680 NfcService.this.enforceNfceeAdminPerm(pkg);
3681 return mDeviceHost.getName();
3682 }
3683
3684 }
3685 final class NxpNfcAdapterExtrasService extends INxpNfcAdapterExtras.Stub {
3686 private Bundle writeNoException() {
3687 Bundle p = new Bundle();
3688 p.putInt("e", 0);
3689 return p;
3690 }
3691
3692 private Bundle writeEeException(int exceptionType, String message) {
3693 Bundle p = new Bundle();
3694 p.putInt("e", exceptionType);
3695 p.putString("m", message);
3696 return p;
3697 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303698
nxpandroid5d64ce92016-11-18 19:48:53 +05303699 @Override
3700 public boolean eSEChipReset(String pkg) throws RemoteException {
3701 NfcService.this.enforceNfceeAdminPerm(pkg);
3702 Bundle result;
3703 boolean stat = false;
3704 try {
3705 synchronized (NfcService.this) {
3706 if (!isNfcEnabledOrShuttingDown()) {
3707 throw new IOException("NFC adapter is disabled");
3708 }
3709 if (mOpenEe == null) {
3710 throw new IOException("NFC EE closed");
3711 }
3712 stat = mSecureElement.doeSEChipReset();
3713 }
3714 result = writeNoException();
3715 } catch (IOException e) {
3716 result = writeEeException(EE_ERROR_IO, e.getMessage());
3717 }
3718 return stat;
3719 }
3720
3721 @Override
nxpandroid64fd68c2015-09-23 16:45:15 +05303722 public boolean reset(String pkg) throws RemoteException {
3723 NfcService.this.enforceNfceeAdminPerm(pkg);
3724 Bundle result;
3725 boolean stat = false;
3726 try {
3727 stat = _nfcEeReset();
3728 result = writeNoException();
3729 } catch (IOException e) {
3730 result = writeEeException(EE_ERROR_IO, e.getMessage());
3731 }
3732 Log.d(TAG,"reset" + stat);
3733 return stat;
3734 }
3735
3736 boolean _nfcEeReset() throws IOException {
3737 synchronized (NfcService.this) {
3738 if (!isNfcEnabledOrShuttingDown()) {
3739 throw new IOException("NFC adapter is disabled");
3740 }
3741 if (mOpenEe == null) {
3742 throw new IOException("NFC EE closed");
3743 }
3744 return mSecureElement.doReset(mOpenEe.handle);
3745 }
3746 }
3747
3748 @Override
3749 public int getSecureElementTechList(String pkg) throws RemoteException {
3750 NfcService.this.enforceNfceeAdminPerm(pkg);
3751 return mDeviceHost.doGetSecureElementTechList();
3752 }
3753
3754 @Override
3755 public byte[] getSecureElementUid(String pkg) throws RemoteException {
3756 NfcService.this.enforceNfceeAdminPerm(pkg);
3757 return mDeviceHost.getSecureElementUid();
3758 }
3759
3760 @Override
3761 public void notifyCheckCertResult(String pkg, boolean success)
3762 throws RemoteException {
3763 if (DBG) Log.d(TAG, "notifyCheckCertResult() " + pkg + ", success=" + success);
3764
3765 NfcService.this.enforceNfceeAdminPerm(pkg);
nxpandroid64fd68c2015-09-23 16:45:15 +05303766 mNxpNfcController.setResultForX509Certificates(success);
nxpandroid64fd68c2015-09-23 16:45:15 +05303767 }
3768
3769 @Override
3770 public void deliverSeIntent(String pkg, Intent seIntent)
3771 throws RemoteException {
3772 Log.d(TAG, "deliverSeIntent() " + pkg + " " + seIntent.getAction());
3773 NfcService.this.enforceNfceeAdminPerm(pkg);
nxpandroid64fd68c2015-09-23 16:45:15 +05303774 sendMessage(MSG_SE_DELIVER_INTENT, seIntent);
3775 }
3776
3777 @Override
3778 public byte[] doGetRouting() throws RemoteException {
3779 return mDeviceHost.doGetRouting();
3780 }
3781
3782 @Override
3783 public Bundle getAtr(String pkg) throws RemoteException {
3784 NfcService.this.enforceNfceeAdminPerm(pkg);
3785
3786 Bundle result;
3787 byte[] out;
3788 try {
3789 out = _getAtr();
3790 result = writeNoException();
3791 result.putByteArray("out", out);
3792 } catch (IOException e) {
3793 result = writeEeException(EE_ERROR_IO, e.getMessage());
3794 }
3795 Log.d(TAG,"getAtr result " + result);
3796 return result;
3797 }
3798
3799 private byte[] _getAtr() throws IOException {
3800 synchronized(NfcService.this) {
3801 if (!isNfcEnabled()) {
3802 throw new IOException("NFC is not enabled");
3803 }
3804 if (mOpenEe == null) {
3805 throw new IOException("NFC EE is not open");
3806 }
3807 if (getCallingPid() != mOpenEe.pid) {
3808 throw new SecurityException("Wrong PID");
3809 }
3810 }
3811 return mSecureElement.doGetAtr(mOpenEe.handle);
3812 }
nxpandroid34627bd2016-05-27 15:52:30 +05303813 @Override
3814 public int selectUicc(int uiccSlot) throws RemoteException {
3815 synchronized(NfcService.this) {
3816 if (!isNfcEnabled()) {
3817 throw new RemoteException("NFC is not enabled");
3818 }
3819 int status = mDeviceHost.doselectUicc(uiccSlot);
3820 Log.i(TAG, "Update routing table");
3821 /*In case of UICC connected and Enabled or Removed ,
3822 *Reconfigure the routing table based on current UICC parameters
3823 **/
3824 if((status == 0x00)||(status == 0x01))
3825 {
nxpandroidebf53fb2016-12-22 18:48:59 +05303826 mPrefsEditor.putInt(PREF_CUR_SELECTED_UICC_ID, uiccSlot);
3827 mPrefsEditor.apply();
nxpandroid34627bd2016-05-27 15:52:30 +05303828 if((mAidRoutingManager != null) && (mCardEmulationManager != null))
3829 {
3830 Log.i(TAG, "Update routing table");
3831 mAidRoutingManager.onNfccRoutingTableCleared();
nxpandroid810c4772017-04-10 18:28:54 +05303832 mIsRoutingTableDirty = true;
nxpandroid34627bd2016-05-27 15:52:30 +05303833 mCardEmulationManager.onNfcEnabled();
nxpandroid34627bd2016-05-27 15:52:30 +05303834 }
3835 else
3836 {
3837 Log.i(TAG, "Update only Mifare and Desfire route");
3838 mIsRoutingTableDirty = true;
3839 applyRouting(false);
3840 }
3841 }
3842 return status;
3843 }
3844 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303845
nxpandroid34627bd2016-05-27 15:52:30 +05303846 @Override
3847 public int getSelectedUicc() throws RemoteException {
3848 if (!isNfcEnabled()) {
3849 throw new RemoteException("NFC is not enabled");
3850 }
3851 return mDeviceHost.doGetSelectedUicc();
3852 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303853
nxpandroid7d44e572016-08-01 19:11:04 +05303854 @Override
3855 public Bundle openuicc(String pkg, IBinder b) throws RemoteException {
3856 NfcService.this.enforceNfceeAdminPerm(pkg);
3857
3858 Bundle result;
3859 int handle = _openuicc(b);
3860 if (handle < 0) {
3861 result = writeEeException(handle, "NFCEE UICC open exception.");
3862 } else {
3863 result = writeNoException();
3864 }
3865 return result;
3866 }
3867
3868 /**
3869 * Opens a connection to the UICC element.
3870 *
3871 * @return A handle with a value >= 0 in case of success, or a
3872 * negative value in case of failure.
3873 */
3874 private int _openuicc(IBinder b) {
3875 synchronized(NfcService.this) {
3876 if (!isNfcEnabled()) {
3877 return EE_ERROR_NFC_DISABLED;
3878 }
3879 if (mInProvisionMode) {
3880 // Deny access to the NFCEE as long as the device is being setup
3881 return EE_ERROR_IO;
3882 }
nxpandroid7d44e572016-08-01 19:11:04 +05303883 if (mOpenEe != null) {
3884 return EE_ERROR_ALREADY_OPEN;
3885 }
3886
3887 boolean restorePolling = false;
3888 if (mNfcPollingEnabled) {
3889 // Disable polling for tags/P2P when connecting to the SMX
3890 // on PN544-based devices. Whenever nfceeClose is called,
3891 // the polling configuration will be restored.
3892 mDeviceHost.disableDiscovery();
3893 mNfcPollingEnabled = false;
3894 restorePolling = true;
3895 }
3896
3897 int handle = doOpenSecureElementConnection(0xF4);
3898 if (handle < 0) {
3899
3900 if (restorePolling) {
3901 mDeviceHost.enableDiscovery(mCurrentDiscoveryParameters, true);
3902 mNfcPollingEnabled = true;
3903 }
3904 return handle;
3905 }
nxpandroid7d44e572016-08-01 19:11:04 +05303906
3907 mOpenEe = new OpenSecureElement(getCallingPid(), handle, b);
3908 try {
3909 b.linkToDeath(mOpenEe, 0);
3910 } catch (RemoteException e) {
3911 mOpenEe.binderDied();
3912 }
3913
3914 // Add the calling package to the list of packages that have accessed
3915 // the secure element.
3916 for (String packageName : mContext.getPackageManager().getPackagesForUid(getCallingUid())) {
3917 mSePackages.add(packageName);
3918 }
3919
3920 return handle;
3921 }
3922 }
3923
3924 @Override
3925 public Bundle closeuicc(String pkg, IBinder binder) throws RemoteException {
3926 NfcService.this.enforceNfceeAdminPerm(pkg);
3927
3928 Bundle result;
3929 try {
3930 Log.w("Nxp", "Close UICC!");
3931 _nfcEeClose(getCallingPid(), binder);
3932 result = writeNoException();
3933 } catch (IOException e) {
3934 result = writeEeException(EE_ERROR_IO, e.getMessage());
3935 }
3936 return result;
3937 }
3938
3939 @Override
3940 public Bundle transceiveuicc(String pkg, byte[] in) throws RemoteException {
3941 NfcService.this.enforceNfceeAdminPerm(pkg);
3942
3943 Bundle result;
3944 byte[] out;
3945 try {
3946 out = _transceiveuicc(in);
3947 result = writeNoException();
3948 result.putByteArray("out", out);
3949 } catch (IOException e) {
3950 result = writeEeException(EE_ERROR_IO, e.getMessage());
3951 }
3952 return result;
3953 }
3954
3955 private byte[] _transceiveuicc(byte[] data) throws IOException {
3956 synchronized(NfcService.this) {
3957 if (!isNfcEnabled()) {
3958 throw new IOException("NFC is not enabled");
3959 }
3960 if (mOpenEe == null) {
3961 throw new IOException("NFC EE is not open");
3962 }
3963 if (getCallingPid() != mOpenEe.pid) {
3964 throw new SecurityException("Wrong PID");
3965 }
3966 }
3967
3968 return doTransceive(mOpenEe.handle, data);
3969 }
nxpandroid64fd68c2015-09-23 16:45:15 +05303970 }
3971
3972 /** resources kept while secure element is open */
3973 private class OpenSecureElement implements IBinder.DeathRecipient {
3974 public int pid; // pid that opened SE
3975 // binder handle used for DeathReceipient. Must keep
3976 // a reference to this, otherwise it can get GC'd and
3977 // the binder stub code might create a different BinderProxy
3978 // for the same remote IBinder, causing mismatched
3979 // link()/unlink()
3980 public IBinder binder;
3981 public int handle; // low-level handle
3982 public OpenSecureElement(int pid, int handle, IBinder binder) {
3983 this.pid = pid;
3984 this.handle = handle;
3985 this.binder = binder;
3986 }
3987 @Override
3988 public void binderDied() {
3989 synchronized (NfcService.this) {
3990 Log.i(TAG, "Tracked app " + pid + " died");
3991 pid = -1;
3992 try {
3993 _nfcEeClose(-1, binder);
3994 } catch (IOException e) { /* already closed */ }
3995 }
3996 }
3997 @Override
3998 public String toString() {
3999 return new StringBuilder('@').append(Integer.toHexString(hashCode())).append("[pid=")
4000 .append(pid).append(" handle=").append(handle).append("]").toString();
4001 }
4002 }
4003
4004 boolean isNfcEnabledOrShuttingDown() {
4005 synchronized (this) {
4006 return (mState == NfcAdapter.STATE_ON || mState == NfcAdapter.STATE_TURNING_OFF);
4007 }
4008 }
4009
4010 boolean isNfcEnabled() {
4011 synchronized (this) {
4012 return mState == NfcAdapter.STATE_ON;
4013 }
4014 }
4015
4016 class WatchDogThread extends Thread {
4017 final Object mCancelWaiter = new Object();
4018 final int mTimeout;
4019 boolean mCanceled = false;
4020
4021 public WatchDogThread(String threadName, int timeout) {
4022 super(threadName);
4023 mTimeout = timeout;
4024 }
4025
4026 @Override
4027 public void run() {
4028 try {
4029 synchronized (mCancelWaiter) {
4030 mCancelWaiter.wait(mTimeout);
4031 if (mCanceled) {
4032 return;
4033 }
4034 }
4035 } catch (InterruptedException e) {
4036 // Should not happen; fall-through to abort.
4037 Log.w(TAG, "Watchdog thread interruped.");
4038 interrupt();
4039 }
4040 Log.e(TAG, "Watchdog triggered, aborting.");
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304041 mDeviceHost.doAbort(getName());
nxpandroid64fd68c2015-09-23 16:45:15 +05304042 }
4043
4044 public synchronized void cancel() {
4045 synchronized (mCancelWaiter) {
4046 mCanceled = true;
4047 mCancelWaiter.notify();
4048 }
4049 }
4050 }
4051
4052 /* For Toast from background process*/
4053
4054 public class ToastHandler
4055 {
4056 // General attributes
4057 private Context mContext;
4058 private Handler mHandler;
4059
4060 public ToastHandler(Context _context)
4061 {
4062 this.mContext = _context;
4063 this.mHandler = new Handler();
4064 }
4065
4066 /**
4067 * Runs the <code>Runnable</code> in a separate <code>Thread</code>.
4068 *
4069 * @param _runnable
4070 * The <code>Runnable</code> containing the <code>Toast</code>
4071 */
4072 private void runRunnable(final Runnable _runnable)
4073 {
4074 Thread thread = new Thread()
4075 {
4076 public void run()
4077 {
4078 mHandler.post(_runnable);
4079 }
4080 };
4081
4082 thread.start();
4083 thread.interrupt();
4084 thread = null;
4085 }
4086
4087 public void showToast(final CharSequence _text, final int _duration)
4088 {
4089 final Runnable runnable = new Runnable()
4090 {
4091 @Override
4092 public void run()
4093 {
4094 Toast.makeText(mContext, _text, _duration).show();
4095 }
4096 };
4097
4098 runRunnable(runnable);
4099 }
4100 }
4101
4102 static byte[] hexStringToBytes(String s) {
4103 if (s == null || s.length() == 0) return null;
4104 int len = s.length();
4105 if (len % 2 != 0) {
4106 s = '0' + s;
4107 len++;
4108 }
4109 byte[] data = new byte[len / 2];
4110 for (int i = 0; i < len; i += 2) {
4111 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
4112 + Character.digit(s.charAt(i + 1), 16));
4113 }
4114 return data;
4115 }
4116
4117 static String toHexString(byte[] buffer, int offset, int length) {
nxpandroid281eb922016-08-25 20:27:46 +05304118 final char[] hexChars = "0123456789abcdef".toCharArray();
nxpandroid64fd68c2015-09-23 16:45:15 +05304119 char[] chars = new char[2 * length];
4120 for (int j = offset; j < offset + length; ++j) {
nxpandroid281eb922016-08-25 20:27:46 +05304121 chars[2 * (j-offset)] = hexChars[(buffer[j] & 0xF0) >>> 4];
4122 chars[2 * (j-offset) + 1] = hexChars[buffer[j] & 0x0F];
nxpandroid64fd68c2015-09-23 16:45:15 +05304123 }
4124 return new String(chars);
4125 }
4126
4127 /**
4128 * Read mScreenState and apply NFC-C polling and NFC-EE routing
4129 */
4130 void applyRouting(boolean force) {
4131 Log.d(TAG, "applyRouting - enter force = " + force + " mScreenState = " + mScreenState);
4132
4133 synchronized (this) {
4134 //Since Reader mode during wired mode is supported
4135 //enableDiscovery or disableDiscovery is allowed
nxpandroid64fd68c2015-09-23 16:45:15 +05304136 if (!isNfcEnabledOrShuttingDown()) {
4137 // PN544 cannot be reconfigured while EE is open
4138 return;
4139 }
4140 WatchDogThread watchDog = new WatchDogThread("applyRouting", ROUTING_WATCHDOG_MS);
4141 if (mInProvisionMode) {
4142 mInProvisionMode = Settings.Secure.getInt(mContentResolver,
4143 Settings.Global.DEVICE_PROVISIONED, 0) == 0;
4144 if (!mInProvisionMode) {
4145 // Notify dispatcher it's fine to dispatch to any package now
4146 // and allow handover transfers.
4147 mNfcDispatcher.disableProvisioningMode();
nxpandroid1153eb32015-11-06 18:46:58 +05304148 /* if provision mode is disabled, then send this info to lower layers as well */
4149 mDeviceHost.doSetProvisionMode(mInProvisionMode);
nxpandroid64fd68c2015-09-23 16:45:15 +05304150 }
4151 }
4152 // Special case: if we're transitioning to unlocked state while
4153 // still talking to a tag, postpone re-configuration.
4154 if (mScreenState == ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED && isTagPresent()) {
4155 Log.d(TAG, "Not updating discovery parameters, tag connected.");
4156 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_RESUME_POLLING),
4157 APPLY_ROUTING_RETRY_TIMEOUT_MS);
4158 return;
4159 }
4160
4161 try {
4162 watchDog.start();
4163 // Compute new polling parameters
4164 NfcDiscoveryParameters newParams = computeDiscoveryParameters(mScreenState);
4165 if (force || !newParams.equals(mCurrentDiscoveryParameters)) {
4166 if (newParams.shouldEnableDiscovery()) {
4167 boolean shouldRestart = mCurrentDiscoveryParameters.shouldEnableDiscovery();
4168 mDeviceHost.enableDiscovery(newParams, shouldRestart);
4169 } else {
4170 mDeviceHost.disableDiscovery();
4171 }
4172 mCurrentDiscoveryParameters = newParams;
4173 } else {
4174 Log.d(TAG, "Discovery configuration equal, not updating.");
4175 }
4176 } finally {
4177 watchDog.cancel();
4178 }
4179 }
4180 }
4181
4182 private NfcDiscoveryParameters computeDiscoveryParameters(int screenState) {
4183 // Recompute discovery parameters based on screen state
4184 NfcDiscoveryParameters.Builder paramsBuilder = NfcDiscoveryParameters.newBuilder();
nxpandroide66eb092017-07-12 21:36:08 +05304185
nxpandroid64fd68c2015-09-23 16:45:15 +05304186 // Polling
nxpandroid5d64ce92016-11-18 19:48:53 +05304187 if ((screenState >= NFC_POLLING_MODE)||mIsTaskBoot) {
nxpandroid64fd68c2015-09-23 16:45:15 +05304188 // Check if reader-mode is enabled
4189 if (mReaderModeParams != null) {
4190 int techMask = 0;
4191 if ((mReaderModeParams.flags & NfcAdapter.FLAG_READER_NFC_A) != 0)
4192 techMask |= NFC_POLL_A;
4193 if ((mReaderModeParams.flags & NfcAdapter.FLAG_READER_NFC_B) != 0)
4194 techMask |= NFC_POLL_B;
4195 if ((mReaderModeParams.flags & NfcAdapter.FLAG_READER_NFC_F) != 0)
4196 techMask |= NFC_POLL_F;
4197 if ((mReaderModeParams.flags & NfcAdapter.FLAG_READER_NFC_V) != 0)
4198 techMask |= NFC_POLL_ISO15693;
4199 if ((mReaderModeParams.flags & NfcAdapter.FLAG_READER_NFC_BARCODE) != 0)
4200 techMask |= NFC_POLL_KOVIO;
4201
4202 paramsBuilder.setTechMask(techMask);
4203 paramsBuilder.setEnableReaderMode(true);
4204 } else {
4205 paramsBuilder.setTechMask(NfcDiscoveryParameters.NFC_POLL_DEFAULT);
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304206 paramsBuilder.setEnableP2p(true);
nxpandroid64fd68c2015-09-23 16:45:15 +05304207 }
nxpandroide66eb092017-07-12 21:36:08 +05304208 }
4209 if ((screenState == ScreenStateHelper.SCREEN_STATE_ON_LOCKED && mInProvisionMode) &&
4210 !mNfcUnlockManager.isLockscreenPollingEnabled()) {
4211 if (mReaderModeParams != null)
nxpandroid64fd68c2015-09-23 16:45:15 +05304212 paramsBuilder.setTechMask(NfcDiscoveryParameters.NFC_POLL_DEFAULT);
4213 // enable P2P for MFM/EDU/Corp provisioning
4214 paramsBuilder.setEnableP2p(true);
nxpandroide66eb092017-07-12 21:36:08 +05304215 } else if ((screenState == ScreenStateHelper.SCREEN_STATE_ON_LOCKED) &&
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304216 (mIsLiveCaseEnabled || mNfcUnlockManager.isLockscreenPollingEnabled())) {
4217 int techMask = 0;
4218 // enable polling for Live Case technologies
4219 if (mIsLiveCaseEnabled)
4220 techMask |= mLiveCaseTechnology;
4221 if (mNfcUnlockManager.isLockscreenPollingEnabled())
nxpandroide66eb092017-07-12 21:36:08 +05304222 {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304223 techMask |= mNfcUnlockManager.getLockscreenPollMask();
nxpandroide66eb092017-07-12 21:36:08 +05304224 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304225 paramsBuilder.setTechMask(techMask);
nxpandroid64fd68c2015-09-23 16:45:15 +05304226 paramsBuilder.setEnableLowPowerDiscovery(false);
4227 paramsBuilder.setEnableP2p(false);
4228 }
4229
nxpandroid64fd68c2015-09-23 16:45:15 +05304230 //To make routing table update.
4231 if(mIsRoutingTableDirty) {
4232 mIsRoutingTableDirty = false;
nxpandroida9a68ba2016-01-14 21:12:17 +05304233 int protoRoute = mNxpPrefs.getInt("PREF_MIFARE_DESFIRE_PROTO_ROUTE_ID", GetDefaultMifareDesfireRouteEntry());
4234 int defaultRoute=mNxpPrefs.getInt("PREF_SET_DEFAULT_ROUTE_ID", GetDefaultRouteEntry());
4235 int techRoute=mNxpPrefs.getInt("PREF_MIFARE_CLT_ROUTE_ID", GetDefaultMifateCLTRouteEntry());
nxpandroid281eb922016-08-25 20:27:46 +05304236 if (DBG) Log.d(TAG, "Set default Route Entry");
nxpandroid64fd68c2015-09-23 16:45:15 +05304237 setDefaultRoute(defaultRoute, protoRoute, techRoute);
4238 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304239
nxpandroid64fd68c2015-09-23 16:45:15 +05304240 return paramsBuilder.build();
4241 }
4242
4243 private boolean isTagPresent() {
4244 for (Object object : mObjectMap.values()) {
4245 if (object instanceof TagEndpoint) {
4246 return ((TagEndpoint) object).isPresent();
4247 }
4248 }
4249 return false;
4250 }
4251 /**
4252 * Disconnect any target if present
4253 */
4254 void maybeDisconnectTarget() {
4255 if (!isNfcEnabledOrShuttingDown()) {
4256 return;
4257 }
4258 Object[] objectsToDisconnect;
4259 synchronized (this) {
4260 Object[] objectValues = mObjectMap.values().toArray();
4261 // Copy the array before we clear mObjectMap,
4262 // just in case the HashMap values are backed by the same array
4263 objectsToDisconnect = Arrays.copyOf(objectValues, objectValues.length);
4264 mObjectMap.clear();
4265 }
4266 for (Object o : objectsToDisconnect) {
4267 if (DBG) Log.d(TAG, "disconnecting " + o.getClass().getName());
4268 if (o instanceof TagEndpoint) {
4269 // Disconnect from tags
4270 TagEndpoint tag = (TagEndpoint) o;
4271 tag.disconnect();
4272 } else if (o instanceof NfcDepEndpoint) {
4273 // Disconnect from P2P devices
4274 NfcDepEndpoint device = (NfcDepEndpoint) o;
4275 if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
4276 // Remote peer is target, request disconnection
4277 device.disconnect();
4278 } else {
4279 // Remote peer is initiator, we cannot disconnect
4280 // Just wait for field removal
4281 }
4282 }
4283 }
4284 }
4285
4286 Object findObject(int key) {
4287 synchronized (this) {
4288 Object device = mObjectMap.get(key);
4289 if (device == null) {
4290 Log.w(TAG, "Handle not found");
4291 }
4292 return device;
4293 }
4294 }
4295
nxpandroid281eb922016-08-25 20:27:46 +05304296 Object findAndRemoveObject(int handle) {
4297 synchronized (this) {
4298 Object device = mObjectMap.get(handle);
4299 if (device == null) {
4300 Log.w(TAG, "Handle not found");
4301 } else {
4302 mObjectMap.remove(handle);
4303 }
4304 return device;
4305 }
4306 }
4307
nxpandroid64fd68c2015-09-23 16:45:15 +05304308 void registerTagObject(TagEndpoint tag) {
4309 synchronized (this) {
4310 mObjectMap.put(tag.getHandle(), tag);
4311 }
4312 }
4313
4314 void unregisterObject(int handle) {
4315 synchronized (this) {
4316 mObjectMap.remove(handle);
4317 }
4318 }
4319
4320 /**
4321 * For use by code in this process
4322 */
4323 public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
4324 throws LlcpException {
4325 return mDeviceHost.createLlcpSocket(sap, miu, rw, linearBufferLength);
4326 }
4327
4328 /**
4329 * For use by code in this process
4330 */
4331 public LlcpConnectionlessSocket createLlcpConnectionLessSocket(int sap, String sn)
4332 throws LlcpException {
4333 return mDeviceHost.createLlcpConnectionlessSocket(sap, sn);
4334 }
4335
4336 /**
4337 * For use by code in this process
4338 */
4339 public LlcpServerSocket createLlcpServerSocket(int sap, String sn, int miu, int rw,
4340 int linearBufferLength) throws LlcpException {
4341 return mDeviceHost.createLlcpServerSocket(sap, sn, miu, rw, linearBufferLength);
4342 }
4343
4344 public void sendMockNdefTag(NdefMessage msg) {
4345 sendMessage(MSG_MOCK_NDEF, msg);
4346 }
4347
4348 public void notifyRoutingTableFull()
4349 {
nxpandroidebf53fb2016-12-22 18:48:59 +05304350 if(!mNxpNfcController.isGsmaCommitOffhostService()) {
4351 ComponentName prevPaymentComponent = mAidCache.getPreviousPreferredPaymentService();
4352
4353 mNxpPrefsEditor = mNxpPrefs.edit();
4354 mNxpPrefsEditor.putInt("PREF_SET_AID_ROUTING_TABLE_FULL",0x01);
4355 mNxpPrefsEditor.commit();
4356 //broadcast Aid Routing Table Full intent to the user
4357 Intent aidTableFull = new Intent();
4358 aidTableFull.putExtra(NxpConstants.EXTRA_GSMA_PREV_PAYMENT_COMPONENT,prevPaymentComponent);
4359 aidTableFull.setAction(NxpConstants.ACTION_ROUTING_TABLE_FULL);
4360 if (DBG) {
4361 Log.d(TAG, "notify aid routing table full to the user");
4362 }
4363 mContext.sendBroadcastAsUser(aidTableFull, UserHandle.CURRENT);
4364 mAidCache.setPreviousPreferredPaymentService(null);
nxpandroid64fd68c2015-09-23 16:45:15 +05304365 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304366 }
4367 /**
4368 * set default Aid route entry in case application does not configure this route entry
4369 */
nxpandroidebf53fb2016-12-22 18:48:59 +05304370 public void setDefaultAidRouteLoc( int routeLoc)
nxpandroid64fd68c2015-09-23 16:45:15 +05304371 {
nxpandroida9a68ba2016-01-14 21:12:17 +05304372 mNxpPrefsEditor = mNxpPrefs.edit();
nxpandroidebf53fb2016-12-22 18:48:59 +05304373 Log.d(TAG, "writing to preferences setDefaultAidRouteLoc :" + routeLoc);
4374
4375 int defaultAidRoute = ((mDeviceHost.getDefaultAidPowerState() & 0x1F) | (routeLoc << ROUTE_LOC_MASK));
4376 if(routeLoc == 0x00)
4377 {
4378 /*
4379 bit pos 1 = Power Off
4380 bit pos 2 = Battery Off
4381 bit pos 4 = Screen Off
4382 Set these bits to 0 because in case routeLoc = HOST it can not work on POWER_OFF, BATTERY_OFF and SCREEN_OFF*/
4383 defaultAidRoute &= 0xE9;
4384 }
4385
4386 mNxpPrefsEditor.putInt("PREF_SET_DEFAULT_ROUTE_ID", defaultAidRoute);
nxpandroida9a68ba2016-01-14 21:12:17 +05304387 mNxpPrefsEditor.commit();
4388 int defaultRoute=mNxpPrefs.getInt("PREF_SET_DEFAULT_ROUTE_ID",0xFF);
nxpandroid64fd68c2015-09-23 16:45:15 +05304389 Log.d(TAG, "reading preferences from user :" + defaultRoute);
4390 }
4391
4392 public int getAidRoutingTableSize ()
4393 {
4394 int aidTableSize = 0x00;
4395 aidTableSize = mDeviceHost.getAidTableSize();
4396 return aidTableSize;
4397 }
4398
nxpandroidcbf24822017-07-12 21:37:17 +05304399 public void routeAids(String aid, int route, int powerState, int aidInfo) {
nxpandroid64fd68c2015-09-23 16:45:15 +05304400 Message msg = mHandler.obtainMessage();
4401 msg.what = MSG_ROUTE_AID;
4402 msg.arg1 = route;
4403 msg.arg2 = powerState;
nxpandroidcbf24822017-07-12 21:37:17 +05304404 Bundle aidbundle = new Bundle();
4405 aidbundle.putInt("aidinfo",aidInfo);
4406 msg.setData(aidbundle);
nxpandroid64fd68c2015-09-23 16:45:15 +05304407 msg.obj = aid;
4408 mHandler.sendMessage(msg);
4409 }
4410
4411 public void unrouteAids(String aid) {
4412 sendMessage(MSG_UNROUTE_AID, aid);
4413 }
nxpandroida5fd6622017-07-31 16:15:18 +05304414
4415 public void routeApduPattern(String apdu, String mask ,int route, int powerState) {
4416 Message msg = mHandler.obtainMessage();
4417 msg.what = MSG_ROUTE_APDU;
4418 msg.arg1 = route;
4419 msg.arg2 = powerState;
4420 Bundle apduPatternbundle = new Bundle();
4421 apduPatternbundle.putString("apduData",apdu);
4422 apduPatternbundle.putString("apduMask",mask);
4423 msg.setData(apduPatternbundle);
4424 mHandler.sendMessage(msg);
4425 }
4426
4427 public void unrouteApduPattern(String apdu) {
4428 //sendMessage(MSG_UNROUTE_APDU, apdu);
4429 mDeviceHost.unrouteApduPattern(hexStringToBytes(apdu));
4430 }
4431
nxpandroide66eb092017-07-12 21:36:08 +05304432 public int getNciVersion() {
4433 return mDeviceHost.getNciVersion();
4434 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304435 private byte[] getT3tIdentifierBytes(String systemCode, String nfcId2, String t3tPmm) {
4436 ByteBuffer buffer = ByteBuffer.allocate(2 + 8 + 8);
nxpandroid34627bd2016-05-27 15:52:30 +05304437 buffer.put(hexStringToBytes(systemCode));
4438 buffer.put(hexStringToBytes(nfcId2));
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304439 buffer.put(hexStringToBytes(t3tPmm));
nxpandroid34627bd2016-05-27 15:52:30 +05304440 byte[] t3tIdBytes = new byte[buffer.position()];
4441 buffer.position(0);
4442 buffer.get(t3tIdBytes);
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304443
nxpandroid34627bd2016-05-27 15:52:30 +05304444 return t3tIdBytes;
4445 }
4446
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304447 public void registerT3tIdentifier(String systemCode, String nfcId2, String t3tPmm) {
4448 Log.d(TAG, "request to register LF_T3T_IDENTIFIER");
4449
4450 byte[] t3tIdentifier = getT3tIdentifierBytes(systemCode, nfcId2, t3tPmm);
nxpandroid34627bd2016-05-27 15:52:30 +05304451 sendMessage(MSG_REGISTER_T3T_IDENTIFIER, t3tIdentifier);
4452 }
4453
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304454 public void deregisterT3tIdentifier(String systemCode, String nfcId2, String t3tPmm) {
4455 Log.d(TAG, "request to deregister LF_T3T_IDENTIFIER");
4456
4457 byte[] t3tIdentifier = getT3tIdentifierBytes(systemCode, nfcId2, t3tPmm);
nxpandroid34627bd2016-05-27 15:52:30 +05304458 sendMessage(MSG_DEREGISTER_T3T_IDENTIFIER, t3tIdentifier);
4459 }
4460
4461 public void clearT3tIdentifiersCache() {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304462 Log.d(TAG, "clear T3t Identifiers Cache");
nxpandroid34627bd2016-05-27 15:52:30 +05304463 mDeviceHost.clearT3tIdentifiersCache();
4464 }
4465
4466 public int getLfT3tMax() {
4467 return mDeviceHost.getLfT3tMax();
4468 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304469
4470 public void commitRouting() {
4471 mHandler.sendEmptyMessage(MSG_COMMIT_ROUTING);
4472 }
4473 /**
4474 * get default Aid route entry in case application does not configure this route entry
4475 */
4476 public int GetDefaultRouteLoc()
4477 {
nxpandroida9a68ba2016-01-14 21:12:17 +05304478 int defaultRouteLoc = mNxpPrefs.getInt("PREF_SET_DEFAULT_ROUTE_ID", GetDefaultRouteEntry()) >> ROUTE_LOC_MASK;
nxpandroid64fd68c2015-09-23 16:45:15 +05304479 Log.d(TAG, "GetDefaultRouteLoc :" + defaultRouteLoc);
4480 return defaultRouteLoc ;
4481 }
4482
4483 /**
4484 * get default MifareDesfireRoute route entry in case application does not configure this route entry
4485 */
4486 public int GetDefaultMifareDesfireRouteEntry()
4487 {
nxpandroid7d44e572016-08-01 19:11:04 +05304488 int routeLoc = mDeviceHost.getDefaultDesfireRoute();
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304489 int defaultMifareDesfireRoute = ((mDeviceHost.getDefaultDesfirePowerState() & 0x3F) | (routeLoc << ROUTE_LOC_MASK));
nxpandroid7d44e572016-08-01 19:11:04 +05304490 if(routeLoc == 0x00)
4491 {
nxpandroid8aecbf82016-09-16 20:21:47 +05304492 /*
4493 bit pos 1 = Power Off
4494 bit pos 2 = Battery Off
4495 bit pos 4 = Screen Off
4496 Set these bits to 0 because in case routeLoc = HOST it can not work on POWER_OFF, BATTERY_OFF and SCREEN_OFF*/
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304497 defaultMifareDesfireRoute &= 0xF9;
nxpandroid7d44e572016-08-01 19:11:04 +05304498 }
nxpandroid281eb922016-08-25 20:27:46 +05304499 if (DBG) Log.d(TAG, "defaultMifareDesfireRoute : " + defaultMifareDesfireRoute);
nxpandroid7d44e572016-08-01 19:11:04 +05304500 return defaultMifareDesfireRoute;
nxpandroid64fd68c2015-09-23 16:45:15 +05304501 }
4502 /**
4503 * set default Aid route entry in case application does not configure this route entry
4504 */
4505
4506 public int GetDefaultRouteEntry()
4507 {
nxpandroid7d44e572016-08-01 19:11:04 +05304508 int routeLoc = mDeviceHost.getDefaultAidRoute();
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304509 int defaultAidRoute = ((mDeviceHost.getDefaultAidPowerState() & 0x3F) | (routeLoc << ROUTE_LOC_MASK));
nxpandroid7d44e572016-08-01 19:11:04 +05304510 if(routeLoc == 0x00)
4511 {
nxpandroid8aecbf82016-09-16 20:21:47 +05304512 /*
4513 bit pos 1 = Power Off
4514 bit pos 2 = Battery Off
4515 bit pos 4 = Screen Off
4516 Set these bits to 0 because in case routeLoc = HOST it can not work on POWER_OFF, BATTERY_OFF and SCREEN_OFF*/
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304517 defaultAidRoute &= 0xF9;
nxpandroid7d44e572016-08-01 19:11:04 +05304518 }
nxpandroid281eb922016-08-25 20:27:46 +05304519 if (DBG) Log.d(TAG, "defaultAidRoute : " + defaultAidRoute);
nxpandroid64fd68c2015-09-23 16:45:15 +05304520 return defaultAidRoute;
4521 }
4522
4523 /**
4524 * get default MifateCLT route entry in case application does not configure this route entry
4525 */
4526 public int GetDefaultMifateCLTRouteEntry()
4527 {
nxpandroid7d44e572016-08-01 19:11:04 +05304528 int routeLoc = mDeviceHost.getDefaultMifareCLTRoute();
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304529 int defaultMifateCLTRoute = ((mDeviceHost.getDefaultMifareCLTPowerState() & 0x3F) | (routeLoc << ROUTE_LOC_MASK) | (TECH_TYPE_A << TECH_TYPE_MASK));
nxpandroid7d44e572016-08-01 19:11:04 +05304530
nxpandroid281eb922016-08-25 20:27:46 +05304531 if (DBG) Log.d(TAG, "defaultMifateCLTRoute : " + defaultMifateCLTRoute);
nxpandroid7d44e572016-08-01 19:11:04 +05304532 return defaultMifateCLTRoute;
nxpandroid64fd68c2015-09-23 16:45:15 +05304533 }
4534
4535 public boolean setDefaultRoute(int defaultRouteEntry, int defaultProtoRouteEntry, int defaultTechRouteEntry) {
4536 boolean ret = mDeviceHost.setDefaultRoute(defaultRouteEntry, defaultProtoRouteEntry, defaultTechRouteEntry);
4537 return ret;
4538 }
4539
4540 public int getDefaultRoute() {
nxpandroida9a68ba2016-01-14 21:12:17 +05304541 return mNxpPrefs.getInt(PREF_DEFAULT_ROUTE_ID, DEFAULT_ROUTE_ID_DEFAULT);
nxpandroid64fd68c2015-09-23 16:45:15 +05304542 }
4543
4544
4545 public void commitingFelicaRouting() {
4546 mHandler.sendEmptyMessage(MSG_COMMITINF_FELICA_ROUTING);
4547 }
4548
4549 public void commitedFelicaRouting() {
4550 mHandler.sendEmptyMessage(MSG_COMMITED_FELICA_ROUTING);
4551 }
4552
nxpandroida9a68ba2016-01-14 21:12:17 +05304553 public int getAidRoutingTableStatus() {
4554 int aidTableStatus = 0x00;
4555 aidTableStatus = mNxpPrefs.getInt("PREF_SET_AID_ROUTING_TABLE_FULL",0x00);
4556 return aidTableStatus;
4557 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304558
nxpandroid64fd68c2015-09-23 16:45:15 +05304559 public void clearRouting() {
4560 mHandler.sendEmptyMessage(MSG_CLEAR_ROUTING);
4561 }
4562
4563 public boolean isVzwFeatureEnabled(){
4564 return mDeviceHost.isVzwFeatureEnabled();
4565 }
4566
4567 public boolean sendData(byte[] data) {
4568 return mDeviceHost.sendRawFrame(data);
4569 }
4570
4571 public int getDefaultSecureElement() {
4572 int[] seList = mDeviceHost.doGetSecureElementList();
4573 if ( seList == null || seList.length != 1) {
4574 //use default value
4575 return -1;
4576 } else {
4577 return seList[0];
4578 }
4579 }
4580
4581 public void etsiStartConfig(int eeHandle) {
4582 Log.d(TAG, "etsiStartConfig Enter");
4583
4584 Log.d(TAG, "etsiStartConfig : etsiInitConfig");
4585 mDeviceHost.etsiInitConfig();
4586
4587 Log.d(TAG, "etsiStartConfig : disableDiscovery");
4588 mDeviceHost.disableDiscovery();
4589
4590 Log.d(TAG, "etsiStartConfig : etsiReaderConfig");
4591 mDeviceHost.etsiReaderConfig(eeHandle);
4592
4593 Log.d(TAG, "etsiStartConfig : notifyEEReaderEvent");
4594 mDeviceHost.notifyEEReaderEvent(ETSI_READER_REQUESTED);
4595
4596 Log.d(TAG, "etsiStartConfig : setEtsiReaederState");
4597 mDeviceHost.setEtsiReaederState(STATE_SE_RDR_MODE_STARTED);
4598 //broadcast SWP_READER_ACTIVATED evt
nxpandroid5d64ce92016-11-18 19:48:53 +05304599 Intent swpReaderRequestedIntent = new Intent();
4600 swpReaderRequestedIntent.setAction(NxpConstants.ACTION_SWP_READER_REQUESTED);
nxpandroid64fd68c2015-09-23 16:45:15 +05304601 if (DBG) {
4602 Log.d(TAG, "SWP READER - Requested");
4603 }
nxpandroid5d64ce92016-11-18 19:48:53 +05304604 mContext.sendBroadcast(swpReaderRequestedIntent);
nxpandroid64fd68c2015-09-23 16:45:15 +05304605
4606 Log.d(TAG, "etsiStartConfig : enableDiscovery");
4607 mDeviceHost.enableDiscovery(mCurrentDiscoveryParameters, true);
4608
4609 Log.d(TAG, "etsiStartConfig Exit");
4610 }
4611
4612 public void etsiStopConfig(int discNtfTimeout) {
4613 Log.d(TAG, "etsiStopConfig Enter");
4614 if( mDeviceHost.getEtsiReaederState() == STATE_SE_RDR_MODE_STOP_IN_PROGRESS)
4615 {
4616 Log.d(TAG, "Attempting etsiStopConfig while STATE_SE_RDR_MODE_STOP_IN_PROGRESS. Returning..");
4617 return;
4618 }
4619 ETSI_STOP_CONFIG = true;
4620 TagRemoveTask tagRemoveTask = new TagRemoveTask();
4621 tagRemoveTask.execute(discNtfTimeout);
4622 Log.d(TAG, "etsiStopConfig : etsiInitConfig");
4623 mDeviceHost.etsiInitConfig();
4624
nxpandroid64fd68c2015-09-23 16:45:15 +05304625 Log.d(TAG, "etsiStopConfig : disableDiscovery");
4626 mDeviceHost.disableDiscovery();
4627
4628 if(mDeviceHost.getEtsiReaederState() == STATE_SE_RDR_MODE_STOPPED)
4629 {
4630 Log.d(TAG, "etsiStopConfig :etsi reader already Stopped. Returning..");
4631 ETSI_STOP_CONFIG = false;
4632 return;
4633 }
4634 Log.d(TAG, "etsiStopConfig : etsiResetReaderConfig");
4635 mDeviceHost.etsiResetReaderConfig();
4636
4637 Log.d(TAG, "etsiStopConfig : notifyEEReaderEvent");
4638 mDeviceHost.notifyEEReaderEvent(ETSI_READER_STOP);
4639
nxpandroid5d64ce92016-11-18 19:48:53 +05304640 Intent swpReaderDeActivatedIntent = new Intent();
nxpandroid64fd68c2015-09-23 16:45:15 +05304641
4642 //broadcast SWP_READER_DEACTIVATED evt
nxpandroid5d64ce92016-11-18 19:48:53 +05304643 swpReaderDeActivatedIntent
nxpandroid64fd68c2015-09-23 16:45:15 +05304644 .setAction(NxpConstants.ACTION_SWP_READER_DEACTIVATED);
4645 if (DBG) {
4646 Log.d(TAG, "SWP READER - DeActivated");
4647 }
nxpandroid5d64ce92016-11-18 19:48:53 +05304648 mContext.sendBroadcast(swpReaderDeActivatedIntent);
nxpandroid64fd68c2015-09-23 16:45:15 +05304649
4650 Log.d(TAG, "etsiStopConfig : setEtsiReaederState");
4651 mDeviceHost.setEtsiReaederState(STATE_SE_RDR_MODE_STOPPED);
4652
4653 Log.d(TAG, "etsiStopConfig : enableDiscovery");
4654 mDeviceHost.enableDiscovery(mCurrentDiscoveryParameters, true);
4655 ETSI_STOP_CONFIG = false;
4656
4657 Log.d(TAG, "etsiStopConfig : updateScreenState");
4658 mDeviceHost.updateScreenState();
4659
4660 Log.d(TAG, "etsiStopConfig Exit");
4661 }
4662
4663 void sendMessage(int what, Object obj) {
4664 Message msg = mHandler.obtainMessage();
4665 msg.what = what;
4666 msg.obj = obj;
4667 mHandler.sendMessage(msg);
4668 }
4669
4670 final class NfcServiceHandler extends Handler {
4671 @Override
4672 public void handleMessage(Message msg) {
4673 switch (msg.what) {
4674 case MSG_ROUTE_AID: {
4675 int route = msg.arg1;
4676 int power = msg.arg2;
nxpandroidcbf24822017-07-12 21:37:17 +05304677 int aidInfo = 0x00;
4678 Bundle dataBundle = msg.getData();
4679 if (dataBundle != null)
4680 aidInfo = dataBundle.getInt("aidinfo");
nxpandroid64fd68c2015-09-23 16:45:15 +05304681 String aid = (String) msg.obj;
nxpandroidcbf24822017-07-12 21:37:17 +05304682 String cuttedAid = aid;
4683 if(aid.endsWith("*")||aid.endsWith("#")) {
4684 cuttedAid = aid.substring(0, aid.length() - 1);
nxpandroid64fd68c2015-09-23 16:45:15 +05304685 }
nxpandroidcbf24822017-07-12 21:37:17 +05304686 mDeviceHost.routeAid(hexStringToBytes(cuttedAid), route, power, aidInfo);
nxpandroid64fd68c2015-09-23 16:45:15 +05304687 // Restart polling config
4688 break;
4689 }
nxpandroid34627bd2016-05-27 15:52:30 +05304690 case MSG_REGISTER_T3T_IDENTIFIER: {
4691 Log.d(TAG, "message to register LF_T3T_IDENTIFIER");
4692 mDeviceHost.disableDiscovery();
4693
4694 byte[] t3tIdentifier = (byte[]) msg.obj;
4695 mDeviceHost.registerT3tIdentifier(t3tIdentifier);
4696
4697 NfcDiscoveryParameters params = computeDiscoveryParameters(mScreenState);
4698 boolean shouldRestart = mCurrentDiscoveryParameters.shouldEnableDiscovery();
4699 mDeviceHost.enableDiscovery(params, shouldRestart);
4700 break;
4701 }
4702 case MSG_DEREGISTER_T3T_IDENTIFIER: {
4703 Log.d(TAG, "message to deregister LF_T3T_IDENTIFIER");
4704 mDeviceHost.disableDiscovery();
4705
4706 byte[] t3tIdentifier = (byte[]) msg.obj;
4707 mDeviceHost.deregisterT3tIdentifier(t3tIdentifier);
4708
4709 NfcDiscoveryParameters params = computeDiscoveryParameters(mScreenState);
4710 boolean shouldRestart = mCurrentDiscoveryParameters.shouldEnableDiscovery();
4711 mDeviceHost.enableDiscovery(params, shouldRestart);
4712 break;
4713 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304714 case MSG_INVOKE_BEAM: {
4715 mP2pLinkManager.onManualBeamInvoke((BeamShareData)msg.obj);
4716 break;
4717 }
nxpandroida5fd6622017-07-31 16:15:18 +05304718
nxpandroid64fd68c2015-09-23 16:45:15 +05304719 case MSG_UNROUTE_AID: {
4720 String aid = (String) msg.obj;
4721 mDeviceHost.unrouteAid(hexStringToBytes(aid));
4722 break;
4723 }
4724
nxpandroid64fd68c2015-09-23 16:45:15 +05304725 case MSG_COMMITINF_FELICA_ROUTING: {
4726 Log.e(TAG, "applyRouting -10");
4727 mIsFelicaOnHostConfiguring = true;
4728 applyRouting(true);
4729 break;
4730 }
4731
4732 case MSG_COMMITED_FELICA_ROUTING: {
4733 Log.e(TAG, "applyRouting -11");
4734 mIsFelicaOnHostConfigured = true;
4735 applyRouting(true);
4736 break;
4737 }
4738
nxpandroid64fd68c2015-09-23 16:45:15 +05304739 case MSG_COMMIT_ROUTING: {
4740 Log.e(TAG, "applyRouting -9");
4741 boolean commit = false;
nxpandroid07d1cc22017-09-14 12:20:58 +05304742 boolean enForced = false;
nxpandroid64fd68c2015-09-23 16:45:15 +05304743 synchronized (NfcService.this) {
4744 if (mCurrentDiscoveryParameters.shouldEnableDiscovery()) {
4745 commit = true;
nxpandroid07d1cc22017-09-14 12:20:58 +05304746 }else if(mAidRoutingManager.isRoutingTableUpdated()){
4747 commit = true;
4748 enForced = true;
4749 Log.d(TAG, "Routing table is updated thus needs to be committed.");
4750 }
4751 else {
nxpandroid64fd68c2015-09-23 16:45:15 +05304752 Log.d(TAG, "Not committing routing because discovery is disabled.");
4753 }
4754 }
4755 if (commit) {
4756 mIsRoutingTableDirty = true;
nxpandroid07d1cc22017-09-14 12:20:58 +05304757 applyRouting(enForced);
nxpandroid64fd68c2015-09-23 16:45:15 +05304758 }
4759
4760
4761 break;
4762 }
4763 case MSG_CLEAR_ROUTING: {
4764 mDeviceHost.clearAidTable();
4765 break;
4766 }
4767
4768 case MSG_CHANGE_DEFAULT_ROUTE:
4769 Log.d(TAG, "Handler: Change default route");
4770 try{
4771 mNxpNfcAdapter.DefaultRouteSet(ROUTE_ID_HOST, true, false, false);
4772 } catch(RemoteException re) {
4773 Log.d(TAG, "NxpNci: onAidRoutingTableFull: Exception to change default route to host!");
4774 }
4775 break;
4776
4777 case MSG_MOCK_NDEF: {
4778 NdefMessage ndefMsg = (NdefMessage) msg.obj;
4779 Bundle extras = new Bundle();
4780 extras.putParcelable(Ndef.EXTRA_NDEF_MSG, ndefMsg);
4781 extras.putInt(Ndef.EXTRA_NDEF_MAXLENGTH, 0);
4782 extras.putInt(Ndef.EXTRA_NDEF_CARDSTATE, Ndef.NDEF_MODE_READ_ONLY);
4783 extras.putInt(Ndef.EXTRA_NDEF_TYPE, Ndef.TYPE_OTHER);
4784 Tag tag = Tag.createMockTag(new byte[]{0x00},
4785 new int[]{TagTechnology.NDEF},
4786 new Bundle[]{extras});
4787 Log.d(TAG, "mock NDEF tag, starting corresponding activity");
4788 Log.d(TAG, tag.toString());
4789 int dispatchStatus = mNfcDispatcher.dispatchTag(tag);
4790 if (dispatchStatus == NfcDispatcher.DISPATCH_SUCCESS) {
4791 playSound(SOUND_END);
4792 } else if (dispatchStatus == NfcDispatcher.DISPATCH_FAIL) {
4793 playSound(SOUND_ERROR);
4794 }
4795 break;
4796 }
4797
4798 case MSG_SE_DELIVER_INTENT: {
4799 Log.d(TAG, "SE DELIVER INTENT");
4800 Intent seIntent = (Intent) msg.obj;
4801
4802 String action = seIntent.getAction();
4803 if (action.equals("com.gsma.services.nfc.action.TRANSACTION_EVENT")) {
4804 byte[] byteAid = seIntent.getByteArrayExtra("com.android.nfc_extras.extra.AID");
4805 byte[] data = seIntent.getByteArrayExtra("com.android.nfc_extras.extra.DATA");
4806 String seName = seIntent.getStringExtra("com.android.nfc_extras.extra.SE_NAME");
4807 StringBuffer strAid = new StringBuffer();
4808 for (int i = 0; i < byteAid.length; i++) {
4809 String hex = Integer.toHexString(0xFF & byteAid[i]);
4810 if (hex.length() == 1)
4811 strAid.append('0');
4812 strAid.append(hex);
4813 }
4814 Intent gsmaIntent = new Intent();
4815 gsmaIntent.setAction("com.gsma.services.nfc.action.TRANSACTION_EVENT");
4816 if (byteAid != null)
4817 gsmaIntent.putExtra("com.gsma.services.nfc.extra.AID", byteAid);
4818 if (data != null)
4819 gsmaIntent.putExtra("com.gsma.services.nfc.extra.DATA", data);
4820
4821 //"nfc://secure:0/<seName>/<strAid>"
4822 String url = new String ("nfc://secure:0/" + seName + "/" + strAid);
4823 gsmaIntent.setData(Uri.parse(url));
4824 gsmaIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
4825 gsmaIntent.setPackage(seIntent.getPackage());
4826
4827 Boolean receptionMode = mNxpNfcController.mMultiReceptionMap.get(seName);
4828 if (receptionMode == null)
4829 receptionMode = defaultTransactionEventReceptionMode;
4830
4831 if (receptionMode == multiReceptionMode) {
4832 // if multicast reception for GSMA
4833 mContext.sendBroadcast(gsmaIntent);
4834 } else {
4835 // if unicast reception for GSMA
4836 try {
4837 if (mIsSentUnicastReception == false) {
4838 //start gsma
4839 gsmaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4840 mContext.startActivity(gsmaIntent);
4841 mIsSentUnicastReception = true;
4842 }
4843 } catch (Exception e) {
4844 if (DBG) Log.d(TAG, "Exception: " + e.getMessage());
4845 }
4846 }
4847 } else {
4848 mContext.sendBroadcast(seIntent);
4849 }
4850 break;
4851 }
4852
4853 case MSG_NDEF_TAG:
4854 if (DBG) Log.d(TAG, "Tag detected, notifying applications");
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304855 mNumTagsDetected.incrementAndGet();
nxpandroid64fd68c2015-09-23 16:45:15 +05304856 TagEndpoint tag = (TagEndpoint) msg.obj;
nxpandroid281eb922016-08-25 20:27:46 +05304857 byte[] debounceTagUid;
4858 int debounceTagMs;
4859 ITagRemovedCallback debounceTagRemovedCallback;
4860 synchronized (NfcService.this) {
4861 debounceTagUid = mDebounceTagUid;
4862 debounceTagMs = mDebounceTagDebounceMs;
4863 debounceTagRemovedCallback = mDebounceTagRemovedCallback;
4864 }
nxpandroid281eb922016-08-25 20:27:46 +05304865
nxpandroid64fd68c2015-09-23 16:45:15 +05304866 ReaderModeParams readerParams = null;
4867 int presenceCheckDelay = DEFAULT_PRESENCE_CHECK_DELAY;
4868 DeviceHost.TagDisconnectedCallback callback =
4869 new DeviceHost.TagDisconnectedCallback() {
4870 @Override
4871 public void onTagDisconnected(long handle) {
nxpandroid03323c82017-09-14 11:13:16 +05304872 if(nci_version != NCI_VERSION_2_0) {
4873 applyRouting(false);
4874 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304875 }
4876 };
4877 synchronized (NfcService.this) {
4878 readerParams = mReaderModeParams;
4879 }
4880 if (readerParams != null) {
4881 presenceCheckDelay = readerParams.presenceCheckDelay;
4882 if ((readerParams.flags & NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK) != 0) {
4883 if (DBG) Log.d(TAG, "Skipping NDEF detection in reader mode");
4884 tag.startPresenceChecking(presenceCheckDelay, callback);
4885 dispatchTagEndpoint(tag, readerParams);
4886 break;
4887 }
4888 }
4889
nxpandroid64fd68c2015-09-23 16:45:15 +05304890 if (tag.getConnectedTechnology() == TagTechnology.NFC_BARCODE) {
4891 // When these tags start containing NDEF, they will require
4892 // the stack to deal with them in a different way, since
4893 // they are activated only really shortly.
4894 // For now, don't consider NDEF on these.
4895 if (DBG) Log.d(TAG, "Skipping NDEF detection for NFC Barcode");
4896 tag.startPresenceChecking(presenceCheckDelay, callback);
4897 dispatchTagEndpoint(tag, readerParams);
4898 break;
4899 }
4900 NdefMessage ndefMsg = tag.findAndReadNdef();
4901
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304902 if (ndefMsg == null) {
4903 // First try to see if this was a bad tag read
4904 if (!tag.reconnect()) {
nxpandroid64fd68c2015-09-23 16:45:15 +05304905 tag.disconnect();
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304906 break;
nxpandroid64fd68c2015-09-23 16:45:15 +05304907 }
4908 }
nxpandroid6fd9cdb2017-07-12 18:25:41 +05304909
4910 if (debounceTagUid != null) {
4911 // If we're debouncing and the UID or the NDEF message of the tag match,
4912 // don't dispatch but drop it.
4913 if (Arrays.equals(debounceTagUid, tag.getUid()) ||
4914 (ndefMsg != null && ndefMsg.equals(mLastReadNdefMessage))) {
4915 mHandler.removeMessages(MSG_TAG_DEBOUNCE);
4916 mHandler.sendEmptyMessageDelayed(MSG_TAG_DEBOUNCE, debounceTagMs);
4917 tag.disconnect();
4918 return;
4919 } else {
4920 synchronized (NfcService.this) {
4921 mDebounceTagUid = null;
4922 mDebounceTagRemovedCallback = null;
4923 }
4924 if (debounceTagRemovedCallback != null) {
4925 try {
4926 debounceTagRemovedCallback.onTagRemoved();
4927 } catch (RemoteException e) {
4928 // Ignore
4929 }
4930 }
4931 }
4932 }
4933
4934 mLastReadNdefMessage = ndefMsg;
4935
4936 tag.startPresenceChecking(presenceCheckDelay, callback);
4937 dispatchTagEndpoint(tag, readerParams);
nxpandroid64fd68c2015-09-23 16:45:15 +05304938 break;
4939
nxpandroid5387b022017-02-03 18:04:32 +05304940 case MSG_CARD_EMULATION: {
nxpandroid64fd68c2015-09-23 16:45:15 +05304941 if (DBG) Log.d(TAG, "Card Emulation message");
4942 /* Tell the host-emu manager an AID has been selected on
4943 * a secure element.
4944 */
4945 if (mCardEmulationManager != null) {
4946 mCardEmulationManager.onOffHostAidSelected();
4947 }
4948 Pair<byte[], Pair> transactionInfo = (Pair<byte[], Pair>) msg.obj;
4949 Pair<byte[], Integer> dataSrcInfo = (Pair<byte[], Integer>) transactionInfo.second;
nxpandroid5387b022017-02-03 18:04:32 +05304950 String evtSrc = "";
nxpandroid64fd68c2015-09-23 16:45:15 +05304951 String gsmaSrc = "";
4952 String gsmaDataAID = toHexString(transactionInfo.first, 0, transactionInfo.first.length);
4953 {
4954 Log.d(TAG, "Event source " + dataSrcInfo.second);
4955
nxpandroid64fd68c2015-09-23 16:45:15 +05304956 if(dataSrcInfo.second == UICC_ID_TYPE) {
4957 evtSrc = NxpConstants.UICC_ID;
4958 gsmaSrc = "SIM1";
nxpandroid7d44e572016-08-01 19:11:04 +05304959 } else if(dataSrcInfo.second == UICC2_ID_TYPE) {
4960 evtSrc = NxpConstants.UICC2_ID;
4961 gsmaSrc = "SIM2";
nxpandroid64fd68c2015-09-23 16:45:15 +05304962 } else if(dataSrcInfo.second == SMART_MX_ID_TYPE) {
4963 evtSrc = NxpConstants.SMART_MX_ID;
4964 gsmaSrc = "ESE";
4965 }
4966 /* Send broadcast ordered */
nxpandroid281eb922016-08-25 20:27:46 +05304967 Intent transactionIntent = new Intent();
4968 transactionIntent.setAction(NxpConstants.ACTION_TRANSACTION_DETECTED);
4969 transactionIntent.putExtra(NxpConstants.EXTRA_AID, transactionInfo.first);
4970 transactionIntent.putExtra(NxpConstants.EXTRA_DATA, dataSrcInfo.first);
4971 transactionIntent.putExtra(NxpConstants.EXTRA_SOURCE, evtSrc);
nxpandroid64fd68c2015-09-23 16:45:15 +05304972 if (DBG) {
4973 Log.d(TAG, "Start Activity Card Emulation event");
4974 }
4975 mIsSentUnicastReception = false;
nxpandroid281eb922016-08-25 20:27:46 +05304976 mContext.sendBroadcast(transactionIntent, NfcPermissions.NFC_PERMISSION);
nxpandroid64fd68c2015-09-23 16:45:15 +05304977 }
nxpandroid64fd68c2015-09-23 16:45:15 +05304978
4979 /* Send "transaction events" to all authorized/registered components" */
4980 Intent evtIntent = new Intent();
4981 evtIntent.setAction(NxpConstants.ACTION_MULTI_EVT_TRANSACTION);
4982 evtIntent.setData(Uri.parse("nfc://secure:0/"+ gsmaSrc+"/"+ gsmaDataAID));
4983 evtIntent.putExtra(NxpConstants.EXTRA_GSMA_AID, transactionInfo.first);
4984 evtIntent.putExtra(NxpConstants.EXTRA_GSMA_DATA, dataSrcInfo.first);
4985 Log.d(TAG, "Broadcasting " + NxpConstants.ACTION_MULTI_EVT_TRANSACTION);
4986 sendMultiEvtBroadcast(evtIntent);
4987
nxpandroid5387b022017-02-03 18:04:32 +05304988 /* Send broadcast */
4989 if (dataSrcInfo.first != null) {
4990 String evt_data = toHexString(dataSrcInfo.first, 0, dataSrcInfo.first.length);
4991 if (DBG) Log.d(TAG, "Data is :"+evt_data);
4992 }
4993 Intent aidIntent = new Intent();
4994 aidIntent.setAction(ACTION_AID_SELECTED);
4995 aidIntent.putExtra(EXTRA_AID, transactionInfo.first);
4996 aidIntent.putExtra(NxpConstants.EXTRA_SOURCE, evtSrc);
4997 aidIntent.putExtra(NxpConstants.EXTRA_DATA,dataSrcInfo.first);
4998 if (DBG) Log.d(TAG, "Broadcasting " + ACTION_AID_SELECTED);
4999 sendSeBroadcast(aidIntent);
5000 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305001 break;
5002
5003 case MSG_CONNECTIVITY_EVENT:
5004 if (DBG) {
5005 Log.d(TAG, "SE EVENT CONNECTIVITY");
5006 }
5007 Integer evtSrcInfo = (Integer) msg.obj;
5008 Log.d(TAG, "Event source " + evtSrcInfo);
5009 String evtSrc = "";
5010 if(evtSrcInfo == UICC_ID_TYPE) {
5011 evtSrc = NxpConstants.UICC_ID;
nxpandroid7d44e572016-08-01 19:11:04 +05305012 } else if(evtSrcInfo == UICC2_ID_TYPE) {
5013 evtSrc = NxpConstants.UICC2_ID;
nxpandroid64fd68c2015-09-23 16:45:15 +05305014 } else if(evtSrcInfo == SMART_MX_ID_TYPE) {
5015 evtSrc = NxpConstants.SMART_MX_ID;
5016 }
5017
5018 Intent eventConnectivityIntent = new Intent();
5019 eventConnectivityIntent.setAction(NxpConstants.ACTION_CONNECTIVITY_EVENT_DETECTED);
5020 eventConnectivityIntent.putExtra(NxpConstants.EXTRA_SOURCE, evtSrc);
5021 if (DBG) {
5022 Log.d(TAG, "Broadcasting Intent");
5023 }
5024 mContext.sendBroadcast(eventConnectivityIntent, NfcPermissions.NFC_PERMISSION);
5025 break;
5026
5027 case MSG_EMVCO_MULTI_CARD_DETECTED_EVENT:
5028 if (DBG) {
5029 Log.d(TAG, "EMVCO MULTI CARD DETECTED EVENT");
5030 }
5031
5032 Intent eventEmvcoMultiCardIntent = new Intent();
5033 eventEmvcoMultiCardIntent.setAction(ACTION_EMVCO_MULTIPLE_CARD_DETECTED);
5034 if (DBG) {
5035 Log.d(TAG, "Broadcasting Intent");
5036 }
5037 mContext.sendBroadcast(eventEmvcoMultiCardIntent, NFC_PERM);
5038 break;
5039
5040 case MSG_SE_EMV_CARD_REMOVAL:
5041 if (DBG) Log.d(TAG, "Card Removal message");
5042 /* Send broadcast */
5043 Intent cardRemovalIntent = new Intent();
5044 cardRemovalIntent.setAction(ACTION_EMV_CARD_REMOVAL);
5045 if (DBG) Log.d(TAG, "Broadcasting " + ACTION_EMV_CARD_REMOVAL);
5046 sendSeBroadcast(cardRemovalIntent);
5047 break;
5048
5049 case MSG_SE_APDU_RECEIVED:
5050 if (DBG) Log.d(TAG, "APDU Received message");
5051 byte[] apduBytes = (byte[]) msg.obj;
5052 /* Send broadcast */
5053 Intent apduReceivedIntent = new Intent();
5054 apduReceivedIntent.setAction(ACTION_APDU_RECEIVED);
5055 if (apduBytes != null && apduBytes.length > 0) {
5056 apduReceivedIntent.putExtra(EXTRA_APDU_BYTES, apduBytes);
5057 }
5058 if (DBG) Log.d(TAG, "Broadcasting " + ACTION_APDU_RECEIVED);
5059 sendSeBroadcast(apduReceivedIntent);
5060 break;
5061
5062 case MSG_SE_MIFARE_ACCESS:
5063 if (DBG) Log.d(TAG, "MIFARE access message");
5064 /* Send broadcast */
5065 byte[] mifareCmd = (byte[]) msg.obj;
5066 Intent mifareAccessIntent = new Intent();
5067 mifareAccessIntent.setAction(ACTION_MIFARE_ACCESS_DETECTED);
5068 if (mifareCmd != null && mifareCmd.length > 1) {
5069 int mifareBlock = mifareCmd[1] & 0xff;
5070 if (DBG) Log.d(TAG, "Mifare Block=" + mifareBlock);
5071 mifareAccessIntent.putExtra(EXTRA_MIFARE_BLOCK, mifareBlock);
5072 }
5073 if (DBG) Log.d(TAG, "Broadcasting " + ACTION_MIFARE_ACCESS_DETECTED);
5074 sendSeBroadcast(mifareAccessIntent);
5075 break;
5076
5077 case MSG_LLCP_LINK_ACTIVATION:
5078 if (mIsDebugBuild) {
5079 Intent actIntent = new Intent(ACTION_LLCP_UP);
5080 mContext.sendBroadcast(actIntent);
5081 }
5082 llcpActivated((NfcDepEndpoint) msg.obj);
5083 break;
5084
5085 case MSG_LLCP_LINK_DEACTIVATED:
5086 if (mIsDebugBuild) {
5087 Intent deactIntent = new Intent(ACTION_LLCP_DOWN);
5088 mContext.sendBroadcast(deactIntent);
5089 }
5090 NfcDepEndpoint device = (NfcDepEndpoint) msg.obj;
5091 boolean needsDisconnect = false;
5092
5093 Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
5094 synchronized (NfcService.this) {
5095 /* Check if the device has been already unregistered */
5096 if (mObjectMap.remove(device.getHandle()) != null) {
5097 /* Disconnect if we are initiator */
5098 if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
5099 if (DBG) Log.d(TAG, "disconnecting from target");
5100 needsDisconnect = true;
5101 } else {
5102 if (DBG) Log.d(TAG, "not disconnecting from initiator");
5103 }
5104 }
5105 }
5106 if (needsDisconnect) {
5107 device.disconnect(); // restarts polling loop
5108 }
5109
5110 mP2pLinkManager.onLlcpDeactivated();
5111 break;
5112 case MSG_LLCP_LINK_FIRST_PACKET:
5113 mP2pLinkManager.onLlcpFirstPacketReceived();
5114 break;
5115 case MSG_TARGET_DESELECTED:
5116 /* Broadcast Intent Target Deselected */
5117 if (DBG) Log.d(TAG, "Target Deselected");
5118 Intent intent = new Intent();
5119 intent.setAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
5120 if (DBG) Log.d(TAG, "Broadcasting Intent");
5121 mContext.sendOrderedBroadcast(intent, NfcPermissions.NFC_PERMISSION);
5122 break;
5123
5124 case MSG_SE_FIELD_ACTIVATED: {
5125 if (DBG) Log.d(TAG, "SE FIELD ACTIVATED");
5126 Intent eventFieldOnIntent = new Intent();
5127 eventFieldOnIntent.setAction(ACTION_RF_FIELD_ON_DETECTED);
5128 sendSeBroadcast(eventFieldOnIntent);
5129 break;
5130 }
5131 case MSG_RESUME_POLLING:
5132 mNfcAdapter.resumePolling();
5133 break;
5134
5135 case MSG_SE_FIELD_DEACTIVATED: {
5136 if (DBG) Log.d(TAG, "SE FIELD DEACTIVATED");
5137 Intent eventFieldOffIntent = new Intent();
5138 eventFieldOffIntent.setAction(ACTION_RF_FIELD_OFF_DETECTED);
5139 sendSeBroadcast(eventFieldOffIntent);
5140 break;
5141 }
5142
5143 case MSG_SE_LISTEN_ACTIVATED: {
5144 if (DBG) Log.d(TAG, "SE LISTEN MODE ACTIVATED");
5145 Intent listenModeActivated = new Intent();
5146 listenModeActivated.setAction(ACTION_SE_LISTEN_ACTIVATED);
5147 sendSeBroadcast(listenModeActivated);
5148 break;
5149 }
5150
5151 case MSG_SE_LISTEN_DEACTIVATED: {
5152 if (DBG) Log.d(TAG, "SE LISTEN MODE DEACTIVATED");
5153 Intent listenModeDeactivated = new Intent();
5154 listenModeDeactivated.setAction(ACTION_SE_LISTEN_DEACTIVATED);
5155 sendSeBroadcast(listenModeDeactivated);
5156 break;
5157 }
5158
5159 case MSG_SWP_READER_REQUESTED:
5160
5161 /* Send broadcast ordered */
nxpandroid281eb922016-08-25 20:27:46 +05305162 Intent swpReaderRequestedIntent = new Intent();
nxpandroid64fd68c2015-09-23 16:45:15 +05305163 ArrayList<Integer> techList = (ArrayList<Integer>) msg.obj;
nxpandroid281eb922016-08-25 20:27:46 +05305164 Integer[] techs = techList.toArray(new Integer[techList.size()]);
5165 swpReaderRequestedIntent
nxpandroid64fd68c2015-09-23 16:45:15 +05305166 .setAction(NxpConstants.ACTION_SWP_READER_REQUESTED);
5167 if (DBG) {
5168 Log.d(TAG, "SWP READER - Requested");
5169 }
nxpandroid281eb922016-08-25 20:27:46 +05305170 mContext.sendBroadcast(swpReaderRequestedIntent);
nxpandroid64fd68c2015-09-23 16:45:15 +05305171 break;
5172
5173 case MSG_SWP_READER_REQUESTED_FAIL:
5174
5175 /* Send broadcast ordered */
nxpandroid281eb922016-08-25 20:27:46 +05305176 Intent swpReaderRequestedFailIntent = new Intent();
nxpandroid64fd68c2015-09-23 16:45:15 +05305177
nxpandroid281eb922016-08-25 20:27:46 +05305178 swpReaderRequestedFailIntent
nxpandroid64fd68c2015-09-23 16:45:15 +05305179 .setAction(NxpConstants.ACTION_SWP_READER_REQUESTED_FAILED);
5180 if (DBG) {
5181 Log.d(TAG, "SWP READER - Requested Fail");
5182 }
nxpandroid281eb922016-08-25 20:27:46 +05305183 mContext.sendBroadcast(swpReaderRequestedFailIntent);
nxpandroid64fd68c2015-09-23 16:45:15 +05305184 break;
5185
5186 case MSG_SWP_READER_ACTIVATED:
5187
5188 /* Send broadcast ordered */
nxpandroid281eb922016-08-25 20:27:46 +05305189 Intent swpReaderActivatedIntent = new Intent();
nxpandroid64fd68c2015-09-23 16:45:15 +05305190
nxpandroid281eb922016-08-25 20:27:46 +05305191 swpReaderActivatedIntent
nxpandroid64fd68c2015-09-23 16:45:15 +05305192 .setAction(NxpConstants.ACTION_SWP_READER_ACTIVATED);
5193 if (DBG) {
5194 Log.d(TAG, "SWP READER - Activated");
5195 }
nxpandroid281eb922016-08-25 20:27:46 +05305196 mContext.sendBroadcast(swpReaderActivatedIntent);
nxpandroid64fd68c2015-09-23 16:45:15 +05305197 break;
5198
5199 case MSG_ETSI_START_CONFIG:
5200 {
5201 Log.d(TAG, "NfcServiceHandler - MSG_ETSI_START_CONFIG");
5202 ArrayList<Integer> configList = (ArrayList<Integer>) msg.obj;
5203 int eeHandle;
5204 if(configList.contains(0x402))
5205 {
5206 eeHandle = 0x402;
5207 }
5208 else{
5209 eeHandle = 0x4C0;
5210 }
5211 etsiStartConfig(eeHandle);
5212 }
5213 break;
5214
5215 case MSG_ETSI_STOP_CONFIG:
5216
5217 Log.d(TAG, "NfcServiceHandler - MSG_ETSI_STOP_CONFIG");
5218
5219 etsiStopConfig((int)msg.obj);
5220 break;
5221
5222 case MSG_ETSI_SWP_TIMEOUT:
5223
5224 Log.d(TAG, "NfcServiceHandler - MSG_ETSI_SWP_TIMEOUT");
5225
5226 mDeviceHost.setEtsiReaederState(STATE_SE_RDR_MODE_STOP_CONFIG);
5227 etsiStopConfig((int)msg.obj);
5228
5229 break;
nxpandroide66eb092017-07-12 21:36:08 +05305230 case MSG_APPLY_SCREEN_STATE:
nxpandroid64fd68c2015-09-23 16:45:15 +05305231
5232 mScreenState = (int)msg.obj;
nxpandroide66eb092017-07-12 21:36:08 +05305233
5234 if(mScreenState == ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED)
5235 {
5236 applyRouting(false);
5237 }
5238 int screen_state_mask = (mNfcUnlockManager.isLockscreenPollingEnabled()) ?
5239 (ScreenStateHelper.SCREEN_POLLING_TAG_MASK | mScreenState) : mScreenState;
5240
5241 if(mNfcUnlockManager.isLockscreenPollingEnabled())
5242 applyRouting(false);
5243 mDeviceHost.doSetScreenOrPowerState(screen_state_mask);
5244
5245/* mRoutingWakeLock.acquire();
nxpandroid64fd68c2015-09-23 16:45:15 +05305246 try {
5247 Log.e(TAG, "applyRouting -20");
5248 applyRouting(false);
5249 } finally {
5250 mRoutingWakeLock.release();
nxpandroide66eb092017-07-12 21:36:08 +05305251 }*/
nxpandroid64fd68c2015-09-23 16:45:15 +05305252 break;
nxpandroid281eb922016-08-25 20:27:46 +05305253 case MSG_TAG_DEBOUNCE:
5254 // Didn't see the tag again, tag is gone
5255 ITagRemovedCallback tagRemovedCallback;
5256 synchronized (NfcService.this) {
5257 mDebounceTagUid = null;
5258 tagRemovedCallback = mDebounceTagRemovedCallback;
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305259 mDebounceTagRemovedCallback = null;
nxpandroid281eb922016-08-25 20:27:46 +05305260 }
5261 if (tagRemovedCallback != null) {
5262 try {
5263 tagRemovedCallback.onTagRemoved();
5264 } catch (RemoteException e) {
5265 // Ignore
5266 }
5267 }
5268 break;
nxpandroid5d64ce92016-11-18 19:48:53 +05305269 case MSG_RESTART_WATCHDOG:
5270 int enable = msg.arg1;
5271 disableInternalwatchDog.cancel();
5272 try{
5273 disableInternalwatchDog.join();
5274 } catch (java.lang.InterruptedException e) {
5275 }
5276 disableInternalwatchDog = new WatchDogThread("disableInternal", ROUTING_WATCHDOG_MS);
5277 Log.d(TAG, "New Watchdog: WatchDog Thread ID is "+ disableInternalwatchDog.getId());
5278 disableInternalwatchDog.start();
5279 break;
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305280 case MSG_UPDATE_STATS:
5281 if (mNumTagsDetected.get() > 0) {
5282 MetricsLogger.count(mContext, TRON_NFC_TAG, mNumTagsDetected.get());
5283 mNumTagsDetected.set(0);
5284 }
5285 if (mNumHceDetected.get() > 0) {
5286 MetricsLogger.count(mContext, TRON_NFC_CE, mNumHceDetected.get());
5287 mNumHceDetected.set(0);
5288 }
5289 if (mNumP2pDetected.get() > 0) {
5290 MetricsLogger.count(mContext, TRON_NFC_P2P, mNumP2pDetected.get());
5291 mNumP2pDetected.set(0);
5292 }
5293 removeMessages(MSG_UPDATE_STATS);
5294 sendEmptyMessageDelayed(MSG_UPDATE_STATS, STATS_UPDATE_INTERVAL_MS);
5295 break;
nxpandroida5fd6622017-07-31 16:15:18 +05305296
5297 case MSG_ROUTE_APDU:{
5298 int route = msg.arg1;
5299 int power = msg.arg2;
5300 String apduData = null;
5301 String apduMask = null;
5302 Bundle dataBundle = msg.getData();
5303 if (dataBundle != null) {
5304 apduData = dataBundle.getString("apduData");
5305 apduMask = dataBundle.getString("apduMask");
5306 }
5307 // Send the APDU
5308 if(apduData != null && dataBundle != null)
5309 mDeviceHost.routeApduPattern(route, power, hexStringToBytes(apduData) ,hexStringToBytes(apduMask));
5310 break;
5311 }
5312 case MSG_UNROUTE_APDU: {
5313 String apdu = (String) msg.obj;
5314 mDeviceHost.unrouteApduPattern(hexStringToBytes(apdu));
5315 break;
5316 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305317 default:
5318 Log.e(TAG, "Unknown message received");
5319 break;
5320 }
5321 }
5322
5323 private void sendSeBroadcast(Intent intent) {
5324 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
5325 // Resume app switches so the receivers can start activites without delay
5326 mNfcDispatcher.resumeAppSwitches();
5327 ArrayList<String> matchingPackages = new ArrayList<String>();
5328 ArrayList<String> preferredPackages = new ArrayList<String>();
nxpandroida51b5bd2017-04-10 18:28:21 +05305329 Log.d(TAG, "NFCINTENT sendNfcEeAccessProtectedBroadcast");
nxpandroid64fd68c2015-09-23 16:45:15 +05305330 if(mInstalledPackages == null) {
5331 Log.d(TAG, "No packages to send broadcast.");
5332 return;
5333 }
5334 synchronized(this) {
5335 for (PackageInfo pkg : mInstalledPackages) {
5336 if (pkg != null && pkg.applicationInfo != null) {
nxpandroida51b5bd2017-04-10 18:28:21 +05305337 if (pkg.packageName.equals(PACKAGE_SMART_CARD_SERVICE)) {
5338 preferredPackages.add(pkg.packageName);
5339 Log.d(TAG, "NFCINTENT PACKAGE ADDED");
5340 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305341 if (mNfceeAccessControl.check(pkg.applicationInfo)) {
5342 matchingPackages.add(pkg.packageName);
5343 if (mCardEmulationManager != null &&
5344 mCardEmulationManager.packageHasPreferredService(pkg.packageName)) {
5345 preferredPackages.add(pkg.packageName);
5346 }
5347 }
5348 }
5349 }
5350 if (preferredPackages.size() > 0) {
5351 // If there's any packages in here which are preferred, only
5352 // send field events to those packages, to prevent other apps
5353 // with signatures in nfcee_access.xml from acting upon the events.
5354 for (String packageName : preferredPackages){
5355 intent.setPackage(packageName);
nxpandroida51b5bd2017-04-10 18:28:21 +05305356 Log.d(TAG, "NFCINTENT SENT TO PACKAGE" + packageName);
nxpandroid64fd68c2015-09-23 16:45:15 +05305357 mContext.sendBroadcast(intent);
5358 }
5359 } else {
5360 for (String packageName : matchingPackages){
5361 intent.setPackage(packageName);
5362 mContext.sendBroadcast(intent);
5363 }
5364 }
5365 }
5366 }
5367
5368 private void sendMultiEvtBroadcast(Intent intent) {
5369
5370 ArrayList<String> packageList = mNxpNfcController.getEnabledMultiEvtsPackageList();
nxpandroida9a68ba2016-01-14 21:12:17 +05305371 ComponentName unicastComponent = null;
nxpandroid64fd68c2015-09-23 16:45:15 +05305372 if(packageList.size() == 0) {
5373 Log.d(TAG, "No packages to send broadcast.");
nxpandroida9a68ba2016-01-14 21:12:17 +05305374 unicastComponent = mNxpNfcController.getUnicastPackage();
5375 if(unicastComponent != null)
5376 {
5377 intent.setComponent(unicastComponent);
5378 try {
5379 //start gsma
5380 Log.d(TAG, "Starting activity uincast Pkg"+unicastComponent.flattenToString());
5381 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
5382 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5383 if(mContext.getPackageManager().resolveActivity(intent, 0) != null)
5384 {
nxpandroid5d64ce92016-11-18 19:48:53 +05305385 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
nxpandroida9a68ba2016-01-14 21:12:17 +05305386 } else {
5387 Log.d(TAG, "Intent not resolved");
5388 }
5389 } catch (Exception e) {
5390 if (DBG) Log.d(TAG, "Exception: " + e.getMessage());
5391 }
5392 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305393 return;
5394 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305395 for(int i=0; i<packageList.size(); i++) {
5396 Log.d(TAG,"MultiEvt Enabled Application packageName: " + packageList.get(i));
5397 intent.setPackage(packageList.get(i));
nxpandroid5d64ce92016-11-18 19:48:53 +05305398 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT,
5399 NxpConstants.PERMISSIONS_TRANSACTION_EVENT);
nxpandroid64fd68c2015-09-23 16:45:15 +05305400 }
5401 }
5402
5403 private boolean llcpActivated(NfcDepEndpoint device) {
5404 Log.d(TAG, "LLCP Activation message");
5405
5406 if (device.getMode() == NfcDepEndpoint.MODE_P2P_TARGET) {
5407 if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
5408 if (device.connect()) {
5409 /* Check LLCP compliance */
5410 if (mDeviceHost.doCheckLlcp()) {
5411 /* Activate LLCP Link */
5412 if (mDeviceHost.doActivateLlcp()) {
5413 if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
5414 synchronized (NfcService.this) {
5415 // Register P2P device
5416 mObjectMap.put(device.getHandle(), device);
5417 }
nxpandroid1153eb32015-11-06 18:46:58 +05305418 mP2pLinkManager.onLlcpActivated(device.getLlcpVersion());
nxpandroid64fd68c2015-09-23 16:45:15 +05305419 return true;
5420 } else {
5421 /* should not happen */
5422 Log.w(TAG, "Initiator LLCP activation failed. Disconnect.");
5423 device.disconnect();
5424 }
5425 } else {
5426 if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
5427 device.disconnect();
5428 }
5429 } else {
5430 if (DBG) Log.d(TAG, "Cannot connect remote Target. Polling loop restarted.");
5431 /*
5432 * The polling loop should have been restarted in failing
5433 * doConnect
5434 */
5435 }
5436 } else if (device.getMode() == NfcDepEndpoint.MODE_P2P_INITIATOR) {
5437 if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
5438 /* Check LLCP compliancy */
5439 if (mDeviceHost.doCheckLlcp()) {
5440 /* Activate LLCP Link */
5441 if (mDeviceHost.doActivateLlcp()) {
5442 if (DBG) Log.d(TAG, "Target Activate LLCP OK");
5443 synchronized (NfcService.this) {
5444 // Register P2P device
5445 mObjectMap.put(device.getHandle(), device);
5446 }
nxpandroid1153eb32015-11-06 18:46:58 +05305447 mP2pLinkManager.onLlcpActivated(device.getLlcpVersion());
nxpandroid64fd68c2015-09-23 16:45:15 +05305448 return true;
5449 }
5450 } else {
5451 Log.w(TAG, "checkLlcp failed");
5452 }
5453 }
5454
5455 return false;
5456 }
5457
5458 private void dispatchTagEndpoint(TagEndpoint tagEndpoint, ReaderModeParams readerParams) {
5459 Tag tag = new Tag(tagEndpoint.getUid(), tagEndpoint.getTechList(),
5460 tagEndpoint.getTechExtras(), tagEndpoint.getHandle(), mNfcTagService);
5461 registerTagObject(tagEndpoint);
5462 if (readerParams != null) {
5463 try {
5464 if ((readerParams.flags & NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS) == 0) {
5465 playSound(SOUND_END);
5466 }
5467 if (readerParams.callback != null) {
5468 readerParams.callback.onTagDiscovered(tag);
5469 return;
5470 } else {
5471 // Follow normal dispatch below
5472 }
5473 } catch (RemoteException e) {
5474 Log.e(TAG, "Reader mode remote has died, falling back.", e);
5475 // Intentional fall-through
5476 } catch (Exception e) {
5477 // Catch any other exception
5478 Log.e(TAG, "App exception, not dispatching.", e);
5479 return;
5480 }
5481 }
5482 int dispatchResult = mNfcDispatcher.dispatchTag(tag);
5483 if (dispatchResult == NfcDispatcher.DISPATCH_FAIL) {
5484 unregisterObject(tagEndpoint.getHandle());
5485 playSound(SOUND_ERROR);
5486 } else if (dispatchResult == NfcDispatcher.DISPATCH_SUCCESS) {
5487 playSound(SOUND_END);
5488 }
5489 }
5490 }
5491
5492 private NfcServiceHandler mHandler = new NfcServiceHandler();
5493
5494 class ApplyRoutingTask extends AsyncTask<Integer, Void, Void> {
5495 @Override
5496 protected Void doInBackground(Integer... params) {
5497 synchronized (NfcService.this) {
5498 if (params == null || params.length != 1) {
5499 // force apply current routing
5500 Log.e(TAG, "applyRouting -1");
5501 applyRouting(true);
5502 return null;
5503 }
5504 mScreenState = params[0].intValue();
nxpandroid64fd68c2015-09-23 16:45:15 +05305505 mRoutingWakeLock.acquire();
5506 try {
5507 Log.e(TAG, "applyRouting -2");
5508 applyRouting(false);
5509 } finally {
5510 mRoutingWakeLock.release();
5511 }
5512 return null;
5513 }
5514 }
5515 }
5516
5517 class TagRemoveTask extends AsyncTask<Integer, Void, Void> {
5518 @Override
5519 protected Void doInBackground(Integer... params) {
5520
nxpandroid5d64ce92016-11-18 19:48:53 +05305521 Intent swpReaderTagRemoveIntent = new Intent();
nxpandroid64fd68c2015-09-23 16:45:15 +05305522
nxpandroid5d64ce92016-11-18 19:48:53 +05305523 swpReaderTagRemoveIntent.setAction(NxpConstants.ACTION_SWP_READER_TAG_REMOVE);
nxpandroid64fd68c2015-09-23 16:45:15 +05305524
5525 int counter = 0;
5526 int discNtfTimeout = params[0].intValue();
5527
5528 while(ETSI_STOP_CONFIG == true)
5529 { /* Send broadcast ordered */
5530
5531 if(discNtfTimeout == 0)
5532 {
5533 /*Do nothing*/
5534 }
5535 else if(counter < discNtfTimeout)
5536 {
5537 counter++;
5538 }
5539 else
5540 {
5541 ETSI_STOP_CONFIG = false;
5542 break;
5543 }
5544 if (DBG) {
5545 Log.d(TAG, "SWP READER - Tag Remove");
5546 }
nxpandroid5d64ce92016-11-18 19:48:53 +05305547 mContext.sendBroadcast(swpReaderTagRemoveIntent);
nxpandroid64fd68c2015-09-23 16:45:15 +05305548 try{
5549 Thread.sleep(1000);
5550 } catch(Exception e) {
5551 e.printStackTrace();
5552 }
5553 }
5554 return null;
5555 }
5556 }
5557
5558
5559 private final BroadcastReceiver x509CertificateReceiver = new BroadcastReceiver() {
5560 @Override
5561 public void onReceive(Context context, Intent intent) {
5562 boolean result = intent.getBooleanExtra(NxpConstants.EXTRA_RESULT, false);
5563 mNxpNfcController.setResultForCertificates(result);
5564 }
5565 };
5566
5567 private final BroadcastReceiver mEnableNfc = new BroadcastReceiver() {
5568 @Override
5569 public void onReceive(Context context, Intent intent) {
5570 String action = intent.getAction();
5571 Intent nfcDialogIntent = new Intent(mContext, EnableNfcDialogActivity.class);
5572 nfcDialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
5573 mContext.startActivityAsUser(nfcDialogIntent, UserHandle.CURRENT);
5574 }
5575 };
5576
5577 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
5578 @Override
5579 public void onReceive(Context context, Intent intent) {
5580 String action = intent.getAction();
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305581 Log.e(TAG, "screen state "+action);
nxpandroid64fd68c2015-09-23 16:45:15 +05305582 if (action.equals(
5583 NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
5584 // Perform applyRouting() in AsyncTask to serialize blocking calls
5585 new ApplyRoutingTask().execute();
5586 } else if ((action.equals(Intent.ACTION_SCREEN_ON)
5587 || action.equals(Intent.ACTION_SCREEN_OFF)
5588 || action.equals(Intent.ACTION_USER_PRESENT)) &&
5589 mState == NfcAdapter.STATE_ON) {
5590 // Perform applyRouting() in AsyncTask to serialize blocking calls
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305591 int screenState = mScreenStateHelper.checkScreenState();
nxpandroid64fd68c2015-09-23 16:45:15 +05305592 if (action.equals(Intent.ACTION_SCREEN_OFF)) {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305593 if(mScreenState != ScreenStateHelper.SCREEN_STATE_OFF_LOCKED)
nxpandroid64fd68c2015-09-23 16:45:15 +05305594 {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305595 Log.e(TAG, "screen state OFF required");
5596 screenState = mKeyguard.isKeyguardLocked() ?
5597 ScreenStateHelper.SCREEN_STATE_OFF_LOCKED :
5598 ScreenStateHelper.SCREEN_STATE_OFF_UNLOCKED;
nxpandroid64fd68c2015-09-23 16:45:15 +05305599 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305600 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
5601 screenState = mKeyguard.isKeyguardLocked() ?
5602 ScreenStateHelper.SCREEN_STATE_ON_LOCKED : ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED;
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305603 Log.e(TAG, "screen state on");
5604 /*
nxpandroid64fd68c2015-09-23 16:45:15 +05305605 if(screenState == ScreenStateHelper.SCREEN_STATE_ON_LOCKED && mScreenState == ScreenStateHelper.SCREEN_STATE_OFF) {
nxpandroid64fd68c2015-09-23 16:45:15 +05305606 } else if (screenState == ScreenStateHelper.SCREEN_STATE_ON_LOCKED && mScreenState == ScreenStateHelper.SCREEN_STATE_ON_LOCKED) {
5607 return;
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305608 }*/
nxpandroid64fd68c2015-09-23 16:45:15 +05305609 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
5610 if (mScreenState != ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED) {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305611 Log.e(TAG, "screen state user present");
nxpandroid64fd68c2015-09-23 16:45:15 +05305612 screenState = ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED;
nxpandroid64fd68c2015-09-23 16:45:15 +05305613 } else {
5614 return;
5615 }
5616 }
nxpandroide66eb092017-07-12 21:36:08 +05305617 if(nci_version != NCI_VERSION_2_0) {
5618 new ApplyRoutingTask().execute(Integer.valueOf(screenState));
5619 }
5620 sendMessage(NfcService.MSG_APPLY_SCREEN_STATE, screenState);
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305621 Log.e(TAG, "screen state "+screenState);
5622 Log.e(TAG, "screen state mScreenState "+mScreenState);
nxpandroid64fd68c2015-09-23 16:45:15 +05305623 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
nxpandroid6fd9cdb2017-07-12 18:25:41 +05305624 int screenState = mScreenStateHelper.checkScreenState();
nxpandroid64fd68c2015-09-23 16:45:15 +05305625 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
5626 synchronized (this) {
5627 mUserId = userId;
5628 }
5629 mP2pLinkManager.onUserSwitched(getUserId());
5630 if (mIsHceCapable) {
5631 mCardEmulationManager.onUserSwitched(getUserId());
5632 }
nxpandroide66eb092017-07-12 21:36:08 +05305633 screenState = mScreenStateHelper.checkScreenState();
nxpandroid64fd68c2015-09-23 16:45:15 +05305634 new ApplyRoutingTask().execute(Integer.valueOf(screenState));
nxpandroid64fd68c2015-09-23 16:45:15 +05305635 }
5636 }
5637 };
5638
5639 private final BroadcastReceiver mOwnerReceiver = new BroadcastReceiver() {
5640 @Override
5641 public void onReceive(Context context, Intent intent) {
5642 String action = intent.getAction();
5643 if (action.equals(Intent.ACTION_PACKAGE_REMOVED) ||
5644 action.equals(Intent.ACTION_PACKAGE_ADDED) ||
5645 action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE) ||
5646 action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
5647 updatePackageCache();
5648
5649 if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
5650 // Clear the NFCEE access cache in case a UID gets recycled
5651 mNfceeAccessControl.invalidateCache();
5652 }
nxpandroid5d64ce92016-11-18 19:48:53 +05305653 } else if(action.equals(Intent.ACTION_SHUTDOWN)) {
5654 mPowerShutDown = true;
5655 if (DBG) Log.d(TAG,"Device is shutting down.");
5656 mDeviceHost.doSetScreenOrPowerState(ScreenStateHelper.POWER_STATE_OFF);
nxpandroid64fd68c2015-09-23 16:45:15 +05305657 }
5658 }
5659 };
5660
5661 final BroadcastReceiver mAlaReceiver = new BroadcastReceiver() {
5662 @Override
5663 public void onReceive(Context context, Intent intent) {
5664 String action = intent.getAction();
5665 if (NfcAdapter.ACTION_ADAPTER_STATE_CHANGED.equals(intent.getAction())) {
5666 int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
5667 NfcAdapter.STATE_OFF);
5668 if (state == NfcAdapter.STATE_ON) {
5669 Log.e(TAG, "Loader service update start from NFC_ON Broadcast");
5670 NfcAlaService nas = new NfcAlaService();
nxpandroid5d3fdf82017-07-31 16:11:33 +05305671 int lsVersion = mNfcAla.doGetLSConfigVersion();
5672
5673 if(lsVersion >= LOADER_SERVICE_VERSION_LOW_LIMIT &&
5674 lsVersion <= LOADER_SERVICE_VERSION_HIGH_LIMIT)
nxpandroid64fd68c2015-09-23 16:45:15 +05305675 nas.updateLoaderService();
5676 }
5677 }
5678 }
5679 };
5680
5681 private final BroadcastReceiver mPolicyReceiver = new BroadcastReceiver() {
5682 @Override
5683 public void onReceive(Context context, Intent intent){
5684 String action = intent.getAction();
5685 if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
5686 .equals(action)) {
5687 enforceBeamShareActivityPolicy(context,
5688 new UserHandle(getSendingUserId()), mIsNdefPushEnabled);
5689 }
5690 }
5691 };
5692
5693 /**
nxpandroid64fd68c2015-09-23 16:45:15 +05305694 * for debugging only - no i18n
5695 */
5696 static String stateToString(int state) {
5697 switch (state) {
5698 case NfcAdapter.STATE_OFF:
5699 return "off";
5700 case NfcAdapter.STATE_TURNING_ON:
5701 return "turning on";
5702 case NfcAdapter.STATE_ON:
5703 return "on";
5704 case NfcAdapter.STATE_TURNING_OFF:
5705 return "turning off";
5706 default:
5707 return "<error>";
5708 }
5709 }
5710
5711 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5712 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5713 != PackageManager.PERMISSION_GRANTED) {
5714 pw.println("Permission Denial: can't dump nfc from from pid="
5715 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
5716 + " without permission " + android.Manifest.permission.DUMP);
5717 return;
5718 }
5719
5720 synchronized (this) {
5721 pw.println("mState=" + stateToString(mState));
5722 pw.println("mIsZeroClickRequested=" + mIsNdefPushEnabled);
5723 pw.println("mScreenState=" + ScreenStateHelper.screenStateToString(mScreenState));
5724 pw.println("mNfcPollingEnabled=" + mNfcPollingEnabled);
5725 pw.println("mNfceeRouteEnabled=" + mNfceeRouteEnabled);
5726 pw.println("mOpenEe=" + mOpenEe);
nxpandroid64fd68c2015-09-23 16:45:15 +05305727 pw.println("mLockscreenPollMask=" + mLockscreenPollMask);
5728 pw.println(mCurrentDiscoveryParameters);
5729 mP2pLinkManager.dump(fd, pw, args);
5730 if (mIsHceCapable) {
5731 mCardEmulationManager.dump(fd, pw, args);
5732 }
5733 mNfceeAccessControl.dump(fd, pw, args);
5734 mNfcDispatcher.dump(fd, pw, args);
5735 pw.println(mDeviceHost.dump());
5736
5737 }
5738 }
nxpandroid34627bd2016-05-27 15:52:30 +05305739 /**
5740 * Update the status of all the services which were populated to commit to routing table
5741 */
5742 public void updateStatusOfServices(boolean commitStatus) {
nxpandroidebf53fb2016-12-22 18:48:59 +05305743 if(commitStatus == true)
5744 {
5745 mAidCache.setPreviousPreferredPaymentService(null);
5746 }
nxpandroid34627bd2016-05-27 15:52:30 +05305747 mCardEmulationManager.updateStatusOfServices(commitStatus);
5748 }
nxpandroid64fd68c2015-09-23 16:45:15 +05305749}