1/* 2 * Copyright (C) 2007 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 17package com.android.internal.telephony.cat; 18 19import android.content.Context; 20import android.content.Intent; 21import android.content.pm.PackageManager; 22import android.content.pm.ResolveInfo; 23import android.content.res.Resources.NotFoundException; 24import android.os.AsyncResult; 25import android.os.Handler; 26import android.os.HandlerThread; 27import android.os.Message; 28import android.os.SystemProperties; 29import android.telephony.SubscriptionManager; 30import android.telephony.TelephonyManager; 31 32import com.android.internal.telephony.CommandsInterface; 33import com.android.internal.telephony.PhoneConstants; 34import com.android.internal.telephony.SubscriptionController; 35import com.android.internal.telephony.uicc.IccFileHandler; 36import com.android.internal.telephony.uicc.IccRecords; 37import com.android.internal.telephony.uicc.IccUtils; 38import com.android.internal.telephony.uicc.UiccCard; 39import com.android.internal.telephony.uicc.UiccCardApplication; 40import com.android.internal.telephony.uicc.IccCardStatus.CardState; 41import com.android.internal.telephony.uicc.IccRefreshResponse; 42import com.android.internal.telephony.uicc.UiccController; 43 44import java.io.ByteArrayOutputStream; 45import java.util.List; 46import java.util.Locale; 47 48import static com.android.internal.telephony.cat.CatCmdMessage. 49 SetupEventListConstants.IDLE_SCREEN_AVAILABLE_EVENT; 50import static com.android.internal.telephony.cat.CatCmdMessage. 51 SetupEventListConstants.LANGUAGE_SELECTION_EVENT; 52 53class RilMessage { 54 int mId; 55 Object mData; 56 ResultCode mResCode; 57 58 RilMessage(int msgId, String rawData) { 59 mId = msgId; 60 mData = rawData; 61 } 62 63 RilMessage(RilMessage other) { 64 mId = other.mId; 65 mData = other.mData; 66 mResCode = other.mResCode; 67 } 68} 69 70/** 71 * Class that implements SIM Toolkit Telephony Service. Interacts with the RIL 72 * and application. 73 * 74 * {@hide} 75 */ 76public class CatService extends Handler implements AppInterface { 77 private static final boolean DBG = false; 78 79 // Class members 80 private static IccRecords mIccRecords; 81 private static UiccCardApplication mUiccApplication; 82 83 // Service members. 84 // Protects singleton instance lazy initialization. 85 private static final Object sInstanceLock = new Object(); 86 private static CatService[] sInstance = null; 87 private CommandsInterface mCmdIf; 88 private Context mContext; 89 private CatCmdMessage mCurrntCmd = null; 90 private CatCmdMessage mMenuCmd = null; 91 92 private RilMessageDecoder mMsgDecoder = null; 93 private boolean mStkAppInstalled = false; 94 95 private UiccController mUiccController; 96 private CardState mCardState = CardState.CARDSTATE_ABSENT; 97 98 // Service constants. 99 protected static final int MSG_ID_SESSION_END = 1; 100 protected static final int MSG_ID_PROACTIVE_COMMAND = 2; 101 protected static final int MSG_ID_EVENT_NOTIFY = 3; 102 protected static final int MSG_ID_CALL_SETUP = 4; 103 static final int MSG_ID_REFRESH = 5; 104 static final int MSG_ID_RESPONSE = 6; 105 static final int MSG_ID_SIM_READY = 7; 106 107 protected static final int MSG_ID_ICC_CHANGED = 8; 108 protected static final int MSG_ID_ALPHA_NOTIFY = 9; 109 110 static final int MSG_ID_RIL_MSG_DECODED = 10; 111 112 // Events to signal SIM presence or absent in the device. 113 private static final int MSG_ID_ICC_RECORDS_LOADED = 20; 114 115 //Events to signal SIM REFRESH notificatations 116 private static final int MSG_ID_ICC_REFRESH = 30; 117 118 private static final int DEV_ID_KEYPAD = 0x01; 119 private static final int DEV_ID_DISPLAY = 0x02; 120 private static final int DEV_ID_UICC = 0x81; 121 private static final int DEV_ID_TERMINAL = 0x82; 122 private static final int DEV_ID_NETWORK = 0x83; 123 124 static final String STK_DEFAULT = "Default Message"; 125 126 private HandlerThread mHandlerThread; 127 private int mSlotId; 128 129 /* For multisim catservice should not be singleton */ 130 private CatService(CommandsInterface ci, UiccCardApplication ca, IccRecords ir, 131 Context context, IccFileHandler fh, UiccCard ic, int slotId) { 132 if (ci == null || ca == null || ir == null || context == null || fh == null 133 || ic == null) { 134 throw new NullPointerException( 135 "Service: Input parameters must not be null"); 136 } 137 mCmdIf = ci; 138 mContext = context; 139 mSlotId = slotId; 140 mHandlerThread = new HandlerThread("Cat Telephony service" + slotId); 141 mHandlerThread.start(); 142 143 // Get the RilMessagesDecoder for decoding the messages. 144 mMsgDecoder = RilMessageDecoder.getInstance(this, fh, slotId); 145 if (null == mMsgDecoder) { 146 CatLog.d(this, "Null RilMessageDecoder instance"); 147 return; 148 } 149 mMsgDecoder.start(); 150 151 // Register ril events handling. 152 mCmdIf.setOnCatSessionEnd(this, MSG_ID_SESSION_END, null); 153 mCmdIf.setOnCatProactiveCmd(this, MSG_ID_PROACTIVE_COMMAND, null); 154 mCmdIf.setOnCatEvent(this, MSG_ID_EVENT_NOTIFY, null); 155 mCmdIf.setOnCatCallSetUp(this, MSG_ID_CALL_SETUP, null); 156 //mCmdIf.setOnSimRefresh(this, MSG_ID_REFRESH, null); 157 158 mCmdIf.registerForIccRefresh(this, MSG_ID_ICC_REFRESH, null); 159 mCmdIf.setOnCatCcAlphaNotify(this, MSG_ID_ALPHA_NOTIFY, null); 160 161 mIccRecords = ir; 162 mUiccApplication = ca; 163 164 // Register for SIM ready event. 165 mIccRecords.registerForRecordsLoaded(this, MSG_ID_ICC_RECORDS_LOADED, null); 166 CatLog.d(this, "registerForRecordsLoaded slotid=" + mSlotId + " instance:" + this); 167 168 169 mUiccController = UiccController.getInstance(); 170 mUiccController.registerForIccChanged(this, MSG_ID_ICC_CHANGED, null); 171 172 // Check if STK application is available 173 mStkAppInstalled = isStkAppInstalled(); 174 175 CatLog.d(this, "Running CAT service on Slotid: " + mSlotId + 176 ". STK app installed:" + mStkAppInstalled); 177 } 178 179 /** 180 * Used for instantiating the Service from the Card. 181 * 182 * @param ci CommandsInterface object 183 * @param context phone app context 184 * @param ic Icc card 185 * @param slotId to know the index of card 186 * @return The only Service object in the system 187 */ 188 public static CatService getInstance(CommandsInterface ci, 189 Context context, UiccCard ic, int slotId) { 190 UiccCardApplication ca = null; 191 IccFileHandler fh = null; 192 IccRecords ir = null; 193 if (ic != null) { 194 /* Since Cat is not tied to any application, but rather is Uicc application 195 * in itself - just get first FileHandler and IccRecords object 196 */ 197 ca = ic.getApplicationIndex(0); 198 if (ca != null) { 199 fh = ca.getIccFileHandler(); 200 ir = ca.getIccRecords(); 201 } 202 } 203 204 synchronized (sInstanceLock) { 205 if (sInstance == null) { 206 int simCount = TelephonyManager.getDefault().getSimCount(); 207 sInstance = new CatService[simCount]; 208 for (int i = 0; i < simCount; i++) { 209 sInstance[i] = null; 210 } 211 } 212 if (sInstance[slotId] == null) { 213 if (ci == null || ca == null || ir == null || context == null || fh == null 214 || ic == null) { 215 return null; 216 } 217 218 sInstance[slotId] = new CatService(ci, ca, ir, context, fh, ic, slotId); 219 } else if ((ir != null) && (mIccRecords != ir)) { 220 if (mIccRecords != null) { 221 mIccRecords.unregisterForRecordsLoaded(sInstance[slotId]); 222 } 223 224 mIccRecords = ir; 225 mUiccApplication = ca; 226 227 mIccRecords.registerForRecordsLoaded(sInstance[slotId], 228 MSG_ID_ICC_RECORDS_LOADED, null); 229 CatLog.d(sInstance[slotId], "registerForRecordsLoaded slotid=" + slotId 230 + " instance:" + sInstance[slotId]); 231 } 232 return sInstance[slotId]; 233 } 234 } 235 236 public void dispose() { 237 synchronized (sInstanceLock) { 238 CatLog.d(this, "Disposing CatService object"); 239 mIccRecords.unregisterForRecordsLoaded(this); 240 241 // Clean up stk icon if dispose is called 242 broadcastCardStateAndIccRefreshResp(CardState.CARDSTATE_ABSENT, null); 243 244 mCmdIf.unSetOnCatSessionEnd(this); 245 mCmdIf.unSetOnCatProactiveCmd(this); 246 mCmdIf.unSetOnCatEvent(this); 247 mCmdIf.unSetOnCatCallSetUp(this); 248 mCmdIf.unSetOnCatCcAlphaNotify(this); 249 250 mCmdIf.unregisterForIccRefresh(this); 251 if (mUiccController != null) { 252 mUiccController.unregisterForIccChanged(this); 253 mUiccController = null; 254 } 255 mMsgDecoder.dispose(); 256 mMsgDecoder = null; 257 mHandlerThread.quit(); 258 mHandlerThread = null; 259 removeCallbacksAndMessages(null); 260 if (sInstance != null) { 261 if (SubscriptionManager.isValidSlotId(mSlotId)) { 262 sInstance[mSlotId] = null; 263 } else { 264 CatLog.d(this, "error: invaild slot id: " + mSlotId); 265 } 266 } 267 } 268 } 269 270 @Override 271 protected void finalize() { 272 CatLog.d(this, "Service finalized"); 273 } 274 275 private void handleRilMsg(RilMessage rilMsg) { 276 if (rilMsg == null) { 277 return; 278 } 279 280 // dispatch messages 281 CommandParams cmdParams = null; 282 switch (rilMsg.mId) { 283 case MSG_ID_EVENT_NOTIFY: 284 if (rilMsg.mResCode == ResultCode.OK) { 285 cmdParams = (CommandParams) rilMsg.mData; 286 if (cmdParams != null) { 287 handleCommand(cmdParams, false); 288 } 289 } 290 break; 291 case MSG_ID_PROACTIVE_COMMAND: 292 try { 293 cmdParams = (CommandParams) rilMsg.mData; 294 } catch (ClassCastException e) { 295 // for error handling : cast exception 296 CatLog.d(this, "Fail to parse proactive command"); 297 // Don't send Terminal Resp if command detail is not available 298 if (mCurrntCmd != null) { 299 sendTerminalResponse(mCurrntCmd.mCmdDet, ResultCode.CMD_DATA_NOT_UNDERSTOOD, 300 false, 0x00, null); 301 } 302 break; 303 } 304 if (cmdParams != null) { 305 if (rilMsg.mResCode == ResultCode.OK) { 306 handleCommand(cmdParams, true); 307 } else { 308 // for proactive commands that couldn't be decoded 309 // successfully respond with the code generated by the 310 // message decoder. 311 sendTerminalResponse(cmdParams.mCmdDet, rilMsg.mResCode, 312 false, 0, null); 313 } 314 } 315 break; 316 case MSG_ID_REFRESH: 317 cmdParams = (CommandParams) rilMsg.mData; 318 if (cmdParams != null) { 319 handleCommand(cmdParams, false); 320 } 321 break; 322 case MSG_ID_SESSION_END: 323 handleSessionEnd(); 324 break; 325 case MSG_ID_CALL_SETUP: 326 // prior event notify command supplied all the information 327 // needed for set up call processing. 328 break; 329 } 330 } 331 332 /** 333 * This function validates the events in SETUP_EVENT_LIST which are currently 334 * supported by the Android framework. In case of SETUP_EVENT_LIST has NULL events 335 * or no events, all the events need to be reset. 336 */ 337 private boolean isSupportedSetupEventCommand(CatCmdMessage cmdMsg) { 338 boolean flag = true; 339 340 for (int eventVal: cmdMsg.getSetEventList().eventList) { 341 CatLog.d(this,"Event: " + eventVal); 342 switch (eventVal) { 343 /* Currently android is supporting only the below events in SetupEventList 344 * Language Selection. */ 345 case IDLE_SCREEN_AVAILABLE_EVENT: 346 case LANGUAGE_SELECTION_EVENT: 347 break; 348 default: 349 flag = false; 350 } 351 } 352 return flag; 353 } 354 355 /** 356 * Handles RIL_UNSOL_STK_EVENT_NOTIFY or RIL_UNSOL_STK_PROACTIVE_COMMAND command 357 * from RIL. 358 * Sends valid proactive command data to the application using intents. 359 * RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE will be send back if the command is 360 * from RIL_UNSOL_STK_PROACTIVE_COMMAND. 361 */ 362 private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) { 363 CatLog.d(this, cmdParams.getCommandType().name()); 364 365 // Log all proactive commands. 366 if (isProactiveCmd) { 367 if (mUiccController != null) { 368 mUiccController.addCardLog("ProactiveCommand mSlotId=" + mSlotId + 369 " cmdParams=" + cmdParams); 370 } 371 } 372 373 CharSequence message; 374 ResultCode resultCode; 375 CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams); 376 switch (cmdParams.getCommandType()) { 377 case SET_UP_MENU: 378 if (removeMenu(cmdMsg.getMenu())) { 379 mMenuCmd = null; 380 } else { 381 mMenuCmd = cmdMsg; 382 } 383 resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED 384 : ResultCode.OK; 385 sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); 386 break; 387 case DISPLAY_TEXT: 388 break; 389 case REFRESH: 390 // ME side only handles refresh commands which meant to remove IDLE 391 // MODE TEXT. 392 cmdParams.mCmdDet.typeOfCommand = CommandType.SET_UP_IDLE_MODE_TEXT.value(); 393 break; 394 case SET_UP_IDLE_MODE_TEXT: 395 resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED 396 : ResultCode.OK; 397 sendTerminalResponse(cmdParams.mCmdDet,resultCode, false, 0, null); 398 break; 399 case SET_UP_EVENT_LIST: 400 if (isSupportedSetupEventCommand(cmdMsg)) { 401 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); 402 } else { 403 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, 404 false, 0, null); 405 } 406 break; 407 case PROVIDE_LOCAL_INFORMATION: 408 ResponseData resp; 409 switch (cmdParams.mCmdDet.commandQualifier) { 410 case CommandParamsFactory.DTTZ_SETTING: 411 resp = new DTTZResponseData(null); 412 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); 413 break; 414 case CommandParamsFactory.LANGUAGE_SETTING: 415 resp = new LanguageResponseData(Locale.getDefault().getLanguage()); 416 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); 417 break; 418 default: 419 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); 420 } 421 // No need to start STK app here. 422 return; 423 case LAUNCH_BROWSER: 424 if ((((LaunchBrowserParams) cmdParams).mConfirmMsg.text != null) 425 && (((LaunchBrowserParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { 426 message = mContext.getText(com.android.internal.R.string.launchBrowserDefault); 427 ((LaunchBrowserParams) cmdParams).mConfirmMsg.text = message.toString(); 428 } 429 break; 430 case SELECT_ITEM: 431 case GET_INPUT: 432 case GET_INKEY: 433 break; 434 case SEND_DTMF: 435 case SEND_SMS: 436 case SEND_SS: 437 case SEND_USSD: 438 if ((((DisplayTextParams)cmdParams).mTextMsg.text != null) 439 && (((DisplayTextParams)cmdParams).mTextMsg.text.equals(STK_DEFAULT))) { 440 message = mContext.getText(com.android.internal.R.string.sending); 441 ((DisplayTextParams)cmdParams).mTextMsg.text = message.toString(); 442 } 443 break; 444 case PLAY_TONE: 445 break; 446 case SET_UP_CALL: 447 if ((((CallSetupParams) cmdParams).mConfirmMsg.text != null) 448 && (((CallSetupParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { 449 message = mContext.getText(com.android.internal.R.string.SetupCallDefault); 450 ((CallSetupParams) cmdParams).mConfirmMsg.text = message.toString(); 451 } 452 break; 453 case OPEN_CHANNEL: 454 case CLOSE_CHANNEL: 455 case RECEIVE_DATA: 456 case SEND_DATA: 457 BIPClientParams cmd = (BIPClientParams) cmdParams; 458 /* Per 3GPP specification 102.223, 459 * if the alpha identifier is not provided by the UICC, 460 * the terminal MAY give information to the user 461 * noAlphaUsrCnf defines if you need to show user confirmation or not 462 */ 463 boolean noAlphaUsrCnf = false; 464 try { 465 noAlphaUsrCnf = mContext.getResources().getBoolean( 466 com.android.internal.R.bool.config_stkNoAlphaUsrCnf); 467 } catch (NotFoundException e) { 468 noAlphaUsrCnf = false; 469 } 470 if ((cmd.mTextMsg.text == null) && (cmd.mHasAlphaId || noAlphaUsrCnf)) { 471 CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id"); 472 // If alpha length is zero, we just respond with OK. 473 if (isProactiveCmd) { 474 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); 475 } else if (cmdParams.getCommandType() == CommandType.OPEN_CHANNEL) { 476 mCmdIf.handleCallSetupRequestFromSim(true, null); 477 } 478 return; 479 } 480 // Respond with permanent failure to avoid retry if STK app is not present. 481 if (!mStkAppInstalled) { 482 CatLog.d(this, "No STK application found."); 483 if (isProactiveCmd) { 484 sendTerminalResponse(cmdParams.mCmdDet, 485 ResultCode.BEYOND_TERMINAL_CAPABILITY, 486 false, 0, null); 487 return; 488 } 489 } 490 /* 491 * CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by 492 * either PROACTIVE_COMMAND or EVENT_NOTIFY. 493 * If PROACTIVE_COMMAND is used for those commands, send terminal 494 * response here. 495 */ 496 if (isProactiveCmd && 497 ((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) || 498 (cmdParams.getCommandType() == CommandType.RECEIVE_DATA) || 499 (cmdParams.getCommandType() == CommandType.SEND_DATA))) { 500 sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); 501 } 502 break; 503 default: 504 CatLog.d(this, "Unsupported command"); 505 return; 506 } 507 mCurrntCmd = cmdMsg; 508 broadcastCatCmdIntent(cmdMsg); 509 } 510 511 512 private void broadcastCatCmdIntent(CatCmdMessage cmdMsg) { 513 Intent intent = new Intent(AppInterface.CAT_CMD_ACTION); 514 intent.putExtra("STK CMD", cmdMsg); 515 intent.putExtra("SLOT_ID", mSlotId); 516 CatLog.d(this, "Sending CmdMsg: " + cmdMsg+ " on slotid:" + mSlotId); 517 mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION); 518 } 519 520 /** 521 * Handles RIL_UNSOL_STK_SESSION_END unsolicited command from RIL. 522 * 523 */ 524 private void handleSessionEnd() { 525 CatLog.d(this, "SESSION END on "+ mSlotId); 526 527 mCurrntCmd = mMenuCmd; 528 Intent intent = new Intent(AppInterface.CAT_SESSION_END_ACTION); 529 intent.putExtra("SLOT_ID", mSlotId); 530 mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION); 531 } 532 533 534 private void sendTerminalResponse(CommandDetails cmdDet, 535 ResultCode resultCode, boolean includeAdditionalInfo, 536 int additionalInfo, ResponseData resp) { 537 538 if (cmdDet == null) { 539 return; 540 } 541 ByteArrayOutputStream buf = new ByteArrayOutputStream(); 542 543 Input cmdInput = null; 544 if (mCurrntCmd != null) { 545 cmdInput = mCurrntCmd.geInput(); 546 } 547 548 // command details 549 int tag = ComprehensionTlvTag.COMMAND_DETAILS.value(); 550 if (cmdDet.compRequired) { 551 tag |= 0x80; 552 } 553 buf.write(tag); 554 buf.write(0x03); // length 555 buf.write(cmdDet.commandNumber); 556 buf.write(cmdDet.typeOfCommand); 557 buf.write(cmdDet.commandQualifier); 558 559 // device identities 560 // According to TS102.223/TS31.111 section 6.8 Structure of 561 // TERMINAL RESPONSE, "For all SIMPLE-TLV objects with Min=N, 562 // the ME should set the CR(comprehension required) flag to 563 // comprehension not required.(CR=0)" 564 // Since DEVICE_IDENTITIES and DURATION TLVs have Min=N, 565 // the CR flag is not set. 566 tag = ComprehensionTlvTag.DEVICE_IDENTITIES.value(); 567 buf.write(tag); 568 buf.write(0x02); // length 569 buf.write(DEV_ID_TERMINAL); // source device id 570 buf.write(DEV_ID_UICC); // destination device id 571 572 // result 573 tag = ComprehensionTlvTag.RESULT.value(); 574 if (cmdDet.compRequired) { 575 tag |= 0x80; 576 } 577 buf.write(tag); 578 int length = includeAdditionalInfo ? 2 : 1; 579 buf.write(length); 580 buf.write(resultCode.value()); 581 582 // additional info 583 if (includeAdditionalInfo) { 584 buf.write(additionalInfo); 585 } 586 587 // Fill optional data for each corresponding command 588 if (resp != null) { 589 resp.format(buf); 590 } else { 591 encodeOptionalTags(cmdDet, resultCode, cmdInput, buf); 592 } 593 594 byte[] rawData = buf.toByteArray(); 595 String hexString = IccUtils.bytesToHexString(rawData); 596 if (DBG) { 597 CatLog.d(this, "TERMINAL RESPONSE: " + hexString); 598 } 599 600 mCmdIf.sendTerminalResponse(hexString, null); 601 } 602 603 private void encodeOptionalTags(CommandDetails cmdDet, 604 ResultCode resultCode, Input cmdInput, ByteArrayOutputStream buf) { 605 CommandType cmdType = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand); 606 if (cmdType != null) { 607 switch (cmdType) { 608 case GET_INKEY: 609 // ETSI TS 102 384,27.22.4.2.8.4.2. 610 // If it is a response for GET_INKEY command and the response timeout 611 // occured, then add DURATION TLV for variable timeout case. 612 if ((resultCode.value() == ResultCode.NO_RESPONSE_FROM_USER.value()) && 613 (cmdInput != null) && (cmdInput.duration != null)) { 614 getInKeyResponse(buf, cmdInput); 615 } 616 break; 617 case PROVIDE_LOCAL_INFORMATION: 618 if ((cmdDet.commandQualifier == CommandParamsFactory.LANGUAGE_SETTING) && 619 (resultCode.value() == ResultCode.OK.value())) { 620 getPliResponse(buf); 621 } 622 break; 623 default: 624 CatLog.d(this, "encodeOptionalTags() Unsupported Cmd details=" + cmdDet); 625 break; 626 } 627 } else { 628 CatLog.d(this, "encodeOptionalTags() bad Cmd details=" + cmdDet); 629 } 630 } 631 632 private void getInKeyResponse(ByteArrayOutputStream buf, Input cmdInput) { 633 int tag = ComprehensionTlvTag.DURATION.value(); 634 635 buf.write(tag); 636 buf.write(0x02); // length 637 buf.write(cmdInput.duration.timeUnit.SECOND.value()); // Time (Unit,Seconds) 638 buf.write(cmdInput.duration.timeInterval); // Time Duration 639 } 640 641 private void getPliResponse(ByteArrayOutputStream buf) { 642 // Locale Language Setting 643 final String lang = Locale.getDefault().getLanguage(); 644 645 if (lang != null) { 646 // tag 647 int tag = ComprehensionTlvTag.LANGUAGE.value(); 648 buf.write(tag); 649 ResponseData.writeLength(buf, lang.length()); 650 buf.write(lang.getBytes(), 0, lang.length()); 651 } 652 } 653 654 private void sendMenuSelection(int menuId, boolean helpRequired) { 655 656 ByteArrayOutputStream buf = new ByteArrayOutputStream(); 657 658 // tag 659 int tag = BerTlv.BER_MENU_SELECTION_TAG; 660 buf.write(tag); 661 662 // length 663 buf.write(0x00); // place holder 664 665 // device identities 666 tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value(); 667 buf.write(tag); 668 buf.write(0x02); // length 669 buf.write(DEV_ID_KEYPAD); // source device id 670 buf.write(DEV_ID_UICC); // destination device id 671 672 // item identifier 673 tag = 0x80 | ComprehensionTlvTag.ITEM_ID.value(); 674 buf.write(tag); 675 buf.write(0x01); // length 676 buf.write(menuId); // menu identifier chosen 677 678 // help request 679 if (helpRequired) { 680 tag = ComprehensionTlvTag.HELP_REQUEST.value(); 681 buf.write(tag); 682 buf.write(0x00); // length 683 } 684 685 byte[] rawData = buf.toByteArray(); 686 687 // write real length 688 int len = rawData.length - 2; // minus (tag + length) 689 rawData[1] = (byte) len; 690 691 String hexString = IccUtils.bytesToHexString(rawData); 692 693 mCmdIf.sendEnvelope(hexString, null); 694 } 695 696 private void eventDownload(int event, int sourceId, int destinationId, 697 byte[] additionalInfo, boolean oneShot) { 698 699 ByteArrayOutputStream buf = new ByteArrayOutputStream(); 700 701 // tag 702 int tag = BerTlv.BER_EVENT_DOWNLOAD_TAG; 703 buf.write(tag); 704 705 // length 706 buf.write(0x00); // place holder, assume length < 128. 707 708 // event list 709 tag = 0x80 | ComprehensionTlvTag.EVENT_LIST.value(); 710 buf.write(tag); 711 buf.write(0x01); // length 712 buf.write(event); // event value 713 714 // device identities 715 tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value(); 716 buf.write(tag); 717 buf.write(0x02); // length 718 buf.write(sourceId); // source device id 719 buf.write(destinationId); // destination device id 720 721 /* 722 * Check for type of event download to be sent to UICC - Browser 723 * termination,Idle screen available, User activity, Language selection 724 * etc as mentioned under ETSI TS 102 223 section 7.5 725 */ 726 727 /* 728 * Currently the below events are supported: 729 * Language Selection Event. 730 * Other event download commands should be encoded similar way 731 */ 732 /* TODO: eventDownload should be extended for other Envelope Commands */ 733 switch (event) { 734 case IDLE_SCREEN_AVAILABLE_EVENT: 735 CatLog.d(sInstance, " Sending Idle Screen Available event download to ICC"); 736 break; 737 case LANGUAGE_SELECTION_EVENT: 738 CatLog.d(sInstance, " Sending Language Selection event download to ICC"); 739 tag = 0x80 | ComprehensionTlvTag.LANGUAGE.value(); 740 buf.write(tag); 741 // Language length should be 2 byte 742 buf.write(0x02); 743 break; 744 default: 745 break; 746 } 747 748 // additional information 749 if (additionalInfo != null) { 750 for (byte b : additionalInfo) { 751 buf.write(b); 752 } 753 } 754 755 byte[] rawData = buf.toByteArray(); 756 757 // write real length 758 int len = rawData.length - 2; // minus (tag + length) 759 rawData[1] = (byte) len; 760 761 String hexString = IccUtils.bytesToHexString(rawData); 762 763 CatLog.d(this, "ENVELOPE COMMAND: " + hexString); 764 765 mCmdIf.sendEnvelope(hexString, null); 766 } 767 768 /** 769 * Used by application to get an AppInterface object. 770 * 771 * @return The only Service object in the system 772 */ 773 //TODO Need to take care for MSIM 774 public static AppInterface getInstance() { 775 int slotId = PhoneConstants.DEFAULT_CARD_INDEX; 776 SubscriptionController sControl = SubscriptionController.getInstance(); 777 if (sControl != null) { 778 slotId = sControl.getSlotId(sControl.getDefaultSubId()); 779 } 780 return getInstance(null, null, null, slotId); 781 } 782 783 /** 784 * Used by application to get an AppInterface object. 785 * 786 * @return The only Service object in the system 787 */ 788 public static AppInterface getInstance(int slotId) { 789 return getInstance(null, null, null, slotId); 790 } 791 792 @Override 793 public void handleMessage(Message msg) { 794 CatLog.d(this, "handleMessage[" + msg.what + "]"); 795 796 switch (msg.what) { 797 case MSG_ID_SESSION_END: 798 case MSG_ID_PROACTIVE_COMMAND: 799 case MSG_ID_EVENT_NOTIFY: 800 case MSG_ID_REFRESH: 801 CatLog.d(this, "ril message arrived,slotid:" + mSlotId); 802 String data = null; 803 if (msg.obj != null) { 804 AsyncResult ar = (AsyncResult) msg.obj; 805 if (ar != null && ar.result != null) { 806 try { 807 data = (String) ar.result; 808 } catch (ClassCastException e) { 809 break; 810 } 811 } 812 } 813 mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, data)); 814 break; 815 case MSG_ID_CALL_SETUP: 816 mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, null)); 817 break; 818 case MSG_ID_ICC_RECORDS_LOADED: 819 break; 820 case MSG_ID_RIL_MSG_DECODED: 821 handleRilMsg((RilMessage) msg.obj); 822 break; 823 case MSG_ID_RESPONSE: 824 handleCmdResponse((CatResponseMessage) msg.obj); 825 break; 826 case MSG_ID_ICC_CHANGED: 827 CatLog.d(this, "MSG_ID_ICC_CHANGED"); 828 updateIccAvailability(); 829 break; 830 case MSG_ID_ICC_REFRESH: 831 if (msg.obj != null) { 832 AsyncResult ar = (AsyncResult) msg.obj; 833 if (ar != null && ar.result != null) { 834 broadcastCardStateAndIccRefreshResp(CardState.CARDSTATE_PRESENT, 835 (IccRefreshResponse) ar.result); 836 } else { 837 CatLog.d(this,"Icc REFRESH with exception: " + ar.exception); 838 } 839 } else { 840 CatLog.d(this, "IccRefresh Message is null"); 841 } 842 break; 843 case MSG_ID_ALPHA_NOTIFY: 844 CatLog.d(this, "Received CAT CC Alpha message from card"); 845 if (msg.obj != null) { 846 AsyncResult ar = (AsyncResult) msg.obj; 847 if (ar != null && ar.result != null) { 848 broadcastAlphaMessage((String)ar.result); 849 } else { 850 CatLog.d(this, "CAT Alpha message: ar.result is null"); 851 } 852 } else { 853 CatLog.d(this, "CAT Alpha message: msg.obj is null"); 854 } 855 break; 856 default: 857 throw new AssertionError("Unrecognized CAT command: " + msg.what); 858 } 859 } 860 861 /** 862 ** This function sends a CARD status (ABSENT, PRESENT, REFRESH) to STK_APP. 863 ** This is triggered during ICC_REFRESH or CARD STATE changes. In case 864 ** REFRESH, additional information is sent in 'refresh_result' 865 ** 866 **/ 867 private void broadcastCardStateAndIccRefreshResp(CardState cardState, 868 IccRefreshResponse iccRefreshState) { 869 Intent intent = new Intent(AppInterface.CAT_ICC_STATUS_CHANGE); 870 boolean cardPresent = (cardState == CardState.CARDSTATE_PRESENT); 871 872 if (iccRefreshState != null) { 873 //This case is when MSG_ID_ICC_REFRESH is received. 874 intent.putExtra(AppInterface.REFRESH_RESULT, iccRefreshState.refreshResult); 875 CatLog.d(this, "Sending IccResult with Result: " 876 + iccRefreshState.refreshResult); 877 } 878 879 // This sends an intent with CARD_ABSENT (0 - false) /CARD_PRESENT (1 - true). 880 intent.putExtra(AppInterface.CARD_STATUS, cardPresent); 881 CatLog.d(this, "Sending Card Status: " 882 + cardState + " " + "cardPresent: " + cardPresent); 883 mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION); 884 } 885 886 private void broadcastAlphaMessage(String alphaString) { 887 CatLog.d(this, "Broadcasting CAT Alpha message from card: " + alphaString); 888 Intent intent = new Intent(AppInterface.CAT_ALPHA_NOTIFY_ACTION); 889 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 890 intent.putExtra(AppInterface.ALPHA_STRING, alphaString); 891 intent.putExtra("SLOT_ID", mSlotId); 892 mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION); 893 } 894 895 @Override 896 public synchronized void onCmdResponse(CatResponseMessage resMsg) { 897 if (resMsg == null) { 898 return; 899 } 900 // queue a response message. 901 Message msg = obtainMessage(MSG_ID_RESPONSE, resMsg); 902 msg.sendToTarget(); 903 } 904 905 private boolean validateResponse(CatResponseMessage resMsg) { 906 boolean validResponse = false; 907 if ((resMsg.mCmdDet.typeOfCommand == CommandType.SET_UP_EVENT_LIST.value()) 908 || (resMsg.mCmdDet.typeOfCommand == CommandType.SET_UP_MENU.value())) { 909 CatLog.d(this, "CmdType: " + resMsg.mCmdDet.typeOfCommand); 910 validResponse = true; 911 } else if (mCurrntCmd != null) { 912 validResponse = resMsg.mCmdDet.compareTo(mCurrntCmd.mCmdDet); 913 CatLog.d(this, "isResponse for last valid cmd: " + validResponse); 914 } 915 return validResponse; 916 } 917 918 private boolean removeMenu(Menu menu) { 919 try { 920 if (menu.items.size() == 1 && menu.items.get(0) == null) { 921 return true; 922 } 923 } catch (NullPointerException e) { 924 CatLog.d(this, "Unable to get Menu's items size"); 925 return true; 926 } 927 return false; 928 } 929 930 private void handleCmdResponse(CatResponseMessage resMsg) { 931 // Make sure the response details match the last valid command. An invalid 932 // response is a one that doesn't have a corresponding proactive command 933 // and sending it can "confuse" the baseband/ril. 934 // One reason for out of order responses can be UI glitches. For example, 935 // if the application launch an activity, and that activity is stored 936 // by the framework inside the history stack. That activity will be 937 // available for relaunch using the latest application dialog 938 // (long press on the home button). Relaunching that activity can send 939 // the same command's result again to the CatService and can cause it to 940 // get out of sync with the SIM. This can happen in case of 941 // non-interactive type Setup Event List and SETUP_MENU proactive commands. 942 // Stk framework would have already sent Terminal Response to Setup Event 943 // List and SETUP_MENU proactive commands. After sometime Stk app will send 944 // Envelope Command/Event Download. In which case, the response details doesn't 945 // match with last valid command (which are not related). 946 // However, we should allow Stk framework to send the message to ICC. 947 if (!validateResponse(resMsg)) { 948 return; 949 } 950 ResponseData resp = null; 951 boolean helpRequired = false; 952 CommandDetails cmdDet = resMsg.getCmdDetails(); 953 AppInterface.CommandType type = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand); 954 955 switch (resMsg.mResCode) { 956 case HELP_INFO_REQUIRED: 957 helpRequired = true; 958 // fall through 959 case OK: 960 case PRFRMD_WITH_PARTIAL_COMPREHENSION: 961 case PRFRMD_WITH_MISSING_INFO: 962 case PRFRMD_WITH_ADDITIONAL_EFS_READ: 963 case PRFRMD_ICON_NOT_DISPLAYED: 964 case PRFRMD_MODIFIED_BY_NAA: 965 case PRFRMD_LIMITED_SERVICE: 966 case PRFRMD_WITH_MODIFICATION: 967 case PRFRMD_NAA_NOT_ACTIVE: 968 case PRFRMD_TONE_NOT_PLAYED: 969 case LAUNCH_BROWSER_ERROR: 970 case TERMINAL_CRNTLY_UNABLE_TO_PROCESS: 971 switch (type) { 972 case SET_UP_MENU: 973 helpRequired = resMsg.mResCode == ResultCode.HELP_INFO_REQUIRED; 974 sendMenuSelection(resMsg.mUsersMenuSelection, helpRequired); 975 return; 976 case SELECT_ITEM: 977 resp = new SelectItemResponseData(resMsg.mUsersMenuSelection); 978 break; 979 case GET_INPUT: 980 case GET_INKEY: 981 Input input = mCurrntCmd.geInput(); 982 if (!input.yesNo) { 983 // when help is requested there is no need to send the text 984 // string object. 985 if (!helpRequired) { 986 resp = new GetInkeyInputResponseData(resMsg.mUsersInput, 987 input.ucs2, input.packed); 988 } 989 } else { 990 resp = new GetInkeyInputResponseData( 991 resMsg.mUsersYesNoSelection); 992 } 993 break; 994 case DISPLAY_TEXT: 995 if (resMsg.mResCode == ResultCode.TERMINAL_CRNTLY_UNABLE_TO_PROCESS) { 996 // For screenbusy case there will be addtional information in the terminal 997 // response. And the value of the additional information byte is 0x01. 998 resMsg.setAdditionalInfo(0x01); 999 } else { 1000 resMsg.mIncludeAdditionalInfo = false; 1001 resMsg.mAdditionalInfo = 0; 1002 } 1003 break; 1004 case LAUNCH_BROWSER: 1005 break; 1006 // 3GPP TS.102.223: Open Channel alpha confirmation should not send TR 1007 case OPEN_CHANNEL: 1008 case SET_UP_CALL: 1009 mCmdIf.handleCallSetupRequestFromSim(resMsg.mUsersConfirm, null); 1010 // No need to send terminal response for SET UP CALL. The user's 1011 // confirmation result is send back using a dedicated ril message 1012 // invoked by the CommandInterface call above. 1013 mCurrntCmd = null; 1014 return; 1015 case SET_UP_EVENT_LIST: 1016 if (IDLE_SCREEN_AVAILABLE_EVENT == resMsg.mEventValue) { 1017 eventDownload(resMsg.mEventValue, DEV_ID_DISPLAY, DEV_ID_UICC, 1018 resMsg.mAddedInfo, false); 1019 } else { 1020 eventDownload(resMsg.mEventValue, DEV_ID_TERMINAL, DEV_ID_UICC, 1021 resMsg.mAddedInfo, false); 1022 } 1023 // No need to send the terminal response after event download. 1024 return; 1025 default: 1026 break; 1027 } 1028 break; 1029 case BACKWARD_MOVE_BY_USER: 1030 case USER_NOT_ACCEPT: 1031 // if the user dismissed the alert dialog for a 1032 // setup call/open channel, consider that as the user 1033 // rejecting the call. Use dedicated API for this, rather than 1034 // sending a terminal response. 1035 if (type == CommandType.SET_UP_CALL || type == CommandType.OPEN_CHANNEL) { 1036 mCmdIf.handleCallSetupRequestFromSim(false, null); 1037 mCurrntCmd = null; 1038 return; 1039 } else { 1040 resp = null; 1041 } 1042 break; 1043 case NO_RESPONSE_FROM_USER: 1044 case UICC_SESSION_TERM_BY_USER: 1045 resp = null; 1046 break; 1047 default: 1048 return; 1049 } 1050 sendTerminalResponse(cmdDet, resMsg.mResCode, resMsg.mIncludeAdditionalInfo, 1051 resMsg.mAdditionalInfo, resp); 1052 mCurrntCmd = null; 1053 } 1054 1055 private boolean isStkAppInstalled() { 1056 Intent intent = new Intent(AppInterface.CAT_CMD_ACTION); 1057 PackageManager pm = mContext.getPackageManager(); 1058 List<ResolveInfo> broadcastReceivers = 1059 pm.queryBroadcastReceivers(intent, PackageManager.GET_META_DATA); 1060 int numReceiver = broadcastReceivers == null ? 0 : broadcastReceivers.size(); 1061 1062 return (numReceiver > 0); 1063 } 1064 1065 public void update(CommandsInterface ci, 1066 Context context, UiccCard ic) { 1067 UiccCardApplication ca = null; 1068 IccRecords ir = null; 1069 1070 if (ic != null) { 1071 /* Since Cat is not tied to any application, but rather is Uicc application 1072 * in itself - just get first FileHandler and IccRecords object 1073 */ 1074 ca = ic.getApplicationIndex(0); 1075 if (ca != null) { 1076 ir = ca.getIccRecords(); 1077 } 1078 } 1079 1080 synchronized (sInstanceLock) { 1081 if ((ir != null) && (mIccRecords != ir)) { 1082 if (mIccRecords != null) { 1083 mIccRecords.unregisterForRecordsLoaded(this); 1084 } 1085 1086 CatLog.d(this, 1087 "Reinitialize the Service with SIMRecords and UiccCardApplication"); 1088 mIccRecords = ir; 1089 mUiccApplication = ca; 1090 1091 // re-Register for SIM ready event. 1092 mIccRecords.registerForRecordsLoaded(this, MSG_ID_ICC_RECORDS_LOADED, null); 1093 CatLog.d(this, "registerForRecordsLoaded slotid=" + mSlotId + " instance:" + this); 1094 } 1095 } 1096 } 1097 1098 void updateIccAvailability() { 1099 if (null == mUiccController) { 1100 return; 1101 } 1102 1103 CardState newState = CardState.CARDSTATE_ABSENT; 1104 UiccCard newCard = mUiccController.getUiccCard(mSlotId); 1105 if (newCard != null) { 1106 newState = newCard.getCardState(); 1107 } 1108 CardState oldState = mCardState; 1109 mCardState = newState; 1110 CatLog.d(this,"New Card State = " + newState + " " + "Old Card State = " + oldState); 1111 if (oldState == CardState.CARDSTATE_PRESENT && 1112 newState != CardState.CARDSTATE_PRESENT) { 1113 broadcastCardStateAndIccRefreshResp(newState, null); 1114 } else if (oldState != CardState.CARDSTATE_PRESENT && 1115 newState == CardState.CARDSTATE_PRESENT) { 1116 // Card moved to PRESENT STATE. 1117 mCmdIf.reportStkServiceIsRunning(null); 1118 } 1119 } 1120} 1121