tls: make sure saved session is refcounted
otherwise OpenSSL will eventually garbage collect it out from under us,
causing a crash when we try to reuse it. Also free it properly when
we're done with it.
Same also for imtest.
Fixes #3191, and maybe #2979