Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Файл примера peerwireclient.cpp
network/torrent/peerwireclient.cpp

 /****************************************************************************
 **
 ** Copyright (C) 2004-2008 Trolltech ASA. All rights reserved.
 **
 ** This file is part of the example classes of the Qt Toolkit.
 **
 ** This file may be used under the terms of the GNU General Public
 ** License versions 2.0 or 3.0 as published by the Free Software
 ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
 ** included in the packaging of this file.  Alternatively you may (at
 ** your option) use any later version of the GNU General Public
 ** License if such license has been publicly approved by Trolltech ASA
 ** (or its successors, if any) and the KDE Free Qt Foundation. In
 ** addition, as a special exception, Trolltech gives you certain
 ** additional rights. These rights are described in the Trolltech GPL
 ** Exception version 1.2, which can be found at
 ** http://www.trolltech.com/products/qt/gplexception/ and in the file
 ** GPL_EXCEPTION.txt in this package.
 **
 ** Please review the following information to ensure GNU General
 ** Public Licensing requirements will be met:
 ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If
 ** you are unsure which license is appropriate for your use, please
 ** review the following information:
 ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
 ** or contact the sales department at sales@trolltech.com.
 **
 ** In addition, as a special exception, Trolltech, as the sole
 ** copyright holder for Qt Designer, grants users of the Qt/Eclipse
 ** Integration plug-in the right for the Qt/Eclipse Integration to
 ** link to functionality provided by Qt Designer and its related
 ** libraries.
 **
 ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
 ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
 ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly
 ** granted herein.
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 **
 ****************************************************************************/

 #include "peerwireclient.h"

 #include <QHostAddress>
 #include <QTimerEvent>

 static const int PendingRequestTimeout = 60 * 1000;
 static const int ClientTimeout = 120 * 1000;
 static const int ConnectTimeout = 60 * 1000;
 static const int KeepAliveInterval = 30 * 1000;
 static const int RateControlTimerDelay = 2000;
 static const int MinimalHeaderSize = 48;
 static const int FullHeaderSize = 68;
 static const char ProtocolId[] = "BitTorrent protocol";
 static const char ProtocolIdSize = 19;

 // Считывает 32-х битные беззнаковые целые из data в сетевом порядке.
 static inline quint32 fromNetworkData(const char *data)
 {
     const unsigned char *udata = (const unsigned char *)data;
     return (quint32(udata[0]) << 24)
         | (quint32(udata[1]) << 16)
         | (quint32(udata[2]) << 8)
         | (quint32(udata[3]));
 }

 // Записывает 32-х битные беззнаковые целые из num в data в сетевом порядке.
 static inline void toNetworkData(quint32 num, char *data)
 {
     unsigned char *udata = (unsigned char *)data;
     udata[3] = (num & 0xff);
     udata[2] = (num & 0xff00) >> 8;
     udata[1] = (num & 0xff0000) >> 16;
     udata[0] = (num & 0xff000000) >> 24;
 }

 // Конструирует неподключённый клиент PeerWire и запускает таймер соединения.
 PeerWireClient::PeerWireClient(const QByteArray &peerId, QObject *parent)
     : QTcpSocket(parent), pendingBlockSizes(0),
       pwState(ChokingPeer | ChokedByPeer), receivedHandShake(false), gotPeerId(false),
       sentHandShake(false), nextPacketLength(-1), pendingRequestTimer(0), invalidateTimeout(false),
       keepAliveTimer(0), torrentPeer(0)
 {
     memset(uploadSpeedData, 0, sizeof(uploadSpeedData));
     memset(downloadSpeedData, 0, sizeof(downloadSpeedData));

     transferSpeedTimer = startTimer(RateControlTimerDelay);
     timeoutTimer = startTimer(ConnectTimeout);
     peerIdString = peerId;

     connect(this, SIGNAL(readyRead()), this, SIGNAL(readyToTransfer()));
     connect(this, SIGNAL(connected()), this, SIGNAL(readyToTransfer()));

     connect(&socket, SIGNAL(connected()),
             this, SIGNAL(connected()));
     connect(&socket, SIGNAL(readyRead()),
             this, SIGNAL(readyRead()));
     connect(&socket, SIGNAL(disconnected()),
             this, SIGNAL(disconnected()));
     connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SIGNAL(error(QAbstractSocket::SocketError)));
     connect(&socket, SIGNAL(bytesWritten(qint64)),
             this, SIGNAL(bytesWritten(qint64)));
     connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
             this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));

 }

 // Регистрирует ID пира и сумму SHA1 торрента и инициализирует
 // приветствие.
 void PeerWireClient::initialize(const QByteArray &infoHash, int pieceCount)
 {
     this->infoHash = infoHash;
     peerPieces.resize(pieceCount);
     if (!sentHandShake)
         sendHandShake();
 }

 void PeerWireClient::setPeer(TorrentPeer *peer)
 {
     torrentPeer = peer;
 }

 TorrentPeer *PeerWireClient::peer() const
 {
     return torrentPeer;
 }

 QBitArray PeerWireClient::availablePieces() const
 {
     return peerPieces;
 }

 QList<TorrentBlock> PeerWireClient::incomingBlocks() const
 {
     return incoming;
 }

 // Посылает сообщение "блокировки" прося пира перестать запрашивать блоки.
 void PeerWireClient::chokePeer()
 {
     const char message[] = {0, 0, 0, 1, 0};
     write(message, sizeof(message));
     pwState |= ChokingPeer;

     // После получения сообщения блокировки пир подразумевает все
     // планируемые запросы утерянными.
     pendingBlocks.clear();
     pendingBlockSizes = 0;
 }

 // Посылает сообщение "разблокировки" позволяя пиру начать/продолжить
 // запрашивать блоки.
 void PeerWireClient::unchokePeer()
 {
     const char message[] = {0, 0, 0, 1, 1};
     write(message, sizeof(message));
     pwState &= ~ChokingPeer;

     if (pendingRequestTimer)
         killTimer(pendingRequestTimer);
 }

 // Посылает сообщение "keep-alive" чтобы предотвратить закрытие
 // соединения пиром в отсутствие активности
 void PeerWireClient::sendKeepAlive()
 {
     const char message[] = {0, 0, 0, 0};
     write(message, sizeof(message));
 }

 // Посылает сообщение "заинтересован", информируя пира что у него есть
 // куски которые мы хотим скачать.
 void PeerWireClient::sendInterested()
 {
     const char message[] = {0, 0, 0, 1, 2};
     write(message, sizeof(message));
     pwState |= InterestedInPeer;

     // После сообщения пиру что мы заинтересованы мы ожидаем получить
     // разблокирование в течении определённого промежутка времени; в противном случае мы бросаем
     // соединение.
     if (pendingRequestTimer)
         killTimer(pendingRequestTimer);
     pendingRequestTimer = startTimer(PendingRequestTimeout);
 }

 // Посылаем сообщение "не заинтересован", информируя пира что у него
 // нет кусков которые мы хотели бы скачать.
 void PeerWireClient::sendNotInterested()
 {
     const char message[] = {0, 0, 0, 1, 3};
     write(message, sizeof(message));
     pwState &= ~InterestedInPeer;
 }

 // Посылаем кусок уведомления / сообщение "есть", информируя пира
 // что у нас есть только что скачанный новый кусок.
 void PeerWireClient::sendPieceNotification(int piece)
 {
     if (!sentHandShake)
         sendHandShake();

     char message[] = {0, 0, 0, 5, 4, 0, 0, 0, 0};
     toNetworkData(piece, &message[5]);
     write(message, sizeof(message));
 }

 // Посылаем полный список кусков которые мы скачали.
 void PeerWireClient::sendPieceList(const QBitArray &bitField)
 {
     // Сообщение битовой маски может быть отослано только сразу же после
     // завершения последовательности приветствий и перед любым
     // другим сообщением.
     if (!sentHandShake)
         sendHandShake();

     // Не посылаем битовую маску если она полностью состоит из нулей.
     if (bitField.count(true) == 0)
         return;

     int bitFieldSize = bitField.size();
     int size = (bitFieldSize + 7) / 8;
     QByteArray bits(size, '\0');
     for (int i = 0; i < bitFieldSize; ++i) {
         if (bitField.testBit(i)) {
             quint32 byte = quint32(i) / 8;
             quint32 bit = quint32(i) % 8;
             bits[byte] = uchar(bits.at(byte)) | (1 << (7 - bit));
         }
     }

     char message[] = {0, 0, 0, 1, 5};
     toNetworkData(bits.size() + 1, &message[0]);
     write(message, sizeof(message));
     write(bits);
 }

 // Посылаем запрос блока.
 void PeerWireClient::requestBlock(int piece, int offset, int length)
 {
     char message[] = {0, 0, 0, 1, 6};
     toNetworkData(13, &message[0]);
     write(message, sizeof(message));

     char numbers[4 * 3];
     toNetworkData(piece, &numbers[0]);
     toNetworkData(offset, &numbers[4]);
     toNetworkData(length, &numbers[8]);
     write(numbers, sizeof(numbers));

     incoming << TorrentBlock(piece, offset, length);

     // После запрашивания блока мы ожидаем что блок будет послан
     // другим пиром в течении определённого числа секунд. В противном случае мы
     // бросаем соединение.
     if (pendingRequestTimer)
         killTimer(pendingRequestTimer);
     pendingRequestTimer = startTimer(PendingRequestTimeout);
 }

 // Отменяем запрос блока.
 void PeerWireClient::cancelRequest(int piece, int offset, int length)
 {
     char message[] = {0, 0, 0, 1, 8};
     toNetworkData(13, &message[0]);
     write(message, sizeof(message));

     char numbers[4 * 3];
     toNetworkData(piece, &numbers[0]);
     toNetworkData(offset, &numbers[4]);
     toNetworkData(length, &numbers[8]);
     write(numbers, sizeof(numbers));

     incoming.removeAll(TorrentBlock(piece, offset, length));
 }

 // Посылаем блок пиру.
 void PeerWireClient::sendBlock(int piece, int offset, const QByteArray &data)
 {
     QByteArray block;

     char message[] = {0, 0, 0, 1, 7};
     toNetworkData(9 + data.size(), &message[0]);
     block += QByteArray(message, sizeof(message));

     char numbers[4 * 2];
     toNetworkData(piece, &numbers[0]);
     toNetworkData(offset, &numbers[4]);
     block += QByteArray(numbers, sizeof(numbers));
     block += data;

     BlockInfo blockInfo;
     blockInfo.pieceIndex = piece;
     blockInfo.offset = offset;
     blockInfo.length = data.size();
     blockInfo.block = block;

     pendingBlocks << blockInfo;
     pendingBlockSizes += block.size();

     if (pendingBlockSizes > 32 * 16384) {
         chokePeer();
         unchokePeer();
         return;
     }
     emit readyToTransfer();
 }

 // Пытаемся записать 'bytes' байтов в сокет из буфера.
 // Это используется RateController, который точно контролирует сколько
 // каждый клиент может записать.
 qint64 PeerWireClient::writeToSocket(qint64 bytes)
 {
     qint64 totalWritten = 0;
     do {
         if (outgoingBuffer.isEmpty() && !pendingBlocks.isEmpty()) {
             BlockInfo block = pendingBlocks.takeFirst();
             pendingBlockSizes -= block.length;
             outgoingBuffer += block.block;
         }
         qint64 written = socket.write(outgoingBuffer.constData(),
                                       qMin<qint64>(bytes - totalWritten, outgoingBuffer.size()));
         if (written <= 0)
             return totalWritten ? totalWritten : written;

         totalWritten += written;
         uploadSpeedData[0] += written;
         outgoingBuffer.remove(0, written);
     } while (totalWritten < bytes && (!outgoingBuffer.isEmpty() || !pendingBlocks.isEmpty()));

     return totalWritten;
 }

 // Пытаемся прочитать 'bytes' байтов из сокета.
 qint64 PeerWireClient::readFromSocket(qint64 bytes)
 {
     char buffer[1024];
     qint64 totalRead = 0;
     do {
         qint64 bytesRead = socket.read(buffer, qMin<qint64>(sizeof(buffer), bytes - totalRead));
         if (bytesRead <= 0)
             break;
         qint64 oldSize = incomingBuffer.size();
         incomingBuffer.resize(oldSize + bytesRead);
         memcpy(incomingBuffer.data() + oldSize, buffer, bytesRead);

         totalRead += bytesRead;
     } while (totalRead < bytes);

     if (totalRead > 0) {
         downloadSpeedData[0] += totalRead;
         emit bytesReceived(totalRead);
         processIncomingData();
     }
     return totalRead;
 }

 // Возвращаем среднее число байтов в секунду которые скачивает
 // этот клиент.
 qint64 PeerWireClient::downloadSpeed() const
 {
     qint64 sum = 0;
     for (unsigned int i = 0; i < sizeof(downloadSpeedData) / sizeof(qint64); ++i)
         sum += downloadSpeedData[i];
     return sum / (8 * 2);
 }

 // Возвращает среднее число байтов в секунду которые отдаёт
 // этот клиент.
 qint64 PeerWireClient::uploadSpeed() const
 {
     qint64 sum = 0;
     for (unsigned int i = 0; i < sizeof(uploadSpeedData) / sizeof(qint64); ++i)
         sum += uploadSpeedData[i];
     return sum / (8 * 2);
 }

 void PeerWireClient::setReadBufferSize(int size)
 {
     socket.setReadBufferSize(size);
 }

 bool PeerWireClient::canTransferMore() const
 {
     return bytesAvailable() > 0 || socket.bytesAvailable() > 0
         || !outgoingBuffer.isEmpty() || !pendingBlocks.isEmpty();
 }

 void PeerWireClient::connectToHostImplementation(const QString &hostName,
                                                  quint16 port, OpenMode openMode)

 {
     setOpenMode(openMode);
     socket.connectToHost(hostName, port, openMode);
 }

 void PeerWireClient::diconnectFromHostImplementation()
 {
     socket.disconnectFromHost();
 }

 void PeerWireClient::timerEvent(QTimerEvent *event)
 {
     if (event->timerId() == transferSpeedTimer) {
         // Сменяем записи отдачи/скачивания.
         for (int i = 6; i >= 0; --i) {
             uploadSpeedData[i + 1] = uploadSpeedData[i];
             downloadSpeedData[i + 1] = downloadSpeedData[i];
         }
         uploadSpeedData[0] = 0;
         downloadSpeedData[0] = 0;
     } else if (event->timerId() == timeoutTimer) {
         // Отключаемся если вышло время; в противном случае таймаут
         // перезапускается.
         if (invalidateTimeout) {
             invalidateTimeout = false;
         } else {
             abort();
         }
     } else if (event->timerId() == pendingRequestTimer) {
         abort();
     } else if (event->timerId() == keepAliveTimer) {
         sendKeepAlive();
     }
     QTcpSocket::timerEvent(event);
 }

 // Посылаем приветствие пиру.
 void PeerWireClient::sendHandShake()
 {
     sentHandShake = true;

     // Перезапускаем таймаут
     if (timeoutTimer)
         killTimer(timeoutTimer);
     timeoutTimer = startTimer(ClientTimeout);

     // Записываем 68 байтов приветствия PeerWire.
     write(&ProtocolIdSize, 1);
     write(ProtocolId, ProtocolIdSize);
     write(QByteArray(8, '\0'));
     write(infoHash);
     write(peerIdString);
 }

 void PeerWireClient::processIncomingData()
 {
     invalidateTimeout = true;
     if (!receivedHandShake) {
         // Проверяем что мы получили достаточно данных
         if (bytesAvailable() < MinimalHeaderSize)
             return;

         // Санитарная чистка ID протокола
         QByteArray id = read(ProtocolIdSize + 1);
         if (id.at(0) != ProtocolIdSize || !id.mid(1).startsWith(ProtocolId)) {
             abort();
             return;
         }

         // Отменяем 8 зарезеврированных байтов, затем читаем хэш информации и ID пира
         (void) read(8);

         // читаем infoHash
         QByteArray peerInfoHash = read(20);
         if (!infoHash.isEmpty() && peerInfoHash != infoHash) {
             abort();
             return;
         }

         emit infoHashReceived(peerInfoHash);
         if (infoHash.isEmpty()) {
             abort();
             return;
         }

         // Посылаем приветствие
         if (!sentHandShake)
             sendHandShake();
         receivedHandShake = true;
     }

     // Обрабатываем отложенное прибытие ID пира
     if (!gotPeerId) {
         if (bytesAvailable() < 20)
             return;
         gotPeerId = true;
         if (read(20) == peerIdString) {
             // Мы подключены к себе
             abort();
             return;
         }
     }

     // Инициализируем таймер поддержки соединения
     if (!keepAliveTimer)
         keepAliveTimer = startTimer(KeepAliveInterval);

     do {
         // Выясняем длину пакета
         if (nextPacketLength == -1) {
             if (bytesAvailable() < 4)
                 return;

             char tmp[4];
             read(tmp, sizeof(tmp));
             nextPacketLength = fromNetworkData(tmp);

             if (nextPacketLength < 0 || nextPacketLength > 200000) {
                 // Предупреждаем DoS
                 abort();
                 return;
             }
         }

         // Поддержка соединения
         if (nextPacketLength == 0) {
             nextPacketLength = -1;
             continue;
         }

         // Ждём с парсингом пока весь пакет не будет получен
         if (bytesAvailable() < nextPacketLength)
             return;

         // Читаем пакет
         QByteArray packet = read(nextPacketLength);
         if (packet.size() != nextPacketLength) {
             abort();
             return;
         }

         switch (packet.at(0)) {
         case ChokePacket:
             // Нас заглушили.
             pwState |= ChokedByPeer;
             incoming.clear();
             if (pendingRequestTimer)
                 killTimer(pendingRequestTimer);
             emit choked();
             break;
         case UnchokePacket:
             // Нас разглушили.
             pwState &= ~ChokedByPeer;
             emit unchoked();
             break;
         case InterestedPacket:
             // Пир заинтересован в скачивании.
             pwState |= PeerIsInterested;
             emit interested();
             break;
         case NotInterestedPacket:
             // Пир не заинтересован в скачивании.
             pwState &= ~PeerIsInterested;
             emit notInterested();
             break;
         case HavePacket: {
             // У пира есть новый доступный кусок.
             quint32 index = fromNetworkData(&packet.data()[1]);
             if (index < quint32(peerPieces.size())) {
                 // Принимаем индексы только допустимого диапазона.
                 peerPieces.setBit(int(index));
             }
             emit piecesAvailable(availablePieces());
             break;
         }
         case BitFieldPacket:
             // У пира доступен следующий кусок.
             for (int i = 1; i < packet.size(); ++i) {
                 for (int bit = 0; bit < 8; ++bit) {
                     if (packet.at(i) & (1 << (7 - bit))) {
                         int bitIndex = int(((i - 1) * 8) + bit);
                         if (bitIndex >= 0 && bitIndex < peerPieces.size()) {
                             // Неожиданно сломанный клиент заявляет что у  него есть
                             // кусок чей индекс вне допустимого предела.
                             // Наиболее распространённая ошибка когда индекс равено размеру
                             // блока.
                             peerPieces.setBit(bitIndex);
                         }
                     }
                 }
             }
             emit piecesAvailable(availablePieces());
             break;
         case RequestPacket: {
             // Пир запрашивает блок.
             quint32 index = fromNetworkData(&packet.data()[1]);
             quint32 begin = fromNetworkData(&packet.data()[5]);
             quint32 length = fromNetworkData(&packet.data()[9]);
             emit blockRequested(int(index), int(begin), int(length));
             break;
         }
         case PiecePacket: {
             int index = int(fromNetworkData(&packet.data()[1]));
             int begin = int(fromNetworkData(&packet.data()[5]));

             incoming.removeAll(TorrentBlock(index, begin, packet.size() - 9));

             // Пир посылает блок.
             emit blockReceived(index, begin, packet.mid(9));

             // Убиваем таймер планируемого блока.
             if (pendingRequestTimer) {
                 killTimer(pendingRequestTimer);
                 pendingRequestTimer = 0;
             }
             break;
         }
         case CancelPacket: {
             // Пир отменяет запрос блока.
             quint32 index = fromNetworkData(&packet.data()[1]);
             quint32 begin = fromNetworkData(&packet.data()[5]);
             quint32 length = fromNetworkData(&packet.data()[9]);
             for (int i = 0; i < pendingBlocks.size(); ++i) {
                 const BlockInfo &blockInfo = pendingBlocks.at(i);
                 if (blockInfo.pieceIndex == int(index)
                     && blockInfo.offset == int(begin)
                     && blockInfo.length == int(length)) {
                     pendingBlocks.removeAt(i);
                     break;
                 }
             }
             break;
         }
         default:
             // Неподдерживаемый тип пакета; просто игнорируем его.
             break;
         }
         nextPacketLength = -1;
     } while (bytesAvailable() > 0);
 }

 void PeerWireClient::socketStateChanged(QAbstractSocket::SocketState state)
 {
     setLocalAddress(socket.localAddress());
     setLocalPort(socket.localPort());
     setPeerName(socket.peerName());
     setPeerAddress(socket.peerAddress());
     setPeerPort(socket.peerPort());
     setSocketState(state);
 }

 qint64 PeerWireClient::readData(char *data, qint64 size)
 {
     int n = qMin<int>(size, incomingBuffer.size());
     memcpy(data, incomingBuffer.constData(), n);
     incomingBuffer.remove(0, n);
     return n;
 }

 qint64 PeerWireClient::readLineData(char *data, qint64 maxlen)
 {
     return QIODevice::readLineData(data, maxlen);
 }

 qint64 PeerWireClient::writeData(const char *data, qint64 size)
 {
     int oldSize = outgoingBuffer.size();
     outgoingBuffer.resize(oldSize + size);
     memcpy(outgoingBuffer.data() + oldSize, data, size);
     emit readyToTransfer();
     return size;
 }


Copyright © 2008 Trolltech Торговые марки
Qt 4.3.5