GsmSMSDispatcher.java revision ac09d2af145b4d820a34f5e7628bc42e2e211bdb
1/*
2 * Copyright (C) 2006 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.gsm;
18
19import android.app.Activity;
20import android.app.PendingIntent;
21import android.app.PendingIntent.CanceledException;
22import android.content.Intent;
23import android.os.AsyncResult;
24import android.os.Message;
25import android.os.SystemProperties;
26import android.provider.Telephony.Sms;
27import android.provider.Telephony.Sms.Intents;
28import android.telephony.PhoneNumberUtils;
29import android.telephony.SmsCbMessage;
30import android.telephony.SmsManager;
31import android.telephony.gsm.GsmCellLocation;
32import android.util.Log;
33
34import com.android.internal.telephony.CommandsInterface;
35import com.android.internal.telephony.IccUtils;
36import com.android.internal.telephony.PhoneBase;
37import com.android.internal.telephony.SMSDispatcher;
38import com.android.internal.telephony.SmsHeader;
39import com.android.internal.telephony.SmsMessageBase;
40import com.android.internal.telephony.SmsMessageBase.TextEncodingDetails;
41import com.android.internal.telephony.SmsStorageMonitor;
42import com.android.internal.telephony.SmsUsageMonitor;
43import com.android.internal.telephony.TelephonyProperties;
44
45import java.util.HashMap;
46import java.util.Iterator;
47
48import static android.telephony.SmsMessage.MessageClass;
49
50public final class GsmSMSDispatcher extends SMSDispatcher {
51    private static final String TAG = "GSM";
52
53    /** Status report received */
54    private static final int EVENT_NEW_SMS_STATUS_REPORT = 100;
55
56    /** New broadcast SMS */
57    private static final int EVENT_NEW_BROADCAST_SMS = 101;
58
59    /** Result of writing SM to UICC (when SMS-PP service is not available). */
60    private static final int EVENT_WRITE_SMS_COMPLETE = 102;
61
62    /** Handler for SMS-PP data download messages to UICC. */
63    private final UsimDataDownloadHandler mDataDownloadHandler;
64
65    public GsmSMSDispatcher(PhoneBase phone, SmsStorageMonitor storageMonitor,
66            SmsUsageMonitor usageMonitor) {
67        super(phone, storageMonitor, usageMonitor);
68        mDataDownloadHandler = new UsimDataDownloadHandler(mCm);
69        mCm.setOnNewGsmSms(this, EVENT_NEW_SMS, null);
70        mCm.setOnSmsStatus(this, EVENT_NEW_SMS_STATUS_REPORT, null);
71        mCm.setOnNewGsmBroadcastSms(this, EVENT_NEW_BROADCAST_SMS, null);
72    }
73
74    @Override
75    public void dispose() {
76        mCm.unSetOnNewGsmSms(this);
77        mCm.unSetOnSmsStatus(this);
78        mCm.unSetOnNewGsmBroadcastSms(this);
79    }
80
81    @Override
82    protected String getFormat() {
83        return android.telephony.SmsMessage.FORMAT_3GPP;
84    }
85
86    /**
87     * Handles 3GPP format-specific events coming from the phone stack.
88     * Other events are handled by {@link SMSDispatcher#handleMessage}.
89     *
90     * @param msg the message to handle
91     */
92    @Override
93    public void handleMessage(Message msg) {
94        switch (msg.what) {
95        case EVENT_NEW_SMS_STATUS_REPORT:
96            handleStatusReport((AsyncResult) msg.obj);
97            break;
98
99        case EVENT_NEW_BROADCAST_SMS:
100            handleBroadcastSms((AsyncResult)msg.obj);
101            break;
102
103        case EVENT_WRITE_SMS_COMPLETE:
104            AsyncResult ar = (AsyncResult) msg.obj;
105            if (ar.exception == null) {
106                Log.d(TAG, "Successfully wrote SMS-PP message to UICC");
107                mCm.acknowledgeLastIncomingGsmSms(true, 0, null);
108            } else {
109                Log.d(TAG, "Failed to write SMS-PP message to UICC", ar.exception);
110                mCm.acknowledgeLastIncomingGsmSms(false,
111                        CommandsInterface.GSM_SMS_FAIL_CAUSE_UNSPECIFIED_ERROR, null);
112            }
113            break;
114
115        default:
116            super.handleMessage(msg);
117        }
118    }
119
120    /**
121     * Called when a status report is received.  This should correspond to
122     * a previously successful SEND.
123     *
124     * @param ar AsyncResult passed into the message handler.  ar.result should
125     *           be a String representing the status report PDU, as ASCII hex.
126     */
127    private void handleStatusReport(AsyncResult ar) {
128        String pduString = (String) ar.result;
129        SmsMessage sms = SmsMessage.newFromCDS(pduString);
130
131        if (sms != null) {
132            int tpStatus = sms.getStatus();
133            int messageRef = sms.messageRef;
134            for (int i = 0, count = deliveryPendingList.size(); i < count; i++) {
135                SmsTracker tracker = deliveryPendingList.get(i);
136                if (tracker.mMessageRef == messageRef) {
137                    // Found it.  Remove from list and broadcast.
138                    if(tpStatus >= Sms.STATUS_FAILED || tpStatus < Sms.STATUS_PENDING ) {
139                       deliveryPendingList.remove(i);
140                    }
141                    PendingIntent intent = tracker.mDeliveryIntent;
142                    Intent fillIn = new Intent();
143                    fillIn.putExtra("pdu", IccUtils.hexStringToBytes(pduString));
144                    fillIn.putExtra("format", android.telephony.SmsMessage.FORMAT_3GPP);
145                    try {
146                        intent.send(mContext, Activity.RESULT_OK, fillIn);
147                    } catch (CanceledException ex) {}
148
149                    // Only expect to see one tracker matching this messageref
150                    break;
151                }
152            }
153        }
154        acknowledgeLastIncomingSms(true, Intents.RESULT_SMS_HANDLED, null);
155    }
156
157    /** {@inheritDoc} */
158    @Override
159    public int dispatchMessage(SmsMessageBase smsb) {
160
161        // If sms is null, means there was a parsing error.
162        if (smsb == null) {
163            Log.e(TAG, "dispatchMessage: message is null");
164            return Intents.RESULT_SMS_GENERIC_ERROR;
165        }
166
167        SmsMessage sms = (SmsMessage) smsb;
168
169        if (sms.isTypeZero()) {
170            // As per 3GPP TS 23.040 9.2.3.9, Type Zero messages should not be
171            // Displayed/Stored/Notified. They should only be acknowledged.
172            Log.d(TAG, "Received short message type 0, Don't display or store it. Send Ack");
173            return Intents.RESULT_SMS_HANDLED;
174        }
175
176        // Send SMS-PP data download messages to UICC. See 3GPP TS 31.111 section 7.1.1.
177        if (sms.isUsimDataDownload()) {
178            UsimServiceTable ust = mPhone.getUsimServiceTable();
179            // If we receive an SMS-PP message before the UsimServiceTable has been loaded,
180            // assume that the data download service is not present. This is very unlikely to
181            // happen because the IMS connection will not be established until after the ISIM
182            // records have been loaded, after the USIM service table has been loaded.
183            if (ust != null && ust.isAvailable(
184                    UsimServiceTable.UsimService.DATA_DL_VIA_SMS_PP)) {
185                Log.d(TAG, "Received SMS-PP data download, sending to UICC.");
186                return mDataDownloadHandler.startDataDownload(sms);
187            } else {
188                Log.d(TAG, "DATA_DL_VIA_SMS_PP service not available, storing message to UICC.");
189                String smsc = IccUtils.bytesToHexString(
190                        PhoneNumberUtils.networkPortionToCalledPartyBCDWithLength(
191                                sms.getServiceCenterAddress()));
192                mCm.writeSmsToSim(SmsManager.STATUS_ON_ICC_UNREAD, smsc,
193                        IccUtils.bytesToHexString(sms.getPdu()),
194                        obtainMessage(EVENT_WRITE_SMS_COMPLETE));
195                return Activity.RESULT_OK;  // acknowledge after response from write to USIM
196            }
197        }
198
199        if (mSmsReceiveDisabled) {
200            // Device doesn't support SMS service,
201            Log.d(TAG, "Received short message on device which doesn't support "
202                    + "SMS service. Ignored.");
203            return Intents.RESULT_SMS_HANDLED;
204        }
205
206        // Special case the message waiting indicator messages
207        boolean handled = false;
208        if (sms.isMWISetMessage()) {
209            mPhone.setVoiceMessageWaiting(1, -1);  // line 1: unknown number of msgs waiting
210            handled = sms.isMwiDontStore();
211            if (false) {
212                Log.d(TAG, "Received voice mail indicator set SMS shouldStore=" + !handled);
213            }
214        } else if (sms.isMWIClearMessage()) {
215            mPhone.setVoiceMessageWaiting(1, 0);   // line 1: no msgs waiting
216            handled = sms.isMwiDontStore();
217            if (false) {
218                Log.d(TAG, "Received voice mail indicator clear SMS shouldStore=" + !handled);
219            }
220        }
221
222        if (handled) {
223            return Intents.RESULT_SMS_HANDLED;
224        }
225
226        if (!mStorageMonitor.isStorageAvailable() &&
227                sms.getMessageClass() != MessageClass.CLASS_0) {
228            // It's a storable message and there's no storage available.  Bail.
229            // (See TS 23.038 for a description of class 0 messages.)
230            return Intents.RESULT_SMS_OUT_OF_MEMORY;
231        }
232
233        return dispatchNormalMessage(smsb);
234    }
235
236    /** {@inheritDoc} */
237    @Override
238    protected void sendData(String destAddr, String scAddr, int destPort,
239            byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) {
240        SmsMessage.SubmitPdu pdu = SmsMessage.getSubmitPdu(
241                scAddr, destAddr, destPort, data, (deliveryIntent != null));
242        sendRawPdu(pdu.encodedScAddress, pdu.encodedMessage, sentIntent, deliveryIntent);
243    }
244
245    /** {@inheritDoc} */
246    @Override
247    protected void sendText(String destAddr, String scAddr, String text,
248            PendingIntent sentIntent, PendingIntent deliveryIntent) {
249        SmsMessage.SubmitPdu pdu = SmsMessage.getSubmitPdu(
250                scAddr, destAddr, text, (deliveryIntent != null));
251        sendRawPdu(pdu.encodedScAddress, pdu.encodedMessage, sentIntent, deliveryIntent);
252    }
253
254    /** {@inheritDoc} */
255    @Override
256    protected TextEncodingDetails calculateLength(CharSequence messageBody,
257            boolean use7bitOnly) {
258        return SmsMessage.calculateLength(messageBody, use7bitOnly);
259    }
260
261    /** {@inheritDoc} */
262    @Override
263    protected void sendNewSubmitPdu(String destinationAddress, String scAddress,
264            String message, SmsHeader smsHeader, int encoding,
265            PendingIntent sentIntent, PendingIntent deliveryIntent, boolean lastPart) {
266        SmsMessage.SubmitPdu pdu = SmsMessage.getSubmitPdu(scAddress, destinationAddress,
267                message, deliveryIntent != null, SmsHeader.toByteArray(smsHeader),
268                encoding, smsHeader.languageTable, smsHeader.languageShiftTable);
269        sendRawPdu(pdu.encodedScAddress, pdu.encodedMessage, sentIntent, deliveryIntent);
270    }
271
272    /** {@inheritDoc} */
273    @Override
274    protected void sendSms(SmsTracker tracker) {
275        HashMap<String, Object> map = tracker.mData;
276
277        byte smsc[] = (byte[]) map.get("smsc");
278        byte pdu[] = (byte[]) map.get("pdu");
279
280        Message reply = obtainMessage(EVENT_SEND_SMS_COMPLETE, tracker);
281        mCm.sendSMS(IccUtils.bytesToHexString(smsc), IccUtils.bytesToHexString(pdu), reply);
282    }
283
284    /** {@inheritDoc} */
285    @Override
286    protected void acknowledgeLastIncomingSms(boolean success, int result, Message response) {
287        mCm.acknowledgeLastIncomingGsmSms(success, resultToCause(result), response);
288    }
289
290    private static int resultToCause(int rc) {
291        switch (rc) {
292            case Activity.RESULT_OK:
293            case Intents.RESULT_SMS_HANDLED:
294                // Cause code is ignored on success.
295                return 0;
296            case Intents.RESULT_SMS_OUT_OF_MEMORY:
297                return CommandsInterface.GSM_SMS_FAIL_CAUSE_MEMORY_CAPACITY_EXCEEDED;
298            case Intents.RESULT_SMS_GENERIC_ERROR:
299            default:
300                return CommandsInterface.GSM_SMS_FAIL_CAUSE_UNSPECIFIED_ERROR;
301        }
302    }
303
304    /**
305     * Holds all info about a message page needed to assemble a complete
306     * concatenated message
307     */
308    private static final class SmsCbConcatInfo {
309        private final SmsCbHeader mHeader;
310
311        private final String mPlmn;
312
313        private final int mLac;
314
315        private final int mCid;
316
317        public SmsCbConcatInfo(SmsCbHeader header, String plmn, int lac, int cid) {
318            mHeader = header;
319            mPlmn = plmn;
320            mLac = lac;
321            mCid = cid;
322        }
323
324        @Override
325        public int hashCode() {
326            return mHeader.messageIdentifier * 31 + mHeader.updateNumber;
327        }
328
329        @Override
330        public boolean equals(Object obj) {
331            if (obj instanceof SmsCbConcatInfo) {
332                SmsCbConcatInfo other = (SmsCbConcatInfo)obj;
333
334                // Two pages match if all header attributes (except the page
335                // index) are identical, and both pages belong to the same
336                // location (which is also determined by the scope parameter)
337                if (mHeader.geographicalScope == other.mHeader.geographicalScope
338                        && mHeader.messageCode == other.mHeader.messageCode
339                        && mHeader.updateNumber == other.mHeader.updateNumber
340                        && mHeader.messageIdentifier == other.mHeader.messageIdentifier
341                        && mHeader.dataCodingScheme == other.mHeader.dataCodingScheme
342                        && mHeader.nrOfPages == other.mHeader.nrOfPages) {
343                    return matchesLocation(other.mPlmn, other.mLac, other.mCid);
344                }
345            }
346
347            return false;
348        }
349
350        /**
351         * Checks if this concatenation info matches the given location. The
352         * granularity of the match depends on the geographical scope.
353         *
354         * @param plmn PLMN
355         * @param lac Location area code
356         * @param cid Cell ID
357         * @return true if matching, false otherwise
358         */
359        public boolean matchesLocation(String plmn, int lac, int cid) {
360            switch (mHeader.geographicalScope) {
361                case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE:
362                case SmsCbMessage.GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE:
363                    if (mCid != cid) {
364                        return false;
365                    }
366                    // deliberate fall-through
367                case SmsCbMessage.GEOGRAPHICAL_SCOPE_LA_WIDE:
368                    if (mLac != lac) {
369                        return false;
370                    }
371                    // deliberate fall-through
372                case SmsCbMessage.GEOGRAPHICAL_SCOPE_PLMN_WIDE:
373                    return mPlmn != null && mPlmn.equals(plmn);
374            }
375
376            return false;
377        }
378    }
379
380    // This map holds incomplete concatenated messages waiting for assembly
381    private final HashMap<SmsCbConcatInfo, byte[][]> mSmsCbPageMap =
382            new HashMap<SmsCbConcatInfo, byte[][]>();
383
384    /**
385     * Handle 3GPP format SMS-CB message.
386     * @param ar the AsyncResult containing the received PDUs
387     */
388    private void handleBroadcastSms(AsyncResult ar) {
389        try {
390            byte[] receivedPdu = (byte[])ar.result;
391
392            if (false) {
393                for (int i = 0; i < receivedPdu.length; i += 8) {
394                    StringBuilder sb = new StringBuilder("SMS CB pdu data: ");
395                    for (int j = i; j < i + 8 && j < receivedPdu.length; j++) {
396                        int b = receivedPdu[j] & 0xff;
397                        if (b < 0x10) {
398                            sb.append('0');
399                        }
400                        sb.append(Integer.toHexString(b)).append(' ');
401                    }
402                    Log.d(TAG, sb.toString());
403                }
404            }
405
406            SmsCbHeader header = new SmsCbHeader(receivedPdu);
407            String plmn = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC);
408            GsmCellLocation cellLocation = (GsmCellLocation) mPhone.getCellLocation();
409            int lac = cellLocation.getLac();
410            int cid = cellLocation.getCid();
411
412            byte[][] pdus;
413            if (header.nrOfPages > 1) {
414                // Multi-page message
415                SmsCbConcatInfo concatInfo = new SmsCbConcatInfo(header, plmn, lac, cid);
416
417                // Try to find other pages of the same message
418                pdus = mSmsCbPageMap.get(concatInfo);
419
420                if (pdus == null) {
421                    // This it the first page of this message, make room for all
422                    // pages and keep until complete
423                    pdus = new byte[header.nrOfPages][];
424
425                    mSmsCbPageMap.put(concatInfo, pdus);
426                }
427
428                // Page parameter is one-based
429                pdus[header.pageIndex - 1] = receivedPdu;
430
431                for (int i = 0; i < pdus.length; i++) {
432                    if (pdus[i] == null) {
433                        // Still missing pages, exit
434                        return;
435                    }
436                }
437
438                // Message complete, remove and dispatch
439                mSmsCbPageMap.remove(concatInfo);
440            } else {
441                // Single page message
442                pdus = new byte[1][];
443                pdus[0] = receivedPdu;
444            }
445
446            boolean isEmergencyMessage = SmsCbHeader.isEmergencyMessage(header.messageIdentifier);
447            dispatchBroadcastPdus(pdus, isEmergencyMessage);
448
449            // Remove messages that are out of scope to prevent the map from
450            // growing indefinitely, containing incomplete messages that were
451            // never assembled
452            Iterator<SmsCbConcatInfo> iter = mSmsCbPageMap.keySet().iterator();
453
454            while (iter.hasNext()) {
455                SmsCbConcatInfo info = iter.next();
456
457                if (!info.matchesLocation(plmn, lac, cid)) {
458                    iter.remove();
459                }
460            }
461        } catch (RuntimeException e) {
462            Log.e(TAG, "Error in decoding SMS CB pdu", e);
463        }
464    }
465}
466