You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
3.3 KiB

7 years ago
​
​
​
7 years ago
7 years ago
​
​
​
7 years ago
7 years ago
​
​
​
​
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
17 hours ago
7 years ago
​
​
​
​
​
7 years ago
​
​
​
​
​
​
7 years ago
7 years ago
​
7 years ago
​
​
7 years ago
2 years ago
2 years ago
​
​
​
7 years ago
7 years ago
​
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
17 hours ago
​
​
​
​
2 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
7 years ago
7 years ago
​
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
17 hours ago
7 years ago
​
​
​
​
​
7 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
  1. #ifndef _SERVER_CORE_SERVER_MODULE_
  2. #define _SERVER_CORE_SERVER_MODULE_
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #ifndef __linux__
  6. // #include <WinSock2.h>
  7. #define WIN32_LEAN_AND_MEAN
  8. #include <windows.h>
  9. #include <winsock2.h>
  10. #include <ws2tcpip.h>
  11. #else
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <fcntl.h> /* low-level i/o */
  15. #include <linux/types.h>
  16. #include <netdb.h>
  17. #include <netinet/in.h>
  18. #include <netinet/ip.h>
  19. #include <netinet/tcp.h>
  20. #include <sys/ioctl.h>
  21. #include <sys/mman.h>
  22. #include <sys/socket.h>
  23. #include <sys/stat.h>
  24. #include <sys/time.h>
  25. #include <sys/types.h>
  26. #include <sys/un.h>
  27. #include <unistd.h>
  28. #endif
  29. #include "../../components/base/basicLogCollection.h"
  30. #include "../../components/base/basicSettingsProvider.h"
  31. #include "../../components/base/basicThread.h"
  32. #include "../../components/base/basicTypes.h"
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <vector>
  37. // #include "../../components/base/basicEngine.h"
  38. #include "../../components/base/basicEventHeap.h"
  39. #include "../protocol/protocol.h"
  40. #include "netClientHandler.h"
  41. #include "netServiceEngine.h"
  42. #ifndef _SERVER_APPLICATION_
  43. #define AUTOMATIC_IP_DETECTION
  44. #endif
  45. // #define USE_SSL_ENCRIPTION
  46. #ifdef USE_SSL_ENCRIPTION
  47. #include "../../components/obect/objectCertStorage.h"
  48. #endif
  49. #define NWS_SETTINGS_HOST "NW_HOSTNAME_IP"
  50. #define NWS_SETTINGS_PORT "NW_LISTEN_PORT"
  51. // typedef _Primitive_Ring<_Core_Channel> ChannelsRing;
  52. typedef std::vector<networkClientHandler *> vectorNetHandlers;
  53. // TCP keepalive on accepted connections: a dead peer is detected after IDLE + INTERVAL * PROBES seconds
  54. #define NWS_KEEPALIVE_IDLE_S 30
  55. #define NWS_KEEPALIVE_INTERVAL_S 10
  56. #define NWS_KEEPALIVE_PROBES 3
  57. #define INVALID_SOCKET -1
  58. #define UNIX_PATH_MAX 108
  59. void signal_void_handler(int SIG);
  60. class networkServer : public basicThread, public basicEventHandler
  61. {
  62. private:
  63. vectorNetHandlers m_vHandlersPool;
  64. networkServiceEngine * m_pKernelEngine;
  65. config_setting_t * m_pSettings;
  66. protected:
  67. basicLogCollection * m_pLog;
  68. struct sockaddr * MainSocketAddress;
  69. CSTR m_pHostName;
  70. uint16_t m_nPortNumber;
  71. #ifdef __linux__
  72. int MainSocket;
  73. #else
  74. SOCKET MainSocket;
  75. #endif
  76. U8 m_bConnectionType;
  77. void m_fThreadProc(void);
  78. void cleanupClients(void);
  79. public:
  80. explicit networkServer(config_setting_t * Settings = NULL, networkServiceEngine * ptr = NULL);
  81. virtual ~networkServer();
  82. bool BootUp(void); // Config By Settings provided in constructor, on fail uses next BootUp
  83. #ifdef USE_SSL_ENCRIPTION
  84. bool BootUp(U16 Port, bool useSSL = false); // Uses Default Hostname and Port as parameter, on fail (getlocalhost) uses next Bootup
  85. bool BootUp(CSTR HOST_NAME, U16 Port, bool useSSL = false); // Uses parameters
  86. #else
  87. bool BootUp(U16 Port); // Uses Default Hostname and Port as parameter, on fail (getlocalhost) uses next Bootup
  88. bool BootUp(CSTR HOST_NAME, U16 Port); // Uses parameters
  89. #endif
  90. #ifdef __linux__
  91. bool BootUp(CSTR UNIX_SOCKET_NAME);
  92. #endif
  93. bool attachEngine(networkServiceEngine * ptr);
  94. virtual bool dispatchEvent(EVENT_CONTAINER * Evt);
  95. CSTR getAddress(void)
  96. { /* if( m_pHostName ) return strdup( m_pHostName ); */
  97. return NULL;
  98. }
  99. CSTR getHostname(void)
  100. {
  101. if (m_pHostName)
  102. {
  103. return strdup(m_pHostName);
  104. }
  105. }
  106. uint16_t getPort(void)
  107. {
  108. return m_nPortNumber;
  109. }
  110. };
  111. #endif