+{
+ gnutls_certificate_free_credentials(certificate);
+ gnutls_priority_deinit(cipherCache);
+ gnutls_global_deinit();
+}
+
+SSL_handle_t * SSLi_newconnection( int * fileDescriptor, bool_t * isSSLReady )
+{
+ gnutls_session_t * session
+ = Memory_safeCalloc(1, sizeof(gnutls_session_t));
+
+ gnutls_init(session, GNUTLS_SERVER);
+ gnutls_priority_set(*session, cipherCache);
+ gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE, certificate);
+
+ gnutls_certificate_server_set_request(*session, GNUTLS_CERT_REQUIRE);
+
+ gnutls_transport_set_int(*session, *fileDescriptor);
+
+ if(isSSLReady && SSLi_nonblockaccept(session, isSSLReady))
+ *isSSLReady = true;
+
+ return session;
+}
+
+bool_t SSLi_getSHA1Hash(SSL_handle_t *session, uint8_t *hash)
+{
+ gnutls_datum_t const * certificateData = gnutls_certificate_get_peers(*session, NULL);
+
+ size_t resultSize = 0;
+ int error = gnutls_fingerprint( GNUTLS_DIG_SHA1, certificateData, hash, &resultSize);
+ return error == GNUTLS_E_SUCCESS && resultSize == 20;
+}
+
+int SSLi_nonblockaccept( SSL_handle_t *session, bool_t * isSSLReady )
+{
+ int error;
+ do {
+ error = gnutls_handshake(*session);
+ } while(error < GNUTLS_E_SUCCESS && !gnutls_error_is_fatal(error));
+
+ if ( error < GNUTLS_E_SUCCESS ) {
+ Log_warn("TLS handshake failed with error %i (%s).", error, gnutls_strerror(error));
+ }
+
+ if(isSSLReady)
+ *isSSLReady = true;
+
+ return error;
+}
+
+int SSLi_read(SSL_handle_t *session, uint8_t *buffer, int length)
+{
+ return gnutls_record_recv(*session, buffer, length);
+}
+
+int SSLi_write(SSL_handle_t *session, uint8_t *buffer, int length)
+{
+ return gnutls_record_send(*session, buffer, length);
+}
+
+int SSLi_get_error(SSL_handle_t *session, int code)
+{
+ return code;
+}
+
+bool_t SSLi_data_pending(SSL_handle_t *session)
+{
+ return gnutls_record_check_pending(*session);
+}
+
+void SSLi_shutdown(SSL_handle_t *session)
+{
+ gnutls_bye(*session, GNUTLS_SHUT_WR);
+}
+
+void SSLi_free(SSL_handle_t *session)
+{
+ gnutls_deinit(*session);
+ free(session);
+}