Make CBB_len return a length, not remaining.

It switched from CBB_remaining to CBB_len partway through review, but
the semantics are still CBB_remaining. Using CBB_len allows the
len_before/len_after logic to continue working even if, in the future,
handshake messages are built on a non-fixed CBB.

Change-Id: Id466bb341a14dbbafcdb26e4c940a04181f2787d
Reviewed-on: https://boringssl-review.googlesource.com/5371
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/bytestring/cbb.c b/crypto/bytestring/cbb.c
index b9291ce..1da6a21 100644
--- a/crypto/bytestring/cbb.c
+++ b/crypto/bytestring/cbb.c
@@ -249,9 +249,8 @@
 
 size_t CBB_len(const CBB *cbb) {
   assert(cbb->child == NULL);
-  assert(!cbb->base->can_resize);
 
-  return cbb->base->cap - cbb->base->len;
+  return cbb->base->len;
 }
 
 static int cbb_add_length_prefixed(CBB *cbb, CBB *out_contents,
diff --git a/include/openssl/bytestring.h b/include/openssl/bytestring.h
index 3419275..4fceeaa 100644
--- a/include/openssl/bytestring.h
+++ b/include/openssl/bytestring.h
@@ -284,9 +284,12 @@
  * 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|. */
+/* CBB_len returns the number of bytes written to |cbb|'s top-level |CBB|. It
+ * may be compared before and after an operation to determine how many bytes
+ * were written.
+ *
+ * It is a fatal error to call this on a CBB 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
diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index 7daa864..7005704 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -1224,20 +1224,20 @@
   }
 
   for (i = 0; i < kNumExtensions; i++) {
-    const size_t space_before = CBB_len(&cbb);
+    const size_t len_before = CBB_len(&cbb);
     if (!kExtensions[i].add_clienthello(s, &cbb)) {
       CBB_cleanup(&cbb);
       OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
       return NULL;
     }
-    const size_t space_after = CBB_len(&cbb);
+    const size_t len_after = CBB_len(&cbb);
 
-    if (space_after != space_before) {
+    if (len_after != len_before) {
       s->s3->tmp.extensions.sent |= (1u << i);
     }
   }
 
-  ret = limit - CBB_len(&cbb);
+  ret += CBB_len(&cbb);
   CBB_cleanup(&cbb);
 
   /* Add extended master secret. */
@@ -1513,7 +1513,7 @@
     }
   }
 
-  ret = limit - CBB_len(&cbb);
+  ret += CBB_len(&cbb);
   CBB_cleanup(&cbb);
 
   if (s->s3->tmp.extended_master_secret) {