
/* This file is actually an example of using the OpenCDK library
 * to retrieve an OpenPGP key from a key server.
 */

#include <stdlib.h>
#include <gnutls/gnutls.h>
#include <gnutls/extra.h>
#include <opencdk.h>

/* A callback function that tries to connect
 * to a public keyserver to get the specified key.
 * The callback should be set as:
 *
 * gnutls_openpgp_set_recv_key_function( session, recv_openpgp_key);
 *
 * in the initialization of a gnutls session.
 */

static const char *hostname = "hkp://wwwkeys.pgp.net";
static const short port = 11371;

int
recv_openpgp_key(gnutls_session session, const unsigned char *keyfpr, 
       unsigned int keyfpr_length, gnutls_datum * key)
{
   int rc;
   CDK_KBNODE knode = NULL;

   /* The key fingerprint should be 20 bytes
    * in v4 keys.
    */
   if (keyfpr_length != 20)
      return -1;

   rc = cdk_keyserver_recv_key( hostname, port, keyfpr, 
      CDK_DBSEARCH_FPR, &knode );

   if( !rc ) {
       size_t len;

       cdk_kbnode_write_to_mem( knode, NULL, &len);

       key->data = gnutls_malloc( len);
       if (key->data==NULL) {
          rc = -1;
          goto finish;
       }

       key->size = len;
       cdk_kbnode_write_to_mem( knode, key->data, &len);

       rc = 0; /* success */

   } else {
       rc = -1;
   }

   finish:

   cdk_kbnode_release( knode );
   return rc;

}


