summaryrefslogtreecommitdiff
path: root/src/mm-sms-part-cdma.c
blob: 6e3f1179548ea68d61ca44cce6018e061c9cc6ae (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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details:
 *
 * Copyright (C) 2013 Google, Inc.
 */

#include <ctype.h>
#include <string.h>

#include <glib.h>

#include <ModemManager.h>
#define _LIBMM_INSIDE_MM
#include <libmm-glib.h>

#include "mm-charsets.h"
#include "mm-sms-part-cdma.h"
#include "mm-log-object.h"

/*
 * Documentation that you may want to have around:
 *
 *   3GPP2 C.S0015-B: Short Message Service (SMS) for Wideband Spread Spectrum
 *                    Systems.
 *
 *   3GPP2 C.R1001-G: Administration of Parameter Value Assignments for CDMA2000
 *                    Spread Spectrum Standards.
 *
 *   3GPP2 X.S0004-550-E: Mobile Application Part (MAP).
 *
 *   3GPP2 C.S0005-E: Upper Layer (Layer 3) Signaling Standard for CDMA2000
 *                    Spread Spectrum Systems.
 *
 *   3GPP2 N.S0005-O: Cellular Radiotelecommunications Intersystem Operations.
 */

/* 3GPP2 C.S0015-B, section 3.4, table 3.4-1 */
typedef enum {
    MESSAGE_TYPE_POINT_TO_POINT = 0,
    MESSAGE_TYPE_BROADCAST      = 1,
    MESSAGE_TYPE_ACKNOWLEDGE    = 2
} MessageType;

/* 3GPP2 C.S0015-B, section 3.4.3, table 3.4.3-1 */
typedef enum {
    PARAMETER_ID_TELESERVICE_ID         = 0,
    PARAMETER_ID_SERVICE_CATEGORY       = 1,
    PARAMETER_ID_ORIGINATING_ADDRESS    = 2,
    PARAMETER_ID_ORIGINATING_SUBADDRESS = 3,
    PARAMETER_ID_DESTINATION_ADDRESS    = 4,
    PARAMETER_ID_DESTINATION_SUBADDRESS = 5,
    PARAMETER_ID_BEARER_REPLY_OPTION    = 6,
    PARAMETER_ID_CAUSE_CODES            = 7,
    PARAMETER_ID_BEARER_DATA            = 8
} ParameterId;

/* 3GPP2 C.S0015-B, section 3.4.3.3 */
typedef enum {
    DIGIT_MODE_DTMF  = 0,
    DIGIT_MODE_ASCII = 1
} DigitMode;

/* 3GPP2 C.S0015-B, section 3.4.3.3 */
typedef enum {
    NUMBER_MODE_DIGIT                = 0,
    NUMBER_MODE_DATA_NETWORK_ADDRESS = 1
} NumberMode;

/* 3GPP2 C.S0005-E, section 2.7.1.3.2.4, table 2.7.1.3.2.4-2 */
typedef enum {
    NUMBER_TYPE_UNKNOWN          = 0,
    NUMBER_TYPE_INTERNATIONAL    = 1,
    NUMBER_TYPE_NATIONAL         = 2,
    NUMBER_TYPE_NETWORK_SPECIFIC = 3,
    NUMBER_TYPE_SUBSCRIBER       = 4,
    /* 5 reserved */
    NUMBER_TYPE_ABBREVIATED      = 6,
    /* 7 reserved */
} NumberType;

/* 3GPP2 C.S0015-B, section 3.4.3.3, table 3.4.3.3-1 */
typedef enum {
    DATA_NETWORK_ADDRESS_TYPE_UNKNOWN                = 0,
    DATA_NETWORK_ADDRESS_TYPE_INTERNET_PROTOCOL      = 1,
    DATA_NETWORK_ADDRESS_TYPE_INTERNET_EMAIL_ADDRESS = 2
} DataNetworkAddressType;

/* 3GPP2 C.S0005-E, section 2.7.1.3.2.4, table 2.7.1.3.2.4-3 */
typedef enum {
    NUMBERING_PLAN_UNKNOWN = 0,
    NUMBERING_PLAN_ISDN    = 1,
    NUMBERING_PLAN_DATA    = 3,
    NUMBERING_PLAN_TELEX   = 4,
    NUMBERING_PLAN_PRIVATE = 9,
    /* 15 reserved */
} NumberingPlan;

/* 3GPP2 C.S0015-B, section 3.4.3.6 */
typedef enum {
    ERROR_CLASS_NO_ERROR  = 0,
    /* 1 reserved */
    ERROR_CLASS_TEMPORARY = 2,
    ERROR_CLASS_PERMANENT = 3
} ErrorClass;

/* 3GPP2 N.S0005-O, section 6.5.2.125*/
typedef enum {
    CAUSE_CODE_NETWORK_PROBLEM_ADDRESS_VACANT              = 0,
    CAUSE_CODE_NETWORK_PROBLEM_ADDRESS_TRANSLATION_FAILURE = 1,
    CAUSE_CODE_NETWORK_PROBLEM_NETWORK_RESOURCE_OUTAGE     = 2,
    CAUSE_CODE_NETWORK_PROBLEM_NETWORK_FAILURE             = 3,
    CAUSE_CODE_NETWORK_PROBLEM_INVALID_TELESERVICE_ID      = 4,
    CAUSE_CODE_NETWORK_PROBLEM_OTHER                       = 5,
    /* 6 to 31 reserved, treat as CAUSE_CODE_NETWORK_PROBLEM_OTHER */
    CAUSE_CODE_TERMINAL_PROBLEM_NO_PAGE_RESPONSE                      = 32,
    CAUSE_CODE_TERMINAL_PROBLEM_DESTINATION_BUSY                      = 33,
    CAUSE_CODE_TERMINAL_PROBLEM_NO_ACKNOWLEDGMENT                     = 34,
    CAUSE_CODE_TERMINAL_PROBLEM_DESTINATION_RESOURCE_SHORTAGE         = 35,
    CAUSE_CODE_TERMINAL_PROBLEM_SMS_DELIVERY_POSTPONED                = 36,
    CAUSE_CODE_TERMINAL_PROBLEM_DESTINATION_OUT_OF_SERVICE            = 37,
    CAUSE_CODE_TERMINAL_PROBLEM_DESTINATION_NO_LONGER_AT_THIS_ADDRESS = 38,
    CAUSE_CODE_TERMINAL_PROBLEM_OTHER                                 = 39,
    /* 40 to 47 reserved, treat as CAUSE_CODE_TERMINAL_PROBLEM_OTHER */
    /* 48 to 63 reserved, treat as CAUSE_CODE_TERMINAL_PROBLEM_SMS_DELIVERY_POSTPONED */
    CAUSE_CODE_RADIO_INTERFACE_PROBLEM_RESOURCE_SHORTAGE = 64,
    CAUSE_CODE_RADIO_INTERFACE_PROBLEM_INCOMPATIBILITY   = 65,
    CAUSE_CODE_RADIO_INTERFACE_PROBLEM_OTHER             = 66,
    /* 67 to 95 reserved, treat as CAUSE_CODE_RADIO_INTERFACE_PROBLEM_OTHER */
    CAUSE_CODE_GENERAL_PROBLEM_ENCODING                            = 96,
    CAUSE_CODE_GENERAL_PROBLEM_SMS_ORIGINATION_DENIED              = 97,
    CAUSE_CODE_GENERAL_PROBLEM_SMS_TERMINATION_DENIED              = 98,
    CAUSE_CODE_GENERAL_PROBLEM_SUPPLEMENTARY_SERVICE_NOT_SUPPORTED = 99,
    CAUSE_CODE_GENERAL_PROBLEM_SMS_NOT_SUPPORTED                   = 100,
    /* 101 reserved */
    CAUSE_CODE_GENERAL_PROBLEM_MISSING_EXPECTED_PARAMETER   = 102,
    CAUSE_CODE_GENERAL_PROBLEM_MISSING_MANDATORY_PARAMETER  = 103,
    CAUSE_CODE_GENERAL_PROBLEM_UNRECOGNIZED_PARAMETER_VALUE = 104,
    CAUSE_CODE_GENERAL_PROBLEM_UNEXPECTED_PARAMETER_VALUE   = 105,
    CAUSE_CODE_GENERAL_PROBLEM_USER_DATA_SIZE_ERROR         = 106,
    CAUSE_CODE_GENERAL_PROBLEM_OTHER                        = 107,
    /* 108 to 223 reserved, treat as CAUSE_CODE_GENERAL_PROBLEM_OTHER */
    /* 224 to 255 reserved for TIA/EIA-41 extension, otherwise treat as CAUSE_CODE_GENERAL_PROBLEM_OTHER */
} CauseCode;

/* 3GPP2 C.S0015-B, section 4.5, table 4.5-1 */
typedef enum {
    SUBPARAMETER_ID_MESSAGE_ID                      = 0,
    SUBPARAMETER_ID_USER_DATA                       = 1,
    SUBPARAMETER_ID_USER_RESPONSE_CODE              = 2,
    SUBPARAMETER_ID_MESSAGE_CENTER_TIME_STAMP       = 3,
    SUBPARAMETER_ID_VALIDITY_PERIOD_ABSOLUTE        = 4,
    SUBPARAMETER_ID_VALIDITY_PERIOD_RELATIVE        = 5,
    SUBPARAMETER_ID_DEFERRED_DELIVERY_TIME_ABSOLUTE = 6,
    SUBPARAMETER_ID_DEFERRED_DELIVERY_TIME_RELATIVE = 7,
    SUBPARAMETER_ID_PRIORITY_INDICATOR              = 8,
    SUBPARAMETER_ID_PRIVACY_INDICATOR               = 9,
    SUBPARAMETER_ID_REPLY_OPTION                    = 10,
    SUBPARAMETER_ID_NUMBER_OF_MESSAGES              = 11,
    SUBPARAMETER_ID_ALERT_ON_MESSAGE_DELIVERY       = 12,
    SUBPARAMETER_ID_LANGUAGE_INDICATOR              = 13,
    SUBPARAMETER_ID_CALL_BACK_NUMBER                = 14,
    SUBPARAMETER_ID_MESSAGE_DISPLAY_MODE            = 15,
    SUBPARAMETER_ID_MULTIPLE_ENCODING_USER_DATA     = 16,
    SUBPARAMETER_ID_MESSAGE_DEPOSIT_INDEX           = 17,
    SUBPARAMETER_ID_SERVICE_CATEGORY_PROGRAM_DATA   = 18,
    SUBPARAMETER_ID_SERVICE_CATEGORY_PROGRAM_RESULT = 19,
    SUBPARAMETER_ID_MESSAGE_STATUS                  = 20,
    SUBPARAMETER_ID_TP_FAILURE_CAUSE                = 21,
    SUBPARAMETER_ID_ENHANCED_VMN                    = 22,
    SUBPARAMETER_ID_ENHANCED_VMN_ACK                = 23,
} SubparameterId;

/* 3GPP2 C.S0015-B, section 4.5.1, table 4.5.1-1 */
typedef enum {
    TELESERVICE_MESSAGE_TYPE_UNKNOWN                  = 0,
    TELESERVICE_MESSAGE_TYPE_DELIVER                  = 1,
    TELESERVICE_MESSAGE_TYPE_SUBMIT                   = 2,
    TELESERVICE_MESSAGE_TYPE_CANCELLATION             = 3,
    TELESERVICE_MESSAGE_TYPE_DELIVERY_ACKNOWLEDGEMENT = 4,
    TELESERVICE_MESSAGE_TYPE_USER_ACKNOWLEDGEMENT     = 5,
    TELESERVICE_MESSAGE_TYPE_READ_ACKNOWLEDGEMENT     = 6,
} TeleserviceMessageType;

/* C.R1001-G, section 9.1, table 9.1-1 */
typedef enum {
    ENCODING_OCTET                     = 0,
    ENCODING_EXTENDED_PROTOCOL_MESSAGE = 1,
    ENCODING_ASCII_7BIT                = 2,
    ENCODING_IA5                       = 3,
    ENCODING_UNICODE                   = 4,
    ENCODING_SHIFT_JIS                 = 5,
    ENCODING_KOREAN                    = 6,
    ENCODING_LATIN_HEBREW              = 7,
    ENCODING_LATIN                     = 8,
    ENCODING_GSM_7BIT                  = 9,
    ENCODING_GSM_DCS                   = 10,
} Encoding;

static const gchar *
encoding_to_string (Encoding encoding)
{
    static const gchar *encoding_str[] = {
        "octet",
        "extend protocol message",
        "7-bit ASCII",
        "IA5",
        "unicode",
        "shift-j is",
        "korean",
        "latin/hebrew",
        "latin",
        "7-bit GSM",
        "GSM data coding scheme"
    };

    if (encoding >= ENCODING_OCTET && encoding <= ENCODING_GSM_DCS)
        return encoding_str[encoding];

    return "unknown";
}

/*****************************************************************************/
/* Read bits; o_bits < 8; n_bits <= 8
 *
 * Byte 0            Byte 1
 * [7|6|5|4|3|2|1|0] [7|6|5|4|3|2|1|0]
 *
 * o_bits+n_bits <= 16
 *
 */
static guint8
read_bits (const guint8 *bytes,
           guint8 o_bits,
           guint8 n_bits)
{
    guint8 bits_in_first;
    guint8 bits_in_second;

    g_assert (o_bits < 8);
    g_assert (n_bits <= 8);
    g_assert (o_bits + n_bits <= 16);

    /* Read only from the first byte */
    if (o_bits + n_bits <= 8)
        return (bytes[0] >> (8 - o_bits - n_bits)) & ((1 << n_bits) - 1);

    /* Read (8 - o_bits) from the first byte and (n_bits - (8 - o_bits)) from the second byte */
    bits_in_first = 8 - o_bits;
    bits_in_second = n_bits - bits_in_first;
    return (read_bits (&bytes[0], o_bits, bits_in_first) << bits_in_second) | read_bits (&bytes[1], 0, bits_in_second);
}

/*****************************************************************************/
/* Cause code to delivery state */

static MMSmsDeliveryState
cause_code_to_delivery_state (guint8 error_class,
                              guint8 cause_code)
{
    guint delivery_state = 0;

    switch (error_class) {
    case ERROR_CLASS_NO_ERROR:
        return MM_SMS_DELIVERY_STATE_COMPLETED_RECEIVED;
    case ERROR_CLASS_TEMPORARY:
        delivery_state += 0x300;
        break;
    case ERROR_CLASS_PERMANENT:
        delivery_state += 0x200;
        break;
    default:
        return MM_SMS_DELIVERY_STATE_UNKNOWN;
    }

    /* Fixes for unknown cause codes */

    if (cause_code >= 6 && cause_code <= 31)
        /* 6 to 31 reserved, treat as CAUSE_CODE_NETWORK_PROBLEM_OTHER */
        delivery_state += CAUSE_CODE_NETWORK_PROBLEM_OTHER;
    else if (cause_code >= 40 && cause_code <= 47)
        /* 40 to 47 reserved, treat as CAUSE_CODE_TERMINAL_PROBLEM_OTHER */
        delivery_state += CAUSE_CODE_TERMINAL_PROBLEM_OTHER;
    else if (cause_code >= 48 && cause_code <= 63)
        /* 48 to 63 reserved, treat as CAUSE_CODE_TERMINAL_PROBLEM_SMS_DELIVERY_POSTPONED */
        delivery_state += CAUSE_CODE_TERMINAL_PROBLEM_SMS_DELIVERY_POSTPONED;
    else if (cause_code >= 67 && cause_code <= 95)
        /* 67 to 95 reserved, treat as CAUSE_CODE_RADIO_INTERFACE_PROBLEM_OTHER */
        delivery_state += CAUSE_CODE_RADIO_INTERFACE_PROBLEM_OTHER;
    else if (cause_code == 101)
        /* 101 reserved */
        delivery_state += CAUSE_CODE_GENERAL_PROBLEM_OTHER;
    else if (cause_code >= 108) /* cause_code <= 255 is always true */
        /* 108 to 223 reserved, treat as CAUSE_CODE_GENERAL_PROBLEM_OTHER
         * 224 to 255 reserved for TIA/EIA-41 extension, otherwise treat as CAUSE_CODE_GENERAL_PROBLEM_OTHER */
        delivery_state += CAUSE_CODE_GENERAL_PROBLEM_OTHER;
    else
        /* direct relationship */
        delivery_state += cause_code;

    return (MMSmsDeliveryState) delivery_state;
}

/*****************************************************************************/

MMSmsPart *
mm_sms_part_cdma_new_from_pdu (guint         index,
                               const gchar  *hexpdu,
                               gpointer      log_object,
                               GError      **error)
{
    gsize pdu_len;
    guint8 *pdu;
    MMSmsPart *part;

    /* Convert PDU from hex to binary */
    pdu = (guint8 *) mm_utils_hexstr2bin (hexpdu, &pdu_len);
    if (!pdu) {
        g_set_error_literal (error,
                             MM_CORE_ERROR,
                             MM_CORE_ERROR_FAILED,
                             "Couldn't convert CDMA PDU from hex to binary");
        return NULL;
    }

    part = mm_sms_part_cdma_new_from_binary_pdu (index, pdu, pdu_len, log_object, error);
    g_free (pdu);

    return part;
}

struct Parameter {
    guint8 parameter_id;
    guint8 parameter_len;
    guint8 parameter_value[];
} __attribute__((packed));

static void
read_teleservice_id (MMSmsPart              *sms_part,
                     const struct Parameter *parameter,
                     gpointer                log_object)
{
    guint16 teleservice_id;

    g_assert (parameter->parameter_id == PARAMETER_ID_TELESERVICE_ID);

    if (parameter->parameter_len != 2) {
        mm_obj_dbg (log_object, "        invalid teleservice ID length found (%u != 2): ignoring",
                    parameter->parameter_len);
        return;
    }

    memcpy (&teleservice_id, &parameter->parameter_value[0], 2);
    teleservice_id = GUINT16_FROM_BE (teleservice_id);

    switch (teleservice_id){
    case MM_SMS_CDMA_TELESERVICE_ID_CMT91:
    case MM_SMS_CDMA_TELESERVICE_ID_WPT:
    case MM_SMS_CDMA_TELESERVICE_ID_WMT:
    case MM_SMS_CDMA_TELESERVICE_ID_VMN:
    case MM_SMS_CDMA_TELESERVICE_ID_WAP:
    case MM_SMS_CDMA_TELESERVICE_ID_WEMT:
    case MM_SMS_CDMA_TELESERVICE_ID_SCPT:
    case MM_SMS_CDMA_TELESERVICE_ID_CATPT:
        break;
    default:
        mm_obj_dbg (log_object, "        invalid teleservice ID found (%u): ignoring", teleservice_id);
        return;
    }

    mm_obj_dbg (log_object, "        teleservice ID: %s (%u)",
                mm_sms_cdma_teleservice_id_get_string (teleservice_id),
                teleservice_id);

    mm_sms_part_set_cdma_teleservice_id (sms_part,
                                         (MMSmsCdmaTeleserviceId)teleservice_id);
}

static void
read_service_category (MMSmsPart              *sms_part,
                       const struct Parameter *parameter,
                       gpointer                log_object)
{
    guint16 service_category;

    g_assert (parameter->parameter_id == PARAMETER_ID_SERVICE_CATEGORY);

    if (parameter->parameter_len != 2) {
        mm_obj_dbg (log_object, "        invalid service category length found (%u != 2): ignoring",
                    parameter->parameter_len);
        return;
    }

    memcpy (&service_category, &parameter->parameter_value[0], 2);
    service_category = GUINT16_FROM_BE (service_category);

    switch (service_category) {
    case MM_SMS_CDMA_SERVICE_CATEGORY_EMERGENCY_BROADCAST:
    case MM_SMS_CDMA_SERVICE_CATEGORY_ADMINISTRATIVE:
    case MM_SMS_CDMA_SERVICE_CATEGORY_MAINTENANCE:
    case MM_SMS_CDMA_SERVICE_CATEGORY_GENERAL_NEWS_LOCAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_GENERAL_NEWS_REGIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_GENERAL_NEWS_NATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_GENERAL_NEWS_INTERNATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_BUSINESS_NEWS_LOCAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_BUSINESS_NEWS_REGIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_BUSINESS_NEWS_NATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_BUSINESS_NEWS_INTERNATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_SPORTS_NEWS_LOCAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_SPORTS_NEWS_REGIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_SPORTS_NEWS_NATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_SPORTS_NEWS_INTERNATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_ENTERTAINMENT_NEWS_LOCAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_ENTERTAINMENT_NEWS_REGIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_ENTERTAINMENT_NEWS_NATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_ENTERTAINMENT_NEWS_INTERNATIONAL:
    case MM_SMS_CDMA_SERVICE_CATEGORY_LOCAL_WEATHER:
    case MM_SMS_CDMA_SERVICE_CATEGORY_TRAFFIC_REPORT:
    case MM_SMS_CDMA_SERVICE_CATEGORY_FLIGHT_SCHEDULES:
    case MM_SMS_CDMA_SERVICE_CATEGORY_RESTAURANTS:
    case MM_SMS_CDMA_SERVICE_CATEGORY_LODGINGS:
    case MM_SMS_CDMA_SERVICE_CATEGORY_RETAIL_DIRECTORY:
    case MM_SMS_CDMA_SERVICE_CATEGORY_ADVERTISEMENTS:
    case MM_SMS_CDMA_SERVICE_CATEGORY_STOCK_QUOTES:
    case MM_SMS_CDMA_SERVICE_CATEGORY_EMPLOYMENT:
    case MM_SMS_CDMA_SERVICE_CATEGORY_HOSPITALS:
    case MM_SMS_CDMA_SERVICE_CATEGORY_TECHNOLOGY_NEWS:
    case MM_SMS_CDMA_SERVICE_CATEGORY_MULTICATEGORY:
    case MM_SMS_CDMA_SERVICE_CATEGORY_CMAS_PRESIDENTIAL_ALERT:
    case MM_SMS_CDMA_SERVICE_CATEGORY_CMAS_EXTREME_THREAT:
    case MM_SMS_CDMA_SERVICE_CATEGORY_CMAS_SEVERE_THREAT:
    case MM_SMS_CDMA_SERVICE_CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY:
    case MM_SMS_CDMA_SERVICE_CATEGORY_CMAS_TEST:
        break;
    default:
        mm_obj_dbg (log_object, "        invalid service category found (%u): ignoring", service_category);
        return;
    }

    mm_obj_dbg (log_object, "        service category: %s (%u)",
                mm_sms_cdma_service_category_get_string (service_category),
                service_category);

    mm_sms_part_set_cdma_service_category (sms_part,
                                           (MMSmsCdmaServiceCategory)service_category);
}

static guint8
dtmf_to_ascii (guint8   dtmf,
               gpointer log_object)
{
    static const gchar dtmf_to_ascii_digits[13] = {
        '\0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '*', '#' };

    if (dtmf > 0 && dtmf < 13)
        return dtmf_to_ascii_digits[dtmf];

    mm_obj_dbg (log_object, "        invalid dtmf digit: %u", dtmf);
    return '\0';
}

static void
read_address (MMSmsPart              *sms_part,
              const struct Parameter *parameter,
              gpointer                log_object)
{
    guint8 digit_mode;
    guint8 number_mode;
    guint8 number_type;
    guint8 numbering_plan;
    guint8 num_fields;
    guint byte_offset = 0;
    guint bit_offset = 0;
    guint i;
    gchar *number = NULL;

#define OFFSETS_UPDATE(n_bits) do { \
        bit_offset += n_bits;       \
        if (bit_offset >= 8) {      \
            bit_offset-=8;          \
            byte_offset++;          \
        }                           \
    } while (0)

#define PARAMETER_SIZE_CHECK(required_size)                             \
    if (parameter->parameter_len < required_size) {                     \
        mm_obj_dbg (log_object, "        cannot read address, need at least %u bytes (got %u)", \
                    required_size,                                      \
                    parameter->parameter_len);                          \
        return;                                                         \
    }

    /* Readability of digit mode and number mode (first 2 bits, i.e. first byte) */
    PARAMETER_SIZE_CHECK (1);

    /* Digit mode */
    digit_mode = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 1);
    OFFSETS_UPDATE (1);
    g_assert (digit_mode <= 1);
    switch (digit_mode) {
    case DIGIT_MODE_DTMF:
        mm_obj_dbg (log_object, "        digit mode: dtmf");
        break;
    case DIGIT_MODE_ASCII:
        mm_obj_dbg (log_object, "        digit mode: ascii");
        break;
    default:
        g_assert_not_reached ();
    }

    /* Number mode */
    number_mode = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 1);
    OFFSETS_UPDATE (1);
    switch (number_mode) {
    case NUMBER_MODE_DIGIT:
        mm_obj_dbg (log_object, "        number mode: digit");
        break;
    case NUMBER_MODE_DATA_NETWORK_ADDRESS:
        mm_obj_dbg (log_object, "        number mode: data network address");
        break;
    default:
        g_assert_not_reached ();
    }

    /* Number type */
    if (digit_mode == DIGIT_MODE_ASCII) {
        /* No need for readability check, still in first byte always */
        number_type = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 3);
        OFFSETS_UPDATE (3);
        switch (number_type) {
        case NUMBER_TYPE_UNKNOWN:
            mm_obj_dbg (log_object, "        number type: unknown");
            break;
        case NUMBER_TYPE_INTERNATIONAL:
            mm_obj_dbg (log_object, "        number type: international");
            break;
        case NUMBER_TYPE_NATIONAL:
            mm_obj_dbg (log_object, "        number type: national");
            break;
        case NUMBER_TYPE_NETWORK_SPECIFIC:
            mm_obj_dbg (log_object, "        number type: specific");
            break;
        case NUMBER_TYPE_SUBSCRIBER:
            mm_obj_dbg (log_object, "        number type: subscriber");
            break;
        case NUMBER_TYPE_ABBREVIATED:
            mm_obj_dbg (log_object, "        number type: abbreviated");
            break;
        default:
            mm_obj_dbg (log_object, "        number type unknown (%u)", number_type);
            break;
        }
    } else
        number_type = 0xFF;

    /* Numbering plan */
    if (digit_mode == DIGIT_MODE_ASCII && number_mode == NUMBER_MODE_DIGIT) {
        /* Readability of numbering plan; may go to second byte */
        PARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + 4) / 8));
        numbering_plan = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 4);
        OFFSETS_UPDATE (4);
        switch (numbering_plan) {
        case NUMBERING_PLAN_UNKNOWN:
            mm_obj_dbg (log_object, "        numbering plan: unknown");
            break;
        case NUMBERING_PLAN_ISDN:
            mm_obj_dbg (log_object, "        numbering plan: isdn");
            break;
        case NUMBERING_PLAN_DATA:
            mm_obj_dbg (log_object, "        numbering plan: data");
            break;
        case NUMBERING_PLAN_TELEX:
            mm_obj_dbg (log_object, "        numbering plan: telex");
            break;
        case NUMBERING_PLAN_PRIVATE:
            mm_obj_dbg (log_object, "        numbering plan: private");
            break;
        default:
            mm_obj_dbg (log_object, "        numbering plan unknown (%u)", numbering_plan);
            break;
        }
    } else
        numbering_plan = 0xFF;

    /* Readability of num_fields; will go to third byte (((bit_offset + 8) / 8) == 1) */
    PARAMETER_SIZE_CHECK (byte_offset + 2);
    num_fields = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 8);
    OFFSETS_UPDATE (8);
    mm_obj_dbg (log_object, "        num fields: %u", num_fields);

    /* Address string */

    if (digit_mode == DIGIT_MODE_DTMF) {
        /* DTMF */
        PARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 4)) / 8));
        number = g_malloc (num_fields + 1);
        for (i = 0; i < num_fields; i++) {
            number[i] = dtmf_to_ascii (read_bits (&parameter->parameter_value[byte_offset], bit_offset, 4), log_object);
            OFFSETS_UPDATE (4);
        }
        number[i] = '\0';
    } else if (number_mode == NUMBER_MODE_DIGIT) {
        /* ASCII
         * TODO: should we expose numbering plan and number type? */
        PARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 8)) / 8));
        number = g_malloc (num_fields + 1);
        for (i = 0; i < num_fields; i++) {
            number[i] = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 8);
            OFFSETS_UPDATE (8);
        }
        number[i] = '\0';
    } else if (number_type == DATA_NETWORK_ADDRESS_TYPE_INTERNET_EMAIL_ADDRESS) {
        /* Internet e-mail address (ASCII) */
        PARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 8)) / 8));
        number = g_malloc (num_fields + 1);
        for (i = 0; i < num_fields; i++) {
            number[i] = read_bits (&parameter->parameter_value[byte_offset], bit_offset, 8);
            OFFSETS_UPDATE (8);
        }
        number[i] = '\0';
    } else if (number_type == DATA_NETWORK_ADDRESS_TYPE_INTERNET_PROTOCOL) {
        GString *str;

        /* Binary data network address (most significant first)
         * For now, just print the hex string (e.g. FF:01...) */
        PARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 8)) / 8));
        str = g_string_sized_new (num_fields * 2);
        for (i = 0; i < num_fields; i++) {
            g_string_append_printf (str, "%.2X", read_bits (&parameter->parameter_value[byte_offset], bit_offset, 8));
            OFFSETS_UPDATE (8);
        }
        number = g_string_free (str, FALSE);
    } else
        mm_obj_dbg (log_object, "        data network address number type unknown (%u)", number_type);

    mm_obj_dbg (log_object, "        address: %s", number);

    mm_sms_part_set_number (sms_part, number);
    g_free (number);

#undef OFFSETS_UPDATE
#undef PARAMETER_SIZE_CHECK
}

static void
read_bearer_reply_option (MMSmsPart              *sms_part,
                          const struct Parameter *parameter,
                          gpointer                log_object)
{
    guint8 sequence;

    g_assert (parameter->parameter_id == PARAMETER_ID_BEARER_REPLY_OPTION);

    if (parameter->parameter_len != 1) {
        mm_obj_dbg (log_object, "        invalid bearer reply option length found (%u != 1): ignoring",
                parameter->parameter_len);
        return;
    }

    sequence = read_bits (&parameter->parameter_value[0], 0, 6);
    mm_obj_dbg (log_object, "        sequence: %u", sequence);

    mm_sms_part_set_message_reference (sms_part, sequence);
}

static void
read_cause_codes (MMSmsPart              *sms_part,
                  const struct Parameter *parameter,
                  gpointer                log_object)
{
    guint8 sequence;
    guint8 error_class;
    guint8 cause_code;
    MMSmsDeliveryState delivery_state;

    g_assert (parameter->parameter_id == PARAMETER_ID_BEARER_REPLY_OPTION);

    if (parameter->parameter_len != 1 && parameter->parameter_len != 2) {
        mm_obj_dbg (log_object, "        invalid cause codes length found (%u): ignoring",
                parameter->parameter_len);
        return;
    }

    sequence = read_bits (&parameter->parameter_value[0], 0, 6);
    mm_obj_dbg (log_object, "        sequence: %u", sequence);

    error_class = read_bits (&parameter->parameter_value[0], 6, 2);
    mm_obj_dbg (log_object, "        error class: %u", error_class);

    if (error_class != ERROR_CLASS_NO_ERROR) {
        if (parameter->parameter_len != 2) {
            mm_obj_dbg (log_object, "        invalid cause codes length found (%u != 2): ignoring",
                    parameter->parameter_len);
            return;
        }
        cause_code = parameter->parameter_value[1];
        mm_obj_dbg (log_object, "        cause code: %u", cause_code);
    } else
        cause_code = 0;

    delivery_state = cause_code_to_delivery_state (error_class, cause_code);
    mm_obj_dbg (log_object, "        delivery state: %s", mm_sms_delivery_state_get_string (delivery_state));

    mm_sms_part_set_message_reference (sms_part, sequence);
    mm_sms_part_set_delivery_state (sms_part, delivery_state);
}

static void
read_bearer_data_message_identifier (MMSmsPart              *sms_part,
                                     const struct Parameter *subparameter,
                                     gpointer                log_object)
{
    guint8 message_type;
    guint16 message_id;
    guint8 header_ind;

    g_assert (subparameter->parameter_id == SUBPARAMETER_ID_MESSAGE_ID);

    if (subparameter->parameter_len != 3) {
        mm_obj_dbg (log_object, "        invalid message identifier length found (%u): ignoring",
                subparameter->parameter_len);
        return;
    }

    message_type = read_bits (&subparameter->parameter_value[0], 0, 4);
    switch (message_type) {
    case TELESERVICE_MESSAGE_TYPE_UNKNOWN:
        mm_obj_dbg (log_object, "            message type: unknown");
        break;
    case TELESERVICE_MESSAGE_TYPE_DELIVER:
        mm_obj_dbg (log_object, "            message type: deliver");
        mm_sms_part_set_pdu_type (sms_part, MM_SMS_PDU_TYPE_CDMA_DELIVER);
        break;
    case TELESERVICE_MESSAGE_TYPE_SUBMIT:
        mm_obj_dbg (log_object, "            message type: submit");
        mm_sms_part_set_pdu_type (sms_part, MM_SMS_PDU_TYPE_CDMA_SUBMIT);
        break;
    case TELESERVICE_MESSAGE_TYPE_CANCELLATION:
        mm_obj_dbg (log_object, "            message type: cancellation");
        mm_sms_part_set_pdu_type (sms_part, MM_SMS_PDU_TYPE_CDMA_CANCELLATION);
        break;
    case TELESERVICE_MESSAGE_TYPE_DELIVERY_ACKNOWLEDGEMENT:
        mm_obj_dbg (log_object, "            message type: delivery acknowledgement");
        mm_sms_part_set_pdu_type (sms_part, MM_SMS_PDU_TYPE_CDMA_DELIVERY_ACKNOWLEDGEMENT);
        break;
    case TELESERVICE_MESSAGE_TYPE_USER_ACKNOWLEDGEMENT:
        mm_obj_dbg (log_object, "            message type: user acknowledgement");
        mm_sms_part_set_pdu_type (sms_part, MM_SMS_PDU_TYPE_CDMA_USER_ACKNOWLEDGEMENT);
        break;
    case TELESERVICE_MESSAGE_TYPE_READ_ACKNOWLEDGEMENT:
        mm_obj_dbg (log_object, "            message type: read acknowledgement");
        mm_sms_part_set_pdu_type (sms_part, MM_SMS_PDU_TYPE_CDMA_READ_ACKNOWLEDGEMENT);
        break;
    default:
        mm_obj_dbg (log_object, "            message type unknown (%u)", message_type);
        break;
    }

    message_id = ((read_bits (&subparameter->parameter_value[0], 4, 8) << 8) |
                  (read_bits (&subparameter->parameter_value[1], 4, 8)));
    message_id = GUINT16_FROM_BE (message_id);
    mm_obj_dbg (log_object, "            message id: %u", (guint) message_id);

    header_ind = read_bits (&subparameter->parameter_value[2], 4, 1);
    mm_obj_dbg (log_object, "            header indicator: %u", header_ind);
}

static void
read_bearer_data_user_data (MMSmsPart              *sms_part,
                            const struct Parameter *subparameter,
                            gpointer                log_object)
{
    guint8 message_encoding;
    guint8 message_type = 0;
    guint8 num_fields;
    guint byte_offset = 0;
    guint bit_offset = 0;

#define OFFSETS_UPDATE(n_bits) do { \
        bit_offset += n_bits;       \
        if (bit_offset >= 8) {      \
            bit_offset-=8;          \
            byte_offset++;          \
        }                           \
    } while (0)

#define SUBPARAMETER_SIZE_CHECK(required_size)                             \
    if (subparameter->parameter_len < required_size) {                  \
        mm_obj_dbg (log_object, "        cannot read user data, need at least %u bytes (got %u)", \
                required_size,                                          \
                subparameter->parameter_len);                           \
        return;                                                         \
    }

    g_assert (subparameter->parameter_id == SUBPARAMETER_ID_USER_DATA);

    /* Message encoding */
    SUBPARAMETER_SIZE_CHECK (1);
    message_encoding = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 5);
    OFFSETS_UPDATE (5);
    mm_obj_dbg (log_object, "            message encoding: %s", encoding_to_string (message_encoding));

    /* Message type, only if extended protocol message */
    if (message_encoding == ENCODING_EXTENDED_PROTOCOL_MESSAGE) {
        SUBPARAMETER_SIZE_CHECK (2);
        message_type = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 8);
        OFFSETS_UPDATE (8);
        mm_obj_dbg (log_object, "            message type: %u", message_type);
    }

    /* Number of fields */
    SUBPARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + 8) / 8));
    num_fields = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 8);
    OFFSETS_UPDATE (8);
    mm_obj_dbg (log_object, "            num fields: %u", num_fields);

    /* Now, process actual text or data */
    switch (message_encoding) {
    case ENCODING_OCTET: {
        GByteArray *data;
        guint i;

        SUBPARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 8)) / 8));

        data = g_byte_array_sized_new (num_fields);
        g_byte_array_set_size (data, num_fields);
        for (i = 0; i < num_fields; i++) {
            data->data[i] = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 8);
            OFFSETS_UPDATE (8);
        }

        mm_obj_dbg (log_object, "            data: (%u bytes)", num_fields);
        mm_sms_part_take_data (sms_part, data);
        break;
    }

    case ENCODING_ASCII_7BIT: {
        gchar *text;
        guint i;

        SUBPARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 7)) / 8));

        text = g_malloc (num_fields + 1);
        for (i = 0; i < num_fields; i++) {
            text[i] = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 7);
            OFFSETS_UPDATE (7);
        }
        text[i] = '\0';

        mm_obj_dbg (log_object, "            text: '%s'", text);
        mm_sms_part_take_text (sms_part, text);
        break;
    }

    case ENCODING_LATIN: {
        gchar *latin;
        gchar *text;
        guint i;

        SUBPARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_fields * 8)) / 8));

        latin = g_malloc (num_fields + 1);
        for (i = 0; i < num_fields; i++) {
            latin[i] = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 8);
            OFFSETS_UPDATE (8);
        }
        latin[i] = '\0';

        text = g_convert (latin, -1, "UTF-8", "ISO-8859-1", NULL, NULL, NULL);
        if (!text) {
            mm_obj_dbg (log_object, "            text/data: ignored (latin to UTF-8 conversion error)");
        } else {
            mm_obj_dbg (log_object, "            text: '%s'", text);
            mm_sms_part_take_text (sms_part, text);
        }

        g_free (latin);
        break;
    }

    case ENCODING_UNICODE: {
        gchar *utf16;
        gchar *text;
        guint i;
        guint num_bytes;

        /* 2 bytes per field! */
        num_bytes = num_fields * 2;

        SUBPARAMETER_SIZE_CHECK (byte_offset + 1 + ((bit_offset + (num_bytes * 8)) / 8));

        utf16 = g_malloc (num_bytes);
        for (i = 0; i < num_bytes; i++) {
            utf16[i] = read_bits (&subparameter->parameter_value[byte_offset], bit_offset, 8);
            OFFSETS_UPDATE (8);
        }

        text = g_convert (utf16, num_bytes, "UTF-8", "UCS-2BE", NULL, NULL, NULL);
        if (!text) {
            mm_obj_dbg (log_object, "            text/data: ignored (UTF-16 to UTF-8 conversion error)");
        } else {
            mm_obj_dbg (log_object, "            text: '%s'", text);
            mm_sms_part_take_text (sms_part, text);
        }

        g_free (utf16);
        break;
    }

    default:
        mm_obj_dbg (log_object, "            text/data: ignored (unsupported encoding)");
    }

#undef OFFSETS_UPDATE
#undef SUBPARAMETER_SIZE_CHECK
}

static void
read_bearer_data (MMSmsPart              *sms_part,
                  const struct Parameter *parameter,
                  gpointer                log_object)
{
    guint offset;

#define PARAMETER_SIZE_CHECK(required_size)                             \
    if (parameter->parameter_len < required_size) {                     \
        mm_obj_dbg (log_object, "        cannot read bearer data, need at least %u bytes (got %u)", \
                    required_size,                                      \
                    parameter->parameter_len);                          \
        return;                                                         \
    }

    offset = 0;
    while (offset < parameter->parameter_len) {
        const struct Parameter *subparameter;

        PARAMETER_SIZE_CHECK (offset + 2);
        subparameter = (const struct Parameter *)&parameter->parameter_value[offset];
        offset += 2;

        PARAMETER_SIZE_CHECK (offset + subparameter->parameter_len);
        offset += subparameter->parameter_len;

        switch (subparameter->parameter_id) {
        case SUBPARAMETER_ID_MESSAGE_ID:
            mm_obj_dbg (log_object, "        reading message ID...");
            read_bearer_data_message_identifier (sms_part, subparameter, log_object);
            break;
        case SUBPARAMETER_ID_USER_DATA:
            mm_obj_dbg (log_object, "        reading user data...");
            read_bearer_data_user_data (sms_part, subparameter, log_object);
            break;
        case SUBPARAMETER_ID_USER_RESPONSE_CODE:
            mm_obj_dbg (log_object, "        skipping user response code...");
            break;
        case SUBPARAMETER_ID_MESSAGE_CENTER_TIME_STAMP:
            mm_obj_dbg (log_object, "        skipping message center timestamp...");
            break;
        case SUBPARAMETER_ID_VALIDITY_PERIOD_ABSOLUTE:
            mm_obj_dbg (log_object, "        skipping absolute validity period...");
            break;
        case SUBPARAMETER_ID_VALIDITY_PERIOD_RELATIVE:
            mm_obj_dbg (log_object, "        skipping relative validity period...");
            break;
        case SUBPARAMETER_ID_DEFERRED_DELIVERY_TIME_ABSOLUTE:
            mm_obj_dbg (log_object, "        skipping absolute deferred delivery time...");
            break;
        case SUBPARAMETER_ID_DEFERRED_DELIVERY_TIME_RELATIVE:
            mm_obj_dbg (log_object, "        skipping relative deferred delivery time...");
            break;
        case SUBPARAMETER_ID_PRIORITY_INDICATOR:
            mm_obj_dbg (log_object, "        skipping priority indicator...");
            break;
        case SUBPARAMETER_ID_PRIVACY_INDICATOR:
            mm_obj_dbg (log_object, "        skipping privacy indicator...");
            break;
        case SUBPARAMETER_ID_REPLY_OPTION:
            mm_obj_dbg (log_object, "        skipping reply option...");
            break;
        case SUBPARAMETER_ID_NUMBER_OF_MESSAGES:
            mm_obj_dbg (log_object, "        skipping number of messages...");
            break;
        case SUBPARAMETER_ID_ALERT_ON_MESSAGE_DELIVERY:
            mm_obj_dbg (log_object, "        skipping alert on message delivery...");
            break;
        case SUBPARAMETER_ID_LANGUAGE_INDICATOR:
            mm_obj_dbg (log_object, "        skipping language indicator...");
            break;
        case SUBPARAMETER_ID_CALL_BACK_NUMBER:
            mm_obj_dbg (log_object, "        skipping call back number...");
            break;
        case SUBPARAMETER_ID_MESSAGE_DISPLAY_MODE:
            mm_obj_dbg (log_object, "        skipping message display mode...");
            break;
        case SUBPARAMETER_ID_MULTIPLE_ENCODING_USER_DATA:
            mm_obj_dbg (log_object, "        skipping multiple encoding user data...");
            break;
        case SUBPARAMETER_ID_MESSAGE_DEPOSIT_INDEX:
            mm_obj_dbg (log_object, "        skipping message deposit index...");
            break;
        case SUBPARAMETER_ID_SERVICE_CATEGORY_PROGRAM_DATA:
            mm_obj_dbg (log_object, "        skipping service category program data...");
            break;
        case SUBPARAMETER_ID_SERVICE_CATEGORY_PROGRAM_RESULT:
            mm_obj_dbg (log_object, "        skipping service category program result...");
            break;
        case SUBPARAMETER_ID_MESSAGE_STATUS:
            mm_obj_dbg (log_object, "        skipping message status...");
            break;
        case SUBPARAMETER_ID_TP_FAILURE_CAUSE:
            mm_obj_dbg (log_object, "        skipping TP failure case...");
            break;
        case SUBPARAMETER_ID_ENHANCED_VMN:
            mm_obj_dbg (log_object, "        skipping enhanced vmn...");
            break;
        case SUBPARAMETER_ID_ENHANCED_VMN_ACK:
            mm_obj_dbg (log_object, "        skipping enhanced vmn ack...");
            break;
        default:
            mm_obj_dbg (log_object, "    unknown subparameter found: '%u' (ignoring)",
                    subparameter->parameter_id);
            break;
        }
    }

#undef PARAMETER_SIZE_CHECK
}

MMSmsPart *
mm_sms_part_cdma_new_from_binary_pdu (guint          index,
                                      const guint8  *pdu,
                                      gsize          pdu_len,
                                      gpointer       log_object,
                                      GError       **error)
{
    MMSmsPart *sms_part;
    guint offset;
    guint message_type;

    /* Create the new MMSmsPart */
    sms_part = mm_sms_part_new (index, MM_SMS_PDU_TYPE_UNKNOWN);

    if (index != SMS_PART_INVALID_INDEX)
        mm_obj_dbg (log_object, "parsing CDMA PDU (%u)...", index);
    else
        mm_obj_dbg (log_object, "parsing CDMA PDU...");

#define PDU_SIZE_CHECK(required_size, check_descr_str)                 \
    if (pdu_len < required_size) {                                     \
        g_set_error (error,                                            \
                     MM_CORE_ERROR,                                    \
                     MM_CORE_ERROR_FAILED,                             \
                     "CDMA PDU too short, %s: %" G_GSIZE_FORMAT " < %u",    \
                     check_descr_str,                                  \
                     pdu_len,                                          \
                     required_size);                                   \
        mm_sms_part_free (sms_part);                                   \
        return NULL;                                                   \
    }

    offset = 0;

    /* First byte: SMS message type */
    PDU_SIZE_CHECK (offset + 1, "cannot read SMS message type");
    message_type = pdu[offset++];
    switch (message_type) {
    case MESSAGE_TYPE_POINT_TO_POINT:
    case MESSAGE_TYPE_BROADCAST:
    case MESSAGE_TYPE_ACKNOWLEDGE:
        break;
    default:
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_FAILED,
                     "Invalid SMS message type (%u)",
                     message_type);
        mm_sms_part_free (sms_part);
        return NULL;
    }

    /* Now walk parameters one by one */
    while (offset < pdu_len) {
        const struct Parameter *parameter;

        PDU_SIZE_CHECK (offset + 2, "cannot read parameter header");
        parameter = (const struct Parameter *)&pdu[offset];
        offset += 2;

        PDU_SIZE_CHECK (offset + parameter->parameter_len, "cannot read parameter value");
        offset += parameter->parameter_len;

        switch (parameter->parameter_id) {
        case PARAMETER_ID_TELESERVICE_ID:
            mm_obj_dbg (log_object, "    reading teleservice ID...");
            read_teleservice_id (sms_part, parameter, log_object);
            break;
        case PARAMETER_ID_SERVICE_CATEGORY:
            mm_obj_dbg (log_object, "    reading service category...");
            read_service_category (sms_part, parameter, log_object);
            break;
        case PARAMETER_ID_ORIGINATING_ADDRESS:
            mm_obj_dbg (log_object, "    reading originating address...");
            if (mm_sms_part_get_number (sms_part))
                mm_obj_dbg (log_object, "        cannot read originating address; an address field was already read");
            else
                read_address (sms_part, parameter, log_object);
            break;
        case PARAMETER_ID_ORIGINATING_SUBADDRESS:
            mm_obj_dbg (log_object, "    skipping originating subaddress...");
            break;
        case PARAMETER_ID_DESTINATION_ADDRESS:
            mm_obj_dbg (log_object, "    reading destination address...");
            if (mm_sms_part_get_number (sms_part))
                mm_obj_dbg (log_object, "        cannot read destination address; an address field was already read");
            else
                read_address (sms_part, parameter, log_object);
            break;
        case PARAMETER_ID_DESTINATION_SUBADDRESS:
            mm_obj_dbg (log_object, "    skipping destination subaddress...");
            break;
        case PARAMETER_ID_BEARER_REPLY_OPTION:
            mm_obj_dbg (log_object, "    reading bearer reply option...");
            read_bearer_reply_option (sms_part, parameter, log_object);
            break;
        case PARAMETER_ID_CAUSE_CODES:
            mm_obj_dbg (log_object, "    reading cause codes...");
            read_cause_codes (sms_part, parameter, log_object);
            break;
        case PARAMETER_ID_BEARER_DATA:
            mm_obj_dbg (log_object, "    reading bearer data...");
            read_bearer_data (sms_part, parameter, log_object);
            break;
        default:
            mm_obj_dbg (log_object, "    unknown parameter found: '%u' (ignoring)",
                    parameter->parameter_id);
            break;
        }
    }

    /* Check mandatory parameters */
    switch (message_type) {
    case MESSAGE_TYPE_POINT_TO_POINT:
        if (mm_sms_part_get_cdma_teleservice_id (sms_part) == MM_SMS_CDMA_TELESERVICE_ID_UNKNOWN)
            mm_obj_dbg (log_object, "    mandatory parameter missing: teleservice ID not found or invalid in point-to-point message");
        break;
    case MESSAGE_TYPE_BROADCAST:
        if (mm_sms_part_get_cdma_service_category (sms_part) == MM_SMS_CDMA_SERVICE_CATEGORY_UNKNOWN)
            mm_obj_dbg (log_object, "    mandatory parameter missing: service category not found or invalid in broadcast message");
        break;
    case MESSAGE_TYPE_ACKNOWLEDGE:
        if (mm_sms_part_get_message_reference (sms_part) == 0)
            mm_obj_dbg (log_object, "    mandatory parameter missing: cause codes not found or invalid in acknowledge message");
        break;
    default:
        break;
    }

#undef PDU_SIZE_CHECK

    return sms_part;
}

/*****************************************************************************/
/* Write bits; o_bits < 8; n_bits <= 8
 *
 * Byte 0            Byte 1
 * [7|6|5|4|3|2|1|0] [7|6|5|4|3|2|1|0]
 *
 * o_bits+n_bits <= 16
 *
 * NOTE! The bits being set should be 0 initially.
 */
static void
write_bits (guint8 *bytes,
            guint8 o_bits,
            guint8 n_bits,
            guint8 bits)
{
    guint8 bits_in_first;
    guint8 bits_in_second;

    g_assert (o_bits < 8);
    g_assert (n_bits <= 8);
    g_assert (o_bits + n_bits <= 16);

    /* Write only in the first byte */
    if (o_bits + n_bits <= 8) {
        bytes[0] |= (bits & ((1 << n_bits) - 1)) << (8 - o_bits - n_bits);
        return;
    }

    /* Write (8 - o_bits) in the first byte and (n_bits - (8 - o_bits)) in the second byte */
    bits_in_first = 8 - o_bits;
    bits_in_second = n_bits - bits_in_first;

    write_bits (&bytes[0], o_bits, bits_in_first, (bits >> bits_in_second));
    write_bits (&bytes[1], 0, bits_in_second, bits);
}

/*****************************************************************************/

static guint8
dtmf_from_ascii (guint8   ascii,
                 gpointer log_object)
{
    if (ascii >= '1' && ascii <= '9')
        return ascii - '0';
    if (ascii == '0')
        return 10;
    if (ascii == '*')
        return 11;
    if (ascii == '#')
        return 12;

    mm_obj_dbg (log_object, "        invalid ascii digit in dtmf conversion: %c", ascii);
    return 0;
}

static gboolean
write_teleservice_id (MMSmsPart  *part,
                      guint8     *pdu,
                      guint      *absolute_offset,
                      gpointer    log_object,
                      GError    **error)
{
    guint16 aux16;

    mm_obj_dbg (log_object, "    writing teleservice ID...");

    if (mm_sms_part_get_cdma_teleservice_id (part) != MM_SMS_CDMA_TELESERVICE_ID_WMT) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_UNSUPPORTED,
                     "Teleservice '%s' not supported",
                     mm_sms_cdma_teleservice_id_get_string (
                         mm_sms_part_get_cdma_teleservice_id (part)));
        return FALSE;
    }

    mm_obj_dbg (log_object, "        teleservice ID: %s (%u)",
                mm_sms_cdma_teleservice_id_get_string (MM_SMS_CDMA_TELESERVICE_ID_WMT),
                MM_SMS_CDMA_TELESERVICE_ID_WMT);

    /* Teleservice ID: WMT always */
    pdu[0] = PARAMETER_ID_TELESERVICE_ID;
    pdu[1] = 2; /* parameter_len, always 2 */
    aux16 = GUINT16_TO_BE (MM_SMS_CDMA_TELESERVICE_ID_WMT);
    memcpy (&pdu[2], &aux16, 2);

    *absolute_offset += 4;
    return TRUE;
}

static gboolean
write_destination_address (MMSmsPart  *part,
                           guint8     *pdu,
                           guint      *absolute_offset,
                           gpointer    log_object,
                           GError    **error)
{
    const gchar *number;
    guint bit_offset;
    guint byte_offset;
    guint n_digits;
    guint i;

    mm_obj_dbg (log_object, "    writing destination address...");

#define OFFSETS_UPDATE(n_bits) do { \
        bit_offset += n_bits;       \
        if (bit_offset >= 8) {      \
            bit_offset-=8;          \
            byte_offset++;          \
        }                           \
    } while (0)

    number = mm_sms_part_get_number (part);
    n_digits = strlen (number);

    pdu[0] = PARAMETER_ID_DESTINATION_ADDRESS;
    /* Write parameter length at the end */

    byte_offset = 2;
    bit_offset = 0;

    /* Digit mode: DTMF always */
    mm_obj_dbg (log_object, "        digit mode: dtmf");
    write_bits (&pdu[byte_offset], bit_offset, 1, DIGIT_MODE_DTMF);
    OFFSETS_UPDATE (1);

    /* Number mode: DIGIT always */
    mm_obj_dbg (log_object, "        number mode: digit");
    write_bits (&pdu[byte_offset], bit_offset, 1, NUMBER_MODE_DIGIT);
    OFFSETS_UPDATE (1);

    /* Number type and numbering plan only needed in ASCII digit mode, so skip */

    /* Number of fields */
    if (n_digits > 256) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_UNSUPPORTED,
                     "Number too long (max 256 digits, %u given)",
                     n_digits);
        return FALSE;
    }
    mm_obj_dbg (log_object, "        num fields: %u", n_digits);
    write_bits (&pdu[byte_offset], bit_offset, 8, n_digits);
    OFFSETS_UPDATE (8);

    /* Actual DTMF encoded number */
    mm_obj_dbg (log_object, "        address: %s", number);
    for (i = 0; i < n_digits; i++) {
        guint8 dtmf;

        dtmf = dtmf_from_ascii (number[i], log_object);
        if (!dtmf) {
            g_set_error (error,
                         MM_CORE_ERROR,
                         MM_CORE_ERROR_UNSUPPORTED,
                         "Unsupported character in number: '%c'. Cannot convert to DTMF",
                         number[i]);
            return FALSE;
        }
        write_bits (&pdu[byte_offset], bit_offset, 4, dtmf);
        OFFSETS_UPDATE (4);
    }

#undef OFFSETS_UPDATE

    /* Write parameter length (remove header length to offset) */
    byte_offset += !!bit_offset - 2;
    if (byte_offset > 256) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_UNSUPPORTED,
                     "Number too long (max 256 bytes, %u given)",
                     byte_offset);
        return FALSE;
    }
    pdu[1] = byte_offset;

    *absolute_offset += (2 + pdu[1]);
    return TRUE;
}

static gboolean
write_bearer_data_message_identifier (MMSmsPart  *part,
                                      guint8     *pdu,
                                      guint      *parameter_offset,
                                      gpointer    log_object,
                                      GError    **error)
{
    pdu[0] = SUBPARAMETER_ID_MESSAGE_ID;
    pdu[1] = 3; /* subparameter_len, always 3 */

    mm_obj_dbg (log_object, "        writing message identifier: submit");

    /* Message type */
    write_bits (&pdu[2], 0, 4, TELESERVICE_MESSAGE_TYPE_SUBMIT);

    /* Skip adding a message id; assume it's filled in by device */

    /* And no need for a header ind value, always false */

    *parameter_offset += 5;
    return TRUE;
}

static void
decide_best_encoding (const gchar *text,
                      gpointer     log_object,
                      GByteArray **out,
                      guint       *num_fields,
                      guint       *num_bits_per_field,
                      Encoding    *encoding)
{
    guint ascii_unsupported = 0;
    guint i;
    guint len;
    g_autoptr(GError) error = NULL;

    len = strlen (text);

    /* Check if we can do ASCII-7 */
    for (i = 0; i < len; i++) {
        if (text[i] & 0x80) {
            ascii_unsupported++;
            break;
        }
    }

    /* If ASCII-7 already supported, done we are */
    if (!ascii_unsupported) {
        *out = g_byte_array_sized_new (len);
        g_byte_array_append (*out, (const guint8 *)text, len);
        *num_fields = len;
        *num_bits_per_field = 7;
        *encoding = ENCODING_ASCII_7BIT;
        return;
    }

    /* Check if we can do Latin encoding */
    if (mm_charset_can_convert_to (text, MM_MODEM_CHARSET_8859_1)) {
        *out = g_byte_array_sized_new (len);
        if (!mm_modem_charset_byte_array_append (*out,
                                                 text,
                                                 FALSE,
                                                 MM_MODEM_CHARSET_8859_1,
                                                 &error))
            mm_obj_warn (log_object, "failed to convert to latin encoding: %s", error->message);
        *num_fields = (*out)->len;
        *num_bits_per_field = 8;
        *encoding = ENCODING_LATIN;
        return;
    }

    /* If no Latin and no ASCII, default to UTF-16 */
    *out = g_byte_array_sized_new (len * 2);
    if (!mm_modem_charset_byte_array_append (*out,
                                             text,
                                             FALSE,
                                             MM_MODEM_CHARSET_UCS2,
                                             &error))
        mm_obj_warn (log_object, "failed to convert to UTF-16 encoding: %s", error->message);
    *num_fields = (*out)->len / 2;
    *num_bits_per_field = 16;
    *encoding = ENCODING_UNICODE;
}

static gboolean
write_bearer_data_user_data (MMSmsPart  *part,
                             guint8     *pdu,
                             guint      *parameter_offset,
                             gpointer    log_object,
                             GError    **error)
{
    const gchar *text;
    const GByteArray *data;
    guint bit_offset = 0;
    guint byte_offset = 0;
    guint num_fields;
    guint num_bits_per_field;
    guint i;
    Encoding encoding;
    GByteArray *converted = NULL;
    const GByteArray *aux;
    guint num_bits_per_iter;

    mm_obj_dbg (log_object, "        writing user data...");

#define OFFSETS_UPDATE(n_bits) do { \
        bit_offset += n_bits;       \
        if (bit_offset >= 8) {      \
            bit_offset-=8;          \
            byte_offset++;          \
        }                           \
    } while (0)

    text = mm_sms_part_get_text (part);
    data = mm_sms_part_get_data (part);
    g_assert (text || data);
    g_assert (!(!text && !data));

    pdu[0] = SUBPARAMETER_ID_USER_DATA;
    /* Write parameter length at the end */
    byte_offset = 2;
    bit_offset = 0;

    /* Text or Data */
    if (text) {
        decide_best_encoding (text,
                              log_object,
                              &converted,
                              &num_fields,
                              &num_bits_per_field,
                              &encoding);
        aux = (const GByteArray *)converted;
    } else {
        aux = data;
        num_fields = data->len;
        num_bits_per_field = 8;
        encoding = ENCODING_OCTET;
    }

    /* Message encoding*/
    mm_obj_dbg (log_object, "            message encoding: %s", encoding_to_string (encoding));
    write_bits (&pdu[byte_offset], bit_offset, 5, encoding);
    OFFSETS_UPDATE (5);

    /* Number of fields */
    if (num_fields > 256) {
        if (converted)
            g_byte_array_unref (converted);
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_UNSUPPORTED,
                     "Data too long (max 256 fields, %u given)",
                     num_fields);
        return FALSE;
    }
    mm_obj_dbg (log_object, "            num fields: %u", num_fields);
    write_bits (&pdu[byte_offset], bit_offset, 8, num_fields);
    OFFSETS_UPDATE (8);

    /* For ASCII-7, write 7 bits in each iteration; for the remaining ones
     * go byte per byte */
    if (text)
        mm_obj_dbg (log_object, "            text: '%s'", text);
    else
        mm_obj_dbg (log_object, "            data: (%u bytes)", num_fields);
    num_bits_per_iter = num_bits_per_field < 8 ? num_bits_per_field : 8;
    for (i = 0; i < aux->len; i++) {
        write_bits (&pdu[byte_offset], bit_offset, num_bits_per_iter, aux->data[i]);
        OFFSETS_UPDATE (num_bits_per_iter);
    }

    if (converted)
        g_byte_array_unref (converted);

#undef OFFSETS_UPDATE

    /* Write subparameter length (remove header length to offset) */
    byte_offset += !!bit_offset - 2;
    if (byte_offset > 256) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_UNSUPPORTED,
                     "Data or Text too long (max 256 bytes, %u given)",
                     byte_offset);
        return FALSE;
    }
    pdu[1] = byte_offset;

    *parameter_offset += (2 + pdu[1]);
    return TRUE;
}

static gboolean
write_bearer_data (MMSmsPart  *part,
                   guint8     *pdu,
                   guint      *absolute_offset,
                   gpointer    log_object,
                   GError    **error)
{
    GError *inner_error = NULL;
    guint offset = 0;

    mm_obj_dbg (log_object, "    writing bearer data...");

    pdu[0] = PARAMETER_ID_BEARER_DATA;
    /* Write parameter length at the end */

    offset = 2;
    if (!write_bearer_data_message_identifier (part, &pdu[offset], &offset, log_object, &inner_error))
        mm_obj_dbg (log_object, "error writing message identifier: %s", inner_error->message);
    else if (!write_bearer_data_user_data (part, &pdu[offset], &offset, log_object, &inner_error))
        mm_obj_dbg (log_object, "error writing user data: %s", inner_error->message);

    if (inner_error) {
        g_propagate_error (error, inner_error);
        g_prefix_error (error, "Error writing bearer data: ");
        return FALSE;
    }

    /* Write parameter length (remove header length to offset) */
    offset -= 2;
    if (offset > 256) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_UNSUPPORTED,
                     "Bearer data too long (max 256 bytes, %u given)",
                     offset);
        return FALSE;
    }
    pdu[1] = offset;

    *absolute_offset += (2 + pdu[1]);
    return TRUE;
}

guint8 *
mm_sms_part_cdma_get_submit_pdu (MMSmsPart  *part,
                                 guint      *out_pdulen,
                                 gpointer    log_object,
                                 GError    **error)
{
    GError *inner_error = NULL;
    guint offset = 0;
    guint8 *pdu;

    g_return_val_if_fail (mm_sms_part_get_number (part) != NULL, NULL);
    g_return_val_if_fail (mm_sms_part_get_text (part) != NULL || mm_sms_part_get_data (part) != NULL, NULL);

    if (mm_sms_part_get_pdu_type (part) != MM_SMS_PDU_TYPE_CDMA_SUBMIT) {
        g_set_error (error,
                     MM_MESSAGE_ERROR,
                     MM_MESSAGE_ERROR_INVALID_PDU_PARAMETER,
                     "Invalid PDU type to generate a 'submit' PDU: '%s'",
                     mm_sms_pdu_type_get_string (mm_sms_part_get_pdu_type (part)));
        return NULL;
    }

    mm_obj_dbg (log_object, "creating PDU for part...");

    /* Current max size estimations:
     *  Message type: 1 byte
     *  Teleservice ID: 5 bytes
     *  Destination address: 2 + 256 bytes
     *  Bearer data: 2 + 256 bytes
     */
    pdu = g_malloc0 (1024);

    /* First byte: SMS message type */
    pdu[offset++] = MESSAGE_TYPE_POINT_TO_POINT;

    if (!write_teleservice_id (part, &pdu[offset], &offset, log_object, &inner_error))
        mm_obj_dbg (log_object, "error writing teleservice ID: %s", inner_error->message);
    else if (!write_destination_address (part, &pdu[offset], &offset, log_object, &inner_error))
        mm_obj_dbg (log_object, "error writing destination address: %s", inner_error->message);
    else if (!write_bearer_data (part, &pdu[offset], &offset, log_object, &inner_error))
        mm_obj_dbg (log_object, "error writing bearer data: %s", inner_error->message);

    if (inner_error) {
        g_propagate_error (error, inner_error);
        g_prefix_error (error, "Cannot create CDMA SMS part: ");
        g_free (pdu);
        return NULL;
    }

    *out_pdulen = offset;
    return pdu;
}