From df528b0fd2f746dba222d9ca00dab2700b2bb00a Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 22 Oct 2026 13:34:34 -0700 Subject: [PATCH] fix(runtime): [1.2.x] backport worker stacks SNMP locking and input boundaries (#662) Backport the applicable runtime bugs from develop #644, #646 and #660. Raise small platform worker stacks while preserving larger defaults and rejecting overflowing buffer configurations. Serialize SNMP session construction, cleanup and every SNMPv3 request process-wide while v1 and v2c requests stay parallel. Net-SNMP's README.thread says SNMPv3 support was never checked for multi-threading correctness. One unresponsive v3 agent now delays other v3 polls by up to timeout x (retries + 1); narrowing the lock needs the asynchronous API and is a develop-only follow-up. Reject unavailable PHP reader slots and invalid host/thread CLI numbers before indexing or sizing state. Consume overlong config lines once, parse final lines without a newline, and keep config values out of warnings. Merge after #661. This keeps the flat maintenance sources and existing runtime interfaces; no new dependencies or CI gates. Release notes will be collected in the final maintenance PR. Validation: native build and version smoke test pass through mise. ASan/UBSan contracts exercise worker-stack defaults and errors, active-session SNMP locking, and physical config-line boundaries. A probe linked to the maintenance production objects passes five script-output boundaries and three unavailable PHP slot cases. Seven invalid numeric CLI invocations fail before config/database access. The critical flawfinder gate passes. No live database or device was contacted. --------- Signed-off-by: Thomas Vincent --- php.c | 23 ++++++++++++++++ snmp.c | 81 +++++++++++++++++++++++++++++++++++++++++++------------ spine.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++------- util.c | 40 ++++++++++++++++++++++----- 4 files changed, 195 insertions(+), 33 deletions(-) diff --git a/php.c b/php.c index a28ff981..6f689c33 100644 --- a/php.c +++ b/php.c @@ -131,6 +131,20 @@ static void php_set_state(int php_process, int state) { thread_mutex_unlock(LOCK_PHP); } +/* Returns an undefined ("U") result for a slot that cannot be addressed, or + * NULL when php_process names a usable script server slot. */ +static char *php_unavailable_slot(int php_process) { + char *unavailable; + + if (php_processes != NULL && set.php_servers >= 0 && set.php_servers <= MAX_PHP_SERVERS && + php_process >= 0 && php_process < set.php_servers) { + return NULL; + } + + STRDUP_OR_DIE(unavailable, "U", "PHP unavailable slot"); + return unavailable; +} + /*! \fn char *php_cmd(const char *php_command, int php_process) * \brief calls the script server and executes a script command * \param php_command the formatted php script server command @@ -151,6 +165,11 @@ char *php_cmd(const char *php_command, int php_process) { int write_fd; int retries = 0; + + if ((result_string = php_unavailable_slot(php_process)) != NULL) { + return result_string; + } + assert(php_command != 0); /* pad command with CR-LF */ @@ -308,6 +327,10 @@ static char *php_readpipe_until(int php_process, char *command, double deadline) char *cp; char *bptr; + if ((result_string = php_unavailable_slot(php_process)) != NULL) { + return result_string; + } + if (!(result_string = (char *)malloc(RESULTS_BUFFER))) { die("ERROR: Fatal malloc error: php.c php_readpipe!"); } diff --git a/snmp.c b/snmp.c index 69767fa2..1272d124 100644 --- a/snmp.c +++ b/snmp.c @@ -104,17 +104,8 @@ void snmp_spine_close(void) { snmp_shutdown("spine"); } -/*! \fn void *snmp_host_init(int host_id, char *hostname, int snmp_version, - * char *snmp_community, char *snmp_username, char *snmp_password, - * char *snmp_auth_protocol, char *snmp_priv_passphrase, char *snmp_priv_protocol, - * char *snmp_context, char *snmp_engine_id, int snmp_port, int snmp_timeout) - * \brief initializes an snmp_session object for a Spine host - * - * This function will initialize NET-SNMP for the Spine host - * in question. - * - */ -void *snmp_host_init(int host_id, char *hostname, int snmp_version, char *snmp_community, +/* Session construction body; the caller holds LOCK_SNMP. */ +static void *snmp_host_init_unlocked(int host_id, char *hostname, int snmp_version, char *snmp_community, char *snmp_username, char *snmp_password, char *snmp_auth_protocol, char *snmp_priv_passphrase, char *snmp_priv_protocol, char *snmp_context, char *snmp_engine_id, int snmp_port, int snmp_timeout) { @@ -344,9 +335,7 @@ void *snmp_host_init(int host_id, char *hostname, int snmp_version, char *snmp_c } /* open SNMP Session */ - thread_mutex_lock(LOCK_SNMP); sessp = snmp_sess_open(&session); - thread_mutex_unlock(LOCK_SNMP); if (!sessp) { if (is_debug_device(host_id)) { @@ -359,6 +348,62 @@ void *snmp_host_init(int host_id, char *hostname, int snmp_version, char *snmp_c return sessp; } + +/*! \fn void *snmp_host_init(int host_id, char *hostname, int snmp_version, + * char *snmp_community, char *snmp_username, char *snmp_password, + * char *snmp_auth_protocol, char *snmp_priv_passphrase, char *snmp_priv_protocol, + * char *snmp_context, char *snmp_engine_id, int snmp_port, int snmp_timeout) + * \brief initializes an snmp_session object for a Spine host + * + * This function will initialize NET-SNMP for the Spine host + * in question. + * + */ +/* Serialize v3 session construction and requests, keeping v1/v2c requests + * parallel. Net-SNMP's README.thread says "SNMPv3 support was never checked + * for multi-threading correctness", so spine takes the conservative course of + * allowing only one v3 transaction in the library at a time. + * + * The lock is held for the whole blocking v3 request, so an unresponsive agent + * delays other v3 polls and session opens by up to timeout * (retries + 1). + * Bounding the wait needs the asynchronous interface, which is a develop-branch + * change rather than a maintenance fix. */ +void *snmp_host_init(int host_id, char *hostname, int snmp_version, char *snmp_community, + char *snmp_username, char *snmp_password, char *snmp_auth_protocol, + char *snmp_priv_passphrase, char *snmp_priv_protocol, + char *snmp_context, char *snmp_engine_id, int snmp_port, int snmp_timeout) { + void *session; + int cancellation_state; + + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancellation_state); + thread_mutex_lock(LOCK_SNMP); + session = snmp_host_init_unlocked(host_id, hostname, snmp_version, snmp_community, + snmp_username, snmp_password, snmp_auth_protocol, snmp_priv_passphrase, + snmp_priv_protocol, snmp_context, snmp_engine_id, snmp_port, snmp_timeout); + thread_mutex_unlock(LOCK_SNMP); + pthread_setcancelstate(cancellation_state, NULL); + return session; +} + +static int snmp_synchronized_response(const host_t *host, struct snmp_pdu *request, + struct snmp_pdu **response) { + int status; + int cancellation_state; + const struct snmp_session *session = snmp_sess_session(host->snmp_session); + bool serialized = session == NULL || session->version == SNMP_VERSION_3; + + if (serialized) { + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancellation_state); + thread_mutex_lock(LOCK_SNMP); + } + status = snmp_sess_synch_response(host->snmp_session, request, response); + if (serialized) { + thread_mutex_unlock(LOCK_SNMP); + pthread_setcancelstate(cancellation_state, NULL); + } + return status; +} + /*! \fn void snmp_host_cleanup(void *snmp_session) * \brief closes an established snmp session * @@ -368,7 +413,9 @@ void *snmp_host_init(int host_id, char *hostname, int snmp_version, char *snmp_c */ void snmp_host_cleanup(void *snmp_session) { if (snmp_session != NULL) { + thread_mutex_lock(LOCK_SNMP); snmp_sess_close(snmp_session); + thread_mutex_unlock(LOCK_SNMP); } } @@ -429,7 +476,7 @@ char *snmp_get_base(host_t *current_host, char *snmp_oid, bool should_fail) { /* poll host */ SPINE_LOG_DEVDBG(("Device[%i] DEBUG: snmp_sess_sync_response(%s)", current_host->id, snmp_oid)); - status = snmp_sess_synch_response(current_host->snmp_session, pdu, &response); + status = snmp_synchronized_response(current_host, pdu, &response); SPINE_LOG_DEVDBG(("Device[%i] DEBUG: snmp_sess_sync_response(%s) [complete]", current_host->id, snmp_oid)); } @@ -578,7 +625,7 @@ char *snmp_getnext(host_t *current_host, char *snmp_oid) { } /* poll host */ - status = snmp_sess_synch_response(current_host->snmp_session, pdu, &response); + status = snmp_synchronized_response(current_host, pdu, &response); /* add status to host structure */ current_host->snmp_status = status; @@ -671,7 +718,7 @@ int snmp_count(host_t *current_host, char *snmp_oid) { snmp_add_null_var(pdu, anOID, anOID_len); /* do the request, use thread safe call */ - status = snmp_sess_synch_response(current_host->snmp_session, pdu, &response); + status = snmp_synchronized_response(current_host, pdu, &response); //SPINE_LOG_DEBUG(("TRACE: Status %i Response %i", status, response->errstat)); @@ -834,7 +881,7 @@ void snmp_get_multi(host_t *current_host, target_t *poller_items, snmp_oids_t *s /* execute the multi-get request */ retry: - status = snmp_sess_synch_response(current_host->snmp_session, pdu, &response); + status = snmp_synchronized_response(current_host, pdu, &response); /* liftoff, successful poll, process it!! */ if (status == STAT_SUCCESS) { diff --git a/spine.c b/spine.c index 5d32657d..c2bdb1aa 100644 --- a/spine.c +++ b/spine.c @@ -96,6 +96,8 @@ #include "common.h" #include "spine.h" +#include +#include /* Global Variables */ int entries = 0; @@ -190,6 +192,57 @@ void drop_root(uid_t server_uid, gid_t server_gid) { * \return 0 if SUCCESS, or -1 if FAILED * */ + +/* Reject invalid sizes before the stack formula can overflow. */ +#if RESULTS_BUFFER < 2 +#error RESULTS_BUFFER must hold a value and terminator +#endif +#if RESULTS_BUFFER > (SIZE_MAX - (2 * 180 * 1024 + 65535)) / 10 +#error RESULTS_BUFFER overflows the worker stack size +#endif +#define SPINE_THREAD_STACK_SIZE \ + (((size_t) 2 * ((size_t) 180 * 1024 + 5 * (size_t) RESULTS_BUFFER) + 65535) & ~(size_t) 65535) + +static int spine_thread_attr_init(pthread_attr_t *attributes) { + size_t current = 0; + size_t wanted = SPINE_THREAD_STACK_SIZE; + int status; + +#ifdef PTHREAD_STACK_MIN + if (wanted < (size_t) PTHREAD_STACK_MIN) wanted = (size_t) PTHREAD_STACK_MIN; +#endif + + status = pthread_attr_init(attributes); + if (status != 0) { + return status; + } + + if (pthread_attr_getstacksize(attributes, ¤t) == 0 && current >= wanted) { + return 0; + } + + status = pthread_attr_setstacksize(attributes, wanted); + if (status != 0) { + pthread_attr_destroy(attributes); + } + + return status; +} + + +/* Accept a whole in-range decimal before sizing workers or selecting hosts. */ +static bool parse_cli_int(const char *text, long minimum, long maximum, int *value) { + char *end; + long parsed; + + if (text[0] < '0' || text[0] > '9') return FALSE; + errno = 0; + parsed = strtol(text, &end, 10); + if (errno != 0 || *end != '\0' || parsed < minimum || parsed > maximum) return FALSE; + *value = (int)parsed; + return TRUE; +} + int main(int argc, char *argv[]) { char *conf_file = NULL; double begin_time, end_time, cur_time; @@ -346,9 +399,9 @@ int main(int argc, char *argv[]) { die("ERROR: %s can only be used once", arg); } - set.start_host_id = atoi(opt = getarg(opt, &argv)); + opt = getarg(opt, &argv); - if (!HOSTID_DEFINED(set.start_host_id)) { + if (!parse_cli_int(opt, 0, INT_MAX, &set.start_host_id)) { die("ERROR: '%s=%s' is invalid first-host ID", arg, opt); } } @@ -358,9 +411,9 @@ int main(int argc, char *argv[]) { die("ERROR: %s can only be used once", arg); } - set.end_host_id = atoi(opt = getarg(opt, &argv)); + opt = getarg(opt, &argv); - if (!HOSTID_DEFINED(set.end_host_id)) { + if (!parse_cli_int(opt, 0, INT_MAX, &set.end_host_id)) { die("ERROR: '%s=%s' is invalid last-host ID", arg, opt); } } @@ -370,7 +423,14 @@ int main(int argc, char *argv[]) { } else if (STRMATCH(arg, "-t") || STRIMATCH(arg, "--threads")) { - set.threads = atoi(getarg(opt, &argv)); + opt = getarg(opt, &argv); + if (!parse_cli_int(opt, 1, INT_MAX, &set.threads)) { + die("ERROR: Invalid thread count"); + } + if (set.threads > MAX_THREADS) { + fprintf(stderr, "WARNING: Thread count exceeds maximum; using %d\n", MAX_THREADS); + set.threads = MAX_THREADS; + } set.threads_set = TRUE; } @@ -444,11 +504,15 @@ int main(int argc, char *argv[]) { } else if (!HOSTID_DEFINED(set.start_host_id) && all_digits(arg)) { - set.start_host_id = atoi(arg); + if (!parse_cli_int(arg, 0, INT_MAX, &set.start_host_id)) { + die("ERROR: Invalid host ID"); + } } else if (!HOSTID_DEFINED(set.end_host_id) && all_digits(arg)) { - set.end_host_id = atoi(arg); + if (!parse_cli_int(arg, 0, INT_MAX, &set.end_host_id)) { + die("ERROR: Invalid host ID"); + } } else { @@ -697,8 +761,10 @@ int main(int argc, char *argv[]) { } /* initialize threads and mutexes */ - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + if (spine_thread_attr_init(&attr) != 0 || + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) { + die("ERROR: Unable to initialize polling thread attributes"); + } init_mutexes(); diff --git a/util.c b/util.c index a51480d2..30f61ba8 100644 --- a/util.c +++ b/util.c @@ -561,11 +561,21 @@ void read_config_options() { /* get Cacti defined max threads override spine.conf */ if (set.threads_set == FALSE) { if ((res = getpsetting(&mysql, mode, "threads")) != 0) { - set.threads = atoi(res); - free((char *)res); - if (set.threads > MAX_THREADS) { + char *end; + long threads; + + /* Zero or garbage would start no workers; match the -t bounds. */ + errno = 0; + threads = strtol(res, &end, 10); + if (res[0] < '0' || res[0] > '9' || errno != 0 || *end != '\0' || threads < 1) { + SPINE_LOG(("WARNING: Invalid threads setting, using %d", DEFAULT_THREADS)); + set.threads = DEFAULT_THREADS; + } else if (threads > MAX_THREADS) { set.threads = MAX_THREADS; + } else { + set.threads = (int) threads; } + free((char *)res); } } @@ -1054,6 +1064,17 @@ void poller_push_data_to_main() { * * \return 0 if successful or -1 if the file could not be opened */ +/* Consume an overlong physical line so its tail cannot become a directive. */ +static bool config_line_complete(FILE *fp, const char *line, size_t capacity) { + int next; + + if (line[capacity - 1] != '\0' || line[capacity - 2] == '\n') return TRUE; + next = getc(fp); + if (next == EOF || next == '\n') return TRUE; + while (next != EOF && next != '\n') next = getc(fp); + return FALSE; +} + int read_spine_config(char *file) { FILE *fp; char buff[BUFSIZE]; @@ -1074,10 +1095,15 @@ int read_spine_config(char *file) { } while (!feof(fp)) { - chars = fgets(buff, BUFSIZE, fp); + buff[sizeof(buff) - 1] = 1; + chars = fgets(buff, sizeof(buff), fp); + if (chars != NULL && !config_line_complete(fp, buff, sizeof(buff))) { + if (!set.stderr_notty) fprintf(stderr, "WARNING: Ignoring an overlong config line\n"); + continue; + } - if (chars != NULL && !feof(fp) && *buff != '#' && *buff != ' ' && *buff != '\n') { - sscanf(buff, "%15s %255s", p1, p2); + if (chars != NULL && *buff != '#' && *buff != ' ' && *buff != '\n') { + if (sscanf(buff, "%1023s %1023s", p1, p2) != 2) continue; if (STRIMATCH(p1, "RDB_Host")) STRNCOPY(set.rdb_host, p2); else if (STRIMATCH(p1, "RDB_Database")) STRNCOPY(set.rdb_db, p2); @@ -1108,7 +1134,7 @@ int read_spine_config(char *file) { set.log_destination = LOGDEST_BOTH; } else if (STRIMATCH(p1, "SNMP_Clientaddr")) STRNCOPY(set.snmp_clientaddr, p2); else if (!set.stderr_notty) { - fprintf(stderr,"WARNING: Unrecongized directive: %s=%s in %s\n", p1, p2, file); + fprintf(stderr,"WARNING: Unrecognized directive %s in config file\n", p1); } *p1 = '\0';