SMSDispatcher.java revision cafda9904d2804959d51697cdc63a185e687cb98
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 (!Telephony.NEW_API) { 349 // TODO(ywen):Temporarily only enable this with a flag so not to break existing apps 350 if (SmsApplication.shouldWriteMessageForPackage( 351 tracker.mAppInfo.applicationInfo.packageName, mContext)) { 352 // Persist it into the SMS database as a sent message 353 // so the user can see it in their default app. 354 tracker.writeSentMessage(mContext); 355 } 356 } 357 if (tracker.mDeliveryIntent != null) { 358 // Expecting a status report. Add it to the list. 359 deliveryPendingList.add(tracker); 360 } 361 tracker.onSent(mContext); 362 } else { 363 if (DBG) Rlog.d(TAG, "SMS send failed"); 364 365 int ss = mPhone.getServiceState().getState(); 366 367 if ( tracker.mImsRetry > 0 && ss != ServiceState.STATE_IN_SERVICE) { 368 // This is retry after failure over IMS but voice is not available. 369 // Set retry to max allowed, so no retry is sent and 370 // cause RESULT_ERROR_GENERIC_FAILURE to be returned to app. 371 tracker.mRetryCount = MAX_SEND_RETRIES; 372 373 Rlog.d(TAG, "handleSendComplete: Skipping retry: " 374 +" isIms()="+isIms() 375 +" mRetryCount="+tracker.mRetryCount 376 +" mImsRetry="+tracker.mImsRetry 377 +" mMessageRef="+tracker.mMessageRef 378 +" SS= "+mPhone.getServiceState().getState()); 379 } 380 381 // if sms over IMS is not supported on data and voice is not available... 382 if (!isIms() && ss != ServiceState.STATE_IN_SERVICE) { 383 tracker.onFailed(mContext, getNotInServiceError(ss), 0/*errorCode*/); 384 } else if ((((CommandException)(ar.exception)).getCommandError() 385 == CommandException.Error.SMS_FAIL_RETRY) && 386 tracker.mRetryCount < MAX_SEND_RETRIES) { 387 // Retry after a delay if needed. 388 // TODO: According to TS 23.040, 9.2.3.6, we should resend 389 // with the same TP-MR as the failed message, and 390 // TP-RD set to 1. However, we don't have a means of 391 // knowing the MR for the failed message (EF_SMSstatus 392 // may or may not have the MR corresponding to this 393 // message, depending on the failure). Also, in some 394 // implementations this retry is handled by the baseband. 395 tracker.mRetryCount++; 396 Message retryMsg = obtainMessage(EVENT_SEND_RETRY, tracker); 397 sendMessageDelayed(retryMsg, SEND_RETRY_DELAY); 398 } else { 399 int errorCode = 0; 400 if (ar.result != null) { 401 errorCode = ((SmsResponse)ar.result).mErrorCode; 402 } 403 int error = RESULT_ERROR_GENERIC_FAILURE; 404 if (((CommandException)(ar.exception)).getCommandError() 405 == CommandException.Error.FDN_CHECK_FAILURE) { 406 error = RESULT_ERROR_FDN_CHECK_FAILURE; 407 } 408 tracker.onFailed(mContext, error, errorCode); 409 } 410 } 411 } 412 413 /** 414 * Handles outbound message when the phone is not in service. 415 * 416 * @param ss Current service state. Valid values are: 417 * OUT_OF_SERVICE 418 * EMERGENCY_ONLY 419 * POWER_OFF 420 * @param sentIntent the PendingIntent to send the error to 421 */ 422 protected static void handleNotInService(int ss, PendingIntent sentIntent) { 423 if (sentIntent != null) { 424 try { 425 if (ss == ServiceState.STATE_POWER_OFF) { 426 sentIntent.send(RESULT_ERROR_RADIO_OFF); 427 } else { 428 sentIntent.send(RESULT_ERROR_NO_SERVICE); 429 } 430 } catch (CanceledException ex) {} 431 } 432 } 433 434 /** 435 * @param ss service state 436 * @return The result error based on input service state for not in service error 437 */ 438 protected static int getNotInServiceError(int ss) { 439 if (ss == ServiceState.STATE_POWER_OFF) { 440 return RESULT_ERROR_RADIO_OFF; 441 } 442 return RESULT_ERROR_NO_SERVICE; 443 } 444 445 /** 446 * Send a data based SMS to a specific application port. 447 * 448 * @param destAddr the address to send the message to 449 * @param scAddr is the service center address or null to use 450 * the current default SMSC 451 * @param destPort the port to deliver the message to 452 * @param data the body of the message to send 453 * @param sentIntent if not NULL this <code>PendingIntent</code> is 454 * broadcast when the message is successfully sent, or failed. 455 * The result code will be <code>Activity.RESULT_OK<code> for success, 456 * or one of these errors:<br> 457 * <code>RESULT_ERROR_GENERIC_FAILURE</code><br> 458 * <code>RESULT_ERROR_RADIO_OFF</code><br> 459 * <code>RESULT_ERROR_NULL_PDU</code><br> 460 * <code>RESULT_ERROR_NO_SERVICE</code><br>. 461 * For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include 462 * the extra "errorCode" containing a radio technology specific value, 463 * generally only useful for troubleshooting.<br> 464 * The per-application based SMS control checks sentIntent. If sentIntent 465 * is NULL the caller will be checked against all unknown applications, 466 * which cause smaller number of SMS to be sent in checking period. 467 * @param deliveryIntent if not NULL this <code>PendingIntent</code> is 468 * broadcast when the message is delivered to the recipient. The 469 * raw pdu of the status report is in the extended data ("pdu"). 470 */ 471 protected abstract void sendData(String destAddr, String scAddr, int destPort, 472 byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent); 473 474 /** 475 * Send a text based SMS. 476 * 477 * @param destAddr the address to send the message to 478 * @param scAddr is the service center address or null to use 479 * the current default SMSC 480 * @param text the body of the message to send 481 * @param sentIntent if not NULL this <code>PendingIntent</code> is 482 * broadcast when the message is successfully sent, or failed. 483 * The result code will be <code>Activity.RESULT_OK<code> for success, 484 * or one of these errors:<br> 485 * <code>RESULT_ERROR_GENERIC_FAILURE</code><br> 486 * <code>RESULT_ERROR_RADIO_OFF</code><br> 487 * <code>RESULT_ERROR_NULL_PDU</code><br> 488 * <code>RESULT_ERROR_NO_SERVICE</code><br>. 489 * For <code>RESULT_ERROR_GENERIC_FAILURE</code> the sentIntent may include 490 * the extra "errorCode" containing a radio technology specific value, 491 * generally only useful for troubleshooting.<br> 492 * The per-application based SMS control checks sentIntent. If sentIntent 493 * is NULL the caller will be checked against all unknown applications, 494 * which cause smaller number of SMS to be sent in checking period. 495 * @param deliveryIntent if not NULL this <code>PendingIntent</code> is 496 * broadcast when the message is delivered to the recipient. The 497 * raw pdu of the status report is in the extended data ("pdu"). 498 */ 499 protected abstract void sendText(String destAddr, String scAddr, 500 String text, PendingIntent sentIntent, PendingIntent deliveryIntent); 501 502 /** 503 * Inject an SMS PDU into the android platform. 504 * 505 * @param pdu is the byte array of pdu to be injected into android telephony layer 506 * @param format is the format of SMS pdu (3gpp or 3gpp2) 507 * @param receivedIntent if not NULL this <code>PendingIntent</code> is 508 * broadcast when the message is successfully received by the 509 * android telephony layer. This intent is broadcasted at 510 * the same time an SMS received from radio is responded back. 511 */ 512 protected abstract void injectSmsPdu(byte[] pdu, String format, PendingIntent receivedIntent); 513 514 /** 515 * Calculate the number of septets needed to encode the message. 516 * 517 * @param messageBody the message to encode 518 * @param use7bitOnly ignore (but still count) illegal characters if true 519 * @return TextEncodingDetails 520 */ 521 protected abstract TextEncodingDetails calculateLength(CharSequence messageBody, 522 boolean use7bitOnly); 523 524 /** 525 * Update the status of a pending (send-by-IP) SMS message and resend by PSTN if necessary. 526 * This outbound message was handled by the carrier app. If the carrier app fails to send 527 * this message, it would be resent by PSTN. 528 * 529 * @param messageRef the reference number of the SMS message. 530 * @param success True if and only if the message was sent successfully. If its value is 531 * false, this message should be resent via PSTN. 532 */ 533 protected abstract void updateSmsSendStatus(int messageRef, boolean success); 534 535 /** 536 * Handler for a {@link GsmSMSDispatcher} or {@link CdmaSMSDispatcher} broadcast. 537 * If SMS sending is successfuly, sends EVENT_SEND_SMS_COMPLETE message. Otherwise, 538 * send the message via the GSM/CDMA network. 539 */ 540 protected final class SMSDispatcherReceiver extends BroadcastReceiver { 541 542 private final SmsTracker mTracker; 543 544 public SMSDispatcherReceiver(SmsTracker tracker) { 545 mTracker = tracker; 546 } 547 548 @Override 549 public void onReceive(Context context, Intent intent) { 550 String action = intent.getAction(); 551 if (action.equals(Intents.SMS_SEND_ACTION)) { 552 int rc = getResultCode(); 553 if (rc == Activity.RESULT_OK) { 554 Rlog.d(TAG, "Sending SMS by IP pending."); 555 Bundle resultExtras = getResultExtras(false); 556 if (resultExtras != null && resultExtras.containsKey("messageref")) { 557 mTracker.mMessageRef = resultExtras.getInt("messageref"); 558 Rlog.d(TAG, "messageref = " + mTracker.mMessageRef); 559 } else { 560 Rlog.e(TAG, "Can't find messageref in result extras."); 561 } 562 sendPendingList.add(mTracker); 563 } else { 564 Rlog.d(TAG, "Sending SMS by IP failed."); 565 sendSmsByPstn(mTracker); 566 } 567 } else { 568 Rlog.e(TAG, "unexpected BroadcastReceiver action: " + action); 569 } 570 } 571 } 572 573 /** 574 * Send a multi-part text based SMS. 575 * 576 * @param destAddr the address to send the message to 577 * @param scAddr is the service center address or null to use 578 * the current default SMSC 579 * @param parts an <code>ArrayList</code> of strings that, in order, 580 * comprise the original message 581 * @param sentIntents if not null, an <code>ArrayList</code> of 582 * <code>PendingIntent</code>s (one for each message part) that is 583 * broadcast when the corresponding message part has been sent. 584 * The result code will be <code>Activity.RESULT_OK<code> for success, 585 * or one of these errors: 586 * <code>RESULT_ERROR_GENERIC_FAILURE</code> 587 * <code>RESULT_ERROR_RADIO_OFF</code> 588 * <code>RESULT_ERROR_NULL_PDU</code> 589 * <code>RESULT_ERROR_NO_SERVICE</code>. 590 * The per-application based SMS control checks sentIntent. If sentIntent 591 * is NULL the caller will be checked against all unknown applications, 592 * which cause smaller number of SMS to be sent in checking period. 593 * @param deliveryIntents if not null, an <code>ArrayList</code> of 594 * <code>PendingIntent</code>s (one for each message part) that is 595 * broadcast when the corresponding message part has been delivered 596 * to the recipient. The raw pdu of the status report is in the 597 * extended data ("pdu"). 598 */ 599 protected void sendMultipartText(String destAddr, String scAddr, 600 ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, 601 ArrayList<PendingIntent> deliveryIntents) { 602 Uri messageUri = writeOutboxMessage( 603 SubscriptionManager.getPreferredSmsSubId(), 604 destAddr, 605 getMultipartMessageText(parts), 606 deliveryIntents != null && deliveryIntents.size() > 0); 607 int refNumber = getNextConcatenatedRef() & 0x00FF; 608 int msgCount = parts.size(); 609 int encoding = SmsConstants.ENCODING_UNKNOWN; 610 611 TextEncodingDetails[] encodingForParts = new TextEncodingDetails[msgCount]; 612 for (int i = 0; i < msgCount; i++) { 613 TextEncodingDetails details = calculateLength(parts.get(i), false); 614 if (encoding != details.codeUnitSize 615 && (encoding == SmsConstants.ENCODING_UNKNOWN 616 || encoding == SmsConstants.ENCODING_7BIT)) { 617 encoding = details.codeUnitSize; 618 } 619 encodingForParts[i] = details; 620 } 621 622 // States to track at the message level (for all parts) 623 final AtomicInteger unsentPartCount = new AtomicInteger(msgCount); 624 final AtomicBoolean anyPartFailed = new AtomicBoolean(false); 625 626 for (int i = 0; i < msgCount; i++) { 627 SmsHeader.ConcatRef concatRef = new SmsHeader.ConcatRef(); 628 concatRef.refNumber = refNumber; 629 concatRef.seqNumber = i + 1; // 1-based sequence 630 concatRef.msgCount = msgCount; 631 // TODO: We currently set this to true since our messaging app will never 632 // send more than 255 parts (it converts the message to MMS well before that). 633 // However, we should support 3rd party messaging apps that might need 16-bit 634 // references 635 // Note: It's not sufficient to just flip this bit to true; it will have 636 // ripple effects (several calculations assume 8-bit ref). 637 concatRef.isEightBits = true; 638 SmsHeader smsHeader = new SmsHeader(); 639 smsHeader.concatRef = concatRef; 640 641 // Set the national language tables for 3GPP 7-bit encoding, if enabled. 642 if (encoding == SmsConstants.ENCODING_7BIT) { 643 smsHeader.languageTable = encodingForParts[i].languageTable; 644 smsHeader.languageShiftTable = encodingForParts[i].languageShiftTable; 645 } 646 647 PendingIntent sentIntent = null; 648 if (sentIntents != null && sentIntents.size() > i) { 649 sentIntent = sentIntents.get(i); 650 } 651 652 PendingIntent deliveryIntent = null; 653 if (deliveryIntents != null && deliveryIntents.size() > i) { 654 deliveryIntent = deliveryIntents.get(i); 655 } 656 657 sendNewSubmitPdu(destAddr, scAddr, parts.get(i), smsHeader, encoding, 658 sentIntent, deliveryIntent, (i == (msgCount - 1)), 659 unsentPartCount, anyPartFailed, messageUri); 660 } 661 } 662 663 /** 664 * Create a new SubmitPdu and send it. 665 */ 666 protected abstract void sendNewSubmitPdu(String destinationAddress, String scAddress, 667 String message, SmsHeader smsHeader, int encoding, 668 PendingIntent sentIntent, PendingIntent deliveryIntent, boolean lastPart, 669 AtomicInteger unsentPartCount, AtomicBoolean anyPartFailed, Uri messageUri); 670 671 /** 672 * Send a SMS 673 * @param tracker will contain: 674 * -smsc the SMSC to send the message through, or NULL for the 675 * default SMSC 676 * -pdu the raw PDU to send 677 * -sentIntent if not NULL this <code>Intent</code> is 678 * broadcast when the message is successfully sent, or failed. 679 * The result code will be <code>Activity.RESULT_OK<code> for success, 680 * or one of these errors: 681 * <code>RESULT_ERROR_GENERIC_FAILURE</code> 682 * <code>RESULT_ERROR_RADIO_OFF</code> 683 * <code>RESULT_ERROR_NULL_PDU</code> 684 * <code>RESULT_ERROR_NO_SERVICE</code>. 685 * The per-application based SMS control checks sentIntent. If sentIntent 686 * is NULL the caller will be checked against all unknown applications, 687 * which cause smaller number of SMS to be sent in checking period. 688 * -deliveryIntent if not NULL this <code>Intent</code> is 689 * broadcast when the message is delivered to the recipient. The 690 * raw pdu of the status report is in the extended data ("pdu"). 691 * -param destAddr the destination phone number (for short code confirmation) 692 */ 693 protected void sendRawPdu(SmsTracker tracker) { 694 HashMap map = tracker.mData; 695 byte pdu[] = (byte[]) map.get("pdu"); 696 697 if (mSmsSendDisabled) { 698 Rlog.e(TAG, "Device does not support sending sms."); 699 tracker.onFailed(mContext, RESULT_ERROR_NO_SERVICE, 0/*errorCode*/); 700 return; 701 } 702 703 if (pdu == null) { 704 Rlog.e(TAG, "Empty PDU"); 705 tracker.onFailed(mContext, RESULT_ERROR_NULL_PDU, 0/*errorCode*/); 706 return; 707 } 708 709 // Get calling app package name via UID from Binder call 710 PackageManager pm = mContext.getPackageManager(); 711 String[] packageNames = pm.getPackagesForUid(Binder.getCallingUid()); 712 713 if (packageNames == null || packageNames.length == 0) { 714 // Refuse to send SMS if we can't get the calling package name. 715 Rlog.e(TAG, "Can't get calling app package name: refusing to send SMS"); 716 tracker.onFailed(mContext, RESULT_ERROR_GENERIC_FAILURE, 0/*errorCode*/); 717 return; 718 } 719 720 // Get package info via packagemanager 721 PackageInfo appInfo; 722 try { 723 // XXX this is lossy- apps can share a UID 724 appInfo = pm.getPackageInfo(packageNames[0], PackageManager.GET_SIGNATURES); 725 } catch (PackageManager.NameNotFoundException e) { 726 Rlog.e(TAG, "Can't get calling app package info: refusing to send SMS"); 727 tracker.onFailed(mContext, RESULT_ERROR_GENERIC_FAILURE, 0/*errorCode*/); 728 return; 729 } 730 731 // checkDestination() returns true if the destination is not a premium short code or the 732 // sending app is approved to send to short codes. Otherwise, a message is sent to our 733 // handler with the SmsTracker to request user confirmation before sending. 734 if (checkDestination(tracker)) { 735 // check for excessive outgoing SMS usage by this app 736 if (!mUsageMonitor.check(appInfo.packageName, SINGLE_PART_SMS)) { 737 sendMessage(obtainMessage(EVENT_SEND_LIMIT_REACHED_CONFIRMATION, tracker)); 738 return; 739 } 740 741 int ss = mPhone.getServiceState().getState(); 742 743 // if sms over IMS is not supported on data and voice is not available... 744 if (!isIms() && ss != ServiceState.STATE_IN_SERVICE) { 745 tracker.onFailed(mContext, getNotInServiceError(ss), 0/*errorCode*/); 746 } else { 747 sendSms(tracker); 748 } 749 } 750 } 751 752 /** 753 * Check if destination is a potential premium short code and sender is not pre-approved to 754 * send to short codes. 755 * 756 * @param tracker the tracker for the SMS to send 757 * @return true if the destination is approved; false if user confirmation event was sent 758 */ 759 boolean checkDestination(SmsTracker tracker) { 760 if (mContext.checkCallingOrSelfPermission(SEND_SMS_NO_CONFIRMATION_PERMISSION) 761 == PackageManager.PERMISSION_GRANTED) { 762 return true; // app is pre-approved to send to short codes 763 } else { 764 int rule = mPremiumSmsRule.get(); 765 int smsCategory = SmsUsageMonitor.CATEGORY_NOT_SHORT_CODE; 766 if (rule == PREMIUM_RULE_USE_SIM || rule == PREMIUM_RULE_USE_BOTH) { 767 String simCountryIso = mTelephonyManager.getSimCountryIso(); 768 if (simCountryIso == null || simCountryIso.length() != 2) { 769 Rlog.e(TAG, "Can't get SIM country Iso: trying network country Iso"); 770 simCountryIso = mTelephonyManager.getNetworkCountryIso(); 771 } 772 773 smsCategory = mUsageMonitor.checkDestination(tracker.mDestAddress, simCountryIso); 774 } 775 if (rule == PREMIUM_RULE_USE_NETWORK || rule == PREMIUM_RULE_USE_BOTH) { 776 String networkCountryIso = mTelephonyManager.getNetworkCountryIso(); 777 if (networkCountryIso == null || networkCountryIso.length() != 2) { 778 Rlog.e(TAG, "Can't get Network country Iso: trying SIM country Iso"); 779 networkCountryIso = mTelephonyManager.getSimCountryIso(); 780 } 781 782 smsCategory = SmsUsageMonitor.mergeShortCodeCategories(smsCategory, 783 mUsageMonitor.checkDestination(tracker.mDestAddress, networkCountryIso)); 784 } 785 786 if (smsCategory == SmsUsageMonitor.CATEGORY_NOT_SHORT_CODE 787 || smsCategory == SmsUsageMonitor.CATEGORY_FREE_SHORT_CODE 788 || smsCategory == SmsUsageMonitor.CATEGORY_STANDARD_SHORT_CODE) { 789 return true; // not a premium short code 790 } 791 792 // Wait for user confirmation unless the user has set permission to always allow/deny 793 int premiumSmsPermission = mUsageMonitor.getPremiumSmsPermission( 794 tracker.mAppInfo.packageName); 795 if (premiumSmsPermission == SmsUsageMonitor.PREMIUM_SMS_PERMISSION_UNKNOWN) { 796 // First time trying to send to premium SMS. 797 premiumSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER; 798 } 799 800 switch (premiumSmsPermission) { 801 case SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW: 802 Rlog.d(TAG, "User approved this app to send to premium SMS"); 803 return true; 804 805 case SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW: 806 Rlog.w(TAG, "User denied this app from sending to premium SMS"); 807 sendMessage(obtainMessage(EVENT_STOP_SENDING, tracker)); 808 return false; // reject this message 809 810 case SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER: 811 default: 812 int event; 813 if (smsCategory == SmsUsageMonitor.CATEGORY_POSSIBLE_PREMIUM_SHORT_CODE) { 814 event = EVENT_CONFIRM_SEND_TO_POSSIBLE_PREMIUM_SHORT_CODE; 815 } else { 816 event = EVENT_CONFIRM_SEND_TO_PREMIUM_SHORT_CODE; 817 } 818 sendMessage(obtainMessage(event, tracker)); 819 return false; // wait for user confirmation 820 } 821 } 822 } 823 824 /** 825 * Deny sending an SMS if the outgoing queue limit is reached. Used when the message 826 * must be confirmed by the user due to excessive usage or potential premium SMS detected. 827 * @param tracker the SmsTracker for the message to send 828 * @return true if the message was denied; false to continue with send confirmation 829 */ 830 private boolean denyIfQueueLimitReached(SmsTracker tracker) { 831 if (mPendingTrackerCount >= MO_MSG_QUEUE_LIMIT) { 832 // Deny sending message when the queue limit is reached. 833 Rlog.e(TAG, "Denied because queue limit reached"); 834 tracker.onFailed(mContext, RESULT_ERROR_LIMIT_EXCEEDED, 0/*errorCode*/); 835 return true; 836 } 837 mPendingTrackerCount++; 838 return false; 839 } 840 841 /** 842 * Returns the label for the specified app package name. 843 * @param appPackage the package name of the app requesting to send an SMS 844 * @return the label for the specified app, or the package name if getApplicationInfo() fails 845 */ 846 private CharSequence getAppLabel(String appPackage) { 847 PackageManager pm = mContext.getPackageManager(); 848 try { 849 ApplicationInfo appInfo = pm.getApplicationInfo(appPackage, 0); 850 return appInfo.loadLabel(pm); 851 } catch (PackageManager.NameNotFoundException e) { 852 Rlog.e(TAG, "PackageManager Name Not Found for package " + appPackage); 853 return appPackage; // fall back to package name if we can't get app label 854 } 855 } 856 857 /** 858 * Post an alert when SMS needs confirmation due to excessive usage. 859 * @param tracker an SmsTracker for the current message. 860 */ 861 protected void handleReachSentLimit(SmsTracker tracker) { 862 if (denyIfQueueLimitReached(tracker)) { 863 return; // queue limit reached; error was returned to caller 864 } 865 866 CharSequence appLabel = getAppLabel(tracker.mAppInfo.packageName); 867 Resources r = Resources.getSystem(); 868 Spanned messageText = Html.fromHtml(r.getString(R.string.sms_control_message, appLabel)); 869 870 ConfirmDialogListener listener = new ConfirmDialogListener(tracker, null); 871 872 AlertDialog d = new AlertDialog.Builder(mContext) 873 .setTitle(R.string.sms_control_title) 874 .setIcon(R.drawable.stat_sys_warning) 875 .setMessage(messageText) 876 .setPositiveButton(r.getString(R.string.sms_control_yes), listener) 877 .setNegativeButton(r.getString(R.string.sms_control_no), listener) 878 .setOnCancelListener(listener) 879 .create(); 880 881 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 882 d.show(); 883 } 884 885 /** 886 * Post an alert for user confirmation when sending to a potential short code. 887 * @param isPremium true if the destination is known to be a premium short code 888 * @param tracker the SmsTracker for the current message. 889 */ 890 protected void handleConfirmShortCode(boolean isPremium, SmsTracker tracker) { 891 if (denyIfQueueLimitReached(tracker)) { 892 return; // queue limit reached; error was returned to caller 893 } 894 895 int detailsId; 896 if (isPremium) { 897 detailsId = R.string.sms_premium_short_code_details; 898 } else { 899 detailsId = R.string.sms_short_code_details; 900 } 901 902 CharSequence appLabel = getAppLabel(tracker.mAppInfo.packageName); 903 Resources r = Resources.getSystem(); 904 Spanned messageText = Html.fromHtml(r.getString(R.string.sms_short_code_confirm_message, 905 appLabel, tracker.mDestAddress)); 906 907 LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( 908 Context.LAYOUT_INFLATER_SERVICE); 909 View layout = inflater.inflate(R.layout.sms_short_code_confirmation_dialog, null); 910 911 ConfirmDialogListener listener = new ConfirmDialogListener(tracker, 912 (TextView)layout.findViewById(R.id.sms_short_code_remember_undo_instruction)); 913 914 915 TextView messageView = (TextView) layout.findViewById(R.id.sms_short_code_confirm_message); 916 messageView.setText(messageText); 917 918 ViewGroup detailsLayout = (ViewGroup) layout.findViewById( 919 R.id.sms_short_code_detail_layout); 920 TextView detailsView = (TextView) detailsLayout.findViewById( 921 R.id.sms_short_code_detail_message); 922 detailsView.setText(detailsId); 923 924 CheckBox rememberChoice = (CheckBox) layout.findViewById( 925 R.id.sms_short_code_remember_choice_checkbox); 926 rememberChoice.setOnCheckedChangeListener(listener); 927 928 AlertDialog d = new AlertDialog.Builder(mContext) 929 .setView(layout) 930 .setPositiveButton(r.getString(R.string.sms_short_code_confirm_allow), listener) 931 .setNegativeButton(r.getString(R.string.sms_short_code_confirm_deny), listener) 932 .setOnCancelListener(listener) 933 .create(); 934 935 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 936 d.show(); 937 938 listener.setPositiveButton(d.getButton(DialogInterface.BUTTON_POSITIVE)); 939 listener.setNegativeButton(d.getButton(DialogInterface.BUTTON_NEGATIVE)); 940 } 941 942 /** 943 * Returns the premium SMS permission for the specified package. If the package has never 944 * been seen before, the default {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ASK_USER} 945 * will be returned. 946 * @param packageName the name of the package to query permission 947 * @return one of {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_UNKNOWN}, 948 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ASK_USER}, 949 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_NEVER_ALLOW}, or 950 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW} 951 */ 952 public int getPremiumSmsPermission(String packageName) { 953 return mUsageMonitor.getPremiumSmsPermission(packageName); 954 } 955 956 /** 957 * Sets the premium SMS permission for the specified package and save the value asynchronously 958 * to persistent storage. 959 * @param packageName the name of the package to set permission 960 * @param permission one of {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ASK_USER}, 961 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_NEVER_ALLOW}, or 962 * {@link SmsUsageMonitor#PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW} 963 */ 964 public void setPremiumSmsPermission(String packageName, int permission) { 965 mUsageMonitor.setPremiumSmsPermission(packageName, permission); 966 } 967 968 /** 969 * Send the message along to the radio. 970 * 971 * @param tracker holds the SMS message to send 972 */ 973 protected abstract void sendSms(SmsTracker tracker); 974 975 /** 976 * Send the SMS via the PSTN network. 977 * 978 * @param tracker holds the Sms tracker ready to be sent 979 */ 980 protected abstract void sendSmsByPstn(SmsTracker tracker); 981 982 /** 983 * Retry the message along to the radio. 984 * 985 * @param tracker holds the SMS message to send 986 */ 987 public void sendRetrySms(SmsTracker tracker) { 988 // re-routing to ImsSMSDispatcher 989 if (mImsSMSDispatcher != null) { 990 mImsSMSDispatcher.sendRetrySms(tracker); 991 } else { 992 Rlog.e(TAG, mImsSMSDispatcher + " is null. Retry failed"); 993 } 994 } 995 996 /** 997 * Send the multi-part SMS based on multipart Sms tracker 998 * 999 * @param tracker holds the multipart Sms tracker ready to be sent 1000 */ 1001 private void sendMultipartSms(SmsTracker tracker) { 1002 ArrayList<String> parts; 1003 ArrayList<PendingIntent> sentIntents; 1004 ArrayList<PendingIntent> deliveryIntents; 1005 1006 HashMap<String, Object> map = tracker.mData; 1007 1008 String destinationAddress = (String) map.get("destination"); 1009 String scAddress = (String) map.get("scaddress"); 1010 1011 parts = (ArrayList<String>) map.get("parts"); 1012 sentIntents = (ArrayList<PendingIntent>) map.get("sentIntents"); 1013 deliveryIntents = (ArrayList<PendingIntent>) map.get("deliveryIntents"); 1014 1015 // check if in service 1016 int ss = mPhone.getServiceState().getState(); 1017 // if sms over IMS is not supported on data and voice is not available... 1018 if (!isIms() && ss != ServiceState.STATE_IN_SERVICE) { 1019 for (int i = 0, count = parts.size(); i < count; i++) { 1020 PendingIntent sentIntent = null; 1021 if (sentIntents != null && sentIntents.size() > i) { 1022 sentIntent = sentIntents.get(i); 1023 } 1024 handleNotInService(ss, sentIntent); 1025 } 1026 return; 1027 } 1028 1029 sendMultipartText(destinationAddress, scAddress, parts, sentIntents, deliveryIntents); 1030 } 1031 1032 /** 1033 * Keeps track of an SMS that has been sent to the RIL, until it has 1034 * successfully been sent, or we're done trying. 1035 */ 1036 protected static final class SmsTracker { 1037 // fields need to be public for derived SmsDispatchers 1038 public final HashMap<String, Object> mData; 1039 public int mRetryCount; 1040 public int mImsRetry; // nonzero indicates initial message was sent over Ims 1041 public int mMessageRef; 1042 String mFormat; 1043 1044 public final PendingIntent mSentIntent; 1045 public final PendingIntent mDeliveryIntent; 1046 1047 public final PackageInfo mAppInfo; 1048 public final String mDestAddress; 1049 1050 private long mTimestamp = System.currentTimeMillis(); 1051 public Uri mMessageUri; // Uri of persisted message if we wrote one 1052 1053 // Reference to states of a multipart message that this part belongs to 1054 private AtomicInteger mUnsentPartCount; 1055 private AtomicBoolean mAnyPartFailed; 1056 1057 private SmsTracker(HashMap<String, Object> data, PendingIntent sentIntent, 1058 PendingIntent deliveryIntent, PackageInfo appInfo, String destAddr, String format, 1059 AtomicInteger unsentPartCount, AtomicBoolean anyPartFailed, Uri messageUri) { 1060 mData = data; 1061 mSentIntent = sentIntent; 1062 mDeliveryIntent = deliveryIntent; 1063 mRetryCount = 0; 1064 mAppInfo = appInfo; 1065 mDestAddress = destAddr; 1066 mFormat = format; 1067 mImsRetry = 0; 1068 mMessageRef = 0; 1069 mUnsentPartCount = unsentPartCount; 1070 mAnyPartFailed = anyPartFailed; 1071 mMessageUri = messageUri; 1072 } 1073 1074 /** 1075 * Returns whether this tracker holds a multi-part SMS. 1076 * @return true if the tracker holds a multi-part SMS; false otherwise 1077 */ 1078 boolean isMultipart() { 1079 return mData.containsKey("parts"); 1080 } 1081 1082 /** 1083 * Persist this as a sent message 1084 */ 1085 void writeSentMessage(Context context) { 1086 String text = (String)mData.get("text"); 1087 if (text != null) { 1088 boolean deliveryReport = (mDeliveryIntent != null); 1089 // Using invalid threadId 0 here. When the message is inserted into the db, the 1090 // provider looks up the threadId based on the recipient(s). 1091 mMessageUri = Sms.addMessageToUri(context.getContentResolver(), 1092 Telephony.Sms.Sent.CONTENT_URI, 1093 mDestAddress, 1094 text /*body*/, 1095 null /*subject*/, 1096 mTimestamp /*date*/, 1097 true /*read*/, 1098 deliveryReport /*deliveryReport*/, 1099 0 /*threadId*/); 1100 } 1101 } 1102 1103 /** 1104 * Update the status of this message if we persisted it 1105 */ 1106 public void updateSentMessageStatus(Context context, int status) { 1107 if (mMessageUri != null) { 1108 // If we wrote this message in writeSentMessage, update it now 1109 ContentValues values = new ContentValues(1); 1110 values.put(Sms.STATUS, status); 1111 SqliteWrapper.update(context, context.getContentResolver(), 1112 mMessageUri, values, null, null); 1113 } 1114 } 1115 1116 /** 1117 * Update the error_code column of a message 1118 * 1119 * @param context The Context 1120 * @param errorCode The error code 1121 */ 1122 private void updateMessageErrorCode(Context context, int errorCode) { 1123 if (!Telephony.NEW_API) { 1124 // TODO(ywen):Temporarily only enable this with a flag so not to break existing apps 1125 return; 1126 } 1127 if (mMessageUri == null) { 1128 return; 1129 } 1130 final ContentValues values = new ContentValues(1); 1131 values.put(Sms.ERROR_CODE, errorCode); 1132 final long identity = Binder.clearCallingIdentity(); 1133 try { 1134 if (SqliteWrapper.update(context, context.getContentResolver(), mMessageUri, values, 1135 null/*where*/, null/*selectionArgs*/) != 1) { 1136 Rlog.e(TAG, "Failed to update message error code"); 1137 } 1138 } finally { 1139 Binder.restoreCallingIdentity(identity); 1140 } 1141 } 1142 1143 /** 1144 * Set the final state of a message: FAILED or SENT 1145 * 1146 * @param context The Context 1147 * @param messageType The final message type 1148 */ 1149 private void setMessageFinalState(Context context, int messageType) { 1150 if (!Telephony.NEW_API) { 1151 // TODO(ywen):Temporarily only enable this with a flag so not to break existing apps 1152 return; 1153 } 1154 if (mMessageUri == null) { 1155 return; 1156 } 1157 final ContentValues values = new ContentValues(1); 1158 values.put(Sms.TYPE, messageType); 1159 final long identity = Binder.clearCallingIdentity(); 1160 try { 1161 if (SqliteWrapper.update(context, context.getContentResolver(), mMessageUri, values, 1162 null/*where*/, null/*selectionArgs*/) != 1) { 1163 Rlog.e(TAG, "Failed to move message to " + messageType); 1164 } 1165 } finally { 1166 Binder.restoreCallingIdentity(identity); 1167 } 1168 } 1169 1170 /** 1171 * Handle a failure of a single part message or a part of a multipart message 1172 * 1173 * @param context The Context 1174 * @param error The error to send back with 1175 * @param errorCode 1176 */ 1177 public void onFailed(Context context, int error, int errorCode) { 1178 if (mAnyPartFailed != null) { 1179 mAnyPartFailed.set(true); 1180 } 1181 // is single part or last part of multipart message 1182 boolean isSinglePartOrLastPart = true; 1183 if (mUnsentPartCount != null) { 1184 isSinglePartOrLastPart = mUnsentPartCount.decrementAndGet() == 0; 1185 } 1186 if (errorCode != 0) { 1187 updateMessageErrorCode(context, errorCode); 1188 } 1189 if (isSinglePartOrLastPart) { 1190 setMessageFinalState(context, Sms.MESSAGE_TYPE_FAILED); 1191 } 1192 if (mSentIntent != null) { 1193 try { 1194 // Extra information to send with the sent intent 1195 Intent fillIn = new Intent(); 1196 if (mMessageUri != null) { 1197 // Pass this to SMS apps so that they know where it is stored 1198 fillIn.putExtra("uri", mMessageUri.toString()); 1199 } 1200 if (errorCode != 0) { 1201 fillIn.putExtra("errorCode", errorCode); 1202 } 1203 if (mUnsentPartCount != null && isSinglePartOrLastPart) { 1204 // Is multipart and last part 1205 fillIn.putExtra(SEND_NEXT_MSG_EXTRA, true); 1206 } 1207 mSentIntent.send(context, error, fillIn); 1208 } catch (CanceledException ex) { 1209 Rlog.e(TAG, "Failed to send result"); 1210 } 1211 } 1212 } 1213 1214 /** 1215 * Handle the sent of a single part message or a part of a multipart message 1216 * 1217 * @param context The Context 1218 */ 1219 public void onSent(Context context) { 1220 // is single part or last part of multipart message 1221 boolean isSinglePartOrLastPart = true; 1222 if (mUnsentPartCount != null) { 1223 isSinglePartOrLastPart = mUnsentPartCount.decrementAndGet() == 0; 1224 } 1225 if (isSinglePartOrLastPart) { 1226 boolean success = true; 1227 if (mAnyPartFailed != null && mAnyPartFailed.get()) { 1228 success = false; 1229 } 1230 if (success) { 1231 setMessageFinalState(context, Sms.MESSAGE_TYPE_SENT); 1232 } else { 1233 setMessageFinalState(context, Sms.MESSAGE_TYPE_FAILED); 1234 } 1235 } 1236 if (mSentIntent != null) { 1237 try { 1238 // Extra information to send with the sent intent 1239 Intent fillIn = new Intent(); 1240 if (mMessageUri != null) { 1241 // Pass this to SMS apps so that they know where it is stored 1242 fillIn.putExtra("uri", mMessageUri.toString()); 1243 } 1244 if (mUnsentPartCount != null && isSinglePartOrLastPart) { 1245 // Is multipart and last part 1246 fillIn.putExtra(SEND_NEXT_MSG_EXTRA, true); 1247 } 1248 mSentIntent.send(context, Activity.RESULT_OK, fillIn); 1249 } catch (CanceledException ex) { 1250 Rlog.e(TAG, "Failed to send result"); 1251 } 1252 } 1253 } 1254 } 1255 1256 protected SmsTracker getSmsTracker(HashMap<String, Object> data, PendingIntent sentIntent, 1257 PendingIntent deliveryIntent, String format, AtomicInteger unsentPartCount, 1258 AtomicBoolean anyPartFailed, Uri messageUri) { 1259 // Get calling app package name via UID from Binder call 1260 PackageManager pm = mContext.getPackageManager(); 1261 String[] packageNames = pm.getPackagesForUid(Binder.getCallingUid()); 1262 1263 // Get package info via packagemanager 1264 PackageInfo appInfo = null; 1265 if (packageNames != null && packageNames.length > 0) { 1266 try { 1267 // XXX this is lossy- apps can share a UID 1268 appInfo = pm.getPackageInfo(packageNames[0], PackageManager.GET_SIGNATURES); 1269 } catch (PackageManager.NameNotFoundException e) { 1270 // error will be logged in sendRawPdu 1271 } 1272 } 1273 // Strip non-digits from destination phone number before checking for short codes 1274 // and before displaying the number to the user if confirmation is required. 1275 String destAddr = PhoneNumberUtils.extractNetworkPortion((String) data.get("destAddr")); 1276 return new SmsTracker(data, sentIntent, deliveryIntent, appInfo, destAddr, format, 1277 unsentPartCount, anyPartFailed, messageUri); 1278 } 1279 1280 protected SmsTracker getSmsTracker(HashMap<String, Object> data, PendingIntent sentIntent, 1281 PendingIntent deliveryIntent, String format, Uri messageUri) { 1282 return getSmsTracker(data, sentIntent, deliveryIntent, format, null/*unsentPartCount*/, 1283 null/*anyPartFailed*/, messageUri); 1284 } 1285 1286 protected HashMap<String, Object> getSmsTrackerMap(String destAddr, String scAddr, 1287 String text, SmsMessageBase.SubmitPduBase pdu) { 1288 HashMap<String, Object> map = new HashMap<String, Object>(); 1289 map.put("destAddr", destAddr); 1290 map.put("scAddr", scAddr); 1291 map.put("text", text); 1292 map.put("smsc", pdu.encodedScAddress); 1293 map.put("pdu", pdu.encodedMessage); 1294 return map; 1295 } 1296 1297 protected HashMap<String, Object> getSmsTrackerMap(String destAddr, String scAddr, 1298 int destPort, byte[] data, SmsMessageBase.SubmitPduBase pdu) { 1299 HashMap<String, Object> map = new HashMap<String, Object>(); 1300 map.put("destAddr", destAddr); 1301 map.put("scAddr", scAddr); 1302 map.put("destPort", destPort); 1303 map.put("data", data); 1304 map.put("smsc", pdu.encodedScAddress); 1305 map.put("pdu", pdu.encodedMessage); 1306 return map; 1307 } 1308 1309 /** 1310 * Dialog listener for SMS confirmation dialog. 1311 */ 1312 private final class ConfirmDialogListener 1313 implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, 1314 CompoundButton.OnCheckedChangeListener { 1315 1316 private final SmsTracker mTracker; 1317 private Button mPositiveButton; 1318 private Button mNegativeButton; 1319 private boolean mRememberChoice; // default is unchecked 1320 private final TextView mRememberUndoInstruction; 1321 1322 ConfirmDialogListener(SmsTracker tracker, TextView textView) { 1323 mTracker = tracker; 1324 mRememberUndoInstruction = textView; 1325 } 1326 1327 void setPositiveButton(Button button) { 1328 mPositiveButton = button; 1329 } 1330 1331 void setNegativeButton(Button button) { 1332 mNegativeButton = button; 1333 } 1334 1335 @Override 1336 public void onClick(DialogInterface dialog, int which) { 1337 // Always set the SMS permission so that Settings will show a permission setting 1338 // for the app (it won't be shown until after the app tries to send to a short code). 1339 int newSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER; 1340 1341 if (which == DialogInterface.BUTTON_POSITIVE) { 1342 Rlog.d(TAG, "CONFIRM sending SMS"); 1343 // XXX this is lossy- apps can have more than one signature 1344 EventLog.writeEvent(EventLogTags.EXP_DET_SMS_SENT_BY_USER, 1345 mTracker.mAppInfo.applicationInfo == null ? 1346 -1 : mTracker.mAppInfo.applicationInfo.uid); 1347 sendMessage(obtainMessage(EVENT_SEND_CONFIRMED_SMS, mTracker)); 1348 if (mRememberChoice) { 1349 newSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW; 1350 } 1351 } else if (which == DialogInterface.BUTTON_NEGATIVE) { 1352 Rlog.d(TAG, "DENY sending SMS"); 1353 // XXX this is lossy- apps can have more than one signature 1354 EventLog.writeEvent(EventLogTags.EXP_DET_SMS_DENIED_BY_USER, 1355 mTracker.mAppInfo.applicationInfo == null ? 1356 -1 : mTracker.mAppInfo.applicationInfo.uid); 1357 sendMessage(obtainMessage(EVENT_STOP_SENDING, mTracker)); 1358 if (mRememberChoice) { 1359 newSmsPermission = SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW; 1360 } 1361 } 1362 setPremiumSmsPermission(mTracker.mAppInfo.packageName, newSmsPermission); 1363 } 1364 1365 @Override 1366 public void onCancel(DialogInterface dialog) { 1367 Rlog.d(TAG, "dialog dismissed: don't send SMS"); 1368 sendMessage(obtainMessage(EVENT_STOP_SENDING, mTracker)); 1369 } 1370 1371 @Override 1372 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 1373 Rlog.d(TAG, "remember this choice: " + isChecked); 1374 mRememberChoice = isChecked; 1375 if (isChecked) { 1376 mPositiveButton.setText(R.string.sms_short_code_confirm_always_allow); 1377 mNegativeButton.setText(R.string.sms_short_code_confirm_never_allow); 1378 if (mRememberUndoInstruction != null) { 1379 mRememberUndoInstruction. 1380 setText(R.string.sms_short_code_remember_undo_instruction); 1381 mRememberUndoInstruction.setPadding(0,0,0,32); 1382 } 1383 } else { 1384 mPositiveButton.setText(R.string.sms_short_code_confirm_allow); 1385 mNegativeButton.setText(R.string.sms_short_code_confirm_deny); 1386 if (mRememberUndoInstruction != null) { 1387 mRememberUndoInstruction.setText(""); 1388 mRememberUndoInstruction.setPadding(0,0,0,0); 1389 } 1390 } 1391 } 1392 } 1393 1394 public boolean isIms() { 1395 if (mImsSMSDispatcher != null) { 1396 return mImsSMSDispatcher.isIms(); 1397 } else { 1398 Rlog.e(TAG, mImsSMSDispatcher + " is null"); 1399 return false; 1400 } 1401 } 1402 1403 public String getImsSmsFormat() { 1404 if (mImsSMSDispatcher != null) { 1405 return mImsSMSDispatcher.getImsSmsFormat(); 1406 } else { 1407 Rlog.e(TAG, mImsSMSDispatcher + " is null"); 1408 return null; 1409 } 1410 } 1411 1412 protected Uri writeOutboxMessage(long subId, String address, String text, 1413 boolean requireDeliveryReport) { 1414 if (!Telephony.NEW_API) { 1415 // TODO(ywen): Temporarily only enable this with a flag so not to break existing apps 1416 return null; 1417 } 1418 final ContentValues values = new ContentValues(7); 1419 values.put(Telephony.Sms.SUB_ID, subId); 1420 values.put(Telephony.Sms.ADDRESS, address); 1421 values.put(Telephony.Sms.DATE, System.currentTimeMillis()); // milliseconds 1422 values.put(Telephony.Sms.SEEN, 1); 1423 values.put(Telephony.Sms.READ, 1); 1424 values.put(Telephony.Sms.BODY, text); 1425 if (requireDeliveryReport) { 1426 values.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_PENDING); 1427 } 1428 final long identity = Binder.clearCallingIdentity(); 1429 try { 1430 final Uri uri = mContext.getContentResolver().insert( 1431 Telephony.Sms.Outbox.CONTENT_URI, values); 1432 return uri; 1433 } catch (Exception e) { 1434 Rlog.e(TAG, "Failed to persist outbox message", e); 1435 return null; 1436 } finally { 1437 Binder.restoreCallingIdentity(identity); 1438 } 1439 } 1440 1441 private String getMultipartMessageText(ArrayList<String> parts) { 1442 final StringBuilder sb = new StringBuilder(); 1443 for (String part : parts) { 1444 if (part != null) { 1445 sb.append(part); 1446 } 1447 } 1448 return sb.toString(); 1449 } 1450} 1451