SMSDispatcher.java revision fce79caf5d7628cde43c5f0cd3d369673bc15212
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.AlertDialog; 21import android.app.PendingIntent; 22import android.app.PendingIntent.CanceledException; 23import android.content.BroadcastReceiver; 24import android.content.ContentResolver; 25import android.content.ContentValues; 26import android.content.Context; 27import android.content.DialogInterface; 28import android.content.Intent; 29import android.content.pm.ApplicationInfo; 30import android.content.pm.PackageInfo; 31import android.content.pm.PackageManager; 32import android.content.res.Resources; 33import android.database.ContentObserver; 34import android.database.sqlite.SqliteWrapper; 35import android.net.Uri; 36import android.os.AsyncResult; 37import android.os.Binder; 38import android.os.Bundle; 39import android.os.Handler; 40import android.os.Message; 41import android.os.SystemProperties; 42import android.provider.Settings; 43import android.provider.Telephony; 44import android.provider.Telephony.Sms; 45import android.provider.Telephony.Sms.Intents; 46import android.telephony.PhoneNumberUtils; 47import android.telephony.Rlog; 48import android.telephony.ServiceState; 49import android.telephony.SubscriptionManager; 50import android.telephony.TelephonyManager; 51import android.text.Html; 52import android.text.Spanned; 53import android.util.EventLog; 54import android.view.LayoutInflater; 55import android.view.View; 56import android.view.ViewGroup; 57import android.view.WindowManager; 58import android.widget.Button; 59import android.widget.CheckBox; 60import android.widget.CompoundButton; 61import android.widget.TextView; 62 63import com.android.internal.R; 64import com.android.internal.telephony.GsmAlphabet.TextEncodingDetails; 65 66import java.util.ArrayList; 67import java.util.Collections; 68import java.util.HashMap; 69import java.util.List; 70import java.util.Random; 71import java.util.concurrent.atomic.AtomicBoolean; 72import java.util.concurrent.atomic.AtomicInteger; 73 74import static android.telephony.SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE; 75import static android.telephony.SmsManager.RESULT_ERROR_GENERIC_FAILURE; 76import static android.telephony.SmsManager.RESULT_ERROR_LIMIT_EXCEEDED; 77import static android.telephony.SmsManager.RESULT_ERROR_NO_SERVICE; 78import static android.telephony.SmsManager.RESULT_ERROR_NULL_PDU; 79import static android.telephony.SmsManager.RESULT_ERROR_RADIO_OFF; 80 81public abstract class SMSDispatcher extends Handler { 82 static final String TAG = "SMSDispatcher"; // accessed from inner class 83 static final boolean DBG = false; 84 private static final String SEND_NEXT_MSG_EXTRA = "SendNextMsg"; 85 86 /** Permission required to send SMS to short codes without user confirmation. */ 87 private static final String SEND_SMS_NO_CONFIRMATION_PERMISSION = 88 "android.permission.SEND_SMS_NO_CONFIRMATION"; 89 90 private static final int PREMIUM_RULE_USE_SIM = 1; 91 private static final int PREMIUM_RULE_USE_NETWORK = 2; 92 private static final int PREMIUM_RULE_USE_BOTH = 3; 93 private final AtomicInteger mPremiumSmsRule = new AtomicInteger(PREMIUM_RULE_USE_SIM); 94 private final SettingsObserver mSettingsObserver; 95 96 /** SMS send complete. */ 97 protected static final int EVENT_SEND_SMS_COMPLETE = 2; 98 99 /** Retry sending a previously failed SMS message */ 100 private static final int EVENT_SEND_RETRY = 3; 101 102 /** Confirmation required for sending a large number of messages. */ 103 private static final int EVENT_SEND_LIMIT_REACHED_CONFIRMATION = 4; 104 105 /** Send the user confirmed SMS */ 106 static final int EVENT_SEND_CONFIRMED_SMS = 5; // accessed from inner class 107 108 /** Don't send SMS (user did not confirm). */ 109 static final int EVENT_STOP_SENDING = 7; // accessed from inner class 110 111 /** Confirmation required for third-party apps sending to an SMS short code. */ 112 private static final int EVENT_CONFIRM_SEND_TO_POSSIBLE_PREMIUM_SHORT_CODE = 8; 113 114 /** Confirmation required for third-party apps sending to an SMS short code. */ 115 private static final int EVENT_CONFIRM_SEND_TO_PREMIUM_SHORT_CODE = 9; 116 117 /** Handle status report from {@code CdmaInboundSmsHandler}. */ 118 protected static final int EVENT_HANDLE_STATUS_REPORT = 10; 119 120 /** Radio is ON */ 121 protected static final int EVENT_RADIO_ON = 11; 122 123 /** IMS registration/SMS format changed */ 124 protected static final int EVENT_IMS_STATE_CHANGED = 12; 125 126 /** Callback from RIL_REQUEST_IMS_REGISTRATION_STATE */ 127 protected static final int EVENT_IMS_STATE_DONE = 13; 128 129 // other 130 protected static final int EVENT_NEW_ICC_SMS = 14; 131 protected static final int EVENT_ICC_CHANGED = 15; 132 133 protected PhoneBase mPhone; 134 protected final Context mContext; 135 protected final ContentResolver mResolver; 136 protected final CommandsInterface mCi; 137 protected final TelephonyManager mTelephonyManager; 138 139 /** Maximum number of times to retry sending a failed SMS. */ 140 private static final int MAX_SEND_RETRIES = 3; 141 /** Delay before next send attempt on a failed SMS, in milliseconds. */ 142 private static final int SEND_RETRY_DELAY = 2000; 143 /** single part SMS */ 144 private static final int SINGLE_PART_SMS = 1; 145 /** Message sending queue limit */ 146 private static final int MO_MSG_QUEUE_LIMIT = 5; 147 148 /** 149 * Message reference for a CONCATENATED_8_BIT_REFERENCE or 150 * CONCATENATED_16_BIT_REFERENCE message set. Should be 151 * incremented for each set of concatenated messages. 152 * Static field shared by all dispatcher objects. 153 */ 154 private static int sConcatenatedRef = new Random().nextInt(256); 155 156 /** Outgoing message counter. Shared by all dispatchers. */ 157 private SmsUsageMonitor mUsageMonitor; 158 159 private ImsSMSDispatcher mImsSMSDispatcher; 160 161 /** Number of outgoing SmsTrackers waiting for user confirmation. */ 162 private int mPendingTrackerCount; 163 164 /* Flags indicating whether the current device allows sms service */ 165 protected boolean mSmsCapable = true; 166 protected boolean mSmsSendDisabled; 167 168 protected static int getNextConcatenatedRef() { 169 sConcatenatedRef += 1; 170 return sConcatenatedRef; 171 } 172 173 /** 174 * Create a new SMS dispatcher. 175 * @param phone the Phone to use 176 * @param usageMonitor the SmsUsageMonitor to use 177 */ 178 protected SMSDispatcher(PhoneBase phone, SmsUsageMonitor usageMonitor, 179 ImsSMSDispatcher imsSMSDispatcher) { 180 mPhone = phone; 181 mImsSMSDispatcher = imsSMSDispatcher; 182 mContext = phone.getContext(); 183 mResolver = mContext.getContentResolver(); 184 mCi = phone.mCi; 185 mUsageMonitor = usageMonitor; 186 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 187 mSettingsObserver = new SettingsObserver(this, mPremiumSmsRule, mContext); 188 mContext.getContentResolver().registerContentObserver(Settings.Global.getUriFor( 189 Settings.Global.SMS_SHORT_CODE_RULE), false, mSettingsObserver); 190 191 mSmsCapable = mContext.getResources().getBoolean( 192 com.android.internal.R.bool.config_sms_capable); 193 mSmsSendDisabled = !SystemProperties.getBoolean( 194 TelephonyProperties.PROPERTY_SMS_SEND, mSmsCapable); 195 Rlog.d(TAG, "SMSDispatcher: ctor mSmsCapable=" + mSmsCapable + " format=" + getFormat() 196 + " mSmsSendDisabled=" + mSmsSendDisabled); 197 } 198 199 /** 200 * Observe the secure setting for updated premium sms determination rules 201 */ 202 private static class SettingsObserver extends ContentObserver { 203 private final AtomicInteger mPremiumSmsRule; 204 private final Context mContext; 205 SettingsObserver(Handler handler, AtomicInteger premiumSmsRule, Context context) { 206 super(handler); 207 mPremiumSmsRule = premiumSmsRule; 208 mContext = context; 209 onChange(false); // load initial value; 210 } 211 212 @Override 213 public void onChange(boolean selfChange) { 214 mPremiumSmsRule.set(Settings.Global.getInt(mContext.getContentResolver(), 215 Settings.Global.SMS_SHORT_CODE_RULE, PREMIUM_RULE_USE_SIM)); 216 } 217 } 218 219 protected void updatePhoneObject(PhoneBase phone) { 220 mPhone = phone; 221 mUsageMonitor = phone.mSmsUsageMonitor; 222 Rlog.d(TAG, "Active phone changed to " + mPhone.getPhoneName() ); 223 } 224 225 /** Unregister for incoming SMS events. */ 226 public void dispose() { 227 mContext.getContentResolver().unregisterContentObserver(mSettingsObserver); 228 } 229 230 /** 231 * The format of the message PDU in the associated broadcast intent. 232 * This will be either "3gpp" for GSM/UMTS/LTE messages in 3GPP format 233 * or "3gpp2" for CDMA/LTE messages in 3GPP2 format. 234 * 235 * Note: All applications which handle incoming SMS messages by processing the 236 * SMS_RECEIVED_ACTION broadcast intent MUST pass the "format" extra from the intent 237 * into the new methods in {@link android.telephony.SmsMessage} which take an 238 * extra format parameter. This is required in order to correctly decode the PDU on 239 * devices which require support for both 3GPP and 3GPP2 formats at the same time, 240 * such as CDMA/LTE devices and GSM/CDMA world phones. 241 * 242 * @return the format of the message PDU 243 */ 244 protected abstract String getFormat(); 245 246 /** 247 * Pass the Message object to subclass to handle. Currently used to pass CDMA status reports 248 * from {@link com.android.internal.telephony.cdma.CdmaInboundSmsHandler}. 249 * @param o the SmsMessage containing the status report 250 */ 251 protected void handleStatusReport(Object o) { 252 Rlog.d(TAG, "handleStatusReport() called with no subclass."); 253 } 254 255 /* TODO: Need to figure out how to keep track of status report routing in a 256 * persistent manner. If the phone process restarts (reboot or crash), 257 * we will lose this list and any status reports that come in after 258 * will be dropped. 259 */ 260 /** Sent messages awaiting a delivery status report. */ 261 protected final ArrayList<SmsTracker> deliveryPendingList = new ArrayList<SmsTracker>(); 262 263 /** Outgoing messages being handled by the carrier app. */ 264 protected final List<SmsTracker> sendPendingList = 265 Collections.synchronizedList(new ArrayList<SmsTracker>()); 266 267 /** 268 * Handles events coming from the phone stack. Overridden from handler. 269 * 270 * @param msg the message to handle 271 */ 272 @Override 273 public void handleMessage(Message msg) { 274 switch (msg.what) { 275 case EVENT_SEND_SMS_COMPLETE: 276 // An outbound SMS has been successfully transferred, or failed. 277 handleSendComplete((AsyncResult) msg.obj); 278 break; 279 280 case EVENT_SEND_RETRY: 281 Rlog.d(TAG, "SMS retry.."); 282 sendRetrySms((SmsTracker) msg.obj); 283 break; 284 285 case EVENT_SEND_LIMIT_REACHED_CONFIRMATION: 286 handleReachSentLimit((SmsTracker)(msg.obj)); 287 break; 288 289 case EVENT_CONFIRM_SEND_TO_POSSIBLE_PREMIUM_SHORT_CODE: 290 handleConfirmShortCode(false, (SmsTracker)(msg.obj)); 291 break; 292 293 case EVENT_CONFIRM_SEND_TO_PREMIUM_SHORT_CODE: 294 handleConfirmShortCode(true, (SmsTracker)(msg.obj)); 295 break; 296 297 case EVENT_SEND_CONFIRMED_SMS: 298 { 299 SmsTracker tracker = (SmsTracker) msg.obj; 300 if (tracker.isMultipart()) { 301 sendMultipartSms(tracker); 302 } else { 303 sendSms(tracker); 304 } 305 mPendingTrackerCount--; 306 break; 307 } 308 309 case EVENT_STOP_SENDING: 310 { 311 SmsTracker tracker = (SmsTracker) msg.obj; 312 tracker.onFailed(mContext, RESULT_ERROR_LIMIT_EXCEEDED, 0/*errorCode*/); 313 mPendingTrackerCount--; 314 break; 315 } 316 317 case EVENT_HANDLE_STATUS_REPORT: 318 handleStatusReport(msg.obj); 319 break; 320 321 default: 322 Rlog.e(TAG, "handleMessage() ignoring message of unexpected type " + msg.what); 323 } 324 } 325 326 /** 327 * Called when SMS send completes. Broadcasts a sentIntent on success. 328 * On failure, either sets up retries or broadcasts a sentIntent with 329 * the failure in the result code. 330 * 331 * @param ar AsyncResult passed into the message handler. ar.result should 332 * an SmsResponse instance if send was successful. ar.userObj 333 * should be an SmsTracker instance. 334 */ 335 protected void handleSendComplete(AsyncResult ar) { 336 SmsTracker tracker = (SmsTracker) ar.userObj; 337 PendingIntent sentIntent = tracker.mSentIntent; 338 339 if (ar.result != null) { 340 tracker.mMessageRef = ((SmsResponse)ar.result).mMessageRef; 341 } else { 342 Rlog.d(TAG, "SmsResponse was null"); 343 } 344 345 if (ar.exception == null) { 346 if (DBG) Rlog.d(TAG, "SMS send complete. Broadcasting intent: " + sentIntent); 347 348 if (!SystemProperties.getBoolean("telephony.sms.autopersist", false)) { 349 // TODO(ywen): Temporarily only disable this with a system property 350 // so not to break existing apps 351 if (SmsApplication.shouldWriteMessageForPackage( 352 tracker.mAppInfo.applicationInfo.packageName, mContext)) { 353 // Persist it into the SMS database as a sent message 354 // so the user can see it in their default app. 355 tracker.writeSentMessage(mContext); 356 } 357 } 358 if (tracker.mDeliveryIntent != null) { 359 // Expecting a status report. Add it to the list. 360 deliveryPendingList.add(tracker); 361 } 362 tracker.onSent(mContext); 363 } else { 364 if (DBG) Rlog.d(TAG, "SMS send failed"); 365 366 int ss = mPhone.getServiceState().getState(); 367 368 if ( tracker.mImsRetry > 0 && ss != ServiceState.STATE_IN_SERVICE) { 369 // This is retry after failure over IMS but voice is not available. 370 // Set retry to max allowed, so no retry is sent and 371 // cause RESULT_ERROR_GENERIC_FAILURE to be returned to app. 372 tracker.mRetryCount = MAX_SEND_RETRIES; 373 374 Rlog.d(TAG, "handleSendComplete: Skipping retry: " 375 +" isIms()="+isIms() 376 +" mRetryCount="+tracker.mRetryCount 377 +" mImsRetry="+tracker.mImsRetry 378 +" mMessageRef="+tracker.mMessageRef 379 +" SS= "+mPhone.getServiceState().getState()); 380 } 381 382 // if sms over IMS is not supported on data and voice is not available... 383 if (!isIms() && ss != ServiceState.STATE_IN_SERVICE) { 384 tracker.onFailed(mContext, getNotInServiceError(ss), 0/*errorCode*/); 385 } else if ((((CommandException)(ar.exception)).getCommandError() 386 == CommandException.Error.SMS_FAIL_RETRY) && 387 tracker.mRetryCount < MAX_SEND_RETRIES) { 388 // Retry after a delay if needed. 389 // TODO: According to TS 23.040, 9.2.3.6, we should resend 390 // with the same TP-MR as the failed message, and 391 // TP-RD set to 1. However, we don't have a means of 392 // knowing the MR for the failed message (EF_SMSstatus 393 // may or may not have the MR corresponding to this 394 // message, depending on the failure). Also, in some 395 // implementations this retry is handled by the baseband. 396 tracker.mRetryCount++; 397 Message retryMsg = obtainMessage(EVENT_SEND_RETRY, tracker); 398 sendMessageDelayed(retryMsg, SEND_RETRY_DELAY); 399 } else { 400 int errorCode = 0; 401 if (ar.result != null) { 402 errorCode = ((SmsResponse)ar.result).mErrorCode; 403 } 404 int error = RESULT_ERROR_GENERIC_FAILURE; 405 if (((CommandException)(ar.exception)).getCommandError() 406 == CommandException.Error.FDN_CHECK_FAILURE) { 407 error = RESULT_ERROR_FDN_CHECK_FAILURE; 408 } 409 tracker.onFailed(mContext, error, errorCode); 410 } 411 } 412 } 413 414 /** 415 * Handles outbound message when the phone is not in service. 416 * 417 * @param ss Current service state. Valid values are: 418 * OUT_OF_SERVICE 419 * EMERGENCY_ONLY 420 * POWER_OFF 421 * @param sentIntent the PendingIntent to send the error to 422 */ 423 protected static void handleNotInService(int ss, PendingIntent sentIntent) { 424 if (sentIntent != null) { 425 try { 426 if (ss == ServiceState.STATE_POWER_OFF) { 427 sentIntent.send(RESULT_ERROR_RADIO_OFF); 428 } else { 429 sentIntent.send(RESULT_ERROR_NO_SERVICE); 430 } 431 } catch (CanceledException ex) {} 432 } 433 } 434 435 /** 436 * @param ss service state 437 * @return The result error based on input service state for not in service error 438 */ 439 protected static int getNotInServiceError(int ss) { 440 if (ss == ServiceState.STATE_POWER_OFF) { 441 return RESULT_ERROR_RADIO_OFF; 442 } 443 return RESULT_ERROR_NO_SERVICE; 444 } 445 446 /** 447 * Send a data based SMS to a specific application port. 448 * 449 * @param destAddr the address to send the message to 450 * @param scAddr is the service center address or null to use 451 * the current default SMSC 452 * @param destPort the port to deliver the message to 453 * @param data the body of the message to send 454 * @param sentIntent if not NULL this <code>PendingIntent</code> is 455 * broadcast when the message is successfully sent, or failed. 456 * The result code will be <code>Activity.RESULT_OK<code> for success, 457 * or one of these errors:<br> 458 * <code>RESULT_ERROR_GENERIC_FAILURE</code><br> 459 * <code>RESULT_ERROR_RADIO_OFF</code><br> 460 * <code>RESULT_ERROR_NULL_PDU</code><br> 461 * <code>RESULT_ERROR_NO_SERVICE</code><br>. 462 * For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include 463 * the extra "errorCode" containing a radio technology specific value, 464 * generally only useful for troubleshooting.<br> 465 * The per-application based SMS control checks sentIntent. If sentIntent 466 * is NULL the caller will be checked against all unknown applications, 467 * which cause smaller number of SMS to be sent in checking period. 468 * @param deliveryIntent if not NULL this <code>PendingIntent</code> is 469 * broadcast when the message is delivered to the recipient. The 470 * raw pdu of the status report is in the extended data ("pdu"). 471 */ 472 protected abstract void sendData(String destAddr, String scAddr, int destPort, 473 byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent); 474 475 /** 476 * Send a text based SMS. 477 * 478 * @param destAddr the address to send the message to 479 * @param scAddr is the service center address or null to use 480 * the current default SMSC 481 * @param text the body of the message to send 482 * @param sentIntent if not NULL this <code>PendingIntent</code> is 483 * broadcast when the message is successfully sent, or failed. 484 * The result code will be <code>Activity.RESULT_OK<code> for success, 485 * or one of these errors:<br> 486 * <code>RESULT_ERROR_GENERIC_FAILURE</code><br> 487 * <code>RESULT_ERROR_RADIO_OFF</code><br> 488 * <code>RESULT_ERROR_NULL_PDU</code><br> 489 * <code>RESULT_ERROR_NO_SERVICE</code><br>. 490 * For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include 491 * the extra "errorCode" containing a radio technology specific value, 492 * generally only useful for troubleshooting.<br> 493 * The per-application based SMS control checks sentIntent. If sentIntent 494 * is NULL the caller will be checked against all unknown applications, 495 * which cause smaller number of SMS to be sent in checking period. 496 * @param deliveryIntent if not NULL this <code>PendingIntent</code> is 497 * broadcast when the message is delivered to the recipient. The 498 * raw pdu of the status report is in the extended data ("pdu"). 499 */ 500 protected abstract void sendText(String destAddr, String scAddr, 501 String text, PendingIntent sentIntent, PendingIntent deliveryIntent); 502 503 /** 504 * Inject an SMS PDU into the android platform. 505 * 506 * @param pdu is the byte array of pdu to be injected into android telephony layer 507 * @param format is the format of SMS pdu (3gpp or 3gpp2) 508 * @param receivedIntent if not NULL this <code>PendingIntent</code> is 509 * broadcast when the message is successfully received by the 510 * android telephony layer. This intent is broadcasted at 511 * the same time an SMS received from radio is responded back. 512 */ 513 protected abstract void injectSmsPdu(byte[] pdu, String format, PendingIntent receivedIntent); 514 515 /** 516 * Calculate the number of septets needed to encode the message. 517 * 518 * @param messageBody the message to encode 519 * @param use7bitOnly ignore (but still count) illegal characters if true 520 * @return TextEncodingDetails 521 */ 522 protected abstract TextEncodingDetails calculateLength(CharSequence messageBody, 523 boolean use7bitOnly); 524 525 /** 526 * Update the status of a pending (send-by-IP) SMS message and resend by PSTN if necessary. 527 * This outbound message was handled by the carrier app. If the carrier app fails to send 528 * this message, it would be resent by PSTN. 529 * 530 * @param messageRef the reference number of the SMS message. 531 * @param success True if and only if the message was sent successfully. If its value is 532 * false, this message should be resent via PSTN. 533 */ 534 protected abstract void updateSmsSendStatus(int messageRef, boolean success); 535 536 /** 537 * Handler for a {@link GsmSMSDispatcher} or {@link CdmaSMSDispatcher} broadcast. 538 * If SMS sending is successfuly, sends EVENT_SEND_SMS_COMPLETE message. Otherwise, 539 * send the message via the GSM/CDMA network. 540 */ 541 protected final class SMSDispatcherReceiver extends BroadcastReceiver { 542 543 private final SmsTracker mTracker; 544 545 public SMSDispatcherReceiver(SmsTracker tracker) { 546 mTracker = tracker; 547 } 548 549 @Override 550 public void onReceive(Context context, Intent intent) { 551 String action = intent.getAction(); 552 if (action.equals(Intents.SMS_SEND_ACTION)) { 553 int rc = getResultCode(); 554 if (rc == Activity.RESULT_OK) { 555 Rlog.d(TAG, "Sending SMS by IP pending."); 556 Bundle resultExtras = getResultExtras(false); 557 if (resultExtras != null && resultExtras.containsKey("messageref")) { 558 mTracker.mMessageRef = resultExtras.getInt("messageref"); 559 Rlog.d(TAG, "messageref = " + mTracker.mMessageRef); 560 } else { 561 Rlog.e(TAG, "Can't find messageref in result extras."); 562 } 563 sendPendingList.add(mTracker); 564 } else { 565 Rlog.d(TAG, "Sending SMS by IP failed."); 566 sendSmsByPstn(mTracker); 567 } 568 } else { 569 Rlog.e(TAG, "unexpected BroadcastReceiver action: " + action); 570 } 571 } 572 } 573 574 /** 575 * Send a multi-part text based SMS. 576 * 577 * @param destAddr the address to send the message to 578 * @param scAddr is the service center address or null to use 579 * the current default SMSC 580 * @param parts an <code>ArrayList</code> of strings that, in order, 581 * comprise the original message 582 * @param sentIntents if not null, an <code>ArrayList</code> of 583 * <code>PendingIntent</code>s (one for each message part) that is 584 * broadcast when the corresponding message part has been sent. 585 * The result code will be <code>Activity.RESULT_OK<code> for success, 586 * or one of these errors: 587 * <code>RESULT_ERROR_GENERIC_FAILURE</code> 588 * <code>RESULT_ERROR_RADIO_OFF</code> 589 * <code>RESULT_ERROR_NULL_PDU</code> 590 * <code>RESULT_ERROR_NO_SERVICE</code>. 591 * The per-application based SMS control checks sentIntent. If sentIntent 592 * is NULL the caller will be checked against all unknown applications, 593 * which cause smaller number of SMS to be sent in checking period. 594 * @param deliveryIntents if not null, an <code>ArrayList</code> of 595 * <code>PendingIntent</code>s (one for each message part) that is 596 * broadcast when the corresponding message part has been delivered 597 * to the recipient. The raw pdu of the status report is in the 598 * extended data ("pdu"). 599 */ 600 protected void sendMultipartText(String destAddr, String scAddr, 601 ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, 602 ArrayList<PendingIntent> deliveryIntents) { 603 Uri messageUri = writeOutboxMessage( 604 SubscriptionManager.getPreferredSmsSubId(), 605 destAddr, 606 getMultipartMessageText(parts), 607 deliveryIntents != null && deliveryIntents.size() > 0); 608 int refNumber = getNextConcatenatedRef() & 0x00FF; 609 int msgCount = parts.size(); 610 int encoding = SmsConstants.ENCODING_UNKNOWN; 611 612 TextEncodingDetails[] encodingForParts = new TextEncodingDetails[msgCount]; 613 for (int i = 0; i < msgCount; i++) { 614 TextEncodingDetails details = calculateLength(parts.get(i), false); 615 if (encoding != details.codeUnitSize 616 && (encoding == SmsConstants.ENCODING_UNKNOWN 617 || encoding == SmsConstants.ENCODING_7BIT)) { 618 encoding = details.codeUnitSize; 619 } 620 encodingForParts[i] = details; 621 } 622 623 // States to track at the message level (for all parts) 624 final AtomicInteger unsentPartCount = new AtomicInteger(msgCount); 625 final AtomicBoolean anyPartFailed = new AtomicBoolean(false); 626 627 for (int i = 0; i < msgCount; i++) { 628 SmsHeader.ConcatRef concatRef = new SmsHeader.ConcatRef(); 629 concatRef.refNumber = refNumber; 630 concatRef.seqNumber = i + 1; // 1-based sequence 631 concatRef.msgCount = msgCount; 632 // TODO: We currently set this to true since our messaging app will never 633 // send more than 255 parts (it converts the message to MMS well before that). 634 // However, we should support 3rd party messaging apps that might need 16-bit 635 // references 636 // Note: It's not sufficient to just flip this bit to true; it will have 637 // ripple effects (several calculations assume 8-bit ref). 638 concatRef.isEightBits = true; 639 SmsHeader smsHeader = new SmsHeader(); 640 smsHeader.concatRef = concatRef; 641 642 // Set the national language tables for 3GPP 7-bit encoding, if enabled. 643 if (encoding == SmsConstants.ENCODING_7BIT) { 644 smsHeader.languageTable = encodingForParts[i].languageTable; 645 smsHeader.languageShiftTable = encodingForParts[i].languageShiftTable; 646 } 647 648 PendingIntent sentIntent = null; 649 if (sentIntents != null && sentIntents.size() > i) { 650 sentIntent = sentIntents.get(i); 651 } 652 653 PendingIntent deliveryIntent = null; 654 if (deliveryIntents != null && deliveryIntents.size() > i) { 655 deliveryIntent = deliveryIntents.get(i); 656 } 657 658 sendNewSubmitPdu(destAddr, scAddr, parts.get(i), smsHeader, encoding, 659 sentIntent, deliveryIntent, (i == (msgCount - 1)), 660 unsentPartCount, anyPartFailed, messageUri); 661 } 662 } 663 664 /** 665 * Create a new SubmitPdu and send it. 666 */ 667 protected abstract void sendNewSubmitPdu(String destinationAddress, String scAddress, 668 String message, SmsHeader smsHeader, int encoding, 669 PendingIntent sentIntent, PendingIntent deliveryIntent, boolean lastPart, 670 AtomicInteger unsentPartCount, AtomicBoolean anyPartFailed, Uri messageUri); 671 672 /** 673 * Send a SMS 674 * @param tracker will contain: 675 * -smsc the SMSC to send the message through, or NULL for the 676 * default SMSC 677 * -pdu the raw PDU to send 678 * -sentIntent if not NULL this <code>Intent</code> is 679 * broadcast when the message is successfully sent, or failed. 680 * The result code will be <code>Activity.RESULT_OK<code> for success, 681 * or one of these errors: 682 * <code>RESULT_ERROR_GENERIC_FAILURE</code> 683 * <code>RESULT_ERROR_RADIO_OFF</code> 684 * <code>RESULT_ERROR_NULL_PDU</code> 685 * <code>RESULT_ERROR_NO_SERVICE</code>. 686 * The per-application based SMS control checks sentIntent. If sentIntent 687 * is NULL the caller will be checked against all unknown applications, 688 * which cause smaller number of SMS to be sent in checking period. 689 * -deliveryIntent if not NULL this <code>Intent</code> is 690 * broadcast when the message is delivered to the recipient. The 691 * raw pdu of the status report is in the extended data ("pdu"). 692 * -param destAddr the destination phone number (for short code confirmation) 693 */ 694 protected void sendRawPdu(SmsTracker tracker) { 695 HashMap map = tracker.mData; 696 byte pdu[] = (byte[]) map.get("pdu"); 697 698 if (mSmsSendDisabled) { 699 Rlog.e(TAG, "Device does not support sending sms."); 700 tracker.onFailed(mContext, RESULT_ERROR_NO_SERVICE, 0/*errorCode*/); 701 return; 702 } 703 704 if (pdu == null) { 705 Rlog.e(TAG, "Empty PDU"); 706 tracker.onFailed(mContext, RESULT_ERROR_NULL_PDU, 0/*errorCode*/); 707 return; 708 } 709 710 // Get calling app package name via UID from Binder call 711 PackageManager pm = mContext.getPackageManager(); 712 String[] packageNames = pm.getPackagesForUid(Binder.getCallingUid()); 713 714 if (packageNames == null || packageNames.length == 0) { 715 // Refuse to send SMS if we can't get the calling package name. 716 Rlog.e(TAG, "Can't get calling app package name: refusing to send SMS"); 717 tracker.onFailed(mContext, RESULT_ERROR_GENERIC_FAILURE, 0/*errorCode*/); 718 return; 719 } 720 721 // Get package info via packagemanager 722 PackageInfo appInfo; 723 try { 724 // XXX this is lossy- apps can share a UID 725 appInfo = pm.getPackageInfo(packageNames[0], PackageManager.GET_SIGNATURES); 726 } catch (PackageManager.NameNotFoundException e) { 727 Rlog.e(TAG, "Can't get calling app package info: refusing to send SMS"); 728 tracker.onFailed(mContext, RESULT_ERROR_GENERIC_FAILURE, 0/*errorCode*/); 729 return; 730 } 731 732 // checkDestination() returns true if the destination is not a premium short code or the 733 // sending app is approved to send to short codes. Otherwise, a message is sent to our 734 // handler with the SmsTracker to request user confirmation before sending. 735 if (checkDestination(tracker)) { 736 // check for excessive outgoing SMS usage by this app 737 if (!mUsageMonitor.check(appInfo.packageName, SINGLE_PART_SMS)) { 738 sendMessage(obtainMessage(EVENT_SEND_LIMIT_REACHED_CONFIRMATION, tracker)); 739 return; 740 } 741 742 int ss = mPhone.getServiceState().getState(); 743 744 // if sms over IMS is not supported on data and voice is not available... 745 if (!isIms() && ss != ServiceState.STATE_IN_SERVICE) { 746 tracker.onFailed(mContext, getNotInServiceError(ss), 0/*errorCode*/); 747 } else { 748 sendSms(tracker); 749 } 750 } 751 } 752 753 /** 754 * Check if destination is a potential premium short code and sender is not pre-approved to 755 * send to short codes. 756 * 757 * @param tracker the tracker for the SMS to send 758 * @return true if the destination is approved; false if user confirmation event was sent 759 */ 760 boolean checkDestination(SmsTracker tracker) { 761 if (mContext.checkCallingOrSelfPermission(SEND_SMS_NO_CONFIRMATION_PERMISSION) 762 == PackageManager.PERMISSION_GRANTED) { 763 return true; // app is pre-approved to send to short codes 764 } else { 765 int rule = mPremiumSmsRule.get(); 766 int smsCategory = SmsUsageMonitor.CATEGORY_NOT_SHORT_CODE; 767 if (rule == PREMIUM_RULE_USE_SIM || rule == PREMIUM_RULE_USE_BOTH) { 768 String simCountryIso = mTelephonyManager.getSimCountryIso(); 769 if (simCountryIso == null || simCountryIso.length() != 2) { 770 Rlog.e(TAG, "Can't get SIM country Iso: trying network country Iso"); 771 simCountryIso = mTelephonyManager.getNetworkCountryIso(); 772 } 773 774 smsCategory = mUsageMonitor.checkDestination(tracker.mDestAddress, simCountryIso); 775 } 776 if (rule == PREMIUM_RULE_USE_NETWORK || rule == PREMIUM_RULE_USE_BOTH) { 777 String networkCountryIso = mTelephonyManager.getNetworkCountryIso(); 778 if (networkCountryIso == null || networkCountryIso.length() != 2) { 779 Rlog.e(TAG, "Can't get Network country Iso: trying SIM country Iso"); 780 networkCountryIso = mTelephonyManager.getSimCountryIso(); 781 } 782 783 smsCategory = SmsUsageMonitor.mergeShortCodeCategories(smsCategory, 784 mUsageMonitor.checkDestination(tracker.mDestAddress, networkCountryIso)); 785 } 786 787 if (smsCategory == SmsUsageMonitor.CATEGORY_NOT_SHORT_CODE 788 || smsCategory == SmsUsageMonitor.CATEGORY_FREE_SHORT_CODE 789 || smsCategory == SmsUsageMonitor.CATEGORY_STANDARD_SHORT_CODE) { 790 return true; // not a premium short code 791 } 792 793 // Wait for user confirmation unless the user has set permission to always allow/deny 794 int premiumSmsPermission = mUsageMonitor.getPremiumSmsPermission( 795 tracker.mAppInfo.packageName); 796 if (premiumSmsPermission == SmsUsageMonitor.PREMIUM_SMS_PERMISSION_UNKNOWN) { 797 // First time trying to send to premium SMS. 798 premiumSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER; 799 } 800 801 switch (premiumSmsPermission) { 802 case SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW: 803 Rlog.d(TAG, "User approved this app to send to premium SMS"); 804 return true; 805 806 case SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW: 807 Rlog.w(TAG, "User denied this app from sending to premium SMS"); 808 sendMessage(obtainMessage(EVENT_STOP_SENDING, tracker)); 809 return false; // reject this message 810 811 case SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER: 812 default: 813 int event; 814 if (smsCategory == SmsUsageMonitor.CATEGORY_POSSIBLE_PREMIUM_SHORT_CODE) { 815 event = EVENT_CONFIRM_SEND_TO_POSSIBLE_PREMIUM_SHORT_CODE; 816 } else { 817 event = EVENT_CONFIRM_SEND_TO_PREMIUM_SHORT_CODE; 818 } 819 sendMessage(obtainMessage(event, tracker)); 820 return false; // wait for user confirmation 821 } 822 } 823 } 824 825 /** 826 * Deny sending an SMS if the outgoing queue limit is reached. Used when the message 827 * must be confirmed by the user due to excessive usage or potential premium SMS detected. 828 * @param tracker the SmsTracker for the message to send 829 * @return true if the message was denied; false to continue with send confirmation 830 */ 831 private boolean denyIfQueueLimitReached(SmsTracker tracker) { 832 if (mPendingTrackerCount >= MO_MSG_QUEUE_LIMIT) { 833 // Deny sending message when the queue limit is reached. 834 Rlog.e(TAG, "Denied because queue limit reached"); 835 tracker.onFailed(mContext, RESULT_ERROR_LIMIT_EXCEEDED, 0/*errorCode*/); 836 return true; 837 } 838 mPendingTrackerCount++; 839 return false; 840 } 841 842 /** 843 * Returns the label for the specified app package name. 844 * @param appPackage the package name of the app requesting to send an SMS 845 * @return the label for the specified app, or the package name if getApplicationInfo() fails 846 */ 847 private CharSequence getAppLabel(String appPackage) { 848 PackageManager pm = mContext.getPackageManager(); 849 try { 850 ApplicationInfo appInfo = pm.getApplicationInfo(appPackage, 0); 851 return appInfo.loadLabel(pm); 852 } catch (PackageManager.NameNotFoundException e) { 853 Rlog.e(TAG, "PackageManager Name Not Found for package " + appPackage); 854 return appPackage; // fall back to package name if we can't get app label 855 } 856 } 857 858 /** 859 * Post an alert when SMS needs confirmation due to excessive usage. 860 * @param tracker an SmsTracker for the current message. 861 */ 862 protected void handleReachSentLimit(SmsTracker tracker) { 863 if (denyIfQueueLimitReached(tracker)) { 864 return; // queue limit reached; error was returned to caller 865 } 866 867 CharSequence appLabel = getAppLabel(tracker.mAppInfo.packageName); 868 Resources r = Resources.getSystem(); 869 Spanned messageText = Html.fromHtml(r.getString(R.string.sms_control_message, appLabel)); 870 871 ConfirmDialogListener listener = new ConfirmDialogListener(tracker, null); 872 873 AlertDialog d = new AlertDialog.Builder(mContext) 874 .setTitle(R.string.sms_control_title) 875 .setIcon(R.drawable.stat_sys_warning) 876 .setMessage(messageText) 877 .setPositiveButton(r.getString(R.string.sms_control_yes), listener) 878 .setNegativeButton(r.getString(R.string.sms_control_no), listener) 879 .setOnCancelListener(listener) 880 .create(); 881 882 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 883 d.show(); 884 } 885 886 /** 887 * Post an alert for user confirmation when sending to a potential short code. 888 * @param isPremium true if the destination is known to be a premium short code 889 * @param tracker the SmsTracker for the current message. 890 */ 891 protected void handleConfirmShortCode(boolean isPremium, SmsTracker tracker) { 892 if (denyIfQueueLimitReached(tracker)) { 893 return; // queue limit reached; error was returned to caller 894 } 895 896 int detailsId; 897 if (isPremium) { 898 detailsId = R.string.sms_premium_short_code_details; 899 } else { 900 detailsId = R.string.sms_short_code_details; 901 } 902 903 CharSequence appLabel = getAppLabel(tracker.mAppInfo.packageName); 904 Resources r = Resources.getSystem(); 905 Spanned messageText = Html.fromHtml(r.getString(R.string.sms_short_code_confirm_message, 906 appLabel, tracker.mDestAddress)); 907 908 LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( 909 Context.LAYOUT_INFLATER_SERVICE); 910 View layout = inflater.inflate(R.layout.sms_short_code_confirmation_dialog, null); 911 912 ConfirmDialogListener listener = new ConfirmDialogListener(tracker, 913 (TextView)layout.findViewById(R.id.sms_short_code_remember_undo_instruction)); 914 915 916 TextView messageView = (TextView) layout.findViewById(R.id.sms_short_code_confirm_message); 917 messageView.setText(messageText); 918 919 ViewGroup detailsLayout = (ViewGroup) layout.findViewById( 920 R.id.sms_short_code_detail_layout); 921 TextView detailsView = (TextView) detailsLayout.findViewById( 922 R.id.sms_short_code_detail_message); 923 detailsView.setText(detailsId); 924 925 CheckBox rememberChoice = (CheckBox) layout.findViewById( 926 R.id.sms_short_code_remember_choice_checkbox); 927 rememberChoice.setOnCheckedChangeListener(listener); 928 929 AlertDialog d = new AlertDialog.Builder(mContext) 930 .setView(layout) 931 .setPositiveButton(r.getString(R.string.sms_short_code_confirm_allow), listener) 932 .setNegativeButton(r.getString(R.string.sms_short_code_confirm_deny), listener) 933 .setOnCancelListener(listener) 934 .create(); 935 936 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 937 d.show(); 938 939 listener.setPositiveButton(d.getButton(DialogInterface.BUTTON_POSITIVE)); 940 listener.setNegativeButton(d.getButton(DialogInterface.BUTTON_NEGATIVE)); 941 } 942 943 /** 944 * Returns the premium SMS permission for the specified package. If the package has never 945 * been seen before, the default {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ASK_USER} 946 * will be returned. 947 * @param packageName the name of the package to query permission 948 * @return one of {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_UNKNOWN}, 949 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ASK_USER}, 950 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_NEVER_ALLOW}, or 951 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW} 952 */ 953 public int getPremiumSmsPermission(String packageName) { 954 return mUsageMonitor.getPremiumSmsPermission(packageName); 955 } 956 957 /** 958 * Sets the premium SMS permission for the specified package and save the value asynchronously 959 * to persistent storage. 960 * @param packageName the name of the package to set permission 961 * @param permission one of {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ASK_USER}, 962 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_NEVER_ALLOW}, or 963 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW} 964 */ 965 public void setPremiumSmsPermission(String packageName, int permission) { 966 mUsageMonitor.setPremiumSmsPermission(packageName, permission); 967 } 968 969 /** 970 * Send the message along to the radio. 971 * 972 * @param tracker holds the SMS message to send 973 */ 974 protected abstract void sendSms(SmsTracker tracker); 975 976 /** 977 * Send the SMS via the PSTN network. 978 * 979 * @param tracker holds the Sms tracker ready to be sent 980 */ 981 protected abstract void sendSmsByPstn(SmsTracker tracker); 982 983 /** 984 * Retry the message along to the radio. 985 * 986 * @param tracker holds the SMS message to send 987 */ 988 public void sendRetrySms(SmsTracker tracker) { 989 // re-routing to ImsSMSDispatcher 990 if (mImsSMSDispatcher != null) { 991 mImsSMSDispatcher.sendRetrySms(tracker); 992 } else { 993 Rlog.e(TAG, mImsSMSDispatcher + " is null. Retry failed"); 994 } 995 } 996 997 /** 998 * Send the multi-part SMS based on multipart Sms tracker 999 * 1000 * @param tracker holds the multipart Sms tracker ready to be sent 1001 */ 1002 private void sendMultipartSms(SmsTracker tracker) { 1003 ArrayList<String> parts; 1004 ArrayList<PendingIntent> sentIntents; 1005 ArrayList<PendingIntent> deliveryIntents; 1006 1007 HashMap<String, Object> map = tracker.mData; 1008 1009 String destinationAddress = (String) map.get("destination"); 1010 String scAddress = (String) map.get("scaddress"); 1011 1012 parts = (ArrayList<String>) map.get("parts"); 1013 sentIntents = (ArrayList<PendingIntent>) map.get("sentIntents"); 1014 deliveryIntents = (ArrayList<PendingIntent>) map.get("deliveryIntents"); 1015 1016 // check if in service 1017 int ss = mPhone.getServiceState().getState(); 1018 // if sms over IMS is not supported on data and voice is not available... 1019 if (!isIms() && ss != ServiceState.STATE_IN_SERVICE) { 1020 for (int i = 0, count = parts.size(); i < count; i++) { 1021 PendingIntent sentIntent = null; 1022 if (sentIntents != null && sentIntents.size() > i) { 1023 sentIntent = sentIntents.get(i); 1024 } 1025 handleNotInService(ss, sentIntent); 1026 } 1027 return; 1028 } 1029 1030 sendMultipartText(destinationAddress, scAddress, parts, sentIntents, deliveryIntents); 1031 } 1032 1033 /** 1034 * Keeps track of an SMS that has been sent to the RIL, until it has 1035 * successfully been sent, or we're done trying. 1036 */ 1037 protected static final class SmsTracker { 1038 // fields need to be public for derived SmsDispatchers 1039 public final HashMap<String, Object> mData; 1040 public int mRetryCount; 1041 public int mImsRetry; // nonzero indicates initial message was sent over Ims 1042 public int mMessageRef; 1043 String mFormat; 1044 1045 public final PendingIntent mSentIntent; 1046 public final PendingIntent mDeliveryIntent; 1047 1048 public final PackageInfo mAppInfo; 1049 public final String mDestAddress; 1050 1051 private long mTimestamp = System.currentTimeMillis(); 1052 public Uri mMessageUri; // Uri of persisted message if we wrote one 1053 1054 // Reference to states of a multipart message that this part belongs to 1055 private AtomicInteger mUnsentPartCount; 1056 private AtomicBoolean mAnyPartFailed; 1057 1058 private SmsTracker(HashMap<String, Object> data, PendingIntent sentIntent, 1059 PendingIntent deliveryIntent, PackageInfo appInfo, String destAddr, String format, 1060 AtomicInteger unsentPartCount, AtomicBoolean anyPartFailed, Uri messageUri) { 1061 mData = data; 1062 mSentIntent = sentIntent; 1063 mDeliveryIntent = deliveryIntent; 1064 mRetryCount = 0; 1065 mAppInfo = appInfo; 1066 mDestAddress = destAddr; 1067 mFormat = format; 1068 mImsRetry = 0; 1069 mMessageRef = 0; 1070 mUnsentPartCount = unsentPartCount; 1071 mAnyPartFailed = anyPartFailed; 1072 mMessageUri = messageUri; 1073 } 1074 1075 /** 1076 * Returns whether this tracker holds a multi-part SMS. 1077 * @return true if the tracker holds a multi-part SMS; false otherwise 1078 */ 1079 boolean isMultipart() { 1080 return mData.containsKey("parts"); 1081 } 1082 1083 /** 1084 * Persist this as a sent message 1085 */ 1086 void writeSentMessage(Context context) { 1087 String text = (String)mData.get("text"); 1088 if (text != null) { 1089 boolean deliveryReport = (mDeliveryIntent != null); 1090 // Using invalid threadId 0 here. When the message is inserted into the db, the 1091 // provider looks up the threadId based on the recipient(s). 1092 mMessageUri = Sms.addMessageToUri(context.getContentResolver(), 1093 Telephony.Sms.Sent.CONTENT_URI, 1094 mDestAddress, 1095 text /*body*/, 1096 null /*subject*/, 1097 mTimestamp /*date*/, 1098 true /*read*/, 1099 deliveryReport /*deliveryReport*/, 1100 0 /*threadId*/); 1101 } 1102 } 1103 1104 /** 1105 * Update the status of this message if we persisted it 1106 */ 1107 public void updateSentMessageStatus(Context context, int status) { 1108 if (mMessageUri != null) { 1109 // If we wrote this message in writeSentMessage, update it now 1110 ContentValues values = new ContentValues(1); 1111 values.put(Sms.STATUS, status); 1112 SqliteWrapper.update(context, context.getContentResolver(), 1113 mMessageUri, values, null, null); 1114 } 1115 } 1116 1117 /** 1118 * Update the error_code column of a message 1119 * 1120 * @param context The Context 1121 * @param errorCode The error code 1122 */ 1123 private void updateMessageErrorCode(Context context, int errorCode) { 1124 if (!SystemProperties.getBoolean("telephony.sms.autopersist", false)) { 1125 // TODO(ywen): Temporarily only enable this with a system property 1126 // so not to break existing apps 1127 return; 1128 } 1129 if (mMessageUri == null) { 1130 return; 1131 } 1132 final ContentValues values = new ContentValues(1); 1133 values.put(Sms.ERROR_CODE, errorCode); 1134 final long identity = Binder.clearCallingIdentity(); 1135 try { 1136 if (SqliteWrapper.update(context, context.getContentResolver(), mMessageUri, values, 1137 null/*where*/, null/*selectionArgs*/) != 1) { 1138 Rlog.e(TAG, "Failed to update message error code"); 1139 } 1140 } finally { 1141 Binder.restoreCallingIdentity(identity); 1142 } 1143 } 1144 1145 /** 1146 * Set the final state of a message: FAILED or SENT 1147 * 1148 * @param context The Context 1149 * @param messageType The final message type 1150 */ 1151 private void setMessageFinalState(Context context, int messageType) { 1152 if (!SystemProperties.getBoolean("telephony.sms.autopersist", false)) { 1153 // TODO(ywen): Temporarily only enable this with a system property 1154 // so not to break existing apps 1155 return; 1156 } 1157 if (mMessageUri == null) { 1158 return; 1159 } 1160 final ContentValues values = new ContentValues(1); 1161 values.put(Sms.TYPE, messageType); 1162 final long identity = Binder.clearCallingIdentity(); 1163 try { 1164 if (SqliteWrapper.update(context, context.getContentResolver(), mMessageUri, values, 1165 null/*where*/, null/*selectionArgs*/) != 1) { 1166 Rlog.e(TAG, "Failed to move message to " + messageType); 1167 } 1168 } finally { 1169 Binder.restoreCallingIdentity(identity); 1170 } 1171 } 1172 1173 /** 1174 * Handle a failure of a single part message or a part of a multipart message 1175 * 1176 * @param context The Context 1177 * @param error The error to send back with 1178 * @param errorCode 1179 */ 1180 public void onFailed(Context context, int error, int errorCode) { 1181 if (mAnyPartFailed != null) { 1182 mAnyPartFailed.set(true); 1183 } 1184 // is single part or last part of multipart message 1185 boolean isSinglePartOrLastPart = true; 1186 if (mUnsentPartCount != null) { 1187 isSinglePartOrLastPart = mUnsentPartCount.decrementAndGet() == 0; 1188 } 1189 if (errorCode != 0) { 1190 updateMessageErrorCode(context, errorCode); 1191 } 1192 if (isSinglePartOrLastPart) { 1193 setMessageFinalState(context, Sms.MESSAGE_TYPE_FAILED); 1194 } 1195 if (mSentIntent != null) { 1196 try { 1197 // Extra information to send with the sent intent 1198 Intent fillIn = new Intent(); 1199 if (mMessageUri != null) { 1200 // Pass this to SMS apps so that they know where it is stored 1201 fillIn.putExtra("uri", mMessageUri.toString()); 1202 } 1203 if (errorCode != 0) { 1204 fillIn.putExtra("errorCode", errorCode); 1205 } 1206 if (mUnsentPartCount != null && isSinglePartOrLastPart) { 1207 // Is multipart and last part 1208 fillIn.putExtra(SEND_NEXT_MSG_EXTRA, true); 1209 } 1210 mSentIntent.send(context, error, fillIn); 1211 } catch (CanceledException ex) { 1212 Rlog.e(TAG, "Failed to send result"); 1213 } 1214 } 1215 } 1216 1217 /** 1218 * Handle the sent of a single part message or a part of a multipart message 1219 * 1220 * @param context The Context 1221 */ 1222 public void onSent(Context context) { 1223 // is single part or last part of multipart message 1224 boolean isSinglePartOrLastPart = true; 1225 if (mUnsentPartCount != null) { 1226 isSinglePartOrLastPart = mUnsentPartCount.decrementAndGet() == 0; 1227 } 1228 if (isSinglePartOrLastPart) { 1229 boolean success = true; 1230 if (mAnyPartFailed != null && mAnyPartFailed.get()) { 1231 success = false; 1232 } 1233 if (success) { 1234 setMessageFinalState(context, Sms.MESSAGE_TYPE_SENT); 1235 } else { 1236 setMessageFinalState(context, Sms.MESSAGE_TYPE_FAILED); 1237 } 1238 } 1239 if (mSentIntent != null) { 1240 try { 1241 // Extra information to send with the sent intent 1242 Intent fillIn = new Intent(); 1243 if (mMessageUri != null) { 1244 // Pass this to SMS apps so that they know where it is stored 1245 fillIn.putExtra("uri", mMessageUri.toString()); 1246 } 1247 if (mUnsentPartCount != null && isSinglePartOrLastPart) { 1248 // Is multipart and last part 1249 fillIn.putExtra(SEND_NEXT_MSG_EXTRA, true); 1250 } 1251 mSentIntent.send(context, Activity.RESULT_OK, fillIn); 1252 } catch (CanceledException ex) { 1253 Rlog.e(TAG, "Failed to send result"); 1254 } 1255 } 1256 } 1257 } 1258 1259 protected SmsTracker getSmsTracker(HashMap<String, Object> data, PendingIntent sentIntent, 1260 PendingIntent deliveryIntent, String format, AtomicInteger unsentPartCount, 1261 AtomicBoolean anyPartFailed, Uri messageUri) { 1262 // Get calling app package name via UID from Binder call 1263 PackageManager pm = mContext.getPackageManager(); 1264 String[] packageNames = pm.getPackagesForUid(Binder.getCallingUid()); 1265 1266 // Get package info via packagemanager 1267 PackageInfo appInfo = null; 1268 if (packageNames != null && packageNames.length > 0) { 1269 try { 1270 // XXX this is lossy- apps can share a UID 1271 appInfo = pm.getPackageInfo(packageNames[0], PackageManager.GET_SIGNATURES); 1272 } catch (PackageManager.NameNotFoundException e) { 1273 // error will be logged in sendRawPdu 1274 } 1275 } 1276 // Strip non-digits from destination phone number before checking for short codes 1277 // and before displaying the number to the user if confirmation is required. 1278 String destAddr = PhoneNumberUtils.extractNetworkPortion((String) data.get("destAddr")); 1279 return new SmsTracker(data, sentIntent, deliveryIntent, appInfo, destAddr, format, 1280 unsentPartCount, anyPartFailed, messageUri); 1281 } 1282 1283 protected SmsTracker getSmsTracker(HashMap<String, Object> data, PendingIntent sentIntent, 1284 PendingIntent deliveryIntent, String format, Uri messageUri) { 1285 return getSmsTracker(data, sentIntent, deliveryIntent, format, null/*unsentPartCount*/, 1286 null/*anyPartFailed*/, messageUri); 1287 } 1288 1289 protected HashMap<String, Object> getSmsTrackerMap(String destAddr, String scAddr, 1290 String text, SmsMessageBase.SubmitPduBase pdu) { 1291 HashMap<String, Object> map = new HashMap<String, Object>(); 1292 map.put("destAddr", destAddr); 1293 map.put("scAddr", scAddr); 1294 map.put("text", text); 1295 map.put("smsc", pdu.encodedScAddress); 1296 map.put("pdu", pdu.encodedMessage); 1297 return map; 1298 } 1299 1300 protected HashMap<String, Object> getSmsTrackerMap(String destAddr, String scAddr, 1301 int destPort, byte[] data, SmsMessageBase.SubmitPduBase pdu) { 1302 HashMap<String, Object> map = new HashMap<String, Object>(); 1303 map.put("destAddr", destAddr); 1304 map.put("scAddr", scAddr); 1305 map.put("destPort", destPort); 1306 map.put("data", data); 1307 map.put("smsc", pdu.encodedScAddress); 1308 map.put("pdu", pdu.encodedMessage); 1309 return map; 1310 } 1311 1312 /** 1313 * Dialog listener for SMS confirmation dialog. 1314 */ 1315 private final class ConfirmDialogListener 1316 implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, 1317 CompoundButton.OnCheckedChangeListener { 1318 1319 private final SmsTracker mTracker; 1320 private Button mPositiveButton; 1321 private Button mNegativeButton; 1322 private boolean mRememberChoice; // default is unchecked 1323 private final TextView mRememberUndoInstruction; 1324 1325 ConfirmDialogListener(SmsTracker tracker, TextView textView) { 1326 mTracker = tracker; 1327 mRememberUndoInstruction = textView; 1328 } 1329 1330 void setPositiveButton(Button button) { 1331 mPositiveButton = button; 1332 } 1333 1334 void setNegativeButton(Button button) { 1335 mNegativeButton = button; 1336 } 1337 1338 @Override 1339 public void onClick(DialogInterface dialog, int which) { 1340 // Always set the SMS permission so that Settings will show a permission setting 1341 // for the app (it won't be shown until after the app tries to send to a short code). 1342 int newSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER; 1343 1344 if (which == DialogInterface.BUTTON_POSITIVE) { 1345 Rlog.d(TAG, "CONFIRM sending SMS"); 1346 // XXX this is lossy- apps can have more than one signature 1347 EventLog.writeEvent(EventLogTags.EXP_DET_SMS_SENT_BY_USER, 1348 mTracker.mAppInfo.applicationInfo == null ? 1349 -1 : mTracker.mAppInfo.applicationInfo.uid); 1350 sendMessage(obtainMessage(EVENT_SEND_CONFIRMED_SMS, mTracker)); 1351 if (mRememberChoice) { 1352 newSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW; 1353 } 1354 } else if (which == DialogInterface.BUTTON_NEGATIVE) { 1355 Rlog.d(TAG, "DENY sending SMS"); 1356 // XXX this is lossy- apps can have more than one signature 1357 EventLog.writeEvent(EventLogTags.EXP_DET_SMS_DENIED_BY_USER, 1358 mTracker.mAppInfo.applicationInfo == null ? 1359 -1 : mTracker.mAppInfo.applicationInfo.uid); 1360 sendMessage(obtainMessage(EVENT_STOP_SENDING, mTracker)); 1361 if (mRememberChoice) { 1362 newSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW; 1363 } 1364 } 1365 setPremiumSmsPermission(mTracker.mAppInfo.packageName, newSmsPermission); 1366 } 1367 1368 @Override 1369 public void onCancel(DialogInterface dialog) { 1370 Rlog.d(TAG, "dialog dismissed: don't send SMS"); 1371 sendMessage(obtainMessage(EVENT_STOP_SENDING, mTracker)); 1372 } 1373 1374 @Override 1375 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 1376 Rlog.d(TAG, "remember this choice: " + isChecked); 1377 mRememberChoice = isChecked; 1378 if (isChecked) { 1379 mPositiveButton.setText(R.string.sms_short_code_confirm_always_allow); 1380 mNegativeButton.setText(R.string.sms_short_code_confirm_never_allow); 1381 if (mRememberUndoInstruction != null) { 1382 mRememberUndoInstruction. 1383 setText(R.string.sms_short_code_remember_undo_instruction); 1384 mRememberUndoInstruction.setPadding(0,0,0,32); 1385 } 1386 } else { 1387 mPositiveButton.setText(R.string.sms_short_code_confirm_allow); 1388 mNegativeButton.setText(R.string.sms_short_code_confirm_deny); 1389 if (mRememberUndoInstruction != null) { 1390 mRememberUndoInstruction.setText(""); 1391 mRememberUndoInstruction.setPadding(0,0,0,0); 1392 } 1393 } 1394 } 1395 } 1396 1397 public boolean isIms() { 1398 if (mImsSMSDispatcher != null) { 1399 return mImsSMSDispatcher.isIms(); 1400 } else { 1401 Rlog.e(TAG, mImsSMSDispatcher + " is null"); 1402 return false; 1403 } 1404 } 1405 1406 public String getImsSmsFormat() { 1407 if (mImsSMSDispatcher != null) { 1408 return mImsSMSDispatcher.getImsSmsFormat(); 1409 } else { 1410 Rlog.e(TAG, mImsSMSDispatcher + " is null"); 1411 return null; 1412 } 1413 } 1414 1415 protected Uri writeOutboxMessage(long subId, String address, String text, 1416 boolean requireDeliveryReport) { 1417 if (!SystemProperties.getBoolean("telephony.sms.autopersist", false)) { 1418 // TODO(ywen): Temporarily only enable this with a system property 1419 // so not to break existing apps 1420 return null; 1421 } 1422 final ContentValues values = new ContentValues(7); 1423 values.put(Telephony.Sms.SUB_ID, subId); 1424 values.put(Telephony.Sms.ADDRESS, address); 1425 values.put(Telephony.Sms.DATE, System.currentTimeMillis()); // milliseconds 1426 values.put(Telephony.Sms.SEEN, 1); 1427 values.put(Telephony.Sms.READ, 1); 1428 values.put(Telephony.Sms.BODY, text); 1429 if (requireDeliveryReport) { 1430 values.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_PENDING); 1431 } 1432 final long identity = Binder.clearCallingIdentity(); 1433 try { 1434 final Uri uri = mContext.getContentResolver().insert( 1435 Telephony.Sms.Outbox.CONTENT_URI, values); 1436 return uri; 1437 } catch (Exception e) { 1438 Rlog.e(TAG, "Failed to persist outbox message", e); 1439 return null; 1440 } finally { 1441 Binder.restoreCallingIdentity(identity); 1442 } 1443 } 1444 1445 private String getMultipartMessageText(ArrayList<String> parts) { 1446 final StringBuilder sb = new StringBuilder(); 1447 for (String part : parts) { 1448 if (part != null) { 1449 sb.append(part); 1450 } 1451 } 1452 return sb.toString(); 1453 } 1454} 1455