2009-05-18 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>

Added source filename(__FILE__) and line number(__LINE__) to
	exception message.	
	* src/AbstractCommand.cc
	* src/AbstractDiskWriter.cc
	* src/AbstractProxyResponseCommand.cc
	* src/BDE.h
	* src/BtAllowedFastMessage.cc
	* src/BtHandshakeMessageValidator.h
	* src/BtHaveAllMessage.cc
	* src/BtHaveNoneMessage.cc
	* src/BtPieceMessage.cc
	* src/BtRejectMessage.cc
	* src/ChunkedDecoder.cc
	* src/CookieStorage.cc
	* src/DHTAnnouncePeerMessage.cc
	* src/DHTEntryPointNameResolveCommand.cc
	* src/DHTMessageFactoryImpl.cc
	* src/DHTMessageTracker.cc
	* src/DHTRoutingTableDeserializer.cc
	* src/DHTRoutingTableSerializer.cc
	* src/DHTSetup.cc
	* src/DHTTokenTracker.cc
	* src/DefaultBtAnnounce.cc
	* src/DefaultBtContext.cc
	* src/DefaultBtInteractive.cc
	* src/DefaultBtMessageFactory.cc
	* src/DefaultBtProgressInfoFile.cc
	* src/DefaultExtensionMessageFactory.cc
	* src/DlAbortEx.h
	* src/DlRetryEx.h
	* src/DownloadCommand.cc
	* src/DownloadEngineFactory.cc
	* src/DownloadFailureException.h
	* src/Exception.cc
	* src/Exception.h
	* src/ExpatMetalinkProcessor.cc
	* src/ExpatXmlRpcRequestProcessor.cc
	* src/FallocFileAllocationIterator.cc
	* src/FatalException.h
	* src/FtpConnection.cc
	* src/FtpFinishDownloadCommand.cc
	* src/FtpInitiateConnectionCommand.cc
	* src/FtpNegotiationCommand.cc
	* src/GZipDecoder.cc
	* src/HandshakeExtensionMessage.cc
	* src/HttpConnection.cc
	* src/HttpHeaderProcessor.cc
	* src/HttpInitiateConnectionCommand.cc
	* src/HttpResponse.cc
	* src/HttpResponseCommand.cc
	* src/HttpServer.cc
	* src/HttpSkipResponseCommand.cc
	* src/InitiateConnectionCommandFactory.cc
	* src/IteratableChunkChecksumValidator.cc
	* src/LibgcryptARC4Context.h
	* src/LibgcryptARC4Decryptor.h
	* src/LibgcryptARC4Encryptor.h
	* src/LibgcryptDHKeyExchange.h
	* src/LibgnutlsTLSContext.cc
	* src/LibsslARC4Context.h
	* src/LibsslARC4Decryptor.h
	* src/LibsslARC4Encryptor.h
	* src/LibsslDHKeyExchange.h
	* src/LibsslTLSContext.cc
	* src/MSEHandshake.cc
	* src/MessageDigestHelper.cc
	* src/MetalinkHelper.cc
	* src/MultiDiskAdaptor.cc
	* src/NameMatchOptionHandler.h
	* src/NameResolver.cc
	* src/Netrc.cc
	* src/NsCookieParser.cc
	* src/OptionHandlerException.cc
	* src/OptionHandlerException.h
	* src/OptionHandlerImpl.h
	* src/OptionParser.cc
	* src/ParameterizedStringParser.cc
	* src/PeerAbstractCommand.cc
	* src/PeerConnection.cc
	* src/PeerMessageUtil.cc
	* src/PeerReceiveHandshakeCommand.cc
	* src/Platform.cc
	* src/ReceiverMSEHandshakeCommand.cc
	* src/RecoverableException.h
	* src/RequestGroup.cc
	* src/SimpleLogger.cc
	* src/SocketCore.cc
	* src/Sqlite3MozCookieParser.cc
	* src/UTPexExtensionMessage.cc
	* src/Util.cc
	* src/XML2SAXMetalinkProcessor.cc
	* src/Xml2XmlRpcRequestProcessor.cc
	* src/XmlRpcMethodImpl.cc
	* src/bencode.cc
	* src/download_helper.cc
	* src/messageDigest.h
	* test/ExceptionTest.cc
	* test/TestUtil.cc
pull/1/head
Tatsuhiro Tsujikawa 2009-05-18 15:07:15 +00:00
parent ff83fc65df
commit 20e215047c
97 changed files with 638 additions and 462 deletions

101
ChangeLog
View File

@ -1,3 +1,104 @@
2009-05-18 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
Added source filename(__FILE__) and line number(__LINE__) to
exception message.
* src/AbstractCommand.cc
* src/AbstractDiskWriter.cc
* src/AbstractProxyResponseCommand.cc
* src/BDE.h
* src/BtAllowedFastMessage.cc
* src/BtHandshakeMessageValidator.h
* src/BtHaveAllMessage.cc
* src/BtHaveNoneMessage.cc
* src/BtPieceMessage.cc
* src/BtRejectMessage.cc
* src/ChunkedDecoder.cc
* src/CookieStorage.cc
* src/DHTAnnouncePeerMessage.cc
* src/DHTEntryPointNameResolveCommand.cc
* src/DHTMessageFactoryImpl.cc
* src/DHTMessageTracker.cc
* src/DHTRoutingTableDeserializer.cc
* src/DHTRoutingTableSerializer.cc
* src/DHTSetup.cc
* src/DHTTokenTracker.cc
* src/DefaultBtAnnounce.cc
* src/DefaultBtContext.cc
* src/DefaultBtInteractive.cc
* src/DefaultBtMessageFactory.cc
* src/DefaultBtProgressInfoFile.cc
* src/DefaultExtensionMessageFactory.cc
* src/DlAbortEx.h
* src/DlRetryEx.h
* src/DownloadCommand.cc
* src/DownloadEngineFactory.cc
* src/DownloadFailureException.h
* src/Exception.cc
* src/Exception.h
* src/ExpatMetalinkProcessor.cc
* src/ExpatXmlRpcRequestProcessor.cc
* src/FallocFileAllocationIterator.cc
* src/FatalException.h
* src/FtpConnection.cc
* src/FtpFinishDownloadCommand.cc
* src/FtpInitiateConnectionCommand.cc
* src/FtpNegotiationCommand.cc
* src/GZipDecoder.cc
* src/HandshakeExtensionMessage.cc
* src/HttpConnection.cc
* src/HttpHeaderProcessor.cc
* src/HttpInitiateConnectionCommand.cc
* src/HttpResponse.cc
* src/HttpResponseCommand.cc
* src/HttpServer.cc
* src/HttpSkipResponseCommand.cc
* src/InitiateConnectionCommandFactory.cc
* src/IteratableChunkChecksumValidator.cc
* src/LibgcryptARC4Context.h
* src/LibgcryptARC4Decryptor.h
* src/LibgcryptARC4Encryptor.h
* src/LibgcryptDHKeyExchange.h
* src/LibgnutlsTLSContext.cc
* src/LibsslARC4Context.h
* src/LibsslARC4Decryptor.h
* src/LibsslARC4Encryptor.h
* src/LibsslDHKeyExchange.h
* src/LibsslTLSContext.cc
* src/MSEHandshake.cc
* src/MessageDigestHelper.cc
* src/MetalinkHelper.cc
* src/MultiDiskAdaptor.cc
* src/NameMatchOptionHandler.h
* src/NameResolver.cc
* src/Netrc.cc
* src/NsCookieParser.cc
* src/OptionHandlerException.cc
* src/OptionHandlerException.h
* src/OptionHandlerImpl.h
* src/OptionParser.cc
* src/ParameterizedStringParser.cc
* src/PeerAbstractCommand.cc
* src/PeerConnection.cc
* src/PeerMessageUtil.cc
* src/PeerReceiveHandshakeCommand.cc
* src/Platform.cc
* src/ReceiverMSEHandshakeCommand.cc
* src/RecoverableException.h
* src/RequestGroup.cc
* src/SimpleLogger.cc
* src/SocketCore.cc
* src/Sqlite3MozCookieParser.cc
* src/UTPexExtensionMessage.cc
* src/Util.cc
* src/XML2SAXMetalinkProcessor.cc
* src/Xml2XmlRpcRequestProcessor.cc
* src/XmlRpcMethodImpl.cc
* src/bencode.cc
* src/download_helper.cc
* src/messageDigest.h
* test/ExceptionTest.cc
* test/TestUtil.cc
2009-05-16 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net> 2009-05-16 Tatsuhiro Tsujikawa <t-tujikawa@users.sourceforge.net>
Bump up version number to 1.4.0 Bump up version number to 1.4.0

View File

@ -140,7 +140,7 @@ bool AbstractCommand::execute() {
} }
return executeInternal(); return executeInternal();
} else if(_errorEvent) { } else if(_errorEvent) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat(MSG_NETWORK_PROBLEM, (StringFormat(MSG_NETWORK_PROBLEM,
socket->getSocketError().c_str()).str()); socket->getSocketError().c_str()).str());
} else { } else {
@ -151,15 +151,15 @@ bool AbstractCommand::execute() {
req->getProtocol()); req->getProtocol());
ss->setError(); ss->setError();
throw DlRetryEx(EX_TIME_OUT, DownloadResult::TIME_OUT); throw DL_RETRY_EX2(EX_TIME_OUT, DownloadResult::TIME_OUT);
} }
e->commands.push_back(this); e->commands.push_back(this);
return false; return false;
} }
} catch(DlAbortEx& err) { } catch(DlAbortEx& err) {
logger->error(MSG_DOWNLOAD_ABORTED, logger->error(MSG_DOWNLOAD_ABORTED,
DlAbortEx(StringFormat DL_ABORT_EX2(StringFormat
("URI=%s", req->getCurrentUrl().c_str()).str(),err), ("URI=%s", req->getCurrentUrl().c_str()).str(),err),
cuid, req->getUrl().c_str()); cuid, req->getUrl().c_str());
_requestGroup->addURIResult(req->getUrl(), err.getCode()); _requestGroup->addURIResult(req->getUrl(), err.getCode());
onAbort(); onAbort();
@ -168,8 +168,8 @@ bool AbstractCommand::execute() {
return true; return true;
} catch(DlRetryEx& err) { } catch(DlRetryEx& err) {
logger->info(MSG_RESTARTING_DOWNLOAD, logger->info(MSG_RESTARTING_DOWNLOAD,
DlRetryEx(StringFormat DL_RETRY_EX2(StringFormat
("URI=%s", req->getCurrentUrl().c_str()).str(),err), ("URI=%s", req->getCurrentUrl().c_str()).str(),err),
cuid, req->getUrl().c_str()); cuid, req->getUrl().c_str());
req->addTryCount(); req->addTryCount();
req->resetRedirectCount(); req->resetRedirectCount();
@ -432,7 +432,7 @@ bool AbstractCommand::asyncResolveHostname()
e->_requestGroupMan->getOrCreateServerStat e->_requestGroupMan->getOrCreateServerStat
(req->getHost(), req->getProtocol())->setError(); (req->getHost(), req->getProtocol())->setError();
} }
throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid, throw DL_ABORT_EX(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
_asyncNameResolver->getHostname().c_str(), _asyncNameResolver->getHostname().c_str(),
_asyncNameResolver->getError().c_str()).str()); _asyncNameResolver->getError().c_str()).str());
default: default:
@ -491,7 +491,7 @@ void AbstractCommand::checkIfConnectionEstablished
e->_requestGroupMan->getOrCreateServerStat e->_requestGroupMan->getOrCreateServerStat
(req->getHost(), req->getProtocol())->setError(); (req->getHost(), req->getProtocol())->setError();
} }
throw DlRetryEx throw DL_RETRY_EX
(StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str()); (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
} }
} }

View File

@ -88,7 +88,7 @@ void AbstractDiskWriter::closeFile()
void AbstractDiskWriter::openExistingFile(uint64_t totalLength) void AbstractDiskWriter::openExistingFile(uint64_t totalLength)
{ {
if(!File(_filename).exists()) { if(!File(_filename).exists()) {
throw DlAbortEx 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());
} }
@ -100,7 +100,7 @@ void AbstractDiskWriter::openExistingFile(uint64_t totalLength)
} }
if((fd = open(_filename.c_str(), flags, OPEN_MODE)) < 0) { if((fd = open(_filename.c_str(), flags, OPEN_MODE)) < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_OPEN, _filename.c_str(), strerror(errno)).str()); (StringFormat(EX_FILE_OPEN, _filename.c_str(), strerror(errno)).str());
} }
} }
@ -111,7 +111,7 @@ void AbstractDiskWriter::createFile(int addFlags)
Util::mkdirs(File(_filename).getDirname()); Util::mkdirs(File(_filename).getDirname());
if((fd = open(_filename.c_str(), O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags, if((fd = open(_filename.c_str(), O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags,
OPEN_MODE)) < 0) { OPEN_MODE)) < 0) {
throw DlAbortEx(StringFormat(EX_FILE_OPEN, throw DL_ABORT_EX(StringFormat(EX_FILE_OPEN,
_filename.c_str(), strerror(errno)).str()); _filename.c_str(), strerror(errno)).str());
} }
} }
@ -140,7 +140,7 @@ ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len)
void AbstractDiskWriter::seek(off_t offset) void AbstractDiskWriter::seek(off_t offset)
{ {
if(lseek(fd, offset, SEEK_SET) == (off_t)-1) { if(lseek(fd, offset, SEEK_SET) == (off_t)-1) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_SEEK, _filename.c_str(), strerror(errno)).str()); (StringFormat(EX_FILE_SEEK, _filename.c_str(), strerror(errno)).str());
} }
} }
@ -152,10 +152,10 @@ void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, off_t
// If errno is ENOSPC(not enough space in device), throw // If errno is ENOSPC(not enough space in device), throw
// DownloadFailureException and abort download instantly. // DownloadFailureException and abort download instantly.
if(errno == ENOSPC) { if(errno == ENOSPC) {
throw DownloadFailureException 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 DlAbortEx(StringFormat(EX_FILE_WRITE, throw DL_ABORT_EX(StringFormat(EX_FILE_WRITE,
_filename.c_str(), strerror(errno)).str()); _filename.c_str(), strerror(errno)).str());
} }
} }
@ -165,7 +165,7 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs
ssize_t ret; ssize_t ret;
seek(offset); seek(offset);
if((ret = readDataInternal(data, len)) < 0) { if((ret = readDataInternal(data, len)) < 0) {
throw DlAbortEx(StringFormat(EX_FILE_READ, throw DL_ABORT_EX(StringFormat(EX_FILE_READ,
_filename.c_str(), strerror(errno)).str()); _filename.c_str(), strerror(errno)).str());
} }
return ret; return ret;
@ -174,7 +174,7 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs
void AbstractDiskWriter::truncate(uint64_t length) void AbstractDiskWriter::truncate(uint64_t length)
{ {
if(fd == -1) { if(fd == -1) {
throw DlAbortEx("File not opened."); throw DL_ABORT_EX("File not opened.");
} }
#ifdef __MINGW32__ #ifdef __MINGW32__
// Since mingw32's ftruncate cannot handle over 2GB files, we use SetEndOfFile // Since mingw32's ftruncate cannot handle over 2GB files, we use SetEndOfFile
@ -182,12 +182,12 @@ void AbstractDiskWriter::truncate(uint64_t length)
HANDLE handle = LongToHandle(_get_osfhandle(fd)); HANDLE handle = LongToHandle(_get_osfhandle(fd));
seek(length); seek(length);
if(SetEndOfFile(handle) == 0) { if(SetEndOfFile(handle) == 0) {
throw DlAbortEx(StringFormat("SetEndOfFile failed. cause: %s", throw DL_ABORT_EX(StringFormat("SetEndOfFile failed. cause: %s",
GetLastError()).str()); GetLastError()).str());
} }
#else #else
if(ftruncate(fd, length) == -1) { if(ftruncate(fd, length) == -1) {
throw DlAbortEx(StringFormat("ftruncate failed. cause: %s", throw DL_ABORT_EX(StringFormat("ftruncate failed. cause: %s",
strerror(errno)).str()); strerror(errno)).str());
} }
#endif #endif
@ -197,11 +197,11 @@ void AbstractDiskWriter::truncate(uint64_t length)
void AbstractDiskWriter::allocate(off_t offset, uint64_t length) void AbstractDiskWriter::allocate(off_t offset, uint64_t length)
{ {
if(fd == -1) { if(fd == -1) {
throw DlAbortEx("File not yet opened."); 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) { if(r != 0) {
throw DlAbortEx(StringFormat("posix_fallocate failed. cause: %s", throw DL_ABORT_EX(StringFormat("posix_fallocate failed. cause: %s",
strerror(r)).str()); strerror(r)).str());
} }
} }

View File

@ -67,7 +67,7 @@ bool AbstractProxyResponseCommand::executeInternal() {
return false; return false;
} }
if(httpResponse->getResponseStatus() != HttpHeader::S200) { if(httpResponse->getResponseStatus() != HttpHeader::S200) {
throw DlRetryEx(EX_PROXY_CONNECTION_FAILED); throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED);
} }
e->commands.push_back(getNextCommand()); e->commands.push_back(getNextCommand());
return true; return true;

View File

@ -42,7 +42,7 @@
#include <deque> #include <deque>
#include "SharedHandle.h" #include "SharedHandle.h"
#include "RecoverableException.h" #include "DlAbortEx.h"
namespace aria2 { namespace aria2 {
@ -72,7 +72,7 @@ private:
// Returns Integer. // Returns Integer.
virtual Integer i() const virtual Integer i() const
{ {
throw RecoverableException("Not Integer"); throw DL_ABORT_EX("Not Integer");
} }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
@ -81,14 +81,14 @@ private:
// Returns std::string. // Returns std::string.
virtual const std::string& s() const virtual const std::string& s() const
{ {
throw RecoverableException("Not String"); throw DL_ABORT_EX("Not String");
} }
// Returns std::string.data() casted to unsigned char*. // Returns std::string.data() casted to unsigned char*.
// Use s().size() to get length. // Use s().size() to get length.
virtual const unsigned char* uc() const virtual const unsigned char* uc() const
{ {
throw RecoverableException("Not String"); throw DL_ABORT_EX("Not String");
} }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
@ -100,33 +100,33 @@ private:
// this is the same behavior of std::map's operator[]. // this is the same behavior of std::map's operator[].
virtual BDE& operator[](const std::string& key) virtual BDE& operator[](const std::string& key)
{ {
throw RecoverableException("Not Dict"); throw DL_ABORT_EX("Not Dict");
} }
// Returns true if the given key is found in dict. // Returns true if the given key is found in dict.
virtual bool containsKey(const std::string& key) const virtual bool containsKey(const std::string& key) const
{ {
throw RecoverableException("Not Dict"); throw DL_ABORT_EX("Not Dict");
} }
// Removes specified key from dict. // Removes specified key from dict.
virtual void removeKey(const std::string& key) virtual void removeKey(const std::string& key)
{ {
throw RecoverableException("Not Dict"); throw DL_ABORT_EX("Not Dict");
} }
// Returns a read/write iterator that points to the first pair in // Returns a read/write iterator that points to the first pair in
// the dict. // the dict.
virtual Dict::iterator dictBegin() virtual Dict::iterator dictBegin()
{ {
throw RecoverableException("Not Dict"); throw DL_ABORT_EX("Not Dict");
} }
// Returns a read/write read-only iterator that points to one past // Returns a read/write read-only iterator that points to one past
// the last pair in the dict. // the last pair in the dict.
virtual Dict::iterator dictEnd() virtual Dict::iterator dictEnd()
{ {
throw RecoverableException("Not Dict"); throw DL_ABORT_EX("Not Dict");
} }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
@ -135,45 +135,45 @@ private:
// Appends given bde to list. // Appends given bde to list.
virtual void append(const BDE& bde) virtual void append(const BDE& bde)
{ {
throw RecoverableException("Not List"); throw DL_ABORT_EX("Not List");
} }
// Alias for append() // Alias for append()
virtual void operator<<(const BDE& bde) virtual void operator<<(const BDE& bde)
{ {
throw RecoverableException("Not List"); throw DL_ABORT_EX("Not List");
} }
// Returns the reference of the object at the given index. // Returns the reference of the object at the given index.
virtual BDE& operator[](size_t index) virtual BDE& operator[](size_t index)
{ {
throw RecoverableException("Not List"); throw DL_ABORT_EX("Not List");
} }
// Returns a read/write iterator that points to the first object // Returns a read/write iterator that points to the first object
// in list. // in list.
virtual List::iterator listBegin() virtual List::iterator listBegin()
{ {
throw RecoverableException("Not List"); throw DL_ABORT_EX("Not List");
} }
// Returns a read/write iterator that points to the one past the // Returns a read/write iterator that points to the one past the
// last object in list. // last object in list.
virtual List::iterator listEnd() virtual List::iterator listEnd()
{ {
throw RecoverableException("Not List"); throw DL_ABORT_EX("Not List");
} }
// Returns size of list or dict. // Returns size of list or dict.
virtual size_t size() const virtual size_t size() const
{ {
throw RecoverableException("Neither Dict nor List"); throw DL_ABORT_EX("Neither Dict nor List");
} }
// Returns true if size of list or dict is 0. // Returns true if size of list or dict is 0.
virtual bool empty() const virtual bool empty() const
{ {
throw RecoverableException("Neither Dict nor List"); throw DL_ABORT_EX("Neither Dict nor List");
} }
}; };

View File

@ -49,7 +49,7 @@ SharedHandle<BtAllowedFastMessage> BtAllowedFastMessage::create
void BtAllowedFastMessage::doReceivedAction() { void BtAllowedFastMessage::doReceivedAction() {
if(!peer->isFastExtensionEnabled()) { if(!peer->isFastExtensionEnabled()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("%s received while fast extension is disabled", (StringFormat("%s received while fast extension is disabled",
toString().c_str()).str()); toString().c_str()).str());
} }

View File

@ -36,11 +36,13 @@
#define _D_BT_HANDSHAKE_MESSAGE_VALIDATOR_H_ #define _D_BT_HANDSHAKE_MESSAGE_VALIDATOR_H_
#include "BtMessageValidator.h" #include "BtMessageValidator.h"
#include <cstring>
#include "BtHandshakeMessage.h" #include "BtHandshakeMessage.h"
#include "Util.h" #include "Util.h"
#include "PeerMessageUtil.h" #include "PeerMessageUtil.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <cstring>
namespace aria2 { namespace aria2 {
@ -59,16 +61,16 @@ public:
virtual bool validate(Errors& error) { virtual bool validate(Errors& error) {
// TODO // TODO
if(message->getPstrlen() != 19) { if(message->getPstrlen() != 19) {
throw DlAbortEx(StringFormat("invalid handshake pstrlen=%u", 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 DlAbortEx throw DL_ABORT_EX
(StringFormat("invalid handshake pstr=%s", (StringFormat("invalid handshake pstr=%s",
Util::urlencode(message->getPstr(), 19).c_str()).str()); Util::urlencode(message->getPstr(), 19).c_str()).str());
} }
if(memcmp(infoHash, message->getInfoHash(), 20) != 0) { if(memcmp(infoHash, message->getInfoHash(), 20) != 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("invalid handshake info hash: expected:%s, actual:%s", (StringFormat("invalid handshake info hash: expected:%s, actual:%s",
Util::toHex(infoHash, 20).c_str(), Util::toHex(infoHash, 20).c_str(),
Util::toHex(message->getInfoHash(), 20).c_str()).str()); Util::toHex(message->getInfoHash(), 20).c_str()).str());

View File

@ -51,7 +51,7 @@ SharedHandle<BtHaveAllMessage> BtHaveAllMessage::create
void BtHaveAllMessage::doReceivedAction() void BtHaveAllMessage::doReceivedAction()
{ {
if(!peer->isFastExtensionEnabled()) { if(!peer->isFastExtensionEnabled()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("%s received while fast extension is disabled", (StringFormat("%s received while fast extension is disabled",
toString().c_str()).str()); toString().c_str()).str());
} }

View File

@ -50,7 +50,7 @@ SharedHandle<BtHaveNoneMessage> BtHaveNoneMessage::create
void BtHaveNoneMessage::doReceivedAction() void BtHaveNoneMessage::doReceivedAction()
{ {
if(!peer->isFastExtensionEnabled()) { if(!peer->isFastExtensionEnabled()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("%s received while fast extension is disabled", (StringFormat("%s received while fast extension is disabled",
toString().c_str()).str()); toString().c_str()).str());
} }

View File

@ -163,7 +163,7 @@ size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
static_cast<ssize_t>(length)) { static_cast<ssize_t>(length)) {
return peerConnection->sendMessage(buf, length); return peerConnection->sendMessage(buf, length);
} else { } else {
throw DlAbortEx(EX_DATA_READ); throw DL_ABORT_EX(EX_DATA_READ);
} }
} }

View File

@ -52,7 +52,7 @@ SharedHandle<BtRejectMessage> BtRejectMessage::create
void BtRejectMessage::doReceivedAction() void BtRejectMessage::doReceivedAction()
{ {
if(!peer->isFastExtensionEnabled()) { if(!peer->isFastExtensionEnabled()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("%s received while fast extension is disabled.", (StringFormat("%s received while fast extension is disabled.",
toString().c_str()).str()); toString().c_str()).str());
} }
@ -61,7 +61,7 @@ void BtRejectMessage::doReceivedAction()
RequestSlot slot = RequestSlot slot =
dispatcher->getOutstandingRequest(getIndex(), getBegin(), getLength()); dispatcher->getOutstandingRequest(getIndex(), getBegin(), getLength());
if(RequestSlot::isNull(slot)) { if(RequestSlot::isNull(slot)) {
//throw DlAbortEx("reject recieved, but it is not in the request slots."); //throw DL_ABORT_EX("reject recieved, but it is not in the request slots.");
} else { } else {
dispatcher->removeOutstandingRequest(slot); dispatcher->removeOutstandingRequest(slot);
} }

View File

@ -75,7 +75,7 @@ static bool readData(std::string& out, uint64_t& chunkSize, std::string& in)
in.erase(0, 2); in.erase(0, 2);
return true; return true;
} else { } else {
throw DlAbortEx(EX_INVALID_CHUNK_SIZE); throw DL_ABORT_EX(EX_INVALID_CHUNK_SIZE);
} }
} else { } else {
return false; return false;

View File

@ -33,17 +33,19 @@
*/ */
/* copyright --> */ /* copyright --> */
#include "CookieStorage.h" #include "CookieStorage.h"
#include <algorithm>
#include <fstream>
#include "Util.h" #include "Util.h"
#include "LogFactory.h" #include "LogFactory.h"
#include "Logger.h" #include "Logger.h"
#include "RecoverableException.h" #include "DlAbortEx.h"
#include "StringFormat.h" #include "StringFormat.h"
#include "NsCookieParser.h" #include "NsCookieParser.h"
#ifdef HAVE_SQLITE3 #ifdef HAVE_SQLITE3
# include "Sqlite3MozCookieParser.h" # include "Sqlite3MozCookieParser.h"
#endif // HAVE_SQLITE3 #endif // HAVE_SQLITE3
#include <algorithm>
#include <fstream>
namespace aria2 { namespace aria2 {
@ -145,7 +147,7 @@ void CookieStorage::load(const std::string& filename)
std::ifstream s(filename.c_str(), std::ios::binary); std::ifstream s(filename.c_str(), std::ios::binary);
s.get(header, sizeof(header)); s.get(header, sizeof(header));
if(s.bad()) { if(s.bad()) {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Failed to read header of cookie file %s", (StringFormat("Failed to read header of cookie file %s",
filename.c_str()).str()); filename.c_str()).str());
} }
@ -155,7 +157,7 @@ void CookieStorage::load(const std::string& filename)
#ifdef HAVE_SQLITE3 #ifdef HAVE_SQLITE3
storeCookies(Sqlite3MozCookieParser().parse(filename)); storeCookies(Sqlite3MozCookieParser().parse(filename));
#else // !HAVE_SQLITE3 #else // !HAVE_SQLITE3
throw RecoverableException throw DL_ABORT_EX
("Cannot read SQLite3 database because SQLite3 support is disabled by" ("Cannot read SQLite3 database because SQLite3 support is disabled by"
" configuration."); " configuration.");
#endif // !HAVE_SQLITE3 #endif // !HAVE_SQLITE3
@ -163,7 +165,7 @@ void CookieStorage::load(const std::string& filename)
storeCookies(NsCookieParser().parse(filename)); storeCookies(NsCookieParser().parse(filename));
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
throw RecoverableException throw DL_ABORT_EX2
(StringFormat("Failed to load cookies from %s", filename.c_str()).str(), (StringFormat("Failed to load cookies from %s", filename.c_str()).str(),
e); e);
} }

View File

@ -104,7 +104,7 @@ void DHTAnnouncePeerMessage::validate() const
if(!_tokenTracker->validateToken(_token, _infoHash, if(!_tokenTracker->validateToken(_token, _infoHash,
_remoteNode->getIPAddress(), _remoteNode->getIPAddress(),
_remoteNode->getPort())) { _remoteNode->getPort())) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Invalid token=%s from %s:%u", (StringFormat("Invalid token=%s from %s:%u",
Util::toHex(_token).c_str(), Util::toHex(_token).c_str(),
_remoteNode->getIPAddress().c_str(), _remoteNode->getIPAddress().c_str(),

View File

@ -159,7 +159,7 @@ bool DHTEntryPointNameResolveCommand::resolveHostname
return true; return true;
break; break;
case AsyncNameResolver::STATUS_ERROR: case AsyncNameResolver::STATUS_ERROR:
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid, (StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
hostname.c_str(), hostname.c_str(),
resolver->getError().c_str()).str()); resolver->getError().c_str()).str());

View File

@ -89,7 +89,7 @@ static const BDE& getDictionary(const BDE& dict,
if(d.isDict()) { if(d.isDict()) {
return d; return d;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
} }
} }
@ -101,7 +101,7 @@ static const BDE& getString(const BDE& dict,
if(c.isString()) { if(c.isString()) {
return c; return c;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
} }
} }
@ -113,7 +113,7 @@ static const BDE& getInteger(const BDE& dict,
if(c.isInteger()) { if(c.isInteger()) {
return c; return c;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
} }
} }
@ -124,7 +124,7 @@ static const BDE& getString(const BDE& list, size_t index)
if(c.isString()) { if(c.isString()) {
return c; return c;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. element[%u] is not String.", (StringFormat("Malformed DHT message. element[%u] is not String.",
index).str()); index).str());
} }
@ -136,7 +136,7 @@ static const BDE& getInteger(const BDE& list, size_t index)
if(c.isInteger()) { if(c.isInteger()) {
return c; return c;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. element[%u] is not Integer.", (StringFormat("Malformed DHT message. element[%u] is not Integer.",
index).str()); index).str());
} }
@ -149,7 +149,7 @@ static const BDE& getList(const BDE& dict,
if(l.isList()) { if(l.isList()) {
return l; return l;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
} }
} }
@ -157,7 +157,7 @@ static const BDE& getList(const BDE& dict,
void DHTMessageFactoryImpl::validateID(const BDE& id) const void DHTMessageFactoryImpl::validateID(const BDE& id) const
{ {
if(id.s().size() != DHT_ID_LENGTH) { if(id.s().size() != DHT_ID_LENGTH) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. Invalid ID length." (StringFormat("Malformed DHT message. Invalid ID length."
" Expected:%d, Actual:%d", " Expected:%d, Actual:%d",
DHT_ID_LENGTH, id.s().size()).str()); DHT_ID_LENGTH, id.s().size()).str());
@ -168,7 +168,7 @@ void DHTMessageFactoryImpl::validatePort(const BDE& i) const
{ {
BDE::Integer port = i.i(); BDE::Integer port = i.i();
if(!(0 < port && port < UINT16_MAX)) { if(!(0 < port && port < UINT16_MAX)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. Invalid port=%s", (StringFormat("Malformed DHT message. Invalid port=%s",
Util::itos(port).c_str()).str()); Util::itos(port).c_str()).str());
} }
@ -184,7 +184,7 @@ SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage
const BDE& y = getString(dict, DHTMessage::Y); const BDE& y = getString(dict, DHTMessage::Y);
const BDE& aDict = getDictionary(dict, DHTQueryMessage::A); const BDE& aDict = getDictionary(dict, DHTQueryMessage::A);
if(y.s() != DHTQueryMessage::Q) { if(y.s() != DHTQueryMessage::Q) {
throw DlAbortEx("Malformed DHT message. y != q"); throw DL_ABORT_EX("Malformed DHT message. y != q");
} }
const BDE& id = getString(aDict, DHTMessage::ID); const BDE& id = getString(aDict, DHTMessage::ID);
validateID(id); validateID(id);
@ -214,7 +214,7 @@ SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage
static_cast<uint16_t>(port.i()), static_cast<uint16_t>(port.i()),
token.s(), transactionID.s()); token.s(), transactionID.s());
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Unsupported message type: %s", (StringFormat("Unsupported message type: %s",
messageType.s().c_str()).str()); messageType.s().c_str()).str());
} }
@ -238,9 +238,9 @@ DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
} else { } else {
_logger->debug("e doesn't have 2 elements."); _logger->debug("e doesn't have 2 elements.");
} }
throw DlAbortEx("Received Error DHT message."); throw DL_ABORT_EX("Received Error DHT message.");
} else if(y.s() != DHTResponseMessage::R) { } else if(y.s() != DHTResponseMessage::R) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Malformed DHT message. y != r: y=%s", (StringFormat("Malformed DHT message. y != r: y=%s",
Util::urlencode(y.s()).c_str()).str()); Util::urlencode(y.s()).c_str()).str());
} }
@ -264,13 +264,13 @@ DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
return createGetPeersReplyMessageWithNodes(remoteNode, dict, return createGetPeersReplyMessageWithNodes(remoteNode, dict,
transactionID.s()); transactionID.s());
} else { } else {
throw DlAbortEx("Malformed DHT message: missing nodes/values"); throw DL_ABORT_EX("Malformed DHT message: missing nodes/values");
} }
} }
} else if(messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) { } else if(messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) {
return createAnnouncePeerReplyMessage(remoteNode, transactionID.s()); return createAnnouncePeerReplyMessage(remoteNode, transactionID.s());
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Unsupported message type: %s", messageType.c_str()).str()); (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
} }
} }
@ -326,7 +326,7 @@ std::deque<SharedHandle<DHTNode> >
DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length) DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length)
{ {
if(length%26 != 0) { if(length%26 != 0) {
throw DlAbortEx("Nodes length is not multiple of 26"); throw DL_ABORT_EX("Nodes length is not multiple of 26");
} }
std::deque<SharedHandle<DHTNode> > nodes; std::deque<SharedHandle<DHTNode> > nodes;
for(size_t offset = 0; offset < length; offset += 26) { for(size_t offset = 0; offset < length; offset += 26) {

View File

@ -74,7 +74,7 @@ DHTMessageTracker::messageArrived(const BDE& dict,
{ {
const BDE& tid = dict[DHTMessage::T]; const BDE& tid = dict[DHTMessage::T];
if(!tid.isString()) { if(!tid.isString()) {
throw DlAbortEx(StringFormat("Malformed DHT message. From:%s:%u", throw DL_ABORT_EX(StringFormat("Malformed DHT message. From:%s:%u",
ipaddr.c_str(), port).str()); ipaddr.c_str(), port).str());
} }
_logger->debug("Searching tracker entry for TransactionID=%s, Remote=%s:%u", _logger->debug("Searching tracker entry for TransactionID=%s, Remote=%s:%u",

View File

@ -114,7 +114,7 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in)
} else if(memcmp(headerCompat, buf, 8) == 0) { } else if(memcmp(headerCompat, buf, 8) == 0) {
version = 2; version = 2;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Failed to load DHT routing table. cause:%s", (StringFormat("Failed to load DHT routing table. cause:%s",
"bad header").str()); "bad header").str());
} }
@ -192,7 +192,7 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in)
_localNode = localNode; _localNode = localNode;
} catch(std::ios::failure const& exception) { } catch(std::ios::failure const& exception) {
_nodes.clear(); _nodes.clear();
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Failed to load DHT routing table. cause:%s", (StringFormat("Failed to load DHT routing table. cause:%s",
strerror(errno)).str()); strerror(errno)).str());
} }

View File

@ -121,7 +121,7 @@ void DHTRoutingTableSerializer::serialize(std::ostream& o)
o.write(zero, 4); o.write(zero, 4);
} }
} catch(std::ios::failure const& exception) { } catch(std::ios::failure const& exception) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Failed to save DHT routing table. cause:%s", (StringFormat("Failed to save DHT routing table. cause:%s",
strerror(errno)).str()); strerror(errno)).str());
} }

View File

@ -114,7 +114,7 @@ void DHTSetup::setup(std::deque<Command*>& commands,
IntSequence seq = Util::parseIntRange(option->get(PREF_DHT_LISTEN_PORT)); IntSequence seq = Util::parseIntRange(option->get(PREF_DHT_LISTEN_PORT));
uint16_t port; uint16_t port;
if(!connection->bind(port, seq)) { if(!connection->bind(port, seq)) {
throw DlAbortEx("Error occurred while binding port for DHT"); throw DL_ABORT_EX("Error occurred while binding port for DHT");
} }
localNode->setPort(port); localNode->setPort(port);
} }

View File

@ -63,7 +63,7 @@ std::string DHTTokenTracker::generateToken(const unsigned char* infoHash,
{ {
unsigned char src[DHT_ID_LENGTH+6+SECRET_SIZE]; unsigned char src[DHT_ID_LENGTH+6+SECRET_SIZE];
if(!PeerMessageUtil::createcompact(src+DHT_ID_LENGTH, ipaddr, port)) { if(!PeerMessageUtil::createcompact(src+DHT_ID_LENGTH, ipaddr, port)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Token generation failed: ipaddr=%s, port=%u", (StringFormat("Token generation failed: ipaddr=%s, port=%u",
ipaddr.c_str(), port).str()); ipaddr.c_str(), port).str());
} }

View File

@ -207,11 +207,11 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse,
const BDE dict = const BDE dict =
bencode::decode(trackerResponse, trackerResponseLength); bencode::decode(trackerResponse, trackerResponseLength);
if(!dict.isDict()) { if(!dict.isDict()) {
throw DlAbortEx(MSG_NULL_TRACKER_RESPONSE); throw DL_ABORT_EX(MSG_NULL_TRACKER_RESPONSE);
} }
const BDE& failure = dict[BtAnnounce::FAILURE_REASON]; const BDE& failure = dict[BtAnnounce::FAILURE_REASON];
if(failure.isString()) { if(failure.isString()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_TRACKER_FAILURE, failure.s().c_str()).str()); (StringFormat(EX_TRACKER_FAILURE, failure.s().c_str()).str());
} }
const BDE& warn = dict[BtAnnounce::WARNING_MESSAGE]; const BDE& warn = dict[BtAnnounce::WARNING_MESSAGE];

View File

@ -141,14 +141,14 @@ void DefaultBtContext::extractFileEntries(const BDE& infoDict,
const BDE& fileLengthData = fileDict[BtContext::C_LENGTH]; const BDE& fileLengthData = fileDict[BtContext::C_LENGTH];
if(!fileLengthData.isInteger()) { if(!fileLengthData.isInteger()) {
throw DlAbortEx(StringFormat(MSG_MISSING_BT_INFO, throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
BtContext::C_LENGTH.c_str()).str()); BtContext::C_LENGTH.c_str()).str());
} }
length += fileLengthData.i(); length += fileLengthData.i();
const BDE& pathList = fileDict[BtContext::C_PATH]; const BDE& pathList = fileDict[BtContext::C_PATH];
if(!pathList.isList() || pathList.empty()) { if(!pathList.isList() || pathList.empty()) {
throw DlAbortEx("Path is empty."); throw DL_ABORT_EX("Path is empty.");
} }
std::vector<std::string> pathelem(pathList.size()); std::vector<std::string> pathelem(pathList.size());
@ -176,7 +176,7 @@ void DefaultBtContext::extractFileEntries(const BDE& infoDict,
fileMode = BtContext::SINGLE; fileMode = BtContext::SINGLE;
const BDE& lengthData = infoDict[BtContext::C_LENGTH]; const BDE& lengthData = infoDict[BtContext::C_LENGTH];
if(!lengthData.isInteger()) { if(!lengthData.isInteger()) {
throw DlAbortEx(StringFormat(MSG_MISSING_BT_INFO, throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
BtContext::C_LENGTH.c_str()).str()); BtContext::C_LENGTH.c_str()).str());
} }
totalLength = lengthData.i(); totalLength = lengthData.i();
@ -310,11 +310,11 @@ void DefaultBtContext::processRootDictionary(const BDE& rootDict,
{ {
clear(); clear();
if(!rootDict.isDict()) { if(!rootDict.isDict()) {
throw DlAbortEx("torrent file does not contain a root dictionary."); throw DL_ABORT_EX("torrent file does not contain a root dictionary.");
} }
const BDE& infoDict = rootDict[BtContext::C_INFO]; const BDE& infoDict = rootDict[BtContext::C_INFO];
if(!infoDict.isDict()) { if(!infoDict.isDict()) {
throw DlAbortEx(StringFormat(MSG_MISSING_BT_INFO, throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
BtContext::C_INFO.c_str()).str()); BtContext::C_INFO.c_str()).str());
} }
// retrieve infoHash // retrieve infoHash
@ -327,20 +327,20 @@ void DefaultBtContext::processRootDictionary(const BDE& rootDict,
// calculate the number of pieces // calculate the number of pieces
const BDE& piecesData = infoDict[BtContext::C_PIECES]; const BDE& piecesData = infoDict[BtContext::C_PIECES];
if(!piecesData.isString()) { if(!piecesData.isString()) {
throw DlAbortEx(StringFormat(MSG_MISSING_BT_INFO, throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
BtContext::C_PIECES.c_str()).str()); BtContext::C_PIECES.c_str()).str());
} }
if(piecesData.s().empty()) { if(piecesData.s().empty()) {
throw DlAbortEx("The length of piece hash is 0."); throw DL_ABORT_EX("The length of piece hash is 0.");
} }
numPieces = piecesData.s().size()/PIECE_HASH_LENGTH; numPieces = piecesData.s().size()/PIECE_HASH_LENGTH;
if(numPieces == 0) { if(numPieces == 0) {
throw DlAbortEx("The number of pieces is 0."); throw DL_ABORT_EX("The number of pieces is 0.");
} }
// retrieve piece length // retrieve piece length
const BDE& pieceLengthData = infoDict[BtContext::C_PIECE_LENGTH]; const BDE& pieceLengthData = infoDict[BtContext::C_PIECE_LENGTH];
if(!pieceLengthData.isInteger()) { if(!pieceLengthData.isInteger()) {
throw DlAbortEx(StringFormat(MSG_MISSING_BT_INFO, throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
BtContext::C_PIECE_LENGTH.c_str()).str()); BtContext::C_PIECE_LENGTH.c_str()).str());
} }
pieceLength = pieceLengthData.i(); pieceLength = pieceLengthData.i();
@ -360,7 +360,7 @@ void DefaultBtContext::processRootDictionary(const BDE& rootDict,
// retrieve file entries // retrieve file entries
extractFileEntries(infoDict, defaultName, overrideName, urlList); extractFileEntries(infoDict, defaultName, overrideName, urlList);
if((totalLength+pieceLength-1)/pieceLength != numPieces) { if((totalLength+pieceLength-1)/pieceLength != numPieces) {
throw DlAbortEx("Too few/many piece hash."); throw DL_ABORT_EX("Too few/many piece hash.");
} }
// retrieve announce // retrieve announce
extractAnnounce(rootDict); extractAnnounce(rootDict);
@ -509,7 +509,7 @@ void DefaultBtContext::setFilePathWithIndex
if(0 < index && index <= fileEntries.size()) { if(0 < index && index <= fileEntries.size()) {
fileEntries[index-1]->setPath(path); fileEntries[index-1]->setPath(path);
} else { } else {
throw DlAbortEx(StringFormat("No such file with index=%u", throw DL_ABORT_EX(StringFormat("No such file with index=%u",
static_cast<unsigned int>(index)).str()); static_cast<unsigned int>(index)).str());
} }
} }

View File

@ -102,7 +102,7 @@ BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) {
} }
if(memcmp(message->getPeerId(), _btContext->getPeerId(), if(memcmp(message->getPeerId(), _btContext->getPeerId(),
PEER_ID_LENGTH) == 0) { PEER_ID_LENGTH) == 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat (StringFormat
("CUID#%d - Drop connection from the same Peer ID", cuid).str()); ("CUID#%d - Drop connection from the same Peer ID", cuid).str());
} }
@ -369,7 +369,7 @@ void DefaultBtInteractive::detectMessageFlooding() {
if(floodingCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) { if(floodingCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) {
if(floodingStat.getChokeUnchokeCount() >= 2 || if(floodingStat.getChokeUnchokeCount() >= 2 ||
floodingStat.getKeepAliveCount() >= 2) { floodingStat.getKeepAliveCount() >= 2) {
throw DlAbortEx(EX_FLOODING_DETECTED); throw DL_ABORT_EX(EX_FLOODING_DETECTED);
} else { } else {
floodingStat.reset(); floodingStat.reset();
} }
@ -386,7 +386,7 @@ void DefaultBtInteractive::checkActiveInteraction()
if(!peer->amInterested() && !peer->peerInterested() && if(!peer->amInterested() && !peer->peerInterested() &&
inactiveCheckPoint.elapsed(interval)) { inactiveCheckPoint.elapsed(interval)) {
// TODO change the message // TODO change the message
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Disconnect peer because we are not interested each other" (StringFormat("Disconnect peer because we are not interested each other"
" after %u second(s).", interval).str()); " after %u second(s).", interval).str());
} }
@ -397,7 +397,7 @@ void DefaultBtInteractive::checkActiveInteraction()
{ {
time_t interval = 2*60; time_t interval = 2*60;
if(inactiveCheckPoint.elapsed(interval)) { if(inactiveCheckPoint.elapsed(interval)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_DROP_INACTIVE_CONNECTION, interval).str()); (StringFormat(EX_DROP_INACTIVE_CONNECTION, interval).str());
} }
} }

View File

@ -204,12 +204,12 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
msg = BtExtendedMessage::create(_extensionMessageFactory, msg = BtExtendedMessage::create(_extensionMessageFactory,
peer, data, dataLength); peer, data, dataLength);
} else { } else {
throw DlAbortEx("Received extended message from peer during a session with extended messaging disabled."); throw DL_ABORT_EX("Received extended message from peer during a session with extended messaging disabled.");
} }
break; break;
} }
default: default:
throw DlAbortEx(StringFormat("Invalid message ID. id=%u", id).str()); throw DL_ABORT_EX(StringFormat("Invalid message ID. id=%u", id).str());
} }
} }
setCommonProperty(msg); setCommonProperty(msg);

View File

@ -183,11 +183,11 @@ void DefaultBtProgressInfoFile::save() {
_logger->info(MSG_SAVED_SEGMENT_FILE); _logger->info(MSG_SAVED_SEGMENT_FILE);
} catch(std::ios::failure const& exception) { } catch(std::ios::failure const& exception) {
// TODO std::ios::failure doesn't give us the reasons of failure... // TODO std::ios::failure doesn't give us the reasons of failure...
throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE, throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_WRITE,
_filename.c_str(), strerror(errno)).str()); _filename.c_str(), strerror(errno)).str());
} }
if(!File(filenameTemp).renameTo(_filename)) { if(!File(filenameTemp).renameTo(_filename)) {
throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE, throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_WRITE,
_filename.c_str(), strerror(errno)).str()); _filename.c_str(), strerror(errno)).str());
} }
} }
@ -212,7 +212,7 @@ void DefaultBtProgressInfoFile::load()
} else if(DefaultBtProgressInfoFile::V0001 == versionHex) { } else if(DefaultBtProgressInfoFile::V0001 == versionHex) {
version = 1; version = 1;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Unsupported ctrl file version: %s", (StringFormat("Unsupported ctrl file version: %s",
versionHex.c_str()).str()); versionHex.c_str()).str());
} }
@ -232,7 +232,7 @@ void DefaultBtProgressInfoFile::load()
} }
if((infoHashLength < 0) || if((infoHashLength < 0) ||
((infoHashLength == 0) && infoHashCheckEnabled)) { ((infoHashLength == 0) && infoHashCheckEnabled)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Invalid info hash length: %d", infoHashLength).str()); (StringFormat("Invalid info hash length: %d", infoHashLength).str());
} }
if(infoHashLength > 0) { if(infoHashLength > 0) {
@ -242,7 +242,7 @@ void DefaultBtProgressInfoFile::load()
if(infoHashCheckEnabled && if(infoHashCheckEnabled &&
Util::toHex(savedInfoHash, infoHashLength) != Util::toHex(savedInfoHash, infoHashLength) !=
btContext->getInfoHashAsString()) { btContext->getInfoHashAsString()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("info hash mismatch. expected: %s, actual: %s", (StringFormat("info hash mismatch. expected: %s, actual: %s",
btContext->getInfoHashAsString().c_str(), btContext->getInfoHashAsString().c_str(),
Util::toHex(savedInfoHash, Util::toHex(savedInfoHash,
@ -264,7 +264,7 @@ void DefaultBtProgressInfoFile::load()
totalLength = ntoh64(totalLength); totalLength = ntoh64(totalLength);
} }
if(totalLength != _dctx->getTotalLength()) { if(totalLength != _dctx->getTotalLength()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("total length mismatch. expected: %s, actual: %s", (StringFormat("total length mismatch. expected: %s, actual: %s",
Util::itos(_dctx->getTotalLength()).c_str(), Util::itos(_dctx->getTotalLength()).c_str(),
Util::itos(totalLength).c_str()).str()); Util::itos(totalLength).c_str()).str());
@ -288,7 +288,7 @@ void DefaultBtProgressInfoFile::load()
uint32_t expectedBitfieldLength = uint32_t expectedBitfieldLength =
((totalLength+pieceLength-1)/pieceLength+7)/8; ((totalLength+pieceLength-1)/pieceLength+7)/8;
if(expectedBitfieldLength != bitfieldLength) { if(expectedBitfieldLength != bitfieldLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("bitfield length mismatch. expected: %d, actual: %d", (StringFormat("bitfield length mismatch. expected: %d, actual: %d",
expectedBitfieldLength, expectedBitfieldLength,
bitfieldLength).str()); bitfieldLength).str());
@ -316,7 +316,7 @@ void DefaultBtProgressInfoFile::load()
index = ntohl(index); index = ntohl(index);
} }
if(!(index < _dctx->getNumPieces())) { if(!(index < _dctx->getNumPieces())) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("piece index out of range: %u", index).str()); (StringFormat("piece index out of range: %u", index).str());
} }
uint32_t length; uint32_t length;
@ -325,7 +325,7 @@ void DefaultBtProgressInfoFile::load()
length = ntohl(length); length = ntohl(length);
} }
if(!(length <=_dctx->getPieceLength())) { if(!(length <=_dctx->getPieceLength())) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("piece length out of range: %u", length).str()); (StringFormat("piece length out of range: %u", length).str());
} }
PieceHandle piece(new Piece(index, length)); PieceHandle piece(new Piece(index, length));
@ -336,7 +336,7 @@ void DefaultBtProgressInfoFile::load()
bitfieldLength = ntohl(bitfieldLength); bitfieldLength = ntohl(bitfieldLength);
} }
if(piece->getBitfieldLength() != bitfieldLength) { if(piece->getBitfieldLength() != bitfieldLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("piece bitfield length mismatch." (StringFormat("piece bitfield length mismatch."
" expected: %u actual: %u", " expected: %u actual: %u",
piece->getBitfieldLength(), bitfieldLength).str()); piece->getBitfieldLength(), bitfieldLength).str());
@ -368,7 +368,7 @@ void DefaultBtProgressInfoFile::load()
src.setBitfield(savedBitfield, bitfieldLength); src.setBitfield(savedBitfield, bitfieldLength);
if((src.getCompletedLength() || numInFlightPiece) && if((src.getCompletedLength() || numInFlightPiece) &&
!_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) { !_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
("WARNING: Detected a change in piece length. You can proceed with" ("WARNING: Detected a change in piece length. You can proceed with"
" --allow-piece-length-change=true, but you may lose some download" " --allow-piece-length-change=true, but you may lose some download"
" progress."); " progress.");
@ -384,7 +384,7 @@ void DefaultBtProgressInfoFile::load()
delete [] savedBitfield; delete [] savedBitfield;
delete [] savedInfoHash; delete [] savedInfoHash;
// TODO std::ios::failure doesn't give us the reasons of failure... // TODO std::ios::failure doesn't give us the reasons of failure...
throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_READ, throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_READ,
_filename.c_str(), strerror(errno)).str()); _filename.c_str(), strerror(errno)).str());
} }
} }

View File

@ -73,7 +73,7 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t
} else { } else {
std::string extensionName = _registry->getExtensionName(extensionMessageID); std::string extensionName = _registry->getExtensionName(extensionMessageID);
if(extensionName.empty()) { if(extensionName.empty()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("No extension registered for extended message ID %u", (StringFormat("No extension registered for extended message ID %u",
extensionMessageID).str()); extensionMessageID).str());
} }
@ -84,7 +84,7 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t
m->setPeerStorage(_peerStorage); m->setPeerStorage(_peerStorage);
return m; return m;
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Unsupported extension message received. extensionMessageID=%u, extensionName=%s", (StringFormat("Unsupported extension message received. extensionMessageID=%u, extensionName=%s",
extensionMessageID, extensionName.c_str()).str()); extensionMessageID, extensionName.c_str()).str());
} }

View File

@ -46,14 +46,21 @@ protected:
return e; return e;
} }
public: public:
DlAbortEx(const std::string& msg):RecoverableException(msg) {} DlAbortEx(const char* file, int line, const std::string& msg):
DlAbortEx(const std::string& msg, RecoverableException(file, line, msg) {}
const Exception& cause):RecoverableException(msg, cause) {} DlAbortEx(const char* file, int line, const std::string& msg,
DlAbortEx(const RecoverableException& e):RecoverableException(e) {} const Exception& cause):
DlAbortEx(const std::string& msg, DownloadResult::RESULT code): RecoverableException(file, line, msg, cause) {}
RecoverableException(msg, code) {} DlAbortEx(const char* file, int line, const RecoverableException& e):
RecoverableException(file, line, e) {}
DlAbortEx(const char* file, int line, const std::string& msg,
DownloadResult::RESULT code):
RecoverableException(file, line, msg, code) {}
}; };
#define DL_ABORT_EX(arg) DlAbortEx(__FILE__, __LINE__, arg)
#define DL_ABORT_EX2(arg1, arg2) DlAbortEx(__FILE__, __LINE__, arg1, arg2)
} // namespace aria2 } // namespace aria2
#endif // _D_DL_ABORT_EX_H_ #endif // _D_DL_ABORT_EX_H_

View File

@ -46,14 +46,21 @@ protected:
return e; return e;
} }
public: public:
DlRetryEx(const std::string& msg):RecoverableException(msg) {} DlRetryEx(const char* file, int line, const std::string& msg):
DlRetryEx(const std::string& msg, RecoverableException(file, line, msg) {}
const Exception& cause):RecoverableException(msg, cause) {} DlRetryEx(const char* file, int line, const std::string& msg,
DlRetryEx(const DlRetryEx& e):RecoverableException(e) {} const Exception& cause):
DlRetryEx(const std::string& msg, DownloadResult::RESULT code): RecoverableException(file, line, msg, cause) {}
RecoverableException(msg, code) {} DlRetryEx(const char* file, int line, const DlRetryEx& e):
RecoverableException(file, line, e) {}
DlRetryEx(const char* file, int line, const std::string& msg,
DownloadResult::RESULT code):
RecoverableException(file, line, msg, code) {}
}; };
#define DL_RETRY_EX(arg) DlRetryEx(__FILE__, __LINE__, arg)
#define DL_RETRY_EX2(arg1, arg2) DlRetryEx(__FILE__, __LINE__, arg1, arg2)
} // namespace aria2 } // namespace aria2
#endif // _D_DL_RETRY_EX_H_ #endif // _D_DL_RETRY_EX_H_

View File

@ -184,7 +184,7 @@ bool DownloadCommand::executeInternal() {
if(!segmentComplete && bufSize == 0 && if(!segmentComplete && bufSize == 0 &&
!socket->wantRead() && !socket->wantWrite()) { !socket->wantRead() && !socket->wantWrite()) {
throw DlRetryEx(EX_GOT_EOF); throw DL_RETRY_EX(EX_GOT_EOF);
} }
if(segmentComplete) { if(segmentComplete) {
@ -236,10 +236,11 @@ void DownloadCommand::checkLowestDownloadSpeed() const
if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) { if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
unsigned int nowSpeed = peerStat->calculateDownloadSpeed(); unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) { if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) {
throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED, throw DL_ABORT_EX2(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
nowSpeed, nowSpeed,
lowestDownloadSpeedLimit, lowestDownloadSpeedLimit,
req->getHost().c_str()).str(), DownloadResult::TOO_SLOW_DOWNLOAD_SPEED); req->getHost().c_str()).str(),
DownloadResult::TOO_SLOW_DOWNLOAD_SPEED);
} }
} }
} }
@ -294,7 +295,7 @@ void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment,
actualPieceHash.c_str()); actualPieceHash.c_str());
segment->clear(); segment->clear();
_requestGroup->getSegmentMan()->cancelSegment(cuid); _requestGroup->getSegmentMan()->cancelSegment(cuid);
throw DlRetryEx throw DL_RETRY_EX
(StringFormat("Invalid checksum index=%d", segment->getIndex()).str()); (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
} }
} }

View File

@ -98,7 +98,7 @@ DownloadEngineFactory::newDownloadEngine(Option* op,
if(ep->good()) { if(ep->good()) {
eventPoll = ep; eventPoll = ep;
} else { } else {
throw DlAbortEx("Initializing EpollEventPoll failed." throw DL_ABORT_EX("Initializing EpollEventPoll failed."
" Try --event-poll=select"); " Try --event-poll=select");
} }
} else } else

View File

@ -50,16 +50,24 @@ protected:
return e; return e;
} }
public: public:
DownloadFailureException(const std::string& msg):RecoverableException(msg) {} DownloadFailureException(const char* file, int line, const std::string& msg):
DownloadFailureException(const std::string& msg, RecoverableException(file, line, msg) {}
DownloadFailureException(const char* file, int line, const std::string& msg,
const Exception& cause): const Exception& cause):
RecoverableException(msg, cause) {} RecoverableException(file, line, msg, cause) {}
DownloadFailureException(const DownloadFailureException& e): DownloadFailureException(const char* file, int line,
RecoverableException(e) {} const DownloadFailureException& e):
DownloadFailureException(const std::string& msg, DownloadResult::RESULT code): RecoverableException(file, line, e) {}
RecoverableException(msg, code) {} DownloadFailureException(const char* file, int line,
const std::string& msg, DownloadResult::RESULT code):
RecoverableException(file, line, msg, code) {}
}; };
#define DOWNLOAD_FAILURE_EXCEPTION(arg)\
DownloadFailureException(__FILE__, __LINE__, arg)
#define DOWNLOAD_FAILURE_EXCEPTION2(arg1, arg2)\
DownloadFailureException(__FILE__, __LINE__, arg1, arg2)
} // namespace aria2 } // namespace aria2
#endif // _D_DOWNLOAD_FAILURE_EXCEPTION_H_ #endif // _D_DOWNLOAD_FAILURE_EXCEPTION_H_

View File

@ -34,15 +34,19 @@
/* copyright --> */ /* copyright --> */
#include "Exception.h" #include "Exception.h"
#include <sstream>
namespace aria2 { namespace aria2 {
Exception::Exception(const std::string& msg):exception(), _msg(msg) {} Exception::Exception(const char* file, int line, const std::string& msg):
_file(file), _line(line), _msg(msg) {}
Exception::Exception(const std::string& msg, Exception::Exception(const char* file, int line, const std::string& msg,
const Exception& cause): const Exception& cause):
exception(), _msg(msg), _cause(cause.copy()) {} _file(file), _line(line), _msg(msg), _cause(cause.copy()) {}
Exception::Exception(const Exception& e):_msg(e._msg), _cause(e._cause) Exception::Exception(const char* file, int line, const Exception& e):
_file(file), _line(line), _msg(e._msg), _cause(e._cause)
{} {}
Exception::~Exception() throw() {} Exception::~Exception() throw() {}
@ -54,17 +58,15 @@ const char* Exception::what() const throw()
std::string Exception::stackTrace() const throw() std::string Exception::stackTrace() const throw()
{ {
std::string stackTrace = "Exception: "; std::stringstream s;
stackTrace += what(); s << "Exception: " << "[" << _file << ":" << _line << "] " << what() << "\n";
stackTrace += "\n";
SharedHandle<Exception> e = _cause; SharedHandle<Exception> e = _cause;
while(!e.isNull()) { while(!e.isNull()) {
stackTrace += " -> "; s << " -> " << "[" << e->_file << ":" << e->_line << "] "
stackTrace += e->what(); << e->what() << "\n";
stackTrace += "\n";
e = e->_cause; e = e->_cause;
} }
return stackTrace; return s.str();
} }
} // namespace aria2 } // namespace aria2

View File

@ -43,6 +43,10 @@ namespace aria2 {
class Exception:public std::exception { class Exception:public std::exception {
private: private:
const char* _file;
int _line;
std::string _msg; std::string _msg;
SharedHandle<Exception> _cause; SharedHandle<Exception> _cause;
@ -51,11 +55,12 @@ protected:
virtual SharedHandle<Exception> copy() const = 0; virtual SharedHandle<Exception> copy() const = 0;
public: public:
explicit Exception(const std::string& msg); explicit Exception(const char* file, int line, const std::string& msg);
Exception(const std::string& msg, const Exception& cause); Exception(const char* file, int line, const std::string& msg,
const Exception& cause);
Exception(const Exception& e); Exception(const char* file, int line, const Exception& e);
virtual ~Exception() throw(); virtual ~Exception() throw();

View File

@ -123,12 +123,12 @@ MetalinkProcessor::parseFromBinaryStream(const SharedHandle<BinaryStream>& binar
break; break;
} }
if(XML_Parse(parser, (const char*)buf, res, 0) == XML_STATUS_ERROR) { if(XML_Parse(parser, (const char*)buf, res, 0) == XML_STATUS_ERROR) {
throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); throw DL_ABORT_EX(MSG_CANNOT_PARSE_METALINK);
} }
readOffset += res; readOffset += res;
} }
if(XML_Parse(parser, 0, 0, 1) == XML_STATUS_ERROR) { if(XML_Parse(parser, 0, 0, 1) == XML_STATUS_ERROR) {
throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); throw DL_ABORT_EX(MSG_CANNOT_PARSE_METALINK);
} }
} catch(Exception& e) { } catch(Exception& e) {
XML_ParserFree(parser); XML_ParserFree(parser);
@ -136,7 +136,7 @@ MetalinkProcessor::parseFromBinaryStream(const SharedHandle<BinaryStream>& binar
} }
XML_ParserFree(parser); XML_ParserFree(parser);
if(!_stm->finished()) { if(!_stm->finished()) {
throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); throw DL_ABORT_EX(MSG_CANNOT_PARSE_METALINK);
} }
return _stm->getResult(); return _stm->getResult();
} }

View File

@ -112,7 +112,7 @@ XmlRpcRequestProcessor::parseMemory(const std::string& xml)
XML_ParserFree(parser); XML_ParserFree(parser);
if(r == XML_STATUS_ERROR) { if(r == XML_STATUS_ERROR) {
throw DlAbortEx(MSG_CANNOT_PARSE_XML_RPC_REQUEST); throw DL_ABORT_EX(MSG_CANNOT_PARSE_XML_RPC_REQUEST);
} }
return XmlRpcRequest(_stm->getMethodName(), _stm->getCurrentFrameValue()); return XmlRpcRequest(_stm->getMethodName(), _stm->getCurrentFrameValue());
} }

View File

@ -44,7 +44,7 @@ FallocFileAllocationIterator::FallocFileAllocationIterator
void FallocFileAllocationIterator::allocateChunk() void FallocFileAllocationIterator::allocateChunk()
{ {
if(static_cast<uint64_t>(_offset) > _totalLength) { if(static_cast<uint64_t>(_offset) > _totalLength) {
throw DlAbortEx("FallocFileAllocationIterator: offset is larger than" throw DL_ABORT_EX("FallocFileAllocationIterator: offset is larger than"
" totalLength"); " totalLength");
} }
_stream->allocate(_offset, _totalLength-_offset); _stream->allocate(_offset, _totalLength-_offset);

View File

@ -46,12 +46,19 @@ protected:
return e; return e;
} }
public: public:
FatalException(const std::string& msg):Exception(msg) {} FatalException(const char* file, int line, const std::string& msg):
FatalException(const std::string& msg, Exception(file, line, msg) {}
const Exception& cause):Exception(msg, cause) {} FatalException(const char* file, int line, const std::string& msg,
const Exception& cause):
Exception(file, line, msg, cause) {}
FatalException(const FatalException& e):Exception(e) {} FatalException(const FatalException& e):Exception(e) {}
}; };
#define FATAL_EXCEPTION(arg)\
FatalException(__FILE__, __LINE__, arg)
#define FATAL_EXCEPTION2(arg1, arg2)\
FatalException(__FILE__, __LINE__, arg1, arg2)
} // namespace aria2 } // namespace aria2
#endif // _D_FATAL_EXCEPTION_EX_H_ #endif // _D_FATAL_EXCEPTION_EX_H_

View File

@ -291,10 +291,10 @@ bool FtpConnection::bulkReceiveResponse(std::pair<unsigned int, std::string>& re
if(socket->wantRead() || socket->wantWrite()) { if(socket->wantRead() || socket->wantWrite()) {
return false; return false;
} }
throw DlRetryEx(EX_GOT_EOF); throw DL_RETRY_EX(EX_GOT_EOF);
} }
if(strbuf.size()+size > MAX_RECV_BUFFER) { if(strbuf.size()+size > MAX_RECV_BUFFER) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat("Max FTP recv buffer reached. length=%lu", (StringFormat("Max FTP recv buffer reached. length=%lu",
static_cast<unsigned long>(strbuf.size()+size)).str()); static_cast<unsigned long>(strbuf.size()+size)).str());
} }
@ -304,7 +304,7 @@ bool FtpConnection::bulkReceiveResponse(std::pair<unsigned int, std::string>& re
if(strbuf.size() >= 4) { if(strbuf.size() >= 4) {
status = getStatus(strbuf); status = getStatus(strbuf);
if(status == 0) { if(status == 0) {
throw DlAbortEx(EX_INVALID_RESPONSE); throw DL_ABORT_EX(EX_INVALID_RESPONSE);
} }
} else { } else {
return false; return false;
@ -411,7 +411,7 @@ unsigned int FtpConnection::receivePasvResponse(std::pair<std::string, uint16_t>
// port number // port number
dest.second = 256*p1+p2; dest.second = 256*p1+p2;
} else { } else {
throw DlRetryEx(EX_INVALID_RESPONSE); throw DL_RETRY_EX(EX_INVALID_RESPONSE);
} }
} }
return response.first; return response.first;
@ -432,7 +432,7 @@ unsigned int FtpConnection::receivePwdResponse(std::string& pwd)
(last = response.second.find("\"", ++first)) != std::string::npos) { (last = response.second.find("\"", ++first)) != std::string::npos) {
pwd = response.second.substr(first, last-first); pwd = response.second.substr(first, last-first);
} else { } else {
throw DlAbortEx(EX_INVALID_RESPONSE); throw DL_ABORT_EX(EX_INVALID_RESPONSE);
} }
} }
return response.first; return response.first;

View File

@ -82,7 +82,7 @@ bool FtpFinishDownloadCommand::execute()
return false; return false;
} }
if(status != 226) { if(status != 226) {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) { if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
std::map<std::string, std::string> options; std::map<std::string, std::string> options;

View File

@ -94,7 +94,7 @@ Command* FtpInitiateConnectionCommand::createNextCommand
proxyRequest, socket); proxyRequest, socket);
} else { } else {
// TODO // TODO
throw DlAbortEx("ERROR"); throw DL_ABORT_EX("ERROR");
} }
} else { } else {
if(proxyMethod == V_TUNNEL) { if(proxyMethod == V_TUNNEL) {
@ -114,7 +114,7 @@ Command* FtpInitiateConnectionCommand::createNextCommand
command = c; command = c;
} else { } else {
// TODO // TODO
throw DlAbortEx("ERROR"); throw DL_ABORT_EX("ERROR");
} }
} }
} else { } else {

View File

@ -135,7 +135,7 @@ bool FtpNegotiationCommand::recvGreeting() {
return false; return false;
} }
if(status != 220) { if(status != 220) {
throw DlAbortEx(EX_CONNECTION_FAILED); throw DL_ABORT_EX(EX_CONNECTION_FAILED);
} }
sequence = SEQ_SEND_USER; sequence = SEQ_SEND_USER;
@ -164,7 +164,7 @@ bool FtpNegotiationCommand::recvUser() {
sequence = SEQ_SEND_PASS; sequence = SEQ_SEND_PASS;
break; break;
default: default:
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
return true; return true;
} }
@ -185,7 +185,7 @@ bool FtpNegotiationCommand::recvPass() {
return false; return false;
} }
if(status != 230) { if(status != 230) {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
sequence = SEQ_SEND_TYPE; sequence = SEQ_SEND_TYPE;
return true; return true;
@ -207,7 +207,7 @@ bool FtpNegotiationCommand::recvType() {
return false; return false;
} }
if(status != 200) { if(status != 200) {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
sequence = SEQ_SEND_PWD; sequence = SEQ_SEND_PWD;
return true; return true;
@ -232,7 +232,7 @@ bool FtpNegotiationCommand::recvPwd()
return false; return false;
} }
if(status != 257) { if(status != 257) {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
ftp->setBaseWorkingDir(pwd); ftp->setBaseWorkingDir(pwd);
logger->info("CUID#%d - base working directory is '%s'", cuid, pwd.c_str()); logger->info("CUID#%d - base working directory is '%s'", cuid, pwd.c_str());
@ -261,9 +261,9 @@ bool FtpNegotiationCommand::recvCwd() {
poolConnection(); poolConnection();
_requestGroup->increaseAndValidateFileNotFoundCount(); _requestGroup->increaseAndValidateFileNotFoundCount();
if (status == 550) if (status == 550)
throw DlAbortEx(MSG_RESOURCE_NOT_FOUND, DownloadResult::RESOURCE_NOT_FOUND); throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND, DownloadResult::RESOURCE_NOT_FOUND);
else else
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
if(getOption()->getAsBool(PREF_REMOTE_TIME)) { if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
sequence = SEQ_SEND_MDTM; sequence = SEQ_SEND_MDTM;
@ -330,7 +330,7 @@ bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
dctx->setFilename(dctx->getDir()+"/"+Util::urldecode(req->getFile())); dctx->setFilename(dctx->getDir()+"/"+Util::urldecode(req->getFile()));
_requestGroup->preDownloadProcessing(); _requestGroup->preDownloadProcessing();
if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) { if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
_requestGroup->getFilePath().c_str()).str()); _requestGroup->getFilePath().c_str()).str());
} }
@ -418,7 +418,7 @@ bool FtpNegotiationCommand::recvSize() {
if(status == 213) { if(status == 213) {
if(size > INT64_MAX) { if(size > INT64_MAX) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str()); (StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str());
} }
if(_requestGroup->getPieceStorage().isNull()) { if(_requestGroup->getPieceStorage().isNull()) {
@ -485,7 +485,7 @@ bool FtpNegotiationCommand::recvPort() {
return false; return false;
} }
if(status != 200) { if(status != 200) {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
sequence = SEQ_SEND_REST; sequence = SEQ_SEND_REST;
return true; return true;
@ -509,7 +509,7 @@ bool FtpNegotiationCommand::recvPasv() {
return false; return false;
} }
if(status != 227) { if(status != 227) {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
// make a data connection to the server. // make a data connection to the server.
logger->info(MSG_CONNECTING_TO_SERVER, cuid, logger->info(MSG_CONNECTING_TO_SERVER, cuid,
@ -551,7 +551,7 @@ bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
// then throw exception here. // then throw exception here.
if(status != 350) { if(status != 350) {
if(!segment.isNull() && segment->getPositionToWrite() != 0) { if(!segment.isNull() && segment->getPositionToWrite() != 0) {
throw DlAbortEx("FTP server doesn't support resuming."); throw DL_ABORT_EX("FTP server doesn't support resuming.");
} }
} }
sequence = SEQ_SEND_RETR; sequence = SEQ_SEND_RETR;
@ -576,9 +576,9 @@ bool FtpNegotiationCommand::recvRetr() {
if(status != 150 && status != 125) { if(status != 150 && status != 125) {
_requestGroup->increaseAndValidateFileNotFoundCount(); _requestGroup->increaseAndValidateFileNotFoundCount();
if (status == 550) if (status == 550)
throw DlAbortEx(MSG_RESOURCE_NOT_FOUND, DownloadResult::RESOURCE_NOT_FOUND); throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND, DownloadResult::RESOURCE_NOT_FOUND);
else else
throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
} }
if(getOption()->getAsBool(PREF_FTP_PASV)) { if(getOption()->getAsBool(PREF_FTP_PASV)) {
sequence = SEQ_NEGOTIATION_COMPLETED; sequence = SEQ_NEGOTIATION_COMPLETED;

View File

@ -60,7 +60,7 @@ void GZipDecoder::init()
// initalize z_stream with gzip/zlib format auto detection enabled. // initalize z_stream with gzip/zlib format auto detection enabled.
if(Z_OK != inflateInit2(_strm, 47)) { if(Z_OK != inflateInit2(_strm, 47)) {
throw DlAbortEx("Initializing z_stream failed."); throw DL_ABORT_EX("Initializing z_stream failed.");
} }
} }
@ -94,7 +94,7 @@ std::string GZipDecoder::decode(const unsigned char* in, size_t length)
if(ret == Z_STREAM_END) { if(ret == Z_STREAM_END) {
_finished = true; _finished = true;
} else if(ret != Z_OK) { } else if(ret != Z_OK) {
throw DlAbortEx(StringFormat("libz::inflate() failed. cause:%s", throw DL_ABORT_EX(StringFormat("libz::inflate() failed. cause:%s",
_strm->msg).str()); _strm->msg).str());
} }

View File

@ -126,7 +126,7 @@ HandshakeExtensionMessageHandle
HandshakeExtensionMessage::create(const unsigned char* data, size_t length) HandshakeExtensionMessage::create(const unsigned char* data, size_t length)
{ {
if(length < 1) { if(length < 1) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE,
EXTENSION_NAME.c_str(), length).str()); EXTENSION_NAME.c_str(), length).str());
} }
@ -135,7 +135,7 @@ HandshakeExtensionMessage::create(const unsigned char* data, size_t length)
Util::urlencode(data, length).c_str()); Util::urlencode(data, length).c_str());
const BDE dict = bencode::decode(data+1, length-1); const BDE dict = bencode::decode(data+1, length-1);
if(!dict.isDict()) { if(!dict.isDict()) {
throw DlAbortEx("Unexpected payload format for extended message handshake"); throw DL_ABORT_EX("Unexpected payload format for extended message handshake");
} }
const BDE& port = dict["p"]; const BDE& port = dict["p"];
if(port.isInteger() && 0 < port.i() && port.i() < 65536) { if(port.isInteger() && 0 < port.i() && port.i() < 65536) {

View File

@ -121,7 +121,7 @@ void HttpConnection::sendProxyRequest(const HttpRequestHandle& httpRequest)
HttpResponseHandle HttpConnection::receiveResponse() HttpResponseHandle HttpConnection::receiveResponse()
{ {
if(outstandingHttpRequests.empty()) { if(outstandingHttpRequests.empty()) {
throw DlAbortEx(EX_NO_HTTP_REQUEST_ENTRY_FOUND); throw DL_ABORT_EX(EX_NO_HTTP_REQUEST_ENTRY_FOUND);
} }
HttpRequestEntryHandle entry = outstandingHttpRequests.front(); HttpRequestEntryHandle entry = outstandingHttpRequests.front();
HttpHeaderProcessorHandle proc = entry->getHttpHeaderProcessor(); HttpHeaderProcessorHandle proc = entry->getHttpHeaderProcessor();
@ -133,7 +133,7 @@ HttpResponseHandle HttpConnection::receiveResponse()
if(socket->wantRead() || socket->wantWrite()) { if(socket->wantRead() || socket->wantWrite()) {
return SharedHandle<HttpResponse>(); return SharedHandle<HttpResponse>();
} else { } else {
throw DlRetryEx(EX_INVALID_RESPONSE); throw DL_RETRY_EX(EX_INVALID_RESPONSE);
} }
} }
proc->update(buf, size); proc->update(buf, size);

View File

@ -62,7 +62,7 @@ void HttpHeaderProcessor::update(const std::string& data)
void HttpHeaderProcessor::checkHeaderLimit(size_t incomingLength) void HttpHeaderProcessor::checkHeaderLimit(size_t incomingLength)
{ {
if(_buf.size()+incomingLength > _limit) { if(_buf.size()+incomingLength > _limit) {
throw DlAbortEx("Too large http header"); throw DL_ABORT_EX("Too large http header");
} }
} }
@ -99,7 +99,7 @@ SharedHandle<HttpHeader> HttpHeaderProcessor::getHttpResponseHeader()
if(((delimpos = _buf.find("\r\n")) == std::string::npos && if(((delimpos = _buf.find("\r\n")) == std::string::npos &&
(delimpos = _buf.find("\n")) == std::string::npos) || (delimpos = _buf.find("\n")) == std::string::npos) ||
delimpos < 12) { delimpos < 12) {
throw DlRetryEx(EX_NO_STATUS_HEADER); throw DL_RETRY_EX(EX_NO_STATUS_HEADER);
} }
HttpHeaderHandle httpHeader(new HttpHeader()); HttpHeaderHandle httpHeader(new HttpHeader());
httpHeader->setVersion(_buf.substr(0, 8)); httpHeader->setVersion(_buf.substr(0, 8));
@ -120,12 +120,12 @@ SharedHandle<HttpHeader> HttpHeaderProcessor::getHttpRequestHeader()
if(((delimpos = _buf.find("\r\n")) == std::string::npos && if(((delimpos = _buf.find("\r\n")) == std::string::npos &&
(delimpos = _buf.find("\n")) == std::string::npos) || (delimpos = _buf.find("\n")) == std::string::npos) ||
delimpos < 14) { delimpos < 14) {
throw DlRetryEx(EX_NO_STATUS_HEADER); throw DL_RETRY_EX(EX_NO_STATUS_HEADER);
} }
std::deque<std::string> firstLine; std::deque<std::string> firstLine;
Util::slice(firstLine, _buf.substr(0, delimpos), ' ', true); Util::slice(firstLine, _buf.substr(0, delimpos), ' ', true);
if(firstLine.size() != 3) { if(firstLine.size() != 3) {
throw DlAbortEx("Malformed HTTP request header."); throw DL_ABORT_EX("Malformed HTTP request header.");
} }
SharedHandle<HttpHeader> httpHeader(new HttpHeader()); SharedHandle<HttpHeader> httpHeader(new HttpHeader());
httpHeader->setMethod(firstLine[0]); httpHeader->setMethod(firstLine[0]);

View File

@ -88,7 +88,7 @@ Command* HttpInitiateConnectionCommand::createNextCommand
command = c; command = c;
} else { } else {
// TODO // TODO
throw DlAbortEx("ERROR"); throw DL_ABORT_EX("ERROR");
} }
} else { } else {
SharedHandle<HttpConnection> httpConnection SharedHandle<HttpConnection> httpConnection

View File

@ -74,7 +74,7 @@ void HttpResponse::validateResponse() const
} }
if(status >= HttpHeader::S300) { if(status >= HttpHeader::S300) {
if(!httpHeader->defined(HttpHeader::LOCATION)) { if(!httpHeader->defined(HttpHeader::LOCATION)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_LOCATION_HEADER_REQUIRED, (StringFormat(EX_LOCATION_HEADER_REQUIRED,
Util::parseUInt(status)).str()); Util::parseUInt(status)).str());
} }
@ -82,7 +82,7 @@ void HttpResponse::validateResponse() const
// compare the received range against the requested range // compare the received range against the requested range
RangeHandle responseRange = httpHeader->getRange(); RangeHandle responseRange = httpHeader->getRange();
if(!httpRequest->isRangeSatisfied(responseRange)) { if(!httpRequest->isRangeSatisfied(responseRange)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat (StringFormat
(EX_INVALID_RANGE_HEADER, (EX_INVALID_RANGE_HEADER,
Util::itos(httpRequest->getStartByte(), true).c_str(), Util::itos(httpRequest->getStartByte(), true).c_str(),
@ -139,7 +139,7 @@ void HttpResponse::processRedirect()
logger->info(MSG_REDIRECT, cuid, logger->info(MSG_REDIRECT, cuid,
httpRequest->getRequest()->getCurrentUrl().c_str()); httpRequest->getRequest()->getCurrentUrl().c_str());
} else { } else {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat("CUID#%d - Redirect to %s failed. It may not be a valid" (StringFormat("CUID#%d - Redirect to %s failed. It may not be a valid"
" URI.", cuid, " URI.", cuid,
httpRequest->getRequest()->getCurrentUrl().c_str()).str()); httpRequest->getRequest()->getCurrentUrl().c_str()).str());

View File

@ -139,7 +139,7 @@ bool HttpResponseCommand::executeInternal()
dctx->setContentType(httpResponse->getContentType()); dctx->setContentType(httpResponse->getContentType());
_requestGroup->preDownloadProcessing(); _requestGroup->preDownloadProcessing();
if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) { if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
_requestGroup->getFilePath().c_str()).str()); _requestGroup->getFilePath().c_str()).str());
} }
@ -276,7 +276,7 @@ static SharedHandle<Decoder> getTransferEncodingDecoder
if(httpResponse->isTransferEncodingSpecified()) { if(httpResponse->isTransferEncodingSpecified()) {
decoder = httpResponse->getTransferEncodingDecoder(); decoder = httpResponse->getTransferEncodingDecoder();
if(decoder.isNull()) { if(decoder.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED, (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
httpResponse->getTransferEncoding().c_str()).str()); httpResponse->getTransferEncoding().c_str()).str());
} }

View File

@ -66,7 +66,7 @@ SharedHandle<HttpHeader> HttpServer::receiveRequest()
unsigned char buf[size]; unsigned char buf[size];
_socket->peekData(buf, size); _socket->peekData(buf, size);
if(size == 0 && !(_socket->wantRead() || _socket->wantWrite())) { if(size == 0 && !(_socket->wantRead() || _socket->wantWrite())) {
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
_headerProcessor->update(buf, size); _headerProcessor->update(buf, size);
if(!_headerProcessor->eoh()) { if(!_headerProcessor->eoh()) {
@ -104,7 +104,7 @@ bool HttpServer::receiveBody()
(_lastContentLength-_lastBody.tellg())); (_lastContentLength-_lastBody.tellg()));
_socket->readData(buf, length); _socket->readData(buf, length);
if(length == 0 && !(_socket->wantRead() || _socket->wantWrite())) { if(length == 0 && !(_socket->wantRead() || _socket->wantWrite())) {
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
_lastBody.write(buf, length); _lastBody.write(buf, length);
return _lastContentLength == static_cast<uint64_t>(_lastBody.tellp()); return _lastContentLength == static_cast<uint64_t>(_lastBody.tellp());

View File

@ -109,7 +109,7 @@ bool HttpSkipResponseCommand::executeInternal()
} }
if(_totalLength != 0 && bufSize == 0 && if(_totalLength != 0 && bufSize == 0 &&
!socket->wantRead() && !socket->wantWrite()) { !socket->wantRead() && !socket->wantWrite()) {
throw DlRetryEx(EX_GOT_EOF); throw DL_RETRY_EX(EX_GOT_EOF);
} }
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
logger->debug(EX_EXCEPTION_CAUGHT, e); logger->debug(EX_EXCEPTION_CAUGHT, e);
@ -151,7 +151,7 @@ bool HttpSkipResponseCommand::processResponse()
unsigned int rnum = unsigned int rnum =
_httpResponse->getHttpRequest()->getRequest()->getRedirectCount(); _httpResponse->getHttpRequest()->getRequest()->getRedirectCount();
if(rnum >= Request::MAX_REDIRECT) { if(rnum >= Request::MAX_REDIRECT) {
throw DlAbortEx(StringFormat("Too many redirects: count=%u", rnum).str()); throw DL_ABORT_EX(StringFormat("Too many redirects: count=%u", rnum).str());
} }
_httpResponse->processRedirect(); _httpResponse->processRedirect();
return prepareForRetry(0); return prepareForRetry(0);
@ -165,13 +165,13 @@ bool HttpSkipResponseCommand::processResponse()
(req->getHost(), req->getDir())) { (req->getHost(), req->getDir())) {
return prepareForRetry(0); return prepareForRetry(0);
} else { } else {
throw DlAbortEx(EX_AUTH_FAILED); throw DL_ABORT_EX(EX_AUTH_FAILED);
} }
}else if(_httpResponse->getResponseStatus() == HttpHeader::S404) { }else if(_httpResponse->getResponseStatus() == HttpHeader::S404) {
throw DlAbortEx(MSG_RESOURCE_NOT_FOUND, throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
DownloadResult::RESOURCE_NOT_FOUND); DownloadResult::RESOURCE_NOT_FOUND);
} else { } else {
throw DlAbortEx(StringFormat(EX_BAD_STATUS, Util::parseUInt(_httpResponse->getResponseStatus())).str()); throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, Util::parseUInt(_httpResponse->getResponseStatus())).str());
} }
} else { } else {
return prepareForRetry(0); return prepareForRetry(0);

View File

@ -67,7 +67,7 @@ InitiateConnectionCommandFactory::createInitiateConnectionCommand(int32_t cuid,
return new FtpInitiateConnectionCommand(cuid, req, requestGroup, e); return new FtpInitiateConnectionCommand(cuid, req, requestGroup, e);
} else { } else {
// these protocols are not supported yet // these protocols are not supported yet
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("%s is not supported yet.", (StringFormat("%s is not supported yet.",
req->getProtocol().c_str()).str()); req->getProtocol().c_str()).str());
} }

View File

@ -152,7 +152,7 @@ std::string IteratableChunkChecksumValidator::digest(off_t offset, size_t length
size_t r = _pieceStorage->getDiskAdaptor()->readData(_buffer, BUFSIZE, size_t r = _pieceStorage->getDiskAdaptor()->readData(_buffer, BUFSIZE,
curoffset); curoffset);
if(r == 0 || r < static_cast<size_t>(woffset)) { if(r == 0 || r < static_cast<size_t>(woffset)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_READ, _dctx->getActualBasePath().c_str(), (StringFormat(EX_FILE_READ, _dctx->getActualBasePath().c_str(),
strerror(errno)).str()); strerror(errno)).str());
} }

View File

@ -36,9 +36,11 @@
#define _D_LIBGCRYPT_ARC4_CONTEXT_H_ #define _D_LIBGCRYPT_ARC4_CONTEXT_H_
#include "common.h" #include "common.h"
#include <gcrypt.h>
#include "DlAbortEx.h" #include "DlAbortEx.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <gcrypt.h>
namespace aria2 { namespace aria2 {
@ -48,7 +50,7 @@ private:
void handleError(gcry_error_t err) const void handleError(gcry_error_t err) const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libgcrypt routine(ARC4Context class): %s", (StringFormat("Exception in libgcrypt routine(ARC4Context class): %s",
gcry_strerror(err)).str()); gcry_strerror(err)).str());
} }

View File

@ -36,10 +36,12 @@
#define _D_LIBGCRYPT_ARC4_DECRYPTOR_H_ #define _D_LIBGCRYPT_ARC4_DECRYPTOR_H_
#include "common.h" #include "common.h"
#include <gcrypt.h>
#include "DlAbortEx.h" #include "DlAbortEx.h"
#include "LibgcryptARC4Context.h" #include "LibgcryptARC4Context.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <gcrypt.h>
namespace aria2 { namespace aria2 {
@ -49,7 +51,7 @@ private:
void handleError(gcry_error_t err) const void handleError(gcry_error_t err) const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libgcrypt routine(ARC4Decryptor class): %s", (StringFormat("Exception in libgcrypt routine(ARC4Decryptor class): %s",
gcry_strerror(err)).str()); gcry_strerror(err)).str());
} }

View File

@ -36,10 +36,12 @@
#define _D_LIBGCRYPT_ARC4_ENCRYPTOR_H_ #define _D_LIBGCRYPT_ARC4_ENCRYPTOR_H_
#include "common.h" #include "common.h"
#include <gcrypt.h>
#include "DlAbortEx.h" #include "DlAbortEx.h"
#include "LibgcryptARC4Context.h" #include "LibgcryptARC4Context.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <gcrypt.h>
namespace aria2 { namespace aria2 {
@ -49,7 +51,7 @@ private:
void handleError(gcry_error_t err) const void handleError(gcry_error_t err) const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libgcrypt routine(ARC4Encryptor class): %s", (StringFormat("Exception in libgcrypt routine(ARC4Encryptor class): %s",
gcry_strerror(err)).str()); gcry_strerror(err)).str());
} }

View File

@ -56,7 +56,7 @@ private:
void handleError(gcry_error_t err) const void handleError(gcry_error_t err) const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libgcrypt routine(DHKeyExchange class): %s", (StringFormat("Exception in libgcrypt routine(DHKeyExchange class): %s",
gcry_strerror(err)).str()); gcry_strerror(err)).str());
} }
@ -112,7 +112,7 @@ public:
size_t getPublicKey(unsigned char* out, size_t outLength) const size_t getPublicKey(unsigned char* out, size_t outLength) const
{ {
if(outLength < _keyLength) { if(outLength < _keyLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Insufficient buffer for public key. expect:%u, actual:%u", (StringFormat("Insufficient buffer for public key. expect:%u, actual:%u",
_keyLength, outLength).str()); _keyLength, outLength).str());
} }
@ -138,7 +138,7 @@ public:
size_t peerPublicKeyLength) const size_t peerPublicKeyLength) const
{ {
if(outLength < _keyLength) { if(outLength < _keyLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Insufficient buffer for secret. expect:%u, actual:%u", (StringFormat("Insufficient buffer for secret. expect:%u, actual:%u",
_keyLength, outLength).str()); _keyLength, outLength).str());
} }

View File

@ -87,7 +87,7 @@ void TLSContext::addClientKeyFile(const std::string& certfile,
keyfile.c_str(), keyfile.c_str(),
GNUTLS_X509_FMT_PEM); GNUTLS_X509_FMT_PEM);
if(ret != GNUTLS_E_SUCCESS) { if(ret != GNUTLS_E_SUCCESS) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Failed to load client certificate from %s and" (StringFormat("Failed to load client certificate from %s and"
" private key from %s. Cause: %s", " private key from %s. Cause: %s",
certfile.c_str(), keyfile.c_str(), certfile.c_str(), keyfile.c_str(),
@ -102,7 +102,7 @@ void TLSContext::addTrustedCACertFile(const std::string& certfile)
certfile.c_str(), certfile.c_str(),
GNUTLS_X509_FMT_PEM); GNUTLS_X509_FMT_PEM);
if(ret < 0) { if(ret < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat (StringFormat
(MSG_LOADING_TRUSTED_CA_CERT_FAILED, (MSG_LOADING_TRUSTED_CA_CERT_FAILED,
certfile.c_str(), gnutls_strerror(ret)).str()); certfile.c_str(), gnutls_strerror(ret)).str());

View File

@ -36,11 +36,13 @@
#define _D_LIBSSL_ARC4_CONTEXT_H_ #define _D_LIBSSL_ARC4_CONTEXT_H_
#include "common.h" #include "common.h"
#include "DlAbortEx.h"
#include "StringFormat.h"
#include <openssl/evp.h> #include <openssl/evp.h>
#include <openssl/err.h> #include <openssl/err.h>
#include "DlAbortEx.h"
#include "StringFormat.h"
namespace aria2 { namespace aria2 {
class LibsslARC4Context { class LibsslARC4Context {
@ -49,7 +51,7 @@ private:
void handleError() const void handleError() const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libssl routine(ARC4Context class): %s", (StringFormat("Exception in libssl routine(ARC4Context class): %s",
ERR_error_string(ERR_get_error(), 0)).str()); ERR_error_string(ERR_get_error(), 0)).str());
} }

View File

@ -36,11 +36,13 @@
#define _D_LIBSSL_ARC4_DECRYPTOR_H_ #define _D_LIBSSL_ARC4_DECRYPTOR_H_
#include "common.h" #include "common.h"
#include <openssl/evp.h>
#include <openssl/err.h>
#include "DlAbortEx.h" #include "DlAbortEx.h"
#include "LibsslARC4Context.h" #include "LibsslARC4Context.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <openssl/evp.h>
#include <openssl/err.h>
namespace aria2 { namespace aria2 {
@ -50,7 +52,7 @@ private:
void handleError() const void handleError() const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libssl routine(ARC4Decryptor class): %s", (StringFormat("Exception in libssl routine(ARC4Decryptor class): %s",
ERR_error_string(ERR_get_error(), 0)).str()); ERR_error_string(ERR_get_error(), 0)).str());
} }

View File

@ -36,11 +36,13 @@
#define _D_LIBSSL_ARC4_ENCRYPTOR_H_ #define _D_LIBSSL_ARC4_ENCRYPTOR_H_
#include "common.h" #include "common.h"
#include <openssl/evp.h>
#include <openssl/err.h>
#include "DlAbortEx.h" #include "DlAbortEx.h"
#include "LibsslARC4Context.h" #include "LibsslARC4Context.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <openssl/evp.h>
#include <openssl/err.h>
namespace aria2 { namespace aria2 {
@ -50,7 +52,7 @@ private:
void handleError() const void handleError() const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libssl routine(ARC4Encryptor class): %s", (StringFormat("Exception in libssl routine(ARC4Encryptor class): %s",
ERR_error_string(ERR_get_error(), 0)).str()); ERR_error_string(ERR_get_error(), 0)).str());
} }

View File

@ -62,7 +62,7 @@ private:
void handleError(const std::string& funName) const void handleError(const std::string& funName) const
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Exception in libssl routine %s(DHKeyExchange class): %s", (StringFormat("Exception in libssl routine %s(DHKeyExchange class): %s",
funName.c_str(), ERR_error_string(ERR_get_error(), 0)).str()); funName.c_str(), ERR_error_string(ERR_get_error(), 0)).str());
} }
@ -123,7 +123,7 @@ public:
size_t getPublicKey(unsigned char* out, size_t outLength) const size_t getPublicKey(unsigned char* out, size_t outLength) const
{ {
if(outLength < _keyLength) { if(outLength < _keyLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Insufficient buffer for public key. expect:%u, actual:%u", (StringFormat("Insufficient buffer for public key. expect:%u, actual:%u",
_keyLength, outLength).str()); _keyLength, outLength).str());
} }
@ -132,7 +132,7 @@ public:
size_t offset = _keyLength-publicKeyBytes; size_t offset = _keyLength-publicKeyBytes;
size_t nwritten = BN_bn2bin(_publicKey, out+offset); size_t nwritten = BN_bn2bin(_publicKey, out+offset);
if(nwritten != publicKeyBytes) { if(nwritten != publicKeyBytes) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, publicKeyBytes).str()); (StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, publicKeyBytes).str());
} }
return nwritten; return nwritten;
@ -150,7 +150,7 @@ public:
size_t peerPublicKeyLength) const size_t peerPublicKeyLength) const
{ {
if(outLength < _keyLength) { if(outLength < _keyLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Insufficient buffer for secret. expect:%u, actual:%u", (StringFormat("Insufficient buffer for secret. expect:%u, actual:%u",
_keyLength, outLength).str()); _keyLength, outLength).str());
} }
@ -171,7 +171,7 @@ public:
size_t nwritten = BN_bn2bin(secret, out+offset); size_t nwritten = BN_bn2bin(secret, out+offset);
BN_free(secret); BN_free(secret);
if(nwritten != secretBytes) { if(nwritten != secretBytes) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, secretBytes).str()); (StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, secretBytes).str());
} }
return nwritten; return nwritten;

View File

@ -79,13 +79,13 @@ void TLSContext::addClientKeyFile(const std::string& certfile,
{ {
if(SSL_CTX_use_PrivateKey_file(_sslCtx, keyfile.c_str(), if(SSL_CTX_use_PrivateKey_file(_sslCtx, keyfile.c_str(),
SSL_FILETYPE_PEM) != 1) { SSL_FILETYPE_PEM) != 1) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat (StringFormat
("Failed to load client private key from %s. Cause: %s", ("Failed to load client private key from %s. Cause: %s",
keyfile.c_str(), ERR_error_string(ERR_get_error(), 0)).str()); keyfile.c_str(), ERR_error_string(ERR_get_error(), 0)).str());
} }
if(SSL_CTX_use_certificate_chain_file(_sslCtx, certfile.c_str()) != 1) { if(SSL_CTX_use_certificate_chain_file(_sslCtx, certfile.c_str()) != 1) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat (StringFormat
("Failed to load client certificate from %s. Cause: %s", ("Failed to load client certificate from %s. Cause: %s",
certfile.c_str(), ERR_error_string(ERR_get_error(), 0)).str()); certfile.c_str(), ERR_error_string(ERR_get_error(), 0)).str());
@ -96,7 +96,7 @@ void TLSContext::addTrustedCACertFile(const std::string& certfile)
throw(DlAbortEx) throw(DlAbortEx)
{ {
if(SSL_CTX_load_verify_locations(_sslCtx, certfile.c_str(), 0) != 1) { if(SSL_CTX_load_verify_locations(_sslCtx, certfile.c_str(), 0) != 1) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat (StringFormat
(MSG_LOADING_TRUSTED_CA_CERT_FAILED, (MSG_LOADING_TRUSTED_CA_CERT_FAILED,
certfile.c_str(), ERR_error_string(ERR_get_error(), 0)).str()); certfile.c_str(), ERR_error_string(ERR_get_error(), 0)).str());

View File

@ -95,7 +95,7 @@ MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
size_t r = 20-_rbufLength; size_t r = 20-_rbufLength;
_socket->readData(_rbuf+_rbufLength, r); _socket->readData(_rbuf+_rbufLength, r);
if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) { if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) {
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
_rbufLength += r; _rbufLength += r;
if(_rbufLength < 20) { if(_rbufLength < 20) {
@ -305,7 +305,7 @@ bool MSEHandshake::findInitiatorVCMarker()
if(_socket->wantRead() || _socket->wantWrite()) { if(_socket->wantRead() || _socket->wantWrite()) {
return false; return false;
} }
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
// find vc // find vc
{ {
@ -313,7 +313,7 @@ bool MSEHandshake::findInitiatorVCMarker()
std::string vc(&_initiatorVCMarker[0], &_initiatorVCMarker[VC_LENGTH]); std::string vc(&_initiatorVCMarker[0], &_initiatorVCMarker[VC_LENGTH]);
if((_markerIndex = buf.find(vc)) == std::string::npos) { if((_markerIndex = buf.find(vc)) == std::string::npos) {
if(616-KEY_LENGTH <= _rbufLength+r) { if(616-KEY_LENGTH <= _rbufLength+r) {
throw DlAbortEx("Failed to find VC marker."); throw DL_ABORT_EX("Failed to find VC marker.");
} else { } else {
_socket->readData(_rbuf+_rbufLength, r); _socket->readData(_rbuf+_rbufLength, r);
_rbufLength += r; _rbufLength += r;
@ -355,7 +355,7 @@ bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength()
_negotiatedCryptoType = CRYPTO_ARC4; _negotiatedCryptoType = CRYPTO_ARC4;
} }
if(_negotiatedCryptoType == CRYPTO_NONE) { if(_negotiatedCryptoType == CRYPTO_NONE) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("CUID#%d - No supported crypto type selected.", _cuid).str()); (StringFormat("CUID#%d - No supported crypto type selected.", _cuid).str());
} }
} }
@ -395,7 +395,7 @@ bool MSEHandshake::findReceiverHashMarker()
if(_socket->wantRead() || _socket->wantWrite()) { if(_socket->wantRead() || _socket->wantWrite()) {
return false; return false;
} }
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
// find hash('req1', S), S is _secret. // find hash('req1', S), S is _secret.
{ {
@ -405,7 +405,7 @@ bool MSEHandshake::findReceiverHashMarker()
std::string req1(&md[0], &md[sizeof(md)]); std::string req1(&md[0], &md[sizeof(md)]);
if((_markerIndex = buf.find(req1)) == std::string::npos) { if((_markerIndex = buf.find(req1)) == std::string::npos) {
if(628-KEY_LENGTH <= _rbufLength+r) { if(628-KEY_LENGTH <= _rbufLength+r) {
throw DlAbortEx("Failed to find hash marker."); throw DL_ABORT_EX("Failed to find hash marker.");
} else { } else {
_socket->readData(_rbuf+_rbufLength, r); _socket->readData(_rbuf+_rbufLength, r);
_rbufLength += r; _rbufLength += r;
@ -447,7 +447,7 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength
} }
} }
if(btContext.isNull()) { if(btContext.isNull()) {
throw DlAbortEx("Unknown info hash."); throw DL_ABORT_EX("Unknown info hash.");
} }
initCipher(btContext->getInfoHash()); initCipher(btContext->getInfoHash());
@ -471,7 +471,7 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength
_negotiatedCryptoType = CRYPTO_ARC4; _negotiatedCryptoType = CRYPTO_ARC4;
} }
if(_negotiatedCryptoType == CRYPTO_NONE) { if(_negotiatedCryptoType == CRYPTO_NONE) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("CUID#%d - No supported crypto type provided.", _cuid).str()); (StringFormat("CUID#%d - No supported crypto type provided.", _cuid).str());
} }
} }
@ -547,7 +547,7 @@ uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const cha
uint16_t padLength = decodeLength16(padlenbuf); uint16_t padLength = decodeLength16(padlenbuf);
_logger->debug("CUID#%d - len(%s)=%u", _cuid, padName, padLength); _logger->debug("CUID#%d - len(%s)=%u", _cuid, padName, padLength);
if(padLength > 512) { if(padLength > 512) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Too large %s length: %u", padName, padLength).str()); (StringFormat("Too large %s length: %u", padName, padLength).str());
} }
return padLength; return padLength;
@ -559,7 +559,7 @@ void MSEHandshake::verifyVC(const unsigned char* vcbuf)
unsigned char vc[VC_LENGTH]; unsigned char vc[VC_LENGTH];
_decryptor->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc)); _decryptor->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc));
if(memcmp(VC, vc, sizeof(VC)) != 0) { if(memcmp(VC, vc, sizeof(VC)) != 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Invalid VC: %s", Util::toHex(vc, VC_LENGTH).c_str()).str()); (StringFormat("Invalid VC: %s", Util::toHex(vc, VC_LENGTH).c_str()).str());
} }
} }
@ -570,7 +570,7 @@ void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf)
unsigned char md[20]; unsigned char md[20];
createReq1Hash(md); createReq1Hash(md);
if(memcmp(md, req1buf, sizeof(md)) != 0) { if(memcmp(md, req1buf, sizeof(md)) != 0) {
throw DlAbortEx("Invalid req1 hash found."); throw DL_ABORT_EX("Invalid req1 hash found.");
} }
} }
@ -583,7 +583,7 @@ size_t MSEHandshake::receiveNBytes(size_t bytes)
} }
_socket->readData(_rbuf+_rbufLength, r); _socket->readData(_rbuf+_rbufLength, r);
if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) { if(r == 0 && !_socket->wantRead() && !_socket->wantWrite()) {
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
_rbufLength += r; _rbufLength += r;
} }

View File

@ -91,7 +91,7 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx,
for(uint64_t i = 0; i < iteration; ++i) { for(uint64_t i = 0; i < iteration; ++i) {
ssize_t readLength = bs->readData(BUF, BUFSIZE, offset); ssize_t readLength = bs->readData(BUF, BUFSIZE, offset);
if((size_t)readLength != BUFSIZE) { if((size_t)readLength != BUFSIZE) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str()); (StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str());
} }
ctx->digestUpdate(BUF, readLength); ctx->digestUpdate(BUF, readLength);
@ -100,7 +100,7 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx,
if(tail) { if(tail) {
ssize_t readLength = bs->readData(BUF, tail, offset); ssize_t readLength = bs->readData(BUF, tail, offset);
if((size_t)readLength != tail) { if((size_t)readLength != tail) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str()); (StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str());
} }
ctx->digestUpdate(BUF, readLength); ctx->digestUpdate(BUF, readLength);
@ -130,7 +130,7 @@ void MessageDigestHelper::digest(unsigned char* md, size_t mdLength,
const std::string& algo, const void* data, size_t length) const std::string& algo, const void* data, size_t length)
{ {
if(mdLength < MessageDigestContext::digestLength(algo)) { if(mdLength < MessageDigestContext::digestLength(algo)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Insufficient space for storing message digest: %d required, but only %d is allocated", (StringFormat("Insufficient space for storing message digest: %d required, but only %d is allocated",
MessageDigestContext::digestLength(algo), mdLength).str()); MessageDigestContext::digestLength(algo), mdLength).str());
} }

View File

@ -71,7 +71,7 @@ void MetalinkHelper::query
const SharedHandle<Metalinker>& metalinker, const Option* option) const SharedHandle<Metalinker>& metalinker, const Option* option)
{ {
if(metalinker->entries.empty()) { if(metalinker->entries.empty()) {
throw DlAbortEx("No file entry found. Probably, the metalink file is not configured properly or broken."); throw DL_ABORT_EX("No file entry found. Probably, the metalink file is not configured properly or broken.");
} }
metalinker->queryEntry(result, metalinker->queryEntry(result,
option->get(PREF_METALINK_VERSION), option->get(PREF_METALINK_VERSION),

View File

@ -398,7 +398,7 @@ findFirstDiskWriterEntry(const DiskWriterEntries& diskWriterEntries, off_t offse
// In case when offset is out-of-range // In case when offset is out-of-range
if(!isInRange(*first, offset)) { if(!isInRange(*first, offset)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_OFFSET_OUT_OF_RANGE, (StringFormat(EX_FILE_OFFSET_OUT_OF_RANGE,
Util::itos(offset, true).c_str()).str()); Util::itos(offset, true).c_str()).str());
} }
@ -408,7 +408,7 @@ findFirstDiskWriterEntry(const DiskWriterEntries& diskWriterEntries, off_t offse
static void throwOnDiskWriterNotOpened(const SharedHandle<DiskWriterEntry>& e, static void throwOnDiskWriterNotOpened(const SharedHandle<DiskWriterEntry>& e,
off_t offset) off_t offset)
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("DiskWriter for offset=%s, filename=%s is not opened.", (StringFormat("DiskWriter for offset=%s, filename=%s is not opened.",
Util::itos(offset).c_str(), Util::itos(offset).c_str(),
e->getFilePath().c_str()).str()); e->getFilePath().c_str()).str());

View File

@ -99,7 +99,7 @@ public:
try { try {
parseArg(option, arg); parseArg(option, arg);
} catch(Exception& e) { } catch(Exception& e) {
throw OptionHandlerException(_optName, e); throw OPTION_HANDLER_EXCEPTION2(_optName, e);
} }
} }

View File

@ -56,7 +56,7 @@ void NameResolver::resolve(std::deque<std::string>& resolvedAddresses,
int s; int s;
s = getaddrinfo(hostname.c_str(), 0, &hints, &res); s = getaddrinfo(hostname.c_str(), 0, &hints, &res);
if(s) { if(s) {
throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME, throw DL_ABORT_EX(StringFormat(EX_RESOLVE_HOSTNAME,
hostname.c_str(), gai_strerror(s)).str()); hostname.c_str(), gai_strerror(s)).str());
} }
struct addrinfo* rp; struct addrinfo* rp;

View File

@ -33,12 +33,14 @@
*/ */
/* copyright --> */ /* copyright --> */
#include "Netrc.h" #include "Netrc.h"
#include "RecoverableException.h"
#include "StringFormat.h"
#include "A2STR.h"
#include <fstream> #include <fstream>
#include <algorithm> #include <algorithm>
#include "DlAbortEx.h"
#include "StringFormat.h"
#include "A2STR.h"
namespace aria2 { namespace aria2 {
const std::string Netrc::MACHINE("machine"); const std::string Netrc::MACHINE("machine");
@ -59,7 +61,7 @@ std::string Netrc::getRequiredNextToken(std::ifstream& f) const
if(f >> token) { if(f >> token) {
return token; return token;
} else { } else {
throw RecoverableException throw DL_ABORT_EX
("Netrc:parse error. EOF reached where a token expected."); ("Netrc:parse error. EOF reached where a token expected.");
} }
} }
@ -81,7 +83,7 @@ void Netrc::parse(const std::string& path)
std::ifstream f(path.c_str(), std::ios::binary); std::ifstream f(path.c_str(), std::ios::binary);
if(!f) { if(!f) {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("File not found: %s", path.c_str()).str()); (StringFormat("File not found: %s", path.c_str()).str());
} }
@ -97,7 +99,7 @@ void Netrc::parse(const std::string& path)
authenticator.reset(new DefaultAuthenticator()); authenticator.reset(new DefaultAuthenticator());
} else { } else {
if(authenticator.isNull()) { if(authenticator.isNull()) {
throw RecoverableException throw DL_ABORT_EX
("Netrc:parse error. %s encounterd where 'machine' or 'default' expected."); ("Netrc:parse error. %s encounterd where 'machine' or 'default' expected.");
} }
if(token == Netrc::LOGIN) { if(token == Netrc::LOGIN) {

View File

@ -33,11 +33,13 @@
*/ */
/* copyright --> */ /* copyright --> */
#include "NsCookieParser.h" #include "NsCookieParser.h"
#include <fstream>
#include "Util.h" #include "Util.h"
#include "A2STR.h" #include "A2STR.h"
#include "RecoverableException.h" #include "DlAbortEx.h"
#include "StringFormat.h" #include "StringFormat.h"
#include <fstream>
namespace aria2 { namespace aria2 {
@ -75,7 +77,7 @@ std::deque<Cookie> NsCookieParser::parse(const std::string& filename)
{ {
std::ifstream s(filename.c_str(), std::ios::binary); std::ifstream s(filename.c_str(), std::ios::binary);
if(!s) { if(!s) {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Failed to open file %s", filename.c_str()).str()); (StringFormat("Failed to open file %s", filename.c_str()).str());
} }
std::string line; std::string line;

View File

@ -40,18 +40,22 @@ namespace aria2 {
const std::string OptionHandlerException::MESSAGE const std::string OptionHandlerException::MESSAGE
("Exception occurred while processing option %s:"); ("Exception occurred while processing option %s:");
OptionHandlerException::OptionHandlerException(const std::string& optName): OptionHandlerException::OptionHandlerException(const char* file, int line,
const std::string& optName):
RecoverableException RecoverableException
(StringFormat(MESSAGE.c_str(), optName.c_str()).str()), _optName(optName) {} (file, line, StringFormat(MESSAGE.c_str(), optName.c_str()).str()),
OptionHandlerException::OptionHandlerException(const std::string& optName,
const Exception& cause):
RecoverableException
(StringFormat(MESSAGE.c_str(), optName.c_str()).str(), cause),
_optName(optName) {} _optName(optName) {}
OptionHandlerException::OptionHandlerException(const OptionHandlerException& e): OptionHandlerException::OptionHandlerException(const char* file, int line,
RecoverableException(e), _optName(e._optName) {} const std::string& optName,
const Exception& cause):
RecoverableException
(file, line, StringFormat(MESSAGE.c_str(), optName.c_str()).str(), cause),
_optName(optName) {}
OptionHandlerException::OptionHandlerException(const char* file, int line,
const OptionHandlerException& e):
RecoverableException(file, line, e), _optName(e._optName) {}
OptionHandlerException::~OptionHandlerException() throw() {} OptionHandlerException::~OptionHandlerException() throw() {}

View File

@ -46,17 +46,25 @@ private:
protected: protected:
virtual SharedHandle<Exception> copy() const; virtual SharedHandle<Exception> copy() const;
public: public:
OptionHandlerException(const std::string& optName); OptionHandlerException(const char* file, int line,
const std::string& optName);
OptionHandlerException(const std::string& optName, const Exception& cause); OptionHandlerException(const char* file, int line, const std::string& optName,
const Exception& cause);
OptionHandlerException(const OptionHandlerException& e); OptionHandlerException(const char* file, int line,
const OptionHandlerException& e);
virtual ~OptionHandlerException() throw(); virtual ~OptionHandlerException() throw();
const std::string& getOptionName() const throw(); const std::string& getOptionName() const throw();
}; };
#define OPTION_HANDLER_EXCEPTION(arg)\
OptionHandlerException(__FILE__, __LINE__, arg)
#define OPTION_HANDLER_EXCEPTION2(arg1, arg2)\
OptionHandlerException(__FILE__, __LINE__, arg1, arg2)
} // namespace aria2 } // namespace aria2
#endif // _D_OPTION_HANDLER_EXCEPTION_EX_H_ #endif // _D_OPTION_HANDLER_EXCEPTION_EX_H_

View File

@ -127,7 +127,7 @@ public:
option.put(_optName, V_FALSE); option.put(_optName, V_FALSE);
} else { } else {
std::string msg = _optName+" "+_("must be either 'true' or 'false'."); std::string msg = _optName+" "+_("must be either 'true' or 'false'.");
throw DlAbortEx(msg); throw DL_ABORT_EX(msg);
} }
} }
@ -160,7 +160,7 @@ public:
int32_t v = seq.next(); int32_t v = seq.next();
if(v < _min || _max < v) { if(v < _min || _max < v) {
std::string msg = _optName+" "+_("must be between %s and %s."); std::string msg = _optName+" "+_("must be between %s and %s.");
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(msg.c_str(), Util::itos(_min).c_str(), (StringFormat(msg.c_str(), Util::itos(_min).c_str(),
Util::itos(_max).c_str()).str()); Util::itos(_max).c_str()).str());
} }
@ -215,7 +215,7 @@ public:
} else { } else {
msg += _("must be a number."); msg += _("must be a number.");
} }
throw DlAbortEx(msg); throw DL_ABORT_EX(msg);
} }
} }
@ -281,7 +281,7 @@ public:
} else { } else {
msg += _("must be a number."); msg += _("must be a number.");
} }
throw DlAbortEx(msg); throw DL_ABORT_EX(msg);
} }
} }
@ -462,7 +462,7 @@ public:
msg += "'"+*itr+"' "; msg += "'"+*itr+"' ";
} }
} }
throw DlAbortEx(msg); throw DL_ABORT_EX(msg);
} else { } else {
option.put(_optName, optarg); option.put(_optName, optarg);
} }
@ -502,7 +502,7 @@ public:
int32_t port = Util::parseInt(proxy.second); int32_t port = Util::parseInt(proxy.second);
if(proxy.first.empty() || proxy.second.empty() || if(proxy.first.empty() || proxy.second.empty() ||
port <= 0 || 65535 < port) { port <= 0 || 65535 < port) {
throw DlAbortEx(_("unrecognized proxy format")); throw DL_ABORT_EX(_("unrecognized proxy format"));
} }
option.put(_optName, optarg); option.put(_optName, optarg);
setHostAndPort(option, proxy.first, port); setHostAndPort(option, proxy.first, port);
@ -545,7 +545,7 @@ public:
if(req.setUrl(url)) { if(req.setUrl(url)) {
option.put(_optName, url); option.put(_optName, url);
} else { } else {
throw DlAbortEx(_("unrecognized proxy format")); throw DL_ABORT_EX(_("unrecognized proxy format"));
} }
} }

View File

@ -142,7 +142,7 @@ void OptionParser::parseArg
op = findByShortName(c); op = findByShortName(c);
} }
if(op.isNull()) { if(op.isNull()) {
throw DlAbortEx("Failed to parse command-line options."); throw DL_ABORT_EX("Failed to parse command-line options.");
} }
out << op->getName() << "="; out << op->getName() << "=";
if(optarg) { if(optarg) {

View File

@ -88,12 +88,12 @@ PStringDatumHandle ParameterizedStringParser::createSelect(const std::string& sr
++offset; ++offset;
std::string::size_type rightParenIndex = src.find("}", offset); std::string::size_type rightParenIndex = src.find("}", offset);
if(rightParenIndex == std::string::npos) { if(rightParenIndex == std::string::npos) {
throw DlAbortEx("Missing '}' in the parameterized string."); throw DL_ABORT_EX("Missing '}' in the parameterized string.");
} }
std::deque<std::string> values; std::deque<std::string> values;
Util::slice(values, src.substr(offset, rightParenIndex-offset), ',', true); Util::slice(values, src.substr(offset, rightParenIndex-offset), ',', true);
if(values.empty()) { if(values.empty()) {
throw DlAbortEx("Empty {} is not allowed."); throw DL_ABORT_EX("Empty {} is not allowed.");
} }
offset = rightParenIndex+1; offset = rightParenIndex+1;
PStringDatumHandle next = diggPString(src, offset); PStringDatumHandle next = diggPString(src, offset);
@ -106,7 +106,7 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src,
++offset; ++offset;
std::string::size_type rightParenIndex = src.find("]", offset); std::string::size_type rightParenIndex = src.find("]", offset);
if(rightParenIndex == std::string::npos) { if(rightParenIndex == std::string::npos) {
throw DlAbortEx("Missing ']' in the parameterized string."); throw DL_ABORT_EX("Missing ']' in the parameterized string.");
} }
std::string loopStr = src.substr(offset, rightParenIndex-offset); std::string loopStr = src.substr(offset, rightParenIndex-offset);
offset = rightParenIndex+1; offset = rightParenIndex+1;
@ -118,13 +118,13 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src,
if(Util::isNumber(stepStr)) { if(Util::isNumber(stepStr)) {
step = Util::parseUInt(stepStr); step = Util::parseUInt(stepStr);
} else { } else {
throw DlAbortEx("A step count must be a positive number."); throw DL_ABORT_EX("A step count must be a positive number.");
} }
loopStr.erase(colonIndex); loopStr.erase(colonIndex);
} }
std::pair<std::string, std::string> range = Util::split(loopStr, "-"); std::pair<std::string, std::string> range = Util::split(loopStr, "-");
if(range.first.empty() || range.second.empty()) { if(range.first.empty() || range.second.empty()) {
throw DlAbortEx("Loop range missing."); throw DL_ABORT_EX("Loop range missing.");
} }
NumberDecoratorHandle nd; NumberDecoratorHandle nd;
unsigned int start; unsigned int start;
@ -142,7 +142,7 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src,
start = Util::alphaToNum(range.first); start = Util::alphaToNum(range.first);
end = Util::alphaToNum(range.second); end = Util::alphaToNum(range.second);
} else { } else {
throw DlAbortEx("Invalid loop range."); throw DL_ABORT_EX("Invalid loop range.");
} }
PStringDatumHandle next(diggPString(src, offset)); PStringDatumHandle next(diggPString(src, offset));

View File

@ -87,12 +87,12 @@ bool PeerAbstractCommand::execute()
_hupEvent) { _hupEvent) {
checkPoint.reset(); checkPoint.reset();
} else if(_errorEvent) { } else if(_errorEvent) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_NETWORK_PROBLEM, (StringFormat(MSG_NETWORK_PROBLEM,
socket->getSocketError().c_str()).str()); socket->getSocketError().c_str()).str());
} }
if(checkPoint.elapsed(timeout)) { if(checkPoint.elapsed(timeout)) {
throw DlAbortEx(EX_TIME_OUT); throw DL_ABORT_EX(EX_TIME_OUT);
} }
return executeInternal(); return executeInternal();
} catch(DownloadFailureException& err) { } catch(DownloadFailureException& err) {

View File

@ -90,7 +90,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
// we got EOF // we got EOF
logger->debug("CUID#%d - In PeerConnection::receiveMessage(), remain=%lu", logger->debug("CUID#%d - In PeerConnection::receiveMessage(), remain=%lu",
cuid, static_cast<unsigned long>(temp)); cuid, static_cast<unsigned long>(temp));
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
lenbufLength += remaining; lenbufLength += remaining;
if(4 > lenbufLength) { if(4 > lenbufLength) {
@ -99,7 +99,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
} }
uint32_t payloadLength = ntohl(*(reinterpret_cast<uint32_t*>(lenbuf))); uint32_t payloadLength = ntohl(*(reinterpret_cast<uint32_t*>(lenbuf)));
if(payloadLength > MAX_PAYLOAD_LEN) { if(payloadLength > MAX_PAYLOAD_LEN) {
throw DlAbortEx(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str()); throw DL_ABORT_EX(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str());
} }
currentPayloadLength = payloadLength; currentPayloadLength = payloadLength;
} }
@ -121,7 +121,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) {
cuid, cuid,
static_cast<unsigned long>(currentPayloadLength), static_cast<unsigned long>(currentPayloadLength),
static_cast<unsigned long>(temp)); static_cast<unsigned long>(temp));
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
resbufLength += remaining; resbufLength += remaining;
if(currentPayloadLength > resbufLength) { if(currentPayloadLength > resbufLength) {
@ -168,7 +168,7 @@ bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength,
logger->debug logger->debug
("CUID#%d - In PeerConnection::receiveHandshake(), remain=%lu", ("CUID#%d - In PeerConnection::receiveHandshake(), remain=%lu",
cuid, static_cast<unsigned long>(temp)); cuid, static_cast<unsigned long>(temp));
throw DlAbortEx(EX_EOF_FROM_PEER); throw DL_ABORT_EX(EX_EOF_FROM_PEER);
} }
resbufLength += remaining; resbufLength += remaining;
if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength) { if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength) {

View File

@ -65,38 +65,38 @@ uint16_t PeerMessageUtil::getShortIntParam(const unsigned char* msg, size_t pos)
void PeerMessageUtil::checkIndex(size_t index, size_t pieces) { void PeerMessageUtil::checkIndex(size_t index, size_t pieces) {
if(!(index < pieces)) { if(!(index < pieces)) {
throw DlAbortEx(StringFormat("Invalid index: %lu", throw DL_ABORT_EX(StringFormat("Invalid index: %lu",
static_cast<unsigned long>(index)).str()); static_cast<unsigned long>(index)).str());
} }
} }
void PeerMessageUtil::checkBegin(uint32_t begin, size_t pieceLength) { void PeerMessageUtil::checkBegin(uint32_t begin, size_t pieceLength) {
if(!(begin < pieceLength)) { if(!(begin < pieceLength)) {
throw DlAbortEx(StringFormat("Invalid begin: %u", begin).str()); throw DL_ABORT_EX(StringFormat("Invalid begin: %u", begin).str());
} }
} }
void PeerMessageUtil::checkLength(size_t length) { void PeerMessageUtil::checkLength(size_t length) {
if(length > MAX_BLOCK_LENGTH) { if(length > MAX_BLOCK_LENGTH) {
throw DlAbortEx(StringFormat("Length too long: %lu > %uKB", throw DL_ABORT_EX(StringFormat("Length too long: %lu > %uKB",
static_cast<unsigned long>(length), static_cast<unsigned long>(length),
MAX_BLOCK_LENGTH/1024).str()); MAX_BLOCK_LENGTH/1024).str());
} }
if(length == 0) { if(length == 0) {
throw DlAbortEx(StringFormat("Invalid length: %lu", throw DL_ABORT_EX(StringFormat("Invalid length: %lu",
static_cast<unsigned long>(length)).str()); static_cast<unsigned long>(length)).str());
} }
} }
void PeerMessageUtil::checkRange(uint32_t begin, size_t length, size_t pieceLength) { void PeerMessageUtil::checkRange(uint32_t begin, size_t length, size_t pieceLength) {
if(!(0 < length)) { if(!(0 < length)) {
throw DlAbortEx(StringFormat("Invalid range: begin=%u, length=%lu", throw DL_ABORT_EX(StringFormat("Invalid range: begin=%u, length=%lu",
begin, begin,
static_cast<unsigned long>(length)).str()); static_cast<unsigned long>(length)).str());
} }
uint32_t end = begin+length; uint32_t end = begin+length;
if(!(end <= pieceLength)) { if(!(end <= pieceLength)) {
throw DlAbortEx(StringFormat("Invalid range: begin=%u, length=%lu", throw DL_ABORT_EX(StringFormat("Invalid range: begin=%u, length=%lu",
begin, begin,
static_cast<unsigned long>(length)).str()); static_cast<unsigned long>(length)).str());
} }
@ -106,14 +106,14 @@ void PeerMessageUtil::checkBitfield(const unsigned char* bitfield,
size_t bitfieldLength, size_t bitfieldLength,
size_t pieces) { size_t pieces) {
if(!(bitfieldLength == (pieces+7)/8)) { if(!(bitfieldLength == (pieces+7)/8)) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Invalid bitfield length: %lu", (StringFormat("Invalid bitfield length: %lu",
static_cast<unsigned long>(bitfieldLength)).str()); static_cast<unsigned long>(bitfieldLength)).str());
} }
char lastbyte = bitfield[bitfieldLength-1]; char lastbyte = bitfield[bitfieldLength-1];
for(size_t i = 0; i < 8-pieces%8 && pieces%8 != 0; ++i) { for(size_t i = 0; i < 8-pieces%8 && pieces%8 != 0; ++i) {
if(!(((lastbyte >> i) & 1) == 0)) { if(!(((lastbyte >> i) & 1) == 0)) {
throw DlAbortEx("Invalid bitfield"); throw DL_ABORT_EX("Invalid bitfield");
} }
} }
} }
@ -187,7 +187,7 @@ void PeerMessageUtil::assertPayloadLengthGreater
(size_t threshold, size_t actual, const std::string& msgName) (size_t threshold, size_t actual, const std::string& msgName)
{ {
if(actual <= threshold) { if(actual <= threshold) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, msgName.c_str(), actual).str()); (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, msgName.c_str(), actual).str());
} }
} }
@ -196,7 +196,7 @@ void PeerMessageUtil::assertPayloadLengthEqual
(size_t expected, size_t actual, const std::string& msgName) (size_t expected, size_t actual, const std::string& msgName)
{ {
if(expected != actual) { if(expected != actual) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_INVALID_PAYLOAD_SIZE, msgName.c_str(), (StringFormat(EX_INVALID_PAYLOAD_SIZE, msgName.c_str(),
actual, expected).str()); actual, expected).str());
} }
@ -207,7 +207,7 @@ void PeerMessageUtil::assertID
{ {
uint8_t id = getId(data); uint8_t id = getId(data);
if(expected != id) { if(expected != id) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_INVALID_BT_MESSAGE_ID, id, msgName.c_str(), (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, msgName.c_str(),
expected).str()); expected).str());
} }

View File

@ -102,7 +102,7 @@ bool PeerReceiveHandshakeCommand::executeInternal()
btRegistry->getPeerStorage(infoHash); btRegistry->getPeerStorage(infoHash);
if(btContext.isNull() || !btRuntime->ready()) { if(btContext.isNull() || !btRuntime->ready()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Unknown info hash %s", infoHash.c_str()).str()); (StringFormat("Unknown info hash %s", infoHash.c_str()).str());
} }
TransferStat tstat = btContext->getOwnerRequestGroup()->calculateStat(); TransferStat tstat = btContext->getOwnerRequestGroup()->calculateStat();

View File

@ -102,7 +102,7 @@ bool Platform::setUp()
WSADATA wsaData; WSADATA wsaData;
memset((char*)&wsaData, 0, sizeof(wsaData)); memset((char*)&wsaData, 0, sizeof(wsaData));
if (WSAStartup(MAKEWORD(1, 1), &wsaData)) { if (WSAStartup(MAKEWORD(1, 1), &wsaData)) {
throw DlAbortEx(MSG_WINSOCK_INIT_FAILD); throw DL_ABORT_EX(MSG_WINSOCK_INIT_FAILD);
} }
#endif // HAVE_WINSOCK2_H #endif // HAVE_WINSOCK2_H

View File

@ -95,7 +95,7 @@ bool ReceiverMSEHandshakeCommand::executeInternal()
break; break;
case MSEHandshake::HANDSHAKE_LEGACY: { case MSEHandshake::HANDSHAKE_LEGACY: {
if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
throw DlAbortEx("The legacy BitTorrent handshake is not acceptable by the preference."); throw DL_ABORT_EX("The legacy BitTorrent handshake is not acceptable by the preference.");
} }
SharedHandle<PeerConnection> peerConnection SharedHandle<PeerConnection> peerConnection
(new PeerConnection(cuid, socket)); (new PeerConnection(cuid, socket));
@ -107,7 +107,7 @@ bool ReceiverMSEHandshakeCommand::executeInternal()
return true; return true;
} }
default: default:
throw DlAbortEx("Not supported handshake type."); throw DL_ABORT_EX("Not supported handshake type.");
} }
break; break;
} }

View File

@ -50,20 +50,23 @@ protected:
return e; return e;
} }
public: public:
RecoverableException(const std::string& msg): RecoverableException(const char* file, int line, const std::string& msg):
Exception(msg), Exception(file, line, msg),
_code(DownloadResult::UNKNOWN_ERROR) {} _code(DownloadResult::UNKNOWN_ERROR) {}
RecoverableException(const std::string& msg, const Exception& cause): RecoverableException(const char* file, int line, const std::string& msg,
Exception(msg, cause), const Exception& cause):
Exception(file, line, msg, cause),
_code(DownloadResult::UNKNOWN_ERROR) {} _code(DownloadResult::UNKNOWN_ERROR) {}
RecoverableException(const RecoverableException& e): RecoverableException(const char* file, int line,
Exception(e), const RecoverableException& e):
Exception(file, line, e),
_code(DownloadResult::UNKNOWN_ERROR) {} _code(DownloadResult::UNKNOWN_ERROR) {}
RecoverableException(const std::string& msg, DownloadResult::RESULT result): RecoverableException(const char* file, int line, const std::string& msg,
Exception(msg), _code(result) {} DownloadResult::RESULT result):
Exception(file, line, msg), _code(result) {}
DownloadResult::RESULT getCode() const { return _code; } DownloadResult::RESULT getCode() const { return _code; }
}; };

View File

@ -207,18 +207,18 @@ void RequestGroup::createInitialCommand(std::deque<Command*>& commands,
BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext); BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
if(!btContext.isNull()) { if(!btContext.isNull()) {
if(_option->getAsBool(PREF_DRY_RUN)) { if(_option->getAsBool(PREF_DRY_RUN)) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
("Cancel BitTorrent download in dry-run context."); ("Cancel BitTorrent download in dry-run context.");
} }
SharedHandle<BtRegistry> btRegistry = e->getBtRegistry(); SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
if(!btRegistry->getBtContext(btContext->getInfoHashAsString()).isNull()) { if(!btRegistry->getBtContext(btContext->getInfoHashAsString()).isNull()) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat("InfoHash %s is already registered.", (StringFormat("InfoHash %s is already registered.",
btContext->getInfoHashAsString().c_str()).str()); btContext->getInfoHashAsString().c_str()).str());
} }
if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) { if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
getFilePath().c_str()).str()); getFilePath().c_str()).str());
} }
@ -313,7 +313,7 @@ void RequestGroup::createInitialCommand(std::deque<Command*>& commands,
!_option->getAsBool(PREF_ALLOW_OVERWRITE) && !_option->getAsBool(PREF_ALLOW_OVERWRITE) &&
!_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) { !_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
// TODO we need this->haltRequested = true? // TODO we need this->haltRequested = true?
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat (StringFormat
(MSG_FILE_ALREADY_EXISTS, (MSG_FILE_ALREADY_EXISTS,
getFilePath().c_str()).str()); getFilePath().c_str()).str());
@ -364,7 +364,7 @@ void RequestGroup::createInitialCommand(std::deque<Command*>& commands,
createNextCommand(commands, e, 1, method); createNextCommand(commands, e, 1, method);
}else { }else {
if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) { if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
getFilePath().c_str()).str()); getFilePath().c_str()).str());
} }
@ -529,7 +529,7 @@ void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoF
} }
setProgressInfoFile(progressInfoFile); setProgressInfoFile(progressInfoFile);
} catch(RecoverableException& e) { } catch(RecoverableException& e) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION2
(StringFormat(EX_DOWNLOAD_ABORTED).str(), e); (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
} }
} }
@ -546,12 +546,12 @@ void RequestGroup::shouldCancelDownloadForSafety()
if(tryAutoFileRenaming()) { if(tryAutoFileRenaming()) {
_logger->notice(MSG_FILE_RENAMED, getFilePath().c_str()); _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
} else { } else {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat("File renaming failed: %s", (StringFormat("File renaming failed: %s",
getFilePath().c_str()).str()); getFilePath().c_str()).str());
} }
} else { } else {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION
(StringFormat(MSG_FILE_ALREADY_EXISTS, (StringFormat(MSG_FILE_ALREADY_EXISTS,
getFilePath().c_str()).str()); getFilePath().c_str()).str());
} }
@ -722,7 +722,7 @@ void RequestGroup::validateFilename(const std::string& expectedFilename,
return; return;
} }
if(expectedFilename != actualFilename) { if(expectedFilename != actualFilename) {
throw DlAbortEx(StringFormat(EX_FILENAME_MISMATCH, throw DL_ABORT_EX(StringFormat(EX_FILENAME_MISMATCH,
expectedFilename.c_str(), expectedFilename.c_str(),
actualFilename.c_str()).str()); actualFilename.c_str()).str());
} }
@ -735,7 +735,7 @@ void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
return; return;
} }
if(expectedTotalLength != actualTotalLength) { if(expectedTotalLength != actualTotalLength) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_SIZE_MISMATCH, (StringFormat(EX_SIZE_MISMATCH,
Util::itos(expectedTotalLength, true).c_str(), Util::itos(expectedTotalLength, true).c_str(),
Util::itos(actualTotalLength, true).c_str()).str()); Util::itos(actualTotalLength, true).c_str()).str());
@ -1200,7 +1200,7 @@ void RequestGroup::increaseAndValidateFileNotFoundCount()
const unsigned int maxCount = _option->getAsInt(PREF_MAX_FILE_NOT_FOUND); const unsigned int maxCount = _option->getAsInt(PREF_MAX_FILE_NOT_FOUND);
if(maxCount > 0 && _fileNotFoundCount >= maxCount && if(maxCount > 0 && _fileNotFoundCount >= maxCount &&
_segmentMan->calculateSessionDownloadLength() == 0) { _segmentMan->calculateSessionDownloadLength() == 0) {
throw DownloadFailureException throw DOWNLOAD_FAILURE_EXCEPTION2
(StringFormat("Reached max-file-not-found count=%u", maxCount).str(), (StringFormat("Reached max-file-not-found count=%u", maxCount).str(),
DownloadResult::MAX_FILE_NOT_FOUND); DownloadResult::MAX_FILE_NOT_FOUND);
} }

View File

@ -94,7 +94,7 @@ SimpleLogger::~SimpleLogger() {
void SimpleLogger::openFile(const std::string& filename) { void SimpleLogger::openFile(const std::string& filename) {
file.open(filename.c_str(), std::ios::app|std::ios::binary); file.open(filename.c_str(), std::ios::app|std::ios::binary);
if(!file) { if(!file) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str()); (StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str());
} }
} }

View File

@ -173,7 +173,7 @@ void SocketCore::bind(uint16_t port)
int s; int s;
s = getaddrinfo(0, uitos(port).c_str(), &hints, &res); s = getaddrinfo(0, uitos(port).c_str(), &hints, &res);
if(s) { if(s) {
throw DlAbortEx(StringFormat(EX_SOCKET_BIND, gai_strerror(s)).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_BIND, gai_strerror(s)).str());
} }
struct addrinfo* rp; struct addrinfo* rp;
for(rp = res; rp; rp = rp->ai_next) { for(rp = res; rp; rp = rp->ai_next) {
@ -195,14 +195,14 @@ void SocketCore::bind(uint16_t port)
} }
freeaddrinfo(res); freeaddrinfo(res);
if(sockfd == -1) { if(sockfd == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_BIND, "all addresses failed").str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_BIND, "all addresses failed").str());
} }
} }
void SocketCore::beginListen() void SocketCore::beginListen()
{ {
if(listen(sockfd, 1) == -1) { if(listen(sockfd, 1) == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_LISTEN, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_LISTEN, errorMsg()).str());
} }
} }
@ -213,7 +213,7 @@ SocketCore* SocketCore::acceptConnection() const
sock_t fd; sock_t fd;
while((fd = accept(sockfd, reinterpret_cast<struct sockaddr*>(&sockaddr), &len)) == -1 && SOCKET_ERRNO == EINTR); while((fd = accept(sockfd, reinterpret_cast<struct sockaddr*>(&sockaddr), &len)) == -1 && SOCKET_ERRNO == EINTR);
if(fd == -1) { if(fd == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_ACCEPT, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_ACCEPT, errorMsg()).str());
} }
return new SocketCore(fd, _sockType); return new SocketCore(fd, _sockType);
} }
@ -224,7 +224,7 @@ void SocketCore::getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const
socklen_t len = sizeof(sockaddr); socklen_t len = sizeof(sockaddr);
struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr); struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
if(getsockname(sockfd, addrp, &len) == -1) { if(getsockname(sockfd, addrp, &len) == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str());
} }
addrinfo = Util::getNumericNameInfo(addrp, len); addrinfo = Util::getNumericNameInfo(addrp, len);
} }
@ -235,7 +235,7 @@ void SocketCore::getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const
socklen_t len = sizeof(sockaddr); socklen_t len = sizeof(sockaddr);
struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr); struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
if(getpeername(sockfd, addrp, &len) == -1) { if(getpeername(sockfd, addrp, &len) == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str());
} }
peerinfo = Util::getNumericNameInfo(addrp, len); peerinfo = Util::getNumericNameInfo(addrp, len);
} }
@ -254,7 +254,7 @@ void SocketCore::establishConnection(const std::string& host, uint16_t port)
int s; int s;
s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res); s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res);
if(s) { if(s) {
throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME, throw DL_ABORT_EX(StringFormat(EX_RESOLVE_HOSTNAME,
host.c_str(), gai_strerror(s)).str()); host.c_str(), gai_strerror(s)).str());
} }
struct addrinfo* rp; struct addrinfo* rp;
@ -283,7 +283,7 @@ void SocketCore::establishConnection(const std::string& host, uint16_t port)
} }
freeaddrinfo(res); freeaddrinfo(res);
if(sockfd == -1) { if(sockfd == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_CONNECT, host.c_str(), throw DL_ABORT_EX(StringFormat(EX_SOCKET_CONNECT, host.c_str(),
"all addresses failed").str()); "all addresses failed").str());
} }
} }
@ -293,7 +293,7 @@ void SocketCore::setNonBlockingMode()
#ifdef __MINGW32__ #ifdef __MINGW32__
static u_long flag = 1; static u_long flag = 1;
if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) { if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_NONBLOCKING, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_NONBLOCKING, errorMsg()).str());
} }
#else #else
int flags; int flags;
@ -309,7 +309,7 @@ void SocketCore::setBlockingMode()
#ifdef __MINGW32__ #ifdef __MINGW32__
static u_long flag = 0; static u_long flag = 0;
if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) { if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_BLOCKING, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_BLOCKING, errorMsg()).str());
} }
#else #else
int flags; int flags;
@ -355,7 +355,7 @@ void SocketCore::closeConnection()
void SocketCore::initEPOLL() void SocketCore::initEPOLL()
{ {
if((_epfd = epoll_create(1)) == -1) { if((_epfd = epoll_create(1)) == -1) {
throw DlRetryEx(StringFormat("epoll_create failed:%s", errorMsg()).str()); throw DL_RETRY_EX(StringFormat("epoll_create failed:%s", errorMsg()).str());
} }
memset(&_epEvent, 0, sizeof(struct epoll_event)); memset(&_epEvent, 0, sizeof(struct epoll_event));
@ -363,7 +363,7 @@ void SocketCore::initEPOLL()
_epEvent.data.fd = sockfd; _epEvent.data.fd = sockfd;
if(epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &_epEvent) == -1) { if(epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &_epEvent) == -1) {
throw DlRetryEx(StringFormat("epoll_ctl failed:%s", errorMsg()).str()); throw DL_RETRY_EX(StringFormat("epoll_ctl failed:%s", errorMsg()).str());
} }
} }
@ -384,7 +384,7 @@ bool SocketCore::isWritable(time_t timeout)
} else if(r == 0) { } else if(r == 0) {
return false; return false;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str());
} }
} else } else
#endif // HAVE_EPOLL #endif // HAVE_EPOLL
@ -407,7 +407,7 @@ bool SocketCore::isWritable(time_t timeout)
if(SOCKET_ERRNO == A2_EINPROGRESS || SOCKET_ERRNO == EINTR) { if(SOCKET_ERRNO == A2_EINPROGRESS || SOCKET_ERRNO == EINTR) {
return false; return false;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str());
} }
} }
} else { } else {
@ -437,7 +437,7 @@ bool SocketCore::isReadable(time_t timeout)
} else if(r == 0) { } else if(r == 0) {
return false; return false;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str());
} }
} else } else
#endif // HAVE_EPOLL #endif // HAVE_EPOLL
@ -460,7 +460,7 @@ bool SocketCore::isReadable(time_t timeout)
if(SOCKET_ERRNO == A2_EINPROGRESS || SOCKET_ERRNO == EINTR) { if(SOCKET_ERRNO == A2_EINPROGRESS || SOCKET_ERRNO == EINTR) {
return false; return false;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str());
} }
} }
} else { } else {
@ -509,14 +509,14 @@ ssize_t SocketCore::writeData(const char* data, size_t len)
_wantWrite = true; _wantWrite = true;
ret = 0; ret = 0;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_SEND, errorMsg()).str());
} }
} }
} else { } else {
#ifdef HAVE_LIBSSL #ifdef HAVE_LIBSSL
ret = SSL_write(ssl, data, len); ret = SSL_write(ssl, data, len);
if(ret == 0) { if(ret == 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat (StringFormat
(EX_SOCKET_SEND, ERR_error_string(SSL_get_error(ssl, ret), 0)).str()); (EX_SOCKET_SEND, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
} }
@ -524,7 +524,7 @@ ssize_t SocketCore::writeData(const char* data, size_t len)
ret = sslHandleEAGAIN(ret); ret = sslHandleEAGAIN(ret);
} }
if(ret < 0) { if(ret < 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat (StringFormat
(EX_SOCKET_SEND, ERR_error_string(SSL_get_error(ssl, ret), 0)).str()); (EX_SOCKET_SEND, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
} }
@ -536,7 +536,7 @@ ssize_t SocketCore::writeData(const char* data, size_t len)
gnutlsRecordCheckDirection(); gnutlsRecordCheckDirection();
ret = 0; ret = 0;
} else if(ret < 0) { } else if(ret < 0) {
throw DlRetryEx(StringFormat(EX_SOCKET_SEND, gnutls_strerror(ret)).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_SEND, gnutls_strerror(ret)).str());
} }
#endif // HAVE_LIBGNUTLS #endif // HAVE_LIBGNUTLS
} }
@ -558,7 +558,7 @@ void SocketCore::readData(char* data, size_t& len)
_wantRead = true; _wantRead = true;
ret = 0; ret = 0;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_RECV, errorMsg()).str());
} }
} }
} else { } else {
@ -567,7 +567,7 @@ void SocketCore::readData(char* data, size_t& len)
// TODO handling len == 0 case required // TODO handling len == 0 case required
ret = SSL_read(ssl, data, len); ret = SSL_read(ssl, data, len);
if(ret == 0) { if(ret == 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat (StringFormat
(EX_SOCKET_RECV, ERR_error_string(SSL_get_error(ssl, ret), 0)).str()); (EX_SOCKET_RECV, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
} }
@ -575,7 +575,7 @@ void SocketCore::readData(char* data, size_t& len)
ret = sslHandleEAGAIN(ret); ret = sslHandleEAGAIN(ret);
} }
if(ret < 0) { if(ret < 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat (StringFormat
(EX_SOCKET_RECV, ERR_error_string(SSL_get_error(ssl, ret), 0)).str()); (EX_SOCKET_RECV, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
} }
@ -586,7 +586,7 @@ void SocketCore::readData(char* data, size_t& len)
gnutlsRecordCheckDirection(); gnutlsRecordCheckDirection();
ret = 0; ret = 0;
} else if(ret < 0) { } else if(ret < 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str()); (StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str());
} }
#endif // HAVE_LIBGNUTLS #endif // HAVE_LIBGNUTLS
@ -608,7 +608,7 @@ void SocketCore::peekData(char* data, size_t& len)
_wantRead = true; _wantRead = true;
ret = 0; ret = 0;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_PEEK, errorMsg()).str());
} }
} }
} else { } else {
@ -617,7 +617,7 @@ void SocketCore::peekData(char* data, size_t& len)
// TODO handling len == 0 case required // TODO handling len == 0 case required
ret = SSL_peek(ssl, data, len); ret = SSL_peek(ssl, data, len);
if(ret == 0) { if(ret == 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat(EX_SOCKET_PEEK, (StringFormat(EX_SOCKET_PEEK,
ERR_error_string(SSL_get_error(ssl, ret), 0)).str()); ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
} }
@ -625,7 +625,7 @@ void SocketCore::peekData(char* data, size_t& len)
ret = sslHandleEAGAIN(ret); ret = sslHandleEAGAIN(ret);
} }
if(ret < 0) { if(ret < 0) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat(EX_SOCKET_PEEK, (StringFormat(EX_SOCKET_PEEK,
ERR_error_string(SSL_get_error(ssl, ret), 0)).str()); ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
} }
@ -636,7 +636,7 @@ void SocketCore::peekData(char* data, size_t& len)
gnutlsRecordCheckDirection(); gnutlsRecordCheckDirection();
ret = 0; ret = 0;
} else if(ret < 0) { } else if(ret < 0) {
throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, throw DL_RETRY_EX(StringFormat(EX_SOCKET_PEEK,
gnutls_strerror(ret)).str()); gnutls_strerror(ret)).str());
} }
#endif // HAVE_LIBGNUTLS #endif // HAVE_LIBGNUTLS
@ -685,7 +685,7 @@ static ssize_t GNUTLS_RECORD_RECV_NO_INTERRUPT
while((ret = gnutls_record_recv(sslSession, data, len)) == while((ret = gnutls_record_recv(sslSession, data, len)) ==
GNUTLS_E_INTERRUPTED); GNUTLS_E_INTERRUPTED);
if(ret < 0 && ret != GNUTLS_E_AGAIN) { if(ret < 0 && ret != GNUTLS_E_AGAIN) {
throw DlRetryEx throw DL_RETRY_EX
(StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str()); (StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str());
} }
return ret; return ret;
@ -731,12 +731,12 @@ void SocketCore::prepareSecureConnection()
// for SSL // for SSL
ssl = SSL_new(_tlsContext->getSSLCtx()); ssl = SSL_new(_tlsContext->getSSLCtx());
if(!ssl) { if(!ssl) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_SSL_INIT_FAILURE, (StringFormat(EX_SSL_INIT_FAILURE,
ERR_error_string(ERR_get_error(), 0)).str()); ERR_error_string(ERR_get_error(), 0)).str());
} }
if(SSL_set_fd(ssl, sockfd) == 0) { if(SSL_set_fd(ssl, sockfd) == 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_SSL_INIT_FAILURE, (StringFormat(EX_SSL_INIT_FAILURE,
ERR_error_string(ERR_get_error(), 0)).str()); ERR_error_string(ERR_get_error(), 0)).str());
} }
@ -782,19 +782,19 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
case SSL_ERROR_WANT_X509_LOOKUP: case SSL_ERROR_WANT_X509_LOOKUP:
case SSL_ERROR_ZERO_RETURN: case SSL_ERROR_ZERO_RETURN:
if (blocking) { if (blocking) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_SSL_CONNECT_ERROR, ssl_error).str()); (StringFormat(EX_SSL_CONNECT_ERROR, ssl_error).str());
} }
break; break;
case SSL_ERROR_SYSCALL: case SSL_ERROR_SYSCALL:
throw DlAbortEx(EX_SSL_IO_ERROR); throw DL_ABORT_EX(EX_SSL_IO_ERROR);
case SSL_ERROR_SSL: case SSL_ERROR_SSL:
throw DlAbortEx(EX_SSL_PROTOCOL_ERROR); throw DL_ABORT_EX(EX_SSL_PROTOCOL_ERROR);
default: default:
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_SSL_UNKNOWN_ERROR, ssl_error).str()); (StringFormat(EX_SSL_UNKNOWN_ERROR, ssl_error).str());
} }
} }
@ -802,19 +802,19 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
// verify peer // verify peer
X509* peerCert = SSL_get_peer_certificate(ssl); X509* peerCert = SSL_get_peer_certificate(ssl);
if(!peerCert) { if(!peerCert) {
throw DlAbortEx(MSG_NO_CERT_FOUND); throw DL_ABORT_EX(MSG_NO_CERT_FOUND);
} }
auto_delete<X509*> certDeleter(peerCert, X509_free); auto_delete<X509*> certDeleter(peerCert, X509_free);
long verifyResult = SSL_get_verify_result(ssl); long verifyResult = SSL_get_verify_result(ssl);
if(verifyResult != X509_V_OK) { if(verifyResult != X509_V_OK) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_CERT_VERIFICATION_FAILED, (StringFormat(MSG_CERT_VERIFICATION_FAILED,
X509_verify_cert_error_string(verifyResult)).str()); X509_verify_cert_error_string(verifyResult)).str());
} }
X509_NAME* name = X509_get_subject_name(peerCert); X509_NAME* name = X509_get_subject_name(peerCert);
if(!name) { if(!name) {
throw DlAbortEx("Could not get X509 name object from the certificate."); throw DL_ABORT_EX("Could not get X509 name object from the certificate.");
} }
bool hostnameOK = false; bool hostnameOK = false;
@ -838,7 +838,7 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
} }
} }
if(!hostnameOK) { if(!hostnameOK) {
throw DlAbortEx(MSG_HOSTNAME_NOT_MATCH); throw DL_ABORT_EX(MSG_HOSTNAME_NOT_MATCH);
} }
} }
#endif // HAVE_LIBSSL #endif // HAVE_LIBSSL
@ -848,7 +848,7 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
gnutlsRecordCheckDirection(); gnutlsRecordCheckDirection();
return false; return false;
} else if(ret < 0) { } else if(ret < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)).str()); (StringFormat(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)).str());
} }
@ -857,7 +857,7 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
unsigned int status; unsigned int status;
ret = gnutls_certificate_verify_peers2(sslSession, &status); ret = gnutls_certificate_verify_peers2(sslSession, &status);
if(ret < 0) { if(ret < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("gnutls_certificate_verify_peer2() failed. Cause: %s", (StringFormat("gnutls_certificate_verify_peer2() failed. Cause: %s",
gnutls_strerror(ret)).str()); gnutls_strerror(ret)).str());
} }
@ -873,27 +873,27 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
errors += " `issuer is not known'"; errors += " `issuer is not known'";
} }
if(!errors.empty()) { if(!errors.empty()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_CERT_VERIFICATION_FAILED, errors.c_str()).str()); (StringFormat(MSG_CERT_VERIFICATION_FAILED, errors.c_str()).str());
} }
} }
// certificate type: only X509 is allowed. // certificate type: only X509 is allowed.
if(gnutls_certificate_type_get(sslSession) != GNUTLS_CRT_X509) { if(gnutls_certificate_type_get(sslSession) != GNUTLS_CRT_X509) {
throw DlAbortEx("Certificate type is not X509."); throw DL_ABORT_EX("Certificate type is not X509.");
} }
unsigned int peerCertsLength; unsigned int peerCertsLength;
const gnutls_datum_t* peerCerts = gnutls_certificate_get_peers const gnutls_datum_t* peerCerts = gnutls_certificate_get_peers
(sslSession, &peerCertsLength); (sslSession, &peerCertsLength);
if(!peerCerts) { if(!peerCerts) {
throw DlAbortEx(MSG_NO_CERT_FOUND); throw DL_ABORT_EX(MSG_NO_CERT_FOUND);
} }
Time now; Time now;
for(unsigned int i = 0; i < peerCertsLength; ++i) { for(unsigned int i = 0; i < peerCertsLength; ++i) {
gnutls_x509_crt_t cert; gnutls_x509_crt_t cert;
ret = gnutls_x509_crt_init(&cert); ret = gnutls_x509_crt_init(&cert);
if(ret < 0) { if(ret < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("gnutls_x509_crt_init() failed. Cause: %s", (StringFormat("gnutls_x509_crt_init() failed. Cause: %s",
gnutls_strerror(ret)).str()); gnutls_strerror(ret)).str());
} }
@ -901,28 +901,28 @@ bool SocketCore::initiateSecureConnection(const std::string& hostname)
(cert, gnutls_x509_crt_deinit); (cert, gnutls_x509_crt_deinit);
ret = gnutls_x509_crt_import(cert, &peerCerts[i], GNUTLS_X509_FMT_DER); ret = gnutls_x509_crt_import(cert, &peerCerts[i], GNUTLS_X509_FMT_DER);
if(ret < 0) { if(ret < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("gnutls_x509_crt_import() failed. Cause: %s", (StringFormat("gnutls_x509_crt_import() failed. Cause: %s",
gnutls_strerror(ret)).str()); gnutls_strerror(ret)).str());
} }
if(i == 0) { if(i == 0) {
if(!gnutls_x509_crt_check_hostname(cert, hostname.c_str())) { if(!gnutls_x509_crt_check_hostname(cert, hostname.c_str())) {
throw DlAbortEx(MSG_HOSTNAME_NOT_MATCH); throw DL_ABORT_EX(MSG_HOSTNAME_NOT_MATCH);
} }
} }
time_t activationTime = gnutls_x509_crt_get_activation_time(cert); time_t activationTime = gnutls_x509_crt_get_activation_time(cert);
if(activationTime == -1) { if(activationTime == -1) {
throw DlAbortEx("Could not get activation time from certificate."); throw DL_ABORT_EX("Could not get activation time from certificate.");
} }
if(now.getTime() < activationTime) { if(now.getTime() < activationTime) {
throw DlAbortEx("Certificate is not activated yet."); throw DL_ABORT_EX("Certificate is not activated yet.");
} }
time_t expirationTime = gnutls_x509_crt_get_expiration_time(cert); time_t expirationTime = gnutls_x509_crt_get_expiration_time(cert);
if(expirationTime == -1) { if(expirationTime == -1) {
throw DlAbortEx("Could not get expiration time from certificate."); throw DL_ABORT_EX("Could not get expiration time from certificate.");
} }
if(expirationTime < now.getTime()) { if(expirationTime < now.getTime()) {
throw DlAbortEx("Certificate has expired."); throw DL_ABORT_EX("Certificate has expired.");
} }
} }
} }
@ -983,7 +983,7 @@ ssize_t SocketCore::writeData(const char* data, size_t len,
int s; int s;
s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res); s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res);
if(s) { if(s) {
throw DlAbortEx(StringFormat(EX_SOCKET_SEND, gai_strerror(s)).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_SEND, gai_strerror(s)).str());
} }
struct addrinfo* rp; struct addrinfo* rp;
ssize_t r = -1; ssize_t r = -1;
@ -1000,7 +1000,7 @@ ssize_t SocketCore::writeData(const char* data, size_t len,
} }
freeaddrinfo(res); freeaddrinfo(res);
if(r == -1) { if(r == -1) {
throw DlAbortEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str()); throw DL_ABORT_EX(StringFormat(EX_SOCKET_SEND, errorMsg()).str());
} }
return r; return r;
} }
@ -1022,7 +1022,7 @@ ssize_t SocketCore::readDataFrom(char* data, size_t len,
_wantRead = true; _wantRead = true;
r = 0; r = 0;
} else { } else {
throw DlRetryEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str()); throw DL_RETRY_EX(StringFormat(EX_SOCKET_RECV, errorMsg()).str());
} }
} else { } else {
sender = Util::getNumericNameInfo(addrp, sockaddrlen); sender = Util::getNumericNameInfo(addrp, sockaddrlen);
@ -1037,7 +1037,7 @@ std::string SocketCore::getSocketError() const
socklen_t optlen = sizeof(error); socklen_t optlen = sizeof(error);
if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (a2_sockopt_t) &error, &optlen) == -1) { if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (a2_sockopt_t) &error, &optlen) == -1) {
throw DlAbortEx(StringFormat("Failed to get socket error: %s", throw DL_ABORT_EX(StringFormat("Failed to get socket error: %s",
errorMsg()).str()); errorMsg()).str());
} }
if(error != 0) { if(error != 0) {

View File

@ -38,7 +38,7 @@
#include <sqlite3.h> #include <sqlite3.h>
#include "RecoverableException.h" #include "DlAbortEx.h"
#include "Util.h" #include "Util.h"
#include "StringFormat.h" #include "StringFormat.h"
#include "A2STR.h" #include "A2STR.h"
@ -98,7 +98,7 @@ Sqlite3MozCookieParser::parse(const std::string& filename) const
ret = sqlite3_open_v2(filename.c_str(), &db, SQLITE_OPEN_READONLY, 0); ret = sqlite3_open_v2(filename.c_str(), &db, SQLITE_OPEN_READONLY, 0);
#else // !HAVE_SQLITE3_OPEN_V2 #else // !HAVE_SQLITE3_OPEN_V2
if(!File(filename).isFile()) { if(!File(filename).isFile()) {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Failed to open SQLite3 database: %s", (StringFormat("Failed to open SQLite3 database: %s",
filename.c_str()).str()); filename.c_str()).str());
} }
@ -107,7 +107,7 @@ Sqlite3MozCookieParser::parse(const std::string& filename) const
if(SQLITE_OK != ret) { if(SQLITE_OK != ret) {
std::string errMsg = sqlite3_errmsg(db); std::string errMsg = sqlite3_errmsg(db);
sqlite3_close(db); sqlite3_close(db);
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Failed to open SQLite3 database: %s", (StringFormat("Failed to open SQLite3 database: %s",
errMsg.c_str()).str()); errMsg.c_str()).str());
} }
@ -123,7 +123,7 @@ Sqlite3MozCookieParser::parse(const std::string& filename) const
} }
if(SQLITE_OK != ret) { if(SQLITE_OK != ret) {
sqlite3_close(db); sqlite3_close(db);
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Failed to read SQLite3 database: %s", (StringFormat("Failed to read SQLite3 database: %s",
errMsg.c_str()).str()); errMsg.c_str()).str());
} }

View File

@ -167,7 +167,7 @@ UTPexExtensionMessageHandle
UTPexExtensionMessage::create(const unsigned char* data, size_t len) UTPexExtensionMessage::create(const unsigned char* data, size_t len)
{ {
if(len < 1) { if(len < 1) {
throw DlAbortEx(StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, throw DL_ABORT_EX(StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE,
EXTENSION_NAME.c_str(), len).str()); EXTENSION_NAME.c_str(), len).str());
} }
UTPexExtensionMessageHandle msg(new UTPexExtensionMessage(*data)); UTPexExtensionMessageHandle msg(new UTPexExtensionMessage(*data));

View File

@ -427,19 +427,19 @@ int32_t Util::parseInt(const std::string& s, int32_t base)
{ {
std::string trimed = Util::trim(s); std::string trimed = Util::trim(s);
if(trimed.empty()) { if(trimed.empty()) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"empty string").str()); "empty string").str());
} }
char* stop; char* stop;
errno = 0; errno = 0;
long int v = strtol(trimed.c_str(), &stop, base); long int v = strtol(trimed.c_str(), &stop, base);
if(*stop != '\0') { if(*stop != '\0') {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} else if((((v == LONG_MIN) || (v == LONG_MAX)) && (errno == ERANGE)) || } else if((((v == LONG_MIN) || (v == LONG_MAX)) && (errno == ERANGE)) ||
(v > INT32_MAX) || (v > INT32_MAX) ||
(v < INT32_MIN)) { (v < INT32_MIN)) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} }
return v; return v;
@ -449,22 +449,22 @@ uint32_t Util::parseUInt(const std::string& s, int base)
{ {
std::string trimed = Util::trim(s); std::string trimed = Util::trim(s);
if(trimed.empty()) { if(trimed.empty()) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"empty string").str()); "empty string").str());
} }
// We don't allow negative number. // We don't allow negative number.
if(trimed[0] == '-') { if(trimed[0] == '-') {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} }
char* stop; char* stop;
errno = 0; errno = 0;
unsigned long int v = strtoul(trimed.c_str(), &stop, base); unsigned long int v = strtoul(trimed.c_str(), &stop, base);
if(*stop != '\0') { if(*stop != '\0') {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) { } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} }
return v; return v;
@ -474,17 +474,17 @@ int64_t Util::parseLLInt(const std::string& s, int32_t base)
{ {
std::string trimed = Util::trim(s); std::string trimed = Util::trim(s);
if(trimed.empty()) { if(trimed.empty()) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"empty string").str()); "empty string").str());
} }
char* stop; char* stop;
errno = 0; errno = 0;
int64_t v = strtoll(trimed.c_str(), &stop, base); int64_t v = strtoll(trimed.c_str(), &stop, base);
if(*stop != '\0') { if(*stop != '\0') {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) { } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} }
return v; return v;
@ -494,22 +494,22 @@ uint64_t Util::parseULLInt(const std::string& s, int base)
{ {
std::string trimed = Util::trim(s); std::string trimed = Util::trim(s);
if(trimed.empty()) { if(trimed.empty()) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"empty string").str()); "empty string").str());
} }
// We don't allow negative number. // We don't allow negative number.
if(trimed[0] == '-') { if(trimed[0] == '-') {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} }
char* stop; char* stop;
errno = 0; errno = 0;
uint64_t v = strtoull(trimed.c_str(), &stop, base); uint64_t v = strtoull(trimed.c_str(), &stop, base);
if(*stop != '\0') { if(*stop != '\0') {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} else if((v == ULLONG_MAX) && (errno == ERANGE)) { } else if((v == ULLONG_MAX) && (errno == ERANGE)) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
trimed.c_str()).str()); trimed.c_str()).str());
} }
return v; return v;
@ -531,7 +531,7 @@ IntSequence Util::parseIntRange(const std::string& src)
} else { } else {
std::pair<std::string, std::string> vp = Util::split(p.first.c_str(), "-"); std::pair<std::string, std::string> vp = Util::split(p.first.c_str(), "-");
if(vp.first.empty() || vp.second.empty()) { if(vp.first.empty() || vp.second.empty()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(MSG_INCOMPLETE_RANGE, p.first.c_str()).str()); (StringFormat(MSG_INCOMPLETE_RANGE, p.first.c_str()).str());
} }
int32_t v1 = Util::parseInt(vp.first.c_str()); int32_t v1 = Util::parseInt(vp.first.c_str());
@ -656,10 +656,10 @@ int64_t Util::getRealSize(const std::string& sizeWithUnit)
int64_t v = Util::parseLLInt(size); int64_t v = Util::parseLLInt(size);
if(v < 0) { if(v < 0) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Negative value detected: %s", sizeWithUnit.c_str()).str()); (StringFormat("Negative value detected: %s", sizeWithUnit.c_str()).str());
} else if(INT64_MAX/mult < v) { } else if(INT64_MAX/mult < v) {
throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
"overflow/underflow").str()); "overflow/underflow").str());
} }
return v*mult; return v*mult;
@ -827,11 +827,11 @@ void Util::mkdirs(const std::string& dirpath)
if(dir.isDir()) { if(dir.isDir()) {
// do nothing // do nothing
} else if(dir.exists()) { } else if(dir.exists()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_MAKE_DIR, dir.getPath().c_str(), (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
"File already exists.").str()); "File already exists.").str());
} else if(!dir.mkdirs()) { } else if(!dir.mkdirs()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_MAKE_DIR, dir.getPath().c_str(), (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
strerror(errno)).str()); strerror(errno)).str());
} }
@ -871,7 +871,7 @@ void* Util::allocateAlignedMemory(size_t alignment, size_t size)
void* buffer; void* buffer;
int res; int res;
if((res = posix_memalign(&buffer, alignment, size)) != 0) { if((res = posix_memalign(&buffer, alignment, size)) != 0) {
throw FatalException throw FATAL_EXCEPTION
(StringFormat("Error in posix_memalign: %s", strerror(res)).str()); (StringFormat("Error in posix_memalign: %s", strerror(res)).str());
} }
return buffer; return buffer;
@ -886,7 +886,7 @@ Util::getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV, int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
NI_NUMERICHOST|NI_NUMERICSERV); NI_NUMERICHOST|NI_NUMERICSERV);
if(s != 0) { if(s != 0) {
throw DlAbortEx(StringFormat("Failed to get hostname and port. cause: %s", throw DL_ABORT_EX(StringFormat("Failed to get hostname and port. cause: %s",
gai_strerror(s)).str()); gai_strerror(s)).str());
} }
return std::pair<std::string, uint16_t>(host, atoi(service)); // TODO return std::pair<std::string, uint16_t>(host, atoi(service)); // TODO
@ -920,7 +920,7 @@ Util::parseIndexPath(const std::string& line)
std::pair<std::string, std::string> p = Util::split(line, "="); std::pair<std::string, std::string> p = Util::split(line, "=");
size_t index = parseUInt(p.first); size_t index = parseUInt(p.first);
if(p.second.empty()) { if(p.second.empty()) {
throw DlAbortEx(StringFormat("Path with index=%u is empty.", throw DL_ABORT_EX(StringFormat("Path with index=%u is empty.",
static_cast<unsigned int>(index)).str()); static_cast<unsigned int>(index)).str());
} }
return std::map<size_t, std::string>::value_type(index, p.second); return std::map<size_t, std::string>::value_type(index, p.second);

View File

@ -136,7 +136,7 @@ MetalinkProcessor::parseFile(const std::string& filename)
int retval = xmlSAXUserParseFile(&mySAXHandler, sessionData.get(), int retval = xmlSAXUserParseFile(&mySAXHandler, sessionData.get(),
filename.c_str()); filename.c_str());
if(retval != 0) { if(retval != 0) {
throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); throw DL_ABORT_EX(MSG_CANNOT_PARSE_METALINK);
} }
return _stm->getResult(); return _stm->getResult();
} }
@ -150,7 +150,7 @@ MetalinkProcessor::parseFromBinaryStream(const SharedHandle<BinaryStream>& binar
ssize_t res = binaryStream->readData(buf, 4, 0); ssize_t res = binaryStream->readData(buf, 4, 0);
if(res != 4) { if(res != 4) {
throw DlAbortEx("Too small data for parsing XML."); throw DL_ABORT_EX("Too small data for parsing XML.");
} }
SharedHandle<SessionData> sessionData(new SessionData(_stm)); SharedHandle<SessionData> sessionData(new SessionData(_stm));
@ -163,7 +163,7 @@ MetalinkProcessor::parseFromBinaryStream(const SharedHandle<BinaryStream>& binar
break; break;
} }
if(xmlParseChunk(ctx, (const char*)buf, res, 0) != 0) { if(xmlParseChunk(ctx, (const char*)buf, res, 0) != 0) {
throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); throw DL_ABORT_EX(MSG_CANNOT_PARSE_METALINK);
} }
readOffset += res; readOffset += res;
} }
@ -175,7 +175,7 @@ MetalinkProcessor::parseFromBinaryStream(const SharedHandle<BinaryStream>& binar
xmlFreeParserCtxt(ctx); xmlFreeParserCtxt(ctx);
if(!_stm->finished()) { if(!_stm->finished()) {
throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); throw DL_ABORT_EX(MSG_CANNOT_PARSE_METALINK);
} }
return _stm->getResult(); return _stm->getResult();
} }

View File

@ -141,7 +141,7 @@ XmlRpcRequestProcessor::parseMemory(const std::string& xml)
int r = xmlSAXUserParseMemory(&mySAXHandler, sessionData.get(), int r = xmlSAXUserParseMemory(&mySAXHandler, sessionData.get(),
xml.data(), xml.size()); xml.data(), xml.size());
if(r != 0) { if(r != 0) {
throw DlAbortEx(MSG_CANNOT_PARSE_XML_RPC_REQUEST); throw DL_ABORT_EX(MSG_CANNOT_PARSE_XML_RPC_REQUEST);
} }
return XmlRpcRequest(_stm->getMethodName(), _stm->getCurrentFrameValue()); return XmlRpcRequest(_stm->getMethodName(), _stm->getCurrentFrameValue());
} }

View File

@ -86,7 +86,7 @@ BDE AddUriXmlRpcMethod::process(const XmlRpcRequest& req, DownloadEngine* e)
const BDE& params = req._params; const BDE& params = req._params;
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isList() || params[0].empty()) { if(params.empty() || !params[0].isList() || params[0].empty()) {
throw DlAbortEx("URI is not provided."); throw DL_ABORT_EX("URI is not provided.");
} }
std::deque<std::string> uris; std::deque<std::string> uris;
for(BDE::List::const_iterator i = params[0].listBegin(); for(BDE::List::const_iterator i = params[0].listBegin();
@ -109,7 +109,7 @@ BDE AddUriXmlRpcMethod::process(const XmlRpcRequest& req, DownloadEngine* e)
e->_requestGroupMan->addReservedGroup(result.front()); e->_requestGroupMan->addReservedGroup(result.front());
return createGIDResponse(result.front()->getGID()); return createGIDResponse(result.front()->getGID());
} else { } else {
throw DlAbortEx("No URI to download."); throw DL_ABORT_EX("No URI to download.");
} }
} }
@ -119,7 +119,7 @@ BDE AddTorrentXmlRpcMethod::process
const BDE& params = req._params; const BDE& params = req._params;
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx("Torrent data is not provided."); throw DL_ABORT_EX("Torrent data is not provided.");
} }
std::deque<std::string> uris; std::deque<std::string> uris;
@ -145,7 +145,7 @@ BDE AddTorrentXmlRpcMethod::process
e->_requestGroupMan->addReservedGroup(result.front()); e->_requestGroupMan->addReservedGroup(result.front());
return createGIDResponse(result.front()->getGID()); return createGIDResponse(result.front()->getGID());
} else { } else {
throw DlAbortEx("No Torrent to download."); throw DL_ABORT_EX("No Torrent to download.");
} }
} }
@ -155,7 +155,7 @@ BDE AddMetalinkXmlRpcMethod::process
const BDE& params = req._params; const BDE& params = req._params;
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx("Metalink data is not provided."); throw DL_ABORT_EX("Metalink data is not provided.");
} }
SharedHandle<Option> requestOption(new Option(*e->option)); SharedHandle<Option> requestOption(new Option(*e->option));
@ -173,7 +173,7 @@ BDE AddMetalinkXmlRpcMethod::process
} }
return gids; return gids;
} else { } else {
throw DlAbortEx("No files to download."); throw DL_ABORT_EX("No files to download.");
} }
} }
@ -184,7 +184,7 @@ BDE RemoveXmlRpcMethod::process(const XmlRpcRequest& req, DownloadEngine* e)
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx(MSG_GID_NOT_PROVIDED); throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
} }
int32_t gid = Util::parseInt(params[0].s()); int32_t gid = Util::parseInt(params[0].s());
@ -194,13 +194,13 @@ BDE RemoveXmlRpcMethod::process(const XmlRpcRequest& req, DownloadEngine* e)
if(group.isNull()) { if(group.isNull()) {
group = e->_requestGroupMan->findReservedGroup(gid); group = e->_requestGroupMan->findReservedGroup(gid);
if(group.isNull()) { if(group.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Active Download not found for GID#%d", gid).str()); (StringFormat("Active Download not found for GID#%d", gid).str());
} }
if(group->isDependencyResolved()) { if(group->isDependencyResolved()) {
e->_requestGroupMan->removeReservedGroup(gid); e->_requestGroupMan->removeReservedGroup(gid);
} else { } else {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("GID#%d cannot be removed now", gid).str()); (StringFormat("GID#%d cannot be removed now", gid).str());
} }
} else { } else {
@ -320,7 +320,7 @@ BDE GetFilesXmlRpcMethod::process
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx(MSG_GID_NOT_PROVIDED); throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
} }
int32_t gid = Util::parseInt(params[0].s()); int32_t gid = Util::parseInt(params[0].s());
@ -331,7 +331,7 @@ BDE GetFilesXmlRpcMethod::process
SharedHandle<DownloadResult> dr = SharedHandle<DownloadResult> dr =
e->_requestGroupMan->findDownloadResult(gid); e->_requestGroupMan->findDownloadResult(gid);
if(dr.isNull()) { if(dr.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("No file data is available for GID#%d", gid).str()); (StringFormat("No file data is available for GID#%d", gid).str());
} else { } else {
createFileEntry(files, dr->fileEntries.begin(), dr->fileEntries.end()); createFileEntry(files, dr->fileEntries.begin(), dr->fileEntries.end());
@ -351,14 +351,14 @@ BDE GetUrisXmlRpcMethod::process
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx(MSG_GID_NOT_PROVIDED); throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
} }
int32_t gid = Util::parseInt(params[0].s()); int32_t gid = Util::parseInt(params[0].s());
SharedHandle<RequestGroup> group = findRequestGroup(e->_requestGroupMan, gid); SharedHandle<RequestGroup> group = findRequestGroup(e->_requestGroupMan, gid);
if(group.isNull()) { if(group.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("No URI data is available for GID#%d", gid).str()); (StringFormat("No URI data is available for GID#%d", gid).str());
} }
BDE uriList = BDE::list(); BDE uriList = BDE::list();
@ -380,14 +380,14 @@ BDE GetPeersXmlRpcMethod::process
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx(MSG_GID_NOT_PROVIDED); throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
} }
int32_t gid = Util::parseInt(params[0].s()); int32_t gid = Util::parseInt(params[0].s());
SharedHandle<RequestGroup> group = findRequestGroup(e->_requestGroupMan, gid); SharedHandle<RequestGroup> group = findRequestGroup(e->_requestGroupMan, gid);
if(group.isNull()) { if(group.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("No peer data is available for GID#%d", gid).str()); (StringFormat("No peer data is available for GID#%d", gid).str());
} }
BDE peers = BDE::list(); BDE peers = BDE::list();
@ -412,7 +412,7 @@ BDE TellStatusXmlRpcMethod::process
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx(MSG_GID_NOT_PROVIDED); throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
} }
int32_t gid = Util::parseInt(params[0].s()); int32_t gid = Util::parseInt(params[0].s());
@ -426,7 +426,7 @@ BDE TellStatusXmlRpcMethod::process
SharedHandle<DownloadResult> ds = SharedHandle<DownloadResult> ds =
e->_requestGroupMan->findDownloadResult(gid); e->_requestGroupMan->findDownloadResult(gid);
if(ds.isNull()) { if(ds.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("No such download for GID#%d", gid).str()); (StringFormat("No such download for GID#%d", gid).str());
} }
gatherStoppedDownload(entryDict, ds); gatherStoppedDownload(entryDict, ds);
@ -503,13 +503,13 @@ BDE ChangeOptionXmlRpcMethod::process
const BDE& params = req._params; const BDE& params = req._params;
assert(params.isList()); assert(params.isList());
if(params.empty() || !params[0].isString()) { if(params.empty() || !params[0].isString()) {
throw DlAbortEx(MSG_GID_NOT_PROVIDED); throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
} }
int32_t gid = Util::parseInt(params[0].s()); int32_t gid = Util::parseInt(params[0].s());
SharedHandle<RequestGroup> group = findRequestGroup(e->_requestGroupMan, gid); SharedHandle<RequestGroup> group = findRequestGroup(e->_requestGroupMan, gid);
if(group.isNull()) { if(group.isNull()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Cannot change option for GID#%d", gid).str()); (StringFormat("Cannot change option for GID#%d", gid).str());
} }
SharedHandle<Option> option(new Option(*group->getOption().get())); SharedHandle<Option> option(new Option(*group->getOption().get()));
@ -549,7 +549,7 @@ BDE ChangeGlobalOptionXmlRpcMethod::process
BDE NoSuchMethodXmlRpcMethod::process BDE NoSuchMethodXmlRpcMethod::process
(const XmlRpcRequest& req, DownloadEngine* e) (const XmlRpcRequest& req, DownloadEngine* e)
{ {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("No such method: %s", req._methodName.c_str()).str()); (StringFormat("No such method: %s", req._methodName.c_str()).str());
} }

View File

@ -38,7 +38,7 @@
#include <sstream> #include <sstream>
#include "StringFormat.h" #include "StringFormat.h"
#include "RecoverableException.h" #include "DlAbortEx.h"
namespace aria2 { namespace aria2 {
@ -50,7 +50,7 @@ static void checkdelim(std::istream& ss, const char delim = ':')
{ {
char d; char d;
if(!(ss.get(d) && d == delim)) { if(!(ss.get(d) && d == delim)) {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Delimiter '%c' not found.", delim).str()); (StringFormat("Delimiter '%c' not found.", delim).str());
} }
} }
@ -60,7 +60,7 @@ static std::string decoderawstring(std::istream& ss)
int length; int length;
ss >> length; ss >> length;
if(!ss || length < 0) { if(!ss || length < 0) {
throw RecoverableException("A positive integer expected but none found."); throw DL_ABORT_EX("A positive integer expected but none found.");
} }
// TODO check length, it must be less than or equal to INT_MAX // TODO check length, it must be less than or equal to INT_MAX
checkdelim(ss); checkdelim(ss);
@ -69,7 +69,7 @@ static std::string decoderawstring(std::istream& ss)
std::string str(&buf[0], &buf[length]); std::string str(&buf[0], &buf[length]);
delete [] buf; delete [] buf;
if(ss.gcount() != static_cast<int>(length)) { if(ss.gcount() != static_cast<int>(length)) {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Expected %lu bytes of data, but only %d read.", (StringFormat("Expected %lu bytes of data, but only %d read.",
static_cast<unsigned long>(length), ss.gcount()).str()); static_cast<unsigned long>(length), ss.gcount()).str());
} }
@ -86,7 +86,7 @@ static BDE decodeinteger(std::istream& ss)
BDE::Integer integer; BDE::Integer integer;
ss >> integer; ss >> integer;
if(!ss) { if(!ss) {
throw RecoverableException("Integer expected but none found"); throw DL_ABORT_EX("Integer expected but none found");
} }
checkdelim(ss, 'e'); checkdelim(ss, 'e');
return BDE(integer); return BDE(integer);
@ -105,7 +105,7 @@ static BDE decodedict(std::istream& ss)
dict[key] = decodeiter(ss); dict[key] = decodeiter(ss);
} }
} }
throw RecoverableException("Unexpected EOF in dict context. 'e' expected."); throw DL_ABORT_EX("Unexpected EOF in dict context. 'e' expected.");
} }
static BDE decodelist(std::istream& ss) static BDE decodelist(std::istream& ss)
@ -120,14 +120,14 @@ static BDE decodelist(std::istream& ss)
list << decodeiter(ss); list << decodeiter(ss);
} }
} }
throw RecoverableException("Unexpected EOF in list context. 'e' expected."); throw DL_ABORT_EX("Unexpected EOF in list context. 'e' expected.");
} }
static BDE decodeiter(std::istream& ss) static BDE decodeiter(std::istream& ss)
{ {
char c; char c;
if(!ss.get(c)) { if(!ss.get(c)) {
throw RecoverableException("Unexpected EOF in term context." throw DL_ABORT_EX("Unexpected EOF in term context."
" 'd', 'l', 'i' or digit is expected."); " 'd', 'l', 'i' or digit is expected.");
} }
if(c == 'd') { if(c == 'd') {
@ -168,7 +168,7 @@ BDE decodeFromFile(const std::string& filename)
if(f) { if(f) {
return decode(f); return decode(f);
} else { } else {
throw RecoverableException throw DL_ABORT_EX
(StringFormat("Cannot open file '%s'.", filename.c_str()).str()); (StringFormat("Cannot open file '%s'.", filename.c_str()).str());
} }
} }

View File

@ -266,7 +266,7 @@ void createRequestGroupForMetalink
Metalink2RequestGroup().generate(result, dw, option); Metalink2RequestGroup().generate(result, dw, option);
} }
if(result.empty()) { if(result.empty()) {
throw DlAbortEx(MSG_NO_FILES_TO_DOWNLOAD); throw DL_ABORT_EX(MSG_NO_FILES_TO_DOWNLOAD);
} }
} }
#endif // ENABLE_METALINK #endif // ENABLE_METALINK
@ -405,7 +405,7 @@ void createRequestGroupForUriList
createRequestGroupForUriList(result, option, std::cin); createRequestGroupForUriList(result, option, std::cin);
} else { } else {
if(!File(option->get(PREF_INPUT_FILE)).isFile()) { if(!File(option->get(PREF_INPUT_FILE)).isFile()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat(EX_FILE_OPEN, option->get(PREF_INPUT_FILE).c_str(), (StringFormat(EX_FILE_OPEN, option->get(PREF_INPUT_FILE).c_str(),
"No such file").str()); "No such file").str());
} }

View File

@ -104,7 +104,7 @@ public:
{ {
DigestAlgoMap::const_iterator itr = digestAlgos.find(algostring); DigestAlgoMap::const_iterator itr = digestAlgos.find(algostring);
if(itr == digestAlgos.end()) { if(itr == digestAlgos.end()) {
throw DlAbortEx throw DL_ABORT_EX
(StringFormat("Digest algorithm %s is not supported.", (StringFormat("Digest algorithm %s is not supported.",
algostring.c_str()).str()); algostring.c_str()).str());
} }

View File

@ -1,9 +1,10 @@
#include "Exception.h" #include "Exception.h"
#include "DownloadFailureException.h"
#include "Util.h"
#include <iostream> #include <iostream>
#include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/HelperMacros.h>
#include "DownloadFailureException.h"
namespace aria2 { namespace aria2 {
class ExceptionTest:public CppUnit::TestFixture { class ExceptionTest:public CppUnit::TestFixture {
@ -24,14 +25,16 @@ CPPUNIT_TEST_SUITE_REGISTRATION(ExceptionTest);
void ExceptionTest::testStackTrace() void ExceptionTest::testStackTrace()
{ {
DownloadFailureException c1("cause1"); DownloadFailureException c1 = DOWNLOAD_FAILURE_EXCEPTION("cause1");
DownloadFailureException c2("cause2", c1); DownloadFailureException c2 = DOWNLOAD_FAILURE_EXCEPTION2("cause2", c1);
DownloadFailureException e("exception thrown", c2); DownloadFailureException e = DOWNLOAD_FAILURE_EXCEPTION2("exception thrown",
c2);
CPPUNIT_ASSERT_EQUAL(std::string("Exception: exception thrown\n" CPPUNIT_ASSERT_EQUAL
" -> cause2\n" (std::string("Exception: [ExceptionTest.cc:31] exception thrown\n"
" -> cause1\n"), " -> [ExceptionTest.cc:29] cause2\n"
e.stackTrace()); " -> [ExceptionTest.cc:28] cause1\n"),
e.stackTrace());
} }
} // namespace aria2 } // namespace aria2

View File

@ -20,12 +20,12 @@ void createFile(const std::string& path, size_t length)
File(File(path).getDirname()).mkdirs(); File(File(path).getDirname()).mkdirs();
int fd = creat(path.c_str(), OPEN_MODE); int fd = creat(path.c_str(), OPEN_MODE);
if(fd == -1) { if(fd == -1) {
throw FatalException(StringFormat("Could not create file=%s. cause:%s", throw FATAL_EXCEPTION(StringFormat("Could not create file=%s. cause:%s",
path.c_str(), strerror(errno)).str()); path.c_str(), strerror(errno)).str());
} }
if(-1 == ftruncate(fd, length)) { if(-1 == ftruncate(fd, length)) {
throw FatalException(StringFormat("ftruncate failed. cause:%s", throw FATAL_EXCEPTION(StringFormat("ftruncate failed. cause:%s",
strerror(errno)).str()); strerror(errno)).str());
} }
close(fd); close(fd);
} }