Index: CHANGES
===================================================================
RCS file: /home/openssl/cvs/openssl/CHANGES,v
retrieving revision 1.1556
diff -u -r1.1556 CHANGES
--- CHANGES	5 May 2010 22:05:33 -0000	1.1556
+++ CHANGES	24 May 2010 22:24:28 -0000
@@ -3,6 +3,14 @@
  _______________
 
  Changes between 1.0.0 and 1.1.0  [xx XXX xxxx]
+ 
+  *) CHIL Engine did not free the helper function pointers pushed onto the
+     ex_data function stack for RSA structures.  This caused problems with
+     calling programs that initialize multiple times, like Apache.  The
+     second time around would crash the program if CHIL loaded the underlying
+     libnfhwcrhk.so in a different location.  Move the cleanup to a finish
+     handler method for the RSA structures.
+     [ , Sander Temme  sander@temme.net]
 
   *) New function OPENSSL_gmtime_diff to find the difference in days
      and seconds between two tm structures. This will be used to provide
Index: engines/e_chil.c
===================================================================
RCS file: /home/openssl/cvs/openssl/engines/e_chil.c,v
retrieving revision 1.12
diff -u -r1.12 e_chil.c
--- engines/e_chil.c	24 Mar 2010 23:42:05 -0000	1.12
+++ engines/e_chil.c	24 May 2010 22:24:28 -0000
@@ -138,6 +138,7 @@
 #ifndef OPENSSL_NO_RSA
 static void hwcrhk_ex_free(void *obj, void *item, CRYPTO_EX_DATA *ad,
 	int ind,long argl, void *argp);
+static int hwcrhk_rsa_finish(RSA *rsa);
 #endif
 
 /* Interaction stuff */
@@ -193,7 +194,7 @@
 	hwcrhk_rsa_mod_exp,
 	hwcrhk_mod_exp_mont,
 	NULL,
-	NULL,
+	hwcrhk_rsa_finish,
 	0,
 	NULL,
 	NULL,
@@ -602,7 +603,7 @@
 	if (hndidx_rsa == -1)
 		hndidx_rsa = RSA_get_ex_new_index(0,
 			"nFast HWCryptoHook RSA key handle",
-			NULL, NULL, hwcrhk_ex_free);
+			NULL, NULL, NULL);
 #endif
 	return 1;
 err:
@@ -1162,6 +1163,36 @@
                 }
 #endif
 }
+
+/* 
+ * Cleanup function for RSA structures.  This is a wrapper function
+ * around hwcrhk_ex_free, which was supposed to be registered as a
+ * free_func for the ex_data entry attached to RSA instances.  Since
+ * the free_func is not robust when the ENGINE gets loaded multiple
+ * times, call it instead in a finish handler for RSA structures.
+ */
+
+int hwcrhk_rsa_finish(RSA *rsa)
+{
+	/* The intention is that this is our index on the stack of
+	 * CRYPTO_EX_DATA_FUNCS.  This value is not used by
+	 * hwcrhk_ex_free() 
+	 */
+	int index = 0; 
+	void *item;
+	CRYPTO_EX_DATA *ad;
+
+	/* Retrieve the ex_data data.  This value is used by
+	 * hwcrhk_ex_free() to unload the loaded key from the HSM(s) 
+	 */
+	ad = &rsa->ex_data;
+	item = CRYPTO_get_ex_data(ad, index);
+
+	hwcrhk_ex_free(rsa, item, ad, 0, 0, 
+		   "nFast HWCryptoHook RSA key handle");
+
+	return 1;
+}
 #endif
 
 /* Mutex calls: since the HWCryptoHook model closely follows the POSIX model
