BluetoothMapSmsPdu.java revision fd6603b8bf9ed72dcc8bd59aaef3209251b6e17c
1/*
2* Copyright (C) 2013 Samsung System LSI
3* Licensed under the Apache License, Version 2.0 (the "License");
4* you may not use this file except in compliance with the License.
5* You may obtain a copy of the License at
6*
7*      http://www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14*/
15package com.android.bluetooth.map;
16
17import static android.telephony.TelephonyManager.PHONE_TYPE_CDMA;
18import static com.android.internal.telephony.SmsConstants.ENCODING_7BIT;
19
20import java.io.ByteArrayInputStream;
21import java.io.ByteArrayOutputStream;
22import java.io.DataInputStream;
23import java.io.EOFException;
24import java.io.IOException;
25import java.io.UnsupportedEncodingException;
26import java.text.SimpleDateFormat;
27import java.util.ArrayList;
28import java.util.Calendar;
29import java.util.Date;
30import java.util.Random;
31
32import android.telephony.PhoneNumberUtils;
33import android.telephony.SmsMessage;
34import android.telephony.TelephonyManager;
35import android.util.Log;
36
37import com.android.internal.telephony.*;
38/*import com.android.internal.telephony.GsmAlphabet.TextEncodingDetails;
39import com.android.internal.telephony.SmsConstants;*/
40import com.android.internal.telephony.SmsHeader;
41import com.android.internal.telephony.SmsMessageBase;
42import com.android.internal.telephony.SmsMessageBase.SubmitPduBase;
43import com.android.internal.telephony.cdma.sms.*;
44import com.android.internal.telephony.gsm.SmsMessage.SubmitPdu;
45
46public class BluetoothMapSmsPdu {
47
48    private static final String TAG = "BluetoothMapSmsPdu";
49    private static final boolean V = true;
50    private static int INVALID_VALUE = -1;
51    public static int SMS_TYPE_GSM = 1;
52    public static int SMS_TYPE_CDMA = 2;
53
54
55    /* TODO: We need to handle the SC-address mentioned in errata 4335.
56     * Since the definition could be read in three different ways, I have asked
57     * the car working group for clarification, and are awaiting confirmation that
58     * this clarification will go into the MAP spec:
59     *  "The native format should be <sc_addr><tpdu> where <sc_addr> is <length><ton><1..10 octet of address>
60     *   coded according to 24.011. The IEI is not to be used, as the fixed order of the data makes a type 4 LV
61     *   information element sufficient. <length> is a single octet which value is the length of the value-field
62     *   in octets including both the <ton> and the <address>."
63     * */
64
65
66    public static class SmsPdu {
67        private byte[] data;
68        private byte[] scAddress = {0}; // At the moment we do not use the scAddress, hence set the length to 0.
69        private int userDataMsgOffset = 0;
70        private int encoding;
71        private int languageTable;
72        private int languageShiftTable;
73        private int type;
74
75        /* Members used for pdu decoding */
76        private int userDataSeptetPadding = INVALID_VALUE;
77        private int msgSeptetCount = 0;
78
79        SmsPdu(byte[] data, int type){
80            this.data = data;
81            this.encoding = INVALID_VALUE;
82            this.type = type;
83            this.languageTable = INVALID_VALUE;
84            this.languageShiftTable = INVALID_VALUE;
85            this.userDataMsgOffset = gsmSubmitGetTpUdOffset(); // Assume no user data header
86        }
87
88        /**
89         * Create a pdu instance based on the data generated on this device.
90         * @param data
91         * @param encoding
92         * @param type
93         * @param languageTable
94         */
95        SmsPdu(byte[]data, int encoding, int type, int languageTable){
96            this.data = data;
97            this.encoding = encoding;
98            this.type = type;
99            this.languageTable = languageTable;
100        }
101        public byte[] getData(){
102            return data;
103        }
104        public byte[] getScAddress(){
105            return scAddress;
106        }
107        public void setEncoding(int encoding) {
108            this.encoding = encoding;
109        }
110        public int getEncoding(){
111            return encoding;
112        }
113        public int getType(){
114            return type;
115        }
116        public int getUserDataMsgOffset() {
117            return userDataMsgOffset;
118        }
119        /** The user data message payload size in bytes - excluding the user data header. */
120        public int getUserDataMsgSize() {
121            return data.length - userDataMsgOffset;
122        }
123
124        public int getLanguageShiftTable() {
125            return languageShiftTable;
126        }
127
128        public int getLanguageTable() {
129            return languageTable;
130        }
131
132        public int getUserDataSeptetPadding() {
133            return userDataSeptetPadding;
134        }
135
136        public int getMsgSeptetCount() {
137            return msgSeptetCount;
138        }
139
140
141        /* PDU parsing/modification functionality */
142        private final static byte TELESERVICE_IDENTIFIER                    = 0x00;
143        private final static byte SERVICE_CATEGORY                          = 0x01;
144        private final static byte ORIGINATING_ADDRESS                       = 0x02;
145        private final static byte ORIGINATING_SUB_ADDRESS                   = 0x03;
146        private final static byte DESTINATION_ADDRESS                       = 0x04;
147        private final static byte DESTINATION_SUB_ADDRESS                   = 0x05;
148        private final static byte BEARER_REPLY_OPTION                       = 0x06;
149        private final static byte CAUSE_CODES                               = 0x07;
150        private final static byte BEARER_DATA                               = 0x08;
151
152        /**
153         * Find and return the offset to the specified parameter ID
154         * @param parameterId The parameter ID to find
155         * @return the offset in number of bytes to the parameterID entry in the pdu data.
156         * The byte at the offset contains the parameter ID, the byte following contains the
157         * parameter length, and offset + 2 is the first byte of the parameter data.
158         */
159        private int cdmaGetParameterOffset(byte parameterId) {
160            ByteArrayInputStream pdu = new ByteArrayInputStream(data);
161            int offset = 0;
162            boolean found = false;
163
164            try {
165                pdu.skip(1); // Skip the message type
166
167                while (pdu.available() > 0) {
168                    int currentId = pdu.read();
169                    int currentLen = pdu.read();
170
171                    if(currentId == parameterId) {
172                        found = true;
173                        break;
174                    }
175                    else {
176                        pdu.skip(currentLen);
177                        offset += 2 + currentLen;
178                    }
179                }
180                pdu.close();
181            } catch (Exception e) {
182                Log.e(TAG, "cdmaGetParameterOffset: ", e);
183            }
184
185            if(found)
186                return offset;
187            else
188                return 0;
189        }
190
191        private final static byte BEARER_DATA_MSG_ID = 0x00;
192
193        private int cdmaGetSubParameterOffset(byte subParameterId) {
194            ByteArrayInputStream pdu = new ByteArrayInputStream(data);
195            int offset = 0;
196            boolean found = false;
197            offset = cdmaGetParameterOffset(BEARER_DATA) + 2; // Add to offset the BEARER_DATA parameter id and length bytes
198            pdu.skip(offset);
199            try {
200
201                while (pdu.available() > 0) {
202                    int currentId = pdu.read();
203                    int currentLen = pdu.read();
204
205                    if(currentId == subParameterId) {
206                        found = true;
207                        break;
208                    }
209                    else {
210                        pdu.skip(currentLen);
211                        offset += 2 + currentLen;
212                    }
213                }
214                pdu.close();
215            } catch (Exception e) {
216                Log.e(TAG, "cdmaGetParameterOffset: ", e);
217            }
218
219            if(found)
220                return offset;
221            else
222                return 0;
223        }
224
225
226        public void cdmaChangeToDeliverPdu(long date){
227            /* Things to change:
228             *  - Message Type in bearer data (Not the overall point-to-point type)
229             *  - Change address ID from destination to originating (sub addresses are not used)
230             *  - A time stamp is not mandatory.
231             */
232            int offset;
233            offset = cdmaGetParameterOffset(DESTINATION_ADDRESS);
234            data[offset] = ORIGINATING_ADDRESS;
235            offset = cdmaGetParameterOffset(DESTINATION_SUB_ADDRESS);
236            data[offset] = ORIGINATING_SUB_ADDRESS;
237
238            offset = cdmaGetSubParameterOffset(BEARER_DATA_MSG_ID);
239
240//            if(data != null && data.length > 2) {
241                int tmp = data[offset+2] & 0xff; // Skip the subParam ID and length, and read the first byte.
242                // Mask out the type
243                tmp &= 0x0f;
244                // Set the new type
245                tmp |= ((BearerData.MESSAGE_TYPE_DELIVER << 4) & 0xf0);
246                // Store the result
247                data[offset+2] = (byte) tmp;
248
249//            }
250                //TODO: Error handling.
251                /* TODO: Do we need to change anything in the user data? Not sure if the user data is
252                 *        just encoded using GSM encoding, or it is an actual GSM submit PDU embedded
253                 *        in the user data?
254                 */
255
256        }
257
258        private static final byte TP_MIT_DELIVER       = 0x00; // bit 0 and 1
259        private static final byte TP_MMS_NO_MORE       = 0x04; // bit 2
260        private static final byte TP_RP_NO_REPLY_PATH  = 0x00; // bit 7
261        private static final byte TP_UDHI_MASK         = 0x20; // bit 6
262        private static final byte TP_SRI_NO_REPORT     = 0x00; // bit 5
263
264        private int gsmSubmitGetTpPidOffset() {
265            /* calculate the offset to TP_PID and return the TP_PID byte.
266             * The TP-DA has variable length, and the length excludes the 2 byte length and type headers.
267             * The TP-DA is two bytes within the PDU */
268            int offset = 2 + (data[2] & 0xff) + 2; //
269            if((offset > data.length) || (offset > (2 + 12))) // max length of TP_DA is 12 bytes + two byte offset
270                throw new IllegalArgumentException("wrongly formatted gsm submit PDU");
271            return offset;
272        }
273
274        public int gsmSubmitGetTpDcs() {
275            return data[gsmSubmitGetTpDcsOffset()] & 0xff;
276        }
277
278        public boolean gsmSubmitHasUserDataHeader() {
279            return ((data[0] & 0xff) & TP_UDHI_MASK) == TP_UDHI_MASK;
280        }
281
282        private int gsmSubmitGetTpDcsOffset() {
283            return gsmSubmitGetTpPidOffset() + 1;
284        }
285
286        private int gsmSubmitGetTpUdlOffset() {
287            switch(((data[0]  & 0xff) & (0x08 | 0x04))>>2) {
288            case 0: // Not TP-VP present
289                return gsmSubmitGetTpPidOffset() + 2;
290            case 1: // TP-VP relative format
291                return gsmSubmitGetTpPidOffset() + 2 + 1;
292            case 2: // TP-VP enhanced format
293            case 3: // TP-VP absolute format
294                break;
295            }
296            return gsmSubmitGetTpPidOffset() + 2 + 7;
297        }
298        private int gsmSubmitGetTpUdOffset() {
299            return gsmSubmitGetTpUdlOffset() + 1;
300        }
301
302        public void gsmDecodeUserDataHeader() {
303            ByteArrayInputStream pdu = new ByteArrayInputStream(data);
304
305            pdu.skip(gsmSubmitGetTpUdlOffset());
306            int userDataLength = pdu.read();
307            int userDataHeaderLength = pdu.read();
308
309            // This part is only needed to extract the language info, hence only needed for 7 bit encoding
310            if(encoding == SmsConstants.ENCODING_7BIT)
311            {
312                byte[] udh = new byte[userDataHeaderLength];
313                try {
314                    pdu.read(udh);
315                } catch (IOException e) {
316                    Log.w(TAG, "unable to read userDataHeader", e);
317                }
318                SmsHeader userDataHeader = SmsHeader.fromByteArray(udh);
319                languageTable = userDataHeader.languageTable;
320                languageShiftTable = userDataHeader.languageShiftTable;
321
322                int headerBits = (userDataHeaderLength + 1) * 8;
323                int headerSeptets = headerBits / 7;
324                headerSeptets += (headerBits % 7) > 0 ? 1 : 0;
325                userDataSeptetPadding = (headerSeptets * 7) - headerBits;
326                msgSeptetCount = userDataLength - headerSeptets;
327            }
328            userDataMsgOffset = gsmSubmitGetTpUdOffset() + userDataHeaderLength + 1; // Add the byte containing the length
329        }
330
331        private void gsmWriteDate(ByteArrayOutputStream header, long time) throws UnsupportedEncodingException {
332            SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
333            Date date = new Date(time);
334            String timeStr = format.format(date); // Format to YYMMDDTHHMMSS UTC time
335            byte[] timeChars = timeStr.getBytes("US-ASCII");
336
337            for(int i = 0, n = timeStr.length()/2; i < n; i++) {
338                header.write((timeChars[i+1]-0x30) << 4 | (timeChars[i]-0x30)); // Offset from ascii char to decimal value
339            }
340
341            Calendar cal = Calendar.getInstance();
342            int offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (15 * 60 * 1000); /* offset in quarters of an hour */
343            String offsetString;
344            if(offset < 0) {
345                offsetString = String.format("%1$02d", -(offset));
346                char[] offsetChars = offsetString.toCharArray();
347                header.write((offsetChars[1]-0x30) << 4 | 0x40 | (offsetChars[0]-0x30));
348            }
349            else {
350                offsetString = String.format("%1$02d", offset);
351                char[] offsetChars = offsetString.toCharArray();
352                header.write((offsetChars[1]-0x30) << 4 | (offsetChars[0]-0x30));
353            }
354        }
355
356/*        private void gsmSubmitExtractUserData() {
357            int userDataLength = data[gsmSubmitGetTpUdlOffset()];
358            userData = new byte[userDataLength];
359            System.arraycopy(userData, 0, data, gsmSubmitGetTpUdOffset(), userDataLength);
360
361        }*/
362
363        /**
364         * Change the GSM Submit Pdu data in this object to a deliver PDU:
365         *  - Build the new header with deliver PDU type, originator and time stamp.
366         *  - Extract encoding details from the submit PDU
367         *  - Extract user data length and user data from the submitPdu
368         *  - Build the new PDU
369         * @param date the time stamp to include (The value is the number of milliseconds since Jan. 1, 1970 GMT.)
370         * @param originator the phone number to include in the deliver PDU header. Any undesired characters,
371         *                    such as '-' will be striped from this string.
372         */
373        public void gsmChangeToDeliverPdu(long date, String originator)
374        {
375            ByteArrayOutputStream newPdu = new ByteArrayOutputStream(22); // 22 is the max length of the deliver pdu header
376            byte[] encodedAddress;
377            int userDataLength = 0;
378            try {
379                newPdu.write(TP_MIT_DELIVER | TP_MMS_NO_MORE | TP_RP_NO_REPLY_PATH | TP_SRI_NO_REPORT
380                             | (data[0] & 0xff)  & TP_UDHI_MASK);
381                encodedAddress = PhoneNumberUtils.networkPortionToCalledPartyBCDWithLength(originator);
382                // Insert originator address into the header - this includes the length
383                newPdu.write(encodedAddress);
384                newPdu.write(data[gsmSubmitGetTpPidOffset()]);
385                newPdu.write(data[gsmSubmitGetTpDcsOffset()]);
386                // Generate service center time stamp
387                gsmWriteDate(newPdu, date);
388                userDataLength = (data[gsmSubmitGetTpUdlOffset()] & 0xff);
389                newPdu.write(userDataLength);
390                // Copy the pdu user data - keep in mind that the userDataLength is not the length in bytes for 7-bit encoding.
391                newPdu.write(data, gsmSubmitGetTpUdOffset(), data.length - gsmSubmitGetTpUdOffset());
392            } catch (IOException e) {
393                Log.e(TAG, "", e);
394                throw new IllegalArgumentException("Failed to change type to deliver PDU."); // TODO: Is this the best way to handle this error? - which cannot occur...
395            }
396            data = newPdu.toByteArray();
397        }
398
399        /* SMS encoding to bmessage strings */
400        /** get the encoding type as a bMessage string */
401        public String getEncodingString(){
402            if(type == SMS_TYPE_GSM)
403            {
404                switch(encoding){
405                case SmsMessage.ENCODING_7BIT:
406                    if(languageTable == 0)
407                        return "G-7BIT";
408                    else
409                        return "G-7BITEXT";
410                case SmsMessage.ENCODING_8BIT:
411                    return "G-8BIT";
412                case SmsMessage.ENCODING_16BIT:
413                    return "G-16BIT";
414                case SmsMessage.ENCODING_UNKNOWN:
415                    default:
416                    return "";
417                }
418            } else /* SMS_TYPE_CDMA */ {
419                switch(encoding){
420                case SmsMessage.ENCODING_7BIT:
421                    return "C-7ASCII";
422                case SmsMessage.ENCODING_8BIT:
423                    return "C-8BIT";
424                case SmsMessage.ENCODING_16BIT:
425                    return "C-UNICODE";
426                case SmsMessage.ENCODING_KSC5601:
427                    return "C-KOREAN";
428                case SmsMessage.ENCODING_UNKNOWN:
429                    default:
430                    return "";
431                }
432            }
433        }
434    }
435
436    private static int sConcatenatedRef = new Random().nextInt(256);
437
438    protected static int getNextConcatenatedRef() {
439        sConcatenatedRef += 1;
440        return sConcatenatedRef;
441    }
442    public static ArrayList<SmsPdu> getSubmitPdus(String messageText, String address){
443        /* Use the generic GSM/CDMA SMS Message functionality within Android to generate the
444         * SMS PDU's as once generated to send the SMS message.
445         */
446
447        int activePhone = TelephonyManager.getDefault().getCurrentPhoneType(); // TODO: Change to use: ((TelephonyManager)myContext.getSystemService(Context.TELEPHONY_SERVICE))
448        int phoneType;
449        GsmAlphabet.TextEncodingDetails ted = (PHONE_TYPE_CDMA == activePhone) ?
450            com.android.internal.telephony.cdma.SmsMessage.calculateLength((CharSequence)messageText, false) :
451            com.android.internal.telephony.gsm.SmsMessage.calculateLength((CharSequence)messageText, false);
452
453        SmsPdu newPdu;
454        String destinationAddress;
455        int msgCount = ted.msgCount;
456        int encoding;
457        int languageTable;
458        int languageShiftTable;
459        int refNumber = getNextConcatenatedRef() & 0x00FF;
460        ArrayList<String> smsFragments = SmsMessage.fragmentText(messageText);
461        ArrayList<SmsPdu> pdus = new ArrayList<SmsPdu>(msgCount);
462        byte[] data;
463
464        // Default to GSM, as this code should not be used, if we neither have CDMA not GSM.
465        phoneType = (activePhone == PHONE_TYPE_CDMA) ? SMS_TYPE_CDMA : SMS_TYPE_GSM;
466        encoding = ted.codeUnitSize;
467        languageTable = ted.languageTable;
468        languageShiftTable = ted.languageShiftTable;
469        destinationAddress = PhoneNumberUtils.stripSeparators(address);
470        if(destinationAddress == null || destinationAddress.length() < 2) {
471            destinationAddress = "12"; // Ensure we add a number at least 2 digits as specified in the GSM spec.
472        }
473
474        if(msgCount == 1){
475            data = SmsMessage.getSubmitPdu(null, destinationAddress, smsFragments.get(0), false).encodedMessage;
476            newPdu = new SmsPdu(data, encoding, phoneType, languageTable);
477            pdus.add(newPdu);
478        }
479
480        /* This code is a reduced copy of the actual code used in the Android SMS sub system,
481         * hence the comments have been left untouched. */
482        for(int i = 0; i < msgCount; i++){
483            SmsHeader.ConcatRef concatRef = new SmsHeader.ConcatRef();
484            concatRef.refNumber = refNumber;
485            concatRef.seqNumber = i + 1;  // 1-based sequence
486            concatRef.msgCount = msgCount;
487            // TODO: We currently set this to true since our messaging app will never
488            // send more than 255 parts (it converts the message to MMS well before that).
489            // However, we should support 3rd party messaging apps that might need 16-bit
490            // references
491            // Note:  It's not sufficient to just flip this bit to true; it will have
492            // ripple effects (several calculations assume 8-bit ref).
493            concatRef.isEightBits = true;
494            SmsHeader smsHeader = new SmsHeader();
495            smsHeader.concatRef = concatRef;
496
497            /* Depending on the type, call either GSM or CDMA getSubmitPdu(). The encoding
498             * will be determined(again) by getSubmitPdu().
499             * All packets need to be encoded using the same encoding, as the bMessage
500             * only have one filed to describe the encoding for all messages in a concatenated
501             * SMS... */
502            if (encoding == SmsConstants.ENCODING_7BIT) {
503                smsHeader.languageTable = languageTable;
504                smsHeader.languageShiftTable = languageShiftTable;
505            }
506
507            if(phoneType == SMS_TYPE_GSM){
508                data = com.android.internal.telephony.gsm.SmsMessage.getSubmitPdu(null, destinationAddress,
509                        smsFragments.get(i), false, SmsHeader.toByteArray(smsHeader),
510                        encoding, languageTable, languageShiftTable).encodedMessage;
511            } else { // SMS_TYPE_CDMA
512                UserData uData = new UserData();
513                uData.payloadStr = smsFragments.get(i);
514                uData.userDataHeader = smsHeader;
515                if (encoding == SmsConstants.ENCODING_7BIT) {
516                    uData.msgEncoding = UserData.ENCODING_GSM_7BIT_ALPHABET;
517                } else { // assume UTF-16
518                    uData.msgEncoding = UserData.ENCODING_UNICODE_16;
519                }
520                uData.msgEncodingSet = true;
521                data = com.android.internal.telephony.cdma.SmsMessage.getSubmitPdu(destinationAddress,
522                        uData, false).encodedMessage;
523            }
524            newPdu = new SmsPdu(data, encoding, phoneType, languageTable);
525            pdus.add(newPdu);
526        }
527
528        return pdus;
529    }
530
531    /**
532     * Generate a list of deliver PDUs. The messageText and address parameters must be different from null,
533     * for CDMA the date can be omitted (and will be ignored if supplied)
534     * @param messageText The text to include.
535     * @param address The originator address.
536     * @param date The delivery time stamp.
537     * @return
538     */
539    public static ArrayList<SmsPdu> getDeliverPdus(String messageText, String address, long date){
540        ArrayList<SmsPdu> deliverPdus = getSubmitPdus(messageText, address);
541
542        /*
543         * For CDMA the only difference between deliver and submit pdus are the messageType,
544         * which is set in encodeMessageId, (the higher 4 bits of the 1st byte
545         * of the Message identification sub parameter data.) and the address type.
546         *
547         * For GSM, a larger part of the header needs to be generated.
548         */
549        for(SmsPdu currentPdu : deliverPdus){
550            if(currentPdu.getType() == SMS_TYPE_CDMA){
551                currentPdu.cdmaChangeToDeliverPdu(date);
552            } else { /* SMS_TYPE_GSM */
553                currentPdu.gsmChangeToDeliverPdu(date, address);
554            }
555        }
556
557        return deliverPdus;
558    }
559
560    public static void testSendRawPdu(SmsPdu pdu){
561        if(pdu.getType() == SMS_TYPE_CDMA){
562            /* TODO: Try to send the message using SmsManager.sendData()?*/
563        }else {
564
565        }
566    }
567
568    /**
569     * The decoding only supports decoding the actual textual content of the PDU received
570     * from the MAP client. (As the Android system has no interface to send pre encoded PDUs)
571     * The destination address must be extracted from the bmessage vCard(s).
572     */
573    public static String decodePdu(byte[] data, int type) {
574        String ret;
575        if(type == SMS_TYPE_CDMA) {
576            /* This is able to handle both submit and deliver PDUs */
577            ret = com.android.internal.telephony.cdma.SmsMessage.createFromEfRecord(0, data).getMessageBody();
578        } else {
579            /* For GSM, there is no submit pdu decoder, and most parser utils are private, and only minded for submit pdus */
580            ret = gsmParseSubmitPdu(data);
581        }
582        return ret;
583    }
584
585    /* At the moment we do not support using a SC-address. Use this function to strip off
586     * the SC-address before parsing it to the SmsPdu. (this was added in errata 4335)
587     */
588    private static byte[] gsmStripOffScAddress(byte[] data) {
589        /* The format of a native GSM SMS is: <sc-address><pdu> where sc-address is:
590         * <length-byte><type-byte><number-bytes> */
591        int addressLength = data[0] & 0xff; // Treat the byte value as an unsigned value
592        if(addressLength >= data.length) // TODO: We could verify that the address-length is no longer than 11 bytes
593            throw new IllegalArgumentException("Length of address exeeds the length of the PDU data.");
594        int pduLength = data.length-(1+addressLength);
595        byte[] newData = new byte[pduLength];
596        System.arraycopy(data, 1+addressLength, newData, 0, pduLength);
597        return newData;
598    }
599
600    private static String gsmParseSubmitPdu(byte[] data) {
601        /* Things to do:
602         *  - extract hasUsrData bit
603         *  - extract TP-DCS -> Character set, compressed etc.
604         *  - extract user data header to get the language properties
605         *  - extract user data
606         *  - decode the string */
607        //Strip off the SC-address before parsing
608        SmsPdu pdu = new SmsPdu(gsmStripOffScAddress(data), SMS_TYPE_GSM);
609        boolean userDataCompressed = false;
610        int dataCodingScheme = pdu.gsmSubmitGetTpDcs();
611        int encodingType =  SmsConstants.ENCODING_UNKNOWN;
612        String messageBody = null;
613
614        // Look up the data encoding scheme
615        if ((dataCodingScheme & 0x80) == 0) {
616            // Bits 7..4 == 0xxx
617            userDataCompressed = (0 != (dataCodingScheme & 0x20));
618
619            if (userDataCompressed) {
620                Log.w(TAG, "4 - Unsupported SMS data coding scheme "
621                        + "(compression) " + (dataCodingScheme & 0xff));
622            } else {
623                switch ((dataCodingScheme >> 2) & 0x3) {
624                case 0: // GSM 7 bit default alphabet
625                    encodingType =  SmsConstants.ENCODING_7BIT;
626                    break;
627
628                case 2: // UCS 2 (16bit)
629                    encodingType =  SmsConstants.ENCODING_16BIT;
630                    break;
631
632                case 1: // 8 bit data
633                case 3: // reserved
634                    Log.w(TAG, "1 - Unsupported SMS data coding scheme "
635                            + (dataCodingScheme & 0xff));
636                    encodingType =  SmsConstants.ENCODING_8BIT;
637                    break;
638                }
639            }
640        } else if ((dataCodingScheme & 0xf0) == 0xf0) {
641            userDataCompressed = false;
642
643            if (0 == (dataCodingScheme & 0x04)) {
644                // GSM 7 bit default alphabet
645                encodingType =  SmsConstants.ENCODING_7BIT;
646            } else {
647                // 8 bit data
648                encodingType =  SmsConstants.ENCODING_8BIT;
649            }
650        } else if ((dataCodingScheme & 0xF0) == 0xC0
651                || (dataCodingScheme & 0xF0) == 0xD0
652                || (dataCodingScheme & 0xF0) == 0xE0) {
653            // 3GPP TS 23.038 V7.0.0 (2006-03) section 4
654
655            // 0xC0 == 7 bit, don't store
656            // 0xD0 == 7 bit, store
657            // 0xE0 == UCS-2, store
658
659            if ((dataCodingScheme & 0xF0) == 0xE0) {
660                encodingType =  SmsConstants.ENCODING_16BIT;
661            } else {
662                encodingType =  SmsConstants.ENCODING_7BIT;
663            }
664
665            userDataCompressed = false;
666
667            // bit 0x04 reserved
668        } else if ((dataCodingScheme & 0xC0) == 0x80) {
669            // 3GPP TS 23.038 V7.0.0 (2006-03) section 4
670            // 0x80..0xBF == Reserved coding groups
671            if (dataCodingScheme == 0x84) {
672                // This value used for KSC5601 by carriers in Korea.
673                encodingType =  SmsConstants.ENCODING_KSC5601;
674            } else {
675                Log.w(TAG, "5 - Unsupported SMS data coding scheme "
676                        + (dataCodingScheme & 0xff));
677            }
678        } else {
679            Log.w(TAG, "3 - Unsupported SMS data coding scheme "
680                    + (dataCodingScheme & 0xff));
681        }
682
683        /* TODO: This is NOT good design - to have the pdu class being depending on these two function calls.
684         *        - move the encoding extraction into the pdu class */
685        pdu.setEncoding(encodingType);
686        if(pdu.gsmSubmitHasUserDataHeader()) {
687            pdu.gsmDecodeUserDataHeader();
688        }
689
690        try {
691            switch (encodingType) {
692            case  SmsConstants.ENCODING_UNKNOWN:
693            case  SmsConstants.ENCODING_8BIT:
694                messageBody = null;
695                break;
696
697            case  SmsConstants.ENCODING_7BIT:
698                messageBody = GsmAlphabet.gsm7BitPackedToString(pdu.getData(), pdu.getUserDataMsgOffset(),
699                                pdu.getMsgSeptetCount(), pdu.getUserDataSeptetPadding(), pdu.getLanguageTable(),
700                                pdu.getLanguageShiftTable());
701
702                break;
703
704            case  SmsConstants.ENCODING_16BIT:
705                messageBody = new String(pdu.getData(), pdu.getUserDataMsgOffset(), pdu.getUserDataMsgSize(), "utf-16");
706                break;
707
708            case SmsConstants.ENCODING_KSC5601:
709                messageBody = new String(pdu.getData(), pdu.getUserDataMsgOffset(), pdu.getUserDataMsgSize(), "KSC5601");
710
711                break;
712            }
713        } catch (UnsupportedEncodingException e) {
714            Log.e(TAG, "Unsupported encoding type???", e); // This should never happen.
715            return null;
716        }
717
718        return messageBody;
719    }
720
721}
722