diff --git a/source/linux/network.c b/source/linux/network.c index 81c8b215..7f7b57a1 100644 --- a/source/linux/network.c +++ b/source/linux/network.c @@ -338,7 +338,7 @@ int get_network_config_and_transfer(struct aws_iotdevice_network_ifconfig *ifcon return AWS_OP_ERR; } int result = AWS_OP_ERR; - int fd = 0; + int fd = -1; struct ifaddrs *address_info = NULL; if (getifaddrs(&address_info)) { AWS_LOGF_ERROR( @@ -408,8 +408,10 @@ int get_network_config_and_transfer(struct aws_iotdevice_network_ifconfig *ifcon goto cleanup; } next_interface: - close(fd); - fd = 0; + if (fd != -1) { + close(fd); + fd = -1; + } address = address->ifa_next; } /* while */ result = AWS_OP_SUCCESS; @@ -421,7 +423,7 @@ int get_network_config_and_transfer(struct aws_iotdevice_network_ifconfig *ifcon if (address_info) { freeifaddrs(address_info); } - if (fd) { + if (fd != -1) { close(fd); } return result; diff --git a/tests/metrics_tests.c b/tests/metrics_tests.c index a34a0ec6..94966091 100644 --- a/tests/metrics_tests.c +++ b/tests/metrics_tests.c @@ -20,6 +20,11 @@ #include #include +#ifdef AWS_OS_LINUX +# include +# include +#endif /* AWS_OS_LINUX */ + const char *TM_NUMBER = "TestMetricNumber"; const char *TM_NUMBER_LIST = "TestMetricNumberList"; const char *TM_STRING_LIST = "TestMetricStringList"; @@ -338,6 +343,14 @@ static int s_devicedefender_get_network_connections(struct aws_allocator *alloca AWS_ZERO_STRUCT(ifconfig); ASSERT_SUCCESS(get_network_config_and_transfer(&ifconfig, allocator)); +#ifdef AWS_OS_LINUX + /* Regression test: Check that get_network_config_and_transfer didn't + * accidentally close file descriptor 0 (aka stdin) */ + errno = 0; + bool file_descriptor_0_is_closed = (fcntl(0, F_GETFD) == -1) && (errno != 0); + ASSERT_FALSE(file_descriptor_0_is_closed); +#endif /* AWS_OS_LINUX */ + struct aws_array_list net_conns; AWS_ZERO_STRUCT(net_conns); aws_array_list_init_dynamic(&net_conns, allocator, 5, sizeof(struct aws_iotdevice_metric_net_connection));