From 82e3539db301d17f7a5c07c75c714692f3a61baf Mon Sep 17 00:00:00 2001
From: chrysn <chrysn@fsfe.org>
Date: Tue, 7 May 2024 00:53:39 +0200
Subject: [PATCH] Connection: Clean up in __destroy__

Cleaning up in __del__ (or any __del__, really) triggered pypy's checks
for valid C API use.

Closes: https://github.com/mclab-hbrs/DTLSSocket/issues/12
---
 DTLSSocket/dtls.pyx | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/DTLSSocket/dtls.pyx b/DTLSSocket/dtls.pyx
index 013e866..42cc1fd 100644
--- a/DTLSSocket/dtls.pyx
+++ b/DTLSSocket/dtls.pyx
@@ -156,18 +156,20 @@ cdef class Connection(Session):
   def __init__(self, DTLS dtls, Session s):
     super().__init__(addr = s.addr, port = s.port, flowinfo=s.flowinfo, scope_id=s.scope_id)
     self.d = dtls
-  def __del__(self):
-    self.d.close(self)
-    self.d.resetPeer(self)
+  def __dealloc__(self):
+    peer = tdtls.dtls_get_peer(self.d.ctx, &self.session)
+    if peer:
+      tdtls.dtls_reset_peer(self.d.ctx, peer)
 
 cdef class MCConnection(Session):
   cdef DTLS d
   def __init__(self, DTLS dtls, Session s):
     super().__init__(addr = s.addr, port = s.port, flowinfo=s.flowinfo, scope_id=s.scope_id)
     self.d = dtls
-  def __del__(self):
-    self.d.joinLeaveGroupe(self.addr, self.d._sock, join=False)
-    self.d.resetPeer(self)
+  def __dealloc__(self):
+    peer = tdtls.dtls_get_peer(self.d.ctx, &self.session)
+    if peer:
+      tdtls.dtls_reset_peer(self.d.ctx, peer)
 
 cdef class DTLS:
   cdef dtls_context_t *ctx
-- 
GitLab