From 613000d83cb0af9640a107a0cdde68e318a6c26e Mon Sep 17 00:00:00 2001 From: Pu Cheng Date: Fri, 20 Nov 2026 05:49:41 +0800 Subject: [PATCH] in BUGFIX reject a stream without a file descriptor in ly_in_file() For a stream without a file descriptor (fmemopen(), open_memstream()) fileno() returns -1, which ly_in_fd() takes as a query of the current descriptor. ly_in_file() then returned the previous stream as if the input was changed and stored the new stream in the handler, while the handler kept reading the previous file. Return NULL and leave the handler untouched, as documented. --- src/in.c | 3 +++ tests/utests/basic/test_inout.c | 11 ++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/in.c b/src/in.c index c92739147..a1fded19a 100644 --- a/src/in.c +++ b/src/in.c @@ -164,6 +164,9 @@ ly_in_file(struct ly_in *in, FILE *f) prev_f = in->method.f; if (f) { + /* a stream without a descriptor cannot be mapped, and ly_in_fd() would take -1 as a query */ + LY_CHECK_ERR_RET(fileno(f) == -1, LOGERR(NULL, LY_EINVAL, "Input stream has no file descriptor."), NULL); + /* convert LY_IN_FILE handler into LY_IN_FD to be able to update it via ly_in_fd() */ in->type = LY_IN_FD; in->method.fd = fileno(prev_f); diff --git a/tests/utests/basic/test_inout.c b/tests/utests/basic/test_inout.c index c5e1d5c9c..bb3ef90ff 100644 --- a/tests/utests/basic/test_inout.c +++ b/tests/utests/basic/test_inout.c @@ -164,7 +164,8 @@ static void test_input_file(void **UNUSED(state)) { struct ly_in *in = NULL; - FILE *f1 = NULL, *f2 = NULL; + FILE *f1 = NULL, *f2 = NULL, *f3 = NULL; + char buf[] = "{}"; assert_int_equal(LY_EINVAL, ly_in_new_file(NULL, NULL)); assert_null(ly_in_file(NULL, NULL)); @@ -179,6 +180,14 @@ test_input_file(void **UNUSED(state)) assert_ptr_equal(f1, ly_in_file(in, f2)); assert_ptr_equal(f2, ly_in_file(in, NULL)); assert_ptr_equal(f2, ly_in_file(in, NULL)); +#ifndef _WIN32 + /* a stream without a file descriptor cannot be used and the handler keeps its stream */ + assert_non_null(f3 = fmemopen(buf, sizeof buf, "r")); + assert_null(ly_in_file(in, f3)); + CHECK_LOG_LASTMSG("Input stream has no file descriptor."); + assert_ptr_equal(f2, ly_in_file(in, NULL)); + fclose(f3); +#endif ly_in_free(in, 1); /* f1 is still open */ assert_int_not_equal(-1, fileno(f1));