From 7a450b0c02e4bb2908198eaa361fde63ad89b87d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:52:12 +0000 Subject: [PATCH] la_serva: fix memory/descriptor leaks, crashes and a DB-log deadlock Leaks that grew without bound: - Dead module connections were never removed (half-open TCP after a module power loss / network drop): every one kept 3 threads, 8 MB of socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s; la_mojo sends a status about every second), and accepted sockets get TCP keepalive (30 s idle, 3 probes of 10 s). - The client socket was only closed on an I/O error: a handler removed for any other reason (module disabled / not registered, idle) leaked its descriptor until accept() failed with EMFILE - which ended the accept thread for good. ~serverPort now shuts down and closes it; transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED, EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is always a disconnect, whatever errno holds. - servaSessionManager::reopenSession stored the reopened (expired) session in the per-track map, overwriting the track's ACTIVE session: its data and open report.db leaked and it was never closed in MySQL. Reopened sessions are now kept outside the map and released by the caller (addVideo, getSessionBase). - servaVideoComposer leaked its session data, an open SQLite connection and both video queues on every composition; servaKernel leaked a composer whose compose() failed, never initialised / released the automatic composer (it ran at most once) and leaked the media info of every encoded video (processVideoFile success path). Crashes / corruption: - vector erase() with the old iterator reused (netServer client cleanup, encoder / composer pools, 4 ModBus action loops). - transportSocket::_close wrote the stop byte into the read end of the pipe (threads only stopped at the 5 s select timeout, blocking the accept thread on every disconnect) and left closed pipe numbers set (a second _close could write into another connection's socket). - Session map used without the lock from RPC, kernel and ModBus threads: now a recursive mutex held for each public operation. - Freeze on the first MySQL error with DB logging enabled: Query() logs while holding the non-recursive DB mutex and the log service wrote synchronously into the DB (same-thread and two-thread deadlock). The DB log service now queues lines (max 1000) and writes them with MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect retries per query are bounded (3) instead of looping forever while holding the mutex. The log line parser also skips the UTC offset. - basicMutex::try_lock returned true when the lock was NOT taken: an uncontended try_lock took the mutex and the caller never released it (basicEngine, serial transport, ...). - Kernel restart (web commands): the ModBus singleton was deleted but not reset (next getInstance returned freed memory), the remote client kept the deleted kernel and refused to start again, and EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving component still used. Now fixed / the DB object is kept. - Life monitoring overflowed module_id[4] for platforms with > 4 modules; registerServA overflowed a 120-byte stack buffer, closed a popen() stream with fclose and leaked the config; 9 config strings in servaBackend were allocated one byte short; video chunk length is now checked against the packet; "eased" events copied every field from itself (all 0); networkServer freed libconfig's host string. Minor: ModBus action list / sessions freed at shutdown, session-start event payload freed if the event cannot be created, the per-second "No History Auto Delete!" log line moved to DEBUG_EXTRA. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/serverMySQL_dataBinder.cpp | 57 +++++++--- lib/App/serva/objectMySQLLoggingService.cpp | 40 +++++-- lib/App/serva/objectMySQLLoggingService.h | 14 +++ lib/App/serva/servaBackend.cpp | 31 +++-- lib/App/serva/servaKernel.cpp | 27 ++++- lib/App/serva/servaKernelToolKit.cpp | 14 ++- lib/App/serva/servaLifeMonitoring.cpp | 3 +- lib/App/serva/servaMediaEncoder.h | 2 +- lib/App/serva/servaModBusManager.cpp | 15 ++- lib/App/serva/servaRemoteClient.cpp | 6 + lib/App/serva/servaRemoteClientHandler.cpp | 50 +++++--- lib/App/serva/servaRemoteClientHandler.h | 6 +- lib/App/serva/servaSessionManager.cpp | 53 ++++++--- lib/App/serva/servaSessionManager.h | 9 +- lib/App/serva/servaVideoComposer.cpp | 18 ++- lib/App/serva/servaVideoComposer.h | 2 +- lib/components/base/basicMutex.h | 4 +- lib/data/mysql/mysql_class.cpp | 58 +++++++++- lib/data/mysql/mysql_class.h | 4 + lib/data/net/netServer.cpp | 119 ++++++++++++-------- lib/data/net/netServer.h | 7 ++ lib/data/net/serverPort.cpp | 27 ++++- lib/data/transport/transportSocket.cpp | 25 ++-- 23 files changed, 429 insertions(+), 162 deletions(-) diff --git a/lib/App/common/serverMySQL_dataBinder.cpp b/lib/App/common/serverMySQL_dataBinder.cpp index b2acd28f..7efb923e 100644 --- a/lib/App/common/serverMySQL_dataBinder.cpp +++ b/lib/App/common/serverMySQL_dataBinder.cpp @@ -1829,24 +1829,55 @@ DBC_UINT64_LIST *servaMySQLDBC::listScadaPosts( uint64_t platform_id ){ return tVal; }; -bool servaMySQLDBC::putIntoLog(CSTR A, CSTR B, CSTR C) +// Escapes for a quoted MySQL string literal without using the connection (mysql_real_escape_string +// needs the access mutex, which the log path must not wait for) +static void logEscape(const char * src, char * dst, size_t dstSize) { - if (m_bIsConnected) + size_t o = 0; + for (const char * c = (src != NULL) ? src : ""; *c && o + 2 < dstSize; c++) { - char tQBuf[MAX_PATH_LEN]; - CSTR LL = m_pDatabase->escapeString(C); - if (LL) + char e = 0; + switch (*c) { - sprintf(tQBuf, "INSERT INTO `server_log_messages` SET lvl = '%s', `ts`='%s', `msg`='%s'", A, B, LL); - free(LL); -#ifdef DEBUG_ALL - LOG(tQBuf); -#endif - m_pDatabase->SilentQuery(tQBuf); - return true; + case '\\': e = '\\'; break; + case '\'': e = '\''; break; + case '"' : e = '"'; break; + case '\n': e = 'n'; break; + case '\r': e = 'r'; break; + case 0x1a: e = 'Z'; break; + default : break; }; + if (e) + { + dst[o++] = '\\'; + dst[o++] = e; + } + else + { + dst[o++] = *c; + } }; - return false; + dst[o] = (char) 0; +} + +/* + Called by the database log service from inside the log broadcast: must never block on the database + (see MySQL_Connector::TrySilentQuery). Returns false if the connection is busy right now; the log + service keeps the line and retries later. +*/ +bool servaMySQLDBC::putIntoLog(CSTR A, CSTR B, CSTR C) +{ + if (! m_bIsConnected || m_pDatabase == NULL) + { + return false; + } + char tType[8], tTS[48], tMsg[MAX_PATH_LEN]; + logEscape(A, tType, sizeof(tType)); + logEscape(B, tTS, sizeof(tTS)); + logEscape(C, tMsg, sizeof(tMsg)); + char tQBuf[MAX_PATH_LEN + 128]; + snprintf(tQBuf, sizeof(tQBuf), "INSERT INTO `server_log_messages` SET lvl = '%s', `ts`='%s', `msg`='%s'", tType, tTS, tMsg); + return m_pDatabase->TrySilentQuery(tQBuf); } uint64_t servaMySQLDBC::registerMojo(CSTR A, CSTR B) diff --git a/lib/App/serva/objectMySQLLoggingService.cpp b/lib/App/serva/objectMySQLLoggingService.cpp index fa021107..cf73d041 100644 --- a/lib/App/serva/objectMySQLLoggingService.cpp +++ b/lib/App/serva/objectMySQLLoggingService.cpp @@ -15,19 +15,37 @@ void objectMySQLLoggingService::logMessage( CSTR Msg ){ logMessage( (const char * ) Msg ); }; +/* + Runs inside the log broadcast (log mutex held), possibly on a thread that is itself inside a database + call. Writing synchronously deadlocked the server on the first MySQL error (non-recursive DB mutex on + the same thread, or DB mutex <-> log mutex between two threads). Now the line is queued and the queue + is written only while the database is free (putIntoLog never blocks); the rest goes out with a later line. +*/ void objectMySQLLoggingService::logMessage( const char *Msg ){ - if( !m_bLogging ) return; - if( m_pDBC ){ - char tType[3]; - char tTS[20]; - strncpy( tType, Msg, 2); - tType[2] = (char) 0; - strncpy( tTS, Msg+3, 19); - tTS[19] = (char) 0; - CSTR tMsg = (CSTR)Msg+23; - m_pDBC->putIntoLog( tType, tTS, tMsg ); - } else { + if( !m_bLogging || Msg == NULL ) return; + if( m_pDBC == NULL ){ m_bLogging = false; + return; + }; + // Expected format: "LL YYYY-MM-DD HH:MM:SS " (shorter lines were read past their end) + if ( strlen( Msg ) < 23 ) return; + MYSQL_LOG_LINE tLine; + strncpy( tLine.type, Msg, 2 ); + tLine.type[2] = (char) 0; + strncpy( tLine.ts, Msg+3, 19 ); + tLine.ts[19] = (char) 0; + // The timestamp may carry a UTC offset ("...HH:MM:SS+0200"): the message starts after it + const char *tRest = Msg + 22; + while ( *tRest && *tRest != ' ' ) tRest++; + if ( *tRest == ' ' ) tRest++; + tLine.msg = std::string( tRest ); + std::lock_guard tGuard( m_mPending ); + m_qPending.push_back( tLine ); + while ( m_qPending.size() > MYSQL_LOG_MAX_PENDING ) m_qPending.pop_front(); // bounded: drop the oldest + while ( !m_qPending.empty() ) { + MYSQL_LOG_LINE &tL = m_qPending.front(); + if ( !m_pDBC->putIntoLog( tL.type, tL.ts, (CSTR) tL.msg.c_str() ) ) break; // busy: retry with the next line + m_qPending.pop_front(); }; }; diff --git a/lib/App/serva/objectMySQLLoggingService.h b/lib/App/serva/objectMySQLLoggingService.h index c9a558b8..95e88ea5 100644 --- a/lib/App/serva/objectMySQLLoggingService.h +++ b/lib/App/serva/objectMySQLLoggingService.h @@ -2,6 +2,9 @@ #define __OBJECTMYSQLLOGGINGSERVICE_H_INCL__ #include +#include +#include +#include #include "../components/base/basicFunctionality.h" #include "../components/base/basicLoggingService.h" #include "../common/serverDataBinder.h" @@ -12,10 +15,21 @@ * @author Gagua */ +// Lines waiting for the database (it is busy, or the line was logged by a thread inside a DB call) +#define MYSQL_LOG_MAX_PENDING 1000 + +typedef struct S_MYSQL_LOG_LINE{ + char type[3]; + char ts[20]; + std::string msg; +} MYSQL_LOG_LINE; + class objectMySQLLoggingService : public basicLoggingService { private: bool m_bLogging; serverDataBinder * m_pDBC; + std::deque m_qPending; + std::mutex m_mPending; public: // Constructor objectMySQLLoggingService(); diff --git a/lib/App/serva/servaBackend.cpp b/lib/App/serva/servaBackend.cpp index 10303847..2d9e3bd4 100644 --- a/lib/App/serva/servaBackend.cpp +++ b/lib/App/serva/servaBackend.cpp @@ -225,13 +225,13 @@ int main( int argc, char *argv[] ){ switch( eType ){ case ST_SN:{ - gsCFG_LICENSE = (CSTR) malloc(strlen( pTemp )); + gsCFG_LICENSE = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator //memcpy( gsCFG_LICENSE, pTemp, strlen( pTemp ) ); sprintf( gsCFG_LICENSE, "%s", pTemp ); break; }; case ST_BIND_ADDRESS:{ - gsCFG_ADDRESS = (CSTR) malloc(strlen( pTemp )); + gsCFG_ADDRESS = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( gsCFG_ADDRESS, "%s", pTemp ); break; }; @@ -240,12 +240,12 @@ int main( int argc, char *argv[] ){ break; }; case ST_PID_FILE:{ - gsCFG_PID_FILE = (CSTR) malloc(strlen( pTemp )); + gsCFG_PID_FILE = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( gsCFG_PID_FILE, "%s", pTemp ); break; }; case ST_LOG_FILE:{ - FLE_NAME = (CSTR) malloc(strlen( pTemp )); + FLE_NAME = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( FLE_NAME, "%s", pTemp ); break; }; @@ -265,27 +265,27 @@ int main( int argc, char *argv[] ){ break; }; case ST_DATABASE_SERVER:{ - gsCFG_DB_SERVER = (CSTR) malloc(strlen( pTemp )); + gsCFG_DB_SERVER = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( gsCFG_DB_SERVER, "%s", pTemp ); break; }; case ST_DATABASE_USER:{ - gsCFG_DB_USER = (CSTR) malloc(strlen( pTemp )); + gsCFG_DB_USER = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( gsCFG_DB_USER, "%s", pTemp ); break; }; case ST_DATABASE_PASSWORD:{ - gsCFG_DB_PASSWORD = (CSTR) malloc(strlen( pTemp )); + gsCFG_DB_PASSWORD = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( gsCFG_DB_PASSWORD, "%s", pTemp ); break; }; case ST_DATABASE_NAME:{ - gsCFG_DB_NAME = (CSTR) malloc(strlen( pTemp )); + gsCFG_DB_NAME = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( gsCFG_DB_NAME, "%s", pTemp ); break; }; case ST_SOCKET_NAME:{ - SSP_NAME = (CSTR) malloc(strlen( pTemp )); + SSP_NAME = (CSTR) malloc(strlen( pTemp ) + 1); // + 1: terminator sprintf( SSP_NAME, "%s", pTemp ); break; }; @@ -475,14 +475,11 @@ int main( int argc, char *argv[] ){ break; }; case EXIT_CODE_RELOAD_SERVICES:{ - delete( DBC ); - - DBC = servaMySQLDBC::getInstance( Settings ); - - if( DBC ) { - if( !DBC->connect() ) ExitCode = 0; - - } else ExitCode = 0; + // Keep the database object: the session manager, the RPC connections, the life + // monitor and the DB log service survive the kernel restart and hold pointers to it + // (deleting and recreating it left them all dangling). The connection itself + // reconnects on its own when the server went away. + if( DBC == NULL ) ExitCode = 0; break; }; case EXIT_CODE_FACTORY_RESET:{ diff --git a/lib/App/serva/servaKernel.cpp b/lib/App/serva/servaKernel.cpp index c8621645..9ff2d726 100644 --- a/lib/App/serva/servaKernel.cpp +++ b/lib/App/serva/servaKernel.cpp @@ -63,6 +63,7 @@ servaKernel::servaKernel( config_setting_t *ptr ):kernelPrototype( ptr ){ m_pSM = NULL; m_pRPC = NULL;//?? m_pModBus = NULL; + m_pVideoComposer = NULL; // was never initialised: automatic composing ran at most once, or never memset( &m_sServaConfig, 0, sizeof( DBC_SERVA_CONFIG )); setWM( WM_NONE ); }; @@ -81,6 +82,17 @@ servaKernel::~servaKernel(){ //}; if ( m_pModBus ) { delete( (servaModBusManager *) m_pModBus ); + m_pModBus = NULL; + }; + // Running encoders / composers belong to this kernel (their destructors stop and join the threads); + // before, they were left running when the kernel was restarted + for ( V_MEDIA_ENCODERS::iterator idx = m_vEncodersPool.begin(); idx != m_vEncodersPool.end(); idx++ ) delete( *idx ); + m_vEncodersPool.clear(); + for ( V_VIDEO_COMPOSERS::iterator idx = m_vComposersPool.begin(); idx != m_vComposersPool.end(); idx++ ) delete( *idx ); + m_vComposersPool.clear(); + if ( m_pVideoComposer ) { + delete( m_pVideoComposer ); + m_pVideoComposer = NULL; }; #ifdef LINUX_KERNEL_WATCHDOG LOG("Disable WD!"); @@ -343,6 +355,7 @@ void servaKernel::m_fThreadProc( void ){ m_vComposersPool.push_back(tCMP); } else { LOG("Disengage Composer!"); + delete( tCMP ); // was leaked }; }; }; @@ -446,9 +459,9 @@ void servaKernel::m_fThreadProc( void ){ if ( m_vEncodersPool.size() ) { for ( V_MEDIA_ENCODERS::iterator idx = m_vEncodersPool.begin(); idx < m_vEncodersPool.end(); ) { - if ( (*idx)->getStatus() == ENCODER_FINISHED ) { - handleEncodedVideo( *idx ); - m_vEncodersPool.erase( idx ); + if ( (*idx)->getStatus() == ENCODER_FINISHED ) { + handleEncodedVideo( *idx ); // deletes the encoder + idx = m_vEncodersPool.erase( idx ); // erase() invalidates idx: continue with the returned one } else idx++; }; }; @@ -457,7 +470,7 @@ void servaKernel::m_fThreadProc( void ){ for ( V_VIDEO_COMPOSERS::iterator idx = m_vComposersPool.begin(); idx< m_vComposersPool.end(); ) { if ( (*idx)->isFinished() ) { delete( *idx ); - m_vComposersPool.erase( idx ); + idx = m_vComposersPool.erase( idx ); } else idx++; }; }; @@ -480,6 +493,11 @@ void servaKernel::m_fThreadProc( void ){ if ( m_pLifeMonitor ) m_pLifeMonitor->validate(); if ( m_pModBus ) ((servaModBusManager *)m_pModBus)->validate(); //m_pHardwareManager->updateSysInfo( &m_sSysInfo ); + // The automatic composer was never released after it finished, so it ran only once + if ( m_pVideoComposer != NULL && m_pVideoComposer->isFinished() ) { + delete( m_pVideoComposer ); + m_pVideoComposer = NULL; + }; if ( m_pVideoComposer == NULL ) { uint64_t tSID = m_pDBC->getSessionWithUnmergedVideo( m_sServaConfig.composerProceedDelay ); if ( tSID ) { @@ -544,6 +562,7 @@ bool servaKernel::processVideoFile( uint64_t dbid ){ LOG("Encoder Created!"); #endif m_vEncodersPool.push_back( ptr ); + free( NFO ); // was leaked on this (the normal) path return true; }; }; diff --git a/lib/App/serva/servaKernelToolKit.cpp b/lib/App/serva/servaKernelToolKit.cpp index 2a20a0a3..f6cc0948 100644 --- a/lib/App/serva/servaKernelToolKit.cpp +++ b/lib/App/serva/servaKernelToolKit.cpp @@ -84,6 +84,7 @@ bool servaKernel::registerServA(){ DBC_SERVA_CONFIG *tData = m_pDBC->getServaConfig(); if ( tData ) { memcpy(&m_sServaConfig, tData, sizeof(DBC_SERVA_CONFIG)); + free( tData ); // was leaked } else { memset(&m_sServaConfig, 0, sizeof(DBC_SERVA_CONFIG)); m_sServaConfig.encoderLimit = 1; @@ -93,13 +94,14 @@ bool servaKernel::registerServA(){ m_pDBC->setServerStatValue( SERVER_VERSION, _BUILD_STRING_ ); m_pDBC->setSystemProp("version_string", _BUILD_STRING_ ); #ifndef NO_EXEC_EXTERNALS - char OS_INFO[120]; + char OS_INFO[128]; // was 120 while fgets() wrote up to 127 bytes and [127] was set: stack overflow + OS_INFO[0] = (char)0; FILE *fd = popen("/bin/uname -s -r -v -m","r"); if( fd!= NULL ) { - fgets( OS_INFO, 127, fd); - OS_INFO[127] = (char)0; + if ( fgets( OS_INFO, sizeof( OS_INFO ), fd ) == NULL ) OS_INFO[0] = (char)0; + OS_INFO[sizeof( OS_INFO ) - 1] = (char)0; trim( OS_INFO ); - fclose( fd ); + pclose( fd ); // popen() streams must be closed with pclose() (fclose leaves a zombie process) fd = NULL; m_pDBC->setServerStatValue( SERVER_OS, OS_INFO ); m_pDBC->setSystemProp("os_info", (CSTR) OS_INFO ); @@ -235,9 +237,9 @@ bool servaKernel::updateStatus(){ LOG("No History Time Limit is set!"); #endif }; -#ifdef DEBUG +#ifdef DEBUG_EXTRA } else { - LOG("No History Auto Delete!"); + LOG("No History Auto Delete!"); // every second: ~86400 log lines (and DB log rows) a day in DEBUG builds #endif }; //Temperature reading diff --git a/lib/App/serva/servaLifeMonitoring.cpp b/lib/App/serva/servaLifeMonitoring.cpp index 5cfd2cb2..9a2cd90a 100644 --- a/lib/App/serva/servaLifeMonitoring.cpp +++ b/lib/App/serva/servaLifeMonitoring.cpp @@ -40,7 +40,8 @@ servaLifeMonitoring::servaLifeMonitoring():basicValidatable(),basicThread(){ uint8_t cid = 0; tHZ->lvl = 255; // To clean prev State tHZ->validated = false; - for ( DBC_UINT64_LIST::iterator jdx = tML->begin(); jdx != tML->end(); jdx++ ) { + // module_id[] has 4 entries: a platform with more modules overflowed the zone + for ( DBC_UINT64_LIST::iterator jdx = tML->begin(); jdx != tML->end() && cid < 4; jdx++ ) { tHZ->module_id[cid] = *jdx; tHZ->module_monitored[cid] = true; cid++; diff --git a/lib/App/serva/servaMediaEncoder.h b/lib/App/serva/servaMediaEncoder.h index 23fa6446..8b954b2b 100644 --- a/lib/App/serva/servaMediaEncoder.h +++ b/lib/App/serva/servaMediaEncoder.h @@ -59,7 +59,7 @@ class servaMediaEncoder: public basicThread{ //virtual void m_fThreadBProc( void ); public: explicit servaMediaEncoder( uint64_t Ref = 0 ); - ~servaMediaEncoder(); + virtual ~servaMediaEncoder(); bool create( CSTR src, CSTR dst, uint8_t fps = 15, int width = -1, int height = -1, CSTR custom = NULL ); uint8_t getStatus(); uint64_t getDBID(){ return m_nRefID;}; diff --git a/lib/App/serva/servaModBusManager.cpp b/lib/App/serva/servaModBusManager.cpp index 5f77a805..fe390235 100644 --- a/lib/App/serva/servaModBusManager.cpp +++ b/lib/App/serva/servaModBusManager.cpp @@ -34,6 +34,13 @@ servaModBusManager::servaModBusManager():basicThread(),basicValidatable(){ servaModBusManager::~servaModBusManager(){ waitThreadEnd( true ); + // The kernel deletes this singleton on restart: the next getInstance() must create a new one + // (it returned the deleted object before) + if ( _instance == this ) _instance = NULL; + m_mProtector.lock(); + for ( V_MODBUS_ACION_ITEMS::iterator idx = m_vActioItems.begin(); idx != m_vActioItems.end(); idx++ ) free( *idx ); + m_vActioItems.clear(); + m_mProtector.unlock(); if (m_vRtuUnits.size()) { for( V_MODBUS_RTU_INFO::iterator idx=m_vRtuUnits.begin(); idx != m_vRtuUnits.end(); idx++ ) { free( *idx ); @@ -402,7 +409,7 @@ void servaModBusManager::m_fThreadProc( void ){ if ( tRTU ) { if( handleRTU( tRTU, (*idx)->value, (*idx)->mask) ) { free( *idx ); - m_vActioItems.erase( idx ); + idx = m_vActioItems.erase( idx ); // erase() invalidates the iterator } else { LOG_ERROR("Cannot Issue SCADA Signal!"); idx++; @@ -605,7 +612,7 @@ bool servaModBusManager::dispatchEvent( EVENT_CONTAINER *Evt ){ if( (*idd)->module_id == tRTU->id ) { if( (((*idd)->value & bON ) == bON ) || (((*idd)->mask & bOFF ) == bOFF ) ){ free((*idd)); - m_vActioItems.erase( idd ); + idd = m_vActioItems.erase( idd ); // erase() invalidates the iterator } else idd++; } else idd++; }; @@ -862,7 +869,7 @@ void servaModBusManager::activateCoil( uint64_t rtu_id, uint8_t function_id, uin //check if shceduled signal is current if( (((*idz)->value & bON ) == bON ) || (((*idz)->mask & bOFF ) == bOFF ) ){ free((*idz)); - m_vActioItems.erase( idz ); + idz = m_vActioItems.erase( idz ); // erase() invalidates the iterator } else idz++; //break; } else idz++; @@ -909,7 +916,7 @@ void servaModBusManager::mitigateCoil( uint64_t rtu_id, uint8_t function_id, uin //check if shceduled signal is current if( (((*idz)->value & bON ) == bON ) || (((*idz)->mask & bOFF ) == bOFF ) ){ free((*idz)); - m_vActioItems.erase( idz ); + idz = m_vActioItems.erase( idz ); // erase() invalidates the iterator } else idz++; //break; } else idz++; diff --git a/lib/App/serva/servaRemoteClient.cpp b/lib/App/serva/servaRemoteClient.cpp index 90a9bf73..012e4da3 100644 --- a/lib/App/serva/servaRemoteClient.cpp +++ b/lib/App/serva/servaRemoteClient.cpp @@ -18,6 +18,10 @@ servaRemoteClient *servaRemoteClient::_instance = NULL; servaRemoteClient *servaRemoteClient::getInstance( servaKernel *ptr ){ if ( _instance == NULL ) { _instance = new servaRemoteClient( ptr ); + } else if ( ptr != NULL ) { + // The kernel is deleted and recreated on restart (web command): the server keeps running + // and its connections stay, but they must use the new kernel (was a dangling pointer) + _instance->m_pMaster = ptr; } return _instance; }; @@ -49,6 +53,8 @@ bool servaRemoteClient::start(){ if( MainSocket == INVALID_SOCKET ){ return BootUp(); }; + // Already accepting (kernel restart): init() would refuse and make the new kernel fail to start + if ( basicThread::getStatus() == TH_WORKING ) return true; return init(); }; diff --git a/lib/App/serva/servaRemoteClientHandler.cpp b/lib/App/serva/servaRemoteClientHandler.cpp index 637f114d..1db54544 100644 --- a/lib/App/serva/servaRemoteClientHandler.cpp +++ b/lib/App/serva/servaRemoteClientHandler.cpp @@ -23,6 +23,10 @@ servaRPCHadnler::servaRPCHadnler( int SocketFD, networkServiceEngine *ptr ):basi m_nOutbondSerial = 0; m_dSessionDBID = 0; m_bClientStructsArePacked = true; // Hope the Client as We are + m_bTrainOnTrack = false; + m_tLastRx = time( NULL ); + memset( m_cRemoteIP, 0, sizeof( m_cRemoteIP ) ); + memset( m_cRemoteIdentity, 0, sizeof( m_cRemoteIdentity ) ); m_nPreTrainCloudStatus = m_nCloudStatus = ARGUS_CLOUD_STATUS_NA; m_pDBC = servaMySQLDBC::getInstance(); m_pSM = servaSessionManager::getInstance(); @@ -82,7 +86,8 @@ bool servaRPCHadnler::setRemotePeerIP( CSTR ptr ){ sprintf(tB,"Remote Peer: %s", ptr ); LOG( tB ); #endif - strncpy( m_cRemoteIP, ptr, 64 ); + strncpy( m_cRemoteIP, ptr, sizeof( m_cRemoteIP ) - 1 ); + m_cRemoteIP[sizeof( m_cRemoteIP ) - 1] = (char)0; return true; }; @@ -128,6 +133,7 @@ protocolPackage *servaRPCHadnler::packetExtractor(U8 *Buffer, size_t BufferSize) }; bool servaRPCHadnler::packetHandler( protocolPackage *Package ){ + m_tLastRx = time( NULL ); // the peer is alive m_nInbondSerial = Package->m_pData[1]; m_nInbondSerial = ( m_nInbondSerial << 8 ) | Package->m_pData[2]; @@ -323,17 +329,18 @@ bool servaRPCHadnler::packetHandler( protocolPackage *Package ){ if( Package->m_nSize != tSize ){ m_bClientStructsArePacked = false; ARGUS_DATA_EVENT_EASED *tPtr = (ARGUS_DATA_EVENT_EASED *) (Package->m_pData+ARGUS_PAYLOAD_START); + // was tData.X = tData.X: every field except AREA stayed 0 tData.AREA = tPtr->AREA; - tData.AZIMUTH = tData.AZIMUTH; - tData.ELEVATION = tData.ELEVATION; - tData.MODULE_ID = tData.MODULE_ID; - tData.MS = tData.MS; - tData.RANGE = tData.RANGE; - tData.REF_ID = tData.REF_ID; - tData.SRC = tData.SRC; - tData.TS = tData.TS; - tData.TYPE = tData.TYPE; - strncpy( tData.UUID, tData.UUID, 64 ); + tData.AZIMUTH = tPtr->AZIMUTH; + tData.ELEVATION = tPtr->ELEVATION; + tData.MODULE_ID = tPtr->MODULE_ID; + tData.MS = tPtr->MS; + tData.RANGE = tPtr->RANGE; + tData.REF_ID = tPtr->REF_ID; + tData.SRC = tPtr->SRC; + tData.TS = tPtr->TS; + tData.TYPE = tPtr->TYPE; + memcpy( tData.UUID, tPtr->UUID, sizeof( tData.UUID ) ); } else { memcpy( &tData, Package->m_pData+ARGUS_PAYLOAD_START, sizeof(ARGUS_DATA_EVENT) ); }; @@ -433,7 +440,9 @@ bool servaRPCHadnler::packetHandler( protocolPackage *Package ){ break; }; case ARGUS_DATA_MSG_VIDEO_DATA:{ - uint32_t tt = m_pVideoHelper.saveNextChunk( Package->m_pData+ARGUS_HEADER_SIZE+1 ); + // payload after the message code, without the checksum + size_t tAvail = ( Package->m_nSize > ARGUS_HEADER_SIZE + 1 + ARGUS_CHECKSUM_SIZE ) ? Package->m_nSize - ARGUS_HEADER_SIZE - 1 - ARGUS_CHECKSUM_SIZE : 0; + uint32_t tt = m_pVideoHelper.saveNextChunk( Package->m_pData+ARGUS_HEADER_SIZE+1, tAvail ); #ifdef DEBUG_EXTRA char tK[128]; sprintf( tK, "Saved %d Bytes of Video!", tt ); @@ -471,6 +480,14 @@ void servaRPCHadnler::m_fThreadProc( void ){ if ( cTimeTSeconds != tTimeTSeconds ) { tSecondsCounter++; tTimeTSeconds = cTimeTSeconds; + // Dead connection: mark it disconnected, the network server then removes this handler + // (and ~serverPort closes the socket) + if ( ( cTimeTSeconds - m_tLastRx ) > RPC_IDLE_TIMEOUT_S && getConnectionStatus() != CS_DISCONNECTED ) { + char tB[160]; + snprintf( tB, sizeof( tB ), "No data from [%s][%s] for %d s - dropping the connection", m_cRemoteIP, m_cRemoteIdentity, RPC_IDLE_TIMEOUT_S ); + LOG_ERROR( tB ); + setConnectionStatus( CS_DISCONNECTED ); + }; // update clowd status m_mCloudProtector.lock(); m_pDBC->setCloudStatus( ARGUS_OBJECT_MODULE, m_dMojoDBID, m_nCloudStatus ); @@ -650,8 +667,8 @@ void servaVideoTransferHelper::clear(){ memset( &m_sIn, 0, sizeof(ARGUS_DATA_VIDEO_INFO) ); }; -uint32_t servaVideoTransferHelper::saveNextChunk( uint8_t *ptr ){ - if ( ptr ){ +uint32_t servaVideoTransferHelper::saveNextChunk( uint8_t *ptr, size_t avail ){ + if ( ptr && avail >= 12 ){ uint64_t tDBID = ptr[0]; tDBID = ( tDBID << 8 ) | ptr[1]; tDBID = ( tDBID << 8 ) | ptr[2]; @@ -664,6 +681,11 @@ uint32_t servaVideoTransferHelper::saveNextChunk( uint8_t *ptr ){ chusz = ( chusz << 8 ) | ptr[9]; chusz = ( chusz << 8 ) | ptr[10]; chusz = ( chusz << 8 ) | ptr[11]; + if ( chusz > avail - 12 ) { + // the length field claims more data than the packet holds + LOG_ERROR("Video chunk size exceeds the packet"); + return 0; + }; if ( m_pFD ) { if ( chusz ) { int rv = fwrite( ptr+12, 1, chusz, m_pFD ); diff --git a/lib/App/serva/servaRemoteClientHandler.h b/lib/App/serva/servaRemoteClientHandler.h index 6f16ed7b..f7a9e967 100644 --- a/lib/App/serva/servaRemoteClientHandler.h +++ b/lib/App/serva/servaRemoteClientHandler.h @@ -42,11 +42,14 @@ class servaVideoTransferHelper{ public: servaVideoTransferHelper(); ~servaVideoTransferHelper(); - uint32_t saveNextChunk( uint8_t *ptr ); + uint32_t saveNextChunk( uint8_t *ptr, size_t avail ); void clear(); bool init( CSTR base, uint64_t MID, uint64_t SID, ARGUS_DATA_VIDEO_INFO *ptr ); uint64_t getReferenceID(){ return m_nRemoteRefID; }; }; +// A connection that sends nothing for this long is dead (la_mojo sends a status about every second). +// Half-open connections (module powered off, cable/VPN down) are never reported by the socket itself. +#define RPC_IDLE_TIMEOUT_S 60 #define TRAIN_ON_TRACK true #define TRAIN_IS_GONE false @@ -72,6 +75,7 @@ class servaRPCHadnler: public basicThread, public networkClientHandler, public p uint32_t m_nCloudStatus; uint32_t m_nPreTrainCloudStatus; bool m_bTrainOnTrack; + volatile time_t m_tLastRx; // time of the last received packet bool peer_send_ack_evt( uint64_t evt_dbid, CSTR uuid ); bool peer_send_req_draw( uint8_t sensor, uint8_t draw_type = ARGUS_RPC_DRAW_TYPE_FAST, bool getexisted = true ); bool peer_send_byte_status( uint8_t status ); diff --git a/lib/App/serva/servaSessionManager.cpp b/lib/App/serva/servaSessionManager.cpp index 55d0e503..23dc8849 100644 --- a/lib/App/serva/servaSessionManager.cpp +++ b/lib/App/serva/servaSessionManager.cpp @@ -98,9 +98,25 @@ servaSessionManager::servaSessionManager( config_setting_t * Settings ){ servaSessionManager::~servaSessionManager(){ //Close all Ongoing Session since Application goes to die m_pDBC->closeAllOnGoingSessions(); + std::lock_guard tGuard( m_mSessionProtector ); + for( M_SESSIONS::iterator idx = m_mSessions.begin(); idx != m_mSessions.end(); idx++ ) freeSession( (*idx).second ); + m_mSessions.clear(); +}; + +void servaSessionManager::freeSession( SESSION_DATA *& sp ){ + if ( sp == NULL ) return; + if ( sp->m_pDataReport ) delete( sp->m_pDataReport ); // closes the session's report.db + free( sp ); + sp = NULL; +}; + +void servaSessionManager::closeReopened( SESSION_DATA *& sp ){ + // Reopened sessions are not in m_mSessions: just release them + freeSession( sp ); }; uint64_t servaSessionManager::addEvent( uint64_t tack_id, uint64_t module_id, ARGUS_DATA_EVENT *ptr ){ + std::lock_guard tGuard( m_mSessionProtector ); uint64_t rV = 0; if( SESSION_DATA *sp = updateSession( tack_id, module_id ) ) { if( addEvent( sp, ptr ) ) rV = sp->db_id; @@ -109,6 +125,7 @@ uint64_t servaSessionManager::addEvent( uint64_t tack_id, uint64_t module_id, AR }; bool servaSessionManager::addEvent( uint64_t sid, ARGUS_DATA_EVENT *ptr ){ + std::lock_guard tGuard( m_mSessionProtector ); if( SESSION_DATA *sp = validateSession( sid ) ) { return addEvent( sp, ptr ); }; @@ -236,6 +253,7 @@ bool servaSessionManager::addEvent( SESSION_DATA *sp, ARGUS_DATA_EVENT *ptr ){ }; bool servaSessionManager::addVideo( DBC_RPC_MEDIA_INFO_EX *ptr ){//uint32_t module_id, uint32_t ts, uint16_t tsms, CSTR uuid, CSTR fmt, uint8_t fps ){ + std::lock_guard tGuard( m_mSessionProtector ); if ( ptr == NULL ){ LOG_ERROR( "ExtInfo ptr is null!"); return false; @@ -278,11 +296,12 @@ bool servaSessionManager::addVideo( DBC_RPC_MEDIA_INFO_EX *ptr ){//uint32_t modu LOG( tQBuf ); #endif bool rv = sp->m_pDataReport->SilentQuery( tQBuf ); - if( bExpiredSession ) dropSession( ptr->session_id ); + if( bExpiredSession ) closeReopened( sp ); return rv; } else { LOG_ERROR( "Report DB is closed!"); }; + if( bExpiredSession ) closeReopened( sp ); return false; }; @@ -292,6 +311,7 @@ bool servaSessionManager::create(){ }; SESSION_DATA *servaSessionManager::getActiveSessionByTrack( uint64_t tack_id ){ + std::lock_guard tGuard( m_mSessionProtector ); SESSION_DATA * rVal = NULL; try { m_mSessionProtector.lock(); @@ -320,6 +340,7 @@ CSTR servaSessionManager::getReportDir( uint64_t track_id, uint32_t ts ){ }; CSTR servaSessionManager::getSessionBase( uint64_t sid ){ + std::lock_guard tGuard( m_mSessionProtector ); CSTR rData = NULL; SESSION_DATA *sp = validateSession( sid ); if ( sp ) return strdup( sp->reportVaultPath ); @@ -327,7 +348,7 @@ CSTR servaSessionManager::getSessionBase( uint64_t sid ){ sp = reopenSession( sid ); if ( sp ) { rData = strdup( sp->reportVaultPath ); - dropSession( sid ); + closeReopened( sp ); }; return rData; }; @@ -415,16 +436,13 @@ SESSION_DATA *servaSessionManager::reopenSession( uint64_t session_id ){ }; }; - if ( tData ){ - LOG("Assign Session To Vector!"); - m_mSessionProtector.lock(); - m_mSessions[tData->track_id] = tData; - m_mSessionProtector.unlock(); - }; + // Not put into m_mSessions: the map holds the ACTIVE session of each track, and storing the + // reopened one there overwrote (and leaked, never closed) the track's running session. return tData; }; SESSION_DATA *servaSessionManager::updateSession( uint64_t tack_id, uint64_t module_id ){ + std::lock_guard tGuard( m_mSessionProtector ); SESSION_DATA * tData = NULL; try { m_mSessionProtector.lock(); @@ -591,6 +609,7 @@ SESSION_DATA *servaSessionManager::updateSession( uint64_t tack_id, uint64_t mod tSData->track_id = tData->track_id; EVENT_CONTAINER *tEvt = createBasicEvent( tack_id, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_STARTED, NULL, NULL, tSData ); if ( tEvt ) basicEventHeap::getInstance()->broadcast( tEvt ); + else free( tSData ); }; // Put Session into collection m_mSessionProtector.lock(); @@ -638,6 +657,7 @@ SESSION_DATA *servaSessionManager::updateSession( uint64_t tack_id, uint64_t mod tSData->track_id = tData->track_id; EVENT_CONTAINER *tEvt = createBasicEvent( tack_id, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_STARTED, NULL, NULL, tSData ); if ( tEvt ) basicEventHeap::getInstance()->broadcast( tEvt ); + else free( tSData ); }; }; }; @@ -648,6 +668,7 @@ SESSION_DATA *servaSessionManager::updateSession( uint64_t tack_id, uint64_t mod }; bool servaSessionManager::updateSessionStat( uint64_t session_id, bool evt ){ + std::lock_guard tGuard( m_mSessionProtector ); if( SESSION_DATA *tD = validateSession( session_id ) ){ tD->lts = time( NULL ); if ( evt ) { @@ -689,9 +710,7 @@ bool servaSessionManager::validate(){ }; if ( bMustDelete ) { // Remove Session - delete( (*dE).second->m_pDataReport ); - free( (*dE).second ); - (*dE).second = NULL; + freeSession( (*dE).second ); m_mSessions.erase( dE ); }; m_mSessionProtector.unlock(); @@ -699,12 +718,14 @@ bool servaSessionManager::validate(){ }; SESSION_DATA *servaSessionManager::validateSession( uint64_t sid ){ + std::lock_guard tGuard( m_mSessionProtector ); for( M_SESSIONS::iterator idx = m_mSessions.begin(); idx != m_mSessions.end(); idx++ ) - if( (*idx).second->db_id == sid ) return (*idx).second; + if( (*idx).second && (*idx).second->db_id == sid ) return (*idx).second; return NULL; }; bool servaSessionManager::dropSession( uint64_t session_id ){ + std::lock_guard tGuard( m_mSessionProtector ); #ifdef DEBUG LOG("Drop Session!"); #endif @@ -715,16 +736,14 @@ bool servaSessionManager::dropSession( uint64_t session_id ){ }; bool servaSessionManager::dropSession( M_SESSIONS::iterator idx ){ - m_mSessionProtector.lock(); - delete( (*idx).second->m_pDataReport ); - free( (*idx).second ); - (*idx).second = NULL; + std::lock_guard tGuard( m_mSessionProtector ); + freeSession( (*idx).second ); m_mSessions.erase( idx ); - m_mSessionProtector.unlock(); return true; }; bool servaSessionManager::eraseSession( uint64_t session_id ){ + std::lock_guard tGuard( m_mSessionProtector ); // Erase just not important sessions // In case The session is Opened! #ifdef DEBUG diff --git a/lib/App/serva/servaSessionManager.h b/lib/App/serva/servaSessionManager.h index 73bc7d7f..61d1d98c 100644 --- a/lib/App/serva/servaSessionManager.h +++ b/lib/App/serva/servaSessionManager.h @@ -2,6 +2,7 @@ #define __SERV_A_SESSION_MANAGER_HEADER__ #include +#include #include "../data/sqlite/sqlite_class.h" #include "../common/dataBinder_ReportAux.h" @@ -25,10 +26,16 @@ class servaSessionManager{ bool m_bRepIsConnected; char web_access_user[64]; char web_access_group[64]; - basicMutex m_mSessionProtector; + // Recursive: public methods hold it for the whole operation and call each other + // (RPC handler threads, kernel thread and ModBus thread use the sessions concurrently) + std::recursive_mutex m_mSessionProtector; char m_pDbReportBase[MAX_PATH]; bool addEvent( SESSION_DATA *sp, ARGUS_DATA_EVENT *ptr ); //DBC_EVT_RECORD *ptr ); + // Opens an expired session outside m_mSessions (the map holds the ACTIVE session per track); + // release it with closeReopened() SESSION_DATA * reopenSession( uint64_t session_id ); + void closeReopened( SESSION_DATA *& sp ); + void freeSession( SESSION_DATA *& sp ); bool dropSession( uint64_t session_id ); bool dropSession( M_SESSIONS::iterator idx ); protected: diff --git a/lib/App/serva/servaVideoComposer.cpp b/lib/App/serva/servaVideoComposer.cpp index 5f2e08c0..51f4fb16 100644 --- a/lib/App/serva/servaVideoComposer.cpp +++ b/lib/App/serva/servaVideoComposer.cpp @@ -1361,6 +1361,8 @@ servaVideoComposer::servaVideoComposer( uint64_t session_id ){ m_uRModuleID = 0; m_uComposerRecordId = 0; m_nSessionID = session_id; + m_pSessionData = NULL; // set by compose(); freed by the destructor + m_bLStage = m_bRStage = 0; if ( m_pDBC ) { DBC_MEDIA_COMPOSER_DATA * tData = m_pDBC->getVideoComposerData(); if (tData) { @@ -1377,6 +1379,18 @@ servaVideoComposer::servaVideoComposer( uint64_t session_id ){ servaVideoComposer::~servaVideoComposer(){ finishupCompose(); + // The thread reads the queues and the session data: stop it before releasing them + waitThreadEnd( true ); + // Before, everything below leaked on every composition, including an open SQLite connection + for ( V_VP_INFO::iterator idx = m_vLVideoQueue.begin(); idx != m_vLVideoQueue.end(); idx++ ) free( *idx ); + m_vLVideoQueue.clear(); + for ( V_VP_INFO::iterator idx = m_vRVideoQueue.begin(); idx != m_vRVideoQueue.end(); idx++ ) free( *idx ); + m_vRVideoQueue.clear(); + if ( m_pSessionData ) { + if ( m_pSessionData->m_pDataReport ) delete( m_pSessionData->m_pDataReport ); + free( m_pSessionData ); + m_pSessionData = NULL; + }; }; bool servaVideoComposer::compose(){ @@ -1517,7 +1531,7 @@ bool servaVideoComposer::loadLeftQueue(){ Assoc * cArr; Assoc::iterator it; for (size_t i = 0; i < result->size(); i++){ - VIDEO_PART_INFO *tVI = (VIDEO_PART_INFO *)malloc(sizeof(VIDEO_PART_INFO )); + VIDEO_PART_INFO *tVI = (VIDEO_PART_INFO *)calloc(1, sizeof(VIDEO_PART_INFO )); if ( tVI ) { cArr = result->at(i); it = cArr->find("id"); @@ -1575,7 +1589,7 @@ bool servaVideoComposer::loadRightQueue(){ Assoc * cArr; Assoc::iterator it; for (size_t i = 0; i < result->size(); i++){ - VIDEO_PART_INFO *tVI = (VIDEO_PART_INFO *)malloc(sizeof(VIDEO_PART_INFO )); + VIDEO_PART_INFO *tVI = (VIDEO_PART_INFO *)calloc(1, sizeof(VIDEO_PART_INFO )); if ( tVI ) { cArr = result->at(i); it = cArr->find("id"); diff --git a/lib/App/serva/servaVideoComposer.h b/lib/App/serva/servaVideoComposer.h index 3f40efc7..e041bd37 100644 --- a/lib/App/serva/servaVideoComposer.h +++ b/lib/App/serva/servaVideoComposer.h @@ -60,7 +60,7 @@ class servaVideoComposer: public basicThread { virtual void m_fThreadProc(void); public: explicit servaVideoComposer( uint64_t session_id ); - ~servaVideoComposer(); + virtual ~servaVideoComposer(); bool compose(); bool isFinished(); uint8_t getStatus(); diff --git a/lib/components/base/basicMutex.h b/lib/components/base/basicMutex.h index 20000d74..45bd8590 100644 --- a/lib/components/base/basicMutex.h +++ b/lib/components/base/basicMutex.h @@ -84,9 +84,11 @@ inline void basicMutex::lock(void) MUTEX_LOCK(m_sMutexHandle); } +// true = the mutex was acquired (pthread_mutex_trylock returns 0 on success). It returned the opposite: +// an uncontended try_lock() took the mutex but reported failure, so the caller never released it. inline bool basicMutex::try_lock(void) { - return (MUTEX_TRY_LOCK(m_sMutexHandle) != 0); + return (MUTEX_TRY_LOCK(m_sMutexHandle) == 0); } inline void basicMutex::unlock(void) diff --git a/lib/data/mysql/mysql_class.cpp b/lib/data/mysql/mysql_class.cpp index af776802..a8183af6 100644 --- a/lib/data/mysql/mysql_class.cpp +++ b/lib/data/mysql/mysql_class.cpp @@ -281,6 +281,7 @@ AAssoc * MySQL_Connector::Query(CSTR QS, bool useCache) } else { Result = mysql_store_result( m_pDBLink ); };*/ + int tRetries = 0; while (mysql_query(m_pDBLink, QS)) { LOG_ERROR(mysql_error(m_pDBLink)); @@ -293,8 +294,14 @@ AAssoc * MySQL_Connector::Query(CSTR QS, bool useCache) case 2013: case 2014: { - ReConnect(); - continue; + // Bounded: with the server down this looped forever while holding the access mutex, + // blocking every thread that uses the database + if (tRetries++ < MYSQL_MAX_RECONNECT_ATTEMPTS) + { + ReConnect(); + continue; + } + break; }; }; break; @@ -383,6 +390,31 @@ CSTR MySQL_Connector::escapeBinary(uint8_t * Data, uint32_t Size) return temp; } +/* + Non-blocking query without logging, for the database log service: it runs inside the log broadcast + (log mutex held) and must not wait for the access mutex - a thread that holds the access mutex and + logs an error waits for the log mutex (deadlock), and on the same thread the non-recursive access + mutex would deadlock by itself. Returns false when the connection is busy. +*/ +bool MySQL_Connector::TrySilentQuery(CSTR QS) +{ + if (! m_mAccessMutex.try_lock()) + { + return false; + } + bool RetVal = (mysql_query(m_pDBLink, QS) == 0); + if (RetVal) + { + MYSQL_RES * tRes = mysql_store_result(m_pDBLink); // INSERT: normally none + if (tRes) + { + mysql_free_result(tRes); + } + } + m_mAccessMutex.unlock(); + return RetVal; +} + uint64_t MySQL_Connector::QueryID(CSTR QS) { uint64_t RetVal = 0; @@ -392,6 +424,7 @@ uint64_t MySQL_Connector::QueryID(CSTR QS) #ifdef DEBUG_MYSQL_QUERIES LOG(QS); #endif + int tRetries = 0; while (mysql_query(m_pDBLink, QS)) { LOG_ERROR(mysql_error(m_pDBLink)); @@ -404,8 +437,14 @@ uint64_t MySQL_Connector::QueryID(CSTR QS) case 2013: case 2014: { - ReConnect(); - continue; + // Bounded: with the server down this looped forever while holding the access mutex, + // blocking every thread that uses the database + if (tRetries++ < MYSQL_MAX_RECONNECT_ATTEMPTS) + { + ReConnect(); + continue; + } + break; }; }; break; @@ -423,6 +462,7 @@ void MySQL_Connector::SilentQuery(CSTR QS) #ifdef DEBUG_MYSQL_QUERIES LOG(QS); #endif + int tRetries = 0; while (mysql_query(m_pDBLink, QS)) { LOG_ERROR(mysql_error(m_pDBLink)); @@ -435,8 +475,14 @@ void MySQL_Connector::SilentQuery(CSTR QS) case 2013: case 2014: { - ReConnect(); - continue; + // Bounded: with the server down this looped forever while holding the access mutex, + // blocking every thread that uses the database + if (tRetries++ < MYSQL_MAX_RECONNECT_ATTEMPTS) + { + ReConnect(); + continue; + } + break; }; }; break; diff --git a/lib/data/mysql/mysql_class.h b/lib/data/mysql/mysql_class.h index d9b8c792..5adf3678 100644 --- a/lib/data/mysql/mysql_class.h +++ b/lib/data/mysql/mysql_class.h @@ -11,6 +11,9 @@ #define DEBUG_MYSQL_QUERIES #endif +// Reconnect attempts per query when the server went away (before: unlimited, holding the access mutex) +#define MYSQL_MAX_RECONNECT_ATTEMPTS 3 + class MySQL_Connector { private: @@ -47,6 +50,7 @@ class MySQL_Connector uint64_t QueryID(CSTR QS); void SilentQuery(CSTR QS); + bool TrySilentQuery(CSTR QS); // never blocks, never logs (for the DB log service) AAssoc * Query(CSTR QS, bool useCache = false); }; diff --git a/lib/data/net/netServer.cpp b/lib/data/net/netServer.cpp index edb0bd48..77cc91f7 100644 --- a/lib/data/net/netServer.cpp +++ b/lib/data/net/netServer.cpp @@ -23,6 +23,8 @@ networkServer::networkServer(config_setting_t * Settings, networkServiceEngine * { m_pLog = basicLogCollection::getInstance(); m_bConnectionType = 0; + m_pHostName = NULL; // always owned (malloc/strdup) once set + m_nPortNumber = 0; m_vHandlersPool.clear(); MainSocketAddress = NULL; m_pKernelEngine = ptr; @@ -108,7 +110,8 @@ bool networkServer::BootUp(void) free(m_pHostName); m_pHostName = NULL; LOG_ERROR("Ethernet IP address Not Detected! Using Settings"); - if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, (const char **) &m_pHostName)) + const char * tCfgHost = NULL; + if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, &tCfgHost)) { m_pHostName = (CSTR) malloc(CTEXT); sprintf(m_pHostName, "localhost"); @@ -119,6 +122,7 @@ bool networkServer::BootUp(void) } else { + m_pHostName = strdup(tCfgHost); // libconfig owns tCfgHost: ~networkServer frees m_pHostName sprintf(tBuffer, "Host Address Read From Settings: %s", m_pHostName); LOG(tBuffer); }; @@ -126,7 +130,8 @@ bool networkServer::BootUp(void) freeifaddrs(ifaddr); }; #else - if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, (const char **) &m_pHostName)) + const char * tCfgHost = NULL; + if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, &tCfgHost)) { m_pHostName = (CSTR) malloc(CTEXT); sprintf(m_pHostName, "localhost"); @@ -137,6 +142,7 @@ bool networkServer::BootUp(void) } else { + m_pHostName = strdup(tCfgHost); // libconfig owns tCfgHost: ~networkServer frees m_pHostName sprintf(tBuffer, "Host Address Read From Settings: %s", m_pHostName); LOG(tBuffer); }; @@ -328,6 +334,15 @@ bool networkServer::BootUp(U16 Port) int RetCode; size_t S_NAMLEN = CTEXT; + if (m_pHostName == NULL) + { + m_pHostName = (CSTR) malloc(CTEXT); + if (m_pHostName == NULL) + { + return false; + } + m_pHostName[0] = (char) 0; + } RetCode = gethostname(m_pHostName, S_NAMLEN); if ( RetCode < 0 ) { LOG_ERROR("Can't Get Hostname!"); @@ -455,61 +470,36 @@ void networkServer::m_fThreadProc(void) { case EAGAIN: { - // Checkup client disconnection - if (m_vHandlersPool.size()) - { - for (vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end();) - { - // LRF_ClientHandler *tClient = (LRF_ClientHandler *)(*index); - if ((*index)->getStatus() == false) - { - // Remove Client Handler -#ifdef DEBUG_EXTRA - LOG("Remove Client"); -#endif - if (m_pKernelEngine) - { - if (m_pKernelEngine->detachClient(*index)) - { -#ifdef DEBUG_EXTRA - LOG("Client Stoped"); -#endif - m_vHandlersPool.erase(index); -#ifdef DEBUG_EXTRA - LOG("Remove Client Done"); -#endif - continue; - } - else - { - LOG_ERROR("Client detach from Kernel Failure!"); - } - } - else - { - LOG_ERROR("No Kernel Attached!"); - } - }; - index++; - }; - }; + // No new connection: remove the clients that disconnected + cleanupClients(); SLEEP(10); continue; }; + // Transient: a full descriptor table (EMFILE/ENFILE) or memory shortage clears up once + // disconnected clients are removed, an aborted handshake / signal only affects that attempt. + // Before, every error ended the accept thread: the server stopped accepting for good. + case EMFILE : + case ENFILE : + case ENOBUFS : + case ENOMEM : + case ECONNABORTED: + case EINTR : + case EPROTO : + case EPERM : + { + char tB[96]; + snprintf(tB, sizeof(tB), "accept() failed temporarily (errno %d), retrying", errno); + LOG_ERROR(tB); + cleanupClients(); + SLEEP(100); + continue; + }; // case EWOULDBLOCK: me->Log(" The socket is marked non-blocking and no connections are present to be accepted."); break; case EBADF : LOG_ERROR("The descriptor is invalid."); break; - case ECONNABORTED: LOG_ERROR("A connection has been aborted."); break; - case EINTR : LOG_ERROR("The system call was interrupted by a signal that was caught before a valid connection arrived."); break; case EINVAL : LOG_ERROR("Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break; - case EMFILE : LOG_ERROR("The per-process limit of open file descriptors has been reached."); break; - case ENFILE : LOG_ERROR("The system limit on the total number of open files has been reached."); break; case ENOTSOCK : LOG_ERROR("The descriptor references a file, not a socket."); break; case EOPNOTSUPP : LOG_ERROR("The referenced socket is not of type SOCK_STREAM."); break; case EFAULT : LOG_ERROR("The addr argument is not in a writable part of the user address space."); break; - case ENOBUFS : - case ENOMEM : LOG_ERROR("Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory."); break; - case EPROTO : LOG_ERROR("Protocol error."); break; - case EPERM : LOG_ERROR("Firewall rules forbid connection."); break; case ENOSR: #ifdef __linux__ case ESOCKTNOSUPPORT: @@ -539,6 +529,16 @@ void networkServer::m_fThreadProc(void) flags |= O_NONBLOCK | O_NDELAY; // RetCode = ioctl( MainSocket, FIONBIO, (char *) &dontblock ); RetCode = fcntl(ClientSocket, F_SETFL, flags); + // Detect dead peers (module powered off, cable/VPN down): without keepalive a half-open + // connection is never reported and its handler (threads, 8 MB buffers, descriptor) stays forever. + if (m_bConnectionType == 1) + { + int tOn = 1, tIdle = NWS_KEEPALIVE_IDLE_S, tIntvl = NWS_KEEPALIVE_INTERVAL_S, tCnt = NWS_KEEPALIVE_PROBES; + setsockopt(ClientSocket, SOL_SOCKET, SO_KEEPALIVE, &tOn, sizeof(tOn)); + setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPIDLE, &tIdle, sizeof(tIdle)); + setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPINTVL, &tIntvl, sizeof(tIntvl)); + setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPCNT, &tCnt, sizeof(tCnt)); + } #ifdef DEBUG if (RetCode == 0) { @@ -592,6 +592,29 @@ void networkServer::m_fThreadProc(void) #endif } +// Removes the handlers whose connection is gone (called from the accept thread) +void networkServer::cleanupClients(void) +{ + for (vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index != m_vHandlersPool.end();) + { + if ((*index)->getStatus() == false) + { + if (m_pKernelEngine == NULL) + { + LOG_ERROR("No Kernel Attached!"); + return; + } + if (m_pKernelEngine->detachClient(*index)) + { + index = m_vHandlersPool.erase(index); // erase() invalidates the iterator: continue with the returned one + continue; + } + LOG_ERROR("Client detach from Kernel Failure!"); + }; + index++; + }; +} + bool networkServer::dispatchEvent(EVENT_CONTAINER * Evt) { if (Evt == NULL) diff --git a/lib/data/net/netServer.h b/lib/data/net/netServer.h index 442ae6f2..853bf503 100644 --- a/lib/data/net/netServer.h +++ b/lib/data/net/netServer.h @@ -18,6 +18,7 @@ #include #include #include + #include #include #include #include @@ -59,6 +60,11 @@ // typedef _Primitive_Ring<_Core_Channel> ChannelsRing; typedef std::vector vectorNetHandlers; +// TCP keepalive on accepted connections: a dead peer is detected after IDLE + INTERVAL * PROBES seconds +#define NWS_KEEPALIVE_IDLE_S 30 +#define NWS_KEEPALIVE_INTERVAL_S 10 +#define NWS_KEEPALIVE_PROBES 3 + #define INVALID_SOCKET -1 #define UNIX_PATH_MAX 108 @@ -86,6 +92,7 @@ class networkServer : public basicThread, public basicEventHandler #endif U8 m_bConnectionType; void m_fThreadProc(void); + void cleanupClients(void); public: diff --git a/lib/data/net/serverPort.cpp b/lib/data/net/serverPort.cpp index ad8097c7..3380d281 100644 --- a/lib/data/net/serverPort.cpp +++ b/lib/data/net/serverPort.cpp @@ -22,7 +22,28 @@ serverPort::serverPort(SOCKET AcceptedSocket) : serverPort::~serverPort() { - // Send Abort to controll socket that waits Input .... + // The accepted socket belongs to this port. It was only closed on a read/write error, so a client + // removed for any other reason (module disabled / not registered, dead connection) leaked its descriptor + // until accept() failed with EMFILE. +#ifdef __linux__ + if (m_nSocketFD > -1) + { + shutdown(m_nSocketFD, SHUT_RDWR); // wakes up the receiver thread blocked in select() + } + _close(); // stop both I/O threads before the descriptor goes away + if (m_nSocketFD > -1) + { + close(m_nSocketFD); + m_nSocketFD = -1; + } +#else + _close(); + if (m_nSocketFD != INVALID_SOCKET) + { + closesocket(m_nSocketFD); + m_nSocketFD = INVALID_SOCKET; + } +#endif } bool serverPort::create(void) @@ -147,9 +168,11 @@ int serverPort::recptBlock(unsigned char * Buffer, int * BufferLength) { RetVal = recv(m_nSocketFD, Buffer, MAXIMAL_SOCKET_IO_BUFFER_LENGTH, 0); // RetVal = read(m_nSocketFD, Buffer, MAXIMAL_SOCKET_PACKET_LENGTH); + // 0 = orderly close by the peer (errno is not set then and may hold an old EAGAIN); + // < 0 is an error unless the call would block / was interrupted if (RetVal < 1) { - if (errno != EAGAIN && errno != EINTR) + if (RetVal == 0 || (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { LOG_ERROR("Peer Closes Connection!"); shutdown(m_nSocketFD, 2); diff --git a/lib/data/transport/transportSocket.cpp b/lib/data/transport/transportSocket.cpp index 7990451b..b458d79e 100644 --- a/lib/data/transport/transportSocket.cpp +++ b/lib/data/transport/transportSocket.cpp @@ -66,19 +66,18 @@ bool transportSocket::create(void) bool transportSocket::_close(void) { setConnectionStatus(CS_DISCONNECTED); - // LOG("Sending Close Req!"); - if (m_iControlPipeFD[0] > -1) - { - // LOG("Sending Close Req[1]!"); - write(m_iControlPipeFD[0], "E", 1); - }; - waitThreadAEnd( true ); + // The sender thread (A) reads the control pipe's read end [0]: the stop byte goes into the + // write end [1] (it was written into [0], which fails, so A only stopped at its 5 s select timeout). + // The receiver thread (B) is stopped by the force flag (and wakes up when the socket is shut down). if (m_iControlPipeFD[1] > -1) { - // LOG("Sending Close Req[2]!"); - write(m_iControlPipeFD[1], "E", 1); + if (write(m_iControlPipeFD[1], "E", 1) < 0) + { + // pipe full or broken: the force flag below still stops the thread + } }; - waitThreadBEnd( true ); + waitThreadAEnd(true); + waitThreadBEnd(true); //if ( m_bInitComplete ) //{ // LOG("Uninit"); @@ -86,15 +85,17 @@ bool transportSocket::_close(void) // LOG("Uninit Done!"); //} // LOG("Closeing FIDs!"); + // Mark closed: _close() runs again from ~transportSocket after a derived class closed the transport, + // and the old numbers may already belong to another connection's socket or pipe. if (m_iControlPipeFD[0] > -1) { - // LOG("Closeing FIDs[1]!"); close(m_iControlPipeFD[0]); + m_iControlPipeFD[0] = -1; }; if (m_iControlPipeFD[1] > -1) { - // LOG("Closeing FIDs[2]!"); close(m_iControlPipeFD[1]); + m_iControlPipeFD[1] = -1; }; return true; } -- 2.39.5