Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 3b4ffb18 authored by Tom Taylor's avatar Tom Taylor
Browse files

Add an app-supplied cross stack id to log messages

Also, when receiving an sms, generate a message id used in logcat
logging. Pass the message id through the intent to the default sms
app receiving the sms.

Bug: 135755360

Test: manually tested sending and receiving sms's and mms's by sending
and receiving via the Messaging app and verifying the messageId is
getting passed back and forth. Updated existing tests.

Change-Id: Iffbeb85bf5e157b85bec33c977efec6772ed9137
parent 8f77571f
Loading
Loading
Loading
Loading
+31 −18
Original line number Diff line number Diff line
@@ -40,7 +40,6 @@ import android.os.Message;
import android.os.UserManager;
import android.provider.Telephony;
import android.telephony.CarrierConfigManager;
import com.android.telephony.Rlog;
import android.telephony.SmsCbMessage;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
@@ -58,6 +57,7 @@ import com.android.internal.telephony.uicc.IccUtils;
import com.android.internal.telephony.uicc.UiccController;
import com.android.internal.telephony.uicc.UiccProfile;
import com.android.internal.util.HexDump;
import com.android.telephony.Rlog;

import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -461,10 +461,11 @@ public class IccSmsInterfaceManager {
     */
    public void sendText(String callingPackage, String destAddr, String scAddr,
            String text, PendingIntent sentIntent, PendingIntent deliveryIntent,
            boolean persistMessageForNonDefaultSmsApp) {
            boolean persistMessageForNonDefaultSmsApp, long messageId) {
        sendTextInternal(callingPackage, destAddr, scAddr, text, sentIntent, deliveryIntent,
                persistMessageForNonDefaultSmsApp, SMS_MESSAGE_PRIORITY_NOT_SPECIFIED,
                false /* expectMore */, SMS_MESSAGE_PERIOD_NOT_SPECIFIED, false /* isForVvm */);
                false /* expectMore */, SMS_MESSAGE_PERIOD_NOT_SPECIFIED, false /* isForVvm */,
                messageId);
    }

    /**
@@ -480,7 +481,7 @@ public class IccSmsInterfaceManager {
        }
        sendTextInternal(callingPackage, destAddr, scAddr, text, sentIntent, deliveryIntent,
                persistMessage, SMS_MESSAGE_PRIORITY_NOT_SPECIFIED, false /* expectMore */,
                SMS_MESSAGE_PERIOD_NOT_SPECIFIED, isForVvm);
                SMS_MESSAGE_PERIOD_NOT_SPECIFIED, isForVvm, 0L /* messageId */);
    }

    /**
@@ -527,23 +528,26 @@ public class IccSmsInterfaceManager {
     *  Validity Period(Minimum) -> 5 mins
     *  Validity Period(Maximum) -> 635040 mins(i.e.63 weeks).
     *  Any Other values including negative considered as Invalid Validity Period of the message.
     * @param messageId An id that uniquely identifies the message requested to be sent.
     *                 Used for logging and diagnostics purposes. The id may be 0.
     */

    private void sendTextInternal(String callingPackage, String destAddr, String scAddr,
            String text, PendingIntent sentIntent, PendingIntent deliveryIntent,
            boolean persistMessageForNonDefaultSmsApp, int priority, boolean expectMore,
            int validityPeriod, boolean isForVvm) {
            int validityPeriod, boolean isForVvm, long messageId) {
        if (Rlog.isLoggable("SMS", Log.VERBOSE)) {
            log("sendText: destAddr=" + destAddr + " scAddr=" + scAddr
                    + " text='" + text + "' sentIntent=" + sentIntent + " deliveryIntent="
                    + deliveryIntent + " priority=" + priority + " expectMore=" + expectMore
                    + " validityPeriod=" + validityPeriod + " isForVVM=" + isForVvm);
                    + " validityPeriod=" + validityPeriod + " isForVVM=" + isForVvm
                    + " id= " +  messageId);
        }
        notifyIfOutgoingEmergencySms(destAddr);
        destAddr = filterDestAddress(destAddr);
        mDispatchersController.sendText(destAddr, scAddr, text, sentIntent, deliveryIntent,
                null/*messageUri*/, callingPackage, persistMessageForNonDefaultSmsApp,
                priority, expectMore, validityPeriod, isForVvm);
                priority, expectMore, validityPeriod, isForVvm, messageId);
    }

    /**
@@ -602,7 +606,7 @@ public class IccSmsInterfaceManager {
        }
        sendTextInternal(callingPackage, destAddr, scAddr, text, sentIntent, deliveryIntent,
                persistMessageForNonDefaultSmsApp, priority, expectMore, validityPeriod,
                false /* isForVvm */);
                false /* isForVvm */, 0L /* messageId */);
    }

    /**
@@ -664,15 +668,19 @@ public class IccSmsInterfaceManager {
     *   broadcast when the corresponding message part has been delivered
     *   to the recipient.  The raw pdu of the status report is in the
     *   extended data ("pdu").
     * @param messageId An id that uniquely identifies the message requested to be sent.
     *                 Used for logging and diagnostics purposes. The id may be 0.
     */

    public void sendMultipartText(String callingPackage, String destAddr, String scAddr,
            List<String> parts, List<PendingIntent> sentIntents,
            List<PendingIntent> deliveryIntents, boolean persistMessageForNonDefaultSmsApp) {
            List<PendingIntent> deliveryIntents, boolean persistMessageForNonDefaultSmsApp,
            long messageId) {
        sendMultipartTextWithOptions(callingPackage, destAddr, scAddr, parts, sentIntents,
                deliveryIntents, persistMessageForNonDefaultSmsApp,
                SMS_MESSAGE_PRIORITY_NOT_SPECIFIED, false /* expectMore */,
                SMS_MESSAGE_PERIOD_NOT_SPECIFIED);
                SMS_MESSAGE_PERIOD_NOT_SPECIFIED,
                messageId);
    }

    /**
@@ -720,12 +728,14 @@ public class IccSmsInterfaceManager {
     *  Validity Period(Minimum) -> 5 mins
     *  Validity Period(Maximum) -> 635040 mins(i.e.63 weeks).
     *  Any Other values including negative considered as Invalid Validity Period of the message.
     * @param messageId An id that uniquely identifies the message requested to be sent.
     *                 Used for logging and diagnostics purposes. The id may be 0.
     */

    public void sendMultipartTextWithOptions(String callingPackage, String destAddr,
            String scAddr, List<String> parts, List<PendingIntent> sentIntents,
            List<PendingIntent> deliveryIntents, boolean persistMessageForNonDefaultSmsApp,
            int priority, boolean expectMore, int validityPeriod) {
            int priority, boolean expectMore, int validityPeriod, long messageId) {
        if (!mSmsPermissions.checkCallingCanSendText(
                persistMessageForNonDefaultSmsApp, callingPackage, "Sending SMS message")) {
            returnUnspecifiedFailure(sentIntents);
@@ -734,8 +744,9 @@ public class IccSmsInterfaceManager {
        if (Rlog.isLoggable("SMS", Log.VERBOSE)) {
            int i = 0;
            for (String part : parts) {
                log("sendMultipartTextWithOptions: destAddr=" + destAddr + ", srAddr=" + scAddr +
                        ", part[" + (i++) + "]=" + part);
                log("sendMultipartTextWithOptions: destAddr=" + destAddr + ", srAddr=" + scAddr
                        + ", part[" + (i++) + "]=" + part
                        + " id: " + messageId);
            }
        }
        notifyIfOutgoingEmergencySms(destAddr);
@@ -766,7 +777,7 @@ public class IccSmsInterfaceManager {
                mDispatchersController.sendText(destAddr, scAddr, singlePart, singleSentIntent,
                        singleDeliveryIntent, null /* messageUri */, callingPackage,
                        persistMessageForNonDefaultSmsApp, priority, expectMore, validityPeriod,
                        false /* isForVvm */);
                        false /* isForVvm */, messageId);
            }
            return;
        }
@@ -777,7 +788,7 @@ public class IccSmsInterfaceManager {
                                      (ArrayList<PendingIntent>) sentIntents,
                                      (ArrayList<PendingIntent>) deliveryIntents,
                                      null, callingPackage, persistMessageForNonDefaultSmsApp,
                                          priority, expectMore, validityPeriod);
                                          priority, expectMore, validityPeriod, messageId);

    }

@@ -1261,7 +1272,8 @@ public class IccSmsInterfaceManager {
        mDispatchersController.sendText(textAndAddress[1], scAddress, textAndAddress[0],
                sentIntent, deliveryIntent, messageUri, callingPkg,
                true /* persistMessageForNonDefaultSmsApp */, SMS_MESSAGE_PRIORITY_NOT_SPECIFIED,
                false /* expectMore */, SMS_MESSAGE_PERIOD_NOT_SPECIFIED, false /* isForVvm */);
                false /* expectMore */, SMS_MESSAGE_PERIOD_NOT_SPECIFIED, false /* isForVvm */,
                0L /* messageId */);
    }

    @UnsupportedAppUsage
@@ -1319,7 +1331,7 @@ public class IccSmsInterfaceManager {
                        true  /* persistMessageForNonDefaultSmsApp */,
                        SMS_MESSAGE_PRIORITY_NOT_SPECIFIED,
                        false /* expectMore */, SMS_MESSAGE_PERIOD_NOT_SPECIFIED,
                        false /* isForVvm */);
                        false /* isForVvm */, 0L /* messageId */);
            }
            return;
        }
@@ -1335,7 +1347,8 @@ public class IccSmsInterfaceManager {
                true  /* persistMessageForNonDefaultSmsApp */,
                SMS_MESSAGE_PRIORITY_NOT_SPECIFIED,
                false /* expectMore */,
                SMS_MESSAGE_PERIOD_NOT_SPECIFIED);
                SMS_MESSAGE_PERIOD_NOT_SPECIFIED,
                0L /* messageId */);
    }

    public int getSmsCapacityOnIcc() {
+44 −22
Original line number Diff line number Diff line
@@ -760,7 +760,7 @@ public abstract class InboundSmsHandler extends StateMachine {
            }
            tracker = TelephonyComponentFactory.getInstance()
                    .inject(InboundSmsTracker.class.getName())
                    .makeInboundSmsTracker(sms.getPdu(),
                    .makeInboundSmsTracker(mContext, sms.getPdu(),
                    sms.getTimestampMillis(), destPort, is3gpp2(), false,
                    sms.getOriginatingAddress(), sms.getDisplayOriginatingAddress(),
                    sms.getMessageBody(), sms.getMessageClass() == MessageClass.CLASS_0,
@@ -772,7 +772,7 @@ public abstract class InboundSmsHandler extends StateMachine {
            int destPort = (portAddrs != null ? portAddrs.destPort : -1);
            tracker = TelephonyComponentFactory.getInstance()
                    .inject(InboundSmsTracker.class.getName())
                    .makeInboundSmsTracker(sms.getPdu(),
                    .makeInboundSmsTracker(mContext, sms.getPdu(),
                    sms.getTimestampMillis(), destPort, is3gpp2(), sms.getOriginatingAddress(),
                    sms.getDisplayOriginatingAddress(), concatRef.refNumber, concatRef.seqNumber,
                    concatRef.msgCount, false, sms.getMessageBody(),
@@ -835,7 +835,8 @@ public abstract class InboundSmsHandler extends StateMachine {
        // Do not process when the message count is invalid.
        if (messageCount <= 0) {
            loge("processMessagePart: returning false due to invalid message count "
                    + messageCount);
                    + messageCount
                    + " id: " + tracker.getMessageId());
            return false;
        }

@@ -880,9 +881,11 @@ public abstract class InboundSmsHandler extends StateMachine {
                    // UserDataHeader is invalid.
                    if (index >= pdus.length || index < 0) {
                        loge(String.format(
                                "processMessagePart: invalid seqNumber = %d, messageCount = %d",
                                "processMessagePart: invalid seqNumber = %d, messageCount = %d,"
                                + " id = %s",
                                index + tracker.getIndexOffset(),
                                messageCount));
                                messageCount,
                                tracker.getMessageId()));
                        continue;
                    }

@@ -919,7 +922,9 @@ public abstract class InboundSmsHandler extends StateMachine {
                    }
                }
            } catch (SQLException e) {
                loge("Can't access multipart SMS database", e);
                loge("Can't access multipart SMS database"
                        + " id: " + tracker.getMessageId(),
                        e);
                return false;
            } finally {
                if (cursor != null) {
@@ -942,7 +947,8 @@ public abstract class InboundSmsHandler extends StateMachine {
        List<byte[]> pduList = Arrays.asList(pdus);
        if (pduList.size() == 0 || pduList.contains(null)) {
            String errorMsg = "processMessagePart: returning false due to "
                    + (pduList.size() == 0 ? "pduList.size() == 0" : "pduList.contains(null)");
                    + (pduList.size() == 0 ? "pduList.size() == 0" : "pduList.contains(null)"
                    + " id: " + tracker.getMessageId());
            loge(errorMsg);
            mLocalLog.log(errorMsg);
            return false;
@@ -957,7 +963,9 @@ public abstract class InboundSmsHandler extends StateMachine {
                    if (msg != null) {
                        pdu = msg.getUserData();
                    } else {
                        loge("processMessagePart: SmsMessage.createFromPdu returned null");
                        loge("processMessagePart: SmsMessage.createFromPdu returned null"
                                + " id: "
                                + tracker.getMessageId());
                        mMetrics.writeIncomingWapPush(mPhone.getPhoneId(), mLastSmsWasInjected,
                                SmsConstants.FORMAT_3GPP, timestamps, false);
                        return false;
@@ -979,7 +987,7 @@ public abstract class InboundSmsHandler extends StateMachine {

        if (isWapPush) {
            int result = mWapPush.dispatchWapPdu(output.toByteArray(), resultReceiver,
                    this, address, tracker.getSubId());
                    this, address, tracker.getSubId(), tracker.getMessageId());
            if (DBG) log("dispatchWapPdu() returned " + result);
            // Add result of WAP-PUSH into metrics. RESULT_SMS_HANDLED indicates that the WAP-PUSH
            // needs to be ignored, so treating it as a success case.
@@ -1011,7 +1019,7 @@ public abstract class InboundSmsHandler extends StateMachine {

        if (!filterInvoked) {
            dispatchSmsDeliveryIntent(pdus, format, destPort, resultReceiver,
                    tracker.isClass0(), tracker.getSubId());
                    tracker.isClass0(), tracker.getSubId(), tracker.getMessageId());
        }

        return true;
@@ -1106,7 +1114,7 @@ public abstract class InboundSmsHandler extends StateMachine {
        CarrierServicesSmsFilterCallback filterCallback =
                new CarrierServicesSmsFilterCallback(
                        pdus, destPort, tracker.getFormat(), resultReceiver, userUnlocked,
                        tracker.isClass0(), tracker.getSubId());
                        tracker.isClass0(), tracker.getSubId(), tracker.getMessageId());
        CarrierServicesSmsFilter carrierServicesFilter = new CarrierServicesSmsFilter(
                mContext, mPhone, pdus, destPort, tracker.getFormat(),
                filterCallback, getName(), mLocalLog);
@@ -1268,10 +1276,13 @@ public abstract class InboundSmsHandler extends StateMachine {
     * @param resultReceiver the receiver handling the delivery result
     */
    private void dispatchSmsDeliveryIntent(byte[][] pdus, String format, int destPort,
            SmsBroadcastReceiver resultReceiver, boolean isClass0, int subId) {
            SmsBroadcastReceiver resultReceiver, boolean isClass0, int subId, long messageId) {
        Intent intent = new Intent();
        intent.putExtra("pdus", pdus);
        intent.putExtra("format", format);
        if (messageId != 0L) {
            intent.putExtra("messageId", messageId);
        }

        if (destPort == -1) {
            intent.setAction(Intents.SMS_DELIVER_ACTION);
@@ -1282,8 +1293,9 @@ public abstract class InboundSmsHandler extends StateMachine {
            if (componentName != null) {
                // Deliver SMS message only to this receiver.
                intent.setComponent(componentName);
                log("Delivering SMS to: " + componentName.getPackageName() +
                    " " + componentName.getClassName());
                log("Delivering SMS to: " + componentName.getPackageName()
                        + " " + componentName.getClassName()
                        + " id: " + messageId);
            } else {
                intent.setComponent(null);
            }
@@ -1330,7 +1342,8 @@ public abstract class InboundSmsHandler extends StateMachine {
            // moveToNext() returns false if no duplicates were found
            if (cursor != null && cursor.moveToNext()) {
                if (cursor.getCount() != 1) {
                    loge("Exact match query returned " + cursor.getCount() + " rows");
                    loge("Exact match query returned " + cursor.getCount() + " rows"
                            + " id: " + tracker.getMessageId());
                }

                // if the exact matching row is marked deleted, that means this message has already
@@ -1373,7 +1386,8 @@ public abstract class InboundSmsHandler extends StateMachine {
                // moveToNext() returns false if no duplicates were found
                if (cursor != null && cursor.moveToNext()) {
                    if (cursor.getCount() != 1) {
                        loge("Inexact match query returned " + cursor.getCount() + " rows");
                        loge("Inexact match query returned " + cursor.getCount() + " rows"
                                + " id: " + tracker.getMessageId());
                    }
                    // delete the old message segment permanently
                    deleteFromRawTable(inexactMatchQuery.first, inexactMatchQuery.second,
@@ -1398,7 +1412,8 @@ public abstract class InboundSmsHandler extends StateMachine {
        byte[] oldPdu = HexDump.hexStringToByteArray(oldPduString);
        if (!Arrays.equals(oldPdu, tracker.getPdu())) {
            loge("Warning: dup message PDU of length " + pdu.length
                    + " is different from existing PDU of length " + oldPdu.length);
                    + " is different from existing PDU of length " + oldPdu.length
                    + " id: " + tracker.getMessageId());
        }
    }

@@ -1419,7 +1434,9 @@ public abstract class InboundSmsHandler extends StateMachine {
                    return Intents.RESULT_SMS_DUPLICATED;   // reject message
                }
            } catch (SQLException e) {
                loge("Can't access SMS database", e);
                loge("Can't access SMS database"
                        + " id: " + tracker.getMessageId(),
                        e);
                return RESULT_SMS_DATABASE_ERROR;    // reject message
            }
        } else {
@@ -1447,7 +1464,8 @@ public abstract class InboundSmsHandler extends StateMachine {
            }
            return Intents.RESULT_SMS_HANDLED;
        } catch (Exception e) {
            loge("error parsing URI for new row: " + newUri, e);
            loge("error parsing URI for new row: " + newUri
                    + " id: " + tracker.getMessageId(), e);
            return RESULT_SMS_INVALID_URI;
        }
    }
@@ -1559,10 +1577,11 @@ public abstract class InboundSmsHandler extends StateMachine {
        private final boolean mUserUnlocked;
        private final boolean mIsClass0;
        private final int mSubId;
        private final long mMessageId;

        CarrierServicesSmsFilterCallback(byte[][] pdus, int destPort, String smsFormat,
                SmsBroadcastReceiver smsBroadcastReceiver,  boolean userUnlocked,
                boolean isClass0, int subId) {
                boolean isClass0, int subId, long messageId) {
            mPdus = pdus;
            mDestPort = destPort;
            mSmsFormat = smsFormat;
@@ -1570,6 +1589,7 @@ public abstract class InboundSmsHandler extends StateMachine {
            mUserUnlocked = userUnlocked;
            mIsClass0 = isClass0;
            mSubId = subId;
            mMessageId = messageId;
        }

        @Override
@@ -1578,14 +1598,16 @@ public abstract class InboundSmsHandler extends StateMachine {
            if ((result & CarrierMessagingService.RECEIVE_OPTIONS_DROP) == 0) {
                if (VisualVoicemailSmsFilter.filter(mContext, mPdus,
                        mSmsFormat, mDestPort, mSubId)) {
                    log("Visual voicemail SMS dropped");
                    log("Visual voicemail SMS dropped"
                            + " id: " + mMessageId);
                    dropSms(mSmsBroadcastReceiver);
                    return;
                }

                if (mUserUnlocked) {
                    dispatchSmsDeliveryIntent(
                            mPdus, mSmsFormat, mDestPort, mSmsBroadcastReceiver, mIsClass0, mSubId);
                            mPdus, mSmsFormat, mDestPort, mSmsBroadcastReceiver, mIsClass0, mSubId,
                            mMessageId);
                } else {
                    // Don't do anything further, leave the message in the raw table if the
                    // credential-encrypted storage is still locked and show the new message
+67 −8
Original line number Diff line number Diff line
@@ -18,12 +18,21 @@ package com.android.internal.telephony;

import android.compat.annotation.UnsupportedAppUsage;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.telephony.Rlog;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Pair;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.HexDump;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

@@ -33,6 +42,8 @@ import java.util.Date;
 * outgoing messages.
 */
public class InboundSmsTracker {
    // Need 8 bytes to get a message id as a long.
    private static final int NUM_OF_BYTES_HASH_VALUE_FOR_MESSAGE_ID = 8;

    // Fields for single and multi-part messages
    private final byte[] mPdu;
@@ -43,6 +54,7 @@ public class InboundSmsTracker {
    private final String mMessageBody;
    private final boolean mIsClass0;
    private final int mSubId;
    private final long mMessageId;

    // Fields for concatenating multi-part SMS messages
    private final String mAddress;
@@ -95,6 +107,7 @@ public class InboundSmsTracker {
    /**
     * Create a tracker for a single-part SMS.
     *
     * @param context
     * @param pdu the message PDU
     * @param timestamp the message timestamp
     * @param destPort the destination port
@@ -104,9 +117,9 @@ public class InboundSmsTracker {
     * @param displayAddress email address if this message was from an email gateway, otherwise same
     *                       as originating address
     */
    public InboundSmsTracker(byte[] pdu, long timestamp, int destPort, boolean is3gpp2,
            boolean is3gpp2WapPdu, String address, String displayAddress, String messageBody,
            boolean isClass0, int subId) {
    public InboundSmsTracker(Context context, byte[] pdu, long timestamp, int destPort,
            boolean is3gpp2, boolean is3gpp2WapPdu, String address, String displayAddress,
            String messageBody, boolean isClass0, int subId) {
        mPdu = pdu;
        mTimestamp = timestamp;
        mDestPort = destPort;
@@ -121,6 +134,7 @@ public class InboundSmsTracker {
        mSequenceNumber = getIndexOffset();     // 0 or 1, depending on type
        mMessageCount = 1;
        mSubId = subId;
        mMessageId = createMessageId(context, timestamp, subId);
    }

    /**
@@ -142,10 +156,10 @@ public class InboundSmsTracker {
     * @param messageCount the total number of segments
     * @param is3gpp2WapPdu true for 3GPP2 format WAP PDU; false otherwise
     */
    public InboundSmsTracker(byte[] pdu, long timestamp, int destPort, boolean is3gpp2,
            String address, String displayAddress, int referenceNumber, int sequenceNumber,
            int messageCount, boolean is3gpp2WapPdu, String messageBody, boolean isClass0,
            int subId) {
    public InboundSmsTracker(Context context, byte[] pdu, long timestamp, int destPort,
             boolean is3gpp2, String address, String displayAddress, int referenceNumber,
             int sequenceNumber, int messageCount, boolean is3gpp2WapPdu, String messageBody,
             boolean isClass0, int subId) {
        mPdu = pdu;
        mTimestamp = timestamp;
        mDestPort = destPort;
@@ -161,6 +175,7 @@ public class InboundSmsTracker {
        mSequenceNumber = sequenceNumber;
        mMessageCount = messageCount;
        mSubId = subId;
        mMessageId = createMessageId(context, timestamp, subId);
    }

    /**
@@ -168,7 +183,7 @@ public class InboundSmsTracker {
     * Since this constructor is used only for recovery during startup, the Dispatcher is null.
     * @param cursor a Cursor pointing to the row to construct this SmsTracker for
     */
    public InboundSmsTracker(Cursor cursor, boolean isCurrentFormat3gpp2) {
    public InboundSmsTracker(Context context, Cursor cursor, boolean isCurrentFormat3gpp2) {
        mPdu = HexDump.hexStringToByteArray(cursor.getString(InboundSmsHandler.PDU_COLUMN));

        // TODO: add a column to raw db to store this
@@ -224,6 +239,7 @@ public class InboundSmsTracker {
                    Integer.toString(mReferenceNumber), Integer.toString(mMessageCount)};
        }
        mMessageBody = cursor.getString(InboundSmsHandler.MESSAGE_BODY_COLUMN);
        mMessageId = createMessageId(context, mTimestamp, mSubId);
    }

    public ContentValues getContentValues() {
@@ -301,6 +317,8 @@ public class InboundSmsTracker {
            builder.append(") deleteArgs=(").append(Arrays.toString(mDeleteWhereArgs));
            builder.append(')');
        }
        builder.append(" id=");
        builder.append(mMessageId);
        builder.append('}');
        return builder.toString();
    }
@@ -396,6 +414,43 @@ public class InboundSmsTracker {
        return where + " AND (" + whereDestPort + ")";
    }

    private static long createMessageId(Context context, long timestamp, int subId) {
        int slotId = SubscriptionManager.getSlotIndex(subId);
        TelephonyManager telephonyManager =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getImei(slotId);
        if (TextUtils.isEmpty(deviceId)) {
            return 0L;
        }
        String messagePrint = deviceId + timestamp;
        return getShaValue(messagePrint);
    }

    private static long getShaValue(String messagePrint) {
        try {
            return ByteBuffer.wrap(getShaBytes(messagePrint,
                    NUM_OF_BYTES_HASH_VALUE_FOR_MESSAGE_ID)).getLong();
        } catch (final NoSuchAlgorithmException | UnsupportedEncodingException e) {
            Rlog.e("InboundSmsTracker", "Exception while getting SHA value for message",
                    e);
        }
        return 0L;
    }

    private static byte[] getShaBytes(String messagePrint, int maxNumOfBytes)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.reset();
        messageDigest.update(messagePrint.getBytes("UTF-8"));
        byte[] hashResult = messageDigest.digest();
        if (hashResult.length >= maxNumOfBytes) {
            byte[] truncatedHashResult = new byte[maxNumOfBytes];
            System.arraycopy(hashResult, 0, truncatedHashResult, 0, maxNumOfBytes);
            return truncatedHashResult;
        }
        return hashResult;
    }

    /**
     * Sequence numbers for concatenated messages start at 1. The exception is CDMA WAP PDU
     * messages, which use a 0-based index.
@@ -437,4 +492,8 @@ public class InboundSmsTracker {
    public String[] getDeleteWhereArgs() {
        return mDeleteWhereArgs;
    }

    public long getMessageId() {
        return mMessageId;
    }
}
+108 −60

File changed.

Preview size limit exceeded, changes collapsed.

+5 −3
Original line number Diff line number Diff line
@@ -27,12 +27,12 @@ import android.database.SQLException;
import android.os.PersistableBundle;
import android.os.UserManager;
import android.telephony.CarrierConfigManager;
import com.android.telephony.Rlog;
import android.telephony.SubscriptionManager;

import com.android.internal.telephony.cdma.CdmaInboundSmsHandler;
import com.android.internal.telephony.gsm.GsmInboundSmsHandler;
import com.android.internal.telephony.metrics.TelephonyMetrics;
import com.android.telephony.Rlog;

import java.util.HashMap;
import java.util.HashSet;
@@ -188,7 +188,9 @@ public class SmsBroadcastUndelivered {
                InboundSmsTracker tracker;
                try {
                    tracker = TelephonyComponentFactory.getInstance()
                            .inject(InboundSmsTracker.class.getName()).makeInboundSmsTracker(cursor,
                            .inject(InboundSmsTracker.class.getName()).makeInboundSmsTracker(
                                    context,
                                    cursor,
                                    isCurrentFormat3gpp2);
                } catch (IllegalArgumentException e) {
                    Rlog.e(TAG, "error loading SmsTracker: " + e);
Loading