summaryrefslogtreecommitdiffstats
path: root/src/nfc/qnearfieldtarget_ios.mm
blob: b058ad7507065bff8c21e66c16de3eefe9d3440e (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
// Copyright (C) 2020 Governikus GmbH & Co. KG
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "ios/qiosnfcndefsessiondelegate_p.h"
#include "ios/qiosndefnotifier_p.h"

#include "qnearfieldtarget_ios_p.h"

#import <CoreNFC/NFCNDEFReaderSession.h>
#import <CoreNFC/NFCReaderSession.h>
#import <CoreNFC/NFCTagReaderSession.h>
#import <CoreNFC/NFCISO7816Tag.h>
#import <CoreNFC/NFCTag.h>

#include <QtCore/qapplicationstatic.h>
#include <QtCore/qloggingcategory.h>

QT_BEGIN_NAMESPACE

Q_APPLICATION_STATIC(ResponseProvider, responseProvider)

void ResponseProvider::provideResponse(QNearFieldTarget::RequestId requestId, bool success, QByteArray recvBuffer) {
    Q_EMIT responseReceived(requestId, success, recvBuffer);
}

void NfcDeleter::operator()(void *obj)
{
    id some = static_cast<id>(obj);

    if ([some conformsToProtocol:@protocol(NFCNDEFTag)])
        [static_cast<id<NFCNDEFTag>>(some) release];
    else if ([some conformsToProtocol:@protocol(NFCTag)])
        [static_cast<id<NFCTag>>(some) release];
    else
        Q_UNREACHABLE();
}

QNearFieldTargetPrivateImpl:: QNearFieldTargetPrivateImpl(void *tag, QObject *parent) :
    QNearFieldTargetPrivate(parent),
    nfcTag(tag)
{
    Q_ASSERT(nfcTag);

    QObject::connect(this, &QNearFieldTargetPrivate::error, this, &QNearFieldTargetPrivateImpl::onTargetError);
    QObject::connect(responseProvider, &ResponseProvider::responseReceived, this, &QNearFieldTargetPrivateImpl::onResponseReceived);
    QObject::connect(&targetCheckTimer, &QTimer::timeout, this, &QNearFieldTargetPrivateImpl::onTargetCheck);
    targetCheckTimer.start(500);
}

QNearFieldTargetPrivateImpl:: QNearFieldTargetPrivateImpl(void *delegate, void *tag, QObject *parent) :
    QNearFieldTargetPrivate(parent),
    nfcTag(tag)
{
    Q_ASSERT(delegate && tag);
    Q_ASSERT([id(tag) conformsToProtocol:@protocol(NFCNDEFTag)]);

    auto qtDelegate = static_cast<QIosNfcNdefSessionDelegate *>(sessionDelegate = delegate);
    notifier = [qtDelegate ndefNotifier];
    Q_ASSERT(notifier);

    // The 'notifier' lives on a (potentially different, unspecified) thread,
    // thus connection is 'queued'.
    QObject::connect(notifier, &QNfcNdefNotifier::tagError, this,
                     &QNearFieldTargetPrivate::error, Qt::QueuedConnection);

    QObject::connect(this, &QNearFieldTargetPrivate::error, this, &QNearFieldTargetPrivateImpl::onTargetError);
    QObject::connect(&targetCheckTimer, &QTimer::timeout, this, &QNearFieldTargetPrivateImpl::onTargetCheck);

    targetCheckTimer.start(500);
}

QNearFieldTargetPrivateImpl::~QNearFieldTargetPrivateImpl()
{
}

void QNearFieldTargetPrivateImpl::invalidate()
{
    queue.clear();
    ndefOperations.clear();

    if (isNdefTag()) {
        Q_ASSERT(notifier);

        QObject::disconnect(notifier, nullptr, this, nullptr);
        notifier = nullptr;
    }

    nfcTag.reset();
    sessionDelegate = nil;

    targetCheckTimer.stop();

    QMetaObject::invokeMethod(this, [this]() {
        Q_EMIT targetLost(this);
    }, Qt::QueuedConnection);
}

QByteArray QNearFieldTargetPrivateImpl::uid() const
{
    if (!nfcTag || isNdefTag()) // NFCNDEFTag does not have this information ...
        return {};

    if (@available(iOS 13, *)) {
        id<NFCTag> tag = static_cast<id<NFCTag>>(nfcTag.get());
        id<NFCISO7816Tag> iso7816Tag = tag.asNFCISO7816Tag;
        if (iso7816Tag)
            return QByteArray::fromNSData(iso7816Tag.identifier);
    }

    return {};
}

QNearFieldTarget::Type QNearFieldTargetPrivateImpl::type() const
{
    if (!nfcTag || isNdefTag()) // No information provided by NFCNDEFTag.
        return QNearFieldTarget::ProprietaryTag;

    if (@available(iOS 13, *)) {
        id<NFCTag> tag = static_cast<id<NFCTag>>(nfcTag.get());
        id<NFCISO7816Tag> iso7816Tag = tag.asNFCISO7816Tag;

        if (tag.type != NFCTagTypeISO7816Compatible || iso7816Tag == nil)
             return QNearFieldTarget::ProprietaryTag;

        if (iso7816Tag.historicalBytes != nil && iso7816Tag.applicationData == nil)
            return QNearFieldTarget::NfcTagType4A;

        if (iso7816Tag.historicalBytes == nil && iso7816Tag.applicationData != nil)
            return QNearFieldTarget::NfcTagType4B;

        return QNearFieldTarget::NfcTagType4;
    }

    return QNearFieldTarget::ProprietaryTag;
}

QNearFieldTarget::AccessMethods QNearFieldTargetPrivateImpl::accessMethods() const
{
    if (isNdefTag())
        return QNearFieldTarget::NdefAccess;

    if (@available(iOS 13, *)) {
        id<NFCTag> tag = static_cast<id<NFCTag>>(nfcTag.get());
        if (tag && [tag conformsToProtocol:@protocol(NFCISO7816Tag)])
            return QNearFieldTarget::TagTypeSpecificAccess;
    }

    return QNearFieldTarget::UnknownAccess;
}

int QNearFieldTargetPrivateImpl::maxCommandLength() const
{
    if (accessMethods() & QNearFieldTarget::TagTypeSpecificAccess)
        return 0xFEFF;

    // TODO: check if 'capacity' of NFCNDEFTag can be used?
    return 0;
}

QNearFieldTarget::RequestId QNearFieldTargetPrivateImpl::sendCommand(const QByteArray &command)
{
    QNearFieldTarget::RequestId requestId = QNearFieldTarget::RequestId(new QNearFieldTarget::RequestIdPrivate());

    if (!(accessMethods() & QNearFieldTarget::TagTypeSpecificAccess)) {
        reportError(QNearFieldTarget::UnsupportedError, requestId);
        return requestId;
    }

    queue.enqueue(std::pair(requestId, command));

    if (!connect()) {
        reportError(QNearFieldTarget::TargetOutOfRangeError, requestId);
        return requestId;
    }

    onExecuteRequest();
    return requestId;
}

bool QNearFieldTargetPrivateImpl::hasNdefMessage()
{
    return hasNDEFMessage;
}

QNearFieldTarget::RequestId QNearFieldTargetPrivateImpl::readNdefMessages()
{
    hasNDEFMessage = false;

    QNearFieldTarget::RequestId requestId = QNearFieldTarget::RequestId(new QNearFieldTarget::RequestIdPrivate);

    if (!(accessMethods() & QNearFieldTarget::NdefAccess) || !isNdefTag()) {
        qCWarning(QT_IOS_NFC, "Target does not allow to read NDEF messages, "
                              "was not detected as NDEF tag by the reader session?");
        reportError(QNearFieldTarget::UnsupportedError, requestId);
        return requestId;
    }

    NdefOperation op;
    op.type = NdefOperation::Read;
    op.requestId = requestId;

    ndefOperations.push_back(op);
    onExecuteRequest();

    return requestId;
}

QNearFieldTarget::RequestId QNearFieldTargetPrivateImpl::writeNdefMessages(const QList<QNdefMessage> &messages)
{
    auto requestId = QNearFieldTarget::RequestId(new QNearFieldTarget::RequestIdPrivate);

    if (!(accessMethods() & QNearFieldTarget::NdefAccess) || !isNdefTag()) {
        qCWarning(QT_IOS_NFC, "Target does not allow to write NDEF messages, "
                              "was not detected as NDEF tag by the reader session?");
        reportError(QNearFieldTarget::UnsupportedError, requestId);
        return requestId;
    }

    if (messages.size() != 1) {
        // The native framework does not allow to write 'messages', only _one_ message
        // at a time. Not to multiply the complexity of having 'ndefOperations' queue
        // with some queue inside the delegate's code (plus some unpredictable errors
        // handling) - require a single message as a single request.
        qCWarning(QT_IOS_NFC, "Only one NDEF message per request ID can be written");
        return requestId;
    }

    NdefOperation op;
    op.type = NdefOperation::Write;
    op.requestId = requestId;
    op.message = messages.first();

    ndefOperations.push_back(op);
    onExecuteRequest();

    return requestId;
}

bool QNearFieldTargetPrivateImpl::isAvailable() const
{
    if (requestInProgress.isValid())
        return true;

    const auto tagIsAvailable = [this](auto tag) {
        return tag && (!connected || tag.available);
    };

    if (isNdefTag())
        return tagIsAvailable(static_cast<id<NFCNDEFTag>>(nfcTag.get()));

    if (@available(iOS 13, *))
        return tagIsAvailable(static_cast<id<NFCTag>>(nfcTag.get()));

    return false;
}

bool QNearFieldTargetPrivateImpl::connect()
{
    if (connected || requestInProgress.isValid())
        return true;

    if (isNdefTag())
        return connected = true;

    if (!isAvailable() || queue.isEmpty())
        return false;

    if (@available(iOS 13, *)) {
        requestInProgress = queue.head().first;
        id<NFCTag> tag = static_cast<id<NFCTag>>(nfcTag.get());
        NFCTagReaderSession* session = tag.session;
        [session connectToTag: tag completionHandler: ^(NSError* error){
            const bool success = error == nil;
            QMetaObject::invokeMethod(this, [this, success] {
                requestInProgress = QNearFieldTarget::RequestId();
                if (success) {
                    connected = true;
                    onExecuteRequest();
                } else {
                    const auto requestId = queue.dequeue().first;
                    reportError(QNearFieldTarget::ConnectionError, requestId);
                    invalidate();
                }
            });
        }];
        return true;
    }

    return false;
}

bool QNearFieldTargetPrivateImpl::isNdefTag() const
{
    const id tag = static_cast<id>(nfcTag.get());
    if ([tag conformsToProtocol:@protocol(NFCMiFareTag)])
        return false;
    if ([tag conformsToProtocol:@protocol(NFCFeliCaTag)])
        return false;
    if ([tag conformsToProtocol:@protocol(NFCISO15693Tag)])
        return false;
    if ([tag conformsToProtocol:@protocol(NFCISO7816Tag)])
        return false;
    return [tag conformsToProtocol:@protocol(NFCNDEFTag)];
}

void QNearFieldTargetPrivateImpl::onTargetCheck()
{
    if (!isAvailable())
        invalidate();
}

void QNearFieldTargetPrivateImpl::onTargetError(QNearFieldTarget::Error error, const QNearFieldTarget::RequestId &id)
{
    Q_UNUSED(id);

    if (error == QNearFieldTarget::TimeoutError)
        invalidate();
}

namespace {

QNdefMessage ndefToQtNdefMessage(NFCNDEFMessage *nativeMessage)
{
    if (!nativeMessage)
        return {};

    QList<QNdefRecord> ndefRecords;
    for (NFCNDEFPayload *ndefRecord in nativeMessage.records) {
        QNdefRecord qtNdefRecord;
        if (ndefRecord.typeNameFormat != NFCTypeNameFormatUnchanged) // Does not match anything in Qt.
            qtNdefRecord.setTypeNameFormat(QNdefRecord::TypeNameFormat(ndefRecord.typeNameFormat));
        if (ndefRecord.identifier)
            qtNdefRecord.setId(QByteArray::fromNSData(ndefRecord.identifier));
        if (ndefRecord.type)
            qtNdefRecord.setType(QByteArray::fromNSData(ndefRecord.type));
        if (ndefRecord.payload)
            qtNdefRecord.setPayload(QByteArray::fromNSData(ndefRecord.payload));
        ndefRecords.push_back(qtNdefRecord);
    }

    return QNdefMessage{ndefRecords};
}

} // Unnamed namespace.

void QNearFieldTargetPrivateImpl::onExecuteRequest()
{
    if (!nfcTag || requestInProgress.isValid())
        return;

    if (isNdefTag()) {
        if (ndefOperations.empty())
            return;

        auto *ndefDelegate = static_cast<QIosNfcNdefSessionDelegate *>(sessionDelegate);
        Q_ASSERT(ndefDelegate);

        Q_ASSERT(qt_Nfc_Queue()); // This is where callbacks get called.

        const auto op = ndefOperations.front();
        ndefOperations.pop_front();
        requestInProgress = op.requestId;
        auto requestId = requestInProgress; // Copy so we capture by value in the block.

        id<NFCNDEFTag> ndefTag = static_cast<id<NFCNDEFTag>>(nfcTag.get());

        std::unique_ptr<QNfcNdefNotifier> guard(new QNfcNdefNotifier);
        auto *cbNotifier = guard.get();

        QObject::connect(cbNotifier, &QNfcNdefNotifier::tagError, this,
                         &QNearFieldTargetPrivate::error, Qt::QueuedConnection);

        if (op.type == NdefOperation::Read) {
            QObject::connect(cbNotifier, &QNfcNdefNotifier::ndefMessageRead,
                             this, &QNearFieldTargetPrivateImpl::messageRead,
                             Qt::QueuedConnection);

            // We call it here, but the callback will be executed on an unspecified thread.
            [ndefTag readNDEFWithCompletionHandler:^(NFCNDEFMessage * _Nullable msg, NSError * _Nullable err) {
                const std::unique_ptr<QNfcNdefNotifier> notifierGuard(cbNotifier);
                if (err) {
                    NSLog(@"Reading NDEF messaged ended with error: %@", err);
                    emit cbNotifier->tagError(QNearFieldTarget::NdefReadError, requestId);
                    return;
                }

                const QNdefMessage ndefMessage(ndefToQtNdefMessage(msg));
                emit cbNotifier->ndefMessageRead(ndefMessage, requestId);
            }];
        } else {
            QObject::connect(cbNotifier, &QNfcNdefNotifier::ndefMessageWritten,
                             this, &QNearFieldTargetPrivateImpl::messageWritten,
                             Qt::QueuedConnection);

            NSData *ndefData = op.message.toByteArray().toNSData(); // autoreleased.
            Q_ASSERT(ndefData);

            NFCNDEFMessage *ndefMessage = [NFCNDEFMessage ndefMessageWithData:ndefData]; // autoreleased.
            Q_ASSERT(ndefMessage);

            [ndefTag writeNDEF:ndefMessage completionHandler:^(NSError *err) {
                const std::unique_ptr<QNfcNdefNotifier> notifierGuard(cbNotifier);
                if (err) {
                    NSLog(@"Writing NDEF messaged ended with error: %@", err);
                    emit cbNotifier->tagError(QNearFieldTarget::NdefWriteError, requestId);
                    return;
                }

                emit cbNotifier->ndefMessageWritten(requestId);
            }];
        }
        guard.release(); // Owned by the completion handler now.
        return;
    }

    if (@available(iOS 13, *)) {
        if (queue.isEmpty())
            return;
        const auto request = queue.dequeue();
        requestInProgress = request.first;
        const auto tag = static_cast<id<NFCISO7816Tag>>(nfcTag.get());
        auto *apdu = [[[NFCISO7816APDU alloc] initWithData: request.second.toNSData()] autorelease];
        [tag sendCommandAPDU: apdu completionHandler: ^(NSData* responseData, uint8_t sw1, uint8_t sw2, NSError* error){
            QByteArray recvBuffer = QByteArray::fromNSData(responseData);
            recvBuffer += static_cast<char>(sw1);
            recvBuffer += static_cast<char>(sw2);
            const bool success = error == nil;
            responseProvider->provideResponse(request.first, success, recvBuffer);
        }];
    }
}

void  QNearFieldTargetPrivateImpl::onResponseReceived(QNearFieldTarget::RequestId requestId, bool success, QByteArray recvBuffer)
{
    if (requestInProgress != requestId)
        return;

    requestInProgress = QNearFieldTarget::RequestId();
    if (success) {
        setResponseForRequest(requestId, recvBuffer, true);
        onExecuteRequest();
    } else {
        reportError(QNearFieldTarget::CommandError, requestId);
        invalidate();
    }
}

void QNearFieldTargetPrivateImpl::messageRead(const QNdefMessage &message, QNearFieldTarget::RequestId requestId)
{
    hasNDEFMessage = message.size() != 0;

    setResponseForRequest(requestId, message.toByteArray(), true);
    requestInProgress = {}; // Invalidating, so we can execute the next one.
    onExecuteRequest();

    Q_EMIT ndefMessageRead(message);
}

void QNearFieldTargetPrivateImpl::messageWritten(QNearFieldTarget::RequestId requestId)
{
    requestInProgress = {}; // Invalidating, so we can execute the next one.
    onExecuteRequest();

    Q_EMIT requestCompleted(requestId);
}

QT_END_NAMESPACE