From 531c47b47ce62663a7dcafdad5333d3f58e6203b Mon Sep 17 00:00:00 2001 From: cpq Date: Wed, 17 Mar 2021 13:46:50 +0000 Subject: [PATCH] mg_to64 overflow protection --- mongoose.c | 3 ++- src/util.c | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/mongoose.c b/mongoose.c index 23ed3362..1406453c 100644 --- a/mongoose.c +++ b/mongoose.c @@ -4195,11 +4195,12 @@ int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { } int64_t mg_to64(struct mg_str str) { - int64_t result = 0, neg = 1; + int64_t result = 0, neg = 1, max = 922337203685477580 /* INT64_MAX / 10 */; size_t i = 0; while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++; if (i < str.len && str.ptr[i] == '-') neg = -1, i++; while (i < str.len && str.ptr[i] >= '0' && str.ptr[i] <= '9') { + if (result > max) return 0; result *= 10; result += (str.ptr[i] - '0'); i++; diff --git a/src/util.c b/src/util.c index 2943df73..d4f6c258 100644 --- a/src/util.c +++ b/src/util.c @@ -262,11 +262,12 @@ int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { } int64_t mg_to64(struct mg_str str) { - int64_t result = 0, neg = 1; + int64_t result = 0, neg = 1, max = 922337203685477580 /* INT64_MAX / 10 */; size_t i = 0; while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++; if (i < str.len && str.ptr[i] == '-') neg = -1, i++; while (i < str.len && str.ptr[i] >= '0' && str.ptr[i] <= '9') { + if (result > max) return 0; result *= 10; result += (str.ptr[i] - '0'); i++;