minor: improve and document the key search loop.

Simplify and otherwise polish the loop that tries to find a key
matching the slot id string passed in.

Signed-off-by: Anthony Foiani <anthony.foiani@gmail.com>
engine_pkcs11: Reduce memory leaks from pkcs11_load_key

This function returns an EVP_PKEY*, but allocates many other objects
to get that value.  As far as I can tell, there's no graceful way to
get at those objects through the EVP_PKEY* itself.

My solution is to introduce an auxilary storage that maps EVP_PKEY*
values to the extra objects, so that they can be freed later.  This
works as expected, and reduces the memory leak substantially.

I have a small sample program that does four "CMS_Sign" operations
then four "CMS_Encrypt" operations, obtaining then freeing the key
each time.

Without this patch:

  ==25864== LEAK SUMMARY:
  ==25864==    definitely lost: 4,920 bytes in 27 blocks
  ==25864==    indirectly lost: 147,092 bytes in 3,137 blocks
  ==25864==      possibly lost: 0 bytes in 0 blocks
  ==25864==    still reachable: 14,231 bytes in 429 blocks
  ==25864==         suppressed: 0 bytes in 0 blocks

With this patch:

  ==25989== LEAK SUMMARY:
  ==25989==    definitely lost: 4,600 bytes in 23 blocks
  ==25989==    indirectly lost: 328 bytes in 5 blocks
  ==25989==      possibly lost: 0 bytes in 0 blocks
  ==25989==    still reachable: 14,231 bytes in 429 blocks
  ==25989==         suppressed: 0 bytes in 0 blocks

Note that "indirectly lost" went from 147K to less than 1K.

Unfortunately, I could not find a way to do this transparently, as
there doesn't seem to be any way for third-party code to change the
"pkey_free" hook for EVP_PKEYs.

Thankfully, the transformation is straightforward.  Assuming one
obtains the private key via:

  EVP_PKEY * pkey;
  pkey = ENGINE_load_private_key( engine, keyid, NULL, NULL );

Instead of freeing it directly with:

  EVP_PKEY_free( pkey );

One must instead call a new control function:

  ENGINE_ctrl_cmd( engine, "RELEASE_KEY", 0,
                   (void *)pkey, NULL, 0 );

If anyone knows how to properly "subclass" EVP_PKEYs from outside the
openssl code base, I'd love to learn how.

Signed-off-by: Anthony Foiani <anthony.foiani@gmail.com>
engine_pkcs11: streamline verbose output

This cleans up my previous patch so that it does not spew as much to
the console.

In the process, it introduces some helper macros that make debugging
output a bit less intrusive in the main code flow.

Signed-off-by: Anthony Foiani <anthony.foiani@gmail.com>
engine_pkcs11: allow environment variable to set verbosity.

Previously, when using the engine programmatically, the only way to
set the verbosity was a control call.

With this patch, we can instead just set the ENGINE_PKCS11_VERBOSE
environment variable to control the initial verbosity.

Signed-off-by: Anthony Foiani <anthony.foiani@gmail.com>