2010-06-09 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>

Made protected member variables of Command private. Added accessor
	funcs.
pull/1/head
Tatsuhiro Tsujikawa 2010-06-08 15:02:20 +00:00
parent 7cd9b21937
commit 9afc36152a
48 changed files with 541 additions and 436 deletions

View File

@ -1,3 +1,8 @@
2010-06-09 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
Made protected member variables of Command private. Added accessor
funcs.
2010-06-08 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> 2010-06-08 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
Made public member variables of DownloadEngine private. Added Made public member variables of DownloadEngine private. Added

View File

@ -101,20 +101,23 @@ AbstractCommand::~AbstractCommand() {
} }
bool AbstractCommand::execute() { bool AbstractCommand::execute() {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - socket: read:%d, write:%d, hup:%d, err:%d", getLogger()->debug("CUID#%s - socket: read:%d, write:%d, hup:%d, err:%d",
util::itos(cuid).c_str(), _readEvent, _writeEvent, _hupEvent, util::itos(getCuid()).c_str(),
_errorEvent); readEventEnabled(),
writeEventEnabled(),
hupEventEnabled(),
errorEventEnabled());
} }
try { try {
if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) { if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
return true; return true;
} }
if(!req.isNull() && req->removalRequested()) { if(!req.isNull() && req->removalRequested()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug getLogger()->debug
("CUID#%s - Discard original URI=%s because it is requested.", ("CUID#%s - Discard original URI=%s because it is requested.",
util::itos(cuid).c_str(), req->getUri().c_str()); util::itos(getCuid()).c_str(), req->getUri().c_str());
} }
return prepareForRetry(0); return prepareForRetry(0);
} }
@ -124,39 +127,42 @@ bool AbstractCommand::execute() {
!_requestGroup->getPieceStorage()->hasMissingUnusedPiece()) { !_requestGroup->getPieceStorage()->hasMissingUnusedPiece()) {
SharedHandle<Request> fasterRequest = _fileEntry->findFasterRequest(req); SharedHandle<Request> fasterRequest = _fileEntry->findFasterRequest(req);
if(!fasterRequest.isNull()) { if(!fasterRequest.isNull()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Use faster Request hostname=%s, port=%u", getLogger()->info("CUID#%s - Use faster Request hostname=%s, port=%u",
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
fasterRequest->getHost().c_str(), fasterRequest->getHost().c_str(),
fasterRequest->getPort()); fasterRequest->getPort());
} }
// Cancel current Request object and use faster one. // Cancel current Request object and use faster one.
_fileEntry->removeRequest(req); _fileEntry->removeRequest(req);
Command* command = Command* command =
InitiateConnectionCommandFactory::createInitiateConnectionCommand InitiateConnectionCommandFactory::createInitiateConnectionCommand
(cuid, fasterRequest, _fileEntry, _requestGroup, e); (getCuid(), fasterRequest, _fileEntry, _requestGroup, e);
e->setNoWait(true); e->setNoWait(true);
e->addCommand(command); e->addCommand(command);
return true; return true;
} }
} }
if((checkSocketIsReadable && _readEvent) || if((checkSocketIsReadable && readEventEnabled()) ||
(checkSocketIsWritable && _writeEvent) || (checkSocketIsWritable && writeEventEnabled()) ||
_hupEvent || hupEventEnabled() ||
#ifdef ENABLE_ASYNC_DNS #ifdef ENABLE_ASYNC_DNS
(nameResolverCheck && nameResolveFinished()) || (nameResolverCheck && nameResolveFinished()) ||
#endif // ENABLE_ASYNC_DNS #endif // ENABLE_ASYNC_DNS
(!checkSocketIsReadable && !checkSocketIsWritable && !nameResolverCheck)) { (!checkSocketIsReadable && !checkSocketIsWritable &&
!nameResolverCheck)) {
checkPoint = global::wallclock; checkPoint = global::wallclock;
if(!_requestGroup->getPieceStorage().isNull()) { if(!_requestGroup->getPieceStorage().isNull()) {
_segments.clear(); _segments.clear();
_requestGroup->getSegmentMan()->getInFlightSegment(_segments, cuid); _requestGroup->getSegmentMan()->getInFlightSegment
(_segments, getCuid());
if(!req.isNull() && _segments.empty()) { if(!req.isNull() && _segments.empty()) {
// This command previously has assigned segments, but it is // This command previously has assigned segments, but it is
// canceled. So discard current request chain. // canceled. So discard current request chain.
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - It seems previously assigned segments are" getLogger()->debug("CUID#%s - It seems previously assigned segments"
" canceled. Restart.", util::itos(cuid).c_str()); " are canceled. Restart.",
util::itos(getCuid()).c_str());
} }
return prepareForRetry(0); return prepareForRetry(0);
} }
@ -164,21 +170,22 @@ bool AbstractCommand::execute() {
_requestGroup->getDownloadContext()->getFileEntries().size() == 1) { _requestGroup->getDownloadContext()->getFileEntries().size() == 1) {
if(_segments.empty()) { if(_segments.empty()) {
SharedHandle<Segment> segment = SharedHandle<Segment> segment =
_requestGroup->getSegmentMan()->getSegment(cuid); _requestGroup->getSegmentMan()->getSegment(getCuid());
if(!segment.isNull()) { if(!segment.isNull()) {
_segments.push_back(segment); _segments.push_back(segment);
} }
} }
if(_segments.empty()) { if(_segments.empty()) {
// TODO socket could be pooled here if pipelining is enabled... // TODO socket could be pooled here if pipelining is enabled...
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_NO_SEGMENT_AVAILABLE, util::itos(cuid).c_str()); getLogger()->info(MSG_NO_SEGMENT_AVAILABLE,
util::itos(getCuid()).c_str());
} }
// When all segments are ignored in SegmentMan, there are // When all segments are ignored in SegmentMan, there are
// no URIs available, so don't retry. // no URIs available, so don't retry.
if(_requestGroup->getSegmentMan()->allSegmentsIgnored()) { if(_requestGroup->getSegmentMan()->allSegmentsIgnored()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("All segments are ignored."); getLogger()->debug("All segments are ignored.");
} }
return true; return true;
} else { } else {
@ -189,7 +196,7 @@ bool AbstractCommand::execute() {
size_t maxSegments = req->getMaxPipelinedRequest(); size_t maxSegments = req->getMaxPipelinedRequest();
if(_segments.size() < maxSegments) { if(_segments.size() < maxSegments) {
_requestGroup->getSegmentMan()->getSegment _requestGroup->getSegmentMan()->getSegment
(_segments, cuid, _fileEntry, maxSegments); (_segments, getCuid(), _fileEntry, maxSegments);
} }
if(_segments.empty()) { if(_segments.empty()) {
return prepareForRetry(0); return prepareForRetry(0);
@ -197,7 +204,7 @@ bool AbstractCommand::execute() {
} }
} }
return executeInternal(); return executeInternal();
} else if(_errorEvent) { } else if(errorEventEnabled()) {
throw DL_RETRY_EX throw DL_RETRY_EX
(StringFormat(MSG_NETWORK_PROBLEM, (StringFormat(MSG_NETWORK_PROBLEM,
socket->getSocketError().c_str()).str()); socket->getSocketError().c_str()).str());
@ -217,14 +224,15 @@ bool AbstractCommand::execute() {
} }
} catch(DlAbortEx& err) { } catch(DlAbortEx& err) {
if(req.isNull()) { if(req.isNull()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug(EX_EXCEPTION_CAUGHT, err); getLogger()->debug(EX_EXCEPTION_CAUGHT, err);
} }
} else { } else {
logger->error(MSG_DOWNLOAD_ABORTED, getLogger()->error
DL_ABORT_EX2(StringFormat (MSG_DOWNLOAD_ABORTED,
("URI=%s", req->getCurrentUri().c_str()).str(),err), DL_ABORT_EX2(StringFormat
util::itos(cuid).c_str(), req->getUri().c_str()); ("URI=%s", req->getCurrentUri().c_str()).str(),err),
util::itos(getCuid()).c_str(), req->getUri().c_str());
_fileEntry->addURIResult(req->getUri(), err.getCode()); _fileEntry->addURIResult(req->getUri(), err.getCode());
_requestGroup->setLastUriResult(req->getUri(), err.getCode()); _requestGroup->setLastUriResult(req->getUri(), err.getCode());
if(err.getCode() == downloadresultcode::CANNOT_RESUME) { if(err.getCode() == downloadresultcode::CANNOT_RESUME) {
@ -236,23 +244,26 @@ bool AbstractCommand::execute() {
return true; return true;
} catch(DlRetryEx& err) { } catch(DlRetryEx& err) {
assert(!req.isNull()); assert(!req.isNull());
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_RESTARTING_DOWNLOAD, getLogger()->info
DL_RETRY_EX2(StringFormat (MSG_RESTARTING_DOWNLOAD,
("URI=%s", req->getCurrentUri().c_str()).str(), DL_RETRY_EX2(StringFormat
err), ("URI=%s", req->getCurrentUri().c_str()).str(),
util::itos(cuid).c_str(), req->getUri().c_str()); err),
util::itos(getCuid()).c_str(), req->getUri().c_str());
} }
req->addTryCount(); req->addTryCount();
req->resetRedirectCount(); req->resetRedirectCount();
const unsigned int maxTries = getOption()->getAsInt(PREF_MAX_TRIES); const unsigned int maxTries = getOption()->getAsInt(PREF_MAX_TRIES);
bool isAbort = maxTries != 0 && req->getTryCount() >= maxTries; bool isAbort = maxTries != 0 && req->getTryCount() >= maxTries;
if(isAbort) { if(isAbort) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_MAX_TRY, util::itos(cuid).c_str(), req->getTryCount()); getLogger()->info(MSG_MAX_TRY,
util::itos(getCuid()).c_str(), req->getTryCount());
} }
logger->error(MSG_DOWNLOAD_ABORTED, err, util::itos(cuid).c_str(), getLogger()->error(MSG_DOWNLOAD_ABORTED, err,
req->getUri().c_str()); util::itos(getCuid()).c_str(),
req->getUri().c_str());
_fileEntry->addURIResult(req->getUri(), err.getCode()); _fileEntry->addURIResult(req->getUri(), err.getCode());
_requestGroup->setLastUriResult(req->getUri(), err.getCode()); _requestGroup->setLastUriResult(req->getUri(), err.getCode());
if(err.getCode() == downloadresultcode::CANNOT_RESUME) { if(err.getCode() == downloadresultcode::CANNOT_RESUME) {
@ -265,7 +276,7 @@ bool AbstractCommand::execute() {
return prepareForRetry(0); return prepareForRetry(0);
} }
} catch(DownloadFailureException& err) { } catch(DownloadFailureException& err) {
logger->error(EX_EXCEPTION_CAUGHT, err); getLogger()->error(EX_EXCEPTION_CAUGHT, err);
if(!req.isNull()) { if(!req.isNull()) {
_fileEntry->addURIResult(req->getUri(), err.getCode()); _fileEntry->addURIResult(req->getUri(), err.getCode());
_requestGroup->setLastUriResult(req->getUri(), err.getCode()); _requestGroup->setLastUriResult(req->getUri(), err.getCode());
@ -283,18 +294,18 @@ void AbstractCommand::tryReserved() {
// and there are no URI left. Because file length is unknown, we // and there are no URI left. Because file length is unknown, we
// can assume that there are no in-flight request object. // can assume that there are no in-flight request object.
if(entry->getLength() == 0 && entry->getRemainingUris().empty()) { if(entry->getLength() == 0 && entry->getRemainingUris().empty()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Not trying next request." getLogger()->debug("CUID#%s - Not trying next request."
" No reserved/pooled request is remaining and" " No reserved/pooled request is remaining and"
" total length is still unknown.", " total length is still unknown.",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
return; return;
} }
} }
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Trying reserved/pooled request.", getLogger()->debug("CUID#%s - Trying reserved/pooled request.",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
std::vector<Command*> commands; std::vector<Command*> commands;
_requestGroup->createNextCommand(commands, e, 1); _requestGroup->createNextCommand(commands, e, 1);
@ -304,25 +315,25 @@ void AbstractCommand::tryReserved() {
bool AbstractCommand::prepareForRetry(time_t wait) { bool AbstractCommand::prepareForRetry(time_t wait) {
if(!_requestGroup->getPieceStorage().isNull()) { if(!_requestGroup->getPieceStorage().isNull()) {
_requestGroup->getSegmentMan()->cancelSegment(cuid); _requestGroup->getSegmentMan()->cancelSegment(getCuid());
} }
if(!req.isNull()) { if(!req.isNull()) {
_fileEntry->poolRequest(req); _fileEntry->poolRequest(req);
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Pooling request URI=%s", getLogger()->debug("CUID#%s - Pooling request URI=%s",
util::itos(cuid).c_str(), req->getUri().c_str()); util::itos(getCuid()).c_str(), req->getUri().c_str());
} }
if(!_requestGroup->getSegmentMan().isNull()) { if(!_requestGroup->getSegmentMan().isNull()) {
_requestGroup->getSegmentMan()->recognizeSegmentFor(_fileEntry); _requestGroup->getSegmentMan()->recognizeSegmentFor(_fileEntry);
} }
} }
Command* command = new CreateRequestCommand(cuid, _requestGroup, e); Command* command = new CreateRequestCommand(getCuid(), _requestGroup, e);
if(wait == 0) { if(wait == 0) {
e->setNoWait(true); e->setNoWait(true);
e->addCommand(command); e->addCommand(command);
} else { } else {
SleepCommand* scom = new SleepCommand(cuid, e, _requestGroup, SleepCommand* scom = new SleepCommand(getCuid(), e, _requestGroup,
command, wait); command, wait);
e->addCommand(scom); e->addCommand(scom);
} }
@ -332,17 +343,18 @@ bool AbstractCommand::prepareForRetry(time_t wait) {
void AbstractCommand::onAbort() { void AbstractCommand::onAbort() {
if(!req.isNull()) { if(!req.isNull()) {
// TODO This might be a problem if the failure is caused by proxy. // TODO This might be a problem if the failure is caused by proxy.
e->getRequestGroupMan()->getOrCreateServerStat(req->getHost(), e->getRequestGroupMan()->getOrCreateServerStat
req->getProtocol())->setError(); (req->getHost(), req->getProtocol())->setError();
_fileEntry->removeIdenticalURI(req->getUri()); _fileEntry->removeIdenticalURI(req->getUri());
_fileEntry->removeRequest(req); _fileEntry->removeRequest(req);
} }
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Aborting download", util::itos(cuid).c_str()); getLogger()->debug("CUID#%s - Aborting download",
util::itos(getCuid()).c_str());
} }
if(!_requestGroup->getPieceStorage().isNull()) { if(!_requestGroup->getPieceStorage().isNull()) {
SharedHandle<SegmentMan> segmentMan = _requestGroup->getSegmentMan(); SharedHandle<SegmentMan> segmentMan = _requestGroup->getSegmentMan();
segmentMan->cancelSegment(cuid); segmentMan->cancelSegment(getCuid());
// Don't do following process if BitTorrent is involved or files // Don't do following process if BitTorrent is involved or files
// in DownloadContext is more than 1. The latter condition is // in DownloadContext is more than 1. The latter condition is
// limitation of current implementation. // limitation of current implementation.
@ -357,12 +369,13 @@ void AbstractCommand::onAbort() {
// Local file exists, but given servers(or at least contacted // Local file exists, but given servers(or at least contacted
// ones) doesn't support resume. Let's restart download from // ones) doesn't support resume. Let's restart download from
// scratch. // scratch.
logger->notice("CUID#%s - Failed to resume download." getLogger()->notice("CUID#%s - Failed to resume download."
" Download from scratch.", " Download from scratch.",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Gathering URIs that has CANNOT_RESUME error", getLogger()->debug
util::itos(cuid).c_str()); ("CUID#%s - Gathering URIs that has CANNOT_RESUME error",
util::itos(getCuid()).c_str());
} }
// Set PREF_ALWAYS_RESUME to V_TRUE to avoid repeating this // Set PREF_ALWAYS_RESUME to V_TRUE to avoid repeating this
// process. // process.
@ -377,10 +390,10 @@ void AbstractCommand::onAbort() {
uris.reserve(res.size()); uris.reserve(res.size());
std::transform(res.begin(), res.end(), std::back_inserter(uris), std::transform(res.begin(), res.end(), std::back_inserter(uris),
std::mem_fun_ref(&URIResult::getURI)); std::mem_fun_ref(&URIResult::getURI));
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - %lu URIs found.", getLogger()->debug("CUID#%s - %lu URIs found.",
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
static_cast<unsigned long int>(uris.size())); static_cast<unsigned long int>(uris.size()));
} }
_fileEntry->addUris(uris.begin(), uris.end()); _fileEntry->addUris(uris.begin(), uris.end());
segmentMan->recognizeSegmentFor(_fileEntry); segmentMan->recognizeSegmentFor(_fileEntry);
@ -571,13 +584,14 @@ SharedHandle<Request> AbstractCommand::createProxyRequest() const
if(!proxy.empty()) { if(!proxy.empty()) {
proxyRequest.reset(new Request()); proxyRequest.reset(new Request());
if(proxyRequest->setUri(proxy)) { if(proxyRequest->setUri(proxy)) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Using proxy", util::itos(cuid).c_str()); getLogger()->debug("CUID#%s - Using proxy",
util::itos(getCuid()).c_str());
} }
} else { } else {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Failed to parse proxy string", getLogger()->debug("CUID#%s - Failed to parse proxy string",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
proxyRequest.reset(); proxyRequest.reset();
} }
@ -595,9 +609,9 @@ bool AbstractCommand::isAsyncNameResolverInitialized() const
void AbstractCommand::initAsyncNameResolver(const std::string& hostname) void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
{ {
_asyncNameResolver.reset(new AsyncNameResolver()); _asyncNameResolver.reset(new AsyncNameResolver());
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_RESOLVING_HOSTNAME, getLogger()->info(MSG_RESOLVING_HOSTNAME,
util::itos(cuid).c_str(), hostname.c_str()); util::itos(getCuid()).c_str(), hostname.c_str());
} }
_asyncNameResolver->resolve(hostname); _asyncNameResolver->resolve(hostname);
setNameResolverCheck(_asyncNameResolver); setNameResolverCheck(_asyncNameResolver);
@ -615,10 +629,11 @@ bool AbstractCommand::asyncResolveHostname()
e->getRequestGroupMan()->getOrCreateServerStat e->getRequestGroupMan()->getOrCreateServerStat
(req->getHost(), req->getProtocol())->setError(); (req->getHost(), req->getProtocol())->setError();
} }
throw DL_ABORT_EX(StringFormat(MSG_NAME_RESOLUTION_FAILED, throw DL_ABORT_EX
util::itos(cuid).c_str(), (StringFormat(MSG_NAME_RESOLUTION_FAILED,
_asyncNameResolver->getHostname().c_str(), util::itos(getCuid()).c_str(),
_asyncNameResolver->getError().c_str()).str()); _asyncNameResolver->getHostname().c_str(),
_asyncNameResolver->getError().c_str()).str());
default: default:
return false; return false;
} }
@ -678,10 +693,11 @@ std::string AbstractCommand::resolveHostname
} }
res.resolve(addrs, hostname); res.resolve(addrs, hostname);
} }
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_NAME_RESOLUTION_COMPLETE, util::itos(cuid).c_str(), getLogger()->info(MSG_NAME_RESOLUTION_COMPLETE,
hostname.c_str(), util::itos(getCuid()).c_str(),
strjoin(addrs.begin(), addrs.end(), ", ").c_str()); hostname.c_str(),
strjoin(addrs.begin(), addrs.end(), ", ").c_str());
} }
for(std::vector<std::string>::const_iterator i = addrs.begin(), for(std::vector<std::string>::const_iterator i = addrs.begin(),
eoi = addrs.end(); i != eoi; ++i) { eoi = addrs.end(); i != eoi; ++i) {
@ -690,10 +706,10 @@ std::string AbstractCommand::resolveHostname
ipaddr = e->findCachedIPAddress(hostname, port); ipaddr = e->findCachedIPAddress(hostname, port);
} else { } else {
ipaddr = addrs.front(); ipaddr = addrs.front();
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_DNS_CACHE_HIT, getLogger()->info(MSG_DNS_CACHE_HIT,
util::itos(cuid).c_str(), hostname.c_str(), util::itos(getCuid()).c_str(), hostname.c_str(),
strjoin(addrs.begin(), addrs.end(), ", ").c_str()); strjoin(addrs.begin(), addrs.end(), ", ").c_str());
} }
} }
return ipaddr; return ipaddr;
@ -730,14 +746,14 @@ bool AbstractCommand::checkIfConnectionEstablished
// See also InitiateConnectionCommand::executeInternal() // See also InitiateConnectionCommand::executeInternal()
e->markBadIPAddress(connectedHostname, connectedAddr, connectedPort); e->markBadIPAddress(connectedHostname, connectedAddr, connectedPort);
if(!e->findCachedIPAddress(connectedHostname, connectedPort).empty()) { if(!e->findCachedIPAddress(connectedHostname, connectedPort).empty()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECT_FAILED_AND_RETRY, getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY,
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
connectedAddr.c_str(), connectedPort); connectedAddr.c_str(), connectedPort);
} }
Command* command = Command* command =
InitiateConnectionCommandFactory::createInitiateConnectionCommand InitiateConnectionCommandFactory::createInitiateConnectionCommand
(cuid, req, _fileEntry, _requestGroup, e); (getCuid(), req, _fileEntry, _requestGroup, e);
e->setNoWait(true); e->setNoWait(true);
e->addCommand(command); e->addCommand(command);
return false; return false;

View File

@ -145,9 +145,9 @@ void ActivePeerConnectionCommand::connectToPeer(const SharedHandle<Peer>& peer)
command->setPeerStorage(_peerStorage); command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage); command->setPieceStorage(_pieceStorage);
e->addCommand(command); e->addCommand(command);
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_PEER, getLogger()->info(MSG_CONNECTING_TO_PEER,
util::itos(cuid).c_str(), peer->ipaddr.c_str()); util::itos(getCuid()).c_str(), peer->ipaddr.c_str());
} }
} }

View File

@ -60,9 +60,9 @@ void BtStopDownloadCommand::preProcess()
_exit = true; _exit = true;
} }
if(_checkPoint.difference(global::wallclock) >= _timeout) { if(_checkPoint.difference(global::wallclock) >= _timeout) {
logger->notice("GID#%s Stop downloading torrent due to" getLogger()->notice("GID#%s Stop downloading torrent due to"
" --bt-stop-timeout option.", " --bt-stop-timeout option.",
util::itos(_requestGroup->getGID()).c_str()); util::itos(_requestGroup->getGID()).c_str());
_requestGroup->setHaltRequested(true); _requestGroup->setHaltRequested(true);
_exit = true; _exit = true;
} }

View File

@ -72,8 +72,9 @@ bool CheckIntegrityCommand::executeInternal()
// needed. // needed.
_requestGroup->enableSaveControlFile(); _requestGroup->enableSaveControlFile();
if(_requestGroup->downloadFinished()) { if(_requestGroup->downloadFinished()) {
logger->notice(MSG_VERIFICATION_SUCCESSFUL, getLogger()->notice
_requestGroup->getDownloadContext()->getBasePath().c_str()); (MSG_VERIFICATION_SUCCESSFUL,
_requestGroup->getDownloadContext()->getBasePath().c_str());
std::vector<Command*> commands; std::vector<Command*> commands;
try { try {
_entry->onDownloadFinished(commands, _e); _entry->onDownloadFinished(commands, _e);
@ -83,8 +84,9 @@ bool CheckIntegrityCommand::executeInternal()
} }
_e->addCommand(commands); _e->addCommand(commands);
} else { } else {
logger->error(MSG_VERIFICATION_FAILED, getLogger()->error
_requestGroup->getDownloadContext()->getBasePath().c_str()); (MSG_VERIFICATION_FAILED,
_requestGroup->getDownloadContext()->getBasePath().c_str());
std::vector<Command*> commands; std::vector<Command*> commands;
try { try {
_entry->onDownloadIncomplete(commands,_e); _entry->onDownloadIncomplete(commands,_e);
@ -105,10 +107,12 @@ bool CheckIntegrityCommand::executeInternal()
bool CheckIntegrityCommand::handleException(Exception& e) bool CheckIntegrityCommand::handleException(Exception& e)
{ {
_e->getCheckIntegrityMan()->dropPickedEntry(); _e->getCheckIntegrityMan()->dropPickedEntry();
logger->error(MSG_FILE_VALIDATION_FAILURE, e, util::itos(cuid).c_str()); getLogger()->error(MSG_FILE_VALIDATION_FAILURE, e,
logger->error(MSG_DOWNLOAD_NOT_COMPLETE, util::itos(getCuid()).c_str());
util::itos(cuid).c_str(), getLogger()->error
_requestGroup->getDownloadContext()->getBasePath().c_str()); (MSG_DOWNLOAD_NOT_COMPLETE,
util::itos(getCuid()).c_str(),
_requestGroup->getDownloadContext()->getBasePath().c_str());
return true; return true;
} }

View File

@ -57,9 +57,10 @@ Command* CheckIntegrityDispatcherCommand::createCommand
(const SharedHandle<CheckIntegrityEntry>& entry) (const SharedHandle<CheckIntegrityEntry>& entry)
{ {
cuid_t newCUID = _e->newCUID(); cuid_t newCUID = _e->newCUID();
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Dispatching CheckIntegrityCommand CUID#%s.", getLogger()->info("CUID#%s - Dispatching CheckIntegrityCommand CUID#%s.",
util::itos(cuid).c_str(), util::itos(newCUID).c_str()); util::itos(getCuid()).c_str(),
util::itos(newCUID).c_str());
} }
return new CheckIntegrityCommand return new CheckIntegrityCommand
(newCUID, entry->getRequestGroup(), _e, entry); (newCUID, entry->getRequestGroup(), _e, entry);

View File

@ -41,9 +41,9 @@ namespace aria2 {
int32_t Command::uuidGen = 0; int32_t Command::uuidGen = 0;
Command::Command(cuid_t cuid):uuid(uuidGen++), Command::Command(cuid_t cuid):uuid(uuidGen++),
status(STATUS_INACTIVE), _status(STATUS_INACTIVE),
cuid(cuid), _cuid(cuid),
logger(LogFactory::getInstance()), _logger(LogFactory::getInstance()),
_readEvent(false), _readEvent(false),
_writeEvent(false), _writeEvent(false),
_errorEvent(false), _errorEvent(false),
@ -51,17 +51,17 @@ Command::Command(cuid_t cuid):uuid(uuidGen++),
void Command::transitStatus() void Command::transitStatus()
{ {
switch(status) { switch(_status) {
case STATUS_REALTIME: case STATUS_REALTIME:
break; break;
default: default:
status = STATUS_INACTIVE; _status = STATUS_INACTIVE;
} }
} }
void Command::setStatus(STATUS status) void Command::setStatus(STATUS status)
{ {
this->status = status; _status = status;
} }
void Command::readEventReceived() void Command::readEventReceived()

View File

@ -58,15 +58,40 @@ public:
private: private:
CommandUuid uuid; CommandUuid uuid;
static int32_t uuidGen; static int32_t uuidGen;
STATUS status; STATUS _status;
protected:
cuid_t cuid; cuid_t _cuid;
Logger* logger; Logger* _logger;
bool _readEvent; bool _readEvent;
bool _writeEvent; bool _writeEvent;
bool _errorEvent; bool _errorEvent;
bool _hupEvent; bool _hupEvent;
protected:
Logger* getLogger() const
{
return _logger;
}
bool readEventEnabled() const
{
return _readEvent;
}
bool writeEventEnabled() const
{
return _writeEvent;
}
bool errorEventEnabled() const
{
return _errorEvent;
}
bool hupEventEnabled() const
{
return _hupEvent;
}
public: public:
Command(cuid_t cuid); Command(cuid_t cuid);
@ -74,21 +99,21 @@ public:
virtual bool execute() = 0; virtual bool execute() = 0;
cuid_t getCuid() const { return cuid; } cuid_t getCuid() const { return _cuid; }
const CommandUuid& getUuid() const { return uuid; } const CommandUuid& getUuid() const { return uuid; }
void setStatusActive() { this->status = STATUS_ACTIVE; } void setStatusActive() { _status = STATUS_ACTIVE; }
void setStatusInactive() { this->status = STATUS_INACTIVE; } void setStatusInactive() { _status = STATUS_INACTIVE; }
void setStatusRealtime() { this->status = STATUS_REALTIME; } void setStatusRealtime() { _status = STATUS_REALTIME; }
void setStatus(STATUS status); void setStatus(STATUS status);
bool statusMatch(Command::STATUS statusFilter) const bool statusMatch(Command::STATUS statusFilter) const
{ {
return statusFilter <= status; return statusFilter <= _status;
} }
void transitStatus(); void transitStatus();

View File

@ -97,7 +97,7 @@ bool CreateRequestCommand::executeInternal()
Command* command = Command* command =
InitiateConnectionCommandFactory::createInitiateConnectionCommand InitiateConnectionCommandFactory::createInitiateConnectionCommand
(cuid, req, _fileEntry, _requestGroup, e); (getCuid(), req, _fileEntry, _requestGroup, e);
e->setNoWait(true); e->setNoWait(true);
e->addCommand(command); e->addCommand(command);
return true; return true;
@ -114,13 +114,14 @@ bool CreateRequestCommand::prepareForRetry(time_t wait)
// CreateRequestCommand is deleted one second later: This is not // CreateRequestCommand is deleted one second later: This is not
// efficient. For this reason, reuse current CreateRequestCommand. // efficient. For this reason, reuse current CreateRequestCommand.
if(!_requestGroup->getPieceStorage().isNull()) { if(!_requestGroup->getPieceStorage().isNull()) {
_requestGroup->getSegmentMan()->cancelSegment(cuid); _requestGroup->getSegmentMan()->cancelSegment(getCuid());
} }
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Reusing CreateRequestCommand", getLogger()->debug("CUID#%s - Reusing CreateRequestCommand",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
SleepCommand* scom = new SleepCommand(cuid, e, _requestGroup, this, wait); SleepCommand* scom = new SleepCommand
(getCuid(), e, _requestGroup, this, wait);
e->addCommand(scom); e->addCommand(scom);
return false; return false;
} }

View File

@ -82,7 +82,7 @@ void DHTAutoSaveCommand::process()
void DHTAutoSaveCommand::save() void DHTAutoSaveCommand::save()
{ {
std::string dhtFile = _e->getOption()->get(PREF_DHT_FILE_PATH); std::string dhtFile = _e->getOption()->get(PREF_DHT_FILE_PATH);
logger->info("Saving DHT routing table to %s.", dhtFile.c_str()); getLogger()->info("Saving DHT routing table to %s.", dhtFile.c_str());
std::string tempFile = dhtFile; std::string tempFile = dhtFile;
tempFile += "__temp"; tempFile += "__temp";
@ -92,11 +92,12 @@ void DHTAutoSaveCommand::save()
File dir(f.getDirname()); File dir(f.getDirname());
if(!dir.exists()) { if(!dir.exists()) {
if(!dir.mkdirs()) { if(!dir.mkdirs()) {
logger->info(EX_MAKE_DIR, dir.getPath().c_str(), strerror(errno)); getLogger()->info(EX_MAKE_DIR,
dir.getPath().c_str(), strerror(errno));
return; return;
} }
} else if(!dir.isDir()) { } else if(!dir.isDir()) {
logger->info(EX_NOT_DIRECTORY, dir.getPath().c_str()); getLogger()->info(EX_NOT_DIRECTORY, dir.getPath().c_str());
return; return;
} }
} }
@ -127,12 +128,12 @@ void DHTAutoSaveCommand::save()
serializer.serialize(o); serializer.serialize(o);
} }
if(!File(tempFile).renameTo(dhtFile)) { if(!File(tempFile).renameTo(dhtFile)) {
logger->error("Cannot move file from %s to %s.", getLogger()->error("Cannot move file from %s to %s.",
tempFile.c_str(), dhtFile.c_str()); tempFile.c_str(), dhtFile.c_str());
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error("Exception caught while saving DHT routing table to %s", getLogger()->error("Exception caught while saving DHT routing table to %s",
e, dhtFile.c_str()); e, dhtFile.c_str());
} }
} }

View File

@ -101,7 +101,7 @@ bool DHTEntryPointNameResolveCommand::execute()
return false; return false;
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(EX_EXCEPTION_CAUGHT, e); getLogger()->error(EX_EXCEPTION_CAUGHT, e);
} }
_resolver->reset(); _resolver->reset();
_entryPoints.pop_front(); _entryPoints.pop_front();
@ -122,22 +122,24 @@ bool DHTEntryPointNameResolveCommand::execute()
_resolvedEntryPoints.push_back(p); _resolvedEntryPoints.push_back(p);
addPingTask(p); addPingTask(p);
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(EX_EXCEPTION_CAUGHT, e); getLogger()->error(EX_EXCEPTION_CAUGHT, e);
} }
_entryPoints.pop_front(); _entryPoints.pop_front();
} }
} }
if(_bootstrapEnabled && _resolvedEntryPoints.size()) { if(_bootstrapEnabled && _resolvedEntryPoints.size()) {
_taskQueue->addPeriodicTask1(_taskFactory->createNodeLookupTask(_localNode->getID())); _taskQueue->addPeriodicTask1(_taskFactory->createNodeLookupTask
(_localNode->getID()));
_taskQueue->addPeriodicTask1(_taskFactory->createBucketRefreshTask()); _taskQueue->addPeriodicTask1(_taskFactory->createBucketRefreshTask());
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(EX_EXCEPTION_CAUGHT, e); getLogger()->error(EX_EXCEPTION_CAUGHT, e);
} }
return true; return true;
} }
void DHTEntryPointNameResolveCommand::addPingTask(const std::pair<std::string, uint16_t>& addr) void DHTEntryPointNameResolveCommand::addPingTask
(const std::pair<std::string, uint16_t>& addr)
{ {
SharedHandle<DHTNode> entryNode(new DHTNode()); SharedHandle<DHTNode> entryNode(new DHTNode());
entryNode->setIPAddress(addr.first); entryNode->setIPAddress(addr.first);
@ -154,26 +156,26 @@ bool DHTEntryPointNameResolveCommand::resolveHostname
{ {
switch(resolver->getStatus()) { switch(resolver->getStatus()) {
case AsyncNameResolver::STATUS_READY: case AsyncNameResolver::STATUS_READY:
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_RESOLVING_HOSTNAME, getLogger()->info(MSG_RESOLVING_HOSTNAME,
util::itos(cuid).c_str(), hostname.c_str()); util::itos(getCuid()).c_str(), hostname.c_str());
} }
resolver->resolve(hostname); resolver->resolve(hostname);
setNameResolverCheck(resolver); setNameResolverCheck(resolver);
return false; return false;
case AsyncNameResolver::STATUS_SUCCESS: case AsyncNameResolver::STATUS_SUCCESS:
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_NAME_RESOLUTION_COMPLETE, getLogger()->info(MSG_NAME_RESOLUTION_COMPLETE,
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
resolver->getHostname().c_str(), resolver->getHostname().c_str(),
resolver->getResolvedAddresses().front().c_str()); resolver->getResolvedAddresses().front().c_str());
} }
return true; return true;
break; break;
case AsyncNameResolver::STATUS_ERROR: case AsyncNameResolver::STATUS_ERROR:
throw DL_ABORT_EX throw DL_ABORT_EX
(StringFormat(MSG_NAME_RESOLUTION_FAILED, (StringFormat(MSG_NAME_RESOLUTION_FAILED,
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
hostname.c_str(), hostname.c_str(),
resolver->getError().c_str()).str()); resolver->getError().c_str()).str());
default: default:
@ -199,22 +201,26 @@ void DHTEntryPointNameResolveCommand::setBootstrapEnabled(bool f)
_bootstrapEnabled = f; _bootstrapEnabled = f;
} }
void DHTEntryPointNameResolveCommand::setTaskQueue(const SharedHandle<DHTTaskQueue>& taskQueue) void DHTEntryPointNameResolveCommand::setTaskQueue
(const SharedHandle<DHTTaskQueue>& taskQueue)
{ {
_taskQueue = taskQueue; _taskQueue = taskQueue;
} }
void DHTEntryPointNameResolveCommand::setTaskFactory(const SharedHandle<DHTTaskFactory>& taskFactory) void DHTEntryPointNameResolveCommand::setTaskFactory
(const SharedHandle<DHTTaskFactory>& taskFactory)
{ {
_taskFactory = taskFactory; _taskFactory = taskFactory;
} }
void DHTEntryPointNameResolveCommand::setRoutingTable(const SharedHandle<DHTRoutingTable>& routingTable) void DHTEntryPointNameResolveCommand::setRoutingTable
(const SharedHandle<DHTRoutingTable>& routingTable)
{ {
_routingTable = routingTable; _routingTable = routingTable;
} }
void DHTEntryPointNameResolveCommand::setLocalNode(const SharedHandle<DHTNode>& localNode) void DHTEntryPointNameResolveCommand::setLocalNode
(const SharedHandle<DHTNode>& localNode)
{ {
_localNode = localNode; _localNode = localNode;
} }

View File

@ -80,10 +80,10 @@ bool DHTGetPeersCommand::execute()
((_numRetry > 0 && ((_numRetry > 0 &&
_lastGetPeerTime.difference(global::wallclock) >= (time_t)_numRetry*5) || _lastGetPeerTime.difference(global::wallclock) >= (time_t)_numRetry*5) ||
_lastGetPeerTime.difference(global::wallclock) >= GET_PEER_INTERVAL)) { _lastGetPeerTime.difference(global::wallclock) >= GET_PEER_INTERVAL)) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("Issuing PeerLookup for infoHash=%s", getLogger()->debug("Issuing PeerLookup for infoHash=%s",
bittorrent::getInfoHashString bittorrent::getInfoHashString
(_requestGroup->getDownloadContext()).c_str()); (_requestGroup->getDownloadContext()).c_str());
} }
_task = _taskFactory->createPeerLookupTask _task = _taskFactory->createPeerLookupTask
(_requestGroup->getDownloadContext(), _btRuntime, _peerStorage); (_requestGroup->getDownloadContext(), _btRuntime, _peerStorage);

View File

@ -90,7 +90,7 @@ bool DHTInteractionCommand::execute()
try { try {
_dispatcher->sendMessages(); _dispatcher->sendMessages();
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(EX_EXCEPTION_CAUGHT, e); getLogger()->error(EX_EXCEPTION_CAUGHT, e);
} }
_e->addCommand(this); _e->addCommand(this);
return false; return false;

View File

@ -62,7 +62,7 @@ void DHTPeerAnnounceCommand::process()
try { try {
_peerAnnounceStorage->handleTimeout(); _peerAnnounceStorage->handleTimeout();
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(EX_EXCEPTION_CAUGHT, e); getLogger()->error(EX_EXCEPTION_CAUGHT, e);
} }
} }

View File

@ -63,7 +63,7 @@ void DHTTokenUpdateCommand::process()
try { try {
_tokenTracker->updateTokenSecret(); _tokenTracker->updateTokenSecret();
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(EX_EXCEPTION_CAUGHT, e); getLogger()->error(EX_EXCEPTION_CAUGHT, e);
} }
} }

View File

@ -84,7 +84,8 @@ DownloadCommand::DownloadCommand(cuid_t cuid,
#ifdef ENABLE_MESSAGE_DIGEST #ifdef ENABLE_MESSAGE_DIGEST
{ {
if(getOption()->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) { if(getOption()->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) {
std::string algo = _requestGroup->getDownloadContext()->getPieceHashAlgo(); std::string algo =
_requestGroup->getDownloadContext()->getPieceHashAlgo();
if(MessageDigestContext::supports(algo)) { if(MessageDigestContext::supports(algo)) {
_messageDigestContext.reset(new MessageDigestContext()); _messageDigestContext.reset(new MessageDigestContext());
_messageDigestContext->trySetAlgo(algo); _messageDigestContext->trySetAlgo(algo);
@ -124,7 +125,10 @@ bool DownloadCommand::executeInternal() {
bufSize = std::min(segment->getLength()-segment->getWrittenLength(), bufSize = std::min(segment->getLength()-segment->getWrittenLength(),
BUFSIZE); BUFSIZE);
} else { } else {
bufSize = std::min(static_cast<size_t>(_fileEntry->getLastOffset()-segment->getPositionToWrite()), BUFSIZE); bufSize =
std::min(static_cast<size_t>
(_fileEntry->getLastOffset()-segment->getPositionToWrite()),
BUFSIZE);
} }
} else { } else {
bufSize = BUFSIZE; bufSize = BUFSIZE;
@ -185,7 +189,8 @@ bool DownloadCommand::executeInternal() {
segmentPartComplete = true; segmentPartComplete = true;
} }
} else if(!_transferEncodingDecoder.isNull() && } else if(!_transferEncodingDecoder.isNull() &&
(segment->complete() || segment->getPositionToWrite() == _fileEntry->getLastOffset())) { (segment->complete() ||
segment->getPositionToWrite() == _fileEntry->getLastOffset())) {
// In this case, transferEncodingDecoder is used and // In this case, transferEncodingDecoder is used and
// Content-Length is known. // Content-Length is known.
segmentPartComplete = true; segmentPartComplete = true;
@ -206,43 +211,48 @@ bool DownloadCommand::executeInternal() {
// If segment->getLength() == 0, the server doesn't provide // If segment->getLength() == 0, the server doesn't provide
// content length, but the client detected that download // content length, but the client detected that download
// completed. // completed.
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, util::itos(cuid).c_str()); getLogger()->info(MSG_SEGMENT_DOWNLOAD_COMPLETED,
util::itos(getCuid()).c_str());
} }
#ifdef ENABLE_MESSAGE_DIGEST #ifdef ENABLE_MESSAGE_DIGEST
{ {
const std::string& expectedPieceHash = const std::string& expectedPieceHash =
_requestGroup->getDownloadContext()->getPieceHash(segment->getIndex()); _requestGroup->getDownloadContext()->getPieceHash
(segment->getIndex());
if(_pieceHashValidationEnabled && !expectedPieceHash.empty()) { if(_pieceHashValidationEnabled && !expectedPieceHash.empty()) {
if(segment->isHashCalculated()) { if(segment->isHashCalculated()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("Hash is available! index=%lu", getLogger()->debug
static_cast<unsigned long>(segment->getIndex())); ("Hash is available! index=%lu",
static_cast<unsigned long>(segment->getIndex()));
} }
validatePieceHash(segment, expectedPieceHash, segment->getHashString()); validatePieceHash
(segment, expectedPieceHash, segment->getHashString());
} else { } else {
_messageDigestContext->digestReset(); _messageDigestContext->digestReset();
validatePieceHash(segment, expectedPieceHash, validatePieceHash
MessageDigestHelper::digest (segment, expectedPieceHash,
(_messageDigestContext.get(), MessageDigestHelper::digest
_requestGroup->getPieceStorage()->getDiskAdaptor(), (_messageDigestContext.get(),
segment->getPosition(), _requestGroup->getPieceStorage()->getDiskAdaptor(),
segment->getLength())); segment->getPosition(),
segment->getLength()));
} }
} else { } else {
_requestGroup->getSegmentMan()->completeSegment(cuid, segment); _requestGroup->getSegmentMan()->completeSegment(getCuid(), segment);
} }
} }
#else // !ENABLE_MESSAGE_DIGEST #else // !ENABLE_MESSAGE_DIGEST
_requestGroup->getSegmentMan()->completeSegment(cuid, segment); _requestGroup->getSegmentMan()->completeSegment(getCuid(), segment);
#endif // !ENABLE_MESSAGE_DIGEST #endif // !ENABLE_MESSAGE_DIGEST
} else { } else {
// If segment is not canceled here, in the next pipelining // If segment is not canceled here, in the next pipelining
// request, aria2 requests bad range // request, aria2 requests bad range
// [FileEntry->getLastOffset(), FileEntry->getLastOffset()) // [FileEntry->getLastOffset(), FileEntry->getLastOffset())
_requestGroup->getSegmentMan()->cancelSegment(cuid, segment); _requestGroup->getSegmentMan()->cancelSegment(getCuid(), segment);
} }
checkLowestDownloadSpeed(); checkLowestDownloadSpeed();
// this unit is going to download another segment. // this unit is going to download another segment.
@ -314,7 +324,7 @@ bool DownloadCommand::prepareForNextSegment() {
SharedHandle<SegmentMan> segmentMan = _requestGroup->getSegmentMan(); SharedHandle<SegmentMan> segmentMan = _requestGroup->getSegmentMan();
SharedHandle<Segment> nextSegment = SharedHandle<Segment> nextSegment =
segmentMan->getCleanSegmentIfOwnerIsIdle segmentMan->getCleanSegmentIfOwnerIsIdle
(cuid, tempSegment->getIndex()+1); (getCuid(), tempSegment->getIndex()+1);
if(nextSegment.isNull()) { if(nextSegment.isNull()) {
return prepareForRetry(0); return prepareForRetry(0);
} else { } else {
@ -334,16 +344,16 @@ void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment,
const std::string& actualPieceHash) const std::string& actualPieceHash)
{ {
if(actualPieceHash == expectedPieceHash) { if(actualPieceHash == expectedPieceHash) {
logger->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str()); getLogger()->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str());
_requestGroup->getSegmentMan()->completeSegment(cuid, segment); _requestGroup->getSegmentMan()->completeSegment(getCuid(), segment);
} else { } else {
logger->info(EX_INVALID_CHUNK_CHECKSUM, getLogger()->info(EX_INVALID_CHUNK_CHECKSUM,
segment->getIndex(), segment->getIndex(),
util::itos(segment->getPosition(), true).c_str(), util::itos(segment->getPosition(), true).c_str(),
expectedPieceHash.c_str(), expectedPieceHash.c_str(),
actualPieceHash.c_str()); actualPieceHash.c_str());
segment->clear(); segment->clear();
_requestGroup->getSegmentMan()->cancelSegment(cuid); _requestGroup->getSegmentMan()->cancelSegment(getCuid());
throw DL_RETRY_EX throw DL_RETRY_EX
(StringFormat("Invalid checksum index=%d", segment->getIndex()).str()); (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
} }

View File

@ -68,10 +68,11 @@ bool FileAllocationCommand::executeInternal()
} }
_fileAllocationEntry->allocateChunk(); _fileAllocationEntry->allocateChunk();
if(_fileAllocationEntry->finished()) { if(_fileAllocationEntry->finished()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug(MSG_ALLOCATION_COMPLETED, getLogger()->debug
_timer.difference(global::wallclock), (MSG_ALLOCATION_COMPLETED,
util::itos(_requestGroup->getTotalLength(), true).c_str()); _timer.difference(global::wallclock),
util::itos(_requestGroup->getTotalLength(), true).c_str());
} }
_e->getFileAllocationMan()->dropPickedEntry(); _e->getFileAllocationMan()->dropPickedEntry();
@ -94,9 +95,11 @@ bool FileAllocationCommand::executeInternal()
bool FileAllocationCommand::handleException(Exception& e) bool FileAllocationCommand::handleException(Exception& e)
{ {
_e->getFileAllocationMan()->dropPickedEntry(); _e->getFileAllocationMan()->dropPickedEntry();
logger->error(MSG_FILE_ALLOCATION_FAILURE, e, util::itos(cuid).c_str()); getLogger()->error
logger->error(MSG_DOWNLOAD_NOT_COMPLETE, util::itos(cuid).c_str(), (MSG_FILE_ALLOCATION_FAILURE, e, util::itos(getCuid()).c_str());
_requestGroup->getDownloadContext()->getBasePath().c_str()); getLogger()->error
(MSG_DOWNLOAD_NOT_COMPLETE, util::itos(getCuid()).c_str(),
_requestGroup->getDownloadContext()->getBasePath().c_str());
return true; return true;
} }

View File

@ -54,8 +54,9 @@ Command* FileAllocationDispatcherCommand::createCommand
(const SharedHandle<FileAllocationEntry>& entry) (const SharedHandle<FileAllocationEntry>& entry)
{ {
cuid_t newCUID = _e->newCUID(); cuid_t newCUID = _e->newCUID();
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_FILE_ALLOCATION_DISPATCH, util::itos(newCUID).c_str()); getLogger()->info(MSG_FILE_ALLOCATION_DISPATCH,
util::itos(newCUID).c_str());
} }
FileAllocationCommand* command = FileAllocationCommand* command =
new FileAllocationCommand(newCUID, entry->getRequestGroup(), _e, entry); new FileAllocationCommand(newCUID, entry->getRequestGroup(), _e, entry);

View File

@ -70,7 +70,7 @@ bool FillRequestGroupCommand::execute()
rgman->clearQueueCheck(); rgman->clearQueueCheck();
rgman->fillRequestGroupFromReserver(_e); rgman->fillRequestGroupFromReserver(_e);
} catch(RecoverableException& ex) { } catch(RecoverableException& ex) {
logger->error(EX_EXCEPTION_CAUGHT, ex); getLogger()->error(EX_EXCEPTION_CAUGHT, ex);
// Re-request queue check to fulfill the requests of all // Re-request queue check to fulfill the requests of all
// downloads, some might come after this exception. // downloads, some might come after this exception.
rgman->requestQueueCheck(); rgman->requestQueueCheck();

View File

@ -70,9 +70,12 @@ FtpDownloadCommand::~FtpDownloadCommand() {}
bool FtpDownloadCommand::prepareForNextSegment() bool FtpDownloadCommand::prepareForNextSegment()
{ {
if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION) && if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION) &&
static_cast<uint64_t>(_fileEntry->gtoloff(_segments.front()->getPositionToWrite())) == _fileEntry->getLength()) { static_cast<uint64_t>
(_fileEntry->gtoloff(_segments.front()->getPositionToWrite())) ==
_fileEntry->getLength()) {
Command* command = new FtpFinishDownloadCommand Command* command = new FtpFinishDownloadCommand
(cuid, req, _fileEntry, _requestGroup, _ftpConnection, e, ctrlSocket); (getCuid(), req, _fileEntry, _requestGroup, _ftpConnection, e,
ctrlSocket);
e->addCommand(command); e->addCommand(command);
if(_requestGroup->downloadFinished()) { if(_requestGroup->downloadFinished()) {

View File

@ -90,7 +90,7 @@ bool FtpFinishDownloadCommand::execute()
socket, options); socket, options);
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->info(EX_EXCEPTION_CAUGHT, e); getLogger()->info(EX_EXCEPTION_CAUGHT, e);
} }
if(_requestGroup->downloadFinished()) { if(_requestGroup->downloadFinished()) {
return true; return true;

View File

@ -93,9 +93,9 @@ Command* FtpInitiateConnectionCommand::createNextCommand
proxyRequest->getHost(), proxyRequest->getPort()); proxyRequest->getHost(), proxyRequest->getPort());
} }
if(pooledSocket.isNull()) { if(pooledSocket.isNull()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, getLogger()->info(MSG_CONNECTING_TO_SERVER,
util::itos(cuid).c_str(), addr.c_str(), port); util::itos(getCuid()).c_str(), addr.c_str(), port);
} }
socket.reset(new SocketCore()); socket.reset(new SocketCore());
socket->establishConnection(addr, port); socket->establishConnection(addr, port);
@ -104,17 +104,17 @@ Command* FtpInitiateConnectionCommand::createNextCommand
// Use GET for FTP via HTTP proxy. // Use GET for FTP via HTTP proxy.
req->setMethod(Request::METHOD_GET); req->setMethod(Request::METHOD_GET);
SharedHandle<HttpConnection> hc SharedHandle<HttpConnection> hc
(new HttpConnection(cuid, socket, getOption().get())); (new HttpConnection(getCuid(), socket, getOption().get()));
HttpRequestCommand* c = HttpRequestCommand* c =
new HttpRequestCommand(cuid, req, _fileEntry, new HttpRequestCommand(getCuid(), req, _fileEntry,
_requestGroup, hc, e, socket); _requestGroup, hc, e, socket);
c->setConnectedAddr(hostname, addr, port); c->setConnectedAddr(hostname, addr, port);
c->setProxyRequest(proxyRequest); c->setProxyRequest(proxyRequest);
command = c; command = c;
} else if(proxyMethod == V_TUNNEL) { } else if(proxyMethod == V_TUNNEL) {
FtpTunnelRequestCommand* c = FtpTunnelRequestCommand* c =
new FtpTunnelRequestCommand(cuid, req, _fileEntry, new FtpTunnelRequestCommand(getCuid(), req, _fileEntry,
_requestGroup, e, _requestGroup, e,
proxyRequest, socket); proxyRequest, socket);
c->setConnectedAddr(hostname, addr, port); c->setConnectedAddr(hostname, addr, port);
@ -126,7 +126,7 @@ Command* FtpInitiateConnectionCommand::createNextCommand
} else { } else {
if(proxyMethod == V_TUNNEL) { if(proxyMethod == V_TUNNEL) {
command = command =
new FtpNegotiationCommand(cuid, req, _fileEntry, new FtpNegotiationCommand(getCuid(), req, _fileEntry,
_requestGroup, e, pooledSocket, _requestGroup, e, pooledSocket,
FtpNegotiationCommand::SEQ_SEND_CWD, FtpNegotiationCommand::SEQ_SEND_CWD,
options["baseWorkingDir"]); options["baseWorkingDir"]);
@ -134,10 +134,10 @@ Command* FtpInitiateConnectionCommand::createNextCommand
// Use GET for FTP via HTTP proxy. // Use GET for FTP via HTTP proxy.
req->setMethod(Request::METHOD_GET); req->setMethod(Request::METHOD_GET);
SharedHandle<HttpConnection> hc SharedHandle<HttpConnection> hc
(new HttpConnection(cuid, pooledSocket, getOption().get())); (new HttpConnection(getCuid(), pooledSocket, getOption().get()));
HttpRequestCommand* c = HttpRequestCommand* c =
new HttpRequestCommand(cuid, req, _fileEntry, new HttpRequestCommand(getCuid(), req, _fileEntry,
_requestGroup, hc, e, pooledSocket); _requestGroup, hc, e, pooledSocket);
c->setProxyRequest(proxyRequest); c->setProxyRequest(proxyRequest);
command = c; command = c;
@ -153,20 +153,20 @@ Command* FtpInitiateConnectionCommand::createNextCommand
e->getAuthConfigFactory()->createAuthConfig e->getAuthConfigFactory()->createAuthConfig
(req, getOption().get())->getUser()); (req, getOption().get())->getUser());
if(pooledSocket.isNull()) { if(pooledSocket.isNull()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, getLogger()->info(MSG_CONNECTING_TO_SERVER,
util::itos(cuid).c_str(), addr.c_str(), port); util::itos(getCuid()).c_str(), addr.c_str(), port);
} }
socket.reset(new SocketCore()); socket.reset(new SocketCore());
socket->establishConnection(addr, port); socket->establishConnection(addr, port);
FtpNegotiationCommand* c = FtpNegotiationCommand* c =
new FtpNegotiationCommand(cuid, req, _fileEntry, new FtpNegotiationCommand(getCuid(), req, _fileEntry,
_requestGroup, e, socket); _requestGroup, e, socket);
c->setConnectedAddr(hostname, addr, port); c->setConnectedAddr(hostname, addr, port);
command = c; command = c;
} else { } else {
command = command =
new FtpNegotiationCommand(cuid, req, _fileEntry, new FtpNegotiationCommand(getCuid(), req, _fileEntry,
_requestGroup, e, pooledSocket, _requestGroup, e, pooledSocket,
FtpNegotiationCommand::SEQ_SEND_CWD, FtpNegotiationCommand::SEQ_SEND_CWD,
options["baseWorkingDir"]); options["baseWorkingDir"]);

View File

@ -109,9 +109,10 @@ bool FtpNegotiationCommand::executeInternal() {
} else if(sequence == SEQ_NEGOTIATION_COMPLETED) { } else if(sequence == SEQ_NEGOTIATION_COMPLETED) {
FtpDownloadCommand* command = FtpDownloadCommand* command =
new FtpDownloadCommand new FtpDownloadCommand
(cuid, req, _fileEntry, _requestGroup, ftp, e, dataSocket, socket); (getCuid(), req, _fileEntry, _requestGroup, ftp, e, dataSocket, socket);
command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)); command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
command->setLowestDownloadSpeedLimit(getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT)); command->setLowestDownloadSpeedLimit
(getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
if(!_fileEntry->isSingleHostMultiConnectionEnabled()) { if(!_fileEntry->isSingleHostMultiConnectionEnabled()) {
_fileEntry->removeURIWhoseHostnameIs(req->getHost()); _fileEntry->removeURIWhoseHostnameIs(req->getHost());
} }
@ -119,7 +120,8 @@ bool FtpNegotiationCommand::executeInternal() {
(_fileEntry->getRemainingUris(), command); (_fileEntry->getRemainingUris(), command);
e->addCommand(command); e->addCommand(command);
return true; return true;
} else if(sequence == SEQ_HEAD_OK || sequence == SEQ_DOWNLOAD_ALREADY_COMPLETED) { } else if(sequence == SEQ_HEAD_OK ||
sequence == SEQ_DOWNLOAD_ALREADY_COMPLETED) {
return true; return true;
} else if(sequence == SEQ_FILE_PREPARATION) { } else if(sequence == SEQ_FILE_PREPARATION) {
if(getOption()->getAsBool(PREF_FTP_PASV)) { if(getOption()->getAsBool(PREF_FTP_PASV)) {
@ -252,9 +254,9 @@ bool FtpNegotiationCommand::recvPwd()
throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
ftp->setBaseWorkingDir(pwd); ftp->setBaseWorkingDir(pwd);
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - base working directory is '%s'", getLogger()->info("CUID#%s - base working directory is '%s'",
util::itos(cuid).c_str(), pwd.c_str()); util::itos(getCuid()).c_str(), pwd.c_str());
} }
sequence = SEQ_SEND_CWD; sequence = SEQ_SEND_CWD;
return true; return true;
@ -318,23 +320,24 @@ bool FtpNegotiationCommand::recvMdtm()
time_t t = lastModifiedTime.getTime(); time_t t = lastModifiedTime.getTime();
struct tm* tms = gmtime(&t); // returned struct is statically allocated. struct tm* tms = gmtime(&t); // returned struct is statically allocated.
if(tms) { if(tms) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("MDTM result was parsed as: %s GMT", asctime(tms)); getLogger()->debug("MDTM result was parsed as: %s GMT", asctime(tms));
} }
} else { } else {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("gmtime() failed for MDTM result."); getLogger()->debug("gmtime() failed for MDTM result.");
} }
} }
} else { } else {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("MDTM response was returned, but it seems not to be a" getLogger()->debug("MDTM response was returned, but it seems not to be"
" time value as in specified in RFC3659."); " a time value as in specified in RFC3659.");
} }
} }
} else { } else {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - MDTM command failed.", util::itos(cuid).c_str()); getLogger()->info("CUID#%s - MDTM command failed.",
util::itos(getCuid()).c_str());
} }
} }
sequence = SEQ_SEND_SIZE; sequence = SEQ_SEND_SIZE;
@ -385,9 +388,9 @@ bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
_requestGroup->getPieceStorage()->markAllPiecesDone(); _requestGroup->getPieceStorage()->markAllPiecesDone();
sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED; sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED;
logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
util::itos(_requestGroup->getGID()).c_str(), util::itos(_requestGroup->getGID()).c_str(),
_requestGroup->getFirstFilePath().c_str()); _requestGroup->getFirstFilePath().c_str());
poolConnection(); poolConnection();
@ -406,7 +409,7 @@ bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
// We have to make sure that command that has Request object must // We have to make sure that command that has Request object must
// have segment after PieceStorage is initialized. See // have segment after PieceStorage is initialized. See
// AbstractCommand::execute() // AbstractCommand::execute()
_requestGroup->getSegmentMan()->getSegment(cuid, 0); _requestGroup->getSegmentMan()->getSegment(getCuid(), 0);
return true; return true;
} else { } else {
_requestGroup->adjustFilename _requestGroup->adjustFilename
@ -421,15 +424,18 @@ bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
return false; return false;
} }
BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), getOption().get())); BtProgressInfoFileHandle infoFile
(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(),
_requestGroup->getPieceStorage(),
getOption().get()));
if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) { if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
_requestGroup->getPieceStorage()->markAllPiecesDone(); _requestGroup->getPieceStorage()->markAllPiecesDone();
sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED; sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED;
logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
util::itos(_requestGroup->getGID()).c_str(), util::itos(_requestGroup->getGID()).c_str(),
_requestGroup->getFirstFilePath().c_str()); _requestGroup->getFirstFilePath().c_str());
poolConnection(); poolConnection();
@ -439,7 +445,7 @@ bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
// We have to make sure that command that has Request object must // We have to make sure that command that has Request object must
// have segment after PieceStorage is initialized. See // have segment after PieceStorage is initialized. See
// AbstractCommand::execute() // AbstractCommand::execute()
_requestGroup->getSegmentMan()->getSegment(cuid, 0); _requestGroup->getSegmentMan()->getSegment(getCuid(), 0);
prepareForNextAction(this); prepareForNextAction(this);
@ -458,7 +464,8 @@ bool FtpNegotiationCommand::recvSize() {
if(size > INT64_MAX) { if(size > INT64_MAX) {
throw DL_ABORT_EX throw DL_ABORT_EX
(StringFormat(EX_TOO_LARGE_FILE, util::uitos(size, true).c_str()).str()); (StringFormat(EX_TOO_LARGE_FILE,
util::uitos(size, true).c_str()).str());
} }
if(_requestGroup->getPieceStorage().isNull()) { if(_requestGroup->getPieceStorage().isNull()) {
@ -470,9 +477,9 @@ bool FtpNegotiationCommand::recvSize() {
} }
} else { } else {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - The remote FTP Server doesn't recognize SIZE" getLogger()->info("CUID#%s - The remote FTP Server doesn't recognize SIZE"
" command. Continue.", util::itos(cuid).c_str()); " command. Continue.", util::itos(getCuid()).c_str());
} }
// Even if one of the other servers waiting in the queue supports SIZE // Even if one of the other servers waiting in the queue supports SIZE
// command, resuming and segmented downloading are disabled when the first // command, resuming and segmented downloading are disabled when the first
@ -555,10 +562,10 @@ bool FtpNegotiationCommand::recvPasv() {
return true; return true;
} else { } else {
// make a data connection to the server. // make a data connection to the server.
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, util::itos(cuid).c_str(), getLogger()->info(MSG_CONNECTING_TO_SERVER, util::itos(getCuid()).c_str(),
dest.first.c_str(), dest.first.c_str(),
dest.second); dest.second);
} }
dataSocket.reset(new SocketCore()); dataSocket.reset(new SocketCore());
dataSocket->establishConnection(dest.first, dest.second); dataSocket->establishConnection(dest.first, dest.second);
@ -578,15 +585,15 @@ bool FtpNegotiationCommand::resolveProxy()
if(_proxyAddr.empty()) { if(_proxyAddr.empty()) {
return false; return false;
} }
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, util::itos(cuid).c_str(), getLogger()->info(MSG_CONNECTING_TO_SERVER, util::itos(getCuid()).c_str(),
_proxyAddr.c_str(), proxyReq->getPort()); _proxyAddr.c_str(), proxyReq->getPort());
} }
dataSocket.reset(new SocketCore()); dataSocket.reset(new SocketCore());
dataSocket->establishConnection(_proxyAddr, proxyReq->getPort()); dataSocket->establishConnection(_proxyAddr, proxyReq->getPort());
disableReadCheckSocket(); disableReadCheckSocket();
setWriteCheckSocket(dataSocket); setWriteCheckSocket(dataSocket);
_http.reset(new HttpConnection(cuid, dataSocket, getOption().get())); _http.reset(new HttpConnection(getCuid(), dataSocket, getOption().get()));
sequence = SEQ_SEND_TUNNEL_REQUEST; sequence = SEQ_SEND_TUNNEL_REQUEST;
return false; return false;
} }
@ -607,15 +614,16 @@ bool FtpNegotiationCommand::sendTunnelRequest()
(StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED,
error.c_str()).str()); error.c_str()).str());
} else { } else {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECT_FAILED_AND_RETRY, getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY,
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
_proxyAddr.c_str(), proxyReq->getPort()); _proxyAddr.c_str(), proxyReq->getPort());
} }
_proxyAddr = nextProxyAddr; _proxyAddr = nextProxyAddr;
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, util::itos(cuid).c_str(), getLogger()->info(MSG_CONNECTING_TO_SERVER,
_proxyAddr.c_str(), proxyReq->getPort()); util::itos(getCuid()).c_str(),
_proxyAddr.c_str(), proxyReq->getPort());
} }
dataSocket->establishConnection(_proxyAddr, proxyReq->getPort()); dataSocket->establishConnection(_proxyAddr, proxyReq->getPort());
return false; return false;

View File

@ -58,7 +58,7 @@ FtpTunnelRequestCommand::~FtpTunnelRequestCommand() {}
Command* FtpTunnelRequestCommand::getNextCommand() Command* FtpTunnelRequestCommand::getNextCommand()
{ {
return new FtpTunnelResponseCommand return new FtpTunnelResponseCommand
(cuid, req, _fileEntry, _requestGroup, httpConnection, e, socket); (getCuid(), req, _fileEntry, _requestGroup, httpConnection, e, socket);
} }
} // namespace aria2 } // namespace aria2

View File

@ -59,7 +59,7 @@ FtpTunnelResponseCommand::~FtpTunnelResponseCommand() {}
Command* FtpTunnelResponseCommand::getNextCommand() Command* FtpTunnelResponseCommand::getNextCommand()
{ {
return new FtpNegotiationCommand(cuid, req, _fileEntry, return new FtpNegotiationCommand(getCuid(), req, _fileEntry,
_requestGroup, e, socket); _requestGroup, e, socket);
} }

View File

@ -74,7 +74,7 @@ bool HttpDownloadCommand::prepareForNextSegment() {
bool downloadFinished = _requestGroup->downloadFinished(); bool downloadFinished = _requestGroup->downloadFinished();
if(req->isPipeliningEnabled() && !downloadFinished) { if(req->isPipeliningEnabled() && !downloadFinished) {
HttpRequestCommand* command = HttpRequestCommand* command =
new HttpRequestCommand(cuid, req, _fileEntry, new HttpRequestCommand(getCuid(), req, _fileEntry,
_requestGroup, _httpConnection, e, _requestGroup, _httpConnection, e,
socket); socket);
// Set proxy request here. aria2 sends the HTTP request specialized for // Set proxy request here. aria2 sends the HTTP request specialized for

View File

@ -77,24 +77,24 @@ Command* HttpInitiateConnectionCommand::createNextCommand
proxyRequest->getHost(), proxyRequest->getPort()); proxyRequest->getHost(), proxyRequest->getPort());
std::string proxyMethod = resolveProxyMethod(req->getProtocol()); std::string proxyMethod = resolveProxyMethod(req->getProtocol());
if(pooledSocket.isNull()) { if(pooledSocket.isNull()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, getLogger()->info(MSG_CONNECTING_TO_SERVER,
util::itos(cuid).c_str(), addr.c_str(), port); util::itos(getCuid()).c_str(), addr.c_str(), port);
} }
socket.reset(new SocketCore()); socket.reset(new SocketCore());
socket->establishConnection(addr, port); socket->establishConnection(addr, port);
if(proxyMethod == V_TUNNEL) { if(proxyMethod == V_TUNNEL) {
HttpProxyRequestCommand* c = HttpProxyRequestCommand* c =
new HttpProxyRequestCommand(cuid, req, _fileEntry, new HttpProxyRequestCommand(getCuid(), req, _fileEntry,
_requestGroup, e, _requestGroup, e,
proxyRequest, socket); proxyRequest, socket);
c->setConnectedAddr(hostname, addr, port); c->setConnectedAddr(hostname, addr, port);
command = c; command = c;
} else if(proxyMethod == V_GET) { } else if(proxyMethod == V_GET) {
SharedHandle<HttpConnection> httpConnection SharedHandle<HttpConnection> httpConnection
(new HttpConnection(cuid, socket, getOption().get())); (new HttpConnection(getCuid(), socket, getOption().get()));
HttpRequestCommand* c = new HttpRequestCommand(cuid, req, HttpRequestCommand* c = new HttpRequestCommand(getCuid(), req,
_fileEntry, _fileEntry,
_requestGroup, _requestGroup,
httpConnection, e, httpConnection, e,
@ -108,8 +108,8 @@ Command* HttpInitiateConnectionCommand::createNextCommand
} }
} else { } else {
SharedHandle<HttpConnection> httpConnection SharedHandle<HttpConnection> httpConnection
(new HttpConnection(cuid, pooledSocket, getOption().get())); (new HttpConnection(getCuid(), pooledSocket, getOption().get()));
HttpRequestCommand* c = new HttpRequestCommand(cuid, req, HttpRequestCommand* c = new HttpRequestCommand(getCuid(), req,
_fileEntry, _fileEntry,
_requestGroup, _requestGroup,
httpConnection, e, httpConnection, e,
@ -123,18 +123,19 @@ Command* HttpInitiateConnectionCommand::createNextCommand
SharedHandle<SocketCore> pooledSocket = SharedHandle<SocketCore> pooledSocket =
e->popPooledSocket(resolvedAddresses, req->getPort()); e->popPooledSocket(resolvedAddresses, req->getPort());
if(pooledSocket.isNull()) { if(pooledSocket.isNull()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, getLogger()->info(MSG_CONNECTING_TO_SERVER,
util::itos(cuid).c_str(), addr.c_str(), port); util::itos(getCuid()).c_str(), addr.c_str(), port);
} }
socket.reset(new SocketCore()); socket.reset(new SocketCore());
socket->establishConnection(addr, port); socket->establishConnection(addr, port);
} else { } else {
socket = pooledSocket; socket = pooledSocket;
} }
SharedHandle<HttpConnection> httpConnection(new HttpConnection(cuid, socket, getOption().get())); SharedHandle<HttpConnection> httpConnection
(new HttpConnection(getCuid(), socket, getOption().get()));
HttpRequestCommand* c = HttpRequestCommand* c =
new HttpRequestCommand(cuid, req, _fileEntry, _requestGroup, new HttpRequestCommand(getCuid(), req, _fileEntry, _requestGroup,
httpConnection, e, socket); httpConnection, e, socket);
if(pooledSocket.isNull()) { if(pooledSocket.isNull()) {
c->setConnectedAddr(hostname, addr, port); c->setConnectedAddr(hostname, addr, port);

View File

@ -74,8 +74,8 @@ bool HttpListenCommand::execute()
std::pair<std::string, uint16_t> peerInfo; std::pair<std::string, uint16_t> peerInfo;
socket->getPeerInfo(peerInfo); socket->getPeerInfo(peerInfo);
logger->info("XML-RPC: Accepted the connection from %s:%u.", getLogger()->info("XML-RPC: Accepted the connection from %s:%u.",
peerInfo.first.c_str(), peerInfo.second); peerInfo.first.c_str(), peerInfo.second);
HttpServerCommand* c = HttpServerCommand* c =
new HttpServerCommand(_e->newCUID(), _e, socket); new HttpServerCommand(_e->newCUID(), _e, socket);
@ -83,8 +83,8 @@ bool HttpListenCommand::execute()
_e->addCommand(c); _e->addCommand(c);
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug(MSG_ACCEPT_FAILURE, e, util::itos(cuid).c_str()); getLogger()->debug(MSG_ACCEPT_FAILURE, e, util::itos(getCuid()).c_str());
} }
} }
_e->addCommand(this); _e->addCommand(this);
@ -97,9 +97,9 @@ bool HttpListenCommand::bindPort(uint16_t port)
_e->deleteSocketForReadCheck(_serverSocket, this); _e->deleteSocketForReadCheck(_serverSocket, this);
} }
_serverSocket.reset(new SocketCore()); _serverSocket.reset(new SocketCore());
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Setting up HttpListenCommand", getLogger()->info("CUID#%s - Setting up HttpListenCommand",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
try { try {
int flags = 0; int flags = 0;
@ -109,13 +109,15 @@ bool HttpListenCommand::bindPort(uint16_t port)
_serverSocket->bind(port, flags); _serverSocket->bind(port, flags);
_serverSocket->beginListen(); _serverSocket->beginListen();
_serverSocket->setNonBlockingMode(); _serverSocket->setNonBlockingMode();
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_LISTENING_PORT, util::itos(cuid).c_str(), port); getLogger()->info(MSG_LISTENING_PORT,
util::itos(getCuid()).c_str(), port);
} }
_e->addSocketForReadCheck(_serverSocket, this); _e->addSocketForReadCheck(_serverSocket, this);
return true; return true;
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->error(MSG_BIND_FAILURE, e, util::itos(cuid).c_str(), port); getLogger()->error(MSG_BIND_FAILURE, e,
util::itos(getCuid()).c_str(), port);
if(!_serverSocket.isNull()) { if(!_serverSocket.isNull()) {
_e->deleteSocketForReadCheck(_serverSocket, this); _e->deleteSocketForReadCheck(_serverSocket, this);
} }

View File

@ -58,7 +58,7 @@ HttpProxyRequestCommand::~HttpProxyRequestCommand() {}
Command* HttpProxyRequestCommand::getNextCommand() Command* HttpProxyRequestCommand::getNextCommand()
{ {
return new HttpProxyResponseCommand return new HttpProxyResponseCommand
(cuid, req, _fileEntry, _requestGroup, httpConnection, e, socket); (getCuid(), req, _fileEntry, _requestGroup, httpConnection, e, socket);
} }
} // namespace aria2 } // namespace aria2

View File

@ -59,7 +59,7 @@ HttpProxyResponseCommand::~HttpProxyResponseCommand() {}
Command* HttpProxyResponseCommand::getNextCommand() Command* HttpProxyResponseCommand::getNextCommand()
{ {
return new HttpRequestCommand(cuid, req, _fileEntry, return new HttpRequestCommand(getCuid(), req, _fileEntry,
_requestGroup, httpConnection, e, socket); _requestGroup, httpConnection, e, socket);
} }

View File

@ -165,7 +165,7 @@ bool HttpRequestCommand::executeInternal() {
_httpConnection->sendPendingData(); _httpConnection->sendPendingData();
} }
if(_httpConnection->sendBufferIsEmpty()) { if(_httpConnection->sendBufferIsEmpty()) {
Command* command = new HttpResponseCommand(cuid, req, _fileEntry, Command* command = new HttpResponseCommand(getCuid(), req, _fileEntry,
_requestGroup, _requestGroup,
_httpConnection, e, socket); _httpConnection, e, socket);
e->addCommand(command); e->addCommand(command);

View File

@ -115,7 +115,8 @@ bool HttpResponseCommand::executeInternal()
req->supportsPersistentConnection req->supportsPersistentConnection
(httpResponse->supportsPersistentConnection()); (httpResponse->supportsPersistentConnection());
if(req->isPipeliningEnabled()) { if(req->isPipeliningEnabled()) {
req->setMaxPipelinedRequest(getOption()->getAsInt(PREF_MAX_HTTP_PIPELINING)); req->setMaxPipelinedRequest
(getOption()->getAsInt(PREF_MAX_HTTP_PIPELINING));
} }
if(httpResponse->getResponseStatus() >= HttpHeader::S300) { if(httpResponse->getResponseStatus() >= HttpHeader::S300) {
@ -181,8 +182,8 @@ bool HttpResponseCommand::executeInternal()
getTransferEncodingDecoder(httpResponse), getTransferEncodingDecoder(httpResponse),
getContentEncodingDecoder(httpResponse))); getContentEncodingDecoder(httpResponse)));
} else { } else {
e->addCommand(createHttpDownloadCommand(httpResponse, e->addCommand(createHttpDownloadCommand
getTransferEncodingDecoder(httpResponse))); (httpResponse, getTransferEncodingDecoder(httpResponse)));
} }
return true; return true;
} }
@ -226,13 +227,16 @@ bool HttpResponseCommand::handleDefaultEncoding
return true; return true;
} }
BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), getOption().get())); BtProgressInfoFileHandle infoFile
(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(),
_requestGroup->getPieceStorage(),
getOption().get()));
if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) { if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
_requestGroup->getPieceStorage()->markAllPiecesDone(); _requestGroup->getPieceStorage()->markAllPiecesDone();
logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
util::itos(_requestGroup->getGID()).c_str(), util::itos(_requestGroup->getGID()).c_str(),
_requestGroup->getFirstFilePath().c_str()); _requestGroup->getFirstFilePath().c_str());
return true; return true;
} }
@ -242,7 +246,7 @@ bool HttpResponseCommand::handleDefaultEncoding
// have segment after PieceStorage is initialized. See // have segment after PieceStorage is initialized. See
// AbstractCommand::execute() // AbstractCommand::execute()
SharedHandle<Segment> segment = SharedHandle<Segment> segment =
_requestGroup->getSegmentMan()->getSegment(cuid, 0); _requestGroup->getSegmentMan()->getSegment(getCuid(), 0);
// pipelining requires implicit range specified. But the request for // pipelining requires implicit range specified. But the request for
// this response most likely dones't contains range header. This means // this response most likely dones't contains range header. This means
// we can't continue to use this socket because server sends all entity // we can't continue to use this socket because server sends all entity
@ -255,7 +259,7 @@ bool HttpResponseCommand::handleDefaultEncoding
command = createHttpDownloadCommand command = createHttpDownloadCommand
(httpResponse, getTransferEncodingDecoder(httpResponse)); (httpResponse, getTransferEncodingDecoder(httpResponse));
} else { } else {
_requestGroup->getSegmentMan()->cancelSegment(cuid); _requestGroup->getSegmentMan()->cancelSegment(getCuid());
_fileEntry->poolRequest(req); _fileEntry->poolRequest(req);
} }
// After command is passed to prepareForNextAction(), it is managed // After command is passed to prepareForNextAction(), it is managed
@ -326,9 +330,9 @@ bool HttpResponseCommand::handleOtherEncoding
_requestGroup->initPieceStorage(); _requestGroup->initPieceStorage();
_requestGroup->getPieceStorage()->markAllPiecesDone(); _requestGroup->getPieceStorage()->markAllPiecesDone();
logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
util::itos(_requestGroup->getGID()).c_str(), util::itos(_requestGroup->getGID()).c_str(),
_requestGroup->getFirstFilePath().c_str()); _requestGroup->getFirstFilePath().c_str());
poolConnection(); poolConnection();
return true; return true;
@ -348,7 +352,7 @@ bool HttpResponseCommand::handleOtherEncoding
// We have to make sure that command that has Request object must // We have to make sure that command that has Request object must
// have segment after PieceStorage is initialized. See // have segment after PieceStorage is initialized. See
// AbstractCommand::execute() // AbstractCommand::execute()
_requestGroup->getSegmentMan()->getSegment(cuid, 0); _requestGroup->getSegmentMan()->getSegment(getCuid(), 0);
e->addCommand e->addCommand
(createHttpDownloadCommand(httpResponse, (createHttpDownloadCommand(httpResponse,
@ -365,7 +369,8 @@ bool HttpResponseCommand::skipResponseBody
// thrown away. // thrown away.
HttpSkipResponseCommand* command = new HttpSkipResponseCommand HttpSkipResponseCommand* command = new HttpSkipResponseCommand
(cuid, req, _fileEntry, _requestGroup, httpConnection, httpResponse, e, socket); (getCuid(), req, _fileEntry, _requestGroup, httpConnection, httpResponse,
e, socket);
command->setTransferEncodingDecoder(decoder); command->setTransferEncodingDecoder(decoder);
// If request method is HEAD or the response body is zero-length, // If request method is HEAD or the response body is zero-length,
@ -390,7 +395,7 @@ HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand
{ {
HttpDownloadCommand* command = HttpDownloadCommand* command =
new HttpDownloadCommand(cuid, req, _fileEntry, _requestGroup, new HttpDownloadCommand(getCuid(), req, _fileEntry, _requestGroup,
httpResponse, httpConnection, e, socket); httpResponse, httpConnection, e, socket);
command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)); command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
command->setLowestDownloadSpeedLimit command->setLowestDownloadSpeedLimit

View File

@ -99,7 +99,7 @@ bool HttpServerBodyCommand::execute()
std::string responseData = res.toXml(gzip); std::string responseData = res.toXml(gzip);
_httpServer->feedResponse(responseData, "text/xml"); _httpServer->feedResponse(responseData, "text/xml");
Command* command = Command* command =
new HttpServerResponseCommand(cuid, _httpServer, _e, _socket); new HttpServerResponseCommand(getCuid(), _httpServer, _e, _socket);
_e->addCommand(command); _e->addCommand(command);
_e->setNoWait(true); _e->setNoWait(true);
return true; return true;
@ -112,7 +112,7 @@ bool HttpServerBodyCommand::execute()
} }
} else { } else {
if(_timeoutTimer.difference(global::wallclock) >= 30) { if(_timeoutTimer.difference(global::wallclock) >= 30) {
logger->info("HTTP request body timeout."); getLogger()->info("HTTP request body timeout.");
return true; return true;
} else { } else {
_e->addCommand(this); _e->addCommand(this);
@ -120,9 +120,10 @@ bool HttpServerBodyCommand::execute()
} }
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Error occurred while reading HTTP request body", getLogger()->info
e, util::itos(cuid).c_str()); ("CUID#%s - Error occurred while reading HTTP request body",
e, util::itos(getCuid()).c_str());
} }
return true; return true;
} }

View File

@ -111,7 +111,7 @@ bool HttpServerCommand::execute()
"WWW-Authenticate: Basic realm=\"aria2\"", "WWW-Authenticate: Basic realm=\"aria2\"",
"","text/html"); "","text/html");
Command* command = Command* command =
new HttpServerResponseCommand(cuid, _httpServer, _e, _socket); new HttpServerResponseCommand(getCuid(), _httpServer, _e, _socket);
_e->addCommand(command); _e->addCommand(command);
_e->setNoWait(true); _e->setNoWait(true);
return true; return true;
@ -119,20 +119,20 @@ bool HttpServerCommand::execute()
if(static_cast<uint64_t> if(static_cast<uint64_t>
(_e->getOption()->getAsInt(PREF_XML_RPC_MAX_REQUEST_SIZE)) < (_e->getOption()->getAsInt(PREF_XML_RPC_MAX_REQUEST_SIZE)) <
_httpServer->getContentLength()) { _httpServer->getContentLength()) {
logger->info("Request too long. ContentLength=%s." getLogger()->info("Request too long. ContentLength=%s."
" See --xml-rpc-max-request-size option to loose" " See --xml-rpc-max-request-size option to loose"
" this limitation.", " this limitation.",
util::uitos(_httpServer->getContentLength()).c_str()); util::uitos(_httpServer->getContentLength()).c_str());
return true; return true;
} }
Command* command = new HttpServerBodyCommand(cuid, _httpServer, _e, Command* command = new HttpServerBodyCommand(getCuid(), _httpServer, _e,
_socket); _socket);
_e->addCommand(command); _e->addCommand(command);
_e->setNoWait(true); _e->setNoWait(true);
return true; return true;
} else { } else {
if(_timeoutTimer.difference(global::wallclock) >= 30) { if(_timeoutTimer.difference(global::wallclock) >= 30) {
logger->info("HTTP request timeout."); getLogger()->info("HTTP request timeout.");
return true; return true;
} else { } else {
_e->addCommand(this); _e->addCommand(this);
@ -140,9 +140,9 @@ bool HttpServerCommand::execute()
} }
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Error occurred while reading HTTP request", getLogger()->info("CUID#%s - Error occurred while reading HTTP request",
e, util::itos(cuid).c_str()); e, util::itos(getCuid()).c_str());
} }
return true; return true;
} }

View File

@ -76,29 +76,32 @@ bool HttpServerResponseCommand::execute()
try { try {
_httpServer->sendResponse(); _httpServer->sendResponse();
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Error occurred while transmitting response body.", getLogger()->info
e, util::itos(cuid).c_str()); ("CUID#%s - Error occurred while transmitting response body.",
e, util::itos(getCuid()).c_str());
} }
return true; return true;
} }
if(_httpServer->sendBufferIsEmpty()) { if(_httpServer->sendBufferIsEmpty()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - HttpServer: all response transmitted.", getLogger()->info("CUID#%s - HttpServer: all response transmitted.",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
if(_httpServer->supportsPersistentConnection()) { if(_httpServer->supportsPersistentConnection()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Persist connection.", util::itos(cuid).c_str()); getLogger()->info("CUID#%s - Persist connection.",
util::itos(getCuid()).c_str());
} }
_e->addCommand(new HttpServerCommand(cuid, _httpServer, _e, _socket)); _e->addCommand
(new HttpServerCommand(getCuid(), _httpServer, _e, _socket));
} }
return true; return true;
} else { } else {
if(_timeoutTimer.difference(global::wallclock) >= 10) { if(_timeoutTimer.difference(global::wallclock) >= 10) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - HttpServer: Timeout while trasmitting" getLogger()->info("CUID#%s - HttpServer: Timeout while trasmitting"
" response.", util::itos(cuid).c_str()); " response.", util::itos(getCuid()).c_str());
} }
return true; return true;
} else { } else {

View File

@ -118,8 +118,8 @@ bool HttpSkipResponseCommand::executeInternal()
throw DL_RETRY_EX(EX_GOT_EOF); throw DL_RETRY_EX(EX_GOT_EOF);
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug(EX_EXCEPTION_CAUGHT, e); getLogger()->debug(EX_EXCEPTION_CAUGHT, e);
} }
return processResponse(); return processResponse();
} }

View File

@ -101,14 +101,14 @@ bool InitiateConnectionCommand::executeInternal() {
// TODO ipaddr might not be used if pooled sockt was found. // TODO ipaddr might not be used if pooled sockt was found.
e->markBadIPAddress(hostname, ipaddr, port); e->markBadIPAddress(hostname, ipaddr, port);
if(!e->findCachedIPAddress(hostname, port).empty()) { if(!e->findCachedIPAddress(hostname, port).empty()) {
if(logger->info()) { if(getLogger()->info()) {
logger->info(EX_EXCEPTION_CAUGHT, ex); getLogger()->info(EX_EXCEPTION_CAUGHT, ex);
logger->info(MSG_CONNECT_FAILED_AND_RETRY, getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY,
util::itos(cuid).c_str(), ipaddr.c_str(), port); util::itos(getCuid()).c_str(), ipaddr.c_str(), port);
} }
Command* command = Command* command =
InitiateConnectionCommandFactory::createInitiateConnectionCommand InitiateConnectionCommandFactory::createInitiateConnectionCommand
(cuid, req, _fileEntry, _requestGroup, e); (getCuid(), req, _fileEntry, _requestGroup, e);
e->setNoWait(true); e->setNoWait(true);
e->addCommand(command); e->addCommand(command);
return true; return true;

View File

@ -150,14 +150,15 @@ bool InitiatorMSEHandshakeCommand::executeInternal() {
case INITIATOR_RECEIVE_PAD_D: { case INITIATOR_RECEIVE_PAD_D: {
if(_mseHandshake->receivePad()) { if(_mseHandshake->receivePad()) {
SharedHandle<PeerConnection> peerConnection SharedHandle<PeerConnection> peerConnection
(new PeerConnection(cuid, socket)); (new PeerConnection(getCuid(), socket));
if(_mseHandshake->getNegotiatedCryptoType() == MSEHandshake::CRYPTO_ARC4) { if(_mseHandshake->getNegotiatedCryptoType() == MSEHandshake::CRYPTO_ARC4){
peerConnection->enableEncryption(_mseHandshake->getEncryptor(), peerConnection->enableEncryption(_mseHandshake->getEncryptor(),
_mseHandshake->getDecryptor()); _mseHandshake->getDecryptor());
} }
PeerInteractionCommand* c = PeerInteractionCommand* c =
new PeerInteractionCommand new PeerInteractionCommand
(cuid, _requestGroup, peer, e, _btRuntime, _pieceStorage, _peerStorage, (getCuid(), _requestGroup, peer, e, _btRuntime, _pieceStorage,
_peerStorage,
socket, socket,
PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE, PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE,
peerConnection); peerConnection);
@ -174,10 +175,11 @@ bool InitiatorMSEHandshakeCommand::executeInternal() {
bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait) bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait)
{ {
if(getOption()->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { if(getOption()->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Establishing connection using legacy BitTorrent" getLogger()->info
" handshake is disabled by preference.", ("CUID#%s - Establishing connection using legacy BitTorrent"
util::itos(cuid).c_str()); " handshake is disabled by preference.",
util::itos(getCuid()).c_str());
} }
if(_peerStorage->isPeerAvailable() && _btRuntime->lessThanEqMinPeers()) { if(_peerStorage->isPeerAvailable() && _btRuntime->lessThanEqMinPeers()) {
SharedHandle<Peer> peer = _peerStorage->getUnusedPeer(); SharedHandle<Peer> peer = _peerStorage->getUnusedPeer();
@ -192,12 +194,12 @@ bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait)
return true; return true;
} else { } else {
// try legacy BitTorrent handshake // try legacy BitTorrent handshake
if(logger->info()) { if(getLogger()->info()) {
logger->info("CUID#%s - Retry using legacy BitTorrent handshake.", getLogger()->info("CUID#%s - Retry using legacy BitTorrent handshake.",
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
} }
PeerInitiateConnectionCommand* command = PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(cuid, _requestGroup, peer, e, new PeerInitiateConnectionCommand(getCuid(), _requestGroup, peer, e,
_btRuntime, false); _btRuntime, false);
command->setPeerStorage(_peerStorage); command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage); command->setPieceStorage(_pieceStorage);

View File

@ -64,24 +64,24 @@ bool LpdDispatchMessageCommand::execute()
} }
if(_dispatcher->isAnnounceReady()) { if(_dispatcher->isAnnounceReady()) {
try { try {
logger->info("Dispatching LPD message for infohash=%s", getLogger()->info("Dispatching LPD message for infohash=%s",
util::toHex(_dispatcher->getInfoHash()).c_str()); util::toHex(_dispatcher->getInfoHash()).c_str());
if(_dispatcher->sendMessage()) { if(_dispatcher->sendMessage()) {
logger->info("Sending LPD message is complete."); getLogger()->info("Sending LPD message is complete.");
_dispatcher->resetAnnounceTimer(); _dispatcher->resetAnnounceTimer();
_tryCount = 0; _tryCount = 0;
} else { } else {
++_tryCount; ++_tryCount;
if(_tryCount >= 5) { if(_tryCount >= 5) {
logger->info("Sending LPD message %u times but all failed."); getLogger()->info("Sending LPD message %u times but all failed.");
_dispatcher->resetAnnounceTimer(); _dispatcher->resetAnnounceTimer();
_tryCount = 0; _tryCount = 0;
} else { } else {
logger->info("Could not send LPD message, retry shortly."); getLogger()->info("Could not send LPD message, retry shortly.");
} }
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->info("Failed to send LPD message.", e); getLogger()->info("Failed to send LPD message.", e);
_dispatcher->resetAnnounceTimer(); _dispatcher->resetAnnounceTimer();
_tryCount = 0; _tryCount = 0;
} }

View File

@ -94,17 +94,18 @@ bool LpdReceiveMessageCommand::execute()
SharedHandle<DownloadContext> dctx = SharedHandle<DownloadContext> dctx =
reg->getDownloadContext(m->getInfoHash()); reg->getDownloadContext(m->getInfoHash());
if(dctx.isNull()) { if(dctx.isNull()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("Download Context is null for infohash=%s.", getLogger()->debug("Download Context is null for infohash=%s.",
util::toHex(m->getInfoHash()).c_str()); util::toHex(m->getInfoHash()).c_str());
} }
continue; continue;
} }
const BDE& torrentAttrs = dctx->getAttribute(bittorrent::BITTORRENT); const BDE& torrentAttrs = dctx->getAttribute(bittorrent::BITTORRENT);
if(torrentAttrs.containsKey(bittorrent::PRIVATE)) { if(torrentAttrs.containsKey(bittorrent::PRIVATE)) {
if(torrentAttrs[bittorrent::PRIVATE].i() == 1) { if(torrentAttrs[bittorrent::PRIVATE].i() == 1) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("Ignore LPD message because the torrent is private."); getLogger()->debug
("Ignore LPD message because the torrent is private.");
} }
continue; continue;
} }
@ -117,16 +118,16 @@ bool LpdReceiveMessageCommand::execute()
assert(!peerStorage.isNull()); assert(!peerStorage.isNull());
SharedHandle<Peer> peer = m->getPeer(); SharedHandle<Peer> peer = m->getPeer();
if(peerStorage->addPeer(peer)) { if(peerStorage->addPeer(peer)) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("LPD peer %s:%u local=%d added.", getLogger()->debug("LPD peer %s:%u local=%d added.",
peer->ipaddr.c_str(), peer->port, peer->ipaddr.c_str(), peer->port,
peer->isLocalPeer()?1:0); peer->isLocalPeer()?1:0);
} }
} else { } else {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("LPD peer %s:%u local=%d not added.", getLogger()->debug("LPD peer %s:%u local=%d not added.",
peer->ipaddr.c_str(), peer->port, peer->ipaddr.c_str(), peer->port,
peer->isLocalPeer()?1:0); peer->isLocalPeer()?1:0);
} }
} }
} }

View File

@ -81,12 +81,13 @@ PeerAbstractCommand::~PeerAbstractCommand()
bool PeerAbstractCommand::execute() bool PeerAbstractCommand::execute()
{ {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s -" getLogger()->debug("CUID#%s -"
" socket: read:%d, write:%d, hup:%d, err:%d, noCheck:%d", " socket: read:%d, write:%d, hup:%d, err:%d, noCheck:%d",
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
_readEvent, _writeEvent, _hupEvent, _errorEvent, readEventEnabled(), writeEventEnabled(),
noCheck); hupEventEnabled(), errorEventEnabled(),
noCheck);
} }
if(exitBeforeExecute()) { if(exitBeforeExecute()) {
onAbort(); onAbort();
@ -94,11 +95,11 @@ bool PeerAbstractCommand::execute()
} }
try { try {
if(noCheck || if(noCheck ||
(checkSocketIsReadable && _readEvent) || (checkSocketIsReadable && readEventEnabled()) ||
(checkSocketIsWritable && _writeEvent) || (checkSocketIsWritable && writeEventEnabled()) ||
_hupEvent) { hupEventEnabled()) {
checkPoint = global::wallclock; checkPoint = global::wallclock;
} else if(_errorEvent) { } else if(errorEventEnabled()) {
throw DL_ABORT_EX throw DL_ABORT_EX
(StringFormat(MSG_NETWORK_PROBLEM, (StringFormat(MSG_NETWORK_PROBLEM,
socket->getSocketError().c_str()).str()); socket->getSocketError().c_str()).str());
@ -108,16 +109,17 @@ bool PeerAbstractCommand::execute()
} }
return executeInternal(); return executeInternal();
} catch(DownloadFailureException& err) { } catch(DownloadFailureException& err) {
logger->error(EX_DOWNLOAD_ABORTED, err); getLogger()->error(EX_DOWNLOAD_ABORTED, err);
onAbort(); onAbort();
onFailure(); onFailure();
return true; return true;
} catch(RecoverableException& err) { } catch(RecoverableException& err) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug(MSG_TORRENT_DOWNLOAD_ABORTED, err, getLogger()->debug(MSG_TORRENT_DOWNLOAD_ABORTED, err,
util::itos(cuid).c_str()); util::itos(getCuid()).c_str());
logger->debug(MSG_PEER_BANNED, getLogger()->debug(MSG_PEER_BANNED,
util::itos(cuid).c_str(), peer->ipaddr.c_str(), peer->port); util::itos(getCuid()).c_str(), peer->ipaddr.c_str(),
peer->port);
} }
onAbort(); onAbort();
return prepareForNextPeer(0); return prepareForNextPeer(0);

View File

@ -80,16 +80,16 @@ PeerInitiateConnectionCommand::~PeerInitiateConnectionCommand()
} }
bool PeerInitiateConnectionCommand::executeInternal() { bool PeerInitiateConnectionCommand::executeInternal() {
if(logger->info()) { if(getLogger()->info()) {
logger->info(MSG_CONNECTING_TO_SERVER, getLogger()->info(MSG_CONNECTING_TO_SERVER,
util::itos(cuid).c_str(), peer->ipaddr.c_str(), util::itos(getCuid()).c_str(), peer->ipaddr.c_str(),
peer->port); peer->port);
} }
socket.reset(new SocketCore()); socket.reset(new SocketCore());
socket->establishConnection(peer->ipaddr, peer->port); socket->establishConnection(peer->ipaddr, peer->port);
if(_mseHandshakeEnabled) { if(_mseHandshakeEnabled) {
InitiatorMSEHandshakeCommand* c = InitiatorMSEHandshakeCommand* c =
new InitiatorMSEHandshakeCommand(cuid, _requestGroup, peer, e, new InitiatorMSEHandshakeCommand(getCuid(), _requestGroup, peer, e,
_btRuntime, socket); _btRuntime, socket);
c->setPeerStorage(_peerStorage); c->setPeerStorage(_peerStorage);
c->setPieceStorage(_pieceStorage); c->setPieceStorage(_pieceStorage);
@ -97,7 +97,8 @@ bool PeerInitiateConnectionCommand::executeInternal() {
} else { } else {
PeerInteractionCommand* command = PeerInteractionCommand* command =
new PeerInteractionCommand new PeerInteractionCommand
(cuid, _requestGroup, peer, e, _btRuntime, _pieceStorage, _peerStorage, (getCuid(), _requestGroup, peer, e, _btRuntime, _pieceStorage,
_peerStorage,
socket, PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE); socket, PeerInteractionCommand::INITIATOR_SEND_HANDSHAKE);
e->addCommand(command); e->addCommand(command);
} }

View File

@ -89,10 +89,11 @@ bool PeerListenCommand::bindPort(uint16_t& port, IntSequence& seq)
socket->bind(port); socket->bind(port);
socket->beginListen(); socket->beginListen();
socket->setNonBlockingMode(); socket->setNonBlockingMode();
logger->notice("BitTorrent: listening to port %d", port); getLogger()->notice("BitTorrent: listening to port %d", port);
return true; return true;
} catch(RecoverableException& ex) { } catch(RecoverableException& ex) {
logger->error(MSG_BIND_FAILURE, ex, util::itos(cuid).c_str(), port); getLogger()->error(MSG_BIND_FAILURE, ex,
util::itos(getCuid()).c_str(), port);
socket->closeConnection(); socket->closeConnection();
} }
} }
@ -128,15 +129,15 @@ bool PeerListenCommand::execute() {
Command* command = Command* command =
new ReceiverMSEHandshakeCommand(cuid, peer, e, peerSocket); new ReceiverMSEHandshakeCommand(cuid, peer, e, peerSocket);
e->addCommand(command); e->addCommand(command);
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("Accepted the connection from %s:%u.", getLogger()->debug("Accepted the connection from %s:%u.",
peer->ipaddr.c_str(), peer->ipaddr.c_str(),
peer->port); peer->port);
logger->debug("Added CUID#%s to receive BitTorrent/MSE handshake.", getLogger()->debug("Added CUID#%s to receive BitTorrent/MSE handshake.",
util::itos(cuid).c_str()); util::itos(cuid).c_str());
} }
} catch(RecoverableException& ex) { } catch(RecoverableException& ex) {
logger->debug(MSG_ACCEPT_FAILURE, ex, util::itos(cuid).c_str()); getLogger()->debug(MSG_ACCEPT_FAILURE, ex, util::itos(getCuid()).c_str());
} }
} }
e->addCommand(this); e->addCommand(this);

View File

@ -130,11 +130,11 @@ bool PeerReceiveHandshakeCommand::executeInternal()
btRuntime->lessThanMaxPeers()) { btRuntime->lessThanMaxPeers()) {
if(peerStorage->addPeer(peer)) { if(peerStorage->addPeer(peer)) {
peer->usedBy(cuid); peer->usedBy(getCuid());
PeerInteractionCommand* command = PeerInteractionCommand* command =
new PeerInteractionCommand new PeerInteractionCommand
(cuid, (getCuid(),
downloadContext->getOwnerRequestGroup(), downloadContext->getOwnerRequestGroup(),
peer, peer,
e, e,
@ -145,10 +145,10 @@ bool PeerReceiveHandshakeCommand::executeInternal()
PeerInteractionCommand::RECEIVER_WAIT_HANDSHAKE, PeerInteractionCommand::RECEIVER_WAIT_HANDSHAKE,
_peerConnection); _peerConnection);
e->addCommand(command); e->addCommand(command);
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug(MSG_INCOMING_PEER_CONNECTION, getLogger()->debug(MSG_INCOMING_PEER_CONNECTION,
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
util::itos(peer->usedBy()).c_str()); util::itos(peer->usedBy()).c_str());
} }
} }
} }

View File

@ -98,13 +98,15 @@ bool ReceiverMSEHandshakeCommand::executeInternal()
break; break;
case MSEHandshake::HANDSHAKE_LEGACY: { case MSEHandshake::HANDSHAKE_LEGACY: {
if(e->getOption()->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { if(e->getOption()->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
throw DL_ABORT_EX("The legacy BitTorrent handshake is not acceptable by the preference."); throw DL_ABORT_EX
("The legacy BitTorrent handshake is not acceptable by the"
" preference.");
} }
SharedHandle<PeerConnection> peerConnection SharedHandle<PeerConnection> peerConnection
(new PeerConnection(cuid, socket)); (new PeerConnection(getCuid(), socket));
peerConnection->presetBuffer(_mseHandshake->getBuffer(), peerConnection->presetBuffer(_mseHandshake->getBuffer(),
_mseHandshake->getBufferLength()); _mseHandshake->getBufferLength());
Command* c = new PeerReceiveHandshakeCommand(cuid, peer, e, socket, Command* c = new PeerReceiveHandshakeCommand(getCuid(), peer, e, socket,
peerConnection); peerConnection);
e->addCommand(c); e->addCommand(c);
return true; return true;
@ -185,7 +187,7 @@ bool ReceiverMSEHandshakeCommand::executeInternal()
void ReceiverMSEHandshakeCommand::createCommand() void ReceiverMSEHandshakeCommand::createCommand()
{ {
SharedHandle<PeerConnection> peerConnection SharedHandle<PeerConnection> peerConnection
(new PeerConnection(cuid, socket)); (new PeerConnection(getCuid(), socket));
if(_mseHandshake->getNegotiatedCryptoType() == MSEHandshake::CRYPTO_ARC4) { if(_mseHandshake->getNegotiatedCryptoType() == MSEHandshake::CRYPTO_ARC4) {
peerConnection->enableEncryption(_mseHandshake->getEncryptor(), peerConnection->enableEncryption(_mseHandshake->getEncryptor(),
_mseHandshake->getDecryptor()); _mseHandshake->getDecryptor());
@ -198,7 +200,7 @@ void ReceiverMSEHandshakeCommand::createCommand()
// as a hint. If this info hash and one in BitTorrent Handshake does not // as a hint. If this info hash and one in BitTorrent Handshake does not
// match, then drop connection. // match, then drop connection.
Command* c = Command* c =
new PeerReceiveHandshakeCommand(cuid, peer, e, socket, peerConnection); new PeerReceiveHandshakeCommand(getCuid(), peer, e, socket, peerConnection);
e->addCommand(c); e->addCommand(c);
} }

View File

@ -83,7 +83,7 @@ bool SeedCheckCommand::execute() {
} }
if(checkStarted) { if(checkStarted) {
if(seedCriteria->evaluate()) { if(seedCriteria->evaluate()) {
logger->notice(MSG_SEEDING_END); getLogger()->notice(MSG_SEEDING_END);
_btRuntime->setHalt(true); _btRuntime->setHalt(true);
} }
} }

View File

@ -62,9 +62,9 @@ void TimedHaltCommand::preProcess()
void TimedHaltCommand::process() void TimedHaltCommand::process()
{ {
if(!_e->isHaltRequested()) { if(!_e->isHaltRequested()) {
logger->notice(MSG_TIME_HAS_PASSED, _interval); getLogger()->notice(MSG_TIME_HAS_PASSED, _interval);
if(_forceHalt) { if(_forceHalt) {
logger->notice("This is emergency shutdown."); getLogger()->notice("This is emergency shutdown.");
_e->requestForceHalt(); _e->requestForceHalt();
} else { } else {
_e->requestHalt(); _e->requestHalt();

View File

@ -96,8 +96,8 @@ bool TrackerWatcherCommand::execute() {
} }
} }
if(_btAnnounce->noMoreAnnounce()) { if(_btAnnounce->noMoreAnnounce()) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("no more announce"); getLogger()->debug("no more announce");
} }
return true; return true;
} }
@ -108,13 +108,13 @@ bool TrackerWatcherCommand::execute() {
try { try {
_trackerRequestGroup->createInitialCommand(commands, e); _trackerRequestGroup->createInitialCommand(commands, e);
} catch(RecoverableException& ex) { } catch(RecoverableException& ex) {
logger->error(EX_EXCEPTION_CAUGHT, ex); getLogger()->error(EX_EXCEPTION_CAUGHT, ex);
std::for_each(commands.begin(), commands.end(), Deleter()); std::for_each(commands.begin(), commands.end(), Deleter());
commands.clear(); commands.clear();
} }
e->addCommand(commands); e->addCommand(commands);
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("added tracker request command"); getLogger()->debug("added tracker request command");
} }
} }
} else if(_trackerRequestGroup->downloadFinished()){ } else if(_trackerRequestGroup->downloadFinished()){
@ -125,7 +125,7 @@ bool TrackerWatcherCommand::execute() {
_btAnnounce->announceSuccess(); _btAnnounce->announceSuccess();
_btAnnounce->resetAnnounce(); _btAnnounce->resetAnnounce();
} catch(RecoverableException& ex) { } catch(RecoverableException& ex) {
logger->error(EX_EXCEPTION_CAUGHT, ex); getLogger()->error(EX_EXCEPTION_CAUGHT, ex);
_btAnnounce->announceFailure(); _btAnnounce->announceFailure();
if(_btAnnounce->isAllAnnounceFailed()) { if(_btAnnounce->isAllAnnounceFailed()) {
_btAnnounce->resetAnnounce(); _btAnnounce->resetAnnounce();
@ -180,10 +180,10 @@ void TrackerWatcherCommand::processTrackerResponse
command->setPeerStorage(_peerStorage); command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage); command->setPieceStorage(_pieceStorage);
e->addCommand(command); e->addCommand(command);
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("CUID#%s - Adding new command CUID#%s", getLogger()->debug("CUID#%s - Adding new command CUID#%s",
util::itos(cuid).c_str(), util::itos(getCuid()).c_str(),
util::itos(peer->usedBy()).c_str()); util::itos(peer->usedBy()).c_str());
} }
} }
} }
@ -222,12 +222,12 @@ TrackerWatcherCommand::createRequestGroup(const std::string& uri)
uris.push_back(uri); uris.push_back(uri);
SharedHandle<RequestGroup> rg(new RequestGroup(getOption())); SharedHandle<RequestGroup> rg(new RequestGroup(getOption()));
if(backupTrackerIsAvailable(_requestGroup->getDownloadContext())) { if(backupTrackerIsAvailable(_requestGroup->getDownloadContext())) {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("This is multi-tracker announce."); getLogger()->debug("This is multi-tracker announce.");
} }
} else { } else {
if(logger->debug()) { if(getLogger()->debug()) {
logger->debug("This is single-tracker announce."); getLogger()->debug("This is single-tracker announce.");
} }
} }
// If backup tracker is available, try 2 times for each tracker // If backup tracker is available, try 2 times for each tracker
@ -253,9 +253,9 @@ TrackerWatcherCommand::createRequestGroup(const std::string& uri)
rg->setFileAllocationEnabled(false); rg->setFileAllocationEnabled(false);
rg->setPreLocalFileCheckEnabled(false); rg->setPreLocalFileCheckEnabled(false);
util::removeMetalinkContentTypes(rg); util::removeMetalinkContentTypes(rg);
if(logger->info()) { if(getLogger()->info()) {
logger->info("Creating tracker request group GID#%s", getLogger()->info("Creating tracker request group GID#%s",
util::itos(rg->getGID()).c_str()); util::itos(rg->getGID()).c_str());
} }
return rg; return rg;
} }