diff --git a/core/src/main/scalanative/sttp/client4/curl/AbstractCurlBackend.scala b/core/src/main/scalanative/sttp/client4/curl/AbstractCurlBackend.scala index 7f50880cd..28b0e56ed 100644 --- a/core/src/main/scalanative/sttp/client4/curl/AbstractCurlBackend.scala +++ b/core/src/main/scalanative/sttp/client4/curl/AbstractCurlBackend.scala @@ -286,9 +286,17 @@ abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean curl.option(HeaderData, spaces.headersResp) curl.option(Url, request.uri.toString) setMethod(curl, request.method) - setRequestBody(curl, request.body, request.method).flatMap { _ => + // the try block below frees the native resources only once the transfer starts, so earlier failures free them here + cleanupOnError(setRequestBody(curl, request.body, request.method)) { + curl.cleanup() + freeSpaces(spaces) + }.flatMap { _ => val multi = CurlApi.multiInit - liftM(multi.addHandle(curl)).flatMap { _ => + cleanupOnError(liftM(multi.addHandle(curl))) { + multi.cleanup() + curl.cleanup() + freeSpaces(spaces) + }.flatMap { _ => // Track whether native resources (multi, curl, spaces) have already been cleaned up — // either by transferring ownership to CurlMultiInputStream or by explicit freeing in a fallback path. // When true, the outer catch block must NOT attempt to free them (would double-free). @@ -518,6 +526,13 @@ abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean buffer.toByteArray } + /** Runs `cleanup` if `fa` fails, including when evaluating `fa` throws. */ + private def cleanupOnError[A](fa: => F[A])(cleanup: => Unit): F[A] = + monad.handleError(monad.suspend(fa)) { case e => + cleanup + monad.error(e) + } + private def liftM(code: CurlMCode.CurlMCode): F[CurlMCode.CurlMCode] = code match { case CurlMCode.Ok => monad.unit(code)