1 /*
2 * Copyright (C) 2012 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 * Communicate with secure elements that are attached to the NFC
19 * controller.
20 */
21 #include <semaphore.h>
22 #include <errno.h>
23 #include "OverrideLog.h"
24 #include "SecureElement.h"
25 #include "config.h"
26 #include "PowerSwitch.h"
27 #include "HostAidRouter.h"
28 #include "JavaClassConstants.h"
29
30
31 /*****************************************************************************
32 **
33 ** public variables
34 **
35 *****************************************************************************/
36 int gSEId = -1; // secure element ID to use in connectEE(), -1 means not set
37 int gGatePipe = -1; // gate id or static pipe id to use in connectEE(), -1 means not set
38 bool gUseStaticPipe = false; // if true, use gGatePipe as static pipe id. if false, use as gate id
39
40 namespace android
41 {
42 extern void startRfDiscovery (bool isStart);
43 }
44
45 //////////////////////////////////////////////
46 //////////////////////////////////////////////
47
48
49 SecureElement SecureElement::sSecElem;
50 const char* SecureElement::APP_NAME = "nfc_jni";
51
52
53 /*******************************************************************************
54 **
55 ** Function: SecureElement
56 **
57 ** Description: Initialize member variables.
58 **
59 ** Returns: None
60 **
61 *******************************************************************************/
SecureElement()62 SecureElement::SecureElement ()
63 : mActiveEeHandle (NFA_HANDLE_INVALID),
64 mDestinationGate (4), //loopback gate
65 mNfaHciHandle (NFA_HANDLE_INVALID),
66 mNativeData (NULL),
67 mIsInit (false),
68 mActualNumEe (0),
69 mNumEePresent(0),
70 mbNewEE (true), // by default we start w/thinking there are new EE
71 mNewPipeId (0),
72 mNewSourceGate (0),
73 mActiveSeOverride(0),
74 mCommandStatus (NFA_STATUS_OK),
75 mIsPiping (false),
76 mCurrentRouteSelection (NoRoute),
77 mActualResponseSize(0),
78 mUseOberthurWarmReset (false),
79 mActivatedInListenMode (false),
80 mOberthurWarmResetCommand (3),
81 mRfFieldIsOn(false)
82 {
83 memset (&mEeInfo, 0, sizeof(mEeInfo));
84 memset (&mUiccInfo, 0, sizeof(mUiccInfo));
85 memset (&mHciCfg, 0, sizeof(mHciCfg));
86 memset (mResponseData, 0, sizeof(mResponseData));
87 memset (mAidForEmptySelect, 0, sizeof(mAidForEmptySelect));
88 memset (&mLastRfFieldToggle, 0, sizeof(mLastRfFieldToggle));
89 }
90
91
92 /*******************************************************************************
93 **
94 ** Function: ~SecureElement
95 **
96 ** Description: Release all resources.
97 **
98 ** Returns: None
99 **
100 *******************************************************************************/
~SecureElement()101 SecureElement::~SecureElement ()
102 {
103 }
104
105
106 /*******************************************************************************
107 **
108 ** Function: getInstance
109 **
110 ** Description: Get the SecureElement singleton object.
111 **
112 ** Returns: SecureElement object.
113 **
114 *******************************************************************************/
getInstance()115 SecureElement& SecureElement::getInstance()
116 {
117 return sSecElem;
118 }
119
120
121 /*******************************************************************************
122 **
123 ** Function: setActiveSeOverride
124 **
125 ** Description: Specify which secure element to turn on.
126 ** activeSeOverride: ID of secure element
127 **
128 ** Returns: None
129 **
130 *******************************************************************************/
setActiveSeOverride(UINT8 activeSeOverride)131 void SecureElement::setActiveSeOverride(UINT8 activeSeOverride)
132 {
133 ALOGD ("SecureElement::setActiveSeOverride, seid=0x%X", activeSeOverride);
134 mActiveSeOverride = activeSeOverride;
135 }
136
137
138 /*******************************************************************************
139 **
140 ** Function: initialize
141 **
142 ** Description: Initialize all member variables.
143 ** native: Native data.
144 **
145 ** Returns: True if ok.
146 **
147 *******************************************************************************/
initialize(nfc_jni_native_data * native)148 bool SecureElement::initialize (nfc_jni_native_data* native)
149 {
150 static const char fn [] = "SecureElement::initialize";
151 tNFA_STATUS nfaStat;
152 UINT8 xx = 0, yy = 0;
153 unsigned long num = 0;
154
155 ALOGD ("%s: enter", fn);
156
157 if (GetNumValue("NFA_HCI_DEFAULT_DEST_GATE", &num, sizeof(num)))
158 mDestinationGate = num;
159 ALOGD ("%s: Default destination gate: 0x%X", fn, mDestinationGate);
160
161 // active SE, if not set active all SEs
162 if (GetNumValue("ACTIVE_SE", &num, sizeof(num)))
163 mActiveSeOverride = num;
164 ALOGD ("%s: Active SE override: 0x%X", fn, mActiveSeOverride);
165
166 if (GetNumValue("OBERTHUR_WARM_RESET_COMMAND", &num, sizeof(num)))
167 {
168 mUseOberthurWarmReset = true;
169 mOberthurWarmResetCommand = (UINT8) num;
170 }
171
172 mActiveEeHandle = NFA_HANDLE_INVALID;
173 mNfaHciHandle = NFA_HANDLE_INVALID;
174
175 mNativeData = native;
176 mActualNumEe = MAX_NUM_EE;
177 mbNewEE = true;
178 mNewPipeId = 0;
179 mNewSourceGate = 0;
180 mCurrentRouteSelection = NoRoute;
181 memset (mEeInfo, 0, sizeof(mEeInfo));
182 memset (&mUiccInfo, 0, sizeof(mUiccInfo));
183 memset (&mHciCfg, 0, sizeof(mHciCfg));
184 mUsedAids.clear ();
185 memset(mAidForEmptySelect, 0, sizeof(mAidForEmptySelect));
186
187 // Get Fresh EE info.
188 if (! getEeInfo())
189 return (false);
190
191 {
192 SyncEventGuard guard (mEeRegisterEvent);
193 ALOGD ("%s: try ee register", fn);
194 nfaStat = NFA_EeRegister (nfaEeCallback);
195 if (nfaStat != NFA_STATUS_OK)
196 {
197 ALOGE ("%s: fail ee register; error=0x%X", fn, nfaStat);
198 return (false);
199 }
200 mEeRegisterEvent.wait ();
201 }
202
203 // If the controller has an HCI Network, register for that
204 for (xx = 0; xx < mActualNumEe; xx++)
205 {
206 if ((mEeInfo[xx].num_interface > 0) && (mEeInfo[xx].ee_interface[0] == NCI_NFCEE_INTERFACE_HCI_ACCESS) )
207 {
208 ALOGD ("%s: Found HCI network, try hci register", fn);
209
210 SyncEventGuard guard (mHciRegisterEvent);
211
212 nfaStat = NFA_HciRegister (const_cast<char*>(APP_NAME), nfaHciCallback, TRUE);
213 if (nfaStat != NFA_STATUS_OK)
214 {
215 ALOGE ("%s: fail hci register; error=0x%X", fn, nfaStat);
216 return (false);
217 }
218 mHciRegisterEvent.wait();
219 break;
220 }
221 }
222
223 mRouteDataSet.initialize ();
224 mRouteDataSet.import (); //read XML file
225 HostAidRouter::getInstance().initialize ();
226
227 GetStrValue(NAME_AID_FOR_EMPTY_SELECT, (char*)&mAidForEmptySelect[0], sizeof(mAidForEmptySelect));
228
229 mIsInit = true;
230 ALOGD ("%s: exit", fn);
231 return (true);
232 }
233
234
235 /*******************************************************************************
236 **
237 ** Function: finalize
238 **
239 ** Description: Release all resources.
240 **
241 ** Returns: None
242 **
243 *******************************************************************************/
finalize()244 void SecureElement::finalize ()
245 {
246 static const char fn [] = "SecureElement::finalize";
247 ALOGD ("%s: enter", fn);
248 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
249
250 NFA_EeDeregister (nfaEeCallback);
251
252 if (mNfaHciHandle != NFA_HANDLE_INVALID)
253 NFA_HciDeregister (const_cast<char*>(APP_NAME));
254
255 mNfaHciHandle = NFA_HANDLE_INVALID;
256 mNativeData = NULL;
257 mIsInit = false;
258 mActualNumEe = 0;
259 mNumEePresent = 0;
260 mNewPipeId = 0;
261 mNewSourceGate = 0;
262 mIsPiping = false;
263 memset (mEeInfo, 0, sizeof(mEeInfo));
264 memset (&mUiccInfo, 0, sizeof(mUiccInfo));
265
266 ALOGD ("%s: exit", fn);
267 }
268
269
270 /*******************************************************************************
271 **
272 ** Function: getEeInfo
273 **
274 ** Description: Get latest information about execution environments from stack.
275 **
276 ** Returns: True if at least 1 EE is available.
277 **
278 *******************************************************************************/
getEeInfo()279 bool SecureElement::getEeInfo()
280 {
281 static const char fn [] = "SecureElement::getEeInfo";
282 ALOGD ("%s: enter; mbNewEE=%d, mActualNumEe=%d", fn, mbNewEE, mActualNumEe);
283 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
284 UINT8 xx = 0, yy = 0;
285
286 // If mbNewEE is true then there is new EE info.
287 if (mbNewEE)
288 {
289 mActualNumEe = MAX_NUM_EE;
290
291 if ((nfaStat = NFA_EeGetInfo (&mActualNumEe, mEeInfo)) != NFA_STATUS_OK)
292 {
293 ALOGE ("%s: fail get info; error=0x%X", fn, nfaStat);
294 mActualNumEe = 0;
295 }
296 else
297 {
298 mbNewEE = false;
299
300 ALOGD ("%s: num EEs discovered: %u", fn, mActualNumEe);
301 if (mActualNumEe != 0)
302 {
303 for (UINT8 xx = 0; xx < mActualNumEe; xx++)
304 {
305 if ((mEeInfo[xx].num_interface != 0) && (mEeInfo[xx].ee_interface[0] != NCI_NFCEE_INTERFACE_HCI_ACCESS) )
306 mNumEePresent++;
307
308 ALOGD ("%s: EE[%u] Handle: 0x%04x Status: %s Num I/f: %u: (0x%02x, 0x%02x) Num TLVs: %u",
309 fn, xx, mEeInfo[xx].ee_handle, eeStatusToString(mEeInfo[xx].ee_status), mEeInfo[xx].num_interface,
310 mEeInfo[xx].ee_interface[0], mEeInfo[xx].ee_interface[1], mEeInfo[xx].num_tlvs);
311
312 for (yy = 0; yy < mEeInfo[xx].num_tlvs; yy++)
313 {
314 ALOGD ("%s: EE[%u] TLV[%u] Tag: 0x%02x Len: %u Values[]: 0x%02x 0x%02x 0x%02x ...",
315 fn, xx, yy, mEeInfo[xx].ee_tlv[yy].tag, mEeInfo[xx].ee_tlv[yy].len, mEeInfo[xx].ee_tlv[yy].info[0],
316 mEeInfo[xx].ee_tlv[yy].info[1], mEeInfo[xx].ee_tlv[yy].info[2]);
317 }
318 }
319 }
320 }
321 }
322 ALOGD ("%s: exit; mActualNumEe=%d, mNumEePresent=%d", fn, mActualNumEe,mNumEePresent);
323 return (mActualNumEe != 0);
324 }
325
326
327 /*******************************************************************************
328 **
329 ** Function TimeDiff
330 **
331 ** Description Computes time difference in milliseconds.
332 **
333 ** Returns Time difference in milliseconds
334 **
335 *******************************************************************************/
TimeDiff(timespec start,timespec end)336 static UINT32 TimeDiff(timespec start, timespec end)
337 {
338 end.tv_sec -= start.tv_sec;
339 end.tv_nsec -= start.tv_nsec;
340
341 if (end.tv_nsec < 0) {
342 end.tv_nsec += 10e8;
343 end.tv_sec -=1;
344 }
345
346 return (end.tv_sec * 1000) + (end.tv_nsec / 10e5);
347 }
348
349 /*******************************************************************************
350 **
351 ** Function: isRfFieldOn
352 **
353 ** Description: Can be used to determine if the SE is in an RF field
354 **
355 ** Returns: True if the SE is activated in an RF field
356 **
357 *******************************************************************************/
isRfFieldOn()358 bool SecureElement::isRfFieldOn() {
359 AutoMutex mutex(mMutex);
360 if (mRfFieldIsOn) {
361 return true;
362 }
363 struct timespec now;
364 int ret = clock_gettime(CLOCK_MONOTONIC, &now);
365 if (ret == -1) {
366 ALOGE("isRfFieldOn(): clock_gettime failed");
367 return false;
368 }
369 if (TimeDiff(mLastRfFieldToggle, now) < 50) {
370 // If it was less than 50ms ago that RF field
371 // was turned off, still return ON.
372 return true;
373 } else {
374 return false;
375 }
376 }
377
378 /*******************************************************************************
379 **
380 ** Function: isActivatedInListenMode
381 **
382 ** Description: Can be used to determine if the SE is activated in listen mode
383 **
384 ** Returns: True if the SE is activated in listen mode
385 **
386 *******************************************************************************/
isActivatedInListenMode()387 bool SecureElement::isActivatedInListenMode() {
388 return mActivatedInListenMode;
389 }
390
391 /*******************************************************************************
392 **
393 ** Function: getListOfEeHandles
394 **
395 ** Description: Get the list of handles of all execution environments.
396 ** e: Java Virtual Machine.
397 **
398 ** Returns: List of handles of all execution environments.
399 **
400 *******************************************************************************/
getListOfEeHandles(JNIEnv * e)401 jintArray SecureElement::getListOfEeHandles (JNIEnv* e)
402 {
403 static const char fn [] = "SecureElement::getListOfEeHandles";
404 ALOGD ("%s: enter", fn);
405 if (mNumEePresent == 0)
406 return NULL;
407 jintArray list = NULL;
408
409 if (!mIsInit)
410 {
411 ALOGE ("%s: not init", fn);
412 return (NULL);
413 }
414
415 // Get Fresh EE info.
416 if (! getEeInfo())
417 return (NULL);
418
419 list = e->NewIntArray (mNumEePresent); //allocate array
420 jint jj = 0;
421 int cnt = 0;
422 for (int ii = 0; ii < mActualNumEe && cnt < mNumEePresent; ii++)
423 {
424 ALOGD ("%s: %u = 0x%X", fn, ii, mEeInfo[ii].ee_handle);
425 if ((mEeInfo[ii].num_interface == 0) || (mEeInfo[ii].ee_interface[0] == NCI_NFCEE_INTERFACE_HCI_ACCESS) )
426 {
427 continue;
428 }
429
430 jj = mEeInfo[ii].ee_handle & ~NFA_HANDLE_GROUP_EE;
431 e->SetIntArrayRegion (list, cnt++, 1, &jj);
432 }
433 //e->DeleteLocalRef (list);
434
435 ALOGD("%s: exit", fn);
436 return list;
437 }
438
439
440 /*******************************************************************************
441 **
442 ** Function: activate
443 **
444 ** Description: Turn on the secure element.
445 ** seID: ID of secure element; 0xF3 or 0xF4.
446 **
447 ** Returns: True if ok.
448 **
449 *******************************************************************************/
activate(jint seID)450 bool SecureElement::activate (jint seID)
451 {
452 static const char fn [] = "SecureElement::activate";
453 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
454 int numActivatedEe = 0;
455
456 ALOGD ("%s: enter; seID=0x%X", fn, seID);
457
458 if (!mIsInit)
459 {
460 ALOGE ("%s: not init", fn);
461 return false;
462 }
463
464 if (mActiveEeHandle != NFA_HANDLE_INVALID)
465 {
466 ALOGD ("%s: already active", fn);
467 return true;
468 }
469
470 // Get Fresh EE info if needed.
471 if (! getEeInfo())
472 {
473 ALOGE ("%s: no EE info", fn);
474 return false;
475 }
476
477 UINT16 overrideEeHandle = 0;
478 if (mActiveSeOverride)
479 overrideEeHandle = NFA_HANDLE_GROUP_EE | mActiveSeOverride;
480
481 if (mRfFieldIsOn) {
482 ALOGE("%s: RF field indication still on, resetting", fn);
483 mRfFieldIsOn = false;
484 }
485
486 ALOGD ("%s: override ee h=0x%X", fn, overrideEeHandle );
487 //activate every discovered secure element
488 for (int index=0; index < mActualNumEe; index++)
489 {
490 tNFA_EE_INFO& eeItem = mEeInfo[index];
491
492 if ((eeItem.ee_handle == EE_HANDLE_0xF3) || (eeItem.ee_handle == EE_HANDLE_0xF4))
493 {
494 if (overrideEeHandle && (overrideEeHandle != eeItem.ee_handle) )
495 continue; // do not enable all SEs; only the override one
496
497 if (eeItem.ee_status != NFC_NFCEE_STATUS_INACTIVE)
498 {
499 ALOGD ("%s: h=0x%X already activated", fn, eeItem.ee_handle);
500 numActivatedEe++;
501 continue;
502 }
503
504 {
505 SyncEventGuard guard (mEeSetModeEvent);
506 ALOGD ("%s: set EE mode activate; h=0x%X", fn, eeItem.ee_handle);
507 if ((nfaStat = NFA_EeModeSet (eeItem.ee_handle, NFA_EE_MD_ACTIVATE)) == NFA_STATUS_OK)
508 {
509 mEeSetModeEvent.wait (); //wait for NFA_EE_MODE_SET_EVT
510 if (eeItem.ee_status == NFC_NFCEE_STATUS_ACTIVE)
511 numActivatedEe++;
512 }
513 else
514 ALOGE ("%s: NFA_EeModeSet failed; error=0x%X", fn, nfaStat);
515 }
516 }
517 } //for
518
519 mActiveEeHandle = getDefaultEeHandle();
520 if (mActiveEeHandle == NFA_HANDLE_INVALID)
521 ALOGE ("%s: ee handle not found", fn);
522 ALOGD ("%s: exit; active ee h=0x%X", fn, mActiveEeHandle);
523 return mActiveEeHandle != NFA_HANDLE_INVALID;
524 }
525
526
527 /*******************************************************************************
528 **
529 ** Function: deactivate
530 **
531 ** Description: Turn off the secure element.
532 ** seID: ID of secure element; 0xF3 or 0xF4.
533 **
534 ** Returns: True if ok.
535 **
536 *******************************************************************************/
deactivate(jint seID)537 bool SecureElement::deactivate (jint seID)
538 {
539 static const char fn [] = "SecureElement::deactivate";
540 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
541 int numDeactivatedEe = 0;
542 bool retval = false;
543
544 ALOGD ("%s: enter; seID=0x%X, mActiveEeHandle=0x%X", fn, seID, mActiveEeHandle);
545
546 if (!mIsInit)
547 {
548 ALOGE ("%s: not init", fn);
549 goto TheEnd;
550 }
551
552 //if the controller is routing to sec elems or piping,
553 //then the secure element cannot be deactivated
554 if ((mCurrentRouteSelection == SecElemRoute) || mIsPiping)
555 {
556 ALOGE ("%s: still busy", fn);
557 goto TheEnd;
558 }
559
560 if (mActiveEeHandle == NFA_HANDLE_INVALID)
561 {
562 ALOGE ("%s: invalid EE handle", fn);
563 goto TheEnd;
564 }
565
566 mActiveEeHandle = NFA_HANDLE_INVALID;
567 retval = true;
568
569 TheEnd:
570 ALOGD ("%s: exit; ok=%u", fn, retval);
571 return retval;
572 }
573
574
575 /*******************************************************************************
576 **
577 ** Function: notifyTransactionListenersOfAid
578 **
579 ** Description: Notify the NFC service about a transaction event from secure element.
580 ** aid: Buffer contains application ID.
581 ** aidLen: Length of application ID.
582 **
583 ** Returns: None
584 **
585 *******************************************************************************/
notifyTransactionListenersOfAid(const UINT8 * aidBuffer,UINT8 aidBufferLen)586 void SecureElement::notifyTransactionListenersOfAid (const UINT8* aidBuffer, UINT8 aidBufferLen)
587 {
588 static const char fn [] = "SecureElement::notifyTransactionListenersOfAid";
589 ALOGD ("%s: enter; aid len=%u", fn, aidBufferLen);
590
591 if (aidBufferLen == 0)
592 return;
593
594 jobject tlvJavaArray = NULL;
595 JNIEnv* e = NULL;
596 UINT8* tlv = 0;
597 const UINT16 tlvMaxLen = aidBufferLen + 10;
598 UINT16 tlvActualLen = 0;
599 bool stat = false;
600
601 mNativeData->vm->AttachCurrentThread (&e, NULL);
602 if (e == NULL)
603 {
604 ALOGE ("%s: jni env is null", fn);
605 return;
606 }
607
608 tlv = new UINT8 [tlvMaxLen];
609 if (tlv == NULL)
610 {
611 ALOGE ("%s: fail allocate tlv", fn);
612 goto TheEnd;
613 }
614
615 memcpy (tlv, aidBuffer, aidBufferLen);
616 tlvActualLen = aidBufferLen;
617
618 tlvJavaArray = e->NewByteArray (tlvActualLen);
619 if (tlvJavaArray == NULL)
620 {
621 ALOGE ("%s: fail allocate array", fn);
622 goto TheEnd;
623 }
624
625 e->SetByteArrayRegion ((jbyteArray)tlvJavaArray, 0, tlvActualLen, (jbyte *)tlv);
626 if (e->ExceptionCheck())
627 {
628 e->ExceptionClear();
629 ALOGE ("%s: fail fill array", fn);
630 goto TheEnd;
631 }
632
633 e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifyTransactionListeners, tlvJavaArray);
634 if (e->ExceptionCheck())
635 {
636 e->ExceptionClear();
637 ALOGE ("%s: fail notify", fn);
638 goto TheEnd;
639 }
640
641 TheEnd:
642 if (tlvJavaArray)
643 e->DeleteLocalRef (tlvJavaArray);
644 mNativeData->vm->DetachCurrentThread ();
645 delete [] tlv;
646 ALOGD ("%s: exit", fn);
647 }
648
649
650 /*******************************************************************************
651 **
652 ** Function: connectEE
653 **
654 ** Description: Connect to the execution environment.
655 **
656 ** Returns: True if ok.
657 **
658 *******************************************************************************/
connectEE()659 bool SecureElement::connectEE ()
660 {
661 static const char fn [] = "SecureElement::connectEE";
662 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
663 bool retVal = false;
664 UINT8 destHost = 0;
665 unsigned long num = 0;
666 char pipeConfName[40];
667 tNFA_HANDLE eeHandle = mActiveEeHandle;
668
669 ALOGD ("%s: enter, mActiveEeHandle: 0x%04x, SEID: 0x%x, pipe_gate_num=%d, use pipe=%d",
670 fn, mActiveEeHandle, gSEId, gGatePipe, gUseStaticPipe);
671
672 if (!mIsInit)
673 {
674 ALOGE ("%s: not init", fn);
675 return (false);
676 }
677
678 if (gSEId != -1)
679 {
680 eeHandle = gSEId | NFA_HANDLE_GROUP_EE;
681 ALOGD ("%s: Using SEID: 0x%x", fn, eeHandle );
682 }
683
684 if (eeHandle == NFA_HANDLE_INVALID)
685 {
686 ALOGE ("%s: invalid handle 0x%X", fn, eeHandle);
687 return (false);
688 }
689
690 tNFA_EE_INFO *pEE = findEeByHandle (eeHandle);
691
692 if (pEE == NULL)
693 {
694 ALOGE ("%s: Handle 0x%04x NOT FOUND !!", fn, eeHandle);
695 return (false);
696 }
697
698 // Disable RF discovery completely while the DH is connected
699 android::startRfDiscovery(false);
700
701 mNewSourceGate = 0;
702
703 if (gGatePipe == -1)
704 {
705 // pipe/gate num was not specifed by app, get from config file
706 mNewPipeId = 0;
707
708 // Construct the PIPE name based on the EE handle (e.g. NFA_HCI_STATIC_PIPE_ID_F3 for UICC0).
709 snprintf (pipeConfName, sizeof(pipeConfName), "NFA_HCI_STATIC_PIPE_ID_%02X", eeHandle & NFA_HANDLE_MASK);
710
711 if (GetNumValue(pipeConfName, &num, sizeof(num)) && (num != 0))
712 {
713 mNewPipeId = num;
714 ALOGD ("%s: Using static pipe id: 0x%X", __FUNCTION__, mNewPipeId);
715 }
716 else
717 {
718 ALOGD ("%s: Did not find value '%s' defined in the .conf", __FUNCTION__, pipeConfName);
719 }
720 }
721 else
722 {
723 if (gUseStaticPipe)
724 {
725 mNewPipeId = gGatePipe;
726 }
727 else
728 {
729 mNewPipeId = 0;
730 mDestinationGate= gGatePipe;
731 }
732 }
733
734 // If the .conf file had a static pipe to use, just use it.
735 if (mNewPipeId != 0)
736 {
737 UINT8 host = (mNewPipeId == STATIC_PIPE_0x70) ? 0x02 : 0x03;
738 UINT8 gate = (mNewPipeId == STATIC_PIPE_0x70) ? 0xF0 : 0xF1;
739 nfaStat = NFA_HciAddStaticPipe(mNfaHciHandle, host, gate, mNewPipeId);
740 if (nfaStat != NFA_STATUS_OK)
741 {
742 ALOGE ("%s: fail create static pipe; error=0x%X", fn, nfaStat);
743 retVal = false;
744 goto TheEnd;
745 }
746 }
747 else
748 {
749 if ( (pEE->num_tlvs >= 1) && (pEE->ee_tlv[0].tag == NFA_EE_TAG_HCI_HOST_ID) )
750 destHost = pEE->ee_tlv[0].info[0];
751 else
752 destHost = 2;
753
754 // Get a list of existing gates and pipes
755 {
756 ALOGD ("%s: get gate, pipe list", fn);
757 SyncEventGuard guard (mPipeListEvent);
758 nfaStat = NFA_HciGetGateAndPipeList (mNfaHciHandle);
759 if (nfaStat == NFA_STATUS_OK)
760 {
761 mPipeListEvent.wait();
762 if (mHciCfg.status == NFA_STATUS_OK)
763 {
764 for (UINT8 xx = 0; xx < mHciCfg.num_pipes; xx++)
765 {
766 if ( (mHciCfg.pipe[xx].dest_host == destHost)
767 && (mHciCfg.pipe[xx].dest_gate == mDestinationGate) )
768 {
769 mNewSourceGate = mHciCfg.pipe[xx].local_gate;
770 mNewPipeId = mHciCfg.pipe[xx].pipe_id;
771
772 ALOGD ("%s: found configured gate: 0x%02x pipe: 0x%02x", fn, mNewSourceGate, mNewPipeId);
773 break;
774 }
775 }
776 }
777 }
778 }
779
780 if (mNewSourceGate == 0)
781 {
782 ALOGD ("%s: allocate gate", fn);
783 //allocate a source gate and store in mNewSourceGate
784 SyncEventGuard guard (mAllocateGateEvent);
785 if ((nfaStat = NFA_HciAllocGate (mNfaHciHandle)) != NFA_STATUS_OK)
786 {
787 ALOGE ("%s: fail allocate source gate; error=0x%X", fn, nfaStat);
788 goto TheEnd;
789 }
790 mAllocateGateEvent.wait ();
791 if (mCommandStatus != NFA_STATUS_OK)
792 goto TheEnd;
793 }
794
795 if (mNewPipeId == 0)
796 {
797 ALOGD ("%s: create pipe", fn);
798 SyncEventGuard guard (mCreatePipeEvent);
799 nfaStat = NFA_HciCreatePipe (mNfaHciHandle, mNewSourceGate, destHost, mDestinationGate);
800 if (nfaStat != NFA_STATUS_OK)
801 {
802 ALOGE ("%s: fail create pipe; error=0x%X", fn, nfaStat);
803 goto TheEnd;
804 }
805 mCreatePipeEvent.wait ();
806 if (mCommandStatus != NFA_STATUS_OK)
807 goto TheEnd;
808 }
809
810 {
811 ALOGD ("%s: open pipe", fn);
812 SyncEventGuard guard (mPipeOpenedEvent);
813 nfaStat = NFA_HciOpenPipe (mNfaHciHandle, mNewPipeId);
814 if (nfaStat != NFA_STATUS_OK)
815 {
816 ALOGE ("%s: fail open pipe; error=0x%X", fn, nfaStat);
817 goto TheEnd;
818 }
819 mPipeOpenedEvent.wait ();
820 if (mCommandStatus != NFA_STATUS_OK)
821 goto TheEnd;
822 }
823 }
824
825 retVal = true;
826
827 TheEnd:
828 mIsPiping = retVal;
829 if (!retVal)
830 {
831 // if open failed we need to de-allocate the gate
832 disconnectEE(0);
833 }
834
835 ALOGD ("%s: exit; ok=%u", fn, retVal);
836 return retVal;
837 }
838
839
840 /*******************************************************************************
841 **
842 ** Function: disconnectEE
843 **
844 ** Description: Disconnect from the execution environment.
845 ** seID: ID of secure element.
846 **
847 ** Returns: True if ok.
848 **
849 *******************************************************************************/
disconnectEE(jint seID)850 bool SecureElement::disconnectEE (jint seID)
851 {
852 static const char fn [] = "SecureElement::disconnectEE";
853 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
854 tNFA_HANDLE eeHandle = seID;
855
856 ALOGD("%s: seID=0x%X; handle=0x%04x", fn, seID, eeHandle);
857
858 if (mUseOberthurWarmReset)
859 {
860 //send warm-reset command to Oberthur secure element which deselects the applet;
861 //this is an Oberthur-specific command;
862 ALOGD("%s: try warm-reset on pipe id 0x%X; cmd=0x%X", fn, mNewPipeId, mOberthurWarmResetCommand);
863 SyncEventGuard guard (mRegistryEvent);
864 nfaStat = NFA_HciSetRegistry (mNfaHciHandle, mNewPipeId,
865 1, 1, &mOberthurWarmResetCommand);
866 if (nfaStat == NFA_STATUS_OK)
867 {
868 mRegistryEvent.wait ();
869 ALOGD("%s: completed warm-reset on pipe 0x%X", fn, mNewPipeId);
870 }
871 }
872
873 if (mNewSourceGate)
874 {
875 SyncEventGuard guard (mDeallocateGateEvent);
876 if ((nfaStat = NFA_HciDeallocGate (mNfaHciHandle, mNewSourceGate)) == NFA_STATUS_OK)
877 mDeallocateGateEvent.wait ();
878 else
879 ALOGE ("%s: fail dealloc gate; error=0x%X", fn, nfaStat);
880 }
881 mIsPiping = false;
882 // Re-enable RF discovery
883 // Note that it only effactuates the current configuration,
884 // so if polling/listening were configured OFF (forex because
885 // the screen was off), they will stay OFF with this call.
886 android::startRfDiscovery(true);
887 return true;
888 }
889
890
891 /*******************************************************************************
892 **
893 ** Function: transceive
894 **
895 ** Description: Send data to the secure element; read it's response.
896 ** xmitBuffer: Data to transmit.
897 ** xmitBufferSize: Length of data.
898 ** recvBuffer: Buffer to receive response.
899 ** recvBufferMaxSize: Maximum size of buffer.
900 ** recvBufferActualSize: Actual length of response.
901 ** timeoutMillisec: timeout in millisecond.
902 **
903 ** Returns: True if ok.
904 **
905 *******************************************************************************/
transceive(UINT8 * xmitBuffer,INT32 xmitBufferSize,UINT8 * recvBuffer,INT32 recvBufferMaxSize,INT32 & recvBufferActualSize,INT32 timeoutMillisec)906 bool SecureElement::transceive (UINT8* xmitBuffer, INT32 xmitBufferSize, UINT8* recvBuffer,
907 INT32 recvBufferMaxSize, INT32& recvBufferActualSize, INT32 timeoutMillisec)
908 {
909 static const char fn [] = "SecureElement::transceive";
910 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
911 bool isSuccess = false;
912 bool waitOk = false;
913 UINT8 newSelectCmd[NCI_MAX_AID_LEN + 10];
914
915 ALOGD ("%s: enter; xmitBufferSize=%ld; recvBufferMaxSize=%ld; timeout=%ld", fn, xmitBufferSize, recvBufferMaxSize, timeoutMillisec);
916
917 // Check if we need to replace an "empty" SELECT command.
918 // 1. Has there been a AID configured, and
919 // 2. Is that AID a valid length (i.e 16 bytes max), and
920 // 3. Is the APDU at least 4 bytes (for header), and
921 // 4. Is INS == 0xA4 (SELECT command), and
922 // 5. Is P1 == 0x04 (SELECT by AID), and
923 // 6. Is the APDU len 4 or 5 bytes.
924 //
925 // Note, the length of the configured AID is in the first
926 // byte, and AID starts from the 2nd byte.
927 if (mAidForEmptySelect[0] // 1
928 && (mAidForEmptySelect[0] <= NCI_MAX_AID_LEN) // 2
929 && (xmitBufferSize >= 4) // 3
930 && (xmitBuffer[1] == 0xA4) // 4
931 && (xmitBuffer[2] == 0x04) // 5
932 && (xmitBufferSize <= 5)) // 6
933 {
934 UINT8 idx = 0;
935
936 // Copy APDU command header from the input buffer.
937 memcpy(&newSelectCmd[0], &xmitBuffer[0], 4);
938 idx = 4;
939
940 // Set the Lc value to length of the new AID
941 newSelectCmd[idx++] = mAidForEmptySelect[0];
942
943 // Copy the AID
944 memcpy(&newSelectCmd[idx], &mAidForEmptySelect[1], mAidForEmptySelect[0]);
945 idx += mAidForEmptySelect[0];
946
947 // If there is an Le (5th byte of APDU), add it to the end.
948 if (xmitBufferSize == 5)
949 newSelectCmd[idx++] = xmitBuffer[4];
950
951 // Point to the new APDU
952 xmitBuffer = &newSelectCmd[0];
953 xmitBufferSize = idx;
954
955 ALOGD ("%s: Empty AID SELECT cmd detected, substituting AID from config file, new length=%d", fn, idx);
956 }
957
958 {
959 SyncEventGuard guard (mTransceiveEvent);
960 mActualResponseSize = 0;
961 memset (mResponseData, 0, sizeof(mResponseData));
962 if ((mNewPipeId == STATIC_PIPE_0x70) || (mNewPipeId == STATIC_PIPE_0x71))
963 nfaStat = NFA_HciSendEvent (mNfaHciHandle, mNewPipeId, EVT_SEND_DATA, xmitBufferSize, xmitBuffer, sizeof(mResponseData), mResponseData, 0);
964 else
965 nfaStat = NFA_HciSendEvent (mNfaHciHandle, mNewPipeId, NFA_HCI_EVT_POST_DATA, xmitBufferSize, xmitBuffer, sizeof(mResponseData), mResponseData, 0);
966
967 if (nfaStat == NFA_STATUS_OK)
968 {
969 waitOk = mTransceiveEvent.wait (timeoutMillisec);
970 if (waitOk == false) //timeout occurs
971 {
972 ALOGE ("%s: wait response timeout", fn);
973 goto TheEnd;
974 }
975 }
976 else
977 {
978 ALOGE ("%s: fail send data; error=0x%X", fn, nfaStat);
979 goto TheEnd;
980 }
981 }
982
983 if (mActualResponseSize > recvBufferMaxSize)
984 recvBufferActualSize = recvBufferMaxSize;
985 else
986 recvBufferActualSize = mActualResponseSize;
987
988 memcpy (recvBuffer, mResponseData, recvBufferActualSize);
989 isSuccess = true;
990
991 TheEnd:
992 ALOGD ("%s: exit; isSuccess: %d; recvBufferActualSize: %ld", fn, isSuccess, recvBufferActualSize);
993 return (isSuccess);
994 }
995
996
997 /*******************************************************************************
998 **
999 ** Function: notifyListenModeState
1000 **
1001 ** Description: Notify the NFC service about whether the SE was activated
1002 ** in listen mode.
1003 ** isActive: Whether the secure element is activated.
1004 **
1005 ** Returns: None
1006 **
1007 *******************************************************************************/
notifyListenModeState(bool isActivated)1008 void SecureElement::notifyListenModeState (bool isActivated) {
1009 static const char fn [] = "SecureElement::notifyListenMode";
1010 JNIEnv *e = NULL;
1011
1012 ALOGD ("%s: enter; listen mode active=%u", fn, isActivated);
1013 mNativeData->vm->AttachCurrentThread (&e, NULL);
1014
1015 if (e == NULL)
1016 {
1017 ALOGE ("%s: jni env is null", fn);
1018 return;
1019 }
1020
1021 mActivatedInListenMode = isActivated;
1022 if (isActivated) {
1023 e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifySeListenActivated);
1024 }
1025 else {
1026 e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifySeListenDeactivated);
1027 }
1028
1029 if (e->ExceptionCheck())
1030 {
1031 e->ExceptionClear();
1032 ALOGE ("%s: fail notify", fn);
1033 }
1034
1035 mNativeData->vm->DetachCurrentThread ();
1036 ALOGD ("%s: exit", fn);
1037 }
1038
1039 /*******************************************************************************
1040 **
1041 ** Function: notifyRfFieldEvent
1042 **
1043 ** Description: Notify the NFC service about RF field events from the stack.
1044 ** isActive: Whether any secure element is activated.
1045 **
1046 ** Returns: None
1047 **
1048 *******************************************************************************/
notifyRfFieldEvent(bool isActive)1049 void SecureElement::notifyRfFieldEvent (bool isActive)
1050 {
1051 static const char fn [] = "SecureElement::notifyRfFieldEvent";
1052 JNIEnv *e = NULL;
1053
1054 ALOGD ("%s: enter; is active=%u", fn, isActive);
1055 mNativeData->vm->AttachCurrentThread (&e, NULL);
1056
1057 if (e == NULL)
1058 {
1059 ALOGE ("%s: jni env is null", fn);
1060 return;
1061 }
1062
1063 mMutex.lock();
1064 int ret = clock_gettime (CLOCK_MONOTONIC, &mLastRfFieldToggle);
1065 if (ret == -1) {
1066 ALOGE("%s: clock_gettime failed", fn);
1067 // There is no good choice here...
1068 }
1069 if (isActive) {
1070 mRfFieldIsOn = true;
1071 e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifySeFieldActivated);
1072 }
1073 else {
1074 mRfFieldIsOn = false;
1075 e->CallVoidMethod (mNativeData->manager, android::gCachedNfcManagerNotifySeFieldDeactivated);
1076 }
1077 mMutex.unlock();
1078
1079 if (e->ExceptionCheck())
1080 {
1081 e->ExceptionClear();
1082 ALOGE ("%s: fail notify", fn);
1083 }
1084 mNativeData->vm->DetachCurrentThread ();
1085 ALOGD ("%s: exit", fn);
1086 }
1087
1088
1089 /*******************************************************************************
1090 **
1091 ** Function: storeUiccInfo
1092 **
1093 ** Description: Store a copy of the execution environment information from the stack.
1094 ** info: execution environment information.
1095 **
1096 ** Returns: None
1097 **
1098 *******************************************************************************/
storeUiccInfo(tNFA_EE_DISCOVER_REQ & info)1099 void SecureElement::storeUiccInfo (tNFA_EE_DISCOVER_REQ& info)
1100 {
1101 static const char fn [] = "SecureElement::storeUiccInfo";
1102 ALOGD ("%s: Status: %u Num EE: %u", fn, info.status, info.num_ee);
1103
1104 SyncEventGuard guard (mUiccInfoEvent);
1105 memcpy (&mUiccInfo, &info, sizeof(mUiccInfo));
1106 for (UINT8 xx = 0; xx < info.num_ee; xx++)
1107 {
1108 //for each technology (A, B, F, B'), print the bit field that shows
1109 //what protocol(s) is support by that technology
1110 ALOGD ("%s EE[%u] Handle: 0x%04x techA: 0x%02x techB: 0x%02x techF: 0x%02x techBprime: 0x%02x",
1111 fn, xx, info.ee_disc_info[xx].ee_handle,
1112 info.ee_disc_info[xx].la_protocol,
1113 info.ee_disc_info[xx].lb_protocol,
1114 info.ee_disc_info[xx].lf_protocol,
1115 info.ee_disc_info[xx].lbp_protocol);
1116 }
1117 mUiccInfoEvent.notifyOne ();
1118 }
1119
1120
1121 /*******************************************************************************
1122 **
1123 ** Function: getUiccId
1124 **
1125 ** Description: Get the ID of the secure element.
1126 ** eeHandle: Handle to the secure element.
1127 ** uid: Array to receive the ID.
1128 **
1129 ** Returns: True if ok.
1130 **
1131 *******************************************************************************/
getUiccId(tNFA_HANDLE eeHandle,jbyteArray & uid)1132 bool SecureElement::getUiccId (tNFA_HANDLE eeHandle, jbyteArray& uid)
1133 {
1134 static const char fn [] = "SecureElement::getUiccId";
1135 ALOGD ("%s: ee h=0x%X", fn, eeHandle);
1136 bool retval = false;
1137 JNIEnv* e = NULL;
1138
1139 mNativeData->vm->AttachCurrentThread (&e, NULL);
1140 if (e == NULL)
1141 {
1142 ALOGE ("%s: jni env is null", fn);
1143 return false;
1144 }
1145
1146 findUiccByHandle (eeHandle);
1147 //cannot get UID from the stack; nothing to do
1148
1149 TheEnd:
1150 mNativeData->vm->DetachCurrentThread ();
1151 ALOGD ("%s: exit; ret=%u", fn, retval);
1152 return retval;
1153 }
1154
1155
1156 /*******************************************************************************
1157 **
1158 ** Function: getTechnologyList
1159 **
1160 ** Description: Get all the technologies supported by a secure element.
1161 ** eeHandle: Handle of secure element.
1162 ** techList: List to receive the technologies.
1163 **
1164 ** Returns: True if ok.
1165 **
1166 *******************************************************************************/
getTechnologyList(tNFA_HANDLE eeHandle,jintArray & techList)1167 bool SecureElement::getTechnologyList (tNFA_HANDLE eeHandle, jintArray& techList)
1168 {
1169 static const char fn [] = "SecureElement::getTechnologyList";
1170 ALOGD ("%s: ee h=0x%X", fn, eeHandle);
1171 bool retval = false;
1172 JNIEnv* e = NULL;
1173 jint theList = 0;
1174
1175 mNativeData->vm->AttachCurrentThread (&e, NULL);
1176 if (e == NULL)
1177 {
1178 ALOGE ("%s: jni env is null", fn);
1179 return false;
1180 }
1181
1182 tNFA_EE_DISCOVER_INFO *pUICC = findUiccByHandle (eeHandle);
1183
1184 if (pUICC->la_protocol != 0)
1185 theList = TARGET_TYPE_ISO14443_3A;
1186 else if (pUICC->lb_protocol != 0)
1187 theList = TARGET_TYPE_ISO14443_3B;
1188 else if (pUICC->lf_protocol != 0)
1189 theList = TARGET_TYPE_FELICA;
1190 else if (pUICC->lbp_protocol != 0)
1191 theList = TARGET_TYPE_ISO14443_3B;
1192 else
1193 theList = TARGET_TYPE_UNKNOWN;
1194
1195 TheEnd:
1196 mNativeData->vm->DetachCurrentThread ();
1197 ALOGD ("%s: exit; ret=%u", fn, retval);
1198 return retval;
1199 }
1200
1201
1202 /*******************************************************************************
1203 **
1204 ** Function: adjustRoutes
1205 **
1206 ** Description: Adjust routes in the controller's listen-mode routing table.
1207 ** selection: which set of routes to configure the controller.
1208 **
1209 ** Returns: None
1210 **
1211 *******************************************************************************/
adjustRoutes(RouteSelection selection)1212 void SecureElement::adjustRoutes (RouteSelection selection)
1213 {
1214 static const char fn [] = "SecureElement::adjustRoutes";
1215 ALOGD ("%s: enter; selection=%u", fn, selection);
1216 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
1217 RouteDataSet::Database* db = mRouteDataSet.getDatabase (RouteDataSet::DefaultRouteDatabase);
1218
1219 if (selection == SecElemRoute)
1220 db = mRouteDataSet.getDatabase (RouteDataSet::SecElemRouteDatabase);
1221
1222 mCurrentRouteSelection = selection;
1223 adjustProtocolRoutes (db, selection);
1224 adjustTechnologyRoutes (db, selection);
1225 HostAidRouter::getInstance ().deleteAllRoutes (); //stop all AID routes to host
1226
1227 if (db->empty())
1228 {
1229 ALOGD ("%s: no route configuration", fn);
1230 goto TheEnd;
1231 }
1232
1233
1234 TheEnd:
1235 NFA_EeUpdateNow (); //apply new routes now
1236 ALOGD ("%s: exit", fn);
1237 }
1238
1239
1240 /*******************************************************************************
1241 **
1242 ** Function: applyRoutes
1243 **
1244 ** Description: Read route data from file and apply them again.
1245 **
1246 ** Returns: None
1247 **
1248 *******************************************************************************/
applyRoutes()1249 void SecureElement::applyRoutes ()
1250 {
1251 static const char fn [] = "SecureElement::applyRoutes";
1252 ALOGD ("%s: enter", fn);
1253 if (mCurrentRouteSelection != NoRoute)
1254 {
1255 mRouteDataSet.import (); //read XML file
1256 adjustRoutes (mCurrentRouteSelection);
1257 }
1258 ALOGD ("%s: exit", fn);
1259 }
1260
1261
1262 /*******************************************************************************
1263 **
1264 ** Function: adjustProtocolRoutes
1265 **
1266 ** Description: Adjust default routing based on protocol in NFC listen mode.
1267 ** isRouteToEe: Whether routing to EE (true) or host (false).
1268 **
1269 ** Returns: None
1270 **
1271 *******************************************************************************/
adjustProtocolRoutes(RouteDataSet::Database * db,RouteSelection routeSelection)1272 void SecureElement::adjustProtocolRoutes (RouteDataSet::Database* db, RouteSelection routeSelection)
1273 {
1274 static const char fn [] = "SecureElement::adjustProtocolRoutes";
1275 ALOGD ("%s: enter", fn);
1276 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
1277 const tNFA_PROTOCOL_MASK protoMask = NFA_PROTOCOL_MASK_ISO_DEP;
1278
1279 ///////////////////////
1280 // delete route to host
1281 ///////////////////////
1282 {
1283 ALOGD ("%s: delete route to host", fn);
1284 SyncEventGuard guard (mRoutingEvent);
1285 if ((nfaStat = NFA_EeSetDefaultProtoRouting (NFA_EE_HANDLE_DH, 0, 0, 0)) == NFA_STATUS_OK)
1286 mRoutingEvent.wait ();
1287 else
1288 ALOGE ("%s: fail delete route to host; error=0x%X", fn, nfaStat);
1289 }
1290
1291 ///////////////////////
1292 // delete route to every sec elem
1293 ///////////////////////
1294 for (int i=0; i < mActualNumEe; i++)
1295 {
1296 if ((mEeInfo[i].num_interface != 0) &&
1297 (mEeInfo[i].ee_interface[0] != NFC_NFCEE_INTERFACE_HCI_ACCESS) &&
1298 (mEeInfo[i].ee_status == NFA_EE_STATUS_ACTIVE))
1299 {
1300 ALOGD ("%s: delete route to EE h=0x%X", fn, mEeInfo[i].ee_handle);
1301 SyncEventGuard guard (mRoutingEvent);
1302 if ((nfaStat = NFA_EeSetDefaultProtoRouting (mEeInfo[i].ee_handle, 0, 0, 0)) == NFA_STATUS_OK)
1303 mRoutingEvent.wait ();
1304 else
1305 ALOGE ("%s: fail delete route to EE; error=0x%X", fn, nfaStat);
1306 }
1307 }
1308
1309 //////////////////////
1310 // configure route for every discovered sec elem
1311 //////////////////////
1312 for (int i=0; i < mActualNumEe; i++)
1313 {
1314 //if sec elem is active
1315 if ((mEeInfo[i].num_interface != 0) &&
1316 (mEeInfo[i].ee_interface[0] != NFC_NFCEE_INTERFACE_HCI_ACCESS) &&
1317 (mEeInfo[i].ee_status == NFA_EE_STATUS_ACTIVE))
1318 {
1319 tNFA_PROTOCOL_MASK protocolsSwitchOn = 0; //all protocols that are active at full power
1320 tNFA_PROTOCOL_MASK protocolsSwitchOff = 0; //all protocols that are active when phone is turned off
1321 tNFA_PROTOCOL_MASK protocolsBatteryOff = 0; //all protocols that are active when there is no power
1322
1323 //for every route in XML, look for protocol route;
1324 //collect every protocol according to it's desired power mode
1325 for (RouteDataSet::Database::iterator iter = db->begin(); iter != db->end(); iter++)
1326 {
1327 RouteData* routeData = *iter;
1328 RouteDataForProtocol* route = NULL;
1329 if (routeData->mRouteType != RouteData::ProtocolRoute)
1330 continue; //skip other kinds of routing data
1331 route = (RouteDataForProtocol*) (*iter);
1332 if (route->mNfaEeHandle == mEeInfo[i].ee_handle)
1333 {
1334 if (route->mSwitchOn)
1335 protocolsSwitchOn |= route->mProtocol;
1336 if (route->mSwitchOff)
1337 protocolsSwitchOff |= route->mProtocol;
1338 if (route->mBatteryOff)
1339 protocolsBatteryOff |= route->mProtocol;
1340 }
1341 }
1342
1343 if (protocolsSwitchOn | protocolsSwitchOff | protocolsBatteryOff)
1344 {
1345 ALOGD ("%s: route to EE h=0x%X", fn, mEeInfo[i].ee_handle);
1346 SyncEventGuard guard (mRoutingEvent);
1347 nfaStat = NFA_EeSetDefaultProtoRouting (mEeInfo[i].ee_handle,
1348 protocolsSwitchOn, protocolsSwitchOff, protocolsBatteryOff);
1349 if (nfaStat == NFA_STATUS_OK)
1350 mRoutingEvent.wait ();
1351 else
1352 ALOGE ("%s: fail route to EE; error=0x%X", fn, nfaStat);
1353 }
1354 } //if sec elem is active
1355 } //for every discovered sec elem
1356
1357 //////////////////////
1358 // configure route to host
1359 //////////////////////
1360 {
1361 tNFA_PROTOCOL_MASK protocolsSwitchOn = 0; //all protocols that are active at full power
1362 tNFA_PROTOCOL_MASK protocolsSwitchOff = 0; //all protocols that are active when phone is turned off
1363 tNFA_PROTOCOL_MASK protocolsBatteryOff = 0; //all protocols that are active when there is no power
1364
1365 //for every route in XML, look for protocol route;
1366 //collect every protocol according to it's desired power mode
1367 for (RouteDataSet::Database::iterator iter = db->begin(); iter != db->end(); iter++)
1368 {
1369 RouteData* routeData = *iter;
1370 RouteDataForProtocol* route = NULL;
1371 if (routeData->mRouteType != RouteData::ProtocolRoute)
1372 continue; //skip other kinds of routing data
1373 route = (RouteDataForProtocol*) (*iter);
1374 if (route->mNfaEeHandle == NFA_EE_HANDLE_DH)
1375 {
1376 if (route->mSwitchOn)
1377 protocolsSwitchOn |= route->mProtocol;
1378 if (route->mSwitchOff)
1379 protocolsSwitchOff |= route->mProtocol;
1380 if (route->mBatteryOff)
1381 protocolsBatteryOff |= route->mProtocol;
1382 }
1383 }
1384
1385 if (protocolsSwitchOn | protocolsSwitchOff | protocolsBatteryOff)
1386 {
1387 ALOGD ("%s: route to EE h=0x%X", fn, NFA_EE_HANDLE_DH);
1388 SyncEventGuard guard (mRoutingEvent);
1389 nfaStat = NFA_EeSetDefaultProtoRouting (NFA_EE_HANDLE_DH,
1390 protocolsSwitchOn, protocolsSwitchOff, protocolsBatteryOff);
1391 if (nfaStat == NFA_STATUS_OK)
1392 mRoutingEvent.wait ();
1393 else
1394 ALOGE ("%s: fail route to EE; error=0x%X", fn, nfaStat);
1395 }
1396 }
1397
1398 //////////////////////
1399 // if route database is empty, setup a default route
1400 //////////////////////
1401 if (db->empty())
1402 {
1403 tNFA_HANDLE eeHandle = NFA_EE_HANDLE_DH;
1404 if (routeSelection == SecElemRoute)
1405 eeHandle = mActiveEeHandle;
1406 ALOGD ("%s: route to default EE h=0x%X", fn, eeHandle);
1407 SyncEventGuard guard (mRoutingEvent);
1408 nfaStat = NFA_EeSetDefaultProtoRouting (eeHandle, protoMask, 0, 0);
1409 if (nfaStat == NFA_STATUS_OK)
1410 mRoutingEvent.wait ();
1411 else
1412 ALOGE ("%s: fail route to EE; error=0x%X", fn, nfaStat);
1413 }
1414 ALOGD ("%s: exit", fn);
1415 }
1416
1417
1418 /*******************************************************************************
1419 **
1420 ** Function: adjustTechnologyRoutes
1421 **
1422 ** Description: Adjust default routing based on technology in NFC listen mode.
1423 ** isRouteToEe: Whether routing to EE (true) or host (false).
1424 **
1425 ** Returns: None
1426 **
1427 *******************************************************************************/
adjustTechnologyRoutes(RouteDataSet::Database * db,RouteSelection routeSelection)1428 void SecureElement::adjustTechnologyRoutes (RouteDataSet::Database* db, RouteSelection routeSelection)
1429 {
1430 static const char fn [] = "SecureElement::adjustTechnologyRoutes";
1431 ALOGD ("%s: enter", fn);
1432 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
1433 const tNFA_TECHNOLOGY_MASK techMask = NFA_TECHNOLOGY_MASK_A | NFA_TECHNOLOGY_MASK_B;
1434
1435 ///////////////////////
1436 // delete route to host
1437 ///////////////////////
1438 {
1439 ALOGD ("%s: delete route to host", fn);
1440 SyncEventGuard guard (mRoutingEvent);
1441 if ((nfaStat = NFA_EeSetDefaultTechRouting (NFA_EE_HANDLE_DH, 0, 0, 0)) == NFA_STATUS_OK)
1442 mRoutingEvent.wait ();
1443 else
1444 ALOGE ("%s: fail delete route to host; error=0x%X", fn, nfaStat);
1445 }
1446
1447 ///////////////////////
1448 // delete route to every sec elem
1449 ///////////////////////
1450 for (int i=0; i < mActualNumEe; i++)
1451 {
1452 if ((mEeInfo[i].num_interface != 0) &&
1453 (mEeInfo[i].ee_interface[0] != NFC_NFCEE_INTERFACE_HCI_ACCESS) &&
1454 (mEeInfo[i].ee_status == NFA_EE_STATUS_ACTIVE))
1455 {
1456 ALOGD ("%s: delete route to EE h=0x%X", fn, mEeInfo[i].ee_handle);
1457 SyncEventGuard guard (mRoutingEvent);
1458 if ((nfaStat = NFA_EeSetDefaultTechRouting (mEeInfo[i].ee_handle, 0, 0, 0)) == NFA_STATUS_OK)
1459 mRoutingEvent.wait ();
1460 else
1461 ALOGE ("%s: fail delete route to EE; error=0x%X", fn, nfaStat);
1462 }
1463 }
1464
1465 //////////////////////
1466 // configure route for every discovered sec elem
1467 //////////////////////
1468 for (int i=0; i < mActualNumEe; i++)
1469 {
1470 //if sec elem is active
1471 if ((mEeInfo[i].num_interface != 0) &&
1472 (mEeInfo[i].ee_interface[0] != NFC_NFCEE_INTERFACE_HCI_ACCESS) &&
1473 (mEeInfo[i].ee_status == NFA_EE_STATUS_ACTIVE))
1474 {
1475 tNFA_TECHNOLOGY_MASK techsSwitchOn = 0; //all techs that are active at full power
1476 tNFA_TECHNOLOGY_MASK techsSwitchOff = 0; //all techs that are active when phone is turned off
1477 tNFA_TECHNOLOGY_MASK techsBatteryOff = 0; //all techs that are active when there is no power
1478
1479 //for every route in XML, look for tech route;
1480 //collect every tech according to it's desired power mode
1481 for (RouteDataSet::Database::iterator iter = db->begin(); iter != db->end(); iter++)
1482 {
1483 RouteData* routeData = *iter;
1484 RouteDataForTechnology* route = NULL;
1485 if (routeData->mRouteType != RouteData::TechnologyRoute)
1486 continue; //skip other kinds of routing data
1487 route = (RouteDataForTechnology*) (*iter);
1488 if (route->mNfaEeHandle == mEeInfo[i].ee_handle)
1489 {
1490 if (route->mSwitchOn)
1491 techsSwitchOn |= route->mTechnology;
1492 if (route->mSwitchOff)
1493 techsSwitchOff |= route->mTechnology;
1494 if (route->mBatteryOff)
1495 techsBatteryOff |= route->mTechnology;
1496 }
1497 }
1498
1499 if (techsSwitchOn | techsSwitchOff | techsBatteryOff)
1500 {
1501 ALOGD ("%s: route to EE h=0x%X", fn, mEeInfo[i].ee_handle);
1502 SyncEventGuard guard (mRoutingEvent);
1503 nfaStat = NFA_EeSetDefaultTechRouting (mEeInfo[i].ee_handle,
1504 techsSwitchOn, techsSwitchOff, techsBatteryOff);
1505 if (nfaStat == NFA_STATUS_OK)
1506 mRoutingEvent.wait ();
1507 else
1508 ALOGE ("%s: fail route to EE; error=0x%X", fn, nfaStat);
1509 }
1510 } //if sec elem is active
1511 } //for every discovered sec elem
1512
1513 //////////////////////
1514 // configure route to host
1515 //////////////////////
1516 {
1517 tNFA_TECHNOLOGY_MASK techsSwitchOn = 0; //all techs that are active at full power
1518 tNFA_TECHNOLOGY_MASK techsSwitchOff = 0; //all techs that are active when phone is turned off
1519 tNFA_TECHNOLOGY_MASK techsBatteryOff = 0; //all techs that are active when there is no power
1520
1521 //for every route in XML, look for protocol route;
1522 //collect every protocol according to it's desired power mode
1523 for (RouteDataSet::Database::iterator iter = db->begin(); iter != db->end(); iter++)
1524 {
1525 RouteData* routeData = *iter;
1526 RouteDataForTechnology * route = NULL;
1527 if (routeData->mRouteType != RouteData::TechnologyRoute)
1528 continue; //skip other kinds of routing data
1529 route = (RouteDataForTechnology*) (*iter);
1530 if (route->mNfaEeHandle == NFA_EE_HANDLE_DH)
1531 {
1532 if (route->mSwitchOn)
1533 techsSwitchOn |= route->mTechnology;
1534 if (route->mSwitchOff)
1535 techsSwitchOff |= route->mTechnology;
1536 if (route->mBatteryOff)
1537 techsBatteryOff |= route->mTechnology;
1538 }
1539 }
1540
1541 if (techsSwitchOn | techsSwitchOff | techsBatteryOff)
1542 {
1543 ALOGD ("%s: route to EE h=0x%X", fn, NFA_EE_HANDLE_DH);
1544 SyncEventGuard guard (mRoutingEvent);
1545 nfaStat = NFA_EeSetDefaultTechRouting (NFA_EE_HANDLE_DH,
1546 techsSwitchOn, techsSwitchOff, techsBatteryOff);
1547 if (nfaStat == NFA_STATUS_OK)
1548 mRoutingEvent.wait ();
1549 else
1550 ALOGE ("%s: fail route to EE; error=0x%X", fn, nfaStat);
1551 }
1552 }
1553
1554 //////////////////////
1555 // if route database is empty, setup a default route
1556 //////////////////////
1557 if (db->empty())
1558 {
1559 tNFA_HANDLE eeHandle = NFA_EE_HANDLE_DH;
1560 if (routeSelection == SecElemRoute)
1561 eeHandle = mActiveEeHandle;
1562 ALOGD ("%s: route to default EE h=0x%X", fn, eeHandle);
1563 SyncEventGuard guard (mRoutingEvent);
1564 nfaStat = NFA_EeSetDefaultTechRouting (eeHandle, techMask, 0, 0);
1565 if (nfaStat == NFA_STATUS_OK)
1566 mRoutingEvent.wait ();
1567 else
1568 ALOGE ("%s: fail route to EE; error=0x%X", fn, nfaStat);
1569 }
1570 ALOGD ("%s: exit", fn);
1571 }
1572
1573
1574 /*******************************************************************************
1575 **
1576 ** Function: nfaEeCallback
1577 **
1578 ** Description: Receive execution environment-related events from stack.
1579 ** event: Event code.
1580 ** eventData: Event data.
1581 **
1582 ** Returns: None
1583 **
1584 *******************************************************************************/
nfaEeCallback(tNFA_EE_EVT event,tNFA_EE_CBACK_DATA * eventData)1585 void SecureElement::nfaEeCallback (tNFA_EE_EVT event, tNFA_EE_CBACK_DATA* eventData)
1586 {
1587 static const char fn [] = "SecureElement::nfaEeCallback";
1588
1589 switch (event)
1590 {
1591 case NFA_EE_REGISTER_EVT:
1592 {
1593 SyncEventGuard guard (sSecElem.mEeRegisterEvent);
1594 ALOGD ("%s: NFA_EE_REGISTER_EVT; status=%u", fn, eventData->ee_register);
1595 sSecElem.mEeRegisterEvent.notifyOne();
1596 }
1597 break;
1598
1599 case NFA_EE_MODE_SET_EVT:
1600 {
1601 ALOGD ("%s: NFA_EE_MODE_SET_EVT; status: 0x%04X handle: 0x%04X mActiveEeHandle: 0x%04X", fn,
1602 eventData->mode_set.status, eventData->mode_set.ee_handle, sSecElem.mActiveEeHandle);
1603
1604 if (eventData->mode_set.status == NFA_STATUS_OK)
1605 {
1606 tNFA_EE_INFO *pEE = sSecElem.findEeByHandle (eventData->mode_set.ee_handle);
1607 if (pEE)
1608 {
1609 pEE->ee_status ^= 1;
1610 ALOGD ("%s: NFA_EE_MODE_SET_EVT; pEE->ee_status: %s (0x%04x)", fn, SecureElement::eeStatusToString(pEE->ee_status), pEE->ee_status);
1611 }
1612 else
1613 ALOGE ("%s: NFA_EE_MODE_SET_EVT; EE: 0x%04x not found. mActiveEeHandle: 0x%04x", fn, eventData->mode_set.ee_handle, sSecElem.mActiveEeHandle);
1614 }
1615 SyncEventGuard guard (sSecElem.mEeSetModeEvent);
1616 sSecElem.mEeSetModeEvent.notifyOne();
1617 }
1618 break;
1619
1620 case NFA_EE_SET_TECH_CFG_EVT:
1621 {
1622 ALOGD ("%s: NFA_EE_SET_TECH_CFG_EVT; status=0x%X", fn, eventData->status);
1623 SyncEventGuard guard (sSecElem.mRoutingEvent);
1624 sSecElem.mRoutingEvent.notifyOne ();
1625 }
1626 break;
1627
1628 case NFA_EE_SET_PROTO_CFG_EVT:
1629 {
1630 ALOGD ("%s: NFA_EE_SET_PROTO_CFG_EVT; status=0x%X", fn, eventData->status);
1631 SyncEventGuard guard (sSecElem.mRoutingEvent);
1632 sSecElem.mRoutingEvent.notifyOne ();
1633 }
1634 break;
1635
1636 case NFA_EE_ACTION_EVT:
1637 {
1638 tNFA_EE_ACTION& action = eventData->action;
1639 if (action.trigger == NFC_EE_TRIG_SELECT)
1640 ALOGD ("%s: NFA_EE_ACTION_EVT; h=0x%X; trigger=select (0x%X)", fn, action.ee_handle, action.trigger);
1641 else if (action.trigger == NFC_EE_TRIG_APP_INIT)
1642 {
1643 tNFC_APP_INIT& app_init = action.param.app_init;
1644 ALOGD ("%s: NFA_EE_ACTION_EVT; h=0x%X; trigger=app-init (0x%X); aid len=%u; data len=%u", fn,
1645 action.ee_handle, action.trigger, app_init.len_aid, app_init.len_data);
1646 //if app-init operation is successful;
1647 //app_init.data[] contains two bytes, which are the status codes of the event;
1648 //app_init.data[] does not contain an APDU response;
1649 //see EMV Contactless Specification for Payment Systems; Book B; Entry Point Specification;
1650 //version 2.1; March 2011; section 3.3.3.5;
1651 if ( (app_init.len_data > 1) &&
1652 (app_init.data[0] == 0x90) &&
1653 (app_init.data[1] == 0x00) )
1654 {
1655 sSecElem.notifyTransactionListenersOfAid (app_init.aid, app_init.len_aid);
1656 }
1657 }
1658 else if (action.trigger == NFC_EE_TRIG_RF_PROTOCOL)
1659 ALOGD ("%s: NFA_EE_ACTION_EVT; h=0x%X; trigger=rf protocol (0x%X)", fn, action.ee_handle, action.trigger);
1660 else if (action.trigger == NFC_EE_TRIG_RF_TECHNOLOGY)
1661 ALOGD ("%s: NFA_EE_ACTION_EVT; h=0x%X; trigger=rf tech (0x%X)", fn, action.ee_handle, action.trigger);
1662 else
1663 ALOGE ("%s: NFA_EE_ACTION_EVT; h=0x%X; unknown trigger (0x%X)", fn, action.ee_handle, action.trigger);
1664 }
1665 break;
1666
1667 case NFA_EE_DISCOVER_REQ_EVT:
1668 ALOGD ("%s: NFA_EE_DISCOVER_REQ_EVT; status=0x%X; num ee=%u", __FUNCTION__,
1669 eventData->discover_req.status, eventData->discover_req.num_ee);
1670 sSecElem.storeUiccInfo (eventData->discover_req);
1671 break;
1672
1673 case NFA_EE_NO_CB_ERR_EVT:
1674 ALOGD ("%s: NFA_EE_NO_CB_ERR_EVT status=%u", fn, eventData->status);
1675 break;
1676
1677 case NFA_EE_ADD_AID_EVT:
1678 {
1679 ALOGD ("%s: NFA_EE_ADD_AID_EVT status=%u", fn, eventData->status);
1680 SyncEventGuard guard (sSecElem.mAidAddRemoveEvent);
1681 sSecElem.mAidAddRemoveEvent.notifyOne ();
1682 }
1683 break;
1684
1685 case NFA_EE_REMOVE_AID_EVT:
1686 {
1687 ALOGD ("%s: NFA_EE_REMOVE_AID_EVT status=%u", fn, eventData->status);
1688 SyncEventGuard guard (sSecElem.mAidAddRemoveEvent);
1689 sSecElem.mAidAddRemoveEvent.notifyOne ();
1690 }
1691 break;
1692
1693 case NFA_EE_NEW_EE_EVT:
1694 {
1695 ALOGD ("%s: NFA_EE_NEW_EE_EVT h=0x%X; status=%u", fn,
1696 eventData->new_ee.ee_handle, eventData->new_ee.ee_status);
1697 // Indicate there are new EE
1698 sSecElem.mbNewEE = true;
1699 }
1700 break;
1701
1702 default:
1703 ALOGE ("%s: unknown event=%u ????", fn, event);
1704 break;
1705 }
1706 }
1707
1708 /*******************************************************************************
1709 **
1710 ** Function getSeVerInfo
1711 **
1712 ** Description Gets version information and id for a secure element. The
1713 ** seIndex parmeter is the zero based index of the secure
1714 ** element to get verion info for. The version infommation
1715 ** is returned as a string int the verInfo parameter.
1716 **
1717 ** Returns ture on success, false on failure
1718 **
1719 *******************************************************************************/
getSeVerInfo(int seIndex,char * verInfo,int verInfoSz,UINT8 * seid)1720 bool SecureElement::getSeVerInfo(int seIndex, char * verInfo, int verInfoSz, UINT8 * seid)
1721 {
1722 ALOGD("%s: enter, seIndex=%d", __FUNCTION__, seIndex);
1723
1724 if (seIndex > (mActualNumEe-1))
1725 {
1726 ALOGE("%s: invalid se index: %d, only %d SEs in system", __FUNCTION__, seIndex, mActualNumEe);
1727 return false;
1728 }
1729
1730 *seid = mEeInfo[seIndex].ee_handle;
1731
1732 if ((mEeInfo[seIndex].num_interface == 0) || (mEeInfo[seIndex].ee_interface[0] == NCI_NFCEE_INTERFACE_HCI_ACCESS) )
1733 {
1734 return false;
1735 }
1736
1737 strncpy(verInfo, "Version info not available", verInfoSz-1);
1738 verInfo[verInfoSz-1] = '\0';
1739
1740 UINT8 pipe = (mEeInfo[seIndex].ee_handle == EE_HANDLE_0xF3) ? 0x70 : 0x71;
1741 UINT8 host = (pipe == STATIC_PIPE_0x70) ? 0x02 : 0x03;
1742 UINT8 gate = (pipe == STATIC_PIPE_0x70) ? 0xF0 : 0xF1;
1743
1744 tNFA_STATUS nfaStat = NFA_HciAddStaticPipe(mNfaHciHandle, host, gate, pipe);
1745 if (nfaStat != NFA_STATUS_OK)
1746 {
1747 ALOGE ("%s: NFA_HciAddStaticPipe() failed, pipe = 0x%x, error=0x%X", __FUNCTION__, pipe, nfaStat);
1748 return true;
1749 }
1750
1751 SyncEventGuard guard (mVerInfoEvent);
1752 if (NFA_STATUS_OK == (nfaStat = NFA_HciGetRegistry (mNfaHciHandle, pipe, 0x02)))
1753 {
1754 if (false == mVerInfoEvent.wait(200))
1755 {
1756 ALOGE ("%s: wait response timeout", __FUNCTION__);
1757 }
1758 else
1759 {
1760 snprintf(verInfo, verInfoSz-1, "Oberthur OS S/N: 0x%02x%02x%02x", mVerInfo[0], mVerInfo[1], mVerInfo[2]);
1761 verInfo[verInfoSz-1] = '\0';
1762 }
1763 }
1764 else
1765 {
1766 ALOGE ("%s: NFA_HciGetRegistry () failed: 0x%X", __FUNCTION__, nfaStat);
1767 }
1768 return true;
1769 }
1770
1771 /*******************************************************************************
1772 **
1773 ** Function getActualNumEe
1774 **
1775 ** Description Returns number of secure elements we know about.
1776 **
1777 ** Returns Number of secure elements we know about.
1778 **
1779 *******************************************************************************/
getActualNumEe()1780 UINT8 SecureElement::getActualNumEe()
1781 {
1782 return mActualNumEe;
1783 }
1784
1785 /*******************************************************************************
1786 **
1787 ** Function: nfaHciCallback
1788 **
1789 ** Description: Receive Host Controller Interface-related events from stack.
1790 ** event: Event code.
1791 ** eventData: Event data.
1792 **
1793 ** Returns: None
1794 **
1795 *******************************************************************************/
nfaHciCallback(tNFA_HCI_EVT event,tNFA_HCI_EVT_DATA * eventData)1796 void SecureElement::nfaHciCallback (tNFA_HCI_EVT event, tNFA_HCI_EVT_DATA* eventData)
1797 {
1798 static const char fn [] = "SecureElement::nfaHciCallback";
1799 ALOGD ("%s: event=0x%X", fn, event);
1800
1801 switch (event)
1802 {
1803 case NFA_HCI_REGISTER_EVT:
1804 {
1805 ALOGD ("%s: NFA_HCI_REGISTER_EVT; status=0x%X; handle=0x%X", fn,
1806 eventData->hci_register.status, eventData->hci_register.hci_handle);
1807 SyncEventGuard guard (sSecElem.mHciRegisterEvent);
1808 sSecElem.mNfaHciHandle = eventData->hci_register.hci_handle;
1809 sSecElem.mHciRegisterEvent.notifyOne();
1810 }
1811 break;
1812
1813 case NFA_HCI_ALLOCATE_GATE_EVT:
1814 {
1815 ALOGD ("%s: NFA_HCI_ALLOCATE_GATE_EVT; status=0x%X; gate=0x%X", fn, eventData->status, eventData->allocated.gate);
1816 SyncEventGuard guard (sSecElem.mAllocateGateEvent);
1817 sSecElem.mCommandStatus = eventData->status;
1818 sSecElem.mNewSourceGate = (eventData->allocated.status == NFA_STATUS_OK) ? eventData->allocated.gate : 0;
1819 sSecElem.mAllocateGateEvent.notifyOne();
1820 }
1821 break;
1822
1823 case NFA_HCI_DEALLOCATE_GATE_EVT:
1824 {
1825 tNFA_HCI_DEALLOCATE_GATE& deallocated = eventData->deallocated;
1826 ALOGD ("%s: NFA_HCI_DEALLOCATE_GATE_EVT; status=0x%X; gate=0x%X", fn, deallocated.status, deallocated.gate);
1827 SyncEventGuard guard (sSecElem.mDeallocateGateEvent);
1828 sSecElem.mDeallocateGateEvent.notifyOne();
1829 }
1830 break;
1831
1832 case NFA_HCI_GET_GATE_PIPE_LIST_EVT:
1833 {
1834 ALOGD ("%s: NFA_HCI_GET_GATE_PIPE_LIST_EVT; status=0x%X; num_pipes: %u num_gates: %u", fn,
1835 eventData->gates_pipes.status, eventData->gates_pipes.num_pipes, eventData->gates_pipes.num_gates);
1836 SyncEventGuard guard (sSecElem.mPipeListEvent);
1837 sSecElem.mCommandStatus = eventData->gates_pipes.status;
1838 sSecElem.mHciCfg = eventData->gates_pipes;
1839 sSecElem.mPipeListEvent.notifyOne();
1840 }
1841 break;
1842
1843 case NFA_HCI_CREATE_PIPE_EVT:
1844 {
1845 ALOGD ("%s: NFA_HCI_CREATE_PIPE_EVT; status=0x%X; pipe=0x%X; src gate=0x%X; dest host=0x%X; dest gate=0x%X", fn,
1846 eventData->created.status, eventData->created.pipe, eventData->created.source_gate, eventData->created.dest_host, eventData->created.dest_gate);
1847 SyncEventGuard guard (sSecElem.mCreatePipeEvent);
1848 sSecElem.mCommandStatus = eventData->created.status;
1849 sSecElem.mNewPipeId = eventData->created.pipe;
1850 sSecElem.mCreatePipeEvent.notifyOne();
1851 }
1852 break;
1853
1854 case NFA_HCI_OPEN_PIPE_EVT:
1855 {
1856 ALOGD ("%s: NFA_HCI_OPEN_PIPE_EVT; status=0x%X; pipe=0x%X", fn, eventData->opened.status, eventData->opened.pipe);
1857 SyncEventGuard guard (sSecElem.mPipeOpenedEvent);
1858 sSecElem.mCommandStatus = eventData->opened.status;
1859 sSecElem.mPipeOpenedEvent.notifyOne();
1860 }
1861 break;
1862
1863 case NFA_HCI_EVENT_SENT_EVT:
1864 ALOGD ("%s: NFA_HCI_EVENT_SENT_EVT; status=0x%X", fn, eventData->evt_sent.status);
1865 break;
1866
1867 case NFA_HCI_RSP_RCVD_EVT: //response received from secure element
1868 {
1869 tNFA_HCI_RSP_RCVD& rsp_rcvd = eventData->rsp_rcvd;
1870 ALOGD ("%s: NFA_HCI_RSP_RCVD_EVT; status: 0x%X; code: 0x%X; pipe: 0x%X; len: %u", fn,
1871 rsp_rcvd.status, rsp_rcvd.rsp_code, rsp_rcvd.pipe, rsp_rcvd.rsp_len);
1872 }
1873 break;
1874
1875 case NFA_HCI_GET_REG_RSP_EVT :
1876 ALOGD ("%s: NFA_HCI_GET_REG_RSP_EVT; status: 0x%X; pipe: 0x%X, len: %d", fn,
1877 eventData->registry.status, eventData->registry.pipe, eventData->registry.data_len);
1878 if (eventData->registry.data_len >= 19 && ((eventData->registry.pipe == STATIC_PIPE_0x70) || (eventData->registry.pipe == STATIC_PIPE_0x71)))
1879 {
1880 SyncEventGuard guard (sSecElem.mVerInfoEvent);
1881 // Oberthur OS version is in bytes 16,17, and 18
1882 sSecElem.mVerInfo[0] = eventData->registry.reg_data[16];
1883 sSecElem.mVerInfo[1] = eventData->registry.reg_data[17];
1884 sSecElem.mVerInfo[2] = eventData->registry.reg_data[18];
1885 sSecElem.mVerInfoEvent.notifyOne ();
1886 }
1887 break;
1888
1889 case NFA_HCI_EVENT_RCVD_EVT:
1890 ALOGD ("%s: NFA_HCI_EVENT_RCVD_EVT; code: 0x%X; pipe: 0x%X; data len: %u", fn,
1891 eventData->rcvd_evt.evt_code, eventData->rcvd_evt.pipe, eventData->rcvd_evt.evt_len);
1892 if ((eventData->rcvd_evt.pipe == STATIC_PIPE_0x70) || (eventData->rcvd_evt.pipe == STATIC_PIPE_0x71))
1893 {
1894 ALOGD ("%s: NFA_HCI_EVENT_RCVD_EVT; data from static pipe", fn);
1895 SyncEventGuard guard (sSecElem.mTransceiveEvent);
1896 sSecElem.mActualResponseSize = (eventData->rcvd_evt.evt_len > MAX_RESPONSE_SIZE) ? MAX_RESPONSE_SIZE : eventData->rcvd_evt.evt_len;
1897 sSecElem.mTransceiveEvent.notifyOne ();
1898 }
1899 else if (eventData->rcvd_evt.evt_code == NFA_HCI_EVT_POST_DATA)
1900 {
1901 ALOGD ("%s: NFA_HCI_EVENT_RCVD_EVT; NFA_HCI_EVT_POST_DATA", fn);
1902 SyncEventGuard guard (sSecElem.mTransceiveEvent);
1903 sSecElem.mActualResponseSize = (eventData->rcvd_evt.evt_len > MAX_RESPONSE_SIZE) ? MAX_RESPONSE_SIZE : eventData->rcvd_evt.evt_len;
1904 sSecElem.mTransceiveEvent.notifyOne ();
1905 }
1906 else if (eventData->rcvd_evt.evt_code == NFA_HCI_EVT_TRANSACTION)
1907 {
1908 ALOGD ("%s: NFA_HCI_EVENT_RCVD_EVT; NFA_HCI_EVT_TRANSACTION", fn);
1909 // If we got an AID, notify any listeners
1910 if ((eventData->rcvd_evt.evt_len > 3) && (eventData->rcvd_evt.p_evt_buf[0] == 0x81) )
1911 sSecElem.notifyTransactionListenersOfAid (&eventData->rcvd_evt.p_evt_buf[2], eventData->rcvd_evt.p_evt_buf[1]);
1912 }
1913 break;
1914
1915 case NFA_HCI_SET_REG_RSP_EVT: //received response to write registry command
1916 {
1917 tNFA_HCI_REGISTRY& registry = eventData->registry;
1918 ALOGD ("%s: NFA_HCI_SET_REG_RSP_EVT; status=0x%X; pipe=0x%X", fn, registry.status, registry.pipe);
1919 SyncEventGuard guard (sSecElem.mRegistryEvent);
1920 sSecElem.mRegistryEvent.notifyOne ();
1921 break;
1922 }
1923
1924 default:
1925 ALOGE ("%s: unknown event code=0x%X ????", fn, event);
1926 break;
1927 }
1928 }
1929
1930
1931 /*******************************************************************************
1932 **
1933 ** Function: findEeByHandle
1934 **
1935 ** Description: Find information about an execution environment.
1936 ** eeHandle: Handle to execution environment.
1937 **
1938 ** Returns: Information about an execution environment.
1939 **
1940 *******************************************************************************/
findEeByHandle(tNFA_HANDLE eeHandle)1941 tNFA_EE_INFO *SecureElement::findEeByHandle (tNFA_HANDLE eeHandle)
1942 {
1943 for (UINT8 xx = 0; xx < mActualNumEe; xx++)
1944 {
1945 if (mEeInfo[xx].ee_handle == eeHandle)
1946 return (&mEeInfo[xx]);
1947 }
1948 return (NULL);
1949 }
1950
1951
1952 /*******************************************************************************
1953 **
1954 ** Function: getDefaultEeHandle
1955 **
1956 ** Description: Get the handle to the execution environment.
1957 **
1958 ** Returns: Handle to the execution environment.
1959 **
1960 *******************************************************************************/
getDefaultEeHandle()1961 tNFA_HANDLE SecureElement::getDefaultEeHandle ()
1962 {
1963 UINT16 overrideEeHandle = NFA_HANDLE_GROUP_EE | mActiveSeOverride;
1964 // Find the first EE that is not the HCI Access i/f.
1965 for (UINT8 xx = 0; xx < mActualNumEe; xx++)
1966 {
1967 if (mActiveSeOverride && (overrideEeHandle != mEeInfo[xx].ee_handle))
1968 continue; //skip all the EE's that are ignored
1969 if ((mEeInfo[xx].num_interface != 0) &&
1970 (mEeInfo[xx].ee_interface[0] != NCI_NFCEE_INTERFACE_HCI_ACCESS) &&
1971 (mEeInfo[xx].ee_status != NFC_NFCEE_STATUS_INACTIVE))
1972 return (mEeInfo[xx].ee_handle);
1973 }
1974 return NFA_HANDLE_INVALID;
1975 }
1976
1977
1978 /*******************************************************************************
1979 **
1980 ** Function: findUiccByHandle
1981 **
1982 ** Description: Find information about an execution environment.
1983 ** eeHandle: Handle of the execution environment.
1984 **
1985 ** Returns: Information about the execution environment.
1986 **
1987 *******************************************************************************/
findUiccByHandle(tNFA_HANDLE eeHandle)1988 tNFA_EE_DISCOVER_INFO *SecureElement::findUiccByHandle (tNFA_HANDLE eeHandle)
1989 {
1990 for (UINT8 index = 0; index < mUiccInfo.num_ee; index++)
1991 {
1992 if (mUiccInfo.ee_disc_info[index].ee_handle == eeHandle)
1993 {
1994 return (&mUiccInfo.ee_disc_info[index]);
1995 }
1996 }
1997 ALOGE ("SecureElement::findUiccByHandle: ee h=0x%4x not found", eeHandle);
1998 return NULL;
1999 }
2000
2001
2002 /*******************************************************************************
2003 **
2004 ** Function: eeStatusToString
2005 **
2006 ** Description: Convert status code to status text.
2007 ** status: Status code
2008 **
2009 ** Returns: None
2010 **
2011 *******************************************************************************/
eeStatusToString(UINT8 status)2012 const char* SecureElement::eeStatusToString (UINT8 status)
2013 {
2014 switch (status)
2015 {
2016 case NFC_NFCEE_STATUS_ACTIVE:
2017 return("Connected/Active");
2018 case NFC_NFCEE_STATUS_INACTIVE:
2019 return("Connected/Inactive");
2020 case NFC_NFCEE_STATUS_REMOVED:
2021 return("Removed");
2022 }
2023 return("?? Unknown ??");
2024 }
2025
2026
2027 /*******************************************************************************
2028 **
2029 ** Function: connectionEventHandler
2030 **
2031 ** Description: Receive card-emulation related events from stack.
2032 ** event: Event code.
2033 ** eventData: Event data.
2034 **
2035 ** Returns: None
2036 **
2037 *******************************************************************************/
connectionEventHandler(UINT8 event,tNFA_CONN_EVT_DATA * eventData)2038 void SecureElement::connectionEventHandler (UINT8 event, tNFA_CONN_EVT_DATA* eventData)
2039 {
2040 switch (event)
2041 {
2042 case NFA_CE_UICC_LISTEN_CONFIGURED_EVT:
2043 {
2044 SyncEventGuard guard (mUiccListenEvent);
2045 mUiccListenEvent.notifyOne ();
2046 }
2047 break;
2048 }
2049 }
2050
2051
2052 /*******************************************************************************
2053 **
2054 ** Function: routeToSecureElement
2055 **
2056 ** Description: Adjust controller's listen-mode routing table so transactions
2057 ** are routed to the secure elements.
2058 **
2059 ** Returns: True if ok.
2060 **
2061 *******************************************************************************/
routeToSecureElement()2062 bool SecureElement::routeToSecureElement ()
2063 {
2064 static const char fn [] = "SecureElement::routeToSecureElement";
2065 ALOGD ("%s: enter", fn);
2066 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
2067 tNFA_TECHNOLOGY_MASK tech_mask = NFA_TECHNOLOGY_MASK_A | NFA_TECHNOLOGY_MASK_B;
2068 bool retval = false;
2069
2070 if (! mIsInit)
2071 {
2072 ALOGE ("%s: not init", fn);
2073 return false;
2074 }
2075
2076 if (mCurrentRouteSelection == SecElemRoute)
2077 {
2078 ALOGE ("%s: already sec elem route", fn);
2079 return true;
2080 }
2081
2082 if (mActiveEeHandle == NFA_HANDLE_INVALID)
2083 {
2084 ALOGE ("%s: invalid EE handle", fn);
2085 return false;
2086 }
2087
2088 adjustRoutes (SecElemRoute);
2089
2090 {
2091 unsigned long num = 0;
2092 if (GetNumValue("UICC_LISTEN_TECH_MASK", &num, sizeof(num)))
2093 tech_mask = num;
2094 ALOGD ("%s: start UICC listen; h=0x%X; tech mask=0x%X", fn, mActiveEeHandle, tech_mask);
2095 SyncEventGuard guard (mUiccListenEvent);
2096 nfaStat = NFA_CeConfigureUiccListenTech (mActiveEeHandle, tech_mask);
2097 if (nfaStat == NFA_STATUS_OK)
2098 {
2099 mUiccListenEvent.wait ();
2100 retval = true;
2101 }
2102 else
2103 ALOGE ("%s: fail to start UICC listen", fn);
2104 }
2105
2106 ALOGD ("%s: exit; ok=%u", fn, retval);
2107 return retval;
2108 }
2109
2110
2111 /*******************************************************************************
2112 **
2113 ** Function: routeToDefault
2114 **
2115 ** Description: Adjust controller's listen-mode routing table so transactions
2116 ** are routed to the default destination.
2117 **
2118 ** Returns: True if ok.
2119 **
2120 *******************************************************************************/
routeToDefault()2121 bool SecureElement::routeToDefault ()
2122 {
2123 static const char fn [] = "SecureElement::routeToDefault";
2124 tNFA_STATUS nfaStat = NFA_STATUS_FAILED;
2125 bool retval = false;
2126
2127 ALOGD ("%s: enter", fn);
2128 if (! mIsInit)
2129 {
2130 ALOGE ("%s: not init", fn);
2131 return false;
2132 }
2133
2134 if (mCurrentRouteSelection == DefaultRoute)
2135 {
2136 ALOGD ("%s: already default route", fn);
2137 return true;
2138 }
2139
2140 if (mActiveEeHandle != NFA_HANDLE_INVALID)
2141 {
2142 ALOGD ("%s: stop UICC listen; EE h=0x%X", fn, mActiveEeHandle);
2143 SyncEventGuard guard (mUiccListenEvent);
2144 nfaStat = NFA_CeConfigureUiccListenTech (mActiveEeHandle, 0);
2145 if (nfaStat == NFA_STATUS_OK)
2146 {
2147 mUiccListenEvent.wait ();
2148 retval = true;
2149 }
2150 else
2151 ALOGE ("%s: fail to stop UICC listen", fn);
2152 }
2153 else
2154 retval = true;
2155
2156 adjustRoutes (DefaultRoute);
2157
2158 ALOGD ("%s: exit; ok=%u", fn, retval);
2159 return retval;
2160 }
2161
2162
2163 /*******************************************************************************
2164 **
2165 ** Function: isBusy
2166 **
2167 ** Description: Whether controller is routing listen-mode events to
2168 ** secure elements or a pipe is connected.
2169 **
2170 ** Returns: True if either case is true.
2171 **
2172 *******************************************************************************/
isBusy()2173 bool SecureElement::isBusy ()
2174 {
2175 bool retval = (mCurrentRouteSelection == SecElemRoute) || mIsPiping;
2176 ALOGD ("SecureElement::isBusy: %u", retval);
2177 return retval;
2178 }
2179
2180