Set up the SSL_HANDSHAKE object earlier.

This is to free up moving ssl->state into SSL_HANDSHAKE. ssl->state
serves two purposes right now. First, it is the state tracking for
SSL_HANDSHAKE. Second, it lets the system know there is a handshake
waiting to complete.

Instead, arrange things so that, if there is a handshake waiting to
complete, hs is not NULL. That means we need to initialize it when
creating a new connection and when discovering a renego.

Note this means we cannot make initializing an SSL_HANDSHAKE depend on
client vs. server.

Change-Id: I585a8d7e700c4ffe4d372248d34c44106ad7e7a0
Reviewed-on: https://boringssl-review.googlesource.com/12696
Reviewed-by: David Benjamin <davidben@google.com>
diff --git a/ssl/s3_lib.c b/ssl/s3_lib.c
index 1aad8e6..859cb9b 100644
--- a/ssl/s3_lib.c
+++ b/ssl/s3_lib.c
@@ -167,10 +167,16 @@
 
   s3 = OPENSSL_malloc(sizeof *s3);
   if (s3 == NULL) {
-    goto err;
+    return 0;
   }
   memset(s3, 0, sizeof *s3);
 
+  s3->hs = ssl_handshake_new(ssl);
+  if (s3->hs == NULL) {
+    OPENSSL_free(s3);
+    return 0;
+  }
+
   EVP_MD_CTX_init(&s3->handshake_hash);
   EVP_MD_CTX_init(&s3->handshake_md5);
 
@@ -183,8 +189,6 @@
    * at the API boundary rather than in internal state. */
   ssl->version = TLS1_2_VERSION;
   return 1;
-err:
-  return 0;
 }
 
 void ssl3_free(SSL *ssl) {
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index c5f8d35..2b73409 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -631,12 +631,9 @@
     return 1;
   }
 
-  /* Set up a new handshake if necessary. */
-  if (ssl->state == SSL_ST_INIT && ssl->s3->hs == NULL) {
-    ssl->s3->hs = ssl_handshake_new(ssl);
-    if (ssl->s3->hs == NULL) {
-      return -1;
-    }
+  if (ssl->s3->hs == NULL) {
+    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
+    return -1;
   }
 
   /* Run the handshake. */
@@ -715,6 +712,15 @@
   }
 
   /* Begin a new handshake. */
+  if (ssl->s3->hs != NULL) {
+    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
+    return 0;
+  }
+  ssl->s3->hs = ssl_handshake_new(ssl);
+  if (ssl->s3->hs == NULL) {
+    return 0;
+  }
+
   ssl->s3->total_renegotiations++;
   ssl->state = SSL_ST_INIT;
   return 1;