

#include <gnutls/gnutls.h>

/* This function will try to verify the peer's certificate, and
 * also check if the hostname matches, and the activation, expiration dates.
 */
void verify_certificate( gnutls_session session, const char* hostname)
{
   int status;

   /* This verification function uses the trusted CAs in the credentials
    * structure. So you must have installed one or more CA certificates.
    */
   status = gnutls_certificate_verify_peers(session);

   if (status == GNUTLS_E_NO_CERTIFICATE_FOUND) {
      printf("No certificate was sent");
      return;
   }

   if (status & GNUTLS_CERT_INVALID || status & GNUTLS_CERT_NOT_TRUSTED
      || status & GNUTLS_CERT_CORRUPTED || status & GNUTLS_CERT_REVOKED) {
      printf("The certificate is not trusted");
      return;
   }

   if ( gnutls_certificate_expiration_time_peers(session) < time(0)) {
      printf("The certificate has expired\n");
      return;
   }

   if ( gnutls_certificate_activation_time_peers(session) > time(0)) {
      printf("The certificate is not yet activated\n");
      return;
   }

   if ( gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
      const gnutls_datum* cert_list;
      int cert_list_size;
      
      cert_list = gnutls_certificate_get_peers( session, &cert_list_size);
      if ( cert_list == NULL) {
         printf("No certificate was found!\n");
         return;
      }
      if ( !gnutls_x509_check_certificates_hostname( &cert_list[0], hostname)) {
         printf("The certificate does not match hostname\n");
         return;
      }
   }
   
   printf("The certificate is trusted.\n");
   return;
}

