From f4d82c12dd82733febd4926400471e1ca88b11ab Mon Sep 17 00:00:00 2001
From: Marc Hoersken <info@marc-hoersken.de>
Date: Sun, 9 Sep 2012 10:35:14 +0200
Subject: [PATCH] curl_schannel.c: Reference count the credential/session
 handle

Reference counting the credential handle should avoid that such a
handle is freed while it is still required for connection shutdown
---
 lib/curl_schannel.c |   12 +++++++++++-
 lib/urldata.h       |    1 +
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/lib/curl_schannel.c b/lib/curl_schannel.c
index c050315..4b0dd18 100644
--- a/lib/curl_schannel.c
+++ b/lib/curl_schannel.c
@@ -509,6 +509,11 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
     return CURLE_SSL_CONNECT_ERROR;
   }
 
+  /* increment the reference counter of the credential/session handle */
+  if(connssl->cred && connssl->ctxt) {
+    connssl->cred->refcount++;
+  }
+
   /* save the current session data for possible re-use */
   incache = !(Curl_ssl_getsessionid(conn, (void**)&old_cred, NULL));
   if(incache) {
@@ -1125,6 +1130,11 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
       s_pSecFn->DeleteSecurityContext(&connssl->ctxt->ctxt_handle);
       Curl_safefree(connssl->ctxt);
     }
+
+    /* decrement the reference counter of the credential/session handle */
+    if(connssl->cred && connssl->cred->refcount > 0) {
+      connssl->cred->refcount--;
+    }
   }
 
   /* free internal buffer for received encrypted data */
@@ -1148,7 +1158,7 @@ void Curl_schannel_session_free(void *ptr)
 {
   struct curl_schannel_cred *cred = ptr;
 
-  if(cred) {
+  if(cred && cred->refcount == 0) {
     s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
     Curl_safefree(cred);
   }
diff --git a/lib/urldata.h b/lib/urldata.h
index fddfc0d..5f893c9 100644
--- a/lib/urldata.h
+++ b/lib/urldata.h
@@ -234,6 +234,7 @@ enum protection_level {
 struct curl_schannel_cred {
   CredHandle cred_handle;
   TimeStamp time_stamp;
+  int refcount;
 };
 
 struct curl_schannel_ctxt {
-- 
1.7.10.msysgit.1

