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

Changed naming standards for class member variable: now it looks
	like var_ instead of _var.
This commit is contained in:
Tatsuhiro Tsujikawa 2010-06-21 13:51:56 +00:00
parent ae957baa98
commit ca4940622c
550 changed files with 10253 additions and 10248 deletions

View File

@ -1,3 +1,8 @@
2010-06-21 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
Changed naming standards for class member variable: now it looks
like var_ instead of _var.
2010-06-20 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
When wrong type DHT reply message is received for a transaction

View File

@ -43,12 +43,12 @@ AbstractAuthResolver::~AbstractAuthResolver() {}
void AbstractAuthResolver::setUserDefinedAuthConfig(const AuthConfigHandle& authConfig)
{
_userDefinedAuthConfig = authConfig;
userDefinedAuthConfig_ = authConfig;
}
void AbstractAuthResolver::setDefaultAuthConfig(const AuthConfigHandle& authConfig)
{
_defaultAuthConfig = authConfig;
defaultAuthConfig_ = authConfig;
}
} // namespace aria2

View File

@ -41,9 +41,9 @@ namespace aria2 {
class AbstractAuthResolver : public AuthResolver {
private:
SharedHandle<AuthConfig> _userDefinedAuthConfig;
SharedHandle<AuthConfig> userDefinedAuthConfig_;
SharedHandle<AuthConfig> _defaultAuthConfig;
SharedHandle<AuthConfig> defaultAuthConfig_;
public:
AbstractAuthResolver();
@ -53,14 +53,14 @@ public:
const SharedHandle<AuthConfig>& getUserDefinedAuthConfig() const
{
return _userDefinedAuthConfig;
return userDefinedAuthConfig_;
}
void setDefaultAuthConfig(const SharedHandle<AuthConfig>& authConfig);
const SharedHandle<AuthConfig>& getDefaultAuthConfig() const
{
return _defaultAuthConfig;
return defaultAuthConfig_;
}
};

View File

@ -43,59 +43,59 @@ namespace aria2 {
AbstractBtMessage::AbstractBtMessage(uint8_t id, const std::string& name):
BtMessage(id),
_sendingInProgress(false),
_invalidate(false),
_uploading(false),
_cuid(0),
_name(name),
_metadataGetMode(false),
_logger(LogFactory::getInstance())
sendingInProgress_(false),
invalidate_(false),
uploading_(false),
cuid_(0),
name_(name),
metadataGetMode_(false),
logger_(LogFactory::getInstance())
{}
AbstractBtMessage::~AbstractBtMessage() {}
void AbstractBtMessage::setPeer(const SharedHandle<Peer>& peer)
{
_peer = peer;
peer_ = peer;
}
void AbstractBtMessage::validate()
{
if(!_validator.isNull()) {
_validator->validate();
if(!validator_.isNull()) {
validator_->validate();
}
}
void
AbstractBtMessage::setBtMessageValidator(const SharedHandle<BtMessageValidator>& validator) {
_validator = validator;
validator_ = validator;
}
void AbstractBtMessage::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
pieceStorage_ = pieceStorage;
}
void AbstractBtMessage::setBtMessageDispatcher
(const WeakHandle<BtMessageDispatcher>& dispatcher)
{
_dispatcher = dispatcher;
dispatcher_ = dispatcher;
}
void AbstractBtMessage::setPeerConnection(const WeakHandle<PeerConnection>& peerConnection)
{
_peerConnection = peerConnection;
peerConnection_ = peerConnection;
}
void AbstractBtMessage::setBtMessageFactory(const WeakHandle<BtMessageFactory>& factory)
{
_messageFactory = factory;
messageFactory_ = factory;
}
void AbstractBtMessage::setBtRequestFactory(const WeakHandle<BtRequestFactory>& factory)
{
_requestFactory = factory;
requestFactory_ = factory;
}
} // namespace aria2

View File

@ -51,64 +51,64 @@ class Logger;
class AbstractBtMessage : public BtMessage {
private:
bool _sendingInProgress;
bool _invalidate;
bool _uploading;
cuid_t _cuid;
bool sendingInProgress_;
bool invalidate_;
bool uploading_;
cuid_t cuid_;
std::string _name;
std::string name_;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PieceStorage> pieceStorage_;
SharedHandle<Peer> _peer;
SharedHandle<Peer> peer_;
WeakHandle<BtMessageDispatcher> _dispatcher;
WeakHandle<BtMessageDispatcher> dispatcher_;
WeakHandle<BtMessageFactory> _messageFactory;
WeakHandle<BtMessageFactory> messageFactory_;
WeakHandle<BtRequestFactory> _requestFactory;
WeakHandle<BtRequestFactory> requestFactory_;
WeakHandle<PeerConnection> _peerConnection;
WeakHandle<PeerConnection> peerConnection_;
SharedHandle<BtMessageValidator> _validator;
SharedHandle<BtMessageValidator> validator_;
bool _metadataGetMode;
bool metadataGetMode_;
Logger* _logger;
Logger* logger_;
protected:
Logger* getLogger() const
{
return _logger;
return logger_;
}
const SharedHandle<PieceStorage>& getPieceStorage() const
{
return _pieceStorage;
return pieceStorage_;
}
const WeakHandle<PeerConnection>& getPeerConnection() const
{
return _peerConnection;
return peerConnection_;
}
const WeakHandle<BtMessageDispatcher>& getBtMessageDispatcher() const
{
return _dispatcher;
return dispatcher_;
}
const WeakHandle<BtRequestFactory>& getBtRequestFactory() const
{
return _requestFactory;
return requestFactory_;
}
const WeakHandle<BtMessageFactory>& getBtMessageFactory() const
{
return _messageFactory;
return messageFactory_;
}
bool isMetadataGetMode() const
{
return _metadataGetMode;
return metadataGetMode_;
}
public:
AbstractBtMessage(uint8_t id, const std::string& name);
@ -116,40 +116,40 @@ public:
virtual ~AbstractBtMessage();
virtual bool isSendingInProgress() {
return _sendingInProgress;
return sendingInProgress_;
}
void setSendingInProgress(bool sendingInProgress) {
_sendingInProgress = sendingInProgress;
sendingInProgress_ = sendingInProgress;
}
virtual bool isInvalidate() {
return _invalidate;
return invalidate_;
}
void setInvalidate(bool invalidate) {
_invalidate = invalidate;
invalidate_ = invalidate;
}
virtual bool isUploading() {
return _uploading;
return uploading_;
}
void setUploading(bool uploading) {
_uploading = uploading;
uploading_ = uploading;
}
cuid_t getCuid() const {
return _cuid;
return cuid_;
}
void setCuid(cuid_t cuid) {
_cuid = cuid;
cuid_ = cuid;
}
const SharedHandle<Peer>& getPeer() const
{
return _peer;
return peer_;
}
void setPeer(const SharedHandle<Peer>& peer);
@ -183,12 +183,12 @@ public:
const std::string& getName() const
{
return _name;
return name_;
}
void enableMetadataGetMode()
{
_metadataGetMode = true;
metadataGetMode_ = true;
}
};

View File

@ -77,28 +77,28 @@ AbstractCommand::AbstractCommand(cuid_t cuid,
RequestGroup* requestGroup,
DownloadEngine* e,
const SocketHandle& s):
Command(cuid), _checkPoint(global::wallclock),
_timeout(requestGroup->getTimeout()),
_requestGroup(requestGroup),
_req(req), _fileEntry(fileEntry), _e(e), _socket(s),
_checkSocketIsReadable(false), _checkSocketIsWritable(false),
_nameResolverCheck(false)
Command(cuid), checkPoint_(global::wallclock),
timeout_(requestGroup->getTimeout()),
requestGroup_(requestGroup),
req_(req), fileEntry_(fileEntry), e_(e), socket_(s),
checkSocketIsReadable_(false), checkSocketIsWritable_(false),
nameResolverCheck_(false)
{
if(!_socket.isNull() && _socket->isOpen()) {
setReadCheckSocket(_socket);
if(!socket_.isNull() && socket_->isOpen()) {
setReadCheckSocket(socket_);
}
_requestGroup->increaseStreamConnection();
_requestGroup->increaseNumCommand();
requestGroup_->increaseStreamConnection();
requestGroup_->increaseNumCommand();
}
AbstractCommand::~AbstractCommand() {
disableReadCheckSocket();
disableWriteCheckSocket();
#ifdef ENABLE_ASYNC_DNS
disableNameResolverCheck(_asyncNameResolver);
disableNameResolverCheck(asyncNameResolver_);
#endif // ENABLE_ASYNC_DNS
_requestGroup->decreaseNumCommand();
_requestGroup->decreaseStreamConnection();
requestGroup_->decreaseNumCommand();
requestGroup_->decreaseStreamConnection();
}
bool AbstractCommand::execute() {
@ -111,22 +111,22 @@ bool AbstractCommand::execute() {
errorEventEnabled());
}
try {
if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
if(requestGroup_->downloadFinished() || requestGroup_->isHaltRequested()) {
return true;
}
if(!_req.isNull() && _req->removalRequested()) {
if(!req_.isNull() && req_->removalRequested()) {
if(getLogger()->debug()) {
getLogger()->debug
("CUID#%s - Discard original URI=%s because it is requested.",
util::itos(getCuid()).c_str(), _req->getUri().c_str());
util::itos(getCuid()).c_str(), req_->getUri().c_str());
}
return prepareForRetry(0);
}
// TODO it is not needed to check other PeerStats every time.
// Find faster Request when no segment is available.
if(!_req.isNull() && _fileEntry->countPooledRequest() > 0 &&
if(!req_.isNull() && fileEntry_->countPooledRequest() > 0 &&
!getPieceStorage()->hasMissingUnusedPiece()) {
SharedHandle<Request> fasterRequest = _fileEntry->findFasterRequest(_req);
SharedHandle<Request> fasterRequest = fileEntry_->findFasterRequest(req_);
if(!fasterRequest.isNull()) {
if(getLogger()->info()) {
getLogger()->info("CUID#%s - Use faster Request hostname=%s, port=%u",
@ -135,28 +135,28 @@ bool AbstractCommand::execute() {
fasterRequest->getPort());
}
// Cancel current Request object and use faster one.
_fileEntry->removeRequest(_req);
fileEntry_->removeRequest(req_);
Command* command =
InitiateConnectionCommandFactory::createInitiateConnectionCommand
(getCuid(), fasterRequest, _fileEntry, _requestGroup, _e);
_e->setNoWait(true);
_e->addCommand(command);
(getCuid(), fasterRequest, fileEntry_, requestGroup_, e_);
e_->setNoWait(true);
e_->addCommand(command);
return true;
}
}
if((_checkSocketIsReadable && readEventEnabled()) ||
(_checkSocketIsWritable && writeEventEnabled()) ||
if((checkSocketIsReadable_ && readEventEnabled()) ||
(checkSocketIsWritable_ && writeEventEnabled()) ||
hupEventEnabled() ||
#ifdef ENABLE_ASYNC_DNS
(_nameResolverCheck && nameResolveFinished()) ||
(nameResolverCheck_ && nameResolveFinished()) ||
#endif // ENABLE_ASYNC_DNS
(!_checkSocketIsReadable && !_checkSocketIsWritable &&
!_nameResolverCheck)) {
_checkPoint = global::wallclock;
(!checkSocketIsReadable_ && !checkSocketIsWritable_ &&
!nameResolverCheck_)) {
checkPoint_ = global::wallclock;
if(!getPieceStorage().isNull()) {
_segments.clear();
getSegmentMan()->getInFlightSegment(_segments, getCuid());
if(!_req.isNull() && _segments.empty()) {
segments_.clear();
getSegmentMan()->getInFlightSegment(segments_, getCuid());
if(!req_.isNull() && segments_.empty()) {
// This command previously has assigned segments, but it is
// canceled. So discard current request chain.
if(getLogger()->debug()) {
@ -166,16 +166,16 @@ bool AbstractCommand::execute() {
}
return prepareForRetry(0);
}
if(_req.isNull() || _req->getMaxPipelinedRequest() == 1 ||
if(req_.isNull() || req_->getMaxPipelinedRequest() == 1 ||
getDownloadContext()->getFileEntries().size() == 1) {
if(_segments.empty()) {
if(segments_.empty()) {
SharedHandle<Segment> segment =
getSegmentMan()->getSegment(getCuid());
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...
if(getLogger()->info()) {
getLogger()->info(MSG_NO_SEGMENT_AVAILABLE,
@ -193,12 +193,12 @@ bool AbstractCommand::execute() {
}
}
} else {
size_t maxSegments = _req->getMaxPipelinedRequest();
if(_segments.size() < maxSegments) {
size_t maxSegments = req_->getMaxPipelinedRequest();
if(segments_.size() < maxSegments) {
getSegmentMan()->getSegment
(_segments, getCuid(), _fileEntry, maxSegments);
(segments_, getCuid(), fileEntry_, maxSegments);
}
if(_segments.empty()) {
if(segments_.empty()) {
return prepareForRetry(0);
}
}
@ -207,23 +207,23 @@ bool AbstractCommand::execute() {
} else if(errorEventEnabled()) {
throw DL_RETRY_EX
(StringFormat(MSG_NETWORK_PROBLEM,
_socket->getSocketError().c_str()).str());
socket_->getSocketError().c_str()).str());
} else {
if(_checkPoint.difference(global::wallclock) >= _timeout) {
if(checkPoint_.difference(global::wallclock) >= timeout_) {
// timeout triggers ServerStat error state.
SharedHandle<ServerStat> ss =
_e->getRequestGroupMan()->getOrCreateServerStat(_req->getHost(),
_req->getProtocol());
e_->getRequestGroupMan()->getOrCreateServerStat(req_->getHost(),
req_->getProtocol());
ss->setError();
throw DL_RETRY_EX2(EX_TIME_OUT, downloadresultcode::TIME_OUT);
}
_e->addCommand(this);
e_->addCommand(this);
return false;
}
} catch(DlAbortEx& err) {
if(_req.isNull()) {
if(req_.isNull()) {
if(getLogger()->debug()) {
getLogger()->debug(EX_EXCEPTION_CAUGHT, err);
}
@ -231,43 +231,43 @@ bool AbstractCommand::execute() {
getLogger()->error
(MSG_DOWNLOAD_ABORTED,
DL_ABORT_EX2(StringFormat
("URI=%s", _req->getCurrentUri().c_str()).str(),err),
util::itos(getCuid()).c_str(), _req->getUri().c_str());
_fileEntry->addURIResult(_req->getUri(), err.getCode());
_requestGroup->setLastUriResult(_req->getUri(), err.getCode());
("URI=%s", req_->getCurrentUri().c_str()).str(),err),
util::itos(getCuid()).c_str(), req_->getUri().c_str());
fileEntry_->addURIResult(req_->getUri(), err.getCode());
requestGroup_->setLastUriResult(req_->getUri(), err.getCode());
if(err.getCode() == downloadresultcode::CANNOT_RESUME) {
_requestGroup->increaseResumeFailureCount();
requestGroup_->increaseResumeFailureCount();
}
}
onAbort();
tryReserved();
return true;
} catch(DlRetryEx& err) {
assert(!_req.isNull());
assert(!req_.isNull());
if(getLogger()->info()) {
getLogger()->info
(MSG_RESTARTING_DOWNLOAD,
DL_RETRY_EX2(StringFormat
("URI=%s", _req->getCurrentUri().c_str()).str(),
("URI=%s", req_->getCurrentUri().c_str()).str(),
err),
util::itos(getCuid()).c_str(), _req->getUri().c_str());
util::itos(getCuid()).c_str(), req_->getUri().c_str());
}
_req->addTryCount();
_req->resetRedirectCount();
req_->addTryCount();
req_->resetRedirectCount();
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(getLogger()->info()) {
getLogger()->info(MSG_MAX_TRY,
util::itos(getCuid()).c_str(), _req->getTryCount());
util::itos(getCuid()).c_str(), req_->getTryCount());
}
getLogger()->error(MSG_DOWNLOAD_ABORTED, err,
util::itos(getCuid()).c_str(),
_req->getUri().c_str());
_fileEntry->addURIResult(_req->getUri(), err.getCode());
_requestGroup->setLastUriResult(_req->getUri(), err.getCode());
req_->getUri().c_str());
fileEntry_->addURIResult(req_->getUri(), err.getCode());
requestGroup_->setLastUriResult(req_->getUri(), err.getCode());
if(err.getCode() == downloadresultcode::CANNOT_RESUME) {
_requestGroup->increaseResumeFailureCount();
requestGroup_->increaseResumeFailureCount();
}
onAbort();
tryReserved();
@ -277,11 +277,11 @@ bool AbstractCommand::execute() {
}
} catch(DownloadFailureException& err) {
getLogger()->error(EX_EXCEPTION_CAUGHT, err);
if(!_req.isNull()) {
_fileEntry->addURIResult(_req->getUri(), err.getCode());
_requestGroup->setLastUriResult(_req->getUri(), err.getCode());
if(!req_.isNull()) {
fileEntry_->addURIResult(req_->getUri(), err.getCode());
requestGroup_->setLastUriResult(req_->getUri(), err.getCode());
}
_requestGroup->setHaltRequested(true);
requestGroup_->setHaltRequested(true);
return true;
}
}
@ -308,45 +308,45 @@ void AbstractCommand::tryReserved() {
util::itos(getCuid()).c_str());
}
std::vector<Command*> commands;
_requestGroup->createNextCommand(commands, _e, 1);
_e->setNoWait(true);
_e->addCommand(commands);
requestGroup_->createNextCommand(commands, e_, 1);
e_->setNoWait(true);
e_->addCommand(commands);
}
bool AbstractCommand::prepareForRetry(time_t wait) {
if(!getPieceStorage().isNull()) {
getSegmentMan()->cancelSegment(getCuid());
}
if(!_req.isNull()) {
_fileEntry->poolRequest(_req);
if(!req_.isNull()) {
fileEntry_->poolRequest(req_);
if(getLogger()->debug()) {
getLogger()->debug("CUID#%s - Pooling request URI=%s",
util::itos(getCuid()).c_str(), _req->getUri().c_str());
util::itos(getCuid()).c_str(), req_->getUri().c_str());
}
if(!getSegmentMan().isNull()) {
getSegmentMan()->recognizeSegmentFor(_fileEntry);
getSegmentMan()->recognizeSegmentFor(fileEntry_);
}
}
Command* command = new CreateRequestCommand(getCuid(), _requestGroup, _e);
Command* command = new CreateRequestCommand(getCuid(), requestGroup_, e_);
if(wait == 0) {
_e->setNoWait(true);
_e->addCommand(command);
e_->setNoWait(true);
e_->addCommand(command);
} else {
SleepCommand* scom = new SleepCommand(getCuid(), _e, _requestGroup,
SleepCommand* scom = new SleepCommand(getCuid(), e_, requestGroup_,
command, wait);
_e->addCommand(scom);
e_->addCommand(scom);
}
return true;
}
void AbstractCommand::onAbort() {
if(!_req.isNull()) {
if(!req_.isNull()) {
// TODO This might be a problem if the failure is caused by proxy.
_e->getRequestGroupMan()->getOrCreateServerStat
(_req->getHost(), _req->getProtocol())->setError();
_fileEntry->removeIdenticalURI(_req->getUri());
_fileEntry->removeRequest(_req);
e_->getRequestGroupMan()->getOrCreateServerStat
(req_->getHost(), req_->getProtocol())->setError();
fileEntry_->removeIdenticalURI(req_->getUri());
fileEntry_->removeRequest(req_);
}
if(getLogger()->debug()) {
getLogger()->debug("CUID#%s - Aborting download",
@ -358,13 +358,13 @@ void AbstractCommand::onAbort() {
// in DownloadContext is more than 1. The latter condition is
// limitation of current implementation.
if(!getOption()->getAsBool(PREF_ALWAYS_RESUME) &&
!_fileEntry.isNull() &&
!fileEntry_.isNull() &&
getSegmentMan()->calculateSessionDownloadLength() == 0 &&
!_requestGroup->p2pInvolved() &&
!requestGroup_->p2pInvolved() &&
getDownloadContext()->getFileEntries().size() == 1) {
const int maxTries = getOption()->getAsInt(PREF_MAX_RESUME_FAILURE_TRIES);
if((maxTries > 0 && _requestGroup->getResumeFailureCount() >= maxTries)||
_fileEntry->emptyRequestUri()) {
if((maxTries > 0 && requestGroup_->getResumeFailureCount() >= maxTries)||
fileEntry_->emptyRequestUri()) {
// Local file exists, but given servers(or at least contacted
// ones) doesn't support resume. Let's restart download from
// scratch.
@ -380,7 +380,7 @@ void AbstractCommand::onAbort() {
// process.
getOption()->put(PREF_ALWAYS_RESUME, V_TRUE);
std::deque<URIResult> res;
_fileEntry->extractURIResult(res, downloadresultcode::CANNOT_RESUME);
fileEntry_->extractURIResult(res, downloadresultcode::CANNOT_RESUME);
if(!res.empty()) {
getSegmentMan()->cancelAllSegments();
getSegmentMan()->eraseSegmentWrittenLengthMemo();
@ -394,8 +394,8 @@ void AbstractCommand::onAbort() {
util::itos(getCuid()).c_str(),
static_cast<unsigned long int>(uris.size()));
}
_fileEntry->addUris(uris.begin(), uris.end());
getSegmentMan()->recognizeSegmentFor(_fileEntry);
fileEntry_->addUris(uris.begin(), uris.end());
getSegmentMan()->recognizeSegmentFor(fileEntry_);
}
}
}
@ -403,10 +403,10 @@ void AbstractCommand::onAbort() {
}
void AbstractCommand::disableReadCheckSocket() {
if(_checkSocketIsReadable) {
_e->deleteSocketForReadCheck(_readCheckTarget, this);
_checkSocketIsReadable = false;
_readCheckTarget.reset();
if(checkSocketIsReadable_) {
e_->deleteSocketForReadCheck(readCheckTarget_, this);
checkSocketIsReadable_ = false;
readCheckTarget_.reset();
}
}
@ -414,16 +414,16 @@ void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
if(!socket->isOpen()) {
disableReadCheckSocket();
} else {
if(_checkSocketIsReadable) {
if(_readCheckTarget != socket) {
_e->deleteSocketForReadCheck(_readCheckTarget, this);
_e->addSocketForReadCheck(socket, this);
_readCheckTarget = socket;
if(checkSocketIsReadable_) {
if(readCheckTarget_ != socket) {
e_->deleteSocketForReadCheck(readCheckTarget_, this);
e_->addSocketForReadCheck(socket, this);
readCheckTarget_ = socket;
}
} else {
_e->addSocketForReadCheck(socket, this);
_checkSocketIsReadable = true;
_readCheckTarget = socket;
e_->addSocketForReadCheck(socket, this);
checkSocketIsReadable_ = true;
readCheckTarget_ = socket;
}
}
}
@ -439,10 +439,10 @@ void AbstractCommand::setReadCheckSocketIf
}
void AbstractCommand::disableWriteCheckSocket() {
if(_checkSocketIsWritable) {
_e->deleteSocketForWriteCheck(_writeCheckTarget, this);
_checkSocketIsWritable = false;
_writeCheckTarget.reset();
if(checkSocketIsWritable_) {
e_->deleteSocketForWriteCheck(writeCheckTarget_, this);
checkSocketIsWritable_ = false;
writeCheckTarget_.reset();
}
}
@ -450,16 +450,16 @@ void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
if(!socket->isOpen()) {
disableWriteCheckSocket();
} else {
if(_checkSocketIsWritable) {
if(_writeCheckTarget != socket) {
_e->deleteSocketForWriteCheck(_writeCheckTarget, this);
_e->addSocketForWriteCheck(socket, this);
_writeCheckTarget = socket;
if(checkSocketIsWritable_) {
if(writeCheckTarget_ != socket) {
e_->deleteSocketForWriteCheck(writeCheckTarget_, this);
e_->addSocketForWriteCheck(socket, this);
writeCheckTarget_ = socket;
}
} else {
_e->addSocketForWriteCheck(socket, this);
_checkSocketIsWritable = true;
_writeCheckTarget = socket;
e_->addSocketForWriteCheck(socket, this);
checkSocketIsWritable_ = true;
writeCheckTarget_ = socket;
}
}
}
@ -512,16 +512,16 @@ static bool isProxyRequest
class DomainMatch {
private:
std::string _hostname;
std::string hostname_;
public:
DomainMatch(const std::string& hostname):_hostname(hostname) {}
DomainMatch(const std::string& hostname):hostname_(hostname) {}
bool operator()(const std::string& domain) const
{
if(util::startsWith(domain, A2STR::DOT_C)) {
return util::endsWith(_hostname, domain);
return util::endsWith(hostname_, domain);
} else {
return util::endsWith(_hostname, A2STR::DOT_C+domain);
return util::endsWith(hostname_, A2STR::DOT_C+domain);
}
}
};
@ -569,17 +569,17 @@ static bool inNoProxy(const SharedHandle<Request>& req,
bool AbstractCommand::isProxyDefined() const
{
return isProxyRequest(_req->getProtocol(), getOption()) &&
!inNoProxy(_req, getOption()->get(PREF_NO_PROXY));
return isProxyRequest(req_->getProtocol(), getOption()) &&
!inNoProxy(req_, getOption()->get(PREF_NO_PROXY));
}
SharedHandle<Request> AbstractCommand::createProxyRequest() const
{
SharedHandle<Request> proxyRequest;
if(inNoProxy(_req, getOption()->get(PREF_NO_PROXY))) {
if(inNoProxy(req_, getOption()->get(PREF_NO_PROXY))) {
return proxyRequest;
}
std::string proxy = getProxyUri(_req->getProtocol(), getOption());
std::string proxy = getProxyUri(req_->getProtocol(), getOption());
if(!proxy.empty()) {
proxyRequest.reset(new Request());
if(proxyRequest->setUri(proxy)) {
@ -602,37 +602,37 @@ SharedHandle<Request> AbstractCommand::createProxyRequest() const
bool AbstractCommand::isAsyncNameResolverInitialized() const
{
return !_asyncNameResolver.isNull();
return !asyncNameResolver_.isNull();
}
void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
{
_asyncNameResolver.reset(new AsyncNameResolver());
asyncNameResolver_.reset(new AsyncNameResolver());
if(getLogger()->info()) {
getLogger()->info(MSG_RESOLVING_HOSTNAME,
util::itos(getCuid()).c_str(), hostname.c_str());
}
_asyncNameResolver->resolve(hostname);
setNameResolverCheck(_asyncNameResolver);
asyncNameResolver_->resolve(hostname);
setNameResolverCheck(asyncNameResolver_);
}
bool AbstractCommand::asyncResolveHostname()
{
switch(_asyncNameResolver->getStatus()) {
switch(asyncNameResolver_->getStatus()) {
case AsyncNameResolver::STATUS_SUCCESS:
disableNameResolverCheck(_asyncNameResolver);
disableNameResolverCheck(asyncNameResolver_);
return true;
case AsyncNameResolver::STATUS_ERROR:
disableNameResolverCheck(_asyncNameResolver);
if(!isProxyRequest(_req->getProtocol(), getOption())) {
_e->getRequestGroupMan()->getOrCreateServerStat
(_req->getHost(), _req->getProtocol())->setError();
disableNameResolverCheck(asyncNameResolver_);
if(!isProxyRequest(req_->getProtocol(), getOption())) {
e_->getRequestGroupMan()->getOrCreateServerStat
(req_->getHost(), req_->getProtocol())->setError();
}
throw DL_ABORT_EX
(StringFormat(MSG_NAME_RESOLUTION_FAILED,
util::itos(getCuid()).c_str(),
_asyncNameResolver->getHostname().c_str(),
_asyncNameResolver->getError().c_str()).str());
asyncNameResolver_->getHostname().c_str(),
asyncNameResolver_->getError().c_str()).str());
default:
return false;
}
@ -640,36 +640,36 @@ bool AbstractCommand::asyncResolveHostname()
const std::vector<std::string>& AbstractCommand::getResolvedAddresses()
{
return _asyncNameResolver->getResolvedAddresses();
return asyncNameResolver_->getResolvedAddresses();
}
void AbstractCommand::setNameResolverCheck
(const SharedHandle<AsyncNameResolver>& resolver) {
if(!resolver.isNull()) {
_nameResolverCheck = true;
_e->addNameResolverCheck(resolver, this);
nameResolverCheck_ = true;
e_->addNameResolverCheck(resolver, this);
}
}
void AbstractCommand::disableNameResolverCheck
(const SharedHandle<AsyncNameResolver>& resolver) {
if(!resolver.isNull()) {
_nameResolverCheck = false;
_e->deleteNameResolverCheck(resolver, this);
nameResolverCheck_ = false;
e_->deleteNameResolverCheck(resolver, this);
}
}
bool AbstractCommand::nameResolveFinished() const {
return
_asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
_asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_ERROR;
asyncNameResolver_->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
asyncNameResolver_->getStatus() == AsyncNameResolver::STATUS_ERROR;
}
#endif // ENABLE_ASYNC_DNS
std::string AbstractCommand::resolveHostname
(std::vector<std::string>& addrs, const std::string& hostname, uint16_t port)
{
_e->findAllCachedIPAddresses(std::back_inserter(addrs), hostname, port);
e_->findAllCachedIPAddresses(std::back_inserter(addrs), hostname, port);
std::string ipaddr;
if(addrs.empty()) {
#ifdef ENABLE_ASYNC_DNS
@ -687,7 +687,7 @@ std::string AbstractCommand::resolveHostname
{
NameResolver res;
res.setSocktype(SOCK_STREAM);
if(_e->getOption()->getAsBool(PREF_DISABLE_IPV6)) {
if(e_->getOption()->getAsBool(PREF_DISABLE_IPV6)) {
res.setFamily(AF_INET);
}
res.resolve(addrs, hostname);
@ -700,9 +700,9 @@ std::string AbstractCommand::resolveHostname
}
for(std::vector<std::string>::const_iterator i = addrs.begin(),
eoi = addrs.end(); i != eoi; ++i) {
_e->cacheIPAddress(hostname, *i, port);
e_->cacheIPAddress(hostname, *i, port);
}
ipaddr = _e->findCachedIPAddress(hostname, port);
ipaddr = e_->findCachedIPAddress(hostname, port);
} else {
ipaddr = addrs.front();
if(getLogger()->info()) {
@ -720,14 +720,14 @@ std::string AbstractCommand::resolveHostname
void AbstractCommand::prepareForNextAction(Command* nextCommand)
{
SharedHandle<CheckIntegrityEntry> entry
(new StreamCheckIntegrityEntry(_requestGroup, nextCommand));
(new StreamCheckIntegrityEntry(requestGroup_, nextCommand));
std::vector<Command*>* commands = new std::vector<Command*>();
auto_delete_container<std::vector<Command*> > commandsDel(commands);
_requestGroup->processCheckIntegrityEntry(*commands, entry, _e);
_e->addCommand(*commands);
requestGroup_->processCheckIntegrityEntry(*commands, entry, e_);
e_->addCommand(*commands);
commands->clear();
_e->setNoWait(true);
e_->setNoWait(true);
}
bool AbstractCommand::checkIfConnectionEstablished
@ -740,8 +740,8 @@ bool AbstractCommand::checkIfConnectionEstablished
std::string error = socket->getSocketError();
if(!error.empty()) {
// See also InitiateConnectionCommand::executeInternal()
_e->markBadIPAddress(connectedHostname, connectedAddr, connectedPort);
if(!_e->findCachedIPAddress(connectedHostname, connectedPort).empty()) {
e_->markBadIPAddress(connectedHostname, connectedAddr, connectedPort);
if(!e_->findCachedIPAddress(connectedHostname, connectedPort).empty()) {
if(getLogger()->info()) {
getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY,
util::itos(getCuid()).c_str(),
@ -749,17 +749,17 @@ bool AbstractCommand::checkIfConnectionEstablished
}
Command* command =
InitiateConnectionCommandFactory::createInitiateConnectionCommand
(getCuid(), _req, _fileEntry, _requestGroup, _e);
_e->setNoWait(true);
_e->addCommand(command);
(getCuid(), req_, fileEntry_, requestGroup_, e_);
e_->setNoWait(true);
e_->addCommand(command);
return false;
}
_e->removeCachedIPAddress(connectedHostname, connectedPort);
e_->removeCachedIPAddress(connectedHostname, connectedPort);
// Don't set error if proxy server is used and its method is GET.
if(resolveProxyMethod(_req->getProtocol()) != V_GET ||
!isProxyRequest(_req->getProtocol(), getOption())) {
_e->getRequestGroupMan()->getOrCreateServerStat
(_req->getHost(), _req->getProtocol())->setError();
if(resolveProxyMethod(req_->getProtocol()) != V_GET ||
!isProxyRequest(req_->getProtocol(), getOption())) {
e_->getRequestGroupMan()->getOrCreateServerStat
(req_->getHost(), req_->getProtocol())->setError();
}
throw DL_RETRY_EX
(StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
@ -781,12 +781,12 @@ const std::string& AbstractCommand::resolveProxyMethod
const SharedHandle<Option>& AbstractCommand::getOption() const
{
return _requestGroup->getOption();
return requestGroup_->getOption();
}
void AbstractCommand::createSocket()
{
_socket.reset(new SocketCore());
socket_.reset(new SocketCore());
}
} // namespace aria2

View File

@ -55,25 +55,25 @@ class AsyncNameResolver;
class AbstractCommand : public Command {
private:
Timer _checkPoint;
time_t _timeout;
Timer checkPoint_;
time_t timeout_;
RequestGroup* _requestGroup;
SharedHandle<Request> _req;
SharedHandle<FileEntry> _fileEntry;
DownloadEngine* _e;
SharedHandle<SocketCore> _socket;
std::vector<SharedHandle<Segment> > _segments;
RequestGroup* requestGroup_;
SharedHandle<Request> req_;
SharedHandle<FileEntry> fileEntry_;
DownloadEngine* e_;
SharedHandle<SocketCore> socket_;
std::vector<SharedHandle<Segment> > segments_;
#ifdef ENABLE_ASYNC_DNS
SharedHandle<AsyncNameResolver> _asyncNameResolver;
SharedHandle<AsyncNameResolver> asyncNameResolver_;
#endif // ENABLE_ASYNC_DNS
bool _checkSocketIsReadable;
bool _checkSocketIsWritable;
SharedHandle<SocketCore> _readCheckTarget;
SharedHandle<SocketCore> _writeCheckTarget;
bool _nameResolverCheck;
bool checkSocketIsReadable_;
bool checkSocketIsWritable_;
SharedHandle<SocketCore> readCheckTarget_;
SharedHandle<SocketCore> writeCheckTarget_;
bool nameResolverCheck_;
#ifdef ENABLE_ASYNC_DNS
void setNameResolverCheck(const SharedHandle<AsyncNameResolver>& resolver);
@ -86,49 +86,49 @@ private:
protected:
RequestGroup* getRequestGroup() const
{
return _requestGroup;
return requestGroup_;
}
const SharedHandle<Request>& getRequest() const
{
return _req;
return req_;
}
void setRequest(const SharedHandle<Request>& request)
{
_req = request;
req_ = request;
}
const SharedHandle<FileEntry>& getFileEntry() const
{
return _fileEntry;
return fileEntry_;
}
void setFileEntry(const SharedHandle<FileEntry>& fileEntry)
{
_fileEntry = fileEntry;
fileEntry_ = fileEntry;
}
DownloadEngine* getDownloadEngine() const
{
return _e;
return e_;
}
const SharedHandle<SocketCore>& getSocket() const
{
return _socket;
return socket_;
}
void setSocket(const SharedHandle<SocketCore>& s)
{
_socket = s;
socket_ = s;
}
void createSocket();
const std::vector<SharedHandle<Segment> >& getSegments() const
{
return _segments;
return segments_;
}
#ifdef ENABLE_ASYNC_DNS
@ -170,7 +170,7 @@ protected:
*/
void setWriteCheckSocketIf(const SharedHandle<SocketCore>& socket, bool pred);
void setTimeout(time_t timeout) { _timeout = timeout; }
void setTimeout(time_t timeout) { timeout_ = timeout; }
void prepareForNextAction(Command* nextCommand = 0);
@ -205,17 +205,17 @@ protected:
const SharedHandle<DownloadContext>& getDownloadContext() const
{
return _requestGroup->getDownloadContext();
return requestGroup_->getDownloadContext();
}
const SharedHandle<SegmentMan>& getSegmentMan() const
{
return _requestGroup->getSegmentMan();
return requestGroup_->getSegmentMan();
}
const SharedHandle<PieceStorage>& getPieceStorage() const
{
return _requestGroup->getPieceStorage();
return requestGroup_->getPieceStorage();
}
public:
AbstractCommand(cuid_t cuid, const SharedHandle<Request>& req,

View File

@ -57,11 +57,11 @@
namespace aria2 {
AbstractDiskWriter::AbstractDiskWriter(const std::string& filename):
_filename(filename),
_fd(-1),
_readOnly(false),
_directIOAllowed(false),
_logger(LogFactory::getInstance()) {}
filename_(filename),
fd_(-1),
readOnly_(false),
directIOAllowed_(false),
logger_(LogFactory::getInstance()) {}
AbstractDiskWriter::~AbstractDiskWriter()
{
@ -70,7 +70,7 @@ AbstractDiskWriter::~AbstractDiskWriter()
void AbstractDiskWriter::openFile(uint64_t totalLength)
{
if(File(_filename).exists()) {
if(File(filename_).exists()) {
openExistingFile(totalLength);
} else {
initAndOpenFile(totalLength);
@ -79,40 +79,40 @@ void AbstractDiskWriter::openFile(uint64_t totalLength)
void AbstractDiskWriter::closeFile()
{
if(_fd >= 0) {
close(_fd);
_fd = -1;
if(fd_ >= 0) {
close(fd_);
fd_ = -1;
}
}
void AbstractDiskWriter::openExistingFile(uint64_t totalLength)
{
if(!File(_filename).exists()) {
if(!File(filename_).exists()) {
throw DL_ABORT_EX
(StringFormat(EX_FILE_OPEN, _filename.c_str(), MSG_FILE_NOT_FOUND).str());
(StringFormat(EX_FILE_OPEN, filename_.c_str(), MSG_FILE_NOT_FOUND).str());
}
int flags = O_BINARY;
if(_readOnly) {
if(readOnly_) {
flags |= O_RDONLY;
} else {
flags |= O_RDWR;
}
if((_fd = open(_filename.c_str(), flags, OPEN_MODE)) < 0) {
if((fd_ = open(filename_.c_str(), flags, OPEN_MODE)) < 0) {
throw DL_ABORT_EX
(StringFormat(EX_FILE_OPEN, _filename.c_str(), strerror(errno)).str());
(StringFormat(EX_FILE_OPEN, filename_.c_str(), strerror(errno)).str());
}
}
void AbstractDiskWriter::createFile(int addFlags)
{
assert(!_filename.empty());
util::mkdirs(File(_filename).getDirname());
if((_fd = open(_filename.c_str(), O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags,
assert(!filename_.empty());
util::mkdirs(File(filename_).getDirname());
if((fd_ = open(filename_.c_str(), O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags,
OPEN_MODE)) < 0) {
throw DL_ABORT_EX(StringFormat(EX_FILE_OPEN,
_filename.c_str(), strerror(errno)).str());
filename_.c_str(), strerror(errno)).str());
}
}
@ -121,7 +121,7 @@ ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data, size_t
ssize_t writtenLength = 0;
while((size_t)writtenLength < len) {
ssize_t ret = 0;
while((ret = write(_fd, data+writtenLength, len-writtenLength)) == -1 && errno == EINTR);
while((ret = write(fd_, data+writtenLength, len-writtenLength)) == -1 && errno == EINTR);
if(ret == -1) {
return -1;
}
@ -133,15 +133,15 @@ ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data, size_t
ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len)
{
ssize_t ret = 0;
while((ret = read(_fd, data, len)) == -1 && errno == EINTR);
while((ret = read(fd_, data, len)) == -1 && errno == EINTR);
return ret;
}
void AbstractDiskWriter::seek(off_t offset)
{
if(a2lseek(_fd, offset, SEEK_SET) == (off_t)-1) {
if(a2lseek(fd_, offset, SEEK_SET) == (off_t)-1) {
throw DL_ABORT_EX
(StringFormat(EX_FILE_SEEK, _filename.c_str(), strerror(errno)).str());
(StringFormat(EX_FILE_SEEK, filename_.c_str(), strerror(errno)).str());
}
}
@ -153,10 +153,10 @@ void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, off_t
// DownloadFailureException and abort download instantly.
if(errno == ENOSPC) {
throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat(EX_FILE_WRITE, _filename.c_str(), strerror(errno)).str());
(StringFormat(EX_FILE_WRITE, filename_.c_str(), strerror(errno)).str());
}
throw DL_ABORT_EX(StringFormat(EX_FILE_WRITE,
_filename.c_str(), strerror(errno)).str());
filename_.c_str(), strerror(errno)).str());
}
}
@ -166,27 +166,27 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs
seek(offset);
if((ret = readDataInternal(data, len)) < 0) {
throw DL_ABORT_EX(StringFormat(EX_FILE_READ,
_filename.c_str(), strerror(errno)).str());
filename_.c_str(), strerror(errno)).str());
}
return ret;
}
void AbstractDiskWriter::truncate(uint64_t length)
{
if(_fd == -1) {
if(fd_ == -1) {
throw DL_ABORT_EX("File not opened.");
}
#ifdef __MINGW32__
// Since mingw32's ftruncate cannot handle over 2GB files, we use SetEndOfFile
// instead.
HANDLE handle = LongToHandle(_get_osfhandle(_fd));
HANDLE handle = LongToHandle(_get_osfhandle(fd_));
seek(length);
if(SetEndOfFile(handle) == 0) {
throw DL_ABORT_EX(StringFormat("SetEndOfFile failed. cause: %s",
GetLastError()).str());
}
#else
if(ftruncate(_fd, length) == -1) {
if(ftruncate(fd_, length) == -1) {
throw DL_ABORT_EX(StringFormat("ftruncate failed. cause: %s",
strerror(errno)).str());
}
@ -196,10 +196,10 @@ void AbstractDiskWriter::truncate(uint64_t length)
#ifdef HAVE_POSIX_FALLOCATE
void AbstractDiskWriter::allocate(off_t offset, uint64_t length)
{
if(_fd == -1) {
if(fd_ == -1) {
throw DL_ABORT_EX("File not yet opened.");
}
int r = posix_fallocate(_fd, offset, length);
int r = posix_fallocate(fd_, offset, length);
if(r != 0) {
throw DL_ABORT_EX(StringFormat("posix_fallocate failed. cause: %s",
strerror(r)).str());
@ -209,16 +209,16 @@ void AbstractDiskWriter::allocate(off_t offset, uint64_t length)
uint64_t AbstractDiskWriter::size()
{
return File(_filename).size();
return File(filename_).size();
}
void AbstractDiskWriter::enableDirectIO()
{
#ifdef ENABLE_DIRECT_IO
if(_directIOAllowed) {
if(directIOAllowed_) {
int flg;
while((flg = fcntl(_fd, F_GETFL)) == -1 && errno == EINTR);
while(fcntl(_fd, F_SETFL, flg|O_DIRECT) == -1 && errno == EINTR);
while((flg = fcntl(fd_, F_GETFL)) == -1 && errno == EINTR);
while(fcntl(fd_, F_SETFL, flg|O_DIRECT) == -1 && errno == EINTR);
}
#endif // ENABLE_DIRECT_IO
}
@ -227,19 +227,19 @@ void AbstractDiskWriter::disableDirectIO()
{
#ifdef ENABLE_DIRECT_IO
int flg;
while((flg = fcntl(_fd, F_GETFL)) == -1 && errno == EINTR);
while(fcntl(_fd, F_SETFL, flg&(~O_DIRECT)) == -1 && errno == EINTR);
while((flg = fcntl(fd_, F_GETFL)) == -1 && errno == EINTR);
while(fcntl(fd_, F_SETFL, flg&(~O_DIRECT)) == -1 && errno == EINTR);
#endif // ENABLE_DIRECT_IO
}
void AbstractDiskWriter::enableReadOnly()
{
_readOnly = true;
readOnly_ = true;
}
void AbstractDiskWriter::disableReadOnly()
{
_readOnly = false;
readOnly_ = false;
}
} // namespace aria2

View File

@ -44,14 +44,14 @@ class Logger;
class AbstractDiskWriter : public DiskWriter {
private:
std::string _filename;
int _fd;
std::string filename_;
int fd_;
bool _readOnly;
bool readOnly_;
bool _directIOAllowed;
bool directIOAllowed_;
Logger* _logger;
Logger* logger_;
ssize_t writeDataInternal(const unsigned char* data, size_t len);
ssize_t readDataInternal(unsigned char* data, size_t len);
@ -86,7 +86,7 @@ public:
virtual void disableDirectIO();
virtual void allowDirectIO() { _directIOAllowed = true; }
virtual void allowDirectIO() { directIOAllowed_ = true; }
virtual void enableReadOnly();

View File

@ -63,8 +63,8 @@ AbstractProxyRequestCommand::AbstractProxyRequestCommand
const SocketHandle& s)
:
AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
_proxyRequest(proxyRequest),
_httpConnection(new HttpConnection(cuid, s))
proxyRequest_(proxyRequest),
httpConnection_(new HttpConnection(cuid, s))
{
setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
disableReadCheckSocket();
@ -75,21 +75,21 @@ AbstractProxyRequestCommand::~AbstractProxyRequestCommand() {}
bool AbstractProxyRequestCommand::executeInternal() {
//socket->setBlockingMode();
if(_httpConnection->sendBufferIsEmpty()) {
if(httpConnection_->sendBufferIsEmpty()) {
if(!checkIfConnectionEstablished
(getSocket(), _connectedHostname, _connectedAddr, _connectedPort)) {
(getSocket(), connectedHostname_, connectedAddr_, connectedPort_)) {
return true;
}
SharedHandle<HttpRequest> httpRequest(new HttpRequest());
httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
httpRequest->setRequest(getRequest());
httpRequest->setProxyRequest(_proxyRequest);
httpRequest->setProxyRequest(proxyRequest_);
_httpConnection->sendProxyRequest(httpRequest);
httpConnection_->sendProxyRequest(httpRequest);
} else {
_httpConnection->sendPendingData();
httpConnection_->sendPendingData();
}
if(_httpConnection->sendBufferIsEmpty()) {
if(httpConnection_->sendBufferIsEmpty()) {
getDownloadEngine()->addCommand(getNextCommand());
return true;
} else {

View File

@ -44,19 +44,19 @@ class SocketCore;
class AbstractProxyRequestCommand : public AbstractCommand {
private:
SharedHandle<Request> _proxyRequest;
SharedHandle<Request> proxyRequest_;
SharedHandle<HttpConnection> _httpConnection;
SharedHandle<HttpConnection> httpConnection_;
std::string _connectedHostname;
std::string _connectedAddr;
uint16_t _connectedPort;
std::string connectedHostname_;
std::string connectedAddr_;
uint16_t connectedPort_;
protected:
virtual bool executeInternal();
const SharedHandle<HttpConnection>& getHttpConnection() const
{
return _httpConnection;
return httpConnection_;
}
public:
AbstractProxyRequestCommand(cuid_t cuid,
@ -74,9 +74,9 @@ public:
void setConnectedAddr
(const std::string& hostname, const std::string& addr, uint16_t port)
{
_connectedHostname = hostname;
_connectedAddr = addr;
_connectedPort = port;
connectedHostname_ = hostname;
connectedAddr_ = addr;
connectedPort_ = port;
}
};

View File

@ -62,12 +62,12 @@ AbstractProxyResponseCommand::AbstractProxyResponseCommand
DownloadEngine* e,
const SocketHandle& s)
:AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
_httpConnection(httpConnection) {}
httpConnection_(httpConnection) {}
AbstractProxyResponseCommand::~AbstractProxyResponseCommand() {}
bool AbstractProxyResponseCommand::executeInternal() {
SharedHandle<HttpResponse> httpResponse = _httpConnection->receiveResponse();
SharedHandle<HttpResponse> httpResponse = httpConnection_->receiveResponse();
if(httpResponse.isNull()) {
// the server has not responded our request yet.
getDownloadEngine()->addCommand(this);

View File

@ -44,13 +44,13 @@ class SocketCore;
class AbstractProxyResponseCommand : public AbstractCommand {
private:
SharedHandle<HttpConnection> _httpConnection;
SharedHandle<HttpConnection> httpConnection_;
protected:
virtual bool executeInternal();
const SharedHandle<HttpConnection>& getHttpConnection() const
{
return _httpConnection;
return httpConnection_;
}
public:
AbstractProxyResponseCommand

View File

@ -44,40 +44,40 @@
namespace aria2 {
AbstractSingleDiskAdaptor::AbstractSingleDiskAdaptor():
_totalLength(0), _readOnly(false) {}
totalLength_(0), readOnly_(false) {}
AbstractSingleDiskAdaptor::~AbstractSingleDiskAdaptor() {}
void AbstractSingleDiskAdaptor::initAndOpenFile()
{
_diskWriter->initAndOpenFile(_totalLength);
diskWriter_->initAndOpenFile(totalLength_);
}
void AbstractSingleDiskAdaptor::openFile()
{
_diskWriter->openFile(_totalLength);
diskWriter_->openFile(totalLength_);
}
void AbstractSingleDiskAdaptor::closeFile()
{
_diskWriter->closeFile();
diskWriter_->closeFile();
}
void AbstractSingleDiskAdaptor::openExistingFile()
{
_diskWriter->openExistingFile(_totalLength);
diskWriter_->openExistingFile(totalLength_);
}
void AbstractSingleDiskAdaptor::writeData
(const unsigned char* data, size_t len, off_t offset)
{
_diskWriter->writeData(data, len, offset);
diskWriter_->writeData(data, len, offset);
}
ssize_t AbstractSingleDiskAdaptor::readData
(unsigned char* data, size_t len, off_t offset)
{
return _diskWriter->readData(data, len, offset);
return diskWriter_->readData(data, len, offset);
}
bool AbstractSingleDiskAdaptor::fileExists()
@ -92,7 +92,7 @@ uint64_t AbstractSingleDiskAdaptor::size()
void AbstractSingleDiskAdaptor::truncate(uint64_t length)
{
_diskWriter->truncate(length);
diskWriter_->truncate(length);
}
FileAllocationIteratorHandle
@ -102,14 +102,14 @@ AbstractSingleDiskAdaptor::fileAllocationIterator()
if(doesFallocate()) {
SharedHandle<FallocFileAllocationIterator> h
(new FallocFileAllocationIterator
(_diskWriter.get(), size() ,_totalLength));
(diskWriter_.get(), size() ,totalLength_));
return h;
} else
#endif // HAVE_POSIX_FALLOCATE
{
SingleFileAllocationIteratorHandle h
(new SingleFileAllocationIterator
(_diskWriter.get(), size(), _totalLength));
(diskWriter_.get(), size(), totalLength_));
h->init();
return h;
}
@ -117,42 +117,42 @@ AbstractSingleDiskAdaptor::fileAllocationIterator()
void AbstractSingleDiskAdaptor::enableDirectIO()
{
_diskWriter->enableDirectIO();
diskWriter_->enableDirectIO();
}
void AbstractSingleDiskAdaptor::disableDirectIO()
{
_diskWriter->disableDirectIO();
diskWriter_->disableDirectIO();
}
void AbstractSingleDiskAdaptor::enableReadOnly()
{
_diskWriter->enableReadOnly();
_readOnly = true;
diskWriter_->enableReadOnly();
readOnly_ = true;
}
void AbstractSingleDiskAdaptor::disableReadOnly()
{
_diskWriter->disableReadOnly();
_readOnly = false;
diskWriter_->disableReadOnly();
readOnly_ = false;
}
void AbstractSingleDiskAdaptor::cutTrailingGarbage()
{
if(File(getFilePath()).size() > _totalLength) {
_diskWriter->truncate(_totalLength);
if(File(getFilePath()).size() > totalLength_) {
diskWriter_->truncate(totalLength_);
}
}
void AbstractSingleDiskAdaptor::setDiskWriter
(const DiskWriterHandle& diskWriter)
{
_diskWriter = diskWriter;
diskWriter_ = diskWriter;
}
void AbstractSingleDiskAdaptor::setTotalLength(const uint64_t& totalLength)
{
_totalLength = totalLength;
totalLength_ = totalLength;
}
} // namespace aria2

View File

@ -44,9 +44,9 @@ class FileAllocationIterator;
class AbstractSingleDiskAdaptor : public DiskAdaptor {
private:
SharedHandle<DiskWriter> _diskWriter;
uint64_t _totalLength;
bool _readOnly;
SharedHandle<DiskWriter> diskWriter_;
uint64_t totalLength_;
bool readOnly_;
public:
AbstractSingleDiskAdaptor();
@ -83,7 +83,7 @@ public:
// Make sure that DiskWriter is set before calling this function.
virtual void disableReadOnly();
virtual bool isReadOnlyEnabled() const { return _readOnly; }
virtual bool isReadOnlyEnabled() const { return readOnly_; }
virtual void cutTrailingGarbage();
@ -93,14 +93,14 @@ public:
const SharedHandle<DiskWriter>& getDiskWriter() const
{
return _diskWriter;
return diskWriter_;
}
void setTotalLength(const uint64_t& totalLength);
uint64_t getTotalLength() const
{
return _totalLength;
return totalLength_;
}
};

View File

@ -65,34 +65,34 @@ ActivePeerConnectionCommand::ActivePeerConnectionCommand
time_t interval)
:
Command(cuid),
_requestGroup(requestGroup),
_interval(interval),
_e(e),
_numNewConnection(5)
requestGroup_(requestGroup),
interval_(interval),
e_(e),
numNewConnection_(5)
{
_requestGroup->increaseNumCommand();
requestGroup_->increaseNumCommand();
}
ActivePeerConnectionCommand::~ActivePeerConnectionCommand()
{
_requestGroup->decreaseNumCommand();
requestGroup_->decreaseNumCommand();
}
bool ActivePeerConnectionCommand::execute() {
if(_btRuntime->isHalt()) {
if(btRuntime_->isHalt()) {
return true;
}
if(_checkPoint.difference(global::wallclock) >= _interval) {
_checkPoint = global::wallclock;
TransferStat tstat = _requestGroup->calculateStat();
if(checkPoint_.difference(global::wallclock) >= interval_) {
checkPoint_ = global::wallclock;
TransferStat tstat = requestGroup_->calculateStat();
const unsigned int maxDownloadLimit =
_requestGroup->getMaxDownloadSpeedLimit();
const unsigned int maxUploadLimit = _requestGroup->getMaxUploadSpeedLimit();
requestGroup_->getMaxDownloadSpeedLimit();
const unsigned int maxUploadLimit = requestGroup_->getMaxUploadSpeedLimit();
unsigned int thresholdSpeed;
if(!bittorrent::getTorrentAttrs
(_requestGroup->getDownloadContext())->metadata.empty()) {
(requestGroup_->getDownloadContext())->metadata.empty()) {
thresholdSpeed =
_requestGroup->getOption()->getAsInt(PREF_BT_REQUEST_PEER_SPEED_LIMIT);
requestGroup_->getOption()->getAsInt(PREF_BT_REQUEST_PEER_SPEED_LIMIT);
} else {
thresholdSpeed = 0;
}
@ -100,36 +100,36 @@ bool ActivePeerConnectionCommand::execute() {
thresholdSpeed = std::min(maxDownloadLimit, thresholdSpeed);
}
if(// for seeder state
(_pieceStorage->downloadFinished() && _btRuntime->lessThanMaxPeers() &&
(pieceStorage_->downloadFinished() && btRuntime_->lessThanMaxPeers() &&
(maxUploadLimit == 0 || tstat.getUploadSpeed() < maxUploadLimit*0.8)) ||
// for leecher state
(!_pieceStorage->downloadFinished() &&
(!pieceStorage_->downloadFinished() &&
(tstat.getDownloadSpeed() < thresholdSpeed ||
_btRuntime->lessThanMinPeers()))) {
btRuntime_->lessThanMinPeers()))) {
unsigned int numConnection = 0;
if(_pieceStorage->downloadFinished()) {
if(_btRuntime->getMaxPeers() > _btRuntime->getConnections()) {
if(pieceStorage_->downloadFinished()) {
if(btRuntime_->getMaxPeers() > btRuntime_->getConnections()) {
numConnection =
std::min(_numNewConnection,
_btRuntime->getMaxPeers()-_btRuntime->getConnections());
std::min(numNewConnection_,
btRuntime_->getMaxPeers()-btRuntime_->getConnections());
}
} else {
numConnection = _numNewConnection;
numConnection = numNewConnection_;
}
for(unsigned int numAdd = numConnection;
numAdd > 0 && _peerStorage->isPeerAvailable(); --numAdd) {
SharedHandle<Peer> peer = _peerStorage->getUnusedPeer();
numAdd > 0 && peerStorage_->isPeerAvailable(); --numAdd) {
SharedHandle<Peer> peer = peerStorage_->getUnusedPeer();
connectToPeer(peer);
}
if(_btRuntime->getConnections() == 0 &&
!_pieceStorage->downloadFinished()) {
_btAnnounce->overrideMinInterval(BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL);
if(btRuntime_->getConnections() == 0 &&
!pieceStorage_->downloadFinished()) {
btAnnounce_->overrideMinInterval(BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL);
}
}
}
_e->addCommand(this);
e_->addCommand(this);
return false;
}
@ -138,13 +138,13 @@ void ActivePeerConnectionCommand::connectToPeer(const SharedHandle<Peer>& peer)
if(peer.isNull()) {
return;
}
peer->usedBy(_e->newCUID());
peer->usedBy(e_->newCUID());
PeerInitiateConnectionCommand* command =
new PeerInitiateConnectionCommand(peer->usedBy(), _requestGroup, peer, _e,
_btRuntime);
command->setPeerStorage(_peerStorage);
command->setPieceStorage(_pieceStorage);
_e->addCommand(command);
new PeerInitiateConnectionCommand(peer->usedBy(), requestGroup_, peer, e_,
btRuntime_);
command->setPeerStorage(peerStorage_);
command->setPieceStorage(pieceStorage_);
e_->addCommand(command);
if(getLogger()->info()) {
getLogger()->info(MSG_CONNECTING_TO_PEER,
util::itos(getCuid()).c_str(),
@ -155,25 +155,25 @@ void ActivePeerConnectionCommand::connectToPeer(const SharedHandle<Peer>& peer)
void ActivePeerConnectionCommand::setBtRuntime
(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
btRuntime_ = btRuntime;
}
void ActivePeerConnectionCommand::setPieceStorage
(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
pieceStorage_ = pieceStorage;
}
void ActivePeerConnectionCommand::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
peerStorage_ = peerStorage;
}
void ActivePeerConnectionCommand::setBtAnnounce
(const SharedHandle<BtAnnounce>& btAnnounce)
{
_btAnnounce = btAnnounce;
btAnnounce_ = btAnnounce;
}
} // namespace aria2

View File

@ -51,16 +51,16 @@ class BtAnnounce;
class ActivePeerConnectionCommand : public Command {
private:
RequestGroup* _requestGroup;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<BtAnnounce> _btAnnounce;
RequestGroup* requestGroup_;
SharedHandle<BtRuntime> btRuntime_;
SharedHandle<PieceStorage> pieceStorage_;
SharedHandle<PeerStorage> peerStorage_;
SharedHandle<BtAnnounce> btAnnounce_;
time_t _interval; // UNIT: sec
DownloadEngine* _e;
Timer _checkPoint;
unsigned int _numNewConnection; // the number of the connection to establish.
time_t interval_; // UNIT: sec
DownloadEngine* e_;
Timer checkPoint_;
unsigned int numNewConnection_; // the number of the connection to establish.
public:
ActivePeerConnectionCommand(cuid_t cuid,
RequestGroup* requestGroup,
@ -75,7 +75,7 @@ public:
void setNumNewConnection(size_t numNewConnection)
{
_numNewConnection = numNewConnection;
numNewConnection_ = numNewConnection;
}
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime);

View File

@ -63,9 +63,9 @@ namespace aria2 {
AdaptiveURISelector::AdaptiveURISelector
(const SharedHandle<ServerStatMan>& serverStatMan, RequestGroup* requestGroup):
_serverStatMan(serverStatMan),
_requestGroup(requestGroup),
_logger(LogFactory::getInstance())
serverStatMan_(serverStatMan),
requestGroup_(requestGroup),
logger_(LogFactory::getInstance())
{
resetCounters();
}
@ -74,12 +74,12 @@ AdaptiveURISelector::~AdaptiveURISelector() {}
std::string AdaptiveURISelector::select(FileEntry* fileEntry)
{
if(_logger->debug()) {
_logger->debug("AdaptiveURISelector: called %d",
_requestGroup->getNumConnection());
if(logger_->debug()) {
logger_->debug("AdaptiveURISelector: called %d",
requestGroup_->getNumConnection());
}
std::deque<std::string>& uris = fileEntry->getRemainingUris();
if (uris.empty() && _requestGroup->getNumConnection() <= 1) {
if (uris.empty() && requestGroup_->getNumConnection() <= 1) {
// here we know the download will fail, trying to find previously
// failed uris that may succeed with more permissive values
mayRetryWithIncreasedTimeout(fileEntry);
@ -95,8 +95,8 @@ std::string AdaptiveURISelector::select(FileEntry* fileEntry)
void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
{
if (_requestGroup->getTimeout()*2 >= MAX_TIMEOUT) return;
_requestGroup->setTimeout(_requestGroup->getTimeout()*2);
if (requestGroup_->getTimeout()*2 >= MAX_TIMEOUT) return;
requestGroup_->setTimeout(requestGroup_->getTimeout()*2);
std::deque<std::string>& uris = fileEntry->getRemainingUris();
// looking for retries
@ -105,12 +105,12 @@ void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry)
std::transform(timeouts.begin(), timeouts.end(), std::back_inserter(uris),
std::mem_fun_ref(&URIResult::getURI));
if(_logger->debug()) {
if(logger_->debug()) {
for(std::deque<std::string>::const_iterator i = uris.begin(),
eoi = uris.end(); i != eoi; ++i) {
_logger->debug("AdaptiveURISelector: will retry server with increased"
logger_->debug("AdaptiveURISelector: will retry server with increased"
" timeout (%d s): %s",
_requestGroup->getTimeout(), (*i).c_str());
requestGroup_->getTimeout(), (*i).c_str());
}
}
}
@ -122,48 +122,48 @@ std::string AdaptiveURISelector::selectOne(const std::deque<std::string>& uris)
return A2STR::NIL;
} else {
const unsigned int numPieces =
_requestGroup->getDownloadContext()->getNumPieces();
requestGroup_->getDownloadContext()->getNumPieces();
bool reservedContext = numPieces > 0 &&
_nbConnections > std::min(numPieces,
_requestGroup->getNumConcurrentCommand());
nbConnections_ > std::min(numPieces,
requestGroup_->getNumConcurrentCommand());
bool selectBest = numPieces == 0 || reservedContext;
if(numPieces > 0)
++_nbConnections;
++nbConnections_;
/* At least, 3 mirrors must be tested */
if(getNbTestedServers(uris) < 3) {
std::string notTested = getFirstNotTestedUri(uris);
if(notTested != A2STR::NIL) {
if(_logger->debug()) {
_logger->debug("AdaptiveURISelector: choosing the first non tested"
if(logger_->debug()) {
logger_->debug("AdaptiveURISelector: choosing the first non tested"
" mirror: %s", notTested.c_str());
}
--_nbServerToEvaluate;
--nbServerToEvaluate_;
return notTested;
}
}
if(!selectBest && _nbConnections > 1 && _nbServerToEvaluate > 0) {
_nbServerToEvaluate--;
if(!selectBest && nbConnections_ > 1 && nbServerToEvaluate_ > 0) {
nbServerToEvaluate_--;
std::string notTested = getFirstNotTestedUri(uris);
if(notTested != A2STR::NIL) {
/* Here we return the first untested mirror */
if(_logger->debug()) {
_logger->debug("AdaptiveURISelector: choosing non tested mirror %s"
if(logger_->debug()) {
logger_->debug("AdaptiveURISelector: choosing non tested mirror %s"
" for connection #%d",
notTested.c_str(), _nbConnections);
notTested.c_str(), nbConnections_);
}
return notTested;
} else {
/* Here we return a mirror which need to be tested again */
std::string toReTest = getFirstToTestUri(uris);
if(toReTest != A2STR::NIL) {
if(_logger->debug()) {
_logger->debug("AdaptiveURISelector: choosing mirror %s which has"
if(logger_->debug()) {
logger_->debug("AdaptiveURISelector: choosing mirror %s which has"
" not been tested recently for connection #%d",
toReTest.c_str(), _nbConnections);
toReTest.c_str(), nbConnections_);
}
return toReTest;
} else {
@ -187,16 +187,16 @@ std::string AdaptiveURISelector::getBestMirror
if (bests.size() < 2) {
std::string uri = getMaxDownloadSpeedUri(uris);
if(_logger->debug()) {
_logger->debug("AdaptiveURISelector: choosing the best mirror :"
if(logger_->debug()) {
logger_->debug("AdaptiveURISelector: choosing the best mirror :"
" %.2fKB/s %s (other mirrors are at least 25%% slower)",
(float) max/1024, uri.c_str());
}
return uri;
} else {
std::string uri = selectRandomUri(bests);
if(_logger->debug()) {
_logger->debug("AdaptiveURISelector: choosing randomly one of the best"
if(logger_->debug()) {
logger_->debug("AdaptiveURISelector: choosing randomly one of the best"
" mirrors (range [%.2fKB/s, %.2fKB/s]): %s",
(float) min/1024, (float) max/1024, uri.c_str());
}
@ -206,9 +206,9 @@ std::string AdaptiveURISelector::getBestMirror
void AdaptiveURISelector::resetCounters()
{
_nbConnections = 1;
_nbServerToEvaluate =
_requestGroup->getOption()->getAsInt(PREF_METALINK_SERVERS) - 1;
nbConnections_ = 1;
nbServerToEvaluate_ =
requestGroup_->getOption()->getAsInt(PREF_METALINK_SERVERS) - 1;
}
void AdaptiveURISelector::tuneDownloadCommand
@ -221,16 +221,16 @@ void AdaptiveURISelector::adjustLowestSpeedLimit
(const std::deque<std::string>& uris, DownloadCommand* command) const
{
unsigned int lowest =
_requestGroup->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
requestGroup_->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT);
if (lowest > 0) {
unsigned int low_lowest = 4 * 1024;
unsigned int max = getMaxDownloadSpeed(uris);
if (max > 0 && lowest > max / 4) {
_logger->notice("Lowering lowest-speed-limit since known max speed is too"
logger_->notice("Lowering lowest-speed-limit since known max speed is too"
" near (new:%d was:%d max:%d)", max / 4, lowest, max);
command->setLowestDownloadSpeedLimit(max / 4);
} else if (max == 0 && lowest > low_lowest) {
_logger->notice("Lowering lowest-speed-limit since we have no clue about"
logger_->notice("Lowering lowest-speed-limit since we have no clue about"
" available speed (now:%d was:%d)", low_lowest, lowest);
command->setLowestDownloadSpeedLimit(low_lowest);
}
@ -341,7 +341,7 @@ SharedHandle<ServerStat> AdaptiveURISelector::getServerStats
{
Request r;
r.setUri(uri);
return _serverStatMan->find(r.getHost(), r.getProtocol());
return serverStatMan_->find(r.getHost(), r.getProtocol());
}
unsigned int AdaptiveURISelector::getNbTestedServers

View File

@ -47,15 +47,15 @@ class Logger;
class AdaptiveURISelector:public URISelector {
private:
SharedHandle<ServerStatMan> _serverStatMan;
// No need to delete _requestGroup
RequestGroup* _requestGroup;
unsigned int _nbServerToEvaluate;
unsigned int _nbConnections;
SharedHandle<ServerStatMan> serverStatMan_;
// No need to delete requestGroup_
RequestGroup* requestGroup_;
unsigned int nbServerToEvaluate_;
unsigned int nbConnections_;
static const time_t MAX_TIMEOUT = 60;
Logger* _logger;
Logger* logger_;
void mayRetryWithIncreasedTimeout(FileEntry* fileEntry);

View File

@ -45,14 +45,14 @@ class AlphaNumberDecorator : public NumberDecorator
{
private:
size_t _width;
size_t width_;
char _zero;
char zero_;
std::string widen(const std::string& s, size_t width)
{
std::string t = s;
std::string zero(1, _zero);
std::string zero(1, zero_);
while(t.size() < width) {
t.insert(0, zero);
}
@ -61,14 +61,14 @@ private:
public:
AlphaNumberDecorator(size_t width, bool uppercase = false):
_width(width), _zero(uppercase?'A':'a') {}
width_(width), zero_(uppercase?'A':'a') {}
virtual ~AlphaNumberDecorator() {}
virtual std::string decorate(unsigned int number)
{
if(number == 0) {
return widen(std::string(1, _zero), _width);
return widen(std::string(1, zero_), width_);
}
int base = 26;
@ -77,12 +77,12 @@ public:
do {
unsigned int quot = number/base;
unsigned int rem = number%base;
u[index++] = _zero+rem;
u[index++] = zero_+rem;
number = quot;
} while(number);
std::reverse(&u[0], &u[index]);
return widen(std::string(&u[0], &u[index]), _width);
return widen(std::string(&u[0], &u[index]), width_);
}
};

View File

@ -50,13 +50,13 @@ const std::string AnnounceList::COMPLETED("completed");
AnnounceList::AnnounceList
(const std::vector<std::vector<std::string> >& announceList):
_currentTrackerInitialized(false) {
currentTrackerInitialized_(false) {
reconfigure(announceList);
}
AnnounceList::AnnounceList
(const std::deque<SharedHandle<AnnounceTier> >& announceTiers):
_tiers(announceTiers), _currentTrackerInitialized(false) {
tiers_(announceTiers), currentTrackerInitialized_(false) {
resetIterator();
}
@ -70,7 +70,7 @@ void AnnounceList::reconfigure
}
std::deque<std::string> urls((*itr).begin(), (*itr).end());
SharedHandle<AnnounceTier> tier(new AnnounceTier(urls));
_tiers.push_back(tier);
tiers_.push_back(tier);
}
resetIterator();
}
@ -78,72 +78,72 @@ void AnnounceList::reconfigure
void AnnounceList::reconfigure(const std::string& url) {
std::deque<std::string> urls;
urls.push_back(url);
_tiers.push_back(SharedHandle<AnnounceTier>(new AnnounceTier(urls)));
tiers_.push_back(SharedHandle<AnnounceTier>(new AnnounceTier(urls)));
resetIterator();
}
void AnnounceList::resetIterator() {
_currentTier = _tiers.begin();
if(_currentTier != _tiers.end() && (*_currentTier)->urls.size()) {
_currentTracker = (*_currentTier)->urls.begin();
_currentTrackerInitialized = true;
currentTier_ = tiers_.begin();
if(currentTier_ != tiers_.end() && (*currentTier_)->urls.size()) {
currentTracker_ = (*currentTier_)->urls.begin();
currentTrackerInitialized_ = true;
} else {
_currentTrackerInitialized = false;
currentTrackerInitialized_ = false;
}
}
std::string AnnounceList::getAnnounce() const {
if(_currentTrackerInitialized) {
return *_currentTracker;
if(currentTrackerInitialized_) {
return *currentTracker_;
} else {
return A2STR::NIL;
}
}
void AnnounceList::announceSuccess() {
if(_currentTrackerInitialized) {
(*_currentTier)->nextEvent();
std::string url = *_currentTracker;
(*_currentTier)->urls.erase(_currentTracker);
(*_currentTier)->urls.push_front(url);
_currentTier = _tiers.begin();
_currentTracker = (*_currentTier)->urls.begin();
if(currentTrackerInitialized_) {
(*currentTier_)->nextEvent();
std::string url = *currentTracker_;
(*currentTier_)->urls.erase(currentTracker_);
(*currentTier_)->urls.push_front(url);
currentTier_ = tiers_.begin();
currentTracker_ = (*currentTier_)->urls.begin();
}
}
void AnnounceList::announceFailure() {
if(_currentTrackerInitialized) {
++_currentTracker;
if(_currentTracker == (*_currentTier)->urls.end()) {
if(currentTrackerInitialized_) {
++currentTracker_;
if(currentTracker_ == (*currentTier_)->urls.end()) {
// force next event
(*_currentTier)->nextEventIfAfterStarted();
++_currentTier;
if(_currentTier == _tiers.end()) {
_currentTrackerInitialized = false;
(*currentTier_)->nextEventIfAfterStarted();
++currentTier_;
if(currentTier_ == tiers_.end()) {
currentTrackerInitialized_ = false;
} else {
_currentTracker = (*_currentTier)->urls.begin();
currentTracker_ = (*currentTier_)->urls.begin();
}
}
}
}
AnnounceTier::AnnounceEvent AnnounceList::getEvent() const {
if(_currentTrackerInitialized) {
return (*_currentTier)->event;
if(currentTrackerInitialized_) {
return (*currentTier_)->event;
} else {
return AnnounceTier::STARTED;
}
}
void AnnounceList::setEvent(AnnounceTier::AnnounceEvent event) {
if(_currentTrackerInitialized) {
(*_currentTier)->event = event;
if(currentTrackerInitialized_) {
(*currentTier_)->event = event;
}
}
std::string AnnounceList::getEventString() const {
if(_currentTrackerInitialized) {
switch((*_currentTier)->event) {
if(currentTrackerInitialized_) {
switch((*currentTier_)->event) {
case AnnounceTier::STARTED:
case AnnounceTier::STARTED_AFTER_COMPLETION:
return STARTED;
@ -188,18 +188,18 @@ public:
};
size_t AnnounceList::countStoppedAllowedTier() const {
return count_if(_tiers.begin(), _tiers.end(), FindStoppedAllowedTier());
return count_if(tiers_.begin(), tiers_.end(), FindStoppedAllowedTier());
}
size_t AnnounceList::countCompletedAllowedTier() const {
return count_if(_tiers.begin(), _tiers.end(), FindCompletedAllowedTier());
return count_if(tiers_.begin(), tiers_.end(), FindCompletedAllowedTier());
}
void AnnounceList::setCurrentTier
(const std::deque<SharedHandle<AnnounceTier> >::iterator& itr) {
if(itr != _tiers.end()) {
_currentTier = itr;
_currentTracker = (*_currentTier)->urls.begin();
if(itr != tiers_.end()) {
currentTier_ = itr;
currentTracker_ = (*currentTier_)->urls.begin();
}
}
@ -216,23 +216,23 @@ find_wrap_if(InputIterator first, InputIterator last,
void AnnounceList::moveToStoppedAllowedTier() {
std::deque<SharedHandle<AnnounceTier> >::iterator itr =
find_wrap_if(_tiers.begin(), _tiers.end(),
_currentTier,
find_wrap_if(tiers_.begin(), tiers_.end(),
currentTier_,
FindStoppedAllowedTier());
setCurrentTier(itr);
}
void AnnounceList::moveToCompletedAllowedTier() {
std::deque<SharedHandle<AnnounceTier> >::iterator itr =
find_wrap_if(_tiers.begin(), _tiers.end(),
_currentTier,
find_wrap_if(tiers_.begin(), tiers_.end(),
currentTier_,
FindCompletedAllowedTier());
setCurrentTier(itr);
}
void AnnounceList::shuffle() {
for(std::deque<SharedHandle<AnnounceTier> >::const_iterator itr =
_tiers.begin(), eoi = _tiers.end(); itr != eoi; ++itr) {
tiers_.begin(), eoi = tiers_.end(); itr != eoi; ++itr) {
std::deque<std::string>& urls = (*itr)->urls;
std::random_shuffle(urls.begin(), urls.end(),
*(SimpleRandomizer::getInstance().get()));
@ -241,7 +241,7 @@ void AnnounceList::shuffle() {
bool AnnounceList::allTiersFailed() const
{
return _currentTier == _tiers.end();
return currentTier_ == tiers_.end();
}
void AnnounceList::resetTier()
@ -251,8 +251,8 @@ void AnnounceList::resetTier()
bool AnnounceList::currentTierAcceptsStoppedEvent() const
{
if(_currentTrackerInitialized) {
return FindStoppedAllowedTier()(*_currentTier);
if(currentTrackerInitialized_) {
return FindStoppedAllowedTier()(*currentTier_);
} else {
return false;
}
@ -260,8 +260,8 @@ bool AnnounceList::currentTierAcceptsStoppedEvent() const
bool AnnounceList::currentTierAcceptsCompletedEvent() const
{
if(_currentTrackerInitialized) {
return FindCompletedAllowedTier()(*_currentTier);
if(currentTrackerInitialized_) {
return FindCompletedAllowedTier()(*currentTier_);
} else {
return false;
}

View File

@ -45,16 +45,16 @@ namespace aria2 {
class AnnounceList {
public:
private:
std::deque<SharedHandle<AnnounceTier> > _tiers;
std::deque<SharedHandle<AnnounceTier> >::iterator _currentTier;
std::deque<std::string>::iterator _currentTracker;
bool _currentTrackerInitialized;
std::deque<SharedHandle<AnnounceTier> > tiers_;
std::deque<SharedHandle<AnnounceTier> >::iterator currentTier_;
std::deque<std::string>::iterator currentTracker_;
bool currentTrackerInitialized_;
void resetIterator();
void setCurrentTier
(const std::deque<SharedHandle<AnnounceTier> >::iterator& itr);
public:
AnnounceList():_currentTrackerInitialized(false) {}
AnnounceList():currentTrackerInitialized_(false) {}
AnnounceList(const std::vector<std::vector<std::string> >& announceList);
AnnounceList(const std::deque<SharedHandle<AnnounceTier> >& tiers);
@ -62,7 +62,7 @@ public:
void reconfigure(const std::string& url);
size_t countTier() const {
return _tiers.size();
return tiers_.size();
}
/**

View File

@ -48,58 +48,58 @@ void callback(void* arg, int status, int timeouts, struct hostent* host)
{
AsyncNameResolver* resolverPtr = reinterpret_cast<AsyncNameResolver*>(arg);
if(status != ARES_SUCCESS) {
resolverPtr->_error = ares_strerror(status);
resolverPtr->_status = AsyncNameResolver::STATUS_ERROR;
resolverPtr->error_ = ares_strerror(status);
resolverPtr->status_ = AsyncNameResolver::STATUS_ERROR;
return;
}
for(char** ap = host->h_addr_list; *ap; ++ap) {
struct in_addr addr;
memcpy(&addr, *ap, sizeof(in_addr));
resolverPtr->_resolvedAddresses.push_back(inet_ntoa(addr));
resolverPtr->resolvedAddresses_.push_back(inet_ntoa(addr));
}
resolverPtr->_status = AsyncNameResolver::STATUS_SUCCESS;
resolverPtr->status_ = AsyncNameResolver::STATUS_SUCCESS;
}
AsyncNameResolver::AsyncNameResolver():
_status(STATUS_READY)
status_(STATUS_READY)
{
// TODO evaluate return value
ares_init(&_channel);
ares_init(&channel_);
}
AsyncNameResolver::~AsyncNameResolver()
{
ares_destroy(_channel);
ares_destroy(channel_);
}
void AsyncNameResolver::resolve(const std::string& name)
{
_hostname = name;
_status = STATUS_QUERYING;
ares_gethostbyname(_channel, name.c_str(), AF_INET, callback, this);
hostname_ = name;
status_ = STATUS_QUERYING;
ares_gethostbyname(channel_, name.c_str(), AF_INET, callback, this);
}
int AsyncNameResolver::getFds(fd_set* rfdsPtr, fd_set* wfdsPtr) const
{
return ares_fds(_channel, rfdsPtr, wfdsPtr);
return ares_fds(channel_, rfdsPtr, wfdsPtr);
}
void AsyncNameResolver::process(fd_set* rfdsPtr, fd_set* wfdsPtr)
{
ares_process(_channel, rfdsPtr, wfdsPtr);
ares_process(channel_, rfdsPtr, wfdsPtr);
}
#ifdef HAVE_LIBCARES
int AsyncNameResolver::getsock(sock_t* sockets) const
{
return ares_getsock(_channel, reinterpret_cast<ares_socket_t*>(sockets),
return ares_getsock(channel_, reinterpret_cast<ares_socket_t*>(sockets),
ARES_GETSOCK_MAXNUM);
}
void AsyncNameResolver::process(ares_socket_t readfd, ares_socket_t writefd)
{
ares_process_fd(_channel, readfd, writefd);
ares_process_fd(channel_, readfd, writefd);
}
#endif // HAVE_LIBCARES
@ -111,12 +111,12 @@ bool AsyncNameResolver::operator==(const AsyncNameResolver& resolver) const
void AsyncNameResolver::reset()
{
_hostname = A2STR::NIL;
_resolvedAddresses.clear();
_status = STATUS_READY;
ares_destroy(_channel);
hostname_ = A2STR::NIL;
resolvedAddresses_.clear();
status_ = STATUS_READY;
ares_destroy(channel_);
// TODO evaluate return value
ares_init(&_channel);
ares_init(&channel_);
}
} // namespace aria2

View File

@ -62,12 +62,12 @@ public:
STATUS_ERROR,
};
private:
STATUS _status;
ares_channel _channel;
STATUS status_;
ares_channel channel_;
std::vector<std::string> _resolvedAddresses;
std::string _error;
std::string _hostname;
std::vector<std::string> resolvedAddresses_;
std::string error_;
std::string hostname_;
public:
AsyncNameResolver();
@ -77,17 +77,17 @@ public:
const std::vector<std::string>& getResolvedAddresses() const
{
return _resolvedAddresses;
return resolvedAddresses_;
}
const std::string& getError() const
{
return _error;
return error_;
}
STATUS getStatus() const
{
return _status;
return status_;
}
int getFds(fd_set* rfdsPtr, fd_set* wfdsPtr) const;
@ -110,7 +110,7 @@ public:
const std::string& getHostname() const
{
return _hostname;
return hostname_;
}
};

View File

@ -47,28 +47,28 @@ namespace aria2 {
class AuthConfig {
private:
std::string _authScheme;
std::string _user;
std::string _password;
std::string authScheme_;
std::string user_;
std::string password_;
public:
AuthConfig() {}
AuthConfig(const std::string& user, const std::string& password):
_user(user), _password(password) {}
user_(user), password_(password) {}
std::string getAuthText() const
{
return strconcat(_user, ":", _password);
return strconcat(user_, ":", password_);
}
const std::string& getUser() const
{
return _user;
return user_;
}
const std::string& getPassword() const
{
return _password;
return password_;
}
};

View File

@ -71,10 +71,10 @@ AuthConfigFactory::createAuthConfig
}
std::deque<BasicCred>::const_iterator i =
findBasicCred(request->getHost(), request->getDir());
if(i == _basicCreds.end()) {
if(i == basicCreds_.end()) {
return SharedHandle<AuthConfig>();
} else {
return createAuthConfig((*i)._user, (*i)._password);
return createAuthConfig((*i).user_, (*i).password_);
}
} else {
if(!request->getUsername().empty()) {
@ -93,7 +93,7 @@ AuthConfigFactory::createAuthConfig
// First, check we have password corresponding to host and
// username
NetrcAuthResolver authResolver;
authResolver.setNetrc(_netrc);
authResolver.setNetrc(netrc_);
SharedHandle<AuthConfig> ac =
authResolver.resolveAuthConfig(request->getHost());
@ -133,7 +133,7 @@ AuthResolverHandle AuthConfigFactory::createHttpAuthResolver
resolver.reset(new DefaultAuthResolver());
} else {
NetrcAuthResolverHandle authResolver(new NetrcAuthResolver());
authResolver->setNetrc(_netrc);
authResolver->setNetrc(netrc_);
authResolver->ignoreDefault();
resolver = authResolver;
}
@ -150,7 +150,7 @@ AuthResolverHandle AuthConfigFactory::createFtpAuthResolver
resolver.reset(new DefaultAuthResolver());
} else {
NetrcAuthResolverHandle authResolver(new NetrcAuthResolver());
authResolver->setNetrc(_netrc);
authResolver->setNetrc(netrc_);
resolver = authResolver;
}
resolver->setUserDefinedAuthConfig
@ -164,18 +164,18 @@ AuthResolverHandle AuthConfigFactory::createFtpAuthResolver
void AuthConfigFactory::setNetrc(const SharedHandle<Netrc>& netrc)
{
_netrc = netrc;
netrc_ = netrc;
}
void AuthConfigFactory::updateBasicCred(const BasicCred& basicCred)
{
std::deque<BasicCred>::iterator i =
std::lower_bound(_basicCreds.begin(), _basicCreds.end(), basicCred);
std::lower_bound(basicCreds_.begin(), basicCreds_.end(), basicCred);
if(i != _basicCreds.end() && (*i) == basicCred) {
if(i != basicCreds_.end() && (*i) == basicCred) {
(*i) = basicCred;
} else {
_basicCreds.insert(i, basicCred);
basicCreds_.insert(i, basicCred);
}
}
@ -184,7 +184,7 @@ bool AuthConfigFactory::activateBasicCred
{
std::deque<BasicCred>::iterator i = findBasicCred(host, path);
if(i == _basicCreds.end()) {
if(i == basicCreds_.end()) {
SharedHandle<AuthConfig> authConfig =
createHttpAuthResolver(op)->resolveAuthConfig(host);
if(authConfig.isNull()) {
@ -192,8 +192,8 @@ bool AuthConfigFactory::activateBasicCred
} else {
BasicCred bc(authConfig->getUser(), authConfig->getPassword(),
host, path, true);
i = std::lower_bound(_basicCreds.begin(), _basicCreds.end(), bc);
_basicCreds.insert(i, bc);
i = std::lower_bound(basicCreds_.begin(), basicCreds_.end(), bc);
basicCreds_.insert(i, bc);
return true;
}
} else {
@ -206,34 +206,34 @@ AuthConfigFactory::BasicCred::BasicCred
(const std::string& user, const std::string& password,
const std::string& host, const std::string& path,
bool activated):
_user(user), _password(password),
_host(host), _path(path), _activated(activated)
user_(user), password_(password),
host_(host), path_(path), activated_(activated)
{
if(!util::endsWith(_path, "/")) {
_path += "/";
if(!util::endsWith(path_, "/")) {
path_ += "/";
}
}
void AuthConfigFactory::BasicCred::activate()
{
_activated = true;
activated_ = true;
}
bool AuthConfigFactory::BasicCred::isActivated() const
{
return _activated;
return activated_;
}
bool AuthConfigFactory::BasicCred::operator==(const BasicCred& cred) const
{
return _host == cred._host && _path == cred._path;
return host_ == cred.host_ && path_ == cred.path_;
}
bool AuthConfigFactory::BasicCred::operator<(const BasicCred& cred) const
{
int c = _host.compare(cred._host);
int c = host_.compare(cred.host_);
if(c == 0) {
return _path > cred._path;
return path_ > cred.path_;
} else {
return c < 0;
}
@ -245,13 +245,13 @@ AuthConfigFactory::findBasicCred(const std::string& host,
{
BasicCred bc("", "", host, path);
std::deque<BasicCred>::iterator i =
std::lower_bound(_basicCreds.begin(), _basicCreds.end(), bc);
for(; i != _basicCreds.end() && (*i)._host == host; ++i) {
if(util::startsWith(bc._path, (*i)._path)) {
std::lower_bound(basicCreds_.begin(), basicCreds_.end(), bc);
for(; i != basicCreds_.end() && (*i).host_ == host; ++i) {
if(util::startsWith(bc.path_, (*i).path_)) {
return i;
}
}
return _basicCreds.end();
return basicCreds_.end();
}
} // namespace aria2

View File

@ -53,7 +53,7 @@ class AuthResolver;
class AuthConfigFactory {
private:
SharedHandle<Netrc> _netrc;
SharedHandle<Netrc> netrc_;
SharedHandle<AuthConfig> createAuthConfig(const std::string& user,
const std::string& password) const;
@ -64,11 +64,11 @@ private:
public:
class BasicCred {
public:
std::string _user;
std::string _password;
std::string _host;
std::string _path;
bool _activated;
std::string user_;
std::string password_;
std::string host_;
std::string path_;
bool activated_;
BasicCred(const std::string& user, const std::string& password,
const std::string& host, const std::string& path,
@ -83,7 +83,7 @@ public:
bool operator<(const BasicCred& cred) const;
};
private:
std::deque<BasicCred> _basicCreds;
std::deque<BasicCred> basicCreds_;
public:
AuthConfigFactory();
@ -109,13 +109,13 @@ public:
(const std::string& host, const std::string& path, const Option* op);
// Find a BasicCred using host and path and return the iterator
// pointing to it. If not found, then return _basicCreds.end().
// pointing to it. If not found, then return basicCreds_.end().
std::deque<AuthConfigFactory::BasicCred>::iterator
findBasicCred(const std::string& host, const std::string& path);
// If the same BasicCred is already added, then it is replaced with
// given basicCred. Otherwise, insert given basicCred to
// _basicCreds.
// basicCreds_.
void updateBasicCred(const BasicCred& basicCred);
static const std::string ANONYMOUS;

View File

@ -43,45 +43,45 @@
namespace aria2 {
BNode::BNode(const SharedHandle<DHTBucket>& bucket):
_bucket(bucket),
_up(0),
_left(0),
_right(0) {}
bucket_(bucket),
up_(0),
left_(0),
right_(0) {}
BNode::~BNode()
{
delete _left;
delete _right;
delete left_;
delete right_;
}
void BNode::setLeft(BNode* left)
{
_left = left;
_left->_up = this;
left_ = left;
left_->up_ = this;
}
void BNode::setRight(BNode* right)
{
_right = right;
_right->_up = this;
right_ = right;
right_->up_ = this;
}
void BNode::setUp(BNode* up)
{
_up = up;
up_ = up;
}
void BNode::setBucket(const SharedHandle<DHTBucket>& bucket)
{
_bucket = bucket;
bucket_ = bucket;
}
bool BNode::isInRange(const unsigned char* key) const
{
if(_bucket.isNull()) {
return _left->isInRange(key) || _right->isInRange(key);
if(bucket_.isNull()) {
return left_->isInRange(key) || right_->isInRange(key);
} else {
return _bucket->isInRange(key);
return bucket_->isInRange(key);
}
}

View File

@ -48,13 +48,13 @@ class DHTNode;
class BNode {
private:
SharedHandle<DHTBucket> _bucket;
SharedHandle<DHTBucket> bucket_;
BNode* _up;
BNode* up_;
BNode* _left;
BNode* left_;
BNode* _right;
BNode* right_;
public:
BNode(const SharedHandle<DHTBucket>& bucket = SharedHandle<DHTBucket>());
@ -63,28 +63,28 @@ public:
const SharedHandle<DHTBucket>& getBucket() const
{
return _bucket;
return bucket_;
}
void setBucket(const SharedHandle<DHTBucket>& bucket);
BNode* getLeft() const
{
return _left;
return left_;
}
void setLeft(BNode* left);
BNode* getRight() const
{
return _right;
return right_;
}
void setRight(BNode* right);
BNode* getUp() const
{
return _up;
return up_;
}
void setUp(BNode* up);

View File

@ -46,51 +46,51 @@ using namespace aria2::expr;
namespace aria2 {
BitfieldMan::BitfieldMan(size_t blockLength, uint64_t totalLength)
:_blockLength(blockLength),
_totalLength(totalLength),
_bitfieldLength(0),
_blocks(0),
_filterEnabled(false),
_bitfield(0),
_useBitfield(0),
_filterBitfield(0),
_cachedNumMissingBlock(0),
_cachedNumFilteredBlock(0),
_cachedCompletedLength(0),
_cachedFilteredCompletedLength(0),
_cachedFilteredTotalLength(0)
:blockLength_(blockLength),
totalLength_(totalLength),
bitfieldLength_(0),
blocks_(0),
filterEnabled_(false),
bitfield_(0),
useBitfield_(0),
filterBitfield_(0),
cachedNumMissingBlock_(0),
cachedNumFilteredBlock_(0),
cachedCompletedLength_(0),
cachedFilteredCompletedLength_(0),
cachedFilteredTotalLength_(0)
{
if(_blockLength > 0 && _totalLength > 0) {
_blocks = _totalLength/_blockLength+(_totalLength%_blockLength ? 1 : 0);
_bitfieldLength = _blocks/8+(_blocks%8 ? 1 : 0);
_bitfield = new unsigned char[_bitfieldLength];
_useBitfield = new unsigned char[_bitfieldLength];
memset(_bitfield, 0, _bitfieldLength);
memset(_useBitfield, 0, _bitfieldLength);
if(blockLength_ > 0 && totalLength_ > 0) {
blocks_ = totalLength_/blockLength_+(totalLength_%blockLength_ ? 1 : 0);
bitfieldLength_ = blocks_/8+(blocks_%8 ? 1 : 0);
bitfield_ = new unsigned char[bitfieldLength_];
useBitfield_ = new unsigned char[bitfieldLength_];
memset(bitfield_, 0, bitfieldLength_);
memset(useBitfield_, 0, bitfieldLength_);
updateCache();
}
}
BitfieldMan::BitfieldMan(const BitfieldMan& bitfieldMan)
:_blockLength(bitfieldMan._blockLength),
_totalLength(bitfieldMan._totalLength),
_bitfieldLength(bitfieldMan._bitfieldLength),
_blocks(bitfieldMan._blocks),
_filterEnabled(bitfieldMan._filterEnabled),
_bitfield(new unsigned char[_bitfieldLength]),
_useBitfield(new unsigned char[_bitfieldLength]),
_filterBitfield(0),
_cachedNumMissingBlock(0),
_cachedNumFilteredBlock(0),
_cachedCompletedLength(0),
_cachedFilteredCompletedLength(0),
_cachedFilteredTotalLength(0)
:blockLength_(bitfieldMan.blockLength_),
totalLength_(bitfieldMan.totalLength_),
bitfieldLength_(bitfieldMan.bitfieldLength_),
blocks_(bitfieldMan.blocks_),
filterEnabled_(bitfieldMan.filterEnabled_),
bitfield_(new unsigned char[bitfieldLength_]),
useBitfield_(new unsigned char[bitfieldLength_]),
filterBitfield_(0),
cachedNumMissingBlock_(0),
cachedNumFilteredBlock_(0),
cachedCompletedLength_(0),
cachedFilteredCompletedLength_(0),
cachedFilteredTotalLength_(0)
{
memcpy(_bitfield, bitfieldMan._bitfield, _bitfieldLength);
memcpy(_useBitfield, bitfieldMan._useBitfield, _bitfieldLength);
if(_filterEnabled) {
_filterBitfield = new unsigned char[_bitfieldLength];
memcpy(_filterBitfield, bitfieldMan._filterBitfield, _bitfieldLength);
memcpy(bitfield_, bitfieldMan.bitfield_, bitfieldLength_);
memcpy(useBitfield_, bitfieldMan.useBitfield_, bitfieldLength_);
if(filterEnabled_) {
filterBitfield_ = new unsigned char[bitfieldLength_];
memcpy(filterBitfield_, bitfieldMan.filterBitfield_, bitfieldLength_);
}
updateCache();
}
@ -98,26 +98,26 @@ BitfieldMan::BitfieldMan(const BitfieldMan& bitfieldMan)
BitfieldMan& BitfieldMan::operator=(const BitfieldMan& bitfieldMan)
{
if(this != &bitfieldMan) {
_blockLength = bitfieldMan._blockLength;
_totalLength = bitfieldMan._totalLength;
_blocks = bitfieldMan._blocks;
_bitfieldLength = bitfieldMan._bitfieldLength;
_filterEnabled = bitfieldMan._filterEnabled;
blockLength_ = bitfieldMan.blockLength_;
totalLength_ = bitfieldMan.totalLength_;
blocks_ = bitfieldMan.blocks_;
bitfieldLength_ = bitfieldMan.bitfieldLength_;
filterEnabled_ = bitfieldMan.filterEnabled_;
delete [] _bitfield;
_bitfield = new unsigned char[_bitfieldLength];
memcpy(_bitfield, bitfieldMan._bitfield, _bitfieldLength);
delete [] bitfield_;
bitfield_ = new unsigned char[bitfieldLength_];
memcpy(bitfield_, bitfieldMan.bitfield_, bitfieldLength_);
delete [] _useBitfield;
_useBitfield = new unsigned char[_bitfieldLength];
memcpy(_useBitfield, bitfieldMan._useBitfield, _bitfieldLength);
delete [] useBitfield_;
useBitfield_ = new unsigned char[bitfieldLength_];
memcpy(useBitfield_, bitfieldMan.useBitfield_, bitfieldLength_);
delete [] _filterBitfield;
if(_filterEnabled) {
_filterBitfield = new unsigned char[_bitfieldLength];
memcpy(_filterBitfield, bitfieldMan._filterBitfield, _bitfieldLength);
delete [] filterBitfield_;
if(filterEnabled_) {
filterBitfield_ = new unsigned char[bitfieldLength_];
memcpy(filterBitfield_, bitfieldMan.filterBitfield_, bitfieldLength_);
} else {
_filterBitfield = 0;
filterBitfield_ = 0;
}
updateCache();
@ -126,16 +126,16 @@ BitfieldMan& BitfieldMan::operator=(const BitfieldMan& bitfieldMan)
}
BitfieldMan::~BitfieldMan() {
delete [] _bitfield;
delete [] _useBitfield;
delete [] _filterBitfield;
delete [] bitfield_;
delete [] useBitfield_;
delete [] filterBitfield_;
}
size_t BitfieldMan::getBlockLength(size_t index) const
{
if(index == _blocks-1) {
if(index == blocks_-1) {
return getLastBlockLength();
} else if(index < _blocks-1) {
} else if(index < blocks_-1) {
return getBlockLength();
} else {
return 0;
@ -145,14 +145,14 @@ size_t BitfieldMan::getBlockLength(size_t index) const
bool BitfieldMan::hasMissingPiece
(const unsigned char* peerBitfield, size_t length) const
{
if(_bitfieldLength != length) {
if(bitfieldLength_ != length) {
return false;
}
bool retval = false;
for(size_t i = 0; i < _bitfieldLength; ++i) {
unsigned char temp = peerBitfield[i] & ~_bitfield[i];
if(_filterEnabled) {
temp &= _filterBitfield[i];
for(size_t i = 0; i < bitfieldLength_; ++i) {
unsigned char temp = peerBitfield[i] & ~bitfield_[i];
if(filterEnabled_) {
temp &= filterBitfield_[i];
}
if(temp&0xff) {
retval = true;
@ -164,37 +164,37 @@ bool BitfieldMan::hasMissingPiece
bool BitfieldMan::getFirstMissingUnusedIndex(size_t& index) const
{
if(_filterEnabled) {
if(filterEnabled_) {
return bitfield::getFirstMissingIndex
(index, ~array(_bitfield)&~array(_useBitfield)&array(_filterBitfield),
_blocks);
(index, ~array(bitfield_)&~array(useBitfield_)&array(filterBitfield_),
blocks_);
} else {
return bitfield::getFirstMissingIndex
(index, ~array(_bitfield)&~array(_useBitfield), _blocks);
(index, ~array(bitfield_)&~array(useBitfield_), blocks_);
}
}
size_t BitfieldMan::getFirstNMissingUnusedIndex
(std::vector<size_t>& out, size_t n) const
{
if(_filterEnabled) {
if(filterEnabled_) {
return bitfield::getFirstNMissingIndex
(std::back_inserter(out), n,
~array(_bitfield)&~array(_useBitfield)&array(_filterBitfield), _blocks);
~array(bitfield_)&~array(useBitfield_)&array(filterBitfield_), blocks_);
} else {
return bitfield::getFirstNMissingIndex
(std::back_inserter(out), n,
~array(_bitfield)&~array(_useBitfield), _blocks);
~array(bitfield_)&~array(useBitfield_), blocks_);
}
}
bool BitfieldMan::getFirstMissingIndex(size_t& index) const
{
if(_filterEnabled) {
if(filterEnabled_) {
return bitfield::getFirstMissingIndex
(index, ~array(_bitfield)&array(_filterBitfield), _blocks);
(index, ~array(bitfield_)&array(filterBitfield_), blocks_);
} else {
return bitfield::getFirstMissingIndex(index, ~array(_bitfield), _blocks);
return bitfield::getFirstMissingIndex(index, ~array(bitfield_), blocks_);
}
}
@ -262,14 +262,14 @@ bool BitfieldMan::getSparseMissingUnusedIndex
const unsigned char* ignoreBitfield,
size_t ignoreBitfieldLength) const
{
if(_filterEnabled) {
if(filterEnabled_) {
return aria2::getSparseMissingUnusedIndex
(index, array(ignoreBitfield)|~array(_filterBitfield)|array(_bitfield)|array(_useBitfield),
_useBitfield, _blocks);
(index, array(ignoreBitfield)|~array(filterBitfield_)|array(bitfield_)|array(useBitfield_),
useBitfield_, blocks_);
} else {
return aria2::getSparseMissingUnusedIndex
(index, array(ignoreBitfield)|array(_bitfield)|array(_useBitfield),
_useBitfield, _blocks);
(index, array(ignoreBitfield)|array(bitfield_)|array(useBitfield_),
useBitfield_, blocks_);
}
}
@ -290,12 +290,12 @@ static bool copyBitfield(unsigned char* dst, const Array& src, size_t blocks)
bool BitfieldMan::getAllMissingIndexes(unsigned char* misbitfield, size_t len)
const
{
assert(len == _bitfieldLength);
if(_filterEnabled) {
assert(len == bitfieldLength_);
if(filterEnabled_) {
return copyBitfield
(misbitfield, ~array(_bitfield)&array(_filterBitfield), _blocks);
(misbitfield, ~array(bitfield_)&array(filterBitfield_), blocks_);
} else {
return copyBitfield(misbitfield, ~array(_bitfield), _blocks);
return copyBitfield(misbitfield, ~array(bitfield_), blocks_);
}
}
@ -303,19 +303,19 @@ bool BitfieldMan::getAllMissingIndexes(unsigned char* misbitfield, size_t len,
const unsigned char* peerBitfield,
size_t peerBitfieldLength) const
{
assert(len == _bitfieldLength);
if(_bitfieldLength != peerBitfieldLength) {
assert(len == bitfieldLength_);
if(bitfieldLength_ != peerBitfieldLength) {
return false;
}
if(_filterEnabled) {
if(filterEnabled_) {
return copyBitfield
(misbitfield,
~array(_bitfield)&array(peerBitfield)&array(_filterBitfield),
_blocks);
~array(bitfield_)&array(peerBitfield)&array(filterBitfield_),
blocks_);
} else {
return copyBitfield
(misbitfield, ~array(_bitfield)&array(peerBitfield),
_blocks);
(misbitfield, ~array(bitfield_)&array(peerBitfield),
blocks_);
}
}
@ -324,52 +324,52 @@ bool BitfieldMan::getAllMissingUnusedIndexes(unsigned char* misbitfield,
const unsigned char* peerBitfield,
size_t peerBitfieldLength) const
{
assert(len == _bitfieldLength);
if(_bitfieldLength != peerBitfieldLength) {
assert(len == bitfieldLength_);
if(bitfieldLength_ != peerBitfieldLength) {
return false;
}
if(_filterEnabled) {
if(filterEnabled_) {
return copyBitfield
(misbitfield,
~array(_bitfield)&~array(_useBitfield)&array(peerBitfield)&
array(_filterBitfield),
_blocks);
~array(bitfield_)&~array(useBitfield_)&array(peerBitfield)&
array(filterBitfield_),
blocks_);
} else {
return copyBitfield
(misbitfield,
~array(_bitfield)&~array(_useBitfield)&array(peerBitfield),
_blocks);
~array(bitfield_)&~array(useBitfield_)&array(peerBitfield),
blocks_);
}
}
size_t BitfieldMan::countMissingBlock() const {
return _cachedNumMissingBlock;
return cachedNumMissingBlock_;
}
size_t BitfieldMan::countMissingBlockNow() const {
if(_filterEnabled) {
array_ptr<unsigned char> temp(new unsigned char[_bitfieldLength]);
for(size_t i = 0; i < _bitfieldLength; ++i) {
temp[i] = _bitfield[i]&_filterBitfield[i];
if(filterEnabled_) {
array_ptr<unsigned char> temp(new unsigned char[bitfieldLength_]);
for(size_t i = 0; i < bitfieldLength_; ++i) {
temp[i] = bitfield_[i]&filterBitfield_[i];
}
size_t count = bitfield::countSetBit(_filterBitfield, _blocks)-
bitfield::countSetBit(temp, _blocks);
size_t count = bitfield::countSetBit(filterBitfield_, blocks_)-
bitfield::countSetBit(temp, blocks_);
return count;
} else {
return _blocks-bitfield::countSetBit(_bitfield, _blocks);
return blocks_-bitfield::countSetBit(bitfield_, blocks_);
}
}
size_t BitfieldMan::countFilteredBlockNow() const {
if(_filterEnabled) {
return bitfield::countSetBit(_filterBitfield, _blocks);
if(filterEnabled_) {
return bitfield::countSetBit(filterBitfield_, blocks_);
} else {
return 0;
}
}
bool BitfieldMan::setBitInternal(unsigned char* bitfield, size_t index, bool on) {
if(_blocks <= index) { return false; }
if(blocks_ <= index) { return false; }
unsigned char mask = 128 >> (index%8);
if(on) {
bitfield[index/8] |= mask;
@ -380,29 +380,29 @@ bool BitfieldMan::setBitInternal(unsigned char* bitfield, size_t index, bool on)
}
bool BitfieldMan::setUseBit(size_t index) {
return setBitInternal(_useBitfield, index, true);
return setBitInternal(useBitfield_, index, true);
}
bool BitfieldMan::unsetUseBit(size_t index) {
return setBitInternal(_useBitfield, index, false);
return setBitInternal(useBitfield_, index, false);
}
bool BitfieldMan::setBit(size_t index) {
bool b = setBitInternal(_bitfield, index, true);
bool b = setBitInternal(bitfield_, index, true);
updateCache();
return b;
}
bool BitfieldMan::unsetBit(size_t index) {
bool b = setBitInternal(_bitfield, index, false);
bool b = setBitInternal(bitfield_, index, false);
updateCache();
return b;
}
bool BitfieldMan::isFilteredAllBitSet() const {
if(_filterEnabled) {
for(size_t i = 0; i < _bitfieldLength; ++i) {
if((_bitfield[i]&_filterBitfield[i]) != _filterBitfield[i]) {
if(filterEnabled_) {
for(size_t i = 0; i < bitfieldLength_; ++i) {
if((bitfield_[i]&filterBitfield_[i]) != filterBitfield_[i]) {
return false;
}
}
@ -428,77 +428,77 @@ static bool testAllBitSet
bool BitfieldMan::isAllBitSet() const
{
return testAllBitSet(_bitfield, _bitfieldLength, _blocks);
return testAllBitSet(bitfield_, bitfieldLength_, blocks_);
}
bool BitfieldMan::isAllFilterBitSet() const
{
if(!_filterBitfield) {
if(!filterBitfield_) {
return false;
}
return testAllBitSet(_filterBitfield, _bitfieldLength, _blocks);
return testAllBitSet(filterBitfield_, bitfieldLength_, blocks_);
}
bool BitfieldMan::isBitSet(size_t index) const
{
return bitfield::test(_bitfield, _blocks, index);
return bitfield::test(bitfield_, blocks_, index);
}
bool BitfieldMan::isUseBitSet(size_t index) const
{
return bitfield::test(_useBitfield, _blocks, index);
return bitfield::test(useBitfield_, blocks_, index);
}
void BitfieldMan::setBitfield(const unsigned char* bitfield, size_t bitfieldLength) {
if(_bitfieldLength != bitfieldLength) {
if(bitfieldLength_ != bitfieldLength) {
return;
}
memcpy(_bitfield, bitfield, _bitfieldLength);
memset(_useBitfield, 0, _bitfieldLength);
memcpy(bitfield_, bitfield, bitfieldLength_);
memset(useBitfield_, 0, bitfieldLength_);
updateCache();
}
void BitfieldMan::clearAllBit() {
memset(_bitfield, 0, _bitfieldLength);
memset(bitfield_, 0, bitfieldLength_);
updateCache();
}
void BitfieldMan::setAllBit() {
for(size_t i = 0; i < _blocks; ++i) {
setBitInternal(_bitfield, i, true);
for(size_t i = 0; i < blocks_; ++i) {
setBitInternal(bitfield_, i, true);
}
updateCache();
}
void BitfieldMan::clearAllUseBit() {
memset(_useBitfield, 0, _bitfieldLength);
memset(useBitfield_, 0, bitfieldLength_);
updateCache();
}
void BitfieldMan::setAllUseBit() {
for(size_t i = 0; i < _blocks; ++i) {
setBitInternal(_useBitfield, i, true);
for(size_t i = 0; i < blocks_; ++i) {
setBitInternal(useBitfield_, i, true);
}
}
bool BitfieldMan::setFilterBit(size_t index) {
return setBitInternal(_filterBitfield, index, true);
return setBitInternal(filterBitfield_, index, true);
}
void BitfieldMan::ensureFilterBitfield()
{
if(!_filterBitfield) {
_filterBitfield = new unsigned char[_bitfieldLength];
memset(_filterBitfield, 0, _bitfieldLength);
if(!filterBitfield_) {
filterBitfield_ = new unsigned char[bitfieldLength_];
memset(filterBitfield_, 0, bitfieldLength_);
}
}
void BitfieldMan::addFilter(uint64_t offset, uint64_t length) {
ensureFilterBitfield();
if(length > 0) {
size_t startBlock = offset/_blockLength;
size_t endBlock = (offset+length-1)/_blockLength;
for(size_t i = startBlock; i <= endBlock && i < _blocks; i++) {
size_t startBlock = offset/blockLength_;
size_t endBlock = (offset+length-1)/blockLength_;
for(size_t i = startBlock; i <= endBlock && i < blocks_; i++) {
setFilterBit(i);
}
}
@ -508,10 +508,10 @@ void BitfieldMan::addFilter(uint64_t offset, uint64_t length) {
void BitfieldMan::removeFilter(uint64_t offset, uint64_t length) {
ensureFilterBitfield();
if(length > 0) {
size_t startBlock = offset/_blockLength;
size_t endBlock = (offset+length-1)/_blockLength;
for(size_t i = startBlock; i <= endBlock && i < _blocks; i++) {
setBitInternal(_filterBitfield, i, false);
size_t startBlock = offset/blockLength_;
size_t endBlock = (offset+length-1)/blockLength_;
for(size_t i = startBlock; i <= endBlock && i < blocks_; i++) {
setBitInternal(filterBitfield_, i, false);
}
}
updateCache();
@ -520,16 +520,16 @@ void BitfieldMan::removeFilter(uint64_t offset, uint64_t length) {
void BitfieldMan::addNotFilter(uint64_t offset, uint64_t length)
{
ensureFilterBitfield();
if(length > 0 && _blocks > 0) {
size_t startBlock = offset/_blockLength;
if(_blocks <= startBlock) {
startBlock = _blocks;
if(length > 0 && blocks_ > 0) {
size_t startBlock = offset/blockLength_;
if(blocks_ <= startBlock) {
startBlock = blocks_;
}
size_t endBlock = (offset+length-1)/_blockLength;
size_t endBlock = (offset+length-1)/blockLength_;
for(size_t i = 0; i < startBlock; ++i) {
setFilterBit(i);
}
for(size_t i = endBlock+1; i < _blocks; ++i) {
for(size_t i = endBlock+1; i < blocks_; ++i) {
setFilterBit(i);
}
}
@ -538,61 +538,61 @@ void BitfieldMan::addNotFilter(uint64_t offset, uint64_t length)
void BitfieldMan::enableFilter() {
ensureFilterBitfield();
_filterEnabled = true;
filterEnabled_ = true;
updateCache();
}
void BitfieldMan::disableFilter() {
_filterEnabled = false;
filterEnabled_ = false;
updateCache();
}
void BitfieldMan::clearFilter() {
if(_filterBitfield) {
delete [] _filterBitfield;
_filterBitfield = 0;
if(filterBitfield_) {
delete [] filterBitfield_;
filterBitfield_ = 0;
}
_filterEnabled = false;
filterEnabled_ = false;
updateCache();
}
uint64_t BitfieldMan::getFilteredTotalLengthNow() const {
if(!_filterBitfield) {
if(!filterBitfield_) {
return 0;
}
size_t filteredBlocks = bitfield::countSetBit(_filterBitfield, _blocks);
size_t filteredBlocks = bitfield::countSetBit(filterBitfield_, blocks_);
if(filteredBlocks == 0) {
return 0;
}
if(bitfield::test(_filterBitfield, _blocks, _blocks-1)) {
return ((uint64_t)filteredBlocks-1)*_blockLength+getLastBlockLength();
if(bitfield::test(filterBitfield_, blocks_, blocks_-1)) {
return ((uint64_t)filteredBlocks-1)*blockLength_+getLastBlockLength();
} else {
return ((uint64_t)filteredBlocks)*_blockLength;
return ((uint64_t)filteredBlocks)*blockLength_;
}
}
uint64_t BitfieldMan::getCompletedLength(bool useFilter) const {
unsigned char* temp;
if(useFilter) {
temp = new unsigned char[_bitfieldLength];
for(size_t i = 0; i < _bitfieldLength; ++i) {
temp[i] = _bitfield[i];
if(_filterEnabled) {
temp[i] &= _filterBitfield[i];
temp = new unsigned char[bitfieldLength_];
for(size_t i = 0; i < bitfieldLength_; ++i) {
temp[i] = bitfield_[i];
if(filterEnabled_) {
temp[i] &= filterBitfield_[i];
}
}
} else {
temp = _bitfield;
temp = bitfield_;
}
size_t completedBlocks = bitfield::countSetBit(temp, _blocks);
size_t completedBlocks = bitfield::countSetBit(temp, blocks_);
uint64_t completedLength = 0;
if(completedBlocks == 0) {
completedLength = 0;
} else {
if(bitfield::test(temp, _blocks, _blocks-1)) {
completedLength = ((uint64_t)completedBlocks-1)*_blockLength+getLastBlockLength();
if(bitfield::test(temp, blocks_, blocks_-1)) {
completedLength = ((uint64_t)completedBlocks-1)*blockLength_+getLastBlockLength();
} else {
completedLength = ((uint64_t)completedBlocks)*_blockLength;
completedLength = ((uint64_t)completedBlocks)*blockLength_;
}
}
if(useFilter) {
@ -611,11 +611,11 @@ uint64_t BitfieldMan::getFilteredCompletedLengthNow() const {
void BitfieldMan::updateCache()
{
_cachedNumMissingBlock = countMissingBlockNow();
_cachedNumFilteredBlock = countFilteredBlockNow();
_cachedFilteredTotalLength = getFilteredTotalLengthNow();
_cachedCompletedLength = getCompletedLengthNow();
_cachedFilteredCompletedLength = getFilteredCompletedLengthNow();
cachedNumMissingBlock_ = countMissingBlockNow();
cachedNumFilteredBlock_ = countFilteredBlockNow();
cachedFilteredTotalLength_ = getFilteredTotalLengthNow();
cachedCompletedLength_ = getCompletedLengthNow();
cachedFilteredCompletedLength_ = getFilteredCompletedLengthNow();
}
bool BitfieldMan::isBitRangeSet(size_t startIndex, size_t endIndex) const
@ -649,14 +649,14 @@ bool BitfieldMan::isBitSetOffsetRange(uint64_t offset, uint64_t length) const
if(length <= 0) {
return false;
}
if(_totalLength <= offset) {
if(totalLength_ <= offset) {
return false;
}
if(_totalLength < offset+length) {
length = _totalLength-offset;
if(totalLength_ < offset+length) {
length = totalLength_-offset;
}
size_t startBlock = offset/_blockLength;
size_t endBlock = (offset+length-1)/_blockLength;
size_t startBlock = offset/blockLength_;
size_t endBlock = (offset+length-1)/blockLength_;
for(size_t i = startBlock; i <= endBlock; i++) {
if(!isBitSet(i)) {
return false;
@ -667,11 +667,11 @@ bool BitfieldMan::isBitSetOffsetRange(uint64_t offset, uint64_t length) const
uint64_t BitfieldMan::getMissingUnusedLength(size_t startingIndex) const
{
if(startingIndex < 0 || _blocks <= startingIndex) {
if(startingIndex < 0 || blocks_ <= startingIndex) {
return 0;
}
uint64_t length = 0;
for(size_t i = startingIndex; i < _blocks; ++i) {
for(size_t i = startingIndex; i < blocks_; ++i) {
if(isBitSet(i) || isUseBitSet(i)) {
break;
}

View File

@ -45,21 +45,21 @@ namespace aria2 {
class BitfieldMan {
private:
size_t _blockLength;
uint64_t _totalLength;
size_t _bitfieldLength;
size_t _blocks;
bool _filterEnabled;
unsigned char* _bitfield;
unsigned char* _useBitfield;
unsigned char* _filterBitfield;
size_t blockLength_;
uint64_t totalLength_;
size_t bitfieldLength_;
size_t blocks_;
bool filterEnabled_;
unsigned char* bitfield_;
unsigned char* useBitfield_;
unsigned char* filterBitfield_;
// for caching
size_t _cachedNumMissingBlock;
size_t _cachedNumFilteredBlock;
uint64_t _cachedCompletedLength;
uint64_t _cachedFilteredCompletedLength;
uint64_t _cachedFilteredTotalLength;
size_t cachedNumMissingBlock_;
size_t cachedNumFilteredBlock_;
uint64_t cachedCompletedLength_;
uint64_t cachedFilteredCompletedLength_;
uint64_t cachedFilteredTotalLength_;
bool setBitInternal(unsigned char* bitfield, size_t index, bool on);
bool setFilterBit(size_t index);
@ -69,7 +69,7 @@ private:
uint64_t getCompletedLength(bool useFilter) const;
// If _filterBitfield is 0, allocate _bitfieldLength bytes to it and
// If filterBitfield_ is 0, allocate bitfieldLength_ bytes to it and
// set 0 to all bytes.
void ensureFilterBitfield();
public:
@ -102,19 +102,19 @@ public:
size_t getBlockLength() const
{
return _blockLength;
return blockLength_;
}
size_t getLastBlockLength() const
{
return _totalLength-_blockLength*(_blocks-1);
return totalLength_-blockLength_*(blocks_-1);
}
size_t getBlockLength(size_t index) const;
uint64_t getTotalLength() const { return _totalLength; }
uint64_t getTotalLength() const { return totalLength_; }
// Returns true iff there is a bit index which is set in _bitfield,
// Returns true iff there is a bit index which is set in bitfield_,
// but not set in this object.
//
// affected by filter
@ -181,23 +181,23 @@ public:
const unsigned char* getBitfield() const
{
return _bitfield;
return bitfield_;
}
size_t getBitfieldLength() const
{
return _bitfieldLength;
return bitfieldLength_;
}
// affected by filter
size_t countFilteredBlock() const
{
return _cachedNumFilteredBlock;
return cachedNumFilteredBlock_;
}
size_t countBlock() const
{
return _blocks;
return blocks_;
}
// affected by filter
@ -205,7 +205,7 @@ public:
size_t getMaxIndex() const
{
return _blocks-1;
return blocks_-1;
}
void setBitfield(const unsigned char* bitfield, size_t bitfieldLength);
@ -228,13 +228,13 @@ public:
void disableFilter();
bool isFilterEnabled() const
{
return _filterEnabled;
return filterEnabled_;
}
// affected by filter
uint64_t getFilteredTotalLength() const
{
return _cachedFilteredTotalLength;
return cachedFilteredTotalLength_;
}
// affected by filter
@ -242,7 +242,7 @@ public:
uint64_t getCompletedLength() const
{
return _cachedCompletedLength;
return cachedCompletedLength_;
}
uint64_t getCompletedLengthNow() const;
@ -250,7 +250,7 @@ public:
// affected by filter
uint64_t getFilteredCompletedLength() const
{
return _cachedFilteredCompletedLength;
return cachedFilteredCompletedLength_;
}
// affected by filter
@ -270,7 +270,7 @@ public:
const unsigned char* getFilterBitfield() const
{
return _filterBitfield;
return filterBitfield_;
}
};

View File

@ -43,12 +43,12 @@ namespace aria2 {
class BtAbortOutstandingRequestEvent {
private:
SharedHandle<Piece> _piece;
SharedHandle<Piece> piece_;
public:
BtAbortOutstandingRequestEvent(const SharedHandle<Piece>& piece):
_piece(piece) {}
piece_(piece) {}
const SharedHandle<Piece>& getPiece() const { return _piece; }
const SharedHandle<Piece>& getPiece() const { return piece_; }
};
} // namespace aria2

View File

@ -50,33 +50,33 @@ namespace aria2 {
const std::string BtBitfieldMessage::NAME("bitfield");
BtBitfieldMessage::BtBitfieldMessage():SimpleBtMessage(ID, NAME),
_bitfield(0),
_bitfieldLength(0)
bitfield_(0),
bitfieldLength_(0)
{}
BtBitfieldMessage::BtBitfieldMessage
(const unsigned char* bitfield, size_t bitfieldLength):
SimpleBtMessage(ID, NAME),
_bitfield(0),
_bitfieldLength(0)
bitfield_(0),
bitfieldLength_(0)
{
setBitfield(bitfield, bitfieldLength);
}
BtBitfieldMessage::~BtBitfieldMessage()
{
delete [] _bitfield;
delete [] bitfield_;
}
void BtBitfieldMessage::setBitfield
(const unsigned char* bitfield, size_t bitfieldLength) {
if(_bitfield == bitfield) {
if(bitfield_ == bitfield) {
return;
}
delete [] _bitfield;
_bitfieldLength = bitfieldLength;
_bitfield = new unsigned char[_bitfieldLength];
memcpy(_bitfield, bitfield, _bitfieldLength);
delete [] bitfield_;
bitfieldLength_ = bitfieldLength;
bitfield_ = new unsigned char[bitfieldLength_];
memcpy(bitfield_, bitfield, bitfieldLength_);
}
BtBitfieldMessageHandle
@ -93,9 +93,9 @@ void BtBitfieldMessage::doReceivedAction() {
if(isMetadataGetMode()) {
return;
}
getPieceStorage()->updatePieceStats(_bitfield, _bitfieldLength,
getPieceStorage()->updatePieceStats(bitfield_, bitfieldLength_,
getPeer()->getBitfield());
getPeer()->setBitfield(_bitfield, _bitfieldLength);
getPeer()->setBitfield(bitfield_, bitfieldLength_);
if(getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) {
throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER);
}
@ -108,19 +108,19 @@ unsigned char* BtBitfieldMessage::createMessage() {
* bitfield --- bitfield, len bytes
* total: 5+len bytes
*/
const size_t msgLength = 5+_bitfieldLength;
const size_t msgLength = 5+bitfieldLength_;
unsigned char* msg = new unsigned char[msgLength];
bittorrent::createPeerMessageString(msg, msgLength, 1+_bitfieldLength, ID);
memcpy(msg+5, _bitfield, _bitfieldLength);
bittorrent::createPeerMessageString(msg, msgLength, 1+bitfieldLength_, ID);
memcpy(msg+5, bitfield_, bitfieldLength_);
return msg;
}
size_t BtBitfieldMessage::getMessageLength() {
return 5+_bitfieldLength;
return 5+bitfieldLength_;
}
std::string BtBitfieldMessage::toString() const {
return strconcat(NAME, " ", util::toHex(_bitfield, _bitfieldLength));
return strconcat(NAME, " ", util::toHex(bitfield_, bitfieldLength_));
}
} // namespace aria2

View File

@ -45,8 +45,8 @@ typedef SharedHandle<BtBitfieldMessage> BtBitfieldMessageHandle;
class BtBitfieldMessage : public SimpleBtMessage {
private:
unsigned char* _bitfield;
size_t _bitfieldLength;
unsigned char* bitfield_;
size_t bitfieldLength_;
public:
BtBitfieldMessage();
@ -60,9 +60,9 @@ public:
void setBitfield(const unsigned char* bitfield, size_t bitfieldLength);
const unsigned char* getBitfield() const { return _bitfield; }
const unsigned char* getBitfield() const { return bitfield_; }
size_t getBitfieldLength() const { return _bitfieldLength; }
size_t getBitfieldLength() const { return bitfieldLength_; }
static BtBitfieldMessageHandle create
(const unsigned char* data, size_t dataLength);

View File

@ -43,19 +43,19 @@ namespace aria2 {
class BtBitfieldMessageValidator : public BtMessageValidator {
private:
const BtBitfieldMessage* _message;
size_t _numPiece;
const BtBitfieldMessage* message_;
size_t numPiece_;
public:
BtBitfieldMessageValidator(const BtBitfieldMessage* message,
size_t numPiece):
_message(message),
_numPiece(numPiece) {}
message_(message),
numPiece_(numPiece) {}
virtual void validate()
{
bittorrent::checkBitfield(_message->getBitfield(),
_message->getBitfieldLength(),
_numPiece);
bittorrent::checkBitfield(message_->getBitfield(),
message_->getBitfieldLength(),
numPiece_);
}
};

View File

@ -41,18 +41,18 @@ namespace aria2 {
class BtCancelSendingPieceEvent {
private:
size_t _index;
uint32_t _begin;
size_t _length;
size_t index_;
uint32_t begin_;
size_t length_;
public:
BtCancelSendingPieceEvent(size_t index, uint32_t begin, size_t length):
_index(index), _begin(begin), _length(length) {}
index_(index), begin_(begin), length_(length) {}
size_t getIndex() const { return _index; }
size_t getIndex() const { return index_; }
uint32_t getBegin() const { return _begin; }
uint32_t getBegin() const { return begin_; }
size_t getLength() const { return _length; }
size_t getLength() const { return length_; }
};
} // namespace aria2

View File

@ -53,9 +53,9 @@ namespace aria2 {
BtDependency::BtDependency(const WeakHandle<RequestGroup>& dependant,
const SharedHandle<RequestGroup>& dependee):
_dependant(dependant),
_dependee(dependee),
_logger(LogFactory::getInstance()) {}
dependant_(dependant),
dependee_(dependee),
logger_(LogFactory::getInstance()) {}
BtDependency::~BtDependency() {}
@ -73,12 +73,12 @@ static void copyValues(const SharedHandle<FileEntry>& d,
bool BtDependency::resolve()
{
if(_dependee->getNumCommand() == 0 && _dependee->downloadFinished()) {
SharedHandle<RequestGroup> dependee = _dependee;
if(dependee_->getNumCommand() == 0 && dependee_->downloadFinished()) {
SharedHandle<RequestGroup> dependee = dependee_;
// cut reference here
_dependee.reset();
dependee_.reset();
SharedHandle<DownloadContext> context(new DownloadContext());
context->setDir(_dependant->getDownloadContext()->getDir());
context->setDir(dependant_->getDownloadContext()->getDir());
try {
SharedHandle<DiskAdaptor> diskAdaptor =
dependee->getPieceStorage()->getDiskAdaptor();
@ -96,7 +96,7 @@ bool BtDependency::resolve()
const std::vector<SharedHandle<FileEntry> >& fileEntries =
context->getFileEntries();
const std::vector<SharedHandle<FileEntry> >& dependantFileEntries =
_dependant->getDownloadContext()->getFileEntries();
dependant_->getDownloadContext()->getFileEntries();
// If dependant's FileEntry::getOriginalName() is empty, we
// assume that torrent is single file. In Metalink3, this is
// always assumed.
@ -106,9 +106,9 @@ bool BtDependency::resolve()
} else {
std::for_each(fileEntries.begin(), fileEntries.end(),
std::bind2nd(mem_fun_sh(&FileEntry::setRequested),false));
// Copy file path in _dependant's FileEntries to newly created
// Copy file path in dependant_'s FileEntries to newly created
// context's FileEntries to endorse the path structure of
// _dependant. URIs and singleHostMultiConnection are also copied.
// dependant_. URIs and singleHostMultiConnection are also copied.
std::vector<SharedHandle<FileEntry> >::const_iterator ctxFilesEnd =
fileEntries.end();
for(std::vector<SharedHandle<FileEntry> >::const_iterator s =
@ -130,26 +130,26 @@ bool BtDependency::resolve()
}
}
} catch(RecoverableException& e) {
_logger->error(EX_EXCEPTION_CAUGHT, e);
if(_logger->info()) {
_logger->info("BtDependency for GID#%s failed. Go without Bt.",
util::itos(_dependant->getGID()).c_str());
logger_->error(EX_EXCEPTION_CAUGHT, e);
if(logger_->info()) {
logger_->info("BtDependency for GID#%s failed. Go without Bt.",
util::itos(dependant_->getGID()).c_str());
}
return true;
}
if(_logger->info()) {
_logger->info("Dependency resolved for GID#%s",
util::itos(_dependant->getGID()).c_str());
if(logger_->info()) {
logger_->info("Dependency resolved for GID#%s",
util::itos(dependant_->getGID()).c_str());
}
_dependant->setDownloadContext(context);
dependant_->setDownloadContext(context);
return true;
} else if(_dependee->getNumCommand() == 0) {
// _dependee's download failed.
} else if(dependee_->getNumCommand() == 0) {
// dependee_'s download failed.
// cut reference here
_dependee.reset();
if(_logger->info()) {
_logger->info("BtDependency for GID#%s failed. Go without Bt.",
util::itos(_dependant->getGID()).c_str());
dependee_.reset();
if(logger_->info()) {
logger_->info("BtDependency for GID#%s failed. Go without Bt.",
util::itos(dependant_->getGID()).c_str());
}
return true;
} else {

View File

@ -46,9 +46,9 @@ class Logger;
class BtDependency : public Dependency
{
private:
WeakHandle<RequestGroup> _dependant;
SharedHandle<RequestGroup> _dependee;
Logger* _logger;
WeakHandle<RequestGroup> dependant_;
SharedHandle<RequestGroup> dependee_;
Logger* logger_;
public:
BtDependency(const WeakHandle<RequestGroup>& dependant,
const SharedHandle<RequestGroup>& dependee);

View File

@ -54,8 +54,8 @@ const std::string BtExtendedMessage::NAME("extended");
BtExtendedMessage::BtExtendedMessage
(const ExtensionMessageHandle& extensionMessage):
SimpleBtMessage(ID, NAME),
_extensionMessage(extensionMessage),
_msgLength(0)
extensionMessage_(extensionMessage),
msgLength_(0)
{}
unsigned char* BtExtendedMessage::createMessage()
@ -67,20 +67,20 @@ unsigned char* BtExtendedMessage::createMessage()
* extpayload --- extpayload, nbytes
* total: 6+extpayload.length bytes
*/
std::string payload = _extensionMessage->getPayload();
_msgLength = 6+payload.size();
unsigned char* msg = new unsigned char[_msgLength];
bittorrent::createPeerMessageString(msg, _msgLength, 2+payload.size(), ID);
*(msg+5) = _extensionMessage->getExtensionMessageID();
std::string payload = extensionMessage_->getPayload();
msgLength_ = 6+payload.size();
unsigned char* msg = new unsigned char[msgLength_];
bittorrent::createPeerMessageString(msg, msgLength_, 2+payload.size(), ID);
*(msg+5) = extensionMessage_->getExtensionMessageID();
memcpy(msg+6, payload.data(), payload.size());
return msg;
}
size_t BtExtendedMessage::getMessageLength() {
if(!_msgLength) {
_msgLength = 6+_extensionMessage->getPayload().size();
if(!msgLength_) {
msgLength_ = 6+extensionMessage_->getPayload().size();
}
return _msgLength;
return msgLength_;
}
bool BtExtendedMessage::sendPredicate() const
@ -89,7 +89,7 @@ bool BtExtendedMessage::sendPredicate() const
}
std::string BtExtendedMessage::toString() const {
return strconcat(NAME, " ", _extensionMessage->toString());
return strconcat(NAME, " ", extensionMessage_->toString());
}
BtExtendedMessageHandle
@ -108,8 +108,8 @@ BtExtendedMessage::create(const SharedHandle<ExtensionMessageFactory>& factory,
void BtExtendedMessage::doReceivedAction()
{
if(!_extensionMessage.isNull()) {
_extensionMessage->doReceivedAction();
if(!extensionMessage_.isNull()) {
extensionMessage_->doReceivedAction();
}
}

View File

@ -47,9 +47,9 @@ typedef SharedHandle<BtExtendedMessage> BtExtendedMessageHandle;
class BtExtendedMessage:public SimpleBtMessage
{
private:
SharedHandle<ExtensionMessage> _extensionMessage;
SharedHandle<ExtensionMessage> extensionMessage_;
size_t _msgLength;
size_t msgLength_;
public:
BtExtendedMessage(const SharedHandle<ExtensionMessage>& extensionMessage =
SharedHandle<ExtensionMessage>());
@ -76,7 +76,7 @@ public:
const SharedHandle<ExtensionMessage>& getExtensionMessage() const
{
return _extensionMessage;
return extensionMessage_;
}
};

View File

@ -57,44 +57,44 @@ BtHandshakeMessage::BtHandshakeMessage(const unsigned char* infoHash,
SimpleBtMessage(ID, NAME)
{
init();
memcpy(_infoHash, infoHash, INFO_HASH_LENGTH);
memcpy(_peerId, peerId, PEER_ID_LENGTH);
memcpy(infoHash_, infoHash, INFO_HASH_LENGTH);
memcpy(peerId_, peerId, PEER_ID_LENGTH);
}
void BtHandshakeMessage::init() {
_pstrlen = 19;
_pstr = new unsigned char[PSTR_LENGTH];
_reserved = new unsigned char[RESERVED_LENGTH];
_infoHash = new unsigned char[INFO_HASH_LENGTH];
_peerId = new unsigned char[PEER_ID_LENGTH];
memcpy(_pstr, BT_PSTR, PSTR_LENGTH);
memset(_reserved, 0, RESERVED_LENGTH);
pstrlen_ = 19;
pstr_ = new unsigned char[PSTR_LENGTH];
reserved_ = new unsigned char[RESERVED_LENGTH];
infoHash_ = new unsigned char[INFO_HASH_LENGTH];
peerId_ = new unsigned char[PEER_ID_LENGTH];
memcpy(pstr_, BT_PSTR, PSTR_LENGTH);
memset(reserved_, 0, RESERVED_LENGTH);
// fast extension
_reserved[7] |= 0x04;
reserved_[7] |= 0x04;
// extended messaging
_reserved[5] |= 0x10;
reserved_[5] |= 0x10;
}
SharedHandle<BtHandshakeMessage>
BtHandshakeMessage::create(const unsigned char* data, size_t dataLength)
{
SharedHandle<BtHandshakeMessage> message(new BtHandshakeMessage());
message->_pstrlen = data[0];
memcpy(message->_pstr, &data[1], PSTR_LENGTH);
memcpy(message->_reserved, &data[20], RESERVED_LENGTH);
memcpy(message->_infoHash, &data[28], INFO_HASH_LENGTH);
memcpy(message->_peerId, &data[48], PEER_ID_LENGTH);
message->pstrlen_ = data[0];
memcpy(message->pstr_, &data[1], PSTR_LENGTH);
memcpy(message->reserved_, &data[20], RESERVED_LENGTH);
memcpy(message->infoHash_, &data[28], INFO_HASH_LENGTH);
memcpy(message->peerId_, &data[48], PEER_ID_LENGTH);
return message;
}
unsigned char* BtHandshakeMessage::createMessage()
{
unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
msg[0] = _pstrlen;
memcpy(msg+1, _pstr, PSTR_LENGTH);
memcpy(msg+20, _reserved, RESERVED_LENGTH);
memcpy(msg+28, _infoHash, INFO_HASH_LENGTH);
memcpy(msg+48, _peerId, PEER_ID_LENGTH);
msg[0] = pstrlen_;
memcpy(msg+1, pstr_, PSTR_LENGTH);
memcpy(msg+20, reserved_, RESERVED_LENGTH);
memcpy(msg+28, infoHash_, INFO_HASH_LENGTH);
memcpy(msg+48, peerId_, PEER_ID_LENGTH);
return msg;
}
@ -104,33 +104,33 @@ size_t BtHandshakeMessage::getMessageLength() {
std::string BtHandshakeMessage::toString() const {
return strconcat(NAME, " peerId=",
util::percentEncode(_peerId, PEER_ID_LENGTH),
util::percentEncode(peerId_, PEER_ID_LENGTH),
", reserved=",
util::toHex(_reserved, RESERVED_LENGTH));
util::toHex(reserved_, RESERVED_LENGTH));
}
bool BtHandshakeMessage::isFastExtensionSupported() const {
return _reserved[7]&0x04;
return reserved_[7]&0x04;
}
bool BtHandshakeMessage::isExtendedMessagingEnabled() const
{
return _reserved[5]&0x10;
return reserved_[5]&0x10;
}
bool BtHandshakeMessage::isDHTEnabled() const
{
return _reserved[7]&0x01;
return reserved_[7]&0x01;
}
void BtHandshakeMessage::setInfoHash(const unsigned char* infoHash)
{
memcpy(_infoHash, infoHash, INFO_HASH_LENGTH);
memcpy(infoHash_, infoHash, INFO_HASH_LENGTH);
}
void BtHandshakeMessage::setPeerId(const unsigned char* peerId)
{
memcpy(_peerId, peerId, PEER_ID_LENGTH);
memcpy(peerId_, peerId, PEER_ID_LENGTH);
}
} // namespace aria2

View File

@ -46,11 +46,11 @@ public:
static const size_t RESERVED_LENGTH = 8;
static const size_t MESSAGE_LENGTH = 68;
private:
uint8_t _pstrlen;
unsigned char* _pstr;
unsigned char* _reserved;
unsigned char* _infoHash;
unsigned char* _peerId;
uint8_t pstrlen_;
unsigned char* pstr_;
unsigned char* reserved_;
unsigned char* infoHash_;
unsigned char* peerId_;
void init();
public:
BtHandshakeMessage();
@ -64,10 +64,10 @@ public:
create(const unsigned char* data, size_t dataLength);
virtual ~BtHandshakeMessage() {
delete [] _pstr;
delete [] _reserved;
delete [] _infoHash;
delete [] _peerId;
delete [] pstr_;
delete [] reserved_;
delete [] infoHash_;
delete [] peerId_;
}
static const uint8_t ID = INT8_MAX;
@ -91,32 +91,32 @@ public:
void setDHTEnabled(bool enabled)
{
if(enabled) {
_reserved[7] |= 0x01;
reserved_[7] |= 0x01;
} else {
_reserved[7] &= ~0x01;
reserved_[7] &= ~0x01;
}
}
uint8_t getPstrlen() const {
return _pstrlen;
return pstrlen_;
}
const unsigned char* getPstr() const {
return _pstr;
return pstr_;
}
const unsigned char* getReserved() const {
return _reserved;
return reserved_;
}
const unsigned char* getInfoHash() const {
return _infoHash;
return infoHash_;
}
void setInfoHash(const unsigned char* infoHash);
const unsigned char* getPeerId() const {
return _peerId;
return peerId_;
}
void setPeerId(const unsigned char* peerId);

View File

@ -48,33 +48,33 @@ namespace aria2 {
class BtHandshakeMessageValidator : public BtMessageValidator {
private:
const BtHandshakeMessage* _message;
unsigned char _infoHash[INFO_HASH_LENGTH];
const BtHandshakeMessage* message_;
unsigned char infoHash_[INFO_HASH_LENGTH];
public:
BtHandshakeMessageValidator(const BtHandshakeMessage* message,
const unsigned char* infoHash):
_message(message)
message_(message)
{
memcpy(_infoHash, infoHash, sizeof(_infoHash));
memcpy(infoHash_, infoHash, sizeof(infoHash_));
}
virtual void validate()
{
if(_message->getPstrlen() != 19) {
if(message_->getPstrlen() != 19) {
throw DL_ABORT_EX(StringFormat("invalid handshake pstrlen=%u",
_message->getPstrlen()).str());
message_->getPstrlen()).str());
}
if(memcmp(BtHandshakeMessage::BT_PSTR, _message->getPstr(), 19) != 0) {
if(memcmp(BtHandshakeMessage::BT_PSTR, message_->getPstr(), 19) != 0) {
throw DL_ABORT_EX
(StringFormat("invalid handshake pstr=%s",
util::percentEncode
(_message->getPstr(), 19).c_str()).str());
(message_->getPstr(), 19).c_str()).str());
}
if(memcmp(_infoHash, _message->getInfoHash(), sizeof(_infoHash)) != 0) {
if(memcmp(infoHash_, message_->getInfoHash(), sizeof(infoHash_)) != 0) {
throw DL_ABORT_EX
(StringFormat("invalid handshake info hash: expected:%s, actual:%s",
util::toHex(_infoHash, sizeof(_infoHash)).c_str(),
util::toHex(_message->getInfoHash(),
util::toHex(infoHash_, sizeof(infoHash_)).c_str(),
util::toHex(message_->getInfoHash(),
INFO_HASH_LENGTH).c_str()).str());
}
}

View File

@ -55,7 +55,7 @@ void BtInterestedMessage::doReceivedAction()
}
getPeer()->peerInterested(true);
if(!getPeer()->amChoking()) {
_peerStorage->executeChoke();
peerStorage_->executeChoke();
}
}
@ -71,7 +71,7 @@ void BtInterestedMessage::onSendComplete() {
void BtInterestedMessage::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
peerStorage_ = peerStorage;
}
} // namespace aria2

View File

@ -46,7 +46,7 @@ typedef SharedHandle<BtInterestedMessage> BtInterestedMessageHandle;
class BtInterestedMessage : public ZeroBtMessage {
private:
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PeerStorage> peerStorage_;
public:
BtInterestedMessage();

View File

@ -45,77 +45,77 @@
namespace aria2 {
BtLeecherStateChoke::BtLeecherStateChoke():
_round(0),
_lastRound(0),
_logger(LogFactory::getInstance()) {}
round_(0),
lastRound_(0),
logger_(LogFactory::getInstance()) {}
BtLeecherStateChoke::~BtLeecherStateChoke() {}
BtLeecherStateChoke::PeerEntry::PeerEntry(const SharedHandle<Peer>& peer):
_peer(peer), _downloadSpeed(peer->calculateDownloadSpeed()),
peer_(peer), downloadSpeed_(peer->calculateDownloadSpeed()),
// peer must be interested to us and sent block in the last 30 seconds
_regularUnchoker
regularUnchoker_
(peer->peerInterested() &&
peer->getLastDownloadUpdate().difference(global::wallclock) < 30) {}
const SharedHandle<Peer>& BtLeecherStateChoke::PeerEntry::getPeer() const
{
return _peer;
return peer_;
}
unsigned int BtLeecherStateChoke::PeerEntry::getDownloadSpeed() const
{
return _downloadSpeed;
return downloadSpeed_;
}
bool BtLeecherStateChoke::PeerEntry::isRegularUnchoker() const
{
return _regularUnchoker;
return regularUnchoker_;
}
void BtLeecherStateChoke::PeerEntry::enableChokingRequired()
{
_peer->chokingRequired(true);
peer_->chokingRequired(true);
}
void BtLeecherStateChoke::PeerEntry::disableChokingRequired()
{
_peer->chokingRequired(false);
peer_->chokingRequired(false);
}
void BtLeecherStateChoke::PeerEntry::enableOptUnchoking()
{
_peer->optUnchoking(true);
peer_->optUnchoking(true);
}
void BtLeecherStateChoke::PeerEntry::disableOptUnchoking()
{
_peer->optUnchoking(false);
peer_->optUnchoking(false);
}
bool BtLeecherStateChoke::PeerEntry::isSnubbing() const
{
return _peer->snubbing();
return peer_->snubbing();
}
bool BtLeecherStateChoke::PeerEntry::operator<(const PeerEntry& peerEntry) const
{
return _downloadSpeed > peerEntry._downloadSpeed;
return downloadSpeed_ > peerEntry.downloadSpeed_;
}
class PeerFilter {
private:
bool _amChoking;
bool _peerInterested;
bool amChoking_;
bool peerInterested_;
public:
PeerFilter(bool amChoking, bool peerInterested):
_amChoking(amChoking),
_peerInterested(peerInterested) {}
amChoking_(amChoking),
peerInterested_(peerInterested) {}
bool operator()(const BtLeecherStateChoke::PeerEntry& peerEntry) const
{
return peerEntry.getPeer()->amChoking() == _amChoking &&
peerEntry.getPeer()->peerInterested() == _peerInterested;
return peerEntry.getPeer()->amChoking() == amChoking_ &&
peerEntry.getPeer()->peerInterested() == peerInterested_;
}
};
@ -132,7 +132,7 @@ void BtLeecherStateChoke::plannedOptimisticUnchoke
std::random_shuffle(peerEntries.begin(), i,
*(SimpleRandomizer::getInstance().get()));
(*peerEntries.begin()).enableOptUnchoking();
_logger->info
logger_->info
("POU: %s", (*peerEntries.begin()).getPeer()->getIPAddress().c_str());
}
}
@ -152,7 +152,7 @@ void BtLeecherStateChoke::regularUnchoke(std::vector<PeerEntry>& peerEntries)
std::vector<PeerEntry>::iterator peerIter = peerEntries.begin();
for(;peerIter != rest && count; ++peerIter, --count) {
(*peerIter).disableChokingRequired();
_logger->info("RU: %s, dlspd=%u",
logger_->info("RU: %s, dlspd=%u",
(*peerIter).getPeer()->getIPAddress().c_str(),
(*peerIter).getDownloadSpeed());
if((*peerIter).getPeer()->optUnchoking()) {
@ -167,11 +167,11 @@ void BtLeecherStateChoke::regularUnchoke(std::vector<PeerEntry>& peerEntries)
eoi = peerEntries.end(); i != eoi; ++i) {
if((*i).getPeer()->peerInterested()) {
(*i).enableOptUnchoking();
_logger->info("OU: %s", (*i).getPeer()->getIPAddress().c_str());
logger_->info("OU: %s", (*i).getPeer()->getIPAddress().c_str());
break;
} else {
(*i).disableChokingRequired();
_logger->info("OU: %s", (*i).getPeer()->getIPAddress().c_str());
logger_->info("OU: %s", (*i).getPeer()->getIPAddress().c_str());
}
}
}
@ -190,8 +190,8 @@ void
BtLeecherStateChoke::executeChoke
(const std::vector<SharedHandle<Peer> >& peerSet)
{
_logger->info("Leecher state, %d choke round started", _round);
_lastRound = global::wallclock;
logger_->info("Leecher state, %d choke round started", round_);
lastRound_ = global::wallclock;
std::vector<PeerEntry> peerEntries;
std::transform(peerSet.begin(), peerSet.end(),
@ -206,19 +206,19 @@ BtLeecherStateChoke::executeChoke
std::mem_fun_ref(&PeerEntry::enableChokingRequired));
// planned optimistic unchoke
if(_round == 0) {
if(round_ == 0) {
plannedOptimisticUnchoke(peerEntries);
}
regularUnchoke(peerEntries);
if(++_round == 3) {
_round = 0;
if(++round_ == 3) {
round_ = 0;
}
}
const Timer& BtLeecherStateChoke::getLastRound() const
{
return _lastRound;
return lastRound_;
}
} // namespace aria2

View File

@ -49,17 +49,17 @@ class Logger;
class BtLeecherStateChoke {
private:
int _round;
int round_;
Timer _lastRound;
Timer lastRound_;
Logger* _logger;
Logger* logger_;
class PeerEntry {
private:
SharedHandle<Peer> _peer;
unsigned int _downloadSpeed;
bool _regularUnchoker;
SharedHandle<Peer> peer_;
unsigned int downloadSpeed_;
bool regularUnchoker_;
public:
PeerEntry(const SharedHandle<Peer>& peer);

View File

@ -50,9 +50,9 @@ class BtEvent;
class BtMessage {
private:
uint8_t _id;
uint8_t id_;
public:
BtMessage(uint8_t id):_id(id) {}
BtMessage(uint8_t id):id_(id) {}
virtual ~BtMessage() {}
@ -62,7 +62,7 @@ public:
virtual bool isUploading() = 0;
uint8_t getId() { return _id; }
uint8_t getId() { return id_; }
virtual void doReceivedAction() = 0;

View File

@ -55,7 +55,7 @@ void BtNotInterestedMessage::doReceivedAction()
}
getPeer()->peerInterested(false);
if(!getPeer()->amChoking()) {
_peerStorage->executeChoke();
peerStorage_->executeChoke();
}
}
@ -71,7 +71,7 @@ void BtNotInterestedMessage::onSendComplete() {
void BtNotInterestedMessage::setPeerStorage
(const SharedHandle<PeerStorage>& peerStorage)
{
_peerStorage = peerStorage;
peerStorage_ = peerStorage;
}
} // namespace aria2

View File

@ -46,7 +46,7 @@ typedef SharedHandle<BtNotInterestedMessage> BtNotInterestedMessageHandle;
class BtNotInterestedMessage : public ZeroBtMessage {
private:
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<PeerStorage> peerStorage_;
public:
BtNotInterestedMessage();

View File

@ -62,25 +62,25 @@ const std::string BtPieceMessage::NAME("piece");
BtPieceMessage::BtPieceMessage
(size_t index, uint32_t begin, size_t blockLength):
AbstractBtMessage(ID, NAME),
_index(index),
_begin(begin),
_blockLength(blockLength),
_block(0),
_rawData(0)
index_(index),
begin_(begin),
blockLength_(blockLength),
block_(0),
rawData_(0)
{
setUploading(true);
}
BtPieceMessage::~BtPieceMessage()
{
delete [] _rawData;
delete [] rawData_;
}
void BtPieceMessage::setRawMessage(unsigned char* data)
{
delete [] _rawData;
_rawData = data;
_block = data+9;
delete [] rawData_;
rawData_ = data;
block_ = data+9;
}
BtPieceMessageHandle BtPieceMessage::create
@ -101,27 +101,27 @@ void BtPieceMessage::doReceivedAction()
return;
}
RequestSlot slot = getBtMessageDispatcher()->getOutstandingRequest
(_index, _begin, _blockLength);
getPeer()->updateDownloadLength(_blockLength);
(index_, begin_, blockLength_);
getPeer()->updateDownloadLength(blockLength_);
if(!RequestSlot::isNull(slot)) {
getPeer()->snubbing(false);
SharedHandle<Piece> piece = getPieceStorage()->getPiece(_index);
off_t offset = (off_t)_index*_downloadContext->getPieceLength()+_begin;
SharedHandle<Piece> piece = getPieceStorage()->getPiece(index_);
off_t offset = (off_t)index_*downloadContext_->getPieceLength()+begin_;
if(getLogger()->debug()) {
getLogger()->debug(MSG_PIECE_RECEIVED,
util::itos(getCuid()).c_str(),
_index, _begin, _blockLength, offset,
index_, begin_, blockLength_, offset,
slot.getBlockIndex());
}
getPieceStorage()->getDiskAdaptor()->writeData
(_block, _blockLength, offset);
(block_, blockLength_, offset);
piece->completeBlock(slot.getBlockIndex());
if(getLogger()->debug()) {
getLogger()->debug(MSG_PIECE_BITFIELD, util::itos(getCuid()).c_str(),
util::toHex(piece->getBitfield(),
piece->getBitfieldLength()).c_str());
}
piece->updateHash(_begin, _block, _blockLength);
piece->updateHash(begin_, block_, blockLength_);
getBtMessageDispatcher()->removeOutstandingRequest(slot);
if(piece->pieceComplete()) {
if(checkPieceHash(piece)) {
@ -133,7 +133,7 @@ void BtPieceMessage::doReceivedAction()
} else {
if(getLogger()->debug()) {
getLogger()->debug("CUID#%s - RequestSlot not found, index=%d, begin=%d",
util::itos(getCuid()).c_str(), _index, _begin);
util::itos(getCuid()).c_str(), index_, begin_);
}
}
}
@ -151,9 +151,9 @@ unsigned char* BtPieceMessage::createMessageHeader()
*/
unsigned char* msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
9+_blockLength, ID);
bittorrent::setIntParam(&msgHeader[5], _index);
bittorrent::setIntParam(&msgHeader[9], _begin);
9+blockLength_, ID);
bittorrent::setIntParam(&msgHeader[5], index_);
bittorrent::setIntParam(&msgHeader[9], begin_);
return msgHeader;
}
@ -180,13 +180,13 @@ void BtPieceMessage::send()
size_t msgHdrLen = getMessageHeaderLength();
if(getLogger()->debug()) {
getLogger()->debug("msglength = %lu bytes",
static_cast<unsigned long>(msgHdrLen+_blockLength));
static_cast<unsigned long>(msgHdrLen+blockLength_));
}
getPeerConnection()->pushBytes(msgHdr, msgHdrLen);
getPeerConnection()->sendPendingData();
off_t pieceDataOffset =
(off_t)_index*_downloadContext->getPieceLength()+_begin;
writtenLength = sendPieceData(pieceDataOffset, _blockLength);
(off_t)index_*downloadContext_->getPieceLength()+begin_;
writtenLength = sendPieceData(pieceDataOffset, blockLength_);
} else {
writtenLength = getPeerConnection()->sendPendingData();
}
@ -215,8 +215,8 @@ size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const
std::string BtPieceMessage::toString() const
{
return strconcat(NAME, " index=", util::itos(_index), ", begin=",
util::itos(_begin), ", length=", util::itos(_blockLength));
return strconcat(NAME, " index=", util::itos(index_), ", begin=",
util::itos(begin_), ", length=", util::itos(blockLength_));
}
bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece)
@ -227,13 +227,13 @@ bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece)
static_cast<unsigned long>(piece->getIndex()));
}
return
piece->getHashString()==_downloadContext->getPieceHash(piece->getIndex());
piece->getHashString()==downloadContext_->getPieceHash(piece->getIndex());
} else {
off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
return MessageDigestHelper::staticSHA1Digest
(getPieceStorage()->getDiskAdaptor(), offset, piece->getLength())
== _downloadContext->getPieceHash(piece->getIndex());
== downloadContext_->getPieceHash(piece->getIndex());
}
}
@ -264,7 +264,7 @@ void BtPieceMessage::erasePieceOnDisk(const SharedHandle<Piece>& piece)
size_t BUFSIZE = 4096;
unsigned char buf[BUFSIZE];
memset(buf, 0, BUFSIZE);
off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
div_t res = div(piece->getLength(), BUFSIZE);
for(int i = 0; i < res.quot; ++i) {
getPieceStorage()->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
@ -279,16 +279,16 @@ void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
{
if(!isInvalidate() &&
!isSendingInProgress() &&
!getPeer()->isInAmAllowedIndexSet(_index)) {
!getPeer()->isInAmAllowedIndexSet(index_)) {
if(getLogger()->debug()) {
getLogger()->debug(MSG_REJECT_PIECE_CHOKED,
util::itos(getCuid()).c_str(),
_index, _begin, _blockLength);
index_, begin_, blockLength_);
}
if(getPeer()->isFastExtensionEnabled()) {
BtMessageHandle rej =
getBtMessageFactory()->createRejectMessage
(_index, _begin, _blockLength);
(index_, begin_, blockLength_);
getBtMessageDispatcher()->addMessageToQueue(rej);
}
setInvalidate(true);
@ -300,18 +300,18 @@ void BtPieceMessage::onCancelSendingPieceEvent
{
if(!isInvalidate() &&
!isSendingInProgress() &&
_index == event.getIndex() &&
_begin == event.getBegin() &&
_blockLength == event.getLength()) {
index_ == event.getIndex() &&
begin_ == event.getBegin() &&
blockLength_ == event.getLength()) {
if(getLogger()->debug()) {
getLogger()->debug(MSG_REJECT_PIECE_CANCEL,
util::itos(getCuid()).c_str(),
_index, _begin, _blockLength);
index_, begin_, blockLength_);
}
if(getPeer()->isFastExtensionEnabled()) {
BtMessageHandle rej =
getBtMessageFactory()->createRejectMessage
(_index, _begin, _blockLength);
(index_, begin_, blockLength_);
getBtMessageDispatcher()->addMessageToQueue(rej);
}
setInvalidate(true);
@ -321,7 +321,7 @@ void BtPieceMessage::onCancelSendingPieceEvent
void BtPieceMessage::setDownloadContext
(const SharedHandle<DownloadContext>& downloadContext)
{
_downloadContext = downloadContext;
downloadContext_ = downloadContext;
}
} // namespace aria2

View File

@ -47,12 +47,12 @@ typedef SharedHandle<BtPieceMessage> BtPieceMessageHandle;
class BtPieceMessage : public AbstractBtMessage {
private:
size_t _index;
uint32_t _begin;
uint32_t _blockLength;
unsigned char* _block;
unsigned char* _rawData;
SharedHandle<DownloadContext> _downloadContext;
size_t index_;
uint32_t begin_;
uint32_t blockLength_;
unsigned char* block_;
unsigned char* rawData_;
SharedHandle<DownloadContext> downloadContext_;
static size_t MESSAGE_HEADER_LENGTH;
@ -74,24 +74,24 @@ public:
static const std::string NAME;
size_t getIndex() const { return _index; }
size_t getIndex() const { return index_; }
void setIndex(size_t index) { _index = index; }
void setIndex(size_t index) { index_ = index; }
uint32_t getBegin() const { return _begin; }
uint32_t getBegin() const { return begin_; }
void setBegin(uint32_t begin) { _begin = begin; }
void setBegin(uint32_t begin) { begin_ = begin; }
const unsigned char* getBlock() const { return _block; }
const unsigned char* getBlock() const { return block_; }
size_t getBlockLength() const { return _blockLength; }
size_t getBlockLength() const { return blockLength_; }
// Stores raw message data. After this function call, this object
// has ownership of data. Caller must not be free or alter data.
// Member block is pointed to block starting position in data.
void setRawMessage(unsigned char* data);
void setBlockLength(size_t blockLength) { _blockLength = blockLength; }
void setBlockLength(size_t blockLength) { blockLength_ = blockLength; }
void setDownloadContext(const SharedHandle<DownloadContext>& downloadContext);

View File

@ -43,21 +43,21 @@ namespace aria2 {
class BtPieceMessageValidator : public BtMessageValidator {
private:
const BtPieceMessage* _message;
size_t _numPiece;
size_t _pieceLength;
const BtPieceMessage* message_;
size_t numPiece_;
size_t pieceLength_;
public:
BtPieceMessageValidator(const BtPieceMessage* message,
size_t numPiece,
size_t pieceLength):
_message(message),
_numPiece(numPiece),
_pieceLength(pieceLength) {}
message_(message),
numPiece_(numPiece),
pieceLength_(pieceLength) {}
virtual void validate()
{
bittorrent::checkIndex(_message->getIndex(), _numPiece);
bittorrent::checkBegin(_message->getBegin(), _pieceLength);
bittorrent::checkIndex(message_->getIndex(), numPiece_);
bittorrent::checkBegin(message_->getBegin(), pieceLength_);
}
};

View File

@ -52,7 +52,7 @@ namespace aria2 {
const std::string BtPortMessage::NAME("port");
BtPortMessage::BtPortMessage(uint16_t port):
SimpleBtMessage(ID, NAME), _port(port) {}
SimpleBtMessage(ID, NAME), port_(port) {}
SharedHandle<BtPortMessage> BtPortMessage::create
(const unsigned char* data, size_t dataLength)
@ -66,8 +66,8 @@ SharedHandle<BtPortMessage> BtPortMessage::create
void BtPortMessage::doReceivedAction()
{
if(!_taskFactory.isNull() && !_taskQueue.isNull()) {
if(_port == 0) {
if(!taskFactory_.isNull() && !taskQueue_.isNull()) {
if(port_ == 0) {
if(getLogger()->debug()) {
getLogger()->debug("Ignored port 0.");
}
@ -77,16 +77,16 @@ void BtPortMessage::doReceivedAction()
// instance created with proper node ID and is added to a routing table.
SharedHandle<DHTNode> node(new DHTNode());
node->setIPAddress(getPeer()->getIPAddress());
node->setPort(_port);
node->setPort(port_);
{
SharedHandle<DHTTask> task = _taskFactory->createPingTask(node);
_taskQueue->addImmediateTask(task);
SharedHandle<DHTTask> task = taskFactory_->createPingTask(node);
taskQueue_->addImmediateTask(task);
}
if(_routingTable->countBucket() == 1) {
if(routingTable_->countBucket() == 1) {
// initiate bootstrap
getLogger()->info("Dispatch node_lookup since too few buckets.");
_taskQueue->addImmediateTask
(_taskFactory->createNodeLookupTask(_localNode->getID()));
taskQueue_->addImmediateTask
(taskFactory_->createNodeLookupTask(localNode_->getID()));
}
} else {
getLogger()->info
@ -104,7 +104,7 @@ unsigned char* BtPortMessage::createMessage()
*/
unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
bittorrent::createPeerMessageString(msg, MESSAGE_LENGTH, 3, ID);
bittorrent::setShortIntParam(&msg[5], _port);
bittorrent::setShortIntParam(&msg[5], port_);
return msg;
}
@ -113,27 +113,27 @@ size_t BtPortMessage::getMessageLength() {
}
std::string BtPortMessage::toString() const {
return strconcat(NAME, " port=", util::uitos(_port));
return strconcat(NAME, " port=", util::uitos(port_));
}
void BtPortMessage::setLocalNode(const WeakHandle<DHTNode>& localNode)
{
_localNode = localNode;
localNode_ = localNode;
}
void BtPortMessage::setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable)
{
_routingTable = routingTable;
routingTable_ = routingTable;
}
void BtPortMessage::setTaskQueue(const WeakHandle<DHTTaskQueue>& taskQueue)
{
_taskQueue = taskQueue;
taskQueue_ = taskQueue;
}
void BtPortMessage::setTaskFactory(const WeakHandle<DHTTaskFactory>& taskFactory)
{
_taskFactory = taskFactory;
taskFactory_ = taskFactory;
}
} // namespace aria2

View File

@ -46,16 +46,16 @@ class DHTTaskFactory;
class BtPortMessage : public SimpleBtMessage {
private:
uint16_t _port;
uint16_t port_;
static const size_t MESSAGE_LENGTH = 7;
WeakHandle<DHTNode> _localNode;
WeakHandle<DHTNode> localNode_;
WeakHandle<DHTRoutingTable> _routingTable;
WeakHandle<DHTRoutingTable> routingTable_;
WeakHandle<DHTTaskQueue> _taskQueue;
WeakHandle<DHTTaskQueue> taskQueue_;
WeakHandle<DHTTaskFactory> _taskFactory;
WeakHandle<DHTTaskFactory> taskFactory_;
public:
BtPortMessage(uint16_t port);
@ -63,7 +63,7 @@ public:
static const std::string NAME;
uint16_t getPort() const { return _port; }
uint16_t getPort() const { return port_; }
static SharedHandle<BtPortMessage> create
(const unsigned char* data, size_t dataLength);

View File

@ -47,18 +47,18 @@ namespace aria2 {
SharedHandle<DownloadContext>
BtRegistry::getDownloadContext(gid_t gid) const
{
return get(gid)._downloadContext;
return get(gid).downloadContext_;
}
SharedHandle<DownloadContext>
BtRegistry::getDownloadContext(const std::string& infoHash) const
{
SharedHandle<DownloadContext> dctx;
for(std::map<gid_t, BtObject>::const_iterator i = _pool.begin(),
eoi = _pool.end(); i != eoi; ++i) {
if(bittorrent::getTorrentAttrs((*i).second._downloadContext)->infoHash ==
for(std::map<gid_t, BtObject>::const_iterator i = pool_.begin(),
eoi = pool_.end(); i != eoi; ++i) {
if(bittorrent::getTorrentAttrs((*i).second.downloadContext_)->infoHash ==
infoHash) {
dctx = (*i).second._downloadContext;
dctx = (*i).second.downloadContext_;
break;
}
}
@ -67,13 +67,13 @@ BtRegistry::getDownloadContext(const std::string& infoHash) const
void BtRegistry::put(gid_t gid, const BtObject& obj)
{
_pool[gid] = obj;
pool_[gid] = obj;
}
BtObject BtRegistry::get(gid_t gid) const
{
std::map<gid_t, BtObject>::const_iterator i = _pool.find(gid);
if(i == _pool.end()) {
std::map<gid_t, BtObject>::const_iterator i = pool_.find(gid);
if(i == pool_.end()) {
return BtObject();
} else {
return (*i).second;
@ -82,11 +82,11 @@ BtObject BtRegistry::get(gid_t gid) const
bool BtRegistry::remove(gid_t gid)
{
return _pool.erase(gid);
return pool_.erase(gid);
}
void BtRegistry::removeAll() {
_pool.clear();
pool_.clear();
}
} // namespace aria2

View File

@ -52,12 +52,12 @@ class BtProgressInfoFile;
class DownloadContext;
struct BtObject {
SharedHandle<DownloadContext> _downloadContext;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PeerStorage> _peerStorage;
SharedHandle<BtAnnounce> _btAnnounce;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<BtProgressInfoFile> _btProgressInfoFile;
SharedHandle<DownloadContext> downloadContext_;
SharedHandle<PieceStorage> pieceStorage_;
SharedHandle<PeerStorage> peerStorage_;
SharedHandle<BtAnnounce> btAnnounce_;
SharedHandle<BtRuntime> btRuntime_;
SharedHandle<BtProgressInfoFile> btProgressInfoFile_;
BtObject(const SharedHandle<DownloadContext>& downloadContext,
const SharedHandle<PieceStorage>& pieceStorage,
@ -65,29 +65,29 @@ struct BtObject {
const SharedHandle<BtAnnounce>& btAnnounce,
const SharedHandle<BtRuntime>& btRuntime,
const SharedHandle<BtProgressInfoFile>& btProgressInfoFile):
_downloadContext(downloadContext),
_pieceStorage(pieceStorage),
_peerStorage(peerStorage),
_btAnnounce(btAnnounce),
_btRuntime(btRuntime),
_btProgressInfoFile(btProgressInfoFile) {}
downloadContext_(downloadContext),
pieceStorage_(pieceStorage),
peerStorage_(peerStorage),
btAnnounce_(btAnnounce),
btRuntime_(btRuntime),
btProgressInfoFile_(btProgressInfoFile) {}
BtObject() {}
bool isNull() const
{
return _downloadContext.isNull() &&
_pieceStorage.isNull() &&
_peerStorage.isNull() &&
_btAnnounce.isNull() &&
_btRuntime.isNull() &&
_btProgressInfoFile.isNull();
return downloadContext_.isNull() &&
pieceStorage_.isNull() &&
peerStorage_.isNull() &&
btAnnounce_.isNull() &&
btRuntime_.isNull() &&
btProgressInfoFile_.isNull();
}
};
class BtRegistry {
private:
std::map<gid_t, BtObject> _pool;
std::map<gid_t, BtObject> pool_;
public:
SharedHandle<DownloadContext>
getDownloadContext(gid_t gid) const;
@ -102,9 +102,9 @@ public:
template<typename OutputIterator>
OutputIterator getAllDownloadContext(OutputIterator dest)
{
for(std::map<gid_t, BtObject>::const_iterator i = _pool.begin(),
eoi = _pool.end(); i != eoi; ++i) {
*dest++ = (*i).second._downloadContext;
for(std::map<gid_t, BtObject>::const_iterator i = pool_.begin(),
eoi = pool_.end(); i != eoi; ++i) {
*dest++ = (*i).second.downloadContext_;
}
return dest;
}

View File

@ -46,7 +46,7 @@ const std::string BtRequestMessage::NAME("request");
BtRequestMessage::BtRequestMessage
(size_t index, uint32_t begin, uint32_t length, size_t blockIndex):
RangeBtMessage(ID, NAME, index, begin, length),
_blockIndex(blockIndex) {}
blockIndex_(blockIndex) {}
SharedHandle<BtRequestMessage> BtRequestMessage::create
(const unsigned char* data, size_t dataLength)
@ -79,7 +79,7 @@ void BtRequestMessage::doReceivedAction()
void BtRequestMessage::onQueued()
{
RequestSlot requestSlot(getIndex(), getBegin(), getLength(), _blockIndex,
RequestSlot requestSlot(getIndex(), getBegin(), getLength(), blockIndex_,
getPieceStorage()->getPiece(getIndex()));
getBtMessageDispatcher()->addOutstandingRequest(requestSlot);
}

View File

@ -45,7 +45,7 @@ typedef SharedHandle<BtRequestMessage> BtRequestMessageHandle;
class BtRequestMessage : public RangeBtMessage {
private:
size_t _blockIndex;
size_t blockIndex_;
public:
BtRequestMessage(size_t index = 0,
uint32_t begin = 0,
@ -56,8 +56,8 @@ public:
static const std::string NAME;
size_t getBlockIndex() const { return _blockIndex; }
void setBlockIndex(size_t blockIndex) { _blockIndex = blockIndex; }
size_t getBlockIndex() const { return blockIndex_; }
void setBlockIndex(size_t blockIndex) { blockIndex_ = blockIndex; }
static SharedHandle<BtRequestMessage> create
(const unsigned char* data, size_t dataLength);

View File

@ -42,90 +42,90 @@ namespace aria2 {
class BtRuntime {
private:
uint64_t _uploadLengthAtStartup;
uint16_t _port;
bool _halt;
unsigned int _connections;
bool _ready;
uint64_t uploadLengthAtStartup_;
uint16_t port_;
bool halt_;
unsigned int connections_;
bool ready_;
// Maximum number of peers to hold connections at the same time.
// 0 means unlimited.
unsigned int _maxPeers;
unsigned int maxPeers_;
// Minimum number of peers. This value is used for getting more peers from
// tracker. 0 means always the number of peers is under minimum.
unsigned int _minPeers;
unsigned int minPeers_;
static const unsigned int DEFAULT_MIN_PEERS = 40;
public:
BtRuntime():
_uploadLengthAtStartup(0),
_port(0),
_halt(false),
_connections(0),
_ready(false),
_maxPeers(DEFAULT_MAX_PEERS),
_minPeers(DEFAULT_MIN_PEERS)
uploadLengthAtStartup_(0),
port_(0),
halt_(false),
connections_(0),
ready_(false),
maxPeers_(DEFAULT_MAX_PEERS),
minPeers_(DEFAULT_MIN_PEERS)
{}
~BtRuntime() {}
uint64_t getUploadLengthAtStartup() const {
return _uploadLengthAtStartup;
return uploadLengthAtStartup_;
}
void setUploadLengthAtStartup(uint64_t length) {
_uploadLengthAtStartup = length;
uploadLengthAtStartup_ = length;
}
void setListenPort(uint16_t port) {
_port = port;
port_ = port;
}
uint16_t getListenPort() const { return _port; }
uint16_t getListenPort() const { return port_; }
bool isHalt() const { return _halt; }
bool isHalt() const { return halt_; }
void setHalt(bool halt) {
_halt = halt;
halt_ = halt;
}
unsigned int getConnections() const { return _connections; }
unsigned int getConnections() const { return connections_; }
void increaseConnections() { ++_connections; }
void increaseConnections() { ++connections_; }
void decreaseConnections() { --_connections; }
void decreaseConnections() { --connections_; }
bool lessThanMaxPeers() const
{
return _maxPeers == 0 || _connections < _maxPeers;
return maxPeers_ == 0 || connections_ < maxPeers_;
}
bool lessThanMinPeers() const
{
return _minPeers == 0 || _connections < _minPeers;
return minPeers_ == 0 || connections_ < minPeers_;
}
bool lessThanEqMinPeers() const
{
return _minPeers == 0 || _connections <= _minPeers;
return minPeers_ == 0 || connections_ <= minPeers_;
}
bool ready() { return _ready; }
bool ready() { return ready_; }
void setReady(bool go) { _ready = go; }
void setReady(bool go) { ready_ = go; }
void setMaxPeers(unsigned int maxPeers)
{
_maxPeers = maxPeers;
_minPeers = static_cast<unsigned int>(maxPeers*0.8);
if(_minPeers == 0 && maxPeers != 0) {
_minPeers = maxPeers;
maxPeers_ = maxPeers;
minPeers_ = static_cast<unsigned int>(maxPeers*0.8);
if(minPeers_ == 0 && maxPeers != 0) {
minPeers_ = maxPeers;
}
}
unsigned int getMaxPeers() const
{
return _maxPeers;
return maxPeers_;
}
static const unsigned int DEFAULT_MAX_PEERS = 55;

View File

@ -45,48 +45,48 @@
namespace aria2 {
BtSeederStateChoke::BtSeederStateChoke():
_round(0),
_lastRound(0),
_logger(LogFactory::getInstance()) {}
round_(0),
lastRound_(0),
logger_(LogFactory::getInstance()) {}
BtSeederStateChoke::~BtSeederStateChoke() {}
BtSeederStateChoke::PeerEntry::PeerEntry
(const SharedHandle<Peer>& peer):
_peer(peer),
_outstandingUpload(peer->countOutstandingUpload()),
_lastAmUnchoking(peer->getLastAmUnchoking()),
_recentUnchoking(_lastAmUnchoking.difference(global::wallclock) < TIME_FRAME),
_uploadSpeed(peer->calculateUploadSpeed())
peer_(peer),
outstandingUpload_(peer->countOutstandingUpload()),
lastAmUnchoking_(peer->getLastAmUnchoking()),
recentUnchoking_(lastAmUnchoking_.difference(global::wallclock) < TIME_FRAME),
uploadSpeed_(peer->calculateUploadSpeed())
{}
bool
BtSeederStateChoke::PeerEntry::operator<(const PeerEntry& rhs) const
{
if(this->_outstandingUpload && !rhs._outstandingUpload) {
if(this->outstandingUpload_ && !rhs.outstandingUpload_) {
return true;
} else if(!this->_outstandingUpload && rhs._outstandingUpload) {
} else if(!this->outstandingUpload_ && rhs.outstandingUpload_) {
return false;
}
if(this->_recentUnchoking &&
(this->_lastAmUnchoking > rhs._lastAmUnchoking)) {
if(this->recentUnchoking_ &&
(this->lastAmUnchoking_ > rhs.lastAmUnchoking_)) {
return true;
} else if(rhs._recentUnchoking) {
} else if(rhs.recentUnchoking_) {
return false;
} else {
return this->_uploadSpeed > rhs._uploadSpeed;
return this->uploadSpeed_ > rhs.uploadSpeed_;
}
}
void BtSeederStateChoke::PeerEntry::disableOptUnchoking()
{
_peer->optUnchoking(false);
peer_->optUnchoking(false);
}
void BtSeederStateChoke::unchoke
(std::vector<BtSeederStateChoke::PeerEntry>& peers)
{
int count = (_round == 2) ? 4 : 3;
int count = (round_ == 2) ? 4 : 3;
std::sort(peers.begin(), peers.end());
@ -94,18 +94,18 @@ void BtSeederStateChoke::unchoke
for(std::vector<PeerEntry>::iterator eoi = peers.end();
r != eoi && count; ++r, --count) {
(*r).getPeer()->chokingRequired(false);
_logger->info("RU: %s, ulspd=%u", (*r).getPeer()->getIPAddress().c_str(),
logger_->info("RU: %s, ulspd=%u", (*r).getPeer()->getIPAddress().c_str(),
(*r).getUploadSpeed());
}
if(_round < 2) {
if(round_ < 2) {
std::for_each(peers.begin(), peers.end(),
std::mem_fun_ref(&PeerEntry::disableOptUnchoking));
if(r != peers.end()) {
std::random_shuffle(r, peers.end(),
*(SimpleRandomizer::getInstance().get()));
(*r).getPeer()->optUnchoking(true);
_logger->info("POU: %s", (*r).getPeer()->getIPAddress().c_str());
logger_->info("POU: %s", (*r).getPeer()->getIPAddress().c_str());
}
}
}
@ -138,8 +138,8 @@ void
BtSeederStateChoke::executeChoke
(const std::vector<SharedHandle<Peer> >& peerSet)
{
_logger->info("Seeder state, %d choke round started", _round);
_lastRound = global::wallclock;
logger_->info("Seeder state, %d choke round started", round_);
lastRound_ = global::wallclock;
std::vector<PeerEntry> peerEntries;
@ -154,8 +154,8 @@ BtSeederStateChoke::executeChoke
unchoke(peerEntries);
if(++_round == 3) {
_round = 0;
if(++round_ == 3) {
round_ = 0;
}
}

View File

@ -49,19 +49,19 @@ class Logger;
class BtSeederStateChoke {
private:
int _round;
int round_;
Timer _lastRound;
Timer lastRound_;
Logger* _logger;
Logger* logger_;
class PeerEntry {
private:
SharedHandle<Peer> _peer;
size_t _outstandingUpload;
Timer _lastAmUnchoking;
bool _recentUnchoking;
unsigned int _uploadSpeed;
SharedHandle<Peer> peer_;
size_t outstandingUpload_;
Timer lastAmUnchoking_;
bool recentUnchoking_;
unsigned int uploadSpeed_;
const static time_t TIME_FRAME = 20;
public:
@ -69,9 +69,9 @@ private:
bool operator<(const PeerEntry& rhs) const;
const SharedHandle<Peer>& getPeer() const { return _peer; }
const SharedHandle<Peer>& getPeer() const { return peer_; }
unsigned int getUploadSpeed() const { return _uploadSpeed; }
unsigned int getUploadSpeed() const { return uploadSpeed_; }
void disableOptUnchoking();
};
@ -87,7 +87,7 @@ public:
void executeChoke(const std::vector<SharedHandle<Peer> >& peerSet);
const Timer& getLastRound() const { return _lastRound; }
const Timer& getLastRound() const { return lastRound_; }
};
} // namespace aria2

View File

@ -77,7 +77,7 @@
namespace aria2 {
BtSetup::BtSetup():_logger(LogFactory::getInstance()) {}
BtSetup::BtSetup():logger_(LogFactory::getInstance()) {}
void BtSetup::setup(std::vector<Command*>& commands,
RequestGroup* requestGroup,
@ -91,10 +91,10 @@ void BtSetup::setup(std::vector<Command*>& commands,
bittorrent::getTorrentAttrs(requestGroup->getDownloadContext());
bool metadataGetMode = torrentAttrs->metadata.empty();
BtObject btObject = e->getBtRegistry()->get(requestGroup->getGID());
SharedHandle<PieceStorage> pieceStorage = btObject._pieceStorage;
SharedHandle<PeerStorage> peerStorage = btObject._peerStorage;
SharedHandle<BtRuntime> btRuntime = btObject._btRuntime;
SharedHandle<BtAnnounce> btAnnounce = btObject._btAnnounce;
SharedHandle<PieceStorage> pieceStorage = btObject.pieceStorage_;
SharedHandle<PeerStorage> peerStorage = btObject.peerStorage_;
SharedHandle<BtRuntime> btRuntime = btObject.btRuntime_;
SharedHandle<BtAnnounce> btAnnounce = btObject.btAnnounce_;
// commands
{
TrackerWatcherCommand* c =
@ -182,7 +182,7 @@ void BtSetup::setup(std::vector<Command*>& commands,
if(option->getAsBool(PREF_BT_ENABLE_LPD) &&
(metadataGetMode || !torrentAttrs->privateTorrent)) {
if(LpdReceiveMessageCommand::getNumInstance() == 0) {
_logger->info("Initializing LpdMessageReceiver.");
logger_->info("Initializing LpdMessageReceiver.");
SharedHandle<LpdMessageReceiver> receiver
(new LpdMessageReceiver(LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT));
bool initialized = false;
@ -206,7 +206,7 @@ void BtSetup::setup(std::vector<Command*>& commands,
}
}
if(initialized) {
_logger->info("LpdMessageReceiver initialized. multicastAddr=%s:%u,"
logger_->info("LpdMessageReceiver initialized. multicastAddr=%s:%u,"
" localAddr=%s",
LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT,
receiver->getLocalAddress().c_str());
@ -214,7 +214,7 @@ void BtSetup::setup(std::vector<Command*>& commands,
LpdReceiveMessageCommand::getInstance(e, receiver);
e->addCommand(cmd);
} else {
_logger->info("LpdMessageReceiver not initialized.");
logger_->info("LpdMessageReceiver not initialized.");
}
}
if(LpdReceiveMessageCommand::getNumInstance()) {
@ -222,20 +222,20 @@ void BtSetup::setup(std::vector<Command*>& commands,
bittorrent::getInfoHash(requestGroup->getDownloadContext());
SharedHandle<LpdMessageReceiver> receiver =
LpdReceiveMessageCommand::getInstance()->getLpdMessageReceiver();
_logger->info("Initializing LpdMessageDispatcher.");
logger_->info("Initializing LpdMessageDispatcher.");
SharedHandle<LpdMessageDispatcher> dispatcher
(new LpdMessageDispatcher
(std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]),
btRuntime->getListenPort(),
LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT));
if(dispatcher->init(receiver->getLocalAddress(), /*ttl*/1, /*loop*/0)) {
_logger->info("LpdMessageDispatcher initialized.");
logger_->info("LpdMessageDispatcher initialized.");
LpdDispatchMessageCommand* cmd =
new LpdDispatchMessageCommand(e->newCUID(), dispatcher, e);
cmd->setBtRuntime(btRuntime);
e->addCommand(cmd);
} else {
_logger->info("LpdMessageDispatcher not initialized.");
logger_->info("LpdMessageDispatcher not initialized.");
}
}
}

View File

@ -48,7 +48,7 @@ class Command;
class BtSetup {
private:
Logger* _logger;
Logger* logger_;
public:
BtSetup();

View File

@ -50,28 +50,28 @@ BtStopDownloadCommand::BtStopDownloadCommand
DownloadEngine* e,
time_t timeout):
TimeBasedCommand(cuid, e, 1),
_requestGroup(requestGroup),
_timeout(timeout)
requestGroup_(requestGroup),
timeout_(timeout)
{}
void BtStopDownloadCommand::preProcess()
{
if(_btRuntime->isHalt() || _pieceStorage->downloadFinished()) {
if(btRuntime_->isHalt() || pieceStorage_->downloadFinished()) {
enableExit();
}
if(_checkPoint.difference(global::wallclock) >= _timeout) {
if(checkPoint_.difference(global::wallclock) >= timeout_) {
getLogger()->notice("GID#%s Stop downloading torrent due to"
" --bt-stop-timeout option.",
util::itos(_requestGroup->getGID()).c_str());
_requestGroup->setHaltRequested(true);
util::itos(requestGroup_->getGID()).c_str());
requestGroup_->setHaltRequested(true);
enableExit();
}
}
void BtStopDownloadCommand::process()
{
if(_requestGroup->calculateStat().getDownloadSpeed() > 0) {
_checkPoint = global::wallclock;
if(requestGroup_->calculateStat().getDownloadSpeed() > 0) {
checkPoint_ = global::wallclock;
}
}

View File

@ -44,19 +44,19 @@ class RequestGroup;
class PieceStorage;
class BtRuntime;
// Stop downloading torrent if in consecutive _timeout seconds,
// Stop downloading torrent if in consecutive timeout_ seconds,
// download speed is zero and the number of seeder is 0.
class BtStopDownloadCommand:public TimeBasedCommand {
private:
RequestGroup* _requestGroup;
RequestGroup* requestGroup_;
time_t _timeout;
time_t timeout_;
Timer _checkPoint;
Timer checkPoint_;
SharedHandle<BtRuntime> _btRuntime;
SharedHandle<BtRuntime> btRuntime_;
SharedHandle<PieceStorage> _pieceStorage;
SharedHandle<PieceStorage> pieceStorage_;
public:
BtStopDownloadCommand
(cuid_t cuid,
@ -70,12 +70,12 @@ public:
void setBtRuntime(const SharedHandle<BtRuntime>& btRuntime)
{
_btRuntime = btRuntime;
btRuntime_ = btRuntime;
}
void setPieceStorage(const SharedHandle<PieceStorage>& pieceStorage)
{
_pieceStorage = pieceStorage;
pieceStorage_ = pieceStorage;
}
};

View File

@ -44,7 +44,7 @@ ByteArrayDiskWriter::~ByteArrayDiskWriter() {}
void ByteArrayDiskWriter::clear()
{
_buf.str(A2STR::NIL);
buf_.str(A2STR::NIL);
}
void ByteArrayDiskWriter::initAndOpenFile(uint64_t totalLength)
@ -65,29 +65,29 @@ void ByteArrayDiskWriter::writeData(const unsigned char* data, size_t dataLength
{
uint64_t length = size();
if(length < (uint64_t)position) {
_buf.seekp(length, std::ios::beg);
buf_.seekp(length, std::ios::beg);
for(uint64_t i = length; i < (uint64_t)position; ++i) {
_buf.put('\0');
buf_.put('\0');
}
} else {
_buf.seekp(position, std::ios::beg);
buf_.seekp(position, std::ios::beg);
}
_buf.write(reinterpret_cast<const char*>(data), dataLength);
buf_.write(reinterpret_cast<const char*>(data), dataLength);
}
ssize_t ByteArrayDiskWriter::readData(unsigned char* data, size_t len, off_t position)
{
_buf.seekg(position, std::ios::beg);
_buf.read(reinterpret_cast<char*>(data), len);
_buf.clear();
return _buf.gcount();
buf_.seekg(position, std::ios::beg);
buf_.read(reinterpret_cast<char*>(data), len);
buf_.clear();
return buf_.gcount();
}
uint64_t ByteArrayDiskWriter::size()
{
_buf.seekg(0, std::ios::end);
_buf.clear();
return _buf.tellg();
buf_.seekg(0, std::ios::end);
buf_.clear();
return buf_.tellg();
}
} // namespace aria2

View File

@ -42,7 +42,7 @@ namespace aria2 {
class ByteArrayDiskWriter : public DiskWriter {
private:
std::stringstream _buf;
std::stringstream buf_;
void clear();
public:
@ -68,12 +68,12 @@ public:
void setString(const std::string& s)
{
_buf.str(s);
buf_.str(s);
}
std::string getString() const
{
return _buf.str();
return buf_.str();
}
};

View File

@ -42,18 +42,18 @@ namespace aria2 {
class CUIDCounter {
private:
cuid_t _count;
cuid_t count_;
public:
CUIDCounter():_count(0) {}
CUIDCounter():count_(0) {}
~CUIDCounter() {}
cuid_t newID()
{
if(_count == INT64_MAX) {
_count = 0;
if(count_ == INT64_MAX) {
count_ = 0;
}
return ++_count;
return ++count_;
}
};

View File

@ -53,7 +53,7 @@ CheckIntegrityCommand::CheckIntegrityCommand
(cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e,
const SharedHandle<CheckIntegrityEntry>& entry):
RealtimeCommand(cuid, requestGroup, e),
_entry(entry)
entry_(entry)
{}
CheckIntegrityCommand::~CheckIntegrityCommand() {}
@ -64,8 +64,8 @@ bool CheckIntegrityCommand::executeInternal()
getDownloadEngine()->getCheckIntegrityMan()->dropPickedEntry();
return true;
}
_entry->validateChunk();
if(_entry->finished()) {
entry_->validateChunk();
if(entry_->finished()) {
getDownloadEngine()->getCheckIntegrityMan()->dropPickedEntry();
// Enable control file saving here. See also
// RequestGroup::processCheckIntegrityEntry() to know why this is
@ -77,7 +77,7 @@ bool CheckIntegrityCommand::executeInternal()
getRequestGroup()->getDownloadContext()->getBasePath().c_str());
std::vector<Command*>* commands = new std::vector<Command*>();
auto_delete_container<std::vector<Command*> > commandsDel(commands);
_entry->onDownloadFinished(*commands, getDownloadEngine());
entry_->onDownloadFinished(*commands, getDownloadEngine());
getDownloadEngine()->addCommand(*commands);
commands->clear();
} else {
@ -86,7 +86,7 @@ bool CheckIntegrityCommand::executeInternal()
getRequestGroup()->getDownloadContext()->getBasePath().c_str());
std::vector<Command*>* commands = new std::vector<Command*>();
auto_delete_container<std::vector<Command*> > commandsDel(commands);
_entry->onDownloadIncomplete(*commands, getDownloadEngine());
entry_->onDownloadIncomplete(*commands, getDownloadEngine());
getDownloadEngine()->addCommand(*commands);
commands->clear();
}

View File

@ -44,7 +44,7 @@ class CheckIntegrityEntry;
class CheckIntegrityCommand : public RealtimeCommand {
private:
SharedHandle<CheckIntegrityEntry> _entry;
SharedHandle<CheckIntegrityEntry> entry_;
public:
CheckIntegrityCommand(cuid_t cuid,
RequestGroup* requestGroup,

View File

@ -56,30 +56,30 @@ CheckIntegrityEntry::~CheckIntegrityEntry() {}
void CheckIntegrityEntry::validateChunk()
{
_validator->validateChunk();
validator_->validateChunk();
}
uint64_t CheckIntegrityEntry::getTotalLength()
{
if(_validator.isNull()) {
if(validator_.isNull()) {
return 0;
} else {
return _validator->getTotalLength();
return validator_->getTotalLength();
}
}
off_t CheckIntegrityEntry::getCurrentLength()
{
if(_validator.isNull()) {
if(validator_.isNull()) {
return 0;
} else {
return _validator->getCurrentOffset();
return validator_->getCurrentOffset();
}
}
bool CheckIntegrityEntry::finished()
{
return _validator->finished();
return validator_->finished();
}
void CheckIntegrityEntry::cutTrailingGarbage()
@ -106,7 +106,7 @@ void CheckIntegrityEntry::proceedFileAllocation
void CheckIntegrityEntry::setValidator
(const SharedHandle<IteratableValidator>& validator)
{
_validator = validator;
validator_ = validator;
}
} // namespace aria2

View File

@ -49,7 +49,7 @@ class FileAllocationEntry;
class CheckIntegrityEntry : public RequestGroupEntry,
public ProgressAwareEntry {
private:
SharedHandle<IteratableValidator> _validator;
SharedHandle<IteratableValidator> validator_;
protected:
void setValidator(const SharedHandle<IteratableValidator>& validator);

View File

@ -46,34 +46,34 @@ namespace aria2 {
class Checksum {
private:
std::string _algo;
std::string _messageDigest;
std::string algo_;
std::string messageDigest_;
public:
// _messageDigest is ascii hexadecimal notation.
// messageDigest_ is ascii hexadecimal notation.
Checksum(const std::string& algo, const std::string& messageDigest):
_algo(algo), _messageDigest(messageDigest) {}
algo_(algo), messageDigest_(messageDigest) {}
Checksum():
_algo(MessageDigestContext::SHA1) {}
algo_(MessageDigestContext::SHA1) {}
~Checksum() {}
bool isEmpty() const {
return _messageDigest.empty();
return messageDigest_.empty();
}
void setMessageDigest(const std::string& md) {
this->_messageDigest = md;
this->messageDigest_ = md;
}
const std::string& getMessageDigest() const {
return _messageDigest;
return messageDigest_;
}
void setAlgo(const std::string& algo) {
this->_algo = algo;
this->algo_ = algo;
}
const std::string& getAlgo() const {
return _algo;
return algo_;
}
};

View File

@ -47,23 +47,23 @@ namespace aria2 {
class ChunkChecksum {
private:
std::string _algo;
std::vector<std::string> _checksums;
size_t _checksumLength;
std::string algo_;
std::vector<std::string> checksums_;
size_t checksumLength_;
public:
ChunkChecksum():_checksumLength(0) {}
ChunkChecksum():checksumLength_(0) {}
ChunkChecksum(const std::string& algo,
const std::vector<std::string>& checksums,
size_t checksumLength):
_algo(algo),
_checksums(checksums),
_checksumLength(checksumLength) {}
algo_(algo),
checksums_(checksums),
checksumLength_(checksumLength) {}
bool validateChunk(const std::string& actualChecksum,
size_t checksumIndex) const
{
if(checksumIndex < _checksums.size()) {
if(checksumIndex < checksums_.size()) {
return actualChecksum == getChecksum(checksumIndex);
} else {
return false;
@ -72,18 +72,18 @@ public:
uint64_t getEstimatedDataLength() const
{
return ((uint64_t)_checksumLength)*_checksums.size();
return ((uint64_t)checksumLength_)*checksums_.size();
}
size_t countChecksum() const
{
return _checksums.size();
return checksums_.size();
}
const std::string& getChecksum(size_t index) const
{
if(index < _checksums.size()) {
return _checksums[index];
if(index < checksums_.size()) {
return checksums_[index];
} else {
return A2STR::NIL;
}
@ -91,32 +91,32 @@ public:
const std::vector<std::string>& getChecksums() const
{
return _checksums;
return checksums_;
}
size_t getChecksumLength() const
{
return _checksumLength;
return checksumLength_;
}
const std::string& getAlgo() const
{
return _algo;
return algo_;
}
void setAlgo(const std::string& algo)
{
_algo = algo;
algo_ = algo;
}
void setChecksumLength(size_t length)
{
_checksumLength = length;
checksumLength_ = length;
}
void setChecksums(const std::vector<std::string>& mds)
{
_checksums = mds;
checksums_ = mds;
}
};

View File

@ -43,7 +43,7 @@ namespace aria2 {
const std::string ChunkedDecoder::NAME("ChunkedDecoder");
ChunkedDecoder::ChunkedDecoder():_chunkSize(0), _state(READ_SIZE) {}
ChunkedDecoder::ChunkedDecoder():chunkSize_(0), state_(READ_SIZE) {}
ChunkedDecoder::~ChunkedDecoder() {}
@ -84,24 +84,24 @@ static bool readData(std::string& out, uint64_t& chunkSize, std::string& in)
std::string ChunkedDecoder::decode(const unsigned char* inbuf, size_t inlen)
{
_buf.append(&inbuf[0], &inbuf[inlen]);
buf_.append(&inbuf[0], &inbuf[inlen]);
std::string outbuf;
while(1) {
if(_state == READ_SIZE) {
if(readChunkSize(_chunkSize, _buf)) {
if(_chunkSize == 0) {
_state = STREAM_END;
if(state_ == READ_SIZE) {
if(readChunkSize(chunkSize_, buf_)) {
if(chunkSize_ == 0) {
state_ = STREAM_END;
break;
} else {
_state = READ_DATA;
state_ = READ_DATA;
}
} else {
break;
}
} else if(_state == READ_DATA) {
if(readData(outbuf, _chunkSize, _buf)) {
_state = READ_SIZE;
} else if(state_ == READ_DATA) {
if(readData(outbuf, chunkSize_, buf_)) {
state_ = READ_SIZE;
} else {
break;
}
@ -112,7 +112,7 @@ std::string ChunkedDecoder::decode(const unsigned char* inbuf, size_t inlen)
bool ChunkedDecoder::finished()
{
return _state == STREAM_END;
return state_ == STREAM_END;
}
void ChunkedDecoder::release() {}

View File

@ -47,11 +47,11 @@ private:
STREAM_END
};
std::string _buf;
std::string buf_;
uint64_t _chunkSize;
uint64_t chunkSize_;
STATE _state;
STATE state_;
static const std::string NAME;

View File

@ -38,55 +38,55 @@
namespace aria2 {
Command::Command(cuid_t cuid):_status(STATUS_INACTIVE),
_cuid(cuid),
_logger(LogFactory::getInstance()),
_readEvent(false),
_writeEvent(false),
_errorEvent(false),
_hupEvent(false) {}
Command::Command(cuid_t cuid):status_(STATUS_INACTIVE),
cuid_(cuid),
logger_(LogFactory::getInstance()),
readEvent_(false),
writeEvent_(false),
errorEvent_(false),
hupEvent_(false) {}
void Command::transitStatus()
{
switch(_status) {
switch(status_) {
case STATUS_REALTIME:
break;
default:
_status = STATUS_INACTIVE;
status_ = STATUS_INACTIVE;
}
}
void Command::setStatus(STATUS status)
{
_status = status;
status_ = status;
}
void Command::readEventReceived()
{
_readEvent = true;
readEvent_ = true;
}
void Command::writeEventReceived()
{
_writeEvent = true;
writeEvent_ = true;
}
void Command::errorEventReceived()
{
_errorEvent = true;
errorEvent_ = true;
}
void Command::hupEventReceived()
{
_hupEvent = true;
hupEvent_ = true;
}
void Command::clearIOEvents()
{
_readEvent = false;
_writeEvent = false;
_errorEvent = false;
_hupEvent = false;
readEvent_ = false;
writeEvent_ = false;
errorEvent_ = false;
hupEvent_ = false;
}
} // namespace aria2

View File

@ -54,39 +54,39 @@ public:
STATUS_ONESHOT_REALTIME
};
private:
STATUS _status;
STATUS status_;
cuid_t _cuid;
Logger* _logger;
cuid_t cuid_;
Logger* logger_;
bool _readEvent;
bool _writeEvent;
bool _errorEvent;
bool _hupEvent;
bool readEvent_;
bool writeEvent_;
bool errorEvent_;
bool hupEvent_;
protected:
Logger* getLogger() const
{
return _logger;
return logger_;
}
bool readEventEnabled() const
{
return _readEvent;
return readEvent_;
}
bool writeEventEnabled() const
{
return _writeEvent;
return writeEvent_;
}
bool errorEventEnabled() const
{
return _errorEvent;
return errorEvent_;
}
bool hupEventEnabled() const
{
return _hupEvent;
return hupEvent_;
}
public:
Command(cuid_t cuid);
@ -95,19 +95,19 @@ public:
virtual bool execute() = 0;
cuid_t getCuid() const { return _cuid; }
cuid_t getCuid() const { return cuid_; }
void setStatusActive() { _status = STATUS_ACTIVE; }
void setStatusActive() { status_ = STATUS_ACTIVE; }
void setStatusInactive() { _status = STATUS_INACTIVE; }
void setStatusInactive() { status_ = STATUS_INACTIVE; }
void setStatusRealtime() { _status = STATUS_REALTIME; }
void setStatusRealtime() { status_ = STATUS_REALTIME; }
void setStatus(STATUS status);
bool statusMatch(Command::STATUS statusFilter) const
{
return statusFilter <= _status;
return statusFilter <= status_;
}
void transitStatus();

View File

@ -119,7 +119,7 @@ static void printProgress
<< rg->getNumConnection();
#ifdef ENABLE_BITTORRENT
SharedHandle<PeerStorage> ps =
e->getBtRegistry()->get(rg->getGID())._peerStorage;
e->getBtRegistry()->get(rg->getGID()).peerStorage_;
if(!ps.isNull()) {
std::vector<SharedHandle<Peer> > peers;
ps->getActivePeers(peers);
@ -150,19 +150,19 @@ static void printProgress
class PrintSummary
{
private:
size_t _cols;
const DownloadEngine* _e;
const SizeFormatter& _sizeFormatter;
size_t cols_;
const DownloadEngine* e_;
const SizeFormatter& sizeFormatter_;
public:
PrintSummary
(size_t cols, const DownloadEngine* e,
const SizeFormatter& sizeFormatter):
_cols(cols), _e(e), _sizeFormatter(sizeFormatter) {}
cols_(cols), e_(e), sizeFormatter_(sizeFormatter) {}
void operator()(const SharedHandle<RequestGroup>& rg)
{
const char SEP_CHAR = '-';
printProgress(std::cout, rg, _e, _sizeFormatter);
printProgress(std::cout, rg, e_, sizeFormatter_);
const std::vector<SharedHandle<FileEntry> >& fileEntries =
rg->getDownloadContext()->getFileEntries();
std::cout << "\n"
@ -170,7 +170,7 @@ public:
writeFilePath(fileEntries.begin(), fileEntries.end(),
std::cout, rg->inMemoryDownload());
std::cout << "\n"
<< std::setfill(SEP_CHAR) << std::setw(_cols) << SEP_CHAR << "\n";
<< std::setfill(SEP_CHAR) << std::setw(cols_) << SEP_CHAR << "\n";
}
};
@ -203,23 +203,23 @@ static void printProgressSummary
}
ConsoleStatCalc::ConsoleStatCalc(time_t summaryInterval, bool humanReadable):
_summaryInterval(summaryInterval)
summaryInterval_(summaryInterval)
{
if(humanReadable) {
_sizeFormatter.reset(new AbbrevSizeFormatter());
sizeFormatter_.reset(new AbbrevSizeFormatter());
} else {
_sizeFormatter.reset(new PlainSizeFormatter());
sizeFormatter_.reset(new PlainSizeFormatter());
}
}
void
ConsoleStatCalc::calculateStat(const DownloadEngine* e)
{
if(_cp.difference(global::wallclock) < 1) {
if(cp_.difference(global::wallclock) < 1) {
return;
}
_cp = global::wallclock;
const SizeFormatter& sizeFormatter = *_sizeFormatter.get();
cp_ = global::wallclock;
const SizeFormatter& sizeFormatter = *sizeFormatter_.get();
#ifdef __MINGW32__
bool isTTY = true;
@ -243,9 +243,9 @@ ConsoleStatCalc::calculateStat(const DownloadEngine* e)
}
std::ostringstream o;
if(e->getRequestGroupMan()->countRequestGroup() > 0) {
if((_summaryInterval > 0) &&
_lastSummaryNotified.difference(global::wallclock) >= _summaryInterval) {
_lastSummaryNotified = global::wallclock;
if((summaryInterval_ > 0) &&
lastSummaryNotified_.difference(global::wallclock) >= summaryInterval_) {
lastSummaryNotified_ = global::wallclock;
printProgressSummary(e->getRequestGroupMan()->getRequestGroups(), cols, e,
sizeFormatter);
std::cout << "\n";

View File

@ -72,13 +72,13 @@ protected:
class ConsoleStatCalc:public StatCalc
{
private:
Timer _cp;
Timer cp_;
Timer _lastSummaryNotified;
Timer lastSummaryNotified_;
time_t _summaryInterval;
time_t summaryInterval_;
SharedHandle<SizeFormatter> _sizeFormatter;
SharedHandle<SizeFormatter> sizeFormatter_;
public:
ConsoleStatCalc(time_t summaryInterval, bool humanReadable = true);

View File

@ -61,14 +61,14 @@ bool ContentTypeRequestGroupCriteria::match
if(requestGroup->getDownloadContext()->getFileEntries().size() != 1) {
return false;
}
if(tailMatch(_extensions.begin(), _extensions.end(),
if(tailMatch(extensions_.begin(), extensions_.end(),
requestGroup->getFirstFilePath())) {
return true;
} else {
return
std::find(_contentTypes.begin(), _contentTypes.end(),
std::find(contentTypes_.begin(), contentTypes_.end(),
requestGroup->getDownloadContext()->getFirstFileEntry()->
getContentType()) != _contentTypes.end();
getContentType()) != contentTypes_.end();
}
}

View File

@ -44,16 +44,16 @@ namespace aria2 {
class ContentTypeRequestGroupCriteria:public RequestGroupCriteria
{
private:
std::vector<std::string> _contentTypes;
std::vector<std::string> _extensions;
std::vector<std::string> contentTypes_;
std::vector<std::string> extensions_;
public:
template<typename InputIterator>
ContentTypeRequestGroupCriteria(InputIterator contentTypeFirst,
InputIterator contentTypeLast,
InputIterator extensionFirst,
InputIterator extensionLast):
_contentTypes(contentTypeFirst, contentTypeLast),
_extensions(extensionFirst, extensionLast) {}
contentTypes_(contentTypeFirst, contentTypeLast),
extensions_(extensionFirst, extensionLast) {}
virtual bool match(const RequestGroup* requestGroup) const;
};

View File

@ -74,41 +74,41 @@ Cookie::Cookie(const std::string& name,
const std::string& path,
const std::string& domain,
bool secure):
_name(name),
_value(value),
_expiry(expiry),
_path(path),
_domain(normalizeDomain(domain)),
_secure(secure),
_creationTime(time(0)),
_lastAccess(_creationTime) {}
name_(name),
value_(value),
expiry_(expiry),
path_(path),
domain_(normalizeDomain(domain)),
secure_(secure),
creationTime_(time(0)),
lastAccess_(creationTime_) {}
Cookie::Cookie(const std::string& name,
const std::string& value,
const std::string& path,
const std::string& domain,
bool secure):
_name(name),
_value(value),
_expiry(0),
_path(path),
_domain(normalizeDomain(domain)),
_secure(secure),
_creationTime(time(0)),
_lastAccess(_creationTime) {}
name_(name),
value_(value),
expiry_(0),
path_(path),
domain_(normalizeDomain(domain)),
secure_(secure),
creationTime_(time(0)),
lastAccess_(creationTime_) {}
Cookie::Cookie():_expiry(0), _secure(false), _lastAccess(time(0)) {}
Cookie::Cookie():expiry_(0), secure_(false), lastAccess_(time(0)) {}
Cookie::~Cookie() {}
std::string Cookie::toString() const
{
return strconcat(_name, "=", _value);
return strconcat(name_, "=", value_);
}
bool Cookie::good() const
{
return !_name.empty();
return !name_.empty();
}
static bool pathInclude(const std::string& requestPath, const std::string& path)
@ -138,7 +138,7 @@ static bool domainMatch(const std::string& normReqHost,
//
// Also original Netscape implementation behaves exactly the same.
// _domain always starts ".". See Cookie::Cookie().
// domain_ always starts ".". See Cookie::Cookie().
return util::endsWith(normReqHost, domain);
}
@ -146,11 +146,11 @@ bool Cookie::match(const std::string& requestHost,
const std::string& requestPath,
time_t date, bool secure) const
{
if((secure || (!_secure && !secure)) &&
(requestHost == _domain || // For default domain or IP address
domainMatch(normalizeDomain(requestHost), _domain)) &&
pathInclude(requestPath, _path) &&
(isSessionCookie() || (date < _expiry))) {
if((secure || (!secure_ && !secure)) &&
(requestHost == domain_ || // For default domain or IP address
domainMatch(normalizeDomain(requestHost), domain_)) &&
pathInclude(requestPath, path_) &&
(isSessionCookie() || (date < expiry_))) {
return true;
} else {
return false;
@ -160,25 +160,25 @@ bool Cookie::match(const std::string& requestHost,
bool Cookie::validate(const std::string& requestHost,
const std::string& requestPath) const
{
// If _domain doesn't start with "." or it is IP address, then it
// If domain_ doesn't start with "." or it is IP address, then it
// must equal to requestHost. Otherwise, do domain tail match.
if(requestHost != _domain) {
if(requestHost != domain_) {
std::string normReqHost = normalizeDomain(requestHost);
if(normReqHost != _domain) {
if(normReqHost != domain_) {
// domain must start with '.'
if(*_domain.begin() != '.') {
if(*domain_.begin() != '.') {
return false;
}
// domain must not end with '.'
if(*_domain.rbegin() == '.') {
if(*domain_.rbegin() == '.') {
return false;
}
// domain must include at least one embeded '.'
if(_domain.size() < 4 ||
_domain.find(A2STR::DOT_C, 1) == std::string::npos) {
if(domain_.size() < 4 ||
domain_.find(A2STR::DOT_C, 1) == std::string::npos) {
return false;
}
if(!util::endsWith(normReqHost, _domain)) {
if(!util::endsWith(normReqHost, domain_)) {
return false;
}
// From RFC2965 3.3.2 Rejecting Cookies
@ -187,16 +187,16 @@ bool Cookie::validate(const std::string& requestHost,
// that contains one or more dots.
size_t dotCount = std::count(normReqHost.begin(),
normReqHost.begin()+
(normReqHost.size()-_domain.size()), '.');
(normReqHost.size()-domain_.size()), '.');
if(dotCount > 1 || (dotCount == 1 && normReqHost[0] != '.')) {
return false;
}
}
}
if(requestPath != _path) {
if(requestPath != path_) {
// From RFC2965 3.3.2 Rejecting Cookies
// * The value for the Path attribute is not a prefix of the request-URI.
if(!pathInclude(requestPath, _path)) {
if(!pathInclude(requestPath, path_)) {
return false;
}
}
@ -205,48 +205,48 @@ bool Cookie::validate(const std::string& requestHost,
bool Cookie::operator==(const Cookie& cookie) const
{
return _domain == cookie._domain && _path == cookie._path &&
_name == cookie._name;
return domain_ == cookie.domain_ && path_ == cookie.path_ &&
name_ == cookie.name_;
}
bool Cookie::isExpired() const
{
return !_expiry == 0 && Time().getTime() >= _expiry;
return !expiry_ == 0 && Time().getTime() >= expiry_;
}
std::string Cookie::toNsCookieFormat() const
{
std::stringstream ss;
ss << _domain << "\t";
if(util::startsWith(_domain, A2STR::DOT_C)) {
ss << domain_ << "\t";
if(util::startsWith(domain_, A2STR::DOT_C)) {
ss << "TRUE";
} else {
ss << "FALSE";
}
ss << "\t";
ss << _path << "\t";
if(_secure) {
ss << path_ << "\t";
if(secure_) {
ss << "TRUE";
} else {
ss << "FALSE";
}
ss << "\t";
ss << _expiry << "\t";
ss << _name << "\t";
ss << _value;
ss << expiry_ << "\t";
ss << name_ << "\t";
ss << value_;
return ss.str();
}
void Cookie::markOriginServerOnly()
{
if(util::startsWith(_domain, A2STR::DOT_C)) {
_domain.erase(_domain.begin(), _domain.begin()+1);
if(util::startsWith(domain_, A2STR::DOT_C)) {
domain_.erase(domain_.begin(), domain_.begin()+1);
}
}
void Cookie::updateLastAccess()
{
_lastAccess = time(0);
lastAccess_ = time(0);
}
} // namespace aria2

View File

@ -45,19 +45,19 @@ namespace aria2 {
class Cookie {
private:
std::string _name;
std::string _value;
time_t _expiry;
std::string _path;
std::string _domain;
bool _secure;
time_t _creationTime;
time_t _lastAccess;
std::string name_;
std::string value_;
time_t expiry_;
std::string path_;
std::string domain_;
bool secure_;
time_t creationTime_;
time_t lastAccess_;
public:
/*
* If expires = 0 is given, then the cookie becomes session cookie.
* domain is normalized using normalizeDomain() function and
* assigned to _domain. If domain is not specified in cookie, call
* assigned to domain_. If domain is not specified in cookie, call
* markOriginServerOnly() after construction.
*/
Cookie(const std::string& name,
@ -70,7 +70,7 @@ public:
/*
* Creates session cookie. This is equivalent to Cookie(name, value,
* 0, path, domain, secure); domain is normalized using
* normalizeDomain() function and assigned to _domain. If domain is
* normalizeDomain() function and assigned to domain_. If domain is
* not specified in cookie, call markOriginServerOnly() after
* construction.
*/
@ -100,55 +100,55 @@ public:
const std::string& getName() const
{
return _name;
return name_;
}
const std::string& getValue() const
{
return _value;
return value_;
}
const std::string& getPath() const
{
return _path;
return path_;
}
const std::string& getDomain() const
{
return _domain;
return domain_;
}
time_t getExpiry() const
{
return _expiry;
return expiry_;
}
bool isSecureCookie() const
{
return _secure;
return secure_;
}
bool isSessionCookie() const
{
return _expiry == 0;
return expiry_ == 0;
}
std::string toNsCookieFormat() const;
// Makes this Cookie only sent to the origin server. This function
// removes first "." from _domain if _domain starts with ".".
// removes first "." from domain_ if domain_ starts with ".".
void markOriginServerOnly();
time_t getCreationTime() const
{
return _creationTime;
return creationTime_;
}
void updateLastAccess();
time_t getLastAccess() const
{
return _lastAccess;
return lastAccess_;
}
static std::string normalizeDomain(const std::string& domain);

View File

@ -54,36 +54,36 @@
namespace aria2 {
CookieStorage::DomainEntry::DomainEntry
(const std::string& domain):_key(domain)
(const std::string& domain):key_(domain)
{
std::reverse(_key.begin(), _key.end());
std::reverse(key_.begin(), key_.end());
}
void CookieStorage::DomainEntry::updateLastAccess()
{
_lastAccess = time(0);
lastAccess_ = time(0);
}
bool CookieStorage::DomainEntry::addCookie(const Cookie& cookie)
{
updateLastAccess();
std::deque<Cookie>::iterator i = std::find(_cookies.begin(), _cookies.end(),
std::deque<Cookie>::iterator i = std::find(cookies_.begin(), cookies_.end(),
cookie);
if(i == _cookies.end()) {
if(i == cookies_.end()) {
if(cookie.isExpired()) {
return false;
} else {
if(_cookies.size() >= CookieStorage::MAX_COOKIE_PER_DOMAIN) {
if(cookies_.size() >= CookieStorage::MAX_COOKIE_PER_DOMAIN) {
std::deque<Cookie>::iterator m = std::min_element
(_cookies.begin(), _cookies.end(), LeastRecentAccess<Cookie>());
(cookies_.begin(), cookies_.end(), LeastRecentAccess<Cookie>());
*m = cookie;
} else {
_cookies.push_back(cookie);
cookies_.push_back(cookie);
}
return true;
}
} else if(cookie.isExpired()) {
_cookies.erase(i);
cookies_.erase(i);
return false;
} else {
*i = cookie;
@ -93,18 +93,18 @@ bool CookieStorage::DomainEntry::addCookie(const Cookie& cookie)
bool CookieStorage::DomainEntry::contains(const Cookie& cookie) const
{
return std::find(_cookies.begin(), _cookies.end(), cookie) != _cookies.end();
return std::find(cookies_.begin(), cookies_.end(), cookie) != cookies_.end();
}
void CookieStorage::DomainEntry::writeCookie(std::ostream& o) const
{
for(std::deque<Cookie>::const_iterator i = _cookies.begin(),
eoi = _cookies.end(); i != eoi; ++i) {
for(std::deque<Cookie>::const_iterator i = cookies_.begin(),
eoi = cookies_.end(); i != eoi; ++i) {
o << (*i).toNsCookieFormat() << "\n";
}
}
CookieStorage::CookieStorage():_logger(LogFactory::getInstance()) {}
CookieStorage::CookieStorage():logger_(LogFactory::getInstance()) {}
CookieStorage::~CookieStorage() {}
@ -118,23 +118,23 @@ bool CookieStorage::store(const Cookie& cookie)
if(!cookie.good()) {
return false;
}
if(_domains.size() >= DOMAIN_EVICTION_TRIGGER) {
std::sort(_domains.begin(), _domains.end(),
if(domains_.size() >= DOMAIN_EVICTION_TRIGGER) {
std::sort(domains_.begin(), domains_.end(),
LeastRecentAccess<DomainEntry>());
size_t delnum = (size_t)(_domains.size()*DOMAIN_EVICTION_RATE);
_domains.erase(_domains.begin(), _domains.begin()+delnum);
std::sort(_domains.begin(), _domains.end());
size_t delnum = (size_t)(domains_.size()*DOMAIN_EVICTION_RATE);
domains_.erase(domains_.begin(), domains_.begin()+delnum);
std::sort(domains_.begin(), domains_.end());
}
DomainEntry v(cookie.getDomain());
std::deque<DomainEntry>::iterator i =
std::lower_bound(_domains.begin(), _domains.end(), v);
std::lower_bound(domains_.begin(), domains_.end(), v);
bool added = false;
if(i != _domains.end() && (*i).getKey() == v.getKey()) {
if(i != domains_.end() && (*i).getKey() == v.getKey()) {
added = (*i).addCookie(cookie);
} else {
added = v.addCookie(cookie);
if(added) {
_domains.insert(i, v);
domains_.insert(i, v);
}
}
return added;
@ -144,7 +144,7 @@ bool CookieStorage::parseAndStore(const std::string& setCookieString,
const std::string& requestHost,
const std::string& requestPath)
{
Cookie cookie = _parser.parse(setCookieString, requestHost, requestPath);
Cookie cookie = parser_.parse(setCookieString, requestHost, requestPath);
if(cookie.validate(requestHost, requestPath)) {
return store(cookie);
} else {
@ -153,13 +153,13 @@ bool CookieStorage::parseAndStore(const std::string& setCookieString,
}
struct CookiePathDivider {
Cookie _cookie;
int _pathDepth;
CookiePathDivider(const Cookie& cookie):_cookie(cookie)
Cookie cookie_;
int pathDepth_;
CookiePathDivider(const Cookie& cookie):cookie_(cookie)
{
std::vector<std::string> paths;
util::split(_cookie.getPath(), std::back_inserter(paths), A2STR::SLASH_C);
_pathDepth = paths.size();
util::split(cookie_.getPath(), std::back_inserter(paths), A2STR::SLASH_C);
pathDepth_ = paths.size();
}
};
@ -172,7 +172,7 @@ public:
Cookie operator()(const CookiePathDivider& cookiePathDivider) const
{
return cookiePathDivider._cookie;
return cookiePathDivider.cookie_;
}
};
@ -194,9 +194,9 @@ public:
// "name1=foo" with a path mapping of "/" should be sent after a
// cookie "name1=foo2" with a path mapping of "/bar" if they are
// both to be sent.
int comp = lhs._pathDepth-rhs._pathDepth;
int comp = lhs.pathDepth_-rhs.pathDepth_;
if(comp == 0) {
return lhs._cookie.getCreationTime() < rhs._cookie.getCreationTime();
return lhs.cookie_.getCreationTime() < rhs.cookie_.getCreationTime();
} else {
return comp > 0;
}
@ -224,8 +224,8 @@ bool CookieStorage::contains(const Cookie& cookie) const
{
CookieStorage::DomainEntry v(cookie.getDomain());
std::deque<CookieStorage::DomainEntry>::const_iterator i =
std::lower_bound(_domains.begin(), _domains.end(), v);
if(i != _domains.end() && (*i).getKey() == v.getKey()) {
std::lower_bound(domains_.begin(), domains_.end(), v);
if(i != domains_.end() && (*i).getKey() == v.getKey()) {
return (*i).contains(cookie);
} else {
return false;
@ -241,7 +241,7 @@ std::vector<Cookie> CookieStorage::criteriaFind(const std::string& requestHost,
searchCookieByDomainSuffix
((!numericHost && requestHost.find(A2STR::DOT_C) == std::string::npos)?
requestHost+".local":requestHost,
_domains.begin(), _domains.end(),
domains_.begin(), domains_.end(),
std::back_inserter(res),
requestHost, requestPath, date, secure);
if(!numericHost) {
@ -259,7 +259,7 @@ std::vector<Cookie> CookieStorage::criteriaFind(const std::string& requestHost,
domainComponents.begin()+1, eoi = domainComponents.end();
di != eoi; ++di) {
domain = strconcat(A2STR::DOT_C, *di, domain);
searchCookieByDomainSuffix(domain, _domains.begin(), _domains.end(),
searchCookieByDomainSuffix(domain, domains_.begin(), domains_.end(),
std::back_inserter(res),
normRequestHost, requestPath, date, secure);
}
@ -276,8 +276,8 @@ std::vector<Cookie> CookieStorage::criteriaFind(const std::string& requestHost,
size_t CookieStorage::size() const
{
size_t numCookie = 0;
for(std::deque<DomainEntry>::const_iterator i = _domains.begin(),
eoi = _domains.end(); i != eoi; ++i) {
for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
eoi = domains_.end(); i != eoi; ++i) {
numCookie += (*i).countCookie();
}
return numCookie;
@ -288,12 +288,12 @@ bool CookieStorage::load(const std::string& filename)
char header[16]; // "SQLite format 3" plus \0
std::ifstream s(filename.c_str(), std::ios::binary);
if(!s) {
_logger->error("Failed to open cookie file %s", filename.c_str());
logger_->error("Failed to open cookie file %s", filename.c_str());
return false;
}
s.get(header, sizeof(header));
if(!s) {
_logger->error("Failed to read header of cookie file %s",
logger_->error("Failed to read header of cookie file %s",
filename.c_str());
return false;
}
@ -313,7 +313,7 @@ bool CookieStorage::load(const std::string& filename)
}
return true;
} catch(RecoverableException& e) {
_logger->error("Failed to load cookies from %s", filename.c_str());
logger_->error("Failed to load cookies from %s", filename.c_str());
return false;
}
}
@ -324,17 +324,17 @@ bool CookieStorage::saveNsFormat(const std::string& filename)
{
std::ofstream o(tempfilename.c_str(), std::ios::binary);
if(!o) {
_logger->error("Cannot create cookie file %s, cause %s",
logger_->error("Cannot create cookie file %s, cause %s",
filename.c_str(), strerror(errno));
return false;
}
for(std::deque<DomainEntry>::const_iterator i = _domains.begin(),
eoi = _domains.end(); i != eoi; ++i) {
for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
eoi = domains_.end(); i != eoi; ++i) {
(*i).writeCookie(o);
}
o.flush();
if(!o) {
_logger->error("Failed to save cookies to %s, cause %s",
logger_->error("Failed to save cookies to %s, cause %s",
filename.c_str(), strerror(errno));
return false;
}
@ -342,7 +342,7 @@ bool CookieStorage::saveNsFormat(const std::string& filename)
if(File(tempfilename).renameTo(filename)) {
return true;
} else {
_logger->error("Could not rename file %s as %s",
logger_->error("Could not rename file %s as %s",
tempfilename.c_str(), filename.c_str());
return false;
}

View File

@ -57,17 +57,17 @@ public:
class DomainEntry {
private:
std::string _key;
std::string key_;
time_t _lastAccess;
time_t lastAccess_;
std::deque<Cookie> _cookies;
std::deque<Cookie> cookies_;
public:
DomainEntry(const std::string& domain);
const std::string& getKey() const
{
return _key;
return key_;
}
template<typename OutputIterator>
@ -77,8 +77,8 @@ public:
const std::string& requestPath,
time_t date, bool secure)
{
for(std::deque<Cookie>::iterator i = _cookies.begin();
i != _cookies.end(); ++i) {
for(std::deque<Cookie>::iterator i = cookies_.begin();
i != cookies_.end(); ++i) {
if((*i).match(requestHost, requestPath, date, secure)) {
(*i).updateLastAccess();
out++ = *i;
@ -89,7 +89,7 @@ public:
size_t countCookie() const
{
return _cookies.size();
return cookies_.size();
}
bool addCookie(const Cookie& cookie);
@ -98,7 +98,7 @@ public:
time_t getLastAccess() const
{
return _lastAccess;
return lastAccess_;
}
void writeCookie(std::ostream& o) const;
@ -108,20 +108,20 @@ public:
template<typename OutputIterator>
OutputIterator dumpCookie(OutputIterator out) const
{
return std::copy(_cookies.begin(), _cookies.end(), out);
return std::copy(cookies_.begin(), cookies_.end(), out);
}
bool operator<(const DomainEntry& de) const
{
return _key < de._key;
return key_ < de.key_;
}
};
private:
std::deque<DomainEntry> _domains;
std::deque<DomainEntry> domains_;
CookieParser _parser;
CookieParser parser_;
Logger* _logger;
Logger* logger_;
template<typename InputIterator>
void storeCookies(InputIterator first, InputIterator last)
@ -146,7 +146,7 @@ public:
const std::string& requestPath);
// Finds cookies matched with given criteria and returns them.
// Matched cookies' _lastAccess property is updated.
// Matched cookies' lastAccess_ property is updated.
std::vector<Cookie> criteriaFind(const std::string& requestHost,
const std::string& requestPath,
time_t date, bool secure);
@ -173,8 +173,8 @@ public:
template<typename OutputIterator>
OutputIterator dumpCookie(OutputIterator out) const
{
for(std::deque<DomainEntry>::const_iterator i = _domains.begin(),
eoi = _domains.end(); i != eoi; ++i) {
for(std::deque<DomainEntry>::const_iterator i = domains_.begin(),
eoi = domains_.end(); i != eoi; ++i) {
out = (*i).dumpCookie(out);
}
return out;

View File

@ -66,7 +66,7 @@ std::string DHTAbstractMessage::getBencodedMessage()
bool DHTAbstractMessage::send()
{
std::string message = getBencodedMessage();
ssize_t r = _connection->sendMessage
ssize_t r = connection_->sendMessage
(reinterpret_cast<const unsigned char*>(message.c_str()),
message.size(),
getRemoteNode()->getIPAddress(),
@ -78,25 +78,25 @@ bool DHTAbstractMessage::send()
void DHTAbstractMessage::setConnection
(const WeakHandle<DHTConnection>& connection)
{
_connection = connection;
connection_ = connection;
}
void DHTAbstractMessage::setMessageDispatcher
(const WeakHandle<DHTMessageDispatcher>& dispatcher)
{
_dispatcher = dispatcher;
dispatcher_ = dispatcher;
}
void DHTAbstractMessage::setMessageFactory
(const WeakHandle<DHTMessageFactory>& factory)
{
_factory = factory;
factory_ = factory;
}
void DHTAbstractMessage::setRoutingTable
(const WeakHandle<DHTRoutingTable>& routingTable)
{
_routingTable = routingTable;
routingTable_ = routingTable;
}
} // namespace aria2

View File

@ -48,13 +48,13 @@ class DHTRoutingTable;
class DHTAbstractMessage:public DHTMessage {
private:
WeakHandle<DHTConnection> _connection;
WeakHandle<DHTConnection> connection_;
WeakHandle<DHTMessageDispatcher> _dispatcher;
WeakHandle<DHTMessageDispatcher> dispatcher_;
WeakHandle<DHTMessageFactory> _factory;
WeakHandle<DHTMessageFactory> factory_;
WeakHandle<DHTRoutingTable> _routingTable;
WeakHandle<DHTRoutingTable> routingTable_;
public:
DHTAbstractMessage(const SharedHandle<DHTNode>& localNode,
const SharedHandle<DHTNode>& remoteNode,
@ -72,28 +72,28 @@ public:
const WeakHandle<DHTConnection>& getConnection() const
{
return _connection;
return connection_;
}
void setConnection(const WeakHandle<DHTConnection>& connection);
const WeakHandle<DHTMessageDispatcher>& getMessageDispatcher() const
{
return _dispatcher;
return dispatcher_;
}
void setMessageDispatcher(const WeakHandle<DHTMessageDispatcher>& dispatcher);
const WeakHandle<DHTMessageFactory>& getMessageFactory() const
{
return _factory;
return factory_;
}
void setMessageFactory(const WeakHandle<DHTMessageFactory>& factory);
const WeakHandle<DHTRoutingTable>& getRoutingTable() const
{
return _routingTable;
return routingTable_;
}
void setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable);

View File

@ -63,11 +63,11 @@ class DHTMessage;
template<class ResponseMessage>
class DHTAbstractNodeLookupTask:public DHTAbstractTask {
private:
unsigned char _targetID[DHT_ID_LENGTH];
unsigned char targetID_[DHT_ID_LENGTH];
std::deque<SharedHandle<DHTNodeLookupEntry> > _entries;
std::deque<SharedHandle<DHTNodeLookupEntry> > entries_;
size_t _inFlightMessage;
size_t inFlightMessage_;
template<typename Container>
void toEntries
@ -83,10 +83,10 @@ private:
void sendMessage()
{
for(std::deque<SharedHandle<DHTNodeLookupEntry> >::iterator i =
_entries.begin(), eoi = _entries.end();
i != eoi && _inFlightMessage < ALPHA; ++i) {
entries_.begin(), eoi = entries_.end();
i != eoi && inFlightMessage_ < ALPHA; ++i) {
if((*i)->used == false) {
++_inFlightMessage;
++inFlightMessage_;
(*i)->used = true;
SharedHandle<DHTMessage> m = createMessage((*i)->node);
SharedHandle<DHTMessageCallback> callback(createCallback());
@ -100,10 +100,10 @@ private:
if(needsAdditionalOutgoingMessage()) {
sendMessage();
}
if(_inFlightMessage == 0) {
if(inFlightMessage_ == 0) {
if(getLogger()->debug()) {
getLogger()->debug("Finished node_lookup for node ID %s",
util::toHex(_targetID, DHT_ID_LENGTH).c_str());
util::toHex(targetID_, DHT_ID_LENGTH).c_str());
}
onFinish();
updateBucket();
@ -111,8 +111,8 @@ private:
} else {
if(getLogger()->debug()) {
getLogger()->debug("%d in flight message for node ID %s",
_inFlightMessage,
util::toHex(_targetID, DHT_ID_LENGTH).c_str());
inFlightMessage_,
util::toHex(targetID_, DHT_ID_LENGTH).c_str());
}
}
}
@ -121,12 +121,12 @@ private:
protected:
const unsigned char* getTargetID() const
{
return _targetID;
return targetID_;
}
const std::deque<SharedHandle<DHTNodeLookupEntry> >& getEntries() const
{
return _entries;
return entries_;
}
virtual void getNodesFromMessage
@ -146,9 +146,9 @@ protected:
virtual SharedHandle<DHTMessageCallback> createCallback() = 0;
public:
DHTAbstractNodeLookupTask(const unsigned char* targetID):
_inFlightMessage(0)
inFlightMessage_(0)
{
memcpy(_targetID, targetID, DHT_ID_LENGTH);
memcpy(targetID_, targetID, DHT_ID_LENGTH);
}
static const size_t ALPHA = 3;
@ -156,16 +156,16 @@ public:
virtual void startup()
{
std::vector<SharedHandle<DHTNode> > nodes;
getRoutingTable()->getClosestKNodes(nodes, _targetID);
_entries.clear();
toEntries(_entries, nodes);
if(_entries.empty()) {
getRoutingTable()->getClosestKNodes(nodes, targetID_);
entries_.clear();
toEntries(entries_, nodes);
if(entries_.empty()) {
setFinished(true);
} else {
// TODO use RTT here
_inFlightMessage = 0;
inFlightMessage_ = 0;
sendMessage();
if(_inFlightMessage == 0) {
if(inFlightMessage_ == 0) {
if(getLogger()->debug()) {
getLogger()->debug("No message was sent in this lookup stage. Finished.");
}
@ -176,7 +176,7 @@ public:
void onReceived(const ResponseMessage* message)
{
--_inFlightMessage;
--inFlightMessage_;
onReceivedInternal(message);
std::vector<SharedHandle<DHTNode> > nodes;
getNodesFromMessage(nodes, message);
@ -188,7 +188,7 @@ public:
newEntries.begin(), eoi = newEntries.end(); i != eoi; ++i) {
if(memcmp(getLocalNode()->getID(), (*i)->node->getID(),
DHT_ID_LENGTH) != 0) {
_entries.push_front(*i);
entries_.push_front(*i);
++count;
if(getLogger()->debug()) {
getLogger()->debug("Received nodes: id=%s, ip=%s",
@ -201,13 +201,13 @@ public:
if(getLogger()->debug()) {
getLogger()->debug("%u node lookup entries added.", count);
}
std::stable_sort(_entries.begin(), _entries.end(), DHTIDCloser(_targetID));
_entries.erase(std::unique(_entries.begin(), _entries.end()), _entries.end());
std::stable_sort(entries_.begin(), entries_.end(), DHTIDCloser(targetID_));
entries_.erase(std::unique(entries_.begin(), entries_.end()), entries_.end());
if(getLogger()->debug()) {
getLogger()->debug("%u node lookup entries are unique.", _entries.size());
getLogger()->debug("%u node lookup entries are unique.", entries_.size());
}
if(_entries.size() > DHTBucket::K) {
_entries.erase(_entries.begin()+DHTBucket::K, _entries.end());
if(entries_.size() > DHTBucket::K) {
entries_.erase(entries_.begin()+DHTBucket::K, entries_.end());
}
sendMessageAndCheckFinish();
}
@ -218,11 +218,11 @@ public:
getLogger()->debug("node lookup message timeout for node ID=%s",
util::toHex(node->getID(), DHT_ID_LENGTH).c_str());
}
--_inFlightMessage;
--inFlightMessage_;
for(std::deque<SharedHandle<DHTNodeLookupEntry> >::iterator i =
_entries.begin(), eoi = _entries.end(); i != eoi; ++i) {
entries_.begin(), eoi = entries_.end(); i != eoi; ++i) {
if((*i)->node == node) {
_entries.erase(i);
entries_.erase(i);
break;
}
}

View File

@ -47,38 +47,38 @@
namespace aria2 {
DHTAbstractTask::DHTAbstractTask():
_finished(false),
_logger(LogFactory::getInstance())
finished_(false),
logger_(LogFactory::getInstance())
{}
bool DHTAbstractTask::finished()
{
return _finished;
return finished_;
}
void DHTAbstractTask::setRoutingTable(const WeakHandle<DHTRoutingTable> routingTable)
{
_routingTable = routingTable;
routingTable_ = routingTable;
}
void DHTAbstractTask::setMessageDispatcher(const WeakHandle<DHTMessageDispatcher> dispatcher)
{
_dispatcher = dispatcher;
dispatcher_ = dispatcher;
}
void DHTAbstractTask::setMessageFactory(const WeakHandle<DHTMessageFactory> factory)
{
_factory = factory;
factory_ = factory;
}
void DHTAbstractTask::setTaskQueue(const WeakHandle<DHTTaskQueue> taskQueue)
{
_taskQueue = taskQueue;
taskQueue_ = taskQueue;
}
void DHTAbstractTask::setLocalNode(const SharedHandle<DHTNode>& localNode)
{
_localNode = localNode;
localNode_ = localNode;
}
} // namespace aria2

View File

@ -52,28 +52,28 @@ class Logger;
class DHTAbstractTask:public DHTTask {
private:
bool _finished;
bool finished_;
Logger* _logger;
Logger* logger_;
SharedHandle<DHTNode> _localNode;
SharedHandle<DHTNode> localNode_;
WeakHandle<DHTRoutingTable> _routingTable;
WeakHandle<DHTRoutingTable> routingTable_;
WeakHandle<DHTMessageDispatcher> _dispatcher;
WeakHandle<DHTMessageDispatcher> dispatcher_;
WeakHandle<DHTMessageFactory> _factory;
WeakHandle<DHTMessageFactory> factory_;
WeakHandle<DHTTaskQueue> _taskQueue;
WeakHandle<DHTTaskQueue> taskQueue_;
protected:
void setFinished(bool f)
{
_finished = f;
finished_ = f;
}
Logger* getLogger() const
{
return _logger;
return logger_;
}
public:
DHTAbstractTask();
@ -82,35 +82,35 @@ public:
const WeakHandle<DHTRoutingTable>& getRoutingTable() const
{
return _routingTable;
return routingTable_;
}
void setRoutingTable(const WeakHandle<DHTRoutingTable> routingTable);
const WeakHandle<DHTMessageDispatcher>& getMessageDispatcher() const
{
return _dispatcher;
return dispatcher_;
}
void setMessageDispatcher(const WeakHandle<DHTMessageDispatcher> dispatcher);
const WeakHandle<DHTMessageFactory>& getMessageFactory() const
{
return _factory;
return factory_;
}
void setMessageFactory(const WeakHandle<DHTMessageFactory> factory);
const WeakHandle<DHTTaskQueue>& getTaskQueue() const
{
return _taskQueue;
return taskQueue_;
}
void setTaskQueue(const WeakHandle<DHTTaskQueue> taskQueue);
const SharedHandle<DHTNode>& getLocalNode() const
{
return _localNode;
return localNode_;
}
void setLocalNode(const SharedHandle<DHTNode>& localNode);

View File

@ -67,18 +67,18 @@ DHTAnnouncePeerMessage::DHTAnnouncePeerMessage
const std::string& token,
const std::string& transactionID):
DHTQueryMessage(localNode, remoteNode, transactionID),
_token(token),
_tcpPort(tcpPort)
token_(token),
tcpPort_(tcpPort)
{
memcpy(_infoHash, infoHash, DHT_ID_LENGTH);
memcpy(infoHash_, infoHash, DHT_ID_LENGTH);
}
DHTAnnouncePeerMessage::~DHTAnnouncePeerMessage() {}
void DHTAnnouncePeerMessage::doReceivedAction()
{
_peerAnnounceStorage->addPeerAnnounce
(_infoHash, getRemoteNode()->getIPAddress(), _tcpPort);
peerAnnounceStorage_->addPeerAnnounce
(infoHash_, getRemoteNode()->getIPAddress(), tcpPort_);
SharedHandle<DHTMessage> reply =
getMessageFactory()->createAnnouncePeerReplyMessage
@ -90,9 +90,9 @@ SharedHandle<Dict> DHTAnnouncePeerMessage::getArgument()
{
SharedHandle<Dict> aDict = Dict::g();
aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH));
aDict->put(INFO_HASH, String::g(_infoHash, DHT_ID_LENGTH));
aDict->put(PORT, Integer::g(_tcpPort));
aDict->put(TOKEN, _token);
aDict->put(INFO_HASH, String::g(infoHash_, DHT_ID_LENGTH));
aDict->put(PORT, Integer::g(tcpPort_));
aDict->put(TOKEN, token_);
return aDict;
}
@ -103,12 +103,12 @@ const std::string& DHTAnnouncePeerMessage::getMessageType() const
void DHTAnnouncePeerMessage::validate() const
{
if(!_tokenTracker->validateToken(_token, _infoHash,
if(!tokenTracker_->validateToken(token_, infoHash_,
getRemoteNode()->getIPAddress(),
getRemoteNode()->getPort())) {
throw DL_ABORT_EX
(StringFormat("Invalid token=%s from %s:%u",
util::toHex(_token).c_str(),
util::toHex(token_).c_str(),
getRemoteNode()->getIPAddress().c_str(),
getRemoteNode()->getPort()).str());
}
@ -117,20 +117,20 @@ void DHTAnnouncePeerMessage::validate() const
void DHTAnnouncePeerMessage::setPeerAnnounceStorage
(const WeakHandle<DHTPeerAnnounceStorage>& storage)
{
_peerAnnounceStorage = storage;
peerAnnounceStorage_ = storage;
}
void DHTAnnouncePeerMessage::setTokenTracker
(const WeakHandle<DHTTokenTracker>& tokenTracker)
{
_tokenTracker = tokenTracker;
tokenTracker_ = tokenTracker;
}
std::string DHTAnnouncePeerMessage::toStringOptional() const
{
return strconcat("token=", util::toHex(_token),
", info_hash=", util::toHex(_infoHash, INFO_HASH_LENGTH),
", tcpPort=", util::uitos(_tcpPort));
return strconcat("token=", util::toHex(token_),
", info_hash=", util::toHex(infoHash_, INFO_HASH_LENGTH),
", tcpPort=", util::uitos(tcpPort_));
}
} // namespace aria2

View File

@ -46,15 +46,15 @@ class DHTTokenTracker;
class DHTAnnouncePeerMessage:public DHTQueryMessage {
private:
std::string _token;
std::string token_;
unsigned char _infoHash[DHT_ID_LENGTH];
unsigned char infoHash_[DHT_ID_LENGTH];
uint16_t _tcpPort;
uint16_t tcpPort_;
WeakHandle<DHTPeerAnnounceStorage> _peerAnnounceStorage;
WeakHandle<DHTPeerAnnounceStorage> peerAnnounceStorage_;
WeakHandle<DHTTokenTracker> _tokenTracker;
WeakHandle<DHTTokenTracker> tokenTracker_;
protected:
virtual std::string toStringOptional() const;
public:
@ -77,17 +77,17 @@ public:
const unsigned char* getInfoHash() const
{
return _infoHash;
return infoHash_;
}
const std::string& getToken() const
{
return _token;
return token_;
}
uint16_t getTCPPort() const
{
return _tcpPort;
return tcpPort_;
}
void setPeerAnnounceStorage(const WeakHandle<DHTPeerAnnounceStorage>& storage);

View File

@ -107,7 +107,7 @@ void DHTAutoSaveCommand::save()
}
std::vector<SharedHandle<DHTNode> > nodes;
std::vector<SharedHandle<DHTBucket> > buckets;
_routingTable->getBuckets(buckets);
routingTable_->getBuckets(buckets);
for(std::vector<SharedHandle<DHTBucket> >::const_iterator i = buckets.begin(),
eoi = buckets.end(); i != eoi; ++i) {
const SharedHandle<DHTBucket>& bucket = *i;
@ -117,7 +117,7 @@ void DHTAutoSaveCommand::save()
}
DHTRoutingTableSerializer serializer;
serializer.setLocalNode(_localNode);
serializer.setLocalNode(localNode_);
serializer.setNodes(nodes);
try {
@ -142,13 +142,13 @@ void DHTAutoSaveCommand::save()
void DHTAutoSaveCommand::setLocalNode(const SharedHandle<DHTNode>& localNode)
{
_localNode = localNode;
localNode_ = localNode;
}
void DHTAutoSaveCommand::setRoutingTable
(const SharedHandle<DHTRoutingTable>& routingTable)
{
_routingTable = routingTable;
routingTable_ = routingTable;
}
} // namespace aria2

View File

@ -46,9 +46,9 @@ class DHTNode;
class DHTAutoSaveCommand : public TimeBasedCommand
{
private:
SharedHandle<DHTNode> _localNode;
SharedHandle<DHTNode> localNode_;
SharedHandle<DHTRoutingTable> _routingTable;
SharedHandle<DHTRoutingTable> routingTable_;
void save();
public:

View File

@ -53,46 +53,46 @@ namespace aria2 {
DHTBucket::DHTBucket(size_t prefixLength,
const unsigned char* max, const unsigned char* min,
const SharedHandle<DHTNode>& localNode):
_prefixLength(prefixLength),
_localNode(localNode),
_lastUpdated(global::wallclock),
_logger(LogFactory::getInstance())
prefixLength_(prefixLength),
localNode_(localNode),
lastUpdated_(global::wallclock),
logger_(LogFactory::getInstance())
{
memcpy(_max, max, DHT_ID_LENGTH);
memcpy(_min, min, DHT_ID_LENGTH);
memcpy(max_, max, DHT_ID_LENGTH);
memcpy(min_, min, DHT_ID_LENGTH);
}
DHTBucket::DHTBucket(const SharedHandle<DHTNode>& localNode):
_prefixLength(0),
_localNode(localNode),
_lastUpdated(global::wallclock),
_logger(LogFactory::getInstance())
prefixLength_(0),
localNode_(localNode),
lastUpdated_(global::wallclock),
logger_(LogFactory::getInstance())
{
memset(_max, 0xff, DHT_ID_LENGTH);
memset(_min, 0, DHT_ID_LENGTH);
memset(max_, 0xff, DHT_ID_LENGTH);
memset(min_, 0, DHT_ID_LENGTH);
}
DHTBucket::~DHTBucket() {}
void DHTBucket::getRandomNodeID(unsigned char* nodeID) const
{
if(_prefixLength == 0) {
if(prefixLength_ == 0) {
util::generateRandomKey(nodeID);
} else {
size_t lastByteIndex = (_prefixLength-1)/8;
size_t lastByteIndex = (prefixLength_-1)/8;
util::generateRandomKey(nodeID);
memcpy(nodeID, _min, lastByteIndex+1);
memcpy(nodeID, min_, lastByteIndex+1);
}
}
bool DHTBucket::isInRange(const SharedHandle<DHTNode>& node) const
{
return isInRange(node->getID(), _max, _min);
return isInRange(node->getID(), max_, min_);
}
bool DHTBucket::isInRange(const unsigned char* nodeID) const
{
return isInRange(nodeID, _max, _min);
return isInRange(nodeID, max_, min_);
}
// Returns true if nodeID is in [min, max] (inclusive).
@ -111,45 +111,45 @@ bool DHTBucket::addNode(const SharedHandle<DHTNode>& node)
{
notifyUpdate();
std::deque<SharedHandle<DHTNode> >::iterator itr =
std::find(_nodes.begin(), _nodes.end(), node);
if(itr == _nodes.end()) {
if(_nodes.size() < K) {
_nodes.push_back(node);
std::find(nodes_.begin(), nodes_.end(), node);
if(itr == nodes_.end()) {
if(nodes_.size() < K) {
nodes_.push_back(node);
return true;
} else {
if(_nodes.front()->isBad()) {
_nodes.erase(_nodes.begin());
_nodes.push_back(node);
if(nodes_.front()->isBad()) {
nodes_.erase(nodes_.begin());
nodes_.push_back(node);
return true;
} else {
return false;
}
}
} else {
_nodes.erase(itr);
_nodes.push_back(node);
nodes_.erase(itr);
nodes_.push_back(node);
return true;
}
}
void DHTBucket::cacheNode(const SharedHandle<DHTNode>& node)
{
// _cachedNodes are sorted by last time seen
_cachedNodes.push_front(node);
if(_cachedNodes.size() > CACHE_SIZE) {
_cachedNodes.resize(CACHE_SIZE, SharedHandle<DHTNode>());
// cachedNodes_ are sorted by last time seen
cachedNodes_.push_front(node);
if(cachedNodes_.size() > CACHE_SIZE) {
cachedNodes_.resize(CACHE_SIZE, SharedHandle<DHTNode>());
}
}
void DHTBucket::dropNode(const SharedHandle<DHTNode>& node)
{
if(_cachedNodes.size()) {
if(cachedNodes_.size()) {
std::deque<SharedHandle<DHTNode> >::iterator itr =
find(_nodes.begin(), _nodes.end(), node);
if(itr != _nodes.end()) {
_nodes.erase(itr);
_nodes.push_back(_cachedNodes.front());
_cachedNodes.erase(_cachedNodes.begin());
find(nodes_.begin(), nodes_.end(), node);
if(itr != nodes_.end()) {
nodes_.erase(itr);
nodes_.push_back(cachedNodes_.front());
cachedNodes_.erase(cachedNodes_.begin());
}
}
}
@ -157,26 +157,26 @@ void DHTBucket::dropNode(const SharedHandle<DHTNode>& node)
void DHTBucket::moveToHead(const SharedHandle<DHTNode>& node)
{
std::deque<SharedHandle<DHTNode> >::iterator itr =
std::find(_nodes.begin(), _nodes.end(), node);
if(itr != _nodes.end()) {
_nodes.erase(itr);
_nodes.push_front(node);
std::find(nodes_.begin(), nodes_.end(), node);
if(itr != nodes_.end()) {
nodes_.erase(itr);
nodes_.push_front(node);
}
}
void DHTBucket::moveToTail(const SharedHandle<DHTNode>& node)
{
std::deque<SharedHandle<DHTNode> >::iterator itr =
std::find(_nodes.begin(), _nodes.end(), node);
if(itr != _nodes.end()) {
_nodes.erase(itr);
_nodes.push_back(node);
std::find(nodes_.begin(), nodes_.end(), node);
if(itr != nodes_.end()) {
nodes_.erase(itr);
nodes_.push_back(node);
}
}
bool DHTBucket::splitAllowed() const
{
return _prefixLength < DHT_ID_LENGTH*8-1 && isInRange(_localNode);
return prefixLength_ < DHT_ID_LENGTH*8-1 && isInRange(localNode_);
}
SharedHandle<DHTBucket> DHTBucket::split()
@ -184,35 +184,35 @@ SharedHandle<DHTBucket> DHTBucket::split()
assert(splitAllowed());
unsigned char rMax[DHT_ID_LENGTH];
memcpy(rMax, _max, DHT_ID_LENGTH);
bitfield::flipBit(rMax, DHT_ID_LENGTH, _prefixLength);
memcpy(rMax, max_, DHT_ID_LENGTH);
bitfield::flipBit(rMax, DHT_ID_LENGTH, prefixLength_);
unsigned char rMin[DHT_ID_LENGTH];
memcpy(rMin, _min, DHT_ID_LENGTH);
memcpy(rMin, min_, DHT_ID_LENGTH);
bitfield::flipBit(_min, DHT_ID_LENGTH, _prefixLength);
bitfield::flipBit(min_, DHT_ID_LENGTH, prefixLength_);
++_prefixLength;
SharedHandle<DHTBucket> rBucket(new DHTBucket(_prefixLength,
rMax, rMin, _localNode));
++prefixLength_;
SharedHandle<DHTBucket> rBucket(new DHTBucket(prefixLength_,
rMax, rMin, localNode_));
std::deque<SharedHandle<DHTNode> > lNodes;
for(std::deque<SharedHandle<DHTNode> >::iterator i = _nodes.begin(),
eoi = _nodes.end(); i != eoi; ++i) {
for(std::deque<SharedHandle<DHTNode> >::iterator i = nodes_.begin(),
eoi = nodes_.end(); i != eoi; ++i) {
if(rBucket->isInRange(*i)) {
assert(rBucket->addNode(*i));
} else {
lNodes.push_back(*i);
}
}
_nodes = lNodes;
nodes_ = lNodes;
// TODO create toString() and use it.
if(_logger->debug()) {
_logger->debug("New bucket. prefixLength=%u, Range:%s-%s",
if(logger_->debug()) {
logger_->debug("New bucket. prefixLength=%u, Range:%s-%s",
static_cast<unsigned int>(rBucket->getPrefixLength()),
util::toHex(rBucket->getMinID(), DHT_ID_LENGTH).c_str(),
util::toHex(rBucket->getMaxID(), DHT_ID_LENGTH).c_str());
_logger->debug("Existing bucket. prefixLength=%u, Range:%s-%s",
static_cast<unsigned int>(_prefixLength),
logger_->debug("Existing bucket. prefixLength=%u, Range:%s-%s",
static_cast<unsigned int>(prefixLength_),
util::toHex(getMinID(), DHT_ID_LENGTH).c_str(),
util::toHex(getMaxID(), DHT_ID_LENGTH).c_str());
}
@ -222,7 +222,7 @@ SharedHandle<DHTBucket> DHTBucket::split()
void DHTBucket::getGoodNodes
(std::vector<SharedHandle<DHTNode> >& goodNodes) const
{
goodNodes.insert(goodNodes.end(), _nodes.begin(), _nodes.end());
goodNodes.insert(goodNodes.end(), nodes_.begin(), nodes_.end());
goodNodes.erase(std::remove_if(goodNodes.begin(), goodNodes.end(),
mem_fun_sh(&DHTNode::isBad)), goodNodes.end());
}
@ -233,8 +233,8 @@ SharedHandle<DHTNode> DHTBucket::getNode(const unsigned char* nodeID, const std:
node->setIPAddress(ipaddr);
node->setPort(port);
std::deque<SharedHandle<DHTNode> >::const_iterator itr =
std::find(_nodes.begin(), _nodes.end(), node);
if(itr == _nodes.end()) {
std::find(nodes_.begin(), nodes_.end(), node);
if(itr == nodes_.end()) {
return SharedHandle<DHTNode>();
} else {
return *itr;
@ -243,19 +243,19 @@ SharedHandle<DHTNode> DHTBucket::getNode(const unsigned char* nodeID, const std:
bool DHTBucket::operator==(const DHTBucket& bucket) const
{
return memcmp(_max, bucket._max, DHT_ID_LENGTH) == 0 &&
memcmp(_min, bucket._min, DHT_ID_LENGTH) == 0;
return memcmp(max_, bucket.max_, DHT_ID_LENGTH) == 0 &&
memcmp(min_, bucket.min_, DHT_ID_LENGTH) == 0;
}
bool DHTBucket::needsRefresh() const
{
return _nodes.size() < K ||
_lastUpdated.difference(global::wallclock) >= DHT_BUCKET_REFRESH_INTERVAL;
return nodes_.size() < K ||
lastUpdated_.difference(global::wallclock) >= DHT_BUCKET_REFRESH_INTERVAL;
}
void DHTBucket::notifyUpdate()
{
_lastUpdated = global::wallclock;
lastUpdated_ = global::wallclock;
}
class FindQuestionableNode {
@ -268,14 +268,14 @@ public:
bool DHTBucket::containsQuestionableNode() const
{
return std::find_if(_nodes.begin(), _nodes.end(), FindQuestionableNode()) != _nodes.end();
return std::find_if(nodes_.begin(), nodes_.end(), FindQuestionableNode()) != nodes_.end();
}
SharedHandle<DHTNode> DHTBucket::getLRUQuestionableNode() const
{
std::deque<SharedHandle<DHTNode> >::const_iterator i =
std::find_if(_nodes.begin(), _nodes.end(), FindQuestionableNode());
if(i == _nodes.end()) {
std::find_if(nodes_.begin(), nodes_.end(), FindQuestionableNode());
if(i == nodes_.end()) {
return SharedHandle<DHTNode>();
} else {
return *i;

View File

@ -52,25 +52,25 @@ class Logger;
class DHTBucket {
private:
size_t _prefixLength;
size_t prefixLength_;
// this bucket contains nodes of distance between [_min, _max](inclusive).
unsigned char _min[DHT_ID_LENGTH];
// this bucket contains nodes of distance between [min_, max_](inclusive).
unsigned char min_[DHT_ID_LENGTH];
unsigned char _max[DHT_ID_LENGTH];
unsigned char max_[DHT_ID_LENGTH];
SharedHandle<DHTNode> _localNode;
SharedHandle<DHTNode> localNode_;
// sorted in ascending order
std::deque<SharedHandle<DHTNode> > _nodes;
std::deque<SharedHandle<DHTNode> > nodes_;
// a replacement cache. The maximum size is specified by CACHE_SIZE.
// This is sorted by last time seen.
std::deque<SharedHandle<DHTNode> > _cachedNodes;
std::deque<SharedHandle<DHTNode> > cachedNodes_;
Timer _lastUpdated;
Timer lastUpdated_;
Logger* _logger;
Logger* logger_;
bool isInRange(const unsigned char* nodeID,
const unsigned char* max, const unsigned char* min) const;
@ -103,27 +103,27 @@ public:
size_t getPrefixLength() const
{
return _prefixLength;
return prefixLength_;
}
const unsigned char* getMaxID() const
{
return _max;
return max_;
}
const unsigned char* getMinID() const
{
return _min;
return min_;
}
size_t countNode() const
{
return _nodes.size();
return nodes_.size();
}
const std::deque<SharedHandle<DHTNode> >& getNodes() const
{
return _nodes;
return nodes_;
}
void getGoodNodes(std::vector<SharedHandle<DHTNode> >& nodes) const;
@ -150,7 +150,7 @@ public:
const std::deque<SharedHandle<DHTNode> >& getCachedNodes() const
{
return _cachedNodes;
return cachedNodes_;
}
};

View File

@ -62,25 +62,25 @@ void DHTBucketRefreshCommand::preProcess()
void DHTBucketRefreshCommand::process()
{
_taskQueue->addPeriodicTask1(_taskFactory->createBucketRefreshTask());
taskQueue_->addPeriodicTask1(taskFactory_->createBucketRefreshTask());
}
void DHTBucketRefreshCommand::setRoutingTable
(const SharedHandle<DHTRoutingTable>& routingTable)
{
_routingTable = routingTable;
routingTable_ = routingTable;
}
void DHTBucketRefreshCommand::setTaskQueue
(const SharedHandle<DHTTaskQueue>& taskQueue)
{
_taskQueue = taskQueue;
taskQueue_ = taskQueue;
}
void DHTBucketRefreshCommand::setTaskFactory
(const SharedHandle<DHTTaskFactory>& taskFactory)
{
_taskFactory = taskFactory;
taskFactory_ = taskFactory;
}
} // namespace aria2

View File

@ -46,11 +46,11 @@ class DHTTaskFactory;
class DHTBucketRefreshCommand:public TimeBasedCommand {
private:
SharedHandle<DHTRoutingTable> _routingTable;
SharedHandle<DHTRoutingTable> routingTable_;
SharedHandle<DHTTaskQueue> _taskQueue;
SharedHandle<DHTTaskQueue> taskQueue_;
SharedHandle<DHTTaskFactory> _taskFactory;
SharedHandle<DHTTaskFactory> taskFactory_;
public:
DHTBucketRefreshCommand(cuid_t cuid, DownloadEngine* e, time_t interval);

Some files were not shown because too many files have changed in this diff Show More