Add infrastructure for better extension handling.

Rather than four massive functions that handle every extension,
organise the code by extension with four smaller functions for each.

Change-Id: I876b31dacb05aca9884ed3ae7c48462e6ffe3b49
Reviewed-on: https://boringssl-review.googlesource.com/5142
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/include/openssl/bytestring.h b/include/openssl/bytestring.h
index b30ae5c..8583c4e 100644
--- a/include/openssl/bytestring.h
+++ b/include/openssl/bytestring.h
@@ -278,6 +278,11 @@
  * on error. */
 OPENSSL_EXPORT int CBB_flush(CBB *cbb);
 
+/* CBB_len returns the number of bytes remaining in a fixed CBB. It is a fatal
+ * error to call this on a non-fixed CBB or one with any active children. This
+ * does not flush |cbb|. */
+OPENSSL_EXPORT size_t CBB_len(const CBB *cbb);
+
 /* CBB_add_u8_length_prefixed sets |*out_contents| to a new child of |cbb|. The
  * data written to |*out_contents| will be prefixed in |cbb| with an 8-bit
  * length. It returns one on success or zero on error. */
diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h
index 84897f1..93d5efe 100644
--- a/include/openssl/ssl.h
+++ b/include/openssl/ssl.h
@@ -1537,9 +1537,6 @@
                        * SSLv3/TLS rollback check */
   uint16_t max_send_fragment;
   char *tlsext_hostname;
-  /* should_ack_sni is true if the SNI extension should be acked. This is
-   * only used by a server. */
-  char should_ack_sni;
   /* RFC4507 session ticket expected to be received or sent */
   int tlsext_ticket_expected;
   size_t tlsext_ecpointformatlist_length;
@@ -3056,6 +3053,7 @@
 #define SSL_R_EMS_STATE_INCONSISTENT 276
 #define SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION 277
 #define SSL_R_TOO_MANY_WARNING_ALERTS 278
+#define SSL_R_UNEXPECTED_EXTENSION 279
 #define SSL_R_SSLV3_ALERT_CLOSE_NOTIFY 1000
 #define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010
 #define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020
diff --git a/include/openssl/ssl3.h b/include/openssl/ssl3.h
index 9021309..aa1256b 100644
--- a/include/openssl/ssl3.h
+++ b/include/openssl/ssl3.h
@@ -453,6 +453,24 @@
 
     int reuse_message;
 
+    union {
+      /* sent is a bitset where the bits correspond to elements of kExtensions
+       * in t1_lib.c. Each bit is set if that extension was sent in a
+       * ClientHello. It's not used by servers. */
+      uint32_t sent;
+      /* received is a bitset, like |sent|, but is used by servers to record
+       * which extensions were received from a client. */
+      uint32_t received;
+    } extensions;
+
+
+    /* SNI extension */
+
+    /* should_ack_sni is used by a server and indicates that the SNI extension
+     * should be echoed in the ServerHello. */
+    unsigned should_ack_sni:1;
+
+
     /* Client-only: cert_req determines if a client certificate is to be sent.
      * This is 0 if no client Certificate message is to be sent, 1 if there is
      * a client certificate, and 2 to send an empty client Certificate