summaryrefslogtreecommitdiffstats
path: root/src/com/android/bluetooth/mapclient/obex/BmessageParser.java
blob: 2705e3429e082d258e0a202b5812ff1c57af90cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.bluetooth.mapclient;

import android.util.Log;

import com.android.bluetooth.mapclient.BmsgTokenizer.Property;
import com.android.vcard.VCardEntry;
import com.android.vcard.VCardEntryConstructor;
import com.android.vcard.VCardEntryHandler;
import com.android.vcard.VCardParser;
import com.android.vcard.VCardParser_V21;
import com.android.vcard.VCardParser_V30;
import com.android.vcard.exception.VCardException;
import com.android.vcard.exception.VCardVersionException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;

/* BMessage as defined by MAP_SPEC_V101 Section 3.1.3 Message format (x-bt/message) */
class BmessageParser {
    private static final String TAG = "BmessageParser";
    private static final boolean DBG = false;

    private static final String CRLF = "\r\n";

    private static final Property BEGIN_BMSG = new Property("BEGIN", "BMSG");
    private static final Property END_BMSG = new Property("END", "BMSG");

    private static final Property BEGIN_VCARD = new Property("BEGIN", "VCARD");
    private static final Property END_VCARD = new Property("END", "VCARD");

    private static final Property BEGIN_BENV = new Property("BEGIN", "BENV");
    private static final Property END_BENV = new Property("END", "BENV");

    private static final Property BEGIN_BBODY = new Property("BEGIN", "BBODY");
    private static final Property END_BBODY = new Property("END", "BBODY");

    private static final Property BEGIN_MSG = new Property("BEGIN", "MSG");
    private static final Property END_MSG = new Property("END", "MSG");

    private static final int CRLF_LEN = 2;

    /*
     * length of "container" for 'message' in bmessage-body-content:
     * BEGIN:MSG<CRLF> + <CRLF> + END:MSG<CRFL>
     */
    private static final int MSG_CONTAINER_LEN = 22;
    private final Bmessage mBmsg;
    private BmsgTokenizer mParser;

    private BmessageParser() {
        mBmsg = new Bmessage();
    }

    public static Bmessage createBmessage(String str) {
        BmessageParser p = new BmessageParser();

        if (DBG) {
            Log.d(TAG, "actual wired contents: " + str);
        }

        try {
            p.parse(str);
        } catch (IOException e) {
            Log.e(TAG, "I/O exception when parsing bMessage", e);
            return null;
        } catch (ParseException e) {
            Log.e(TAG, "Cannot parse bMessage", e);
            return null;
        }

        return p.mBmsg;
    }

    private ParseException expected(Property... props) {
        boolean first = true;
        StringBuilder sb = new StringBuilder();

        for (Property prop : props) {
            if (!first) {
                sb.append(" or ");
            }
            sb.append(prop);
            first = false;
        }

        return new ParseException("Expected: " + sb.toString(), mParser.pos());
    }

    private void parse(String str) throws IOException, ParseException {
        Property prop;

        /*
         * <bmessage-object>::= { "BEGIN:BMSG" <CRLF> <bmessage-property>
         * [<bmessage-originator>]* <bmessage-envelope> "END:BMSG" <CRLF> }
         */
        mParser = new BmsgTokenizer(str + CRLF);

        prop = mParser.next();
        if (!prop.equals(BEGIN_BMSG)) {
            throw expected(BEGIN_BMSG);
        }

        prop = parseProperties();

        while (prop.equals(BEGIN_VCARD)) {
            /* <bmessage-originator>::= <vcard> <CRLF> */

            StringBuilder vcard = new StringBuilder();
            prop = extractVcard(vcard);

            VCardEntry entry = parseVcard(vcard.toString());
            mBmsg.mOriginators.add(entry);
        }

        if (!prop.equals(BEGIN_BENV)) {
            throw expected(BEGIN_BENV);
        }

        prop = parseEnvelope(1);

        if (!prop.equals(END_BMSG)) {
            throw expected(END_BENV);
        }

        /*
         * there should be no meaningful data left in stream here so we just
         * ignore whatever is left
         */
        mParser = null;
    }

    private Property parseProperties() throws ParseException {
        Property prop;
        /*
         * <bmessage-property>::=<bmessage-version-property>
         * <bmessage-readstatus-property> <bmessage-type-property>
         * <bmessage-folder-property> <bmessage-version-property>::="VERSION:"
         * <common-digit>*"."<common-digit>* <CRLF>
         * <bmessage-readstatus-property>::="STATUS:" 'readstatus' <CRLF>
         * <bmessage-type-property>::="TYPE:" 'type' <CRLF>
         * <bmessage-folder-property>::="FOLDER:" 'foldername' <CRLF>
         */
        do {
            prop = mParser.next();

            if (prop.name.equals("VERSION")) {
                mBmsg.mBmsgVersion = prop.value;

            } else if (prop.name.equals("STATUS")) {
                for (Bmessage.Status s : Bmessage.Status.values()) {
                    if (prop.value.equals(s.toString())) {
                        mBmsg.mBmsgStatus = s;
                        break;
                    }
                }

            } else if (prop.name.equals("TYPE")) {
                for (Bmessage.Type t : Bmessage.Type.values()) {
                    if (prop.value.equals(t.toString())) {
                        mBmsg.mBmsgType = t;
                        break;
                    }
                }

            } else if (prop.name.equals("FOLDER")) {
                mBmsg.mBmsgFolder = prop.value;

            }

        } while (!prop.equals(BEGIN_VCARD) && !prop.equals(BEGIN_BENV));

        return prop;
    }

    private Property parseEnvelope(int level) throws IOException, ParseException {
        Property prop;

        /*
         * we can support as many nesting level as we want, but MAP spec clearly
         * defines that there should be no more than 3 levels. so we verify it
         * here.
         */

        if (level > 3) {
            throw new ParseException("bEnvelope is nested more than 3 times", mParser.pos());
        }

        /*
         * <bmessage-envelope> ::= { "BEGIN:BENV" <CRLF> [<bmessage-recipient>]*
         * <bmessage-envelope> | <bmessage-content> "END:BENV" <CRLF> }
         */

        prop = mParser.next();

        while (prop.equals(BEGIN_VCARD)) {

            /* <bmessage-originator>::= <vcard> <CRLF> */

            StringBuilder vcard = new StringBuilder();
            prop = extractVcard(vcard);

            if (level == 1) {
                VCardEntry entry = parseVcard(vcard.toString());
                mBmsg.mRecipients.add(entry);
            }
        }

        if (prop.equals(BEGIN_BENV)) {
            prop = parseEnvelope(level + 1);

        } else if (prop.equals(BEGIN_BBODY)) {
            prop = parseBody();

        } else {
            throw expected(BEGIN_BENV, BEGIN_BBODY);
        }

        if (!prop.equals(END_BENV)) {
            throw expected(END_BENV);
        }

        return mParser.next();
    }

    private Property parseBody() throws IOException, ParseException {
        Property prop;

        /*
         * <bmessage-content>::= { "BEGIN:BBODY"<CRLF> [<bmessage-body-part-ID>
         * <CRLF>] <bmessage-body-property> <bmessage-body-content>* <CRLF>
         * "END:BBODY"<CRLF> } <bmessage-body-part-ID>::="PARTID:" 'Part-ID'
         * <bmessage-body-property>::=[<bmessage-body-encoding-property>]
         * [<bmessage-body-charset-property>]
         * [<bmessage-body-language-property>]
         * <bmessage-body-content-length-property>
         * <bmessage-body-encoding-property>::="ENCODING:"'encoding' <CRLF>
         * <bmessage-body-charset-property>::="CHARSET:"'charset' <CRLF>
         * <bmessage-body-language-property>::="LANGUAGE:"'language' <CRLF>
         * <bmessage-body-content-length-property>::= "LENGTH:" <common-digit>*
         * <CRLF>
         */

        do {
            prop = mParser.next();

            if (prop.name.equals("PARTID")) {
                // Do nothing
            } else if (prop.name.equals("ENCODING")) {
                mBmsg.mBbodyEncoding = prop.value;

            } else if (prop.name.equals("CHARSET")) {
                mBmsg.mBbodyCharset = prop.value;

            } else if (prop.name.equals("LANGUAGE")) {
                mBmsg.mBbodyLanguage = prop.value;

            } else if (prop.name.equals("LENGTH")) {
                try {
                    mBmsg.mBbodyLength = Integer.parseInt(prop.value);
                } catch (NumberFormatException e) {
                    throw new ParseException("Invalid LENGTH value", mParser.pos());
                }

            }

        } while (!prop.equals(BEGIN_MSG));

        /*
         * check that the charset is always set to UTF-8. We expect only text transfer (in lieu with
         * the MAPv12 specifying only RFC2822 (text only) for MMS/EMAIL and SMS do not support
         * non-text content. If the charset is not set to UTF-8, it is safe to set the message as
         * empty. We force the getMessage (see Client) to only call getMessage with
         * UTF-8 as the MCE is not obliged to support native charset.
         */
        if (!"UTF-8".equals(mBmsg.mBbodyCharset)) {
            Log.e(TAG, "The charset was not set to charset UTF-8: " + mBmsg.mBbodyCharset);
        }

        /*
         * <bmessage-body-content>::={ "BEGIN:MSG"<CRLF> 'message'<CRLF>
         * "END:MSG"<CRLF> }
         */

        int messageLen = mBmsg.mBbodyLength - MSG_CONTAINER_LEN;
        int offset = messageLen + CRLF_LEN;
        int restartPos = mParser.pos() + offset;
        /*
         * length is specified in bytes so we need to convert from unicode
         * string back to bytes array
         */
        String remng = mParser.remaining();
        byte[] data = remng.getBytes();

        /* restart parsing from after 'message'<CRLF> */
        mParser = new BmsgTokenizer(new String(data, offset, data.length - offset), restartPos);

        prop = mParser.next(true);

        if (prop != null) {
            if (prop.equals(END_MSG)) {
                if ("UTF-8".equals(mBmsg.mBbodyCharset)) {
                    mBmsg.mMessage = new String(data, 0, messageLen, StandardCharsets.UTF_8);
                } else {
                    mBmsg.mMessage = null;
                }
            } else {
                /* Handle possible exception for incorrect LENGTH value
                 * from MSE while parsing  GET Message response */
                Log.e(TAG, "Prop Invalid: " + prop.toString());
                Log.e(TAG, "Possible Invalid LENGTH value");
                throw expected(END_MSG);
            }
        } else {
            data = null;

            /*
             * now we check if bMessage can be parsed if LENGTH is handled as
             * number of characters instead of number of bytes
             */
            if (offset < 0 || offset > remng.length()) {
                /* Handle possible exception for incorrect LENGTH value
                 * from MSE while parsing  GET Message response */
                throw new ParseException("Invalid LENGTH value", mParser.pos());
            }

            Log.w(TAG, "byte LENGTH seems to be invalid, trying with char length");

            mParser = new BmsgTokenizer(remng.substring(offset));

            prop = mParser.next();

            if (!prop.equals(END_MSG)) {
                throw expected(END_MSG);
            }

            if ("UTF-8".equals(mBmsg.mBbodyCharset)) {
                mBmsg.mMessage = remng.substring(0, messageLen);
            } else {
                mBmsg.mMessage = null;
            }
        }

        prop = mParser.next();

        if (!prop.equals(END_BBODY)) {
            throw expected(END_BBODY);
        }

        return mParser.next();
    }

    private Property extractVcard(StringBuilder out) throws IOException, ParseException {
        Property prop;

        out.append(BEGIN_VCARD).append(CRLF);

        do {
            prop = mParser.next();
            out.append(prop).append(CRLF);
        } while (!prop.equals(END_VCARD));

        return mParser.next();
    }

    private VCardEntry parseVcard(String str) throws IOException, ParseException {
        VCardEntry vcard = null;

        try {
            VCardParser p = new VCardParser_V21();
            VCardEntryConstructor c = new VCardEntryConstructor();
            VcardHandler handler = new VcardHandler();
            c.addEntryHandler(handler);
            p.addInterpreter(c);
            p.parse(new ByteArrayInputStream(str.getBytes()));

            vcard = handler.vcard;

        } catch (VCardVersionException e1) {
            try {
                VCardParser p = new VCardParser_V30();
                VCardEntryConstructor c = new VCardEntryConstructor();
                VcardHandler handler = new VcardHandler();
                c.addEntryHandler(handler);
                p.addInterpreter(c);
                p.parse(new ByteArrayInputStream(str.getBytes()));

                vcard = handler.vcard;

            } catch (VCardVersionException e2) {
                // will throw below
            } catch (VCardException e2) {
                // will throw below
            }

        } catch (VCardException e1) {
            // will throw below
        }

        if (vcard == null) {
            throw new ParseException("Cannot parse vCard object (neither 2.1 nor 3.0?)",
                    mParser.pos());
        }

        return vcard;
    }

    private class VcardHandler implements VCardEntryHandler {
        public VCardEntry vcard;

        @Override
        public void onStart() {
        }

        @Override
        public void onEntryCreated(VCardEntry entry) {
            vcard = entry;
        }

        @Override
        public void onEnd() {
        }
    }
}