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.

628 lines
17 KiB

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
6 hours ago
​
7 years ago
​
​
​
7 years ago
​
​
​
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
6 hours 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
6 hours 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
6 hours 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
6 hours ago
​
​
​
7 years ago
​
7 years ago
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
7 years ago
7 years ago
7 years ago
​
​
7 years ago
​
​
​
7 years ago
​
3 years ago
​
​
​
​
3 years 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
7 years ago
​
​
7 years ago
​
​
​
​
7 years ago
​
​
7 years ago
7 years ago
7 years ago
​
7 years ago
​
7 years ago
​
7 years ago
​
​
7 years ago
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
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
6 hours ago
​
​
​
​
​
​
​
​
​
​
​
7 years ago
7 years ago
​
7 years ago
​
​
7 years ago
​
7 years ago
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
7 years ago
​
​
​
​
​
7 years ago
7 years ago
​
​
​
​
​
​
​
7 years ago
​
​
​
​
7 years 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
​
​
​
​
​
​
​
​
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
6 hours 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
6 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
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
6 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
2 years ago
2 years ago
​
2 years ago
2 years ago
​
​
​
​
2 years ago
2 years ago
​
​
​
​
​
2 years ago
2 years ago
​
​
7 years ago
​
2 years ago
2 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
6 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
  1. #include "netServer.h"
  2. // #include "../../App/3dSERVER/LRF_ClientHandler.h"
  3. #include "netClientHandler.h"
  4. #define LOG(X) m_pLog->Log("NS", this, X)
  5. #ifdef DEBUG
  6. #define LOG_ERROR(X) \
  7. { \
  8. char _tBfrErrMSG234[256]; \
  9. sprintf(_tBfrErrMSG234, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  10. m_pLog->Log("NS", this, _LOG_ERROR, _tBfrErrMSG234); \
  11. }
  12. #else
  13. #define LOG_ERROR(X) m_pLog->Log("NS", this, _LOG_ERROR, X);
  14. #endif
  15. void signal_void_handler(int SIG) {
  16. if ( SIG ) SIG = 121; // dummy to prevent Warnings
  17. }
  18. networkServer::networkServer(config_setting_t * Settings, networkServiceEngine * ptr) :
  19. basicThread()
  20. {
  21. m_pLog = basicLogCollection::getInstance();
  22. m_bConnectionType = 0;
  23. m_pHostName = NULL; // always owned (malloc/strdup) once set
  24. m_nPortNumber = 0;
  25. m_vHandlersPool.clear();
  26. MainSocketAddress = NULL;
  27. m_pKernelEngine = ptr;
  28. MainSocket = INVALID_SOCKET;
  29. if (Settings != NULL)
  30. {
  31. m_pSettings = Settings;
  32. }
  33. else
  34. {
  35. m_pSettings = basicSettingsProvider::getInstance()->getSubNode(NULL, "NETWORK_SERVER");
  36. };
  37. }
  38. networkServer::~networkServer()
  39. {
  40. m_bThreadStatus = TH_ENDED;
  41. if (m_pHostName != NULL)
  42. {
  43. free(m_pHostName);
  44. }
  45. }
  46. bool networkServer::BootUp(void)
  47. {
  48. config_setting_t * pSetting;
  49. int tVal;
  50. char tBuffer[CTEXT];
  51. m_pHostName = NULL;
  52. if (m_pSettings != NULL)
  53. {
  54. LOG("NetServer Getting Settings ...");
  55. #ifdef AUTOMATIC_IP_DETECTION
  56. struct ifaddrs * ifaddr = NULL;
  57. struct ifaddrs * ifa;
  58. m_pHostName = (CSTR) malloc(CTEXT);
  59. if (-1 == getifaddrs(&ifaddr))
  60. {
  61. LOG_ERROR("Cannot get Net Integfaces!");
  62. return false;
  63. }
  64. else
  65. {
  66. bool regs = false;
  67. char ip[16];
  68. struct sockaddr_in * inn;
  69. unsigned char A, B, C, D;
  70. #ifdef DEBUG
  71. LOG("Gotta check some IFs");
  72. #endif
  73. for (ifa = ifaddr; ifa; ifa = ifa->ifa_next)
  74. {
  75. if (ifa->ifa_addr == NULL)
  76. {
  77. // Can Bus
  78. LOG("IFA->ifa_addr is NULL");
  79. continue;
  80. };
  81. if (ifa->ifa_addr->sa_family != AF_INET)
  82. {
  83. continue;
  84. }
  85. inn = (struct sockaddr_in *) ifa->ifa_addr;
  86. D = (inn->sin_addr.s_addr >> 24) & 0xFF;
  87. C = (inn->sin_addr.s_addr >> 16) & 0xFF;
  88. B = (inn->sin_addr.s_addr >> 8) & 0xFF;
  89. A = (inn->sin_addr.s_addr >> 0) & 0xFF;
  90. sprintf(ip, "%d.%d.%d.%d", A, B, C, D);
  91. sprintf(tBuffer, "Network Interface: %s [%s]", ifa->ifa_name, ip);
  92. if (strncmp(ifa->ifa_name, "eth", 3) == 0 || strncmp(ifa->ifa_name, "enp", 3) == 0)
  93. {
  94. regs = true;
  95. sprintf(m_pHostName, ip);
  96. };
  97. LOG(tBuffer);
  98. };
  99. if (! regs)
  100. {
  101. free(m_pHostName);
  102. m_pHostName = NULL;
  103. LOG_ERROR("Ethernet IP address Not Detected! Using Settings");
  104. const char * tCfgHost = NULL;
  105. if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, &tCfgHost))
  106. {
  107. m_pHostName = (CSTR) malloc(CTEXT);
  108. sprintf(m_pHostName, "localhost");
  109. pSetting = config_setting_add(m_pSettings, NWS_SETTINGS_HOST, CONFIG_TYPE_STRING);
  110. config_setting_set_string(pSetting, m_pHostName);
  111. basicSettingsProvider::getInstance()->compromise();
  112. LOG("No Host defined");
  113. }
  114. else
  115. {
  116. m_pHostName = strdup(tCfgHost); // libconfig owns tCfgHost: ~networkServer frees m_pHostName
  117. sprintf(tBuffer, "Host Address Read From Settings: %s", m_pHostName);
  118. LOG(tBuffer);
  119. };
  120. };
  121. freeifaddrs(ifaddr);
  122. };
  123. #else
  124. const char * tCfgHost = NULL;
  125. if (! config_setting_lookup_string(m_pSettings, NWS_SETTINGS_HOST, &tCfgHost))
  126. {
  127. m_pHostName = (CSTR) malloc(CTEXT);
  128. sprintf(m_pHostName, "localhost");
  129. pSetting = config_setting_add(m_pSettings, NWS_SETTINGS_HOST, CONFIG_TYPE_STRING);
  130. config_setting_set_string(pSetting, m_pHostName);
  131. basicSettingsProvider::getInstance()->compromise();
  132. LOG("No Host defined");
  133. }
  134. else
  135. {
  136. m_pHostName = strdup(tCfgHost); // libconfig owns tCfgHost: ~networkServer frees m_pHostName
  137. sprintf(tBuffer, "Host Address Read From Settings: %s", m_pHostName);
  138. LOG(tBuffer);
  139. };
  140. #endif
  141. if (! config_setting_lookup_int(m_pSettings, NWS_SETTINGS_PORT, &tVal))
  142. {
  143. m_nPortNumber = 2222;
  144. pSetting = config_setting_add(m_pSettings, NWS_SETTINGS_PORT, CONFIG_TYPE_INT);
  145. config_setting_set_int(pSetting, m_nPortNumber);
  146. basicSettingsProvider::getInstance()->compromise();
  147. LOG("No Port defined");
  148. }
  149. else
  150. {
  151. m_nPortNumber = tVal;
  152. sprintf(tBuffer, "Port Read From Settings: %d", m_nPortNumber);
  153. LOG(tBuffer);
  154. };
  155. sprintf(tBuffer, "Final Network Config is: %s:%d", m_pHostName, m_nPortNumber);
  156. LOG(tBuffer);
  157. if (basicSettingsProvider::getInstance()->isCompromised())
  158. {
  159. basicSettingsProvider::getInstance()->validate();
  160. }
  161. return BootUp(m_pHostName, m_nPortNumber);
  162. }
  163. else
  164. {
  165. // Last try to bootup by detecting host and default port 2222
  166. return BootUp(2222);
  167. };
  168. }
  169. bool networkServer::BootUp(CSTR HOST_NAME, U16 PORT)
  170. {
  171. #ifdef __linux__
  172. int RetCode;
  173. struct hostent * h_info;
  174. #ifdef DEBUG
  175. LOG("BootUp");
  176. #endif
  177. MainSocket = socket(AF_INET, SOCK_STREAM, 0);
  178. if (MainSocket == -1)
  179. {
  180. LOG_ERROR("Some throuble with networking on this machine (Socket Error)!");
  181. return false;
  182. };
  183. const int enable = 1;
  184. if (setsockopt(MainSocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
  185. {
  186. LOG_ERROR("setsockopt(SO_REUSEADDR) failed");
  187. };
  188. MainSocketAddress = NULL;
  189. MainSocketAddress = (struct sockaddr *) malloc(sizeof(struct sockaddr_in));
  190. if (MainSocketAddress == NULL)
  191. {
  192. LOG_ERROR("Some throuble with networking on this machine (Cannot Alloc Sockaddr Struct)!");
  193. return false;
  194. };
  195. bzero(MainSocketAddress, sizeof(struct sockaddr_in));
  196. h_info = gethostbyname(HOST_NAME);
  197. if (h_info == NULL)
  198. {
  199. LOG_ERROR("Some throuble with networking on this machine (Cannot Get Hostname)!");
  200. return false;
  201. };
  202. //*****************************************
  203. //* there we building our network address *
  204. //*****************************************
  205. bcopy(h_info->h_addr, &(((struct sockaddr_in *) MainSocketAddress)->sin_addr), h_info->h_length);
  206. ((struct sockaddr_in *) MainSocketAddress)->sin_family = h_info->h_addrtype;
  207. ((struct sockaddr_in *) MainSocketAddress)->sin_port = htons(PORT);
  208. RetCode = bind(MainSocket, MainSocketAddress, sizeof(struct sockaddr_in));
  209. if (RetCode != 0)
  210. {
  211. LOG_ERROR("Error Binding to Port/Address");
  212. return false;
  213. };
  214. RetCode = listen(MainSocket, 128);
  215. if (RetCode != 0)
  216. {
  217. LOG_ERROR("Cannot Listen Port/Address");
  218. return false;
  219. };
  220. int flags;
  221. flags = fcntl(MainSocket, F_GETFL, NULL);
  222. flags |= O_NONBLOCK | O_NDELAY;
  223. // RetCode = ioctl( MainSocket, FIONBIO, (char *) &dontblock );
  224. RetCode = fcntl(MainSocket, F_SETFL, flags);
  225. if (RetCode == 0)
  226. {
  227. LOG("Set N-Blocking Mode of Accepting Socket");
  228. }
  229. else
  230. {
  231. LOG("Can't set N-Blocking Mode of Accepting Socket");
  232. };
  233. #else
  234. char temp[CTEXT];
  235. WSADATA wsaData;
  236. int iResult;
  237. // Initialize Winsock
  238. iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  239. if (iResult != 0)
  240. {
  241. sprintf(temp, "WSAStartup failed with error: %d\n", iResult);
  242. LOG_ERROR(temp);
  243. return false;
  244. };
  245. MainSocket = INVALID_SOCKET;
  246. SOCKET ClientSocket = INVALID_SOCKET;
  247. struct addrinfo * result = NULL;
  248. struct addrinfo hints;
  249. int iSendResult;
  250. char recvbuf[512];
  251. int recvbuflen = 512;
  252. ZeroMemory(&hints, sizeof(hints));
  253. hints.ai_family = AF_INET;
  254. hints.ai_socktype = SOCK_STREAM;
  255. hints.ai_protocol = IPPROTO_TCP;
  256. hints.ai_flags = AI_PASSIVE;
  257. // Resolve the server address and port
  258. sprintf(temp, "%d", PORT);
  259. iResult = getaddrinfo(NULL, temp, &hints, &result);
  260. if (iResult != 0)
  261. {
  262. sprintf(temp, "getaddrinfo failed with error: %d\n", iResult);
  263. LOG_ERROR(temp);
  264. WSACleanup();
  265. return false;
  266. };
  267. // Create a SOCKET for connecting to server
  268. MainSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  269. if (MainSocket == INVALID_SOCKET)
  270. {
  271. sprintf(temp, "socket failed with error: %ld\n", WSAGetLastError());
  272. LOG_ERROR(temp);
  273. freeaddrinfo(result);
  274. WSACleanup();
  275. return false;
  276. };
  277. // Setup the TCP listening socket
  278. iResult = bind(MainSocket, result->ai_addr, (int) result->ai_addrlen);
  279. if (iResult == SOCKET_ERROR)
  280. {
  281. sprintf(temp, "bind failed with error: %d\n", WSAGetLastError());
  282. LOG_ERROR(temp);
  283. freeaddrinfo(result);
  284. closesocket(MainSocket);
  285. WSACleanup();
  286. return false;
  287. };
  288. freeaddrinfo(result);
  289. iResult = listen(MainSocket, SOMAXCONN);
  290. if (iResult == SOCKET_ERROR)
  291. {
  292. sprintf(temp, "listen failed with error: %d\n", WSAGetLastError());
  293. LOG_ERROR(temp);
  294. closesocket(MainSocket);
  295. WSACleanup();
  296. return false;
  297. };
  298. #endif
  299. m_bConnectionType = 1;
  300. return init();
  301. }
  302. bool networkServer::BootUp(U16 Port)
  303. {
  304. char temp[CTEXT];
  305. m_nPortNumber = Port;
  306. #ifdef __linux__
  307. int RetCode;
  308. size_t S_NAMLEN = CTEXT;
  309. if (m_pHostName == NULL)
  310. {
  311. m_pHostName = (CSTR) malloc(CTEXT);
  312. if (m_pHostName == NULL)
  313. {
  314. return false;
  315. }
  316. m_pHostName[0] = (char) 0;
  317. }
  318. RetCode = gethostname(m_pHostName, S_NAMLEN);
  319. if ( RetCode < 0 ) {
  320. LOG_ERROR("Can't Get Hostname!");
  321. };
  322. sprintf(temp, "Running on host: %s:%d", m_pHostName, m_nPortNumber);
  323. LOG(temp);
  324. #else
  325. sprintf(m_pHostName, "");
  326. #endif
  327. return BootUp(m_pHostName, m_nPortNumber);
  328. }
  329. bool networkServer::attachEngine(networkServiceEngine * ptr)
  330. {
  331. m_pKernelEngine = ptr;
  332. if (m_vHandlersPool.size())
  333. {
  334. // Pass Kernel to all already connected nodes
  335. for (vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++)
  336. {
  337. //((LRF_ClientHandler *)(*index))->attachEngine(m_pDetectorKernel);
  338. (*index)->attachEngine(m_pKernelEngine);
  339. };
  340. };
  341. return true;
  342. }
  343. #ifdef __linux__
  344. bool networkServer::BootUp(CSTR SOCKET_NAME)
  345. {
  346. //struct sockaddr_un MainPort;
  347. //size_t S_NAMLEN = CTEXT;
  348. int RetCode;
  349. char localhost[CTEXT];
  350. char temp[512];
  351. LOG("Core BootUp");
  352. MainSocket = socket(PF_UNIX, SOCK_STREAM, 0);
  353. if (MainSocket == -1)
  354. {
  355. LOG_ERROR("Some throuble with Kernel on this machine (UnixSocket Error)!");
  356. return false;
  357. };
  358. if (unlink(SOCKET_NAME) == -1)
  359. {
  360. LOG("Old Socket File was not deleted!");
  361. };
  362. localhost[0] = 0;
  363. // RetCode = gethostname( localhost, S_NAMLEN );
  364. sprintf(temp, "Running Unix Socket: %s::%s", localhost, SOCKET_NAME);
  365. LOG(temp);
  366. MainSocketAddress = (sockaddr *) malloc(sizeof(struct sockaddr_un));
  367. bzero(MainSocketAddress, sizeof(struct sockaddr_un));
  368. //*****************************************
  369. //* there we building our network address *
  370. //*****************************************
  371. ((struct sockaddr_un *) MainSocketAddress)->sun_family = AF_UNIX;
  372. snprintf(((struct sockaddr_un *) MainSocketAddress)->sun_path, UNIX_PATH_MAX, SOCKET_NAME);
  373. RetCode = bind(MainSocket, MainSocketAddress, sizeof(struct sockaddr_un));
  374. if (RetCode != 0)
  375. {
  376. LOG_ERROR("Error Binding to Port/Address");
  377. return false;
  378. };
  379. RetCode = listen(MainSocket, 128);
  380. if (RetCode != 0)
  381. {
  382. LOG_ERROR("Cannot Listen UNIX SOCKET");
  383. return false;
  384. };
  385. U8 dontblock;
  386. // Set Socket permitions 666
  387. fchmod(MainSocket, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
  388. dontblock = fcntl(MainSocket, F_GETFL, NULL);
  389. dontblock |= O_NONBLOCK | O_NDELAY;
  390. RetCode = ioctl(MainSocket, FIONBIO, (char *) &dontblock);
  391. if (RetCode == 0)
  392. {
  393. LOG("Set N-Blocking Mode of Master Socket");
  394. }
  395. else
  396. {
  397. LOG("Can't set N-Blocking Mode of Master Socket");
  398. };
  399. m_bConnectionType = 2;
  400. return init();
  401. }
  402. #endif
  403. void networkServer::m_fThreadProc(void)
  404. {
  405. struct sockaddr ClientAddress;
  406. socklen_t size;
  407. int RetCode;
  408. #ifdef __linux__
  409. int ClientSocket;
  410. if (m_bConnectionType == 1)
  411. {
  412. size = (socklen_t) sizeof(struct sockaddr_in);
  413. }
  414. else
  415. {
  416. size = (socklen_t) sizeof(struct sockaddr_un);
  417. };
  418. #else
  419. SOCKET ClientSocket;
  420. #endif
  421. #ifdef DEBUG
  422. LOG("Core Worker Thread Started");
  423. LOG("Ready to Accept Connections");
  424. #endif
  425. pthread_setname_np(pthread_self(), "networkServer");
  426. m_bThreadStatus = TH_WORKING;
  427. while (m_bThreadStatus < TH_ENDED)
  428. {
  429. ClientSocket = accept(MainSocket, &ClientAddress, &size);
  430. if (ClientSocket < 0)
  431. {
  432. switch (errno)
  433. {
  434. case EAGAIN:
  435. {
  436. // No new connection: remove the clients that disconnected
  437. cleanupClients();
  438. SLEEP(10);
  439. continue;
  440. };
  441. // Transient: a full descriptor table (EMFILE/ENFILE) or memory shortage clears up once
  442. // disconnected clients are removed, an aborted handshake / signal only affects that attempt.
  443. // Before, every error ended the accept thread: the server stopped accepting for good.
  444. case EMFILE :
  445. case ENFILE :
  446. case ENOBUFS :
  447. case ENOMEM :
  448. case ECONNABORTED:
  449. case EINTR :
  450. case EPROTO :
  451. case EPERM :
  452. {
  453. char tB[96];
  454. snprintf(tB, sizeof(tB), "accept() failed temporarily (errno %d), retrying", errno);
  455. LOG_ERROR(tB);
  456. cleanupClients();
  457. SLEEP(100);
  458. continue;
  459. };
  460. // case EWOULDBLOCK: me->Log(" The socket is marked non-blocking and no connections are present to be accepted."); break;
  461. case EBADF : LOG_ERROR("The descriptor is invalid."); break;
  462. case EINVAL : LOG_ERROR("Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break;
  463. case ENOTSOCK : LOG_ERROR("The descriptor references a file, not a socket."); break;
  464. case EOPNOTSUPP : LOG_ERROR("The referenced socket is not of type SOCK_STREAM."); break;
  465. case EFAULT : LOG_ERROR("The addr argument is not in a writable part of the user address space."); break;
  466. case ENOSR:
  467. #ifdef __linux__
  468. case ESOCKTNOSUPPORT:
  469. #endif
  470. case EPROTONOSUPPORT:
  471. case ETIMEDOUT : LOG_ERROR(" Unusual error in Kernel (Timeout, No Socket Support in Kernel, Unsupported Protocol)"); break;
  472. // case ERESTARTSYS: me->Log(" Unusual error by Kernel"); break;
  473. default: LOG_ERROR(" Unhandled error in Kernel"); break;
  474. };
  475. m_bThreadStatus = TH_ENDED;
  476. }
  477. else
  478. {
  479. /*
  480. if( m_bConnectionType == 1 ){
  481. char tstr[CQUERY];
  482. #ifdef __linux__
  483. inet_ntop( AF_INET, &(((struct sockaddr_in*) &(ClientAddress ))->sin_addr ), tstr, CQUERY );//size );
  484. #else
  485. strcpy( tstr, inet_ntoa( ((struct sockaddr_in*)&ClientAddress)->sin_addr ) );
  486. //InetNtop(AF_INET, &(((struct sockaddr_in*) &(ClientAddress ))->sin_addr ), tstr, size );
  487. #endif
  488. };
  489. */
  490. int flags;
  491. flags = fcntl(ClientSocket, F_GETFL, NULL);
  492. flags |= O_NONBLOCK | O_NDELAY;
  493. // RetCode = ioctl( MainSocket, FIONBIO, (char *) &dontblock );
  494. RetCode = fcntl(ClientSocket, F_SETFL, flags);
  495. // Detect dead peers (module powered off, cable/VPN down): without keepalive a half-open
  496. // connection is never reported and its handler (threads, 8 MB buffers, descriptor) stays forever.
  497. if (m_bConnectionType == 1)
  498. {
  499. int tOn = 1, tIdle = NWS_KEEPALIVE_IDLE_S, tIntvl = NWS_KEEPALIVE_INTERVAL_S, tCnt = NWS_KEEPALIVE_PROBES;
  500. setsockopt(ClientSocket, SOL_SOCKET, SO_KEEPALIVE, &tOn, sizeof(tOn));
  501. setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPIDLE, &tIdle, sizeof(tIdle));
  502. setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPINTVL, &tIntvl, sizeof(tIntvl));
  503. setsockopt(ClientSocket, IPPROTO_TCP, TCP_KEEPCNT, &tCnt, sizeof(tCnt));
  504. }
  505. #ifdef DEBUG
  506. if (RetCode == 0)
  507. {
  508. LOG("Set N-Blocking Mode of Client Socket");
  509. }
  510. else
  511. {
  512. LOG("Can't set N-Blocking Mode of Client Socket");
  513. };
  514. LOG("Client Connection Accepted");
  515. #endif
  516. if (m_pKernelEngine)
  517. {
  518. networkClientHandler * tHandle;
  519. #ifdef DEBUG
  520. LOG("Before New Handler");
  521. #endif
  522. tHandle = m_pKernelEngine->attachNewClient(ClientSocket, &ClientAddress);
  523. #ifdef DEBUG
  524. LOG("After New Handler");
  525. #endif
  526. if (tHandle != NULL)
  527. {
  528. #ifdef DEBUG_EXTRA
  529. LOG("Handle Not NULL");
  530. #endif
  531. // tHandle->attachEngine( m_pKernelEngine );
  532. m_vHandlersPool.push_back(tHandle);
  533. }
  534. else
  535. {
  536. #ifdef DEBUG
  537. LOG_ERROR("No Client Handler Created!");
  538. #endif
  539. shutdown(ClientSocket, 2);
  540. close(ClientSocket);
  541. };
  542. }
  543. else
  544. {
  545. #ifdef DEBUG
  546. LOG_ERROR("No Kernel Attached!");
  547. #endif
  548. shutdown(ClientSocket, 2);
  549. close(ClientSocket);
  550. };
  551. };
  552. };
  553. #ifdef DEBUG
  554. LOG("Core Worker Thread Ended");
  555. #endif
  556. }
  557. // Removes the handlers whose connection is gone (called from the accept thread)
  558. void networkServer::cleanupClients(void)
  559. {
  560. for (vectorNetHandlers::iterator index = m_vHandlersPool.begin(); index != m_vHandlersPool.end();)
  561. {
  562. if ((*index)->getStatus() == false)
  563. {
  564. if (m_pKernelEngine == NULL)
  565. {
  566. LOG_ERROR("No Kernel Attached!");
  567. return;
  568. }
  569. if (m_pKernelEngine->detachClient(*index))
  570. {
  571. index = m_vHandlersPool.erase(index); // erase() invalidates the iterator: continue with the returned one
  572. continue;
  573. }
  574. LOG_ERROR("Client detach from Kernel Failure!");
  575. };
  576. index++;
  577. };
  578. }
  579. bool networkServer::dispatchEvent(EVENT_CONTAINER * Evt)
  580. {
  581. if (Evt == NULL)
  582. {
  583. return false;
  584. }
  585. return true;
  586. }
  587. #undef LOG
  588. #undef LOG_ERROR