Index: lib/nss.c
===================================================================
RCS file: /cvsroot/curl/curl/lib/nss.c,v
retrieving revision 1.50
diff -u -p -r1.50 nss.c
--- lib/nss.c	8 Jun 2009 21:25:17 -0000	1.50
+++ lib/nss.c	20 Jul 2009 09:42:57 -0000
@@ -857,9 +857,15 @@ void Curl_nss_cleanup(void)
    */
   PR_Lock(nss_initlock);
   if (initialized) {
-    if(mod)
+    /* Free references to client certificates held in the SSL session cache.
+     * Omitting this hampers destruction of the security module owning
+     * the certificates. */
+    SSL_ClearSessionCache();
+
+    if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
       SECMOD_DestroyModule(mod);
-    mod = NULL;
+      mod = NULL;
+    }
     NSS_Shutdown();
   }
   PR_Unlock(nss_initlock);
@@ -940,9 +946,6 @@ CURLcode Curl_nss_connect(struct connect
   curl_socket_t sockfd = conn->sock[sockindex];
   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
   SECStatus rv;
-#ifdef HAVE_PK11_CREATEGENERICOBJECT
-  char *configstring = NULL;
-#endif
   char *certDir = NULL;
   int curlerr;
   const int *cipher_to_enable;
@@ -995,21 +998,23 @@ CURLcode Curl_nss_connect(struct connect
       NSS_SetDomesticPolicy();
 
 #ifdef HAVE_PK11_CREATEGENERICOBJECT
-    configstring = aprintf("library=%s name=PEM", pem_library);
-    if(!configstring) {
-      PR_Unlock(nss_initlock);
-      goto error;
-    }
-    mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
-    free(configstring);
+    if(!mod) {
+      char *configstring = aprintf("library=%s name=PEM", pem_library);
+      if(!configstring) {
+        PR_Unlock(nss_initlock);
+        goto error;
+      }
+      mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
+      free(configstring);
 
-    if(!mod || !mod->loaded) {
-      if(mod) {
-        SECMOD_DestroyModule(mod);
-        mod = NULL;
+      if(!mod || !mod->loaded) {
+        if(mod) {
+          SECMOD_DestroyModule(mod);
+          mod = NULL;
+        }
+        infof(data, "WARNING: failed to load NSS PEM library %s. Using OpenSSL "
+              "PEM certificates will not work.\n", pem_library);
       }
-      infof(data, "WARNING: failed to load NSS PEM library %s. Using OpenSSL "
-            "PEM certificates will not work.\n", pem_library);
     }
 #endif
   }

