tool: improve --stderr handling

- freopen stderr with the user-specified file (--stderr file) instead of
  using a separate 'errors' stream.

- In tool_setup.h override stdio.h's stderr macro as global variable
  tool_stderr.

Both freopen and overriding the stderr macro are necessary because if
the user-specified filename is "-" then stdout is assigned to
tool_stderr and no freopen takes place. See the PR for more information.

Ref: https://github.com/curl/curl/issues/10491

Closes https://github.com/curl/curl/pull/10673
This commit is contained in:
Jay Satiro 2023-03-04 04:07:24 -05:00
parent 395b9175b7
commit 2f17a9b654
14 changed files with 151 additions and 60 deletions

View file

@ -42,6 +42,7 @@
#include "tool_parsecfg.h"
#include "tool_main.h"
#include "dynbuf.h"
#include "tool_stderr.h"
#include "memdebug.h" /* keep this as LAST include */
@ -1036,19 +1037,7 @@ ParameterError getparameter(const char *flag, /* f or -long-flag */
break;
case 'v': /* --stderr */
if(strcmp(nextarg, "-")) {
FILE *newfile = fopen(nextarg, FOPEN_WRITETEXT);
if(!newfile)
warnf(global, "Failed to open %s!\n", nextarg);
else {
if(global->errors_fopened)
fclose(global->errors);
global->errors = newfile;
global->errors_fopened = TRUE;
}
}
else
global->errors = stdout;
tool_set_stderr_file(nextarg);
break;
case 'w': /* --interface */
/* interface */
@ -2567,9 +2556,9 @@ ParameterError parse_args(struct GlobalConfig *global, int argc,
const char *reason = param2text(result);
if(orig_opt && strcmp(":", orig_opt))
helpf(global->errors, "option %s: %s\n", orig_opt, reason);
helpf(stderr, "option %s: %s\n", orig_opt, reason);
else
helpf(global->errors, "%s\n", reason);
helpf(stderr, "%s\n", reason);
}
curlx_unicodefree(orig_opt);