aboutsummaryrefslogtreecommitdiff
path: root/src/mm-modem-helpers.c
blob: 53aebb82a1990e2c9e2f7efd3bcabfdc34ffd01f (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
/* -*- 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) 2008 - 2009 Novell, Inc.
 * Copyright (C) 2009 - 2011 Red Hat, Inc.
 */

#include <config.h>
#include <stdio.h>
#include <ctype.h>
#include <glib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>

#include <ModemManager.h>
#include <libmm-common.h>

#include "mm-modem-helpers.h"
#include "mm-log.h"

const char *
mm_strip_tag (const char *str, const char *cmd)
{
    const char *p = str;

    if (p) {
        if (!strncmp (p, cmd, strlen (cmd)))
            p += strlen (cmd);
        while (isspace (*p))
            p++;
    }
    return p;
}

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

static void
mm_3gpp_network_info_free (MM3gppNetworkInfo *info)
{
    g_free (info->operator_long);
    g_free (info->operator_short);
    g_free (info->operator_code);
    g_free (info);
}

void
mm_3gpp_network_info_list_free (GList *info_list)
{
    g_list_foreach (info_list, (GFunc)mm_3gpp_network_info_free, NULL);
    g_list_free (info_list);
}

static MMModemAccessTechnology
get_mm_access_tech_from_etsi_access_tech (guint act)
{
    /* See ETSI TS 27.007 */
    switch (act) {
    case 0:
        return MM_MODEM_ACCESS_TECHNOLOGY_GSM;
    case 1:
        return MM_MODEM_ACCESS_TECHNOLOGY_GSM_COMPACT;
    case 2:
        return MM_MODEM_ACCESS_TECHNOLOGY_UMTS;
    case 3:
        return MM_MODEM_ACCESS_TECHNOLOGY_EDGE;
    case 4:
        return MM_MODEM_ACCESS_TECHNOLOGY_HSDPA;
    case 5:
        return MM_MODEM_ACCESS_TECHNOLOGY_HSUPA;
    case 6:
        return MM_MODEM_ACCESS_TECHNOLOGY_HSPA;
    case 7:
        return MM_MODEM_ACCESS_TECHNOLOGY_LTE;
    default:
        return MM_MODEM_ACCESS_TECHNOLOGY_UNKNOWN;
    }
}

static gchar *
get_unquoted_scan_value (GMatchInfo *info, guint32 num)
{
    gchar *quoted;
    gsize len;

    quoted = g_match_info_fetch (info, num);
    if (!quoted)
        return NULL;

    len = strlen (quoted);

    /* Unquote the item if needed */
    if ((len >= 2) && (quoted[0] == '"') && (quoted[len - 1] == '"')) {
        quoted[0] = ' ';
        quoted[len - 1] = ' ';
        quoted = g_strstrip (quoted);
    }

    if (!strlen (quoted)) {
        g_free (quoted);
        return NULL;
    }

    return quoted;
}

static MMModem3gppNetworkAvailability
parse_network_status (const gchar *str)
{
    /* Expecting a value between '0' and '3' inclusive */
    if (!str ||
        strlen (str) != 1 ||
        str[0] < '0' ||
        str[0] > '3') {
        mm_warn ("Cannot parse network status: '%s'", str);
        return MM_MODEM_3GPP_NETWORK_AVAILABILITY_UNKNOWN;
    }

    return (MMModem3gppNetworkAvailability) (str[0] - '0');
}

static MMModemAccessTechnology
parse_access_tech (const gchar *str)
{
    /* Recognized access technologies are between '0' and '7' inclusive... */
    if (!str ||
        strlen (str) != 1 ||
        str[0] < '0' ||
        str[0] > '7') {
        mm_warn ("Cannot parse access tech: '%s'", str);
        return MM_MODEM_ACCESS_TECHNOLOGY_UNKNOWN;
    }

    return get_mm_access_tech_from_etsi_access_tech (str[0] - '0');
}

GList *
mm_3gpp_parse_scan_response (const gchar *reply,
                             GError **error)
{
    GRegex *r;
    GList *info_list = NULL;
    GMatchInfo *match_info;
    gboolean umts_format = TRUE;
    GEnumClass *network_availability_class;
    GFlagsClass *access_tech_class;
    GError *inner_error = NULL;

    g_return_val_if_fail (reply != NULL, NULL);
    if (error)
        g_return_val_if_fail (*error == NULL, NULL);

    if (!strstr (reply, "+COPS: ")) {
        g_set_error_literal (error,
                             MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Could not parse scan results.");
        return NULL;
    }

    reply = strstr (reply, "+COPS: ") + 7;

    /* Cell access technology (GSM, UTRAN, etc) got added later and not all
     * modems implement it.  Some modesm have quirks that make it hard to
     * use one regular experession for matching both pre-UMTS and UMTS
     * responses.  So try UMTS-format first and fall back to pre-UMTS if
     * we get no UMTS-formst matches.
     */

    /* Quirk: Sony-Ericsson TM-506 sometimes includes a stray ')' like so,
     *        which is what makes it hard to match both pre-UMTS and UMTS in
     *        the same regex:
     *
     *       +COPS: (2,"","T-Mobile","31026",0),(1,"AT&T","AT&T","310410"),0)
     */

    r = g_regex_new ("\\((\\d),([^,\\)]*),([^,\\)]*),([^,\\)]*)[\\)]?,(\\d)\\)", G_REGEX_UNGREEDY, 0, &inner_error);
    if (inner_error) {
        mm_err ("Invalid regular expression: %s", inner_error->message);
        g_error_free (inner_error);
        g_set_error_literal (error,
                             MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Could not parse scan results");
        return NULL;
    }

    /* If we didn't get any hits, try the pre-UMTS format match */
    if (!g_regex_match (r, reply, 0, &match_info)) {
        g_regex_unref (r);
        g_match_info_free (match_info);
        match_info = NULL;

        /* Pre-UMTS format doesn't include the cell access technology after
         * the numeric operator element.
         *
         * Ex: Motorola C-series (BUSlink SCWi275u) like so:
         *
         *       +COPS: (2,"T-Mobile","","310260"),(0,"Cingular Wireless","","310410")
         */

        /* Quirk: Some Nokia phones (N80) don't send the quotes for empty values:
         *
         *       +COPS: (2,"T - Mobile",,"31026"),(1,"Einstein PCS",,"31064"),(1,"Cingular",,"31041"),,(0,1,3),(0,2)
         */

        r = g_regex_new ("\\((\\d),([^,\\)]*),([^,\\)]*),([^\\)]*)\\)", G_REGEX_UNGREEDY, 0, &inner_error);
        if (inner_error) {
            mm_err ("Invalid regular expression: %s", inner_error->message);
            g_error_free (inner_error);
            g_set_error_literal (error,
                                 MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                                 "Could not parse scan results");
            return NULL;
        }

        g_regex_match (r, reply, 0, &match_info);
        umts_format = FALSE;
    }

    network_availability_class = G_ENUM_CLASS (g_type_class_ref (MM_TYPE_MODEM_3GPP_NETWORK_AVAILABILITY));
    access_tech_class = G_FLAGS_CLASS (g_type_class_ref (MM_TYPE_MODEM_ACCESS_TECHNOLOGY));

    /* Parse the results */
    while (g_match_info_matches (match_info)) {
        MM3gppNetworkInfo *info;
        gchar *tmp;
        gboolean valid = FALSE;

        info = g_new0 (MM3gppNetworkInfo, 1);

        tmp = get_unquoted_scan_value (match_info, 1);
        info->status = parse_network_status (tmp);
        g_free (tmp);

        info->operator_long = get_unquoted_scan_value (match_info, 2);
        info->operator_short = get_unquoted_scan_value (match_info, 3);
        info->operator_code = get_unquoted_scan_value (match_info, 4);

        /* Only try for access technology with UMTS-format matches.
         * If none give, assume GSM */
        tmp = (umts_format ?
               get_unquoted_scan_value (match_info, 5) :
               NULL);
        info->access_tech = (tmp ?
                             parse_access_tech (tmp) :
                             MM_MODEM_ACCESS_TECHNOLOGY_GSM);
        g_free (tmp);

        /* If the operator number isn't valid (ie, at least 5 digits),
         * ignore the scan result; it's probably the parameter stuff at the
         * end of the +COPS response.  The regex will sometimes catch this
         * but there's no good way to ignore it.
         */
        if (info->operator_code && (strlen (info->operator_code) >= 5)) {
            valid = TRUE;
            tmp = info->operator_code;
            while (*tmp) {
                if (!isdigit (*tmp) && (*tmp != '-')) {
                    valid = FALSE;
                    break;
                }
                tmp++;
            }
        }

        if (valid) {
            GEnumValue *network_availability;
            GFlagsValue *access_tech;

            network_availability = g_enum_get_value (network_availability_class,
                                                     info->status);
            access_tech = g_flags_get_first_value (access_tech_class,
                                                   info->access_tech);

            mm_dbg ("Found network '%s' ('%s','%s'); availability: %s, access tech: %s",
                    info->operator_code,
                    info->operator_short ? info->operator_short : "no short name",
                    info->operator_long ? info->operator_long : "no long name",
                    network_availability->value_nick,
                    access_tech->value_nick);

            info_list = g_list_prepend (info_list, info);
        }
        else
            mm_3gpp_network_info_free (info);

        g_match_info_next (match_info, NULL);
    }

    g_match_info_free (match_info);
    g_regex_unref (r);

    g_type_class_unref (network_availability_class);
    g_type_class_unref (access_tech_class);

    return info_list;
}

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

static void
mm_3gpp_pdp_context_free (MM3gppPdpContext *pdp)
{
    g_free (pdp->pdp_type);
    g_free (pdp->apn);
    g_free (pdp);
}

void
mm_3gpp_pdp_context_list_free (GList *list)
{
    g_list_foreach (list, (GFunc)mm_3gpp_pdp_context_free, NULL);
    g_list_free (list);
}

static gint
mm_3gpp_pdp_context_cmp (MM3gppPdpContext *a,
                         MM3gppPdpContext *b)
{
    return (a->cid - b->cid);
}

GList *
mm_3gpp_parse_pdp_query_response (const gchar *reply,
                                  GError **error)
{
    GError *inner_error = NULL;
    GRegex *r;
    GMatchInfo *match_info;
    GList *list;

    if (!reply[0])
        /* No APNs configured, all done */
        return NULL;

    list = NULL;
    r = g_regex_new ("\\+CGDCONT:\\s*(\\d+)\\s*,([^,\\)]*),([^,\\)]*),([^,\\)]*)",
                     G_REGEX_DOLLAR_ENDONLY | G_REGEX_RAW,
                     0, &inner_error);
    if (r) {
        g_regex_match_full (r, reply, strlen (reply), 0, 0, &match_info, &inner_error);

        while (!inner_error &&
               g_match_info_matches (match_info)) {
            MM3gppPdpContext *pdp;
            gchar *cid;

            pdp = g_new0 (MM3gppPdpContext, 1);
            cid = g_match_info_fetch (match_info, 1);
            pdp->cid = (guint)atoi (cid);
            pdp->pdp_type = get_unquoted_scan_value (match_info, 2);
            pdp->apn = get_unquoted_scan_value (match_info, 3);
            g_free (cid);

            list = g_list_prepend (list, pdp);

            g_match_info_next (match_info, &inner_error);
        }

        g_match_info_free (match_info);
        g_regex_unref (r);
    }

    if (inner_error) {
        mm_3gpp_pdp_context_list_free (list);
        g_propagate_error (error, inner_error);
        g_prefix_error (error, "Couldn't properly parse list of PDP contexts. ");
        return NULL;
    }

    list = g_list_sort (list, (GCompareFunc)mm_3gpp_pdp_context_cmp);

    return list;
}

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

/* +CREG: <stat>                      (GSM 07.07 CREG=1 unsolicited) */
#define CREG1 "\\+(CREG|CGREG):\\s*0*([0-9])"

/* +CREG: <n>,<stat>                  (GSM 07.07 CREG=1 solicited) */
#define CREG2 "\\+(CREG|CGREG):\\s*0*([0-9]),\\s*0*([0-9])"

/* +CREG: <stat>,<lac>,<ci>           (GSM 07.07 CREG=2 unsolicited) */
#define CREG3 "\\+(CREG|CGREG):\\s*0*([0-9]),\\s*([^,\\s]*)\\s*,\\s*([^,\\s]*)"

/* +CREG: <n>,<stat>,<lac>,<ci>       (GSM 07.07 solicited and some CREG=2 unsolicited) */
#define CREG4 "\\+(CREG|CGREG):\\s*0*([0-9]),\\s*0*([0-9])\\s*,\\s*([^,]*)\\s*,\\s*([^,\\s]*)"

/* +CREG: <stat>,<lac>,<ci>,<AcT>     (ETSI 27.007 CREG=2 unsolicited) */
#define CREG5 "\\+(CREG|CGREG):\\s*0*([0-9])\\s*,\\s*([^,\\s]*)\\s*,\\s*([^,\\s]*)\\s*,\\s*0*([0-9])"

/* +CREG: <n>,<stat>,<lac>,<ci>,<AcT> (ETSI 27.007 solicited and some CREG=2 unsolicited) */
#define CREG6 "\\+(CREG|CGREG):\\s*0*([0-9]),\\s*0*([0-9])\\s*,\\s*([^,\\s]*)\\s*,\\s*([^,\\s]*)\\s*,\\s*0*([0-9])"

/* +CREG: <n>,<stat>,<lac>,<ci>,<AcT?>,<something> (Samsung Wave S8500) */
/* '<CR><LF>+CREG: 2,1,000B,2816, B, C2816<CR><LF><CR><LF>OK<CR><LF>' */
#define CREG7 "\\+(CREG|CGREG):\\s*0*([0-9]),\\s*0*([0-9])\\s*,\\s*([^,\\s]*)\\s*,\\s*([^,\\s]*)\\s*,\\s*([^,\\s]*)\\s*,\\s*[^,\\s]*"

/* +CREG: <stat>,<lac>,<ci>,<AcT>,<RAC> (ETSI 27.007 v9.20 CREG=2 unsolicited with RAC) */
#define CREG8 "\\+(CREG|CGREG):\\s*(\\d{1})\\s*,\\s*([^,\\s]*)\\s*,\\s*([^,\\s]*)\\s*,\\s*(\\d{1,2})\\s*,\\s*([^,\\s]*)"

GPtrArray *
mm_3gpp_creg_regex_get (gboolean solicited)
{
    GPtrArray *array = g_ptr_array_sized_new (7);
    GRegex *regex;

    /* #1 */
    if (solicited)
        regex = g_regex_new (CREG1 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG1 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #2 */
    if (solicited)
        regex = g_regex_new (CREG2 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG2 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #3 */
    if (solicited)
        regex = g_regex_new (CREG3 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG3 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #4 */
    if (solicited)
        regex = g_regex_new (CREG4 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG4 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #5 */
    if (solicited)
        regex = g_regex_new (CREG5 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG5 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #6 */
    if (solicited)
        regex = g_regex_new (CREG6 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG6 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #7 */
    if (solicited)
        regex = g_regex_new (CREG7 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG7 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    /* #8 */
    if (solicited)
        regex = g_regex_new (CREG8 "$", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    else
        regex = g_regex_new ("\\r\\n" CREG8 "\\r\\n", G_REGEX_RAW | G_REGEX_OPTIMIZE, 0, NULL);
    g_assert (regex);
    g_ptr_array_add (array, regex);

    return array;
}

void
mm_3gpp_creg_regex_destroy (GPtrArray *array)
{
    g_ptr_array_foreach (array, (GFunc) g_regex_unref, NULL);
    g_ptr_array_free (array, TRUE);
}

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

GRegex *
mm_3gpp_ciev_regex_get (void)
{
    return g_regex_new ("\\r\\n\\+CIEV: (\\d+),(\\d)\\r\\n",
                        G_REGEX_RAW | G_REGEX_OPTIMIZE,
                        0,
                        NULL);
}

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

static gulong
parse_uint (char *str, int base, glong nmin, glong nmax, gboolean *valid)
{
    gulong ret = 0;
    char *endquote;

    *valid = FALSE;
    if (!str)
        return 0;

    /* Strip quotes */
    if (str[0] == '"')
        str++;
    endquote = strchr (str, '"');
    if (endquote)
        *endquote = '\0';

    if (strlen (str)) {
        ret = strtol (str, NULL, base);
        if ((nmin == nmax) || (ret >= nmin && ret <= nmax))
            *valid = TRUE;
    }
    return *valid ? (guint) ret : 0;
}

static gboolean
item_is_lac_not_stat (GMatchInfo *info, guint32 item)
{
    char *str;
    gboolean is_lac = FALSE;

    /* A <stat> will always be a single digit, without quotes */
    str = g_match_info_fetch (info, item);
    g_assert (str);
    is_lac = (strchr (str, '"') || strlen (str) > 1);
    g_free (str);
    return is_lac;
}

gboolean
mm_3gpp_parse_creg_response (GMatchInfo *info,
                             MMModem3gppRegistrationState *out_reg_state,
                             gulong *out_lac,
                             gulong *out_ci,
                             MMModemAccessTechnology *out_act,
                             gboolean *out_cgreg,
                             GError **error)
{
    gboolean success = FALSE, foo;
    gint n_matches, act = -1;
    gulong stat = 0, lac = 0, ci = 0;
    guint istat = 0, ilac = 0, ici = 0, iact = 0;
    char *str;

    g_return_val_if_fail (info != NULL, FALSE);
    g_return_val_if_fail (out_reg_state != NULL, FALSE);
    g_return_val_if_fail (out_lac != NULL, FALSE);
    g_return_val_if_fail (out_ci != NULL, FALSE);
    g_return_val_if_fail (out_act != NULL, FALSE);
    g_return_val_if_fail (out_cgreg != NULL, FALSE);

    str = g_match_info_fetch (info, 1);
    if (str && strstr (str, "CGREG"))
        *out_cgreg = TRUE;
    g_free (str);

    /* Normally the number of matches could be used to determine what each
     * item is, but we have overlap in one case.
     */
    n_matches = g_match_info_get_match_count (info);
    if (n_matches == 3) {
        /* CREG=1: +CREG: <stat> */
        istat = 2;
    } else if (n_matches == 4) {
        /* Solicited response: +CREG: <n>,<stat> */
        istat = 3;
    } else if (n_matches == 5) {
        /* CREG=2 (GSM 07.07): +CREG: <stat>,<lac>,<ci> */
        istat = 2;
        ilac = 3;
        ici = 4;
    } else if (n_matches == 6) {
        /* CREG=2 (ETSI 27.007): +CREG: <stat>,<lac>,<ci>,<AcT>
         * CREG=2 (non-standard): +CREG: <n>,<stat>,<lac>,<ci>
         */

        /* Check if the third item is the LAC to distinguish the two cases */
        if (item_is_lac_not_stat (info, 3)) {
            istat = 2;
            ilac = 3;
            ici = 4;
            iact = 5;
        } else {
            istat = 3;
            ilac = 4;
            ici = 5;
        }
    } else if (n_matches == 7) {
        /* CREG=2 (solicited):            +CREG: <n>,<stat>,<lac>,<ci>,<AcT>
         * CREG=2 (unsolicited with RAC): +CREG: <stat>,<lac>,<ci>,<AcT>,<RAC>
         */

        /* Check if the third item is the LAC to distinguish the two cases */
        if (item_is_lac_not_stat (info, 3)) {
            istat = 2;
            ilac = 3;
            ici = 4;
            iact = 5;
        } else {
            istat = 3;
            ilac = 4;
            ici = 5;
            iact = 6;
        }
     }

    /* Status */
    str = g_match_info_fetch (info, istat);
    stat = parse_uint (str, 10, 0, 5, &success);
    g_free (str);
    if (!success) {
        g_set_error_literal (error,
                             MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Could not parse the registration status response");
        return FALSE;
    }

    /* Location Area Code */
    if (ilac) {
        /* FIXME: some phones apparently swap the LAC bytes (LG, SonyEricsson,
         * Sagem).  Need to handle that.
         */
        str = g_match_info_fetch (info, ilac);
        lac = parse_uint (str, 16, 1, 0xFFFF, &foo);
        g_free (str);
    }

    /* Cell ID */
    if (ici) {
        str = g_match_info_fetch (info, ici);
        ci = parse_uint (str, 16, 1, 0x0FFFFFFE, &foo);
        g_free (str);
    }

    /* Access Technology */
    if (iact) {
        str = g_match_info_fetch (info, iact);
        act = (gint) parse_uint (str, 10, 0, 7, &foo);
        g_free (str);
        if (!foo)
            act = -1;
    }

    /* 'roaming' is the last valid state */
    if (stat > MM_MODEM_3GPP_REGISTRATION_STATE_ROAMING) {
        mm_warn ("Registration State '%lu' is unknown", stat);
        stat = MM_MODEM_3GPP_REGISTRATION_STATE_UNKNOWN;
    }

    *out_reg_state = (MMModem3gppRegistrationState) stat;
    if (stat != MM_MODEM_3GPP_REGISTRATION_STATE_UNKNOWN) {
        /* Don't fill in lac/ci/act if the device's state is unknown */
        *out_lac = lac;
        *out_ci = ci;

        *out_act = get_mm_access_tech_from_etsi_access_tech (act);
    }
    return TRUE;
}

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

gboolean
mm_cdma_parse_spservice_response (const char *reply,
                                  MMModemCdmaRegistrationState *out_cdma_1x_state,
                                  MMModemCdmaRegistrationState *out_evdo_state)
{
    const char *p;

    g_return_val_if_fail (reply != NULL, FALSE);
    g_return_val_if_fail (out_cdma_1x_state != NULL, FALSE);
    g_return_val_if_fail (out_evdo_state != NULL, FALSE);

    p = mm_strip_tag (reply, "+SPSERVICE:");
    if (!isdigit (*p))
        return FALSE;

    switch (atoi (p)) {
    case 0:   /* no service */
        *out_cdma_1x_state = MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN;
        *out_evdo_state = MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN;
        break;
    case 1:   /* 1xRTT */
        *out_cdma_1x_state = MM_MODEM_CDMA_REGISTRATION_STATE_REGISTERED;
        *out_evdo_state = MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN;
        break;
    case 2:   /* EVDO rev 0 */
    case 3:   /* EVDO rev A */
        *out_cdma_1x_state = MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN;
        *out_evdo_state = MM_MODEM_CDMA_REGISTRATION_STATE_REGISTERED;
        break;
    default:
        return FALSE;
    }
    return TRUE;
}

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

typedef struct {
    int num;
    gboolean roam_ind;
    const char *banner;
} EriItem;

/* NOTE: these may be Sprint-specific for now... */
static const EriItem eris[] = {
    { 0,  TRUE,  "Digital or Analog Roaming" },
    { 1,  FALSE, "Home" },
    { 2,  TRUE,  "Digital or Analog Roaming" },
    { 3,  TRUE,  "Out of neighborhood" },
    { 4,  TRUE,  "Out of building" },
    { 5,  TRUE,  "Preferred system" },
    { 6,  TRUE,  "Available System" },
    { 7,  TRUE,  "Alliance Partner" },
    { 8,  TRUE,  "Premium Partner" },
    { 9,  TRUE,  "Full Service Functionality" },
    { 10, TRUE,  "Partial Service Functionality" },
    { 64, TRUE,  "Preferred system" },
    { 65, TRUE,  "Available System" },
    { 66, TRUE,  "Alliance Partner" },
    { 67, TRUE,  "Premium Partner" },
    { 68, TRUE,  "Full Service Functionality" },
    { 69, TRUE,  "Partial Service Functionality" },
    { 70, TRUE,  "Analog A" },
    { 71, TRUE,  "Analog B" },
    { 72, TRUE,  "CDMA 800 A" },
    { 73, TRUE,  "CDMA 800 B" },
    { 74, TRUE,  "International Roaming" },
    { 75, TRUE,  "Extended Network" },
    { 76, FALSE,  "Campus" },
    { 77, FALSE,  "In Building" },
    { 78, TRUE,  "Regional" },
    { 79, TRUE,  "Community" },
    { 80, TRUE,  "Business" },
    { 81, TRUE,  "Zone 1" },
    { 82, TRUE,  "Zone 2" },
    { 83, TRUE,  "National" },
    { 84, TRUE,  "Local" },
    { 85, TRUE,  "City" },
    { 86, TRUE,  "Government" },
    { 87, TRUE,  "USA" },
    { 88, TRUE,  "State" },
    { 89, TRUE,  "Resort" },
    { 90, TRUE,  "Headquarters" },
    { 91, TRUE,  "Personal" },
    { 92, FALSE,  "Home" },
    { 93, TRUE,  "Residential" },
    { 94, TRUE,  "University" },
    { 95, TRUE,  "College" },
    { 96, TRUE,  "Hotel Guest" },
    { 97, TRUE,  "Rental" },
    { 98, FALSE,  "Corporate" },
    { 99, FALSE,  "Home Provider" },
    { 100, FALSE,  "Campus" },
    { 101, FALSE,  "In Building" },
    { 102, TRUE,  "Regional" },
    { 103, TRUE,  "Community" },
    { 104, TRUE,  "Business" },
    { 105, TRUE,  "Zone 1" },
    { 106, TRUE,  "Zone 2" },
    { 107, TRUE,  "National" },
    { 108, TRUE,  "Local" },
    { 109, TRUE,  "City" },
    { 110, TRUE,  "Government" },
    { 111, TRUE,  "USA" },
    { 112, TRUE,  "State" },
    { 113, TRUE,  "Resort" },
    { 114, TRUE,  "Headquarters" },
    { 115, TRUE,  "Personal" },
    { 116, FALSE,  "Home" },
    { 117, TRUE,  "Residential" },
    { 118, TRUE,  "University" },
    { 119, TRUE,  "College" },
    { 120, TRUE,  "Hotel Guest" },
    { 121, TRUE,  "Rental" },
    { 122, FALSE,  "Corporate" },
    { 123, FALSE,  "Home Provider" },
    { 124, TRUE,  "International" },
    { 125, TRUE,  "International" },
    { 126, TRUE,  "International" },
    { 127, FALSE,  "Premium Service" },
    { 128, FALSE,  "Enhanced Service" },
    { 129, FALSE,  "Enhanced Digital" },
    { 130, FALSE,  "Enhanced Roaming" },
    { 131, FALSE,  "Alliance Service" },
    { 132, FALSE,  "Alliance Network" },
    { 133, FALSE,  "Data Roaming" },    /* Sprint: Vision Roaming */
    { 134, FALSE,  "Extended Service" },
    { 135, FALSE,  "Expanded Services" },
    { 136, FALSE,  "Expanded Network" },
    { 137, TRUE,  "Premium Service" },
    { 138, TRUE,  "Enhanced Service" },
    { 139, TRUE,  "Enhanced Digital" },
    { 140, TRUE,  "Enhanced Roaming" },
    { 141, TRUE,  "Alliance Service" },
    { 142, TRUE,  "Alliance Network" },
    { 143, TRUE,  "Data Roaming" },    /* Sprint: Vision Roaming */
    { 144, TRUE,  "Extended Service" },
    { 145, TRUE,  "Expanded Services" },
    { 146, TRUE,  "Expanded Network" },
    { 147, TRUE,  "Premium Service" },
    { 148, TRUE,  "Enhanced Service" },
    { 149, TRUE,  "Enhanced Digital" },
    { 150, TRUE,  "Enhanced Roaming" },
    { 151, TRUE,  "Alliance Service" },
    { 152, TRUE,  "Alliance Network" },
    { 153, TRUE,  "Data Roaming" },    /* Sprint: Vision Roaming */
    { 154, TRUE,  "Extended Service" },
    { 155, TRUE,  "Expanded Services" },
    { 156, TRUE,  "Expanded Network" },
    { 157, TRUE,  "Premium International" },
    { 158, TRUE,  "Premium International" },
    { 159, TRUE,  "Premium International" },
    { 160, TRUE,  NULL },
    { 161, TRUE,  NULL },
    { 162, FALSE,  NULL },
    { 163, FALSE,  NULL },
    { 164, FALSE,  "Extended Voice/Data Network" },
    { 165, FALSE,  "Extended Voice/Data Network" },
    { 166, TRUE,  "Extended Voice/Data Network" },
    { 167, FALSE,  "Extended Broadband" },
    { 168, FALSE,  "Extended Broadband" },
    { 169, TRUE,  "Extended Broadband" },
    { 170, FALSE,  "Extended Data" },
    { 171, FALSE,  "Extended Data" },
    { 172, TRUE,  "Extended Data" },
    { 173, FALSE,  "Extended Data Network" },
    { 174, FALSE,  "Extended Data Network" },
    { 175, TRUE,  "Extended Data Network" },
    { 176, FALSE,  "Extended Network" },
    { 177, FALSE,  "Extended Network" },
    { 178, TRUE,  "Extended Network" },
    { 179, FALSE,  "Extended Service" },
    { 180, TRUE,  "Extended Service" },
    { 181, FALSE,  "Extended Voice" },
    { 182, FALSE,  "Extended Voice" },
    { 183, TRUE,  "Extended Voice" },
    { 184, FALSE,  "Extended Voice/Data" },
    { 185, FALSE,  "Extended Voice/Data" },
    { 186, TRUE,  "Extended Voice/Data" },
    { 187, FALSE,  "Extended Voice Network" },
    { 188, FALSE,  "Extended Voice Network" },
    { 189, TRUE,  "Extended Voice Network" },
    { 190, FALSE,  "Extended Voice/Data" },
    { 191, FALSE,  "Extended Voice/Data" },
    { 192, TRUE,  "Extended Voice/Data" },
    { 193, TRUE,  "International" },
    { 194, FALSE,  "International Services" },
    { 195, FALSE,  "International Voice" },
    { 196, FALSE,  "International Voice/Data" },
    { 197, FALSE,  "International Voice/Data" },
    { 198, TRUE,  "International Voice/Data" },
    { 199, FALSE,  "Extended Voice/Data Network" },
    { 200, TRUE,  "Extended Voice/Data Network" },
    { 201, TRUE,  "Extended Voice/Data Network" },
    { 202, FALSE,  "Extended Broadband" },
    { 203, TRUE,  "Extended Broadband" },
    { 204, TRUE,  "Extended Broadband" },
    { 205, FALSE,  "Extended Data" },
    { 206, TRUE,  "Extended Data" },
    { 207, TRUE,  "Extended Data" },
    { 208, FALSE,  "Extended Data Network" },
    { 209, TRUE,  "Extended Data Network" },
    { 210, TRUE,  "Extended Data Network" },
    { 211, FALSE,  "Extended Network" },
    { 212, TRUE,  "Extended Network" },
    { 213, FALSE,  "Extended Service" },
    { 214, TRUE,  "Extended Service" },
    { 215, TRUE,  "Extended Service" },
    { 216, FALSE,  "Extended Voice" },
    { 217, TRUE,  "Extended Voice" },
    { 218, TRUE,  "Extended Voice" },
    { 219, FALSE,  "Extended Voice/Data" },
    { 220, TRUE,  "Extended Voice/Data" },
    { 221, TRUE,  "Extended Voice/Data" },
    { 222, FALSE,  "Extended Voice Network" },
    { 223, FALSE,  "Extended Voice Network" },
    { 224, TRUE,  "Extended Voice Network" },
    { 225, FALSE,  "Extended Voice/Data" },
    { 226, TRUE,  "Extended Voice/Data" },
    { 227, TRUE,  "Extended Voice/Data" },
    { 228, TRUE,  "International" },
    { 229, TRUE,  "International" },
    { 230, TRUE,  "International Services" },
    { 231, TRUE,  "International Voice" },
    { 232, FALSE,  "International Voice/Data" },
    { 233, TRUE,  "International Voice/Data" },
    { 234, TRUE,  "International Voice/Data" },
    { 235, TRUE,  "Premium International" },
    { 236, TRUE,  NULL },
    { 237, TRUE,  NULL },
    { 238, FALSE,  NULL },
    { 239, FALSE,  NULL },
    { -1, FALSE, NULL },
};

gboolean
mm_cdma_parse_eri (const char *reply,
                   gboolean *out_roaming,
                   guint32 *out_ind,
                   const char **out_desc)
{
    long int ind;
    const EriItem *iter = &eris[0];
    gboolean found = FALSE;

    g_return_val_if_fail (reply != NULL, FALSE);
    g_return_val_if_fail (out_roaming != NULL, FALSE);

    errno = 0;
    ind = strtol (reply, NULL, 10);
    if (errno == 0) {
        if (out_ind)
            *out_ind = ind;

        while (iter->num != -1) {
            if (iter->num == ind) {
                *out_roaming = iter->roam_ind;
                if (out_desc)
                    *out_desc = iter->banner;
                found = TRUE;
                break;
            }
            iter++;
        }
    }

    return found;
}

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

gboolean
mm_gsm_parse_cscs_support_response (const char *reply,
                                    MMModemCharset *out_charsets)
{
    MMModemCharset charsets = MM_MODEM_CHARSET_UNKNOWN;
    GRegex *r;
    GMatchInfo *match_info;
    char *p, *str;
    gboolean success = FALSE;

    g_return_val_if_fail (reply != NULL, FALSE);
    g_return_val_if_fail (out_charsets != NULL, FALSE);

    /* Find the first '(' or '"'; the general format is:
     *
     * +CSCS: ("IRA","GSM","UCS2")
     *
     * but some devices (some Blackberries) don't include the ().
     */
    p = strchr (reply, '(');
    if (p)
        p++;
    else {
        p = strchr (reply, '"');
        if (!p)
            return FALSE;
    }

    /* Now parse each charset */
    r = g_regex_new ("\\s*([^,\\)]+)\\s*", 0, 0, NULL);
    if (!r)
        return FALSE;

    if (g_regex_match_full (r, p, strlen (p), 0, 0, &match_info, NULL)) {
        while (g_match_info_matches (match_info)) {
            str = g_match_info_fetch (match_info, 1);
            charsets |= mm_modem_charset_from_string (str);
            g_free (str);

            g_match_info_next (match_info, NULL);
            success = TRUE;
        }
    }
    g_match_info_free (match_info);
    g_regex_unref (r);

    if (success)
        *out_charsets = charsets;

    return success;
}

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

static void
convert_operator_from_ucs2 (gchar **operator)
{
    const gchar *p;
    gchar *converted;
    gsize len;

    g_return_if_fail (operator != NULL);
    g_return_if_fail (*operator != NULL);

    p = *operator;
    len = strlen (p);

    /* Len needs to be a multiple of 4 for UCS2 */
    if ((len < 4) || ((len % 4) != 0))
        return;

    while (*p) {
        if (!isxdigit (*p++))
            return;
    }

    converted = mm_modem_charset_hex_to_utf8 (*operator, MM_MODEM_CHARSET_UCS2);
    if (converted) {
        g_free (*operator);
        *operator = converted;
    }
}

gchar *
mm_3gpp_parse_operator (const gchar *reply,
                        MMModemCharset cur_charset)
{
    gchar *operator = NULL;

    if (reply && !strncmp (reply, "+COPS: ", 7)) {
        /* Got valid reply */
		GRegex *r;
		GMatchInfo *match_info;

		reply += 7;
		r = g_regex_new ("(\\d),(\\d),\"(.+)\"", G_REGEX_UNGREEDY, 0, NULL);
		if (!r)
            return NULL;

		g_regex_match (r, reply, 0, &match_info);
		if (g_match_info_matches (match_info))
            operator = g_match_info_fetch (match_info, 3);

		g_match_info_free (match_info);
		g_regex_unref (r);
    }

    if (operator) {
        /* Some modems (Option & HSO) return the operator name as a hexadecimal
         * string of the bytes of the operator name as encoded by the current
         * character set.
         */
        if (cur_charset == MM_MODEM_CHARSET_UCS2)
            convert_operator_from_ucs2 (&operator);

        /* Ensure the operator name is valid UTF-8 so that we can send it
         * through D-Bus and such.
         */
        if (!g_utf8_validate (operator, -1, NULL)) {
            g_free (operator);
            operator = NULL;
        }
    }

    return operator;
}

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

/* Map two letter facility codes into flag values. There are
 * many more facilities defined (for various flavors of call
 * barring); we only map the ones we care about. */
static MMModemGsmFacility
mm_gsm_string_to_facility (const char *string)
{
    g_return_val_if_fail (string != NULL, MM_MODEM_GSM_FACILITY_NONE);

    if (!strcmp (string, "SC"))
        return MM_MODEM_GSM_FACILITY_SIM;
    else if (!strcmp (string, "PS"))
        return MM_MODEM_GSM_FACILITY_PH_SIM;
    else if (!strcmp (string, "PF"))
        return MM_MODEM_GSM_FACILITY_PH_FSIM;
    else if (!strcmp (string, "FD"))
        return MM_MODEM_GSM_FACILITY_FIXED_DIALING;
    else if (!strcmp (string, "PN"))
        return MM_MODEM_GSM_FACILITY_NET_PERS;
    else if (!strcmp (string, "PU"))
        return MM_MODEM_GSM_FACILITY_NET_SUB_PERS;
    else if (!strcmp (string, "PP"))
        return MM_MODEM_GSM_FACILITY_PROVIDER_PERS;
    else if (!strcmp (string, "PC"))
        return MM_MODEM_GSM_FACILITY_CORP_PERS;
    else
        return MM_MODEM_GSM_FACILITY_NONE;

}

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

char *
mm_gsm_get_facility_name (MMModemGsmFacility facility)
{
    switch (facility) {
    case MM_MODEM_GSM_FACILITY_SIM:
        return "SC";
    case MM_MODEM_GSM_FACILITY_PH_SIM:
        return "PS";
    case MM_MODEM_GSM_FACILITY_PH_FSIM:
        return "PF";
    case MM_MODEM_GSM_FACILITY_FIXED_DIALING:
        return "FD";
    case MM_MODEM_GSM_FACILITY_NET_PERS:
        return "PN";
    case MM_MODEM_GSM_FACILITY_NET_SUB_PERS:
        return "PU";
    case MM_MODEM_GSM_FACILITY_PROVIDER_PERS:
        return "PP";
    case MM_MODEM_GSM_FACILITY_CORP_PERS:
        return "PC";
    default:
        return NULL;
    }
}

gboolean
mm_gsm_parse_clck_test_response (const char *reply,
                                 MMModemGsmFacility *out_facilities)
{
    MMModemGsmFacility facilities = MM_MODEM_GSM_FACILITY_NONE;
    GRegex *r;
    GMatchInfo *match_info;
    char *p, *str;
    gboolean success = FALSE;

    g_return_val_if_fail (reply != NULL, FALSE);
    g_return_val_if_fail (out_facilities != NULL, FALSE);

    /* the general format is:
     *
     * +CLCK: ("SC","AO","AI","PN")
     */
    p = strchr (reply, '(');
    if (p)
        p++;
    else {
        p = strchr (reply, '"');
        if (!p)
            return FALSE;
    }

    /* Now parse each facility */
    r = g_regex_new ("\\s*\"([^,\\)]+)\"\\s*", 0, 0, NULL);
    if (!r)
        return FALSE;

    if (g_regex_match_full (r, p, strlen (p), 0, 0, &match_info, NULL)) {
        while (g_match_info_matches (match_info)) {
            str = g_match_info_fetch (match_info, 1);
            if (str) {
                facilities |= mm_gsm_string_to_facility (str);
                g_free (str);
            }

            g_match_info_next (match_info, NULL);
            success = TRUE;
        }
    }
    g_match_info_free (match_info);
    g_regex_unref (r);

    if (success)
        *out_facilities = facilities;

    return success;
}

gboolean
mm_gsm_parse_clck_response (const char *reply, gboolean *enabled)
{
    GRegex *r;
    GMatchInfo *match_info;
    char *p, *str;
    gboolean success = FALSE;

    g_return_val_if_fail (reply != NULL, FALSE);
    g_return_val_if_fail (enabled != NULL, FALSE);

    p = strchr (reply, ':');
    if (p)
        p++;

    r = g_regex_new ("\\s*([01])\\s*", 0, 0, NULL);
    if (!r)
        return FALSE;

    if (g_regex_match (r, p, 0, &match_info)) {
        success = TRUE;
        str = g_match_info_fetch (match_info, 1);
        if (str) {
            if (*str == '0')
                *enabled = FALSE;
            else if (*str == '1')
                *enabled = TRUE;
            else
                success = FALSE;

            g_free (str);
        }
    }
    g_match_info_free (match_info);
    g_regex_unref (r);
    return success;
}

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

MMModemGsmAccessTech
mm_gsm_string_to_access_tech (const char *string)
{
    g_return_val_if_fail (string != NULL, MM_MODEM_GSM_ACCESS_TECH_UNKNOWN);

    /* Better technologies are listed first since modems sometimes say
     * stuff like "GPRS/EDGE" and that should be handled as EDGE.
     */
    if (strcasestr (string, "HSPA+"))
        return MM_MODEM_GSM_ACCESS_TECH_HSPA_PLUS;
    else if (strcasestr (string, "HSPA"))
        return MM_MODEM_GSM_ACCESS_TECH_HSPA;
    else if (strcasestr (string, "HSDPA/HSUPA"))
        return MM_MODEM_GSM_ACCESS_TECH_HSPA;
    else if (strcasestr (string, "HSUPA"))
        return MM_MODEM_GSM_ACCESS_TECH_HSUPA;
    else if (strcasestr (string, "HSDPA"))
        return MM_MODEM_GSM_ACCESS_TECH_HSDPA;
    else if (strcasestr (string, "UMTS"))
        return MM_MODEM_GSM_ACCESS_TECH_UMTS;
    else if (strcasestr (string, "EDGE"))
        return MM_MODEM_GSM_ACCESS_TECH_EDGE;
    else if (strcasestr (string, "GPRS"))
        return MM_MODEM_GSM_ACCESS_TECH_GPRS;
    else if (strcasestr (string, "GSM"))
        return MM_MODEM_GSM_ACCESS_TECH_GSM;

    return MM_MODEM_GSM_ACCESS_TECH_UNKNOWN;
}

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

char *
mm_create_device_identifier (guint vid,
                             guint pid,
                             const char *ati,
                             const char *ati1,
                             const char *gsn,
                             const char *revision,
                             const char *model,
                             const char *manf)
{
    GString *devid, *msg = NULL;
    GChecksum *sum;
    char *p, *ret = NULL;
    char str_vid[10], str_pid[10];

    /* Build up the device identifier */
    devid = g_string_sized_new (50);
    if (ati)
        g_string_append (devid, ati);
    if (ati1) {
        /* Only append "ATI1" if it's differnet than "ATI" */
        if (!ati || (strcmp (ati, ati1) != 0))
            g_string_append (devid, ati1);
    }
    if (gsn)
        g_string_append (devid, gsn);
    if (revision)
        g_string_append (devid, revision);
    if (model)
        g_string_append (devid, model);
    if (manf)
        g_string_append (devid, manf);

    if (!strlen (devid->str)) {
        g_string_free (devid, TRUE);
        return NULL;
    }

    p = devid->str;
    msg = g_string_sized_new (strlen (devid->str) + 17);

    sum = g_checksum_new (G_CHECKSUM_SHA1);

    if (vid) {
        snprintf (str_vid, sizeof (str_vid) - 1, "%08x", vid);
        g_checksum_update (sum, (const guchar *) &str_vid[0], strlen (str_vid));
        g_string_append_printf (msg, "%08x", vid);
    }
    if (vid) {
        snprintf (str_pid, sizeof (str_pid) - 1, "%08x", pid);
        g_checksum_update (sum, (const guchar *) &str_pid[0], strlen (str_pid));
        g_string_append_printf (msg, "%08x", pid);
    }

    while (*p) {
        /* Strip spaces and linebreaks */
        if (!isblank (*p) && !isspace (*p) && isascii (*p)) {
            g_checksum_update (sum, (const guchar *) p, 1);
            g_string_append_c (msg, *p);
        }
        p++;
    }
    ret = g_strdup (g_checksum_get_string (sum));
    g_checksum_free (sum);

    mm_dbg ("Device ID source '%s'", msg->str);
    mm_dbg ("Device ID '%s'", ret);
    g_string_free (msg, TRUE);
    g_string_free (devid, TRUE);

    return ret;
}

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

struct CindResponse {
    char *desc;
    guint idx;
    gint min;
    gint max;
};

static CindResponse *
cind_response_new (const char *desc, guint idx, gint min, gint max)
{
    CindResponse *r;
    char *p;

    g_return_val_if_fail (desc != NULL, NULL);
    g_return_val_if_fail (idx >= 0, NULL);

    r = g_malloc0 (sizeof (CindResponse));

    /* Strip quotes */
    r->desc = p = g_malloc0 (strlen (desc) + 1);
    while (*desc) {
        if (*desc != '"' && !isspace (*desc))
            *p++ = tolower (*desc);
        desc++;
    }

    r->idx = idx;
    r->max = max;
    r->min = min;
    return r;
}

static void
cind_response_free (CindResponse *r)
{
    g_return_if_fail (r != NULL);

    g_free (r->desc);
    memset (r, 0, sizeof (CindResponse));
    g_free (r);
}

const char *
cind_response_get_desc (CindResponse *r)
{
    g_return_val_if_fail (r != NULL, NULL);

    return r->desc;
}

guint
cind_response_get_index (CindResponse *r)
{
    g_return_val_if_fail (r != NULL, 0);

    return r->idx;
}

gint
cind_response_get_min (CindResponse *r)
{
    g_return_val_if_fail (r != NULL, -1);

    return r->min;
}

gint
cind_response_get_max (CindResponse *r)
{
    g_return_val_if_fail (r != NULL, -1);

    return r->max;
}

#define CIND_TAG "+CIND:"

GHashTable *
mm_parse_cind_test_response (const char *reply, GError **error)
{
    GHashTable *hash;
    GRegex *r;
    GMatchInfo *match_info;
    guint idx = 1;

    g_return_val_if_fail (reply != NULL, NULL);

    /* Strip whitespace and response tag */
    if (g_str_has_prefix (reply, CIND_TAG))
        reply += strlen (CIND_TAG);
    while (isspace (*reply))
        reply++;

    r = g_regex_new ("\\(([^,]*),\\((\\d+)[-,](\\d+)\\)", G_REGEX_UNGREEDY, 0, NULL);
    if (!r) {
        g_set_error_literal (error,
                             MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Could not parse scan results.");
        return NULL;
    }

    hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) cind_response_free);

    if (g_regex_match_full (r, reply, strlen (reply), 0, 0, &match_info, NULL)) {
        while (g_match_info_matches (match_info)) {
            CindResponse *resp;
            char *desc, *tmp;
            gint min = 0, max = 0;

            desc = g_match_info_fetch (match_info, 1);

            tmp = g_match_info_fetch (match_info, 2);
            min = atoi (tmp);
            g_free (tmp);

            tmp = g_match_info_fetch (match_info, 3);
            max = atoi (tmp);
            g_free (tmp);

            resp = cind_response_new (desc, idx++, min, max);
            if (resp)
                g_hash_table_insert (hash, g_strdup (resp->desc), resp);

            g_free (desc);

            g_match_info_next (match_info, NULL);
        }
    }
    g_match_info_free (match_info);
    g_regex_unref (r);

    return hash;
}

GByteArray *
mm_parse_cind_query_response(const char *reply, GError **error)
{
    GByteArray *array = NULL;
    const char *p = reply;
    GRegex *r = NULL;
    GMatchInfo *match_info;
    guint8 t = 0;

    g_return_val_if_fail (reply != NULL, NULL);

    if (!g_str_has_prefix (p, CIND_TAG)) {
        g_set_error_literal (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Could not parse the +CIND response");
        return NULL;
    }

    p += strlen (CIND_TAG);
    while (isspace (*p))
        p++;

    r = g_regex_new ("(\\d+)[^0-9]+", G_REGEX_UNGREEDY, 0, NULL);
    if (!r) {
        g_set_error_literal (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Internal failure attempting to parse +CIND response");
        return NULL;
    }

    if (!g_regex_match_full (r, p, strlen (p), 0, 0, &match_info, NULL)) {
        g_set_error_literal (error, MM_CORE_ERROR, MM_CORE_ERROR_FAILED,
                             "Failure parsing the +CIND response");
        goto done;
    }

    array = g_byte_array_sized_new (g_match_info_get_match_count (match_info));

    /* Add a zero element so callers can use 1-based indexes returned by
     * cind_response_get_index().
     */
    g_byte_array_append (array, &t, 1);

    while (g_match_info_matches (match_info)) {
        char *str;
        gulong val;

        str = g_match_info_fetch (match_info, 1);

        errno = 0;
        val = strtoul (str, NULL, 10);

        t = 0;
        if ((errno == 0) && (val < 255))
            t = (guint8) val;
        /* FIXME: indicate errors somehow? */
        g_byte_array_append (array, &t, 1);

        g_free (str);
        g_match_info_next (match_info, NULL);
    }

done:
    g_match_info_free (match_info);
    g_regex_unref (r);

    return array;
}

gint
mm_cdma_normalize_class (const gchar *orig_class)
{
    gchar class;

    g_return_val_if_fail (orig_class != NULL, '0');

    class = toupper (orig_class[0]);

    /* Cellular (850MHz) */
    if (class == '1' || class == 'C')
        return 1;
    /* PCS (1900MHz) */
    if (class == '2' || class == 'P')
        return 2;

    /* Unknown/not registered */
    return 0;
}

gchar
mm_cdma_normalize_band (const gchar *long_band,
                        gint *out_class)
{
    gchar band;

    g_return_val_if_fail (long_band != NULL, 'Z');

    /* There are two response formats for the band; one includes the band
     * class and the other doesn't.  For modems that include the band class
     * (ex Novatel S720) you'll see "Px" or "Cx" depending on whether the modem
     * is registered on a PCS/1900 (P) or Cellular/850 (C) system.
     */
    band = toupper (long_band[0]);

    /* Possible band class in first position; return it */
    if (band == 'C' || band == 'P') {
        gchar tmp[2] = { band, '\0' };

        *out_class = mm_cdma_normalize_class (tmp);
        band = toupper (long_band[1]);
    }

    /* normalize to A - F, and Z */
    if (band >= 'A' && band <= 'F')
        return band;

    /* Unknown/not registered */
    return 'Z';
}

gint
mm_cdma_convert_sid (const gchar *sid)
{
    glong tmp_sid;

    g_return_val_if_fail (sid != NULL, MM_MODEM_CDMA_SID_UNKNOWN);

    errno = 0;
    tmp_sid = strtol (sid, NULL, 10);
    if ((errno == EINVAL) || (errno == ERANGE))
        return MM_MODEM_CDMA_SID_UNKNOWN;
    else if (tmp_sid < G_MININT || tmp_sid > G_MAXINT)
        return MM_MODEM_CDMA_SID_UNKNOWN;

    return (gint) tmp_sid;
}

guint
mm_count_bits_set (gulong number)
{
    guint c;

    for (c = 0; number; c++)
        number &= number - 1;
    return c;
}