Return SSL_TLSEXT_ERR_NOACK with no NPN/ALPN

We were returning SSL_TLSEXT_ERR_OK even if we did not select any
NPN/ALPN support.

(cherry-picked from changes fc7924bc78afc46c3c75722a735fe4db65c33304
and 2a5460fc2ab3453b54d3f6b01f6c83dc7502fbdc)

Bug: https://code.google.com/p/android/issues/detail?id=66562
Bug: 13396322
Change-Id: Id38e9af3c8f7cc00bac19ba3aebdc103d4b5f09a
diff --git a/crypto/src/main/native/org_conscrypt_NativeCrypto.cpp b/crypto/src/main/native/org_conscrypt_NativeCrypto.cpp
index 6e171a7..cc5abbd 100644
--- a/crypto/src/main/native/org_conscrypt_NativeCrypto.cpp
+++ b/crypto/src/main/native/org_conscrypt_NativeCrypto.cpp
@@ -5619,6 +5619,7 @@
         if (fdsEmergency[1] != -1) {
             close(fdsEmergency[1]);
         }
+        clearCallbackState();
         MUTEX_CLEANUP(mutex);
     }
 
@@ -5666,20 +5667,22 @@
         sslHandshakeCallbacks = shc;
         fileDescriptor = fd;
         if (npnProtocols != NULL) {
-            npnProtocolsArray = npnProtocols;
-            npnProtocolsLength = e->GetArrayLength(npnProtocols);
             npnProtocolsData = e->GetByteArrayElements(npnProtocols, NULL);
             if (npnProtocolsData == NULL) {
+                clearCallbackState();
                 return false;
             }
+            npnProtocolsArray = npnProtocols;
+            npnProtocolsLength = e->GetArrayLength(npnProtocols);
         }
         if (alpnProtocols != NULL) {
-            alpnProtocolsArray = alpnProtocols;
-            alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
             alpnProtocolsData = e->GetByteArrayElements(alpnProtocols, NULL);
             if (alpnProtocolsData == NULL) {
+                clearCallbackState();
                 return false;
             }
+            alpnProtocolsArray = alpnProtocols;
+            alpnProtocolsLength = e->GetArrayLength(alpnProtocols);
         }
         return true;
     }
@@ -6794,6 +6797,7 @@
         switch (status) {
         case OPENSSL_NPN_NEGOTIATED:
             JNI_TRACE("ssl=%p proto_select NPN/ALPN negotiated", ssl);
+            return SSL_TLSEXT_ERR_OK;
             break;
         case OPENSSL_NPN_UNSUPPORTED:
             JNI_TRACE("ssl=%p proto_select NPN/ALPN unsupported", ssl);
@@ -6803,9 +6807,13 @@
             break;
         }
     } else {
+        if (out != NULL && outLength != NULL) {
+            *out = NULL;
+            *outLength = 0;
+        }
         JNI_TRACE("protocols=NULL");
     }
-    return SSL_TLSEXT_ERR_OK;
+    return SSL_TLSEXT_ERR_NOACK;
 }
 
 /**
@@ -6855,8 +6863,12 @@
     if (npnProtocols != NULL) {
         *out = npnProtocols;
         *outlen = appData->npnProtocolsLength;
+        return SSL_TLSEXT_ERR_OK;
+    } else {
+        *out = NULL;
+        *outlen = 0;
+        return SSL_TLSEXT_ERR_NOACK;
     }
-    return SSL_TLSEXT_ERR_OK;
 }
 
 static void NativeCrypto_SSL_CTX_enable_npn(JNIEnv* env, jclass, jlong ssl_ctx_address)