Fix file descriptor leak (on `bind()` failure) in QUIC client.
PiperOrigin-RevId: 471918850
diff --git a/quiche/quic/tools/quic_client_default_network_helper.cc b/quiche/quic/tools/quic_client_default_network_helper.cc
index 24c4b3e..a408a8f 100644
--- a/quiche/quic/tools/quic_client_default_network_helper.cc
+++ b/quiche/quic/tools/quic_client_default_network_helper.cc
@@ -4,6 +4,7 @@
#include "quiche/quic/tools/quic_client_default_network_helper.h"
+#include "absl/cleanup/cleanup.h"
#include "quiche/quic/core/io/quic_event_loop.h"
#include "quiche/quic/core/quic_default_packet_writer.h"
#include "quiche/quic/core/quic_packets.h"
@@ -71,6 +72,7 @@
if (fd < 0) {
return false;
}
+ auto closer = absl::MakeCleanup([fd] { close(fd); });
QuicSocketAddress client_address;
if (bind_to_address.IsInitialized()) {
@@ -113,10 +115,13 @@
<< strerror(errno);
}
- fd_address_map_[fd] = client_address;
- bool success = event_loop_->RegisterSocket(
- fd, kSocketEventReadable | kSocketEventWritable, this);
- return success;
+ if (event_loop_->RegisterSocket(
+ fd, kSocketEventReadable | kSocketEventWritable, this)) {
+ fd_address_map_[fd] = client_address;
+ std::move(closer).Cancel();
+ return true;
+ }
+ return false;
}
void QuicClientDefaultNetworkHelper::CleanUpUDPSocket(int fd) {
diff --git a/quiche/quic/tools/quic_client_epoll_network_helper.cc b/quiche/quic/tools/quic_client_epoll_network_helper.cc
index b9798bd..60bf6c1 100644
--- a/quiche/quic/tools/quic_client_epoll_network_helper.cc
+++ b/quiche/quic/tools/quic_client_epoll_network_helper.cc
@@ -11,6 +11,7 @@
#include <sys/socket.h>
#include <unistd.h>
+#include "absl/cleanup/cleanup.h"
#include "quiche/quic/core/crypto/quic_random.h"
#include "quiche/quic/core/http/spdy_utils.h"
#include "quiche/quic/core/quic_connection.h"
@@ -62,6 +63,7 @@
if (fd < 0) {
return false;
}
+ auto closer = absl::MakeCleanup([fd] { close(fd); });
QuicSocketAddress client_address;
if (bind_to_address.IsInitialized()) {
@@ -106,6 +108,7 @@
fd_address_map_[fd] = client_address;
epoll_server_->RegisterFD(fd, this, kEpollFlags);
+ std::move(closer).Cancel();
return true;
}