From 2978d33089947ebdceef62f815cf020d035d457c Mon Sep 17 00:00:00 2001 From: Daniel Stenberg Date: Tue, 5 Aug 2025 13:43:49 +0200 Subject: [PATCH] tool_cb_wrt: use dynbuf instead of "manual" malloc When creating new file names for no-clobber Closes #18182 --- src/tool_cb_wrt.c | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/src/tool_cb_wrt.c b/src/tool_cb_wrt.c index 7b570b8e57..3ac14cd012 100644 --- a/src/tool_cb_wrt.c +++ b/src/tool_cb_wrt.c @@ -68,35 +68,24 @@ bool tool_create_output_file(struct OutStruct *outs, } while(fd == -1 && errno == EINTR); if(config->file_clobber_mode == CLOBBER_NEVER && fd == -1) { int next_num = 1; - size_t len = strlen(fname); - size_t newlen = len + 13; /* nul + 1-11 digits + dot */ - char *newname; - /* Guard against wraparound in new filename */ - if(newlen < len) { - errorf(global, "overflow in filename generation"); - return FALSE; - } - newname = malloc(newlen); - if(!newname) { - errorf(global, "out of memory"); - return FALSE; - } - memcpy(newname, fname, len); - newname[len] = '.'; + struct dynbuf fbuffer; + curlx_dyn_init(&fbuffer, 1025); /* !checksrc! disable ERRNOVAR 1 */ while(fd == -1 && /* have not successfully opened a file */ (errno == EEXIST || errno == EISDIR) && /* because we keep having files that already exist */ next_num < 100 /* and we have not reached the retry limit */ ) { - msnprintf(newname + len + 1, 12, "%d", next_num); + curlx_dyn_reset(&fbuffer); + if(curlx_dyn_addf(&fbuffer, "%s.%d", fname, next_num)) + return FALSE; next_num++; do { - fd = open(newname, O_CREAT | O_WRONLY | O_EXCL | CURL_O_BINARY, - OPENMODE); + fd = open(curlx_dyn_ptr(&fbuffer), + O_CREAT | O_WRONLY | O_EXCL | CURL_O_BINARY, OPENMODE); /* Keep retrying in the hope that it is not interrupted sometime */ } while(fd == -1 && errno == EINTR); } - outs->filename = newname; /* remember the new one */ + outs->filename = curlx_dyn_ptr(&fbuffer); /* remember the new one */ outs->alloc_filename = TRUE; } /* An else statement to not overwrite existing files and not retry with -- 2.47.3