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));