summaryrefslogtreecommitdiffstats
path: root/src/plugins/bearer/symbian/qnetworksession_impl.cpp
blob: 17a053e2777cb1a508bd2b3c47f34db5ca905707 (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
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.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 the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qnetworksession_impl.h"
#include "symbianengine.h"

#include <es_enum.h>
#include <es_sock.h>
#include <in_sock.h>
#include <private/qcore_symbian_p.h>

#ifdef SNAP_FUNCTIONALITY_AVAILABLE
#include <cmmanager.h>
#endif

#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE)
#include <extendedconnpref.h>
#endif

#ifndef QT_NO_BEARERMANAGEMENT

QT_BEGIN_NAMESPACE

QNetworkSessionPrivateImpl::QNetworkSessionPrivateImpl(SymbianEngine *engine)
:   engine(engine), iSocketServ(qt_symbianGetSocketServer()),
    ipConnectionNotifier(0), ipConnectionStarter(0),
    iHandleStateNotificationsFromManager(false), iFirstSync(true), iStoppedByUser(false),
    iClosedByUser(false), iError(QNetworkSession::UnknownSessionError), iALREnabled(0),
    iConnectInBackground(false), iCurrentIap(0), isOpening(false)
{

#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    iMobility = NULL;
#endif

    TRAP_IGNORE(iConnectionMonitor.ConnectL());
}

void QNetworkSessionPrivateImpl::closeHandles()
{
    QMutexLocker lock(&mutex);
    updateCurrentIap(0);
    // Cancel Connection Progress Notifications first.
    // Note: ConnectionNotifier must be destroyed before RConnection::Close()
    //       => deleting ipConnectionNotifier results RConnection::CancelProgressNotification()
    delete ipConnectionNotifier;
    ipConnectionNotifier = NULL;

#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    // mobility monitor must be deleted before RConnection is closed
    delete iMobility;
    iMobility = NULL;
#endif

    // Cancel possible RConnection::Start() - may call RConnection::Close if Start was in progress
    delete ipConnectionStarter;
    ipConnectionStarter = 0;
    //close any open connection (note Close twice is safe in case Cancel did it above)
    iConnection.Close();

    QSymbianSocketManager::instance().setDefaultConnection(0);

#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this)
             << " - handles closed";
#endif

}

QNetworkSessionPrivateImpl::~QNetworkSessionPrivateImpl()
{
    isOpen = false;
    isOpening = false;

    closeHandles();
    iConnectionMonitor.Close();
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this)
             << " - destroyed";
#endif
}

void QNetworkSessionPrivateImpl::configurationStateChanged(quint32 accessPointId, quint32 connMonId, QNetworkSession::State newState)
{
    if (iHandleStateNotificationsFromManager) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
        qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                 << "configurationStateChanged from manager for IAP : " << QString::number(accessPointId)
                 << "connMon ID : " << QString::number(connMonId) << " : to a state: " << newState
                 << "whereas my current state is: " << state;
#else
      Q_UNUSED(connMonId);
#endif
        this->newState(newState, accessPointId);
    }
}

void QNetworkSessionPrivateImpl::configurationRemoved(QNetworkConfigurationPrivatePointer config)
{
    if (!publicConfig.isValid())
        return;

    TUint32 publicNumericId =
        toSymbianConfig(privateConfiguration(publicConfig))->numericIdentifier();

    if (toSymbianConfig(config)->numericIdentifier() == publicNumericId) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
        qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                 << "configurationRemoved IAP: " << QString::number(publicNumericId) << " : going to State: Invalid";
#endif
        this->newState(QNetworkSession::Invalid, publicNumericId);
    }
}

void QNetworkSessionPrivateImpl::configurationAdded(QNetworkConfigurationPrivatePointer config)
{
    Q_UNUSED(config);
    // If session is based on service network, some other app may create new access points
    // to the SNAP --> synchronize session's state with that of interface's.
    if (!publicConfig.isValid() || publicConfig.type() != QNetworkConfiguration::ServiceNetwork)
        return;

#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
        qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                 << "configurationAdded IAP: "
                 << toSymbianConfig(config)->numericIdentifier();
#endif

        syncStateWithInterface();
}

// Function sets the state of the session to match the state
// of the underlying interface (the configuration this session is based on)
void QNetworkSessionPrivateImpl::syncStateWithInterface()
{
    if (!publicConfig.isValid())
        return;

    if (iFirstSync) {
        QObject::connect(engine,
                         SIGNAL(configurationStateChanged(quint32,quint32,QNetworkSession::State)),
                         this,
                         SLOT(configurationStateChanged(quint32,quint32,QNetworkSession::State)));
        // Listen to configuration removals, so that in case the configuration
        // this session is based on is removed, session knows to enter Invalid -state.
        QObject::connect(engine, SIGNAL(configurationRemoved(QNetworkConfigurationPrivatePointer)),
                         this, SLOT(configurationRemoved(QNetworkConfigurationPrivatePointer)));
        // Connect to configuration additions, so that in case a configuration is added
        // in a SNAP this session is based on, the session knows to synch its state with its
        // interface.
        QObject::connect(engine, SIGNAL(configurationAdded(QNetworkConfigurationPrivatePointer)),
                         this, SLOT(configurationAdded(QNetworkConfigurationPrivatePointer)));
    }
    // Start listening IAP state changes from QNetworkConfigurationManagerPrivate
    iHandleStateNotificationsFromManager = true;    

    // Check what is the state of the configuration this session is based on
    // and set the session in appropriate state.
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
             << "syncStateWithInterface() state of publicConfig is: " << publicConfig.state();
#endif
    switch (publicConfig.state()) {
    case QNetworkConfiguration::Active:
        newState(QNetworkSession::Connected);
        break;
    case QNetworkConfiguration::Discovered:
        newState(QNetworkSession::Disconnected);
        break;
    case QNetworkConfiguration::Defined:
        newState(QNetworkSession::NotAvailable);
        break;
    case QNetworkConfiguration::Undefined:
    default:
        newState(QNetworkSession::Invalid);
    }
}

#ifndef QT_NO_NETWORKINTERFACE
QNetworkInterface QNetworkSessionPrivateImpl::interface(TUint iapId) const
{
    QString interfaceName;

    TSoInetInterfaceInfo ifinfo;
    TPckg<TSoInetInterfaceInfo> ifinfopkg(ifinfo);
    TSoInetIfQuery ifquery;
    TPckg<TSoInetIfQuery> ifquerypkg(ifquery);
 
    // Open dummy socket for interface queries
    RSocket socket;
    TInt retVal = socket.Open(iSocketServ, _L("udp"));
    if (retVal != KErrNone) {
        return QNetworkInterface();
    }
 
    // Start enumerating interfaces
    socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl);
    while(socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, ifinfopkg) == KErrNone) {
        ifquery.iName = ifinfo.iName;
        TInt err = socket.GetOpt(KSoInetIfQueryByName, KSolInetIfQuery, ifquerypkg);
        if(err == KErrNone && ifquery.iZone[1] == iapId) { // IAP ID is index 1 of iZone
            if(ifinfo.iAddress.Address() > 0) {
                interfaceName = QString::fromUtf16(ifinfo.iName.Ptr(),ifinfo.iName.Length());
                break;
            }
        }
    }
 
    socket.Close();
 
    if (interfaceName.isEmpty()) {
        return QNetworkInterface();
    }
 
    return QNetworkInterface::interfaceFromName(interfaceName);
}
#endif

#ifndef QT_NO_NETWORKINTERFACE
QNetworkInterface QNetworkSessionPrivateImpl::currentInterface() const
{
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
             << "currentInterface() requested, state: " << state
             << "publicConfig validity: " << publicConfig.isValid();
    if (activeInterface.isValid())
        qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                 << "interface is: " << activeInterface.humanReadableName();
#endif

    if (!publicConfig.isValid() || state != QNetworkSession::Connected) {
        return QNetworkInterface();
    }
    
    return activeInterface;
}
#endif

QVariant QNetworkSessionPrivateImpl::sessionProperty(const QString& key) const
{
    if (key == "ConnectInBackground") {
        return QVariant(iConnectInBackground);
    }
    return QVariant();
}

void QNetworkSessionPrivateImpl::setSessionProperty(const QString& key, const QVariant& value)
{
    // Valid value means adding property, invalid means removing it.
    if (key == "ConnectInBackground") {
        if (value.isValid()) {
            iConnectInBackground = value.toBool();
        } else {
            iConnectInBackground = EFalse;
        }
    }
}

QString QNetworkSessionPrivateImpl::errorString() const
{
    switch (iError) {
    case QNetworkSession::UnknownSessionError:
        return tr("Unknown session error.");
    case QNetworkSession::SessionAbortedError:
        return tr("The session was aborted by the user or system.");
    case QNetworkSession::OperationNotSupportedError:
        return tr("The requested operation is not supported by the system.");
    case QNetworkSession::InvalidConfigurationError:
        return tr("The specified configuration cannot be used.");
    case QNetworkSession::RoamingError:
        return tr("Roaming was aborted or is not possible.");
    }
 
    return QString();
}

QNetworkSession::SessionError QNetworkSessionPrivateImpl::error() const
{
    return iError;
}

void QNetworkSessionPrivateImpl::open()
{
    QMutexLocker lock(&mutex);
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
        qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                << "open() called, session state is: " << state << " and isOpen is: "
                << isOpen << isOpening;
#endif

    if (isOpen || isOpening)
        return;

    isOpening = true;

    // Stop handling IAP state change signals from QNetworkConfigurationManagerPrivate
    // => RConnection::ProgressNotification will be used for IAP/SNAP monitoring
    iHandleStateNotificationsFromManager = false;

    // Configuration may have been invalidated after session creation by platform
    // (e.g. configuration has been deleted).
    if (!publicConfig.isValid()) {
        newState(QNetworkSession::Invalid);
        iError = QNetworkSession::InvalidConfigurationError;
        emit QNetworkSessionPrivate::error(iError);
        return;
    }
    // If opening a undefined configuration, session emits error and enters
    // NotAvailable -state. Note that we will try ones in 'defined' state to avoid excessive
    // need for WLAN scans (via updateConfigurations()), because user may have walked
    // into a WLAN range, but periodic background scan has not occurred yet -->
    // we don't want to force application to make frequent updateConfigurations() calls
    // to be able to try if e.g. home WLAN is available.
    if (publicConfig.state() == QNetworkConfiguration::Undefined) {
        newState(QNetworkSession::NotAvailable);
        iError = QNetworkSession::InvalidConfigurationError;
        emit QNetworkSessionPrivate::error(iError);
        return;
    }
    // Clear possible previous states
    iStoppedByUser = false;
    iClosedByUser = false;

    Q_ASSERT(!iConnection.SubSessionHandle());
    TInt error = iConnection.Open(iSocketServ);
    if (error != KErrNone) {
        // Could not open RConnection
        newState(QNetworkSession::Invalid);
        iError = QNetworkSession::UnknownSessionError;
        emit QNetworkSessionPrivate::error(iError);
        syncStateWithInterface();    
        return;
    }
    
    // Use RConnection::ProgressNotification for IAP/SNAP monitoring
    // (<=> ConnectionProgressNotifier uses RConnection::ProgressNotification)
    if (!ipConnectionNotifier) {
        ipConnectionNotifier = new ConnectionProgressNotifier(*this,iConnection);
    }
    if (ipConnectionNotifier) {
        ipConnectionNotifier->StartNotifications();
    }
    
    if (publicConfig.type() == QNetworkConfiguration::InternetAccessPoint) {
            SymbianNetworkConfigurationPrivate *symbianConfig =
                toSymbianConfig(privateConfiguration(publicConfig));

#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE)
            // With One Click Connectivity (Symbian^3 onwards) it is possible
            // to connect silently, without any popups.
            TConnPrefList pref;
            TExtendedConnPref prefs;

            prefs.SetIapId(symbianConfig->numericIdentifier());
            if (iConnectInBackground) {
                prefs.SetNoteBehaviour( TExtendedConnPref::ENoteBehaviourConnSilent );
            }
            pref.AppendL(&prefs);
#else
            TCommDbConnPref pref;
            pref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);

            pref.SetIapId(symbianConfig->numericIdentifier());
#endif
            if (!ipConnectionStarter) {
                ipConnectionStarter = new ConnectionStarter(*this, iConnection);
                ipConnectionStarter->Start(pref);
            }
            // Avoid flip flop of states if the configuration is already
            // active. IsOpen/opened() will indicate when ready.
            if (state != QNetworkSession::Connected) {
                newState(QNetworkSession::Connecting);
            }
    } else if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) {
        SymbianNetworkConfigurationPrivate *symbianConfig =
            toSymbianConfig(privateConfiguration(publicConfig));

#if defined(OCC_FUNCTIONALITY_AVAILABLE) && defined(SNAP_FUNCTIONALITY_AVAILABLE)
        // On Symbian^3 if service network is not reachable, it triggers a UI (aka EasyWLAN) where
        // user can create new IAPs. To detect this, we need to store the number of IAPs
        // there was before connection was started.
        iKnownConfigsBeforeConnectionStart = engine->accessPointConfigurationIdentifiers();
        TConnPrefList snapPref;
        TExtendedConnPref prefs;
        prefs.SetSnapId(symbianConfig->numericIdentifier());
        if (iConnectInBackground) {
            prefs.SetNoteBehaviour( TExtendedConnPref::ENoteBehaviourConnSilent );
        }
        snapPref.AppendL(&prefs);
#else
        TConnSnapPref snapPref(symbianConfig->numericIdentifier());
#endif
        if (!ipConnectionStarter) {
            ipConnectionStarter = new ConnectionStarter(*this, iConnection);
            ipConnectionStarter->Start(snapPref);
        }
        // Avoid flip flop of states if the configuration is already
        // active. IsOpen/opened() will indicate when ready.
        if (state != QNetworkSession::Connected) {
            newState(QNetworkSession::Connecting);
        }
    } else if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
        iKnownConfigsBeforeConnectionStart = engine->accessPointConfigurationIdentifiers();
        if (!ipConnectionStarter) {
            ipConnectionStarter = new ConnectionStarter(*this, iConnection);
            ipConnectionStarter->Start();
        }
        newState(QNetworkSession::Connecting);
    }
 
    if (error != KErrNone) {
        isOpen = false;
        isOpening = false;
        iError = QNetworkSession::UnknownSessionError;
        closeHandles();
        emit QNetworkSessionPrivate::error(iError);
        syncStateWithInterface();    
    }
}

TUint QNetworkSessionPrivateImpl::iapClientCount(TUint aIAPId) const
{
    TRequestStatus status;
    TUint connectionCount;
    if (!iConnectionMonitor.Handle())
        return 0;
    iConnectionMonitor.GetConnectionCount(connectionCount, status);
    User::WaitForRequest(status);
    if (status.Int() == KErrNone) {
        for (TUint i = 1; i <= connectionCount; i++) {
            TUint connectionId;
            TUint subConnectionCount;
            iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount);
            TUint apId;
            iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount, KIAPId, apId, status);
            User::WaitForRequest(status);
            if (apId == aIAPId) {
                TConnMonClientEnumBuf buf;
                iConnectionMonitor.GetPckgAttribute(connectionId, 0, KClientInfo, buf, status);
                User::WaitForRequest(status);
                if (status.Int() == KErrNone) {
                    return buf().iCount;
                }
            }
        }
    }
    return 0;
}

void QNetworkSessionPrivateImpl::close(bool allowSignals)
{
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
            << "close() called, session state is: " << state << " and isOpen is : "
            << isOpen;
#endif

    if (!isOpen && state != QNetworkSession::Connecting) {
        return;
    }
    // Mark this session as closed-by-user so that we are able to report
    // distinguish between stop() and close() state transitions
    // when reporting.
    iClosedByUser = true;
    isOpen = false;
    isOpening = false;

    serviceConfig = QNetworkConfiguration();
    
    closeHandles();

    // Start handling IAP state change signals from QNetworkConfigurationManagerPrivate
    iHandleStateNotificationsFromManager = true;

    // If UserChoice, go down immediately. If some other configuration,
    // go down immediately if there is no reports expected from the platform;
    // in practice Connection Monitor is aware of connections only after
    // KFinishedSelection event, and hence reports only after that event, but
    // that does not seem to be trusted on all Symbian versions --> safest
    // to go down.
    if (publicConfig.type() == QNetworkConfiguration::UserChoice || state == QNetworkSession::Connecting) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
        qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                 << "going disconnected right away, since either UserChoice or Connecting";
#endif
        newState(QNetworkSession::Closing);
        newState(QNetworkSession::Disconnected);
    }
    if (allowSignals) {
        emit closed();
    }
}

void QNetworkSessionPrivateImpl::stop()
{
    QMutexLocker lock(&mutex);
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
            << "stop() called, session state is: " << state << " and isOpen is : "
            << isOpen;
#endif
    if (!isOpen &&
        publicConfig.isValid() &&
        publicConfig.type() == QNetworkConfiguration::InternetAccessPoint &&
        iConnectionMonitor.Handle()) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
            << "since session is not open, using RConnectionMonitor to stop() the interface";
#endif
        iStoppedByUser = true;
        // If the publicConfig is type of IAP, enumerate through connections at
        // connection monitor. If publicConfig is active in that list, stop it.
        // Otherwise there is nothing to stop. Note: because this QNetworkSession is not open,
        // activeConfig is not usable.
        TUint count;
        TRequestStatus status;
        iConnectionMonitor.GetConnectionCount(count, status);
        User::WaitForRequest(status);
        if (status.Int() != KErrNone) {
            return;
        }
        TUint numSubConnections; // Not used but needed by GetConnectionInfo i/f
        TUint connectionId;
        for (TUint i = 1; i <= count; ++i) {
            // Get (connection monitor's assigned) connection ID
            TInt ret = iConnectionMonitor.GetConnectionInfo(i, connectionId, numSubConnections);            
            if (ret == KErrNone) {
                SymbianNetworkConfigurationPrivate *symbianConfig =
                    toSymbianConfig(privateConfiguration(publicConfig));

                // See if connection Id matches with our Id. If so, stop() it.
                if (symbianConfig->connectionIdentifier() == connectionId) {
                    ret = iConnectionMonitor.SetBoolAttribute(connectionId,
                                                              0, // subConnectionId don't care
                                                              KConnectionStop,
                                                              ETrue);
                }
            }
            // Enter disconnected state right away since the session is not even open.
            // Symbian^3 connection monitor does not emit KLinkLayerClosed when
            // connection is stopped via connection monitor.
            newState(QNetworkSession::Disconnected);
        }
    } else if (isOpen) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
            << "since session is open, using RConnection to stop() the interface";
#endif
        // Since we are open, use RConnection to stop the interface
        isOpen = false;
        isOpening = false;
        iStoppedByUser = true;
        newState(QNetworkSession::Closing);
        if (ipConnectionNotifier) {
            ipConnectionNotifier->StopNotifications();
            // Start handling IAP state change signals from QNetworkConfigurationManagerPrivate
            iHandleStateNotificationsFromManager = true;
        }
        iConnection.Stop(RConnection::EStopAuthoritative);
        isOpen = true;
        isOpening = false;
        close(false);
        emit closed();
    }
}

void QNetworkSessionPrivateImpl::migrate()
{
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    if (iMobility) {
        QSymbianSocketManager::instance().setDefaultConnection(0);
        // Start migrating to new IAP
        iMobility->MigrateToPreferredCarrier();
    }
#endif
}

void QNetworkSessionPrivateImpl::ignore()
{
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    if (iMobility) {
        iMobility->IgnorePreferredCarrier();

        if (!iALRUpgradingConnection) {
            newState(QNetworkSession::Disconnected);
        } else {
            newState(QNetworkSession::Connected,iOldRoamingIap);
        }
    }
#endif
}

void QNetworkSessionPrivateImpl::accept()
{
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    if (iMobility) {
        iMobility->NewCarrierAccepted();

        QNetworkConfiguration newActiveConfig = activeConfiguration(iNewRoamingIap);

        QSymbianSocketManager::instance().setDefaultConnection(&iConnection);

        updateCurrentIap(iNewRoamingIap);

        newState(QNetworkSession::Connected, iNewRoamingIap);
    }
#endif
}

void QNetworkSessionPrivateImpl::reject()
{
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    if (iMobility) {
        iMobility->NewCarrierRejected();

        if (!iALRUpgradingConnection) {
            newState(QNetworkSession::Disconnected);
        } else {
            QNetworkConfiguration newActiveConfig = activeConfiguration(iOldRoamingIap);

            QSymbianSocketManager::instance().setDefaultConnection(&iConnection);

            newState(QNetworkSession::Connected, iOldRoamingIap);
        }
    }
#endif
}

#ifdef SNAP_FUNCTIONALITY_AVAILABLE
void QNetworkSessionPrivateImpl::PreferredCarrierAvailable(TAccessPointInfo aOldAPInfo,
                                                       TAccessPointInfo aNewAPInfo,
                                                       TBool aIsUpgrade,
                                                       TBool aIsSeamless)
{
    iOldRoamingIap = aOldAPInfo.AccessPoint();
    iNewRoamingIap = aNewAPInfo.AccessPoint();
    newState(QNetworkSession::Roaming);
    if (iALREnabled > 0) {
        iALRUpgradingConnection = aIsUpgrade;
        QList<QNetworkConfiguration> configs = publicConfig.children();
        for (int i=0; i < configs.count(); i++) {
            SymbianNetworkConfigurationPrivate *symbianConfig =
                toSymbianConfig(privateConfiguration(configs[i]));

            if (symbianConfig->numericIdentifier() == aNewAPInfo.AccessPoint()) {
                // Any slot connected to the signal might throw an std::exception,
                // which must not propagate into Symbian code (this function is a callback
                // from platform). We could convert exception to a symbian Leave, but since the
                // prototype of this function bans this (no trailing 'L'), we just catch
                // and drop.
                QT_TRY {
                    emit preferredConfigurationChanged(configs[i], aIsSeamless);
                }
                QT_CATCH (std::exception&) {}
            }
        }
    } else {
        migrate();
    }
}

void QNetworkSessionPrivateImpl::NewCarrierActive(TAccessPointInfo /*aNewAPInfo*/, TBool /*aIsSeamless*/)
{
    if (iALREnabled > 0) {
        QT_TRY {
            emit newConfigurationActivated();
        }
        QT_CATCH (std::exception&) {}
    } else {
        accept();
    }
}

void QNetworkSessionPrivateImpl::Error(TInt aError)
{
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
            << "roaming Error() occurred" << aError << ", isOpen is: " << isOpen;
#endif
    if (aError == KErrCancel)
        return; //avoid recursive deletion
    if (isOpen) {
        isOpen = false;
        isOpening = false;
        activeConfig = QNetworkConfiguration();
        serviceConfig = QNetworkConfiguration();
        iError = QNetworkSession::RoamingError;
        closeHandles();
        emit QNetworkSessionPrivate::error(iError);
        QT_TRY {
            syncStateWithInterface();
            // In some cases IAP is still in Connected state when
            // syncStateWithInterface(); is called
            // => Following call makes sure that Session state
            //    changes immediately to Disconnected.
            newState(QNetworkSession::Disconnected);
            emit closed();
        }
        QT_CATCH (std::exception&) {}
    } else if (iStoppedByUser) {
        // If the user of this session has called the stop() and
        // configuration is based on internet SNAP, this needs to be
        // done here because platform might roam.
        QT_TRY {
            newState(QNetworkSession::Disconnected);
        }
        QT_CATCH (std::exception&) {}
    }
}
#endif

void QNetworkSessionPrivateImpl::setALREnabled(bool enabled)
{
    if (enabled) {
        iALREnabled++;
    } else {
        iALREnabled--;
    }
}

QNetworkConfiguration QNetworkSessionPrivateImpl::bestConfigFromSNAP(const QNetworkConfiguration& snapConfig) const
{
    QNetworkConfiguration config;
    QList<QNetworkConfiguration> subConfigurations = snapConfig.children();
    for (int i = 0; i < subConfigurations.count(); i++ ) {
        if (subConfigurations[i].state() == QNetworkConfiguration::Active) {
            config = subConfigurations[i];
            break;
        } else if (!config.isValid() && subConfigurations[i].state() == QNetworkConfiguration::Discovered) {
            config = subConfigurations[i];
        }
    }
    if (!config.isValid() && subConfigurations.count() > 0) {
        config = subConfigurations[0];
    }
    return config;
}

quint64 QNetworkSessionPrivateImpl::bytesWritten() const
{
    return transferredData(KUplinkData);
}

quint64 QNetworkSessionPrivateImpl::bytesReceived() const
{
    return transferredData(KDownlinkData);
}

quint64 QNetworkSessionPrivateImpl::transferredData(TUint dataType) const
{
    if (!publicConfig.isValid()) {
        return 0;
    }
    
    QNetworkConfiguration config;
    if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
        if (serviceConfig.isValid()) {
            config = serviceConfig;
        } else {
            if (activeConfig.isValid()) {
                config = activeConfig;
            }
        }
    } else {
        config = publicConfig;
    }

    if (!config.isValid()) {
        return 0;
    }
    
    if (!iConnectionMonitor.Handle())
        return 0;
    TUint count;
    TRequestStatus status;
    iConnectionMonitor.GetConnectionCount(count, status);
    User::WaitForRequest(status);
    if (status.Int() != KErrNone) {
        return 0;
    }
    
    TUint transferredData = 0;
    TUint numSubConnections;
    TUint connectionId;
    bool configFound;
    for (TUint i = 1; i <= count; i++) {
        TInt ret = iConnectionMonitor.GetConnectionInfo(i, connectionId, numSubConnections);
        if (ret == KErrNone) {
            TUint apId;
            iConnectionMonitor.GetUintAttribute(connectionId, 0, KIAPId, apId, status);
            User::WaitForRequest(status);
            if (status.Int() == KErrNone) {
                configFound = false;
                if (config.type() == QNetworkConfiguration::ServiceNetwork) {
                    QList<QNetworkConfiguration> configs = config.children();
                    for (int i=0; i < configs.count(); i++) {
                        SymbianNetworkConfigurationPrivate *symbianConfig =
                            toSymbianConfig(privateConfiguration(configs[i]));

                        if (symbianConfig->numericIdentifier() == apId) {
                            configFound = true;
                            break;
                        }
                    }
                } else {
                    SymbianNetworkConfigurationPrivate *symbianConfig =
                        toSymbianConfig(privateConfiguration(config));

                    if (symbianConfig->numericIdentifier() == apId)
                        configFound = true;
                }
                if (configFound) {
                    TUint tData;
                    iConnectionMonitor.GetUintAttribute(connectionId, 0, dataType, tData, status );
                    User::WaitForRequest(status);
                    if (status.Int() == KErrNone) {
                    transferredData += tData;
                    }
                }
            }
        }
    }
    
    return transferredData;
}

quint64 QNetworkSessionPrivateImpl::activeTime() const
{
    if (!isOpen || startTime.isNull()) {
        return 0;
    }
    return startTime.secsTo(QDateTime::currentDateTime());
}

bool QNetworkSessionPrivateImpl::activeIapId(TUint32& iapId) const
{
    if (!iConnection.SubSessionHandle())
        return false;
    _LIT(KSetting, "IAP\\Id");
    TInt err = iConnection.GetIntSetting(KSetting, iapId);
    if (err != KErrNone)
        return false;
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    // Check if this is an Easy WLAN configuration. On Symbian^3 RConnection may report
    // the used configuration as 'EasyWLAN' IAP ID if someone has just opened the configuration
    // from WLAN Scan dialog, _and_ that connection is still up. We need to find the
    // real matching configuration. Function alters the Easy WLAN ID to real IAP ID (only if
    // easy WLAN):
    easyWlanTrueIapId(iapId);
#endif
    return true;
}

QNetworkConfiguration QNetworkSessionPrivateImpl::activeConfiguration(TUint32 iapId) const
{
    if (iapId == 0) {
        bool ok = activeIapId(iapId);
        if (!ok)
            return QNetworkConfiguration();
    }

#ifdef SNAP_FUNCTIONALITY_AVAILABLE
    if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) {
        // Try to search IAP from the used SNAP using IAP Id
        QList<QNetworkConfiguration> children = publicConfig.children();
        for (int i=0; i < children.count(); i++) {
            SymbianNetworkConfigurationPrivate *childConfig =
                toSymbianConfig(privateConfiguration(children[i]));

            if (childConfig->numericIdentifier() == iapId)
                return children[i];
        }

        // Given IAP Id was not found from the used SNAP
        // => Try to search matching IAP using mappingName
        //    mappingName contains:
        //      1. "Access point name" for "Packet data" Bearer
        //      2. "WLAN network name" (= SSID) for "Wireless LAN" Bearer
        //      3. "Dial-up number" for "Data call Bearer" or "High Speed (GSM)" Bearer
        //    <=> Note: It's possible that in this case reported IAP is
        //              clone of the one of the IAPs of the used SNAP
        //              => If mappingName matches, clone has been found
        QNetworkConfiguration pt = QNetworkConfigurationManager().configurationFromIdentifier(
                QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId)));

        SymbianNetworkConfigurationPrivate *symbianConfig =
            toSymbianConfig(privateConfiguration(pt));
        if (symbianConfig) {
            for (int i=0; i < children.count(); i++) {
                SymbianNetworkConfigurationPrivate *childConfig =
                    toSymbianConfig(privateConfiguration(children[i]));

                if (childConfig->configMappingName() == symbianConfig->configMappingName()) {
                    return children[i];
                }
            }
        } else {
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
            // On Symbian^3 (only, not earlier or Symbian^4) if the SNAP was not reachable, it
            // triggers user choice type of activity (EasyWLAN). As a result, a new IAP may be
            // created, and hence if was not found yet. Therefore update configurations and see if
            // there is something new.

            // 1. Update knowledge from the databases.
            if (thread() != engine->thread())
                QMetaObject::invokeMethod(engine, "requestUpdate", Qt::BlockingQueuedConnection);
            else
                engine->requestUpdate();

            // 2. Check if new configuration was created during connection creation
            QList<QString> knownConfigs = engine->accessPointConfigurationIdentifiers();
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
            qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                    << "opened configuration was not known beforehand, looking for new.";
#endif
            if (knownConfigs.count() > iKnownConfigsBeforeConnectionStart.count()) {
                // Configuration count increased => new configuration was created
                // => Search new, created configuration
                QString newIapId;
                for (int i=0; i < iKnownConfigsBeforeConnectionStart.count(); i++) {
                    if (knownConfigs[i] != iKnownConfigsBeforeConnectionStart[i]) {
                        newIapId = knownConfigs[i];
                        break;
                    }
                }
                if (newIapId.isEmpty()) {
                    newIapId = knownConfigs[knownConfigs.count()-1];
                }
                pt = QNetworkConfigurationManager().configurationFromIdentifier(newIapId);
                if (pt.isValid()) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                            << "new configuration was found, name, IAP id: " << pt.name() << pt.identifier();
#endif
                    return pt;
                }
            }
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
            qDebug() << "QNS this : " << QString::number((uint)this) << " - "
                    << "configuration was not found, returning invalid.";
#endif
#endif
            // Given IAP Id was not found from known IAPs array
            return QNetworkConfiguration();
        }
        // Matching IAP was not found from used SNAP
        // => IAP from another SNAP is returned
        //    (Note: Returned IAP matches to given IAP Id)
        return pt;
    }
#endif
    if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
        if (engine) {
            QNetworkConfiguration pt = QNetworkConfigurationManager().configurationFromIdentifier(
                    QT_BEARERMGMT_CONFIGURATION_IAP_PREFIX+QString::number(qHash(iapId)));
            // Try to found User Selected IAP from known IAPs (accessPointConfigurations)
            if (pt.isValid()) {
                return pt;
            } else {
                // Check if new (WLAN) IAP was created in IAP/SNAP dialog
                // 1. Sync internal configurations array to commsdb first
                if (thread() != engine->thread()) {
                    QMetaObject::invokeMethod(engine, "requestUpdate",
                                              Qt::BlockingQueuedConnection);
                } else {
                    engine->requestUpdate();
                }
                // 2. Check if new configuration was created during connection creation
                QStringList knownConfigs = engine->accessPointConfigurationIdentifiers();
                if (knownConfigs.count() > iKnownConfigsBeforeConnectionStart.count()) {
                    // Configuration count increased => new configuration was created
                    // => Search new, created configuration
                    QString newIapId;
                    for (int i=0; i < iKnownConfigsBeforeConnectionStart.count(); i++) {
                        if (knownConfigs[i] != iKnownConfigsBeforeConnectionStart[i]) {
                            newIapId = knownConfigs[i];
                            break;
                        }
                    }
                    if (newIapId.isEmpty()) {
                        newIapId = knownConfigs[knownConfigs.count()-1];
                    }
                    pt = QNetworkConfigurationManager().configurationFromIdentifier(newIapId);
                    if (pt.isValid())
                        return pt;
                }
            }
        }
        return QNetworkConfiguration();
    }

    return publicConfig;
}

void QNetworkSessionPrivateImpl::updateCurrentIap(TUint32 iapId)
{
    if (iCurrentIap == iapId)
        return;

    if (iCurrentIap != 0)
        QSymbianSocketManager::instance().removeActiveConnection(iCurrentIap);

    iCurrentIap = iapId;

    if (iCurrentIap != 0)
        QSymbianSocketManager::instance().addActiveConnection(iCurrentIap);
}

void QNetworkSessionPrivateImpl::ConnectionStartComplete(TInt statusCode)
{
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
            << "RConnection::Start completed with status code: " << statusCode;
#endif
    // ConnectionStarter *ipConnectionStarter will delete itself at the end of RunL
    ipConnectionStarter = 0;

    switch (statusCode) {
        case KErrNone: // Connection created successfully
            {
            TInt error = KErrNone;
            TUint32 iapId;
            QNetworkConfiguration newActiveConfig;
            if (activeIapId(iapId))
                newActiveConfig = activeConfiguration(iapId);
            if (!newActiveConfig.isValid()) {
                // RConnection startup was successful but no configuration
                // was found. That indicates that user has chosen to create a
                // new WLAN configuration (from scan results), but that new
                // configuration does not have access to Internet (Internet
                // Connectivity Test, ICT, failed).
                error = KErrGeneral;
            } else {
                QSymbianSocketManager::instance().setDefaultConnection(&iConnection);
                updateCurrentIap(iapId);
            }
            if (error != KErrNone) {
                isOpen = false;
                isOpening = false;
                iError = QNetworkSession::UnknownSessionError;
                closeHandles();
                QT_TRYCATCH_LEAVING(emit QNetworkSessionPrivate::error(iError));
                if (!newActiveConfig.isValid()) {
                    // No valid configuration, bail out.
                    // Status updates from QNCM won't be received correctly
                    // because there is no configuration to associate them with so transit here.
                    newState(QNetworkSession::Closing);
                    newState(QNetworkSession::Disconnected);
                }
                QT_TRYCATCH_LEAVING(syncStateWithInterface());
                return;
            }
 
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
            if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) {
                // Activate ALR monitoring
                iMobility = CActiveCommsMobilityApiExt::NewL(iConnection, *this);
            }
#endif

            isOpen = true;
            isOpening = false;
            activeConfig = newActiveConfig;

            SymbianNetworkConfigurationPrivate *symbianConfig =
                toSymbianConfig(privateConfiguration(activeConfig));

#ifndef QT_NO_NETWORKINTERFACE
            activeInterface = interface(symbianConfig->numericIdentifier());
#endif
            if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
                serviceConfig = QNetworkConfigurationManager()
                    .configurationFromIdentifier(activeConfig.identifier());
            }

            startTime = QDateTime::currentDateTime();

            QT_TRYCATCH_LEAVING({
                    newState(QNetworkSession::Connected);
                    emit quitPendingWaitsForOpened();
                });
            }
            break;
        case KErrNotFound: // Connection failed
            isOpen = false;
            isOpening = false;
            activeConfig = QNetworkConfiguration();
            serviceConfig = QNetworkConfiguration();
            iError = QNetworkSession::InvalidConfigurationError;
            closeHandles();
            QT_TRYCATCH_LEAVING(emit QNetworkSessionPrivate::error(iError));
            QT_TRYCATCH_LEAVING(syncStateWithInterface());
            break;
        case KErrCancel: // Connection attempt cancelled
        case KErrAlreadyExists: // Connection already exists
        default:
            isOpen = false;
            isOpening = false;
            activeConfig = QNetworkConfiguration();
            serviceConfig = QNetworkConfiguration();
            if (statusCode == KErrCancel) {
                iError = QNetworkSession::SessionAbortedError;
            } else if (publicConfig.state() == QNetworkConfiguration::Undefined ||
                publicConfig.state() == QNetworkConfiguration::Defined) {
                iError = QNetworkSession::InvalidConfigurationError;
            } else {
                iError = QNetworkSession::UnknownSessionError;
            }
            closeHandles();
            QT_TRYCATCH_LEAVING(emit QNetworkSessionPrivate::error(iError));
            QT_TRYCATCH_LEAVING(syncStateWithInterface());
            break;
    }
}

// Enters newState if feasible according to current state.
// AccessPointId may be given as parameter. If it is zero, state-change is assumed to
// concern this session's configuration. If non-zero, the configuration is looked up
// and checked if it matches the configuration this session is based on.
bool QNetworkSessionPrivateImpl::newState(QNetworkSession::State newState, TUint accessPointId)
{
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - "
             << "NEW STATE, IAP ID : " << QString::number(accessPointId) << " , newState : " << QString::number(newState);
#endif
    // Make sure that activeConfig is always updated when SNAP is signaled to be
    // connected.
    if (isOpen && publicConfig.type() == QNetworkConfiguration::ServiceNetwork &&
        newState == QNetworkSession::Connected) {
        activeConfig = activeConfiguration(accessPointId);

#ifndef QT_NO_NETWORKINTERFACE
        SymbianNetworkConfigurationPrivate *symbianConfig =
            toSymbianConfig(privateConfiguration(activeConfig));

        activeInterface = interface(symbianConfig->numericIdentifier());
#endif

#ifdef SNAP_FUNCTIONALITY_AVAILABLE
        QSymbianSocketManager::instance().setDefaultConnection(&iConnection);
#endif
    }

    // Make sure that same state is not signaled twice in a row.
    if (state == newState) {
        return true;
    }

    // Make sure that Connecting state does not overwrite Roaming state
    if (state == QNetworkSession::Roaming && newState == QNetworkSession::Connecting) {
        return false;
    }
    
    // Make sure that Connected state is not reported when Connection is
    // already Closing.
    // Note: Stopping connection results sometimes KLinkLayerOpen
    //       to be reported first (just before KLinkLayerClosed).
    if (state == QNetworkSession::Closing && newState == QNetworkSession::Connected) {
        return false;
    }

    // Make sure that some lagging 'closing' state-changes do not overwrite
    // if we are already disconnected or closed.
    if (state == QNetworkSession::Disconnected && newState == QNetworkSession::Closing) {
        return false;
    }

    // Make sure that some lagging 'connecting' state-changes do not overwrite
    // if we are already connected (may righfully still happen with roaming though).
    if (state == QNetworkSession::Connected && newState == QNetworkSession::Connecting) {
        return false;
    }

    bool emitSessionClosed = false;

    // If we abruptly go down and user hasn't closed the session, we've been aborted.
    // Note that session may be in 'closing' state and not in 'connected' state, because
    // depending on platform the platform may report KConfigDaemonStartingDeregistration
    // event before KLinkLayerClosed
    if ((isOpen && state == QNetworkSession::Connected && newState == QNetworkSession::Disconnected) ||
        (isOpen && !iClosedByUser && newState == QNetworkSession::Disconnected)) {
        // Active & Connected state should change directly to Disconnected state
        // only when something forces connection to close (eg. when another
        // application or session stops connection or when network drops
        // unexpectedly).
        isOpen = false;
        isOpening = false;
        activeConfig = QNetworkConfiguration();
        serviceConfig = QNetworkConfiguration();
        iError = QNetworkSession::SessionAbortedError;
        closeHandles();
        emit QNetworkSessionPrivate::error(iError);
        // Start handling IAP state change signals from QNetworkConfigurationManagerPrivate
        iHandleStateNotificationsFromManager = true;
        emitSessionClosed = true; // Emit SessionClosed after state change has been reported
    }

    bool retVal = false;
    if (accessPointId == 0) {
        state = newState;
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
        qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed A to: " << state;
#endif
        emit stateChanged(state);
        retVal = true;
    } else {
        if (publicConfig.type() == QNetworkConfiguration::InternetAccessPoint) {
            SymbianNetworkConfigurationPrivate *symbianConfig =
                toSymbianConfig(privateConfiguration(publicConfig));

            if (symbianConfig->numericIdentifier() == accessPointId) {
                state = newState;
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed B to: " << state;
#endif
                emit stateChanged(state);
                retVal = true;
            }
        } else if (publicConfig.type() == QNetworkConfiguration::UserChoice && isOpen) {
            SymbianNetworkConfigurationPrivate *symbianConfig =
                toSymbianConfig(privateConfiguration(activeConfig));

            if (symbianConfig->numericIdentifier() == accessPointId) {
                state = newState;
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed C to: " << state;
#endif
                emit stateChanged(state);
                retVal = true;
            }
        } else if (publicConfig.type() == QNetworkConfiguration::ServiceNetwork) {
            QList<QNetworkConfiguration> subConfigurations = publicConfig.children();
            for (int i = 0; i < subConfigurations.count(); i++) {
                SymbianNetworkConfigurationPrivate *symbianConfig =
                    toSymbianConfig(privateConfiguration(subConfigurations[i]));

                if (symbianConfig->numericIdentifier() == accessPointId) {
                    if (newState != QNetworkSession::Disconnected) {
                        state = newState;
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                        qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed D  to: " << state;
#endif
                        emit stateChanged(state);
                        retVal = true;
                    } else {
                        QNetworkConfiguration config = bestConfigFromSNAP(publicConfig);
                        if ((config.state() == QNetworkConfiguration::Defined) ||
                            (config.state() == QNetworkConfiguration::Discovered)) {
                            activeConfig = QNetworkConfiguration();
                            state = newState;
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                            qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed E  to: " << state;
#endif
                            emit stateChanged(state);
                            retVal = true;
                        } else if (config.state() == QNetworkConfiguration::Active) {
                            // Connection to used IAP was closed, but there is another
                            // IAP that's active in used SNAP
                            // => Change state back to Connected
                            state =  QNetworkSession::Connected;
                            emit stateChanged(state);
                            retVal = true;
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                            qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed F  to: " << state;
#endif
                        }
                    }
                }
            }
#ifdef SNAP_FUNCTIONALITY_AVAILABLE
            // If the retVal is not true here, it means that the status update may apply to an IAP outside of
            // SNAP (session is based on SNAP but follows IAP outside of it), which may occur on Symbian^3 EasyWlan.
            if (retVal == false && activeConfig.isValid() &&
                toSymbianConfig(privateConfiguration(activeConfig))->numericIdentifier() == accessPointId) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "===> EMIT State changed G  to: " << state;
#endif
                if (newState == QNetworkSession::Disconnected) {
                    activeConfig = QNetworkConfiguration();
                }
                state = newState;
                emit stateChanged(state);
                retVal = true;
            }
#endif
        }
    }
    if (emitSessionClosed) {
        emit closed();
    }
    if (state == QNetworkSession::Disconnected) {
        // Just in case clear activeConfiguration.
        activeConfig = QNetworkConfiguration();
    }
    return retVal;
}

void QNetworkSessionPrivateImpl::handleSymbianConnectionStatusChange(TInt aConnectionStatus,
                                                                 TInt aError,
                                                                 TUint accessPointId)
{
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
    qDebug() << "QNS this : " << QString::number((uint)this) << " - " << QString::number(accessPointId) << " , status : " << QString::number(aConnectionStatus);
#endif
    switch (aConnectionStatus)
        {
        // Connection unitialised
        case KConnectionUninitialised:
            break;

        // Starting connetion selection
        case KStartingSelection:
            break;

        // Selection finished
        case KFinishedSelection:
            if (aError == KErrNone)
                {
                break;
                }
            else
                {
                // The user pressed e.g. "Cancel" and did not select an IAP
                newState(QNetworkSession::Disconnected,accessPointId);
                }
            break;

        // Connection failure
        case KConnectionFailure:
            newState(QNetworkSession::NotAvailable);
            break;

        // Prepearing connection (e.g. dialing)
        case KPsdStartingConfiguration:
        case KPsdFinishedConfiguration:
        case KCsdFinishedDialling:
        case KCsdScanningScript:
        case KCsdGettingLoginInfo:
        case KCsdGotLoginInfo:
            break;

        case KConfigDaemonStartingRegistration:
        // Creating connection (e.g. GPRS activation)
        case KCsdStartingConnect:
        case KCsdFinishedConnect:
            newState(QNetworkSession::Connecting,accessPointId);
            break;

        // Starting log in
        case KCsdStartingLogIn:
            break;

        // Finished login
        case KCsdFinishedLogIn:
            break;

        // Connection open
        case KConnectionOpen:
            break;

        case KLinkLayerOpen:
            newState(QNetworkSession::Connected,accessPointId);
            break;

        // Connection blocked or suspended
        case KDataTransferTemporarilyBlocked:
            break;

        case KConfigDaemonStartingDeregistration:
        // Hangup or GRPS deactivation
        case KConnectionStartingClose:
            newState(QNetworkSession::Closing,accessPointId);
            break;

        // Connection stopped
        case KConfigDaemonFinishedDeregistrationStop: //this comes if this is the last session, instead of KLinkLayerClosed
        case KConfigDaemonFinishedDeregistrationPreserve:
        // Connection closed
        case KConnectionClosed:
        case KLinkLayerClosed:
            newState(QNetworkSession::Disconnected,accessPointId);
            // Report manager about this to make sure this event
            // is received by all interseted parties (mediated by
            // manager because it does always receive all events from
            // connection monitor).
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
            qDebug() << "QNS this : " << QString::number((uint)this) << " - " << "reporting disconnection to manager.";
#endif
            if (publicConfig.isValid()) {
                SymbianNetworkConfigurationPrivate *symbianConfig =
                    toSymbianConfig(privateConfiguration(publicConfig));

                engine->configurationStateChangeReport(symbianConfig->numericIdentifier(),
                                                       QNetworkSession::Disconnected);
            }
            break;
        // Unhandled state
        default:
            break;
        }
}

#if defined(SNAP_FUNCTIONALITY_AVAILABLE)
bool QNetworkSessionPrivateImpl::easyWlanTrueIapId(TUint32 &trueIapId) const
{
    RCmManager iCmManager;
    TRAPD(err, iCmManager.OpenL());
    if (err != KErrNone)
        return false;

    // Check if this is easy wlan id in the first place
    if (trueIapId != iCmManager.EasyWlanIdL()) {
        iCmManager.Close();
        return false;
    }

    iCmManager.Close();

    // Loop through all connections that connection monitor is aware
    // and check for IAPs based on easy WLAN
    if (!iConnectionMonitor.Handle())
        return false;
    TRequestStatus status;
    TUint connectionCount;
    iConnectionMonitor.GetConnectionCount(connectionCount, status);
    User::WaitForRequest(status);
    TUint connectionId;
    TUint subConnectionCount;
    TUint apId;
    if (status.Int() == KErrNone) {
        for (TUint i = 1; i <= connectionCount; i++) {
            iConnectionMonitor.GetConnectionInfo(i, connectionId, subConnectionCount);
            iConnectionMonitor.GetUintAttribute(connectionId, subConnectionCount,
                                                KIAPId, apId, status);
            User::WaitForRequest(status);
            if (apId == trueIapId) {
                TBuf<50>easyWlanNetworkName;
                iConnectionMonitor.GetStringAttribute(connectionId, 0, KNetworkName,
                                                      easyWlanNetworkName, status);
                User::WaitForRequest(status);
                if (status.Int() != KErrNone)
                    continue;

                const QString ssid = QString::fromUtf16(easyWlanNetworkName.Ptr(),
                                                            easyWlanNetworkName.Length());

                QNetworkConfigurationPrivatePointer ptr = engine->configurationFromSsid(ssid);
                if (ptr) {
#ifdef QT_BEARERMGMT_SYMBIAN_DEBUG
                    qDebug() << "QNCM easyWlanTrueIapId(), found true IAP ID: "
                             << toSymbianConfig(ptr)->numericIdentifier();
#endif
                    trueIapId = toSymbianConfig(ptr)->numericIdentifier();
                    return true;
                }
            }
        }
    }
    return false;
}
#endif

RConnection* QNetworkSessionPrivateImpl::nativeSession()
{
    return &iConnection;
}

ConnectionProgressNotifier::ConnectionProgressNotifier(QNetworkSessionPrivateImpl& owner, RConnection& connection)
    : CActive(CActive::EPriorityUserInput), iOwner(owner), iConnection(connection)
{
    CActiveScheduler::Add(this);
}

ConnectionProgressNotifier::~ConnectionProgressNotifier()
{
    Cancel();
}

void ConnectionProgressNotifier::StartNotifications()
{
    if (!IsActive()) {
        SetActive();
        iConnection.ProgressNotification(iProgress, iStatus);
    }
}

void ConnectionProgressNotifier::StopNotifications()
{
    Cancel();
}

void ConnectionProgressNotifier::DoCancel()
{
    iConnection.CancelProgressNotification();
}

void ConnectionProgressNotifier::RunL()
{
    if (iStatus == KErrNone) {
        SetActive();
        iConnection.ProgressNotification(iProgress, iStatus);
        // warning, this object may be deleted in the callback - do nothing after handleSymbianConnectionStatusChange
        QT_TRYCATCH_LEAVING(iOwner.handleSymbianConnectionStatusChange(iProgress().iStage, iProgress().iError));
    }
}

ConnectionStarter::ConnectionStarter(QNetworkSessionPrivateImpl &owner, RConnection &connection)
    : CActive(CActive::EPriorityUserInput), iOwner(owner), iConnection(connection)
{
    CActiveScheduler::Add(this);
}

ConnectionStarter::~ConnectionStarter()
{
    Cancel();
}

void ConnectionStarter::Start()
{
    if (!IsActive()) {
        iConnection.Start(iStatus);
        SetActive();
    }
}

void ConnectionStarter::Start(TConnPref &pref)
{
    if (!IsActive()) {
        iConnection.Start(pref, iStatus);
        SetActive();
    }
}

void ConnectionStarter::RunL()
{
    iOwner.ConnectionStartComplete(iStatus.Int());
    delete this;
}

TInt ConnectionStarter::RunError(TInt err)
{
    qWarning() << "ConnectionStarter::RunError" << err;
    // there must have been a leave from iOwner.ConnectionStartComplete, in which case "delete this" in RunL was missed.
    delete this;
    return KErrNone;
}

void ConnectionStarter::DoCancel()
{
    iConnection.Close();
}

QT_END_NAMESPACE

#endif //QT_NO_BEARERMANAGEMENT