aboutsummaryrefslogtreecommitdiffstats
path: root/src/phonesim.cpp
blob: e7e42c4f6fa2a07146143c703bb7982a301ae856 (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
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
/****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
**     http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/

#include "phonesim.h"

#include "hardwaremanipulator.h"
#include "simfilesystem.h"
#include "simapplication.h"
#include "callmanager.h"
#include <qatutils.h>

#include <qstring.h>
#include <qbytearray.h>
#include <qregexp.h>
#include <qdebug.h>

#define PHONEBOOK_NLENGTH 32
#define PHONEBOOK_TLENGTH 16
#define PHONEBOOK_GLENGTH 255
#define PHONEBOOK_SLENGTH 16
#define PHONEBOOK_ELENGTH 255
#define PHONEBOOK_SIPLENGTH 255
#define PHONEBOOK_TELLENGTH 255

#define INVALID_VALUE_HIDDEN -1

SimXmlNode::SimXmlNode( const QString& _tag )
{
    parent = 0;
    next = 0;
    children = 0;
    attributes = 0;
    tag = _tag;
}


SimXmlNode::~SimXmlNode()
{
    SimXmlNode *temp1, *temp2;
    temp1 = children;
    while ( temp1 ) {
        temp2 = temp1->next;
        delete temp1;
        temp1 = temp2;
    }
    temp1 = attributes;
    while ( temp1 ) {
        temp2 = temp1->next;
        delete temp1;
        temp1 = temp2;
    }
}

void SimXmlNode::addChild( SimXmlNode *child )
{
    SimXmlNode *current = children;
    SimXmlNode *prev = 0;
    while ( current ) {
        prev = current;
        current = current->next;
    }
    if ( prev ) {
        prev->next = child;
    } else {
        children = child;
    }
    child->next = 0;
    child->parent = this;
}


void SimXmlNode::addAttribute( SimXmlNode *child )
{
    SimXmlNode *current = attributes;
    SimXmlNode *prev = 0;
    while ( current ) {
        prev = current;
        current = current->next;
    }
    if ( prev ) {
        prev->next = child;
    } else {
        attributes = child;
    }
    child->next = 0;
    child->parent = this;
}


QString SimXmlNode::getAttribute( const QString& name )
{
    SimXmlNode *current = attributes;
    while ( current ) {
        if ( current->tag == name )
            return current->contents;
        current = current->next;
    }
    return QString();
}


SimXmlHandler::SimXmlHandler()
{
    tree = new SimXmlNode( QString() );
    current = tree;
}


SimXmlHandler::~SimXmlHandler()
{
    delete tree;
}


bool SimXmlHandler::startElement( const QString& name, const QXmlStreamAttributes& atts )
{
    SimXmlNode *node = new SimXmlNode( name );
    SimXmlNode *attr;
    int index;
    current->addChild( node );
    for ( index = 0; index < atts.size(); ++index ) {
        attr = new SimXmlNode( atts[index].name().toString() );
        attr->contents = atts[index].value().toString();
        node->addAttribute( attr );
    }
    current = node;
    return true;
}


bool SimXmlHandler::endElement()
{
    current = current->parent;
    return true;
}


bool SimXmlHandler::characters( const QString& ch )
{
    current->contents += ch;
    return true;
}


SimXmlNode *SimXmlHandler::documentElement() const
{
    if ( tree->children && tree->children->tag == "simulator" ) {
        return tree->children;
    } else {
        return tree;
    }
}


SimState::SimState( SimRules *rules, SimXmlNode& e )
{
    _rules = rules;
    if ( e.tag == "state" ) {
        _name = e.getAttribute( "name" );
    }
    SimXmlNode *n = e.children;
    while ( n != 0 ) {
        if ( n->tag == "chat" ) {

            // Load a chat response definition.
            items.append( new SimChat( this, *n ) );

        } else if ( n->tag == "unsolicited" ) {

            // Load an unsolicited response definition.
            items.append( new SimUnsolicited( this, *n ) );

        }
        n = n->next;
    }
}


void SimState::enter()
{
    QList<SimItem *>::Iterator iter;
    for ( iter = items.begin(); iter != items.end(); ++iter ) {
        (*iter)->enter();
    }
}


void SimState::leave()
{
    QList<SimItem *>::Iterator iter;
    for ( iter = items.begin(); iter != items.end(); ++iter ) {
        (*iter)->leave();
    }
}


bool SimState::command( const QString& cmd )
{
    // Search for a "SimChat" item that understands the command.
    QList<SimItem *>::Iterator iter;
    for ( iter = items.begin(); iter != items.end(); ++iter ) {
        if ( (*iter)->command( cmd ) ) {
            return true;
        }
    }

    // Pass unhandled commands to the default state to be processed.
    SimState *defaultState = rules()->defaultState();
    if ( defaultState != this ) {
        return defaultState->command( cmd );
    } else {
        return false;
    }
}


SimChat::SimChat( SimState *state, SimXmlNode& e )
    : SimItem( state )
{
    SimXmlNode *n = e.children;
    responseDelay = 0;
    wildcard = false;
    eol = true;

    listSMS = false;
    deleteSMS = false;
    readSMS = false;

    while ( n != 0 ) {
        if ( n->tag == "command" ) {
            _command = n->contents;
            int w=_command.indexOf(QChar('*'));
            while(w <= 2 && w >= 0)
                w=_command.indexOf(QChar('*'), w+1);
            if ( w > 2 ) {
                wildcard = true;
            } else {
                wildcard = false;
            }
            QString wc = n->getAttribute( "wildcard" );
            if ( wc == "true" )
                wildcard = true;    // Force the use of wildcarding.
        } else if ( n->tag == "response" ) {
            QString delay = n->getAttribute( "delay" );
            response = n->contents;
            if ( delay != QString() )
                responseDelay = delay.toInt();
            else
                responseDelay = 0;
            QString eolstr = n->getAttribute( "eol" );
            eol = (eolstr != "false");
        } else if ( n->tag == "switch" ) {
            switchTo = n->getAttribute( "name" );
        } else if ( n->tag == "set" ) {
	    variables += n->getAttribute( "name" );
	    values += n->getAttribute( "value" );
        } else if ( n->tag == "newcall" ) {
            newCallVar = n->getAttribute( "name" );
        } else if ( n->tag == "forgetcall" ) {
            forgetCallId = n->getAttribute( "id" );
        } else if ( n->tag == "listSMS" ) {
            listSMS = true;
        } else if ( n->tag =="deleteSMS" ) {
            deleteSMS = true;
        } else if ( n->tag == "readSMS" ) {
            readSMS = true;
        }

        n = n->next;
    }
}

QString PS_toHex( const QByteArray& binary )
{
    QString str = "";
    static char const hexchars[] = "0123456789ABCDEF";

    for ( int i = 0; i < binary.size(); i++ ) {
        str += (QChar)(hexchars[ (binary[i] >> 4) & 0x0F ]);
        str += (QChar)(hexchars[ binary[i] & 0x0F ]);
    }

    return str;
}

bool SimChat::command( const QString& cmd )
{
    QString wild;
    // command may contain vars, expand them.
    QString _ecommand = state()->rules()->expand(_command);

    if ( wildcard ) {
        int s=QRegExp(_ecommand,Qt::CaseSensitive,QRegExp::Wildcard).indexIn(cmd,0);
        if (s==0) {
            int w=_ecommand.indexOf(QChar('*'));
            while(w <= 2 && w >= 0)
                w=_ecommand.indexOf(QChar('*'),w+1);
            wild = cmd.mid(w,cmd.length()-_ecommand.length()+1);
        } else
            return false;
    } else if ( !wildcard && cmd == _ecommand ) {

        // Matched the entire command.
        wild = "";

    } else {
        return false;
    }

    // Send the response.
    if (!readSMS && !deleteSMS && !listSMS)
        state()->rules()->respond( response, responseDelay, eol );

    // Set the variables.
    for ( int varNum = 0; varNum < variables.size(); ++varNum ) {
    	QString variable = variables[varNum];
	QString value = values[varNum];
        if ( value != "*" ) {
            int index = value.indexOf( "${*}" );
            if ( index == -1 ) {
                state()->rules()->setVariable( variable, value );
            } else {
                if ( wild.length() > 0 && wild[wild.length() - 1] == 0x1A ) {
                    // Strip the terminating ^Z from SMS PDU's.
                    wild = wild.left( wild.length() - 1 );
                }
                state()->rules()->setVariable
                    ( variable, value.left( index ) + wild +
                    value.mid( index + 4 ) );
            }
        } else {
            state()->rules()->setVariable( variable, wild );
        }
    }

    // Switch to the new state.
    if ( switchTo != QString() ) {
        state()->rules()->switchTo( switchTo );
    }

    // Allocate a new call identifier or forget this call identifier.
    if ( newCallVar.length() > 0 ) {
        state()->rules()->setVariable
            ( newCallVar, QString::number( state()->rules()->newCall() ) );
    }
    if ( forgetCallId.length() > 0 ) {
        if ( forgetCallId == "*" )
            if ( wild.length() == 0 )
                state()->rules()->forgetAllCalls();
            else
                state()->rules()->forgetCall( wild.toInt() );
        else
            state()->rules()->forgetCall
                ( state()->rules()->expand( forgetCallId ).toInt() );
    }
    if ( listSMS && state()->rules()->getMachine() ) {
        QString listSMSResponse;
        QSMSMessageList &SMSList = state()->rules()->getMachine()->getSMSList();
        QString status;

        if ( state()->rules()->variable("MSGMEM") == "SM" ) {
            for ( int i=0; i<SMSList.count(); i++ ) {
                if ( SMSList.getDeletedFlag(i) == true )
                    continue;

                status = QString::number(SMSList.getStatus(i));
                listSMSResponse.append("+CMGL: " + QString::number(i+1) + "," + status + ",," +
                                       QString::number(SMSList.getLength(i)) + "\\n" +
                                       PS_toHex( SMSList.readSMS(i) ) + "\\n");
            }
        }

	if (listSMSResponse.isEmpty())
            listSMSResponse.append("+CMS ERROR: 321");
	else
            listSMSResponse.append("\\nOK");

        state()->rules()->respond(listSMSResponse , responseDelay, eol );
    }

    if ( deleteSMS && state()->rules()->getMachine() ) {
        QString deleteSMSResponse;
        QSMSMessageList &SMSList = state()->rules()->getMachine()->getSMSList();
        int index = wild.toInt();

        if ( index > SMSList.count() || index <= 0 || (SMSList.getDeletedFlag(index-1) == true) ) {
            deleteSMSResponse.append("ERROR");
        } else {
            SMSList.deleteSMS(index-1);
            deleteSMSResponse.append("OK");
        }

        state()->rules()->respond(deleteSMSResponse , responseDelay, eol );
    }

    if ( readSMS && state()->rules()->getMachine() ) {
        QString readSMSResponse;
        QSMSMessageList &SMSList = state()->rules()->getMachine()->getSMSList();
        int index = wild.toInt();

        if ( index > SMSList.count() || index <= 0 || (SMSList.getDeletedFlag(index-1) == true) ) {
            readSMSResponse.append("ERROR");
        } else {
            QString status = QString::number(SMSList.getStatus(index-1));
            readSMSResponse.append("+CMGR: " + status + ",," +
                                       QString::number(SMSList.getLength(index-1)) + "\\n" +
                                       PS_toHex( SMSList.readSMS(index-1) ) + "\\n");
        }

	readSMSResponse += "\\nOK";
        state()->rules()->respond(readSMSResponse , responseDelay, eol );
    }
    return true;
}


SimUnsolicited::SimUnsolicited( SimState *state, SimXmlNode& e )
    : SimItem( state ), done(false)
{
    QString delay = e.getAttribute( "delay" );
    response = e.contents;
    if ( delay != QString() )
        responseDelay = delay.toInt();
    else
        responseDelay = 0;
    switchTo = e.getAttribute( "switch" );
    doOnce = e.getAttribute( "once" ) == "true";

    timer = new QTimer( this );
    timer->setSingleShot( true );
    connect( timer, SIGNAL(timeout()), this, SLOT(timeout()) );
}


void SimUnsolicited::enter()
{
    if (!doOnce || !done)
        timer->start( responseDelay );
}


void SimUnsolicited::leave()
{
    timer->stop();
}


void SimUnsolicited::timeout()
{
    if (state() && state()->rules()) {
        state()->rules()->unsolicited( response );

        if ( switchTo != QString() ) {
            state()->rules()->switchTo( switchTo );
        }
    }

    done = true;
}

static bool readXmlFile( SimXmlHandler *handler, const QString& filename )
{
    QFile f( filename );
    if ( !f.open( QIODevice::ReadOnly ) )
        return false;
    QXmlStreamReader reader( &f );
    while ( !reader.atEnd() ) {
        reader.readNext();
        if ( reader.hasError() )
            break;
        if ( reader.isStartElement() ) {
            handler->startElement( reader.name().toString(), reader.attributes() );
        } else if ( reader.isEndElement() ) {
            handler->endElement();
        } else if ( reader.isCharacters() ) {
            handler->characters( reader.text().toString() );
        }
    }
    f.close();
    return !reader.hasError();
}

SimRules::SimRules( int fd, QObject *p,  const QString& filename, HardwareManipulatorFactory *hmf )
    : QTcpSocket(p)
{
    setSocketDescriptor(fd);
    machine = 0;
    toolkitApp = 0;

    if (hmf)
        machine = hmf->create(this, 0);

    if (machine) {
        connect(machine, SIGNAL(unsolicitedCommand(QString)),
                this, SLOT(unsolicited(QString)));
        connect(machine, SIGNAL(command(QString)),
                this, SLOT(command(QString)));
        connect(machine, SIGNAL(variableChanged(QString,QString)),
                this, SLOT(setVariable(QString,QString)));
        connect(machine, SIGNAL(switchTo(QString)),
                this, SLOT(switchTo(QString)));
    }

    _callManager = new CallManager(this);
    connect( _callManager, SIGNAL(send(QString)),
             this, SLOT(respond(QString)) );
    connect( _callManager, SIGNAL(unsolicited(QString)),
             this, SLOT(unsolicited(QString)) );
    connect( _callManager, SIGNAL(dialCheck(QString,bool&)),
             this, SLOT(dialCheck(QString,bool&)) );

    if ( machine ) {
        connect( machine, SIGNAL(startIncomingCall(QString,QString,QString)),
                 _callManager, SLOT(startIncomingCall(QString,QString,QString)) );
        connect ( _callManager, SIGNAL( callStatesChanged( QList<CallInfo> * ) ),
                  machine, SLOT( callManagement( QList<CallInfo> * ) ) );
        connect ( machine, SIGNAL( stateChangedToAlerting() ), _callManager,
                SLOT( dialingToAlerting() ) );
        connect ( machine, SIGNAL( stateChangedToConnected() ), _callManager,
                SLOT( dialingToConnected() ) );
        connect ( machine, SIGNAL( stateChangedToHangup( int ) ), _callManager,
                SLOT( hangupRemote( int ) ) );
    }

    connect(this,SIGNAL(readyRead()),
        this,SLOT(tryReadCommand()));
    connect(this,SIGNAL(disconnected()),
        this,SLOT(destruct()));
    // Initialize the local state.
    currentState = 0;
    defState = 0;
    usedCallIds = 0;
    fileSystem = 0;
    useGsm0710 = false;
    currentChannel = 1;
    incomingUsed = 0;
    lineUsed = 0;
    defaultToolkitApp = toolkitApp = new DemoSimApplication( this, this );
    conformanceApp = new ConformanceSimApplication( this, this );
    connect( _callManager, SIGNAL(controlEvent(QSimControlEvent)),
             toolkitApp, SLOT(controlEvent(QSimControlEvent)) );

    simApps.append( toolkitApp );
    simApps.append( conformanceApp );

    if ( machine )
        machine->handleNewApp();

    // Load the simulator rules into memory as a DOM-like tree.
    SimXmlHandler *handler = new SimXmlHandler();
    if ( !readXmlFile( handler, filename ) ) {
        qWarning() << filename << ": could not parse simulator rule file";
        delete handler;
        return;
    }

    // Load the default state and set it as current.
    defState = new SimState( this, *(handler->documentElement()) );
    states.append( defState );

    initPhoneBooks();

    // Load the other states, and the start state's name (if specified).
    SimXmlNode *n = handler->documentElement()->children;
    QString start = QString();
    while ( n != 0 ) {
        if ( n->tag == "state" ) {

            // Load a new state definition.
            SimState *state = new SimState( this, *n );
            states.append( state );

        } else if ( n->tag == "start" ) {

            // Set a new start state.
            start = n->getAttribute( "name" );

        } else if ( n->tag == "set" ) {

            // Set the initial value of a variable.
            QString name = n->getAttribute( "name" );
            QString value = n->getAttribute( "value" );
            if ( name != QString() && value != QString() ) {
                setVariable(name, value);
            }

        } else if ( n->tag == "filesystem" ) {

            // Load the SIM filesystem.
            fileSystem = new SimFileSystem( this, *n );

        } else if ( n->tag == "phonebook" ) {

            // Load a phonebook definition.
            loadPhoneBook( *n );

        }
        n = n->next;
    }

    // Clean up the XML reader objects.
    delete handler;

    // Set the start state appropriately.
    currentState = state( start );
    if ( !currentState )
        currentState = defState;
    currentState->enter();
}


#define MAX_GSM0710_FRAME_SIZE      31


static const unsigned char crcTable[256] = {
    0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75,
    0x0E, 0x9F, 0xED, 0x7C, 0x09, 0x98, 0xEA, 0x7B,
    0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69,
    0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67,
    0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D,
    0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43,
    0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, 0x51,
    0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F,
    0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05,
    0x7E, 0xEF, 0x9D, 0x0C, 0x79, 0xE8, 0x9A, 0x0B,
    0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19,
    0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17,
    0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D,
    0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33,
    0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, 0x21,
    0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F,
    0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95,
    0xEE, 0x7F, 0x0D, 0x9C, 0xE9, 0x78, 0x0A, 0x9B,
    0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89,
    0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87,
    0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD,
    0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3,
    0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, 0xB1,
    0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF,
    0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5,
    0x9E, 0x0F, 0x7D, 0xEC, 0x99, 0x08, 0x7A, 0xEB,
    0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9,
    0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7,
    0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD,
    0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3,
    0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, 0xC1,
    0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF
};

static int computeCrc( const char *data, uint len )
{
    int sum = 0xFF;
    while ( len > 0 ) {
        sum = crcTable[ ( sum ^ *data++ ) & 0xFF ];
        --len;
    }
    return ((0xFF - sum) & 0xFF);
}


void SimRules::tryReadCommand()
{
    int len, posn;
    int channel, type;
    int temp, lasteol;

    // Read as much data as possible into "incomingBuffer".
    len = sizeof(incomingBuffer) - 1 - incomingUsed;
    len = read( incomingBuffer + incomingUsed, len );
    if ( len <= 0 ) {
        // The connection has been closed by the remote end.
        return;
    }
    incomingUsed += len;

    // Split the incoming data into GSM 07.10 packets or text lines.
    if ( useGsm0710 ) {
        // Extract GSM 07.10 packets from the incoming buffer.
        posn = 0;
        while ( posn < incomingUsed ) {
            if ( incomingBuffer[posn] == (char)0xF9 ) {

                // Skip additional 0xF9 bytes between frames.
                while ( ( posn + 1 ) < incomingUsed &&
                        incomingBuffer[posn + 1] == (char)0xF9 ) {
                    ++posn;
                }

                // We need at least 4 bytes for the header.
                if ( ( posn + 4 ) > incomingUsed )
                    break;

                // The low bits of the second and fourth bytes should be 1,
                // which indicates short channel number and length values.
                if ( ( incomingBuffer[posn + 1] & 0x01 ) == 0 ||
                     ( incomingBuffer[posn + 3] & 0x01 ) == 0 ) {
                    ++posn;
                    continue;
                }

                // Get the packet length and validate it.
                len = (incomingBuffer[posn + 3] >> 1) & 0x7F;
                if ( ( posn + 5 + len ) > incomingUsed )
                    break;

                // Verify the packet header checksum.
                if ( ( ( computeCrc( incomingBuffer + posn + 1, 3 ) ^
                         incomingBuffer[posn + len + 4] ) & 0xFF ) != 0 ) {
                    qDebug() << "*** GSM 07.10 checksum check failed ***";
                    posn += len + 5;
                    continue;
                }

                // Get the channel number and packet type from the header.
                channel = (incomingBuffer[posn + 1] >> 2) & 0x3F;
                type = incomingBuffer[posn + 2] & 0xEF;  // Strip "PF" bit.

                // Dispatch data packets to the appropriate channel.
                if ( type == 0xEF || type == 0x03 ) {
                    if ( channel == 0 ) {
                        if ( len == 2 &&
                             incomingBuffer[posn + 4] == (char)0xC3 &&
                             incomingBuffer[posn + 5] == (char)0x01 ) {
                            // This is the "terminate" commmand, which
                            // indicates that we should exit GSM 07.10 mode.
                            useGsm0710 = false;
                            posn += len + 5;
                            if ( posn < incomingUsed &&
                                 incomingBuffer[posn] == (char)0xF9 ) {
                                // Skip the trailing 0xF9 on the terminate.
                                ++posn;
                            }
                            qDebug() << "GSM 07.10 mode deactivated";
                            break;
                        }
                    } else {
                        // Ordinary data packet on a specific channel.
                        memcpy( lineBuffer + lineUsed,
                                incomingBuffer + posn + 4, len );
                        lineUsed += len;

                        // Process any complete lines that we have received.
                        lasteol = 0;
                        temp = 0;
                        currentChannel = channel;
                        while ( temp < lineUsed ) {
                            if ( lineBuffer[temp] == '\r' ) {
                                lineBuffer[temp] = '\0';
                                command( lineBuffer + lasteol );
                                ++temp;
                                if ( temp < lineUsed &&
                                     lineBuffer[temp] == '\n' ) {
                                    ++temp;
                                }
                                lasteol = temp;
                            } else if ( lineBuffer[temp] == 0x1A ) {
                                // Probably the terminator on an SMS PDU,
                                // which may or may not be followed by a CR.
                                lineBuffer[temp] = '\0';
                                command( lineBuffer + lasteol );
                                ++temp;
                                if ( temp < lineUsed &&
                                     lineBuffer[temp] == '\r' ) {
                                    ++temp;
                                }
                                lasteol = temp;
                            } else if ( lineBuffer[temp] == '\n' ) {
                                lineBuffer[temp] = '\0';
                                command( lineBuffer + lasteol );
                                ++temp;
                                lasteol = temp;
                            } else {
                                ++temp;
                            }
                        }
                        currentChannel = 1;
                        memmove( lineBuffer, lineBuffer + lasteol,
                                 lineUsed - lasteol );
                        lineUsed -= lasteol;
                    }
                }
                posn += len + 5;

            } else {
                // Skip garbage byte outside of a GSM 07.10 packet.
                ++posn;
            }
        }
        memmove( incomingBuffer, incomingBuffer + posn, incomingUsed - posn );
        incomingUsed -= posn;
        if ( !useGsm0710 )
            goto processText;   // We've just exited GSM 07.10 mode.
    } else {
        // We aren't using multi-plexing yet, so split into text lines.
    processText:
        len = 0;
        while ( len < incomingUsed ) {
            if ( incomingBuffer[len] == '\r' ) {
                if ( (len + 1) < incomingUsed &&
                     incomingBuffer[len + 1] == '\n' ) {
                    ++len;
                }
                lineBuffer[lineUsed] = '\0';
                if ( lineBuffer[0] != (char)0xF9 ) {
                    command( lineBuffer );
                }
                lineUsed = 0;
            } else if ( incomingBuffer[len] == 0x1A ) {
                // Probably the terminator on an SMS PDU,
                // which may or may not be followed by a CR.
                if ( (len + 1) < incomingUsed &&
                     incomingBuffer[len + 1] == '\r' ) {
                    ++len;
                }
                lineBuffer[lineUsed] = '\0';
                if ( lineBuffer[0] != (char)0xF9 ) {
                    command( lineBuffer );
                }
                lineUsed = 0;
            } else if ( incomingBuffer[len] == '\n' ) {
                lineBuffer[lineUsed] = '\0';
                if ( lineBuffer[0] != (char)0xF9 ) {
                    command( lineBuffer );
                }
                lineUsed = 0;
            } else if ( lineUsed < (int)( sizeof(lineBuffer) - 1 ) ) {
                lineBuffer[lineUsed++] = incomingBuffer[len];
            }
            ++len;
        }
        incomingUsed = 0;
    }
}

void SimRules::destruct()
{
    int count = simApps.count();

    for ( int i = 0; i < count; i++ )
        simApps.removeAt( 0 );

    delete conformanceApp;
    conformanceApp = NULL;
    delete defaultToolkitApp;
    defaultToolkitApp = NULL;
    toolkitApp = NULL;

    if ( getMachine() )
        getMachine()->handleNewApp();

    if ( defState )
        delete defState;
    defState = NULL;

    if ( _callManager )
        delete _callManager;
    _callManager = NULL;

    if ( fileSystem )
        delete fileSystem;
    fileSystem = NULL;

    if (machine) machine->deleteLater();
    deleteLater();
}

void SimRules::setPhoneNumber(const QString &s)
{
    mPhoneNumber = s;

    if (machine) machine->setPhoneNumber(s);
}

HardwareManipulator * SimRules::getMachine() const
{
    return machine;
}

void SimRules::setSimApplication( SimApplication *app )
{
    if ( toolkitApp == app )
        return;

    if ( toolkitApp )
        toolkitApp->abort();

    toolkitApp = app;
}

const QList<SimApplication *> SimRules::getSimApps()
{
    return simApps;
}

void SimRules::switchTo(const QString& name)
{
    SimState *newState = state( name );
    if ( newState ) {
        if ( currentState )
            currentState->leave();
        currentState = newState;
        currentState->enter();
    }
}


SimState *SimRules::state( const QString& name ) const
{
    if ( name == "default" )
        return defaultState();

    QList<SimState *>::ConstIterator iter;
    for ( iter = states.begin(); iter != states.end(); ++iter ) {

        if ( (*iter)->name() == name ) {
            return *iter;
        }

    }
    qWarning() << "Warning: no state called \"" << name << "\" has been defined";
    return 0;
}

bool SimRules::simCsimOk( const QByteArray& payload )
{
    unsigned char sw1 = 0x90;
    unsigned char sw2 = 0x00;
    QByteArray resp = payload;

    if ( toolkitApp ) {
        QByteArray cmd = toolkitApp->fetch();
        if ( !cmd.isEmpty() ) {
            sw1 = 0x91;
            sw2 = cmd.size();
        }
    }

    resp += sw1;
    resp += sw2;
    respond( "+CSIM: " + QString::number( resp.size() * 2 ) + "," +
                           QAtUtils::toHex( resp ) + "\\n\\nOK" );

    return true;
}

bool SimRules::simCommand( const QString& cmd )
{
    // 3GPP Terminal Response Command
    if ( cmd.startsWith("AT+CUSATT=") ) {
        int start = cmd.indexOf( QChar('=') ) + 1;
        QByteArray response = QAtUtils::fromHex( cmd.mid(start) );
        QSimTerminalResponse resp = QSimTerminalResponse::fromPdu( response );

        if ( !toolkitApp || !toolkitApp->response( resp ) )
            respond( "ERROR" );

        return true;
    }

    // 3GPP Envelope command
    if ( cmd.startsWith("AT+CUSATE=") ) {
        int start = cmd.indexOf( QChar('=') ) + 1;
        QByteArray envelope = QAtUtils::fromHex( cmd.mid(start) );
        QSimEnvelope env = QSimEnvelope::fromPdu( envelope );

        if (!toolkitApp || !toolkitApp->envelope( env ) )
            respond( "ERROR" );

        respond( "OK" );

        return true;
    }

    // If not AT+CSIM, then this is not a SIM toolkit command.
    if ( !cmd.startsWith( "AT+CSIM=" ) )
        return false;

    if ( getMachine() && !getMachine()->getSimPresent() )
        return true;

    // Extract the binary payload of the AT+CSIM command.
    int comma = cmd.indexOf( QChar(',') );
    if ( comma < 0 )
        return false;
    QByteArray param = QAtUtils::fromHex( cmd.mid(comma + 1) );

    if ( param.length() < 4 ) {
        /* Wrong length */
        respond( "+CSIM: 4,6700\\n\\nOK" );
        return false;
    }

    if ( param[0] != (char)0xA0 ) {
        /* CLA not supported */
        respond( "+CSIM: 4,6800\\n\\nOK" );
        return false;
    }

    // Determine what kind of command we are dealing with.
    // Check for TERMINAL PROFILE, FETCH, TERMINAL RESPONSE,
    // ENVELOPE and UNBLOCK CHV packets.
    if ( param[1] == (char)0x10 ) {
        /* Abort the SIM application and force it to return to the main menu. */
        if ( toolkitApp )
            toolkitApp->abort();

        /* Download of a TERMINAL PROFILE.  We respond with a simple OK,
         * on the assumption that what we were sent was valid.  */
        return simCsimOk( QByteArray() );
    } else if ( param[1] == (char)0x12 ) {
        if ( !toolkitApp ) {
            respond( "+CSIM: 4,6F00\\n\\nOK" );
            return true;
        }

        /* Fetch the current command contents. */
        QByteArray resp = toolkitApp->fetch( true );
        if ( resp.isEmpty() ) {
            /* We weren't expecting a FETCH. */
            respond( "+CSIM: 4,6F00\\n\\nOK" );
            return true;
        }

        return simCsimOk( resp );
    } else if ( param.length() >= 5 && param[1] == (char)0x14 ) {
        if ( !toolkitApp ) {
            respond( "+CSIM: 4,6F00\\n\\nOK" );
            return true;
        }

        /* Process a TERMINAL RESPONSE message. */
        QSimTerminalResponse resp =
            QSimTerminalResponse::fromPdu( param.mid(5) );

        /* Incase of successful case, response is sent inside
         * the SimApplication::response function. response function
         * also handles the notification of new command
         */
        if ( !toolkitApp->response( resp ) )
            respond( "+CSIM: 4,6F00\\n\\nOK" );

        return true;
    } else if ( param.length() >= 5 && param[1] == (char)0x2c &&
                    param[4] == (char)0x10 && param.size() >= 21 ) {
        // UNBLOCK CHV command, for resetting a PIN using a PUK.
        QString pinName = "PINVALUE";
        QString pukName = "PUKVALUE";
        if ( param[3] == (char)0x02 ) {
            pinName = "PIN2VALUE";
            pukName = "PUK2VALUE";
        }
        QByteArray pukValue = param.mid(5, 8);
        QByteArray pinValue = param.mid(13, 8);
        while ( pukValue.size() > 0 && pukValue[pukValue.size() - 1] == (char)0xFF )
            pukValue = pukValue.left( pukValue.size() - 1 );
        while ( pinValue.size() > 0 && pinValue[pinValue.size() - 1] == (char)0xFF )
            pinValue = pinValue.left( pinValue.size() - 1 );
        if ( QString::fromUtf8( pukValue ) != variable( pukName ) ) {
            respond( "+CSIM: 4,9804\\n\\nOK" );
        } else {
            setVariable( pinName, QString::fromUtf8( pinValue ) );
            simCsimOk( QByteArray() );
        }

        return true;
    } else if ( param.length() >= 5 && param[1] == (char)0xC2 ) {
        /* ENVELOPE */
        if ( !toolkitApp ) {
            respond( "+CSIM: 4,6F00\\n\\nOK" );
            return true;
        }

        QSimEnvelope env = QSimEnvelope::fromPdu( param.mid(5) );
        if ( toolkitApp->envelope( env ) )
            return simCsimOk( QByteArray() );

        /* Envelope not supported or current command doesn't allow envelopes. */
        respond( "+CSIM: 4,6F00\\n\\nOK" );
        return true;
    } else if ( param[1] == (char)0xf2 ) {
        /* STATUS command, for now ignore the parameters */
        return simCsimOk( QByteArray() );
    }

    // Don't know this SIM command.
    respond( "+CSIM: 4,6D00\\n\\nOK" );
    return true;
}

void SimRules::command( const QString& cmd )
{
    if(getMachine())
        getMachine()->handleToData(cmd);

    // Process call-related commands with the call manager.
    if ( _callManager->command( cmd ) )
        return;

    // Process SIM toolkit related commands with the current SIM application.
    if ( simCommand( cmd ) )
        return;

    if ( ! currentState->command( cmd ) ) {
        if ( cmd.startsWith( "AT+CRSM=" ) && fileSystem ) {

            // Process a filesystem access command.
            fileSystem->crsm( cmd.mid(8) );

        } else if ( cmd.startsWith( "AT+CPBS" ) ||
                    cmd.startsWith( "AT+CPBR" ) ||
                    cmd.startsWith( "AT+CPBW" ) ) {

            // Process a phonebook access command.
            phoneBook( cmd );

        } else if ( cmd.startsWith( "AT+CMUX=0," ) ) {

            // Request to turn on GSM 07.10 multiplexing.
            respond( "OK" );
            useGsm0710 = true;

        } else if ( cmd.startsWith( "AT+CPWD=\"SC\",\"" ) ) {

            // Change SIM PIN value.
            changePin( cmd );

        } else if ( cmd.startsWith( "AT" ) ) {

            // All other AT commands are not understood.
            respond( "ERROR" );

        }
    }
}

SimPhoneBook::SimPhoneBook( int size, QObject *parent )
    : QObject( parent )
{
    while ( size-- > 0 ) {
        numbers.append( QString() );
        names.append( QString() );
        hiddens.append( INVALID_VALUE_HIDDEN );
        groups.append( QString() );
        adNumbers.append( QString() );
        secondTexts.append( QString() );
        emails.append( QString() );
        sipUris.append( QString() );
        telUris.append( QString() );
    }
}

SimPhoneBook::~SimPhoneBook()
{
}

int SimPhoneBook::used() const
{
    int count = 0;
    for ( int index = 0; index < numbers.size(); ++index ) {
        if ( !numbers[index].isEmpty() )
            ++count;
    }
    return count;
}

QString SimPhoneBook::number( int index ) const
{
    if ( index >= 1 && index <= numbers.size() )
        return numbers[index - 1];
    else
        return QString();
}

QString SimPhoneBook::name( int index ) const
{
    if ( index >= 1 && index <= names.size() )
        return names[index - 1];
    else
        return QString();
}

int SimPhoneBook::hidden( int index ) const
{
    if ( index >= 1 && index <= hiddens.size() )
        return hiddens[index - 1];
    else
        return INVALID_VALUE_HIDDEN;
}

QString SimPhoneBook::group( int index ) const
{
    if ( index >= 1 && index <= groups.size() )
        return groups[index - 1];
    else
        return QString();
}

QString SimPhoneBook::adNumber( int index ) const
{
    if ( index >= 1 && index <= adNumbers.size() )
        return adNumbers[index - 1];
    else
        return QString();
}

QString SimPhoneBook::secondText( int index ) const
{
    if ( index >= 1 && index <= secondTexts.size() )
        return secondTexts[index - 1];
    else
        return QString();
}

QString SimPhoneBook::email( int index ) const
{
    if ( index >= 1 && index <= emails.size() )
        return emails[index - 1];
    else
        return QString();
}

QString SimPhoneBook::sipUri( int index ) const
{
    if ( index >= 1 && index <= sipUris.size() )
        return sipUris[index - 1];
    else
        return QString();
}

QString SimPhoneBook::telUri( int index ) const
{
    if ( index >= 1 && index <= telUris.size() )
        return telUris[index - 1];
    else
        return QString();
}

void SimPhoneBook::setDetails( int index, const QString& number,
    const QString& name, int hidden, const QString& group,
    const QString& adNumber, const QString& secondText, const QString& email,
    const QString& sipUri, const QString& telUri )
{
    if ( index >= 1 && index <= numbers.size() ) {
        numbers.replace( index - 1, number );
        names.replace( index - 1, name );
        hiddens.replace( index - 1, hidden );
        groups.replace( index - 1, group );
        adNumbers.replace( index - 1, adNumber );
        secondTexts.replace( index - 1, secondText );
        emails.replace( index - 1, email );
        sipUris.replace( index - 1, sipUri );
        telUris.replace( index - 1, telUri );
    }
}

void SimRules::initPhoneBooks()
{
    currentPhoneBook = "SM";
    phoneBooks.insert( "SM", new SimPhoneBook( 150, this ) );
}

void SimRules::loadPhoneBook( SimXmlNode& node )
{
    QString name = node.getAttribute( "name" );
    int size = node.getAttribute( "size" ).toInt();
    if ( !phoneBooks.contains( name ) ) {
        phoneBooks.insert( name, new SimPhoneBook( size, this ) );
    }
    SimPhoneBook *pb = phoneBooks[name];
    SimXmlNode *n = node.children;
    while ( n != 0 ) {
        if ( n->tag == "entry" ) {
            // Load a phone book entry.
            int index = n->getAttribute( "index" ).toInt();
            QString number = n->getAttribute( "number" );
            QString name = n->getAttribute( "name" );
            QString hiddenString = n->getAttribute( "hidden" );
            int hidden;
            if ( hiddenString.isEmpty() )
                hidden = INVALID_VALUE_HIDDEN;
            else
                hidden = hiddenString.toInt();
            QString group = n->getAttribute( "group" );
            QString adNumber = n->getAttribute( "adnumber" );
            QString secondText = n->getAttribute( "secondtext" );
            QString email = n->getAttribute( "email" );
            QString sipUri = n->getAttribute( "sip_uri" );
            QString telUri = n->getAttribute( "tel_uri" );
            pb->setDetails( index, number, name, hidden, group, adNumber,
                            secondText, email, sipUri, telUri );
        }
        n = n->next;
    }
}

QString SimRules::convertCharset( const QString& str )
{
    if ( variables["SCS"] == "UCS2" ) {
        static const char hexchars[] = "0123456789ABCDEF";
        const QChar *c = str.unicode();
        int length = str.length();
        QString s;
        while ( length-- > 0 ) {
            uint ch = c->unicode();
            ++c;
            s += hexchars[ (ch >> 12) & 0x0F ];
            s += hexchars[ (ch >> 8) & 0x0F ];
            s += hexchars[ (ch >> 4) & 0x0F ];
            s += hexchars[ ch & 0x0F ];
        }
        return s;
    } else {
        return str;
    }
}

void SimRules::phoneBook( const QString& cmd )
{
    SimPhoneBook *pb = currentPB();
    if ( !pb )
        return;

    // If the SIM PIN is not ready, then disable the phone books.
    if ( variable("PINNAME") != "READY" ) {
        respond( "ERROR" );
        return;
    }

    if ( cmd.startsWith( "AT+CPBS=?" ) ) {
        QStringList names = phoneBooks.keys();
        QString response = "+CPBS: (";
        foreach ( QString name, names ) {
            if ( response.length() > 8 )
                response += QChar(',');
            response += "\"" + name + "\"";
        }
        response += ")\\n\\nOK";
        respond( response );
    } else if ( cmd.startsWith( "AT+CPBS?" ) ) {
        respond( "+CPBS: \"" + currentPhoneBook + "\"," +
                 QString::number( pb->used() ) + "," +
                 QString::number( pb->size() ) + "\\n\\nOK" );
    } else if ( cmd.startsWith( "AT+CPBS=\"" ) ) {
        QString name = cmd.mid(9).left(2);
        if ( phoneBooks.contains( name ) ) {
            // If a password is supplied, then check it against PIN2VALUE.
            int comma = cmd.indexOf( QChar(',') );
            if ( comma >= 0 ) {
                QString password = cmd.mid(comma + 1);
                password.remove( QChar('"') );
                if ( password != variable( "PIN2VALUE" ) ) {
                    respond( "ERROR" );
                    return;
                }
            }
            currentPhoneBook = name;
            respond( "OK" );
        } else {
            // Invalid phone book name.
            respond( "ERROR" );
        }
    } else if ( cmd.startsWith( "AT+CPBR=?" ) ) {
        respond( "+CPBR: (1-" + QString::number( pb->size() ) + ")"
                 + "," + QString::number( PHONEBOOK_NLENGTH )
                 + "," + QString::number( PHONEBOOK_TLENGTH )
                 + "," + QString::number( PHONEBOOK_GLENGTH )
                 + "," + QString::number( PHONEBOOK_SLENGTH )
                 + "," + QString::number( PHONEBOOK_ELENGTH )
                 + "," + QString::number( PHONEBOOK_SIPLENGTH )
                 + "," + QString::number( PHONEBOOK_TELLENGTH ) + "\\n\\nOK");
    } else if ( cmd.startsWith( "AT+CPBR=" ) ) {
        QString args = cmd.mid(8);
        int comma = args.indexOf( QChar(',') );
        int first, last;
        if ( comma < 0 ) {
            // Read one entry.
            first = args.toInt();
            last = first;
        } else {
            // Read a range of entries.
            first = args.left(comma).toInt();
            last = args.mid(comma + 1).toInt();
        }
        while ( first <= last ) {
            QString number = pb->number( first );
            QString name = convertCharset( pb ->name( first ) );
            int hidden = pb->hidden( first );
            QString group = convertCharset( pb->group( first ) );
            QString adNumber = pb->adNumber( first );
            QString secondText = convertCharset( pb->secondText( first ) );
            QString email = convertCharset( pb->email( first ) );
            QString sipUri = convertCharset( pb->sipUri( first ) );
            QString telUri = convertCharset( pb->telUri( first ) );
            if ( !number.isEmpty() ) {
                QString s = "+CPBR: " + QString::number( first ) + "," +
                         QAtUtils::encodeNumber( number ) + ",\"" +
                         QAtUtils::quote( name ) + "\"";
                if (hidden != INVALID_VALUE_HIDDEN) {
                    s += "," + QString::number( hidden );
                } else
                    goto out;
                if ( !group.isEmpty() ) {
                    s += ",\"" + QAtUtils::quote( group ) + "\"";
                } else
                    goto out;
                if ( !adNumber.isEmpty() ) {
                    s += "," + QAtUtils::encodeNumber( adNumber );
                } else
                    goto out;
                if ( !secondText.isEmpty() ) {
                    s += ",\"" + QAtUtils::quote( secondText ) + "\"";
                } else
                    goto out;
                if ( !email.isEmpty() ) {
                    s += ",\"" + QAtUtils::quote( email ) + "\"";
                } else
                    goto out;
                if ( !sipUri.isEmpty() ) {
                    s += ",\"" + QAtUtils::quote( sipUri ) + "\"";
                } else
                    goto out;
                if ( !telUri.isEmpty() ) {
                    s += ",\"" + QAtUtils::quote( telUri ) + "\"";
                } else
                    goto out;

out:
                respond( s );
            }
            ++first;
        }
        respond( "OK" );
    } else if ( cmd.startsWith( "AT+CPBW=" ) ) {
        uint posn = 8;
        int index = (int)QAtUtils::parseNumber( cmd, posn );
        if ( index < 1 || index > pb->size() ) {
            // Invalid index.
            respond( "ERROR" );
            return;
        }
        if ( ((int)posn) >= cmd.length() ) {
            // Delete an entry from the phone book.
            pb->setDetails( index, QString(), QString() );
        } else {
            // Write new details to an entry.
            QString number = QAtUtils::nextString( cmd, posn );
            uint type = QAtUtils::parseNumber( cmd, posn );
            QString name = QAtUtils::nextString( cmd, posn );
            number = QAtUtils::decodeNumber( number, type );
            QString group = QAtUtils::nextString( cmd, posn );
            QString adNumber = QAtUtils::nextString( cmd, posn );
            uint adType = QAtUtils::parseNumber( cmd, posn );
            adNumber = QAtUtils::decodeNumber( adNumber, adType );
            QString secondText = QAtUtils::nextString( cmd, posn );
            QString email = QAtUtils::nextString( cmd, posn );
            QString sipUri = QAtUtils::nextString( cmd, posn );
            QString telUri = QAtUtils::nextString( cmd, posn );
            int hidden = QAtUtils::parseNumber( cmd, posn, INVALID_VALUE_HIDDEN);
            if ( number.length() > PHONEBOOK_NLENGTH ||
                 name.length() > PHONEBOOK_TLENGTH ||
                 group.length() > PHONEBOOK_GLENGTH ||
                 adNumber.length() > PHONEBOOK_NLENGTH ||
                 secondText.length() > PHONEBOOK_SLENGTH ||
                 email.length() > PHONEBOOK_ELENGTH ||
                 sipUri.length() > PHONEBOOK_SIPLENGTH ||
                 telUri.length() > PHONEBOOK_TELLENGTH ) {
                 respond( "ERROR" );
                 return;
            }
            pb->setDetails( index, number, name, hidden, group,
                            adNumber, secondText, email, sipUri, telUri );
        }
        respond( "OK" );
    } else {
        respond( "ERROR" );
    }
}

void SimRules::changePin( const QString& cmd )
{
    QStringList parts = cmd.split(QChar('"'));
    if (parts.size() < 6) {
        respond( "ERROR" );
        return;
    }
    QString oldPin = parts[3];
    QString newPin = parts[5];
    if ( variable( "PINVALUE" ) != oldPin ) {
        respond( "ERROR" );
        return;
    }
    if ( newPin.size() < 4 || newPin.size() > 8 ) {
        respond( "ERROR" );
        return;
    }
    setVariable( "PINVALUE", newPin );
    respond( "OK" );
}

SimPhoneBook *SimRules::currentPB() const
{
    if ( phoneBooks.contains( currentPhoneBook ) )
        return phoneBooks[currentPhoneBook];
    else
        return 0;
}

int SimRules::newCall()
{
    int id;
    for( id = 1; id <= 8; ++id ) {
        if ( ( usedCallIds & (1 << id) ) == 0 ) {
            break;
        }
    }
    usedCallIds |= (1 << id);
    return id;
}


void SimRules::forgetCall( int id )
{
    usedCallIds &= ~(1 << id);
}


void SimRules::forgetAllCalls()
{
    usedCallIds = 0;
}

QString expandEscapes( const QString& data, bool eol )
{
    // Expand escapes and end of line markers in the data.
    static char const escapes[] = "\a\bcde\fghijklm\nopq\rs\tu\vwxyz";
    QByteArray res;
    QByteArray buffer = data.toUtf8();
    const char *buf = buffer.data();
    int ch;
    int prevch = 0;

    res += ( '\r' );
    res += ( '\n' );

    while ( ( ch = *buf++ ) != '\0' ) {
        if ( ch == '\n' ) {
            res += ( '\r' );
            res += ( '\n' );
        } else if ( ch == '\\' ) {
            ch = *buf++;
            if ( ch == '\0' ) {
                res += ( '\\' );
                break;
            } else if ( ch == 'n' ) {
                res += ( '\r' );
                res += ( '\n' );
                ch = '\n';
            } else if ( ch >= 'a' && ch <= 'z' ) {
                ch = escapes[ch - 'a'];
                res += ( ch );
            } else {
                res += ( '\\' );
                res += ( ch );
            }
        } else if ( ch != '\r' ) {
            res += ( ch );
        }
        prevch = ch;
    }
    if ( prevch != '\n' && eol ) {
        res += ( '\r' );
        res += ( '\n' );
    }

    return QString::fromUtf8(res.data());
}


void SimRules::respond( const QString& resp, int delay, bool eol )
{
    QString r = expand( resp );
    QByteArray escaped = expandEscapes( r, eol ).toUtf8();

    if ( !delay ) {
        writeChatData(escaped.data(), escaped.length());
        flush();
    } else {
        SimDelayTimer *timer = new SimDelayTimer( escaped, currentChannel );
        timer->setSingleShot( true );
        connect(timer,SIGNAL(timeout()),this,SLOT(delayTimeout()));
        timer->start( delay );
    }
    if(getMachine())
        getMachine()->handleFromData(QString(escaped));
}

void SimRules::proactiveCommandNotify( const QByteArray& cmd )
{
    unsolicited( "+CUSATP: " + QAtUtils::toHex( cmd ) );
}

void SimRules::callControlEventNotify( const QSimControlEvent& evt )
{
    unsolicited( "*TCC: " + QString::number( (int) (evt.type()) ) +
              "," + QAtUtils::toHex( evt.toPdu() ) );
}

void SimRules::delayTimeout()
{
    SimDelayTimer *timer = (SimDelayTimer *)sender();
    int save = currentChannel;
    currentChannel = timer->channel;
    writeChatData(timer->response.toLatin1().data(), timer->response.length());
    flush();
    currentChannel = save;
    timer->deleteLater();
}


void SimRules::dialCheck( const QString& number, bool& ok )
{
    // Bail out if the fixed-dialing phone book is not active or present.
    if ( variable("FD") != "1" )
        return;
    if ( !phoneBooks.contains( "FD" ) ) {
        ok = false;
        return;
    }

    // The dial is OK if the number starts with an existing number in "FD".
    for( int i = 1; i <= phoneBooks["FD"]->used(); i++ ){
        if( number.startsWith(phoneBooks["FD"]->number(i)) ){
            ok = true;
            return;
        }
        ok = false;
    }

    // The dial is OK if it is one of the standard emergency numbers.
    if (number == "112" || number == "911" || number == "08" || number == "000") {
        ok = true;
    }
}

void SimRules::unsolicited( const QString& resp )
{
    QString r = expand( resp );

    QByteArray escaped = expandEscapes( r, true ).toUtf8();
    writeChatData( escaped , escaped.length() );
    flush();
}


void SimRules::writeGsmFrame( int type, const char *data, uint len )
{
    char frame[MAX_GSM0710_FRAME_SIZE + 6];
    frame[0] = (char)0xF9;
    frame[1] = (char)((currentChannel << 2) | 0x03);
    frame[2] = (char)type;
    frame[3] = (char)((len << 1) | 0x01);
    if ( len > 0 )
        memcpy( frame + 4, data, len);
    // Note: GSM 07.10 says that the CRC is only computed over the header.
    frame[len + 4] = (char)computeCrc( frame + 1, 3 );
    frame[len + 5] = (char)0xF9;
    write( frame, len + 6 );
}


void SimRules::writeChatData( const char *data, uint len )
{
    if ( !isOpen() )
        return;
    if ( !useGsm0710 ) {
        // We aren't using multi-plexing at present.
        write( data, len );
    } else {
        // Format GSM 07.10 frames and send them via the current channel.
        uint templen;
        while ( len > 0 ) {
            templen = len;
            if ( templen > MAX_GSM0710_FRAME_SIZE ) {
                templen = MAX_GSM0710_FRAME_SIZE;
            }
            writeGsmFrame( 0xEF, data, templen );
            data += templen;
            len -= templen;
        }
    }
}


QString SimRules::expand( const QString& s )
{
    int prev, index, len, start, end;
    QString result;
    QString name;

    index = s.indexOf( QChar('$') );
    if ( index == -1 )
        return s;

    prev = 0;
    len = s.length();
    do {
        result += s.mid( prev, index - prev );
        ++index;
        if ( index < len && s[index] == '{' ) {
            ++index;
            start = index;
            end = s.indexOf( QChar('}'), index );
            if ( end == -1 ) {
                end = len;
                index = len;
            } else {
                index = end + 1;
            }
            name = s.mid( start, end - start );
            result += variable(name);
        } else {
            result += "$";
        }
        prev = index;
        index = s.indexOf( QChar('$'), index );
    } while ( index != -1 );
    result += s.mid( prev );
    return result;
}

void SimRules::queryVariable( const QString &name )
{
    emit returnQueryVariable( name, variable(name) );
}

void SimRules::queryState( )
{
    if (currentState)
        emit returnQueryState( currentState->name() );
    else
        emit returnQueryState( QString() );
}

void SimRules::setVariable( const QString& name, const QString& value )
{
        variables[name] = expand(value);
}

QString SimRules::variable( const QString& name )
{
    return variables[name];

}