Implement SSL_clear with ssl_new and ssl_free.

State on s3 gets freed in both ssl3_clear and ssl3_free. Considate to just
ssl3_free. This replaces the (SSL,ssl,ssl3)_clear calls in (SSL,ssl,ssl3)_new
with the state that was initialized. This results in a little code duplication
between SSL_new and SSL_clear because state is on the wrong object. I've just
left TODOs for now; some of it will need disentangling.

We're far from it, but going forward, separate state between s and s->s3 as:

- s contains configuration state, DTLS or TLS. It is initialized from SSL_CTX,
  configurable directly afterwards, and preserved across SSL_clear calls.
  (Including when it's implicitly set as part of a handshake callback.)

- Connection state hangs off s->s3 (TLS) and s->d1 (DTLS). It is reset across
  SSL_clear. This should happen naturally out of a ssl_free/ssl_new pair.

The goal is to avoid needing separate initialize and reset code for anything;
the point any particular state is reset is the point its owning context is
destroyed and recreated.

Change-Id: I5d779010778109f8c339c07433a0777feaf94d1f
Reviewed-on: https://boringssl-review.googlesource.com/2822
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/ssl/d1_lib.c b/ssl/d1_lib.c
index 0b9e25c..ce05b89 100644
--- a/ssl/d1_lib.c
+++ b/ssl/d1_lib.c
@@ -162,7 +162,13 @@
   }
 
   s->d1 = d1;
-  s->method->ssl_clear(s);
+
+  /* Set the version to the highest version for DTLS. This controls the initial
+   * state of |s->enc_method| and what the API reports as the version prior to
+   * negotiation.
+   *
+   * TODO(davidben): This is fragile and confusing. */
+  s->version = DTLS1_2_VERSION;
   return 1;
 }
 
@@ -214,6 +220,10 @@
 void dtls1_free(SSL *s) {
   ssl3_free(s);
 
+  if (s == NULL || s->d1 == NULL) {
+    return;
+  }
+
   dtls1_clear_queues(s);
 
   pqueue_free(s->d1->unprocessed_rcds.q);
@@ -226,41 +236,6 @@
   s->d1 = NULL;
 }
 
-void dtls1_clear(SSL *s) {
-  pqueue unprocessed_rcds;
-  pqueue processed_rcds;
-  pqueue buffered_messages;
-  pqueue sent_messages;
-  pqueue buffered_app_data;
-  unsigned int mtu;
-
-  if (s->d1) {
-    unprocessed_rcds = s->d1->unprocessed_rcds.q;
-    processed_rcds = s->d1->processed_rcds.q;
-    buffered_messages = s->d1->buffered_messages;
-    sent_messages = s->d1->sent_messages;
-    buffered_app_data = s->d1->buffered_app_data.q;
-    mtu = s->d1->mtu;
-
-    dtls1_clear_queues(s);
-
-    memset(s->d1, 0, sizeof(*(s->d1)));
-
-    if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
-      s->d1->mtu = mtu;
-    }
-
-    s->d1->unprocessed_rcds.q = unprocessed_rcds;
-    s->d1->processed_rcds.q = processed_rcds;
-    s->d1->buffered_messages = buffered_messages;
-    s->d1->sent_messages = sent_messages;
-    s->d1->buffered_app_data.q = buffered_app_data;
-  }
-
-  ssl3_clear(s);
-  s->version = DTLS1_2_VERSION;
-}
-
 long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg) {
   int ret = 0;