summaryrefslogtreecommitdiff
path: root/TelepathyQt/outgoing-file-transfer-channel.cpp
blob: 040455b60a6d897895830d880b3886403c0c1d5f (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
/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2009 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/OutgoingFileTransferChannel>

#include "TelepathyQt/_gen/outgoing-file-transfer-channel.moc.hpp"

#include "TelepathyQt/debug-internal.h"

#include <TelepathyQt/Connection>
#include <TelepathyQt/PendingFailure>
#include <TelepathyQt/PendingVariant>
#include <TelepathyQt/Types>
#include <TelepathyQt/types-internal.h>

#include <QIODevice>
#include <QTcpSocket>

namespace Tp
{

static const int FT_BLOCK_SIZE = 16 * 1024;

struct TP_QT_NO_EXPORT OutgoingFileTransferChannel::Private
{
    Private(OutgoingFileTransferChannel *parent);
    ~Private();

    // Public object
    OutgoingFileTransferChannel *parent;

    Client::ChannelTypeFileTransferInterface *fileTransferInterface;

    // Introspection
    QIODevice *input;
    QTcpSocket *socket;
    SocketAddressIPv4 addr;

    qint64 pos;
    bool weOpenedDevice;
};

OutgoingFileTransferChannel::Private::Private(OutgoingFileTransferChannel *parent)
    : parent(parent),
      fileTransferInterface(parent->interface<Client::ChannelTypeFileTransferInterface>()),
      input(nullptr),
      socket(nullptr),
      pos(0),
      weOpenedDevice(false)
{
}

OutgoingFileTransferChannel::Private::~Private()
{
}

/**
 * \class OutgoingFileTransferChannel
 * \ingroup clientchannel
 * \headerfile TelepathyQt/outgoing-file-transfer-channel.h <TelepathyQt/OutgoingFileTransferChannel>
 *
 * \brief The OutgoingFileTransferChannel class represents a Telepathy channel
 * of type FileTransfer for outgoing file transfers.
 *
 * For more details, please refer to \telepathy_spec.
 *
 * See \ref async_model, \ref shared_ptr
 */

/**
 * Feature representing the core that needs to become ready to make the
 * OutgoingFileTransferChannel object usable.
 *
 * This is currently the same as FileTransferChannel::FeatureCore, but may change to include more.
 *
 * When calling isReady(), becomeReady(), this feature is implicitly added
 * to the requested features.
 */
const Feature OutgoingFileTransferChannel::FeatureCore =
    Feature(QLatin1String(FileTransferChannel::staticMetaObject.className()), 0); // FT::FeatureCore

/**
 * Create a new OutgoingFileTransferChannel object.
 *
 * \param connection Connection owning this channel, and specifying the
 *                   service.
 * \param objectPath The channel object path.
 * \param immutableProperties The channel immutable properties.
 * \return An OutgoingFileTransferChannelPtr object pointing to the newly created
 *         OutgoingFileTransferChannel object.
 */
OutgoingFileTransferChannelPtr OutgoingFileTransferChannel::create(const ConnectionPtr &connection,
        const QString &objectPath, const QVariantMap &immutableProperties)
{
    return OutgoingFileTransferChannelPtr(new OutgoingFileTransferChannel(
                connection, objectPath, immutableProperties,
                OutgoingFileTransferChannel::FeatureCore));
}

/**
 * Construct a new OutgoingFileTransferChannel object.
 *
 * \param connection Connection owning this channel, and specifying the
 *                   service.
 * \param objectPath The channel object path.
 * \param immutableProperties The channel immutable properties.
 * \param coreFeature The core feature of the channel type, if any. The corresponding introspectable should
 *                    depend on OutgoingFileTransferChannel::FeatureCore.
 */
OutgoingFileTransferChannel::OutgoingFileTransferChannel(
        const ConnectionPtr &connection,
        const QString &objectPath,
        const QVariantMap &immutableProperties,
        const Feature &coreFeature)
    : FileTransferChannel(connection, objectPath, immutableProperties, coreFeature),
      mPriv(new Private(this))
{
}

/**
 * Class destructor.
 */
OutgoingFileTransferChannel::~OutgoingFileTransferChannel()
{
    delete mPriv;
}

/**
 * Provide the file for an outgoing file transfer which has been offered.
 *
 * The state will change to #FileTransferStateOpen as soon as the transfer
 * starts.
 * The given input device should not be destroyed until the state()
 * changes to #FileTransferStateCompleted or #FileTransferStateCancelled.
 * If input is a sequential device QIODevice::isSequential(), it should be
 * closed when no more data is available, so that it's known when to stop reading.
 *
 * Only the primary handler of a file transfer channel may call this method.
 *
 * This method requires FileTransferChannel::FeatureCore to be ready.
 *
 * \param input A QIODevice object where the data will be read from.
 * \return A PendingOperation object which will emit PendingOperation::finished
 *         when the call has finished.
 * \sa stateChanged(), state(), stateReason()
 */
PendingOperation *OutgoingFileTransferChannel::provideFile(QIODevice *input)
{
    if (!isReady(FileTransferChannel::FeatureCore)) {
        warning() << "FileTransferChannel::FeatureCore must be ready before "
            "calling provideFile";
        return new PendingFailure(TP_QT_ERROR_NOT_AVAILABLE,
                QLatin1String("Channel not ready"),
                OutgoingFileTransferChannelPtr(this));
    }

    // let's fail here direclty as we may only have one device to handle
    if (mPriv->input) {
        warning() << "File transfer can only be started once in the same "
            "channel";
        return new PendingFailure(TP_QT_ERROR_NOT_AVAILABLE,
                QLatin1String("File transfer can only be started once in the same channel"),
                OutgoingFileTransferChannelPtr(this));
    }

    if (!input->isOpen()) {
        if (input->open(QIODevice::ReadOnly)) {
            mPriv->weOpenedDevice = true;
        }
    }

    if (!input->isReadable()) {
        mPriv->weOpenedDevice = false;
        warning() << "Unable to open IO device for reading";
        return new PendingFailure(TP_QT_ERROR_PERMISSION_DENIED,
                QLatin1String("Unable to open IO device for reading"),
                OutgoingFileTransferChannelPtr(this));
    }

    mPriv->input = input;
    connect(input,
            SIGNAL(aboutToClose()),
            SLOT(onInputAboutToClose()));

    PendingVariant *pv = new PendingVariant(
            mPriv->fileTransferInterface->ProvideFile(
                SocketAddressTypeIPv4,
                SocketAccessControlLocalhost,
                QDBusVariant(QVariant(QString()))),
            OutgoingFileTransferChannelPtr(this));
    connect(pv,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onProvideFileFinished(Tp::PendingOperation*)));
    return pv;
}

void OutgoingFileTransferChannel::onProvideFileFinished(PendingOperation *op)
{
    if (op->isError()) {
        warning() << "Error providing file transfer " <<
            op->errorName() << ":" << op->errorMessage();
        invalidate(op->errorName(), op->errorMessage());
        return;
    }

    PendingVariant *pv = qobject_cast<PendingVariant *>(op);
    mPriv->addr = qdbus_cast<SocketAddressIPv4>(pv->result());
    debug().nospace() << "Got address " << mPriv->addr.address <<
        ":" << mPriv->addr.port;

    if (state() == FileTransferStateOpen) {
        connectToHost();
    }
}

void OutgoingFileTransferChannel::connectToHost()
{
    if (isConnected() || mPriv->addr.address.isNull()) {
        return;
    }

    mPriv->pos = initialOffset();

    mPriv->socket = new QTcpSocket(this);

    connect(mPriv->socket, SIGNAL(connected()),
            SLOT(onSocketConnected()));
    connect(mPriv->socket, SIGNAL(disconnected()),
            SLOT(onSocketDisconnected()));
    connect(mPriv->socket, SIGNAL(error(QAbstractSocket::SocketError)),
            SLOT(onSocketError(QAbstractSocket::SocketError)));
    connect(mPriv->socket, SIGNAL(bytesWritten(qint64)),
            SLOT(doTransfer()));

    debug().nospace() << "Connecting to host " <<
        mPriv->addr.address << ":" << mPriv->addr.port << "...";
    mPriv->socket->connectToHost(mPriv->addr.address, mPriv->addr.port);
}

void OutgoingFileTransferChannel::onSocketConnected()
{
    debug() << "Connected to host";
    setConnected();

    connect(mPriv->input, SIGNAL(readyRead()),
            SLOT(doTransfer()));

    // for non sequential devices, let's seek to the initialOffset
    if (mPriv->weOpenedDevice && !mPriv->input->isSequential()) {
        mPriv->input->seek(initialOffset());
    }

    debug() << "Starting transfer...";
    doTransfer();
}

void OutgoingFileTransferChannel::onSocketDisconnected()
{
    debug() << "Disconnected from host";
    setFinished();
}

void OutgoingFileTransferChannel::onSocketError(QAbstractSocket::SocketError error)
{
    debug() << "Socket error" << error;
    setFinished();
}

void OutgoingFileTransferChannel::onInputAboutToClose()
{
    debug() << "Input closed";

    // read all remaining data from input device and write to output device
    if (isConnected()) {
        QByteArray data;
        data = mPriv->input->readAll();
        mPriv->socket->write(data); // never fails
    }

    setFinished();
}

void OutgoingFileTransferChannel::doTransfer()
{
    // read FT_BLOCK_SIZE each time, as input can be a QFile, we don't want to
    // block reading the whole file
    char buffer[FT_BLOCK_SIZE];
    char *p = buffer;

    memset(buffer, 0, sizeof(buffer));
    qint64 len = mPriv->input->read(buffer, sizeof(buffer));

    bool scheduleTransfer = false;
    if (((qulonglong) mPriv->pos < initialOffset()) && (len > 0)) {
        qint64 skip = (qint64) qMin(initialOffset() - mPriv->pos,
                (qulonglong) len);

        mPriv->pos += skip;
        debug() << "skipping" << skip << "bytes";
        if (skip == len) {
            // nothing to write, all data read was skipped
            // schedule a transfer, as readyRead may never be called and
            // bytesWriiten will not
            scheduleTransfer = true;
            goto end;
        }

        p += skip;
        len -= skip;
    }

    if (len > 0) {
        mPriv->socket->write(p, len); // never fails
    }

end:
    if (len == -1 || (!mPriv->input->isSequential() && mPriv->input->atEnd())) {
        // error or EOF
        setFinished();
        return;
    }

    mPriv->pos += len;

    if (scheduleTransfer) {
        QMetaObject::invokeMethod(this, SLOT(doTransfer()),
                Qt::QueuedConnection);
    }
}

void OutgoingFileTransferChannel::setFinished()
{
    if (isFinished()) {
        // it shouldn't happen but let's make sure
        return;
    }

    if (mPriv->socket) {
        disconnect(mPriv->socket, SIGNAL(connected()),
                   this, SLOT(onSocketConnected()));
        disconnect(mPriv->socket, SIGNAL(disconnected()),
                   this, SLOT(onSocketDisconnected()));
        disconnect(mPriv->socket, SIGNAL(error(QAbstractSocket::SocketError)),
                   this, SLOT(onSocketError(QAbstractSocket::SocketError)));
        disconnect(mPriv->socket, SIGNAL(bytesWritten(qint64)),
                   this, SLOT(doTransfer()));
        mPriv->socket->close();
    }

    if (mPriv->input) {
        disconnect(mPriv->input, SIGNAL(aboutToClose()),
                   this, SLOT(onInputAboutToClose()));
        disconnect(mPriv->input, SIGNAL(readyRead()),
                   this, SLOT(doTransfer()));

        if (mPriv->weOpenedDevice) {
            mPriv->input->close();
        }
    }

    FileTransferChannel::setFinished();
}

} // Tp