Skip to content

Commit b51044b

Browse files
committed
Fix long-standing race in net-tokio reading after a disconnect event
If rust-lightning tells us to disconnect a socket after we read some bytes from the socket, but before we actually give those bytes to rust-lightning, we may end up calling rust-lightning with a Descriptor that isn't registered anymore. Sadly, there really isn't a good way to solve this, and it should be a pretty quick event, so we just busy-wait.
1 parent 84315a5 commit b51044b

File tree

1 file changed

+34
-14
lines changed

1 file changed

+34
-14
lines changed

lightning-net-tokio/src/lib.rs

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ use lightning::ln::peer_handler;
7070
use lightning::ln::peer_handler::SocketDescriptor as LnSocketTrait;
7171
use lightning::ln::msgs::ChannelMessageHandler;
7272

73-
use std::task;
73+
use std::{task, thread};
7474
use std::net::SocketAddr;
7575
use std::sync::{Arc, Mutex};
7676
use std::sync::atomic::{AtomicU64, Ordering};
@@ -112,6 +112,11 @@ struct Connection {
112112
// send into any read_blocker to wake the reading future back up and set read_paused back to
113113
// false.
114114
read_blocker: Option<oneshot::Sender<()>>,
115+
// When we are told by rust-lightning to disconnect, we can't return to rust-lightning until we
116+
// are sure we won't call any more read/write PeerManager functions with the same connection.
117+
// This is set to true if we're in such a condition (with disconnect checked before with the
118+
// top-level mutex held) and false when we can return.
119+
block_disconnect_socket: bool,
115120
read_paused: bool,
116121
disconnect_state: DisconnectionState,
117122
id: u64,
@@ -129,20 +134,29 @@ impl Connection {
129134
} }
130135
}
131136

137+
macro_rules! prepare_read_write_call {
138+
() => { {
139+
let mut us_lock = us.lock().unwrap();
140+
if us_lock.disconnect_state == DisconnectionState::RLTriggeredDisconnect {
141+
shutdown_socket!("disconnect_socket() call from RL");
142+
}
143+
us_lock.block_disconnect_socket = true;
144+
} }
145+
}
146+
132147
// Whenever we want to block on reading or waiting for reading to resume, we have to
133148
// at least select with the write_avail_receiver, which is used by the
134149
// SocketDescriptor to wake us up if we need to shut down the socket or if we need
135150
// to generate a write_buffer_space_avail call.
136151
macro_rules! select_write_ev {
137152
($v: expr) => { {
138153
assert!($v.is_some()); // We can't have dropped the sending end, its in the us Arc!
139-
if us.lock().unwrap().disconnect_state == DisconnectionState::RLTriggeredDisconnect {
140-
shutdown_socket!("disconnect_socket() call from RL");
141-
}
154+
prepare_read_write_call!();
142155
if let Err(e) = peer_manager.write_buffer_space_avail(&mut SocketDescriptor::new(us.clone())) {
143156
us.lock().unwrap().disconnect_state = DisconnectionState::RLTriggeredDisconnect;
144157
shutdown_socket!(e);
145158
}
159+
us.lock().unwrap().block_disconnect_socket = false;
146160
} }
147161
}
148162

@@ -175,6 +189,7 @@ impl Connection {
175189
v = write_avail_receiver.recv() => select_write_ev!(v),
176190
}
177191
}
192+
prepare_read_write_call!();
178193
match peer_manager.read_event(&mut SocketDescriptor::new(Arc::clone(&us)), &buf[0..len]) {
179194
Ok(pause_read) => {
180195
if pause_read {
@@ -196,6 +211,7 @@ impl Connection {
196211
shutdown_socket!(e)
197212
},
198213
}
214+
us.lock().unwrap().block_disconnect_socket = false;
199215
},
200216
Err(e) => {
201217
println!("Connection closed: {}", e);
@@ -204,6 +220,7 @@ impl Connection {
204220
},
205221
}
206222
}
223+
us.lock().unwrap().block_disconnect_socket = false;
207224
let writer_option = us.lock().unwrap().writer.take();
208225
if let Some(mut writer) = writer_option {
209226
// If the socket is already closed, shutdown() will fail, so just ignore it.
@@ -233,7 +250,7 @@ impl Connection {
233250

234251
(reader, receiver,
235252
Arc::new(Mutex::new(Self {
236-
writer: Some(writer), event_notify, write_avail,
253+
writer: Some(writer), event_notify, write_avail, block_disconnect_socket: false,
237254
read_blocker: None, read_paused: false, disconnect_state: DisconnectionState::NeedDisconnectEvent,
238255
id: ID_COUNTER.fetch_add(1, Ordering::AcqRel)
239256
})))
@@ -422,15 +439,18 @@ impl peer_handler::SocketDescriptor for SocketDescriptor {
422439
}
423440

424441
fn disconnect_socket(&mut self) {
425-
let mut us = self.conn.lock().unwrap();
426-
us.disconnect_state = DisconnectionState::RLTriggeredDisconnect;
427-
us.read_paused = true;
428-
// Wake up the sending thread, assuming it is still alive
429-
let _ = us.write_avail.try_send(());
430-
// TODO: There's a race where we don't meet the requirements of disconnect_socket if the
431-
// read task is about to call a PeerManager function (eg read_event or write_event).
432-
// Ideally we need to release the us lock and block until we have confirmation from the
433-
// read task that it has broken out of its main loop.
442+
{
443+
let mut us = self.conn.lock().unwrap();
444+
us.disconnect_state = DisconnectionState::RLTriggeredDisconnect;
445+
us.read_paused = true;
446+
// Wake up the sending thread, assuming it is still alive
447+
let _ = us.write_avail.try_send(());
448+
// Happy-path return:
449+
if !us.block_disconnect_socket { return; }
450+
}
451+
while self.conn.lock().unwrap().block_disconnect_socket {
452+
thread::yield_now();
453+
}
434454
}
435455
}
436456
impl Clone for SocketDescriptor {

0 commit comments

Comments
 (0)