Use safer string copying in gui for file list

This commit is contained in:
Mario Hüttel 2021-04-10 14:37:51 +02:00
parent 31b17dfd8d
commit f2972903d5

View File

@ -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 * @brief load_temperature_file_list_from_sdcard
* @return -1 File error, 0 successful * @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; FILINFO finfo;
FRESULT fres; FRESULT fres;
if (!list) if (!list)
return -1001; 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"); fres = f_findfirst(&directory, &finfo, "/", "*.tpr");
i = 0; i = 0;
while (fres == FR_OK && finfo.fname[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); fres = f_findnext(&directory, &finfo);
i++; i++;
if (i >= len) if (i >= len)