From 7dae62a7c32ef554bdb966f703be1557e54bb170 Mon Sep 17 00:00:00 2001 From: Hiroshi Hatake Date: Fri, 26 Jul 2024 11:51:53 +0900 Subject: [PATCH] compat: decode_statsd: Import and use a generic safe version of strtok_r Signed-off-by: Hiroshi Hatake --- include/cmetrics/cmt_compat.h | 23 ++++++++++++++++++++++- src/cmt_decode_statsd.c | 8 ++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/include/cmetrics/cmt_compat.h b/include/cmetrics/cmt_compat.h index d7d2510..a4f8a9d 100644 --- a/include/cmetrics/cmt_compat.h +++ b/include/cmetrics/cmt_compat.h @@ -23,9 +23,30 @@ #include #ifdef _WIN32 #include -#define strtok_r strtok_s #endif +/* This function is copied from monkey/monkey. + https://github.com/monkey/monkey/blob/2567a70912ed7a68d9e75dca3cf22d3927fea99a/mk_core/deps/libevent/evdns.c#L3323 */ +static inline char * +cmt_platform_strtok_r(char *s, const char *delim, char **state) { + char *cp, *start; + start = cp = s ? s : *state; + if (!cp) + return NULL; + while (*cp && !strchr(delim, *cp)) + ++cp; + if (!*cp) { + if (cp == start) + return NULL; + *state = NULL; + return start; + } else { + *cp++ = '\0'; + *state = cp; + return start; + } +} + static inline struct tm *cmt_platform_gmtime_r(const time_t *timep, struct tm *result) { #ifdef CMT_HAVE_GMTIME_S diff --git a/src/cmt_decode_statsd.c b/src/cmt_decode_statsd.c index 130fa43..34f77b9 100644 --- a/src/cmt_decode_statsd.c +++ b/src/cmt_decode_statsd.c @@ -134,7 +134,7 @@ static int decode_labels(struct cmt *cmt, } if (labels != NULL) { - label_kv = strtok_r(labels, ",", &store); + label_kv = cmt_platform_strtok_r(labels, ",", &store); while (label_kv != NULL) { colon = strchr(label_kv, ':'); @@ -185,7 +185,7 @@ static int decode_labels(struct cmt *cmt, cfl_sds_destroy(label_k); retry: - label_kv = strtok_r(NULL, ",", &store); + label_kv = cmt_platform_strtok_r(NULL, ",", &store); } } @@ -524,7 +524,7 @@ static int decode_metrics_lines(struct cmt *cmt, char *line = NULL; char *store = NULL; - line = strtok_r(in_buf, "\n", &store); + line = cmt_platform_strtok_r(in_buf, "\n", &store); while (line != NULL) { /* StatsD format always has | at least one. */ if (strstr(line, "|") == NULL) { @@ -538,7 +538,7 @@ static int decode_metrics_lines(struct cmt *cmt, break; } retry: - line = strtok_r(NULL, "\n", &store); + line = cmt_platform_strtok_r(NULL, "\n", &store); } return ret;