2008-11-03 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com>

Made BtRegistry non-static object. Now DownloadEngine has a
	reference to its object.
	* src/AbstractBtMessage.cc
	* src/ActivePeerConnectionCommand.cc
	* src/ActivePeerConnectionCommand.h
	* src/BtContextAwareCommand.cc
	* src/BtContextAwareCommand.h
	* src/BtExtendedMessage.cc
	* src/BtExtendedMessage.h
	* src/BtInterestedMessage.cc
	* src/BtInterestedMessage.h
	* src/BtNotInterestedMessage.cc
	* src/BtNotInterestedMessage.h
	* src/BtRegistry.cc
	* src/BtRegistry.h
	* src/BtSeederStateChoke.cc
	* src/BtSetup.cc
	* src/DHTGetPeersCommand.cc
	* src/DHTGetPeersCommand.h
	* src/DHTPeerAnnounceEntry.cc
	* src/DHTPeerAnnounceEntry.h
	* src/DHTPeerAnnounceStorage.cc
	* src/DHTPeerAnnounceStorage.h
	* src/DHTPeerLookupTask.cc
	* src/DHTPeerLookupTask.h
	* src/DHTSetup.cc
	* src/DHTSetup.h
	* src/DHTTaskFactory.h
	* src/DHTTaskFactoryImpl.cc
	* src/DHTTaskFactoryImpl.h
	* src/DefaultBtAnnounce.cc
	* src/DefaultBtInteractive.cc
	* src/DefaultBtInteractive.h
	* src/DefaultBtMessageDispatcher.cc
	* src/DefaultBtMessageDispatcher.h
	* src/DefaultBtMessageFactory.cc
	* src/DefaultBtMessageFactory.h
	* src/DefaultBtMessageReceiver.cc
	* src/DefaultBtProgressInfoFile.cc
	* src/DefaultBtProgressInfoFile.h
	* src/DefaultBtRequestFactory.cc
	* src/DefaultBtRequestFactory.h
	* src/DefaultExtensionMessageFactory.cc
	* src/DefaultExtensionMessageFactory.h
	* src/DefaultPeerStorage.cc
	* src/DefaultPeerStorage.h
	* src/DownloadEngine.cc
	* src/DownloadEngine.h
	* src/InitiatorMSEHandshakeCommand.cc
	* src/InitiatorMSEHandshakeCommand.h
	* src/MSEHandshake.cc
	* src/MSEHandshake.h
	* src/Makefile.am
	* src/Makefile.in
	* src/PeerChokeCommand.cc
	* src/PeerChokeCommand.h
	* src/PeerInitiateConnectionCommand.cc
	* src/PeerInitiateConnectionCommand.h
	* src/PeerInteractionCommand.cc
	* src/PeerInteractionCommand.h
	* src/PeerObject.h
	* src/PeerReceiveHandshakeCommand.cc
	* src/PeerReceiveHandshakeCommand.h
	* src/ReceiverMSEHandshakeCommand.cc
	* src/RequestGroup.cc
	* src/RequestGroup.h
	* src/RequestGroupMan.cc
	* src/RequestGroupMan.h
	* src/SeedCheckCommand.cc
	* src/SeedCheckCommand.h
	* src/ShareRatioSeedCriteria.h
	* src/SimpleBtMessage.cc
	* src/TrackerWatcherCommand.cc
	* src/TrackerWatcherCommand.h
	* src/UTPexExtensionMessage.cc
	* src/UTPexExtensionMessage.h
	* test/BtCancelMessageTest.cc
	* test/BtChokeMessageTest.cc
	* test/BtExtendedMessageTest.cc
	* test/BtInterestedMessageTest.cc
	* test/BtNotInterestedMessageTest.cc
	* test/BtPieceMessageTest.cc
	* test/BtPortMessageTest.cc
	* test/BtRegistryTest.cc
	* test/BtRejectMessageTest.cc
	* test/BtRequestMessageTest.cc
	* test/DHTPeerAnnounceEntryTest.cc
	* test/DHTPeerAnnounceStorageTest.cc
	* test/DefaultBtMessageDispatcherTest.cc
	* test/DefaultBtMessageFactoryTest.cc
	* test/DefaultBtProgressInfoFileTest.cc
	* test/DefaultBtRequestFactoryTest.cc
	* test/DefaultExtensionMessageFactoryTest.cc
	* test/MSEHandshakeTest.cc
	* test/MockDHTTaskFactory.h
	* test/ShareRatioSeedCriteriaTest.cc
	* test/UTPexExtensionMessageTest.cc
pull/1/head
Tatsuhiro Tsujikawa 2008-11-03 06:49:02 +00:00
parent 93edc7bd20
commit 7cf589e784
96 changed files with 1709 additions and 1423 deletions

100
ChangeLog
View File

@ -1,3 +1,103 @@
2008-11-03 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com>
Made BtRegistry non-static object. Now DownloadEngine has a reference to
its object.
* src/AbstractBtMessage.cc
* src/ActivePeerConnectionCommand.cc
* src/ActivePeerConnectionCommand.h
* src/BtContextAwareCommand.cc
* src/BtContextAwareCommand.h
* src/BtExtendedMessage.cc
* src/BtExtendedMessage.h
* src/BtInterestedMessage.cc
* src/BtInterestedMessage.h
* src/BtNotInterestedMessage.cc
* src/BtNotInterestedMessage.h
* src/BtRegistry.cc
* src/BtRegistry.h
* src/BtSeederStateChoke.cc
* src/BtSetup.cc
* src/DHTGetPeersCommand.cc
* src/DHTGetPeersCommand.h
* src/DHTPeerAnnounceEntry.cc
* src/DHTPeerAnnounceEntry.h
* src/DHTPeerAnnounceStorage.cc
* src/DHTPeerAnnounceStorage.h
* src/DHTPeerLookupTask.cc
* src/DHTPeerLookupTask.h
* src/DHTSetup.cc
* src/DHTSetup.h
* src/DHTTaskFactory.h
* src/DHTTaskFactoryImpl.cc
* src/DHTTaskFactoryImpl.h
* src/DefaultBtAnnounce.cc
* src/DefaultBtInteractive.cc
* src/DefaultBtInteractive.h
* src/DefaultBtMessageDispatcher.cc
* src/DefaultBtMessageDispatcher.h
* src/DefaultBtMessageFactory.cc
* src/DefaultBtMessageFactory.h
* src/DefaultBtMessageReceiver.cc
* src/DefaultBtProgressInfoFile.cc
* src/DefaultBtProgressInfoFile.h
* src/DefaultBtRequestFactory.cc
* src/DefaultBtRequestFactory.h
* src/DefaultExtensionMessageFactory.cc
* src/DefaultExtensionMessageFactory.h
* src/DefaultPeerStorage.cc
* src/DefaultPeerStorage.h
* src/DownloadEngine.cc
* src/DownloadEngine.h
* src/InitiatorMSEHandshakeCommand.cc
* src/InitiatorMSEHandshakeCommand.h
* src/MSEHandshake.cc
* src/MSEHandshake.h
* src/Makefile.am
* src/Makefile.in
* src/PeerChokeCommand.cc
* src/PeerChokeCommand.h
* src/PeerInitiateConnectionCommand.cc
* src/PeerInitiateConnectionCommand.h
* src/PeerInteractionCommand.cc
* src/PeerInteractionCommand.h
* src/PeerObject.h
* src/PeerReceiveHandshakeCommand.cc
* src/PeerReceiveHandshakeCommand.h
* src/ReceiverMSEHandshakeCommand.cc
* src/RequestGroup.cc
* src/RequestGroup.h
* src/RequestGroupMan.cc
* src/RequestGroupMan.h
* src/SeedCheckCommand.cc
* src/SeedCheckCommand.h
* src/ShareRatioSeedCriteria.h
* src/SimpleBtMessage.cc
* src/TrackerWatcherCommand.cc
* src/TrackerWatcherCommand.h
* src/UTPexExtensionMessage.cc
* src/UTPexExtensionMessage.h
* test/BtCancelMessageTest.cc
* test/BtChokeMessageTest.cc
* test/BtExtendedMessageTest.cc
* test/BtInterestedMessageTest.cc
* test/BtNotInterestedMessageTest.cc
* test/BtPieceMessageTest.cc
* test/BtPortMessageTest.cc
* test/BtRegistryTest.cc
* test/BtRejectMessageTest.cc
* test/BtRequestMessageTest.cc
* test/DHTPeerAnnounceEntryTest.cc
* test/DHTPeerAnnounceStorageTest.cc
* test/DefaultBtMessageDispatcherTest.cc
* test/DefaultBtMessageFactoryTest.cc
* test/DefaultBtProgressInfoFileTest.cc
* test/DefaultBtRequestFactoryTest.cc
* test/DefaultExtensionMessageFactoryTest.cc
* test/MSEHandshakeTest.cc
* test/MockDHTTaskFactory.h
* test/ShareRatioSeedCriteriaTest.cc
* test/UTPexExtensionMessageTest.cc
2008-10-27 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com>
Fixed compiler warning.

View File

@ -36,7 +36,6 @@
#include "Peer.h"
#include "BtContext.h"
#include "PieceStorage.h"
#include "BtRegistry.h"
#include "BtEventListener.h"
#include "BtMessageValidator.h"
#include "LogFactory.h"
@ -99,7 +98,6 @@ SharedHandle<BtMessageValidator> AbstractBtMessage::getBtMessageValidator() cons
void AbstractBtMessage::setBtContext(const SharedHandle<BtContext>& btContext)
{
this->btContext = btContext;
this->pieceStorage = PIECE_STORAGE(btContext);
}
SharedHandle<BtContext> AbstractBtMessage::getBtContext() const

View File

@ -52,14 +52,16 @@
namespace aria2 {
ActivePeerConnectionCommand::ActivePeerConnectionCommand(int cuid,
ActivePeerConnectionCommand::ActivePeerConnectionCommand
(int cuid,
RequestGroup* requestGroup,
DownloadEngine* e,
const BtContextHandle& btContext,
time_t interval)
:Command(cuid),
BtContextAwareCommand(btContext),
:
Command(cuid),
RequestGroupAware(requestGroup),
_btContext(btContext),
interval(interval),
e(e),
_thresholdSpeed(e->option->getAsInt(PREF_BT_REQUEST_PEER_SPEED_LIMIT)),
@ -75,32 +77,32 @@ ActivePeerConnectionCommand::ActivePeerConnectionCommand(int cuid,
ActivePeerConnectionCommand::~ActivePeerConnectionCommand() {}
bool ActivePeerConnectionCommand::execute() {
if(btRuntime->isHalt()) {
if(_btRuntime->isHalt()) {
return true;
}
if(checkPoint.elapsed(interval)) {
checkPoint.reset();
TransferStat tstat = _requestGroup->calculateStat();
if(// for seeder state
(pieceStorage->downloadFinished() && btRuntime->lessThanMaxPeers() &&
(_pieceStorage->downloadFinished() && _btRuntime->lessThanMaxPeers() &&
(_maxUploadSpeedLimit == 0 ||
tstat.getUploadSpeed() < _maxUploadSpeedLimit*0.8)) ||
// for leecher state
(!pieceStorage->downloadFinished() &&
(!_pieceStorage->downloadFinished() &&
(tstat.getDownloadSpeed() < _thresholdSpeed ||
btRuntime->lessThanMinPeers()))) {
unsigned int numConnection = pieceStorage->downloadFinished() ?
_btRuntime->lessThanMinPeers()))) {
unsigned int numConnection = _pieceStorage->downloadFinished() ?
std::min(_numNewConnection,
BtRuntime::MAX_PEERS-btRuntime->getConnections()) :
BtRuntime::MAX_PEERS-_btRuntime->getConnections()) :
_numNewConnection;
for(unsigned int numAdd = numConnection;
numAdd > 0 && peerStorage->isPeerAvailable(); --numAdd) {
PeerHandle peer = peerStorage->getUnusedPeer();
numAdd > 0 && _peerStorage->isPeerAvailable(); --numAdd) {
PeerHandle peer = _peerStorage->getUnusedPeer();
connectToPeer(peer);
}
if(btRuntime->getConnections() == 0 &&
!pieceStorage->downloadFinished()) {
btAnnounce->overrideMinInterval(BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL);
if(_btRuntime->getConnections() == 0 &&
!_pieceStorage->downloadFinished()) {
_btAnnounce->overrideMinInterval(BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL);
}
}
}
@ -115,10 +117,37 @@ void ActivePeerConnectionCommand::connectToPeer(const PeerHandle& peer)
}
peer->usedBy(CUIDCounterSingletonHolder::instance()->newID());
PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(peer->usedBy(), _requestGroup, peer, e, btContext);
new PeerInitiateConnectionCommand(peer->usedBy(), _requestGroup, peer, e,
_btContext, _btRuntime);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
e->commands.push_back(command);
logger->info(MSG_CONNECTING_TO_PEER,
cuid, peer->ipaddr.c_str());
}
void ActivePeerConnectionCommand::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void ActivePeerConnectionCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void ActivePeerConnectionCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void ActivePeerConnectionCommand::setBtAnnounce
(const SharedHandle<BtAnnounce>& btAnnounce)
{
_btAnnounce = btAnnounce;
}
} // namespace aria2

View File

@ -36,7 +36,7 @@
#define _D_ACTIVE_PEER_CONNECTION_COMMAND_H_
#include "Command.h"
#include "BtContextAwareCommand.h"
#include "SharedHandle.h"
#include "RequestGroupAware.h"
#include "TimeA2.h"
@ -44,12 +44,22 @@ namespace aria2 {
class DownloadEngine;
class Peer;
class BtContext;
class BtRuntime;
class PieceStorage;
class PeerStorage;
class BtAnnounce;
class ActivePeerConnectionCommand : public Command,
public BtContextAwareCommand,
public RequestGroupAware
{
private:
SharedHandle<BtContext> _btContext;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<BtAnnounce> _btAnnounce;
time_t interval; // UNIT: sec
DownloadEngine* e;
Time checkPoint;
@ -73,6 +83,14 @@ public:
{
_numNewConnection = numNewConnection;
}
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setBtAnnounce(const SharedHandle<BtAnnounce>& btAnnounce);
};
} // namespace aria2

View File

@ -1,56 +0,0 @@
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* 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.
*/
/* copyright --> */
#include "BtContextAwareCommand.h"
#include "BtRegistry.h"
#include "BtContext.h"
#include "BtRuntime.h"
#include "PieceStorage.h"
#include "PeerStorage.h"
#include "BtAnnounce.h"
#include "BtProgressInfoFile.h"
namespace aria2 {
BtContextAwareCommand::BtContextAwareCommand(const BtContextHandle& btContext):
btContext(btContext),
btRuntime(BT_RUNTIME(btContext)),
pieceStorage(PIECE_STORAGE(btContext)),
peerStorage(PEER_STORAGE(btContext)),
btAnnounce(BT_ANNOUNCE(btContext)),
btProgressInfoFile(BT_PROGRESS_INFO_FILE(btContext)) {}
BtContextAwareCommand::~BtContextAwareCommand() {}
} // namespace aria2

View File

@ -1,67 +0,0 @@
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* 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.
*/
/* copyright --> */
#ifndef _D_BT_CONTEXT_AWARE_COMMAND_H_
#define _D_BT_CONTEXT_AWARE_COMMAND_H_
#include "common.h"
#include "SharedHandle.h"
namespace aria2 {
class BtContext;
class BtRuntime;
class PieceStorage;
class PeerStorage;
class BtAnnounce;
class BtProgressInfoFile;
class BtContextAwareCommand
{
protected:
SharedHandle<BtContext> btContext;
SharedHandle<BtRuntime> btRuntime;
SharedHandle<PieceStorage> pieceStorage;
SharedHandle<PeerStorage> peerStorage;
SharedHandle<BtAnnounce> btAnnounce;
SharedHandle<BtProgressInfoFile> btProgressInfoFile;
public:
BtContextAwareCommand(const SharedHandle<BtContext>& btContext);
virtual ~BtContextAwareCommand();
};
} // namespace aria2
#endif // _D_BT_CONTEXT_AWARE_COMMAND_H_

View File

@ -33,13 +33,6 @@
*/
/* copyright --> */
#include "BtExtendedMessage.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "BtMessageFactory.h"
#include "BtMessageReceiver.h"
#include "BtMessageDispatcher.h"
#include "BtRequestFactory.h"
#include "PeerConnection.h"
#include "ExtensionMessage.h"
#include "ExtensionMessageFactory.h"
#include "PeerMessageUtil.h"
@ -96,7 +89,7 @@ std::string BtExtendedMessage::toString() const {
}
BtExtendedMessageHandle
BtExtendedMessage::create(const BtContextHandle& btContext,
BtExtendedMessage::create(const SharedHandle<ExtensionMessageFactory>& factory,
const PeerHandle& peer,
const unsigned char* data, size_t dataLength)
{
@ -109,8 +102,6 @@ BtExtendedMessage::create(const BtContextHandle& btContext,
throw DlAbortEx
(StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "extended", ID).str());
}
ExtensionMessageFactoryHandle factory = EXTENSION_MESSAGE_FACTORY(btContext,
peer);
assert(!factory.isNull());
ExtensionMessageHandle extmsg = factory->createMessage(data+1,
dataLength-1);

View File

@ -39,6 +39,7 @@
namespace aria2 {
class ExtensionMessage;
class ExtensionMessageFactory;
class BtExtendedMessage;
typedef SharedHandle<BtExtendedMessage> BtExtendedMessageHandle;
@ -59,7 +60,8 @@ public:
static const uint8_t ID = 20;
static BtExtendedMessageHandle create(const SharedHandle<BtContext>& btContext,
static BtExtendedMessageHandle create
(const SharedHandle<ExtensionMessageFactory>& factory,
const SharedHandle<Peer>& peer,
const unsigned char* data,
size_t dataLength);

View File

@ -37,9 +37,7 @@
#include "DlAbortEx.h"
#include "message.h"
#include "Peer.h"
#include "BtRegistry.h"
#include "BtContext.h"
#include "PeerStorage.h"
#include "StringFormat.h"
namespace aria2 {
@ -60,9 +58,6 @@ BtInterestedMessageHandle BtInterestedMessage::create(const unsigned char* data,
void BtInterestedMessage::doReceivedAction() {
peer->peerInterested(true);
if(!peer->amChoking()) {
PEER_STORAGE(btContext)->executeChoke();
}
}
bool BtInterestedMessage::sendPredicate() const {

View File

@ -48,6 +48,7 @@ private:
unsigned char* msg;
static size_t MESSAGE_LENGTH;
public:
BtInterestedMessage():msg(0) {}

View File

@ -37,7 +37,6 @@
#include "DlAbortEx.h"
#include "message.h"
#include "Peer.h"
#include "BtRegistry.h"
#include "BtContext.h"
#include "PeerStorage.h"
#include "StringFormat.h"
@ -61,7 +60,7 @@ BtNotInterestedMessageHandle BtNotInterestedMessage::create(const unsigned char*
void BtNotInterestedMessage::doReceivedAction() {
peer->peerInterested(false);
if(!peer->amChoking()) {
PEER_STORAGE(btContext)->executeChoke();
_peerStorage->executeChoke();
}
}
@ -97,4 +96,10 @@ std::string BtNotInterestedMessage::toString() const {
return NOT_INTERESTED;
}
void BtNotInterestedMessage::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
} // namespace aria2

View File

@ -39,6 +39,7 @@
namespace aria2 {
class PeerStorage;
class BtNotInterestedMessage;
typedef SharedHandle<BtNotInterestedMessage> BtNotInterestedMessageHandle;
@ -47,6 +48,8 @@ class BtNotInterestedMessage : public SimpleBtMessage {
private:
unsigned char* msg;
SharedHandle<PeerStorage> _peerStorage;
static size_t MESSAGE_LENGTH;
public:
BtNotInterestedMessage():msg(0) {}
@ -72,6 +75,8 @@ public:
virtual bool sendPredicate() const;
virtual void onSendComplete();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
};
} // namespace aria2

View File

@ -40,23 +40,10 @@
#include "BtAnnounce.h"
#include "BtRuntime.h"
#include "BtProgressInfoFile.h"
#include "PeerObject.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "BtMessageDispatcher.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
namespace aria2 {
BtContextMap BtRegistry::btContextMap;
PeerStorageMap BtRegistry::peerStorageMap;
PieceStorageMap BtRegistry::pieceStorageMap;
BtAnnounceMap BtRegistry::btAnnounceMap;
BtRuntimeMap BtRegistry::btRuntimeMap;
BtProgressInfoFileMap BtRegistry::btProgressInfoFileMap;
PeerObjectClusterRegistry BtRegistry::peerObjectClusterRegistry;
BtRegistry::BtRegistry() {}
PeerStorageHandle BtRegistry::getPeerStorage(const std::string& key)
{
@ -136,25 +123,6 @@ std::deque<SharedHandle<BtContext> > BtRegistry::getAllBtContext()
return btContextMap.getAll();
}
PeerObjectClusterHandle
BtRegistry::getPeerObjectCluster(const std::string& key)
{
return peerObjectClusterRegistry.getHandle(key);
}
void
BtRegistry::registerPeerObjectCluster(const std::string& key,
const PeerObjectClusterHandle& cluster)
{
peerObjectClusterRegistry.registerHandle(key, cluster);
}
void
BtRegistry::unregisterPeerObjectCluster(const std::string& key)
{
peerObjectClusterRegistry.unregisterHandle(key);
}
void BtRegistry::unregisterAll() {
btContextMap.clear();
peerStorageMap.clear();
@ -162,7 +130,6 @@ void BtRegistry::unregisterAll() {
btAnnounceMap.clear();
btRuntimeMap.clear();
btProgressInfoFileMap.clear();
peerObjectClusterRegistry.clear();
}
void BtRegistry::unregister(const std::string& key)
@ -173,7 +140,6 @@ void BtRegistry::unregister(const std::string& key)
btAnnounceMap.unregisterHandle(key);
btRuntimeMap.unregisterHandle(key);
btProgressInfoFileMap.unregisterHandle(key);
peerObjectClusterRegistry.unregisterHandle(key);
}
} // namespace aria2

View File

@ -36,11 +36,13 @@
#define _D_BT_REGISTRY_H_
#include "common.h"
#include "SharedHandle.h"
#include "HandleRegistry.h"
#include <string>
#include <map>
#include "SharedHandle.h"
#include "HandleRegistry.h"
namespace aria2 {
class PeerStorage;
@ -49,7 +51,6 @@ class BtAnnounce;
class BtRuntime;
class BtProgressInfoFile;
class BtContext;
class PeerObject;
typedef HandleRegistry<std::string, PeerStorage> PeerStorageMap;
typedef HandleRegistry<std::string, PieceStorage> PieceStorageMap;
@ -58,104 +59,49 @@ typedef HandleRegistry<std::string, BtRuntime> BtRuntimeMap;
typedef HandleRegistry<std::string, BtProgressInfoFile> BtProgressInfoFileMap;
typedef HandleRegistry<std::string, BtContext> BtContextMap;
// for BtMessageFactory
typedef HandleRegistry<std::string, PeerObject> PeerObjectCluster;
typedef SharedHandle<PeerObjectCluster> PeerObjectClusterHandle;
typedef HandleRegistry<std::string, PeerObjectCluster> PeerObjectClusterRegistry;
class BtRegistry {
private:
BtRegistry() {}
static BtContextMap btContextMap;
static PeerStorageMap peerStorageMap;
static PieceStorageMap pieceStorageMap;
static BtAnnounceMap btAnnounceMap;
static BtRuntimeMap btRuntimeMap;
static BtProgressInfoFileMap btProgressInfoFileMap;
static PeerObjectClusterRegistry peerObjectClusterRegistry;
BtContextMap btContextMap;
PeerStorageMap peerStorageMap;
PieceStorageMap pieceStorageMap;
BtAnnounceMap btAnnounceMap;
BtRuntimeMap btRuntimeMap;
BtProgressInfoFileMap btProgressInfoFileMap;
public:
static SharedHandle<BtContext> getBtContext(const std::string& key);
static void registerBtContext(const std::string& key,
BtRegistry();
SharedHandle<BtContext> getBtContext(const std::string& key);
void registerBtContext(const std::string& key,
const SharedHandle<BtContext>& btContext);
static SharedHandle<PeerStorage> getPeerStorage(const std::string& key);
static void registerPeerStorage(const std::string& key,
SharedHandle<PeerStorage> getPeerStorage(const std::string& key);
void registerPeerStorage(const std::string& key,
const SharedHandle<PeerStorage>& peer);
static SharedHandle<PieceStorage> getPieceStorage(const std::string& key);
static void registerPieceStorage(const std::string& key,
SharedHandle<PieceStorage> getPieceStorage(const std::string& key);
void registerPieceStorage(const std::string& key,
const SharedHandle<PieceStorage>& pieceStorage);
static SharedHandle<BtRuntime> getBtRuntime(const std::string& key);
static void registerBtRuntime(const std::string& key,
SharedHandle<BtRuntime> getBtRuntime(const std::string& key);
void registerBtRuntime(const std::string& key,
const SharedHandle<BtRuntime>& btRuntime);
static SharedHandle<BtAnnounce> getBtAnnounce(const std::string& key);
static void registerBtAnnounce(const std::string& key,
SharedHandle<BtAnnounce> getBtAnnounce(const std::string& key);
void registerBtAnnounce(const std::string& key,
const SharedHandle<BtAnnounce>& btAnnounce);
static SharedHandle<BtProgressInfoFile> getBtProgressInfoFile(const std::string& key);
static void registerBtProgressInfoFile(const std::string& key,
const SharedHandle<BtProgressInfoFile>& btProgressInfoFile);
SharedHandle<BtProgressInfoFile>
getBtProgressInfoFile(const std::string& key);
void registerBtProgressInfoFile(const std::string& key,
const SharedHandle<BtProgressInfoFile>& file);
static std::deque<SharedHandle<BtContext> > getAllBtContext();
std::deque<SharedHandle<BtContext> > getAllBtContext();
// for PeerObject
static PeerObjectClusterHandle
getPeerObjectCluster(const std::string& key);
void unregisterAll();
static void
registerPeerObjectCluster(const std::string& key,
const PeerObjectClusterHandle& cluster);
static void
unregisterPeerObjectCluster(const std::string& key);
static void unregisterAll();
static void unregister(const std::string& key);
void unregister(const std::string& key);
};
#define PEER_STORAGE(btContext) \
BtRegistry::getPeerStorage(btContext->getInfoHashAsString())
#define PIECE_STORAGE(btContext) \
BtRegistry::getPieceStorage(btContext->getInfoHashAsString())
#define BT_ANNOUNCE(btContext) \
BtRegistry::getBtAnnounce(btContext->getInfoHashAsString())
#define BT_RUNTIME(btContext) \
BtRegistry::getBtRuntime(btContext->getInfoHashAsString())
#define BT_PROGRESS_INFO_FILE(btContext) \
BtRegistry::getBtProgressInfoFile(btContext->getInfoHashAsString())
#define PEER_OBJECT_CLUSTER(btContext) \
BtRegistry::getPeerObjectCluster(btContext->getInfoHashAsString())
#define PEER_OBJECT(btContext, peer) \
PEER_OBJECT_CLUSTER(btContext)->getHandle(peer->getID())
#define BT_MESSAGE_DISPATCHER(btContext, peer) \
PEER_OBJECT(btContext, peer)->btMessageDispatcher
#define BT_MESSAGE_RECEIVER(btContext, peer) \
PEER_OBJECT(btContext, peer)->btMessageReceiver
#define BT_MESSAGE_FACTORY(btContext, peer) \
PEER_OBJECT(btContext, peer)->btMessageFactory
#define BT_REQUEST_FACTORY(btContext, peer) \
PEER_OBJECT(btContext, peer)->btRequestFactory
#define PEER_CONNECTION(btContext, peer) \
PEER_OBJECT(btContext, peer)->peerConnection
#define EXTENSION_MESSAGE_FACTORY(btContext, peer) \
PEER_OBJECT(btContext, peer)->extensionMessageFactory
} // namespace aria2
#endif // _D_BT_REGISTRY_H_

View File

@ -33,10 +33,11 @@
*/
/* copyright --> */
#include "BtSeederStateChoke.h"
#include <algorithm>
#include "BtContext.h"
#include "Peer.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "BtMessageDispatcher.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
@ -46,7 +47,6 @@
#include "Logger.h"
#include "LogFactory.h"
#include "a2time.h"
#include <algorithm>
namespace aria2 {
@ -70,19 +70,19 @@ public:
bool operator()(Peer* left, Peer* right) const
{
size_t leftUpload = BT_MESSAGE_DISPATCHER(_btContext, left)->countOutstandingRequest();
size_t rightUpload = BT_MESSAGE_DISPATCHER(_btContext, right)->countOutstandingRequest();
if(leftUpload && !rightUpload) {
return true;
} else if(!leftUpload && rightUpload) {
return false;
}
// TODO Should peer have the reference to message dispatcher?
// size_t leftUpload = BT_MESSAGE_DISPATCHER(_btContext, left)->countOutstandingUpload();
// size_t rightUpload = BT_MESSAGE_DISPATCHER(_btContext, right)->countOutstandingUpload();
// if(leftUpload && !rightUpload) {
// return true;
// } else if(!leftUpload && rightUpload) {
// return false;
// }
const int TIME_FRAME = 20;
if(!left->getLastAmUnchoking().elapsed(TIME_FRAME) &&
left->getLastAmUnchoking().isNewer(right->getLastAmUnchoking())) {
return true;
} else if(!right->getLastAmUnchoking().elapsed(TIME_FRAME) &&
right->getLastAmUnchoking().isNewer(left->getLastAmUnchoking())) {
} else if(!right->getLastAmUnchoking().elapsed(TIME_FRAME)) {
return false;
} else {
return left->calculateUploadSpeed(_now) > right->calculateUploadSpeed(_now);

View File

@ -56,6 +56,8 @@
#include "DHTPeerAnnounceStorage.h"
#include "DHTSetup.h"
#include "DHTRegistry.h"
#include "BtProgressInfoFile.h"
#include "BtAnnounce.h"
namespace aria2 {
@ -70,26 +72,64 @@ void BtSetup::setup(std::deque<Command*>& commands,
if(btContext.isNull()) {
return;
}
SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
SharedHandle<PieceStorage> pieceStorage =
btRegistry->getPieceStorage(btContext->getInfoHashAsString());
SharedHandle<PeerStorage> peerStorage =
btRegistry->getPeerStorage(btContext->getInfoHashAsString());
SharedHandle<BtRuntime> btRuntime =
btRegistry->getBtRuntime(btContext->getInfoHashAsString());
SharedHandle<BtAnnounce> btAnnounce =
btRegistry->getBtAnnounce(btContext->getInfoHashAsString());
// commands
commands.push_back(new TrackerWatcherCommand(CUIDCounterSingletonHolder::instance()->newID(),
{
TrackerWatcherCommand* c =
new TrackerWatcherCommand(CUIDCounterSingletonHolder::instance()->newID(),
requestGroup,
e,
btContext));
commands.push_back(new PeerChokeCommand(CUIDCounterSingletonHolder::instance()->newID(),
e,
btContext));
btContext);
c->setPeerStorage(peerStorage);
c->setPieceStorage(pieceStorage);
c->setBtRuntime(btRuntime);
c->setBtAnnounce(btAnnounce);
commands.push_back(new ActivePeerConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(),
requestGroup, e, btContext, 10));
commands.push_back(c);
}
{
PeerChokeCommand* c =
new PeerChokeCommand(CUIDCounterSingletonHolder::instance()->newID(),
e,
btContext);
c->setPeerStorage(peerStorage);
c->setBtRuntime(btRuntime);
commands.push_back(c);
}
{
ActivePeerConnectionCommand* c =
new ActivePeerConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(),
requestGroup, e, btContext, 10);
c->setBtRuntime(btRuntime);
c->setPieceStorage(pieceStorage);
c->setPeerStorage(peerStorage);
c->setBtAnnounce(btAnnounce);
commands.push_back(c);
}
if(!btContext->isPrivate() && DHTSetup::initialized()) {
DHTRegistry::_peerAnnounceStorage->addPeerAnnounce(btContext);
DHTGetPeersCommand* command = new DHTGetPeersCommand(CUIDCounterSingletonHolder::instance()->newID(),
DHTRegistry::_peerAnnounceStorage->addPeerAnnounce(btContext->getInfoHash(),
peerStorage);
DHTGetPeersCommand* command =
new DHTGetPeersCommand(CUIDCounterSingletonHolder::instance()->newID(),
requestGroup,
e,
btContext);
command->setTaskQueue(DHTRegistry::_taskQueue);
command->setTaskFactory(DHTRegistry::_taskFactory);
command->setBtRuntime(btRuntime);
command->setPeerStorage(peerStorage);
commands.push_back(command);
}
SharedHandle<UnionSeedCriteria> unionCri(new UnionSeedCriteria());
@ -100,16 +140,26 @@ void BtSetup::setup(std::deque<Command*>& commands,
{
double ratio = option->getAsDouble(PREF_SEED_RATIO);
if(ratio > 0.0) {
SharedHandle<SeedCriteria> cri(new ShareRatioSeedCriteria(option->getAsDouble(PREF_SEED_RATIO), btContext));
SharedHandle<ShareRatioSeedCriteria> cri
(new ShareRatioSeedCriteria(option->getAsDouble(PREF_SEED_RATIO),
btContext));
cri->setPieceStorage(pieceStorage);
cri->setPeerStorage(peerStorage);
cri->setBtRuntime(btRuntime);
unionCri->addSeedCriteria(cri);
}
}
if(unionCri->getSeedCriterion().size() > 0) {
commands.push_back(new SeedCheckCommand(CUIDCounterSingletonHolder::instance()->newID(),
SeedCheckCommand* c =
new SeedCheckCommand(CUIDCounterSingletonHolder::instance()->newID(),
requestGroup,
e,
btContext,
unionCri));
unionCri);
c->setPieceStorage(pieceStorage);
c->setBtRuntime(btRuntime);
commands.push_back(c);
}
if(PeerListenCommand::getNumInstance() == 0) {
@ -117,7 +167,7 @@ void BtSetup::setup(std::deque<Command*>& commands,
IntSequence seq = Util::parseIntRange(option->get(PREF_LISTEN_PORT));
uint16_t port;
if(listenCommand->bindPort(port, seq)) {
BT_RUNTIME(btContext)->setListenPort(port);
btRuntime->setListenPort(port);
commands.push_back(listenCommand);
} else {
_logger->error(_("Errors occurred while binding port.\n"));
@ -125,7 +175,7 @@ void BtSetup::setup(std::deque<Command*>& commands,
}
}
BT_RUNTIME(btContext)->setReady(true);
btRuntime->setReady(true);
}
} // namespace aria2

View File

@ -54,8 +54,8 @@ DHTGetPeersCommand::DHTGetPeersCommand(int32_t cuid,
DownloadEngine* e,
const BtContextHandle& ctx):
Command(cuid),
BtContextAwareCommand(ctx),
RequestGroupAware(requestGroup),
_btContext(ctx),
_e(e),
_numRetry(0),
_lastGetPeerTime(0)
@ -65,19 +65,21 @@ DHTGetPeersCommand::~DHTGetPeersCommand() {}
bool DHTGetPeersCommand::execute()
{
if(btRuntime->isHalt()) {
if(_btRuntime->isHalt()) {
return true;
}
if(_task.isNull() &&
((_numRetry > 0 && _lastGetPeerTime.elapsed(RETRY_INTERVAL)) ||
_lastGetPeerTime.elapsed(GET_PEER_INTERVAL))) {
logger->debug("Issuing PeerLookup for infoHash=%s",
btContext->getInfoHashAsString().c_str());
_task = dynamic_pointer_cast<DHTPeerLookupTask>(_taskFactory->createPeerLookupTask(btContext));
_btContext->getInfoHashAsString().c_str());
_task = dynamic_pointer_cast<DHTPeerLookupTask>
(_taskFactory->createPeerLookupTask(_btContext, _btRuntime,
_peerStorage));
_taskQueue->addPeriodicTask2(_task);
} else if(!_task.isNull() && _task->finished()) {
_lastGetPeerTime.reset();
if(_numRetry < MAX_RETRIES && btRuntime->lessThanMinPeers()) {
if(_numRetry < MAX_RETRIES && _btRuntime->lessThanMinPeers()) {
++_numRetry;
} else {
_numRetry = 0;
@ -99,4 +101,14 @@ void DHTGetPeersCommand::setTaskFactory(const SharedHandle<DHTTaskFactory>& task
_taskFactory = taskFactory;
}
void DHTGetPeersCommand::setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void DHTGetPeersCommand::setPeerStorage(const SharedHandle<PeerStorage>& ps)
{
_peerStorage = ps;
}
} // namespace aria2

View File

@ -36,8 +36,8 @@
#define _D_DHT_GET_PEERS_COMMAND_H_
#include "Command.h"
#include "BtContextAwareCommand.h"
#include "RequestGroupAware.h"
#include "SharedHandle.h"
#include "TimeA2.h"
namespace aria2 {
@ -47,9 +47,11 @@ class DHTTaskFactory;
class DHTPeerLookupTask;
class DownloadEngine;
class RequestGroup;
class BtContext;
class BtRuntime;
class PeerStorage;
class DHTGetPeersCommand:public Command,
public BtContextAwareCommand,
public RequestGroupAware
{
private:
@ -59,6 +61,12 @@ private:
static const size_t MAX_RETRIES = 10;
SharedHandle<BtContext> _btContext;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PeerStorage> _peerStorage;
DownloadEngine* _e;
SharedHandle<DHTTaskQueue> _taskQueue;
@ -82,6 +90,10 @@ public:
void setTaskQueue(const SharedHandle<DHTTaskQueue>& taskQueue);
void setTaskFactory(const SharedHandle<DHTTaskFactory>& taskFactory);
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
};
} // namespace aria2

View File

@ -33,13 +33,13 @@
*/
/* copyright --> */
#include "DHTPeerAnnounceEntry.h"
#include "BtContext.h"
#include "Peer.h"
#include "BtRegistry.h"
#include "PeerStorage.h"
#include <cstring>
#include <algorithm>
#include "Peer.h"
#include "PeerStorage.h"
namespace aria2 {
DHTPeerAnnounceEntry::DHTPeerAnnounceEntry(const unsigned char* infoHash)
@ -60,9 +60,15 @@ void DHTPeerAnnounceEntry::addPeerAddrEntry(const PeerAddrEntry& entry)
notifyUpdate();
}
void DHTPeerAnnounceEntry::setBtContext(const SharedHandle<BtContext>& btCtx)
void DHTPeerAnnounceEntry::clearLocal()
{
_btCtx = btCtx;
_peerStorage.reset();
}
void DHTPeerAnnounceEntry::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
size_t DHTPeerAnnounceEntry::countPeerAddrEntry() const
@ -99,7 +105,7 @@ void DHTPeerAnnounceEntry::removeStalePeerAddrEntry(time_t timeout)
bool DHTPeerAnnounceEntry::empty() const
{
return _peerAddrEntries.empty() && _btCtx.isNull();
return _peerAddrEntries.empty() && _peerStorage.isNull();
}
void DHTPeerAnnounceEntry::getPeers(std::deque<SharedHandle<Peer> >& peers) const
@ -109,11 +115,8 @@ void DHTPeerAnnounceEntry::getPeers(std::deque<SharedHandle<Peer> >& peers) cons
SharedHandle<Peer> peer(new Peer((*i).getIPAddress(), (*i).getPort()));
peers.push_back(peer);
}
if(!_btCtx.isNull()) {
SharedHandle<PeerStorage> peerStorage = PEER_STORAGE(_btCtx);
if(!peerStorage.isNull()) {
peerStorage->getActivePeers(peers);
}
if(!_peerStorage.isNull()) {
_peerStorage->getActivePeers(peers);
}
}

View File

@ -36,16 +36,18 @@
#define _D_DHT_PEER_ANNOUNCE_ENTRY_H_
#include "common.h"
#include <deque>
#include "SharedHandle.h"
#include "DHTConstants.h"
#include "PeerAddrEntry.h"
#include "TimeA2.h"
#include <deque>
namespace aria2 {
class Peer;
class BtContext;
class PeerStorage;
class DHTPeerAnnounceEntry {
private:
@ -53,7 +55,7 @@ private:
std::deque<PeerAddrEntry> _peerAddrEntries;
SharedHandle<BtContext> _btCtx;
SharedHandle<PeerStorage> _peerStorage;
Time _lastUpdated;
public:
@ -65,7 +67,9 @@ public:
// if it already exists, update "Last Updated" property.
void addPeerAddrEntry(const PeerAddrEntry& entry);
void setBtContext(const SharedHandle<BtContext>& btCtx);
void clearLocal();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
size_t countPeerAddrEntry() const;

View File

@ -33,9 +33,13 @@
*/
/* copyright --> */
#include "DHTPeerAnnounceStorage.h"
#include <cstring>
#include <algorithm>
#include "DHTPeerAnnounceEntry.h"
#include "Peer.h"
#include "BtContext.h"
#include "PeerStorage.h"
#include "DHTConstants.h"
#include "DHTTaskQueue.h"
#include "DHTTaskFactory.h"
@ -44,8 +48,6 @@
#include "Logger.h"
#include "Util.h"
#include "a2functional.h"
#include <cstring>
#include <algorithm>
namespace aria2 {
@ -91,24 +93,27 @@ DHTPeerAnnounceStorage::addPeerAnnounce(const unsigned char* infoHash,
}
// add peer announce as localhost downloading the content
void DHTPeerAnnounceStorage::addPeerAnnounce(const BtContextHandle& ctx)
void DHTPeerAnnounceStorage::addPeerAnnounce
(const unsigned char* infoHash, const SharedHandle<PeerStorage>& peerStorage)
{
_logger->debug("Adding localhost to peer announce list: infoHash=%s",
ctx->getInfoHashAsString().c_str());
getPeerAnnounceEntry(ctx->getInfoHash())->setBtContext(ctx);
Util::toHex(infoHash, DHT_ID_LENGTH).c_str());
SharedHandle<DHTPeerAnnounceEntry> entry =
getPeerAnnounceEntry(infoHash);
entry->setPeerStorage(peerStorage);
}
void DHTPeerAnnounceStorage::removePeerAnnounce(const BtContextHandle& ctx)
void DHTPeerAnnounceStorage::removeLocalPeerAnnounce
(const unsigned char* infoHash)
{
SharedHandle<DHTPeerAnnounceEntry> entry(new DHTPeerAnnounceEntry(
ctx->getInfoHash()));
SharedHandle<DHTPeerAnnounceEntry> entry(new DHTPeerAnnounceEntry(infoHash));
std::deque<SharedHandle<DHTPeerAnnounceEntry> >::iterator i =
std::lower_bound(_entries.begin(), _entries.end(), entry, InfoHashLess());
if(i != _entries.end() &&
memcmp(ctx->getInfoHash(), (*i)->getInfoHash(), DHT_ID_LENGTH) == 0) {
(*i)->setBtContext(SharedHandle<BtContext>());
memcmp(infoHash, (*i)->getInfoHash(), DHT_ID_LENGTH) == 0) {
(*i)->clearLocal();
if((*i)->empty()) {
_entries.erase(i);
}

View File

@ -41,7 +41,7 @@
namespace aria2 {
class BtContext;
class PeerStorage;
class Peer;
class DHTPeerAnnounceEntry;
class DHTTaskQueue;
@ -68,11 +68,12 @@ public:
const std::string& ipaddr, uint16_t port);
// add peer announce as localhost downloading the content
void addPeerAnnounce(const SharedHandle<BtContext>& ctx);
void addPeerAnnounce(const unsigned char* infoHash,
const SharedHandle<PeerStorage>& peerStorage);
// give 0 to DHTPeerAnnounceEntry::setBtContext().
// Call DHTPeerAnnounceEntry::clearLocal() for infoHash if found.
// If DHTPeerAnnounceEntry is empty, it is erased.
void removePeerAnnounce(const SharedHandle<BtContext>& ctx);
void removeLocalPeerAnnounce(const unsigned char* infoHash);
bool contains(const unsigned char* infoHash) const;

View File

@ -41,7 +41,6 @@
#include "DHTNodeLookupEntry.h"
#include "DHTMessageDispatcher.h"
#include "DHTMessageCallback.h"
#include "BtRegistry.h"
#include "PeerStorage.h"
#include "BtRuntime.h"
#include "BtContext.h"
@ -52,9 +51,7 @@ namespace aria2 {
DHTPeerLookupTask::DHTPeerLookupTask(const SharedHandle<BtContext>& btContext):
DHTAbstractNodeLookupTask(btContext->getInfoHash()),
_ctx(btContext),
_peerStorage(PEER_STORAGE(btContext)),
_btRuntime(BT_RUNTIME(btContext)) {}
_ctx(btContext) {}
void
DHTPeerLookupTask::getNodesFromMessage(std::deque<SharedHandle<DHTNode> >& nodes,
@ -110,4 +107,14 @@ const std::deque<SharedHandle<Peer> >& DHTPeerLookupTask::getPeers() const
return _peers;
}
void DHTPeerLookupTask::setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void DHTPeerLookupTask::setPeerStorage(const SharedHandle<PeerStorage>& ps)
{
_peerStorage = ps;
}
} // namespace aria2

View File

@ -69,6 +69,10 @@ public:
virtual void onFinish();
const std::deque<SharedHandle<Peer> >& getPeers() const;
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
};
} // namespace aria2

View File

@ -33,6 +33,10 @@
*/
/* copyright --> */
#include "DHTSetup.h"
#include <fstream>
#include <algorithm>
#include "LogFactory.h"
#include "Logger.h"
#include "Util.h"
@ -66,12 +70,11 @@
#include "DlAbortEx.h"
#include "RecoverableException.h"
#include "a2functional.h"
#include <fstream>
#include <algorithm>
namespace aria2 {
size_t DHTSetup::_initialized = 0;
// TODO DownloadEngine should hold this flag.
bool DHTSetup::_initialized = false;
DHTSetup::DHTSetup():_logger(LogFactory::getInstance()) {}

View File

@ -46,7 +46,7 @@ class Command;
class DHTSetup {
private:
static size_t _initialized;
static bool _initialized;
Logger* _logger;

View File

@ -41,6 +41,8 @@
namespace aria2 {
class BtContext;
class BtRuntime;
class PeerStorage;
class DHTTask;
class DHTNode;
class DHTBucket;
@ -59,7 +61,9 @@ public:
virtual SharedHandle<DHTTask> createBucketRefreshTask() = 0;
virtual SharedHandle<DHTTask>
createPeerLookupTask(const SharedHandle<BtContext>& ctx) = 0;
createPeerLookupTask(const SharedHandle<BtContext>& ctx,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<PeerStorage>& peerStorage) = 0;
virtual SharedHandle<DHTTask>
createPeerAnnounceTask(const unsigned char* infoHash) = 0;

View File

@ -84,9 +84,15 @@ DHTTaskFactoryImpl::createBucketRefreshTask()
}
SharedHandle<DHTTask>
DHTTaskFactoryImpl::createPeerLookupTask(const SharedHandle<BtContext>& ctx)
DHTTaskFactoryImpl::createPeerLookupTask
(const SharedHandle<BtContext>& ctx,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<PeerStorage>& peerStorage)
{
SharedHandle<DHTPeerLookupTask> task(new DHTPeerLookupTask(ctx));
// TODO these may be not freed by RequestGroup::releaseRuntimeResource()
task->setBtRuntime(btRuntime);
task->setPeerStorage(peerStorage);
setCommonProperty(task);
return task;
}

View File

@ -77,7 +77,9 @@ public:
virtual SharedHandle<DHTTask> createBucketRefreshTask();
virtual SharedHandle<DHTTask>
createPeerLookupTask(const SharedHandle<BtContext>& ctx);
createPeerLookupTask(const SharedHandle<BtContext>& ctx,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<PeerStorage>& peerStorage);
virtual SharedHandle<DHTTask>
createPeerAnnounceTask(const unsigned char* infoHash);

View File

@ -33,7 +33,6 @@
*/
/* copyright --> */
#include "DefaultBtAnnounce.h"
#include "BtRegistry.h"
#include "LogFactory.h"
#include "Logger.h"
#include "MetaFileUtil.h"
@ -68,10 +67,7 @@ DefaultBtAnnounce::DefaultBtAnnounce(const BtContextHandle& btContext,
announceList(btContext->getAnnounceTiers()),
option(option),
logger(LogFactory::getInstance()),
_randomizer(SimpleRandomizer::getInstance()),
btRuntime(BT_RUNTIME(btContext)),
pieceStorage(PIECE_STORAGE(btContext)),
peerStorage(PEER_STORAGE(btContext))
_randomizer(SimpleRandomizer::getInstance())
{
prevAnnounceTime.setTimeInSec(0);
generateKey();

View File

@ -33,6 +33,9 @@
*/
/* copyright --> */
#include "DefaultBtInteractive.h"
#include <cstring>
#include "prefs.h"
#include "message.h"
#include "BtHandshakeMessage.h"
@ -47,9 +50,7 @@
#include "HandshakeExtensionMessage.h"
#include "UTPexExtensionMessage.h"
#include "DefaultExtensionMessageFactory.h"
#include "BtRegistry.h"
#include "DHTNode.h"
#include "PeerObject.h"
#include "Peer.h"
#include "Piece.h"
#include "BtContext.h"
@ -61,17 +62,17 @@
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "PeerConnection.h"
#include "BtRegistry.h"
#include "Logger.h"
#include "LogFactory.h"
#include "StringFormat.h"
#include "RequestGroup.h"
#include <cstring>
namespace aria2 {
DefaultBtInteractive::DefaultBtInteractive(const SharedHandle<BtContext>& btContext, const SharedHandle<Peer>& peer):
BtContextAwareCommand(btContext),
DefaultBtInteractive::DefaultBtInteractive
(const SharedHandle<BtContext>& btContext, const SharedHandle<Peer>& peer)
:
_btContext(btContext),
peer(peer),
logger(LogFactory::getInstance()),
allowedFastSetSize(10),
@ -84,11 +85,10 @@ DefaultBtInteractive::DefaultBtInteractive(const SharedHandle<BtContext>& btCont
DefaultBtInteractive::~DefaultBtInteractive() {}
void DefaultBtInteractive::initiateHandshake() {
SharedHandle<BtMessage> message =
messageFactory->createHandshakeMessage(btContext->getInfoHash(),
btContext->getPeerId());
messageFactory->createHandshakeMessage(_btContext->getInfoHash(),
_btContext->getPeerId());
dispatcher->addMessageToQueue(message);
dispatcher->sendMessages();
}
@ -99,8 +99,11 @@ BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) {
if(message.isNull()) {
return SharedHandle<BtMessage>();
}
if(memcmp(message->getPeerId(), btContext->getPeerId(), PEER_ID_LENGTH) == 0) {
throw DlAbortEx(StringFormat("CUID#%d - Drop connection from the same Peer ID", cuid).str());
if(memcmp(message->getPeerId(), _btContext->getPeerId(),
PEER_ID_LENGTH) == 0) {
throw DlAbortEx
(StringFormat
("CUID#%d - Drop connection from the same Peer ID", cuid).str());
}
peer->setPeerId(message->getPeerId());
@ -111,12 +114,9 @@ BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) {
}
if(message->isExtendedMessagingEnabled()) {
peer->setExtendedMessagingEnabled(true);
DefaultExtensionMessageFactoryHandle factory
(new DefaultExtensionMessageFactory(btContext, peer));
if(!_utPexEnabled) {
factory->removeExtension("ut_pex");
_extensionMessageFactory->removeExtension("ut_pex");
}
PEER_OBJECT(btContext, peer)->extensionMessageFactory = factory;
logger->info(MSG_EXTENDED_MESSAGING_ENABLED, cuid);
}
if(message->isDHTEnabled()) {
@ -152,7 +152,8 @@ void DefaultBtInteractive::doPostHandshakeProcessing() {
void DefaultBtInteractive::addPortMessageToQueue()
{
dispatcher->addMessageToQueue(messageFactory->createPortMessage(_localNode->getPort()));
dispatcher->addMessageToQueue
(messageFactory->createPortMessage(_localNode->getPort()));
}
void DefaultBtInteractive::addHandshakeExtendedMessageToQueue()
@ -160,8 +161,8 @@ void DefaultBtInteractive::addHandshakeExtendedMessageToQueue()
static const std::string CLIENT_ARIA2("aria2");
HandshakeExtensionMessageHandle m(new HandshakeExtensionMessage());
m->setClientVersion(CLIENT_ARIA2);
m->setTCPPort(btRuntime->getListenPort());
m->setExtensions(EXTENSION_MESSAGE_FACTORY(btContext, peer)->getExtensions());
m->setTCPPort(_btRuntime->getListenPort());
m->setExtensions(_extensionMessageFactory->getExtensions());
SharedHandle<BtMessage> msg = messageFactory->createBtExtendedMessage(m);
dispatcher->addMessageToQueue(msg);
@ -169,15 +170,15 @@ void DefaultBtInteractive::addHandshakeExtendedMessageToQueue()
void DefaultBtInteractive::addBitfieldMessageToQueue() {
if(peer->isFastExtensionEnabled()) {
if(pieceStorage->allDownloadFinished()) {
if(_pieceStorage->allDownloadFinished()) {
dispatcher->addMessageToQueue(messageFactory->createHaveAllMessage());
} else if(pieceStorage->getCompletedLength() > 0) {
} else if(_pieceStorage->getCompletedLength() > 0) {
dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
} else {
dispatcher->addMessageToQueue(messageFactory->createHaveNoneMessage());
}
} else {
if(pieceStorage->getCompletedLength() > 0) {
if(_pieceStorage->getCompletedLength() > 0) {
dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
}
}
@ -186,10 +187,11 @@ void DefaultBtInteractive::addBitfieldMessageToQueue() {
void DefaultBtInteractive::addAllowedFastMessageToQueue() {
if(peer->isFastExtensionEnabled()) {
std::deque<size_t> fastSet;
btContext->computeFastSet(fastSet, peer->ipaddr, allowedFastSetSize);
_btContext->computeFastSet(fastSet, peer->ipaddr, allowedFastSetSize);
for(std::deque<size_t>::const_iterator itr = fastSet.begin();
itr != fastSet.end(); itr++) {
dispatcher->addMessageToQueue(messageFactory->createAllowedFastMessage(*itr));
dispatcher->addMessageToQueue
(messageFactory->createAllowedFastMessage(*itr));
}
}
}
@ -208,16 +210,17 @@ void DefaultBtInteractive::decideChoking() {
void DefaultBtInteractive::checkHave() {
std::deque<size_t> indexes;
pieceStorage->getAdvertisedPieceIndexes(indexes, cuid, haveCheckPoint);
_pieceStorage->getAdvertisedPieceIndexes(indexes, cuid, haveCheckPoint);
haveCheckPoint.reset();
if(indexes.size() >= 20) {
if(peer->isFastExtensionEnabled() && pieceStorage->allDownloadFinished()) {
if(peer->isFastExtensionEnabled() && _pieceStorage->allDownloadFinished()) {
dispatcher->addMessageToQueue(messageFactory->createHaveAllMessage());
} else {
dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
}
} else {
for(std::deque<size_t>::iterator itr = indexes.begin(); itr != indexes.end(); itr++) {
for(std::deque<size_t>::iterator itr = indexes.begin();
itr != indexes.end(); itr++) {
dispatcher->addMessageToQueue(messageFactory->createHaveMessage(*itr));
}
}
@ -235,7 +238,7 @@ size_t DefaultBtInteractive::receiveMessages() {
size_t msgcount = 0;
for(int i = 0; i < 50; i++) {
if(maxDownloadSpeedLimit > 0) {
TransferStat stat = btContext->getOwnerRequestGroup()->calculateStat();
TransferStat stat = _btContext->getOwnerRequestGroup()->calculateStat();
if(maxDownloadSpeedLimit < stat.downloadSpeed) {
break;
}
@ -274,7 +277,7 @@ size_t DefaultBtInteractive::receiveMessages() {
}
void DefaultBtInteractive::decideInterest() {
if(pieceStorage->hasMissingPiece(peer)) {
if(_pieceStorage->hasMissingPiece(peer)) {
if(!peer->amInterested()) {
logger->debug(MSG_PEER_INTERESTED, cuid);
dispatcher->
@ -290,7 +293,7 @@ void DefaultBtInteractive::decideInterest() {
}
void DefaultBtInteractive::fillPiece(size_t maxMissingBlock) {
if(pieceStorage->hasMissingPiece(peer)) {
if(_pieceStorage->hasMissingPiece(peer)) {
size_t numMissingBlock = btRequestFactory->countMissingBlock();
@ -300,7 +303,7 @@ void DefaultBtInteractive::fillPiece(size_t maxMissingBlock) {
btRequestFactory->getTargetPieceIndexes(excludedIndexes);
while(numMissingBlock < maxMissingBlock) {
SharedHandle<Piece> piece =
pieceStorage->getMissingFastPiece(peer, excludedIndexes);
_pieceStorage->getMissingFastPiece(peer, excludedIndexes);
if(piece.isNull()) {
break;
} else {
@ -315,7 +318,7 @@ void DefaultBtInteractive::fillPiece(size_t maxMissingBlock) {
btRequestFactory->getTargetPieceIndexes(excludedIndexes);
while(numMissingBlock < maxMissingBlock) {
SharedHandle<Piece> piece =
pieceStorage->getMissingPiece(peer, excludedIndexes);
_pieceStorage->getMissingPiece(peer, excludedIndexes);
if(piece.isNull()) {
break;
} else {
@ -344,7 +347,7 @@ void DefaultBtInteractive::addRequests() {
0 : MAX_PENDING_REQUEST-dispatcher->countOutstandingRequest();
if(reqNumToCreate > 0) {
BtMessages requests;
if(pieceStorage->isEndGame()) {
if(_pieceStorage->isEndGame()) {
btRequestFactory->createRequestMessagesOnEndGame(requests, reqNumToCreate);
} else {
btRequestFactory->createRequestMessages(requests, reqNumToCreate);
@ -383,7 +386,8 @@ void DefaultBtInteractive::checkActiveInteraction()
inactiveCheckPoint.elapsed(interval)) {
// TODO change the message
throw DlAbortEx
(StringFormat("Disconnect peer because we are not interested each other after %u second(s).", interval).str());
(StringFormat("Disconnect peer because we are not interested each other"
" after %u second(s).", interval).str());
}
}
// Since the peers which are *just* connected and do nothing to improve
@ -403,7 +407,7 @@ void DefaultBtInteractive::addPeerExchangeMessage()
if(_pexCheckPoint.elapsed(UTPexExtensionMessage::DEFAULT_INTERVAL)) {
UTPexExtensionMessageHandle m
(new UTPexExtensionMessage(peer->getExtensionMessageID("ut_pex")));
const Peers& peers = peerStorage->getPeers();
const Peers& peers = _peerStorage->getPeers();
{
for(std::deque<SharedHandle<Peer> >::const_iterator i =
peers.begin(); i != peers.end() && !m->freshPeersAreFull(); ++i) {
@ -445,7 +449,7 @@ void DefaultBtInteractive::doInteractionProcessing() {
btRequestFactory->removeCompletedPiece();
decideInterest();
if(!pieceStorage->downloadFinished()) {
if(!_pieceStorage->downloadFinished()) {
addRequests();
}
@ -481,32 +485,61 @@ size_t DefaultBtInteractive::countOutstandingRequest()
return dispatcher->countOutstandingRequest();
}
void DefaultBtInteractive::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void DefaultBtInteractive::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void DefaultBtInteractive::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void DefaultBtInteractive::setPeer(const SharedHandle<Peer>& peer)
{
this->peer = peer;
}
void DefaultBtInteractive::setBtMessageReceiver(const BtMessageReceiverWeakHandle& receiver)
void DefaultBtInteractive::setBtMessageReceiver
(const SharedHandle<BtMessageReceiver>& receiver)
{
this->btMessageReceiver = receiver;
}
void DefaultBtInteractive::setDispatcher(const BtMessageDispatcherWeakHandle& dispatcher)
void DefaultBtInteractive::setDispatcher
(const SharedHandle<BtMessageDispatcher>& dispatcher)
{
this->dispatcher = dispatcher;
}
void DefaultBtInteractive::setBtRequestFactory(const BtRequestFactoryWeakHandle& factory)
void DefaultBtInteractive::setBtRequestFactory
(const SharedHandle<BtRequestFactory>& factory)
{
this->btRequestFactory = factory;
}
void DefaultBtInteractive::setPeerConnection(const PeerConnectionWeakHandle& peerConnection)
void DefaultBtInteractive::setPeerConnection
(const SharedHandle<PeerConnection>& peerConnection)
{
this->peerConnection = peerConnection;
}
void DefaultBtInteractive::setBtMessageFactory(const BtMessageFactoryWeakHandle& factory)
void DefaultBtInteractive::setExtensionMessageFactory
(const SharedHandle<ExtensionMessageFactory>& factory)
{
_extensionMessageFactory = factory;
}
void DefaultBtInteractive::setBtMessageFactory
(const SharedHandle<BtMessageFactory>& factory)
{
this->messageFactory = factory;
}

View File

@ -36,12 +36,17 @@
#define _D_DEFAULT_BT_INTERACTIVE_H_
#include "BtInteractive.h"
#include "BtContextAwareCommand.h"
#include "TimeA2.h"
#include <limits.h>
#include "TimeA2.h"
namespace aria2 {
class BtContext;
class BtRuntime;
class PieceStorage;
class PeerStorage;
class Peer;
class BtMessage;
class BtMessageReceiver;
@ -49,6 +54,7 @@ class BtMessageDispatcher;
class BtMessageFactory;
class BtRequestFactory;
class PeerConnection;
class ExtensionMessageFactory;
class DHTNode;
class Logger;
@ -85,16 +91,26 @@ public:
}
};
class DefaultBtInteractive : public BtInteractive, public BtContextAwareCommand {
class DefaultBtInteractive : public BtInteractive {
private:
int32_t cuid;
SharedHandle<BtContext> _btContext;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<Peer> peer;
WeakHandle<BtMessageReceiver> btMessageReceiver;
WeakHandle<BtMessageDispatcher> dispatcher;
WeakHandle<BtRequestFactory> btRequestFactory;
WeakHandle<PeerConnection> peerConnection;
WeakHandle<BtMessageFactory> messageFactory;
SharedHandle<BtMessageReceiver> btMessageReceiver;
SharedHandle<BtMessageDispatcher> dispatcher;
SharedHandle<BtRequestFactory> btRequestFactory;
SharedHandle<PeerConnection> peerConnection;
SharedHandle<BtMessageFactory> messageFactory;
SharedHandle<ExtensionMessageFactory> _extensionMessageFactory;
WeakHandle<DHTNode> _localNode;
@ -163,17 +179,26 @@ public:
this->cuid = cuid;
}
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setPeer(const SharedHandle<Peer>& peer);
void setBtMessageReceiver(const WeakHandle<BtMessageReceiver>& receiver);
void setBtMessageReceiver(const SharedHandle<BtMessageReceiver>& receiver);
void setDispatcher(const WeakHandle<BtMessageDispatcher>& dispatcher);
void setDispatcher(const SharedHandle<BtMessageDispatcher>& dispatcher);
void setBtRequestFactory(const WeakHandle<BtRequestFactory>& factory);
void setBtRequestFactory(const SharedHandle<BtRequestFactory>& factory);
void setPeerConnection(const WeakHandle<PeerConnection>& peerConnection);
void setPeerConnection(const SharedHandle<PeerConnection>& peerConnection);
void setBtMessageFactory(const WeakHandle<BtMessageFactory>& factory);
void setBtMessageFactory(const SharedHandle<BtMessageFactory>& factory);
void setExtensionMessageFactory
(const SharedHandle<ExtensionMessageFactory>& factory);
void setKeepAliveInterval(time_t keepAliveInterval) {
this->keepAliveInterval = keepAliveInterval;

View File

@ -33,6 +33,9 @@
*/
/* copyright --> */
#include "DefaultBtMessageDispatcher.h"
#include <algorithm>
#include "prefs.h"
#include "BtAbortOutstandingRequestEvent.h"
#include "BtCancelSendingPieceEvent.h"
@ -44,13 +47,11 @@
#include "PeerStorage.h"
#include "PieceStorage.h"
#include "BtMessage.h"
#include "BtRegistry.h"
#include "Peer.h"
#include "Piece.h"
#include "LogFactory.h"
#include "Logger.h"
#include "a2functional.h"
#include <algorithm>
namespace aria2 {
@ -86,7 +87,7 @@ void DefaultBtMessageDispatcher::sendMessages() {
messageQueue.pop_front();
if(maxUploadSpeedLimit > 0 &&
msg->isUploading() && !msg->isSendingInProgress()) {
TransferStat stat = peerStorage->calculateStat();
TransferStat stat = _peerStorage->calculateStat();
if(maxUploadSpeedLimit < stat.getUploadSpeed()) {
tempQueue.push_back(msg);
continue;
@ -228,7 +229,7 @@ public:
void DefaultBtMessageDispatcher::doChokedAction()
{
std::for_each(requestSlots.begin(), requestSlots.end(),
ProcessChokedRequestSlot(cuid, peer, pieceStorage));
ProcessChokedRequestSlot(cuid, peer, _pieceStorage));
requestSlots.erase(std::remove_if(requestSlots.begin(), requestSlots.end(),
FindChokedRequestSlot(peer)),
@ -332,13 +333,13 @@ void DefaultBtMessageDispatcher::checkRequestSlotAndDoNecessaryThing()
std::for_each(requestSlots.begin(), requestSlots.end(),
ProcessStaleRequestSlot(cuid,
peer,
pieceStorage,
_pieceStorage,
this,
messageFactory,
now,
requestTimeout));
requestSlots.erase(std::remove_if(requestSlots.begin(), requestSlots.end(),
FindStaleRequestSlot(pieceStorage,
FindStaleRequestSlot(_pieceStorage,
now,
requestTimeout)),
requestSlots.end());
@ -437,8 +438,18 @@ void DefaultBtMessageDispatcher::setPeer(const SharedHandle<Peer>& peer)
void DefaultBtMessageDispatcher::setBtContext(const BtContextHandle& btContext)
{
this->btContext = btContext;
this->pieceStorage = PIECE_STORAGE(btContext);
this->peerStorage = PEER_STORAGE(btContext);
}
void DefaultBtMessageDispatcher::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void DefaultBtMessageDispatcher::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void DefaultBtMessageDispatcher::setBtMessageFactory(const WeakHandle<BtMessageFactory>& factory)

View File

@ -55,8 +55,8 @@ private:
std::deque<SharedHandle<BtMessage> > messageQueue;
std::deque<RequestSlot> requestSlots;
SharedHandle<BtContext> btContext;
SharedHandle<PeerStorage> peerStorage;
SharedHandle<PieceStorage> pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PieceStorage> _pieceStorage;
WeakHandle<BtMessageFactory> messageFactory;
SharedHandle<Peer> peer;
unsigned int maxUploadSpeedLimit;
@ -111,6 +111,10 @@ public:
void setBtContext(const SharedHandle<BtContext>& btContext);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setBtMessageFactory(const WeakHandle<BtMessageFactory>& factory);
void setCuid(int32_t cuid) {

View File

@ -65,10 +65,11 @@
#include "ExtensionMessage.h"
#include "Peer.h"
#include "Piece.h"
#include "BtRegistry.h"
#include "BtContext.h"
#include "PieceStorage.h"
#include "PeerStorage.h"
#include "StringFormat.h"
#include "ExtensionMessageFactory.h"
namespace aria2 {
@ -98,7 +99,12 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
msg = BtInterestedMessage::create(data, dataLength);
break;
case BtNotInterestedMessage::ID:
msg = BtNotInterestedMessage::create(data, dataLength);
{
SharedHandle<BtNotInterestedMessage> m =
BtNotInterestedMessage::create(data, dataLength);
m->setPeerStorage(_peerStorage);
msg = m;
}
break;
case BtHaveMessage::ID:
msg = BtHaveMessage::create(data, dataLength);
@ -123,7 +129,7 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
BtMessageValidatorHandle validator
(new BtRequestMessageValidator(temp.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(temp->getIndex())));
_pieceStorage->getPieceLength(temp->getIndex())));
temp->setBtMessageValidator(validator);
msg = temp;
break;
@ -133,7 +139,7 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
BtMessageValidatorHandle validator
(new BtCancelMessageValidator(temp.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(temp->getIndex())));
_pieceStorage->getPieceLength(temp->getIndex())));
temp->setBtMessageValidator(validator);
msg = temp;
break;
@ -143,7 +149,7 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
BtMessageValidatorHandle validator
(new BtPieceMessageValidator(temp.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(temp->getIndex())));
_pieceStorage->getPieceLength(temp->getIndex())));
temp->setBtMessageValidator(validator);
msg = temp;
break;
@ -159,7 +165,7 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
BtMessageValidatorHandle validator
(new BtRejectMessageValidator(temp.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(temp->getIndex())));
_pieceStorage->getPieceLength(temp->getIndex())));
temp->setBtMessageValidator(validator);
msg = temp;
break;
@ -193,7 +199,8 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
}
case BtExtendedMessage::ID: {
if(peer->isExtendedMessagingEnabled()) {
msg = BtExtendedMessage::create(btContext, peer, data, dataLength);
msg = BtExtendedMessage::create(_extensionMessageFactory,
peer, data, dataLength);
} else {
throw DlAbortEx("Received extended message from peer during a session with extended messaging disabled.");
}
@ -211,6 +218,7 @@ void DefaultBtMessageFactory::setCommonProperty(const AbstractBtMessageHandle& m
msg->setCuid(cuid);
msg->setPeer(peer);
msg->setBtContext(btContext);
msg->setPieceStorage(_pieceStorage);
msg->setBtMessageDispatcher(dispatcher);
msg->setBtRequestFactory(requestFactory);
msg->setBtMessageFactory(WeakHandle<BtMessageFactory>(this));
@ -254,7 +262,7 @@ DefaultBtMessageFactory::createRequestMessage(const PieceHandle& piece, size_t b
BtMessageValidatorHandle validator
(new BtRequestMessageValidator(msg.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(msg->getIndex())));
_pieceStorage->getPieceLength(msg->getIndex())));
msg->setBtMessageValidator(validator);
setCommonProperty(msg);
return msg;
@ -267,7 +275,7 @@ DefaultBtMessageFactory::createCancelMessage(size_t index, uint32_t begin, size_
BtMessageValidatorHandle validator
(new BtCancelMessageValidator(msg.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(index)));
_pieceStorage->getPieceLength(index)));
msg->setBtMessageValidator(validator);
setCommonProperty(msg);
return msg;
@ -280,7 +288,7 @@ DefaultBtMessageFactory::createPieceMessage(size_t index, uint32_t begin, size_t
BtMessageValidatorHandle validator
(new BtPieceMessageValidator(msg.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(index)));
_pieceStorage->getPieceLength(index)));
msg->setBtMessageValidator(validator);
setCommonProperty(msg);
return msg;
@ -334,8 +342,8 @@ BtMessageHandle
DefaultBtMessageFactory::createBitfieldMessage()
{
BtBitfieldMessageHandle msg
(new BtBitfieldMessage(pieceStorage->getBitfield(),
pieceStorage->getBitfieldLength()));
(new BtBitfieldMessage(_pieceStorage->getBitfield(),
_pieceStorage->getBitfieldLength()));
SharedHandle<BtMessageValidator> v
(new BtBitfieldMessageValidator(msg.get(),
btContext->getNumPieces()));
@ -375,7 +383,7 @@ DefaultBtMessageFactory::createRejectMessage(size_t index, uint32_t begin, size_
BtMessageValidatorHandle validator
(new BtRejectMessageValidator(msg.get(),
btContext->getNumPieces(),
pieceStorage->getPieceLength(index)));
_pieceStorage->getPieceLength(index)));
msg->setBtMessageValidator(validator);
setCommonProperty(msg);
return msg;
@ -427,7 +435,18 @@ void DefaultBtMessageFactory::setPeer(const SharedHandle<Peer>& peer)
void DefaultBtMessageFactory::setBtContext(const SharedHandle<BtContext>& btContext)
{
this->btContext = btContext;
this->pieceStorage = PIECE_STORAGE(btContext);
}
void DefaultBtMessageFactory::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void DefaultBtMessageFactory::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void DefaultBtMessageFactory::setBtMessageDispatcher(const WeakHandle<BtMessageDispatcher>& dispatcher)
@ -435,6 +454,12 @@ void DefaultBtMessageFactory::setBtMessageDispatcher(const WeakHandle<BtMessageD
this->dispatcher = dispatcher;
}
void DefaultBtMessageFactory::setExtensionMessageFactory
(const SharedHandle<ExtensionMessageFactory>& factory)
{
_extensionMessageFactory = factory;
}
void DefaultBtMessageFactory::setLocalNode(const WeakHandle<DHTNode>& localNode)
{
_localNode = localNode;

View File

@ -40,12 +40,14 @@
namespace aria2 {
class BtContext;
class PieceStorage;
class PeerStorage;
class Peer;
class AbstractBtMessage;
class BtMessageDispatcher;
class BtRequestFactory;
class PeerConnection;
class PieceStorage;
class ExtensionMessageFactory;
class DHTNode;
class DHTRoutingTable;
class DHTTaskQueue;
@ -55,7 +57,8 @@ class DefaultBtMessageFactory : public BtMessageFactory {
private:
int32_t cuid;
SharedHandle<BtContext> btContext;
SharedHandle<PieceStorage> pieceStorage;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<Peer> peer;
bool _dhtEnabled;
@ -66,6 +69,8 @@ private:
WeakHandle<PeerConnection> peerConnection;
SharedHandle<ExtensionMessageFactory> _extensionMessageFactory;
WeakHandle<DHTNode> _localNode;
WeakHandle<DHTRoutingTable> _routingTable;
@ -131,6 +136,10 @@ public:
void setBtContext(const SharedHandle<BtContext>& btContext);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setCuid(int32_t cuid) {
this->cuid = cuid;
}
@ -145,6 +154,9 @@ public:
void setPeerConnection(const WeakHandle<PeerConnection>& connection);
void setExtensionMessageFactory
(const SharedHandle<ExtensionMessageFactory>& factory);
void setLocalNode(const WeakHandle<DHTNode>& localNode);
void setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable);

View File

@ -33,17 +33,18 @@
*/
/* copyright --> */
#include "DefaultBtMessageReceiver.h"
#include <cstring>
#include "BtHandshakeMessage.h"
#include "message.h"
#include "BtContext.h"
#include "BtRegistry.h"
#include "Peer.h"
#include "PeerConnection.h"
#include "BtMessageDispatcher.h"
#include "BtMessageFactory.h"
#include "Logger.h"
#include "LogFactory.h"
#include <cstring>
namespace aria2 {

View File

@ -33,6 +33,11 @@
*/
/* copyright --> */
#include "DefaultBtProgressInfoFile.h"
#include <cerrno>
#include <cstring>
#include <fstream>
#include "BtContext.h"
#include "PieceStorage.h"
#include "Piece.h"
@ -41,7 +46,6 @@
#include "BitfieldMan.h"
#include "Option.h"
#include "TransferStat.h"
#include "BtRegistry.h"
#include "LogFactory.h"
#include "Logger.h"
#include "prefs.h"
@ -52,9 +56,6 @@
#include "a2io.h"
#include "DownloadFailureException.h"
#include "StringFormat.h"
#include <fstream>
#include <cerrno>
#include <cstring>
namespace aria2 {
@ -86,7 +87,7 @@ void DefaultBtProgressInfoFile::updateFilename()
bool DefaultBtProgressInfoFile::isTorrentDownload()
{
return !dynamic_pointer_cast<BtContext>(_dctx).isNull();
return !_btRuntime.isNull();
}
// Since version 0001, Integers are saved in binary form, network byte order.
@ -138,8 +139,7 @@ void DefaultBtProgressInfoFile::save() {
// uploadLength: 64 bits
uint64_t uploadLengthNL = 0;
if(torrentDownload) {
BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
TransferStat stat = PEER_STORAGE(btContext)->calculateStat();
TransferStat stat = _peerStorage->calculateStat();
uploadLengthNL = hton64(stat.getAllTimeUploadLength());
}
o.write(reinterpret_cast<const char*>(&uploadLengthNL),
@ -267,8 +267,7 @@ void DefaultBtProgressInfoFile::load()
uploadLength = ntoh64(uploadLength);
}
if(isTorrentDownload()) {
BT_RUNTIME(dynamic_pointer_cast<BtContext>(_dctx))->
setUploadLengthAtStartup(uploadLength);
_btRuntime->setUploadLengthAtStartup(uploadLength);
}
// TODO implement the conversion mechanism between different piece length.
@ -401,4 +400,16 @@ bool DefaultBtProgressInfoFile::exists()
}
}
void DefaultBtProgressInfoFile::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void DefaultBtProgressInfoFile::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
} // namespace aria2

View File

@ -41,6 +41,8 @@ namespace aria2 {
class DownloadContext;
class PieceStorage;
class PeerStorage;
class BtRuntime;
class Logger;
class Option;
@ -48,6 +50,9 @@ class DefaultBtProgressInfoFile : public BtProgressInfoFile {
private:
SharedHandle<DownloadContext> _dctx;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<BtRuntime> _btRuntime;
const Option* _option;
Logger* _logger;
std::string _filename;
@ -76,6 +81,10 @@ public:
// re-set filename using current _dctx.
virtual void updateFilename();
// for torrents
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
};
} // namespace aria2

View File

@ -33,6 +33,9 @@
*/
/* copyright --> */
#include "DefaultBtRequestFactory.h"
#include <algorithm>
#include "LogFactory.h"
#include "Logger.h"
#include "Piece.h"
@ -42,9 +45,7 @@
#include "BtMessageDispatcher.h"
#include "BtMessageFactory.h"
#include "BtMessage.h"
#include "BtRegistry.h"
#include "a2functional.h"
#include <algorithm>
namespace aria2 {
@ -93,7 +94,7 @@ void DefaultBtRequestFactory::removeTargetPiece(const PieceHandle& piece) {
pieces.erase(std::remove(pieces.begin(), pieces.end(), piece),
pieces.end());
dispatcher->doAbortOutstandingRequestAction(piece);
pieceStorage->cancelPiece(piece);
_pieceStorage->cancelPiece(piece);
}
class ProcessChokedPiece {
@ -129,7 +130,7 @@ public:
void DefaultBtRequestFactory::doChokedAction()
{
std::for_each(pieces.begin(), pieces.end(),
ProcessChokedPiece(peer, pieceStorage));
ProcessChokedPiece(peer, _pieceStorage));
pieces.erase(std::remove_if(pieces.begin(), pieces.end(),
FindChokedPiece(peer)),
pieces.end());
@ -138,7 +139,7 @@ void DefaultBtRequestFactory::doChokedAction()
void DefaultBtRequestFactory::removeAllTargetPiece() {
for(Pieces::iterator itr = pieces.begin(); itr != pieces.end(); ++itr) {
dispatcher->doAbortOutstandingRequestAction(*itr);
pieceStorage->cancelPiece(*itr);
_pieceStorage->cancelPiece(*itr);
}
pieces.clear();
}
@ -225,7 +226,12 @@ std::deque<SharedHandle<Piece> >& DefaultBtRequestFactory::getTargetPieces()
void DefaultBtRequestFactory::setBtContext(const SharedHandle<BtContext>& btContext)
{
this->btContext = btContext;
this->pieceStorage = PIECE_STORAGE(btContext);
}
void DefaultBtRequestFactory::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void DefaultBtRequestFactory::setPeer(const SharedHandle<Peer>& peer)

View File

@ -51,7 +51,7 @@ class DefaultBtRequestFactory : public BtRequestFactory {
private:
int32_t cuid;
SharedHandle<BtContext> btContext;
SharedHandle<PieceStorage> pieceStorage;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<Peer> peer;
WeakHandle<BtMessageDispatcher> dispatcher;
WeakHandle<BtMessageFactory> messageFactory;
@ -95,6 +95,8 @@ public:
void setBtContext(const SharedHandle<BtContext>& btContext);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setPeer(const SharedHandle<Peer>& peer);
void setBtMessageDispatcher(const WeakHandle<BtMessageDispatcher>& dispatcher);

View File

@ -40,8 +40,8 @@
#include "UTPexExtensionMessage.h"
#include "LogFactory.h"
#include "Logger.h"
#include "BtRegistry.h"
#include "StringFormat.h"
#include "PeerStorage.h"
namespace aria2 {
@ -76,8 +76,8 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t
if(extensionName == "ut_pex") {
// uTorrent compatible Peer-Exchange
UTPexExtensionMessageHandle m =
UTPexExtensionMessage::create(_btContext, data, length);
m->setBtContext(_btContext);
UTPexExtensionMessage::create(data, length);
m->setPeerStorage(_peerStorage);
return m;
} else {
throw DlAbortEx
@ -92,6 +92,12 @@ void DefaultExtensionMessageFactory::setBtContext(const BtContextHandle& btConte
_btContext = btContext;
}
void DefaultExtensionMessageFactory::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void DefaultExtensionMessageFactory::setPeer(const PeerHandle& peer)
{
_peer = peer;

View File

@ -40,6 +40,7 @@
namespace aria2 {
class BtContext;
class PeerStorage;
class Peer;
class Logger;
@ -47,6 +48,8 @@ class DefaultExtensionMessageFactory:public ExtensionMessageFactory {
private:
SharedHandle<BtContext> _btContext;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<Peer> _peer;
Logger* _logger;
@ -64,6 +67,8 @@ public:
void setBtContext(const SharedHandle<BtContext>& btContext);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setPeer(const SharedHandle<Peer>& peer);
};

View File

@ -33,9 +33,11 @@
*/
/* copyright --> */
#include "DefaultPeerStorage.h"
#include <algorithm>
#include "LogFactory.h"
#include "Logger.h"
#include "BtRegistry.h"
#include "message.h"
#include "a2time.h"
#include "Peer.h"
@ -44,7 +46,6 @@
#include "BtSeederStateChoke.h"
#include "BtLeecherStateChoke.h"
#include "PieceStorage.h"
#include <algorithm>
namespace aria2 {
@ -53,7 +54,6 @@ DefaultPeerStorage::DefaultPeerStorage(const BtContextHandle& btContext,
btContext(btContext),
option(option),
logger(LogFactory::getInstance()),
btRuntime(BT_RUNTIME(btContext)),
maxPeerListSize(BtRuntime::MAX_PEERS+(BtRuntime::MAX_PEERS >> 2)),
removedPeerSessionDownloadLength(0),
removedPeerSessionUploadLength(0),
@ -206,7 +206,7 @@ TransferStat DefaultPeerStorage::calculateStat() {
TransferStat stat = std::for_each(peers.begin(), peers.end(), CalculateStat()).getTransferStat();
stat.sessionDownloadLength += removedPeerSessionDownloadLength;
stat.sessionUploadLength += removedPeerSessionUploadLength;
stat.setAllTimeUploadLength(btRuntime->getUploadLengthAtStartup()+
stat.setAllTimeUploadLength(_btRuntime->getUploadLengthAtStartup()+
stat.getSessionUploadLength());
return stat;
}
@ -252,7 +252,7 @@ void DefaultPeerStorage::returnPeer(const PeerHandle& peer)
bool DefaultPeerStorage::chokeRoundIntervalElapsed()
{
const time_t CHOKE_ROUND_INTERVAL = 10;
if(PIECE_STORAGE(btContext)->downloadFinished()) {
if(_pieceStorage->downloadFinished()) {
return _seederStateChoke->getLastRound().elapsed(CHOKE_ROUND_INTERVAL);
} else {
return _leecherStateChoke->getLastRound().elapsed(CHOKE_ROUND_INTERVAL);
@ -263,11 +263,21 @@ void DefaultPeerStorage::executeChoke()
{
std::deque<SharedHandle<Peer> > activePeers;
getActivePeers(activePeers);
if(PIECE_STORAGE(btContext)->downloadFinished()) {
if(_pieceStorage->downloadFinished()) {
return _seederStateChoke->executeChoke(activePeers);
} else {
return _leecherStateChoke->executeChoke(activePeers);
}
}
void DefaultPeerStorage::setPieceStorage(const SharedHandle<PieceStorage>& ps)
{
_pieceStorage = ps;
}
void DefaultPeerStorage::setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
} // namespace aria2

View File

@ -45,14 +45,16 @@ class Logger;
class BtRuntime;
class BtSeederStateChoke;
class BtLeecherStateChoke;
class PieceStorage;
class DefaultPeerStorage : public PeerStorage {
private:
SharedHandle<BtContext> btContext;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PieceStorage> _pieceStorage;
const Option* option;
std::deque<SharedHandle<Peer> > peers;
Logger* logger;
SharedHandle<BtRuntime> btRuntime;
size_t maxPeerListSize;
uint64_t removedPeerSessionDownloadLength;
uint64_t removedPeerSessionUploadLength;
@ -67,12 +69,6 @@ public:
virtual ~DefaultPeerStorage();
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime) {
this->btRuntime = btRuntime;
}
SharedHandle<BtRuntime> getBtRuntime() const { return btRuntime; }
virtual bool addPeer(const SharedHandle<Peer>& peer);
size_t countPeer() const;
@ -107,6 +103,9 @@ public:
void onReturningPeer(const SharedHandle<Peer>& peer);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
};
} // namespace aria2

View File

@ -33,6 +33,14 @@
*/
/* copyright --> */
#include "DownloadEngine.h"
#include <signal.h>
#include <cstring>
#include <cerrno>
#include <algorithm>
#include <numeric>
#ifdef ENABLE_ASYNC_DNS
#include "AsyncNameResolver.h"
#endif // ENABLE_ASYNC_DNS
@ -54,11 +62,14 @@
#include "ServerStatMan.h"
#include "CookieStorage.h"
#include "A2STR.h"
#include <signal.h>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <cerrno>
#include "BtRegistry.h"
#include "BtContext.h"
#include "PeerStorage.h"
#include "PieceStorage.h"
#include "BtAnnounce.h"
#include "BtRuntime.h"
#include "BtProgressInfoFile.h"
namespace aria2 {
@ -399,7 +410,8 @@ void AsyncNameResolverEntry::process(fd_set* rfdsPtr, fd_set* wfdsPtr)
DownloadEngine::DownloadEngine():logger(LogFactory::getInstance()),
_haltRequested(false),
_noWait(false),
_cookieStorage(new CookieStorage())
_cookieStorage(new CookieStorage()),
_btRegistry(new BtRegistry())
{
#ifdef HAVE_EPOLL
@ -1016,6 +1028,11 @@ DownloadEngine::popPooledSocket
return s;
}
SharedHandle<BtRegistry> DownloadEngine::getBtRegistry() const
{
return _btRegistry;
}
DownloadEngine::SocketPoolEntry::SocketPoolEntry
(const SharedHandle<SocketCore>& socket,
const std::map<std::string, std::string>& options,

View File

@ -36,6 +36,15 @@
#define _D_DOWNLOAD_ENGINE_H_
#include "common.h"
#ifdef HAVE_EPOLL_CREATE
# include <sys/epoll.h>
#endif // HAVE_EPOLL_CREATE
#include <string>
#include <deque>
#include <map>
#include "SharedHandle.h"
#include "Command.h"
#include "a2netcompat.h"
@ -44,12 +53,6 @@
#ifdef ENABLE_ASYNC_DNS
# include "AsyncNameResolver.h"
#endif // ENABLE_ASYNC_DNS
#include <string>
#include <deque>
#include <map>
#ifdef HAVE_EPOLL
# include <sys/epoll.h>
#endif // HAVE_EPOLL
namespace aria2 {
@ -61,6 +64,7 @@ class StatCalc;
class CheckIntegrityMan;
class SocketCore;
class CookieStorage;
class BtRegistry;
class CommandEvent
{
@ -292,6 +296,8 @@ private:
SharedHandle<CookieStorage> _cookieStorage;
SharedHandle<BtRegistry> _btRegistry;
void shortSleep() const;
/**
@ -405,6 +411,8 @@ public:
uint16_t port);
SharedHandle<CookieStorage> getCookieStorage() const;
SharedHandle<BtRegistry> getBtRegistry() const;
};
typedef SharedHandle<DownloadEngine> DownloadEngineHandle;

View File

@ -46,10 +46,8 @@
#include "PeerConnection.h"
#include "BtContext.h"
#include "BtRuntime.h"
#include "PieceStorage.h"
#include "PeerStorage.h"
#include "BtAnnounce.h"
#include "BtProgressInfoFile.h"
#include "PieceStorage.h"
#include "Option.h"
#include "MSEHandshake.h"
#include "ARC4Encryptor.h"
@ -63,11 +61,13 @@ InitiatorMSEHandshakeCommand::InitiatorMSEHandshakeCommand
const SharedHandle<Peer>& p,
DownloadEngine* e,
const SharedHandle<BtContext>& btContext,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<SocketCore>& s):
PeerAbstractCommand(cuid, p, e, s),
BtContextAwareCommand(btContext),
RequestGroupAware(requestGroup),
_btContext(btContext),
_btRuntime(btRuntime),
_sequence(INITIATOR_SEND_KEY),
_mseHandshake(new MSEHandshake(cuid, socket, e->option))
{
@ -75,12 +75,12 @@ InitiatorMSEHandshakeCommand::InitiatorMSEHandshakeCommand
setWriteCheckSocket(socket);
setTimeout(e->option->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
btRuntime->increaseConnections();
_btRuntime->increaseConnections();
}
InitiatorMSEHandshakeCommand::~InitiatorMSEHandshakeCommand()
{
btRuntime->decreaseConnections();
_btRuntime->decreaseConnections();
delete _mseHandshake;
}
@ -112,7 +112,7 @@ bool InitiatorMSEHandshakeCommand::executeInternal() {
break;
case INITIATOR_WAIT_KEY: {
if(_mseHandshake->receivePublicKey()) {
_mseHandshake->initCipher(btContext->getInfoHash());
_mseHandshake->initCipher(_btContext->getInfoHash());
if(_mseHandshake->sendInitiatorStep2()) {
_sequence = INITIATOR_FIND_VC_MARKER;
} else {
@ -148,11 +148,13 @@ bool InitiatorMSEHandshakeCommand::executeInternal() {
peerConnection->enableEncryption(_mseHandshake->getEncryptor(),
_mseHandshake->getDecryptor());
}
Command* c =
new PeerInteractionCommand(cuid, _requestGroup, peer, e, btContext,
PeerInteractionCommand* c =
new PeerInteractionCommand(cuid, _requestGroup, peer, e, _btContext,
_btRuntime, _pieceStorage,
socket,
PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE,
peerConnection);
c->setPeerStorage(_peerStorage);
e->commands.push_back(c);
return true;
}
@ -167,21 +169,25 @@ bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait)
{
if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
logger->info("CUID#%d - Establishing connection using legacy BitTorrent handshake is disabled by preference.", cuid);
if(peerStorage->isPeerAvailable() && btRuntime->lessThanEqMinPeers()) {
SharedHandle<Peer> peer = peerStorage->getUnusedPeer();
if(_peerStorage->isPeerAvailable() && _btRuntime->lessThanEqMinPeers()) {
SharedHandle<Peer> peer = _peerStorage->getUnusedPeer();
peer->usedBy(CUIDCounterSingletonHolder::instance()->newID());
Command* command =
new PeerInitiateConnectionCommand(peer->usedBy(), _requestGroup, peer, e,
btContext);
PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(peer->usedBy(), _requestGroup, peer,
e, _btContext, _btRuntime);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
e->commands.push_back(command);
}
return true;
} else {
// try legacy BitTorrent handshake
logger->info("CUID#%d - Retry using legacy BitTorrent handshake.", cuid);
Command* command =
new PeerInitiateConnectionCommand(cuid, _requestGroup, peer, e, btContext,
false);
PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(cuid, _requestGroup, peer, e,
_btContext, _btRuntime, false);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
e->commands.push_back(command);
return true;
}
@ -190,13 +196,25 @@ bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait)
void InitiatorMSEHandshakeCommand::onAbort()
{
if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
peerStorage->returnPeer(peer);
_peerStorage->returnPeer(peer);
}
}
bool InitiatorMSEHandshakeCommand::exitBeforeExecute()
{
return btRuntime->isHalt();
return _btRuntime->isHalt();
}
void InitiatorMSEHandshakeCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void InitiatorMSEHandshakeCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
} // namespace aria2

View File

@ -37,14 +37,16 @@
#include "PeerAbstractCommand.h"
#include "RequestGroupAware.h"
#include "BtContextAwareCommand.h"
namespace aria2 {
class BtContext;
class PeerStorage;
class PieceStorage;
class BtRuntime;
class MSEHandshake;
class InitiatorMSEHandshakeCommand : public PeerAbstractCommand,
public BtContextAwareCommand,
public RequestGroupAware
{
public:
@ -58,6 +60,14 @@ public:
INITIATOR_RECEIVE_PAD_D,
};
private:
SharedHandle<BtContext> _btContext;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<BtRuntime> _btRuntime;
Seq _sequence;
MSEHandshake* _mseHandshake;
protected:
@ -71,10 +81,14 @@ public:
const SharedHandle<Peer>& peer,
DownloadEngine* e,
const SharedHandle<BtContext>& btContext,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<SocketCore>& s);
virtual ~InitiatorMSEHandshakeCommand();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
};
} // namespace aria2

View File

@ -33,6 +33,10 @@
*/
/* copyright --> */
#include "MSEHandshake.h"
#include <cstring>
#include <cassert>
#include "message.h"
#include "DlAbortEx.h"
#include "LogFactory.h"
@ -46,13 +50,10 @@
#include "MessageDigestHelper.h"
#include "SimpleRandomizer.h"
#include "Util.h"
#include "BtRegistry.h"
#include "BtContext.h"
#include "prefs.h"
#include "Option.h"
#include "StringFormat.h"
#include <cstring>
#include <cassert>
namespace aria2 {
@ -424,14 +425,14 @@ bool MSEHandshake::findReceiverHashMarker()
return true;
}
bool MSEHandshake::receiveReceiverHashAndPadCLength()
bool MSEHandshake::receiveReceiverHashAndPadCLength
(const std::deque<SharedHandle<BtContext> >& btContexts)
{
size_t r = 20+VC_LENGTH+CRYPTO_BITFIELD_LENGTH+2/*PadC length*/-_rbufLength;
if(r > receiveNBytes(r)) {
return false;
}
// resolve info hash
std::deque<SharedHandle<BtContext> > btContexts = BtRegistry::getAllBtContext();
// pointing to the position of HASH('req2', SKEY) xor HASH('req3', S)
unsigned char* rbufptr = _rbuf;
SharedHandle<BtContext> btContext;

View File

@ -36,6 +36,9 @@
#define _D_MSE_HANDSHAKE_H_
#include "common.h"
#include <deque>
#include "SharedHandle.h"
#include "BtConstants.h"
#include "SocketBuffer.h"
@ -48,6 +51,7 @@ class SocketCore;
class DHKeyExchange;
class ARC4Encryptor;
class ARC4Decryptor;
class BtContext;
class MSEHandshake {
public:
@ -153,7 +157,8 @@ public:
bool findReceiverHashMarker();
bool receiveReceiverHashAndPadCLength();
bool receiveReceiverHashAndPadCLength
(const std::deque<SharedHandle<BtContext> >& btContexts);
bool receiveReceiverIALength();

View File

@ -252,7 +252,6 @@ SRCS += MetaEntry.h\
BtAnnounce.cc BtAnnounce.h\
DefaultBtAnnounce.cc DefaultBtAnnounce.h\
BtRuntime.h\
BtContextAwareCommand.cc BtContextAwareCommand.h\
BtMessage.h\
AbstractBtMessage.cc AbstractBtMessage.h\
SimpleBtMessage.cc SimpleBtMessage.h\

View File

@ -81,7 +81,6 @@ bin_PROGRAMS = aria2c$(EXEEXT)
@ENABLE_BITTORRENT_TRUE@ BtAnnounce.cc BtAnnounce.h\
@ENABLE_BITTORRENT_TRUE@ DefaultBtAnnounce.cc DefaultBtAnnounce.h\
@ENABLE_BITTORRENT_TRUE@ BtRuntime.h\
@ENABLE_BITTORRENT_TRUE@ BtContextAwareCommand.cc BtContextAwareCommand.h\
@ENABLE_BITTORRENT_TRUE@ BtMessage.h\
@ENABLE_BITTORRENT_TRUE@ AbstractBtMessage.cc AbstractBtMessage.h\
@ENABLE_BITTORRENT_TRUE@ SimpleBtMessage.cc SimpleBtMessage.h\
@ -446,9 +445,8 @@ am__libaria2c_a_SOURCES_DIST = Socket.h SocketCore.cc SocketCore.h \
DefaultBtContext.h PeerStorage.h DefaultPeerStorage.cc \
DefaultPeerStorage.h BtAnnounce.cc BtAnnounce.h \
DefaultBtAnnounce.cc DefaultBtAnnounce.h BtRuntime.h \
BtContextAwareCommand.cc BtContextAwareCommand.h BtMessage.h \
AbstractBtMessage.cc AbstractBtMessage.h SimpleBtMessage.cc \
SimpleBtMessage.h BtAllowedFastMessage.cc \
BtMessage.h AbstractBtMessage.cc AbstractBtMessage.h \
SimpleBtMessage.cc SimpleBtMessage.h BtAllowedFastMessage.cc \
BtAllowedFastMessage.h BtBitfieldMessage.cc \
BtBitfieldMessage.h BtCancelMessage.cc BtCancelMessage.h \
BtChokeMessage.cc BtChokeMessage.h BtHaveAllMessage.cc \
@ -608,7 +606,6 @@ am__libaria2c_a_SOURCES_DIST = Socket.h SocketCore.cc SocketCore.h \
@ENABLE_BITTORRENT_TRUE@ DefaultPeerStorage.$(OBJEXT) \
@ENABLE_BITTORRENT_TRUE@ BtAnnounce.$(OBJEXT) \
@ENABLE_BITTORRENT_TRUE@ DefaultBtAnnounce.$(OBJEXT) \
@ENABLE_BITTORRENT_TRUE@ BtContextAwareCommand.$(OBJEXT) \
@ENABLE_BITTORRENT_TRUE@ AbstractBtMessage.$(OBJEXT) \
@ENABLE_BITTORRENT_TRUE@ SimpleBtMessage.$(OBJEXT) \
@ENABLE_BITTORRENT_TRUE@ BtAllowedFastMessage.$(OBJEXT) \
@ -1261,7 +1258,6 @@ distclean-compile:
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtCheckIntegrityEntry.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtChokeMessage.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtContext.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtContextAwareCommand.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtDependency.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtExtendedMessage.Po@am__quote@
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BtFileAllocationEntry.Po@am__quote@

View File

@ -42,23 +42,34 @@ namespace aria2 {
PeerChokeCommand::PeerChokeCommand(int32_t cuid,
DownloadEngine* e,
const BtContextHandle& btContext):
const SharedHandle<BtContext>& btContext):
Command(cuid),
BtContextAwareCommand(btContext),
e(e)
{}
e(e),
_btContext(btContext) {}
PeerChokeCommand::~PeerChokeCommand() {}
bool PeerChokeCommand::execute() {
if(btRuntime->isHalt()) {
if(_btRuntime->isHalt()) {
return true;
}
if(peerStorage->chokeRoundIntervalElapsed()) {
peerStorage->executeChoke();
if(_peerStorage->chokeRoundIntervalElapsed()) {
_peerStorage->executeChoke();
}
e->commands.push_back(this);
return false;
}
void PeerChokeCommand::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void PeerChokeCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
} // namespace aria2

View File

@ -36,18 +36,24 @@
#define _D_PEER_CHOKE_COMMAND_H_
#include "Command.h"
#include "BtContextAwareCommand.h"
#include "SharedHandle.h"
namespace aria2 {
class DownloadEngine;
class BtContext;
class BtRuntime;
class PeerStorage;
class PeerChokeCommand : public Command,
public BtContextAwareCommand
{
class PeerChokeCommand : public Command {
private:
DownloadEngine* e;
SharedHandle<BtContext> _btContext;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<BtRuntime> _btRuntime;
public:
PeerChokeCommand(int32_t cuid,
DownloadEngine* e,
@ -56,6 +62,10 @@ public:
virtual ~PeerChokeCommand();
virtual bool execute();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
};
} // namespace aria2

View File

@ -43,33 +43,35 @@
#include "Socket.h"
#include "Logger.h"
#include "Peer.h"
#include "PeerConnection.h"
#include "BtContext.h"
#include "BtRuntime.h"
#include "PieceStorage.h"
#include "PeerStorage.h"
#include "BtAnnounce.h"
#include "BtProgressInfoFile.h"
#include "PieceStorage.h"
#include "PeerConnection.h"
namespace aria2 {
PeerInitiateConnectionCommand::PeerInitiateConnectionCommand(int cuid,
PeerInitiateConnectionCommand::PeerInitiateConnectionCommand
(int cuid,
RequestGroup* requestGroup,
const PeerHandle& peer,
DownloadEngine* e,
const BtContextHandle& btContext,
const SharedHandle<BtContext>& btContext,
const SharedHandle<BtRuntime>& btRuntime,
bool mseHandshakeEnabled)
:PeerAbstractCommand(cuid, peer, e),
BtContextAwareCommand(btContext),
:
PeerAbstractCommand(cuid, peer, e),
RequestGroupAware(requestGroup),
_btContext(btContext),
_btRuntime(btRuntime),
_mseHandshakeEnabled(mseHandshakeEnabled)
{
btRuntime->increaseConnections();
_btRuntime->increaseConnections();
}
PeerInitiateConnectionCommand::~PeerInitiateConnectionCommand()
{
btRuntime->decreaseConnections();
_btRuntime->decreaseConnections();
}
bool PeerInitiateConnectionCommand::executeInternal() {
@ -77,40 +79,58 @@ bool PeerInitiateConnectionCommand::executeInternal() {
peer->port);
socket.reset(new SocketCore());
socket->establishConnection(peer->ipaddr, peer->port);
Command* command;
if(_mseHandshakeEnabled) {
command =
new InitiatorMSEHandshakeCommand(cuid, _requestGroup, peer, e, btContext,
socket);
InitiatorMSEHandshakeCommand* c =
new InitiatorMSEHandshakeCommand(cuid, _requestGroup, peer, e, _btContext,
_btRuntime, socket);
c->setPeerStorage(_peerStorage);
c->setPieceStorage(_pieceStorage);
e->commands.push_back(c);
} else {
command =
new PeerInteractionCommand(cuid, _requestGroup, peer, e, btContext, socket,
PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE);
}
PeerInteractionCommand* command =
new PeerInteractionCommand
(cuid, _requestGroup, peer, e, _btContext, _btRuntime, _pieceStorage,
socket, PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE);
command->setPeerStorage(_peerStorage);
e->commands.push_back(command);
}
return true;
}
// TODO this method removed when PeerBalancerCommand is implemented
bool PeerInitiateConnectionCommand::prepareForNextPeer(time_t wait) {
if(peerStorage->isPeerAvailable() && btRuntime->lessThanEqMinPeers()) {
PeerHandle peer = peerStorage->getUnusedPeer();
if(_peerStorage->isPeerAvailable() && _btRuntime->lessThanEqMinPeers()) {
PeerHandle peer = _peerStorage->getUnusedPeer();
peer->usedBy(CUIDCounterSingletonHolder::instance()->newID());
Command* command =
PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(peer->usedBy(), _requestGroup, peer, e,
btContext);
_btContext, _btRuntime);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
e->commands.push_back(command);
}
return true;
}
void PeerInitiateConnectionCommand::onAbort() {
peerStorage->returnPeer(peer);
_peerStorage->returnPeer(peer);
}
bool PeerInitiateConnectionCommand::exitBeforeExecute()
{
return btRuntime->isHalt();
return _btRuntime->isHalt();
}
void PeerInitiateConnectionCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void PeerInitiateConnectionCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
} // namespace aria2

View File

@ -37,15 +37,26 @@
#include "PeerAbstractCommand.h"
#include "RequestGroupAware.h"
#include "BtContextAwareCommand.h"
namespace aria2 {
class BtContext;
class BtRuntime;
class PeerStorage;
class PieceStorage;
class PeerInitiateConnectionCommand : public PeerAbstractCommand,
public BtContextAwareCommand,
public RequestGroupAware
{
private:
SharedHandle<BtContext> _btContext;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PieceStorage> _pieceStorage;
bool _mseHandshakeEnabled;
protected:
virtual bool executeInternal();
@ -59,9 +70,14 @@ public:
const SharedHandle<Peer>& peer,
DownloadEngine* e,
const SharedHandle<BtContext>& btContext,
const SharedHandle<BtRuntime>& btRuntime,
bool mseHandshakeEnabled = true);
virtual ~PeerInitiateConnectionCommand();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
};
} // namespace aria2

View File

@ -33,6 +33,9 @@
*/
/* copyright --> */
#include "PeerInteractionCommand.h"
#include <algorithm>
#include "DownloadEngine.h"
#include "PeerInitiateConnectionCommand.h"
#include "DefaultBtInteractive.h"
@ -43,7 +46,6 @@
#include "Option.h"
#include "BtContext.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "Peer.h"
#include "BtMessage.h"
#include "BtRuntime.h"
@ -64,21 +66,28 @@
#include "DHTRegistry.h"
#include "PieceStorage.h"
#include "RequestGroup.h"
#include <algorithm>
#include "BtAnnounce.h"
#include "BtProgressInfoFile.h"
#include "DefaultExtensionMessageFactory.h"
namespace aria2 {
PeerInteractionCommand::PeerInteractionCommand(int32_t cuid,
PeerInteractionCommand::PeerInteractionCommand
(int32_t cuid,
RequestGroup* requestGroup,
const PeerHandle& p,
DownloadEngine* e,
const BtContextHandle& btContext,
const SharedHandle<BtContext>& btContext,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<PieceStorage>& pieceStorage,
const SocketHandle& s,
Seq sequence,
const PeerConnectionHandle& passedPeerConnection)
:PeerAbstractCommand(cuid, p, e, s),
BtContextAwareCommand(btContext),
RequestGroupAware(requestGroup),
_btContext(btContext),
_btRuntime(btRuntime),
_pieceStorage(pieceStorage),
sequence(sequence),
maxDownloadSpeedLimit(0)
{
@ -88,9 +97,21 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid,
setWriteCheckSocket(socket);
setTimeout(e->option->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
}
DefaultBtMessageFactoryHandle factory(new DefaultBtMessageFactory());
SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
SharedHandle<PeerStorage> peerStorage =
btRegistry->getPeerStorage(_btContext->getInfoHashAsString());
SharedHandle<DefaultExtensionMessageFactory> extensionMessageFactory
(new DefaultExtensionMessageFactory(_btContext, peer));
extensionMessageFactory->setPeerStorage(peerStorage);
SharedHandle<DefaultBtMessageFactory> factory(new DefaultBtMessageFactory());
factory->setCuid(cuid);
factory->setBtContext(btContext);
factory->setBtContext(_btContext);
factory->setPieceStorage(pieceStorage);
factory->setPeerStorage(peerStorage);
factory->setExtensionMessageFactory(extensionMessageFactory);
factory->setPeer(peer);
factory->setLocalNode(DHTRegistry::_localNode);
factory->setRoutingTable(DHTRegistry::_routingTable);
@ -104,39 +125,52 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid,
peerConnection = passedPeerConnection;
}
DefaultBtMessageDispatcherHandle dispatcher(new DefaultBtMessageDispatcher());
SharedHandle<DefaultBtMessageDispatcher> dispatcher
(new DefaultBtMessageDispatcher());
dispatcher->setCuid(cuid);
dispatcher->setPeer(peer);
dispatcher->setBtContext(btContext);
dispatcher->setMaxUploadSpeedLimit(e->option->getAsInt(PREF_MAX_UPLOAD_LIMIT));
dispatcher->setBtContext(_btContext);
dispatcher->setPieceStorage(pieceStorage);
dispatcher->setPeerStorage(peerStorage);
dispatcher->setMaxUploadSpeedLimit
(e->option->getAsInt(PREF_MAX_UPLOAD_LIMIT));
dispatcher->setRequestTimeout(e->option->getAsInt(PREF_BT_REQUEST_TIMEOUT));
dispatcher->setBtMessageFactory(factory);
DefaultBtMessageReceiverHandle receiver(new DefaultBtMessageReceiver());
receiver->setCuid(cuid);
receiver->setPeer(peer);
receiver->setBtContext(btContext);
receiver->setBtContext(_btContext);
receiver->setPeerConnection(peerConnection);
receiver->setDispatcher(dispatcher);
receiver->setBtMessageFactory(factory);
DefaultBtRequestFactoryHandle reqFactory(new DefaultBtRequestFactory());
SharedHandle<DefaultBtRequestFactory> reqFactory
(new DefaultBtRequestFactory());
reqFactory->setCuid(cuid);
reqFactory->setPeer(peer);
reqFactory->setBtContext(btContext);
reqFactory->setBtContext(_btContext);
reqFactory->setPieceStorage(pieceStorage);
reqFactory->setBtMessageDispatcher(dispatcher);
reqFactory->setBtMessageFactory(factory);
DefaultBtInteractiveHandle btInteractive(new DefaultBtInteractive(btContext, peer));
DefaultBtInteractiveHandle btInteractive
(new DefaultBtInteractive(_btContext, peer));
btInteractive->setBtRuntime(_btRuntime);
btInteractive->setPieceStorage(_pieceStorage);
btInteractive->setPeerStorage(peerStorage); // Note: Not a member variable.
btInteractive->setCuid(cuid);
btInteractive->setBtMessageReceiver(receiver);
btInteractive->setDispatcher(dispatcher);
btInteractive->setBtRequestFactory(reqFactory);
btInteractive->setPeerConnection(peerConnection);
btInteractive->setKeepAliveInterval(e->option->getAsInt(PREF_BT_KEEP_ALIVE_INTERVAL));
btInteractive->setMaxDownloadSpeedLimit(e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
btInteractive->setExtensionMessageFactory(extensionMessageFactory);
btInteractive->setKeepAliveInterval
(e->option->getAsInt(PREF_BT_KEEP_ALIVE_INTERVAL));
btInteractive->setMaxDownloadSpeedLimit
(e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
btInteractive->setBtMessageFactory(factory);
if(!btContext->isPrivate()) {
if(!_btContext->isPrivate()) {
if(e->option->getAsBool(PREF_ENABLE_PEER_EXCHANGE)) {
btInteractive->setUTPexEnabled(true);
}
@ -153,32 +187,23 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid,
factory->setBtRequestFactory(reqFactory);
factory->setPeerConnection(peerConnection);
PeerObjectHandle peerObject(new PeerObject());
peerObject->btMessageDispatcher = dispatcher;
peerObject->btMessageReceiver = receiver;
peerObject->btMessageFactory = factory;
peerObject->btRequestFactory = reqFactory;
peerObject->peerConnection = peerConnection;
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), peerObject);
setUploadLimit(e->option->getAsInt(PREF_MAX_UPLOAD_LIMIT));
peer->allocateSessionResource(btContext->getPieceLength(), btContext->getTotalLength());
peer->allocateSessionResource(_btContext->getPieceLength(),
_btContext->getTotalLength());
maxDownloadSpeedLimit = e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT);
btRuntime->increaseConnections();
_btRuntime->increaseConnections();
}
PeerInteractionCommand::~PeerInteractionCommand() {
if(peer->getCompletedLength() > 0) {
pieceStorage->subtractPieceStats(peer->getBitfield(),
_pieceStorage->subtractPieceStats(peer->getBitfield(),
peer->getBitfieldLength());
}
peer->releaseSessionResource();
PEER_OBJECT_CLUSTER(btContext)->unregisterHandle(peer->getID());
btRuntime->decreaseConnections();
_btRuntime->decreaseConnections();
//logger->debug("CUID#%d - unregistered message factory using ID:%s",
//cuid, peer->getId().c_str());
}
@ -229,7 +254,8 @@ bool PeerInteractionCommand::executeInternal() {
if(btInteractive->countReceivedMessageInIteration() > 0) {
updateKeepAlive();
}
if((peer->amInterested() && !peer->peerChoking() && (peer->getLatency() < 1500)) ||
if((peer->amInterested() && !peer->peerChoking() &&
(peer->getLatency() < 1500)) ||
(peer->peerInterested() && !peer->amChoking())) {
// Writable check causes CPU usage high because socket becomes writable
@ -263,15 +289,18 @@ bool PeerInteractionCommand::executeInternal() {
// TODO this method removed when PeerBalancerCommand is implemented
bool PeerInteractionCommand::prepareForNextPeer(time_t wait) {
if(peerStorage->isPeerAvailable() && btRuntime->lessThanEqMinPeers()) {
PeerHandle peer = peerStorage->getUnusedPeer();
if(_peerStorage->isPeerAvailable() && _btRuntime->lessThanEqMinPeers()) {
PeerHandle peer = _peerStorage->getUnusedPeer();
peer->usedBy(CUIDCounterSingletonHolder::instance()->newID());
PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(peer->usedBy(),
_requestGroup,
peer,
e,
btContext);
_btContext,
_btRuntime);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
e->commands.push_back(command);
}
return true;
@ -279,7 +308,7 @@ bool PeerInteractionCommand::prepareForNextPeer(time_t wait) {
void PeerInteractionCommand::onAbort() {
btInteractive->cancelAllPiece();
peerStorage->returnPeer(peer);
_peerStorage->returnPeer(peer);
}
void PeerInteractionCommand::onFailure()
@ -289,7 +318,13 @@ void PeerInteractionCommand::onFailure()
bool PeerInteractionCommand::exitBeforeExecute()
{
return btRuntime->isHalt();
return _btRuntime->isHalt();
}
void PeerInteractionCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
} // namespace aria2

View File

@ -37,15 +37,17 @@
#include "PeerAbstractCommand.h"
#include "RequestGroupAware.h"
#include "BtContextAwareCommand.h"
namespace aria2 {
class BtContext;
class BtInteractive;
class PeerConnection;
class BtRuntime;
class PeerStorage;
class PieceStorage;
class PeerInteractionCommand : public PeerAbstractCommand,
public BtContextAwareCommand,
public RequestGroupAware
{
public:
@ -55,6 +57,14 @@ public:
RECEIVER_WAIT_HANDSHAKE,
WIRED};
private:
SharedHandle<BtContext> _btContext;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
Seq sequence;
SharedHandle<BtInteractive> btInteractive;
unsigned int maxDownloadSpeedLimit;
@ -70,12 +80,16 @@ public:
const SharedHandle<Peer>& peer,
DownloadEngine* e,
const SharedHandle<BtContext>& btContext,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<PieceStorage>& pieceStorage,
const SharedHandle<SocketCore>& s,
Seq sequence,
const SharedHandle<PeerConnection>& peerConnection = SharedHandle<PeerConnection>());
const SharedHandle<PeerConnection>& peerConnection =
SharedHandle<PeerConnection>());
virtual ~PeerInteractionCommand();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
};
} // namespace aria2

View File

@ -1,63 +0,0 @@
/* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* 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.
*/
/* copyright --> */
#ifndef _D_PEER_OBJECT_H_
#define _D_PEER_OBJECT_H_
#include "common.h"
namespace aria2 {
class BtMessageFactory;
class BtRequestFactory;
class BtMessageDispatcher;
class BtMessageReceiver;
class ExtensionMessageFactory;
class PeerConnection;
class PeerObject {
public:
SharedHandle<BtMessageFactory> btMessageFactory;
SharedHandle<BtRequestFactory> btRequestFactory;
SharedHandle<BtMessageDispatcher> btMessageDispatcher;
SharedHandle<BtMessageReceiver> btMessageReceiver;
SharedHandle<PeerConnection> peerConnection;
SharedHandle<ExtensionMessageFactory> extensionMessageFactory;
};
typedef SharedHandle<PeerObject> PeerObjectHandle;
} // namespace aria2
#endif // _D_PEER_OBJECT_H_

View File

@ -45,6 +45,8 @@
#include "PeerStorage.h"
#include "PieceStorage.h"
#include "BtRuntime.h"
#include "BtAnnounce.h"
#include "BtProgressInfoFile.h"
#include "BtConstants.h"
#include "message.h"
#include "Socket.h"
@ -57,11 +59,13 @@
namespace aria2 {
PeerReceiveHandshakeCommand::PeerReceiveHandshakeCommand(int32_t cuid,
PeerReceiveHandshakeCommand::PeerReceiveHandshakeCommand
(int32_t cuid,
const PeerHandle& peer,
DownloadEngine* e,
const SocketHandle& s,
const SharedHandle<PeerConnection>& peerConnection):
const SharedHandle<PeerConnection>& peerConnection)
:
PeerAbstractCommand(cuid, peer, e, s),
_peerConnection(peerConnection),
_thresholdSpeed(e->option->getAsInt(PREF_BT_REQUEST_PEER_SPEED_LIMIT))
@ -93,28 +97,40 @@ bool PeerReceiveHandshakeCommand::executeInternal()
if(dataLength >= 48) {
// check info_hash
std::string infoHash = Util::toHex(&data[28], INFO_HASH_LENGTH);
BtContextHandle btContext = BtRegistry::getBtContext(infoHash);
if(btContext.isNull() || !BT_RUNTIME(btContext)->ready()) {
SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
SharedHandle<BtContext> btContext = btRegistry->getBtContext(infoHash);
SharedHandle<BtRuntime> btRuntime = btRegistry->getBtRuntime(infoHash);
SharedHandle<PieceStorage> pieceStorage =
btRegistry->getPieceStorage(infoHash);
SharedHandle<PeerStorage> peerStorage =
btRegistry->getPeerStorage(infoHash);
if(btContext.isNull() || !btRuntime->ready()) {
throw DlAbortEx
(StringFormat("Unknown info hash %s", infoHash.c_str()).str());
}
TransferStat tstat = btContext->getOwnerRequestGroup()->calculateStat();
if((!PIECE_STORAGE(btContext)->downloadFinished() &&
if((!pieceStorage->downloadFinished() &&
tstat.getDownloadSpeed() < _thresholdSpeed) ||
BT_RUNTIME(btContext)->lessThanMaxPeers()) {
if(PEER_STORAGE(btContext)->addPeer(peer)) {
btRuntime->lessThanMaxPeers()) {
if(peerStorage->addPeer(peer)) {
peer->usedBy(cuid);
PeerInteractionCommand* command =
new PeerInteractionCommand(cuid,
new PeerInteractionCommand
(cuid,
btContext->getOwnerRequestGroup(),
peer,
e,
btContext,
btRuntime,
pieceStorage,
socket,
PeerInteractionCommand::RECEIVER_WAIT_HANDSHAKE,
_peerConnection);
command->setPeerStorage(peerStorage);
e->commands.push_back(command);
logger->debug(MSG_INCOMING_PEER_CONNECTION, cuid, peer->usedBy());
}

View File

@ -54,15 +54,15 @@ protected:
virtual bool executeInternal();
virtual bool exitBeforeExecute();
public:
PeerReceiveHandshakeCommand(int32_t cuid,
PeerReceiveHandshakeCommand
(int32_t cuid,
const SharedHandle<Peer>& peer,
DownloadEngine* e,
const SharedHandle<SocketCore>& s,
const SharedHandle<PeerConnection>& peerConnection = SharedHandle<PeerConnection>());
const SharedHandle<PeerConnection>& peerConnection =
SharedHandle<PeerConnection>());
virtual ~PeerReceiveHandshakeCommand();
};
} // namespace aria2

View File

@ -48,6 +48,13 @@
#include "ARC4Encryptor.h"
#include "ARC4Decryptor.h"
#include "RequestGroupMan.h"
#include "BtRegistry.h"
#include "BtContext.h"
#include "PeerStorage.h"
#include "PieceStorage.h"
#include "BtAnnounce.h"
#include "BtRuntime.h"
#include "BtProgressInfoFile.h"
namespace aria2 {
@ -128,7 +135,8 @@ bool ReceiverMSEHandshakeCommand::executeInternal()
break;
}
case RECEIVER_RECEIVE_PAD_C_LENGTH: {
if(_mseHandshake->receiveReceiverHashAndPadCLength()) {
if(_mseHandshake->receiveReceiverHashAndPadCLength
(e->getBtRegistry()->getAllBtContext())) {
_sequence = RECEIVER_RECEIVE_PAD_C;
}
break;

View File

@ -33,6 +33,10 @@
*/
/* copyright --> */
#include "RequestGroup.h"
#include <cassert>
#include <algorithm>
#include "PostDownloadHandler.h"
#include "DownloadEngine.h"
#include "DefaultSegmentManFactory.h"
@ -87,7 +91,6 @@
# include "BtPostDownloadHandler.h"
# include "DHTSetup.h"
# include "DHTRegistry.h"
# include "PeerObject.h"
# include "BtMessageFactory.h"
# include "BtRequestFactory.h"
# include "BtMessageDispatcher.h"
@ -100,8 +103,6 @@
#ifdef ENABLE_METALINK
# include "MetalinkPostDownloadHandler.h"
#endif // ENABLE_METALINK
#include <cassert>
#include <algorithm>
namespace aria2 {
@ -200,35 +201,46 @@ void RequestGroup::createInitialCommand(std::deque<Command*>& commands,
_pieceStorage->setFileFilter(Util::parseIntRange(_option->get(PREF_SELECT_FILE)));
}
BtProgressInfoFileHandle
SharedHandle<DefaultBtProgressInfoFile>
progressInfoFile(new DefaultBtProgressInfoFile(_downloadContext,
_pieceStorage,
_option));
BtRegistry::registerBtContext(btContext->getInfoHashAsString(), btContext);
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
btRegistry->registerBtContext(btContext->getInfoHashAsString(),
btContext);
btRegistry->registerPieceStorage(btContext->getInfoHashAsString(),
_pieceStorage);
BtRegistry::registerBtProgressInfoFile(btContext->getInfoHashAsString(),
btRegistry->registerBtProgressInfoFile(btContext->getInfoHashAsString(),
progressInfoFile);
BtRuntimeHandle btRuntime(new BtRuntime());
btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT));
BtRegistry::registerBtRuntime(btContext->getInfoHashAsString(), btRuntime);
btRegistry->registerBtRuntime(btContext->getInfoHashAsString(),
btRuntime);
_btRuntime = btRuntime;
progressInfoFile->setBtRuntime(btRuntime);
PeerStorageHandle peerStorage(new DefaultPeerStorage(btContext, _option));
BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage);
SharedHandle<DefaultPeerStorage> peerStorage
(new DefaultPeerStorage(btContext, _option));
peerStorage->setBtRuntime(btRuntime);
peerStorage->setPieceStorage(_pieceStorage);
btRegistry->registerPeerStorage(btContext->getInfoHashAsString(),
peerStorage);
_peerStorage = peerStorage;
progressInfoFile->setPeerStorage(peerStorage);
BtAnnounceHandle btAnnounce(new DefaultBtAnnounce(btContext, _option));
BtRegistry::registerBtAnnounce(btContext->getInfoHashAsString(), btAnnounce);
SharedHandle<DefaultBtAnnounce> btAnnounce
(new DefaultBtAnnounce(btContext, _option));
btAnnounce->setBtRuntime(btRuntime);
btAnnounce->setPieceStorage(_pieceStorage);
btAnnounce->setPeerStorage(peerStorage);
btRegistry->registerBtAnnounce(btContext->getInfoHashAsString(),
btAnnounce);
btAnnounce->shuffleAnnounce();
{
SharedHandle<PeerObjectCluster> po(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
po);
}
// Remove the control file if download file doesn't exist
if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
progressInfoFile->removeFile();
@ -624,14 +636,8 @@ unsigned int RequestGroup::getNumConnection() const
{
unsigned int numConnection = _numStreamConnection;
#ifdef ENABLE_BITTORRENT
{
BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
if(!btContext.isNull()) {
BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
if(!btRuntime.isNull()) {
numConnection += btRuntime->getConnections();
}
}
if(!_btRuntime.isNull()) {
numConnection += _btRuntime->getConnections();
}
#endif // ENABLE_BITTORRENT
return numConnection;
@ -652,14 +658,8 @@ TransferStat RequestGroup::calculateStat()
{
TransferStat stat;
#ifdef ENABLE_BITTORRENT
{
BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
if(!btContext.isNull()) {
PeerStorageHandle peerStorage = PEER_STORAGE(btContext);
if(!peerStorage.isNull()) {
stat = peerStorage->calculateStat();
}
}
if(!_peerStorage.isNull()) {
stat = _peerStorage->calculateStat();
}
#endif // ENABLE_BITTORRENT
if(!_segmentMan.isNull()) {
@ -672,14 +672,8 @@ void RequestGroup::setHaltRequested(bool f)
{
_haltRequested = f;
#ifdef ENABLE_BITTORRENT
{
BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
if(!btContext.isNull()) {
BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
if(!btRuntime.isNull()) {
btRuntime->setHalt(f);
}
}
if(!_btRuntime.isNull()) {
_btRuntime->setHalt(f);
}
#endif // ENABLE_BITTORRENT
}
@ -690,18 +684,21 @@ void RequestGroup::setForceHaltRequested(bool f)
_forceHaltRequested = f;
}
void RequestGroup::releaseRuntimeResource()
void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
{
#ifdef ENABLE_BITTORRENT
BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
if(!btContext.isNull()) {
BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString());
SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
BtContextHandle btContextInReg =
btRegistry->getBtContext(btContext->getInfoHashAsString());
if(!btContextInReg.isNull() &&
btContextInReg->getOwnerRequestGroup()->getGID() ==
btContext->getOwnerRequestGroup()->getGID()) {
BtRegistry::unregister(btContext->getInfoHashAsString());
btRegistry->unregister(btContext->getInfoHashAsString());
if(!DHTRegistry::_peerAnnounceStorage.isNull()) {
DHTRegistry::_peerAnnounceStorage->removePeerAnnounce(btContext);
DHTRegistry::_peerAnnounceStorage->
removeLocalPeerAnnounce(btContext->getInfoHash());
}
}
}

View File

@ -36,11 +36,13 @@
#define _D_REQUEST_GROUP_H_
#include "common.h"
#include <string>
#include <deque>
#include "SharedHandle.h"
#include "TransferStat.h"
#include "TimeA2.h"
#include <string>
#include <deque>
namespace aria2 {
@ -62,6 +64,10 @@ class CheckIntegrityEntry;
class DownloadResult;
class ServerHost;
class URISelector;
#ifdef ENABLE_BITTORRENT
class BtRuntime;
class PeerStorage;
#endif // ENABLE_BITTORRENT
class RequestGroup {
private:
@ -120,6 +126,10 @@ private:
unsigned int _fileNotFoundCount;
WeakHandle<BtRuntime> _btRuntime;
WeakHandle<PeerStorage> _peerStorage;
const Option* _option;
Logger* _logger;
@ -287,7 +297,7 @@ public:
bool isDependencyResolved();
void releaseRuntimeResource();
void releaseRuntimeResource(DownloadEngine* e);
void postDownloadProcessing(std::deque<SharedHandle<RequestGroup> >& groups);

View File

@ -122,6 +122,7 @@ RequestGroupMan::getRequestGroups() const
class ProcessStoppedRequestGroup {
private:
DownloadEngine* _e;
std::deque<SharedHandle<RequestGroup> >& _reservedGroups;
std::deque<SharedHandle<DownloadResult> >& _downloadResults;
Logger* _logger;
@ -143,8 +144,10 @@ private:
}
public:
ProcessStoppedRequestGroup
(std::deque<SharedHandle<RequestGroup> >& reservedGroups,
(DownloadEngine* e,
std::deque<SharedHandle<RequestGroup> >& reservedGroups,
std::deque<SharedHandle<DownloadResult> >& downloadResults):
_e(e),
_reservedGroups(reservedGroups),
_downloadResults(downloadResults),
_logger(LogFactory::getInstance()) {}
@ -178,7 +181,7 @@ public:
} catch(RecoverableException& ex) {
_logger->error(EX_EXCEPTION_CAUGHT, ex);
}
group->releaseRuntimeResource();
group->releaseRuntimeResource(_e);
_downloadResults.push_back(group->createDownloadResult());
}
}
@ -227,14 +230,15 @@ void RequestGroupMan::updateServerStat()
CollectServerStat(this));
}
void RequestGroupMan::removeStoppedGroup()
void RequestGroupMan::removeStoppedGroup(DownloadEngine* e)
{
size_t numPrev = _requestGroups.size();
updateServerStat();
std::for_each(_requestGroups.begin(), _requestGroups.end(),
ProcessStoppedRequestGroup(_reservedGroups, _downloadResults));
ProcessStoppedRequestGroup(e, _reservedGroups,
_downloadResults));
_requestGroups.erase(std::remove_if(_requestGroups.begin(),
_requestGroups.end(),
@ -264,7 +268,7 @@ void RequestGroupMan::configureRequestGroup
void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e)
{
RequestGroups temp;
removeStoppedGroup();
removeStoppedGroup(e);
unsigned int count = 0;
for(int num = _maxSimultaneousDownloads-_requestGroups.size();
num > 0 && _reservedGroups.size() > 0; --num) {

View File

@ -89,7 +89,7 @@ public:
void getInitialCommands(std::deque<Command*>& commands, DownloadEngine* e);
void removeStoppedGroup();
void removeStoppedGroup(DownloadEngine* e);
void fillRequestGroupFromReserver(DownloadEngine* e);

View File

@ -46,17 +46,17 @@ namespace aria2 {
SeedCheckCommand::SeedCheckCommand(int cuid,
RequestGroup* requestGroup,
DownloadEngine* e,
const BtContextHandle& btContext,
const SharedHandle<BtContext>& btContext,
const SeedCriteriaHandle& seedCriteria)
:Command(cuid),
BtContextAwareCommand(btContext),
RequestGroupAware(requestGroup),
e(e),
_btContext(btContext),
seedCriteria(seedCriteria),
checkStarted(false) {}
bool SeedCheckCommand::execute() {
if(btRuntime->isHalt()) {
if(_btRuntime->isHalt()) {
return true;
}
if(!seedCriteria.get()) {
@ -64,7 +64,7 @@ bool SeedCheckCommand::execute() {
}
if(checkPoint.elapsed(1)) {
if(!checkStarted) {
if(pieceStorage->downloadFinished()) {
if(_pieceStorage->downloadFinished()) {
checkStarted = true;
seedCriteria->reset();
}
@ -72,7 +72,7 @@ bool SeedCheckCommand::execute() {
if(checkStarted) {
if(seedCriteria->evaluate()) {
logger->notice(MSG_SEEDING_END);
btRuntime->setHalt(true);
_btRuntime->setHalt(true);
}
}
}
@ -80,9 +80,22 @@ bool SeedCheckCommand::execute() {
return false;
}
void SeedCheckCommand::setSeedCriteria(const SharedHandle<SeedCriteria>& seedCriteria)
void SeedCheckCommand::setSeedCriteria
(const SharedHandle<SeedCriteria>& seedCriteria)
{
this->seedCriteria = seedCriteria;
}
void SeedCheckCommand::setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void SeedCheckCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
} // namespace aria2

View File

@ -36,7 +36,7 @@
#define _D_SEED_CHECK_COMMAND_H_
#include "Command.h"
#include "BtContextAwareCommand.h"
#include "SharedHandle.h"
#include "RequestGroupAware.h"
#include "TimeA2.h"
@ -44,13 +44,18 @@ namespace aria2 {
class DownloadEngine;
class SeedCriteria;
class BtContext;
class BtRuntime;
class PieceStorage;
class SeedCheckCommand : public Command,
public BtContextAwareCommand,
public RequestGroupAware
{
private:
DownloadEngine* e;
SharedHandle<BtContext> _btContext;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<BtRuntime> _btRuntime;
Time checkPoint;
SharedHandle<SeedCriteria> seedCriteria;
bool checkStarted;
@ -66,6 +71,10 @@ public:
virtual bool execute();
void setSeedCriteria(const SharedHandle<SeedCriteria>& seedCriteria);
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
};
} // namespace aria2

View File

@ -40,7 +40,6 @@
#include "PeerStorage.h"
#include "PieceStorage.h"
#include "BtRuntime.h"
#include "BtRegistry.h"
namespace aria2 {
@ -48,16 +47,13 @@ class ShareRatioSeedCriteria : public SeedCriteria {
private:
double ratio;
SharedHandle<BtContext> btContext;
SharedHandle<PeerStorage> peerStorage;
SharedHandle<PieceStorage> pieceStorage;
SharedHandle<BtRuntime> btRuntime;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<BtRuntime> _btRuntime;
public:
ShareRatioSeedCriteria(double ratio, const SharedHandle<BtContext>& btContext)
:ratio(ratio),
btContext(btContext),
peerStorage(PEER_STORAGE(btContext)),
pieceStorage(PIECE_STORAGE(btContext)),
btRuntime(BT_RUNTIME(btContext)) {}
btContext(btContext) {}
virtual ~ShareRatioSeedCriteria() {}
@ -67,11 +63,11 @@ public:
if(btContext->getTotalLength() == 0) {
return false;
}
TransferStat stat = peerStorage->calculateStat();
TransferStat stat = _peerStorage->calculateStat();
uint64_t allTimeUploadLength =
btRuntime->getUploadLengthAtStartup()+stat.getSessionUploadLength();
_btRuntime->getUploadLengthAtStartup()+stat.getSessionUploadLength();
return ratio <=
((double)allTimeUploadLength)/pieceStorage->getCompletedLength();
((double)allTimeUploadLength)/_pieceStorage->getCompletedLength();
}
void setRatio(double ratio) {
@ -81,6 +77,21 @@ public:
double getRatio() const {
return ratio;
}
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
};
} // namespace aria2

View File

@ -34,7 +34,6 @@
/* copyright --> */
#include "SimpleBtMessage.h"
#include "message.h"
#include "BtRegistry.h"
#include "Peer.h"
#include "PeerConnection.h"
#include "Logger.h"

View File

@ -33,6 +33,9 @@
*/
/* copyright --> */
#include "TrackerWatcherCommand.h"
#include <sstream>
#include "DownloadEngine.h"
#include "BtContext.h"
#include "BtAnnounce.h"
@ -55,7 +58,6 @@
#include "Logger.h"
#include "A2STR.h"
#include "SocketCore.h"
#include <sstream>
namespace aria2 {
@ -64,9 +66,9 @@ TrackerWatcherCommand::TrackerWatcherCommand(int32_t cuid,
DownloadEngine* e,
const BtContextHandle& btContext):
Command(cuid),
BtContextAwareCommand(btContext),
RequestGroupAware(requestGroup),
e(e) {}
e(e),
_btContext(btContext) {}
TrackerWatcherCommand::~TrackerWatcherCommand() {}
@ -83,7 +85,7 @@ bool TrackerWatcherCommand::execute() {
return false;
}
}
if(btAnnounce->noMoreAnnounce()) {
if(_btAnnounce->noMoreAnnounce()) {
logger->debug("no more announce");
return true;
}
@ -100,35 +102,37 @@ bool TrackerWatcherCommand::execute() {
std::string trackerResponse = getTrackerResponse(_trackerRequestGroup);
processTrackerResponse(trackerResponse);
btAnnounce->announceSuccess();
btAnnounce->resetAnnounce();
_btAnnounce->announceSuccess();
_btAnnounce->resetAnnounce();
} catch(RecoverableException& ex) {
logger->error(EX_EXCEPTION_CAUGHT, ex);
btAnnounce->announceFailure();
if(btAnnounce->isAllAnnounceFailed()) {
btAnnounce->resetAnnounce();
_btAnnounce->announceFailure();
if(_btAnnounce->isAllAnnounceFailed()) {
_btAnnounce->resetAnnounce();
}
}
_trackerRequestGroup.reset();
} else if(_trackerRequestGroup->getNumCommand() == 0){
// handle errors here
btAnnounce->announceFailure(); // inside it, trackers = 0.
_btAnnounce->announceFailure(); // inside it, trackers = 0.
_trackerRequestGroup.reset();
if(btAnnounce->isAllAnnounceFailed()) {
btAnnounce->resetAnnounce();
if(_btAnnounce->isAllAnnounceFailed()) {
_btAnnounce->resetAnnounce();
}
}
e->commands.push_back(this);
return false;
}
std::string TrackerWatcherCommand::getTrackerResponse(const RequestGroupHandle& requestGroup)
std::string TrackerWatcherCommand::getTrackerResponse
(const RequestGroupHandle& requestGroup)
{
std::stringstream strm;
unsigned char data[2048];
requestGroup->getPieceStorage()->getDiskAdaptor()->openFile();
while(1) {
ssize_t dataLength = requestGroup->getPieceStorage()->getDiskAdaptor()->readData(data, sizeof(data), strm.tellp());
ssize_t dataLength = requestGroup->getPieceStorage()->
getDiskAdaptor()->readData(data, sizeof(data), strm.tellp());
if(dataLength == 0) {
break;
}
@ -138,12 +142,14 @@ std::string TrackerWatcherCommand::getTrackerResponse(const RequestGroupHandle&
}
// TODO we have to deal with the exception thrown By BtAnnounce
void TrackerWatcherCommand::processTrackerResponse(const std::string& trackerResponse)
void TrackerWatcherCommand::processTrackerResponse
(const std::string& trackerResponse)
{
btAnnounce->processAnnounceResponse(reinterpret_cast<const unsigned char*>(trackerResponse.c_str()),
_btAnnounce->processAnnounceResponse
(reinterpret_cast<const unsigned char*>(trackerResponse.c_str()),
trackerResponse.size());
while(!btRuntime->isHalt() && btRuntime->lessThanMinPeers()) {
PeerHandle peer = peerStorage->getUnusedPeer();
while(!_btRuntime->isHalt() && _btRuntime->lessThanMinPeers()) {
PeerHandle peer = _peerStorage->getUnusedPeer();
if(peer.isNull()) {
break;
}
@ -153,7 +159,10 @@ void TrackerWatcherCommand::processTrackerResponse(const std::string& trackerRes
_requestGroup,
peer,
e,
btContext);
_btContext,
_btRuntime);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
e->commands.push_back(command);
logger->debug("CUID#%d - Adding new command CUID#%d", cuid, peer->usedBy());
}
@ -161,9 +170,9 @@ void TrackerWatcherCommand::processTrackerResponse(const std::string& trackerRes
RequestGroupHandle TrackerWatcherCommand::createAnnounce() {
RequestGroupHandle rg;
if(btAnnounce->isAnnounceReady()) {
rg = createRequestGroup(btAnnounce->getAnnounceUrl());
btAnnounce->announceStart(); // inside it, trackers++.
if(_btAnnounce->isAnnounceReady()) {
rg = createRequestGroup(_btAnnounce->getAnnounceUrl());
_btAnnounce->announceStart(); // inside it, trackers++.
}
return rg;
}
@ -191,4 +200,28 @@ TrackerWatcherCommand::createRequestGroup(const std::string& uri)
return rg;
}
void TrackerWatcherCommand::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
}
void TrackerWatcherCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
}
void TrackerWatcherCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
}
void TrackerWatcherCommand::setBtAnnounce
(const SharedHandle<BtAnnounce>& btAnnounce)
{
_btAnnounce = btAnnounce;
}
} // namespace aria2

View File

@ -36,21 +36,35 @@
#define _D_TRACKER_WATCHER_COMMAND_H_
#include "Command.h"
#include "BtContextAwareCommand.h"
#include "SharedHandle.h"
#include "RequestGroupAware.h"
namespace aria2 {
class DownloadEngine;
class RequestGroup;
class BtContext;
class PeerStorage;
class PieceStorage;
class BtRuntime;
class BtAnnounce;
class TrackerWatcherCommand : public Command,
public BtContextAwareCommand,
public RequestGroupAware
{
private:
DownloadEngine* e;
SharedHandle<BtContext> _btContext;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<BtAnnounce> _btAnnounce;
SharedHandle<RequestGroup> _trackerRequestGroup;
/**
* Returns a command for announce request. Returns 0 if no announce request
@ -73,6 +87,14 @@ public:
SharedHandle<RequestGroup> createAnnounce();
virtual bool execute();
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage);
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);
void setBtAnnounce(const SharedHandle<BtAnnounce>& btAnnounce);
};
} // namespace aria2

View File

@ -34,13 +34,11 @@
/* copyright --> */
#include "UTPexExtensionMessage.h"
#include "Peer.h"
#include "BtContext.h"
#include "Dictionary.h"
#include "Data.h"
#include "BencodeVisitor.h"
#include "Util.h"
#include "PeerMessageUtil.h"
#include "BtRegistry.h"
#include "PeerStorage.h"
#include "CompactPeerListProcessor.h"
#include "MetaFileUtil.h"
@ -96,7 +94,7 @@ std::string UTPexExtensionMessage::toString() const
void UTPexExtensionMessage::doReceivedAction()
{
PEER_STORAGE(_btContext)->addPeer(_freshPeers);
_peerStorage->addPeer(_freshPeers);
}
bool UTPexExtensionMessage::addFreshPeer(const PeerHandle& peer)
@ -161,14 +159,14 @@ size_t UTPexExtensionMessage::getMaxDroppedPeer() const
return _maxDroppedPeer;
}
void UTPexExtensionMessage::setBtContext(const BtContextHandle& btContext)
void UTPexExtensionMessage::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_btContext = btContext;
_peerStorage = peerStorage;
}
UTPexExtensionMessageHandle
UTPexExtensionMessage::create(const BtContextHandle& btContext,
const unsigned char* data, size_t len)
UTPexExtensionMessage::create(const unsigned char* data, size_t len)
{
if(len < 1) {
throw DlAbortEx(StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE,

View File

@ -36,13 +36,15 @@
#define _D_UT_PEX_EXTENSION_MESSAGE_H_
#include "ExtensionMessage.h"
#include "a2time.h"
#include <utility>
#include <deque>
#include "a2time.h"
namespace aria2 {
class BtContext;
class PeerStorage;
class Peer;
class UTPexExtensionMessage;
typedef SharedHandle<UTPexExtensionMessage> UTPexExtensionMessageHandle;
@ -55,7 +57,7 @@ private:
std::deque<SharedHandle<Peer> > _droppedPeers;
SharedHandle<BtContext> _btContext;
SharedHandle<PeerStorage> _peerStorage;
time_t _interval;
@ -101,10 +103,10 @@ public:
bool droppedPeersAreFull() const;
void setBtContext(const SharedHandle<BtContext>& btContext);
void setPeerStorage(const SharedHandle<PeerStorage>& peerStorage);
static UTPexExtensionMessageHandle create(const SharedHandle<BtContext>& btContext,
const unsigned char* data, size_t len);
static UTPexExtensionMessageHandle
create(const unsigned char* data, size_t len);
void setMaxFreshPeer(size_t maxFreshPeer);

View File

@ -1,19 +1,15 @@
#include "BtCancelMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "MockBtMessageDispatcher.h"
#include "MockBtContext.h"
#include "Peer.h"
#include "FileEntry.h"
#include "PeerObject.h"
#include "Piece.h"
#include "BtRegistry.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -29,19 +25,9 @@ private:
SharedHandle<MockBtContext> btContext;
public:
void setUp() {
BtRegistry::unregisterAll();
peer.reset(new Peer("host", 6969));
btContext.reset(new MockBtContext());
btContext->setInfoHash((const unsigned char*)"12345678901234567890");
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> po(new PeerObject());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po);
}
void tearDown() {
BtRegistry::unregisterAll();
}
void testCreate();
@ -119,7 +105,8 @@ void BtCancelMessageTest::testDoReceivedAction() {
msg.setLength(16*1024);
msg.setBtContext(btContext);
msg.setPeer(peer);
SharedHandle<MockBtMessageDispatcher2> dispatcher(new MockBtMessageDispatcher2());
SharedHandle<MockBtMessageDispatcher2> dispatcher
(new MockBtMessageDispatcher2());
msg.setBtMessageDispatcher(dispatcher);
msg.doReceivedAction();

View File

@ -1,18 +1,15 @@
#include "BtChokeMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "MockBtMessageDispatcher.h"
#include "MockBtRequestFactory.h"
#include "MockBtContext.h"
#include "Peer.h"
#include "FileEntry.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "BtMessageFactory.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -34,16 +31,10 @@ public:
SharedHandle<MockBtContext> btContext;
void setUp() {
BtRegistry::unregisterAll();
peer.reset(new Peer("host", 6969));
peer->allocateSessionResource(1024, 1024*1024);
btContext.reset(new MockBtContext());
btContext->setInfoHash((const unsigned char*)"12345678901234567890");
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> po(new PeerObject());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po);
}
void testCreate();

View File

@ -1,21 +1,15 @@
#include "BtExtendedMessage.h"
#include "PeerMessageUtil.h"
#include "MockBtContext.h"
#include "MockExtensionMessageFactory.h"
#include "BtRegistry.h"
#include "Peer.h"
#include "PeerObject.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "BtMessageDispatcher.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "Exception.h"
#include "FileEntry.h"
#include <cstring>
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "MockExtensionMessageFactory.h"
#include "Peer.h"
#include "Exception.h"
namespace aria2 {
class BtExtendedMessageTest:public CppUnit::TestFixture {
@ -29,16 +23,6 @@ class BtExtendedMessageTest:public CppUnit::TestFixture {
private:
public:
void setUp()
{
BtRegistry::unregisterAll();
}
void tearDown()
{
BtRegistry::unregisterAll();
}
void testCreate();
void testGetMessage();
void testDoReceivedAction();
@ -51,27 +35,18 @@ CPPUNIT_TEST_SUITE_REGISTRATION(BtExtendedMessageTest);
void BtExtendedMessageTest::testCreate() {
SharedHandle<Peer> peer(new Peer("192.168.0.1", 6969));
peer->allocateSessionResource(1024, 1024*1024);
SharedHandle<MockBtContext> ctx(new MockBtContext());
unsigned char infohash[20];
memset(infohash, 0, sizeof(infohash));
ctx->setInfoHash(infohash);
SharedHandle<MockExtensionMessageFactory> exmsgFactory
(new MockExtensionMessageFactory());
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(ctx->getInfoHashAsString(), cluster);
SharedHandle<PeerObject> peerObject(new PeerObject());
peerObject->extensionMessageFactory = exmsgFactory;
PEER_OBJECT_CLUSTER(ctx)->registerHandle(peer->getID(), peerObject);
// payload:{4:name3:foo}->11bytes
std::string payload = "4:name3:foo";
unsigned char msg[17];// 6+11bytes
PeerMessageUtil::createPeerMessageString((unsigned char*)msg, sizeof(msg), 13, 20);
PeerMessageUtil::createPeerMessageString((unsigned char*)msg,
sizeof(msg), 13, 20);
msg[5] = 1; // Set dummy extended message ID 1
memcpy(msg+6, payload.c_str(), payload.size());
SharedHandle<BtExtendedMessage> pm = BtExtendedMessage::create(ctx,
SharedHandle<BtExtendedMessage> pm = BtExtendedMessage::create(exmsgFactory,
peer,
&msg[4], 13);
CPPUNIT_ASSERT_EQUAL((uint8_t)20, pm->getId());
@ -80,7 +55,7 @@ void BtExtendedMessageTest::testCreate() {
try {
unsigned char msg[5];
PeerMessageUtil::createPeerMessageString(msg, sizeof(msg), 1, 20);
BtExtendedMessage::create(ctx, peer, &msg[4], 1);
BtExtendedMessage::create(exmsgFactory, peer, &msg[4], 1);
CPPUNIT_FAIL("exception must be thrown.");
} catch(Exception& e) {
std::cerr << e.stackTrace() << std::endl;
@ -89,7 +64,7 @@ void BtExtendedMessageTest::testCreate() {
try {
unsigned char msg[6];
PeerMessageUtil::createPeerMessageString(msg, sizeof(msg), 2, 21);
BtExtendedMessage::create(ctx, peer, &msg[4], 2);
BtExtendedMessage::create(exmsgFactory, peer, &msg[4], 2);
CPPUNIT_FAIL("exception must be thrown.");
} catch(Exception& e) {
std::cerr << e.stackTrace() << std::endl;

View File

@ -1,8 +1,11 @@
#include "BtInterestedMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "Peer.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -67,6 +70,7 @@ void BtInterestedMessageTest::testDoReceivedAction() {
SharedHandle<Peer> peer(new Peer("host", 6969));
peer->allocateSessionResource(1024, 1024*1024);
msg.setPeer(peer);
CPPUNIT_ASSERT(!peer->peerInterested());
msg.doReceivedAction();
CPPUNIT_ASSERT(peer->peerInterested());

View File

@ -1,8 +1,12 @@
#include "BtNotInterestedMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "Peer.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerStorage.h"
namespace aria2 {
@ -19,6 +23,7 @@ private:
public:
void setUp() {
// TODO add peer storage here
}
void testCreate();

View File

@ -1,4 +1,9 @@
#include "BtPieceMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "MockBtContext.h"
#include "MockBtMessage.h"
@ -9,15 +14,7 @@
#include "FileEntry.h"
#include "Peer.h"
#include "Piece.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "BtMessageReceiver.h"
#include "BtRequestFactory.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include "BtHandshakeMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -75,37 +72,33 @@ public:
}
};
SharedHandle<MockBtContext> _btContext;
SharedHandle<MockBtMessageDispatcher> btMessageDispatcher;
SharedHandle<MockBtMessageFactory> _btMessageFactory;
SharedHandle<Peer> peer;
SharedHandle<BtPieceMessage> msg;
void setUp() {
BtRegistry::unregisterAll();
SharedHandle<MockBtContext> btContext(new MockBtContext());
btContext->setInfoHash((const unsigned char*)"12345678901234567890");
btContext->setPieceLength(16*1024);
btContext->setTotalLength(256*1024);
_btContext.reset(new MockBtContext());
_btContext->setInfoHash((const unsigned char*)"12345678901234567890");
_btContext->setPieceLength(16*1024);
_btContext->setTotalLength(256*1024);
peer.reset(new Peer("host", 6969));
peer->allocateSessionResource(btContext->getPieceLength(),
btContext->getTotalLength());
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> po(new PeerObject());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po);
peer->allocateSessionResource(_btContext->getPieceLength(),
_btContext->getTotalLength());
btMessageDispatcher.reset(new MockBtMessageDispatcher());
PEER_OBJECT(btContext, peer)->btMessageDispatcher = btMessageDispatcher;
PEER_OBJECT(btContext, peer)->btMessageFactory.reset(new MockBtMessageFactory2());
_btMessageFactory.reset(new MockBtMessageFactory2());
msg.reset(new BtPieceMessage());
msg->setIndex(1);
msg->setBegin(1024);
msg->setBlockLength(16*1024);
msg->setBtContext(btContext);
msg->setBtContext(_btContext);
msg->setPeer(peer);
msg->setBtMessageDispatcher(btMessageDispatcher);
msg->setBtMessageFactory(BT_MESSAGE_FACTORY(btContext, peer));
msg->setBtMessageFactory(_btMessageFactory);
}
};
@ -181,7 +174,8 @@ void BtPieceMessageTest::testChokingEvent_allowedFastEnabled() {
CPPUNIT_ASSERT(msg->isInvalidate());
CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->messageQueue.size());
MockBtMessage2* rej = (MockBtMessage2*)btMessageDispatcher->messageQueue.front().get();
MockBtMessage2* rej =
(MockBtMessage2*)btMessageDispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL((size_t)1, rej->index);
CPPUNIT_ASSERT_EQUAL((uint32_t)1024, rej->begin);
CPPUNIT_ASSERT_EQUAL((size_t)16*1024, rej->length);
@ -271,7 +265,8 @@ void BtPieceMessageTest::testCancelSendingPieceEvent_allowedFastEnabled() {
CPPUNIT_ASSERT(msg->isInvalidate());
CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->messageQueue.size());
MockBtMessage2* rej = (MockBtMessage2*)btMessageDispatcher->messageQueue.front().get();
MockBtMessage2* rej = (MockBtMessage2*)btMessageDispatcher->
messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL((size_t)1, rej->index);
CPPUNIT_ASSERT_EQUAL((uint32_t)1024, rej->begin);
CPPUNIT_ASSERT_EQUAL((size_t)16*1024, rej->length);

View File

@ -1,4 +1,9 @@
#include "BtPortMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "Util.h"
#include "array_fun.h"
@ -8,8 +13,6 @@
#include "MockDHTTask.h"
#include "MockDHTTaskFactory.h"
#include "MockDHTTaskQueue.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {

View File

@ -1,4 +1,7 @@
#include "BtRegistry.h"
#include <cppunit/extensions/HelperMacros.h>
#include "Exception.h"
#include "MockBtContext.h"
#include "MockPeerStorage.h"
@ -7,14 +10,6 @@
#include "MockBtProgressInfoFile.h"
#include "BtRuntime.h"
#include "FileEntry.h"
#include "PeerObject.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "BtMessageDispatcher.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -27,28 +22,16 @@ class BtRegistryTest:public CppUnit::TestFixture {
CPPUNIT_TEST(testGetBtRuntime);
CPPUNIT_TEST(testGetBtAnnounce);
CPPUNIT_TEST(testGetBtProgressInfoFile);
CPPUNIT_TEST(testGetPeerObjectCluster);
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp()
{
BtRegistry::unregisterAll();
}
void tearDown()
{
BtRegistry::unregisterAll();
}
void testGetBtContext();
void testGetPeerStorage();
void testGetPieceStorage();
void testGetBtRuntime();
void testGetBtAnnounce();
void testGetBtProgressInfoFile();
void testGetPeerObjectCluster();
};
@ -56,74 +39,67 @@ CPPUNIT_TEST_SUITE_REGISTRATION( BtRegistryTest );
void BtRegistryTest::testGetBtContext()
{
CPPUNIT_ASSERT(BtRegistry::getBtContext("test").isNull());
BtRegistry btRegistry;
CPPUNIT_ASSERT(btRegistry.getBtContext("test").isNull());
SharedHandle<BtContext> btContext(new MockBtContext());
BtRegistry::registerBtContext("test", btContext);
btRegistry.registerBtContext("test", btContext);
CPPUNIT_ASSERT_EQUAL(btContext.get(),
BtRegistry::getBtContext("test").get());
btRegistry.getBtContext("test").get());
}
void BtRegistryTest::testGetPeerStorage() {
CPPUNIT_ASSERT(!BtRegistry::getPeerStorage("test").get());
BtRegistry btRegistry;
CPPUNIT_ASSERT(!btRegistry.getPeerStorage("test").get());
SharedHandle<PeerStorage> peerStorage(new MockPeerStorage());
BtRegistry::registerPeerStorage("test", peerStorage);
btRegistry.registerPeerStorage("test", peerStorage);
CPPUNIT_ASSERT_EQUAL(peerStorage.get(),
BtRegistry::getPeerStorage("test").get());
btRegistry.getPeerStorage("test").get());
}
void BtRegistryTest::testGetPieceStorage() {
CPPUNIT_ASSERT(!BtRegistry::getPieceStorage("test").get());
BtRegistry btRegistry;
CPPUNIT_ASSERT(!btRegistry.getPieceStorage("test").get());
SharedHandle<PieceStorage> pieceStorage(new MockPieceStorage());
BtRegistry::registerPieceStorage("test", pieceStorage);
btRegistry.registerPieceStorage("test", pieceStorage);
CPPUNIT_ASSERT_EQUAL(pieceStorage.get(),
BtRegistry::getPieceStorage("test").get());
btRegistry.getPieceStorage("test").get());
}
void BtRegistryTest::testGetBtRuntime() {
CPPUNIT_ASSERT(!BtRegistry::getBtRuntime("test").get());
BtRegistry btRegistry;
CPPUNIT_ASSERT(!btRegistry.getBtRuntime("test").get());
SharedHandle<BtRuntime> runtime;
BtRegistry::registerBtRuntime("test", runtime);
btRegistry.registerBtRuntime("test", runtime);
CPPUNIT_ASSERT_EQUAL(runtime.get(),
BtRegistry::getBtRuntime("test").get());
btRegistry.getBtRuntime("test").get());
}
void BtRegistryTest::testGetBtAnnounce() {
CPPUNIT_ASSERT(!BtRegistry::getBtAnnounce("test").get());
BtRegistry btRegistry;
CPPUNIT_ASSERT(!btRegistry.getBtAnnounce("test").get());
SharedHandle<BtAnnounce> btAnnounce(new MockBtAnnounce());
BtRegistry::registerBtAnnounce("test", btAnnounce);
btRegistry.registerBtAnnounce("test", btAnnounce);
CPPUNIT_ASSERT_EQUAL(btAnnounce.get(),
BtRegistry::getBtAnnounce("test").get());
btRegistry.getBtAnnounce("test").get());
}
void BtRegistryTest::testGetBtProgressInfoFile() {
CPPUNIT_ASSERT(!BtRegistry::getBtProgressInfoFile("test").get());
BtRegistry btRegistry;
CPPUNIT_ASSERT(!btRegistry.getBtProgressInfoFile("test").get());
SharedHandle<BtProgressInfoFile> btProgressInfoFile(new MockBtProgressInfoFile());
BtRegistry::registerBtProgressInfoFile("test", btProgressInfoFile);
btRegistry.registerBtProgressInfoFile("test", btProgressInfoFile);
CPPUNIT_ASSERT_EQUAL(btProgressInfoFile.get(),
BtRegistry::getBtProgressInfoFile("test").get());
}
void BtRegistryTest::testGetPeerObjectCluster() {
CPPUNIT_ASSERT(!BtRegistry::getPeerObjectCluster("test").get());
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster("test", cluster);
CPPUNIT_ASSERT(BtRegistry::getPeerObjectCluster("test").get());
BtRegistry::unregisterPeerObjectCluster("test");
CPPUNIT_ASSERT(!BtRegistry::getPeerObjectCluster("test").get());
btRegistry.getBtProgressInfoFile("test").get());
}
} // namespace aria2

View File

@ -1,18 +1,14 @@
#include "BtRejectMessage.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "PeerMessageUtil.h"
#include "Peer.h"
#include "FileEntry.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "BtMessageFactory.h"
#include "BtRequestFactory.h"
#include "BtMessageReceiver.h"
#include "ExtensionMessageFactory.h"
#include "PeerConnection.h"
#include "MockBtMessageDispatcher.h"
#include "MockBtContext.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -67,37 +63,28 @@ public:
typedef SharedHandle<MockBtMessageDispatcher2> MockBtMessageDispatcher2Handle;
SharedHandle<MockBtContext> _btContext;
SharedHandle<Peer> peer;
SharedHandle<MockBtMessageDispatcher2> dispatcher;
SharedHandle<BtRejectMessage> msg;
void setUp() {
BtRegistry::unregisterAll();
peer.reset(new Peer("host", 6969));
peer->allocateSessionResource(1024, 1024*1024);
SharedHandle<MockBtContext> btContext(new MockBtContext());
btContext->setInfoHash((const unsigned char*)"12345678901234567890");
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> po(new PeerObject());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po);
_btContext.reset(new MockBtContext());
_btContext->setInfoHash((const unsigned char*)"12345678901234567890");
dispatcher.reset(new MockBtMessageDispatcher2());
PEER_OBJECT(btContext, peer)->btMessageDispatcher = dispatcher;
msg.reset(new BtRejectMessage());
msg->setPeer(peer);
msg->setBtContext(btContext);
msg->setBtContext(_btContext);
msg->setIndex(1);
msg->setBegin(16);
msg->setLength(32);
msg->setBtMessageDispatcher(dispatcher);
}
void tearDown() {
BtRegistry::unregisterAll();
}
};
@ -151,11 +138,13 @@ void BtRejectMessageTest::testDoReceivedAction() {
RequestSlot slot(1, 16, 32, 2);
dispatcher->setRequestSlot(slot);
CPPUNIT_ASSERT(!RequestSlot::isNull(dispatcher->getOutstandingRequest(1, 16, 32)));
CPPUNIT_ASSERT
(!RequestSlot::isNull(dispatcher->getOutstandingRequest(1, 16, 32)));
msg->doReceivedAction();
CPPUNIT_ASSERT(RequestSlot::isNull(dispatcher->getOutstandingRequest(1, 16, 32)));
CPPUNIT_ASSERT
(RequestSlot::isNull(dispatcher->getOutstandingRequest(1, 16, 32)));
}
void BtRejectMessageTest::testDoReceivedActionNoMatch() {
@ -163,11 +152,13 @@ void BtRejectMessageTest::testDoReceivedActionNoMatch() {
RequestSlot slot(2, 16, 32, 2);
dispatcher->setRequestSlot(slot);
CPPUNIT_ASSERT(!RequestSlot::isNull(dispatcher->getOutstandingRequest(2, 16, 32)));
CPPUNIT_ASSERT
(!RequestSlot::isNull(dispatcher->getOutstandingRequest(2, 16, 32)));
msg->doReceivedAction();
CPPUNIT_ASSERT(!RequestSlot::isNull(dispatcher->getOutstandingRequest(2, 16, 32)));
CPPUNIT_ASSERT
(!RequestSlot::isNull(dispatcher->getOutstandingRequest(2, 16, 32)));
}
@ -175,7 +166,8 @@ void BtRejectMessageTest::testDoReceivedActionFastExtensionDisabled() {
RequestSlot slot(1, 16, 32, 2);
dispatcher->setRequestSlot(slot);
CPPUNIT_ASSERT(!RequestSlot::isNull(dispatcher->getOutstandingRequest(1, 16, 32)));
CPPUNIT_ASSERT
(!RequestSlot::isNull(dispatcher->getOutstandingRequest(1, 16, 32)));
try {
msg->doReceivedAction();
CPPUNIT_FAIL("exception must be thrown.");

View File

@ -10,15 +10,8 @@
#include "MockPieceStorage.h"
#include "MockBtMessageFactory.h"
#include "MockBtMessageDispatcher.h"
#include "DefaultBtContext.h"
#include "BtAbortOutstandingRequestEvent.h"
#include "Peer.h"
#include "BtRegistry.h"
#include "PeerObject.h"
#include "BtMessageReceiver.h"
#include "BtRequestFactory.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include "FileEntry.h"
#include "BtHandshakeMessage.h"
#include "BtRequestMessageValidator.h"
@ -75,7 +68,10 @@ public:
uint32_t begin;
size_t length;
public:
MockBtMessage2(std::string type, size_t index, uint32_t begin, size_t length):type(type), index(index), begin(begin), length(length) {}
MockBtMessage2(std::string type, size_t index, uint32_t begin,
size_t length)
:
type(type), index(index), begin(begin), length(length) {}
};
typedef SharedHandle<MockBtMessage2> MockBtMessage2Handle;
@ -84,59 +80,54 @@ public:
public:
virtual SharedHandle<BtMessage>
createPieceMessage(size_t index, uint32_t begin, size_t length) {
SharedHandle<MockBtMessage2> btMsg(new MockBtMessage2("piece", index, begin, length));
SharedHandle<MockBtMessage2> btMsg
(new MockBtMessage2("piece", index, begin, length));
return btMsg;
}
virtual SharedHandle<BtMessage>
createRejectMessage(size_t index, uint32_t begin, size_t length) {
SharedHandle<MockBtMessage2> btMsg(new MockBtMessage2("reject", index, begin, length));
SharedHandle<MockBtMessage2> btMsg
(new MockBtMessage2("reject", index, begin, length));
return btMsg;
}
};
typedef SharedHandle<MockBtMessageFactory2> MockBtMessageFactory2Handle;
SharedHandle<Peer> peer;
SharedHandle<MockBtMessageDispatcher> dispatcher;
SharedHandle<MockBtContext> _btContext;
SharedHandle<MockPieceStorage> _pieceStorage;
SharedHandle<Peer> _peer;
SharedHandle<MockBtMessageDispatcher> _dispatcher;
SharedHandle<MockBtMessageFactory> _messageFactory;
SharedHandle<BtRequestMessage> msg;
void setUp() {
BtRegistry::unregisterAll();
_btContext.reset(new MockBtContext());
_btContext->setInfoHash((const unsigned char*)"12345678901234567890");
_btContext->setPieceLength(16*1024);
_btContext->setTotalLength(256*1024);
SharedHandle<MockBtContext> btContext(new MockBtContext());
btContext->setInfoHash((const unsigned char*)"12345678901234567890");
btContext->setPieceLength(16*1024);
btContext->setTotalLength(256*1024);
_pieceStorage.reset(new MockPieceStorage2());
SharedHandle<MockPieceStorage> pieceStorage(new MockPieceStorage2());
_peer.reset(new Peer("host", 6969));
_peer->allocateSessionResource(_btContext->getPieceLength(),
_btContext->getTotalLength());
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
pieceStorage);
_dispatcher.reset(new MockBtMessageDispatcher());
peer.reset(new Peer("host", 6969));
peer->allocateSessionResource(btContext->getPieceLength(),
btContext->getTotalLength());
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> po(new PeerObject());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po);
dispatcher.reset(new MockBtMessageDispatcher());
PEER_OBJECT(btContext, peer)->btMessageDispatcher = dispatcher;
PEER_OBJECT(btContext, peer)->btMessageFactory.reset(new MockBtMessageFactory2());
_messageFactory.reset(new MockBtMessageFactory2());
msg.reset(new BtRequestMessage());
msg->setBtContext(btContext);
msg->setPeer(peer);
msg->setBtContext(_btContext);
msg->setPeer(_peer);
msg->setIndex(1);
msg->setBegin(16);
msg->setLength(32);
msg->setBlockIndex(2);
msg->setBtMessageDispatcher(dispatcher);
msg->setBtMessageFactory(BT_MESSAGE_FACTORY(btContext, peer));
msg->setBtMessageDispatcher(_dispatcher);
msg->setBtMessageFactory(_messageFactory);
msg->setPieceStorage(_pieceStorage);
}
};
@ -187,11 +178,12 @@ void BtRequestMessageTest::testGetMessage() {
}
void BtRequestMessageTest::testDoReceivedAction_hasPieceAndAmNotChoking() {
peer->amChoking(false);
_peer->amChoking(false);
msg->doReceivedAction();
CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher->messageQueue.size());
MockBtMessage2* pieceMsg = (MockBtMessage2*)dispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL((size_t)1, _dispatcher->messageQueue.size());
MockBtMessage2* pieceMsg =
(MockBtMessage2*)_dispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL(std::string("piece"), pieceMsg->type);
CPPUNIT_ASSERT_EQUAL((size_t)1, pieceMsg->index);
CPPUNIT_ASSERT_EQUAL((uint32_t)16, pieceMsg->begin);
@ -199,12 +191,13 @@ void BtRequestMessageTest::testDoReceivedAction_hasPieceAndAmNotChoking() {
}
void BtRequestMessageTest::testDoReceivedAction_hasPieceAndAmChokingAndFastExtensionEnabled() {
peer->amChoking(true);
peer->setFastExtensionEnabled(true);
_peer->amChoking(true);
_peer->setFastExtensionEnabled(true);
msg->doReceivedAction();
CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher->messageQueue.size());
MockBtMessage2* pieceMsg = (MockBtMessage2*)dispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL((size_t)1, _dispatcher->messageQueue.size());
MockBtMessage2* pieceMsg =
(MockBtMessage2*)_dispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL(std::string("reject"), pieceMsg->type);
CPPUNIT_ASSERT_EQUAL((size_t)1, pieceMsg->index);
CPPUNIT_ASSERT_EQUAL((uint32_t)16, pieceMsg->begin);
@ -212,20 +205,21 @@ void BtRequestMessageTest::testDoReceivedAction_hasPieceAndAmChokingAndFastExten
}
void BtRequestMessageTest::testDoReceivedAction_hasPieceAndAmChokingAndFastExtensionDisabled() {
peer->amChoking(true);
_peer->amChoking(true);
msg->doReceivedAction();
CPPUNIT_ASSERT_EQUAL((size_t)0, dispatcher->messageQueue.size());
CPPUNIT_ASSERT_EQUAL((size_t)0, _dispatcher->messageQueue.size());
}
void BtRequestMessageTest::testDoReceivedAction_doesntHavePieceAndFastExtensionEnabled() {
msg->setIndex(2);
peer->amChoking(false);
peer->setFastExtensionEnabled(true);
_peer->amChoking(false);
_peer->setFastExtensionEnabled(true);
msg->doReceivedAction();
CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher->messageQueue.size());
MockBtMessage2* pieceMsg = (MockBtMessage2*)dispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL((size_t)1, _dispatcher->messageQueue.size());
MockBtMessage2* pieceMsg =
(MockBtMessage2*)_dispatcher->messageQueue.front().get();
CPPUNIT_ASSERT_EQUAL(std::string("reject"), pieceMsg->type);
CPPUNIT_ASSERT_EQUAL((size_t)2, pieceMsg->index);
CPPUNIT_ASSERT_EQUAL((uint32_t)16, pieceMsg->begin);
@ -234,10 +228,10 @@ void BtRequestMessageTest::testDoReceivedAction_doesntHavePieceAndFastExtensionE
void BtRequestMessageTest::testDoReceivedAction_doesntHavePieceAndFastExtensionDisabled() {
msg->setIndex(2);
peer->amChoking(false);
_peer->amChoking(false);
msg->doReceivedAction();
CPPUNIT_ASSERT_EQUAL((size_t)0, dispatcher->messageQueue.size());
CPPUNIT_ASSERT_EQUAL((size_t)0, _dispatcher->messageQueue.size());
}
void BtRequestMessageTest::testHandleAbortRequestEvent() {

View File

@ -1,11 +1,13 @@
#include "DHTPeerAnnounceEntry.h"
#include <cstring>
#include <cppunit/extensions/HelperMacros.h>
#include "Exception.h"
#include "Util.h"
#include "MockBtContext.h"
#include "MockPeerStorage.h"
#include "BtRegistry.h"
#include "FileEntry.h"
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -18,16 +20,6 @@ class DHTPeerAnnounceEntryTest:public CppUnit::TestFixture {
CPPUNIT_TEST(testGetPeers);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
BtRegistry::unregisterAll();
}
void tearDown()
{
BtRegistry::unregisterAll();
}
void testRemoveStalePeerAddrEntry();
void testEmpty();
void testAddPeerAddrEntry();
@ -69,7 +61,7 @@ void DHTPeerAnnounceEntryTest::testEmpty()
}
{
DHTPeerAnnounceEntry entry(infohash);
entry.setBtContext(SharedHandle<BtContext>(new MockBtContext()));
entry.setPeerStorage(SharedHandle<PeerStorage>(new MockPeerStorage()));
CPPUNIT_ASSERT(!entry.empty());
}
{
@ -100,8 +92,6 @@ void DHTPeerAnnounceEntryTest::testGetPeers()
unsigned char infohash[DHT_ID_LENGTH];
memset(infohash, 0xff, DHT_ID_LENGTH);
SharedHandle<MockBtContext> ctx(new MockBtContext());
ctx->setInfoHash(infohash);
SharedHandle<MockPeerStorage> peerStorage(new MockPeerStorage());
{
SharedHandle<Peer> activePeers[2];
@ -111,7 +101,6 @@ void DHTPeerAnnounceEntryTest::testGetPeers()
peerStorage->setActivePeers(std::deque<SharedHandle<Peer> >(&activePeers[0],
&activePeers[2]));
}
BtRegistry::registerPeerStorage(ctx->getInfoHashAsString(), peerStorage);
DHTPeerAnnounceEntry entry(infohash);
{
@ -132,7 +121,7 @@ void DHTPeerAnnounceEntryTest::testGetPeers()
CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.2"), peers[1]->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)6882, peers[1]->port);
}
entry.setBtContext(ctx);
entry.setPeerStorage(peerStorage);
{
std::deque<SharedHandle<Peer> > peers;
entry.getPeers(peers);

View File

@ -1,11 +1,14 @@
#include "DHTPeerAnnounceStorage.h"
#include <cppunit/extensions/HelperMacros.h>
#include "Exception.h"
#include "Util.h"
#include "MockBtContext.h"
#include "MockPeerStorage.h"
#include "DHTConstants.h"
#include "Peer.h"
#include "FileEntry.h"
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -16,10 +19,6 @@ class DHTPeerAnnounceStorageTest:public CppUnit::TestFixture {
CPPUNIT_TEST(testRemovePeerAnnounce);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {}
void tearDown() {}
void testAddAnnounce();
void testRemovePeerAnnounce();
};
@ -59,17 +58,21 @@ void DHTPeerAnnounceStorageTest::testRemovePeerAnnounce()
SharedHandle<MockBtContext> ctx1(new MockBtContext());
ctx1->setInfoHash(infohash1);
SharedHandle<MockPeerStorage> peerStorage1(new MockPeerStorage());
SharedHandle<MockBtContext> ctx2(new MockBtContext());
ctx2->setInfoHash(infohash2);
storage.addPeerAnnounce(infohash1, "192.168.0.1", 6881);
storage.addPeerAnnounce(ctx1);
storage.addPeerAnnounce(ctx2);
SharedHandle<MockPeerStorage> peerStorage2(new MockPeerStorage());
storage.removePeerAnnounce(ctx2);
storage.addPeerAnnounce(infohash1, "192.168.0.1", 6881);
storage.addPeerAnnounce(ctx1->getInfoHash(), peerStorage1);
storage.addPeerAnnounce(ctx2->getInfoHash(), peerStorage2);
storage.removeLocalPeerAnnounce(ctx2->getInfoHash());
CPPUNIT_ASSERT(!storage.contains(infohash2));
storage.removePeerAnnounce(ctx1);
storage.removeLocalPeerAnnounce(ctx1->getInfoHash());
CPPUNIT_ASSERT(storage.contains(infohash1));
}

View File

@ -1,22 +1,19 @@
#include "DefaultBtMessageDispatcher.h"
#include <cassert>
#include <cppunit/extensions/HelperMacros.h>
#include "Util.h"
#include "Exception.h"
#include "MockPieceStorage.h"
#include "MockPeerStorage.h"
#include "BtRegistry.h"
#include "DefaultBtContext.h"
#include "MockBtMessage.h"
#include "MockBtMessageFactory.h"
#include "prefs.h"
#include "BtCancelSendingPieceEvent.h"
#include "PeerObject.h"
#include "BtRequestFactory.h"
#include "BtMessageReceiver.h"
#include "ExtensionMessageFactory.h"
#include "PeerConnection.h"
#include "BtHandshakeMessage.h"
#include <cppunit/extensions/HelperMacros.h>
#include <cassert>
namespace aria2 {
@ -44,6 +41,7 @@ private:
SharedHandle<DefaultBtMessageDispatcher> btMessageDispatcher;
SharedHandle<MockPeerStorage> peerStorage;
SharedHandle<MockPieceStorage> pieceStorage;
SharedHandle<MockBtMessageFactory> _messageFactory;
public:
void tearDown() {}
@ -137,26 +135,17 @@ public:
btContext->getTotalLength());
peerStorage.reset(new MockPeerStorage());
pieceStorage.reset(new MockPieceStorage());
BtRegistry::unregisterAll();
BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(),
peerStorage);
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
pieceStorage);
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> peerObject(new PeerObject());
peerObject->btMessageFactory.reset(new MockBtMessageFactory2());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), peerObject);
_messageFactory.reset(new MockBtMessageFactory2());
btMessageDispatcher.reset(new DefaultBtMessageDispatcher());
btMessageDispatcher->setCuid(1);
btMessageDispatcher->setBtContext(btContext);
btMessageDispatcher->setPeer(peer);
btMessageDispatcher->setBtContext(btContext);
btMessageDispatcher->setPieceStorage(pieceStorage);
btMessageDispatcher->setPeerStorage(peerStorage);
btMessageDispatcher->setBtMessageFactory(_messageFactory);
btMessageDispatcher->setCuid(1);
btMessageDispatcher->setMaxUploadSpeedLimit(0);
btMessageDispatcher->setBtMessageFactory(peerObject->btMessageFactory);
}
};
@ -235,7 +224,8 @@ void DefaultBtMessageDispatcherTest::testSendMessages_overUploadLimit() {
CPPUNIT_ASSERT(!msg2->isSendCalled());
CPPUNIT_ASSERT(msg3->isSendCalled());
CPPUNIT_ASSERT_EQUAL((size_t)2, btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)2,
btMessageDispatcher->getMessageQueue().size());
}
void DefaultBtMessageDispatcherTest::testSendMessages_sendingInProgress() {
@ -259,7 +249,8 @@ void DefaultBtMessageDispatcherTest::testSendMessages_sendingInProgress() {
CPPUNIT_ASSERT(msg2->isSendCalled());
CPPUNIT_ASSERT(!msg3->isSendCalled());
CPPUNIT_ASSERT_EQUAL((size_t)2, btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)2,
btMessageDispatcher->getMessageQueue().size());
}
void DefaultBtMessageDispatcherTest::testDoCancelSendingPieceAction() {
@ -287,21 +278,17 @@ void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing() {
SharedHandle<MockPieceStorage2> pieceStorage(new MockPieceStorage2());
pieceStorage->setPiece(piece);
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
pieceStorage);
btMessageDispatcher.reset(new DefaultBtMessageDispatcher());
btMessageDispatcher->setCuid(1);
btMessageDispatcher->setBtContext(btContext);
btMessageDispatcher->setPeer(peer);
btMessageDispatcher->setRequestTimeout(60);
btMessageDispatcher->setPieceStorage(pieceStorage);
btMessageDispatcher->addOutstandingRequest(slot);
btMessageDispatcher->checkRequestSlotAndDoNecessaryThing();
CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->getRequestSlots().size());
CPPUNIT_ASSERT_EQUAL((size_t)0,
btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)1,
btMessageDispatcher->getRequestSlots().size());
}
void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_timeout() {
@ -316,23 +303,17 @@ void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_tim
SharedHandle<MockPieceStorage2> pieceStorage(new MockPieceStorage2());
pieceStorage->setPiece(piece);
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
pieceStorage);
btMessageDispatcher.reset(new DefaultBtMessageDispatcher());
btMessageDispatcher->setCuid(1);
btMessageDispatcher->setBtContext(btContext);
btMessageDispatcher->setPeer(peer);
btMessageDispatcher->setRequestTimeout(60);
btMessageDispatcher->setBtMessageFactory(BT_MESSAGE_FACTORY(btContext,
peer));
btMessageDispatcher->setPieceStorage(pieceStorage);
btMessageDispatcher->addOutstandingRequest(slot);
btMessageDispatcher->checkRequestSlotAndDoNecessaryThing();
CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->getRequestSlots().size());
CPPUNIT_ASSERT_EQUAL((size_t)0,
btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)0,
btMessageDispatcher->getRequestSlots().size());
CPPUNIT_ASSERT_EQUAL(false, piece->isBlockUsed(0));
CPPUNIT_ASSERT_EQUAL(true, peer->snubbing());
}
@ -345,24 +326,17 @@ void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_com
SharedHandle<MockPieceStorage2> pieceStorage(new MockPieceStorage2());
pieceStorage->setPiece(piece);
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
pieceStorage);
btMessageDispatcher.reset(new DefaultBtMessageDispatcher());
btMessageDispatcher->setCuid(1);
btMessageDispatcher->setBtContext(btContext);
btMessageDispatcher->setPeer(peer);
btMessageDispatcher->setRequestTimeout(60);
btMessageDispatcher->setBtMessageFactory(BT_MESSAGE_FACTORY(btContext,
peer));
btMessageDispatcher->setPieceStorage(pieceStorage);
btMessageDispatcher->addOutstandingRequest(slot);
btMessageDispatcher->checkRequestSlotAndDoNecessaryThing();
CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->getRequestSlots().size());
CPPUNIT_ASSERT_EQUAL((size_t)1,
btMessageDispatcher->getMessageQueue().size());
CPPUNIT_ASSERT_EQUAL((size_t)0,
btMessageDispatcher->getRequestSlots().size());
}
void DefaultBtMessageDispatcherTest::testIsSendingInProgress() {
@ -378,7 +352,8 @@ void DefaultBtMessageDispatcherTest::testIsSendingInProgress() {
void DefaultBtMessageDispatcherTest::testCountOutstandingRequest() {
RequestSlot slot(0, 0, MY_PIECE_LENGTH, 0);
btMessageDispatcher->addOutstandingRequest(slot);
CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->countOutstandingRequest());
CPPUNIT_ASSERT_EQUAL((size_t)1,
btMessageDispatcher->countOutstandingRequest());
}
void DefaultBtMessageDispatcherTest::testIsOutstandingRequest() {
@ -401,7 +376,8 @@ void DefaultBtMessageDispatcherTest::testGetOutstandingRequest() {
RequestSlot s3 = btMessageDispatcher->getOutstandingRequest(1, 1024, 17*1024);
CPPUNIT_ASSERT(RequestSlot::isNull(s3));
RequestSlot s4 = btMessageDispatcher->getOutstandingRequest(1, 2*1024, 16*1024);
RequestSlot s4 =
btMessageDispatcher->getOutstandingRequest(1, 2*1024, 16*1024);
CPPUNIT_ASSERT(RequestSlot::isNull(s4));
RequestSlot s5 = btMessageDispatcher->getOutstandingRequest(2, 1024, 16*1024);

View File

@ -1,21 +1,19 @@
#include "DefaultBtMessageFactory.h"
#include <cstring>
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include "Peer.h"
#include "PeerMessageUtil.h"
#include "BtRegistry.h"
#include "MockBtContext.h"
#include "MockExtensionMessageFactory.h"
#include "BtExtendedMessage.h"
#include "BtPortMessage.h"
#include "PeerObject.h"
#include "BtRequestFactory.h"
#include "BtMessageDispatcher.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "Exception.h"
#include "FileEntry.h"
#include <cstring>
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -28,34 +26,26 @@ class DefaultBtMessageFactoryTest:public CppUnit::TestFixture {
private:
SharedHandle<MockBtContext> _btContext;
SharedHandle<Peer> _peer;
SharedHandle<MockExtensionMessageFactory> _exmsgFactory;
SharedHandle<DefaultBtMessageFactory> _factory;
public:
void setUp()
{
BtRegistry::unregisterAll();
SharedHandle<MockBtContext> btContext(new MockBtContext());
_btContext.reset(new MockBtContext());
unsigned char infohash[20];
memset(infohash, 0, sizeof(infohash));
btContext->setInfoHash(infohash);
_btContext = btContext;
_btContext->setInfoHash(infohash);
_peer.reset(new Peer("192.168.0.1", 6969));
_peer->allocateSessionResource(1024, 1024*1024);
_peer->setExtendedMessagingEnabled(true);
SharedHandle<MockExtensionMessageFactory> exmsgFactory
(new MockExtensionMessageFactory());
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(_btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> peerObject(new PeerObject());
peerObject->extensionMessageFactory = exmsgFactory;
_exmsgFactory.reset(new MockExtensionMessageFactory());
PEER_OBJECT_CLUSTER(_btContext)->registerHandle(_peer->getID(), peerObject);
}
void tearDown()
{
BtRegistry::unregisterAll();
_factory.reset(new DefaultBtMessageFactory());
_factory->setBtContext(_btContext);
_factory->setPeer(_peer);
_factory->setExtensionMessageFactory(_exmsgFactory);
}
void testCreateBtMessage_BtExtendedMessage();
@ -67,26 +57,22 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DefaultBtMessageFactoryTest);
void DefaultBtMessageFactoryTest::testCreateBtMessage_BtExtendedMessage()
{
DefaultBtMessageFactory factory;
factory.setBtContext(_btContext);
factory.setPeer(_peer);
// payload:{4:name3:foo}->11bytes
std::string payload = "4:name3:foo";
char msg[17];// 6+11bytes
PeerMessageUtil::createPeerMessageString((unsigned char*)msg, sizeof(msg), 13, 20);
PeerMessageUtil::createPeerMessageString((unsigned char*)msg, sizeof(msg),
13, 20);
msg[5] = 1; // Set dummy extended message ID 1
memcpy(msg+6, payload.c_str(), payload.size());
SharedHandle<BtExtendedMessage> m
(dynamic_pointer_cast<BtExtendedMessage>
(factory.createBtMessage((const unsigned char*)msg+4, sizeof(msg))));
(_factory->createBtMessage((const unsigned char*)msg+4, sizeof(msg))));
try {
// disable extended messaging
_peer->setExtendedMessagingEnabled(false);
factory.createBtMessage((const unsigned char*)msg+4, sizeof(msg));
_factory->createBtMessage((const unsigned char*)msg+4, sizeof(msg));
CPPUNIT_FAIL("exception must be thrown.");
} catch(Exception& e) {
std::cerr << e.stackTrace() << std::endl;
@ -95,10 +81,6 @@ void DefaultBtMessageFactoryTest::testCreateBtMessage_BtExtendedMessage()
void DefaultBtMessageFactoryTest::testCreatePortMessage()
{
DefaultBtMessageFactory factory;
factory.setBtContext(_btContext);
factory.setPeer(_peer);
{
unsigned char data[7];
PeerMessageUtil::createPeerMessageString(data, sizeof(data), 3, 9);
@ -106,7 +88,7 @@ void DefaultBtMessageFactoryTest::testCreatePortMessage()
try {
SharedHandle<BtPortMessage> m
(dynamic_pointer_cast<BtPortMessage>
(factory.createBtMessage(&data[4], sizeof(data)-4)));
(_factory->createBtMessage(&data[4], sizeof(data)-4)));
CPPUNIT_ASSERT(!m.isNull());
CPPUNIT_ASSERT_EQUAL((uint16_t)6881, m->getPort());
} catch(Exception& e) {
@ -115,7 +97,7 @@ void DefaultBtMessageFactoryTest::testCreatePortMessage()
}
{
SharedHandle<BtPortMessage> m
(dynamic_pointer_cast<BtPortMessage>(factory.createPortMessage(6881)));
(dynamic_pointer_cast<BtPortMessage>(_factory->createPortMessage(6881)));
CPPUNIT_ASSERT_EQUAL((uint16_t)6881, m->getPort());
}
}

View File

@ -1,4 +1,9 @@
#include "DefaultBtProgressInfoFile.h"
#include <fstream>
#include <cppunit/extensions/HelperMacros.h>
#include "Option.h"
#include "Util.h"
#include "Exception.h"
@ -8,13 +13,10 @@
#include "MockPeerStorage.h"
#include "MockPieceStorage.h"
#include "BtRuntime.h"
#include "BtRegistry.h"
#include "prefs.h"
#include "SingleFileDownloadContext.h"
#include "Piece.h"
#include "FileEntry.h"
#include <fstream>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -36,16 +38,16 @@ private:
#ifdef ENABLE_BITTORRENT
SharedHandle<MockBtContext> _btContext;
SharedHandle<MockPeerStorage> _peerStorage;
SharedHandle<BtRuntime> _btRuntime;
#endif // ENABLE_BITTORRENT
SharedHandle<MockPieceStorage> _pieceStorage;
SharedHandle<Option> _option;
SharedHandle<BitfieldMan> _bitfield;
public:
void setUp() {
BtRegistry::unregisterAll();
}
void initializeMembers(int32_t pieceLength, int64_t totalLength)
{
_option.reset(new Option());
@ -64,27 +66,11 @@ public:
_btContext.reset(new MockBtContext());
_btContext->setInfoHash(infoHash);
SharedHandle<MockPeerStorage> peerStorage(new MockPeerStorage());
SharedHandle<BtRuntime> btRuntime(new BtRuntime());
BtRegistry::registerBtContext(_btContext->getInfoHashAsString(),
_btContext);
BtRegistry::registerPieceStorage(_btContext->getInfoHashAsString(),
_pieceStorage);
BtRegistry::registerPeerStorage(_btContext->getInfoHashAsString(),
peerStorage);
BtRegistry::registerBtRuntime(_btContext->getInfoHashAsString(),
btRuntime);
_peerStorage.reset(new MockPeerStorage());
_btRuntime.reset(new BtRuntime());
#endif // ENABLE_BITTORRENT
}
void tearDown()
{
BtRegistry::unregisterAll();
}
void testSave();
void testLoad();
void testLoad_compat();
@ -112,6 +98,9 @@ void DefaultBtProgressInfoFileTest::testLoad_compat()
_btContext->setNumPieces(80);
DefaultBtProgressInfoFile infoFile(_btContext, _pieceStorage, _option.get());
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./load.aria2"), infoFile.getFilename());
infoFile.load();
@ -122,11 +111,12 @@ void DefaultBtProgressInfoFileTest::testLoad_compat()
CPPUNIT_ASSERT_EQUAL((uint64_t)81920, _btContext->getTotalLength());
// upload length
CPPUNIT_ASSERT_EQUAL((uint64_t)1024, BT_RUNTIME(_btContext)->getUploadLengthAtStartup());
CPPUNIT_ASSERT_EQUAL((uint64_t)1024, _btRuntime->getUploadLengthAtStartup());
// bitfield
CPPUNIT_ASSERT_EQUAL(std::string("fffffffffffffffffffe"),
Util::toHex(_bitfield->getBitfield(), _bitfield->getBitfieldLength()));
Util::toHex(_bitfield->getBitfield(),
_bitfield->getBitfieldLength()));
// the number of in-flight pieces
CPPUNIT_ASSERT_EQUAL((size_t)2,
@ -161,6 +151,8 @@ void DefaultBtProgressInfoFileTest::testLoad()
DefaultBtProgressInfoFile infoFile(_btContext, _pieceStorage, _option.get());
CPPUNIT_ASSERT_EQUAL(std::string("./load-v0001.aria2"),
infoFile.getFilename());
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
infoFile.load();
@ -170,11 +162,12 @@ void DefaultBtProgressInfoFileTest::testLoad()
CPPUNIT_ASSERT_EQUAL((uint64_t)81920, _btContext->getTotalLength());
// upload length
CPPUNIT_ASSERT_EQUAL((uint64_t)1024, BT_RUNTIME(_btContext)->getUploadLengthAtStartup());
CPPUNIT_ASSERT_EQUAL((uint64_t)1024, _btRuntime->getUploadLengthAtStartup());
// bitfield
CPPUNIT_ASSERT_EQUAL(std::string("fffffffffffffffffffe"),
Util::toHex(_bitfield->getBitfield(), _bitfield->getBitfieldLength()));
Util::toHex(_bitfield->getBitfield(),
_bitfield->getBitfieldLength()));
// the number of in-flight pieces
CPPUNIT_ASSERT_EQUAL((size_t)2,
@ -209,7 +202,7 @@ void DefaultBtProgressInfoFileTest::testSave()
_pieceStorage->setCompletedLength(80896);
TransferStat stat;
stat.setAllTimeUploadLength(1024);
dynamic_pointer_cast<MockPeerStorage>(PEER_STORAGE(_btContext))->setStat(stat);
_peerStorage->setStat(stat);
SharedHandle<Piece> p1(new Piece(1, 1024));
SharedHandle<Piece> p2(new Piece(2, 512));
@ -219,7 +212,11 @@ void DefaultBtProgressInfoFileTest::testSave()
_pieceStorage->addInFlightPiece(inFlightPieces);
DefaultBtProgressInfoFile infoFile(_btContext, _pieceStorage, _option.get());
CPPUNIT_ASSERT_EQUAL(std::string("./save-temp.aria2"), infoFile.getFilename());
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./save-temp.aria2"),
infoFile.getFilename());
infoFile.save();
@ -235,7 +232,8 @@ void DefaultBtProgressInfoFileTest::testSave()
unsigned char extension[4];
in.read((char*)extension, sizeof(extension));
CPPUNIT_ASSERT_EQUAL(std::string("00000001"), Util::toHex(extension, sizeof(extension)));
CPPUNIT_ASSERT_EQUAL(std::string("00000001"),
Util::toHex(extension, sizeof(extension)));
uint32_t infoHashLength;
in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
@ -320,7 +318,11 @@ void DefaultBtProgressInfoFileTest::testLoad_nonBt_compat()
(new SingleFileDownloadContext(1024, 81920, "load-nonBt"));
DefaultBtProgressInfoFile infoFile(dctx, _pieceStorage, _option.get());
CPPUNIT_ASSERT_EQUAL(std::string("./load-nonBt.aria2"), infoFile.getFilename());
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./load-nonBt.aria2"),
infoFile.getFilename());
infoFile.load();
// check the contents of objects
@ -330,7 +332,8 @@ void DefaultBtProgressInfoFileTest::testLoad_nonBt_compat()
// bitfield
CPPUNIT_ASSERT_EQUAL(std::string("fffffffffffffffffffe"),
Util::toHex(_bitfield->getBitfield(), _bitfield->getBitfieldLength()));
Util::toHex(_bitfield->getBitfield(),
_bitfield->getBitfieldLength()));
// the number of in-flight pieces
CPPUNIT_ASSERT_EQUAL((size_t)2,
@ -361,6 +364,8 @@ void DefaultBtProgressInfoFileTest::testLoad_nonBt()
(new SingleFileDownloadContext(1024, 81920, "load-nonBt-v0001"));
DefaultBtProgressInfoFile infoFile(dctx, _pieceStorage, _option.get());
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./load-nonBt-v0001.aria2"),
infoFile.getFilename());
infoFile.load();
@ -372,7 +377,8 @@ void DefaultBtProgressInfoFileTest::testLoad_nonBt()
// bitfield
CPPUNIT_ASSERT_EQUAL(std::string("fffffffffffffffffffe"),
Util::toHex(_bitfield->getBitfield(), _bitfield->getBitfieldLength()));
Util::toHex(_bitfield->getBitfield(),
_bitfield->getBitfieldLength()));
// the number of in-flight pieces
CPPUNIT_ASSERT_EQUAL((size_t)2,
@ -404,6 +410,9 @@ void DefaultBtProgressInfoFileTest::testLoad_nonBt_pieceLengthShorter()
(new SingleFileDownloadContext(512, 81920, "load-nonBt-v0001"));
DefaultBtProgressInfoFile infoFile(dctx, _pieceStorage, _option.get());
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./load-nonBt-v0001.aria2"),
infoFile.getFilename());
infoFile.load();
@ -412,7 +421,8 @@ void DefaultBtProgressInfoFileTest::testLoad_nonBt_pieceLengthShorter()
// bitfield
CPPUNIT_ASSERT_EQUAL(std::string("fffffffffffffffffffffffffffffffffffffffc"),
Util::toHex(_bitfield->getBitfield(), _bitfield->getBitfieldLength()));
Util::toHex(_bitfield->getBitfield(),
_bitfield->getBitfieldLength()));
// the number of in-flight pieces
CPPUNIT_ASSERT_EQUAL((size_t)0,
@ -438,7 +448,10 @@ void DefaultBtProgressInfoFileTest::testSave_nonBt()
_pieceStorage->addInFlightPiece(inFlightPieces);
DefaultBtProgressInfoFile infoFile(dctx, _pieceStorage, _option.get());
CPPUNIT_ASSERT_EQUAL(std::string("./save-temp.aria2"), infoFile.getFilename());
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./save-temp.aria2"),
infoFile.getFilename());
infoFile.save();
@ -454,7 +467,8 @@ void DefaultBtProgressInfoFileTest::testSave_nonBt()
unsigned char extension[4];
in.read((char*)extension, sizeof(extension));
CPPUNIT_ASSERT_EQUAL(std::string("00000000"), Util::toHex(extension, sizeof(extension)));
CPPUNIT_ASSERT_EQUAL(std::string("00000000"),
Util::toHex(extension, sizeof(extension)));
uint32_t infoHashLength;
in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
@ -531,6 +545,9 @@ void DefaultBtProgressInfoFileTest::testUpdateFilename()
(new SingleFileDownloadContext(1024, 81920, "file1"));
DefaultBtProgressInfoFile infoFile(dctx, SharedHandle<MockPieceStorage>(), 0);
infoFile.setBtRuntime(_btRuntime);
infoFile.setPeerStorage(_peerStorage);
CPPUNIT_ASSERT_EQUAL(std::string("./file1.aria2"), infoFile.getFilename());
dctx->setUFilename("file1.1");

View File

@ -1,19 +1,17 @@
#include "DefaultBtRequestFactory.h"
#include <algorithm>
#include <cppunit/extensions/HelperMacros.h>
#include "MockBtMessage.h"
#include "MockBtMessageFactory.h"
#include "MockBtMessageDispatcher.h"
#include "MockBtContext.h"
#include "BtRegistry.h"
#include "MockPieceStorage.h"
#include "Peer.h"
#include "PeerObject.h"
#include "BtMessageReceiver.h"
#include "PeerConnection.h"
#include "ExtensionMessageFactory.h"
#include "FileEntry.h"
#include "BtHandshakeMessage.h"
#include <algorithm>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -28,8 +26,12 @@ class DefaultBtRequestFactoryTest:public CppUnit::TestFixture {
CPPUNIT_TEST(testGetTargetPieceIndexes);
CPPUNIT_TEST_SUITE_END();
private:
SharedHandle<DefaultBtRequestFactory> btRequestFactory;
SharedHandle<MockBtContext> btContext;
SharedHandle<Peer> _peer;
SharedHandle<DefaultBtRequestFactory> _requestFactory;
SharedHandle<MockBtContext> _btContext;
SharedHandle<MockPieceStorage> _pieceStorage;
SharedHandle<MockBtMessageFactory> _messageFactory;
SharedHandle<MockBtMessageDispatcher> _dispatcher;
public:
void testAddTargetPiece();
void testRemoveCompletedPiece();
@ -43,7 +45,8 @@ public:
size_t index;
size_t blockIndex;
MockBtRequestMessage(size_t index, size_t blockIndex):index(index), blockIndex(blockIndex) {}
MockBtRequestMessage(size_t index, size_t blockIndex):
index(index), blockIndex(blockIndex) {}
};
typedef SharedHandle<MockBtRequestMessage> MockBtRequestMessageHandle;
@ -82,42 +85,27 @@ public:
}
};
void setUp() {
BtRegistry::unregisterAll();
btContext.reset(new MockBtContext());
btContext->setInfoHash((const unsigned char*)"12345678901234567890");
btContext->setPieceLength(16*1024);
btContext->setTotalLength(256*1024);
SharedHandle<MockPieceStorage> pieceStorage(new MockPieceStorage());
BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
pieceStorage);
SharedHandle<Peer> peer(new Peer("host", 6969));
SharedHandle<PeerObjectCluster> cluster(new PeerObjectCluster());
BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
cluster);
SharedHandle<PeerObject> peerObject(new PeerObject());
peerObject->btMessageFactory.reset(new MockBtMessageFactory2());
PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), peerObject);
SharedHandle<MockBtMessageDispatcher> dispatcher
(new MockBtMessageDispatcher());
PEER_OBJECT(btContext, peer)->btMessageDispatcher = dispatcher;
btRequestFactory.reset(new DefaultBtRequestFactory());
btRequestFactory->setBtContext(btContext);
btRequestFactory->setPeer(peer);
btRequestFactory->setBtMessageDispatcher(dispatcher);
btRequestFactory->setBtMessageFactory(peerObject->btMessageFactory);
}
void tearDown()
void setUp()
{
BtRegistry::unregisterAll();
_btContext.reset(new MockBtContext());
_btContext->setInfoHash((const unsigned char*)"12345678901234567890");
_btContext->setPieceLength(16*1024);
_btContext->setTotalLength(256*1024);
_pieceStorage.reset(new MockPieceStorage());
_peer.reset(new Peer("host", 6969));
_messageFactory.reset(new MockBtMessageFactory2());
_dispatcher.reset(new MockBtMessageDispatcher());
_requestFactory.reset(new DefaultBtRequestFactory());
_requestFactory->setBtContext(_btContext);
_requestFactory->setPieceStorage(_pieceStorage);
_requestFactory->setPeer(_peer);
_requestFactory->setBtMessageDispatcher(_dispatcher);
_requestFactory->setBtMessageFactory(_messageFactory);
}
};
@ -127,39 +115,40 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DefaultBtRequestFactoryTest);
void DefaultBtRequestFactoryTest::testAddTargetPiece() {
{
SharedHandle<Piece> piece(new Piece(0, 16*1024*10));
btRequestFactory->addTargetPiece(piece);
CPPUNIT_ASSERT_EQUAL((size_t)1, btRequestFactory->countTargetPiece());
_requestFactory->addTargetPiece(piece);
CPPUNIT_ASSERT_EQUAL((size_t)1, _requestFactory->countTargetPiece());
}
{
SharedHandle<Piece> piece(new Piece(1, 16*1024*9));
piece->completeBlock(0);
btRequestFactory->addTargetPiece(piece);
CPPUNIT_ASSERT_EQUAL((size_t)2, btRequestFactory->countTargetPiece());
_requestFactory->addTargetPiece(piece);
CPPUNIT_ASSERT_EQUAL((size_t)2, _requestFactory->countTargetPiece());
}
CPPUNIT_ASSERT_EQUAL((size_t)18, btRequestFactory->countMissingBlock());
CPPUNIT_ASSERT_EQUAL((size_t)18, _requestFactory->countMissingBlock());
}
void DefaultBtRequestFactoryTest::testRemoveCompletedPiece() {
SharedHandle<Piece> piece1(new Piece(0, 16*1024));
SharedHandle<Piece> piece2(new Piece(1, 16*1024));
piece2->setAllBlock();
btRequestFactory->addTargetPiece(piece1);
btRequestFactory->addTargetPiece(piece2);
CPPUNIT_ASSERT_EQUAL((size_t)2, btRequestFactory->countTargetPiece());
btRequestFactory->removeCompletedPiece();
CPPUNIT_ASSERT_EQUAL((size_t)1, btRequestFactory->countTargetPiece());
CPPUNIT_ASSERT_EQUAL((size_t)0, btRequestFactory->getTargetPieces().front()->getIndex());
_requestFactory->addTargetPiece(piece1);
_requestFactory->addTargetPiece(piece2);
CPPUNIT_ASSERT_EQUAL((size_t)2, _requestFactory->countTargetPiece());
_requestFactory->removeCompletedPiece();
CPPUNIT_ASSERT_EQUAL((size_t)1, _requestFactory->countTargetPiece());
CPPUNIT_ASSERT_EQUAL((size_t)0,
_requestFactory->getTargetPieces().front()->getIndex());
}
void DefaultBtRequestFactoryTest::testCreateRequestMessages() {
int PIECE_LENGTH = 16*1024*2;
SharedHandle<Piece> piece1(new Piece(0, PIECE_LENGTH));
SharedHandle<Piece> piece2(new Piece(1, PIECE_LENGTH));
btRequestFactory->addTargetPiece(piece1);
btRequestFactory->addTargetPiece(piece2);
_requestFactory->addTargetPiece(piece1);
_requestFactory->addTargetPiece(piece2);
std::deque<SharedHandle<BtMessage> > msgs;
btRequestFactory->createRequestMessages(msgs, 3);
_requestFactory->createRequestMessages(msgs, 3);
CPPUNIT_ASSERT_EQUAL((size_t)3, msgs.size());
std::deque<SharedHandle<BtMessage> >::iterator itr = msgs.begin();
@ -177,7 +166,7 @@ void DefaultBtRequestFactoryTest::testCreateRequestMessages() {
{
std::deque<SharedHandle<BtMessage> > msgs;
btRequestFactory->createRequestMessages(msgs, 3);
_requestFactory->createRequestMessages(msgs, 3);
CPPUNIT_ASSERT_EQUAL((size_t)1, msgs.size());
}
}
@ -186,16 +175,16 @@ void DefaultBtRequestFactoryTest::testCreateRequestMessages_onEndGame() {
SharedHandle<MockBtMessageDispatcher2> dispatcher
(new MockBtMessageDispatcher2());
btRequestFactory->setBtMessageDispatcher(dispatcher);
_requestFactory->setBtMessageDispatcher(dispatcher);
int PIECE_LENGTH = 16*1024*2;
SharedHandle<Piece> piece1(new Piece(0, PIECE_LENGTH));
SharedHandle<Piece> piece2(new Piece(1, PIECE_LENGTH));
btRequestFactory->addTargetPiece(piece1);
btRequestFactory->addTargetPiece(piece2);
_requestFactory->addTargetPiece(piece1);
_requestFactory->addTargetPiece(piece2);
std::deque<SharedHandle<BtMessage> > msgs;
btRequestFactory->createRequestMessagesOnEndGame(msgs, 3);
_requestFactory->createRequestMessagesOnEndGame(msgs, 3);
std::deque<SharedHandle<MockBtRequestMessage> > mmsgs;
for(std::deque<SharedHandle<BtMessage> >::iterator i = msgs.begin();
@ -223,31 +212,33 @@ void DefaultBtRequestFactoryTest::testCreateRequestMessages_onEndGame() {
void DefaultBtRequestFactoryTest::testRemoveTargetPiece() {
SharedHandle<Piece> piece1(new Piece(0, 16*1024));
btRequestFactory->addTargetPiece(piece1);
_requestFactory->addTargetPiece(piece1);
CPPUNIT_ASSERT(std::find(btRequestFactory->getTargetPieces().begin(),
btRequestFactory->getTargetPieces().end(),
piece1) != btRequestFactory->getTargetPieces().end());
CPPUNIT_ASSERT(std::find(_requestFactory->getTargetPieces().begin(),
_requestFactory->getTargetPieces().end(),
piece1) !=
_requestFactory->getTargetPieces().end());
btRequestFactory->removeTargetPiece(piece1);
_requestFactory->removeTargetPiece(piece1);
CPPUNIT_ASSERT(std::find(btRequestFactory->getTargetPieces().begin(),
btRequestFactory->getTargetPieces().end(),
piece1) == btRequestFactory->getTargetPieces().end());
CPPUNIT_ASSERT(std::find(_requestFactory->getTargetPieces().begin(),
_requestFactory->getTargetPieces().end(),
piece1) ==
_requestFactory->getTargetPieces().end());
}
void DefaultBtRequestFactoryTest::testGetTargetPieceIndexes()
{
SharedHandle<Piece> piece1(new Piece(1, btContext->getPieceLength()));
SharedHandle<Piece> piece3(new Piece(3, btContext->getPieceLength()));
SharedHandle<Piece> piece5(new Piece(5, btContext->getPieceLength()));
SharedHandle<Piece> piece1(new Piece(1, _btContext->getPieceLength()));
SharedHandle<Piece> piece3(new Piece(3, _btContext->getPieceLength()));
SharedHandle<Piece> piece5(new Piece(5, _btContext->getPieceLength()));
btRequestFactory->addTargetPiece(piece3);
btRequestFactory->addTargetPiece(piece1);
btRequestFactory->addTargetPiece(piece5);
_requestFactory->addTargetPiece(piece3);
_requestFactory->addTargetPiece(piece1);
_requestFactory->addTargetPiece(piece5);
std::deque<size_t> indexes;
btRequestFactory->getTargetPieceIndexes(indexes);
_requestFactory->getTargetPieceIndexes(indexes);
CPPUNIT_ASSERT_EQUAL((size_t)3, indexes.size());
CPPUNIT_ASSERT_EQUAL((size_t)3, indexes[0]);
CPPUNIT_ASSERT_EQUAL((size_t)1, indexes[1]);

View File

@ -1,15 +1,17 @@
#include "DefaultExtensionMessageFactory.h"
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include "Peer.h"
#include "MockBtContext.h"
#include "MockPeerStorage.h"
#include "PeerMessageUtil.h"
#include "HandshakeExtensionMessage.h"
#include "UTPexExtensionMessage.h"
#include "Exception.h"
#include "BtRegistry.h"
#include "BtRuntime.h"
#include "FileEntry.h"
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -22,29 +24,27 @@ class DefaultExtensionMessageFactoryTest:public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE_END();
private:
SharedHandle<MockBtContext> _btContext;
SharedHandle<MockPeerStorage> _peerStorage;
SharedHandle<Peer> _peer;
SharedHandle<DefaultExtensionMessageFactory> _factory;
public:
void setUp()
{
BtRegistry::unregisterAll();
SharedHandle<MockBtContext> btContext(new MockBtContext());
_btContext.reset(new MockBtContext());
unsigned char infohash[20];
memset(infohash, 0, sizeof(infohash));
btContext->setInfoHash(infohash);
_btContext = btContext;
_btContext->setInfoHash(infohash);
SharedHandle<BtRuntime> btRuntime(new BtRuntime());
BtRegistry::registerBtRuntime(_btContext->getInfoHashAsString(),
btRuntime);
_peerStorage.reset(new MockPeerStorage());
_peer.reset(new Peer("192.168.0.1", 6969));
_peer->allocateSessionResource(1024, 1024*1024);
_peer->setExtension("ut_pex", 1);
}
void tearDown()
{
BtRegistry::unregisterAll();
_factory.reset(new DefaultExtensionMessageFactory());
_factory->setBtContext(_btContext);
_factory->setPeerStorage(_peerStorage);
_factory->setPeer(_peer);
}
void testCreateMessage_unknown();
@ -57,9 +57,6 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DefaultExtensionMessageFactoryTest);
void DefaultExtensionMessageFactoryTest::testCreateMessage_unknown()
{
DefaultExtensionMessageFactory factory;
factory.setBtContext(_btContext);
factory.setPeer(_peer);
_peer->setExtension("foo", 255);
char id[1] = { 255 };
@ -67,8 +64,8 @@ void DefaultExtensionMessageFactoryTest::testCreateMessage_unknown()
std::string data = std::string(&id[0], &id[1]);
try {
// this test fails because localhost doesn't have extension id = 255.
factory.createMessage(reinterpret_cast<const unsigned char*>(data.c_str()),
data.size());
_factory->createMessage
(reinterpret_cast<const unsigned char*>(data.c_str()), data.size());
CPPUNIT_FAIL("exception must be thrown.");
} catch(Exception& e) {
std::cerr << e.stackTrace() << std::endl;
@ -77,26 +74,18 @@ void DefaultExtensionMessageFactoryTest::testCreateMessage_unknown()
void DefaultExtensionMessageFactoryTest::testCreateMessage_Handshake()
{
DefaultExtensionMessageFactory factory;
factory.setBtContext(_btContext);
factory.setPeer(_peer);
char id[1] = { 0 };
std::string data = std::string(&id[0], &id[1])+"d1:v5:aria2e";
SharedHandle<HandshakeExtensionMessage> m
(dynamic_pointer_cast<HandshakeExtensionMessage>
(factory.createMessage(reinterpret_cast<const unsigned char*>(data.c_str()),
data.size())));
(_factory->createMessage
(reinterpret_cast<const unsigned char*>(data.c_str()), data.size())));
CPPUNIT_ASSERT_EQUAL(std::string("aria2"), m->getClientVersion());
}
void DefaultExtensionMessageFactoryTest::testCreateMessage_UTPex()
{
DefaultExtensionMessageFactory factory;
factory.setBtContext(_btContext);
factory.setPeer(_peer);
unsigned char c1[6];
unsigned char c2[6];
unsigned char c3[6];
@ -106,7 +95,7 @@ void DefaultExtensionMessageFactoryTest::testCreateMessage_UTPex()
PeerMessageUtil::createcompact(c3, "192.168.0.2", 6882);
PeerMessageUtil::createcompact(c4, "10.1.1.3",10000);
char id[1] = { factory.getExtensionMessageID("ut_pex") };
char id[1] = { _factory->getExtensionMessageID("ut_pex") };
std::string data = std::string(&id[0], &id[1])+"d5:added12:"+
std::string(&c1[0], &c1[6])+std::string(&c2[0], &c2[6])+
@ -116,9 +105,9 @@ void DefaultExtensionMessageFactoryTest::testCreateMessage_UTPex()
SharedHandle<UTPexExtensionMessage> m
(dynamic_pointer_cast<UTPexExtensionMessage>
(factory.createMessage(reinterpret_cast<const unsigned char*>(data.c_str()),
data.size())));
CPPUNIT_ASSERT_EQUAL(factory.getExtensionMessageID("ut_pex"),
(_factory->createMessage
(reinterpret_cast<const unsigned char*>(data.c_str()), data.size())));
CPPUNIT_ASSERT_EQUAL(_factory->getExtensionMessageID("ut_pex"),
m->getExtensionMessageID());
}

View File

@ -1,13 +1,14 @@
#include "MSEHandshake.h"
#include <cppunit/extensions/HelperMacros.h>
#include "Exception.h"
#include "Util.h"
#include "prefs.h"
#include "Socket.h"
#include "Option.h"
#include "BtRegistry.h"
#include "MockBtContext.h"
#include "FileEntry.h"
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -29,14 +30,6 @@ public:
unsigned char infoHash[20];
memset(infoHash, 0, sizeof(infoHash));
_btctx->setInfoHash(infoHash);
BtRegistry::unregisterAll();
BtRegistry::registerBtContext(_btctx->getInfoHashAsString(), _btctx);
}
void tearDown()
{
BtRegistry::unregisterAll();
}
void testHandshake();
@ -78,7 +71,9 @@ void MSEHandshakeTest::doHandshake(const SharedHandle<MSEHandshake>& initiator,
initiator->sendInitiatorStep2();
while(!receiver->findReceiverHashMarker());
while(!receiver->receiveReceiverHashAndPadCLength());
std::deque<SharedHandle<BtContext> > btContexts;
btContexts.push_back(_btctx);
while(!receiver->receiveReceiverHashAndPadCLength(btContexts));
while(!receiver->receivePad());
while(!receiver->receiveReceiverIALength());
while(!receiver->receiveReceiverIA());

View File

@ -9,19 +9,22 @@ class MockDHTTaskFactory:public DHTTaskFactory {
public:
virtual ~MockDHTTaskFactory() {}
virtual SharedHandle<DHTTask> createPingTask(const SharedHandle<DHTNode>& remoteNode,
virtual SharedHandle<DHTTask>
createPingTask(const SharedHandle<DHTNode>& remoteNode,
size_t numRetry = 0)
{
return SharedHandle<DHTTask>();
}
virtual SharedHandle<DHTTask> createGetIDTask(const SharedHandle<DHTNode>& remoteNode,
virtual SharedHandle<DHTTask>
createGetIDTask(const SharedHandle<DHTNode>& remoteNode,
size_t numRetry = 0)
{
return SharedHandle<DHTTask>();
}
virtual SharedHandle<DHTTask> createNodeLookupTask(const unsigned char* targetID)
virtual SharedHandle<DHTTask>
createNodeLookupTask(const unsigned char* targetID)
{
return SharedHandle<DHTTask>();
}
@ -31,17 +34,22 @@ public:
return SharedHandle<DHTTask>();
}
virtual SharedHandle<DHTTask> createPeerLookupTask(const SharedHandle<BtContext>& ctx)
virtual SharedHandle<DHTTask>
createPeerLookupTask(const SharedHandle<BtContext>& ctx,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<PeerStorage>& peerStorage)
{
return SharedHandle<DHTTask>();
}
virtual SharedHandle<DHTTask> createPeerAnnounceTask(const unsigned char* infoHash)
virtual SharedHandle<DHTTask>
createPeerAnnounceTask(const unsigned char* infoHash)
{
return SharedHandle<DHTTask>();
}
virtual SharedHandle<DHTTask> createReplaceNodeTask(const SharedHandle<DHTBucket>& bucket,
virtual SharedHandle<DHTTask>
createReplaceNodeTask(const SharedHandle<DHTBucket>& bucket,
const SharedHandle<DHTNode>& newNode)
{
return SharedHandle<DHTTask>();

View File

@ -1,9 +1,11 @@
#include "ShareRatioSeedCriteria.h"
#include <cppunit/extensions/HelperMacros.h>
#include "MockBtContext.h"
#include "MockPeerStorage.h"
#include "MockPieceStorage.h"
#include "FileEntry.h"
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -22,36 +24,35 @@ CPPUNIT_TEST_SUITE_REGISTRATION(ShareRatioSeedCriteriaTest);
void ShareRatioSeedCriteriaTest::testEvaluate() {
std::string infoHash = "01234567890123456789";
std::string infoHashString = Util::toHex((const unsigned char*)infoHash.c_str(), infoHash.size());
MockBtContext* mockBtContext = new MockBtContext();
mockBtContext->setTotalLength(1000000);
mockBtContext->setInfoHash((const unsigned char*)infoHash.c_str());
SharedHandle<BtContext> btContext(mockBtContext);
std::string infoHashString =
Util::toHex((const unsigned char*)infoHash.c_str(), infoHash.size());
SharedHandle<MockBtContext> btContext(new MockBtContext());
btContext->setTotalLength(1000000);
btContext->setInfoHash((const unsigned char*)infoHash.c_str());
SharedHandle<BtRuntime> btRuntime(new BtRuntime());
btRuntime->setUploadLengthAtStartup(500000);
BtRegistry::registerBtRuntime(infoHashString, btRuntime);
MockPeerStorage* mockPeerStorage = new MockPeerStorage();
SharedHandle<MockPeerStorage> peerStorage(new MockPeerStorage());
TransferStat stat;
stat.setSessionDownloadLength(1000000);
stat.setSessionUploadLength(500000);
mockPeerStorage->setStat(stat);
SharedHandle<PeerStorage> peerStorage(mockPeerStorage);
BtRegistry::registerPeerStorage(infoHashString, peerStorage);
peerStorage->setStat(stat);
MockPieceStorage* mockPieceStorage = new MockPieceStorage();
mockPieceStorage->setCompletedLength(1000000);
BtRegistry::registerPieceStorage(infoHashString,
SharedHandle<PieceStorage>(mockPieceStorage));
SharedHandle<MockPieceStorage> pieceStorage(new MockPieceStorage());
pieceStorage->setCompletedLength(1000000);
ShareRatioSeedCriteria cri(1.0, btContext);
cri.setPeerStorage(peerStorage);
cri.setPieceStorage(pieceStorage);
cri.setBtRuntime(btRuntime);
CPPUNIT_ASSERT(cri.evaluate());
cri.setRatio(2.0);
CPPUNIT_ASSERT(!cri.evaluate());
// check div by zero
mockBtContext->setTotalLength(0);
btContext->setTotalLength(0);
CPPUNIT_ASSERT(!cri.evaluate());
}

View File

@ -1,15 +1,16 @@
#include "UTPexExtensionMessage.h"
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include "Peer.h"
#include "a2netcompat.h"
#include "Util.h"
#include "PeerMessageUtil.h"
#include "BtRegistry.h"
#include "MockBtContext.h"
#include "MockPeerStorage.h"
#include "Exception.h"
#include "FileEntry.h"
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
namespace aria2 {
@ -28,24 +29,11 @@ class UTPexExtensionMessageTest:public CppUnit::TestFixture {
CPPUNIT_TEST(testDroppedPeersAreFull);
CPPUNIT_TEST_SUITE_END();
private:
SharedHandle<MockBtContext> _btContext;
SharedHandle<MockPeerStorage> _peerStorage;
public:
void setUp()
{
BtRegistry::unregisterAll();
SharedHandle<MockBtContext> btContext(new MockBtContext());
unsigned char infohash[20];
memset(infohash, 0, sizeof(infohash));
btContext->setInfoHash(infohash);
_btContext = btContext;
SharedHandle<MockPeerStorage> peerStorage(new MockPeerStorage());
BtRegistry::registerPeerStorage(_btContext->getInfoHashAsString(),
peerStorage);
}
void tearDown()
{
BtRegistry::unregisterAll();
_peerStorage.reset(new MockPeerStorage());
}
void testGetExtensionMessageID();
@ -143,18 +131,18 @@ void UTPexExtensionMessageTest::testDoReceivedAction()
SharedHandle<Peer> p4(new Peer("10.1.1.3", 10000));
p4->startBadCondition();
msg.addDroppedPeer(p4);
msg.setBtContext(_btContext);
msg.setPeerStorage(_peerStorage);
msg.doReceivedAction();
CPPUNIT_ASSERT_EQUAL((size_t)2, PEER_STORAGE(_btContext)->getPeers().size());
CPPUNIT_ASSERT_EQUAL((size_t)2, _peerStorage->getPeers().size());
{
SharedHandle<Peer> p = PEER_STORAGE(_btContext)->getPeers()[0];
SharedHandle<Peer> p = _peerStorage->getPeers()[0];
CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), p->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)6881, p->port);
}
{
SharedHandle<Peer> p = PEER_STORAGE(_btContext)->getPeers()[1];
SharedHandle<Peer> p = _peerStorage->getPeers()[1];
CPPUNIT_ASSERT_EQUAL(std::string("10.1.1.2"), p->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)9999, p->port);
}
@ -162,9 +150,6 @@ void UTPexExtensionMessageTest::testDoReceivedAction()
void UTPexExtensionMessageTest::testCreate()
{
_btContext->setPieceLength(256*1024);
_btContext->setTotalLength(1024*1024);
unsigned char c1[6];
unsigned char c2[6];
unsigned char c3[6];
@ -183,26 +168,30 @@ void UTPexExtensionMessageTest::testCreate()
"e";
SharedHandle<UTPexExtensionMessage> msg =
UTPexExtensionMessage::create(_btContext,
reinterpret_cast<const unsigned char*>(data.c_str()),
data.size());
UTPexExtensionMessage::create
(reinterpret_cast<const unsigned char*>(data.c_str()), data.size());
CPPUNIT_ASSERT_EQUAL((uint8_t)1, msg->getExtensionMessageID());
CPPUNIT_ASSERT_EQUAL((size_t)2, msg->getFreshPeers().size());
CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), msg->getFreshPeers()[0]->ipaddr);
CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"),
msg->getFreshPeers()[0]->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)6881, msg->getFreshPeers()[0]->port);
CPPUNIT_ASSERT_EQUAL(std::string("10.1.1.2"), msg->getFreshPeers()[1]->ipaddr);
CPPUNIT_ASSERT_EQUAL(std::string("10.1.1.2"),
msg->getFreshPeers()[1]->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)9999, msg->getFreshPeers()[1]->port);
CPPUNIT_ASSERT_EQUAL((size_t)2, msg->getDroppedPeers().size());
CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.2"), msg->getDroppedPeers()[0]->ipaddr);
CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.2"),
msg->getDroppedPeers()[0]->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)6882, msg->getDroppedPeers()[0]->port);
CPPUNIT_ASSERT_EQUAL(std::string("10.1.1.3"), msg->getDroppedPeers()[1]->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)10000, msg->getDroppedPeers()[1]->port);
CPPUNIT_ASSERT_EQUAL(std::string("10.1.1.3"),
msg->getDroppedPeers()[1]->ipaddr);
CPPUNIT_ASSERT_EQUAL((uint16_t)10000,
msg->getDroppedPeers()[1]->port);
try {
// 0 length data
std::string in = "";
UTPexExtensionMessage::create(_btContext,
reinterpret_cast<const unsigned char*>(in.c_str()),
in.size());
UTPexExtensionMessage::create
(reinterpret_cast<const unsigned char*>(in.c_str()), in.size());
CPPUNIT_FAIL("exception must be thrown.");
} catch(Exception& e) {
std::cerr << e.stackTrace() << std::endl;