Avoid printing unterminated string in readline()

When running with -v, readline() in io.c uses strncpy() to copy a string
(*without* the terminating NULL) into an uninitialized buffer created by
malloc().

When message() then prints this, it can lead to garbage data being
emitted since it's potentially reading past the intended end of the
string. In practice, this appears to only be an additional byte or 2
before a NULL is encountered.

The issue was hit when readline() encountered "\r\n\r\n", not longer
strings, but I imagine it's dependent on things like compiler / libc /
the weather as to whether the end of the buffer returned by malloc()
will be zeroed or not; I've seen similar issues pop up with "working"
code running on newer distros.
This commit is contained in:
Matt Merhar 2024-09-13 18:30:25 -04:00
parent 84d44b608b
commit 9df98a6e31

2
io.c
View file

@ -57,7 +57,7 @@ int readline(PTSTREAM *pts) {
if( args_info.verbose_flag ) {
/* Copy line of data into dstr without trailing newline */
char *dstr = malloc(strlen(buf) + 1);
char *dstr = calloc(1, strlen(buf) + 1);
strncpy( dstr, buf, strlen(buf));
if (strcmp(dstr, ""))
message( " <- %s\n", dstr );