diff --git a/src/AppleMessageDigestImpl.cc b/src/AppleMessageDigestImpl.cc index 3416c257..b3966e32 100644 --- a/src/AppleMessageDigestImpl.cc +++ b/src/AppleMessageDigestImpl.cc @@ -37,6 +37,7 @@ #include #include "array_fun.h" +#include "a2functional.h" #include "HashFuncEntry.h" namespace aria2 { @@ -117,29 +118,31 @@ std::unique_ptr MessageDigestImpl::create (const std::string& hashType) { if (hashType == "sha-1") { - return std::unique_ptr(new MessageDigestSHA1()); + return make_unique(); } if (hashType == "sha-224") { - return std::unique_ptr(new MessageDigestSHA224()); + return make_unique(); } if (hashType == "sha-256") { - return std::unique_ptr(new MessageDigestSHA256()); + return make_unique(); } if (hashType == "sha-384") { - return std::unique_ptr(new MessageDigestSHA384()); + return make_unique(); } if (hashType == "sha-512") { - return std::unique_ptr(new MessageDigestSHA512()); + return make_unique(); } if (hashType == "md5") { - return std::unique_ptr(new MessageDigestMD5()); + return make_unique(); } return nullptr; } bool MessageDigestImpl::supports(const std::string& hashType) { - return hashType == "sha-1" || hashType == "sha-224" || hashType == "sha-256" || hashType == "sha-384" || hashType == "sha-512" || hashType == "md5"; + return hashType == "sha-1" || hashType == "sha-224" || + hashType == "sha-256" || hashType == "sha-384" || + hashType == "sha-512" || hashType == "md5"; } size_t MessageDigestImpl::getDigestLength(const std::string& hashType) diff --git a/src/AppleTLSContext.cc b/src/AppleTLSContext.cc index e4a45768..0c9fe999 100644 --- a/src/AppleTLSContext.cc +++ b/src/AppleTLSContext.cc @@ -58,11 +58,11 @@ namespace { }; #endif // defined(__MAC_10_7) - class cfrelease { + class CFReleaser { const void *ptr_; public: - inline cfrelease(const void *ptr) : ptr_(ptr) {} - inline ~cfrelease() { if (ptr_) CFRelease(ptr_); } + inline CFReleaser(const void *ptr) : ptr_(ptr) {} + inline ~CFReleaser() { if (ptr_) CFRelease(ptr_); } }; static inline bool isWhitespace(char c) @@ -123,13 +123,13 @@ namespace { A2_LOG_ERROR("Failed to get a certref!"); return false; } - cfrelease del_ref(ref); + CFReleaser del_ref(ref); CFDataRef data = SecCertificateCopyData(ref); if (!data) { A2_LOG_ERROR("Failed to get a data!"); return false; } - cfrelease del_data(data); + CFReleaser del_data(data); // Do try all supported hash algorithms. // Usually the fingerprint would be sha1 or md5, however this is more @@ -183,12 +183,12 @@ SecIdentityRef AppleTLSContext::getCredentials() bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint) { - std::string fp = stripWhitespace(fingerprint); + auto fp = stripWhitespace(fingerprint); // Verify this is a valid hex representation and normalize. fp = util::toHex(util::fromHex(fp.begin(), fp.end())); // Verify this can represent a hash - std::vector ht = MessageDigest::getSupportedHashTypes(); + auto ht = MessageDigest::getSupportedHashTypes(); if (std::find_if(ht.begin(), ht.end(), hash_validator(fp)) == ht.end()) { A2_LOG_INFO(fmt("%s is not a fingerprint, invalid hash representation", fingerprint.c_str())); return false; @@ -198,25 +198,25 @@ bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint) A2_LOG_DEBUG(fmt("Looking for cert with fingerprint %s", fp.c_str())); // Build and run the KeyChain the query. - SecPolicyRef policy = SecPolicyCreateSSL(true, nullptr); + auto policy = SecPolicyCreateSSL(true, nullptr); if (!policy) { A2_LOG_ERROR("Failed to create SecPolicy"); return false; } - cfrelease del_policy(policy); + CFReleaser del_policy(policy); const void *query_values[] = { kSecClassIdentity, kCFBooleanTrue, policy, kSecMatchLimitAll }; - CFDictionaryRef query = CFDictionaryCreate(nullptr, query_keys, query_values, - 4, nullptr, nullptr); + auto query = CFDictionaryCreate(nullptr, query_keys, query_values, 4, + nullptr, nullptr); if (!query) { A2_LOG_ERROR("Failed to create identity query"); return false; } - cfrelease del_query(query); + CFReleaser del_query(query); CFArrayRef identities; OSStatus err = SecItemCopyMatching(query, (CFTypeRef*)&identities); if (err != errSecSuccess) { @@ -254,7 +254,7 @@ bool AppleTLSContext::tryAsFingerprint(const std::string& fingerprint) if (err != errSecSuccess) { A2_LOG_ERROR("Certificate search failed: " + errToString(err)); } - cfrelease del_search(search); + CFReleaser del_search(search); SecIdentityRef id; while (SecIdentitySearchCopyNext(search, &id) == errSecSuccess) { diff --git a/src/AppleTLSSession.cc b/src/AppleTLSSession.cc index d34282ec..074d27b0 100644 --- a/src/AppleTLSSession.cc +++ b/src/AppleTLSSession.cc @@ -326,8 +326,8 @@ AppleTLSSession::AppleTLSSession(AppleTLSContext* ctx) state_ = st_error; return; } - for (SSLCipherSuiteList::iterator i = enabled.begin(), e = enabled.end(); i != e; ++i) { - A2_LOG_INFO(fmt("AppleTLS: Enabled suite %s", suiteToString(*i))); + for (const auto& suite: enabled) { + A2_LOG_INFO(fmt("AppleTLS: Enabled suite %s", suiteToString(suite))); } if (SSLSetEnabledCiphers(sslCtx_, &enabled[0], enabled.size()) != noErr) { A2_LOG_ERROR("AppleTLS: Failed to set enabled ciphers list"); @@ -336,37 +336,39 @@ AppleTLSSession::AppleTLSSession(AppleTLSContext* ctx) } #endif - if (ctx->getSide() == TLS_SERVER) { - SecIdentityRef creds = ctx->getCredentials(); - if (!creds) { - A2_LOG_ERROR("AppleTLS: No credentials"); - state_ = st_error; - return; - } - CFArrayRef certs = CFArrayCreate(nullptr, (const void**)&creds, 1, nullptr); - if (!certs) { - A2_LOG_ERROR("AppleTLS: Failed to setup credentials"); - state_ = st_error; - return; - } - std::unique_ptr del_certs((void*)certs, CFRelease); - lastError_ = SSLSetCertificate(sslCtx_, certs); - if (lastError_ != noErr) { - A2_LOG_ERROR(fmt("AppleTLS: Failed to set credentials: %s", getLastErrorString().c_str())); - state_ = st_error; - return; - } + if (ctx->getSide() != TLS_SERVER) { + // Done with client-only initialization + return; + } + + SecIdentityRef creds = ctx->getCredentials(); + if (!creds) { + A2_LOG_ERROR("AppleTLS: No credentials"); + state_ = st_error; + return; + } + CFArrayRef certs = CFArrayCreate(nullptr, (const void**)&creds, 1, nullptr); + if (!certs) { + A2_LOG_ERROR("AppleTLS: Failed to setup credentials"); + state_ = st_error; + return; + } + std::unique_ptr del_certs((void*)certs, CFRelease); + lastError_ = SSLSetCertificate(sslCtx_, certs); + if (lastError_ != noErr) { + A2_LOG_ERROR(fmt("AppleTLS: Failed to set credentials: %s", getLastErrorString().c_str())); + state_ = st_error; + return; + } #ifndef CIPHER_NO_DHPARAM - lastError_ = SSLSetDiffieHellmanParams(sslCtx_, dhparam, sizeof(dhparam)); - if (lastError_ != noErr) { - A2_LOG_WARN(fmt("AppleTLS: Failed to set DHParams: %s", getLastErrorString().c_str())); - // Engine will still generate some for us, so this is no problem, except - // it will take longer. - } -#endif // CIPHER_NO_DHPARAM - + lastError_ = SSLSetDiffieHellmanParams(sslCtx_, dhparam, sizeof(dhparam)); + if (lastError_ != noErr) { + A2_LOG_WARN(fmt("AppleTLS: Failed to set DHParams: %s", getLastErrorString().c_str())); + // Engine will still generate some for us, so this is no problem, except + // it will take longer. } +#endif // CIPHER_NO_DHPARAM } AppleTLSSession::~AppleTLSSession() diff --git a/src/DownloadEngine.cc b/src/DownloadEngine.cc index 04c44d24..efa86950 100644 --- a/src/DownloadEngine.cc +++ b/src/DownloadEngine.cc @@ -124,27 +124,28 @@ void executeCommand(std::deque>& commands, for(size_t i = 0; i < max; ++i) { auto com = std::move(commands.front()); commands.pop_front(); - if(com->statusMatch(statusFilter)) { - com->transitStatus(); - if(com->execute()) { - com.reset(); - } else { - com->clearIOEvents(); - com.release(); - } - } else { + if (!com->statusMatch(statusFilter)) { com->clearIOEvents(); commands.push_back(std::move(com)); + continue; + } + com->transitStatus(); + if (com->execute()) { + com.reset(); + } + else { + com->clearIOEvents(); + com.release(); } } } } // namespace namespace { -class GHR { +class GlobalHaltRequestedFinalizer { public: - GHR() {} - ~GHR() + GlobalHaltRequestedFinalizer() {} + ~GlobalHaltRequestedFinalizer() { global::globalHaltRequested = 5; } @@ -153,7 +154,7 @@ public: int DownloadEngine::run(bool oneshot) { - GHR ghr; + GlobalHaltRequestedFinalizer ghrf; while(!commands_.empty() || !routineCommands_.empty()) { if(!commands_.empty()) { waitData(); @@ -243,12 +244,16 @@ void DownloadEngine::afterEachIteration() global::globalHaltRequested = 2; setNoWait(true); setRefreshInterval(0); - } else if(global::globalHaltRequested == 3) { + return; + } + + if(global::globalHaltRequested == 3) { A2_LOG_NOTICE(_("Emergency shutdown sequence commencing...")); requestForceHalt(); global::globalHaltRequested = 4; setNoWait(true); setRefreshInterval(0); + return; } } @@ -300,20 +305,21 @@ void DownloadEngine::poolSocket(const std::string& key, std::multimap::value_type p(key, entry); socketPool_.insert(p); - if(lastSocketPoolScan_.difference(global::wallclock()) >= 60) { - std::multimap newPool; - A2_LOG_DEBUG("Scaning SocketPool and erasing timed out entry."); - lastSocketPoolScan_ = global::wallclock(); - for(auto & elem : socketPool_) { - if(!elem.second.isTimeout()) { - newPool.insert(elem); - } - } - A2_LOG_DEBUG(fmt("%lu entries removed.", - static_cast - (socketPool_.size()-newPool.size()))); - socketPool_ = newPool; + if(lastSocketPoolScan_.difference(global::wallclock()) < 60) { + return; } + std::multimap newPool; + A2_LOG_DEBUG("Scaning SocketPool and erasing timed out entry."); + lastSocketPoolScan_ = global::wallclock(); + for(auto & elem : socketPool_) { + if(!elem.second.isTimeout()) { + newPool.insert(elem); + } + } + A2_LOG_DEBUG(fmt("%lu entries removed.", + static_cast + (socketPool_.size()-newPool.size()))); + socketPool_ = newPool; } namespace { @@ -382,17 +388,18 @@ void DownloadEngine::poolSocket(const std::shared_ptr& request, const std::shared_ptr& socket, time_t timeout) { - if(!proxyRequest) { - std::pair peerInfo; - if(getPeerInfo(peerInfo, socket)) { - poolSocket(peerInfo.first, peerInfo.second, - A2STR::NIL, 0, socket, timeout); - } - } else { + if(proxyRequest) { // If proxy is defined, then pool socket with its hostname. poolSocket(request->getHost(), request->getPort(), proxyRequest->getHost(), proxyRequest->getPort(), socket, timeout); + return; + } + + std::pair peerInfo; + if(getPeerInfo(peerInfo, socket)) { + poolSocket(peerInfo.first, peerInfo.second, + A2STR::NIL, 0, socket, timeout); } } @@ -404,17 +411,18 @@ void DownloadEngine::poolSocket const std::string& options, time_t timeout) { - if(!proxyRequest) { - std::pair peerInfo; - if(getPeerInfo(peerInfo, socket)) { - poolSocket(peerInfo.first, peerInfo.second, username, - A2STR::NIL, 0, socket, options, timeout); - } - } else { + if(proxyRequest) { // If proxy is defined, then pool socket with its hostname. poolSocket(request->getHost(), request->getPort(), username, proxyRequest->getHost(), proxyRequest->getPort(), socket, options, timeout); + return; + } + + std::pair peerInfo; + if(getPeerInfo(peerInfo, socket)) { + poolSocket(peerInfo.first, peerInfo.second, username, + A2STR::NIL, 0, socket, options, timeout); } } diff --git a/src/DownloadEngineFactory.cc b/src/DownloadEngineFactory.cc index 2cfef18a..1dd6aaa3 100644 --- a/src/DownloadEngineFactory.cc +++ b/src/DownloadEngineFactory.cc @@ -91,58 +91,54 @@ std::unique_ptr createEventPoll(Option* op) #ifdef HAVE_LIBUV if (pollMethod == V_LIBUV) { auto ep = make_unique(); - if(ep->good()) { - return std::move(ep); - } else { + if(!ep->good()) { throw DL_ABORT_EX("Initializing LibuvEventPoll failed." " Try --event-poll=select"); } + return std::move(ep); } else #endif // HAVE_LIBUV #ifdef HAVE_EPOLL if(pollMethod == V_EPOLL) { auto ep = make_unique(); - if(ep->good()) { - return std::move(ep); - } else { + if(!ep->good()) { throw DL_ABORT_EX("Initializing EpollEventPoll failed." " Try --event-poll=select"); } + return std::move(ep); } else #endif // HAVE_EPLL #ifdef HAVE_KQUEUE - if(pollMethod == V_KQUEUE) { - auto kp = make_unique(); - if(kp->good()) { - return std::move(kp); - } else { - throw DL_ABORT_EX("Initializing KqueueEventPoll failed." - " Try --event-poll=select"); - } - } else + if(pollMethod == V_KQUEUE) { + auto kp = make_unique(); + if(!kp->good()) { + throw DL_ABORT_EX("Initializing KqueueEventPoll failed." + " Try --event-poll=select"); + } + return std::move(kp); + } else #endif // HAVE_KQUEUE #ifdef HAVE_PORT_ASSOCIATE - if(pollMethod == V_PORT) { - auto pp = make_unique(); - if(pp->good()) { - return std::move(pp); - } else { - throw DL_ABORT_EX("Initializing PortEventPoll failed." - " Try --event-poll=select"); - } - } else + if(pollMethod == V_PORT) { + auto pp = make_unique(); + if(!pp->good()) { + throw DL_ABORT_EX("Initializing PortEventPoll failed." + " Try --event-poll=select"); + } + return std::move(pp); + } else #endif // HAVE_PORT_ASSOCIATE #ifdef HAVE_POLL - if(pollMethod == V_POLL) { - return make_unique(); - } else + if(pollMethod == V_POLL) { + return make_unique(); + } else #endif // HAVE_POLL - if(pollMethod == V_SELECT) { - return make_unique(); - } else { - assert(0); - } + if(pollMethod == V_SELECT) { + return make_unique(); + } + assert(0); + return nullptr; } } // namespace diff --git a/src/LibuvEventPoll.cc b/src/LibuvEventPoll.cc index 07d60a1e..791d8521 100644 --- a/src/LibuvEventPoll.cc +++ b/src/LibuvEventPoll.cc @@ -107,8 +107,8 @@ LibuvEventPoll::LibuvEventPoll() LibuvEventPoll::~LibuvEventPoll() { - for (KPolls::iterator i = polls_.begin(), e = polls_.end(); i != e; ++i) { - i->second->close(); + for (auto& p: polls_) { + p.second->close(); } // Actually kill the polls, and timers, if any. uv_run(loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT)); @@ -256,8 +256,8 @@ bool LibuvEventPoll::addEvents(sock_t socket, Command* command, int events, bool LibuvEventPoll::deleteEvents(sock_t socket, const LibuvEventPoll::KEvent& event) { - std::shared_ptr socketEntry(new KSocketEntry(socket)); - KSocketEntrySet::iterator i = socketEntries_.find(socketEntry); + auto socketEntry = std::make_shared(socket); + auto i = socketEntries_.find(socketEntry); if (i == socketEntries_.end()) { A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); @@ -266,7 +266,7 @@ bool LibuvEventPoll::deleteEvents(sock_t socket, event.removeSelf(*i); - KPolls::iterator poll = polls_.find(socket); + auto poll = polls_.find(socket); if (poll == polls_.end()) { return false; } diff --git a/src/LibuvEventPoll.h b/src/LibuvEventPoll.h index a6974d1b..b56b9afb 100644 --- a/src/LibuvEventPoll.h +++ b/src/LibuvEventPoll.h @@ -76,7 +76,7 @@ private: uv_poll_t handle_; static void poll_callback(uv_poll_t* handle, int status, int events) { - KPoll* poll = static_cast(handle->data); + auto poll = static_cast(handle->data); poll->eventer_->pollCallback(poll, status, events); } static void close_callback(uv_handle_t* handle) { @@ -87,8 +87,8 @@ private: inline KPoll(LibuvEventPoll* eventer, KSocketEntry* entry, sock_t sock) : eventer_(eventer), entry_(entry) { - uv_poll_init_socket(eventer->loop_, &handle_, sock); - handle_.data = this; + uv_poll_init_socket(eventer->loop_, &handle_, sock); + handle_.data = this; } inline void start() { uv_poll_start(&handle_, entry_->getEvents() & IEV_RW, poll_callback); diff --git a/src/MultiUrlRequestInfo.cc b/src/MultiUrlRequestInfo.cc index 8f54c4e3..8347e331 100644 --- a/src/MultiUrlRequestInfo.cc +++ b/src/MultiUrlRequestInfo.cc @@ -134,14 +134,12 @@ std::unique_ptr getStatCalc(const std::shared_ptr