From 269520ee69e2306eaf792ccff916ba5486d2bb5f Mon Sep 17 00:00:00 2001 From: Tatsuhiro Tsujikawa Date: Tue, 10 Nov 2015 23:02:21 +0900 Subject: Don't write control file if content is not changed from previous one This is desirable so that we don't have to wake up disk if control file is not changed, and it is not have to be written again. We use the same method (SHA1 hash) to check the content is the same. The limitation is the hash is stored in memory, so we have to write the first time in each session. See GH-382 --- src/SessionSerializer.cc | 76 +----------------------------------------------- 1 file changed, 1 insertion(+), 75 deletions(-) (limited to 'src/SessionSerializer.cc') diff --git a/src/SessionSerializer.cc b/src/SessionSerializer.cc index f2d12116..7dd91aef 100644 --- a/src/SessionSerializer.cc +++ b/src/SessionSerializer.cc @@ -53,7 +53,7 @@ #include "BufferedFile.h" #include "OptionParser.h" #include "OptionHandler.h" -#include "MessageDigest.h" +#include "SHA1IOFile.h" #if HAVE_ZLIB #include "GZipFile.h" @@ -327,80 +327,6 @@ bool SessionSerializer::save(IOFile& fp) const return true; } -namespace { -// Class to calculate SHA1 hash value for data written into this -// object. No file I/O is done in this class. -class SHA1IOFile : public IOFile { -public: - SHA1IOFile() - : sha1_(MessageDigest::sha1()) - {} - - std::string digest() - { - return sha1_->digest(); - } -protected: - virtual size_t onRead(void* ptr, size_t count) CXX11_OVERRIDE - { - assert(0); - return 0; - } - - virtual size_t onWrite(const void* ptr, size_t count) CXX11_OVERRIDE - { - sha1_->update(ptr, count); - - return count; - } - - virtual char* onGets(char* s, int size) CXX11_OVERRIDE - { - assert(0); - return nullptr; - } - - virtual int onVprintf(const char* format, va_list va) CXX11_OVERRIDE - { - assert(0); - return -1; - } - - virtual int onFlush() CXX11_OVERRIDE - { - return 0; - } - - virtual int onClose() CXX11_OVERRIDE - { - return 0; - } - - virtual bool onSupportsColor() CXX11_OVERRIDE - { - return false; - } - - virtual bool isError() const CXX11_OVERRIDE - { - return false; - } - - virtual bool isEOF() const CXX11_OVERRIDE - { - return false; - } - - virtual bool isOpen() const CXX11_OVERRIDE - { - return true; - } - -private: - std::unique_ptr sha1_; -}; -} // namespace - std::string SessionSerializer::calculateHash() const { SHA1IOFile sha1io; -- cgit From b1132d6b10cd3791b9529d7031d723fd0e2d8215 Mon Sep 17 00:00:00 2001 From: Tatsuhiro Tsujikawa Date: Sun, 27 Dec 2015 18:39:47 +0900 Subject: make clang-format using clang-format-3.6 --- examples/libaria2ex.cc | 53 +- examples/libaria2wx.cc | 178 ++- src/ARC4Encryptor.h | 8 +- src/AbstractAuthResolver.cc | 8 +- src/AbstractAuthResolver.h | 1 + src/AbstractBtMessage.cc | 32 +- src/AbstractBtMessage.h | 83 +- src/AbstractCommand.cc | 216 ++-- src/AbstractCommand.h | 66 +- src/AbstractDiskWriter.cc | 385 +++--- src/AbstractDiskWriter.h | 16 +- src/AbstractHttpServerResponseCommand.cc | 62 +- src/AbstractHttpServerResponseCommand.h | 14 +- src/AbstractOptionHandler.cc | 61 +- src/AbstractOptionHandler.h | 24 +- src/AbstractProxyRequestCommand.cc | 38 +- src/AbstractProxyRequestCommand.h | 8 +- src/AbstractProxyResponseCommand.cc | 29 +- src/AbstractProxyResponseCommand.h | 15 +- src/AbstractSingleDiskAdaptor.cc | 94 +- src/AbstractSingleDiskAdaptor.h | 17 +- src/ActivePeerConnectionCommand.cc | 97 +- src/ActivePeerConnectionCommand.h | 6 +- src/AdaptiveFileAllocationIterator.cc | 47 +- src/AdaptiveFileAllocationIterator.h | 8 +- src/AdaptiveURISelector.cc | 170 +-- src/AdaptiveURISelector.h | 14 +- src/Adler32MessageDigestImpl.cc | 22 +- src/Adler32MessageDigestImpl.h | 8 +- src/AnnounceList.cc | 136 ++- src/AnnounceList.h | 4 +- src/AnnounceTier.cc | 9 +- src/AnonDiskWriterFactory.h | 8 +- src/ApiCallbackDownloadEventListener.cc | 17 +- src/ApiCallbackDownloadEventListener.h | 5 +- src/AppleMessageDigestImpl.cc | 98 +- src/AppleTLSContext.cc | 73 +- src/AppleTLSContext.h | 33 +- src/AppleTLSSession.cc | 395 +++--- src/AppleTLSSession.h | 10 +- src/AsyncNameResolver.cc | 35 +- src/AsyncNameResolver.h | 37 +- src/AsyncNameResolverMan.cc | 87 +- src/AsyncNameResolverMan.h | 19 +- src/AuthConfig.cc | 15 +- src/AuthConfig.h | 15 +- src/AuthConfigFactory.cc | 157 ++- src/AuthConfigFactory.h | 25 +- src/AuthResolver.h | 4 +- src/AutoSaveCommand.cc | 9 +- src/AutoSaveCommand.h | 3 +- src/BackupIPv4ConnectCommand.cc | 86 +- src/BackupIPv4ConnectCommand.h | 9 +- src/BencodeParser.cc | 101 +- src/BencodeParser.h | 1 + src/BitfieldMan.cc | 772 ++++++------ src/BitfieldMan.h | 77 +- src/BtAbortOutstandingRequestEvent.cc | 9 +- src/BtAbortOutstandingRequestEvent.h | 1 + src/BtAllowedFastMessage.cc | 30 +- src/BtAllowedFastMessage.h | 4 +- src/BtAnnounce.h | 4 +- src/BtBitfieldMessage.cc | 50 +- src/BtBitfieldMessage.h | 5 +- src/BtBitfieldMessageValidator.cc | 13 +- src/BtBitfieldMessageValidator.h | 4 +- src/BtCancelMessage.cc | 17 +- src/BtCancelMessage.h | 4 +- src/BtCancelSendingPieceEvent.h | 7 +- src/BtCheckIntegrityEntry.cc | 41 +- src/BtCheckIntegrityEntry.h | 12 +- src/BtChokeMessage.cc | 22 +- src/BtChokeMessage.h | 4 +- src/BtChokingEvent.h | 3 +- src/BtDependency.cc | 85 +- src/BtDependency.h | 4 +- src/BtExtendedMessage.cc | 37 +- src/BtExtendedMessage.h | 14 +- src/BtFileAllocationEntry.cc | 33 +- src/BtFileAllocationEntry.h | 6 +- src/BtHandshakeMessage.cc | 44 +- src/BtHandshakeMessage.h | 47 +- src/BtHandshakeMessageValidator.cc | 32 +- src/BtHandshakeMessageValidator.h | 1 + src/BtHaveAllMessage.cc | 21 +- src/BtHaveAllMessage.h | 4 +- src/BtHaveMessage.cc | 12 +- src/BtHaveMessage.h | 4 +- src/BtHaveNoneMessage.cc | 13 +- src/BtHaveNoneMessage.h | 4 +- src/BtInteractive.h | 5 +- src/BtInterestedMessage.cc | 19 +- src/BtInterestedMessage.h | 5 +- src/BtKeepAliveMessage.cc | 5 +- src/BtKeepAliveMessage.h | 8 +- src/BtLeecherStateChoke.cc | 71 +- src/BtLeecherStateChoke.h | 14 +- src/BtMessage.h | 12 +- src/BtMessageDispatcher.h | 14 +- src/BtMessageFactory.h | 4 +- src/BtMessageReceiver.h | 4 +- src/BtNotInterestedMessage.cc | 19 +- src/BtNotInterestedMessage.h | 5 +- src/BtPieceMessage.cc | 212 ++-- src/BtPieceMessage.h | 11 +- src/BtPieceMessageValidator.cc | 12 +- src/BtPieceMessageValidator.h | 4 +- src/BtPortMessage.cc | 48 +- src/BtPortMessage.h | 5 +- src/BtPostDownloadHandler.cc | 52 +- src/BtPostDownloadHandler.h | 5 +- src/BtRegistry.cc | 68 +- src/BtRegistry.h | 28 +- src/BtRejectMessage.cc | 33 +- src/BtRejectMessage.h | 4 +- src/BtRequestFactory.h | 5 +- src/BtRequestMessage.cc | 52 +- src/BtRequestMessage.h | 13 +- src/BtRuntime.cc | 19 +- src/BtRuntime.h | 17 +- src/BtSeederStateChoke.cc | 84 +- src/BtSeederStateChoke.h | 5 +- src/BtSetup.cc | 134 +-- src/BtSetup.h | 3 +- src/BtStopDownloadCommand.cc | 24 +- src/BtStopDownloadCommand.h | 10 +- src/BtSuggestPieceMessage.cc | 9 +- src/BtSuggestPieceMessage.h | 7 +- src/BtUnchokeMessage.cc | 18 +- src/BtUnchokeMessage.h | 5 +- src/BufferedFile.cc | 56 +- src/BufferedFile.h | 4 +- src/ByteArrayDiskWriter.cc | 39 +- src/ByteArrayDiskWriter.h | 9 +- src/ByteArrayDiskWriterFactory.h | 3 +- src/CUIDCounter.cc | 4 +- src/CUIDCounter.h | 1 + src/CheckIntegrityCommand.cc | 48 +- src/CheckIntegrityCommand.h | 7 +- src/CheckIntegrityDispatcherCommand.cc | 19 +- src/CheckIntegrityDispatcherCommand.h | 15 +- src/CheckIntegrityEntry.cc | 41 +- src/CheckIntegrityEntry.h | 20 +- src/Checksum.cc | 31 +- src/Checksum.h | 11 +- src/ChecksumCheckIntegrityEntry.cc | 39 +- src/ChecksumCheckIntegrityEntry.h | 27 +- src/ChunkChecksum.cc | 35 +- src/ChunkChecksum.h | 25 +- src/ChunkedDecodingStreamFilter.cc | 114 +- src/ChunkedDecodingStreamFilter.h | 12 +- src/ColorizedStream.cc | 5 +- src/ColorizedStream.h | 72 +- src/Command.cc | 42 +- src/Command.h | 20 +- src/ConnectCommand.cc | 37 +- src/ConnectCommand.h | 14 +- src/ConsoleStatCalc.cc | 192 +-- src/ConsoleStatCalc.h | 12 +- src/ContentTypeRequestGroupCriteria.cc | 28 +- src/ContentTypeRequestGroupCriteria.h | 4 +- src/Context.cc | 135 ++- src/ContextAttribute.cc | 2 +- src/ControlChain.h | 3 +- src/Cookie.cc | 96 +- src/Cookie.h | 95 +- src/CookieStorage.cc | 288 ++--- src/CookieStorage.h | 40 +- src/CreateRequestCommand.cc | 65 +- src/CreateRequestCommand.h | 6 +- src/DHKeyExchange.h | 8 +- src/DHTAbstractMessage.cc | 29 +- src/DHTAbstractMessage.h | 23 +- src/DHTAbstractNodeLookupTask.h | 90 +- src/DHTAbstractTask.cc | 18 +- src/DHTAbstractTask.h | 34 +- src/DHTAnnouncePeerMessage.cc | 56 +- src/DHTAnnouncePeerMessage.h | 22 +- src/DHTAnnouncePeerReplyMessage.cc | 12 +- src/DHTAnnouncePeerReplyMessage.h | 2 +- src/DHTAutoSaveCommand.cc | 39 +- src/DHTAutoSaveCommand.h | 8 +- src/DHTBucket.cc | 123 +- src/DHTBucket.h | 44 +- src/DHTBucketRefreshCommand.cc | 19 +- src/DHTBucketRefreshCommand.h | 3 +- src/DHTBucketRefreshTask.cc | 7 +- src/DHTBucketRefreshTask.h | 2 +- src/DHTBucketTree.cc | 125 +- src/DHTBucketTree.h | 19 +- src/DHTConnectionImpl.cc | 22 +- src/DHTConnectionImpl.h | 16 +- src/DHTEntryPointNameResolveCommand.cc | 139 +-- src/DHTEntryPointNameResolveCommand.h | 8 +- src/DHTFindNodeMessage.cc | 19 +- src/DHTFindNodeMessage.h | 9 +- src/DHTFindNodeReplyMessage.cc | 43 +- src/DHTFindNodeReplyMessage.h | 7 +- src/DHTGetPeersCommand.cc | 68 +- src/DHTGetPeersCommand.h | 3 +- src/DHTGetPeersMessage.cc | 29 +- src/DHTGetPeersMessage.h | 10 +- src/DHTGetPeersReplyMessage.cc | 64 +- src/DHTGetPeersReplyMessage.h | 12 +- src/DHTIDCloser.h | 7 +- src/DHTInteractionCommand.cc | 66 +- src/DHTInteractionCommand.h | 7 +- src/DHTMessage.cc | 8 +- src/DHTMessage.h | 26 +- src/DHTMessageCallback.h | 5 +- src/DHTMessageDispatcher.h | 8 +- src/DHTMessageDispatcherImpl.cc | 47 +- src/DHTMessageDispatcherImpl.h | 22 +- src/DHTMessageEntry.cc | 16 +- src/DHTMessageFactory.h | 31 +- src/DHTMessageFactoryImpl.cc | 353 +++--- src/DHTMessageFactoryImpl.h | 100 +- src/DHTMessageReceiver.cc | 63 +- src/DHTMessageReceiver.h | 8 +- src/DHTMessageTracker.cc | 112 +- src/DHTMessageTracker.h | 9 +- src/DHTMessageTrackerEntry.cc | 45 +- src/DHTMessageTrackerEntry.h | 9 +- src/DHTNode.cc | 71 +- src/DHTNode.h | 26 +- src/DHTNodeLookupEntry.cc | 9 +- src/DHTNodeLookupTask.cc | 14 +- src/DHTNodeLookupTask.h | 14 +- src/DHTNodeLookupTaskCallback.cc | 15 +- src/DHTNodeLookupTaskCallback.h | 10 +- src/DHTPeerAnnounceCommand.cc | 22 +- src/DHTPeerAnnounceCommand.h | 3 +- src/DHTPeerAnnounceEntry.cc | 25 +- src/DHTPeerAnnounceEntry.h | 14 +- src/DHTPeerAnnounceStorage.cc | 46 +- src/DHTPeerAnnounceStorage.h | 15 +- src/DHTPeerLookupTask.cc | 50 +- src/DHTPeerLookupTask.h | 27 +- src/DHTPeerLookupTaskCallback.cc | 14 +- src/DHTPeerLookupTaskCallback.h | 19 +- src/DHTPingMessage.cc | 17 +- src/DHTPingMessage.h | 2 +- src/DHTPingReplyMessage.cc | 16 +- src/DHTPingReplyMessage.h | 8 +- src/DHTPingReplyMessageCallback.h | 11 +- src/DHTPingTask.cc | 39 +- src/DHTPingTask.h | 3 +- src/DHTQueryMessage.cc | 19 +- src/DHTQueryMessage.h | 3 +- src/DHTRegistry.cc | 11 +- src/DHTRegistry.h | 43 +- src/DHTReplaceNodeTask.cc | 42 +- src/DHTReplaceNodeTask.h | 3 +- src/DHTResponseMessage.cc | 24 +- src/DHTResponseMessage.h | 3 +- src/DHTRoutingTable.cc | 76 +- src/DHTRoutingTable.h | 12 +- src/DHTRoutingTableDeserializer.cc | 63 +- src/DHTRoutingTableDeserializer.h | 15 +- src/DHTRoutingTableSerializer.cc | 53 +- src/DHTRoutingTableSerializer.h | 5 +- src/DHTSetup.cc | 116 +- src/DHTTask.h | 2 +- src/DHTTaskExecutor.cc | 16 +- src/DHTTaskExecutor.h | 25 +- src/DHTTaskFactoryImpl.cc | 33 +- src/DHTTaskFactoryImpl.h | 14 +- src/DHTTaskQueueImpl.cc | 9 +- src/DHTTaskQueueImpl.h | 15 +- src/DHTTokenTracker.cc | 35 +- src/DHTTokenTracker.h | 4 +- src/DHTTokenUpdateCommand.cc | 17 +- src/DHTTokenUpdateCommand.h | 3 +- src/DHTUnknownMessage.cc | 35 +- src/DHTUnknownMessage.h | 3 +- src/DNSCache.cc | 83 +- src/DNSCache.h | 25 +- src/DefaultAuthResolver.cc | 9 +- src/DefaultAuthResolver.h | 4 +- src/DefaultBtAnnounce.cc | 265 +++-- src/DefaultBtAnnounce.h | 46 +- src/DefaultBtInteractive.cc | 502 ++++---- src/DefaultBtInteractive.h | 76 +- src/DefaultBtMessageDispatcher.cc | 175 ++- src/DefaultBtMessageDispatcher.h | 36 +- src/DefaultBtMessageFactory.cc | 170 ++- src/DefaultBtMessageFactory.h | 77 +- src/DefaultBtMessageReceiver.cc | 71 +- src/DefaultBtMessageReceiver.h | 9 +- src/DefaultBtProgressInfoFile.cc | 178 +-- src/DefaultBtRequestFactory.cc | 151 +-- src/DefaultBtRequestFactory.h | 34 +- src/DefaultDiskWriter.cc | 11 +- src/DefaultDiskWriter.h | 2 +- src/DefaultDiskWriterFactory.cc | 4 +- src/DefaultDiskWriterFactory.h | 7 +- src/DefaultExtensionMessageFactory.cc | 128 +- src/DefaultExtensionMessageFactory.h | 7 +- src/DefaultPeerStorage.cc | 130 +- src/DefaultPeerStorage.h | 9 +- src/DefaultPieceStorage.cc | 464 ++++---- src/DefaultPieceStorage.h | 172 ++- src/DefaultStreamPieceSelector.cc | 20 +- src/DefaultStreamPieceSelector.h | 11 +- src/DelayedCommand.h | 12 +- src/DirectDiskAdaptor.cc | 6 +- src/DiskAdaptor.cc | 4 +- src/DiskAdaptor.h | 15 +- src/DiskWriter.h | 4 +- src/DiskWriterFactory.h | 4 +- src/DlAbortEx.cc | 36 +- src/DlAbortEx.h | 5 +- src/DlRetryEx.cc | 18 +- src/DlRetryEx.h | 3 +- src/DownloadCommand.cc | 252 ++-- src/DownloadCommand.h | 6 +- src/DownloadContext.cc | 151 +-- src/DownloadContext.h | 59 +- src/DownloadEngine.cc | 303 +++-- src/DownloadEngine.h | 117 +- src/DownloadEngineFactory.cc | 101 +- src/DownloadEngineFactory.h | 4 +- src/DownloadFailureException.cc | 42 +- src/DownloadFailureException.h | 18 +- src/DownloadHandler.cc | 4 +- src/DownloadHandler.h | 4 +- src/DownloadHandlerConstants.cc | 45 +- src/DownloadResult.cc | 23 +- src/DownloadResult.h | 5 +- src/EpollEventPoll.cc | 120 +- src/EpollEventPoll.h | 28 +- src/Event.h | 166 ++- src/EventPoll.h | 11 +- src/EvictSocketPoolCommand.cc | 10 +- src/Exception.cc | 139 +-- src/Exception.h | 16 +- src/ExpatXmlParser.cc | 63 +- src/ExpatXmlParser.h | 1 + src/ExtensionMessageRegistry.cc | 26 +- src/ExtensionMessageRegistry.h | 6 +- src/FallocFileAllocationIterator.cc | 26 +- src/FallocFileAllocationIterator.h | 4 +- src/FatalException.cc | 17 +- src/FatalException.h | 8 +- src/FeatureConfig.cc | 135 +-- src/FeedbackURISelector.cc | 86 +- src/FeedbackURISelector.h | 23 +- src/File.cc | 152 +-- src/File.h | 6 +- src/FileAllocationCommand.cc | 31 +- src/FileAllocationCommand.h | 1 + src/FileAllocationDispatcherCommand.cc | 19 +- src/FileAllocationDispatcherCommand.h | 15 +- src/FileAllocationEntry.cc | 13 +- src/FileAllocationEntry.h | 16 +- src/FileAllocationIterator.h | 3 +- src/FileEntry.cc | 320 +++-- src/FileEntry.h | 139 +-- src/FillRequestGroupCommand.cc | 17 +- src/FillRequestGroupCommand.h | 1 + src/FtpConnection.cc | 335 +++--- src/FtpConnection.h | 12 +- src/FtpDownloadCommand.cc | 41 +- src/FtpDownloadCommand.h | 5 +- src/FtpFinishDownloadCommand.cc | 59 +- src/FtpFinishDownloadCommand.h | 5 +- src/FtpInitiateConnectionCommand.cc | 178 ++- src/FtpInitiateConnectionCommand.h | 26 +- src/FtpNegotiationCommand.cc | 521 ++++---- src/FtpNegotiationCommand.h | 9 +- src/FtpNegotiationConnectChain.h | 10 +- src/FtpTunnelRequestCommand.cc | 27 +- src/FtpTunnelRequestCommand.h | 6 +- src/FtpTunnelRequestConnectChain.h | 11 +- src/FtpTunnelResponseCommand.cc | 36 +- src/FtpTunnelResponseCommand.h | 13 +- src/GZipDecodingStreamFilter.cc | 53 +- src/GZipDecodingStreamFilter.h | 8 +- src/GZipEncoder.cc | 30 +- src/GZipEncoder.h | 1 + src/GZipFile.cc | 62 +- src/GZipFile.h | 4 +- src/GenericParser.h | 34 +- src/GeomStreamPieceSelector.cc | 26 +- src/GeomStreamPieceSelector.h | 11 +- src/GroupId.cc | 60 +- src/GroupId.h | 12 +- src/GrowSegment.cc | 16 +- src/GrowSegment.h | 40 +- src/HandshakeExtensionMessage.cc | 86 +- src/HandshakeExtensionMessage.h | 38 +- src/HashFuncEntry.h | 36 +- src/HaveEraseCommand.cc | 12 +- src/HaveEraseCommand.h | 3 +- src/HttpConnection.cc | 88 +- src/HttpConnection.h | 6 +- src/HttpDownloadCommand.cc | 59 +- src/HttpDownloadCommand.h | 6 +- src/HttpHeader.cc | 176 +-- src/HttpHeader.h | 7 +- src/HttpHeaderProcessor.cc | 36 +- src/HttpHeaderProcessor.h | 8 +- src/HttpInitiateConnectionCommand.cc | 115 +- src/HttpInitiateConnectionCommand.h | 17 +- src/HttpListenCommand.cc | 35 +- src/HttpListenCommand.h | 1 + src/HttpProxyRequestCommand.cc | 27 +- src/HttpProxyRequestCommand.h | 6 +- src/HttpProxyRequestConnectChain.h | 11 +- src/HttpProxyResponseCommand.cc | 27 +- src/HttpProxyResponseCommand.h | 12 +- src/HttpRequest.cc | 222 ++-- src/HttpRequest.h | 51 +- src/HttpRequestCommand.cc | 144 ++- src/HttpRequestCommand.h | 10 +- src/HttpRequestConnectChain.h | 18 +- src/HttpResponse.cc | 105 +- src/HttpResponse.h | 8 +- src/HttpResponseCommand.cc | 169 ++- src/HttpResponseCommand.h | 6 +- src/HttpServer.cc | 332 +++--- src/HttpServer.h | 56 +- src/HttpServerBodyCommand.cc | 184 ++- src/HttpServerBodyCommand.h | 11 +- src/HttpServerCommand.cc | 165 +-- src/HttpServerCommand.h | 7 +- src/HttpServerResponseCommand.cc | 31 +- src/HttpServerResponseCommand.h | 1 + src/HttpSkipResponseCommand.cc | 100 +- src/IOFile.cc | 53 +- src/IOFile.h | 4 +- src/IndexBtMessage.cc | 5 +- src/IndexBtMessage.h | 12 +- src/IndexBtMessageValidator.cc | 10 +- src/IndexBtMessageValidator.h | 1 + src/IndexedList.h | 329 +++-- src/InitiateConnectionCommand.cc | 81 +- src/InitiateConnectionCommand.h | 33 +- src/InitiateConnectionCommandFactory.cc | 45 +- src/InitiateConnectionCommandFactory.h | 10 +- src/InitiatorMSEHandshakeCommand.cc | 144 +-- src/InitiatorMSEHandshakeCommand.h | 15 +- src/InorderStreamPieceSelector.cc | 20 +- src/InorderStreamPieceSelector.h | 11 +- src/InorderURISelector.cc | 11 +- src/InorderURISelector.h | 10 +- src/InternalARC4Encryptor.cc | 3 +- src/InternalDHKeyExchange.cc | 24 +- src/InternalMessageDigestImpl.cc | 32 +- src/IteratableChecksumValidator.cc | 32 +- src/IteratableChecksumValidator.h | 9 +- src/IteratableChunkChecksumValidator.cc | 75 +- src/IteratableChunkChecksumValidator.h | 8 +- src/IteratableValidator.h | 3 +- src/JsonParser.cc | 219 ++-- src/JsonParser.h | 1 + src/KeepRunningCommand.cc | 5 +- src/KeepRunningCommand.h | 1 + src/KqueueEventPoll.cc | 127 +- src/KqueueEventPoll.h | 26 +- src/LibgcryptARC4Encryptor.cc | 34 +- src/LibgcryptARC4Encryptor.h | 1 + src/LibgcryptDHKeyExchange.cc | 85 +- src/LibgcryptDHKeyExchange.h | 4 +- src/LibgcryptMessageDigestImpl.cc | 30 +- src/LibgmpDHKeyExchange.cc | 64 +- src/LibgmpDHKeyExchange.h | 14 +- src/LibgnutlsTLSContext.cc | 76 +- src/LibgnutlsTLSContext.h | 18 +- src/LibgnutlsTLSSession.cc | 185 +-- src/LibgnutlsTLSSession.h | 6 +- src/LibnettleARC4Encryptor.cc | 6 +- src/LibnettleARC4Encryptor.h | 1 + src/LibnettleMessageDigestImpl.cc | 37 +- src/LibsslARC4Encryptor.cc | 6 +- src/LibsslARC4Encryptor.h | 1 + src/LibsslDHKeyExchange.cc | 97 +- src/LibsslDHKeyExchange.h | 4 +- src/LibsslMessageDigestImpl.cc | 55 +- src/LibsslTLSContext.cc | 144 +-- src/LibsslTLSContext.h | 19 +- src/LibsslTLSSession.cc | 152 +-- src/LibsslTLSSession.h | 6 +- src/LibuvEventPoll.cc | 125 +- src/LibuvEventPoll.h | 51 +- src/Lock.h | 26 +- src/LogFactory.cc | 48 +- src/LogFactory.h | 32 +- src/Logger.cc | 111 +- src/Logger.h | 63 +- src/LongestSequencePieceSelector.cc | 33 +- src/LongestSequencePieceSelector.h | 7 +- src/LpdDispatchMessageCommand.cc | 36 +- src/LpdDispatchMessageCommand.h | 10 +- src/LpdMessage.cc | 9 +- src/LpdMessageDispatcher.cc | 66 +- src/LpdMessageDispatcher.h | 27 +- src/LpdMessageReceiver.cc | 46 +- src/LpdMessageReceiver.h | 15 +- src/LpdReceiveMessageCommand.cc | 30 +- src/LpdReceiveMessageCommand.h | 9 +- src/MSEHandshake.cc | 287 +++-- src/MSEHandshake.h | 55 +- src/MemoryBencodePreDownloadHandler.h | 2 +- src/MemoryBufferPreDownloadHandler.h | 2 +- src/MemoryPreDownloadHandler.h | 5 +- src/MessageDigest.cc | 76 +- src/MessageDigest.h | 5 +- src/MessageDigestImpl.h | 15 +- src/MetadataInfo.cc | 5 +- src/MetadataInfo.h | 11 +- src/Metalink2RequestGroup.cc | 206 ++-- src/Metalink2RequestGroup.h | 8 +- src/MetalinkEntry.cc | 80 +- src/MetalinkEntry.h | 19 +- src/MetalinkHttpEntry.cc | 17 +- src/MetalinkMetaurl.cc | 16 +- src/MetalinkParserController.cc | 227 ++-- src/MetalinkParserController.h | 11 +- src/MetalinkParserState.h | 29 +- src/MetalinkParserStateImpl.cc | 49 +- src/MetalinkParserStateImpl.h | 19 +- src/MetalinkParserStateMachine.cc | 90 +- src/MetalinkParserStateMachine.h | 28 +- src/MetalinkParserStateV3Impl.cc | 372 +++--- src/MetalinkParserStateV3Impl.h | 157 +-- src/MetalinkParserStateV4Impl.cc | 237 ++-- src/MetalinkParserStateV4Impl.h | 135 +-- src/MetalinkPostDownloadHandler.cc | 44 +- src/MetalinkPostDownloadHandler.h | 3 +- src/MetalinkResource.cc | 10 +- src/MetalinkResource.h | 6 +- src/Metalinker.cc | 23 +- src/Metalinker.h | 4 +- src/MultiDiskAdaptor.cc | 309 +++-- src/MultiDiskAdaptor.h | 52 +- src/MultiFileAllocationIterator.cc | 62 +- src/MultiFileAllocationIterator.h | 4 +- src/MultiUrlRequestInfo.cc | 209 ++-- src/MultiUrlRequestInfo.h | 10 +- src/NameResolveCommand.cc | 84 +- src/NameResolveCommand.h | 6 +- src/NameResolver.cc | 28 +- src/NameResolver.h | 6 +- src/NetStat.cc | 23 +- src/NetStat.h | 31 +- src/Netrc.cc | 133 ++- src/Netrc.h | 29 +- src/NetrcAuthResolver.cc | 40 +- src/NetrcAuthResolver.h | 9 +- src/Notifier.cc | 6 +- src/Notifier.h | 1 + src/NsCookieParser.cc | 52 +- src/NsCookieParser.h | 4 +- src/NullHandle.h | 3 +- src/NullOutputFile.h | 6 +- src/NullProgressInfoFile.h | 7 +- src/NullSinkStreamFilter.h | 27 +- src/NullStatCalc.h | 2 +- src/NullWebSocketSessionMan.h | 3 +- src/OpenedFileCounter.cc | 51 +- src/OpenedFileCounter.h | 5 +- src/Option.cc | 88 +- src/Option.h | 6 +- src/OptionHandler.cc | 12 +- src/OptionHandler.h | 6 +- src/OptionHandlerException.cc | 33 +- src/OptionHandlerException.h | 19 +- src/OptionHandlerFactory.cc | 1583 +++++++++---------------- src/OptionHandlerImpl.cc | 520 ++++---- src/OptionHandlerImpl.h | 170 ++- src/OptionParser.cc | 167 +-- src/OptionParser.h | 8 +- src/OutputFile.h | 3 +- src/ParserStateMachine.h | 15 +- src/Peer.cc | 64 +- src/Peer.h | 87 +- src/PeerAbstractCommand.cc | 113 +- src/PeerAbstractCommand.h | 29 +- src/PeerAddrEntry.cc | 23 +- src/PeerAddrEntry.h | 20 +- src/PeerChokeCommand.cc | 22 +- src/PeerChokeCommand.h | 4 +- src/PeerConnection.cc | 140 +-- src/PeerConnection.h | 27 +- src/PeerInitiateConnectionCommand.cc | 70 +- src/PeerInitiateConnectionCommand.h | 4 +- src/PeerInteractionCommand.cc | 197 +-- src/PeerInteractionCommand.h | 25 +- src/PeerListenCommand.cc | 63 +- src/PeerListenCommand.h | 1 + src/PeerReceiveHandshakeCommand.cc | 96 +- src/PeerReceiveHandshakeCommand.h | 15 +- src/PeerSessionResource.cc | 90 +- src/PeerSessionResource.h | 66 +- src/PeerStat.cc | 55 +- src/PeerStat.h | 20 +- src/PeerStorage.h | 6 +- src/Piece.cc | 158 ++- src/Piece.h | 44 +- src/PieceHashCheckIntegrityEntry.cc | 18 +- src/PieceHashCheckIntegrityEntry.h | 9 +- src/PieceSelector.h | 4 +- src/PieceStatMan.cc | 35 +- src/PieceStatMan.h | 17 +- src/PieceStorage.h | 82 +- src/PiecedSegment.cc | 55 +- src/PiecedSegment.h | 9 +- src/Platform.cc | 65 +- src/PollEventPoll.cc | 142 +-- src/PollEventPoll.h | 29 +- src/PortEventPoll.cc | 139 +-- src/PortEventPoll.h | 34 +- src/PostDownloadHandler.h | 3 +- src/PreDownloadHandler.h | 3 +- src/PriorityPieceSelector.cc | 16 +- src/PriorityPieceSelector.h | 10 +- src/ProtocolDetector.cc | 27 +- src/Range.cc | 33 +- src/RangeBtMessage.cc | 23 +- src/RangeBtMessage.h | 11 +- src/RangeBtMessageValidator.cc | 15 +- src/RangeBtMessageValidator.h | 4 +- src/RarestPieceSelector.cc | 20 +- src/RarestPieceSelector.h | 9 +- src/RealtimeCommand.cc | 16 +- src/RealtimeCommand.h | 12 +- src/ReceiverMSEHandshakeCommand.cc | 123 +- src/ReceiverMSEHandshakeCommand.h | 9 +- src/RecoverableException.cc | 67 +- src/RecoverableException.h | 15 +- src/Request.cc | 94 +- src/Request.h | 87 +- src/RequestGroup.cc | 625 +++++----- src/RequestGroup.h | 183 +-- src/RequestGroupCriteria.h | 3 +- src/RequestGroupEntry.cc | 10 +- src/RequestGroupEntry.h | 12 +- src/RequestGroupMan.cc | 578 ++++----- src/RequestGroupMan.h | 148 +-- src/RequestSlot.h | 39 +- src/RpcMethod.cc | 71 +- src/RpcMethod.h | 14 +- src/RpcMethodImpl.cc | 992 ++++++++-------- src/RpcMethodImpl.h | 544 ++++----- src/RpcRequest.cc | 29 +- src/RpcRequest.h | 9 +- src/RpcResponse.cc | 126 +- src/RpcResponse.h | 34 +- src/SHA1IOFile.cc | 39 +- src/SSHSession.cc | 28 +- src/SSHSession.h | 6 +- src/SaveSessionCommand.cc | 34 +- src/SaveSessionCommand.h | 3 +- src/SeedCheckCommand.cc | 43 +- src/SeedCheckCommand.h | 8 +- src/SegList.h | 37 +- src/Segment.h | 7 +- src/SegmentMan.cc | 289 ++--- src/SegmentMan.h | 31 +- src/SelectEventPoll.cc | 128 +- src/SelectEventPoll.h | 76 +- src/SequentialDispatcherCommand.h | 22 +- src/SequentialPicker.h | 31 +- src/ServerStat.cc | 126 +- src/ServerStat.h | 63 +- src/ServerStatMan.cc | 113 +- src/ServerStatMan.h | 2 +- src/SessionSerializer.cc | 203 ++-- src/SessionSerializer.h | 1 + src/SftpDownloadCommand.cc | 36 +- src/SftpDownloadCommand.h | 6 +- src/SftpFinishDownloadCommand.cc | 40 +- src/SftpFinishDownloadCommand.h | 7 +- src/SftpNegotiationCommand.cc | 145 ++- src/SftpNegotiationCommand.h | 7 +- src/SftpNegotiationConnectChain.h | 10 +- src/ShareRatioSeedCriteria.cc | 28 +- src/ShareRatioSeedCriteria.h | 13 +- src/Signature.cc | 15 +- src/Signature.h | 16 +- src/SimpleBtMessage.cc | 20 +- src/SimpleBtMessage.h | 1 - src/SimpleRandomizer.cc | 25 +- src/SimpleRandomizer.h | 14 +- src/SingleFileAllocationIterator.cc | 28 +- src/SingleFileAllocationIterator.h | 20 +- src/SingletonHolder.h | 22 +- src/SinkStreamFilter.cc | 41 +- src/SinkStreamFilter.h | 25 +- src/SocketBuffer.cc | 96 +- src/SocketBuffer.h | 33 +- src/SocketCore.cc | 842 ++++++------- src/SocketCore.h | 71 +- src/SocketRecvBuffer.cc | 13 +- src/SocketRecvBuffer.h | 24 +- src/SpeedCalc.cc | 32 +- src/SpeedCalc.h | 5 +- src/Sqlite3CookieParser.cc | 84 +- src/Sqlite3CookieParser.h | 2 + src/Sqlite3CookieParserImpl.cc | 24 +- src/Sqlite3CookieParserImpl.h | 6 +- src/StreamCheckIntegrityEntry.cc | 27 +- src/StreamCheckIntegrityEntry.h | 21 +- src/StreamFileAllocationEntry.cc | 37 +- src/StreamFileAllocationEntry.h | 12 +- src/StreamFilter.cc | 10 +- src/StreamFilter.h | 6 +- src/StreamPieceSelector.h | 7 +- src/TLSContext.h | 5 +- src/TLSSession.h | 7 +- src/TimeA2.cc | 30 +- src/TimeA2.h | 6 +- src/TimeBasedCommand.cc | 28 +- src/TimeBasedCommand.h | 27 +- src/TimeSeedCriteria.cc | 7 +- src/TimeSeedCriteria.h | 6 +- src/TimedHaltCommand.cc | 29 +- src/TimedHaltCommand.h | 3 +- src/TimerA2.cc | 14 +- src/TimerA2.h | 15 +- src/TorrentAttribute.cc | 11 +- src/TorrentAttribute.h | 7 +- src/TrackerWatcherCommand.cc | 204 ++-- src/TrackerWatcherCommand.h | 33 +- src/TransferStat.cc | 7 +- src/TransferStat.h | 11 +- src/TruncFileAllocationIterator.cc | 27 +- src/TruncFileAllocationIterator.h | 3 +- src/UDPTrackerClient.cc | 311 +++-- src/UDPTrackerClient.h | 83 +- src/UDPTrackerRequest.cc | 31 +- src/UDPTrackerRequest.h | 7 +- src/URIResult.cc | 5 +- src/URIResult.h | 12 +- src/URISelector.h | 8 +- src/UTMetadataDataExtensionMessage.cc | 52 +- src/UTMetadataDataExtensionMessage.h | 5 +- src/UTMetadataExtensionMessage.cc | 9 +- src/UTMetadataExtensionMessage.h | 13 +- src/UTMetadataPostDownloadHandler.cc | 42 +- src/UTMetadataPostDownloadHandler.h | 5 +- src/UTMetadataRejectExtensionMessage.cc | 9 +- src/UTMetadataRejectExtensionMessage.h | 2 +- src/UTMetadataRequestExtensionMessage.cc | 66 +- src/UTMetadataRequestExtensionMessage.h | 3 +- src/UTMetadataRequestFactory.cc | 25 +- src/UTMetadataRequestFactory.h | 25 +- src/UTMetadataRequestTracker.cc | 28 +- src/UTMetadataRequestTracker.h | 14 +- src/UTPexExtensionMessage.cc | 92 +- src/UTPexExtensionMessage.h | 16 +- src/UnionSeedCriteria.cc | 6 +- src/UnionSeedCriteria.h | 1 + src/UnknownLengthPieceStorage.cc | 152 ++- src/UnknownLengthPieceStorage.h | 160 ++- src/UnknownOptionException.cc | 29 +- src/UnknownOptionException.h | 13 +- src/UriListParser.cc | 42 +- src/UriListParser.h | 1 + src/ValueBase.cc | 216 +--- src/ValueBase.h | 57 +- src/ValueBaseBencodeParser.h | 2 +- src/ValueBaseDiskWriter.h | 39 +- src/ValueBaseJsonParser.h | 2 +- src/ValueBaseStructParserStateImpl.cc | 44 +- src/ValueBaseStructParserStateImpl.h | 32 +- src/ValueBaseStructParserStateMachine.cc | 57 +- src/ValueBaseStructParserStateMachine.h | 7 +- src/WatchProcessCommand.cc | 40 +- src/WatchProcessCommand.h | 10 +- src/WebSocketInteractionCommand.cc | 45 +- src/WebSocketInteractionCommand.h | 13 +- src/WebSocketResponseCommand.cc | 29 +- src/WebSocketResponseCommand.h | 1 + src/WebSocketSession.cc | 154 ++- src/WebSocketSession.h | 41 +- src/WebSocketSessionMan.cc | 17 +- src/WebSocketSessionMan.h | 9 +- src/WinConsoleFile.cc | 89 +- src/WinConsoleFile.h | 53 +- src/WinTLSContext.cc | 46 +- src/WinTLSContext.h | 21 +- src/WinTLSSession.cc | 176 +-- src/WinTLSSession.h | 34 +- src/WrDiskCache.cc | 27 +- src/WrDiskCache.h | 10 +- src/WrDiskCacheEntry.cc | 47 +- src/WrDiskCacheEntry.h | 60 +- src/XORCloser.h | 20 +- src/Xml2XmlParser.cc | 158 ++- src/Xml2XmlParser.h | 1 + src/XmlAttr.cc | 13 +- src/XmlParser.cc | 22 +- src/XmlParser.h | 18 +- src/XmlRpcDiskWriter.cc | 27 +- src/XmlRpcDiskWriter.h | 14 +- src/XmlRpcRequestParserController.cc | 16 +- src/XmlRpcRequestParserController.h | 7 +- src/XmlRpcRequestParserState.h | 5 +- src/XmlRpcRequestParserStateImpl.cc | 252 ++-- src/XmlRpcRequestParserStateImpl.h | 85 +- src/XmlRpcRequestParserStateMachine.cc | 34 +- src/XmlRpcRequestParserStateMachine.h | 19 +- src/ZeroBtMessage.cc | 15 +- src/ZeroBtMessage.h | 6 +- src/a2algo.h | 34 +- src/a2functional.h | 82 +- src/a2gmp.cc | 5 +- src/a2io.h | 172 +-- src/a2iterator.h | 7 +- src/a2netcompat.h | 64 +- src/a2time.h | 14 +- src/alloca.c | 511 ++++---- src/aria2api.cc | 502 ++++---- src/array_fun.h | 81 +- src/asctime_r.c | 31 +- src/asctime_r.h | 2 +- src/base32.cc | 36 +- src/base32.h | 38 +- src/base64.h | 126 +- src/bencode2.cc | 23 +- src/bignum.h | 506 ++++---- src/bitfield.cc | 4 +- src/bitfield.h | 107 +- src/bittorrent_helper.cc | 629 +++++----- src/bittorrent_helper.h | 127 +- src/common.h | 48 +- src/console.cc | 21 +- src/cookie_helper.cc | 265 +++-- src/cookie_helper.h | 24 +- src/crypto_endian.h | 22 +- src/crypto_hash.cc | 589 ++++----- src/crypto_hash.h | 12 +- src/daemon.cc | 24 +- src/download_handlers.cc | 36 +- src/download_helper.cc | 338 +++--- src/download_helper.h | 75 +- src/fmt.cc | 6 +- src/fmt.h | 8 +- src/gai_strerror.c | 15 +- src/gai_strerror.h | 10 +- src/getaddrinfo.c | 648 +++++----- src/getaddrinfo.h | 164 +-- src/getrandom_linux.c | 5 +- src/getrandom_linux.h | 2 +- src/gettimeofday.c | 25 +- src/gettimeofday.h | 9 +- src/help_tags.cc | 28 +- src/includes/aria2/aria2.h | 31 +- src/json.cc | 84 +- src/json.h | 19 +- src/libgen.c | 64 +- src/libgen.h | 9 +- src/localtime_r.c | 33 +- src/localtime_r.h | 2 +- src/magnet.cc | 14 +- src/magnet.h | 1 - src/main.cc | 16 +- src/message_digest_helper.cc | 30 +- src/message_digest_helper.h | 12 +- src/metalink_helper.cc | 75 +- src/metalink_helper.h | 30 +- src/option_processing.cc | 164 +-- src/paramed_string.cc | 10 +- src/paramed_string.h | 132 ++- src/prefs.cc | 63 +- src/rpc_helper.cc | 28 +- src/rpc_helper.h | 3 +- src/strptime.c | 719 ++++++----- src/strptime.h | 2 +- src/timegm.c | 22 +- src/timegm.h | 4 +- src/timespec.h | 5 +- src/uri.cc | 156 ++- src/uri_split.c | 144 +-- src/uri_split.h | 6 +- src/util.cc | 1217 ++++++++++--------- src/util.h | 431 ++++--- src/util_security.cc | 13 +- src/util_security.h | 60 +- src/version_usage.cc | 153 +-- test/ARC4Test.cc | 4 +- test/AbstractCommandTest.cc | 4 +- test/AllTest.cc | 10 +- test/AnnounceListTest.cc | 73 +- test/Aria2ApiTest.cc | 68 +- test/AsyncNameResolverTest.cc | 6 +- test/AuthConfigFactoryTest.cc | 73 +- test/Base32Test.cc | 6 +- test/Base64Test.cc | 171 +-- test/Bencode2Test.cc | 6 +- test/BitfieldManTest.cc | 194 ++- test/BittorrentHelperTest.cc | 440 +++---- test/BtAllowedFastMessageTest.cc | 39 +- test/BtBitfieldMessageTest.cc | 53 +- test/BtCancelMessageTest.cc | 36 +- test/BtChokeMessageTest.cc | 41 +- test/BtDependencyTest.cc | 96 +- test/BtExtendedMessageTest.cc | 45 +- test/BtHandshakeMessageTest.cc | 85 +- test/BtHaveAllMessageTest.cc | 32 +- test/BtHaveMessageTest.cc | 31 +- test/BtHaveNoneMessageTest.cc | 32 +- test/BtInterestedMessageTest.cc | 31 +- test/BtKeepAliveMessageTest.cc | 15 +- test/BtNotInterestedMessageTest.cc | 31 +- test/BtPieceMessageTest.cc | 63 +- test/BtPortMessageTest.cc | 52 +- test/BtPostDownloadHandlerTest.cc | 30 +- test/BtRegistryTest.cc | 17 +- test/BtRejectMessageTest.cc | 67 +- test/BtRequestMessageTest.cc | 103 +- test/BtSuggestPieceMessageTest.cc | 25 +- test/BtUnchokeMessageTest.cc | 30 +- test/BufferedFileTest.cc | 8 +- test/ByteArrayDiskWriterTest.cc | 16 +- test/ChunkedDecodingStreamFilterTest.cc | 120 +- test/CookieBoxTest.cc | 16 +- test/CookieHelperTest.cc | 24 +- test/CookieStorageTest.cc | 141 ++- test/CookieTest.cc | 36 +- test/DHKeyExchangeTest.cc | 9 +- test/DHTAnnouncePeerMessageTest.cc | 14 +- test/DHTAnnouncePeerReplyMessageTest.cc | 4 +- test/DHTBucketTest.cc | 199 ++-- test/DHTBucketTreeTest.cc | 11 +- test/DHTConnectionImplTest.cc | 13 +- test/DHTFindNodeMessageTest.cc | 23 +- test/DHTFindNodeReplyMessageTest.cc | 42 +- test/DHTGetPeersMessageTest.cc | 43 +- test/DHTGetPeersReplyMessageTest.cc | 84 +- test/DHTIDCloserTest.cc | 4 +- test/DHTMessageFactoryImplTest.cc | 134 +-- test/DHTMessageTrackerEntryTest.cc | 14 +- test/DHTMessageTrackerTest.cc | 12 +- test/DHTNodeTest.cc | 4 +- test/DHTPeerAnnounceEntryTest.cc | 17 +- test/DHTPeerAnnounceStorageTest.cc | 6 +- test/DHTPingMessageTest.cc | 14 +- test/DHTPingReplyMessageTest.cc | 4 +- test/DHTRoutingTableDeserializerTest.cc | 42 +- test/DHTRoutingTableSerializerTest.cc | 55 +- test/DHTRoutingTableTest.cc | 25 +- test/DHTTaskExecutorTest.cc | 14 +- test/DHTTokenTrackerTest.cc | 4 +- test/DHTUnknownMessageTest.cc | 19 +- test/DNSCacheTest.cc | 4 +- test/DefaultAuthResolverTest.cc | 5 +- test/DefaultBtAnnounceTest.cc | 296 +++-- test/DefaultBtMessageDispatcherTest.cc | 108 +- test/DefaultBtMessageFactoryTest.cc | 24 +- test/DefaultBtProgressInfoFileTest.cc | 152 +-- test/DefaultBtRequestFactoryTest.cc | 22 +- test/DefaultDiskWriterTest.cc | 12 +- test/DefaultExtensionMessageFactoryTest.cc | 66 +- test/DefaultPeerStorageTest.cc | 39 +- test/DefaultPieceStorageTest.cc | 70 +- test/DirectDiskAdaptorTest.cc | 15 +- test/DownloadContextTest.cc | 27 +- test/DownloadHandlersTest.cc | 23 +- test/DownloadHelperTest.cc | 158 ++- test/ExceptionTest.cc | 26 +- test/ExtensionMessageRegistryTest.cc | 43 +- test/FallocFileAllocationIteratorTest.cc | 14 +- test/FeatureConfigTest.cc | 37 +- test/FeedbackURISelectorTest.cc | 19 +- test/FileEntryTest.cc | 23 +- test/FileTest.cc | 65 +- test/FixedNumberRandomizer.h | 11 +- test/FmtTest.cc | 4 +- test/FtpConnectionTest.cc | 29 +- test/GZipDecoder.cc | 37 +- test/GZipDecoder.h | 2 +- test/GZipDecoderTest.cc | 14 +- test/GZipDecodingStreamFilterTest.cc | 13 +- test/GZipEncoderTest.cc | 8 +- test/GZipFileTest.cc | 8 +- test/GeomStreamPieceSelectorTest.cc | 3 +- test/GroupIdTest.cc | 26 +- test/GrowSegmentTest.cc | 5 +- test/HandshakeExtensionMessageTest.cc | 85 +- test/HttpHeaderProcessorTest.cc | 177 ++- test/HttpHeaderTest.cc | 20 +- test/HttpRequestTest.cc | 561 ++++----- test/HttpResponseTest.cc | 139 ++- test/HttpServerTest.cc | 109 +- test/IndexedListTest.cc | 169 ++- test/InorderPieceSelector.h | 11 +- test/InorderURISelectorTest.cc | 13 +- test/IteratableChecksumValidatorTest.cc | 40 +- test/IteratableChunkChecksumValidatorTest.cc | 42 +- test/JsonTest.cc | 6 +- test/LongestSequencePieceSelectorTest.cc | 8 +- test/LpdMessageDispatcherTest.cc | 31 +- test/LpdMessageReceiverTest.cc | 34 +- test/MSEHandshakeTest.cc | 79 +- test/MagnetTest.cc | 16 +- test/MessageDigestHelperTest.cc | 27 +- test/MessageDigestTest.cc | 14 +- test/Metalink2RequestGroupTest.cc | 79 +- test/MetalinkEntryTest.cc | 31 +- test/MetalinkHelperTest.cc | 31 +- test/MetalinkParserControllerTest.cc | 50 +- test/MetalinkPostDownloadHandlerTest.cc | 37 +- test/MetalinkProcessorTest.cc | 795 +++++++------ test/MetalinkerTest.cc | 13 +- test/MockBtAnnounce.h | 50 +- test/MockBtMessage.h | 47 +- test/MockBtMessageDispatcher.h | 59 +- test/MockBtMessageFactory.h | 70 +- test/MockBtProgressInfoFile.h | 13 +- test/MockBtRequestFactory.h | 18 +- test/MockDHTMessage.h | 77 +- test/MockDHTMessageCallback.h | 12 +- test/MockDHTMessageDispatcher.h | 36 +- test/MockDHTMessageFactory.h | 56 +- test/MockDHTTask.h | 14 +- test/MockDHTTaskFactory.h | 10 +- test/MockDHTTaskQueue.h | 20 +- test/MockExtensionMessage.h | 46 +- test/MockExtensionMessageFactory.h | 6 +- test/MockPeerStorage.h | 60 +- test/MockPieceSelector.h | 7 +- test/MockPieceStorage.h | 230 ++-- test/MockSegment.h | 51 +- test/MultiDiskAdaptorTest.cc | 135 ++- test/MultiFileAllocationIteratorTest.cc | 102 +- test/NetrcAuthResolverTest.cc | 18 +- test/NetrcTest.cc | 43 +- test/NsCookieParserTest.cc | 9 +- test/OptionHandlerTest.cc | 60 +- test/OptionParserTest.cc | 29 +- test/OptionTest.cc | 19 +- test/ParamedStringTest.cc | 30 +- test/PeerConnectionTest.cc | 6 +- test/PeerSessionResourceTest.cc | 18 +- test/PeerTest.cc | 22 +- test/PieceStatManTest.cc | 44 +- test/PieceTest.cc | 36 +- test/PriorityPieceSelectorTest.cc | 14 +- test/ProtocolDetectorTest.cc | 24 +- test/RarestPieceSelectorTest.cc | 10 +- test/RequestGroupManTest.cc | 196 ++- test/RequestGroupTest.cc | 18 +- test/RequestTest.cc | 23 +- test/RpcHelperTest.cc | 190 +-- test/RpcMethodTest.cc | 399 ++++--- test/RpcResponseTest.cc | 43 +- test/SegListTest.cc | 14 +- test/SegmentManTest.cc | 35 +- test/SegmentTest.cc | 5 +- test/SequentialPickerTest.cc | 4 +- test/ServerStatManTest.cc | 76 +- test/ServerStatTest.cc | 26 +- test/SessionSerializerTest.cc | 69 +- test/ShareRatioSeedCriteriaTest.cc | 6 +- test/SignatureTest.cc | 8 +- test/SingleFileAllocationIteratorTest.cc | 11 +- test/SingletonHolderTest.cc | 15 +- test/SinkStreamFilterTest.cc | 32 +- test/SocketCoreTest.cc | 75 +- test/SpeedCalcTest.cc | 13 +- test/Sqlite3CookieParserTest.cc | 23 +- test/TestUtil.cc | 74 +- test/TestUtil.h | 62 +- test/TimeSeedCriteriaTest.cc | 6 +- test/TimeTest.cc | 35 +- test/TimegmTest.cc | 10 +- test/UDPTrackerClientTest.cc | 122 +- test/UTMetadataDataExtensionMessageTest.cc | 16 +- test/UTMetadataPostDownloadHandlerTest.cc | 60 +- test/UTMetadataRejectExtensionMessageTest.cc | 11 +- test/UTMetadataRequestExtensionMessageTest.cc | 24 +- test/UTMetadataRequestFactoryTest.cc | 21 +- test/UTMetadataRequestTrackerTest.cc | 4 +- test/UTPexExtensionMessageTest.cc | 82 +- test/UriListParserTest.cc | 19 +- test/UriSplitTest.cc | 111 +- test/UriTest.cc | 92 +- test/UtilSecurityTest.cc | 338 +++--- test/UtilTest1.cc | 617 ++++++---- test/UtilTest2.cc | 221 ++-- test/ValueBaseBencodeParserTest.cc | 77 +- test/ValueBaseJsonParserTest.cc | 21 +- test/ValueBaseTest.cc | 19 +- test/WrDiskCacheEntryTest.cc | 10 +- test/WrDiskCacheTest.cc | 10 +- test/XORCloserTest.cc | 8 +- test/XmlRpcRequestParserControllerTest.cc | 10 +- test/a2algoTest.cc | 8 +- test/a2functionalTest.cc | 14 +- test/array_funTest.cc | 32 +- test/bitfieldTest.cc | 12 +- test/extension_message_test_helper.h | 7 +- 1095 files changed, 30411 insertions(+), 33758 deletions(-) (limited to 'src/SessionSerializer.cc') diff --git a/examples/libaria2ex.cc b/examples/libaria2ex.cc index c22ac606..85373760 100644 --- a/examples/libaria2ex.cc +++ b/examples/libaria2ex.cc @@ -43,7 +43,7 @@ int downloadEventCallback(aria2::Session* session, aria2::DownloadEvent event, aria2::A2Gid gid, void* userData) { - switch(event) { + switch (event) { case aria2::EVENT_ON_DOWNLOAD_COMPLETE: std::cerr << "COMPLETE"; break; @@ -55,15 +55,17 @@ int downloadEventCallback(aria2::Session* session, aria2::DownloadEvent event, } std::cerr << " [" << aria2::gidToHex(gid) << "] "; aria2::DownloadHandle* dh = aria2::getDownloadHandle(session, gid); - if(!dh) return 0; - if(dh->getNumFiles() > 0) { + if (!dh) + return 0; + if (dh->getNumFiles() > 0) { aria2::FileData f = dh->getFile(1); // Path may be empty if the file name has not been determined yet. - if(f.path.empty()) { - if(!f.uris.empty()) { + if (f.path.empty()) { + if (!f.uris.empty()) { std::cerr << f.uris[0].uri; } - } else { + } + else { std::cerr << f.path; } } @@ -75,7 +77,7 @@ int downloadEventCallback(aria2::Session* session, aria2::DownloadEvent event, int main(int argc, char** argv) { int rv; - if(argc < 2) { + if (argc < 2) { std::cerr << "Usage: libaria2ex URI [URI...]\n" << "\n" << " Download given URIs in parallel in the current directory." @@ -92,46 +94,45 @@ int main(int argc, char** argv) config.downloadEventCallback = downloadEventCallback; session = aria2::sessionNew(aria2::KeyVals(), config); // Add download item to session - for(int i = 1; i < argc; ++i) { + for (int i = 1; i < argc; ++i) { std::vector uris = {argv[i]}; aria2::KeyVals options; rv = aria2::addUri(session, nullptr, uris, options); - if(rv < 0) { + if (rv < 0) { std::cerr << "Failed to add download " << uris[0] << std::endl; } } auto start = std::chrono::steady_clock::now(); - for(;;) { + for (;;) { rv = aria2::run(session, aria2::RUN_ONCE); - if(rv != 1) { + if (rv != 1) { break; } // the application can call aria2 API to add URI or query progress // here auto now = std::chrono::steady_clock::now(); - auto count = std::chrono::duration_cast - (now - start).count(); + auto count = std::chrono::duration_cast( + now - start).count(); // Print progress information once per 500ms - if(count >= 500) { + if (count >= 500) { start = now; aria2::GlobalStat gstat = aria2::getGlobalStat(session); std::cerr << "Overall #Active:" << gstat.numActive << " #waiting:" << gstat.numWaiting - << " D:" << gstat.downloadSpeed/1024 << "KiB/s" - << " U:"<< gstat.uploadSpeed/1024 << "KiB/s " << std::endl; + << " D:" << gstat.downloadSpeed / 1024 << "KiB/s" + << " U:" << gstat.uploadSpeed / 1024 << "KiB/s " << std::endl; std::vector gids = aria2::getActiveDownload(session); - for(const auto& gid : gids) { + for (const auto& gid : gids) { aria2::DownloadHandle* dh = aria2::getDownloadHandle(session, gid); - if(dh) { + if (dh) { std::cerr << " [" << aria2::gidToHex(gid) << "] " - << dh->getCompletedLength() << "/" - << dh->getTotalLength() << "(" - << (dh->getTotalLength() > 0 ? - (100*dh->getCompletedLength()/dh->getTotalLength()) - : 0) << "%)" - << " D:" - << dh->getDownloadSpeed()/1024 << "KiB/s, U:" - << dh->getUploadSpeed()/1024 << "KiB/s" + << dh->getCompletedLength() << "/" << dh->getTotalLength() + << "(" << (dh->getTotalLength() > 0 + ? (100 * dh->getCompletedLength() / + dh->getTotalLength()) + : 0) << "%)" + << " D:" << dh->getDownloadSpeed() / 1024 + << "KiB/s, U:" << dh->getUploadSpeed() / 1024 << "KiB/s" << std::endl; aria2::deleteDownloadHandle(dh); } diff --git a/examples/libaria2wx.cc b/examples/libaria2wx.cc index f40f1a4d..88e8231e 100644 --- a/examples/libaria2wx.cc +++ b/examples/libaria2wx.cc @@ -38,7 +38,8 @@ // the main window. // // Compile and link like this: -// $ g++ -O2 -Wall -g -std=c++11 `wx-config --cflags` -o libaria2wx libaria2wx.cc `wx-config --libs` -laria2 -pthread +// $ g++ -O2 -Wall -g -std=c++11 `wx-config --cflags` -o libaria2wx +// libaria2wx.cc `wx-config --libs` -laria2 -pthread #include #include #include @@ -51,7 +52,7 @@ // Interface to send message to downloader thread from UI thread struct Job { - virtual ~Job() {}; + virtual ~Job(){}; virtual void execute(aria2::Session* session) = 0; }; @@ -59,15 +60,14 @@ class MainFrame; // Interface to report back to UI thread from downloader thread struct Notification { - virtual ~Notification() {}; + virtual ~Notification(){}; virtual void notify(MainFrame* frame) = 0; }; // std::queue wrapper synchronized by mutex. In this example // program, only one thread consumes from the queue, so separating // empty() and pop() is not a problem. -template -class SynchronizedQueue { +template class SynchronizedQueue { public: SynchronizedQueue() {} ~SynchronizedQueue() {} @@ -88,8 +88,9 @@ public: std::lock_guard l(m_); return q_.empty(); } + private: - std::queue > q_; + std::queue> q_; std::mutex m_; }; @@ -109,8 +110,9 @@ struct ShutdownJob : public Job { // Job to send URI to download and options to downloader thread struct AddUriJob : public Job { AddUriJob(std::vector&& uris, aria2::KeyVals&& options) - : uris(uris), options(options) - {} + : uris(uris), options(options) + { + } virtual void execute(aria2::Session* session) { // TODO check return value @@ -148,6 +150,7 @@ public: void OnTimer(wxTimerEvent& event); void OnAddUri(wxCommandEvent& event); void UpdateActiveStatus(const std::vector& v); + private: wxTextCtrl* text_; wxTimer timer_; @@ -157,13 +160,9 @@ private: DECLARE_EVENT_TABLE() }; -enum { - TIMER_ID = 1 -}; +enum { TIMER_ID = 1 }; -enum { - MI_ADD_URI = 1 -}; +enum { MI_ADD_URI = 1 }; BEGIN_EVENT_TABLE(MainFrame, wxFrame) EVT_CLOSE(MainFrame::OnCloseWindow) @@ -177,6 +176,7 @@ public: void OnButton(wxCommandEvent& event); wxString GetUri(); wxString GetOption(); + private: wxTextCtrl* uriText_; wxTextCtrl* optionText_; @@ -193,7 +193,8 @@ IMPLEMENT_APP(Aria2App) bool Aria2App::OnInit() { - if(!wxApp::OnInit()) return false; + if (!wxApp::OnInit()) + return false; aria2::libraryInit(); MainFrame* frame = new MainFrame(wxT("libaria2 GUI example")); frame->Show(true); @@ -207,14 +208,12 @@ int Aria2App::OnExit() } MainFrame::MainFrame(const wxString& title) - : wxFrame(nullptr, wxID_ANY, title, wxDefaultPosition, - wxSize(640, 400)), - timer_(this, TIMER_ID), - downloaderThread_(downloaderJob, std::ref(jobq_), std::ref(notifyq_)) + : wxFrame(nullptr, wxID_ANY, title, wxDefaultPosition, wxSize(640, 400)), + timer_(this, TIMER_ID), + downloaderThread_(downloaderJob, std::ref(jobq_), std::ref(notifyq_)) { wxMenu* downloadMenu = new wxMenu; - downloadMenu->Append(MI_ADD_URI, wxT("&Add URI"), - wxT("Add URI to download")); + downloadMenu->Append(MI_ADD_URI, wxT("&Add URI"), wxT("Add URI to download")); wxMenuBar* menuBar = new wxMenuBar(); menuBar->Append(downloadMenu, wxT("&Download")); @@ -237,35 +236,36 @@ void MainFrame::OnAddUri(wxCommandEvent& WXUNUSED(event)) { AddUriDialog dlg(this); int ret = dlg.ShowModal(); - if(ret == 0) { - if(dlg.GetUri().IsEmpty()) { + if (ret == 0) { + if (dlg.GetUri().IsEmpty()) { return; } - std::vector uris = { std::string(dlg.GetUri().mb_str()) }; + std::vector uris = {std::string(dlg.GetUri().mb_str())}; std::string optstr(dlg.GetOption().mb_str()); aria2::KeyVals options; int keyfirst = 0; - for(int i = 0; i < (int)optstr.size(); ++i) { - if(optstr[i] == '\n') { - keyfirst = i+1; - } else if(optstr[i] == '=') { + for (int i = 0; i < (int)optstr.size(); ++i) { + if (optstr[i] == '\n') { + keyfirst = i + 1; + } + else if (optstr[i] == '=') { int j; - for(j = i+1; j < (int)optstr.size(); ++j) { - if(optstr[j] == '\n') { + for (j = i + 1; j < (int)optstr.size(); ++j) { + if (optstr[j] == '\n') { break; } } - if(i - keyfirst > 0) { - options.push_back - (std::make_pair(optstr.substr(keyfirst, i - keyfirst), - optstr.substr(i + 1, j - i - 1))); + if (i - keyfirst > 0) { + options.push_back( + std::make_pair(optstr.substr(keyfirst, i - keyfirst), + optstr.substr(i + 1, j - i - 1))); } keyfirst = j + 1; i = j; } } - jobq_.push(std::unique_ptr(new AddUriJob(std::move(uris), - std::move(options)))); + jobq_.push(std::unique_ptr( + new AddUriJob(std::move(uris), std::move(options)))); } } @@ -281,56 +281,47 @@ void MainFrame::OnCloseWindow(wxCloseEvent& WXUNUSED(event)) void MainFrame::OnTimer(wxTimerEvent& event) { - while(!notifyq_.empty()) { + while (!notifyq_.empty()) { std::unique_ptr nt = notifyq_.pop(); nt->notify(this); } } -template -std::string abbrevsize(T size) +template std::string abbrevsize(T size) { - if(size >= 1024*1024*1024) { - return std::to_string(size/1024/1024/1024)+"G"; - } else if(size >= 1024*1024) { - return std::to_string(size/1024/1024)+"M"; - } else if(size >= 1024) { - return std::to_string(size/1024)+"K"; - } else { + if (size >= 1024 * 1024 * 1024) { + return std::to_string(size / 1024 / 1024 / 1024) + "G"; + } + else if (size >= 1024 * 1024) { + return std::to_string(size / 1024 / 1024) + "M"; + } + else if (size >= 1024) { + return std::to_string(size / 1024) + "K"; + } + else { return std::to_string(size); } } -wxString towxs(const std::string& s) -{ - return wxString(s.c_str(), wxConvUTF8); -} +wxString towxs(const std::string& s) { return wxString(s.c_str(), wxConvUTF8); } void MainFrame::UpdateActiveStatus(const std::vector& v) { text_->Clear(); - for(auto& a : v) { - *text_ << wxT("[") - << towxs(aria2::gidToHex(a.gid)) - << wxT("] ") - << towxs(abbrevsize(a.completedLength)) - << wxT("/") - << towxs(abbrevsize(a.totalLength)) - << wxT("(") - << (a.totalLength != 0 ? a.completedLength*100/a.totalLength : 0) - << wxT("%)") - << wxT(" D:") - << towxs(abbrevsize(a.downloadSpeed)) - << wxT(" U:") - << towxs(abbrevsize(a.uploadSpeed)) - << wxT("\n") + for (auto& a : v) { + *text_ << wxT("[") << towxs(aria2::gidToHex(a.gid)) << wxT("] ") + << towxs(abbrevsize(a.completedLength)) << wxT("/") + << towxs(abbrevsize(a.totalLength)) << wxT("(") + << (a.totalLength != 0 ? a.completedLength * 100 / a.totalLength : 0) + << wxT("%)") << wxT(" D:") << towxs(abbrevsize(a.downloadSpeed)) + << wxT(" U:") << towxs(abbrevsize(a.uploadSpeed)) << wxT("\n") << wxT("File:") << towxs(a.filename) << wxT("\n"); } } AddUriDialog::AddUriDialog(wxWindow* parent) - : wxDialog(parent, wxID_ANY, wxT("Add URI"), wxDefaultPosition, - wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) + : wxDialog(parent, wxID_ANY, wxT("Add URI"), wxDefaultPosition, + wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) { wxPanel* panel = new wxPanel(this, wxID_ANY); wxBoxSizer* box = new wxBoxSizer(wxVERTICAL); @@ -339,9 +330,8 @@ AddUriDialog::AddUriDialog(wxWindow* parent) uriText_ = new wxTextCtrl(panel, wxID_ANY); box->Add(uriText_, wxSizerFlags().Align(wxGROW)); // Option multi text input - box->Add(new wxStaticText - (panel, wxID_ANY, - wxT("Options (key=value pair per line, e.g. dir=/tmp"))); + box->Add(new wxStaticText( + panel, wxID_ANY, wxT("Options (key=value pair per line, e.g. dir=/tmp"))); optionText_ = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE); box->Add(optionText_, wxSizerFlags().Align(wxGROW)); @@ -363,38 +353,25 @@ AddUriDialog::AddUriDialog(wxWindow* parent) void AddUriDialog::OnButton(wxCommandEvent& event) { int ret = -1; - if(event.GetEventObject() == okBtn_) { + if (event.GetEventObject() == okBtn_) { ret = 0; } EndModal(ret); } -wxString AddUriDialog::GetUri() -{ - return uriText_->GetValue(); -} +wxString AddUriDialog::GetUri() { return uriText_->GetValue(); } -wxString AddUriDialog::GetOption() -{ - return optionText_->GetValue(); -} +wxString AddUriDialog::GetOption() { return optionText_->GetValue(); } struct DownloadStatusNotification : public Notification { - DownloadStatusNotification(std::vector&& v) - : v(v) {} - virtual void notify(MainFrame* frame) - { - frame->UpdateActiveStatus(v); - } + DownloadStatusNotification(std::vector&& v) : v(v) {} + virtual void notify(MainFrame* frame) { frame->UpdateActiveStatus(v); } std::vector v; }; struct ShutdownNotification : public Notification { ShutdownNotification() {} - virtual void notify(MainFrame* frame) - { - frame->Close(); - } + virtual void notify(MainFrame* frame) { frame->Close(); } }; int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq) @@ -406,32 +383,32 @@ int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq) config.keepRunning = true; session = aria2::sessionNew(aria2::KeyVals(), config); auto start = std::chrono::steady_clock::now(); - for(;;) { + for (;;) { int rv = aria2::run(session, aria2::RUN_ONCE); - if(rv != 1) { + if (rv != 1) { break; } auto now = std::chrono::steady_clock::now(); - auto count = std::chrono::duration_cast - (now - start).count(); - while(!jobq.empty()) { + auto count = std::chrono::duration_cast( + now - start).count(); + while (!jobq.empty()) { std::unique_ptr job = jobq.pop(); job->execute(session); } - if(count >= 900) { + if (count >= 900) { start = now; std::vector gids = aria2::getActiveDownload(session); std::vector v; - for(auto gid : gids) { + for (auto gid : gids) { aria2::DownloadHandle* dh = aria2::getDownloadHandle(session, gid); - if(dh) { + if (dh) { DownloadStatus st; st.gid = gid; st.totalLength = dh->getTotalLength(); st.completedLength = dh->getCompletedLength(); st.downloadSpeed = dh->getDownloadSpeed(); st.uploadSpeed = dh->getUploadSpeed(); - if(dh->getNumFiles() > 0) { + if (dh->getNumFiles() > 0) { aria2::FileData file = dh->getFile(1); st.filename = file.path; } @@ -439,8 +416,8 @@ int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq) aria2::deleteDownloadHandle(dh); } } - notifyq.push(std::unique_ptr - (new DownloadStatusNotification(std::move(v)))); + notifyq.push(std::unique_ptr( + new DownloadStatusNotification(std::move(v)))); } } int rv = aria2::sessionFinal(session); @@ -449,4 +426,3 @@ int downloaderJob(JobQueue& jobq, NotifyQueue& notifyq) notifyq.push(std::unique_ptr(new ShutdownNotification())); return rv; } - diff --git a/src/ARC4Encryptor.h b/src/ARC4Encryptor.h index 96c55936..9100de22 100644 --- a/src/ARC4Encryptor.h +++ b/src/ARC4Encryptor.h @@ -38,13 +38,13 @@ #include "common.h" #ifdef USE_INTERNAL_ARC4 -# include "InternalARC4Encryptor.h" +#include "InternalARC4Encryptor.h" #elif HAVE_LIBNETTLE -# include "LibnettleARC4Encryptor.h" +#include "LibnettleARC4Encryptor.h" #elif HAVE_LIBGCRYPT -# include "LibgcryptARC4Encryptor.h" +#include "LibgcryptARC4Encryptor.h" #elif HAVE_OPENSSL -# include "LibsslARC4Encryptor.h" +#include "LibsslARC4Encryptor.h" #endif #endif // D_ARC4_ENCRYPTOR_H diff --git a/src/AbstractAuthResolver.cc b/src/AbstractAuthResolver.cc index 9eceeba4..6a4e28b2 100644 --- a/src/AbstractAuthResolver.cc +++ b/src/AbstractAuthResolver.cc @@ -42,8 +42,8 @@ AbstractAuthResolver::AbstractAuthResolver() {} AbstractAuthResolver::~AbstractAuthResolver() {} -void AbstractAuthResolver::setUserDefinedCred -(std::string user, std::string password) +void AbstractAuthResolver::setUserDefinedCred(std::string user, + std::string password) { userDefinedUser_ = std::move(user); userDefinedPassword_ = std::move(password); @@ -55,8 +55,8 @@ AbstractAuthResolver::getUserDefinedAuthConfig() const return AuthConfig::create(userDefinedUser_, userDefinedPassword_); } -void AbstractAuthResolver::setDefaultCred -(std::string user, std::string password) +void AbstractAuthResolver::setDefaultCred(std::string user, + std::string password) { defaultUser_ = std::move(user); defaultPassword_ = std::move(password); diff --git a/src/AbstractAuthResolver.h b/src/AbstractAuthResolver.h index 25dd923e..b03e72e2 100644 --- a/src/AbstractAuthResolver.h +++ b/src/AbstractAuthResolver.h @@ -52,6 +52,7 @@ public: void setDefaultCred(std::string user, std::string password); std::unique_ptr getDefaultAuthConfig() const; + private: std::string userDefinedUser_; std::string userDefinedPassword_; diff --git a/src/AbstractBtMessage.cc b/src/AbstractBtMessage.cc index 76eb4787..3bb90967 100644 --- a/src/AbstractBtMessage.cc +++ b/src/AbstractBtMessage.cc @@ -40,18 +40,19 @@ namespace aria2 { AbstractBtMessage::AbstractBtMessage(uint8_t id, const char* name) - : BtMessage(id), - invalidate_(false), - uploading_(false), - cuid_(0), - name_(name), - pieceStorage_(nullptr), - dispatcher_(nullptr), - messageFactory_(nullptr), - requestFactory_(nullptr), - peerConnection_(nullptr), - metadataGetMode_(false) -{} + : BtMessage(id), + invalidate_(false), + uploading_(false), + cuid_(0), + name_(name), + pieceStorage_(nullptr), + dispatcher_(nullptr), + messageFactory_(nullptr), + requestFactory_(nullptr), + peerConnection_(nullptr), + metadataGetMode_(false) +{ +} AbstractBtMessage::~AbstractBtMessage() {} @@ -62,14 +63,13 @@ void AbstractBtMessage::setPeer(const std::shared_ptr& peer) void AbstractBtMessage::validate() { - if(validator_) { + if (validator_) { validator_->validate(); } } -void -AbstractBtMessage::setBtMessageValidator -(std::unique_ptr validator) +void AbstractBtMessage::setBtMessageValidator( + std::unique_ptr validator) { validator_ = std::move(validator); } diff --git a/src/AbstractBtMessage.h b/src/AbstractBtMessage.h index 5b46ce21..d03b6567 100644 --- a/src/AbstractBtMessage.h +++ b/src/AbstractBtMessage.h @@ -71,69 +71,38 @@ private: std::unique_ptr validator_; bool metadataGetMode_; + protected: - PieceStorage* getPieceStorage() const - { - return pieceStorage_; - } + PieceStorage* getPieceStorage() const { return pieceStorage_; } - PeerConnection* getPeerConnection() const - { - return peerConnection_; - } + PeerConnection* getPeerConnection() const { return peerConnection_; } - BtMessageDispatcher* getBtMessageDispatcher() const - { - return dispatcher_; - } + BtMessageDispatcher* getBtMessageDispatcher() const { return dispatcher_; } - BtRequestFactory* getBtRequestFactory() const - { - return requestFactory_; - } + BtRequestFactory* getBtRequestFactory() const { return requestFactory_; } - BtMessageFactory* getBtMessageFactory() const - { - return messageFactory_; - } + BtMessageFactory* getBtMessageFactory() const { return messageFactory_; } + + bool isMetadataGetMode() const { return metadataGetMode_; } - bool isMetadataGetMode() const - { - return metadataGetMode_; - } public: AbstractBtMessage(uint8_t id, const char* name); virtual ~AbstractBtMessage(); - virtual bool isInvalidate() CXX11_OVERRIDE { - return invalidate_; - } + virtual bool isInvalidate() CXX11_OVERRIDE { return invalidate_; } - void setInvalidate(bool invalidate) { - invalidate_ = invalidate; - } + void setInvalidate(bool invalidate) { invalidate_ = invalidate; } - virtual bool isUploading() CXX11_OVERRIDE { - return uploading_; - } + virtual bool isUploading() CXX11_OVERRIDE { return uploading_; } - void setUploading(bool uploading) { - uploading_ = uploading; - } + void setUploading(bool uploading) { uploading_ = uploading; } - cuid_t getCuid() const { - return cuid_; - } + cuid_t getCuid() const { return cuid_; } - void setCuid(cuid_t cuid) { - cuid_ = cuid; - } + void setCuid(cuid_t cuid) { cuid_ = cuid; } - const std::shared_ptr& getPeer() const - { - return peer_; - } + const std::shared_ptr& getPeer() const { return peer_; } void setPeer(const std::shared_ptr& peer); @@ -143,11 +112,15 @@ public: virtual void onQueued() CXX11_OVERRIDE {} - virtual void onAbortOutstandingRequestEvent - (const BtAbortOutstandingRequestEvent& event) CXX11_OVERRIDE {} + virtual void onAbortOutstandingRequestEvent( + const BtAbortOutstandingRequestEvent& event) CXX11_OVERRIDE + { + } - virtual void onCancelSendingPieceEvent - (const BtCancelSendingPieceEvent& event) CXX11_OVERRIDE {} + virtual void onCancelSendingPieceEvent(const BtCancelSendingPieceEvent& event) + CXX11_OVERRIDE + { + } virtual void onChokingEvent(const BtChokingEvent& event) CXX11_OVERRIDE {} @@ -163,15 +136,9 @@ public: void setBtRequestFactory(BtRequestFactory* factory); - const char* getName() const - { - return name_; - } + const char* getName() const { return name_; } - void enableMetadataGetMode() - { - metadataGetMode_ = true; - } + void enableMetadataGetMode() { metadataGetMode_ = true; } }; } // namespace aria2 diff --git a/src/AbstractCommand.cc b/src/AbstractCommand.cc index 59b92c06..27762cc8 100644 --- a/src/AbstractCommand.cc +++ b/src/AbstractCommand.cc @@ -74,31 +74,28 @@ namespace aria2 { -AbstractCommand::AbstractCommand -(cuid_t cuid, - const std::shared_ptr& req, - const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - DownloadEngine* e, - const std::shared_ptr& s, - const std::shared_ptr& socketRecvBuffer, - bool incNumConnection) - : Command(cuid), - req_(req), - fileEntry_(fileEntry), - socket_(s), - socketRecvBuffer_(socketRecvBuffer), +AbstractCommand::AbstractCommand( + cuid_t cuid, const std::shared_ptr& req, + const std::shared_ptr& fileEntry, RequestGroup* requestGroup, + DownloadEngine* e, const std::shared_ptr& s, + const std::shared_ptr& socketRecvBuffer, + bool incNumConnection) + : Command(cuid), + req_(req), + fileEntry_(fileEntry), + socket_(s), + socketRecvBuffer_(socketRecvBuffer), #ifdef ENABLE_ASYNC_DNS - asyncNameResolverMan_(make_unique()), + asyncNameResolverMan_(make_unique()), #endif // ENABLE_ASYNC_DNS - requestGroup_(requestGroup), - e_(e), - checkPoint_(global::wallclock()), - serverStatTimer_(global::wallclock()), - timeout_(requestGroup->getTimeout()), - checkSocketIsReadable_(false), - checkSocketIsWritable_(false), - incNumConnection_(incNumConnection) + requestGroup_(requestGroup), + e_(e), + checkPoint_(global::wallclock()), + serverStatTimer_(global::wallclock()), + timeout_(requestGroup->getTimeout()), + checkSocketIsReadable_(false), + checkSocketIsWritable_(false), + incNumConnection_(incNumConnection) { if (socket_ && socket_->isOpen()) { setReadCheckSocket(socket_); @@ -127,19 +124,18 @@ AbstractCommand::~AbstractCommand() } } -void -AbstractCommand::useFasterRequest(const std::shared_ptr& fasterRequest) +void AbstractCommand::useFasterRequest( + const std::shared_ptr& fasterRequest) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - Use faster Request hostname=%s, port=%u", - getCuid(), - fasterRequest->getHost().c_str(), + getCuid(), fasterRequest->getHost().c_str(), fasterRequest->getPort())); // Cancel current Request object and use faster one. fileEntry_->removeRequest(req_); e_->setNoWait(true); - e_->addCommand - (InitiateConnectionCommandFactory::createInitiateConnectionCommand - (getCuid(), fasterRequest, fileEntry_, requestGroup_, e_)); + e_->addCommand( + InitiateConnectionCommandFactory::createInitiateConnectionCommand( + getCuid(), fasterRequest, fileEntry_, requestGroup_, e_)); } bool AbstractCommand::shouldProcess() const @@ -167,7 +163,7 @@ bool AbstractCommand::shouldProcess() const if (!checkSocketIsReadable_ && !checkSocketIsWritable_ && !resolverChecked) { return true; } -#else // ENABLE_ASYNC_DNS +#else // ENABLE_ASYNC_DNS if (!checkSocketIsReadable_ && !checkSocketIsWritable_) { return true; } @@ -180,11 +176,8 @@ bool AbstractCommand::execute() { A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - socket: read:%d, write:%d, hup:%d, err:%d", - getCuid(), - readEventEnabled(), - writeEventEnabled(), - hupEventEnabled(), - errorEventEnabled())); + getCuid(), readEventEnabled(), writeEventEnabled(), + hupEventEnabled(), errorEventEnabled())); try { if (requestGroup_->downloadFinished() || requestGroup_->isHaltRequested()) { return true; @@ -194,8 +187,7 @@ bool AbstractCommand::execute() A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Discard original URI=%s because it is" " requested.", - getCuid(), - req_->getUri().c_str())); + getCuid(), req_->getUri().c_str())); return prepareForRetry(0); } @@ -243,8 +235,8 @@ bool AbstractCommand::execute() if (getOption()->getAsBool(PREF_SELECT_LEAST_USED_HOST)) { getDownloadEngine()->getRequestGroupMan()->getUsedHosts(usedHosts); } - auto fasterRequest = fileEntry_->findFasterRequest - (req_, usedHosts, e_->getRequestGroupMan()->getServerStatMan()); + auto fasterRequest = fileEntry_->findFasterRequest( + req_, usedHosts, e_->getRequestGroupMan()->getServerStatMan()); if (fasterRequest) { useFasterRequest(fasterRequest); return true; @@ -296,8 +288,8 @@ bool AbstractCommand::execute() size_t minSplitSize = calculateMinSplitSize(); size_t maxSegments = req_->getMaxPipelinedRequest(); if (segments_.size() < maxSegments) { - sm->getSegment - (segments_, getCuid(), minSplitSize, fileEntry_, maxSegments); + sm->getSegment(segments_, getCuid(), minSplitSize, fileEntry_, + maxSegments); } if (segments_.empty()) { return prepareForRetry(0); @@ -308,22 +300,21 @@ bool AbstractCommand::execute() } if (errorEventEnabled()) { - throw DL_RETRY_EX - (fmt(MSG_NETWORK_PROBLEM, socket_->getSocketError().c_str())); + throw DL_RETRY_EX( + fmt(MSG_NETWORK_PROBLEM, socket_->getSocketError().c_str())); } if (checkPoint_.difference(global::wallclock()) >= timeout_) { // timeout triggers ServerStat error state. - auto ss = e_->getRequestGroupMan()->getOrCreateServerStat - (req_->getHost(), req_->getProtocol()); + auto ss = e_->getRequestGroupMan()->getOrCreateServerStat( + req_->getHost(), req_->getProtocol()); ss->setError(); // When DNS query was timeout, req_->getConnectedAddr() is // empty. if (!req_->getConnectedAddr().empty()) { // Purging IP address cache to renew IP address. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Marking IP address %s as bad", - getCuid(), - req_->getConnectedAddr().c_str())); + getCuid(), req_->getConnectedAddr().c_str())); e_->markBadIPAddress(req_->getConnectedHostname(), req_->getConnectedAddr(), req_->getConnectedPort()); @@ -345,9 +336,9 @@ bool AbstractCommand::execute() catch (DlAbortEx& err) { requestGroup_->setLastErrorCode(err.getErrorCode(), err.what()); if (req_) { - A2_LOG_ERROR_EX - (fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), - DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err)); + A2_LOG_ERROR_EX( + fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), + DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err)); fileEntry_->addURIResult(req_->getUri(), err.getErrorCode()); if (err.getErrorCode() == error_code::CANNOT_RESUME) { requestGroup_->increaseResumeFailureCount(); @@ -362,9 +353,9 @@ bool AbstractCommand::execute() } catch (DlRetryEx& err) { assert(req_); - A2_LOG_INFO_EX - (fmt(MSG_RESTARTING_DOWNLOAD, getCuid(), req_->getUri().c_str()), - DL_RETRY_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err)); + A2_LOG_INFO_EX( + fmt(MSG_RESTARTING_DOWNLOAD, getCuid(), req_->getUri().c_str()), + DL_RETRY_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err)); req_->addTryCount(); req_->resetRedirectCount(); req_->resetUri(); @@ -373,8 +364,8 @@ bool AbstractCommand::execute() bool isAbort = maxTries != 0 && req_->getTryCount() >= maxTries; if (isAbort) { A2_LOG_INFO(fmt(MSG_MAX_TRY, getCuid(), req_->getTryCount())); - A2_LOG_ERROR_EX - (fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), err); + A2_LOG_ERROR_EX( + fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), err); fileEntry_->addURIResult(req_->getUri(), err.getErrorCode()); requestGroup_->setLastErrorCode(err.getErrorCode(), err.what()); if (err.getErrorCode() == error_code::CANNOT_RESUME) { @@ -394,11 +385,12 @@ bool AbstractCommand::execute() catch (DownloadFailureException& err) { requestGroup_->setLastErrorCode(err.getErrorCode(), err.what()); if (req_) { - A2_LOG_ERROR_EX - (fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), - DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err)); + A2_LOG_ERROR_EX( + fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), + DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err)); fileEntry_->addURIResult(req_->getUri(), err.getErrorCode()); - } else { + } + else { A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, err); } requestGroup_->setHaltRequested(true); @@ -422,8 +414,8 @@ void AbstractCommand::tryReserved() return; } } - A2_LOG_DEBUG - (fmt("CUID#%" PRId64 " - Trying reserved/pooled request.", getCuid())); + A2_LOG_DEBUG( + fmt("CUID#%" PRId64 " - Trying reserved/pooled request.", getCuid())); std::vector> commands; requestGroup_->createNextCommand(commands, e_, 1); e_->setNoWait(true); @@ -443,8 +435,7 @@ bool AbstractCommand::prepareForRetry(time_t wait) req_->setMaxPipelinedRequest(1); fileEntry_->poolRequest(req_); - A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Pooling request URI=%s", - getCuid(), + A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Pooling request URI=%s", getCuid(), req_->getUri().c_str())); if (getSegmentMan()) { getSegmentMan()->recognizeSegmentFor(fileEntry_); @@ -518,8 +509,7 @@ void AbstractCommand::onAbort() uris.reserve(res.size()); std::transform(std::begin(res), std::end(res), std::back_inserter(uris), std::mem_fn(&URIResult::getURI)); - A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - %lu URIs found.", - getCuid(), + A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - %lu URIs found.", getCuid(), static_cast(uris.size()))); fileEntry_->addUris(std::begin(uris), std::end(uris)); getSegmentMan()->recognizeSegmentFor(fileEntry_); @@ -536,8 +526,8 @@ void AbstractCommand::disableReadCheckSocket() readCheckTarget_.reset(); } -void -AbstractCommand::setReadCheckSocket(const std::shared_ptr& socket) +void AbstractCommand::setReadCheckSocket( + const std::shared_ptr& socket) { if (!socket->isOpen()) { disableReadCheckSocket(); @@ -558,9 +548,8 @@ AbstractCommand::setReadCheckSocket(const std::shared_ptr& socket) readCheckTarget_ = socket; } -void -AbstractCommand::setReadCheckSocketIf(const std::shared_ptr& socket, - bool pred) +void AbstractCommand::setReadCheckSocketIf( + const std::shared_ptr& socket, bool pred) { if (pred) { setReadCheckSocket(socket); @@ -580,8 +569,8 @@ void AbstractCommand::disableWriteCheckSocket() writeCheckTarget_.reset(); } -void -AbstractCommand::setWriteCheckSocket(const std::shared_ptr& socket) +void AbstractCommand::setWriteCheckSocket( + const std::shared_ptr& socket) { if (!socket->isOpen()) { disableWriteCheckSocket(); @@ -602,8 +591,8 @@ AbstractCommand::setWriteCheckSocket(const std::shared_ptr& socket) writeCheckTarget_ = socket; } -void AbstractCommand::setWriteCheckSocketIf -(const std::shared_ptr& socket, bool pred) +void AbstractCommand::setWriteCheckSocketIf( + const std::shared_ptr& socket, bool pred) { if (pred) { setWriteCheckSocket(socket); @@ -623,10 +612,8 @@ void AbstractCommand::swapSocket(std::shared_ptr& socket) namespace { // Constructs proxy URI, merging username and password if they are // defined. -std::string makeProxyUri(PrefPtr proxyPref, - PrefPtr proxyUser, - PrefPtr proxyPasswd, - const Option* option) +std::string makeProxyUri(PrefPtr proxyPref, PrefPtr proxyUser, + PrefPtr proxyPasswd, const Option* option) { uri::UriStruct us; if (!uri::parse(us, option->get(proxyPref))) { @@ -645,15 +632,13 @@ std::string makeProxyUri(PrefPtr proxyPref, namespace { // Returns proxy option value for the given protocol. -std::string getProxyOptionFor(PrefPtr proxyPref, - PrefPtr proxyUser, - PrefPtr proxyPasswd, - const Option* option) +std::string getProxyOptionFor(PrefPtr proxyPref, PrefPtr proxyUser, + PrefPtr proxyPasswd, const Option* option) { std::string uri = makeProxyUri(proxyPref, proxyUser, proxyPasswd, option); if (uri.empty()) { - return makeProxyUri - (PREF_ALL_PROXY, PREF_ALL_PROXY_USER, PREF_ALL_PROXY_PASSWD, option); + return makeProxyUri(PREF_ALL_PROXY, PREF_ALL_PROXY_USER, + PREF_ALL_PROXY_PASSWD, option); } return uri; @@ -665,20 +650,18 @@ std::string getProxyOptionFor(PrefPtr proxyPref, std::string getProxyUri(const std::string& protocol, const Option* option) { if (protocol == "http") { - return getProxyOptionFor - (PREF_HTTP_PROXY, PREF_HTTP_PROXY_USER, PREF_HTTP_PROXY_PASSWD, option); + return getProxyOptionFor(PREF_HTTP_PROXY, PREF_HTTP_PROXY_USER, + PREF_HTTP_PROXY_PASSWD, option); } if (protocol == "https") { - return getProxyOptionFor(PREF_HTTPS_PROXY, - PREF_HTTPS_PROXY_USER, - PREF_HTTPS_PROXY_PASSWD, - option); + return getProxyOptionFor(PREF_HTTPS_PROXY, PREF_HTTPS_PROXY_USER, + PREF_HTTPS_PROXY_PASSWD, option); } if (protocol == "ftp" || protocol == "sftp") { - return getProxyOptionFor - (PREF_FTP_PROXY, PREF_FTP_PROXY_USER, PREF_FTP_PROXY_PASSWD, option); + return getProxyOptionFor(PREF_FTP_PROXY, PREF_FTP_PROXY_USER, + PREF_FTP_PROXY_PASSWD, option); } return A2STR::NIL; @@ -752,8 +735,8 @@ std::shared_ptr AbstractCommand::createProxyRequest() const A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Using proxy", getCuid())); } else { - A2_LOG_DEBUG - (fmt("CUID#%" PRId64 " - Failed to parse proxy string", getCuid())); + A2_LOG_DEBUG( + fmt("CUID#%" PRId64 " - Failed to parse proxy string", getCuid())); proxyRequest.reset(); } } @@ -790,8 +773,7 @@ std::string AbstractCommand::resolveHostname(std::vector& addrs, ->getOrCreateServerStat(req_->getHost(), req_->getProtocol()) ->setError(); } - throw DL_ABORT_EX2(fmt(MSG_NAME_RESOLUTION_FAILED, - getCuid(), + throw DL_ABORT_EX2(fmt(MSG_NAME_RESOLUTION_FAILED, getCuid(), hostname.c_str(), asyncNameResolverMan_->getLastError().c_str()), error_code::NAME_RESOLVE_ERROR); @@ -801,10 +783,8 @@ std::string AbstractCommand::resolveHostname(std::vector& addrs, case 1: asyncNameResolverMan_->getResolvedAddress(addrs); if (addrs.empty()) { - throw DL_ABORT_EX2(fmt(MSG_NAME_RESOLUTION_FAILED, - getCuid(), - hostname.c_str(), - "No address returned"), + throw DL_ABORT_EX2(fmt(MSG_NAME_RESOLUTION_FAILED, getCuid(), + hostname.c_str(), "No address returned"), error_code::NAME_RESOLVE_ERROR); } break; @@ -829,21 +809,20 @@ std::string AbstractCommand::resolveHostname(std::vector& addrs, return ipaddr; } -void AbstractCommand::prepareForNextAction -(std::unique_ptr checkEntry) +void AbstractCommand::prepareForNextAction( + std::unique_ptr checkEntry) { std::vector> commands; - requestGroup_->processCheckIntegrityEntry - (commands, std::move(checkEntry), e_); + requestGroup_->processCheckIntegrityEntry(commands, std::move(checkEntry), + e_); e_->addCommand(std::move(commands)); e_->setNoWait(true); } -bool AbstractCommand::checkIfConnectionEstablished -(const std::shared_ptr& socket, - const std::string& connectedHostname, - const std::string& connectedAddr, - uint16_t connectedPort) +bool AbstractCommand::checkIfConnectionEstablished( + const std::shared_ptr& socket, + const std::string& connectedHostname, const std::string& connectedAddr, + uint16_t connectedPort) { std::string error = socket->getSocketError(); if (error.empty()) { @@ -864,14 +843,12 @@ bool AbstractCommand::checkIfConnectionEstablished throw DL_RETRY_EX(fmt(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str())); } - A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY, - getCuid(), - connectedAddr.c_str(), - connectedPort)); + A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY, getCuid(), + connectedAddr.c_str(), connectedPort)); e_->setNoWait(true); - e_->addCommand - (InitiateConnectionCommandFactory::createInitiateConnectionCommand - (getCuid(), req_, fileEntry_, requestGroup_, e_)); + e_->addCommand( + InitiateConnectionCommandFactory::createInitiateConnectionCommand( + getCuid(), req_, fileEntry_, requestGroup_, e_)); return false; } @@ -909,10 +886,7 @@ void AbstractCommand::setRequest(const std::shared_ptr& request) req_ = request; } -void AbstractCommand::resetRequest() -{ - req_.reset(); -} +void AbstractCommand::resetRequest() { req_.reset(); } void AbstractCommand::setFileEntry(const std::shared_ptr& fileEntry) { diff --git a/src/AbstractCommand.h b/src/AbstractCommand.h index 6cf5a5de..1cb366df 100644 --- a/src/AbstractCommand.h +++ b/src/AbstractCommand.h @@ -62,8 +62,7 @@ class AsyncNameResolver; class AsyncNameResolverMan; #endif // ENABLE_ASYNC_DNS -class AbstractCommand : public Command -{ +class AbstractCommand : public Command { private: std::shared_ptr req_; std::shared_ptr fileEntry_; @@ -97,15 +96,9 @@ private: bool shouldProcess() const; public: - RequestGroup* getRequestGroup() const - { - return requestGroup_; - } + RequestGroup* getRequestGroup() const { return requestGroup_; } - const std::shared_ptr& getRequest() const - { - return req_; - } + const std::shared_ptr& getRequest() const { return req_; } void setRequest(const std::shared_ptr& request); @@ -113,27 +106,15 @@ public: // setRequest(std::shared_ptr()); void resetRequest(); - const std::shared_ptr& getFileEntry() const - { - return fileEntry_; - } + const std::shared_ptr& getFileEntry() const { return fileEntry_; } void setFileEntry(const std::shared_ptr& fileEntry); - DownloadEngine* getDownloadEngine() const - { - return e_; - } + DownloadEngine* getDownloadEngine() const { return e_; } - const std::shared_ptr& getSocket() const - { - return socket_; - } + const std::shared_ptr& getSocket() const { return socket_; } - std::shared_ptr& getSocket() - { - return socket_; - } + std::shared_ptr& getSocket() { return socket_; } void setSocket(const std::shared_ptr& s); @@ -155,8 +136,7 @@ public: // arguments until resolved address is returned. Exception is // thrown on error. port is used for retrieving cached addresses. std::string resolveHostname(std::vector& addrs, - const std::string& hostname, - uint16_t port); + const std::string& hostname, uint16_t port); void tryReserved(); @@ -185,10 +165,7 @@ public: // check. void swapSocket(std::shared_ptr& socket); - std::chrono::seconds getTimeout() const - { - return timeout_; - } + std::chrono::seconds getTimeout() const { return timeout_; } void setTimeout(std::chrono::seconds timeout) { @@ -229,10 +206,7 @@ public: const std::shared_ptr& getSegmentMan() const; const std::shared_ptr& getPieceStorage() const; - Timer& getCheckPoint() - { - return checkPoint_; - } + Timer& getCheckPoint() { return checkPoint_; } void checkSocketRecvBuffer(); @@ -247,21 +221,15 @@ protected: // Returns true if the derived class wants to execute // executeInternal() unconditionally - virtual bool noCheck() const - { - return false; - } + virtual bool noCheck() const { return false; } public: - AbstractCommand(cuid_t cuid, - const std::shared_ptr& req, - const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - DownloadEngine* e, - const std::shared_ptr& s = nullptr, - const std::shared_ptr& socketRecvBuffer = - nullptr, - bool incNumConnection = true); + AbstractCommand( + cuid_t cuid, const std::shared_ptr& req, + const std::shared_ptr& fileEntry, RequestGroup* requestGroup, + DownloadEngine* e, const std::shared_ptr& s = nullptr, + const std::shared_ptr& socketRecvBuffer = nullptr, + bool incNumConnection = true); virtual ~AbstractCommand(); diff --git a/src/AbstractDiskWriter.cc b/src/AbstractDiskWriter.cc index e3ce6d6b..931ee88a 100644 --- a/src/AbstractDiskWriter.cc +++ b/src/AbstractDiskWriter.cc @@ -36,7 +36,7 @@ #include #ifdef HAVE_MMAP -# include +#include #endif // HAVE_MMAP #include @@ -57,24 +57,22 @@ namespace aria2 { AbstractDiskWriter::AbstractDiskWriter(const std::string& filename) - : filename_(filename), - fd_(A2_BAD_FD), + : filename_(filename), + fd_(A2_BAD_FD), #ifdef __MINGW32__ - mapView_(0), -#else // !__MINGW32__ + mapView_(0), +#else // !__MINGW32__ #endif // !__MINGW32__ - readOnly_(false), - enableMmap_(false), - mapaddr_(nullptr), - maplen_(0) - -{} + readOnly_(false), + enableMmap_(false), + mapaddr_(nullptr), + maplen_(0) -AbstractDiskWriter::~AbstractDiskWriter() { - closeFile(); } +AbstractDiskWriter::~AbstractDiskWriter() { closeFile(); } + namespace { // Returns error code depending on the platform. For MinGW32, return // the value of GetLastError(). Otherwise, return errno. @@ -82,7 +80,7 @@ int fileError() { #ifdef __MINGW32__ return GetLastError(); -#else // !__MINGW32__ +#else // !__MINGW32__ return errno; #endif // !__MINGW32__ } @@ -96,18 +94,15 @@ std::string fileStrerror(int errNum) { #ifdef __MINGW32__ static char buf[256]; - if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - 0, - errNum, - // Default language - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - (LPTSTR) &buf, - sizeof(buf), - 0) == 0) { + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + 0, errNum, + // Default language + MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR)&buf, + sizeof(buf), 0) == 0) { snprintf(buf, sizeof(buf), "File I/O error %x", errNum); } return buf; -#else // !__MINGW32__ +#else // !__MINGW32__ return util::safeStrerror(errNum); #endif // !__MINGW32__ } @@ -117,17 +112,19 @@ void AbstractDiskWriter::openFile(int64_t totalLength) { try { openExistingFile(totalLength); - } catch(RecoverableException& e) { - if( + } + catch (RecoverableException& e) { + if ( #ifdef __MINGW32__ - e.getErrNum() == ERROR_FILE_NOT_FOUND || - e.getErrNum() == ERROR_PATH_NOT_FOUND -#else // !__MINGW32__ - e.getErrNum() == ENOENT + e.getErrNum() == ERROR_FILE_NOT_FOUND || + e.getErrNum() == ERROR_PATH_NOT_FOUND +#else // !__MINGW32__ + e.getErrNum() == ENOENT #endif // !__MINGW32__ - ) { + ) { initAndOpenFile(totalLength); - } else { + } + else { throw; } } @@ -136,34 +133,35 @@ void AbstractDiskWriter::openFile(int64_t totalLength) void AbstractDiskWriter::closeFile() { #if defined(HAVE_MMAP) || defined(__MINGW32__) - if(mapaddr_) { + if (mapaddr_) { int errNum = 0; #ifdef __MINGW32__ - if(!UnmapViewOfFile(mapaddr_)) { + if (!UnmapViewOfFile(mapaddr_)) { errNum = GetLastError(); } CloseHandle(mapView_); mapView_ = INVALID_HANDLE_VALUE; -#else // !__MINGW32__ - if(munmap(mapaddr_, maplen_) == -1) { +#else // !__MINGW32__ + if (munmap(mapaddr_, maplen_) == -1) { errNum = errno; } #endif // !__MINGW32__ - if(errNum != 0) { + if (errNum != 0) { int errNum = fileError(); - A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", - filename_.c_str(), fileStrerror(errNum).c_str())); - } else { + A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", filename_.c_str(), + fileStrerror(errNum).c_str())); + } + else { A2_LOG_INFO(fmt("Unmapping file %s succeeded", filename_.c_str())); } mapaddr_ = nullptr; maplen_ = 0; } #endif // HAVE_MMAP || defined __MINGW32__ - if(fd_ != A2_BAD_FD) { + if (fd_ != A2_BAD_FD) { #ifdef __MINGW32__ CloseHandle(fd_); -#else // !__MINGW32__ +#else // !__MINGW32__ close(fd_); #endif // !__MINGW32__ fd_ = A2_BAD_FD; @@ -180,29 +178,32 @@ HANDLE openFileWithFlags(const std::string& filename, int flags, DWORD sharedMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; DWORD creationDisp = 0; - if(flags & O_RDWR) { + if (flags & O_RDWR) { desiredAccess = GENERIC_READ | GENERIC_WRITE; - } else if(flags & O_WRONLY) { + } + else if (flags & O_WRONLY) { desiredAccess = GENERIC_WRITE; - } else { + } + else { desiredAccess = GENERIC_READ; } - if(flags & O_CREAT) { - if(flags & O_TRUNC) { + if (flags & O_CREAT) { + if (flags & O_TRUNC) { creationDisp |= CREATE_ALWAYS; - } else { + } + else { creationDisp |= CREATE_NEW; } - } else { + } + else { creationDisp |= OPEN_EXISTING; } hn = CreateFileW(utf8ToWChar(filename).c_str(), desiredAccess, sharedMode, /* lpSecurityAttributes */ 0, creationDisp, FILE_ATTRIBUTE_NORMAL, /* hTemplateFile */ 0); - if(hn == INVALID_HANDLE_VALUE) { + if (hn == INVALID_HANDLE_VALUE) { int errNum = GetLastError(); - throw DL_ABORT_EX3(errNum, fmt(EX_FILE_OPEN, - filename.c_str(), + throw DL_ABORT_EX3(errNum, fmt(EX_FILE_OPEN, filename.c_str(), fileStrerror(errNum).c_str()), errCode); } @@ -213,9 +214,10 @@ int openFileWithFlags(const std::string& filename, int flags, error_code::Value errCode) { int fd; - while((fd = a2open(utf8ToWChar(filename).c_str(), flags, OPEN_MODE)) == -1 - && errno == EINTR); - if(fd < 0) { + while ((fd = a2open(utf8ToWChar(filename).c_str(), flags, OPEN_MODE)) == -1 && + errno == EINTR) + ; + if (fd < 0) { int errNum = errno; throw DL_ABORT_EX3(errNum, fmt(EX_FILE_OPEN, filename.c_str(), util::safeStrerror(errNum).c_str()), @@ -233,9 +235,10 @@ int openFileWithFlags(const std::string& filename, int flags, void AbstractDiskWriter::openExistingFile(int64_t totalLength) { int flags = O_BINARY; - if(readOnly_) { + if (readOnly_) { flags |= O_RDONLY; - } else { + } + else { flags |= O_RDWR; } fd_ = openFileWithFlags(filename_, flags, error_code::FILE_OPEN_ERROR); @@ -245,32 +248,38 @@ void AbstractDiskWriter::createFile(int addFlags) { assert(!filename_.empty()); util::mkdirs(File(filename_).getDirname()); - fd_ = openFileWithFlags(filename_, O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags, + fd_ = openFileWithFlags(filename_, + O_CREAT | O_RDWR | O_TRUNC | O_BINARY | addFlags, error_code::FILE_CREATE_ERROR); } ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data, size_t len, int64_t offset) { - if(mapaddr_) { + if (mapaddr_) { memcpy(mapaddr_ + offset, data, len); return len; - } else { + } + else { ssize_t writtenLength = 0; seek(offset); - while((size_t)writtenLength < len) { + while ((size_t)writtenLength < len) { #ifdef __MINGW32__ DWORD nwrite; - if(WriteFile(fd_, data+writtenLength, len-writtenLength, &nwrite, 0)) { + if (WriteFile(fd_, data + writtenLength, len - writtenLength, &nwrite, + 0)) { writtenLength += nwrite; - } else { + } + else { return -1; } -#else // !__MINGW32__ +#else // !__MINGW32__ ssize_t ret = 0; - while((ret = write(fd_, data+writtenLength, len-writtenLength)) == -1 && - errno == EINTR); - if(ret == -1) { + while ((ret = write(fd_, data + writtenLength, len - writtenLength)) == + -1 && + errno == EINTR) + ; + if (ret == -1) { return -1; } writtenLength += ret; @@ -283,25 +292,28 @@ ssize_t AbstractDiskWriter::writeDataInternal(const unsigned char* data, ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len, int64_t offset) { - if(mapaddr_) { + if (mapaddr_) { if (offset >= maplen_) { return 0; } auto readlen = std::min(maplen_ - offset, static_cast(len)); memcpy(data, mapaddr_ + offset, readlen); return readlen; - } else { + } + else { seek(offset); #ifdef __MINGW32__ DWORD nread; - if(ReadFile(fd_, data, len, &nread, 0)) { + if (ReadFile(fd_, data, len, &nread, 0)) { return nread; - } else { + } + else { return -1; } -#else // !__MINGW32__ +#else // !__MINGW32__ ssize_t ret = 0; - while((ret = read(fd_, data, len)) == -1 && errno == EINTR); + while ((ret = read(fd_, data, len)) == -1 && errno == EINTR) + ; return ret; #endif // !__MINGW32__ } @@ -313,45 +325,46 @@ void AbstractDiskWriter::seek(int64_t offset) #ifdef __MINGW32__ LARGE_INTEGER fileLength; fileLength.QuadPart = offset; - if(SetFilePointerEx(fd_, fileLength, 0, FILE_BEGIN) == 0) -#else // !__MINGW32__ - if(a2lseek(fd_, offset, SEEK_SET) == (a2_off_t)-1) + if (SetFilePointerEx(fd_, fileLength, 0, FILE_BEGIN) == 0) +#else // !__MINGW32__ + if (a2lseek(fd_, offset, SEEK_SET) == (a2_off_t)-1) #endif // !__MINGW32__ - { - int errNum = fileError(); - throw DL_ABORT_EX2(fmt(EX_FILE_SEEK, filename_.c_str(), - fileStrerror(errNum).c_str()), - error_code::FILE_IO_ERROR); - } + { + int errNum = fileError(); + throw DL_ABORT_EX2( + fmt(EX_FILE_SEEK, filename_.c_str(), fileStrerror(errNum).c_str()), + error_code::FILE_IO_ERROR); + } } void AbstractDiskWriter::ensureMmapWrite(size_t len, int64_t offset) { #if defined(HAVE_MMAP) || defined(__MINGW32__) - if(enableMmap_) { - if(mapaddr_) { - if(static_cast(len + offset) > maplen_) { + if (enableMmap_) { + if (mapaddr_) { + if (static_cast(len + offset) > maplen_) { int errNum = 0; #ifdef __MINGW32__ - if(!UnmapViewOfFile(mapaddr_)) { + if (!UnmapViewOfFile(mapaddr_)) { errNum = GetLastError(); } CloseHandle(mapView_); mapView_ = INVALID_HANDLE_VALUE; -#else // !__MINGW32__ - if(munmap(mapaddr_, maplen_) == -1) { +#else // !__MINGW32__ + if (munmap(mapaddr_, maplen_) == -1) { errNum = errno; } #endif // !__MINGW32__ - if(errNum != 0) { - A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", - filename_.c_str(), fileStrerror(errNum).c_str())); + if (errNum != 0) { + A2_LOG_ERROR(fmt("Unmapping file %s failed: %s", filename_.c_str(), + fileStrerror(errNum).c_str())); } mapaddr_ = nullptr; maplen_ = 0; enableMmap_ = false; } - } else { + } + else { int64_t filesize = size(); if (filesize == 0) { @@ -362,37 +375,37 @@ void AbstractDiskWriter::ensureMmapWrite(size_t len, int64_t offset) } int errNum = 0; - if(static_cast(len + offset) <= filesize) { + if (static_cast(len + offset) <= filesize) { #ifdef __MINGW32__ - mapView_ = CreateFileMapping(fd_, 0, PAGE_READWRITE, - filesize >> 32, filesize & 0xffffffffu, - 0); - if(mapView_) { - mapaddr_ = reinterpret_cast - (MapViewOfFile(mapView_, FILE_MAP_WRITE, 0, 0, 0)); - if(!mapaddr_) { + mapView_ = CreateFileMapping(fd_, 0, PAGE_READWRITE, filesize >> 32, + filesize & 0xffffffffu, 0); + if (mapView_) { + mapaddr_ = reinterpret_cast( + MapViewOfFile(mapView_, FILE_MAP_WRITE, 0, 0, 0)); + if (!mapaddr_) { errNum = GetLastError(); CloseHandle(mapView_); mapView_ = INVALID_HANDLE_VALUE; } - } else { + } + else { errNum = GetLastError(); } -#else // !__MINGW32__ - mapaddr_ = reinterpret_cast - (mmap(nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0)); - if(!mapaddr_) { +#else // !__MINGW32__ + mapaddr_ = reinterpret_cast(mmap( + nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0)); + if (!mapaddr_) { errNum = errno; } #endif // !__MINGW32__ - if(mapaddr_) { + if (mapaddr_) { A2_LOG_DEBUG(fmt("Mapping file %s succeeded, length=%" PRId64 "", - filename_.c_str(), - static_cast(filesize))); + filename_.c_str(), static_cast(filesize))); maplen_ = filesize; - } else { - A2_LOG_WARN(fmt("Mapping file %s failed: %s", - filename_.c_str(), fileStrerror(errNum).c_str())); + } + else { + A2_LOG_WARN(fmt("Mapping file %s failed: %s", filename_.c_str(), + fileStrerror(errNum).c_str())); enableMmap_ = false; } } @@ -401,158 +414,142 @@ void AbstractDiskWriter::ensureMmapWrite(size_t len, int64_t offset) #endif // HAVE_MMAP || __MINGW32__ } -void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, int64_t offset) +void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, + int64_t offset) { ensureMmapWrite(len, offset); - if(writeDataInternal(data, len, offset) < 0) { + if (writeDataInternal(data, len, offset) < 0) { int errNum = fileError(); - if( - // If the error indicates disk full situation, throw - // DownloadFailureException and abort download instantly. + if ( +// If the error indicates disk full situation, throw +// DownloadFailureException and abort download instantly. #ifdef __MINGW32__ - errNum == ERROR_DISK_FULL || errNum == ERROR_HANDLE_DISK_FULL -#else // !__MINGW32__ - errNum == ENOSPC + errNum == ERROR_DISK_FULL || errNum == ERROR_HANDLE_DISK_FULL +#else // !__MINGW32__ + errNum == ENOSPC #endif // !__MINGW32__ - ) { - throw DOWNLOAD_FAILURE_EXCEPTION3 - (errNum, fmt(EX_FILE_WRITE, filename_.c_str(), - fileStrerror(errNum).c_str()), - error_code::NOT_ENOUGH_DISK_SPACE); - } else { - throw DL_ABORT_EX3 - (errNum, fmt(EX_FILE_WRITE, filename_.c_str(), - fileStrerror(errNum).c_str()), - error_code::FILE_IO_ERROR); + ) { + throw DOWNLOAD_FAILURE_EXCEPTION3( + errNum, + fmt(EX_FILE_WRITE, filename_.c_str(), fileStrerror(errNum).c_str()), + error_code::NOT_ENOUGH_DISK_SPACE); + } + else { + throw DL_ABORT_EX3(errNum, fmt(EX_FILE_WRITE, filename_.c_str(), + fileStrerror(errNum).c_str()), + error_code::FILE_IO_ERROR); } } } -ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, int64_t offset) +ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, + int64_t offset) { ssize_t ret; - if((ret = readDataInternal(data, len, offset)) < 0) { + if ((ret = readDataInternal(data, len, offset)) < 0) { int errNum = fileError(); - throw DL_ABORT_EX3 - (errNum, fmt(EX_FILE_READ, filename_.c_str(), - fileStrerror(errNum).c_str()), - error_code::FILE_IO_ERROR); + throw DL_ABORT_EX3(errNum, fmt(EX_FILE_READ, filename_.c_str(), + fileStrerror(errNum).c_str()), + error_code::FILE_IO_ERROR); } return ret; } void AbstractDiskWriter::truncate(int64_t length) { - if(fd_ == A2_BAD_FD) { + if (fd_ == A2_BAD_FD) { throw DL_ABORT_EX("File not yet opened."); } #ifdef __MINGW32__ // Since mingw32's ftruncate cannot handle over 2GB files, we use // SetEndOfFile instead. seek(length); - if(SetEndOfFile(fd_) == 0) -#else // !__MINGW32__ - if(a2ftruncate(fd_, length) == -1) + if (SetEndOfFile(fd_) == 0) +#else // !__MINGW32__ + if (a2ftruncate(fd_, length) == -1) #endif // !__MINGW32__ - { - int errNum = fileError(); - throw DL_ABORT_EX2(fmt("File truncation failed. cause: %s", - fileStrerror(errNum).c_str()), - error_code::FILE_IO_ERROR); - } + { + int errNum = fileError(); + throw DL_ABORT_EX2( + fmt("File truncation failed. cause: %s", fileStrerror(errNum).c_str()), + error_code::FILE_IO_ERROR); + } } void AbstractDiskWriter::allocate(int64_t offset, int64_t length, bool sparse) { - if(fd_ == A2_BAD_FD) { + if (fd_ == A2_BAD_FD) { throw DL_ABORT_EX("File not yet opened."); } - if(sparse) { + if (sparse) { #ifdef __MINGW32__ DWORD bytesReturned; - if(!DeviceIoControl(fd_, FSCTL_SET_SPARSE, 0, 0, 0, 0, - &bytesReturned, 0)) { + if (!DeviceIoControl(fd_, FSCTL_SET_SPARSE, 0, 0, 0, 0, &bytesReturned, + 0)) { A2_LOG_WARN(fmt("Making file sparse failed or pending: %s", fileStrerror(GetLastError()).c_str())); } #endif // __MINGW32__ - truncate(offset+length); + truncate(offset + length); return; } -#ifdef HAVE_SOME_FALLOCATE -# ifdef __MINGW32__ - truncate(offset+length); -# elif defined(__APPLE__) && defined(__MACH__) +#ifdef HAVE_SOME_FALLOCATE +#ifdef __MINGW32__ + truncate(offset + length); +#elif defined(__APPLE__) && defined(__MACH__) auto toalloc = offset + length - size(); while (toalloc > 0) { fstore_t fstore = { - F_ALLOCATECONTIG | F_ALLOCATEALL, - F_PEOFPOSMODE, - 0, - // Allocate in 1GB chunks or else some OSX versions may choke. - std::min(toalloc, (int64_t)1<<30), - 0 - }; + F_ALLOCATECONTIG | F_ALLOCATEALL, F_PEOFPOSMODE, 0, + // Allocate in 1GB chunks or else some OSX versions may choke. + std::min(toalloc, (int64_t)1 << 30), 0}; if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) { // Retry non-contig. fstore.fst_flags = F_ALLOCATEALL; if (fcntl(fd_, F_PREALLOCATE, &fstore) == -1) { int err = errno; - throw DL_ABORT_EX3(err, - fmt("fcntl(F_PREALLOCATE) of %" PRId64 " failed. cause: %s", - fstore.fst_length, util::safeStrerror(err).c_str()), - error_code::FILE_IO_ERROR); + throw DL_ABORT_EX3( + err, fmt("fcntl(F_PREALLOCATE) of %" PRId64 " failed. cause: %s", + fstore.fst_length, util::safeStrerror(err).c_str()), + error_code::FILE_IO_ERROR); } } toalloc -= fstore.fst_bytesalloc; } // This forces the allocation on disk. ftruncate(fd_, offset + length); -# elif HAVE_FALLOCATE +#elif HAVE_FALLOCATE // For linux, we use fallocate to detect file system supports // fallocate or not. int r; - while((r = fallocate(fd_, 0, offset, length)) == -1 && errno == EINTR); + while ((r = fallocate(fd_, 0, offset, length)) == -1 && errno == EINTR) + ; int errNum = errno; - if(r == -1) { - throw DL_ABORT_EX3(errNum, - fmt("fallocate failed. cause: %s", - util::safeStrerror(errNum).c_str()), + if (r == -1) { + throw DL_ABORT_EX3(errNum, fmt("fallocate failed. cause: %s", + util::safeStrerror(errNum).c_str()), error_code::FILE_IO_ERROR); } -# elif HAVE_POSIX_FALLOCATE +#elif HAVE_POSIX_FALLOCATE int r = posix_fallocate(fd_, offset, length); - if(r != 0) { - throw DL_ABORT_EX3(r, - fmt("posix_fallocate failed. cause: %s", - util::safeStrerror(r).c_str()), + if (r != 0) { + throw DL_ABORT_EX3(r, fmt("posix_fallocate failed. cause: %s", + util::safeStrerror(r).c_str()), error_code::FILE_IO_ERROR); } -# else -# error "no *_fallocate function available." -# endif +#else +#error "no *_fallocate function available." +#endif #endif // HAVE_SOME_FALLOCATE } -int64_t AbstractDiskWriter::size() -{ - return File(filename_).size(); -} +int64_t AbstractDiskWriter::size() { return File(filename_).size(); } -void AbstractDiskWriter::enableReadOnly() -{ - readOnly_ = true; -} +void AbstractDiskWriter::enableReadOnly() { readOnly_ = true; } -void AbstractDiskWriter::disableReadOnly() -{ - readOnly_ = false; -} +void AbstractDiskWriter::disableReadOnly() { readOnly_ = false; } -void AbstractDiskWriter::enableMmap() -{ - enableMmap_ = true; -} +void AbstractDiskWriter::enableMmap() { enableMmap_ = true; } void AbstractDiskWriter::dropCache(int64_t len, int64_t offset) { diff --git a/src/AbstractDiskWriter.h b/src/AbstractDiskWriter.h index f469ab4f..9e5c4799 100644 --- a/src/AbstractDiskWriter.h +++ b/src/AbstractDiskWriter.h @@ -48,7 +48,7 @@ private: HANDLE fd_; // The handle for memory mapped file. mmap equivalent in Windows. HANDLE mapView_; -#else // !__MINGW32__ +#else // !__MINGW32__ int fd_; #endif // !__MINGW32__ @@ -65,8 +65,10 @@ private: void seek(int64_t offset); void ensureMmapWrite(size_t len, int64_t offset); + protected: void createFile(int addFlags = 0); + public: AbstractDiskWriter(const std::string& filename); virtual ~AbstractDiskWriter(); @@ -77,17 +79,17 @@ public: virtual void openExistingFile(int64_t totalLength = 0) CXX11_OVERRIDE; - virtual void writeData(const unsigned char* data, size_t len, int64_t offset) - CXX11_OVERRIDE; + virtual void writeData(const unsigned char* data, size_t len, + int64_t offset) CXX11_OVERRIDE; - virtual ssize_t readData(unsigned char* data, size_t len, int64_t offset) - CXX11_OVERRIDE; + virtual ssize_t readData(unsigned char* data, size_t len, + int64_t offset) CXX11_OVERRIDE; virtual void truncate(int64_t length) CXX11_OVERRIDE; // File must be opened before calling this function. - virtual void allocate(int64_t offset, int64_t length, bool sparse) - CXX11_OVERRIDE; + virtual void allocate(int64_t offset, int64_t length, + bool sparse) CXX11_OVERRIDE; virtual int64_t size() CXX11_OVERRIDE; diff --git a/src/AbstractHttpServerResponseCommand.cc b/src/AbstractHttpServerResponseCommand.cc index 057e74fa..80923ae9 100644 --- a/src/AbstractHttpServerResponseCommand.cc +++ b/src/AbstractHttpServerResponseCommand.cc @@ -47,17 +47,15 @@ namespace aria2 { -AbstractHttpServerResponseCommand::AbstractHttpServerResponseCommand -(cuid_t cuid, - const std::shared_ptr& httpServer, - DownloadEngine* e, - const std::shared_ptr& socket) - : Command(cuid), - e_(e), - socket_(socket), - httpServer_(httpServer), - readCheck_(false), - writeCheck_(true) +AbstractHttpServerResponseCommand::AbstractHttpServerResponseCommand( + cuid_t cuid, const std::shared_ptr& httpServer, + DownloadEngine* e, const std::shared_ptr& socket) + : Command(cuid), + e_(e), + socket_(socket), + httpServer_(httpServer), + readCheck_(false), + writeCheck_(true) { setStatus(Command::STATUS_ONESHOT_REALTIME); e_->addSocketForWriteCheck(socket_, this); @@ -65,31 +63,33 @@ AbstractHttpServerResponseCommand::AbstractHttpServerResponseCommand AbstractHttpServerResponseCommand::~AbstractHttpServerResponseCommand() { - if(readCheck_) { + if (readCheck_) { e_->deleteSocketForReadCheck(socket_, this); } - if(writeCheck_) { + if (writeCheck_) { e_->deleteSocketForWriteCheck(socket_, this); } } void AbstractHttpServerResponseCommand::updateReadWriteCheck() { - if(httpServer_->wantRead()) { - if(!readCheck_) { + if (httpServer_->wantRead()) { + if (!readCheck_) { readCheck_ = true; e_->addSocketForReadCheck(socket_, this); } - } else if(readCheck_) { + } + else if (readCheck_) { readCheck_ = false; e_->deleteSocketForReadCheck(socket_, this); } - if(httpServer_->wantWrite()) { - if(!writeCheck_) { + if (httpServer_->wantWrite()) { + if (!writeCheck_) { writeCheck_ = true; e_->addSocketForWriteCheck(socket_, this); } - } else if(writeCheck_) { + } + else if (writeCheck_) { writeCheck_ = false; e_->deleteSocketForWriteCheck(socket_, this); } @@ -97,34 +97,36 @@ void AbstractHttpServerResponseCommand::updateReadWriteCheck() bool AbstractHttpServerResponseCommand::execute() { - if(e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) { + if (e_->getRequestGroupMan()->downloadFinished() || e_->isHaltRequested()) { return true; } try { ssize_t len = httpServer_->sendResponse(); - if(len > 0) { + if (len > 0) { timeoutTimer_ = global::wallclock(); } - } catch(RecoverableException& e) { - A2_LOG_INFO_EX - (fmt("CUID#%" PRId64 - " - Error occurred while transmitting response body.", - getCuid()), - e); + } + catch (RecoverableException& e) { + A2_LOG_INFO_EX(fmt("CUID#%" PRId64 + " - Error occurred while transmitting response body.", + getCuid()), + e); return true; } - if(httpServer_->sendBufferIsEmpty()) { + if (httpServer_->sendBufferIsEmpty()) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - HttpServer: all response transmitted.", getCuid())); afterSend(httpServer_, e_); return true; - } else { + } + else { if (timeoutTimer_.difference(global::wallclock()) >= 30_s) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - HttpServer: Timeout while trasmitting response.", getCuid())); return true; - } else { + } + else { updateReadWriteCheck(); e_->addCommand(std::unique_ptr(this)); return false; diff --git a/src/AbstractHttpServerResponseCommand.h b/src/AbstractHttpServerResponseCommand.h index 431351b8..9d07d771 100644 --- a/src/AbstractHttpServerResponseCommand.h +++ b/src/AbstractHttpServerResponseCommand.h @@ -57,19 +57,17 @@ private: bool writeCheck_; void updateReadWriteCheck(); + protected: - DownloadEngine* getDownloadEngine() - { - return e_; - } + DownloadEngine* getDownloadEngine() { return e_; } // Called after content body is completely sent. virtual void afterSend(const std::shared_ptr& httpServer, DownloadEngine* e) = 0; + public: - AbstractHttpServerResponseCommand(cuid_t cuid, - const std::shared_ptr& httpServer, - DownloadEngine* e, - const std::shared_ptr& socket); + AbstractHttpServerResponseCommand( + cuid_t cuid, const std::shared_ptr& httpServer, + DownloadEngine* e, const std::shared_ptr& socket); virtual ~AbstractHttpServerResponseCommand(); diff --git a/src/AbstractOptionHandler.cc b/src/AbstractOptionHandler.cc index c888d504..51fdf4ff 100644 --- a/src/AbstractOptionHandler.cc +++ b/src/AbstractOptionHandler.cc @@ -44,20 +44,19 @@ namespace aria2 { -AbstractOptionHandler::AbstractOptionHandler -(PrefPtr pref, - const char* description, - const std::string& defaultValue, - ARG_TYPE argType, - char shortName) - : pref_(pref), - description_(description), - defaultValue_(defaultValue), - argType_(argType), - shortName_(shortName), - tags_(0), - flags_(0) -{} +AbstractOptionHandler::AbstractOptionHandler(PrefPtr pref, + const char* description, + const std::string& defaultValue, + ARG_TYPE argType, char shortName) + : pref_(pref), + description_(description), + defaultValue_(defaultValue), + argType_(argType), + shortName_(shortName), + tags_(0), + flags_(0) +{ +} AbstractOptionHandler::~AbstractOptionHandler() {} @@ -65,7 +64,8 @@ void AbstractOptionHandler::parse(Option& option, const std::string& arg) const { try { parseArg(option, arg); - } catch(Exception& e) { + } + catch (Exception& e) { throw OPTION_HANDLER_EXCEPTION2(pref_, e); } } @@ -75,49 +75,38 @@ bool AbstractOptionHandler::hasTag(uint32_t tag) const return (tags_ & (1 << tag)); } -void AbstractOptionHandler::addTag(uint32_t tag) -{ - tags_ |= (1 << tag); -} +void AbstractOptionHandler::addTag(uint32_t tag) { tags_ |= (1 << tag); } std::string AbstractOptionHandler::toTagString() const { std::string s; - for(int i = 0; i < MAX_HELP_TAG; ++i) { - if(tags_ & (1 << i)) { + for (int i = 0; i < MAX_HELP_TAG; ++i) { + if (tags_ & (1 << i)) { s += strHelpTag(i); s += ", "; } } - if(!s.empty()) { + if (!s.empty()) { s.resize(s.size() - 2); } return s; } -const char* AbstractOptionHandler::getName() const -{ - return pref_->k; -} +const char* AbstractOptionHandler::getName() const { return pref_->k; } void AbstractOptionHandler::updateFlags(int flag, bool val) { - if(val) { + if (val) { flags_ |= flag; - } else { + } + else { flags_ &= ~flag; } } -bool AbstractOptionHandler::isHidden() const -{ - return flags_ & FLAG_HIDDEN; -} +bool AbstractOptionHandler::isHidden() const { return flags_ & FLAG_HIDDEN; } -void AbstractOptionHandler::hide() -{ - updateFlags(FLAG_HIDDEN, true); -} +void AbstractOptionHandler::hide() { updateFlags(FLAG_HIDDEN, true); } bool AbstractOptionHandler::getEraseAfterParse() const { diff --git a/src/AbstractOptionHandler.h b/src/AbstractOptionHandler.h index f59518db..20e91dd4 100644 --- a/src/AbstractOptionHandler.h +++ b/src/AbstractOptionHandler.h @@ -55,17 +55,16 @@ protected: char shortName_; virtual void parseArg(Option& option, const std::string& arg) const = 0; + public: - AbstractOptionHandler(PrefPtr pref, - const char* description = NO_DESCRIPTION, - const std::string& defaultValue = NO_DEFAULT_VALUE, - ARG_TYPE argType = REQ_ARG, - char shortName = 0); + AbstractOptionHandler(PrefPtr pref, const char* description = NO_DESCRIPTION, + const std::string& defaultValue = NO_DEFAULT_VALUE, + ARG_TYPE argType = REQ_ARG, char shortName = 0); virtual ~AbstractOptionHandler(); - virtual void parse(Option& option, const std::string& arg) const - CXX11_OVERRIDE; + virtual void parse(Option& option, + const std::string& arg) const CXX11_OVERRIDE; virtual bool hasTag(uint32_t tag) const CXX11_OVERRIDE; @@ -85,15 +84,9 @@ public: return defaultValue_; } - virtual PrefPtr getPref() const CXX11_OVERRIDE - { - return pref_; - } + virtual PrefPtr getPref() const CXX11_OVERRIDE { return pref_; } - virtual char getShortName() const CXX11_OVERRIDE - { - return shortName_; - } + virtual char getShortName() const CXX11_OVERRIDE { return shortName_; } virtual OptionHandler::ARG_TYPE getArgType() const CXX11_OVERRIDE { @@ -137,6 +130,7 @@ public: FLAG_CHANGE_GLOBAL_OPTION = 1 << 5, FLAG_CUMULATIVE = 1 << 6 }; + private: // bitwise OR of (1 << HelpTag value) defined in help_tags.h. uint32_t tags_; diff --git a/src/AbstractProxyRequestCommand.cc b/src/AbstractProxyRequestCommand.cc index 3dd01adf..74d23142 100644 --- a/src/AbstractProxyRequestCommand.cc +++ b/src/AbstractProxyRequestCommand.cc @@ -49,20 +49,15 @@ namespace aria2 { -AbstractProxyRequestCommand::AbstractProxyRequestCommand -(cuid_t cuid, - const std::shared_ptr& req, - const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - DownloadEngine* e, - const std::shared_ptr& proxyRequest, - const std::shared_ptr& s) - : - AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), - proxyRequest_(proxyRequest), - httpConnection_ - (std::make_shared - (cuid, s, std::make_shared(s))) +AbstractProxyRequestCommand::AbstractProxyRequestCommand( + cuid_t cuid, const std::shared_ptr& req, + const std::shared_ptr& fileEntry, RequestGroup* requestGroup, + DownloadEngine* e, const std::shared_ptr& proxyRequest, + const std::shared_ptr& s) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), + proxyRequest_(proxyRequest), + httpConnection_(std::make_shared( + cuid, s, std::make_shared(s))) { setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT))); disableReadCheckSocket(); @@ -71,22 +66,25 @@ AbstractProxyRequestCommand::AbstractProxyRequestCommand AbstractProxyRequestCommand::~AbstractProxyRequestCommand() {} -bool AbstractProxyRequestCommand::executeInternal() { - //socket->setBlockingMode(); - if(httpConnection_->sendBufferIsEmpty()) { +bool AbstractProxyRequestCommand::executeInternal() +{ + // socket->setBlockingMode(); + if (httpConnection_->sendBufferIsEmpty()) { auto httpRequest = make_unique(); httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT)); httpRequest->setRequest(getRequest()); httpRequest->setProxyRequest(proxyRequest_); httpConnection_->sendProxyRequest(std::move(httpRequest)); - } else { + } + else { httpConnection_->sendPendingData(); } - if(httpConnection_->sendBufferIsEmpty()) { + if (httpConnection_->sendBufferIsEmpty()) { getDownloadEngine()->addCommand(getNextCommand()); return true; - } else { + } + else { setWriteCheckSocket(getSocket()); addCommandSelf(); return false; diff --git a/src/AbstractProxyRequestCommand.h b/src/AbstractProxyRequestCommand.h index e394a2a4..07835b31 100644 --- a/src/AbstractProxyRequestCommand.h +++ b/src/AbstractProxyRequestCommand.h @@ -47,6 +47,7 @@ private: std::shared_ptr proxyRequest_; std::shared_ptr httpConnection_; + protected: virtual bool executeInternal() CXX11_OVERRIDE; @@ -59,12 +60,11 @@ protected: { return proxyRequest_; } + public: - AbstractProxyRequestCommand(cuid_t cuid, - const std::shared_ptr& req, + AbstractProxyRequestCommand(cuid_t cuid, const std::shared_ptr& req, const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - DownloadEngine* e, + RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr& proxyRequest, const std::shared_ptr& s); diff --git a/src/AbstractProxyResponseCommand.cc b/src/AbstractProxyResponseCommand.cc index 14461ea7..90a11244 100644 --- a/src/AbstractProxyResponseCommand.cc +++ b/src/AbstractProxyResponseCommand.cc @@ -50,27 +50,28 @@ namespace aria2 { -AbstractProxyResponseCommand::AbstractProxyResponseCommand -(cuid_t cuid, - const std::shared_ptr& req, - const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - const std::shared_ptr& httpConnection, - DownloadEngine* e, - const std::shared_ptr& s) - :AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), - httpConnection_(httpConnection) {} +AbstractProxyResponseCommand::AbstractProxyResponseCommand( + cuid_t cuid, const std::shared_ptr& req, + const std::shared_ptr& fileEntry, RequestGroup* requestGroup, + const std::shared_ptr& httpConnection, DownloadEngine* e, + const std::shared_ptr& s) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), + httpConnection_(httpConnection) +{ +} AbstractProxyResponseCommand::~AbstractProxyResponseCommand() {} -bool AbstractProxyResponseCommand::executeInternal() { - std::shared_ptr httpResponse = httpConnection_->receiveResponse(); - if(!httpResponse) { +bool AbstractProxyResponseCommand::executeInternal() +{ + std::shared_ptr httpResponse = + httpConnection_->receiveResponse(); + if (!httpResponse) { // the server has not responded our request yet. addCommandSelf(); return false; } - if(httpResponse->getStatusCode() != 200) { + if (httpResponse->getStatusCode() != 200) { throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED); } getDownloadEngine()->addCommand(getNextCommand()); diff --git a/src/AbstractProxyResponseCommand.h b/src/AbstractProxyResponseCommand.h index edc19583..8bcdd36d 100644 --- a/src/AbstractProxyResponseCommand.h +++ b/src/AbstractProxyResponseCommand.h @@ -45,6 +45,7 @@ class SocketCore; class AbstractProxyResponseCommand : public AbstractCommand { private: std::shared_ptr httpConnection_; + protected: virtual bool executeInternal() CXX11_OVERRIDE; @@ -52,15 +53,13 @@ protected: { return httpConnection_; } + public: - AbstractProxyResponseCommand - (cuid_t cuid, - const std::shared_ptr& req, - const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - const std::shared_ptr& httpConnection, - DownloadEngine* e, - const std::shared_ptr& s); + AbstractProxyResponseCommand( + cuid_t cuid, const std::shared_ptr& req, + const std::shared_ptr& fileEntry, RequestGroup* requestGroup, + const std::shared_ptr& httpConnection, DownloadEngine* e, + const std::shared_ptr& s); virtual ~AbstractProxyResponseCommand(); diff --git a/src/AbstractSingleDiskAdaptor.cc b/src/AbstractSingleDiskAdaptor.cc index 899168f1..470beb37 100644 --- a/src/AbstractSingleDiskAdaptor.cc +++ b/src/AbstractSingleDiskAdaptor.cc @@ -41,13 +41,15 @@ #include "WrDiskCacheEntry.h" #include "LogFactory.h" #ifdef HAVE_SOME_FALLOCATE -# include "FallocFileAllocationIterator.h" +#include "FallocFileAllocationIterator.h" #endif // HAVE_SOME_FALLOCATE namespace aria2 { -AbstractSingleDiskAdaptor::AbstractSingleDiskAdaptor(): - totalLength_(0), readOnly_(false) {} +AbstractSingleDiskAdaptor::AbstractSingleDiskAdaptor() + : totalLength_(0), readOnly_(false) +{ +} AbstractSingleDiskAdaptor::~AbstractSingleDiskAdaptor() {} @@ -61,34 +63,31 @@ void AbstractSingleDiskAdaptor::openFile() diskWriter_->openFile(totalLength_); } -void AbstractSingleDiskAdaptor::closeFile() -{ - diskWriter_->closeFile(); -} +void AbstractSingleDiskAdaptor::closeFile() { diskWriter_->closeFile(); } void AbstractSingleDiskAdaptor::openExistingFile() { diskWriter_->openExistingFile(totalLength_); } -void AbstractSingleDiskAdaptor::writeData -(const unsigned char* data, size_t len, int64_t offset) +void AbstractSingleDiskAdaptor::writeData(const unsigned char* data, size_t len, + int64_t offset) { diskWriter_->writeData(data, len, offset); } -ssize_t AbstractSingleDiskAdaptor::readData -(unsigned char* data, size_t len, int64_t offset) +ssize_t AbstractSingleDiskAdaptor::readData(unsigned char* data, size_t len, + int64_t offset) { return diskWriter_->readData(data, len, offset); } -ssize_t AbstractSingleDiskAdaptor::readDataDropCache -(unsigned char* data, size_t len, int64_t offset) +ssize_t AbstractSingleDiskAdaptor::readDataDropCache(unsigned char* data, + size_t len, int64_t offset) { auto rv = readData(data, len, offset); - if(rv > 0) { + if (rv > 0) { diskWriter_->dropCache(len, offset); } @@ -106,31 +105,32 @@ void AbstractSingleDiskAdaptor::writeCache(const WrDiskCacheEntry* entry) size_t buflen = 0; size_t buffoffset = 0; const WrDiskCacheEntry::DataCellSet& dataSet = entry->getDataSet(); - for(auto & d : dataSet) { - if(start+static_cast(buflen) < d->goff) { - A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", - start, static_cast(buflen))); - writeData(buf+buffoffset, buflen-buffoffset, start); + for (auto& d : dataSet) { + if (start + static_cast(buflen) < d->goff) { + A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", start, + static_cast(buflen))); + writeData(buf + buffoffset, buflen - buffoffset, start); start = d->goff; buflen = buffoffset = 0; } - if(buflen == 0 && (d->goff & 0xfff) == 0 && (d->len & 0xfff) == 0) { + if (buflen == 0 && (d->goff & 0xfff) == 0 && (d->len & 0xfff) == 0) { // Already aligned. Write it without copy. - A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", - start, static_cast(d->len))); + A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", start, + static_cast(d->len))); writeData(d->data + d->offset, d->len, start); start += d->len; - } else { - if(buflen == 0) { + } + else { + if (buflen == 0) { buflen = buffoffset = d->goff & 0xfff; } size_t wlen = std::min(sizeof(buf) - buflen, d->len); - memcpy(buf+buflen, d->data + d->offset, wlen); + memcpy(buf + buflen, d->data + d->offset, wlen); buflen += wlen; - if(buflen == sizeof(buf)) { - A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", - start, static_cast(buflen))); - writeData(buf+buffoffset, buflen-buffoffset, start); + if (buflen == sizeof(buf)) { + A2_LOG_DEBUG(fmt("Cache flush goff=%" PRId64 ", len=%lu", start, + static_cast(buflen))); + writeData(buf + buffoffset, buflen - buffoffset, start); memcpy(buf, d->data + d->offset + wlen, d->len - wlen); start += sizeof(buf) - buffoffset; buflen = d->len - wlen; @@ -138,7 +138,7 @@ void AbstractSingleDiskAdaptor::writeCache(const WrDiskCacheEntry* entry) } } } - writeData(buf+buffoffset, buflen-buffoffset, start); + writeData(buf + buffoffset, buflen - buffoffset, start); } bool AbstractSingleDiskAdaptor::fileExists() @@ -146,10 +146,7 @@ bool AbstractSingleDiskAdaptor::fileExists() return File(getFilePath()).exists(); } -int64_t AbstractSingleDiskAdaptor::size() -{ - return File(getFilePath()).size(); -} +int64_t AbstractSingleDiskAdaptor::size() { return File(getFilePath()).size(); } void AbstractSingleDiskAdaptor::truncate(int64_t length) { @@ -159,18 +156,18 @@ void AbstractSingleDiskAdaptor::truncate(int64_t length) std::unique_ptr AbstractSingleDiskAdaptor::fileAllocationIterator() { - switch(getFileAllocationMethod()) { + switch (getFileAllocationMethod()) { #ifdef HAVE_SOME_FALLOCATE - case(DiskAdaptor::FILE_ALLOC_FALLOC): - return make_unique - (diskWriter_.get(), size() ,totalLength_); + case (DiskAdaptor::FILE_ALLOC_FALLOC): + return make_unique(diskWriter_.get(), size(), + totalLength_); #endif // HAVE_SOME_FALLOCATE - case(DiskAdaptor::FILE_ALLOC_TRUNC): - return make_unique - (diskWriter_.get(), size(), totalLength_); + case (DiskAdaptor::FILE_ALLOC_TRUNC): + return make_unique(diskWriter_.get(), size(), + totalLength_); default: - return make_unique - (diskWriter_.get(), size(), totalLength_); + return make_unique(diskWriter_.get(), + size(), totalLength_); } } @@ -186,20 +183,17 @@ void AbstractSingleDiskAdaptor::disableReadOnly() readOnly_ = false; } -void AbstractSingleDiskAdaptor::enableMmap() -{ - diskWriter_->enableMmap(); -} +void AbstractSingleDiskAdaptor::enableMmap() { diskWriter_->enableMmap(); } void AbstractSingleDiskAdaptor::cutTrailingGarbage() { - if(File(getFilePath()).size() > totalLength_) { + if (File(getFilePath()).size() > totalLength_) { diskWriter_->truncate(totalLength_); } } -void AbstractSingleDiskAdaptor::setDiskWriter -(std::unique_ptr diskWriter) +void AbstractSingleDiskAdaptor::setDiskWriter( + std::unique_ptr diskWriter) { diskWriter_ = std::move(diskWriter); } diff --git a/src/AbstractSingleDiskAdaptor.h b/src/AbstractSingleDiskAdaptor.h index ef279df1..8d17686c 100644 --- a/src/AbstractSingleDiskAdaptor.h +++ b/src/AbstractSingleDiskAdaptor.h @@ -47,6 +47,7 @@ private: std::unique_ptr diskWriter_; int64_t totalLength_; bool readOnly_; + public: AbstractSingleDiskAdaptor(); @@ -63,12 +64,11 @@ public: virtual void writeData(const unsigned char* data, size_t len, int64_t offset) CXX11_OVERRIDE; - virtual ssize_t readData(unsigned char* data, size_t len, int64_t offset) - CXX11_OVERRIDE; + virtual ssize_t readData(unsigned char* data, size_t len, + int64_t offset) CXX11_OVERRIDE; virtual ssize_t readDataDropCache(unsigned char* data, size_t len, - int64_t offset) - CXX11_OVERRIDE; + int64_t offset) CXX11_OVERRIDE; virtual void writeCache(const WrDiskCacheEntry* entry) CXX11_OVERRIDE; @@ -78,8 +78,8 @@ public: virtual void truncate(int64_t length) CXX11_OVERRIDE; - virtual std::unique_ptr fileAllocationIterator() - CXX11_OVERRIDE; + virtual std::unique_ptr + fileAllocationIterator() CXX11_OVERRIDE; // Make sure that DiskWriter is set before calling this function. virtual void enableReadOnly() CXX11_OVERRIDE; @@ -104,10 +104,7 @@ public: void setTotalLength(int64_t totalLength); - int64_t getTotalLength() const - { - return totalLength_; - } + int64_t getTotalLength() const { return totalLength_; } }; } // namespace aria2 diff --git a/src/ActivePeerConnectionCommand.cc b/src/ActivePeerConnectionCommand.cc index 1e2b44da..7e566b42 100644 --- a/src/ActivePeerConnectionCommand.cc +++ b/src/ActivePeerConnectionCommand.cc @@ -56,16 +56,14 @@ namespace aria2 { -ActivePeerConnectionCommand::ActivePeerConnectionCommand -(cuid_t cuid, - RequestGroup* requestGroup, - DownloadEngine* e, - std::chrono::seconds interval) - : Command(cuid), - requestGroup_(requestGroup), - interval_(std::move(interval)), - e_(e), - numNewConnection_(5) +ActivePeerConnectionCommand::ActivePeerConnectionCommand( + cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, + std::chrono::seconds interval) + : Command(cuid), + requestGroup_(requestGroup), + interval_(std::move(interval)), + e_(e), + numNewConnection_(5) { requestGroup_->increaseNumCommand(); } @@ -75,50 +73,53 @@ ActivePeerConnectionCommand::~ActivePeerConnectionCommand() requestGroup_->decreaseNumCommand(); } -bool ActivePeerConnectionCommand::execute() { - if(btRuntime_->isHalt()) { +bool ActivePeerConnectionCommand::execute() +{ + if (btRuntime_->isHalt()) { return true; } - if(checkPoint_.difference(global::wallclock()) >= interval_) { + if (checkPoint_.difference(global::wallclock()) >= interval_) { checkPoint_ = global::wallclock(); NetStat& stat = requestGroup_->getDownloadContext()->getNetStat(); const int maxDownloadLimit = requestGroup_->getMaxDownloadSpeedLimit(); const int maxUploadLimit = requestGroup_->getMaxUploadSpeedLimit(); int thresholdSpeed; - if(!bittorrent::getTorrentAttrs - (requestGroup_->getDownloadContext())->metadata.empty()) { - thresholdSpeed = - requestGroup_->getOption()->getAsInt(PREF_BT_REQUEST_PEER_SPEED_LIMIT); - } else { + if (!bittorrent::getTorrentAttrs(requestGroup_->getDownloadContext()) + ->metadata.empty()) { + thresholdSpeed = requestGroup_->getOption()->getAsInt( + PREF_BT_REQUEST_PEER_SPEED_LIMIT); + } + else { thresholdSpeed = 0; } - if(maxDownloadLimit > 0) { + if (maxDownloadLimit > 0) { thresholdSpeed = std::min(maxDownloadLimit, thresholdSpeed); } - if(// for seeder state - (pieceStorage_->downloadFinished() && btRuntime_->lessThanMaxPeers() && - (maxUploadLimit == 0 || - stat.calculateUploadSpeed() < maxUploadLimit*0.8)) || - // for leecher state - (!pieceStorage_->downloadFinished() && - (stat.calculateDownloadSpeed() < thresholdSpeed || - btRuntime_->lessThanMinPeers()))) { + if ( // for seeder state + (pieceStorage_->downloadFinished() && btRuntime_->lessThanMaxPeers() && + (maxUploadLimit == 0 || + stat.calculateUploadSpeed() < maxUploadLimit * 0.8)) || + // for leecher state + (!pieceStorage_->downloadFinished() && + (stat.calculateDownloadSpeed() < thresholdSpeed || + btRuntime_->lessThanMinPeers()))) { int numConnection = 0; - if(pieceStorage_->downloadFinished()) { - if(btRuntime_->getMaxPeers() > btRuntime_->getConnections()) { + if (pieceStorage_->downloadFinished()) { + if (btRuntime_->getMaxPeers() > btRuntime_->getConnections()) { numConnection = - std::min(numNewConnection_, - btRuntime_->getMaxPeers()-btRuntime_->getConnections()); + std::min(numNewConnection_, btRuntime_->getMaxPeers() - + btRuntime_->getConnections()); } - } else { + } + else { numConnection = numNewConnection_; } makeNewConnections(numConnection); - if(btRuntime_->getConnections() == 0 && - !pieceStorage_->downloadFinished()) { + if (btRuntime_->getConnections() == 0 && + !pieceStorage_->downloadFinished()) { btAnnounce_->overrideMinInterval(BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL); } } @@ -129,43 +130,43 @@ bool ActivePeerConnectionCommand::execute() { void ActivePeerConnectionCommand::makeNewConnections(int num) { - for(; num && peerStorage_->isPeerAvailable(); --num) { + for (; num && peerStorage_->isPeerAvailable(); --num) { cuid_t ncuid = e_->newCUID(); std::shared_ptr peer = peerStorage_->checkoutPeer(ncuid); // sanity check - if(!peer) { + if (!peer) { break; } - auto command = make_unique - (ncuid, requestGroup_, peer, e_, btRuntime_); + auto command = make_unique( + ncuid, requestGroup_, peer, e_, btRuntime_); command->setPeerStorage(peerStorage_); command->setPieceStorage(pieceStorage_); e_->addCommand(std::move(command)); - A2_LOG_INFO(fmt(MSG_CONNECTING_TO_PEER, getCuid(), - peer->getIPAddress().c_str())); + A2_LOG_INFO( + fmt(MSG_CONNECTING_TO_PEER, getCuid(), peer->getIPAddress().c_str())); } } -void ActivePeerConnectionCommand::setBtRuntime -(const std::shared_ptr& btRuntime) +void ActivePeerConnectionCommand::setBtRuntime( + const std::shared_ptr& btRuntime) { btRuntime_ = btRuntime; } -void ActivePeerConnectionCommand::setPieceStorage -(const std::shared_ptr& pieceStorage) +void ActivePeerConnectionCommand::setPieceStorage( + const std::shared_ptr& pieceStorage) { pieceStorage_ = pieceStorage; } -void ActivePeerConnectionCommand::setPeerStorage -(const std::shared_ptr& peerStorage) +void ActivePeerConnectionCommand::setPeerStorage( + const std::shared_ptr& peerStorage) { peerStorage_ = peerStorage; } -void ActivePeerConnectionCommand::setBtAnnounce -(const std::shared_ptr& btAnnounce) +void ActivePeerConnectionCommand::setBtAnnounce( + const std::shared_ptr& btAnnounce) { btAnnounce_ = btAnnounce; } diff --git a/src/ActivePeerConnectionCommand.h b/src/ActivePeerConnectionCommand.h index fc6203f8..d92dc260 100644 --- a/src/ActivePeerConnectionCommand.h +++ b/src/ActivePeerConnectionCommand.h @@ -64,10 +64,8 @@ private: Timer checkPoint_; int numNewConnection_; // the number of the connection to establish. public: - ActivePeerConnectionCommand(cuid_t cuid, - RequestGroup* requestGroup, - DownloadEngine* e, - std::chrono::seconds interval); + ActivePeerConnectionCommand(cuid_t cuid, RequestGroup* requestGroup, + DownloadEngine* e, std::chrono::seconds interval); virtual ~ActivePeerConnectionCommand(); diff --git a/src/AdaptiveFileAllocationIterator.cc b/src/AdaptiveFileAllocationIterator.cc index f86517a8..05093b68 100644 --- a/src/AdaptiveFileAllocationIterator.cc +++ b/src/AdaptiveFileAllocationIterator.cc @@ -40,68 +40,71 @@ #include "Logger.h" #include "a2functional.h" #ifdef HAVE_FALLOCATE -# include "FallocFileAllocationIterator.h" +#include "FallocFileAllocationIterator.h" #endif // HAVE_FALLOCATE namespace aria2 { -AdaptiveFileAllocationIterator::AdaptiveFileAllocationIterator -(BinaryStream* stream, int64_t offset, int64_t totalLength) - : stream_(stream), - offset_(offset), - totalLength_(totalLength) -{} +AdaptiveFileAllocationIterator::AdaptiveFileAllocationIterator( + BinaryStream* stream, int64_t offset, int64_t totalLength) + : stream_(stream), offset_(offset), totalLength_(totalLength) +{ +} AdaptiveFileAllocationIterator::~AdaptiveFileAllocationIterator() {} void AdaptiveFileAllocationIterator::allocateChunk() { - if(!allocator_) { + if (!allocator_) { #ifdef HAVE_FALLOCATE try { A2_LOG_DEBUG("Testing file system supports fallocate."); - if(offset_ < totalLength_) { + if (offset_ < totalLength_) { int64_t len = std::min(totalLength_ - offset_, static_cast(4_k)); stream_->allocate(offset_, len, false); offset_ += len; } A2_LOG_DEBUG("File system supports fallocate."); - allocator_ = make_unique - (stream_, offset_, totalLength_); - } catch(RecoverableException& e) { + allocator_ = make_unique(stream_, offset_, + totalLength_); + } + catch (RecoverableException& e) { A2_LOG_DEBUG("File system does not support fallocate."); - auto salloc = make_unique - (stream_, offset_, totalLength_); + auto salloc = make_unique(stream_, offset_, + totalLength_); salloc->init(); allocator_ = std::move(salloc); } -#else // !HAVE_FALLOCATE - auto salloc = make_unique - (stream_, offset_, totalLength_); +#else // !HAVE_FALLOCATE + auto salloc = make_unique(stream_, offset_, + totalLength_); salloc->init(); allocator_ = std::move(salloc); #endif // !HAVE_FALLOCATE allocator_->allocateChunk(); - } else { + } + else { allocator_->allocateChunk(); } } bool AdaptiveFileAllocationIterator::finished() { - if(!allocator_) { + if (!allocator_) { return offset_ == totalLength_; - } else { + } + else { return allocator_->finished(); } } int64_t AdaptiveFileAllocationIterator::getCurrentLength() { - if(!allocator_) { + if (!allocator_) { return offset_; - } else { + } + else { return allocator_->getCurrentLength(); } } diff --git a/src/AdaptiveFileAllocationIterator.h b/src/AdaptiveFileAllocationIterator.h index 6d0c804d..cbeee594 100644 --- a/src/AdaptiveFileAllocationIterator.h +++ b/src/AdaptiveFileAllocationIterator.h @@ -43,8 +43,7 @@ namespace aria2 { class BinaryStream; -class AdaptiveFileAllocationIterator:public FileAllocationIterator -{ +class AdaptiveFileAllocationIterator : public FileAllocationIterator { private: std::unique_ptr allocator_; @@ -53,9 +52,10 @@ private: int64_t offset_; int64_t totalLength_; + public: - AdaptiveFileAllocationIterator - (BinaryStream* stream, int64_t offset, int64_t totalLength); + AdaptiveFileAllocationIterator(BinaryStream* stream, int64_t offset, + int64_t totalLength); virtual ~AdaptiveFileAllocationIterator(); diff --git a/src/AdaptiveURISelector.cc b/src/AdaptiveURISelector.cc index b820b803..4a9f9b6b 100644 --- a/src/AdaptiveURISelector.cc +++ b/src/AdaptiveURISelector.cc @@ -65,22 +65,21 @@ namespace aria2 { * be tested again. Otherwise, it doesn't return anymore mirrors. */ -AdaptiveURISelector::AdaptiveURISelector -(std::shared_ptr serverStatMan, RequestGroup* requestGroup) - : serverStatMan_(std::move(serverStatMan)), - requestGroup_(requestGroup) +AdaptiveURISelector::AdaptiveURISelector( + std::shared_ptr serverStatMan, RequestGroup* requestGroup) + : serverStatMan_(std::move(serverStatMan)), requestGroup_(requestGroup) { resetCounters(); } AdaptiveURISelector::~AdaptiveURISelector() {} -std::string AdaptiveURISelector::select -(FileEntry* fileEntry, - const std::vector >& usedHosts) +std::string AdaptiveURISelector::select( + FileEntry* fileEntry, + const std::vector>& usedHosts) { - A2_LOG_DEBUG(fmt("AdaptiveURISelector: called %d", - requestGroup_->getNumConnection())); + A2_LOG_DEBUG( + fmt("AdaptiveURISelector: called %d", requestGroup_->getNumConnection())); std::deque& uris = fileEntry->getRemainingUris(); if (uris.empty() && requestGroup_->getNumConnection() <= 1) { // here we know the download will fail, trying to find previously @@ -90,7 +89,7 @@ std::string AdaptiveURISelector::select std::string selected = selectOne(uris); - if(selected != A2STR::NIL) { + if (selected != A2STR::NIL) { uris.erase(std::find(std::begin(uris), std::end(uris), selected)); } return selected; @@ -102,8 +101,9 @@ constexpr auto MAX_TIMEOUT = 60_s; void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry) { - if (requestGroup_->getTimeout()*2 >= MAX_TIMEOUT) return; - requestGroup_->setTimeout(requestGroup_->getTimeout()*2); + if (requestGroup_->getTimeout() * 2 >= MAX_TIMEOUT) + return; + requestGroup_->setTimeout(requestGroup_->getTimeout() * 2); std::deque& uris = fileEntry->getRemainingUris(); // looking for retries @@ -112,7 +112,7 @@ void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry) std::transform(std::begin(timeouts), std::end(timeouts), std::back_inserter(uris), std::mem_fn(&URIResult::getURI)); - if(A2_LOG_DEBUG_ENABLED) { + if (A2_LOG_DEBUG_ENABLED) { for (const auto& uri : uris) { A2_LOG_DEBUG( fmt("AdaptiveURISelector: will retry server with increased" @@ -126,25 +126,27 @@ void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry) std::string AdaptiveURISelector::selectOne(const std::deque& uris) { - if(uris.empty()) { + if (uris.empty()) { return A2STR::NIL; - } else { + } + else { const size_t numPieces = - requestGroup_->getDownloadContext()->getNumPieces(); + requestGroup_->getDownloadContext()->getNumPieces(); - bool reservedContext = numPieces > 0 && - static_cast(nbConnections_) > std::min - (numPieces, - static_cast(requestGroup_->getNumConcurrentCommand())); + bool reservedContext = + numPieces > 0 && + static_cast(nbConnections_) > + std::min(numPieces, static_cast( + requestGroup_->getNumConcurrentCommand())); bool selectBest = numPieces == 0 || reservedContext; - if(numPieces > 0) + if (numPieces > 0) ++nbConnections_; /* At least, 3 mirrors must be tested */ - if(getNbTestedServers(uris) < 3) { + if (getNbTestedServers(uris) < 3) { std::string notTested = getFirstNotTestedUri(uris); - if(notTested != A2STR::NIL) { + if (notTested != A2STR::NIL) { A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the first non tested" " mirror: %s", notTested.c_str())); @@ -153,24 +155,26 @@ std::string AdaptiveURISelector::selectOne(const std::deque& uris) } } - if(!selectBest && nbConnections_ > 1 && nbServerToEvaluate_ > 0) { + if (!selectBest && nbConnections_ > 1 && nbServerToEvaluate_ > 0) { nbServerToEvaluate_--; std::string notTested = getFirstNotTestedUri(uris); - if(notTested != A2STR::NIL) { + if (notTested != A2STR::NIL) { /* Here we return the first untested mirror */ A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing non tested mirror %s" " for connection #%d", notTested.c_str(), nbConnections_)); return notTested; - } else { + } + else { /* Here we return a mirror which need to be tested again */ std::string toReTest = getFirstToTestUri(uris); - if(toReTest != A2STR::NIL) { + if (toReTest != A2STR::NIL) { A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing mirror %s which has" " not been tested recently for connection #%d", toReTest.c_str(), nbConnections_)); return toReTest; - } else { + } + else { return getBestMirror(uris); } } @@ -181,28 +185,26 @@ std::string AdaptiveURISelector::selectOne(const std::deque& uris) } } -std::string AdaptiveURISelector::getBestMirror -(const std::deque& uris) const +std::string +AdaptiveURISelector::getBestMirror(const std::deque& uris) const { /* Here we return one of the bests mirrors */ int max = getMaxDownloadSpeed(uris); - int min = max-(int)(max*0.25); + int min = max - (int)(max * 0.25); std::deque bests = getUrisBySpeed(uris, min); if (bests.size() < 2) { std::string uri = getMaxDownloadSpeedUri(uris); A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing the best mirror :" " %.2fKB/s %s (other mirrors are at least 25%% slower)", - (float) max/1024, - uri.c_str())); + (float)max / 1024, uri.c_str())); return uri; - } else { + } + else { std::string uri = selectRandomUri(bests); A2_LOG_DEBUG(fmt("AdaptiveURISelector: choosing randomly one of the best" " mirrors (range [%.2fKB/s, %.2fKB/s]): %s", - (float) min/1024, - (float) max/1024, - uri.c_str())); + (float)min / 1024, (float)max / 1024, uri.c_str())); return uri; } } @@ -210,36 +212,32 @@ std::string AdaptiveURISelector::getBestMirror void AdaptiveURISelector::resetCounters() { nbConnections_ = 1; - nbServerToEvaluate_ = - requestGroup_->getOption()->getAsInt(PREF_SPLIT) - 1; + nbServerToEvaluate_ = requestGroup_->getOption()->getAsInt(PREF_SPLIT) - 1; } -void AdaptiveURISelector::tuneDownloadCommand -(const std::deque& uris, DownloadCommand* command) +void AdaptiveURISelector::tuneDownloadCommand( + const std::deque& uris, DownloadCommand* command) { adjustLowestSpeedLimit(uris, command); } -void AdaptiveURISelector::adjustLowestSpeedLimit -(const std::deque& uris, DownloadCommand* command) const +void AdaptiveURISelector::adjustLowestSpeedLimit( + const std::deque& uris, DownloadCommand* command) const { - int lowest = - requestGroup_->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT); + int lowest = requestGroup_->getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT); if (lowest > 0) { int low_lowest = 4_k; int max = getMaxDownloadSpeed(uris); if (max > 0 && lowest > max / 4) { A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since known max speed is" " too near (new:%d was:%d max:%d)"), - max / 4, - lowest, - max)); + max / 4, lowest, max)); command->setLowestDownloadSpeedLimit(max / 4); - } else if (max == 0 && lowest > low_lowest) { + } + else if (max == 0 && lowest > low_lowest) { A2_LOG_NOTICE(fmt(_("Lowering lowest-speed-limit since we have no clue" " about available speed (now:%d was:%d)"), - low_lowest, - lowest)); + low_lowest, lowest)); command->setLowestDownloadSpeedLimit(low_lowest); } } @@ -253,30 +251,30 @@ int getUriMaxSpeed(std::shared_ptr ss) } } // namespace -int AdaptiveURISelector::getMaxDownloadSpeed -(const std::deque& uris) const +int AdaptiveURISelector::getMaxDownloadSpeed( + const std::deque& uris) const { std::string uri = getMaxDownloadSpeedUri(uris); - if(uri == A2STR::NIL) + if (uri == A2STR::NIL) return 0; return getUriMaxSpeed(getServerStats(uri)); } -std::string AdaptiveURISelector::getMaxDownloadSpeedUri -(const std::deque& uris) const +std::string AdaptiveURISelector::getMaxDownloadSpeedUri( + const std::deque& uris) const { int max = -1; std::string uri = A2STR::NIL; - for(auto& u : uris) { + for (auto& u : uris) { std::shared_ptr ss = getServerStats(u); - if(!ss) + if (!ss) continue; - if((int)ss->getSingleConnectionAvgSpeed() > max) { + if ((int)ss->getSingleConnectionAvgSpeed() > max) { max = ss->getSingleConnectionAvgSpeed(); uri = u; } - if((int)ss->getMultiConnectionAvgSpeed() > max) { + if ((int)ss->getMultiConnectionAvgSpeed() > max) { max = ss->getMultiConnectionAvgSpeed(); uri = u; } @@ -284,84 +282,86 @@ std::string AdaptiveURISelector::getMaxDownloadSpeedUri return uri; } -std::deque AdaptiveURISelector::getUrisBySpeed -(const std::deque& uris, int min) const +std::deque +AdaptiveURISelector::getUrisBySpeed(const std::deque& uris, + int min) const { std::deque bests; - for(auto& uri : uris) { + for (auto& uri : uris) { std::shared_ptr ss = getServerStats(uri); - if(!ss) + if (!ss) continue; - if(ss->getSingleConnectionAvgSpeed() > min || - ss->getMultiConnectionAvgSpeed() > min) { + if (ss->getSingleConnectionAvgSpeed() > min || + ss->getMultiConnectionAvgSpeed() > min) { bests.push_back(uri); } } return bests; } -std::string AdaptiveURISelector::selectRandomUri -(const std::deque& uris) const +std::string +AdaptiveURISelector::selectRandomUri(const std::deque& uris) const { int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size()); auto i = std::begin(uris); - i = i+pos; + i = i + pos; return *i; } -std::string AdaptiveURISelector::getFirstNotTestedUri -(const std::deque& uris) const +std::string AdaptiveURISelector::getFirstNotTestedUri( + const std::deque& uris) const { for (const auto& i : uris) { std::shared_ptr ss = getServerStats(i); - if(!ss) + if (!ss) return i; } return A2STR::NIL; } -std::string AdaptiveURISelector::getFirstToTestUri -(const std::deque& uris) const +std::string AdaptiveURISelector::getFirstToTestUri( + const std::deque& uris) const { int counter; int power; for (const auto& u : uris) { std::shared_ptr ss = getServerStats(u); - if(!ss) + if (!ss) continue; counter = ss->getCounter(); - if(counter > 8) + if (counter > 8) continue; power = (int)pow(2.0, (float)counter); /* We test the mirror another time if it has not been * tested since 2^counter days */ - if(ss->getLastUpdated().difference() > std::chrono::hours(power * 24)) { + if (ss->getLastUpdated().difference() > std::chrono::hours(power * 24)) { return u; } } return A2STR::NIL; } -std::shared_ptr AdaptiveURISelector::getServerStats -(const std::string& uri) const +std::shared_ptr +AdaptiveURISelector::getServerStats(const std::string& uri) const { uri_split_result us; - if(uri_split(&us, uri.c_str()) == 0) { + if (uri_split(&us, uri.c_str()) == 0) { std::string host = uri::getFieldString(us, USR_HOST, uri.c_str()); std::string protocol = uri::getFieldString(us, USR_SCHEME, uri.c_str()); return serverStatMan_->find(host, protocol); - } else { + } + else { return nullptr; } } -int AdaptiveURISelector::getNbTestedServers -(const std::deque& uris) const +int AdaptiveURISelector::getNbTestedServers( + const std::deque& uris) const { int counter = 0; - for(const auto& u : uris) { + for (const auto& u : uris) { std::shared_ptr ss = getServerStats(u); - if(!ss) + if (!ss) ++counter; } return uris.size() - counter; diff --git a/src/AdaptiveURISelector.h b/src/AdaptiveURISelector.h index 28a7fa0b..88122bde 100644 --- a/src/AdaptiveURISelector.h +++ b/src/AdaptiveURISelector.h @@ -46,7 +46,7 @@ class ServerStatMan; class RequestGroup; class ServerStat; -class AdaptiveURISelector:public URISelector { +class AdaptiveURISelector : public URISelector { private: std::shared_ptr serverStatMan_; // No need to delete requestGroup_ @@ -69,20 +69,20 @@ private: std::shared_ptr getServerStats(const std::string& uri) const; int getNbTestedServers(const std::deque& uris) const; std::string getBestMirror(const std::deque& uris) const; + public: AdaptiveURISelector(std::shared_ptr serverStatMan, RequestGroup* requestGroup); virtual ~AdaptiveURISelector(); - virtual std::string select - (FileEntry* fileEntry, - const std::vector >& usedHosts) - CXX11_OVERRIDE; + virtual std::string + select(FileEntry* fileEntry, + const std::vector>& usedHosts) + CXX11_OVERRIDE; virtual void tuneDownloadCommand(const std::deque& uris, - DownloadCommand* command) - CXX11_OVERRIDE; + DownloadCommand* command) CXX11_OVERRIDE; virtual void resetCounters() CXX11_OVERRIDE; }; diff --git a/src/Adler32MessageDigestImpl.cc b/src/Adler32MessageDigestImpl.cc index 96ce07ca..f356999a 100644 --- a/src/Adler32MessageDigestImpl.cc +++ b/src/Adler32MessageDigestImpl.cc @@ -43,23 +43,18 @@ namespace aria2 { Adler32MessageDigestImpl::Adler32MessageDigestImpl() - : adler_(adler32(0, Z_NULL, 0)) -{} - -size_t Adler32MessageDigestImpl::getDigestLength() const + : adler_(adler32(0, Z_NULL, 0)) { - return length(); } -void Adler32MessageDigestImpl::reset() -{ - adler_ = adler32(0, Z_NULL, 0); -} +size_t Adler32MessageDigestImpl::getDigestLength() const { return length(); } + +void Adler32MessageDigestImpl::reset() { adler_ = adler32(0, Z_NULL, 0); } void Adler32MessageDigestImpl::update(const void* data, size_t length) { - adler_ = adler32(adler_, reinterpret_cast(data), - length); + adler_ = + adler32(adler_, reinterpret_cast(data), length); } void Adler32MessageDigestImpl::digest(unsigned char* md) @@ -68,9 +63,6 @@ void Adler32MessageDigestImpl::digest(unsigned char* md) memcpy(md, &adler, getDigestLength()); } -size_t Adler32MessageDigestImpl::length() -{ - return 4; -} +size_t Adler32MessageDigestImpl::length() { return 4; } } // namespace aria2 diff --git a/src/Adler32MessageDigestImpl.h b/src/Adler32MessageDigestImpl.h index 1fb91785..048edbaf 100644 --- a/src/Adler32MessageDigestImpl.h +++ b/src/Adler32MessageDigestImpl.h @@ -41,8 +41,11 @@ namespace aria2 { #ifdef HAVE_ZLIB -#define ADLER32_MESSAGE_DIGEST \ - { "adler32", make_hi() }, +#define ADLER32_MESSAGE_DIGEST \ + { \ + "adler32", make_hi() \ + } \ + , class Adler32MessageDigestImpl : public MessageDigestImpl { public: @@ -52,6 +55,7 @@ public: virtual void update(const void* data, size_t length) CXX11_OVERRIDE; virtual void digest(unsigned char* md) CXX11_OVERRIDE; static size_t length(); + private: unsigned long adler_; }; diff --git a/src/AnnounceList.cc b/src/AnnounceList.cc index b65106d3..234a33c8 100644 --- a/src/AnnounceList.cc +++ b/src/AnnounceList.cc @@ -42,64 +42,71 @@ namespace aria2 { -AnnounceList::AnnounceList():currentTrackerInitialized_(false) {} +AnnounceList::AnnounceList() : currentTrackerInitialized_(false) {} -AnnounceList::AnnounceList -(const std::vector>& announceList): - currentTrackerInitialized_(false) { +AnnounceList::AnnounceList( + const std::vector>& announceList) + : currentTrackerInitialized_(false) +{ reconfigure(announceList); } -AnnounceList::AnnounceList -(const std::deque>& announceTiers): - tiers_(announceTiers), currentTrackerInitialized_(false) { +AnnounceList::AnnounceList( + const std::deque>& announceTiers) + : tiers_(announceTiers), currentTrackerInitialized_(false) +{ resetIterator(); } AnnounceList::~AnnounceList() {} -void AnnounceList::reconfigure -(const std::vector>& announceList) +void AnnounceList::reconfigure( + const std::vector>& announceList) { - for (const auto& vec: announceList) { - if(vec.empty()) { + for (const auto& vec : announceList) { + if (vec.empty()) { continue; } std::deque uris(std::begin(vec), std::end(vec)); - auto tier = - std::make_shared(std::move(uris)); + auto tier = std::make_shared(std::move(uris)); tiers_.push_back(std::move(tier)); } resetIterator(); } -void AnnounceList::reconfigure(const std::string& url) { - std::deque urls{ url }; +void AnnounceList::reconfigure(const std::string& url) +{ + std::deque urls{url}; tiers_.push_back(std::make_shared(std::move(urls))); resetIterator(); } -void AnnounceList::resetIterator() { +void AnnounceList::resetIterator() +{ currentTier_ = std::begin(tiers_); - if(currentTier_ != std::end(tiers_) && (*currentTier_)->urls.size()) { + if (currentTier_ != std::end(tiers_) && (*currentTier_)->urls.size()) { currentTracker_ = std::begin((*currentTier_)->urls); currentTrackerInitialized_ = true; - } else { + } + else { currentTrackerInitialized_ = false; } } -std::string AnnounceList::getAnnounce() const { - if(currentTrackerInitialized_) { +std::string AnnounceList::getAnnounce() const +{ + if (currentTrackerInitialized_) { return *currentTracker_; - } else { + } + else { return A2STR::NIL; } } -void AnnounceList::announceSuccess() { - if(currentTrackerInitialized_) { +void AnnounceList::announceSuccess() +{ + if (currentTrackerInitialized_) { (*currentTier_)->nextEvent(); auto url = *currentTracker_; (*currentTier_)->urls.erase(currentTracker_); @@ -109,39 +116,45 @@ void AnnounceList::announceSuccess() { } } -void AnnounceList::announceFailure() { - if(currentTrackerInitialized_) { +void AnnounceList::announceFailure() +{ + if (currentTrackerInitialized_) { ++currentTracker_; - if(currentTracker_ == std::end((*currentTier_)->urls)) { + if (currentTracker_ == std::end((*currentTier_)->urls)) { // force next event (*currentTier_)->nextEventIfAfterStarted(); ++currentTier_; - if(currentTier_ == std::end(tiers_)) { + if (currentTier_ == std::end(tiers_)) { currentTrackerInitialized_ = false; - } else { + } + else { currentTracker_ = std::begin((*currentTier_)->urls); } } } } -AnnounceTier::AnnounceEvent AnnounceList::getEvent() const { - if(currentTrackerInitialized_) { +AnnounceTier::AnnounceEvent AnnounceList::getEvent() const +{ + if (currentTrackerInitialized_) { return (*currentTier_)->event; - } else { + } + else { return AnnounceTier::STARTED; } } -void AnnounceList::setEvent(AnnounceTier::AnnounceEvent event) { - if(currentTrackerInitialized_) { +void AnnounceList::setEvent(AnnounceTier::AnnounceEvent event) +{ + if (currentTrackerInitialized_) { (*currentTier_)->event = event; } } -const char* AnnounceList::getEventString() const { - if(currentTrackerInitialized_) { - switch((*currentTier_)->event) { +const char* AnnounceList::getEventString() const +{ + if (currentTrackerInitialized_) { + switch ((*currentTier_)->event) { case AnnounceTier::STARTED: case AnnounceTier::STARTED_AFTER_COMPLETION: return "started"; @@ -152,7 +165,8 @@ const char* AnnounceList::getEventString() const { default: return ""; } - } else { + } + else { return ""; } } @@ -160,8 +174,9 @@ const char* AnnounceList::getEventString() const { namespace { class FindStoppedAllowedTier { public: - bool operator()(const std::shared_ptr& tier) const { - switch(tier->event) { + bool operator()(const std::shared_ptr& tier) const + { + switch (tier->event) { case AnnounceTier::DOWNLOADING: case AnnounceTier::STOPPED: case AnnounceTier::COMPLETED: @@ -177,8 +192,9 @@ public: namespace { class FindCompletedAllowedTier { public: - bool operator()(const std::shared_ptr& tier) const { - switch(tier->event) { + bool operator()(const std::shared_ptr& tier) const + { + switch (tier->event) { case AnnounceTier::DOWNLOADING: case AnnounceTier::COMPLETED: return true; @@ -189,38 +205,44 @@ public: }; } // namespace -size_t AnnounceList::countStoppedAllowedTier() const { +size_t AnnounceList::countStoppedAllowedTier() const +{ return count_if(std::begin(tiers_), std::end(tiers_), FindStoppedAllowedTier()); } -size_t AnnounceList::countCompletedAllowedTier() const { +size_t AnnounceList::countCompletedAllowedTier() const +{ return count_if(std::begin(tiers_), std::end(tiers_), FindCompletedAllowedTier()); } -void AnnounceList::setCurrentTier -(std::deque>::iterator itr) { - if(itr != std::end(tiers_)) { +void AnnounceList::setCurrentTier( + std::deque>::iterator itr) +{ + if (itr != std::end(tiers_)) { currentTier_ = std::move(itr); currentTracker_ = std::begin((*currentTier_)->urls); } } -void AnnounceList::moveToStoppedAllowedTier() { +void AnnounceList::moveToStoppedAllowedTier() +{ auto itr = find_wrap_if(std::begin(tiers_), std::end(tiers_), currentTier_, FindStoppedAllowedTier()); setCurrentTier(std::move(itr)); } -void AnnounceList::moveToCompletedAllowedTier() { +void AnnounceList::moveToCompletedAllowedTier() +{ auto itr = find_wrap_if(std::begin(tiers_), std::end(tiers_), currentTier_, FindCompletedAllowedTier()); setCurrentTier(std::move(itr)); } -void AnnounceList::shuffle() { - for (const auto& tier: tiers_) { +void AnnounceList::shuffle() +{ + for (const auto& tier : tiers_) { auto& urls = tier->urls; std::shuffle(std::begin(urls), std::end(urls), *SimpleRandomizer::getInstance()); @@ -232,14 +254,11 @@ bool AnnounceList::allTiersFailed() const return currentTier_ == std::end(tiers_); } -void AnnounceList::resetTier() -{ - resetIterator(); -} +void AnnounceList::resetTier() { resetIterator(); } bool AnnounceList::currentTierAcceptsStoppedEvent() const { - if(currentTrackerInitialized_) { + if (currentTrackerInitialized_) { return FindStoppedAllowedTier()(*currentTier_); } @@ -248,16 +267,13 @@ bool AnnounceList::currentTierAcceptsStoppedEvent() const bool AnnounceList::currentTierAcceptsCompletedEvent() const { - if(currentTrackerInitialized_) { + if (currentTrackerInitialized_) { return FindCompletedAllowedTier()(*currentTier_); } return false; } -size_t AnnounceList::countTier() const -{ - return tiers_.size(); -} +size_t AnnounceList::countTier() const { return tiers_.size(); } } // namespace aria2 diff --git a/src/AnnounceList.h b/src/AnnounceList.h index c5d1da35..dd4e8f7e 100644 --- a/src/AnnounceList.h +++ b/src/AnnounceList.h @@ -56,8 +56,8 @@ private: bool currentTrackerInitialized_; void resetIterator(); - void setCurrentTier - (std::deque>::iterator itr); + void setCurrentTier(std::deque>::iterator itr); + public: AnnounceList(); AnnounceList(const std::vector>& announceList); diff --git a/src/AnnounceTier.cc b/src/AnnounceTier.cc index 577994e4..7472b36e 100644 --- a/src/AnnounceTier.cc +++ b/src/AnnounceTier.cc @@ -37,14 +37,15 @@ namespace aria2 { AnnounceTier::AnnounceTier(std::deque urls) - : event(STARTED), urls(std::move(urls)) -{} + : event(STARTED), urls(std::move(urls)) +{ +} AnnounceTier::~AnnounceTier() {} void AnnounceTier::nextEvent() { - switch(event) { + switch (event) { case STARTED: event = DOWNLOADING; break; @@ -64,7 +65,7 @@ void AnnounceTier::nextEvent() void AnnounceTier::nextEventIfAfterStarted() { - switch(event) { + switch (event) { case STOPPED: event = HALTED; break; diff --git a/src/AnonDiskWriterFactory.h b/src/AnonDiskWriterFactory.h index 573d203e..25d2dc26 100644 --- a/src/AnonDiskWriterFactory.h +++ b/src/AnonDiskWriterFactory.h @@ -42,14 +42,14 @@ namespace aria2 { // DiskwriterFactory class template to create DiskWriter derived // object, ignoring filename. -template -class AnonDiskWriterFactory:public DiskWriterFactory { +template +class AnonDiskWriterFactory : public DiskWriterFactory { public: AnonDiskWriterFactory() {} virtual ~AnonDiskWriterFactory() {} - virtual std::unique_ptr newDiskWriter(const std::string& filename) - CXX11_OVERRIDE + virtual std::unique_ptr + newDiskWriter(const std::string& filename) CXX11_OVERRIDE { return make_unique(); } diff --git a/src/ApiCallbackDownloadEventListener.cc b/src/ApiCallbackDownloadEventListener.cc index 3a5e3742..9145dd92 100644 --- a/src/ApiCallbackDownloadEventListener.cc +++ b/src/ApiCallbackDownloadEventListener.cc @@ -37,19 +37,16 @@ namespace aria2 { -ApiCallbackDownloadEventListener::ApiCallbackDownloadEventListener -(Session* session, - DownloadEventCallback callback, - void* userData) - : session_(session), - callback_(callback), - userData_(userData) -{} +ApiCallbackDownloadEventListener::ApiCallbackDownloadEventListener( + Session* session, DownloadEventCallback callback, void* userData) + : session_(session), callback_(callback), userData_(userData) +{ +} ApiCallbackDownloadEventListener::~ApiCallbackDownloadEventListener() {} -void ApiCallbackDownloadEventListener::onEvent -(DownloadEvent event, const RequestGroup* group) +void ApiCallbackDownloadEventListener::onEvent(DownloadEvent event, + const RequestGroup* group) { callback_(session_, event, group->getGID(), userData_); } diff --git a/src/ApiCallbackDownloadEventListener.h b/src/ApiCallbackDownloadEventListener.h index 81cae4ff..c7776e1d 100644 --- a/src/ApiCallbackDownloadEventListener.h +++ b/src/ApiCallbackDownloadEventListener.h @@ -45,8 +45,9 @@ public: DownloadEventCallback callback, void* userData); virtual ~ApiCallbackDownloadEventListener(); - virtual void onEvent(DownloadEvent event, const RequestGroup* group) - CXX11_OVERRIDE; + virtual void onEvent(DownloadEvent event, + const RequestGroup* group) CXX11_OVERRIDE; + private: Session* session_; DownloadEventCallback callback_; diff --git a/src/AppleMessageDigestImpl.cc b/src/AppleMessageDigestImpl.cc index 59e4c4dd..4204cc5f 100644 --- a/src/AppleMessageDigestImpl.cc +++ b/src/AppleMessageDigestImpl.cc @@ -42,77 +42,50 @@ namespace aria2 { namespace { -template +template class MessageDigestBase : public MessageDigestImpl { public: MessageDigestBase() { reset(); } virtual ~MessageDigestBase() {} - static size_t length() { - return dlen; - } - virtual size_t getDigestLength() const CXX11_OVERRIDE { - return dlen; - } - virtual void reset() CXX11_OVERRIDE { - init_fn(&ctx_); - } - virtual void update(const void* data, size_t length) CXX11_OVERRIDE { + static size_t length() { return dlen; } + virtual size_t getDigestLength() const CXX11_OVERRIDE { return dlen; } + virtual void reset() CXX11_OVERRIDE { init_fn(&ctx_); } + virtual void update(const void* data, size_t length) CXX11_OVERRIDE + { auto bytes = reinterpret_cast(data); while (length) { - CC_LONG l = std::min(length, (size_t)std::numeric_limits::max()); + CC_LONG l = + std::min(length, (size_t)std::numeric_limits::max()); update_fn(&ctx_, bytes, l); length -= l; bytes += l; } } - virtual void digest(unsigned char* md) CXX11_OVERRIDE { - final_fn(md, &ctx_); - } + virtual void digest(unsigned char* md) CXX11_OVERRIDE { final_fn(md, &ctx_); } + private: ctx_t ctx_; }; -typedef MessageDigestBase -MessageDigestMD5; -typedef MessageDigestBase -MessageDigestSHA1; -typedef MessageDigestBase -MessageDigestSHA224; -typedef MessageDigestBase -MessageDigestSHA256; -typedef MessageDigestBase -MessageDigestSHA384; -typedef MessageDigestBase -MessageDigestSHA512; +typedef MessageDigestBase MessageDigestMD5; +typedef MessageDigestBase MessageDigestSHA1; +typedef MessageDigestBase MessageDigestSHA224; +typedef MessageDigestBase MessageDigestSHA256; +typedef MessageDigestBase MessageDigestSHA384; +typedef MessageDigestBase MessageDigestSHA512; } // namespace @@ -122,13 +95,12 @@ std::unique_ptr MessageDigestImpl::sha1() } MessageDigestImpl::hashes_t MessageDigestImpl::hashes = { - { "sha-1", make_hi() }, - { "sha-224", make_hi() }, - { "sha-256", make_hi() }, - { "sha-384", make_hi() }, - { "sha-512", make_hi() }, - { "md5", make_hi() }, - ADLER32_MESSAGE_DIGEST -}; + {"sha-1", make_hi()}, + {"sha-224", make_hi()}, + {"sha-256", make_hi()}, + {"sha-384", make_hi()}, + {"sha-512", make_hi()}, + {"md5", make_hi()}, + ADLER32_MESSAGE_DIGEST}; } // namespace aria2 diff --git a/src/AppleTLSContext.cc b/src/AppleTLSContext.cc index e53bd87f..808ad570 100644 --- a/src/AppleTLSContext.cc +++ b/src/AppleTLSContext.cc @@ -56,17 +56,11 @@ using namespace aria2; #if defined(__MAC_10_6) #if defined(__MAC_10_7) -static const void* query_keys[] = { - kSecClass, - kSecReturnRef, - kSecMatchPolicy, - kSecMatchLimit -}; +static const void* query_keys[] = {kSecClass, kSecReturnRef, kSecMatchPolicy, + kSecMatchLimit}; #endif // defined(__MAC_10_7) -template -class CFRef -{ +template class CFRef { T ref_; public: @@ -74,10 +68,7 @@ public: CFRef(T ref) : ref_(ref) {} - ~CFRef() - { - reset(nullptr); - } + ~CFRef() { reset(nullptr); } void reset(T ref) { @@ -87,20 +78,11 @@ public: ref_ = ref; } - T get() - { - return ref_; - } + T get() { return ref_; } - const T get() const - { - return ref_; - } + const T get() const { return ref_; } - operator bool() const - { - return !!ref_; - } + operator bool() const { return !!ref_; } }; static inline bool isWhitespace(char c) @@ -116,8 +98,7 @@ static inline std::string stripWhitespace(std::string str) return str; } -struct hash_validator -{ +struct hash_validator { const std::string& hash_; hash_validator(const std::string& hash) : hash_(hash) {} @@ -128,14 +109,14 @@ struct hash_validator } }; -struct hash_finder -{ +struct hash_finder { CFDataRef data_; const std::string& hash_; hash_finder(CFDataRef data, const std::string& hash) - : data_(data), hash_(hash) - {} + : data_(data), hash_(hash) + { + } inline bool operator()(std::string type) const { @@ -163,8 +144,7 @@ std::string errToString(OSStatus err) return rv; } -bool checkIdentity(const SecIdentityRef id, - const std::string& fingerPrint, +bool checkIdentity(const SecIdentityRef id, const std::string& fingerPrint, const std::vector supported) { CFRef ref; @@ -235,10 +215,7 @@ bool AppleTLSContext::addTrustedCACertFile(const std::string& certfile) return false; } -SecIdentityRef AppleTLSContext::getCredentials() -{ - return credentials_; -} +SecIdentityRef AppleTLSContext::getCredentials() { return credentials_; } bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint) { @@ -264,12 +241,8 @@ bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint) A2_LOG_ERROR("Failed to create SecPolicy"); return false; } - const void* query_values[] = { - kSecClassIdentity, - kCFBooleanTrue, - policy.get(), - kSecMatchLimitAll - }; + const void* query_values[] = {kSecClassIdentity, kCFBooleanTrue, policy.get(), + kSecMatchLimitAll}; CFRef query(CFDictionaryCreate( nullptr, query_keys, query_values, 4, nullptr, nullptr)); if (!query) { @@ -372,18 +345,12 @@ bool AppleTLSContext::tryAsPKCS12(CFDataRef data, const char* password) #if defined(__MAC_10_6) CFRef passwordRef; if (password) { - passwordRef.reset(CFStringCreateWithBytes(nullptr, - (const UInt8*)password, + passwordRef.reset(CFStringCreateWithBytes(nullptr, (const UInt8*)password, strlen(password), - kCFStringEncodingUTF8, - false)); + kCFStringEncodingUTF8, false)); } - const void* keys[] = { - kSecImportExportPassphrase - }; - const void* values[] = { - passwordRef.get() - }; + const void* keys[] = {kSecImportExportPassphrase}; + const void* values[] = {passwordRef.get()}; CFRef options( CFDictionaryCreate(nullptr, keys, values, 1, nullptr, nullptr)); if (!options) { diff --git a/src/AppleTLSContext.h b/src/AppleTLSContext.h index 6c72e5e9..800b8d46 100644 --- a/src/AppleTLSContext.h +++ b/src/AppleTLSContext.h @@ -46,12 +46,12 @@ namespace aria2 { -class AppleTLSContext : public TLSContext -{ +class AppleTLSContext : public TLSContext { public: AppleTLSContext(TLSSessionSide side, TLSVersion ver) - : side_(side), minTLSVer_(ver), verifyPeer_(true), credentials_(nullptr) - {} + : side_(side), minTLSVer_(ver), verifyPeer_(true), credentials_(nullptr) + { + } virtual ~AppleTLSContext(); @@ -59,28 +59,16 @@ public: virtual bool addCredentialFile(const std::string& certfile, const std::string& keyfile) CXX11_OVERRIDE; - virtual bool addSystemTrustedCACerts() CXX11_OVERRIDE - { - return true; - } + virtual bool addSystemTrustedCACerts() CXX11_OVERRIDE { return true; } // certfile can contain multiple certificates. virtual bool addTrustedCACertFile(const std::string& certfile) CXX11_OVERRIDE; - virtual bool good() const CXX11_OVERRIDE - { - return true; - } + virtual bool good() const CXX11_OVERRIDE { return true; } - virtual TLSSessionSide getSide() const CXX11_OVERRIDE - { - return side_; - } + virtual TLSSessionSide getSide() const CXX11_OVERRIDE { return side_; } - virtual bool getVerifyPeer() const CXX11_OVERRIDE - { - return verifyPeer_; - } + virtual bool getVerifyPeer() const CXX11_OVERRIDE { return verifyPeer_; } virtual void setVerifyPeer(bool verify) CXX11_OVERRIDE { @@ -89,10 +77,7 @@ public: SecIdentityRef getCredentials(); - TLSVersion getMinTLSVersion() const - { - return minTLSVer_; - } + TLSVersion getMinTLSVersion() const { return minTLSVer_; } private: TLSSessionSide side_; diff --git a/src/AppleTLSSession.cc b/src/AppleTLSSession.cc index be2c0713..93bf78c5 100644 --- a/src/AppleTLSSession.cc +++ b/src/AppleTLSSession.cc @@ -101,172 +101,168 @@ static inline const char* protoToString(SSLProtocol proto) { \ n, #s \ } -static struct -{ +static struct { SSLCipherSuite suite; const char* name; } kSuites[] = { - // From CipherSuite.h (10.9) - SUITE(SSL_NULL_WITH_NULL_NULL, 0x0000), - SUITE(SSL_RSA_WITH_NULL_MD5, 0x0001), - SUITE(SSL_RSA_WITH_NULL_SHA, 0x0002), - SUITE(SSL_RSA_EXPORT_WITH_RC4_40_MD5, 0x0003), - SUITE(SSL_RSA_WITH_RC4_128_MD5, 0x0004), - SUITE(SSL_RSA_WITH_RC4_128_SHA, 0x0005), - SUITE(SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, 0x0006), - SUITE(SSL_RSA_WITH_IDEA_CBC_SHA, 0x0007), - SUITE(SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, 0x0008), - SUITE(SSL_RSA_WITH_DES_CBC_SHA, 0x0009), - SUITE(SSL_RSA_WITH_3DES_EDE_CBC_SHA, 0x000A), - SUITE(SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, 0x000B), - SUITE(SSL_DH_DSS_WITH_DES_CBC_SHA, 0x000C), - SUITE(SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA, 0x000D), - SUITE(SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, 0x000E), - SUITE(SSL_DH_RSA_WITH_DES_CBC_SHA, 0x000F), - SUITE(SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA, 0x0010), - SUITE(SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, 0x0011), - SUITE(SSL_DHE_DSS_WITH_DES_CBC_SHA, 0x0012), - SUITE(SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, 0x0013), - SUITE(SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, 0x0014), - SUITE(SSL_DHE_RSA_WITH_DES_CBC_SHA, 0x0015), - SUITE(SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 0x0016), - SUITE(SSL_DH_anon_EXPORT_WITH_RC4_40_MD5, 0x0017), - SUITE(SSL_DH_anon_WITH_RC4_128_MD5, 0x0018), - SUITE(SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA, 0x0019), - SUITE(SSL_DH_anon_WITH_DES_CBC_SHA, 0x001A), - SUITE(SSL_DH_anon_WITH_3DES_EDE_CBC_SHA, 0x001B), - SUITE(SSL_FORTEZZA_DMS_WITH_NULL_SHA, 0x001C), - SUITE(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, 0x001D), - SUITE(TLS_RSA_WITH_AES_128_CBC_SHA, 0x002F), - SUITE(TLS_DH_DSS_WITH_AES_128_CBC_SHA, 0x0030), - SUITE(TLS_DH_RSA_WITH_AES_128_CBC_SHA, 0x0031), - SUITE(TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 0x0032), - SUITE(TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 0x0033), - SUITE(TLS_DH_anon_WITH_AES_128_CBC_SHA, 0x0034), - SUITE(TLS_RSA_WITH_AES_256_CBC_SHA, 0x0035), - SUITE(TLS_DH_DSS_WITH_AES_256_CBC_SHA, 0x0036), - SUITE(TLS_DH_RSA_WITH_AES_256_CBC_SHA, 0x0037), - SUITE(TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 0x0038), - SUITE(TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 0x0039), - SUITE(TLS_DH_anon_WITH_AES_256_CBC_SHA, 0x003A), - SUITE(TLS_ECDH_ECDSA_WITH_NULL_SHA, 0xC001), - SUITE(TLS_ECDH_ECDSA_WITH_RC4_128_SHA, 0xC002), - SUITE(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, 0xC003), - SUITE(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, 0xC004), - SUITE(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, 0xC005), - SUITE(TLS_ECDHE_ECDSA_WITH_NULL_SHA, 0xC006), - SUITE(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 0xC007), - SUITE(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, 0xC008), - SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 0xC009), - SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 0xC00A), - SUITE(TLS_ECDH_RSA_WITH_NULL_SHA, 0xC00B), - SUITE(TLS_ECDH_RSA_WITH_RC4_128_SHA, 0xC00C), - SUITE(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, 0xC00D), - SUITE(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, 0xC00E), - SUITE(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, 0xC00F), - SUITE(TLS_ECDHE_RSA_WITH_NULL_SHA, 0xC010), - SUITE(TLS_ECDHE_RSA_WITH_RC4_128_SHA, 0xC011), - SUITE(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 0xC012), - SUITE(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 0xC013), - SUITE(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 0xC014), - SUITE(TLS_ECDH_anon_WITH_NULL_SHA, 0xC015), - SUITE(TLS_ECDH_anon_WITH_RC4_128_SHA, 0xC016), - SUITE(TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, 0xC017), - SUITE(TLS_ECDH_anon_WITH_AES_128_CBC_SHA, 0xC018), - SUITE(TLS_ECDH_anon_WITH_AES_256_CBC_SHA, 0xC019), - SUITE(TLS_NULL_WITH_NULL_NULL, 0x0000), - SUITE(TLS_RSA_WITH_NULL_MD5, 0x0001), - SUITE(TLS_RSA_WITH_NULL_SHA, 0x0002), - SUITE(TLS_RSA_WITH_RC4_128_MD5, 0x0004), - SUITE(TLS_RSA_WITH_RC4_128_SHA, 0x0005), - SUITE(TLS_RSA_WITH_3DES_EDE_CBC_SHA, 0x000A), - SUITE(TLS_RSA_WITH_NULL_SHA256, 0x003B), - SUITE(TLS_RSA_WITH_AES_128_CBC_SHA256, 0x003C), - SUITE(TLS_RSA_WITH_AES_256_CBC_SHA256, 0x003D), - SUITE(TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, 0x000D), - SUITE(TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, 0x0010), - SUITE(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, 0x0013), - SUITE(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 0x0016), - SUITE(TLS_DH_DSS_WITH_AES_128_CBC_SHA256, 0x003E), - SUITE(TLS_DH_RSA_WITH_AES_128_CBC_SHA256, 0x003F), - SUITE(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, 0x0040), - SUITE(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, 0x0067), - SUITE(TLS_DH_DSS_WITH_AES_256_CBC_SHA256, 0x0068), - SUITE(TLS_DH_RSA_WITH_AES_256_CBC_SHA256, 0x0069), - SUITE(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, 0x006A), - SUITE(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, 0x006B), - SUITE(TLS_DH_anon_WITH_RC4_128_MD5, 0x0018), - SUITE(TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, 0x001B), - SUITE(TLS_DH_anon_WITH_AES_128_CBC_SHA256, 0x006C), - SUITE(TLS_DH_anon_WITH_AES_256_CBC_SHA256, 0x006D), - SUITE(TLS_PSK_WITH_RC4_128_SHA, 0x008A), - SUITE(TLS_PSK_WITH_3DES_EDE_CBC_SHA, 0x008B), - SUITE(TLS_PSK_WITH_AES_128_CBC_SHA, 0x008C), - SUITE(TLS_PSK_WITH_AES_256_CBC_SHA, 0x008D), - SUITE(TLS_DHE_PSK_WITH_RC4_128_SHA, 0x008E), - SUITE(TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, 0x008F), - SUITE(TLS_DHE_PSK_WITH_AES_128_CBC_SHA, 0x0090), - SUITE(TLS_DHE_PSK_WITH_AES_256_CBC_SHA, 0x0091), - SUITE(TLS_RSA_PSK_WITH_RC4_128_SHA, 0x0092), - SUITE(TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, 0x0093), - SUITE(TLS_RSA_PSK_WITH_AES_128_CBC_SHA, 0x0094), - SUITE(TLS_RSA_PSK_WITH_AES_256_CBC_SHA, 0x0095), - SUITE(TLS_PSK_WITH_NULL_SHA, 0x002C), - SUITE(TLS_DHE_PSK_WITH_NULL_SHA, 0x002D), - SUITE(TLS_RSA_PSK_WITH_NULL_SHA, 0x002E), - SUITE(TLS_RSA_WITH_AES_128_GCM_SHA256, 0x009C), - SUITE(TLS_RSA_WITH_AES_256_GCM_SHA384, 0x009D), - SUITE(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, 0x009E), - SUITE(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, 0x009F), - SUITE(TLS_DH_RSA_WITH_AES_128_GCM_SHA256, 0x00A0), - SUITE(TLS_DH_RSA_WITH_AES_256_GCM_SHA384, 0x00A1), - SUITE(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, 0x00A2), - SUITE(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, 0x00A3), - SUITE(TLS_DH_DSS_WITH_AES_128_GCM_SHA256, 0x00A4), - SUITE(TLS_DH_DSS_WITH_AES_256_GCM_SHA384, 0x00A5), - SUITE(TLS_DH_anon_WITH_AES_128_GCM_SHA256, 0x00A6), - SUITE(TLS_DH_anon_WITH_AES_256_GCM_SHA384, 0x00A7), - SUITE(TLS_PSK_WITH_AES_128_GCM_SHA256, 0x00A8), - SUITE(TLS_PSK_WITH_AES_256_GCM_SHA384, 0x00A9), - SUITE(TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, 0x00AA), - SUITE(TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, 0x00AB), - SUITE(TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, 0x00AC), - SUITE(TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, 0x00AD), - SUITE(TLS_PSK_WITH_AES_128_CBC_SHA256, 0x00AE), - SUITE(TLS_PSK_WITH_AES_256_CBC_SHA384, 0x00AF), - SUITE(TLS_PSK_WITH_NULL_SHA256, 0x00B0), - SUITE(TLS_PSK_WITH_NULL_SHA384, 0x00B1), - SUITE(TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, 0x00B2), - SUITE(TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, 0x00B3), - SUITE(TLS_DHE_PSK_WITH_NULL_SHA256, 0x00B4), - SUITE(TLS_DHE_PSK_WITH_NULL_SHA384, 0x00B5), - SUITE(TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, 0x00B6), - SUITE(TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, 0x00B7), - SUITE(TLS_RSA_PSK_WITH_NULL_SHA256, 0x00B8), - SUITE(TLS_RSA_PSK_WITH_NULL_SHA384, 0x00B9), - SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0xC023), - SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0xC024), - SUITE(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, 0xC025), - SUITE(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, 0xC026), - SUITE(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0xC027), - SUITE(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, 0xC028), - SUITE(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, 0xC029), - SUITE(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, 0xC02A), - SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0xC02B), - SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0xC02C), - SUITE(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, 0xC02D), - SUITE(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, 0xC02E), - SUITE(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0xC02F), - SUITE(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0xC030), - SUITE(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, 0xC031), - SUITE(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, 0xC032), - SUITE(TLS_EMPTY_RENEGOTIATION_INFO_SCSV, 0x00FF), - SUITE(SSL_RSA_WITH_RC2_CBC_MD5, 0xFF80), - SUITE(SSL_RSA_WITH_IDEA_CBC_MD5, 0xFF81), - SUITE(SSL_RSA_WITH_DES_CBC_MD5, 0xFF82), - SUITE(SSL_RSA_WITH_3DES_EDE_CBC_MD5, 0xFF83), - SUITE(SSL_NO_SUCH_CIPHERSUITE, 0xFFFF) -}; + // From CipherSuite.h (10.9) + SUITE(SSL_NULL_WITH_NULL_NULL, 0x0000), + SUITE(SSL_RSA_WITH_NULL_MD5, 0x0001), SUITE(SSL_RSA_WITH_NULL_SHA, 0x0002), + SUITE(SSL_RSA_EXPORT_WITH_RC4_40_MD5, 0x0003), + SUITE(SSL_RSA_WITH_RC4_128_MD5, 0x0004), + SUITE(SSL_RSA_WITH_RC4_128_SHA, 0x0005), + SUITE(SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, 0x0006), + SUITE(SSL_RSA_WITH_IDEA_CBC_SHA, 0x0007), + SUITE(SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, 0x0008), + SUITE(SSL_RSA_WITH_DES_CBC_SHA, 0x0009), + SUITE(SSL_RSA_WITH_3DES_EDE_CBC_SHA, 0x000A), + SUITE(SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, 0x000B), + SUITE(SSL_DH_DSS_WITH_DES_CBC_SHA, 0x000C), + SUITE(SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA, 0x000D), + SUITE(SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, 0x000E), + SUITE(SSL_DH_RSA_WITH_DES_CBC_SHA, 0x000F), + SUITE(SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA, 0x0010), + SUITE(SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, 0x0011), + SUITE(SSL_DHE_DSS_WITH_DES_CBC_SHA, 0x0012), + SUITE(SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, 0x0013), + SUITE(SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, 0x0014), + SUITE(SSL_DHE_RSA_WITH_DES_CBC_SHA, 0x0015), + SUITE(SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 0x0016), + SUITE(SSL_DH_anon_EXPORT_WITH_RC4_40_MD5, 0x0017), + SUITE(SSL_DH_anon_WITH_RC4_128_MD5, 0x0018), + SUITE(SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA, 0x0019), + SUITE(SSL_DH_anon_WITH_DES_CBC_SHA, 0x001A), + SUITE(SSL_DH_anon_WITH_3DES_EDE_CBC_SHA, 0x001B), + SUITE(SSL_FORTEZZA_DMS_WITH_NULL_SHA, 0x001C), + SUITE(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, 0x001D), + SUITE(TLS_RSA_WITH_AES_128_CBC_SHA, 0x002F), + SUITE(TLS_DH_DSS_WITH_AES_128_CBC_SHA, 0x0030), + SUITE(TLS_DH_RSA_WITH_AES_128_CBC_SHA, 0x0031), + SUITE(TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 0x0032), + SUITE(TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 0x0033), + SUITE(TLS_DH_anon_WITH_AES_128_CBC_SHA, 0x0034), + SUITE(TLS_RSA_WITH_AES_256_CBC_SHA, 0x0035), + SUITE(TLS_DH_DSS_WITH_AES_256_CBC_SHA, 0x0036), + SUITE(TLS_DH_RSA_WITH_AES_256_CBC_SHA, 0x0037), + SUITE(TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 0x0038), + SUITE(TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 0x0039), + SUITE(TLS_DH_anon_WITH_AES_256_CBC_SHA, 0x003A), + SUITE(TLS_ECDH_ECDSA_WITH_NULL_SHA, 0xC001), + SUITE(TLS_ECDH_ECDSA_WITH_RC4_128_SHA, 0xC002), + SUITE(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, 0xC003), + SUITE(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, 0xC004), + SUITE(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, 0xC005), + SUITE(TLS_ECDHE_ECDSA_WITH_NULL_SHA, 0xC006), + SUITE(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 0xC007), + SUITE(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, 0xC008), + SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 0xC009), + SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 0xC00A), + SUITE(TLS_ECDH_RSA_WITH_NULL_SHA, 0xC00B), + SUITE(TLS_ECDH_RSA_WITH_RC4_128_SHA, 0xC00C), + SUITE(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, 0xC00D), + SUITE(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, 0xC00E), + SUITE(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, 0xC00F), + SUITE(TLS_ECDHE_RSA_WITH_NULL_SHA, 0xC010), + SUITE(TLS_ECDHE_RSA_WITH_RC4_128_SHA, 0xC011), + SUITE(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 0xC012), + SUITE(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 0xC013), + SUITE(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 0xC014), + SUITE(TLS_ECDH_anon_WITH_NULL_SHA, 0xC015), + SUITE(TLS_ECDH_anon_WITH_RC4_128_SHA, 0xC016), + SUITE(TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, 0xC017), + SUITE(TLS_ECDH_anon_WITH_AES_128_CBC_SHA, 0xC018), + SUITE(TLS_ECDH_anon_WITH_AES_256_CBC_SHA, 0xC019), + SUITE(TLS_NULL_WITH_NULL_NULL, 0x0000), + SUITE(TLS_RSA_WITH_NULL_MD5, 0x0001), SUITE(TLS_RSA_WITH_NULL_SHA, 0x0002), + SUITE(TLS_RSA_WITH_RC4_128_MD5, 0x0004), + SUITE(TLS_RSA_WITH_RC4_128_SHA, 0x0005), + SUITE(TLS_RSA_WITH_3DES_EDE_CBC_SHA, 0x000A), + SUITE(TLS_RSA_WITH_NULL_SHA256, 0x003B), + SUITE(TLS_RSA_WITH_AES_128_CBC_SHA256, 0x003C), + SUITE(TLS_RSA_WITH_AES_256_CBC_SHA256, 0x003D), + SUITE(TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, 0x000D), + SUITE(TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, 0x0010), + SUITE(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, 0x0013), + SUITE(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, 0x0016), + SUITE(TLS_DH_DSS_WITH_AES_128_CBC_SHA256, 0x003E), + SUITE(TLS_DH_RSA_WITH_AES_128_CBC_SHA256, 0x003F), + SUITE(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, 0x0040), + SUITE(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, 0x0067), + SUITE(TLS_DH_DSS_WITH_AES_256_CBC_SHA256, 0x0068), + SUITE(TLS_DH_RSA_WITH_AES_256_CBC_SHA256, 0x0069), + SUITE(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, 0x006A), + SUITE(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, 0x006B), + SUITE(TLS_DH_anon_WITH_RC4_128_MD5, 0x0018), + SUITE(TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, 0x001B), + SUITE(TLS_DH_anon_WITH_AES_128_CBC_SHA256, 0x006C), + SUITE(TLS_DH_anon_WITH_AES_256_CBC_SHA256, 0x006D), + SUITE(TLS_PSK_WITH_RC4_128_SHA, 0x008A), + SUITE(TLS_PSK_WITH_3DES_EDE_CBC_SHA, 0x008B), + SUITE(TLS_PSK_WITH_AES_128_CBC_SHA, 0x008C), + SUITE(TLS_PSK_WITH_AES_256_CBC_SHA, 0x008D), + SUITE(TLS_DHE_PSK_WITH_RC4_128_SHA, 0x008E), + SUITE(TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, 0x008F), + SUITE(TLS_DHE_PSK_WITH_AES_128_CBC_SHA, 0x0090), + SUITE(TLS_DHE_PSK_WITH_AES_256_CBC_SHA, 0x0091), + SUITE(TLS_RSA_PSK_WITH_RC4_128_SHA, 0x0092), + SUITE(TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, 0x0093), + SUITE(TLS_RSA_PSK_WITH_AES_128_CBC_SHA, 0x0094), + SUITE(TLS_RSA_PSK_WITH_AES_256_CBC_SHA, 0x0095), + SUITE(TLS_PSK_WITH_NULL_SHA, 0x002C), + SUITE(TLS_DHE_PSK_WITH_NULL_SHA, 0x002D), + SUITE(TLS_RSA_PSK_WITH_NULL_SHA, 0x002E), + SUITE(TLS_RSA_WITH_AES_128_GCM_SHA256, 0x009C), + SUITE(TLS_RSA_WITH_AES_256_GCM_SHA384, 0x009D), + SUITE(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, 0x009E), + SUITE(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, 0x009F), + SUITE(TLS_DH_RSA_WITH_AES_128_GCM_SHA256, 0x00A0), + SUITE(TLS_DH_RSA_WITH_AES_256_GCM_SHA384, 0x00A1), + SUITE(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, 0x00A2), + SUITE(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, 0x00A3), + SUITE(TLS_DH_DSS_WITH_AES_128_GCM_SHA256, 0x00A4), + SUITE(TLS_DH_DSS_WITH_AES_256_GCM_SHA384, 0x00A5), + SUITE(TLS_DH_anon_WITH_AES_128_GCM_SHA256, 0x00A6), + SUITE(TLS_DH_anon_WITH_AES_256_GCM_SHA384, 0x00A7), + SUITE(TLS_PSK_WITH_AES_128_GCM_SHA256, 0x00A8), + SUITE(TLS_PSK_WITH_AES_256_GCM_SHA384, 0x00A9), + SUITE(TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, 0x00AA), + SUITE(TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, 0x00AB), + SUITE(TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, 0x00AC), + SUITE(TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, 0x00AD), + SUITE(TLS_PSK_WITH_AES_128_CBC_SHA256, 0x00AE), + SUITE(TLS_PSK_WITH_AES_256_CBC_SHA384, 0x00AF), + SUITE(TLS_PSK_WITH_NULL_SHA256, 0x00B0), + SUITE(TLS_PSK_WITH_NULL_SHA384, 0x00B1), + SUITE(TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, 0x00B2), + SUITE(TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, 0x00B3), + SUITE(TLS_DHE_PSK_WITH_NULL_SHA256, 0x00B4), + SUITE(TLS_DHE_PSK_WITH_NULL_SHA384, 0x00B5), + SUITE(TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, 0x00B6), + SUITE(TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, 0x00B7), + SUITE(TLS_RSA_PSK_WITH_NULL_SHA256, 0x00B8), + SUITE(TLS_RSA_PSK_WITH_NULL_SHA384, 0x00B9), + SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 0xC023), + SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, 0xC024), + SUITE(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, 0xC025), + SUITE(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, 0xC026), + SUITE(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 0xC027), + SUITE(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, 0xC028), + SUITE(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, 0xC029), + SUITE(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, 0xC02A), + SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 0xC02B), + SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0xC02C), + SUITE(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, 0xC02D), + SUITE(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, 0xC02E), + SUITE(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 0xC02F), + SUITE(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0xC030), + SUITE(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, 0xC031), + SUITE(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, 0xC032), + SUITE(TLS_EMPTY_RENEGOTIATION_INFO_SCSV, 0x00FF), + SUITE(SSL_RSA_WITH_RC2_CBC_MD5, 0xFF80), + SUITE(SSL_RSA_WITH_IDEA_CBC_MD5, 0xFF81), + SUITE(SSL_RSA_WITH_DES_CBC_MD5, 0xFF82), + SUITE(SSL_RSA_WITH_3DES_EDE_CBC_MD5, 0xFF83), + SUITE(SSL_NO_SUCH_CIPHERSUITE, 0xFFFF)}; #undef SUITE static inline std::string suiteToString(const SSLCipherSuite suite) @@ -283,9 +279,8 @@ static inline std::string suiteToString(const SSLCipherSuite suite) return ss.str(); } -static const char* kBlocked[] = { - "NULL", "anon", "MD5", "EXPORT", "DES", "IDEA", "NO_SUCH", "EMPTY", "PSK" -}; +static const char* kBlocked[] = {"NULL", "anon", "MD5", "EXPORT", "DES", + "IDEA", "NO_SUCH", "EMPTY", "PSK"}; static inline bool isBlockedSuite(SSLCipherSuite suite) { @@ -309,7 +304,7 @@ static SSLCipherSuiteList constructEnabledSuites(SSLContextRef ctx) #ifndef CIPHER_CONSTRUCT_ALWAYS static #endif - SSLCipherSuiteList rv(0); + SSLCipherSuiteList rv(0); #ifndef CIPHER_CONSTRUCT_ALWAYS if (!rv.empty()) { @@ -345,17 +340,16 @@ TLSSession* TLSSession::make(TLSContext* ctx) } AppleTLSSession::AppleTLSSession(AppleTLSContext* ctx) - : sslCtx_(nullptr), - sockfd_(0), - state_(st_constructed), - lastError_(noErr), - writeBuffered_(0) + : sslCtx_(nullptr), + sockfd_(0), + state_(st_constructed), + lastError_(noErr), + writeBuffered_(0) { #if defined(__MAC_10_8) - sslCtx_ = SSLCreateContext(nullptr, - ctx->getSide() == TLS_SERVER ? kSSLServerSide : - kSSLClientSide, - kSSLStreamType); + sslCtx_ = SSLCreateContext( + nullptr, ctx->getSide() == TLS_SERVER ? kSSLServerSide : kSSLClientSide, + kSSLStreamType); lastError_ = sslCtx_ ? noErr : paramErr; #else lastError_ = SSLNewContext(ctx->getSide() == TLS_SERVER, &sslCtx_); @@ -388,13 +382,13 @@ AppleTLSSession::AppleTLSSession(AppleTLSContext* ctx) switch (ctx->getMinTLSVersion()) { case TLS_PROTO_SSL3: (void)SSLSetProtocolVersionEnabled(sslCtx_, kSSLProtocol3, true); - // fall through + // fall through case TLS_PROTO_TLS10: (void)SSLSetProtocolVersionEnabled(sslCtx_, kTLSProtocol1, true); - // fall through + // fall through case TLS_PROTO_TLS11: (void)SSLSetProtocolVersionEnabled(sslCtx_, kTLSProtocol11, true); - // fall through + // fall through case TLS_PROTO_TLS12: (void)SSLSetProtocolVersionEnabled(sslCtx_, kTLSProtocol12, true); default: @@ -414,8 +408,8 @@ AppleTLSSession::AppleTLSSession(AppleTLSContext* ctx) #if defined(__MAC_10_8) if (!ctx->getVerifyPeer()) { // This disables client verification - (void)SSLSetSessionOption( - sslCtx_, kSSLSessionOptionBreakOnServerAuth, true); + (void)SSLSetSessionOption(sslCtx_, kSSLSessionOptionBreakOnServerAuth, + true); } #else (void)SSLSetEnableCertVerify(sslCtx_, ctx->getVerifyPeer()); @@ -700,8 +694,7 @@ OSStatus AppleTLSSession::sockRead(void* data, size_t* len) } int AppleTLSSession::tlsConnect(const std::string& hostname, - TLSVersion& version, - std::string& handshakeErr) + TLSVersion& version, std::string& handshakeErr) { if (state_ != st_initialized) { return TLS_ERR_ERROR; @@ -733,27 +726,25 @@ int AppleTLSSession::tlsConnect(const std::string& hostname, (void)SSLGetNegotiatedProtocolVersion(sslCtx_, &proto); SSLCipherSuite suite = SSL_NO_SUCH_CIPHERSUITE; (void)SSLGetNegotiatedCipher(sslCtx_, &suite); - A2_LOG_INFO(fmt("AppleTLS: Connected to %s with %s (%s)", - hostname.c_str(), - protoToString(proto), - suiteToString(suite).c_str())); + A2_LOG_INFO(fmt("AppleTLS: Connected to %s with %s (%s)", hostname.c_str(), + protoToString(proto), suiteToString(suite).c_str())); switch (proto) { - case kSSLProtocol3: - version = TLS_PROTO_SSL3; - break; - case kTLSProtocol1: - version = TLS_PROTO_TLS10; - break; - case kTLSProtocol11: - version = TLS_PROTO_TLS11; - break; - case kTLSProtocol12: - version = TLS_PROTO_TLS12; - break; - default: - version = TLS_PROTO_NONE; - break; + case kSSLProtocol3: + version = TLS_PROTO_SSL3; + break; + case kTLSProtocol1: + version = TLS_PROTO_TLS10; + break; + case kTLSProtocol11: + version = TLS_PROTO_TLS11; + break; + case kTLSProtocol12: + version = TLS_PROTO_TLS12; + break; + default: + version = TLS_PROTO_NONE; + break; } return TLS_ERR_OK; diff --git a/src/AppleTLSSession.h b/src/AppleTLSSession.h index 2c491dff..33641591 100644 --- a/src/AppleTLSSession.h +++ b/src/AppleTLSSession.h @@ -41,8 +41,7 @@ namespace aria2 { -class AppleTLSSession : public TLSSession -{ +class AppleTLSSession : public TLSSession { enum state_t { st_constructed, st_initialized, @@ -95,8 +94,7 @@ public: // if the underlying transport blocks, or TLS_ERR_ERROR. // When returning TLS_ERR_ERROR, provide certificate validation error // in |handshakeErr|. - virtual int tlsConnect(const std::string& hostname, - TLSVersion& version, + virtual int tlsConnect(const std::string& hostname, TLSVersion& version, std::string& handshakeErr) CXX11_OVERRIDE; // Performs server side handshake. This function returns TLS_ERR_OK @@ -108,8 +106,8 @@ public: virtual std::string getLastErrorString() CXX11_OVERRIDE; private: - static OSStatus - SocketWrite(SSLConnectionRef conn, const void* data, size_t* len) + static OSStatus SocketWrite(SSLConnectionRef conn, const void* data, + size_t* len) { return ((AppleTLSSession*)conn)->sockWrite(data, len); } diff --git a/src/AsyncNameResolver.cc b/src/AsyncNameResolver.cc index 34a33dc1..b041d6f9 100644 --- a/src/AsyncNameResolver.cc +++ b/src/AsyncNameResolver.cc @@ -46,50 +46,47 @@ namespace aria2 { void callback(void* arg, int status, int timeouts, struct hostent* host) { AsyncNameResolver* resolverPtr = reinterpret_cast(arg); - if(status != ARES_SUCCESS) { + if (status != ARES_SUCCESS) { resolverPtr->error_ = ares_strerror(status); resolverPtr->status_ = AsyncNameResolver::STATUS_ERROR; return; } - for(char** ap = host->h_addr_list; *ap; ++ap) { + for (char** ap = host->h_addr_list; *ap; ++ap) { char addrstring[NI_MAXHOST]; - if(inetNtop(host->h_addrtype, *ap, addrstring, sizeof(addrstring)) == 0) { + if (inetNtop(host->h_addrtype, *ap, addrstring, sizeof(addrstring)) == 0) { resolverPtr->resolvedAddresses_.push_back(addrstring); } } - if(resolverPtr->resolvedAddresses_.empty()) { + if (resolverPtr->resolvedAddresses_.empty()) { resolverPtr->error_ = "no address returned or address conversion failed"; resolverPtr->status_ = AsyncNameResolver::STATUS_ERROR; - } else { + } + else { resolverPtr->status_ = AsyncNameResolver::STATUS_SUCCESS; } } -AsyncNameResolver::AsyncNameResolver -(int family +AsyncNameResolver::AsyncNameResolver(int family #ifdef HAVE_ARES_ADDR_NODE - , ares_addr_node* servers + , + ares_addr_node* servers #endif // HAVE_ARES_ADDR_NODE - ) - : status_(STATUS_READY), - family_(family) + ) + : status_(STATUS_READY), family_(family) { // TODO evaluate return value ares_init(&channel_); #if defined(HAVE_ARES_SET_SERVERS) && defined(HAVE_ARES_ADDR_NODE) - if(servers) { + if (servers) { // ares_set_servers has been added since c-ares 1.7.1 - if(ares_set_servers(channel_, servers) != ARES_SUCCESS) { + if (ares_set_servers(channel_, servers) != ARES_SUCCESS) { A2_LOG_DEBUG("ares_set_servers failed"); } } #endif // HAVE_ARES_SET_SERVERS && HAVE_ARES_ADDR_NODE } -AsyncNameResolver::~AsyncNameResolver() -{ - ares_destroy(channel_); -} +AsyncNameResolver::~AsyncNameResolver() { ares_destroy(channel_); } void AsyncNameResolver::resolve(const std::string& name) { @@ -148,11 +145,11 @@ ares_addr_node* parseAsyncDNSServers(const std::string& serversOpt) ares_addr_node root; root.next = nullptr; ares_addr_node* tail = &root; - for (const auto& s: servers) { + for (const auto& s : servers) { auto node = make_unique(); size_t len = net::getBinAddr(&node->addr, s.c_str()); - if(len != 0) { + if (len != 0) { node->next = nullptr; node->family = (len == 4 ? AF_INET : AF_INET6); tail->next = node.release(); diff --git a/src/AsyncNameResolver.h b/src/AsyncNameResolver.h index fac6df5e..de7113c3 100644 --- a/src/AsyncNameResolver.h +++ b/src/AsyncNameResolver.h @@ -47,8 +47,9 @@ namespace aria2 { class AsyncNameResolver { - friend void callback - (void* arg, int status, int timeouts, struct hostent* host); + friend void callback(void* arg, int status, int timeouts, + struct hostent* host); + public: enum STATUS { STATUS_READY, @@ -56,6 +57,7 @@ public: STATUS_SUCCESS, STATUS_ERROR, }; + private: STATUS status_; int family_; @@ -64,13 +66,14 @@ private: std::vector resolvedAddresses_; std::string error_; std::string hostname_; + public: - AsyncNameResolver - (int family + AsyncNameResolver(int family #ifdef HAVE_ARES_ADDR_NODE - , ares_addr_node* servers + , + ares_addr_node* servers #endif // HAVE_ARES_ADDR_NODE - ); + ); ~AsyncNameResolver(); @@ -81,24 +84,15 @@ public: return resolvedAddresses_; } - const std::string& getError() const - { - return error_; - } + const std::string& getError() const { return error_; } - STATUS getStatus() const - { - return status_; - } + STATUS getStatus() const { return status_; } int getFds(fd_set* rfdsPtr, fd_set* wfdsPtr) const; void process(fd_set* rfdsPtr, fd_set* wfdsPtr); - int getFamily() const - { - return family_; - } + int getFamily() const { return family_; } #ifdef HAVE_LIBCARES int getsock(sock_t* sockets) const; @@ -113,11 +107,7 @@ public: void reset(); - const std::string& getHostname() const - { - return hostname_; - } - + const std::string& getHostname() const { return hostname_; } }; #ifdef HAVE_ARES_ADDR_NODE @@ -126,7 +116,6 @@ ares_addr_node* parseAsyncDNSServers(const std::string& serversOpt); #endif // HAVE_ARES_ADDR_NODE - } // namespace aria2 #endif // D_ASYNC_NAME_RESOLVER_H diff --git a/src/AsyncNameResolverMan.cc b/src/AsyncNameResolverMan.cc index ddf044f6..ef5fb741 100644 --- a/src/AsyncNameResolverMan.cc +++ b/src/AsyncNameResolverMan.cc @@ -49,21 +49,16 @@ namespace aria2 { AsyncNameResolverMan::AsyncNameResolverMan() - : numResolver_(0), - resolverCheck_(0), - ipv4_(true), - ipv6_(true) -{} - -AsyncNameResolverMan::~AsyncNameResolverMan() + : numResolver_(0), resolverCheck_(0), ipv4_(true), ipv6_(true) { - assert(!resolverCheck_); } +AsyncNameResolverMan::~AsyncNameResolverMan() { assert(!resolverCheck_); } + bool AsyncNameResolverMan::started() const { - for(size_t i = 0; i < numResolver_; ++i) { - if(asyncNameResolver_[i]) { + for (size_t i = 0; i < numResolver_; ++i) { + if (asyncNameResolver_[i]) { return true; } } @@ -71,46 +66,44 @@ bool AsyncNameResolverMan::started() const } void AsyncNameResolverMan::startAsync(const std::string& hostname, - DownloadEngine* e, - Command* command) + DownloadEngine* e, Command* command) { numResolver_ = 0; // Set IPv6 resolver first, so that we can push IPv6 address in // front of IPv6 address in getResolvedAddress(). - if(ipv6_) { + if (ipv6_) { startAsyncFamily(hostname, AF_INET6, e, command); ++numResolver_; } - if(ipv4_) { + if (ipv4_) { startAsyncFamily(hostname, AF_INET, e, command); ++numResolver_; } - A2_LOG_INFO(fmt(MSG_RESOLVING_HOSTNAME, command->getCuid(), - hostname.c_str())); + A2_LOG_INFO( + fmt(MSG_RESOLVING_HOSTNAME, command->getCuid(), hostname.c_str())); } void AsyncNameResolverMan::startAsyncFamily(const std::string& hostname, - int family, - DownloadEngine* e, + int family, DownloadEngine* e, Command* command) { - asyncNameResolver_[numResolver_] = std::make_shared - (family + asyncNameResolver_[numResolver_] = + std::make_shared(family #ifdef HAVE_ARES_ADDR_NODE - , - e->getAsyncDNSServers() + , + e->getAsyncDNSServers() #endif // HAVE_ARES_ADDR_NODE - ); + ); asyncNameResolver_[numResolver_]->resolve(hostname); setNameResolverCheck(numResolver_, e, command); } -void AsyncNameResolverMan::getResolvedAddress(std::vector& res) -const +void AsyncNameResolverMan::getResolvedAddress( + std::vector& res) const { - for(size_t i = 0; i < numResolver_; ++i) { - if(asyncNameResolver_[i]->getStatus() == - AsyncNameResolver::STATUS_SUCCESS) { + for (size_t i = 0; i < numResolver_; ++i) { + if (asyncNameResolver_[i]->getStatus() == + AsyncNameResolver::STATUS_SUCCESS) { auto& addrs = asyncNameResolver_[i]->getResolvedAddresses(); res.insert(std::end(res), std::begin(addrs), std::end(addrs)); } @@ -121,16 +114,15 @@ const void AsyncNameResolverMan::setNameResolverCheck(DownloadEngine* e, Command* command) { - for(size_t i = 0; i < numResolver_; ++i) { + for (size_t i = 0; i < numResolver_; ++i) { setNameResolverCheck(i, e, command); } } -void AsyncNameResolverMan::setNameResolverCheck(size_t index, - DownloadEngine* e, +void AsyncNameResolverMan::setNameResolverCheck(size_t index, DownloadEngine* e, Command* command) { - if(asyncNameResolver_[index]) { + if (asyncNameResolver_[index]) { assert((resolverCheck_ & (1 << index)) == 0); resolverCheck_ |= 1 << index; e->addNameResolverCheck(asyncNameResolver_[index], command); @@ -140,7 +132,7 @@ void AsyncNameResolverMan::setNameResolverCheck(size_t index, void AsyncNameResolverMan::disableNameResolverCheck(DownloadEngine* e, Command* command) { - for(size_t i = 0; i < numResolver_; ++i) { + for (size_t i = 0; i < numResolver_; ++i) { disableNameResolverCheck(i, e, command); } } @@ -149,7 +141,7 @@ void AsyncNameResolverMan::disableNameResolverCheck(size_t index, DownloadEngine* e, Command* command) { - if(asyncNameResolver_[index] && (resolverCheck_ & (1 << index))) { + if (asyncNameResolver_[index] && (resolverCheck_ & (1 << index))) { resolverCheck_ &= ~(1 << index); e->deleteNameResolverCheck(asyncNameResolver_[index], command); } @@ -160,11 +152,11 @@ int AsyncNameResolverMan::getStatus() const size_t success = 0; size_t error = 0; bool ipv4Success = false; - for(size_t i = 0; i < numResolver_; ++i) { - switch(asyncNameResolver_[i]->getStatus()) { + for (size_t i = 0; i < numResolver_; ++i) { + switch (asyncNameResolver_[i]->getStatus()) { case AsyncNameResolver::STATUS_SUCCESS: ++success; - if(asyncNameResolver_[i]->getFamily() == AF_INET) { + if (asyncNameResolver_[i]->getFamily() == AF_INET) { ipv4Success = true; } break; @@ -180,19 +172,21 @@ int AsyncNameResolverMan::getStatus() const // have to wait for a long time before timeout. We don't do the // inverse, because, based on today's deployment of DNS servers, // almost all of them can respond to A queries just fine. - if((success && ipv4Success) || success == numResolver_) { + if ((success && ipv4Success) || success == numResolver_) { return 1; - } else if(error == numResolver_) { + } + else if (error == numResolver_) { return -1; - } else { + } + else { return 0; } } const std::string& AsyncNameResolverMan::getLastError() const { - for(size_t i = 0; i < numResolver_; ++i) { - if(asyncNameResolver_[i]->getStatus() == AsyncNameResolver::STATUS_ERROR) { + for (size_t i = 0; i < numResolver_; ++i) { + if (asyncNameResolver_[i]->getStatus() == AsyncNameResolver::STATUS_ERROR) { // TODO This is not last error chronologically. return asyncNameResolver_[i]->getError(); } @@ -204,7 +198,7 @@ void AsyncNameResolverMan::reset(DownloadEngine* e, Command* command) { disableNameResolverCheck(e, command); assert(resolverCheck_ == 0); - for(size_t i = 0; i < numResolver_; ++i) { + for (size_t i = 0; i < numResolver_; ++i) { asyncNameResolver_[i].reset(); } numResolver_ = 0; @@ -219,14 +213,13 @@ void configureAsyncNameResolverMan(AsyncNameResolverMan* asyncNameResolverMan, // before network interfaces up. To workaround this, we check // addresses again if both addresses are not configured at the // startup. - if(!net::getIPv4AddrConfigured() && !net::getIPv6AddrConfigured()) { + if (!net::getIPv4AddrConfigured() && !net::getIPv6AddrConfigured()) { net::checkAddrconfig(); } - if(!net::getIPv4AddrConfigured()) { + if (!net::getIPv4AddrConfigured()) { asyncNameResolverMan->setIPv4(false); } - if(!net::getIPv6AddrConfigured() || - option->getAsBool(PREF_DISABLE_IPV6)) { + if (!net::getIPv6AddrConfigured() || option->getAsBool(PREF_DISABLE_IPV6)) { asyncNameResolverMan->setIPv6(false); } } diff --git a/src/AsyncNameResolverMan.h b/src/AsyncNameResolverMan.h index 6f84434e..617474ec 100644 --- a/src/AsyncNameResolverMan.h +++ b/src/AsyncNameResolverMan.h @@ -55,15 +55,9 @@ public: // must call it before the destruction of this object. ~AsyncNameResolverMan(); // Enable IPv4 address lookup. default: true - void setIPv4(bool ipv4) - { - ipv4_ = ipv4; - } + void setIPv4(bool ipv4) { ipv4_ = ipv4; } // Enable IPv6 address lookup. default: true - void setIPv6(bool ipv6) - { - ipv6_ = ipv6; - } + void setIPv6(bool ipv6) { ipv6_ = ipv6; } // Returns true if asynchronous name resolution has been started. bool started() const; // Starts asynchronous name resolution. @@ -76,10 +70,7 @@ public: // Removes resolvers from DownloadEngine. void disableNameResolverCheck(DownloadEngine* e, Command* command); // Returns true if any of resolvers are added in DownloadEngine. - bool resolverChecked() const - { - return resolverCheck_; - } + bool resolverChecked() const { return resolverCheck_; } // Returns status value: 0 for inprogress, 1 for success and -1 for // failure. int getStatus() const; @@ -87,9 +78,9 @@ public: const std::string& getLastError() const; // Resets state. Also removes resolvers from DownloadEngine. void reset(DownloadEngine* e, Command* command); + private: - void startAsyncFamily(const std::string& hostname, - int family, + void startAsyncFamily(const std::string& hostname, int family, DownloadEngine* e, Command* command); void setNameResolverCheck(size_t resolverIndex, DownloadEngine* e, Command* command); diff --git a/src/AuthConfig.cc b/src/AuthConfig.cc index a2f22ce1..6184ec3c 100644 --- a/src/AuthConfig.cc +++ b/src/AuthConfig.cc @@ -43,9 +43,9 @@ namespace aria2 { AuthConfig::AuthConfig() {} AuthConfig::AuthConfig(std::string user, std::string password) - : user_(std::move(user)), - password_(std::move(password)) -{} + : user_(std::move(user)), password_(std::move(password)) +{ +} AuthConfig::~AuthConfig() {} @@ -57,12 +57,13 @@ std::string AuthConfig::getAuthText() const return s; } -std::unique_ptr AuthConfig::create -(std::string user, std::string password) +std::unique_ptr AuthConfig::create(std::string user, + std::string password) { - if(user.empty()) { + if (user.empty()) { return nullptr; - } else { + } + else { return make_unique(std::move(user), std::move(password)); } } diff --git a/src/AuthConfig.h b/src/AuthConfig.h index e25c0af3..6c35dbef 100644 --- a/src/AuthConfig.h +++ b/src/AuthConfig.h @@ -48,6 +48,7 @@ private: std::string authScheme_; std::string user_; std::string password_; + public: AuthConfig(); AuthConfig(std::string user, std::string password); @@ -59,18 +60,12 @@ public: std::string getAuthText() const; - const std::string& getUser() const - { - return user_; - } + const std::string& getUser() const { return user_; } - const std::string& getPassword() const - { - return password_; - } + const std::string& getPassword() const { return password_; } - static std::unique_ptr create - (std::string user, std::string password); + static std::unique_ptr create(std::string user, + std::string password); }; std::ostream& operator<<(std::ostream& o, diff --git a/src/AuthConfigFactory.cc b/src/AuthConfigFactory.cc index 2f3c0573..43ba7285 100644 --- a/src/AuthConfigFactory.cc +++ b/src/AuthConfigFactory.cc @@ -57,51 +57,54 @@ AuthConfigFactory::AuthConfigFactory() {} AuthConfigFactory::~AuthConfigFactory() {} std::unique_ptr -AuthConfigFactory::createAuthConfig -(const std::shared_ptr& request, const Option* op) +AuthConfigFactory::createAuthConfig(const std::shared_ptr& request, + const Option* op) { - if(request->getProtocol() == "http" || request->getProtocol() == "https") { - if(op->getAsBool(PREF_HTTP_AUTH_CHALLENGE)) { - if(!request->getUsername().empty()) { - updateBasicCred(make_unique(request->getUsername(), - request->getPassword(), - request->getHost(), - request->getPort(), - request->getDir(), true)); + if (request->getProtocol() == "http" || request->getProtocol() == "https") { + if (op->getAsBool(PREF_HTTP_AUTH_CHALLENGE)) { + if (!request->getUsername().empty()) { + updateBasicCred(make_unique( + request->getUsername(), request->getPassword(), request->getHost(), + request->getPort(), request->getDir(), true)); return AuthConfig::create(request->getUsername(), request->getPassword()); } auto i = findBasicCred(request->getHost(), request->getPort(), request->getDir()); - if(i == std::end(basicCreds_)) { + if (i == std::end(basicCreds_)) { return nullptr; - } else { + } + else { return AuthConfig::create((*i)->user_, (*i)->password_); } - } else { - if(!request->getUsername().empty()) { + } + else { + if (!request->getUsername().empty()) { return AuthConfig::create(request->getUsername(), request->getPassword()); - } else { - return - createHttpAuthResolver(op)->resolveAuthConfig(request->getHost()); + } + else { + return createHttpAuthResolver(op) + ->resolveAuthConfig(request->getHost()); } } - } else if(request->getProtocol() == "ftp" || - request->getProtocol() == "sftp") { - if(!request->getUsername().empty()) { - if(request->hasPassword()) { + } + else if (request->getProtocol() == "ftp" || + request->getProtocol() == "sftp") { + if (!request->getUsername().empty()) { + if (request->hasPassword()) { return AuthConfig::create(request->getUsername(), request->getPassword()); - } else { - if(!op->getAsBool(PREF_NO_NETRC)) { + } + else { + if (!op->getAsBool(PREF_NO_NETRC)) { // First, check we have password corresponding to host and // username NetrcAuthResolver authResolver; authResolver.setNetrc(netrc_.get()); auto ac = authResolver.resolveAuthConfig(request->getHost()); - if(ac && ac->getUser() == request->getUsername()) { + if (ac && ac->getUser() == request->getUsername()) { return ac; } } @@ -110,22 +113,24 @@ AuthConfigFactory::createAuthConfig return AuthConfig::create(request->getUsername(), op->get(PREF_FTP_PASSWD)); } - } else { - return - createFtpAuthResolver(op)->resolveAuthConfig(request->getHost()); } - } else { + else { + return createFtpAuthResolver(op)->resolveAuthConfig(request->getHost()); + } + } + else { return nullptr; } } -std::unique_ptr AuthConfigFactory::createHttpAuthResolver -(const Option* op) const +std::unique_ptr +AuthConfigFactory::createHttpAuthResolver(const Option* op) const { std::unique_ptr resolver; - if(op->getAsBool(PREF_NO_NETRC)) { + if (op->getAsBool(PREF_NO_NETRC)) { resolver = make_unique(); - } else { + } + else { auto authResolver = make_unique(); authResolver->setNetrc(netrc_.get()); authResolver->ignoreDefault(); @@ -136,13 +141,14 @@ std::unique_ptr AuthConfigFactory::createHttpAuthResolver return std::move(resolver); } -std::unique_ptr AuthConfigFactory::createFtpAuthResolver -(const Option* op) const +std::unique_ptr +AuthConfigFactory::createFtpAuthResolver(const Option* op) const { std::unique_ptr resolver; - if(op->getAsBool(PREF_NO_NETRC)) { + if (op->getAsBool(PREF_NO_NETRC)) { resolver = make_unique(); - } else { + } + else { auto authResolver = make_unique(); authResolver->setNetrc(netrc_.get()); resolver = std::move(authResolver); @@ -161,61 +167,55 @@ void AuthConfigFactory::setNetrc(std::unique_ptr netrc) void AuthConfigFactory::updateBasicCred(std::unique_ptr basicCred) { auto i = basicCreds_.lower_bound(basicCred); - if(i != std::end(basicCreds_) && *i == basicCred) { + if (i != std::end(basicCreds_) && *i == basicCred) { *(*i) = std::move(*basicCred); - } else { + } + else { basicCreds_.insert(i, std::move(basicCred)); } } -bool AuthConfigFactory::activateBasicCred -(const std::string& host, - uint16_t port, - const std::string& path, - const Option* op) +bool AuthConfigFactory::activateBasicCred(const std::string& host, + uint16_t port, + const std::string& path, + const Option* op) { auto i = findBasicCred(host, port, path); - if(i == std::end(basicCreds_)) { + if (i == std::end(basicCreds_)) { auto authConfig = createHttpAuthResolver(op)->resolveAuthConfig(host); - if(!authConfig) { + if (!authConfig) { return false; - } else { + } + else { basicCreds_.insert(make_unique(authConfig->getUser(), - authConfig->getPassword(), - host, port, path, true)); + authConfig->getPassword(), host, + port, path, true)); return true; } - } else { + } + else { (*i)->activate(); return true; } } -BasicCred::BasicCred -(std::string user, std::string password, - std::string host, uint16_t port, std::string path, - bool activated) - : user_(std::move(user)), - password_(std::move(password)), - host_(std::move(host)), - port_(port), - path_(std::move(path)), - activated_(activated) +BasicCred::BasicCred(std::string user, std::string password, std::string host, + uint16_t port, std::string path, bool activated) + : user_(std::move(user)), + password_(std::move(password)), + host_(std::move(host)), + port_(port), + path_(std::move(path)), + activated_(activated) { - if(path_.empty() || path_[path_.size()-1] != '/') { + if (path_.empty() || path_[path_.size() - 1] != '/') { path_ += "/"; } } -void BasicCred::activate() -{ - activated_ = true; -} +void BasicCred::activate() { activated_ = true; } -bool BasicCred::isActivated() const -{ - return activated_; -} +bool BasicCred::isActivated() const { return activated_; } bool BasicCred::operator==(const BasicCred& cred) const { @@ -224,22 +224,21 @@ bool BasicCred::operator==(const BasicCred& cred) const bool BasicCred::operator<(const BasicCred& cred) const { - return host_ < cred.host_ || - (!(cred.host_ < host_) && (port_ < cred.port_ || - (!(cred.port_ < port_) && path_ > cred.path_))); + return host_ < cred.host_ || (!(cred.host_ < host_) && + (port_ < cred.port_ || (!(cred.port_ < port_) && + path_ > cred.path_))); } -AuthConfigFactory::BasicCredSet::iterator AuthConfigFactory::findBasicCred -(const std::string& host, - uint16_t port, - const std::string& path) +AuthConfigFactory::BasicCredSet::iterator +AuthConfigFactory::findBasicCred(const std::string& host, uint16_t port, + const std::string& path) { auto bc = make_unique("", "", host, port, path); auto i = basicCreds_.lower_bound(bc); - for(; i != std::end(basicCreds_) && - (*i)->host_ == host && - (*i)->port_ == port; ++i) { - if(util::startsWith(bc->path_, (*i)->path_)) { + for (; + i != std::end(basicCreds_) && (*i)->host_ == host && (*i)->port_ == port; + ++i) { + if (util::startsWith(bc->path_, (*i)->path_)) { return i; } } diff --git a/src/AuthConfigFactory.h b/src/AuthConfigFactory.h index 03c85bd4..c9ae60ec 100644 --- a/src/AuthConfigFactory.h +++ b/src/AuthConfigFactory.h @@ -61,9 +61,8 @@ public: std::string path_; bool activated_; - BasicCred(std::string user, std::string password, - std::string host, uint16_t port, std::string path, - bool activated = false); + BasicCred(std::string user, std::string password, std::string host, + uint16_t port, std::string path, bool activated = false); void activate(); @@ -78,6 +77,7 @@ class AuthConfigFactory { public: typedef std::set, DerefLess>> BasicCredSet; + private: std::unique_ptr netrc_; @@ -86,6 +86,7 @@ private: std::unique_ptr createFtpAuthResolver(const Option* op) const; BasicCredSet basicCreds_; + public: AuthConfigFactory(); @@ -95,8 +96,8 @@ public: // are used in this method: PREF_HTTP_USER, PREF_HTTP_PASSWD, // PREF_FTP_USER, PREF_FTP_PASSWD, PREF_NO_NETRC and // PREF_HTTP_AUTH_CHALLENGE. - std::unique_ptr createAuthConfig - (const std::shared_ptr& request, const Option* op); + std::unique_ptr + createAuthConfig(const std::shared_ptr& request, const Option* op); void setNetrc(std::unique_ptr netrc); @@ -106,20 +107,14 @@ public: // null, then returns false. Otherwise new BasicCred is created // using this AuthConfig object with given host and path "/" and // returns true. - bool activateBasicCred - (const std::string& host, - uint16_t port, - const std::string& path, - const Option* op); + bool activateBasicCred(const std::string& host, uint16_t port, + const std::string& path, const Option* op); // Find a BasicCred using host, port and path and return the // iterator pointing to it. If not found, then return // basicCreds_.end(). - BasicCredSet::iterator - findBasicCred - (const std::string& host, - uint16_t port, - const std::string& path); + BasicCredSet::iterator findBasicCred(const std::string& host, uint16_t port, + const std::string& path); // If the same BasicCred is already added, then it is replaced with // given basicCred. Otherwise, insert given basicCred to diff --git a/src/AuthResolver.h b/src/AuthResolver.h index c02e5ec5..86438f9f 100644 --- a/src/AuthResolver.h +++ b/src/AuthResolver.h @@ -48,8 +48,8 @@ class AuthResolver { public: virtual ~AuthResolver() {} - virtual std::unique_ptr resolveAuthConfig - (const std::string& hostname) = 0; + virtual std::unique_ptr + resolveAuthConfig(const std::string& hostname) = 0; }; } // namespace aria2 diff --git a/src/AutoSaveCommand.cc b/src/AutoSaveCommand.cc index 400a55dc..b0471f0d 100644 --- a/src/AutoSaveCommand.cc +++ b/src/AutoSaveCommand.cc @@ -40,15 +40,16 @@ namespace aria2 { AutoSaveCommand::AutoSaveCommand(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) - : TimeBasedCommand(cuid, e, std::move(interval), true) -{} + : TimeBasedCommand(cuid, e, std::move(interval), true) +{ +} AutoSaveCommand::~AutoSaveCommand() {} void AutoSaveCommand::preProcess() { - if(getDownloadEngine()->getRequestGroupMan()->downloadFinished() || - getDownloadEngine()->isHaltRequested()) { + if (getDownloadEngine()->getRequestGroupMan()->downloadFinished() || + getDownloadEngine()->isHaltRequested()) { enableExit(); } } diff --git a/src/AutoSaveCommand.h b/src/AutoSaveCommand.h index 591246a0..66b97398 100644 --- a/src/AutoSaveCommand.h +++ b/src/AutoSaveCommand.h @@ -39,8 +39,7 @@ namespace aria2 { -class AutoSaveCommand : public TimeBasedCommand -{ +class AutoSaveCommand : public TimeBasedCommand { public: AutoSaveCommand(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval); diff --git a/src/BackupIPv4ConnectCommand.cc b/src/BackupIPv4ConnectCommand.cc index 66eaf6a9..61ef9e28 100644 --- a/src/BackupIPv4ConnectCommand.cc +++ b/src/BackupIPv4ConnectCommand.cc @@ -45,24 +45,22 @@ namespace aria2 { -BackupConnectInfo::BackupConnectInfo() - : cancel(false) -{} +BackupConnectInfo::BackupConnectInfo() : cancel(false) {} -BackupIPv4ConnectCommand::BackupIPv4ConnectCommand -(cuid_t cuid, const std::string& ipaddr, uint16_t port, - const std::shared_ptr& info, Command* mainCommand, - RequestGroup* requestGroup, DownloadEngine* e) -: Command(cuid), - ipaddr_(ipaddr), - port_(port), - info_(info), - mainCommand_(mainCommand), - requestGroup_(requestGroup), - e_(e), - startTime_(global::wallclock()), - timeoutCheck_(global::wallclock()), - timeout_(requestGroup_->getOption()->getAsInt(PREF_CONNECT_TIMEOUT)) +BackupIPv4ConnectCommand::BackupIPv4ConnectCommand( + cuid_t cuid, const std::string& ipaddr, uint16_t port, + const std::shared_ptr& info, Command* mainCommand, + RequestGroup* requestGroup, DownloadEngine* e) + : Command(cuid), + ipaddr_(ipaddr), + port_(port), + info_(info), + mainCommand_(mainCommand), + requestGroup_(requestGroup), + e_(e), + startTime_(global::wallclock()), + timeoutCheck_(global::wallclock()), + timeout_(requestGroup_->getOption()->getAsInt(PREF_CONNECT_TIMEOUT)) { requestGroup_->increaseStreamCommand(); requestGroup_->increaseNumCommand(); @@ -72,7 +70,7 @@ BackupIPv4ConnectCommand::~BackupIPv4ConnectCommand() { requestGroup_->decreaseNumCommand(); requestGroup_->decreaseStreamCommand(); - if(socket_) { + if (socket_) { e_->deleteSocketForWriteCheck(socket_, this); } } @@ -80,60 +78,68 @@ BackupIPv4ConnectCommand::~BackupIPv4ConnectCommand() bool BackupIPv4ConnectCommand::execute() { bool retval = false; - if(requestGroup_->downloadFinished() || requestGroup_->isHaltRequested()) { + if (requestGroup_->downloadFinished() || requestGroup_->isHaltRequested()) { retval = true; - } else if(info_->cancel) { - A2_LOG_INFO(fmt("CUID#%" PRId64 " - Backup connection canceled", - getCuid())); + } + else if (info_->cancel) { + A2_LOG_INFO( + fmt("CUID#%" PRId64 " - Backup connection canceled", getCuid())); retval = true; - } else if(socket_) { - if(writeEventEnabled()) { + } + else if (socket_) { + if (writeEventEnabled()) { try { std::string error = socket_->getSocketError(); - if(error.empty()) { + if (error.empty()) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - Backup connection to %s " - "established", getCuid(), ipaddr_.c_str())); + "established", + getCuid(), ipaddr_.c_str())); info_->ipaddr = ipaddr_; e_->deleteSocketForWriteCheck(socket_, this); info_->socket.swap(socket_); mainCommand_->setStatus(STATUS_ONESHOT_REALTIME); e_->setNoWait(true); retval = true; - } else { + } + else { A2_LOG_INFO(fmt("CUID#%" PRId64 " - Backup connection failed: %s", getCuid(), error.c_str())); retval = true; } - } catch(RecoverableException& e) { - A2_LOG_INFO_EX(fmt("CUID#%" PRId64 " - Backup connection failed", - getCuid()), e); + } + catch (RecoverableException& e) { + A2_LOG_INFO_EX( + fmt("CUID#%" PRId64 " - Backup connection failed", getCuid()), e); retval = true; } } - } else if(!socket_) { + } + else if (!socket_) { // TODO Although we check 300ms initial timeout as described in // RFC 6555, the interval will be much longer and around 1 second // due to the refresh interval mechanism in DownloadEngine. - if(startTime_.difference(global::wallclock()) >= - std::chrono::milliseconds(300)) { + if (startTime_.difference(global::wallclock()) >= + std::chrono::milliseconds(300)) { socket_ = std::make_shared(); try { socket_->establishConnection(ipaddr_, port_); e_->addSocketForWriteCheck(socket_, this); timeoutCheck_ = global::wallclock(); - } catch(RecoverableException& e) { - A2_LOG_INFO_EX(fmt("CUID#%" PRId64 " - Backup connection failed", - getCuid()), e); + } + catch (RecoverableException& e) { + A2_LOG_INFO_EX( + fmt("CUID#%" PRId64 " - Backup connection failed", getCuid()), e); socket_.reset(); retval = true; } } - } else if(timeoutCheck_.difference(global::wallclock()) >= timeout_) { - A2_LOG_INFO(fmt("CUID#%" PRId64 " - Backup connection command timeout", - getCuid())); + } + else if (timeoutCheck_.difference(global::wallclock()) >= timeout_) { + A2_LOG_INFO( + fmt("CUID#%" PRId64 " - Backup connection command timeout", getCuid())); retval = true; } - if(!retval) { + if (!retval) { e_->addCommand(std::unique_ptr(this)); } return retval; diff --git a/src/BackupIPv4ConnectCommand.h b/src/BackupIPv4ConnectCommand.h index 8ae50e06..0c4f8365 100644 --- a/src/BackupIPv4ConnectCommand.h +++ b/src/BackupIPv4ConnectCommand.h @@ -64,13 +64,14 @@ struct BackupConnectInfo { // "Happy Eyeballs" implementation. class BackupIPv4ConnectCommand : public Command { public: - BackupIPv4ConnectCommand(cuid_t cuid, - const std::string& ipaddr, uint16_t port, + BackupIPv4ConnectCommand(cuid_t cuid, const std::string& ipaddr, + uint16_t port, const std::shared_ptr& info, - Command* mainCommand, - RequestGroup* requestGroup, DownloadEngine* e); + Command* mainCommand, RequestGroup* requestGroup, + DownloadEngine* e); ~BackupIPv4ConnectCommand(); virtual bool execute() CXX11_OVERRIDE; + private: std::string ipaddr_; uint16_t port_; diff --git a/src/BencodeParser.cc b/src/BencodeParser.cc index 84d94322..f5423072 100644 --- a/src/BencodeParser.cc +++ b/src/BencodeParser.cc @@ -60,53 +60,54 @@ enum { } // namespace BencodeParser::BencodeParser(StructParserStateMachine* psm) - : psm_(psm), - currentState_(BENCODE_INITIAL), - strLength_(0), - numberSign_(1), - number_(0), - numConsumed_(0), - lastError_(0) + : psm_(psm), + currentState_(BENCODE_INITIAL), + strLength_(0), + numberSign_(1), + number_(0), + numConsumed_(0), + lastError_(0) { stateStack_.push(BENCODE_FINISH); } -BencodeParser::~BencodeParser() -{} +BencodeParser::~BencodeParser() {} ssize_t BencodeParser::parseUpdate(const char* data, size_t size) { size_t i; - if(currentState_ == BENCODE_FINISH) { + if (currentState_ == BENCODE_FINISH) { return 0; - } else if(currentState_ == BENCODE_ERROR) { + } + else if (currentState_ == BENCODE_ERROR) { return lastError_; } - for(i = 0; i < size && currentState_ != BENCODE_FINISH; ++i) { + for (i = 0; i < size && currentState_ != BENCODE_FINISH; ++i) { char c = data[i]; - switch(currentState_) { + switch (currentState_) { case BENCODE_LIST: - if(c == 'e') { + if (c == 'e') { onListEnd(); break; - } else { + } + else { int rv = pushState(currentState_); - if(rv < 0) { + if (rv < 0) { return rv; } currentState_ = BENCODE_VALUE; runBeginCallback(STRUCT_ARRAY_DATA_T); } - // Fall through + // Fall through case BENCODE_INITIAL: case BENCODE_VALUE: - switch(c) { + switch (c) { case 'd': { currentState_ = BENCODE_DICT_KEY; runBeginCallback(STRUCT_DICT_T); break; } - case'l': + case 'l': currentState_ = BENCODE_LIST; runBeginCallback(STRUCT_ARRAY_T); break; @@ -118,25 +119,26 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) runBeginCallback(STRUCT_NUMBER_T); break; default: - if(util::isDigit(c)) { + if (util::isDigit(c)) { strLength_ = c - '0'; numConsumed_ = 1; currentState_ = BENCODE_STRING_LEN; runBeginCallback(STRUCT_STRING_T); break; - } else { + } + else { currentState_ = BENCODE_ERROR; return lastError_ = ERR_UNEXPECTED_CHAR_BEFORE_VAL; } } break; case BENCODE_DICT_KEY: { - if(c == 'e') { + if (c == 'e') { onDictEnd(); break; } int rv = pushState(currentState_); - if(rv < 0) { + if (rv < 0) { return rv; } strLength_ = 0; @@ -147,8 +149,8 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) } case BENCODE_STRING_LEN: { size_t j; - for(j = i; j < size && in(data[j], '0', '9'); ++j) { - if((INT64_MAX - (data[j] - '0'))/ 10 < strLength_) { + for (j = i; j < size && in(data[j], '0', '9'); ++j) { + if ((INT64_MAX - (data[j] - '0')) / 10 < strLength_) { currentState_ = BENCODE_ERROR; return lastError_ = ERR_STRING_LENGTH_OUT_OF_RANGE; } @@ -156,18 +158,19 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) strLength_ += data[j] - '0'; } numConsumed_ += j - i; - if(j != size) { - if(data[j] != ':' || numConsumed_ == 0) { + if (j != size) { + if (data[j] != ':' || numConsumed_ == 0) { currentState_ = BENCODE_ERROR; return lastError_ = ERR_INVALID_STRING_LENGTH; } i = j; currentState_ = BENCODE_STRING; - if(strLength_ == 0) { + if (strLength_ == 0) { runCharactersCallback(nullptr, 0); onStringEnd(); } - } else { + } + else { i = j - 1; } break; @@ -177,13 +180,13 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) runCharactersCallback(&data[i], nread); strLength_ -= nread; i += nread - 1; - if(strLength_ == 0) { + if (strLength_ == 0) { onStringEnd(); } break; } case BENCODE_NUMBER_SIGN: { - switch(c) { + switch (c) { case '+': numberSign_ = 1; currentState_ = BENCODE_NUMBER; @@ -193,7 +196,7 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) currentState_ = BENCODE_NUMBER; break; default: - if(util::isDigit(c)) { + if (util::isDigit(c)) { number_ = c - '0'; numConsumed_ = 1; currentState_ = BENCODE_NUMBER; @@ -203,8 +206,8 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) } case BENCODE_NUMBER: { size_t j; - for(j = i; j < size && in(data[j], '0', '9'); ++j) { - if((INT64_MAX - (data[j] - '0'))/ 10 < number_) { + for (j = i; j < size && in(data[j], '0', '9'); ++j) { + if ((INT64_MAX - (data[j] - '0')) / 10 < number_) { currentState_ = BENCODE_ERROR; return lastError_ = ERR_NUMBER_OUT_OF_RANGE; } @@ -212,14 +215,15 @@ ssize_t BencodeParser::parseUpdate(const char* data, size_t size) number_ += data[j] - '0'; } numConsumed_ += j - i; - if(j != size) { - if(data[j] != 'e' || numConsumed_ == 0) { + if (j != size) { + if (data[j] != 'e' || numConsumed_ == 0) { currentState_ = BENCODE_ERROR; return lastError_ = ERR_INVALID_NUMBER; } i = j; onNumberEnd(); - } else { + } + else { i = j - 1; } break; @@ -233,9 +237,8 @@ ssize_t BencodeParser::parseFinal(const char* data, size_t len) { ssize_t rv; rv = parseUpdate(data, len); - if(rv >= 0) { - if(currentState_ != BENCODE_FINISH && - currentState_ != BENCODE_INITIAL) { + if (rv >= 0) { + if (currentState_ != BENCODE_FINISH && currentState_ != BENCODE_INITIAL) { rv = ERR_PREMATURE_DATA; } } @@ -247,7 +250,7 @@ void BencodeParser::reset() psm_->reset(); currentState_ = BENCODE_INITIAL; lastError_ = 0; - while(!stateStack_.empty()) { + while (!stateStack_.empty()) { stateStack_.pop(); } stateStack_.push(BENCODE_FINISH); @@ -255,8 +258,8 @@ void BencodeParser::reset() void BencodeParser::onStringEnd() { - runEndCallback(stateTop() == BENCODE_DICT_KEY ? - STRUCT_DICT_KEY_T : STRUCT_STRING_T); + runEndCallback(stateTop() == BENCODE_DICT_KEY ? STRUCT_DICT_KEY_T + : STRUCT_STRING_T); onValueEnd(); } @@ -281,7 +284,7 @@ void BencodeParser::onListEnd() void BencodeParser::onValueEnd() { - switch(stateTop()) { + switch (stateTop()) { case BENCODE_DICT_KEY: popState(); pushState(BENCODE_DICT_VAL); @@ -307,18 +310,16 @@ void BencodeParser::onValueEnd() int BencodeParser::pushState(int state) { - if(stateStack_.size() >= 50) { + if (stateStack_.size() >= 50) { return ERR_STRUCTURE_TOO_DEEP; - } else { + } + else { stateStack_.push(state); return 0; } } -int BencodeParser::stateTop() const -{ - return stateStack_.top(); -} +int BencodeParser::stateTop() const { return stateStack_.top(); } int BencodeParser::popState() { diff --git a/src/BencodeParser.h b/src/BencodeParser.h index eb1c4d67..c6b7debd 100644 --- a/src/BencodeParser.h +++ b/src/BencodeParser.h @@ -72,6 +72,7 @@ public: // Resets the internal state of the parser and makes it ready for // reuse. void reset(); + private: int pushState(int state); int stateTop() const; diff --git a/src/BitfieldMan.cc b/src/BitfieldMan.cc index c1904205..8eb1bc16 100644 --- a/src/BitfieldMan.cc +++ b/src/BitfieldMan.cc @@ -45,23 +45,23 @@ using namespace aria2::expr; namespace aria2 { BitfieldMan::BitfieldMan(int32_t blockLength, int64_t totalLength) - : totalLength_(totalLength), - cachedCompletedLength_(0), - cachedFilteredCompletedLength_(0), - cachedFilteredTotalLength_(0), - bitfield_(nullptr), - useBitfield_(nullptr), - filterBitfield_(nullptr), - bitfieldLength_(0), - cachedNumMissingBlock_(0), - cachedNumFilteredBlock_(0), - blocks_(0), - blockLength_(blockLength), - filterEnabled_(false) -{ - if(blockLength_ > 0 && totalLength_ > 0) { - blocks_ = (totalLength_+blockLength_-1)/blockLength_; - bitfieldLength_ = blocks_/8+(blocks_%8 ? 1 : 0); + : totalLength_(totalLength), + cachedCompletedLength_(0), + cachedFilteredCompletedLength_(0), + cachedFilteredTotalLength_(0), + bitfield_(nullptr), + useBitfield_(nullptr), + filterBitfield_(nullptr), + bitfieldLength_(0), + cachedNumMissingBlock_(0), + cachedNumFilteredBlock_(0), + blocks_(0), + blockLength_(blockLength), + filterEnabled_(false) +{ + if (blockLength_ > 0 && totalLength_ > 0) { + blocks_ = (totalLength_ + blockLength_ - 1) / blockLength_; + bitfieldLength_ = blocks_ / 8 + (blocks_ % 8 ? 1 : 0); bitfield_ = new unsigned char[bitfieldLength_]; useBitfield_ = new unsigned char[bitfieldLength_]; memset(bitfield_, 0, bitfieldLength_); @@ -71,23 +71,23 @@ BitfieldMan::BitfieldMan(int32_t blockLength, int64_t totalLength) } BitfieldMan::BitfieldMan(const BitfieldMan& bitfieldMan) - : totalLength_(bitfieldMan.totalLength_), - cachedCompletedLength_(0), - cachedFilteredCompletedLength_(0), - cachedFilteredTotalLength_(0), - bitfield_(new unsigned char[bitfieldMan.bitfieldLength_]), - useBitfield_(new unsigned char[bitfieldMan.bitfieldLength_]), - filterBitfield_(nullptr), - bitfieldLength_(bitfieldMan.bitfieldLength_), - cachedNumMissingBlock_(0), - cachedNumFilteredBlock_(0), - blocks_(bitfieldMan.blocks_), - blockLength_(bitfieldMan.blockLength_), - filterEnabled_(bitfieldMan.filterEnabled_) + : totalLength_(bitfieldMan.totalLength_), + cachedCompletedLength_(0), + cachedFilteredCompletedLength_(0), + cachedFilteredTotalLength_(0), + bitfield_(new unsigned char[bitfieldMan.bitfieldLength_]), + useBitfield_(new unsigned char[bitfieldMan.bitfieldLength_]), + filterBitfield_(nullptr), + bitfieldLength_(bitfieldMan.bitfieldLength_), + cachedNumMissingBlock_(0), + cachedNumFilteredBlock_(0), + blocks_(bitfieldMan.blocks_), + blockLength_(bitfieldMan.blockLength_), + filterEnabled_(bitfieldMan.filterEnabled_) { memcpy(bitfield_, bitfieldMan.bitfield_, bitfieldLength_); memcpy(useBitfield_, bitfieldMan.useBitfield_, bitfieldLength_); - if(filterEnabled_) { + if (filterEnabled_) { filterBitfield_ = new unsigned char[bitfieldLength_]; memcpy(filterBitfield_, bitfieldMan.filterBitfield_, bitfieldLength_); } @@ -96,26 +96,27 @@ BitfieldMan::BitfieldMan(const BitfieldMan& bitfieldMan) BitfieldMan& BitfieldMan::operator=(const BitfieldMan& bitfieldMan) { - if(this != &bitfieldMan) { + if (this != &bitfieldMan) { totalLength_ = bitfieldMan.totalLength_; blockLength_ = bitfieldMan.blockLength_; blocks_ = bitfieldMan.blocks_; bitfieldLength_ = bitfieldMan.bitfieldLength_; filterEnabled_ = bitfieldMan.filterEnabled_; - delete [] bitfield_; + delete[] bitfield_; bitfield_ = new unsigned char[bitfieldLength_]; memcpy(bitfield_, bitfieldMan.bitfield_, bitfieldLength_); - delete [] useBitfield_; + delete[] useBitfield_; useBitfield_ = new unsigned char[bitfieldLength_]; memcpy(useBitfield_, bitfieldMan.useBitfield_, bitfieldLength_); - delete [] filterBitfield_; - if(filterEnabled_) { + delete[] filterBitfield_; + if (filterEnabled_) { filterBitfield_ = new unsigned char[bitfieldLength_]; memcpy(filterBitfield_, bitfieldMan.filterBitfield_, bitfieldLength_); - } else { + } + else { filterBitfield_ = nullptr; } @@ -124,41 +125,44 @@ BitfieldMan& BitfieldMan::operator=(const BitfieldMan& bitfieldMan) return *this; } -BitfieldMan::~BitfieldMan() { - delete [] bitfield_; - delete [] useBitfield_; - delete [] filterBitfield_; +BitfieldMan::~BitfieldMan() +{ + delete[] bitfield_; + delete[] useBitfield_; + delete[] filterBitfield_; } int32_t BitfieldMan::getLastBlockLength() const { - return totalLength_-blockLength_*(blocks_-1); + return totalLength_ - blockLength_ * (blocks_ - 1); } int32_t BitfieldMan::getBlockLength(size_t index) const { - if(index == blocks_-1) { + if (index == blocks_ - 1) { return getLastBlockLength(); - } else if(index < blocks_-1) { + } + else if (index < blocks_ - 1) { return getBlockLength(); - } else { + } + else { return 0; } } -bool BitfieldMan::hasMissingPiece -(const unsigned char* peerBitfield, size_t length) const +bool BitfieldMan::hasMissingPiece(const unsigned char* peerBitfield, + size_t length) const { - if(bitfieldLength_ != length) { + if (bitfieldLength_ != length) { return false; } bool retval = false; - for(size_t i = 0; i < bitfieldLength_; ++i) { + for (size_t i = 0; i < bitfieldLength_; ++i) { unsigned char temp = peerBitfield[i] & ~bitfield_[i]; - if(filterEnabled_) { + if (filterEnabled_) { temp &= filterBitfield_[i]; } - if(temp&0xffu) { + if (temp & 0xffu) { retval = true; break; } @@ -168,58 +172,66 @@ bool BitfieldMan::hasMissingPiece bool BitfieldMan::getFirstMissingUnusedIndex(size_t& index) const { - if(filterEnabled_) { - return bitfield::getFirstSetBitIndex - (index, ~array(bitfield_)&~array(useBitfield_)&array(filterBitfield_), - blocks_); - } else { - return bitfield::getFirstSetBitIndex - (index, ~array(bitfield_)&~array(useBitfield_), blocks_); + if (filterEnabled_) { + return bitfield::getFirstSetBitIndex(index, ~array(bitfield_) & + ~array(useBitfield_) & + array(filterBitfield_), + blocks_); + } + else { + return bitfield::getFirstSetBitIndex( + index, ~array(bitfield_) & ~array(useBitfield_), blocks_); } } -size_t BitfieldMan::getFirstNMissingUnusedIndex -(std::vector& out, size_t n) const +size_t BitfieldMan::getFirstNMissingUnusedIndex(std::vector& out, + size_t n) const { - if(filterEnabled_) { - return bitfield::getFirstNSetBitIndex - (std::back_inserter(out), n, - ~array(bitfield_)&~array(useBitfield_)&array(filterBitfield_), blocks_); - } else { - return bitfield::getFirstNSetBitIndex - (std::back_inserter(out), n, - ~array(bitfield_)&~array(useBitfield_), blocks_); + if (filterEnabled_) { + return bitfield::getFirstNSetBitIndex( + std::back_inserter(out), n, + ~array(bitfield_) & ~array(useBitfield_) & array(filterBitfield_), + blocks_); + } + else { + return bitfield::getFirstNSetBitIndex( + std::back_inserter(out), n, ~array(bitfield_) & ~array(useBitfield_), + blocks_); } } bool BitfieldMan::getFirstMissingIndex(size_t& index) const { - if(filterEnabled_) { - return bitfield::getFirstSetBitIndex - (index, ~array(bitfield_)&array(filterBitfield_), blocks_); - } else { + if (filterEnabled_) { + return bitfield::getFirstSetBitIndex( + index, ~array(bitfield_) & array(filterBitfield_), blocks_); + } + else { return bitfield::getFirstSetBitIndex(index, ~array(bitfield_), blocks_); } } namespace { -template -size_t getStartIndex(size_t index, const Array& bitfield, size_t blocks) { - while(index < blocks && bitfield::test(bitfield, blocks, index)) { +template +size_t getStartIndex(size_t index, const Array& bitfield, size_t blocks) +{ + while (index < blocks && bitfield::test(bitfield, blocks, index)) { ++index; } - if(blocks <= index) { + if (blocks <= index) { return blocks; - } else { + } + else { return index; } } } // namespace namespace { -template -size_t getEndIndex(size_t index, const Array& bitfield, size_t blocks) { - while(index < blocks && !bitfield::test(bitfield, blocks, index)) { +template +size_t getEndIndex(size_t index, const Array& bitfield, size_t blocks) +{ + while (index < blocks && !bitfield::test(bitfield, blocks, index)) { ++index; } return index; @@ -227,191 +239,178 @@ size_t getEndIndex(size_t index, const Array& bitfield, size_t blocks) { } // namespace namespace { -template -bool getSparseMissingUnusedIndex -(size_t& index, - int32_t minSplitSize, - const Array& bitfield, - const unsigned char* useBitfield, - int32_t blockLength, - size_t blocks) +template +bool getSparseMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const Array& bitfield, + const unsigned char* useBitfield, + int32_t blockLength, size_t blocks) { BitfieldMan::Range maxRange; BitfieldMan::Range currentRange; size_t nextIndex = 0; - while(nextIndex < blocks) { - currentRange.startIndex = - getStartIndex(nextIndex, bitfield, blocks); - if(currentRange.startIndex == blocks) { + while (nextIndex < blocks) { + currentRange.startIndex = getStartIndex(nextIndex, bitfield, blocks); + if (currentRange.startIndex == blocks) { break; } currentRange.endIndex = - getEndIndex(currentRange.startIndex, bitfield, blocks); + getEndIndex(currentRange.startIndex, bitfield, blocks); - if(currentRange.startIndex > 0) { - if(bitfield::test(useBitfield, blocks, currentRange.startIndex-1)) { + if (currentRange.startIndex > 0) { + if (bitfield::test(useBitfield, blocks, currentRange.startIndex - 1)) { currentRange.startIndex = currentRange.getMidIndex(); } } // If range is equal, choose a range where its startIndex-1 is // set. - if(maxRange < currentRange || - (maxRange == currentRange && - maxRange.startIndex > 0 && currentRange.startIndex > 0 && - (!bitfield::test(bitfield, blocks, maxRange.startIndex-1) || - bitfield::test(useBitfield, blocks, maxRange.startIndex-1)) - && - bitfield::test(bitfield, blocks, currentRange.startIndex-1) && - !bitfield::test(useBitfield, blocks, currentRange.startIndex-1))) { + if (maxRange < currentRange || + (maxRange == currentRange && maxRange.startIndex > 0 && + currentRange.startIndex > 0 && + (!bitfield::test(bitfield, blocks, maxRange.startIndex - 1) || + bitfield::test(useBitfield, blocks, maxRange.startIndex - 1)) && + bitfield::test(bitfield, blocks, currentRange.startIndex - 1) && + !bitfield::test(useBitfield, blocks, currentRange.startIndex - 1))) { maxRange = currentRange; } nextIndex = currentRange.endIndex; - } - if(maxRange.getSize()) { - if(maxRange.startIndex == 0) { + if (maxRange.getSize()) { + if (maxRange.startIndex == 0) { index = 0; return true; - } else { - if((!bitfield::test(useBitfield, blocks, maxRange.startIndex-1) && - bitfield::test(bitfield, blocks, maxRange.startIndex-1)) || - (static_cast(maxRange.endIndex-maxRange.startIndex)* - blockLength >= minSplitSize)) { + } + else { + if ((!bitfield::test(useBitfield, blocks, maxRange.startIndex - 1) && + bitfield::test(bitfield, blocks, maxRange.startIndex - 1)) || + (static_cast(maxRange.endIndex - maxRange.startIndex) * + blockLength >= + minSplitSize)) { index = maxRange.startIndex; return true; - } else { + } + else { return false; } } - } else { + } + else { return false; } } } // namespace -bool BitfieldMan::getSparseMissingUnusedIndex -(size_t& index, - int32_t minSplitSize, - const unsigned char* ignoreBitfield, - size_t ignoreBitfieldLength) const +bool BitfieldMan::getSparseMissingUnusedIndex( + size_t& index, int32_t minSplitSize, const unsigned char* ignoreBitfield, + size_t ignoreBitfieldLength) const { - if(filterEnabled_) { - return aria2::getSparseMissingUnusedIndex - (index, minSplitSize, - array(ignoreBitfield)|~array(filterBitfield_)| - array(bitfield_)|array(useBitfield_), - useBitfield_, blockLength_, blocks_); - } else { - return aria2::getSparseMissingUnusedIndex - (index, minSplitSize, - array(ignoreBitfield)|array(bitfield_)|array(useBitfield_), - useBitfield_, blockLength_, blocks_); + if (filterEnabled_) { + return aria2::getSparseMissingUnusedIndex( + index, minSplitSize, array(ignoreBitfield) | ~array(filterBitfield_) | + array(bitfield_) | array(useBitfield_), + useBitfield_, blockLength_, blocks_); + } + else { + return aria2::getSparseMissingUnusedIndex( + index, minSplitSize, + array(ignoreBitfield) | array(bitfield_) | array(useBitfield_), + useBitfield_, blockLength_, blocks_); } } namespace { -template -bool getGeomMissingUnusedIndex -(size_t& index, - int32_t minSplitSize, - const Array& bitfield, - const unsigned char* useBitfield, - int32_t blockLength, - size_t blocks, - double base, - size_t offsetIndex) +template +bool getGeomMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const Array& bitfield, + const unsigned char* useBitfield, + int32_t blockLength, size_t blocks, double base, + size_t offsetIndex) { double start = 0; double end = 1; - while(start+offsetIndex < blocks) { + while (start + offsetIndex < blocks) { index = blocks; - for(size_t i = start+offsetIndex, - eoi = std::min(blocks, static_cast(end+offsetIndex)); - i < eoi; ++i) { - if(bitfield::test(useBitfield, blocks, i)) { + for (size_t i = start + offsetIndex, + eoi = std::min(blocks, static_cast(end + offsetIndex)); + i < eoi; ++i) { + if (bitfield::test(useBitfield, blocks, i)) { break; - } else if(!bitfield::test(bitfield, blocks, i)) { + } + else if (!bitfield::test(bitfield, blocks, i)) { index = i; break; } } - if(index < blocks) { + if (index < blocks) { return true; - } else { + } + else { start = end; end *= base; } } - return getSparseMissingUnusedIndex(index, minSplitSize, - bitfield, useBitfield, + return getSparseMissingUnusedIndex(index, minSplitSize, bitfield, useBitfield, blockLength, blocks); } } // namespace -bool BitfieldMan::getGeomMissingUnusedIndex -(size_t& index, - int32_t minSplitSize, - const unsigned char* ignoreBitfield, - size_t ignoreBitfieldLength, - double base, - size_t offsetIndex) const -{ - if(filterEnabled_) { - return aria2::getGeomMissingUnusedIndex - (index, minSplitSize, - array(ignoreBitfield)|~array(filterBitfield_)| - array(bitfield_)|array(useBitfield_), - useBitfield_, blockLength_, blocks_, - base, offsetIndex); - } else { - return aria2::getGeomMissingUnusedIndex - (index, minSplitSize, - array(ignoreBitfield)|array(bitfield_)|array(useBitfield_), - useBitfield_, blockLength_, blocks_, - base, offsetIndex); +bool BitfieldMan::getGeomMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const unsigned char* ignoreBitfield, + size_t ignoreBitfieldLength, + double base, + size_t offsetIndex) const +{ + if (filterEnabled_) { + return aria2::getGeomMissingUnusedIndex( + index, minSplitSize, array(ignoreBitfield) | ~array(filterBitfield_) | + array(bitfield_) | array(useBitfield_), + useBitfield_, blockLength_, blocks_, base, offsetIndex); + } + else { + return aria2::getGeomMissingUnusedIndex( + index, minSplitSize, + array(ignoreBitfield) | array(bitfield_) | array(useBitfield_), + useBitfield_, blockLength_, blocks_, base, offsetIndex); } } namespace { -template -bool getInorderMissingUnusedIndex -(size_t& index, - int32_t minSplitSize, - const Array& bitfield, - const unsigned char* useBitfield, - int32_t blockLength, - size_t blocks) +template +bool getInorderMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const Array& bitfield, + const unsigned char* useBitfield, + int32_t blockLength, size_t blocks) { // We always return first piece if it is available. - if(!bitfield::test(bitfield, blocks, 0) && - !bitfield::test(useBitfield, blocks, 0)) { + if (!bitfield::test(bitfield, blocks, 0) && + !bitfield::test(useBitfield, blocks, 0)) { index = 0; return true; } - for(size_t i = 1; i < blocks;) { - if(!bitfield::test(bitfield, blocks, i) && - !bitfield::test(useBitfield, blocks, i)) { + for (size_t i = 1; i < blocks;) { + if (!bitfield::test(bitfield, blocks, i) && + !bitfield::test(useBitfield, blocks, i)) { // If previous piece has already been retrieved, we can download // from this index. - if(!bitfield::test(useBitfield, blocks, i-1) && - bitfield::test(bitfield, blocks, i-1)) { + if (!bitfield::test(useBitfield, blocks, i - 1) && + bitfield::test(bitfield, blocks, i - 1)) { index = i; return true; } // Check free space of minSplitSize. size_t j; - for(j = i; j < blocks; ++j) { - if(bitfield::test(bitfield, blocks, j) || - bitfield::test(useBitfield, blocks, j)) { + for (j = i; j < blocks; ++j) { + if (bitfield::test(bitfield, blocks, j) || + bitfield::test(useBitfield, blocks, j)) { break; } - if(static_cast(j-i+1)*blockLength >= minSplitSize) { + if (static_cast(j - i + 1) * blockLength >= minSplitSize) { index = j; return true; } } - i = j+1; - } else { + i = j + 1; + } + else { ++i; } } @@ -419,50 +418,49 @@ bool getInorderMissingUnusedIndex } } // namespace -bool BitfieldMan::getInorderMissingUnusedIndex -(size_t& index, - int32_t minSplitSize, - const unsigned char* ignoreBitfield, - size_t ignoreBitfieldLength) const +bool BitfieldMan::getInorderMissingUnusedIndex( + size_t& index, int32_t minSplitSize, const unsigned char* ignoreBitfield, + size_t ignoreBitfieldLength) const { - if(filterEnabled_) { - return aria2::getInorderMissingUnusedIndex - (index, minSplitSize, - array(ignoreBitfield)|~array(filterBitfield_)| - array(bitfield_)|array(useBitfield_), - useBitfield_, blockLength_, blocks_); - } else { - return aria2::getInorderMissingUnusedIndex - (index, minSplitSize, - array(ignoreBitfield)|array(bitfield_)|array(useBitfield_), - useBitfield_, blockLength_, blocks_); + if (filterEnabled_) { + return aria2::getInorderMissingUnusedIndex( + index, minSplitSize, array(ignoreBitfield) | ~array(filterBitfield_) | + array(bitfield_) | array(useBitfield_), + useBitfield_, blockLength_, blocks_); + } + else { + return aria2::getInorderMissingUnusedIndex( + index, minSplitSize, + array(ignoreBitfield) | array(bitfield_) | array(useBitfield_), + useBitfield_, blockLength_, blocks_); } } namespace { -template +template bool copyBitfield(unsigned char* dst, const Array& src, size_t blocks) { unsigned char bits = 0; - size_t len = (blocks+7)/8; - for(size_t i = 0; i < len-1; ++i) { + size_t len = (blocks + 7) / 8; + for (size_t i = 0; i < len - 1; ++i) { dst[i] = src[i]; bits |= dst[i]; } - dst[len-1] = src[len-1]&bitfield::lastByteMask(blocks); - bits |= dst[len-1]; + dst[len - 1] = src[len - 1] & bitfield::lastByteMask(blocks); + bits |= dst[len - 1]; return bits != 0; } } // namespace -bool BitfieldMan::getAllMissingIndexes(unsigned char* misbitfield, size_t len) - const +bool BitfieldMan::getAllMissingIndexes(unsigned char* misbitfield, + size_t len) const { assert(len == bitfieldLength_); - if(filterEnabled_) { - return copyBitfield - (misbitfield, ~array(bitfield_)&array(filterBitfield_), blocks_); - } else { + if (filterEnabled_) { + return copyBitfield(misbitfield, ~array(bitfield_) & array(filterBitfield_), + blocks_); + } + else { return copyBitfield(misbitfield, ~array(bitfield_), blocks_); } } @@ -472,18 +470,17 @@ bool BitfieldMan::getAllMissingIndexes(unsigned char* misbitfield, size_t len, size_t peerBitfieldLength) const { assert(len == bitfieldLength_); - if(bitfieldLength_ != peerBitfieldLength) { + if (bitfieldLength_ != peerBitfieldLength) { return false; } - if(filterEnabled_) { - return copyBitfield - (misbitfield, - ~array(bitfield_)&array(peerBitfield)&array(filterBitfield_), - blocks_); - } else { - return copyBitfield - (misbitfield, ~array(bitfield_)&array(peerBitfield), - blocks_); + if (filterEnabled_) { + return copyBitfield(misbitfield, ~array(bitfield_) & array(peerBitfield) & + array(filterBitfield_), + blocks_); + } + else { + return copyBitfield(misbitfield, ~array(bitfield_) & array(peerBitfield), + blocks_); } } @@ -493,102 +490,112 @@ bool BitfieldMan::getAllMissingUnusedIndexes(unsigned char* misbitfield, size_t peerBitfieldLength) const { assert(len == bitfieldLength_); - if(bitfieldLength_ != peerBitfieldLength) { + if (bitfieldLength_ != peerBitfieldLength) { return false; } - if(filterEnabled_) { - return copyBitfield - (misbitfield, - ~array(bitfield_)&~array(useBitfield_)&array(peerBitfield)& - array(filterBitfield_), - blocks_); - } else { - return copyBitfield - (misbitfield, - ~array(bitfield_)&~array(useBitfield_)&array(peerBitfield), - blocks_); + if (filterEnabled_) { + return copyBitfield(misbitfield, + ~array(bitfield_) & ~array(useBitfield_) & + array(peerBitfield) & array(filterBitfield_), + blocks_); + } + else { + return copyBitfield(misbitfield, ~array(bitfield_) & ~array(useBitfield_) & + array(peerBitfield), + blocks_); } } -size_t BitfieldMan::countMissingBlock() const { - return cachedNumMissingBlock_; -} +size_t BitfieldMan::countMissingBlock() const { return cachedNumMissingBlock_; } -size_t BitfieldMan::countMissingBlockNow() const { - if(filterEnabled_) { +size_t BitfieldMan::countMissingBlockNow() const +{ + if (filterEnabled_) { return bitfield::countSetBit(filterBitfield_, blocks_) - - bitfield::countSetBitSlow(array(bitfield_)&array(filterBitfield_), - blocks_); - } else { - return blocks_-bitfield::countSetBit(bitfield_, blocks_); + bitfield::countSetBitSlow(array(bitfield_) & array(filterBitfield_), + blocks_); + } + else { + return blocks_ - bitfield::countSetBit(bitfield_, blocks_); } } -size_t BitfieldMan::countFilteredBlockNow() const { - if(filterEnabled_) { +size_t BitfieldMan::countFilteredBlockNow() const +{ + if (filterEnabled_) { return bitfield::countSetBit(filterBitfield_, blocks_); - } else { + } + else { return 0; } } -bool BitfieldMan::setBitInternal(unsigned char* bitfield, size_t index, bool on) { - if(blocks_ <= index) { return false; } - unsigned char mask = 128 >> (index%8); - if(on) { - bitfield[index/8] |= mask; - } else { - bitfield[index/8] &= ~mask; +bool BitfieldMan::setBitInternal(unsigned char* bitfield, size_t index, bool on) +{ + if (blocks_ <= index) { + return false; + } + unsigned char mask = 128 >> (index % 8); + if (on) { + bitfield[index / 8] |= mask; + } + else { + bitfield[index / 8] &= ~mask; } return true; } -bool BitfieldMan::setUseBit(size_t index) { +bool BitfieldMan::setUseBit(size_t index) +{ return setBitInternal(useBitfield_, index, true); } -bool BitfieldMan::unsetUseBit(size_t index) { +bool BitfieldMan::unsetUseBit(size_t index) +{ return setBitInternal(useBitfield_, index, false); } -bool BitfieldMan::setBit(size_t index) { +bool BitfieldMan::setBit(size_t index) +{ bool b = setBitInternal(bitfield_, index, true); updateCache(); return b; } -bool BitfieldMan::unsetBit(size_t index) { +bool BitfieldMan::unsetBit(size_t index) +{ bool b = setBitInternal(bitfield_, index, false); updateCache(); return b; } -bool BitfieldMan::isFilteredAllBitSet() const { - if(filterEnabled_) { - for(size_t i = 0; i < bitfieldLength_; ++i) { - if((bitfield_[i]&filterBitfield_[i]) != filterBitfield_[i]) { +bool BitfieldMan::isFilteredAllBitSet() const +{ + if (filterEnabled_) { + for (size_t i = 0; i < bitfieldLength_; ++i) { + if ((bitfield_[i] & filterBitfield_[i]) != filterBitfield_[i]) { return false; } } return true; - } else { + } + else { return isAllBitSet(); } } namespace { -bool testAllBitSet -(const unsigned char* bitfield, size_t length, size_t blocks) +bool testAllBitSet(const unsigned char* bitfield, size_t length, size_t blocks) { - if(length == 0) { + if (length == 0) { return true; } - for(size_t i = 0; i < length-1; ++i) { - if(bitfield[i] != 0xffu) { + for (size_t i = 0; i < length - 1; ++i) { + if (bitfield[i] != 0xffu) { return false; } } - return bitfield[length-1] == bitfield::lastByteMask(blocks); + return bitfield[length - 1] == bitfield::lastByteMask(blocks); } } // namespace @@ -599,16 +606,18 @@ bool BitfieldMan::isAllBitSet() const bool BitfieldMan::isAllFilterBitSet() const { - if(!filterBitfield_) { + if (!filterBitfield_) { return false; } return testAllBitSet(filterBitfield_, bitfieldLength_, blocks_); } -bool BitfieldMan::isFilterBitSet(size_t index) const { - if(filterBitfield_) { +bool BitfieldMan::isFilterBitSet(size_t index) const +{ + if (filterBitfield_) { return bitfield::test(filterBitfield_, blocks_, index); - } else { + } + else { return false; } } @@ -623,8 +632,10 @@ bool BitfieldMan::isUseBitSet(size_t index) const return bitfield::test(useBitfield_, blocks_, index); } -void BitfieldMan::setBitfield(const unsigned char* bitfield, size_t bitfieldLength) { - if(bitfieldLength_ != bitfieldLength) { +void BitfieldMan::setBitfield(const unsigned char* bitfield, + size_t bitfieldLength) +{ + if (bitfieldLength_ != bitfieldLength) { return; } memcpy(bitfield_, bitfield, bitfieldLength_); @@ -632,59 +643,66 @@ void BitfieldMan::setBitfield(const unsigned char* bitfield, size_t bitfieldLeng updateCache(); } -void BitfieldMan::clearAllBit() { +void BitfieldMan::clearAllBit() +{ memset(bitfield_, 0, bitfieldLength_); updateCache(); } -void BitfieldMan::setAllBit() { - for(size_t i = 0; i < blocks_; ++i) { +void BitfieldMan::setAllBit() +{ + for (size_t i = 0; i < blocks_; ++i) { setBitInternal(bitfield_, i, true); } updateCache(); } -void BitfieldMan::clearAllUseBit() { +void BitfieldMan::clearAllUseBit() +{ memset(useBitfield_, 0, bitfieldLength_); updateCache(); } -void BitfieldMan::setAllUseBit() { - for(size_t i = 0; i < blocks_; ++i) { +void BitfieldMan::setAllUseBit() +{ + for (size_t i = 0; i < blocks_; ++i) { setBitInternal(useBitfield_, i, true); } } -bool BitfieldMan::setFilterBit(size_t index) { +bool BitfieldMan::setFilterBit(size_t index) +{ return setBitInternal(filterBitfield_, index, true); } void BitfieldMan::ensureFilterBitfield() { - if(!filterBitfield_) { + if (!filterBitfield_) { filterBitfield_ = new unsigned char[bitfieldLength_]; memset(filterBitfield_, 0, bitfieldLength_); } } -void BitfieldMan::addFilter(int64_t offset, int64_t length) { +void BitfieldMan::addFilter(int64_t offset, int64_t length) +{ ensureFilterBitfield(); - if(length > 0) { - size_t startBlock = offset/blockLength_; - size_t endBlock = (offset+length-1)/blockLength_; - for(size_t i = startBlock; i <= endBlock && i < blocks_; i++) { + if (length > 0) { + size_t startBlock = offset / blockLength_; + size_t endBlock = (offset + length - 1) / blockLength_; + for (size_t i = startBlock; i <= endBlock && i < blocks_; i++) { setFilterBit(i); } } updateCache(); } -void BitfieldMan::removeFilter(int64_t offset, int64_t length) { +void BitfieldMan::removeFilter(int64_t offset, int64_t length) +{ ensureFilterBitfield(); - if(length > 0) { - size_t startBlock = offset/blockLength_; - size_t endBlock = (offset+length-1)/blockLength_; - for(size_t i = startBlock; i <= endBlock && i < blocks_; i++) { + if (length > 0) { + size_t startBlock = offset / blockLength_; + size_t endBlock = (offset + length - 1) / blockLength_; + for (size_t i = startBlock; i <= endBlock && i < blocks_; i++) { setBitInternal(filterBitfield_, i, false); } } @@ -694,96 +712,106 @@ void BitfieldMan::removeFilter(int64_t offset, int64_t length) { void BitfieldMan::addNotFilter(int64_t offset, int64_t length) { ensureFilterBitfield(); - if(length > 0 && blocks_ > 0) { - size_t startBlock = offset/blockLength_; - if(blocks_ <= startBlock) { + if (length > 0 && blocks_ > 0) { + size_t startBlock = offset / blockLength_; + if (blocks_ <= startBlock) { startBlock = blocks_; } - size_t endBlock = (offset+length-1)/blockLength_; - for(size_t i = 0; i < startBlock; ++i) { + size_t endBlock = (offset + length - 1) / blockLength_; + for (size_t i = 0; i < startBlock; ++i) { setFilterBit(i); } - for(size_t i = endBlock+1; i < blocks_; ++i) { + for (size_t i = endBlock + 1; i < blocks_; ++i) { setFilterBit(i); } } updateCache(); } -void BitfieldMan::enableFilter() { +void BitfieldMan::enableFilter() +{ ensureFilterBitfield(); filterEnabled_ = true; updateCache(); } -void BitfieldMan::disableFilter() { +void BitfieldMan::disableFilter() +{ filterEnabled_ = false; updateCache(); } -void BitfieldMan::clearFilter() { - if(filterBitfield_) { - delete [] filterBitfield_; +void BitfieldMan::clearFilter() +{ + if (filterBitfield_) { + delete[] filterBitfield_; filterBitfield_ = nullptr; } filterEnabled_ = false; updateCache(); } -int64_t BitfieldMan::getFilteredTotalLengthNow() const { - if(!filterBitfield_) { +int64_t BitfieldMan::getFilteredTotalLengthNow() const +{ + if (!filterBitfield_) { return 0; } size_t filteredBlocks = bitfield::countSetBit(filterBitfield_, blocks_); - if(filteredBlocks == 0) { + if (filteredBlocks == 0) { return 0; } - if(bitfield::test(filterBitfield_, blocks_, blocks_-1)) { - return ((int64_t)filteredBlocks-1)*blockLength_+getLastBlockLength(); - } else { - return ((int64_t)filteredBlocks)*blockLength_; + if (bitfield::test(filterBitfield_, blocks_, blocks_ - 1)) { + return ((int64_t)filteredBlocks - 1) * blockLength_ + getLastBlockLength(); + } + else { + return ((int64_t)filteredBlocks) * blockLength_; } } namespace { -template -int64_t computeCompletedLength(const Array& bitfield, - const BitfieldMan* btman, +template +int64_t computeCompletedLength(const Array& bitfield, const BitfieldMan* btman, CountFun cntfun) { size_t nbits = btman->countBlock(); size_t completedBlocks = cntfun(bitfield, nbits); int64_t completedLength = 0; - if(completedBlocks == 0) { + if (completedBlocks == 0) { completedLength = 0; - } else { - if(bitfield::test(bitfield, nbits, nbits - 1)) { - completedLength = ((int64_t)completedBlocks-1)*btman->getBlockLength() + - btman->getLastBlockLength(); - } else { - completedLength = ((int64_t)completedBlocks)*btman->getBlockLength(); + } + else { + if (bitfield::test(bitfield, nbits, nbits - 1)) { + completedLength = + ((int64_t)completedBlocks - 1) * btman->getBlockLength() + + btman->getLastBlockLength(); + } + else { + completedLength = ((int64_t)completedBlocks) * btman->getBlockLength(); } } return completedLength; } } // namespace -int64_t BitfieldMan::getCompletedLength(bool useFilter) const { - if(useFilter && filterEnabled_) { - auto arr = array(bitfield_)&array(filterBitfield_); - return computeCompletedLength(arr, - this, +int64_t BitfieldMan::getCompletedLength(bool useFilter) const +{ + if (useFilter && filterEnabled_) { + auto arr = array(bitfield_) & array(filterBitfield_); + return computeCompletedLength(arr, this, &bitfield::countSetBitSlow); - } else { + } + else { return computeCompletedLength(bitfield_, this, &bitfield::countSetBit); } } -int64_t BitfieldMan::getCompletedLengthNow() const { +int64_t BitfieldMan::getCompletedLengthNow() const +{ return getCompletedLength(false); } -int64_t BitfieldMan::getFilteredCompletedLengthNow() const { +int64_t BitfieldMan::getFilteredCompletedLengthNow() const +{ return getCompletedLength(true); } @@ -798,8 +826,8 @@ void BitfieldMan::updateCache() bool BitfieldMan::isBitRangeSet(size_t startIndex, size_t endIndex) const { - for(size_t i = startIndex; i <= endIndex; ++i) { - if(!isBitSet(i)) { + for (size_t i = startIndex; i <= endIndex; ++i) { + if (!isBitSet(i)) { return false; } } @@ -808,7 +836,7 @@ bool BitfieldMan::isBitRangeSet(size_t startIndex, size_t endIndex) const void BitfieldMan::unsetBitRange(size_t startIndex, size_t endIndex) { - for(size_t i = startIndex; i <= endIndex; ++i) { + for (size_t i = startIndex; i <= endIndex; ++i) { unsetBit(i); } updateCache(); @@ -816,7 +844,7 @@ void BitfieldMan::unsetBitRange(size_t startIndex, size_t endIndex) void BitfieldMan::setBitRange(size_t startIndex, size_t endIndex) { - for(size_t i = startIndex; i <= endIndex; ++i) { + for (size_t i = startIndex; i <= endIndex; ++i) { setBit(i); } updateCache(); @@ -824,53 +852,53 @@ void BitfieldMan::setBitRange(size_t startIndex, size_t endIndex) bool BitfieldMan::isBitSetOffsetRange(int64_t offset, int64_t length) const { - if(length <= 0) { + if (length <= 0) { return false; } - if(totalLength_ <= offset) { + if (totalLength_ <= offset) { return false; } - if(totalLength_ < offset+length) { - length = totalLength_-offset; + if (totalLength_ < offset + length) { + length = totalLength_ - offset; } - size_t startBlock = offset/blockLength_; - size_t endBlock = (offset+length-1)/blockLength_; - for(size_t i = startBlock; i <= endBlock; i++) { - if(!isBitSet(i)) { + size_t startBlock = offset / blockLength_; + size_t endBlock = (offset + length - 1) / blockLength_; + for (size_t i = startBlock; i <= endBlock; i++) { + if (!isBitSet(i)) { return false; } } return true; } -int64_t BitfieldMan::getOffsetCompletedLength -(int64_t offset, - int64_t length) const +int64_t BitfieldMan::getOffsetCompletedLength(int64_t offset, + int64_t length) const { int64_t res = 0; - if(length == 0 || totalLength_ <= offset) { + if (length == 0 || totalLength_ <= offset) { return 0; } - if(totalLength_ < offset+length) { - length = totalLength_-offset; + if (totalLength_ < offset + length) { + length = totalLength_ - offset; } - size_t start = offset/blockLength_; - size_t end = (offset+length-1)/blockLength_; - if(start == end) { - if(isBitSet(start)) { + size_t start = offset / blockLength_; + size_t end = (offset + length - 1) / blockLength_; + if (start == end) { + if (isBitSet(start)) { res = length; } - } else { - if(isBitSet(start)) { - res += static_cast(start+1)*blockLength_-offset; + } + else { + if (isBitSet(start)) { + res += static_cast(start + 1) * blockLength_ - offset; } - for(size_t i = start+1; i <= end-1; ++i) { - if(isBitSet(i)) { + for (size_t i = start + 1; i <= end - 1; ++i) { + if (isBitSet(i)) { res += blockLength_; } } - if(isBitSet(end)) { - res += offset+length-static_cast(end)*blockLength_; + if (isBitSet(end)) { + res += offset + length - static_cast(end) * blockLength_; } } return res; @@ -878,12 +906,12 @@ int64_t BitfieldMan::getOffsetCompletedLength int64_t BitfieldMan::getMissingUnusedLength(size_t startingIndex) const { - if(blocks_ <= startingIndex) { + if (blocks_ <= startingIndex) { return 0; } int64_t length = 0; - for(size_t i = startingIndex; i < blocks_; ++i) { - if(isBitSet(i) || isUseBitSet(i)) { + for (size_t i = startingIndex; i < blocks_; ++i) { + if (isBitSet(i) || isUseBitSet(i)) { break; } length += getBlockLength(i); @@ -892,19 +920,15 @@ int64_t BitfieldMan::getMissingUnusedLength(size_t startingIndex) const } BitfieldMan::Range::Range(size_t startIndex, size_t endIndex) - : - startIndex(startIndex), - endIndex(endIndex) -{} - -size_t BitfieldMan::Range::getSize() const + : startIndex(startIndex), endIndex(endIndex) { - return endIndex-startIndex; } +size_t BitfieldMan::Range::getSize() const { return endIndex - startIndex; } + size_t BitfieldMan::Range::getMidIndex() const { - return (endIndex-startIndex)/2+startIndex; + return (endIndex - startIndex) / 2 + startIndex; } bool BitfieldMan::Range::operator<(const Range& range) const diff --git a/src/BitfieldMan.h b/src/BitfieldMan.h index 60e44547..e2a5c483 100644 --- a/src/BitfieldMan.h +++ b/src/BitfieldMan.h @@ -92,10 +92,7 @@ public: BitfieldMan& operator=(const BitfieldMan& bitfieldMan); - int32_t getBlockLength() const - { - return blockLength_; - } + int32_t getBlockLength() const { return blockLength_; } int32_t getLastBlockLength() const; @@ -131,11 +128,9 @@ public: // if such bit index is found. Otherwise returns false. // // affected by filter - bool getSparseMissingUnusedIndex - (size_t& index, - int32_t minSplitSize, - const unsigned char* ignoreBitfield, - size_t ignoreBitfieldLength) const; + bool getSparseMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const unsigned char* ignoreBitfield, + size_t ignoreBitfieldLength) const; // Stores missing bit index to index. This function first try to // select smallest index starting offsetIndex in the order: @@ -151,13 +146,10 @@ public: // result. // // affected by filter - bool getGeomMissingUnusedIndex - (size_t& index, - int32_t minSplitSize, - const unsigned char* ignoreBitfield, - size_t ignoreBitfieldLength, - double base, - size_t offsetIndex) const; + bool getGeomMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const unsigned char* ignoreBitfield, + size_t ignoreBitfieldLength, double base, + size_t offsetIndex) const; // Stores missing bit index to index. This function selects smallest // index of missing piece, considering minSplitSize. Set bits in @@ -165,11 +157,9 @@ public: // found. Otherwise returns false. // // affected by filter - bool getInorderMissingUnusedIndex - (size_t& index, - int32_t minSplitSize, - const unsigned char* ignoreBitfield, - size_t ignoreBitfieldLength) const; + bool getInorderMissingUnusedIndex(size_t& index, int32_t minSplitSize, + const unsigned char* ignoreBitfield, + size_t ignoreBitfieldLength) const; // affected by filter bool getAllMissingIndexes(unsigned char* misbitfield, size_t mislen) const; @@ -206,34 +196,19 @@ public: // filterBitfield_ is NULL, returns false. bool isFilterBitSet(size_t index) const; - const unsigned char* getBitfield() const - { - return bitfield_; - } + const unsigned char* getBitfield() const { return bitfield_; } - size_t getBitfieldLength() const - { - return bitfieldLength_; - } + size_t getBitfieldLength() const { return bitfieldLength_; } // affected by filter - size_t countFilteredBlock() const - { - return cachedNumFilteredBlock_; - } + size_t countFilteredBlock() const { return cachedNumFilteredBlock_; } - size_t countBlock() const - { - return blocks_; - } + size_t countBlock() const { return blocks_; } // affected by filter size_t countFilteredBlockNow() const; - size_t getMaxIndex() const - { - return blocks_-1; - } + size_t getMaxIndex() const { return blocks_ - 1; } void setBitfield(const unsigned char* bitfield, size_t bitfieldLength); @@ -253,24 +228,15 @@ public: void enableFilter(); void disableFilter(); - bool isFilterEnabled() const - { - return filterEnabled_; - } + bool isFilterEnabled() const { return filterEnabled_; } // affected by filter - int64_t getFilteredTotalLength() const - { - return cachedFilteredTotalLength_; - } + int64_t getFilteredTotalLength() const { return cachedFilteredTotalLength_; } // affected by filter int64_t getFilteredTotalLengthNow() const; - int64_t getCompletedLength() const - { - return cachedCompletedLength_; - } + int64_t getCompletedLength() const { return cachedCompletedLength_; } int64_t getCompletedLengthNow() const; @@ -299,10 +265,7 @@ public: int64_t getMissingUnusedLength(size_t startingIndex) const; - const unsigned char* getFilterBitfield() const - { - return filterBitfield_; - } + const unsigned char* getFilterBitfield() const { return filterBitfield_; } }; } // namespace aria2 diff --git a/src/BtAbortOutstandingRequestEvent.cc b/src/BtAbortOutstandingRequestEvent.cc index 6afc6f60..673c3f17 100644 --- a/src/BtAbortOutstandingRequestEvent.cc +++ b/src/BtAbortOutstandingRequestEvent.cc @@ -37,10 +37,11 @@ namespace aria2 { -BtAbortOutstandingRequestEvent::BtAbortOutstandingRequestEvent -(const std::shared_ptr& piece) - : piece_(piece) -{} +BtAbortOutstandingRequestEvent::BtAbortOutstandingRequestEvent( + const std::shared_ptr& piece) + : piece_(piece) +{ +} BtAbortOutstandingRequestEvent::~BtAbortOutstandingRequestEvent() {} diff --git a/src/BtAbortOutstandingRequestEvent.h b/src/BtAbortOutstandingRequestEvent.h index b93cd0eb..598fd321 100644 --- a/src/BtAbortOutstandingRequestEvent.h +++ b/src/BtAbortOutstandingRequestEvent.h @@ -46,6 +46,7 @@ class Piece; class BtAbortOutstandingRequestEvent { private: std::shared_ptr piece_; + public: BtAbortOutstandingRequestEvent(const std::shared_ptr& piece); ~BtAbortOutstandingRequestEvent(); diff --git a/src/BtAllowedFastMessage.cc b/src/BtAllowedFastMessage.cc index 9922a624..364d2a23 100644 --- a/src/BtAllowedFastMessage.cc +++ b/src/BtAllowedFastMessage.cc @@ -42,22 +42,24 @@ namespace aria2 { const char BtAllowedFastMessage::NAME[] = "allowed fast"; -BtAllowedFastMessage::BtAllowedFastMessage(size_t index): - IndexBtMessage(ID, NAME, index) {} +BtAllowedFastMessage::BtAllowedFastMessage(size_t index) + : IndexBtMessage(ID, NAME, index) +{ +} -std::unique_ptr BtAllowedFastMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtAllowedFastMessage::create(const unsigned char* data, size_t dataLength) { return IndexBtMessage::create(data, dataLength); } -void BtAllowedFastMessage::doReceivedAction() { - if(!getPeer()->isFastExtensionEnabled()) { - throw DL_ABORT_EX - (fmt("%s received while fast extension is disabled", - toString().c_str())); +void BtAllowedFastMessage::doReceivedAction() +{ + if (!getPeer()->isFastExtensionEnabled()) { + throw DL_ABORT_EX(fmt("%s received while fast extension is disabled", + toString().c_str())); } - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } getPeer()->addPeerAllowedIndex(getIndex()); @@ -65,11 +67,13 @@ void BtAllowedFastMessage::doReceivedAction() { namespace { struct ThisProgressUpdate : public ProgressUpdate { - ThisProgressUpdate(std::shared_ptr peer, size_t index) - : peer(std::move(peer)), index(index) {} + ThisProgressUpdate(std::shared_ptr peer, size_t index) + : peer(std::move(peer)), index(index) + { + } virtual void update(size_t length, bool complete) CXX11_OVERRIDE { - if(complete) { + if (complete) { peer->addAmAllowedIndex(index); } } diff --git a/src/BtAllowedFastMessage.h b/src/BtAllowedFastMessage.h index c58f5190..59dd61ab 100644 --- a/src/BtAllowedFastMessage.h +++ b/src/BtAllowedFastMessage.h @@ -47,8 +47,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BtAnnounce.h b/src/BtAnnounce.h index 21688bb7..61b3c722 100644 --- a/src/BtAnnounce.h +++ b/src/BtAnnounce.h @@ -104,8 +104,8 @@ public: virtual void processAnnounceResponse(const unsigned char* trackerResponse, size_t trackerResponseLength) = 0; - virtual void processUDPTrackerResponse - (const std::shared_ptr& req) = 0; + virtual void + processUDPTrackerResponse(const std::shared_ptr& req) = 0; /** * Returns true if no more announce is needed. diff --git a/src/BtBitfieldMessage.cc b/src/BtBitfieldMessage.cc index ff801c85..9d55d304 100644 --- a/src/BtBitfieldMessage.cc +++ b/src/BtBitfieldMessage.cc @@ -49,24 +49,23 @@ namespace aria2 { const char BtBitfieldMessage::NAME[] = "bitfield"; BtBitfieldMessage::BtBitfieldMessage() - : SimpleBtMessage(ID, NAME), - bitfieldLength_(0) -{} + : SimpleBtMessage(ID, NAME), bitfieldLength_(0) +{ +} -BtBitfieldMessage::BtBitfieldMessage -(const unsigned char* bitfield, size_t bitfieldLength) - : SimpleBtMessage(ID, NAME), - bitfieldLength_(0) +BtBitfieldMessage::BtBitfieldMessage(const unsigned char* bitfield, + size_t bitfieldLength) + : SimpleBtMessage(ID, NAME), bitfieldLength_(0) { setBitfield(bitfield, bitfieldLength); } -BtBitfieldMessage::~BtBitfieldMessage() -{} +BtBitfieldMessage::~BtBitfieldMessage() {} -void BtBitfieldMessage::setBitfield -(const unsigned char* bitfield, size_t bitfieldLength) { - if(bitfield_.get() == bitfield) { +void BtBitfieldMessage::setBitfield(const unsigned char* bitfield, + size_t bitfieldLength) +{ + if (bitfield_.get() == bitfield) { return; } @@ -78,44 +77,45 @@ void BtBitfieldMessage::setBitfield std::unique_ptr BtBitfieldMessage::create(const unsigned char* data, size_t dataLength) { - bittorrent::assertPayloadLengthGreater(1,dataLength, NAME); + bittorrent::assertPayloadLengthGreater(1, dataLength, NAME); bittorrent::assertID(ID, data, NAME); auto message = make_unique(); - message->setBitfield(data+1, dataLength-1); + message->setBitfield(data + 1, dataLength - 1); return message; } -void BtBitfieldMessage::doReceivedAction() { - if(isMetadataGetMode()) { +void BtBitfieldMessage::doReceivedAction() +{ + if (isMetadataGetMode()) { return; } getPieceStorage()->updatePieceStats(bitfield_.get(), bitfieldLength_, getPeer()->getBitfield()); getPeer()->setBitfield(bitfield_.get(), bitfieldLength_); - if(getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { + if (getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER); } } -unsigned char* BtBitfieldMessage::createMessage() { +unsigned char* BtBitfieldMessage::createMessage() +{ /** * len --- 1+bitfieldLength, 4bytes * id --- 5, 1byte * bitfield --- bitfield, bitfieldLength bytes * total: 5+bitfieldLength bytes */ - const size_t msgLength = 5+bitfieldLength_; + const size_t msgLength = 5 + bitfieldLength_; auto msg = new unsigned char[msgLength]; - bittorrent::createPeerMessageString(msg, msgLength, 1+bitfieldLength_, ID); - memcpy(msg+5, bitfield_.get(), bitfieldLength_); + bittorrent::createPeerMessageString(msg, msgLength, 1 + bitfieldLength_, ID); + memcpy(msg + 5, bitfield_.get(), bitfieldLength_); return msg; } -size_t BtBitfieldMessage::getMessageLength() { - return 5+bitfieldLength_; -} +size_t BtBitfieldMessage::getMessageLength() { return 5 + bitfieldLength_; } -std::string BtBitfieldMessage::toString() const { +std::string BtBitfieldMessage::toString() const +{ std::string s = NAME; s += " "; s += util::toHex(bitfield_.get(), bitfieldLength_); diff --git a/src/BtBitfieldMessage.h b/src/BtBitfieldMessage.h index 8494aa7d..640bf6ff 100644 --- a/src/BtBitfieldMessage.h +++ b/src/BtBitfieldMessage.h @@ -43,6 +43,7 @@ class BtBitfieldMessage : public SimpleBtMessage { private: std::unique_ptr bitfield_; size_t bitfieldLength_; + public: BtBitfieldMessage(); @@ -60,8 +61,8 @@ public: size_t getBitfieldLength() const { return bitfieldLength_; } - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BtBitfieldMessageValidator.cc b/src/BtBitfieldMessageValidator.cc index 03d0bf1f..00bf12f8 100644 --- a/src/BtBitfieldMessageValidator.cc +++ b/src/BtBitfieldMessageValidator.cc @@ -38,19 +38,18 @@ namespace aria2 { -BtBitfieldMessageValidator::BtBitfieldMessageValidator -(const BtBitfieldMessage* message, size_t numPiece) - : message_(message), - numPiece_(numPiece) -{} +BtBitfieldMessageValidator::BtBitfieldMessageValidator( + const BtBitfieldMessage* message, size_t numPiece) + : message_(message), numPiece_(numPiece) +{ +} BtBitfieldMessageValidator::~BtBitfieldMessageValidator() {} void BtBitfieldMessageValidator::validate() { bittorrent::checkBitfield(message_->getBitfield(), - message_->getBitfieldLength(), - numPiece_); + message_->getBitfieldLength(), numPiece_); } } // namespace aria2 diff --git a/src/BtBitfieldMessageValidator.h b/src/BtBitfieldMessageValidator.h index 606250a3..2613e3dc 100644 --- a/src/BtBitfieldMessageValidator.h +++ b/src/BtBitfieldMessageValidator.h @@ -45,9 +45,9 @@ class BtBitfieldMessageValidator : public BtMessageValidator { private: const BtBitfieldMessage* message_; size_t numPiece_; + public: - BtBitfieldMessageValidator(const BtBitfieldMessage* message, - size_t numPiece); + BtBitfieldMessageValidator(const BtBitfieldMessage* message, size_t numPiece); ~BtBitfieldMessageValidator(); virtual void validate() CXX11_OVERRIDE; diff --git a/src/BtCancelMessage.cc b/src/BtCancelMessage.cc index ecfff4f0..1ce499c4 100644 --- a/src/BtCancelMessage.cc +++ b/src/BtCancelMessage.cc @@ -39,23 +39,24 @@ namespace aria2 { const char BtCancelMessage::NAME[] = "cancel"; -BtCancelMessage::BtCancelMessage -(size_t index, int32_t begin, int32_t length) - :RangeBtMessage(ID, NAME, index, begin, length) {} +BtCancelMessage::BtCancelMessage(size_t index, int32_t begin, int32_t length) + : RangeBtMessage(ID, NAME, index, begin, length) +{ +} -std::unique_ptr BtCancelMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtCancelMessage::create(const unsigned char* data, size_t dataLength) { return RangeBtMessage::create(data, dataLength); } void BtCancelMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } - getBtMessageDispatcher()->doCancelSendingPieceAction - (getIndex(), getBegin(), getLength()); + getBtMessageDispatcher()->doCancelSendingPieceAction(getIndex(), getBegin(), + getLength()); } } // namespace aria2 diff --git a/src/BtCancelMessage.h b/src/BtCancelMessage.h index fd3c601a..eac8d59d 100644 --- a/src/BtCancelMessage.h +++ b/src/BtCancelMessage.h @@ -47,8 +47,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; }; diff --git a/src/BtCancelSendingPieceEvent.h b/src/BtCancelSendingPieceEvent.h index 18431072..41c1362f 100644 --- a/src/BtCancelSendingPieceEvent.h +++ b/src/BtCancelSendingPieceEvent.h @@ -44,9 +44,12 @@ private: size_t index_; int32_t begin_; int32_t length_; + public: - BtCancelSendingPieceEvent(size_t index, int32_t begin, int32_t length): - index_(index), begin_(begin), length_(length) {} + BtCancelSendingPieceEvent(size_t index, int32_t begin, int32_t length) + : index_(index), begin_(begin), length_(length) + { + } size_t getIndex() const { return index_; } diff --git a/src/BtCheckIntegrityEntry.cc b/src/BtCheckIntegrityEntry.cc index c1c93708..2bd8b7ec 100644 --- a/src/BtCheckIntegrityEntry.cc +++ b/src/BtCheckIntegrityEntry.cc @@ -46,55 +46,52 @@ namespace aria2 { -BtCheckIntegrityEntry::BtCheckIntegrityEntry(RequestGroup* requestGroup): - PieceHashCheckIntegrityEntry(requestGroup, nullptr) {} +BtCheckIntegrityEntry::BtCheckIntegrityEntry(RequestGroup* requestGroup) + : PieceHashCheckIntegrityEntry(requestGroup, nullptr) +{ +} BtCheckIntegrityEntry::~BtCheckIntegrityEntry() {} -void BtCheckIntegrityEntry::onDownloadIncomplete -(std::vector>& commands, DownloadEngine* e) +void BtCheckIntegrityEntry::onDownloadIncomplete( + std::vector>& commands, DownloadEngine* e) { auto& ps = getRequestGroup()->getPieceStorage(); ps->onDownloadIncomplete(); - if(getRequestGroup()->getOption()->getAsBool(PREF_HASH_CHECK_ONLY)) { + if (getRequestGroup()->getOption()->getAsBool(PREF_HASH_CHECK_ONLY)) { return; } const auto& diskAdaptor = ps->getDiskAdaptor(); - if(diskAdaptor->isReadOnlyEnabled()) { + if (diskAdaptor->isReadOnlyEnabled()) { // Now reopen DiskAdaptor with read only disabled. diskAdaptor->closeFile(); diskAdaptor->disableReadOnly(); diskAdaptor->openFile(); } - proceedFileAllocation(commands, - make_unique - (getRequestGroup()), - e); + proceedFileAllocation( + commands, make_unique(getRequestGroup()), e); } -void BtCheckIntegrityEntry::onDownloadFinished -(std::vector>& commands, DownloadEngine* e) +void BtCheckIntegrityEntry::onDownloadFinished( + std::vector>& commands, DownloadEngine* e) { auto group = getRequestGroup(); const auto& option = group->getOption(); - if(option->getAsBool(PREF_BT_ENABLE_HOOK_AFTER_HASH_CHECK)) { + if (option->getAsBool(PREF_BT_ENABLE_HOOK_AFTER_HASH_CHECK)) { util::executeHookByOptName(group, option.get(), PREF_ON_BT_DOWNLOAD_COMPLETE); - SingletonHolder::instance()->notifyDownloadEvent - (EVENT_ON_BT_DOWNLOAD_COMPLETE, group); + SingletonHolder::instance()->notifyDownloadEvent( + EVENT_ON_BT_DOWNLOAD_COMPLETE, group); } // TODO Currently,when all the checksums // are valid, then aria2 goes to seeding mode. Sometimes it is better // to exit rather than doing seeding. So, it would be good to toggle this // behavior. - if(!option->getAsBool(PREF_HASH_CHECK_ONLY) && - option->getAsBool(PREF_BT_HASH_CHECK_SEED)) { - proceedFileAllocation(commands, - make_unique - (getRequestGroup()), - e); + if (!option->getAsBool(PREF_HASH_CHECK_ONLY) && + option->getAsBool(PREF_BT_HASH_CHECK_SEED)) { + proceedFileAllocation( + commands, make_unique(getRequestGroup()), e); } } - } // namespace aria2 diff --git a/src/BtCheckIntegrityEntry.h b/src/BtCheckIntegrityEntry.h index 14f8f74e..491dd3c9 100644 --- a/src/BtCheckIntegrityEntry.h +++ b/src/BtCheckIntegrityEntry.h @@ -45,13 +45,13 @@ public: virtual ~BtCheckIntegrityEntry(); - virtual void onDownloadFinished - (std::vector>& commands, DownloadEngine* e) - CXX11_OVERRIDE; + virtual void + onDownloadFinished(std::vector>& commands, + DownloadEngine* e) CXX11_OVERRIDE; - virtual void onDownloadIncomplete - (std::vector>& commands, DownloadEngine* e) - CXX11_OVERRIDE; + virtual void + onDownloadIncomplete(std::vector>& commands, + DownloadEngine* e) CXX11_OVERRIDE; }; } // namespace aria2 diff --git a/src/BtChokeMessage.cc b/src/BtChokeMessage.cc index 87e5c084..7d75df02 100644 --- a/src/BtChokeMessage.cc +++ b/src/BtChokeMessage.cc @@ -42,17 +42,17 @@ namespace aria2 { const char BtChokeMessage::NAME[] = "choke"; -BtChokeMessage::BtChokeMessage():ZeroBtMessage{ID, NAME} {} +BtChokeMessage::BtChokeMessage() : ZeroBtMessage{ID, NAME} {} -std::unique_ptr BtChokeMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtChokeMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create(data, dataLength); } void BtChokeMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } getPeer()->peerChoking(true); @@ -60,19 +60,17 @@ void BtChokeMessage::doReceivedAction() getBtRequestFactory()->doChokedAction(); } -bool BtChokeMessage::sendPredicate() const -{ - return !getPeer()->amChoking(); -} +bool BtChokeMessage::sendPredicate() const { return !getPeer()->amChoking(); } namespace { struct ThisProgressUpdate : public ProgressUpdate { - ThisProgressUpdate(std::shared_ptr peer, - BtMessageDispatcher* disp) - : peer(std::move(peer)), disp(disp) {} + ThisProgressUpdate(std::shared_ptr peer, BtMessageDispatcher* disp) + : peer(std::move(peer)), disp(disp) + { + } virtual void update(size_t length, bool complete) CXX11_OVERRIDE { - if(complete) { + if (complete) { peer->amChoking(true); disp->doChokingAction(); } diff --git a/src/BtChokeMessage.h b/src/BtChokeMessage.h index 23a63a5e..3ad96dd1 100644 --- a/src/BtChokeMessage.h +++ b/src/BtChokeMessage.h @@ -49,8 +49,8 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual bool sendPredicate() const CXX11_OVERRIDE; diff --git a/src/BtChokingEvent.h b/src/BtChokingEvent.h index 91a9360e..5fa6a0ce 100644 --- a/src/BtChokingEvent.h +++ b/src/BtChokingEvent.h @@ -39,7 +39,8 @@ namespace aria2 { -class BtChokingEvent {}; +class BtChokingEvent { +}; } // namespace aria2 diff --git a/src/BtDependency.cc b/src/BtDependency.cc index afbe9621..3131c5c2 100644 --- a/src/BtDependency.cc +++ b/src/BtDependency.cc @@ -53,12 +53,11 @@ namespace aria2 { -BtDependency::BtDependency -(RequestGroup* dependant, - const std::shared_ptr& dependee) - : dependant_(dependant), - dependee_(dependee) -{} +BtDependency::BtDependency(RequestGroup* dependant, + const std::shared_ptr& dependee) + : dependant_(dependant), dependee_(dependee) +{ +} BtDependency::~BtDependency() {} @@ -77,9 +76,8 @@ void copyValues(const std::shared_ptr& d, namespace { struct EntryCmp { - bool operator() - (const std::shared_ptr& lhs, - const std::shared_ptr& rhs) const + bool operator()(const std::shared_ptr& lhs, + const std::shared_ptr& rhs) const { return lhs->getOriginalName() < rhs->getOriginalName(); } @@ -88,53 +86,54 @@ struct EntryCmp { bool BtDependency::resolve() { - if(!dependee_) { + if (!dependee_) { return true; } - if(dependee_->getNumCommand() == 0 && dependee_->downloadFinished()) { + if (dependee_->getNumCommand() == 0 && dependee_->downloadFinished()) { std::shared_ptr dependee = dependee_; // cut reference here dependee_.reset(); auto context = std::make_shared(); try { std::shared_ptr diskAdaptor = - dependee->getPieceStorage()->getDiskAdaptor(); + dependee->getPieceStorage()->getDiskAdaptor(); diskAdaptor->openExistingFile(); std::string content = util::toString(diskAdaptor); - if(dependee->getDownloadContext()->hasAttribute(CTX_ATTR_BT)) { + if (dependee->getDownloadContext()->hasAttribute(CTX_ATTR_BT)) { auto attrs = - bittorrent::getTorrentAttrs(dependee->getDownloadContext()); - bittorrent::loadFromMemory - (bittorrent::metadata2Torrent(content, attrs), context, - dependant_->getOption(), "default"); + bittorrent::getTorrentAttrs(dependee->getDownloadContext()); + bittorrent::loadFromMemory(bittorrent::metadata2Torrent(content, attrs), + context, dependant_->getOption(), "default"); // We don't call bittorrent::adjustAnnounceUri() because it // has already been called with attrs. - } else { - bittorrent::loadFromMemory - (content, context, dependant_->getOption(), - File(dependee->getFirstFilePath()).getBasename()); + } + else { + bittorrent::loadFromMemory( + content, context, dependant_->getOption(), + File(dependee->getFirstFilePath()).getBasename()); bittorrent::adjustAnnounceUri(bittorrent::getTorrentAttrs(context), dependant_->getOption()); } - const std::vector >& fileEntries = - context->getFileEntries(); - for (auto &fe : fileEntries) { - auto &uri = fe->getRemainingUris(); + const std::vector>& fileEntries = + context->getFileEntries(); + for (auto& fe : fileEntries) { + auto& uri = fe->getRemainingUris(); std::shuffle(std::begin(uri), std::end(uri), *SimpleRandomizer::getInstance()); } - const std::vector >& dependantFileEntries = - dependant_->getDownloadContext()->getFileEntries(); + const std::vector>& dependantFileEntries = + dependant_->getDownloadContext()->getFileEntries(); // If dependant's FileEntry::getOriginalName() is empty, we // assume that torrent is single file. In Metalink3, this is // always assumed. - if(fileEntries.size() == 1 && dependantFileEntries.size() == 1 && - dependantFileEntries[0]->getOriginalName().empty()) { + if (fileEntries.size() == 1 && dependantFileEntries.size() == 1 && + dependantFileEntries[0]->getOriginalName().empty()) { copyValues(fileEntries[0], dependantFileEntries[0]); - } else { - std::vector > destFiles; + } + else { + std::vector> destFiles; destFiles.reserve(fileEntries.size()); - for(auto & e : fileEntries) { + for (auto& e : fileEntries) { e->setRequested(false); destFiles.push_back(e); } @@ -142,19 +141,21 @@ bool BtDependency::resolve() // Copy file path in dependant_'s FileEntries to newly created // context's FileEntries to endorse the path structure of // dependant_. URIs and singleHostMultiConnection are also copied. - for(const auto& e: dependantFileEntries){ + for (const auto& e : dependantFileEntries) { const auto d = std::lower_bound(std::begin(destFiles), std::end(destFiles), e, EntryCmp()); - if(d == std::end(destFiles) || - (*d)->getOriginalName() != e->getOriginalName()) { - throw DL_ABORT_EX - (fmt("No entry %s in torrent file", e->getOriginalName().c_str())); - } else { + if (d == std::end(destFiles) || + (*d)->getOriginalName() != e->getOriginalName()) { + throw DL_ABORT_EX(fmt("No entry %s in torrent file", + e->getOriginalName().c_str())); + } + else { copyValues(*d, e); } } } - } catch(RecoverableException& e) { + } + catch (RecoverableException& e) { A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); A2_LOG_INFO(fmt("BtDependency for GID#%s failed. Go without Bt.", GroupId::toHex(dependant_->getGID()).c_str())); @@ -164,14 +165,16 @@ bool BtDependency::resolve() GroupId::toHex(dependant_->getGID()).c_str())); dependant_->setDownloadContext(context); return true; - } else if(dependee_->getNumCommand() == 0) { + } + else if (dependee_->getNumCommand() == 0) { // dependee_'s download failed. // cut reference here dependee_.reset(); A2_LOG_INFO(fmt("BtDependency for GID#%s failed. Go without Bt.", GroupId::toHex(dependant_->getGID()).c_str())); return true; - } else { + } + else { return false; } } diff --git a/src/BtDependency.h b/src/BtDependency.h index 8613a160..83e66d87 100644 --- a/src/BtDependency.h +++ b/src/BtDependency.h @@ -44,11 +44,11 @@ namespace aria2 { class RequestGroup; class Option; -class BtDependency : public Dependency -{ +class BtDependency : public Dependency { private: RequestGroup* dependant_; std::shared_ptr dependee_; + public: BtDependency(RequestGroup* dependant, const std::shared_ptr& dependee); diff --git a/src/BtExtendedMessage.cc b/src/BtExtendedMessage.cc index 273ea289..add69170 100644 --- a/src/BtExtendedMessage.cc +++ b/src/BtExtendedMessage.cc @@ -50,12 +50,13 @@ namespace aria2 { const char BtExtendedMessage::NAME[] = "extended"; -BtExtendedMessage::BtExtendedMessage -(std::unique_ptr extensionMessage): - SimpleBtMessage(ID, NAME), - extensionMessage_(std::move(extensionMessage)), - msgLength_(0) -{} +BtExtendedMessage::BtExtendedMessage( + std::unique_ptr extensionMessage) + : SimpleBtMessage(ID, NAME), + extensionMessage_(std::move(extensionMessage)), + msgLength_(0) +{ +} unsigned char* BtExtendedMessage::createMessage() { @@ -67,17 +68,18 @@ unsigned char* BtExtendedMessage::createMessage() * total: 6+extpayload.length bytes */ std::string payload = extensionMessage_->getPayload(); - msgLength_ = 6+payload.size(); + msgLength_ = 6 + payload.size(); auto msg = new unsigned char[msgLength_]; - bittorrent::createPeerMessageString(msg, msgLength_, 2+payload.size(), ID); - *(msg+5) = extensionMessage_->getExtensionMessageID(); - memcpy(msg+6, payload.data(), payload.size()); + bittorrent::createPeerMessageString(msg, msgLength_, 2 + payload.size(), ID); + *(msg + 5) = extensionMessage_->getExtensionMessageID(); + memcpy(msg + 6, payload.data(), payload.size()); return msg; } -size_t BtExtendedMessage::getMessageLength() { - if(!msgLength_) { - msgLength_ = 6+extensionMessage_->getPayload().size(); +size_t BtExtendedMessage::getMessageLength() +{ + if (!msgLength_) { + msgLength_ = 6 + extensionMessage_->getPayload().size(); } return msgLength_; } @@ -87,7 +89,8 @@ bool BtExtendedMessage::sendPredicate() const return getPeer()->isExtendedMessagingEnabled(); } -std::string BtExtendedMessage::toString() const { +std::string BtExtendedMessage::toString() const +{ std::string s = NAME; s += " "; s += extensionMessage_->toString(); @@ -102,13 +105,13 @@ BtExtendedMessage::create(ExtensionMessageFactory* factory, bittorrent::assertPayloadLengthGreater(1, dataLength, NAME); bittorrent::assertID(ID, data, NAME); assert(factory); - return make_unique - (factory->createMessage(data+1, dataLength-1)); + return make_unique( + factory->createMessage(data + 1, dataLength - 1)); } void BtExtendedMessage::doReceivedAction() { - if(extensionMessage_) { + if (extensionMessage_) { extensionMessage_->doReceivedAction(); } } diff --git a/src/BtExtendedMessage.h b/src/BtExtendedMessage.h index e1df8aec..dcd0d198 100644 --- a/src/BtExtendedMessage.h +++ b/src/BtExtendedMessage.h @@ -41,25 +41,23 @@ namespace aria2 { class ExtensionMessage; class ExtensionMessageFactory; -class BtExtendedMessage:public SimpleBtMessage -{ +class BtExtendedMessage : public SimpleBtMessage { private: std::unique_ptr extensionMessage_; size_t msgLength_; + public: BtExtendedMessage(std::unique_ptr extensionMessage = - std::unique_ptr{}); + std::unique_ptr{}); static const uint8_t ID = 20; static const char NAME[]; - static std::unique_ptr create - (ExtensionMessageFactory* factory, - const std::shared_ptr& peer, - const unsigned char* data, - size_t dataLength); + static std::unique_ptr + create(ExtensionMessageFactory* factory, const std::shared_ptr& peer, + const unsigned char* data, size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BtFileAllocationEntry.cc b/src/BtFileAllocationEntry.cc index 89a4c7c4..ed44e44e 100644 --- a/src/BtFileAllocationEntry.cc +++ b/src/BtFileAllocationEntry.cc @@ -50,36 +50,39 @@ namespace aria2 { -BtFileAllocationEntry::BtFileAllocationEntry(RequestGroup* requestGroup): - FileAllocationEntry(requestGroup, nullptr) {} +BtFileAllocationEntry::BtFileAllocationEntry(RequestGroup* requestGroup) + : FileAllocationEntry(requestGroup, nullptr) +{ +} BtFileAllocationEntry::~BtFileAllocationEntry() {} -void BtFileAllocationEntry::prepareForNextAction -(std::vector>& commands, DownloadEngine* e) +void BtFileAllocationEntry::prepareForNextAction( + std::vector>& commands, DownloadEngine* e) { - auto &option = getRequestGroup()->getOption(); + auto& option = getRequestGroup()->getOption(); BtSetup().setup(commands, getRequestGroup(), e, option.get()); - if(option->getAsBool(PREF_ENABLE_MMAP) && - option->get(PREF_FILE_ALLOCATION) != V_NONE) { + if (option->getAsBool(PREF_ENABLE_MMAP) && + option->get(PREF_FILE_ALLOCATION) != V_NONE) { getRequestGroup()->getPieceStorage()->getDiskAdaptor()->enableMmap(); } - if(!getRequestGroup()->downloadFinished()) { + if (!getRequestGroup()->downloadFinished()) { // For DownloadContext::resetDownloadStartTime(), see also // RequestGroup::createInitialCommand() getRequestGroup()->getDownloadContext()->resetDownloadStartTime(); - const std::vector >& fileEntries = - getRequestGroup()->getDownloadContext()->getFileEntries(); - if(isUriSuppliedForRequsetFileEntry - (std::begin(fileEntries), std::end(fileEntries))) { + const std::vector>& fileEntries = + getRequestGroup()->getDownloadContext()->getFileEntries(); + if (isUriSuppliedForRequsetFileEntry(std::begin(fileEntries), + std::end(fileEntries))) { getRequestGroup()->createNextCommandWithAdj(commands, e, 0); } - } else { + } + else { #ifdef __MINGW32__ const std::shared_ptr& diskAdaptor = - getRequestGroup()->getPieceStorage()->getDiskAdaptor(); - if(!diskAdaptor->isReadOnlyEnabled()) { + getRequestGroup()->getPieceStorage()->getDiskAdaptor(); + if (!diskAdaptor->isReadOnlyEnabled()) { // On Windows, if aria2 opens files with GENERIC_WRITE access // right, some programs cannot open them aria2 is seeding. To // avoid this situation, re-open the files with read-only diff --git a/src/BtFileAllocationEntry.h b/src/BtFileAllocationEntry.h index b1a2e902..5348ab01 100644 --- a/src/BtFileAllocationEntry.h +++ b/src/BtFileAllocationEntry.h @@ -45,9 +45,9 @@ public: virtual ~BtFileAllocationEntry(); - virtual void prepareForNextAction - (std::vector>& commands, DownloadEngine* e) - CXX11_OVERRIDE; + virtual void + prepareForNextAction(std::vector>& commands, + DownloadEngine* e) CXX11_OVERRIDE; }; } // namespace aria2 diff --git a/src/BtHandshakeMessage.cc b/src/BtHandshakeMessage.cc index 2462d37b..c7ebfef1 100644 --- a/src/BtHandshakeMessage.cc +++ b/src/BtHandshakeMessage.cc @@ -45,23 +45,21 @@ namespace aria2 { const char BtHandshakeMessage::NAME[] = "handshake"; const unsigned char* BtHandshakeMessage::BT_PSTR = - reinterpret_cast("BitTorrent protocol"); + reinterpret_cast("BitTorrent protocol"); -BtHandshakeMessage::BtHandshakeMessage():SimpleBtMessage(ID, NAME) -{ - init(); -} +BtHandshakeMessage::BtHandshakeMessage() : SimpleBtMessage(ID, NAME) { init(); } BtHandshakeMessage::BtHandshakeMessage(const unsigned char* infoHash, - const unsigned char* peerId): - SimpleBtMessage(ID, NAME) + const unsigned char* peerId) + : SimpleBtMessage(ID, NAME) { init(); memcpy(infoHash_, infoHash, INFO_HASH_LENGTH); memcpy(peerId_, peerId, PEER_ID_LENGTH); } -void BtHandshakeMessage::init() { +void BtHandshakeMessage::init() +{ pstrlen_ = 19; pstr_ = new unsigned char[PSTR_LENGTH]; reserved_ = new unsigned char[RESERVED_LENGTH]; @@ -91,37 +89,33 @@ unsigned char* BtHandshakeMessage::createMessage() { auto msg = new unsigned char[MESSAGE_LENGTH]; msg[0] = pstrlen_; - memcpy(msg+1, pstr_, PSTR_LENGTH); - memcpy(msg+20, reserved_, RESERVED_LENGTH); - memcpy(msg+28, infoHash_, INFO_HASH_LENGTH); - memcpy(msg+48, peerId_, PEER_ID_LENGTH); + memcpy(msg + 1, pstr_, PSTR_LENGTH); + memcpy(msg + 20, reserved_, RESERVED_LENGTH); + memcpy(msg + 28, infoHash_, INFO_HASH_LENGTH); + memcpy(msg + 48, peerId_, PEER_ID_LENGTH); return msg; } -size_t BtHandshakeMessage::getMessageLength() { - return MESSAGE_LENGTH; -} +size_t BtHandshakeMessage::getMessageLength() { return MESSAGE_LENGTH; } -std::string BtHandshakeMessage::toString() const { - return fmt("%s peerId=%s, reserved=%s", - NAME, +std::string BtHandshakeMessage::toString() const +{ + return fmt("%s peerId=%s, reserved=%s", NAME, util::percentEncode(peerId_, PEER_ID_LENGTH).c_str(), util::toHex(reserved_, RESERVED_LENGTH).c_str()); } -bool BtHandshakeMessage::isFastExtensionSupported() const { - return reserved_[7]&0x04u; +bool BtHandshakeMessage::isFastExtensionSupported() const +{ + return reserved_[7] & 0x04u; } bool BtHandshakeMessage::isExtendedMessagingEnabled() const { - return reserved_[5]&0x10u; + return reserved_[5] & 0x10u; } -bool BtHandshakeMessage::isDHTEnabled() const -{ - return reserved_[7]&0x01u; -} +bool BtHandshakeMessage::isDHTEnabled() const { return reserved_[7] & 0x01u; } void BtHandshakeMessage::setInfoHash(const unsigned char* infoHash) { diff --git a/src/BtHandshakeMessage.h b/src/BtHandshakeMessage.h index 03ea2b8b..51893b57 100644 --- a/src/BtHandshakeMessage.h +++ b/src/BtHandshakeMessage.h @@ -45,6 +45,7 @@ public: static const unsigned char* BT_PSTR; static const size_t RESERVED_LENGTH = 8; static const size_t MESSAGE_LENGTH = 68; + private: uint8_t pstrlen_; unsigned char* pstr_; @@ -52,29 +53,32 @@ private: unsigned char* infoHash_; unsigned char* peerId_; void init(); + public: BtHandshakeMessage(); /** * infoHash must be 20 byte length. * peerId must be 20 byte length. */ - BtHandshakeMessage(const unsigned char* infoHash, const unsigned char* peerId); + BtHandshakeMessage(const unsigned char* infoHash, + const unsigned char* peerId); - static std::unique_ptr - create(const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); - virtual ~BtHandshakeMessage() { - delete [] pstr_; - delete [] reserved_; - delete [] infoHash_; - delete [] peerId_; + virtual ~BtHandshakeMessage() + { + delete[] pstr_; + delete[] reserved_; + delete[] infoHash_; + delete[] peerId_; } static const uint8_t ID = INT8_MAX; static const char NAME[]; - virtual void doReceivedAction() CXX11_OVERRIDE {}; + virtual void doReceivedAction() CXX11_OVERRIDE{}; virtual unsigned char* createMessage() CXX11_OVERRIDE; @@ -90,34 +94,25 @@ public: void setDHTEnabled(bool enabled) { - if(enabled) { + if (enabled) { reserved_[7] |= 0x01u; - } else { + } + else { reserved_[7] &= ~0x01u; } } - uint8_t getPstrlen() const { - return pstrlen_; - } + uint8_t getPstrlen() const { return pstrlen_; } - const unsigned char* getPstr() const { - return pstr_; - } + const unsigned char* getPstr() const { return pstr_; } - const unsigned char* getReserved() const { - return reserved_; - } + const unsigned char* getReserved() const { return reserved_; } - const unsigned char* getInfoHash() const { - return infoHash_; - } + const unsigned char* getInfoHash() const { return infoHash_; } void setInfoHash(const unsigned char* infoHash); - const unsigned char* getPeerId() const { - return peerId_; - } + const unsigned char* getPeerId() const { return peerId_; } void setPeerId(const unsigned char* peerId); }; diff --git a/src/BtHandshakeMessageValidator.cc b/src/BtHandshakeMessageValidator.cc index 212e2193..e0e16ca4 100644 --- a/src/BtHandshakeMessageValidator.cc +++ b/src/BtHandshakeMessageValidator.cc @@ -43,9 +43,9 @@ namespace aria2 { -BtHandshakeMessageValidator::BtHandshakeMessageValidator -(const BtHandshakeMessage* message, const unsigned char* infoHash) - : message_(message) +BtHandshakeMessageValidator::BtHandshakeMessageValidator( + const BtHandshakeMessage* message, const unsigned char* infoHash) + : message_(message) { memcpy(infoHash_, infoHash, sizeof(infoHash_)); } @@ -54,22 +54,20 @@ BtHandshakeMessageValidator::~BtHandshakeMessageValidator() {} void BtHandshakeMessageValidator::validate() { - if(message_->getPstrlen() != 19) { - throw DL_ABORT_EX(fmt("invalid handshake pstrlen=%u", - message_->getPstrlen())); + if (message_->getPstrlen() != 19) { + throw DL_ABORT_EX( + fmt("invalid handshake pstrlen=%u", message_->getPstrlen())); } - if(memcmp(BtHandshakeMessage::BT_PSTR, message_->getPstr(), 19) != 0) { - throw DL_ABORT_EX - (fmt("invalid handshake pstr=%s", - util::percentEncode - (message_->getPstr(), 19).c_str())); + if (memcmp(BtHandshakeMessage::BT_PSTR, message_->getPstr(), 19) != 0) { + throw DL_ABORT_EX( + fmt("invalid handshake pstr=%s", + util::percentEncode(message_->getPstr(), 19).c_str())); } - if(memcmp(infoHash_, message_->getInfoHash(), sizeof(infoHash_)) != 0) { - throw DL_ABORT_EX - (fmt("invalid handshake info hash: expected:%s, actual:%s", - util::toHex(infoHash_, sizeof(infoHash_)).c_str(), - util::toHex(message_->getInfoHash(), - INFO_HASH_LENGTH).c_str())); + if (memcmp(infoHash_, message_->getInfoHash(), sizeof(infoHash_)) != 0) { + throw DL_ABORT_EX( + fmt("invalid handshake info hash: expected:%s, actual:%s", + util::toHex(infoHash_, sizeof(infoHash_)).c_str(), + util::toHex(message_->getInfoHash(), INFO_HASH_LENGTH).c_str())); } } diff --git a/src/BtHandshakeMessageValidator.h b/src/BtHandshakeMessageValidator.h index 992aec04..4182a4b5 100644 --- a/src/BtHandshakeMessageValidator.h +++ b/src/BtHandshakeMessageValidator.h @@ -49,6 +49,7 @@ class BtHandshakeMessageValidator : public BtMessageValidator { private: const BtHandshakeMessage* message_; unsigned char infoHash_[INFO_HASH_LENGTH]; + public: BtHandshakeMessageValidator(const BtHandshakeMessage* message, const unsigned char* infoHash); diff --git a/src/BtHaveAllMessage.cc b/src/BtHaveAllMessage.cc index 9bf23472..35e47807 100644 --- a/src/BtHaveAllMessage.cc +++ b/src/BtHaveAllMessage.cc @@ -43,30 +43,29 @@ namespace aria2 { const char BtHaveAllMessage::NAME[] = "have all"; -BtHaveAllMessage::BtHaveAllMessage():ZeroBtMessage(ID, NAME) {} +BtHaveAllMessage::BtHaveAllMessage() : ZeroBtMessage(ID, NAME) {} -std::unique_ptr BtHaveAllMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtHaveAllMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create(data, dataLength); } void BtHaveAllMessage::doReceivedAction() { - if(!getPeer()->isFastExtensionEnabled()) { - throw DL_ABORT_EX - (fmt("%s received while fast extension is disabled", - toString().c_str())); + if (!getPeer()->isFastExtensionEnabled()) { + throw DL_ABORT_EX(fmt("%s received while fast extension is disabled", + toString().c_str())); } - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } getPieceStorage()->subtractPieceStats(getPeer()->getBitfield(), getPeer()->getBitfieldLength()); getPeer()->setAllBitfield(); - getPieceStorage()->addPieceStats - (getPeer()->getBitfield(), getPeer()->getBitfieldLength()); - if(getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { + getPieceStorage()->addPieceStats(getPeer()->getBitfield(), + getPeer()->getBitfieldLength()); + if (getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER); } } diff --git a/src/BtHaveAllMessage.h b/src/BtHaveAllMessage.h index efa31dd6..d5c17205 100644 --- a/src/BtHaveAllMessage.h +++ b/src/BtHaveAllMessage.h @@ -47,8 +47,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; }; diff --git a/src/BtHaveMessage.cc b/src/BtHaveMessage.cc index 22b3c27a..246526f8 100644 --- a/src/BtHaveMessage.cc +++ b/src/BtHaveMessage.cc @@ -42,24 +42,24 @@ namespace aria2 { const char BtHaveMessage::NAME[] = "have"; -BtHaveMessage::BtHaveMessage(size_t index):IndexBtMessage(ID, NAME, index) {} +BtHaveMessage::BtHaveMessage(size_t index) : IndexBtMessage(ID, NAME, index) {} -std::unique_ptr BtHaveMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr BtHaveMessage::create(const unsigned char* data, + size_t dataLength) { return IndexBtMessage::create(data, dataLength); } void BtHaveMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } size_t index = getIndex(); - if(!getPeer()->hasPiece(index)) { + if (!getPeer()->hasPiece(index)) { getPeer()->updateBitfield(index, 1); getPieceStorage()->addPieceStats(index); - if(getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { + if (getPeer()->isSeeder() && getPieceStorage()->downloadFinished()) { throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER); } } diff --git a/src/BtHaveMessage.h b/src/BtHaveMessage.h index 45ca574d..6c6cceef 100644 --- a/src/BtHaveMessage.h +++ b/src/BtHaveMessage.h @@ -47,8 +47,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; }; diff --git a/src/BtHaveNoneMessage.cc b/src/BtHaveNoneMessage.cc index 6f1e5460..21cbb61b 100644 --- a/src/BtHaveNoneMessage.cc +++ b/src/BtHaveNoneMessage.cc @@ -41,20 +41,19 @@ namespace aria2 { const char BtHaveNoneMessage::NAME[] = "have none"; -BtHaveNoneMessage::BtHaveNoneMessage():ZeroBtMessage(ID, NAME) {} +BtHaveNoneMessage::BtHaveNoneMessage() : ZeroBtMessage(ID, NAME) {} -std::unique_ptr BtHaveNoneMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtHaveNoneMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create(data, dataLength); } void BtHaveNoneMessage::doReceivedAction() { - if(!getPeer()->isFastExtensionEnabled()) { - throw DL_ABORT_EX - (fmt("%s received while fast extension is disabled", - toString().c_str())); + if (!getPeer()->isFastExtensionEnabled()) { + throw DL_ABORT_EX(fmt("%s received while fast extension is disabled", + toString().c_str())); } } diff --git a/src/BtHaveNoneMessage.h b/src/BtHaveNoneMessage.h index f68cd2d5..3ef74e39 100644 --- a/src/BtHaveNoneMessage.h +++ b/src/BtHaveNoneMessage.h @@ -47,8 +47,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; }; diff --git a/src/BtInteractive.h b/src/BtInteractive.h index a6881dfd..33f55586 100644 --- a/src/BtInteractive.h +++ b/src/BtInteractive.h @@ -41,7 +41,6 @@ namespace aria2 { - class BtHandshakeMessage; class BtInteractive { @@ -50,8 +49,8 @@ public: virtual void initiateHandshake() = 0; - virtual std::unique_ptr receiveHandshake - (bool quickReply = false) = 0; + virtual std::unique_ptr + receiveHandshake(bool quickReply = false) = 0; virtual std::unique_ptr receiveAndSendHandshake() = 0; diff --git a/src/BtInterestedMessage.cc b/src/BtInterestedMessage.cc index 2ef30600..c3c9fec2 100644 --- a/src/BtInterestedMessage.cc +++ b/src/BtInterestedMessage.cc @@ -42,25 +42,25 @@ namespace aria2 { const char BtInterestedMessage::NAME[] = "interested"; BtInterestedMessage::BtInterestedMessage() - : ZeroBtMessage(ID, NAME), - peerStorage_(nullptr) -{} + : ZeroBtMessage(ID, NAME), peerStorage_(nullptr) +{ +} BtInterestedMessage::~BtInterestedMessage() {} -std::unique_ptr BtInterestedMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtInterestedMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create(data, dataLength); } void BtInterestedMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } getPeer()->peerInterested(true); - if(!getPeer()->amChoking()) { + if (!getPeer()->amChoking()) { peerStorage_->executeChoke(); } } @@ -72,11 +72,10 @@ bool BtInterestedMessage::sendPredicate() const namespace { struct ThisProgressUpdate : public ProgressUpdate { - ThisProgressUpdate(std::shared_ptr peer) - : peer(std::move(peer)) {} + ThisProgressUpdate(std::shared_ptr peer) : peer(std::move(peer)) {} virtual void update(size_t length, bool complete) CXX11_OVERRIDE { - if(complete) { + if (complete) { peer->amInterested(true); } } diff --git a/src/BtInterestedMessage.h b/src/BtInterestedMessage.h index a11303a7..31d898e7 100644 --- a/src/BtInterestedMessage.h +++ b/src/BtInterestedMessage.h @@ -45,6 +45,7 @@ class BtInterestedMessage; class BtInterestedMessage : public ZeroBtMessage { private: PeerStorage* peerStorage_; + public: BtInterestedMessage(); virtual ~BtInterestedMessage(); @@ -53,8 +54,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BtKeepAliveMessage.cc b/src/BtKeepAliveMessage.cc index 998426b6..c9fe7937 100644 --- a/src/BtKeepAliveMessage.cc +++ b/src/BtKeepAliveMessage.cc @@ -50,9 +50,6 @@ unsigned char* BtKeepAliveMessage::createMessage() return msg; } -size_t BtKeepAliveMessage::getMessageLength() -{ - return MESSAGE_LENGTH; -} +size_t BtKeepAliveMessage::getMessageLength() { return MESSAGE_LENGTH; } } // namespace aria2 diff --git a/src/BtKeepAliveMessage.h b/src/BtKeepAliveMessage.h index 8ee940ea..23c0e73a 100644 --- a/src/BtKeepAliveMessage.h +++ b/src/BtKeepAliveMessage.h @@ -42,8 +42,9 @@ namespace aria2 { class BtKeepAliveMessage : public SimpleBtMessage { private: static const size_t MESSAGE_LENGTH = 4; + public: - BtKeepAliveMessage():SimpleBtMessage(ID, NAME) {} + BtKeepAliveMessage() : SimpleBtMessage(ID, NAME) {} static const uint8_t ID = 99; @@ -55,10 +56,7 @@ public: virtual size_t getMessageLength() CXX11_OVERRIDE; - virtual std::string toString() const CXX11_OVERRIDE - { - return NAME; - } + virtual std::string toString() const CXX11_OVERRIDE { return NAME; } }; } // namespace aria2 diff --git a/src/BtLeecherStateChoke.cc b/src/BtLeecherStateChoke.cc index a7ddd58f..72d0be9f 100644 --- a/src/BtLeecherStateChoke.cc +++ b/src/BtLeecherStateChoke.cc @@ -46,27 +46,28 @@ namespace aria2 { BtLeecherStateChoke::BtLeecherStateChoke() - : round_(0), - lastRound_(Timer::zero()) -{} + : round_(0), lastRound_(Timer::zero()) +{ +} BtLeecherStateChoke::~BtLeecherStateChoke() {} BtLeecherStateChoke::PeerEntry::PeerEntry(const std::shared_ptr& peer) - : peer_(peer), - downloadSpeed_(peer->calculateDownloadSpeed()), - // peer must be interested to us and sent block in the last 30 seconds - regularUnchoker_( - peer->peerInterested() && - peer->getLastDownloadUpdate().difference(global::wallclock()) < 30_s) + : peer_(peer), + downloadSpeed_(peer->calculateDownloadSpeed()), + // peer must be interested to us and sent block in the last 30 seconds + regularUnchoker_( + peer->peerInterested() && + peer->getLastDownloadUpdate().difference(global::wallclock()) < 30_s) { } BtLeecherStateChoke::PeerEntry::PeerEntry(const PeerEntry& c) - : peer_(c.peer_), - downloadSpeed_(c.downloadSpeed_), - regularUnchoker_(c.regularUnchoker_) -{} + : peer_(c.peer_), + downloadSpeed_(c.downloadSpeed_), + regularUnchoker_(c.regularUnchoker_) +{ +} void BtLeecherStateChoke::PeerEntry::swap(PeerEntry& c) { @@ -76,10 +77,10 @@ void BtLeecherStateChoke::PeerEntry::swap(PeerEntry& c) swap(regularUnchoker_, c.regularUnchoker_); } -BtLeecherStateChoke::PeerEntry& BtLeecherStateChoke::PeerEntry::operator= -(const PeerEntry& c) +BtLeecherStateChoke::PeerEntry& BtLeecherStateChoke::PeerEntry:: +operator=(const PeerEntry& c) { - if(this != &c) { + if (this != &c) { peer_ = c.peer_; downloadSpeed_ = c.downloadSpeed_; regularUnchoker_ = c.regularUnchoker_; @@ -129,29 +130,27 @@ bool BtLeecherStateChoke::PeerEntry::operator<(const PeerEntry& peerEntry) const return downloadSpeed_ > peerEntry.downloadSpeed_; } -void swap -(BtLeecherStateChoke::PeerEntry& a, - BtLeecherStateChoke::PeerEntry& b) +void swap(BtLeecherStateChoke::PeerEntry& a, BtLeecherStateChoke::PeerEntry& b) { a.swap(b); } -bool BtLeecherStateChoke::PeerFilter::operator() - (const PeerEntry& peerEntry) const +bool BtLeecherStateChoke::PeerFilter:: +operator()(const PeerEntry& peerEntry) const { return peerEntry.getPeer()->amChoking() == amChoking_ && - peerEntry.getPeer()->peerInterested() == peerInterested_; + peerEntry.getPeer()->peerInterested() == peerInterested_; } -void BtLeecherStateChoke::plannedOptimisticUnchoke -(std::vector& peerEntries) +void BtLeecherStateChoke::plannedOptimisticUnchoke( + std::vector& peerEntries) { std::for_each(std::begin(peerEntries), std::end(peerEntries), std::mem_fn(&PeerEntry::disableOptUnchoking)); auto i = std::partition(std::begin(peerEntries), std::end(peerEntries), PeerFilter(true, true)); - if(i != std::begin(peerEntries)) { + if (i != std::begin(peerEntries)) { std::shuffle(std::begin(peerEntries), i, *SimpleRandomizer::getInstance()); (*std::begin(peerEntries)).enableOptUnchoking(); A2_LOG_INFO( @@ -172,25 +171,26 @@ void BtLeecherStateChoke::regularUnchoke(std::vector& peerEntries) bool fastOptUnchoker = false; auto peerIter = std::begin(peerEntries); - for(;peerIter != rest && count; ++peerIter, --count) { + for (; peerIter != rest && count; ++peerIter, --count) { peerIter->disableChokingRequired(); A2_LOG_INFO(fmt("RU: %s, dlspd=%d", (*peerIter).getPeer()->getIPAddress().c_str(), (*peerIter).getDownloadSpeed())); - if(peerIter->getPeer()->optUnchoking()) { + if (peerIter->getPeer()->optUnchoking()) { fastOptUnchoker = true; peerIter->disableOptUnchoking(); } } - if(fastOptUnchoker) { + if (fastOptUnchoker) { std::shuffle(peerIter, std::end(peerEntries), *SimpleRandomizer::getInstance()); for (auto& p : peerEntries) { - if(p.getPeer()->peerInterested()) { + if (p.getPeer()->peerInterested()) { p.enableOptUnchoking(); A2_LOG_INFO(fmt("OU: %s", p.getPeer()->getIPAddress().c_str())); break; - } else { + } + else { p.disableChokingRequired(); A2_LOG_INFO(fmt("OU: %s", p.getPeer()->getIPAddress().c_str())); } @@ -205,26 +205,23 @@ void BtLeecherStateChoke::executeChoke(const PeerSet& peerSet) std::vector peerEntries; for (const auto& p : peerSet) { - if(p->isActive() && !p->snubbing()) { + if (p->isActive() && !p->snubbing()) { p->chokingRequired(true); peerEntries.push_back(PeerEntry(p)); } } // planned optimistic unchoke - if(round_ == 0) { + if (round_ == 0) { plannedOptimisticUnchoke(peerEntries); } regularUnchoke(peerEntries); - if(++round_ == 3) { + if (++round_ == 3) { round_ = 0; } } -const Timer& BtLeecherStateChoke::getLastRound() const -{ - return lastRound_; -} +const Timer& BtLeecherStateChoke::getLastRound() const { return lastRound_; } } // namespace aria2 diff --git a/src/BtLeecherStateChoke.h b/src/BtLeecherStateChoke.h index cfe0cfc0..aefc388a 100644 --- a/src/BtLeecherStateChoke.h +++ b/src/BtLeecherStateChoke.h @@ -58,6 +58,7 @@ private: std::shared_ptr peer_; int downloadSpeed_; bool regularUnchoker_; + public: PeerEntry(const std::shared_ptr& peer); PeerEntry(const PeerEntry& c); @@ -92,13 +93,16 @@ private: private: bool amChoking_; bool peerInterested_; + public: - PeerFilter(bool amChoking, bool peerInterested): - amChoking_(amChoking), - peerInterested_(peerInterested) {} + PeerFilter(bool amChoking, bool peerInterested) + : amChoking_(amChoking), peerInterested_(peerInterested) + { + } bool operator()(const PeerEntry& peerEntry) const; }; + public: BtLeecherStateChoke(); @@ -111,9 +115,7 @@ public: friend void swap(PeerEntry& a, PeerEntry& b); }; -void swap -(BtLeecherStateChoke::PeerEntry& a, - BtLeecherStateChoke::PeerEntry& b); +void swap(BtLeecherStateChoke::PeerEntry& a, BtLeecherStateChoke::PeerEntry& b); } // namespace aria2 diff --git a/src/BtMessage.h b/src/BtMessage.h index 5770dc13..7b60a5a3 100644 --- a/src/BtMessage.h +++ b/src/BtMessage.h @@ -50,8 +50,9 @@ class BtEvent; class BtMessage { private: uint8_t id_; + public: - BtMessage(uint8_t id):id_(id) {} + BtMessage(uint8_t id) : id_(id) {} virtual ~BtMessage() {} @@ -67,18 +68,17 @@ public: virtual void validate() = 0; - virtual void onAbortOutstandingRequestEvent - (const BtAbortOutstandingRequestEvent& event) = 0; + virtual void onAbortOutstandingRequestEvent( + const BtAbortOutstandingRequestEvent& event) = 0; - virtual void onCancelSendingPieceEvent - (const BtCancelSendingPieceEvent& event) = 0; + virtual void + onCancelSendingPieceEvent(const BtCancelSendingPieceEvent& event) = 0; virtual void onChokingEvent(const BtChokingEvent& event) = 0; virtual void onQueued() = 0; virtual std::string toString() const = 0; - }; } // namespace aria2 diff --git a/src/BtMessageDispatcher.h b/src/BtMessageDispatcher.h index 6f587630..7f4b986a 100644 --- a/src/BtMessageDispatcher.h +++ b/src/BtMessageDispatcher.h @@ -55,12 +55,14 @@ public: virtual void sendMessages() = 0; - virtual void doCancelSendingPieceAction - (size_t index, int32_t begin, int32_t length) = 0; + virtual void doCancelSendingPieceAction(size_t index, int32_t begin, + int32_t length) = 0; - virtual void doCancelSendingPieceAction(const std::shared_ptr& piece) = 0; + virtual void + doCancelSendingPieceAction(const std::shared_ptr& piece) = 0; - virtual void doAbortOutstandingRequestAction(const std::shared_ptr& piece) = 0; + virtual void + doAbortOutstandingRequestAction(const std::shared_ptr& piece) = 0; virtual void doChokedAction() = 0; @@ -76,8 +78,8 @@ public: virtual bool isOutstandingRequest(size_t index, size_t blockIndex) = 0; - virtual const RequestSlot* getOutstandingRequest - (size_t index, int32_t begin, int32_t length) = 0; + virtual const RequestSlot* getOutstandingRequest(size_t index, int32_t begin, + int32_t length) = 0; virtual void removeOutstandingRequest(const RequestSlot* slot) = 0; diff --git a/src/BtMessageFactory.h b/src/BtMessageFactory.h index fb9e41fd..42940be7 100644 --- a/src/BtMessageFactory.h +++ b/src/BtMessageFactory.h @@ -66,8 +66,8 @@ class BtMessageFactory { public: virtual ~BtMessageFactory() {} - virtual std::unique_ptr - createBtMessage(const unsigned char* msg, size_t msgLength) = 0; + virtual std::unique_ptr createBtMessage(const unsigned char* msg, + size_t msgLength) = 0; virtual std::unique_ptr createHandshakeMessage(const unsigned char* msg, size_t msgLength) = 0; diff --git a/src/BtMessageReceiver.h b/src/BtMessageReceiver.h index 6651d2d2..ea72dc7c 100644 --- a/src/BtMessageReceiver.h +++ b/src/BtMessageReceiver.h @@ -48,8 +48,8 @@ class BtMessageReceiver { public: virtual ~BtMessageReceiver() {} - virtual std::unique_ptr receiveHandshake - (bool quickReply = false) = 0; + virtual std::unique_ptr + receiveHandshake(bool quickReply = false) = 0; virtual std::unique_ptr receiveAndSendHandshake() = 0; diff --git a/src/BtNotInterestedMessage.cc b/src/BtNotInterestedMessage.cc index c79a27de..45c39de1 100644 --- a/src/BtNotInterestedMessage.cc +++ b/src/BtNotInterestedMessage.cc @@ -42,25 +42,25 @@ namespace aria2 { const char BtNotInterestedMessage::NAME[] = "not interested"; BtNotInterestedMessage::BtNotInterestedMessage() - : ZeroBtMessage(ID, NAME), - peerStorage_(nullptr) -{} + : ZeroBtMessage(ID, NAME), peerStorage_(nullptr) +{ +} BtNotInterestedMessage::~BtNotInterestedMessage() {} -std::unique_ptr BtNotInterestedMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtNotInterestedMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create(data, dataLength); } void BtNotInterestedMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } getPeer()->peerInterested(false); - if(!getPeer()->amChoking()) { + if (!getPeer()->amChoking()) { peerStorage_->executeChoke(); } } @@ -72,11 +72,10 @@ bool BtNotInterestedMessage::sendPredicate() const namespace { struct ThisProgressUpdate : public ProgressUpdate { - ThisProgressUpdate(std::shared_ptr peer) - : peer(std::move(peer)) {} + ThisProgressUpdate(std::shared_ptr peer) : peer(std::move(peer)) {} virtual void update(size_t length, bool complete) CXX11_OVERRIDE { - if(complete) { + if (complete) { peer->amInterested(false); } } diff --git a/src/BtNotInterestedMessage.h b/src/BtNotInterestedMessage.h index 9461b726..ae958bf5 100644 --- a/src/BtNotInterestedMessage.h +++ b/src/BtNotInterestedMessage.h @@ -45,6 +45,7 @@ class BtNotInterestedMessage; class BtNotInterestedMessage : public ZeroBtMessage { private: PeerStorage* peerStorage_; + public: BtNotInterestedMessage(); virtual ~BtNotInterestedMessage(); @@ -53,8 +54,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr + create(const unsigned char* data, size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BtPieceMessage.cc b/src/BtPieceMessage.cc index 010e31c5..80026b23 100644 --- a/src/BtPieceMessage.cc +++ b/src/BtPieceMessage.cc @@ -66,93 +66,88 @@ namespace aria2 { const char BtPieceMessage::NAME[] = "piece"; -BtPieceMessage::BtPieceMessage -(size_t index, int32_t begin, int32_t blockLength) - : AbstractBtMessage(ID, NAME), - index_(index), - begin_(begin), - blockLength_(blockLength), - data_(nullptr), - downloadContext_(nullptr), - peerStorage_(nullptr) +BtPieceMessage::BtPieceMessage(size_t index, int32_t begin, int32_t blockLength) + : AbstractBtMessage(ID, NAME), + index_(index), + begin_(begin), + blockLength_(blockLength), + data_(nullptr), + downloadContext_(nullptr), + peerStorage_(nullptr) { setUploading(true); } -BtPieceMessage::~BtPieceMessage() -{} +BtPieceMessage::~BtPieceMessage() {} -void BtPieceMessage::setMsgPayload(const unsigned char* data) -{ - data_ = data; -} +void BtPieceMessage::setMsgPayload(const unsigned char* data) { data_ = data; } -std::unique_ptr BtPieceMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtPieceMessage::create(const unsigned char* data, size_t dataLength) { bittorrent::assertPayloadLengthGreater(9, dataLength, NAME); bittorrent::assertID(ID, data, NAME); return make_unique(bittorrent::getIntParam(data, 1), bittorrent::getIntParam(data, 5), - dataLength-9); + dataLength - 9); } void BtPieceMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } - auto slot = getBtMessageDispatcher()->getOutstandingRequest - (index_, begin_, blockLength_); + auto slot = getBtMessageDispatcher()->getOutstandingRequest(index_, begin_, + blockLength_); getPeer()->updateDownloadLength(blockLength_); downloadContext_->updateDownloadLength(blockLength_); - if(slot) { + if (slot) { getPeer()->snubbing(false); std::shared_ptr piece = getPieceStorage()->getPiece(index_); int64_t offset = - static_cast(index_)*downloadContext_->getPieceLength()+begin_; - A2_LOG_DEBUG(fmt(MSG_PIECE_RECEIVED, - getCuid(), - static_cast(index_), - begin_, - blockLength_, + static_cast(index_) * downloadContext_->getPieceLength() + + begin_; + A2_LOG_DEBUG(fmt(MSG_PIECE_RECEIVED, getCuid(), + static_cast(index_), begin_, blockLength_, static_cast(offset), static_cast(slot->getBlockIndex()))); - if(piece->hasBlock(slot->getBlockIndex())) { + if (piece->hasBlock(slot->getBlockIndex())) { A2_LOG_DEBUG("Already have this block."); return; } - if(piece->getWrDiskCacheEntry()) { + if (piece->getWrDiskCacheEntry()) { // Write Disk Cache enabled. Unfortunately, it incurs extra data // copy. auto dataCopy = new unsigned char[blockLength_]; - memcpy(dataCopy, data_+9, blockLength_); - piece->updateWrCache(getPieceStorage()->getWrDiskCache(), - dataCopy, 0, blockLength_, blockLength_, offset); - } else { - getPieceStorage()->getDiskAdaptor()->writeData(data_+9, blockLength_, + memcpy(dataCopy, data_ + 9, blockLength_); + piece->updateWrCache(getPieceStorage()->getWrDiskCache(), dataCopy, 0, + blockLength_, blockLength_, offset); + } + else { + getPieceStorage()->getDiskAdaptor()->writeData(data_ + 9, blockLength_, offset); } piece->completeBlock(slot->getBlockIndex()); - A2_LOG_DEBUG(fmt(MSG_PIECE_BITFIELD, getCuid(), - util::toHex(piece->getBitfield(), - piece->getBitfieldLength()).c_str())); - piece->updateHash(begin_, data_+9, blockLength_); + A2_LOG_DEBUG(fmt( + MSG_PIECE_BITFIELD, getCuid(), + util::toHex(piece->getBitfield(), piece->getBitfieldLength()).c_str())); + piece->updateHash(begin_, data_ + 9, blockLength_); getBtMessageDispatcher()->removeOutstandingRequest(slot); - if(piece->pieceComplete()) { - if(checkPieceHash(piece)) { + if (piece->pieceComplete()) { + if (checkPieceHash(piece)) { onNewPiece(piece); - } else { + } + else { onWrongPiece(piece); peerStorage_->addBadPeer(getPeer()->getIPAddress()); throw DL_ABORT_EX("Bad piece hash."); } } - } else { - A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - RequestSlot not found, index=%lu, begin=%d", - getCuid(), - static_cast(index_), - begin_)); + } + else { + A2_LOG_DEBUG(fmt("CUID#%" PRId64 + " - RequestSlot not found, index=%lu, begin=%d", + getCuid(), static_cast(index_), begin_)); } } @@ -168,7 +163,7 @@ void BtPieceMessage::createMessageHeader(unsigned char* msgHeader) const * total: 13bytes */ bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH, - 9+blockLength_, ID); + 9 + blockLength_, ID); bittorrent::setIntParam(&msgHeader[5], index_); bittorrent::setIntParam(&msgHeader[9], begin_); } @@ -180,11 +175,13 @@ size_t BtPieceMessage::getMessageHeaderLength() namespace { struct PieceSendUpdate : public ProgressUpdate { - PieceSendUpdate(std::shared_ptr peer, size_t headerLength) - : peer(std::move(peer)), headerLength(headerLength) {} + PieceSendUpdate(std::shared_ptr peer, size_t headerLength) + : peer(std::move(peer)), headerLength(headerLength) + { + } virtual void update(size_t length, bool complete) CXX11_OVERRIDE { - if(headerLength > 0) { + if (headerLength > 0) { size_t m = std::min(headerLength, length); headerLength -= m; length -= m; @@ -198,62 +195,62 @@ struct PieceSendUpdate : public ProgressUpdate { void BtPieceMessage::send() { - if(isInvalidate()) { + if (isInvalidate()) { return; } - A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE, - getCuid(), - getPeer()->getIPAddress().c_str(), - getPeer()->getPort(), + A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE, getCuid(), + getPeer()->getIPAddress().c_str(), getPeer()->getPort(), toString().c_str())); int64_t pieceDataOffset = - static_cast(index_)*downloadContext_->getPieceLength()+begin_; + static_cast(index_) * downloadContext_->getPieceLength() + + begin_; pushPieceData(pieceDataOffset, blockLength_); } void BtPieceMessage::pushPieceData(int64_t offset, int32_t length) const { assert(length <= static_cast(16_k)); - auto buf = make_unique(length+MESSAGE_HEADER_LENGTH); + auto buf = make_unique(length + MESSAGE_HEADER_LENGTH); createMessageHeader(buf.get()); ssize_t r; - r = getPieceStorage()->getDiskAdaptor()->readData - (buf.get()+MESSAGE_HEADER_LENGTH, length, offset); - if(r == length) { - getPeerConnection()->pushBytes(buf.release(), length+MESSAGE_HEADER_LENGTH, - make_unique - (getPeer(), MESSAGE_HEADER_LENGTH)); + r = getPieceStorage()->getDiskAdaptor()->readData( + buf.get() + MESSAGE_HEADER_LENGTH, length, offset); + if (r == length) { + getPeerConnection()->pushBytes( + buf.release(), length + MESSAGE_HEADER_LENGTH, + make_unique(getPeer(), MESSAGE_HEADER_LENGTH)); // To avoid upload rate overflow, we update the length here at // once. downloadContext_->updateUploadLength(length); - } else { + } + else { throw DL_ABORT_EX(EX_DATA_READ); } } std::string BtPieceMessage::toString() const { - return fmt("%s index=%lu, begin=%d, length=%d", - NAME, - static_cast(index_), - begin_, blockLength_); + return fmt("%s index=%lu, begin=%d, length=%d", NAME, + static_cast(index_), begin_, blockLength_); } bool BtPieceMessage::checkPieceHash(const std::shared_ptr& piece) { - if(!getPieceStorage()->isEndGame() && piece->isHashCalculated()) { + if (!getPieceStorage()->isEndGame() && piece->isHashCalculated()) { A2_LOG_DEBUG(fmt("Hash is available!! index=%lu", static_cast(piece->getIndex()))); - return - piece->getDigest() == downloadContext_->getPieceHash(piece->getIndex()); - } else { + return piece->getDigest() == + downloadContext_->getPieceHash(piece->getIndex()); + } + else { A2_LOG_DEBUG(fmt("Calculating hash index=%lu", static_cast(piece->getIndex()))); try { return piece->getDigestWithWrCache(downloadContext_->getPieceLength(), - getPieceStorage()->getDiskAdaptor()) - == downloadContext_->getPieceHash(piece->getIndex()); - } catch(RecoverableException& e) { + getPieceStorage()->getDiskAdaptor()) == + downloadContext_->getPieceHash(piece->getIndex()); + } + catch (RecoverableException& e) { piece->clearAllBlock(getPieceStorage()->getWrDiskCache()); throw; } @@ -262,20 +259,19 @@ bool BtPieceMessage::checkPieceHash(const std::shared_ptr& piece) void BtPieceMessage::onNewPiece(const std::shared_ptr& piece) { - if(piece->getWrDiskCacheEntry()) { + if (piece->getWrDiskCacheEntry()) { // We flush cached data whenever an whole piece is retrieved. - piece->flushWrCache(getPieceStorage()->getWrDiskCache()); - if(piece->getWrDiskCacheEntry()->getError() != + piece->flushWrCache(getPieceStorage()->getWrDiskCache()); + if (piece->getWrDiskCacheEntry()->getError() != WrDiskCacheEntry::CACHE_ERR_SUCCESS) { - piece->clearAllBlock(getPieceStorage()->getWrDiskCache()); - throw DOWNLOAD_FAILURE_EXCEPTION2 - (fmt("Write disk cache flush failure index=%lu", + piece->clearAllBlock(getPieceStorage()->getWrDiskCache()); + throw DOWNLOAD_FAILURE_EXCEPTION2( + fmt("Write disk cache flush failure index=%lu", static_cast(piece->getIndex())), piece->getWrDiskCacheEntry()->getErrorCode()); - } + } } - A2_LOG_INFO(fmt(MSG_GOT_NEW_PIECE, - getCuid(), + A2_LOG_INFO(fmt(MSG_GOT_NEW_PIECE, getCuid(), static_cast(piece->getIndex()))); getPieceStorage()->completePiece(piece); getPieceStorage()->advertisePiece(getCuid(), piece->getIndex()); @@ -283,8 +279,7 @@ void BtPieceMessage::onNewPiece(const std::shared_ptr& piece) void BtPieceMessage::onWrongPiece(const std::shared_ptr& piece) { - A2_LOG_INFO(fmt(MSG_GOT_WRONG_PIECE, - getCuid(), + A2_LOG_INFO(fmt(MSG_GOT_WRONG_PIECE, getCuid(), static_cast(piece->getIndex()))); piece->clearAllBlock(getPieceStorage()->getWrDiskCache()); piece->destroyHashContext(); @@ -293,38 +288,29 @@ void BtPieceMessage::onWrongPiece(const std::shared_ptr& piece) void BtPieceMessage::onChokingEvent(const BtChokingEvent& event) { - if(!isInvalidate() && - !getPeer()->isInAmAllowedIndexSet(index_)) { - A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CHOKED, - getCuid(), - static_cast(index_), - begin_, - blockLength_)); - if(getPeer()->isFastExtensionEnabled()) { - getBtMessageDispatcher()->addMessageToQueue - (getBtMessageFactory()->createRejectMessage - (index_, begin_, blockLength_)); + if (!isInvalidate() && !getPeer()->isInAmAllowedIndexSet(index_)) { + A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CHOKED, getCuid(), + static_cast(index_), begin_, blockLength_)); + if (getPeer()->isFastExtensionEnabled()) { + getBtMessageDispatcher()->addMessageToQueue( + getBtMessageFactory()->createRejectMessage(index_, begin_, + blockLength_)); } setInvalidate(true); } } -void BtPieceMessage::onCancelSendingPieceEvent -(const BtCancelSendingPieceEvent& event) +void BtPieceMessage::onCancelSendingPieceEvent( + const BtCancelSendingPieceEvent& event) { - if(!isInvalidate() && - index_ == event.getIndex() && - begin_ == event.getBegin() && - blockLength_ == event.getLength()) { - A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CANCEL, - getCuid(), - static_cast(index_), - begin_, - blockLength_)); - if(getPeer()->isFastExtensionEnabled()) { - getBtMessageDispatcher()->addMessageToQueue - (getBtMessageFactory()->createRejectMessage - (index_, begin_, blockLength_)); + if (!isInvalidate() && index_ == event.getIndex() && + begin_ == event.getBegin() && blockLength_ == event.getLength()) { + A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CANCEL, getCuid(), + static_cast(index_), begin_, blockLength_)); + if (getPeer()->isFastExtensionEnabled()) { + getBtMessageDispatcher()->addMessageToQueue( + getBtMessageFactory()->createRejectMessage(index_, begin_, + blockLength_)); } setInvalidate(true); } diff --git a/src/BtPieceMessage.h b/src/BtPieceMessage.h index 6ff8470d..58d73f29 100644 --- a/src/BtPieceMessage.h +++ b/src/BtPieceMessage.h @@ -61,6 +61,7 @@ private: void onWrongPiece(const std::shared_ptr& piece); void pushPieceData(int64_t offset, int32_t length) const; + public: BtPieceMessage(size_t index = 0, int32_t begin = 0, int32_t blockLength = 0); @@ -78,7 +79,7 @@ public: void setBegin(int32_t begin) { begin_ = begin; } - const unsigned char* getBlock() const { return data_+9; } + const unsigned char* getBlock() const { return data_ + 9; } int32_t getBlockLength() const { return blockLength_; } @@ -92,8 +93,8 @@ public: void setPeerStorage(PeerStorage* peerStorage); - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; @@ -107,8 +108,8 @@ public: virtual void onChokingEvent(const BtChokingEvent& event) CXX11_OVERRIDE; - virtual void onCancelSendingPieceEvent - (const BtCancelSendingPieceEvent& event) CXX11_OVERRIDE; + virtual void onCancelSendingPieceEvent(const BtCancelSendingPieceEvent& event) + CXX11_OVERRIDE; }; } // namespace aria2 diff --git a/src/BtPieceMessageValidator.cc b/src/BtPieceMessageValidator.cc index 4b5ef38b..f8bb736d 100644 --- a/src/BtPieceMessageValidator.cc +++ b/src/BtPieceMessageValidator.cc @@ -38,12 +38,12 @@ namespace aria2 { -BtPieceMessageValidator::BtPieceMessageValidator -(const BtPieceMessage* message, size_t numPiece, int32_t pieceLength) - : message_(message), - numPiece_(numPiece), - pieceLength_(pieceLength) -{} +BtPieceMessageValidator::BtPieceMessageValidator(const BtPieceMessage* message, + size_t numPiece, + int32_t pieceLength) + : message_(message), numPiece_(numPiece), pieceLength_(pieceLength) +{ +} BtPieceMessageValidator::~BtPieceMessageValidator() {} diff --git a/src/BtPieceMessageValidator.h b/src/BtPieceMessageValidator.h index 89c9d9b1..b1e57e0b 100644 --- a/src/BtPieceMessageValidator.h +++ b/src/BtPieceMessageValidator.h @@ -46,9 +46,9 @@ private: const BtPieceMessage* message_; size_t numPiece_; int32_t pieceLength_; + public: - BtPieceMessageValidator(const BtPieceMessage* message, - size_t numPiece, + BtPieceMessageValidator(const BtPieceMessage* message, size_t numPiece, int32_t pieceLength); ~BtPieceMessageValidator(); diff --git a/src/BtPortMessage.cc b/src/BtPortMessage.cc index 1382a5d0..99b0d699 100644 --- a/src/BtPortMessage.cc +++ b/src/BtPortMessage.cc @@ -53,16 +53,17 @@ namespace aria2 { const char BtPortMessage::NAME[] = "port"; BtPortMessage::BtPortMessage(uint16_t port) - : SimpleBtMessage(ID, NAME), - port_(port), - localNode_(nullptr), - routingTable_(nullptr), - taskQueue_(nullptr), - taskFactory_(nullptr) -{} + : SimpleBtMessage(ID, NAME), + port_(port), + localNode_(nullptr), + routingTable_(nullptr), + taskQueue_(nullptr), + taskFactory_(nullptr) +{ +} -std::unique_ptr BtPortMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr BtPortMessage::create(const unsigned char* data, + size_t dataLength) { bittorrent::assertPayloadLengthEqual(3, dataLength, NAME); bittorrent::assertID(ID, data, NAME); @@ -72,8 +73,8 @@ std::unique_ptr BtPortMessage::create void BtPortMessage::doReceivedAction() { - if(taskFactory_ && taskQueue_) { - if(port_ == 0) { + if (taskFactory_ && taskQueue_) { + if (port_ == 0) { A2_LOG_DEBUG("Ignored port 0."); return; } @@ -86,15 +87,16 @@ void BtPortMessage::doReceivedAction() std::shared_ptr task = taskFactory_->createPingTask(node); taskQueue_->addImmediateTask(task); } - if(routingTable_->getNumBucket() == 1) { + if (routingTable_->getNumBucket() == 1) { // initiate bootstrap A2_LOG_INFO("Dispatch node_lookup since too few buckets."); - taskQueue_->addImmediateTask - (taskFactory_->createNodeLookupTask(localNode_->getID())); + taskQueue_->addImmediateTask( + taskFactory_->createNodeLookupTask(localNode_->getID())); } - } else { - A2_LOG_INFO - ("DHT port message received while localhost didn't declare support it."); + } + else { + A2_LOG_INFO( + "DHT port message received while localhost didn't declare support it."); } } @@ -112,18 +114,14 @@ unsigned char* BtPortMessage::createMessage() return msg; } -size_t BtPortMessage::getMessageLength() { - return MESSAGE_LENGTH; -} +size_t BtPortMessage::getMessageLength() { return MESSAGE_LENGTH; } -std::string BtPortMessage::toString() const { +std::string BtPortMessage::toString() const +{ return fmt("%s port=%u", NAME, port_); } -void BtPortMessage::setLocalNode(DHTNode* localNode) -{ - localNode_ = localNode; -} +void BtPortMessage::setLocalNode(DHTNode* localNode) { localNode_ = localNode; } void BtPortMessage::setRoutingTable(DHTRoutingTable* routingTable) { diff --git a/src/BtPortMessage.h b/src/BtPortMessage.h index 0846e125..453d74cb 100644 --- a/src/BtPortMessage.h +++ b/src/BtPortMessage.h @@ -56,6 +56,7 @@ private: DHTTaskQueue* taskQueue_; DHTTaskFactory* taskFactory_; + public: BtPortMessage(uint16_t port); @@ -65,8 +66,8 @@ public: uint16_t getPort() const { return port_; } - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BtPostDownloadHandler.cc b/src/BtPostDownloadHandler.cc index 60a911b9..a6c40833 100644 --- a/src/BtPostDownloadHandler.cc +++ b/src/BtPostDownloadHandler.cc @@ -58,63 +58,63 @@ namespace aria2 { BtPostDownloadHandler::BtPostDownloadHandler() { - setCriteria(make_unique - (getBtContentTypes(), getBtExtensions())); + setCriteria(make_unique(getBtContentTypes(), + getBtExtensions())); } -void BtPostDownloadHandler::getNextRequestGroups -(std::vector >& groups, - RequestGroup* requestGroup) const +void BtPostDownloadHandler::getNextRequestGroups( + std::vector>& groups, + RequestGroup* requestGroup) const { A2_LOG_INFO(fmt("Generating RequestGroups for Torrent file %s", requestGroup->getFirstFilePath().c_str())); std::unique_ptr torrent; - if(requestGroup->inMemoryDownload()) { - auto& dw = static_cast - (requestGroup->getPieceStorage()->getDiskAdaptor().get()) - ->getDiskWriter(); + if (requestGroup->inMemoryDownload()) { + auto& dw = static_cast( + requestGroup->getPieceStorage()->getDiskAdaptor().get()) + ->getDiskWriter(); auto bdw = static_cast(dw.get()); int error = bdw->finalize(); - if(error == 0) { + if (error == 0) { torrent = bdw->getResult(); } - } else { + } + else { std::string content; try { requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile(); - content = util::toString(requestGroup->getPieceStorage() - ->getDiskAdaptor()); + content = + util::toString(requestGroup->getPieceStorage()->getDiskAdaptor()); requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile(); - } catch(Exception& e) { + } + catch (Exception& e) { requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile(); throw; } ssize_t error; - torrent = bittorrent::ValueBaseBencodeParser().parseFinal - (content.c_str(), content.size(), error); + torrent = bittorrent::ValueBaseBencodeParser().parseFinal( + content.c_str(), content.size(), error); } - if(!torrent) { + if (!torrent) { throw DL_ABORT_EX2("Could not parse BitTorrent metainfo", error_code::BENCODE_PARSE_ERROR); } std::vector> newRgs; createRequestGroupForBitTorrent(newRgs, requestGroup->getOption(), - std::vector(), - "", + std::vector(), "", torrent.get()); requestGroup->followedBy(std::begin(newRgs), std::end(newRgs)); - auto mi = - createMetadataInfoFromFirstFileEntry(requestGroup->getGroupId(), - requestGroup->getDownloadContext()); - if(mi) { + auto mi = createMetadataInfoFromFirstFileEntry( + requestGroup->getGroupId(), requestGroup->getDownloadContext()); + if (mi) { setMetadataInfo(std::begin(newRgs), std::end(newRgs), mi); } auto rgman = requestGroup->getRequestGroupMan(); - if(rgman && rgman->getKeepRunning() && - requestGroup->getOption()->getAsBool(PREF_PAUSE_METADATA)) { - for(auto& rg : newRgs) { + if (rgman && rgman->getKeepRunning() && + requestGroup->getOption()->getAsBool(PREF_PAUSE_METADATA)) { + for (auto& rg : newRgs) { rg->setPauseRequested(true); } } diff --git a/src/BtPostDownloadHandler.h b/src/BtPostDownloadHandler.h index 6e99b956..5eefb6af 100644 --- a/src/BtPostDownloadHandler.h +++ b/src/BtPostDownloadHandler.h @@ -39,13 +39,12 @@ namespace aria2 { -class BtPostDownloadHandler:public PostDownloadHandler -{ +class BtPostDownloadHandler : public PostDownloadHandler { public: BtPostDownloadHandler(); virtual void - getNextRequestGroups(std::vector >& groups, + getNextRequestGroups(std::vector>& groups, RequestGroup* requestGroup) const CXX11_OVERRIDE; }; diff --git a/src/BtRegistry.cc b/src/BtRegistry.cc index 84dfd9a8..f2d33b73 100644 --- a/src/BtRegistry.cc +++ b/src/BtRegistry.cc @@ -47,18 +47,16 @@ namespace aria2 { -BtRegistry::BtRegistry() - : tcpPort_{0}, - udpPort_{0} -{} +BtRegistry::BtRegistry() : tcpPort_{0}, udpPort_{0} {} const std::shared_ptr& BtRegistry::getDownloadContext(a2_gid_t gid) const { auto res = get(gid); - if(res) { + if (res) { return res->downloadContext; - } else { + } + else { return getNull(); } } @@ -66,9 +64,9 @@ BtRegistry::getDownloadContext(a2_gid_t gid) const const std::shared_ptr& BtRegistry::getDownloadContext(const std::string& infoHash) const { - for(auto& kv : pool_) { - if(bittorrent::getTorrentAttrs(kv.second->downloadContext)->infoHash == - infoHash) { + for (auto& kv : pool_) { + if (bittorrent::getTorrentAttrs(kv.second->downloadContext)->infoHash == + infoHash) { return kv.second->downloadContext; } } @@ -83,49 +81,45 @@ void BtRegistry::put(a2_gid_t gid, std::unique_ptr obj) BtObject* BtRegistry::get(a2_gid_t gid) const { auto i = pool_.find(gid); - if(i == std::end(pool_)) { + if (i == std::end(pool_)) { return nullptr; - } else { + } + else { return (*i).second.get(); } } -bool BtRegistry::remove(a2_gid_t gid) -{ - return pool_.erase(gid); -} +bool BtRegistry::remove(a2_gid_t gid) { return pool_.erase(gid); } -void BtRegistry::removeAll() -{ - pool_.clear(); -} +void BtRegistry::removeAll() { pool_.clear(); } -void BtRegistry::setLpdMessageReceiver -(const std::shared_ptr& receiver) +void BtRegistry::setLpdMessageReceiver( + const std::shared_ptr& receiver) { lpdMessageReceiver_ = receiver; } -void BtRegistry::setUDPTrackerClient -(const std::shared_ptr& tracker) +void BtRegistry::setUDPTrackerClient( + const std::shared_ptr& tracker) { udpTrackerClient_ = tracker; } -BtObject::BtObject -(const std::shared_ptr& downloadContext, - const std::shared_ptr& pieceStorage, - const std::shared_ptr& peerStorage, - const std::shared_ptr& btAnnounce, - const std::shared_ptr& btRuntime, - const std::shared_ptr& btProgressInfoFile) - : downloadContext{downloadContext}, - pieceStorage{pieceStorage}, - peerStorage{peerStorage}, - btAnnounce{btAnnounce}, - btRuntime{btRuntime}, - btProgressInfoFile{btProgressInfoFile} -{} +BtObject::BtObject( + const std::shared_ptr& downloadContext, + const std::shared_ptr& pieceStorage, + const std::shared_ptr& peerStorage, + const std::shared_ptr& btAnnounce, + const std::shared_ptr& btRuntime, + const std::shared_ptr& btProgressInfoFile) + : downloadContext{downloadContext}, + pieceStorage{pieceStorage}, + peerStorage{peerStorage}, + btAnnounce{btAnnounce}, + btRuntime{btRuntime}, + btProgressInfoFile{btProgressInfoFile} +{ +} BtObject::BtObject() {} diff --git a/src/BtRegistry.h b/src/BtRegistry.h index dc4cab90..d5659764 100644 --- a/src/BtRegistry.h +++ b/src/BtRegistry.h @@ -80,6 +80,7 @@ private: uint16_t udpPort_; std::shared_ptr lpdMessageReceiver_; std::shared_ptr udpTrackerClient_; + public: BtRegistry(); @@ -93,10 +94,10 @@ public: BtObject* get(a2_gid_t gid) const; - template + template OutputIterator getAllDownloadContext(OutputIterator dest) { - for(auto& kv : pool_) { + for (auto& kv : pool_) { *dest++ = kv.second->downloadContext; } return dest; @@ -106,25 +107,14 @@ public: bool remove(a2_gid_t gid); - void setTcpPort(uint16_t port) - { - tcpPort_ = port; - } - uint16_t getTcpPort() const - { - return tcpPort_; - } + void setTcpPort(uint16_t port) { tcpPort_ = port; } + uint16_t getTcpPort() const { return tcpPort_; } - void setUdpPort(uint16_t port) - { - udpPort_ = port; - } - uint16_t getUdpPort() const - { - return udpPort_; - } + void setUdpPort(uint16_t port) { udpPort_ = port; } + uint16_t getUdpPort() const { return udpPort_; } - void setLpdMessageReceiver(const std::shared_ptr& receiver); + void + setLpdMessageReceiver(const std::shared_ptr& receiver); const std::shared_ptr& getLpdMessageReceiver() const { return lpdMessageReceiver_; diff --git a/src/BtRejectMessage.cc b/src/BtRejectMessage.cc index d26440ea..d9ebba30 100644 --- a/src/BtRejectMessage.cc +++ b/src/BtRejectMessage.cc @@ -43,36 +43,37 @@ namespace aria2 { const char BtRejectMessage::NAME[] = "reject"; -BtRejectMessage::BtRejectMessage -(size_t index, int32_t begin, int32_t length): - RangeBtMessage(ID, NAME, index, begin, length) {} +BtRejectMessage::BtRejectMessage(size_t index, int32_t begin, int32_t length) + : RangeBtMessage(ID, NAME, index, begin, length) +{ +} -std::unique_ptr BtRejectMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtRejectMessage::create(const unsigned char* data, size_t dataLength) { return RangeBtMessage::create(data, dataLength); } void BtRejectMessage::doReceivedAction() { - if(!getPeer()->isFastExtensionEnabled()) { - throw DL_ABORT_EX - (fmt("%s received while fast extension is disabled.", - toString().c_str())); + if (!getPeer()->isFastExtensionEnabled()) { + throw DL_ABORT_EX(fmt("%s received while fast extension is disabled.", + toString().c_str())); } - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } // TODO Current implementation does not close a connection even if // a request for this reject message has never sent. - auto slot = getBtMessageDispatcher()->getOutstandingRequest - (getIndex(), getBegin(), getLength()); - if(slot) { + auto slot = getBtMessageDispatcher()->getOutstandingRequest( + getIndex(), getBegin(), getLength()); + if (slot) { getBtMessageDispatcher()->removeOutstandingRequest(slot); - } else { - //throw DL_ABORT_EX("reject received, but it is not in the request slots."); } - + else { + // throw DL_ABORT_EX("reject received, but it is not in the request + // slots."); + } } } // namespace aria2 diff --git a/src/BtRejectMessage.h b/src/BtRejectMessage.h index 55fc8971..1e4ff271 100644 --- a/src/BtRejectMessage.h +++ b/src/BtRejectMessage.h @@ -47,8 +47,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; }; diff --git a/src/BtRequestFactory.h b/src/BtRequestFactory.h index 6f2da075..224db62d 100644 --- a/src/BtRequestFactory.h +++ b/src/BtRequestFactory.h @@ -69,15 +69,14 @@ public: * returned is capped by max. If |endGame| is true, returns * requests in end game mode. */ - virtual std::vector> createRequestMessages - (size_t max, bool endGame) = 0; + virtual std::vector> + createRequestMessages(size_t max, bool endGame) = 0; /** * Returns the list of index of pieces added using addTargetPiece() * into indexes. */ virtual std::vector getTargetPieceIndexes() const = 0; - }; } // namespace aria2 diff --git a/src/BtRequestMessage.cc b/src/BtRequestMessage.cc index 19ed7743..aa2752b0 100644 --- a/src/BtRequestMessage.cc +++ b/src/BtRequestMessage.cc @@ -45,49 +45,51 @@ namespace aria2 { const char BtRequestMessage::NAME[] = "request"; -BtRequestMessage::BtRequestMessage -(size_t index, int32_t begin, int32_t length, size_t blockIndex): - RangeBtMessage(ID, NAME, index, begin, length), - blockIndex_(blockIndex) {} +BtRequestMessage::BtRequestMessage(size_t index, int32_t begin, int32_t length, + size_t blockIndex) + : RangeBtMessage(ID, NAME, index, begin, length), blockIndex_(blockIndex) +{ +} -std::unique_ptr BtRequestMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtRequestMessage::create(const unsigned char* data, size_t dataLength) { return RangeBtMessage::create(data, dataLength); } void BtRequestMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } - if(getPieceStorage()->hasPiece(getIndex()) && - (!getPeer()->amChoking() || - (getPeer()->amChoking() && - getPeer()->isInAmAllowedIndexSet(getIndex())))) { - getBtMessageDispatcher()->addMessageToQueue - (getBtMessageFactory()->createPieceMessage - (getIndex(), getBegin(), getLength())); - } else { - if(getPeer()->isFastExtensionEnabled()) { - getBtMessageDispatcher()->addMessageToQueue - (getBtMessageFactory()->createRejectMessage - (getIndex(), getBegin(), getLength())); + if (getPieceStorage()->hasPiece(getIndex()) && + (!getPeer()->amChoking() || + (getPeer()->amChoking() && + getPeer()->isInAmAllowedIndexSet(getIndex())))) { + getBtMessageDispatcher()->addMessageToQueue( + getBtMessageFactory()->createPieceMessage(getIndex(), getBegin(), + getLength())); + } + else { + if (getPeer()->isFastExtensionEnabled()) { + getBtMessageDispatcher()->addMessageToQueue( + getBtMessageFactory()->createRejectMessage(getIndex(), getBegin(), + getLength())); } } } void BtRequestMessage::onQueued() { - getBtMessageDispatcher()->addOutstandingRequest - (make_unique(getIndex(), getBegin(), getLength(), blockIndex_, - getPieceStorage()->getPiece(getIndex()))); + getBtMessageDispatcher()->addOutstandingRequest( + make_unique(getIndex(), getBegin(), getLength(), blockIndex_, + getPieceStorage()->getPiece(getIndex()))); } -void BtRequestMessage::onAbortOutstandingRequestEvent -(const BtAbortOutstandingRequestEvent& event) +void BtRequestMessage::onAbortOutstandingRequestEvent( + const BtAbortOutstandingRequestEvent& event) { - if(getIndex() == event.getPiece()->getIndex() && !isInvalidate()) { + if (getIndex() == event.getPiece()->getIndex() && !isInvalidate()) { setInvalidate(true); } } diff --git a/src/BtRequestMessage.h b/src/BtRequestMessage.h index 180ff274..17664bcd 100644 --- a/src/BtRequestMessage.h +++ b/src/BtRequestMessage.h @@ -42,10 +42,9 @@ namespace aria2 { class BtRequestMessage : public RangeBtMessage { private: size_t blockIndex_; + public: - BtRequestMessage(size_t index = 0, - int32_t begin = 0, - int32_t length = 0, + BtRequestMessage(size_t index = 0, int32_t begin = 0, int32_t length = 0, size_t blockIndex = 0); static const uint8_t ID = 6; @@ -55,15 +54,15 @@ public: size_t getBlockIndex() const { return blockIndex_; } void setBlockIndex(size_t blockIndex) { blockIndex_ = blockIndex; } - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; virtual void onQueued() CXX11_OVERRIDE; - virtual void onAbortOutstandingRequestEvent - (const BtAbortOutstandingRequestEvent& event) CXX11_OVERRIDE; + virtual void onAbortOutstandingRequestEvent( + const BtAbortOutstandingRequestEvent& event) CXX11_OVERRIDE; }; } // namespace aria2 diff --git a/src/BtRuntime.cc b/src/BtRuntime.cc index 6007789c..1031151a 100644 --- a/src/BtRuntime.cc +++ b/src/BtRuntime.cc @@ -38,21 +38,22 @@ namespace aria2 { BtRuntime::BtRuntime() - : uploadLengthAtStartup_(0), - halt_(false), - connections_(0), - ready_(false), - maxPeers_(DEFAULT_MAX_PEERS), - minPeers_(DEFAULT_MIN_PEERS) -{} + : uploadLengthAtStartup_(0), + halt_(false), + connections_(0), + ready_(false), + maxPeers_(DEFAULT_MAX_PEERS), + minPeers_(DEFAULT_MIN_PEERS) +{ +} BtRuntime::~BtRuntime() {} void BtRuntime::setMaxPeers(int maxPeers) { maxPeers_ = maxPeers; - minPeers_ = maxPeers*0.8; - if(minPeers_ == 0 && maxPeers != 0) { + minPeers_ = maxPeers * 0.8; + if (minPeers_ == 0 && maxPeers != 0) { minPeers_ = maxPeers; } } diff --git a/src/BtRuntime.h b/src/BtRuntime.h index 2403e765..edf93d6a 100644 --- a/src/BtRuntime.h +++ b/src/BtRuntime.h @@ -51,24 +51,22 @@ private: // Minimum number of peers. This value is used for getting more peers from // tracker. 0 means always the number of peers is under minimum. int minPeers_; + public: BtRuntime(); ~BtRuntime(); - int64_t getUploadLengthAtStartup() const { - return uploadLengthAtStartup_; - } + int64_t getUploadLengthAtStartup() const { return uploadLengthAtStartup_; } - void setUploadLengthAtStartup(int64_t length) { + void setUploadLengthAtStartup(int64_t length) + { uploadLengthAtStartup_ = length; } bool isHalt() const { return halt_; } - void setHalt(bool halt) { - halt_ = halt; - } + void setHalt(bool halt) { halt_ = halt; } int getConnections() const { return connections_; } @@ -97,10 +95,7 @@ public: void setMaxPeers(int maxPeers); - int getMaxPeers() const - { - return maxPeers_; - } + int getMaxPeers() const { return maxPeers_; } static const int DEFAULT_MAX_PEERS = 55; static const int DEFAULT_MIN_PEERS = 40; diff --git a/src/BtSeederStateChoke.cc b/src/BtSeederStateChoke.cc index c192f896..5662b6ac 100644 --- a/src/BtSeederStateChoke.cc +++ b/src/BtSeederStateChoke.cc @@ -45,10 +45,9 @@ namespace aria2 { -BtSeederStateChoke::BtSeederStateChoke() - : round_(0), - lastRound_(Timer::zero()) -{} +BtSeederStateChoke::BtSeederStateChoke() : round_(0), lastRound_(Timer::zero()) +{ +} BtSeederStateChoke::~BtSeederStateChoke() {} @@ -56,22 +55,24 @@ namespace { constexpr auto TIME_FRAME = 20_s; } // namespace -BtSeederStateChoke::PeerEntry::PeerEntry -(const std::shared_ptr& peer): - peer_(peer), - outstandingUpload_(peer->countOutstandingUpload()), - lastAmUnchoking_(peer->getLastAmUnchoking()), - recentUnchoking_(lastAmUnchoking_.difference(global::wallclock()) < TIME_FRAME), - uploadSpeed_(peer->calculateUploadSpeed()) -{} +BtSeederStateChoke::PeerEntry::PeerEntry(const std::shared_ptr& peer) + : peer_(peer), + outstandingUpload_(peer->countOutstandingUpload()), + lastAmUnchoking_(peer->getLastAmUnchoking()), + recentUnchoking_(lastAmUnchoking_.difference(global::wallclock()) < + TIME_FRAME), + uploadSpeed_(peer->calculateUploadSpeed()) +{ +} BtSeederStateChoke::PeerEntry::PeerEntry(const PeerEntry& c) - : peer_(c.peer_), - outstandingUpload_(c.outstandingUpload_), - lastAmUnchoking_(c.lastAmUnchoking_), - recentUnchoking_(c.recentUnchoking_), - uploadSpeed_(c.uploadSpeed_) -{} + : peer_(c.peer_), + outstandingUpload_(c.outstandingUpload_), + lastAmUnchoking_(c.lastAmUnchoking_), + recentUnchoking_(c.recentUnchoking_), + uploadSpeed_(c.uploadSpeed_) +{ +} BtSeederStateChoke::PeerEntry::~PeerEntry() {} @@ -85,10 +86,10 @@ void BtSeederStateChoke::PeerEntry::swap(PeerEntry& c) swap(uploadSpeed_, c.uploadSpeed_); } -BtSeederStateChoke::PeerEntry& BtSeederStateChoke::PeerEntry::operator= -(const PeerEntry& c) +BtSeederStateChoke::PeerEntry& BtSeederStateChoke::PeerEntry:: +operator=(const PeerEntry& c) { - if(this != &c) { + if (this != &c) { peer_ = c.peer_; outstandingUpload_ = c.outstandingUpload_; lastAmUnchoking_ = c.lastAmUnchoking_; @@ -98,20 +99,22 @@ BtSeederStateChoke::PeerEntry& BtSeederStateChoke::PeerEntry::operator= return *this; } -bool -BtSeederStateChoke::PeerEntry::operator<(const PeerEntry& rhs) const +bool BtSeederStateChoke::PeerEntry::operator<(const PeerEntry& rhs) const { - if(this->outstandingUpload_ && !rhs.outstandingUpload_) { + if (this->outstandingUpload_ && !rhs.outstandingUpload_) { return true; - } else if(!this->outstandingUpload_ && rhs.outstandingUpload_) { + } + else if (!this->outstandingUpload_ && rhs.outstandingUpload_) { return false; } - if(this->recentUnchoking_ && - (this->lastAmUnchoking_ > rhs.lastAmUnchoking_)) { + if (this->recentUnchoking_ && + (this->lastAmUnchoking_ > rhs.lastAmUnchoking_)) { return true; - } else if(rhs.recentUnchoking_) { + } + else if (rhs.recentUnchoking_) { return false; - } else { + } + else { return this->uploadSpeed_ > rhs.uploadSpeed_; } } @@ -121,25 +124,24 @@ void BtSeederStateChoke::PeerEntry::disableOptUnchoking() peer_->optUnchoking(false); } -void BtSeederStateChoke::unchoke -(std::vector& peers) +void BtSeederStateChoke::unchoke( + std::vector& peers) { int count = (round_ == 2) ? 4 : 3; std::sort(std::begin(peers), std::end(peers)); auto r = std::begin(peers); - for(; r != std::end(peers) && count; ++r, --count) { + for (; r != std::end(peers) && count; ++r, --count) { (*r).getPeer()->chokingRequired(false); - A2_LOG_INFO(fmt("RU: %s, ulspd=%d", - (*r).getPeer()->getIPAddress().c_str(), + A2_LOG_INFO(fmt("RU: %s, ulspd=%d", (*r).getPeer()->getIPAddress().c_str(), (*r).getUploadSpeed())); } - if(round_ < 2) { + if (round_ < 2) { std::for_each(std::begin(peers), std::end(peers), std::mem_fn(&PeerEntry::disableOptUnchoking)); - if(r != std::end(peers)) { + if (r != std::end(peers)) { std::shuffle(r, std::end(peers), *SimpleRandomizer::getInstance()); (*r).getPeer()->optUnchoking(true); A2_LOG_INFO(fmt("POU: %s", (*r).getPeer()->getIPAddress().c_str())); @@ -153,8 +155,8 @@ void BtSeederStateChoke::executeChoke(const PeerSet& peerSet) lastRound_ = global::wallclock(); std::vector peerEntries; - for(const auto& p : peerSet) { - if(p->isActive() && p->peerInterested()) { + for (const auto& p : peerSet) { + if (p->isActive() && p->peerInterested()) { p->chokingRequired(true); peerEntries.push_back(PeerEntry(p)); } @@ -162,14 +164,12 @@ void BtSeederStateChoke::executeChoke(const PeerSet& peerSet) unchoke(peerEntries); - if(++round_ == 3) { + if (++round_ == 3) { round_ = 0; } } -void swap -(BtSeederStateChoke::PeerEntry& a, - BtSeederStateChoke::PeerEntry& b) +void swap(BtSeederStateChoke::PeerEntry& a, BtSeederStateChoke::PeerEntry& b) { a.swap(b); } diff --git a/src/BtSeederStateChoke.h b/src/BtSeederStateChoke.h index d333b7c6..cc560158 100644 --- a/src/BtSeederStateChoke.h +++ b/src/BtSeederStateChoke.h @@ -80,6 +80,7 @@ private: }; void unchoke(std::vector& peers); + public: BtSeederStateChoke(); @@ -92,9 +93,7 @@ public: friend void swap(PeerEntry& a, PeerEntry& b); }; -void swap -(BtSeederStateChoke::PeerEntry& a, - BtSeederStateChoke::PeerEntry& b); +void swap(BtSeederStateChoke::PeerEntry& a, BtSeederStateChoke::PeerEntry& b); } // namespace aria2 diff --git a/src/BtSetup.cc b/src/BtSetup.cc index 4cf4a6b5..814780c1 100644 --- a/src/BtSetup.cc +++ b/src/BtSetup.cc @@ -91,15 +91,14 @@ namespace aria2 { BtSetup::BtSetup() {} void BtSetup::setup(std::vector>& commands, - RequestGroup* requestGroup, - DownloadEngine* e, + RequestGroup* requestGroup, DownloadEngine* e, const Option* option) { - if(!requestGroup->getDownloadContext()->hasAttribute(CTX_ATTR_BT)){ + if (!requestGroup->getDownloadContext()->hasAttribute(CTX_ATTR_BT)) { return; } auto torrentAttrs = - bittorrent::getTorrentAttrs(requestGroup->getDownloadContext()); + bittorrent::getTorrentAttrs(requestGroup->getDownloadContext()); bool metadataGetMode = torrentAttrs->metadata.empty(); auto& btReg = e->getBtRegistry(); auto btObject = btReg->get(requestGroup->getGID()); @@ -117,7 +116,7 @@ void BtSetup::setup(std::vector>& commands, commands.push_back(std::move(c)); } - if(!metadataGetMode) { + if (!metadataGetMode) { auto c = make_unique(e->newCUID(), e); c->setPeerStorage(peerStorage); c->setBtRuntime(btRuntime); @@ -135,19 +134,19 @@ void BtSetup::setup(std::vector>& commands, commands.push_back(std::move(c)); } - if(metadataGetMode || !torrentAttrs->privateTorrent) { - if(DHTRegistry::isInitialized()) { - auto command = make_unique - (e->newCUID(), requestGroup, e); + if (metadataGetMode || !torrentAttrs->privateTorrent) { + if (DHTRegistry::isInitialized()) { + auto command = + make_unique(e->newCUID(), requestGroup, e); command->setTaskQueue(DHTRegistry::getData().taskQueue.get()); command->setTaskFactory(DHTRegistry::getData().taskFactory.get()); command->setBtRuntime(btRuntime); command->setPeerStorage(peerStorage); commands.push_back(std::move(command)); } - if(DHTRegistry::isInitialized6()) { - auto command = make_unique - (e->newCUID(), requestGroup, e); + if (DHTRegistry::isInitialized6()) { + auto command = + make_unique(e->newCUID(), requestGroup, e); command->setTaskQueue(DHTRegistry::getData6().taskQueue.get()); command->setTaskFactory(DHTRegistry::getData6().taskFactory.get()); command->setBtRuntime(btRuntime); @@ -155,126 +154,129 @@ void BtSetup::setup(std::vector>& commands, commands.push_back(std::move(command)); } } - if(!metadataGetMode) { + if (!metadataGetMode) { auto unionCri = make_unique(); - if(option->defined(PREF_SEED_TIME)) { + if (option->defined(PREF_SEED_TIME)) { unionCri->addSeedCriteria(make_unique( std::chrono::seconds(option->getAsInt(PREF_SEED_TIME) * 60))); } { double ratio = option->getAsDouble(PREF_SEED_RATIO); - if(ratio > 0.0) { - auto cri = make_unique - (option->getAsDouble(PREF_SEED_RATIO), - requestGroup->getDownloadContext()); + if (ratio > 0.0) { + auto cri = make_unique( + option->getAsDouble(PREF_SEED_RATIO), + requestGroup->getDownloadContext()); cri->setPieceStorage(pieceStorage); cri->setBtRuntime(btRuntime); unionCri->addSeedCriteria(std::move(cri)); } } - if(!unionCri->getSeedCriterion().empty()) { - auto c = make_unique - (e->newCUID(), requestGroup, e, std::move(unionCri)); + if (!unionCri->getSeedCriterion().empty()) { + auto c = make_unique(e->newCUID(), requestGroup, e, + std::move(unionCri)); c->setPieceStorage(pieceStorage); c->setBtRuntime(btRuntime); commands.push_back(std::move(c)); } } - if(btReg->getTcpPort() == 0) { - static int families[] = { AF_INET, AF_INET6 }; - size_t familiesLength = e->getOption()->getAsBool(PREF_DISABLE_IPV6)?1:2; - for(size_t i = 0; i < familiesLength; ++i) { - auto command = make_unique - (e->newCUID(), e, families[i]); + if (btReg->getTcpPort() == 0) { + static int families[] = {AF_INET, AF_INET6}; + size_t familiesLength = + e->getOption()->getAsBool(PREF_DISABLE_IPV6) ? 1 : 2; + for (size_t i = 0; i < familiesLength; ++i) { + auto command = + make_unique(e->newCUID(), e, families[i]); bool ret; uint16_t port; - if(btReg->getTcpPort()) { + if (btReg->getTcpPort()) { SegList sgl; int usedPort = btReg->getTcpPort(); - sgl.add(usedPort, usedPort+1); + sgl.add(usedPort, usedPort + 1); ret = command->bindPort(port, sgl); - } else { - auto sgl = util::parseIntSegments - (e->getOption()->get(PREF_LISTEN_PORT)); + } + else { + auto sgl = + util::parseIntSegments(e->getOption()->get(PREF_LISTEN_PORT)); sgl.normalize(); ret = command->bindPort(port, sgl); } - if(ret) { + if (ret) { btReg->setTcpPort(port); // Add command to DownloadEngine directly. e->addCommand(std::move(command)); } } - if(btReg->getTcpPort() == 0) { + if (btReg->getTcpPort() == 0) { throw DL_ABORT_EX(_("Errors occurred while binding port.\n")); } } btAnnounce->setTcpPort(btReg->getTcpPort()); - if(option->getAsBool(PREF_BT_ENABLE_LPD) && - btReg->getTcpPort() && - (metadataGetMode || !torrentAttrs->privateTorrent)) { - if(!btReg->getLpdMessageReceiver()) { + if (option->getAsBool(PREF_BT_ENABLE_LPD) && btReg->getTcpPort() && + (metadataGetMode || !torrentAttrs->privateTorrent)) { + if (!btReg->getLpdMessageReceiver()) { A2_LOG_INFO("Initializing LpdMessageReceiver."); - auto receiver = std::make_shared - (LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT); + auto receiver = std::make_shared(LPD_MULTICAST_ADDR, + LPD_MULTICAST_PORT); bool initialized = false; const std::string& lpdInterface = - e->getOption()->get(PREF_BT_LPD_INTERFACE); - if(lpdInterface.empty()) { - if(receiver->init("")) { + e->getOption()->get(PREF_BT_LPD_INTERFACE); + if (lpdInterface.empty()) { + if (receiver->init("")) { initialized = true; } - } else { - std::vector > ifAddrs; + } + else { + std::vector> ifAddrs; getInterfaceAddress(ifAddrs, lpdInterface, AF_INET, AI_NUMERICHOST); for (const auto& i : ifAddrs) { char host[NI_MAXHOST]; - if(inetNtop(AF_INET, &i.first.in.sin_addr, host, - sizeof(host)) == 0 && - receiver->init(host)) { + if (inetNtop(AF_INET, &i.first.in.sin_addr, host, sizeof(host)) == + 0 && + receiver->init(host)) { initialized = true; break; } } } - if(initialized) { + if (initialized) { btReg->setLpdMessageReceiver(receiver); A2_LOG_INFO(fmt("LpdMessageReceiver initialized. multicastAddr=%s:%u," " localAddr=%s", LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT, receiver->getLocalAddress().c_str())); - e->addCommand(make_unique - (e->newCUID(), receiver, e)); - } else { + e->addCommand( + make_unique(e->newCUID(), receiver, e)); + } + else { A2_LOG_INFO("LpdMessageReceiver not initialized."); } } - if(btReg->getLpdMessageReceiver()) { + if (btReg->getLpdMessageReceiver()) { const unsigned char* infoHash = - bittorrent::getInfoHash(requestGroup->getDownloadContext()); + bittorrent::getInfoHash(requestGroup->getDownloadContext()); A2_LOG_INFO("Initializing LpdMessageDispatcher."); - auto dispatcher = std::make_shared - (std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]), - btReg->getTcpPort(), - LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT); - if(dispatcher->init(btReg->getLpdMessageReceiver()->getLocalAddress(), - /*ttl*/1, /*loop*/1)) { + auto dispatcher = std::make_shared( + std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]), + btReg->getTcpPort(), LPD_MULTICAST_ADDR, LPD_MULTICAST_PORT); + if (dispatcher->init(btReg->getLpdMessageReceiver()->getLocalAddress(), + /*ttl*/ 1, /*loop*/ 1)) { A2_LOG_INFO("LpdMessageDispatcher initialized."); - auto cmd = make_unique - (e->newCUID(), dispatcher, e); + auto cmd = + make_unique(e->newCUID(), dispatcher, e); cmd->setBtRuntime(btRuntime); e->addCommand(std::move(cmd)); - } else { + } + else { A2_LOG_INFO("LpdMessageDispatcher not initialized."); } } } auto btStopTimeout = option->getAsInt(PREF_BT_STOP_TIMEOUT); - if(btStopTimeout > 0) { - auto stopDownloadCommand = make_unique - (e->newCUID(), requestGroup, e, std::chrono::seconds(btStopTimeout)); + if (btStopTimeout > 0) { + auto stopDownloadCommand = make_unique( + e->newCUID(), requestGroup, e, std::chrono::seconds(btStopTimeout)); stopDownloadCommand->setBtRuntime(btRuntime); stopDownloadCommand->setPieceStorage(pieceStorage); commands.push_back(std::move(stopDownloadCommand)); diff --git a/src/BtSetup.h b/src/BtSetup.h index 865545ce..be6833a0 100644 --- a/src/BtSetup.h +++ b/src/BtSetup.h @@ -52,8 +52,7 @@ public: BtSetup(); void setup(std::vector>& commands, - RequestGroup* requestGroup, - DownloadEngine* e, + RequestGroup* requestGroup, DownloadEngine* e, const Option* option); }; diff --git a/src/BtStopDownloadCommand.cc b/src/BtStopDownloadCommand.cc index 74b3b89d..fb009f26 100644 --- a/src/BtStopDownloadCommand.cc +++ b/src/BtStopDownloadCommand.cc @@ -46,22 +46,22 @@ namespace aria2 { -BtStopDownloadCommand::BtStopDownloadCommand -(cuid_t cuid, - RequestGroup* requestGroup, - DownloadEngine* e, - std::chrono::seconds timeout) - : TimeBasedCommand(cuid, e, 1_s), - requestGroup_(requestGroup), - timeout_(std::move(timeout)) -{} +BtStopDownloadCommand::BtStopDownloadCommand(cuid_t cuid, + RequestGroup* requestGroup, + DownloadEngine* e, + std::chrono::seconds timeout) + : TimeBasedCommand(cuid, e, 1_s), + requestGroup_(requestGroup), + timeout_(std::move(timeout)) +{ +} void BtStopDownloadCommand::preProcess() { - if(btRuntime_->isHalt() || pieceStorage_->downloadFinished()) { + if (btRuntime_->isHalt() || pieceStorage_->downloadFinished()) { enableExit(); } - if(checkPoint_.difference(global::wallclock()) >= timeout_) { + if (checkPoint_.difference(global::wallclock()) >= timeout_) { A2_LOG_NOTICE(fmt(_("GID#%s Stop downloading torrent due to" " --bt-stop-timeout option."), GroupId::toHex(requestGroup_->getGID()).c_str())); @@ -74,7 +74,7 @@ void BtStopDownloadCommand::preProcess() void BtStopDownloadCommand::process() { NetStat& stat = requestGroup_->getDownloadContext()->getNetStat(); - if(stat.calculateDownloadSpeed() > 0) { + if (stat.calculateDownloadSpeed() > 0) { checkPoint_ = global::wallclock(); } } diff --git a/src/BtStopDownloadCommand.h b/src/BtStopDownloadCommand.h index ae592a92..70d0fcc4 100644 --- a/src/BtStopDownloadCommand.h +++ b/src/BtStopDownloadCommand.h @@ -47,7 +47,7 @@ class BtRuntime; // Stop downloading torrent if in consecutive timeout_ seconds, // download speed is zero and the number of seeder is 0. -class BtStopDownloadCommand:public TimeBasedCommand { +class BtStopDownloadCommand : public TimeBasedCommand { private: RequestGroup* requestGroup_; @@ -58,12 +58,10 @@ private: std::shared_ptr btRuntime_; std::shared_ptr pieceStorage_; + public: - BtStopDownloadCommand - (cuid_t cuid, - RequestGroup* requestGroup, - DownloadEngine* e, - std::chrono::seconds timeout); + BtStopDownloadCommand(cuid_t cuid, RequestGroup* requestGroup, + DownloadEngine* e, std::chrono::seconds timeout); virtual void preProcess() CXX11_OVERRIDE; diff --git a/src/BtSuggestPieceMessage.cc b/src/BtSuggestPieceMessage.cc index a12b7be7..ef58cd53 100644 --- a/src/BtSuggestPieceMessage.cc +++ b/src/BtSuggestPieceMessage.cc @@ -37,13 +37,14 @@ namespace aria2 { BtSuggestPieceMessage::BtSuggestPieceMessage(size_t index) - : IndexBtMessage{ID, NAME, index} -{} + : IndexBtMessage{ID, NAME, index} +{ +} const char BtSuggestPieceMessage::NAME[] = "suggest piece"; -std::unique_ptr BtSuggestPieceMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtSuggestPieceMessage::create(const unsigned char* data, size_t dataLength) { return IndexBtMessage::create(data, dataLength); } diff --git a/src/BtSuggestPieceMessage.h b/src/BtSuggestPieceMessage.h index 61df93cd..40cc92bf 100644 --- a/src/BtSuggestPieceMessage.h +++ b/src/BtSuggestPieceMessage.h @@ -47,10 +47,11 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr + create(const unsigned char* data, size_t dataLength); - virtual void doReceivedAction() CXX11_OVERRIDE { + virtual void doReceivedAction() CXX11_OVERRIDE + { // TODO Current implementation ignores this message. } }; diff --git a/src/BtUnchokeMessage.cc b/src/BtUnchokeMessage.cc index e76d053c..cc9e203a 100644 --- a/src/BtUnchokeMessage.cc +++ b/src/BtUnchokeMessage.cc @@ -40,34 +40,30 @@ namespace aria2 { const char BtUnchokeMessage::NAME[] = "unchoke"; -BtUnchokeMessage::BtUnchokeMessage():ZeroBtMessage(ID, NAME) {} +BtUnchokeMessage::BtUnchokeMessage() : ZeroBtMessage(ID, NAME) {} -std::unique_ptr BtUnchokeMessage::create -(const unsigned char* data, size_t dataLength) +std::unique_ptr +BtUnchokeMessage::create(const unsigned char* data, size_t dataLength) { return ZeroBtMessage::create(data, dataLength); } void BtUnchokeMessage::doReceivedAction() { - if(isMetadataGetMode()) { + if (isMetadataGetMode()) { return; } getPeer()->peerChoking(false); } -bool BtUnchokeMessage::sendPredicate() const -{ - return getPeer()->amChoking(); -} +bool BtUnchokeMessage::sendPredicate() const { return getPeer()->amChoking(); } namespace { struct ThisProgressUpdate : public ProgressUpdate { - ThisProgressUpdate(std::shared_ptr peer) - : peer(std::move(peer)) {} + ThisProgressUpdate(std::shared_ptr peer) : peer(std::move(peer)) {} virtual void update(size_t length, bool complete) CXX11_OVERRIDE { - if(complete) { + if (complete) { peer->amChoking(false); } } diff --git a/src/BtUnchokeMessage.h b/src/BtUnchokeMessage.h index 5435911e..bd9e6109 100644 --- a/src/BtUnchokeMessage.h +++ b/src/BtUnchokeMessage.h @@ -42,6 +42,7 @@ namespace aria2 { class BtUnchokeMessage : public ZeroBtMessage { private: static const size_t MESSAGE_LENGTH = 5; + public: BtUnchokeMessage(); @@ -49,8 +50,8 @@ public: static const char NAME[]; - static std::unique_ptr create - (const unsigned char* data, size_t dataLength); + static std::unique_ptr create(const unsigned char* data, + size_t dataLength); virtual void doReceivedAction() CXX11_OVERRIDE; diff --git a/src/BufferedFile.cc b/src/BufferedFile.cc index ee35006a..3618f439 100644 --- a/src/BufferedFile.cc +++ b/src/BufferedFile.cc @@ -44,26 +44,26 @@ namespace aria2 { BufferedFile::BufferedFile(const char* filename, const char* mode) - : + : #ifdef __MINGW32__ - fp_(strcmp(DEV_STDIN, filename) == 0 ? - stdin : a2fopen(utf8ToWChar(filename).c_str(), - utf8ToWChar(mode).c_str())), -#else // !__MINGW32__ - fp_(a2fopen(filename, mode)), + fp_(strcmp(DEV_STDIN, filename) == 0 + ? stdin + : a2fopen(utf8ToWChar(filename).c_str(), + utf8ToWChar(mode).c_str())), +#else // !__MINGW32__ + fp_(a2fopen(filename, mode)), #endif // !__MINGW32__ - supportsColor_(fp_ ? isatty(fileno(fp_)) : false) -{} + supportsColor_(fp_ ? isatty(fileno(fp_)) : false) +{ +} BufferedFile::BufferedFile(FILE* fp) - : fp_(fp), supportsColor_(fp_ ? isatty(fileno(fp_)) : false) -{} - -BufferedFile::~BufferedFile() + : fp_(fp), supportsColor_(fp_ ? isatty(fileno(fp_)) : false) { - close(); } +BufferedFile::~BufferedFile() { close(); } + size_t BufferedFile::onRead(void* ptr, size_t count) { return fread(ptr, 1, count, fp_); @@ -74,10 +74,7 @@ size_t BufferedFile::onWrite(const void* ptr, size_t count) return fwrite(ptr, 1, count, fp_); } -char* BufferedFile::onGets(char* s, int size) -{ - return fgets(s, size, fp_); -} +char* BufferedFile::onGets(char* s, int size) { return fgets(s, size, fp_); } int BufferedFile::onClose() { @@ -94,29 +91,14 @@ int BufferedFile::onVprintf(const char* format, va_list va) return vfprintf(fp_, format, va); } -int BufferedFile::onFlush() -{ - return fflush(fp_); -} +int BufferedFile::onFlush() { return fflush(fp_); } -bool BufferedFile::onSupportsColor() -{ - return supportsColor_; -} +bool BufferedFile::onSupportsColor() { return supportsColor_; } -bool BufferedFile::isError() const -{ - return ferror(fp_); -} +bool BufferedFile::isError() const { return ferror(fp_); } -bool BufferedFile::isEOF() const -{ - return feof(fp_); -} +bool BufferedFile::isEOF() const { return feof(fp_); } -bool BufferedFile::isOpen() const -{ - return fp_; -} +bool BufferedFile::isOpen() const { return fp_; } } // namespace aria2 diff --git a/src/BufferedFile.h b/src/BufferedFile.h index 10966b2e..03a57ac6 100644 --- a/src/BufferedFile.h +++ b/src/BufferedFile.h @@ -42,11 +42,12 @@ namespace aria2 { // IOFILE implementation using standard I/O functions. -class BufferedFile:public IOFile { +class BufferedFile : public IOFile { public: BufferedFile(const char* filename, const char* mode); BufferedFile(FILE* fp); virtual ~BufferedFile(); + protected: // wrapper for fread. Using 1 for 2nd argument of fread. virtual size_t onRead(void* ptr, size_t count) CXX11_OVERRIDE; @@ -63,6 +64,7 @@ protected: virtual bool isError() const CXX11_OVERRIDE; virtual bool isEOF() const CXX11_OVERRIDE; virtual bool isOpen() const CXX11_OVERRIDE; + private: // Don't allow copying; BufferedFile(const BufferedFile&); diff --git a/src/ByteArrayDiskWriter.cc b/src/ByteArrayDiskWriter.cc index 8f638dff..0ad91ac6 100644 --- a/src/ByteArrayDiskWriter.cc +++ b/src/ByteArrayDiskWriter.cc @@ -40,44 +40,37 @@ namespace aria2 { ByteArrayDiskWriter::ByteArrayDiskWriter(size_t maxLength) - : maxLength_(maxLength) -{} + : maxLength_(maxLength) +{ +} ByteArrayDiskWriter::~ByteArrayDiskWriter() {} -void ByteArrayDiskWriter::clear() -{ - buf_.str(A2STR::NIL); -} +void ByteArrayDiskWriter::clear() { buf_.str(A2STR::NIL); } -void ByteArrayDiskWriter::initAndOpenFile(int64_t totalLength) -{ - clear(); -} +void ByteArrayDiskWriter::initAndOpenFile(int64_t totalLength) { clear(); } void ByteArrayDiskWriter::openFile(int64_t totalLength) {} void ByteArrayDiskWriter::closeFile() {} -void ByteArrayDiskWriter::openExistingFile(int64_t totalLength) -{ - openFile(); -} +void ByteArrayDiskWriter::openExistingFile(int64_t totalLength) { openFile(); } void ByteArrayDiskWriter::writeData(const unsigned char* data, size_t dataLength, int64_t offset) { - if(offset+dataLength > maxLength_) { + if (offset + dataLength > maxLength_) { throw DL_ABORT_EX(fmt("Maximum length(%lu) exceeded.", static_cast(maxLength_))); } int64_t length = size(); - if(length < offset) { + if (length < offset) { buf_.seekp(length, std::ios::beg); - for(int64_t i = length; i < offset; ++i) { + for (int64_t i = length; i < offset; ++i) { buf_.put('\0'); } - } else { + } + else { buf_.seekp(offset, std::ios::beg); } buf_.write(reinterpret_cast(data), dataLength); @@ -99,14 +92,8 @@ int64_t ByteArrayDiskWriter::size() return buf_.tellg(); } -void ByteArrayDiskWriter::setString(const std::string& s) -{ - buf_.str(s); -} +void ByteArrayDiskWriter::setString(const std::string& s) { buf_.str(s); } -std::string ByteArrayDiskWriter::getString() const -{ - return buf_.str(); -} +std::string ByteArrayDiskWriter::getString() const { return buf_.str(); } } // namespace aria2 diff --git a/src/ByteArrayDiskWriter.h b/src/ByteArrayDiskWriter.h index b5ca7140..a52cb8c8 100644 --- a/src/ByteArrayDiskWriter.h +++ b/src/ByteArrayDiskWriter.h @@ -47,6 +47,7 @@ private: std::stringstream buf_; size_t maxLength_; void clear(); + public: ByteArrayDiskWriter(size_t maxLength = 5_m); virtual ~ByteArrayDiskWriter(); @@ -59,10 +60,10 @@ public: virtual void openExistingFile(int64_t totalLength = 0) CXX11_OVERRIDE; - virtual void writeData(const unsigned char* data, size_t len, int64_t offset) - CXX11_OVERRIDE; - virtual ssize_t readData(unsigned char* data, size_t len, int64_t offset) - CXX11_OVERRIDE; + virtual void writeData(const unsigned char* data, size_t len, + int64_t offset) CXX11_OVERRIDE; + virtual ssize_t readData(unsigned char* data, size_t len, + int64_t offset) CXX11_OVERRIDE; virtual int64_t size() CXX11_OVERRIDE; diff --git a/src/ByteArrayDiskWriterFactory.h b/src/ByteArrayDiskWriterFactory.h index 63860dd7..3c801ee8 100644 --- a/src/ByteArrayDiskWriterFactory.h +++ b/src/ByteArrayDiskWriterFactory.h @@ -40,8 +40,7 @@ namespace aria2 { -typedef AnonDiskWriterFactory -ByteArrayDiskWriterFactory; +typedef AnonDiskWriterFactory ByteArrayDiskWriterFactory; } // namespace aria2 diff --git a/src/CUIDCounter.cc b/src/CUIDCounter.cc index 3ae6b88d..5fbba205 100644 --- a/src/CUIDCounter.cc +++ b/src/CUIDCounter.cc @@ -36,13 +36,13 @@ namespace aria2 { -CUIDCounter::CUIDCounter():count_(0) {} +CUIDCounter::CUIDCounter() : count_(0) {} CUIDCounter::~CUIDCounter() {} cuid_t CUIDCounter::newID() { - if(count_ == INT64_MAX) { + if (count_ == INT64_MAX) { count_ = 0; } return ++count_; diff --git a/src/CUIDCounter.h b/src/CUIDCounter.h index eb118f64..088ad560 100644 --- a/src/CUIDCounter.h +++ b/src/CUIDCounter.h @@ -43,6 +43,7 @@ namespace aria2 { class CUIDCounter { private: cuid_t count_; + public: CUIDCounter(); ~CUIDCounter(); diff --git a/src/CheckIntegrityCommand.cc b/src/CheckIntegrityCommand.cc index 4e0557fb..c6c401d5 100644 --- a/src/CheckIntegrityCommand.cc +++ b/src/CheckIntegrityCommand.cc @@ -48,12 +48,13 @@ namespace aria2 { -CheckIntegrityCommand::CheckIntegrityCommand -(cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, - CheckIntegrityEntry* entry) - : RealtimeCommand{cuid, requestGroup, e}, - entry_{entry} -{} +CheckIntegrityCommand::CheckIntegrityCommand(cuid_t cuid, + RequestGroup* requestGroup, + DownloadEngine* e, + CheckIntegrityEntry* entry) + : RealtimeCommand{cuid, requestGroup, e}, entry_{entry} +{ +} CheckIntegrityCommand::~CheckIntegrityCommand() { @@ -62,33 +63,35 @@ CheckIntegrityCommand::~CheckIntegrityCommand() bool CheckIntegrityCommand::executeInternal() { - if(getRequestGroup()->isHaltRequested()) { + if (getRequestGroup()->isHaltRequested()) { return true; } entry_->validateChunk(); - if(entry_->finished()) { + if (entry_->finished()) { // Enable control file saving here. See also // RequestGroup::processCheckIntegrityEntry() to know why this is // needed. getRequestGroup()->enableSaveControlFile(); - if(getRequestGroup()->downloadFinished()) { - A2_LOG_NOTICE - (fmt(MSG_VERIFICATION_SUCCESSFUL, - getRequestGroup()->getDownloadContext()->getBasePath().c_str())); + if (getRequestGroup()->downloadFinished()) { + A2_LOG_NOTICE( + fmt(MSG_VERIFICATION_SUCCESSFUL, + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); std::vector> commands; entry_->onDownloadFinished(commands, getDownloadEngine()); getDownloadEngine()->addCommand(std::move(commands)); - } else { - A2_LOG_ERROR - (fmt(MSG_VERIFICATION_FAILED, - getRequestGroup()->getDownloadContext()->getBasePath().c_str())); + } + else { + A2_LOG_ERROR( + fmt(MSG_VERIFICATION_FAILED, + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); std::vector> commands; entry_->onDownloadIncomplete(commands, getDownloadEngine()); getDownloadEngine()->addCommand(std::move(commands)); } getDownloadEngine()->setNoWait(true); return true; - } else { + } + else { getDownloadEngine()->addCommand(std::unique_ptr(this)); return false; } @@ -96,13 +99,10 @@ bool CheckIntegrityCommand::executeInternal() bool CheckIntegrityCommand::handleException(Exception& e) { - A2_LOG_ERROR_EX(fmt(MSG_FILE_VALIDATION_FAILURE, - getCuid()), - e); - A2_LOG_ERROR - (fmt(MSG_DOWNLOAD_NOT_COMPLETE, - getCuid(), - getRequestGroup()->getDownloadContext()->getBasePath().c_str())); + A2_LOG_ERROR_EX(fmt(MSG_FILE_VALIDATION_FAILURE, getCuid()), e); + A2_LOG_ERROR( + fmt(MSG_DOWNLOAD_NOT_COMPLETE, getCuid(), + getRequestGroup()->getDownloadContext()->getBasePath().c_str())); return true; } diff --git a/src/CheckIntegrityCommand.h b/src/CheckIntegrityCommand.h index 060548e5..19ff25f2 100644 --- a/src/CheckIntegrityCommand.h +++ b/src/CheckIntegrityCommand.h @@ -46,11 +46,10 @@ class CheckIntegrityEntry; class CheckIntegrityCommand : public RealtimeCommand { private: CheckIntegrityEntry* entry_; + public: - CheckIntegrityCommand(cuid_t cuid, - RequestGroup* requestGroup, - DownloadEngine* e, - CheckIntegrityEntry* entry); + CheckIntegrityCommand(cuid_t cuid, RequestGroup* requestGroup, + DownloadEngine* e, CheckIntegrityEntry* entry); virtual ~CheckIntegrityCommand(); diff --git a/src/CheckIntegrityDispatcherCommand.cc b/src/CheckIntegrityDispatcherCommand.cc index 9c512611..41609069 100644 --- a/src/CheckIntegrityDispatcherCommand.cc +++ b/src/CheckIntegrityDispatcherCommand.cc @@ -43,23 +43,22 @@ namespace aria2 { -CheckIntegrityDispatcherCommand::CheckIntegrityDispatcherCommand -(cuid_t cuid, - CheckIntegrityMan* fileAllocMan, - DownloadEngine* e) - : SequentialDispatcherCommand{cuid, fileAllocMan, e} +CheckIntegrityDispatcherCommand::CheckIntegrityDispatcherCommand( + cuid_t cuid, CheckIntegrityMan* fileAllocMan, DownloadEngine* e) + : SequentialDispatcherCommand{cuid, fileAllocMan, e} { setStatusRealtime(); } -std::unique_ptr CheckIntegrityDispatcherCommand::createCommand -(CheckIntegrityEntry* entry) +std::unique_ptr +CheckIntegrityDispatcherCommand::createCommand(CheckIntegrityEntry* entry) { cuid_t newCUID = getDownloadEngine()->newCUID(); A2_LOG_INFO(fmt("CUID#%" PRId64 " - Dispatching CheckIntegrityCommand " - "CUID#%" PRId64 ".", getCuid(), newCUID)); - return make_unique - (newCUID, entry->getRequestGroup(), getDownloadEngine(), entry); + "CUID#%" PRId64 ".", + getCuid(), newCUID)); + return make_unique(newCUID, entry->getRequestGroup(), + getDownloadEngine(), entry); } } // namespace aria2 diff --git a/src/CheckIntegrityDispatcherCommand.h b/src/CheckIntegrityDispatcherCommand.h index 92ef37d4..0d27bec6 100644 --- a/src/CheckIntegrityDispatcherCommand.h +++ b/src/CheckIntegrityDispatcherCommand.h @@ -42,16 +42,15 @@ namespace aria2 { class CheckIntegrityEntry; -class CheckIntegrityDispatcherCommand : - public SequentialDispatcherCommand { +class CheckIntegrityDispatcherCommand + : public SequentialDispatcherCommand { public: - CheckIntegrityDispatcherCommand - (cuid_t cuid, - CheckIntegrityMan* checkMan, - DownloadEngine* e); + CheckIntegrityDispatcherCommand(cuid_t cuid, CheckIntegrityMan* checkMan, + DownloadEngine* e); + protected: - virtual std::unique_ptr createCommand(CheckIntegrityEntry* entry) - CXX11_OVERRIDE; + virtual std::unique_ptr + createCommand(CheckIntegrityEntry* entry) CXX11_OVERRIDE; }; } // namespace aria2 diff --git a/src/CheckIntegrityEntry.cc b/src/CheckIntegrityEntry.cc index 3f23a7fa..9a634050 100644 --- a/src/CheckIntegrityEntry.cc +++ b/src/CheckIntegrityEntry.cc @@ -46,58 +46,55 @@ namespace aria2 { CheckIntegrityEntry::CheckIntegrityEntry(RequestGroup* requestGroup, std::unique_ptr nextCommand) - : RequestGroupEntry{requestGroup, std::move(nextCommand)} -{} + : RequestGroupEntry{requestGroup, std::move(nextCommand)} +{ +} CheckIntegrityEntry::~CheckIntegrityEntry() {} -void CheckIntegrityEntry::validateChunk() -{ - validator_->validateChunk(); -} +void CheckIntegrityEntry::validateChunk() { validator_->validateChunk(); } int64_t CheckIntegrityEntry::getTotalLength() { - if(!validator_) { + if (!validator_) { return 0; - } else { + } + else { return validator_->getTotalLength(); } } int64_t CheckIntegrityEntry::getCurrentLength() { - if(!validator_) { + if (!validator_) { return 0; - } else { + } + else { return validator_->getCurrentOffset(); } } -bool CheckIntegrityEntry::finished() -{ - return validator_->finished(); -} +bool CheckIntegrityEntry::finished() { return validator_->finished(); } void CheckIntegrityEntry::cutTrailingGarbage() { getRequestGroup()->getPieceStorage()->getDiskAdaptor()->cutTrailingGarbage(); } -void CheckIntegrityEntry::proceedFileAllocation -(std::vector>& commands, - std::unique_ptr entry, - DownloadEngine* e) +void CheckIntegrityEntry::proceedFileAllocation( + std::vector>& commands, + std::unique_ptr entry, DownloadEngine* e) { - if(getRequestGroup()->needsFileAllocation()) { + if (getRequestGroup()->needsFileAllocation()) { e->getFileAllocationMan()->pushEntry(std::move(entry)); - } else { + } + else { entry->prepareForNextAction(commands, e); } } -void CheckIntegrityEntry::setValidator -(std::unique_ptr validator) +void CheckIntegrityEntry::setValidator( + std::unique_ptr validator) { validator_ = std::move(validator); } diff --git a/src/CheckIntegrityEntry.h b/src/CheckIntegrityEntry.h index 4978cf47..99c28b2a 100644 --- a/src/CheckIntegrityEntry.h +++ b/src/CheckIntegrityEntry.h @@ -52,16 +52,18 @@ class CheckIntegrityEntry : public RequestGroupEntry, public ProgressAwareEntry { private: std::unique_ptr validator_; + protected: void setValidator(std::unique_ptr validator); void proceedFileAllocation(std::vector>& commands, std::unique_ptr entry, DownloadEngine* e); + public: - CheckIntegrityEntry(RequestGroup* requestGroup, - std::unique_ptr nextCommand = - std::unique_ptr()); + CheckIntegrityEntry( + RequestGroup* requestGroup, + std::unique_ptr nextCommand = std::unique_ptr()); virtual ~CheckIntegrityEntry(); @@ -77,13 +79,13 @@ public: virtual void initValidator() = 0; - virtual void onDownloadFinished - (std::vector>& commands, - DownloadEngine* e) = 0; + virtual void + onDownloadFinished(std::vector>& commands, + DownloadEngine* e) = 0; - virtual void onDownloadIncomplete - (std::vector>& commands, - DownloadEngine* e) = 0; + virtual void + onDownloadIncomplete(std::vector>& commands, + DownloadEngine* e) = 0; void cutTrailingGarbage(); }; diff --git a/src/Checksum.cc b/src/Checksum.cc index 2d4862e1..035146df 100644 --- a/src/Checksum.cc +++ b/src/Checksum.cc @@ -38,25 +38,17 @@ namespace aria2 { Checksum::Checksum(std::string hashType, std::string digest) - : hashType_(std::move(hashType)), - digest_(std::move(digest)) -{} + : hashType_(std::move(hashType)), digest_(std::move(digest)) +{ +} -Checksum::Checksum() - : hashType_("sha-1") -{} +Checksum::Checksum() : hashType_("sha-1") {} Checksum::~Checksum() {} -bool Checksum::isEmpty() const -{ - return digest_.empty(); -} +bool Checksum::isEmpty() const { return digest_.empty(); } -void Checksum::setDigest(std::string digest) -{ - digest_ = std::move(digest); -} +void Checksum::setDigest(std::string digest) { digest_ = std::move(digest); } void Checksum::setHashType(std::string hashType) { @@ -66,19 +58,16 @@ void Checksum::setHashType(std::string hashType) void Checksum::swap(Checksum& other) { using std::swap; - if(this != &other) { + if (this != &other) { swap(hashType_, other.hashType_); swap(digest_, other.digest_); } } -void swap(Checksum& a, Checksum& b) -{ - a.swap(b); -} +void swap(Checksum& a, Checksum& b) { a.swap(b); } -bool HashTypeStronger::operator() - (const Checksum& lhs, const Checksum& rhs) const +bool HashTypeStronger::operator()(const Checksum& lhs, + const Checksum& rhs) const { return MessageDigest::isStronger(lhs.getHashType(), rhs.getHashType()); } diff --git a/src/Checksum.h b/src/Checksum.h index 686f44a9..2d5bc381 100644 --- a/src/Checksum.h +++ b/src/Checksum.h @@ -45,6 +45,7 @@ class Checksum { private: std::string hashType_; std::string digest_; + public: // digest_ is raw byte array of hash value, not ascii hexadecimal notation. Checksum(std::string hashType, std::string digest); @@ -54,16 +55,10 @@ public: bool isEmpty() const; void setDigest(std::string md); - const std::string& getDigest() const - { - return digest_; - } + const std::string& getDigest() const { return digest_; } void setHashType(std::string type); - const std::string& getHashType() const - { - return hashType_; - } + const std::string& getHashType() const { return hashType_; } void swap(Checksum& other); }; diff --git a/src/ChecksumCheckIntegrityEntry.cc b/src/ChecksumCheckIntegrityEntry.cc index f1c47e07..9e138155 100644 --- a/src/ChecksumCheckIntegrityEntry.cc +++ b/src/ChecksumCheckIntegrityEntry.cc @@ -44,43 +44,42 @@ namespace aria2 { -ChecksumCheckIntegrityEntry::ChecksumCheckIntegrityEntry -(RequestGroup* requestGroup, std::unique_ptr nextCommand) - : CheckIntegrityEntry{requestGroup, std::move(nextCommand)}, - redownload_{false} -{} +ChecksumCheckIntegrityEntry::ChecksumCheckIntegrityEntry( + RequestGroup* requestGroup, std::unique_ptr nextCommand) + : CheckIntegrityEntry{requestGroup, std::move(nextCommand)}, + redownload_{false} +{ +} ChecksumCheckIntegrityEntry::~ChecksumCheckIntegrityEntry() {} bool ChecksumCheckIntegrityEntry::isValidationReady() { const std::shared_ptr& dctx = - getRequestGroup()->getDownloadContext(); + getRequestGroup()->getDownloadContext(); return dctx->isChecksumVerificationAvailable(); } void ChecksumCheckIntegrityEntry::initValidator() { - auto validator = make_unique - (getRequestGroup()->getDownloadContext(), - getRequestGroup()->getPieceStorage()); + auto validator = make_unique( + getRequestGroup()->getDownloadContext(), + getRequestGroup()->getPieceStorage()); validator->init(); setValidator(std::move(validator)); } -void -ChecksumCheckIntegrityEntry::onDownloadFinished -(std::vector>& commands, DownloadEngine* e) -{} +void ChecksumCheckIntegrityEntry::onDownloadFinished( + std::vector>& commands, DownloadEngine* e) +{ +} -void -ChecksumCheckIntegrityEntry::onDownloadIncomplete -(std::vector>& commands, DownloadEngine* e) +void ChecksumCheckIntegrityEntry::onDownloadIncomplete( + std::vector>& commands, DownloadEngine* e) { - if(redownload_) { - proceedFileAllocation(commands, - make_unique - (getRequestGroup(), popNextCommand()), + if (redownload_) { + proceedFileAllocation(commands, make_unique( + getRequestGroup(), popNextCommand()), e); return; } diff --git a/src/ChecksumCheckIntegrityEntry.h b/src/ChecksumCheckIntegrityEntry.h index f043bb6f..8930487a 100644 --- a/src/ChecksumCheckIntegrityEntry.h +++ b/src/ChecksumCheckIntegrityEntry.h @@ -39,14 +39,14 @@ namespace aria2 { -class ChecksumCheckIntegrityEntry:public CheckIntegrityEntry -{ +class ChecksumCheckIntegrityEntry : public CheckIntegrityEntry { private: bool redownload_; + public: - ChecksumCheckIntegrityEntry(RequestGroup* requestGroup, - std::unique_ptr nextCommand = - std::unique_ptr()); + ChecksumCheckIntegrityEntry( + RequestGroup* requestGroup, + std::unique_ptr nextCommand = std::unique_ptr()); virtual ~ChecksumCheckIntegrityEntry(); @@ -54,18 +54,15 @@ public: virtual void initValidator() CXX11_OVERRIDE; - virtual void onDownloadFinished - (std::vector>& commands, - DownloadEngine* e) CXX11_OVERRIDE; + virtual void + onDownloadFinished(std::vector>& commands, + DownloadEngine* e) CXX11_OVERRIDE; - virtual void onDownloadIncomplete - (std::vector>& commands, - DownloadEngine* e) CXX11_OVERRIDE; + virtual void + onDownloadIncomplete(std::vector>& commands, + DownloadEngine* e) CXX11_OVERRIDE; - void setRedownload(bool redownload) - { - redownload_ = redownload; - } + void setRedownload(bool redownload) { redownload_ = redownload; } }; } // namespace aria2 diff --git a/src/ChunkChecksum.cc b/src/ChunkChecksum.cc index 3a081778..1f55a74b 100644 --- a/src/ChunkChecksum.cc +++ b/src/ChunkChecksum.cc @@ -37,20 +37,19 @@ namespace aria2 { -ChunkChecksum::ChunkChecksum():pieceLength_(0) {} +ChunkChecksum::ChunkChecksum() : pieceLength_(0) {} -ChunkChecksum::ChunkChecksum -(std::string hashType, - std::vector pieceHashes, - int32_t pieceLength) - : hashType_(std::move(hashType)), - pieceHashes_(std::move(pieceHashes)), - pieceLength_(pieceLength) -{} +ChunkChecksum::ChunkChecksum(std::string hashType, + std::vector pieceHashes, + int32_t pieceLength) + : hashType_(std::move(hashType)), + pieceHashes_(std::move(pieceHashes)), + pieceLength_(pieceLength) +{ +} -bool ChunkChecksum::validateChunk -(const std::string& actualDigest, - size_t index) const +bool ChunkChecksum::validateChunk(const std::string& actualDigest, + size_t index) const { const std::string& digest = getPieceHash(index); return !digest.empty() && actualDigest == digest; @@ -58,19 +57,17 @@ bool ChunkChecksum::validateChunk int64_t ChunkChecksum::getEstimatedDataLength() const { - return static_cast(pieceLength_)*pieceHashes_.size(); + return static_cast(pieceLength_) * pieceHashes_.size(); } -size_t ChunkChecksum::countPieceHash() const -{ - return pieceHashes_.size(); -} +size_t ChunkChecksum::countPieceHash() const { return pieceHashes_.size(); } const std::string& ChunkChecksum::getPieceHash(size_t index) const { - if(index < pieceHashes_.size()) { + if (index < pieceHashes_.size()) { return pieceHashes_[index]; - } else { + } + else { return A2STR::NIL; } } diff --git a/src/ChunkChecksum.h b/src/ChunkChecksum.h index 14acac85..dfa5bff2 100644 --- a/src/ChunkChecksum.h +++ b/src/ChunkChecksum.h @@ -47,16 +47,14 @@ private: std::string hashType_; std::vector pieceHashes_; int32_t pieceLength_; + public: ChunkChecksum(); - ChunkChecksum - (std::string hashType, - std::vector pieceHashes, - int32_t pieceLength); + ChunkChecksum(std::string hashType, std::vector pieceHashes, + int32_t pieceLength); - bool validateChunk(const std::string& actualDigest, - size_t index) const; + bool validateChunk(const std::string& actualDigest, size_t index) const; int64_t getEstimatedDataLength() const; @@ -71,20 +69,11 @@ public: } void setHashType(std::string hashType); - const std::string& getHashType() const - { - return hashType_; - } + const std::string& getHashType() const { return hashType_; } - int32_t getPieceLength() const - { - return pieceLength_; - } + int32_t getPieceLength() const { return pieceLength_; } - void setPieceLength(int32_t length) - { - pieceLength_ = length; - } + void setPieceLength(int32_t length) { pieceLength_ = length; } }; } // namespace aria2 diff --git a/src/ChunkedDecodingStreamFilter.cc b/src/ChunkedDecodingStreamFilter.cc index 6c98bd5f..9101ceab 100644 --- a/src/ChunkedDecodingStreamFilter.cc +++ b/src/ChunkedDecodingStreamFilter.cc @@ -43,8 +43,8 @@ namespace aria2 { -const std::string ChunkedDecodingStreamFilter::NAME -("ChunkedDecodingStreamFilter"); +const std::string + ChunkedDecodingStreamFilter::NAME("ChunkedDecodingStreamFilter"); namespace { enum { @@ -64,128 +64,141 @@ enum { }; } // namespace -ChunkedDecodingStreamFilter::ChunkedDecodingStreamFilter -(std::unique_ptr delegate) - : StreamFilter{std::move(delegate)}, - state_{PREV_CHUNK_SIZE}, - chunkSize_{0}, - chunkRemaining_{0}, - bytesProcessed_{0} -{} +ChunkedDecodingStreamFilter::ChunkedDecodingStreamFilter( + std::unique_ptr delegate) + : StreamFilter{std::move(delegate)}, + state_{PREV_CHUNK_SIZE}, + chunkSize_{0}, + chunkRemaining_{0}, + bytesProcessed_{0} +{ +} ChunkedDecodingStreamFilter::~ChunkedDecodingStreamFilter() {} void ChunkedDecodingStreamFilter::init() {} -ssize_t ChunkedDecodingStreamFilter::transform -(const std::shared_ptr& out, - const std::shared_ptr& segment, - const unsigned char* inbuf, size_t inlen) +ssize_t +ChunkedDecodingStreamFilter::transform(const std::shared_ptr& out, + const std::shared_ptr& segment, + const unsigned char* inbuf, size_t inlen) { ssize_t outlen = 0; size_t i; bytesProcessed_ = 0; - for(i = 0; i < inlen; ++i) { + for (i = 0; i < inlen; ++i) { unsigned char c = inbuf[i]; - switch(state_) { + switch (state_) { case PREV_CHUNK_SIZE: - if(util::isHexDigit(c)) { + if (util::isHexDigit(c)) { chunkSize_ = util::hexCharToUInt(c); state_ = CHUNK_SIZE; - } else { + } + else { throw DL_ABORT_EX("Bad chunk size: not hex string"); } break; case CHUNK_SIZE: - if(util::isHexDigit(c)) { - if(chunkSize_ & 0x7800000000000000LL) { + if (util::isHexDigit(c)) { + if (chunkSize_ & 0x7800000000000000LL) { throw DL_ABORT_EX("Too big chunk size"); } chunkSize_ <<= 4; chunkSize_ += util::hexCharToUInt(c); - } else if(c == ';') { + } + else if (c == ';') { state_ = CHUNK_EXTENSION; - } else if(c == '\r') { + } + else if (c == '\r') { state_ = PREV_CHUNK_SIZE_LF; - } else { + } + else { throw DL_ABORT_EX("Bad chunk size: not hex string"); } break; case CHUNK_EXTENSION: - if(c == '\r') { + if (c == '\r') { state_ = PREV_CHUNK_SIZE_LF; } break; case PREV_CHUNK_SIZE_LF: - if(c == '\n') { + if (c == '\n') { chunkRemaining_ = chunkSize_; - if(chunkSize_ == 0) { + if (chunkSize_ == 0) { state_ = PREV_TRAILER; - } else { + } + else { state_ = CHUNK; } - } else { + } + else { throw DL_ABORT_EX("Bad chunk encoding: " "missing LF at the end of chunk size"); } break; case CHUNK: { - int64_t readlen = std::min(chunkRemaining_, - static_cast(inlen-i)); - outlen += getDelegate()->transform(out, segment, inbuf+i, readlen); + int64_t readlen = + std::min(chunkRemaining_, static_cast(inlen - i)); + outlen += getDelegate()->transform(out, segment, inbuf + i, readlen); chunkRemaining_ -= readlen; - i += readlen-1; - if(chunkRemaining_ == 0) { + i += readlen - 1; + if (chunkRemaining_ == 0) { state_ = PREV_CHUNK_CR; } break; } case PREV_CHUNK_CR: - if(c == '\r') { + if (c == '\r') { state_ = PREV_CHUNK_LF; - } else { + } + else { throw DL_ABORT_EX("Bad chunk encoding: " "missing CR at the end of chunk"); } break; case PREV_CHUNK_LF: - if(c == '\n') { - if(chunkSize_ == 0) { + if (c == '\n') { + if (chunkSize_ == 0) { state_ = PREV_TRAILER; - } else { + } + else { chunkSize_ = chunkRemaining_ = 0; state_ = PREV_CHUNK_SIZE; } - } else { + } + else { throw DL_ABORT_EX("Bad chunk encoding: " "missing LF at the end of chunk"); } break; case PREV_TRAILER: - if(c == '\r') { + if (c == '\r') { // No trailer state_ = PREV_END_LF; - } else { - state_= TRAILER; + } + else { + state_ = TRAILER; } break; case TRAILER: - if(c == '\r') { + if (c == '\r') { state_ = PREV_TRAILER_LF; } break; case PREV_TRAILER_LF: - if(c == '\n') { + if (c == '\n') { state_ = PREV_TRAILER; - } else { + } + else { throw DL_ABORT_EX("Bad chunk encoding: " "missing LF at the end of trailer"); } break; case PREV_END_LF: - if(c == '\n') { + if (c == '\n') { state_ = CHUNKS_COMPLETE; - } else { + } + else { throw DL_ABORT_EX("Bad chunk encoding: " "missing LF at the end of chunks"); } @@ -197,7 +210,7 @@ ssize_t ChunkedDecodingStreamFilter::transform assert(0); } } - fin: +fin: bytesProcessed_ += i; return outlen; } @@ -209,9 +222,6 @@ bool ChunkedDecodingStreamFilter::finished() void ChunkedDecodingStreamFilter::release() {} -const std::string& ChunkedDecodingStreamFilter::getName() const -{ - return NAME; -} +const std::string& ChunkedDecodingStreamFilter::getName() const { return NAME; } } // namespace aria2 diff --git a/src/ChunkedDecodingStreamFilter.h b/src/ChunkedDecodingStreamFilter.h index 10c4abfa..352859f8 100644 --- a/src/ChunkedDecodingStreamFilter.h +++ b/src/ChunkedDecodingStreamFilter.h @@ -45,18 +45,18 @@ private: int64_t chunkSize_; int64_t chunkRemaining_; size_t bytesProcessed_; + public: - ChunkedDecodingStreamFilter - (std::unique_ptr delegate = nullptr); + ChunkedDecodingStreamFilter(std::unique_ptr delegate = nullptr); virtual ~ChunkedDecodingStreamFilter(); virtual void init() CXX11_OVERRIDE; - virtual ssize_t transform - (const std::shared_ptr& out, - const std::shared_ptr& segment, - const unsigned char* inbuf, size_t inlen) CXX11_OVERRIDE; + virtual ssize_t transform(const std::shared_ptr& out, + const std::shared_ptr& segment, + const unsigned char* inbuf, + size_t inlen) CXX11_OVERRIDE; virtual bool finished() CXX11_OVERRIDE; diff --git a/src/ColorizedStream.cc b/src/ColorizedStream.cc index 0f7656c3..b84ec08c 100644 --- a/src/ColorizedStream.cc +++ b/src/ColorizedStream.cc @@ -35,7 +35,6 @@ #include "ColorizedStream.h" - namespace aria2 { namespace colors { @@ -63,7 +62,7 @@ const Color clear("0"); std::string ColorizedStreamBuf::str(bool color) const { std::stringstream rv; - for (const auto& e: elems) { + for (const auto& e : elems) { if (color || e.first != eColor) { rv << e.second; } @@ -77,7 +76,7 @@ std::string ColorizedStreamBuf::str(bool color) const std::string ColorizedStreamBuf::str(bool color, size_t max) const { std::stringstream rv; - for (const auto& e: elems) { + for (const auto& e : elems) { if (e.first == eColor) { if (color) { rv << e.second; diff --git a/src/ColorizedStream.h b/src/ColorizedStream.h index fb5e4b7e..867af87a 100644 --- a/src/ColorizedStream.h +++ b/src/ColorizedStream.h @@ -46,19 +46,14 @@ namespace aria2 { namespace colors { -class Color -{ +class Color { private: std::string str_; public: - explicit Color(const char* str) - : str_(std::string("\033[") + str + "m") - {} + explicit Color(const char* str) : str_(std::string("\033[") + str + "m") {} - const std::string& str() const { - return str_; - } + const std::string& str() const { return str_; } }; extern const Color black; @@ -83,23 +78,14 @@ extern const Color clear; } // namespace colors typedef std::char_traits traits_t; -class ColorizedStreamBuf - : public std::basic_streambuf -{ - enum part_t - { - eColor, - eString - }; +class ColorizedStreamBuf : public std::basic_streambuf { + enum part_t { eColor, eString }; typedef std::pair elem_t; typedef std::deque elems_t; elems_t elems; public: - ColorizedStreamBuf() - { - elems.push_back(std::make_pair(eString, "")); - } + ColorizedStreamBuf() { elems.push_back(std::make_pair(eString, "")); } void setColor(const colors::Color& color) { @@ -113,45 +99,28 @@ public: return std::char_traits::not_eof(c); } - void append(const std::string& str) - { - elems.back().second += str; - } + void append(const std::string& str) { elems.back().second += str; } - void append(const char* str) - { - elems.back().second += str; - } + void append(const char* str) { elems.back().second += str; } std::string str(bool color) const; std::string str(bool color, size_t max) const; }; -class ColorizedStream: public std::basic_ostream -{ +class ColorizedStream : public std::basic_ostream { public: ColorizedStream() - : std::basic_ios(&buf), - std::basic_ostream(&buf) + : std::basic_ios(&buf), + std::basic_ostream(&buf) { init(&buf); } - void setColor(const colors::Color& color) - { - buf.setColor(color); - } - void append(const std::string& str) { - buf.append(str); - } - void append(const char* str) { - buf.append(str); - } + void setColor(const colors::Color& color) { buf.setColor(color); } + void append(const std::string& str) { buf.append(str); } + void append(const char* str) { buf.append(str); } - std::string str(bool colors) const - { - return buf.str(colors); - } + std::string str(bool colors) const { return buf.str(colors); } std::string str(bool colors, size_t max) const { return buf.str(colors, max); @@ -161,22 +130,21 @@ private: ColorizedStreamBuf buf; }; -inline -ColorizedStream& operator<<(ColorizedStream& stream, const std::string& str) +inline ColorizedStream& operator<<(ColorizedStream& stream, + const std::string& str) { stream.append(str); return stream; } -inline -ColorizedStream& operator<<(ColorizedStream& stream, const char* str) +inline ColorizedStream& operator<<(ColorizedStream& stream, const char* str) { stream.append(str); return stream; } -inline -ColorizedStream& operator<<(ColorizedStream& stream, const colors::Color& c) +inline ColorizedStream& operator<<(ColorizedStream& stream, + const colors::Color& c) { stream.setColor(c); return stream; diff --git a/src/Command.cc b/src/Command.cc index b9e236b7..d24471cd 100644 --- a/src/Command.cc +++ b/src/Command.cc @@ -38,17 +38,18 @@ namespace aria2 { Command::Command(cuid_t cuid) - : cuid_(cuid), - status_(STATUS_INACTIVE), - readEvent_(false), - writeEvent_(false), - errorEvent_(false), - hupEvent_(false) -{} + : cuid_(cuid), + status_(STATUS_INACTIVE), + readEvent_(false), + writeEvent_(false), + errorEvent_(false), + hupEvent_(false) +{ +} void Command::transitStatus() { - switch(status_) { + switch (status_) { case STATUS_REALTIME: break; default: @@ -56,30 +57,15 @@ void Command::transitStatus() } } -void Command::setStatus(STATUS status) -{ - status_ = status; -} +void Command::setStatus(STATUS status) { status_ = status; } -void Command::readEventReceived() -{ - readEvent_ = true; -} +void Command::readEventReceived() { readEvent_ = true; } -void Command::writeEventReceived() -{ - writeEvent_ = true; -} +void Command::writeEventReceived() { writeEvent_ = true; } -void Command::errorEventReceived() -{ - errorEvent_ = true; -} +void Command::errorEventReceived() { errorEvent_ = true; } -void Command::hupEventReceived() -{ - hupEvent_ = true; -} +void Command::hupEventReceived() { hupEvent_ = true; } void Command::clearIOEvents() { diff --git a/src/Command.h b/src/Command.h index 07d4de6d..a50cb811 100644 --- a/src/Command.h +++ b/src/Command.h @@ -62,25 +62,13 @@ private: bool hupEvent_; protected: - bool readEventEnabled() const - { - return readEvent_; - } + bool readEventEnabled() const { return readEvent_; } - bool writeEventEnabled() const - { - return writeEvent_; - } + bool writeEventEnabled() const { return writeEvent_; } - bool errorEventEnabled() const - { - return errorEvent_; - } + bool errorEventEnabled() const { return errorEvent_; } - bool hupEventEnabled() const - { - return hupEvent_; - } + bool hupEventEnabled() const { return hupEvent_; } public: Command(cuid_t cuid); diff --git a/src/ConnectCommand.cc b/src/ConnectCommand.cc index f4fd534b..5d1566be 100644 --- a/src/ConnectCommand.cc +++ b/src/ConnectCommand.cc @@ -47,15 +47,13 @@ namespace aria2 { -ConnectCommand::ConnectCommand(cuid_t cuid, - const std::shared_ptr& req, +ConnectCommand::ConnectCommand(cuid_t cuid, const std::shared_ptr& req, const std::shared_ptr& proxyRequest, const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - DownloadEngine* e, + RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr& s) - : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), - proxyRequest_(proxyRequest) + : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), + proxyRequest_(proxyRequest) { setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT))); disableReadCheckSocket(); @@ -64,19 +62,19 @@ ConnectCommand::ConnectCommand(cuid_t cuid, ConnectCommand::~ConnectCommand() { - if(backupConnectionInfo_) { + if (backupConnectionInfo_) { backupConnectionInfo_->cancel = true; } } -void ConnectCommand::setControlChain -(const std::shared_ptr >& chain) +void ConnectCommand::setControlChain( + const std::shared_ptr>& chain) { chain_ = chain; } -void ConnectCommand::setBackupConnectInfo -(const std::shared_ptr& info) +void ConnectCommand::setBackupConnectInfo( + const std::shared_ptr& info) { backupConnectionInfo_ = info; } @@ -88,13 +86,12 @@ const std::shared_ptr& ConnectCommand::getProxyRequest() const bool ConnectCommand::executeInternal() { - if(backupConnectionInfo_ && !backupConnectionInfo_->ipaddr.empty()) { + if (backupConnectionInfo_ && !backupConnectionInfo_->ipaddr.empty()) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - Use backup connection address %s", getCuid(), backupConnectionInfo_->ipaddr.c_str())); - getDownloadEngine()->markBadIPAddress - (getRequest()->getConnectedHostname(), - getRequest()->getConnectedAddr(), - getRequest()->getConnectedPort()); + getDownloadEngine()->markBadIPAddress(getRequest()->getConnectedHostname(), + getRequest()->getConnectedAddr(), + getRequest()->getConnectedPort()); getRequest()->setConnectedAddrInfo(getRequest()->getConnectedHostname(), backupConnectionInfo_->ipaddr, @@ -102,12 +99,12 @@ bool ConnectCommand::executeInternal() swapSocket(backupConnectionInfo_->socket); backupConnectionInfo_.reset(); } - if(!checkIfConnectionEstablished - (getSocket(), getRequest()->getConnectedHostname(), - getRequest()->getConnectedAddr(), getRequest()->getConnectedPort())) { + if (!checkIfConnectionEstablished( + getSocket(), getRequest()->getConnectedHostname(), + getRequest()->getConnectedAddr(), getRequest()->getConnectedPort())) { return true; } - if(backupConnectionInfo_) { + if (backupConnectionInfo_) { backupConnectionInfo_->cancel = true; backupConnectionInfo_.reset(); } diff --git a/src/ConnectCommand.h b/src/ConnectCommand.h index 29a4cca1..32cfa8e5 100644 --- a/src/ConnectCommand.h +++ b/src/ConnectCommand.h @@ -44,25 +44,25 @@ struct BackupConnectInfo; class ConnectCommand : public AbstractCommand { public: - ConnectCommand(cuid_t cuid, - const std::shared_ptr& req, + ConnectCommand(cuid_t cuid, const std::shared_ptr& req, const std::shared_ptr& proxyRequest, const std::shared_ptr& fileEntry, - RequestGroup* requestGroup, - DownloadEngine* e, + RequestGroup* requestGroup, DownloadEngine* e, const std::shared_ptr& s); virtual ~ConnectCommand(); - void setControlChain - (const std::shared_ptr >& chain); + void + setControlChain(const std::shared_ptr>& chain); void setBackupConnectInfo(const std::shared_ptr& info); const std::shared_ptr& getProxyRequest() const; + protected: virtual bool executeInternal() CXX11_OVERRIDE; virtual bool noCheck() const CXX11_OVERRIDE; + private: std::shared_ptr proxyRequest_; std::shared_ptr backupConnectionInfo_; - std::shared_ptr > chain_; + std::shared_ptr> chain_; }; } // namespace aria2 diff --git a/src/ConsoleStatCalc.cc b/src/ConsoleStatCalc.cc index 0dd4366e..9ea84a88 100644 --- a/src/ConsoleStatCalc.cc +++ b/src/ConsoleStatCalc.cc @@ -66,9 +66,9 @@ #include "Option.h" #ifdef ENABLE_BITTORRENT -# include "bittorrent_helper.h" -# include "PeerStorage.h" -# include "BtRegistry.h" +#include "bittorrent_helper.h" +#include "PeerStorage.h" +#include "BtRegistry.h" #endif // ENABLE_BITTORRENT namespace aria2 { @@ -79,7 +79,7 @@ std::string SizeFormatter::operator()(int64_t size) const } namespace { -class AbbrevSizeFormatter:public SizeFormatter { +class AbbrevSizeFormatter : public SizeFormatter { protected: virtual std::string format(int64_t size) const CXX11_OVERRIDE { @@ -89,7 +89,7 @@ protected: } // namespace namespace { -class PlainSizeFormatter:public SizeFormatter { +class PlainSizeFormatter : public SizeFormatter { protected: virtual std::string format(int64_t size) const CXX11_OVERRIDE { @@ -105,29 +105,31 @@ void printSizeProgress(ColorizedStream& o, const SizeFormatter& sizeFormatter) { #ifdef ENABLE_BITTORRENT - if(rg->getDownloadContext()->hasAttribute(CTX_ATTR_BT) && - !bittorrent::getTorrentAttrs(rg->getDownloadContext()) - ->metadata.empty() && rg->downloadFinished()) { + if (rg->getDownloadContext()->hasAttribute(CTX_ATTR_BT) && + !bittorrent::getTorrentAttrs(rg->getDownloadContext()) + ->metadata.empty() && + rg->downloadFinished()) { o << "SEED("; - if(rg->getCompletedLength() > 0) { + if (rg->getCompletedLength() > 0) { std::streamsize oldprec = o.precision(); o << std::fixed << std::setprecision(1) - << ((stat.allTimeUploadLength*10)/rg->getCompletedLength())/10.0 - << std::setprecision(oldprec) - << std::resetiosflags(std::ios::fixed); - } else { + << ((stat.allTimeUploadLength * 10) / rg->getCompletedLength()) / 10.0 + << std::setprecision(oldprec) << std::resetiosflags(std::ios::fixed); + } + else { o << "--"; } o << ")"; - } else + } + else #endif // ENABLE_BITTORRENT - { - o << sizeFormatter(rg->getCompletedLength()) << "B/" - << sizeFormatter(rg->getTotalLength()) << "B"; - if(rg->getTotalLength() > 0) { - o << "(" << 100*rg->getCompletedLength()/rg->getTotalLength() << "%)"; - } + { + o << sizeFormatter(rg->getCompletedLength()) << "B/" + << sizeFormatter(rg->getTotalLength()) << "B"; + if (rg->getTotalLength() > 0) { + o << "(" << 100 * rg->getCompletedLength() / rg->getTotalLength() << "%)"; } + } } } // namespace @@ -146,20 +148,19 @@ void printProgressCompact(ColorizedStream& o, const DownloadEngine* e, o << "]"; } - const RequestGroupList& groups = - e->getRequestGroupMan()->getRequestGroups(); + const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups(); size_t cnt = 0; const size_t MAX_ITEM = 5; - for(auto i = groups.begin(), - eoi = groups.end(); i != eoi && cnt < MAX_ITEM; ++i, ++cnt) { + for (auto i = groups.begin(), eoi = groups.end(); i != eoi && cnt < MAX_ITEM; + ++i, ++cnt) { const std::shared_ptr& rg = *i; TransferStat stat = rg->calculateStat(); o << "[#" << GroupId::toAbbrevHex(rg->getGID()) << " "; printSizeProgress(o, rg, stat, sizeFormatter); o << "]"; } - if(cnt < groups.size()) { - o << "(+" << groups.size()-cnt << ")"; + if (cnt < groups.size()) { + o << "(+" << groups.size() - cnt << ")"; } } } // namespace @@ -170,30 +171,28 @@ void printProgress(ColorizedStream& o, const std::shared_ptr& rg, { TransferStat stat = rg->calculateStat(); int eta = 0; - if(rg->getTotalLength() > 0 && stat.downloadSpeed > 0) { - eta = (rg->getTotalLength()-rg->getCompletedLength())/stat.downloadSpeed; + if (rg->getTotalLength() > 0 && stat.downloadSpeed > 0) { + eta = + (rg->getTotalLength() - rg->getCompletedLength()) / stat.downloadSpeed; } o << "[#" << GroupId::toAbbrevHex(rg->getGID()) << " "; printSizeProgress(o, rg, stat, sizeFormatter); - o << " CN:" - << rg->getNumConnection(); + o << " CN:" << rg->getNumConnection(); #ifdef ENABLE_BITTORRENT auto btObj = e->getBtRegistry()->get(rg->getGID()); - if(btObj) { + if (btObj) { const PeerSet& peers = btObj->peerStorage->getUsedPeers(); - o << " SD:" - << countSeeder(peers.begin(), peers.end()); + o << " SD:" << countSeeder(peers.begin(), peers.end()); } #endif // ENABLE_BITTORRENT if (!rg->downloadFinished()) { - o << " DL:" << - colors::green << sizeFormatter(stat.downloadSpeed) << "B" << - colors::clear; + o << " DL:" << colors::green << sizeFormatter(stat.downloadSpeed) << "B" + << colors::clear; } if (stat.sessionUploadLength > 0) { - o << " UL:" << - colors::cyan << sizeFormatter(stat.uploadSpeed) << "B" << colors::clear; + o << " UL:" << colors::cyan << sizeFormatter(stat.uploadSpeed) << "B" + << colors::clear; o << "(" << sizeFormatter(stat.allTimeUploadLength) << "B)"; } if (eta > 0) { @@ -204,30 +203,30 @@ void printProgress(ColorizedStream& o, const std::shared_ptr& rg, } // namespace namespace { -class PrintSummary -{ +class PrintSummary { private: size_t cols_; const DownloadEngine* e_; const SizeFormatter& sizeFormatter_; + public: - PrintSummary - (size_t cols, const DownloadEngine* e, - const SizeFormatter& sizeFormatter): - cols_(cols), e_(e), sizeFormatter_(sizeFormatter) {} + PrintSummary(size_t cols, const DownloadEngine* e, + const SizeFormatter& sizeFormatter) + : cols_(cols), e_(e), sizeFormatter_(sizeFormatter) + { + } void operator()(const RequestGroupList::value_type& rg) { const char SEP_CHAR = '-'; ColorizedStream o; printProgress(o, rg, e_, sizeFormatter_); - const std::vector >& fileEntries = - rg->getDownloadContext()->getFileEntries(); + const std::vector>& fileEntries = + rg->getDownloadContext()->getFileEntries(); o << "\nFILE: "; - writeFilePath(fileEntries.begin(), fileEntries.end(), - o, rg->inMemoryDownload()); - o << "\n" - << std::setfill(SEP_CHAR) << std::setw(cols_) << SEP_CHAR << "\n"; + writeFilePath(fileEntries.begin(), fileEntries.end(), o, + rg->inMemoryDownload()); + o << "\n" << std::setfill(SEP_CHAR) << std::setw(cols_) << SEP_CHAR << "\n"; auto str = o.str(false); global::cout()->write(str.c_str()); } @@ -248,17 +247,18 @@ void printProgressSummary(const RequestGroupList& groups, size_t cols, time_t now; struct tm* staticNowtmPtr; char buf[26]; - if(time(&now) != (time_t)-1 && (staticNowtmPtr = localtime(&now)) != nullptr && - asctime_r(staticNowtmPtr, buf) != nullptr) { + if (time(&now) != (time_t)-1 && + (staticNowtmPtr = localtime(&now)) != nullptr && + asctime_r(staticNowtmPtr, buf) != nullptr) { char* lfptr = strchr(buf, '\n'); - if(lfptr) { + if (lfptr) { *lfptr = '\0'; } o << " as of " << buf; } } - o << " *** \n" - << std::setfill(SEP_CHAR) << std::setw(cols) << SEP_CHAR << "\n"; + o << " *** \n" << std::setfill(SEP_CHAR) << std::setw(cols) << SEP_CHAR + << "\n"; global::cout()->write(o.str().c_str()); std::for_each(groups.begin(), groups.end(), PrintSummary(cols, e, sizeFormatter)); @@ -266,30 +266,29 @@ void printProgressSummary(const RequestGroupList& groups, size_t cols, } // namespace ConsoleStatCalc::ConsoleStatCalc(std::chrono::seconds summaryInterval, - bool colorOutput, - bool humanReadable): - summaryInterval_(std::move(summaryInterval)), - readoutVisibility_(true), - truncate_(true), + bool colorOutput, bool humanReadable) + : summaryInterval_(std::move(summaryInterval)), + readoutVisibility_(true), + truncate_(true), #ifdef __MINGW32__ - isTTY_(true), -#else // !__MINGW32__ - isTTY_(isatty(STDOUT_FILENO) == 1), + isTTY_(true), +#else // !__MINGW32__ + isTTY_(isatty(STDOUT_FILENO) == 1), #endif // !__MINGW32__ - colorOutput_(colorOutput) + colorOutput_(colorOutput) { - if(humanReadable) { + if (humanReadable) { sizeFormatter_ = make_unique(); - } else { + } + else { sizeFormatter_ = make_unique(); } } -void -ConsoleStatCalc::calculateStat(const DownloadEngine* e) +void ConsoleStatCalc::calculateStat(const DownloadEngine* e) { - if(cp_.difference(global::wallclock()) + A2_DELTA_MILLIS < - std::chrono::milliseconds(1000)) { + if (cp_.difference(global::wallclock()) + A2_DELTA_MILLIS < + std::chrono::milliseconds(1000)) { return; } cp_ = global::wallclock(); @@ -299,17 +298,18 @@ ConsoleStatCalc::calculateStat(const DownloadEngine* e) // character reached at the last column. unsigned short int cols = 79; - if(isTTY_) { + if (isTTY_) { #ifndef __MINGW32__ #ifdef HAVE_TERMIOS_H struct winsize size; - if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) { - cols = std::max(0, (int)size.ws_col-1); + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) { + cols = std::max(0, (int)size.ws_col - 1); } #endif // HAVE_TERMIOS_H -#else // __MINGW32__ +#else // __MINGW32__ CONSOLE_SCREEN_BUFFER_INFO info; - if(::GetConsoleScreenBufferInfo(::GetStdHandle(STD_OUTPUT_HANDLE), &info)) { + if (::GetConsoleScreenBufferInfo(::GetStdHandle(STD_OUTPUT_HANDLE), + &info)) { cols = std::max(0, info.dwSize.X - 2); } #endif // !__MINGW32__ @@ -317,10 +317,11 @@ ConsoleStatCalc::calculateStat(const DownloadEngine* e) global::cout()->printf("\r%s\r", line.c_str()); } ColorizedStream o; - if(e->getRequestGroupMan()->countRequestGroup() > 0) { - if((summaryInterval_ > 0_s) && - lastSummaryNotified_.difference(global::wallclock())+ - A2_DELTA_MILLIS >= summaryInterval_) { + if (e->getRequestGroupMan()->countRequestGroup() > 0) { + if ((summaryInterval_ > 0_s) && + lastSummaryNotified_.difference(global::wallclock()) + + A2_DELTA_MILLIS >= + summaryInterval_) { lastSummaryNotified_ = global::wallclock(); printProgressSummary(e->getRequestGroupMan()->getRequestGroups(), cols, e, sizeFormatter); @@ -328,57 +329,60 @@ ConsoleStatCalc::calculateStat(const DownloadEngine* e) global::cout()->flush(); } } - if(!readoutVisibility_) { + if (!readoutVisibility_) { return; } size_t numGroup = e->getRequestGroupMan()->countRequestGroup(); const bool color = global::cout()->supportsColor() && isTTY_ && colorOutput_; - if(numGroup == 1) { + if (numGroup == 1) { const std::shared_ptr& rg = - *e->getRequestGroupMan()->getRequestGroups().begin(); + *e->getRequestGroupMan()->getRequestGroups().begin(); printProgress(o, rg, e, sizeFormatter); - } else if(numGroup > 1) { + } + else if (numGroup > 1) { // For more than 2 RequestGroups, use compact readout form printProgressCompact(o, e, sizeFormatter); } { auto& entry = e->getFileAllocationMan()->getPickedEntry(); - if(entry) { + if (entry) { o << " [FileAlloc:#" << GroupId::toAbbrevHex(entry->getRequestGroup()->getGID()) << " " << sizeFormatter(entry->getCurrentLength()) << "B/" << sizeFormatter(entry->getTotalLength()) << "B("; - if(entry->getTotalLength() > 0) { - o << 100LL*entry->getCurrentLength()/entry->getTotalLength(); - } else { + if (entry->getTotalLength() > 0) { + o << 100LL * entry->getCurrentLength() / entry->getTotalLength(); + } + else { o << "--"; } o << "%)]"; - if(e->getFileAllocationMan()->hasNext()) { + if (e->getFileAllocationMan()->hasNext()) { o << "(+" << e->getFileAllocationMan()->countEntryInQueue() << ")"; } } } { auto& entry = e->getCheckIntegrityMan()->getPickedEntry(); - if(entry) { + if (entry) { o << " [Checksum:#" << GroupId::toAbbrevHex(entry->getRequestGroup()->getGID()) << " " << sizeFormatter(entry->getCurrentLength()) << "B/" << sizeFormatter(entry->getTotalLength()) << "B("; - if(entry->getTotalLength() > 0) { - o << 100LL*entry->getCurrentLength()/entry->getTotalLength(); - } else { + if (entry->getTotalLength() > 0) { + o << 100LL * entry->getCurrentLength() / entry->getTotalLength(); + } + else { o << "--"; } o << "%)]"; - if(e->getCheckIntegrityMan()->hasNext()) { + if (e->getCheckIntegrityMan()->hasNext()) { o << "(+" << e->getCheckIntegrityMan()->countEntryInQueue() << ")"; } } } - if(isTTY_) { + if (isTTY_) { if (truncate_) { auto str = o.str(color, cols); global::cout()->write(str.c_str()); diff --git a/src/ConsoleStatCalc.h b/src/ConsoleStatCalc.h index f3faaaa6..f25e6c60 100644 --- a/src/ConsoleStatCalc.h +++ b/src/ConsoleStatCalc.h @@ -45,17 +45,17 @@ namespace aria2 { -class SizeFormatter:public std::unary_function { +class SizeFormatter : public std::unary_function { protected: virtual std::string format(int64_t size) const = 0; + public: virtual ~SizeFormatter() {} std::string operator()(int64_t size) const; }; -class ConsoleStatCalc:public StatCalc -{ +class ConsoleStatCalc : public StatCalc { private: Timer cp_; @@ -68,6 +68,7 @@ private: bool truncate_; bool isTTY_; bool colorOutput_; + public: ConsoleStatCalc(std::chrono::seconds summaryInterval, bool colorOutput = true, bool humanReadable = true); @@ -81,10 +82,7 @@ public: readoutVisibility_ = visibility; } - void setTruncate(bool truncate) - { - truncate_ = truncate; - } + void setTruncate(bool truncate) { truncate_ = truncate; } }; } // namespace aria2 diff --git a/src/ContentTypeRequestGroupCriteria.cc b/src/ContentTypeRequestGroupCriteria.cc index 68cc7f07..40e311e2 100644 --- a/src/ContentTypeRequestGroupCriteria.cc +++ b/src/ContentTypeRequestGroupCriteria.cc @@ -41,28 +41,30 @@ namespace aria2 { -ContentTypeRequestGroupCriteria::ContentTypeRequestGroupCriteria -(const char** contentTypes, const char** extensions) - : contentTypes_(contentTypes), - extensions_(extensions) -{} +ContentTypeRequestGroupCriteria::ContentTypeRequestGroupCriteria( + const char** contentTypes, const char** extensions) + : contentTypes_(contentTypes), extensions_(extensions) +{ +} ContentTypeRequestGroupCriteria::~ContentTypeRequestGroupCriteria() {} -bool ContentTypeRequestGroupCriteria::match -(const RequestGroup* requestGroup) const +bool ContentTypeRequestGroupCriteria::match( + const RequestGroup* requestGroup) const { - if(requestGroup->getDownloadContext()->getFileEntries().size() != 1) { + if (requestGroup->getDownloadContext()->getFileEntries().size() != 1) { return false; } - for(size_t i = 0; extensions_[i]; ++i) { - if(util::iendsWith(requestGroup->getFirstFilePath(), extensions_[i])) { + for (size_t i = 0; extensions_[i]; ++i) { + if (util::iendsWith(requestGroup->getFirstFilePath(), extensions_[i])) { return true; } } - for(size_t i = 0; contentTypes_[i]; ++i) { - if(util::strieq(requestGroup->getDownloadContext()->getFirstFileEntry()-> - getContentType(), contentTypes_[i])) { + for (size_t i = 0; contentTypes_[i]; ++i) { + if (util::strieq(requestGroup->getDownloadContext() + ->getFirstFileEntry() + ->getContentType(), + contentTypes_[i])) { return true; } } diff --git a/src/ContentTypeRequestGroupCriteria.h b/src/ContentTypeRequestGroupCriteria.h index 371f163d..b5a8bd14 100644 --- a/src/ContentTypeRequestGroupCriteria.h +++ b/src/ContentTypeRequestGroupCriteria.h @@ -41,11 +41,11 @@ namespace aria2 { -class ContentTypeRequestGroupCriteria:public RequestGroupCriteria -{ +class ContentTypeRequestGroupCriteria : public RequestGroupCriteria { private: const char** contentTypes_; const char** extensions_; + public: ContentTypeRequestGroupCriteria(const char** contentTypes, const char** extensions); diff --git a/src/Context.cc b/src/Context.cc index 1f6d8d10..7fd52c98 100644 --- a/src/Context.cc +++ b/src/Context.cc @@ -41,7 +41,6 @@ #include #endif // HAVE_SYS_RESOURCE_H - #include #include #include @@ -73,11 +72,11 @@ #include "UriListParser.h" #include "message_digest_helper.h" #ifdef ENABLE_BITTORRENT -# include "bittorrent_helper.h" +#include "bittorrent_helper.h" #endif // ENABLE_BITTORRENT #ifdef ENABLE_METALINK -# include "metalink_helper.h" -# include "MetalinkEntry.h" +#include "metalink_helper.h" +#include "MetalinkEntry.h" #endif // ENABLE_METALINK extern char* optarg; @@ -99,11 +98,10 @@ void showTorrentFile(const std::string& uri) #ifdef ENABLE_METALINK namespace { -void showMetalinkFile -(const std::string& uri, const std::shared_ptr