aria2/src/PeerConnection.cc

279 lines
8.3 KiB
C++
Raw Normal View History

2006-03-21 14:12:51 +00:00
/* <!-- copyright */
/*
* aria2 - The high speed download utility
2006-03-21 14:12:51 +00:00
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
2006-03-21 14:12:51 +00:00
*/
/* copyright --> */
#include "PeerConnection.h"
#include <cstring>
#include <cassert>
#include <algorithm>
2006-03-21 14:12:51 +00:00
#include "message.h"
#include "DlAbortEx.h"
To add LogFactory which creates singleton logger: * src/LogFactory.h: New class. * src/LogFactory.cc: New class. * src/Command.h (logger): New variable. (Constructor): Use LogFactory. * src/AbstractCommand.cc: Use Command::logger * src/PeerConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/SegmentSplitter.h : Made logger protected. * src/SegmentSplitter.cc (Constructor): Use LogFactory. * src/SegmentMan.cc (Constructor): Use LogFactory. * src/DownloadEngine.h : Made logger protected. * src/DownloadEngine.cc (Constructor): Use LogFactory. * src/PeerInteractionCommand.cc : Use Command::logger. * src/HttpResponseCommand.cc : Use Command::logger. * src/SegmentMan.h : Made logger private. * src/TorrentMan.h : Made logger private. * src/TorrentMan.cc : Use LogFactory. * src/FtpNegotiateCommand.cc : Use Command::logger. * src/HttpConnection.h (Constructor): Deleted the argument logger. * src/HttpConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/FtpConnection.h (Constructor): Deleted the argument logger. * src/FtpConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/DownloadCommand.cc : Use Command::logger. * src/PeerAbstractCommand.cc : Use Command::logger. * src/PeerListenCommand.cc : Use Command::logger. * src/PeerInitiateConnectionCommand.cc : Use Command::logger. * src/HttpInitiateConnectionCommand.cc : Use Command::logger. * src/FtpInitiateConnectionCommand.cc : Use Command::logger. * src/TrackerWatcherCommand.cc : Use Command::logger. * src/TrackerUpdateCommand.cc : Use Command::logger. * src/TrackerDownloadCommand.cc : Use Command::logger. * src/RequestSlotMan.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/SendMessageQueue.h (Constructor): Deleted the argument logger. * src/SendMessageQueue.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/main.cc (main): Use LogFactory. * src/DiskAdaptor.h (logger): New variable. * src/DiskAdaptor.cc (Constructor): Use LogFactory. * src/CopyDiskAdaptor.cc (fixFilename): Added a log message.
2006-04-17 16:17:20 +00:00
#include "LogFactory.h"
#include "Logger.h"
2006-12-24 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Rewritten a portion of bittorrent implementation: * src/BtMessageValidator.h: New class. * src/BtBitfieldMessageValidator.h: New class. * src/BtHandshakeMessageValidator.h: New class. * src/BtRequestMessageValidator.h: New class. * src/BtSuggestPieceMessageValidator.h: New class. * src/BtAllowedFastMessageValidator.h: New class. * src/BtRejectMessageValidator.h: New class. * src/BtCancelMessageValidator.h: New class. * src/BtPieceMessageValidator.h: New class. * src/BtHaveMessageValidator.h: New class. * src/BtEventListener.h: New class. * src/AbstractBtEventListener.h: New class. * src/BtEvent.h: New class. * src/BtChokingEvent.h: New class. * src/BtChokedEvent.h: New class. * src/BtCancelSendingPieceEvent.h: New class. * src/BtAbortOutstandingRequestEvent.h: New class. * src/Randomizer.h: New class. * src/SimpleRandomizer.h: New class. * src/BtMessage.h: New class. * src/AbstractBtMessage.h: New class. * src/SimpleBtMessage.h: New class. * src/BtHaveMessage.h: New class. * src/BtInterestedMessage.h: New class. * src/BtAllowedFastMessage.h: New class. * src/BtUnchokeMessage.h: New class. * src/BtCancelMessage.h: New class. * src/BtNotInterestedMessage.h: New class. * src/BtChokeMessage.h: New class. * src/BtHaveNoneMessage.h: New class. * src/BtHandshakeMessage.h: New class. * src/BtSuggestPieceMessage.h: New class. * src/BtHaveMessage.h: New class. * src/BtPieceMessage.h: New class. * src/BtHaveAllMessage.h: New class. * src/BtKeepAliveMessage.h: New class. * src/BtPortMessage.h: New class. * src/BtRejectMessage.h: New class. * src/BtBitfieldMessage.h: New class. * src/BtRequestMessage.h: New class. * src/DefaultBtRequestFactory.h: New class. * src/DefaultBtMessageReceiver.h: New class. * src/BtInteractive.h: New class. * src/BtMessageDispatcher.h: New class. * src/DefaultBtMessageDispatcher.h: New class. * src/DefaultBtInteractive.h: New class. * src/BitfieldManFactory.h: New class. * src/HandleRegistry.h: New class. * src/BtMessageFactory.h: New class. * src/BtMessageReceiver.h: New class. * src/DefaultBtMessageFactory.h: New class. * src/PeerObject.h: New class. * src/BtRequestFactory.h: New class.
2006-12-24 06:25:21 +00:00
#include "BtHandshakeMessage.h"
2012-09-28 14:27:46 +00:00
#include "SocketCore.h"
#include "a2netcompat.h"
#include "ARC4Encryptor.h"
#include "fmt.h"
#include "util.h"
#include "Peer.h"
namespace aria2 {
2006-03-21 14:12:51 +00:00
namespace {
enum {
// Before reading first byte of message length
BT_MSG_PREV_READ_LENGTH,
// Reading 4 bytes message length
BT_MSG_READ_LENGTH,
// Reading message payload following message length
BT_MSG_READ_PAYLOAD
};
} // namespace
PeerConnection::PeerConnection
2012-09-28 14:27:46 +00:00
(cuid_t cuid, const SharedHandle<Peer>& peer, const SharedHandle<SocketCore>& socket)
: cuid_(cuid),
peer_(peer),
socket_(socket),
msgState_(BT_MSG_PREV_READ_LENGTH),
bufferCapacity_(MAX_BUFFER_CAPACITY),
resbuf_(new unsigned char[bufferCapacity_]),
resbufLength_(0),
currentPayloadLength_(0),
resbufOffset_(0),
msgOffset_(0),
socketBuffer_(socket),
encryptionEnabled_(false),
prevPeek_(false)
{}
2006-03-21 14:12:51 +00:00
PeerConnection::~PeerConnection()
{
delete [] resbuf_;
}
2006-03-21 14:12:51 +00:00
void PeerConnection::pushBytes(unsigned char* data, size_t len)
{
if(encryptionEnabled_) {
encryptor_->encrypt(len, data, data);
}
socketBuffer_.pushBytes(data, len);
}
bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength)
{
while(1) {
bool done = false;
size_t i;
for(i = resbufOffset_; i < resbufLength_ && !done; ++i) {
unsigned char c = resbuf_[i];
switch(msgState_) {
case(BT_MSG_PREV_READ_LENGTH):
msgOffset_ = i;
currentPayloadLength_ = 0;
msgState_ = BT_MSG_READ_LENGTH;
// Fall through
case(BT_MSG_READ_LENGTH):
currentPayloadLength_ <<= 8;
currentPayloadLength_ += c;
// The message length is uint32_t
if(i - msgOffset_ == 3) {
if(currentPayloadLength_ + 4 > bufferCapacity_) {
throw DL_ABORT_EX(fmt(EX_TOO_LONG_PAYLOAD, currentPayloadLength_));
}
if(currentPayloadLength_ == 0) {
// Length == 0 means keep-alive message.
done = true;
msgState_ = BT_MSG_PREV_READ_LENGTH;
} else {
msgState_ = BT_MSG_READ_PAYLOAD;
}
}
break;
case(BT_MSG_READ_PAYLOAD):
// We chosen the bufferCapacity_ so that whole message,
// including 4 bytes length and payload, in it. So here we
// just make sure that it happens.
if(resbufLength_ - msgOffset_ >= 4 + currentPayloadLength_) {
i = msgOffset_ + 4 + currentPayloadLength_ - 1;
done = true;
msgState_ = BT_MSG_PREV_READ_LENGTH;
} else {
// We need another read.
i = resbufLength_-1;
}
break;
}
2006-03-21 14:12:51 +00:00
}
resbufOffset_ = i;
if(done) {
if(data) {
memcpy(data, resbuf_ + msgOffset_ + 4, currentPayloadLength_);
}
dataLength = currentPayloadLength_;
return true;
} else {
assert(resbufOffset_ == resbufLength_);
if(resbufLength_ != 0) {
if(msgOffset_ == 0 && resbufLength_ == currentPayloadLength_ + 4) {
// All bytes in buffer have been processed, so clear it
// away.
resbufLength_ = 0;
resbufOffset_ = 0;
msgOffset_ = 0;
} else {
// Shift buffer so that resbuf_[msgOffset_] moves to
// rebuf_[0].
memmove(resbuf_, resbuf_ + msgOffset_, resbufLength_ - msgOffset_);
resbufLength_ -= msgOffset_;
resbufOffset_ = resbufLength_;
msgOffset_ = 0;
}
}
size_t nread;
// To reduce the amount of copy involved in buffer shift, large
// payload will be read exactly.
if(currentPayloadLength_ > 4096) {
nread = currentPayloadLength_ + 4 - resbufLength_;
} else {
nread = bufferCapacity_ - resbufLength_;
}
readData(resbuf_+resbufLength_, nread, encryptionEnabled_);
if(nread == 0) {
if(socket_->wantRead() || socket_->wantWrite()) {
break;
} else {
peer_->setDisconnectedGracefully(true);
throw DL_ABORT_EX(EX_EOF_FROM_PEER);
}
} else {
resbufLength_ += nread;
}
2006-03-21 14:12:51 +00:00
}
}
return false;
2006-03-21 14:12:51 +00:00
}
bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
bool peek) {
if(BtHandshakeMessage::MESSAGE_LENGTH < resbufLength_) {
throw DL_ABORT_EX
("More than BtHandshakeMessage::MESSAGE_LENGTH bytes are buffered.");
}
bool retval = true;
size_t remaining = BtHandshakeMessage::MESSAGE_LENGTH-resbufLength_;
if(remaining > 0) {
size_t temp = remaining;
readData(resbuf_+resbufLength_, remaining, encryptionEnabled_);
if(remaining == 0 && !socket_->wantRead() && !socket_->wantWrite()) {
// we got EOF
A2_LOG_DEBUG
(fmt("CUID#%" PRId64 " - In PeerConnection::receiveHandshake(), remain=%lu",
cuid_,
static_cast<unsigned long>(temp)));
peer_->setDisconnectedGracefully(true);
throw DL_ABORT_EX(EX_EOF_FROM_PEER);
}
resbufLength_ += remaining;
if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength_) {
retval = false;
}
2006-03-21 14:12:51 +00:00
}
size_t writeLength = std::min(resbufLength_, dataLength);
memcpy(data, resbuf_, writeLength);
2006-12-24 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> Rewritten a portion of bittorrent implementation: * src/BtMessageValidator.h: New class. * src/BtBitfieldMessageValidator.h: New class. * src/BtHandshakeMessageValidator.h: New class. * src/BtRequestMessageValidator.h: New class. * src/BtSuggestPieceMessageValidator.h: New class. * src/BtAllowedFastMessageValidator.h: New class. * src/BtRejectMessageValidator.h: New class. * src/BtCancelMessageValidator.h: New class. * src/BtPieceMessageValidator.h: New class. * src/BtHaveMessageValidator.h: New class. * src/BtEventListener.h: New class. * src/AbstractBtEventListener.h: New class. * src/BtEvent.h: New class. * src/BtChokingEvent.h: New class. * src/BtChokedEvent.h: New class. * src/BtCancelSendingPieceEvent.h: New class. * src/BtAbortOutstandingRequestEvent.h: New class. * src/Randomizer.h: New class. * src/SimpleRandomizer.h: New class. * src/BtMessage.h: New class. * src/AbstractBtMessage.h: New class. * src/SimpleBtMessage.h: New class. * src/BtHaveMessage.h: New class. * src/BtInterestedMessage.h: New class. * src/BtAllowedFastMessage.h: New class. * src/BtUnchokeMessage.h: New class. * src/BtCancelMessage.h: New class. * src/BtNotInterestedMessage.h: New class. * src/BtChokeMessage.h: New class. * src/BtHaveNoneMessage.h: New class. * src/BtHandshakeMessage.h: New class. * src/BtSuggestPieceMessage.h: New class. * src/BtHaveMessage.h: New class. * src/BtPieceMessage.h: New class. * src/BtHaveAllMessage.h: New class. * src/BtKeepAliveMessage.h: New class. * src/BtPortMessage.h: New class. * src/BtRejectMessage.h: New class. * src/BtBitfieldMessage.h: New class. * src/BtRequestMessage.h: New class. * src/DefaultBtRequestFactory.h: New class. * src/DefaultBtMessageReceiver.h: New class. * src/BtInteractive.h: New class. * src/BtMessageDispatcher.h: New class. * src/DefaultBtMessageDispatcher.h: New class. * src/DefaultBtInteractive.h: New class. * src/BitfieldManFactory.h: New class. * src/HandleRegistry.h: New class. * src/BtMessageFactory.h: New class. * src/BtMessageReceiver.h: New class. * src/DefaultBtMessageFactory.h: New class. * src/PeerObject.h: New class. * src/BtRequestFactory.h: New class.
2006-12-24 06:25:21 +00:00
dataLength = writeLength;
if(retval && !peek) {
resbufLength_ = 0;
2006-06-22 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com> To make a listening socket non-block: * src/SocketCore.h (setNonBlockingMode): New function. * src/SocketCore.cc (setNonBlockingMode): New function. (beginListen): Added a call to setNonBlockingMode(). (acceptConnection): Call setNonBlockingMode(). (setBlockingMode): Updated. To handle tracker's NAT-checking: * src/PeerConnection.cc (receiveHandshake): 'msg' param is filled with received data and its length is assigned to 'length' param, even if all handshake message is not yet received. * src/PeerInteractionCommand.cc (executeInternal): Use peerInteraction->receiveHandshake(true) when a new peer connects to localhost. A call to peerInteraction->sendHandshake() was removed because it is called from peerInteraction->receiveHandshake(true). * src/PeerInteraction.h (quickReplied): New variable. (receiveHandshake): Added an argument. * src/PeerInteraction.cc (PeerInteraction): Added the initialization of quickReplied. (receiveHandshake): Send handshake message as soon as the info hash in a handshake message from a peer is correct. To change the random part of peer id and key parameter: * src/TorrentMan.h (key): New variable. * src/TorrentMan.cc (setupInternal1): Use Util::randomAlpha() to generate random part of peer id, which is now "-aria2-"+13 alphabet characters([A-Za-z]). key is also generated by Util::randomAlpha() and it is now 8 character long. * src/Util.h (randomAlpha): New function. * src/Util.cc (randomAlpha): New function. * src/TrackerWatcherCommand.cc (execute): In a tracker request: Use torrentMan->key as key parameter. Added no_peer_id=1. Set snubbing flag to false when a choke message is received from a snubbed peer. * src/ChokeMessage.cc (receivedAction): Set snubbing flag to false.
2006-06-22 15:26:18 +00:00
}
return retval;
2006-03-21 14:12:51 +00:00
}
void PeerConnection::readData
(unsigned char* data, size_t& length, bool encryption)
{
socket_->readData(data, length);
if(encryption) {
decryptor_->encrypt(length, data, data);
}
}
void PeerConnection::enableEncryption
(const SharedHandle<ARC4Encryptor>& encryptor,
const SharedHandle<ARC4Encryptor>& decryptor)
{
encryptor_ = encryptor;
decryptor_ = decryptor;
encryptionEnabled_ = true;
}
void PeerConnection::presetBuffer(const unsigned char* data, size_t length)
{
size_t nwrite = std::min(bufferCapacity_, length);
memcpy(resbuf_, data, nwrite);
resbufLength_ = length;
}
bool PeerConnection::sendBufferIsEmpty() const
{
return socketBuffer_.sendBufferIsEmpty();
}
ssize_t PeerConnection::sendPendingData()
{
ssize_t writtenLength = socketBuffer_.send();
A2_LOG_DEBUG(fmt("sent %ld byte(s).", static_cast<long int>(writtenLength)));
return writtenLength;
}
const unsigned char* PeerConnection::getMsgPayloadBuffer() const
{
return resbuf_ + msgOffset_ + 4;
}
void PeerConnection::reserveBuffer(size_t minSize)
{
if(bufferCapacity_ < minSize) {
bufferCapacity_ = minSize;
unsigned char *buf = new unsigned char[bufferCapacity_];
memcpy(buf, resbuf_, resbufLength_);
delete [] resbuf_;
resbuf_ = buf;
}
}
} // namespace aria2