diff --git a/ChangeLog b/ChangeLog index 1d8d1fd3..cff39669 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,13 @@ +2008-04-20 Tatsuhiro Tsujikawa + + Rewritten SharedHandle. Now copy constructor taking raw pointer has + keyword explicit and SharedHandle's default constructor initializes + its internal obj to null, old implementation initializes it using + obj's default constructor. + To assign null, write SharedHandle x(...); x.reset(); + TODO: test/SharedHandleTest.cc needs more tests. + * src/SharedHandle.h + 2008-04-15 Tatsuhiro Tsujikawa Fixed type in man page. diff --git a/src/AbstractAuthResolver.cc b/src/AbstractAuthResolver.cc index 83c419cc..cdac7f9b 100644 --- a/src/AbstractAuthResolver.cc +++ b/src/AbstractAuthResolver.cc @@ -38,7 +38,6 @@ namespace aria2 { AbstractAuthResolver::AbstractAuthResolver(): - _userDefinedAuthConfig(0), _defaultAuthConfig(new AuthConfig()) {} AbstractAuthResolver::~AbstractAuthResolver() {} diff --git a/src/AbstractBtMessage.cc b/src/AbstractBtMessage.cc index 9f243345..bee248c7 100644 --- a/src/AbstractBtMessage.cc +++ b/src/AbstractBtMessage.cc @@ -48,10 +48,6 @@ AbstractBtMessage::AbstractBtMessage():sendingInProgress(false), invalidate(false), uploading(false), cuid(0), - btContext(0), - pieceStorage(0), - peer(0), - validator(0), logger(LogFactory::getInstance()) {} diff --git a/src/AbstractCommand.cc b/src/AbstractCommand.cc index 8399d2af..7482c6a8 100644 --- a/src/AbstractCommand.cc +++ b/src/AbstractCommand.cc @@ -97,7 +97,7 @@ bool AbstractCommand::execute() { //logger->debug("CUID#%d - finished.", cuid); return true; } - PeerStatHandle peerStat = 0; + PeerStatHandle peerStat; if(!_requestGroup->getSegmentMan().isNull()) { peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid); } @@ -316,8 +316,7 @@ bool AbstractCommand::nameResolveFinished() const { void AbstractCommand::prepareForNextAction(Command* nextCommand) { - CheckIntegrityEntryHandle entry = - new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand); + CheckIntegrityEntryHandle entry(new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand)); e->addCommand(_requestGroup->processCheckIntegrityEntry(entry, e)); } diff --git a/src/AbstractProxyRequestCommand.cc b/src/AbstractProxyRequestCommand.cc index a686d250..fcb03077 100644 --- a/src/AbstractProxyRequestCommand.cc +++ b/src/AbstractProxyRequestCommand.cc @@ -50,7 +50,7 @@ AbstractProxyRequestCommand::AbstractProxyRequestCommand(int cuid, RequestGroup* requestGroup, DownloadEngine* e, const SocketHandle& s) - :AbstractCommand(cuid, req, requestGroup, e, s), httpConnection(0) { + :AbstractCommand(cuid, req, requestGroup, e, s) { disableReadCheckSocket(); setWriteCheckSocket(socket); } @@ -60,12 +60,12 @@ AbstractProxyRequestCommand::~AbstractProxyRequestCommand() {} bool AbstractProxyRequestCommand::executeInternal() { socket->setBlockingMode(); - HttpRequestHandle httpRequest = new HttpRequest(); + HttpRequestHandle httpRequest(new HttpRequest()); httpRequest->setUserAgent(e->option->get(PREF_USER_AGENT)); httpRequest->setRequest(req); httpRequest->configure(e->option); - httpConnection= new HttpConnection(cuid, socket, e->option); + httpConnection.reset(new HttpConnection(cuid, socket, e->option)); httpConnection->sendProxyRequest(httpRequest); diff --git a/src/AbstractSingleDiskAdaptor.cc b/src/AbstractSingleDiskAdaptor.cc index 0b21eac0..81fcdf4c 100644 --- a/src/AbstractSingleDiskAdaptor.cc +++ b/src/AbstractSingleDiskAdaptor.cc @@ -39,9 +39,7 @@ namespace aria2 { -AbstractSingleDiskAdaptor::AbstractSingleDiskAdaptor(): - diskWriter(0), - totalLength(0) {} +AbstractSingleDiskAdaptor::AbstractSingleDiskAdaptor():totalLength(0) {} AbstractSingleDiskAdaptor::~AbstractSingleDiskAdaptor() {} @@ -92,8 +90,8 @@ void AbstractSingleDiskAdaptor::truncate(uint64_t length) FileAllocationIteratorHandle AbstractSingleDiskAdaptor::fileAllocationIterator() { - SingleFileAllocationIteratorHandle h = - new SingleFileAllocationIterator(this, size(), totalLength); + SingleFileAllocationIteratorHandle h + (new SingleFileAllocationIterator(this, size(), totalLength)); h->init(); return h; } diff --git a/src/AuthConfigFactory.cc b/src/AuthConfigFactory.cc index 255c627e..b41821f8 100644 --- a/src/AuthConfigFactory.cc +++ b/src/AuthConfigFactory.cc @@ -44,11 +44,12 @@ namespace aria2 { AuthConfigFactory::AuthConfigFactory(const Option* option): - _option(option), _netrc(0) {} + _option(option) {} AuthConfigFactory::~AuthConfigFactory() {} -AuthConfigHandle AuthConfigFactory::createAuthConfig(const RequestHandle& request) const +AuthConfigHandle +AuthConfigFactory::createAuthConfig(const RequestHandle& request) const { if(request->getProtocol() == "http" || request->getProtocol() == "https") { return createHttpAuthResolver()->resolveAuthConfig(request->getHost()); @@ -59,31 +60,33 @@ AuthConfigHandle AuthConfigFactory::createAuthConfig(const RequestHandle& reques return createFtpAuthResolver()->resolveAuthConfig(request->getHost()); } } else { - return new AuthConfig(); + return SharedHandle(new AuthConfig()); } } -AuthConfigHandle AuthConfigFactory::createAuthConfigForHttpProxy(const RequestHandle& request) const +AuthConfigHandle +AuthConfigFactory::createAuthConfigForHttpProxy(const RequestHandle& request) const { return createHttpProxyAuthResolver()->resolveAuthConfig(request->getHost()); } -AuthConfigHandle AuthConfigFactory::createAuthConfig(const std::string& user, const std::string& password) const +AuthConfigHandle +AuthConfigFactory::createAuthConfig(const std::string& user, const std::string& password) const { + SharedHandle ac; if(user.length() > 0) { - return new AuthConfig(user, password); - } else { - return 0; + ac.reset(new AuthConfig(user, password)); } + return ac; } AuthResolverHandle AuthConfigFactory::createHttpAuthResolver() const { - AbstractAuthResolverHandle resolver = 0; + AbstractAuthResolverHandle resolver; if(true || _option->getAsBool(PREF_NO_NETRC)) { - resolver = new DefaultAuthResolver(); + resolver.reset(new DefaultAuthResolver()); } else { - NetrcAuthResolverHandle authResolver = new NetrcAuthResolver(); + NetrcAuthResolverHandle authResolver(new NetrcAuthResolver()); authResolver->setNetrc(_netrc); resolver = authResolver; } @@ -93,26 +96,27 @@ AuthResolverHandle AuthConfigFactory::createHttpAuthResolver() const AuthResolverHandle AuthConfigFactory::createFtpAuthResolver() const { - AbstractAuthResolverHandle resolver = 0; + AbstractAuthResolverHandle resolver; if(_option->getAsBool(PREF_NO_NETRC)) { - resolver = new DefaultAuthResolver(); + resolver.reset(new DefaultAuthResolver()); } else { - NetrcAuthResolverHandle authResolver = new NetrcAuthResolver(); + NetrcAuthResolverHandle authResolver(new NetrcAuthResolver()); authResolver->setNetrc(_netrc); resolver = authResolver; } resolver->setUserDefinedAuthConfig(createAuthConfig(_option->get(PREF_FTP_USER), _option->get(PREF_FTP_PASSWD))); - resolver->setDefaultAuthConfig(new AuthConfig("anonymous", "ARIA2USER@")); + SharedHandle defaultAuthConfig(new AuthConfig("anonymous", "ARIA2USER@")); + resolver->setDefaultAuthConfig(defaultAuthConfig); return resolver; } AuthResolverHandle AuthConfigFactory::createHttpProxyAuthResolver() const { - AbstractAuthResolverHandle resolver = 0; + AbstractAuthResolverHandle resolver; if(true || _option->getAsBool(PREF_NO_NETRC)) { - resolver = new DefaultAuthResolver(); + resolver.reset(new DefaultAuthResolver()); } else { - NetrcAuthResolverHandle authResolver = new NetrcAuthResolver(); + NetrcAuthResolverHandle authResolver(new NetrcAuthResolver()); authResolver->setNetrc(_netrc); resolver = authResolver; } diff --git a/src/BNode.cc b/src/BNode.cc index e8275ab5..ef8db8d3 100644 --- a/src/BNode.cc +++ b/src/BNode.cc @@ -129,7 +129,7 @@ SharedHandle BNode::findBucketFor(BNode* b, const unsigned char* key) if(bnode) { return bnode->getBucket(); } else { - return 0; + return SharedHandle(); } } diff --git a/src/BNode.h b/src/BNode.h index 5b75ee78..37d00dea 100644 --- a/src/BNode.h +++ b/src/BNode.h @@ -55,7 +55,7 @@ private: BNode* _right; public: - BNode(const SharedHandle& bucket = 0); + BNode(const SharedHandle& bucket = SharedHandle()); ~BNode(); diff --git a/src/BitfieldMan.cc b/src/BitfieldMan.cc index cb364643..42cc871e 100644 --- a/src/BitfieldMan.cc +++ b/src/BitfieldMan.cc @@ -49,7 +49,6 @@ BitfieldMan::BitfieldMan(size_t blockLength, uint64_t totalLength) bitfieldLength(0), blocks(0), filterEnabled(false), - randomizer(0), cachedNumMissingBlock(0), cachedNumFilteredBlock(0), cachedCompletedLength(0), @@ -76,7 +75,6 @@ BitfieldMan::BitfieldMan(const BitfieldMan& bitfieldMan) bitfieldLength(0), blocks(0), filterEnabled(false), - randomizer(0), cachedNumMissingBlock(0), cachedNumFilteredBlock(0), cachedCompletedLength(0), diff --git a/src/BitfieldManFactory.cc b/src/BitfieldManFactory.cc index 74f990c4..a0446e50 100644 --- a/src/BitfieldManFactory.cc +++ b/src/BitfieldManFactory.cc @@ -38,17 +38,17 @@ namespace aria2 { -BitfieldManFactoryHandle BitfieldManFactory::factory = 0; +BitfieldManFactoryHandle BitfieldManFactory::factory; BitfieldManFactoryHandle BitfieldManFactory::getFactoryInstance() { if(factory.isNull()) { - factory = new BitfieldManFactory(); + factory.reset(new BitfieldManFactory()); } return factory; } -BitfieldManFactory::BitfieldManFactory():randomizer(0) {} +BitfieldManFactory::BitfieldManFactory() {} BitfieldManFactory::~BitfieldManFactory() {} diff --git a/src/BtAllowedFastMessage.cc b/src/BtAllowedFastMessage.cc index dbceb8a7..78819807 100644 --- a/src/BtAllowedFastMessage.cc +++ b/src/BtAllowedFastMessage.cc @@ -49,7 +49,7 @@ BtAllowedFastMessageHandle BtAllowedFastMessage::create(const unsigned char* dat if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "allowed fast", ID); } - BtAllowedFastMessageHandle message = new BtAllowedFastMessage(); + BtAllowedFastMessageHandle message(new BtAllowedFastMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); return message; } diff --git a/src/BtBitfieldMessage.cc b/src/BtBitfieldMessage.cc index b98c4781..9c8466e0 100644 --- a/src/BtBitfieldMessage.cc +++ b/src/BtBitfieldMessage.cc @@ -63,7 +63,7 @@ BtBitfieldMessage::create(const unsigned char* data, size_t dataLength) if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "bitfield", ID); } - BtBitfieldMessageHandle message = new BtBitfieldMessage(); + BtBitfieldMessageHandle message(new BtBitfieldMessage()); message->setBitfield((unsigned char*)data+1, dataLength-1); return message; } diff --git a/src/BtCancelMessage.cc b/src/BtCancelMessage.cc index 83540e04..144cd089 100644 --- a/src/BtCancelMessage.cc +++ b/src/BtCancelMessage.cc @@ -49,7 +49,7 @@ BtCancelMessageHandle BtCancelMessage::create(const unsigned char* data, size_t if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "cancel", ID); } - BtCancelMessageHandle message = new BtCancelMessage(); + BtCancelMessageHandle message(new BtCancelMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); message->setBegin(PeerMessageUtil::getIntParam(data, 5)); message->setLength(PeerMessageUtil::getIntParam(data, 9)); diff --git a/src/BtCheckIntegrityEntry.cc b/src/BtCheckIntegrityEntry.cc index fcde4b8f..6de47243 100644 --- a/src/BtCheckIntegrityEntry.cc +++ b/src/BtCheckIntegrityEntry.cc @@ -50,7 +50,7 @@ BtCheckIntegrityEntry::~BtCheckIntegrityEntry() {} Commands BtCheckIntegrityEntry::onDownloadIncomplete(DownloadEngine* e) { Commands commands; - FileAllocationEntryHandle entry = new BtFileAllocationEntry(_requestGroup); + FileAllocationEntryHandle entry(new BtFileAllocationEntry(_requestGroup)); if(_requestGroup->needsFileAllocation()) { e->_fileAllocationMan->pushFileAllocationEntry(entry); } else { diff --git a/src/BtChokeMessage.cc b/src/BtChokeMessage.cc index 24326787..9c328e6c 100644 --- a/src/BtChokeMessage.cc +++ b/src/BtChokeMessage.cc @@ -50,7 +50,7 @@ BtChokeMessageHandle BtChokeMessage::create(const unsigned char* data, size_t da if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "choke", ID); } - BtChokeMessageHandle chokeMessage = new BtChokeMessage(); + BtChokeMessageHandle chokeMessage(new BtChokeMessage()); return chokeMessage; } diff --git a/src/BtDependency.cc b/src/BtDependency.cc index 8b7d1a93..40c95867 100644 --- a/src/BtDependency.cc +++ b/src/BtDependency.cc @@ -63,8 +63,8 @@ bool BtDependency::resolve() if(_dependee->getNumCommand() == 0 && _dependee->downloadFinished()) { RequestGroupHandle dependee = _dependee; // cut reference here - _dependee = 0; - DefaultBtContextHandle btContext = new DefaultBtContext(); + _dependee.reset(); + DefaultBtContextHandle btContext(new DefaultBtContext()); try { DiskAdaptorHandle diskAdaptor = dependee->getPieceStorage()->getDiskAdaptor(); diskAdaptor->openExistingFile(); @@ -89,7 +89,7 @@ bool BtDependency::resolve() } else if(_dependee->getNumCommand() == 0) { // _dependee's download failed. // cut reference here - _dependee = 0; + _dependee.reset(); _logger->debug("BtDependency for GID#%d failed. Go without Bt.", _dependant->getGID()); return true; diff --git a/src/BtExtendedMessage.cc b/src/BtExtendedMessage.cc index cef424fc..361503e6 100644 --- a/src/BtExtendedMessage.cc +++ b/src/BtExtendedMessage.cc @@ -111,7 +111,7 @@ BtExtendedMessage::create(const BtContextHandle& btContext, assert(!factory.isNull()); ExtensionMessageHandle extmsg = factory->createMessage(data+1, dataLength-1); - BtExtendedMessageHandle message = new BtExtendedMessage(extmsg); + BtExtendedMessageHandle message(new BtExtendedMessage(extmsg)); return message; } diff --git a/src/BtExtendedMessage.h b/src/BtExtendedMessage.h index b39db283..a2b9cc8a 100644 --- a/src/BtExtendedMessage.h +++ b/src/BtExtendedMessage.h @@ -52,7 +52,8 @@ private: size_t _msgLength; public: - BtExtendedMessage(const SharedHandle& extensionMessage = 0); + BtExtendedMessage(const SharedHandle& extensionMessage = + SharedHandle()); virtual ~BtExtendedMessage(); diff --git a/src/BtHandshakeMessage.cc b/src/BtHandshakeMessage.cc index 3250e432..22b384a7 100644 --- a/src/BtHandshakeMessage.cc +++ b/src/BtHandshakeMessage.cc @@ -72,7 +72,7 @@ void BtHandshakeMessage::init() { SharedHandle BtHandshakeMessage::create(const unsigned char* data, size_t dataLength) { - SharedHandle message = new BtHandshakeMessage(); + SharedHandle message(new BtHandshakeMessage()); message->pstrlen = data[0]; memcpy(message->pstr, &data[1], PSTR_LENGTH); memcpy(message->reserved, &data[20], RESERVED_LENGTH); diff --git a/src/BtHaveAllMessage.cc b/src/BtHaveAllMessage.cc index 08dd3327..ba82fd1a 100644 --- a/src/BtHaveAllMessage.cc +++ b/src/BtHaveAllMessage.cc @@ -48,7 +48,7 @@ BtHaveAllMessageHandle BtHaveAllMessage::create(const unsigned char* data, size_ if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have all", ID); } - BtHaveAllMessageHandle message = new BtHaveAllMessage(); + BtHaveAllMessageHandle message(new BtHaveAllMessage()); return message; } diff --git a/src/BtHaveMessage.cc b/src/BtHaveMessage.cc index 3720f4dc..6ea78e5f 100644 --- a/src/BtHaveMessage.cc +++ b/src/BtHaveMessage.cc @@ -49,7 +49,7 @@ BtHaveMessageHandle BtHaveMessage::create(const unsigned char* data, size_t data if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have", ID); } - BtHaveMessageHandle message = new BtHaveMessage(); + BtHaveMessageHandle message(new BtHaveMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); return message; } diff --git a/src/BtHaveNoneMessage.cc b/src/BtHaveNoneMessage.cc index 4404e2fb..3220ba4a 100644 --- a/src/BtHaveNoneMessage.cc +++ b/src/BtHaveNoneMessage.cc @@ -48,7 +48,7 @@ BtHaveNoneMessageHandle BtHaveNoneMessage::create(const unsigned char* data, siz if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have none", ID); } - BtHaveNoneMessageHandle message = new BtHaveNoneMessage(); + BtHaveNoneMessageHandle message(new BtHaveNoneMessage()); return message; } diff --git a/src/BtInterestedMessage.cc b/src/BtInterestedMessage.cc index da4f21ef..46523abe 100644 --- a/src/BtInterestedMessage.cc +++ b/src/BtInterestedMessage.cc @@ -51,7 +51,7 @@ BtInterestedMessageHandle BtInterestedMessage::create(const unsigned char* data, if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "interested", ID); } - BtInterestedMessageHandle message = new BtInterestedMessage(); + BtInterestedMessageHandle message(new BtInterestedMessage()); return message; } diff --git a/src/BtMessageFactory.h b/src/BtMessageFactory.h index cd4715c2..c89ee279 100644 --- a/src/BtMessageFactory.h +++ b/src/BtMessageFactory.h @@ -41,6 +41,7 @@ namespace aria2 { class BtMessage; +class BtHandshakeMessage; class Piece; class ExtensionMessage; @@ -51,10 +52,10 @@ public: virtual SharedHandle createBtMessage(const unsigned char* msg, size_t msgLength) = 0; - virtual SharedHandle + virtual SharedHandle createHandshakeMessage(const unsigned char* msg, size_t msgLength) = 0; - virtual SharedHandle + virtual SharedHandle createHandshakeMessage(const unsigned char* infoHash, const unsigned char* peerId) = 0; diff --git a/src/BtMessageReceiver.h b/src/BtMessageReceiver.h index f4c6d6ca..c77c37c5 100644 --- a/src/BtMessageReceiver.h +++ b/src/BtMessageReceiver.h @@ -41,14 +41,15 @@ namespace aria2 { class BtMessage; +class BtHandshakeMessage; class BtMessageReceiver { public: virtual ~BtMessageReceiver() {} - virtual SharedHandle receiveHandshake(bool quickReply = false) = 0; + virtual SharedHandle receiveHandshake(bool quickReply = false) = 0; - virtual SharedHandle receiveAndSendHandshake() = 0; + virtual SharedHandle receiveAndSendHandshake() = 0; virtual SharedHandle receiveMessage() = 0; }; diff --git a/src/BtNotInterestedMessage.cc b/src/BtNotInterestedMessage.cc index c72556d4..32ec0da9 100644 --- a/src/BtNotInterestedMessage.cc +++ b/src/BtNotInterestedMessage.cc @@ -51,7 +51,7 @@ BtNotInterestedMessageHandle BtNotInterestedMessage::create(const unsigned char* if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "not interested", ID); } - BtNotInterestedMessageHandle message = new BtNotInterestedMessage(); + BtNotInterestedMessageHandle message(new BtNotInterestedMessage()); return message; } diff --git a/src/BtPieceMessage.cc b/src/BtPieceMessage.cc index 172ab340..a5de003f 100644 --- a/src/BtPieceMessage.cc +++ b/src/BtPieceMessage.cc @@ -69,7 +69,7 @@ BtPieceMessageHandle BtPieceMessage::create(const unsigned char* data, size_t da if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID); } - BtPieceMessageHandle message = new BtPieceMessage(); + BtPieceMessageHandle message(new BtPieceMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); message->setBegin(PeerMessageUtil::getIntParam(data, 5)); message->setBlock(data+9, dataLength-9); diff --git a/src/BtPieceMessage.h b/src/BtPieceMessage.h index 9c377e29..780e78a6 100644 --- a/src/BtPieceMessage.h +++ b/src/BtPieceMessage.h @@ -104,8 +104,14 @@ public: msgHeader(0) { uploading = true; - addEventListener(new BtChokingEventListener(this)); - addEventListener(new BtCancelSendingPieceEventListener(this)); + { + SharedHandle listener(new BtChokingEventListener(this)); + addEventListener(listener); + } + { + SharedHandle listener(new BtCancelSendingPieceEventListener(this)); + addEventListener(listener); + } } virtual ~BtPieceMessage() { diff --git a/src/BtPortMessage.cc b/src/BtPortMessage.cc index c9ef72dc..4414e241 100644 --- a/src/BtPortMessage.cc +++ b/src/BtPortMessage.cc @@ -64,7 +64,7 @@ SharedHandle BtPortMessage::create(const unsigned char* data, siz throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID); } uint16_t port = PeerMessageUtil::getShortIntParam(data, 1); - SharedHandle message = new BtPortMessage(port); + SharedHandle message(new BtPortMessage(port)); return message; } @@ -73,7 +73,7 @@ void BtPortMessage::doReceivedAction() if(!_taskFactory.isNull() && !_taskQueue.isNull()) { // node id is random at this point. When ping reply received, new DHTNode // instance created with proper node ID and is added to a routing table. - SharedHandle node = new DHTNode(); + SharedHandle node(new DHTNode()); node->setIPAddress(peer->ipaddr); node->setPort(_port); { diff --git a/src/BtPostDownloadHandler.cc b/src/BtPostDownloadHandler.cc index 4ea179ce..8253224e 100644 --- a/src/BtPostDownloadHandler.cc +++ b/src/BtPostDownloadHandler.cc @@ -50,8 +50,10 @@ namespace aria2 { BtPostDownloadHandler::BtPostDownloadHandler() { - setCriteria(new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getBtContentTypes(), - DownloadHandlerConstants::getBtExtensions())); + SharedHandle cri + (new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getBtContentTypes(), + DownloadHandlerConstants::getBtExtensions())); + setCriteria(cri); } BtPostDownloadHandler::~BtPostDownloadHandler() {} @@ -61,7 +63,7 @@ RequestGroups BtPostDownloadHandler::getNextRequestGroups(RequestGroup* requestG const Option* op = requestGroup->getOption(); _logger->debug("Generating RequestGroups for Torrent file %s", requestGroup->getFilePath().c_str()); - RequestGroupHandle rg = new RequestGroup(op, std::deque()); + RequestGroupHandle rg(new RequestGroup(op, std::deque())); std::string content; try { @@ -72,7 +74,7 @@ RequestGroups BtPostDownloadHandler::getNextRequestGroups(RequestGroup* requestG requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile(); throw; } - DefaultBtContextHandle btContext = new DefaultBtContext(); + DefaultBtContextHandle btContext(new DefaultBtContext()); btContext->loadFromMemory(content, File(requestGroup->getFilePath()).getBasename()); if(op->defined(PREF_PEER_ID_PREFIX)) { btContext->setPeerIdPrefix(op->get(PREF_PEER_ID_PREFIX)); diff --git a/src/BtRejectMessage.cc b/src/BtRejectMessage.cc index e69d3c73..feb430e0 100644 --- a/src/BtRejectMessage.cc +++ b/src/BtRejectMessage.cc @@ -51,7 +51,7 @@ BtRejectMessageHandle BtRejectMessage::create(const unsigned char* data, size_t if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "reject", ID); } - BtRejectMessageHandle message = new BtRejectMessage(); + BtRejectMessageHandle message(new BtRejectMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); message->setBegin(PeerMessageUtil::getIntParam(data, 5)); message->setLength(PeerMessageUtil::getIntParam(data, 9)); diff --git a/src/BtRequestMessage.cc b/src/BtRequestMessage.cc index 1b014d10..5b9a9bfe 100644 --- a/src/BtRequestMessage.cc +++ b/src/BtRequestMessage.cc @@ -55,7 +55,7 @@ BtRequestMessageHandle BtRequestMessage::create(const unsigned char* data, size_ if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "request", ID); } - BtRequestMessageHandle message = new BtRequestMessage(); + BtRequestMessageHandle message(new BtRequestMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); message->setBegin(PeerMessageUtil::getIntParam(data, 5)); message->setLength(PeerMessageUtil::getIntParam(data, 9)); diff --git a/src/BtRequestMessage.h b/src/BtRequestMessage.h index 80c20489..5c762b8b 100644 --- a/src/BtRequestMessage.h +++ b/src/BtRequestMessage.h @@ -77,7 +77,8 @@ public: blockIndex(blockIndex), msg(0) { - addEventListener(new BtAbortOutstandingRequestEventListener(this)); + SharedHandle listener(new BtAbortOutstandingRequestEventListener(this)); + addEventListener(listener); } virtual ~BtRequestMessage() { diff --git a/src/BtSetup.cc b/src/BtSetup.cc index f0f4866d..f4c97562 100644 --- a/src/BtSetup.cc +++ b/src/BtSetup.cc @@ -66,7 +66,7 @@ Commands BtSetup::setup(RequestGroup* requestGroup, const Option* option) { Commands commands; - BtContextHandle btContext = requestGroup->getDownloadContext(); + BtContextHandle btContext(dynamic_pointer_cast(requestGroup->getDownloadContext())); if(btContext.isNull()) { return commands; } @@ -92,14 +92,16 @@ Commands BtSetup::setup(RequestGroup* requestGroup, command->setTaskFactory(DHTRegistry::_taskFactory); commands.push_back(command); } - SharedHandle unionCri = new UnionSeedCriteria(); + SharedHandle unionCri(new UnionSeedCriteria()); if(option->defined(PREF_SEED_TIME)) { - unionCri->addSeedCriteria(new TimeSeedCriteria(option->getAsInt(PREF_SEED_TIME)*60)); + SharedHandle cri(new TimeSeedCriteria(option->getAsInt(PREF_SEED_TIME)*60)); + unionCri->addSeedCriteria(cri); } { double ratio = option->getAsDouble(PREF_SEED_RATIO); if(ratio > 0.0) { - unionCri->addSeedCriteria(new ShareRatioSeedCriteria(option->getAsDouble(PREF_SEED_RATIO), btContext)); + SharedHandle cri(new ShareRatioSeedCriteria(option->getAsDouble(PREF_SEED_RATIO), btContext)); + unionCri->addSeedCriteria(cri); } } if(unionCri->getSeedCriterion().size() > 0) { diff --git a/src/BtSuggestPieceMessage.cc b/src/BtSuggestPieceMessage.cc index 34762d4b..38aee573 100644 --- a/src/BtSuggestPieceMessage.cc +++ b/src/BtSuggestPieceMessage.cc @@ -48,7 +48,7 @@ BtSuggestPieceMessageHandle BtSuggestPieceMessage::create(const unsigned char* d if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "suggest piece", ID); } - BtSuggestPieceMessageHandle message = new BtSuggestPieceMessage(); + BtSuggestPieceMessageHandle message(new BtSuggestPieceMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); return message; } diff --git a/src/BtUnchokeMessage.cc b/src/BtUnchokeMessage.cc index 8b1b2b93..00c3d437 100644 --- a/src/BtUnchokeMessage.cc +++ b/src/BtUnchokeMessage.cc @@ -48,7 +48,7 @@ BtUnchokeMessageHandle BtUnchokeMessage::create(const unsigned char* data, size_ if(id != ID) { throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "unchoke", ID); } - BtUnchokeMessageHandle message = new BtUnchokeMessage(); + BtUnchokeMessageHandle message(new BtUnchokeMessage()); return message; } diff --git a/src/ByteArrayDiskWriterFactory.cc b/src/ByteArrayDiskWriterFactory.cc index 7de81707..d2eb9de0 100644 --- a/src/ByteArrayDiskWriterFactory.cc +++ b/src/ByteArrayDiskWriterFactory.cc @@ -39,7 +39,7 @@ namespace aria2 { DiskWriterHandle ByteArrayDiskWriterFactory::newDiskWriter() { - return new ByteArrayDiskWriter(); + return SharedHandle(new ByteArrayDiskWriter()); } } // namespace aria2 diff --git a/src/CheckIntegrityEntry.cc b/src/CheckIntegrityEntry.cc index 3951a6c8..e961d9b7 100644 --- a/src/CheckIntegrityEntry.cc +++ b/src/CheckIntegrityEntry.cc @@ -39,8 +39,7 @@ namespace aria2 { CheckIntegrityEntry::CheckIntegrityEntry(RequestGroup* requestGroup, Command* nextCommand): - RequestGroupEntry(requestGroup, nextCommand), - _validator(0) + RequestGroupEntry(requestGroup, nextCommand) {} CheckIntegrityEntry::~CheckIntegrityEntry() {} diff --git a/src/CheckIntegrityMan.cc b/src/CheckIntegrityMan.cc index 3a5f8a1f..156f4bb6 100644 --- a/src/CheckIntegrityMan.cc +++ b/src/CheckIntegrityMan.cc @@ -62,7 +62,7 @@ bool CheckIntegrityMan::removeCheckIntegrityEntry(const CheckIntegrityEntryHandl CheckIntegrityEntryHandle CheckIntegrityMan::getFirstCheckIntegrityEntry() const { if(_checkIntegrityEntries.empty()) { - return 0; + return SharedHandle(); } else { return _checkIntegrityEntries.front(); } diff --git a/src/ChecksumCheckIntegrityEntry.cc b/src/ChecksumCheckIntegrityEntry.cc index 6c4ccd33..0231bcf3 100644 --- a/src/ChecksumCheckIntegrityEntry.cc +++ b/src/ChecksumCheckIntegrityEntry.cc @@ -49,15 +49,18 @@ ChecksumCheckIntegrityEntry::~ChecksumCheckIntegrityEntry() {} bool ChecksumCheckIntegrityEntry::isValidationReady() { - SingleFileDownloadContextHandle dctx = _requestGroup->getDownloadContext(); + SingleFileDownloadContextHandle dctx + (dynamic_pointer_cast(_requestGroup->getDownloadContext())); return !dctx.isNull() && dctx->getChecksum().size() > 0 && dctx->getChecksumHashAlgo().size() > 0; } void ChecksumCheckIntegrityEntry::initValidator() { - _validator = new IteratableChecksumValidator(_requestGroup->getDownloadContext(), - _requestGroup->getPieceStorage()); + SingleFileDownloadContextHandle dctx + (dynamic_pointer_cast(_requestGroup->getDownloadContext())); + _validator.reset(new IteratableChecksumValidator(dctx, + _requestGroup->getPieceStorage())); _validator->init(); } diff --git a/src/CompactPeerListProcessor.cc b/src/CompactPeerListProcessor.cc index b9e10c65..6fbc2015 100644 --- a/src/CompactPeerListProcessor.cc +++ b/src/CompactPeerListProcessor.cc @@ -58,7 +58,7 @@ Peers CompactPeerListProcessor::extractPeer(const MetaEntry* peersEntry) { in.s_addr = *(uint32_t*)(peersData->getData()+i); std::string ipaddr = inet_ntoa(in); uint16_t port = ntohs(*(uint16_t*)(peersData->getData()+i+4)); - PeerHandle peer = new Peer(ipaddr, port); + PeerHandle peer(new Peer(ipaddr, port)); peers.push_back(peer); } } diff --git a/src/ConsoleStatCalc.cc b/src/ConsoleStatCalc.cc index 51b0a7f3..08a7dc59 100644 --- a/src/ConsoleStatCalc.cc +++ b/src/ConsoleStatCalc.cc @@ -80,7 +80,7 @@ ConsoleStatCalc::calculateStat(const RequestGroupManHandle& requestGroupMan, << "#" << firstRequestGroup->getGID() << " "; #ifdef ENABLE_BITTORRENT if(firstRequestGroup->downloadFinished() && - !BtContextHandle(firstRequestGroup->getDownloadContext()).isNull()) { + !dynamic_pointer_cast(firstRequestGroup->getDownloadContext()).isNull()) { std::cout << "SEEDING" << "(" << "ratio:" << std::fixed << std::setprecision(1) << ((stat.getAllTimeUploadLength()*10)/firstRequestGroup->getCompletedLength())/10.0 diff --git a/src/ContentTypeRequestGroupCriteria.cc b/src/ContentTypeRequestGroupCriteria.cc index 9fa53d6b..cd06ab4b 100644 --- a/src/ContentTypeRequestGroupCriteria.cc +++ b/src/ContentTypeRequestGroupCriteria.cc @@ -52,7 +52,7 @@ bool ContentTypeRequestGroupCriteria::match(const RequestGroup* requestGroup) co if(forwardMatch(requestGroup->getFilePath(), _extensions)) { return true; } else { - SingleFileDownloadContextHandle dctx = requestGroup->getDownloadContext(); + SingleFileDownloadContextHandle dctx(dynamic_pointer_cast(requestGroup->getDownloadContext())); if(dctx.isNull()) { return false; } else { diff --git a/src/CookieBoxFactory.cc b/src/CookieBoxFactory.cc index d03051d4..ba610a95 100644 --- a/src/CookieBoxFactory.cc +++ b/src/CookieBoxFactory.cc @@ -43,7 +43,7 @@ namespace aria2 { CookieBoxHandle CookieBoxFactory::createNewInstance() { - CookieBoxHandle box = new CookieBox(); + CookieBoxHandle box(new CookieBox()); box->add(defaultCookies); return box; } diff --git a/src/DHTAbstractMessage.cc b/src/DHTAbstractMessage.cc index 61f3c5b9..85d1fe72 100644 --- a/src/DHTAbstractMessage.cc +++ b/src/DHTAbstractMessage.cc @@ -41,6 +41,7 @@ #include "DHTMessageDispatcher.h" #include "DHTMessageFactory.h" #include "DHTRoutingTable.h" +#include "DHTMessageCallback.h" namespace aria2 { @@ -53,7 +54,7 @@ DHTAbstractMessage::~DHTAbstractMessage() {} std::string DHTAbstractMessage::getBencodedMessage() { - SharedHandle msg = new Dictionary(); + SharedHandle msg(new Dictionary()); msg->put(std::string("t"), new Data(_transactionID)); msg->put(std::string("y"), new Data(getType())); fillMessage(msg.get()); diff --git a/src/DHTAbstractNodeLookupTask.cc b/src/DHTAbstractNodeLookupTask.cc index 598c68a4..8b372aca 100644 --- a/src/DHTAbstractNodeLookupTask.cc +++ b/src/DHTAbstractNodeLookupTask.cc @@ -118,7 +118,9 @@ void DHTAbstractNodeLookupTask::sendMessage() ++_inFlightMessage; (*i)->_used = true; SharedHandle m = createMessage((*i)->_node); - _dispatcher->addMessageToQueue(m, new DHTMessageCallbackImpl(this)); + WeakHandle listener(this); + SharedHandle callback(new DHTMessageCallbackImpl(listener)); + _dispatcher->addMessageToQueue(m, callback); } } } @@ -149,7 +151,7 @@ DHTAbstractNodeLookupTask::toEntries(const std::deque >& n { std::deque > entries; for(std::deque >::const_iterator i = nodes.begin(); i != nodes.end(); ++i) { - SharedHandle e = new DHTNodeLookupEntry(*i); + SharedHandle e(new DHTNodeLookupEntry(*i)); entries.push_back(e); } return entries; diff --git a/src/DHTAbstractTask.cc b/src/DHTAbstractTask.cc index 82866556..9e6c4f52 100644 --- a/src/DHTAbstractTask.cc +++ b/src/DHTAbstractTask.cc @@ -48,8 +48,7 @@ namespace aria2 { DHTAbstractTask::DHTAbstractTask(): _finished(false), - _logger(LogFactory::getInstance()), - _localNode(0) + _logger(LogFactory::getInstance()) {} bool DHTAbstractTask::finished() diff --git a/src/DHTAnnouncePeerMessage.cc b/src/DHTAnnouncePeerMessage.cc index 4c4dd5b2..794bd797 100644 --- a/src/DHTAnnouncePeerMessage.cc +++ b/src/DHTAnnouncePeerMessage.cc @@ -57,9 +57,7 @@ DHTAnnouncePeerMessage::DHTAnnouncePeerMessage(const SharedHandle& loca const std::string& transactionID): DHTQueryMessage(localNode, remoteNode, transactionID), _token(token), - _tcpPort(tcpPort), - _peerAnnounceStorage(0), - _tokenTracker(0) + _tcpPort(tcpPort) { memcpy(_infoHash, infoHash, DHT_ID_LENGTH); } diff --git a/src/DHTAutoSaveCommand.cc b/src/DHTAutoSaveCommand.cc index 90aaa390..30aca9f9 100644 --- a/src/DHTAutoSaveCommand.cc +++ b/src/DHTAutoSaveCommand.cc @@ -53,9 +53,7 @@ namespace aria2 { DHTAutoSaveCommand::DHTAutoSaveCommand(int32_t cuid, DownloadEngine* e, time_t interval): - TimeBasedCommand(cuid, e, interval), - _localNode(0), - _routingTable(0) {} + TimeBasedCommand(cuid, e, interval) {} DHTAutoSaveCommand::~DHTAutoSaveCommand() {} diff --git a/src/DHTBucket.cc b/src/DHTBucket.cc index 720f478d..f9aee519 100644 --- a/src/DHTBucket.cc +++ b/src/DHTBucket.cc @@ -132,7 +132,7 @@ void DHTBucket::cacheNode(const SharedHandle& node) // _cachedNodes are sorted by last time seen _cachedNodes.push_front(node); if(_cachedNodes.size() > CACHE_SIZE) { - _cachedNodes.resize(CACHE_SIZE, 0); + _cachedNodes.resize(CACHE_SIZE, SharedHandle()); } } @@ -182,8 +182,8 @@ SharedHandle DHTBucket::split() memcpy(rMax, _max, DHT_ID_LENGTH); DHTUtil::flipBit(rMax, DHT_ID_LENGTH, _prefixLength); - SharedHandle rBucket = new DHTBucket(newPrefixLength, - rMax, _min, _localNode); + SharedHandle rBucket(new DHTBucket(newPrefixLength, + rMax, _min, _localNode)); std::deque > tempNodes = _nodes; for(std::deque >::iterator i = tempNodes.begin(); i != tempNodes.end();) { @@ -228,13 +228,13 @@ std::deque > DHTBucket::getGoodNodes() const SharedHandle DHTBucket::getNode(const unsigned char* nodeID, const std::string& ipaddr, uint16_t port) const { - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); node->setIPAddress(ipaddr); node->setPort(port); std::deque >::const_iterator itr = std::find(_nodes.begin(), _nodes.end(), node); if(itr == _nodes.end()) { - return 0; + return SharedHandle(); } else { return *itr; } @@ -274,7 +274,7 @@ SharedHandle DHTBucket::getLRUQuestionableNode() const std::deque >::const_iterator i = std::find_if(_nodes.begin(), _nodes.end(), FindQuestionableNode()); if(i == _nodes.end()) { - return 0; + return SharedHandle(); } else { return *i; } diff --git a/src/DHTBucketRefreshCommand.cc b/src/DHTBucketRefreshCommand.cc index ba3da97c..30d62cdb 100644 --- a/src/DHTBucketRefreshCommand.cc +++ b/src/DHTBucketRefreshCommand.cc @@ -43,10 +43,7 @@ namespace aria2 { DHTBucketRefreshCommand::DHTBucketRefreshCommand(int32_t cuid, DownloadEngine* e, time_t interval): - TimeBasedCommand(cuid, e, interval), - _routingTable(0), - _taskQueue(0), - _taskFactory(0) {} + TimeBasedCommand(cuid, e, interval) {} DHTBucketRefreshCommand::~DHTBucketRefreshCommand() {} diff --git a/src/DHTBucketRefreshTask.cc b/src/DHTBucketRefreshTask.cc index 8c8d6cf0..add732c3 100644 --- a/src/DHTBucketRefreshTask.cc +++ b/src/DHTBucketRefreshTask.cc @@ -57,7 +57,7 @@ void DHTBucketRefreshTask::startup() (*i)->notifyUpdate(); unsigned char targetID[DHT_ID_LENGTH]; (*i)->getRandomNodeID(targetID); - SharedHandle task = new DHTNodeLookupTask(targetID); + SharedHandle task(new DHTNodeLookupTask(targetID)); task->setRoutingTable(_routingTable); task->setMessageDispatcher(_dispatcher); task->setMessageFactory(_factory); diff --git a/src/DHTEntryPointNameResolveCommand.cc b/src/DHTEntryPointNameResolveCommand.cc index 3ffe73cc..f5c52008 100644 --- a/src/DHTEntryPointNameResolveCommand.cc +++ b/src/DHTEntryPointNameResolveCommand.cc @@ -55,10 +55,6 @@ DHTEntryPointNameResolveCommand::DHTEntryPointNameResolveCommand(int32_t cuid, D Command(cuid), _e(e), _resolver(new NameResolver()), - _taskQueue(0), - _taskFactory(0), - _routingTable(0), - _localNode(0), _entryPoints(entryPoints), _bootstrapEnabled(false) {} @@ -120,7 +116,7 @@ bool DHTEntryPointNameResolveCommand::execute() void DHTEntryPointNameResolveCommand::addPingTask(const std::pair& addr) { - SharedHandle entryNode = new DHTNode(); + SharedHandle entryNode(new DHTNode()); entryNode->setIPAddress(addr.first); entryNode->setPort(addr.second); diff --git a/src/DHTGetPeersCommand.cc b/src/DHTGetPeersCommand.cc index 56938a34..4b223589 100644 --- a/src/DHTGetPeersCommand.cc +++ b/src/DHTGetPeersCommand.cc @@ -57,9 +57,6 @@ DHTGetPeersCommand::DHTGetPeersCommand(int32_t cuid, BtContextAwareCommand(ctx), RequestGroupAware(requestGroup), _e(e), - _taskQueue(0), - _taskFactory(0), - _task(0), _numRetry(0), _lastGetPeerTime(0) {} @@ -76,7 +73,7 @@ bool DHTGetPeersCommand::execute() _lastGetPeerTime.elapsed(GET_PEER_INTERVAL))) { logger->debug("Issuing PeerLookup for infoHash=%s", btContext->getInfoHashAsString().c_str()); - _task = _taskFactory->createPeerLookupTask(btContext); + _task = dynamic_pointer_cast(_taskFactory->createPeerLookupTask(btContext)); _taskQueue->addPeriodicTask2(_task); } else if(!_task.isNull() && _task->finished()) { _lastGetPeerTime.reset(); @@ -85,7 +82,7 @@ bool DHTGetPeersCommand::execute() } else { _numRetry = 0; } - _task = 0; + _task.reset(); } _e->commands.push_back(this); diff --git a/src/DHTGetPeersMessage.cc b/src/DHTGetPeersMessage.cc index a0bf1e23..52122f02 100644 --- a/src/DHTGetPeersMessage.cc +++ b/src/DHTGetPeersMessage.cc @@ -67,7 +67,7 @@ void DHTGetPeersMessage::doReceivedAction() _remoteNode->getPort()); // Check to see localhost has the contents which has same infohash Peers peers = _peerAnnounceStorage->getPeers(_infoHash); - SharedHandle reply = 0; + SharedHandle reply; if(peers.empty()) { std::deque > nodes = _routingTable->getClosestKNodes(_infoHash); reply = diff --git a/src/DHTInteractionCommand.cc b/src/DHTInteractionCommand.cc index 09d9174c..f758cbe5 100644 --- a/src/DHTInteractionCommand.cc +++ b/src/DHTInteractionCommand.cc @@ -43,17 +43,13 @@ #include "message.h" #include "RequestGroupMan.h" #include "Logger.h" +#include "DHTMessageCallback.h" namespace aria2 { DHTInteractionCommand::DHTInteractionCommand(int32_t cuid, DownloadEngine* e): Command(cuid), - _e(e), - _dispatcher(0), - _receiver(0), - _taskQueue(0), - _readCheckSocket(0) -{} + _e(e) {} DHTInteractionCommand::~DHTInteractionCommand() { diff --git a/src/DHTMessageDispatcher.h b/src/DHTMessageDispatcher.h index 1a6c4390..1ebb5da9 100644 --- a/src/DHTMessageDispatcher.h +++ b/src/DHTMessageDispatcher.h @@ -51,11 +51,13 @@ public: virtual void addMessageToQueue(const SharedHandle& message, time_t timeout, - const SharedHandle& callback = 0) = 0; + const SharedHandle& callback = + SharedHandle()) = 0; virtual void addMessageToQueue(const SharedHandle& message, - const SharedHandle& callback = 0) = 0; + const SharedHandle& callback = + SharedHandle()) = 0; virtual void sendMessages() = 0; diff --git a/src/DHTMessageDispatcherImpl.cc b/src/DHTMessageDispatcherImpl.cc index ae0ec37a..9d85c89b 100644 --- a/src/DHTMessageDispatcherImpl.cc +++ b/src/DHTMessageDispatcherImpl.cc @@ -55,7 +55,8 @@ DHTMessageDispatcherImpl::addMessageToQueue(const SharedHandle& mess time_t timeout, const SharedHandle& callback) { - _messageQueue.push_back(new DHTMessageEntry(message, timeout, callback)); + SharedHandle e(new DHTMessageEntry(message, timeout, callback)); + _messageQueue.push_back(e); } void diff --git a/src/DHTMessageDispatcherImpl.h b/src/DHTMessageDispatcherImpl.h index 96ce72be..9ef29398 100644 --- a/src/DHTMessageDispatcherImpl.h +++ b/src/DHTMessageDispatcherImpl.h @@ -61,11 +61,13 @@ public: virtual void addMessageToQueue(const SharedHandle& message, time_t timeout, - const SharedHandle& callback = 0); + const SharedHandle& callback = + SharedHandle()); virtual void addMessageToQueue(const SharedHandle& message, - const SharedHandle& callback = 0); + const SharedHandle& callback = + SharedHandle()); virtual void sendMessages(); diff --git a/src/DHTMessageFactoryImpl.cc b/src/DHTMessageFactoryImpl.cc index d3fd88cb..cd072a09 100644 --- a/src/DHTMessageFactoryImpl.cc +++ b/src/DHTMessageFactoryImpl.cc @@ -53,6 +53,7 @@ #include "DHTMessageDispatcher.h" #include "DHTPeerAnnounceStorage.h" #include "DHTTokenTracker.h" +#include "DHTMessageCallback.h" #include "PeerMessageUtil.h" #include "BtRuntime.h" #include "Util.h" @@ -63,8 +64,8 @@ namespace aria2 { -DHTMessageFactoryImpl::DHTMessageFactoryImpl():_localNode(0), - _logger(LogFactory::getInstance()) {} +DHTMessageFactoryImpl::DHTMessageFactoryImpl(): + _logger(LogFactory::getInstance()) {} DHTMessageFactoryImpl::~DHTMessageFactoryImpl() {} @@ -73,7 +74,7 @@ DHTMessageFactoryImpl::getRemoteNode(const unsigned char* id, const std::string& { SharedHandle node = _routingTable->getNode(id, ipaddr, port); if(node.isNull()) { - node = new DHTNode(id); + node.reset(new DHTNode(id)); node->setIPAddress(ipaddr); node->setPort(port); } @@ -245,12 +246,13 @@ void DHTMessageFactoryImpl::setCommonProperty(const SharedHandlesetConnection(_connection); m->setMessageDispatcher(_dispatcher); m->setRoutingTable(_routingTable); - m->setMessageFactory(this); + WeakHandle factory(this); + m->setMessageFactory(factory); } SharedHandle DHTMessageFactoryImpl::createPingMessage(const SharedHandle& remoteNode, const std::string& transactionID) { - SharedHandle m = new DHTPingMessage(_localNode, remoteNode, transactionID); + SharedHandle m(new DHTPingMessage(_localNode, remoteNode, transactionID)); setCommonProperty(m); return m; } @@ -260,7 +262,7 @@ DHTMessageFactoryImpl::createPingReplyMessage(const SharedHandle& remot const unsigned char* id, const std::string& transactionID) { - SharedHandle m = new DHTPingReplyMessage(_localNode, remoteNode, id, transactionID); + SharedHandle m(new DHTPingReplyMessage(_localNode, remoteNode, id, transactionID)); setCommonProperty(m); return m; } @@ -270,7 +272,7 @@ DHTMessageFactoryImpl::createFindNodeMessage(const SharedHandle& remote const unsigned char* targetNodeID, const std::string& transactionID) { - SharedHandle m = new DHTFindNodeMessage(_localNode, remoteNode, targetNodeID, transactionID); + SharedHandle m(new DHTFindNodeMessage(_localNode, remoteNode, targetNodeID, transactionID)); setCommonProperty(m); return m; } @@ -280,7 +282,7 @@ DHTMessageFactoryImpl::createFindNodeReplyMessage(const SharedHandle& r const std::deque >& closestKNodes, const std::string& transactionID) { - SharedHandle m = new DHTFindNodeReplyMessage(_localNode, remoteNode, transactionID); + SharedHandle m(new DHTFindNodeReplyMessage(_localNode, remoteNode, transactionID)); m->setClosestKNodes(closestKNodes); setCommonProperty(m); return m; @@ -294,7 +296,7 @@ DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length) } std::deque > nodes; for(size_t offset = 0; offset < length; offset += 26) { - SharedHandle node = new DHTNode(src+offset); + SharedHandle node(new DHTNode(src+offset)); std::pair addr = PeerMessageUtil::unpackcompact(src+offset+DHT_ID_LENGTH); if(addr.first.empty()) { @@ -322,10 +324,10 @@ DHTMessageFactoryImpl::createGetPeersMessage(const SharedHandle& remote const unsigned char* infoHash, const std::string& transactionID) { - SharedHandle m = new DHTGetPeersMessage(_localNode, - remoteNode, - infoHash, - transactionID); + SharedHandle m(new DHTGetPeersMessage(_localNode, + remoteNode, + infoHash, + transactionID)); m->setPeerAnnounceStorage(_peerAnnounceStorage); m->setTokenTracker(_tokenTracker); setCommonProperty(m); @@ -351,8 +353,8 @@ DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle& r const std::string& token, const std::string& transactionID) { - SharedHandle m = - new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID); + SharedHandle m + (new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID)); m->setClosestKNodes(closestKNodes); setCommonProperty(m); return m; @@ -370,7 +372,7 @@ DHTMessageFactoryImpl::createGetPeersReplyMessageWithValues(const SharedHandle(*i); if(data && data->getLen() == 6) { std::pair addr = PeerMessageUtil::unpackcompact(data->getData()); - PeerHandle peer = new Peer(addr.first, addr.second); + PeerHandle peer(new Peer(addr.first, addr.second)); peers.push_back(peer); } } @@ -385,7 +387,7 @@ DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle& r const std::string& token, const std::string& transactionID) { - SharedHandle m = new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID); + SharedHandle m(new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID)); m->setValues(values); setCommonProperty(m); return m; @@ -398,8 +400,8 @@ DHTMessageFactoryImpl::createAnnouncePeerMessage(const SharedHandle& re const std::string& token, const std::string& transactionID) { - SharedHandle m = - new DHTAnnouncePeerMessage(_localNode, remoteNode, infoHash, tcpPort, token, transactionID); + SharedHandle m + (new DHTAnnouncePeerMessage(_localNode, remoteNode, infoHash, tcpPort, token, transactionID)); m->setPeerAnnounceStorage(_peerAnnounceStorage); m->setTokenTracker(_tokenTracker); setCommonProperty(m); @@ -410,8 +412,8 @@ SharedHandle DHTMessageFactoryImpl::createAnnouncePeerReplyMessage(const SharedHandle& remoteNode, const std::string& transactionID) { - SharedHandle m = - new DHTAnnouncePeerReplyMessage(_localNode, remoteNode, transactionID); + SharedHandle m + (new DHTAnnouncePeerReplyMessage(_localNode, remoteNode, transactionID)); setCommonProperty(m); return m; } @@ -421,8 +423,8 @@ DHTMessageFactoryImpl::createUnknownMessage(const unsigned char* data, size_t le const std::string& ipaddr, uint16_t port) { - SharedHandle m = - new DHTUnknownMessage(_localNode, data, length, ipaddr, port); + SharedHandle m + (new DHTUnknownMessage(_localNode, data, length, ipaddr, port)); return m; } diff --git a/src/DHTMessageReceiver.cc b/src/DHTMessageReceiver.cc index 2522338d..fda00568 100644 --- a/src/DHTMessageReceiver.cc +++ b/src/DHTMessageReceiver.cc @@ -53,9 +53,6 @@ namespace aria2 { DHTMessageReceiver::DHTMessageReceiver(const SharedHandle& tracker): _tracker(tracker), - _connection(0), - _factory(0), - _routingTable(0), _logger(LogFactory::getInstance()) {} @@ -70,11 +67,11 @@ SharedHandle DHTMessageReceiver::receiveMessage() remoteAddr, remotePort); if(length <= 0) { - return 0; + return SharedHandle(); } try { bool isReply = false; - MetaEntryHandle msgroot = MetaFileUtil::bdecoding(data, length); + MetaEntryHandle msgroot(MetaFileUtil::bdecoding(data, length)); const Dictionary* d = dynamic_cast(msgroot.get()); if(d) { const Data* y = dynamic_cast(d->get("y")); @@ -90,8 +87,8 @@ SharedHandle DHTMessageReceiver::receiveMessage() _logger->info("Malformed DHT message. This is not a bencoded directory. From:%s:%u", remoteAddr.c_str(), remotePort); return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort); } - SharedHandle message = 0; - SharedHandle callback = 0; + SharedHandle message; + SharedHandle callback; if(isReply) { std::pair, SharedHandle > p = _tracker->messageArrived(d, remoteAddr, remotePort); message = p.first; diff --git a/src/DHTMessageTracker.cc b/src/DHTMessageTracker.cc index f90b1a7e..b3d911fa 100644 --- a/src/DHTMessageTracker.cc +++ b/src/DHTMessageTracker.cc @@ -51,15 +51,14 @@ namespace aria2 { DHTMessageTracker::DHTMessageTracker(): - _routingTable(0), - _factory(0), _logger(LogFactory::getInstance()) {} DHTMessageTracker::~DHTMessageTracker() {} void DHTMessageTracker::addMessage(const SharedHandle& message, time_t timeout, const SharedHandle& callback) { - _entries.push_back(new DHTMessageTrackerEntry(message, timeout, callback)); + SharedHandle e(new DHTMessageTrackerEntry(message, timeout, callback)); + _entries.push_back(e); } void DHTMessageTracker::addMessage(const SharedHandle& message, const SharedHandle& callback) @@ -95,7 +94,7 @@ DHTMessageTracker::messageArrived(const Dictionary* d, } } _logger->debug("Tracker entry not found."); - return std::pair, SharedHandle >(0, 0); + return std::pair, SharedHandle >(); } void DHTMessageTracker::handleTimeout() @@ -139,7 +138,7 @@ DHTMessageTracker::getEntryFor(const SharedHandle& message) const return *i; } } - return 0; + return SharedHandle(); } size_t DHTMessageTracker::countEntry() const diff --git a/src/DHTMessageTracker.h b/src/DHTMessageTracker.h index 2c1f57f1..9c92b78e 100644 --- a/src/DHTMessageTracker.h +++ b/src/DHTMessageTracker.h @@ -67,10 +67,12 @@ public: void addMessage(const SharedHandle& message, time_t timeout, - const SharedHandle& callback = 0); + const SharedHandle& callback = + SharedHandle()); void addMessage(const SharedHandle& message, - const SharedHandle& callback = 0); + const SharedHandle& callback = + SharedHandle()); std::pair, SharedHandle > messageArrived(const Dictionary* d, const std::string& ipaddr, uint16_t port); diff --git a/src/DHTMessageTrackerEntry.h b/src/DHTMessageTrackerEntry.h index d2299b73..25d63ebe 100644 --- a/src/DHTMessageTrackerEntry.h +++ b/src/DHTMessageTrackerEntry.h @@ -63,7 +63,8 @@ private: public: DHTMessageTrackerEntry(const SharedHandle& sentMessage, time_t timeout, - const SharedHandle& callback = 0); + const SharedHandle& callback = + SharedHandle()); bool isTimeout() const; diff --git a/src/DHTNodeLookupTask.cc b/src/DHTNodeLookupTask.cc index 72fd0805..b15e0a27 100644 --- a/src/DHTNodeLookupTask.cc +++ b/src/DHTNodeLookupTask.cc @@ -39,6 +39,7 @@ #include "DHTNodeLookupEntry.h" #include "LogFactory.h" #include "Util.h" +#include namespace aria2 { @@ -49,7 +50,8 @@ DHTNodeLookupTask::DHTNodeLookupTask(const unsigned char* targetNodeID): std::deque > DHTNodeLookupTask::getNodesFromMessage(const SharedHandle& message) { - SharedHandle m = message; + SharedHandle m + (dynamic_pointer_cast(message)); if(m.isNull()) { return std::deque >(); } else { diff --git a/src/DHTPeerAnnounceCommand.cc b/src/DHTPeerAnnounceCommand.cc index eb633aeb..9cba7e4d 100644 --- a/src/DHTPeerAnnounceCommand.cc +++ b/src/DHTPeerAnnounceCommand.cc @@ -43,9 +43,7 @@ namespace aria2 { DHTPeerAnnounceCommand::DHTPeerAnnounceCommand(int32_t cuid, DownloadEngine* e, time_t interval): - TimeBasedCommand(cuid, e, interval), - _peerAnnounceStorage(0) -{} + TimeBasedCommand(cuid, e, interval) {} DHTPeerAnnounceCommand::~DHTPeerAnnounceCommand() {} diff --git a/src/DHTPeerAnnounceEntry.cc b/src/DHTPeerAnnounceEntry.cc index 1ed364ff..393d6cd0 100644 --- a/src/DHTPeerAnnounceEntry.cc +++ b/src/DHTPeerAnnounceEntry.cc @@ -42,8 +42,7 @@ namespace aria2 { -DHTPeerAnnounceEntry::DHTPeerAnnounceEntry(const unsigned char* infoHash): - _btCtx(0) +DHTPeerAnnounceEntry::DHTPeerAnnounceEntry(const unsigned char* infoHash) { memcpy(_infoHash, infoHash, DHT_ID_LENGTH); } @@ -108,7 +107,8 @@ Peers DHTPeerAnnounceEntry::getPeers() const std::deque > peers; for(std::deque::const_iterator i = _peerAddrEntries.begin(); i != _peerAddrEntries.end(); ++i) { - peers.push_back(new Peer((*i).getIPAddress(), (*i).getPort())); + SharedHandle peer(new Peer((*i).getIPAddress(), (*i).getPort())); + peers.push_back(peer); } if(!_btCtx.isNull()) { SharedHandle peerStorage = PEER_STORAGE(_btCtx); diff --git a/src/DHTPeerAnnounceStorage.cc b/src/DHTPeerAnnounceStorage.cc index f6c44f91..46fab662 100644 --- a/src/DHTPeerAnnounceStorage.cc +++ b/src/DHTPeerAnnounceStorage.cc @@ -48,9 +48,8 @@ namespace aria2 { -DHTPeerAnnounceStorage::DHTPeerAnnounceStorage():_taskQueue(0), - _taskFactory(0), - _logger(LogFactory::getInstance()) {} +DHTPeerAnnounceStorage::DHTPeerAnnounceStorage(): + _logger(LogFactory::getInstance()) {} DHTPeerAnnounceStorage::~DHTPeerAnnounceStorage() {} @@ -74,9 +73,9 @@ DHTPeerAnnounceStorage::getPeerAnnounceEntry(const unsigned char* infoHash) { std::deque >::iterator i = std::find_if(_entries.begin(), _entries.end(), FindPeerAnnounceEntry(infoHash)); - SharedHandle entry = 0; + SharedHandle entry; if(i == _entries.end()) { - entry = new DHTPeerAnnounceEntry(infoHash); + entry.reset(new DHTPeerAnnounceEntry(infoHash)); _entries.push_back(entry); } else { entry = *i; @@ -106,7 +105,7 @@ void DHTPeerAnnounceStorage::removePeerAnnounce(const BtContextHandle& ctx) std::deque >::iterator i = std::find_if(_entries.begin(), _entries.end(), FindPeerAnnounceEntry(ctx->getInfoHash())); if(i != _entries.end()) { - (*i)->setBtContext(0); + (*i)->setBtContext(SharedHandle()); if((*i)->empty()) { _entries.erase(i); } diff --git a/src/DHTPeerLookupTask.cc b/src/DHTPeerLookupTask.cc index 5f6152fa..c739f284 100644 --- a/src/DHTPeerLookupTask.cc +++ b/src/DHTPeerLookupTask.cc @@ -58,7 +58,7 @@ DHTPeerLookupTask::DHTPeerLookupTask(const SharedHandle& btContext): std::deque > DHTPeerLookupTask::getNodesFromMessage(const SharedHandle& message) { - SharedHandle m = message; + SharedHandle m(dynamic_pointer_cast(message)); if(m.isNull()) { return std::deque >(); } else { @@ -68,7 +68,7 @@ std::deque > DHTPeerLookupTask::getNodesFromMessage(const void DHTPeerLookupTask::onReceivedInternal(const SharedHandle& message) { - SharedHandle m = message; + SharedHandle m(dynamic_pointer_cast(message)); if(m.isNull()) { return; } diff --git a/src/DHTPingTask.cc b/src/DHTPingTask.cc index 4eb03025..c7ab1049 100644 --- a/src/DHTPingTask.cc +++ b/src/DHTPingTask.cc @@ -55,7 +55,9 @@ DHTPingTask::~DHTPingTask() {} void DHTPingTask::startup() { SharedHandle m = _factory->createPingMessage(_remoteNode); - _dispatcher->addMessageToQueue(m, _timeout, new DHTMessageCallbackImpl(this)); + WeakHandle listener(this); + SharedHandle callback(new DHTMessageCallbackImpl(listener)); + _dispatcher->addMessageToQueue(m, _timeout, callback); } void DHTPingTask::onReceived(const SharedHandle& message) @@ -72,7 +74,9 @@ void DHTPingTask::onTimeout(const SharedHandle& node) _finished = true; } else { SharedHandle m = _factory->createPingMessage(_remoteNode); - _dispatcher->addMessageToQueue(m, _timeout, new DHTMessageCallbackImpl(this)); + WeakHandle listener(this); + SharedHandle callback(new DHTMessageCallbackImpl(listener)); + _dispatcher->addMessageToQueue(m, _timeout, callback); } } diff --git a/src/DHTRegistry.cc b/src/DHTRegistry.cc index 940e5275..3bebacf1 100644 --- a/src/DHTRegistry.cc +++ b/src/DHTRegistry.cc @@ -42,38 +42,39 @@ #include "DHTMessageDispatcher.h" #include "DHTMessageReceiver.h" #include "DHTMessageFactory.h" +#include "DHTMessageCallback.h" namespace aria2 { -SharedHandle DHTRegistry::_localNode = 0; +SharedHandle DHTRegistry::_localNode; -SharedHandle DHTRegistry::_routingTable = 0; +SharedHandle DHTRegistry::_routingTable; -SharedHandle DHTRegistry::_taskQueue = 0; +SharedHandle DHTRegistry::_taskQueue; -SharedHandle DHTRegistry::_taskFactory = 0; +SharedHandle DHTRegistry::_taskFactory; -SharedHandle DHTRegistry::_peerAnnounceStorage = 0; +SharedHandle DHTRegistry::_peerAnnounceStorage; -SharedHandle DHTRegistry::_tokenTracker = 0; +SharedHandle DHTRegistry::_tokenTracker; -SharedHandle DHTRegistry::_messageDispatcher = 0; +SharedHandle DHTRegistry::_messageDispatcher; -SharedHandle DHTRegistry::_messageReceiver = 0; +SharedHandle DHTRegistry::_messageReceiver; -SharedHandle DHTRegistry::_messageFactory = 0; +SharedHandle DHTRegistry::_messageFactory; void DHTRegistry::clear() { - _localNode = 0; - _routingTable = 0; - _taskQueue = 0; - _taskFactory = 0; - _peerAnnounceStorage = 0; - _tokenTracker = 0; - _messageDispatcher = 0; - _messageReceiver = 0; - _messageFactory = 0; + _localNode.reset(); + _routingTable.reset(); + _taskQueue.reset(); + _taskFactory.reset(); + _peerAnnounceStorage.reset(); + _tokenTracker.reset(); + _messageDispatcher.reset(); + _messageReceiver.reset(); + _messageFactory.reset(); } } // namespace aria2 diff --git a/src/DHTReplaceNodeTask.cc b/src/DHTReplaceNodeTask.cc index b1e1cdf4..9c480b2e 100644 --- a/src/DHTReplaceNodeTask.cc +++ b/src/DHTReplaceNodeTask.cc @@ -65,7 +65,9 @@ void DHTReplaceNodeTask::sendMessage() _finished = true; } else { SharedHandle m = _factory->createPingMessage(questionableNode); - _dispatcher->addMessageToQueue(m, _timeout, new DHTMessageCallbackImpl(this)); + WeakHandle listener(this); + SharedHandle callback(new DHTMessageCallbackImpl(listener)); + _dispatcher->addMessageToQueue(m, _timeout, callback); } } diff --git a/src/DHTRoutingTable.cc b/src/DHTRoutingTable.cc index c811c805..1e54c319 100644 --- a/src/DHTRoutingTable.cc +++ b/src/DHTRoutingTable.cc @@ -47,12 +47,12 @@ namespace aria2 { DHTRoutingTable::DHTRoutingTable(const SharedHandle& localNode): _localNode(localNode), - _root(new BNode(new DHTBucket(localNode))), _numBucket(1), - _taskQueue(0), - _taskFactory(0), _logger(LogFactory::getInstance()) -{} +{ + SharedHandle bucket(new DHTBucket(_localNode)); + _root = new BNode(bucket); +} DHTRoutingTable::~DHTRoutingTable() { @@ -84,7 +84,7 @@ bool DHTRoutingTable::addNode(const SharedHandle& node, bool good) Util::toHex(bucket->getMaxID(), DHT_ID_LENGTH).c_str()); SharedHandle r = bucket->split(); - bnode->setBucket(0); + bnode->setBucket(SharedHandle()); BNode* lbnode = new BNode(bucket); BNode* rbnode = new BNode(r); bnode->setLeft(lbnode); diff --git a/src/DHTRoutingTableDeserializer.cc b/src/DHTRoutingTableDeserializer.cc index e749d097..cc38afa7 100644 --- a/src/DHTRoutingTableDeserializer.cc +++ b/src/DHTRoutingTableDeserializer.cc @@ -46,8 +46,7 @@ namespace aria2 { -DHTRoutingTableDeserializer::DHTRoutingTableDeserializer(): - _localNode(0) {} +DHTRoutingTableDeserializer::DHTRoutingTableDeserializer() {} DHTRoutingTableDeserializer::~DHTRoutingTableDeserializer() {} @@ -96,7 +95,7 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in) in.read(buf, 8); // localnode ID in.read(buf, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(reinterpret_cast(buf)); + SharedHandle localNode(new DHTNode(reinterpret_cast(buf))); // 4bytes reserved in.read(buf, 4); @@ -140,7 +139,7 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in) // localnode ID in.read(buf, DHT_ID_LENGTH); - SharedHandle node = new DHTNode(reinterpret_cast(buf)); + SharedHandle node(new DHTNode(reinterpret_cast(buf))); node->setIPAddress(peer.first); node->setPort(peer.second); // 4bytes reserved diff --git a/src/DHTRoutingTableSerializer.cc b/src/DHTRoutingTableSerializer.cc index e2ffa1f1..65d9f16a 100644 --- a/src/DHTRoutingTableSerializer.cc +++ b/src/DHTRoutingTableSerializer.cc @@ -45,7 +45,7 @@ namespace aria2 { -DHTRoutingTableSerializer::DHTRoutingTableSerializer():_localNode(0) {} +DHTRoutingTableSerializer::DHTRoutingTableSerializer() {} DHTRoutingTableSerializer::~DHTRoutingTableSerializer() {} diff --git a/src/DHTSetup.cc b/src/DHTSetup.cc index 85831dad..eaf3ca03 100644 --- a/src/DHTSetup.cc +++ b/src/DHTSetup.cc @@ -58,6 +58,7 @@ #include "DHTRoutingTableDeserializer.h" #include "DHTRegistry.h" #include "DHTBucketRefreshTask.h" +#include "DHTMessageCallback.h" #include "CUIDCounter.h" #include "prefs.h" #include "Option.h" @@ -82,7 +83,7 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) try { // load routing table and localnode id here - SharedHandle localNode = 0; + SharedHandle localNode; DHTRoutingTableDeserializer deserializer; std::string dhtFile = option->get(PREF_DHT_FILE_PATH); @@ -99,10 +100,10 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) } } if(localNode.isNull()) { - localNode = new DHTNode(); + localNode.reset(new DHTNode()); } - SharedHandle connection = new DHTConnectionImpl(); + SharedHandle connection(new DHTConnectionImpl()); { IntSequence seq = Util::parseIntRange(option->get(PREF_DHT_LISTEN_PORT)); uint16_t port; @@ -114,23 +115,23 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) _logger->debug("Initialized local node ID=%s", Util::toHex(localNode->getID(), DHT_ID_LENGTH).c_str()); - SharedHandle routingTable = new DHTRoutingTable(localNode); + SharedHandle routingTable(new DHTRoutingTable(localNode)); - SharedHandle factory = new DHTMessageFactoryImpl(); + SharedHandle factory(new DHTMessageFactoryImpl()); - SharedHandle tracker = new DHTMessageTracker(); + SharedHandle tracker(new DHTMessageTracker()); - SharedHandle dispatcher = new DHTMessageDispatcherImpl(tracker); + SharedHandle dispatcher(new DHTMessageDispatcherImpl(tracker)); - SharedHandle receiver = new DHTMessageReceiver(tracker); + SharedHandle receiver(new DHTMessageReceiver(tracker)); - SharedHandle taskQueue = new DHTTaskQueueImpl(); + SharedHandle taskQueue(new DHTTaskQueueImpl()); - SharedHandle taskFactory = new DHTTaskFactoryImpl(); + SharedHandle taskFactory(new DHTTaskFactoryImpl()); - SharedHandle peerAnnounceStorage = new DHTPeerAnnounceStorage(); + SharedHandle peerAnnounceStorage(new DHTPeerAnnounceStorage()); - SharedHandle tokenTracker = new DHTTokenTracker(); + SharedHandle tokenTracker(new DHTTokenTracker()); // wiring up tracker->setRoutingTable(routingTable); @@ -176,7 +177,8 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) routingTable->addNode(*i); } if(!desnodes.empty() && deserializer.getSerializedTime().elapsed(DHT_BUCKET_REFRESH_INTERVAL)) { - SharedHandle task = taskFactory->createBucketRefreshTask(); + SharedHandle task + (dynamic_pointer_cast(taskFactory->createBucketRefreshTask())); task->setForceRefresh(true); taskQueue->addPeriodicTask1(task); } diff --git a/src/DHTTaskFactoryImpl.cc b/src/DHTTaskFactoryImpl.cc index c4f2101e..9e399cd1 100644 --- a/src/DHTTaskFactoryImpl.cc +++ b/src/DHTTaskFactoryImpl.cc @@ -50,15 +50,11 @@ #include "BtContext.h" #include "PeerStorage.h" #include "BtRuntime.h" +#include "DHTMessageCallback.h" namespace aria2 { -DHTTaskFactoryImpl::DHTTaskFactoryImpl():_localNode(0), - _routingTable(0), - _dispatcher(0), - _factory(0), - _taskQueue(0), - _logger(LogFactory::getInstance()) {} +DHTTaskFactoryImpl::DHTTaskFactoryImpl():_logger(LogFactory::getInstance()) {} DHTTaskFactoryImpl::~DHTTaskFactoryImpl() {} @@ -66,7 +62,7 @@ SharedHandle DHTTaskFactoryImpl::createPingTask(const SharedHandle& remoteNode, size_t numRetry) { - SharedHandle task = new DHTPingTask(remoteNode, numRetry); + SharedHandle task(new DHTPingTask(remoteNode, numRetry)); setCommonProperty(task); return task; } @@ -74,7 +70,7 @@ DHTTaskFactoryImpl::createPingTask(const SharedHandle& remoteNode, SharedHandle DHTTaskFactoryImpl::createNodeLookupTask(const unsigned char* targetID) { - SharedHandle task = new DHTNodeLookupTask(targetID); + SharedHandle task(new DHTNodeLookupTask(targetID)); setCommonProperty(task); return task; } @@ -82,7 +78,7 @@ DHTTaskFactoryImpl::createNodeLookupTask(const unsigned char* targetID) SharedHandle DHTTaskFactoryImpl::createBucketRefreshTask() { - SharedHandle task = new DHTBucketRefreshTask(); + SharedHandle task(new DHTBucketRefreshTask()); setCommonProperty(task); return task; } @@ -90,7 +86,7 @@ DHTTaskFactoryImpl::createBucketRefreshTask() SharedHandle DHTTaskFactoryImpl::createPeerLookupTask(const SharedHandle& ctx) { - SharedHandle task = new DHTPeerLookupTask(ctx); + SharedHandle task(new DHTPeerLookupTask(ctx)); setCommonProperty(task); return task; } @@ -99,14 +95,14 @@ SharedHandle DHTTaskFactoryImpl::createPeerAnnounceTask(const unsigned char* infoHash) { // TODO - return 0; + return SharedHandle(); } SharedHandle DHTTaskFactoryImpl::createReplaceNodeTask(const SharedHandle& bucket, const SharedHandle& newNode) { - SharedHandle task = new DHTReplaceNodeTask(bucket, newNode); + SharedHandle task(new DHTReplaceNodeTask(bucket, newNode)); setCommonProperty(task); return task; } diff --git a/src/DHTTaskQueueImpl.cc b/src/DHTTaskQueueImpl.cc index fe01cdf8..bbec4374 100644 --- a/src/DHTTaskQueueImpl.cc +++ b/src/DHTTaskQueueImpl.cc @@ -37,9 +37,7 @@ namespace aria2 { -DHTTaskQueueImpl::DHTTaskQueueImpl():_periodicTask1(0), - _periodicTask2(0), - _immediateTask(0) {} +DHTTaskQueueImpl::DHTTaskQueueImpl() {} DHTTaskQueueImpl::~DHTTaskQueueImpl() {} @@ -48,7 +46,7 @@ void DHTTaskQueueImpl::executeTask(SharedHandle& task, { while(1) { if(task.isNull() || task->finished()) { - task = 0; + task.reset(); if(taskQueue.empty()) { break; } diff --git a/src/DHTTokenUpdateCommand.cc b/src/DHTTokenUpdateCommand.cc index a76c73cd..e380347f 100644 --- a/src/DHTTokenUpdateCommand.cc +++ b/src/DHTTokenUpdateCommand.cc @@ -45,9 +45,7 @@ namespace aria2 { DHTTokenUpdateCommand::DHTTokenUpdateCommand(int32_t cuid, DownloadEngine* e, time_t interval): - TimeBasedCommand(cuid, e, interval), - _tokenTracker(0) -{} + TimeBasedCommand(cuid, e, interval) {} DHTTokenUpdateCommand::~DHTTokenUpdateCommand() {} diff --git a/src/DHTUnknownMessage.cc b/src/DHTUnknownMessage.cc index 8d8aa140..d188ab08 100644 --- a/src/DHTUnknownMessage.cc +++ b/src/DHTUnknownMessage.cc @@ -42,7 +42,7 @@ namespace aria2 { DHTUnknownMessage::DHTUnknownMessage(const SharedHandle& localNode, const unsigned char* data, size_t length, const std::string& ipaddr, uint16_t port): - DHTMessage(localNode, 0), + DHTMessage(localNode, SharedHandle()), _length(length), _ipaddr(ipaddr), _port(port) diff --git a/src/DefaultBtContext.cc b/src/DefaultBtContext.cc index 43499ac4..737d5d0b 100644 --- a/src/DefaultBtContext.cc +++ b/src/DefaultBtContext.cc @@ -262,7 +262,7 @@ void DefaultBtContext::loadFromMemory(const unsigned char* content, size_t length, const std::string& defaultName) { - SharedHandle rootEntry = MetaFileUtil::bdecoding(content, length); + SharedHandle rootEntry(MetaFileUtil::bdecoding(content, length)); const Dictionary* rootDic = dynamic_cast(rootEntry.get()); if(!rootDic) { throw new DlAbortEx("torrent file does not contain a root dictionary ."); @@ -271,7 +271,7 @@ void DefaultBtContext::loadFromMemory(const unsigned char* content, } void DefaultBtContext::load(const std::string& torrentFile) { - SharedHandle rootEntry = MetaFileUtil::parseMetaFile(torrentFile); + SharedHandle rootEntry(MetaFileUtil::parseMetaFile(torrentFile)); const Dictionary* rootDic = dynamic_cast(rootEntry.get()); if(!rootDic) { throw new DlAbortEx("torrent file does not contain a root dictionary ."); diff --git a/src/DefaultBtInteractive.cc b/src/DefaultBtInteractive.cc index a86993cd..be73826e 100644 --- a/src/DefaultBtInteractive.cc +++ b/src/DefaultBtInteractive.cc @@ -83,7 +83,7 @@ DefaultBtInteractive::~DefaultBtInteractive() {} void DefaultBtInteractive::initiateHandshake() { - SharedHandle message = + SharedHandle message = messageFactory->createHandshakeMessage(btContext->getInfoHash(), btContext->getPeerId()); dispatcher->addMessageToQueue(message); @@ -94,7 +94,7 @@ BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) { SharedHandle message = btMessageReceiver->receiveHandshake(quickReply); if(message.isNull()) { - return 0; + return SharedHandle(); } peer->setPeerId(message->getPeerId()); @@ -104,8 +104,8 @@ BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) { } if(message->isExtendedMessagingEnabled()) { peer->setExtendedMessagingEnabled(true); - DefaultExtensionMessageFactoryHandle factory = - new DefaultExtensionMessageFactory(btContext, peer); + DefaultExtensionMessageFactoryHandle factory + (new DefaultExtensionMessageFactory(btContext, peer)); if(!_utPexEnabled) { factory->removeExtension("ut_pex"); } @@ -150,12 +150,12 @@ void DefaultBtInteractive::addPortMessageToQueue() void DefaultBtInteractive::addHandshakeExtendedMessageToQueue() { - HandshakeExtensionMessageHandle m = new HandshakeExtensionMessage(); + HandshakeExtensionMessageHandle m(new HandshakeExtensionMessage()); m->setClientVersion("aria2"); m->setTCPPort(btRuntime->getListenPort()); m->setExtensions(EXTENSION_MESSAGE_FACTORY(btContext, peer)->getExtensions()); - BtExtendedMessageHandle msg = messageFactory->createBtExtendedMessage(m); + SharedHandle msg = messageFactory->createBtExtendedMessage(m); dispatcher->addMessageToQueue(msg); } @@ -386,8 +386,8 @@ void DefaultBtInteractive::addPeerExchangeMessage() { time_t interval = 60; if(_pexCheckPoint.elapsed(interval)) { - UTPexExtensionMessageHandle m = - new UTPexExtensionMessage(peer->getExtensionMessageID("ut_pex")); + UTPexExtensionMessageHandle m + (new UTPexExtensionMessage(peer->getExtensionMessageID("ut_pex"))); const Peers& peers = peerStorage->getPeers(); { size_t max = 30; @@ -413,7 +413,7 @@ void DefaultBtInteractive::addPeerExchangeMessage() } } } - BtExtendedMessageHandle msg = messageFactory->createBtExtendedMessage(m); + BtMessageHandle msg = messageFactory->createBtExtendedMessage(m); dispatcher->addMessageToQueue(msg); _pexCheckPoint.reset(); } diff --git a/src/DefaultBtMessageDispatcher.cc b/src/DefaultBtMessageDispatcher.cc index 3067c76b..cfd8032d 100644 --- a/src/DefaultBtMessageDispatcher.cc +++ b/src/DefaultBtMessageDispatcher.cc @@ -56,10 +56,6 @@ namespace aria2 { DefaultBtMessageDispatcher::DefaultBtMessageDispatcher(): cuid(0), - btContext(0), - peerStorage(0), - pieceStorage(0), - peer(0), maxUploadSpeedLimit(0), requestTimeout(0), logger(LogFactory::getInstance()) {} @@ -108,8 +104,8 @@ void DefaultBtMessageDispatcher::sendMessages() { // Cancel sending piece message to peer. void DefaultBtMessageDispatcher::doCancelSendingPieceAction(size_t index, uint32_t begin, size_t length) { - BtCancelSendingPieceEventHandle event = - new BtCancelSendingPieceEvent(index, begin, length); + BtCancelSendingPieceEventHandle event + (new BtCancelSendingPieceEvent(index, begin, length)); BtMessages tempQueue = messageQueue; for(BtMessages::iterator itr = tempQueue.begin(); itr != tempQueue.end(); itr++) { @@ -140,8 +136,8 @@ void DefaultBtMessageDispatcher::doAbortOutstandingRequestAction(const PieceHand } } - BtAbortOutstandingRequestEventHandle event = - new BtAbortOutstandingRequestEvent(piece); + BtAbortOutstandingRequestEventHandle event + (new BtAbortOutstandingRequestEvent(piece)); BtMessages tempQueue = messageQueue; for(BtMessages::iterator itr = tempQueue.begin(); itr != tempQueue.end(); ++itr) { @@ -168,7 +164,7 @@ void DefaultBtMessageDispatcher::doChokedAction() } } - BtChokedEventHandle event = new BtChokedEvent(); + BtChokedEventHandle event(new BtChokedEvent()); BtMessages tempQueue = messageQueue; for(BtMessages::iterator itr = tempQueue.begin(); itr != tempQueue.end(); ++itr) { @@ -179,7 +175,7 @@ void DefaultBtMessageDispatcher::doChokedAction() // localhost dispatched choke message to the peer. void DefaultBtMessageDispatcher::doChokingAction() { - BtChokingEventHandle event = new BtChokingEvent(); + BtChokingEventHandle event(new BtChokingEvent()); BtMessages tempQueue = messageQueue; for(BtMessages::iterator itr = tempQueue.begin(); itr != tempQueue.end(); ++itr) { diff --git a/src/DefaultBtMessageFactory.cc b/src/DefaultBtMessageFactory.cc index 75a5e862..e650ca3b 100644 --- a/src/DefaultBtMessageFactory.cc +++ b/src/DefaultBtMessageFactory.cc @@ -72,9 +72,6 @@ namespace aria2 { DefaultBtMessageFactory::DefaultBtMessageFactory():cuid(0), - btContext(0), - pieceStorage(0), - peer(0), _dhtEnabled(false) {} @@ -83,10 +80,10 @@ DefaultBtMessageFactory::~DefaultBtMessageFactory() {} BtMessageHandle DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataLength) { - AbstractBtMessageHandle msg(0); + AbstractBtMessageHandle msg; if(dataLength == 0) { // keep-alive - msg = new BtKeepAliveMessage(); + msg.reset(new BtKeepAliveMessage()); } else { uint8_t id = PeerMessageUtil::getId(data); switch(id) { @@ -104,40 +101,48 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL break; case BtHaveMessage::ID: msg = BtHaveMessage::create(data, dataLength); - msg->setBtMessageValidator(new BtHaveMessageValidator((BtHaveMessage*)msg.get(), - btContext->getNumPieces())); + { + SharedHandle v + (new BtHaveMessageValidator((BtHaveMessage*)msg.get(), + btContext->getNumPieces())); + msg->setBtMessageValidator(v); + } break; case BtBitfieldMessage::ID: msg = BtBitfieldMessage::create(data, dataLength); - msg->setBtMessageValidator(new BtBitfieldMessageValidator((BtBitfieldMessage*)msg.get(), - btContext->getNumPieces())); + { + SharedHandle v + (new BtBitfieldMessageValidator((BtBitfieldMessage*)msg.get(), + btContext->getNumPieces())); + msg->setBtMessageValidator(v); + } break; case BtRequestMessage::ID: { BtRequestMessageHandle temp = BtRequestMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtRequestMessageValidator(temp.get(), + BtMessageValidatorHandle validator + (new BtRequestMessageValidator(temp.get(), btContext->getNumPieces(), - pieceStorage->getPieceLength(temp->getIndex())); + pieceStorage->getPieceLength(temp->getIndex()))); temp->setBtMessageValidator(validator); msg = temp; break; } case BtCancelMessage::ID: { BtCancelMessageHandle temp = BtCancelMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtCancelMessageValidator(temp.get(), + BtMessageValidatorHandle validator + (new BtCancelMessageValidator(temp.get(), btContext->getNumPieces(), - pieceStorage->getPieceLength(temp->getIndex())); + pieceStorage->getPieceLength(temp->getIndex()))); temp->setBtMessageValidator(validator); msg = temp; break; } case BtPieceMessage::ID: { BtPieceMessageHandle temp = BtPieceMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtPieceMessageValidator(temp.get(), - btContext->getNumPieces(), - pieceStorage->getPieceLength(temp->getIndex())); + BtMessageValidatorHandle validator + (new BtPieceMessageValidator(temp.get(), + btContext->getNumPieces(), + pieceStorage->getPieceLength(temp->getIndex()))); temp->setBtMessageValidator(validator); msg = temp; break; @@ -150,28 +155,28 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL break; case BtRejectMessage::ID: { BtRejectMessageHandle temp = BtRejectMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtRejectMessageValidator(temp.get(), - btContext->getNumPieces(), - pieceStorage->getPieceLength(temp->getIndex())); + BtMessageValidatorHandle validator + (new BtRejectMessageValidator(temp.get(), + btContext->getNumPieces(), + pieceStorage->getPieceLength(temp->getIndex()))); temp->setBtMessageValidator(validator); msg = temp; break; } case BtSuggestPieceMessage::ID: { BtSuggestPieceMessageHandle temp = BtSuggestPieceMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtSuggestPieceMessageValidator(temp.get(), - btContext->getNumPieces()); + BtMessageValidatorHandle validator + (new BtSuggestPieceMessageValidator(temp.get(), + btContext->getNumPieces())); temp->setBtMessageValidator(validator); msg = temp; break; } case BtAllowedFastMessage::ID: { BtAllowedFastMessageHandle temp = BtAllowedFastMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtAllowedFastMessageValidator(temp.get(), - btContext->getNumPieces()); + BtMessageValidatorHandle validator + (new BtAllowedFastMessageValidator(temp.get(), + btContext->getNumPieces())); temp->setBtMessageValidator(validator); msg = temp; break; @@ -207,30 +212,30 @@ void DefaultBtMessageFactory::setCommonProperty(const AbstractBtMessageHandle& m msg->setBtContext(btContext); msg->setBtMessageDispatcher(dispatcher); msg->setBtRequestFactory(requestFactory); - msg->setBtMessageFactory(this); + msg->setBtMessageFactory(WeakHandle(this)); msg->setPeerConnection(peerConnection); } -BtMessageHandle +SharedHandle DefaultBtMessageFactory::createHandshakeMessage(const unsigned char* data, size_t dataLength) { SharedHandle msg = BtHandshakeMessage::create(data, dataLength); - BtMessageValidatorHandle validator = - new BtHandshakeMessageValidator(msg.get(), - btContext->getInfoHash()); + BtMessageValidatorHandle validator + (new BtHandshakeMessageValidator(msg.get(), + btContext->getInfoHash())); msg->setBtMessageValidator(validator); setCommonProperty(msg); return msg; } -BtMessageHandle +SharedHandle DefaultBtMessageFactory::createHandshakeMessage(const unsigned char* infoHash, const unsigned char* peerId) { - SharedHandle msg = new BtHandshakeMessage(infoHash, peerId); - BtMessageValidatorHandle validator = - new BtHandshakeMessageValidator(msg.get(), - btContext->getInfoHash()); + SharedHandle msg(new BtHandshakeMessage(infoHash, peerId)); + BtMessageValidatorHandle validator + (new BtHandshakeMessageValidator(msg.get(), + btContext->getInfoHash())); msg->setBtMessageValidator(validator); msg->setDHTEnabled(_dhtEnabled); setCommonProperty(msg); @@ -240,15 +245,15 @@ DefaultBtMessageFactory::createHandshakeMessage(const unsigned char* infoHash, BtMessageHandle DefaultBtMessageFactory::createRequestMessage(const PieceHandle& piece, size_t blockIndex) { - BtRequestMessageHandle msg = - new BtRequestMessage(piece->getIndex(), - blockIndex*piece->getBlockLength(), - piece->getBlockLength(blockIndex), - blockIndex); - BtMessageValidatorHandle validator = - new BtRequestMessageValidator(msg.get(), - btContext->getNumPieces(), - pieceStorage->getPieceLength(msg->getIndex())); + BtRequestMessageHandle msg + (new BtRequestMessage(piece->getIndex(), + blockIndex*piece->getBlockLength(), + piece->getBlockLength(blockIndex), + blockIndex)); + BtMessageValidatorHandle validator + (new BtRequestMessageValidator(msg.get(), + btContext->getNumPieces(), + pieceStorage->getPieceLength(msg->getIndex()))); msg->setBtMessageValidator(validator); setCommonProperty(msg); return msg; @@ -257,11 +262,11 @@ DefaultBtMessageFactory::createRequestMessage(const PieceHandle& piece, size_t b BtMessageHandle DefaultBtMessageFactory::createCancelMessage(size_t index, uint32_t begin, size_t length) { - BtCancelMessageHandle msg = new BtCancelMessage(index, begin, length); - BtMessageValidatorHandle validator = - new BtCancelMessageValidator(msg.get(), - btContext->getNumPieces(), - pieceStorage->getPieceLength(index)); + BtCancelMessageHandle msg(new BtCancelMessage(index, begin, length)); + BtMessageValidatorHandle validator + (new BtCancelMessageValidator(msg.get(), + btContext->getNumPieces(), + pieceStorage->getPieceLength(index))); msg->setBtMessageValidator(validator); setCommonProperty(msg); return msg; @@ -270,11 +275,11 @@ DefaultBtMessageFactory::createCancelMessage(size_t index, uint32_t begin, size_ BtMessageHandle DefaultBtMessageFactory::createPieceMessage(size_t index, uint32_t begin, size_t length) { - BtPieceMessageHandle msg = new BtPieceMessage(index, begin, length); - BtMessageValidatorHandle validator = - new BtPieceMessageValidator(msg.get(), + BtPieceMessageHandle msg(new BtPieceMessage(index, begin, length)); + BtMessageValidatorHandle validator + (new BtPieceMessageValidator(msg.get(), btContext->getNumPieces(), - pieceStorage->getPieceLength(index)); + pieceStorage->getPieceLength(index))); msg->setBtMessageValidator(validator); setCommonProperty(msg); return msg; @@ -283,9 +288,11 @@ DefaultBtMessageFactory::createPieceMessage(size_t index, uint32_t begin, size_t BtMessageHandle DefaultBtMessageFactory::createHaveMessage(size_t index) { - BtHaveMessageHandle msg = new BtHaveMessage(index); - msg->setBtMessageValidator(new BtHaveMessageValidator(msg.get(), - btContext->getNumPieces())); + BtHaveMessageHandle msg(new BtHaveMessage(index)); + SharedHandle v + (new BtHaveMessageValidator(msg.get(), + btContext->getNumPieces())); + msg->setBtMessageValidator(v); setCommonProperty(msg); return msg; } @@ -293,7 +300,7 @@ DefaultBtMessageFactory::createHaveMessage(size_t index) BtMessageHandle DefaultBtMessageFactory::createChokeMessage() { - BtChokeMessageHandle msg = new BtChokeMessage(); + BtChokeMessageHandle msg(new BtChokeMessage()); setCommonProperty(msg); return msg; } @@ -301,7 +308,7 @@ DefaultBtMessageFactory::createChokeMessage() BtMessageHandle DefaultBtMessageFactory::createUnchokeMessage() { - BtUnchokeMessageHandle msg = new BtUnchokeMessage(); + BtUnchokeMessageHandle msg(new BtUnchokeMessage()); setCommonProperty(msg); return msg; } @@ -309,7 +316,7 @@ DefaultBtMessageFactory::createUnchokeMessage() BtMessageHandle DefaultBtMessageFactory::createInterestedMessage() { - BtInterestedMessageHandle msg = new BtInterestedMessage(); + BtInterestedMessageHandle msg(new BtInterestedMessage()); setCommonProperty(msg); return msg; } @@ -317,7 +324,7 @@ DefaultBtMessageFactory::createInterestedMessage() BtMessageHandle DefaultBtMessageFactory::createNotInterestedMessage() { - BtNotInterestedMessageHandle msg = new BtNotInterestedMessage(); + BtNotInterestedMessageHandle msg(new BtNotInterestedMessage()); setCommonProperty(msg); return msg; } @@ -325,11 +332,13 @@ DefaultBtMessageFactory::createNotInterestedMessage() BtMessageHandle DefaultBtMessageFactory::createBitfieldMessage() { - BtBitfieldMessageHandle msg = - new BtBitfieldMessage(pieceStorage->getBitfield(), - pieceStorage->getBitfieldLength()); - msg->setBtMessageValidator(new BtBitfieldMessageValidator(msg.get(), - btContext->getNumPieces())); + BtBitfieldMessageHandle msg + (new BtBitfieldMessage(pieceStorage->getBitfield(), + pieceStorage->getBitfieldLength())); + SharedHandle v + (new BtBitfieldMessageValidator(msg.get(), + btContext->getNumPieces())); + msg->setBtMessageValidator(v); setCommonProperty(msg); return msg; } @@ -337,7 +346,7 @@ DefaultBtMessageFactory::createBitfieldMessage() BtMessageHandle DefaultBtMessageFactory::createKeepAliveMessage() { - BtKeepAliveMessageHandle msg = new BtKeepAliveMessage(); + BtKeepAliveMessageHandle msg(new BtKeepAliveMessage()); setCommonProperty(msg); return msg; } @@ -345,7 +354,7 @@ DefaultBtMessageFactory::createKeepAliveMessage() BtMessageHandle DefaultBtMessageFactory::createHaveAllMessage() { - BtHaveAllMessageHandle msg = new BtHaveAllMessage(); + BtHaveAllMessageHandle msg(new BtHaveAllMessage()); setCommonProperty(msg); return msg; } @@ -353,7 +362,7 @@ DefaultBtMessageFactory::createHaveAllMessage() BtMessageHandle DefaultBtMessageFactory::createHaveNoneMessage() { - BtHaveNoneMessageHandle msg = new BtHaveNoneMessage(); + BtHaveNoneMessageHandle msg(new BtHaveNoneMessage()); setCommonProperty(msg); return msg; } @@ -361,11 +370,11 @@ DefaultBtMessageFactory::createHaveNoneMessage() BtMessageHandle DefaultBtMessageFactory::createRejectMessage(size_t index, uint32_t begin, size_t length) { - BtRejectMessageHandle msg = new BtRejectMessage(index, begin, length); - BtMessageValidatorHandle validator = - new BtRejectMessageValidator(msg.get(), - btContext->getNumPieces(), - pieceStorage->getPieceLength(index)); + BtRejectMessageHandle msg(new BtRejectMessage(index, begin, length)); + BtMessageValidatorHandle validator + (new BtRejectMessageValidator(msg.get(), + btContext->getNumPieces(), + pieceStorage->getPieceLength(index))); msg->setBtMessageValidator(validator); setCommonProperty(msg); return msg; @@ -374,10 +383,10 @@ DefaultBtMessageFactory::createRejectMessage(size_t index, uint32_t begin, size_ BtMessageHandle DefaultBtMessageFactory::createAllowedFastMessage(size_t index) { - BtAllowedFastMessageHandle msg = new BtAllowedFastMessage(index); - BtMessageValidatorHandle validator = - new BtAllowedFastMessageValidator(msg.get(), - btContext->getNumPieces()); + BtAllowedFastMessageHandle msg(new BtAllowedFastMessage(index)); + BtMessageValidatorHandle validator + (new BtAllowedFastMessageValidator(msg.get(), + btContext->getNumPieces())); msg->setBtMessageValidator(validator); setCommonProperty(msg); return msg; @@ -386,7 +395,7 @@ DefaultBtMessageFactory::createAllowedFastMessage(size_t index) BtMessageHandle DefaultBtMessageFactory::createPortMessage(uint16_t port) { - SharedHandle msg = new BtPortMessage(port); + SharedHandle msg(new BtPortMessage(port)); setCommonProperty(msg); return msg; } @@ -394,7 +403,7 @@ DefaultBtMessageFactory::createPortMessage(uint16_t port) BtMessageHandle DefaultBtMessageFactory::createBtExtendedMessage(const ExtensionMessageHandle& msg) { - BtExtendedMessageHandle m = new BtExtendedMessage(msg); + BtExtendedMessageHandle m(new BtExtendedMessage(msg)); setCommonProperty(m); return m; } diff --git a/src/DefaultBtMessageFactory.h b/src/DefaultBtMessageFactory.h index 657319e7..d0de2dd4 100644 --- a/src/DefaultBtMessageFactory.h +++ b/src/DefaultBtMessageFactory.h @@ -83,10 +83,10 @@ public: virtual SharedHandle createBtMessage(const unsigned char* msg, size_t msgLength); - virtual SharedHandle + virtual SharedHandle createHandshakeMessage(const unsigned char* msg, size_t msgLength); - virtual SharedHandle + virtual SharedHandle createHandshakeMessage(const unsigned char* infoHash, const unsigned char* peerId); diff --git a/src/DefaultBtMessageReceiver.cc b/src/DefaultBtMessageReceiver.cc index 9dd65507..973beaf3 100644 --- a/src/DefaultBtMessageReceiver.cc +++ b/src/DefaultBtMessageReceiver.cc @@ -50,10 +50,6 @@ namespace aria2 { DefaultBtMessageReceiver::DefaultBtMessageReceiver(): cuid(0), handshakeSent(false), - btContext(0), - peer(0), - peerConnection(0), - dispatcher(0), logger(LogFactory::getInstance()) { logger->debug("DefaultBtMessageReceiver::instantiated"); @@ -64,7 +60,9 @@ DefaultBtMessageReceiver::~DefaultBtMessageReceiver() logger->debug("DefaultBtMessageReceiver::deleted"); } -BtMessageHandle DefaultBtMessageReceiver::receiveHandshake(bool quickReply) { +SharedHandle +DefaultBtMessageReceiver::receiveHandshake(bool quickReply) +{ unsigned char data[BtHandshakeMessage::MESSAGE_LENGTH]; size_t dataLength = BtHandshakeMessage::MESSAGE_LENGTH; bool retval = peerConnection->receiveHandshake(data, dataLength); @@ -77,7 +75,7 @@ BtMessageHandle DefaultBtMessageReceiver::receiveHandshake(bool quickReply) { } } if(!retval) { - return 0; + return SharedHandle(); } SharedHandle msg = messageFactory->createHandshakeMessage(data, dataLength); std::deque errors; @@ -85,12 +83,14 @@ BtMessageHandle DefaultBtMessageReceiver::receiveHandshake(bool quickReply) { return msg; } -BtMessageHandle DefaultBtMessageReceiver::receiveAndSendHandshake() { +SharedHandle +DefaultBtMessageReceiver::receiveAndSendHandshake() +{ return receiveHandshake(true); } void DefaultBtMessageReceiver::sendHandshake() { - SharedHandle msg = + SharedHandle msg = messageFactory->createHandshakeMessage(btContext->getInfoHash(), btContext->getPeerId()); dispatcher->addMessageToQueue(msg); @@ -101,7 +101,7 @@ BtMessageHandle DefaultBtMessageReceiver::receiveMessage() { unsigned char data[MAX_PAYLOAD_LEN]; size_t dataLength = 0; if(!peerConnection->receiveMessage(data, dataLength)) { - return 0; + return SharedHandle(); } BtMessageHandle msg = messageFactory->createBtMessage(data, dataLength); std::deque errors; @@ -109,7 +109,7 @@ BtMessageHandle DefaultBtMessageReceiver::receiveMessage() { return msg; } else { // TODO throw exception here based on errors; - return 0; + return SharedHandle(); } } diff --git a/src/DefaultBtMessageReceiver.h b/src/DefaultBtMessageReceiver.h index 040062be..6bbcc4ee 100644 --- a/src/DefaultBtMessageReceiver.h +++ b/src/DefaultBtMessageReceiver.h @@ -63,9 +63,9 @@ public: virtual ~DefaultBtMessageReceiver(); - virtual SharedHandle receiveHandshake(bool quickReply = false); + virtual SharedHandle receiveHandshake(bool quickReply = false); - virtual SharedHandle receiveAndSendHandshake(); + virtual SharedHandle receiveAndSendHandshake(); virtual SharedHandle receiveMessage(); diff --git a/src/DefaultBtProgressInfoFile.cc b/src/DefaultBtProgressInfoFile.cc index d5c3c939..2e262449 100644 --- a/src/DefaultBtProgressInfoFile.cc +++ b/src/DefaultBtProgressInfoFile.cc @@ -72,7 +72,7 @@ DefaultBtProgressInfoFile::~DefaultBtProgressInfoFile() {} bool DefaultBtProgressInfoFile::isTorrentDownload() { - return !BtContextHandle(_dctx).isNull(); + return !dynamic_pointer_cast(_dctx).isNull(); } void DefaultBtProgressInfoFile::save() { @@ -98,7 +98,7 @@ void DefaultBtProgressInfoFile::save() { if(torrentDownload) { // infoHashLength: // length: 32 bits - BtContextHandle btContext = _dctx; + BtContextHandle btContext(dynamic_pointer_cast(_dctx)); uint32_t infoHashLength = btContext->getInfoHashLength(); o.write(reinterpret_cast(&infoHashLength), sizeof(infoHashLength)); // infoHash: @@ -119,7 +119,7 @@ void DefaultBtProgressInfoFile::save() { // uploadLength: 64 bits uint64_t uploadLength = 0; if(torrentDownload) { - BtContextHandle btContext = _dctx; + BtContextHandle btContext(dynamic_pointer_cast(_dctx)); TransferStat stat = PEER_STORAGE(btContext)->calculateStat(); uploadLength = stat.getAllTimeUploadLength(); } @@ -189,7 +189,7 @@ void DefaultBtProgressInfoFile::load() if(infoHashLength > 0) { savedInfoHash = new unsigned char[infoHashLength]; in.read(reinterpret_cast(savedInfoHash), infoHashLength); - BtContextHandle btContext = _dctx; + BtContextHandle btContext(dynamic_pointer_cast(_dctx)); if(infoHashCheckEnabled && Util::toHex(savedInfoHash, infoHashLength) != btContext->getInfoHashAsString()) { throw new DlAbortEx("info hash mismatch. expected: %s, actual: %s", @@ -213,7 +213,7 @@ void DefaultBtProgressInfoFile::load() uint64_t uploadLength; in.read(reinterpret_cast(&uploadLength), sizeof(uploadLength)); if(isTorrentDownload()) { - BT_RUNTIME(BtContextHandle(_dctx))->setUploadLengthAtStartup(uploadLength); + BT_RUNTIME(dynamic_pointer_cast(_dctx))->setUploadLengthAtStartup(uploadLength); } // TODO implement the conversion mechanism between different piece length. @@ -249,7 +249,7 @@ void DefaultBtProgressInfoFile::load() if(!(length <=_dctx->getPieceLength())) { throw new DlAbortEx("piece length out of range: %u", length); } - PieceHandle piece = new Piece(index, length); + PieceHandle piece(new Piece(index, length)); uint32_t bitfieldLength; in.read(reinterpret_cast(&bitfieldLength), sizeof(bitfieldLength)); if(piece->getBitfieldLength() != bitfieldLength) { diff --git a/src/DefaultBtRequestFactory.cc b/src/DefaultBtRequestFactory.cc index 34c49c50..74825494 100644 --- a/src/DefaultBtRequestFactory.cc +++ b/src/DefaultBtRequestFactory.cc @@ -48,11 +48,7 @@ namespace aria2 { DefaultBtRequestFactory::DefaultBtRequestFactory(): - cuid(0), - btContext(0), - pieceStorage(0), - peer(0), - dispatcher(0) + cuid(0) { LogFactory::getInstance()->debug("DefaultBtRequestFactory::instantiated"); } diff --git a/src/DefaultDiskWriterFactory.cc b/src/DefaultDiskWriterFactory.cc index ed6bb1da..235e5d89 100644 --- a/src/DefaultDiskWriterFactory.cc +++ b/src/DefaultDiskWriterFactory.cc @@ -39,7 +39,7 @@ namespace aria2 { SharedHandle DefaultDiskWriterFactory::newDiskWriter() { - return new DefaultDiskWriter(); + return SharedHandle(new DefaultDiskWriter()); } } // namespace aria2 diff --git a/src/DefaultExtensionMessageFactory.cc b/src/DefaultExtensionMessageFactory.cc index 51bea129..4b580fb4 100644 --- a/src/DefaultExtensionMessageFactory.cc +++ b/src/DefaultExtensionMessageFactory.cc @@ -45,8 +45,6 @@ namespace aria2 { DefaultExtensionMessageFactory::DefaultExtensionMessageFactory(): - _btContext(0), - _peer(0), _logger(LogFactory::getInstance()) {} DefaultExtensionMessageFactory::DefaultExtensionMessageFactory(const BtContextHandle& btContext, diff --git a/src/DefaultPeerListProcessor.cc b/src/DefaultPeerListProcessor.cc index 9446505d..7f46e975 100644 --- a/src/DefaultPeerListProcessor.cc +++ b/src/DefaultPeerListProcessor.cc @@ -67,7 +67,7 @@ Peers DefaultPeerListProcessor::extractPeer(const MetaEntry* peersEntry) { if(!ip || !port || !port->isNumber()) { continue; } - PeerHandle peer = new Peer(ip->toString(), port->toInt()); + PeerHandle peer(new Peer(ip->toString(), port->toInt())); peers.push_back(peer); } return peers; diff --git a/src/DefaultPeerStorage.cc b/src/DefaultPeerStorage.cc index 63d21c72..c2a2efc5 100644 --- a/src/DefaultPeerStorage.cc +++ b/src/DefaultPeerStorage.cc @@ -123,7 +123,7 @@ PeerHandle DefaultPeerStorage::getUnusedPeer() { Peers::const_iterator itr = std::find_if(peers.begin(), peers.end(), FindFinePeer()); if(itr == peers.end()) { - return 0; + return SharedHandle(); } else { return *itr; } @@ -146,7 +146,7 @@ PeerHandle DefaultPeerStorage::getPeer(const std::string& ipaddr, Peers::const_iterator itr = std::find_if(peers.begin(), peers.end(), FindPeer(ipaddr, port)); if(itr == peers.end()) { - return 0; + return SharedHandle(); } else { return *itr; } diff --git a/src/DefaultPieceStorage.cc b/src/DefaultPieceStorage.cc index 3a0a6459..db8a0e42 100644 --- a/src/DefaultPieceStorage.cc +++ b/src/DefaultPieceStorage.cc @@ -59,7 +59,6 @@ namespace aria2 { DefaultPieceStorage::DefaultPieceStorage(const DownloadContextHandle& downloadContext, const Option* option): downloadContext(downloadContext), - diskAdaptor(0), _diskWriterFactory(new DefaultDiskWriterFactory()), endGamePieceNum(END_GAME_PIECE_NUM), option(option) @@ -103,7 +102,7 @@ PieceHandle DefaultPieceStorage::checkOutPiece(size_t index) PieceHandle piece = findUsedPiece(index); if(piece.isNull()) { - piece = new Piece(index, bitfieldMan->getBlockLength(index)); + piece.reset(new Piece(index, bitfieldMan->getBlockLength(index))); addUsedPiece(piece); return piece; } else { @@ -117,18 +116,17 @@ PieceHandle DefaultPieceStorage::checkOutPiece(size_t index) */ PieceHandle DefaultPieceStorage::getPiece(size_t index) { + PieceHandle piece; if(0 <= index && index <= bitfieldMan->getMaxIndex()) { - PieceHandle piece = findUsedPiece(index); + piece = findUsedPiece(index); if(piece.isNull()) { - piece = new Piece(index, bitfieldMan->getBlockLength(index)); + piece.reset(new Piece(index, bitfieldMan->getBlockLength(index))); if(hasPiece(index)) { piece->setAllBlock(); } } - return piece; - } else { - return 0; } + return piece; } void DefaultPieceStorage::addUsedPiece(const PieceHandle& piece) @@ -153,7 +151,7 @@ PieceHandle DefaultPieceStorage::findUsedPiece(size_t index) const usedPieces.end(), FindPiece(index)); if(itr == usedPieces.end()) { - return 0; + return SharedHandle(); } else { return *itr; } @@ -165,7 +163,7 @@ PieceHandle DefaultPieceStorage::getMissingPiece(const PeerHandle& peer) if(getMissingPieceIndex(index, peer)) { return checkOutPiece(index); } else { - return 0; + return SharedHandle(); } } @@ -199,7 +197,7 @@ PieceHandle DefaultPieceStorage::getMissingFastPiece(const PeerHandle& peer) if(getMissingFastPieceIndex(index, peer)) { return checkOutPiece(index); } else { - return 0; + return SharedHandle(); } } @@ -209,14 +207,14 @@ PieceHandle DefaultPieceStorage::getMissingPiece() if(bitfieldMan->getSparseMissingUnusedIndex(index)) { return checkOutPiece(index); } else { - return 0; + return SharedHandle(); } } PieceHandle DefaultPieceStorage::getMissingPiece(size_t index) { if(hasPiece(index) || isPieceUsed(index)) { - return 0; + return SharedHandle(); } else { return checkOutPiece(index); } @@ -421,7 +419,7 @@ void DefaultPieceStorage::initStorage() logger->debug("Instantiating DirectDiskAdaptor"); DiskWriterHandle writer = _diskWriterFactory->newDiskWriter(); writer->setDirectIOAllowed(option->getAsBool(PREF_ENABLE_DIRECT_IO)); - DirectDiskAdaptorHandle directDiskAdaptor = new DirectDiskAdaptor(); + DirectDiskAdaptorHandle directDiskAdaptor(new DirectDiskAdaptor()); directDiskAdaptor->setDiskWriter(writer); directDiskAdaptor->setTotalLength(downloadContext->getTotalLength()); this->diskAdaptor = directDiskAdaptor; @@ -429,7 +427,7 @@ void DefaultPieceStorage::initStorage() // file mode == DownloadContext::MULTI if(option->get(PREF_DIRECT_FILE_MAPPING) == V_TRUE) { logger->debug("Instantiating MultiDiskAdaptor"); - MultiDiskAdaptorHandle multiDiskAdaptor = new MultiDiskAdaptor(); + MultiDiskAdaptorHandle multiDiskAdaptor(new MultiDiskAdaptor()); multiDiskAdaptor->setDirectIOAllowed(option->getAsBool(PREF_ENABLE_DIRECT_IO)); multiDiskAdaptor->setPieceLength(downloadContext->getPieceLength()); multiDiskAdaptor->setTopDir(downloadContext->getName()); @@ -438,7 +436,7 @@ void DefaultPieceStorage::initStorage() logger->debug("Instantiating CopyDiskAdaptor"); DiskWriterHandle writer = _diskWriterFactory->newDiskWriter(); writer->setDirectIOAllowed(option->getAsBool(PREF_ENABLE_DIRECT_IO)); - CopyDiskAdaptorHandle copyDiskAdaptor = new CopyDiskAdaptor(); + CopyDiskAdaptorHandle copyDiskAdaptor(new CopyDiskAdaptor()); copyDiskAdaptor->setDiskWriter(writer); copyDiskAdaptor->setTempFilename(downloadContext->getName()+".a2tmp"); copyDiskAdaptor->setTotalLength(downloadContext->getTotalLength()); @@ -543,7 +541,7 @@ void DefaultPieceStorage::markPiecesDone(uint64_t length) } size_t r = (length%bitfieldMan->getBlockLength())/Piece::BLOCK_LENGTH; if(r > 0) { - PieceHandle p = new Piece(numPiece, bitfieldMan->getBlockLength(numPiece)); + PieceHandle p(new Piece(numPiece, bitfieldMan->getBlockLength(numPiece))); for(size_t i = 0; i < r; ++i) { p->completeBlock(i); } diff --git a/src/DefaultSegmentManFactory.cc b/src/DefaultSegmentManFactory.cc index a9bb6df2..5ed7edef 100644 --- a/src/DefaultSegmentManFactory.cc +++ b/src/DefaultSegmentManFactory.cc @@ -45,12 +45,7 @@ SegmentManHandle DefaultSegmentManFactory::createNewInstance(const DownloadContextHandle& dctx, const PieceStorageHandle& ps) { - SegmentManHandle segmentMan = new SegmentMan(_option, dctx, ps); - //segmentMan->diskWriter = new DefaultDiskWriter(); - //segmentMan->dir = _option->get(PREF_DIR); - // TODO disable this in multi-simultaneous download mode. - //segmentMan->ufilename = _option->get(PREF_OUT); - //segmentMan->option = _option; + SegmentManHandle segmentMan(new SegmentMan(_option, dctx, ps)); return segmentMan; } diff --git a/src/DelegatingPeerListProcessor.cc b/src/DelegatingPeerListProcessor.cc index c725c8d1..3d85b820 100644 --- a/src/DelegatingPeerListProcessor.cc +++ b/src/DelegatingPeerListProcessor.cc @@ -41,8 +41,14 @@ namespace aria2 { DelegatingPeerListProcessor::DelegatingPeerListProcessor() { - processors.push_back(new DefaultPeerListProcessor()); - processors.push_back(new CompactPeerListProcessor()); + { + SharedHandle proc(new DefaultPeerListProcessor); + processors.push_back(proc); + } + { + SharedHandle proc(new CompactPeerListProcessor); + processors.push_back(proc); + } } DelegatingPeerListProcessor::~DelegatingPeerListProcessor() {} diff --git a/src/DownloadCommand.cc b/src/DownloadCommand.cc index 3e052266..4f86c30f 100644 --- a/src/DownloadCommand.cc +++ b/src/DownloadCommand.cc @@ -67,11 +67,9 @@ DownloadCommand::DownloadCommand(int cuid, DownloadEngine* e, const SocketHandle& s): AbstractCommand(cuid, req, requestGroup, e, s), - peerStat(0), #ifdef ENABLE_MESSAGE_DIGEST - _messageDigestContext(0), + _messageDigestContext(0) #endif // ENABLE_MESSAGE_DIGEST - transferDecoder(0) { #ifdef ENABLE_MESSAGE_DIGEST { @@ -85,7 +83,7 @@ DownloadCommand::DownloadCommand(int cuid, #endif // ENABLE_MESSAGE_DIGEST peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid); if(peerStat.isNull()) { - peerStat = new PeerStat(cuid); + peerStat.reset(new PeerStat(cuid)); _requestGroup->getSegmentMan()->registerPeerStat(peerStat); } peerStat->downloadStart(); @@ -175,7 +173,7 @@ void DownloadCommand::checkLowestDownloadSpeed() const bool DownloadCommand::prepareForNextSegment() { if(_requestGroup->downloadFinished()) { #ifdef ENABLE_MESSAGE_DIGEST - CheckIntegrityEntryHandle entry = new ChecksumCheckIntegrityEntry(_requestGroup); + CheckIntegrityEntryHandle entry(new ChecksumCheckIntegrityEntry(_requestGroup)); if(entry->isValidationReady()) { entry->initValidator(); CheckIntegrityCommand* command = diff --git a/src/DownloadEngine.cc b/src/DownloadEngine.cc index 5d6bda08..85ece318 100644 --- a/src/DownloadEngine.cc +++ b/src/DownloadEngine.cc @@ -84,12 +84,8 @@ bool NameResolverEntry::operator==(const NameResolverEntry& entry) #endif // ENABLE_ASYNC_DNS DownloadEngine::DownloadEngine():logger(LogFactory::getInstance()), - _statCalc(0), _haltRequested(false), - noWait(false), - _requestGroupMan(0), - _fileAllocationMan(0), - _checkIntegrityMan(0) + noWait(false) {} DownloadEngine::~DownloadEngine() { diff --git a/src/DownloadEngineFactory.cc b/src/DownloadEngineFactory.cc index 0c44c9ed..39875e90 100644 --- a/src/DownloadEngineFactory.cc +++ b/src/DownloadEngineFactory.cc @@ -72,16 +72,16 @@ DownloadEngineFactory::newDownloadEngine(Option* op, workingSet = requestGroups; } - DownloadEngineHandle e = new DownloadEngine(); + DownloadEngineHandle e(new DownloadEngine()); e->option = op; - RequestGroupManHandle requestGroupMan = - new RequestGroupMan(workingSet, - op->getAsInt(PREF_MAX_CONCURRENT_DOWNLOADS)); + RequestGroupManHandle + requestGroupMan(new RequestGroupMan(workingSet, + op->getAsInt(PREF_MAX_CONCURRENT_DOWNLOADS))); requestGroupMan->addReservedGroup(reservedSet); e->_requestGroupMan = requestGroupMan; - e->_fileAllocationMan = new FileAllocationMan(); + e->_fileAllocationMan.reset(new FileAllocationMan()); #ifdef ENABLE_MESSAGE_DIGEST - e->_checkIntegrityMan = new CheckIntegrityMan(); + e->_checkIntegrityMan.reset(new CheckIntegrityMan()); #endif // ENABLE_MESSAGE_DIGEST e->commands.push_back(new FillRequestGroupCommand(CUIDCounterSingletonHolder::instance()->newID(), e.get(), 1)); e->commands.push_back(new FileAllocationDispatcherCommand(CUIDCounterSingletonHolder::instance()->newID(), e.get())); diff --git a/src/DownloadHandler.cc b/src/DownloadHandler.cc index 22048a71..93b901d4 100644 --- a/src/DownloadHandler.cc +++ b/src/DownloadHandler.cc @@ -40,9 +40,7 @@ namespace aria2 { -DownloadHandler::DownloadHandler(): - _criteria(0), - _logger(LogFactory::getInstance()) {} +DownloadHandler::DownloadHandler():_logger(LogFactory::getInstance()) {} DownloadHandler::~DownloadHandler() {} diff --git a/src/DownloadHandlerFactory.cc b/src/DownloadHandlerFactory.cc index c54af0b0..8be13559 100644 --- a/src/DownloadHandlerFactory.cc +++ b/src/DownloadHandlerFactory.cc @@ -44,20 +44,20 @@ namespace aria2 { #ifdef ENABLE_METALINK MemoryBufferPreDownloadHandlerHandle -DownloadHandlerFactory::_metalinkPreDownloadHandler = 0; +DownloadHandlerFactory::_metalinkPreDownloadHandler; MetalinkPostDownloadHandlerHandle -DownloadHandlerFactory::_metalinkPostDownloadHandler = 0; +DownloadHandlerFactory::_metalinkPostDownloadHandler; #endif // ENABLE_METALINK #ifdef ENABLE_BITTORRENT MemoryBufferPreDownloadHandlerHandle -DownloadHandlerFactory::_btPreDownloadHandler = 0; +DownloadHandlerFactory::_btPreDownloadHandler; BtPostDownloadHandlerHandle -DownloadHandlerFactory::_btPostDownloadHandler = 0; +DownloadHandlerFactory::_btPostDownloadHandler; #endif // ENABLE_BITTORRENT @@ -67,11 +67,11 @@ MemoryBufferPreDownloadHandlerHandle DownloadHandlerFactory::getMetalinkPreDownloadHandler() { if(_metalinkPreDownloadHandler.isNull()) { - _metalinkPreDownloadHandler = new MemoryBufferPreDownloadHandler(); + _metalinkPreDownloadHandler.reset(new MemoryBufferPreDownloadHandler()); - RequestGroupCriteriaHandle criteria = - new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getMetalinkContentTypes(), - DownloadHandlerConstants::getMetalinkExtensions()); + RequestGroupCriteriaHandle criteria + (new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getMetalinkContentTypes(), + DownloadHandlerConstants::getMetalinkExtensions())); _metalinkPreDownloadHandler->setCriteria(criteria); } return _metalinkPreDownloadHandler; @@ -81,7 +81,7 @@ MetalinkPostDownloadHandlerHandle DownloadHandlerFactory::getMetalinkPostDownloadHandler() { if(_metalinkPostDownloadHandler.isNull()) { - _metalinkPostDownloadHandler = new MetalinkPostDownloadHandler(); + _metalinkPostDownloadHandler.reset(new MetalinkPostDownloadHandler()); } return _metalinkPostDownloadHandler; } @@ -94,11 +94,11 @@ MemoryBufferPreDownloadHandlerHandle DownloadHandlerFactory::getBtPreDownloadHandler() { if(_btPreDownloadHandler.isNull()) { - _btPreDownloadHandler = new MemoryBufferPreDownloadHandler(); + _btPreDownloadHandler.reset(new MemoryBufferPreDownloadHandler()); - RequestGroupCriteriaHandle criteria = - new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getBtContentTypes(), - DownloadHandlerConstants::getBtExtensions()); + RequestGroupCriteriaHandle criteria + (new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getBtContentTypes(), + DownloadHandlerConstants::getBtExtensions())); _btPreDownloadHandler->setCriteria(criteria); } return _btPreDownloadHandler; @@ -107,7 +107,7 @@ DownloadHandlerFactory::getBtPreDownloadHandler() BtPostDownloadHandlerHandle DownloadHandlerFactory::getBtPostDownloadHandler() { if(_btPostDownloadHandler.isNull()) { - _btPostDownloadHandler = new BtPostDownloadHandler(); + _btPostDownloadHandler.reset(new BtPostDownloadHandler()); } return _btPostDownloadHandler; } diff --git a/src/ExpatMetalinkProcessor.cc b/src/ExpatMetalinkProcessor.cc index eb3ade4d..36a6026a 100644 --- a/src/ExpatMetalinkProcessor.cc +++ b/src/ExpatMetalinkProcessor.cc @@ -83,10 +83,7 @@ static void mlCharacters(void* userData, const char* ch, int len) ((SessionData*)userData)->_charactersStack.front() += std::string(&ch[0], &ch[len]); } -ExpatMetalinkProcessor::ExpatMetalinkProcessor(): - _stm(0) -{} - +ExpatMetalinkProcessor::ExpatMetalinkProcessor() {} SharedHandle ExpatMetalinkProcessor::parseFile(const std::string& filename) diff --git a/src/FileAllocationMan.cc b/src/FileAllocationMan.cc index b62f0164..478f2afb 100644 --- a/src/FileAllocationMan.cc +++ b/src/FileAllocationMan.cc @@ -37,7 +37,7 @@ namespace aria2 { -FileAllocationMan::FileAllocationMan():_currentFileAllocationEntry(0) {} +FileAllocationMan::FileAllocationMan() {} FileAllocationMan::~FileAllocationMan() {} @@ -53,7 +53,7 @@ FileAllocationEntryHandle FileAllocationMan::getCurrentFileAllocationEntry() void FileAllocationMan::markCurrentFileAllocationEntryDone() { - _currentFileAllocationEntry = 0; + _currentFileAllocationEntry.reset(); } bool FileAllocationMan::nextFileAllocationEntryExists() const @@ -64,7 +64,7 @@ bool FileAllocationMan::nextFileAllocationEntryExists() const FileAllocationEntryHandle FileAllocationMan::popNextFileAllocationEntry() { if(!nextFileAllocationEntryExists()) { - return 0; + return SharedHandle(); } FileAllocationEntryHandle entry = _fileAllocationEntries.front(); _fileAllocationEntries.pop_front(); diff --git a/src/FtpConnection.cc b/src/FtpConnection.cc index 7875614c..91e0671b 100644 --- a/src/FtpConnection.cc +++ b/src/FtpConnection.cc @@ -106,7 +106,7 @@ void FtpConnection::sendPasv() const SocketHandle FtpConnection::sendPort() const { - SocketHandle serverSocket; + SocketHandle serverSocket(new SocketCore()); serverSocket->bind(0); serverSocket->beginListen(); serverSocket->setNonBlockingMode(); diff --git a/src/FtpInitiateConnectionCommand.cc b/src/FtpInitiateConnectionCommand.cc index 1695a81b..54ae0a9c 100644 --- a/src/FtpInitiateConnectionCommand.cc +++ b/src/FtpInitiateConnectionCommand.cc @@ -57,7 +57,8 @@ FtpInitiateConnectionCommand::FtpInitiateConnectionCommand(int cuid, const RequestHandle& req, RequestGroup* requestGroup, DownloadEngine* e) - :AbstractCommand(cuid, req, requestGroup, e) + :AbstractCommand(cuid, req, requestGroup, e), + nameResolver(new NameResolver()) { setTimeout(e->option->getAsInt(PREF_DNS_TIMEOUT)); setStatusActive(); @@ -95,7 +96,8 @@ bool FtpInitiateConnectionCommand::executeInternal() { e->option->getAsInt(PREF_HTTP_PROXY_PORT)); if(useHttpProxyGet()) { - command = new HttpRequestCommand(cuid, req, _requestGroup, new HttpConnection(cuid, socket, e->option), e, socket); + SharedHandle hc(new HttpConnection(cuid, socket, e->option)); + command = new HttpRequestCommand(cuid, req, _requestGroup, hc, e, socket); } else if(useHttpProxyConnect()) { command = new FtpTunnelRequestCommand(cuid, req, _requestGroup, e, socket); } else { diff --git a/src/FtpNegotiationCommand.cc b/src/FtpNegotiationCommand.cc index db77598d..223cdf68 100644 --- a/src/FtpNegotiationCommand.cc +++ b/src/FtpNegotiationCommand.cc @@ -218,7 +218,8 @@ bool FtpNegotiationCommand::recvSize() { throw new DlAbortEx(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()); } if(_requestGroup->getPieceStorage().isNull()) { - SingleFileDownloadContextHandle dctx = _requestGroup->getDownloadContext(); + SingleFileDownloadContextHandle dctx = + dynamic_pointer_cast(_requestGroup->getDownloadContext()); dctx->setTotalLength(size); dctx->setFilename(Util::urldecode(req->getFile())); _requestGroup->preDownloadProcessing(); @@ -235,7 +236,7 @@ bool FtpNegotiationCommand::recvSize() { return false; } - BtProgressInfoFileHandle infoFile = new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option); + BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option)); if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) { sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED; return false; @@ -305,6 +306,7 @@ bool FtpNegotiationCommand::recvPasv() { logger->info(MSG_CONNECTING_TO_SERVER, cuid, dest.first.c_str(), dest.second); + dataSocket.reset(new SocketCore()); dataSocket->establishConnection(dest.first, dest.second); disableReadCheckSocket(); @@ -369,7 +371,7 @@ bool FtpNegotiationCommand::waitConnection() { disableReadCheckSocket(); setReadCheckSocket(socket); - dataSocket = serverSocket->acceptConnection(); + dataSocket.reset(serverSocket->acceptConnection()); dataSocket->setBlockingMode(); sequence = SEQ_NEGOTIATION_COMPLETED; return false; diff --git a/src/HandleRegistry.h b/src/HandleRegistry.h index 26ddacb3..5d841381 100644 --- a/src/HandleRegistry.h +++ b/src/HandleRegistry.h @@ -61,7 +61,7 @@ public: SharedHandle getHandle(const K& key) { typename HandleMap::const_iterator itr = handleMap.find(key); if(itr == handleMap.end()) { - return 0; + return SharedHandle(); } else { return itr->second; } diff --git a/src/HandshakeExtensionMessage.cc b/src/HandshakeExtensionMessage.cc index e6ac2ad5..022b93e6 100644 --- a/src/HandshakeExtensionMessage.cc +++ b/src/HandshakeExtensionMessage.cc @@ -49,17 +49,15 @@ namespace aria2 { const std::string HandshakeExtensionMessage::EXTENSION_NAME = "handshake"; -HandshakeExtensionMessage::HandshakeExtensionMessage():_tcpPort(0), - _btContext(0), - _peer(0), - _logger(LogFactory::getInstance()) -{} +HandshakeExtensionMessage::HandshakeExtensionMessage(): + _tcpPort(0), + _logger(LogFactory::getInstance()) {} HandshakeExtensionMessage::~HandshakeExtensionMessage() {} std::string HandshakeExtensionMessage::getBencodedData() { - SharedHandle dic = new Dictionary(); + SharedHandle dic(new Dictionary()); if(!_clientVersion.empty()) { Data* v = new Data(_clientVersion); dic->put("v", v); @@ -138,10 +136,10 @@ HandshakeExtensionMessage::create(const unsigned char* data, size_t length) throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE, EXTENSION_NAME.c_str(), length); } - HandshakeExtensionMessageHandle msg = new HandshakeExtensionMessage(); + HandshakeExtensionMessageHandle msg(new HandshakeExtensionMessage()); msg->_logger->debug("Creating HandshakeExtensionMessage from %s", Util::urlencode(data, length).c_str()); - SharedHandle root = MetaFileUtil::bdecoding(data+1, length-1); + SharedHandle root(MetaFileUtil::bdecoding(data+1, length-1)); Dictionary* d = dynamic_cast(root.get()); if(d == 0) { throw new DlAbortEx("Unexpected payload format for extended message handshake"); diff --git a/src/HelpItem.cc b/src/HelpItem.cc index b32c5f09..d1a91817 100644 --- a/src/HelpItem.cc +++ b/src/HelpItem.cc @@ -33,7 +33,6 @@ */ /* copyright --> */ #include "HelpItem.h" -#include namespace aria2 { @@ -41,23 +40,22 @@ namespace aria2 { #define TAGS_MSG _(" Tags: ") #define AVAILABLE_MSG _(" Available Values: ") -std::ostream& operator<<(std::ostream& o, const HelpItem& helpItem) +std::string HelpItem::toString() const { - o << helpItem._usageText << "\n"; - if(!helpItem._availableValues.empty()) { - o << AVAILABLE_MSG << helpItem._availableValues << "\n"; + std::string s(_usageText+"\n"); + if(!_availableValues.empty()) { + s += AVAILABLE_MSG; + s += _availableValues; + s += "\n"; } - if(!helpItem._defaultValue.empty()) { - o << DEFAULT_MSG << helpItem._defaultValue << "\n"; + if(!_defaultValue.empty()) { + s += DEFAULT_MSG; + s += _defaultValue; + s += "\n"; } - o << TAGS_MSG << helpItem.toTagString(); - return o; -} - -std::ostream& operator<<(std::ostream& o, const HelpItemHandle& helpItem) -{ - o << *helpItem.get(); - return o; + s += TAGS_MSG; + s += toTagString(); + return s; } } // namespace aria2 diff --git a/src/HelpItem.h b/src/HelpItem.h index 79d4c4b9..64fa1b01 100644 --- a/src/HelpItem.h +++ b/src/HelpItem.h @@ -65,11 +65,7 @@ public: return _availableValues; } - friend std::ostream& - operator<<(std::ostream& o, const HelpItem& helpItem); - - friend std::ostream& - operator<<(std::ostream& o, const SharedHandle& helpItem); + virtual std::string toString() const; }; typedef SharedHandle HelpItemHandle; diff --git a/src/HelpItemFactory.cc b/src/HelpItemFactory.cc index 014615ed..5025883f 100644 --- a/src/HelpItemFactory.cc +++ b/src/HelpItemFactory.cc @@ -46,14 +46,14 @@ HelpItemFactory::HelpItemFactory() {} TagContainerHandle HelpItemFactory::createHelpItems() { - TagContainerHandle tc = new TagContainer(); + TagContainerHandle tc(new TagContainer()); { - HelpItemHandle item = new HelpItem(PREF_DIR, TEXT_DIR); + HelpItemHandle item(new HelpItem(PREF_DIR, TEXT_DIR)); item->addTag(TAG_BASIC); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_OUT, TEXT_OUT); + HelpItemHandle item(new HelpItem(PREF_OUT, TEXT_OUT)); item->addTag(TAG_BASIC); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); @@ -61,227 +61,227 @@ TagContainerHandle HelpItemFactory::createHelpItems() } #ifdef HAVE_DAEMON { - HelpItemHandle item = new HelpItem(PREF_DAEMON, TEXT_DAEMON); + HelpItemHandle item(new HelpItem(PREF_DAEMON, TEXT_DAEMON)); item->addTag(TAG_ADVANCED); tc->addItem(item); } #endif // HAVE_DAEMON { - HelpItemHandle item = new HelpItem(PREF_SPLIT, TEXT_SPLIT); + HelpItemHandle item(new HelpItem(PREF_SPLIT, TEXT_SPLIT)); item->addTag(TAG_BASIC); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_RETRY_WAIT, TEXT_RETRY_WAIT); + HelpItemHandle item(new HelpItem(PREF_RETRY_WAIT, TEXT_RETRY_WAIT)); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_TIMEOUT, TEXT_TIMEOUT); + HelpItemHandle item(new HelpItem(PREF_TIMEOUT, TEXT_TIMEOUT)); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_MAX_TRIES, TEXT_MAX_TRIES); + HelpItemHandle item(new HelpItem(PREF_MAX_TRIES, TEXT_MAX_TRIES)); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_PROXY, TEXT_HTTP_PROXY); + HelpItemHandle item(new HelpItem(PREF_HTTP_PROXY, TEXT_HTTP_PROXY)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_USER, TEXT_HTTP_USER); + HelpItemHandle item(new HelpItem(PREF_HTTP_USER, TEXT_HTTP_USER)); item->addTag(TAG_BASIC); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_PASSWD, TEXT_HTTP_PASSWD); + HelpItemHandle item(new HelpItem(PREF_HTTP_PASSWD, TEXT_HTTP_PASSWD)); item->addTag(TAG_BASIC); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_PROXY_USER, TEXT_HTTP_PROXY_USER); + HelpItemHandle item(new HelpItem(PREF_HTTP_PROXY_USER, TEXT_HTTP_PROXY_USER)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_PROXY_PASSWD, TEXT_HTTP_PROXY_PASSWD); + HelpItemHandle item(new HelpItem(PREF_HTTP_PROXY_PASSWD, TEXT_HTTP_PROXY_PASSWD)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_PROXY_METHOD, TEXT_HTTP_PROXY_METHOD); + HelpItemHandle item(new HelpItem(PREF_HTTP_PROXY_METHOD, TEXT_HTTP_PROXY_METHOD)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_HTTP_AUTH_SCHEME, TEXT_HTTP_AUTH_SCHEME); + HelpItemHandle item(new HelpItem(PREF_HTTP_AUTH_SCHEME, TEXT_HTTP_AUTH_SCHEME)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_REFERER, TEXT_REFERER); + HelpItemHandle item(new HelpItem(PREF_REFERER, TEXT_REFERER)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FTP_USER, TEXT_FTP_USER); + HelpItemHandle item(new HelpItem(PREF_FTP_USER, TEXT_FTP_USER)); item->addTag(TAG_BASIC); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FTP_PASSWD, TEXT_FTP_PASSWD); + HelpItemHandle item(new HelpItem(PREF_FTP_PASSWD, TEXT_FTP_PASSWD)); item->addTag(TAG_BASIC); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FTP_TYPE, TEXT_FTP_TYPE); + HelpItemHandle item(new HelpItem(PREF_FTP_TYPE, TEXT_FTP_TYPE)); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FTP_PASV, TEXT_FTP_PASV); + HelpItemHandle item(new HelpItem(PREF_FTP_PASV, TEXT_FTP_PASV)); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FTP_VIA_HTTP_PROXY, TEXT_FTP_VIA_HTTP_PROXY); + HelpItemHandle item(new HelpItem(PREF_FTP_VIA_HTTP_PROXY, TEXT_FTP_VIA_HTTP_PROXY)); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_LOWEST_SPEED_LIMIT, TEXT_LOWEST_SPEED_LIMIT); + HelpItemHandle item(new HelpItem(PREF_LOWEST_SPEED_LIMIT, TEXT_LOWEST_SPEED_LIMIT)); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_MAX_DOWNLOAD_LIMIT, TEXT_MAX_DOWNLOAD_LIMIT); + HelpItemHandle item(new HelpItem(PREF_MAX_DOWNLOAD_LIMIT, TEXT_MAX_DOWNLOAD_LIMIT)); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FILE_ALLOCATION, TEXT_FILE_ALLOCATION); + HelpItemHandle item(new HelpItem(PREF_FILE_ALLOCATION, TEXT_FILE_ALLOCATION)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_NO_FILE_ALLOCATION_LIMIT, TEXT_NO_FILE_ALLOCATION_LIMIT, "5M"); + HelpItemHandle item(new HelpItem(PREF_NO_FILE_ALLOCATION_LIMIT, TEXT_NO_FILE_ALLOCATION_LIMIT, "5M")); item->addTag(TAG_ADVANCED); tc->addItem(item); } #ifdef ENABLE_DIRECT_IO { - HelpItemHandle item = new HelpItem(PREF_ENABLE_DIRECT_IO, TEXT_ENABLE_DIRECT_IO, V_TRUE); + HelpItemHandle item(new HelpItem(PREF_ENABLE_DIRECT_IO, TEXT_ENABLE_DIRECT_IO, V_TRUE)); item->addTag(TAG_ADVANCED); tc->addItem(item); } #endif // ENABLE_DIRECT_IO { - HelpItemHandle item = new HelpItem(PREF_ALLOW_OVERWRITE, TEXT_ALLOW_OVERWRITE); + HelpItemHandle item(new HelpItem(PREF_ALLOW_OVERWRITE, TEXT_ALLOW_OVERWRITE)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_ALLOW_PIECE_LENGTH_CHANGE, TEXT_ALLOW_PIECE_LENGTH_CHANGE, V_FALSE); + HelpItemHandle item(new HelpItem(PREF_ALLOW_PIECE_LENGTH_CHANGE, TEXT_ALLOW_PIECE_LENGTH_CHANGE, V_FALSE)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FORCE_SEQUENTIAL, TEXT_FORCE_SEQUENTIAL); + HelpItemHandle item(new HelpItem(PREF_FORCE_SEQUENTIAL, TEXT_FORCE_SEQUENTIAL)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_AUTO_FILE_RENAMING, TEXT_AUTO_FILE_RENAMING); + HelpItemHandle item(new HelpItem(PREF_AUTO_FILE_RENAMING, TEXT_AUTO_FILE_RENAMING)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_PARAMETERIZED_URI, TEXT_PARAMETERIZED_URI); + HelpItemHandle item(new HelpItem(PREF_PARAMETERIZED_URI, TEXT_PARAMETERIZED_URI)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_ENABLE_HTTP_KEEP_ALIVE, TEXT_ENABLE_HTTP_KEEP_ALIVE); + HelpItemHandle item(new HelpItem(PREF_ENABLE_HTTP_KEEP_ALIVE, TEXT_ENABLE_HTTP_KEEP_ALIVE)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_ENABLE_HTTP_PIPELINING, TEXT_ENABLE_HTTP_PIPELINING); + HelpItemHandle item(new HelpItem(PREF_ENABLE_HTTP_PIPELINING, TEXT_ENABLE_HTTP_PIPELINING)); item->addTag(TAG_HTTP); tc->addItem(item); } #ifdef ENABLE_MESSAGE_DIGEST { - HelpItemHandle item = new HelpItem(PREF_CHECK_INTEGRITY, TEXT_CHECK_INTEGRITY); + HelpItemHandle item(new HelpItem(PREF_CHECK_INTEGRITY, TEXT_CHECK_INTEGRITY)); item->addTag(TAG_BASIC); item->addTag(TAG_METALINK); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_REALTIME_CHUNK_CHECKSUM, TEXT_REALTIME_CHUNK_CHECKSUM); + HelpItemHandle item(new HelpItem(PREF_REALTIME_CHUNK_CHECKSUM, TEXT_REALTIME_CHUNK_CHECKSUM)); item->addTag(TAG_METALINK); tc->addItem(item); } #endif // ENABLE_MESSAGE_DIGEST { - HelpItemHandle item = new HelpItem(PREF_CONTINUE, TEXT_CONTINUE); + HelpItemHandle item(new HelpItem(PREF_CONTINUE, TEXT_CONTINUE)); item->addTag(TAG_BASIC); item->addTag(TAG_HTTP); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_USER_AGENT, TEXT_USER_AGENT); + HelpItemHandle item(new HelpItem(PREF_USER_AGENT, TEXT_USER_AGENT)); item->addTag(TAG_HTTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_NO_NETRC, TEXT_NO_NETRC); + HelpItemHandle item(new HelpItem(PREF_NO_NETRC, TEXT_NO_NETRC)); item->addTag(TAG_FTP); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_INPUT_FILE, TEXT_INPUT_FILE); + HelpItemHandle item(new HelpItem(PREF_INPUT_FILE, TEXT_INPUT_FILE)); item->addTag(TAG_BASIC); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_MAX_CONCURRENT_DOWNLOADS, TEXT_MAX_CONCURRENT_DOWNLOADS); + HelpItemHandle item(new HelpItem(PREF_MAX_CONCURRENT_DOWNLOADS, TEXT_MAX_CONCURRENT_DOWNLOADS)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_LOAD_COOKIES, TEXT_LOAD_COOKIES); + HelpItemHandle item(new HelpItem(PREF_LOAD_COOKIES, TEXT_LOAD_COOKIES)); item->addTag(TAG_BASIC); item->addTag(TAG_HTTP); tc->addItem(item); } #if defined ENABLE_BITTORRENT || ENABLE_METALINK { - HelpItemHandle item = new HelpItem(PREF_SHOW_FILES, TEXT_SHOW_FILES); + HelpItemHandle item(new HelpItem(PREF_SHOW_FILES, TEXT_SHOW_FILES)); item->addTag(TAG_BASIC); item->addTag(TAG_METALINK); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_SELECT_FILE, TEXT_SELECT_FILE); + HelpItemHandle item(new HelpItem(PREF_SELECT_FILE, TEXT_SELECT_FILE)); item->addTag(TAG_METALINK); item->addTag(TAG_BITTORRENT); tc->addItem(item); @@ -289,151 +289,151 @@ TagContainerHandle HelpItemFactory::createHelpItems() #endif // ENABLE_BITTORRENT || ENABLE_METALINK #ifdef ENABLE_BITTORRENT { - HelpItemHandle item = new HelpItem(PREF_TORRENT_FILE, TEXT_TORRENT_FILE); + HelpItemHandle item(new HelpItem(PREF_TORRENT_FILE, TEXT_TORRENT_FILE)); item->addTag(TAG_BASIC); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FOLLOW_TORRENT, TEXT_FOLLOW_TORRENT, V_TRUE); + HelpItemHandle item(new HelpItem(PREF_FOLLOW_TORRENT, TEXT_FOLLOW_TORRENT, V_TRUE)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_DIRECT_FILE_MAPPING, TEXT_DIRECT_FILE_MAPPING); + HelpItemHandle item(new HelpItem(PREF_DIRECT_FILE_MAPPING, TEXT_DIRECT_FILE_MAPPING)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_LISTEN_PORT, TEXT_LISTEN_PORT, "6881-6999"); + HelpItemHandle item(new HelpItem(PREF_LISTEN_PORT, TEXT_LISTEN_PORT, "6881-6999")); item->addTag(TAG_BASIC); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_MAX_UPLOAD_LIMIT, TEXT_MAX_UPLOAD_LIMIT); + HelpItemHandle item(new HelpItem(PREF_MAX_UPLOAD_LIMIT, TEXT_MAX_UPLOAD_LIMIT)); item->addTag(TAG_BASIC); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_SEED_TIME, TEXT_SEED_TIME); + HelpItemHandle item(new HelpItem(PREF_SEED_TIME, TEXT_SEED_TIME)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_SEED_RATIO, TEXT_SEED_RATIO, "1.0"); + HelpItemHandle item(new HelpItem(PREF_SEED_RATIO, TEXT_SEED_RATIO, "1.0")); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_PEER_ID_PREFIX, TEXT_PEER_ID_PREFIX); + HelpItemHandle item(new HelpItem(PREF_PEER_ID_PREFIX, TEXT_PEER_ID_PREFIX)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_ENABLE_PEER_EXCHANGE, TEXT_ENABLE_PEER_EXCHANGE, V_TRUE); + HelpItemHandle item(new HelpItem(PREF_ENABLE_PEER_EXCHANGE, TEXT_ENABLE_PEER_EXCHANGE, V_TRUE)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_ENABLE_DHT, TEXT_ENABLE_DHT, V_FALSE); + HelpItemHandle item(new HelpItem(PREF_ENABLE_DHT, TEXT_ENABLE_DHT, V_FALSE)); item->addTag(TAG_BASIC); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_DHT_LISTEN_PORT, TEXT_DHT_LISTEN_PORT, "6881-6999"); + HelpItemHandle item(new HelpItem(PREF_DHT_LISTEN_PORT, TEXT_DHT_LISTEN_PORT, "6881-6999")); item->addTag(TAG_BASIC); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_DHT_ENTRY_POINT, TEXT_DHT_ENTRY_POINT); + HelpItemHandle item(new HelpItem(PREF_DHT_ENTRY_POINT, TEXT_DHT_ENTRY_POINT)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_BT_MIN_CRYPTO_LEVEL, TEXT_BT_MIN_CRYPTO_LEVEL, V_PLAIN); + HelpItemHandle item(new HelpItem(PREF_BT_MIN_CRYPTO_LEVEL, TEXT_BT_MIN_CRYPTO_LEVEL, V_PLAIN)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_BT_REQUIRE_CRYPTO, TEXT_BT_REQUIRE_CRYPTO, V_FALSE); + HelpItemHandle item(new HelpItem(PREF_BT_REQUIRE_CRYPTO, TEXT_BT_REQUIRE_CRYPTO, V_FALSE)); item->addTag(TAG_BITTORRENT); tc->addItem(item); } #endif // ENABLE_BITTORRENT #ifdef ENABLE_METALINK { - HelpItemHandle item = new HelpItem(PREF_METALINK_FILE, TEXT_METALINK_FILE); + HelpItemHandle item(new HelpItem(PREF_METALINK_FILE, TEXT_METALINK_FILE)); item->addTag(TAG_BASIC); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_SERVERS, TEXT_METALINK_SERVERS); + HelpItemHandle item(new HelpItem(PREF_METALINK_SERVERS, TEXT_METALINK_SERVERS)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_VERSION, TEXT_METALINK_VERSION); + HelpItemHandle item(new HelpItem(PREF_METALINK_VERSION, TEXT_METALINK_VERSION)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_LANGUAGE, TEXT_METALINK_LANGUAGE); + HelpItemHandle item(new HelpItem(PREF_METALINK_LANGUAGE, TEXT_METALINK_LANGUAGE)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_OS, TEXT_METALINK_OS); + HelpItemHandle item(new HelpItem(PREF_METALINK_OS, TEXT_METALINK_OS)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_LOCATION, TEXT_METALINK_LOCATION); + HelpItemHandle item(new HelpItem(PREF_METALINK_LOCATION, TEXT_METALINK_LOCATION)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_PREFERRED_PROTOCOL, TEXT_METALINK_PREFERRED_PROTOCOL, V_NONE); + HelpItemHandle item(new HelpItem(PREF_METALINK_PREFERRED_PROTOCOL, TEXT_METALINK_PREFERRED_PROTOCOL, V_NONE)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_FOLLOW_METALINK, TEXT_FOLLOW_METALINK, V_TRUE); + HelpItemHandle item(new HelpItem(PREF_FOLLOW_METALINK, TEXT_FOLLOW_METALINK, V_TRUE)); item->addTag(TAG_METALINK); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL, TEXT_METALINK_ENABLE_UNIQUE_PROTOCOL, V_TRUE); + HelpItemHandle item(new HelpItem(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL, TEXT_METALINK_ENABLE_UNIQUE_PROTOCOL, V_TRUE)); item->addTag(TAG_METALINK); tc->addItem(item); } #endif // ENABLE_METALINK { - HelpItemHandle item = new HelpItem("version", TEXT_VERSION); + HelpItemHandle item(new HelpItem("version", TEXT_VERSION)); item->addTag(TAG_BASIC); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_NO_CONF, TEXT_NO_CONF); + HelpItemHandle item(new HelpItem(PREF_NO_CONF, TEXT_NO_CONF)); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_CONF_PATH, TEXT_CONF_PATH, "$HOME/.aria2/aria2.conf"); + HelpItemHandle item(new HelpItem(PREF_CONF_PATH, TEXT_CONF_PATH, "$HOME/.aria2/aria2.conf")); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem(PREF_STOP, TEXT_STOP, "0"); + HelpItemHandle item(new HelpItem(PREF_STOP, TEXT_STOP, "0")); item->addTag(TAG_ADVANCED); tc->addItem(item); } { - HelpItemHandle item = new HelpItem("help", TEXT_HELP, TAG_BASIC); + HelpItemHandle item(new HelpItem("help", TEXT_HELP, TAG_BASIC)); char buf[64]; snprintf(buf, sizeof(buf), "%s,%s,%s,%s,%s,%s,all", TAG_BASIC, TAG_ADVANCED, TAG_HTTP, TAG_FTP, TAG_METALINK, TAG_BITTORRENT); item->setAvailableValues(buf); diff --git a/src/HttpConnection.cc b/src/HttpConnection.cc index 52e3bfcb..e624a040 100644 --- a/src/HttpConnection.cc +++ b/src/HttpConnection.cc @@ -51,10 +51,9 @@ namespace aria2 { -HttpRequestEntry::HttpRequestEntry(const HttpRequestHandle& httpRequest, - const HttpHeaderProcessorHandle& proc): +HttpRequestEntry::HttpRequestEntry(const HttpRequestHandle& httpRequest): _httpRequest(httpRequest), - _proc(proc) {} + _proc(new HttpHeaderProcessor()) {} HttpRequestEntry::~HttpRequestEntry() {} @@ -96,8 +95,8 @@ void HttpConnection::sendRequest(const HttpRequestHandle& httpRequest) std::string request = httpRequest->createRequest(); logger->info(MSG_SENDING_REQUEST, cuid, eraseConfidentialInfo(request).c_str()); socket->writeData(request.c_str(), request.size()); - outstandingHttpRequests.push_back(new HttpRequestEntry(httpRequest, - new HttpHeaderProcessor())); + SharedHandle entry(new HttpRequestEntry(httpRequest)); + outstandingHttpRequests.push_back(entry); } void HttpConnection::sendProxyRequest(const HttpRequestHandle& httpRequest) @@ -105,8 +104,8 @@ void HttpConnection::sendProxyRequest(const HttpRequestHandle& httpRequest) std::string request = httpRequest->createProxyRequest(); logger->info(MSG_SENDING_REQUEST, cuid, eraseConfidentialInfo(request).c_str()); socket->writeData(request.c_str(), request.size()); - outstandingHttpRequests.push_back(new HttpRequestEntry(httpRequest, - new HttpHeaderProcessor())); + SharedHandle entry(new HttpRequestEntry(httpRequest)); + outstandingHttpRequests.push_back(entry); } HttpResponseHandle HttpConnection::receiveResponse() @@ -126,7 +125,7 @@ HttpResponseHandle HttpConnection::receiveResponse() proc->update(buf, size); if(!proc->eoh()) { socket->readData(buf, size); - return 0; + return SharedHandle(); } size_t putbackDataLength = proc->getPutBackDataLength(); size -= putbackDataLength; @@ -140,7 +139,7 @@ HttpResponseHandle HttpConnection::receiveResponse() entry->getHttpRequest()->getRequest()->setKeepAlive(false); } - HttpResponseHandle httpResponse = new HttpResponse(); + HttpResponseHandle httpResponse(new HttpResponse()); httpResponse->setCuid(cuid); httpResponse->setStatus(Util::parseInt(httpStatusHeader.first)); httpResponse->setHttpHeader(httpStatusHeader.second); diff --git a/src/HttpConnection.h b/src/HttpConnection.h index 89e0d18a..21684fd2 100644 --- a/src/HttpConnection.h +++ b/src/HttpConnection.h @@ -55,8 +55,7 @@ private: SharedHandle _httpRequest; SharedHandle _proc; public: - HttpRequestEntry(const SharedHandle& httpRequest, - const SharedHandle& proc); + HttpRequestEntry(const SharedHandle& httpRequest); ~HttpRequestEntry(); @@ -115,7 +114,7 @@ public: if(outstandingHttpRequests.size() > 0) { return outstandingHttpRequests.front()->getHttpRequest(); } else { - return 0; + return SharedHandle(); } } diff --git a/src/HttpHeader.cc b/src/HttpHeader.cc index d377ca17..9a9ad225 100644 --- a/src/HttpHeader.cc +++ b/src/HttpHeader.cc @@ -83,13 +83,13 @@ RangeHandle HttpHeader::getRange() const if(rangeStr == "") { std::string contentLengthStr = getFirst("Content-Length"); if(contentLengthStr == "") { - return new Range(0, 0, 0); + return SharedHandle(new Range()); } else { uint64_t contentLength = Util::parseULLInt(contentLengthStr); if(contentLength == 0) { - return new Range(0, 0, 0); + return SharedHandle(new Range()); } else { - return new Range(0, contentLength-1, contentLength); + return SharedHandle(new Range(0, contentLength-1, contentLength)); } } } @@ -117,7 +117,7 @@ RangeHandle HttpHeader::getRange() const off_t endByte = Util::parseLLInt(byteRangeRespSpecPair.second); uint64_t entityLength = Util::parseULLInt(byteRangeSpecPair.second); - return new Range(startByte, endByte, entityLength); + return SharedHandle(new Range(startByte, endByte, entityLength)); } } // namespace aria2 diff --git a/src/HttpHeaderProcessor.cc b/src/HttpHeaderProcessor.cc index c581b654..254bb737 100644 --- a/src/HttpHeaderProcessor.cc +++ b/src/HttpHeaderProcessor.cc @@ -103,7 +103,7 @@ std::pair HttpHeaderProcessor::getHttpStatusHeade throw new DlRetryEx(EX_NO_STATUS_HEADER); } std::string status = line.substr(9, 3); - HttpHeaderHandle httpHeader = new HttpHeader(); + HttpHeaderHandle httpHeader(new HttpHeader()); while(getline(strm, line)) { line = Util::trim(line); if(line.empty()) { diff --git a/src/HttpInitiateConnectionCommand.cc b/src/HttpInitiateConnectionCommand.cc index 9bf92132..2ef6b812 100644 --- a/src/HttpInitiateConnectionCommand.cc +++ b/src/HttpInitiateConnectionCommand.cc @@ -55,7 +55,8 @@ HttpInitiateConnectionCommand::HttpInitiateConnectionCommand(int cuid, const RequestHandle& req, RequestGroup* requestGroup, DownloadEngine* e): - AbstractCommand(cuid, req, requestGroup, e) + AbstractCommand(cuid, req, requestGroup, e), + nameResolver(new NameResolver()) { setTimeout(e->option->getAsInt(PREF_DNS_TIMEOUT)); setStatusActive(); @@ -94,7 +95,9 @@ bool HttpInitiateConnectionCommand::executeInternal() { if(useProxyTunnel()) { command = new HttpProxyRequestCommand(cuid, req, _requestGroup, e, socket); } else if(useProxyGet()) { - command = new HttpRequestCommand(cuid, req, _requestGroup, new HttpConnection(cuid, socket, e->option), e, socket); + SharedHandle httpConnection(new HttpConnection(cuid, socket, e->option)); + command = new HttpRequestCommand(cuid, req, _requestGroup, + httpConnection, e, socket); } else { // TODO throw new DlAbortEx("ERROR"); @@ -103,7 +106,9 @@ bool HttpInitiateConnectionCommand::executeInternal() { logger->info(MSG_CONNECTING_TO_SERVER, cuid, req->getHost().c_str(), req->getPort()); socket->establishConnection(hostname, req->getPort()); - command = new HttpRequestCommand(cuid, req, _requestGroup, new HttpConnection(cuid, socket, e->option), e, socket); + SharedHandle httpConnection(new HttpConnection(cuid, socket, e->option)); + command = new HttpRequestCommand(cuid, req, _requestGroup, httpConnection, + e, socket); } e->commands.push_back(command); return true; diff --git a/src/HttpRequest.cc b/src/HttpRequest.cc index f1b0f8f3..9d43902d 100644 --- a/src/HttpRequest.cc +++ b/src/HttpRequest.cc @@ -49,9 +49,7 @@ namespace aria2 { std::string HttpRequest::USER_AGENT = "aria2"; -HttpRequest::HttpRequest():request(0), - segment(0), - entityLength(0), +HttpRequest::HttpRequest():entityLength(0), authEnabled(false), proxyEnabled(false), proxyAuthEnabled(false), @@ -104,9 +102,9 @@ RangeHandle HttpRequest::getRange() const { // content-length is always 0 if(segment.isNull()) { - return new Range(0, 0, 0); + return SharedHandle(new Range()); } else { - return new Range(getStartByte(), getEndByte(), entityLength); + return SharedHandle(new Range(getStartByte(), getEndByte(), entityLength)); } } diff --git a/src/HttpRequestCommand.cc b/src/HttpRequestCommand.cc index 3e845e41..c691c4b3 100644 --- a/src/HttpRequestCommand.cc +++ b/src/HttpRequestCommand.cc @@ -80,10 +80,9 @@ bool HttpRequestCommand::executeInternal() { } if(_segments.empty()) { - HttpRequestHandle httpRequest = new HttpRequest(); + HttpRequestHandle httpRequest(new HttpRequest()); httpRequest->setUserAgent(e->option->get(PREF_USER_AGENT)); httpRequest->setRequest(req); - httpRequest->setSegment(0); httpRequest->setEntityLength(_requestGroup->getTotalLength()); httpRequest->configure(e->option); @@ -92,7 +91,7 @@ bool HttpRequestCommand::executeInternal() { for(Segments::iterator itr = _segments.begin(); itr != _segments.end(); ++itr) { SegmentHandle segment = *itr; if(!_httpConnection->isIssued(segment)) { - HttpRequestHandle httpRequest = new HttpRequest(); + HttpRequestHandle httpRequest(new HttpRequest()); httpRequest->setUserAgent(e->option->get(PREF_USER_AGENT)); httpRequest->setRequest(req); httpRequest->setSegment(segment); diff --git a/src/HttpResponse.cc b/src/HttpResponse.cc index 32e5a934..05946e27 100644 --- a/src/HttpResponse.cc +++ b/src/HttpResponse.cc @@ -51,8 +51,6 @@ namespace aria2 { HttpResponse::HttpResponse():cuid(0), status(0), - httpRequest(0), - httpHeader(0), logger(LogFactory::getInstance()) {} @@ -144,10 +142,10 @@ TransferEncodingHandle HttpResponse::getTransferDecoder() const { if(isTransferEncodingSpecified()) { if(getTransferEncoding() == "chunked") { - return new ChunkedEncoding(); + return SharedHandle(new ChunkedEncoding()); } } - return 0; + return SharedHandle(); } uint64_t HttpResponse::getContentLength() const diff --git a/src/HttpResponseCommand.cc b/src/HttpResponseCommand.cc index b4bb653a..b92ef5ce 100644 --- a/src/HttpResponseCommand.cc +++ b/src/HttpResponseCommand.cc @@ -99,7 +99,8 @@ bool HttpResponseCommand::executeInternal() } if(_requestGroup->getPieceStorage().isNull()) { uint64_t totalLength = httpResponse->getEntityLength(); - SingleFileDownloadContextHandle dctx = _requestGroup->getDownloadContext(); + SingleFileDownloadContextHandle dctx = + dynamic_pointer_cast(_requestGroup->getDownloadContext()); dctx->setTotalLength(totalLength); dctx->setFilename(httpResponse->determinFilename()); dctx->setContentType(httpResponse->getContentType()); @@ -134,7 +135,7 @@ bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpRe return true; } - BtProgressInfoFileHandle infoFile = new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option); + BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option)); if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) { return true; } @@ -176,7 +177,7 @@ bool HttpResponseCommand::handleOtherEncoding(const HttpResponseHandle& httpResp HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand(const HttpResponseHandle& httpResponse) { - TransferEncodingHandle enc = 0; + TransferEncodingHandle enc; if(httpResponse->isTransferEncodingSpecified()) { enc = httpResponse->getTransferDecoder(); if(enc.isNull()) { diff --git a/src/InitiatorMSEHandshakeCommand.cc b/src/InitiatorMSEHandshakeCommand.cc index 38f3d659..913f2d2d 100644 --- a/src/InitiatorMSEHandshakeCommand.cc +++ b/src/InitiatorMSEHandshakeCommand.cc @@ -122,8 +122,8 @@ bool InitiatorMSEHandshakeCommand::executeInternal() { } case INITIATOR_RECEIVE_PAD_D: { if(_mseHandshake->receivePad()) { - SharedHandle peerConnection = - new PeerConnection(cuid, socket, e->option); + SharedHandle peerConnection + (new PeerConnection(cuid, socket, e->option)); if(_mseHandshake->getNegotiatedCryptoType() == MSEHandshake::CRYPTO_ARC4) { peerConnection->enableEncryption(_mseHandshake->getEncryptor(), _mseHandshake->getDecryptor()); diff --git a/src/IteratableChecksumValidator.cc b/src/IteratableChecksumValidator.cc index 415ad594..93c0a8a1 100644 --- a/src/IteratableChecksumValidator.cc +++ b/src/IteratableChecksumValidator.cc @@ -54,7 +54,6 @@ IteratableChecksumValidator::IteratableChecksumValidator(const SingleFileDownloa _dctx(dctx), _pieceStorage(pieceStorage), _currentOffset(0), - _ctx(0), _logger(LogFactory::getInstance()), _buffer(0) {} @@ -107,7 +106,7 @@ void IteratableChecksumValidator::init() #endif // HAVE_POSIX_MEMALIGN _pieceStorage->getDiskAdaptor()->enableDirectIO(); _currentOffset = 0; - _ctx = new MessageDigestContext(); + _ctx.reset(new MessageDigestContext()); _ctx->trySetAlgo(_dctx->getChecksumHashAlgo()); _ctx->digestInit(); } diff --git a/src/IteratableChunkChecksumValidator.cc b/src/IteratableChunkChecksumValidator.cc index 2d2c2590..3859644c 100644 --- a/src/IteratableChunkChecksumValidator.cc +++ b/src/IteratableChunkChecksumValidator.cc @@ -60,7 +60,6 @@ IteratableChunkChecksumValidator(const DownloadContextHandle& dctx, _bitfield(new BitfieldMan(_dctx->getPieceLength(), _dctx->getTotalLength())), _currentIndex(0), _logger(LogFactory::getInstance()), - _ctx(0), _buffer(0) {} IteratableChunkChecksumValidator::~IteratableChunkChecksumValidator() @@ -122,7 +121,7 @@ void IteratableChunkChecksumValidator::init() if(_dctx->getFileEntries().size() == 1) { _pieceStorage->getDiskAdaptor()->enableDirectIO(); } - _ctx = new MessageDigestContext(); + _ctx.reset(new MessageDigestContext()); _ctx->trySetAlgo(_dctx->getPieceHashAlgo()); _ctx->digestInit(); _bitfield->clearAllBit(); diff --git a/src/MSEHandshake.cc b/src/MSEHandshake.cc index c56ef444..0e80db79 100644 --- a/src/MSEHandshake.cc +++ b/src/MSEHandshake.cc @@ -71,8 +71,6 @@ MSEHandshake::MSEHandshake(int32_t cuid, _rbufLength(0), _negotiatedCryptoType(CRYPTO_NONE), _dh(0), - _encryptor(0), - _decryptor(0), _initiator(true), _markerIndex(0), _padLength(0), @@ -158,14 +156,14 @@ void MSEHandshake::initCipher(const unsigned char* infoHash) unsigned char localCipherKey[20]; MessageDigestHelper::digest(localCipherKey, sizeof(localCipherKey), "sha1", s, sizeof(s)); - _encryptor = new ARC4Encryptor(); + _encryptor.reset(new ARC4Encryptor()); _encryptor->init(localCipherKey, sizeof(localCipherKey)); unsigned char peerCipherKey[20]; memcpy(s, _initiator?"keyB":"keyA", 4); MessageDigestHelper::digest(peerCipherKey, sizeof(peerCipherKey), "sha1", s, sizeof(s)); - _decryptor = new ARC4Decryptor(); + _decryptor.reset(new ARC4Decryptor()); _decryptor->init(peerCipherKey, sizeof(peerCipherKey)); // discard first 1024 bytes ARC4 output. @@ -413,7 +411,7 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength() std::deque > btContexts = BtRegistry::getAllBtContext(); // pointing to the position of HASH('req2', SKEY) xor HASH('req3', S) unsigned char* rbufptr = _rbuf; - SharedHandle btContext = 0; + SharedHandle btContext; for(std::deque >::const_iterator i = btContexts.begin(); i != btContexts.end(); ++i) { unsigned char md[20]; diff --git a/src/MemoryBufferPreDownloadHandler.cc b/src/MemoryBufferPreDownloadHandler.cc index 19af96bf..419b58a8 100644 --- a/src/MemoryBufferPreDownloadHandler.cc +++ b/src/MemoryBufferPreDownloadHandler.cc @@ -45,7 +45,8 @@ MemoryBufferPreDownloadHandler::~MemoryBufferPreDownloadHandler() {} void MemoryBufferPreDownloadHandler::execute(RequestGroup* requestGroup) { - requestGroup->setDiskWriterFactory(new ByteArrayDiskWriterFactory()); + SharedHandle dwf(new ByteArrayDiskWriterFactory()); + requestGroup->setDiskWriterFactory(dwf); requestGroup->setFileAllocationEnabled(false); requestGroup->setPreLocalFileCheckEnabled(false); diff --git a/src/MessageDigestHelper.cc b/src/MessageDigestHelper.cc index 5e0d0745..6b82cb44 100644 --- a/src/MessageDigestHelper.cc +++ b/src/MessageDigestHelper.cc @@ -106,7 +106,7 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx, std::string MessageDigestHelper::digest(const std::string& algo, const std::string& filename) { - DiskWriterHandle writer = new DefaultDiskWriter(); + DiskWriterHandle writer(new DefaultDiskWriter()); writer->openExistingFile(filename); return digest(algo, writer, 0, writer->size()); } diff --git a/src/Metalink2RequestGroup.cc b/src/Metalink2RequestGroup.cc index 922a92be..f033d992 100644 --- a/src/Metalink2RequestGroup.cc +++ b/src/Metalink2RequestGroup.cc @@ -155,23 +155,26 @@ Metalink2RequestGroup::createRequestGroup(std::deque std::find_if(entry->resources.begin(), entry->resources.end(), FindBitTorrentUrl()); #ifdef ENABLE_BITTORRENT - SharedHandle torrentRg = 0; + SharedHandle torrentRg; // there is torrent entry if(itr != entry->resources.end()) { std::deque uris; uris.push_back((*itr)->url); - torrentRg = new RequestGroup(_option, uris); - SharedHandle dctx = - new SingleFileDownloadContext(_option->getAsInt(PREF_SEGMENT_SIZE), - 0, - ""); + torrentRg.reset(new RequestGroup(_option, uris)); + SharedHandle dctx + (new SingleFileDownloadContext(_option->getAsInt(PREF_SEGMENT_SIZE), + 0, + "")); //dctx->setDir(_option->get(PREF_DIR)); torrentRg->setDownloadContext(dctx); torrentRg->clearPreDowloadHandler(); torrentRg->clearPostDowloadHandler(); // make it in-memory download - SharedHandle preh = new MemoryBufferPreDownloadHandler(); - preh->setCriteria(new TrueRequestGroupCriteria()); + SharedHandle preh(new MemoryBufferPreDownloadHandler()); + { + SharedHandle cri(new TrueRequestGroupCriteria()); + preh->setCriteria(cri); + } torrentRg->addPreDownloadHandler(preh); groups.push_back(torrentRg); } @@ -180,7 +183,7 @@ Metalink2RequestGroup::createRequestGroup(std::deque std::deque uris; std::for_each(entry->resources.begin(), entry->resources.end(), AccumulateNonP2PUrl(uris)); - SharedHandle rg = new RequestGroup(_option, uris); + SharedHandle rg(new RequestGroup(_option, uris)); // If piece hash is specified in the metalink, // make segment size equal to piece hash size. size_t pieceLength; @@ -193,11 +196,11 @@ Metalink2RequestGroup::createRequestGroup(std::deque #else pieceLength = _option->getAsInt(PREF_SEGMENT_SIZE); #endif // ENABLE_MESSAGE_DIGEST - SharedHandle dctx = - new SingleFileDownloadContext(pieceLength, - entry->getLength(), - "", - entry->file->getPath()); + SharedHandle dctx + (new SingleFileDownloadContext(pieceLength, + entry->getLength(), + "", + entry->file->getPath())); dctx->setDir(_option->get(PREF_DIR)); #ifdef ENABLE_MESSAGE_DIGEST if(entry->chunkChecksum.isNull()) { @@ -220,7 +223,8 @@ Metalink2RequestGroup::createRequestGroup(std::deque #ifdef ENABLE_BITTORRENT // Inject depenency between rg and torrentRg here if torrentRg.isNull() == false if(!torrentRg.isNull()) { - rg->dependsOn(new BtDependency(rg, torrentRg, _option)); + SharedHandle dep(new BtDependency(rg, torrentRg, _option)); + rg->dependsOn(dep); } #endif // ENABLE_BITTORRENT groups.push_back(rg); diff --git a/src/MetalinkEntry.cc b/src/MetalinkEntry.cc index a7be88a0..e098e506 100644 --- a/src/MetalinkEntry.cc +++ b/src/MetalinkEntry.cc @@ -48,11 +48,6 @@ namespace aria2 { MetalinkEntry::MetalinkEntry(): file(0), maxConnections(-1) -#ifdef ENABLE_MESSAGE_DIGEST - , - checksum(0), - chunkChecksum(0) -#endif // ENABLE_MESSAGE_DIGEST {} MetalinkEntry::~MetalinkEntry() {} diff --git a/src/MetalinkParserController.cc b/src/MetalinkParserController.cc index 2f9ed335..85da8760 100644 --- a/src/MetalinkParserController.cc +++ b/src/MetalinkParserController.cc @@ -48,14 +48,7 @@ namespace aria2 { MetalinkParserController::MetalinkParserController(): - _metalinker(new Metalinker()), - _tEntry(0), - _tResource(0) -#ifdef ENABLE_MESSAGE_DIGEST - , - _tChecksum(0), - _tChunkChecksum(0) -#endif // ENABLE_MESSAGE_DIGEST + _metalinker(new Metalinker()) {} MetalinkParserController::~MetalinkParserController() {} @@ -67,11 +60,11 @@ SharedHandle MetalinkParserController::getResult() const void MetalinkParserController::newEntryTransaction() { - _tEntry = new MetalinkEntry(); - _tResource = 0; + _tEntry.reset(new MetalinkEntry()); + _tResource.reset(); #ifdef ENABLE_MESSAGE_DIGEST - _tChecksum = 0; - _tChunkChecksum = 0; + _tChecksum.reset(); + _tChunkChecksum.reset(); #endif // ENABLE_MESSAGE_DIGEST } @@ -81,7 +74,7 @@ void MetalinkParserController::setFileNameOfEntry(const std::string& filename) return; } if(_tEntry->file.isNull()) { - _tEntry->file = new FileEntry(filename, 0, 0); + _tEntry->file.reset(new FileEntry(filename, 0, 0)); } else { _tEntry->file->setPath(filename); } @@ -93,7 +86,7 @@ void MetalinkParserController::setFileLengthOfEntry(uint64_t length) return; } if(_tEntry->file.isNull()) { - _tEntry->file = new FileEntry("", length, 0); + _tEntry->file.reset(new FileEntry("", length, 0)); } else { _tEntry->file->setLength(length); } @@ -140,7 +133,7 @@ void MetalinkParserController::commitEntryTransaction() commitChecksumTransaction(); commitChunkChecksumTransaction(); _metalinker->entries.push_back(_tEntry); - _tEntry = 0; + _tEntry.reset(); } void MetalinkParserController::cancelEntryTransaction() @@ -148,7 +141,7 @@ void MetalinkParserController::cancelEntryTransaction() cancelResourceTransaction(); cancelChecksumTransaction(); cancelChunkChecksumTransaction(); - _tEntry = 0; + _tEntry.reset(); } void MetalinkParserController::newResourceTransaction() @@ -156,7 +149,7 @@ void MetalinkParserController::newResourceTransaction() if(_tEntry.isNull()) { return; } - _tResource = new MetalinkResource(); + _tResource.reset(new MetalinkResource()); } void MetalinkParserController::setURLOfResource(const std::string& url) @@ -215,12 +208,12 @@ void MetalinkParserController::commitResourceTransaction() return; } _tEntry->resources.push_back(_tResource); - _tResource = 0; + _tResource.reset(); } void MetalinkParserController::cancelResourceTransaction() { - _tResource = 0; + _tResource.reset(); } void MetalinkParserController::newChecksumTransaction() @@ -229,7 +222,7 @@ void MetalinkParserController::newChecksumTransaction() if(_tEntry.isNull()) { return; } - _tChecksum = new Checksum(); + _tChecksum.reset(new Checksum()); #endif // ENABLE_MESSAGE_DIGEST } @@ -266,14 +259,14 @@ void MetalinkParserController::commitChecksumTransaction() if(_tEntry->checksum.isNull() || _tEntry->checksum->getAlgo() != "sha1") { _tEntry->checksum = _tChecksum; } - _tChecksum = 0; + _tChecksum.reset(); #endif // ENABLE_MESSAGE_DIGEST } void MetalinkParserController::cancelChecksumTransaction() { #ifdef ENABLE_MESSAGE_DIGEST - _tChecksum = 0; + _tChecksum.reset(); #endif // ENABLE_MESSAGE_DIGEST } @@ -283,7 +276,7 @@ void MetalinkParserController::newChunkChecksumTransaction() if(_tEntry.isNull()) { return; } - _tChunkChecksum = new ChunkChecksum(); + _tChunkChecksum.reset(new ChunkChecksum()); _tempChunkChecksums.clear(); #endif // ENABLE_MESSAGE_DIGEST } @@ -370,14 +363,14 @@ void MetalinkParserController::commitChunkChecksumTransaction() _tChunkChecksum->setChecksums(checksums); _tEntry->chunkChecksum = _tChunkChecksum; } - _tChunkChecksum = 0; + _tChunkChecksum.reset(); #endif // ENABLE_MESSAGE_DIGEST } void MetalinkParserController::cancelChunkChecksumTransaction() { #ifdef ENABLE_MESSAGE_DIGEST - _tChunkChecksum = 0; + _tChunkChecksum.reset(); #endif // ENABLE_MESSAGE_DIGEST } diff --git a/src/MetalinkPostDownloadHandler.cc b/src/MetalinkPostDownloadHandler.cc index f8b48c24..c6da129e 100644 --- a/src/MetalinkPostDownloadHandler.cc +++ b/src/MetalinkPostDownloadHandler.cc @@ -46,8 +46,10 @@ namespace aria2 { MetalinkPostDownloadHandler::MetalinkPostDownloadHandler() { - setCriteria(new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getMetalinkContentTypes(), - DownloadHandlerConstants::getMetalinkExtensions())); + SharedHandle cri + (new ContentTypeRequestGroupCriteria(DownloadHandlerConstants::getMetalinkContentTypes(), + DownloadHandlerConstants::getMetalinkExtensions())); + setCriteria(cri); } MetalinkPostDownloadHandler::~MetalinkPostDownloadHandler() {} diff --git a/src/MetalinkProcessorFactory.cc b/src/MetalinkProcessorFactory.cc index a293e2da..00118cdf 100644 --- a/src/MetalinkProcessorFactory.cc +++ b/src/MetalinkProcessorFactory.cc @@ -45,11 +45,11 @@ namespace aria2 { SharedHandle MetalinkProcessorFactory::newInstance() { #ifdef HAVE_LIBXML2 - return new XML2SAXMetalinkProcessor(); + return SharedHandle(new XML2SAXMetalinkProcessor()); #elif HAVE_LIBEXPAT - return new ExpatMetalinkProcessor(); + return SharedHandle(new ExpatMetalinkProcessor()); #else - return 0; + return SharedHandle(); #endif } diff --git a/src/MultiDiskAdaptor.cc b/src/MultiDiskAdaptor.cc index 3f0f043d..f0548469 100644 --- a/src/MultiDiskAdaptor.cc +++ b/src/MultiDiskAdaptor.cc @@ -45,8 +45,7 @@ namespace aria2 { DiskWriterEntry::DiskWriterEntry(const SharedHandle& fileEntry): - fileEntry(fileEntry), - diskWriter(0) {} + fileEntry(fileEntry) {} DiskWriterEntry::~DiskWriterEntry() {} @@ -115,11 +114,12 @@ void MultiDiskAdaptor::resetDiskWriterEntries() diskWriterEntries.clear(); for(FileEntries::const_iterator itr = fileEntries.begin(); itr != fileEntries.end(); itr++) { - DiskWriterEntryHandle entry = new DiskWriterEntry(*itr); + DiskWriterEntryHandle entry(new DiskWriterEntry(*itr)); if((*itr)->isRequested()) { entry->setDiskWriter(DefaultDiskWriterFactory().newDiskWriter()); } else { - entry->setDiskWriter(new DefaultDiskWriter()); + SharedHandle dw(new DefaultDiskWriter()); + entry->setDiskWriter(dw); } entry->getDiskWriter()->setDirectIOAllowed(_directIOAllowed); diskWriterEntries.push_back(entry); @@ -276,7 +276,7 @@ uint64_t MultiDiskAdaptor::size() const FileAllocationIteratorHandle MultiDiskAdaptor::fileAllocationIterator() { - return new MultiFileAllocationIterator(this); + return SharedHandle(new MultiFileAllocationIterator(this)); } void MultiDiskAdaptor::enableDirectIO() diff --git a/src/MultiFileAllocationIterator.cc b/src/MultiFileAllocationIterator.cc index e4125b35..0af7628b 100644 --- a/src/MultiFileAllocationIterator.cc +++ b/src/MultiFileAllocationIterator.cc @@ -44,7 +44,6 @@ MultiFileAllocationIterator::MultiFileAllocationIterator(MultiDiskAdaptor* diskA _diskAdaptor(diskAdaptor), _entries(makeDiskWriterEntries(diskAdaptor->diskWriterEntries, diskAdaptor->getPieceLength())), - _fileAllocationIterator(0), _offset(0) {} @@ -61,10 +60,10 @@ void MultiFileAllocationIterator::allocateChunk() FileEntryHandle fileEntry = entry->getFileEntry(); if(entry->size() < fileEntry->getLength()) { entry->getDiskWriter()->enableDirectIO(); - _fileAllocationIterator = - new SingleFileAllocationIterator(entry->getDiskWriter().get(), - entry->size(), - fileEntry->getLength()); + _fileAllocationIterator.reset + (new SingleFileAllocationIterator(entry->getDiskWriter().get(), + entry->size(), + fileEntry->getLength())); _fileAllocationIterator->init(); } } @@ -114,7 +113,11 @@ DiskWriterEntries MultiFileAllocationIterator::makeDiskWriterEntries(const DiskW return entries; } DiskWriterEntries temp(srcEntries); - temp.push_front(new DiskWriterEntry(new FileEntry())); + { + SharedHandle f(new FileEntry()); + SharedHandle e(new DiskWriterEntry(f)); + temp.push_front(e); + } DiskWriterEntries entries; DiskWriterEntries::const_iterator done = temp.begin(); for(DiskWriterEntries::const_iterator itr = temp.begin()+1; itr != temp.end(); ++itr) { diff --git a/src/MultiUrlRequestInfo.cc b/src/MultiUrlRequestInfo.cc index 794fa7d0..455004a7 100644 --- a/src/MultiUrlRequestInfo.cc +++ b/src/MultiUrlRequestInfo.cc @@ -84,14 +84,15 @@ void MultiUrlRequestInfo::printMessageForContinue() int MultiUrlRequestInfo::execute() { { - DNSCacheHandle dnsCache = new SimpleDNSCache(); + DNSCacheHandle dnsCache(new SimpleDNSCache()); DNSCacheSingletonHolder::instance(dnsCache); } int returnValue = 0; try { DownloadEngineHandle e = DownloadEngineFactory().newDownloadEngine(_option, _requestGroups); - e->setStatCalc(new ConsoleStatCalc()); + SharedHandle statCalc(new ConsoleStatCalc()); + e->setStatCalc(statCalc); e->fillCommand(); diff --git a/src/Netrc.cc b/src/Netrc.cc index 518be851..9c73fc66 100644 --- a/src/Netrc.cc +++ b/src/Netrc.cc @@ -69,16 +69,16 @@ void Netrc::parse(const std::string& path) throw new RecoverableException("File not found: %s", path.c_str()); } - AuthenticatorHandle authenticator = 0; + AuthenticatorHandle authenticator; std::string token; while(f >> token) { if(token == "machine") { storeAuthenticator(authenticator); - authenticator = new Authenticator(); + authenticator.reset(new Authenticator()); authenticator->setMachine(getRequiredNextToken(f)); } else if(token == "default") { storeAuthenticator(authenticator); - authenticator = new DefaultAuthenticator(); + authenticator.reset(new DefaultAuthenticator()); } else { if(authenticator.isNull()) { throw new RecoverableException("Netrc:parse error. %s encounterd where 'machine' or 'default' expected."); @@ -123,7 +123,7 @@ AuthenticatorHandle Netrc::findAuthenticator(const std::string& hostname) const std::find_if(authenticators.begin(), authenticators.end(), AuthHostMatch(hostname)); if(itr == authenticators.end()) { - return 0; + return SharedHandle(); } else { return *itr; } diff --git a/src/NetrcAuthResolver.cc b/src/NetrcAuthResolver.cc index d1c1af13..647af81a 100644 --- a/src/NetrcAuthResolver.cc +++ b/src/NetrcAuthResolver.cc @@ -56,7 +56,7 @@ AuthConfigHandle NetrcAuthResolver::findNetrcAuthenticator(const std::string& ho if(auth.isNull()) { return _defaultAuthConfig; } else { - return new AuthConfig(auth->getLogin(), auth->getPassword()); + return SharedHandle(new AuthConfig(auth->getLogin(), auth->getPassword())); } } } diff --git a/src/OptionHandlerFactory.cc b/src/OptionHandlerFactory.cc index 36ce7183..9dafed57 100644 --- a/src/OptionHandlerFactory.cc +++ b/src/OptionHandlerFactory.cc @@ -37,91 +37,95 @@ #include "OptionHandlerImpl.h" #include "array_fun.h" +#define SH(X) SharedHandle(X) + namespace aria2 { OptionHandlers OptionHandlerFactory::createOptionHandlers() { OptionHandlers handlers; - handlers.push_back(new HttpProxyOptionHandler(PREF_HTTP_PROXY, - PREF_HTTP_PROXY_HOST, - PREF_HTTP_PROXY_PORT)); - handlers.push_back(new DefaultOptionHandler(PREF_HTTP_USER)); - handlers.push_back(new DefaultOptionHandler(PREF_HTTP_PASSWD)); - handlers.push_back(new DefaultOptionHandler(PREF_HTTP_PROXY_USER)); - handlers.push_back(new DefaultOptionHandler(PREF_HTTP_PROXY_PASSWD)); - handlers.push_back(new ParameterOptionHandler(PREF_HTTP_AUTH_SCHEME, V_BASIC)); - handlers.push_back(new DefaultOptionHandler(PREF_REFERER)); - handlers.push_back(new NumberOptionHandler(PREF_RETRY_WAIT, 0, 60)); - handlers.push_back(new DefaultOptionHandler(PREF_FTP_USER)); - handlers.push_back(new DefaultOptionHandler(PREF_FTP_PASSWD)); - handlers.push_back(new ParameterOptionHandler(PREF_FTP_TYPE, V_BINARY, V_ASCII)); - handlers.push_back(new ParameterOptionHandler(PREF_FTP_VIA_HTTP_PROXY, - V_GET, V_TUNNEL)); - handlers.push_back(new UnitNumberOptionHandler(PREF_MIN_SEGMENT_SIZE, 1024)); - handlers.push_back(new ParameterOptionHandler(PREF_HTTP_PROXY_METHOD, - V_GET, V_TUNNEL)); - handlers.push_back(new IntegerRangeOptionHandler(PREF_LISTEN_PORT, 1024, UINT16_MAX)); - handlers.push_back(new ParameterOptionHandler(PREF_FOLLOW_TORRENT, V_TRUE, V_MEM, V_FALSE)); - handlers.push_back(new BooleanOptionHandler(PREF_NO_PREALLOCATION)); - handlers.push_back(new BooleanOptionHandler(PREF_DIRECT_FILE_MAPPING)); - handlers.push_back(new IntegerRangeOptionHandler(PREF_SELECT_FILE, 1, INT32_MAX)); - handlers.push_back(new NumberOptionHandler(PREF_SEED_TIME, 0)); - handlers.push_back(new FloatNumberOptionHandler(PREF_SEED_RATIO, 0.0)); - handlers.push_back(new UnitNumberOptionHandler(PREF_MAX_UPLOAD_LIMIT, 0)); - handlers.push_back(new DefaultOptionHandler(PREF_METALINK_VERSION)); - handlers.push_back(new DefaultOptionHandler(PREF_METALINK_LANGUAGE)); - handlers.push_back(new DefaultOptionHandler(PREF_METALINK_OS)); - handlers.push_back(new ParameterOptionHandler(PREF_FOLLOW_METALINK, V_TRUE, V_MEM, V_FALSE)); - handlers.push_back(new DefaultOptionHandler(PREF_METALINK_LOCATION)); - handlers.push_back(new UnitNumberOptionHandler(PREF_LOWEST_SPEED_LIMIT, 0)); - handlers.push_back(new UnitNumberOptionHandler(PREF_MAX_DOWNLOAD_LIMIT, 0)); - handlers.push_back(new BooleanOptionHandler(PREF_ALLOW_OVERWRITE)); - handlers.push_back(new BooleanOptionHandler(PREF_CHECK_INTEGRITY)); - handlers.push_back(new BooleanOptionHandler(PREF_REALTIME_CHUNK_CHECKSUM)); - handlers.push_back(new BooleanOptionHandler(PREF_DAEMON)); - handlers.push_back(new DefaultOptionHandler(PREF_DIR)); - handlers.push_back(new DefaultOptionHandler(PREF_OUT)); - handlers.push_back(new LogOptionHandler(PREF_LOG)); - handlers.push_back(new NumberOptionHandler(PREF_SPLIT, 1, 5)); - handlers.push_back(new NumberOptionHandler(PREF_TIMEOUT, 1, 600)); - handlers.push_back(new NumberOptionHandler(PREF_MAX_TRIES, 0)); - handlers.push_back(new BooleanOptionHandler(PREF_FTP_PASV)); - handlers.push_back(new BooleanOptionHandler(PREF_SHOW_FILES)); - handlers.push_back(new DefaultOptionHandler(PREF_TORRENT_FILE)); - handlers.push_back(new DefaultOptionHandler(PREF_METALINK_FILE)); - handlers.push_back(new NumberOptionHandler(PREF_METALINK_SERVERS, 1)); - handlers.push_back(new ParameterOptionHandler(PREF_FILE_ALLOCATION, - V_NONE, V_PREALLOC)); - handlers.push_back(new BooleanOptionHandler(PREF_CONTINUE)); - handlers.push_back(new DefaultOptionHandler(PREF_USER_AGENT)); - handlers.push_back(new BooleanOptionHandler(PREF_NO_NETRC)); - handlers.push_back(new DefaultOptionHandler(PREF_INPUT_FILE)); - handlers.push_back(new NumberOptionHandler(PREF_MAX_CONCURRENT_DOWNLOADS, 1, 45)); - handlers.push_back(new DefaultOptionHandler(PREF_LOAD_COOKIES)); - handlers.push_back(new DefaultOptionHandler(PREF_PEER_ID_PREFIX)); - handlers.push_back(new BooleanOptionHandler(PREF_FORCE_SEQUENTIAL)); - handlers.push_back(new BooleanOptionHandler(PREF_AUTO_FILE_RENAMING)); - handlers.push_back(new BooleanOptionHandler(PREF_PARAMETERIZED_URI)); - handlers.push_back(new BooleanOptionHandler(PREF_ENABLE_HTTP_KEEP_ALIVE)); - handlers.push_back(new BooleanOptionHandler(PREF_ENABLE_HTTP_PIPELINING)); - handlers.push_back(new UnitNumberOptionHandler(PREF_NO_FILE_ALLOCATION_LIMIT, 0)); - handlers.push_back(new BooleanOptionHandler(PREF_ENABLE_DIRECT_IO)); - handlers.push_back(new BooleanOptionHandler(PREF_ALLOW_PIECE_LENGTH_CHANGE)); + + + handlers.push_back(SH(new HttpProxyOptionHandler(PREF_HTTP_PROXY, + PREF_HTTP_PROXY_HOST, + PREF_HTTP_PROXY_PORT))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_HTTP_USER))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_HTTP_PASSWD))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_HTTP_PROXY_USER))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_HTTP_PROXY_PASSWD))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_HTTP_AUTH_SCHEME, V_BASIC))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_REFERER))); + handlers.push_back(SH(new NumberOptionHandler(PREF_RETRY_WAIT, 0, 60))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_FTP_USER))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_FTP_PASSWD))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_FTP_TYPE, V_BINARY, V_ASCII))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_FTP_VIA_HTTP_PROXY, + V_GET, V_TUNNEL))); + handlers.push_back(SH(new UnitNumberOptionHandler(PREF_MIN_SEGMENT_SIZE, 1024))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_HTTP_PROXY_METHOD, + V_GET, V_TUNNEL))); + handlers.push_back(SH(new IntegerRangeOptionHandler(PREF_LISTEN_PORT, 1024, UINT16_MAX))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_FOLLOW_TORRENT, V_TRUE, V_MEM, V_FALSE))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_NO_PREALLOCATION))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_DIRECT_FILE_MAPPING))); + handlers.push_back(SH(new IntegerRangeOptionHandler(PREF_SELECT_FILE, 1, INT32_MAX))); + handlers.push_back(SH(new NumberOptionHandler(PREF_SEED_TIME, 0))); + handlers.push_back(SH(new FloatNumberOptionHandler(PREF_SEED_RATIO, 0.0))); + handlers.push_back(SH(new UnitNumberOptionHandler(PREF_MAX_UPLOAD_LIMIT, 0))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_METALINK_VERSION))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_METALINK_LANGUAGE))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_METALINK_OS))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_FOLLOW_METALINK, V_TRUE, V_MEM, V_FALSE))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_METALINK_LOCATION))); + handlers.push_back(SH(new UnitNumberOptionHandler(PREF_LOWEST_SPEED_LIMIT, 0))); + handlers.push_back(SH(new UnitNumberOptionHandler(PREF_MAX_DOWNLOAD_LIMIT, 0))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ALLOW_OVERWRITE))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_CHECK_INTEGRITY))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_REALTIME_CHUNK_CHECKSUM))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_DAEMON))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_DIR))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_OUT))); + handlers.push_back(SH(new LogOptionHandler(PREF_LOG))); + handlers.push_back(SH(new NumberOptionHandler(PREF_SPLIT, 1, 5))); + handlers.push_back(SH(new NumberOptionHandler(PREF_TIMEOUT, 1, 600))); + handlers.push_back(SH(new NumberOptionHandler(PREF_MAX_TRIES, 0))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_FTP_PASV))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_SHOW_FILES))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_TORRENT_FILE))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_METALINK_FILE))); + handlers.push_back(SH(new NumberOptionHandler(PREF_METALINK_SERVERS, 1))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_FILE_ALLOCATION, + V_NONE, V_PREALLOC))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_CONTINUE))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_USER_AGENT))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_NO_NETRC))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_INPUT_FILE))); + handlers.push_back(SH(new NumberOptionHandler(PREF_MAX_CONCURRENT_DOWNLOADS, 1, 45))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_LOAD_COOKIES))); + handlers.push_back(SH(new DefaultOptionHandler(PREF_PEER_ID_PREFIX))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_FORCE_SEQUENTIAL))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_AUTO_FILE_RENAMING))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_PARAMETERIZED_URI))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ENABLE_HTTP_KEEP_ALIVE))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ENABLE_HTTP_PIPELINING))); + handlers.push_back(SH(new UnitNumberOptionHandler(PREF_NO_FILE_ALLOCATION_LIMIT, 0))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ENABLE_DIRECT_IO))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ALLOW_PIECE_LENGTH_CHANGE))); { const char* params[] = { V_HTTP, V_HTTPS, V_FTP, V_NONE }; - handlers.push_back(new ParameterOptionHandler(PREF_METALINK_PREFERRED_PROTOCOL, - std::deque(¶ms[0], ¶ms[arrayLength(params)]))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_METALINK_PREFERRED_PROTOCOL, + std::deque(¶ms[0], ¶ms[arrayLength(params)])))); } - handlers.push_back(new BooleanOptionHandler(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL)); - handlers.push_back(new BooleanOptionHandler(PREF_ENABLE_PEER_EXCHANGE)); - handlers.push_back(new BooleanOptionHandler(PREF_ENABLE_DHT)); - handlers.push_back(new IntegerRangeOptionHandler(PREF_DHT_LISTEN_PORT, 1024, UINT16_MAX)); - handlers.push_back(new HostPortOptionHandler(PREF_DHT_ENTRY_POINT, + handlers.push_back(SH(new BooleanOptionHandler(PREF_METALINK_ENABLE_UNIQUE_PROTOCOL))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ENABLE_PEER_EXCHANGE))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_ENABLE_DHT))); + handlers.push_back(SH(new IntegerRangeOptionHandler(PREF_DHT_LISTEN_PORT, 1024, UINT16_MAX))); + handlers.push_back(SH(new HostPortOptionHandler(PREF_DHT_ENTRY_POINT, PREF_DHT_ENTRY_POINT_HOST, - PREF_DHT_ENTRY_POINT_PORT)); - handlers.push_back(new NumberOptionHandler(PREF_STOP, 0, INT32_MAX)); - handlers.push_back(new ParameterOptionHandler(PREF_BT_MIN_CRYPTO_LEVEL, V_PLAIN, V_ARC4)); - handlers.push_back(new BooleanOptionHandler(PREF_BT_REQUIRE_CRYPTO)); + PREF_DHT_ENTRY_POINT_PORT))); + handlers.push_back(SH(new NumberOptionHandler(PREF_STOP, 0, INT32_MAX))); + handlers.push_back(SH(new ParameterOptionHandler(PREF_BT_MIN_CRYPTO_LEVEL, V_PLAIN, V_ARC4))); + handlers.push_back(SH(new BooleanOptionHandler(PREF_BT_REQUIRE_CRYPTO))); return handlers; } diff --git a/src/OptionParser.cc b/src/OptionParser.cc index 8267e1dc..551e6929 100644 --- a/src/OptionParser.cc +++ b/src/OptionParser.cc @@ -64,7 +64,7 @@ OptionHandlerHandle OptionParser::getOptionHandlerByName(const std::string& optN return *itr; } } - return new NullOptionHandler(); + return SharedHandle(new NullOptionHandler()); } void OptionParser::setOptionHandlers(const std::deque >& optionHandlers) diff --git a/src/PStringNumLoop.h b/src/PStringNumLoop.h index b12ad3ee..56148fcf 100644 --- a/src/PStringNumLoop.h +++ b/src/PStringNumLoop.h @@ -59,13 +59,21 @@ public: PStringNumLoop(unsigned int startValue, unsigned int endValue, unsigned int step, const NumberDecoratorHandle& nd, - const PStringDatumHandle& next = 0): + const PStringDatumHandle& next): _startValue(startValue), _endValue(endValue), _step(step), _numberDecorator(nd), _next(next) {} + PStringNumLoop(unsigned int startValue, unsigned int endValue, + unsigned int step, + const NumberDecoratorHandle& nd): + _startValue(startValue), + _endValue(endValue), + _step(step), + _numberDecorator(nd) {} + virtual ~PStringNumLoop() {} virtual void accept(PStringVisitor* visitor) diff --git a/src/PStringSegment.cc b/src/PStringSegment.cc index 13653fec..56e40585 100644 --- a/src/PStringSegment.cc +++ b/src/PStringSegment.cc @@ -42,6 +42,9 @@ PStringSegment::PStringSegment(const std::string& value, const SharedHandle& next): _value(value), _next(next) {} +PStringSegment::PStringSegment(const std::string& value): + _value(value) {} + PStringSegment::~PStringSegment() {} void PStringSegment::accept(PStringVisitor* visitor) diff --git a/src/PStringSegment.h b/src/PStringSegment.h index 1942352a..9b6036d3 100644 --- a/src/PStringSegment.h +++ b/src/PStringSegment.h @@ -52,7 +52,9 @@ private: public: PStringSegment(const std::string& value, - const SharedHandle& next = 0); + const SharedHandle& next); + + PStringSegment(const std::string& value); virtual ~PStringSegment(); diff --git a/src/PStringSelect.h b/src/PStringSelect.h index 4a1364cd..2a629f43 100644 --- a/src/PStringSelect.h +++ b/src/PStringSelect.h @@ -51,10 +51,14 @@ private: PStringDatumHandle _next; public: - PStringSelect(const std::deque& values, const PStringDatumHandle& next = 0): + PStringSelect(const std::deque& values, + const PStringDatumHandle& next): _values(values), _next(next) {} + PStringSelect(const std::deque& values): + _values(values) {} + virtual ~PStringSelect() {} virtual void accept(PStringVisitor* visitor) diff --git a/src/ParameterizedStringParser.cc b/src/ParameterizedStringParser.cc index 902d64ba..5de69064 100644 --- a/src/ParameterizedStringParser.cc +++ b/src/ParameterizedStringParser.cc @@ -55,7 +55,7 @@ PStringDatumHandle ParameterizedStringParser::diggPString(const std::string& src int& offset) { if(src.size() == (size_t)offset) { - return 0; + return SharedHandle(); } switch(src[offset]) { case '[': @@ -77,7 +77,7 @@ PStringDatumHandle ParameterizedStringParser::createSegment(const std::string& s std::string value = src.substr(offset, nextDelimiterIndex-offset); offset = nextDelimiterIndex; PStringDatumHandle next = diggPString(src, offset); - return new PStringSegment(value, next); + return SharedHandle(new PStringSegment(value, next)); } PStringDatumHandle ParameterizedStringParser::createSelect(const std::string& src, @@ -95,7 +95,7 @@ PStringDatumHandle ParameterizedStringParser::createSelect(const std::string& sr } offset = rightParenIndex+1; PStringDatumHandle next = diggPString(src, offset); - return new PStringSelect(values, next); + return SharedHandle(new PStringSelect(values, next)); } PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src, @@ -124,27 +124,27 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src, if(range.first == "" || range.second == "") { throw new FatalException("Loop range missing."); } - NumberDecoratorHandle nd = 0; + NumberDecoratorHandle nd; unsigned int start; unsigned int end; if(Util::isNumber(range.first) && Util::isNumber(range.second)) { - nd = new FixedWidthNumberDecorator(range.first.size()); + nd.reset(new FixedWidthNumberDecorator(range.first.size())); start = Util::parseUInt(range.first); end = Util::parseUInt(range.second); } else if(Util::isLowercase(range.first) && Util::isLowercase(range.second)) { - nd = new AlphaNumberDecorator(range.first.size()); + nd.reset(new AlphaNumberDecorator(range.first.size())); start = Util::alphaToNum(range.first); end = Util::alphaToNum(range.second); } else if(Util::isUppercase(range.first) && Util::isUppercase(range.second)) { - nd = new AlphaNumberDecorator(range.first.size(), true); + nd.reset(new AlphaNumberDecorator(range.first.size(), true)); start = Util::alphaToNum(range.first); end = Util::alphaToNum(range.second); } else { throw new FatalException("Invalid loop range."); } - PStringDatumHandle next = diggPString(src, offset); - return new PStringNumLoop(start, end, step, nd, next); + PStringDatumHandle next(diggPString(src, offset)); + return SharedHandle(new PStringNumLoop(start, end, step, nd, next)); } } // namespace aria2 diff --git a/src/PeerConnection.cc b/src/PeerConnection.cc index fcc62c37..d5e549e8 100644 --- a/src/PeerConnection.cc +++ b/src/PeerConnection.cc @@ -58,9 +58,7 @@ PeerConnection::PeerConnection(int32_t cuid, resbufLength(0), currentPayloadLength(0), lenbufLength(0), - _encryptionEnabled(false), - _encryptor(0), - _decryptor(0) + _encryptionEnabled(false) {} PeerConnection::~PeerConnection() {} diff --git a/src/PeerInteractionCommand.cc b/src/PeerInteractionCommand.cc index 51a670ce..b62acc89 100644 --- a/src/PeerInteractionCommand.cc +++ b/src/PeerInteractionCommand.cc @@ -78,7 +78,6 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid, BtContextAwareCommand(btContext), RequestGroupAware(requestGroup), sequence(sequence), - btInteractive(0), maxDownloadSpeedLimit(0) { // TODO move following bunch of processing to separate method, like init() @@ -87,7 +86,7 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid, setWriteCheckSocket(socket); setTimeout(e->option->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)); } - DefaultBtMessageFactoryHandle factory = new DefaultBtMessageFactory(); + DefaultBtMessageFactoryHandle factory(new DefaultBtMessageFactory()); factory->setCuid(cuid); factory->setBtContext(btContext); factory->setPeer(peer); @@ -96,10 +95,14 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid, factory->setTaskQueue(DHTRegistry::_taskQueue); factory->setTaskFactory(DHTRegistry::_taskFactory); - PeerConnectionHandle peerConnection = passedPeerConnection.isNull() ? - new PeerConnection(cuid, socket, e->option) : passedPeerConnection; + PeerConnectionHandle peerConnection; + if(passedPeerConnection.isNull()) { + peerConnection.reset(new PeerConnection(cuid, socket, e->option)); + } else { + peerConnection = passedPeerConnection; + } - DefaultBtMessageDispatcherHandle dispatcher = new DefaultBtMessageDispatcher(); + DefaultBtMessageDispatcherHandle dispatcher(new DefaultBtMessageDispatcher()); dispatcher->setCuid(cuid); dispatcher->setPeer(peer); dispatcher->setBtContext(btContext); @@ -107,7 +110,7 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid, dispatcher->setRequestTimeout(e->option->getAsInt(PREF_BT_REQUEST_TIMEOUT)); dispatcher->setBtMessageFactory(factory); - DefaultBtMessageReceiverHandle receiver = new DefaultBtMessageReceiver(); + DefaultBtMessageReceiverHandle receiver(new DefaultBtMessageReceiver()); receiver->setCuid(cuid); receiver->setPeer(peer); receiver->setBtContext(btContext); @@ -115,14 +118,14 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid, receiver->setDispatcher(dispatcher); receiver->setBtMessageFactory(factory); - DefaultBtRequestFactoryHandle reqFactory = new DefaultBtRequestFactory(); + DefaultBtRequestFactoryHandle reqFactory(new DefaultBtRequestFactory()); reqFactory->setCuid(cuid); reqFactory->setPeer(peer); reqFactory->setBtContext(btContext); reqFactory->setBtMessageDispatcher(dispatcher); reqFactory->setBtMessageFactory(factory); - DefaultBtInteractiveHandle btInteractive = new DefaultBtInteractive(btContext, peer); + DefaultBtInteractiveHandle btInteractive(new DefaultBtInteractive(btContext, peer)); btInteractive->setCuid(cuid); btInteractive->setBtMessageReceiver(receiver); btInteractive->setDispatcher(dispatcher); @@ -148,7 +151,7 @@ PeerInteractionCommand::PeerInteractionCommand(int32_t cuid, factory->setBtRequestFactory(reqFactory); factory->setPeerConnection(peerConnection); - PeerObjectHandle peerObject = new PeerObject(); + PeerObjectHandle peerObject(new PeerObject()); peerObject->btMessageDispatcher = dispatcher; peerObject->btMessageReceiver = receiver; peerObject->btMessageFactory = factory; diff --git a/src/PeerInteractionCommand.h b/src/PeerInteractionCommand.h index ced42d6a..f8430cf7 100644 --- a/src/PeerInteractionCommand.h +++ b/src/PeerInteractionCommand.h @@ -71,7 +71,7 @@ public: const SharedHandle& btContext, const SharedHandle& s, Seq sequence, - const SharedHandle& peerConnection = 0); + const SharedHandle& peerConnection = SharedHandle()); virtual ~PeerInteractionCommand(); diff --git a/src/PeerListenCommand.cc b/src/PeerListenCommand.cc index 9403bffc..1b01b98e 100644 --- a/src/PeerListenCommand.cc +++ b/src/PeerListenCommand.cc @@ -65,6 +65,7 @@ PeerListenCommand::~PeerListenCommand() bool PeerListenCommand::bindPort(uint16_t& port, IntSequence& seq) { + socket.reset(new SocketCore()); while(seq.hasNext()) { int sport = seq.next(); if(!(0 < sport && sport <= UINT16_MAX)) { @@ -93,7 +94,7 @@ bool PeerListenCommand::execute() { for(int i = 0; i < 3 && socket->isReadable(0); i++) { SocketHandle peerSocket; try { - peerSocket = socket->acceptConnection(); + peerSocket.reset(socket->acceptConnection()); std::pair peerInfo; peerSocket->getPeerInfo(peerInfo); std::pair localInfo; @@ -106,7 +107,7 @@ bool PeerListenCommand::execute() { // here. peerSocket->setBlockingMode(); - PeerHandle peer = new Peer(peerInfo.first, 0); + PeerHandle peer(new Peer(peerInfo.first, 0)); int32_t cuid = CUIDCounterSingletonHolder::instance()->newID(); Command* command = new ReceiverMSEHandshakeCommand(cuid, peer, e, peerSocket); diff --git a/src/PeerObject.h b/src/PeerObject.h index 59e382cc..f83f95a5 100644 --- a/src/PeerObject.h +++ b/src/PeerObject.h @@ -48,13 +48,6 @@ class PeerConnection; class PeerObject { public: - PeerObject():btMessageFactory(0), - btRequestFactory(0), - btMessageDispatcher(0), - btMessageReceiver(0), - peerConnection(0), - extensionMessageFactory(0) {} - SharedHandle btMessageFactory; SharedHandle btRequestFactory; SharedHandle btMessageDispatcher; diff --git a/src/PeerReceiveHandshakeCommand.cc b/src/PeerReceiveHandshakeCommand.cc index b37e5aa1..80db9991 100644 --- a/src/PeerReceiveHandshakeCommand.cc +++ b/src/PeerReceiveHandshakeCommand.cc @@ -65,7 +65,7 @@ PeerReceiveHandshakeCommand::PeerReceiveHandshakeCommand(int32_t cuid, _thresholdSpeed(SLOW_SPEED_THRESHOLD) { if(_peerConnection.isNull()) { - _peerConnection = new PeerConnection(cuid, socket, e->option); + _peerConnection.reset(new PeerConnection(cuid, socket, e->option)); } unsigned int maxDownloadSpeed = e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT); if(maxDownloadSpeed > 0) { diff --git a/src/PeerReceiveHandshakeCommand.h b/src/PeerReceiveHandshakeCommand.h index 620b2e90..b0ec6887 100644 --- a/src/PeerReceiveHandshakeCommand.h +++ b/src/PeerReceiveHandshakeCommand.h @@ -58,7 +58,7 @@ public: const SharedHandle& peer, DownloadEngine* e, const SharedHandle& s, - const SharedHandle& peerConnection = 0); + const SharedHandle& peerConnection = SharedHandle()); virtual ~PeerReceiveHandshakeCommand(); diff --git a/src/PieceHashCheckIntegrityEntry.cc b/src/PieceHashCheckIntegrityEntry.cc index 0bedd95c..188e8670 100644 --- a/src/PieceHashCheckIntegrityEntry.cc +++ b/src/PieceHashCheckIntegrityEntry.cc @@ -56,9 +56,9 @@ bool PieceHashCheckIntegrityEntry::isValidationReady() void PieceHashCheckIntegrityEntry::initValidator() { #ifdef ENABLE_MESSAGE_DIGEST - IteratableChunkChecksumValidatorHandle validator = - new IteratableChunkChecksumValidator(_requestGroup->getDownloadContext(), - _requestGroup->getPieceStorage()); + IteratableChunkChecksumValidatorHandle validator + (new IteratableChunkChecksumValidator(_requestGroup->getDownloadContext(), + _requestGroup->getPieceStorage())); validator->init(); _validator = validator; #endif // ENABLE_MESSAGE_DIGEST diff --git a/src/ReceiverMSEHandshakeCommand.cc b/src/ReceiverMSEHandshakeCommand.cc index e01cf346..75240f8c 100644 --- a/src/ReceiverMSEHandshakeCommand.cc +++ b/src/ReceiverMSEHandshakeCommand.cc @@ -90,8 +90,8 @@ bool ReceiverMSEHandshakeCommand::executeInternal() if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { throw new DlAbortEx("The legacy BitTorrent handshake is not acceptable by the preference."); } - SharedHandle peerConnection = - new PeerConnection(cuid, socket, e->option); + SharedHandle peerConnection + (new PeerConnection(cuid, socket, e->option)); peerConnection->presetBuffer(_mseHandshake->getBuffer(), _mseHandshake->getBufferLength()); Command* c = new PeerReceiveHandshakeCommand(cuid, peer, e, socket, @@ -138,8 +138,8 @@ bool ReceiverMSEHandshakeCommand::executeInternal() case RECEIVER_RECEIVE_IA: { if(_mseHandshake->receiveReceiverIA()) { _mseHandshake->sendReceiverStep2(); - SharedHandle peerConnection = - new PeerConnection(cuid, socket, e->option); + SharedHandle peerConnection + (new PeerConnection(cuid, socket, e->option)); if(_mseHandshake->getNegotiatedCryptoType() == MSEHandshake::CRYPTO_ARC4) { peerConnection->enableEncryption(_mseHandshake->getEncryptor(), _mseHandshake->getDecryptor()); diff --git a/src/RequestGroup.cc b/src/RequestGroup.cc index a0cea123..bdfc6736 100644 --- a/src/RequestGroup.cc +++ b/src/RequestGroup.cc @@ -110,13 +110,8 @@ RequestGroup::RequestGroup(const Option* option, _numConcurrentCommand(0), _numStreamConnection(0), _numCommand(0), - _segmentMan(0), _segmentManFactory(new DefaultSegmentManFactory(option)), - _downloadContext(0), - _pieceStorage(0), _progressInfoFile(new NullProgressInfoFile()), - _diskWriterFactory(0), - _dependency(0), _preLocalFileCheckEnabled(true), _haltRequested(false), _forceHaltRequested(false), @@ -171,7 +166,7 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) { #ifdef ENABLE_BITTORRENT { - BtContextHandle btContext = _downloadContext; + BtContextHandle btContext = dynamic_pointer_cast(_downloadContext); if(!btContext.isNull()) { if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) { throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD, @@ -188,10 +183,10 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) _pieceStorage->setFileFilter(Util::parseIntRange(_option->get(PREF_SELECT_FILE))); } - BtProgressInfoFileHandle progressInfoFile = - new DefaultBtProgressInfoFile(_downloadContext, - _pieceStorage, - _option); + BtProgressInfoFileHandle + progressInfoFile(new DefaultBtProgressInfoFile(_downloadContext, + _pieceStorage, + _option)); BtRegistry::registerBtContext(btContext->getInfoHashAsString(), btContext); BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(), @@ -200,19 +195,22 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) progressInfoFile); - BtRuntimeHandle btRuntime = new BtRuntime(); + BtRuntimeHandle btRuntime(new BtRuntime()); btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT)); BtRegistry::registerBtRuntime(btContext->getInfoHashAsString(), btRuntime); - PeerStorageHandle peerStorage = new DefaultPeerStorage(btContext, _option); + PeerStorageHandle peerStorage(new DefaultPeerStorage(btContext, _option)); BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage); - BtAnnounceHandle btAnnounce = new DefaultBtAnnounce(btContext, _option); + BtAnnounceHandle btAnnounce(new DefaultBtAnnounce(btContext, _option)); BtRegistry::registerBtAnnounce(btContext->getInfoHashAsString(), btAnnounce); btAnnounce->shuffleAnnounce(); - BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); + { + SharedHandle po(new PeerObjectCluster()); + BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), + po); + } // Remove the control file if download file doesn't exist if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) { @@ -254,7 +252,7 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) e->commands.push_back(command); } } - CheckIntegrityEntryHandle entry = new BtCheckIntegrityEntry(this); + CheckIntegrityEntryHandle entry(new BtCheckIntegrityEntry(this)); return processCheckIntegrityEntry(entry, e); } @@ -270,13 +268,15 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) getFilePath().c_str()); } initPieceStorage(); - BtProgressInfoFileHandle infoFile = - new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option); + BtProgressInfoFileHandle + infoFile(new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option)); if(!infoFile->exists() && downloadFinishedByFileLength()) { return Commands(); } loadAndOpenFile(infoFile); - return processCheckIntegrityEntry(new StreamCheckIntegrityEntry(0, this), e); + SharedHandle + checkIntegrityEntry(new StreamCheckIntegrityEntry(SharedHandle(), this)); + return processCheckIntegrityEntry(checkIntegrityEntry, e); } } @@ -301,13 +301,13 @@ Commands RequestGroup::processCheckIntegrityEntry(const CheckIntegrityEntryHandl void RequestGroup::initPieceStorage() { if(_downloadContext->getTotalLength() == 0) { - UnknownLengthPieceStorageHandle ps = new UnknownLengthPieceStorage(_downloadContext, _option); + UnknownLengthPieceStorageHandle ps(new UnknownLengthPieceStorage(_downloadContext, _option)); if(!_diskWriterFactory.isNull()) { ps->setDiskWriterFactory(_diskWriterFactory); } _pieceStorage = ps; } else { - DefaultPieceStorageHandle ps = new DefaultPieceStorage(_downloadContext, _option); + DefaultPieceStorageHandle ps(new DefaultPieceStorage(_downloadContext, _option)); if(!_diskWriterFactory.isNull()) { ps->setDiskWriterFactory(_diskWriterFactory); } @@ -416,7 +416,9 @@ bool RequestGroup::tryAutoFileRenaming() for(unsigned int i = 1; i < 10000; ++i) { File newfile(filepath+"."+Util::uitos(i)); if(!newfile.exists()) { - SingleFileDownloadContextHandle(_downloadContext)->setUFilename(newfile.getBasename()); + SingleFileDownloadContextHandle ctx = + dynamic_pointer_cast(_downloadContext); + ctx->setUFilename(newfile.getBasename()); return true; } } @@ -445,15 +447,18 @@ Commands RequestGroup::createNextCommand(DownloadEngine* e, unsigned int numComm std::deque pendingURIs; for(;!_uris.empty() && numCommand--; _uris.pop_front()) { std::string uri = _uris.front(); - RequestHandle req = new Request(); + RequestHandle req(new Request()); if(req->setUrl(uri)) { - ServerHostHandle sv = _singleHostMultiConnectionEnabled ? 0 : searchServerHost(req->getHost()); + ServerHostHandle sv; + if(!_singleHostMultiConnectionEnabled){ + sv = searchServerHost(req->getHost()); + } if(sv.isNull()) { _spentUris.push_back(uri); req->setReferer(_option->get(PREF_REFERER)); req->setMethod(method); Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(), req, this, e); - ServerHostHandle sv = new ServerHost(command->getCuid(), req->getHost()); + ServerHostHandle sv(new ServerHost(command->getCuid(), req->getHost())); registerServerHost(sv); commands.push_back(command); } else { @@ -554,7 +559,7 @@ unsigned int RequestGroup::getNumConnection() const unsigned int numConnection = _numStreamConnection; #ifdef ENABLE_BITTORRENT { - BtContextHandle btContext = _downloadContext; + BtContextHandle btContext = dynamic_pointer_cast(_downloadContext); if(!btContext.isNull()) { BtRuntimeHandle btRuntime = BT_RUNTIME(btContext); if(!btRuntime.isNull()) { @@ -582,7 +587,7 @@ TransferStat RequestGroup::calculateStat() TransferStat stat; #ifdef ENABLE_BITTORRENT { - BtContextHandle btContext = _downloadContext; + BtContextHandle btContext = dynamic_pointer_cast(_downloadContext); if(!btContext.isNull()) { PeerStorageHandle peerStorage = PEER_STORAGE(btContext); if(!peerStorage.isNull()) { @@ -602,7 +607,7 @@ void RequestGroup::setHaltRequested(bool f) _haltRequested = f; #ifdef ENABLE_BITTORRENT { - BtContextHandle btContext = _downloadContext; + BtContextHandle btContext = dynamic_pointer_cast(_downloadContext); if(!btContext.isNull()) { BtRuntimeHandle btRuntime = BT_RUNTIME(btContext); if(!btRuntime.isNull()) { @@ -622,7 +627,7 @@ void RequestGroup::setForceHaltRequested(bool f) void RequestGroup::releaseRuntimeResource() { #ifdef ENABLE_BITTORRENT - BtContextHandle btContext = _downloadContext; + BtContextHandle btContext = dynamic_pointer_cast(_downloadContext); if(!btContext.isNull()) { BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString()); if(!btContextInReg.isNull() && @@ -809,14 +814,15 @@ bool RequestGroup::needsFileAllocation() const DownloadResultHandle RequestGroup::createDownloadResult() const { std::deque uris = getUris(); - return new DownloadResult(_gid, - getFilePath(), - getTotalLength(), - uris.empty() ? "":uris.front(), - uris.size(), - downloadFinished()? - DownloadResult::FINISHED : - DownloadResult::NOT_YET); + return + SharedHandle(new DownloadResult(_gid, + getFilePath(), + getTotalLength(), + uris.empty() ? "":uris.front(), + uris.size(), + downloadFinished()? + DownloadResult::FINISHED : + DownloadResult::NOT_YET)); } void RequestGroup::registerServerHost(const ServerHostHandle& serverHost) @@ -842,7 +848,7 @@ ServerHostHandle RequestGroup::searchServerHost(int32_t cuid) const std::deque >::const_iterator itr = std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid)); if(itr == _serverHosts.end()) { - return 0; + return SharedHandle(); } else { return *itr; } @@ -866,7 +872,7 @@ ServerHostHandle RequestGroup::searchServerHost(const std::string& hostname) con std::deque >::const_iterator itr = std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByHostname(hostname)); if(itr == _serverHosts.end()) { - return 0; + return SharedHandle(); } else { return *itr; } @@ -898,7 +904,8 @@ void RequestGroup::reportDownloadFinished() getFilePath().c_str()); #ifdef ENABLE_BITTORRENT TransferStat stat = calculateStat(); - if(!BtContextHandle(_downloadContext).isNull()) { + SharedHandle ctx = dynamic_pointer_cast(_downloadContext); + if(!ctx.isNull()) { double shareRatio = ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0; _logger->notice(MSG_SHARE_RATIO_REPORT, shareRatio, diff --git a/src/RequestGroupMan.cc b/src/RequestGroupMan.cc index 01ad37c2..cd713fb3 100644 --- a/src/RequestGroupMan.cc +++ b/src/RequestGroupMan.cc @@ -95,7 +95,7 @@ RequestGroupHandle RequestGroupMan::getRequestGroup(size_t index) const if(index < _requestGroups.size()) { return _requestGroups[index]; } else { - return 0; + return SharedHandle(); } } diff --git a/src/SegmentMan.cc b/src/SegmentMan.cc index 0f99628c..673eb2f9 100644 --- a/src/SegmentMan.cc +++ b/src/SegmentMan.cc @@ -102,17 +102,17 @@ SegmentHandle SegmentMan::checkoutSegment(int32_t cuid, const PieceHandle& piece) { if(piece.isNull()) { - return 0; + return SharedHandle(); } logger->debug("Attach segment#%d to CUID#%d.", piece->getIndex(), cuid); - SegmentHandle segment = 0; + SegmentHandle segment; if(piece->getLength() == 0) { - segment = new GrowSegment(piece); + segment.reset(new GrowSegment(piece)); } else { - segment = new PiecedSegment(_downloadContext->getPieceLength(), piece); + segment.reset(new PiecedSegment(_downloadContext->getPieceLength(), piece)); } - SegmentEntryHandle entry = new SegmentEntry(cuid, segment); + SegmentEntryHandle entry(new SegmentEntry(cuid, segment)); usedSegmentEntries.push_back(entry); logger->debug("index=%d, length=%d, segmentLength=%d, writtenLength=%d", @@ -125,7 +125,7 @@ SegmentHandle SegmentMan::checkoutSegment(int32_t cuid, SegmentEntryHandle SegmentMan::findSlowerSegmentEntry(const PeerStatHandle& peerStat) const { unsigned int speed = peerStat->getAvgDownloadSpeed()*0.8; - SegmentEntryHandle slowSegmentEntry(0); + SegmentEntryHandle slowSegmentEntry; for(SegmentEntries::const_iterator itr = usedSegmentEntries.begin(); itr != usedSegmentEntries.end(); ++itr) { const SegmentEntryHandle& segmentEntry = *itr; @@ -165,7 +165,7 @@ SegmentHandle SegmentMan::getSegment(int32_t cuid) { if(piece.isNull()) { PeerStatHandle myPeerStat = getPeerStat(cuid); if(myPeerStat.isNull()) { - return 0; + return SharedHandle(); } SegmentEntryHandle slowSegmentEntry = findSlowerSegmentEntry(myPeerStat); if(slowSegmentEntry.get()) { @@ -178,7 +178,7 @@ SegmentHandle SegmentMan::getSegment(int32_t cuid) { cancelSegment(slowSegmentEntry->cuid); return checkoutSegment(cuid, slowSegmentEntry->segment->getPiece()); } else { - return 0; + return SharedHandle(); } } else { return checkoutSegment(cuid, piece); @@ -187,7 +187,7 @@ SegmentHandle SegmentMan::getSegment(int32_t cuid) { SegmentHandle SegmentMan::getSegment(int32_t cuid, size_t index) { if(_downloadContext->getNumPieces() <= index) { - return 0; + return SharedHandle(); } return checkoutSegment(cuid, _pieceStorage->getMissingPiece(index)); } @@ -257,7 +257,7 @@ PeerStatHandle SegmentMan::getPeerStat(int32_t cuid) const return peerStat; } } - return 0; + return SharedHandle(); } unsigned int SegmentMan::calculateDownloadSpeed() const { diff --git a/src/SegmentMan.h b/src/SegmentMan.h index 3d933538..8807ee48 100644 --- a/src/SegmentMan.h +++ b/src/SegmentMan.h @@ -85,8 +85,8 @@ private: SegmentEntryHandle findSlowerSegmentEntry(const SharedHandle& peerStat) const; public: SegmentMan(const Option* option, - const SharedHandle& downloadContext = 0, - const SharedHandle& pieceStorage = 0); + const SharedHandle& downloadContext, + const SharedHandle& pieceStorage); ~SegmentMan(); diff --git a/src/SharedHandle.h b/src/SharedHandle.h index a5669ed0..a507903b 100644 --- a/src/SharedHandle.h +++ b/src/SharedHandle.h @@ -39,15 +39,131 @@ namespace aria2 { +typedef struct StrongRef {} StrongRef; +typedef struct WeakRef {} WeakRef; + class RefCount { +private: + size_t _strongRefCount; + size_t _weakRefCount; public: - RefCount():totalRefCount(0), strongRefCount(0) {} + RefCount():_strongRefCount(1), _weakRefCount(1) {} - RefCount(unsigned int totalRefCount, unsigned int strongRefCount) - :totalRefCount(totalRefCount), strongRefCount(strongRefCount) {} + RefCount(const WeakRef&):_strongRefCount(0), _weakRefCount(1) {} + + inline void addRefCount() { + ++_strongRefCount; + ++_weakRefCount; + } + + inline void addWeakRefCount() { + ++_weakRefCount; + } + + inline void releaseRefCount() { + --_strongRefCount; + --_weakRefCount; + } + + inline void releaseWeakRefCount() { + --_weakRefCount; + } + + inline size_t getStrongRefCount() { return _strongRefCount; } + + inline size_t getWeakRefCount() { return _weakRefCount; } +}; + +class WeakCount; + +class SharedCount { +private: + friend class WeakCount; + + RefCount* _refCount; +public: + SharedCount():_refCount(new RefCount()) {} + + SharedCount(const SharedCount& s):_refCount(s._refCount) + { + _refCount->addRefCount(); + } + + ~SharedCount() { + _refCount->releaseRefCount(); + if(_refCount->getWeakRefCount() == 0) { + delete _refCount; + } + } + + bool reassign(const SharedCount& s) { + s._refCount->addRefCount(); + _refCount->releaseRefCount(); + if(_refCount->getWeakRefCount() == 0) { + delete _refCount; + _refCount = s._refCount; + return true; + } + size_t thisCount = _refCount->getStrongRefCount(); + _refCount = s._refCount; + return thisCount == 0; + } + + inline size_t getRefCount() const { return _refCount->getStrongRefCount(); } +}; + +class WeakCount { +private: + RefCount* _refCount; +public: + WeakCount(const WeakRef& t):_refCount(new RefCount(t)) {} + + WeakCount(const StrongRef& t):_refCount(new RefCount()) {} + + WeakCount(const WeakCount& w):_refCount(w._refCount) + { + _refCount->addWeakRefCount(); + } + + WeakCount(const SharedCount& s):_refCount(s._refCount) + { + _refCount->addWeakRefCount(); + } + + ~WeakCount() + { + _refCount->releaseWeakRefCount(); + if(_refCount->getWeakRefCount() == 0) { + delete _refCount; + } + } + + bool reassign(const SharedCount& s) { + s._refCount->addWeakRefCount(); + _refCount->releaseWeakRefCount(); + if(_refCount->getWeakRefCount() == 0) { + delete _refCount; + _refCount = s._refCount; + return true; + } + _refCount = s._refCount; + return false; + } + + bool reassign(const WeakCount& s) { + s._refCount->addWeakRefCount(); + _refCount->releaseWeakRefCount(); + if(_refCount->getWeakRefCount() == 0) { + delete _refCount; + _refCount = s._refCount; + return true; + } + _refCount = s._refCount; + return false; + } + + inline size_t getRefCount() const { return _refCount->getStrongRefCount(); } - unsigned int totalRefCount; - unsigned int strongRefCount; }; template @@ -73,70 +189,46 @@ private: template friend bool operator<(const SharedHandle& t1, const SharedHandle& t2); + template friend class SharedHandle; + + template friend class WeakHandle; + T* obj; - RefCount* ucount; - - void releaseReference() { - if(--ucount->strongRefCount == 0) { - delete obj; - obj = 0; - } - if(--ucount->totalRefCount == 0) { - delete ucount; - ucount = 0; - } - } + SharedCount ucount; public: - SharedHandle():obj(new T()), ucount(new RefCount(1, 1)) {} + SharedHandle():obj(0), ucount() {} - SharedHandle(T* obj):obj(obj), ucount(new RefCount(1, 1)) {} - - SharedHandle(const SharedHandle& t):obj(t.get()), ucount(t.getRefCount()) { - ++ucount->totalRefCount; - ++ucount->strongRefCount; - } + explicit SharedHandle(T* obj):obj(obj), ucount() {} template - SharedHandle(const SharedHandle& t) { - obj = dynamic_cast(t.get()); - if(obj) { - ucount = t.getRefCount(); - ++ucount->totalRefCount; - ++ucount->strongRefCount; - } else { - ucount = new RefCount(1, 1); + SharedHandle(const SharedHandle& t):obj(t.obj), ucount(t.ucount) {} + + template + SharedHandle(const SharedHandle& t, T* p): + obj(p), ucount(t.ucount) {} + + ~SharedHandle() { + if(ucount.getRefCount() == 1) { + delete obj; } } - ~SharedHandle() { - releaseReference(); - } - - SharedHandle& operator=(const SharedHandle& t) { - ++t.getRefCount()->totalRefCount; - ++t.getRefCount()->strongRefCount; - releaseReference(); - obj = t.get(); - ucount = t.getRefCount(); + SharedHandle& operator=(const SharedHandle& t) { + if(ucount.reassign(t.ucount)) { + delete obj; + } + obj = t.obj; return *this; } template SharedHandle& operator=(const SharedHandle& t) { - T* to = dynamic_cast(t.get()); - if(to) { - ++t.getRefCount()->totalRefCount; - ++t.getRefCount()->strongRefCount; - releaseReference(); - obj = to; - ucount = t.getRefCount(); - } else { - releaseReference(); - obj = 0; - ucount = new RefCount(1, 1); + if(ucount.reassign(t.ucount)) { + delete obj; } + obj = t.obj; return *this; } @@ -148,8 +240,16 @@ public: return obj; } - RefCount* getRefCount() const { - return ucount; + size_t getRefCount() const { + return ucount.getRefCount(); + } + + void reset() { + *this = SharedHandle(); + } + + void reset(T* t) { + *this = SharedHandle(t); } bool isNull() const { @@ -157,6 +257,16 @@ public: } }; +template +SharedHandle +dynamic_pointer_cast(const SharedHandle& t) { + if(T* p = dynamic_cast(t.get())) { + return SharedHandle(t, p); + } else { + return SharedHandle(); + } +} + template std::ostream& operator<<(std::ostream& o, const SharedHandle& sp) { o << *sp.obj; @@ -195,88 +305,43 @@ private: template friend bool operator<(const WeakHandle& t1, const WeakHandle& t2); + template friend class WeakHandle; + T* obj; - RefCount* ucount; + WeakCount ucount; - void releaseReference() { - if(--ucount->totalRefCount == 0) { - delete ucount; - ucount = 0; - } - } public: - WeakHandle():obj(0), ucount(new RefCount(1, 0)) {} + WeakHandle():obj(0), ucount(WeakRef()) {} - WeakHandle(T* obj):obj(obj), ucount(new RefCount(1, 1)) {} - - WeakHandle(const WeakHandle& t):obj(t.get()), ucount(t.getRefCount()) { - ++ucount->totalRefCount; - } + explicit WeakHandle(T* obj):obj(obj), ucount(StrongRef()) {} template - WeakHandle(const SharedHandle& t):obj(t.get()), ucount(t.getRefCount()) { - obj = dynamic_cast(t.get()); - if(obj) { - ucount = t.getRefCount(); - ++ucount->totalRefCount; - } else { - ucount = new RefCount(1, 0); - } - } + WeakHandle(const SharedHandle& t):obj(t.obj), ucount(t.ucount) {} template - WeakHandle(const WeakHandle& t) { - obj = dynamic_cast(t.get()); - if(obj) { - ucount = t.getRefCount(); - ++ucount->totalRefCount; - } else { - ucount = new RefCount(1, 0); - } - } + WeakHandle(const WeakHandle& t, T* p): + obj(p), ucount(t.ucount) {} - ~WeakHandle() { - releaseReference(); - } + ~WeakHandle() {} WeakHandle& operator=(const WeakHandle& t) { - ++t.getRefCount()->totalRefCount; - releaseReference(); - obj = t.get(); - ucount = t.getRefCount(); + ucount.reassign(t.ucount); + obj = t.obj; return *this; } template WeakHandle& operator=(const SharedHandle& t) { - T* to = dynamic_cast(t.get()); - if(to) { - ++t.getRefCount()->totalRefCount; - releaseReference(); - obj = to; - ucount = t.getRefCount(); - } else { - releaseReference(); - obj = 0; - ucount = new RefCount(1, 0); - } + ucount.reassign(t.ucount); + obj = t.obj; return *this; } template WeakHandle& operator=(const WeakHandle& t) { - T* to = dynamic_cast(t.get()); - if(to) { - ++t.getRefCount()->totalRefCount; - releaseReference(); - obj = to; - ucount = t.getRefCount(); - } else { - releaseReference(); - obj = 0; - ucount = new RefCount(1, 0); - } + ucount.reassign(t.ucount); + obj = t.obj; return *this; } @@ -292,12 +357,16 @@ public: } } - RefCount* getRefCount() const { - return ucount; + size_t getRefCount() const { + return ucount.getRefCount(); + } + + void reset() { + *this = WeakHandle(); } bool isNull() const { - return ucount->strongRefCount == 0 || obj == 0; + return ucount.getRefCount() == 0 || obj == 0; } }; @@ -322,6 +391,16 @@ bool operator<(const WeakHandle& t1, const WeakHandle& t2) { return *t1.obj < *t2.obj; } +template +WeakHandle +dynamic_pointer_cast(const WeakHandle& t) { + if(T* p = dynamic_cast(t.get())) { + return WeakHandle(t, p); + } else { + return WeakHandle(); + } +} + } // namespace aria2 #endif // _D_SHARED_HANDLE_H_ diff --git a/src/SimpleRandomizer.cc b/src/SimpleRandomizer.cc index 93f1b0b0..28dce73b 100644 --- a/src/SimpleRandomizer.cc +++ b/src/SimpleRandomizer.cc @@ -36,6 +36,6 @@ namespace aria2 { -RandomizerHandle SimpleRandomizer::randomizer = 0; +RandomizerHandle SimpleRandomizer::randomizer; } // namespace aria2 diff --git a/src/SimpleRandomizer.h b/src/SimpleRandomizer.h index 125018d1..26d281a2 100644 --- a/src/SimpleRandomizer.h +++ b/src/SimpleRandomizer.h @@ -50,7 +50,7 @@ public: static RandomizerHandle getInstance() { if(randomizer.isNull()) { - randomizer = new SimpleRandomizer(); + randomizer.reset(new SimpleRandomizer()); } return randomizer; } diff --git a/src/SingletonHolder.h b/src/SingletonHolder.h index ba69e838..a63c2fe9 100644 --- a/src/SingletonHolder.h +++ b/src/SingletonHolder.h @@ -58,7 +58,7 @@ public: }; template -T SingletonHolder::_instance = 0; +T SingletonHolder::_instance; } // namespace aria2 diff --git a/src/StreamCheckIntegrityEntry.cc b/src/StreamCheckIntegrityEntry.cc index 46249125..2ba38983 100644 --- a/src/StreamCheckIntegrityEntry.cc +++ b/src/StreamCheckIntegrityEntry.cc @@ -53,9 +53,9 @@ StreamCheckIntegrityEntry::~StreamCheckIntegrityEntry() {} Commands StreamCheckIntegrityEntry::onDownloadIncomplete(DownloadEngine* e) { Commands commands; - FileAllocationEntryHandle entry = - new StreamFileAllocationEntry(_currentRequest, _requestGroup, - popNextCommand()); + FileAllocationEntryHandle entry + (new StreamFileAllocationEntry(_currentRequest, _requestGroup, + popNextCommand())); if(_requestGroup->needsFileAllocation()) { e->_fileAllocationMan->pushFileAllocationEntry(entry); } else { diff --git a/src/TagContainer.cc b/src/TagContainer.cc index 0dc41777..911ee2d3 100644 --- a/src/TagContainer.cc +++ b/src/TagContainer.cc @@ -102,7 +102,7 @@ TaggedItemHandle TagContainer::nameMatch(const std::string& name) const { TaggedItems::const_iterator itr = std::find(_taggedItems.begin(), _taggedItems.end(), TaggedItemHandle(new TaggedItem(name))); if(itr == _taggedItems.end()) { - return 0; + return SharedHandle(); } else { return *itr; } diff --git a/src/TaggedItem.cc b/src/TaggedItem.cc index 4accb514..503e0b1f 100644 --- a/src/TaggedItem.cc +++ b/src/TaggedItem.cc @@ -74,4 +74,23 @@ bool TaggedItem::operator==(const TaggedItem& item) const return _name == item._name; } +std::string TaggedItem::toString() const +{ + return toTagString(); +} + +std::ostream& +operator<<(std::ostream& o, const TaggedItem& item) +{ + o << item.toString(); + return o; +} + +std::ostream& +operator<<(std::ostream& o, const SharedHandle& item) +{ + o << (*item.get()).toString(); + return o; +} + } // namespace aria2 diff --git a/src/TaggedItem.h b/src/TaggedItem.h index bcfa4d87..76dae619 100644 --- a/src/TaggedItem.h +++ b/src/TaggedItem.h @@ -69,6 +69,14 @@ public: bool operator<(const TaggedItem& item) const; bool operator==(const TaggedItem& item) const; + + virtual std::string toString() const; + + friend std::ostream& + operator<<(std::ostream& o, const TaggedItem& item); + + friend std::ostream& + operator<<(std::ostream& o, const SharedHandle& item); }; typedef SharedHandle TaggedItemHandle; diff --git a/src/TrackerWatcherCommand.cc b/src/TrackerWatcherCommand.cc index 9180c272..0d470362 100644 --- a/src/TrackerWatcherCommand.cc +++ b/src/TrackerWatcherCommand.cc @@ -64,10 +64,7 @@ TrackerWatcherCommand::TrackerWatcherCommand(int32_t cuid, Command(cuid), BtContextAwareCommand(btContext), RequestGroupAware(requestGroup), - e(e), - _trackerRequestGroup(0) -{ -} + e(e) {} TrackerWatcherCommand::~TrackerWatcherCommand() {} @@ -109,11 +106,11 @@ bool TrackerWatcherCommand::execute() { btAnnounce->resetAnnounce(); } } - _trackerRequestGroup = 0; + _trackerRequestGroup.reset(); } else if(_trackerRequestGroup->getNumCommand() == 0){ // handle errors here btAnnounce->announceFailure(); // inside it, trackers = 0. - _trackerRequestGroup = 0; + _trackerRequestGroup.reset(); if(btAnnounce->isAllAnnounceFailed()) { btAnnounce->resetAnnounce(); } @@ -160,7 +157,7 @@ void TrackerWatcherCommand::processTrackerResponse(const std::string& trackerRes } RequestGroupHandle TrackerWatcherCommand::createAnnounce() { - RequestGroupHandle rg = 0; + RequestGroupHandle rg; if(btAnnounce->isAnnounceReady()) { rg = createRequestGroup(btAnnounce->getAnnounceUrl()); btAnnounce->announceStart(); // inside it, trackers++. @@ -173,16 +170,17 @@ TrackerWatcherCommand::createRequestGroup(const std::string& uri) { std::deque uris; uris.push_back(uri); - RequestGroupHandle rg = new RequestGroup(e->option, uris); + RequestGroupHandle rg(new RequestGroup(e->option, uris)); - SingleFileDownloadContextHandle dctx = - new SingleFileDownloadContext(e->option->getAsInt(PREF_SEGMENT_SIZE), - 0, - "", - "[tracker.announce]"); + SingleFileDownloadContextHandle dctx + (new SingleFileDownloadContext(e->option->getAsInt(PREF_SEGMENT_SIZE), + 0, + "", + "[tracker.announce]")); dctx->setDir(""); rg->setDownloadContext(dctx); - rg->setDiskWriterFactory(new ByteArrayDiskWriterFactory()); + SharedHandle dwf(new ByteArrayDiskWriterFactory()); + rg->setDiskWriterFactory(dwf); rg->setFileAllocationEnabled(false); rg->setPreLocalFileCheckEnabled(false); logger->info("Creating tracker request group GID#%d", rg->getGID()); diff --git a/src/UTPexExtensionMessage.cc b/src/UTPexExtensionMessage.cc index 603b38d6..5139ece3 100644 --- a/src/UTPexExtensionMessage.cc +++ b/src/UTPexExtensionMessage.cc @@ -52,14 +52,13 @@ namespace aria2 { const std::string UTPexExtensionMessage::EXTENSION_NAME = "ut_pex"; UTPexExtensionMessage::UTPexExtensionMessage(uint8_t extensionMessageID): - _extensionMessageID(extensionMessageID), - _btContext(0) {} + _extensionMessageID(extensionMessageID) {} UTPexExtensionMessage::~UTPexExtensionMessage() {} std::string UTPexExtensionMessage::getBencodedData() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); std::pair freshPeerPair = createCompactPeerListAndFlag(_freshPeers); std::pair droppedPeerPair = createCompactPeerListAndFlag(_droppedPeers); d->put("added", new Data(freshPeerPair.first)); @@ -129,8 +128,8 @@ UTPexExtensionMessage::create(const BtContextHandle& btContext, throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE, EXTENSION_NAME.c_str(), len); } - UTPexExtensionMessageHandle msg = new UTPexExtensionMessage(*data); - SharedHandle root = MetaFileUtil::bdecoding(data+1, len-1); + UTPexExtensionMessageHandle msg(new UTPexExtensionMessage(*data)); + SharedHandle root(MetaFileUtil::bdecoding(data+1, len-1)); if(root.isNull()) { return msg; } diff --git a/src/UnknownLengthPieceStorage.cc b/src/UnknownLengthPieceStorage.cc index f74d7544..5515b92a 100644 --- a/src/UnknownLengthPieceStorage.cc +++ b/src/UnknownLengthPieceStorage.cc @@ -48,18 +48,16 @@ UnknownLengthPieceStorage::UnknownLengthPieceStorage(const DownloadContextHandle const Option* option): _downloadContext(downloadContext), _option(option), - _diskAdaptor(0), _diskWriterFactory(new DefaultDiskWriterFactory()), _totalLength(0), - _downloadFinished(false), - _piece(0) {} + _downloadFinished(false) {} UnknownLengthPieceStorage::~UnknownLengthPieceStorage() {} void UnknownLengthPieceStorage::initStorage() { DiskWriterHandle writer = _diskWriterFactory->newDiskWriter(); - DirectDiskAdaptorHandle directDiskAdaptor = new DirectDiskAdaptor(); + DirectDiskAdaptorHandle directDiskAdaptor(new DirectDiskAdaptor()); directDiskAdaptor->setDiskWriter(writer); directDiskAdaptor->setTotalLength(_downloadContext->getTotalLength()); _diskAdaptor = directDiskAdaptor; @@ -89,13 +87,13 @@ SharedHandle UnknownLengthPieceStorage::getMissingFastPiece(const SharedH PieceHandle UnknownLengthPieceStorage::getMissingPiece() { if(_downloadFinished) { - return 0; + return SharedHandle(); } if(_piece.isNull()) { - _piece = new Piece(); + _piece.reset(new Piece()); return _piece; } else { - return 0; + return SharedHandle(); } } @@ -104,7 +102,7 @@ PieceHandle UnknownLengthPieceStorage::getMissingPiece(size_t index) if(index == 0) { return getMissingPiece(); } else { - return 0; + return SharedHandle(); } } @@ -112,12 +110,12 @@ PieceHandle UnknownLengthPieceStorage::getPiece(size_t index) { if(index == 0) { if(_piece.isNull()) { - return new Piece(); + return SharedHandle(new Piece()); } else { return _piece; } } else { - return 0; + return SharedHandle(); } } @@ -127,14 +125,14 @@ void UnknownLengthPieceStorage::completePiece(const PieceHandle& piece) _downloadFinished = true; _totalLength = _piece->getLength(); _diskAdaptor->setTotalLength(_totalLength); - _piece = 0; + _piece.reset(); } } void UnknownLengthPieceStorage::cancelPiece(const PieceHandle& piece) { if(_piece == piece) { - _piece = 0; + _piece.reset(); } } @@ -174,7 +172,7 @@ void UnknownLengthPieceStorage::markAllPiecesDone() { if(!_piece.isNull()) { _totalLength = _piece->getLength(); - _piece = 0; + _piece.reset(); } _downloadFinished = true; } diff --git a/src/XML2SAXMetalinkProcessor.cc b/src/XML2SAXMetalinkProcessor.cc index e169eee8..0e2c7cf1 100644 --- a/src/XML2SAXMetalinkProcessor.cc +++ b/src/XML2SAXMetalinkProcessor.cc @@ -119,15 +119,13 @@ static xmlSAXHandler mySAXHandler = 0, // xmlStructuredErrorFunc }; -XML2SAXMetalinkProcessor::XML2SAXMetalinkProcessor(): - _stm(0) -{} +XML2SAXMetalinkProcessor::XML2SAXMetalinkProcessor() {} SharedHandle XML2SAXMetalinkProcessor::parseFile(const std::string& filename) { - _stm = new MetalinkParserStateMachine(); - SharedHandle sessionData = new SessionData(_stm); + _stm.reset(new MetalinkParserStateMachine()); + SharedHandle sessionData(new SessionData(_stm)); int retval = xmlSAXUserParseFile(&mySAXHandler, sessionData.get(), filename.c_str()); if(retval != 0) { @@ -139,7 +137,7 @@ XML2SAXMetalinkProcessor::parseFile(const std::string& filename) SharedHandle XML2SAXMetalinkProcessor::parseFromBinaryStream(const SharedHandle& binaryStream) { - _stm = new MetalinkParserStateMachine(); + _stm.reset(new MetalinkParserStateMachine()); size_t bufSize = 4096; unsigned char buf[bufSize]; @@ -148,7 +146,7 @@ XML2SAXMetalinkProcessor::parseFromBinaryStream(const SharedHandle throw new DlAbortEx("Too small data for parsing XML."); } - SharedHandle sessionData = new SessionData(_stm); + SharedHandle sessionData(new SessionData(_stm)); xmlParserCtxtPtr ctx = xmlCreatePushParserCtxt(&mySAXHandler, sessionData.get(), (const char*)buf, res, 0); try { off_t readOffset = res; diff --git a/src/main.cc b/src/main.cc index 8fe77b85..43ba7585 100644 --- a/src/main.cc +++ b/src/main.cc @@ -108,12 +108,12 @@ std::deque unfoldURI(const std::deque& args) RequestGroupHandle createRequestGroup(const Option* op, const std::deque& uris, const std::string& ufilename = "") { - RequestGroupHandle rg = new RequestGroup(op, uris); - SingleFileDownloadContextHandle dctx = - new SingleFileDownloadContext(op->getAsInt(PREF_SEGMENT_SIZE), + RequestGroupHandle rg(new RequestGroup(op, uris)); + SingleFileDownloadContextHandle dctx + (new SingleFileDownloadContext(op->getAsInt(PREF_SEGMENT_SIZE), 0, "", - ufilename); + ufilename)); dctx->setDir(op->get(PREF_DIR)); rg->setDownloadContext(dctx); return rg; @@ -128,8 +128,8 @@ createBtRequestGroup(const std::string& torrentFilePath, Option* op, const std::deque& auxUris) { - SharedHandle rg = new RequestGroup(op, auxUris); - SharedHandle btContext = new DefaultBtContext(); + SharedHandle rg(new RequestGroup(op, auxUris)); + SharedHandle btContext(new DefaultBtContext()); btContext->load(torrentFilePath);// may throw exception if(op->defined(PREF_PEER_ID_PREFIX)) { btContext->setPeerIdPrefix(op->get(PREF_PEER_ID_PREFIX)); @@ -307,7 +307,7 @@ int main(int argc, char* argv[]) logger->info("%s %s %s", PACKAGE, PACKAGE_VERSION, TARGET); logger->info(MSG_LOGGING_STARTED); - AuthConfigFactoryHandle authConfigFactory = new AuthConfigFactory(op); + AuthConfigFactoryHandle authConfigFactory(new AuthConfigFactory(op)); File netrccf(op->get(PREF_NETRC_PATH)); if(!op->getAsBool(PREF_NO_NETRC) && netrccf.isFile()) { mode_t mode = netrccf.mode(); @@ -315,13 +315,13 @@ int main(int argc, char* argv[]) logger->notice(MSG_INCORRECT_NETRC_PERMISSION, op->get(PREF_NETRC_PATH).c_str()); } else { - NetrcHandle netrc = new Netrc(); + NetrcHandle netrc(new Netrc()); netrc->parse(op->get(PREF_NETRC_PATH)); authConfigFactory->setNetrc(netrc); } } - CookieBoxFactoryHandle cookieBoxFactory = new CookieBoxFactory(); + CookieBoxFactoryHandle cookieBoxFactory(new CookieBoxFactory()); CookieBoxFactorySingletonHolder::instance(cookieBoxFactory); if(op->defined(PREF_LOAD_COOKIES)) { File cookieFile(op->get(PREF_LOAD_COOKIES)); @@ -335,7 +335,7 @@ int main(int argc, char* argv[]) } AuthConfigFactorySingleton::instance(authConfigFactory); - CUIDCounterHandle cuidCounter = new CUIDCounter(); + CUIDCounterHandle cuidCounter(new CUIDCounter()); CUIDCounterSingletonHolder::instance(cuidCounter); #ifdef ENABLE_MESSAGE_DIGEST MessageDigestHelper::staticSHA1DigestInit(); @@ -348,7 +348,7 @@ int main(int argc, char* argv[]) #ifdef ENABLE_BITTORRENT if(op->defined(PREF_TORRENT_FILE)) { if(op->get(PREF_SHOW_FILES) == V_TRUE) { - DefaultBtContextHandle btContext = new DefaultBtContext(); + DefaultBtContextHandle btContext(new DefaultBtContext()); btContext->load(op->get(PREF_TORRENT_FILE)); std::cout << btContext << std::endl; } else { diff --git a/src/version_usage.cc b/src/version_usage.cc index cf689b33..c4d35bc0 100644 --- a/src/version_usage.cc +++ b/src/version_usage.cc @@ -113,23 +113,26 @@ void showUsage(const std::string& category) { } else { printf(_("Printing options tagged with '%s'."), category.c_str()); std::cout << "\n"; + SharedHandle helpItem + (dynamic_pointer_cast(tc->nameMatch("help"))); printf(_("See -h option to know other command-line options(%s)."), - SharedHandle(tc->nameMatch("help"))->getAvailableValues().c_str()); + helpItem->getAvailableValues().c_str()); } std::cout << "\n" << _("Options:") << "\n"; - std::copy(items.begin(), items.end(), std::ostream_iterator >(std::cout, "\n")); + + std::copy(items.begin(), items.end(), std::ostream_iterator >(std::cout, "\n")); + } else { std::deque > items = tc->nameMatchForward(category); if(items.size() > 0) { printf(_("Printing options whose name starts with '%s'."), category.c_str()); std::cout << "\n" << _("Options:") << "\n"; - std::copy(items.begin(), items.end(), std::ostream_iterator >(std::cout, "\n")); + std::copy(items.begin(), items.end(), std::ostream_iterator >(std::cout, "\n")); } else { printf(_("No help category or option name matching with '%s'."), category.c_str()); - std::cout << "\n" - << SharedHandle(tc->nameMatch("help")) << "\n"; + std::cout << "\n" << tc->nameMatch("help") << "\n"; } } if(category == TAG_BASIC) { diff --git a/test/AllTest.cc b/test/AllTest.cc index 416ea574..41e44e95 100644 --- a/test/AllTest.cc +++ b/test/AllTest.cc @@ -32,7 +32,8 @@ int main(int argc, char* argv[]) { gnutls_global_init(); #endif // HAVE_LIBGNUTLS - SharedHandle cookieBoxFactory = new aria2::CookieBoxFactory(); + SharedHandle cookieBoxFactory + (new aria2::CookieBoxFactory()); SingletonHolder >::instance(cookieBoxFactory); // Run the tests. diff --git a/test/AuthConfigFactoryTest.cc b/test/AuthConfigFactoryTest.cc index 1b8357e4..8a9fcd44 100644 --- a/test/AuthConfigFactoryTest.cc +++ b/test/AuthConfigFactoryTest.cc @@ -27,7 +27,7 @@ CPPUNIT_TEST_SUITE_REGISTRATION( AuthConfigFactoryTest ); void AuthConfigFactoryTest::testCreateAuthConfig_http() { - SharedHandle req = new Request(); + SharedHandle req(new Request()); req->setUrl("http://localhost/download/aria2-1.0.0.tar.bz2"); Option option; @@ -40,8 +40,9 @@ void AuthConfigFactoryTest::testCreateAuthConfig_http() factory.createAuthConfig(req)->getAuthText()); // with Netrc: disabled by default - SharedHandle netrc = new Netrc(); - netrc->addAuthenticator(new DefaultAuthenticator("default", "defaultpassword", "defaultaccount")); + SharedHandle netrc(new Netrc()); + netrc->addAuthenticator + (SharedHandle(new DefaultAuthenticator("default", "defaultpassword", "defaultaccount"))); factory.setNetrc(netrc); CPPUNIT_ASSERT_EQUAL(std::string(":"), factory.createAuthConfig(req)->getAuthText()); @@ -63,11 +64,12 @@ void AuthConfigFactoryTest::testCreateAuthConfig_http() void AuthConfigFactoryTest::testCreateAuthConfigForHttpProxy() { - SharedHandle req = new Request(); + SharedHandle req(new Request()); req->setUrl("http://localhost/download/aria2-1.0.0.tar.bz2"); // with Netrc - SharedHandle netrc = new Netrc(); - netrc->addAuthenticator(new DefaultAuthenticator("default", "defaultpassword", "defaultaccount")); + SharedHandle netrc(new Netrc()); + netrc->addAuthenticator + (SharedHandle(new DefaultAuthenticator("default", "defaultpassword", "defaultaccount"))); Option option; option.put(PREF_NO_NETRC, V_FALSE); @@ -88,7 +90,7 @@ void AuthConfigFactoryTest::testCreateAuthConfigForHttpProxy() void AuthConfigFactoryTest::testCreateAuthConfig_ftp() { - SharedHandle req = new Request(); + SharedHandle req(new Request()); req->setUrl("ftp://localhost/download/aria2-1.0.0.tar.bz2"); Option option; @@ -101,8 +103,9 @@ void AuthConfigFactoryTest::testCreateAuthConfig_ftp() factory.createAuthConfig(req)->getAuthText()); // with Netrc - SharedHandle netrc = new Netrc(); - netrc->addAuthenticator(new DefaultAuthenticator("default", "defaultpassword", "defaultaccount")); + SharedHandle netrc(new Netrc()); + netrc->addAuthenticator + (SharedHandle(new DefaultAuthenticator("default", "defaultpassword", "defaultaccount"))); factory.setNetrc(netrc); CPPUNIT_ASSERT_EQUAL(std::string("default:defaultpassword"), factory.createAuthConfig(req)->getAuthText()); diff --git a/test/BNodeTest.cc b/test/BNodeTest.cc index 8aafa639..9b353517 100644 --- a/test/BNodeTest.cc +++ b/test/BNodeTest.cc @@ -36,9 +36,9 @@ void BNodeTest::testIsInRange() unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0xff, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); - SharedHandle bucket1 = new DHTBucket(localNode); + SharedHandle bucket1(new DHTBucket(localNode)); SharedHandle bucket2 = bucket1->split(); SharedHandle bucket3 = bucket1->split(); @@ -57,9 +57,9 @@ void BNodeTest::testFindBucketFor() unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0xaa, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); - SharedHandle bucket1 = new DHTBucket(localNode); + SharedHandle bucket1(new DHTBucket(localNode)); SharedHandle bucket2 = bucket1->split(); SharedHandle bucket3 = bucket1->split(); SharedHandle bucket4 = bucket3->split(); @@ -107,9 +107,9 @@ void BNodeTest::testFindClosestKNodes() unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0xaa, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); - SharedHandle bucket1 = new DHTBucket(localNode); + SharedHandle bucket1(new DHTBucket(localNode)); SharedHandle bucket2 = bucket1->split(); SharedHandle bucket3 = bucket1->split(); SharedHandle bucket4 = bucket3->split(); @@ -142,15 +142,15 @@ void BNodeTest::testFindClosestKNodes() for(size_t i = 0; i < 2; ++i) { bucket1->getRandomNodeID(id); - bucket1->addNode(new DHTNode(id)); + bucket1->addNode(SharedHandle(new DHTNode(id))); bucket2->getRandomNodeID(id); - bucket2->addNode(new DHTNode(id)); + bucket2->addNode(SharedHandle(new DHTNode(id))); bucket3->getRandomNodeID(id); - bucket3->addNode(new DHTNode(id)); + bucket3->addNode(SharedHandle(new DHTNode(id))); bucket4->getRandomNodeID(id); - bucket4->addNode(new DHTNode(id)); + bucket4->addNode(SharedHandle(new DHTNode(id))); bucket5->getRandomNodeID(id); - bucket5->addNode(new DHTNode(id)); + bucket5->addNode(SharedHandle(new DHTNode(id))); } { unsigned char targetID[DHT_ID_LENGTH]; @@ -183,7 +183,7 @@ void BNodeTest::testFindClosestKNodes() { for(size_t i = 0; i < 6; ++i) { bucket4->getRandomNodeID(id); - bucket4->addNode(new DHTNode(id)); + bucket4->addNode(SharedHandle(new DHTNode(id))); } unsigned char targetID[DHT_ID_LENGTH]; memset(targetID, 0x80, DHT_ID_LENGTH); @@ -203,9 +203,9 @@ void BNodeTest::testEnumerateBucket() unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0xaa, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); - SharedHandle bucket1 = new DHTBucket(localNode); + SharedHandle bucket1(new DHTBucket(localNode)); SharedHandle bucket2 = bucket1->split(); SharedHandle bucket3 = bucket1->split(); SharedHandle bucket4 = bucket3->split(); diff --git a/test/BencodeVisitorTest.cc b/test/BencodeVisitorTest.cc index 0e780378..7b6af005 100644 --- a/test/BencodeVisitorTest.cc +++ b/test/BencodeVisitorTest.cc @@ -32,14 +32,14 @@ void BencodeVisitorTest::testVisit_data() { BencodeVisitor v; std::string str = "apple"; - MetaEntryHandle m = new Data(str.c_str(), str.size()); + MetaEntryHandle m(new Data(str.c_str(), str.size())); m->accept(&v); CPPUNIT_ASSERT_EQUAL(std::string("5:apple"), v.getBencodedData()); } { BencodeVisitor v; std::string str = "123"; - MetaEntryHandle m = new Data(str.c_str(), str.size(), true); + MetaEntryHandle m(new Data(str.c_str(), str.size(), true)); m->accept(&v); CPPUNIT_ASSERT_EQUAL(std::string("i123e"), v.getBencodedData()); } diff --git a/test/BitfieldManTest.cc b/test/BitfieldManTest.cc index cc46f7c6..00451fbc 100644 --- a/test/BitfieldManTest.cc +++ b/test/BitfieldManTest.cc @@ -30,10 +30,10 @@ private: SharedHandle fixedNumberRandomizer; public: - BitfieldManTest():fixedNumberRandomizer(0) { + BitfieldManTest() { FixedNumberRandomizer* randomizer = new FixedNumberRandomizer(); randomizer->setFixedNumber(0); - this->fixedNumberRandomizer = randomizer; + this->fixedNumberRandomizer.reset(randomizer); } void setUp() { diff --git a/test/BtAllowedFastMessageTest.cc b/test/BtAllowedFastMessageTest.cc index 57d573f2..69a2639d 100644 --- a/test/BtAllowedFastMessageTest.cc +++ b/test/BtAllowedFastMessageTest.cc @@ -70,7 +70,7 @@ void BtAllowedFastMessageTest::testGetMessage() { void BtAllowedFastMessageTest::testDoReceivedAction() { BtAllowedFastMessage msg; msg.setIndex(1); - SharedHandle peer = new Peer("localhost", 6969); + SharedHandle peer(new Peer("localhost", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->setFastExtensionEnabled(true); msg.setPeer(peer); @@ -88,7 +88,7 @@ void BtAllowedFastMessageTest::testDoReceivedAction() { void BtAllowedFastMessageTest::testOnSendComplete() { BtAllowedFastMessage msg; msg.setIndex(1); - SharedHandle peer = new Peer("localhost", 6969); + SharedHandle peer(new Peer("localhost", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->setFastExtensionEnabled(true); msg.setPeer(peer); diff --git a/test/BtBitfieldMessageTest.cc b/test/BtBitfieldMessageTest.cc index 6f765674..51e4cca7 100644 --- a/test/BtBitfieldMessageTest.cc +++ b/test/BtBitfieldMessageTest.cc @@ -70,7 +70,7 @@ void BtBitfieldMessageTest::testGetMessage() { } void BtBitfieldMessageTest::testDoReceivedAction() { - SharedHandle peer = new Peer("host1", 6969); + SharedHandle peer(new Peer("host1", 6969)); peer->allocateSessionResource(16*1024, 16*16*1024); BtBitfieldMessage msg; msg.setPeer(peer); diff --git a/test/BtCancelMessageTest.cc b/test/BtCancelMessageTest.cc index 4554d775..a09bc76c 100644 --- a/test/BtCancelMessageTest.cc +++ b/test/BtCancelMessageTest.cc @@ -25,21 +25,23 @@ class BtCancelMessageTest:public CppUnit::TestFixture { CPPUNIT_TEST(testDoReceivedAction); CPPUNIT_TEST_SUITE_END(); private: - -public: - BtCancelMessageTest():peer(0), btContext(0) {} - SharedHandle peer; SharedHandle btContext; - +public: void setUp() { BtRegistry::unregisterAll(); - peer = new Peer("host", 6969); - btContext = new MockBtContext(); + peer.reset(new Peer("host", 6969)); + btContext.reset(new MockBtContext()); btContext->setInfoHash((const unsigned char*)"12345678901234567890"); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); - PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), new PeerObject()); + cluster); + SharedHandle po(new PeerObject()); + PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po); + } + + void tearDown() { + BtRegistry::unregisterAll(); } void testCreate(); @@ -117,7 +119,7 @@ void BtCancelMessageTest::testDoReceivedAction() { msg.setLength(16*1024); msg.setBtContext(btContext); msg.setPeer(peer); - SharedHandle dispatcher = new MockBtMessageDispatcher2(); + SharedHandle dispatcher(new MockBtMessageDispatcher2()); msg.setBtMessageDispatcher(dispatcher); msg.doReceivedAction(); diff --git a/test/BtChokeMessageTest.cc b/test/BtChokeMessageTest.cc index cf56119d..758ed5df 100644 --- a/test/BtChokeMessageTest.cc +++ b/test/BtChokeMessageTest.cc @@ -35,13 +35,15 @@ public: void setUp() { BtRegistry::unregisterAll(); - peer = new Peer("host", 6969); + peer.reset(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); - btContext = new MockBtContext(); + btContext.reset(new MockBtContext()); btContext->setInfoHash((const unsigned char*)"12345678901234567890"); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); - PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), new PeerObject()); + cluster); + SharedHandle po(new PeerObject()); + PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po); } void testCreate(); @@ -117,9 +119,9 @@ void BtChokeMessageTest::testDoReceivedAction() { msg.setPeer(peer); msg.setBtContext(btContext); - SharedHandle dispatcher = new MockBtMessageDispatcher2(); + SharedHandle dispatcher(new MockBtMessageDispatcher2()); msg.setBtMessageDispatcher(dispatcher); - SharedHandle requestFactory = new MockBtRequestFactory2(); + SharedHandle requestFactory(new MockBtRequestFactory2()); msg.setBtRequestFactory(requestFactory); msg.doReceivedAction(); @@ -133,7 +135,7 @@ void BtChokeMessageTest::testOnSendComplete() { msg.setPeer(peer); msg.setBtContext(btContext); - SharedHandle dispatcher = new MockBtMessageDispatcher2(); + SharedHandle dispatcher(new MockBtMessageDispatcher2()); msg.setBtMessageDispatcher(dispatcher); msg.onSendComplete(); diff --git a/test/BtDependencyTest.cc b/test/BtDependencyTest.cc index dd576079..6aa4d968 100644 --- a/test/BtDependencyTest.cc +++ b/test/BtDependencyTest.cc @@ -23,9 +23,9 @@ class BtDependencyTest:public CppUnit::TestFixture { SharedHandle createDependant(const Option* option) { - SharedHandle dependant = new RequestGroup(option, std::deque()); - SharedHandle dctx = - new SingleFileDownloadContext(0, 0, ""); + SharedHandle dependant(new RequestGroup(option, std::deque())); + SharedHandle dctx + (new SingleFileDownloadContext(0, 0, "")); dctx->setDir("/tmp"); dependant->setDownloadContext(dctx); return dependant; @@ -34,12 +34,13 @@ class BtDependencyTest:public CppUnit::TestFixture { SharedHandle createDependee(const Option* option, const std::string& torrentFile, int64_t length) { - SharedHandle dependee = new RequestGroup(option, std::deque()); - SharedHandle dctx = - new SingleFileDownloadContext(1024*1024, length, torrentFile); + SharedHandle dependee + (new RequestGroup(option, std::deque())); + SharedHandle dctx + (new SingleFileDownloadContext(1024*1024, length, torrentFile)); dctx->setDir("."); dependee->setDownloadContext(dctx); - DefaultPieceStorageHandle ps = new DefaultPieceStorage(dctx, option); + DefaultPieceStorageHandle ps(new DefaultPieceStorage(dctx, option)); dependee->setPieceStorage(ps); ps->initStorage(); dependee->initSegmentMan(); @@ -69,7 +70,8 @@ void BtDependencyTest::testResolve() BtDependency dep(dependant, dependee, &option); CPPUNIT_ASSERT(dep.resolve()); - SharedHandle btContext = dependant->getDownloadContext(); + SharedHandle btContext + (dynamic_pointer_cast(dependant->getDownloadContext())); CPPUNIT_ASSERT(!btContext.isNull()); CPPUNIT_ASSERT_EQUAL(std::string("/tmp/aria2-test"), btContext->getActualBasePath()); } @@ -85,7 +87,8 @@ void BtDependencyTest::testResolve_loadError() BtDependency dep(dependant, dependee, &option); CPPUNIT_ASSERT(dep.resolve()); - SharedHandle dctx = dependant->getDownloadContext(); + SharedHandle dctx + (dynamic_pointer_cast(dependant->getDownloadContext())); CPPUNIT_ASSERT(!dctx.isNull()); CPPUNIT_ASSERT_EQUAL(std::string("/tmp/index.html"), dctx->getActualBasePath()); } catch(Exception* e) { @@ -104,7 +107,8 @@ void BtDependencyTest::testResolve_dependeeFailure() BtDependency dep(dependant, dependee, &option); CPPUNIT_ASSERT(dep.resolve()); - SharedHandle dctx = dependant->getDownloadContext(); + SharedHandle dctx + (dynamic_pointer_cast(dependant->getDownloadContext())); CPPUNIT_ASSERT(!dctx.isNull()); CPPUNIT_ASSERT_EQUAL(std::string("/tmp/index.html"), dctx->getActualBasePath()); } diff --git a/test/BtExtendedMessageTest.cc b/test/BtExtendedMessageTest.cc index ba8d42a8..fc4b547b 100644 --- a/test/BtExtendedMessageTest.cc +++ b/test/BtExtendedMessageTest.cc @@ -49,17 +49,18 @@ public: CPPUNIT_TEST_SUITE_REGISTRATION(BtExtendedMessageTest); void BtExtendedMessageTest::testCreate() { - SharedHandle peer = new Peer("192.168.0.1", 6969); + SharedHandle peer(new Peer("192.168.0.1", 6969)); peer->allocateSessionResource(1024, 1024*1024); - SharedHandle ctx = new MockBtContext(); + SharedHandle ctx(new MockBtContext()); unsigned char infohash[20]; memset(infohash, 0, sizeof(infohash)); ctx->setInfoHash(infohash); - SharedHandle exmsgFactory = new MockExtensionMessageFactory(); - + SharedHandle exmsgFactory + (new MockExtensionMessageFactory()); - BtRegistry::registerPeerObjectCluster(ctx->getInfoHashAsString(), new PeerObjectCluster()); - SharedHandle peerObject = new PeerObject(); + SharedHandle cluster(new PeerObjectCluster()); + BtRegistry::registerPeerObjectCluster(ctx->getInfoHashAsString(), cluster); + SharedHandle peerObject(new PeerObject()); peerObject->extensionMessageFactory = exmsgFactory; PEER_OBJECT_CLUSTER(ctx)->registerHandle(peer->getID(), peerObject); @@ -100,8 +101,8 @@ void BtExtendedMessageTest::testCreate() { void BtExtendedMessageTest::testGetMessage() { std::string payload = "4:name3:foo"; uint8_t extendedMessageID = 1; - SharedHandle exmsg = - new MockExtensionMessage("charlie", extendedMessageID, payload); + SharedHandle exmsg + (new MockExtensionMessage("charlie", extendedMessageID, payload)); BtExtendedMessage msg(exmsg); unsigned char data[17]; @@ -112,8 +113,8 @@ void BtExtendedMessageTest::testGetMessage() { } void BtExtendedMessageTest::testDoReceivedAction() { - SharedHandle exmsg = - new MockExtensionMessage("charlie", 1, ""); + SharedHandle exmsg + (new MockExtensionMessage("charlie", 1, "")); BtExtendedMessage msg(exmsg); msg.doReceivedAction(); CPPUNIT_ASSERT(exmsg->_doReceivedActionCalled); @@ -122,8 +123,8 @@ void BtExtendedMessageTest::testDoReceivedAction() { void BtExtendedMessageTest::testToString() { std::string payload = "4:name3:foo"; uint8_t extendedMessageID = 1; - SharedHandle exmsg = - new MockExtensionMessage("charlie", extendedMessageID, payload); + SharedHandle exmsg + (new MockExtensionMessage("charlie", extendedMessageID, payload)); BtExtendedMessage msg(exmsg); CPPUNIT_ASSERT_EQUAL(std::string("extended charlie"), msg.toString()); } diff --git a/test/BtHandshakeMessageTest.cc b/test/BtHandshakeMessageTest.cc index d845f2bd..ae626e3a 100644 --- a/test/BtHandshakeMessageTest.cc +++ b/test/BtHandshakeMessageTest.cc @@ -78,7 +78,7 @@ void BtHandshakeMessageTest::testGetMessage() { 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0 }; - SharedHandle msg = new BtHandshakeMessage(); + SharedHandle msg(new BtHandshakeMessage()); msg->setInfoHash(infoHash); msg->setPeerId(peerId); diff --git a/test/BtHaveAllMessageTest.cc b/test/BtHaveAllMessageTest.cc index 9351eefa..a32e601d 100644 --- a/test/BtHaveAllMessageTest.cc +++ b/test/BtHaveAllMessageTest.cc @@ -60,7 +60,7 @@ void BtHaveAllMessageTest::testGetMessage() { void BtHaveAllMessageTest::testDoReceivedAction() { BtHaveAllMessage msg; - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(16*1024, 256*1024); peer->setFastExtensionEnabled(true); msg.setPeer(peer); diff --git a/test/BtHaveMessageTest.cc b/test/BtHaveMessageTest.cc index 5081bfb3..2aa91d5b 100644 --- a/test/BtHaveMessageTest.cc +++ b/test/BtHaveMessageTest.cc @@ -65,7 +65,7 @@ void BtHaveMessageTest::testGetMessage() { } void BtHaveMessageTest::testDoReceivedAction() { - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(16*1024, 256*1024); BtHaveMessage msg; msg.setIndex(1); diff --git a/test/BtHaveNoneMessageTest.cc b/test/BtHaveNoneMessageTest.cc index 8acaa10b..d5bbded2 100644 --- a/test/BtHaveNoneMessageTest.cc +++ b/test/BtHaveNoneMessageTest.cc @@ -62,7 +62,7 @@ void BtHaveNoneMessageTest::testGetMessage() { void BtHaveNoneMessageTest::testDoReceivedAction() { BtHaveNoneMessage msg; - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->setFastExtensionEnabled(true); msg.setPeer(peer); diff --git a/test/BtInterestedMessageTest.cc b/test/BtInterestedMessageTest.cc index 23f32349..51c4e522 100644 --- a/test/BtInterestedMessageTest.cc +++ b/test/BtInterestedMessageTest.cc @@ -64,7 +64,7 @@ void BtInterestedMessageTest::testGetMessage() { void BtInterestedMessageTest::testDoReceivedAction() { BtInterestedMessage msg; - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); msg.setPeer(peer); CPPUNIT_ASSERT(!peer->peerInterested()); @@ -74,7 +74,7 @@ void BtInterestedMessageTest::testDoReceivedAction() { void BtInterestedMessageTest::testOnSendComplete() { BtInterestedMessage msg; - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); msg.setPeer(peer); CPPUNIT_ASSERT(!peer->amInterested()); diff --git a/test/BtNotInterestedMessageTest.cc b/test/BtNotInterestedMessageTest.cc index cca0fc9f..7827bd27 100644 --- a/test/BtNotInterestedMessageTest.cc +++ b/test/BtNotInterestedMessageTest.cc @@ -63,7 +63,7 @@ void BtNotInterestedMessageTest::testGetMessage() { } void BtNotInterestedMessageTest::testDoReceivedAction() { - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->peerInterested(true); BtNotInterestedMessage msg; @@ -74,7 +74,7 @@ void BtNotInterestedMessageTest::testDoReceivedAction() { } void BtNotInterestedMessageTest::testOnSendComplete() { - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->amInterested(true); BtNotInterestedMessage msg; diff --git a/test/BtPieceMessageTest.cc b/test/BtPieceMessageTest.cc index 219cf67b..19183f34 100644 --- a/test/BtPieceMessageTest.cc +++ b/test/BtPieceMessageTest.cc @@ -15,6 +15,7 @@ #include "BtRequestFactory.h" #include "PeerConnection.h" #include "ExtensionMessageFactory.h" +#include "BtHandshakeMessage.h" #include #include @@ -36,10 +37,9 @@ class BtPieceMessageTest:public CppUnit::TestFixture { CPPUNIT_TEST(testCancelSendingPieceEvent_invalidate); CPPUNIT_TEST(testCancelSendingPieceEvent_sendingInProgress); CPPUNIT_TEST(testToString); + CPPUNIT_TEST_SUITE_END(); public: - BtPieceMessageTest():btMessageDispatcher(0), peer(0), msg(0) {} - void testCreate(); void testGetMessageHeader(); void testChokingEvent(); @@ -70,7 +70,7 @@ public: createRejectMessage(size_t index, uint32_t begin, size_t length) { - SharedHandle msg = new MockBtMessage2(index, begin, length); + SharedHandle msg(new MockBtMessage2(index, begin, length)); return msg; } }; @@ -81,23 +81,24 @@ public: void setUp() { BtRegistry::unregisterAll(); - - SharedHandle btContext; + SharedHandle btContext(new MockBtContext()); btContext->setInfoHash((const unsigned char*)"12345678901234567890"); btContext->setPieceLength(16*1024); btContext->setTotalLength(256*1024); - peer = new Peer("host", 6969); + peer.reset(new Peer("host", 6969)); peer->allocateSessionResource(btContext->getPieceLength(), btContext->getTotalLength()); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); - PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), new PeerObject()); - btMessageDispatcher = new MockBtMessageDispatcher(); + cluster); + SharedHandle po(new PeerObject()); + PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po); + btMessageDispatcher.reset(new MockBtMessageDispatcher()); PEER_OBJECT(btContext, peer)->btMessageDispatcher = btMessageDispatcher; - PEER_OBJECT(btContext, peer)->btMessageFactory = new MockBtMessageFactory2(); + PEER_OBJECT(btContext, peer)->btMessageFactory.reset(new MockBtMessageFactory2()); - msg = new BtPieceMessage(); + msg.reset(new BtPieceMessage()); msg->setIndex(1); msg->setBegin(1024); msg->setBlockLength(16*1024); @@ -162,7 +163,7 @@ void BtPieceMessageTest::testChokingEvent() { CPPUNIT_ASSERT(!peer->isInAmAllowedIndexSet(1)); CPPUNIT_ASSERT(!peer->isFastExtensionEnabled()); - msg->handleEvent(new BtChokingEvent()); + msg->handleEvent(SharedHandle(new BtChokingEvent())); CPPUNIT_ASSERT(msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->messageQueue.size()); @@ -176,7 +177,7 @@ void BtPieceMessageTest::testChokingEvent_allowedFastEnabled() { CPPUNIT_ASSERT(!peer->isInAmAllowedIndexSet(1)); CPPUNIT_ASSERT(peer->isFastExtensionEnabled()); - msg->handleEvent(new BtChokingEvent()); + msg->handleEvent(SharedHandle(new BtChokingEvent())); CPPUNIT_ASSERT(msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->messageQueue.size()); @@ -195,7 +196,7 @@ void BtPieceMessageTest::testChokingEvent_inAmAllowedIndexSet() { CPPUNIT_ASSERT(peer->isInAmAllowedIndexSet(1)); CPPUNIT_ASSERT(peer->isFastExtensionEnabled()); - msg->handleEvent(new BtChokingEvent()); + msg->handleEvent(SharedHandle(new BtChokingEvent())); CPPUNIT_ASSERT(!msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->messageQueue.size()); @@ -208,7 +209,7 @@ void BtPieceMessageTest::testChokingEvent_invalidate() { CPPUNIT_ASSERT(!peer->isInAmAllowedIndexSet(1)); CPPUNIT_ASSERT(!peer->isFastExtensionEnabled()); - msg->handleEvent(new BtChokingEvent()); + msg->handleEvent(SharedHandle(new BtChokingEvent())); CPPUNIT_ASSERT(msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->messageQueue.size()); @@ -221,7 +222,7 @@ void BtPieceMessageTest::testChokingEvent_sendingInProgress() { CPPUNIT_ASSERT(!peer->isInAmAllowedIndexSet(1)); CPPUNIT_ASSERT(!peer->isFastExtensionEnabled()); - msg->handleEvent(new BtChokingEvent()); + msg->handleEvent(SharedHandle(new BtChokingEvent())); CPPUNIT_ASSERT(!msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->messageQueue.size()); @@ -232,7 +233,8 @@ void BtPieceMessageTest::testCancelSendingPieceEvent() { CPPUNIT_ASSERT(!msg->isSendingInProgress()); CPPUNIT_ASSERT(!peer->isFastExtensionEnabled()); - msg->handleEvent(new BtCancelSendingPieceEvent(1, 1024, 16*1024)); + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(1, 1024, 16*1024))); CPPUNIT_ASSERT(msg->isInvalidate()); } @@ -242,15 +244,18 @@ void BtPieceMessageTest::testCancelSendingPieceEvent_noMatch() { CPPUNIT_ASSERT(!msg->isSendingInProgress()); CPPUNIT_ASSERT(!peer->isFastExtensionEnabled()); - msg->handleEvent(new BtCancelSendingPieceEvent(0, 1024, 16*1024)); + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(0, 1024, 16*1024))); + + CPPUNIT_ASSERT(!msg->isInvalidate()); + + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(1, 0, 16*1024))); CPPUNIT_ASSERT(!msg->isInvalidate()); - msg->handleEvent(new BtCancelSendingPieceEvent(1, 0, 16*1024)); - - CPPUNIT_ASSERT(!msg->isInvalidate()); - - msg->handleEvent(new BtCancelSendingPieceEvent(1, 1024, 0)); + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(1, 1024, 0))); CPPUNIT_ASSERT(!msg->isInvalidate()); } @@ -261,7 +266,8 @@ void BtPieceMessageTest::testCancelSendingPieceEvent_allowedFastEnabled() { CPPUNIT_ASSERT(!msg->isSendingInProgress()); CPPUNIT_ASSERT(peer->isFastExtensionEnabled()); - msg->handleEvent(new BtCancelSendingPieceEvent(1, 1024, 16*1024)); + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(1, 1024, 16*1024))); CPPUNIT_ASSERT(msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)1, btMessageDispatcher->messageQueue.size()); @@ -278,7 +284,8 @@ void BtPieceMessageTest::testCancelSendingPieceEvent_invalidate() { CPPUNIT_ASSERT(!msg->isSendingInProgress()); CPPUNIT_ASSERT(peer->isFastExtensionEnabled()); - msg->handleEvent(new BtCancelSendingPieceEvent(1, 1024, 16*1024)); + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(1, 1024, 16*1024))); CPPUNIT_ASSERT(msg->isInvalidate()); CPPUNIT_ASSERT_EQUAL((size_t)0, btMessageDispatcher->messageQueue.size()); @@ -290,14 +297,15 @@ void BtPieceMessageTest::testCancelSendingPieceEvent_sendingInProgress() { CPPUNIT_ASSERT(msg->isSendingInProgress()); CPPUNIT_ASSERT(!peer->isFastExtensionEnabled()); - msg->handleEvent(new BtCancelSendingPieceEvent(1, 1024, 16*1024)); + msg->handleEvent + (SharedHandle(new BtCancelSendingPieceEvent(1, 1024, 16*1024))); CPPUNIT_ASSERT(!msg->isInvalidate()); } void BtPieceMessageTest::testToString() { CPPUNIT_ASSERT_EQUAL(std::string("piece index=1, begin=1024, length=16384"), - msg->toString()); + msg->toString()); } } // namespace aria2 diff --git a/test/BtPortMessageTest.cc b/test/BtPortMessageTest.cc index 26dda687..3d2d184c 100644 --- a/test/BtPortMessageTest.cc +++ b/test/BtPortMessageTest.cc @@ -39,13 +39,13 @@ public: virtual SharedHandle createPingTask(const SharedHandle& remoteNode, size_t numRetry) { - return new MockDHTTask(remoteNode); + return SharedHandle(new MockDHTTask(remoteNode)); } virtual SharedHandle createNodeLookupTask(const unsigned char* targetID) { - MockDHTTask* task = new MockDHTTask(0); + SharedHandle task(new MockDHTTask(SharedHandle())); task->setTargetID(targetID); return task; } @@ -98,14 +98,14 @@ void BtPortMessageTest::testDoReceivedAction() { unsigned char nodeID[DHT_ID_LENGTH]; memset(nodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(nodeID); + SharedHandle localNode(new DHTNode(nodeID)); // 9 nodes to create at least 2 buckets. - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[9]; for(size_t i = 0; i < arrayLength(nodes); ++i) { memset(nodeID, 0, DHT_ID_LENGTH); nodeID[DHT_ID_LENGTH-1] = i; - nodes[i] = new DHTNode(nodeID); + nodes[i].reset(new DHTNode(nodeID)); } DHTRoutingTable routingTable(localNode); @@ -113,20 +113,23 @@ void BtPortMessageTest::testDoReceivedAction() routingTable.addNode(nodes[i]); } - SharedHandle peer = new Peer("192.168.0.1", 6881); + SharedHandle peer(new Peer("192.168.0.1", 6881)); BtPortMessage msg(6881); MockDHTTaskQueue taskQueue; MockDHTTaskFactory2 taskFactory; msg.setLocalNode(localNode); - msg.setRoutingTable(&routingTable); - msg.setTaskQueue(&taskQueue); - msg.setTaskFactory(&taskFactory); + msg.setRoutingTable(WeakHandle(&routingTable)); + msg.setTaskQueue(WeakHandle(&taskQueue)); + msg.setTaskFactory(WeakHandle(&taskFactory)); msg.setPeer(peer); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)1, taskQueue._immediateTaskQueue.size()); - SharedHandle node = SharedHandle(taskQueue._immediateTaskQueue.front())->_remoteNode; + + SharedHandle task + (dynamic_pointer_cast(taskQueue._immediateTaskQueue[0])); + SharedHandle node = task->_remoteNode; CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), node->getIPAddress()); CPPUNIT_ASSERT_EQUAL((uint16_t)6881, node->getPort()); } @@ -136,27 +139,30 @@ void BtPortMessageTest::testDoReceivedAction_bootstrap() unsigned char nodeID[DHT_ID_LENGTH]; memset(nodeID, 0, DHT_ID_LENGTH); nodeID[0] = 0xff; - SharedHandle localNode = new DHTNode(nodeID); + SharedHandle localNode(new DHTNode(nodeID)); DHTRoutingTable routingTable(localNode); // no nodes , 1 bucket. - SharedHandle peer = new Peer("192.168.0.1", 6881); + SharedHandle peer(new Peer("192.168.0.1", 6881)); BtPortMessage msg(6881); MockDHTTaskQueue taskQueue; MockDHTTaskFactory2 taskFactory; msg.setLocalNode(localNode); - msg.setRoutingTable(&routingTable); - msg.setTaskQueue(&taskQueue); - msg.setTaskFactory(&taskFactory); + msg.setRoutingTable(WeakHandle(&routingTable)); + msg.setTaskQueue(WeakHandle(&taskQueue)); + msg.setTaskFactory(WeakHandle(&taskFactory)); msg.setPeer(peer); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)2, taskQueue._immediateTaskQueue.size()); - SharedHandle node = SharedHandle(taskQueue._immediateTaskQueue[0])->_remoteNode; + SharedHandle task + (dynamic_pointer_cast(taskQueue._immediateTaskQueue[0])); + SharedHandle node(task->_remoteNode); CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), node->getIPAddress()); CPPUNIT_ASSERT_EQUAL((uint16_t)6881, node->getPort()); - SharedHandle task2 = taskQueue._immediateTaskQueue[1]; + SharedHandle task2 + (dynamic_pointer_cast(taskQueue._immediateTaskQueue[1])); CPPUNIT_ASSERT(memcmp(nodeID, task2->_targetID, DHT_ID_LENGTH) == 0); } diff --git a/test/BtPostDownloadHandlerTest.cc b/test/BtPostDownloadHandlerTest.cc index 8f9e49fe..1c457459 100644 --- a/test/BtPostDownloadHandlerTest.cc +++ b/test/BtPostDownloadHandlerTest.cc @@ -31,7 +31,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION( BtPostDownloadHandlerTest ); void BtPostDownloadHandlerTest::testCanHandle_extension() { Option op; - SharedHandle dctx = new SingleFileDownloadContext(0, 0, "test.torrent"); + SharedHandle dctx + (new SingleFileDownloadContext(0, 0, "test.torrent")); RequestGroup rg(&op, std::deque()); rg.setDownloadContext(dctx); @@ -46,7 +47,8 @@ void BtPostDownloadHandlerTest::testCanHandle_extension() void BtPostDownloadHandlerTest::testCanHandle_contentType() { Option op; - SharedHandle dctx = new SingleFileDownloadContext(0, 0, "test"); + SharedHandle dctx + (new SingleFileDownloadContext(0, 0, "test")); dctx->setContentType("application/x-bittorrent"); RequestGroup rg(&op, std::deque()); rg.setDownloadContext(dctx); @@ -62,7 +64,8 @@ void BtPostDownloadHandlerTest::testCanHandle_contentType() void BtPostDownloadHandlerTest::testGetNextRequestGroups() { Option op; - SharedHandle dctx = new SingleFileDownloadContext(0, 0, "test.torrent"); + SharedHandle dctx + (new SingleFileDownloadContext(0, 0, "test.torrent")); RequestGroup rg(&op, std::deque()); rg.setDownloadContext(dctx); rg.initPieceStorage(); @@ -70,7 +73,8 @@ void BtPostDownloadHandlerTest::testGetNextRequestGroups() BtPostDownloadHandler handler; std::deque > groups = handler.getNextRequestGroups(&rg); CPPUNIT_ASSERT_EQUAL((size_t)1, groups.size()); - SharedHandle btctx = groups.front()->getDownloadContext(); + SharedHandle btctx + (dynamic_pointer_cast(groups.front()->getDownloadContext())); CPPUNIT_ASSERT(!btctx.isNull()); CPPUNIT_ASSERT_EQUAL(std::string("aria2-test"), btctx->getName()); } diff --git a/test/BtRegistryTest.cc b/test/BtRegistryTest.cc index 08898517..028a74d8 100644 --- a/test/BtRegistryTest.cc +++ b/test/BtRegistryTest.cc @@ -57,7 +57,7 @@ CPPUNIT_TEST_SUITE_REGISTRATION( BtRegistryTest ); void BtRegistryTest::testGetBtContext() { CPPUNIT_ASSERT(BtRegistry::getBtContext("test").isNull()); - SharedHandle btContext = new MockBtContext(); + SharedHandle btContext(new MockBtContext()); BtRegistry::registerBtContext("test", btContext); CPPUNIT_ASSERT_EQUAL(btContext.get(), BtRegistry::getBtContext("test").get()); @@ -116,7 +116,8 @@ void BtRegistryTest::testGetBtProgressInfoFile() { void BtRegistryTest::testGetPeerObjectCluster() { CPPUNIT_ASSERT(!BtRegistry::getPeerObjectCluster("test").get()); - BtRegistry::registerPeerObjectCluster("test", new PeerObjectCluster()); + SharedHandle cluster(new PeerObjectCluster()); + BtRegistry::registerPeerObjectCluster("test", cluster); CPPUNIT_ASSERT(BtRegistry::getPeerObjectCluster("test").get()); diff --git a/test/BtRejectMessageTest.cc b/test/BtRejectMessageTest.cc index e92b5875..a9e1c993 100644 --- a/test/BtRejectMessageTest.cc +++ b/test/BtRejectMessageTest.cc @@ -71,29 +71,32 @@ public: SharedHandle dispatcher; SharedHandle msg; - BtRejectMessageTest():peer(0), dispatcher(0), msg(0) {} - void setUp() { BtRegistry::unregisterAll(); - peer = new Peer("host", 6969); + peer.reset(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); - SharedHandle btContext = new MockBtContext(); + SharedHandle btContext(new MockBtContext()); btContext->setInfoHash((const unsigned char*)"12345678901234567890"); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); - PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), new PeerObject()); - dispatcher = new MockBtMessageDispatcher2(); + cluster); + SharedHandle po(new PeerObject()); + PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po); + dispatcher.reset(new MockBtMessageDispatcher2()); PEER_OBJECT(btContext, peer)->btMessageDispatcher = dispatcher; - msg = new BtRejectMessage(); + msg.reset(new BtRejectMessage()); msg->setPeer(peer); msg->setBtContext(btContext); msg->setIndex(1); msg->setBegin(16); msg->setLength(32); msg->setBtMessageDispatcher(dispatcher); + } + void tearDown() { + BtRegistry::unregisterAll(); } }; diff --git a/test/BtRequestMessageTest.cc b/test/BtRequestMessageTest.cc index 1d653e93..69bb4fd6 100644 --- a/test/BtRequestMessageTest.cc +++ b/test/BtRequestMessageTest.cc @@ -15,6 +15,7 @@ #include "PeerConnection.h" #include "ExtensionMessageFactory.h" #include "FileEntry.h" +#include "BtHandshakeMessage.h" #include #include @@ -75,13 +76,13 @@ public: public: virtual SharedHandle createPieceMessage(size_t index, uint32_t begin, size_t length) { - SharedHandle btMsg = new MockBtMessage2("piece", index, begin, length); + SharedHandle btMsg(new MockBtMessage2("piece", index, begin, length)); return btMsg; } virtual SharedHandle createRejectMessage(size_t index, uint32_t begin, size_t length) { - SharedHandle btMsg = new MockBtMessage2("reject", index, begin, length); + SharedHandle btMsg(new MockBtMessage2("reject", index, begin, length)); return btMsg; } }; @@ -92,34 +93,34 @@ public: SharedHandle dispatcher; SharedHandle msg; - BtRequestMessageTest():peer(0), dispatcher(0), msg(0) {} - void setUp() { BtRegistry::unregisterAll(); - SharedHandle btContext = new MockBtContext(); + SharedHandle btContext(new MockBtContext()); btContext->setInfoHash((const unsigned char*)"12345678901234567890"); btContext->setPieceLength(16*1024); btContext->setTotalLength(256*1024); - SharedHandle pieceStorage = new MockPieceStorage2(); + SharedHandle pieceStorage(new MockPieceStorage2()); BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(), pieceStorage); - peer = new Peer("host", 6969); + peer.reset(new Peer("host", 6969)); peer->allocateSessionResource(btContext->getPieceLength(), btContext->getTotalLength()); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); - PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), new PeerObject()); + cluster); + SharedHandle po(new PeerObject()); + PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), po); - dispatcher = new MockBtMessageDispatcher(); + dispatcher.reset(new MockBtMessageDispatcher()); PEER_OBJECT(btContext, peer)->btMessageDispatcher = dispatcher; - PEER_OBJECT(btContext, peer)->btMessageFactory = new MockBtMessageFactory2(); + PEER_OBJECT(btContext, peer)->btMessageFactory.reset(new MockBtMessageFactory2()); - msg = new BtRequestMessage(); + msg.reset(new BtRequestMessage()); msg->setBtContext(btContext); msg->setPeer(peer); msg->setIndex(1); @@ -232,9 +233,9 @@ void BtRequestMessageTest::testDoReceivedAction_doesntHavePieceAndFastExtensionD } void BtRequestMessageTest::testHandleAbortRequestEvent() { - SharedHandle piece = new Piece(1, 16*1024); - SharedHandle event = - new BtAbortOutstandingRequestEvent(piece); + SharedHandle piece(new Piece(1, 16*1024)); + SharedHandle event + (new BtAbortOutstandingRequestEvent(piece)); CPPUNIT_ASSERT(!msg->isInvalidate()); msg->handleEvent(event); @@ -243,9 +244,9 @@ void BtRequestMessageTest::testHandleAbortRequestEvent() { } void BtRequestMessageTest::testHandleAbortRequestEvent_indexNoMatch() { - SharedHandle piece = new Piece(2, 16*1024); - SharedHandle event = - new BtAbortOutstandingRequestEvent(piece); + SharedHandle piece(new Piece(2, 16*1024)); + SharedHandle event + (new BtAbortOutstandingRequestEvent(piece)); CPPUNIT_ASSERT(!msg->isInvalidate()); CPPUNIT_ASSERT(!msg->isSendingInProgress()); @@ -254,9 +255,9 @@ void BtRequestMessageTest::testHandleAbortRequestEvent_indexNoMatch() { } void BtRequestMessageTest::testHandleAbortRequestEvent_alreadyInvalidated() { - SharedHandle piece = new Piece(1, 16*1024); - SharedHandle event = - new BtAbortOutstandingRequestEvent(piece); + SharedHandle piece(new Piece(1, 16*1024)); + SharedHandle event + (new BtAbortOutstandingRequestEvent(piece)); msg->setInvalidate(true); CPPUNIT_ASSERT(msg->isInvalidate()); @@ -266,9 +267,9 @@ void BtRequestMessageTest::testHandleAbortRequestEvent_alreadyInvalidated() { } void BtRequestMessageTest::testHandleAbortRequestEvent_sendingInProgress() { - SharedHandle piece = new Piece(1, 16*1024); - SharedHandle event = - new BtAbortOutstandingRequestEvent(piece); + SharedHandle piece(new Piece(1, 16*1024)); + SharedHandle event + (new BtAbortOutstandingRequestEvent(piece)); msg->setSendingInProgress(true); CPPUNIT_ASSERT(!msg->isInvalidate()); diff --git a/test/BtUnchokeMessageTest.cc b/test/BtUnchokeMessageTest.cc index 9ab7ce6c..99d833f8 100644 --- a/test/BtUnchokeMessageTest.cc +++ b/test/BtUnchokeMessageTest.cc @@ -62,7 +62,7 @@ void BtUnchokeMessageTest::testGetMessage() { } void BtUnchokeMessageTest::testDoReceivedAction() { - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->peerChoking(true); BtUnchokeMessage msg; @@ -74,7 +74,7 @@ void BtUnchokeMessageTest::testDoReceivedAction() { } void BtUnchokeMessageTest::testOnSendComplete() { - SharedHandle peer = new Peer("host", 6969); + SharedHandle peer(new Peer("host", 6969)); peer->allocateSessionResource(1024, 1024*1024); peer->amChoking(true); BtUnchokeMessage msg; diff --git a/test/DHTAnnouncePeerMessageTest.cc b/test/DHTAnnouncePeerMessageTest.cc index c2dd6dff..6a00a7e4 100644 --- a/test/DHTAnnouncePeerMessageTest.cc +++ b/test/DHTAnnouncePeerMessageTest.cc @@ -33,7 +33,7 @@ public: createAnnouncePeerReplyMessage(const SharedHandle& remoteNode, const std::string& transactionID) { - return new MockDHTMessage(_localNode, remoteNode, "announce_peer", transactionID); + return SharedHandle(new MockDHTMessage(_localNode, remoteNode, "announce_peer", transactionID)); } }; }; @@ -43,8 +43,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTAnnouncePeerMessageTest); void DHTAnnouncePeerMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -60,7 +60,7 @@ void DHTAnnouncePeerMessageTest::testGetBencodedMessage() std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("q")); cm->put("q", new Data("announce_peer")); @@ -80,8 +80,8 @@ void DHTAnnouncePeerMessageTest::testGetBencodedMessage() void DHTAnnouncePeerMessageTest::testDoReceivedAction() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); @@ -101,14 +101,16 @@ void DHTAnnouncePeerMessageTest::testDoReceivedAction() MockDHTMessageDispatcher dispatcher; DHTAnnouncePeerMessage msg(localNode, remoteNode, infoHash, port, token, transactionID); - msg.setPeerAnnounceStorage(&peerAnnounceStorage); - msg.setMessageFactory(&factory); - msg.setMessageDispatcher(&dispatcher); + msg.setPeerAnnounceStorage(WeakHandle + (&peerAnnounceStorage)); + msg.setMessageFactory(WeakHandle(&factory)); + msg.setMessageDispatcher(WeakHandle(&dispatcher)); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher._messageQueue.size()); - SharedHandle m = dispatcher._messageQueue[0]._message; + SharedHandle m + (dynamic_pointer_cast(dispatcher._messageQueue[0]._message)); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); CPPUNIT_ASSERT_EQUAL(std::string("announce_peer"), m->getMessageType()); diff --git a/test/DHTAnnouncePeerReplyMessageTest.cc b/test/DHTAnnouncePeerReplyMessageTest.cc index a266bd63..8ccfac51 100644 --- a/test/DHTAnnouncePeerReplyMessageTest.cc +++ b/test/DHTAnnouncePeerReplyMessageTest.cc @@ -28,8 +28,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTAnnouncePeerReplyMessageTest); void DHTAnnouncePeerReplyMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -39,7 +39,7 @@ void DHTAnnouncePeerReplyMessageTest::testGetBencodedMessage() std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("r")); Dictionary* r = new Dictionary(); diff --git a/test/DHTBucketTest.cc b/test/DHTBucketTest.cc index 73f54e85..17907757 100644 --- a/test/DHTBucketTest.cc +++ b/test/DHTBucketTest.cc @@ -48,7 +48,7 @@ void DHTBucketTest::testGetRandomNodeID() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); { DHTBucket bucket(localNode); unsigned char nodeID[DHT_ID_LENGTH]; @@ -77,13 +77,13 @@ void DHTBucketTest::testIsInRange() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); { unsigned char nodeID[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); DHTBucket bucket(localNode); CPPUNIT_ASSERT(bucket.isInRange(node)); memset(nodeID, 0xff, sizeof(nodeID)); @@ -104,7 +104,7 @@ void DHTBucketTest::testIsInRange() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); DHTBucket bucket(16, max, min, localNode); CPPUNIT_ASSERT(bucket.isInRange(node)); } @@ -114,7 +114,7 @@ void DHTBucketTest::testIsInRange() 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); DHTBucket bucket(16, max, min, localNode); CPPUNIT_ASSERT(bucket.isInRange(node)); } @@ -123,7 +123,7 @@ void DHTBucketTest::testIsInRange() 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); DHTBucket bucket(16, max, min, localNode); CPPUNIT_ASSERT(bucket.isInRange(node)); } @@ -133,7 +133,7 @@ void DHTBucketTest::testIsInRange() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); DHTBucket bucket(16, max, min, localNode); CPPUNIT_ASSERT(!bucket.isInRange(node)); } @@ -143,7 +143,7 @@ void DHTBucketTest::testIsInRange() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle node = new DHTNode(nodeID); + SharedHandle node(new DHTNode(nodeID)); DHTBucket bucket(16, max, min, localNode); CPPUNIT_ASSERT(!bucket.isInRange(node)); } @@ -157,7 +157,7 @@ void DHTBucketTest::testSplitAllowed() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); CPPUNIT_ASSERT(bucket.splitAllowed()); } @@ -175,7 +175,7 @@ void DHTBucketTest::testSplitAllowed() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(3, max, min, localNode); CPPUNIT_ASSERT(!bucket.splitAllowed()); } @@ -184,7 +184,7 @@ void DHTBucketTest::testSplitAllowed() 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(3, max, min, localNode); CPPUNIT_ASSERT(bucket.splitAllowed()); } @@ -195,7 +195,7 @@ void DHTBucketTest::testSplit() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); { DHTBucket bucket(localNode); SharedHandle r = bucket.split(); @@ -227,7 +227,7 @@ void DHTBucketTest::testSplit() } } { - SharedHandle bucket = new DHTBucket(localNode); + SharedHandle bucket(new DHTBucket(localNode)); for(int i = 0; i < 159; ++i) { CPPUNIT_ASSERT(bucket->splitAllowed()); SharedHandle t = bucket; @@ -260,18 +260,18 @@ void DHTBucketTest::testAddNode() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); unsigned char id[DHT_ID_LENGTH]; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0xf0, i); - nodes[i] = new DHTNode(id); + nodes[i].reset(new DHTNode(id)); CPPUNIT_ASSERT(bucket.addNode(nodes[i])); } createID(id, 0xf0, 0xff); - SharedHandle newNode = new DHTNode(id); + SharedHandle newNode(new DHTNode(id)); CPPUNIT_ASSERT(!bucket.addNode(newNode)); // nodes[0] is located at the tail of the bucket(least recent seen) @@ -284,14 +284,14 @@ void DHTBucketTest::testMoveToHead() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); unsigned char id[DHT_ID_LENGTH]; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0xf0, i); - nodes[i] = new DHTNode(id); + nodes[i].reset(new DHTNode(id)); CPPUNIT_ASSERT(bucket.addNode(nodes[i])); } bucket.moveToHead(nodes[DHTBucket::K-1]); @@ -302,14 +302,14 @@ void DHTBucketTest::testMoveToTail() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); unsigned char id[DHT_ID_LENGTH]; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0xf0, i); - nodes[i] = new DHTNode(id); + nodes[i].reset(new DHTNode(id)); CPPUNIT_ASSERT(bucket.addNode(nodes[i])); } bucket.moveToTail(nodes[0]); @@ -320,14 +320,14 @@ void DHTBucketTest::testGetGoodNodes() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); unsigned char id[DHT_ID_LENGTH]; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0xf0, i); - nodes[i] = new DHTNode(id); + nodes[i].reset(new DHTNode(id)); nodes[i]->setPort(6881+i); CPPUNIT_ASSERT(bucket.addNode(nodes[i])); } @@ -347,12 +347,12 @@ void DHTBucketTest::testCacheNode() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); - SharedHandle n1 = new DHTNode(); - SharedHandle n2 = new DHTNode(); - SharedHandle n3 = new DHTNode(); + SharedHandle n1(new DHTNode()); + SharedHandle n2(new DHTNode()); + SharedHandle n3(new DHTNode()); bucket.cacheNode(n1); bucket.cacheNode(n2); @@ -369,20 +369,20 @@ void DHTBucketTest::testDropNode() { unsigned char localNodeID[DHT_ID_LENGTH]; memset(localNodeID, 0, DHT_ID_LENGTH); - SharedHandle localNode = new DHTNode(localNodeID); + SharedHandle localNode(new DHTNode(localNodeID)); DHTBucket bucket(localNode); unsigned char id[DHT_ID_LENGTH]; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0xf0, i); - nodes[i] = new DHTNode(id); + nodes[i].reset(new DHTNode(id)); nodes[i]->setPort(6881+i); CPPUNIT_ASSERT(bucket.addNode(nodes[i])); } - SharedHandle cachedNode1 = new DHTNode(); - SharedHandle cachedNode2 = new DHTNode(); + SharedHandle cachedNode1(new DHTNode()); + SharedHandle cachedNode2(new DHTNode()); bucket.dropNode(nodes[3]); // nothing happens because the replacement cache is empty. diff --git a/test/DHTFindNodeMessageTest.cc b/test/DHTFindNodeMessageTest.cc index 3b252831..b544fa6c 100644 --- a/test/DHTFindNodeMessageTest.cc +++ b/test/DHTFindNodeMessageTest.cc @@ -35,8 +35,8 @@ public: const std::deque >& closestKNodes, const std::string& transactionID) { - SharedHandle m = - new MockDHTMessage(_localNode, remoteNode, "find_node", transactionID); + SharedHandle m + (new MockDHTMessage(_localNode, remoteNode, "find_node", transactionID)); m->_nodes = closestKNodes; return m; } @@ -48,20 +48,20 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTFindNodeMessageTest); void DHTFindNodeMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); std::string transactionID(&tid[0], &tid[DHT_TRANSACTION_ID_LENGTH]); - SharedHandle targetNode = new DHTNode(); + SharedHandle targetNode(new DHTNode()); DHTFindNodeMessage msg(localNode, remoteNode, targetNode->getID(), transactionID); std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("q")); cm->put("q", new Data("find_node")); @@ -78,14 +78,14 @@ void DHTFindNodeMessageTest::testGetBencodedMessage() void DHTFindNodeMessageTest::testDoReceivedAction() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); std::string transactionID(&tid[0], &tid[DHT_TRANSACTION_ID_LENGTH]); - SharedHandle targetNode = new DHTNode(); + SharedHandle targetNode(new DHTNode()); MockDHTMessageDispatcher dispatcher; MockDHTMessageFactory2 factory; @@ -94,14 +94,15 @@ void DHTFindNodeMessageTest::testDoReceivedAction() routingTable.addNode(targetNode); DHTFindNodeMessage msg(localNode, remoteNode, targetNode->getID(), transactionID); - msg.setMessageDispatcher(&dispatcher); - msg.setMessageFactory(&factory); - msg.setRoutingTable(&routingTable); + msg.setMessageDispatcher(WeakHandle(&dispatcher)); + msg.setMessageFactory(WeakHandle(&factory)); + msg.setRoutingTable(WeakHandle(&routingTable)); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher._messageQueue.size()); - SharedHandle m = dispatcher._messageQueue[0]._message; + SharedHandle m + (dynamic_pointer_cast(dispatcher._messageQueue[0]._message)); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); CPPUNIT_ASSERT_EQUAL(std::string("find_node"), m->getMessageType()); diff --git a/test/DHTFindNodeReplyMessageTest.cc b/test/DHTFindNodeReplyMessageTest.cc index 6410a885..cab09ad1 100644 --- a/test/DHTFindNodeReplyMessageTest.cc +++ b/test/DHTFindNodeReplyMessageTest.cc @@ -30,8 +30,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTFindNodeReplyMessageTest); void DHTFindNodeReplyMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -40,9 +40,9 @@ void DHTFindNodeReplyMessageTest::testGetBencodedMessage() DHTFindNodeReplyMessage msg(localNode, remoteNode, transactionID); std::string compactNodeInfo; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { - nodes[i] = new DHTNode(); + nodes[i].reset(new DHTNode()); nodes[i]->setIPAddress("192.168.0."+Util::uitos(i+1)); nodes[i]->setPort(6881+i); @@ -56,7 +56,7 @@ void DHTFindNodeReplyMessageTest::testGetBencodedMessage() std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("r")); Dictionary* r = new Dictionary(); diff --git a/test/DHTGetPeersMessageTest.cc b/test/DHTGetPeersMessageTest.cc index 1eb27d73..8b514d7b 100644 --- a/test/DHTGetPeersMessageTest.cc +++ b/test/DHTGetPeersMessageTest.cc @@ -38,8 +38,8 @@ public: const std::string& token, const std::string& transactionID) { - SharedHandle m = - new MockDHTMessage(_localNode, remoteNode, "get_peers", transactionID); + SharedHandle m + (new MockDHTMessage(_localNode, remoteNode, "get_peers", transactionID)); m->_peers = peers; m->_token = token; return m; @@ -51,8 +51,8 @@ public: const std::string& token, const std::string& transactionID) { - SharedHandle m = - new MockDHTMessage(_localNode, remoteNode, "get_peers", transactionID); + SharedHandle m + (new MockDHTMessage(_localNode, remoteNode, "get_peers", transactionID)); m->_nodes = closestKNodes; m->_token = token; return m; @@ -66,8 +66,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTGetPeersMessageTest); void DHTGetPeersMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -80,7 +80,7 @@ void DHTGetPeersMessageTest::testGetBencodedMessage() std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("q")); cm->put("q", new Data("get_peers")); @@ -98,8 +98,8 @@ void DHTGetPeersMessageTest::testGetBencodedMessage() void DHTGetPeersMessageTest::testDoReceivedAction() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); @@ -116,21 +116,26 @@ void DHTGetPeersMessageTest::testDoReceivedAction() factory.setLocalNode(localNode); DHTGetPeersMessage msg(localNode, remoteNode, infoHash, transactionID); - msg.setTokenTracker(&tokenTracker); - msg.setMessageDispatcher(&dispatcher); - msg.setMessageFactory(&factory); + msg.setTokenTracker(WeakHandle + (&tokenTracker)); + msg.setMessageDispatcher(WeakHandle + (&dispatcher)); + msg.setMessageFactory(WeakHandle + (&factory)); { // localhost has peer contact information for that infohash. DHTPeerAnnounceStorage peerAnnounceStorage; peerAnnounceStorage.addPeerAnnounce(infoHash, "192.168.0.100", 6888); peerAnnounceStorage.addPeerAnnounce(infoHash, "192.168.0.101", 6889); - msg.setPeerAnnounceStorage(&peerAnnounceStorage); + msg.setPeerAnnounceStorage(WeakHandle + (&peerAnnounceStorage)); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher._messageQueue.size()); - SharedHandle m = dispatcher._messageQueue[0]._message; + SharedHandle m + (dynamic_pointer_cast(dispatcher._messageQueue[0]._message)); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); CPPUNIT_ASSERT_EQUAL(std::string("get_peers"), m->getMessageType()); @@ -154,16 +159,19 @@ void DHTGetPeersMessageTest::testDoReceivedAction() // localhost doesn't have peer contact information for that infohash. DHTPeerAnnounceStorage peerAnnounceStorage; DHTRoutingTable routingTable(localNode); - SharedHandle returnNode1 = new DHTNode(); + SharedHandle returnNode1(new DHTNode()); routingTable.addNode(returnNode1); - msg.setPeerAnnounceStorage(&peerAnnounceStorage); - msg.setRoutingTable(&routingTable); + msg.setPeerAnnounceStorage(WeakHandle + (&peerAnnounceStorage)); + msg.setRoutingTable(WeakHandle + (&routingTable)); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher._messageQueue.size()); - SharedHandle m = dispatcher._messageQueue[0]._message; + SharedHandle m + (dynamic_pointer_cast(dispatcher._messageQueue[0]._message)); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); CPPUNIT_ASSERT_EQUAL(std::string("get_peers"), m->getMessageType()); diff --git a/test/DHTGetPeersReplyMessageTest.cc b/test/DHTGetPeersReplyMessageTest.cc index 59716020..89fd2def 100644 --- a/test/DHTGetPeersReplyMessageTest.cc +++ b/test/DHTGetPeersReplyMessageTest.cc @@ -32,8 +32,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTGetPeersReplyMessageTest); void DHTGetPeersReplyMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -43,7 +43,7 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage() DHTGetPeersReplyMessage msg(localNode, remoteNode, token, transactionID); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("r")); Dictionary* r = new Dictionary(); @@ -53,9 +53,9 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage() { std::string compactNodeInfo; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { - nodes[i] = new DHTNode(); + nodes[i].reset(new DHTNode()); nodes[i]->setIPAddress("192.168.0."+Util::uitos(i+1)); nodes[i]->setPort(6881+i); @@ -83,7 +83,7 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage() List* values = new List(); r->put("values", values); for(size_t i = 0; i < 4; ++i) { - SharedHandle peer = new Peer("192.168.0."+Util::uitos(i+1), 6881+i); + SharedHandle peer(new Peer("192.168.0."+Util::uitos(i+1), 6881+i)); unsigned char buffer[6]; CPPUNIT_ASSERT(PeerMessageUtil::createcompact(buffer, peer->ipaddr, peer->port)); values->add(new Data(buffer, sizeof(buffer))); diff --git a/test/DHTIDCloserTest.cc b/test/DHTIDCloserTest.cc index ebe51a5e..e5d3cdf5 100644 --- a/test/DHTIDCloserTest.cc +++ b/test/DHTIDCloserTest.cc @@ -30,19 +30,24 @@ void DHTIDCloserTest::testOperator() unsigned char id[DHT_ID_LENGTH]; memset(id, 0xf0, DHT_ID_LENGTH); - SharedHandle e1 = new DHTNodeLookupEntry(new DHTNode(id)); + SharedHandle e1 + (new DHTNodeLookupEntry(SharedHandle(new DHTNode(id)))); id[0] = 0xb0; - SharedHandle e2 = new DHTNodeLookupEntry(new DHTNode(id)); + SharedHandle e2 + (new DHTNodeLookupEntry(SharedHandle(new DHTNode(id)))); id[0] = 0xa0; - SharedHandle e3 = new DHTNodeLookupEntry(new DHTNode(id)); + SharedHandle e3 + (new DHTNodeLookupEntry(SharedHandle(new DHTNode(id)))); id[0] = 0x80; - SharedHandle e4 = new DHTNodeLookupEntry(new DHTNode(id)); + SharedHandle e4 + (new DHTNodeLookupEntry(SharedHandle(new DHTNode(id)))); id[0] = 0x00; - SharedHandle e5 = new DHTNodeLookupEntry(new DHTNode(id)); + SharedHandle e5 + (new DHTNodeLookupEntry(SharedHandle(new DHTNode(id)))); std::deque > entries; entries.push_back(e1); diff --git a/test/DHTMessageFactoryImplTest.cc b/test/DHTMessageFactoryImplTest.cc index 7be1de95..3547f1bd 100644 --- a/test/DHTMessageFactoryImplTest.cc +++ b/test/DHTMessageFactoryImplTest.cc @@ -38,9 +38,7 @@ class DHTMessageFactoryImplTest:public CppUnit::TestFixture { CPPUNIT_TEST(testReceivedErrorMessage); CPPUNIT_TEST_SUITE_END(); public: - DHTMessageFactoryImplTest():factory(0), routingTable(0), localNode(0) {} - - DHTMessageFactoryImpl* factory; + SharedHandle factory; SharedHandle routingTable; @@ -52,19 +50,16 @@ public: void setUp() { - localNode = new DHTNode(); - factory = new DHTMessageFactoryImpl(); + localNode.reset(new DHTNode()); + factory.reset(new DHTMessageFactoryImpl()); factory->setLocalNode(localNode); memset(transactionID, 0xff, DHT_TRANSACTION_ID_LENGTH); memset(remoteNodeID, 0x0f, DHT_ID_LENGTH); - routingTable = new DHTRoutingTable(localNode); + routingTable.reset(new DHTRoutingTable(localNode)); factory->setRoutingTable(routingTable); } - void tearDown() - { - delete factory; - } + void tearDown() {} void testCreatePingMessage(); void testCreatePingReplyMessage(); @@ -83,7 +78,7 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTMessageFactoryImplTest); void DHTMessageFactoryImplTest::testCreatePingMessage() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("q")); d->put("q", new Data("ping")); @@ -91,8 +86,9 @@ void DHTMessageFactoryImplTest::testCreatePingMessage() a->put("id", new Data(remoteNodeID, DHT_ID_LENGTH)); d->put("a", a); - SharedHandle m = factory->createQueryMessage(d.get(), "192.168.0.1", 6881); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle m + (dynamic_pointer_cast(factory->createQueryMessage(d.get(), "192.168.0.1", 6881))); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); @@ -104,18 +100,19 @@ void DHTMessageFactoryImplTest::testCreatePingMessage() void DHTMessageFactoryImplTest::testCreatePingReplyMessage() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("r")); Dictionary* r = new Dictionary(); r->put("id", new Data(remoteNodeID, DHT_ID_LENGTH)); d->put("r", r); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); - SharedHandle m = factory->createResponseMessage("ping", d.get(), remoteNode); + SharedHandle m + (dynamic_pointer_cast(factory->createResponseMessage("ping", d.get(), remoteNode))); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); @@ -125,7 +122,7 @@ void DHTMessageFactoryImplTest::testCreatePingReplyMessage() void DHTMessageFactoryImplTest::testCreateFindNodeMessage() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("q")); d->put("q", new Data("find_node")); @@ -136,8 +133,9 @@ void DHTMessageFactoryImplTest::testCreateFindNodeMessage() a->put("target", new Data(targetNodeID, DHT_ID_LENGTH)); d->put("a", a); - SharedHandle m = factory->createQueryMessage(d.get(), "192.168.0.1", 6881); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle m + (dynamic_pointer_cast(factory->createQueryMessage(d.get(), "192.168.0.1", 6881))); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); @@ -152,15 +150,15 @@ void DHTMessageFactoryImplTest::testCreateFindNodeMessage() void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage() { try { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("r")); Dictionary* r = new Dictionary(); r->put("id", new Data(remoteNodeID, DHT_ID_LENGTH)); std::string compactNodeInfo; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { - nodes[i] = new DHTNode(); + nodes[i].reset(new DHTNode()); nodes[i]->setIPAddress("192.168.0."+Util::uitos(i+1)); nodes[i]->setPort(6881+i); @@ -173,11 +171,12 @@ void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage() r->put("nodes", new Data(compactNodeInfo)); d->put("r", r); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); - SharedHandle m = factory->createResponseMessage("find_node", d.get(), remoteNode); + SharedHandle m + (dynamic_pointer_cast(factory->createResponseMessage("find_node", d.get(), remoteNode))); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); @@ -194,7 +193,7 @@ void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage() void DHTMessageFactoryImplTest::testCreateGetPeersMessage() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("q")); d->put("q", new Data("get_peers")); @@ -205,8 +204,9 @@ void DHTMessageFactoryImplTest::testCreateGetPeersMessage() a->put("info_hash", new Data(infoHash, DHT_ID_LENGTH)); d->put("a", a); - SharedHandle m = factory->createQueryMessage(d.get(), "192.168.0.1", 6881); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle m + (dynamic_pointer_cast(factory->createQueryMessage(d.get(), "192.168.0.1", 6881))); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); @@ -221,15 +221,15 @@ void DHTMessageFactoryImplTest::testCreateGetPeersMessage() void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_nodes() { try { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("r")); Dictionary* r = new Dictionary(); r->put("id", new Data(remoteNodeID, DHT_ID_LENGTH)); std::string compactNodeInfo; - SharedHandle nodes[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { - nodes[i] = new DHTNode(); + nodes[i].reset(new DHTNode()); nodes[i]->setIPAddress("192.168.0."+Util::uitos(i+1)); nodes[i]->setPort(6881+i); @@ -243,11 +243,12 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_nodes() r->put("token", new Data("token")); d->put("r", r); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); - SharedHandle m = factory->createResponseMessage("get_peers", d.get(), remoteNode); + SharedHandle m + (dynamic_pointer_cast(factory->createResponseMessage("get_peers", d.get(), remoteNode))); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); @@ -266,7 +267,7 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_nodes() void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_values() { try { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("r")); Dictionary* r = new Dictionary(); @@ -276,7 +277,7 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_values() List* values = new List(); r->put("values", values); for(size_t i = 0; i < 4; ++i) { - SharedHandle peer = new Peer("192.168.0."+Util::uitos(i+1), 6881+i); + SharedHandle peer(new Peer("192.168.0."+Util::uitos(i+1), 6881+i)); unsigned char buffer[6]; CPPUNIT_ASSERT(PeerMessageUtil::createcompact(buffer, peer->ipaddr, peer->port)); values->add(new Data(buffer, sizeof(buffer))); @@ -286,11 +287,12 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_values() r->put("token", new Data("token")); d->put("r", r); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); - SharedHandle m = factory->createResponseMessage("get_peers", d.get(), remoteNode); + SharedHandle m + (dynamic_pointer_cast(factory->createResponseMessage("get_peers", d.get(), remoteNode))); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); @@ -309,7 +311,7 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_values() void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage() { try { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("q")); d->put("q", new Data("announce_peer")); @@ -324,8 +326,9 @@ void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage() a->put("token", new Data(token)); d->put("a", a); - SharedHandle m = factory->createQueryMessage(d.get(), "192.168.0.1", 6882); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle m + (dynamic_pointer_cast(factory->createQueryMessage(d.get(), "192.168.0.1", 6882))); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6882); @@ -347,18 +350,19 @@ void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage() void DHTMessageFactoryImplTest::testCreateAnnouncePeerReplyMessage() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("r")); Dictionary* r = new Dictionary(); r->put("id", new Data(remoteNodeID, DHT_ID_LENGTH)); d->put("r", r); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); - SharedHandle m = factory->createResponseMessage("announce_peer", d.get(), remoteNode); + SharedHandle m + (dynamic_pointer_cast(factory->createResponseMessage("announce_peer", d.get(), remoteNode))); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); @@ -368,7 +372,7 @@ void DHTMessageFactoryImplTest::testCreateAnnouncePeerReplyMessage() void DHTMessageFactoryImplTest::testReceivedErrorMessage() { - SharedHandle d = new Dictionary(); + SharedHandle d(new Dictionary()); d->put("t", new Data(transactionID, DHT_TRANSACTION_ID_LENGTH)); d->put("y", new Data("e")); List* l = new List(); @@ -376,7 +380,7 @@ void DHTMessageFactoryImplTest::testReceivedErrorMessage() l->add(new Data("Not found")); d->put("e", l); - SharedHandle remoteNode = new DHTNode(remoteNodeID); + SharedHandle remoteNode(new DHTNode(remoteNodeID)); remoteNode->setIPAddress("192.168.0.1"); remoteNode->setPort(6881); diff --git a/test/DHTMessageTrackerEntryTest.cc b/test/DHTMessageTrackerEntryTest.cc index f831c065..25d08dae 100644 --- a/test/DHTMessageTrackerEntryTest.cc +++ b/test/DHTMessageTrackerEntryTest.cc @@ -31,10 +31,12 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTMessageTrackerEntryTest); void DHTMessageTrackerEntryTest::testMatch() { - SharedHandle localNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); try { - SharedHandle msg1 = new MockDHTMessage(localNode, new DHTNode()); - SharedHandle msg2 = new MockDHTMessage(localNode, new DHTNode()); + SharedHandle node1(new DHTNode()); + SharedHandle msg1(new MockDHTMessage(localNode, node1)); + SharedHandle node2(new DHTNode()); + SharedHandle msg2(new MockDHTMessage(localNode, node2)); DHTMessageTrackerEntry entry(msg1, 30); diff --git a/test/DHTMessageTrackerTest.cc b/test/DHTMessageTrackerTest.cc index 800e2556..9a0a144a 100644 --- a/test/DHTMessageTrackerTest.cc +++ b/test/DHTMessageTrackerTest.cc @@ -47,14 +47,17 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTMessageTrackerTest); void DHTMessageTrackerTest::testMessageArrived() { - SharedHandle localNode = new DHTNode(); - SharedHandle routingTable = new DHTRoutingTable(localNode); - SharedHandle factory = new MockDHTMessageFactory(); + SharedHandle localNode(new DHTNode()); + SharedHandle routingTable(new DHTRoutingTable(localNode)); + SharedHandle factory(new MockDHTMessageFactory()); factory->setLocalNode(localNode); - SharedHandle m1 = new MockDHTMessage(localNode, new DHTNode()); - SharedHandle m2 = new MockDHTMessage(localNode, new DHTNode()); - SharedHandle m3 = new MockDHTMessage(localNode, new DHTNode()); + SharedHandle m1(new MockDHTMessage(localNode, + SharedHandle(new DHTNode()))); + SharedHandle m2(new MockDHTMessage(localNode, + SharedHandle(new DHTNode()))); + SharedHandle m3(new MockDHTMessage(localNode, + SharedHandle(new DHTNode()))); m1->getRemoteNode()->setIPAddress("192.168.0.1"); m1->getRemoteNode()->setPort(6881); @@ -63,7 +66,7 @@ void DHTMessageTrackerTest::testMessageArrived() m3->getRemoteNode()->setIPAddress("192.168.0.3"); m3->getRemoteNode()->setPort(6883); - SharedHandle c2 = new MockDHTMessageCallback2(); + SharedHandle c2(new MockDHTMessageCallback2()); DHTMessageTracker tracker; tracker.setRoutingTable(routingTable); @@ -73,7 +76,7 @@ void DHTMessageTrackerTest::testMessageArrived() tracker.addMessage(m3); { - SharedHandle res = new Dictionary(); + SharedHandle res(new Dictionary()); res->put("t", new Data(m2->getTransactionID())); std::pair, SharedHandle > p = @@ -86,7 +89,7 @@ void DHTMessageTrackerTest::testMessageArrived() CPPUNIT_ASSERT_EQUAL((size_t)2, tracker.countEntry()); } { - SharedHandle res = new Dictionary(); + SharedHandle res(new Dictionary()); res->put("t", new Data(m3->getTransactionID())); std::pair, SharedHandle > p = tracker.messageArrived(res.get(), m3->getRemoteNode()->getIPAddress(), m3->getRemoteNode()->getPort()); @@ -97,7 +100,7 @@ void DHTMessageTrackerTest::testMessageArrived() CPPUNIT_ASSERT_EQUAL((size_t)1, tracker.countEntry()); } { - SharedHandle res = new Dictionary(); + SharedHandle res(new Dictionary()); res->put("t", new Data(m1->getTransactionID())); std::pair, SharedHandle > p = tracker.messageArrived(res.get(), "192.168.1.100", 6889); diff --git a/test/DHTPeerAnnounceEntryTest.cc b/test/DHTPeerAnnounceEntryTest.cc index 83ef477d..419fe0b0 100644 --- a/test/DHTPeerAnnounceEntryTest.cc +++ b/test/DHTPeerAnnounceEntryTest.cc @@ -69,7 +69,7 @@ void DHTPeerAnnounceEntryTest::testEmpty() } { DHTPeerAnnounceEntry entry(infohash); - entry.setBtContext(new MockBtContext()); + entry.setBtContext(SharedHandle(new MockBtContext())); CPPUNIT_ASSERT(!entry.empty()); } { @@ -100,12 +100,14 @@ void DHTPeerAnnounceEntryTest::testGetPeers() unsigned char infohash[DHT_ID_LENGTH]; memset(infohash, 0xff, DHT_ID_LENGTH); - SharedHandle ctx = new MockBtContext(); + SharedHandle ctx(new MockBtContext()); ctx->setInfoHash(infohash); - SharedHandle peerStorage = new MockPeerStorage(); + SharedHandle peerStorage(new MockPeerStorage()); { - SharedHandle activePeers[] = { new Peer("192.168.0.3", 6883), - new Peer("192.168.0.4", 6884) }; + SharedHandle activePeers[2]; + activePeers[0].reset(new Peer("192.168.0.3", 6883)); + activePeers[1].reset(new Peer("192.168.0.4", 6884)); + peerStorage->setActivePeers(std::deque >(&activePeers[0], &activePeers[2])); } diff --git a/test/DHTPeerAnnounceStorageTest.cc b/test/DHTPeerAnnounceStorageTest.cc index 071939c2..8a11a28c 100644 --- a/test/DHTPeerAnnounceStorageTest.cc +++ b/test/DHTPeerAnnounceStorageTest.cc @@ -55,10 +55,10 @@ void DHTPeerAnnounceStorageTest::testRemovePeerAnnounce() memset(infohash2, 0xf0, DHT_ID_LENGTH); DHTPeerAnnounceStorage storage; - SharedHandle ctx1 = new MockBtContext(); + SharedHandle ctx1(new MockBtContext()); ctx1->setInfoHash(infohash1); - SharedHandle ctx2 = new MockBtContext(); + SharedHandle ctx2(new MockBtContext()); ctx2->setInfoHash(infohash2); storage.addPeerAnnounce(infohash1, "192.168.0.1", 6881); diff --git a/test/DHTPingMessageTest.cc b/test/DHTPingMessageTest.cc index bbd3c7fe..d931c3b7 100644 --- a/test/DHTPingMessageTest.cc +++ b/test/DHTPingMessageTest.cc @@ -34,8 +34,9 @@ public: const unsigned char* remoteNodeID, const std::string& transactionID) { - return new MockDHTMessage(_localNode, remoteNode, "ping_reply", - transactionID); + return SharedHandle + (new MockDHTMessage(_localNode, remoteNode, "ping_reply", + transactionID)); } }; }; @@ -45,8 +46,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTPingMessageTest); void DHTPingMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -56,7 +57,7 @@ void DHTPingMessageTest::testGetBencodedMessage() std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("q")); cm->put("q", new Data("ping")); @@ -72,8 +73,8 @@ void DHTPingMessageTest::testGetBencodedMessage() void DHTPingMessageTest::testDoReceivedAction() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -84,13 +85,14 @@ void DHTPingMessageTest::testDoReceivedAction() factory.setLocalNode(localNode); DHTPingMessage msg(localNode, remoteNode, transactionID); - msg.setMessageDispatcher(&dispatcher); - msg.setMessageFactory(&factory); + msg.setMessageDispatcher(WeakHandle(&dispatcher)); + msg.setMessageFactory(WeakHandle(&factory)); msg.doReceivedAction(); CPPUNIT_ASSERT_EQUAL((size_t)1, dispatcher._messageQueue.size()); - SharedHandle m = dispatcher._messageQueue[0]._message; + SharedHandle m + (dynamic_pointer_cast(dispatcher._messageQueue[0]._message)); CPPUNIT_ASSERT(localNode == m->getLocalNode()); CPPUNIT_ASSERT(remoteNode == m->getRemoteNode()); CPPUNIT_ASSERT_EQUAL(std::string("ping_reply"), m->getMessageType()); diff --git a/test/DHTPingReplyMessageTest.cc b/test/DHTPingReplyMessageTest.cc index aac99565..b39fa1c3 100644 --- a/test/DHTPingReplyMessageTest.cc +++ b/test/DHTPingReplyMessageTest.cc @@ -28,8 +28,8 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTPingReplyMessageTest); void DHTPingReplyMessageTest::testGetBencodedMessage() { - SharedHandle localNode = new DHTNode(); - SharedHandle remoteNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); + SharedHandle remoteNode(new DHTNode()); unsigned char tid[DHT_TRANSACTION_ID_LENGTH]; DHTUtil::generateRandomData(tid, DHT_TRANSACTION_ID_LENGTH); @@ -42,7 +42,7 @@ void DHTPingReplyMessageTest::testGetBencodedMessage() std::string msgbody = msg.getBencodedMessage(); - SharedHandle cm = new Dictionary(); + SharedHandle cm(new Dictionary()); cm->put("t", new Data(transactionID)); cm->put("y", new Data("r")); Dictionary* r = new Dictionary(); diff --git a/test/DHTRoutingTableDeserializerTest.cc b/test/DHTRoutingTableDeserializerTest.cc index f48df545..714dde6b 100644 --- a/test/DHTRoutingTableDeserializerTest.cc +++ b/test/DHTRoutingTableDeserializerTest.cc @@ -32,11 +32,11 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTRoutingTableDeserializerTest); void DHTRoutingTableDeserializerTest::testDeserialize() { - SharedHandle localNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); - SharedHandle nodesSrc[] = { 0, 0, 0 }; + SharedHandle nodesSrc[3]; for(size_t i = 0; i < arrayLength(nodesSrc); ++i) { - nodesSrc[i] = new DHTNode(); + nodesSrc[i].reset(new DHTNode()); nodesSrc[i]->setIPAddress("192.168.0."+Util::uitos(i+1)); nodesSrc[i]->setPort(6881+i); } diff --git a/test/DHTRoutingTableSerializerTest.cc b/test/DHTRoutingTableSerializerTest.cc index a745c8e3..dfb57a75 100644 --- a/test/DHTRoutingTableSerializerTest.cc +++ b/test/DHTRoutingTableSerializerTest.cc @@ -31,11 +31,11 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTRoutingTableSerializerTest); void DHTRoutingTableSerializerTest::testSerialize() { - SharedHandle localNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); - SharedHandle nodesSrc[] = { 0, 0, 0 }; + SharedHandle nodesSrc[3]; for(size_t i = 0; i < arrayLength(nodesSrc); ++i) { - nodesSrc[i] = new DHTNode(); + nodesSrc[i].reset(new DHTNode()); nodesSrc[i]->setIPAddress("192.168.0."+Util::uitos(i+1)); nodesSrc[i]->setPort(6881+i); } diff --git a/test/DHTRoutingTableTest.cc b/test/DHTRoutingTableTest.cc index f77ed24f..0b2e6cd4 100644 --- a/test/DHTRoutingTableTest.cc +++ b/test/DHTRoutingTableTest.cc @@ -31,12 +31,16 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTRoutingTableTest); void DHTRoutingTableTest::testAddNode() { - DHTRoutingTable table(new DHTNode()); - table.setTaskFactory(new MockDHTTaskFactory()); - table.setTaskQueue(new MockDHTTaskQueue()); + SharedHandle localNode(new DHTNode()); + DHTRoutingTable table(localNode); + SharedHandle taskFactory(new MockDHTTaskFactory()); + table.setTaskFactory(taskFactory); + SharedHandle taskQueue(new MockDHTTaskQueue()); + table.setTaskQueue(taskQueue); uint32_t count = 0; for(int i = 0; i < 100; ++i) { - if(table.addNode(new DHTNode())) { + SharedHandle node(new DHTNode()); + if(table.addNode(node)) { ++count; } } @@ -54,26 +58,26 @@ void DHTRoutingTableTest::testGetClosestKNodes() { unsigned char id[DHT_ID_LENGTH]; createID(id, 0x81, 0); - SharedHandle localNode = new DHTNode(id); + SharedHandle localNode(new DHTNode(id)); DHTRoutingTable table(localNode); - SharedHandle nodes1[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - SharedHandle nodes2[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - SharedHandle nodes3[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + SharedHandle nodes1[8]; + SharedHandle nodes2[8]; + SharedHandle nodes3[8]; for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0xf0, i); - nodes1[i] = new DHTNode(id); + nodes1[i].reset(new DHTNode(id)); CPPUNIT_ASSERT(table.addNode(nodes1[i])); } for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0x80, i); - nodes2[i] = new DHTNode(id); + nodes2[i].reset(new DHTNode(id)); CPPUNIT_ASSERT(table.addNode(nodes2[i])); } for(size_t i = 0; i < DHTBucket::K; ++i) { createID(id, 0x70, i); - nodes3[i] = new DHTNode(id); + nodes3[i].reset(new DHTNode(id)); CPPUNIT_ASSERT(table.addNode(nodes3[i])); } { diff --git a/test/DHTUnknownMessageTest.cc b/test/DHTUnknownMessageTest.cc index 2e72517b..7801bdd8 100644 --- a/test/DHTUnknownMessageTest.cc +++ b/test/DHTUnknownMessageTest.cc @@ -23,7 +23,7 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DHTUnknownMessageTest); void DHTUnknownMessageTest::testToString() { - SharedHandle localNode = new DHTNode(); + SharedHandle localNode(new DHTNode()); std::string ipaddr = "192.168.0.1"; uint16_t port = 6881; diff --git a/test/DefaultAuthResolverTest.cc b/test/DefaultAuthResolverTest.cc index 0f5e8fce..017e5651 100644 --- a/test/DefaultAuthResolverTest.cc +++ b/test/DefaultAuthResolverTest.cc @@ -20,9 +20,10 @@ public: { //_netrc = new Netrc(); //_option = new Option(); - _resolver = new DefaultAuthResolver(); + _resolver.reset(new DefaultAuthResolver()); //_factory->setOption(_option.get()); - _resolver->setDefaultAuthConfig(new AuthConfig("foo", "bar")); + _resolver->setDefaultAuthConfig + (SharedHandle(new AuthConfig("foo", "bar"))); } void testResolveAuthConfig_without_userDefined(); @@ -40,7 +41,8 @@ void DefaultAuthResolverTest::testResolveAuthConfig_without_userDefined() void DefaultAuthResolverTest::testResolveAuthConfig_with_userDefined() { - _resolver->setUserDefinedAuthConfig(new AuthConfig("myname", "mypasswd")); + _resolver->setUserDefinedAuthConfig + (SharedHandle(new AuthConfig("myname", "mypasswd"))); SharedHandle authConfig = _resolver->resolveAuthConfig("localhost"); CPPUNIT_ASSERT_EQUAL(std::string("myname:mypasswd"), authConfig->getAuthText()); } diff --git a/test/DefaultBtAnnounceTest.cc b/test/DefaultBtAnnounceTest.cc index 7e6e67ff..c8985587 100644 --- a/test/DefaultBtAnnounceTest.cc +++ b/test/DefaultBtAnnounceTest.cc @@ -34,11 +34,6 @@ private: SharedHandle _btRuntime; Option* _option; public: - DefaultBtAnnounceTest():_btContext(0), - _pieceStorage(0), - _peerStorage(0), - _btRuntime(0) {} - void setUp() { _option = new Option(); @@ -53,23 +48,23 @@ public: std::string peerId = "-aria2-ultrafastdltl"; - _btContext = new MockBtContext(); + _btContext.reset(new MockBtContext()); _btContext->setInfoHash(infoHash); _btContext->setTotalLength(totalLength); _btContext->setPieceLength(pieceLength); _btContext->setPeerId(reinterpret_cast(peerId.c_str())); - _pieceStorage = new MockPieceStorage(); + _pieceStorage.reset(new MockPieceStorage()); _pieceStorage->setTotalLength(totalLength); _pieceStorage->setCompletedLength(pieceLength*10); - _peerStorage = new MockPeerStorage(); + _peerStorage.reset(new MockPeerStorage()); TransferStat stat; stat.setSessionDownloadLength(pieceLength*5); stat.setSessionUploadLength(pieceLength*6); _peerStorage->setStat(stat); - _btRuntime = new BtRuntime(); + _btRuntime.reset(new BtRuntime()); _btRuntime->setListenPort(6989); } @@ -96,12 +91,12 @@ void DefaultBtAnnounceTest::testNoMoreAnnounce() std::string trackerURI1 = "http://localhost/announce"; std::deque uris1; uris1.push_back(trackerURI1); - SharedHandle announceTier1 = new AnnounceTier(uris1); + SharedHandle announceTier1(new AnnounceTier(uris1)); std::string trackerURI2 = "http://backup/announce"; std::deque uris2; uris2.push_back(trackerURI2); - SharedHandle announceTier2 = new AnnounceTier(uris2); + SharedHandle announceTier2(new AnnounceTier(uris2)); _btContext->addAnnounceTier(announceTier1); @@ -111,7 +106,7 @@ void DefaultBtAnnounceTest::testNoMoreAnnounce() btAnnounce.setPieceStorage(_pieceStorage); btAnnounce.setPeerStorage(_peerStorage); btAnnounce.setBtRuntime(_btRuntime); - btAnnounce.setRandomizer(new FixedNumberRandomizer()); + btAnnounce.setRandomizer(SharedHandle(new FixedNumberRandomizer())); btAnnounce.generateKey(); CPPUNIT_ASSERT_EQUAL(std::string("http://localhost/announce?info_hash=%01%23Eg%89%ab%cd%ef%01%23Eg%89%ab%cd%ef%01%23Eg&peer_id=%2daria2%2dultrafastdltl&uploaded=1572864&downloaded=1310720&left=1572864&compact=1&key=AAAAAAAA&numwant=50&no_peer_id=1&port=6989&event=started&supportcrypto=1"), btAnnounce.getAnnounceUrl()); @@ -154,7 +149,7 @@ void DefaultBtAnnounceTest::testGetAnnounceUrl() std::string trackerURI = "http://localhost/announce"; std::deque uris; uris.push_back(trackerURI); - SharedHandle announceTier = new AnnounceTier(uris); + SharedHandle announceTier(new AnnounceTier(uris)); _btContext->addAnnounceTier(announceTier); @@ -162,7 +157,7 @@ void DefaultBtAnnounceTest::testGetAnnounceUrl() btAnnounce.setPieceStorage(_pieceStorage); btAnnounce.setPeerStorage(_peerStorage); btAnnounce.setBtRuntime(_btRuntime); - btAnnounce.setRandomizer(new FixedNumberRandomizer()); + btAnnounce.setRandomizer(SharedHandle(new FixedNumberRandomizer())); btAnnounce.generateKey(); CPPUNIT_ASSERT_EQUAL(std::string("http://localhost/announce?info_hash=%01%23Eg%89%ab%cd%ef%01%23Eg%89%ab%cd%ef%01%23Eg&peer_id=%2daria2%2dultrafastdltl&uploaded=1572864&downloaded=1310720&left=1572864&compact=1&key=AAAAAAAA&numwant=50&no_peer_id=1&port=6989&event=started&supportcrypto=1"), btAnnounce.getAnnounceUrl()); @@ -189,12 +184,12 @@ void DefaultBtAnnounceTest::testIsAllAnnounceFailed() std::string trackerURI1 = "http://localhost/announce"; std::deque uris1; uris1.push_back(trackerURI1); - SharedHandle announceTier1 = new AnnounceTier(uris1); + SharedHandle announceTier1(new AnnounceTier(uris1)); std::string trackerURI2 = "http://backup/announce"; std::deque uris2; uris2.push_back(trackerURI2); - SharedHandle announceTier2 = new AnnounceTier(uris2); + SharedHandle announceTier2(new AnnounceTier(uris2)); _btContext->addAnnounceTier(announceTier1); @@ -204,7 +199,7 @@ void DefaultBtAnnounceTest::testIsAllAnnounceFailed() btAnnounce.setPieceStorage(_pieceStorage); btAnnounce.setPeerStorage(_peerStorage); btAnnounce.setBtRuntime(_btRuntime); - btAnnounce.setRandomizer(new FixedNumberRandomizer()); + btAnnounce.setRandomizer(SharedHandle(new FixedNumberRandomizer())); btAnnounce.generateKey(); CPPUNIT_ASSERT_EQUAL(std::string("http://localhost/announce?info_hash=%01%23Eg%89%ab%cd%ef%01%23Eg%89%ab%cd%ef%01%23Eg&peer_id=%2daria2%2dultrafastdltl&uploaded=1572864&downloaded=1310720&left=1572864&compact=1&key=AAAAAAAA&numwant=50&no_peer_id=1&port=6989&event=started&supportcrypto=1"), btAnnounce.getAnnounceUrl()); @@ -228,7 +223,7 @@ void DefaultBtAnnounceTest::testURLOrderInStoppedEvent() { const char* urls[] = { "http://localhost1/announce", "http://localhost2/announce" }; - SharedHandle announceTier = new AnnounceTier(std::deque(&urls[0], &urls[2])); + SharedHandle announceTier(new AnnounceTier(std::deque(&urls[0], &urls[2]))); _btContext->addAnnounceTier(announceTier); @@ -236,7 +231,7 @@ void DefaultBtAnnounceTest::testURLOrderInStoppedEvent() btAnnounce.setPieceStorage(_pieceStorage); btAnnounce.setPeerStorage(_peerStorage); btAnnounce.setBtRuntime(_btRuntime); - btAnnounce.setRandomizer(new FixedNumberRandomizer()); + btAnnounce.setRandomizer(SharedHandle(new FixedNumberRandomizer())); btAnnounce.generateKey(); CPPUNIT_ASSERT_EQUAL(std::string("http://localhost1/announce?info_hash=%01%23Eg%89%ab%cd%ef%01%23Eg%89%ab%cd%ef%01%23Eg&peer_id=%2daria2%2dultrafastdltl&uploaded=1572864&downloaded=1310720&left=1572864&compact=1&key=AAAAAAAA&numwant=50&no_peer_id=1&port=6989&event=started&supportcrypto=1"), btAnnounce.getAnnounceUrl()); @@ -258,7 +253,7 @@ void DefaultBtAnnounceTest::testURLOrderInCompletedEvent() { const char* urls[] = { "http://localhost1/announce", "http://localhost2/announce" }; - SharedHandle announceTier = new AnnounceTier(std::deque(&urls[0], &urls[2])); + SharedHandle announceTier(new AnnounceTier(std::deque(&urls[0], &urls[2]))); _btContext->addAnnounceTier(announceTier); @@ -266,7 +261,7 @@ void DefaultBtAnnounceTest::testURLOrderInCompletedEvent() btAnnounce.setPieceStorage(_pieceStorage); btAnnounce.setPeerStorage(_peerStorage); btAnnounce.setBtRuntime(_btRuntime); - btAnnounce.setRandomizer(new FixedNumberRandomizer()); + btAnnounce.setRandomizer(SharedHandle(new FixedNumberRandomizer())); btAnnounce.generateKey(); CPPUNIT_ASSERT_EQUAL(std::string("http://localhost1/announce?info_hash=%01%23Eg%89%ab%cd%ef%01%23Eg%89%ab%cd%ef%01%23Eg&peer_id=%2daria2%2dultrafastdltl&uploaded=1572864&downloaded=1310720&left=1572864&compact=1&key=AAAAAAAA&numwant=50&no_peer_id=1&port=6989&event=started&supportcrypto=1"), btAnnounce.getAnnounceUrl()); @@ -288,7 +283,8 @@ void DefaultBtAnnounceTest::testProcessAnnounceResponse_malformed() { try { std::string res = "i123e"; - DefaultBtAnnounce(new MockBtContext(), _option).processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); + SharedHandle ctx(new MockBtContext()); + DefaultBtAnnounce(ctx, _option).processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); CPPUNIT_FAIL("exception must be thrown."); } catch(Exception* e) { std::cerr << *e << std::endl; @@ -300,7 +296,8 @@ void DefaultBtAnnounceTest::testProcessAnnounceResponse_failureReason() { try { std::string res = "d14:failure reason11:hello worlde"; - DefaultBtAnnounce(new MockBtContext(), _option).processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); + SharedHandle ctx(new MockBtContext()); + DefaultBtAnnounce(ctx, _option).processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); CPPUNIT_FAIL("exception must be thrown."); } catch(Exception* e) { std::cerr << *e << std::endl; @@ -319,7 +316,8 @@ void DefaultBtAnnounceTest::testProcessAnnounceResponse() "10:incompletei200e" "e"; - DefaultBtAnnounce an(new MockBtContext(), _option); + SharedHandle ctx(new MockBtContext()); + DefaultBtAnnounce an(ctx, _option); an.processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); CPPUNIT_ASSERT_EQUAL(std::string("foo"), an.getTrackerID()); CPPUNIT_ASSERT_EQUAL((time_t)3000, an.getInterval()); diff --git a/test/DefaultBtContextTest.cc b/test/DefaultBtContextTest.cc index fa1f24e6..104dcc23 100644 --- a/test/DefaultBtContextTest.cc +++ b/test/DefaultBtContextTest.cc @@ -223,7 +223,7 @@ void DefaultBtContextTest::testGetInfoHashAsString() { void DefaultBtContextTest::testGetPeerId() { DefaultBtContext btContext; - btContext.setRandomizer(new FixedNumberRandomizer()); + btContext.setRandomizer(SharedHandle(new FixedNumberRandomizer())); CPPUNIT_ASSERT_EQUAL(std::string("%2daria2%2dAAAAAAAAAAAAA"), Util::torrentUrlencode(btContext.getPeerId(), 20)); } diff --git a/test/DefaultBtMessageDispatcherTest.cc b/test/DefaultBtMessageDispatcherTest.cc index 5b3ae2d1..bb8b7398 100644 --- a/test/DefaultBtMessageDispatcherTest.cc +++ b/test/DefaultBtMessageDispatcherTest.cc @@ -14,6 +14,7 @@ #include "BtMessageReceiver.h" #include "ExtensionMessageFactory.h" #include "PeerConnection.h" +#include "BtHandshakeMessage.h" #include #include @@ -44,8 +45,6 @@ private: SharedHandle peerStorage; SharedHandle pieceStorage; public: - DefaultBtMessageDispatcherTest():btContext(0), peer(0), btMessageDispatcher(0) {} - void tearDown() {} void testAddMessage(); @@ -124,34 +123,35 @@ public: public: virtual SharedHandle createCancelMessage(size_t index, uint32_t begin, size_t length) { - SharedHandle btMsg = new MockBtMessage2(); + SharedHandle btMsg(new MockBtMessage2()); btMsg->type = "cancel"; return btMsg; } }; void setUp() { - btContext = new DefaultBtContext(); + btContext.reset(new DefaultBtContext()); btContext->load("test.torrent"); - peer = new Peer("192.168.0.1", 6969); + peer.reset(new Peer("192.168.0.1", 6969)); peer->allocateSessionResource(btContext->getPieceLength(), btContext->getTotalLength()); - peerStorage = new MockPeerStorage(); - pieceStorage = new MockPieceStorage(); + peerStorage.reset(new MockPeerStorage()); + pieceStorage.reset(new MockPieceStorage()); BtRegistry::unregisterAll(); BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage); BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(), pieceStorage); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(), - new PeerObjectCluster()); + cluster); - SharedHandle peerObject = new PeerObject(); - peerObject->btMessageFactory = new MockBtMessageFactory2(); + SharedHandle peerObject(new PeerObject()); + peerObject->btMessageFactory.reset(new MockBtMessageFactory2()); PEER_OBJECT_CLUSTER(btContext)->registerHandle(peer->getID(), peerObject); - btMessageDispatcher = new DefaultBtMessageDispatcher(); + btMessageDispatcher.reset(new DefaultBtMessageDispatcher()); btMessageDispatcher->setCuid(1); btMessageDispatcher->setBtContext(btContext); btMessageDispatcher->setPeer(peer); @@ -164,7 +164,7 @@ public: CPPUNIT_TEST_SUITE_REGISTRATION(DefaultBtMessageDispatcherTest); void DefaultBtMessageDispatcherTest::testAddMessage() { - SharedHandle msg = new MockBtMessage2(); + SharedHandle msg(new MockBtMessage2()); CPPUNIT_ASSERT_EQUAL(false, msg->isOnQueuedCalled()); btMessageDispatcher->addMessageToQueue(msg); CPPUNIT_ASSERT_EQUAL(true, msg->isOnQueuedCalled()); @@ -177,10 +177,10 @@ void DefaultBtMessageDispatcherTest::testSendMessages() { stat.setUploadSpeed(0); peerStorage->setStat(stat); - SharedHandle msg1 = new MockBtMessage2(); + SharedHandle msg1(new MockBtMessage2()); msg1->setSendingInProgress(false); msg1->setUploading(false); - SharedHandle msg2 = new MockBtMessage2(); + SharedHandle msg2(new MockBtMessage2()); msg2->setSendingInProgress(false); msg2->setUploading(false); btMessageDispatcher->addMessageToQueue(msg1); @@ -196,10 +196,10 @@ void DefaultBtMessageDispatcherTest::testSendMessages_underUploadLimit() { stat.setUploadSpeed(0); peerStorage->setStat(stat); - SharedHandle msg1 = new MockBtMessage2(); + SharedHandle msg1(new MockBtMessage2()); msg1->setSendingInProgress(false); msg1->setUploading(true); - SharedHandle msg2 = new MockBtMessage2(); + SharedHandle msg2(new MockBtMessage2()); msg2->setSendingInProgress(false); msg2->setUploading(true); btMessageDispatcher->addMessageToQueue(msg1); @@ -216,13 +216,13 @@ void DefaultBtMessageDispatcherTest::testSendMessages_overUploadLimit() { stat.setUploadSpeed(150); peerStorage->setStat(stat); - SharedHandle msg1 = new MockBtMessage2(); + SharedHandle msg1(new MockBtMessage2()); msg1->setSendingInProgress(false); msg1->setUploading(true); - SharedHandle msg2 = new MockBtMessage2(); + SharedHandle msg2(new MockBtMessage2()); msg2->setSendingInProgress(false); msg2->setUploading(true); - SharedHandle msg3 = new MockBtMessage2(); + SharedHandle msg3(new MockBtMessage2()); msg3->setSendingInProgress(false); msg3->setUploading(false); @@ -239,13 +239,13 @@ void DefaultBtMessageDispatcherTest::testSendMessages_overUploadLimit() { } void DefaultBtMessageDispatcherTest::testSendMessages_sendingInProgress() { - SharedHandle msg1 = new MockBtMessage2(); + SharedHandle msg1(new MockBtMessage2()); msg1->setSendingInProgress(false); msg1->setUploading(false); - SharedHandle msg2 = new MockBtMessage2(); + SharedHandle msg2(new MockBtMessage2()); msg2->setSendingInProgress(true); msg2->setUploading(false); - SharedHandle msg3 = new MockBtMessage2(); + SharedHandle msg3(new MockBtMessage2()); msg3->setSendingInProgress(false); msg3->setUploading(false); @@ -263,8 +263,8 @@ void DefaultBtMessageDispatcherTest::testSendMessages_sendingInProgress() { } void DefaultBtMessageDispatcherTest::testDoCancelSendingPieceAction() { - SharedHandle msg1 = new MockBtMessage2(); - SharedHandle msg2 = new MockBtMessage2(); + SharedHandle msg1(new MockBtMessage2()); + SharedHandle msg2(new MockBtMessage2()); btMessageDispatcher->addMessageToQueue(msg1); btMessageDispatcher->addMessageToQueue(msg2); @@ -280,17 +280,17 @@ int MY_PIECE_LENGTH = 16*1024; void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing() { RequestSlot slot(0, 0, MY_PIECE_LENGTH, 0); - SharedHandle piece = new Piece(0, MY_PIECE_LENGTH); + SharedHandle piece(new Piece(0, MY_PIECE_LENGTH)); size_t index; CPPUNIT_ASSERT(piece->getMissingUnusedBlockIndex(index)); CPPUNIT_ASSERT_EQUAL((size_t)0, index); - SharedHandle pieceStorage = new MockPieceStorage2(); + SharedHandle pieceStorage(new MockPieceStorage2()); pieceStorage->setPiece(piece); BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(), pieceStorage); - btMessageDispatcher = new DefaultBtMessageDispatcher(); + btMessageDispatcher.reset(new DefaultBtMessageDispatcher()); btMessageDispatcher->setCuid(1); btMessageDispatcher->setBtContext(btContext); btMessageDispatcher->setPeer(peer); @@ -309,17 +309,17 @@ void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_tim // make this slot timeout slot.setDispatchedTime(0); - SharedHandle piece = new Piece(0, MY_PIECE_LENGTH); + SharedHandle piece(new Piece(0, MY_PIECE_LENGTH)); size_t index; CPPUNIT_ASSERT(piece->getMissingUnusedBlockIndex(index)); CPPUNIT_ASSERT_EQUAL((size_t)0, index); - SharedHandle pieceStorage = new MockPieceStorage2(); + SharedHandle pieceStorage(new MockPieceStorage2()); pieceStorage->setPiece(piece); BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(), pieceStorage); - btMessageDispatcher = new DefaultBtMessageDispatcher(); + btMessageDispatcher.reset(new DefaultBtMessageDispatcher()); btMessageDispatcher->setCuid(1); btMessageDispatcher->setBtContext(btContext); btMessageDispatcher->setPeer(peer); @@ -340,16 +340,16 @@ void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_tim void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_completeBlock() { RequestSlot slot(0, 0, MY_PIECE_LENGTH, 0); - SharedHandle piece = new Piece(0, MY_PIECE_LENGTH); + SharedHandle piece(new Piece(0, MY_PIECE_LENGTH)); piece->completeBlock(0); - SharedHandle pieceStorage = new MockPieceStorage2(); + SharedHandle pieceStorage(new MockPieceStorage2()); pieceStorage->setPiece(piece); BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(), pieceStorage); - btMessageDispatcher = new DefaultBtMessageDispatcher(); + btMessageDispatcher.reset(new DefaultBtMessageDispatcher()); btMessageDispatcher->setCuid(1); btMessageDispatcher->setBtContext(btContext); btMessageDispatcher->setPeer(peer); @@ -367,7 +367,7 @@ void DefaultBtMessageDispatcherTest::testCheckRequestSlotAndDoNecessaryThing_com void DefaultBtMessageDispatcherTest::testIsSendingInProgress() { CPPUNIT_ASSERT(!btMessageDispatcher->isSendingInProgress()); - SharedHandle msg = new MockBtMessage2(); + SharedHandle msg(new MockBtMessage2()); msg->setSendingInProgress(false); btMessageDispatcher->addMessageToQueue(msg); CPPUNIT_ASSERT(!btMessageDispatcher->isSendingInProgress()); diff --git a/test/DefaultBtMessageFactoryTest.cc b/test/DefaultBtMessageFactoryTest.cc index 892d60a5..c9259724 100644 --- a/test/DefaultBtMessageFactoryTest.cc +++ b/test/DefaultBtMessageFactoryTest.cc @@ -29,26 +29,25 @@ private: SharedHandle _btContext; SharedHandle _peer; public: - DefaultBtMessageFactoryTest():_btContext(0), _peer(0) {} - void setUp() { BtRegistry::unregisterAll(); - SharedHandle btContext = new MockBtContext(); + SharedHandle btContext(new MockBtContext()); unsigned char infohash[20]; memset(infohash, 0, sizeof(infohash)); btContext->setInfoHash(infohash); _btContext = btContext; - _peer = new Peer("192.168.0.1", 6969); + _peer.reset(new Peer("192.168.0.1", 6969)); _peer->allocateSessionResource(1024, 1024*1024); _peer->setExtendedMessagingEnabled(true); - SharedHandle exmsgFactory = - new MockExtensionMessageFactory(); + SharedHandle exmsgFactory + (new MockExtensionMessageFactory()); + SharedHandle cluster(new PeerObjectCluster()); BtRegistry::registerPeerObjectCluster(_btContext->getInfoHashAsString(), - new PeerObjectCluster()); - SharedHandle peerObject = new PeerObject(); + cluster); + SharedHandle peerObject(new PeerObject()); peerObject->extensionMessageFactory = exmsgFactory; PEER_OBJECT_CLUSTER(_btContext)->registerHandle(_peer->getID(), peerObject); @@ -80,8 +79,9 @@ void DefaultBtMessageFactoryTest::testCreateBtMessage_BtExtendedMessage() msg[5] = 1; // Set dummy extended message ID 1 memcpy(msg+6, payload.c_str(), payload.size()); - SharedHandle m = - factory.createBtMessage((const unsigned char*)msg+4, sizeof(msg)); + SharedHandle m + (dynamic_pointer_cast + (factory.createBtMessage((const unsigned char*)msg+4, sizeof(msg)))); try { // disable extended messaging @@ -105,7 +105,9 @@ void DefaultBtMessageFactoryTest::testCreatePortMessage() PeerMessageUtil::createPeerMessageString(data, sizeof(data), 3, 9); PeerMessageUtil::setShortIntParam(&data[5], 6881); try { - SharedHandle m = factory.createBtMessage(&data[4], sizeof(data)-4); + SharedHandle m + (dynamic_pointer_cast + (factory.createBtMessage(&data[4], sizeof(data)-4))); CPPUNIT_ASSERT(!m.isNull()); CPPUNIT_ASSERT_EQUAL((uint16_t)6881, m->getPort()); } catch(Exception* e) { @@ -116,7 +118,8 @@ void DefaultBtMessageFactoryTest::testCreatePortMessage() } } { - SharedHandle m = factory.createPortMessage(6881); + SharedHandle m + (dynamic_pointer_cast(factory.createPortMessage(6881))); CPPUNIT_ASSERT_EQUAL((uint16_t)6881, m->getPort()); } } diff --git a/test/DefaultBtProgressInfoFileTest.cc b/test/DefaultBtProgressInfoFileTest.cc index b6f3564d..42408385 100644 --- a/test/DefaultBtProgressInfoFileTest.cc +++ b/test/DefaultBtProgressInfoFileTest.cc @@ -31,8 +31,6 @@ private: SharedHandle