summaryrefslogtreecommitdiffstats
path: root/src/network/socket/qsymbiansocketengine.cpp
blob: 688f7248acbd6d1002b2039cc839ceaa21b2bf79 (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
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

//#define QNATIVESOCKETENGINE_DEBUG
#include "qsymbiansocketengine_p.h"

#include "qiodevice.h"
#include "qhostaddress.h"
#include "qelapsedtimer.h"
#include "qvarlengtharray.h"
#include "qnetworkinterface.h"
#include <private/qnetworksession_p.h>
#include <es_sock.h>
#include <in_sock.h>
#include <net/if.h>

#include <private/qcore_symbian_p.h>

#if !defined(QT_NO_NETWORKPROXY)
# include "qnetworkproxy.h"
# include "qabstractsocket.h"
# include "qtcpserver.h"
#endif

#include <QCoreApplication>

#include <qabstracteventdispatcher.h>
#include <qsocketnotifier.h>
#include <qnetworkinterface.h>

#include <private/qthread_p.h>
#include <private/qobject_p.h>
#include <private/qsystemerror_p.h>

#if defined QNATIVESOCKETENGINE_DEBUG
#include <qstring.h>
#include <ctype.h>
#endif

QT_BEGIN_NAMESPACE

#define Q_VOID
// Common constructs
#define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \
    if (!isValid()) { \
        qWarning(""#function" was called on an uninitialized socket device"); \
        return returnValue; \
    } } while (0)
#define Q_CHECK_INVALID_SOCKETLAYER(function, returnValue) do { \
    if (isValid()) { \
        qWarning(""#function" was called on an already initialized socket device"); \
        return returnValue; \
    } } while (0)
#define Q_CHECK_STATE(function, checkState, returnValue) do { \
    if (d->socketState != (checkState)) { \
        qWarning(""#function" was not called in "#checkState); \
        return (returnValue); \
    } } while (0)
#define Q_CHECK_NOT_STATE(function, checkState, returnValue) do { \
    if (d->socketState == (checkState)) { \
        qWarning(""#function" was called in "#checkState); \
        return (returnValue); \
    } } while (0)
#define Q_CHECK_STATES(function, state1, state2, returnValue) do { \
    if (d->socketState != (state1) && d->socketState != (state2)) { \
        qWarning(""#function" was called" \
                 " not in "#state1" or "#state2); \
        return (returnValue); \
    } } while (0)
#define Q_CHECK_TYPE(function, type, returnValue) do { \
    if (d->socketType != (type)) { \
        qWarning(#function" was called by a" \
                 " socket other than "#type""); \
        return (returnValue); \
    } } while (0)

#if defined QNATIVESOCKETENGINE_DEBUG

/*
    Returns a human readable representation of the first \a len
    characters in \a data.
*/
static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
{
    if (!data) return "(null)";
    QByteArray out;
    for (int i = 0; i < len; ++i) {
        char c = data[i];
        if (isprint(c)) {
            out += c;
        } else switch (c) {
        case '\n': out += "\\n"; break;
        case '\r': out += "\\r"; break;
        case '\t': out += "\\t"; break;
        default:
            QString tmp;
            tmp.sprintf("\\%o", c);
            out += tmp.toLatin1();
        }
    }

    if (len < maxSize)
        out += "...";

    return out;
}
#endif

void QSymbianSocketEnginePrivate::getPortAndAddress(const TInetAddr& a, quint16 *port, QHostAddress *addr)
{
    if (a.Family() == KAfInet6) {
        Q_IPV6ADDR tmp;
        memcpy(&tmp, a.Ip6Address().u.iAddr8, sizeof(tmp));
        if (addr) {
            QHostAddress tmpAddress;
            tmpAddress.setAddress(tmp);
            *addr = tmpAddress;
            TPckgBuf<TSoInetIfQuery> query;
            query().iSrcAddr = a;
            TInt err = nativeSocket.GetOpt(KSoInetIfQueryBySrcAddr, KSolInetIfQuery, query);
            if (!err)
                addr->setScopeId(qt_TDesC2QString(query().iName));
            else
            addr->setScopeId(QString::number(a.Scope()));
        }
        if (port)
            *port = a.Port();
        return;
    }
    if (port)
        *port = a.Port();
    if (addr) {
        QHostAddress tmpAddress;
        tmpAddress.setAddress(a.Address());
        *addr = tmpAddress;
    }
}
/*! \internal

    Creates and returns a new socket descriptor of type \a socketType
    and \a socketProtocol.  Returns -1 on failure.
*/
bool QSymbianSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType,
                                         QAbstractSocket::NetworkLayerProtocol socketProtocol)
{
    Q_Q(QSymbianSocketEngine);
    TUint family = KAfInet; // KAfInet6 is only used as an address family, not as a protocol family
    TUint type = (socketType == QAbstractSocket::UdpSocket) ? KSockDatagram : KSockStream;
    TUint protocol = (socketType == QAbstractSocket::UdpSocket) ? KProtocolInetUdp : KProtocolInetTcp;

    //Check if there is a user specified session
    RConnection *connection = 0;
    QVariant v(q->property("_q_networksession"));
    TInt err;
    if (v.isValid()) {
        QSharedPointer<QNetworkSession> s = qvariant_cast<QSharedPointer<QNetworkSession> >(v);
        err = QNetworkSessionPrivate::nativeOpenSocket(*s, nativeSocket, family, type, protocol);
#ifdef QNATIVESOCKETENGINE_DEBUG
        qDebug() << "QSymbianSocketEnginePrivate::createNewSocket - _q_networksession was set" << err;
#endif
    } else
        err = nativeSocket.Open(socketServer, family, type, protocol); //TODO: FIXME - deprecated API, make sure we always have a connection instead

    if (err != KErrNone) {
        switch (err) {
        case KErrNotSupported:
        case KErrNotFound:
            setError(QAbstractSocket::UnsupportedSocketOperationError,
                ProtocolUnsupportedErrorString);
            break;
        default:
            setError(err);
            break;
        }

        return false;
    }
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEnginePrivate::createNewSocket - created" << nativeSocket.SubSessionHandle();
#endif
    socketDescriptor = QSymbianSocketManager::instance().addSocket(nativeSocket);
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << " - allocated socket descriptor" << socketDescriptor;
#endif
    return true;
}

void QSymbianSocketEnginePrivate::setPortAndAddress(TInetAddr& nativeAddr, quint16 port, const QHostAddress &addr)
{
    nativeAddr.SetPort(port);
    if (addr == QHostAddress::Any) {
        //Should allow both IPv4 and IPv6
        //Listening on "0.0.0.0" accepts ONLY ipv4 connections
        //Listening on "::" accepts ONLY ipv6 connections
        nativeAddr.SetFamily(KAFUnspec);
    } else if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
        TPckgBuf<TSoInetIfQuery> query;
        query().iName = qt_QString2TPtrC(addr.scopeId());
        TInt err = nativeSocket.GetOpt(KSoInetIfQueryByName, KSolInetIfQuery, query);
        if (!err)
            nativeAddr.SetScope(query().iIndex);
        else
            nativeAddr.SetScope(0);
        Q_IPV6ADDR ip6 = addr.toIPv6Address();
        TIp6Addr v6addr;
        memcpy(v6addr.u.iAddr8, ip6.c, 16);
        nativeAddr.SetAddress(v6addr);
    } else if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
        nativeAddr.SetAddress(addr.toIPv4Address());
    } else {
        qWarning("unsupported network protocol (%d)", addr.protocol());
    }
}

QSymbianSocketEnginePrivate::QSymbianSocketEnginePrivate() :
    socketDescriptor(-1),
    socketServer(QSymbianSocketManager::instance().getSocketServer()),
    readNotificationsEnabled(false),
    writeNotificationsEnabled(false),
    exceptNotificationsEnabled(false),
    asyncSelect(0)
{
}

QSymbianSocketEnginePrivate::~QSymbianSocketEnginePrivate()
{
}


QSymbianSocketEngine::QSymbianSocketEngine(QObject *parent)
    : QAbstractSocketEngine(*new QSymbianSocketEnginePrivate(), parent)
{
}


QSymbianSocketEngine::~QSymbianSocketEngine()
{
    close();
    // FIXME what else do we need to free?
}

/*!
    Initializes a QSymbianSocketEngine by creating a new socket of type \a
    socketType and network layer protocol \a protocol. Returns true on
    success; otherwise returns false.

    If the socket was already initialized, this function closes the
    socket before reeinitializing it.

    The new socket is non-blocking, and for UDP sockets it's also
    broadcast enabled.
*/
bool QSymbianSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol protocol)
{
    Q_D(QSymbianSocketEngine);
    if (isValid())
        close();

    // Create the socket
    if (!d->createNewSocket(socketType, protocol)) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
        QString typeStr = QLatin1String("UnknownSocketType");
        if (socketType == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
        else if (socketType == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
        QString protocolStr = QLatin1String("UnknownProtocol");
        if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
        else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
        qDebug("QSymbianSocketEngine::initialize(type == %s, protocol == %s) failed: %s",
               typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(), d->socketErrorString.toLatin1().constData());
#endif
        return false;
    }

    // Make the socket nonblocking.
    if (!setOption(NonBlockingSocketOption, 1)) {
        d->setError(QAbstractSocket::UnsupportedSocketOperationError,
                    d->NonBlockingInitFailedErrorString);
        close();
        return false;
    }

    // Set the broadcasting flag if it's a UDP socket.
    if (socketType == QAbstractSocket::UdpSocket
        && !setOption(BroadcastSocketOption, 1)) {
        d->setError(QAbstractSocket::UnsupportedSocketOperationError,
                    d->BroadcastingInitFailedErrorString);
        close();
        return false;
    }


    // Make sure we receive out-of-band data
    if (socketType == QAbstractSocket::TcpSocket
        && !setOption(ReceiveOutOfBandData, 1)) {
        qWarning("QSymbianSocketEngine::initialize unable to inline out-of-band data");
    }


    d->socketType = socketType;
    d->socketProtocol = protocol;
    return true;
}

/*! \overload

    Initializes the socket using \a socketDescriptor instead of
    creating a new one. The socket type and network layer protocol are
    determined automatically. The socket's state is set to \a
    socketState.

    If the socket type is either TCP or UDP, it is made non-blocking.
    UDP sockets are also broadcast enabled.
 */
bool QSymbianSocketEngine::initialize(int socketDescriptor, QAbstractSocket::SocketState socketState)
{
    Q_D(QSymbianSocketEngine);

    if (isValid())
        close();

    if (!QSymbianSocketManager::instance().lookupSocket(socketDescriptor, d->nativeSocket)) {
        qWarning("QSymbianSocketEngine::initialize - socket descriptor not found");
        d->setError(QAbstractSocket::UnsupportedSocketOperationError,
            QSymbianSocketEnginePrivate::InvalidSocketErrorString);
        return false;
    }
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEngine::initialize - attached to" << d->nativeSocket.SubSessionHandle() << socketDescriptor;
#endif
    Q_ASSERT(d->socketDescriptor == socketDescriptor || d->socketDescriptor == -1);
    d->socketDescriptor = socketDescriptor;

    // determine socket type and protocol
    if (!d->fetchConnectionParameters()) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
        qDebug("QSymbianSocketEngine::initialize(socketDescriptor == %i) failed: %s",
               socketDescriptor, d->socketErrorString.toLatin1().constData());
#endif
        d->socketDescriptor = -1;
        return false;
    }

    if (d->socketType != QAbstractSocket::UnknownSocketType) {
        // Make the socket nonblocking.
        if (!setOption(NonBlockingSocketOption, 1)) {
            d->setError(QAbstractSocket::UnsupportedSocketOperationError,
                d->NonBlockingInitFailedErrorString);
            close();
            return false;
        }

        // Set the broadcasting flag if it's a UDP socket.
        if (d->socketType == QAbstractSocket::UdpSocket
            && !setOption(BroadcastSocketOption, 1)) {
            d->setError(QAbstractSocket::UnsupportedSocketOperationError,
                d->BroadcastingInitFailedErrorString);
            close();
            return false;
        }

        // Make sure we receive out-of-band data
        if (d->socketType == QAbstractSocket::TcpSocket
            && !setOption(ReceiveOutOfBandData, 1)) {
            qWarning("QSymbianSocketEngine::initialize unable to inline out-of-band data");
        }
    }

    d->socketState = socketState;
    return true;
}

/*!
    Returns true if the socket is valid; otherwise returns false. A
    socket is valid if it has not been successfully initialized, or if
    it has been closed.
*/
bool QSymbianSocketEngine::isValid() const
{
    Q_D(const QSymbianSocketEngine);
    return d->socketDescriptor != -1;
}


/*!
    Returns the native socket descriptor. Any use of this descriptor
    stands the risk of being non-portable.
*/
int QSymbianSocketEngine::socketDescriptor() const
{
    Q_D(const QSymbianSocketEngine);
    return d->socketDescriptor;
}

/*
    Sets the socket option \a opt to \a v.
*/
bool QSymbianSocketEngine::setOption(QAbstractSocketEngine::SocketOption opt, int v)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setOption(), false);

    TUint n = 0;
    TUint level = KSOLSocket; // default

    if (!QSymbianSocketEnginePrivate::translateSocketOption(opt, n, level))
        return false;

    if (!level && !n)
        return true;

    return (KErrNone == d->nativeSocket.SetOpt(n, level, v));
}

/*
    Returns the value of the socket option \a opt.
*/
int QSymbianSocketEngine::option(QAbstractSocketEngine::SocketOption opt) const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::option(), -1);

    TUint n;
    TUint level = KSOLSocket; // default

    if (!QSymbianSocketEnginePrivate::translateSocketOption(opt, n, level))
        return false;

    if (!level && !n)
        return 1;

    int v = -1;
    //GetOpt() is non const
    TInt err = d->nativeSocket.GetOpt(n, level, v);
    if (!err)
        return v;

    return -1;
}

bool QSymbianSocketEnginePrivate::translateSocketOption(QAbstractSocketEngine::SocketOption opt, TUint &n, TUint &level)
{

    switch (opt) {
    case QAbstractSocketEngine::ReceiveBufferSocketOption:
        n = KSORecvBuf;
        break;
    case QAbstractSocketEngine::SendBufferSocketOption:
        n = KSOSendBuf;
        break;
    case QAbstractSocketEngine::NonBlockingSocketOption:
        n = KSONonBlockingIO;
        break;
    case QAbstractSocketEngine::AddressReusable:
        level = KSolInetIp;
        n = KSoReuseAddr;
        break;
    case QAbstractSocketEngine::BroadcastSocketOption:
    case QAbstractSocketEngine::BindExclusively:
        level = 0;
        n = 0;
        return true;
    case QAbstractSocketEngine::ReceiveOutOfBandData:
        level = KSolInetTcp;
        n = KSoTcpOobInline;
        break;
    case QAbstractSocketEngine::LowDelayOption:
        level = KSolInetTcp;
        n = KSoTcpNoDelay;
        break;
    case QAbstractSocketEngine::KeepAliveOption:
        level = KSolInetTcp;
        n = KSoTcpKeepAlive;
        break;
    case QAbstractSocketEngine::MulticastLoopbackOption:
        level = KSolInetIp;
        n = KSoIp6MulticastLoop;
        break;
    case QAbstractSocketEngine::MulticastTtlOption:
        level = KSolInetIp;
        n = KSoIp6MulticastHops;
        break;
    default:
        return false;
    }
    return true;
}

qint64 QSymbianSocketEngine::receiveBufferSize() const
{
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::receiveBufferSize(), -1);
    return option(ReceiveBufferSocketOption);
}

void QSymbianSocketEngine::setReceiveBufferSize(qint64 size)
{
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setReceiveBufferSize(), Q_VOID);
    setOption(ReceiveBufferSocketOption, size);
}

qint64 QSymbianSocketEngine::sendBufferSize() const
{
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setSendBufferSize(), -1);
    return option(SendBufferSocketOption);
}

void QSymbianSocketEngine::setSendBufferSize(qint64 size)
{
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setSendBufferSize(), Q_VOID);
    setOption(SendBufferSocketOption, size);
}

/*!
    Connects to the remote host name given by \a name on port \a
    port. When this function is called, the upper-level will not
    perform a hostname lookup.

    The native socket engine does not support this operation,
    but some other socket engines (notably proxy-based ones) do.
*/
bool QSymbianSocketEngine::connectToHostByName(const QString &name, quint16 port)
{
    Q_UNUSED(name);
    Q_UNUSED(port);
    Q_D(QSymbianSocketEngine);
    d->setError(QAbstractSocket::UnsupportedSocketOperationError,
        QSymbianSocketEnginePrivate::OperationUnsupportedErrorString);
    return false;
}

/*!
    If there's a connection activity on the socket, process it. Then
    notify our parent if there really was activity.
*/
void QSymbianSocketEngine::connectionNotification()
{
    // FIXME check if we really need to do it like that in Symbian
    Q_D(QSymbianSocketEngine);
    Q_ASSERT(state() == QAbstractSocket::ConnectingState);

    connectToHost(d->peerAddress, d->peerPort);
    if (state() != QAbstractSocket::ConnectingState) {
        // we changed states
        QAbstractSocketEngine::connectionNotification();
    }
}


bool QSymbianSocketEngine::connectToHost(const QHostAddress &addr, quint16 port)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::connectToHost(), false);

#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug("QSymbianSocketEngine::connectToHost() : %d ", d->socketDescriptor);
#endif

    if (!d->checkProxy(addr))
        return false;

    d->peerAddress = addr;
    d->peerPort = port;

    TInetAddr nativeAddr;
    d->setPortAndAddress(nativeAddr, port, addr);
    TRequestStatus status;
    d->nativeSocket.Connect(nativeAddr, status);
    User::WaitForRequest(status);
    TInt err = status.Int();
    //For non blocking connect, KErrAlreadyExists is returned from the second Connect() to indicate
    //the connection is up. So treat this the same as KErrNone which would be returned from the first
    //call if it wouldn't block. (e.g. winsock wrapper in the emulator ignores the nonblocking flag)
    if (err && err != KErrAlreadyExists) {
        switch (err) {
        case KErrWouldBlock:
            d->socketState = QAbstractSocket::ConnectingState;
            break;
        default:
            d->setError(err);
            d->socketState = QAbstractSocket::UnconnectedState;
            break;
        }

        if (d->socketState != QAbstractSocket::ConnectedState) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
            qDebug("QSymbianSocketEngine::connectToHost(%s, %i) == false (%s)",
                   addr.toString().toLatin1().constData(), port,
                   d->socketState == QAbstractSocket::ConnectingState
                   ? "Connection in progress" : d->socketErrorString.toLatin1().constData());
#endif
            return false;
        }
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::Connect(%s, %i) == true",
           addr.toString().toLatin1().constData(), port);
#endif

    d->socketState = QAbstractSocket::ConnectedState;
    d->fetchConnectionParameters();
    return true;
}

bool QSymbianSocketEngine::bind(const QHostAddress &address, quint16 port)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::bind(), false);

    if (!d->checkProxy(address))
        return false;

    Q_CHECK_STATE(QSymbianSocketEngine::bind(), QAbstractSocket::UnconnectedState, false);

    TInetAddr nativeAddr;
    d->setPortAndAddress(nativeAddr, port, address);

    TInt err = d->nativeSocket.Bind(nativeAddr);
#ifdef __WINS__
    if (err == KErrArgument) // winsock prt returns wrong error code
        err = KErrInUse;
#endif

    if (err) {
        switch (err) {
        case KErrNotFound:
            // the specified interface was not found - use the error code expected
            d->setError(QAbstractSocket::SocketAddressNotAvailableError, QSymbianSocketEnginePrivate::AddressNotAvailableErrorString);
            break;
        default:
            d->setError(err);
            break;
        }

#if defined (QNATIVESOCKETENGINE_DEBUG)
        qDebug("QSymbianSocketEngine::bind(%s, %i) == false (%s)",
               address.toString().toLatin1().constData(), port, d->socketErrorString.toLatin1().constData());
#endif

        return false;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::bind(%s, %i) == true",
           address.toString().toLatin1().constData(), port);
#endif
    d->socketState = QAbstractSocket::BoundState;

    d->fetchConnectionParameters();
    return true;
}

bool QSymbianSocketEngine::listen()
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::listen(), false);
    Q_CHECK_STATE(QSymbianSocketEngine::listen(), QAbstractSocket::BoundState, false);
    Q_CHECK_TYPE(QSymbianSocketEngine::listen(), QAbstractSocket::TcpSocket, false);
   // TODO the value 50 is from the QNativeSocketEngine. Maybe it's a bit too much
    // for a mobile platform
    TInt err = d->nativeSocket.Listen(50);
    if (err) {
        d->setError(err);

#if defined (QNATIVESOCKETENGINE_DEBUG)
        qDebug("QSymbianSocketEngine::listen() == false (%s)",
               d->socketErrorString.toLatin1().constData());
#endif
        return false;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::listen() == true");
#endif

    d->socketState = QAbstractSocket::ListeningState;
    return true;
}

int QSymbianSocketEngine::accept()
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::accept(), -1);
    Q_CHECK_STATE(QSymbianSocketEngine::accept(), QAbstractSocket::ListeningState, false);
    Q_CHECK_TYPE(QSymbianSocketEngine::accept(), QAbstractSocket::TcpSocket, false);
    RSocket blankSocket;
    blankSocket.Open(d->socketServer);
    TRequestStatus status;
    d->nativeSocket.Accept(blankSocket, status);
    User::WaitForRequest(status);
    if (status.Int()) {
        blankSocket.Close();
        if (status != KErrWouldBlock)
            qWarning("QSymbianSocketEngine::accept() - error %d", status.Int());
        return -1;
    }

#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEnginePrivate::accept - created" << blankSocket.SubSessionHandle();
#endif
    int fd = QSymbianSocketManager::instance().addSocket(blankSocket);
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << " - allocated socket descriptor" << fd;
#endif
    return fd;
}

qint64 QSymbianSocketEngine::bytesAvailable() const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::bytesAvailable(), -1);
    Q_CHECK_NOT_STATE(QSymbianSocketEngine::bytesAvailable(), QAbstractSocket::UnconnectedState, false);
    int nbytes = 0;
    qint64 available = 0;
    TInt err = d->nativeSocket.GetOpt(KSOReadBytesPending, KSOLSocket, nbytes);
    if (err)
        return 0;
    available = (qint64) nbytes;

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::bytesAvailable() == %lli", available);
#endif
    return available;
}

bool QSymbianSocketEngine::hasPendingDatagrams() const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::hasPendingDatagrams(), false);
    Q_CHECK_NOT_STATE(QSymbianSocketEngine::hasPendingDatagrams(), QAbstractSocket::UnconnectedState, false);
    Q_CHECK_TYPE(QSymbianSocketEngine::hasPendingDatagrams(), QAbstractSocket::UdpSocket, false);
    int nbytes;
    TInt err = d->nativeSocket.GetOpt(KSOReadBytesPending,KSOLSocket, nbytes);
    return err == KErrNone && nbytes > 0;
}

qint64 QSymbianSocketEngine::pendingDatagramSize() const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::pendingDatagramSize(), false);
    Q_CHECK_TYPE(QSymbianSocketEngine::hasPendingDatagrams(), QAbstractSocket::UdpSocket, false);
    int nbytes;
    TInt err = d->nativeSocket.GetOpt(KSOReadBytesPending,KSOLSocket, nbytes);
    if (nbytes > 0) {
        //nbytes includes IP header, which is of variable length (IPv4 with or without options, IPv6...)
        QByteArray next(nbytes,0);
        TPtr8 buffer((TUint8*)next.data(), next.size());
        TInetAddr addr;
        TRequestStatus status;
        //TODO: rather than peek, should we save this for next call to readDatagram?
        //what if calls don't match though?
        d->nativeSocket.RecvFrom(buffer, addr, KSockReadPeek, status);
        User::WaitForRequest(status);
        if (status.Int())
            return 0;
        return buffer.Length();
    }
    return qint64(nbytes);
}


qint64 QSymbianSocketEngine::readDatagram(char *data, qint64 maxSize,
                                                    QHostAddress *address, quint16 *port)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::readDatagram(), -1);
    Q_CHECK_TYPE(QSymbianSocketEngine::readDatagram(), QAbstractSocket::UdpSocket, false);
    TPtr8 buffer((TUint8*)data, (int)maxSize);
    TInetAddr addr;
    TRequestStatus status;
    d->nativeSocket.RecvFrom(buffer, addr, 0, status);
    User::WaitForRequest(status); //Non blocking receive

    if (status.Int()) {
        d->setError(QAbstractSocket::NetworkError, d->ReceiveDatagramErrorString);
    } else if (port || address) {
        d->getPortAndAddress(addr, port, address);
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    int len = buffer.Length();
    qDebug("QSymbianSocketEngine::receiveDatagram(%p \"%s\", %lli, %s, %i) == %lli",
           data, qt_prettyDebug(data, qMin(len, ssize_t(16)), len).data(), maxSize,
           address ? address->toString().toLatin1().constData() : "(nil)",
           port ? *port : 0, (qint64) len);
#endif

    if (status.Int())
        return -1;
    return qint64(buffer.Length());
}


qint64 QSymbianSocketEngine::writeDatagram(const char *data, qint64 len,
                                                   const QHostAddress &host, quint16 port)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::writeDatagram(), -1);
    Q_CHECK_TYPE(QSymbianSocketEngine::writeDatagram(), QAbstractSocket::UdpSocket, -1);
    TPtrC8 buffer((TUint8*)data, (int)len);
    TInetAddr addr;
    d->setPortAndAddress(addr, port, host);
    TSockXfrLength sentBytes;
    TRequestStatus status;
    d->nativeSocket.SendTo(buffer, addr, 0, status, sentBytes);
    User::WaitForRequest(status); //Non blocking send
    TInt err = status.Int(); 

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::writeDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli (err=%d)", data,
           qt_prettyDebug(data, qMin<int>(len, 16), len).data(), len, host.toString().toLatin1().constData(),
           port, (qint64) sentBytes(), err);
#endif

    if (err) {
        switch (err) {
        case KErrWouldBlock:
            // do not error the socket. (otherwise socket layer is reset)
            // On symbian^1 and earlier, KErrWouldBlock is returned when interface is not up yet
            // On symbian^3, KErrNone is returned but sentBytes = 0
            return 0;
        case KErrTooBig:
            d->setError(QAbstractSocket::DatagramTooLargeError, d->DatagramTooLargeErrorString);
            break;
        default:
            d->setError(QAbstractSocket::NetworkError, d->SendDatagramErrorString);
        }
        return -1;
    }

    if (QSysInfo::s60Version() <= QSysInfo::SV_S60_5_0) {
        // This is evil hack, but for some reason native RSocket::SendTo returns 0,
        // for large datagrams (such as 600 bytes). Based on comments from Open C team
        // this should happen only in platforms <= S60 5.0.
        return len;
    }
    return sentBytes();
}

// FIXME check where the native socket engine called that..
bool QSymbianSocketEnginePrivate::fetchConnectionParameters()
{
    localPort = 0;
    localAddress.clear();
    peerPort = 0;
    peerAddress.clear();

    if (socketDescriptor == -1)
        return false;

    if (!nativeSocket.SubSessionHandle()) {
        if (!QSymbianSocketManager::instance().lookupSocket(socketDescriptor, nativeSocket)) {
            setError(QAbstractSocket::UnsupportedSocketOperationError, InvalidSocketErrorString);
            return false;
        }
    }

    // Determine local address
    TSockAddr addr;
    nativeSocket.LocalName(addr);
    getPortAndAddress(addr, &localPort, &localAddress);

    // Determine protocol family
    switch (addr.Family()) {
    case KAfInet:
        socketProtocol = QAbstractSocket::IPv4Protocol;
        break;
    case KAfInet6:
        socketProtocol = QAbstractSocket::IPv6Protocol;
        break;
    default:
        socketProtocol = QAbstractSocket::UnknownNetworkLayerProtocol;
        break;
    }

    // Determine the remote address
    nativeSocket.RemoteName(addr);
    getPortAndAddress(addr, &peerPort, &peerAddress);

    // Determine the socket type (UDP/TCP)
    TProtocolDesc protocol;
    TInt err = nativeSocket.Info(protocol);
    if (err) {
        setError(err);
        return false;
    } else {
        switch (protocol.iProtocol) {
        case KProtocolInetTcp:
            socketType = QAbstractSocket::TcpSocket;
            break;
        case KProtocolInetUdp:
            socketType = QAbstractSocket::UdpSocket;
            break;
        default:
            socketType = QAbstractSocket::UnknownSocketType;
            break;
        }
    }
#if defined (QNATIVESOCKETENGINE_DEBUG)
    QString socketProtocolStr = QLatin1String("UnknownProtocol");
    if (socketProtocol == QAbstractSocket::IPv4Protocol) socketProtocolStr = QLatin1String("IPv4Protocol");
    else if (socketProtocol == QAbstractSocket::IPv6Protocol) socketProtocolStr = QLatin1String("IPv6Protocol");

    QString socketTypeStr = QLatin1String("UnknownSocketType");
    if (socketType == QAbstractSocket::TcpSocket) socketTypeStr = QLatin1String("TcpSocket");
    else if (socketType == QAbstractSocket::UdpSocket) socketTypeStr = QLatin1String("UdpSocket");

    qDebug("QSymbianSocketEnginePrivate::fetchConnectionParameters() local == %s:%i,"
           " peer == %s:%i, socket == %s - %s",
           localAddress.toString().toLatin1().constData(), localPort,
           peerAddress.toString().toLatin1().constData(), peerPort,socketTypeStr.toLatin1().constData(),
           socketProtocolStr.toLatin1().constData());
#endif
    return true;
}

void QSymbianSocketEngine::close()
{
    if (!isValid())
        return;
    Q_D(QSymbianSocketEngine);
#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::close()");
#endif

    d->readNotificationsEnabled = false;
    d->writeNotificationsEnabled = false;
    d->exceptNotificationsEnabled = false;
    if (d->asyncSelect) {
        d->asyncSelect->deleteLater();
        d->asyncSelect = 0;
    }

    //TODO: call nativeSocket.Shutdown(EImmediate) in some cases?
    if (d->socketType == QAbstractSocket::UdpSocket) {
        //TODO: Close hangs without this, but only for UDP - why?
        TRequestStatus stat;
        d->nativeSocket.Shutdown(RSocket::EImmediate, stat);
        User::WaitForRequest(stat);
    }
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEngine::close - closing socket" << d->nativeSocket.SubSessionHandle() << d->socketDescriptor;
#endif
    //remove must come before close to avoid a race where another thread gets the old subsession handle
    //reused & asserts when calling QSymbianSocketManager::instance->addSocket
    QSymbianSocketManager::instance().removeSocket(d->nativeSocket);
    d->nativeSocket.Close();
    d->socketDescriptor = -1;

    d->socketState = QAbstractSocket::UnconnectedState;
    d->hasSetSocketError = false;
    d->localPort = 0;
    d->localAddress.clear();
    d->peerPort = 0;
    d->peerAddress.clear();
}

qint64 QSymbianSocketEngine::write(const char *data, qint64 len)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::write(), -1);
    Q_CHECK_STATE(QSymbianSocketEngine::write(), QAbstractSocket::ConnectedState, -1);
    TPtrC8 buffer((TUint8*)data, (int)len);
    TSockXfrLength sentBytes = 0;
    TRequestStatus status;
    d->nativeSocket.Send(buffer, 0, status, sentBytes);
    User::WaitForRequest(status); //TODO: on emulator this blocks for write >16kB (non blocking IO not implemented properly?)
    TInt err = status.Int(); 

    if (err) {
        switch (err) {
        case KErrDisconnected:
        case KErrEof:
            sentBytes = -1;
            d->setError(QAbstractSocket::RemoteHostClosedError, d->RemoteHostClosedErrorString);
            close();
            break;
        case KErrTooBig:
            d->setError(QAbstractSocket::DatagramTooLargeError, d->DatagramTooLargeErrorString);
            break;
        case KErrWouldBlock:
            break;
        default:
            sentBytes = -1;
            d->setError(err);
            close();
            break;
        }
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::write(%p \"%s\", %llu) == %i",
           data, qt_prettyDebug(data, qMin((int) len, 16),
                                (int) len).data(), len, (int) sentBytes());
#endif

    return qint64(sentBytes());
}
/*
*/
qint64 QSymbianSocketEngine::read(char *data, qint64 maxSize)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::read(), -1);
    Q_CHECK_STATES(QSymbianSocketEngine::read(), QAbstractSocket::ConnectedState, QAbstractSocket::BoundState, -1);

    TPtr8 buffer((TUint8*)data, (int)maxSize);
    TSockXfrLength received = 0;
    TRequestStatus status;
    TSockAddr dummy;
    if (d->socketType == QAbstractSocket::UdpSocket) {
        //RecvOneOrMore() can only be used with stream-interfaced connected sockets; datagram interface sockets will return KErrNotSupported.
        d->nativeSocket.RecvFrom(buffer, dummy, 0, status);
    } else {
        d->nativeSocket.RecvOneOrMore(buffer, 0, status, received);
    }
    User::WaitForRequest(status); //Non blocking receive
    TInt err = status.Int();
    int r = buffer.Length();

    if (err == KErrWouldBlock) {
        // No data was available for reading
        r = -2;
    } else if (err != KErrNone) {
        d->setError(err);
        close();
        r = -1;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QSymbianSocketEngine::read(%p \"%s\", %llu) == %i (err = %d)",
           data, qt_prettyDebug(data, qMin(r, ssize_t(16)), r).data(),
           maxSize, r, err);
#endif

    return qint64(r);
}

int QSymbianSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) const
{
    bool readyRead = false;
    bool readyWrite = false;
    if (selectForRead)
        return nativeSelect(timeout, true, false, &readyRead, &readyWrite);
    else
        return nativeSelect(timeout, false, true, &readyRead, &readyWrite);
}

/*!
 \internal
 \param timeout timeout in milliseconds
 \param checkRead caller is interested if the socket is ready to read
 \param checkWrite caller is interested if the socket is ready for write
 \param selectForRead (out) should set to true if ready to read
 \param selectForWrite (out) should set to true if ready to write
 \return 0 on timeout, >0 on success, <0 on error
 */
int QSymbianSocketEnginePrivate::nativeSelect(int timeout, bool checkRead, bool checkWrite,
                       bool *selectForRead, bool *selectForWrite) const
{
    //cancel asynchronous notifier (only one IOCTL allowed at a time)
    if (asyncSelect)
        asyncSelect->Cancel();

    TPckgBuf<TUint> selectFlags;
    selectFlags() = KSockSelectExcept;
    if (checkRead)
        selectFlags() |= KSockSelectRead;
    if (checkWrite)
        selectFlags() |= KSockSelectWrite;
    TRequestStatus selectStat;
    nativeSocket.Ioctl(KIOctlSelect, selectStat, &selectFlags, KSOLSocket);

    if (timeout < 0)
        User::WaitForRequest(selectStat); //negative means no timeout
    else {
        if (!selectTimer.Handle())
            qt_symbian_throwIfError(selectTimer.CreateLocal());
        TRequestStatus timerStat;
        selectTimer.HighRes(timerStat, timeout * 1000);
        User::WaitForRequest(timerStat, selectStat);
        if (selectStat == KRequestPending) {
            nativeSocket.CancelIoctl();
            //CancelIoctl completes the request (most likely with KErrCancel)
            //We need to wait for this to keep the thread semaphore balanced (or active scheduler will panic)
            User::WaitForRequest(selectStat);
            //restart asynchronous notifier (only one IOCTL allowed at a time)
            if (asyncSelect)
                asyncSelect->IssueRequest();
#ifdef QNATIVESOCKETENGINE_DEBUG
            qDebug() << "QSymbianSocketEnginePrivate::nativeSelect: select timeout";
#endif
            return 0; //timeout
        } else {
            selectTimer.Cancel();
            User::WaitForRequest(timerStat);
        }
    }

#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEnginePrivate::nativeSelect: select status" << selectStat.Int() << (int)selectFlags();
#endif
    if (selectStat != KErrNone)
        return selectStat.Int();
    if (selectFlags() & KSockSelectExcept) {
        TInt err;
        nativeSocket.GetOpt(KSOSelectLastError, KSOLSocket, err);
#ifdef QNATIVESOCKETENGINE_DEBUG
        qDebug() << "QSymbianSocketEnginePrivate::nativeSelect: select last error" <<  err;
#endif
        //TODO: avoidable cast?
        //set the error here, because read won't always return the same error again as select.
        const_cast<QSymbianSocketEnginePrivate*>(this)->setError(err);
        //restart asynchronous notifier (only one IOCTL allowed at a time)
        if (asyncSelect)
            asyncSelect->IssueRequest(); //TODO: in error case should we restart or not?
        return err;
    }
    if (checkRead && (selectFlags() & KSockSelectRead)) {
        Q_ASSERT(selectForRead);
        *selectForRead = true;
    }
    if (checkWrite && (selectFlags() & KSockSelectWrite)) {
        Q_ASSERT(selectForWrite);
        *selectForWrite = true;
    }
    //restart asynchronous notifier (only one IOCTL allowed at a time)
    if (asyncSelect)
        asyncSelect->IssueRequest();
    return 1;
}

bool QSymbianSocketEngine::joinMulticastGroup(const QHostAddress &groupAddress,
                              const QNetworkInterface &iface)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::joinMulticastGroup(), false);
    Q_CHECK_STATE(QSymbianSocketEngine::joinMulticastGroup(), QAbstractSocket::BoundState, false);
    Q_CHECK_TYPE(QSymbianSocketEngine::joinMulticastGroup(), QAbstractSocket::UdpSocket, false);
    return d->multicastGroupMembershipHelper(groupAddress, iface, KSoIp6JoinGroup);
}

bool QSymbianSocketEngine::leaveMulticastGroup(const QHostAddress &groupAddress,
                               const QNetworkInterface &iface)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::leaveMulticastGroup(), false);
    Q_CHECK_STATE(QSymbianSocketEngine::leaveMulticastGroup(), QAbstractSocket::BoundState, false);
    Q_CHECK_TYPE(QSymbianSocketEngine::leaveMulticastGroup(), QAbstractSocket::UdpSocket, false);
    return d->multicastGroupMembershipHelper(groupAddress, iface, KSoIp6LeaveGroup);
}

bool QSymbianSocketEnginePrivate::multicastGroupMembershipHelper(const QHostAddress &groupAddress,
                          const QNetworkInterface &iface,
                          TUint operation)
{
    //TODO - untested
    //translate address
    TPckgBuf<TIp6Mreq> option;
    Q_IPV6ADDR ip6 = groupAddress.toIPv6Address();
    memcpy(option().iAddr.u.iAddr8, ip6.c, 16);
    //translate interface
    //TODO - can we just use iface.index() ?
    TPckgBuf<TSoInetIfQuery> query;
    query().iName = qt_QString2TPtrC(iface.name());
    TInt err = nativeSocket.GetOpt(KSoInetIfQueryByName, KSolInetIfQuery, query);
    if (err == KErrNone)
        option().iInterface = query().iIndex;
    else
        option().iInterface = 0;
    //join or leave group
    return (KErrNone == nativeSocket.SetOpt(operation, KSolInetIp, option));
}

QNetworkInterface QSymbianSocketEngine::multicastInterface() const
{
    //TODO
    const Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::multicastInterface(), QNetworkInterface());
    Q_CHECK_TYPE(QSymbianSocketEngine::multicastInterface(), QAbstractSocket::UdpSocket, QNetworkInterface());
    return QNetworkInterface();
}

bool QSymbianSocketEngine::setMulticastInterface(const QNetworkInterface &iface)
{
    //TODO - this is possibly a unix'ism as the RConnection on which the socket was created is probably controlling this
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setMulticastInterface(), false);
    Q_CHECK_TYPE(QSymbianSocketEngine::setMulticastInterface(), QAbstractSocket::UdpSocket, false);
    return false;
}

bool QSymbianSocketEnginePrivate::checkProxy(const QHostAddress &address)
{
    if (address == QHostAddress::LocalHost || address == QHostAddress::LocalHostIPv6)
        return true;

#if !defined(QT_NO_NETWORKPROXY)
    QObject *parent = q_func()->parent();
    QNetworkProxy proxy;
    if (QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(parent)) {
        proxy = socket->proxy();
    } else if (QTcpServer *server = qobject_cast<QTcpServer *>(parent)) {
        proxy = server->proxy();
    } else {
        // no parent -> no proxy
        return true;
    }

    if (proxy.type() == QNetworkProxy::DefaultProxy)
        proxy = QNetworkProxy::applicationProxy();

    if (proxy.type() != QNetworkProxy::DefaultProxy &&
        proxy.type() != QNetworkProxy::NoProxy) {
        // QSymbianSocketEngine doesn't do proxies
        setError(QAbstractSocket::UnsupportedSocketOperationError,
                 InvalidProxyTypeString);
        return false;
    }
#endif

    return true;
}

// FIXME this is also in QNativeSocketEngine, unify it
/*! \internal

    Sets the error and error string if not set already. The only
    interesting error is the first one that occurred, and not the last
    one.
*/
void QSymbianSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const
{
    if (hasSetSocketError) {
        // Only set socket errors once for one engine; expect the
        // socket to recreate its engine after an error. Note: There's
        // one exception: SocketError(11) bypasses this as it's purely
        // a temporary internal error condition.
        // Another exception is the way the waitFor*() functions set
        // an error when a timeout occurs. After the call to setError()
        // they reset the hasSetSocketError to false
        return;
    }
    if (error != QAbstractSocket::SocketError(11))
        hasSetSocketError = true;

    socketError = error;

    switch (errorString) {
    case NonBlockingInitFailedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unable to initialize non-blocking socket");
        break;
    case BroadcastingInitFailedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unable to initialize broadcast socket");
        break;
    case NoIpV6ErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Attempt to use IPv6 socket on a platform with no IPv6 support");
        break;
    case RemoteHostClosedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("The remote host closed the connection");
        break;
    case TimeOutErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Network operation timed out");
        break;
    case ResourceErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Out of resources");
        break;
    case OperationUnsupportedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unsupported socket operation");
        break;
    case ProtocolUnsupportedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Protocol type not supported");
        break;
    case InvalidSocketErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Invalid socket descriptor");
        break;
    case HostUnreachableErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Host unreachable");
        break;
    case NetworkUnreachableErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Network unreachable");
        break;
    case AccessErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Permission denied");
        break;
    case ConnectionTimeOutErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Connection timed out");
        break;
    case ConnectionRefusedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Connection refused");
        break;
    case AddressInuseErrorString:
        socketErrorString = QSymbianSocketEngine::tr("The bound address is already in use");
        break;
    case AddressNotAvailableErrorString:
        socketErrorString = QSymbianSocketEngine::tr("The address is not available");
        break;
    case AddressProtectedErrorString:
        socketErrorString = QSymbianSocketEngine::tr("The address is protected");
        break;
    case DatagramTooLargeErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Datagram was too large to send");
        break;
    case SendDatagramErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unable to send a message");
        break;
    case ReceiveDatagramErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unable to receive a message");
        break;
    case WriteErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unable to write");
        break;
    case ReadErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Network error");
        break;
    case PortInuseErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Another socket is already listening on the same port");
        break;
    case NotSocketErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Operation on non-socket");
        break;
    case InvalidProxyTypeString:
        socketErrorString = QSymbianSocketEngine::tr("The proxy type is invalid for this operation");
        break;
    case InvalidAddressErrorString:
        socketErrorString = QSymbianSocketEngine::tr("The address is invalid for this operation");
        break;
    case SessionNotOpenErrorString:
        socketErrorString = QSymbianSocketEngine::tr("The specified network session is not opened");
        break;
    case UnknownSocketErrorString:
        socketErrorString = QSymbianSocketEngine::tr("Unknown error");
        break;
    }
}

void QSymbianSocketEnginePrivate::setError(TInt symbianError)
{
    switch (symbianError) {
    case KErrDisconnected:
    case KErrEof:
    case KErrConnectionTerminated: //interface stopped externally - RConnection::Stop(EStopAuthoritative)
        setError(QAbstractSocket::RemoteHostClosedError,
                 QSymbianSocketEnginePrivate::RemoteHostClosedErrorString);
        break;
    case KErrNetUnreach:
        setError(QAbstractSocket::NetworkError,
                 QSymbianSocketEnginePrivate::NetworkUnreachableErrorString);
        break;
    case KErrHostUnreach:
        setError(QAbstractSocket::NetworkError,
                 QSymbianSocketEnginePrivate::HostUnreachableErrorString);
        break;
    case KErrNoProtocolOpt:
        setError(QAbstractSocket::NetworkError,
                 QSymbianSocketEnginePrivate::ProtocolUnsupportedErrorString);
        break;
    case KErrInUse:
        setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
        break;
    case KErrPermissionDenied:
        setError(QAbstractSocket::SocketAccessError, AccessErrorString);
        break;
    case KErrNotSupported:
        setError(QAbstractSocket::UnsupportedSocketOperationError, OperationUnsupportedErrorString);
        break;
    case KErrNoMemory:
        setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
        break;
    case KErrCouldNotConnect:
        setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
        break;
    case KErrTimedOut:
        setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
        break;
    case KErrBadName:
        setError(QAbstractSocket::NetworkError, InvalidAddressErrorString);
        break;
    default:
        socketError = QAbstractSocket::NetworkError;
        socketErrorString = QSystemError(symbianError, QSystemError::NativeError).toString();
        break;
    }
    hasSetSocketError = true;
}

bool QSymbianSocketEngine::isReadNotificationEnabled() const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::isReadNotificationEnabled(), false);
    return d->readNotificationsEnabled;
}

void QSymbianSocketEngine::setReadNotificationEnabled(bool enable)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setReadNotificationEnabled(), Q_VOID);
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEngine::setReadNotificationEnabled" << enable << "socket" << d->socketDescriptor;
#endif
    d->readNotificationsEnabled = enable;
    if (enable && d->threadData->eventDispatcher && !d->asyncSelect)
        d->asyncSelect = q_check_ptr(new QAsyncSelect(0, d->nativeSocket, this));
    // TODO: what do we do if event dispatcher doesn't exist yet?
    if (d->asyncSelect)
        d->asyncSelect->IssueRequest();
}

bool QSymbianSocketEngine::isWriteNotificationEnabled() const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::isWriteNotificationEnabled(), false);
    return d->writeNotificationsEnabled;
}

void QSymbianSocketEngine::setWriteNotificationEnabled(bool enable)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setWriteNotificationEnabled(), Q_VOID);
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEngine::setWriteNotificationEnabled" << enable << "socket" << d->socketDescriptor;
#endif
    d->writeNotificationsEnabled = enable;
    if (enable && d->threadData->eventDispatcher && !d->asyncSelect)
        d->asyncSelect = q_check_ptr(new QAsyncSelect(0, d->nativeSocket, this));
    // TODO: what do we do if event dispatcher doesn't exist yet?
    if (d->asyncSelect)
        d->asyncSelect->IssueRequest();
}

bool QSymbianSocketEngine::isExceptionNotificationEnabled() const
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::isExceptionNotificationEnabled(), false);
    return d->exceptNotificationsEnabled;
    return false;
}

// FIXME do we really need this for symbian?
void QSymbianSocketEngine::setExceptionNotificationEnabled(bool enable)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::setExceptionNotificationEnabled(), Q_VOID);
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEngine::setExceptionNotificationEnabled" << enable << "socket" << d->socketDescriptor;
#endif
    d->exceptNotificationsEnabled = enable;
    if (enable && d->threadData->eventDispatcher && !d->asyncSelect)
        d->asyncSelect = q_check_ptr(new QAsyncSelect(0, d->nativeSocket, this));
    if (d->asyncSelect)
        d->asyncSelect->IssueRequest();
}

bool QSymbianSocketEngine::waitForRead(int msecs, bool *timedOut)
{
    Q_D(const QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::waitForRead(), false);
    Q_CHECK_NOT_STATE(QSymbianSocketEngine::waitForRead(),
                      QAbstractSocket::UnconnectedState, false);

    if (timedOut)
        *timedOut = false;

    int ret = d->nativeSelect(msecs, true);
    if (ret == 0) {
        if (timedOut)
            *timedOut = true;
        d->setError(QAbstractSocket::SocketTimeoutError,
            d->TimeOutErrorString);
        d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
        return false;
    } else if (state() == QAbstractSocket::ConnectingState) {
        connectToHost(d->peerAddress, d->peerPort);
    }

    return ret > 0;
}

bool QSymbianSocketEngine::waitForWrite(int msecs, bool *timedOut)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::waitForWrite(), false);
    Q_CHECK_NOT_STATE(QSymbianSocketEngine::waitForWrite(),
                      QAbstractSocket::UnconnectedState, false);

    if (timedOut)
        *timedOut = false;

    int ret = d->nativeSelect(msecs, false);

    if (ret == 0) {
        if (timedOut)
            *timedOut = true;
        d->setError(QAbstractSocket::SocketTimeoutError,
                    d->TimeOutErrorString);
        d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
        return false;
    } else if (state() == QAbstractSocket::ConnectingState) {
        connectToHost(d->peerAddress, d->peerPort);
    }

    return ret > 0;
}

bool QSymbianSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite,
                                      bool checkRead, bool checkWrite,
                                      int msecs, bool *timedOut)
{
    Q_D(QSymbianSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QSymbianSocketEngine::waitForWrite(), false);
    Q_CHECK_NOT_STATE(QSymbianSocketEngine::waitForReadOrWrite(),
                      QAbstractSocket::UnconnectedState, false);

    int ret = d->nativeSelect(msecs, checkRead, checkWrite, readyToRead, readyToWrite);

    if (ret == 0) {
        if (timedOut)
            *timedOut = true;
        d->setError(QAbstractSocket::SocketTimeoutError,
                    d->TimeOutErrorString);
        d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions
        return false;
    } else if (state() == QAbstractSocket::ConnectingState) {
        connectToHost(d->peerAddress, d->peerPort);
    }

    return ret > 0;
}

qint64 QSymbianSocketEngine::bytesToWrite() const
{
    // This is what the QNativeSocketEngine does
    return 0;
}

//TODO: is defining PostThreadChangeEvent as QEvent::User + 1 safe?
//TODO: would QMetaObject::invokeMethod(obj, "postThreadChangeSlot", Qt::QueuedConnection) be better?
//TODO: if QTBUG-16787 is implemented, use that instead
bool QSymbianSocketEngine::event(QEvent* ev)
{
    Q_D(QSymbianSocketEngine);
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QSymbianSocketEngine::event";
#endif
    switch (ev->type()) {
    case QEvent::ThreadChange:
#ifdef QNATIVESOCKETENGINE_DEBUG
        qDebug() << "ThreadChange" << d->readNotificationsEnabled << d->writeNotificationsEnabled << d->exceptNotificationsEnabled;
#endif
        if (d->asyncSelect) {
            delete d->asyncSelect;
            d->asyncSelect = 0;
            QEvent *postThreadChangeEvent = new QEvent(PostThreadChangeEvent);
            QCoreApplication::postEvent(this, postThreadChangeEvent);
        }
        d->selectTimer.Close();
        return true;
    case PostThreadChangeEvent:
#ifdef QNATIVESOCKETENGINE_DEBUG
        qDebug() << "PostThreadChangeEvent" << d->readNotificationsEnabled << d->writeNotificationsEnabled << d->exceptNotificationsEnabled;
#endif
        // recreate select in new thread
        d->asyncSelect = q_check_ptr(new QAsyncSelect(0, d->nativeSocket, this));
        d->asyncSelect->IssueRequest();
        return true;
    }
    return QAbstractSocketEngine::event(ev);
}

QAsyncSelect::QAsyncSelect(QAbstractEventDispatcher *dispatcher, RSocket& sock, QSymbianSocketEngine *parent)
    : CActive(CActive::EPriorityStandard),
      m_inSocketEvent(false),
      m_deleteLater(false),
      m_socket(sock),
      m_selectFlags(0),
      engine(parent)
{
    CActiveScheduler::Add(this);
}

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

void QAsyncSelect::DoCancel()
{
    m_socket.CancelIoctl();
}

void QAsyncSelect::RunL()
{
    QT_TRYCATCH_LEAVING(run());
}

//RunError is called by the active scheduler if RunL leaves.
//Typically this will happen if a std::bad_alloc propagates down from the application
TInt QAsyncSelect::RunError(TInt aError)
{
    if (engine) {
        QT_TRY {
            engine->d_func()->setError(aError);
            if (engine->isExceptionNotificationEnabled())
                engine->exceptionNotification();
            if (engine->isReadNotificationEnabled())
                engine->readNotification();
        }
        QT_CATCH(...) {}
    }
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QAsyncSelect::RunError" << aError;
#endif
    return KErrNone;
}

void QAsyncSelect::run()
{
    //TODO: block when event loop demands it
    //if (maybeQueueForLater())
    //    return;
    m_inSocketEvent = true;
    m_selectBuf() &= m_selectFlags; //the select ioctl reports everything, so mask to only what we requested
    //KSockSelectReadContinuation is for reading datagrams in a mode that doesn't discard when the
    //datagram is larger than the read buffer - Qt doesn't need to use this.
    if (engine && engine->isReadNotificationEnabled()
        && ((m_selectBuf() & KSockSelectRead) || iStatus != KErrNone)) {
        engine->readNotification();
    }
    if (engine && engine->isWriteNotificationEnabled()
        && ((m_selectBuf() & KSockSelectWrite) || iStatus != KErrNone)) {
        if (engine->state() == QAbstractSocket::ConnectingState)
            engine->connectionNotification();
        else
            engine->writeNotification();
    }
    if (engine && engine->isExceptionNotificationEnabled()
        && ((m_selectBuf() & KSockSelectExcept) || iStatus != KErrNone)) {
        engine->exceptionNotification();
    }
    m_inSocketEvent = false;
    if (m_deleteLater) {
        delete this;
        return;
    }
    // select again (unless disabled by one of the callbacks)
    IssueRequest();
}

void QAsyncSelect::deleteLater()
{
    if (m_inSocketEvent) {
        engine = 0;
        m_deleteLater = true;
    } else {
        delete this;
    }
}

void QAsyncSelect::IssueRequest()
{
    if (m_inSocketEvent)
        return; //prevent thrashing during a callback - socket engine enables/disables multiple notifiers
    TUint selectFlags = 0;
    if (engine->isReadNotificationEnabled())
        selectFlags |= KSockSelectRead;
    if (engine->isWriteNotificationEnabled())
        selectFlags |= KSockSelectWrite;
    if (engine->isExceptionNotificationEnabled())
        selectFlags |= KSockSelectExcept;
    if (selectFlags != m_selectFlags) {
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QAsyncSelect::IssueRequest() - select flags" << m_selectFlags << "->" << selectFlags;
#endif
        Cancel();
        m_selectFlags = selectFlags;
    }
    if (m_selectFlags && !IsActive()) {
        //always request errors (write notification does not complete on connect errors)
        m_selectBuf() = m_selectFlags | KSockSelectExcept;
        m_socket.Ioctl(KIOctlSelect, iStatus, &m_selectBuf, KSOLSocket);
        SetActive();
    }
#ifdef QNATIVESOCKETENGINE_DEBUG
    qDebug() << "QAsyncSelect::IssueRequest() - IsActive" << IsActive();
#endif
}

QT_END_NAMESPACE