diff --git a/daemon/connect/Connection.cpp b/daemon/connect/Connection.cpp index 68c682d7..29d43bb4 100644 --- a/daemon/connect/Connection.cpp +++ b/daemon/connect/Connection.cpp @@ -111,16 +111,16 @@ void Connection::Init() #ifdef WIN32 WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 0), &wsaData); - if (err != 0) + if (err != 0) { error("Could not initialize socket library"); return; } - if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE( wsaData.wVersion ) != 0) + if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE( wsaData.wVersion ) != 0) { error("Could not initialize socket library"); WSACleanup(); - return; + return; } #endif @@ -286,21 +286,21 @@ bool Connection::Bind() #ifdef HAVE_GETADDRINFO struct addrinfo addr_hints, *addr_list, *addr; char portStr[sizeof(int) * 4 + 1]; // is enough to hold any converted int - + memset(&addr_hints, 0, sizeof(addr_hints)); addr_hints.ai_family = AF_UNSPEC; // Allow IPv4 or IPv6 addr_hints.ai_socktype = SOCK_STREAM, addr_hints.ai_flags = AI_PASSIVE; // For wildcard IP address - + sprintf(portStr, "%d", m_port); - + int res = getaddrinfo(m_host, portStr, &addr_hints, &addr_list); if (res != 0) { ReportError("Could not resolve hostname %s", m_host, false, 0); return false; } - + m_broken = false; m_socket = INVALID_SOCKET; for (addr = addr_list; addr != NULL; addr = addr->ai_next) @@ -324,11 +324,11 @@ bool Connection::Bind() m_socket = INVALID_SOCKET; } } - + freeaddrinfo(addr_list); - + #else - + struct sockaddr_in sSocketAddress; memset(&sSocketAddress, 0, sizeof(sSocketAddress)); sSocketAddress.sin_family = AF_INET; @@ -345,17 +345,17 @@ bool Connection::Bind() } } sSocketAddress.sin_port = htons(m_port); - + m_socket = socket(PF_INET, SOCK_STREAM, 0); if (m_socket == INVALID_SOCKET) { ReportError("Socket creation failed for %s", m_host, true, 0); return false; } - + int opt = 1; setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(opt)); - + int res = bind(m_socket, (struct sockaddr *) &sSocketAddress, sizeof(sSocketAddress)); if (res == -1) { @@ -364,19 +364,19 @@ bool Connection::Bind() m_socket = INVALID_SOCKET; } #endif - + if (m_socket == INVALID_SOCKET) { ReportError("Binding socket failed for %s", m_host, true, 0); return false; } - + if (listen(m_socket, 100) < 0) { ReportError("Listen on socket failed for %s", m_host, true, 0); return false; } - + m_status = csListening; return true; @@ -454,7 +454,7 @@ char* Connection::ReadLine(char* buffer, int size, int* bytesReadOut) bufPtr = m_readBuf; m_readBuf[bufAvail] = '\0'; } - + int len = 0; char* p = (char*)memchr(bufPtr, '\n', bufAvail); if (p) @@ -465,29 +465,29 @@ char* Connection::ReadLine(char* buffer, int size, int* bytesReadOut) { len = bufAvail; } - + if (len > size) { len = size; } - + memcpy(inpBuffer, bufPtr, len); inpBuffer += len; bufPtr += len; bufAvail -= len; bytesRead += len; size -= len; - + if (p) { break; } } *inpBuffer = '\0'; - + m_bufAvail = bufAvail > 0 ? bufAvail : 0; // copy back to member m_bufPtr = bufPtr; // copy back to member - + if (bytesReadOut) { *bytesReadOut = bytesRead; @@ -499,7 +499,7 @@ char* Connection::ReadLine(char* buffer, int size, int* bytesReadOut) { return NULL; } - + return buffer; } @@ -521,7 +521,7 @@ Connection* Connection::Accept() { return NULL; } - + Connection* con = new Connection(socket, m_tls); return con; @@ -584,7 +584,7 @@ bool Connection::DoConnect() m_socket = INVALID_SOCKET; m_broken = false; - + #ifdef HAVE_GETADDRINFO struct addrinfo addr_hints, *addr_list, *addr; char portStr[sizeof(int) * 4 + 1]; //is enough to hold any converted int @@ -650,7 +650,7 @@ bool Connection::DoConnect() if (m_socket == INVALID_SOCKET) { return false; - } + } #else @@ -972,7 +972,7 @@ void Connection::CloseTls() int Connection::recv(SOCKET s, char* buf, int len, int flags) { int received = 0; - + if (m_tlsSocket) { m_tlsError = false; @@ -1028,17 +1028,17 @@ unsigned int Connection::ResolveHostAddr(const char* host) #ifdef HAVE_GETHOSTBYNAME_R_6 err = gethostbyname_r(host, &hinfobuf, strbuf, sizeof(strbuf), &hinfo, &h_errnop); err = err || (hinfo == NULL); // error on null hinfo (means 'no entry') -#endif +#endif #ifdef HAVE_GETHOSTBYNAME_R_5 hinfo = gethostbyname_r(host, &hinfobuf, strbuf, sizeof(strbuf), &h_errnop); err = hinfo == NULL; -#endif +#endif #ifdef HAVE_GETHOSTBYNAME_R_3 //NOTE: gethostbyname_r with three parameters were not tested struct hostent_data hinfo_data; hinfo = gethostbyname_r((char*)host, (struct hostent*)hinfobuf, &hinfo_data); err = hinfo == NULL; -#endif +#endif #else m_mutexGetHostByName->Lock(); hinfo = gethostbyname(host); @@ -1054,7 +1054,7 @@ unsigned int Connection::ResolveHostAddr(const char* host) } memcpy(&uaddr, hinfo->h_addr_list[0], sizeof(uaddr)); - + #ifndef HAVE_GETHOSTBYNAME_R m_mutexGetHostByName->Unlock(); #endif @@ -1076,7 +1076,7 @@ const char* Connection::GetRemoteAddr() #endif } m_remoteAddr[sizeof(m_remoteAddr)-1] = '\0'; - + return m_remoteAddr; } @@ -1085,4 +1085,4 @@ int Connection::FetchTotalBytesRead() int total = m_totalBytesRead; m_totalBytesRead = 0; return total; -} \ No newline at end of file +} diff --git a/daemon/connect/TlsSocket.cpp b/daemon/connect/TlsSocket.cpp index f821e907..ca410d13 100644 --- a/daemon/connect/TlsSocket.cpp +++ b/daemon/connect/TlsSocket.cpp @@ -219,7 +219,7 @@ void TlsSocket::Init() { g_OpenSSLMutexes[i] = new Mutex(); } - + SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); @@ -229,7 +229,7 @@ void TlsSocket::Init() CRYPTO_set_dynlock_create_callback(openssl_dynlock_create); CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy); CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock); - + #endif /* HAVE_OPENSSL */ } @@ -309,7 +309,7 @@ void TlsSocket::ReportError(const char* errMsg) char errstr[1024]; ERR_error_string_n(errcode, errstr, sizeof(errstr)); errstr[1024-1] = '\0'; - + if (m_suppressErrors) { debug("%s: %s", errMsg, errstr); @@ -381,7 +381,7 @@ bool TlsSocket::Start() return false; } - m_retCode = gnutls_credentials_set((gnutls_session_t)m_session, GNUTLS_CRD_CERTIFICATE, + m_retCode = gnutls_credentials_set((gnutls_session_t)m_session, GNUTLS_CRD_CERTIFICATE, (gnutls_certificate_credentials_t*)m_context); if (m_retCode != 0) { @@ -428,7 +428,7 @@ bool TlsSocket::Start() return false; } } - + m_session = SSL_new((SSL_CTX*)m_context); if (!m_session) { diff --git a/daemon/connect/WebDownloader.cpp b/daemon/connect/WebDownloader.cpp index a7d2e59d..dfe46d7c 100644 --- a/daemon/connect/WebDownloader.cpp +++ b/daemon/connect/WebDownloader.cpp @@ -125,7 +125,7 @@ void WebDownloader::Run() { detail("Waiting %i sec to retry", g_Options->GetRetryInterval()); int msec = 0; - while (!IsStopped() && (msec < g_Options->GetRetryInterval() * 1000) && + while (!IsStopped() && (msec < g_Options->GetRetryInterval() * 1000) && !(!m_force && g_Options->GetPauseDownload())) { usleep(100 * 1000); @@ -518,7 +518,7 @@ WebDownloader::EStatus WebDownloader::CheckResponse(const char* response) // OK return adRunning; } - else + else { // unknown error, no special handling warn("URL %s failed: %s", m_infoName, response); @@ -747,7 +747,7 @@ bool WebDownloader::Terminate() void WebDownloader::FreeConnection() { - if (m_connection) + if (m_connection) { debug("Releasing connection"); m_connectionMutex.Lock(); diff --git a/daemon/connect/WebDownloader.h b/daemon/connect/WebDownloader.h index ece4d694..19e367a9 100644 --- a/daemon/connect/WebDownloader.h +++ b/daemon/connect/WebDownloader.h @@ -48,7 +48,7 @@ public: adConnectError, adFatalError }; - + private: char* m_url; char* m_outputFilename; @@ -80,7 +80,7 @@ private: void SendHeaders(URL *url); EStatus DownloadHeaders(); EStatus DownloadBody(); - void ParseRedirect(const char* location); + void ParseRedirect(const char* location); protected: virtual void ProcessHeader(const char* line); diff --git a/daemon/extension/NzbScript.cpp b/daemon/extension/NzbScript.cpp index 45e43686..fb189c91 100644 --- a/daemon/extension/NzbScript.cpp +++ b/daemon/extension/NzbScript.cpp @@ -47,7 +47,7 @@ #include "Log.h" #include "Util.h" - + /** * If szStripPrefix is not NULL, only pp-parameters, whose names start with the prefix * are processed. The prefix is then stripped from the names. @@ -61,7 +61,7 @@ void NzbScriptController::PrepareEnvParameters(NzbParameterList* parameters, con { NzbParameter* parameter = *it; const char* value = parameter->GetValue(); - + #ifdef WIN32 char* ansiValue = strdup(value); WebUtil::Utf8ToAnsi(ansiValue, strlen(ansiValue) + 1); diff --git a/daemon/extension/PostScript.cpp b/daemon/extension/PostScript.cpp index c5535dd6..a66c4e43 100644 --- a/daemon/extension/PostScript.cpp +++ b/daemon/extension/PostScript.cpp @@ -129,7 +129,7 @@ void PostScriptController::ExecuteScript(ScriptConfig::Script* script) SetLogPrefix(NULL); ScriptStatus::EStatus status = AnalyseExitCode(exitCode); - + // the locking is needed for accessing the members of NZBInfo DownloadQueue::Lock(); m_postInfo->GetNzbInfo()->GetScriptStatuses()->Add(script->GetName(), status); @@ -168,7 +168,7 @@ void PostScriptController::PrepareParams(const char* scriptName) if (detail) *detail = '\0'; SetEnvVar("NZBPP_TOTALSTATUS", status); - const char* scriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; + const char* scriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; SetEnvVar("NZBPP_SCRIPTSTATUS", scriptStatusName[m_postInfo->GetNzbInfo()->GetScriptStatuses()->CalcTotalStatus()]); // deprecated @@ -210,7 +210,7 @@ void PostScriptController::PrepareParams(const char* scriptName) } PrepareEnvScript(m_postInfo->GetNzbInfo()->GetParameters(), scriptName); - + DownloadQueue::Unlock(); } diff --git a/daemon/extension/QueueScript.cpp b/daemon/extension/QueueScript.cpp index e1ed627e..21a14fbb 100644 --- a/daemon/extension/QueueScript.cpp +++ b/daemon/extension/QueueScript.cpp @@ -184,7 +184,7 @@ void QueueScriptController::PrepareParams(const char* scriptName) SetEnvVar("NZBNA_EVENT", QUEUE_EVENT_NAMES[m_event]); - const char* deleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; + const char* deleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; SetEnvVar("NZBNA_DELETESTATUS", deleteStatusName[m_deleteStatus]); const char* urlStatusName[] = { "NONE", "UNKNOWN", "SUCCESS", "FAILURE", "UNKNOWN", "SCAN_SKIPPED", "SCAN_FAILURE" }; diff --git a/daemon/extension/QueueScript.h b/daemon/extension/QueueScript.h index 3a468812..8b349eb9 100644 --- a/daemon/extension/QueueScript.h +++ b/daemon/extension/QueueScript.h @@ -58,7 +58,7 @@ private: }; typedef std::list Queue; - + Queue m_queue; Mutex m_queueMutex; QueueItem* m_curItem; diff --git a/daemon/extension/ScriptConfig.cpp b/daemon/extension/ScriptConfig.cpp index 8966f35c..8b807b3a 100644 --- a/daemon/extension/ScriptConfig.cpp +++ b/daemon/extension/ScriptConfig.cpp @@ -24,7 +24,7 @@ #ifdef HAVE_CONFIG_H -#include "config.h" +#include "config.h" #endif #ifdef WIN32 @@ -219,8 +219,8 @@ bool ScriptConfig::SaveConfig(Options::OptEntries* optEntries) // write config file back to disk, replace old values of existing options with new values rewind(infile); for (std::vector::iterator it = config.begin(); it != config.end(); it++) - { - char* buf = *it; + { + char* buf = *it; const char* eq = strchr(buf, '='); if (eq && buf[0] != '#') @@ -348,7 +348,7 @@ bool ScriptConfig::LoadConfigTemplates(ConfigTemplates* configTemplates) configTemplates->push_back(configTemplate); } - // clearing the list without deleting of objects, which are in pConfigTemplates now + // clearing the list without deleting of objects, which are in pConfigTemplates now scriptList.clear(); return true; diff --git a/daemon/extension/ScriptConfig.h b/daemon/extension/ScriptConfig.h index 862ac2fc..a8585b17 100644 --- a/daemon/extension/ScriptConfig.h +++ b/daemon/extension/ScriptConfig.h @@ -76,7 +76,7 @@ public: public: ~Scripts(); void Clear(); - Script* Find(const char* name); + Script* Find(const char* name); }; class ConfigTemplate @@ -93,7 +93,7 @@ public: Script* GetScript() { return m_script; } const char* GetTemplate() { return m_template; } }; - + typedef std::vector ConfigTemplatesBase; class ConfigTemplates: public ConfigTemplatesBase diff --git a/daemon/feed/FeedCoordinator.cpp b/daemon/feed/FeedCoordinator.cpp index bba4feb0..d658bfa1 100644 --- a/daemon/feed/FeedCoordinator.cpp +++ b/daemon/feed/FeedCoordinator.cpp @@ -139,7 +139,7 @@ FeedCoordinator::~FeedCoordinator() delete *it; } m_feeds.clear(); - + debug("Deleting FeedCache"); for (FeedCache::iterator it = m_feedCache.begin(); it != m_feedCache.end(); it++) { @@ -293,7 +293,7 @@ void FeedCoordinator::ResetHangingDownloads() continue; } it++; - } + } m_downloadsMutex.Unlock(); } @@ -443,8 +443,8 @@ void FeedCoordinator::FilterFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInfo } for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) - { - FeedItemInfo* feedItemInfo = *it; + { + FeedItemInfo* feedItemInfo = *it; feedItemInfo->SetMatchStatus(FeedItemInfo::msAccepted); feedItemInfo->SetMatchRule(0); feedItemInfo->SetPauseNzb(feedInfo->GetPauseNzb()); @@ -458,7 +458,7 @@ void FeedCoordinator::FilterFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInfo { feedFilter->Match(feedItemInfo); } - } + } delete feedFilter; } @@ -472,9 +472,9 @@ void FeedCoordinator::ProcessFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInf bool firstFetch = feedInfo->GetLastUpdate() == 0; int added = 0; - for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) - { - FeedItemInfo* feedItemInfo = *it; + for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) + { + FeedItemInfo* feedItemInfo = *it; if (feedItemInfo->GetMatchStatus() == FeedItemInfo::msAccepted) { FeedHistoryInfo* feedHistoryInfo = m_feedHistory.Find(feedItemInfo->GetUrl()); @@ -500,7 +500,7 @@ void FeedCoordinator::ProcessFeed(FeedInfo* feedInfo, FeedItemInfos* feedItemInf m_feedHistory.Add(feedItemInfo->GetUrl(), status, time(NULL)); } } - } + } if (added) { @@ -557,7 +557,7 @@ bool FeedCoordinator::ViewFeed(int id, FeedItemInfos** ppFeedItemInfos) FeedInfo* feedInfo = m_feeds.at(id - 1); - return PreviewFeed(feedInfo->GetId(), feedInfo->GetName(), feedInfo->GetUrl(), feedInfo->GetFilter(), + return PreviewFeed(feedInfo->GetId(), feedInfo->GetName(), feedInfo->GetUrl(), feedInfo->GetFilter(), feedInfo->GetBacklog(), feedInfo->GetPauseNzb(), feedInfo->GetCategory(), feedInfo->GetPriority(), feedInfo->GetInterval(), feedInfo->GetFeedScript(), 0, NULL, ppFeedItemInfos); } @@ -571,7 +571,7 @@ bool FeedCoordinator::PreviewFeed(int id, const char* name, const char* url, con FeedInfo* feedInfo = new FeedInfo(id, name, url, backlog, interval, filter, pauseNzb, category, priority, feedScript); feedInfo->SetPreview(true); - + FeedItemInfos* feedItemInfos = NULL; bool hasCache = false; if (cacheTimeSec > 0 && *cacheId != '\0') @@ -664,7 +664,7 @@ bool FeedCoordinator::PreviewFeed(int id, const char* name, const char* url, con m_feedCache.push_back(feedCacheItem); m_downloadsMutex.Unlock(); } - + *ppFeedItemInfos = feedItemInfos; return true; @@ -775,9 +775,9 @@ void FeedCoordinator::CleanupHistory() void FeedCoordinator::CleanupCache() { debug("CleanupCache"); - + m_downloadsMutex.Lock(); - + time_t curTime = time(NULL); int i = 0; for (FeedCache::iterator it = m_feedCache.begin(); it != m_feedCache.end(); ) @@ -797,6 +797,6 @@ void FeedCoordinator::CleanupCache() i++; } } - + m_downloadsMutex.Unlock(); } diff --git a/daemon/feed/FeedCoordinator.h b/daemon/feed/FeedCoordinator.h index 9b2f99e2..a37f94a0 100644 --- a/daemon/feed/FeedCoordinator.h +++ b/daemon/feed/FeedCoordinator.h @@ -112,7 +112,7 @@ protected: virtual void LogDebugInfo(); public: - FeedCoordinator(); + FeedCoordinator(); virtual ~FeedCoordinator(); virtual void Run(); virtual void Stop(); diff --git a/daemon/feed/FeedFile.cpp b/daemon/feed/FeedFile.cpp index 35370179..0b77c2b1 100644 --- a/daemon/feed/FeedFile.cpp +++ b/daemon/feed/FeedFile.cpp @@ -35,7 +35,7 @@ #include #ifdef WIN32 #include -#import named_guids +#import named_guids using namespace MSXML; #else #include @@ -53,9 +53,9 @@ using namespace MSXML; FeedFile::FeedFile(const char* fileName) { - debug("Creating FeedFile"); + debug("Creating FeedFile"); - m_fileName = strdup(fileName); + m_fileName = strdup(fileName); m_feedItemInfos = new FeedItemInfos(); m_feedItemInfos->Retain(); @@ -82,7 +82,7 @@ FeedFile::~FeedFile() void FeedFile::LogDebugInfo() { - info(" FeedFile %s", m_fileName); + info(" FeedFile %s", m_fileName); } void FeedFile::AddItem(FeedItemInfo* feedItemInfo) @@ -92,7 +92,7 @@ void FeedFile::AddItem(FeedItemInfo* feedItemInfo) void FeedFile::ParseSubject(FeedItemInfo* feedItemInfo) { - // if title has quatation marks we use only part within quatation marks + // if title has quatation marks we use only part within quatation marks char* p = (char*)feedItemInfo->GetTitle(); char* start = strchr(p, '\"'); if (start) @@ -128,18 +128,18 @@ void FeedFile::ParseSubject(FeedItemInfo* feedItemInfo) #ifdef WIN32 FeedFile* FeedFile::Create(const char* fileName) { - CoInitialize(NULL); + CoInitialize(NULL); HRESULT hr; MSXML::IXMLDOMDocumentPtr doc; hr = doc.CreateInstance(MSXML::CLSID_DOMDocument); - if (FAILED(hr)) - { - return NULL; - } + if (FAILED(hr)) + { + return NULL; + } - // Load the XML document file... + // Load the XML document file... doc->put_resolveExternals(VARIANT_FALSE); doc->put_validateOnParse(VARIANT_FALSE); doc->put_async(VARIANT_FALSE); @@ -160,14 +160,14 @@ FeedFile* FeedFile::Create(const char* fileName) return NULL; } - FeedFile* file = new FeedFile(fileName); - if (!file->ParseFeed(doc)) + FeedFile* file = new FeedFile(fileName); + if (!file->ParseFeed(doc)) { delete file; file = NULL; } - return file; + return file; } void FeedFile::EncodeUrl(const char* filename, char* url) @@ -207,8 +207,8 @@ bool FeedFile::ParseFeed(IUnknown* nzb) MSXML::IXMLDOMNodePtr tag; MSXML::IXMLDOMNodePtr attr; - - // Debian 6 + + // Debian 6 tag = node->selectSingleNode("title"); if (!tag) { @@ -378,7 +378,7 @@ bool FeedFile::ParseFeed(IUnknown* nzb) FeedFile* FeedFile::Create(const char* fileName) { - FeedFile* file = new FeedFile(fileName); + FeedFile* file = new FeedFile(fileName); xmlSAXHandler SAX_handler = {0}; SAX_handler.startElement = reinterpret_cast(SAX_StartElement); @@ -390,21 +390,21 @@ FeedFile* FeedFile::Create(const char* fileName) file->m_ignoreNextError = false; int ret = xmlSAXUserParseFile(&SAX_handler, file, fileName); - - if (ret != 0) + + if (ret != 0) { - error("Failed to parse rss feed"); + error("Failed to parse rss feed"); delete file; file = NULL; } - + return file; } void FeedFile::Parse_StartElement(const char *name, const char **atts) { ResetTagContent(); - + if (!strcmp("item", name)) { delete m_feedItemInfo; @@ -546,7 +546,7 @@ void FeedFile::SAX_EndElement(FeedFile* file, const char *name) void FeedFile::SAX_characters(FeedFile* file, const char * xmlstr, int len) { char* str = (char*)xmlstr; - + // trim starting blanks int off = 0; for (int i = 0; i < len; i++) @@ -561,9 +561,9 @@ void FeedFile::SAX_characters(FeedFile* file, const char * xmlstr, int len) break; } } - + int newlen = len - off; - + // trim ending blanks for (int i = len - 1; i >= off; i--) { @@ -577,7 +577,7 @@ void FeedFile::SAX_characters(FeedFile* file, const char * xmlstr, int len) break; } } - + if (newlen > 0) { // interpret tag content @@ -604,16 +604,16 @@ void FeedFile::SAX_error(FeedFile* file, const char *msg, ...) file->m_ignoreNextError = false; return; } - - va_list argp; - va_start(argp, msg); - char errMsg[1024]; - vsnprintf(errMsg, sizeof(errMsg), msg, argp); - errMsg[1024-1] = '\0'; - va_end(argp); + + va_list argp; + va_start(argp, msg); + char errMsg[1024]; + vsnprintf(errMsg, sizeof(errMsg), msg, argp); + errMsg[1024-1] = '\0'; + va_end(argp); // remove trailing CRLF for (char* pend = errMsg + strlen(errMsg) - 1; pend >= errMsg && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; - error("Error parsing rss feed: %s", errMsg); + error("Error parsing rss feed: %s", errMsg); } #endif diff --git a/daemon/feed/FeedFile.h b/daemon/feed/FeedFile.h index 558f0999..def00134 100644 --- a/daemon/feed/FeedFile.h +++ b/daemon/feed/FeedFile.h @@ -40,7 +40,7 @@ private: void AddItem(FeedItemInfo* feedItemInfo); void ParseSubject(FeedItemInfo* feedItemInfo); #ifdef WIN32 - bool ParseFeed(IUnknown* nzb); + bool ParseFeed(IUnknown* nzb); static void EncodeUrl(const char* filename, char* url); #else FeedItemInfo* m_feedItemInfo; diff --git a/daemon/feed/FeedFilter.cpp b/daemon/feed/FeedFilter.cpp index f6079c3f..faeba007 100644 --- a/daemon/feed/FeedFilter.cpp +++ b/daemon/feed/FeedFilter.cpp @@ -519,14 +519,14 @@ bool FeedFilter::Term::ParseNumericParam(const char* param) m_fFloatParam = atof(param); m_intParam = (long long)m_fFloatParam; m_float = strchr(param, '.'); - + const char* p; for (p = param; *p && ((*p >= '0' && *p <='9') || *p == '.' || *p == '-') ; p++) ; if (*p) { return false; } - + return true; } diff --git a/daemon/feed/FeedFilter.h b/daemon/feed/FeedFilter.h index 4c54caff..96d2fdf8 100644 --- a/daemon/feed/FeedFilter.h +++ b/daemon/feed/FeedFilter.h @@ -48,7 +48,7 @@ private: fcClosingBrace, fcOrOperator }; - + class Term { private: diff --git a/daemon/feed/FeedInfo.cpp b/daemon/feed/FeedInfo.cpp index 43094a44..a193f0b2 100644 --- a/daemon/feed/FeedInfo.cpp +++ b/daemon/feed/FeedInfo.cpp @@ -405,18 +405,18 @@ FeedHistoryInfo* FeedHistory::Find(const char* url) FeedItemInfos::FeedItemInfos() { debug("Creating FeedItemInfos"); - + m_refCount = 0; } FeedItemInfos::~FeedItemInfos() { debug("Destroing FeedItemInfos"); - + for (iterator it = begin(); it != end(); it++) - { - delete *it; - } + { + delete *it; + } } void FeedItemInfos::Retain() diff --git a/daemon/feed/FeedInfo.h b/daemon/feed/FeedInfo.h index dd222519..51e0eebc 100644 --- a/daemon/feed/FeedInfo.h +++ b/daemon/feed/FeedInfo.h @@ -132,7 +132,7 @@ public: const char* GetName() { return m_name; } const char* GetValue() { return m_value; } }; - + typedef std::deque AttributesBase; class Attributes: public AttributesBase diff --git a/daemon/frontend/ColoredFrontend.cpp b/daemon/frontend/ColoredFrontend.cpp index 81c6fe4a..69b91088 100644 --- a/daemon/frontend/ColoredFrontend.cpp +++ b/daemon/frontend/ColoredFrontend.cpp @@ -95,15 +95,15 @@ void ColoredFrontend::PrintStatus() downloadLimit[0] = 0; } - char postStatus[128]; - if (m_postJobCount > 0) - { - sprintf(postStatus, ", %i post-job%s", m_postJobCount, m_postJobCount > 1 ? "s" : ""); - } - else - { - postStatus[0] = 0; - } + char postStatus[128]; + if (m_postJobCount > 0) + { + sprintf(postStatus, ", %i post-job%s", m_postJobCount, m_postJobCount > 1 ? "s" : ""); + } + else + { + postStatus[0] = 0; + } #ifdef WIN32 char* controlSeq = ""; @@ -122,7 +122,7 @@ void ColoredFrontend::PrintStatus() tmp[1024-1] = '\0'; printf("%s", tmp); m_needGoBack = true; -} +} void ColoredFrontend::PrintMessage(Message * message) { @@ -136,7 +136,7 @@ void ColoredFrontend::PrintMessage(Message * message) case Message::mkError: SetConsoleTextAttribute(m_console, 4); printf("[ERROR]"); - break; + break; case Message::mkWarning: SetConsoleTextAttribute(m_console, 5); printf("[WARNING]"); diff --git a/daemon/frontend/Frontend.cpp b/daemon/frontend/Frontend.cpp index 980557cc..9dcce125 100644 --- a/daemon/frontend/Frontend.cpp +++ b/daemon/frontend/Frontend.cpp @@ -245,7 +245,7 @@ bool Frontend::RequestMessages() // Now listen for the returned log SNzbLogResponse LogResponse; bool read = connection.Recv((char*) &LogResponse, sizeof(LogResponse)); - if (!read || + if (!read || (int)ntohl(LogResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(LogResponse.m_messageBase.m_structSize) != sizeof(LogResponse)) { @@ -310,7 +310,7 @@ bool Frontend::RequestFileList() // Now listen for the returned list SNzbListResponse ListResponse; bool read = connection.Recv((char*) &ListResponse, sizeof(ListResponse)); - if (!read || + if (!read || (int)ntohl(ListResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(ListResponse.m_messageBase.m_structSize) != sizeof(ListResponse)) { @@ -348,7 +348,7 @@ bool Frontend::RequestFileList() { RemoteClient client; client.SetVerbose(false); - + DownloadQueue* downloadQueue = LockQueue(); client.BuildFileList(&ListResponse, buf, downloadQueue); UnlockQueue(); diff --git a/daemon/frontend/NCursesFrontend.cpp b/daemon/frontend/NCursesFrontend.cpp index f9215901..52431e20 100644 --- a/daemon/frontend/NCursesFrontend.cpp +++ b/daemon/frontend/NCursesFrontend.cpp @@ -68,7 +68,7 @@ // undefine macro "clear". void curses_clear() { - clear(); + clear(); } #undef clear #endif @@ -118,32 +118,32 @@ static const int READKEY_EMPTY = ERR; NCursesFrontend::NCursesFrontend() { - m_screenHeight = 0; - m_screenWidth = 0; - m_inputNumberIndex = 0; - m_inputMode = normal; - m_summary = true; - m_fileList = true; - m_neededLogEntries = 0; + m_screenHeight = 0; + m_screenWidth = 0; + m_inputNumberIndex = 0; + m_inputMode = normal; + m_summary = true; + m_fileList = true; + m_neededLogEntries = 0; m_queueWinTop = 0; m_queueWinHeight = 0; m_queueWinClientHeight = 0; m_messagesWinTop = 0; m_messagesWinHeight = 0; m_messagesWinClientHeight = 0; - m_selectedQueueEntry = 0; + m_selectedQueueEntry = 0; m_queueScrollOffset = 0; m_showNzbname = g_Options->GetCursesNzbName(); m_showTimestamp = g_Options->GetCursesTime(); m_groupFiles = g_Options->GetCursesGroup(); m_queueWindowPercentage = 50; m_dataUpdatePos = 0; - m_updateNextTime = false; + m_updateNextTime = false; m_lastEditEntry = -1; m_lastPausePars = false; m_hint = NULL; - // Setup curses + // Setup curses #ifdef WIN32 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); m_screenBuffer = NULL; @@ -165,38 +165,38 @@ NCursesFrontend::NCursesFrontend() m_useColor = true; #else - m_window = initscr(); - if (m_window == NULL) - { - printf("ERROR: m_pWindow == NULL\n"); - exit(-1); - } + m_window = initscr(); + if (m_window == NULL) + { + printf("ERROR: m_pWindow == NULL\n"); + exit(-1); + } keypad(stdscr, true); - nodelay((WINDOW*)m_window, true); - noecho(); - curs_set(0); - m_useColor = has_colors(); + nodelay((WINDOW*)m_window, true); + noecho(); + curs_set(0); + m_useColor = has_colors(); #endif - if (m_useColor) - { + if (m_useColor) + { #ifndef WIN32 - start_color(); + start_color(); #endif - init_pair(0, COLOR_WHITE, COLOR_BLUE); - init_pair(NCURSES_COLORPAIR_TEXT, COLOR_WHITE, COLOR_BLACK); - init_pair(NCURSES_COLORPAIR_INFO, COLOR_GREEN, COLOR_BLACK); - init_pair(NCURSES_COLORPAIR_WARNING, COLOR_MAGENTA, COLOR_BLACK); - init_pair(NCURSES_COLORPAIR_ERROR, COLOR_RED, COLOR_BLACK); - init_pair(NCURSES_COLORPAIR_DEBUG, COLOR_WHITE, COLOR_BLACK); - init_pair(NCURSES_COLORPAIR_DETAIL, COLOR_GREEN, COLOR_BLACK); - init_pair(NCURSES_COLORPAIR_STATUS, COLOR_BLUE, COLOR_WHITE); - init_pair(NCURSES_COLORPAIR_KEYBAR, COLOR_WHITE, COLOR_BLUE); - init_pair(NCURSES_COLORPAIR_INFOLINE, COLOR_WHITE, COLOR_BLUE); - init_pair(NCURSES_COLORPAIR_TEXTHIGHL, COLOR_BLACK, COLOR_CYAN); - init_pair(NCURSES_COLORPAIR_CURSOR, COLOR_BLACK, COLOR_YELLOW); - init_pair(NCURSES_COLORPAIR_HINT, COLOR_WHITE, COLOR_RED); - } + init_pair(0, COLOR_WHITE, COLOR_BLUE); + init_pair(NCURSES_COLORPAIR_TEXT, COLOR_WHITE, COLOR_BLACK); + init_pair(NCURSES_COLORPAIR_INFO, COLOR_GREEN, COLOR_BLACK); + init_pair(NCURSES_COLORPAIR_WARNING, COLOR_MAGENTA, COLOR_BLACK); + init_pair(NCURSES_COLORPAIR_ERROR, COLOR_RED, COLOR_BLACK); + init_pair(NCURSES_COLORPAIR_DEBUG, COLOR_WHITE, COLOR_BLACK); + init_pair(NCURSES_COLORPAIR_DETAIL, COLOR_GREEN, COLOR_BLACK); + init_pair(NCURSES_COLORPAIR_STATUS, COLOR_BLUE, COLOR_WHITE); + init_pair(NCURSES_COLORPAIR_KEYBAR, COLOR_WHITE, COLOR_BLUE); + init_pair(NCURSES_COLORPAIR_INFOLINE, COLOR_WHITE, COLOR_BLUE); + init_pair(NCURSES_COLORPAIR_TEXTHIGHL, COLOR_BLACK, COLOR_CYAN); + init_pair(NCURSES_COLORPAIR_CURSOR, COLOR_BLACK, COLOR_YELLOW); + init_pair(NCURSES_COLORPAIR_HINT, COLOR_WHITE, COLOR_RED); + } } NCursesFrontend::~NCursesFrontend() @@ -213,25 +213,25 @@ NCursesFrontend::~NCursesFrontend() ConsoleCursorInfo.bVisible = true; SetConsoleCursorInfo(hConsole, &ConsoleCursorInfo); #else - keypad(stdscr, false); - echo(); - curs_set(1); - endwin(); + keypad(stdscr, false); + echo(); + curs_set(1); + endwin(); #endif - printf("\n"); + printf("\n"); SetHint(NULL); } void NCursesFrontend::Run() { - debug("Entering NCursesFrontend-loop"); + debug("Entering NCursesFrontend-loop"); m_dataUpdatePos = 0; - while (!IsStopped()) - { - // The data (queue and log) is updated each m_iUpdateInterval msec, - // but the window is updated more often for better reaction on user's input + while (!IsStopped()) + { + // The data (queue and log) is updated each m_iUpdateInterval msec, + // but the window is updated more often for better reaction on user's input bool updateNow = false; int key = ReadConsoleKey(); @@ -241,20 +241,20 @@ void NCursesFrontend::Run() // Update now and next if a key is pressed. updateNow = true; m_updateNextTime = true; - } + } else if (m_updateNextTime) { // Update due to key being pressed during previous call. updateNow = true; m_updateNextTime = false; - } - else if (m_dataUpdatePos <= 0) + } + else if (m_dataUpdatePos <= 0) { updateNow = true; m_updateNextTime = false; } - if (updateNow) + if (updateNow) { Update(key); } @@ -266,11 +266,11 @@ void NCursesFrontend::Run() usleep(10 * 1000); m_dataUpdatePos -= 10; - } + } - FreeData(); - - debug("Exiting NCursesFrontend-loop"); + FreeData(); + + debug("Exiting NCursesFrontend-loop"); } void NCursesFrontend::NeedUpdateData() @@ -281,21 +281,21 @@ void NCursesFrontend::NeedUpdateData() void NCursesFrontend::Update(int key) { - // Figure out how big the screen is + // Figure out how big the screen is CalcWindowSizes(); - if (m_dataUpdatePos <= 0) - { - FreeData(); + if (m_dataUpdatePos <= 0) + { + FreeData(); m_neededLogEntries = m_messagesWinClientHeight; - if (!PrepareData()) - { - return; - } + if (!PrepareData()) + { + return; + } // recalculate frame sizes CalcWindowSizes(); - } + } if (m_inputMode == editQueue) { @@ -307,34 +307,34 @@ void NCursesFrontend::Update(int key) } } - //------------------------------------------ - // Print Current NZBInfoList - //------------------------------------------ + //------------------------------------------ + // Print Current NZBInfoList + //------------------------------------------ if (m_queueWinHeight > 0) { PrintQueue(); } - //------------------------------------------ - // Print Messages - //------------------------------------------ + //------------------------------------------ + // Print Messages + //------------------------------------------ if (m_messagesWinHeight > 0) { PrintMessages(); } - PrintStatus(); + PrintStatus(); PrintKeyInputBar(); - UpdateInput(key); + UpdateInput(key); RefreshScreen(); } void NCursesFrontend::CalcWindowSizes() { - int nrRows, nrColumns; + int nrRows, nrColumns; #ifdef WIN32 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO BufInfo; @@ -342,10 +342,10 @@ void NCursesFrontend::CalcWindowSizes() nrRows = BufInfo.srWindow.Bottom - BufInfo.srWindow.Top + 1; nrColumns = BufInfo.srWindow.Right - BufInfo.srWindow.Left + 1; #else - getmaxyx(stdscr, nrRows, nrColumns); + getmaxyx(stdscr, nrRows, nrColumns); #endif - if (nrRows != m_screenHeight || nrColumns != m_screenWidth) - { + if (nrRows != m_screenHeight || nrColumns != m_screenWidth) + { #ifdef WIN32 m_screenBufferSize = nrRows * nrColumns * sizeof(CHAR_INFO); m_screenBuffer = (CHAR_INFO*)realloc(m_screenBuffer, m_screenBufferSize); @@ -353,14 +353,14 @@ void NCursesFrontend::CalcWindowSizes() m_oldScreenBuffer = (CHAR_INFO*)realloc(m_oldScreenBuffer, m_screenBufferSize); memset(m_oldScreenBuffer, 0, m_screenBufferSize); #else - curses_clear(); + curses_clear(); #endif - m_screenHeight = nrRows; - m_screenWidth = nrColumns; - } + m_screenHeight = nrRows; + m_screenWidth = nrColumns; + } + + int queueSize = CalcQueueSize(); - int queueSize = CalcQueueSize(); - m_queueWinTop = 0; m_queueWinHeight = (m_screenHeight - 2) * m_queueWindowPercentage / 100; if (m_queueWinHeight - 1 > queueSize) @@ -404,8 +404,8 @@ int NCursesFrontend::CalcQueueSize() void NCursesFrontend::PlotLine(const char * string, int row, int pos, int colorPair) { - char buffer[MAX_SCREEN_WIDTH]; - snprintf(buffer, sizeof(buffer), "%-*s", m_screenWidth, string); + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%-*s", m_screenWidth, string); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; int len = strlen(buffer); if (len > m_screenWidth - pos && m_screenWidth - pos < MAX_SCREEN_WIDTH) @@ -429,7 +429,7 @@ void NCursesFrontend::PlotText(const char * string, int row, int pos, int colorP m_screenBuffer[bufPos + i].Attributes = m_colorAttr[colorPair]; } #else - if( m_useColor ) + if( m_useColor ) { attron(COLOR_PAIR(colorPair)); if (blink) @@ -437,8 +437,8 @@ void NCursesFrontend::PlotText(const char * string, int row, int pos, int colorP attron(A_BLINK); } } - mvaddstr(row, pos, (char*)string); - if( m_useColor ) + mvaddstr(row, pos, (char*)string); + if( m_useColor ) { attroff(COLOR_PAIR(colorPair)); if (blink) @@ -475,11 +475,11 @@ void NCursesFrontend::RefreshScreen() memcpy(m_oldScreenBuffer, m_screenBuffer, m_screenBufferSize); } #else - // Cursor placement - wmove((WINDOW*)m_window, m_screenHeight, m_screenWidth); + // Cursor placement + wmove((WINDOW*)m_window, m_screenHeight, m_screenWidth); - // NCurses refresh - refresh(); + // NCurses refresh + refresh(); #endif } @@ -498,25 +498,25 @@ void NCursesFrontend::PrintMessages() char buffer[MAX_SCREEN_WIDTH]; snprintf(buffer, sizeof(buffer), "%s Messages", m_useColor ? "" : "*** "); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; - PlotLine(buffer, lineNr++, 0, NCURSES_COLORPAIR_INFOLINE); - - int line = lineNr + m_messagesWinClientHeight - 1; + PlotLine(buffer, lineNr++, 0, NCURSES_COLORPAIR_INFOLINE); + + int line = lineNr + m_messagesWinClientHeight - 1; int linesToPrint = m_messagesWinClientHeight; - MessageList* messages = LockMessages(); - + MessageList* messages = LockMessages(); + // print messages from bottom for (int i = (int)messages->size() - 1; i >= 0 && linesToPrint > 0; i--) - { - int printedLines = PrintMessage((*messages)[i], line, linesToPrint); + { + int printedLines = PrintMessage((*messages)[i], line, linesToPrint); line -= printedLines; linesToPrint -= printedLines; - } + } if (linesToPrint > 0) { // too few messages, print them again from top - line = lineNr + m_messagesWinClientHeight - 1; + line = lineNr + m_messagesWinClientHeight - 1; while (linesToPrint-- > 0) { PlotLine("", line--, 0, NCURSES_COLORPAIR_TEXT); @@ -529,15 +529,15 @@ void NCursesFrontend::PrintMessages() linesToPrint2 -= printedLines; } } - - UnlockMessages(); + + UnlockMessages(); } int NCursesFrontend::PrintMessage(Message* Msg, int row, int maxLines) { - const char* messageType[] = { "INFO ", "WARNING ", "ERROR ", "DEBUG ", "DETAIL "}; - const int messageTypeColor[] = { NCURSES_COLORPAIR_INFO, NCURSES_COLORPAIR_WARNING, - NCURSES_COLORPAIR_ERROR, NCURSES_COLORPAIR_DEBUG, NCURSES_COLORPAIR_DETAIL }; + const char* messageType[] = { "INFO ", "WARNING ", "ERROR ", "DEBUG ", "DETAIL "}; + const int messageTypeColor[] = { NCURSES_COLORPAIR_INFO, NCURSES_COLORPAIR_WARNING, + NCURSES_COLORPAIR_ERROR, NCURSES_COLORPAIR_DEBUG, NCURSES_COLORPAIR_DETAIL }; char* text = (char*)Msg->GetText(); @@ -582,7 +582,7 @@ int NCursesFrontend::PrintMessage(Message* Msg, int row, int maxLines) { msgLines++; } - + int lines = 0; for (int i = msgLines - 1; i >= 0 && lines < maxLines; i--) { @@ -606,41 +606,41 @@ int NCursesFrontend::PrintMessage(Message* Msg, int row, int maxLines) void NCursesFrontend::PrintStatus() { - char tmp[MAX_SCREEN_WIDTH]; - int statusRow = m_screenHeight - 2; + char tmp[MAX_SCREEN_WIDTH]; + int statusRow = m_screenHeight - 2; - char timeString[100]; - timeString[0] = '\0'; + char timeString[100]; + timeString[0] = '\0'; int currentDownloadSpeed = m_standBy ? 0 : m_currentDownloadSpeed; - if (currentDownloadSpeed > 0 && !m_pauseDownload) - { - long long remain_sec = (long long)(m_remainingSize / currentDownloadSpeed); + if (currentDownloadSpeed > 0 && !m_pauseDownload) + { + long long remain_sec = (long long)(m_remainingSize / currentDownloadSpeed); int h = (int)(remain_sec / 3600); int m = (int)((remain_sec % 3600) / 60); int s = (int)(remain_sec % 60); sprintf(timeString, " (~ %.2d:%.2d:%.2d)", h, m, s); - } + } - char downloadLimit[128]; - if (m_downloadLimit > 0) - { - sprintf(downloadLimit, ", Limit %i KB/s", m_downloadLimit / 1024); - } - else - { - downloadLimit[0] = 0; - } + char downloadLimit[128]; + if (m_downloadLimit > 0) + { + sprintf(downloadLimit, ", Limit %i KB/s", m_downloadLimit / 1024); + } + else + { + downloadLimit[0] = 0; + } - char postStatus[128]; - if (m_postJobCount > 0) - { - sprintf(postStatus, ", %i post-job%s", m_postJobCount, m_postJobCount > 1 ? "s" : ""); - } - else - { - postStatus[0] = 0; - } + char postStatus[128]; + if (m_postJobCount > 0) + { + sprintf(postStatus, ", %i post-job%s", m_postJobCount, m_postJobCount > 1 ? "s" : ""); + } + else + { + postStatus[0] = 0; + } char currentSpeedBuf[20]; char averageSpeedBuf[20]; @@ -653,14 +653,14 @@ void NCursesFrontend::PrintStatus() timeString, postStatus, m_pauseDownload ? (m_standBy ? ", Paused" : ", Pausing") : "", downloadLimit, Util::FormatSpeed(averageSpeedBuf, sizeof(averageSpeedBuf), averageSpeed)); tmp[MAX_SCREEN_WIDTH - 1] = '\0'; - PlotLine(tmp, statusRow, 0, NCURSES_COLORPAIR_STATUS); + PlotLine(tmp, statusRow, 0, NCURSES_COLORPAIR_STATUS); } void NCursesFrontend::PrintKeyInputBar() { - int queueSize = CalcQueueSize(); + int queueSize = CalcQueueSize(); int inputBarRow = m_screenHeight - 1; - + if (m_hint) { time_t time = ::time(NULL); @@ -675,20 +675,20 @@ void NCursesFrontend::PrintKeyInputBar() } } - switch (m_inputMode) - { - case normal: + switch (m_inputMode) + { + case normal: if (m_groupFiles) { - PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime", inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime", inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); } else { - PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime | n(Z)b", inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + PlotLine("(Q)uit | (E)dit | (P)ause | (R)ate | (W)indow | (G)roup | (T)ime | n(Z)b", inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); } - break; - case editQueue: - { + break; + case editQueue: + { const char* status = NULL; if (m_selectedQueueEntry > 0 && queueSize > 1 && m_selectedQueueEntry == queueSize - 1) { @@ -708,17 +708,17 @@ void NCursesFrontend::PrintKeyInputBar() } PlotLine(status, inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); - break; - } - case downloadRate: - char string[128]; - snprintf(string, 128, "Download rate: %i", m_inputValue); + break; + } + case downloadRate: + char string[128]; + snprintf(string, 128, "Download rate: %i", m_inputValue); string[128-1] = '\0'; - PlotLine(string, inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); - // Print the cursor + PlotLine(string, inputBarRow, 0, NCURSES_COLORPAIR_KEYBAR); + // Print the cursor PlotText(" ", inputBarRow, 15 + m_inputNumberIndex, NCURSES_COLORPAIR_CURSOR, true); - break; - } + break; + } } void NCursesFrontend::SetHint(const char* hint) @@ -746,7 +746,7 @@ void NCursesFrontend::PrintQueue() void NCursesFrontend::PrintFileQueue() { - DownloadQueue* downloadQueue = LockQueue(); + DownloadQueue* downloadQueue = LockQueue(); int lineNr = m_queueWinTop + 1; long long remaining = 0; @@ -780,14 +780,14 @@ void NCursesFrontend::PrintFileQueue() char remainingBuf[20]; char unpausedBuf[20]; char buffer[MAX_SCREEN_WIDTH]; - snprintf(buffer, sizeof(buffer), " %sFiles for downloading - %i / %i files in queue - %s / %s", + snprintf(buffer, sizeof(buffer), " %sFiles for downloading - %i / %i files in queue - %s / %s", m_useColor ? "" : "*** ", fileNum, fileNum - pausedFiles, Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining), Util::FormatSize(unpausedBuf, sizeof(unpausedBuf), remaining - paused)); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; PrintTopHeader(buffer, m_queueWinTop, true); - } + } else { lineNr--; @@ -795,10 +795,10 @@ void NCursesFrontend::PrintFileQueue() snprintf(buffer, sizeof(buffer), "%s Files for downloading", m_useColor ? "" : "*** "); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; PrintTopHeader(buffer, lineNr++, true); - PlotLine("Ready to receive nzb-job", lineNr++, 0, NCURSES_COLORPAIR_TEXT); + PlotLine("Ready to receive nzb-job", lineNr++, 0, NCURSES_COLORPAIR_TEXT); } - UnlockQueue(); + UnlockQueue(); } void NCursesFrontend::PrintFilename(FileInfo * fileInfo, int row, bool selected) @@ -866,8 +866,8 @@ void NCursesFrontend::PrintFilename(FileInfo * fileInfo, int row, bool selected) void NCursesFrontend::PrintTopHeader(char* header, int lineNr, bool upTime) { - char buffer[MAX_SCREEN_WIDTH]; - snprintf(buffer, sizeof(buffer), "%-*s", m_screenWidth, header); + char buffer[MAX_SCREEN_WIDTH]; + snprintf(buffer, sizeof(buffer), "%-*s", m_screenWidth, header); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; int headerLen = strlen(header); int charsLeft = m_screenWidth - headerLen - 2; @@ -887,7 +887,7 @@ void NCursesFrontend::PrintTopHeader(char* header, int lineNr, bool upTime) snprintf(timeStr, 30, "%.2d:%.2d", h, m); } } - else + else { snprintf(timeStr, 30, "%i %s %.2d:%.2d:%.2d", d, (d == 1 ? "day" : "days"), h, m, s); if ((int)strlen(timeStr) > charsLeft) @@ -921,65 +921,65 @@ void NCursesFrontend::PrintTopHeader(char* header, int lineNr, bool upTime) snprintf(buffer + m_screenWidth - timeLen, MAX_SCREEN_WIDTH - (m_screenWidth - timeLen), "%s", timeStr); } - PlotLine(buffer, lineNr, 0, NCURSES_COLORPAIR_INFOLINE); + PlotLine(buffer, lineNr, 0, NCURSES_COLORPAIR_INFOLINE); } void NCursesFrontend::PrintGroupQueue() { int lineNr = m_queueWinTop; - DownloadQueue* downloadQueue = LockQueue(); + DownloadQueue* downloadQueue = LockQueue(); if (downloadQueue->GetQueue()->empty()) - { + { char buffer[MAX_SCREEN_WIDTH]; snprintf(buffer, sizeof(buffer), "%s NZBs for downloading", m_useColor ? "" : "*** "); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; PrintTopHeader(buffer, lineNr++, false); - PlotLine("Ready to receive nzb-job", lineNr++, 0, NCURSES_COLORPAIR_TEXT); - } - else - { + PlotLine("Ready to receive nzb-job", lineNr++, 0, NCURSES_COLORPAIR_TEXT); + } + else + { lineNr++; ResetColWidths(); int calcLineNr = lineNr; int i = 0; - for (NzbList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, i++) - { - NzbInfo* nzbInfo = *it; + for (NzbList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, i++) + { + NzbInfo* nzbInfo = *it; if (i >= m_queueScrollOffset && i < m_queueScrollOffset + m_queueWinHeight -1) { PrintGroupname(nzbInfo, calcLineNr++, false, true); } - } + } long long remaining = 0; long long paused = 0; i = 0; - for (NzbList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, i++) - { - NzbInfo* nzbInfo = *it; + for (NzbList::iterator it = downloadQueue->GetQueue()->begin(); it != downloadQueue->GetQueue()->end(); it++, i++) + { + NzbInfo* nzbInfo = *it; if (i >= m_queueScrollOffset && i < m_queueScrollOffset + m_queueWinHeight -1) { PrintGroupname(nzbInfo, lineNr++, i == m_selectedQueueEntry, false); } remaining += nzbInfo->GetRemainingSize(); paused += nzbInfo->GetPausedSize(); - } - + } + char remainingBuf[20]; Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining); char unpausedBuf[20]; Util::FormatSize(unpausedBuf, sizeof(unpausedBuf), remaining - paused); - + char buffer[MAX_SCREEN_WIDTH]; - snprintf(buffer, sizeof(buffer), " %sNZBs for downloading - %i NZBs in queue - %s / %s", + snprintf(buffer, sizeof(buffer), " %sNZBs for downloading - %i NZBs in queue - %s / %s", m_useColor ? "" : "*** ", (int)downloadQueue->GetQueue()->size(), remainingBuf, unpausedBuf); buffer[MAX_SCREEN_WIDTH - 1] = '\0'; PrintTopHeader(buffer, m_queueWinTop, false); - } - UnlockQueue(); + } + UnlockQueue(); } void NCursesFrontend::ResetColWidths() @@ -1045,12 +1045,12 @@ void NCursesFrontend::PrintGroupname(NzbInfo* nzbInfo, int row, bool selected, b char files[20]; snprintf(files, 20, "%i/%i", (int)nzbInfo->GetFileList()->size(), nzbInfo->GetPausedFileCount()); files[20-1] = '\0'; - + char total[20]; Util::FormatSize(total, sizeof(total), nzbInfo->GetSize()); char nameWithIds[1024]; - snprintf(nameWithIds, 1024, "%c%i%c%s%s %s", chBrace1, nzbInfo->GetId(), chBrace2, + snprintf(nameWithIds, 1024, "%c%i%c%s%s %s", chBrace1, nzbInfo->GetId(), chBrace2, priority, downloading, nzbInfo->GetName()); nameWithIds[nameLen] = '\0'; @@ -1096,7 +1096,7 @@ void NCursesFrontend::PrintGroupname(NzbInfo* nzbInfo, int row, bool selected, b } else { - snprintf(buffer, MAX_SCREEN_WIDTH, "%c%i%c%s %s", chBrace1, nzbInfo->GetId(), + snprintf(buffer, MAX_SCREEN_WIDTH, "%c%i%c%s %s", chBrace1, nzbInfo->GetId(), chBrace2, downloading, nzbInfo->GetName()); } @@ -1143,11 +1143,11 @@ bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction action, int offset) // map file-edit-actions to group-edit-actions DownloadQueue::EEditAction FileToGroupMap[] = { (DownloadQueue::EEditAction)0, - DownloadQueue::eaGroupMoveOffset, - DownloadQueue::eaGroupMoveTop, - DownloadQueue::eaGroupMoveBottom, - DownloadQueue::eaGroupPause, - DownloadQueue::eaGroupResume, + DownloadQueue::eaGroupMoveOffset, + DownloadQueue::eaGroupMoveTop, + DownloadQueue::eaGroupMoveBottom, + DownloadQueue::eaGroupPause, + DownloadQueue::eaGroupResume, DownloadQueue::eaGroupDelete, DownloadQueue::eaGroupPauseAllPars, DownloadQueue::eaGroupPauseExtraPars }; @@ -1194,7 +1194,7 @@ bool NCursesFrontend::EditQueue(DownloadQueue::EEditAction action, int offset) void NCursesFrontend::SetCurrentQueueEntry(int entry) { - int queueSize = CalcQueueSize(); + int queueSize = CalcQueueSize(); if (entry < 0) { @@ -1218,7 +1218,7 @@ void NCursesFrontend::SetCurrentQueueEntry(int entry) { m_queueScrollOffset += m_queueWinClientHeight; } - + if (m_queueScrollOffset > queueSize - m_queueWinClientHeight) { m_queueScrollOffset = queueSize - m_queueWinClientHeight; @@ -1227,7 +1227,7 @@ void NCursesFrontend::SetCurrentQueueEntry(int entry) { m_queueScrollOffset = 0; } - + m_selectedQueueEntry = entry; } @@ -1240,7 +1240,7 @@ void NCursesFrontend::UpdateInput(int initialKey) { int key = initialKey; while (key != READKEY_EMPTY) - { + { int queueSize = CalcQueueSize(); // Normal or edit queue mode @@ -1266,7 +1266,7 @@ void NCursesFrontend::UpdateInput(int initialKey) { m_queueWindowPercentage = 0; } - else + else { m_queueWindowPercentage = 50; } @@ -1281,7 +1281,7 @@ void NCursesFrontend::UpdateInput(int initialKey) break; } } - + // Normal mode if (m_inputMode == normal) { @@ -1466,7 +1466,7 @@ int NCursesFrontend::ReadConsoleKey() { INPUT_RECORD InputRecord; DWORD NumberOfEventsRead; - if (ReadConsoleInput(hConsole, &InputRecord, 1, &NumberOfEventsRead) && + if (ReadConsoleInput(hConsole, &InputRecord, 1, &NumberOfEventsRead) && NumberOfEventsRead > 0 && InputRecord.EventType == KEY_EVENT && InputRecord.Event.KeyEvent.bKeyDown) diff --git a/daemon/frontend/NCursesFrontend.h b/daemon/frontend/NCursesFrontend.h index 371e43fa..cd0fe2e7 100644 --- a/daemon/frontend/NCursesFrontend.h +++ b/daemon/frontend/NCursesFrontend.h @@ -42,14 +42,14 @@ private: enum EInputMode { - normal, - editQueue, - downloadRate + normal, + editQueue, + downloadRate }; bool m_useColor; int m_dataUpdatePos; - bool m_updateNextTime; + bool m_updateNextTime; int m_screenHeight; int m_screenWidth; int m_queueWinTop; diff --git a/daemon/main/CommandLineParser.cpp b/daemon/main/CommandLineParser.cpp index 8228075c..0dfcf3e0 100644 --- a/daemon/main/CommandLineParser.cpp +++ b/daemon/main/CommandLineParser.cpp @@ -24,7 +24,7 @@ #ifdef HAVE_CONFIG_H -#include "config.h" +#include "config.h" #endif #ifdef WIN32 @@ -55,33 +55,33 @@ #ifdef HAVE_GETOPT_LONG static struct option long_options[] = - { - {"help", no_argument, 0, 'h'}, - {"configfile", required_argument, 0, 'c'}, - {"noconfigfile", no_argument, 0, 'n'}, - {"printconfig", no_argument, 0, 'p'}, - {"server", no_argument, 0, 's' }, - {"daemon", no_argument, 0, 'D' }, - {"version", no_argument, 0, 'v'}, - {"serverversion", no_argument, 0, 'V'}, - {"option", required_argument, 0, 'o'}, - {"append", no_argument, 0, 'A'}, - {"list", no_argument, 0, 'L'}, - {"pause", no_argument, 0, 'P'}, - {"unpause", no_argument, 0, 'U'}, - {"rate", required_argument, 0, 'R'}, - {"system", no_argument, 0, 'B'}, - {"log", required_argument, 0, 'G'}, - {"top", no_argument, 0, 'T'}, - {"edit", required_argument, 0, 'E'}, - {"connect", no_argument, 0, 'C'}, - {"quit", no_argument, 0, 'Q'}, - {"reload", no_argument, 0, 'O'}, - {"write", required_argument, 0, 'W'}, - {"category", required_argument, 0, 'K'}, - {"scan", no_argument, 0, 'S'}, - {0, 0, 0, 0} - }; + { + {"help", no_argument, 0, 'h'}, + {"configfile", required_argument, 0, 'c'}, + {"noconfigfile", no_argument, 0, 'n'}, + {"printconfig", no_argument, 0, 'p'}, + {"server", no_argument, 0, 's' }, + {"daemon", no_argument, 0, 'D' }, + {"version", no_argument, 0, 'v'}, + {"serverversion", no_argument, 0, 'V'}, + {"option", required_argument, 0, 'o'}, + {"append", no_argument, 0, 'A'}, + {"list", no_argument, 0, 'L'}, + {"pause", no_argument, 0, 'P'}, + {"unpause", no_argument, 0, 'U'}, + {"rate", required_argument, 0, 'R'}, + {"system", no_argument, 0, 'B'}, + {"log", required_argument, 0, 'G'}, + {"top", no_argument, 0, 'T'}, + {"edit", required_argument, 0, 'E'}, + {"connect", no_argument, 0, 'C'}, + {"quit", no_argument, 0, 'Q'}, + {"reload", no_argument, 0, 'O'}, + {"write", required_argument, 0, 'W'}, + {"category", required_argument, 0, 'K'}, + {"scan", no_argument, 0, 'S'}, + {0, 0, 0, 0} + }; #endif static char short_options[] = "c:hno:psvAB:DCE:G:K:LPR:STUQOVW:"; @@ -537,7 +537,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) else if (!strcasecmp(optarg, "O")) { m_editQueueAction = DownloadQueue::eaHistorySetParameter; - + optind++; if (optind > argc) { @@ -545,7 +545,7 @@ void CommandLineParser::InitCommandLine(int argc, const char* const_argv[]) return; } m_editQueueText = strdup(argv[optind-1]); - + if (!strchr(m_editQueueText, '=')) { ReportError("Could not parse value of option 'E'"); @@ -795,8 +795,8 @@ void CommandLineParser::PrintUsage(const char* com) printf("Usage:\n" " %s [switches]\n\n" "Switches:\n" - " -h, --help Print this help-message\n" - " -v, --version Print version and exit\n" + " -h, --help Print this help-message\n" + " -v, --version Print version and exit\n" " -c, --configfile Filename of configuration-file\n" " -n, --noconfigfile Prevent loading of configuration-file\n" " (required options must be passed with --option)\n" @@ -806,7 +806,7 @@ void CommandLineParser::PrintUsage(const char* com) #ifndef WIN32 " -D, --daemon Start nzbget as a server in daemon-mode\n" #endif - " -V, --serverversion Print server's version and exit\n" + " -V, --serverversion Print server's version and exit\n" " -Q, --quit Shutdown server\n" " -O, --reload Reload config and restart all services\n" " -A, --append [] Send file/url to server's\n" @@ -903,8 +903,8 @@ void CommandLineParser::InitFileArg(int argc, const char* argv[]) { // no nzb-file passed if (!m_serverMode && !m_remoteClientMode && - (m_clientOperation == opClientNoOperation || - m_clientOperation == opClientRequestDownload || + (m_clientOperation == opClientNoOperation || + m_clientOperation == opClientRequestDownload || m_clientOperation == opClientRequestWriteLog)) { if (m_clientOperation == opClientRequestWriteLog) @@ -955,8 +955,8 @@ void CommandLineParser::InitFileArg(int argc, const char* argv[]) #endif if (m_serverMode || m_remoteClientMode || - !(m_clientOperation == opClientNoOperation || - m_clientOperation == opClientRequestDownload || + !(m_clientOperation == opClientNoOperation || + m_clientOperation == opClientRequestDownload || m_clientOperation == opClientRequestWriteLog)) { ReportError("Too many arguments"); diff --git a/daemon/main/DiskService.cpp b/daemon/main/DiskService.cpp index 4ddbe0e5..59c016fa 100644 --- a/daemon/main/DiskService.cpp +++ b/daemon/main/DiskService.cpp @@ -59,7 +59,7 @@ void DiskService::ServiceWork() m_interval++; if (m_interval == 5) { - if (!g_Options->GetPauseDownload() && + if (!g_Options->GetPauseDownload() && g_Options->GetDiskSpace() > 0 && !g_StatMeter->GetStandBy()) { // check free disk space every 1 second diff --git a/daemon/main/Maintenance.cpp b/daemon/main/Maintenance.cpp index a06445e2..98b1a672 100644 --- a/daemon/main/Maintenance.cpp +++ b/daemon/main/Maintenance.cpp @@ -65,8 +65,8 @@ private: const char* m_inFilename; const char* m_sigFilename; const char* m_pubKeyFilename; - unsigned char m_inHash[SHA256_DIGEST_LENGTH]; - unsigned char m_signature[256]; + unsigned char m_inHash[SHA256_DIGEST_LENGTH]; + unsigned char m_signature[256]; RSA* m_pubKey; bool ReadSignature(); @@ -286,7 +286,7 @@ void UpdateScriptController::Run() infoName[1024-1] = '\0'; SetInfoName(infoName); - const char* branchName[] = { "STABLE", "TESTING", "DEVEL" }; + const char* branchName[] = { "STABLE", "TESTING", "DEVEL" }; SetEnvVar("NZBUP_BRANCH", branchName[m_branch]); SetEnvVar("NZBUP_RUNMODE", g_CommandLineParser->GetDaemonMode() ? "DAEMON" : "SERVER"); @@ -416,26 +416,26 @@ Signature::~Signature() // Calculate SHA-256 for input file (m_szInFilename) bool Signature::ComputeInHash() { - FILE* infile = fopen(m_inFilename, FOPEN_RB); - if (!infile) + FILE* infile = fopen(m_inFilename, FOPEN_RB); + if (!infile) { return false; } - SHA256_CTX sha256; + SHA256_CTX sha256; SHA256_Init(&sha256); - const int bufSize = 32*1024; - char* buffer = (char*)malloc(bufSize); - while(int bytesRead = fread(buffer, 1, bufSize, infile)) - { - SHA256_Update(&sha256, buffer, bytesRead); - } - SHA256_Final(m_inHash, &sha256); - free(buffer); - fclose(infile); + const int bufSize = 32*1024; + char* buffer = (char*)malloc(bufSize); + while(int bytesRead = fread(buffer, 1, bufSize, infile)) + { + SHA256_Update(&sha256, buffer, bytesRead); + } + SHA256_Final(m_inHash, &sha256); + free(buffer); + fclose(infile); return true; } -// Read signature from file (m_szSigFilename) into memory +// Read signature from file (m_szSigFilename) into memory bool Signature::ReadSignature() { char sigTitle[256]; @@ -443,7 +443,7 @@ bool Signature::ReadSignature() sigTitle[256-1] = '\0'; FILE* infile = fopen(m_sigFilename, FOPEN_RB); - if (!infile) + if (!infile) { return false; } diff --git a/daemon/main/Options.cpp b/daemon/main/Options.cpp index 83649d12..8bd77019 100644 --- a/daemon/main/Options.cpp +++ b/daemon/main/Options.cpp @@ -613,13 +613,13 @@ void Options::ConfigError(const char* msg, ...) void Options::ConfigWarn(const char* msg, ...) { char tmp2[1024]; - + va_list ap; va_start(ap, msg); vsnprintf(tmp2, 1024, msg, ap); tmp2[1024-1] = '\0'; va_end(ap); - + printf("%s(%i): %s\n", Util::BaseFileName(m_configFilename), m_configLine, tmp2); warn("%s(%i): %s", Util::BaseFileName(m_configFilename), m_configLine, tmp2); } @@ -1228,7 +1228,7 @@ void Options::InitServers() sprintf(optname, "Server%i.Group", n); const char* ngroup = GetOption(optname); - + sprintf(optname, "Server%i.Host", n); const char* nhost = GetOption(optname); @@ -1355,7 +1355,7 @@ void Options::InitCategories() m_categories.push_back(category); free(destDir); - + // split Aliases into tokens and create items for each token if (naliases) { @@ -1387,7 +1387,7 @@ void Options::InitFeeds() sprintf(optname, "Feed%i.URL", n); const char* nurl = GetOption(optname); - + sprintf(optname, "Feed%i.Filter", n); const char* nfilter = GetOption(optname); @@ -1543,11 +1543,11 @@ void Options::InitScheduler() } } - if ((taskCommand == scScript || - taskCommand == scProcess || + if ((taskCommand == scScript || + taskCommand == scProcess || taskCommand == scActivateServer || taskCommand == scDeactivateServer || - taskCommand == scFetchFeed) && + taskCommand == scFetchFeed) && Util::EmptyStr(param)) { ConfigError("Task definition not complete for \"Task%i\". Option \"Task%i.Param\" is missing", n, n); @@ -1856,7 +1856,7 @@ bool Options::ValidateOptionName(const char* optname, const char* optvalue) return true; } } - + if (!strncasecmp(optname, "category", 8)) { char* p = (char*)optname + 8; @@ -1990,7 +1990,7 @@ void Options::ConvertOldOption(char *option, int optionBufLen, char *value, int int val = strtol(value, NULL, 10); val = val == -1 ? 1024 : val / 1024; snprintf(value, valueBufLen, "%i", val); - } + } if (!strcasecmp(option, "ConnectionTimeout")) { diff --git a/daemon/main/Options.h b/daemon/main/Options.h index 7095d52f..e80a24bd 100644 --- a/daemon/main/Options.h +++ b/daemon/main/Options.h @@ -117,7 +117,7 @@ public: int GetLineNo() { return m_lineNo; } bool Restricted(); }; - + typedef std::vector OptEntriesBase; class OptEntries: public OptEntriesBase @@ -148,7 +148,7 @@ public: const char* GetPostScript() { return m_postScript; } NameList* GetAliases() { return &m_aliases; } }; - + typedef std::vector CategoriesBase; class Categories: public CategoriesBase diff --git a/daemon/main/Scheduler.cpp b/daemon/main/Scheduler.cpp index 988a08ff..34fd9ee1 100644 --- a/daemon/main/Scheduler.cpp +++ b/daemon/main/Scheduler.cpp @@ -76,7 +76,7 @@ Scheduler::Scheduler() Scheduler::~Scheduler() { debug("Destroying Scheduler"); - + for (TaskList::iterator it = m_taskList.begin(); it != m_taskList.end(); it++) { delete *it; @@ -92,7 +92,7 @@ void Scheduler::AddTask(Task* task) bool Scheduler::CompareTasks(Scheduler::Task* task1, Scheduler::Task* task2) { - return (task1->m_hours < task2->m_hours) || + return (task1->m_hours < task2->m_hours) || ((task1->m_hours == task2->m_hours) && (task1->m_minutes < task2->m_minutes)); } @@ -135,7 +135,7 @@ void Scheduler::CheckTasks() if (!m_taskList.empty()) { - // Detect large step changes of system time + // Detect large step changes of system time time_t diff = current - m_lastCheck; if (diff > 60*90 || diff < 0) { diff --git a/daemon/main/Scheduler.h b/daemon/main/Scheduler.h index 6d801393..e974f262 100644 --- a/daemon/main/Scheduler.h +++ b/daemon/main/Scheduler.h @@ -64,7 +64,7 @@ public: time_t m_lastExecuted; public: - Task(int id, int hours, int minutes, int weekDaysBits, ECommand command, + Task(int id, int hours, int minutes, int weekDaysBits, ECommand command, const char* param); ~Task(); friend class Scheduler; diff --git a/daemon/main/StackTrace.cpp b/daemon/main/StackTrace.cpp index 3cd48ee3..8b140792 100644 --- a/daemon/main/StackTrace.cpp +++ b/daemon/main/StackTrace.cpp @@ -217,7 +217,7 @@ void PrintBacktrace() { #ifdef HAVE_BACKTRACE printf("Segmentation fault, tracing...\n"); - + void *array[100]; size_t size; char **strings; @@ -293,8 +293,8 @@ void InstallErrorHandler() signal(SIGSEGV, SignalProc); #endif #ifdef SIGCHLD_HANDLER - // it could be necessary on some systems to activate a handler for SIGCHLD - // however it make troubles on other systems and is deactivated by default + // it could be necessary on some systems to activate a handler for SIGCHLD + // however it make troubles on other systems and is deactivated by default signal(SIGCHLD, SignalProc); #endif } diff --git a/daemon/main/nzbget.cpp b/daemon/main/nzbget.cpp index 541bb480..f79b7193 100644 --- a/daemon/main/nzbget.cpp +++ b/daemon/main/nzbget.cpp @@ -205,11 +205,11 @@ void RunMain() { // we need to save and later restore current directory each time // the program is reloaded (RPC-Method "reload") in order for - // config to properly load in a case relative paths are used + // config to properly load in a case relative paths are used // in command line char curDir[MAX_PATH + 1]; Util::GetCurrentDirectory(curDir, sizeof(curDir)); - + bool reload = false; while (g_Reloading) { @@ -261,7 +261,7 @@ void Run(bool reload) umask(g_Options->GetUMask()); } #endif - + g_Scanner->InitOptions(); g_QueueScriptCoordinator->InitOptions(); @@ -403,8 +403,8 @@ void Run(bool reload) } // enter main program-loop - while (g_QueueCoordinator->IsRunning() || - g_UrlCoordinator->IsRunning() || + while (g_QueueCoordinator->IsRunning() || + g_UrlCoordinator->IsRunning() || g_PrePostProcessor->IsRunning() || g_FeedCoordinator->IsRunning() || g_ServiceCoordinator->IsRunning() || @@ -413,9 +413,9 @@ void Run(bool reload) #endif g_ArticleCache->IsRunning()) { - if (!g_Options->GetServerMode() && - !g_QueueCoordinator->HasMoreJobs() && - !g_UrlCoordinator->HasMoreJobs() && + if (!g_Options->GetServerMode() && + !g_QueueCoordinator->HasMoreJobs() && + !g_UrlCoordinator->HasMoreJobs() && !g_PrePostProcessor->HasMoreJobs()) { // Standalone-mode: download completed @@ -720,7 +720,7 @@ void ProcessSigVerify() exit(ok ? 93 : 1); #else printf("ERROR: Could not verify signature, the program was compiled without OpenSSL support\n"); - exit(1); + exit(1); #endif } diff --git a/daemon/nntp/ArticleDownloader.cpp b/daemon/nntp/ArticleDownloader.cpp index 7c6bbbb7..406f6916 100644 --- a/daemon/nntp/ArticleDownloader.cpp +++ b/daemon/nntp/ArticleDownloader.cpp @@ -261,7 +261,7 @@ void ArticleDownloader::Run() { serverFailed = true; break; - } + } } } if (!serverFailed) @@ -286,7 +286,7 @@ void ArticleDownloader::Run() break; } } - + remainedRetries = retries; } } @@ -335,7 +335,7 @@ ArticleDownloader::EStatus ArticleDownloader::Download() response = m_connection->JoinGroup(*it); if (response && !strncmp(response, "2", 1)) { - break; + break; } } @@ -530,7 +530,7 @@ ArticleDownloader::EStatus ArticleDownloader::CheckResponse(const char* response // OK return adFinished; } - else + else { // unknown error, no special handling detail("Article %s @ %s failed, %s: %s", m_infoName, m_connectionName, comment, response); @@ -652,7 +652,7 @@ ArticleDownloader::EStatus ArticleDownloader::DecodeCheck() return adFailed; } } - else + else { return adFinished; } @@ -701,7 +701,7 @@ bool ArticleDownloader::Terminate() void ArticleDownloader::FreeConnection(bool keepConnected) { - if (m_connection) + if (m_connection) { debug("Releasing connection"); m_connectionMutex.Lock(); diff --git a/daemon/nntp/ArticleDownloader.h b/daemon/nntp/ArticleDownloader.h index a884970a..7059f3bb 100644 --- a/daemon/nntp/ArticleDownloader.h +++ b/daemon/nntp/ArticleDownloader.h @@ -58,11 +58,11 @@ public: private: ArticleDownloader* m_owner; protected: - virtual void SetLastUpdateTimeNow() { m_owner->SetLastUpdateTimeNow(); } + virtual void SetLastUpdateTimeNow() { m_owner->SetLastUpdateTimeNow(); } public: void SetOwner(ArticleDownloader* owner) { m_owner = owner; } }; - + private: FileInfo* m_fileInfo; ArticleInfo* m_articleInfo; diff --git a/daemon/nntp/ArticleWriter.cpp b/daemon/nntp/ArticleWriter.cpp index 3d3f6ac0..4f488020 100644 --- a/daemon/nntp/ArticleWriter.cpp +++ b/daemon/nntp/ArticleWriter.cpp @@ -273,7 +273,7 @@ void ArticleWriter::Finish(bool success) m_articleInfo->SetSegmentSize(m_articlePtr); } } - else + else { // rawmode if (!Util::MoveFile(m_tempFilename, m_resultFilename)) @@ -294,7 +294,7 @@ bool ArticleWriter::CreateOutputFile(long long size) // keep existing old file from previous program session return true; } - + // delete eventually existing old file from previous program session remove(m_outputFilename); @@ -375,7 +375,7 @@ void ArticleWriter::CompleteFileParts() DownloadQueue::Unlock(); nzbName[1024-1] = '\0'; nzbDestDir[1024-1] = '\0'; - + char infoFilename[1024]; snprintf(infoFilename, 1024, "%s%c%s", nzbName, (int)PATH_SEPARATOR, m_fileInfo->GetFilename()); infoFilename[1024-1] = '\0'; @@ -567,7 +567,7 @@ void ArticleWriter::CompleteFileParts() // if destination directory was changed delete the old directory (if empty) int len = strlen(nzbDestDir); - if (!(!strncmp(nzbDestDir, m_outputFilename, len) && + if (!(!strncmp(nzbDestDir, m_outputFilename, len) && (m_outputFilename[len] == PATH_SEPARATOR || m_outputFilename[len] == ALT_PATH_SEPARATOR))) { debug("Checking old dir for: %s", m_outputFilename); @@ -771,7 +771,7 @@ bool ArticleWriter::MoveCompletedFiles(NzbInfo* nzbInfo, const char* oldDestDir) // move already downloaded files to new destination for (CompletedFiles::iterator it = nzbInfo->GetCompletedFiles()->begin(); it != nzbInfo->GetCompletedFiles()->end(); it++) - { + { CompletedFile* completedFile = *it; char oldFileName[1024]; @@ -796,7 +796,7 @@ bool ArticleWriter::MoveCompletedFiles(NzbInfo* nzbInfo, const char* oldDestDir) oldFileName, newFileName, Util::GetLastErrorMessage(errBuf, sizeof(errBuf))); } } - } + } // move brokenlog.txt if (g_Options->GetBrokenLog()) @@ -845,7 +845,7 @@ bool ArticleWriter::MoveCompletedFiles(NzbInfo* nzbInfo, const char* oldDestDir) nzbInfo->PrintMessage(Message::mkError, "Could not open file %s", brokenLogName); } } - else + else { // move to new destination if (!Util::MoveFile(oldBrokenLogName, brokenLogName)) diff --git a/daemon/nntp/Decoder.cpp b/daemon/nntp/Decoder.cpp index d367b89f..9f2a1a18 100644 --- a/daemon/nntp/Decoder.cpp +++ b/daemon/nntp/Decoder.cpp @@ -71,7 +71,7 @@ Decoder::EFormat Decoder::DetectFormat(const char* buffer, int len) { return efYenc; } - + if ((len == 62 || len == 63) && (buffer[62] == '\n' || buffer[62] == '\r') && *buffer == 'M') { return efUx; @@ -141,7 +141,7 @@ int YDecoder::DecodeBuffer(char* buffer, int len) m_expectedCRC = strtoul(pb, NULL, 16); } pb = strstr(buffer, " size="); - if (pb) + if (pb) { pb += 6; //=strlen(" size=") m_endSize = (long long)atoll(pb); @@ -180,7 +180,7 @@ BreakLoop: } return optr - buffer; } - else + else { if (!m_part && !strncmp(buffer, "=ybegin ", 8)) { @@ -197,7 +197,7 @@ BreakLoop: m_articleFilename[pe - pb] = '\0'; } pb = strstr(buffer, " size="); - if (pb) + if (pb) { pb += 6; //=strlen(" size=") m_size = (long long)atoll(pb); @@ -215,13 +215,13 @@ BreakLoop: m_part = true; m_body = true; char* pb = strstr(buffer, " begin="); - if (pb) + if (pb) { pb += 7; //=strlen(" begin=") m_beginPos = (long long)atoll(pb); } pb = strstr(buffer, " end="); - if (pb) + if (pb) { pb += 5; //=strlen(" end=") m_endPos = (long long)atoll(pb); @@ -296,7 +296,7 @@ int UDecoder::DecodeBuffer(char* buffer, int len) pb += 6; //strlen("begin ") // skip file-permissions - for (; *pb != ' ' && *pb != '\0' && *pb != '\n' && *pb != '\r'; pb++) ; + for (; *pb != ' ' && *pb != '\0' && *pb != '\n' && *pb != '\r'; pb++) ; pb++; // extracting filename @@ -336,19 +336,19 @@ int UDecoder::DecodeBuffer(char* buffer, int len) { if (effLen >= 3) { - *optr++ = UU_DECODE_CHAR (iptr[0]) << 2 | UU_DECODE_CHAR (iptr[1]) >> 4; - *optr++ = UU_DECODE_CHAR (iptr[1]) << 4 | UU_DECODE_CHAR (iptr[2]) >> 2; + *optr++ = UU_DECODE_CHAR (iptr[0]) << 2 | UU_DECODE_CHAR (iptr[1]) >> 4; + *optr++ = UU_DECODE_CHAR (iptr[1]) << 4 | UU_DECODE_CHAR (iptr[2]) >> 2; *optr++ = UU_DECODE_CHAR (iptr[2]) << 6 | UU_DECODE_CHAR (iptr[3]); } else { if (effLen >= 1) { - *optr++ = UU_DECODE_CHAR (iptr[0]) << 2 | UU_DECODE_CHAR (iptr[1]) >> 4; + *optr++ = UU_DECODE_CHAR (iptr[0]) << 2 | UU_DECODE_CHAR (iptr[1]) >> 4; } if (effLen >= 2) { - *optr++ = UU_DECODE_CHAR (iptr[1]) << 4 | UU_DECODE_CHAR (iptr[2]) >> 2; + *optr++ = UU_DECODE_CHAR (iptr[1]) << 4 | UU_DECODE_CHAR (iptr[2]) >> 2; } } } diff --git a/daemon/nntp/NntpConnection.cpp b/daemon/nntp/NntpConnection.cpp index d6e7b836..ba0a10e3 100644 --- a/daemon/nntp/NntpConnection.cpp +++ b/daemon/nntp/NntpConnection.cpp @@ -279,6 +279,6 @@ void NntpConnection::ReportErrorAnswer(const char* msgPrefix, const char* answer char errStr[1024]; snprintf(errStr, 1024, msgPrefix, m_newsServer->GetName(), m_newsServer->GetHost(), answer); errStr[1024-1] = '\0'; - + ReportError(errStr, NULL, false, 0); } diff --git a/daemon/nntp/ServerPool.cpp b/daemon/nntp/ServerPool.cpp index cff3668e..7ca236d1 100644 --- a/daemon/nntp/ServerPool.cpp +++ b/daemon/nntp/ServerPool.cpp @@ -170,7 +170,7 @@ void ServerPool::InitConnections() if (newsServer->GetActive()) { int connections = 0; - + for (Connections::iterator it = m_connections.begin(); it != m_connections.end(); it++) { PooledConnection* connection = *it; @@ -179,7 +179,7 @@ void ServerPool::InitConnections() connections++; } } - + for (int i = connections; i < newsServer->GetMaxConnections(); i++) { PooledConnection* connection = new PooledConnection(newsServer); @@ -215,7 +215,7 @@ NntpConnection* ServerPool::GetConnection(int level, NewsServer* wantServer, Ser PooledConnection* candidateConnection = *it; NewsServer* candidateServer = candidateConnection->GetNewsServer(); if (!candidateConnection->GetInUse() && candidateServer->GetActive() && - candidateServer->GetNormLevel() == level && + candidateServer->GetNormLevel() == level && (!wantServer || candidateServer == wantServer || (wantServer->GetGroup() > 0 && wantServer->GetGroup() == candidateServer->GetGroup())) && (candidateConnection->GetStatus() == Connection::csConnected || diff --git a/daemon/nntp/StatMeter.h b/daemon/nntp/StatMeter.h index ce07be25..4f124502 100644 --- a/daemon/nntp/StatMeter.h +++ b/daemon/nntp/StatMeter.h @@ -85,12 +85,12 @@ class StatMeter : public Debuggable { private: // speed meter - static const int SPEEDMETER_SLOTS = 30; + static const int SPEEDMETER_SLOTS = 30; static const int SPEEDMETER_SLOTSIZE = 1; //Split elapsed time into this number of secs. int m_speedBytes[SPEEDMETER_SLOTS]; long long m_speedTotalBytes; int m_speedTime[SPEEDMETER_SLOTS]; - int m_speedStartTime; + int m_speedStartTime; time_t m_speedCorrection; int m_speedBytesIndex; int m_curSecBytes; diff --git a/daemon/postprocess/ParChecker.cpp b/daemon/postprocess/ParChecker.cpp index 714b4ad3..c90cda7f 100644 --- a/daemon/postprocess/ParChecker.cpp +++ b/daemon/postprocess/ParChecker.cpp @@ -408,7 +408,7 @@ ParChecker::DupeSource::~DupeSource() ParChecker::ParChecker() { - debug("Creating ParChecker"); + debug("Creating ParChecker"); m_status = psFailed; m_destDir = NULL; @@ -432,7 +432,7 @@ ParChecker::ParChecker() ParChecker::~ParChecker() { - debug("Destroying ParChecker"); + debug("Destroying ParChecker"); free(m_destDir); free(m_nzbName); @@ -533,7 +533,7 @@ ParChecker::EStatus ParChecker::RunParCheckAll() int maxlen = baseLen < 1024 ? baseLen : 1024 - 1; strncpy(infoName, parFilename, maxlen); infoName[maxlen] = '\0'; - + char parInfoName[1024]; snprintf(parInfoName, 1024, "%s%c%s", m_nzbName, (int)PATH_SEPARATOR, infoName); parInfoName[1024-1] = '\0'; @@ -574,21 +574,21 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) PrintMessage(Message::mkInfo, "Verifying %s", m_infoName); - debug("par: %s", m_parFilename); - + debug("par: %s", m_parFilename); + snprintf(m_progressLabel, 1024, "Verifying %s", m_infoName); m_progressLabel[1024-1] = '\0'; m_fileProgress = 0; m_stageProgress = 0; UpdateProgress(); - Result res = (Result)PreProcessPar(); + Result res = (Result)PreProcessPar(); if (IsStopped() || res != eSuccess) { Cleanup(); return psFailed; } - + m_stage = ptVerifyingSources; Repairer* repairer = (Repairer*)m_repairer; res = repairer->Process(false); @@ -608,7 +608,7 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) } } - if (m_hasDamagedFiles && !IsStopped() && repairer->missingfilecount > 0 && + if (m_hasDamagedFiles && !IsStopped() && repairer->missingfilecount > 0 && !(addedSplittedFragments && res == eRepairPossible) && (g_Options->GetParScan() == Options::psExtended || g_Options->GetParScan() == Options::psDupe)) @@ -642,12 +642,12 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) Cleanup(); return psFailed; } - + status = psFailed; - + if (res == eSuccess || !m_hasDamagedFiles) { - PrintMessage(Message::mkInfo, "Repair not needed for %s", m_infoName); + PrintMessage(Message::mkInfo, "Repair not needed for %s", m_infoName); status = psRepairNotNeeded; } else if (res == eRepairPossible) @@ -670,7 +670,7 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) res = repairer->Process(true); if (res == eSuccess) { - PrintMessage(Message::mkInfo, "Successfully repaired %s", m_infoName); + PrintMessage(Message::mkInfo, "Successfully repaired %s", m_infoName); status = psRepaired; StatDupeSources(&m_dupeSources); DeleteLeftovers(); @@ -678,10 +678,10 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) } else { - PrintMessage(Message::mkInfo, "Repair possible for %s", m_infoName); + PrintMessage(Message::mkInfo, "Repair possible for %s", m_infoName); } } - + if (m_cancelled) { if (m_stage >= ptRepairing) @@ -705,7 +705,7 @@ ParChecker::EStatus ParChecker::RunParCheck(const char* parFilename) } PrintMessage(Message::mkError, "Repair failed for %s: %s", m_infoName, m_errMsg ? m_errMsg : ""); } - + Cleanup(); return status; } @@ -765,7 +765,7 @@ bool ParChecker::LoadMainParBak() while (!IsStopped()) { m_queuedParFilesMutex.Lock(); - bool hasMorePars = !m_queuedParFiles.empty(); + bool hasMorePars = !m_queuedParFiles.empty(); for (FileList::iterator it = m_queuedParFiles.begin(); it != m_queuedParFiles.end() ;it++) { free(*it); @@ -833,11 +833,11 @@ int ParChecker::ProcessMorePars() { PrintMessage(Message::mkInfo, "Need more %i par-block(s) for %s", missingblockcount, m_infoName); } - + m_queuedParFilesMutex.Lock(); - bool hasMorePars = !m_queuedParFiles.empty(); + bool hasMorePars = !m_queuedParFiles.empty(); m_queuedParFilesMutex.Unlock(); - + if (!hasMorePars) { int blockFound = 0; @@ -849,20 +849,20 @@ int ParChecker::ProcessMorePars() m_fileProgress = 0; UpdateProgress(); } - + m_queuedParFilesMutex.Lock(); hasMorePars = !m_queuedParFiles.empty(); m_queuedParFilesChanged = false; m_queuedParFilesMutex.Unlock(); - + if (!requested && !hasMorePars) { m_errMsg = (char*)malloc(1024); snprintf(m_errMsg, 1024, "not enough par-blocks, %i block(s) needed, but %i block(s) available", missingblockcount, blockFound); - m_errMsg[1024-1] = '\0'; + m_errMsg[1024-1] = '\0'; break; } - + if (!hasMorePars) { // wait until new files are added by "AddParFile" or a change is signaled by "QueueChanged" @@ -900,7 +900,7 @@ bool ParChecker::LoadMorePars() moreFiles.assign(m_queuedParFiles.begin(), m_queuedParFiles.end()); m_queuedParFiles.clear(); m_queuedParFilesMutex.Unlock(); - + for (FileList::iterator it = moreFiles.begin(); it != moreFiles.end() ;it++) { char* parFilename = *it; @@ -1339,7 +1339,7 @@ void ParChecker::WriteBrokenLog(EStatus status) char brokenLogName[1024]; snprintf(brokenLogName, 1024, "%s%c_brokenlog.txt", m_destDir, (int)PATH_SEPARATOR); brokenLogName[1024-1] = '\0'; - + if (status != psRepairNotNeeded || Util::FileExists(brokenLogName)) { FILE* file = fopen(brokenLogName, FOPEN_AB); @@ -1380,7 +1380,7 @@ void ParChecker::WriteBrokenLog(EStatus status) void ParChecker::SaveSourceList() { // Buliding a list of DiskFile-objects, marked as source-files - + for (std::vector::iterator it = ((Repairer*)m_repairer)->sourcefiles.begin(); it != ((Repairer*)m_repairer)->sourcefiles.end(); it++) { @@ -1404,7 +1404,7 @@ void ParChecker::DeleteLeftovers() // After repairing check if all DiskFile-objects saved by "SaveSourceList()" have // corresponding target-files. If not - the source file was replaced. In this case // the DiskFile-object points to the renamed bak-file, which we can delete. - + for (SourceList::iterator it = m_sourceFiles.begin(); it != m_sourceFiles.end(); it++) { DiskFile* sourceFile = (DiskFile*)*it; diff --git a/daemon/postprocess/ParChecker.h b/daemon/postprocess/ParChecker.h index b61fc3f5..80dd8b7e 100644 --- a/daemon/postprocess/ParChecker.h +++ b/daemon/postprocess/ParChecker.h @@ -109,7 +109,7 @@ public: typedef std::vector ValidBlocks; friend class Repairer; - + private: char* m_infoName; char* m_destDir; diff --git a/daemon/postprocess/ParCoordinator.cpp b/daemon/postprocess/ParCoordinator.cpp index e7f00c4b..9dfacbab 100644 --- a/daemon/postprocess/ParCoordinator.cpp +++ b/daemon/postprocess/ParCoordinator.cpp @@ -221,7 +221,7 @@ void ParCoordinator::PostParRenamer::PrintMessage(Message::EKind kind, const cha vsnprintf(text, 1024, format, args); va_end(args); text[1024-1] = '\0'; - + m_postInfo->GetNzbInfo()->AddMessage(kind, text); } @@ -305,7 +305,7 @@ void ParCoordinator::PausePars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo) { debug("ParCoordinator: Pausing pars"); - downloadQueue->EditEntry(nzbInfo->GetId(), + downloadQueue->EditEntry(nzbInfo->GetId(), DownloadQueue::eaGroupPauseExtraPars, 0, NULL); } @@ -447,23 +447,23 @@ void ParCoordinator::ParCheckCompleted() bool ParCoordinator::RequestMorePars(NzbInfo* nzbInfo, const char* parFilename, int blockNeeded, int* blockFoundOut) { DownloadQueue* downloadQueue = DownloadQueue::Lock(); - + Blocks blocks; blocks.clear(); int blockFound = 0; - int curBlockFound = 0; + int curBlockFound = 0; FindPars(downloadQueue, nzbInfo, parFilename, &blocks, true, true, &curBlockFound); - blockFound += curBlockFound; + blockFound += curBlockFound; if (blockFound < blockNeeded) { FindPars(downloadQueue, nzbInfo, parFilename, &blocks, true, false, &curBlockFound); - blockFound += curBlockFound; + blockFound += curBlockFound; } if (blockFound < blockNeeded) { FindPars(downloadQueue, nzbInfo, parFilename, &blocks, false, false, &curBlockFound); - blockFound += curBlockFound; + blockFound += curBlockFound; } if (blockFound >= blockNeeded) @@ -473,7 +473,7 @@ bool ParCoordinator::RequestMorePars(NzbInfo* nzbInfo, const char* parFilename, // if par-collection was built exponentially and all par-files present, // this step selects par-files with exact number of blocks we need. while (blockNeeded > 0) - { + { BlockInfo* bestBlockInfo = NULL; for (Blocks::iterator it = blocks.begin(); it != blocks.end(); it++) { @@ -501,11 +501,11 @@ bool ParCoordinator::RequestMorePars(NzbInfo* nzbInfo, const char* parFilename, break; } } - + // 2. then unpause other files - // this step only needed if the par-collection was built not exponentially + // this step only needed if the par-collection was built not exponentially // or not all par-files present (or some of them were corrupted) - // this step is not optimal, but we hope, that the first step will work good + // this step is not optimal, but we hope, that the first step will work good // in most cases and we will not need the second step often while (blockNeeded > 0) { @@ -552,8 +552,8 @@ bool ParCoordinator::RequestMorePars(NzbInfo* nzbInfo, const char* parFilename, void ParCoordinator::FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, const char* parFilename, Blocks* blocks, bool strictParName, bool exactParName, int* blockFound) { - *blockFound = 0; - + *blockFound = 0; + // extract base name from m_szParFilename (trim .par2-extension and possible .vol-part) char* baseParFilename = Util::BaseFileName(parFilename); char mainBaseFilename[1024]; @@ -561,7 +561,7 @@ void ParCoordinator::FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, co if (!ParParser::ParseParFilename(baseParFilename, &mainBaseLen, NULL)) { // should not happen - nzbInfo->PrintMessage(Message::mkError, "Internal error: could not parse filename %s", baseParFilename); + nzbInfo->PrintMessage(Message::mkError, "Internal error: could not parse filename %s", baseParFilename); return; } int maxlen = mainBaseLen < 1024 ? mainBaseLen : 1024 - 1; @@ -591,7 +591,7 @@ void ParCoordinator::FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, co strncpy(loFileName, fileInfo->GetFilename(), 1024); loFileName[1024-1] = '\0'; for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - + char candidateFileName[1024]; snprintf(candidateFileName, 1024, "%s.par2", mainBaseFilename); candidateFileName[1024-1] = '\0'; @@ -603,8 +603,8 @@ void ParCoordinator::FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, co } } - bool alreadyAdded = false; - // check if file is not in the list already + bool alreadyAdded = false; + // check if file is not in the list already if (useFile) { for (Blocks::iterator it = blocks->begin(); it != blocks->end(); it++) @@ -614,15 +614,15 @@ void ParCoordinator::FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, co { alreadyAdded = true; break; - } - } + } + } } - + // if it is a par2-file with blocks and it was from the same NZB-request // and it belongs to the same file collection (same base name), // then OK, we can use it - if (useFile && !alreadyAdded) - { + if (useFile && !alreadyAdded) + { BlockInfo* blockInfo = new BlockInfo(); blockInfo->m_fileInfo = fileInfo; blockInfo->m_blockCount = blockCount; @@ -644,7 +644,7 @@ void ParCoordinator::UpdateParCheckProgress() } postInfo->SetFileProgress(m_parChecker.GetFileProgress()); postInfo->SetStageProgress(m_parChecker.GetStageProgress()); - PostInfo::EStage StageKind[] = { PostInfo::ptLoadingPars, PostInfo::ptVerifyingSources, PostInfo::ptRepairing, PostInfo::ptVerifyingRepaired }; + PostInfo::EStage StageKind[] = { PostInfo::ptLoadingPars, PostInfo::ptVerifyingSources, PostInfo::ptRepairing, PostInfo::ptVerifyingRepaired }; PostInfo::EStage stage = StageKind[m_parChecker.GetStage()]; time_t current = time(NULL); @@ -672,7 +672,7 @@ void ParCoordinator::UpdateParCheckProgress() (g_Options->GetParTimeLimit() <= 5 && current - postInfo->GetStageTime() > 1 * 60))) { // first five (or one) minutes elapsed, now can check the estimated time - int estimatedRepairTime = (int)((current - postInfo->GetStartTime()) * 1000 / + int estimatedRepairTime = (int)((current - postInfo->GetStartTime()) * 1000 / (postInfo->GetStageProgress() > 0 ? postInfo->GetStageProgress() : 1)); if (estimatedRepairTime > g_Options->GetParTimeLimit() * 60) { @@ -689,7 +689,7 @@ void ParCoordinator::UpdateParCheckProgress() } DownloadQueue::Unlock(); - + CheckPauseState(postInfo); } @@ -702,16 +702,16 @@ void ParCoordinator::CheckPauseState(PostInfo* postInfo) time_t parTime = m_parChecker.GetParTime(); time_t repairTime = m_parChecker.GetRepairTime(); time_t waitTime = time(NULL); - + // wait until Post-processor is unpaused while (g_Options->GetPausePostProcess() && !postInfo->GetNzbInfo()->GetForcePriority() && !m_stopped) { usleep(50 * 1000); - + // update time stamps - + time_t delta = time(NULL) - waitTime; - + if (stageTime > 0) { postInfo->SetStageTime(stageTime + delta); @@ -735,7 +735,7 @@ void ParCoordinator::CheckPauseState(PostInfo* postInfo) void ParCoordinator::ParRenameCompleted() { DownloadQueue* downloadQueue = DownloadQueue::Lock(); - + PostInfo* postInfo = m_parRenamer.GetPostInfo(); postInfo->GetNzbInfo()->SetRenameStatus(m_parRenamer.GetStatus() == ParRenamer::psSuccess ? NzbInfo::rsSuccess : NzbInfo::rsFailure); @@ -747,7 +747,7 @@ void ParCoordinator::ParRenameCompleted() postInfo->SetWorking(false); postInfo->SetStage(PostInfo::ptQueued); - + downloadQueue->Save(); DownloadQueue::Unlock(); @@ -756,20 +756,20 @@ void ParCoordinator::ParRenameCompleted() void ParCoordinator::UpdateParRenameProgress() { DownloadQueue::Lock(); - + PostInfo* postInfo = m_parRenamer.GetPostInfo(); postInfo->SetProgressLabel(m_parRenamer.GetProgressLabel()); postInfo->SetStageProgress(m_parRenamer.GetStageProgress()); time_t current = time(NULL); - + if (postInfo->GetStage() != PostInfo::ptRenaming) { postInfo->SetStage(PostInfo::ptRenaming); postInfo->SetStageTime(current); } - + DownloadQueue::Unlock(); - + CheckPauseState(postInfo); } diff --git a/daemon/postprocess/ParCoordinator.h b/daemon/postprocess/ParCoordinator.h index 0e31b9dd..981e49be 100644 --- a/daemon/postprocess/ParCoordinator.h +++ b/daemon/postprocess/ParCoordinator.h @@ -37,7 +37,7 @@ #include "DupeMatcher.h" #endif -class ParCoordinator +class ParCoordinator { private: #ifndef DISABLE_PARCHECK @@ -86,7 +86,7 @@ private: public: PostInfo* GetPostInfo() { return m_postInfo; } void SetPostInfo(PostInfo* postInfo) { m_postInfo = postInfo; } - + friend class ParCoordinator; }; @@ -110,7 +110,7 @@ private: }; typedef std::list Blocks; - + enum EJobKind { jkParCheck, @@ -139,7 +139,7 @@ public: #ifndef DISABLE_PARCHECK bool AddPar(FileInfo* fileInfo, bool deleted); - void FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, const char* parFilename, + void FindPars(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, const char* parFilename, Blocks* blocks, bool strictParName, bool exactParName, int* blockFound); void StartParCheckJob(PostInfo* postInfo); void StartParRenameJob(PostInfo* postInfo); diff --git a/daemon/postprocess/ParParser.cpp b/daemon/postprocess/ParParser.cpp index dcbf0e75..fc901cc6 100644 --- a/daemon/postprocess/ParParser.cpp +++ b/daemon/postprocess/ParParser.cpp @@ -147,6 +147,6 @@ bool ParParser::ParseParFilename(const char* parFilename, int* baseNameLen, int* { *blocks = blockcnt; } - + return true; } diff --git a/daemon/postprocess/ParRenamer.cpp b/daemon/postprocess/ParRenamer.cpp index 2fca128c..394904b0 100644 --- a/daemon/postprocess/ParRenamer.cpp +++ b/daemon/postprocess/ParRenamer.cpp @@ -99,7 +99,7 @@ ParRenamer::~ParRenamer() void ParRenamer::Cleanup() { ClearHashList(); - + for (DirList::iterator it = m_dirList.begin(); it != m_dirList.end(); it++) { free(*it); @@ -197,14 +197,14 @@ void ParRenamer::BuildDirList(const char* destDir) char* fullFilename = (char*)malloc(1024); DirBrowser* dirBrowser = new DirBrowser(destDir); - + while (const char* filename = dirBrowser->Next()) { if (strcmp(filename, ".") && strcmp(filename, "..") && !m_cancelled) { snprintf(fullFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, filename); fullFilename[1024-1] = '\0'; - + if (Util::DirectoryExists(fullFilename)) { BuildDirList(fullFilename); @@ -215,7 +215,7 @@ void ParRenamer::BuildDirList(const char* destDir) } } } - + free(fullFilename); delete dirBrowser; } @@ -228,13 +228,13 @@ void ParRenamer::LoadParFiles(const char* destDir) for (ParParser::ParFileList::iterator it = parFileList.begin(); it != parFileList.end(); it++) { char* parFilename = *it; - + char fullParFilename[1024]; snprintf(fullParFilename, 1024, "%s%c%s", destDir, PATH_SEPARATOR, parFilename); fullParFilename[1024-1] = '\0'; - + LoadParFile(fullParFilename); - + free(*it); } } @@ -256,7 +256,7 @@ void ParRenamer::LoadParFile(const char* parFilename) { break; } - + Par2RepairerSourceFile* sourceFile = (*it).second; if (!sourceFile || !sourceFile->GetDescriptionPacket()) { @@ -289,7 +289,7 @@ void ParRenamer::CheckFiles(const char* destDir, bool renamePars) m_stageProgress = m_curFile * 1000 / m_fileCount; UpdateProgress(); m_curFile++; - + if (renamePars) { CheckParFile(destDir, fullFilename); @@ -349,7 +349,7 @@ void ParRenamer::CheckRegularFile(const char* destDir, const char* filename) debug("Computing hash for %s", filename); const int blockSize = 16*1024; - + FILE* file = fopen(filename, FOPEN_RB); if (!file) { @@ -358,9 +358,9 @@ void ParRenamer::CheckRegularFile(const char* destDir, const char* filename) } // load first 16K of the file into buffer - + void* buffer = malloc(blockSize); - + int readBytes = fread(buffer, 1, blockSize, file); int error = ferror(file); if (readBytes != blockSize && error) @@ -368,18 +368,18 @@ void ParRenamer::CheckRegularFile(const char* destDir, const char* filename) PrintMessage(Message::mkError, "Could not read file %s", filename); return; } - + fclose(file); - + MD5Hash hash16k; MD5Context context; context.Update(buffer, readBytes); context.Final(hash16k); - + free(buffer); - + debug("file: %s; hash16k: %s", Util::BaseFileName(filename), hash16k.print().c_str()); - + for (FileHashList::iterator it = m_fileHashList.begin(); it != m_fileHashList.end(); it++) { FileHash* fileHash = *it; @@ -396,7 +396,7 @@ void ParRenamer::CheckRegularFile(const char* destDir, const char* filename) { RenameFile(filename, dstFilename); } - + break; } } diff --git a/daemon/postprocess/ParRenamer.h b/daemon/postprocess/ParRenamer.h index 4ec6a9c9..ced0844c 100644 --- a/daemon/postprocess/ParRenamer.h +++ b/daemon/postprocess/ParRenamer.h @@ -41,7 +41,7 @@ public: psFailed, psSuccess }; - + class FileHash { private: @@ -60,7 +60,7 @@ public: typedef std::deque FileHashList; typedef std::deque DirList; - + private: char* m_infoName; char* m_destDir; diff --git a/daemon/postprocess/PrePostProcessor.cpp b/daemon/postprocess/PrePostProcessor.cpp index a1455ab0..487dcaf2 100644 --- a/daemon/postprocess/PrePostProcessor.cpp +++ b/daemon/postprocess/PrePostProcessor.cpp @@ -118,7 +118,7 @@ void PrePostProcessor::Stop() if (m_curJob && m_curJob->GetPostInfo() && (m_curJob->GetPostInfo()->GetStage() == PostInfo::ptUnpacking || - m_curJob->GetPostInfo()->GetStage() == PostInfo::ptExecutingScript) && + m_curJob->GetPostInfo()->GetStage() == PostInfo::ptExecutingScript) && m_curJob->GetPostInfo()->GetPostThread()) { Thread* postThread = m_curJob->GetPostInfo()->GetPostThread(); @@ -360,7 +360,7 @@ void PrePostProcessor::DeleteCleanup(NzbInfo* nzbInfo) remove(fullFilename); } } - + // delete old directory (if empty) if (Util::DirEmpty(nzbInfo->GetDestDir())) { @@ -417,7 +417,7 @@ void PrePostProcessor::CheckPostQueue() postInfo->SetStage(PostInfo::ptQueued); } } - + #endif if (postInfo->GetDeleted()) { @@ -442,7 +442,7 @@ void PrePostProcessor::CheckPostQueue() } } } - + DownloadQueue::Unlock(); } @@ -576,7 +576,7 @@ void PrePostProcessor::StartJob(DownloadQueue* downloadQueue, PostInfo* postInfo postInfo->GetNzbInfo()->GetUnpackStatus() != NzbInfo::usPassword) || (postInfo->GetNzbInfo()->GetUnpackStatus() == NzbInfo::usSuccess && postInfo->GetNzbInfo()->GetParStatus() != NzbInfo::psFailure) || - ((postInfo->GetNzbInfo()->GetUnpackStatus() == NzbInfo::usNone || + ((postInfo->GetNzbInfo()->GetUnpackStatus() == NzbInfo::usNone || postInfo->GetNzbInfo()->GetUnpackStatus() == NzbInfo::usSkipped) && (postInfo->GetNzbInfo()->GetParStatus() == NzbInfo::psNone || postInfo->GetNzbInfo()->GetParStatus() == NzbInfo::psSkipped) && diff --git a/daemon/postprocess/Unpack.cpp b/daemon/postprocess/Unpack.cpp index 839ff307..972f748c 100644 --- a/daemon/postprocess/Unpack.cpp +++ b/daemon/postprocess/Unpack.cpp @@ -137,7 +137,7 @@ void UnpackController::Run() strncpy(m_password, parameter->GetValue(), 1024-1); m_password[1024-1] = '\0'; } - + DownloadQueue::Unlock(); snprintf(m_infoName, 1024, "unpack for %s", m_name); @@ -207,7 +207,7 @@ void UnpackController::Run() PrintMessage(Message::mkInfo, (unpack ? "Nothing to unpack for %s" : "Unpack for %s skipped"), m_name); #ifndef DISABLE_PARCHECK - if (unpack && m_postInfo->GetNzbInfo()->GetParStatus() <= NzbInfo::psSkipped && + if (unpack && m_postInfo->GetNzbInfo()->GetParStatus() <= NzbInfo::psSkipped && m_postInfo->GetNzbInfo()->GetRenameStatus() <= NzbInfo::rsSkipped && m_hasParFiles) { RequestParCheck(false); @@ -301,7 +301,7 @@ void UnpackController::ExecuteUnpack(EUnpacker unpacker, const char* password, b void UnpackController::ExecuteUnrar(const char* password) { - // Format: + // Format: // unrar x -y -p- -o+ *.rar ./_unpack/ ParamList params; @@ -368,7 +368,7 @@ void UnpackController::ExecuteUnrar(const char* password) void UnpackController::ExecuteSevenZip(const char* password, bool multiVolumes) { - // Format: + // Format: // 7z x -y -p- -o./_unpack *.7z // OR // 7z x -y -p- -o./_unpack *.7z.001 @@ -532,7 +532,7 @@ bool UnpackController::JoinFile(const char* fragBaseName) count++; min = segNum < min || min == -1 ? segNum : min; max = segNum > max ? segNum : max; - + long long segmentSize = Util::FileSize(fullFilename); if (segmentSize != firstSegmentSize) { @@ -647,7 +647,7 @@ void UnpackController::Completed() else { #ifndef DISABLE_PARCHECK - if (!m_unpackOk && + if (!m_unpackOk && (m_postInfo->GetNzbInfo()->GetParStatus() <= NzbInfo::psSkipped || !m_postInfo->GetNzbInfo()->GetParFull()) && !m_unpackStartError && !m_unpackSpaceError && !m_unpackPasswordError && @@ -780,7 +780,7 @@ bool UnpackController::FileHasRarSignature(const char* filename) fclose(infile); } - bool rar = cnt == sizeof(fileSignature) && + bool rar = cnt == sizeof(fileSignature) && (!strcmp(rar4Signature, fileSignature) || !strcmp(rar5Signature, fileSignature)); return rar; } @@ -841,7 +841,7 @@ bool UnpackController::Cleanup() if (!m_unpackOk && m_finalDirCreated) { Util::RemoveDirectory(m_finalDir); - } + } if (m_unpackOk && ok && g_Options->GetUnpackCleanupDisk()) { @@ -955,7 +955,7 @@ void UnpackController::AddMessage(Message::EKind kind, const char* text) strncpy(msgText, text, 1024); msgText[1024-1] = '\0'; int len = strlen(text); - + // Modify unrar messages for better readability: // remove the destination path part from message "Extracting file.xxx" if (m_unpacker == upUnrar && !strncmp(text, "Unrar: Extracting ", 19) && diff --git a/daemon/queue/DiskState.cpp b/daemon/queue/DiskState.cpp index bf7c20c6..3b9be28d 100644 --- a/daemon/queue/DiskState.cpp +++ b/daemon/queue/DiskState.cpp @@ -238,7 +238,7 @@ FILE* StateFile::BeginReadTransaction() int DiskState::fscanf(FILE* infile, const char* format, ...) { char line[1024]; - if (!fgets(line, sizeof(line), infile)) + if (!fgets(line, sizeof(line), infile)) { return 0; } @@ -268,7 +268,7 @@ bool DiskState::SaveDownloadQueue(DownloadQueue* downloadQueue) StateFile stateFile("queue", 55); - if (downloadQueue->GetQueue()->empty() && + if (downloadQueue->GetQueue()->empty() && downloadQueue->GetHistory()->empty()) { stateFile.Discard(); @@ -472,7 +472,7 @@ void DiskState::SaveNzbInfo(NzbInfo* nzbInfo, FILE* outfile) fprintf(outfile, "%s\n", nzbInfo->GetQueuedFilename()); fprintf(outfile, "%s\n", nzbInfo->GetName()); fprintf(outfile, "%s\n", nzbInfo->GetCategory()); - fprintf(outfile, "%i,%i,%i,%i,%i\n", (int)nzbInfo->GetPriority(), + fprintf(outfile, "%i,%i,%i,%i,%i\n", (int)nzbInfo->GetPriority(), nzbInfo->GetPostInfo() ? (int)nzbInfo->GetPostInfo()->GetStage() + 1 : 0, (int)nzbInfo->GetDeletePaused(), (int)nzbInfo->GetManyDupeFiles(), nzbInfo->GetFeedId()); fprintf(outfile, "%i,%i,%i,%i,%i,%i,%i\n", (int)nzbInfo->GetParStatus(), (int)nzbInfo->GetUnpackStatus(), @@ -483,7 +483,7 @@ void DiskState::SaveNzbInfo(NzbInfo* nzbInfo, FILE* outfile) fprintf(outfile, "%i,%i,%i\n", nzbInfo->GetFileCount(), nzbInfo->GetParkedFileCount(), nzbInfo->GetMessageCount()); fprintf(outfile, "%i,%i\n", (int)nzbInfo->GetMinTime(), (int)nzbInfo->GetMaxTime()); - fprintf(outfile, "%i,%i,%i,%i\n", (int)nzbInfo->GetParFull(), + fprintf(outfile, "%i,%i,%i,%i\n", (int)nzbInfo->GetParFull(), nzbInfo->GetPostInfo() ? (int)nzbInfo->GetPostInfo()->GetForceParFull() : 0, nzbInfo->GetPostInfo() ? (int)nzbInfo->GetPostInfo()->GetForceRepair() : 0, nzbInfo->GetExtraParBlocks()); @@ -550,7 +550,7 @@ void DiskState::SaveNzbInfo(NzbInfo* nzbInfo, FILE* outfile) FileInfo* fileInfo = *it; if (!fileInfo->GetDeleted()) { - fprintf(outfile, "%i,%i,%i,%i\n", fileInfo->GetId(), (int)fileInfo->GetPaused(), + fprintf(outfile, "%i,%i,%i,%i\n", fileInfo->GetId(), (int)fileInfo->GetPaused(), (int)fileInfo->GetTime(), (int)fileInfo->GetExtraPriority()); } } @@ -775,7 +775,7 @@ bool DiskState::LoadNzbInfo(NzbInfo* nzbInfo, Servers* servers, FILE* infile, in if (fscanf(infile, "%i\n", &unpackCleanedUpDisk) != 1) goto error; nzbInfo->SetUnpackCleanedUpDisk((bool)unpackCleanedUpDisk); } - + int fileCount; if (fscanf(infile, "%i\n", &fileCount) != 1) goto error; nzbInfo->SetFileCount(fileCount); @@ -853,7 +853,7 @@ bool DiskState::LoadNzbInfo(NzbInfo* nzbInfo, Servers* servers, FILE* infile, in if (fscanf(infile, "%lu,%lu\n", &High, &Low) != 2) goto error; nzbInfo->SetSize(Util::JoinInt64(High, Low)); } - + if (formatVersion >= 30) { int totalArticles, successArticles, failedArticles; @@ -966,7 +966,7 @@ bool DiskState::LoadNzbInfo(NzbInfo* nzbInfo, Servers* servers, FILE* infile, in { if (!fgets(buf, sizeof(buf), infile)) goto error; if (buf[0] != 0) buf[strlen(buf)-1] = 0; // remove traling '\n' - + char* scriptName = strchr(buf, ','); if (scriptName) { @@ -993,7 +993,7 @@ bool DiskState::LoadNzbInfo(NzbInfo* nzbInfo, Servers* servers, FILE* infile, in if (!fgets(buf, sizeof(buf), infile)) goto error; } } - + if (formatVersion < 26) { NzbParameter* unpackParameter = nzbInfo->GetParameters()->Find("*Unpack:", false); @@ -1251,7 +1251,7 @@ bool DiskState::LoadFileInfo(FileInfo* fileInfo, const char * filename, bool fil { goto error; } - + if (formatVersion >= 2) { if (!fgets(buf, sizeof(buf), infile)) goto error; @@ -1270,7 +1270,7 @@ bool DiskState::LoadFileInfo(FileInfo* fileInfo, const char * filename, bool fil if (fscanf(infile, "%i\n", &filenameConfirmed) != 1) goto error; if (fileSummary) fileInfo->SetFilenameConfirmed(filenameConfirmed); } - + unsigned long High, Low; if (fscanf(infile, "%lu,%lu\n", &High, &Low) != 2) goto error; if (fileSummary) fileInfo->SetSize(Util::JoinInt64(High, Low)); @@ -1294,7 +1294,7 @@ bool DiskState::LoadFileInfo(FileInfo* fileInfo, const char * filename, bool fil if (fileSummary) fileInfo->SetTotalArticles(totalArticles); if (fileSummary) fileInfo->SetMissedArticles(missedArticles); } - + int size; if (fscanf(infile, "%i\n", &size) != 1) goto error; for (int i = 0; i < size; i++) @@ -1846,7 +1846,7 @@ bool DiskState::LoadDupInfo(DupInfo* dupInfo, FILE* infile, int formatVersion) unsigned long High, Low; unsigned int fullContentHash, filteredContentHash = 0; int dupeScore, dupe = 0, dupeMode = 0; - + if (formatVersion >= 39) { if (fscanf(infile, "%i,%lu,%lu,%u,%u,%i,%i\n", &status, &High, &Low, &fullContentHash, &filteredContentHash, &dupeScore, &dupeMode) != 7) goto error; @@ -1924,7 +1924,7 @@ bool DiskState::LoadHistory(DownloadQueue* downloadQueue, NzbList* nzbList, Serv HistoryInfo::EKind kind = HistoryInfo::hkNzb; int id = 0; int time; - + if (formatVersion >= 33) { int kindval = 0; @@ -1964,7 +1964,7 @@ bool DiskState::LoadHistory(DownloadQueue* downloadQueue, NzbList* nzbList, Serv } historyInfo = new HistoryInfo(nzbInfo); - + if (formatVersion < 28 && nzbInfo->GetParStatus() == 0 && nzbInfo->GetUnpackStatus() == 0 && nzbInfo->GetMoveStatus() == 0) { @@ -2975,7 +2975,7 @@ void DiskState::AppendNzbMessage(int nzbId, Message::EKind kind, const char* tex time_t tm = time(NULL); time_t rawtime = tm + g_Options->GetTimeCorrection(); - + char time[50]; #ifdef HAVE_CTIME_R_3 ctime_r(&rawtime, time, 50); @@ -3048,7 +3048,7 @@ void DiskState::LoadNzbMessages(int nzbId, MessageList* messages) else if (!strncmp(kindStr, "DEBUG", 5)) { kind = Message::mkDebug; - } + } // text p = strchr(p + 1, '\t'); diff --git a/daemon/queue/DiskState.h b/daemon/queue/DiskState.h index da5d6ad8..1f46a80d 100644 --- a/daemon/queue/DiskState.h +++ b/daemon/queue/DiskState.h @@ -19,7 +19,7 @@ * * $Revision$ * $Date$ - * + * */ diff --git a/daemon/queue/DownloadInfo.cpp b/daemon/queue/DownloadInfo.cpp index 69b7afb6..a2e2f7b84 100644 --- a/daemon/queue/DownloadInfo.cpp +++ b/daemon/queue/DownloadInfo.cpp @@ -133,7 +133,7 @@ NzbParameter* NzbParameterList::Find(const char* name, bool caseSensitive) return parameter; } } - + return NULL; } @@ -144,7 +144,7 @@ void NzbParameterList::CopyFrom(NzbParameterList* sourceParameters) NzbParameter* parameter = *it; SetParameter(parameter->GetName(), parameter->GetValue()); } -} +} ScriptStatus::ScriptStatus(const char* name, EStatus status) @@ -192,7 +192,7 @@ ScriptStatus::EStatus ScriptStatusList::CalcTotalStatus() status = scriptStatus->GetStatus(); } } - + return status; } @@ -623,7 +623,7 @@ int NzbInfo::CalcCriticalHealth(bool allowEstimation) { // using empirical critical health 85%, to avoid false alarms for downloads with renamed par-files criticalHealth = 850; - } + } return criticalHealth; } @@ -635,8 +635,8 @@ void NzbInfo::UpdateMinMaxTime() bool first = true; for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); it++) - { - FileInfo* fileInfo = *it; + { + FileInfo* fileInfo = *it; if (first) { m_minTime = fileInfo->GetTime(); diff --git a/daemon/queue/DownloadInfo.h b/daemon/queue/DownloadInfo.h index b92dfd6a..caae3a70 100644 --- a/daemon/queue/DownloadInfo.h +++ b/daemon/queue/DownloadInfo.h @@ -66,7 +66,7 @@ public: soAdd, soSubtract }; - + public: ~ServerStatList(); void StatOp(int serverId, int successArticles, int failedArticles, EStatOperation statOperation); @@ -84,7 +84,7 @@ public: aiFinished, aiFailed }; - + private: int m_partNumber; char* m_messageId; @@ -227,7 +227,7 @@ public: void SetPartialChanged(bool partialChanged) { m_partialChanged = partialChanged; } ServerStatList* GetServerStats() { return &m_serverStats; } }; - + typedef std::deque FileListBase; class FileList : public FileListBase @@ -314,7 +314,7 @@ private: EStatus m_status; friend class ScriptStatusList; - + public: ScriptStatus(const char* name, EStatus status); ~ScriptStatus(); @@ -739,7 +739,7 @@ private: time_t m_startTime; time_t m_stageTime; Thread* m_postThread; - + ParredFiles m_parredFiles; public: diff --git a/daemon/queue/DupeCoordinator.cpp b/daemon/queue/DupeCoordinator.cpp index acb69261..4294e832 100644 --- a/daemon/queue/DupeCoordinator.cpp +++ b/daemon/queue/DupeCoordinator.cpp @@ -60,15 +60,15 @@ bool DupeCoordinator::SameNameOrKey(const char* name1, const char* dupeKey1, /** Check if the title was already downloaded or is already queued: - - if there is a duplicate with exactly same content (via hash-check) - in queue or in history - the new item is skipped; + - if there is a duplicate with exactly same content (via hash-check) + in queue or in history - the new item is skipped; - if there is a duplicate marked as good in history - the new item is skipped; - if there is a duplicate with success-status in dup-history but - there are no duplicates in recent history - the new item is skipped; + there are no duplicates in recent history - the new item is skipped; - if queue has a duplicate with the same or higher score - the new item - is moved to history as dupe-backup; + is moved to history as dupe-backup; - if queue has a duplicate with lower score - the existing item is moved - to history as dupe-backup (unless it is in post-processing stage) and + to history as dupe-backup (unless it is in post-processing stage) and the new item is added to queue; - if queue doesn't have duplicates - the new item is added to queue. */ @@ -85,7 +85,7 @@ void DupeCoordinator::NzbFound(DownloadQueue* downloadQueue, NzbInfo* nzbInfo) (nzbInfo->GetFilteredContentHash() > 0 && nzbInfo->GetFilteredContentHash() == queuedNzbInfo->GetFilteredContentHash()); - // if there is a duplicate with exactly same content (via hash-check) + // if there is a duplicate with exactly same content (via hash-check) // in queue - the new item is skipped if (queuedNzbInfo != nzbInfo && sameContent && nzbInfo->GetKind() == NzbInfo::nkNzb) { @@ -328,7 +328,7 @@ void DupeCoordinator::NzbFound(DownloadQueue* downloadQueue, NzbInfo* nzbInfo) /** - if download of an item fails and there are duplicates in history - - return the best duplicate from history to queue for download; + return the best duplicate from history to queue for download; - if download of an item completes successfully - nothing extra needs to be done; */ void DupeCoordinator::NzbCompleted(DownloadQueue* downloadQueue, NzbInfo* nzbInfo) @@ -438,7 +438,7 @@ void DupeCoordinator::HistoryMark(DownloadQueue* downloadQueue, HistoryInfo* his char nzbName[1024]; historyInfo->GetName(nzbName, 1024); - const char* markStatusName[] = { "NONE", "bad", "good", "success" }; + const char* markStatusName[] = { "NONE", "bad", "good", "success" }; info("Marking %s as %s", nzbName, markStatusName[markStatus]); diff --git a/daemon/queue/HistoryCoordinator.cpp b/daemon/queue/HistoryCoordinator.cpp index 11fd8c53..5c15885c 100644 --- a/daemon/queue/HistoryCoordinator.cpp +++ b/daemon/queue/HistoryCoordinator.cpp @@ -95,7 +95,7 @@ void HistoryCoordinator::ServiceWork() historyInfo->GetName(niceName, 1024); downloadQueue->GetHistory()->erase(downloadQueue->GetHistory()->end() - 1 - index); - + if (historyInfo->GetKind() == HistoryInfo::hkNzb) { DeleteDiskFiles(historyInfo->GetNzbInfo()); @@ -142,7 +142,7 @@ void HistoryCoordinator::DeleteDiskFiles(NzbInfo* nzbInfo) // with "|"-character (for merged groups) char* filename = strdup(nzbInfo->GetQueuedFilename()); char* end = filename - 1; - + while (end) { char* name1 = end + 1; @@ -673,7 +673,7 @@ void HistoryCoordinator::HistorySetDupeParam(HistoryInfo* historyInfo, DownloadQ if (historyInfo->GetKind() == HistoryInfo::hkNzb || historyInfo->GetKind() == HistoryInfo::hkUrl) { - switch (action) + switch (action) { case DownloadQueue::eaHistorySetDupeKey: historyInfo->GetNzbInfo()->SetDupeKey(text); @@ -710,7 +710,7 @@ void HistoryCoordinator::HistorySetDupeParam(HistoryInfo* historyInfo, DownloadQ } else if (historyInfo->GetKind() == HistoryInfo::hkDup) { - switch (action) + switch (action) { case DownloadQueue::eaHistorySetDupeKey: historyInfo->GetDupInfo()->SetDupeKey(text); diff --git a/daemon/queue/NzbFile.cpp b/daemon/queue/NzbFile.cpp index 1c4fce1b..f8cabfbf 100644 --- a/daemon/queue/NzbFile.cpp +++ b/daemon/queue/NzbFile.cpp @@ -37,7 +37,7 @@ #include #ifdef WIN32 #include -#import named_guids +#import named_guids using namespace MSXML; #else #include @@ -56,9 +56,9 @@ using namespace MSXML; NzbFile::NzbFile(const char* fileName, const char* category) { - debug("Creating NZBFile"); + debug("Creating NZBFile"); - m_fileName = strdup(fileName); + m_fileName = strdup(fileName); m_password = NULL; m_nzbInfo = new NzbInfo(); m_nzbInfo->SetFilename(fileName); @@ -76,11 +76,11 @@ NzbFile::NzbFile(const char* fileName, const char* category) NzbFile::~NzbFile() { - debug("Destroying NZBFile"); + debug("Destroying NZBFile"); - // Cleanup - free(m_fileName); - free(m_password); + // Cleanup + free(m_fileName); + free(m_password); #ifndef WIN32 delete m_fileInfo; @@ -92,7 +92,7 @@ NzbFile::~NzbFile() void NzbFile::LogDebugInfo() { - info(" NZBFile %s", m_fileName); + info(" NZBFile %s", m_fileName); } void NzbFile::AddArticle(FileInfo* fileInfo, ArticleInfo* articleInfo) @@ -193,7 +193,7 @@ void NzbFile::ParseSubject(FileInfo* fileInfo, bool TryQuotes) if (TryQuotes) { - // try to use the filename in quatation marks + // try to use the filename in quatation marks char* p = subject; char* start = strchr(p, '\"'); if (start) @@ -217,7 +217,7 @@ void NzbFile::ParseSubject(FileInfo* fileInfo, bool TryQuotes) } } - // tokenize subject, considering spaces as separators and quotation + // tokenize subject, considering spaces as separators and quotation // marks as non separatable token delimiters. // then take the last token containing dot (".") as a filename @@ -304,8 +304,8 @@ void NzbFile::ParseSubject(FileInfo* fileInfo, bool TryQuotes) bool NzbFile::HasDuplicateFilenames() { for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) - { - FileInfo* fileInfo1 = *it; + { + FileInfo* fileInfo1 = *it; int dupe = 1; for (FileList::iterator it2 = it + 1; it2 != m_nzbInfo->GetFileList()->end(); it2++) { @@ -319,15 +319,15 @@ bool NzbFile::HasDuplicateFilenames() // If more than two files have the same parsed filename but different subjects, // this means, that the parsing was not correct. - // in this case we take subjects as filenames to prevent + // in this case we take subjects as filenames to prevent // false "duplicate files"-alarm. - // It's Ok for just two files to have the same filename, this is + // It's Ok for just two files to have the same filename, this is // an often case by posting-errors to repost bad files if (dupe > 2 || (dupe == 2 && m_nzbInfo->GetFileList()->size() == 2)) { return true; } - } + } return false; } @@ -338,13 +338,13 @@ bool NzbFile::HasDuplicateFilenames() void NzbFile::BuildFilenames() { for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) - { - FileInfo* fileInfo = *it; + { + FileInfo* fileInfo = *it; ParseSubject(fileInfo, true); } if (HasDuplicateFilenames()) - { + { for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { FileInfo* fileInfo = *it; @@ -353,14 +353,14 @@ void NzbFile::BuildFilenames() } if (HasDuplicateFilenames()) - { + { m_nzbInfo->SetManyDupeFiles(true); for (FileList::iterator it = m_nzbInfo->GetFileList()->begin(); it != m_nzbInfo->GetFileList()->end(); it++) { FileInfo* fileInfo = *it; fileInfo->SetFilename(fileInfo->GetSubject()); } - } + } } bool CompareFileInfo(FileInfo* first, FileInfo* second) @@ -472,30 +472,30 @@ void NzbFile::ProcessFiles() */ void NzbFile::ReadPassword() { - FILE* file = fopen(m_fileName, FOPEN_RB); - if (!file) - { - return; - } + FILE* file = fopen(m_fileName, FOPEN_RB); + if (!file) + { + return; + } - // obtain file size. - fseek(file , 0 , SEEK_END); - int size = (int)ftell(file); - rewind(file); + // obtain file size. + fseek(file , 0 , SEEK_END); + int size = (int)ftell(file); + rewind(file); // reading first 4KB of the file - // allocate memory to contain the whole file. - char* buf = (char*)malloc(4096); + // allocate memory to contain the whole file. + char* buf = (char*)malloc(4096); size = size < 4096 ? size : 4096; - // copy the file into the buffer. - fread(buf, 1, size, file); + // copy the file into the buffer. + fread(buf, 1, size, file); - fclose(file); + fclose(file); - buf[size-1] = '\0'; + buf[size-1] = '\0'; char* metaPassword = strstr(buf, ""); if (metaPassword) @@ -517,18 +517,18 @@ void NzbFile::ReadPassword() #ifdef WIN32 bool NzbFile::Parse() { - CoInitialize(NULL); + CoInitialize(NULL); HRESULT hr; MSXML::IXMLDOMDocumentPtr doc; hr = doc.CreateInstance(MSXML::CLSID_DOMDocument); - if (FAILED(hr)) - { - return false; - } + if (FAILED(hr)) + { + return false; + } - // Load the XML document file... + // Load the XML document file... doc->put_resolveExternals(VARIANT_FALSE); doc->put_validateOnParse(VARIANT_FALSE); doc->put_async(VARIANT_FALSE); @@ -561,7 +561,7 @@ bool NzbFile::Parse() return false; } - if (!ParseNzb(doc)) + if (!ParseNzb(doc)) { return false; } @@ -578,7 +578,7 @@ bool NzbFile::Parse() ProcessFiles(); - return true; + return true; } void NzbFile::EncodeUrl(const char* filename, char* url, int bufLen) @@ -630,7 +630,7 @@ bool NzbFile::ParseNzb(IUnknown* nzb) MSXML::IXMLDOMNodePtr attribute = node->Getattributes()->getNamedItem("subject"); if (!attribute) return false; _bstr_t subject(attribute->Gettext()); - FileInfo* fileInfo = new FileInfo(); + FileInfo* fileInfo = new FileInfo(); fileInfo->SetSubject(subject); attribute = node->Getattributes()->getNamedItem("date"); @@ -653,8 +653,8 @@ bool NzbFile::ParseNzb(IUnknown* nzb) { MSXML::IXMLDOMNodePtr node = segmentList->Getitem(g); _bstr_t bid = node->Gettext(); - char id[2048]; - snprintf(id, 2048, "<%s>", (const char*)bid); + char id[2048]; + snprintf(id, 2048, "<%s>", (const char*)bid); MSXML::IXMLDOMNodePtr attribute = node->Getattributes()->getNamedItem("number"); if (!attribute) return false; @@ -696,8 +696,8 @@ bool NzbFile::Parse() m_ignoreNextError = false; int ret = xmlSAXUserParseFile(&SAX_handler, this, m_fileName); - - if (ret != 0) + + if (ret != 0) { char messageText[1024]; snprintf(messageText, 1024, "Error parsing nzb-file %s", Util::BaseFileName(m_fileName)); @@ -732,7 +732,7 @@ void NzbFile::Parse_StartElement(const char *name, const char **atts) m_tagContent = NULL; m_tagContentLen = 0; } - + if (!strcmp("file", name)) { m_fileInfo = new FileInfo(); @@ -740,14 +740,14 @@ void NzbFile::Parse_StartElement(const char *name, const char **atts) if (!atts) { - m_nzbInfo->AddMessage(Message::mkWarning, tagAttrMessage); + m_nzbInfo->AddMessage(Message::mkWarning, tagAttrMessage); return; } - for (int i = 0; atts[i]; i += 2) - { - const char* attrname = atts[i]; - const char* attrvalue = atts[i + 1]; + for (int i = 0; atts[i]; i += 2) + { + const char* attrname = atts[i]; + const char* attrvalue = atts[i + 1]; if (!strcmp("subject", attrname)) { m_fileInfo->SetSubject(attrvalue); @@ -775,10 +775,10 @@ void NzbFile::Parse_StartElement(const char *name, const char **atts) long long lsize = -1; int partNumber = -1; - for (int i = 0; atts[i]; i += 2) - { - const char* attrname = atts[i]; - const char* attrvalue = atts[i + 1]; + for (int i = 0; atts[i]; i += 2) + { + const char* attrname = atts[i]; + const char* attrvalue = atts[i + 1]; if (!strcmp("bytes", attrname)) { lsize = atol(attrvalue); @@ -825,7 +825,7 @@ void NzbFile::Parse_EndElement(const char *name) // error: bad nzb-file return; } - + m_fileInfo->GetGroups()->push_back(m_tagContent); m_tagContent = NULL; m_tagContentLen = 0; @@ -871,7 +871,7 @@ void NzbFile::SAX_EndElement(NzbFile* file, const char *name) void NzbFile::SAX_characters(NzbFile* file, const char * xmlstr, int len) { char* str = (char*)xmlstr; - + // trim starting blanks int off = 0; for (int i = 0; i < len; i++) @@ -886,9 +886,9 @@ void NzbFile::SAX_characters(NzbFile* file, const char * xmlstr, int len) break; } } - + int newlen = len - off; - + // trim ending blanks for (int i = len - 1; i >= off; i--) { @@ -902,7 +902,7 @@ void NzbFile::SAX_characters(NzbFile* file, const char * xmlstr, int len) break; } } - + if (newlen > 0) { // interpret tag content @@ -929,13 +929,13 @@ void NzbFile::SAX_error(NzbFile* file, const char *msg, ...) file->m_ignoreNextError = false; return; } - - va_list argp; - va_start(argp, msg); - char errMsg[1024]; - vsnprintf(errMsg, sizeof(errMsg), msg, argp); - errMsg[1024-1] = '\0'; - va_end(argp); + + va_list argp; + va_start(argp, msg); + char errMsg[1024]; + vsnprintf(errMsg, sizeof(errMsg), msg, argp); + errMsg[1024-1] = '\0'; + va_end(argp); // remove trailing CRLF for (char* pend = errMsg + strlen(errMsg) - 1; pend >= errMsg && (*pend == '\n' || *pend == '\r' || *pend == ' '); pend--) *pend = '\0'; diff --git a/daemon/queue/NzbFile.h b/daemon/queue/NzbFile.h index 7feae13e..d9999d51 100644 --- a/daemon/queue/NzbFile.h +++ b/daemon/queue/NzbFile.h @@ -50,7 +50,7 @@ private: bool HasDuplicateFilenames(); void ReadPassword(); #ifdef WIN32 - bool ParseNzb(IUnknown* nzb); + bool ParseNzb(IUnknown* nzb); static void EncodeUrl(const char* filename, char* url, int bufLen); #else FileInfo* m_fileInfo; diff --git a/daemon/queue/QueueCoordinator.cpp b/daemon/queue/QueueCoordinator.cpp index 3a837c56..2f1937aa 100644 --- a/daemon/queue/QueueCoordinator.cpp +++ b/daemon/queue/QueueCoordinator.cpp @@ -219,7 +219,7 @@ void QueueCoordinator::Run() FileInfo* fileInfo; ArticleInfo* articleInfo; bool freeConnection = false; - + DownloadQueue* downloadQueue = DownloadQueue::Lock(); bool hasMoreArticles = GetNextArticle(downloadQueue, fileInfo, articleInfo); articeDownloadsRunning = !m_activeDownloads.empty(); @@ -237,7 +237,7 @@ void QueueCoordinator::Run() freeConnection = true; } DownloadQueue::Unlock(); - + if (freeConnection) { g_ServerPool->FreeConnection(connection, false); @@ -415,7 +415,7 @@ void QueueCoordinator::AddNzbFileToQueue(NzbFile* nzbFile, NzbInfo* urlInfo, boo DownloadQueue::Aspect addedAspect = { DownloadQueue::eaNzbAdded, downloadQueue, nzbInfo, NULL }; downloadQueue->Notify(&addedAspect); } - + downloadQueue->Save(); DownloadQueue::Unlock(); @@ -446,7 +446,7 @@ void QueueCoordinator::CheckDupeFileInfos(NzbInfo* nzbInfo) FileInfo* fileInfo2 = *it2; if (fileInfo != fileInfo2 && !strcmp(fileInfo->GetFilename(), fileInfo2->GetFilename()) && - (fileInfo->GetSize() < fileInfo2->GetSize() || + (fileInfo->GetSize() < fileInfo2->GetSize() || (fileInfo->GetSize() == fileInfo2->GetSize() && index2 < index1))) { warn("File \"%s\" appears twice in collection, adding only the biggest file", fileInfo->GetFilename()); @@ -507,7 +507,7 @@ bool QueueCoordinator::GetNextArticle(DownloadQueue* downloadQueue, FileInfo* &f bool* checkedFiles = NULL; time_t curDate = time(NULL); - while (!ok) + while (!ok) { fileInfo = NULL; int num = 0; @@ -519,7 +519,7 @@ bool QueueCoordinator::GetNextArticle(DownloadQueue* downloadQueue, FileInfo* &f for (FileList::iterator it2 = nzbInfo->GetFileList()->begin(); it2 != nzbInfo->GetFileList()->end(); it2++) { FileInfo* fileInfo1 = *it2; - if ((!checkedFiles || !checkedFiles[num]) && + if ((!checkedFiles || !checkedFiles[num]) && !fileInfo1->GetPaused() && !fileInfo1->GetDeleted() && (g_Options->GetPropagationDelay() == 0 || (int)fileInfo1->GetTime() < (int)curDate - g_Options->GetPropagationDelay()) && @@ -814,7 +814,7 @@ void QueueCoordinator::DeleteFileInfo(DownloadQueue* downloadQueue, FileInfo* fi NzbInfo* nzbInfo = fileInfo->GetNzbInfo(); - DownloadQueue::Aspect aspect = { completed && !fileDeleted ? + DownloadQueue::Aspect aspect = { completed && !fileDeleted ? DownloadQueue::eaFileCompleted : DownloadQueue::eaFileDeleted, downloadQueue, nzbInfo, fileInfo }; downloadQueue->Notify(&aspect); @@ -943,7 +943,7 @@ void QueueCoordinator::ResetHangingDownloads() for (ActiveDownloads::iterator it = m_activeDownloads.begin(); it != m_activeDownloads.end();) { ArticleDownloader* articleDownloader = *it; - + if (tm - articleDownloader->GetLastUpdateTime() > g_Options->GetArticleTimeout() + 1 && articleDownloader->GetStatus() == ArticleDownloader::adRunning) { @@ -951,7 +951,7 @@ void QueueCoordinator::ResetHangingDownloads() articleDownloader->GetConnectionName()); articleDownloader->Stop(); } - + if (tm - articleDownloader->GetLastUpdateTime() > g_Options->GetTerminateTimeout() && articleDownloader->GetStatus() == ArticleDownloader::adRunning) { @@ -980,7 +980,7 @@ void QueueCoordinator::ResetHangingDownloads() continue; } it++; - } + } DownloadQueue::Unlock(); } @@ -1139,7 +1139,7 @@ bool QueueCoordinator::MergeQueueEntries(DownloadQueue* downloadQueue, NzbInfo* // reattach completed file items to new NZBInfo-object for (CompletedFiles::iterator it = srcNzbInfo->GetCompletedFiles()->begin(); it != srcNzbInfo->GetCompletedFiles()->end(); it++) - { + { CompletedFile* completedFile = *it; destNzbInfo->GetCompletedFiles()->push_back(completedFile); } diff --git a/daemon/queue/QueueCoordinator.h b/daemon/queue/QueueCoordinator.h index 423f3557..12e1ccdd 100644 --- a/daemon/queue/QueueCoordinator.h +++ b/daemon/queue/QueueCoordinator.h @@ -38,7 +38,7 @@ #include "Observer.h" #include "QueueEditor.h" #include "NntpConnection.h" - + class QueueCoordinator : public Thread, public Observer, public Debuggable { public: @@ -82,7 +82,7 @@ protected: virtual void LogDebugInfo(); public: - QueueCoordinator(); + QueueCoordinator(); virtual ~QueueCoordinator(); virtual void Run(); virtual void Stop(); diff --git a/daemon/queue/QueueEditor.cpp b/daemon/queue/QueueEditor.cpp index 562c90f1..bc1b85ee 100644 --- a/daemon/queue/QueueEditor.cpp +++ b/daemon/queue/QueueEditor.cpp @@ -419,7 +419,7 @@ bool QueueEditor::EditList(DownloadQueue* downloadQueue, IdList* idList, NameLis return ok; } -bool QueueEditor::InternEditList(ItemList* itemList, +bool QueueEditor::InternEditList(ItemList* itemList, IdList* idList, DownloadQueue::EEditAction action, int offset, const char* text) { ItemList workItems; @@ -433,7 +433,7 @@ bool QueueEditor::InternEditList(ItemList* itemList, { case DownloadQueue::eaFilePauseAllPars: case DownloadQueue::eaFilePauseExtraPars: - PauseParsInGroups(itemList, action == DownloadQueue::eaFilePauseExtraPars); + PauseParsInGroups(itemList, action == DownloadQueue::eaFilePauseExtraPars); break; case DownloadQueue::eaGroupMerge: @@ -448,7 +448,7 @@ bool QueueEditor::InternEditList(ItemList* itemList, case DownloadQueue::eaFileReorder: ReorderFiles(itemList); break; - + default: for (ItemList::iterator it = itemList->begin(); it != itemList->end(); it++) { @@ -546,7 +546,7 @@ void QueueEditor::PrepareList(ItemList* itemList, IdList* idList, } itemList->reserve(idList->size()); - if ((offset != 0) && + if ((offset != 0) && (action == DownloadQueue::eaFileMoveOffset || action == DownloadQueue::eaFileMoveTop || action == DownloadQueue::eaFileMoveBottom)) { // add IDs to list in order they currently have in download queue @@ -604,7 +604,7 @@ void QueueEditor::PrepareList(ItemList* itemList, IdList* idList, } } } - else if ((offset != 0) && + else if ((offset != 0) && (action == DownloadQueue::eaGroupMoveOffset || action == DownloadQueue::eaGroupMoveTop || action == DownloadQueue::eaGroupMoveBottom)) { // add IDs to list in order they currently have in download queue @@ -696,7 +696,7 @@ void QueueEditor::PrepareList(ItemList* itemList, IdList* idList, } } } - else + else { // check ID range int maxId = 0; @@ -835,7 +835,7 @@ bool QueueEditor::EditGroup(NzbInfo* nzbInfo, DownloadQueue::EEditAction action, nzbInfo->SetCleanupDisk(CanCleanupDisk(nzbInfo)); } - DownloadQueue::EEditAction GroupToFileMap[] = { + DownloadQueue::EEditAction GroupToFileMap[] = { (DownloadQueue::EEditAction)0, DownloadQueue::eaFileMoveOffset, DownloadQueue::eaFileMoveTop, @@ -885,7 +885,7 @@ void QueueEditor::PauseParsInGroups(ItemList* itemList, bool extraParsOnly) for (ItemList::iterator it = itemList->begin(); it != itemList->end(); ) { EditItem* item = *it; - if (!firstFileInfo || + if (!firstFileInfo || (firstFileInfo->GetNzbInfo() == item->m_fileInfo->GetNzbInfo())) { GroupFileList.push_back(item->m_fileInfo); @@ -923,9 +923,9 @@ void QueueEditor::PauseParsInGroups(ItemList* itemList, bool extraParsOnly) void QueueEditor::PausePars(FileList* fileList, bool extraParsOnly) { debug("QueueEditor: Pausing pars"); - + FileList Pars, Vols; - + for (FileList::iterator it = fileList->begin(); it != fileList->end(); it++) { FileInfo* fileInfo = *it; @@ -933,7 +933,7 @@ void QueueEditor::PausePars(FileList* fileList, bool extraParsOnly) strncpy(loFileName, fileInfo->GetFilename(), 1024); loFileName[1024-1] = '\0'; for (char* p = loFileName; *p; p++) *p = tolower(*p); // convert string to lowercase - + if (strstr(loFileName, ".par2")) { if (!extraParsOnly) @@ -953,7 +953,7 @@ void QueueEditor::PausePars(FileList* fileList, bool extraParsOnly) } } } - + if (extraParsOnly) { if (!Pars.empty()) @@ -980,7 +980,7 @@ void QueueEditor::PausePars(FileList* fileList, bool extraParsOnly) smallest->SetPaused(true); smallest = fileInfo; } - else + else { fileInfo->SetPaused(true); } @@ -1042,7 +1042,7 @@ void QueueEditor::SetNzbCategory(NzbInfo* nzbInfo, const char* category, bool ap { nzbInfo->GetParameters()->SetParameter("*Unpack:", newUnpack ? "yes" : "no"); } - + if (strcasecmp(oldPostScript, newPostScript)) { // add new params not existed in old category @@ -1096,7 +1096,7 @@ void QueueEditor::SetNzbName(NzbInfo* nzbInfo, const char* name) /** * Check if deletion of already downloaded files is possible (when nzb id deleted from queue). -* The deletion is most always possible, except the case if all remaining files in queue +* The deletion is most always possible, except the case if all remaining files in queue * (belonging to this nzb-file) are PARS. */ bool QueueEditor::CanCleanupDisk(NzbInfo* nzbInfo) @@ -1106,9 +1106,9 @@ bool QueueEditor::CanCleanupDisk(NzbInfo* nzbInfo) return true; } - for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) - { - FileInfo* fileInfo = *it; + for (FileList::iterator it = nzbInfo->GetFileList()->begin(); it != nzbInfo->GetFileList()->end(); it++) + { + FileInfo* fileInfo = *it; char loFileName[1024]; strncpy(loFileName, fileInfo->GetFilename(), 1024); loFileName[1024-1] = '\0'; @@ -1204,7 +1204,7 @@ void QueueEditor::ReorderFiles(ItemList* itemList) { nzbInfo->GetFileList()->erase(it2); nzbInfo->GetFileList()->insert(nzbInfo->GetFileList()->begin() + insertPos, fileInfo); - insertPos++; + insertPos++; } delete item; @@ -1236,7 +1236,7 @@ void QueueEditor::SetNzbDupeParam(NzbInfo* nzbInfo, DownloadQueue::EEditAction a { debug("QueueEditor: setting dupe parameter %i='%s' for '%s'", (int)action, text, nzbInfo->GetName()); - switch (action) + switch (action) { case DownloadQueue::eaGroupSetDupeKey: nzbInfo->SetDupeKey(text); diff --git a/daemon/queue/QueueEditor.h b/daemon/queue/QueueEditor.h index 888b37f1..326ecb29 100644 --- a/daemon/queue/QueueEditor.h +++ b/daemon/queue/QueueEditor.h @@ -73,7 +73,7 @@ private: void MoveGroup(NzbInfo* nzbInfo, int offset); public: - QueueEditor(); + QueueEditor(); ~QueueEditor(); bool EditEntry(DownloadQueue* downloadQueue, int ID, DownloadQueue::EEditAction action, int offset, const char* text); bool EditList(DownloadQueue* downloadQueue, IdList* idList, NameList* nameList, DownloadQueue::EMatchMode matchMode, DownloadQueue::EEditAction action, int offset, const char* text); diff --git a/daemon/queue/Scanner.cpp b/daemon/queue/Scanner.cpp index 21a590c4..8a6ae252 100644 --- a/daemon/queue/Scanner.cpp +++ b/daemon/queue/Scanner.cpp @@ -128,8 +128,8 @@ Scanner::~Scanner() debug("Destroying Scanner"); for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); it++) - { - delete *it; + { + delete *it; } m_fileList.clear(); @@ -146,8 +146,8 @@ void Scanner::InitOptions() void Scanner::ClearQueueList() { for (QueueList::iterator it = m_queueList.begin(); it != m_queueList.end(); it++) - { - delete *it; + { + delete *it; } m_queueList.clear(); } @@ -161,8 +161,8 @@ void Scanner::ServiceWork() m_scanMutex.Lock(); - if (m_requestedNzbDirScan || - (!g_Options->GetPauseScan() && g_Options->GetNzbDirInterval() > 0 && + if (m_requestedNzbDirScan || + (!g_Options->GetPauseScan() && g_Options->GetNzbDirInterval() > 0 && m_nzbDirInterval >= g_Options->GetNzbDirInterval() * 1000)) { // check nzbdir every g_pOptions->GetNzbDirInterval() seconds or if requested @@ -268,8 +268,8 @@ bool Scanner::CanProcessFile(const char* fullFilename, bool checkStat) bool inList = false; for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); it++) - { - FileData* fileData = *it; + { + FileData* fileData = *it; if (!strcmp(fileData->GetFilename(), fullFilename)) { inList = true; @@ -306,7 +306,7 @@ bool Scanner::CanProcessFile(const char* fullFilename, bool checkStat) /** * Remove old files from the list of monitored files. * Normally these files are deleted from the list when they are processed. - * However if a file was detected by function "CanProcessFile" once but wasn't + * However if a file was detected by function "CanProcessFile" once but wasn't * processed later (for example if the user deleted it), it will stay in the list, * until we remove it here. */ @@ -316,9 +316,9 @@ void Scanner::DropOldFiles() int i = 0; for (FileList::iterator it = m_fileList.begin(); it != m_fileList.end(); ) - { - FileData* fileData = *it; - if ((current - fileData->GetLastChange() >= + { + FileData* fileData = *it; + if ((current - fileData->GetLastChange() >= (g_Options->GetNzbDirInterval() + g_Options->GetNzbDirFileAge()) * 2) || // can occur if the system clock was adjusted current < fileData->GetLastChange()) @@ -361,7 +361,7 @@ void Scanner::ProcessIncomingFile(const char* directory, const char* baseFilenam int nzbId = 0; for (QueueList::iterator it = m_queueList.begin(); it != m_queueList.end(); it++) - { + { QueueData* queueData1 = *it; if (Util::SameFilename(queueData1->GetFilename(), fullFilename)) { @@ -388,7 +388,7 @@ void Scanner::ProcessIncomingFile(const char* directory, const char* baseFilenam if (m_scanScript && strcasecmp(extension, ".nzb_processed")) { - ScanScriptController::ExecuteScripts(fullFilename, + ScanScriptController::ExecuteScripts(fullFilename, urlInfo ? urlInfo->GetUrl() : "", directory, &nzbName, &nzbCategory, &priority, parameters, &addTop, &addPaused, &dupeKey, &dupeScore, &dupeMode); @@ -446,7 +446,7 @@ void Scanner::InitPPParameters(const char* category, NzbParameterList* parameter { bool unpack = g_Options->GetUnpack(); const char* postScript = g_Options->GetPostScript(); - + if (!Util::EmptyStr(category)) { Options::Category* categoryObj = g_Options->FindCategory(category, false); @@ -473,7 +473,7 @@ void Scanner::InitPPParameters(const char* category, NzbParameterList* parameter } parameters->SetParameter("*Unpack:", unpack ? "yes" : "no"); - + if (!Util::EmptyStr(postScript)) { // split szPostScript into tokens and create pp-parameter for each token diff --git a/daemon/queue/Scanner.h b/daemon/queue/Scanner.h index 7a22cc86..cf58de2f 100644 --- a/daemon/queue/Scanner.h +++ b/daemon/queue/Scanner.h @@ -82,7 +82,7 @@ private: public: QueueData(const char* filename, const char* nzbName, const char* category, int priority, const char* dupeKey, int dupeScore, EDupeMode dupeMode, - NzbParameterList* parameters, bool addTop, bool addPaused, NzbInfo* urlInfo, + NzbParameterList* parameters, bool addTop, bool addPaused, NzbInfo* urlInfo, EAddStatus* addStatus, int* nzbId); ~QueueData(); const char* GetFilename() { return m_filename; } diff --git a/daemon/queue/UrlCoordinator.cpp b/daemon/queue/UrlCoordinator.cpp index c144b91f..32b44370 100644 --- a/daemon/queue/UrlCoordinator.cpp +++ b/daemon/queue/UrlCoordinator.cpp @@ -83,7 +83,7 @@ void UrlDownloader::ProcessHeader(const char* line) value++; while (*value == ' ') value++; Util::Trim(value); - + debug("X-DNZB: %s", modLine); debug("Value: %s", value); @@ -235,7 +235,7 @@ void UrlCoordinator::ResetHangingDownloads() continue; } it++; - } + } DownloadQueue::Unlock(); } @@ -448,7 +448,7 @@ void UrlCoordinator::UrlCompleted(UrlDownloader* urlDownloader) downloadQueue->GetHistory()->push_front(historyInfo); deleteObj = false; } - + downloadQueue->Save(); DownloadQueue::Unlock(); @@ -476,7 +476,7 @@ bool UrlCoordinator::DeleteQueueEntry(DownloadQueue* downloadQueue, NzbInfo* nzb urlDownloader->Stop(); return true; } - } + } } info("Deleting URL %s", nzbInfo->GetName()); diff --git a/daemon/queue/UrlCoordinator.h b/daemon/queue/UrlCoordinator.h index 4ff62e1b..90407070 100644 --- a/daemon/queue/UrlCoordinator.h +++ b/daemon/queue/UrlCoordinator.h @@ -57,7 +57,7 @@ protected: virtual void LogDebugInfo(); public: - UrlCoordinator(); + UrlCoordinator(); virtual ~UrlCoordinator(); virtual void Run(); virtual void Stop(); diff --git a/daemon/remote/BinRpc.cpp b/daemon/remote/BinRpc.cpp index 31b65917..f7654fd4 100644 --- a/daemon/remote/BinRpc.cpp +++ b/daemon/remote/BinRpc.cpp @@ -56,12 +56,12 @@ extern void ExitProc(); extern void Reload(); const char* g_MessageRequestNames[] = - { "N/A", "Download", "Pause/Unpause", "List", "Set download rate", "Dump debug", - "Edit queue", "Log", "Quit", "Reload", "Version", "Post-queue", "Write log", "Scan", + { "N/A", "Download", "Pause/Unpause", "List", "Set download rate", "Dump debug", + "Edit queue", "Log", "Quit", "Reload", "Version", "Post-queue", "Write log", "Scan", "Pause/Unpause postprocessor", "History" }; const unsigned int g_MessageRequestSizes[] = - { 0, + { 0, sizeof(SNzbDownloadRequest), sizeof(SNzbPauseUnpauseRequest), sizeof(SNzbListRequest), @@ -76,7 +76,7 @@ const unsigned int g_MessageRequestSizes[] = sizeof(SNzbWriteLogRequest), sizeof(SNzbScanRequest), sizeof(SNzbHistoryRequest) - }; + }; @@ -226,7 +226,7 @@ void BinRpcProcessor::Dispatch() g_MessageRequestSizes[ntohl(m_messageBase.m_type)], ntohl(m_messageBase.m_structSize)); return; } - + BinCommand* command = NULL; switch (ntohl(m_messageBase.m_type)) @@ -439,7 +439,7 @@ void DownloadBinCommand::Execute() free(nzbContent); return; } - + int priority = ntohl(DownloadRequest.m_priority); bool addPaused = ntohl(DownloadRequest.m_addPaused); bool addTop = ntohl(DownloadRequest.m_addFirst); @@ -871,7 +871,7 @@ void EditQueueBinCommand::Execute() } char* buf = (char*)malloc(bufLength); - + if (!m_connection->Recv(buf, bufLength)) { error("invalid request"); @@ -1046,14 +1046,14 @@ void WriteLogBinCommand::Execute() } char* recvBuffer = (char*)malloc(ntohl(WriteLogRequest.m_trailingDataLength) + 1); - + if (!m_connection->Recv(recvBuffer, ntohl(WriteLogRequest.m_trailingDataLength))) { error("invalid request"); free(recvBuffer); return; } - + bool OK = true; switch ((Message::EKind)ntohl(WriteLogRequest.m_kind)) { diff --git a/daemon/remote/MessageBase.h b/daemon/remote/MessageBase.h index cb5ce60d..cfea02c2 100644 --- a/daemon/remote/MessageBase.h +++ b/daemon/remote/MessageBase.h @@ -38,11 +38,11 @@ static const int NZBREQUESTPASSWORDSIZE = 32; /** * NZBGet communication protocol uses only two basic data types: integer and char. * Integer values are passed using network byte order (Big-Endian). - * Use function "htonl" and "ntohl" to convert integers to/from machine + * Use function "htonl" and "ntohl" to convert integers to/from machine * (host) byte order. * All char-strings ends with NULL-char. * - * NOTE: + * NOTE: * NZBGet communication protocol is intended for usage only by NZBGet itself. * The communication works only if server and client has the same version. * The compatibility with previous program versions is not provided. diff --git a/daemon/remote/RemoteClient.cpp b/daemon/remote/RemoteClient.cpp index a606f2cc..aa703bed 100644 --- a/daemon/remote/RemoteClient.cpp +++ b/daemon/remote/RemoteClient.cpp @@ -133,7 +133,7 @@ bool RemoteClient::ReceiveBoolResponse() memset(&BoolResponse, 0, sizeof(BoolResponse)); bool read = m_connection->Recv((char*)&BoolResponse, sizeof(BoolResponse)); - if (!read || + if (!read || (int)ntohl(BoolResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(BoolResponse.m_messageBase.m_structSize) != sizeof(BoolResponse)) { @@ -250,13 +250,13 @@ void RemoteClient::BuildFileList(SNzbListResponse* listResponse, const char* tra const char* fileName = bufPtr + sizeof(SNzbListResponseNzbEntry); const char* name = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen); - const char* destDir = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + + const char* destDir = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + ntohl(listAnswer->m_nameLen); - const char* category = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + + const char* category = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen); - const char* m_queuedFilename = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + + const char* m_queuedFilename = bufPtr + sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen) + ntohl(listAnswer->m_categoryLen); - + MatchedNzbInfo* nzbInfo = new MatchedNzbInfo(); nzbInfo->SetId(ntohl(listAnswer->m_id)); nzbInfo->SetKind((NzbInfo::EKind)ntohl(listAnswer->m_kind)); @@ -276,7 +276,7 @@ void RemoteClient::BuildFileList(SNzbListResponse* listResponse, const char* tra downloadQueue->GetQueue()->push_back(nzbInfo); bufPtr += sizeof(SNzbListResponseNzbEntry) + ntohl(listAnswer->m_filenameLen) + - ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen) + + ntohl(listAnswer->m_nameLen) + ntohl(listAnswer->m_destDirLen) + ntohl(listAnswer->m_categoryLen) + ntohl(listAnswer->m_queuedFilenameLen); } @@ -302,7 +302,7 @@ void RemoteClient::BuildFileList(SNzbListResponse* listResponse, const char* tra const char* subject = bufPtr + sizeof(SNzbListResponseFileEntry); const char* fileName = bufPtr + sizeof(SNzbListResponseFileEntry) + ntohl(listAnswer->m_subjectLen); - + MatchedFileInfo* fileInfo = new MatchedFileInfo(); fileInfo->SetId(ntohl(listAnswer->m_id)); fileInfo->SetSize(Util::JoinInt64(ntohl(listAnswer->m_fileSizeHi), ntohl(listAnswer->m_fileSizeLo))); @@ -318,7 +318,7 @@ void RemoteClient::BuildFileList(SNzbListResponse* listResponse, const char* tra fileInfo->SetNzbInfo(nzbInfo); nzbInfo->GetFileList()->push_back(fileInfo); - bufPtr += sizeof(SNzbListResponseFileEntry) + ntohl(listAnswer->m_subjectLen) + + bufPtr += sizeof(SNzbListResponseFileEntry) + ntohl(listAnswer->m_subjectLen) + ntohl(listAnswer->m_filenameLen); } } @@ -351,7 +351,7 @@ bool RemoteClient::RequestServerList(bool files, bool groups, const char* patter // Now listen for the returned list SNzbListResponse ListResponse; bool read = m_connection->Recv((char*) &ListResponse, sizeof(ListResponse)); - if (!read || + if (!read || (int)ntohl(ListResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(ListResponse.m_messageBase.m_structSize) != sizeof(ListResponse)) { @@ -573,7 +573,7 @@ bool RemoteClient::RequestServerList(bool files, bool groups, const char* patter if (!pattern || ((MatchedNzbInfo*)nzbInfo)->m_match) { - printf("[%i] %s%s (%s, %s%s%s)%s%s\n", nzbInfo->GetId(), priority, + printf("[%i] %s%s (%s, %s%s%s)%s%s\n", nzbInfo->GetId(), priority, nzbInfo->GetName(), urlOrFile, remainingStr, pausedStr, threads, category, parameters); matches++; @@ -622,17 +622,17 @@ bool RemoteClient::RequestServerList(bool files, bool groups, const char* patter printf("Remaining size: %s\n", Util::FormatSize(remainingBuf, sizeof(remainingBuf), remaining)); } - if (ntohl(ListResponse.m_downloadRate) > 0 && - !ntohl(ListResponse.m_downloadPaused) && - !ntohl(ListResponse.m_download2Paused) && + if (ntohl(ListResponse.m_downloadRate) > 0 && + !ntohl(ListResponse.m_downloadPaused) && + !ntohl(ListResponse.m_download2Paused) && !ntohl(ListResponse.m_downloadStandBy)) - { - long long remain_sec = (long long)(remaining / ntohl(ListResponse.m_downloadRate)); + { + long long remain_sec = (long long)(remaining / ntohl(ListResponse.m_downloadRate)); int h = (int)(remain_sec / 3600); int m = (int)((remain_sec % 3600) / 60); int s = (int)(remain_sec % 60); printf("Remaining time: %.2d:%.2d:%.2d\n", h, m, s); - } + } char speed[20]; printf("Current download rate: %s\n", @@ -679,7 +679,7 @@ bool RemoteClient::RequestServerList(bool files, bool groups, const char* patter if (ntohl(ListResponse.m_downloadPaused) || ntohl(ListResponse.m_download2Paused)) { - snprintf(serverState, sizeof(serverState), "%s%s", + snprintf(serverState, sizeof(serverState), "%s%s", ntohl(ListResponse.m_downloadStandBy) ? "Paused" : "Pausing", ntohl(ListResponse.m_downloadPaused) && ntohl(ListResponse.m_download2Paused) ? " (+2)" : ntohl(ListResponse.m_download2Paused) ? " (2)" : ""); @@ -728,7 +728,7 @@ bool RemoteClient::RequestServerLog(int lines) // Now listen for the returned log SNzbLogResponse LogResponse; bool read = m_connection->Recv((char*) &LogResponse, sizeof(LogResponse)); - if (!read || + if (!read || (int)ntohl(LogResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(LogResponse.m_messageBase.m_structSize) != sizeof(LogResponse)) { @@ -909,12 +909,12 @@ bool RemoteClient::RequestServerEditQueue(DownloadQueue::EEditAction action, int } int32_t* ids = (int32_t*)(trailingData + textLen); - + for (int i = 0; i < idCount; i++) { ids[i] = htonl(idList[i]); } - + if (nameCount > 0) { char *names = trailingData + textLen + idLength; @@ -1026,7 +1026,7 @@ bool RemoteClient::RequestPostQueue() // Now listen for the returned list SNzbPostQueueResponse PostQueueResponse; bool read = m_connection->Recv((char*) &PostQueueResponse, sizeof(PostQueueResponse)); - if (!read || + if (!read || (int)ntohl(PostQueueResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(PostQueueResponse.m_messageBase.m_structSize) != sizeof(PostQueueResponse)) { @@ -1072,10 +1072,10 @@ bool RemoteClient::RequestPostQueue() const char* postStageName[] = { "", ", Loading Pars", ", Verifying source files", ", Repairing", ", Verifying repaired files", ", Unpacking", ", Executing postprocess-script", "" }; char* infoName = bufPtr + sizeof(SNzbPostQueueResponseEntry) + ntohl(postQueueAnswer->m_nzbFilenameLen); - + printf("[%i] %s%s%s\n", ntohl(postQueueAnswer->m_id), infoName, postStageName[ntohl(postQueueAnswer->m_stage)], completed); - bufPtr += sizeof(SNzbPostQueueResponseEntry) + ntohl(postQueueAnswer->m_nzbFilenameLen) + + bufPtr += sizeof(SNzbPostQueueResponseEntry) + ntohl(postQueueAnswer->m_nzbFilenameLen) + ntohl(postQueueAnswer->m_infoNameLen) + ntohl(postQueueAnswer->m_destDirLen) + ntohl(postQueueAnswer->m_progressLabelLen); } @@ -1152,7 +1152,7 @@ bool RemoteClient::RequestHistory(bool withHidden) // Now listen for the returned list SNzbHistoryResponse HistoryResponse; bool read = m_connection->Recv((char*) &HistoryResponse, sizeof(HistoryResponse)); - if (!read || + if (!read || (int)ntohl(HistoryResponse.m_messageBase.m_signature) != (int)NZBMESSAGE_SIGNATURE || ntohl(HistoryResponse.m_messageBase.m_structSize) != sizeof(HistoryResponse)) { @@ -1206,9 +1206,9 @@ bool RemoteClient::RequestHistory(bool withHidden) int parStatus = ntohl(listAnswer->m_parStatus); int scriptStatus = ntohl(listAnswer->m_scriptStatus); - printf("[%i] %s (%s%s%s%s%s)\n", ntohl(listAnswer->m_id), nicename, + printf("[%i] %s (%s%s%s%s%s)\n", ntohl(listAnswer->m_id), nicename, (kind == HistoryInfo::hkDup ? "Hidden, " : ""), - (kind == HistoryInfo::hkDup ? "" : files), sizeStr, + (kind == HistoryInfo::hkDup ? "" : files), sizeStr, (kind == HistoryInfo::hkDup ? "" : parStatusText[parStatus]), (kind == HistoryInfo::hkDup ? "" : scriptStatusText[scriptStatus])); } @@ -1216,7 +1216,7 @@ bool RemoteClient::RequestHistory(bool withHidden) { const char* urlStatusText[] = { "", "", "Url download successful", "Url download failed", "", "Nzb scan skipped", "Nzb scan failed" }; - printf("[%i] %s (URL, %s)\n", ntohl(listAnswer->m_id), nicename, + printf("[%i] %s (URL, %s)\n", ntohl(listAnswer->m_id), nicename, urlStatusText[ntohl(listAnswer->m_urlStatus)]); } diff --git a/daemon/remote/RemoteServer.cpp b/daemon/remote/RemoteServer.cpp index 07ae0292..b0d13d1a 100644 --- a/daemon/remote/RemoteServer.cpp +++ b/daemon/remote/RemoteServer.cpp @@ -95,7 +95,7 @@ void RemoteServer::Run() if (!m_connection) { - m_connection = new Connection(g_Options->GetControlIp(), + m_connection = new Connection(g_Options->GetControlIp(), m_tls ? g_Options->GetSecurePort() : g_Options->GetControlPort(), m_tls); m_connection->SetTimeout(g_Options->GetUrlTimeout()); @@ -114,7 +114,7 @@ void RemoteServer::Run() // Remote server could not bind or accept connection, waiting 1/2 sec and try again if (IsStopped()) { - break; + break; } usleep(500 * 1000); delete m_connection; @@ -191,7 +191,7 @@ void RequestProcessor::Run() processor.SetConnection(m_connection); processor.Execute(); } - else if (!strncmp((char*)&signature, "POST", 4) || + else if (!strncmp((char*)&signature, "POST", 4) || !strncmp((char*)&signature, "GET ", 4) || !strncmp((char*)&signature, "OPTI", 4)) { diff --git a/daemon/remote/WebServer.cpp b/daemon/remote/WebServer.cpp index 54e7b3a3..00d9f121 100644 --- a/daemon/remote/WebServer.cpp +++ b/daemon/remote/WebServer.cpp @@ -140,7 +140,7 @@ void WebProcessor::Execute() // reading http body (request content) m_request = (char*)malloc(m_contentLen + 1); m_request[m_contentLen] = '\0'; - + if (!m_connection->Recv(m_request, m_contentLen)) { error("Invalid-request: could not read data"); @@ -148,7 +148,7 @@ void WebProcessor::Execute() } debug("Request=%s", m_request); } - + debug("request received from %s", m_connection->GetRemoteAddr()); Dispatch(); @@ -230,7 +230,7 @@ void WebProcessor::ParseUrl() char* pstart = m_url + 1; int len = 0; char* pend = strchr(pstart + 1, '/'); - if (pend) + if (pend) { len = (int)(pend - pstart < (int)sizeof(m_authInfo) - 1 ? pend - pstart : (int)sizeof(m_authInfo) - 1); } @@ -315,7 +315,7 @@ bool WebProcessor::IsAuthorizedIp(const char* remoteAddr) break; } } - + return authorized; } @@ -335,7 +335,7 @@ void WebProcessor::Dispatch() processor.SetUserAccess((XmlRpcProcessor::EUserAccess)m_userAccess); processor.SetUrl(m_url); processor.Execute(); - SendBodyResponse(processor.GetResponse(), strlen(processor.GetResponse()), processor.GetContentType()); + SendBodyResponse(processor.GetResponse(), strlen(processor.GetResponse()), processor.GetContentType()); return; } @@ -344,13 +344,13 @@ void WebProcessor::Dispatch() SendErrorResponse(ERR_HTTP_SERVICE_UNAVAILABLE); return; } - + if (m_httpMethod != hmGet) { SendErrorResponse(ERR_HTTP_BAD_REQUEST); return; } - + // for security reasons we allow only characters "0..9 A..Z a..z . - _ /" in the URLs // we also don't allow ".." in the URLs for (char *p = m_url; *p; p++) @@ -389,7 +389,7 @@ void WebProcessor::SendAuthResponse() "\r\n"; char responseHeader[1024]; snprintf(responseHeader, 1024, AUTH_RESPONSE_HEADER, Util::VersionRevision()); - + // Send the response answer debug("ResponseHeader=%s", responseHeader); m_connection->Send(responseHeader, strlen(responseHeader)); @@ -409,10 +409,10 @@ void WebProcessor::SendOptionsResponse() "Server: nzbget-%s\r\n" "\r\n"; char responseHeader[1024]; - snprintf(responseHeader, 1024, OPTIONS_RESPONSE_HEADER, + snprintf(responseHeader, 1024, OPTIONS_RESPONSE_HEADER, m_origin ? m_origin : "", Util::VersionRevision()); - + // Send the response answer debug("ResponseHeader=%s", responseHeader); m_connection->Send(responseHeader, strlen(responseHeader)); @@ -420,7 +420,7 @@ void WebProcessor::SendOptionsResponse() void WebProcessor::SendErrorResponse(const char* errCode) { - const char* RESPONSE_HEADER = + const char* RESPONSE_HEADER = "HTTP/1.0 %s\r\n" "Connection: close\r\n" "Content-Length: %i\r\n" @@ -452,7 +452,7 @@ void WebProcessor::SendRedirectResponse(const char* url) "\r\n"; char responseHeader[1024]; snprintf(responseHeader, 1024, REDIRECT_RESPONSE_HEADER, url, Util::VersionRevision()); - + // Send the response answer debug("ResponseHeader=%s", responseHeader); m_connection->Send(responseHeader, strlen(responseHeader)); @@ -460,7 +460,7 @@ void WebProcessor::SendRedirectResponse(const char* url) void WebProcessor::SendBodyResponse(const char* body, int bodyLen, const char* contentType) { - const char* RESPONSE_HEADER = + const char* RESPONSE_HEADER = "HTTP/1.1 200 OK\r\n" "Connection: close\r\n" "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n" @@ -474,7 +474,7 @@ void WebProcessor::SendBodyResponse(const char* body, int bodyLen, const char* c "%s" // Content-Encoding: gzip "Server: nzbget-%s\r\n" "\r\n"; - + #ifndef DISABLE_GZIP char *gbuf = NULL; bool gzip = m_gzip && bodyLen > MAX_UNCOMPRESSED_SIZE; @@ -498,7 +498,7 @@ void WebProcessor::SendBodyResponse(const char* body, int bodyLen, const char* c #else bool gzip = false; #endif - + char contentTypeHeader[1024]; if (contentType) { @@ -508,18 +508,18 @@ void WebProcessor::SendBodyResponse(const char* body, int bodyLen, const char* c { contentTypeHeader[0] = '\0'; } - + char responseHeader[1024]; - snprintf(responseHeader, 1024, RESPONSE_HEADER, + snprintf(responseHeader, 1024, RESPONSE_HEADER, m_origin ? m_origin : "", m_serverAuthToken[m_userAccess], bodyLen, contentTypeHeader, gzip ? "Content-Encoding: gzip\r\n" : "", Util::VersionRevision()); - + // Send the request answer m_connection->Send(responseHeader, strlen(responseHeader)); m_connection->Send(body, bodyLen); - + #ifndef DISABLE_GZIP free(gbuf); #endif @@ -536,10 +536,10 @@ void WebProcessor::SendFileResponse(const char* filename) SendErrorResponse(ERR_HTTP_NOT_FOUND); return; } - + // "LoadFileIntoBuffer" adds a trailing NULL, which we don't need here bodyLen--; - + SendBodyResponse(body, bodyLen, DetectContentType(filename)); free(body); diff --git a/daemon/remote/XmlRpc.cpp b/daemon/remote/XmlRpc.cpp index 92180036..6c4098eb 100644 --- a/daemon/remote/XmlRpc.cpp +++ b/daemon/remote/XmlRpc.cpp @@ -399,7 +399,7 @@ void XmlRpcProcessor::Dispatch() if (pstart) { char* pend = strchr(pstart + 1, '?'); - if (pend) + if (pend) { int len = (int)(pend - pstart - 1 < (int)sizeof(methodName) - 1 ? pend - pstart - 1 : (int)sizeof(methodName) - 1); len = len >= sizeof(methodName) ? sizeof(methodName) - 1 : len; @@ -418,8 +418,8 @@ void XmlRpcProcessor::Dispatch() else if (m_protocol == rpXmlRpc) { WebUtil::XmlParseTagValue(m_request, "methodName", methodName, sizeof(methodName), NULL); - } - else if (m_protocol == rpJsonRpc) + } + else if (m_protocol == rpJsonRpc) { int valueLen = 0; if (const char* methodPtr = WebUtil::JsonFindField(m_request, "method", &valueLen)) @@ -574,7 +574,7 @@ void XmlRpcProcessor::BuildResponse(const char* response, const char* callbackFu m_response.Append(closeTag); m_response.Append(footer); m_response.Append(callbackFooter); - + m_contentType = xmlRpc ? "text/xml" : "application/json"; } @@ -582,7 +582,7 @@ XmlCommand* XmlRpcProcessor::CreateCommand(const char* methodName) { XmlCommand* command = NULL; - if (m_userAccess == uaAdd && + if (m_userAccess == uaAdd && !(!strcasecmp(methodName, "append") || !strcasecmp(methodName, "appendurl") || !strcasecmp(methodName, "version"))) { @@ -779,7 +779,7 @@ XmlCommand::XmlCommand() } bool XmlCommand::IsJson() -{ +{ return m_protocol == XmlRpcProcessor::rpJsonRpc || m_protocol == XmlRpcProcessor::rpJsonPRpc; } @@ -816,18 +816,18 @@ void XmlCommand::OptimizeResponse(int recordCount) void XmlCommand::BuildErrorResponse(int errCode, const char* errText, ...) { - const char* XML_RESPONSE_ERROR_BODY = + const char* XML_RESPONSE_ERROR_BODY = "\n" "faultCode%i\n" "faultString%s\n" "\n"; - const char* JSON_RESPONSE_ERROR_BODY = + const char* JSON_RESPONSE_ERROR_BODY = "{\n" - "\"name\" : \"JSONRPCError\",\n" - "\"code\" : %i,\n" - "\"message\" : \"%s\"\n" - "}"; + "\"name\" : \"JSONRPCError\",\n" + "\"code\" : %i,\n" + "\"message\" : \"%s\"\n" + "}"; char fullText[1024]; @@ -1093,7 +1093,7 @@ char* XmlCommand::EncodeStr(const char* str) return strdup(""); } - if (IsJson()) + if (IsJson()) { return WebUtil::JsonEncode(str); } @@ -1177,7 +1177,7 @@ void PauseUnpauseXmlCommand::Execute() BuildBoolResponse(ok); } -// bool scheduleresume(int Seconds) +// bool scheduleresume(int Seconds) void ScheduleResumeXmlCommand::Execute() { if (!CheckSafeMethod()) @@ -1259,7 +1259,7 @@ void SetDownloadRateXmlCommand::Execute() void StatusXmlCommand::Execute() { - const char* XML_STATUS_START = + const char* XML_STATUS_START = "\n" "RemainingSizeLo%u\n" "RemainingSizeHi%u\n" @@ -1301,7 +1301,7 @@ void StatusXmlCommand::Execute() "\n" "\n"; - const char* JSON_STATUS_START = + const char* JSON_STATUS_START = "{\n" "\"RemainingSizeLo\" : %u,\n" "\"RemainingSizeHi\" : %u,\n" @@ -1339,17 +1339,17 @@ void StatusXmlCommand::Execute() "\"QueueScriptCount\" : %i,\n" "\"NewsServers\" : [\n"; - const char* JSON_STATUS_END = + const char* JSON_STATUS_END = "]\n" "}"; - const char* XML_NEWSSERVER_ITEM = + const char* XML_NEWSSERVER_ITEM = "\n" "ID%i\n" "Active%s\n" "\n"; - const char* JSON_NEWSSERVER_ITEM = + const char* JSON_NEWSSERVER_ITEM = "{\n" "\"ID\" : %i,\n" "\"Active\" : %s\n" @@ -1409,9 +1409,9 @@ void StatusXmlCommand::Execute() remainingSizeLo, remainingSizeHi, remainingMBytes, forcedSizeLo, forcedSizeHi, forcedMBytes, downloadedSizeLo, downloadedSizeHi, downloadedMBytes, articleCacheLo, articleCacheHi, articleCacheMBytes, - downloadRate, averageDownloadRate, downloadLimit, threadCount, - postJobCount, postJobCount, urlCount, upTimeSec, downloadTimeSec, - BoolToStr(downloadPaused), BoolToStr(downloadPaused), BoolToStr(downloadPaused), + downloadRate, averageDownloadRate, downloadLimit, threadCount, + postJobCount, postJobCount, urlCount, upTimeSec, downloadTimeSec, + BoolToStr(downloadPaused), BoolToStr(downloadPaused), BoolToStr(downloadPaused), BoolToStr(serverStandBy), BoolToStr(postPaused), BoolToStr(scanPaused), freeDiskSpaceLo, freeDiskSpaceHi, freeDiskSpaceMB, serverTime, resumeTime, BoolToStr(feedActive), queuedScripts); @@ -1465,7 +1465,7 @@ void LogXmlCommand::Execute() } } - const char* XML_LOG_ITEM = + const char* XML_LOG_ITEM = "\n" "ID%i\n" "Kind%s\n" @@ -1473,7 +1473,7 @@ void LogXmlCommand::Execute() "Text%s\n" "\n"; - const char* JSON_LOG_ITEM = + const char* JSON_LOG_ITEM = "{\n" "\"ID\" : %i,\n" "\"Kind\" : \"%s\",\n" @@ -1481,7 +1481,7 @@ void LogXmlCommand::Execute() "\"Text\" : \"%s\"\n" "}"; - const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL" }; + const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL" }; int index = 0; @@ -1512,7 +1512,7 @@ void LogXmlCommand::UnlockMessages() g_Log->UnlockMessages(); } -// struct[] listfiles(int IDFrom, int IDTo, int NZBID) +// struct[] listfiles(int IDFrom, int IDTo, int NZBID) // For backward compatibility with 0.8 parameter "NZBID" is optional void ListFilesXmlCommand::Execute() { @@ -1540,7 +1540,7 @@ void ListFilesXmlCommand::Execute() AppendResponse(IsJson() ? "[\n" : "\n"); DownloadQueue* downloadQueue = DownloadQueue::Lock(); - const char* XML_LIST_ITEM = + const char* XML_LIST_ITEM = "\n" "ID%i\n" "FileSizeLo%u\n" @@ -1563,7 +1563,7 @@ void ListFilesXmlCommand::Execute() "Progress%u\n" "\n"; - const char* JSON_LIST_ITEM = + const char* JSON_LIST_ITEM = "{\n" "\"ID\" : %i,\n" "\"FileSizeLo\" : %u,\n" @@ -1614,8 +1614,8 @@ void ListFilesXmlCommand::Execute() AppendCondResponse(",\n", IsJson() && index++ > 0); AppendFmtResponse(IsJson() ? JSON_LIST_ITEM : XML_LIST_ITEM, - fileInfo->GetId(), fileSizeLo, fileSizeHi, remainingSizeLo, remainingSizeHi, - fileInfo->GetTime(), BoolToStr(fileInfo->GetFilenameConfirmed()), + fileInfo->GetId(), fileSizeLo, fileSizeHi, remainingSizeLo, remainingSizeHi, + fileInfo->GetTime(), BoolToStr(fileInfo->GetFilenameConfirmed()), BoolToStr(fileInfo->GetPaused()), fileInfo->GetNzbInfo()->GetId(), xmlNzbNicename, xmlNzbNicename, xmlNzbFilename, xmlSubject, xmlFilename, xmlDestDir, xmlCategory, fileInfo->GetNzbInfo()->GetPriority(), fileInfo->GetActiveDownloads(), progress); @@ -1684,14 +1684,14 @@ void NzbInfoXmlCommand::AppendNzbInfoFields(NzbInfo* nzbInfo) const char* XML_NZB_ITEM_SCRIPT_START = "\n" "ScriptStatuses\n"; - + const char* XML_NZB_ITEM_STATS_START = "\n" "ServerStats\n"; - + const char* XML_NZB_ITEM_END = "\n"; - + const char* JSON_NZB_ITEM_START = "\"NZBID\" : %i,\n" "\"NZBName\" : \"%s\",\n" @@ -1740,62 +1740,62 @@ void NzbInfoXmlCommand::AppendNzbInfoFields(NzbInfo* nzbInfo) const char* JSON_NZB_ITEM_SCRIPT_START = "],\n" "\"ScriptStatuses\" : [\n"; - + const char* JSON_NZB_ITEM_STATS_START = "],\n" "\"ServerStats\" : [\n"; - + const char* JSON_NZB_ITEM_END = "]\n"; - + const char* XML_PARAMETER_ITEM = "\n" "Name%s\n" "Value%s\n" "\n"; - + const char* JSON_PARAMETER_ITEM = "{\n" "\"Name\" : \"%s\",\n" "\"Value\" : \"%s\"\n" "}"; - + const char* XML_SCRIPT_ITEM = "\n" "Name%s\n" "Status%s\n" "\n"; - + const char* JSON_SCRIPT_ITEM = "{\n" "\"Name\" : \"%s\",\n" "\"Status\" : \"%s\"\n" "}"; - + const char* XML_STAT_ITEM = "\n" "ServerID%i\n" "SuccessArticles%i\n" "FailedArticles%i\n" "\n"; - + const char* JSON_STAT_ITEM = "{\n" "\"ServerID\" : %i,\n" "\"SuccessArticles\" : %i,\n" "\"FailedArticles\" : %i\n" "}"; - - const char* kindName[] = { "NZB", "URL" }; - const char* parStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "REPAIR_POSSIBLE", "MANUAL" }; - const char* unpackStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "SPACE", "PASSWORD" }; - const char* moveStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; - const char* scriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; - const char* deleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; - const char* markStatusName[] = { "NONE", "BAD", "GOOD", "SUCCESS" }; + + const char* kindName[] = { "NZB", "URL" }; + const char* parStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "REPAIR_POSSIBLE", "MANUAL" }; + const char* unpackStatusName[] = { "NONE", "NONE", "FAILURE", "SUCCESS", "SPACE", "PASSWORD" }; + const char* moveStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; + const char* scriptStatusName[] = { "NONE", "FAILURE", "SUCCESS" }; + const char* deleteStatusName[] = { "NONE", "MANUAL", "HEALTH", "DUPE", "BAD", "GOOD", "COPY", "SCAN" }; + const char* markStatusName[] = { "NONE", "BAD", "GOOD", "SUCCESS" }; const char* urlStatusName[] = { "NONE", "UNKNOWN", "SUCCESS", "FAILURE", "UNKNOWN", "SCAN_SKIPPED", "SCAN_FAILURE" }; - const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; - + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; + unsigned long fileSizeHi, fileSizeLo, fileSizeMB; Util::SplitInt64(nzbInfo->GetSize(), &fileSizeHi, &fileSizeLo); fileSizeMB = (int)(nzbInfo->GetSize() / 1024 / 1024); @@ -1814,7 +1814,7 @@ void NzbInfoXmlCommand::AppendNzbInfoFields(NzbInfo* nzbInfo) char* xmlCategory = EncodeStr(nzbInfo->GetCategory()); char* xmlDupeKey = EncodeStr(nzbInfo->GetDupeKey()); const char* exParStatus = nzbInfo->GetExtraParBlocks() > 0 ? "RECIPIENT" : nzbInfo->GetExtraParBlocks() < 0 ? "DONOR" : "NONE"; - + AppendFmtResponse(IsJson() ? JSON_NZB_ITEM_START : XML_NZB_ITEM_START, nzbInfo->GetId(), xmlNzbNicename, xmlNzbNicename, kindName[nzbInfo->GetKind()], xmlUrl, xmlNzbFilename, xmlDestDir, xmlFinalDir, xmlCategory, @@ -1829,7 +1829,7 @@ void NzbInfoXmlCommand::AppendNzbInfoFields(NzbInfo* nzbInfo) nzbInfo->CalcHealth(), nzbInfo->CalcCriticalHealth(false), xmlDupeKey, nzbInfo->GetDupeScore(), dupeModeName[nzbInfo->GetDupeMode()], BoolToStr(nzbInfo->GetDeleteStatus() != NzbInfo::dsNone), - downloadedSizeLo, downloadedSizeHi, downloadedSizeMB, nzbInfo->GetDownloadSec(), + downloadedSizeLo, downloadedSizeHi, downloadedSizeMB, nzbInfo->GetDownloadSec(), nzbInfo->GetPostInfo() && nzbInfo->GetPostInfo()->GetStartTime() ? time(NULL) - nzbInfo->GetPostInfo()->GetStartTime() : nzbInfo->GetPostTotalSec(), nzbInfo->GetParSec(), nzbInfo->GetRepairSec(), nzbInfo->GetUnpackSec(), messageCount, nzbInfo->GetExtraParBlocks()); @@ -1840,7 +1840,7 @@ void NzbInfoXmlCommand::AppendNzbInfoFields(NzbInfo* nzbInfo) free(xmlDestDir); free(xmlFinalDir); free(xmlDupeKey); - + // Post-processing parameters int paramIndex = 0; for (NzbParameterList::iterator it = nzbInfo->GetParameters()->begin(); it != nzbInfo->GetParameters()->end(); it++) @@ -1849,57 +1849,57 @@ void NzbInfoXmlCommand::AppendNzbInfoFields(NzbInfo* nzbInfo) char* xmlName = EncodeStr(parameter->GetName()); char* xmlValue = EncodeStr(parameter->GetValue()); - + AppendCondResponse(",\n", IsJson() && paramIndex++ > 0); AppendFmtResponse(IsJson() ? JSON_PARAMETER_ITEM : XML_PARAMETER_ITEM, xmlName, xmlValue); - + free(xmlName); free(xmlValue); } - + AppendResponse(IsJson() ? JSON_NZB_ITEM_SCRIPT_START : XML_NZB_ITEM_SCRIPT_START); - + // Script statuses int scriptIndex = 0; for (ScriptStatusList::iterator it = nzbInfo->GetScriptStatuses()->begin(); it != nzbInfo->GetScriptStatuses()->end(); it++) { ScriptStatus* scriptStatus = *it; - + char* xmlName = EncodeStr(scriptStatus->GetName()); char* xmlStatus = EncodeStr(scriptStatusName[scriptStatus->GetStatus()]); - + AppendCondResponse(",\n", IsJson() && scriptIndex++ > 0); AppendFmtResponse(IsJson() ? JSON_SCRIPT_ITEM : XML_SCRIPT_ITEM, xmlName, xmlStatus); - + free(xmlName); free(xmlStatus); } - + AppendResponse(IsJson() ? JSON_NZB_ITEM_STATS_START : XML_NZB_ITEM_STATS_START); - + // Server stats int statIndex = 0; for (ServerStatList::iterator it = nzbInfo->GetCurrentServerStats()->begin(); it != nzbInfo->GetCurrentServerStats()->end(); it++) { ServerStat* serverStat = *it; - + AppendCondResponse(",\n", IsJson() && statIndex++ > 0); AppendFmtResponse(IsJson() ? JSON_STAT_ITEM : XML_STAT_ITEM, serverStat->GetServerId(), serverStat->GetSuccessArticles(), serverStat->GetFailedArticles()); } - + AppendResponse(IsJson() ? JSON_NZB_ITEM_END : XML_NZB_ITEM_END); } void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* postInfo, int logEntries, bool postQueue) { - const char* XML_GROUPQUEUE_ITEM_START = + const char* XML_GROUPQUEUE_ITEM_START = "PostInfoText%s\n" "PostStageProgress%i\n" "PostStageTimeSec%i\n"; // PostTotalTimeSec is printed by method "AppendNZBInfoFields" - const char* XML_POSTQUEUE_ITEM_START = + const char* XML_POSTQUEUE_ITEM_START = "ProgressLabel%s\n" "StageProgress%i\n" "StageTimeSec%i\n" @@ -1910,7 +1910,7 @@ void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* postInfo, int logEntries, const char* XML_POSTQUEUE_ITEM_END = "\n"; - + const char* JSON_GROUPQUEUE_ITEM_START = "\"PostInfoText\" : \"%s\",\n" "\"PostStageProgress\" : %i,\n" @@ -1924,7 +1924,7 @@ void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* postInfo, int logEntries, const char* JSON_LOG_START = "\"Log\" : [\n"; - + const char* JSON_POSTQUEUE_ITEM_END = "]\n"; @@ -1943,7 +1943,7 @@ void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* postInfo, int logEntries, "\"Time\" : %i,\n" "\"Text\" : \"%s\"\n" "}"; - + const char* messageType[] = { "INFO", "WARNING", "ERROR", "DEBUG", "DETAIL"}; const char* itemStart = postQueue ? IsJson() ? JSON_POSTQUEUE_ITEM_START : XML_POSTQUEUE_ITEM_START : @@ -1964,7 +1964,7 @@ void NzbInfoXmlCommand::AppendPostInfoFields(PostInfo* postInfo, int logEntries, { AppendFmtResponse(itemStart, "NONE", "", 0, 0, 0, 0); } - + AppendResponse(IsJson() ? JSON_LOG_START : XML_LOG_START); if (logEntries > 0 && postInfo) @@ -2006,7 +2006,7 @@ void ListGroupsXmlCommand::Execute() AppendResponse(IsJson() ? "[\n" : "\n"); - const char* XML_LIST_ITEM_START = + const char* XML_LIST_ITEM_START = "\n" "FirstID%i\n" // deprecated, use "NZBID" instead "LastID%i\n" // deprecated, use "NZBID" instead @@ -2023,10 +2023,10 @@ void ListGroupsXmlCommand::Execute() "ActiveDownloads%i\n" "Status%s\n"; - const char* XML_LIST_ITEM_END = + const char* XML_LIST_ITEM_END = "\n"; - const char* JSON_LIST_ITEM_START = + const char* JSON_LIST_ITEM_START = "{\n" "\"FirstID\" : %i,\n" // deprecated, use "NZBID" instead "\"LastID\" : %i,\n" // deprecated, use "NZBID" instead @@ -2042,7 +2042,7 @@ void ListGroupsXmlCommand::Execute() "\"MaxPriority\" : %i,\n" "\"ActiveDownloads\" : %i,\n" "\"Status\" : \"%s\",\n"; - + const char* JSON_LIST_ITEM_END = "}"; @@ -2088,7 +2088,7 @@ void ListGroupsXmlCommand::Execute() const char* ListGroupsXmlCommand::DetectStatus(NzbInfo* nzbInfo) { - const char* postStageName[] = { "PP_QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "PP_FINISHED" }; + const char* postStageName[] = { "PP_QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "PP_FINISHED" }; const char* status = NULL; @@ -2121,13 +2121,13 @@ const char* ListGroupsXmlCommand::DetectStatus(NzbInfo* nzbInfo) return status; } -typedef struct +typedef struct { int actionId; const char* actionName; } EditCommandEntry; -EditCommandEntry EditCommandNameMap[] = { +EditCommandEntry EditCommandNameMap[] = { { DownloadQueue::eaFileMoveOffset, "FileMoveOffset" }, { DownloadQueue::eaFileMoveTop, "FileMoveTop" }, { DownloadQueue::eaFileMoveBottom, "FileMoveBottom" }, @@ -2162,7 +2162,7 @@ EditCommandEntry EditCommandNameMap[] = { { DownloadQueue::eaHistoryDelete, "HistoryDelete" }, { DownloadQueue::eaHistoryFinalDelete, "HistoryFinalDelete" }, { DownloadQueue::eaHistoryReturn, "HistoryReturn" }, - { DownloadQueue::eaHistoryProcess, "HistoryProcess" }, + { DownloadQueue::eaHistoryProcess, "HistoryProcess" }, { DownloadQueue::eaHistoryRedownload, "HistoryRedownload" }, { DownloadQueue::eaHistorySetParameter, "HistorySetParameter" }, { DownloadQueue::eaHistorySetDupeKey, "HistorySetDupeKey" }, @@ -2412,7 +2412,7 @@ void PostQueueXmlCommand::Execute() AppendResponse(IsJson() ? "[\n" : "\n"); - const char* XML_POSTQUEUE_ITEM_START = + const char* XML_POSTQUEUE_ITEM_START = "\n" "ID%i\n" "InfoName%s\n" @@ -2422,7 +2422,7 @@ void PostQueueXmlCommand::Execute() const char* XML_POSTQUEUE_ITEM_END = "\n"; - + const char* JSON_POSTQUEUE_ITEM_START = "{\n" "\"ID\" : %i,\n" @@ -2434,7 +2434,7 @@ void PostQueueXmlCommand::Execute() const char* JSON_POSTQUEUE_ITEM_END = "}"; - const char* postStageName[] = { "QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "FINISHED" }; + const char* postStageName[] = { "QUEUED", "LOADING_PARS", "VERIFYING_SOURCES", "REPAIRING", "VERIFYING_REPAIRED", "RENAMING", "UNPACKING", "MOVING", "EXECUTING_SCRIPT", "FINISHED" }; NzbList* nzbList = DownloadQueue::Lock()->GetQueue(); @@ -2507,7 +2507,7 @@ void WriteLogXmlCommand::Execute() else if (!strcmp(kind, "DEBUG")) { debug(text); - } + } else { BuildErrorResponse(3, "Invalid Kind"); @@ -2567,11 +2567,11 @@ void HistoryXmlCommand::Execute() "\"HistoryTime\" : %i,\n" "\"Status\" : \"%s\",\n" "\"Log\" : [],\n"; // Deprected, always empty - + const char* XML_HISTORY_ITEM_END = ""; - const char* JSON_HISTORY_ITEM_END = + const char* JSON_HISTORY_ITEM_END = "}"; const char* XML_HISTORY_DUP_ITEM = @@ -2607,7 +2607,7 @@ void HistoryXmlCommand::Execute() "\"Status\" : \"%s\"\n"; const char* dupStatusName[] = { "UNKNOWN", "SUCCESS", "FAILURE", "DELETED", "DUPE", "BAD", "GOOD" }; - const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; + const char* dupeModeName[] = { "SCORE", "ALL", "FORCE" }; bool dup = false; NextParamAsBool(&dup); @@ -2668,7 +2668,7 @@ void HistoryXmlCommand::Execute() { AppendNzbInfoFields(nzbInfo); } - + AppendResponse(IsJson() ? JSON_HISTORY_ITEM_END : XML_HISTORY_ITEM_END); if (it == downloadQueue->GetHistory()->begin()) @@ -2707,7 +2707,7 @@ void UrlQueueXmlCommand::Execute() { AppendResponse(IsJson() ? "[\n" : "\n"); - const char* XML_URLQUEUE_ITEM = + const char* XML_URLQUEUE_ITEM = "\n" "ID%i\n" "NZBFilename%s\n" @@ -2717,7 +2717,7 @@ void UrlQueueXmlCommand::Execute() "Priority%i\n" "\n"; - const char* JSON_URLQUEUE_ITEM = + const char* JSON_URLQUEUE_ITEM = "{\n" "\"ID\" : %i,\n" "\"NZBFilename\" : \"%s\",\n" @@ -2761,13 +2761,13 @@ void UrlQueueXmlCommand::Execute() // struct[] config() void ConfigXmlCommand::Execute() { - const char* XML_CONFIG_ITEM = + const char* XML_CONFIG_ITEM = "\n" "Name%s\n" "Value%s\n" "\n"; - const char* JSON_CONFIG_ITEM = + const char* JSON_CONFIG_ITEM = "{\n" "\"Name\" : \"%s\",\n" "\"Value\" : \"%s\"\n" @@ -2802,13 +2802,13 @@ void ConfigXmlCommand::Execute() // struct[] loadconfig() void LoadConfigXmlCommand::Execute() { - const char* XML_CONFIG_ITEM = + const char* XML_CONFIG_ITEM = "\n" "Name%s\n" "Value%s\n" "\n"; - const char* JSON_CONFIG_ITEM = + const char* JSON_CONFIG_ITEM = "{\n" "\"Name\" : \"%s\",\n" "\"Value\" : \"%s\"\n" @@ -2875,7 +2875,7 @@ void SaveConfigXmlCommand::Execute() // parameter "loadFromDisk" is optional (new in v14) void ConfigTemplatesXmlCommand::Execute() { - const char* XML_CONFIG_ITEM = + const char* XML_CONFIG_ITEM = "\n" "Name%s\n" "DisplayName%s\n" @@ -2887,7 +2887,7 @@ void ConfigTemplatesXmlCommand::Execute() "Template%s\n" "\n"; - const char* JSON_CONFIG_ITEM = + const char* JSON_CONFIG_ITEM = "{\n" "\"Name\" : \"%s\",\n" "\"DisplayName\" : \"%s\",\n" @@ -2903,7 +2903,7 @@ void ConfigTemplatesXmlCommand::Execute() NextParamAsBool(&loadFromDisk); ScriptConfig::ConfigTemplates* configTemplates = g_ScriptConfig->GetConfigTemplates(); - + if (loadFromDisk) { configTemplates = new ScriptConfig::ConfigTemplates(); @@ -3029,7 +3029,7 @@ void ViewFeedXmlCommand::Execute() return; } - const char* XML_FEED_ITEM = + const char* XML_FEED_ITEM = "\n" "Title%s\n" "Filename%s\n" @@ -3050,7 +3050,7 @@ void ViewFeedXmlCommand::Execute() "Status%s\n" "\n"; - const char* JSON_FEED_ITEM = + const char* JSON_FEED_ITEM = "{\n" "\"Title\" : \"%s\",\n" "\"Filename\" : \"%s\",\n" @@ -3071,16 +3071,16 @@ void ViewFeedXmlCommand::Execute() "\"Status\" : \"%s\"\n" "}"; - const char* statusType[] = { "UNKNOWN", "BACKLOG", "FETCHED", "NEW" }; - const char* matchStatusType[] = { "IGNORED", "ACCEPTED", "REJECTED" }; - const char* dupeModeType[] = { "SCORE", "ALL", "FORCE" }; + const char* statusType[] = { "UNKNOWN", "BACKLOG", "FETCHED", "NEW" }; + const char* matchStatusType[] = { "IGNORED", "ACCEPTED", "REJECTED" }; + const char* dupeModeType[] = { "SCORE", "ALL", "FORCE" }; AppendResponse(IsJson() ? "[\n" : "\n"); int index = 0; - for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) - { - FeedItemInfo* feedItemInfo = *it; + for (FeedItemInfos::iterator it = feedItemInfos->begin(); it != feedItemInfos->end(); it++) + { + FeedItemInfo* feedItemInfo = *it; if (includeNonMatching || feedItemInfo->GetMatchStatus() == FeedItemInfo::msAccepted) { @@ -3110,7 +3110,7 @@ void ViewFeedXmlCommand::Execute() free(xmladdcategory); free(xmldupekey); } - } + } feedItemInfos->Release(); @@ -3409,7 +3409,7 @@ void ServerVolumesXmlCommand::Execute() AppendCondResponse(",\n", IsJson() && index > 0); AppendFmtResponse(IsJson() ? JSON_VOLUME_ITEM_START : XML_VOLUME_ITEM_START, index, (int)serverVolume->GetDataTime(), serverVolume->GetFirstDay(), - totalSizeLo, totalSizeHi, totalSizeMB, customSizeLo, customSizeHi, customSizeMB, + totalSizeLo, totalSizeHi, totalSizeMB, customSizeLo, customSizeHi, customSizeMB, (int)serverVolume->GetCustomTime(), serverVolume->GetSecSlot(), serverVolume->GetMinSlot(), serverVolume->GetHourSlot(), serverVolume->GetDaySlot()); diff --git a/daemon/util/Log.cpp b/daemon/util/Log.cpp index e0cf7d57..cdde6354 100644 --- a/daemon/util/Log.cpp +++ b/daemon/util/Log.cpp @@ -82,11 +82,11 @@ void Log::LogDebugInfo() info("--------------------------------------------"); info("Dumping debug info to log"); info("--------------------------------------------"); - + m_debugMutex.Lock(); for (Debuggables::iterator it = m_debuggables.begin(); it != m_debuggables.end(); it++) { - Debuggable* debuggable = *it; + Debuggable* debuggable = *it; debuggable->LogDebugInfo(); } m_debugMutex.Unlock(); @@ -110,7 +110,7 @@ void Log::Filelog(const char* msg, ...) va_end(ap); time_t rawtime = time(NULL) + g_Options->GetTimeCorrection(); - + char time[50]; #ifdef HAVE_CTIME_R_3 ctime_r(&rawtime, time, 50); diff --git a/daemon/util/Log.h b/daemon/util/Log.h index 9b41ef8f..bf913e7b 100644 --- a/daemon/util/Log.h +++ b/daemon/util/Log.h @@ -52,10 +52,10 @@ public: enum EKind { mkInfo, - mkWarning, - mkError, - mkDebug, - mkDetail + mkWarning, + mkError, + mkDebug, + mkDetail }; private: @@ -122,11 +122,11 @@ private: #ifdef DEBUG #ifdef HAVE_VARIADIC_MACROS friend void debug(const char* filename, const char* funcname, int lineNr, const char* msg, ...); -#else +#else friend void debug(const char* msg, ...); #endif #endif - + public: static void Init(); static void Final(); diff --git a/daemon/util/Observer.cpp b/daemon/util/Observer.cpp index 657b8a93..455986ee 100644 --- a/daemon/util/Observer.cpp +++ b/daemon/util/Observer.cpp @@ -53,10 +53,10 @@ void Subject::Detach(Observer* observer) void Subject::Notify(void* aspect) { debug("Notifying observers"); - + for (std::list::iterator it = m_observers.begin(); it != m_observers.end(); it++) { - Observer* Observer = *it; + Observer* Observer = *it; Observer->Update(this, aspect); } } diff --git a/daemon/util/Script.cpp b/daemon/util/Script.cpp index 2c53a1ff..c802e440 100644 --- a/daemon/util/Script.cpp +++ b/daemon/util/Script.cpp @@ -78,7 +78,7 @@ Mutex ScriptController::m_runningMutex; * the cild process assumed to hang and will be killed. Another attempt * will be made. */ - + class ChildWatchDog : public Thread { private: @@ -148,7 +148,7 @@ void EnvironmentStrings::Append(char* string) #ifdef WIN32 /* - * Returns environment block in format suitable for using with CreateProcess. + * Returns environment block in format suitable for using with CreateProcess. * The allocated memory must be freed by caller using "free()". */ char* EnvironmentStrings::GetStrings() @@ -176,7 +176,7 @@ char* EnvironmentStrings::GetStrings() #else /* - * Returns environment block in format suitable for using with execve + * Returns environment block in format suitable for using with execve * The allocated memory must be freed by caller using "free()". */ char** EnvironmentStrings::GetStrings() @@ -230,13 +230,13 @@ ScriptController::~ScriptController() void ScriptController::UnregisterRunningScript() { - m_runningMutex.Lock(); - RunningScripts::iterator it = std::find(m_runningScripts.begin(), m_runningScripts.end(), this); - if (it != m_runningScripts.end()) - { - m_runningScripts.erase(it); - } - m_runningMutex.Unlock(); + m_runningMutex.Lock(); + RunningScripts::iterator it = std::find(m_runningScripts.begin(), m_runningScripts.end(), this); + if (it != m_runningScripts.end()) + { + m_runningScripts.erase(it); + } + m_runningMutex.Unlock(); } void ScriptController::ResetEnv() @@ -275,7 +275,7 @@ void ScriptController::PrepareEnvOptions(const char* stripPrefix) for (Options::OptEntries::iterator it = optEntries->begin(); it != optEntries->end(); it++) { Options::OptEntry* optEntry = *it; - + if (stripPrefix && !strncmp(optEntry->GetName(), stripPrefix, prefixLen) && (int)strlen(optEntry->GetName()) > prefixLen) { SetEnvVarSpecial("NZBPO", optEntry->GetName() + prefixLen, optEntry->GetValue()); @@ -294,21 +294,21 @@ void ScriptController::SetEnvVarSpecial(const char* prefix, const char* name, co char varname[1024]; snprintf(varname, sizeof(varname), "%s_%s", prefix, name); varname[1024-1] = '\0'; - + // Original name SetEnvVar(varname, value); - + char normVarname[1024]; strncpy(normVarname, varname, sizeof(varname)); normVarname[1024-1] = '\0'; - + // Replace special characters with "_" and convert to upper case for (char* ptr = normVarname; *ptr; ptr++) { if (strchr(".:*!\"$%&/()=`+~#'{}[]@- ", *ptr)) *ptr = '_'; *ptr = toupper(*ptr); } - + // Another env var with normalized name (replaced special chars and converted to upper case) if (strcmp(varname, normVarname)) { @@ -333,17 +333,17 @@ void ScriptController::PrepareArgs() { command[bufLen] = '\0'; debug("Extension: %s", command); - + char regPath[512]; snprintf(regPath, 512, "%s\\shell\\open\\command", command); regPath[512-1] = '\0'; - + bufLen = 512-1; if (Util::RegReadStr(HKEY_CLASSES_ROOT, regPath, NULL, command, &bufLen)) { command[bufLen] = '\0'; debug("Command: %s", command); - + DWORD_PTR args[] = { (DWORD_PTR)GetScript(), (DWORD_PTR)0 }; if (FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, command, 0, 0, m_cmdLine, sizeof(m_cmdLine), (va_list*)args)) @@ -400,7 +400,7 @@ int ScriptController::Execute() { cmdLine = m_cmdLine; } - + // create pipes to write and read data HANDLE readPipe, writePipe; SECURITY_ATTRIBUTES securityAttributes; @@ -490,14 +490,14 @@ int ScriptController::Execute() // create new process group (see Terminate() where it is used) setsid(); - + // close up the "read" end close(pipein); - + // make the pipeout to be the same as stdout and stderr dup2(pipeout, 1); dup2(pipeout, 2); - + close(pipeout); #ifdef CHILD_WATCHDOG @@ -543,7 +543,7 @@ int ScriptController::Execute() PrintMessage(Message::mkError, "Could not open pipe to %s", m_infoName); return -1; } - + #ifdef CHILD_WATCHDOG debug("Creating child watchdog"); ChildWatchDog* watchDog = new ChildWatchDog(); @@ -551,7 +551,7 @@ int ScriptController::Execute() watchDog->SetProcessId(pid); watchDog->Start(); #endif - + char* buf = (char*)malloc(10240); debug("Entering pipe-loop"); @@ -592,7 +592,7 @@ int ScriptController::Execute() } delete watchDog; #endif - + free(buf); if (m_readpipe) { @@ -626,11 +626,11 @@ int ScriptController::Execute() } #endif } - + #ifdef CHILD_WATCHDOG } // while (!bChildConfirmed && !m_bTerminated) #endif - + debug("Exit code %i", exitCode); return exitCode; @@ -698,7 +698,7 @@ void ScriptController::Detach() m_readpipe = NULL; fclose(readpipe); } - + void ScriptController::Resume() { m_terminated = false; @@ -743,7 +743,7 @@ void ScriptController::ProcessOutput(char* text) { PrintMessage(Message::mkDebug, "%s", text + 8); } - else + else { PrintMessage(Message::mkInfo, "%s", text); } diff --git a/daemon/util/Script.h b/daemon/util/Script.h index 3f287d3e..061a0eb4 100644 --- a/daemon/util/Script.h +++ b/daemon/util/Script.h @@ -35,7 +35,7 @@ class EnvironmentStrings { private: typedef std::vector Strings; - + Strings m_strings; public: @@ -46,7 +46,7 @@ public: void Append(char* string); #ifdef WIN32 char* GetStrings(); -#else +#else char** GetStrings(); #endif }; diff --git a/daemon/util/Thread.cpp b/daemon/util/Thread.cpp index 4d8d9cb7..d00267c6 100644 --- a/daemon/util/Thread.cpp +++ b/daemon/util/Thread.cpp @@ -140,7 +140,7 @@ void Thread::Start() debug("Starting Thread"); m_running = true; - + // NOTE: we must guarantee, that in a time we set m_bRunning // to value returned from pthread_create, the thread-object still exists. // This is not obviously! @@ -171,7 +171,7 @@ void Thread::Stop() debug("Stopping Thread"); m_stopped = true; -} +} void Thread::Resume() { @@ -217,9 +217,9 @@ void* Thread::thread_handler(void* object) thread->Run(); debug("Thread-func exited"); - + thread->m_running = false; - + if (thread->m_autoDestroy) { debug("Autodestroying Thread-object"); diff --git a/daemon/util/Thread.h b/daemon/util/Thread.h index cd06325b..c004fd80 100644 --- a/daemon/util/Thread.h +++ b/daemon/util/Thread.h @@ -31,7 +31,7 @@ class Mutex { private: void* m_mutexObj; - + public: Mutex(); ~Mutex(); diff --git a/daemon/util/Util.cpp b/daemon/util/Util.cpp index 98664d7e..76acc3ec 100644 --- a/daemon/util/Util.cpp +++ b/daemon/util/Util.cpp @@ -299,7 +299,7 @@ void StringBuilder::AppendFmtV(const char* format, va_list ap) #ifdef WIN32 if (m == -1) { - m = _vscprintf(format, ap); + m = _vscprintf(format, ap); } #endif if (m + 1 > remainingSize) @@ -351,9 +351,9 @@ char* Util::BaseFileName(const char* filename) void Util::NormalizePathSeparators(char* path) { - for (char* p = path; *p; p++) + for (char* p = path; *p; p++) { - if (*p == ALT_PATH_SEPARATOR) + if (*p == ALT_PATH_SEPARATOR) { *p = PATH_SEPARATOR; } @@ -386,14 +386,14 @@ bool Util::ForceDirectories(const char* path, char* errBuf, int bufSize) errBuf[bufSize-1] = 0; return false; } - + if (ok && !S_ISDIR(buffer.st_mode)) { snprintf(errBuf, bufSize, "path %s is not a directory", normPath); errBuf[bufSize-1] = 0; return false; } - + if (!ok #ifdef WIN32 && strlen(normPath) > 2 @@ -421,21 +421,21 @@ bool Util::ForceDirectories(const char* path, char* errBuf, int bufSize) return false; } } - + if (mkdir(normPath, S_DIRMODE) != 0 && errno != EEXIST) { snprintf(errBuf, bufSize, "could not create directory %s: %s", normPath, GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); errBuf[bufSize-1] = 0; return false; } - + if (stat(normPath, &buffer) != 0) { snprintf(errBuf, bufSize, "could not read information for directory %s: %s", normPath, GetLastErrorMessage(sysErrStr, sizeof(sysErrStr))); errBuf[bufSize-1] = 0; return false; } - + if (!S_ISDIR(buffer.st_mode)) { snprintf(errBuf, bufSize, "path %s is not a directory", normPath); @@ -480,46 +480,46 @@ bool Util::DirEmpty(const char* dirFilename) bool Util::LoadFileIntoBuffer(const char* fileName, char** buffer, int* bufferLength) { - FILE* file = fopen(fileName, FOPEN_RB); - if (!file) - { - return false; - } + FILE* file = fopen(fileName, FOPEN_RB); + if (!file) + { + return false; + } - // obtain file size. - fseek(file , 0 , SEEK_END); - int size = (int)ftell(file); - rewind(file); + // obtain file size. + fseek(file , 0 , SEEK_END); + int size = (int)ftell(file); + rewind(file); - // allocate memory to contain the whole file. - *buffer = (char*) malloc(size + 1); - if (!*buffer) - { - return false; - } + // allocate memory to contain the whole file. + *buffer = (char*) malloc(size + 1); + if (!*buffer) + { + return false; + } - // copy the file into the buffer. - fread(*buffer, 1, size, file); + // copy the file into the buffer. + fread(*buffer, 1, size, file); - fclose(file); + fclose(file); - (*buffer)[size] = 0; + (*buffer)[size] = 0; - *bufferLength = size + 1; + *bufferLength = size + 1; - return true; + return true; } bool Util::SaveBufferIntoFile(const char* fileName, const char* buffer, int bufLen) { - FILE* file = fopen(fileName, FOPEN_WB); - if (!file) - { - return false; - } + FILE* file = fopen(fileName, FOPEN_WB); + if (!file) + { + return false; + } int writtenBytes = fwrite(buffer, 1, bufLen, file); - fclose(file); + fclose(file); return writtenBytes == bufLen; } @@ -615,7 +615,7 @@ void Util::MakeValidFilename(char* filename, char cReplaceChar, bool allowSlashe // remove trailing dots and spaces. they are not allowed in directory names on windows, // but we remove them on posix also, in a case the directory is accessed from windows via samba. - for (int len = strlen(filename); len > 0 && (filename[len - 1] == '.' || filename[len - 1] == ' '); len--) + for (int len = strlen(filename); len > 0 && (filename[len - 1] == '.' || filename[len - 1] == ' '); len--) { filename[len - 1] = '\0'; } @@ -674,12 +674,12 @@ void Util::SplitInt64(long long Int64, unsigned long* Hi, unsigned long* Lo) *Lo = (unsigned long)(Int64 & 0xFFFFFFFF); } -/* Base64 decryption is taken from +/* Base64 decryption is taken from * Article "BASE 64 Decoding and Encoding Class 2003" by Jan Raddatz * http://www.codeguru.com/cpp/cpp/algorithms/article.php/c5099/ */ -const static char BASE64_DEALPHABET [128] = +const static char BASE64_DEALPHABET [128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19 @@ -709,7 +709,7 @@ unsigned int DecodeByteQuartet(char* inputBuffer, char* outputBuffer) buffer = buffer << 14; outputBuffer [0] = (char)(buffer >> 24); - + return 1; } else @@ -721,7 +721,7 @@ unsigned int DecodeByteQuartet(char* inputBuffer, char* outputBuffer) outputBuffer [0] = (char)(buffer >> 24); outputBuffer [1] = (char)(buffer >> 16); - + return 2; } } @@ -730,7 +730,7 @@ unsigned int DecodeByteQuartet(char* inputBuffer, char* outputBuffer) buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[0]]) << 6; buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[1]]) << 6; buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[2]]) << 6; - buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[3]]) << 6; + buffer = (buffer | BASE64_DEALPHABET [(int)inputBuffer[3]]) << 6; buffer = buffer << 2; outputBuffer [0] = (char)(buffer >> 24); @@ -917,7 +917,7 @@ long long Util::FreeDiskSize(const char* path) } #else struct statvfs diskdata; - if (!statvfs(path, &diskdata)) + if (!statvfs(path, &diskdata)) { return (long long)diskdata.f_frsize * (long long)diskdata.f_bavail; } @@ -998,7 +998,7 @@ bool Util::ExpandHomePath(const char* filename, char* buffer, int bufSize) strncpy(buffer, filename ? filename : "", bufSize); buffer[bufSize - 1] = '\0'; } - + return true; } #endif @@ -1318,12 +1318,12 @@ ub4 hash(register ub1 *k, register ub4 length, register ub4 initval) // register ub4 initval; /* the previous hash, or an arbitrary value */ { register ub4 a,b,c,len; - + /* Set up the internal state */ len = length; a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ c = initval; /* the previous hash value */ - + /*---------------------------------------- handle most of the key */ while (len >= 12) { @@ -1333,7 +1333,7 @@ ub4 hash(register ub1 *k, register ub4 length, register ub4 initval) mix(a,b,c); k += 12; len -= 12; } - + /*------------------------------------- handle the last 11 bytes */ c += length; switch(len) /* all the case statements fall through */ @@ -1404,8 +1404,8 @@ inline int days_from_1jan(int year,int month,int day) { static const int days[2][12] = { - { 0,31,59,90,120,151,181,212,243,273,304,334}, - { 0,31,60,91,121,152,182,213,244,274,305,335} + { 0,31,59,90,120,151,181,212,243,273,304,334}, + { 0,31,60,91,121,152,182,213,244,274,305,335} }; return days[is_leap(year)][month-1] + day - 1; } @@ -1416,14 +1416,14 @@ inline time_t internal_timegm(tm const *t) int month = t->tm_mon; if(month > 11) { - year += month/12; - month %= 12; + year += month/12; + month %= 12; } else if(month < 0) { - int years_diff = (-month + 11)/12; - year -= years_diff; - month+=12 * years_diff; + int years_diff = (-month + 11)/12; + year -= years_diff; + month+=12 * years_diff; } month++; int day = t->tm_mday; @@ -1528,77 +1528,77 @@ unsigned long Util::Crc32(unsigned char *block, unsigned long length) unsigned long gf2_matrix_times(unsigned long *mat, unsigned long vec) { - unsigned long sum; + unsigned long sum; - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; } void gf2_matrix_square(unsigned long *square, unsigned long *mat) { - int n; + int n; - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); } unsigned long Util::Crc32Combine(unsigned long crc1, unsigned long crc2, unsigned long len2) { - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - /* degenerate case (also disallow negative lengths) */ - if (len2 <= 0) - return crc1; + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; - /* if no more bits set, then done */ - if (len2 == 0) - break; + /* if no more bits set, then done */ + if (len2 == 0) + break; - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; - /* if no more bits set, then done */ - } while (len2 != 0); + /* if no more bits set, then done */ + } while (len2 != 0); - /* return combined crc */ - crc1 ^= crc2; + /* return combined crc */ + crc1 ^= crc2; - return crc1; + return crc1; } int Util::NumberOfCpuCores() @@ -1625,18 +1625,18 @@ bool Util::FlushFileBuffers(int fileDescriptor, char* errBuf, int bufSize) } return ok; #else -#ifdef HAVE_FULLFSYNC +#ifdef HAVE_FULLFSYNC int ret = fcntl(fileDescriptor, F_FULLFSYNC) == -1 ? 1 : 0; #elif HAVE_FDATASYNC - int ret = fdatasync(fileDescriptor); + int ret = fdatasync(fileDescriptor); #else - int ret = fsync(fileDescriptor); -#endif - if (ret != 0) - { + int ret = fsync(fileDescriptor); +#endif + if (ret != 0) + { GetLastErrorMessage(errBuf, bufSize); - } - return ret == 0; + } + return ret == 0; #endif } @@ -1651,7 +1651,7 @@ bool Util::FlushDirBuffers(const char* filename, char* errBuf, int bufSize) char* p = (char*)strrchr(parentPath, PATH_SEPARATOR); if (p) { - *p = '\0'; + *p = '\0'; } fileMode = FOPEN_RB; #endif @@ -1700,16 +1700,16 @@ unsigned int WebUtil::DecodeBase64(char* inputBuffer, int inputBufferLength, cha if ((inputBuffer [InputBufferIndex] >= 48 && inputBuffer [InputBufferIndex] <= 57) || (inputBuffer [InputBufferIndex] >= 65 && inputBuffer [InputBufferIndex] <= 90) || (inputBuffer [InputBufferIndex] >= 97 && inputBuffer [InputBufferIndex] <= 122) || - inputBuffer [InputBufferIndex] == '+' || - inputBuffer [InputBufferIndex] == '/' || + inputBuffer [InputBufferIndex] == '+' || + inputBuffer [InputBufferIndex] == '/' || inputBuffer [InputBufferIndex] == '=') { ByteQuartet [i] = inputBuffer [InputBufferIndex]; i++; } - + InputBufferIndex++; - + if (i == 4) { OutputBufferIndex += DecodeByteQuartet(ByteQuartet, outputBuffer + OutputBufferIndex); i = 0; @@ -1817,7 +1817,7 @@ char* WebUtil::XmlEncode(const char* raw) } // accept only valid XML 1.0 characters - if (cp == 0x9 || cp == 0xA || cp == 0xD || + if (cp == 0x9 || cp == 0xA || cp == 0xD || (0x20 <= cp && cp <= 0xD7FF) || (0xE000 <= cp && cp <= 0xFFFD) || (0x10000 <= cp && cp <= 0x10FFFF)) @@ -2024,7 +2024,7 @@ char* WebUtil::JsonEncode(const char* raw) case '\r': case '\t': reqSize++; - break; + break; default: if (ch < 0x20 || ch >= 0x80) { @@ -2174,7 +2174,7 @@ void WebUtil::JsonDecode(char* raw) break; } p++; - break; + break; } default: *output++ = *p++; @@ -2287,7 +2287,7 @@ void WebUtil::UrlDecode(char* raw) 'a' <= c2 && c2 <= 'f' ? c2 - 'a' + 10 : 0; unsigned char ch = (c1 << 4) + c2; *output++ = (char)ch; - break; + break; } default: *output++ = *p++; @@ -2371,7 +2371,7 @@ char* WebUtil::Latin1ToUtf8(const char* str) while (*in) { if (*in < 128) - { + { *out++ = *in++; } else @@ -2805,21 +2805,21 @@ unsigned int ZLib::GZip(const void* inputBuffer, int inputBufferLength, void* ou zstr.avail_in = inputBufferLength; zstr.next_out = (Bytef*)outputBuffer; zstr.avail_out = outputBufferLength; - + /* add 16 to MAX_WBITS to enforce gzip format */ if (Z_OK != deflateInit2(&zstr, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) { return 0; } - + unsigned int total_out = 0; if (deflate(&zstr, Z_FINISH) == Z_STREAM_END) { total_out = (unsigned int)zstr.total_out; } - + deflateEnd(&zstr); - + return total_out; } diff --git a/daemon/util/Util.h b/daemon/util/Util.h index 89168404..cab2e5c0 100644 --- a/daemon/util/Util.h +++ b/daemon/util/Util.h @@ -175,7 +175,7 @@ public: * If revision number is not available only version is returned ("0.7.0"). */ static const char* VersionRevision() { return VersionRevisionBuf; }; - + static char VersionRevisionBuf[100]; static void Init(); @@ -361,7 +361,7 @@ public: * calculates the size required for output buffer */ static unsigned int GZipLen(int inputBufferLength); - + /* * returns the size of bytes written to szOutputBuffer or 0 if the buffer is too small or an error occured. */ diff --git a/daemon/windows/WinConsole.cpp b/daemon/windows/WinConsole.cpp index 16557802..fd6eee32 100644 --- a/daemon/windows/WinConsole.cpp +++ b/daemon/windows/WinConsole.cpp @@ -24,7 +24,7 @@ #ifdef HAVE_CONFIG_H -#include +#include #endif #define SKIP_DEFAULT_WINDOWS_HEADERS @@ -125,9 +125,9 @@ void WinConsole::InitAppMode() SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); m_instance = (HINSTANCE)GetModuleHandle(0); - DWORD processId; - GetWindowThreadProcessId(GetConsoleWindow(), &processId); - m_appMode = false; + DWORD processId; + GetWindowThreadProcessId(GetConsoleWindow(), &processId); + m_appMode = false; if (GetCurrentProcessId() == processId && g_ArgumentCount == 1) { @@ -358,7 +358,7 @@ void WinConsole::ShowMenu() { POINT curPoint; GetCursorPos(&curPoint); - SetForegroundWindow(m_trayWindow); + SetForegroundWindow(m_trayWindow); UINT itemId = TrackPopupMenu(m_menu, TPM_RETURNCMD | TPM_NONOTIFY, curPoint.x, curPoint.y, 0, m_trayWindow, NULL); @@ -881,10 +881,10 @@ void WinConsole::BuildMenu() /* BOOL DeleteMenu( - HMENU hMenu, // handle to menu - UINT uPosition, // menu item identifier or position - UINT uFlags // menu item flag - ); + HMENU hMenu, // handle to menu + UINT uPosition, // menu item identifier or position + UINT uFlags // menu item flag + ); */ } @@ -965,7 +965,7 @@ void WinConsole::SetupConfigFile() fwrite(config, 1, p - config, outfile); fwrite("MainDir=", 1, 8, outfile); fwrite(appDataPath, 1, strlen(appDataPath), outfile); - + fwrite(p + strlen(SIGNATURE), 1, size - (p + strlen(SIGNATURE) - config) - 1, outfile); fclose(outfile); } diff --git a/daemon/windows/WinService.cpp b/daemon/windows/WinService.cpp index 0bd4d6fe..c7acdbf3 100644 --- a/daemon/windows/WinService.cpp +++ b/daemon/windows/WinService.cpp @@ -40,7 +40,7 @@ extern void ExitProc(); RunProc Run = NULL; char* strServiceName = "NZBGet"; -SERVICE_STATUS_HANDLE nServiceStatusHandle; +SERVICE_STATUS_HANDLE nServiceStatusHandle; DWORD nServiceCurrentStatus; BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWaitHint) @@ -70,7 +70,7 @@ BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWaitHint) void ServiceCtrlHandler(DWORD nControlCode) { switch(nControlCode) - { + { case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: nServiceCurrentStatus = SERVICE_STOP_PENDING; @@ -103,7 +103,7 @@ void ServiceMain(DWORD argc, LPTSTR *argv) { return; } - + Run(); UpdateServiceStatus(SERVICE_STOPPED, 0); @@ -133,7 +133,7 @@ void InstallService(int argc, char *argv[]) printf("Could not install service\n"); return; } - + char exeName[1024]; GetModuleFileName(NULL, exeName, 1024); exeName[1024-1] = '\0'; @@ -168,7 +168,7 @@ void UnInstallService() printf("Could not uninstall service\n"); return; } - + SC_HANDLE hService = OpenService(scm, strServiceName, STANDARD_RIGHTS_REQUIRED); if(!hService) {