SMSDispatcher.java revision db71bda6f696aff6047e6c26c32e0c08bf6851bc
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;
18
19import android.app.Activity;
20import android.app.PendingIntent;
21import android.app.AlertDialog;
22import android.app.PendingIntent.CanceledException;
23import android.content.BroadcastReceiver;
24import android.content.ContentResolver;
25import android.content.ContentValues;
26import android.content.Context;
27import android.content.Intent;
28import android.content.DialogInterface;
29import android.content.IntentFilter;
30import android.content.res.Resources;
31import android.database.Cursor;
32import android.database.SQLException;
33import android.net.Uri;
34import android.os.AsyncResult;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.PowerManager;
39import android.os.StatFs;
40import android.provider.Telephony;
41import android.provider.Telephony.Sms.Intents;
42import android.provider.Settings;
43import android.telephony.SmsMessage;
44import android.telephony.ServiceState;
45import android.util.Config;
46import android.util.Log;
47import android.view.WindowManager;
48
49import com.android.internal.util.HexDump;
50
51import java.io.ByteArrayOutputStream;
52import java.util.ArrayList;
53import java.util.HashMap;
54import java.util.Random;
55
56import com.android.internal.R;
57
58import static android.telephony.SmsManager.RESULT_ERROR_GENERIC_FAILURE;
59import static android.telephony.SmsManager.RESULT_ERROR_NO_SERVICE;
60import static android.telephony.SmsManager.RESULT_ERROR_NULL_PDU;
61import static android.telephony.SmsManager.RESULT_ERROR_RADIO_OFF;
62import static android.telephony.SmsManager.RESULT_ERROR_LIMIT_EXCEEDED;
63import static android.telephony.SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE;
64
65
66public abstract class SMSDispatcher extends Handler {
67    private static final String TAG = "SMS";
68    private static final String SEND_NEXT_MSG_EXTRA = "SendNextMsg";
69
70    /** Default checking period for SMS sent without user permit */
71    private static final int DEFAULT_SMS_CHECK_PERIOD = 3600000;
72
73    /** Default number of SMS sent in checking period without user permit */
74    private static final int DEFAULT_SMS_MAX_COUNT = 100;
75
76    /** Default timeout for SMS sent query */
77    private static final int DEFAULT_SMS_TIMEOUT = 6000;
78
79    protected static final String[] RAW_PROJECTION = new String[] {
80        "pdu",
81        "sequence",
82        "destination_port",
83    };
84
85    static final protected int EVENT_NEW_SMS = 1;
86
87    static final protected int EVENT_SEND_SMS_COMPLETE = 2;
88
89    /** Retry sending a previously failed SMS message */
90    static final protected int EVENT_SEND_RETRY = 3;
91
92    /** Status report received */
93    static final protected int EVENT_NEW_SMS_STATUS_REPORT = 5;
94
95    /** SIM/RUIM storage is full */
96    static final protected int EVENT_ICC_FULL = 6;
97
98    /** SMS confirm required */
99    static final protected int EVENT_POST_ALERT = 7;
100
101    /** Send the user confirmed SMS */
102    static final protected int EVENT_SEND_CONFIRMED_SMS = 8;
103
104    /** Alert is timeout */
105    static final protected int EVENT_ALERT_TIMEOUT = 9;
106
107    /** Stop the sending */
108    static final protected int EVENT_STOP_SENDING = 10;
109
110    /** Memory status reporting is acknowledged by RIL */
111    static final protected int EVENT_REPORT_MEMORY_STATUS_DONE = 11;
112
113    /** Radio is ON */
114    static final protected int EVENT_RADIO_ON = 12;
115
116    /** New broadcast SMS */
117    static final protected int EVENT_NEW_BROADCAST_SMS = 13;
118
119    protected Phone mPhone;
120    protected Context mContext;
121    protected ContentResolver mResolver;
122    protected CommandsInterface mCm;
123
124    protected final WapPushOverSms mWapPush;
125
126    protected final Uri mRawUri = Uri.withAppendedPath(Telephony.Sms.CONTENT_URI, "raw");
127
128    /** Maximum number of times to retry sending a failed SMS. */
129    private static final int MAX_SEND_RETRIES = 3;
130    /** Delay before next send attempt on a failed SMS, in milliseconds. */
131    private static final int SEND_RETRY_DELAY = 2000;
132    /** single part SMS */
133    private static final int SINGLE_PART_SMS = 1;
134    /** Message sending queue limit */
135    private static final int MO_MSG_QUEUE_LIMIT = 5;
136
137    /**
138     * Message reference for a CONCATENATED_8_BIT_REFERENCE or
139     * CONCATENATED_16_BIT_REFERENCE message set.  Should be
140     * incremented for each set of concatenated messages.
141     */
142    private static int sConcatenatedRef;
143
144    private SmsCounter mCounter;
145
146    private ArrayList<SmsTracker> mSTrackers = new ArrayList<SmsTracker>(MO_MSG_QUEUE_LIMIT);
147
148    /** Wake lock to ensure device stays awake while dispatching the SMS intent. */
149    private PowerManager.WakeLock mWakeLock;
150
151    /**
152     * Hold the wake lock for 5 seconds, which should be enough time for
153     * any receiver(s) to grab its own wake lock.
154     */
155    private final int WAKE_LOCK_TIMEOUT = 5000;
156
157    protected boolean mStorageAvailable = true;
158    protected boolean mReportMemoryStatusPending = false;
159
160    protected static int mRemainingMessages = -1;
161
162    protected static int getNextConcatenatedRef() {
163        sConcatenatedRef += 1;
164        return sConcatenatedRef;
165    }
166
167    /**
168     *  Implement the per-application based SMS control, which only allows
169     *  a limit on the number of SMS/MMS messages an app can send in checking
170     *  period.
171     */
172    private class SmsCounter {
173        private int mCheckPeriod;
174        private int mMaxAllowed;
175        private HashMap<String, ArrayList<Long>> mSmsStamp;
176
177        /**
178         * Create SmsCounter
179         * @param mMax is the number of SMS allowed without user permit
180         * @param mPeriod is the checking period
181         */
182        SmsCounter(int mMax, int mPeriod) {
183            mMaxAllowed = mMax;
184            mCheckPeriod = mPeriod;
185            mSmsStamp = new HashMap<String, ArrayList<Long>> ();
186        }
187
188        /**
189         * Check to see if an application allow to send new SMS messages
190         *
191         * @param appName is the application sending sms
192         * @param smsWaiting is the number of new sms wants to be sent
193         * @return true if application is allowed to send the requested number
194         *         of new sms messages
195         */
196        boolean check(String appName, int smsWaiting) {
197            if (!mSmsStamp.containsKey(appName)) {
198                mSmsStamp.put(appName, new ArrayList<Long>());
199            }
200
201            return isUnderLimit(mSmsStamp.get(appName), smsWaiting);
202        }
203
204        private boolean isUnderLimit(ArrayList<Long> sent, int smsWaiting) {
205            Long ct =  System.currentTimeMillis();
206
207            Log.d(TAG, "SMS send size=" + sent.size() + "time=" + ct);
208
209            while (sent.size() > 0 && (ct - sent.get(0)) > mCheckPeriod ) {
210                    sent.remove(0);
211            }
212
213
214            if ( (sent.size() + smsWaiting) <= mMaxAllowed) {
215                for (int i = 0; i < smsWaiting; i++ ) {
216                    sent.add(ct);
217                }
218                return true;
219            }
220            return false;
221        }
222    }
223
224    protected SMSDispatcher(PhoneBase phone) {
225        mPhone = phone;
226        mWapPush = new WapPushOverSms(phone, this);
227        mContext = phone.getContext();
228        mResolver = mContext.getContentResolver();
229        mCm = phone.mCM;
230
231        createWakelock();
232
233        int check_period = Settings.Secure.getInt(mResolver,
234                Settings.Secure.SMS_OUTGOING_CHECK_INTERVAL_MS,
235                DEFAULT_SMS_CHECK_PERIOD);
236        int max_count = Settings.Secure.getInt(mResolver,
237                Settings.Secure.SMS_OUTGOING_CHECK_MAX_COUNT,
238                DEFAULT_SMS_MAX_COUNT);
239        mCounter = new SmsCounter(max_count, check_period);
240
241        mCm.setOnNewSMS(this, EVENT_NEW_SMS, null);
242        mCm.setOnSmsStatus(this, EVENT_NEW_SMS_STATUS_REPORT, null);
243        mCm.setOnIccSmsFull(this, EVENT_ICC_FULL, null);
244        mCm.registerForOn(this, EVENT_RADIO_ON, null);
245
246        // Don't always start message ref at 0.
247        sConcatenatedRef = new Random().nextInt(256);
248
249        // Register for device storage intents.  Use these to notify the RIL
250        // that storage for SMS is or is not available.
251        IntentFilter filter = new IntentFilter();
252        filter.addAction(Intent.ACTION_DEVICE_STORAGE_FULL);
253        filter.addAction(Intent.ACTION_DEVICE_STORAGE_NOT_FULL);
254        mContext.registerReceiver(mResultReceiver, filter);
255    }
256
257    public void dispose() {
258        mCm.unSetOnNewSMS(this);
259        mCm.unSetOnSmsStatus(this);
260        mCm.unSetOnIccSmsFull(this);
261        mCm.unregisterForOn(this);
262    }
263
264    protected void finalize() {
265        Log.d(TAG, "SMSDispatcher finalized");
266    }
267
268
269    /* TODO: Need to figure out how to keep track of status report routing in a
270     *       persistent manner. If the phone process restarts (reboot or crash),
271     *       we will lose this list and any status reports that come in after
272     *       will be dropped.
273     */
274    /** Sent messages awaiting a delivery status report. */
275    protected final ArrayList<SmsTracker> deliveryPendingList = new ArrayList<SmsTracker>();
276
277    /**
278     * Handles events coming from the phone stack. Overridden from handler.
279     *
280     * @param msg the message to handle
281     */
282    @Override
283    public void handleMessage(Message msg) {
284        AsyncResult ar;
285
286        switch (msg.what) {
287        case EVENT_NEW_SMS:
288            // A new SMS has been received by the device
289            if (Config.LOGD) {
290                Log.d(TAG, "New SMS Message Received");
291            }
292
293            SmsMessage sms;
294
295            ar = (AsyncResult) msg.obj;
296
297            if (ar.exception != null) {
298                Log.e(TAG, "Exception processing incoming SMS. Exception:" + ar.exception);
299                return;
300            }
301
302            sms = (SmsMessage) ar.result;
303            try {
304                int result = dispatchMessage(sms.mWrappedSmsMessage);
305                if (result != Activity.RESULT_OK) {
306                    // RESULT_OK means that message was broadcast for app(s) to handle.
307                    // Any other result, we should ack here.
308                    boolean handled = (result == Intents.RESULT_SMS_HANDLED);
309                    notifyAndAcknowledgeLastIncomingSms(handled, result, null);
310                }
311            } catch (RuntimeException ex) {
312                Log.e(TAG, "Exception dispatching message", ex);
313                notifyAndAcknowledgeLastIncomingSms(false, Intents.RESULT_SMS_GENERIC_ERROR, null);
314            }
315
316            break;
317
318        case EVENT_SEND_SMS_COMPLETE:
319            // An outbound SMS has been successfully transferred, or failed.
320            handleSendComplete((AsyncResult) msg.obj);
321            break;
322
323        case EVENT_SEND_RETRY:
324            sendSms((SmsTracker) msg.obj);
325            break;
326
327        case EVENT_NEW_SMS_STATUS_REPORT:
328            handleStatusReport((AsyncResult)msg.obj);
329            break;
330
331        case EVENT_ICC_FULL:
332            handleIccFull();
333            break;
334
335        case EVENT_POST_ALERT:
336            handleReachSentLimit((SmsTracker)(msg.obj));
337            break;
338
339        case EVENT_ALERT_TIMEOUT:
340            ((AlertDialog)(msg.obj)).dismiss();
341            msg.obj = null;
342            if (mSTrackers.isEmpty() == false) {
343                try {
344                    SmsTracker sTracker = mSTrackers.remove(0);
345                    sTracker.mSentIntent.send(RESULT_ERROR_LIMIT_EXCEEDED);
346                } catch (CanceledException ex) {
347                    Log.e(TAG, "failed to send back RESULT_ERROR_LIMIT_EXCEEDED");
348                }
349            }
350            if (Config.LOGD) {
351                Log.d(TAG, "EVENT_ALERT_TIMEOUT, message stop sending");
352            }
353            break;
354
355        case EVENT_SEND_CONFIRMED_SMS:
356            if (mSTrackers.isEmpty() == false) {
357                SmsTracker sTracker = mSTrackers.remove(mSTrackers.size() - 1);
358                if (isMultipartTracker(sTracker)) {
359                    sendMultipartSms(sTracker);
360                } else {
361                    sendSms(sTracker);
362                }
363                removeMessages(EVENT_ALERT_TIMEOUT, msg.obj);
364            }
365            break;
366
367        case EVENT_STOP_SENDING:
368            if (mSTrackers.isEmpty() == false) {
369                // Remove the latest one.
370                try {
371                    SmsTracker sTracker = mSTrackers.remove(mSTrackers.size() - 1);
372                    sTracker.mSentIntent.send(RESULT_ERROR_LIMIT_EXCEEDED);
373                } catch (CanceledException ex) {
374                    Log.e(TAG, "failed to send back RESULT_ERROR_LIMIT_EXCEEDED");
375                }
376                removeMessages(EVENT_ALERT_TIMEOUT, msg.obj);
377            }
378            break;
379
380        case EVENT_REPORT_MEMORY_STATUS_DONE:
381            ar = (AsyncResult)msg.obj;
382            if (ar.exception != null) {
383                mReportMemoryStatusPending = true;
384                Log.v(TAG, "Memory status report to modem pending : mStorageAvailable = "
385                        + mStorageAvailable);
386            } else {
387                mReportMemoryStatusPending = false;
388            }
389            break;
390
391        case EVENT_RADIO_ON:
392            if (mReportMemoryStatusPending) {
393                Log.v(TAG, "Sending pending memory status report : mStorageAvailable = "
394                        + mStorageAvailable);
395                mCm.reportSmsMemoryStatus(mStorageAvailable,
396                        obtainMessage(EVENT_REPORT_MEMORY_STATUS_DONE));
397            }
398
399        case EVENT_NEW_BROADCAST_SMS:
400            handleBroadcastSms((AsyncResult)msg.obj);
401            break;
402        }
403    }
404
405    private void createWakelock() {
406        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
407        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SMSDispatcher");
408        mWakeLock.setReferenceCounted(true);
409    }
410
411    /**
412     * Grabs a wake lock and sends intent as an ordered broadcast.
413     * The resultReceiver will check for errors and ACK/NACK back
414     * to the RIL.
415     *
416     * @param intent intent to broadcast
417     * @param permission Receivers are required to have this permission
418     */
419    void dispatch(Intent intent, String permission) {
420        // Hold a wake lock for WAKE_LOCK_TIMEOUT seconds, enough to give any
421        // receivers time to take their own wake locks.
422        mWakeLock.acquire(WAKE_LOCK_TIMEOUT);
423        mContext.sendOrderedBroadcast(intent, permission, mResultReceiver,
424                this, Activity.RESULT_OK, null, null);
425    }
426
427    /**
428     * Called when SIM_FULL message is received from the RIL.  Notifies interested
429     * parties that SIM storage for SMS messages is full.
430     */
431    private void handleIccFull(){
432        // broadcast SIM_FULL intent
433        Intent intent = new Intent(Intents.SIM_FULL_ACTION);
434        mWakeLock.acquire(WAKE_LOCK_TIMEOUT);
435        mContext.sendBroadcast(intent, "android.permission.RECEIVE_SMS");
436    }
437
438    /**
439     * Called when a status report is received.  This should correspond to
440     * a previously successful SEND.
441     *
442     * @param ar AsyncResult passed into the message handler.  ar.result should
443     *           be a String representing the status report PDU, as ASCII hex.
444     */
445    protected abstract void handleStatusReport(AsyncResult ar);
446
447    /**
448     * Called when SMS send completes. Broadcasts a sentIntent on success.
449     * On failure, either sets up retries or broadcasts a sentIntent with
450     * the failure in the result code.
451     *
452     * @param ar AsyncResult passed into the message handler.  ar.result should
453     *           an SmsResponse instance if send was successful.  ar.userObj
454     *           should be an SmsTracker instance.
455     */
456    protected void handleSendComplete(AsyncResult ar) {
457        SmsTracker tracker = (SmsTracker) ar.userObj;
458        PendingIntent sentIntent = tracker.mSentIntent;
459
460        if (ar.exception == null) {
461            if (Config.LOGD) {
462                Log.d(TAG, "SMS send complete. Broadcasting "
463                        + "intent: " + sentIntent);
464            }
465
466            if (tracker.mDeliveryIntent != null) {
467                // Expecting a status report.  Add it to the list.
468                int messageRef = ((SmsResponse)ar.result).messageRef;
469                tracker.mMessageRef = messageRef;
470                deliveryPendingList.add(tracker);
471            }
472
473            if (sentIntent != null) {
474                try {
475                    if (mRemainingMessages > -1) {
476                        mRemainingMessages--;
477                    }
478
479                    if (mRemainingMessages == 0) {
480                        Intent sendNext = new Intent();
481                        sendNext.putExtra(SEND_NEXT_MSG_EXTRA, true);
482                        sentIntent.send(mContext, Activity.RESULT_OK, sendNext);
483                    } else {
484                        sentIntent.send(Activity.RESULT_OK);
485                    }
486                } catch (CanceledException ex) {}
487            }
488        } else {
489            if (Config.LOGD) {
490                Log.d(TAG, "SMS send failed");
491            }
492
493            int ss = mPhone.getServiceState().getState();
494
495            if (ss != ServiceState.STATE_IN_SERVICE) {
496                handleNotInService(ss, tracker);
497            } else if ((((CommandException)(ar.exception)).getCommandError()
498                    == CommandException.Error.SMS_FAIL_RETRY) &&
499                   tracker.mRetryCount < MAX_SEND_RETRIES) {
500                // Retry after a delay if needed.
501                // TODO: According to TS 23.040, 9.2.3.6, we should resend
502                //       with the same TP-MR as the failed message, and
503                //       TP-RD set to 1.  However, we don't have a means of
504                //       knowing the MR for the failed message (EF_SMSstatus
505                //       may or may not have the MR corresponding to this
506                //       message, depending on the failure).  Also, in some
507                //       implementations this retry is handled by the baseband.
508                tracker.mRetryCount++;
509                Message retryMsg = obtainMessage(EVENT_SEND_RETRY, tracker);
510                sendMessageDelayed(retryMsg, SEND_RETRY_DELAY);
511            } else if (tracker.mSentIntent != null) {
512                int error = RESULT_ERROR_GENERIC_FAILURE;
513
514                if (((CommandException)(ar.exception)).getCommandError()
515                        == CommandException.Error.FDN_CHECK_FAILURE) {
516                    error = RESULT_ERROR_FDN_CHECK_FAILURE;
517                }
518                // Done retrying; return an error to the app.
519                try {
520                    Intent fillIn = new Intent();
521                    if (ar.result != null) {
522                        fillIn.putExtra("errorCode", ((SmsResponse)ar.result).errorCode);
523                    }
524                    if (mRemainingMessages > -1) {
525                        mRemainingMessages--;
526                    }
527
528                    if (mRemainingMessages == 0) {
529                        fillIn.putExtra(SEND_NEXT_MSG_EXTRA, true);
530                    }
531
532                    tracker.mSentIntent.send(mContext, error, fillIn);
533                } catch (CanceledException ex) {}
534            }
535        }
536    }
537
538    /**
539     * Handles outbound message when the phone is not in service.
540     *
541     * @param ss     Current service state.  Valid values are:
542     *                  OUT_OF_SERVICE
543     *                  EMERGENCY_ONLY
544     *                  POWER_OFF
545     * @param tracker   An SmsTracker for the current message.
546     */
547    protected void handleNotInService(int ss, SmsTracker tracker) {
548        if (tracker.mSentIntent != null) {
549            try {
550                if (ss == ServiceState.STATE_POWER_OFF) {
551                    tracker.mSentIntent.send(RESULT_ERROR_RADIO_OFF);
552                } else {
553                    tracker.mSentIntent.send(RESULT_ERROR_NO_SERVICE);
554                }
555            } catch (CanceledException ex) {}
556        }
557    }
558
559    /**
560     * Dispatches an incoming SMS messages.
561     *
562     * @param sms the incoming message from the phone
563     * @return a result code from {@link Telephony.Sms.Intents}, or
564     *         {@link Activity#RESULT_OK} if the message has been broadcast
565     *         to applications
566     */
567    protected abstract int dispatchMessage(SmsMessageBase sms);
568
569
570    /**
571     * If this is the last part send the parts out to the application, otherwise
572     * the part is stored for later processing.
573     *
574     * NOTE: concatRef (naturally) needs to be non-null, but portAddrs can be null.
575     * @return a result code from {@link Telephony.Sms.Intents}, or
576     *         {@link Activity#RESULT_OK} if the message has been broadcast
577     *         to applications
578     */
579    protected int processMessagePart(SmsMessageBase sms,
580            SmsHeader.ConcatRef concatRef, SmsHeader.PortAddrs portAddrs) {
581
582        // Lookup all other related parts
583        StringBuilder where = new StringBuilder("reference_number =");
584        where.append(concatRef.refNumber);
585        where.append(" AND address = ?");
586        String[] whereArgs = new String[] {sms.getOriginatingAddress()};
587
588        byte[][] pdus = null;
589        Cursor cursor = null;
590        try {
591            cursor = mResolver.query(mRawUri, RAW_PROJECTION, where.toString(), whereArgs, null);
592            int cursorCount = cursor.getCount();
593            if (cursorCount != concatRef.msgCount - 1) {
594                // We don't have all the parts yet, store this one away
595                ContentValues values = new ContentValues();
596                values.put("date", new Long(sms.getTimestampMillis()));
597                values.put("pdu", HexDump.toHexString(sms.getPdu()));
598                values.put("address", sms.getOriginatingAddress());
599                values.put("reference_number", concatRef.refNumber);
600                values.put("count", concatRef.msgCount);
601                values.put("sequence", concatRef.seqNumber);
602                if (portAddrs != null) {
603                    values.put("destination_port", portAddrs.destPort);
604                }
605                mResolver.insert(mRawUri, values);
606                return Intents.RESULT_SMS_HANDLED;
607            }
608
609            // All the parts are in place, deal with them
610            int pduColumn = cursor.getColumnIndex("pdu");
611            int sequenceColumn = cursor.getColumnIndex("sequence");
612
613            pdus = new byte[concatRef.msgCount][];
614            for (int i = 0; i < cursorCount; i++) {
615                cursor.moveToNext();
616                int cursorSequence = (int)cursor.getLong(sequenceColumn);
617                pdus[cursorSequence - 1] = HexDump.hexStringToByteArray(
618                        cursor.getString(pduColumn));
619            }
620            // This one isn't in the DB, so add it
621            pdus[concatRef.seqNumber - 1] = sms.getPdu();
622
623            // Remove the parts from the database
624            mResolver.delete(mRawUri, where.toString(), whereArgs);
625        } catch (SQLException e) {
626            Log.e(TAG, "Can't access multipart SMS database", e);
627            // TODO:  Would OUT_OF_MEMORY be more appropriate?
628            return Intents.RESULT_SMS_GENERIC_ERROR;
629        } finally {
630            if (cursor != null) cursor.close();
631        }
632
633        /**
634         * TODO(cleanup): The following code has duplicated logic with
635         * the radio-specific dispatchMessage code, which is fragile,
636         * in addition to being redundant.  Instead, if this method
637         * maybe returned the reassembled message (or just contents),
638         * the following code (which is not really related to
639         * reconstruction) could be better consolidated.
640         */
641
642        // Dispatch the PDUs to applications
643        if (portAddrs != null) {
644            if (portAddrs.destPort == SmsHeader.PORT_WAP_PUSH) {
645                // Build up the data stream
646                ByteArrayOutputStream output = new ByteArrayOutputStream();
647                for (int i = 0; i < concatRef.msgCount; i++) {
648                    SmsMessage msg = SmsMessage.createFromPdu(pdus[i]);
649                    byte[] data = msg.getUserData();
650                    output.write(data, 0, data.length);
651                }
652                // Handle the PUSH
653                return mWapPush.dispatchWapPdu(output.toByteArray());
654            } else {
655                // The messages were sent to a port, so concoct a URI for it
656                dispatchPortAddressedPdus(pdus, portAddrs.destPort);
657            }
658        } else {
659            // The messages were not sent to a port
660            dispatchPdus(pdus);
661        }
662        return Activity.RESULT_OK;
663    }
664
665    /**
666     * Dispatches standard PDUs to interested applications
667     *
668     * @param pdus The raw PDUs making up the message
669     */
670    protected void dispatchPdus(byte[][] pdus) {
671        Intent intent = new Intent(Intents.SMS_RECEIVED_ACTION);
672        intent.putExtra("pdus", pdus);
673        dispatch(intent, "android.permission.RECEIVE_SMS");
674    }
675
676    /**
677     * Dispatches port addressed PDUs to interested applications
678     *
679     * @param pdus The raw PDUs making up the message
680     * @param port The destination port of the messages
681     */
682    protected void dispatchPortAddressedPdus(byte[][] pdus, int port) {
683        Uri uri = Uri.parse("sms://localhost:" + port);
684        Intent intent = new Intent(Intents.DATA_SMS_RECEIVED_ACTION, uri);
685        intent.putExtra("pdus", pdus);
686        dispatch(intent, "android.permission.RECEIVE_SMS");
687    }
688
689    /**
690     * Send a data based SMS to a specific application port.
691     *
692     * @param destAddr the address to send the message to
693     * @param scAddr is the service center address or null to use
694     *  the current default SMSC
695     * @param destPort the port to deliver the message to
696     * @param data the body of the message to send
697     * @param sentIntent if not NULL this <code>PendingIntent</code> is
698     *  broadcast when the message is successfully sent, or failed.
699     *  The result code will be <code>Activity.RESULT_OK<code> for success,
700     *  or one of these errors:<br>
701     *  <code>RESULT_ERROR_GENERIC_FAILURE</code><br>
702     *  <code>RESULT_ERROR_RADIO_OFF</code><br>
703     *  <code>RESULT_ERROR_NULL_PDU</code><br>
704     *  For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include
705     *  the extra "errorCode" containing a radio technology specific value,
706     *  generally only useful for troubleshooting.<br>
707     *  The per-application based SMS control checks sentIntent. If sentIntent
708     *  is NULL the caller will be checked against all unknown applications,
709     *  which cause smaller number of SMS to be sent in checking period.
710     * @param deliveryIntent if not NULL this <code>PendingIntent</code> is
711     *  broadcast when the message is delivered to the recipient.  The
712     *  raw pdu of the status report is in the extended data ("pdu").
713     */
714    protected abstract void sendData(String destAddr, String scAddr, int destPort,
715            byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent);
716
717    /**
718     * Send a text based SMS.
719     *
720     * @param destAddr the address to send the message to
721     * @param scAddr is the service center address or null to use
722     *  the current default SMSC
723     * @param text the body of the message to send
724     * @param sentIntent if not NULL this <code>PendingIntent</code> is
725     *  broadcast when the message is successfully sent, or failed.
726     *  The result code will be <code>Activity.RESULT_OK<code> for success,
727     *  or one of these errors:<br>
728     *  <code>RESULT_ERROR_GENERIC_FAILURE</code><br>
729     *  <code>RESULT_ERROR_RADIO_OFF</code><br>
730     *  <code>RESULT_ERROR_NULL_PDU</code><br>
731     *  For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include
732     *  the extra "errorCode" containing a radio technology specific value,
733     *  generally only useful for troubleshooting.<br>
734     *  The per-application based SMS control checks sentIntent. If sentIntent
735     *  is NULL the caller will be checked against all unknown applications,
736     *  which cause smaller number of SMS to be sent in checking period.
737     * @param deliveryIntent if not NULL this <code>PendingIntent</code> is
738     *  broadcast when the message is delivered to the recipient.  The
739     *  raw pdu of the status report is in the extended data ("pdu").
740     */
741    protected abstract void sendText(String destAddr, String scAddr,
742            String text, PendingIntent sentIntent, PendingIntent deliveryIntent);
743
744    /**
745     * Send a multi-part text based SMS.
746     *
747     * @param destAddr the address to send the message to
748     * @param scAddr is the service center address or null to use
749     *   the current default SMSC
750     * @param parts an <code>ArrayList</code> of strings that, in order,
751     *   comprise the original message
752     * @param sentIntents if not null, an <code>ArrayList</code> of
753     *   <code>PendingIntent</code>s (one for each message part) that is
754     *   broadcast when the corresponding message part has been sent.
755     *   The result code will be <code>Activity.RESULT_OK<code> for success,
756     *   or one of these errors:
757     *   <code>RESULT_ERROR_GENERIC_FAILURE</code>
758     *   <code>RESULT_ERROR_RADIO_OFF</code>
759     *   <code>RESULT_ERROR_NULL_PDU</code>.
760     *  The per-application based SMS control checks sentIntent. If sentIntent
761     *  is NULL the caller will be checked against all unknown applications,
762     *  which cause smaller number of SMS to be sent in checking period.
763     * @param deliveryIntents if not null, an <code>ArrayList</code> of
764     *   <code>PendingIntent</code>s (one for each message part) that is
765     *   broadcast when the corresponding message part has been delivered
766     *   to the recipient.  The raw pdu of the status report is in the
767     *   extended data ("pdu").
768     */
769    protected abstract void sendMultipartText(String destAddr, String scAddr,
770            ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,
771            ArrayList<PendingIntent> deliveryIntents);
772
773    /**
774     * Send a SMS
775     *
776     * @param smsc the SMSC to send the message through, or NULL for the
777     *  default SMSC
778     * @param pdu the raw PDU to send
779     * @param sentIntent if not NULL this <code>Intent</code> is
780     *  broadcast when the message is successfully sent, or failed.
781     *  The result code will be <code>Activity.RESULT_OK<code> for success,
782     *  or one of these errors:
783     *  <code>RESULT_ERROR_GENERIC_FAILURE</code>
784     *  <code>RESULT_ERROR_RADIO_OFF</code>
785     *  <code>RESULT_ERROR_NULL_PDU</code>.
786     *  The per-application based SMS control checks sentIntent. If sentIntent
787     *  is NULL the caller will be checked against all unknown applications,
788     *  which cause smaller number of SMS to be sent in checking period.
789     * @param deliveryIntent if not NULL this <code>Intent</code> is
790     *  broadcast when the message is delivered to the recipient.  The
791     *  raw pdu of the status report is in the extended data ("pdu").
792     */
793    protected void sendRawPdu(byte[] smsc, byte[] pdu, PendingIntent sentIntent,
794            PendingIntent deliveryIntent) {
795        if (pdu == null) {
796            if (sentIntent != null) {
797                try {
798                    sentIntent.send(RESULT_ERROR_NULL_PDU);
799                } catch (CanceledException ex) {}
800            }
801            return;
802        }
803
804        HashMap<String, Object> map = new HashMap<String, Object>();
805        map.put("smsc", smsc);
806        map.put("pdu", pdu);
807
808        SmsTracker tracker = new SmsTracker(map, sentIntent,
809                deliveryIntent);
810        int ss = mPhone.getServiceState().getState();
811
812        if (ss != ServiceState.STATE_IN_SERVICE) {
813            handleNotInService(ss, tracker);
814        } else {
815            String appName = getAppNameByIntent(sentIntent);
816            if (mCounter.check(appName, SINGLE_PART_SMS)) {
817                sendSms(tracker);
818            } else {
819                sendMessage(obtainMessage(EVENT_POST_ALERT, tracker));
820            }
821        }
822    }
823
824    /**
825     * Post an alert while SMS needs user confirm.
826     *
827     * An SmsTracker for the current message.
828     */
829    protected void handleReachSentLimit(SmsTracker tracker) {
830        if (mSTrackers.size() >= MO_MSG_QUEUE_LIMIT) {
831            // Deny the sending when the queue limit is reached.
832            try {
833                tracker.mSentIntent.send(RESULT_ERROR_LIMIT_EXCEEDED);
834            } catch (CanceledException ex) {
835                Log.e(TAG, "failed to send back RESULT_ERROR_LIMIT_EXCEEDED");
836            }
837            return;
838        }
839
840        Resources r = Resources.getSystem();
841
842        String appName = getAppNameByIntent(tracker.mSentIntent);
843
844        AlertDialog d = new AlertDialog.Builder(mContext)
845                .setTitle(r.getString(R.string.sms_control_title))
846                .setMessage(appName + " " + r.getString(R.string.sms_control_message))
847                .setPositiveButton(r.getString(R.string.sms_control_yes), mListener)
848                .setNegativeButton(r.getString(R.string.sms_control_no), mListener)
849                .create();
850
851        d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
852        d.show();
853
854        mSTrackers.add(tracker);
855        sendMessageDelayed ( obtainMessage(EVENT_ALERT_TIMEOUT, d),
856                DEFAULT_SMS_TIMEOUT);
857    }
858
859    protected String getAppNameByIntent(PendingIntent intent) {
860        Resources r = Resources.getSystem();
861        return (intent != null) ? intent.getTargetPackage()
862            : r.getString(R.string.sms_control_default_app_name);
863    }
864
865    /**
866     * Send the message along to the radio.
867     *
868     * @param tracker holds the SMS message to send
869     */
870    protected abstract void sendSms(SmsTracker tracker);
871
872    /**
873     * Send the multi-part SMS based on multipart Sms tracker
874     *
875     * @param tracker holds the multipart Sms tracker ready to be sent
876     */
877    protected abstract void sendMultipartSms (SmsTracker tracker);
878
879    /**
880     * Activate or deactivate cell broadcast SMS.
881     *
882     * @param activate
883     *            0 = activate, 1 = deactivate
884     * @param response
885     *            Callback message is empty on completion
886     */
887    protected abstract void activateCellBroadcastSms(int activate, Message response);
888
889    /**
890     * Query the current configuration of cell broadcast SMS.
891     *
892     * @param response
893     *            Callback message contains the configuration from the modem on completion
894     *            @see #setCellBroadcastConfig
895     */
896    protected abstract void getCellBroadcastSmsConfig(Message response);
897
898    /**
899     * Configure cell broadcast SMS.
900     *
901     * @param configValuesArray
902     *          The first element defines the number of triples that follow.
903     *          A triple is made up of the service category, the language identifier
904     *          and a boolean that specifies whether the category is set active.
905     * @param response
906     *            Callback message is empty on completion
907     */
908    protected abstract void setCellBroadcastConfig(int[] configValuesArray, Message response);
909
910    /**
911     * Send an acknowledge message.
912     * @param success indicates that last message was successfully received.
913     * @param result result code indicating any error
914     * @param response callback message sent when operation completes.
915     */
916    protected abstract void acknowledgeLastIncomingSms(boolean success,
917            int result, Message response);
918
919    /**
920     * Notify interested apps if the framework has rejected an incoming SMS,
921     * and send an acknowledge message to the network.
922     * @param success indicates that last message was successfully received.
923     * @param result result code indicating any error
924     * @param response callback message sent when operation completes.
925     */
926    private void notifyAndAcknowledgeLastIncomingSms(boolean success,
927            int result, Message response) {
928        if (!success) {
929            // broadcast SMS_REJECTED_ACTION intent
930            Intent intent = new Intent(Intents.SMS_REJECTED_ACTION);
931            intent.putExtra("result", result);
932            mWakeLock.acquire(WAKE_LOCK_TIMEOUT);
933            mContext.sendBroadcast(intent, "android.permission.RECEIVE_SMS");
934        }
935        acknowledgeLastIncomingSms(success, result, response);
936    }
937
938    /**
939     * Check if a SmsTracker holds multi-part Sms
940     *
941     * @param tracker a SmsTracker could hold a multi-part Sms
942     * @return true for tracker holds Multi-parts Sms
943     */
944    private boolean isMultipartTracker (SmsTracker tracker) {
945        HashMap map = tracker.mData;
946        return ( map.get("parts") != null);
947    }
948
949    /**
950     * Keeps track of an SMS that has been sent to the RIL, until it has
951     * successfully been sent, or we're done trying.
952     *
953     */
954    static protected class SmsTracker {
955        // fields need to be public for derived SmsDispatchers
956        public HashMap mData;
957        public int mRetryCount;
958        public int mMessageRef;
959
960        public PendingIntent mSentIntent;
961        public PendingIntent mDeliveryIntent;
962
963        SmsTracker(HashMap data, PendingIntent sentIntent,
964                PendingIntent deliveryIntent) {
965            mData = data;
966            mSentIntent = sentIntent;
967            mDeliveryIntent = deliveryIntent;
968            mRetryCount = 0;
969        }
970    }
971
972    protected SmsTracker SmsTrackerFactory(HashMap data, PendingIntent sentIntent,
973            PendingIntent deliveryIntent) {
974        return new SmsTracker(data, sentIntent, deliveryIntent);
975    }
976
977    private DialogInterface.OnClickListener mListener =
978        new DialogInterface.OnClickListener() {
979
980            public void onClick(DialogInterface dialog, int which) {
981                if (which == DialogInterface.BUTTON_POSITIVE) {
982                    Log.d(TAG, "click YES to send out sms");
983                    sendMessage(obtainMessage(EVENT_SEND_CONFIRMED_SMS));
984                } else if (which == DialogInterface.BUTTON_NEGATIVE) {
985                    Log.d(TAG, "click NO to stop sending");
986                    sendMessage(obtainMessage(EVENT_STOP_SENDING));
987                }
988            }
989        };
990
991    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
992        @Override
993        public void onReceive(Context context, Intent intent) {
994            if (intent.getAction().equals(Intent.ACTION_DEVICE_STORAGE_FULL)) {
995                mStorageAvailable = false;
996                mCm.reportSmsMemoryStatus(false, obtainMessage(EVENT_REPORT_MEMORY_STATUS_DONE));
997            } else if (intent.getAction().equals(Intent.ACTION_DEVICE_STORAGE_NOT_FULL)) {
998                mStorageAvailable = true;
999                mCm.reportSmsMemoryStatus(true, obtainMessage(EVENT_REPORT_MEMORY_STATUS_DONE));
1000            } else {
1001                // Assume the intent is one of the SMS receive intents that
1002                // was sent as an ordered broadcast.  Check result and ACK.
1003                int rc = getResultCode();
1004                boolean success = (rc == Activity.RESULT_OK)
1005                        || (rc == Intents.RESULT_SMS_HANDLED);
1006
1007                // For a multi-part message, this only ACKs the last part.
1008                // Previous parts were ACK'd as they were received.
1009                acknowledgeLastIncomingSms(success, rc, null);
1010            }
1011        }
1012    };
1013
1014    protected abstract void handleBroadcastSms(AsyncResult ar);
1015
1016    protected void dispatchBroadcastPdus(byte[][] pdus) {
1017        Intent intent = new Intent("android.provider.telephony.SMS_CB_RECEIVED");
1018        intent.putExtra("pdus", pdus);
1019
1020        if (Config.LOGD)
1021            Log.d(TAG, "Dispatching " + pdus.length + " SMS CB pdus");
1022
1023        dispatch(intent, "android.permission.RECEIVE_SMS");
1024    }
1025
1026}
1027