From f2972903d5378e2a9cd9492b7003dbb8df9b43d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20H=C3=BCttel?= Date: Sat, 10 Apr 2021 14:37:51 +0200 Subject: [PATCH] Use safer string copying in gui for file list --- stm-firmware/ui/gui.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/stm-firmware/ui/gui.c b/stm-firmware/ui/gui.c index 1b4c1a8..74324b8 100644 --- a/stm-firmware/ui/gui.c +++ b/stm-firmware/ui/gui.c @@ -374,6 +374,36 @@ static void gui_menu_constant_temperature_driver(struct lcd_menu *menu, enum men } +/** + * @brief A safe strncpy which ensures thtat the copied string ends in a null character + * @param dest Destiantion ptr + * @param src Source pointer + * @param max_size maximum size of the destination (including null terminator) + * @return 0 if successful, positive, if string was to short to hold all data, negative if parameter error + */ +static int safe_strncpy(char *dest, const char *src, size_t max_size) { + size_t idx; + bool terminated = false; + + if (!dest || !src || !max_size) + return -1000; + + for (idx = 0; idx < max_size; idx++) { + dest[idx] = src[idx]; + if (src[idx] == '\0') { + terminated = true; + break; + } + } + + if (!terminated) { + dest[max_size - 1] = 0; + return 1; + } + + return 0; +} + /** * @brief load_temperature_file_list_from_sdcard * @return -1 File error, 0 successful @@ -385,6 +415,7 @@ static int load_temperature_file_list_from_sdcard(char (*list)[17], uint32_t len FILINFO finfo; FRESULT fres; + if (!list) return -1001; @@ -399,7 +430,7 @@ static int load_temperature_file_list_from_sdcard(char (*list)[17], uint32_t len fres = f_findfirst(&directory, &finfo, "/", "*.tpr"); i = 0; while (fres == FR_OK && finfo.fname[0]) { - strncpy(list[i], finfo.fname, sizeof(*list)); + safe_strncpy(&list[i][0], finfo.fname, sizeof(*list)); fres = f_findnext(&directory, &finfo); i++; if (i >= len)