summaryrefslogtreecommitdiffstats
path: root/src/network/kernel/qhostinfo_symbian.cpp
blob: 70ee5b8642a91f51bbb21905c93fb9da154e05ae (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
/****************************************************************************
**
** 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 QHOSTINFO_DEBUG

// Qt Headers
#include <QByteArray>
#include <QUrl>
#include <QList>

#include "qplatformdefs.h"

#include "qhostinfo_p.h"
#include <private/qcore_symbian_p.h>
#include <private/qsystemerror_p.h>
#include <private/qnetworksession_p.h>

// Header does not exist in the S60 5.0 SDK
//#include <networking/dnd_err.h>
const TInt KErrDndNameNotFound = -5120; // Returned when no data found for GetByName
const TInt KErrDndAddrNotFound = -5121; // Returned when no data found for GetByAddr

QT_BEGIN_NAMESPACE

QHostInfo QHostInfoAgent::fromName(const QString &hostName, QSharedPointer<QNetworkSession> networkSession)
{
    QHostInfo results;

    // Connect to ESOCK
    RSocketServ socketServ(qt_symbianGetSocketServer());
    RHostResolver hostResolver;


    int err;
    if (networkSession)
        err = QNetworkSessionPrivate::nativeOpenHostResolver(*networkSession, hostResolver, KAfInet, KProtocolInetUdp);
    else
        err = hostResolver.Open(socketServ, KAfInet, KProtocolInetUdp);
    if (err) {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QSystemError(err,QSystemError::NativeError).toString());

        return results;
    }

    TNameEntry nameResult;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
        TInetAddr IpAdd;
        IpAdd.Input(qt_QString2TPtrC(hostName));

        // Synchronous request. nameResult returns Host Name.
        err = hostResolver.GetByAddress(IpAdd, nameResult);
        if (err) {
            // TODO - Could there be other errors? Symbian docs don't say.
            if (err == KErrDndAddrNotFound) {
                results.setError(QHostInfo::HostNotFound);
                results.setErrorString(tr("Host not found"));
            } else {
                results.setError(QHostInfo::UnknownError);
                results.setErrorString(QSystemError(err,QSystemError::NativeError).toString());
            }

            return results;
        }

        results.setHostName(qt_TDesC2QString(nameResult().iName));
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }


    // Call RHostResolver::GetByAddress, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.

    // Synchronous request.
    err = hostResolver.GetByName(qt_QString2TPtrC(QString::fromLatin1(aceHostname)), nameResult);
    if (err) {
        // TODO - Could there be other errors? Symbian docs don't say.
        if (err == KErrDndNameNotFound) {
            results.setError(QHostInfo::HostNotFound);
            results.setErrorString(tr("Host not found"));
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(QSystemError(err,QSystemError::NativeError).toString());
        }

        return results;
    }

    QList<QHostAddress> hostAddresses;

    TInetAddr hostAdd = nameResult().iAddr;
    // 39 is the maximum length of an IPv6 address.
    TBuf<39> ipAddr;

    // Fill ipAddr with the IP address from hostAdd
    hostAdd.Output(ipAddr);
    if (ipAddr.Length() > 0)
        hostAddresses.append(QHostAddress(qt_TDesC2QString(ipAddr)));

    // Check if there's more than one IP address linkd to this name
    while (hostResolver.Next(nameResult) == KErrNone) {
        hostAdd = nameResult().iAddr;
        hostAdd.Output(ipAddr);

        // Ensure that record is valid (not an alias and with length greater than 0)
        if (!(nameResult().iFlags & TNameRecord::EAlias) && !(hostAdd.IsUnspecified())) {
            hostAddresses.append(QHostAddress(qt_TDesC2QString(ipAddr)));
        }
    }

    hostResolver.Close();

    results.setAddresses(hostAddresses);
    return results;
}

QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    // null shared pointer
    QSharedPointer<QNetworkSession> networkSession;
    return fromName(hostName, networkSession);
}

QString QHostInfo::localHostName()
{
    // Connect to ESOCK
    RSocketServ socketServ(qt_symbianGetSocketServer());
    RHostResolver hostResolver;

    // Will return both IPv4 and IPv6
    // TODO: Pass RHostResolver.Open() the global RConnection
    int err = hostResolver.Open(socketServ, KAfInet, KProtocolInetUdp);
    if (err)
        return QString();

    THostName hostName;
    err = hostResolver.GetHostName(hostName);
    if (err)
        return QString();

    hostResolver.Close();

    return qt_TDesC2QString(hostName);
}

QString QHostInfo::localDomainName()
{
    // TODO - fill with code.
    return QString();
}


QSymbianHostResolver::QSymbianHostResolver(const QString &hostName, int identifier, QSharedPointer<QNetworkSession> networkSession)
    : CActive(CActive::EPriorityStandard), iHostName(hostName),
      iSocketServ(qt_symbianGetSocketServer()), iNetworkSession(networkSession), iResults(identifier)
{
    CActiveScheduler::Add(this);
}

QSymbianHostResolver::~QSymbianHostResolver()
{
#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostInfoLookupManger::~QSymbianHostResolver" << id();
#endif
    Cancel();
    iHostResolver.Close();
}

// Async equivalent to QHostInfoAgent::fromName()
void QSymbianHostResolver::requestHostLookup()
{

#if defined(QHOSTINFO_DEBUG)
    qDebug("QSymbianHostResolver::requestHostLookup(%s) looking up... (id = %d)",
        iHostName.toLatin1().constData(), id());
#endif

    int err;
    if (iNetworkSession) {
        err = QNetworkSessionPrivate::nativeOpenHostResolver(*iNetworkSession, iHostResolver, KAfInet, KProtocolInetUdp);
#if defined(QHOSTINFO_DEBUG)
        qDebug("using resolver from session (err = %d)", err);
#endif
    } else {
        err = iHostResolver.Open(iSocketServ, KAfInet, KProtocolInetUdp);
#if defined(QHOSTINFO_DEBUG)
        qDebug("using default resolver (err = %d)", err);
#endif
    }
    if (err) {
        iResults.setError(QHostInfo::UnknownError);
        iResults.setErrorString(QSystemError(err, QSystemError::NativeError).toString());

    } else {

        if (iAddress.setAddress(iHostName)) {
            // Reverse lookup
            IpAdd.Input(qt_QString2TPtrC(iHostName));

            // Asynchronous request.
            iHostResolver.GetByAddress(IpAdd, iNameResult, iStatus); // <---- ASYNC
            iState = EGetByAddress;

        } else {

            // IDN support
            QByteArray aceHostname = QUrl::toAce(iHostName);
            iResults.setHostName(iHostName);
            if (aceHostname.isEmpty()) {
                iResults.setError(QHostInfo::HostNotFound);
                iResults.setErrorString(iHostName.isEmpty() ?
                                       QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                                       QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));

                err = KErrArgument;
            } else {
                iEncodedHostName = QString::fromLatin1(aceHostname);
                iHostNamePtr.Set(qt_QString2TPtrC(iEncodedHostName));

                // Asynchronous request.
                iHostResolver.GetByName(iHostNamePtr, iNameResult, iStatus);
                iState = EGetByName;
            }
        }
    }
    SetActive();
    if (err) {
        iHostResolver.Close();

        //self complete so that RunL can inform manager without causing recursion
        iState = EError;
        TRequestStatus* stat = &iStatus;
        User::RequestComplete(stat, err);
    }
}

void QSymbianHostResolver::DoCancel()
{
#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostResolver::DoCancel" << QThread::currentThreadId() << id() << (int)iState << this;
#endif
    if (iState == EGetByAddress || iState == EGetByName || iState == EGetMoreNames) {
        //these states have made an async request to host resolver
        iHostResolver.Cancel();
    } else {
        //for the self completing states there is nothing to cancel
        Q_ASSERT(iState == EError);
    }
}

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

void QSymbianHostResolver::run()
{
    switch (iState) {
    case EGetByName:
        processNameResult();
        break;
    case EGetByAddress:
        processAddressResult();
        break;
    case EError:
        returnResults();
        break;
    default:
        iResults.setError(QHostInfo::UnknownError);
        iResults.setErrorString(QSystemError(KErrCorrupt,QSystemError::NativeError).toString());
        returnResults();
    }
}

void QSymbianHostResolver::returnResults()
{
    iState = EIdle;

    QSymbianHostInfoLookupManger *manager = QSymbianHostInfoLookupManger::globalInstance();
    manager->lookupFinished(this);

    resultEmitter.emitResultsReady(iResults);

    delete this;
}

TInt QSymbianHostResolver::RunError(TInt aError)
{
    QT_TRY {
        iState = EIdle;

        QSymbianHostInfoLookupManger *manager = QSymbianHostInfoLookupManger::globalInstance();
        manager->lookupFinished(this);

        iResults.setError(QHostInfo::UnknownError);
        iResults.setErrorString(QSystemError(aError,QSystemError::NativeError).toString());

        resultEmitter.emitResultsReady(iResults);
    }
    QT_CATCH(...) {}

    delete this;

    return KErrNone;
}

void QSymbianHostResolver::processNameResult()
{
    if (iStatus.Int() == KErrNone) {
        TInetAddr hostAdd = iNameResult().iAddr;
        // 39 is the maximum length of an IPv6 address.
        TBuf<39> ipAddr;

        hostAdd.Output(ipAddr);

        // Ensure that record is valid (not an alias and with length greater than 0)
        if (!(iNameResult().iFlags & TNameRecord::EAlias) && !(hostAdd.IsUnspecified())) {
           if (iNameResult().iAddr.Family() == KAfInet) {
                // IPv4 - prepend
                iHostAddresses.prepend(QHostAddress(qt_TDesC2QString(ipAddr)));
            } else {
                // IPv6 - append
                iHostAddresses.append(QHostAddress(qt_TDesC2QString(ipAddr)));
            }
        }

        iState = EGetByName;
        iHostResolver.Next(iNameResult, iStatus);
        SetActive();
    }
    else if (iStatus.Int() == KErrDndNameNotFound) {
        // No more addresses, so return the results (or an error if there aren't any).
        if (iHostAddresses.count() > 0) {
            iResults.setAddresses(iHostAddresses);
        } else {
            iState = EError;
            iResults.setError(QHostInfo::HostNotFound);
            iResults.setErrorString(QObject::tr("Host not found"));
        }
        returnResults();
    }
    else {
        // Unknown error
        iState = EError;
        iResults.setError(QHostInfo::UnknownError);
        iResults.setErrorString(QSystemError(iStatus.Int(),QSystemError::NativeError).toString());
        returnResults();
    }
}

void QSymbianHostResolver::processAddressResult()
{
    TInt err = iStatus.Int();

    if (err < 0) {
        // TODO - Could there be other errors? Symbian docs don't say.
        if (err == KErrDndAddrNotFound) {
            iResults.setError(QHostInfo::HostNotFound);
            iResults.setErrorString(QObject::tr("Host not found"));
        } else {
            iResults.setError(QHostInfo::UnknownError);
            iResults.setErrorString(QSystemError(err,QSystemError::NativeError).toString());
        }

        returnResults();
        return;
    }

    iResults.setHostName(qt_TDesC2QString(iNameResult().iName));
    iResults.setAddresses(QList<QHostAddress>() << iAddress);
    returnResults();
}


int QSymbianHostResolver::id()
{
    return iResults.lookupId();
}

QSymbianHostInfoLookupManger::QSymbianHostInfoLookupManger()
{
}

QSymbianHostInfoLookupManger::~QSymbianHostInfoLookupManger()
{
}

void QSymbianHostInfoLookupManger::clear()
{
    QMutexLocker locker(&mutex);
#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostInfoLookupManger::clear" << QThread::currentThreadId();
#endif
    //TODO: these aren't deleted because of thread unsafety, but that is a behaviour difference
    //qDeleteAll(iCurrentLookups);
    //qDeleteAll(iScheduledLookups);
    cache.clear();
}

void QSymbianHostInfoLookupManger::lookupFinished(QSymbianHostResolver *r)
{
    QMutexLocker locker(&mutex);

#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostInfoLookupManger::lookupFinished" << QThread::currentThreadId() << r->id() << "current" << iCurrentLookups.count() << "queued" << iScheduledLookups.count();
#endif
    // remove finished lookup from array and destroy
    TInt count = iCurrentLookups.count();
    for (TInt i = 0; i < count; i++) {
        if (iCurrentLookups[i]->id() == r->id()) {
            iCurrentLookups.removeAt(i);
            break;
        }
    }

    runNextLookup();
}

void QSymbianHostInfoLookupManger::runNextLookup()
{
#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostInfoLookupManger::runNextLookup" << QThread::currentThreadId() << "current" << iCurrentLookups.count() << "queued" << iScheduledLookups.count();
#endif
    // check to see if there are any scheduled lookups
    if (iScheduledLookups.count() > 0) {
        // if so, move one to the current lookups and run it
        // FIFO
        QSymbianHostResolver* hostResolver = iScheduledLookups.takeFirst();
        iCurrentLookups.append(hostResolver);
        hostResolver->requestHostLookup();
    }
}

// called from QHostInfo
void QSymbianHostInfoLookupManger::scheduleLookup(QSymbianHostResolver* r)
{
    QMutexLocker locker(&mutex);

#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostInfoLookupManger::scheduleLookup" << QThread::currentThreadId() << r->id() << "current" << iCurrentLookups.count() << "queued" << iScheduledLookups.count();
#endif
    // Check to see if we have space on the current lookups pool.
    if (iCurrentLookups.count() >= KMaxConcurrentLookups) {
        // If no, schedule for later.
        iScheduledLookups.append(r);
#if defined(QHOSTINFO_DEBUG)
    qDebug(" - scheduled");
#endif
        return;
    } else {
        // If yes, add it to the current lookups.
        iCurrentLookups.append(r);

        // ... and trigger the async call.
        r->requestHostLookup();
    }
}

void QSymbianHostInfoLookupManger::abortLookup(int id)
{
    QMutexLocker locker(&mutex);

#if defined(QHOSTINFO_DEBUG)
    qDebug() << "QSymbianHostInfoLookupManger::abortLookup" << QThread::currentThreadId() << id << "current" << iCurrentLookups.count() << "queued" << iScheduledLookups.count();
#endif
    int i = 0;
    // Find the aborted lookup by ID.
    // First in the current lookups.
    for (i = 0; i < iCurrentLookups.count(); i++) {
        if (id == iCurrentLookups[i]->id()) {
            QSymbianHostResolver* r = iCurrentLookups.at(i);
            iCurrentLookups.removeAt(i);
            delete r; //cancels via destructor
            runNextLookup();
            return;
        }
    }
    // Then in the scheduled lookups.
    for (i = 0; i < iScheduledLookups.count(); i++) {
        if (id == iScheduledLookups[i]->id()) {
            QSymbianHostResolver* r = iScheduledLookups.at(i);
            iScheduledLookups.removeAt(i);
            delete r;
            return;
        }
    }
}

QSymbianHostInfoLookupManger* QSymbianHostInfoLookupManger::globalInstance()
{
    return static_cast<QSymbianHostInfoLookupManger*>
            (QAbstractHostInfoLookupManger::globalInstance());
}

QT_END_NAMESPACE