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