From a1160f15562d72d69382f0ad729cf781683afac5 Mon Sep 17 00:00:00 2001
From: Yat Ho <lagoho7@gmail.com>
Date: Sun, 21 Jan 2024 08:09:28 +0800
Subject: [PATCH] fix: keep peer io alive inside utp callback (#6507)

---
 libtransmission/peer-io.cc | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/libtransmission/peer-io.cc b/libtransmission/peer-io.cc
index 74df46f1c..29dd8246b 100644
--- a/libtransmission/peer-io.cc
+++ b/libtransmission/peer-io.cc
@@ -725,6 +725,11 @@ void tr_peerIo::utp_init([[maybe_unused]] struct_utp_context* ctx)
         {
             if (auto* const io = static_cast<tr_peerIo*>(utp_get_userdata(args->socket)); io != nullptr)
             {
+                // The peer io object can destruct inside can_read_wrapper(), so keep
+                // it alive for the duration of this code block. This can happen when
+                // a BT handshake did not complete successfully for example.
+                auto const keep_alive = io->shared_from_this();
+
                 io->inbuf_.add(args->buf, args->len);
                 io->set_enabled(TR_DOWN, true);
                 io->can_read_wrapper();