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.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
515        intent.putExtra("STK CMD", cmdMsg);
516        intent.putExtra("SLOT_ID", mSlotId);
517        CatLog.d(this, "Sending CmdMsg: " + cmdMsg+ " on slotid:" + mSlotId);
518        mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION);
519    }
520
521    /**
522     * Handles RIL_UNSOL_STK_SESSION_END unsolicited command from RIL.
523     *
524     */
525    private void handleSessionEnd() {
526        CatLog.d(this, "SESSION END on "+ mSlotId);
527
528        mCurrntCmd = mMenuCmd;
529        Intent intent = new Intent(AppInterface.CAT_SESSION_END_ACTION);
530        intent.putExtra("SLOT_ID", mSlotId);
531        mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION);
532    }
533
534
535    private void sendTerminalResponse(CommandDetails cmdDet,
536            ResultCode resultCode, boolean includeAdditionalInfo,
537            int additionalInfo, ResponseData resp) {
538
539        if (cmdDet == null) {
540            return;
541        }
542        ByteArrayOutputStream buf = new ByteArrayOutputStream();
543
544        Input cmdInput = null;
545        if (mCurrntCmd != null) {
546            cmdInput = mCurrntCmd.geInput();
547        }
548
549        // command details
550        int tag = ComprehensionTlvTag.COMMAND_DETAILS.value();
551        if (cmdDet.compRequired) {
552            tag |= 0x80;
553        }
554        buf.write(tag);
555        buf.write(0x03); // length
556        buf.write(cmdDet.commandNumber);
557        buf.write(cmdDet.typeOfCommand);
558        buf.write(cmdDet.commandQualifier);
559
560        // device identities
561        // According to TS102.223/TS31.111 section 6.8 Structure of
562        // TERMINAL RESPONSE, "For all SIMPLE-TLV objects with Min=N,
563        // the ME should set the CR(comprehension required) flag to
564        // comprehension not required.(CR=0)"
565        // Since DEVICE_IDENTITIES and DURATION TLVs have Min=N,
566        // the CR flag is not set.
567        tag = ComprehensionTlvTag.DEVICE_IDENTITIES.value();
568        buf.write(tag);
569        buf.write(0x02); // length
570        buf.write(DEV_ID_TERMINAL); // source device id
571        buf.write(DEV_ID_UICC); // destination device id
572
573        // result
574        tag = ComprehensionTlvTag.RESULT.value();
575        if (cmdDet.compRequired) {
576            tag |= 0x80;
577        }
578        buf.write(tag);
579        int length = includeAdditionalInfo ? 2 : 1;
580        buf.write(length);
581        buf.write(resultCode.value());
582
583        // additional info
584        if (includeAdditionalInfo) {
585            buf.write(additionalInfo);
586        }
587
588        // Fill optional data for each corresponding command
589        if (resp != null) {
590            resp.format(buf);
591        } else {
592            encodeOptionalTags(cmdDet, resultCode, cmdInput, buf);
593        }
594
595        byte[] rawData = buf.toByteArray();
596        String hexString = IccUtils.bytesToHexString(rawData);
597        if (DBG) {
598            CatLog.d(this, "TERMINAL RESPONSE: " + hexString);
599        }
600
601        mCmdIf.sendTerminalResponse(hexString, null);
602    }
603
604    private void encodeOptionalTags(CommandDetails cmdDet,
605            ResultCode resultCode, Input cmdInput, ByteArrayOutputStream buf) {
606        CommandType cmdType = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand);
607        if (cmdType != null) {
608            switch (cmdType) {
609                case GET_INKEY:
610                    // ETSI TS 102 384,27.22.4.2.8.4.2.
611                    // If it is a response for GET_INKEY command and the response timeout
612                    // occured, then add DURATION TLV for variable timeout case.
613                    if ((resultCode.value() == ResultCode.NO_RESPONSE_FROM_USER.value()) &&
614                        (cmdInput != null) && (cmdInput.duration != null)) {
615                        getInKeyResponse(buf, cmdInput);
616                    }
617                    break;
618                case PROVIDE_LOCAL_INFORMATION:
619                    if ((cmdDet.commandQualifier == CommandParamsFactory.LANGUAGE_SETTING) &&
620                        (resultCode.value() == ResultCode.OK.value())) {
621                        getPliResponse(buf);
622                    }
623                    break;
624                default:
625                    CatLog.d(this, "encodeOptionalTags() Unsupported Cmd details=" + cmdDet);
626                    break;
627            }
628        } else {
629            CatLog.d(this, "encodeOptionalTags() bad Cmd details=" + cmdDet);
630        }
631    }
632
633    private void getInKeyResponse(ByteArrayOutputStream buf, Input cmdInput) {
634        int tag = ComprehensionTlvTag.DURATION.value();
635
636        buf.write(tag);
637        buf.write(0x02); // length
638        buf.write(cmdInput.duration.timeUnit.SECOND.value()); // Time (Unit,Seconds)
639        buf.write(cmdInput.duration.timeInterval); // Time Duration
640    }
641
642    private void getPliResponse(ByteArrayOutputStream buf) {
643        // Locale Language Setting
644        final String lang = Locale.getDefault().getLanguage();
645
646        if (lang != null) {
647            // tag
648            int tag = ComprehensionTlvTag.LANGUAGE.value();
649            buf.write(tag);
650            ResponseData.writeLength(buf, lang.length());
651            buf.write(lang.getBytes(), 0, lang.length());
652        }
653    }
654
655    private void sendMenuSelection(int menuId, boolean helpRequired) {
656
657        ByteArrayOutputStream buf = new ByteArrayOutputStream();
658
659        // tag
660        int tag = BerTlv.BER_MENU_SELECTION_TAG;
661        buf.write(tag);
662
663        // length
664        buf.write(0x00); // place holder
665
666        // device identities
667        tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value();
668        buf.write(tag);
669        buf.write(0x02); // length
670        buf.write(DEV_ID_KEYPAD); // source device id
671        buf.write(DEV_ID_UICC); // destination device id
672
673        // item identifier
674        tag = 0x80 | ComprehensionTlvTag.ITEM_ID.value();
675        buf.write(tag);
676        buf.write(0x01); // length
677        buf.write(menuId); // menu identifier chosen
678
679        // help request
680        if (helpRequired) {
681            tag = ComprehensionTlvTag.HELP_REQUEST.value();
682            buf.write(tag);
683            buf.write(0x00); // length
684        }
685
686        byte[] rawData = buf.toByteArray();
687
688        // write real length
689        int len = rawData.length - 2; // minus (tag + length)
690        rawData[1] = (byte) len;
691
692        String hexString = IccUtils.bytesToHexString(rawData);
693
694        mCmdIf.sendEnvelope(hexString, null);
695    }
696
697    private void eventDownload(int event, int sourceId, int destinationId,
698            byte[] additionalInfo, boolean oneShot) {
699
700        ByteArrayOutputStream buf = new ByteArrayOutputStream();
701
702        // tag
703        int tag = BerTlv.BER_EVENT_DOWNLOAD_TAG;
704        buf.write(tag);
705
706        // length
707        buf.write(0x00); // place holder, assume length < 128.
708
709        // event list
710        tag = 0x80 | ComprehensionTlvTag.EVENT_LIST.value();
711        buf.write(tag);
712        buf.write(0x01); // length
713        buf.write(event); // event value
714
715        // device identities
716        tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value();
717        buf.write(tag);
718        buf.write(0x02); // length
719        buf.write(sourceId); // source device id
720        buf.write(destinationId); // destination device id
721
722        /*
723         * Check for type of event download to be sent to UICC - Browser
724         * termination,Idle screen available, User activity, Language selection
725         * etc as mentioned under ETSI TS 102 223 section 7.5
726         */
727
728        /*
729         * Currently the below events are supported:
730         * Language Selection Event.
731         * Other event download commands should be encoded similar way
732         */
733        /* TODO: eventDownload should be extended for other Envelope Commands */
734        switch (event) {
735            case IDLE_SCREEN_AVAILABLE_EVENT:
736                CatLog.d(sInstance, " Sending Idle Screen Available event download to ICC");
737                break;
738            case LANGUAGE_SELECTION_EVENT:
739                CatLog.d(sInstance, " Sending Language Selection event download to ICC");
740                tag = 0x80 | ComprehensionTlvTag.LANGUAGE.value();
741                buf.write(tag);
742                // Language length should be 2 byte
743                buf.write(0x02);
744                break;
745            default:
746                break;
747        }
748
749        // additional information
750        if (additionalInfo != null) {
751            for (byte b : additionalInfo) {
752                buf.write(b);
753            }
754        }
755
756        byte[] rawData = buf.toByteArray();
757
758        // write real length
759        int len = rawData.length - 2; // minus (tag + length)
760        rawData[1] = (byte) len;
761
762        String hexString = IccUtils.bytesToHexString(rawData);
763
764        CatLog.d(this, "ENVELOPE COMMAND: " + hexString);
765
766        mCmdIf.sendEnvelope(hexString, null);
767    }
768
769    /**
770     * Used by application to get an AppInterface object.
771     *
772     * @return The only Service object in the system
773     */
774    //TODO Need to take care for MSIM
775    public static AppInterface getInstance() {
776        int slotId = PhoneConstants.DEFAULT_CARD_INDEX;
777        SubscriptionController sControl = SubscriptionController.getInstance();
778        if (sControl != null) {
779            slotId = sControl.getSlotId(sControl.getDefaultSubId());
780        }
781        return getInstance(null, null, null, slotId);
782    }
783
784    /**
785     * Used by application to get an AppInterface object.
786     *
787     * @return The only Service object in the system
788     */
789    public static AppInterface getInstance(int slotId) {
790        return getInstance(null, null, null, slotId);
791    }
792
793    @Override
794    public void handleMessage(Message msg) {
795        CatLog.d(this, "handleMessage[" + msg.what + "]");
796
797        switch (msg.what) {
798        case MSG_ID_SESSION_END:
799        case MSG_ID_PROACTIVE_COMMAND:
800        case MSG_ID_EVENT_NOTIFY:
801        case MSG_ID_REFRESH:
802            CatLog.d(this, "ril message arrived,slotid:" + mSlotId);
803            String data = null;
804            if (msg.obj != null) {
805                AsyncResult ar = (AsyncResult) msg.obj;
806                if (ar != null && ar.result != null) {
807                    try {
808                        data = (String) ar.result;
809                    } catch (ClassCastException e) {
810                        break;
811                    }
812                }
813            }
814            mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, data));
815            break;
816        case MSG_ID_CALL_SETUP:
817            mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, null));
818            break;
819        case MSG_ID_ICC_RECORDS_LOADED:
820            break;
821        case MSG_ID_RIL_MSG_DECODED:
822            handleRilMsg((RilMessage) msg.obj);
823            break;
824        case MSG_ID_RESPONSE:
825            handleCmdResponse((CatResponseMessage) msg.obj);
826            break;
827        case MSG_ID_ICC_CHANGED:
828            CatLog.d(this, "MSG_ID_ICC_CHANGED");
829            updateIccAvailability();
830            break;
831        case MSG_ID_ICC_REFRESH:
832            if (msg.obj != null) {
833                AsyncResult ar = (AsyncResult) msg.obj;
834                if (ar != null && ar.result != null) {
835                    broadcastCardStateAndIccRefreshResp(CardState.CARDSTATE_PRESENT,
836                                  (IccRefreshResponse) ar.result);
837                } else {
838                    CatLog.d(this,"Icc REFRESH with exception: " + ar.exception);
839                }
840            } else {
841                CatLog.d(this, "IccRefresh Message is null");
842            }
843            break;
844        case MSG_ID_ALPHA_NOTIFY:
845            CatLog.d(this, "Received CAT CC Alpha message from card");
846            if (msg.obj != null) {
847                AsyncResult ar = (AsyncResult) msg.obj;
848                if (ar != null && ar.result != null) {
849                    broadcastAlphaMessage((String)ar.result);
850                } else {
851                    CatLog.d(this, "CAT Alpha message: ar.result is null");
852                }
853            } else {
854                CatLog.d(this, "CAT Alpha message: msg.obj is null");
855            }
856            break;
857        default:
858            throw new AssertionError("Unrecognized CAT command: " + msg.what);
859        }
860    }
861
862    /**
863     ** This function sends a CARD status (ABSENT, PRESENT, REFRESH) to STK_APP.
864     ** This is triggered during ICC_REFRESH or CARD STATE changes. In case
865     ** REFRESH, additional information is sent in 'refresh_result'
866     **
867     **/
868    private void  broadcastCardStateAndIccRefreshResp(CardState cardState,
869            IccRefreshResponse iccRefreshState) {
870        Intent intent = new Intent(AppInterface.CAT_ICC_STATUS_CHANGE);
871        boolean cardPresent = (cardState == CardState.CARDSTATE_PRESENT);
872
873        if (iccRefreshState != null) {
874            //This case is when MSG_ID_ICC_REFRESH is received.
875            intent.putExtra(AppInterface.REFRESH_RESULT, iccRefreshState.refreshResult);
876            CatLog.d(this, "Sending IccResult with Result: "
877                    + iccRefreshState.refreshResult);
878        }
879
880        // This sends an intent with CARD_ABSENT (0 - false) /CARD_PRESENT (1 - true).
881        intent.putExtra(AppInterface.CARD_STATUS, cardPresent);
882        CatLog.d(this, "Sending Card Status: "
883                + cardState + " " + "cardPresent: " + cardPresent);
884        mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION);
885    }
886
887    private void broadcastAlphaMessage(String alphaString) {
888        CatLog.d(this, "Broadcasting CAT Alpha message from card: " + alphaString);
889        Intent intent = new Intent(AppInterface.CAT_ALPHA_NOTIFY_ACTION);
890        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
891        intent.putExtra(AppInterface.ALPHA_STRING, alphaString);
892        intent.putExtra("SLOT_ID", mSlotId);
893        mContext.sendBroadcast(intent, AppInterface.STK_PERMISSION);
894    }
895
896    @Override
897    public synchronized void onCmdResponse(CatResponseMessage resMsg) {
898        if (resMsg == null) {
899            return;
900        }
901        // queue a response message.
902        Message msg = obtainMessage(MSG_ID_RESPONSE, resMsg);
903        msg.sendToTarget();
904    }
905
906    private boolean validateResponse(CatResponseMessage resMsg) {
907        boolean validResponse = false;
908        if ((resMsg.mCmdDet.typeOfCommand == CommandType.SET_UP_EVENT_LIST.value())
909                || (resMsg.mCmdDet.typeOfCommand == CommandType.SET_UP_MENU.value())) {
910            CatLog.d(this, "CmdType: " + resMsg.mCmdDet.typeOfCommand);
911            validResponse = true;
912        } else if (mCurrntCmd != null) {
913            validResponse = resMsg.mCmdDet.compareTo(mCurrntCmd.mCmdDet);
914            CatLog.d(this, "isResponse for last valid cmd: " + validResponse);
915        }
916        return validResponse;
917    }
918
919    private boolean removeMenu(Menu menu) {
920        try {
921            if (menu.items.size() == 1 && menu.items.get(0) == null) {
922                return true;
923            }
924        } catch (NullPointerException e) {
925            CatLog.d(this, "Unable to get Menu's items size");
926            return true;
927        }
928        return false;
929    }
930
931    private void handleCmdResponse(CatResponseMessage resMsg) {
932        // Make sure the response details match the last valid command. An invalid
933        // response is a one that doesn't have a corresponding proactive command
934        // and sending it can "confuse" the baseband/ril.
935        // One reason for out of order responses can be UI glitches. For example,
936        // if the application launch an activity, and that activity is stored
937        // by the framework inside the history stack. That activity will be
938        // available for relaunch using the latest application dialog
939        // (long press on the home button). Relaunching that activity can send
940        // the same command's result again to the CatService and can cause it to
941        // get out of sync with the SIM. This can happen in case of
942        // non-interactive type Setup Event List and SETUP_MENU proactive commands.
943        // Stk framework would have already sent Terminal Response to Setup Event
944        // List and SETUP_MENU proactive commands. After sometime Stk app will send
945        // Envelope Command/Event Download. In which case, the response details doesn't
946        // match with last valid command (which are not related).
947        // However, we should allow Stk framework to send the message to ICC.
948        if (!validateResponse(resMsg)) {
949            return;
950        }
951        ResponseData resp = null;
952        boolean helpRequired = false;
953        CommandDetails cmdDet = resMsg.getCmdDetails();
954        AppInterface.CommandType type = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand);
955
956        switch (resMsg.mResCode) {
957        case HELP_INFO_REQUIRED:
958            helpRequired = true;
959            // fall through
960        case OK:
961        case PRFRMD_WITH_PARTIAL_COMPREHENSION:
962        case PRFRMD_WITH_MISSING_INFO:
963        case PRFRMD_WITH_ADDITIONAL_EFS_READ:
964        case PRFRMD_ICON_NOT_DISPLAYED:
965        case PRFRMD_MODIFIED_BY_NAA:
966        case PRFRMD_LIMITED_SERVICE:
967        case PRFRMD_WITH_MODIFICATION:
968        case PRFRMD_NAA_NOT_ACTIVE:
969        case PRFRMD_TONE_NOT_PLAYED:
970        case LAUNCH_BROWSER_ERROR:
971        case TERMINAL_CRNTLY_UNABLE_TO_PROCESS:
972            switch (type) {
973            case SET_UP_MENU:
974                helpRequired = resMsg.mResCode == ResultCode.HELP_INFO_REQUIRED;
975                sendMenuSelection(resMsg.mUsersMenuSelection, helpRequired);
976                return;
977            case SELECT_ITEM:
978                resp = new SelectItemResponseData(resMsg.mUsersMenuSelection);
979                break;
980            case GET_INPUT:
981            case GET_INKEY:
982                Input input = mCurrntCmd.geInput();
983                if (!input.yesNo) {
984                    // when help is requested there is no need to send the text
985                    // string object.
986                    if (!helpRequired) {
987                        resp = new GetInkeyInputResponseData(resMsg.mUsersInput,
988                                input.ucs2, input.packed);
989                    }
990                } else {
991                    resp = new GetInkeyInputResponseData(
992                            resMsg.mUsersYesNoSelection);
993                }
994                break;
995            case DISPLAY_TEXT:
996                if (resMsg.mResCode == ResultCode.TERMINAL_CRNTLY_UNABLE_TO_PROCESS) {
997                    // For screenbusy case there will be addtional information in the terminal
998                    // response. And the value of the additional information byte is 0x01.
999                    resMsg.setAdditionalInfo(0x01);
1000                } else {
1001                    resMsg.mIncludeAdditionalInfo = false;
1002                    resMsg.mAdditionalInfo = 0;
1003                }
1004                break;
1005            case LAUNCH_BROWSER:
1006                break;
1007            // 3GPP TS.102.223: Open Channel alpha confirmation should not send TR
1008            case OPEN_CHANNEL:
1009            case SET_UP_CALL:
1010                mCmdIf.handleCallSetupRequestFromSim(resMsg.mUsersConfirm, null);
1011                // No need to send terminal response for SET UP CALL. The user's
1012                // confirmation result is send back using a dedicated ril message
1013                // invoked by the CommandInterface call above.
1014                mCurrntCmd = null;
1015                return;
1016            case SET_UP_EVENT_LIST:
1017                if (IDLE_SCREEN_AVAILABLE_EVENT == resMsg.mEventValue) {
1018                    eventDownload(resMsg.mEventValue, DEV_ID_DISPLAY, DEV_ID_UICC,
1019                            resMsg.mAddedInfo, false);
1020                 } else {
1021                     eventDownload(resMsg.mEventValue, DEV_ID_TERMINAL, DEV_ID_UICC,
1022                            resMsg.mAddedInfo, false);
1023                 }
1024                // No need to send the terminal response after event download.
1025                return;
1026            default:
1027                break;
1028            }
1029            break;
1030        case BACKWARD_MOVE_BY_USER:
1031        case USER_NOT_ACCEPT:
1032            // if the user dismissed the alert dialog for a
1033            // setup call/open channel, consider that as the user
1034            // rejecting the call. Use dedicated API for this, rather than
1035            // sending a terminal response.
1036            if (type == CommandType.SET_UP_CALL || type == CommandType.OPEN_CHANNEL) {
1037                mCmdIf.handleCallSetupRequestFromSim(false, null);
1038                mCurrntCmd = null;
1039                return;
1040            } else {
1041                resp = null;
1042            }
1043            break;
1044        case NO_RESPONSE_FROM_USER:
1045        case UICC_SESSION_TERM_BY_USER:
1046            resp = null;
1047            break;
1048        default:
1049            return;
1050        }
1051        sendTerminalResponse(cmdDet, resMsg.mResCode, resMsg.mIncludeAdditionalInfo,
1052                resMsg.mAdditionalInfo, resp);
1053        mCurrntCmd = null;
1054    }
1055
1056    private boolean isStkAppInstalled() {
1057        Intent intent = new Intent(AppInterface.CAT_CMD_ACTION);
1058        PackageManager pm = mContext.getPackageManager();
1059        List<ResolveInfo> broadcastReceivers =
1060                            pm.queryBroadcastReceivers(intent, PackageManager.GET_META_DATA);
1061        int numReceiver = broadcastReceivers == null ? 0 : broadcastReceivers.size();
1062
1063        return (numReceiver > 0);
1064    }
1065
1066    public void update(CommandsInterface ci,
1067            Context context, UiccCard ic) {
1068        UiccCardApplication ca = null;
1069        IccRecords ir = null;
1070
1071        if (ic != null) {
1072            /* Since Cat is not tied to any application, but rather is Uicc application
1073             * in itself - just get first FileHandler and IccRecords object
1074             */
1075            ca = ic.getApplicationIndex(0);
1076            if (ca != null) {
1077                ir = ca.getIccRecords();
1078            }
1079        }
1080
1081        synchronized (sInstanceLock) {
1082            if ((ir != null) && (mIccRecords != ir)) {
1083                if (mIccRecords != null) {
1084                    mIccRecords.unregisterForRecordsLoaded(this);
1085                }
1086
1087                CatLog.d(this,
1088                        "Reinitialize the Service with SIMRecords and UiccCardApplication");
1089                mIccRecords = ir;
1090                mUiccApplication = ca;
1091
1092                // re-Register for SIM ready event.
1093                mIccRecords.registerForRecordsLoaded(this, MSG_ID_ICC_RECORDS_LOADED, null);
1094                CatLog.d(this, "registerForRecordsLoaded slotid=" + mSlotId + " instance:" + this);
1095            }
1096        }
1097    }
1098
1099    void updateIccAvailability() {
1100        if (null == mUiccController) {
1101            return;
1102        }
1103
1104        CardState newState = CardState.CARDSTATE_ABSENT;
1105        UiccCard newCard = mUiccController.getUiccCard(mSlotId);
1106        if (newCard != null) {
1107            newState = newCard.getCardState();
1108        }
1109        CardState oldState = mCardState;
1110        mCardState = newState;
1111        CatLog.d(this,"New Card State = " + newState + " " + "Old Card State = " + oldState);
1112        if (oldState == CardState.CARDSTATE_PRESENT &&
1113                newState != CardState.CARDSTATE_PRESENT) {
1114            broadcastCardStateAndIccRefreshResp(newState, null);
1115        } else if (oldState != CardState.CARDSTATE_PRESENT &&
1116                newState == CardState.CARDSTATE_PRESENT) {
1117            // Card moved to PRESENT STATE.
1118            mCmdIf.reportStkServiceIsRunning(null);
1119        }
1120    }
1121}
1122