From c9caceddabda7f18337b2a82d25d65f6224b450a Mon Sep 17 00:00:00 2001
From: sauwming <ming@teluu.com>
Date: Wed, 11 Mar 2026 07:18:49 +0800
Subject: [PATCH] Merge commit from fork

---
 pjnath/src/pjnath/ice_session.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/pjnath/src/pjnath/ice_session.c b/pjnath/src/pjnath/ice_session.c
index 39129761b0..e1513b94f9 100644
--- a/pjnath/src/pjnath/ice_session.c
+++ b/pjnath/src/pjnath/ice_session.c
@@ -3667,7 +3667,10 @@ PJ_DEF(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice,
     transport_id = cand->transport_id;
     pj_sockaddr_cp(&addr, &comp->valid_check->rcand->addr);
 
-    /* Release the mutex now to avoid deadlock (see ticket #1451). */
+    /* Release the mutex now to avoid deadlock (see ticket #1451),
+     * but add ref first to avoid premature destruction in the cb.
+     */
+    pj_grp_lock_add_ref(ice->grp_lock);
     pj_grp_lock_release(ice->grp_lock);
 
     PJ_RACE_ME(5);
@@ -3677,6 +3680,8 @@ PJ_DEF(pj_status_t) pj_ice_sess_send_data(pj_ice_sess *ice,
                                   &addr, 
                                   pj_sockaddr_get_len(&addr));
 
+    pj_grp_lock_dec_ref(ice->grp_lock);
+
 on_return:
     return status;
 }
@@ -3743,7 +3748,9 @@ PJ_DEF(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice,
     } else {
         /* Not a STUN packet. Call application's callback instead, but release
          * the mutex now or otherwise we may get deadlock.
+         * Add ref first to avoid race with session destruction.
          */
+        pj_grp_lock_add_ref(ice->grp_lock);
         pj_grp_lock_release(ice->grp_lock);
 
         PJ_RACE_ME(5);
@@ -3800,6 +3807,9 @@ PJ_DEF(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice,
                          "component [%d] because source addr %s unrecognized "
                          "or unchecked",
                          comp_id, paddr));
+
+                pj_grp_lock_dec_ref(ice->grp_lock);
+
                 return PJ_SUCCESS;
             }
         } 
@@ -3807,6 +3817,8 @@ PJ_DEF(pj_status_t) pj_ice_sess_on_rx_pkt(pj_ice_sess *ice,
         (*ice->cb.on_rx_data)(ice, comp_id, transport_id, pkt, pkt_size, 
                               src_addr, src_addr_len);
         status = PJ_SUCCESS;
+
+        pj_grp_lock_dec_ref(ice->grp_lock);
     }
 
     return status;
